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,
193 DeferredLogger& deferred_logger) /* const */
194 {
195 OPM_TIMEFUNCTION();
196 if (stoppedOrZeroRateTarget(groupStateHelper, deferred_logger)) {
197 return false;
198 }
199
200 const auto& summaryState = simulator.vanguard().summaryState();
201 const auto& schedule = simulator.vanguard().schedule();
202 const auto& well = this->well_ecl_;
203 auto& ws = well_state.well(this->index_of_well_);
204 std::string from;
205 bool is_grup = false;
206 if (well.isInjector()) {
207 from = WellInjectorCMode2String(ws.injection_cmode);
208 is_grup = ws.injection_cmode == Well::InjectorCMode::GRUP;
209 } else {
210 from = WellProducerCMode2String(ws.production_cmode);
211 is_grup = ws.production_cmode == Well::ProducerCMode::GRUP;
212 }
213
214 const int episodeIdx = simulator.episodeIndex();
215 const int iterationIdx = simulator.model().newtonMethod().numIterations();
216 const int nupcol = schedule[episodeIdx].nupcol();
217 const bool oscillating = std::count(this->well_control_log_.begin(), this->well_control_log_.end(), from) >= this->param_.max_number_of_well_switches_;
218 if (oscillating && !is_grup) { // we would like to avoid ending up as GRUP
219 // only output first time
220 const bool output = std::count(this->well_control_log_.begin(), this->well_control_log_.end(), from) == this->param_.max_number_of_well_switches_;
221 if (output) {
222 const auto msg = fmt::format(" The control mode for well {} is oscillating. \n"
223 "We don't allow for more than {} switches after NUPCOL iterations. (NUPCOL = {}) \n"
224 "The control is kept at {}.",
225 this->name(), this->param_.max_number_of_well_switches_, nupcol, from);
226 deferred_logger.info(msg);
227 // add one more to avoid outputting the same info again
228 this->well_control_log_.push_back(from);
229 }
230 return false;
231 }
232 bool changed = false;
233 if (iog == IndividualOrGroup::Individual) {
234 changed = this->checkIndividualConstraints(ws, summaryState, deferred_logger);
235 } else if (iog == IndividualOrGroup::Group) {
236 changed = this->checkGroupConstraints(
237 groupStateHelper, schedule, summaryState, true, well_state, deferred_logger
238 );
239 } else {
240 assert(iog == IndividualOrGroup::Both);
241 changed = this->checkConstraints(groupStateHelper, schedule, summaryState, well_state, deferred_logger);
242 }
243 Parallel::Communication cc = simulator.vanguard().grid().comm();
244 // checking whether control changed
245 if (changed) {
246 std::string to;
247 if (well.isInjector()) {
248 to = WellInjectorCMode2String(ws.injection_cmode);
249 } else {
250 to = WellProducerCMode2String(ws.production_cmode);
251 }
252 std::ostringstream ss;
253 ss << " Switching control mode for well " << this->name()
254 << " from " << from
255 << " to " << to;
256 if (cc.size() > 1) {
257 ss << " on rank " << cc.rank();
258 }
259 deferred_logger.debug(ss.str());
260
261 // We always store the current control as it is used for output
262 // and only after iteration >= nupcol
263 // we log all switches to check if the well controls oscillates
264 if (iterationIdx >= nupcol || this->well_control_log_.empty()) {
265 this->well_control_log_.push_back(from);
266 }
267 updateWellStateWithTarget(simulator, groupStateHelper, well_state, deferred_logger);
268 updatePrimaryVariables(groupStateHelper, deferred_logger);
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 DeferredLogger& deferred_logger,
284 const bool fixed_control,
285 const bool fixed_status,
286 const bool solving_with_zero_rate)
287 {
288 OPM_TIMEFUNCTION();
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, deferred_logger) || !(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, deferred_logger
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, deferred_logger);
343 }
344 updatePrimaryVariables(groupStateHelper, deferred_logger);
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 DeferredLogger& deferred_logger)
403 {
404 OPM_TIMEFUNCTION();
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, deferred_logger);
428 updatePrimaryVariables(groupStateHelper_copy, deferred_logger);
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, deferred_logger);
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, deferred_logger);
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, deferred_logger);
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, deferred_logger);
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 DeferredLogger& deferred_logger)
526 {
527 OPM_TIMEFUNCTION();
528 const auto& summary_state = simulator.vanguard().summaryState();
529 const auto inj_controls = this->well_ecl_.isInjector() ? this->well_ecl_.injectionControls(summary_state) : Well::InjectionControls(0);
530 const auto prod_controls = this->well_ecl_.isProducer() ? this->well_ecl_.productionControls(summary_state) : Well::ProductionControls(0);
531 const auto& ws = well_state.well(this->indexOfWell());
532 const auto pmode_orig = ws.production_cmode;
533 const auto imode_orig = ws.injection_cmode;
534 bool converged = false;
535 try {
536 // TODO: the following two functions will be refactored to be one to reduce the code duplication
537 if (!this->param_.local_well_solver_control_switching_){
538 converged = this->iterateWellEqWithControl(simulator, dt, inj_controls, prod_controls, groupStateHelper, well_state, deferred_logger);
539 } else {
540 if (this->param_.use_implicit_ipr_ && this->well_ecl_.isProducer() && (well_state.well(this->index_of_well_).status == WellStatus::OPEN)) {
541 converged = solveWellWithOperabilityCheck(
542 simulator, dt, inj_controls, prod_controls, groupStateHelper, well_state, deferred_logger
543 );
544 } else {
545 converged = this->iterateWellEqWithSwitching(
546 simulator, dt, inj_controls, prod_controls, groupStateHelper, well_state, deferred_logger,
547 /*fixed_control=*/false, /*fixed_status=*/false, /*solving_with_zero_rate=*/false
548 );
549 }
550 }
551
552 } catch (NumericalProblem& e ) {
553 const std::string msg = "Inner well iterations failed for well " + this->name() + " Treat the well as unconverged. ";
554 deferred_logger.warning("INNER_ITERATION_FAILED", msg);
555 converged = false;
556 }
557 if (converged) {
558 // Add debug info for switched controls
559 if (ws.production_cmode != pmode_orig || ws.injection_cmode != imode_orig) {
560 std::string from,to;
561 if (this->isInjector()) {
562 from = WellInjectorCMode2String(imode_orig);
563 to = WellInjectorCMode2String(ws.injection_cmode);
564 } else {
565 from = WellProducerCMode2String(pmode_orig);
566 to = WellProducerCMode2String(ws.production_cmode);
567 }
568 const auto msg = fmt::format(" Well {} switched from {} to {} during local solve", this->name(), from, to);
569 deferred_logger.debug(msg);
570 const int episodeIdx = simulator.episodeIndex();
571 const int iterationIdx = simulator.model().newtonMethod().numIterations();
572 const auto& schedule = simulator.vanguard().schedule();
573 const int nupcol = schedule[episodeIdx].nupcol();
574 // We always store the current control as it is used for output
575 // and only after iteration >= nupcol
576 // we log all switches to check if the well controls oscillates
577 if (iterationIdx >= nupcol || this->well_control_log_.empty()) {
578 this->well_control_log_.push_back(from);
579 }
580 }
581 }
582
583 return converged;
584 }
585
586 template<typename TypeTag>
587 bool
590 const double dt,
591 const Well::InjectionControls& inj_controls,
592 const Well::ProductionControls& prod_controls,
593 const GroupStateHelperType& groupStateHelper,
594 WellStateType& well_state,
595 DeferredLogger& deferred_logger)
596 {
597 OPM_TIMEFUNCTION();
598 const auto& summary_state = simulator.vanguard().summaryState();
599 bool converged = true;
600 auto& ws = well_state.well(this->index_of_well_);
601 // if well is stopped, check if we can reopen with explicit fraction
602 if (this->wellIsStopped()) {
603 this->openWell();
604 const bool use_vfpexplicit = this->operability_status_.use_vfpexplicit;
605 this->operability_status_.use_vfpexplicit = true;
606 auto bhp_target = estimateOperableBhp(simulator, dt, groupStateHelper, summary_state, well_state, deferred_logger);
607 if (!bhp_target.has_value()) {
608 // no intersection with ipr
609 const auto msg = fmt::format("estimateOperableBhp: Did not find operable BHP for well {}", this->name());
610 deferred_logger.debug(msg);
611 // well can't operate using explicit fractions stop the well
612 // solve with zero rates
613 converged = solveWellWithZeroRate(simulator, dt, groupStateHelper, well_state, deferred_logger);
614 this->stopWell();
615 this->operability_status_.can_obtain_bhp_with_thp_limit = false;
616 this->operability_status_.obey_thp_limit_under_bhp_limit = false;
617 return converged;
618 } else {
619 // solve well with the estimated target bhp (or limit)
620 ws.thp = this->getTHPConstraint(summary_state);
621 const Scalar bhp = std::max(bhp_target.value(),
622 static_cast<Scalar>(prod_controls.bhp_limit));
623 solveWellWithBhp(simulator, dt, bhp, groupStateHelper, well_state, deferred_logger);
624 this->operability_status_.use_vfpexplicit = use_vfpexplicit;
625 }
626 }
627 // solve well-equation
628 converged = this->iterateWellEqWithSwitching(
629 simulator, dt, inj_controls, prod_controls, groupStateHelper, well_state, deferred_logger,
630 /*fixed_control=*/false, /*fixed_status=*/false, /*solving_with_zero_rate=*/false
631 );
632
633
634 const bool isThp = ws.production_cmode == Well::ProducerCMode::THP;
635 // check stability of solution under thp-control
636 if (converged && !stoppedOrZeroRateTarget(groupStateHelper, deferred_logger) && isThp) {
637 auto rates = well_state.well(this->index_of_well_).surface_rates;
638 this->adaptRatesForVFP(rates);
639 this->updateIPRImplicit(simulator, groupStateHelper, well_state, deferred_logger);
640 bool is_stable = WellBhpThpCalculator(*this).isStableSolution(well_state, this->well_ecl_, rates, summary_state);
641 if (!is_stable) {
642 // solution converged to an unstable point!
643 this->operability_status_.use_vfpexplicit = true;
644 auto bhp_stable = WellBhpThpCalculator(*this).estimateStableBhp(well_state, this->well_ecl_, rates, this->getRefDensity(), summary_state);
645 // if we find an intersection with a sufficiently lower bhp, re-solve equations
646 const Scalar reltol = 1e-3;
647 const Scalar cur_bhp = ws.bhp;
648 if (bhp_stable.has_value() && cur_bhp - bhp_stable.value() > cur_bhp*reltol){
649 const auto msg = fmt::format("Well {} converged to an unstable solution, re-solving", this->name());
650 deferred_logger.debug(msg);
651 solveWellWithBhp(
652 simulator, dt, bhp_stable.value(), groupStateHelper, well_state, deferred_logger
653 );
654 // re-solve with hopefully good initial guess
655 ws.thp = this->getTHPConstraint(summary_state);
656 converged = this->iterateWellEqWithSwitching(
657 simulator, dt, inj_controls, prod_controls, groupStateHelper, well_state, deferred_logger,
658 /*fixed_control=*/false, /*fixed_status=*/false, /*solving_with_zero_rate=*/false
659 );
660 }
661 }
662 }
663
664 if (!converged) {
665 // Well did not converge, switch to explicit fractions
666 this->operability_status_.use_vfpexplicit = true;
667 this->openWell();
668 auto bhp_target = estimateOperableBhp(
669 simulator, dt, groupStateHelper, summary_state, well_state, deferred_logger
670 );
671 if (!bhp_target.has_value()) {
672 // solve with zero rate
673 // well can't operate using explicit fractions stop the well
674 converged = solveWellWithZeroRate(simulator, dt, groupStateHelper, well_state, deferred_logger);
675 this->stopWell();
676 this->operability_status_.can_obtain_bhp_with_thp_limit = false;
677 this->operability_status_.obey_thp_limit_under_bhp_limit = false;
678 return converged;
679 } else {
680 // solve well with the estimated target bhp (or limit)
681 const Scalar bhp = std::max(bhp_target.value(),
682 static_cast<Scalar>(prod_controls.bhp_limit));
683 solveWellWithBhp(
684 simulator, dt, bhp, groupStateHelper, well_state, deferred_logger
685 );
686 ws.thp = this->getTHPConstraint(summary_state);
687 const auto msg = fmt::format("Well {} did not converge, re-solving with explicit fractions for VFP caculations.", this->name());
688 deferred_logger.debug(msg);
689 converged = this->iterateWellEqWithSwitching(simulator, dt,
690 inj_controls,
691 prod_controls,
692 groupStateHelper,
693 well_state,
694 deferred_logger,
695 /*fixed_control=*/false,
696 /*fixed_status=*/false,
697 /*solving_with_zero_rate=*/false);
698 }
699 }
700 // update operability
701 this->operability_status_.can_obtain_bhp_with_thp_limit = !this->wellIsStopped();
702 this->operability_status_.obey_thp_limit_under_bhp_limit = !this->wellIsStopped();
703 return converged;
704 }
705
706 template<typename TypeTag>
707 std::optional<typename WellInterface<TypeTag>::Scalar>
709 estimateOperableBhp(const Simulator& simulator,
710 const double dt,
711 const GroupStateHelperType& groupStateHelper,
712 const SummaryState& summary_state,
713 WellStateType& well_state,
714 DeferredLogger& deferred_logger)
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, deferred_logger
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, deferred_logger
734 );
735 if (!converged || this->wellIsStopped()) {
736 return std::nullopt;
737 }
738 this->updateIPRImplicit(simulator, groupStateHelper, well_state, deferred_logger);
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 DeferredLogger& deferred_logger)
753 {
754 OPM_TIMEFUNCTION();
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, deferred_logger,
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 DeferredLogger& deferred_logger)
802 {
803 OPM_TIMEFUNCTION();
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 deferred_logger,
819 /*fixed_control*/true,
820 /*fixed_status*/true,
821 /*solving_with_zero_rate*/true
822 );
823 this->wellStatus_ = well_status_orig;
824 return converged;
825 }
826
827 template<typename TypeTag>
828 bool
830 solveWellForTesting(const Simulator& simulator,
831 const GroupStateHelperType& groupStateHelper,
832 WellStateType& well_state,
833 DeferredLogger& deferred_logger)
834 {
835 OPM_TIMEFUNCTION();
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, deferred_logger
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, deferred_logger
854 );
855 } else {
856 converged = this->iterateWellEqWithSwitching(
857 simulator, dt, inj_controls, prod_controls, groupStateHelper, well_state, deferred_logger,
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 DeferredLogger& deferred_logger)
889 {
890 OPM_TIMEFUNCTION();
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, deferred_logger);
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, deferred_logger);
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 DeferredLogger& deferred_logger)
952 {
953 OPM_TIMEFUNCTION();
954 prepareWellBeforeAssembling(simulator, dt, groupStateHelper, well_state, deferred_logger);
955 assembleWellEqWithoutIteration(simulator, groupStateHelper, dt, well_state, deferred_logger,
956 /*solving_with_zero_rate=*/false);
957 }
958
959
960
961 template <typename TypeTag>
962 void
965 const GroupStateHelperType& groupStateHelper,
966 const double dt,
967 WellStateType& well_state,
968 DeferredLogger& deferred_logger,
969 const bool solving_with_zero_rate)
970 {
971 OPM_TIMEFUNCTION();
972 const auto& summary_state = simulator.vanguard().summaryState();
973 const auto inj_controls = this->well_ecl_.isInjector() ? this->well_ecl_.injectionControls(summary_state) : Well::InjectionControls(0);
974 const auto prod_controls = this->well_ecl_.isProducer() ? this->well_ecl_.productionControls(summary_state) : Well::ProductionControls(0);
975 // 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
976 // TODO: maybe we can use std::optional or pointers to simplify here
977 assembleWellEqWithoutIteration(simulator, groupStateHelper, dt, inj_controls, prod_controls, well_state, deferred_logger, solving_with_zero_rate);
978 }
979
980
981
982 template<typename TypeTag>
983 void
986 const double dt,
987 const GroupStateHelperType& groupStateHelper,
988 WellStateType& well_state,
989 DeferredLogger& deferred_logger)
990 {
991 OPM_TIMEFUNCTION();
992 const bool old_well_operable = this->operability_status_.isOperableAndSolvable();
993
994 if (this->param_.check_well_operability_iter_)
995 checkWellOperability(simulator, well_state, groupStateHelper, deferred_logger);
996
997 // only use inner well iterations for the first newton iterations.
998 const int iteration_idx = simulator.model().newtonMethod().numIterations();
999 if (iteration_idx < this->param_.max_niter_inner_well_iter_ || this->well_ecl_.isMultiSegment()) {
1000 const auto& ws = well_state.well(this->indexOfWell());
1001 const bool nonzero_rate_original =
1002 std::any_of(ws.surface_rates.begin(),
1003 ws.surface_rates.begin() + well_state.numPhases(),
1004 [](Scalar rate) { return rate != Scalar(0.0); });
1005
1006 this->operability_status_.solvable = true;
1007 if (number_of_well_reopenings_ >= this->param_.max_well_status_switch_) {
1008 // only output the first time
1009 if (number_of_well_reopenings_ == this->param_.max_well_status_switch_) {
1010 const std::string msg = fmt::format("well {} is oscillating between open and stop. \n"
1011 "We don't allow for more than {} re-openings "
1012 "and the well is therefore kept stopped.",
1013 this->name(), number_of_well_reopenings_);
1014 deferred_logger.debug(msg);
1015 }
1016 this->stopWell();
1017 changed_to_stopped_this_step_ = true;
1018 bool converged_zero_rate = this->solveWellWithZeroRate(
1019 simulator, dt, groupStateHelper, well_state, deferred_logger
1020 );
1021 if (this->param_.shut_unsolvable_wells_ && !converged_zero_rate ) {
1022 this->operability_status_.solvable = false;
1023 }
1024 // we increse the number of reopenings to avoid output in the next iteration
1025 number_of_well_reopenings_++;
1026 return;
1027 }
1028 bool converged = this->iterateWellEquations(
1029 simulator, dt, groupStateHelper, well_state, deferred_logger
1030 );
1031
1032 if (converged) {
1033 const bool zero_target = this->wellUnderZeroRateTarget(groupStateHelper, deferred_logger);
1034 if (this->wellIsStopped() && !zero_target && nonzero_rate_original) {
1035 // Well had non-zero rate, but was stopped during local well-solve. We re-open the well
1036 // for the next global iteration, but if the zero rate persists, it will be stopped.
1037 // This logic is introduced to prevent/ameliorate stopped/revived oscillations
1038 this->operability_status_.resetOperability();
1039 this->openWell();
1040 deferred_logger.debug(" " + this->name() + " is re-opened after being stopped during local solve");
1041 number_of_well_reopenings_++;
1042 }
1043 } else {
1044 // unsolvable wells are treated as not operable and will not be solved for in this iteration.
1045 if (this->param_.shut_unsolvable_wells_) {
1046 this->operability_status_.solvable = false;
1047 }
1048 }
1049 }
1050 if (this->operability_status_.has_negative_potentials) {
1051 auto well_state_copy = well_state;
1052 std::vector<Scalar> potentials;
1053 try {
1054 computeWellPotentials(simulator, well_state_copy, groupStateHelper, potentials, deferred_logger);
1055 } catch (const std::exception& e) {
1056 const std::string msg = fmt::format("well {}: computeWellPotentials() failed "
1057 "during attempt to recompute potentials for well: ",
1058 this->name(), e.what());
1059 deferred_logger.info(msg);
1060 this->operability_status_.has_negative_potentials = true;
1061 }
1062 auto& ws = well_state.well(this->indexOfWell());
1063 const int np = well_state.numPhases();
1064 for (int p = 0; p < np; ++p) {
1065 ws.well_potentials[p] = std::max(Scalar{0.0}, potentials[p]);
1066 }
1067 }
1068 this->changed_to_open_this_step_ = false;
1069 changed_to_stopped_this_step_ = false;
1070
1071 const bool well_operable = this->operability_status_.isOperableAndSolvable();
1072 if (!well_operable) {
1073 this->stopWell();
1074 try {
1075 this->solveWellWithZeroRate(
1076 simulator, dt, groupStateHelper, well_state, deferred_logger
1077 );
1078 } catch (const std::exception& e) {
1079 const std::string msg = fmt::format("well {}: solveWellWithZeroRate() failed "
1080 "during attempt to solve with zero rate for well: ",
1081 this->name(), e.what());
1082 deferred_logger.info(msg);
1083 // we set the rate to zero to make sure the well dont contribute to the group rate
1084 auto& ws = well_state.well(this->indexOfWell());
1085 const int np = well_state.numPhases();
1086 for (int p = 0; p < np; ++p) {
1087 ws.surface_rates[p] = Scalar{0.0};
1088 }
1089 }
1090 if (old_well_operable) {
1091 deferred_logger.debug(" well " + this->name() + " gets STOPPED during iteration ");
1092 changed_to_stopped_this_step_ = true;
1093 }
1094 } else if (well_state.isOpen(this->name())) {
1095 this->openWell();
1096 if (!old_well_operable) {
1097 deferred_logger.debug(" well " + this->name() + " gets REVIVED during iteration ");
1098 this->changed_to_open_this_step_ = true;
1099 }
1100 }
1101 }
1102
1103 template<typename TypeTag>
1104 void
1105 WellInterface<TypeTag>::addCellRates(std::map<int, RateVector>& cellRates_) const
1106 {
1107 if(!this->operability_status_.solvable)
1108 return;
1109
1110 for (int perfIdx = 0; perfIdx < this->number_of_local_perforations_; ++perfIdx) {
1111 const auto cellIdx = this->cells()[perfIdx];
1112 const auto it = cellRates_.find(cellIdx);
1113 RateVector rates = (it == cellRates_.end()) ? 0.0 : it->second;
1114 for (auto i=0*RateVector::dimension; i < RateVector::dimension; ++i)
1115 {
1116 rates[i] += connectionRates_[perfIdx][i];
1117 }
1118 cellRates_.insert_or_assign(cellIdx, rates);
1119 }
1120 }
1121
1122 template<typename TypeTag>
1125 {
1126 for (int perfIdx = 0; perfIdx < this->number_of_local_perforations_; ++perfIdx) {
1127 if (this->cells()[perfIdx] == cellIdx) {
1128 const unsigned activeCompIdx = FluidSystem::canonicalToActiveCompIdx(FluidSystem::solventComponentIndex(phaseIdx));
1129 return connectionRates_[perfIdx][activeCompIdx].value();
1130 }
1131 }
1132 // this is not thread safe
1133 OPM_THROW(std::invalid_argument, "The well with name " + this->name()
1134 + " does not perforate cell " + std::to_string(cellIdx));
1135 return 0.0;
1136 }
1137
1138
1139
1140
1141 template<typename TypeTag>
1142 void
1144 checkWellOperability(const Simulator& simulator,
1145 const WellStateType& well_state,
1146 const GroupStateHelperType& groupStateHelper,
1147 DeferredLogger& deferred_logger)
1148 {
1149 OPM_TIMEFUNCTION();
1150 if (!this->param_.check_well_operability_) {
1151 return;
1152 }
1153
1154 if (this->wellIsStopped() && !changed_to_stopped_this_step_) {
1155 return;
1156 }
1157
1158 updateWellOperability(simulator, well_state, groupStateHelper, deferred_logger);
1159 if (!this->operability_status_.isOperableAndSolvable()) {
1160 this->operability_status_.use_vfpexplicit = true;
1161 deferred_logger.debug("EXPLICIT_LOOKUP_VFP",
1162 "well not operable, trying with explicit vfp lookup: " + this->name());
1163 updateWellOperability(simulator, well_state, groupStateHelper, deferred_logger);
1164 }
1165 }
1166
1167
1168
1169 template<typename TypeTag>
1170 void
1173 WellStateType& well_state,
1174 const GroupState<Scalar>& group_state,
1175 GLiftEclWells& ecl_well_map,
1176 DeferredLogger& deferred_logger)
1177 {
1178 OPM_TIMEFUNCTION();
1179 const auto& summary_state = simulator.vanguard().summaryState();
1180 const auto& well_name = this->name();
1181 if (!this->wellHasTHPConstraints(summary_state)) {
1182 const std::string msg = fmt::format("GLIFT WTEST: Well {} does not have THP constraints", well_name);
1183 deferred_logger.info(msg);
1184 return;
1185 }
1186 const auto& schedule = simulator.vanguard().schedule();
1187 const auto report_step_idx = simulator.episodeIndex();
1188 const auto& glo = schedule.glo(report_step_idx);
1189 if (!glo.has_well(well_name)) {
1190 const std::string msg = fmt::format(
1191 "GLIFT WTEST: Well {} : Gas lift not activated: "
1192 "WLIFTOPT is probably missing. Skipping.", well_name);
1193 deferred_logger.info(msg);
1194 return;
1195 }
1196 const auto& gl_well = glo.well(well_name);
1197
1198 // Use gas lift optimization to get ALQ for well test
1199 std::unique_ptr<GasLiftSingleWell> glift =
1200 initializeGliftWellTest_<GasLiftSingleWell>(simulator,
1201 well_state,
1202 group_state,
1203 ecl_well_map,
1204 deferred_logger);
1205 auto [wtest_alq, success] = glift->wellTestALQ();
1206 std::string msg;
1207 const auto& unit_system = schedule.getUnits();
1208 if (success) {
1209 well_state.well(well_name).alq_state.set(wtest_alq);
1210 msg = fmt::format(
1211 "GLIFT WTEST: Well {} : Setting ALQ to optimized value = {}",
1212 well_name, unit_system.from_si(UnitSystem::measure::gas_surface_rate, wtest_alq));
1213 }
1214 else {
1215 if (!gl_well.use_glo()) {
1216 msg = fmt::format(
1217 "GLIFT WTEST: Well {} : Gas lift optimization deactivated. Setting ALQ to WLIFTOPT item 3 = {}",
1218 well_name,
1219 unit_system.from_si(UnitSystem::measure::gas_surface_rate, well_state.well(well_name).alq_state.get()));
1220
1221 }
1222 else {
1223 msg = fmt::format(
1224 "GLIFT WTEST: Well {} : Gas lift optimization failed, no ALQ set.",
1225 well_name);
1226 }
1227 }
1228 deferred_logger.info(msg);
1229 }
1230
1231 template<typename TypeTag>
1232 void
1234 updateWellOperability(const Simulator& simulator,
1235 const WellStateType& well_state,
1236 const GroupStateHelperType& groupStateHelper,
1237 DeferredLogger& deferred_logger)
1238 {
1239 OPM_TIMEFUNCTION();
1240 if (this->param_.local_well_solver_control_switching_) {
1241 const bool success = updateWellOperabilityFromWellEq(simulator, groupStateHelper, deferred_logger);
1242 if (!success) {
1243 this->operability_status_.solvable = false;
1244 deferred_logger.debug("Operability check using well equations did not converge for well "
1245 + this->name() + ". Mark the well as unsolvable." );
1246 }
1247 return;
1248 }
1249 this->operability_status_.resetOperability();
1250
1251 bool thp_controlled = this->isInjector() ? well_state.well(this->index_of_well_).injection_cmode == Well::InjectorCMode::THP:
1252 well_state.well(this->index_of_well_).production_cmode == Well::ProducerCMode::THP;
1253 bool bhp_controlled = this->isInjector() ? well_state.well(this->index_of_well_).injection_cmode == Well::InjectorCMode::BHP:
1254 well_state.well(this->index_of_well_).production_cmode == Well::ProducerCMode::BHP;
1255
1256 // Operability checking is not free
1257 // Only check wells under BHP and THP control
1258 bool check_thp = thp_controlled || this->operability_status_.thp_limit_violated_but_not_switched;
1259 if (check_thp || bhp_controlled) {
1260 updateIPR(simulator, deferred_logger);
1261 checkOperabilityUnderBHPLimit(well_state, simulator, deferred_logger);
1262 }
1263 // we do some extra checking for wells under THP control.
1264 if (check_thp) {
1265 checkOperabilityUnderTHPLimit(simulator, well_state, groupStateHelper, deferred_logger);
1266 }
1267 }
1268
1269 template<typename TypeTag>
1270 bool
1273 const GroupStateHelperType& groupStateHelper,
1274 DeferredLogger& deferred_logger)
1275 {
1276 OPM_TIMEFUNCTION();
1277 // only makes sense if we're using this parameter is true
1278 assert(this->param_.local_well_solver_control_switching_);
1279 this->operability_status_.resetOperability();
1280 GroupStateHelperType groupStateHelper_copy = groupStateHelper;
1281 WellStateType well_state_copy = groupStateHelper_copy.wellState();
1282 const double dt = simulator.timeStepSize();
1283 // Ensure that groupStateHelper uses well_state_copy as WellState for iterateWellEquations()
1284 // and the guard ensures that the original well state is restored at scope exit, i.e. at
1285 // the end of this function.
1286 auto guard = groupStateHelper_copy.pushWellState(well_state_copy);
1287 // equations should be converged at this stage, so only one it is needed
1288 bool converged = iterateWellEquations(simulator, dt, groupStateHelper_copy, well_state_copy, deferred_logger);
1289 return converged;
1290 }
1291
1292 template<typename TypeTag>
1293 void
1295 scaleSegmentRatesAndPressure([[maybe_unused]] WellStateType& well_state) const
1296 {
1297 // only relevant for MSW
1298 }
1299
1300 template<typename TypeTag>
1301 void
1303 updateWellStateWithTarget(const Simulator& simulator,
1304 const GroupStateHelperType& groupStateHelper,
1305 WellStateType& well_state,
1306 DeferredLogger& deferred_logger) const
1307 {
1308 OPM_TIMEFUNCTION();
1309 // only bhp and wellRates are used to initilize the primaryvariables for standard wells
1310 const auto& well = this->well_ecl_;
1311 const int well_index = this->index_of_well_;
1312 auto& ws = well_state.well(well_index);
1313 const int np = well_state.numPhases();
1314 const auto& summaryState = simulator.vanguard().summaryState();
1315 const auto& schedule = simulator.vanguard().schedule();
1316
1317 // Discard old primary variables, the new well state
1318 // may not be anywhere near the old one.
1319 ws.primaryvar.resize(0);
1320
1321 if (this->wellIsStopped()) {
1322 for (int p = 0; p<np; ++p) {
1323 ws.surface_rates[p] = 0;
1324 }
1325 ws.thp = 0;
1326 return;
1327 }
1328
1329 if (this->isInjector() )
1330 {
1331 const auto& controls = well.injectionControls(summaryState);
1332
1333 InjectorType injectorType = controls.injector_type;
1334 int phasePos;
1335 switch (injectorType) {
1336 case InjectorType::WATER:
1337 {
1338 phasePos = FluidSystem::canonicalToActivePhaseIdx(FluidSystem::waterPhaseIdx);
1339 break;
1340 }
1341 case InjectorType::OIL:
1342 {
1343 phasePos = FluidSystem::canonicalToActivePhaseIdx(FluidSystem::oilPhaseIdx);
1344 break;
1345 }
1346 case InjectorType::GAS:
1347 {
1348 phasePos = FluidSystem::canonicalToActivePhaseIdx(FluidSystem::gasPhaseIdx);
1349 break;
1350 }
1351 default:
1352 OPM_DEFLOG_THROW(std::runtime_error, "Expected WATER, OIL or GAS as type for injectors " + this->name(), deferred_logger );
1353 }
1354
1355 const auto current = ws.injection_cmode;
1356
1357 switch (current) {
1358 case Well::InjectorCMode::RATE:
1359 {
1360 ws.surface_rates[phasePos] = (1.0 - this->rsRvInj()) * controls.surface_rate;
1361 if(this->rsRvInj() > 0) {
1362 if (injectorType == InjectorType::OIL && FluidSystem::phaseIsActive(FluidSystem::gasPhaseIdx)) {
1363 const int gas_pos = FluidSystem::canonicalToActivePhaseIdx(FluidSystem::gasPhaseIdx);
1364 ws.surface_rates[gas_pos] = controls.surface_rate * this->rsRvInj();
1365 } else if (injectorType == InjectorType::GAS && FluidSystem::phaseIsActive(FluidSystem::oilPhaseIdx)) {
1366 const int oil_pos = FluidSystem::canonicalToActivePhaseIdx(FluidSystem::oilPhaseIdx);
1367 ws.surface_rates[oil_pos] = controls.surface_rate * this->rsRvInj();
1368 } else {
1369 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 );
1370 }
1371 }
1372 break;
1373 }
1374
1375 case Well::InjectorCMode::RESV:
1376 {
1377 std::vector<Scalar> convert_coeff(this->number_of_phases_, 1.0);
1378 this->rateConverter_.calcCoeff(/*fipreg*/ 0, this->pvtRegionIdx_, convert_coeff);
1379 const Scalar coeff = convert_coeff[phasePos];
1380 ws.surface_rates[phasePos] = controls.reservoir_rate/coeff;
1381 break;
1382 }
1383
1384 case Well::InjectorCMode::THP:
1385 {
1386 auto rates = ws.surface_rates;
1387 Scalar bhp = WellBhpThpCalculator(*this).calculateBhpFromThp(well_state,
1388 rates,
1389 well,
1390 summaryState,
1391 this->getRefDensity(),
1392 deferred_logger);
1393 ws.bhp = bhp;
1394 ws.thp = this->getTHPConstraint(summaryState);
1395
1396 // if the total rates are negative or zero
1397 // we try to provide a better intial well rate
1398 // using the well potentials
1399 Scalar total_rate = std::accumulate(rates.begin(), rates.end(), 0.0);
1400 if (total_rate <= 0.0)
1401 ws.surface_rates = ws.well_potentials;
1402
1403 break;
1404 }
1405 case Well::InjectorCMode::BHP:
1406 {
1407 ws.bhp = controls.bhp_limit;
1408 Scalar total_rate = 0.0;
1409 for (int p = 0; p<np; ++p) {
1410 total_rate += ws.surface_rates[p];
1411 }
1412 // if the total rates are negative or zero
1413 // we try to provide a better intial well rate
1414 // using the well potentials
1415 if (total_rate <= 0.0)
1416 ws.surface_rates = ws.well_potentials;
1417
1418 break;
1419 }
1420 case Well::InjectorCMode::GRUP:
1421 {
1422 assert(well.isAvailableForGroupControl());
1423 const auto& group = schedule.getGroup(well.groupName(), this->currentStep());
1424 const Scalar efficiencyFactor = well.getEfficiencyFactor() *
1425 well_state[well.name()].efficiency_scaling_factor;
1426 std::optional<Scalar> target =
1427 this->getGroupInjectionTargetRate(group,
1428 groupStateHelper,
1429 injectorType,
1430 efficiencyFactor,
1431 deferred_logger);
1432 if (target)
1433 ws.surface_rates[phasePos] = *target;
1434 break;
1435 }
1436 case Well::InjectorCMode::CMODE_UNDEFINED:
1437 {
1438 OPM_DEFLOG_THROW(std::runtime_error, "Well control must be specified for well " + this->name(), deferred_logger );
1439 }
1440
1441 }
1442 // for wells with zero injection rate, if we assign exactly zero rate,
1443 // we will have to assume some trivial composition in the wellbore.
1444 // here, we use some small value (about 0.01 m^3/day ~= 1.e-7) to initialize
1445 // the zero rate target, then we can use to retain the composition information
1446 // within the wellbore from the previous result, and hopefully it is a good
1447 // initial guess for the zero rate target.
1448 ws.surface_rates[phasePos] = std::max(Scalar{1.e-7}, ws.surface_rates[phasePos]);
1449
1450 if (ws.bhp == 0.) {
1451 ws.bhp = controls.bhp_limit;
1452 }
1453 }
1454 //Producer
1455 else
1456 {
1457 const auto current = ws.production_cmode;
1458 const auto& controls = well.productionControls(summaryState);
1459 switch (current) {
1460 case Well::ProducerCMode::ORAT:
1461 {
1462 const int oil_pos = FluidSystem::canonicalToActivePhaseIdx(FluidSystem::oilPhaseIdx);
1463 Scalar current_rate = -ws.surface_rates[oil_pos];
1464 // for trivial rates or opposite direction we don't just scale the rates
1465 // but use either the potentials or the mobility ratio to initial the well rates
1466 if (current_rate > 0.0) {
1467 for (int p = 0; p<np; ++p) {
1468 ws.surface_rates[p] *= controls.oil_rate/current_rate;
1469 }
1470 } else {
1471 const std::vector<Scalar> fractions = initialWellRateFractions(simulator, well_state);
1472 double control_fraction = fractions[oil_pos];
1473 if (control_fraction != 0.0) {
1474 for (int p = 0; p<np; ++p) {
1475 ws.surface_rates[p] = - fractions[p] * controls.oil_rate/control_fraction;
1476 }
1477 }
1478 }
1479 break;
1480 }
1481 case Well::ProducerCMode::WRAT:
1482 {
1483 const int water_pos = FluidSystem::canonicalToActivePhaseIdx(FluidSystem::waterPhaseIdx);
1484 Scalar current_rate = -ws.surface_rates[water_pos];
1485 // for trivial rates or opposite direction we don't just scale the rates
1486 // but use either the potentials or the mobility ratio to initial the well rates
1487 if (current_rate > 0.0) {
1488 for (int p = 0; p<np; ++p) {
1489 ws.surface_rates[p] *= controls.water_rate/current_rate;
1490 }
1491 } else {
1492 const std::vector<Scalar> fractions = initialWellRateFractions(simulator, well_state);
1493 const Scalar control_fraction = fractions[water_pos];
1494 if (control_fraction != 0.0) {
1495 for (int p = 0; p<np; ++p) {
1496 ws.surface_rates[p] = - fractions[p] * controls.water_rate / control_fraction;
1497 }
1498 }
1499 }
1500 break;
1501 }
1502 case Well::ProducerCMode::GRAT:
1503 {
1504 const int gas_pos = FluidSystem::canonicalToActivePhaseIdx(FluidSystem::gasPhaseIdx);
1505 Scalar current_rate = -ws.surface_rates[gas_pos];
1506 // or trivial rates or opposite direction we don't just scale the rates
1507 // but use either the potentials or the mobility ratio to initial the well rates
1508 if (current_rate > 0.0) {
1509 for (int p = 0; p<np; ++p) {
1510 ws.surface_rates[p] *= controls.gas_rate/current_rate;
1511 }
1512 } else {
1513 const std::vector<Scalar > fractions = initialWellRateFractions(simulator, well_state);
1514 const Scalar control_fraction = fractions[gas_pos];
1515 if (control_fraction != 0.0) {
1516 for (int p = 0; p<np; ++p) {
1517 ws.surface_rates[p] = - fractions[p] * controls.gas_rate / control_fraction;
1518 }
1519 }
1520 }
1521
1522 break;
1523
1524 }
1525 case Well::ProducerCMode::LRAT:
1526 {
1527 const int water_pos = FluidSystem::canonicalToActivePhaseIdx(FluidSystem::waterPhaseIdx);
1528 const int oil_pos = FluidSystem::canonicalToActivePhaseIdx(FluidSystem::oilPhaseIdx);
1529 Scalar current_rate = - ws.surface_rates[water_pos]
1530 - ws.surface_rates[oil_pos];
1531 // or trivial rates or opposite direction we don't just scale the rates
1532 // but use either the potentials or the mobility ratio to initial the well rates
1533 if (current_rate > 0.0) {
1534 for (int p = 0; p<np; ++p) {
1535 ws.surface_rates[p] *= controls.liquid_rate/current_rate;
1536 }
1537 } else {
1538 const std::vector<Scalar> fractions = initialWellRateFractions(simulator, well_state);
1539 const Scalar control_fraction = fractions[water_pos] + fractions[oil_pos];
1540 if (control_fraction != 0.0) {
1541 for (int p = 0; p<np; ++p) {
1542 ws.surface_rates[p] = - fractions[p] * controls.liquid_rate / control_fraction;
1543 }
1544 }
1545 }
1546 break;
1547 }
1548 case Well::ProducerCMode::CRAT:
1549 {
1550 OPM_DEFLOG_THROW(std::runtime_error,
1551 fmt::format("CRAT control not supported, well {}", this->name()),
1552 deferred_logger);
1553 }
1554 case Well::ProducerCMode::RESV:
1555 {
1556 std::vector<Scalar> convert_coeff(this->number_of_phases_, 1.0);
1557 this->rateConverter_.calcCoeff(/*fipreg*/ 0, this->pvtRegionIdx_, ws.surface_rates, convert_coeff);
1558 Scalar total_res_rate = 0.0;
1559 for (int p = 0; p<np; ++p) {
1560 total_res_rate -= ws.surface_rates[p] * convert_coeff[p];
1561 }
1562 if (controls.prediction_mode) {
1563 // or trivial rates or opposite direction we don't just scale the rates
1564 // but use either the potentials or the mobility ratio to initial the well rates
1565 if (total_res_rate > 0.0) {
1566 for (int p = 0; p<np; ++p) {
1567 ws.surface_rates[p] *= controls.resv_rate/total_res_rate;
1568 }
1569 } else {
1570 const std::vector<Scalar> fractions = initialWellRateFractions(simulator, well_state);
1571 for (int p = 0; p<np; ++p) {
1572 ws.surface_rates[p] = - fractions[p] * controls.resv_rate / convert_coeff[p];
1573 }
1574 }
1575 } else {
1576 std::vector<Scalar> hrates(this->number_of_phases_,0.);
1577 if (FluidSystem::phaseIsActive(FluidSystem::waterPhaseIdx)) {
1578 const int phase_pos = FluidSystem::canonicalToActivePhaseIdx(FluidSystem::waterPhaseIdx);
1579 hrates[phase_pos] = controls.water_rate;
1580 }
1581 if (FluidSystem::phaseIsActive(FluidSystem::oilPhaseIdx)) {
1582 const int phase_pos = FluidSystem::canonicalToActivePhaseIdx(FluidSystem::oilPhaseIdx);
1583 hrates[phase_pos] = controls.oil_rate;
1584 }
1585 if (FluidSystem::phaseIsActive(FluidSystem::gasPhaseIdx)) {
1586 const int phase_pos = FluidSystem::canonicalToActivePhaseIdx(FluidSystem::gasPhaseIdx);
1587 hrates[phase_pos] = controls.gas_rate;
1588 }
1589 std::vector<Scalar> hrates_resv(this->number_of_phases_,0.);
1590 this->rateConverter_.calcReservoirVoidageRates(/*fipreg*/ 0, this->pvtRegionIdx_, hrates, hrates_resv);
1591 Scalar target = std::accumulate(hrates_resv.begin(), hrates_resv.end(), 0.0);
1592 // or trivial rates or opposite direction we don't just scale the rates
1593 // but use either the potentials or the mobility ratio to initial the well rates
1594 if (total_res_rate > 0.0) {
1595 for (int p = 0; p<np; ++p) {
1596 ws.surface_rates[p] *= target/total_res_rate;
1597 }
1598 } else {
1599 const std::vector<Scalar> fractions = initialWellRateFractions(simulator, well_state);
1600 for (int p = 0; p<np; ++p) {
1601 ws.surface_rates[p] = - fractions[p] * target / convert_coeff[p];
1602 }
1603 }
1604 }
1605 break;
1606 }
1607 case Well::ProducerCMode::BHP:
1608 {
1609 ws.bhp = controls.bhp_limit;
1610 Scalar total_rate = 0.0;
1611 for (int p = 0; p<np; ++p) {
1612 total_rate -= ws.surface_rates[p];
1613 }
1614 // if the total rates are negative or zero
1615 // we try to provide a better intial well rate
1616 // using the well potentials
1617 if (total_rate <= 0.0){
1618 for (int p = 0; p<np; ++p) {
1619 ws.surface_rates[p] = -ws.well_potentials[p];
1620 }
1621 }
1622 break;
1623 }
1624 case Well::ProducerCMode::THP:
1625 {
1626 const bool update_success = updateWellStateWithTHPTargetProd(simulator, well_state, groupStateHelper, deferred_logger);
1627
1628 if (!update_success) {
1629 // the following is the original way of initializing well state with THP constraint
1630 // keeping it for robust reason in case that it fails to get a bhp value with THP constraint
1631 // more sophisticated design might be needed in the future
1632 auto rates = ws.surface_rates;
1633 this->adaptRatesForVFP(rates);
1635 well_state, rates, well, summaryState, this->getRefDensity(), deferred_logger);
1636 ws.bhp = bhp;
1637 ws.thp = this->getTHPConstraint(summaryState);
1638 // if the total rates are negative or zero
1639 // we try to provide a better initial well rate
1640 // using the well potentials
1641 const Scalar total_rate = -std::accumulate(rates.begin(), rates.end(), 0.0);
1642 if (total_rate <= 0.0) {
1643 for (int p = 0; p < this->number_of_phases_; ++p) {
1644 ws.surface_rates[p] = -ws.well_potentials[p];
1645 }
1646 }
1647 }
1648 break;
1649 }
1650 case Well::ProducerCMode::GRUP:
1651 {
1652 assert(well.isAvailableForGroupControl());
1653 const auto& group = schedule.getGroup(well.groupName(), this->currentStep());
1654 const Scalar efficiencyFactor = well.getEfficiencyFactor() *
1655 well_state[well.name()].efficiency_scaling_factor;
1656 Scalar scale = this->getGroupProductionTargetRate(group,
1657 groupStateHelper,
1658 efficiencyFactor,
1659 deferred_logger);
1660
1661 // we don't want to scale with zero and get zero rates.
1662 if (scale > 0) {
1663 for (int p = 0; p<np; ++p) {
1664 ws.surface_rates[p] *= scale;
1665 }
1666 ws.trivial_group_target = false;
1667 } else {
1668 // If group target is trivial we dont want to flip to other controls. To avoid oscillation we store
1669 // this information in the well state and explicitly check for this condition when evaluating well controls.
1670 ws.trivial_group_target = true;
1671 }
1672 break;
1673 }
1674 case Well::ProducerCMode::CMODE_UNDEFINED:
1676 {
1677 OPM_DEFLOG_THROW(std::runtime_error, "Well control must be specified for well " + this->name() , deferred_logger);
1678 break;
1679 }
1680 } // end of switch
1681
1682 if (ws.bhp == 0.) {
1683 ws.bhp = controls.bhp_limit;
1684 }
1685 }
1686 }
1687
1688 template<typename TypeTag>
1689 bool
1691 wellUnderZeroRateTarget(const GroupStateHelperType& groupStateHelper, DeferredLogger& deferred_logger) const
1692 {
1693 OPM_TIMEFUNCTION();
1694 const auto& well_state = groupStateHelper.wellState();
1695 // Check if well is under zero rate control, either directly or from group
1696 const bool isGroupControlled = this->wellUnderGroupControl(well_state.well(this->index_of_well_));
1697 if (!isGroupControlled) {
1698 // well is not under group control, check "individual" version
1699 const auto& summaryState = groupStateHelper.summaryState();
1700 return this->wellUnderZeroRateTargetIndividual(summaryState, well_state);
1701 } else {
1702 return this->wellUnderZeroGroupRateTarget(groupStateHelper, deferred_logger, isGroupControlled);
1703 }
1704 }
1705
1706 template <typename TypeTag>
1707 bool
1709 DeferredLogger& deferred_logger,
1710 const std::optional<bool> group_control) const
1711 {
1712 const auto& well_state = groupStateHelper.wellState();
1713 // Check if well is under zero rate target from group
1714 const bool isGroupControlled = group_control.value_or(this->wellUnderGroupControl(well_state.well(this->index_of_well_)));
1715 if (isGroupControlled) {
1716 return this->zeroGroupRateTarget(groupStateHelper, deferred_logger);
1717 }
1718 return false;
1719 }
1720
1721 template<typename TypeTag>
1722 bool
1724 stoppedOrZeroRateTarget(const GroupStateHelperType& groupStateHelper,
1725 DeferredLogger& deferred_logger) const
1726 {
1727 // Check if well is stopped or under zero rate control, either
1728 // directly or from group.
1729 return this->wellIsStopped()
1730 || this->wellUnderZeroRateTarget(groupStateHelper, deferred_logger);
1731 }
1732
1733 template<typename TypeTag>
1734 std::vector<typename WellInterface<TypeTag>::Scalar>
1736 initialWellRateFractions(const Simulator& simulator,
1737 const WellStateType& well_state) const
1738 {
1739 OPM_TIMEFUNCTION();
1740 const int np = this->number_of_phases_;
1741 std::vector<Scalar> scaling_factor(np);
1742 const auto& ws = well_state.well(this->index_of_well_);
1743
1744 Scalar total_potentials = 0.0;
1745 for (int p = 0; p<np; ++p) {
1746 total_potentials += ws.well_potentials[p];
1747 }
1748 if (total_potentials > 0) {
1749 for (int p = 0; p<np; ++p) {
1750 scaling_factor[p] = ws.well_potentials[p] / total_potentials;
1751 }
1752 return scaling_factor;
1753 }
1754 // if we don't have any potentials we weight it using the mobilites
1755 // We only need approximation so we don't bother with the vapporized oil and dissolved gas
1756 Scalar total_tw = 0;
1757 const int nperf = this->number_of_local_perforations_;
1758 for (int perf = 0; perf < nperf; ++perf) {
1759 total_tw += this->well_index_[perf];
1760 }
1761 total_tw = this->parallelWellInfo().communication().sum(total_tw);
1762
1763 for (int perf = 0; perf < nperf; ++perf) {
1764 const int cell_idx = this->well_cells_[perf];
1765 const auto& intQuants = simulator.model().intensiveQuantities(cell_idx, /*timeIdx=*/0);
1766 const auto& fs = intQuants.fluidState();
1767 const Scalar well_tw_fraction = this->well_index_[perf] / total_tw;
1768 Scalar total_mobility = 0.0;
1769 for (int p = 0; p < np; ++p) {
1770 const int canonical_phase_idx = FluidSystem::activeToCanonicalPhaseIdx(p);
1771 total_mobility += fs.invB(canonical_phase_idx).value() * intQuants.mobility(canonical_phase_idx).value();
1772 }
1773 for (int p = 0; p < np; ++p) {
1774 const int canonical_phase_idx = FluidSystem::activeToCanonicalPhaseIdx(p);
1775 scaling_factor[p] += well_tw_fraction * fs.invB(canonical_phase_idx).value() * intQuants.mobility(canonical_phase_idx).value() / total_mobility;
1776 }
1777 }
1778 return scaling_factor;
1779 }
1780
1781
1782
1783 template <typename TypeTag>
1784 void
1787 WellStateType& well_state,
1788 DeferredLogger& deferred_logger) const
1789 {
1790 assert(this->isProducer());
1791 OPM_TIMEFUNCTION();
1792 // Check if the rates of this well only are single-phase, do nothing
1793 // if more than one nonzero rate.
1794 auto& ws = well_state.well(this->index_of_well_);
1795 int nonzero_rate_index = -1;
1796 const Scalar floating_point_error_epsilon = 1e-14;
1797 for (int p = 0; p < this->number_of_phases_; ++p) {
1798 if (std::abs(ws.surface_rates[p]) > floating_point_error_epsilon) {
1799 if (nonzero_rate_index == -1) {
1800 nonzero_rate_index = p;
1801 } else {
1802 // More than one nonzero rate.
1803 return;
1804 }
1805 }
1806 }
1807
1808 // Calculate rates at bhp limit, or 1 bar if no limit.
1809 std::vector<Scalar> well_q_s(this->number_of_phases_, 0.0);
1810 bool rates_evaluated_at_1bar = false;
1811 {
1812 const auto& summary_state = simulator.vanguard().summaryState();
1813 const auto& prod_controls = this->well_ecl_.productionControls(summary_state);
1814 const double bhp_limit = std::max(prod_controls.bhp_limit, 1.0 * unit::barsa);
1815 this->computeWellRatesWithBhp(simulator, bhp_limit, well_q_s, deferred_logger);
1816 // Remember of we evaluated the rates at (approx.) 1 bar or not.
1817 rates_evaluated_at_1bar = (bhp_limit < 1.1 * unit::barsa);
1818 // Check that no rates are positive.
1819 if (std::any_of(well_q_s.begin(), well_q_s.end(), [](Scalar q) { return q > 0.0; })) {
1820 // Did we evaluate at 1 bar? If not, then we can try again at 1 bar.
1821 if (!rates_evaluated_at_1bar) {
1822 this->computeWellRatesWithBhp(simulator, 1.0 * unit::barsa, well_q_s, deferred_logger);
1823 rates_evaluated_at_1bar = true;
1824 }
1825 // At this point we can only set the wrong-direction (if any) values to zero.
1826 for (auto& q : well_q_s) {
1827 q = std::min(q, Scalar{0.0});
1828 }
1829 }
1830 }
1831
1832 if (nonzero_rate_index == -1) {
1833 // No nonzero rates on input.
1834 // Use the computed rate directly, or scaled by a factor
1835 // 0.5 (to avoid too high values) if it was evaluated at 1 bar.
1836 const Scalar factor = rates_evaluated_at_1bar ? 0.5 : 1.0;
1837 for (int p = 0; p < this->number_of_phases_; ++p) {
1838 ws.surface_rates[p] = factor * well_q_s[p];
1839 }
1840 return;
1841 }
1842
1843 // If we are here, we had a single nonzero rate for the well,
1844 // typically from a rate constraint. We must make sure it is
1845 // respected, so if it was lower than the calculated rate for
1846 // the same phase we scale all rates to match.
1847 const Scalar initial_nonzero_rate = ws.surface_rates[nonzero_rate_index];
1848 const Scalar computed_rate = well_q_s[nonzero_rate_index];
1849 if (std::abs(initial_nonzero_rate) < std::abs(computed_rate)) {
1850 // Note that both rates below are negative. The factor should be < 1.0.
1851 const Scalar factor = initial_nonzero_rate / computed_rate;
1852 assert(factor < 1.0);
1853 for (int p = 0; p < this->number_of_phases_; ++p) {
1854 // We skip the nonzero_rate_index, as that should remain as it was.
1855 if (p != nonzero_rate_index) {
1856 ws.surface_rates[p] = factor * well_q_s[p];
1857 }
1858 }
1859 return;
1860 }
1861
1862 // If we are here, we had a single nonzero rate, but it was
1863 // higher than the one calculated from the bhp limit, so we
1864 // use the calculated rates.
1865 for (int p = 0; p < this->number_of_phases_; ++p) {
1866 ws.surface_rates[p] = well_q_s[p];
1867 }
1868 }
1869
1870 template <typename TypeTag>
1871 template<class Value>
1872 void
1874 getTw(std::vector<Value>& Tw,
1875 const int perf,
1876 const IntensiveQuantities& intQuants,
1877 const Value& trans_mult,
1878 const SingleWellStateType& ws) const
1879 {
1880 OPM_TIMEFUNCTION_LOCAL(Subsystem::Wells);
1881 // Add a Forchheimer term to the gas phase CTF if the run uses
1882 // either of the WDFAC or the WDFACCOR keywords.
1883 if (static_cast<std::size_t>(perf) >= this->well_cells_.size()) {
1884 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!");
1885 }
1886
1887 if constexpr (! Indices::gasEnabled) {
1888 return;
1889 }
1890
1891 const auto& wdfac = this->well_ecl_.getWDFAC();
1892
1893 if (! wdfac.useDFactor() || (this->well_index_[perf] == 0.0)) {
1894 return;
1895 }
1896
1897 const Scalar d = this->computeConnectionDFactor(perf, intQuants, ws);
1898 if (d < 1.0e-15) {
1899 return;
1900 }
1901
1902 // Solve quadratic equations for connection rates satisfying the ipr and the flow-dependent skin.
1903 // If more than one solution, pick the one corresponding to lowest absolute rate (smallest skin).
1904 const auto& connection = this->well_ecl_.getConnections()[ws.perf_data.ecl_index[perf]];
1905 const Scalar Kh = connection.Kh();
1906 const Scalar scaling = 3.141592653589 * Kh * connection.wpimult();
1907 const unsigned gas_comp_idx = FluidSystem::canonicalToActiveCompIdx(FluidSystem::gasCompIdx);
1908
1909 const Scalar connection_pressure = ws.perf_data.pressure[perf];
1910 const Scalar cell_pressure = getValue(intQuants.fluidState().pressure(FluidSystem::gasPhaseIdx));
1911 const Scalar drawdown = cell_pressure - connection_pressure;
1912 const Scalar invB = getValue(intQuants.fluidState().invB(FluidSystem::gasPhaseIdx));
1913 const Scalar mob_g = getValue(intQuants.mobility(FluidSystem::gasPhaseIdx)) * invB;
1914 const Scalar a = d;
1915 const Scalar b = 2 * scaling / getValue(Tw[gas_comp_idx]);
1916 const Scalar c = -2 * scaling * mob_g * drawdown;
1917
1918 Scalar consistent_Q = -1.0e20;
1919 // Find and check negative solutions (a --> -a)
1920 const Scalar r2n = b*b + 4*a*c;
1921 if (r2n >= 0) {
1922 const Scalar rn = std::sqrt(r2n);
1923 const Scalar xn1 = (b-rn)*0.5/a;
1924 if (xn1 <= 0) {
1925 consistent_Q = xn1;
1926 }
1927 const Scalar xn2 = (b+rn)*0.5/a;
1928 if (xn2 <= 0 && xn2 > consistent_Q) {
1929 consistent_Q = xn2;
1930 }
1931 }
1932 // Find and check positive solutions
1933 consistent_Q *= -1;
1934 const Scalar r2p = b*b - 4*a*c;
1935 if (r2p >= 0) {
1936 const Scalar rp = std::sqrt(r2p);
1937 const Scalar xp1 = (rp-b)*0.5/a;
1938 if (xp1 > 0 && xp1 < consistent_Q) {
1939 consistent_Q = xp1;
1940 }
1941 const Scalar xp2 = -(rp+b)*0.5/a;
1942 if (xp2 > 0 && xp2 < consistent_Q) {
1943 consistent_Q = xp2;
1944 }
1945 }
1946 Tw[gas_comp_idx] = 1.0 / (1.0 / (trans_mult * this->well_index_[perf]) + (consistent_Q/2 * d / scaling));
1947 }
1948
1949 template <typename TypeTag>
1950 void
1952 updateConnectionDFactor(const Simulator& simulator,
1953 SingleWellStateType& ws) const
1954 {
1955 if (! this->well_ecl_.getWDFAC().useDFactor()) {
1956 return;
1957 }
1958
1959 auto& d_factor = ws.perf_data.connection_d_factor;
1960
1961 for (int perf = 0; perf < this->number_of_local_perforations_; ++perf) {
1962 const int cell_idx = this->well_cells_[perf];
1963 const auto& intQuants = simulator.model().intensiveQuantities(cell_idx, /*timeIdx=*/ 0);
1964
1965 d_factor[perf] = this->computeConnectionDFactor(perf, intQuants, ws);
1966 }
1967 }
1968
1969 template <typename TypeTag>
1972 computeConnectionDFactor(const int perf,
1973 const IntensiveQuantities& intQuants,
1974 const SingleWellStateType& ws) const
1975 {
1976 auto rhoGS = [regIdx = this->pvtRegionIdx()]() {
1977 return FluidSystem::referenceDensity(FluidSystem::gasPhaseIdx, regIdx);
1978 };
1979
1980 // Viscosity is evaluated at connection pressure.
1981 auto gas_visc = [connection_pressure = ws.perf_data.pressure[perf],
1982 temperature = ws.temperature,
1983 regIdx = this->pvtRegionIdx(), &intQuants]()
1984 {
1985 const auto rv = getValue(intQuants.fluidState().Rv());
1986
1987 const auto& gasPvt = FluidSystem::gasPvt();
1988
1989 // Note that rv here is from grid block with typically
1990 // p_block > connection_pressure
1991 // so we may very well have rv > rv_sat
1992 const Scalar rv_sat = gasPvt.saturatedOilVaporizationFactor
1993 (regIdx, temperature, connection_pressure);
1994
1995 if (! (rv < rv_sat)) {
1996 return gasPvt.saturatedViscosity(regIdx, temperature,
1997 connection_pressure);
1998 }
1999
2000 return gasPvt.viscosity(regIdx, temperature, connection_pressure,
2001 rv, getValue(intQuants.fluidState().Rvw()));
2002 };
2003
2004 const auto& connection = this->well_ecl_.getConnections()
2005 [ws.perf_data.ecl_index[perf]];
2006
2007 return this->well_ecl_.getWDFAC().getDFactor(rhoGS, gas_visc, connection);
2008 }
2009
2010
2011 template <typename TypeTag>
2012 void
2015 SingleWellStateType& ws) const
2016 {
2017 auto connCF = [&connIx = std::as_const(ws.perf_data.ecl_index),
2018 &conns = this->well_ecl_.getConnections()]
2019 (const int perf)
2020 {
2021 return conns[connIx[perf]].CF();
2022 };
2023
2024 auto obtain = [](const Eval& value)
2025 {
2026 return getValue(value);
2027 };
2028
2029 auto& tmult = ws.perf_data.connection_compaction_tmult;
2030 auto& ctf = ws.perf_data.connection_transmissibility_factor;
2031
2032 for (int perf = 0; perf < this->number_of_local_perforations_; ++perf) {
2033 const int cell_idx = this->well_cells_[perf];
2034 Scalar trans_mult(0.0);
2035 getTransMult(trans_mult, simulator, cell_idx, obtain);
2036 tmult[perf] = trans_mult;
2037
2038 ctf[perf] = connCF(perf) * tmult[perf];
2039 }
2040 }
2041
2042
2043 template<typename TypeTag>
2046 {
2047 if constexpr (Indices::oilEnabled) {
2048 return fs.pressure(FluidSystem::oilPhaseIdx);
2049 } else if constexpr (Indices::gasEnabled) {
2050 return fs.pressure(FluidSystem::gasPhaseIdx);
2051 } else {
2052 return fs.pressure(FluidSystem::waterPhaseIdx);
2053 }
2054 }
2055
2056 template <typename TypeTag>
2057 template<class Value, class Callback>
2058 void
2060 getTransMult(Value& trans_mult,
2061 const Simulator& simulator,
2062 const int cell_idx,
2063 Callback& extendEval) const
2064 {
2065 const auto& intQuants = simulator.model().intensiveQuantities(cell_idx, /*timeIdx=*/ 0);
2066 trans_mult = simulator.problem().template wellTransMultiplier<Value>(intQuants, cell_idx, extendEval);
2067 }
2068
2069 template <typename TypeTag>
2070 template<class Value, class Callback>
2071 void
2073 getMobility(const Simulator& simulator,
2074 const int local_perf_index,
2075 std::vector<Value>& mob,
2076 Callback& extendEval,
2077 [[maybe_unused]] DeferredLogger& deferred_logger) const
2078 {
2079 auto relpermArray = []()
2080 {
2081 if constexpr (std::is_same_v<Value, Scalar>) {
2082 return std::array<Scalar,3>{};
2083 } else {
2084 return std::array<Eval,3>{};
2085 }
2086 };
2087 if (static_cast<std::size_t>(local_perf_index) >= this->well_cells_.size()) {
2088 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!");
2089 }
2090 const int cell_idx = this->well_cells_[local_perf_index];
2091 assert (int(mob.size()) == this->num_conservation_quantities_);
2092 const auto& intQuants = simulator.model().intensiveQuantities(cell_idx, /*timeIdx=*/0);
2093 const auto& materialLawManager = simulator.problem().materialLawManager();
2094
2095 // either use mobility of the perforation cell or calculate its own
2096 // based on passing the saturation table index
2097 const int satid = this->saturation_table_number_[local_perf_index] - 1;
2098 const int satid_elem = materialLawManager->satnumRegionIdx(cell_idx);
2099 if (satid == satid_elem) { // the same saturation number is used. i.e. just use the mobilty from the cell
2100 for (unsigned phaseIdx = 0; phaseIdx < FluidSystem::numPhases; ++phaseIdx) {
2101 if (!FluidSystem::phaseIsActive(phaseIdx)) {
2102 continue;
2103 }
2104
2105 const unsigned activeCompIdx = FluidSystem::canonicalToActiveCompIdx(FluidSystem::solventComponentIndex(phaseIdx));
2106 mob[activeCompIdx] = extendEval(intQuants.mobility(phaseIdx));
2107 }
2108 if constexpr (has_solvent) {
2109 mob[Indices::contiSolventEqIdx] = extendEval(intQuants.solventMobility());
2110 }
2111 } else {
2112 const auto& paramsCell = materialLawManager->connectionMaterialLawParams(satid, cell_idx);
2113 auto relativePerms = relpermArray();
2114 MaterialLaw::relativePermeabilities(relativePerms, paramsCell, intQuants.fluidState());
2115
2116 // reset the satnumvalue back to original
2117 materialLawManager->connectionMaterialLawParams(satid_elem, cell_idx);
2118
2119 // compute the mobility
2120 for (unsigned phaseIdx = 0; phaseIdx < FluidSystem::numPhases; ++phaseIdx) {
2121 if (!FluidSystem::phaseIsActive(phaseIdx)) {
2122 continue;
2123 }
2124
2125 const unsigned activeCompIdx = FluidSystem::canonicalToActiveCompIdx(FluidSystem::solventComponentIndex(phaseIdx));
2126 mob[activeCompIdx] = extendEval(relativePerms[phaseIdx] / intQuants.fluidState().viscosity(phaseIdx));
2127 }
2128
2129 // this may not work if viscosity and relperms has been modified?
2130 if constexpr (has_solvent) {
2131 OPM_DEFLOG_THROW(std::runtime_error, "individual mobility for wells does not work in combination with solvent", deferred_logger);
2132 }
2133 }
2134
2135 if (this->isInjector() && !this->inj_fc_multiplier_.empty()) {
2136 const auto perf_ecl_index = this->perforationData()[local_perf_index].ecl_index;
2137 const auto& connections = this->well_ecl_.getConnections();
2138 const auto& connection = connections[perf_ecl_index];
2139 if (connection.filterCakeActive()) {
2140 std::transform(mob.begin(), mob.end(), mob.begin(),
2141 [mult = this->inj_fc_multiplier_[local_perf_index] ](const auto val)
2142 { return val * mult; });
2143 }
2144 }
2145 }
2146
2147
2148 template<typename TypeTag>
2149 bool
2152 WellStateType& well_state,
2153 const GroupStateHelperType& groupStateHelper,
2154 DeferredLogger& deferred_logger) const
2155 {
2156 OPM_TIMEFUNCTION();
2157 const auto& summary_state = simulator.vanguard().summaryState();
2158
2159 auto bhp_at_thp_limit = computeBhpAtThpLimitProdWithAlq(
2160 simulator, groupStateHelper, summary_state, this->getALQ(well_state), deferred_logger, /*iterate_if_no_solution */ false);
2161 if (bhp_at_thp_limit) {
2162 std::vector<Scalar> rates(this->number_of_phases_, 0.0);
2163 if (thp_update_iterations) {
2164 computeWellRatesWithBhpIterations(simulator, *bhp_at_thp_limit,
2165 groupStateHelper, rates, deferred_logger);
2166 } else {
2167 computeWellRatesWithBhp(simulator, *bhp_at_thp_limit,
2168 rates, deferred_logger);
2169 }
2170 auto& ws = well_state.well(this->name());
2171 ws.surface_rates = rates;
2172 ws.bhp = *bhp_at_thp_limit;
2173 ws.thp = this->getTHPConstraint(summary_state);
2174 return true;
2175 } else {
2176 return false;
2177 }
2178 }
2179
2180 template<typename TypeTag>
2181 std::optional<typename WellInterface<TypeTag>::Scalar>
2184 const WellStateType& well_state,
2185 Scalar bhp,
2186 const SummaryState& summary_state,
2187 const Scalar alq_value,
2188 DeferredLogger& deferred_logger)
2189 {
2190 OPM_TIMEFUNCTION();
2191 WellStateType well_state_copy = well_state;
2192 const auto& groupStateHelper = simulator.problem().wellModel().groupStateHelper();
2193 GroupStateHelperType groupStateHelper_copy = groupStateHelper;
2194 auto well_guard = groupStateHelper_copy.pushWellState(well_state_copy);
2195 const double dt = simulator.timeStepSize();
2196 const bool converged = this->solveWellWithBhp(
2197 simulator, dt, bhp, groupStateHelper_copy, well_state_copy, deferred_logger
2198 );
2199
2200 bool zero_rates;
2201 auto rates = well_state_copy.well(this->index_of_well_).surface_rates;
2202 zero_rates = true;
2203 for (std::size_t p = 0; p < rates.size(); ++p) {
2204 zero_rates &= rates[p] == 0.0;
2205 }
2206 // For zero rates or unconverged bhp the implicit IPR is problematic.
2207 // Use the old approach for now
2208 if (zero_rates || !converged) {
2209 return this->computeBhpAtThpLimitProdWithAlq(simulator, groupStateHelper_copy, summary_state, alq_value, deferred_logger, /*iterate_if_no_solution */ false);
2210 }
2211 this->updateIPRImplicit(simulator, groupStateHelper_copy, well_state_copy, deferred_logger);
2212 this->adaptRatesForVFP(rates);
2213 return WellBhpThpCalculator(*this).estimateStableBhp(well_state_copy, this->well_ecl_, rates, this->getRefDensity(), summary_state, alq_value);
2214 }
2215
2216 template <typename TypeTag>
2217 void
2220 const std::function<Scalar(const Scalar)>& connPICalc,
2221 const std::vector<Scalar>& mobility,
2222 Scalar* connPI) const
2223 {
2224 const int np = this->number_of_phases_;
2225 for (int p = 0; p < np; ++p) {
2226 // Note: E100's notion of PI value phase mobility includes
2227 // the reciprocal FVF.
2228 const int canonical_phase_idx = FluidSystem::activeToCanonicalPhaseIdx(p);
2229 const auto connMob =
2230 mobility[FluidSystem::activePhaseToActiveCompIdx(p)] * fs.invB(canonical_phase_idx).value();
2231
2232 connPI[p] = connPICalc(connMob);
2233 }
2234
2235 if (FluidSystem::phaseIsActive(FluidSystem::oilPhaseIdx) &&
2236 FluidSystem::phaseIsActive(FluidSystem::gasPhaseIdx))
2237 {
2238 const auto io = FluidSystem::canonicalToActivePhaseIdx(FluidSystem::oilPhaseIdx);
2239 const auto ig = FluidSystem::canonicalToActivePhaseIdx(FluidSystem::gasPhaseIdx);
2240
2241 const auto vapoil = connPI[ig] * fs.Rv().value();
2242 const auto disgas = connPI[io] * fs.Rs().value();
2243
2244 connPI[io] += vapoil;
2245 connPI[ig] += disgas;
2246 }
2247 }
2248
2249
2250 template <typename TypeTag>
2251 void
2254 const Phase preferred_phase,
2255 const std::function<Scalar(const Scalar)>& connIICalc,
2256 const std::vector<Scalar>& mobility,
2257 Scalar* connII,
2258 DeferredLogger& deferred_logger) const
2259 {
2260 auto phase_pos = 0;
2261 if (preferred_phase == Phase::GAS) {
2262 phase_pos = FluidSystem::canonicalToActivePhaseIdx(FluidSystem::gasPhaseIdx);
2263 }
2264 else if (preferred_phase == Phase::OIL) {
2265 phase_pos = FluidSystem::canonicalToActivePhaseIdx(FluidSystem::oilPhaseIdx);
2266 }
2267 else if (preferred_phase == Phase::WATER) {
2268 phase_pos = FluidSystem::canonicalToActivePhaseIdx(FluidSystem::waterPhaseIdx);
2269 }
2270 else {
2271 OPM_DEFLOG_THROW(NotImplemented,
2272 fmt::format("Unsupported Injector Type ({}) "
2273 "for well {} during connection I.I. calculation",
2274 static_cast<int>(preferred_phase), this->name()),
2275 deferred_logger);
2276 }
2277
2278 const auto mt = std::accumulate(mobility.begin(), mobility.end(), 0.0);
2279 const int canonicalPhaseIdx = FluidSystem::activeToCanonicalPhaseIdx(phase_pos);
2280 connII[phase_pos] = connIICalc(mt * fs.invB(canonicalPhaseIdx).value());
2281 }
2282
2283 template<typename TypeTag>
2284 template<class GasLiftSingleWell>
2285 std::unique_ptr<GasLiftSingleWell>
2287 initializeGliftWellTest_(const Simulator& simulator,
2288 WellStateType& well_state,
2289 const GroupState<Scalar>& group_state,
2290 GLiftEclWells& ecl_well_map,
2291 DeferredLogger& deferred_logger)
2292 {
2293 // Instantiate group info object (without initialization) since it is needed in GasLiftSingleWell
2294 auto& comm = simulator.vanguard().grid().comm();
2295 ecl_well_map.try_emplace(this->name(), &(this->wellEcl()), this->indexOfWell());
2297 ecl_well_map,
2298 simulator.vanguard().schedule(),
2299 simulator.vanguard().summaryState(),
2300 simulator.episodeIndex(),
2301 simulator.model().newtonMethod().numIterations(),
2302 deferred_logger,
2303 well_state,
2304 group_state,
2305 comm,
2306 false
2307 };
2308
2309 // Return GasLiftSingleWell object to use the wellTestALQ() function
2310 std::set<int> sync_groups;
2311 const auto& summary_state = simulator.vanguard().summaryState();
2312 return std::make_unique<GasLiftSingleWell>(*this,
2313 simulator,
2314 summary_state,
2315 deferred_logger,
2316 well_state,
2317 group_state,
2318 group_info,
2319 sync_groups,
2320 comm,
2321 false);
2322
2323 }
2324
2325} // namespace Opm
2326
2327#endif
#define OPM_DEFLOG_THROW(Exception, message, deferred_logger)
Definition: DeferredLoggingErrorHelpers.hpp:45
Definition: DeferredLogger.hpp:57
void info(const std::string &tag, const std::string &message)
void warning(const std::string &tag, const std::string &message)
void debug(const std::string &tag, const std::string &message)
Definition: GasLiftGroupInfo.hpp:46
Definition: GroupStateHelper.hpp:53
GroupState< Scalar > & groupState() const
Definition: GroupStateHelper.hpp:180
const SummaryState & summaryState() const
Definition: GroupStateHelper.hpp:257
const WellState< Scalar, IndexTraits > & wellState() const
Definition: GroupStateHelper.hpp:306
WellStateGuard pushWellState(WellState< Scalar, IndexTraits > &well_state)
Definition: GroupStateHelper.hpp:195
GroupStateGuard pushGroupState(GroupState< Scalar > &group_state)
Definition: GroupStateHelper.hpp:190
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 solveWellWithOperabilityCheck(const Simulator &simulator, const double dt, const Well::InjectionControls &inj_controls, const Well::ProductionControls &prod_controls, const GroupStateHelperType &groupStateHelper, WellStateType &well_state, DeferredLogger &deferred_logger)
Definition: WellInterface_impl.hpp:589
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:259
GetPropType< TypeTag, Properties::Simulator > Simulator
Definition: WellInterface.hpp:82
void assembleWellEqWithoutIteration(const Simulator &simulator, const GroupStateHelperType &groupStateHelper, const double dt, WellStateType &well_state, DeferredLogger &deferred_logger, const bool solving_with_zero_rate)
Definition: WellInterface_impl.hpp:964
Scalar computeConnectionDFactor(const int perf, const IntensiveQuantities &intQuants, const SingleWellStateType &ws) const
Definition: WellInterface_impl.hpp:1972
void checkWellOperability(const Simulator &simulator, const WellStateType &well_state, const GroupStateHelperType &groupStateHelper, DeferredLogger &deferred_logger)
Definition: WellInterface_impl.hpp:1144
std::optional< Scalar > computeBhpAtThpLimitProdWithAlqUsingIPR(const Simulator &simulator, const WellStateType &well_state, Scalar bhp, const SummaryState &summary_state, const Scalar alq_value, DeferredLogger &deferred_logger)
Definition: WellInterface_impl.hpp:2183
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, DeferredLogger &deferred_logger)
Definition: WellInterface_impl.hpp:395
typename WellInterfaceFluidSystem< FluidSystem >::RateConverterType RateConverterType
Definition: WellInterface.hpp:105
Scalar wfoam() const
Definition: WellInterface_impl.hpp:127
void getTransMult(Value &trans_mult, const Simulator &simulator, const int cell_idx, Callback &extendEval) const
Definition: WellInterface_impl.hpp:2060
std::vector< RateVector > connectionRates_
Definition: WellInterface.hpp:388
void computeConnLevelProdInd(const FluidState &fs, const std::function< Scalar(const Scalar)> &connPICalc, const std::vector< Scalar > &mobility, Scalar *connPI) const
Definition: WellInterface_impl.hpp:2219
bool iterateWellEquations(const Simulator &simulator, const double dt, const GroupStateHelperType &groupStateHelper, WellStateType &well_state, DeferredLogger &deferred_logger)
Definition: WellInterface_impl.hpp:521
void gliftBeginTimeStepWellTestUpdateALQ(const Simulator &simulator, WellStateType &well_state, const GroupState< Scalar > &group_state, GLiftEclWells &ecl_well_map, DeferredLogger &deferred_logger)
Definition: WellInterface_impl.hpp:1172
Scalar volumetricSurfaceRateForConnection(int cellIdx, int phaseIdx) const
Definition: WellInterface_impl.hpp:1124
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
void getTw(std::vector< Value > &wi, const int perf, const IntensiveQuantities &intQuants, const Value &trans_mult, const SingleWellStateType &ws) const
Definition: WellInterface_impl.hpp:1874
void getMobility(const Simulator &simulator, const int local_perf_index, std::vector< Value > &mob, Callback &extendEval, DeferredLogger &deferred_logger) const
Definition: WellInterface_impl.hpp:2073
GetPropType< TypeTag, Properties::IntensiveQuantities > IntensiveQuantities
Definition: WellInterface.hpp:87
bool wellUnderZeroGroupRateTarget(const GroupStateHelperType &groupStateHelper, DeferredLogger &deferred_logger, const std::optional< bool > group_control=std::nullopt) const
Definition: WellInterface_impl.hpp:1708
GetPropType< TypeTag, Properties::Scalar > Scalar
Definition: WellInterface.hpp:83
bool updateWellStateWithTHPTargetProd(const Simulator &simulator, WellStateType &well_state, const GroupStateHelperType &groupStateHelper, DeferredLogger &deferred_logger) const
Definition: WellInterface_impl.hpp:2151
std::vector< Scalar > initialWellRateFractions(const Simulator &ebosSimulator, const WellStateType &well_state) const
Definition: WellInterface_impl.hpp:1736
virtual void updateWellStateWithTarget(const Simulator &simulator, const GroupStateHelperType &groupStateHelper, WellStateType &well_state, DeferredLogger &deferred_logger) const
Definition: WellInterface_impl.hpp:1303
void updateConnectionDFactor(const Simulator &simulator, SingleWellStateType &ws) const
Definition: WellInterface_impl.hpp:1952
Eval getPerfCellPressure(const FluidState &fs) const
Definition: WellInterface_impl.hpp:2045
void initializeProducerWellState(const Simulator &simulator, WellStateType &well_state, DeferredLogger &deferred_logger) const
Definition: WellInterface_impl.hpp:1786
void updateWellOperability(const Simulator &simulator, const WellStateType &well_state, const GroupStateHelperType &groupStateHelper, DeferredLogger &deferred_logger)
Definition: WellInterface_impl.hpp:1234
bool updateWellControl(const Simulator &simulator, const IndividualOrGroup iog, const GroupStateHelperType &groupStateHelper, WellStateType &well_state, DeferredLogger &deferred_logger)
Definition: WellInterface_impl.hpp:189
void addCellRates(std::map< int, RateVector > &cellRates_) const
Definition: WellInterface_impl.hpp:1105
bool updateWellControlAndStatusLocalIteration(const Simulator &simulator, const GroupStateHelperType &groupStateHelper, const Well::InjectionControls &inj_controls, const Well::ProductionControls &prod_controls, const Scalar WQTotal, WellStateType &well_state, DeferredLogger &deferred_logger, const bool fixed_control, const bool fixed_status, const bool solving_with_zero_rate)
Definition: WellInterface_impl.hpp:277
bool wellUnderZeroRateTarget(const GroupStateHelperType &groupStateHelper, DeferredLogger &deferred_logger) const
Definition: WellInterface_impl.hpp:1691
typename Base::ModelParameters ModelParameters
Definition: WellInterface.hpp:111
GetPropType< TypeTag, Properties::FluidSystem > FluidSystem
Definition: WellInterface.hpp:84
static constexpr bool has_solvent
Definition: WellInterface.hpp:113
GetPropType< TypeTag, Properties::RateVector > RateVector
Definition: WellInterface.hpp:90
void updateConnectionTransmissibilityFactor(const Simulator &simulator, SingleWellStateType &ws) const
Definition: WellInterface_impl.hpp:2014
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:2253
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:2287
Scalar wsalt() const
Definition: WellInterface_impl.hpp:141
bool solveWellWithZeroRate(const Simulator &simulator, const double dt, const GroupStateHelperType &groupStateHelper, WellStateType &well_state, DeferredLogger &deferred_logger)
Definition: WellInterface_impl.hpp:797
bool updateWellOperabilityFromWellEq(const Simulator &simulator, const GroupStateHelperType &groupStateHelper, DeferredLogger &deferred_logger)
Definition: WellInterface_impl.hpp:1272
typename Base::Eval Eval
Definition: WellInterface.hpp:96
bool stoppedOrZeroRateTarget(const GroupStateHelperType &groupStateHelper, DeferredLogger &deferred_logger) const
Definition: WellInterface_impl.hpp:1724
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
void solveWellEquation(const Simulator &simulator, const GroupStateHelperType &groupStateHelper, WellStateType &well_state, DeferredLogger &deferred_logger)
Definition: WellInterface_impl.hpp:885
Scalar wpolymer() const
Definition: WellInterface_impl.hpp:111
GetPropType< TypeTag, Properties::Indices > Indices
Definition: WellInterface.hpp:86
bool solveWellForTesting(const Simulator &simulator, const GroupStateHelperType &groupStateHelper, WellStateType &well_state, DeferredLogger &deferred_logger)
Definition: WellInterface_impl.hpp:830
Scalar wurea() const
Definition: WellInterface_impl.hpp:177
Scalar wmicrobes() const
Definition: WellInterface_impl.hpp:153
void prepareWellBeforeAssembling(const Simulator &simulator, const double dt, const GroupStateHelperType &groupStateHelper, WellStateType &well_state, DeferredLogger &deferred_logger)
Definition: WellInterface_impl.hpp:985
virtual void scaleSegmentRatesAndPressure(WellStateType &well_state) const
Definition: WellInterface_impl.hpp:1295
std::optional< Scalar > estimateOperableBhp(const Simulator &ebos_simulator, const double dt, const GroupStateHelperType &groupStateHelper, const SummaryState &summary_state, WellStateType &well_state, DeferredLogger &deferred_logger)
Definition: WellInterface_impl.hpp:709
bool solveWellWithBhp(const Simulator &simulator, const double dt, const Scalar bhp, const GroupStateHelperType &groupStateHelper, WellStateType &well_state, DeferredLogger &deferred_logger)
Definition: WellInterface_impl.hpp:747
static constexpr bool has_zFraction
Definition: WellInterface.hpp:114
void assembleWellEq(const Simulator &simulator, const double dt, const GroupStateHelperType &groupStateHelper, WellStateType &well_state, DeferredLogger &deferred_logger)
Definition: WellInterface_impl.hpp:947
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:141
Definition: blackoilbioeffectsmodules.hh:43
std::string to_string(const ConvergenceReport::ReservoirFailure::Type t)
Static data associated with a well perforation.
Definition: PerforationData.hpp:30