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