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