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