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