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