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