WellInterface_impl.hpp
Go to the documentation of this file.
1/*
2 Copyright 2017 SINTEF Digital, Mathematics and Cybernetics.
3 Copyright 2017 Statoil ASA.
4 Copyright 2018 IRIS
5
6 This file is part of the Open Porous Media project (OPM).
7
8 OPM is free software: you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation, either version 3 of the License, or
11 (at your option) any later version.
12
13 OPM is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
17
18 You should have received a copy of the GNU General Public License
19 along with OPM. If not, see <http://www.gnu.org/licenses/>.
20*/
21
22#ifndef OPM_WELLINTERFACE_IMPL_HEADER_INCLUDED
23#define OPM_WELLINTERFACE_IMPL_HEADER_INCLUDED
24
25// Improve IDE experience
26#ifndef OPM_WELLINTERFACE_HEADER_INCLUDED
27#include <config.h>
29#endif
30
31#include <opm/common/Exceptions.hpp>
32
33#include <opm/input/eclipse/Schedule/ScheduleTypes.hpp>
34#include <opm/input/eclipse/Schedule/Well/WDFAC.hpp>
35#include <opm/input/eclipse/Schedule/Well/WELDRAW.hpp>
36
38
44
45#include <dune/common/version.hh>
46
47#include <algorithm>
48#include <cassert>
49#include <cstddef>
50#include <numbers>
51#include <utility>
52
53#include <fmt/format.h>
54
55namespace Opm
56{
57
58
59 template<typename TypeTag>
61 WellInterface(const Well& well,
62 const ParallelWellInfo<Scalar>& pw_info,
63 const int time_step,
64 const ModelParameters& param,
65 const RateConverterType& rate_converter,
66 const int pvtRegionIdx,
67 const int num_conservation_quantities,
68 const int num_phases,
69 const int index_of_well,
70 const std::vector<PerforationData<Scalar>>& perf_data)
72 pw_info,
73 time_step,
74 param,
75 rate_converter,
76 pvtRegionIdx,
77 num_conservation_quantities,
78 num_phases,
79 index_of_well,
80 perf_data)
81 {
83
84 if constexpr (has_solvent || has_zFraction) {
85 if (well.isInjector()) {
86 auto injectorType = this->well_ecl_.injectorType();
87 if (injectorType == InjectorType::GAS) {
88 this->wsolvent_ = this->well_ecl_.getSolventFraction();
89 }
90 }
91 }
92 }
93
94
95 template<typename TypeTag>
96 void
98 init(const std::vector<Scalar>& /* depth_arg */,
99 const Scalar gravity_arg,
100 const std::vector<Scalar>& B_avg,
101 const bool changed_to_open_this_step)
102 {
103 this->gravity_ = gravity_arg;
104 B_avg_ = B_avg;
105 this->changed_to_open_this_step_ = changed_to_open_this_step;
106 }
107
108
109
110
111 template<typename TypeTag>
114 wpolymer() const
115 {
116 if constexpr (has_polymer) {
117 return this->wpolymer_();
118 }
119
120 return 0.0;
121 }
122
123
124
125
126
127 template<typename TypeTag>
130 wfoam() const
131 {
132 if constexpr (has_foam) {
133 return this->wfoam_();
134 }
135
136 return 0.0;
137 }
138
139
140
141 template<typename TypeTag>
144 wsalt() const
145 {
146 if constexpr (has_brine) {
147 return this->wsalt_();
148 }
149
150 return 0.0;
151 }
152
153 template<typename TypeTag>
156 wmicrobes() const
157 {
158 if constexpr (has_micp) {
159 return this->wmicrobes_();
160 }
161
162 return 0.0;
163 }
164
165 template<typename TypeTag>
168 woxygen() const
169 {
170 if constexpr (has_micp) {
171 return this->woxygen_();
172 }
173
174 return 0.0;
175 }
176
177 template<typename TypeTag>
180 wurea() const
181 {
182 if constexpr (has_micp) {
183 return this->wurea_();
184 }
185
186 return 0.0;
187 }
188
189 template<typename TypeTag>
190 bool
192 updateWellControl(const Simulator& simulator,
193 const IndividualOrGroup iog,
194 const GroupStateHelperType& groupStateHelper,
195 WellStateType& well_state) /* const */
196 {
197 auto& deferred_logger = groupStateHelper.deferredLogger();
198 OPM_TIMEFUNCTION();
199 if (stoppedOrZeroRateTarget(groupStateHelper)) {
200 return false;
201 }
202
203 const auto& summaryState = simulator.vanguard().summaryState();
204 const auto& schedule = simulator.vanguard().schedule();
205 const auto& well = this->well_ecl_;
206 auto& ws = well_state.well(this->index_of_well_);
207 std::string from;
208 bool is_grup = false;
209 if (well.isInjector()) {
210 from = WellInjectorCMode2String(ws.injection_cmode);
211 is_grup = ws.injection_cmode == Well::InjectorCMode::GRUP;
212 } else {
213 from = WellProducerCMode2String(ws.production_cmode);
214 is_grup = ws.production_cmode == Well::ProducerCMode::GRUP;
215 }
216
217 const int episodeIdx = simulator.episodeIndex();
218 const auto& iterCtx = simulator.problem().iterationContext();
219 const int nupcol = schedule[episodeIdx].nupcol();
220 const bool oscillating =
221 std::ranges::count(this->well_control_log_, from) >= this->param_.max_number_of_well_switches_;
222 if (oscillating && !is_grup) { // we would like to avoid ending up as GRUP
223 // only output first time
224 const bool output =
225 std::ranges::count(this->well_control_log_, from) == this->param_.max_number_of_well_switches_;
226 if (output) {
227 const auto msg = fmt::format(" The control mode for well {} is oscillating. \n"
228 "We don't allow for more than {} switches after NUPCOL iterations. (NUPCOL = {}) \n"
229 "The control is kept at {}.",
230 this->name(), this->param_.max_number_of_well_switches_, nupcol, from);
231 deferred_logger.info(msg);
232 // add one more to avoid outputting the same info again
233 this->well_control_log_.push_back(from);
234 }
235 return false;
236 }
237 bool changed = false;
238 if (iog == IndividualOrGroup::Individual) {
239 changed = this->checkIndividualConstraints(ws, summaryState, deferred_logger);
240 } else if (iog == IndividualOrGroup::Group) {
241 changed = this->checkGroupConstraints(
242 groupStateHelper, schedule, summaryState, true, well_state
243 );
244 } else {
245 assert(iog == IndividualOrGroup::Both);
246 changed = this->checkConstraints(groupStateHelper, schedule, summaryState, well_state);
247 }
248 Parallel::Communication cc = simulator.vanguard().grid().comm();
249 // checking whether control changed
250 if (changed) {
251 std::string to;
252 if (well.isInjector()) {
253 to = WellInjectorCMode2String(ws.injection_cmode);
254 } else {
255 to = WellProducerCMode2String(ws.production_cmode);
256 }
257 std::ostringstream ss;
258 ss << " Switching control mode for well " << this->name()
259 << " from " << from
260 << " to " << to;
261 if (iterCtx.inLocalSolve()) {
262 ss << " (NLDD domain solve)";
263 }
264 if (cc.size() > 1) {
265 ss << " on rank " << cc.rank();
266 }
267 deferred_logger.debug(ss.str());
268
269 // We always store the current control as it is used for output
270 // and only after iteration >= nupcol
271 // we log all switches to check if the well controls oscillates.
272 // Skip logging during NLDD local solves to avoid exhausting the
273 // global oscillation budget with provisional domain-level switches.
274 if (!iterCtx.inLocalSolve()) {
275 if (!iterCtx.withinNupcol(nupcol) || this->well_control_log_.empty()) {
276 this->well_control_log_.push_back(from);
277 }
278 }
279 updateWellStateWithTarget(simulator, groupStateHelper, well_state);
280 updatePrimaryVariables(groupStateHelper);
281 }
282
283 return changed;
284 }
285
286 template<typename TypeTag>
287 void
289 updateWeldrawMaxRate(const Simulator& simulator,
290 WellStateType& well_state,
291 DeferredLogger& deferred_logger) const
292 {
293 if (!this->isProducer()) {
294 return;
295 }
296
297 auto& ws = well_state.well(this->index_of_well_);
298 const auto& weldraw = this->well_ecl_.getWELDRAW();
299 if (!weldraw.active()) {
300 ws.weldraw_max_rate.reset();
301 ws.weldraw_cmode.reset();
302 return;
303 }
304
305 const auto& summary_state = simulator.vanguard().summaryState();
306 const Scalar max_draw = this->well_ecl_.weldrawMaxDrawdown(summary_state);
307 if (!(max_draw > 0.0)) {
308 ws.weldraw_max_rate.reset();
309 ws.weldraw_cmode.reset();
310 return;
311 }
312
313 // The IPR b-coefficients are the surface-rate coefficients with
314 // respect to the drawdown, sum_j Tw_j * mob_j / B_j, summed over the
315 // well's connections. A standard well leaves crossflowing
316 // connections out of that sum while a multisegment well does not, so
317 // the cap of a multisegment well with crossflow is the more lenient
318 // of the two. The terms are non-negative either way, so this cannot
319 // change the sign of the sum below.
320 this->updateIPR(simulator, deferred_logger);
321
322 auto phase_coeff = [this](const unsigned phase_idx) -> Scalar {
323 const unsigned comp_idx = FluidSystem::canonicalToActiveCompIdx(
324 FluidSystem::solventComponentIndex(phase_idx));
325 return this->ipr_b_[comp_idx];
326 };
327
328 Scalar coeff = 0.0;
329 const bool gas_target = (weldraw.targetPhase() == WELDRAW::TargetPhase::GAS);
330 if (gas_target) {
331 if (FluidSystem::phaseIsActive(FluidSystem::gasPhaseIdx)) {
332 coeff += phase_coeff(FluidSystem::gasPhaseIdx);
333 }
334 }
335 else {
336 if (FluidSystem::phaseIsActive(FluidSystem::oilPhaseIdx)) {
337 coeff += phase_coeff(FluidSystem::oilPhaseIdx);
338 }
339 if (FluidSystem::phaseIsActive(FluidSystem::waterPhaseIdx)) {
340 coeff += phase_coeff(FluidSystem::waterPhaseIdx);
341 }
342 }
343
344 if (!(coeff > 0.0)) {
345 // The target phase cannot flow at any drawdown, because it is
346 // inactive, because it has no mobility in any connection, or,
347 // for a standard well, because every connection is crossflowing
348 // and hence left out of the sum. Imposing Qmax = 0 would
349 // silently stop the well, so treat the limit as inactive.
350 deferred_logger.warning("WELDRAW_NO_TARGET_PHASE_MOBILITY",
351 fmt::format("Well {}: the WELDRAW target phase ({}) has no "
352 "producible mobility; the drawdown limit is ignored.",
353 this->name(), gas_target ? "GAS" : "LIQ"));
354 ws.weldraw_max_rate.reset();
355 ws.weldraw_cmode.reset();
356 return;
357 }
358
359 const Scalar max_rate = max_draw * coeff;
360 ws.weldraw_max_rate = max_rate;
361
362 // Remember the rate control the limit is imposed through, but only
363 // while the limit is the more restrictive of the two: a well already
364 // held at a tighter target of its own is not under drawdown control.
365 const auto controls = this->well_ecl_.productionControls(summary_state);
366 const auto cmode = gas_target ? Well::ProducerCMode::GRAT
367 : Well::ProducerCMode::LRAT;
368 const Scalar own_target = gas_target ? controls.gas_rate
369 : controls.liquid_rate;
370 if (!controls.hasControl(cmode) || (max_rate <= own_target)) {
371 ws.weldraw_cmode = cmode;
372 }
373 else {
374 ws.weldraw_cmode.reset();
375 }
376 }
377
378 template<typename TypeTag>
379 bool
382 const GroupStateHelperType& groupStateHelper,
383 const Well::InjectionControls& inj_controls,
384 const Well::ProductionControls& prod_controls,
385 const Scalar wqTotal,
386 WellStateType& well_state,
387 const bool fixed_control,
388 const bool fixed_status,
389 const bool solving_with_zero_rate)
390 {
391 OPM_TIMEFUNCTION();
392 auto& deferred_logger = groupStateHelper.deferredLogger();
393 const auto& summary_state = simulator.vanguard().summaryState();
394 const auto& schedule = simulator.vanguard().schedule();
395 auto& ws = well_state.well(this->index_of_well_);
396 std::string from;
397 if (this->isInjector()) {
398 from = WellInjectorCMode2String(ws.injection_cmode);
399 } else {
400 from = WellProducerCMode2String(ws.production_cmode);
401 }
402 const bool oscillating =
403 std::ranges::count(this->well_control_log_, from) >= this->param_.max_number_of_well_switches_;
404
405 if (oscillating || this->wellUnderZeroRateTarget(groupStateHelper) || !(well_state.well(this->index_of_well_).status == WellStatus::OPEN)) {
406 return false;
407 }
408
409 const Scalar sgn = this->isInjector() ? 1.0 : -1.0;
410 if (!this->wellIsStopped()){
411 if (wqTotal*sgn <= 0.0 && !fixed_status){
412 this->stopWell();
413 return true;
414 } else {
415 bool changed = false;
416 if (!fixed_control) {
417 // When solving_with_zero_rate=true, fixed_control=true, so this block should never
418 // be entered.
419 if (solving_with_zero_rate) {
420 OPM_DEFLOG_THROW(std::runtime_error, fmt::format(
421 "Well {}: solving_with_zero_rate should not be true when fixed_control is false",
422 this->name()), deferred_logger);
423 }
424
425 // Changing to group controls here may lead to inconsistencies in the group handling which in turn
426 // may result in excessive back and forth switching. However, we currently allow this by default.
427 // The switch check_group_constraints_inner_well_iterations_ is a temporary solution.
428 const bool hasGroupControl = this->isInjector() ? inj_controls.hasControl(Well::InjectorCMode::GRUP) :
429 prod_controls.hasControl(Well::ProducerCMode::GRUP);
430 bool isGroupControl = ws.production_cmode == Well::ProducerCMode::GRUP || ws.injection_cmode == Well::InjectorCMode::GRUP;
431 if (! (isGroupControl && !this->param_.check_group_constraints_inner_well_iterations_)) {
432 changed = this->checkIndividualConstraints(ws, summary_state, deferred_logger, inj_controls, prod_controls);
433 }
434 if (hasGroupControl && this->param_.check_group_constraints_inner_well_iterations_) {
435 changed = changed || this->checkGroupConstraints(
436 groupStateHelper, schedule, summary_state, false, well_state
437 );
438 }
439
440 if (changed) {
441 const bool thp_controlled = this->isInjector() ? ws.injection_cmode == Well::InjectorCMode::THP :
442 ws.production_cmode == Well::ProducerCMode::THP;
443 if (thp_controlled){
444 ws.thp = this->getTHPConstraint(summary_state);
445 } else {
446 // don't call for thp since this might trigger additional local solve
447 updateWellStateWithTarget(simulator, groupStateHelper, well_state);
448 }
449 updatePrimaryVariables(groupStateHelper);
450 }
451 }
452 return changed;
453 }
454 } else if (!fixed_status){
455 // well is stopped, check if current bhp allows reopening
456 const Scalar bhp = well_state.well(this->index_of_well_).bhp;
457 Scalar prod_limit = prod_controls.bhp_limit;
458 Scalar inj_limit = inj_controls.bhp_limit;
459 const bool has_thp = this->wellHasTHPConstraints(summary_state);
460 if (has_thp){
461 std::vector<Scalar> rates(this->num_conservation_quantities_);
462 if (this->isInjector()){
463 const Scalar bhp_thp = WellBhpThpCalculator(*this).
464 calculateBhpFromThp(well_state, rates,
465 this->well_ecl_,
466 summary_state,
467 this->getRefDensity(),
468 deferred_logger);
469 inj_limit = std::min(bhp_thp, static_cast<Scalar>(inj_controls.bhp_limit));
470 } else {
471 // if the well can operate, it must at least be able to produce
472 // at the lowest bhp of the bhp-curve (explicit fractions)
473 const Scalar bhp_min = WellBhpThpCalculator(*this).
474 calculateMinimumBhpFromThp(well_state,
475 this->well_ecl_,
476 summary_state,
477 this->getRefDensity());
478 prod_limit = std::max(bhp_min, static_cast<Scalar>(prod_controls.bhp_limit));
479 }
480 }
481 const Scalar bhp_diff = (this->isInjector())? inj_limit - bhp: bhp - prod_limit;
482 if (bhp_diff > 0){
483 this->openWell();
484 well_state.well(this->index_of_well_).bhp = (this->isInjector())? inj_limit : prod_limit;
485 if (has_thp) {
486 well_state.well(this->index_of_well_).thp = this->getTHPConstraint(summary_state);
487 }
488 return true;
489 } else {
490 return false;
491 }
492 } else {
493 return false;
494 }
495 }
496
497 template<typename TypeTag>
498 void
500 wellTesting(const Simulator& simulator,
501 const double simulation_time,
502 const GroupStateHelperType& groupStateHelper,
503 WellStateType& well_state,
504 WellTestState& well_test_state,
505 GLiftEclWells& ecl_well_map,
506 std::map<std::string, double>& open_times)
507 {
508 OPM_TIMEFUNCTION();
509 auto& deferred_logger = groupStateHelper.deferredLogger();
510 const auto& group_state = groupStateHelper.groupState();
511 // A well test is run at the start of the time step, so this is also the
512 // instant the well resumes flowing if the test succeeds -- the mirror of
513 // the economic-limit messages, which report when a well stops flowing.
514 const auto& unit_system = simulator.vanguard().eclState().getUnits();
515 const auto start_time = simulator.vanguard().schedule().getStartTime();
516 const auto when =
517 fmt::format("at time {:.2f} {} (date = {})",
518 unit_system.from_si(UnitSystem::measure::time, simulation_time),
519 unit_system.name(UnitSystem::measure::time),
520 economicLimitDateString(start_time, simulation_time));
521
522 deferred_logger.info(fmt::format("Well {} is being tested {}.", this->name(), when));
523
524 GroupStateHelperType groupStateHelper_copy = groupStateHelper;
525 WellStateType well_state_copy = well_state;
526 // Ensure that groupStateHelper uses well_state_copy as WellState for the well testing
527 // and the guard ensures that the original well state is restored at scope exit, i.e. at
528 // the end of this function.
529 auto guard = groupStateHelper_copy.pushWellState(well_state_copy);
530 auto& ws = well_state_copy.well(this->indexOfWell());
531
532 const auto& summary_state = simulator.vanguard().summaryState();
533 const bool has_thp_limit = this->wellHasTHPConstraints(summary_state);
534 if (this->isProducer()) {
535 ws.production_cmode = has_thp_limit ? Well::ProducerCMode::THP : Well::ProducerCMode::BHP;
536 } else {
537 ws.injection_cmode = has_thp_limit ? Well::InjectorCMode::THP : Well::InjectorCMode::BHP;
538 }
539 // We test the well as an open well during the well testing
540 ws.open();
541
542 scaleSegmentRatesAndPressure(well_state_copy);
543 calculateExplicitQuantities(simulator, groupStateHelper_copy);
544 updatePrimaryVariables(groupStateHelper_copy);
545
546 if (this->isProducer()) {
547 const auto& schedule = simulator.vanguard().schedule();
548 const auto report_step = simulator.episodeIndex();
549 const auto& glo = schedule.glo(report_step);
550 if (glo.active()) {
551 gliftBeginTimeStepWellTestUpdateALQ(simulator,
552 well_state_copy,
553 group_state,
554 ecl_well_map,
555 deferred_logger);
556 }
557 }
558
559 WellTestState welltest_state_temp;
560 // Why a limit closed the well again. Empty when there is no reason to give.
561 std::string closure_reason;
562
563 // The test can fail to re-open the well at several points below, and they
564 // all report it through here. The outcome goes to the PRT; the reason only
565 // to the debug log, because a shut well is re-tested at every interval and
566 // this message recurs for as long as it stays shut.
567 auto notReopened = [this, &when, &deferred_logger](const std::string_view reason)
568 {
569 deferred_logger.info(
570 fmt::format("Well {} is not re-opened {}.", this->name(), when));
571 if (!reason.empty()) {
572 deferred_logger.debug(fmt::format("Because {}.", reason));
573 }
574 };
575
576 bool testWell = true;
577 // if a well is closed because all completions are closed, we need to check each completion
578 // individually. We first open all completions, then we close one by one by calling updateWellTestState
579 // untill the number of closed completions do not increase anymore.
580 while (testWell) {
581 const std::size_t original_number_closed_completions = welltest_state_temp.num_closed_completions();
582 bool converged = solveWellForTesting(simulator, groupStateHelper_copy, well_state_copy);
583 if (!converged) {
584 notReopened("the well equations could not be solved");
585 return;
586 }
587
588
589 updateWellOperability(simulator, well_state_copy, groupStateHelper_copy);
590 if ( !this->isOperableAndSolvable() ) {
591 notReopened("the well is not operable");
592 return;
593 }
594 std::vector<Scalar> potentials;
595 try {
596 computeWellPotentials(simulator, well_state_copy, groupStateHelper_copy, potentials);
597 } catch (const std::exception& e) {
598 notReopened(fmt::format("computing the well potentials failed: {}", e.what()));
599 return;
600 }
601 const int np = well_state_copy.numPhases();
602 for (int p = 0; p < np; ++p) {
603 ws.well_potentials[p] = std::max(Scalar{0.0}, potentials[p]);
604 }
605 const bool under_zero_target = this->wellUnderZeroGroupRateTarget(groupStateHelper_copy);
606 this->updateWellTestState(well_state_copy.well(this->indexOfWell()),
607 simulation_time,
608 /*writeMessageToOPMLog=*/ false,
609 /*during_well_test=*/ true,
610 under_zero_target,
611 welltest_state_temp,
612 simulator.vanguard().eclState().getUnits(),
613 simulator.vanguard().schedule().getStartTime(),
614 deferred_logger,
615 &closure_reason);
616 this->closeCompletions(welltest_state_temp);
617
618 // Stop testing if the well is closed or shut due to all completions shut
619 // Also check if number of completions has increased. If the number of closed completions do not increased
620 // we stop the testing.
621 // TODO: it can be tricky here, if the well is shut/closed due to other reasons
622 if ( welltest_state_temp.num_closed_wells() > 0 ||
623 (original_number_closed_completions == welltest_state_temp.num_closed_completions()) ) {
624 testWell = false; // this terminates the while loop
625 }
626 }
627
628 // update wellTestState if the well test succeeds
629 if (!welltest_state_temp.well_is_closed(this->name())) {
630 well_test_state.open_well(this->name());
631
632 const std::string& sep = economicLimitMessageSeparator();
633 deferred_logger.info(
634 fmt::format("{}\nWell {} is re-opened {}.\n{}",
635 sep, this->name(), when, sep));
636
637 // also reopen completions
638 for (const auto& completion : this->well_ecl_.getCompletions()) {
639 if (!welltest_state_temp.completion_is_closed(this->name(), completion.first))
640 well_test_state.open_completion(this->name(), completion.first);
641 }
642 well_state = well_state_copy;
643 open_times.try_emplace(this->name(), well_test_state.lastTestTime(this->name()));
644 }
645 else {
646 // A limit closed the well again: discard the tested state, stay shut.
647 notReopened(closure_reason);
648 }
649 }
650
651
652
653
654 template<typename TypeTag>
655 bool
657 iterateWellEquations(const Simulator& simulator,
658 const double dt,
659 const GroupStateHelperType& groupStateHelper,
660 WellStateType& well_state)
661 {
662 OPM_TIMEFUNCTION();
663 auto& deferred_logger = groupStateHelper.deferredLogger();
664
665 const auto& summary_state = simulator.vanguard().summaryState();
666 const auto& ws = well_state.well(this->indexOfWell());
667 const auto inj_controls = this->well_ecl_.isInjector() ? this->well_ecl_.injectionControls(summary_state) : Well::InjectionControls(0);
668 const auto prod_controls = this->well_ecl_.isProducer() ? this->productionControlsWithWeldraw(summary_state, ws) : Well::ProductionControls(0);
669 const auto pmode_orig = ws.production_cmode;
670 const auto imode_orig = ws.injection_cmode;
671 bool converged = false;
672 try {
673 // TODO: the following two functions will be refactored to be one to reduce the code duplication
674 if (!this->param_.local_well_solver_control_switching_){
675 converged = this->iterateWellEqWithControl(simulator, dt, inj_controls, prod_controls, groupStateHelper, well_state);
676 } else {
677 if (this->param_.use_implicit_ipr_ && this->well_ecl_.isProducer() && (well_state.well(this->index_of_well_).status == WellStatus::OPEN)) {
678 converged = solveWellWithOperabilityCheck(
679 simulator, dt, inj_controls, prod_controls, groupStateHelper, well_state
680 );
681 } else {
682 converged = this->iterateWellEqWithSwitching(
683 simulator, dt, inj_controls, prod_controls, groupStateHelper, well_state,
684 /*fixed_control=*/false, /*fixed_status=*/false, /*solving_with_zero_rate=*/false
685 );
686 }
687 }
688
689 } catch (NumericalProblem& e ) {
690 const std::string msg = "Inner well iterations failed for well " + this->name() + " Treat the well as unconverged. ";
691 deferred_logger.warning("INNER_ITERATION_FAILED", msg);
692 converged = false;
693 }
694 if (converged) {
695 // Add debug info for switched controls
696 if (ws.production_cmode != pmode_orig || ws.injection_cmode != imode_orig) {
697 std::string from,to;
698 if (this->isInjector()) {
699 from = WellInjectorCMode2String(imode_orig);
700 to = WellInjectorCMode2String(ws.injection_cmode);
701 } else {
702 from = WellProducerCMode2String(pmode_orig);
703 to = WellProducerCMode2String(ws.production_cmode);
704 }
705 const auto msg = fmt::format(" Well {} switched from {} to {} during local solve", this->name(), from, to);
706 deferred_logger.debug(msg);
707 const int episodeIdx = simulator.episodeIndex();
708 const auto& iterCtx = simulator.problem().iterationContext();
709 const auto& schedule = simulator.vanguard().schedule();
710 const int nupcol = schedule[episodeIdx].nupcol();
711 // We always store the current control as it is used for output
712 // and only after iteration >= nupcol
713 // we log all switches to check if the well controls oscillates
714 if (!iterCtx.withinNupcol(nupcol) || this->well_control_log_.empty()) {
715 this->well_control_log_.push_back(from);
716 }
717 }
718 }
719 // Add debug info for problematic group targets
720 if (this->isProducer() && ws.production_cmode == Well::ProducerCMode::GRUP && ws.use_group_target_fallback) {
721 assert(ws.group_target && ws.group_target_fallback);
722 const std::string cmode = Group::ProductionCMode2String(ws.group_target->production_cmode);
723 const std::string cmode_fallback = Group::ProductionCMode2String(ws.group_target_fallback->production_cmode);
724 const auto msg = fmt::format(" Well {} was solved using group target fallback mode {} as current group mode {} was not feasible.",
725 this->name(), cmode_fallback, cmode);
726 deferred_logger.debug(msg);
727 }
728
729 return converged;
730 }
731
732 template<typename TypeTag>
733 bool
736 const double dt,
737 const Well::InjectionControls& inj_controls,
738 const Well::ProductionControls& prod_controls,
739 const GroupStateHelperType& groupStateHelper,
740 WellStateType& well_state)
741 {
742 OPM_TIMEFUNCTION();
743 auto& deferred_logger = groupStateHelper.deferredLogger();
744
745 const auto& summary_state = simulator.vanguard().summaryState();
746 bool converged = true;
747 auto& ws = well_state.well(this->index_of_well_);
748 // if well is stopped, check if we can reopen with explicit fraction
749 if (this->wellIsStopped()) {
750 this->openWell();
751 const bool use_vfpexplicit = this->operability_status_.use_vfpexplicit;
752 this->operability_status_.use_vfpexplicit = true;
753 auto bhp_target = estimateOperableBhp(simulator, dt, groupStateHelper, summary_state, well_state);
754 if (!bhp_target.has_value()) {
755 // no intersection with ipr
756 const auto msg = fmt::format("estimateOperableBhp: Did not find operable BHP for well {}", this->name());
757 deferred_logger.debug(msg);
758 // well can't operate using explicit fractions stop the well
759 // solve with zero rates
760 converged = solveWellWithZeroRate(simulator, dt, groupStateHelper, well_state);
761 this->stopWell();
762 this->operability_status_.can_obtain_bhp_with_thp_limit = false;
763 this->operability_status_.obey_thp_limit_under_bhp_limit = false;
764 return converged;
765 } else {
766 // solve well with the estimated target bhp (or limit)
767 ws.thp = this->getTHPConstraint(summary_state);
768 const Scalar bhp = std::max(bhp_target.value(),
769 static_cast<Scalar>(prod_controls.bhp_limit));
770 solveWellWithBhp(simulator, dt, bhp, groupStateHelper, well_state);
771 this->operability_status_.use_vfpexplicit = use_vfpexplicit;
772 }
773 }
774 // solve well-equation
775 converged = this->iterateWellEqWithSwitching(
776 simulator, dt, inj_controls, prod_controls, groupStateHelper, well_state,
777 /*fixed_control=*/false, /*fixed_status=*/false, /*solving_with_zero_rate=*/false
778 );
779
780
781 const bool isThp = ws.production_cmode == Well::ProducerCMode::THP;
782 // check stability of solution under thp-control
783 if (converged && !stoppedOrZeroRateTarget(groupStateHelper) && isThp) {
784 auto rates = well_state.well(this->index_of_well_).surface_rates;
785 this->adaptRatesForVFP(rates);
786 this->updateIPRImplicit(simulator, groupStateHelper, well_state);
787 bool is_stable = WellBhpThpCalculator(*this).isStableSolution(well_state, this->well_ecl_, rates, summary_state);
788 if (!is_stable) {
789 // solution converged to an unstable point!
790 this->operability_status_.use_vfpexplicit = true;
791 auto bhp_stable = WellBhpThpCalculator(*this).estimateStableBhp(well_state, this->well_ecl_, rates, this->getRefDensity(), summary_state);
792 // if we find an intersection with a sufficiently lower bhp, re-solve equations
793 const Scalar reltol = 1e-3;
794 const Scalar cur_bhp = ws.bhp;
795 if (bhp_stable.has_value() && cur_bhp - bhp_stable.value() > cur_bhp*reltol){
796 const auto msg = fmt::format("Well {} converged to an unstable solution, re-solving", this->name());
797 deferred_logger.debug(msg);
798 solveWellWithBhp(
799 simulator, dt, bhp_stable.value(), groupStateHelper, well_state
800 );
801 // re-solve with hopefully good initial guess
802 ws.thp = this->getTHPConstraint(summary_state);
803 converged = this->iterateWellEqWithSwitching(
804 simulator, dt, inj_controls, prod_controls, groupStateHelper, well_state,
805 /*fixed_control=*/false, /*fixed_status=*/false, /*solving_with_zero_rate=*/false
806 );
807 }
808 }
809 }
810
811 if (!converged) {
812 // Well did not converge, switch to explicit fractions
813 this->operability_status_.use_vfpexplicit = true;
814 this->openWell();
815 auto bhp_target = estimateOperableBhp(
816 simulator, dt, groupStateHelper, summary_state, well_state
817 );
818 if (!bhp_target.has_value()) {
819 // solve with zero rate
820 // well can't operate using explicit fractions stop the well
821 converged = solveWellWithZeroRate(simulator, dt, groupStateHelper, well_state);
822 this->stopWell();
823 this->operability_status_.can_obtain_bhp_with_thp_limit = false;
824 this->operability_status_.obey_thp_limit_under_bhp_limit = false;
825 return converged;
826 } else {
827 // solve well with the estimated target bhp (or limit)
828 const Scalar bhp = std::max(bhp_target.value(),
829 static_cast<Scalar>(prod_controls.bhp_limit));
830 solveWellWithBhp(
831 simulator, dt, bhp, groupStateHelper, well_state
832 );
833 ws.thp = this->getTHPConstraint(summary_state);
834 const auto msg = fmt::format("Well {} did not converge, re-solving with explicit fractions for VFP caculations.", this->name());
835 deferred_logger.debug(msg);
836 converged = this->iterateWellEqWithSwitching(simulator, dt,
837 inj_controls,
838 prod_controls,
839 groupStateHelper,
840 well_state,
841 /*fixed_control=*/false,
842 /*fixed_status=*/false,
843 /*solving_with_zero_rate=*/false);
844 }
845 }
846 // update operability
847 this->operability_status_.can_obtain_bhp_with_thp_limit = !this->wellIsStopped();
848 this->operability_status_.obey_thp_limit_under_bhp_limit = !this->wellIsStopped();
849 return converged;
850 }
851
852 template<typename TypeTag>
853 std::optional<typename WellInterface<TypeTag>::Scalar>
855 estimateOperableBhp(const Simulator& simulator,
856 const double dt,
857 const GroupStateHelperType& groupStateHelper,
858 const SummaryState& summary_state,
859 WellStateType& well_state)
860 {
861 if (!this->wellHasTHPConstraints(summary_state)) {
862 const Scalar bhp_limit = WellBhpThpCalculator(*this).mostStrictBhpFromBhpLimits(summary_state);
863 const bool converged = solveWellWithBhp(
864 simulator, dt, bhp_limit, groupStateHelper, well_state
865 );
866 if (!converged || this->wellIsStopped()) {
867 return std::nullopt;
868 }
869
870 return bhp_limit;
871 }
872 OPM_TIMEFUNCTION();
873 // Given an unconverged well or closed well, estimate an operable bhp (if any)
874 // Get minimal bhp from vfp-curve
875 Scalar bhp_min = WellBhpThpCalculator(*this).calculateMinimumBhpFromThp(well_state, this->well_ecl_, summary_state, this->getRefDensity());
876 // Solve
877 const bool converged = solveWellWithBhp(
878 simulator, dt, bhp_min, groupStateHelper, well_state
879 );
880 if (!converged || this->wellIsStopped()) {
881 return std::nullopt;
882 }
883 this->updateIPRImplicit(simulator, groupStateHelper, well_state);
884 auto rates = well_state.well(this->index_of_well_).surface_rates;
885 this->adaptRatesForVFP(rates);
886 return WellBhpThpCalculator(*this).estimateStableBhp(well_state, this->well_ecl_, rates, this->getRefDensity(), summary_state);
887 }
888
889 template<typename TypeTag>
890 bool
892 solveWellWithBhp(const Simulator& simulator,
893 const double dt,
894 const Scalar bhp,
895 const GroupStateHelperType& groupStateHelper,
896 WellStateType& well_state)
897 {
898 OPM_TIMEFUNCTION();
899
900 // Solve a well using single bhp-constraint (but close if not operable under this)
901 auto group_state = GroupState<Scalar>(); // empty group
902 GroupStateHelperType groupStateHelper_copy = groupStateHelper;
903 // Ensure that groupStateHelper_copy uses the empty group state as GroupState for iterateWellEqWithSwitching()
904 // and the guard ensures that the original group state is restored at scope exit, i.e. at
905 // the end of this function.
906 auto group_guard = groupStateHelper_copy.pushGroupState(group_state);
907
908 auto inj_controls = Well::InjectionControls(0);
909 auto prod_controls = Well::ProductionControls(0);
910 auto& ws = well_state.well(this->index_of_well_);
911 auto cmode_inj = ws.injection_cmode;
912 auto cmode_prod = ws.production_cmode;
913 if (this->isInjector()) {
914 inj_controls.addControl(Well::InjectorCMode::BHP);
915 inj_controls.bhp_limit = bhp;
916 inj_controls.cmode = Well::InjectorCMode::BHP;
917 ws.injection_cmode = Well::InjectorCMode::BHP;
918 } else {
919 prod_controls.addControl(Well::ProducerCMode::BHP);
920 prod_controls.bhp_limit = bhp;
921 prod_controls.cmode = Well::ProducerCMode::BHP;
922 ws.production_cmode = Well::ProducerCMode::BHP;
923 }
924 // update well-state
925 ws.bhp = bhp;
926 // solve
927 const bool converged = this->iterateWellEqWithSwitching(
928 simulator, dt, inj_controls, prod_controls, groupStateHelper_copy,
929 well_state,
930 /*fixed_control=*/true,
931 /*fixed_status=*/false,
932 /*solving_with_zero_rate=*/false
933 );
934 ws.injection_cmode = cmode_inj;
935 ws.production_cmode = cmode_prod;
936 return converged;
937 }
938
939 template<typename TypeTag>
940 bool
942 solveWellWithZeroRate(const Simulator& simulator,
943 const double dt,
944 const GroupStateHelperType& groupStateHelper,
945 WellStateType& well_state)
946 {
947 OPM_TIMEFUNCTION();
948
949 // Solve a well as stopped with isolation (empty group state for assembly)
950 const auto well_status_orig = this->wellStatus_;
951 this->stopWell();
952
953 auto inj_controls = Well::InjectionControls(0);
954 auto prod_controls = Well::ProductionControls(0);
955
956 // Solve with well isolation - the flag "solving_with_zero_rate=true" will be passed down to
957 // assembleWellEqWithoutIterationImpl() to create an empty group state when assembling the
958 // well equations.
959 const bool converged = this->iterateWellEqWithSwitching(
960 simulator, dt, inj_controls, prod_controls,
961 groupStateHelper,
962 well_state,
963 /*fixed_control*/true,
964 /*fixed_status*/true,
965 /*solving_with_zero_rate*/true
966 );
967 this->wellStatus_ = well_status_orig;
968 return converged;
969 }
970
971 template<typename TypeTag>
972 bool
974 solveWellForTesting(const Simulator& simulator,
975 const GroupStateHelperType& groupStateHelper,
976 WellStateType& well_state)
977 {
978 OPM_TIMEFUNCTION();
979 auto& deferred_logger = groupStateHelper.deferredLogger();
980
981 const double dt = simulator.timeStepSize();
982
983 const auto& summary_state = simulator.vanguard().summaryState();
984 auto inj_controls = this->well_ecl_.isInjector() ? this->well_ecl_.injectionControls(summary_state) : Well::InjectionControls(0);
985 auto prod_controls = this->well_ecl_.isProducer() ? this->well_ecl_.productionControls(summary_state) : Well::ProductionControls(0);
986 this->onlyKeepBHPandTHPcontrols(summary_state, well_state, inj_controls, prod_controls);
987
988 bool converged = false;
989 try {
990 // TODO: the following two functions will be refactored to be one to reduce the code duplication
991 if (!this->param_.local_well_solver_control_switching_){
992 converged = this->iterateWellEqWithControl(
993 simulator, dt, inj_controls, prod_controls, groupStateHelper, well_state
994 );
995 } else {
996 if (this->param_.use_implicit_ipr_ && this->well_ecl_.isProducer() && (well_state.well(this->index_of_well_).status == WellStatus::OPEN)) {
997 converged = this->solveWellWithOperabilityCheck(
998 simulator, dt, inj_controls, prod_controls, groupStateHelper, well_state
999 );
1000 } else {
1001 converged = this->iterateWellEqWithSwitching(
1002 simulator, dt, inj_controls, prod_controls, groupStateHelper, well_state,
1003 /*fixed_control=*/false,
1004 /*fixed_status=*/false,
1005 /*solving_with_zero_rate=*/false
1006 );
1007 }
1008 }
1009
1010 } catch (NumericalProblem& e ) {
1011 const std::string msg = "Inner well iterations failed for well " + this->name() + " Treat the well as unconverged. ";
1012 deferred_logger.warning("INNER_ITERATION_FAILED", msg);
1013 converged = false;
1014 }
1015
1016 if (converged) {
1017 deferred_logger.debug("WellTest: Well equation for well " + this->name() + " converged");
1018 return true;
1019 }
1020 const int max_iter = this->param_.max_welleq_iter_;
1021 deferred_logger.debug("WellTest: Well equation for well " + this->name() + " failed converging in "
1022 + std::to_string(max_iter) + " iterations");
1023 return false;
1024 }
1025
1026
1027 template<typename TypeTag>
1028 void
1030 solveWellEquation(const Simulator& simulator,
1031 const GroupStateHelperType& groupStateHelper,
1032 WellStateType& well_state)
1033 {
1034 OPM_TIMEFUNCTION();
1035 auto& deferred_logger = groupStateHelper.deferredLogger();
1036 if (!this->isOperableAndSolvable() && !this->wellIsStopped())
1037 return;
1038
1039 // keep a copy of the original well state
1040 const WellStateType well_state0 = well_state;
1041 const double dt = simulator.timeStepSize();
1042 bool converged = iterateWellEquations(simulator, dt, groupStateHelper, well_state);
1043
1044 // Newly opened wells with THP control sometimes struggles to
1045 // converge due to bad initial guess. Or due to the simple fact
1046 // that the well needs to change to another control.
1047 // We therefore try to solve the well with BHP control to get
1048 // an better initial guess.
1049 // If the well is supposed to operate under THP control
1050 // "updateWellControl" will switch it back to THP later.
1051 if (!converged) {
1052 auto& ws = well_state.well(this->indexOfWell());
1053 bool thp_control = false;
1054 if (this->well_ecl_.isInjector()) {
1055 thp_control = ws.injection_cmode == Well::InjectorCMode::THP;
1056 if (thp_control) {
1057 ws.injection_cmode = Well::InjectorCMode::BHP;
1058 if (this->well_control_log_.empty()) { // only log the first control
1059 this->well_control_log_.push_back(WellInjectorCMode2String(Well::InjectorCMode::THP));
1060 }
1061 }
1062 } else {
1063 thp_control = ws.production_cmode == Well::ProducerCMode::THP;
1064 if (thp_control) {
1065 ws.production_cmode = Well::ProducerCMode::BHP;
1066 if (this->well_control_log_.empty()) { // only log the first control
1067 this->well_control_log_.push_back(WellProducerCMode2String(Well::ProducerCMode::THP));
1068 }
1069 }
1070 }
1071 if (thp_control) {
1072 const std::string msg = std::string("The newly opened well ") + this->name()
1073 + std::string(" with THP control did not converge during inner iterations, we try again with bhp control");
1074 deferred_logger.debug(msg);
1075 converged = this->iterateWellEquations(simulator, dt, groupStateHelper, well_state);
1076 }
1077 }
1078
1079 if (!converged) {
1080 const int max_iter = this->param_.max_welleq_iter_;
1081 deferred_logger.debug("Compute initial well solution for well " + this->name() + ". Failed to converge in "
1082 + std::to_string(max_iter) + " iterations");
1083 well_state = well_state0;
1084 }
1085 }
1086
1087
1088
1089 template <typename TypeTag>
1090 void
1092 assembleWellEq(const Simulator& simulator,
1093 const double dt,
1094 const GroupStateHelperType& groupStateHelper,
1095 WellStateType& well_state)
1096 {
1097 OPM_TIMEFUNCTION();
1098 prepareWellBeforeAssembling(simulator, dt, groupStateHelper, well_state);
1099 assembleWellEqWithoutIteration(simulator, groupStateHelper, dt, well_state,
1100 /*solving_with_zero_rate=*/false);
1101 }
1102
1103
1104
1105 template <typename TypeTag>
1106 void
1109 const GroupStateHelperType& groupStateHelper,
1110 const double dt,
1111 WellStateType& well_state,
1112 const bool solving_with_zero_rate)
1113 {
1114 OPM_TIMEFUNCTION();
1115 const auto& summary_state = simulator.vanguard().summaryState();
1116 const auto inj_controls = this->well_ecl_.isInjector() ? this->well_ecl_.injectionControls(summary_state) : Well::InjectionControls(0);
1117 const auto prod_controls = this->well_ecl_.isProducer()
1118 ? this->productionControlsWithWeldraw(summary_state, well_state.well(this->index_of_well_))
1119 : Well::ProductionControls(0);
1120 // TODO: the reason to have inj_controls and prod_controls in the arguments, is that we want to change the control used for the well functions
1121 // TODO: maybe we can use std::optional or pointers to simplify here
1122 assembleWellEqWithoutIteration(simulator, groupStateHelper, dt, inj_controls, prod_controls, well_state, solving_with_zero_rate);
1123 }
1124
1125
1126
1127 template<typename TypeTag>
1128 void
1131 DeferredLogger& deferred_logger) const
1132 {
1133 // Get scaled well fractions from derived class
1134 std::vector<Scalar> scaled_well_fractions(FluidSystem::numPhases, 0.0);
1135 this->getScaledWellFractions(scaled_well_fractions, deferred_logger);
1136 // Call the base class method
1137 this->Base::updateGroupTargetFallbackFlag(well_state, scaled_well_fractions, deferred_logger);
1138 }
1139
1140
1141
1142 template<typename TypeTag>
1143 void
1146 const double dt,
1147 const GroupStateHelperType& groupStateHelper,
1148 WellStateType& well_state)
1149 {
1150 OPM_TIMEFUNCTION();
1151 auto& deferred_logger = groupStateHelper.deferredLogger();
1152 const bool old_well_operable = this->operability_status_.isOperableAndSolvable();
1153
1154 if (this->param_.check_well_operability_iter_)
1155 checkWellOperability(simulator, well_state, groupStateHelper);
1156
1157 // only use inner well iterations for the first newton iterations.
1158 const auto& iterCtx = simulator.problem().iterationContext();
1159 if (iterCtx.shouldRunInnerWellIterations(this->param_.max_niter_inner_well_iter_)) {
1160 const auto& ws = well_state.well(this->indexOfWell());
1161 const bool nonzero_rate_original =
1162 std::any_of(ws.surface_rates.begin(),
1163 ws.surface_rates.begin() + well_state.numPhases(),
1164 [](Scalar rate) { return rate != Scalar(0.0); });
1165
1166 this->operability_status_.solvable = true;
1167 if (number_of_well_reopenings_ >= this->param_.max_well_status_switch_) {
1168 // only output the first time
1169 if (number_of_well_reopenings_ == this->param_.max_well_status_switch_) {
1170 const std::string msg = fmt::format("well {} is oscillating between open and stop. \n"
1171 "We don't allow for more than {} re-openings "
1172 "and the well is therefore kept stopped.",
1173 this->name(), number_of_well_reopenings_);
1174 deferred_logger.debug(msg);
1175 changed_to_stopped_this_step_ = old_well_operable;
1176 } else {
1177 changed_to_stopped_this_step_ = false;
1178 }
1179 this->stopWell();
1180 bool converged_zero_rate = this->solveWellWithZeroRate(
1181 simulator, dt, groupStateHelper, well_state
1182 );
1183 if (this->param_.shut_unsolvable_wells_ && !converged_zero_rate ) {
1184 this->operability_status_.solvable = false;
1185 } else {
1186 this->operability_status_.can_obtain_bhp_with_thp_limit = false;
1187 this->operability_status_.obey_thp_limit_under_bhp_limit = false;
1188 }
1189 // we increse the number of reopenings to avoid output in the next iteration
1190 number_of_well_reopenings_++;
1191 return;
1192 }
1193 bool converged = this->iterateWellEquations(
1194 simulator, dt, groupStateHelper, well_state
1195 );
1196
1197 if (converged) {
1198 const bool zero_target = this->wellUnderZeroRateTarget(groupStateHelper);
1199 if (this->wellIsStopped() && !zero_target && nonzero_rate_original) {
1200 // Well had non-zero rate, but was stopped during local well-solve. We re-open the well
1201 // for the next global iteration, but if the zero rate persists, it will be stopped.
1202 // This logic is introduced to prevent/ameliorate stopped/revived oscillations
1203 this->operability_status_.resetOperability();
1204 this->openWell();
1205 deferred_logger.debug(" " + this->name() + " is re-opened after being stopped during local solve");
1206 number_of_well_reopenings_++;
1207 }
1208 } else {
1209 // unsolvable wells are treated as not operable and will not be solved for in this iteration.
1210 if (this->param_.shut_unsolvable_wells_) {
1211 this->operability_status_.solvable = false;
1212 }
1213 }
1214 }
1215 if (this->operability_status_.has_negative_potentials) {
1216 auto well_state_copy = well_state;
1217 std::vector<Scalar> potentials;
1218 try {
1219 computeWellPotentials(simulator, well_state_copy, groupStateHelper, potentials);
1220 } catch (const std::exception& e) {
1221 const std::string msg = fmt::format("well {}: computeWellPotentials() failed "
1222 "during attempt to recompute potentials for well: ",
1223 this->name(), e.what());
1224 deferred_logger.info(msg);
1225 this->operability_status_.has_negative_potentials = true;
1226 }
1227 auto& ws = well_state.well(this->indexOfWell());
1228 const int np = well_state.numPhases();
1229 for (int p = 0; p < np; ++p) {
1230 ws.well_potentials[p] = std::max(Scalar{0.0}, potentials[p]);
1231 }
1232 }
1233 this->changed_to_open_this_step_ = false;
1234 changed_to_stopped_this_step_ = false;
1235
1236 const bool well_operable = this->operability_status_.isOperableAndSolvable();
1237 if (!well_operable) {
1238 this->stopWell();
1239 try {
1240 this->solveWellWithZeroRate(
1241 simulator, dt, groupStateHelper, well_state
1242 );
1243 } catch (const std::exception& e) {
1244 const std::string msg = fmt::format("well {}: solveWellWithZeroRate() failed "
1245 "during attempt to solve with zero rate for well: ",
1246 this->name(), e.what());
1247 deferred_logger.info(msg);
1248 // we set the rate to zero to make sure the well dont contribute to the group rate
1249 auto& ws = well_state.well(this->indexOfWell());
1250 const int np = well_state.numPhases();
1251 for (int p = 0; p < np; ++p) {
1252 ws.surface_rates[p] = Scalar{0.0};
1253 }
1254 }
1255 if (old_well_operable) {
1256 const std::string ctx = iterCtx.inLocalSolve() ? " (NLDD domain solve)" : "";
1257 deferred_logger.debug(" well " + this->name() + " gets STOPPED during iteration" + ctx);
1258 changed_to_stopped_this_step_ = true;
1259 }
1260 } else if (well_state.isOpen(this->name())) {
1261 this->openWell();
1262 if (!old_well_operable) {
1263 const std::string ctx = iterCtx.inLocalSolve() ? " (NLDD domain solve)" : "";
1264 deferred_logger.debug(" well " + this->name() + " gets REVIVED during iteration" + ctx);
1265 this->changed_to_open_this_step_ = true;
1266 }
1267 }
1268 }
1269
1270 template<typename TypeTag>
1271 void
1272 WellInterface<TypeTag>::addCellRates(std::map<int, RateVector>& cellRates_) const
1273 {
1274 if(!this->operability_status_.solvable)
1275 return;
1276
1277 for (int perfIdx = 0; perfIdx < this->number_of_local_perforations_; ++perfIdx) {
1278 const auto cellIdx = this->cells()[perfIdx];
1279 const auto it = cellRates_.find(cellIdx);
1280 RateVector rates = (it == cellRates_.end()) ? 0.0 : it->second;
1281 for (auto i=0*RateVector::dimension; i < RateVector::dimension; ++i)
1282 {
1283 rates[i] += connectionRates_[perfIdx][i];
1284 }
1285 cellRates_.insert_or_assign(cellIdx, rates);
1286 }
1287 }
1288
1289 template<typename TypeTag>
1292 {
1293 for (int perfIdx = 0; perfIdx < this->number_of_local_perforations_; ++perfIdx) {
1294 if (this->cells()[perfIdx] == cellIdx) {
1295 const unsigned activeCompIdx = FluidSystem::canonicalToActiveCompIdx(FluidSystem::solventComponentIndex(phaseIdx));
1296 return connectionRates_[perfIdx][activeCompIdx].value();
1297 }
1298 }
1299 // this is not thread safe
1300 OPM_THROW(std::invalid_argument, "The well with name " + this->name()
1301 + " does not perforate cell " + std::to_string(cellIdx));
1302 return 0.0;
1303 }
1304
1305
1306
1307
1308 template<typename TypeTag>
1309 void
1311 checkWellOperability(const Simulator& simulator,
1312 const WellStateType& well_state,
1313 const GroupStateHelperType& groupStateHelper)
1314 {
1315 auto& deferred_logger = groupStateHelper.deferredLogger();
1316 OPM_TIMEFUNCTION();
1317 if (!this->param_.check_well_operability_) {
1318 return;
1319 }
1320
1321 if (this->wellIsStopped() && !changed_to_stopped_this_step_) {
1322 return;
1323 }
1324
1325 updateWellOperability(simulator, well_state, groupStateHelper);
1326 if (!this->operability_status_.isOperableAndSolvable()) {
1327 this->operability_status_.use_vfpexplicit = true;
1328 deferred_logger.debug("EXPLICIT_LOOKUP_VFP",
1329 "well not operable, trying with explicit vfp lookup: " + this->name());
1330 updateWellOperability(simulator, well_state, groupStateHelper);
1331 }
1332 }
1333
1334
1335
1336 template<typename TypeTag>
1337 void
1340 WellStateType& well_state,
1341 const GroupState<Scalar>& group_state,
1342 GLiftEclWells& ecl_well_map,
1343 DeferredLogger& deferred_logger)
1344 {
1345 OPM_TIMEFUNCTION();
1346 const auto& summary_state = simulator.vanguard().summaryState();
1347 const auto& well_name = this->name();
1348 if (!this->wellHasTHPConstraints(summary_state)) {
1349 const std::string msg = fmt::format("GLIFT WTEST: Well {} does not have THP constraints", well_name);
1350 deferred_logger.info(msg);
1351 return;
1352 }
1353 const auto& schedule = simulator.vanguard().schedule();
1354 const auto report_step_idx = simulator.episodeIndex();
1355 const auto& glo = schedule.glo(report_step_idx);
1356 if (!glo.has_well(well_name)) {
1357 const std::string msg = fmt::format(
1358 "GLIFT WTEST: Well {} : Gas lift not activated: "
1359 "WLIFTOPT is probably missing. Skipping.", well_name);
1360 deferred_logger.info(msg);
1361 return;
1362 }
1363 const auto& gl_well = glo.well(well_name);
1364
1365 // Use gas lift optimization to get ALQ for well test
1366 std::unique_ptr<GasLiftSingleWell> glift =
1367 initializeGliftWellTest_<GasLiftSingleWell>(simulator,
1368 well_state,
1369 group_state,
1370 ecl_well_map,
1371 deferred_logger);
1372 auto [wtest_alq, success] = glift->wellTestALQ();
1373 std::string msg;
1374 const auto& unit_system = schedule.getUnits();
1375 if (success) {
1376 well_state.well(well_name).alq_state.set(wtest_alq);
1377 msg = fmt::format(
1378 "GLIFT WTEST: Well {} : Setting ALQ to optimized value = {}",
1379 well_name, unit_system.from_si(UnitSystem::measure::gas_surface_rate, wtest_alq));
1380 }
1381 else {
1382 if (!gl_well.use_glo()) {
1383 msg = fmt::format(
1384 "GLIFT WTEST: Well {} : Gas lift optimization deactivated. Setting ALQ to WLIFTOPT item 3 = {}",
1385 well_name,
1386 unit_system.from_si(UnitSystem::measure::gas_surface_rate, well_state.well(well_name).alq_state.get()));
1387
1388 }
1389 else {
1390 msg = fmt::format(
1391 "GLIFT WTEST: Well {} : Gas lift optimization failed, no ALQ set.",
1392 well_name);
1393 }
1394 }
1395 deferred_logger.info(msg);
1396 }
1397
1398 template<typename TypeTag>
1399 void
1401 updateWellOperability(const Simulator& simulator,
1402 const WellStateType& well_state,
1403 const GroupStateHelperType& groupStateHelper)
1404 {
1405 auto& deferred_logger = groupStateHelper.deferredLogger();
1406 OPM_TIMEFUNCTION();
1407 if (this->param_.local_well_solver_control_switching_) {
1408 const bool success = updateWellOperabilityFromWellEq(simulator, groupStateHelper);
1409 if (!success) {
1410 this->operability_status_.solvable = false;
1411 deferred_logger.debug("Operability check using well equations did not converge for well "
1412 + this->name() + ". Mark the well as unsolvable." );
1413 }
1414 return;
1415 }
1416 this->operability_status_.resetOperability();
1417
1418 bool thp_controlled = this->isInjector() ? well_state.well(this->index_of_well_).injection_cmode == Well::InjectorCMode::THP:
1419 well_state.well(this->index_of_well_).production_cmode == Well::ProducerCMode::THP;
1420 bool bhp_controlled = this->isInjector() ? well_state.well(this->index_of_well_).injection_cmode == Well::InjectorCMode::BHP:
1421 well_state.well(this->index_of_well_).production_cmode == Well::ProducerCMode::BHP;
1422
1423 // Operability checking is not free
1424 // Only check wells under BHP and THP control
1425 bool check_thp = thp_controlled || this->operability_status_.thp_limit_violated_but_not_switched;
1426 if (check_thp || bhp_controlled) {
1427 updateIPR(simulator, deferred_logger);
1428 checkOperabilityUnderBHPLimit(well_state, simulator, deferred_logger);
1429 }
1430 // we do some extra checking for wells under THP control.
1431 if (check_thp) {
1432 checkOperabilityUnderTHPLimit(simulator, well_state, groupStateHelper);
1433 }
1434 }
1435
1436 template<typename TypeTag>
1437 bool
1440 const GroupStateHelperType& groupStateHelper)
1441 {
1442 OPM_TIMEFUNCTION();
1443 // only makes sense if we're using this parameter is true
1444 assert(this->param_.local_well_solver_control_switching_);
1445 this->operability_status_.resetOperability();
1446 GroupStateHelperType groupStateHelper_copy = groupStateHelper;
1447 WellStateType well_state_copy = groupStateHelper_copy.wellState();
1448 const double dt = simulator.timeStepSize();
1449 // Ensure that groupStateHelper uses well_state_copy as WellState for iterateWellEquations()
1450 // and the guard ensures that the original well state is restored at scope exit, i.e. at
1451 // the end of this function.
1452 auto guard = groupStateHelper_copy.pushWellState(well_state_copy);
1453 // equations should be converged at this stage, so only one it is needed
1454 bool converged = iterateWellEquations(simulator, dt, groupStateHelper_copy, well_state_copy);
1455 return converged;
1456 }
1457
1458 template<typename TypeTag>
1459 void
1461 scaleSegmentRatesAndPressure([[maybe_unused]] WellStateType& well_state) const
1462 {
1463 // only relevant for MSW
1464 }
1465
1466 template<typename TypeTag>
1467 void
1469 updateWellStateWithTarget(const Simulator& simulator,
1470 const GroupStateHelperType& groupStateHelper,
1471 WellStateType& well_state) const
1472 {
1473 OPM_TIMEFUNCTION();
1474 auto& deferred_logger = groupStateHelper.deferredLogger();
1475 // only bhp and wellRates are used to initilize the primaryvariables for standard wells
1476 const auto& well = this->well_ecl_;
1477 const int well_index = this->index_of_well_;
1478 auto& ws = well_state.well(well_index);
1479 const int np = well_state.numPhases();
1480 const auto& summaryState = simulator.vanguard().summaryState();
1481 const auto& schedule = simulator.vanguard().schedule();
1482
1483 // Discard old primary variables, the new well state
1484 // may not be anywhere near the old one.
1485 ws.primaryvar.resize(0);
1486
1487 if (this->wellIsStopped()) {
1488 for (int p = 0; p<np; ++p) {
1489 ws.surface_rates[p] = 0;
1490 }
1491 ws.thp = 0;
1492 return;
1493 }
1494
1495 if (this->isInjector() )
1496 {
1497 const auto& controls = well.injectionControls(summaryState);
1498
1499 InjectorType injectorType = controls.injector_type;
1500 int phasePos;
1501 switch (injectorType) {
1502 case InjectorType::WATER:
1503 {
1504 phasePos = FluidSystem::canonicalToActivePhaseIdx(FluidSystem::waterPhaseIdx);
1505 break;
1506 }
1507 case InjectorType::OIL:
1508 {
1509 phasePos = FluidSystem::canonicalToActivePhaseIdx(FluidSystem::oilPhaseIdx);
1510 break;
1511 }
1512 case InjectorType::GAS:
1513 {
1514 phasePos = FluidSystem::canonicalToActivePhaseIdx(FluidSystem::gasPhaseIdx);
1515 break;
1516 }
1517 default:
1518 OPM_DEFLOG_THROW(std::runtime_error, "Expected WATER, OIL or GAS as type for injectors " + this->name(), deferred_logger );
1519 }
1520
1521 const auto current = ws.injection_cmode;
1522
1523 switch (current) {
1524 case Well::InjectorCMode::RATE:
1525 {
1526 ws.surface_rates[phasePos] = (1.0 - this->rsRvInj()) * controls.surface_rate;
1527 if(this->rsRvInj() > 0) {
1528 if (injectorType == InjectorType::OIL && FluidSystem::phaseIsActive(FluidSystem::gasPhaseIdx)) {
1529 const int gas_pos = FluidSystem::canonicalToActivePhaseIdx(FluidSystem::gasPhaseIdx);
1530 ws.surface_rates[gas_pos] = controls.surface_rate * this->rsRvInj();
1531 } else if (injectorType == InjectorType::GAS && FluidSystem::phaseIsActive(FluidSystem::oilPhaseIdx)) {
1532 const int oil_pos = FluidSystem::canonicalToActivePhaseIdx(FluidSystem::oilPhaseIdx);
1533 ws.surface_rates[oil_pos] = controls.surface_rate * this->rsRvInj();
1534 } else {
1535 OPM_DEFLOG_THROW(std::runtime_error, "Expected OIL or GAS as type for injectors when RS/RV (item 10) is non-zero " + this->name(), deferred_logger );
1536 }
1537 }
1538 break;
1539 }
1540
1541 case Well::InjectorCMode::RESV:
1542 {
1543 std::vector<Scalar> convert_coeff(this->number_of_phases_, 1.0);
1544 this->rateConverter_.calcCoeff(/*fipreg*/ 0, this->pvtRegionIdx_, convert_coeff);
1545 const Scalar coeff = convert_coeff[phasePos];
1546 ws.surface_rates[phasePos] = controls.reservoir_rate/coeff;
1547 break;
1548 }
1549
1550 case Well::InjectorCMode::THP:
1551 {
1552 auto rates = ws.surface_rates;
1553 Scalar bhp = WellBhpThpCalculator(*this).calculateBhpFromThp(well_state,
1554 rates,
1555 well,
1556 summaryState,
1557 this->getRefDensity(),
1558 deferred_logger);
1559 ws.bhp = bhp;
1560 ws.thp = this->getTHPConstraint(summaryState);
1561
1562 // if the total rates are negative or zero
1563 // we try to provide a better intial well rate
1564 // using the well potentials
1565 Scalar total_rate = std::accumulate(rates.begin(), rates.end(), 0.0);
1566 if (total_rate <= 0.0)
1567 ws.surface_rates = ws.well_potentials;
1568
1569 break;
1570 }
1571 case Well::InjectorCMode::BHP:
1572 {
1573 ws.bhp = controls.bhp_limit;
1574 Scalar total_rate = 0.0;
1575 for (int p = 0; p<np; ++p) {
1576 total_rate += ws.surface_rates[p];
1577 }
1578 // if the total rates are negative or zero
1579 // we try to provide a better intial well rate
1580 // using the well potentials
1581 if (total_rate <= 0.0)
1582 ws.surface_rates = ws.well_potentials;
1583
1584 break;
1585 }
1586 case Well::InjectorCMode::GRUP:
1587 {
1588 assert(well.isAvailableForGroupControl());
1589 const auto& group = schedule.getGroup(well.groupName(), this->currentStep());
1590 const Scalar efficiencyFactor = well.getEfficiencyFactor() *
1591 well_state[well.name()].efficiency_scaling_factor;
1592 std::optional<Scalar> target =
1593 this->getGroupInjectionTargetRate(group,
1594 groupStateHelper,
1595 injectorType,
1596 efficiencyFactor);
1597 if (target)
1598 ws.surface_rates[phasePos] = *target;
1599 break;
1600 }
1601 case Well::InjectorCMode::CMODE_UNDEFINED:
1602 {
1603 OPM_DEFLOG_THROW(std::runtime_error, "Well control must be specified for well " + this->name(), deferred_logger );
1604 }
1605
1606 }
1607 // for wells with zero injection rate, if we assign exactly zero rate,
1608 // we will have to assume some trivial composition in the wellbore.
1609 // here, we use some small value (about 0.01 m^3/day ~= 1.e-7) to initialize
1610 // the zero rate target, then we can use to retain the composition information
1611 // within the wellbore from the previous result, and hopefully it is a good
1612 // initial guess for the zero rate target.
1613 ws.surface_rates[phasePos] = std::max(Scalar{1.e-7}, ws.surface_rates[phasePos]);
1614
1615 if (ws.bhp == 0.) {
1616 ws.bhp = controls.bhp_limit;
1617 }
1618 }
1619 //Producer
1620 else
1621 {
1622 const auto current = ws.production_cmode;
1623 const auto controls = this->productionControlsWithWeldraw(summaryState, ws);
1624 switch (current) {
1625 case Well::ProducerCMode::ORAT:
1626 {
1627 const int oil_pos = FluidSystem::canonicalToActivePhaseIdx(FluidSystem::oilPhaseIdx);
1628 Scalar current_rate = -ws.surface_rates[oil_pos];
1629 // for trivial rates or opposite direction we don't just scale the rates
1630 // but use either the potentials or the mobility ratio to initial the well rates
1631 if (current_rate > 0.0) {
1632 for (int p = 0; p<np; ++p) {
1633 ws.surface_rates[p] *= controls.oil_rate/current_rate;
1634 }
1635 } else {
1636 const std::vector<Scalar> fractions = initialWellRateFractions(simulator, well_state);
1637 double control_fraction = fractions[oil_pos];
1638 if (control_fraction != 0.0) {
1639 for (int p = 0; p<np; ++p) {
1640 ws.surface_rates[p] = - fractions[p] * controls.oil_rate/control_fraction;
1641 }
1642 }
1643 }
1644 break;
1645 }
1646 case Well::ProducerCMode::WRAT:
1647 {
1648 const int water_pos = FluidSystem::canonicalToActivePhaseIdx(FluidSystem::waterPhaseIdx);
1649 Scalar current_rate = -ws.surface_rates[water_pos];
1650 // for trivial rates or opposite direction we don't just scale the rates
1651 // but use either the potentials or the mobility ratio to initial the well rates
1652 if (current_rate > 0.0) {
1653 for (int p = 0; p<np; ++p) {
1654 ws.surface_rates[p] *= controls.water_rate/current_rate;
1655 }
1656 } else {
1657 const std::vector<Scalar> fractions = initialWellRateFractions(simulator, well_state);
1658 const Scalar control_fraction = fractions[water_pos];
1659 if (control_fraction != 0.0) {
1660 for (int p = 0; p<np; ++p) {
1661 ws.surface_rates[p] = - fractions[p] * controls.water_rate / control_fraction;
1662 }
1663 }
1664 }
1665 break;
1666 }
1667 case Well::ProducerCMode::GRAT:
1668 {
1669 const int gas_pos = FluidSystem::canonicalToActivePhaseIdx(FluidSystem::gasPhaseIdx);
1670 Scalar current_rate = -ws.surface_rates[gas_pos];
1671 // or trivial rates or opposite direction we don't just scale the rates
1672 // but use either the potentials or the mobility ratio to initial the well rates
1673 if (current_rate > 0.0) {
1674 for (int p = 0; p<np; ++p) {
1675 ws.surface_rates[p] *= controls.gas_rate/current_rate;
1676 }
1677 } else {
1678 const std::vector<Scalar > fractions = initialWellRateFractions(simulator, well_state);
1679 const Scalar control_fraction = fractions[gas_pos];
1680 if (control_fraction != 0.0) {
1681 for (int p = 0; p<np; ++p) {
1682 ws.surface_rates[p] = - fractions[p] * controls.gas_rate / control_fraction;
1683 }
1684 }
1685 }
1686
1687 break;
1688
1689 }
1690 case Well::ProducerCMode::LRAT:
1691 {
1692 const int water_pos = FluidSystem::canonicalToActivePhaseIdx(FluidSystem::waterPhaseIdx);
1693 const int oil_pos = FluidSystem::canonicalToActivePhaseIdx(FluidSystem::oilPhaseIdx);
1694 Scalar current_rate = - ws.surface_rates[water_pos]
1695 - ws.surface_rates[oil_pos];
1696 // or trivial rates or opposite direction we don't just scale the rates
1697 // but use either the potentials or the mobility ratio to initial the well rates
1698 if (current_rate > 0.0) {
1699 for (int p = 0; p<np; ++p) {
1700 ws.surface_rates[p] *= controls.liquid_rate/current_rate;
1701 }
1702 } else {
1703 const std::vector<Scalar> fractions = initialWellRateFractions(simulator, well_state);
1704 const Scalar control_fraction = fractions[water_pos] + fractions[oil_pos];
1705 if (control_fraction != 0.0) {
1706 for (int p = 0; p<np; ++p) {
1707 ws.surface_rates[p] = - fractions[p] * controls.liquid_rate / control_fraction;
1708 }
1709 }
1710 }
1711 break;
1712 }
1713 case Well::ProducerCMode::CRAT:
1714 {
1715 OPM_DEFLOG_THROW(std::runtime_error,
1716 fmt::format("CRAT control not supported, well {}", this->name()),
1717 deferred_logger);
1718 }
1719 case Well::ProducerCMode::RESV:
1720 {
1721 std::vector<Scalar> convert_coeff(this->number_of_phases_, 1.0);
1722 this->rateConverter_.calcCoeff(/*fipreg*/ 0, this->pvtRegionIdx_, ws.surface_rates, convert_coeff);
1723 Scalar total_res_rate = 0.0;
1724 for (int p = 0; p<np; ++p) {
1725 total_res_rate -= ws.surface_rates[p] * convert_coeff[p];
1726 }
1727 if (controls.prediction_mode) {
1728 // or trivial rates or opposite direction we don't just scale the rates
1729 // but use either the potentials or the mobility ratio to initial the well rates
1730 if (total_res_rate > 0.0) {
1731 for (int p = 0; p<np; ++p) {
1732 ws.surface_rates[p] *= controls.resv_rate/total_res_rate;
1733 }
1734 } else {
1735 const std::vector<Scalar> fractions = initialWellRateFractions(simulator, well_state);
1736 for (int p = 0; p<np; ++p) {
1737 ws.surface_rates[p] = - fractions[p] * controls.resv_rate / convert_coeff[p];
1738 }
1739 }
1740 } else {
1741 std::vector<Scalar> hrates(this->number_of_phases_,0.);
1742 if (FluidSystem::phaseIsActive(FluidSystem::waterPhaseIdx)) {
1743 const int phase_pos = FluidSystem::canonicalToActivePhaseIdx(FluidSystem::waterPhaseIdx);
1744 hrates[phase_pos] = controls.water_rate;
1745 }
1746 if (FluidSystem::phaseIsActive(FluidSystem::oilPhaseIdx)) {
1747 const int phase_pos = FluidSystem::canonicalToActivePhaseIdx(FluidSystem::oilPhaseIdx);
1748 hrates[phase_pos] = controls.oil_rate;
1749 }
1750 if (FluidSystem::phaseIsActive(FluidSystem::gasPhaseIdx)) {
1751 const int phase_pos = FluidSystem::canonicalToActivePhaseIdx(FluidSystem::gasPhaseIdx);
1752 hrates[phase_pos] = controls.gas_rate;
1753 }
1754 std::vector<Scalar> hrates_resv(this->number_of_phases_,0.);
1755 this->rateConverter_.calcReservoirVoidageRates(/*fipreg*/ 0, this->pvtRegionIdx_, hrates, hrates_resv);
1756 Scalar target = std::accumulate(hrates_resv.begin(), hrates_resv.end(), 0.0);
1757 // or trivial rates or opposite direction we don't just scale the rates
1758 // but use either the potentials or the mobility ratio to initial the well rates
1759 if (total_res_rate > 0.0) {
1760 for (int p = 0; p<np; ++p) {
1761 ws.surface_rates[p] *= target/total_res_rate;
1762 }
1763 } else {
1764 const std::vector<Scalar> fractions = initialWellRateFractions(simulator, well_state);
1765 for (int p = 0; p<np; ++p) {
1766 ws.surface_rates[p] = - fractions[p] * target / convert_coeff[p];
1767 }
1768 }
1769 }
1770 break;
1771 }
1772 case Well::ProducerCMode::BHP:
1773 {
1774 ws.bhp = controls.bhp_limit;
1775 Scalar total_rate = 0.0;
1776 for (int p = 0; p<np; ++p) {
1777 total_rate -= ws.surface_rates[p];
1778 }
1779 // if the total rates are negative or zero
1780 // we try to provide a better intial well rate
1781 // using the well potentials
1782 if (total_rate <= 0.0){
1783 for (int p = 0; p<np; ++p) {
1784 ws.surface_rates[p] = -ws.well_potentials[p];
1785 }
1786 }
1787 break;
1788 }
1789 case Well::ProducerCMode::THP:
1790 {
1791 const bool update_success = updateWellStateWithTHPTargetProd(simulator, well_state, groupStateHelper);
1792
1793 if (!update_success) {
1794 // the following is the original way of initializing well state with THP constraint
1795 // keeping it for robust reason in case that it fails to get a bhp value with THP constraint
1796 // more sophisticated design might be needed in the future
1797 auto rates = ws.surface_rates;
1798 this->adaptRatesForVFP(rates);
1800 well_state, rates, well, summaryState, this->getRefDensity(), deferred_logger);
1801 ws.bhp = bhp;
1802 ws.thp = this->getTHPConstraint(summaryState);
1803 // if the total rates are negative or zero
1804 // we try to provide a better initial well rate
1805 // using the well potentials
1806 const Scalar total_rate = -std::accumulate(rates.begin(), rates.end(), 0.0);
1807 if (total_rate <= 0.0) {
1808 for (int p = 0; p < this->number_of_phases_; ++p) {
1809 ws.surface_rates[p] = -ws.well_potentials[p];
1810 }
1811 }
1812 }
1813 break;
1814 }
1815 case Well::ProducerCMode::GRUP:
1816 {
1817 assert(well.isAvailableForGroupControl());
1818 this->updateGroupTargetFallbackFlag(well_state, deferred_logger);
1819 const auto& group = schedule.getGroup(well.groupName(), this->currentStep());
1820 const Scalar efficiencyFactor = well.getEfficiencyFactor() *
1821 well_state[well.name()].efficiency_scaling_factor;
1822 Scalar scale = this->getGroupProductionTargetRate(group,
1823 groupStateHelper,
1824 efficiencyFactor);
1825
1826 // we don't want to scale with zero and get zero rates.
1827 if (scale > 0) {
1828 for (int p = 0; p<np; ++p) {
1829 ws.surface_rates[p] *= scale;
1830 }
1831 ws.trivial_group_target = false;
1832 } else {
1833 // If group target is trivial we dont want to flip to other controls. To avoid oscillation we store
1834 // this information in the well state and explicitly check for this condition when evaluating well controls.
1835 ws.trivial_group_target = true;
1836 }
1837 break;
1838 }
1839 case Well::ProducerCMode::CMODE_UNDEFINED:
1841 {
1842 OPM_DEFLOG_THROW(std::runtime_error, "Well control must be specified for well " + this->name() , deferred_logger);
1843 break;
1844 }
1845 } // end of switch
1846
1847 if (ws.bhp == 0.) {
1848 ws.bhp = controls.bhp_limit;
1849 }
1850 }
1851 }
1852
1853 template<typename TypeTag>
1854 bool
1856 wellUnderZeroRateTarget(const GroupStateHelperType& groupStateHelper) const
1857 {
1858 OPM_TIMEFUNCTION();
1859 const auto& well_state = groupStateHelper.wellState();
1860 // Check if well is under zero rate control, either directly or from group
1861 const bool isGroupControlled = this->wellUnderGroupControl(well_state.well(this->index_of_well_));
1862 if (!isGroupControlled) {
1863 // well is not under group control, check "individual" version
1864 const auto& summaryState = groupStateHelper.summaryState();
1865 return this->wellUnderZeroRateTargetIndividual(summaryState, well_state);
1866 } else {
1867 return this->wellUnderZeroGroupRateTarget(groupStateHelper, isGroupControlled);
1868 }
1869 }
1870
1871 template <typename TypeTag>
1872 bool
1874 const std::optional<bool> group_control) const
1875 {
1876 const auto& well_state = groupStateHelper.wellState();
1877 // Check if well is under zero rate target from group
1878 const bool isGroupControlled = group_control.value_or(this->wellUnderGroupControl(well_state.well(this->index_of_well_)));
1879 if (isGroupControlled) {
1880 return this->zeroGroupRateTarget(groupStateHelper);
1881 }
1882 return false;
1883 }
1884
1885 template<typename TypeTag>
1886 bool
1888 stoppedOrZeroRateTarget(const GroupStateHelperType& groupStateHelper) const
1889 {
1890 // Check if well is stopped or under zero rate control, either
1891 // directly or from group.
1892 return this->wellIsStopped()
1893 || this->wellUnderZeroRateTarget(groupStateHelper);
1894 }
1895
1896 template<typename TypeTag>
1897 std::vector<typename WellInterface<TypeTag>::Scalar>
1899 initialWellRateFractions(const Simulator& simulator,
1900 const WellStateType& well_state) const
1901 {
1902 OPM_TIMEFUNCTION();
1903 const int np = this->number_of_phases_;
1904 std::vector<Scalar> scaling_factor(np);
1905 const auto& ws = well_state.well(this->index_of_well_);
1906
1907 Scalar total_potentials = 0.0;
1908 for (int p = 0; p<np; ++p) {
1909 total_potentials += ws.well_potentials[p];
1910 }
1911 if (total_potentials > 0) {
1912 for (int p = 0; p<np; ++p) {
1913 scaling_factor[p] = ws.well_potentials[p] / total_potentials;
1914 }
1915 return scaling_factor;
1916 }
1917 // if we don't have any potentials we weight it using the mobilites
1918 // We only need approximation so we don't bother with the vapporized oil and dissolved gas
1919 Scalar total_tw = 0;
1920 const int nperf = this->number_of_local_perforations_;
1921 for (int perf = 0; perf < nperf; ++perf) {
1922 total_tw += this->well_index_[perf];
1923 }
1924 total_tw = this->parallelWellInfo().communication().sum(total_tw);
1925
1926 for (int perf = 0; perf < nperf; ++perf) {
1927 const int cell_idx = this->well_cells_[perf];
1928 const auto& intQuants = simulator.model().intensiveQuantities(cell_idx, /*timeIdx=*/0);
1929 const auto& fs = intQuants.fluidState();
1930 const Scalar well_tw_fraction = this->well_index_[perf] / total_tw;
1931 Scalar total_mobility = 0.0;
1932 for (int p = 0; p < np; ++p) {
1933 const int canonical_phase_idx = FluidSystem::activeToCanonicalPhaseIdx(p);
1934 total_mobility += fs.invB(canonical_phase_idx).value() * intQuants.mobility(canonical_phase_idx).value();
1935 }
1936 for (int p = 0; p < np; ++p) {
1937 const int canonical_phase_idx = FluidSystem::activeToCanonicalPhaseIdx(p);
1938 scaling_factor[p] += well_tw_fraction * fs.invB(canonical_phase_idx).value() * intQuants.mobility(canonical_phase_idx).value() / total_mobility;
1939 }
1940 }
1941 return scaling_factor;
1942 }
1943
1944
1945
1946 template <typename TypeTag>
1947 void
1950 WellStateType& well_state,
1951 DeferredLogger& deferred_logger) const
1952 {
1953 assert(this->isProducer());
1954 OPM_TIMEFUNCTION();
1955 // Check if the rates of this well only are single-phase, do nothing
1956 // if more than one nonzero rate.
1957 auto& ws = well_state.well(this->index_of_well_);
1958 int nonzero_rate_index = -1;
1959 const Scalar floating_point_error_epsilon = 1e-14;
1960 for (int p = 0; p < this->number_of_phases_; ++p) {
1961 if (std::abs(ws.surface_rates[p]) > floating_point_error_epsilon) {
1962 if (nonzero_rate_index == -1) {
1963 nonzero_rate_index = p;
1964 } else {
1965 // More than one nonzero rate.
1966 return;
1967 }
1968 }
1969 }
1970
1971 // Calculate rates at bhp limit, or 1 bar if no limit.
1972 std::vector<Scalar> well_q_s(this->number_of_phases_, 0.0);
1973 bool rates_evaluated_at_1bar = false;
1974 {
1975 const auto& summary_state = simulator.vanguard().summaryState();
1976 const auto& prod_controls = this->well_ecl_.productionControls(summary_state);
1977 const double bhp_limit = std::max(prod_controls.bhp_limit, 1.0 * unit::barsa);
1978 this->computeWellRatesWithBhp(simulator, bhp_limit, well_q_s, deferred_logger);
1979 // Remember of we evaluated the rates at (approx.) 1 bar or not.
1980 rates_evaluated_at_1bar = (bhp_limit < 1.1 * unit::barsa);
1981 // Check that no rates are positive.
1982 if (std::ranges::any_of(well_q_s, [](Scalar q) { return q > 0.0; })) {
1983 // Did we evaluate at 1 bar? If not, then we can try again at 1 bar.
1984 if (!rates_evaluated_at_1bar) {
1985 this->computeWellRatesWithBhp(simulator, 1.0 * unit::barsa, well_q_s, deferred_logger);
1986 rates_evaluated_at_1bar = true;
1987 }
1988 // At this point we can only set the wrong-direction (if any) values to zero.
1989 for (auto& q : well_q_s) {
1990 q = std::min(q, Scalar{0.0});
1991 }
1992 }
1993 }
1994
1995 if (nonzero_rate_index == -1) {
1996 // No nonzero rates on input.
1997 // Use the computed rate directly, or scaled by a factor
1998 // 0.5 (to avoid too high values) if it was evaluated at 1 bar.
1999 const Scalar factor = rates_evaluated_at_1bar ? 0.5 : 1.0;
2000 for (int p = 0; p < this->number_of_phases_; ++p) {
2001 ws.surface_rates[p] = factor * well_q_s[p];
2002 }
2003 return;
2004 }
2005
2006 // If we are here, we had a single nonzero rate for the well,
2007 // typically from a rate constraint. We must make sure it is
2008 // respected, so if it was lower than the calculated rate for
2009 // the same phase we scale all rates to match.
2010 const Scalar initial_nonzero_rate = ws.surface_rates[nonzero_rate_index];
2011 const Scalar computed_rate = well_q_s[nonzero_rate_index];
2012 if (std::abs(initial_nonzero_rate) < std::abs(computed_rate)) {
2013 // Note that both rates below are negative. The factor should be < 1.0.
2014 const Scalar factor = initial_nonzero_rate / computed_rate;
2015 assert(factor < 1.0);
2016 for (int p = 0; p < this->number_of_phases_; ++p) {
2017 // We skip the nonzero_rate_index, as that should remain as it was.
2018 if (p != nonzero_rate_index) {
2019 ws.surface_rates[p] = factor * well_q_s[p];
2020 }
2021 }
2022 return;
2023 }
2024
2025 // If we are here, we had a single nonzero rate, but it was
2026 // higher than the one calculated from the bhp limit, so we
2027 // use the calculated rates.
2028 for (int p = 0; p < this->number_of_phases_; ++p) {
2029 ws.surface_rates[p] = well_q_s[p];
2030 }
2031 }
2032
2033 template <typename TypeTag>
2034 template<class Value>
2035 void
2037 getTw(std::vector<Value>& Tw,
2038 const int perf,
2039 const IntensiveQuantities& intQuants,
2040 const Value& trans_mult,
2041 const SingleWellStateType& ws) const
2042 {
2043 OPM_TIMEFUNCTION_LOCAL(Subsystem::Wells);
2044 // Add a Forchheimer term to the gas phase CTF if the run uses
2045 // either of the WDFAC or the WDFACCOR keywords.
2046 if (static_cast<std::size_t>(perf) >= this->well_cells_.size()) {
2047 OPM_THROW(std::invalid_argument,"The perforation index exceeds the size of the local containers - possibly wellIndex was called with a global instead of a local perforation index!");
2048 }
2049
2050 if constexpr (! Indices::gasEnabled) {
2051 return;
2052 }
2053
2054 const auto& wdfac = this->well_ecl_.getWDFAC();
2055
2056 if (! wdfac.useDFactor() || (this->well_index_[perf] == 0.0)) {
2057 return;
2058 }
2059
2060 const Scalar d = this->computeConnectionDFactor(perf, intQuants, ws);
2061 if (d < 1.0e-15) {
2062 return;
2063 }
2064
2065 // Solve quadratic equations for connection rates satisfying the ipr and the flow-dependent skin.
2066 // If more than one solution, pick the one corresponding to lowest absolute rate (smallest skin).
2067 const auto& connection = this->well_ecl_.getConnections()[ws.perf_data.ecl_index[perf]];
2068 const Scalar Kh = connection.Kh();
2069 const Scalar scaling = std::numbers::pi * Kh * connection.wpimult();
2070 const unsigned gas_comp_idx = FluidSystem::canonicalToActiveCompIdx(FluidSystem::gasCompIdx);
2071
2072 const Scalar connection_pressure = ws.perf_data.pressure[perf];
2073 const Scalar cell_pressure = getValue(intQuants.fluidState().pressure(FluidSystem::gasPhaseIdx));
2074 const Scalar drawdown = cell_pressure - connection_pressure;
2075 const Scalar invB = getValue(intQuants.fluidState().invB(FluidSystem::gasPhaseIdx));
2076 const Scalar mob_g = getValue(intQuants.mobility(FluidSystem::gasPhaseIdx)) * invB;
2077 const Scalar a = d;
2078 const Scalar b = 2 * scaling / getValue(Tw[gas_comp_idx]);
2079 const Scalar c = -2 * scaling * mob_g * drawdown;
2080
2081 Scalar consistent_Q = -1.0e20;
2082 // Find and check negative solutions (a --> -a)
2083 const Scalar r2n = b*b + 4*a*c;
2084 if (r2n >= 0) {
2085 const Scalar rn = std::sqrt(r2n);
2086 const Scalar xn1 = (b-rn)*0.5/a;
2087 if (xn1 <= 0) {
2088 consistent_Q = xn1;
2089 }
2090 const Scalar xn2 = (b+rn)*0.5/a;
2091 if (xn2 <= 0 && xn2 > consistent_Q) {
2092 consistent_Q = xn2;
2093 }
2094 }
2095 // Find and check positive solutions
2096 consistent_Q *= -1;
2097 const Scalar r2p = b*b - 4*a*c;
2098 if (r2p >= 0) {
2099 const Scalar rp = std::sqrt(r2p);
2100 const Scalar xp1 = (rp-b)*0.5/a;
2101 if (xp1 > 0 && xp1 < consistent_Q) {
2102 consistent_Q = xp1;
2103 }
2104 const Scalar xp2 = -(rp+b)*0.5/a;
2105 if (xp2 > 0 && xp2 < consistent_Q) {
2106 consistent_Q = xp2;
2107 }
2108 }
2109 Tw[gas_comp_idx] = 1.0 / (1.0 / (trans_mult * this->well_index_[perf]) + (consistent_Q/2 * d / scaling));
2110 }
2111
2112 template <typename TypeTag>
2113 void
2115 updateConnectionDFactor(const Simulator& simulator,
2116 SingleWellStateType& ws) const
2117 {
2118 if (! this->well_ecl_.getWDFAC().useDFactor()) {
2119 return;
2120 }
2121
2122 auto& d_factor = ws.perf_data.connection_d_factor;
2123
2124 for (int perf = 0; perf < this->number_of_local_perforations_; ++perf) {
2125 const int cell_idx = this->well_cells_[perf];
2126 const auto& intQuants = simulator.model().intensiveQuantities(cell_idx, /*timeIdx=*/ 0);
2127
2128 d_factor[perf] = this->computeConnectionDFactor(perf, intQuants, ws);
2129 }
2130 }
2131
2132 template <typename TypeTag>
2135 computeConnectionDFactor(const int perf,
2136 const IntensiveQuantities& intQuants,
2137 const SingleWellStateType& ws) const
2138 {
2139 auto rhoGS = [regIdx = this->pvtRegionIdx()]() {
2140 return FluidSystem::referenceDensity(FluidSystem::gasPhaseIdx, regIdx);
2141 };
2142
2143 // Viscosity is evaluated at connection pressure.
2144 auto gas_visc = [connection_pressure = ws.perf_data.pressure[perf],
2145 temperature = ws.temperature,
2146 regIdx = this->pvtRegionIdx(), &intQuants]()
2147 {
2148 const auto rv = getValue(intQuants.fluidState().Rv());
2149
2150 const auto& gasPvt = FluidSystem::gasPvt();
2151
2152 // Note that rv here is from grid block with typically
2153 // p_block > connection_pressure
2154 // so we may very well have rv > rv_sat
2155 const Scalar rv_sat = gasPvt.saturatedOilVaporizationFactor
2156 (regIdx, temperature, connection_pressure);
2157
2158 if (! (rv < rv_sat)) {
2159 return gasPvt.saturatedViscosity(regIdx, temperature,
2160 connection_pressure);
2161 }
2162
2163 return gasPvt.viscosity(regIdx, temperature, connection_pressure,
2164 rv, getValue(intQuants.fluidState().Rvw()));
2165 };
2166
2167 const auto& connection = this->well_ecl_.getConnections()
2168 [ws.perf_data.ecl_index[perf]];
2169
2170 return this->well_ecl_.getWDFAC().getDFactor(rhoGS, gas_visc, connection);
2171 }
2172
2173
2174 template <typename TypeTag>
2175 void
2178 SingleWellStateType& ws) const
2179 {
2180 auto connCF = [&connIx = std::as_const(ws.perf_data.ecl_index),
2181 &conns = this->well_ecl_.getConnections()]
2182 (const int perf)
2183 {
2184 return conns[connIx[perf]].CF();
2185 };
2186
2187 auto obtain = [](const Eval& value)
2188 {
2189 return getValue(value);
2190 };
2191
2192 auto& tmult = ws.perf_data.connection_compaction_tmult;
2193 auto& ctf = ws.perf_data.connection_transmissibility_factor;
2194
2195 for (int perf = 0; perf < this->number_of_local_perforations_; ++perf) {
2196 const int cell_idx = this->well_cells_[perf];
2197 Scalar trans_mult(0.0);
2198 getTransMult(trans_mult, simulator, cell_idx, obtain);
2199 tmult[perf] = trans_mult;
2200
2201 ctf[perf] = connCF(perf) * tmult[perf];
2202 }
2203 }
2204
2205
2206 template<typename TypeTag>
2209 {
2210 if constexpr (Indices::oilEnabled) {
2211 return fs.pressure(FluidSystem::oilPhaseIdx);
2212 } else if constexpr (Indices::gasEnabled) {
2213 return fs.pressure(FluidSystem::gasPhaseIdx);
2214 } else {
2215 return fs.pressure(FluidSystem::waterPhaseIdx);
2216 }
2217 }
2218
2219 template <typename TypeTag>
2220 template<class Value, class Callback>
2221 void
2223 getTransMult(Value& trans_mult,
2224 const Simulator& simulator,
2225 const int cell_idx,
2226 Callback& extendEval) const
2227 {
2228 const auto& intQuants = simulator.model().intensiveQuantities(cell_idx, /*timeIdx=*/ 0);
2229 trans_mult = simulator.problem().template wellTransMultiplier<Value>(intQuants, cell_idx, extendEval);
2230 }
2231
2232 template <typename TypeTag>
2233 template<class Value, class Callback>
2234 void
2236 getMobility(const Simulator& simulator,
2237 const int local_perf_index,
2238 std::vector<Value>& mob,
2239 Callback& extendEval,
2240 [[maybe_unused]] DeferredLogger& deferred_logger) const
2241 {
2242 auto relpermArray = []()
2243 {
2244 if constexpr (std::is_same_v<Value, Scalar>) {
2245 return std::array<Scalar,3>{};
2246 } else {
2247 return std::array<Eval,3>{};
2248 }
2249 };
2250 if (static_cast<std::size_t>(local_perf_index) >= this->well_cells_.size()) {
2251 OPM_THROW(std::invalid_argument,"The perforation index exceeds the size of the local containers - possibly getMobility was called with a global instead of a local perforation index!");
2252 }
2253 const int cell_idx = this->well_cells_[local_perf_index];
2254 assert (int(mob.size()) == this->num_conservation_quantities_);
2255 const auto& intQuants = simulator.model().intensiveQuantities(cell_idx, /*timeIdx=*/0);
2256 const auto& materialLawManager = simulator.problem().materialLawManager();
2257
2258 // either use mobility of the perforation cell or calculate its own
2259 // based on passing the saturation table index
2260 const int satid = this->saturation_table_number_[local_perf_index] - 1;
2261 const int satid_elem = materialLawManager->satnumRegionIdx(cell_idx);
2262 if (satid == satid_elem) { // the same saturation number is used. i.e. just use the mobilty from the cell
2263 for (unsigned phaseIdx = 0; phaseIdx < FluidSystem::numPhases; ++phaseIdx) {
2264 if (!FluidSystem::phaseIsActive(phaseIdx)) {
2265 continue;
2266 }
2267
2268 const unsigned activeCompIdx = FluidSystem::canonicalToActiveCompIdx(FluidSystem::solventComponentIndex(phaseIdx));
2269 mob[activeCompIdx] = extendEval(intQuants.mobility(phaseIdx));
2270 }
2271 if constexpr (has_solvent) {
2272 mob[Indices::contiSolventEqIdx] = extendEval(intQuants.solventMobility());
2273 }
2274 } else {
2275 const auto& paramsCell = materialLawManager->connectionMaterialLawParams(satid, cell_idx);
2276 auto relativePerms = relpermArray();
2277 MaterialLaw::relativePermeabilities(relativePerms, paramsCell, intQuants.fluidState());
2278
2279 // reset the satnumvalue back to original
2280 materialLawManager->connectionMaterialLawParams(satid_elem, cell_idx);
2281
2282 // compute the mobility
2283 for (unsigned phaseIdx = 0; phaseIdx < FluidSystem::numPhases; ++phaseIdx) {
2284 if (!FluidSystem::phaseIsActive(phaseIdx)) {
2285 continue;
2286 }
2287
2288 const unsigned activeCompIdx = FluidSystem::canonicalToActiveCompIdx(FluidSystem::solventComponentIndex(phaseIdx));
2289 mob[activeCompIdx] = extendEval(relativePerms[phaseIdx] / intQuants.fluidState().viscosity(phaseIdx));
2290 }
2291
2292 if constexpr (has_solvent) {
2293 const auto Fsolgas = intQuants.solventSaturation() / (intQuants.solventSaturation() + intQuants.fluidState().saturation(FluidSystem::gasPhaseIdx));
2294 using SolventModule = BlackOilSolventModule<TypeTag, true>;
2295 if (Fsolgas > SolventModule::cutOff) { // same cutoff as in the solvent model to avoid division by zero
2296 const unsigned activeGasCompIdx = FluidSystem::canonicalToActiveCompIdx(FluidSystem::solventComponentIndex(FluidSystem::gasPhaseIdx));
2297 const auto& ssfnKrg = SolventModule::ssfnKrg(satid);
2298 const auto& ssfnKrs = SolventModule::ssfnKrs(satid);
2299 mob[activeGasCompIdx] *= extendEval(ssfnKrg.eval(1-Fsolgas, /*extrapolate=*/true));
2300 mob[Indices::contiSolventEqIdx] = extendEval(ssfnKrs.eval(Fsolgas, /*extrapolate=*/true) * relativePerms[activeGasCompIdx] / intQuants.solventViscosity());
2301 }
2302 }
2303 }
2304
2305 if (this->isInjector() && !this->inj_fc_multiplier_.empty()) {
2306 const auto perf_ecl_index = this->perforationData()[local_perf_index].ecl_index;
2307 const auto& connections = this->well_ecl_.getConnections();
2308 const auto& connection = connections[perf_ecl_index];
2309 if (connection.filterCakeActive()) {
2310 std::ranges::transform(mob, mob.begin(),
2311 [mult = this->inj_fc_multiplier_[local_perf_index]]
2312 (const auto val)
2313 { return val * mult; });
2314 }
2315 }
2316 }
2317
2318
2319 template<typename TypeTag>
2320 bool
2323 WellStateType& well_state,
2324 const GroupStateHelperType& groupStateHelper) const
2325 {
2326 auto& deferred_logger = groupStateHelper.deferredLogger();
2327 OPM_TIMEFUNCTION();
2328 const auto& summary_state = simulator.vanguard().summaryState();
2329
2330 auto bhp_at_thp_limit = computeBhpAtThpLimitProdWithAlq(
2331 simulator, groupStateHelper, summary_state, this->getALQ(well_state), /*iterate_if_no_solution */ false);
2332 if (bhp_at_thp_limit) {
2333 std::vector<Scalar> rates(this->number_of_phases_, 0.0);
2334 if (thp_update_iterations) {
2335 computeWellRatesWithBhpIterations(simulator, *bhp_at_thp_limit,
2336 groupStateHelper, rates);
2337 } else {
2338 computeWellRatesWithBhp(simulator, *bhp_at_thp_limit,
2339 rates, deferred_logger);
2340 }
2341 auto& ws = well_state.well(this->name());
2342 ws.surface_rates = rates;
2343 ws.bhp = *bhp_at_thp_limit;
2344 ws.thp = this->getTHPConstraint(summary_state);
2345 return true;
2346 } else {
2347 return false;
2348 }
2349 }
2350
2351 template<typename TypeTag>
2352 std::optional<typename WellInterface<TypeTag>::Scalar>
2355 const WellStateType& well_state,
2356 Scalar bhp,
2357 const SummaryState& summary_state,
2358 const Scalar alq_value)
2359 {
2360 OPM_TIMEFUNCTION();
2361 WellStateType well_state_copy = well_state;
2362 const auto& groupStateHelper = simulator.problem().wellModel().groupStateHelper();
2363 GroupStateHelperType groupStateHelper_copy = groupStateHelper;
2364 auto well_guard = groupStateHelper_copy.pushWellState(well_state_copy);
2365 const double dt = simulator.timeStepSize();
2366 const bool converged = this->solveWellWithBhp(
2367 simulator, dt, bhp, groupStateHelper_copy, well_state_copy
2368 );
2369
2370 bool zero_rates;
2371 auto rates = well_state_copy.well(this->index_of_well_).surface_rates;
2372 zero_rates = true;
2373 for (std::size_t p = 0; p < rates.size(); ++p) {
2374 zero_rates &= rates[p] == 0.0;
2375 }
2376 // For zero rates or unconverged bhp the implicit IPR is problematic.
2377 // Use the old approach for now
2378 if (zero_rates || !converged) {
2379 return this->computeBhpAtThpLimitProdWithAlq(simulator, groupStateHelper_copy, summary_state, alq_value, /*iterate_if_no_solution */ false);
2380 }
2381 this->updateIPRImplicit(simulator, groupStateHelper_copy, well_state_copy);
2382 this->adaptRatesForVFP(rates);
2383 return WellBhpThpCalculator(*this).estimateStableBhp(well_state_copy, this->well_ecl_, rates, this->getRefDensity(), summary_state, alq_value);
2384 }
2385
2386 template <typename TypeTag>
2387 void
2390 const std::function<Scalar(const Scalar)>& connPICalc,
2391 const std::vector<Scalar>& mobility,
2392 Scalar* connPI) const
2393 {
2394 const int np = this->number_of_phases_;
2395 for (int p = 0; p < np; ++p) {
2396 // Note: E100's notion of PI value phase mobility includes
2397 // the reciprocal FVF.
2398 const int canonical_phase_idx = FluidSystem::activeToCanonicalPhaseIdx(p);
2399 const auto connMob =
2400 mobility[FluidSystem::activePhaseToActiveCompIdx(p)] * fs.invB(canonical_phase_idx).value();
2401
2402 connPI[p] = connPICalc(connMob);
2403 }
2404
2405 if (FluidSystem::phaseIsActive(FluidSystem::oilPhaseIdx) &&
2406 FluidSystem::phaseIsActive(FluidSystem::gasPhaseIdx))
2407 {
2408 const auto io = FluidSystem::canonicalToActivePhaseIdx(FluidSystem::oilPhaseIdx);
2409 const auto ig = FluidSystem::canonicalToActivePhaseIdx(FluidSystem::gasPhaseIdx);
2410
2411 const auto vapoil = connPI[ig] * fs.Rv().value();
2412 const auto disgas = connPI[io] * fs.Rs().value();
2413
2414 connPI[io] += vapoil;
2415 connPI[ig] += disgas;
2416 }
2417 }
2418
2419
2420 template <typename TypeTag>
2421 void
2424 const Phase preferred_phase,
2425 const std::function<Scalar(const Scalar)>& connIICalc,
2426 const std::vector<Scalar>& mobility,
2427 Scalar* connII,
2428 DeferredLogger& deferred_logger) const
2429 {
2430 auto phase_pos = 0;
2431 if (preferred_phase == Phase::GAS) {
2432 phase_pos = FluidSystem::canonicalToActivePhaseIdx(FluidSystem::gasPhaseIdx);
2433 }
2434 else if (preferred_phase == Phase::OIL) {
2435 phase_pos = FluidSystem::canonicalToActivePhaseIdx(FluidSystem::oilPhaseIdx);
2436 }
2437 else if (preferred_phase == Phase::WATER) {
2438 phase_pos = FluidSystem::canonicalToActivePhaseIdx(FluidSystem::waterPhaseIdx);
2439 }
2440 else {
2441 OPM_DEFLOG_THROW(NotImplemented,
2442 fmt::format("Unsupported Injector Type ({}) "
2443 "for well {} during connection I.I. calculation",
2444 static_cast<int>(preferred_phase), this->name()),
2445 deferred_logger);
2446 }
2447
2448 const auto mt = std::accumulate(mobility.begin(), mobility.end(), 0.0);
2449 const int canonicalPhaseIdx = FluidSystem::activeToCanonicalPhaseIdx(phase_pos);
2450 connII[phase_pos] = connIICalc(mt * fs.invB(canonicalPhaseIdx).value());
2451 }
2452
2453 template<typename TypeTag>
2454 template<class GasLiftSingleWell>
2455 std::unique_ptr<GasLiftSingleWell>
2457 initializeGliftWellTest_(const Simulator& simulator,
2458 WellStateType& well_state,
2459 const GroupState<Scalar>& group_state,
2460 GLiftEclWells& ecl_well_map,
2461 DeferredLogger& deferred_logger)
2462 {
2463 // Instantiate group info object (without initialization) since it is needed in GasLiftSingleWell
2464 auto& comm = simulator.vanguard().grid().comm();
2465 ecl_well_map.try_emplace(this->name(), &(this->wellEcl()), this->indexOfWell());
2466 const auto& iterCtx = simulator.problem().iterationContext();
2468 ecl_well_map,
2469 simulator.vanguard().schedule(),
2470 simulator.vanguard().summaryState(),
2471 simulator.episodeIndex(),
2472 iterCtx,
2473 deferred_logger,
2474 well_state,
2475 group_state,
2476 comm,
2477 false
2478 };
2479
2480 // Return GasLiftSingleWell object to use the wellTestALQ() function
2481 std::set<int> sync_groups;
2482 const auto& summary_state = simulator.vanguard().summaryState();
2483 return std::make_unique<GasLiftSingleWell>(*this,
2484 simulator,
2485 summary_state,
2486 deferred_logger,
2487 well_state,
2488 group_state,
2489 group_info,
2490 sync_groups,
2491 comm,
2492 false);
2493
2494 }
2495
2496
2497 template <typename TypeTag>
2500 {
2501 FSInfo info{};
2502
2503 // If this process does not contain active perforations, this->well_cells_ is empty.
2504 if (this->well_cells_.size() > 0) {
2505 // The cell of the first perforation *on this process*. For a distributed well
2506 // this is the first perforation of the well only on the process holding it;
2507 // the broadcast below replaces the values on all the other processes.
2508 const int cell_idx = this->well_cells_[0];
2509 const auto& intQuants = simulator.model().intensiveQuantities(cell_idx, /*timeIdx=*/0);
2510 const auto& fs = intQuants.fluidState();
2511
2512 info.temperature = getValue(fs.temperature(FluidSystem::oilPhaseIdx));
2513 info.saltConcentration = getValue(fs.saltConcentration());
2514 }
2515
2516 // Broadcast from the process holding the first open connection of the well
2517 // (ParallelWellInfo::communicateFirstPerforation), so that all processes use the
2518 // conditions of the same cell.
2519 return this->parallel_well_info_.communication().size() == 1
2520 ? info
2521 : this->parallel_well_info_.broadcastFirstPerforationValue(info);
2522 }
2523
2524} // namespace Opm
2525
2526#endif
#define OPM_DEFLOG_THROW(Exception, message, deferred_logger)
Definition: DeferredLoggingErrorHelpers.hpp:47
Contains the high level supplements required to extend the black oil model by solvents.
Definition: blackoilsolventmodules.hh:69
Definition: DeferredLogger.hpp:57
void info(const std::string &tag, const std::string &message)
void warning(const std::string &tag, const std::string &message)
Definition: GasLiftGroupInfo.hpp:47
Definition: GroupStateHelper.hpp:56
GroupState< Scalar > & groupState() const
Definition: GroupStateHelper.hpp:301
const SummaryState & summaryState() const
Definition: GroupStateHelper.hpp:429
const WellState< Scalar, IndexTraits > & wellState() const
Definition: GroupStateHelper.hpp:510
DeferredLogger & deferredLogger() const
Get the deferred logger.
Definition: GroupStateHelper.hpp:233
WellStateGuard pushWellState(WellState< Scalar, IndexTraits > &well_state)
Definition: GroupStateHelper.hpp:368
GroupStateGuard pushGroupState(GroupState< Scalar > &group_state)
Definition: GroupStateHelper.hpp:345
Definition: GroupState.hpp:41
Class encapsulating some information about parallel wells.
Definition: ParallelWellInfo.hpp:217
Definition: SingleWellState.hpp:44
Scalar temperature
Definition: SingleWellState.hpp:111
PerfData< Scalar > perf_data
Definition: SingleWellState.hpp:160
Class for computing BHP limits.
Definition: WellBhpThpCalculator.hpp:41
Scalar calculateMinimumBhpFromThp(const WellState< Scalar, IndexTraits > &well_state, const Well &well, const SummaryState &summaryState, const Scalar rho) const
Scalar mostStrictBhpFromBhpLimits(const SummaryState &summaryState) const
Obtain the most strict BHP from BHP limits.
bool isStableSolution(const WellState< Scalar, IndexTraits > &well_state, const Well &well, const std::vector< Scalar > &rates, const SummaryState &summaryState) const
EvalWell calculateBhpFromThp(const WellState< Scalar, IndexTraits > &well_state, const std::vector< EvalWell > &rates, const Well &well, const SummaryState &summaryState, const Scalar rho, DeferredLogger &deferred_logger) const
std::optional< Scalar > estimateStableBhp(const WellState< Scalar, IndexTraits > &well_state, const Well &well, const std::vector< Scalar > &rates, const Scalar rho, const SummaryState &summaryState) const
int number_of_local_perforations_
Definition: WellInterfaceGeneric.hpp:396
FluidSystem::Scalar wsolvent_
Definition: WellInterfaceGeneric.hpp:436
Definition: WellInterfaceIndices.hpp:34
bool stoppedOrZeroRateTarget(const GroupStateHelperType &groupStateHelper) const
Definition: WellInterface_impl.hpp:1888
bool updateWellOperabilityFromWellEq(const Simulator &simulator, const GroupStateHelperType &groupStateHelper)
Definition: WellInterface_impl.hpp:1439
void checkWellOperability(const Simulator &simulator, const WellStateType &well_state, const GroupStateHelperType &groupStateHelper)
Definition: WellInterface_impl.hpp:1311
void updateWellOperability(const Simulator &simulator, const WellStateType &well_state, const GroupStateHelperType &groupStateHelper)
Definition: WellInterface_impl.hpp:1401
bool solveWellWithOperabilityCheck(const Simulator &simulator, const double dt, const Well::InjectionControls &inj_controls, const Well::ProductionControls &prod_controls, const GroupStateHelperType &groupStateHelper, WellStateType &well_state)
Definition: WellInterface_impl.hpp:735
Scalar woxygen() const
Definition: WellInterface_impl.hpp:168
IndividualOrGroup
Definition: WellInterface.hpp:258
GetPropType< TypeTag, Properties::Simulator > Simulator
Definition: WellInterface.hpp:84
void assembleWellEqWithoutIteration(const Simulator &simulator, const GroupStateHelperType &groupStateHelper, const double dt, WellStateType &well_state, const bool solving_with_zero_rate)
Definition: WellInterface_impl.hpp:1108
Scalar computeConnectionDFactor(const int perf, const IntensiveQuantities &intQuants, const SingleWellStateType &ws) const
Definition: WellInterface_impl.hpp:2135
void updateWeldrawMaxRate(const Simulator &simulator, WellStateType &well_state, DeferredLogger &deferred_logger) const
Definition: WellInterface_impl.hpp:289
typename WellInterfaceFluidSystem< FluidSystem >::RateConverterType RateConverterType
Definition: WellInterface.hpp:110
Scalar wfoam() const
Definition: WellInterface_impl.hpp:130
bool updateWellControlAndStatusLocalIteration(const Simulator &simulator, const GroupStateHelperType &groupStateHelper, const Well::InjectionControls &inj_controls, const Well::ProductionControls &prod_controls, const Scalar WQTotal, WellStateType &well_state, const bool fixed_control, const bool fixed_status, const bool solving_with_zero_rate)
Definition: WellInterface_impl.hpp:381
void getTransMult(Value &trans_mult, const Simulator &simulator, const int cell_idx, Callback &extendEval) const
Definition: WellInterface_impl.hpp:2223
std::vector< RateVector > connectionRates_
Definition: WellInterface.hpp:403
bool solveWellForTesting(const Simulator &simulator, const GroupStateHelperType &groupStateHelper, WellStateType &well_state)
Definition: WellInterface_impl.hpp:974
void computeConnLevelProdInd(const FluidState &fs, const std::function< Scalar(const Scalar)> &connPICalc, const std::vector< Scalar > &mobility, Scalar *connPI) const
Definition: WellInterface_impl.hpp:2389
void gliftBeginTimeStepWellTestUpdateALQ(const Simulator &simulator, WellStateType &well_state, const GroupState< Scalar > &group_state, GLiftEclWells &ecl_well_map, DeferredLogger &deferred_logger)
Definition: WellInterface_impl.hpp:1339
Scalar volumetricSurfaceRateForConnection(int cellIdx, int phaseIdx) const
Definition: WellInterface_impl.hpp:1291
virtual void init(const std::vector< Scalar > &depth_arg, const Scalar gravity_arg, const std::vector< Scalar > &B_avg, const bool changed_to_open_this_step)
Definition: WellInterface_impl.hpp:98
std::optional< Scalar > computeBhpAtThpLimitProdWithAlqUsingIPR(const Simulator &simulator, const WellStateType &well_state, Scalar bhp, const SummaryState &summary_state, const Scalar alq_value)
Definition: WellInterface_impl.hpp:2354
void getTw(std::vector< Value > &wi, const int perf, const IntensiveQuantities &intQuants, const Value &trans_mult, const SingleWellStateType &ws) const
Definition: WellInterface_impl.hpp:2037
void getMobility(const Simulator &simulator, const int local_perf_index, std::vector< Value > &mob, Callback &extendEval, DeferredLogger &deferred_logger) const
Definition: WellInterface_impl.hpp:2236
GetPropType< TypeTag, Properties::IntensiveQuantities > IntensiveQuantities
Definition: WellInterface.hpp:89
GetPropType< TypeTag, Properties::Scalar > Scalar
Definition: WellInterface.hpp:85
std::vector< Scalar > initialWellRateFractions(const Simulator &ebosSimulator, const WellStateType &well_state) const
Definition: WellInterface_impl.hpp:1899
void solveWellEquation(const Simulator &simulator, const GroupStateHelperType &groupStateHelper, WellStateType &well_state)
Definition: WellInterface_impl.hpp:1030
void updateConnectionDFactor(const Simulator &simulator, SingleWellStateType &ws) const
Definition: WellInterface_impl.hpp:2115
Eval getPerfCellPressure(const FluidState &fs) const
Definition: WellInterface_impl.hpp:2208
void initializeProducerWellState(const Simulator &simulator, WellStateType &well_state, DeferredLogger &deferred_logger) const
Definition: WellInterface_impl.hpp:1949
virtual void updateWellStateWithTarget(const Simulator &simulator, const GroupStateHelperType &groupStateHelper, WellStateType &well_state) const
Definition: WellInterface_impl.hpp:1469
void addCellRates(std::map< int, RateVector > &cellRates_) const
Definition: WellInterface_impl.hpp:1272
typename Base::ModelParameters ModelParameters
Definition: WellInterface.hpp:116
GetPropType< TypeTag, Properties::FluidSystem > FluidSystem
Definition: WellInterface.hpp:86
static constexpr bool has_solvent
Definition: WellInterface.hpp:118
bool wellUnderZeroRateTarget(const GroupStateHelperType &groupStateHelper) const
Definition: WellInterface_impl.hpp:1856
GetPropType< TypeTag, Properties::RateVector > RateVector
Definition: WellInterface.hpp:92
void updateConnectionTransmissibilityFactor(const Simulator &simulator, SingleWellStateType &ws) const
Definition: WellInterface_impl.hpp:2177
void computeConnLevelInjInd(const FluidState &fs, const Phase preferred_phase, const std::function< Scalar(const Scalar)> &connIICalc, const std::vector< Scalar > &mobility, Scalar *connII, DeferredLogger &deferred_logger) const
Definition: WellInterface_impl.hpp:2423
typename GasLiftGroupInfo< Scalar, IndexTraits >::GLiftEclWells GLiftEclWells
Definition: WellInterface.hpp:94
std::unique_ptr< GasLiftSingleWell > initializeGliftWellTest_(const Simulator &simulator, WellStateType &well_state, const GroupState< Scalar > &group_state, GLiftEclWells &ecl_well_map, DeferredLogger &deferred_logger)
Definition: WellInterface_impl.hpp:2457
BlackOilFluidStateType< Eval > FluidState
Definition: WellInterface.hpp:148
std::optional< Scalar > estimateOperableBhp(const Simulator &ebos_simulator, const double dt, const GroupStateHelperType &groupStateHelper, const SummaryState &summary_state, WellStateType &well_state)
Definition: WellInterface_impl.hpp:855
Scalar wsalt() const
Definition: WellInterface_impl.hpp:144
bool solveWellWithZeroRate(const Simulator &simulator, const double dt, const GroupStateHelperType &groupStateHelper, WellStateType &well_state)
Definition: WellInterface_impl.hpp:942
bool wellUnderZeroGroupRateTarget(const GroupStateHelperType &groupStateHelper, const std::optional< bool > group_control=std::nullopt) const
Definition: WellInterface_impl.hpp:1873
bool solveWellWithBhp(const Simulator &simulator, const double dt, const Scalar bhp, const GroupStateHelperType &groupStateHelper, WellStateType &well_state)
Definition: WellInterface_impl.hpp:892
void prepareWellBeforeAssembling(const Simulator &simulator, const double dt, const GroupStateHelperType &groupStateHelper, WellStateType &well_state)
Definition: WellInterface_impl.hpp:1145
void wellTesting(const Simulator &simulator, const double simulation_time, const GroupStateHelperType &groupStateHelper, WellStateType &well_state, WellTestState &welltest_state, GLiftEclWells &ecl_well_map, std::map< std::string, double > &open_times)
Definition: WellInterface_impl.hpp:500
typename Base::Eval Eval
Definition: WellInterface.hpp:98
WellInterface(const Well &well, const ParallelWellInfo< Scalar > &pw_info, const int time_step, const ModelParameters &param, const RateConverterType &rate_converter, const int pvtRegionIdx, const int num_conservation_quantities, const int num_phases, const int index_of_well, const std::vector< PerforationData< Scalar > > &perf_data)
Constructor.
Definition: WellInterface_impl.hpp:61
bool updateWellStateWithTHPTargetProd(const Simulator &simulator, WellStateType &well_state, const GroupStateHelperType &groupStateHelper) const
Definition: WellInterface_impl.hpp:2322
bool iterateWellEquations(const Simulator &simulator, const double dt, const GroupStateHelperType &groupStateHelper, WellStateType &well_state)
Definition: WellInterface_impl.hpp:657
Scalar wpolymer() const
Definition: WellInterface_impl.hpp:114
GetPropType< TypeTag, Properties::Indices > Indices
Definition: WellInterface.hpp:88
bool updateWellControl(const Simulator &simulator, const IndividualOrGroup iog, const GroupStateHelperType &groupStateHelper, WellStateType &well_state)
Definition: WellInterface_impl.hpp:192
Scalar wurea() const
Definition: WellInterface_impl.hpp:180
void updateGroupTargetFallbackFlag(WellStateType &well_state, DeferredLogger &deferred_logger) const
Definition: WellInterface_impl.hpp:1130
FSInfo getFirstPerfCellConditions(const Simulator &simulator) const
Temperature and salt concentration of the first perforated cell, broadcast so that all processes of a...
Definition: WellInterface_impl.hpp:2499
void assembleWellEq(const Simulator &simulator, const double dt, const GroupStateHelperType &groupStateHelper, WellStateType &well_state)
Definition: WellInterface_impl.hpp:1092
Scalar wmicrobes() const
Definition: WellInterface_impl.hpp:156
virtual void scaleSegmentRatesAndPressure(WellStateType &well_state) const
Definition: WellInterface_impl.hpp:1461
static constexpr bool has_zFraction
Definition: WellInterface.hpp:119
Definition: WellState.hpp:68
constexpr int numPhases() const
The number of phases present.
Definition: WellState.hpp:274
const SingleWellState< Scalar, IndexTraits > & well(std::size_t well_index) const
Definition: WellState.hpp:315
bool isOpen(const std::string &name) const
Definition: WellState.hpp:222
@ NONE
Definition: DeferredLogger.hpp:46
Dune::Communication< MPIComm > Communication
Definition: ParallelCommunication.hpp:30
Phase
Phase indices for reservoir coupling, we currently only support black-oil phases (oil,...
Definition: ReservoirCoupling.hpp:165
Definition: blackoilbioeffectsmodules.hh:45
const std::string & economicLimitMessageSeparator()
Separator line used to frame economic-limit workover messages. Built once and returned by reference (...
Definition: EconomicLimitsMessage.hpp:61
std::string economicLimitDateString(const std::time_t start_time, const double sim_time)
Calendar date (DD-Mon-YYYY, UTC) reached at start_time plus sim_time seconds.
Definition: EconomicLimitsMessage.hpp:41
std::string to_string(const ConvergenceReport::ReservoirFailure::Type t)
Reservoir temperature and salt concentration of the first perforated cell.
Definition: ParallelWellInfo.hpp:44
Scalar temperature
Definition: ParallelWellInfo.hpp:45
Static data associated with a well perforation.
Definition: PerforationData.hpp:30