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