BlackoilWellModelNetwork_impl.hpp
Go to the documentation of this file.
1/*
2 Copyright 2016 - 2019 SINTEF Digital, Mathematics & Cybernetics.
3 Copyright 2016 - 2018 Equinor ASA.
4 Copyright 2017 Dr. Blatt - HPC-Simulation-Software & Services
5 Copyright 2016 - 2018 Norce AS
6
7 This file is part of the Open Porous Media project (OPM).
8
9 OPM is free software: you can redistribute it and/or modify
10 it under the terms of the GNU General Public License as published by
11 the Free Software Foundation, either version 3 of the License, or
12 (at your option) any later version.
13
14 OPM is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 GNU General Public License for more details.
18
19 You should have received a copy of the GNU General Public License
20 along with OPM. If not, see <http://www.gnu.org/licenses/>.
21*/
22
23#ifndef OPM_BLACKOILWELLMODEL_NETWORK_IMPL_HEADER_INCLUDED
24#define OPM_BLACKOILWELLMODEL_NETWORK_IMPL_HEADER_INCLUDED
25
26// Improve IDE experience
27#ifndef OPM_BLACKOILWELLMODEL_NETWORK_HEADER_INCLUDED
28#include <config.h>
30#endif
31
32#include <opm/common/TimingMacros.hpp>
33#include <opm/common/utility/numeric/RootFinders.hpp>
34
35#include <opm/input/eclipse/Units/Units.hpp>
36
42
43#include <fmt/format.h>
44
45#include <optional>
46#include <string>
47#include <type_traits>
48
49namespace Opm {
50
51template<typename TypeTag>
54 : BaseType(well_model)
55 , well_model_(well_model)
56{}
57
58template<typename TypeTag>
59void
61doPreStepRebalance(DeferredLogger& deferred_logger)
62{
63 OPM_TIMEFUNCTION();
64 const double dt = well_model_.simulator().timeStepSize();
65 // TODO: should we also have the group and network backed-up
66 // here in case the solution did not get converged?
67 auto& well_state = well_model_.wellState();
68
69 const bool changed_well_group =
70 well_model_.updateWellControlsAndNetwork(/*mandatory_network_balance=*/true,
71 dt,
72 deferred_logger);
73 well_model_.assembleWellEqWithoutIteration(dt);
74 const bool converged =
75 well_model_.getWellConvergence(well_model_.B_avg(), true).converged() &&
76 !changed_well_group;
77
79 // A well that fails numerically should not make the whole time step fail. It is stopped
80 // and solved with zero rate, as is done for wells that can not be solved in the inner well
81 // iterations. The well is solved again, and can be reopened, in the Newton iterations of the
82 // time step. A well can be distributed over several ranks, so if it fails on one of them,
83 // all ranks of the well recover, as the recovery contains collective operations. Other failures
84 // are thrown after all wells are solved, so that the ranks of a well are not left waiting for
85 // a rank that has stopped solving the wells.
86 // The state of the well that is solved is kept to be able to restore it if the well fails. The recovery
87 // is done before the next well is solved, so only one state is needed.
88 std::optional<std::remove_cvref_t<decltype(well_state.well(0))>> state_before_step;
90 this->well_model_,
91 [](const auto& well) -> const auto& { return well->parallelWellInfo().communication(); },
92 [&](auto& well) {
93 state_before_step = well_state.well(well->indexOfWell());
94 well->solveEqAndUpdateWellState(well_model_.simulator(),
95 well_model_.groupStateHelper(),
96 well_state);
97 },
98 [&](auto& well, const bool failed_on_this_rank, const std::string& reason) {
99 // log on the ranks where the well failed only, not once more for each other rank of the well
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));
105 }
106 well_state.well(well->indexOfWell()) = state_before_step.value();
107 try {
108 well->updatePrimaryVariables(well_model_.groupStateHelper());
109 } catch (const NumericalProblem&) {
110 // The recovery must not fail the time step. The solve with zero rate below
111 // handles a state that is not finite.
112 }
113 well->stopWellAndSolveWithZeroRate(well_model_.simulator(),
114 dt,
115 well_model_.groupStateHelper(),
116 well_state);
117 });
118 OPM_END_PARALLEL_TRY_CATCH("BlackoilWellModelNetwork::doPreStepRebalance() failed: ",
119 well_model_.simulator().vanguard().grid().comm());
120
121 if (!converged) {
122 deferred_logger.warning("Initial (pre-step) network balance did not converge.");
123 }
124}
125
126template<typename TypeTag>
127std::tuple<bool, typename BlackoilWellModelNetwork<TypeTag>::Scalar>
129update(const bool mandatory_network_balance,
130 DeferredLogger& deferred_logger,
131 const bool relax_network_tolerance)
132{
133 OPM_TIMEFUNCTION();
134 const int episodeIdx = well_model_.simulator().episodeIndex();
135 if (!well_model_.wellsActive() && !details::anyNetworkActive(well_model_.schedule(), episodeIdx)) {
136 return {/*more_network_update=*/false, /*network_imbalance=*/0.0};
137 }
138
139 const auto& comm = well_model_.simulator().vanguard().grid().comm();
140
141 // network related
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();
147 // Calculate common THP for subsea manifold well group (item 3 of NODEPROP set to YES)
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()) {
170 // Tight reservoir-coupling: exchange node pressures and slave rates with the
171 // slaves per inner sub-iteration. Must run before the break below so the converged
172 // sub-iteration still feeds back the slaves' rates.
173 well_model_.rescoupHelper().maybeExchangeNetworkSubIterationWithSlaves();
174 }
175#endif
176 if (!more_network_sub_update) {
177 break;
178 }
179
180 for (const auto& well : well_model_) {
181 if (!well->wellEcl().predictionMode()) {
182 continue;
183 }
184
185 const auto domain = details::domainForWell(*well);
186
187 if (!domain.has_value()) {
188 continue;
189 }
190
191 const auto it = this->nodePressures(*domain).find(well->wellEcl().groupName());
192 if (it != this->nodePressures(*domain).end()) {
193 well->prepareWellBeforeAssembling(well_model_.simulator(),
194 dt,
195 well_model_.groupStateHelper(),
196 well_model_.wellState());
197 // Option B: after re-solving at the current network THP, update
198 // ws.well_potentials for injection wells. The rate_less_than_potential
199 // check in WellConstraints::activeInjectionConstraint compares current
200 // injection rates against ws.well_potentials to decide whether switching
201 // to THP mode would increase or decrease injection. The potentials are
202 // normally computed once per timestep at the static WCONINJE THP and are
203 // stale during network iterations. Refreshing them here (from the rate
204 // the well just solved to under the current network THP) makes the check
205 // accurate for subsequent outer iterations.
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]);
213 }
214 }
215 }
216 }
217 }
218 well_model_.updateAndCommunicateGroupData(episodeIdx, /*update_wellgrouptarget*/ true);
219 }
220 more_network_update = more_network_sub_update || well_group_thp_updated;
221 }
222 return { more_network_update, network_imbalance };
223}
224
225template <typename TypeTag>
226bool
228computeWellGroupThp(const double dt, DeferredLogger& local_deferredLogger)
229{
230 OPM_TIMEFUNCTION();
231 const int reportStepIdx = well_model_.simulator().episodeIndex();
232 // This function is only relevant for auto-choke groups, and
233 // therefore as of now only relevant for the production network.
234 // \TODO: If we later also want to support auto-choke groups in the
235 // injection network, we should change this function also.
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();
239
240 if (!network.active()) {
241 return false;
242 }
243
244 auto& well_state = well_model_.wellState();
245 auto& group_state = well_model_.groupState();
246
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();
250 if (has_choke) {
251 const auto& summary_state = well_model_.simulator().vanguard().summaryState();
252 const Group& group = well_model_.schedule().getGroup(nodeName, reportStepIdx);
253
254 //TODO: Auto choke combined with RESV control is not supported
255 std::vector<Scalar> resv_coeff(Indices::numPhases, 1.0);
256
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;
261 if (cmode_tmp == Group::ProductionCMode::FLD || cmode_tmp == Group::ProductionCMode::NONE) {
262 fld_none = true;
263 // Target is set for an ancestor group. Target for autochoke group to be
264 // derived via group guide rates
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,
269 parentGroup,
270 resv_coeff,
271 efficiencyFactor);
272 target_tmp = target.first;
273 cmode_tmp = target.second;
274 }
276 TargetCalculatorType tcalc{well_model_.groupStateHelper(), resv_coeff, group};
277 if (!fld_none)
278 {
279 // Target is set for the autochoke group itself
280 target_tmp = well_model_.groupStateHelper().getProductionGroupTarget(group);
281 }
282
283 const Scalar orig_target = target_tmp;
284
285 auto mismatch = [&] (auto group_thp) {
286 Scalar group_rate(0.0);
287 Scalar rate(0.0);
288 for (auto& well : well_model_) {
289 // The choke regulates the production of the group, so
290 // an injector in the group takes no part in the rate
291 // that is matched against the target.
292 if (well->isInjector()) {
293 continue;
294 }
295 std::string well_name = well->name();
296 auto& ws = well_state.well(well_name);
297 if (group.hasWell(well_name)) {
298 // A well without a VFP table cannot be put under THP
299 // control, so the common THP is not imposed on it.
300 if (well->wellEcl().vfp_table_number() > 0) {
301 well->setDynamicThpLimit(group_thp);
302 }
303 const auto inj_controls = Well::InjectionControls(0);
304 // The well equations are solved here to find the group
305 // THP, so the controls must carry the drawdown limit;
306 // callers that pass controls explicitly are required to
307 // have applied it.
308 const auto prod_controls =
309 well->productionControlsWithWeldraw(summary_state, ws);
310 well->iterateWellEqWithSwitching(well_model_.simulator(),
311 dt,
312 inj_controls,
313 prod_controls,
314 well_model_.groupStateHelper(),
315 well_state,
316 /*fixed_control=*/false,
317 /*fixed_status=*/false,
318 /*solving_with_zero_rate=*/false);
319 rate = -tcalc.calcModeRateFromRates(ws.surface_rates);
320 group_rate += rate;
321 }
322 }
323 return (group_rate - orig_target)/orig_target;
324 };
325
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;
330
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())
334 {
335 autochoke_thp = this->well_group_thp_calc_.at(nodeName);
336 }
337
338 using WellBhpThpCalculatorType = WellBhpThpCalculator<Scalar, IndexTraits>;
339 //Find an initial bracket
340 std::array<Scalar, 2> range_initial;
341 if (!autochoke_thp.has_value()){
342 Scalar min_thp, max_thp;
343 // Retrieve the terminal pressure of the associated root of the manifold group
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();
348 }
349 min_thp = network.node(node_name).terminal_pressure().value();
350 WellBhpThpCalculatorType::bruteForceBracketCommonTHP(mismatch, min_thp, max_thp);
351 // Narrow down the bracket
352 Scalar low1, high1;
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,
356 range,
357 low1,
358 high1,
359 appr_sol,
360 0.0,
361 local_deferredLogger);
362 min_thp = low1;
363 max_thp = high1;
364 range_initial = {min_thp, max_thp};
365 }
366
367 if (!autochoke_thp.has_value() || autochoke_thp.value() > nodal_pressure) {
368 // The bracket is based on the initial bracket or
369 // on a range based on a previous calculated group thp
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;
373 Scalar low, high;
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,
379 range,
380 low,
381 high,
382 approximate_solution,
383 tolerance1,
384 local_deferredLogger);
385
386 if (approximate_solution.has_value()) {
387 autochoke_thp = *approximate_solution;
388 local_deferredLogger.debug("Approximate group THP value found: " +
389 std::to_string(autochoke_thp.value()));
390 } else if (finding_bracket) {
391 const Scalar tolerance2 = thp_tolerance;
392 const int max_iteration_solve = 100;
393 int iteration = 0;
394 autochoke_thp = RegulaFalsiBisection<ThrowOnError>::
395 solve(mismatch,
396 low,
397 high,
398 max_iteration_solve,
399 tolerance2,
400 iteration);
401 local_deferredLogger.debug(" bracket = [" + std::to_string(low) + ", " +
402 std::to_string(high) + "], " +
403 "iteration = " + std::to_string(iteration));
404 local_deferredLogger.debug("Group THP value = " + std::to_string(autochoke_thp.value()));
405 } else {
406 autochoke_thp.reset();
407 local_deferredLogger.debug("Group THP solve failed due to bracketing failure");
408 }
409 }
410 if (autochoke_thp.has_value()) {
411 this->well_group_thp_calc_[nodeName] = autochoke_thp.value();
412 // Note: The node pressure of the auto-choke node is set
413 // to well_group_thp in computeNetworkPressures()
414 // and must be larger or equal to the pressure of the uptree node of its branch.
415 well_group_thp = std::max(autochoke_thp.value(), nodal_pressure);
416 }
417
418 for (auto& well : well_model_) {
419 std::string well_name = well->name();
420
421 if (well->isInjector() || !well->wellEcl().predictionMode())
422 continue;
423
424 // As above: a well without a VFP table cannot be put under THP
425 // control, so the auto-choke group THP is not imposed on it.
426 if (group.hasWell(well_name)
427 && well->wellEcl().vfp_table_number() > 0) {
428 well->setDynamicThpLimit(well_group_thp);
429 }
430 const auto& ws = well_model_.wellState().well(well->indexOfWell());
431 const bool thp_is_limit = ws.production_cmode == Well::ProducerCMode::THP;
432 if (thp_is_limit) {
433 well->prepareWellBeforeAssembling(well_model_.simulator(),
434 dt,
435 well_model_.groupStateHelper(),
436 well_model_.wellState());
437 }
438 }
439
440 // Use the group THP in computeNetworkPressures().
441 const auto& current_well_group_thp = group_state.is_autochoke_group(nodeName)
442 ? group_state.well_group_thp(nodeName)
443 : 1e30;
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);
447 }
448 }
449 }
450 return well_group_thp_updated;
451}
452
453} // namespace Opm
454
455#endif // OPM_BLACKOILWELLMODEL_NETWORK_IMPL_HEADER_INCLUDED
#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)