ReservoirCoupling.hpp
Go to the documentation of this file.
1/*
2 Copyright 2024 Equinor ASA
3
4 This file is part of the Open Porous Media project (OPM).
5
6 OPM is free software: you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation, either version 3 of the License, or
9 (at your option) any later version.
10
11 OPM is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
15
16 You should have received a copy of the GNU General Public License
17 along with OPM. If not, see <http://www.gnu.org/licenses/>.
18*/
19
20#ifndef OPM_RESERVOIR_COUPLING_HPP
21#define OPM_RESERVOIR_COUPLING_HPP
24#include <opm/input/eclipse/Schedule/Group/Group.hpp>
25#include <opm/input/eclipse/Schedule/Group/GuideRate.hpp>
26#include <opm/input/eclipse/Units/Units.hpp>
27
28#include <dune/common/parallel/mpitraits.hh>
29
30#include <fmt/format.h>
31
32#include <mpi.h>
33#include <cmath>
34#include <iostream>
35#include <memory>
36#include <stdexcept>
37#include <vector>
38
39namespace Opm {
40namespace ReservoirCoupling {
41
42class Logger {
43public:
44 Logger() = delete; // No default constructor - must have comm
45 explicit Logger(const Parallel::Communication& comm) : comm_(comm) {}
46
47 void clearDeferredLogger() { deferred_logger_ = nullptr; }
48 void debug(const std::string &msg) const;
49 DeferredLogger& deferredLogger() { return *deferred_logger_; }
50 DeferredLogger& deferredLogger() const { return *deferred_logger_; }
51 void error(const std::string &msg) const;
52 bool haveDeferredLogger() const { return deferred_logger_ != nullptr; }
53 void info(const std::string &msg) const;
54 void warning(const std::string &msg) const;
55 void setDeferredLogger(DeferredLogger *deferred_logger) { deferred_logger_ = deferred_logger; }
56
57private:
58 template<typename DeferredFn, typename OpmLogFn>
59 void forward_(const std::string &msg, DeferredFn deferred_fn, OpmLogFn opmlog_fn) const;
60
61 const Parallel::Communication& comm_;
62 DeferredLogger *deferred_logger_ = nullptr;
63};
64
93public:
94 explicit ScopedLoggerGuard(Logger& logger, DeferredLogger* deferred_logger)
95 : logger_(&logger)
96 {
97 logger_->setDeferredLogger(deferred_logger);
98 }
99
101 // Only clear if we still own the logger (not moved-from)
102 if (logger_) {
103 logger_->clearDeferredLogger();
104 }
105 }
106
107 // Prevent copying to ensure single ownership
110
111 // Enable moving - required for returning from functions and std::optional
113 : logger_(other.logger_)
114 {
115 // Transfer ownership: moved-from object becomes inactive and won't clear the logger
116 other.logger_ = nullptr;
117 }
118
120 if (this != &other) {
121 // Clean up current logger before taking ownership of new one
122 if (logger_) {
123 logger_->clearDeferredLogger();
124 }
125 // Transfer ownership from other
126 logger_ = other.logger_;
127 other.logger_ = nullptr;
128 }
129 return *this;
130 }
131
132private:
133 // Use pointer instead of reference to enable move semantics
134 // (references cannot be reassigned, which is required for move operations)
135 Logger* logger_{nullptr};
136};
137
138enum class MessageTag : int {
153 SlaveName,
161};
162
173inline constexpr double slave_end_of_run_sentinel = -1.0;
174
176inline bool isSlaveEndOfRunSentinel(double next_report_time_offset)
177{
178 return next_report_time_offset < 0.0;
179}
180
183enum class Phase : std::size_t {
184 Oil = 0, // Matches Opm::Phase::OIL
185 Gas, // Matches Opm::Phase::GAS
186 Water, // Matches Opm::Phase::WATER
187 Count
188};
189
195enum class RateKind {
201};
202
203template <class Scalar>
205 InjectionRates() = default;
206
207 std::array<Scalar, static_cast<std::size_t>(Phase::Count)> rate{};
208 [[nodiscard]] Scalar& operator[](Phase p) noexcept { return rate[static_cast<std::size_t>(p)]; }
209 [[nodiscard]] Scalar operator[](Phase p) const noexcept { return rate[static_cast<std::size_t>(p)]; }
210};
211
212// Used to communicate potentials for oil, gas, and water rates between slave and master processes
213template <class Scalar>
215 std::array<Scalar, static_cast<std::size_t>(Phase::Count)> rate{};
216
217 [[nodiscard]] Scalar& operator[](Phase p) noexcept { return rate[static_cast<std::size_t>(p)]; }
218 [[nodiscard]] Scalar operator[](Phase p) const noexcept { return rate[static_cast<std::size_t>(p)]; }
219};
220
221template <class Scalar>
223 ProductionRates() = default;
224
225 explicit ProductionRates(const GuideRate::RateVector& rate_vector)
226 : rate{static_cast<Scalar>(rate_vector.oil_rat),
227 static_cast<Scalar>(rate_vector.gas_rat),
228 static_cast<Scalar>(rate_vector.wat_rat)}
229 {}
230
231 std::array<Scalar, static_cast<std::size_t>(Phase::Count)> rate{};
232 [[nodiscard]] Scalar& operator[](Phase p) noexcept { return rate[static_cast<std::size_t>(p)]; }
233 [[nodiscard]] Scalar operator[](Phase p) const noexcept { return rate[static_cast<std::size_t>(p)]; }
234};
235
236// Slave group production data sent to the corresponding master group for target calculation.
237template <class Scalar>
239 // Group production potentials are used by the master group for guiderate calculations
241 // Production rates are used by the master group in guiderate calculations
242 // when converting the guide rate target to the phase of the master group.
243 ProductionRates<Scalar> surface_rates; // Surface production rates by phase (network=false)
244 // Network surface rates - computed with network=true, meaning efficiency factors
245 // are 1.0 for groups/wells with GEFAC/WEFAC item 3 = "NO"
246 ProductionRates<Scalar> network_surface_rates; // Surface rates for network calculations
247 // Individual phase reservoir production rates - needed when master's parent group
248 // has RESV control mode, so the conversion uses slave's PVT properties
249 ProductionRates<Scalar> reservoir_rates; // Reservoir production rates by phase
250 Scalar voidage_rate{0.0}; // Reservoir voidage replacement rate
251 Scalar gas_reinjection_rate{0.0}; // Reinjection (surface) rate for the gas phase
252 // Number of the slave group's producers under group control. Zero means that no
253 // producer follows the group's target, e.g. because all of them are on their own
254 // THP or BHP limit. The master then excludes the master group from its parent's
255 // guide-rate distribution, see
256 // RescoupConstraintsCalculator::excludeAndRedistributeProductionTargets_().
258
259 // The following are only used for the summary output of the master group, which
260 // has no wells of its own. They are summed over the slave group's producers as
261 // the group summary vectors of the slave run are (see the corresponding
262 // evaluators in opm-common's Summary.cpp).
263 //
264 // well_potentials are not the same as potentials above, which are the group
265 // potentials of the group state, set by GuideRateHandler for the guide rates.
266 // Those are summed with WEFAC and GEFAC but without the wells' efficiency
267 // scaling factor, and are only updated when the guide rates are updated.
268 // well_potentials are summed from the current well potentials with all the
269 // efficiency factors, as GOPP etc. of the slave run.
270 Scalar gas_lift_rate{0.0}; // Lift gas rate (GGLIR)
271 ProductionRates<Scalar> well_potentials; // Production potentials (GOPP, GWPP, GGPP)
272 ProductionRates<Scalar> history_rates; // Production history rates (GOPRH, ...)
273 int num_flowing_producers{0}; // Number of flowing producers (GMWPR)
274};
275
276// Slave group injection data sent to the corresponding master group for target calculation.
277template <class Scalar>
279 InjectionRates<Scalar> surface_rates{}; // Surface injection rates by phase
280 InjectionRates<Scalar> reservoir_rates{}; // Reservoir injection rates by phase
281 // Number of the slave group's injectors under group control, by phase
282 // (indexed by Phase). Zero means that no injector follows the group's
283 // target for the phase, e.g. because all of them are on their own BHP
284 // limit. The master then excludes the master group from its parent's
285 // guide-rate distribution, see
286 // RescoupConstraintsCalculator::excludeAndRedistributeInjectionTargets_().
287 std::array<int, static_cast<std::size_t>(Phase::Count)> num_group_controlled_injectors{};
288
289 // The following are only used for the summary output of the master group, as
290 // for SlaveGroupProductionData, where it is also explained how well_potentials
291 // differ from potentials.
292 InjectionRates<Scalar> well_potentials{}; // Injection potentials (GWPI, GGPI, GOPI)
293 InjectionRates<Scalar> history_rates{}; // Injection history rates (GWIRH, ...)
294 int num_flowing_injectors{0}; // Number of flowing injectors (GMWIN)
295};
296
297template <class Scalar>
299 // To save memory and avoid varying size of the struct when serializing
300 // and deserializing the group name, we use an index instead of the full name.
301 std::size_t group_name_idx; // Index of group name in the master group names vector
302 Scalar target; // Target rate for the group
303 Group::InjectionCMode cmode; // Control mode for the group
304 Phase phase; // Phase the target applies to
305};
306
307template <class Scalar>
309 // To save memory and avoid varying size of the struct when serializing
310 // and deserializing the group name, we use an index instead of the full name.
311 std::size_t group_name_idx; // Index of group name in the master group names vector
312 Scalar target; // Target rate for the active control mode
313 Group::ProductionCMode cmode; // Active control mode for the group
314 // Per-rate-type effective limits (-1 = no limit defined in hierarchy).
315 // These are guide-rate-distributed limits from the group hierarchy.
316 Scalar oil_limit;
318 Scalar gas_limit;
321};
322
325template <class Scalar>
327 Scalar oil_limit{-1};
328 Scalar water_limit{-1};
329 Scalar gas_limit{-1};
330 Scalar liquid_limit{-1};
331 Scalar resv_limit{-1};
332};
333
340template <class Scalar>
342 // To save memory and avoid varying size of the struct when serializing
343 // and deserializing the group name, we use an index instead of the full name.
344 std::size_t group_name_idx; // Index of group name in the master group names vector
345 Scalar pressure; // Network-leaf node pressure (SI units, Pa)
346};
347
348// Helper functions
351void customErrorHandler_(MPI_Comm* comm, int* err, const std::string &msg);
352void customErrorHandlerSlave_(MPI_Comm* comm, int* err, ...);
353void customErrorHandlerMaster_(MPI_Comm* comm, int* err, ...);
354void setErrhandler(MPI_Comm comm, bool is_master);
355std::pair<std::vector<char>, std::size_t> serializeStrings(const std::vector<std::string>& data);
356
360inline std::string formatDays(double seconds) {
361 double days = seconds / unit::day;
362 return fmt::format(fmt::runtime("{:.0f}s ({:.2f} days)"), seconds, days);
363}
364
366template <class Scalar>
372};
373
385template <class Scalar>
387flowChangeTimeStepLimit(Scalar limiting_fraction,
388 Scalar step_length,
389 Scalar min_step,
390 const std::vector<Scalar>& start_flows,
391 const std::vector<Scalar>& end_flows);
392
410struct Seconds {
412 static constexpr double abstol = 1e-15;
413
415 static constexpr double reltol = 1e-15;
416
435 static bool compare_eq(double a, double b);
436
442 static bool compare_gt(double a, double b);
443
449 static bool compare_gt_or_eq(double a, double b);
450
456 static bool compare_lt(double a, double b);
457
463 static bool compare_lt_or_eq(double a, double b);
464};
465
466} // namespace ReservoirCoupling
467} // namespace Opm
468
469#endif // OPM_RESERVOIR_COUPLING_HPP
Definition: DeferredLogger.hpp:57
Definition: ReservoirCoupling.hpp:42
void error(const std::string &msg) const
void info(const std::string &msg) const
void warning(const std::string &msg) const
void setDeferredLogger(DeferredLogger *deferred_logger)
Definition: ReservoirCoupling.hpp:55
void clearDeferredLogger()
Definition: ReservoirCoupling.hpp:47
Logger(const Parallel::Communication &comm)
Definition: ReservoirCoupling.hpp:45
bool haveDeferredLogger() const
Definition: ReservoirCoupling.hpp:52
DeferredLogger & deferredLogger()
Definition: ReservoirCoupling.hpp:49
void debug(const std::string &msg) const
DeferredLogger & deferredLogger() const
Definition: ReservoirCoupling.hpp:50
Guard for managing DeferredLogger lifecycle in ReservoirCoupling.
Definition: ReservoirCoupling.hpp:92
~ScopedLoggerGuard()
Definition: ReservoirCoupling.hpp:100
ScopedLoggerGuard & operator=(const ScopedLoggerGuard &)=delete
ScopedLoggerGuard(ScopedLoggerGuard &&other) noexcept
Definition: ReservoirCoupling.hpp:112
ScopedLoggerGuard(const ScopedLoggerGuard &)=delete
ScopedLoggerGuard & operator=(ScopedLoggerGuard &&other) noexcept
Definition: ReservoirCoupling.hpp:119
ScopedLoggerGuard(Logger &logger, DeferredLogger *deferred_logger)
Definition: ReservoirCoupling.hpp:94
Dune::Communication< MPIComm > Communication
Definition: ParallelCommunication.hpp:30
std::string formatDays(double seconds)
Format seconds as a human-readable string showing both seconds and days.
Definition: ReservoirCoupling.hpp:360
RateKind
Selects which kind of rate to retrieve from slave group data.
Definition: ReservoirCoupling.hpp:195
FlowChangeLimit< Scalar > flowChangeTimeStepLimit(Scalar limiting_fraction, Scalar step_length, Scalar min_step, const std::vector< Scalar > &start_flows, const std::vector< Scalar > &end_flows)
Limit the next sync step from the flow change of a master group (GRUPMAST item 4)
void customErrorHandler_(MPI_Comm *comm, int *err, const std::string &msg)
std::pair< std::vector< char >, std::size_t > serializeStrings(const std::vector< std::string > &data)
void customErrorHandlerSlave_(MPI_Comm *comm, int *err,...)
MessageTag
Definition: ReservoirCoupling.hpp:138
void setErrhandler(MPI_Comm comm, bool is_master)
constexpr double slave_end_of_run_sentinel
Sentinel sent by a slave on the MessageTag::SlaveNextReportDate channel to tell the master that the s...
Definition: ReservoirCoupling.hpp:173
bool isSlaveEndOfRunSentinel(double next_report_time_offset)
Whether a next-report-date offset received from a slave is the end-of-run sentinel.
Definition: ReservoirCoupling.hpp:176
void customErrorHandlerMaster_(MPI_Comm *comm, int *err,...)
Phase convertPhaseToReservoirCouplingPhase(::Opm::Phase phase)
Phase
Phase indices for reservoir coupling, we currently only support black-oil phases (oil,...
Definition: ReservoirCoupling.hpp:183
::Opm::Phase convertToOpmPhase(const Phase phase)
Definition: blackoilbioeffectsmodules.hh:45
Result of flowChangeTimeStepLimit()
Definition: ReservoirCoupling.hpp:367
Scalar time_step_limit
Upper limit for the next sync step length (infinity if the flow change does not limit it)
Definition: ReservoirCoupling.hpp:369
Scalar max_change
The largest fractional flow change (infinity for a flow that starts from zero)
Definition: ReservoirCoupling.hpp:371
Definition: ReservoirCoupling.hpp:298
Scalar target
Definition: ReservoirCoupling.hpp:302
std::size_t group_name_idx
Definition: ReservoirCoupling.hpp:301
Group::InjectionCMode cmode
Definition: ReservoirCoupling.hpp:303
Phase phase
Definition: ReservoirCoupling.hpp:304
Definition: ReservoirCoupling.hpp:204
Scalar operator[](Phase p) const noexcept
Definition: ReservoirCoupling.hpp:209
std::array< Scalar, static_cast< std::size_t >(Phase::Count)> rate
Definition: ReservoirCoupling.hpp:207
Scalar & operator[](Phase p) noexcept
Definition: ReservoirCoupling.hpp:208
Master-computed network-leaf node pressure for a single master group.
Definition: ReservoirCoupling.hpp:341
std::size_t group_name_idx
Definition: ReservoirCoupling.hpp:344
Scalar pressure
Definition: ReservoirCoupling.hpp:345
Per-rate-type production limits received from master hierarchy. A value of -1 means no limit defined ...
Definition: ReservoirCoupling.hpp:326
Scalar liquid_limit
Definition: ReservoirCoupling.hpp:330
Scalar gas_limit
Definition: ReservoirCoupling.hpp:329
Scalar resv_limit
Definition: ReservoirCoupling.hpp:331
Scalar water_limit
Definition: ReservoirCoupling.hpp:328
Scalar oil_limit
Definition: ReservoirCoupling.hpp:327
Definition: ReservoirCoupling.hpp:214
std::array< Scalar, static_cast< std::size_t >(Phase::Count)> rate
Definition: ReservoirCoupling.hpp:215
Scalar & operator[](Phase p) noexcept
Definition: ReservoirCoupling.hpp:217
Scalar operator[](Phase p) const noexcept
Definition: ReservoirCoupling.hpp:218
Definition: ReservoirCoupling.hpp:308
Scalar liquid_limit
Definition: ReservoirCoupling.hpp:319
Scalar resv_limit
Definition: ReservoirCoupling.hpp:320
Scalar oil_limit
Definition: ReservoirCoupling.hpp:316
Group::ProductionCMode cmode
Definition: ReservoirCoupling.hpp:313
Scalar target
Definition: ReservoirCoupling.hpp:312
std::size_t group_name_idx
Definition: ReservoirCoupling.hpp:311
Scalar water_limit
Definition: ReservoirCoupling.hpp:317
Scalar gas_limit
Definition: ReservoirCoupling.hpp:318
Definition: ReservoirCoupling.hpp:222
Scalar operator[](Phase p) const noexcept
Definition: ReservoirCoupling.hpp:233
ProductionRates(const GuideRate::RateVector &rate_vector)
Definition: ReservoirCoupling.hpp:225
Scalar & operator[](Phase p) noexcept
Definition: ReservoirCoupling.hpp:232
std::array< Scalar, static_cast< std::size_t >(Phase::Count)> rate
Definition: ReservoirCoupling.hpp:231
Utility class for comparing double values representing epoch dates or elapsed time.
Definition: ReservoirCoupling.hpp:410
static bool compare_gt_or_eq(double a, double b)
Determines if a is greater than b within the specified tolerance.
static bool compare_gt(double a, double b)
Determines if a is greater than b within the specified tolerance.
static bool compare_lt_or_eq(double a, double b)
Determines if a is less than or equal to b within the specified tolerance.
static bool compare_eq(double a, double b)
Determines if two double values are equal within a specified tolerance.
static constexpr double reltol
Relative tolerance used for comparisons.
Definition: ReservoirCoupling.hpp:415
static bool compare_lt(double a, double b)
Determines if a is less than b within the specified tolerance.
static constexpr double abstol
Absolute tolerance used for comparisons.
Definition: ReservoirCoupling.hpp:412
Definition: ReservoirCoupling.hpp:278
InjectionRates< Scalar > surface_rates
Definition: ReservoirCoupling.hpp:279
InjectionRates< Scalar > reservoir_rates
Definition: ReservoirCoupling.hpp:280
InjectionRates< Scalar > well_potentials
Definition: ReservoirCoupling.hpp:292
InjectionRates< Scalar > history_rates
Definition: ReservoirCoupling.hpp:293
std::array< int, static_cast< std::size_t >(Phase::Count)> num_group_controlled_injectors
Definition: ReservoirCoupling.hpp:287
int num_flowing_injectors
Definition: ReservoirCoupling.hpp:294
Definition: ReservoirCoupling.hpp:238
Scalar gas_reinjection_rate
Definition: ReservoirCoupling.hpp:251
Potentials< Scalar > potentials
Definition: ReservoirCoupling.hpp:240
int num_flowing_producers
Definition: ReservoirCoupling.hpp:273
int num_group_controlled_producers
Definition: ReservoirCoupling.hpp:257
ProductionRates< Scalar > network_surface_rates
Definition: ReservoirCoupling.hpp:246
ProductionRates< Scalar > reservoir_rates
Definition: ReservoirCoupling.hpp:249
Scalar voidage_rate
Definition: ReservoirCoupling.hpp:250
ProductionRates< Scalar > surface_rates
Definition: ReservoirCoupling.hpp:243
ProductionRates< Scalar > history_rates
Definition: ReservoirCoupling.hpp:272
ProductionRates< Scalar > well_potentials
Definition: ReservoirCoupling.hpp:271
Scalar gas_lift_rate
Definition: ReservoirCoupling.hpp:270