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