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