diff --git a/opm/models/blackoil/blackoilmicpmodules.hh b/opm/models/blackoil/blackoilmicpmodules.hh index 630191b095..88d4155757 100644 --- a/opm/models/blackoil/blackoilmicpmodules.hh +++ b/opm/models/blackoil/blackoilmicpmodules.hh @@ -35,7 +35,7 @@ #include -#include +#include #include namespace Opm { @@ -230,10 +230,10 @@ public: if constexpr (enableMICP) { const auto& velocityInf = problem.model().linearizer().getVelocityInfo(); auto velocityInfos = velocityInf[globalSpaceIdex]; - Scalar normVelocityCell = 0.0; - for (const auto& velocityInfo : velocityInfos) { - normVelocityCell = max(normVelocityCell, std::abs(velocityInfo.velocity[waterPhaseIdx])); - } + const Scalar normVelocityCell = + std::accumulate(velocityInfos.begin(), velocityInfos.end(), 0.0, + [](const auto acc, const auto& info) + { return max(acc, std::abs(info.velocity[waterPhaseIdx])); }); // get the model parameters const auto b = intQuants.fluidState().invB(waterPhaseIdx); diff --git a/opm/models/parallel/mpiutil.cpp b/opm/models/parallel/mpiutil.cpp index e6f966dc38..c8ee6d169b 100644 --- a/opm/models/parallel/mpiutil.cpp +++ b/opm/models/parallel/mpiutil.cpp @@ -76,22 +76,23 @@ struct Packer static void pack(const std::string& content, std::vector& buf, int& offset) { - unsigned int size = content.size(); - Packer::pack(size, buf, offset); - if (size > 0) { - MPI_Pack(const_cast(content.c_str()), size, MPI_CHAR, buf.data(), buf.size(), &offset, MPI_COMM_WORLD); + unsigned int sz = content.size(); + Packer::pack(sz, buf, offset); + if (sz > 0) { + MPI_Pack(const_cast(content.c_str()), sz, MPI_CHAR, + buf.data(), buf.size(), &offset, MPI_COMM_WORLD); } } static std::string unpack(const std::vector& recv_buffer, int& offset) { - unsigned int size = Packer::unpack(recv_buffer, offset); + unsigned int sz = Packer::unpack(recv_buffer, offset); std::string text; - if (size > 0) { + if (sz > 0) { auto* data = const_cast(recv_buffer.data()); - std::vector chars(size); - MPI_Unpack(data, recv_buffer.size(), &offset, chars.data(), size, MPI_CHAR, MPI_COMM_WORLD); - text = std::string(chars.data(), size); + std::vector chars(sz); + MPI_Unpack(data, recv_buffer.size(), &offset, chars.data(), sz, MPI_CHAR, MPI_COMM_WORLD); + text = std::string(chars.data(), sz); } return text; } @@ -103,18 +104,15 @@ struct Packer> { static int size(const std::string& content) { - int sz = 0; - sz += packSize(); - for (const T& elem : content) { - sz += Packer::size(elem); - } - return sz; + return std::accumulate(content.begin(), content.end(), packSize(), + [](const auto acc, const auto elem) + { return acc + Packer::size(elem); }); } static void pack(const std::vector& content, std::vector& buf, int& offset) { - unsigned int size = content.size(); - Packer::pack(size, buf, offset); + unsigned int sz = content.size(); + Packer::pack(sz, buf, offset); for (const T& elem : content) { Packer::pack(elem); } @@ -122,10 +120,10 @@ struct Packer> static std::vector unpack(const std::vector& recv_buffer, int& offset) { - unsigned int size = Packer::unpack(recv_buffer, offset); + unsigned int sz = Packer::unpack(recv_buffer, offset); std::vector content; - content.reserve(size); - for (unsigned int i = 0; i < size; ++i) { + content.reserve(sz); + for (unsigned int i = 0; i < sz; ++i) { content.push_back(Packer::unpack(recv_buffer, offset)); } return content; diff --git a/opm/models/utils/parametersystem.cpp b/opm/models/utils/parametersystem.cpp index 4fb0b55983..d873266577 100644 --- a/opm/models/utils/parametersystem.cpp +++ b/opm/models/utils/parametersystem.cpp @@ -41,6 +41,7 @@ #include #endif +#include #include #include #include @@ -99,9 +100,9 @@ private: struct Storage_ { Storage_() + : tree(std::make_unique()) + , registrationOpen(true) { - tree = std::make_unique(); - registrationOpen = true; } std::unique_ptr tree; @@ -212,7 +213,7 @@ void printParamList(std::ostream& os, void printParamUsage(std::ostream& os, const ParamInfo& paramInfo) { - std::string paramMessage, paramType, paramDescription; + std::string paramMessage; int ttyWidth = Opm::getTtyWidth(); @@ -668,8 +669,6 @@ std::string parseCommandLineOptions(int argc, argc, argv, i, numPositionalParams); if (numHandled < 1) { - std::ostringstream oss; - if (!helpPreamble.empty()) { printUsage(helpPreamble, std::cerr, errorMsg); } @@ -794,14 +793,14 @@ bool printUnused(std::ostream& os) std::vector unknownKeyList; getFlattenedKeyList(runTimeAllKeyList, MetaData::tree()); - for (const auto& key : runTimeAllKeyList) { - if (MetaData::registry().find(key) == MetaData::registry().end()) { - // key was not registered by the program! - unknownKeyList.push_back(key); - } - } + std::copy_if(runTimeAllKeyList.begin(), runTimeAllKeyList.end(), + std::back_inserter(unknownKeyList), + [](const auto& key) + { + return MetaData::registry().find(key) == MetaData::registry().end(); + }); - if (unknownKeyList.size() > 0) { + if (!unknownKeyList.empty()) { os << "# [unused run-time specified parameters]\n"; for (const auto& unused : unknownKeyList) { os << unused << "=\"" diff --git a/opm/simulators/flow/BlackoilModelNldd.hpp b/opm/simulators/flow/BlackoilModelNldd.hpp index 16dd6189c8..095a50180c 100644 --- a/opm/simulators/flow/BlackoilModelNldd.hpp +++ b/opm/simulators/flow/BlackoilModelNldd.hpp @@ -62,6 +62,7 @@ #include #include #include +#include #include #include #include @@ -856,10 +857,10 @@ private: case DomainOrderingMeasure::AveragePressure: { // Use average pressures to order domains. for (const auto& domain : domains_) { - Scalar press_sum = 0.0; - for (const int c : domain.cells) { - press_sum += solution[c][Indices::pressureSwitchIdx]; - } + const Scalar press_sum = + std::accumulate(domain.cells.begin(), domain.cells.end(), Scalar{0}, + [&solution](const auto acc, const auto c) + { return acc + solution[c][Indices::pressureSwitchIdx]; }); const Scalar avgpress = press_sum / domain.cells.size(); measure_per_domain[domain.index] = avgpress; } @@ -868,11 +869,10 @@ private: case DomainOrderingMeasure::MaxPressure: { // Use max pressures to order domains. for (const auto& domain : domains_) { - Scalar maxpress = 0.0; - for (const int c : domain.cells) { - maxpress = std::max(maxpress, solution[c][Indices::pressureSwitchIdx]); - } - measure_per_domain[domain.index] = maxpress; + measure_per_domain[domain.index] = + std::accumulate(domain.cells.begin(), domain.cells.end(), Scalar{0}, + [&solution](const auto acc, const auto c) + { return std::max(acc, solution[c][Indices::pressureSwitchIdx]); }); } break; } diff --git a/opm/simulators/flow/FlowGenericProblem_impl.hpp b/opm/simulators/flow/FlowGenericProblem_impl.hpp index ac2850f3ed..f50daa4422 100644 --- a/opm/simulators/flow/FlowGenericProblem_impl.hpp +++ b/opm/simulators/flow/FlowGenericProblem_impl.hpp @@ -139,10 +139,12 @@ readRockParameters_(const std::vector& cellCenterDepths, { const auto& comp = rock_config.comp(); rockParams_.clear(); - for (const auto& c : comp) { - rockParams_.push_back({static_cast(c.pref), - static_cast(c.compressibility)}); - } + std::transform(comp.begin(), comp.end(), std::back_inserter(rockParams_), + [](const auto& c) + { + return RockParams{static_cast(c.pref), + static_cast(c.compressibility)}; + }); } // Warn that ROCK and ROCKOPTS item 2 = STORE is used together diff --git a/opm/simulators/flow/FlowGenericVanguard.cpp b/opm/simulators/flow/FlowGenericVanguard.cpp index b9995da38f..56cfb6ee1f 100644 --- a/opm/simulators/flow/FlowGenericVanguard.cpp +++ b/opm/simulators/flow/FlowGenericVanguard.cpp @@ -93,6 +93,7 @@ #include #endif // HAVE_MPI +#include #include #include @@ -343,10 +344,8 @@ void FlowGenericVanguard::init() if (comm.rank() == 0) { const auto& wells = this->schedule().getWellsatEnd(); - for (const auto& well : wells) - { - hasMsWell = hasMsWell || well.isMultiSegment(); - } + hasMsWell = std::any_of(wells.begin(), wells.end(), + [](const auto& well) { return well.isMultiSegment(); }); } } @@ -368,14 +367,12 @@ void FlowGenericVanguard::init() bool FlowGenericVanguard::drsdtconEnabled() const { - for (const auto& schIt : this->schedule()) { - const auto& oilVaporizationControl = schIt.oilvap(); - if (oilVaporizationControl.getType() == OilVaporizationProperties::OilVaporization::DRSDTCON) { - return true; - } - } - - return false; + return std::any_of(this->schedule().begin(), this->schedule().end(), + [](const auto& schIt) + { + return schIt.oilvap().getType() == + OilVaporizationProperties::OilVaporization::DRSDTCON; + }); } std::unordered_map diff --git a/opm/simulators/flow/FlowProblemBlackoil.hpp b/opm/simulators/flow/FlowProblemBlackoil.hpp index 5c23784a7c..59c301503c 100644 --- a/opm/simulators/flow/FlowProblemBlackoil.hpp +++ b/opm/simulators/flow/FlowProblemBlackoil.hpp @@ -346,9 +346,8 @@ public: { std::array coords; simulator.vanguard().cartesianCoordinate(idx, coords); - for (auto& c : coords) { - ++c; - } + std::transform(coords.begin(), coords.end(), coords.begin(), + [](const auto c) { return c + 1; }); return coords; }); diff --git a/opm/simulators/flow/FlowProblemComp.hpp b/opm/simulators/flow/FlowProblemComp.hpp index fc561849a9..796d53b042 100644 --- a/opm/simulators/flow/FlowProblemComp.hpp +++ b/opm/simulators/flow/FlowProblemComp.hpp @@ -196,9 +196,8 @@ public: this->readRockParameters_(simulator.vanguard().cellCenterDepths(), [&simulator](const unsigned idx) { std::array coords; simulator.vanguard().cartesianCoordinate(idx, coords); - for (auto& c : coords) { - ++c; - } + std::transform(coords.begin(), coords.end(), coords.begin(), + [](const auto c) { return c + 1; }); return coords; }); FlowProblemType::readMaterialParameters_(); diff --git a/opm/simulators/flow/GenericCpGridVanguard.cpp b/opm/simulators/flow/GenericCpGridVanguard.cpp index 03bf389aeb..88c9800c64 100644 --- a/opm/simulators/flow/GenericCpGridVanguard.cpp +++ b/opm/simulators/flow/GenericCpGridVanguard.cpp @@ -470,17 +470,21 @@ void GenericCpGridVanguard::doCreateGrids_(Eclips if (isRoot) { const auto& active_porv = eclState.fieldProps().porv(false); const auto& unit_system = eclState.getUnits(); - const auto& volume_unit = unit_system.name( UnitSystem::measure::volume); - double total_pore_volume = unit_system.from_si( UnitSystem::measure::volume, std::accumulate(active_porv.begin(), active_porv.end(), 0.0)); - OpmLog::info(fmt::format("Total number of active cells: {} / total pore volume: {:0.0f} {}", grid_->numCells(), total_pore_volume , volume_unit)); + const auto& volume_unit = unit_system.name(UnitSystem::measure::volume); + double total_pore_volume = unit_system.from_si(UnitSystem::measure::volume, + std::accumulate(active_porv.begin(), active_porv.end(), 0.0)); + OpmLog::info(fmt::format("Total number of active cells: {} / total pore volume: {:0.0f} {}", + grid_->numCells(), total_pore_volume , volume_unit)); - double removed_pore_volume = 0; - for (const auto& global_index : removed_cells) - removed_pore_volume += active_porv[ eclState.getInputGrid().activeIndex(global_index) ]; + double removed_pore_volume = + std::accumulate(removed_cells.begin(), removed_cells.end(), 0.0, + [&active_porv, &eclState](const auto acc, const auto global_index) + { return acc + active_porv[eclState.getInputGrid().activeIndex(global_index)]; }); if (removed_pore_volume > 0) { - removed_pore_volume = unit_system.from_si( UnitSystem::measure::volume, removed_pore_volume ); - OpmLog::info(fmt::format("Removed {} cells with a pore volume of {:0.0f} {} ({:5.3f} %) due to MINPV/MINPVV", + removed_pore_volume = unit_system.from_si(UnitSystem::measure::volume, removed_pore_volume); + OpmLog::info(fmt::format("Removed {} cells with a pore volume of {:0.0f} " + "{} ({:5.3f} %) due to MINPV/MINPVV", removed_cells.size(), removed_pore_volume, volume_unit, diff --git a/opm/simulators/flow/GenericOutputBlackoilModule.cpp b/opm/simulators/flow/GenericOutputBlackoilModule.cpp index d9ed173939..7a6f3ad769 100644 --- a/opm/simulators/flow/GenericOutputBlackoilModule.cpp +++ b/opm/simulators/flow/GenericOutputBlackoilModule.cpp @@ -76,12 +76,13 @@ namespace { defineInterRegionFlowArrays(const Opm::EclipseState& eclState, const Opm::SummaryConfig& summaryConfig) { - auto regions = std::vector{}; - - const auto& fprops = eclState.fieldProps(); - for (const auto& arrayName : summaryConfig.fip_regions_interreg_flow()) { - regions.push_back({ arrayName, std::cref(fprops.get_int(arrayName)) }); - } + using SRegion = Opm::InterRegFlowMap::SingleRegion; + auto regions = std::vector{}; + const auto fip_regions = summaryConfig.fip_regions_interreg_flow(); + std::transform(fip_regions.begin(), fip_regions.end(), + std::back_inserter(regions), + [&fprops = eclState.fieldProps()](const auto& arrayName) + { return SRegion{arrayName, std::cref(fprops.get_int(arrayName))}; }); return regions; } diff --git a/opm/simulators/flow/InterRegFlows.cpp b/opm/simulators/flow/InterRegFlows.cpp index d7db02e720..905ea3b47d 100644 --- a/opm/simulators/flow/InterRegFlows.cpp +++ b/opm/simulators/flow/InterRegFlows.cpp @@ -190,9 +190,11 @@ Opm::InterRegFlowMap::getInterRegFlows() const auto maps = std::vector{}; maps.reserve(this->regionMaps_.size()); - for (const auto& regionMap : this->regionMaps_) { - maps.push_back(regionMap.getInterRegFlows()); - } + std::transform(this->regionMaps_.begin(), + this->regionMaps_.end(), + std::back_inserter(maps), + [](const auto& regionMap) + { return regionMap.getInterRegFlows(); }); return maps; } @@ -203,9 +205,11 @@ Opm::InterRegFlowMap::getLocalMaxRegionID() const auto maxLocalRegionID = std::vector{}; maxLocalRegionID.reserve(this->regionMaps_.size()); - for (const auto& regionMap : this->regionMaps_) { - maxLocalRegionID.push_back(regionMap.getLocalMaxRegionID()); - } + std::transform(this->regionMaps_.begin(), + this->regionMaps_.end(), + std::back_inserter(maxLocalRegionID), + [](const auto& regionMap) + { return regionMap.getLocalMaxRegionID(); }); return maxLocalRegionID; } diff --git a/opm/simulators/flow/KeywordValidation.hpp b/opm/simulators/flow/KeywordValidation.hpp index cff1210a58..00d8a71a6e 100644 --- a/opm/simulators/flow/KeywordValidation.hpp +++ b/opm/simulators/flow/KeywordValidation.hpp @@ -156,9 +156,9 @@ struct SupportedKeywords { public: allow_values(const std::initializer_list& allowed_values) { - for (auto item : allowed_values) { - m_allowed_values.push_back(item); - } + std::copy(allowed_values.begin(), + allowed_values.end(), + std::back_inserter(m_allowed_values)); } bool operator()(const T& value) const diff --git a/opm/simulators/flow/NonlinearSolver.cpp b/opm/simulators/flow/NonlinearSolver.cpp index 03915ade21..585c1673be 100644 --- a/opm/simulators/flow/NonlinearSolver.cpp +++ b/opm/simulators/flow/NonlinearSolver.cpp @@ -82,9 +82,8 @@ void stabilizeNonlinearUpdate(BVector& dx, BVector& dxOld, if (omega == 1.) { return; } - for (auto& d : dx) { - d *= omega; - } + std::transform(dx.begin(), dx.end(), dx.begin(), + [omega](const auto d) { return d*omega; }); return; } case NonlinearRelaxType::SOR: { diff --git a/opm/simulators/flow/ReservoirCouplingSpawnSlaves.cpp b/opm/simulators/flow/ReservoirCouplingSpawnSlaves.cpp index 93d4f14717..12c7dad13d 100644 --- a/opm/simulators/flow/ReservoirCouplingSpawnSlaves.cpp +++ b/opm/simulators/flow/ReservoirCouplingSpawnSlaves.cpp @@ -261,9 +261,7 @@ serializeStrings_(std::vector data) const std::size_t total_size = 0; std::vector serialized_data; for (const auto& str: data) { - for (const auto& c: str) { - serialized_data.push_back(c); - } + std::copy(str.begin(), str.end(), std::back_inserter(serialized_data)); serialized_data.push_back('\0'); total_size += str.size() + 1; } diff --git a/opm/simulators/flow/partitionCells.cpp b/opm/simulators/flow/partitionCells.cpp index 597b1b1338..c51856ed05 100644 --- a/opm/simulators/flow/partitionCells.cpp +++ b/opm/simulators/flow/partitionCells.cpp @@ -251,11 +251,10 @@ void ZoltanPartitioner::connectNeighbors(std::vector& cells, // Expand current frontier using precomputed neighbor map for (const int cell : frontier) { - for (const int neighbor : neighbor_map_.at(cell)) { - if (visited.insert(neighbor).second) { // New discovery - new_frontier.push_back(neighbor); - } - } + const auto& nmap = neighbor_map_.at(cell); + std::copy_if(nmap.begin(), nmap.end(), std::back_inserter(new_frontier), + [&visited](const auto& neighbor) + { return visited.insert(neighbor).second; }); } frontier.swap(new_frontier); // Prepare next level @@ -507,9 +506,8 @@ namespace { comm.broadcast(startPtr.data(), comm.size() + 1, 0); // We're scattering two ints per cell - for (auto& startIx : startPtr) { - startIx *= 2; - } + std::transform(startPtr.begin(), startPtr.end(), startPtr.begin(), + [](const auto startIx) { return startIx * 2; }); auto sendLength = std::vector(comm.size()); std::adjacent_difference(startPtr.begin() + 1, diff --git a/opm/simulators/linalg/MILU.cpp b/opm/simulators/linalg/MILU.cpp index 84643b1a7e..ee86302a1e 100644 --- a/opm/simulators/linalg/MILU.cpp +++ b/opm/simulators/linalg/MILU.cpp @@ -20,17 +20,19 @@ #include #include -#include + #include #include #include #include #include +#include #include #include +#include template T Opm::detail::identityFunctor(const T& t){return t;}; @@ -216,10 +218,8 @@ void milun_decomposition(const M& A, int n, MILU_VARIANT milu, M& ILU, { auto& newRow = ILU[ordering[iter.index()]]; // reset stored generation - for ( auto& col: newRow) - { - col = 0; - } + std::fill(newRow.begin(), newRow.end(), 0); + // copy row. for(auto col = iter->begin(), cend = iter->end(); col != cend; ++col) { diff --git a/opm/simulators/linalg/PropertyTree.cpp b/opm/simulators/linalg/PropertyTree.cpp index d52dd0d11b..94ff903466 100644 --- a/opm/simulators/linalg/PropertyTree.cpp +++ b/opm/simulators/linalg/PropertyTree.cpp @@ -108,9 +108,10 @@ PropertyTree::get_child_items_as_vector(const std::string& child) const } items.emplace(); - for (const auto& childItem : *subTree) { - items->push_back(childItem.second.template get_value()); - } + std::transform(subTree->begin(), subTree->end(), + std::back_inserter(*items), + [](const auto& childItem) + { return childItem.second.template get_value(); }); return items; } diff --git a/opm/simulators/timestepping/gatherConvergenceReport.cpp b/opm/simulators/timestepping/gatherConvergenceReport.cpp index 470fbdfab6..8d0705e227 100644 --- a/opm/simulators/timestepping/gatherConvergenceReport.cpp +++ b/opm/simulators/timestepping/gatherConvergenceReport.cpp @@ -154,9 +154,9 @@ namespace Opm const auto rankReports = CollectConvReports { packer, mpi_communicator }(local_report); - for (const auto& rankReport : rankReports) { - combinedReport += rankReport; - } + std::for_each(rankReports.begin(), rankReports.end(), + [&combinedReport](const auto& rankReport) + { combinedReport += rankReport; }); return combinedReport; } diff --git a/opm/simulators/utils/GridDataOutput_impl.hpp b/opm/simulators/utils/GridDataOutput_impl.hpp index 3b4b629123..022d5fe3a6 100644 --- a/opm/simulators/utils/GridDataOutput_impl.hpp +++ b/opm/simulators/utils/GridDataOutput_impl.hpp @@ -23,6 +23,7 @@ #include +#include #include #include #include @@ -44,13 +45,10 @@ SimMeshDataAccessor:: template bool SimMeshDataAccessor::polyhedralCellPresent() const { - for (const auto& cit : elements(gridView_, dunePartition_)) { - auto corner_geom = cit.geometry(); - if (Dune::VTK::geometryType(corner_geom.type()) == Dune::VTK::polyhedron) { - return true; - } - } - return false; + const auto& elems = elements(gridView_, dunePartition_); + return std::any_of(elems.begin(), elems.end(), + [](const auto& cit) + { return Dune::VTK::geometryType(cit.geometry().type()) == Dune::VTK::polyhedron; }); } template diff --git a/opm/simulators/utils/compressPartition.cpp b/opm/simulators/utils/compressPartition.cpp index c7b84ae179..4be535d1ce 100644 --- a/opm/simulators/utils/compressPartition.cpp +++ b/opm/simulators/utils/compressPartition.cpp @@ -20,7 +20,6 @@ #include #include -#include #include #include @@ -51,11 +50,13 @@ namespace { } } - for (auto& domain : partition) { - if (domain >= 0) { - domain = compressed[domain - low]; - } - } + std::for_each(partition.begin(), partition.end(), + [Low = low, &compressed](auto& domain) + { + if (domain >= 0) { + domain = compressed[domain - Low]; + } + }); } } // Anonymous namespace diff --git a/opm/simulators/wells/BlackoilWellModelGasLift_impl.hpp b/opm/simulators/wells/BlackoilWellModelGasLift_impl.hpp index a2c148c97c..9463a9a24a 100644 --- a/opm/simulators/wells/BlackoilWellModelGasLift_impl.hpp +++ b/opm/simulators/wells/BlackoilWellModelGasLift_impl.hpp @@ -118,9 +118,10 @@ maybeDoGasLiftOptimize(const Simulator& simulator, if constexpr (glift_debug) { std::vector*> wc; wc.reserve(well_container.size()); - for (const auto& w : well_container) { - wc.push_back(static_cast*>(w.get())); - } + std::transform(well_container.begin(), well_container.end(), + std::back_inserter(wc), + [](const auto& w) + { return static_cast*>(w.get()); }); this->gliftDebugShowALQ(wc, wellState, deferred_logger); diff --git a/opm/simulators/wells/BlackoilWellModelGeneric.cpp b/opm/simulators/wells/BlackoilWellModelGeneric.cpp index b4d6c5e60e..c625221b91 100644 --- a/opm/simulators/wells/BlackoilWellModelGeneric.cpp +++ b/opm/simulators/wells/BlackoilWellModelGeneric.cpp @@ -192,12 +192,8 @@ template bool BlackoilWellModelGeneric:: anyMSWellOpenLocal() const { - for (const auto& well : wells_ecl_) { - if (well.isMultiSegment()) { - return true; - } - } - return false; + return std::any_of(wells_ecl_.begin(), wells_ecl_.end(), + [](const auto& well) { return well.isMultiSegment(); }); } template @@ -1455,25 +1451,33 @@ forceShutWellByName(const std::string& wellname, // Only add the well to the closed list on the // process that owns it. int well_was_shut = 0; - for (const auto& well : well_container_generic_) { - if (well->name() == wellname) { - // if one well on individuel control (typical thp/bhp) in a group strugles to converge - // it may lead to problems for the other wells in the group - // we dont want to shut all the wells in a group only the one creating the problems. - const auto& ws = this->wellState().well(well->indexOfWell()); - if (dont_shut_grup_wells) { - if (well->isInjector()) { - if (ws.injection_cmode == Well::InjectorCMode::GRUP) - continue; - } else { - if (ws.production_cmode == Well::ProducerCMode::GRUP) - continue; - } - } - wellTestState().close_well(wellname, WellTestConfig::Reason::PHYSICAL, simulation_time); - well_was_shut = 1; - break; - } + const auto it = std::find_if(well_container_generic_.begin(), + well_container_generic_.end(), + [&wellname, &wState = this->wellState(), dont_shut_grup_wells](const auto& well) + { + if (well->name() == wellname) { + // if one well on individual control (typical thp/bhp) + // in a group struggles to converge + // it may lead to problems for the other wells in the group + // we dont want to shut all the wells in a group only the one + // creating the problems. + if (dont_shut_grup_wells) { + const auto& ws = wState.well(well->indexOfWell()); + if (well->isInjector()) { + return ws.injection_cmode != Well::InjectorCMode::GRUP; + } else { + return ws.production_cmode != Well::ProducerCMode::GRUP; + } + } + return true; + } + else { + return false; + } + }); + if (it != well_container_generic_.end()) { + wellTestState().close_well(wellname, WellTestConfig::Reason::PHYSICAL, simulation_time); + well_was_shut = 1; } // Communicate across processes if a well was shut. diff --git a/opm/simulators/wells/BlackoilWellModel_impl.hpp b/opm/simulators/wells/BlackoilWellModel_impl.hpp index c275eb35cf..7436422ddc 100644 --- a/opm/simulators/wells/BlackoilWellModel_impl.hpp +++ b/opm/simulators/wells/BlackoilWellModel_impl.hpp @@ -2177,11 +2177,10 @@ namespace Opm { // compute global average grid.comm().sum(B_avg.data(), B_avg.size()); - for (auto& bval : B_avg) - { - bval /= global_num_cells_; - } - B_avg_ = B_avg; + B_avg_.resize(B_avg.size()); + std::transform(B_avg.begin(), B_avg.end(), B_avg_.begin(), + [gcells = global_num_cells_](const auto bval) + { return bval / gcells; }); } diff --git a/opm/simulators/wells/GasLiftGroupInfo.cpp b/opm/simulators/wells/GasLiftGroupInfo.cpp index 5fc09ad606..dc260a271f 100644 --- a/opm/simulators/wells/GasLiftGroupInfo.cpp +++ b/opm/simulators/wells/GasLiftGroupInfo.cpp @@ -687,9 +687,9 @@ initializeWell2GroupMapRecursive_(const Group& group, { Scalar gfac = group.getGroupEfficiencyFactor(); cur_efficiency = gfac * cur_efficiency; - for (auto &item : group_efficiency) { - item *= gfac; - } + std::transform(group_efficiency.begin(), group_efficiency.end(), + group_efficiency.begin(), + [gfac](const auto& item) { return item * gfac; }); if (this->group_rate_map_.count(group.name()) == 1) { // extract the subset of groups that has limits or targets that can affect // gas lift optimization. diff --git a/opm/simulators/wells/GasLiftSingleWell_impl.hpp b/opm/simulators/wells/GasLiftSingleWell_impl.hpp index 14875bf939..51c35a5589 100644 --- a/opm/simulators/wells/GasLiftSingleWell_impl.hpp +++ b/opm/simulators/wells/GasLiftSingleWell_impl.hpp @@ -26,6 +26,8 @@ #include #endif +#include + #include #include @@ -128,9 +130,10 @@ computeWellRates_(Scalar bhp, bool bhp_is_limited, bool debug_output ) const this->displayDebugMessage_(msg); } - for (auto& potential : potentials) { - potential = std::min(Scalar{0.0}, potential); - } + std::transform(potentials.begin(), potentials.end(), + potentials.begin(), + [](const auto& potential) + { return std::min(Scalar{0}, potential); }); return {-potentials[this->oil_pos_], -potentials[this->gas_pos_], -potentials[this->water_pos_], diff --git a/opm/simulators/wells/GasLiftStage2.cpp b/opm/simulators/wells/GasLiftStage2.cpp index 018ff49ca8..5a832ff678 100644 --- a/opm/simulators/wells/GasLiftStage2.cpp +++ b/opm/simulators/wells/GasLiftStage2.cpp @@ -18,9 +18,10 @@ */ #include -#include #include +#include + #include #include @@ -32,12 +33,13 @@ #include #include -#include - +#include #include #include #include +#include + namespace Opm { template @@ -791,15 +793,17 @@ updateGradVector_(const std::string& name, std::vector& grads, Scalar grad) { - for (auto itr = grads.begin(); itr != grads.end(); itr++) { - if (itr->first == name) { - itr->second = grad; - return; - } + auto it = std::find_if(grads.begin(), grads.end(), + [&name](const auto& itr) + { return itr.first == name; }); + if (it != grads.end()) { + it->second = grad; + } + else { + grads.push_back({name, grad}); + // NOTE: the gradient vector is no longer sorted, but sorting will be done + // later in getEcoGradients() } - grads.push_back({name, grad}); - // NOTE: the gradient vector is no longer sorted, but sorting will be done - // later in getEcoGradients() } diff --git a/opm/simulators/wells/GroupState.hpp b/opm/simulators/wells/GroupState.hpp index 41cc270bd5..2e5da37ee5 100644 --- a/opm/simulators/wells/GroupState.hpp +++ b/opm/simulators/wells/GroupState.hpp @@ -155,13 +155,13 @@ public: // That the collect function mutates the vector v is an artifact for // testing. - auto collect = [&data, &pos](auto& v) { + auto doCollect = [&data, &pos](auto& v) { for (auto& x : v) { data[pos++] = x; x = -1; } }; - forAllGroupData(collect); + forAllGroupData(doCollect); for (const auto& x : this->inj_vrep_rate) { data[pos++] = x.second; } @@ -173,12 +173,11 @@ public: // Distribute the summed vector to the data items. pos = 0; - auto distribute = [&data, &pos](auto& v) { - for (auto& x : v) { - x = data[pos++]; - } + auto doDistribute = [&data, &pos](auto& v) { + std::copy_n(data.begin() + pos, v.size(), v.begin()); + pos += v.size(); }; - forAllGroupData(distribute); + forAllGroupData(doDistribute); for (auto& x : this->inj_vrep_rate) { x.second = data[pos++]; } diff --git a/opm/simulators/wells/MultisegmentWellEquations.cpp b/opm/simulators/wells/MultisegmentWellEquations.cpp index aaa8527e90..a3f6598efe 100644 --- a/opm/simulators/wells/MultisegmentWellEquations.cpp +++ b/opm/simulators/wells/MultisegmentWellEquations.cpp @@ -42,6 +42,7 @@ #include #include +#include #include namespace Opm { @@ -73,10 +74,10 @@ init(const int numPerfs, // calculating the NNZ for duneD_ // NNZ = number_of_segments + 2 * (number_of_inlets / number_of_outlets) { - int nnz_d = well_.numberOfSegments(); - for (const std::vector& inlets : segment_inlets) { - nnz_d += 2 * inlets.size(); - } + const int nnz_d = std::accumulate(segment_inlets.begin(), segment_inlets.end(), + well_.numberOfSegments(), + [](const auto acc, const auto& inlets) + { return acc + 2 * inlets.size(); }); duneD_.setSize(well_.numberOfSegments(), well_.numberOfSegments(), nnz_d); } duneB_.setSize(well_.numberOfSegments(), numPerfs, numPerfs); diff --git a/opm/simulators/wells/RateConverter.cpp b/opm/simulators/wells/RateConverter.cpp index 23ae600caa..558fac37d3 100644 --- a/opm/simulators/wells/RateConverter.cpp +++ b/opm/simulators/wells/RateConverter.cpp @@ -81,8 +81,8 @@ sumRates(std::unordered_map& attributes_hpv, assert(ra.pv > 0.); } const Scalar pv_sum = ra.pv; - for (Scalar & d : ra.data) - d /= pv_sum; + std::transform(ra.data.begin(), ra.data.end(), ra.data.begin(), + [pv_sum](const auto d) { return d / pv_sum; }); ra.pv = pv_sum; } } diff --git a/opm/simulators/wells/RegionAverageCalculator.hpp b/opm/simulators/wells/RegionAverageCalculator.hpp index 70007b2556..6cb2326da6 100644 --- a/opm/simulators/wells/RegionAverageCalculator.hpp +++ b/opm/simulators/wells/RegionAverageCalculator.hpp @@ -30,6 +30,7 @@ #include #include +#include #include /** @@ -82,12 +83,13 @@ namespace Opm { template void defineState(const Simulator& simulator) { - int numRegions = 0; const auto& gridView = simulator.gridView(); const auto& comm = gridView.comm(); - for (const auto& reg : rmap_.activeRegions()) { - numRegions = std::max(numRegions, reg); - } + int numRegions = + std::accumulate(rmap_.activeRegions().begin(), + rmap_.activeRegions().end(), 0, + [](const auto acc, const auto& reg) + { return std::max(acc, reg); }); numRegions = comm.max(numRegions); // reg = 0 is used for field for (int reg = 0; reg <= numRegions ; ++ reg) { diff --git a/opm/simulators/wells/WellGroupHelpers.cpp b/opm/simulators/wells/WellGroupHelpers.cpp index fc9b28c9fa..331ad48cef 100644 --- a/opm/simulators/wells/WellGroupHelpers.cpp +++ b/opm/simulators/wells/WellGroupHelpers.cpp @@ -46,6 +46,7 @@ #include #include #include + #include #include #include @@ -1009,7 +1010,8 @@ computeNetworkPressures(const Network::ExtNetwork& network, // convention that production rates are negative, so we must // take a copy and flip signs. auto rates = node_inflows[node]; - for (auto& r : rates) { r *= -1.0; } + std::transform(rates.begin(), rates.end(), rates.begin(), + [](const auto r) { return -r; }); assert(rates.size() == 3); // NB! ALQ in extended network is never implicitly the gas lift rate (GRAT), i.e., the // gas lift rates only enters the network pressure calculations through the rates diff --git a/opm/simulators/wells/WellInterface_impl.hpp b/opm/simulators/wells/WellInterface_impl.hpp index a5ef34179d..3a6dc02a48 100644 --- a/opm/simulators/wells/WellInterface_impl.hpp +++ b/opm/simulators/wells/WellInterface_impl.hpp @@ -1920,9 +1920,9 @@ namespace Opm const auto& connections = this->well_ecl_.getConnections(); const auto& connection = connections[perf_ecl_index]; if (connection.filterCakeActive()) { - for (auto& val : mob) { - val *= this->inj_fc_multiplier_[perf]; - } + std::transform(mob.begin(), mob.end(), mob.begin(), + [mult = this->inj_fc_multiplier_[perf] ](const auto val) + { return val * mult; }); } } } diff --git a/tests/test_norne_pvt.cpp b/tests/test_norne_pvt.cpp index 2fc8f15fcc..cd41edec1c 100644 --- a/tests/test_norne_pvt.cpp +++ b/tests/test_norne_pvt.cpp @@ -31,9 +31,6 @@ #endif #include -#include -#include - #include #include #include @@ -47,6 +44,7 @@ #include +#include using namespace Opm; @@ -107,15 +105,13 @@ void verify_norne_oil_pvt_region1(const Opm::EclipseState& eclState, const Opm:: 0.77691738473}; { - std::vector tableIndex(P.size() , 0); - // convert the pressures to SI units (bar to Pascal) - for (auto& value : P) - value *= Metric::Pressure; + std::transform(P.begin(), P.end(), P.begin(), + [](const auto value) { return value * Metric::Pressure; }); // convert the gas dissolution factors to SI units - for (auto& value : rs) - value *= Metric::GasDissolutionFactor; + std::transform(rs.begin(), rs.end(), rs.begin(), + [](const auto value) { return value * Metric::GasDissolutionFactor; }); for (unsigned i = 0; i < P.size(); ++i) { double mu; @@ -255,12 +251,12 @@ void verify_norne_oil_pvt_region2(const Opm::EclipseState& eclState, const Opm:: 0.55474601877, 0.55809201119, 0.54526832277}; // convert the pressures to SI units (bar to Pascal) - for (auto& value : P) - value *= Metric::Pressure; + std::transform(P.begin(), P.end(), P.begin(), + [](const auto value) { return value * Metric::Pressure; }); // convert the gas dissolution factors to SI units - for (auto& value : rs) - value *= Metric::GasDissolutionFactor; + std::transform(rs.begin(), rs.end(), rs.begin(), + [](const auto value) { return value * Metric::GasDissolutionFactor; }); for (unsigned i = 0; i < P.size(); ++i) { double mu; diff --git a/tests/test_parallelwellinfo.cpp b/tests/test_parallelwellinfo.cpp index 2da84d22d5..2c342d3086 100644 --- a/tests/test_parallelwellinfo.cpp +++ b/tests/test_parallelwellinfo.cpp @@ -118,10 +118,11 @@ BOOST_AUTO_TEST_CASE(ParallelWellComparison) pairs = {{"Test1", false},{"Test2", true}, {"Test1", true} }; std::vector> well_info; - - for (const auto& wellinfo : pairs) { - well_info.emplace_back(wellinfo, Opm::Parallel::Communication()); - } + + std::transform(pairs.begin(), pairs.end(), + std::back_inserter(well_info), + [](const auto& wellinfo) -> Opm::ParallelWellInfo + { return {wellinfo, Opm::Parallel::Communication()}; }); //well_info.assign(pairs.begin(), pairs.end());