23#ifndef OPM_BLACKOILWELLMODEL_NETWORK_IMPL_HEADER_INCLUDED
24#define OPM_BLACKOILWELLMODEL_NETWORK_IMPL_HEADER_INCLUDED
27#ifndef OPM_BLACKOILWELLMODEL_NETWORK_HEADER_INCLUDED
32#include <opm/common/TimingMacros.hpp>
33#include <opm/common/utility/numeric/RootFinders.hpp>
35#include <opm/input/eclipse/Units/Units.hpp>
43#include <fmt/format.h>
51template<
typename TypeTag>
55 , well_model_(well_model)
58template<
typename TypeTag>
64 const double dt = well_model_.simulator().timeStepSize();
67 auto& well_state = well_model_.wellState();
69 const bool changed_well_group =
70 well_model_.updateWellControlsAndNetwork(
true,
73 well_model_.assembleWellEqWithoutIteration(dt);
74 const bool converged =
75 well_model_.getWellConvergence(well_model_.B_avg(),
true).converged() &&
88 std::optional<std::remove_cvref_t<
decltype(well_state.well(0))>> state_before_step;
91 [](
const auto& well) ->
const auto& {
return well->parallelWellInfo().communication(); },
93 state_before_step = well_state.well(well->indexOfWell());
94 well->solveEqAndUpdateWellState(well_model_.simulator(),
95 well_model_.groupStateHelper(),
98 [&](
auto& well,
const bool failed_on_this_rank,
const std::string& reason) {
100 if (failed_on_this_rank) {
101 deferred_logger.
warning(
"PRESTEP_NETWORK_REBALANCE_WELL_FAILED",
102 fmt::format(
"Well {} failed during the initial (pre-step) network balance ({}). "
103 "The well is stopped and solved with zero rate.",
104 well->name(), reason));
106 well_state.well(well->indexOfWell()) = state_before_step.value();
108 well->updatePrimaryVariables(well_model_.groupStateHelper());
109 }
catch (
const NumericalProblem&) {
113 well->stopWellAndSolveWithZeroRate(well_model_.simulator(),
115 well_model_.groupStateHelper(),
119 well_model_.simulator().vanguard().grid().comm());
122 deferred_logger.
warning(
"Initial (pre-step) network balance did not converge.");
126template<
typename TypeTag>
127std::tuple<bool, typename BlackoilWellModelNetwork<TypeTag>::Scalar>
129update(
const bool mandatory_network_balance,
131 const bool relax_network_tolerance)
134 const int episodeIdx = well_model_.simulator().episodeIndex();
139 const auto& comm = well_model_.simulator().vanguard().grid().comm();
142 Scalar network_imbalance = 0.0;
143 bool more_network_update =
false;
144 if (this->shouldBalance(episodeIdx) || mandatory_network_balance) {
145 OPM_TIMEBLOCK(BalanceNetwork);
146 const double dt = well_model_.simulator().timeStepSize();
148 const bool well_group_thp_updated = computeWellGroupThp(dt, deferred_logger);
149 const int max_number_of_sub_iterations =
150 well_model_.param().network_max_sub_iterations_;
151 const Scalar network_pressure_update_damping_factor =
152 well_model_.param().network_pressure_update_damping_factor_;
153 const Scalar network_max_pressure_update =
154 well_model_.param().network_max_pressure_update_in_bars_ * unit::barsa;
155 bool more_network_sub_update =
false;
156 for (
int i = 0; i < max_number_of_sub_iterations; i++) {
157 const auto local_network_imbalance =
158 this->updatePressures(episodeIdx,
159 network_pressure_update_damping_factor,
160 network_max_pressure_update);
161 network_imbalance = comm.max(local_network_imbalance);
162 const auto& balance = well_model_.schedule()[episodeIdx].network_balance();
163 constexpr Scalar relaxation_factor = 10.0;
164 const Scalar tolerance =
165 relax_network_tolerance ? relaxation_factor * balance.pressure_tolerance()
166 : balance.pressure_tolerance();
167 more_network_sub_update = this->active() && network_imbalance > tolerance;
168#ifdef RESERVOIR_COUPLING_ENABLED
169 if (well_model_.isReservoirCouplingMaster()) {
173 well_model_.rescoupHelper().maybeExchangeNetworkSubIterationWithSlaves();
176 if (!more_network_sub_update) {
180 for (
const auto& well : well_model_) {
181 if (!well->wellEcl().predictionMode()) {
187 if (!domain.has_value()) {
191 const auto it = this->nodePressures(*domain).find(well->wellEcl().groupName());
192 if (it != this->nodePressures(*domain).end()) {
193 well->prepareWellBeforeAssembling(well_model_.simulator(),
195 well_model_.groupStateHelper(),
196 well_model_.wellState());
206 if (well->isInjector()) {
207 auto& ws = well_model_.wellState().well(well->indexOfWell());
208 if (ws.injection_cmode == Well::InjectorCMode::THP) {
209 const int np = well_model_.numPhases();
210 for (
int p = 0; p < np; ++p) {
211 ws.well_potentials[p] =
212 std::max(Scalar{0.0}, ws.surface_rates[p]);
218 well_model_.updateAndCommunicateGroupData(episodeIdx,
true);
220 more_network_update = more_network_sub_update || well_group_thp_updated;
222 return { more_network_update, network_imbalance };
225template <
typename TypeTag>
231 const int reportStepIdx = well_model_.simulator().episodeIndex();
236 const auto& network = well_model_.schedule()[reportStepIdx].network();
237 const auto& balance = well_model_.schedule()[reportStepIdx].network_balance();
238 const Scalar thp_tolerance = balance.thp_tolerance();
240 if (!network.active()) {
244 auto& well_state = well_model_.wellState();
245 auto& group_state = well_model_.groupState();
247 bool well_group_thp_updated =
false;
248 for (
const std::string& nodeName : network.node_names()) {
249 const bool has_choke = network.node(nodeName).as_choke();
251 const auto& summary_state = well_model_.simulator().vanguard().summaryState();
252 const Group& group = well_model_.schedule().getGroup(nodeName, reportStepIdx);
255 std::vector<Scalar> resv_coeff(Indices::numPhases, 1.0);
257 const auto ctrl = group.productionControls(summary_state);
258 auto cmode_tmp = ctrl.cmode;
259 Scalar target_tmp{0.0};
260 bool fld_none =
false;
265 const Scalar efficiencyFactor = 1.0;
266 const Group& parentGroup = well_model_.schedule().getGroup(group.parent(), reportStepIdx);
267 auto target = well_model_.groupStateHelper().
268 getAutoChokeGroupProductionTargetRate(group,
272 target_tmp = target.first;
273 cmode_tmp = target.second;
276 TargetCalculatorType tcalc{well_model_.groupStateHelper(), resv_coeff, group};
280 target_tmp = well_model_.groupStateHelper().getProductionGroupTarget(group);
283 const Scalar orig_target = target_tmp;
285 auto mismatch = [&] (
auto group_thp) {
286 Scalar group_rate(0.0);
288 for (
auto& well : well_model_) {
292 if (well->isInjector()) {
295 std::string well_name = well->name();
296 auto& ws = well_state.well(well_name);
297 if (group.hasWell(well_name)) {
300 if (well->wellEcl().vfp_table_number() > 0) {
301 well->setDynamicThpLimit(group_thp);
303 const auto inj_controls = Well::InjectionControls(0);
308 const auto prod_controls =
309 well->productionControlsWithWeldraw(summary_state, ws);
310 well->iterateWellEqWithSwitching(well_model_.simulator(),
314 well_model_.groupStateHelper(),
319 rate = -tcalc.calcModeRateFromRates(ws.surface_rates);
323 return (group_rate - orig_target)/orig_target;
326 const auto upbranch = network.uptree_branch(nodeName);
327 const auto it = this->node_pressures_.find((*upbranch).uptree_node());
328 const Scalar nodal_pressure = it->second;
329 Scalar well_group_thp = nodal_pressure;
331 std::optional<Scalar> autochoke_thp;
332 if (
auto iter = this->well_group_thp_calc_.find(nodeName);
333 iter != this->well_group_thp_calc_.end())
335 autochoke_thp = this->well_group_thp_calc_.at(nodeName);
340 std::array<Scalar, 2> range_initial;
341 if (!autochoke_thp.has_value()){
342 Scalar min_thp, max_thp;
344 std::string node_name = nodeName;
345 while (!network.node(node_name).terminal_pressure().has_value()) {
346 auto branch = network.uptree_branch(node_name).value();
347 node_name = branch.uptree_node();
349 min_thp = network.node(node_name).terminal_pressure().value();
350 WellBhpThpCalculatorType::bruteForceBracketCommonTHP(mismatch, min_thp, max_thp);
353 std::array<Scalar, 2> range = {Scalar{0.9}*min_thp, Scalar{1.1}*max_thp};
354 std::optional<Scalar> appr_sol;
355 WellBhpThpCalculatorType::bruteForceBracketCommonTHP(mismatch,
361 local_deferredLogger);
364 range_initial = {min_thp, max_thp};
367 if (!autochoke_thp.has_value() || autochoke_thp.value() > nodal_pressure) {
370 std::array<Scalar, 2> range = autochoke_thp.has_value() ?
371 std::array<Scalar, 2>{Scalar{0.9} * autochoke_thp.value(),
372 Scalar{1.1} * autochoke_thp.value()} : range_initial;
374 std::optional<Scalar> approximate_solution;
375 const Scalar tolerance1 = thp_tolerance;
376 local_deferredLogger.
debug(
"Using brute force search to bracket the group THP");
377 const bool finding_bracket = WellBhpThpCalculatorType::
378 bruteForceBracketCommonTHP(mismatch,
382 approximate_solution,
384 local_deferredLogger);
386 if (approximate_solution.has_value()) {
387 autochoke_thp = *approximate_solution;
388 local_deferredLogger.
debug(
"Approximate group THP value found: " +
390 }
else if (finding_bracket) {
391 const Scalar tolerance2 = thp_tolerance;
392 const int max_iteration_solve = 100;
394 autochoke_thp = RegulaFalsiBisection<ThrowOnError>::
406 autochoke_thp.reset();
407 local_deferredLogger.
debug(
"Group THP solve failed due to bracketing failure");
410 if (autochoke_thp.has_value()) {
411 this->well_group_thp_calc_[nodeName] = autochoke_thp.value();
415 well_group_thp = std::max(autochoke_thp.value(), nodal_pressure);
418 for (
auto& well : well_model_) {
419 std::string well_name = well->name();
421 if (well->isInjector() || !well->wellEcl().predictionMode())
426 if (group.hasWell(well_name)
427 && well->wellEcl().vfp_table_number() > 0) {
428 well->setDynamicThpLimit(well_group_thp);
430 const auto& ws = well_model_.wellState().well(well->indexOfWell());
431 const bool thp_is_limit = ws.production_cmode == Well::ProducerCMode::THP;
433 well->prepareWellBeforeAssembling(well_model_.simulator(),
435 well_model_.groupStateHelper(),
436 well_model_.wellState());
441 const auto& current_well_group_thp = group_state.is_autochoke_group(nodeName)
442 ? group_state.well_group_thp(nodeName)
444 if (std::abs(current_well_group_thp - well_group_thp) > balance.pressure_tolerance()) {
445 well_group_thp_updated =
true;
446 group_state.update_well_group_thp(nodeName, well_group_thp);
450 return well_group_thp_updated;
#define OPM_END_PARALLEL_TRY_CATCH(prefix, comm)
Catch exception and throw in a parallel try-catch clause.
Definition: DeferredLoggingErrorHelpers.hpp:197
#define OPM_BEGIN_PARALLEL_TRY_CATCH()
Macro to setup the try of a parallel try-catch.
Definition: DeferredLoggingErrorHelpers.hpp:160
Class for handling the blackoil well network model.
Definition: BlackoilWellModelNetworkGeneric.hpp:107
bool computeWellGroupThp(const double dt, DeferredLogger &local_deferredLogger)
Definition: BlackoilWellModelNetwork_impl.hpp:228
std::tuple< bool, Scalar > update(const bool mandatory_network_balance, DeferredLogger &deferred_logger, const bool relax_network_tolerance=false)
Definition: BlackoilWellModelNetwork_impl.hpp:129
BlackoilWellModelNetwork(BlackoilWellModel< TypeTag > &well_model)
Definition: BlackoilWellModelNetwork_impl.hpp:53
void doPreStepRebalance(DeferredLogger &deferred_logger)
Definition: BlackoilWellModelNetwork_impl.hpp:61
Class for handling the blackoil well model.
Definition: BlackoilWellModel.hpp:100
Definition: DeferredLogger.hpp:57
void warning(const std::string &tag, const std::string &message)
void debug(const std::string &tag, const std::string &message)
Definition: TargetCalculator.hpp:39
Class for computing BHP limits.
Definition: WellBhpThpCalculator.hpp:41
@ NONE
Definition: DeferredLogger.hpp:46
std::optional< NetworkDomain > domainForWell(const Well &well)
Definition: BlackoilWellModelNetworkGeneric.hpp:73
bool anyNetworkActive(const Schedule &schedule, const int timeStepIdx)
Helper to check if any network (production, gas injection, water injection) is active at a given time...
Definition: blackoilbioeffectsmodules.hh:45
bool solveWellsWithSharedRecovery(Wells &&wells, GetCommunication &&get_communication, Solve &&solve, Recover &&recover)
Solve a list of wells, and recover from numerical failures, with the failures of the wells deferred.
Definition: WellSolveRecovery.hpp:110
std::string to_string(const ConvergenceReport::ReservoirFailure::Type t)