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