diff --git a/GeneratorInterface/Core/interface/LHEWeightHelper.h b/GeneratorInterface/Core/interface/LHEWeightHelper.h index b2f636250f230..80bd3cf14af19 100644 --- a/GeneratorInterface/Core/interface/LHEWeightHelper.h +++ b/GeneratorInterface/Core/interface/LHEWeightHelper.h @@ -25,6 +25,7 @@ namespace gen { bool isConsistent(); void swapHeaders(); void setFailIfInvalidXML(bool value) { failIfInvalidXML_ = value; } + private: std::vector headerLines_; bool failIfInvalidXML_ = false; diff --git a/GeneratorInterface/Core/plugins/GenWeightProductProducer.cc b/GeneratorInterface/Core/plugins/GenWeightProductProducer.cc index f9eebff3475cd..3eef6a5701171 100644 --- a/GeneratorInterface/Core/plugins/GenWeightProductProducer.cc +++ b/GeneratorInterface/Core/plugins/GenWeightProductProducer.cc @@ -61,7 +61,7 @@ void GenWeightProductProducer::produce(edm::Event& iEvent, const edm::EventSetup edm::Handle genEventInfo; iEvent.getByToken(genEventToken_, genEventInfo); - float centralWeight = genEventInfo->weights().size() > 0 ? genEventInfo->weights().at(0) : 1.; + float centralWeight = !genEventInfo->weights().empty() ? genEventInfo->weights().at(0) : 1.; auto weightProduct = weightHelper_.weightProduct(genEventInfo->weights(), centralWeight); iEvent.put(std::move(weightProduct)); } @@ -82,9 +82,9 @@ void GenWeightProductProducer::beginLuminosityBlockProduce(edm::LuminosityBlock& weightHelper_.parseWeightGroupsFromNames(weightNames_); auto weightInfoProduct = std::make_unique(); - if (weightHelper_.weightGroups().size() == 0) - weightHelper_.addUnassociatedGroup(); - + if (weightHelper_.weightGroups().empty()) + weightHelper_.addUnassociatedGroup(); + for (auto& weightGroup : weightHelper_.weightGroups()) { weightInfoProduct->addWeightGroupInfo(std::make_unique(*weightGroup.clone())); } diff --git a/GeneratorInterface/Core/plugins/LHEWeightProductProducer.cc b/GeneratorInterface/Core/plugins/LHEWeightProductProducer.cc index 21e550acfcc76..7634842f1f8d3 100644 --- a/GeneratorInterface/Core/plugins/LHEWeightProductProducer.cc +++ b/GeneratorInterface/Core/plugins/LHEWeightProductProducer.cc @@ -49,12 +49,12 @@ class LHEWeightProductProducer : public edm::one::EDProducer>("lheSourceLabels")), - lheEventTokens_(edm::vector_transform(lheLabels_, - [this](const std::string& tag) { return mayConsume(tag); })), - lheRunInfoTokens_(edm::vector_transform(lheLabels_, - [this](const std::string& tag) { return mayConsume(tag); })), - lheWeightInfoTokens_(edm::vector_transform(lheLabels_, - [this](const std::string& tag) { return mayConsume(tag); })) { + lheEventTokens_(edm::vector_transform( + lheLabels_, [this](const std::string& tag) { return mayConsume(tag); })), + lheRunInfoTokens_(edm::vector_transform( + lheLabels_, [this](const std::string& tag) { return mayConsume(tag); })), + lheWeightInfoTokens_(edm::vector_transform( + lheLabels_, [this](const std::string& tag) { return mayConsume(tag); })) { produces(); produces(); weightHelper_.setFailIfInvalidXML(iConfig.getUntrackedParameter("failIfInvalidXML", false)); @@ -72,7 +72,7 @@ void LHEWeightProductProducer::produce(edm::Event& iEvent, const edm::EventSetup for (auto& token : lheEventTokens_) { iEvent.getByToken(token, lheEventInfo); if (lheEventInfo.isValid()) { - break; + break; } } @@ -85,13 +85,12 @@ void LHEWeightProductProducer::beginRun(edm::Run const& run, edm::EventSetup con for (auto& label : lheLabels_) { run.getByLabel(label, lheRunInfoHandle); if (lheRunInfoHandle.isValid()) { - hasLhe_ = true; - break; + hasLhe_ = true; + break; } } if (!hasLhe_) - return; - + return; typedef std::vector::const_iterator header_cit; LHERunInfoProduct::Header headerWeightInfo; @@ -119,20 +118,21 @@ void LHEWeightProductProducer::beginLuminosityBlockProduce(edm::LuminosityBlock& } if (!hasLhe_) - return; + return; try { weightHelper_.parseWeights(); } catch (cms::Exception& e) { - std::string error = e.what(); - error += "\n NOTE: if you want to attempt to process this sample anyway, set failIfInvalidXML = False " - "in the configuration file\n. If you set this flag and the error persists, the issue " - " is fatal and must be solved at the LHE/gridpack level."; - throw cms::Exception("LHEWeightProductProducer") << error; + std::string error = e.what(); + error += + "\n NOTE: if you want to attempt to process this sample anyway, set failIfInvalidXML = False " + "in the configuration file\n. If you set this flag and the error persists, the issue " + " is fatal and must be solved at the LHE/gridpack level."; + throw cms::Exception("LHEWeightProductProducer") << error; } - if (weightHelper_.weightGroups().size() == 0) - weightHelper_.addUnassociatedGroup(); + if (weightHelper_.weightGroups().empty()) + weightHelper_.addUnassociatedGroup(); auto weightInfoProduct = std::make_unique(); for (auto& weightGroup : weightHelper_.weightGroups()) { diff --git a/GeneratorInterface/Core/src/GenWeightHelper.cc b/GeneratorInterface/Core/src/GenWeightHelper.cc index 1fc086f688e56..b06475941efd6 100644 --- a/GeneratorInterface/Core/src/GenWeightHelper.cc +++ b/GeneratorInterface/Core/src/GenWeightHelper.cc @@ -43,7 +43,7 @@ namespace gen { {"", index, weightName, weightName, std::unordered_map(), groupIndex}); if (isPartonShowerWeightGroup(parsedWeights_.back())) { if (showerGroupIndex < 0) { - showerGroupIndex = ++groupIndex; + showerGroupIndex = ++groupIndex; } parsedWeights_.back().wgtGroup_idx = showerGroupIndex; // all parton showers are grouped together } diff --git a/GeneratorInterface/Core/src/LHEWeightHelper.cc b/GeneratorInterface/Core/src/LHEWeightHelper.cc index 2acc27c3f0da9..4be51105c9cec 100644 --- a/GeneratorInterface/Core/src/LHEWeightHelper.cc +++ b/GeneratorInterface/Core/src/LHEWeightHelper.cc @@ -13,8 +13,8 @@ namespace gen { parsedWeights_.clear(); if (!isConsistent() && failIfInvalidXML_) { - throw cms::Exception("LHEWeightHelper") << - "XML in LHE is not consistent: Most likely, XML tags are out of order."; + throw cms::Exception("LHEWeightHelper") + << "XML in LHE is not consistent: Most likely, XML tags are out of order."; } else if (!isConsistent()) { swapHeaders(); } @@ -27,7 +27,7 @@ namespace gen { // in case of > instead of < if (xmlError != 0 && failIfInvalidXML_) { xmlDoc.PrintError(); - throw cms::Exception("LHEWeightHelper") + throw cms::Exception("LHEWeightHelper") << "The LHE header is not valid XML! Weight information was not properly parsed."; } else if (xmlError != 0 && !failIfInvalidXML_) { boost::replace_all(fullHeader, "<", "<"); @@ -93,11 +93,11 @@ namespace gen { std::string LHEWeightHelper::parseGroupName(tinyxml2::XMLElement* el) { std::vector nameAlts_ = {"name", "type"}; - for (auto nameAtt : nameAlts_) { + for (const auto& nameAtt : nameAlts_) { if (el->Attribute(nameAtt.c_str())) { std::string groupName = el->Attribute(nameAtt.c_str()); - if (groupName.find(".") != std::string::npos) - groupName.erase(groupName.find("."), groupName.size()); + if (groupName.find('.') != std::string::npos) + groupName.erase(groupName.find('.'), groupName.size()); return groupName; } } @@ -111,7 +111,7 @@ namespace gen { bool LHEWeightHelper::isConsistent() { int curLevel = 0; - for (auto line : headerLines_) { + for (const auto& line : headerLines_) { if (line.find(" psNames = {"isr", "fsr", "nominal", "baseline", "emission"}; - for (auto name : psNames) { + for (const auto& name : psNames) { if (groupname.find(name) != std::string::npos) return true; } @@ -128,7 +128,7 @@ namespace gen { } catch (std::invalid_argument& e) { pdfGroup.setIsWellFormed(false); } - } else if (pdfGroup.lhaIds().size() > 0) { + } else if (!pdfGroup.lhaIds().empty()) { return pdfGroup.lhaIds().back() + 1; } else { return LHAPDF::lookupLHAPDFID(weight.groupname); @@ -240,7 +240,7 @@ namespace gen { // Fall back to unordered search int counter = 0; - for (auto weightGroup : weightGroups_) { + for (const auto& weightGroup : weightGroups_) { if (weightGroup.containsWeight(wgtId, weightIndex)) return counter; counter++; @@ -290,8 +290,8 @@ namespace gen { wgtPS.cacheWeightIndicesByLabel(); std::vector labels = wgtPS.weightLabels(); - if (labels.size() > FIRST_PSWEIGHT_ENTRY && labels.at(FIRST_PSWEIGHT_ENTRY).find(":") != std::string::npos && - labels.at(FIRST_PSWEIGHT_ENTRY).find("=") != std::string::npos) { + if (labels.size() > FIRST_PSWEIGHT_ENTRY && labels.at(FIRST_PSWEIGHT_ENTRY).find(':') != std::string::npos && + labels.at(FIRST_PSWEIGHT_ENTRY).find('=') != std::string::npos) { wgtPS.setNameIsPythiaSyntax(true); } } diff --git a/GeneratorInterface/LHEInterface/plugins/ExternalLHEProducer.cc b/GeneratorInterface/LHEInterface/plugins/ExternalLHEProducer.cc index 753f1c78dd00a..cf944ea8bdeec 100644 --- a/GeneratorInterface/LHEInterface/plugins/ExternalLHEProducer.cc +++ b/GeneratorInterface/LHEInterface/plugins/ExternalLHEProducer.cc @@ -67,7 +67,7 @@ Description: [one line class summary] // class ExternalLHEProducer - : public edm::one::EDProducer { + : public edm::one::EDProducer { public: explicit ExternalLHEProducer(const edm::ParameterSet& iConfig); ~ExternalLHEProducer() override; @@ -124,15 +124,15 @@ class ExternalLHEProducer // constructors and destructor // ExternalLHEProducer::ExternalLHEProducer(const edm::ParameterSet& iConfig) - : scriptName_((iConfig.getParameter("scriptName")).fullPath()), - outputFile_(iConfig.getParameter("outputFile")), - args_(iConfig.getParameter>("args")), - npars_(iConfig.getParameter("numberOfParameters")), - nEvents_(iConfig.getUntrackedParameter("nEvents")), - storeXML_(iConfig.getUntrackedParameter("storeXML")) { + : scriptName_((iConfig.getParameter("scriptName")).fullPath()), + outputFile_(iConfig.getParameter("outputFile")), + args_(iConfig.getParameter>("args")), + npars_(iConfig.getParameter("numberOfParameters")), + nEvents_(iConfig.getUntrackedParameter("nEvents")), + storeXML_(iConfig.getUntrackedParameter("storeXML")) { if (npars_ != args_.size()) throw cms::Exception("ExternalLHEProducer") - << "Problem with configuration: " << args_.size() << " script arguments given, expected " << npars_; + << "Problem with configuration: " << args_.size() << " script arguments given, expected " << npars_; if (iConfig.exists("nPartonMapping")) { auto& processMap(iConfig.getParameterSetVector("nPartonMapping")); @@ -147,7 +147,7 @@ ExternalLHEProducer::ExternalLHEProducer(const edm::ParameterSet& iConfig) order = 1; else throw cms::Exception("ExternalLHEProducer") - << "Invalid order specification for process " << processId << ": " << orderStr; + << "Invalid order specification for process " << processId << ": " << orderStr; unsigned np(cfg.getParameter("np")); @@ -178,13 +178,13 @@ void ExternalLHEProducer::produce(edm::Event& iEvent, const edm::EventSetup& iSe nextEvent(); if (!partonLevel) { throw edm::Exception(edm::errors::EventGenerationFailure) - << "No lhe event found in ExternalLHEProducer::produce(). " - << "The likely cause is that the lhe file contains fewer events than were requested, which is possible " - << "in case of phase space integration or uneweighting efficiency problems."; + << "No lhe event found in ExternalLHEProducer::produce(). " + << "The likely cause is that the lhe file contains fewer events than were requested, which is possible " + << "in case of phase space integration or uneweighting efficiency problems."; } std::unique_ptr product( - new LHEEventProduct(*partonLevel->getHEPEUP(), partonLevel->originalXWGTUP())); + new LHEEventProduct(*partonLevel->getHEPEUP(), partonLevel->originalXWGTUP())); if (partonLevel->getPDF()) { product->setPDF(*partonLevel->getPDF()); } @@ -211,20 +211,20 @@ void ExternalLHEProducer::produce(edm::Event& iEvent, const edm::EventSetup& iSe np = procDef.second; } catch (std::out_of_range&) { throw cms::Exception("ExternalLHEProducer") - << "Unexpected IDPRUP encountered: " << partonLevel->getHEPEUP()->IDPRUP; + << "Unexpected IDPRUP encountered: " << partonLevel->getHEPEUP()->IDPRUP; } switch (order) { - case 0: - product->setNpLO(np); - product->setNpNLO(-1); - break; - case 1: - product->setNpLO(-1); - product->setNpNLO(np); - break; - default: - break; + case 0: + product->setNpLO(np); + product->setNpNLO(-1); + break; + case 1: + product->setNpLO(-1); + product->setNpNLO(np); + break; + default: + break; } } @@ -273,9 +273,9 @@ void ExternalLHEProducer::beginRunProduce(edm::Run& run, edm::EventSetup const& if (!rng.isAvailable()) { throw cms::Exception("Configuration") - << "The ExternalLHEProducer module requires the RandomNumberGeneratorService\n" + << "The ExternalLHEProducer module requires the RandomNumberGeneratorService\n" "which is not present in the configuration file. You must add the service\n" - "in the configuration file if you want to run ExternalLHEProducer"; + "in the configuration file if you want to run ExternalLHEProducer"; } std::ostringstream randomStream; randomStream << rng->mySeed(); @@ -369,9 +369,9 @@ void ExternalLHEProducer::endRunProduce(edm::Run& run, edm::EventSetup const& es nextEvent(); if (partonLevel) { throw edm::Exception(edm::errors::EventGenerationFailure) - << "Error in ExternalLHEProducer::endRunProduce(). " - << "Event loop is over, but there are still lhe events to process." - << "This could happen if lhe file contains more events than requested. This is never expected to happen."; + << "Error in ExternalLHEProducer::endRunProduce(). " + << "Event loop is over, but there are still lhe events to process." + << "This could happen if lhe file contains more events than requested. This is never expected to happen."; } reader_.reset(); @@ -442,11 +442,11 @@ void ExternalLHEProducer::executeScript() { if ((fd_flags = fcntl(filedes[1], F_GETFD, NULL)) == -1) { throw cms::Exception("ExternalLHEProducer") - << "Failed to get pipe file descriptor flags (errno=" << rc << ", " << strerror(rc) << ")"; + << "Failed to get pipe file descriptor flags (errno=" << rc << ", " << strerror(rc) << ")"; } if (fcntl(filedes[1], F_SETFD, fd_flags | FD_CLOEXEC) == -1) { throw cms::Exception("ExternalLHEProducer") - << "Failed to set pipe file descriptor flags (errno=" << rc << ", " << strerror(rc) << ")"; + << "Failed to set pipe file descriptor flags (errno=" << rc << ", " << strerror(rc) << ")"; } argc = 1 + args_.size(); @@ -478,7 +478,7 @@ void ExternalLHEProducer::executeScript() { if (pid == -1) { throw cms::Exception("ForkException") - << "Unable to fork a child (errno=" << errno << ", " << strerror(errno) << ")"; + << "Unable to fork a child (errno=" << errno << ", " << strerror(errno) << ")"; } close(filedes[1]); @@ -488,7 +488,7 @@ void ExternalLHEProducer::executeScript() { } if ((rc2 == sizeof(int)) && rc) { throw cms::Exception("ExternalLHEProducer") - << "Failed to execute script (errno=" << rc << ", " << strerror(rc) << ")"; + << "Failed to execute script (errno=" << rc << ", " << strerror(rc) << ")"; } close(filedes[0]); @@ -500,7 +500,7 @@ void ExternalLHEProducer::executeScript() { continue; } else { throw cms::Exception("ExternalLHEProducer") - << "Failed to read child status (errno=" << errno << ", " << strerror(errno) << ")"; + << "Failed to read child status (errno=" << errno << ", " << strerror(errno) << ")"; } } if (WIFSIGNALED(status)) { @@ -543,7 +543,7 @@ std::unique_ptr ExternalLHEProducer::readOutput() { << " (errno=" << errno << ", " << strerror(errno) << ")."; } - return std::unique_ptr(new std::string(ss.str())); + return std::make_unique(ss.str()); } // ------------ method fills 'descriptions' with the allowed parameters for the module ------------ diff --git a/GeneratorInterface/LHEInterface/plugins/LHESource.cc b/GeneratorInterface/LHEInterface/plugins/LHESource.cc index ce248aa8a0850..b7c8e40968afe 100644 --- a/GeneratorInterface/LHEInterface/plugins/LHESource.cc +++ b/GeneratorInterface/LHEInterface/plugins/LHESource.cc @@ -31,13 +31,12 @@ using namespace lhef; -LHESource::LHESource(const edm::ParameterSet ¶ms, - const edm::InputSourceDescription &desc) : - ProducerSourceFromFiles(params, desc, false), - reader_(new LHEReader(fileNames(0), params.getUntrackedParameter("skipEvents", 0))), - lheProvenanceHelper_(edm::TypeID(typeid(LHEEventProduct)), edm::TypeID(typeid(LHERunInfoProduct)), productRegistryUpdate()), - phid_() -{ +LHESource::LHESource(const edm::ParameterSet& params, const edm::InputSourceDescription& desc) + : ProducerSourceFromFiles(params, desc, false), + reader_(new LHEReader(fileNames(0), params.getUntrackedParameter("skipEvents", 0))), + lheProvenanceHelper_( + edm::TypeID(typeid(LHEEventProduct)), edm::TypeID(typeid(LHERunInfoProduct)), productRegistryUpdate()), + phid_() { nextEvent(); lheProvenanceHelper_.lheAugment(nullptr); // Initialize metadata, and save the process history ID for use every event. @@ -48,17 +47,11 @@ LHESource::LHESource(const edm::ParameterSet ¶ms, //produces(); } -LHESource::~LHESource() -{ -} +LHESource::~LHESource() {} -void LHESource::endJob() -{ - reader_.reset(); -} +void LHESource::endJob() { reader_.reset(); } -void LHESource::nextEvent() -{ +void LHESource::nextEvent() { if (partonLevel_) { return; } @@ -67,7 +60,7 @@ void LHESource::nextEvent() do { newFileOpened = false; partonLevel_ = reader_->next(&newFileOpened); - if(newFileOpened) { + if (newFileOpened) { incrementFileIndex(); } } while (newFileOpened && !partonLevel_); @@ -79,8 +72,7 @@ void LHESource::nextEvent() auto runInfoThis = partonLevel_->getRunInfo(); if (runInfoThis != runInfoLast_) { runInfoLast_ = runInfoThis; - std::unique_ptr product( - new LHERunInfoProduct(*runInfoThis->getHEPRUP())); + std::unique_ptr product(new LHERunInfoProduct(*runInfoThis->getHEPRUP())); fillRunInfoProduct(*runInfoThis, *product); if (runInfoProductLast_) { @@ -98,27 +90,23 @@ void LHESource::nextEvent() } } -void -LHESource::fillRunInfoProduct(lhef::LHERunInfo const& iInfo, LHERunInfoProduct& oProduct) { - for(auto const& h: iInfo.getHeaders()) { +void LHESource::fillRunInfoProduct(lhef::LHERunInfo const& iInfo, LHERunInfoProduct& oProduct) { + for (auto const& h : iInfo.getHeaders()) { oProduct.addHeader(h); } - for(auto const& c: iInfo.getComments()) { + for (auto const& c : iInfo.getComments()) { oProduct.addComment(c); } } - -void -LHESource::readRun_(edm::RunPrincipal& runPrincipal) { +void LHESource::readRun_(edm::RunPrincipal& runPrincipal) { runAuxiliary()->setProcessHistoryID(phid_); runPrincipal.fillRunPrincipal(processHistoryRegistryForUpdate()); putRunInfoProduct(runPrincipal); } -void -LHESource::readLuminosityBlock_(edm::LuminosityBlockPrincipal& lumiPrincipal) { +void LHESource::readLuminosityBlock_(edm::LuminosityBlockPrincipal& lumiPrincipal) { luminosityBlockAuxiliary()->setProcessHistoryID(phid_); lumiPrincipal.fillLuminosityBlockPrincipal( processHistoryRegistry().getMapped(lumiPrincipal.aux().processHistoryID())); @@ -132,8 +120,7 @@ void LHESource::putRunInfoProduct(edm::RunPrincipal& iRunPrincipal) { } } -bool LHESource::setRunAndEventInfo(edm::EventID&, edm::TimeValue_t&, edm::EventAuxiliary::ExperimentType&) -{ +bool LHESource::setRunAndEventInfo(edm::EventID&, edm::TimeValue_t&, edm::EventAuxiliary::ExperimentType&) { nextEvent(); if (!partonLevel_) { // We just finished an input file. See if there is another. @@ -146,42 +133,38 @@ bool LHESource::setRunAndEventInfo(edm::EventID&, edm::TimeValue_t&, edm::EventA return true; } -void -LHESource::readEvent_(edm::EventPrincipal& eventPrincipal) { +void LHESource::readEvent_(edm::EventPrincipal& eventPrincipal) { assert(eventCached() || processingMode() != RunsLumisAndEvents); edm::EventAuxiliary aux(eventID(), processGUID(), edm::Timestamp(presentTime()), false); aux.setProcessHistoryID(phid_); eventPrincipal.fillEventPrincipal(aux, processHistoryRegistry().getMapped(aux.processHistoryID())); std::unique_ptr product( - new LHEEventProduct(*partonLevel_->getHEPEUP(), - partonLevel_->originalXWGTUP()) - ); + new LHEEventProduct(*partonLevel_->getHEPEUP(), partonLevel_->originalXWGTUP())); if (partonLevel_->getPDF()) { product->setPDF(*partonLevel_->getPDF()); } std::for_each(partonLevel_->weights().begin(), partonLevel_->weights().end(), - boost::bind(&LHEEventProduct::addWeight, - product.get(), _1)); + boost::bind(&LHEEventProduct::addWeight, product.get(), _1)); product->setScales(partonLevel_->scales()); product->setNpLO(partonLevel_->npLO()); product->setNpNLO(partonLevel_->npNLO()); std::for_each(partonLevel_->getComments().begin(), partonLevel_->getComments().end(), - boost::bind(&LHEEventProduct::addComment, - product.get(), _1)); + boost::bind(&LHEEventProduct::addComment, product.get(), _1)); std::unique_ptr edp(new edm::Wrapper(std::move(product))); - eventPrincipal.put(lheProvenanceHelper_.eventProductBranchDescription_, std::move(edp), lheProvenanceHelper_.eventProductProvenance_); + eventPrincipal.put(lheProvenanceHelper_.eventProductBranchDescription_, + std::move(edp), + lheProvenanceHelper_.eventProductProvenance_); partonLevel_.reset(); resetEventCached(); } -std::shared_ptr -LHESource::readRunAuxiliary_() { +std::shared_ptr LHESource::readRunAuxiliary_() { edm::Timestamp ts = edm::Timestamp(presentTime()); resetNewRun(); auto aux = std::make_shared(eventID().run(), ts, edm::Timestamp::invalidTimestamp()); @@ -189,19 +172,18 @@ LHESource::readRunAuxiliary_() { return aux; } -std::shared_ptr -LHESource::readLuminosityBlockAuxiliary_() { - if (processingMode() == Runs) return std::shared_ptr(); +std::shared_ptr LHESource::readLuminosityBlockAuxiliary_() { + if (processingMode() == Runs) + return std::shared_ptr(); edm::Timestamp ts = edm::Timestamp(presentTime()); resetNewLumi(); - auto aux = std::make_shared(eventID().run(), eventID().luminosityBlock(), - ts, edm::Timestamp::invalidTimestamp()); + auto aux = std::make_shared( + eventID().run(), eventID().luminosityBlock(), ts, edm::Timestamp::invalidTimestamp()); aux->setProcessHistoryID(phid_); return aux; } -void -LHESource::fillDescriptions(edm::ConfigurationDescriptions& descriptions) { +void LHESource::fillDescriptions(edm::ConfigurationDescriptions& descriptions) { edm::ParameterSetDescription desc; desc.setComment("A source which reads LHE files."); edm::ProducerSourceFromFiles::fillDescription(desc); diff --git a/GeneratorInterface/LHEInterface/plugins/LHESource.h b/GeneratorInterface/LHEInterface/plugins/LHESource.h index 46bad67ce4f4c..5d70b7b5e404a 100644 --- a/GeneratorInterface/LHEInterface/plugins/LHESource.h +++ b/GeneratorInterface/LHEInterface/plugins/LHESource.h @@ -51,7 +51,7 @@ class LHESource : public edm::ProducerSourceFromFiles { void putRunInfoProduct(edm::RunPrincipal&); void putWeightInfoProduct(edm::RunPrincipal&); - void fillRunInfoProduct(lhef::LHERunInfo const&, LHERunInfoProduct& ); + void fillRunInfoProduct(lhef::LHERunInfo const&, LHERunInfoProduct&); std::unique_ptr reader_; diff --git a/PhysicsTools/NanoAOD/interface/GenWeightCounters.h b/PhysicsTools/NanoAOD/interface/GenWeightCounters.h index 4229cddb32ab6..11cb9aa8c79e4 100644 --- a/PhysicsTools/NanoAOD/interface/GenWeightCounters.h +++ b/PhysicsTools/NanoAOD/interface/GenWeightCounters.h @@ -1,8 +1,8 @@ #ifndef GENWEIGHTSCOUNTERS_h #define GENWEIGHTSCOUNTERS_h -#include -#include -#include +#include +#include +#include namespace genCounter { void mergeSumVectors(std::vector& v1, std::vector const& v2) { @@ -32,12 +32,12 @@ namespace genCounter { void incLHE(double w0, const std::vector& weightV, const std::string& wName) { //if new type of weight, create a map element - if(weightSumMap_.find(wName) == weightSumMap_.end()) { - std::vector temp; - weightSumMap_.insert({wName, temp}); + if (weightSumMap_.find(wName) == weightSumMap_.end()) { + std::vector temp; + weightSumMap_.insert({wName, temp}); } if (!weightV.empty()) { - if (weightSumMap_[wName].empty()) + if (weightSumMap_[wName].empty()) weightSumMap_[wName].resize(weightV.size(), 0); for (unsigned int i = 0, n = weightV.size(); i < n; ++i) weightSumMap_[wName][i] += (w0 * weightV[i]); @@ -52,16 +52,15 @@ namespace genCounter { sumw2_ += other.sumw2_; //if weightMap_ for "this" is empty, create map elements with empty //vectors before merging - if(weightSumMap_.empty() && !other.weightSumMap_.empty()) { - for(auto& wmap : other.weightSumMap_) { - std::vector temp; + if (weightSumMap_.empty() && !other.weightSumMap_.empty()) { + for (auto& wmap : other.weightSumMap_) { + std::vector temp; weightSumMap_.insert({wmap.first, temp}); } } - for(auto& wmap : weightSumMap_) { + for (auto& wmap : weightSumMap_) { mergeSumVectors(wmap.second, other.weightSumMap_.at(wmap.first)); } - } //private: @@ -106,5 +105,5 @@ namespace genCounter { } }; -} +} // namespace genCounter #endif diff --git a/PhysicsTools/NanoAOD/plugins/LHETablesProducer.cc b/PhysicsTools/NanoAOD/plugins/LHETablesProducer.cc index 1646b08a29381..877c5e8f7eb6f 100644 --- a/PhysicsTools/NanoAOD/plugins/LHETablesProducer.cc +++ b/PhysicsTools/NanoAOD/plugins/LHETablesProducer.cc @@ -18,7 +18,7 @@ class LHETablesProducer : public edm::global::EDProducer<> { [this](const edm::InputTag& tag) { return mayConsume(tag); })), precision_(params.getParameter("precision")), storeLHEParticles_(params.getParameter("storeLHEParticles")), - storeAllLHEInfo_(params.getParameter("storeAllLHEInfo")){ + storeAllLHEInfo_(params.getParameter("storeAllLHEInfo")) { produces("LHE"); if (storeLHEParticles_) produces("LHEPart"); @@ -55,9 +55,9 @@ class LHETablesProducer : public edm::global::EDProducer<> { unsigned int lheNj = 0, lheNb = 0, lheNc = 0, lheNuds = 0, lheNglu = 0; double lheVpt = 0; double alphaS = 0; - double alphaQED=0; - double scale = 0; - int idproc = 0; + double alphaQED = 0; + double scale = 0; + int idproc = 0; const auto& hepeup = lheProd.hepeup(); const auto& pup = hepeup.PUP; int lep = -1, lepBar = -1, nu = -1, nuBar = -1; @@ -75,8 +75,8 @@ class LHETablesProducer : public edm::global::EDProducer<> { std::vector vals_mother1; std::vector vals_mother2; alphaS = hepeup.AQCDUP; - alphaQED = hepeup.AQEDUP; - scale = hepeup.SCALUP; + alphaQED = hepeup.AQEDUP; + scale = hepeup.SCALUP; idproc = hepeup.IDPRUP; for (unsigned int i = 0, n = pup.size(); i < n; ++i) { int status = hepeup.ISTUP[i]; @@ -86,12 +86,12 @@ class LHETablesProducer : public edm::global::EDProducer<> { vals_pid.push_back(hepeup.IDUP[i]); vals_spin.push_back(hepeup.SPINUP[i]); vals_status.push_back(status); - if (storeAllLHEInfo_){ - vals_col1.push_back(hepeup.ICOLUP[i].first); - vals_col2.push_back(hepeup.ICOLUP[i].second); - vals_mother1.push_back(hepeup.MOTHUP[i].first); - vals_mother2.push_back(hepeup.MOTHUP[i].second); - vals_time.push_back(hepeup.VTIMUP[i]); + if (storeAllLHEInfo_) { + vals_col1.push_back(hepeup.ICOLUP[i].first); + vals_col2.push_back(hepeup.ICOLUP[i].second); + vals_mother1.push_back(hepeup.MOTHUP[i].first); + vals_mother2.push_back(hepeup.MOTHUP[i].second); + vals_time.push_back(hepeup.VTIMUP[i]); } if (status == -1) { vals_pt.push_back(0); @@ -149,47 +149,38 @@ class LHETablesProducer : public edm::global::EDProducer<> { lheVpt = std::hypot(pup[v.first][0] + pup[v.second][0], pup[v.first][1] + pup[v.second][1]); } - out.addColumnValue( - "Njets", lheNj, "Number of jets (partons) at LHE step"); + out.addColumnValue("Njets", lheNj, "Number of jets (partons) at LHE step"); out.addColumnValue("Nb", lheNb, "Number of b partons at LHE step"); out.addColumnValue("Nc", lheNc, "Number of c partons at LHE step"); - out.addColumnValue( - "Nuds", lheNuds, "Number of u,d,s partons at LHE step"); - out.addColumnValue( - "Nglu", lheNglu, "Number of gluon partons at LHE step"); + out.addColumnValue("Nuds", lheNuds, "Number of u,d,s partons at LHE step"); + out.addColumnValue("Nglu", lheNglu, "Number of gluon partons at LHE step"); out.addColumnValue("HT", lheHT, "HT, scalar sum of parton pTs at LHE step"); - out.addColumnValue("HTIncoming", - lheHTIncoming, - "HT, scalar sum of parton pTs at LHE step, restricted to partons"); + out.addColumnValue( + "HTIncoming", lheHTIncoming, "HT, scalar sum of parton pTs at LHE step, restricted to partons"); out.addColumnValue("Vpt", lheVpt, "pT of the W or Z boson at LHE step"); out.addColumnValue("NpNLO", lheProd.npNLO(), "number of partons at NLO"); out.addColumnValue("NpLO", lheProd.npLO(), "number of partons at LO"); out.addColumnValue("AlphaS", alphaS, "Per-event alphaS"); - if (storeAllLHEInfo_){ - out.addColumnValue("AlphaQED", alphaQED, "Per-event alphaQED"); - out.addColumnValue("Scale", scale, "Per-event scale"); - out.addColumnValue("ProcessID", idproc, "Process id (as in the card ordering)"); + if (storeAllLHEInfo_) { + out.addColumnValue("AlphaQED", alphaQED, "Per-event alphaQED"); + out.addColumnValue("Scale", scale, "Per-event scale"); + out.addColumnValue("ProcessID", idproc, "Process id (as in the card ordering)"); } auto outPart = std::make_unique(vals_pt.size(), "LHEPart", false); outPart->addColumn("pt", vals_pt, "Pt of LHE particles", this->precision_); - outPart->addColumn( - "eta", vals_eta, "Pseodorapidity of LHE particles", this->precision_); - outPart->addColumn( - "phi", vals_phi, "Phi of LHE particles", this->precision_); - outPart->addColumn( - "mass", vals_mass, "Mass of LHE particles", this->precision_); - outPart->addColumn( - "incomingpz", vals_pz, "Pz of incoming LHE particles", this->precision_); + outPart->addColumn("eta", vals_eta, "Pseodorapidity of LHE particles", this->precision_); + outPart->addColumn("phi", vals_phi, "Phi of LHE particles", this->precision_); + outPart->addColumn("mass", vals_mass, "Mass of LHE particles", this->precision_); + outPart->addColumn("incomingpz", vals_pz, "Pz of incoming LHE particles", this->precision_); outPart->addColumn("pdgId", vals_pid, "PDG ID of LHE particles"); - outPart->addColumn( - "status", vals_status, "LHE particle status; -1:incoming, 1:outgoing"); + outPart->addColumn("status", vals_status, "LHE particle status; -1:incoming, 1:outgoing"); outPart->addColumn("spin", vals_spin, "Spin of LHE particles"); - if (storeAllLHEInfo_){ - outPart->addColumn("color1", vals_col1, "First color index of LHE particles"); - outPart->addColumn("color2", vals_col2, "Second color index of LHE particles"); - outPart->addColumn("mother1", vals_mother1, "First mother index of LHE particles"); - outPart->addColumn("mother2", vals_mother2, "Second mother index of LHE particles"); - outPart->addColumn("lifetime", vals_time, "Own lifetime of LHE particles", this->precision_); + if (storeAllLHEInfo_) { + outPart->addColumn("color1", vals_col1, "First color index of LHE particles"); + outPart->addColumn("color2", vals_col2, "Second color index of LHE particles"); + outPart->addColumn("mother1", vals_mother1, "First mother index of LHE particles"); + outPart->addColumn("mother2", vals_mother2, "Second mother index of LHE particles"); + outPart->addColumn("lifetime", vals_time, "Own lifetime of LHE particles", this->precision_); } return outPart; } @@ -201,7 +192,8 @@ class LHETablesProducer : public edm::global::EDProducer<> { desc.add("precision", -1)->setComment("precision on the 4-momenta of the LHE particles"); desc.add("storeLHEParticles", false) ->setComment("Whether we want to store the 4-momenta of the status 1 particles at LHE level"); - desc.add("storeAllLHEInfo", false)->setComment("Whether to store the whole set of intermediate LHE particles, not only the status +/-1 ones"); + desc.add("storeAllLHEInfo", false) + ->setComment("Whether to store the whole set of intermediate LHE particles, not only the status +/-1 ones"); descriptions.add("lheInfoTable", desc); } diff --git a/PhysicsTools/NanoAOD/plugins/LHEWeightsTableProducer.cc b/PhysicsTools/NanoAOD/plugins/LHEWeightsTableProducer.cc index ae11ba2dcb014..0fbdb7d4c5af9 100644 --- a/PhysicsTools/NanoAOD/plugins/LHEWeightsTableProducer.cc +++ b/PhysicsTools/NanoAOD/plugins/LHEWeightsTableProducer.cc @@ -30,23 +30,23 @@ namespace { using CounterMap = genCounter::CounterMap; using Counter = genCounter::Counter; -class LHEWeightsTableProducer : -public edm::global::EDProducer, - edm::StreamCache, - edm::RunSummaryCache, - edm::EndRunProducer> { +class LHEWeightsTableProducer : public edm::global::EDProducer, + edm::StreamCache, + edm::RunSummaryCache, + edm::EndRunProducer> { public: LHEWeightsTableProducer(edm::ParameterSet const& params); void produce(edm::StreamID id, edm::Event& iEvent, const edm::EventSetup& iSetup) const override; //func changed//sroychow void addWeightGroupToTable(std::map>& lheWeightTables, - std::map>& weightVecsizes, - std::map& weightlabels, - const char* typeName, - const WeightGroupDataContainer& weightInfos, - WeightsContainer& allWeights, Counter& counter, - double genWeight) const; + std::map>& weightVecsizes, + std::map& weightlabels, + const char* typeName, + const WeightGroupDataContainer& weightInfos, + WeightsContainer& allWeights, + Counter& counter, + double genWeight) const; WeightGroupDataContainer weightDataPerType(edm::Handle& weightsHandle, gen::WeightType weightType, int& maxStore) const; @@ -54,11 +54,12 @@ public edm::global::EDProducer, std::vector orderedScaleWeights(const std::vector& scaleWeights, const gen::ScaleWeightGroupInfo& scaleGroup) const; - std::vector preferredPSweights(const std::vector& psWeights, const gen::PartonShowerWeightGroupInfo& pswV) const; + std::vector preferredPSweights(const std::vector& psWeights, + const gen::PartonShowerWeightGroupInfo& pswV) const; //Lumiblock std::shared_ptr globalBeginLuminosityBlock(edm::LuminosityBlock const& iLumi, - edm::EventSetup const&) const override { + edm::EventSetup const&) const override { // Set equal to the max number of groups // subtrack 1 for each weight group you find bool foundLheWeights = false; @@ -66,21 +67,21 @@ public edm::global::EDProducer, for (auto& token : lheWeightInfoTokens_) { iLumi.getByToken(token, lheWeightInfoHandle); if (lheWeightInfoHandle.isValid()) { - foundLheWeights = true; - break; + foundLheWeights = true; + break; } } edm::Handle genWeightInfoHandle; iLumi.getByToken(genWeightInfoToken_, genWeightInfoHandle); - + std::unordered_map storePerType; for (size_t i = 0; i < weightgroups_.size(); i++) storePerType[weightgroups_.at(i)] = maxGroupsPerType_.at(i); - + WeightGroupsToStore weightsToStore; for (auto weightType : gen::allWeightTypes) { - if (foundLheWeights) { - auto lheWeights = weightDataPerType(lheWeightInfoHandle, weightType, storePerType[weightType]); + if (foundLheWeights) { + auto lheWeights = weightDataPerType(lheWeightInfoHandle, weightType, storePerType[weightType]); for (auto& w : lheWeights) weightsToStore.at(inLHE).push_back({w.index, std::move(w.group)}); } @@ -90,44 +91,46 @@ public edm::global::EDProducer, } return std::make_shared(weightsToStore); } - + // nothing to do here - virtual void globalEndLuminosityBlock(edm::LuminosityBlock const&, edm::EventSetup const&) const override {} + void globalEndLuminosityBlock(edm::LuminosityBlock const&, edm::EventSetup const&) const override {} // create an empty counter - std::unique_ptr beginStream(edm::StreamID) const override { return std::make_unique(); } + std::unique_ptr beginStream(edm::StreamID) const override { return std::make_unique(); } // inizialize to zero at begin run - void streamBeginRun(edm::StreamID id, - edm::Run const&, edm::EventSetup const&) const override { streamCache(id)->clear(); } - + void streamBeginRun(edm::StreamID id, edm::Run const&, edm::EventSetup const&) const override { + streamCache(id)->clear(); + } + void streamBeginLuminosityBlock(edm::StreamID id, - edm::LuminosityBlock const& lumiBlock, - edm::EventSetup const& eventSetup) const override { + edm::LuminosityBlock const& lumiBlock, + edm::EventSetup const& eventSetup) const override { auto counterMap = streamCache(id); edm::Handle genLumiInfoHead; lumiBlock.getByToken(genLumiInfoHeadTag_, genLumiInfoHead); if (!genLumiInfoHead.isValid()) edm::LogWarning("LHETablesProducer") - << "No GenLumiInfoHeader product found, will not fill generator model string.\n"; - counterMap->setLabel(genLumiInfoHead.isValid() ? genLumiInfoHead->configDescription() : ""); + << "No GenLumiInfoHeader product found, will not fill generator model string.\n"; + counterMap->setLabel(genLumiInfoHead.isValid() ? genLumiInfoHead->configDescription() : ""); std::string label = genLumiInfoHead.isValid() ? counterMap->getLabel() : "NULL"; - } // create an empty counter std::shared_ptr globalBeginRunSummary(edm::Run const&, edm::EventSetup const&) const override { return std::make_shared(); } // add this stream to the summary - void streamEndRunSummary(edm::StreamID id, edm::Run const&, - edm::EventSetup const&, CounterMap* runCounterMap) const override; + void streamEndRunSummary(edm::StreamID id, + edm::Run const&, + edm::EventSetup const&, + CounterMap* runCounterMap) const override; // nothing to do per se void globalEndRunSummary(edm::Run const&, edm::EventSetup const&, CounterMap* runCounterMap) const override {} // write the total to the run void globalEndRunProduce(edm::Run& iRun, edm::EventSetup const& es, CounterMap const* runCounterMap) const override; // nothing to do here //void globalEndRun(edm::Run const& iRun, edm::EventSetup const& es, CounterMap* runCounterMap) const override {} - + static void fillDescriptions(edm::ConfigurationDescriptions& descriptions); - + protected: const std::vector> lheWeightTokens_; const std::vector> lheWeightInfoTokens_; @@ -139,40 +142,41 @@ public edm::global::EDProducer, const std::vector maxGroupsPerType_; const std::vector pdfIds_; const std::unordered_map weightTypeNames_ = { - {gen::WeightType::kScaleWeights, "LHEScaleWeight"}, - {gen::WeightType::kPdfWeights, "LHEPdfWeight"}, - {gen::WeightType::kMEParamWeights, "MEParamWeight"}, - {gen::WeightType::kPartonShowerWeights, "PSWeight"}, - {gen::WeightType::kUnknownWeights, "UnknownWeight"}, + {gen::WeightType::kScaleWeights, "LHEScaleWeight"}, + {gen::WeightType::kPdfWeights, "LHEPdfWeight"}, + {gen::WeightType::kMEParamWeights, "MEParamWeight"}, + {gen::WeightType::kPartonShowerWeights, "PSWeight"}, + {gen::WeightType::kUnknownWeights, "UnknownWeight"}, }; //std::unordered_map weightGroupIndices_; int lheWeightPrecision_; - bool storeAllPSweights_; + bool storeAllPSweights_; enum { inLHE, inGen }; }; //put back if needed; till now not used LHEWeightsTableProducer::LHEWeightsTableProducer(edm::ParameterSet const& params) - : lheWeightTokens_( - edm::vector_transform(params.getParameter>("lheWeights"), - [this](const edm::InputTag& tag) { return mayConsume(tag); })), + : lheWeightTokens_( + edm::vector_transform(params.getParameter>("lheWeights"), + [this](const edm::InputTag& tag) { return mayConsume(tag); })), lheWeightInfoTokens_(edm::vector_transform( - params.getParameter>("lheWeights"), - [this](const edm::InputTag& tag) { return mayConsume(tag); })), - genWeightToken_(consumes(params.getParameter("genWeights"))), - genWeightInfoToken_(consumes(params.getParameter("genWeights"))), - genEventInfoToken_(consumes(params.getParameter("genEvent"))), - genLumiInfoHeadTag_(mayConsume(params.getParameter("genLumiInfoHeader"))), - weightgroups_(edm::vector_transform(params.getParameter>("weightgroups"), - [](auto& c) { return gen::WeightType(c.at(0)); })), - maxGroupsPerType_(params.getParameter>("maxGroupsPerType")), - pdfIds_(params.getUntrackedParameter>("pdfIds", {})), - lheWeightPrecision_(params.getParameter("lheWeightPrecision")), - storeAllPSweights_(params.getParameter("storeAllPSweights")) -{ + params.getParameter>("lheWeights"), + [this](const edm::InputTag& tag) { return mayConsume(tag); })), + genWeightToken_(consumes(params.getParameter("genWeights"))), + genWeightInfoToken_( + consumes(params.getParameter("genWeights"))), + genEventInfoToken_(consumes(params.getParameter("genEvent"))), + genLumiInfoHeadTag_( + mayConsume(params.getParameter("genLumiInfoHeader"))), + weightgroups_(edm::vector_transform(params.getParameter>("weightgroups"), + [](auto& c) { return gen::WeightType(c.at(0)); })), + maxGroupsPerType_(params.getParameter>("maxGroupsPerType")), + pdfIds_(params.getUntrackedParameter>("pdfIds", {})), + lheWeightPrecision_(params.getParameter("lheWeightPrecision")), + storeAllPSweights_(params.getParameter("storeAllPSweights")) { if (weightgroups_.size() != maxGroupsPerType_.size()) throw std::invalid_argument("Inputs 'weightgroups' and 'weightgroupNums' must have equal size"); - for(auto& wg : weightTypeNames_) { + for (auto& wg : weightTypeNames_) { produces(wg.second); produces(wg.second + "sizes"); } @@ -188,15 +192,15 @@ void LHEWeightsTableProducer::produce(edm::StreamID id, edm::Event& iEvent, cons bool foundLheWeights = false; for (auto& token : lheWeightTokens_) { iEvent.getByToken(token, lheWeightHandle); - if (lheWeightHandle.isValid()) { - foundLheWeights = true; - break; - } + if (lheWeightHandle.isValid()) { + foundLheWeights = true; + break; + } } //Taken from genweight producer //Added sroychow // generator information (always available) auto const& genInfo = iEvent.get(genEventInfoToken_); - const double genWeight = genInfo.weight(); + const double genWeight = genInfo.weight(); // table for gen info, always available auto outGeninfo = std::make_unique(1, "genWeight", true); outGeninfo->setDoc("generator weight"); @@ -204,7 +208,7 @@ void LHEWeightsTableProducer::produce(edm::StreamID id, edm::Event& iEvent, cons iEvent.put(std::move(outGeninfo), "GENWeight"); //this will take care of sum of genWeights counter.incGenOnly(genWeight); - + std::string& model_label = streamCache(id)->getLabel(); auto outM = std::make_unique((!model_label.empty()) ? std::string("GenModel_") + model_label : ""); iEvent.put(std::move(outM), "genModel"); @@ -214,30 +218,32 @@ void LHEWeightsTableProducer::produce(edm::StreamID id, edm::Event& iEvent, cons const GenWeightProduct* lheWeightProduct = lheWeightHandle.product(); lheWeights = lheWeightProduct->weights(); } - + edm::Handle genWeightHandle; iEvent.getByToken(genWeightToken_, genWeightHandle); const GenWeightProduct* genWeightProduct = genWeightHandle.product(); WeightsContainer genWeights = genWeightProduct->weights(); - + auto const& weightInfos = *luminosityBlockCache(iEvent.getLuminosityBlock().index()); - + //create a container with dummy weight vector std::map> lheWeightTables; std::map> weightVecsizes; std::map weightlabels; - for(auto& wg : weightTypeNames_) { + for (auto& wg : weightTypeNames_) { lheWeightTables.insert(std::make_pair(wg.first, std::vector())); weightVecsizes.insert(std::make_pair(wg.first, std::vector())); weightlabels.insert(std::make_pair(wg.first, "")); } if (foundLheWeights) { - addWeightGroupToTable(lheWeightTables, weightVecsizes, weightlabels, "LHE", weightInfos.at(inLHE), lheWeights, counter, genWeight); + addWeightGroupToTable( + lheWeightTables, weightVecsizes, weightlabels, "LHE", weightInfos.at(inLHE), lheWeights, counter, genWeight); } - addWeightGroupToTable(lheWeightTables, weightVecsizes, weightlabels, "Gen", weightInfos.at(inGen), genWeights, counter, genWeight); - - for(auto& wg : weightTypeNames_) { + addWeightGroupToTable( + lheWeightTables, weightVecsizes, weightlabels, "Gen", weightInfos.at(inGen), genWeights, counter, genWeight); + + for (auto& wg : weightTypeNames_) { std::string wname = wg.second; auto& weightVec = lheWeightTables[wg.first]; counter.incLHE(genWeight, weightVec, wname); @@ -245,9 +251,10 @@ void LHEWeightsTableProducer::produce(edm::StreamID id, edm::Event& iEvent, cons outTable->addColumn("", weightVec, weightlabels[wg.first], lheWeightPrecision_); //now add the vector containing the sizes of alt sets - auto outTableSizes = std::make_unique(weightVecsizes[wg.first].size(), wname + "_AltSetSizes", false); - outTableSizes->addColumn("", weightVecsizes[wg.first], "Sizes of weight arrays for weight type:" + wname, - lheWeightPrecision_); + auto outTableSizes = + std::make_unique(weightVecsizes[wg.first].size(), wname + "_AltSetSizes", false); + outTableSizes->addColumn( + "", weightVecsizes[wg.first], "Sizes of weight arrays for weight type:" + wname, lheWeightPrecision_); iEvent.put(std::move(outTable), wname); iEvent.put(std::move(outTableSizes), wname + "sizes"); } @@ -257,23 +264,24 @@ void LHEWeightsTableProducer::produce(edm::StreamID id, edm::Event& iEvent, cons */ void LHEWeightsTableProducer::addWeightGroupToTable(std::map>& lheWeightTables, - std::map>& weightVecsizes, - std::map& weightlabels, - const char* typeName, - const WeightGroupDataContainer& weightInfos, - WeightsContainer& allWeights, Counter& counter, - double genWeight) const { + std::map>& weightVecsizes, + std::map& weightlabels, + const char* typeName, + const WeightGroupDataContainer& weightInfos, + WeightsContainer& allWeights, + Counter& counter, + double genWeight) const { std::unordered_map typeCount = {}; for (auto& type : gen::allWeightTypes) - typeCount[type] = 0; - + typeCount[type] = 0; + for (const auto& groupInfo : weightInfos) { //std::string entryName = typeName; gen::WeightType weightType = groupInfo.group->weightType(); std::string name = weightTypeNames_.at(weightType); std::string label = "[" + std::to_string(typeCount[weightType]) + "] " + groupInfo.group->description(); label.append("["); - label.append(std::to_string(lheWeightTables[weightType].size()));//to append the start index of this set + label.append(std::to_string(lheWeightTables[weightType].size())); //to append the start index of this set label.append("]; "); auto& weights = allWeights.at(groupInfo.index); //std::cout << "Group name is " << groupInfo.group->name() << " is it wellFormed? " << groupInfo.group->isWellFormed() << std::endl; @@ -287,14 +295,18 @@ void LHEWeightsTableProducer::addWeightGroupToTable(std::map(gen::ScaleWeightGroupInfo::MIN_SCALE_VARIATIONS, weights.size()); - weights = std::vector(weights.begin(), weights.begin()+nstore); - label.append("WARNING: Unexpected format found. Contains first " + std::to_string(nstore) + " elements of weights vector, unordered"); + weights = std::vector(weights.begin(), weights.begin() + nstore); + label.append("WARNING: Unexpected format found. Contains first " + std::to_string(nstore) + + " elements of weights vector, unordered"); } - } else if (!storeAllPSweights_ && weightType == gen::WeightType::kPartonShowerWeights && groupInfo.group->isWellFormed()) { + } else if (!storeAllPSweights_ && weightType == gen::WeightType::kPartonShowerWeights && + groupInfo.group->isWellFormed()) { const auto psGroup = *static_cast(groupInfo.group.get()); weights = preferredPSweights(weights, psGroup); - label.append("PS weights (w_var / w_nominal); [0] is ISR=0.5 FSR=1; [1] is ISR=1 FSR=0.5; [2] is ISR=2 FSR=1; [3] is ISR=1 FSR=2"); - } + label.append( + "PS weights (w_var / w_nominal); [0] is ISR=0.5 FSR=1; [1] is ISR=1 FSR=0.5; [2] is ISR=2 FSR=1; [3] is " + "ISR=1 FSR=2"); + } //else // label.append(groupInfo.group->description()); lheWeightTables[weightType].insert(lheWeightTables[weightType].end(), weights.begin(), weights.end()); @@ -309,10 +321,10 @@ void LHEWeightsTableProducer::addWeightGroupToTable(std::map& weightsHandle, - gen::WeightType weightType, - int& maxStore) const { - std::vectorallgroups; - if (weightType == gen::WeightType::kPdfWeights && pdfIds_.size() > 0) { + gen::WeightType weightType, + int& maxStore) const { + std::vector allgroups; + if (weightType == gen::WeightType::kPdfWeights && !pdfIds_.empty()) { allgroups = weightsHandle->pdfGroupsWithIndicesByLHAIDs(pdfIds_); } else allgroups = weightsHandle->weightGroupsAndIndicesByType(weightType); @@ -334,7 +346,7 @@ WeightGroupDataContainer LHEWeightsTableProducer::weightDataPerType(edm::Handle< } std::vector LHEWeightsTableProducer::orderedScaleWeights(const std::vector& scaleWeights, - const gen::ScaleWeightGroupInfo& scaleGroup) const { + const gen::ScaleWeightGroupInfo& scaleGroup) const { std::vector weights; weights.emplace_back(scaleWeights.at(scaleGroup.muR05muF05Index())); weights.emplace_back(scaleWeights.at(scaleGroup.muR05muF1Index())); @@ -345,52 +357,54 @@ std::vector LHEWeightsTableProducer::orderedScaleWeights(const std::vect weights.emplace_back(scaleWeights.at(scaleGroup.muR2muF05Index())); weights.emplace_back(scaleWeights.at(scaleGroup.muR2muF1Index())); weights.emplace_back(scaleWeights.at(scaleGroup.muR2muF2Index())); - + return weights; } -std::vector LHEWeightsTableProducer::preferredPSweights(const std::vector& psWeights, - const gen::PartonShowerWeightGroupInfo& pswV) const { +std::vector LHEWeightsTableProducer::preferredPSweights(const std::vector& psWeights, + const gen::PartonShowerWeightGroupInfo& pswV) const { std::vector psTosave; - + double baseline = psWeights.at(pswV.weightIndexFromLabel("Baseline")); - psTosave.emplace_back(psWeights.at(pswV.variationIndex(true, true, gen::PSVarType::def))/baseline); - psTosave.emplace_back(psWeights.at(pswV.variationIndex(false, true, gen::PSVarType::def))/baseline); - psTosave.emplace_back(psWeights.at(pswV.variationIndex(true, false, gen::PSVarType::def))/baseline); - psTosave.emplace_back(psWeights.at(pswV.variationIndex(false, false, gen::PSVarType::def))/baseline); + psTosave.emplace_back(psWeights.at(pswV.variationIndex(true, true, gen::PSVarType::def)) / baseline); + psTosave.emplace_back(psWeights.at(pswV.variationIndex(false, true, gen::PSVarType::def)) / baseline); + psTosave.emplace_back(psWeights.at(pswV.variationIndex(true, false, gen::PSVarType::def)) / baseline); + psTosave.emplace_back(psWeights.at(pswV.variationIndex(false, false, gen::PSVarType::def)) / baseline); return psTosave; } void LHEWeightsTableProducer::streamEndRunSummary(edm::StreamID id, - edm::Run const&, - edm::EventSetup const&, - CounterMap* runCounterMap) const { + edm::Run const&, + edm::EventSetup const&, + CounterMap* runCounterMap) const { Counter& counter = *streamCache(id)->get(); //this takes care for mergeing all the weight sums runCounterMap->mergeSumMap(*streamCache(id)); } -void LHEWeightsTableProducer::globalEndRunProduce(edm::Run& iRun, edm::EventSetup const&, CounterMap const* runCounterMap) const { +void LHEWeightsTableProducer::globalEndRunProduce(edm::Run& iRun, + edm::EventSetup const&, + CounterMap const* runCounterMap) const { auto out = std::make_unique(); - + for (auto x : runCounterMap->countermap) { auto& runCounter = x.second; std::string label = std::string("_") + x.first; std::string doclabel = (!x.first.empty()) ? (std::string(", for model label ") + x.first) : ""; - + out->addInt("genEventCount" + label, "event count" + doclabel, runCounter.num_); out->addFloat("genEventSumw" + label, "sum of gen weights" + doclabel, runCounter.sumw_); out->addFloat("genEventSumw2" + label, "sum of gen (weight^2)" + doclabel, runCounter.sumw2_); - + double norm = runCounter.sumw_ ? 1.0 / runCounter.sumw_ : 1; //Sum from map - for(auto& sumw : runCounter.weightSumMap_) { - + for (auto& sumw : runCounter.weightSumMap_) { //Normalize with genEventSumw - for(auto& val : sumw.second) val *= norm; - out->addVFloat(sumw.first + "Sumw" + label, - "Sum of genEventWeight *" + sumw.first + "[i]/genEventSumw" + doclabel, - sumw.second) ; + for (auto& val : sumw.second) + val *= norm; + out->addVFloat(sumw.first + "Sumw" + label, + "Sum of genEventWeight *" + sumw.first + "[i]/genEventSumw" + doclabel, + sumw.second); } } iRun.put(std::move(out)); @@ -399,16 +413,18 @@ void LHEWeightsTableProducer::fillDescriptions(edm::ConfigurationDescriptions& d edm::ParameterSetDescription desc; desc.add>("lheWeights"); desc.add>("lheInfo", std::vector{{"externalLHEProducer"}, {"source"}}) - ->setComment("tag(s) for the LHE information (LHEEventProduct and LHERunInfoProduct)"); + ->setComment("tag(s) for the LHE information (LHEEventProduct and LHERunInfoProduct)"); //desc.add>("genWeights"); desc.add("genWeights"); - desc.add("genEvent", edm::InputTag("generator"))->setComment("tag for the GenEventInfoProduct, to get the main weight"); - desc.add("genLumiInfoHeader", edm::InputTag("generator"))->setComment("tag for the GenLumiInfoProduct, to get the model string"); + desc.add("genEvent", edm::InputTag("generator")) + ->setComment("tag for the GenEventInfoProduct, to get the main weight"); + desc.add("genLumiInfoHeader", edm::InputTag("generator")) + ->setComment("tag for the GenLumiInfoProduct, to get the model string"); desc.add>("weightgroups"); desc.add>("maxGroupsPerType"); desc.addOptionalUntracked>("pdfIds"); desc.add("lheWeightPrecision", -1)->setComment("Number of bits in the mantissa for LHE weights"); - desc.add("storeAllPSweights", 0)->setComment("True:stores all 45 PS weights; False:saves preferred 4"); + desc.add("storeAllPSweights", false)->setComment("True:stores all 45 PS weights; False:saves preferred 4"); descriptions.addDefault(desc); } diff --git a/PhysicsTools/NanoAOD/plugins/NanoAODOutputModule.cc b/PhysicsTools/NanoAOD/plugins/NanoAODOutputModule.cc index ca44bf6b3bcd1..4a6999ed42733 100644 --- a/PhysicsTools/NanoAOD/plugins/NanoAODOutputModule.cc +++ b/PhysicsTools/NanoAOD/plugins/NanoAODOutputModule.cc @@ -2,7 +2,7 @@ // // Package: PhysicsTools/NanoAODOutput // Class : NanoAODOutputModule -// +// // Implementation: // [Notes on implementation] // @@ -65,7 +65,7 @@ class NanoAODOutputModule : public edm::one::OutputModule<> { int m_eventsSinceFlush{0}; std::string m_compressionAlgorithm; bool m_writeProvenance; - bool m_fakeName; //crab workaround, remove after crab is fixed + bool m_fakeName; //crab workaround, remove after crab is fixed int m_autoFlush; edm::ProcessHistoryRegistry m_processHistoryRegistry; edm::JobReport::Token m_jrToken; @@ -75,45 +75,48 @@ class NanoAODOutputModule : public edm::one::OutputModule<> { static constexpr int m_firstFlush{1000}; class CommonEventBranches { - public: - void branch(TTree &tree) { - tree.Branch("run", & m_run, "run/i"); - tree.Branch("luminosityBlock", & m_luminosityBlock, "luminosityBlock/i"); - tree.Branch("event", & m_event, "event/l"); - } - void fill(const edm::EventID & id) { - m_run = id.run(); m_luminosityBlock = id.luminosityBlock(); m_event = id.event(); - } - private: - UInt_t m_run; UInt_t m_luminosityBlock; ULong64_t m_event; + public: + void branch(TTree& tree) { + tree.Branch("run", &m_run, "run/i"); + tree.Branch("luminosityBlock", &m_luminosityBlock, "luminosityBlock/i"); + tree.Branch("event", &m_event, "event/l"); + } + void fill(const edm::EventID& id) { + m_run = id.run(); + m_luminosityBlock = id.luminosityBlock(); + m_event = id.event(); + } + + private: + UInt_t m_run; + UInt_t m_luminosityBlock; + ULong64_t m_event; } m_commonBranches; class CommonLumiBranches { - public: - void branch(TTree &tree) { - tree.Branch("run", & m_run, "run/i"); - tree.Branch("luminosityBlock", & m_luminosityBlock, "luminosityBlock/i"); - } - void fill(const edm::LuminosityBlockID & id) { - m_run = id.run(); - m_luminosityBlock = id.value(); - } - private: - UInt_t m_run; UInt_t m_luminosityBlock; + public: + void branch(TTree& tree) { + tree.Branch("run", &m_run, "run/i"); + tree.Branch("luminosityBlock", &m_luminosityBlock, "luminosityBlock/i"); + } + void fill(const edm::LuminosityBlockID& id) { + m_run = id.run(); + m_luminosityBlock = id.value(); + } + + private: + UInt_t m_run; + UInt_t m_luminosityBlock; } m_commonLumiBranches; class CommonRunBranches { - public: - void branch(TTree &tree) { - tree.Branch("run", & m_run, "run/i"); - } - void fill(const edm::RunID & id) { - m_run = id.run(); - } - private: - UInt_t m_run; - } m_commonRunBranches; + public: + void branch(TTree& tree) { tree.Branch("run", &m_run, "run/i"); } + void fill(const edm::RunID& id) { m_run = id.run(); } + private: + UInt_t m_run; + } m_commonRunBranches; std::vector m_tables; std::vector m_tableTokens; @@ -124,11 +127,9 @@ class NanoAODOutputModule : public edm::one::OutputModule<> { std::vector m_runTables; - std::vector> m_nanoMetadata; - + std::vector> m_nanoMetadata; }; - // // constants, enums and typedefs // @@ -140,22 +141,19 @@ class NanoAODOutputModule : public edm::one::OutputModule<> { // // constructors and destructor // -NanoAODOutputModule::NanoAODOutputModule(edm::ParameterSet const& pset): - edm::one::OutputModuleBase::OutputModuleBase(pset), - edm::one::OutputModule<>(pset), - m_fileName(pset.getUntrackedParameter("fileName")), - m_logicalFileName(pset.getUntrackedParameter("logicalFileName")), - m_compressionLevel(pset.getUntrackedParameter("compressionLevel")), - m_compressionAlgorithm(pset.getUntrackedParameter("compressionAlgorithm")), - m_writeProvenance(pset.getUntrackedParameter("saveProvenance", true)), - m_fakeName(pset.getUntrackedParameter("fakeNameForCrab", false)), - m_autoFlush(pset.getUntrackedParameter("autoFlush", -10000000)), - m_processHistoryRegistry() -{ -} - -void -NanoAODOutputModule::write(edm::EventForOutput const& iEvent) { +NanoAODOutputModule::NanoAODOutputModule(edm::ParameterSet const& pset) + : edm::one::OutputModuleBase::OutputModuleBase(pset), + edm::one::OutputModule<>(pset), + m_fileName(pset.getUntrackedParameter("fileName")), + m_logicalFileName(pset.getUntrackedParameter("logicalFileName")), + m_compressionLevel(pset.getUntrackedParameter("compressionLevel")), + m_compressionAlgorithm(pset.getUntrackedParameter("compressionAlgorithm")), + m_writeProvenance(pset.getUntrackedParameter("saveProvenance", true)), + m_fakeName(pset.getUntrackedParameter("fakeNameForCrab", false)), + m_autoFlush(pset.getUntrackedParameter("autoFlush", -10000000)), + m_processHistoryRegistry() {} + +void NanoAODOutputModule::write(edm::EventForOutput const& iEvent) { //Get data from 'e' and write it to the file edm::Service jr; jr->eventWrittenToFile(m_jrToken, iEvent.id().run(), iEvent.id().event()); @@ -171,7 +169,7 @@ NanoAODOutputModule::write(edm::EventForOutput const& iEvent) { float percentClusterDone = m_firstFlush / static_cast(m_autoFlush); maxMemory = static_cast(m_tree->GetTotBytes()) / percentClusterDone; } else if (m_tree->GetZipBytes() == 0) { - maxMemory = 100*1024*1024; // Degenerate case of no information in the tree; arbitrary value + maxMemory = 100 * 1024 * 1024; // Degenerate case of no information in the tree; arbitrary value } else { // Estimate the memory we'll be using by scaling the current compression ratio. float cxnRatio = m_tree->GetTotBytes() / static_cast(m_tree->GetZipBytes()); @@ -230,16 +228,17 @@ NanoAODOutputModule::write(edm::EventForOutput const& iEvent) { m_triggers_areSorted = true; } // fill triggers - for (auto & t : m_triggers) t.fill(iEvent,*m_tree); + for (auto& t : m_triggers) + t.fill(iEvent, *m_tree); // fill event branches - for (auto & t : m_evstrings) t.fill(iEvent,*m_tree); + for (auto& t : m_evstrings) + t.fill(iEvent, *m_tree); m_tree->Fill(); m_processHistoryRegistry.registerProcessHistory(iEvent.processHistory()); } -void -NanoAODOutputModule::writeLuminosityBlock(edm::LuminosityBlockForOutput const& iLumi) { +void NanoAODOutputModule::writeLuminosityBlock(edm::LuminosityBlockForOutput const& iLumi) { edm::Service jr; jr->reportLumiSection(m_jrToken, iLumi.id().run(), iLumi.id().value()); @@ -249,24 +248,25 @@ NanoAODOutputModule::writeLuminosityBlock(edm::LuminosityBlockForOutput const& i m_processHistoryRegistry.registerProcessHistory(iLumi.processHistory()); } -void -NanoAODOutputModule::writeRun(edm::RunForOutput const& iRun) { +void NanoAODOutputModule::writeRun(edm::RunForOutput const& iRun) { edm::Service jr; jr->reportRunNumber(m_jrToken, iRun.id().run()); m_commonRunBranches.fill(iRun.id()); - for (auto & t : m_runTables) t.fill(iRun,*m_runTree); + for (auto& t : m_runTables) + t.fill(iRun, *m_runTree); edm::Handle hstring; - for (const auto & p : m_nanoMetadata) { + for (const auto& p : m_nanoMetadata) { iRun.getByToken(p.second, hstring); - TObjString *tos = dynamic_cast(m_file->Get(p.first.c_str())); + TObjString* tos = dynamic_cast(m_file->Get(p.first.c_str())); if (tos) { - if (hstring->str() != tos->GetString()) throw cms::Exception("LogicError", "Inconsistent nanoMetadata " + p.first + " (" + hstring->str() +")"); + if (hstring->str() != tos->GetString()) + throw cms::Exception("LogicError", "Inconsistent nanoMetadata " + p.first + " (" + hstring->str() + ")"); } else { - auto ostr = std::make_unique(hstring->str().c_str()); - m_file->WriteTObject(ostr.release(), p.first.c_str()); + auto ostr = std::make_unique(hstring->str().c_str()); + m_file->WriteTObject(ostr.release(), p.first.c_str()); } } @@ -275,35 +275,31 @@ NanoAODOutputModule::writeRun(edm::RunForOutput const& iRun) { m_processHistoryRegistry.registerProcessHistory(iRun.processHistory()); } -bool -NanoAODOutputModule::isFileOpen() const { - return nullptr != m_file.get(); -} +bool NanoAODOutputModule::isFileOpen() const { return nullptr != m_file.get(); } -void -NanoAODOutputModule::openFile(edm::FileBlock const&) { - m_file = std::make_unique(m_fileName.c_str(),"RECREATE","",m_compressionLevel); +void NanoAODOutputModule::openFile(edm::FileBlock const&) { + m_file = std::make_unique(m_fileName.c_str(), "RECREATE", "", m_compressionLevel); edm::Service jr; cms::Digest branchHash; m_jrToken = jr->outputFileOpened(m_fileName, m_logicalFileName, std::string(), - m_fakeName?"PoolOutputModule":"NanoAODOutputModule", + m_fakeName ? "PoolOutputModule" : "NanoAODOutputModule", description().moduleLabel(), edm::createGlobalIdentifier(), std::string(), branchHash.digest().toString(), - std::vector() - ); + std::vector()); if (m_compressionAlgorithm == std::string("ZLIB")) { - m_file->SetCompressionAlgorithm(ROOT::kZLIB); - } else if (m_compressionAlgorithm == std::string("LZMA")) { - m_file->SetCompressionAlgorithm(ROOT::kLZMA); - } else { - throw cms::Exception("Configuration") << "NanoAODOutputModule configured with unknown compression algorithm '" << m_compressionAlgorithm << "'\n" - << "Allowed compression algorithms are ZLIB and LZMA\n"; - } + m_file->SetCompressionAlgorithm(ROOT::kZLIB); + } else if (m_compressionAlgorithm == std::string("LZMA")) { + m_file->SetCompressionAlgorithm(ROOT::kLZMA); + } else { + throw cms::Exception("Configuration") + << "NanoAODOutputModule configured with unknown compression algorithm '" << m_compressionAlgorithm << "'\n" + << "Allowed compression algorithms are ZLIB and LZMA\n"; + } /* Setup file structure here */ m_tables.clear(); m_tableTokens.clear(); @@ -326,15 +322,16 @@ NanoAODOutputModule::openFile(edm::FileBlock const&) { throw cms::Exception("Configuration", "NanoAODOutputModule cannot handle class " + keep.first->className()); } - for (const auto & keep : keeps[edm::InRun]) { - if(keep.first->className() == "nanoaod::MergeableCounterTable" ) - m_runTables.push_back(SummaryTableOutputBranches(keep.first, keep.second)); - else if(keep.first->className() == "nanoaod::UniqueString" && keep.first->moduleLabel() == "nanoMetadata") - m_nanoMetadata.emplace_back(keep.first->productInstanceName(), keep.second); - else throw cms::Exception("Configuration", "NanoAODOutputModule cannot handle class " + keep.first->className() + " in Run branch"); + for (const auto& keep : keeps[edm::InRun]) { + if (keep.first->className() == "nanoaod::MergeableCounterTable") + m_runTables.push_back(SummaryTableOutputBranches(keep.first, keep.second)); + else if (keep.first->className() == "nanoaod::UniqueString" && keep.first->moduleLabel() == "nanoMetadata") + m_nanoMetadata.emplace_back(keep.first->productInstanceName(), keep.second); + else + throw cms::Exception("Configuration", + "NanoAODOutputModule cannot handle class " + keep.first->className() + " in Run branch"); } - // create the trees m_tree = std::make_unique("Events", "Events"); m_tree->SetAutoSave(0); @@ -348,7 +345,7 @@ NanoAODOutputModule::openFile(edm::FileBlock const&) { m_runTree = std::make_unique("Runs", "Runs"); m_runTree->SetAutoSave(0); m_commonRunBranches.branch(*m_runTree); - + if (m_writeProvenance) { m_metaDataTree = std::make_unique(edm::poolNames::metaDataTreeName().c_str(), "Job metadata"); m_metaDataTree->SetAutoSave(0); @@ -356,48 +353,46 @@ NanoAODOutputModule::openFile(edm::FileBlock const&) { m_parameterSetsTree->SetAutoSave(0); } } -void -NanoAODOutputModule::reallyCloseFile() { +void NanoAODOutputModule::reallyCloseFile() { if (m_writeProvenance) { - int basketSize = 16384; // fixme configurable? - edm::fillParameterSetBranch(m_parameterSetsTree.get(), basketSize); - edm::fillProcessHistoryBranch(m_metaDataTree.get(), basketSize, m_processHistoryRegistry); - if (m_metaDataTree->GetNbranches() != 0) { - m_metaDataTree->SetEntries(-1); - } - if (m_parameterSetsTree->GetNbranches() != 0) { - m_parameterSetsTree->SetEntries(-1); - } + int basketSize = 16384; // fixme configurable? + edm::fillParameterSetBranch(m_parameterSetsTree.get(), basketSize); + edm::fillProcessHistoryBranch(m_metaDataTree.get(), basketSize, m_processHistoryRegistry); + if (m_metaDataTree->GetNbranches() != 0) { + m_metaDataTree->SetEntries(-1); + } + if (m_parameterSetsTree->GetNbranches() != 0) { + m_parameterSetsTree->SetEntries(-1); + } } m_file->Write(); m_file->Close(); m_file.reset(); - m_tree.release(); // apparently root has ownership - m_lumiTree.release(); // - m_runTree.release(); // - m_metaDataTree.release(); // - m_parameterSetsTree.release(); // + m_tree.release(); // apparently root has ownership + m_lumiTree.release(); // + m_runTree.release(); // + m_metaDataTree.release(); // + m_parameterSetsTree.release(); // edm::Service jr; jr->outputFileClosed(m_jrToken); } -void -NanoAODOutputModule::fillDescriptions(edm::ConfigurationDescriptions& descriptions) { +void NanoAODOutputModule::fillDescriptions(edm::ConfigurationDescriptions& descriptions) { edm::ParameterSetDescription desc; desc.addUntracked("fileName"); - desc.addUntracked("logicalFileName",""); + desc.addUntracked("logicalFileName", ""); - desc.addUntracked("compressionLevel", 9) - ->setComment("ROOT compression level of output file."); + desc.addUntracked("compressionLevel", 9)->setComment("ROOT compression level of output file."); desc.addUntracked("compressionAlgorithm", "ZLIB") - ->setComment("Algorithm used to compress data in the ROOT output file, allowed values are ZLIB and LZMA"); + ->setComment("Algorithm used to compress data in the ROOT output file, allowed values are ZLIB and LZMA"); desc.addUntracked("saveProvenance", true) - ->setComment("Save process provenance information, e.g. for edmProvDump"); + ->setComment("Save process provenance information, e.g. for edmProvDump"); desc.addUntracked("fakeNameForCrab", false) - ->setComment("Change the OutputModule name in the fwk job report to fake PoolOutputModule. This is needed to run on cran (and publish) till crab is fixed"); - desc.addUntracked("autoFlush", -10000000) - ->setComment("Autoflush parameter for ROOT file"); + ->setComment( + "Change the OutputModule name in the fwk job report to fake PoolOutputModule. This is needed to run on cran " + "(and publish) till crab is fixed"); + desc.addUntracked("autoFlush", -10000000)->setComment("Autoflush parameter for ROOT file"); //replace with whatever you want to get from the EDM by default const std::vector keep = {"drop *", @@ -412,16 +407,13 @@ NanoAODOutputModule::fillDescriptions(edm::ConfigurationDescriptions& descriptio edm::ParameterSetDescription dataSet; dataSet.setAllowAnything(); desc.addUntracked("dataset", dataSet) - ->setComment("PSet is only used by Data Operations and not by this module."); - + ->setComment("PSet is only used by Data Operations and not by this module."); + edm::ParameterSetDescription branchSet; branchSet.setAllowAnything(); desc.add("branches", branchSet); - - descriptions.addDefault(desc); - } DEFINE_FWK_MODULE(NanoAODOutputModule); diff --git a/SimDataFormats/GeneratorProducts/interface/GenWeightProduct.h b/SimDataFormats/GeneratorProducts/interface/GenWeightProduct.h index 872ae29b65d9f..ed28a0dcd3d4f 100644 --- a/SimDataFormats/GeneratorProducts/interface/GenWeightProduct.h +++ b/SimDataFormats/GeneratorProducts/interface/GenWeightProduct.h @@ -31,7 +31,7 @@ class GenWeightProduct { void setNumWeightSets(int num) { weightsVector_.resize(num); } void addWeightSet() { weightsVector_.push_back({}); } void addWeight(double weight, int setEntry, int weightNum) { - if (weightsVector_.size() == 0 && setEntry == 0) + if (weightsVector_.empty() && setEntry == 0) addWeightSet(); if (static_cast(weightsVector_.size()) <= setEntry) throw std::domain_error("Out of range weight"); diff --git a/SimDataFormats/GeneratorProducts/interface/MEParamWeightGroupInfo.h b/SimDataFormats/GeneratorProducts/interface/MEParamWeightGroupInfo.h index 2ea53a8d32adb..2b6714b240542 100644 --- a/SimDataFormats/GeneratorProducts/interface/MEParamWeightGroupInfo.h +++ b/SimDataFormats/GeneratorProducts/interface/MEParamWeightGroupInfo.h @@ -12,9 +12,9 @@ namespace gen { weightType_ = WeightType::kMEParamWeights; } MEParamWeightGroupInfo(std::string header) : MEParamWeightGroupInfo(header, header) {} - virtual ~MEParamWeightGroupInfo() override {} + ~MEParamWeightGroupInfo() override {} void copy(const MEParamWeightGroupInfo& other); - virtual MEParamWeightGroupInfo* clone() const override; + MEParamWeightGroupInfo* clone() const override; int getCentralIndex() { return centralIdx; } int getVariationIndex(int sig) { return massValue.at(numSigma + sig).second; } double getVariationValue(int sig) { return massValue.at(numSigma + sig).first; } diff --git a/SimDataFormats/GeneratorProducts/interface/PartonShowerWeightGroupInfo.h b/SimDataFormats/GeneratorProducts/interface/PartonShowerWeightGroupInfo.h index 9c64d5ce849e2..a2652f6a9883e 100644 --- a/SimDataFormats/GeneratorProducts/interface/PartonShowerWeightGroupInfo.h +++ b/SimDataFormats/GeneratorProducts/interface/PartonShowerWeightGroupInfo.h @@ -6,7 +6,7 @@ #include "SimDataFormats/GeneratorProducts/interface/WeightGroupInfo.h" namespace gen { - enum class PSVarType { muR, cNS, con, def, red, alphaS}; + enum class PSVarType { muR, cNS, con, def, red, alphaS }; enum class PSSplittingType { combined, g2gg, x2xg, g2qq }; class PartonShowerWeightGroupInfo : public WeightGroupInfo { @@ -17,9 +17,9 @@ namespace gen { } PartonShowerWeightGroupInfo(std::string header) : PartonShowerWeightGroupInfo(header, header) {} PartonShowerWeightGroupInfo(const PartonShowerWeightGroupInfo &other) { copy(other); } - virtual ~PartonShowerWeightGroupInfo() override {} + ~PartonShowerWeightGroupInfo() override {} void copy(const PartonShowerWeightGroupInfo &other); - virtual PartonShowerWeightGroupInfo *clone() const override; + PartonShowerWeightGroupInfo *clone() const override; void setNameIsPythiaSyntax(bool isPythiaSyntax) { nameIsPythiaSyntax_ = isPythiaSyntax; } bool nameIsPythiaSyntax(bool isPythiaSyntax) const { return nameIsPythiaSyntax_; } int variationIndex(bool isISR, bool isUp, PSVarType variationType, PSSplittingType splittingType) const; diff --git a/SimDataFormats/GeneratorProducts/interface/PdfWeightGroupInfo.h b/SimDataFormats/GeneratorProducts/interface/PdfWeightGroupInfo.h index f04fb71ffa728..5c8214fa9eb35 100644 --- a/SimDataFormats/GeneratorProducts/interface/PdfWeightGroupInfo.h +++ b/SimDataFormats/GeneratorProducts/interface/PdfWeightGroupInfo.h @@ -34,9 +34,9 @@ namespace gen { } PdfWeightGroupInfo(std::string header) : WeightGroupInfo(header) { weightType_ = WeightType::kPdfWeights; } PdfWeightGroupInfo(const PdfWeightGroupInfo& other) { copy(other); } - virtual ~PdfWeightGroupInfo() override {} + ~PdfWeightGroupInfo() override {} void copy(const PdfWeightGroupInfo& other); - virtual PdfWeightGroupInfo* clone() const override; + PdfWeightGroupInfo* clone() const override; void setUncertaintyType(PdfUncertaintyType uncertaintyType) { uncertaintyType_ = uncertaintyType; } void setHasAlphasVariations(bool hasAlphasVars) { hasAlphasVars_ = hasAlphasVars; } diff --git a/SimDataFormats/GeneratorProducts/interface/ScaleWeightGroupInfo.h b/SimDataFormats/GeneratorProducts/interface/ScaleWeightGroupInfo.h index 31e8812ddf85c..0ba1672ce6731 100644 --- a/SimDataFormats/GeneratorProducts/interface/ScaleWeightGroupInfo.h +++ b/SimDataFormats/GeneratorProducts/interface/ScaleWeightGroupInfo.h @@ -42,9 +42,9 @@ namespace gen { } ScaleWeightGroupInfo(std::string header) : ScaleWeightGroupInfo(header, header) {} ScaleWeightGroupInfo(const ScaleWeightGroupInfo& other) { copy(other); } - virtual ~ScaleWeightGroupInfo() override {} + ~ScaleWeightGroupInfo() override {} void copy(const ScaleWeightGroupInfo& other); - virtual ScaleWeightGroupInfo* clone() const override; + ScaleWeightGroupInfo* clone() const override; bool containsCentralWeight() const { return containsCentral_; } void addContainedId(int globalIndex, std::string id, std::string label, float muR, float muF); bool isWellFormed() { return isWellFormed_ && hasAllWeights; } diff --git a/SimDataFormats/GeneratorProducts/interface/UnknownWeightGroupInfo.h b/SimDataFormats/GeneratorProducts/interface/UnknownWeightGroupInfo.h index d314b9ad40d8a..3513cc70841dc 100644 --- a/SimDataFormats/GeneratorProducts/interface/UnknownWeightGroupInfo.h +++ b/SimDataFormats/GeneratorProducts/interface/UnknownWeightGroupInfo.h @@ -15,9 +15,9 @@ namespace gen { weightType_ = WeightType::kUnknownWeights; isWellFormed_ = false; } - virtual ~UnknownWeightGroupInfo() override {} + ~UnknownWeightGroupInfo() override {} void copy(const UnknownWeightGroupInfo& other); - virtual UnknownWeightGroupInfo* clone() const override; + UnknownWeightGroupInfo* clone() const override; }; } // namespace gen diff --git a/SimDataFormats/GeneratorProducts/src/GenWeightInfoProduct.cc b/SimDataFormats/GeneratorProducts/src/GenWeightInfoProduct.cc index 23b63469354f2..f6bb6e5af5ade 100644 --- a/SimDataFormats/GeneratorProducts/src/GenWeightInfoProduct.cc +++ b/SimDataFormats/GeneratorProducts/src/GenWeightInfoProduct.cc @@ -58,12 +58,14 @@ std::optional GenWeightInfoProduct::pdfGroupWithIndexByLHA std::vector pdfGroups = weightGroupsAndIndicesByType(gen::WeightType::kPdfWeights); auto matchingPdfSet = std::find_if(pdfGroups.begin(), pdfGroups.end(), [lhaid](gen::WeightGroupData& data) { - auto pdfGroup = std::make_unique(*static_cast(data.group.release())); + auto pdfGroup = + std::make_unique(*static_cast(data.group.release())); return pdfGroup->containsLhapdfId(lhaid); }); - return matchingPdfSet == pdfGroups.end() ? std::nullopt : - std::optional({matchingPdfSet->index, std::move(matchingPdfSet->group)}); + return matchingPdfSet == pdfGroups.end() + ? std::nullopt + : std::optional({matchingPdfSet->index, std::move(matchingPdfSet->group)}); } std::vector GenWeightInfoProduct::pdfGroupsWithIndicesByLHAIDs( @@ -73,7 +75,8 @@ std::vector GenWeightInfoProduct::pdfGroupsWithIndicesByLH for (auto lhaid : lhaids) { auto matchingPdfSet = std::find_if(pdfGroups.begin(), pdfGroups.end(), [lhaid](gen::WeightGroupData& data) { - auto pdfGroup = std::make_unique(*static_cast(data.group.release())); + auto pdfGroup = + std::make_unique(*static_cast(data.group.release())); return pdfGroup->containsLhapdfId(lhaid); }); if (matchingPdfSet != pdfGroups.end()) { @@ -93,4 +96,6 @@ std::vector GenWeightInfoProduct::weightGroupIndicesByType(gen::WeightType return matchingGroupIndices; } -void GenWeightInfoProduct::addWeightGroupInfo(std::unique_ptr info) { weightGroupsInfo_.push_back(std::move(info)); } +void GenWeightInfoProduct::addWeightGroupInfo(std::unique_ptr info) { + weightGroupsInfo_.push_back(std::move(info)); +} diff --git a/SimDataFormats/GeneratorProducts/src/ScaleWeightGroupInfo.cc b/SimDataFormats/GeneratorProducts/src/ScaleWeightGroupInfo.cc index 99826e88d14b9..2e1bbc7f16d26 100644 --- a/SimDataFormats/GeneratorProducts/src/ScaleWeightGroupInfo.cc +++ b/SimDataFormats/GeneratorProducts/src/ScaleWeightGroupInfo.cc @@ -99,7 +99,7 @@ namespace gen { std::vector ScaleWeightGroupInfo::dynNames() const { std::vector returnVec; - for (auto item : dynNames_) { + for (const auto& item : dynNames_) { if (!item.empty()) returnVec.push_back(item); } diff --git a/SimDataFormats/GeneratorProducts/src/WeightGroupInfo.cc b/SimDataFormats/GeneratorProducts/src/WeightGroupInfo.cc index 8e199219435ac..edd383b15dac6 100644 --- a/SimDataFormats/GeneratorProducts/src/WeightGroupInfo.cc +++ b/SimDataFormats/GeneratorProducts/src/WeightGroupInfo.cc @@ -24,8 +24,8 @@ namespace gen { WeightMetaInfo WeightGroupInfo::weightMetaInfo(int weightEntry) const { return idsContained_.at(weightEntry); } WeightMetaInfo WeightGroupInfo::weightMetaInfoByGlobalIndex(std::string wgtId, int weightEntry) const { - if (wgtId.empty()) - wgtId = std::to_string(weightEntry); + if (wgtId.empty()) + wgtId = std::to_string(weightEntry); int entry = weightVectorEntry(wgtId, weightEntry); if (entry < 0 || entry >= static_cast(idsContained_.size())) throw std::range_error("Weight entry " + std::to_string(weightEntry) + " is not a member of group " + name_ + @@ -60,8 +60,8 @@ namespace gen { } void WeightGroupInfo::addContainedId(int weightEntry, std::string id, std::string label = "") { - if (id.empty()) - id = std::to_string(weightEntry); + if (id.empty()) + id = std::to_string(weightEntry); if (firstId_ == -1 || weightEntry < firstId_) { firstId_ = weightEntry; @@ -75,9 +75,9 @@ namespace gen { WeightMetaInfo info = {static_cast(weightEntry), localIndex, id, label}; // logic to insert for all cases e.g. inserting in the middle of the vector if (localIndex == idsContained_.size()) - idsContained_.emplace_back(info); + idsContained_.emplace_back(info); else - idsContained_.insert(idsContained_.begin() + localIndex, info); + idsContained_.insert(idsContained_.begin() + localIndex, info); } std::vector WeightGroupInfo::containedIds() const { return idsContained_; } @@ -85,8 +85,8 @@ namespace gen { bool WeightGroupInfo::indexInRange(int index) const { return (index <= lastId_ && index >= firstId_); } void WeightGroupInfo::cacheWeightIndicesByLabel() { - for (const auto& weight : idsContained_) - weightLabelsToIndices_[weight.label] = weight.localIndex; + for (const auto& weight : idsContained_) + weightLabelsToIndices_[weight.label] = weight.localIndex; } std::vector WeightGroupInfo::weightLabels() const { @@ -98,17 +98,17 @@ namespace gen { } int WeightGroupInfo::weightIndexFromLabel(std::string weightLabel) const { - if (!weightLabelsToIndices_.empty()) { - if (weightLabelsToIndices_.find(weightLabel) != weightLabelsToIndices_.end()) - return static_cast(weightLabelsToIndices_.at(weightLabel)); - return -1; - } - - auto it = std::find_if(idsContained_.begin(), idsContained_.end(), - [weightLabel](const auto& w) { return weightLabel == w.label; }); - if (it == idsContained_.end()) - return -1; - return std::distance(idsContained_.begin(), it); + if (!weightLabelsToIndices_.empty()) { + if (weightLabelsToIndices_.find(weightLabel) != weightLabelsToIndices_.end()) + return static_cast(weightLabelsToIndices_.at(weightLabel)); + return -1; + } + + auto it = std::find_if( + idsContained_.begin(), idsContained_.end(), [weightLabel](const auto& w) { return weightLabel == w.label; }); + if (it == idsContained_.end()) + return -1; + return std::distance(idsContained_.begin(), it); } } // namespace gen