22#ifndef OPM_WELLINTERFACE_IMPL_HEADER_INCLUDED
23#define OPM_WELLINTERFACE_IMPL_HEADER_INCLUDED
26#ifndef OPM_WELLINTERFACE_HEADER_INCLUDED
31#include <opm/common/Exceptions.hpp>
33#include <opm/input/eclipse/Schedule/ScheduleTypes.hpp>
34#include <opm/input/eclipse/Schedule/Well/WDFAC.hpp>
35#include <opm/input/eclipse/Schedule/Well/WELDRAW.hpp>
46#include <dune/common/version.hh>
55#include <fmt/format.h>
61 template<
typename TypeTag>
68 const int pvtRegionIdx,
69 const int num_conservation_quantities,
71 const int index_of_well,
79 num_conservation_quantities,
87 if (well.isInjector()) {
88 auto injectorType = this->
well_ecl_.injectorType();
89 if (injectorType == InjectorType::GAS) {
97 template<
typename TypeTag>
100 init(
const std::vector<Scalar>& ,
102 const std::vector<Scalar>& B_avg,
103 const bool changed_to_open_this_step)
105 this->gravity_ = gravity_arg;
107 this->changed_to_open_this_step_ = changed_to_open_this_step;
113 template<
typename TypeTag>
118 if constexpr (has_polymer) {
119 return this->wpolymer_();
129 template<
typename TypeTag>
134 if constexpr (has_foam) {
135 return this->wfoam_();
143 template<
typename TypeTag>
148 if constexpr (has_brine) {
149 return this->wsalt_();
155 template<
typename TypeTag>
160 if constexpr (has_micp) {
161 return this->wmicrobes_();
167 template<
typename TypeTag>
172 if constexpr (has_micp) {
173 return this->woxygen_();
179 template<
typename TypeTag>
184 if constexpr (has_micp) {
185 return this->wurea_();
191 template<
typename TypeTag>
201 if (stoppedOrZeroRateTarget(groupStateHelper)) {
205 const auto& summaryState = simulator.vanguard().summaryState();
206 const auto& schedule = simulator.vanguard().schedule();
207 const auto& well = this->well_ecl_;
208 auto& ws = well_state.
well(this->index_of_well_);
210 bool is_grup =
false;
211 if (well.isInjector()) {
212 from = WellInjectorCMode2String(ws.injection_cmode);
213 is_grup = ws.injection_cmode == Well::InjectorCMode::GRUP;
215 from = WellProducerCMode2String(ws.production_cmode);
216 is_grup = ws.production_cmode == Well::ProducerCMode::GRUP;
219 const int episodeIdx = simulator.episodeIndex();
220 const auto& iterCtx = simulator.problem().iterationContext();
221 const int nupcol = schedule[episodeIdx].nupcol();
222 const bool oscillating =
223 std::ranges::count(this->well_control_log_, from) >= this->param_.max_number_of_well_switches_;
224 if (oscillating && !is_grup) {
227 std::ranges::count(this->well_control_log_, from) == this->param_.max_number_of_well_switches_;
229 const auto msg = fmt::format(
" The control mode for well {} is oscillating. \n"
230 "We don't allow for more than {} switches after NUPCOL iterations. (NUPCOL = {}) \n"
231 "The control is kept at {}.",
232 this->name(), this->param_.max_number_of_well_switches_, nupcol, from);
233 deferred_logger.info(msg);
235 this->well_control_log_.push_back(from);
239 bool changed =
false;
240 if (iog == IndividualOrGroup::Individual) {
241 changed = this->checkIndividualConstraints(ws, summaryState, deferred_logger);
242 }
else if (iog == IndividualOrGroup::Group) {
243 changed = this->checkGroupConstraints(
244 groupStateHelper, schedule, summaryState,
true, well_state
247 assert(iog == IndividualOrGroup::Both);
248 changed = this->checkConstraints(groupStateHelper, schedule, summaryState, well_state);
254 if (well.isInjector()) {
255 to = WellInjectorCMode2String(ws.injection_cmode);
257 to = WellProducerCMode2String(ws.production_cmode);
259 std::ostringstream ss;
260 ss <<
" Switching control mode for well " << this->name()
263 if (iterCtx.inLocalSolve()) {
264 ss <<
" (NLDD domain solve)";
267 ss <<
" on rank " << cc.rank();
269 deferred_logger.debug(ss.str());
276 if (!iterCtx.inLocalSolve()) {
277 if (!iterCtx.withinNupcol(nupcol) || this->log_all_control_switches_
278 || this->well_control_log_.empty()) {
279 this->well_control_log_.push_back(from);
282 updateWellStateWithTarget(simulator, groupStateHelper, well_state);
283 updatePrimaryVariables(groupStateHelper);
289 template<
typename TypeTag>
296 if (!this->isProducer()) {
300 auto& ws = well_state.
well(this->index_of_well_);
301 const auto& weldraw = this->well_ecl_.getWELDRAW();
302 if (!weldraw.active()) {
303 ws.weldraw_max_rate.reset();
304 ws.weldraw_cmode.reset();
308 const auto& summary_state = simulator.vanguard().summaryState();
309 const Scalar max_draw = this->well_ecl_.weldrawMaxDrawdown(summary_state);
310 if (!(max_draw > 0.0)) {
311 ws.weldraw_max_rate.reset();
312 ws.weldraw_cmode.reset();
323 this->updateIPR(simulator, deferred_logger);
325 auto phase_coeff = [
this](
const unsigned phase_idx) ->
Scalar {
326 const unsigned comp_idx = FluidSystem::canonicalToActiveCompIdx(
327 FluidSystem::solventComponentIndex(phase_idx));
328 return this->ipr_b_[comp_idx];
332 const bool gas_target = (weldraw.targetPhase() == WELDRAW::TargetPhase::GAS);
334 if (FluidSystem::phaseIsActive(FluidSystem::gasPhaseIdx)) {
335 coeff += phase_coeff(FluidSystem::gasPhaseIdx);
339 if (FluidSystem::phaseIsActive(FluidSystem::oilPhaseIdx)) {
340 coeff += phase_coeff(FluidSystem::oilPhaseIdx);
342 if (FluidSystem::phaseIsActive(FluidSystem::waterPhaseIdx)) {
343 coeff += phase_coeff(FluidSystem::waterPhaseIdx);
347 if (!(coeff > 0.0)) {
353 deferred_logger.
warning(
"WELDRAW_NO_TARGET_PHASE_MOBILITY",
354 fmt::format(
"Well {}: the WELDRAW target phase ({}) has no "
355 "producible mobility; the drawdown limit is ignored.",
356 this->name(), gas_target ?
"GAS" :
"LIQ"));
357 ws.weldraw_max_rate.reset();
358 ws.weldraw_cmode.reset();
362 const Scalar max_rate = max_draw * coeff;
363 ws.weldraw_max_rate = max_rate;
368 const auto controls = this->well_ecl_.productionControls(summary_state);
369 const auto cmode = gas_target ? Well::ProducerCMode::GRAT
370 : Well::ProducerCMode::LRAT;
371 const Scalar own_target = gas_target ? controls.gas_rate
372 : controls.liquid_rate;
373 if (!controls.hasControl(cmode) || (max_rate <= own_target)) {
374 ws.weldraw_cmode = cmode;
377 ws.weldraw_cmode.reset();
381 template<
typename TypeTag>
386 const Well::InjectionControls& inj_controls,
387 const Well::ProductionControls& prod_controls,
390 const bool fixed_control,
391 const bool fixed_status,
392 const bool solving_with_zero_rate)
396 const auto& summary_state = simulator.vanguard().summaryState();
397 const auto& schedule = simulator.vanguard().schedule();
398 auto& ws = well_state.
well(this->index_of_well_);
400 if (this->isInjector()) {
401 from = WellInjectorCMode2String(ws.injection_cmode);
403 from = WellProducerCMode2String(ws.production_cmode);
405 const bool oscillating =
406 std::ranges::count(this->well_control_log_, from) >= this->param_.max_number_of_well_switches_;
408 if (oscillating || this->wellUnderZeroRateTarget(groupStateHelper) || !(well_state.
well(this->index_of_well_).status == WellStatus::OPEN)) {
412 const Scalar sgn = this->isInjector() ? 1.0 : -1.0;
413 if (!this->wellIsStopped()){
414 if (wqTotal*sgn <= 0.0 && !fixed_status){
418 bool changed =
false;
419 if (!fixed_control) {
422 if (solving_with_zero_rate) {
424 "Well {}: solving_with_zero_rate should not be true when fixed_control is false",
425 this->name()), deferred_logger);
431 const bool hasGroupControl = this->isInjector() ? inj_controls.hasControl(Well::InjectorCMode::GRUP) :
432 prod_controls.hasControl(Well::ProducerCMode::GRUP);
433 bool isGroupControl = ws.production_cmode == Well::ProducerCMode::GRUP || ws.injection_cmode == Well::InjectorCMode::GRUP;
434 if (! (isGroupControl && !this->param_.check_group_constraints_inner_well_iterations_)) {
435 changed = this->checkIndividualConstraints(ws, summary_state, deferred_logger, inj_controls, prod_controls);
437 if (hasGroupControl && this->param_.check_group_constraints_inner_well_iterations_) {
438 changed = changed || this->checkGroupConstraints(
439 groupStateHelper, schedule, summary_state,
false, well_state
444 const bool thp_controlled = this->isInjector() ? ws.injection_cmode == Well::InjectorCMode::THP :
445 ws.production_cmode == Well::ProducerCMode::THP;
447 ws.thp = this->getTHPConstraint(summary_state);
450 updateWellStateWithTarget(simulator, groupStateHelper, well_state);
452 updatePrimaryVariables(groupStateHelper);
457 }
else if (!fixed_status){
459 const Scalar bhp = well_state.
well(this->index_of_well_).bhp;
460 Scalar prod_limit = prod_controls.bhp_limit;
461 Scalar inj_limit = inj_controls.bhp_limit;
462 const bool has_thp = this->wellHasTHPConstraints(summary_state);
464 std::vector<Scalar> rates(this->num_conservation_quantities_);
465 if (this->isInjector()){
467 calculateBhpFromThp(well_state, rates,
470 this->getRefDensity(),
472 inj_limit = std::min(bhp_thp,
static_cast<Scalar>(inj_controls.bhp_limit));
477 calculateMinimumBhpFromThp(well_state,
480 this->getRefDensity());
481 prod_limit = std::max(bhp_min,
static_cast<Scalar>(prod_controls.bhp_limit));
484 const Scalar bhp_diff = (this->isInjector())? inj_limit - bhp: bhp - prod_limit;
487 well_state.
well(this->index_of_well_).bhp = (this->isInjector())? inj_limit : prod_limit;
489 well_state.
well(this->index_of_well_).thp = this->getTHPConstraint(summary_state);
500 template<
typename TypeTag>
504 const double simulation_time,
507 WellTestState& well_test_state,
509 std::map<std::string, double>& open_times)
513 const auto& group_state = groupStateHelper.
groupState();
517 const auto& unit_system = simulator.vanguard().eclState().getUnits();
518 const auto start_time = simulator.vanguard().schedule().getStartTime();
520 fmt::format(
"at time {:.2f} {} (date = {})",
521 unit_system.from_si(UnitSystem::measure::time, simulation_time),
522 unit_system.name(UnitSystem::measure::time),
525 deferred_logger.info(fmt::format(
"Well {} is being tested {}.", this->name(), when));
532 auto guard = groupStateHelper_copy.
pushWellState(well_state_copy);
533 auto& ws = well_state_copy.
well(this->indexOfWell());
535 const auto& summary_state = simulator.vanguard().summaryState();
536 const bool has_thp_limit = this->wellHasTHPConstraints(summary_state);
537 if (this->isProducer()) {
538 ws.production_cmode = has_thp_limit ? Well::ProducerCMode::THP : Well::ProducerCMode::BHP;
540 ws.injection_cmode = has_thp_limit ? Well::InjectorCMode::THP : Well::InjectorCMode::BHP;
545 scaleSegmentRatesAndPressure(well_state_copy);
546 calculateExplicitQuantities(simulator, groupStateHelper_copy);
547 updatePrimaryVariables(groupStateHelper_copy);
549 if (this->isProducer()) {
550 const auto& schedule = simulator.vanguard().schedule();
551 const auto report_step = simulator.episodeIndex();
552 const auto& glo = schedule.glo(report_step);
554 gliftBeginTimeStepWellTestUpdateALQ(simulator,
562 WellTestState welltest_state_temp;
564 std::string closure_reason;
570 auto notReopened = [
this, &when, &deferred_logger](
const std::string_view reason)
572 deferred_logger.info(
573 fmt::format(
"Well {} is not re-opened {}.", this->name(), when));
574 if (!reason.empty()) {
575 deferred_logger.debug(fmt::format(
"Because {}.", reason));
579 bool testWell =
true;
584 const std::size_t original_number_closed_completions = welltest_state_temp.num_closed_completions();
585 bool converged = solveWellForTesting(simulator, groupStateHelper_copy, well_state_copy);
587 notReopened(
"the well equations could not be solved");
592 updateWellOperability(simulator, well_state_copy, groupStateHelper_copy);
593 if ( !this->isOperableAndSolvable() ) {
594 notReopened(
"the well is not operable");
597 std::vector<Scalar> potentials;
599 computeWellPotentials(simulator, well_state_copy, groupStateHelper_copy, potentials);
600 }
catch (
const std::exception& e) {
601 notReopened(fmt::format(
"computing the well potentials failed: {}", e.what()));
604 const int np = well_state_copy.
numPhases();
605 for (
int p = 0; p < np; ++p) {
606 ws.well_potentials[p] = std::max(
Scalar{0.0}, potentials[p]);
608 const bool under_zero_target = this->wellUnderZeroGroupRateTarget(groupStateHelper_copy);
609 this->updateWellTestState(well_state_copy.
well(this->indexOfWell()),
615 simulator.vanguard().eclState().getUnits(),
616 simulator.vanguard().schedule().getStartTime(),
619 this->closeCompletions(welltest_state_temp);
625 if ( welltest_state_temp.num_closed_wells() > 0 ||
626 (original_number_closed_completions == welltest_state_temp.num_closed_completions()) ) {
632 if (!welltest_state_temp.well_is_closed(this->name())) {
633 well_test_state.open_well(this->name());
636 deferred_logger.info(
637 fmt::format(
"{}\nWell {} is re-opened {}.\n{}",
638 sep, this->name(), when, sep));
641 for (
const auto& completion : this->well_ecl_.getCompletions()) {
642 if (!welltest_state_temp.completion_is_closed(this->name(), completion.first))
643 well_test_state.open_completion(this->name(), completion.first);
645 well_state = well_state_copy;
646 open_times.try_emplace(this->name(), well_test_state.lastTestTime(this->name()));
650 notReopened(closure_reason);
657 template<
typename TypeTag>
668 const auto& summary_state = simulator.vanguard().summaryState();
669 const auto& ws = well_state.
well(this->indexOfWell());
670 const auto inj_controls = this->well_ecl_.isInjector() ? this->well_ecl_.injectionControls(summary_state) : Well::InjectionControls(0);
671 const auto prod_controls = this->well_ecl_.isProducer() ? this->productionControlsWithWeldraw(summary_state, ws) : Well::ProductionControls(0);
672 const auto pmode_orig = ws.production_cmode;
673 const auto imode_orig = ws.injection_cmode;
675 const auto ws_before_solve = ws;
676 bool converged =
false;
677 bool solve_threw =
false;
680 if (!this->param_.local_well_solver_control_switching_){
681 converged = this->iterateWellEqWithControl(simulator, dt, inj_controls, prod_controls, groupStateHelper, well_state);
683 if (this->param_.use_implicit_ipr_ && this->well_ecl_.isProducer() && (well_state.
well(this->index_of_well_).status == WellStatus::OPEN)) {
684 converged = solveWellWithOperabilityCheck(
685 simulator, dt, inj_controls, prod_controls, groupStateHelper, well_state
688 converged = this->iterateWellEqWithSwitching(
689 simulator, dt, inj_controls, prod_controls, groupStateHelper, well_state,
695 }
catch (NumericalProblem& e ) {
696 const std::string msg =
"Inner well iterations failed for well " + this->name() +
" Treat the well as unconverged. ";
697 deferred_logger.warning(
"INNER_ITERATION_FAILED", msg);
705 if (well_state.
well(this->indexOfWell()).restoreIfDiverged(ws_before_solve, solve_threw)) {
712 this->updatePrimaryVariables(groupStateHelper);
713 this->assembleWellEqWithoutIteration(simulator, groupStateHelper, dt, inj_controls, prod_controls,
715 }
catch (
const NumericalProblem&) {
721 if (ws.production_cmode != pmode_orig || ws.injection_cmode != imode_orig) {
723 if (this->isInjector()) {
724 from = WellInjectorCMode2String(imode_orig);
725 to = WellInjectorCMode2String(ws.injection_cmode);
727 from = WellProducerCMode2String(pmode_orig);
728 to = WellProducerCMode2String(ws.production_cmode);
730 const auto msg = fmt::format(
" Well {} switched from {} to {} during local solve", this->name(), from, to);
731 deferred_logger.debug(msg);
732 const int episodeIdx = simulator.episodeIndex();
733 const auto& iterCtx = simulator.problem().iterationContext();
734 const auto& schedule = simulator.vanguard().schedule();
735 const int nupcol = schedule[episodeIdx].nupcol();
739 if (!iterCtx.withinNupcol(nupcol) || this->log_all_control_switches_
740 || this->well_control_log_.empty()) {
741 this->well_control_log_.push_back(from);
746 if (this->isProducer() && ws.production_cmode == Well::ProducerCMode::GRUP && ws.use_group_target_fallback) {
747 assert(ws.group_target && ws.group_target_fallback);
748 const std::string cmode = Group::ProductionCMode2String(ws.group_target->production_cmode);
749 const std::string cmode_fallback = Group::ProductionCMode2String(ws.group_target_fallback->production_cmode);
750 const auto msg = fmt::format(
" Well {} was solved using group target fallback mode {} as current group mode {} was not feasible.",
751 this->name(), cmode_fallback, cmode);
752 deferred_logger.debug(msg);
758 template<
typename TypeTag>
763 auto& ws = well_state.
well(this->index_of_well_);
764 ws.rs_rep = ws.rv_rep = ws.rsw_rep = ws.rvw_rep = 0.0;
765 if (!this->isProducer()) {
769 const bool waterActive = FluidSystem::phaseIsActive(FluidSystem::waterPhaseIdx);
770 const bool oilActive = FluidSystem::phaseIsActive(FluidSystem::oilPhaseIdx);
771 const bool gasActive = FluidSystem::phaseIsActive(FluidSystem::gasPhaseIdx);
772 if (!gasActive || (!oilActive && !waterActive)) {
777 const int waterPos = waterActive ? FluidSystem::canonicalToActivePhaseIdx(FluidSystem::waterPhaseIdx) : -1;
778 const int oilPos = oilActive ? FluidSystem::canonicalToActivePhaseIdx(FluidSystem::oilPhaseIdx) : -1;
779 const int gasPos = FluidSystem::canonicalToActivePhaseIdx(FluidSystem::gasPhaseIdx);
783 const int numPhases = this->numPhases();
784 constexpr std::size_t numMixingRates = 4;
785 std::vector<Scalar> sums(numPhases + numMixingRates, 0.0);
786 const auto& perf_rates = ws.perf_data.phase_rates;
787 const auto& perf_mixing = ws.perf_data.phase_mixing_rates;
788 for (
int perf = 0; perf < this->numLocalPerfs(); ++perf) {
789 for (
int phase = 0; phase < numPhases; ++phase) {
790 sums[phase] += perf_rates[perf * numPhases + phase];
792 for (std::size_t mix = 0; mix < numMixingRates; ++mix) {
793 sums[numPhases + mix] += perf_mixing[perf][mix];
796 this->parallelWellInfo().communication().sum(sums.data(), sums.size());
798 const Scalar dis_gas = sums[numPhases + ws.dissolved_gas];
799 const Scalar dis_gas_water = sums[numPhases + ws.dissolved_gas_in_water];
800 const Scalar vap_oil = sums[numPhases + ws.vaporized_oil];
801 const Scalar vap_water = sums[numPhases + ws.vaporized_water];
805 const Scalar free_oil = oilActive ? sums[oilPos] - vap_oil : 0.0;
806 const Scalar free_water = waterActive ? sums[waterPos] - vap_water : 0.0;
807 const Scalar free_gas = sums[gasPos] - dis_gas - dis_gas_water;
808 const auto ratio = [](
const Scalar num,
const Scalar den) {
809 return (den != 0.0) ? num / den :
Scalar{0.0};
815 const Scalar surface_gas = std::abs(ws.surface_rates[gasPos]);
816 const Scalar solvent = has_solvent ? std::abs(ws.sum_solvent_rates()) :
Scalar{0.0};
817 const Scalar hydrocarbon_gas = std::max(surface_gas - solvent,
Scalar{0.0});
825 Scalar rvw = waterActive ? ratio(vap_water, free_gas) :
Scalar{0.0};
828 if (waterActive && FluidSystem::enableVaporizedWater()) {
829 const Scalar qw = std::abs(ws.surface_rates[waterPos]);
830 const Scalar qg = hydrocarbon_gas;
831 const Scalar rvw_max = FluidSystem::gasPvt()
832 .saturatedWaterVaporizationFactor(this->pvtRegionIdx(), ws.temperature, ws.bhp);
833 rvw = (qg > 0.0) ? std::min(qw / qg, rvw_max) :
Scalar{0.0};
838 const Scalar rs = ratio(dis_gas, free_oil);
839 const Scalar rv = ratio(vap_oil, free_gas);
840 if (rs >= 0.0 && rv >= 0.0 && rs * rv < 1.0) {
847 const Scalar qo = std::abs(ws.surface_rates[oilPos]);
848 const Scalar qg = hydrocarbon_gas;
849 const int pvtReg = this->pvtRegionIdx();
852 const Scalar rs_max = FluidSystem::enableDissolvedGas()
853 ? FluidSystem::oilPvt().saturatedGasDissolutionFactor(pvtReg, ws.temperature, ws.bhp)
855 const Scalar rv_max = FluidSystem::enableVaporizedOil()
856 ? FluidSystem::gasPvt().saturatedOilVaporizationFactor(pvtReg, ws.temperature, ws.bhp)
858 const Scalar rs_inf = (qo > 0.0) ? std::min(qg / qo, rs_max) :
Scalar{0.0};
859 const Scalar rv_inf = (qg > 0.0) ? std::min(qo / qg, rv_max) :
Scalar{0.0};
860 if (rs_inf * rv_inf < 1.0) {
870 const Scalar rsw = std::max(ratio(dis_gas_water, free_water),
Scalar{0.0});
872 ws.rvw_rep = (rsw * rvw < 1.0) ? rvw :
Scalar{0.0};
876 template<
typename TypeTag>
881 const Well::InjectionControls& inj_controls,
882 const Well::ProductionControls& prod_controls,
889 const auto& summary_state = simulator.vanguard().summaryState();
890 bool converged =
true;
891 auto& ws = well_state.
well(this->index_of_well_);
893 if (this->wellIsStopped()) {
895 const bool use_vfpexplicit = this->operability_status_.use_vfpexplicit;
896 this->operability_status_.use_vfpexplicit =
true;
897 auto bhp_target = estimateOperableBhp(simulator, dt, groupStateHelper, summary_state, well_state);
898 if (!bhp_target.has_value()) {
900 const auto msg = fmt::format(
"estimateOperableBhp: Did not find operable BHP for well {}", this->name());
901 deferred_logger.debug(msg);
904 converged = solveWellWithZeroRate(simulator, dt, groupStateHelper, well_state);
906 this->operability_status_.can_obtain_bhp_with_thp_limit =
false;
907 this->operability_status_.obey_thp_limit_under_bhp_limit =
false;
911 ws.thp = this->getTHPConstraint(summary_state);
912 const Scalar bhp = std::max(bhp_target.value(),
913 static_cast<Scalar>(prod_controls.bhp_limit));
914 solveWellWithBhp(simulator, dt, bhp, groupStateHelper, well_state);
915 this->operability_status_.use_vfpexplicit = use_vfpexplicit;
919 converged = this->iterateWellEqWithSwitching(
920 simulator, dt, inj_controls, prod_controls, groupStateHelper, well_state,
925 const bool isThp = ws.production_cmode == Well::ProducerCMode::THP;
927 if (converged && !stoppedOrZeroRateTarget(groupStateHelper) && isThp) {
928 auto rates = well_state.
well(this->index_of_well_).surface_rates;
929 this->adaptRatesForVFP(rates);
930 this->updateIPRImplicit(simulator, groupStateHelper, well_state);
934 this->operability_status_.use_vfpexplicit =
true;
937 const Scalar reltol = 1e-3;
938 const Scalar cur_bhp = ws.bhp;
939 if (bhp_stable.has_value() && cur_bhp - bhp_stable.value() > cur_bhp*reltol){
940 const auto msg = fmt::format(
"Well {} converged to an unstable solution, re-solving", this->name());
941 deferred_logger.debug(msg);
943 simulator, dt, bhp_stable.value(), groupStateHelper, well_state
946 ws.thp = this->getTHPConstraint(summary_state);
947 converged = this->iterateWellEqWithSwitching(
948 simulator, dt, inj_controls, prod_controls, groupStateHelper, well_state,
957 this->operability_status_.use_vfpexplicit =
true;
959 auto bhp_target = estimateOperableBhp(
960 simulator, dt, groupStateHelper, summary_state, well_state
962 if (!bhp_target.has_value()) {
965 converged = solveWellWithZeroRate(simulator, dt, groupStateHelper, well_state);
967 this->operability_status_.can_obtain_bhp_with_thp_limit =
false;
968 this->operability_status_.obey_thp_limit_under_bhp_limit =
false;
972 const Scalar bhp = std::max(bhp_target.value(),
973 static_cast<Scalar>(prod_controls.bhp_limit));
975 simulator, dt, bhp, groupStateHelper, well_state
977 ws.thp = this->getTHPConstraint(summary_state);
978 const auto msg = fmt::format(
"Well {} did not converge, re-solving with explicit fractions for VFP caculations.", this->name());
979 deferred_logger.debug(msg);
980 converged = this->iterateWellEqWithSwitching(simulator, dt,
991 this->operability_status_.can_obtain_bhp_with_thp_limit = !this->wellIsStopped();
992 this->operability_status_.obey_thp_limit_under_bhp_limit = !this->wellIsStopped();
996 template<
typename TypeTag>
997 std::optional<typename WellInterface<TypeTag>::Scalar>
1002 const SummaryState& summary_state,
1005 if (!this->wellHasTHPConstraints(summary_state)) {
1007 const bool converged = solveWellWithBhp(
1008 simulator, dt, bhp_limit, groupStateHelper, well_state
1010 if (!converged || this->wellIsStopped()) {
1011 return std::nullopt;
1021 const bool converged = solveWellWithBhp(
1022 simulator, dt, bhp_min, groupStateHelper, well_state
1024 if (!converged || this->wellIsStopped()) {
1025 return std::nullopt;
1027 this->updateIPRImplicit(simulator, groupStateHelper, well_state);
1028 auto rates = well_state.
well(this->index_of_well_).surface_rates;
1029 this->adaptRatesForVFP(rates);
1033 template<
typename TypeTag>
1050 auto group_guard = groupStateHelper_copy.
pushGroupState(group_state);
1052 auto inj_controls = Well::InjectionControls(0);
1053 auto prod_controls = Well::ProductionControls(0);
1054 auto& ws = well_state.
well(this->index_of_well_);
1055 auto cmode_inj = ws.injection_cmode;
1056 auto cmode_prod = ws.production_cmode;
1057 if (this->isInjector()) {
1058 inj_controls.addControl(Well::InjectorCMode::BHP);
1059 inj_controls.bhp_limit = bhp;
1060 inj_controls.cmode = Well::InjectorCMode::BHP;
1061 ws.injection_cmode = Well::InjectorCMode::BHP;
1063 prod_controls.addControl(Well::ProducerCMode::BHP);
1064 prod_controls.bhp_limit = bhp;
1065 prod_controls.cmode = Well::ProducerCMode::BHP;
1066 ws.production_cmode = Well::ProducerCMode::BHP;
1071 const bool converged = this->iterateWellEqWithSwitching(
1072 simulator, dt, inj_controls, prod_controls, groupStateHelper_copy,
1078 ws.injection_cmode = cmode_inj;
1079 ws.production_cmode = cmode_prod;
1083 template<
typename TypeTag>
1094 const auto well_status_orig = this->wellStatus_;
1097 auto inj_controls = Well::InjectionControls(0);
1098 auto prod_controls = Well::ProductionControls(0);
1103 const bool converged = this->iterateWellEqWithSwitching(
1104 simulator, dt, inj_controls, prod_controls,
1111 this->wellStatus_ = well_status_orig;
1115 template<
typename TypeTag>
1125 const double dt = simulator.timeStepSize();
1127 const auto& summary_state = simulator.vanguard().summaryState();
1128 auto inj_controls = this->well_ecl_.isInjector() ? this->well_ecl_.injectionControls(summary_state) : Well::InjectionControls(0);
1129 auto prod_controls = this->well_ecl_.isProducer() ? this->well_ecl_.productionControls(summary_state) : Well::ProductionControls(0);
1130 this->onlyKeepBHPandTHPcontrols(summary_state, well_state, inj_controls, prod_controls);
1132 bool converged =
false;
1135 if (!this->param_.local_well_solver_control_switching_){
1136 converged = this->iterateWellEqWithControl(
1137 simulator, dt, inj_controls, prod_controls, groupStateHelper, well_state
1140 if (this->param_.use_implicit_ipr_ && this->well_ecl_.isProducer() && (well_state.
well(this->index_of_well_).status == WellStatus::OPEN)) {
1141 converged = this->solveWellWithOperabilityCheck(
1142 simulator, dt, inj_controls, prod_controls, groupStateHelper, well_state
1145 converged = this->iterateWellEqWithSwitching(
1146 simulator, dt, inj_controls, prod_controls, groupStateHelper, well_state,
1154 }
catch (NumericalProblem& e ) {
1155 const std::string msg =
"Inner well iterations failed for well " + this->name() +
" Treat the well as unconverged. ";
1156 deferred_logger.warning(
"INNER_ITERATION_FAILED", msg);
1161 deferred_logger.debug(
"WellTest: Well equation for well " + this->name() +
" converged");
1164 const int max_iter = this->param_.max_welleq_iter_;
1165 deferred_logger.debug(
"WellTest: Well equation for well " + this->name() +
" failed converging in "
1171 template<
typename TypeTag>
1180 if (!this->isOperableAndSolvable() && !this->wellIsStopped())
1185 const double dt = simulator.timeStepSize();
1186 bool converged = iterateWellEquations(simulator, dt, groupStateHelper, well_state);
1196 auto& ws = well_state.
well(this->indexOfWell());
1197 bool thp_control =
false;
1198 if (this->well_ecl_.isInjector()) {
1199 thp_control = ws.injection_cmode == Well::InjectorCMode::THP;
1201 ws.injection_cmode = Well::InjectorCMode::BHP;
1202 if (this->well_control_log_.empty()) {
1203 this->well_control_log_.push_back(WellInjectorCMode2String(Well::InjectorCMode::THP));
1207 thp_control = ws.production_cmode == Well::ProducerCMode::THP;
1209 ws.production_cmode = Well::ProducerCMode::BHP;
1210 if (this->well_control_log_.empty()) {
1211 this->well_control_log_.push_back(WellProducerCMode2String(Well::ProducerCMode::THP));
1216 const std::string msg = std::string(
"The newly opened well ") + this->name()
1217 + std::string(
" with THP control did not converge during inner iterations, we try again with bhp control");
1218 deferred_logger.debug(msg);
1219 converged = this->iterateWellEquations(simulator, dt, groupStateHelper, well_state);
1224 const int max_iter = this->param_.max_welleq_iter_;
1225 deferred_logger.debug(
"Compute initial well solution for well " + this->name() +
". Failed to converge in "
1227 well_state = well_state0;
1233 template <
typename TypeTag>
1242 prepareWellBeforeAssembling(simulator, dt, groupStateHelper, well_state);
1243 assembleWellEqWithoutIteration(simulator, groupStateHelper, dt, well_state,
1249 template <
typename TypeTag>
1256 const bool solving_with_zero_rate)
1259 const auto& summary_state = simulator.vanguard().summaryState();
1260 const auto inj_controls = this->well_ecl_.isInjector() ? this->well_ecl_.injectionControls(summary_state) : Well::InjectionControls(0);
1261 const auto prod_controls = this->well_ecl_.isProducer()
1262 ? this->productionControlsWithWeldraw(summary_state, well_state.
well(this->index_of_well_))
1263 : Well::ProductionControls(0);
1266 assembleWellEqWithoutIteration(simulator, groupStateHelper, dt, inj_controls, prod_controls, well_state, solving_with_zero_rate);
1271 template<
typename TypeTag>
1278 std::vector<Scalar> scaled_well_fractions(FluidSystem::numPhases, 0.0);
1279 this->getScaledWellFractions(scaled_well_fractions, deferred_logger);
1281 this->Base::updateGroupTargetFallbackFlag(well_state, scaled_well_fractions, deferred_logger);
1286 template<
typename TypeTag>
1296 const bool old_well_operable = this->operability_status_.isOperableAndSolvable();
1298 if (this->param_.check_well_operability_iter_)
1299 checkWellOperability(simulator, well_state, groupStateHelper);
1302 const auto& iterCtx = simulator.problem().iterationContext();
1303 if (iterCtx.shouldRunInnerWellIterations(this->param_.max_niter_inner_well_iter_)) {
1304 const auto& ws = well_state.
well(this->indexOfWell());
1305 const bool nonzero_rate_original =
1306 std::any_of(ws.surface_rates.begin(),
1307 ws.surface_rates.begin() + well_state.
numPhases(),
1308 [](
Scalar rate) { return rate != Scalar(0.0); });
1310 this->operability_status_.solvable =
true;
1311 if (number_of_well_reopenings_ >= this->param_.max_well_status_switch_) {
1313 if (number_of_well_reopenings_ == this->param_.max_well_status_switch_) {
1314 const std::string msg = fmt::format(
"well {} is oscillating between open and stop. \n"
1315 "We don't allow for more than {} re-openings "
1316 "and the well is therefore kept stopped.",
1317 this->name(), number_of_well_reopenings_);
1318 deferred_logger.debug(msg);
1319 changed_to_stopped_this_step_ = old_well_operable;
1321 changed_to_stopped_this_step_ =
false;
1324 bool converged_zero_rate = this->solveWellWithZeroRate(
1325 simulator, dt, groupStateHelper, well_state
1327 if (this->param_.shut_unsolvable_wells_ && !converged_zero_rate ) {
1328 this->operability_status_.solvable =
false;
1330 this->operability_status_.can_obtain_bhp_with_thp_limit =
false;
1331 this->operability_status_.obey_thp_limit_under_bhp_limit =
false;
1334 number_of_well_reopenings_++;
1337 bool converged = this->iterateWellEquations(
1338 simulator, dt, groupStateHelper, well_state
1342 const bool zero_target = this->wellUnderZeroRateTarget(groupStateHelper);
1343 if (this->wellIsStopped() && !zero_target && nonzero_rate_original) {
1347 this->operability_status_.resetOperability();
1349 deferred_logger.debug(
" " + this->name() +
" is re-opened after being stopped during local solve");
1350 number_of_well_reopenings_++;
1354 if (this->param_.shut_unsolvable_wells_) {
1355 this->operability_status_.solvable =
false;
1359 if (this->operability_status_.has_negative_potentials) {
1360 auto well_state_copy = well_state;
1361 std::vector<Scalar> potentials;
1363 computeWellPotentials(simulator, well_state_copy, groupStateHelper, potentials);
1364 }
catch (
const std::exception& e) {
1365 const std::string msg = fmt::format(
"well {}: computeWellPotentials() failed "
1366 "during attempt to recompute potentials for well: {}",
1367 this->name(), e.what());
1368 deferred_logger.info(msg);
1369 this->operability_status_.has_negative_potentials =
true;
1371 auto& ws = well_state.
well(this->indexOfWell());
1373 for (
int p = 0; p < np; ++p) {
1374 ws.well_potentials[p] = std::max(
Scalar{0.0}, potentials[p]);
1377 this->changed_to_open_this_step_ =
false;
1378 changed_to_stopped_this_step_ =
false;
1380 const bool well_operable = this->operability_status_.isOperableAndSolvable();
1381 if (!well_operable) {
1382 this->stopWellAndSolveWithZeroRate(simulator, dt, groupStateHelper, well_state);
1383 if (old_well_operable) {
1384 const std::string ctx = iterCtx.inLocalSolve() ?
" (NLDD domain solve)" :
"";
1385 deferred_logger.debug(
" well " + this->name() +
" gets STOPPED during iteration" + ctx);
1386 changed_to_stopped_this_step_ =
true;
1388 }
else if (well_state.
isOpen(this->name())) {
1390 if (!old_well_operable) {
1391 const std::string ctx = iterCtx.inLocalSolve() ?
" (NLDD domain solve)" :
"";
1392 deferred_logger.debug(
" well " + this->name() +
" gets REVIVED during iteration" + ctx);
1393 this->changed_to_open_this_step_ =
true;
1398 template<
typename TypeTag>
1408 const auto ws_before_zero_rate_solve = well_state.
well(this->indexOfWell());
1409 bool solve_threw =
false;
1411 this->solveWellWithZeroRate(
1412 simulator, dt, groupStateHelper, well_state
1414 }
catch (
const std::exception& e) {
1416 const std::string msg = fmt::format(
"well {}: solveWellWithZeroRate() failed "
1417 "during attempt to solve with zero rate for well: {}",
1418 this->name(), e.what());
1424 const bool restored =
1425 well_state.
well(this->indexOfWell()).restoreIfDiverged(ws_before_zero_rate_solve, solve_threw);
1427 if (
anyRank(this->parallelWellInfo().communication(), restored)) {
1428 this->resetStoppedWell(simulator, dt, groupStateHelper, well_state);
1435 auto& ws = well_state.
well(this->indexOfWell());
1436 std::ranges::fill(ws.surface_rates,
Scalar{0.0});
1437 std::ranges::fill(ws.reservoir_rates,
Scalar{0.0});
1438 const auto num_well_rates = std::min(ws.surface_rates.size(), ws.segments.rates.size());
1439 std::fill_n(ws.segments.rates.begin(), num_well_rates,
Scalar{0.0});
1443 template<
typename TypeTag>
1452 auto& ws = well_state.
well(this->indexOfWell());
1453 std::ranges::fill(ws.surface_rates,
Scalar{0.0});
1454 std::ranges::fill(ws.segments.rates,
Scalar{0.0});
1457 std::ranges::fill(ws.reservoir_rates,
Scalar{0.0});
1460 this->updatePrimaryVariables(groupStateHelper);
1461 this->assembleWellEqWithoutIteration(simulator, groupStateHelper, dt,
1462 Well::InjectionControls(0), Well::ProductionControls(0),
1464 }
catch (
const NumericalProblem&) {
1473 template<
typename TypeTag>
1477 if(!this->operability_status_.solvable)
1480 for (
int perfIdx = 0; perfIdx < this->number_of_local_perforations_; ++perfIdx) {
1481 const auto cellIdx = this->cells()[perfIdx];
1482 const auto it = cellRates_.find(cellIdx);
1483 RateVector rates = (it == cellRates_.end()) ? 0.0 : it->second;
1484 for (
auto i=0*RateVector::dimension; i < RateVector::dimension; ++i)
1486 rates[i] += connectionRates_[perfIdx][i];
1488 cellRates_.insert_or_assign(cellIdx, rates);
1492 template<
typename TypeTag>
1496 for (
int perfIdx = 0; perfIdx < this->number_of_local_perforations_; ++perfIdx) {
1497 if (this->cells()[perfIdx] == cellIdx) {
1498 const unsigned activeCompIdx = FluidSystem::canonicalToActiveCompIdx(FluidSystem::solventComponentIndex(phaseIdx));
1499 return connectionRates_[perfIdx][activeCompIdx].value();
1503 OPM_THROW(std::invalid_argument,
"The well with name " + this->name()
1511 template<
typename TypeTag>
1520 if (!this->param_.check_well_operability_) {
1524 if (this->wellIsStopped() && !changed_to_stopped_this_step_) {
1528 updateWellOperability(simulator, well_state, groupStateHelper);
1529 if (!this->operability_status_.isOperableAndSolvable()) {
1530 this->operability_status_.use_vfpexplicit =
true;
1531 deferred_logger.debug(
"EXPLICIT_LOOKUP_VFP",
1532 "well not operable, trying with explicit vfp lookup: " + this->name());
1533 updateWellOperability(simulator, well_state, groupStateHelper);
1539 template<
typename TypeTag>
1549 const auto& summary_state = simulator.vanguard().summaryState();
1550 const auto& well_name = this->name();
1551 if (!this->wellHasTHPConstraints(summary_state)) {
1552 const std::string msg = fmt::format(
"GLIFT WTEST: Well {} does not have THP constraints", well_name);
1553 deferred_logger.
info(msg);
1556 const auto& schedule = simulator.vanguard().schedule();
1557 const auto report_step_idx = simulator.episodeIndex();
1558 const auto& glo = schedule.glo(report_step_idx);
1559 if (!glo.has_well(well_name)) {
1560 const std::string msg = fmt::format(
1561 "GLIFT WTEST: Well {} : Gas lift not activated: "
1562 "WLIFTOPT is probably missing. Skipping.", well_name);
1563 deferred_logger.
info(msg);
1566 const auto& gl_well = glo.well(well_name);
1569 std::unique_ptr<GasLiftSingleWell> glift =
1570 initializeGliftWellTest_<GasLiftSingleWell>(simulator,
1575 auto [wtest_alq, success] = glift->wellTestALQ();
1577 const auto& unit_system = schedule.getUnits();
1579 well_state.
well(well_name).alq_state.set(wtest_alq);
1581 "GLIFT WTEST: Well {} : Setting ALQ to optimized value = {}",
1582 well_name, unit_system.from_si(UnitSystem::measure::gas_surface_rate, wtest_alq));
1585 if (!gl_well.use_glo()) {
1587 "GLIFT WTEST: Well {} : Gas lift optimization deactivated. Setting ALQ to WLIFTOPT item 3 = {}",
1589 unit_system.from_si(UnitSystem::measure::gas_surface_rate, well_state.
well(well_name).alq_state.get()));
1594 "GLIFT WTEST: Well {} : Gas lift optimization failed, no ALQ set.",
1598 deferred_logger.
info(msg);
1601 template<
typename TypeTag>
1610 if (this->param_.local_well_solver_control_switching_) {
1611 const bool success = updateWellOperabilityFromWellEq(simulator, groupStateHelper);
1613 this->operability_status_.solvable =
false;
1614 deferred_logger.debug(
"Operability check using well equations did not converge for well "
1615 + this->name() +
". Mark the well as unsolvable." );
1619 this->operability_status_.resetOperability();
1621 bool thp_controlled = this->isInjector() ? well_state.
well(this->index_of_well_).injection_cmode == Well::InjectorCMode::THP:
1622 well_state.
well(this->index_of_well_).production_cmode == Well::ProducerCMode::THP;
1623 bool bhp_controlled = this->isInjector() ? well_state.
well(this->index_of_well_).injection_cmode == Well::InjectorCMode::BHP:
1624 well_state.
well(this->index_of_well_).production_cmode == Well::ProducerCMode::BHP;
1628 bool check_thp = thp_controlled || this->operability_status_.thp_limit_violated_but_not_switched;
1629 if (check_thp || bhp_controlled) {
1630 updateIPR(simulator, deferred_logger);
1631 checkOperabilityUnderBHPLimit(well_state, simulator, deferred_logger);
1635 checkOperabilityUnderTHPLimit(simulator, well_state, groupStateHelper);
1639 template<
typename TypeTag>
1647 assert(this->param_.local_well_solver_control_switching_);
1648 this->operability_status_.resetOperability();
1651 const double dt = simulator.timeStepSize();
1655 auto guard = groupStateHelper_copy.
pushWellState(well_state_copy);
1657 bool converged = iterateWellEquations(simulator, dt, groupStateHelper_copy, well_state_copy);
1661 template<
typename TypeTag>
1669 template<
typename TypeTag>
1679 const auto& well = this->well_ecl_;
1680 const int well_index = this->index_of_well_;
1681 auto& ws = well_state.
well(well_index);
1683 const auto& summaryState = simulator.vanguard().summaryState();
1684 const auto& schedule = simulator.vanguard().schedule();
1688 ws.primaryvar.resize(0);
1690 if (this->wellIsStopped()) {
1691 for (
int p = 0; p<np; ++p) {
1692 ws.surface_rates[p] = 0;
1698 if (this->isInjector() )
1700 const auto& controls = well.injectionControls(summaryState);
1702 InjectorType injectorType = controls.injector_type;
1704 switch (injectorType) {
1705 case InjectorType::WATER:
1707 phasePos = FluidSystem::canonicalToActivePhaseIdx(FluidSystem::waterPhaseIdx);
1710 case InjectorType::OIL:
1712 phasePos = FluidSystem::canonicalToActivePhaseIdx(FluidSystem::oilPhaseIdx);
1715 case InjectorType::GAS:
1717 phasePos = FluidSystem::canonicalToActivePhaseIdx(FluidSystem::gasPhaseIdx);
1721 OPM_DEFLOG_THROW(std::runtime_error,
"Expected WATER, OIL or GAS as type for injectors " + this->name(), deferred_logger );
1724 const auto current = ws.injection_cmode;
1727 case Well::InjectorCMode::RATE:
1729 ws.surface_rates[phasePos] = (1.0 - this->rsRvInj()) * controls.surface_rate;
1730 if(this->rsRvInj() > 0) {
1731 if (injectorType == InjectorType::OIL && FluidSystem::phaseIsActive(FluidSystem::gasPhaseIdx)) {
1732 const int gas_pos = FluidSystem::canonicalToActivePhaseIdx(FluidSystem::gasPhaseIdx);
1733 ws.surface_rates[gas_pos] = controls.surface_rate * this->rsRvInj();
1734 }
else if (injectorType == InjectorType::GAS && FluidSystem::phaseIsActive(FluidSystem::oilPhaseIdx)) {
1735 const int oil_pos = FluidSystem::canonicalToActivePhaseIdx(FluidSystem::oilPhaseIdx);
1736 ws.surface_rates[oil_pos] = controls.surface_rate * this->rsRvInj();
1738 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 );
1744 case Well::InjectorCMode::RESV:
1746 std::vector<Scalar> convert_coeff(this->number_of_phases_, 1.0);
1747 this->rateConverter_.calcCoeff( 0, this->pvtRegionIdx_, convert_coeff);
1748 const Scalar coeff = convert_coeff[phasePos];
1749 ws.surface_rates[phasePos] = controls.reservoir_rate/coeff;
1753 case Well::InjectorCMode::THP:
1755 auto rates = ws.surface_rates;
1760 this->getRefDensity(),
1763 ws.thp = this->getTHPConstraint(summaryState);
1768 Scalar total_rate = std::accumulate(rates.begin(), rates.end(), 0.0);
1769 if (total_rate <= 0.0)
1770 ws.surface_rates = ws.well_potentials;
1774 case Well::InjectorCMode::BHP:
1776 ws.bhp = controls.bhp_limit;
1778 for (
int p = 0; p<np; ++p) {
1779 total_rate += ws.surface_rates[p];
1784 if (total_rate <= 0.0)
1785 ws.surface_rates = ws.well_potentials;
1789 case Well::InjectorCMode::GRUP:
1791 assert(well.isAvailableForGroupControl());
1792 const auto& group = schedule.getGroup(well.groupName(), this->currentStep());
1793 const Scalar efficiencyFactor = well.getEfficiencyFactor() *
1794 well_state[well.name()].efficiency_scaling_factor;
1795 std::optional<Scalar> target =
1796 this->getGroupInjectionTargetRate(group,
1801 ws.surface_rates[phasePos] = *target;
1804 case Well::InjectorCMode::CMODE_UNDEFINED:
1806 OPM_DEFLOG_THROW(std::runtime_error,
"Well control must be specified for well " + this->name(), deferred_logger );
1816 ws.surface_rates[phasePos] = std::max(
Scalar{1.e-7}, ws.surface_rates[phasePos]);
1819 ws.bhp = controls.bhp_limit;
1825 const auto current = ws.production_cmode;
1826 const auto controls = this->productionControlsWithWeldraw(summaryState, ws);
1828 case Well::ProducerCMode::ORAT:
1830 const int oil_pos = FluidSystem::canonicalToActivePhaseIdx(FluidSystem::oilPhaseIdx);
1831 Scalar current_rate = -ws.surface_rates[oil_pos];
1834 if (current_rate > 0.0) {
1835 for (
int p = 0; p<np; ++p) {
1836 ws.surface_rates[p] *= controls.oil_rate/current_rate;
1839 const std::vector<Scalar> fractions = initialWellRateFractions(simulator, well_state);
1840 double control_fraction = fractions[oil_pos];
1841 if (control_fraction != 0.0) {
1842 for (
int p = 0; p<np; ++p) {
1843 ws.surface_rates[p] = - fractions[p] * controls.oil_rate/control_fraction;
1849 case Well::ProducerCMode::WRAT:
1851 const int water_pos = FluidSystem::canonicalToActivePhaseIdx(FluidSystem::waterPhaseIdx);
1852 Scalar current_rate = -ws.surface_rates[water_pos];
1855 if (current_rate > 0.0) {
1856 for (
int p = 0; p<np; ++p) {
1857 ws.surface_rates[p] *= controls.water_rate/current_rate;
1860 const std::vector<Scalar> fractions = initialWellRateFractions(simulator, well_state);
1861 const Scalar control_fraction = fractions[water_pos];
1862 if (control_fraction != 0.0) {
1863 for (
int p = 0; p<np; ++p) {
1864 ws.surface_rates[p] = - fractions[p] * controls.water_rate / control_fraction;
1870 case Well::ProducerCMode::GRAT:
1872 const int gas_pos = FluidSystem::canonicalToActivePhaseIdx(FluidSystem::gasPhaseIdx);
1873 Scalar current_rate = -ws.surface_rates[gas_pos];
1876 if (current_rate > 0.0) {
1877 for (
int p = 0; p<np; ++p) {
1878 ws.surface_rates[p] *= controls.gas_rate/current_rate;
1881 const std::vector<Scalar > fractions = initialWellRateFractions(simulator, well_state);
1882 const Scalar control_fraction = fractions[gas_pos];
1883 if (control_fraction != 0.0) {
1884 for (
int p = 0; p<np; ++p) {
1885 ws.surface_rates[p] = - fractions[p] * controls.gas_rate / control_fraction;
1893 case Well::ProducerCMode::LRAT:
1895 const int water_pos = FluidSystem::canonicalToActivePhaseIdx(FluidSystem::waterPhaseIdx);
1896 const int oil_pos = FluidSystem::canonicalToActivePhaseIdx(FluidSystem::oilPhaseIdx);
1897 Scalar current_rate = - ws.surface_rates[water_pos]
1898 - ws.surface_rates[oil_pos];
1901 if (current_rate > 0.0) {
1902 for (
int p = 0; p<np; ++p) {
1903 ws.surface_rates[p] *= controls.liquid_rate/current_rate;
1906 const std::vector<Scalar> fractions = initialWellRateFractions(simulator, well_state);
1907 const Scalar control_fraction = fractions[water_pos] + fractions[oil_pos];
1908 if (control_fraction != 0.0) {
1909 for (
int p = 0; p<np; ++p) {
1910 ws.surface_rates[p] = - fractions[p] * controls.liquid_rate / control_fraction;
1916 case Well::ProducerCMode::CRAT:
1919 fmt::format(
"CRAT control not supported, well {}", this->name()),
1922 case Well::ProducerCMode::RESV:
1924 std::vector<Scalar> convert_coeff(this->number_of_phases_, 1.0);
1925 this->rateConverter_.calcCoeff( 0, this->pvtRegionIdx_, ws.surface_rates, convert_coeff);
1926 Scalar total_res_rate = 0.0;
1927 for (
int p = 0; p<np; ++p) {
1928 total_res_rate -= ws.surface_rates[p] * convert_coeff[p];
1930 if (controls.prediction_mode) {
1933 if (total_res_rate > 0.0) {
1934 for (
int p = 0; p<np; ++p) {
1935 ws.surface_rates[p] *= controls.resv_rate/total_res_rate;
1938 const std::vector<Scalar> fractions = initialWellRateFractions(simulator, well_state);
1939 for (
int p = 0; p<np; ++p) {
1940 ws.surface_rates[p] = - fractions[p] * controls.resv_rate / convert_coeff[p];
1944 std::vector<Scalar> hrates(this->number_of_phases_,0.);
1945 if (FluidSystem::phaseIsActive(FluidSystem::waterPhaseIdx)) {
1946 const int phase_pos = FluidSystem::canonicalToActivePhaseIdx(FluidSystem::waterPhaseIdx);
1947 hrates[phase_pos] = controls.water_rate;
1949 if (FluidSystem::phaseIsActive(FluidSystem::oilPhaseIdx)) {
1950 const int phase_pos = FluidSystem::canonicalToActivePhaseIdx(FluidSystem::oilPhaseIdx);
1951 hrates[phase_pos] = controls.oil_rate;
1953 if (FluidSystem::phaseIsActive(FluidSystem::gasPhaseIdx)) {
1954 const int phase_pos = FluidSystem::canonicalToActivePhaseIdx(FluidSystem::gasPhaseIdx);
1955 hrates[phase_pos] = controls.gas_rate;
1957 std::vector<Scalar> hrates_resv(this->number_of_phases_,0.);
1958 this->rateConverter_.calcReservoirVoidageRates( 0, this->pvtRegionIdx_, hrates, hrates_resv);
1959 Scalar target = std::accumulate(hrates_resv.begin(), hrates_resv.end(), 0.0);
1962 if (total_res_rate > 0.0) {
1963 for (
int p = 0; p<np; ++p) {
1964 ws.surface_rates[p] *= target/total_res_rate;
1967 const std::vector<Scalar> fractions = initialWellRateFractions(simulator, well_state);
1968 for (
int p = 0; p<np; ++p) {
1969 ws.surface_rates[p] = - fractions[p] * target / convert_coeff[p];
1975 case Well::ProducerCMode::BHP:
1977 ws.bhp = controls.bhp_limit;
1979 for (
int p = 0; p<np; ++p) {
1980 total_rate -= ws.surface_rates[p];
1985 if (total_rate <= 0.0){
1986 for (
int p = 0; p<np; ++p) {
1987 ws.surface_rates[p] = -ws.well_potentials[p];
1992 case Well::ProducerCMode::THP:
1994 const bool update_success = updateWellStateWithTHPTargetProd(simulator, well_state, groupStateHelper);
1996 if (!update_success) {
2000 auto rates = ws.surface_rates;
2001 this->adaptRatesForVFP(rates);
2003 well_state, rates, well, summaryState, this->getRefDensity(), deferred_logger);
2005 ws.thp = this->getTHPConstraint(summaryState);
2009 const Scalar total_rate = -std::accumulate(rates.begin(), rates.end(), 0.0);
2010 if (total_rate <= 0.0) {
2011 for (
int p = 0; p < this->number_of_phases_; ++p) {
2012 ws.surface_rates[p] = -ws.well_potentials[p];
2018 case Well::ProducerCMode::GRUP:
2020 assert(well.isAvailableForGroupControl());
2021 this->updateGroupTargetFallbackFlag(well_state, deferred_logger);
2022 const auto& group = schedule.getGroup(well.groupName(), this->currentStep());
2023 const Scalar efficiencyFactor = well.getEfficiencyFactor() *
2024 well_state[well.name()].efficiency_scaling_factor;
2025 Scalar scale = this->getGroupProductionTargetRate(group,
2031 for (
int p = 0; p<np; ++p) {
2032 ws.surface_rates[p] *= scale;
2037 case Well::ProducerCMode::CMODE_UNDEFINED:
2040 OPM_DEFLOG_THROW(std::runtime_error,
"Well control must be specified for well " + this->name() , deferred_logger);
2046 ws.bhp = controls.bhp_limit;
2051 template<
typename TypeTag>
2057 const auto& well_state = groupStateHelper.
wellState();
2059 const bool isGroupControlled = this->wellUnderGroupControl(well_state.well(this->index_of_well_));
2060 if (!isGroupControlled) {
2062 const auto& summaryState = groupStateHelper.
summaryState();
2063 return this->wellUnderZeroRateTargetIndividual(summaryState, well_state);
2065 return this->wellUnderZeroGroupRateTarget(groupStateHelper, isGroupControlled);
2069 template <
typename TypeTag>
2072 const std::optional<bool> group_control)
const
2074 const auto& well_state = groupStateHelper.
wellState();
2076 const bool isGroupControlled = group_control.value_or(this->wellUnderGroupControl(well_state.well(this->index_of_well_)));
2077 if (isGroupControlled) {
2078 return this->zeroGroupRateTarget(groupStateHelper);
2083 template<
typename TypeTag>
2090 return this->wellIsStopped()
2091 || this->wellUnderZeroRateTarget(groupStateHelper);
2094 template<
typename TypeTag>
2095 std::vector<typename WellInterface<TypeTag>::Scalar>
2101 const int np = this->number_of_phases_;
2102 std::vector<Scalar> scaling_factor(np);
2103 const auto& ws = well_state.
well(this->index_of_well_);
2105 Scalar total_potentials = 0.0;
2106 for (
int p = 0; p<np; ++p) {
2107 total_potentials += ws.well_potentials[p];
2109 if (total_potentials > 0) {
2110 for (
int p = 0; p<np; ++p) {
2111 scaling_factor[p] = ws.well_potentials[p] / total_potentials;
2113 return scaling_factor;
2118 const int nperf = this->number_of_local_perforations_;
2119 for (
int perf = 0; perf < nperf; ++perf) {
2120 total_tw += this->well_index_[perf];
2122 total_tw = this->parallelWellInfo().communication().sum(total_tw);
2124 for (
int perf = 0; perf < nperf; ++perf) {
2125 const int cell_idx = this->well_cells_[perf];
2126 const auto& intQuants = simulator.model().intensiveQuantities(cell_idx, 0);
2127 const auto& fs = intQuants.fluidState();
2128 const Scalar well_tw_fraction = this->well_index_[perf] / total_tw;
2129 Scalar total_mobility = 0.0;
2130 for (
int p = 0; p < np; ++p) {
2131 const int canonical_phase_idx = FluidSystem::activeToCanonicalPhaseIdx(p);
2132 total_mobility += fs.invB(canonical_phase_idx).value() * intQuants.mobility(canonical_phase_idx).value();
2134 for (
int p = 0; p < np; ++p) {
2135 const int canonical_phase_idx = FluidSystem::activeToCanonicalPhaseIdx(p);
2136 scaling_factor[p] += well_tw_fraction * fs.invB(canonical_phase_idx).value() * intQuants.mobility(canonical_phase_idx).value() / total_mobility;
2139 return scaling_factor;
2144 template <
typename TypeTag>
2151 assert(this->isProducer());
2155 auto& ws = well_state.
well(this->index_of_well_);
2156 int nonzero_rate_index = -1;
2157 const Scalar floating_point_error_epsilon = 1e-14;
2158 for (
int p = 0; p < this->number_of_phases_; ++p) {
2159 if (std::abs(ws.surface_rates[p]) > floating_point_error_epsilon) {
2160 if (nonzero_rate_index == -1) {
2161 nonzero_rate_index = p;
2170 std::vector<Scalar> well_q_s(this->number_of_phases_, 0.0);
2171 bool rates_evaluated_at_1bar =
false;
2173 const auto& summary_state = simulator.vanguard().summaryState();
2174 const auto& prod_controls = this->well_ecl_.productionControls(summary_state);
2175 const double bhp_limit = std::max(prod_controls.bhp_limit, 1.0 * unit::barsa);
2176 this->computeWellRatesWithBhp(simulator, bhp_limit, well_q_s, deferred_logger);
2178 rates_evaluated_at_1bar = (bhp_limit < 1.1 * unit::barsa);
2180 if (std::ranges::any_of(well_q_s, [](
Scalar q) {
return q > 0.0; })) {
2182 if (!rates_evaluated_at_1bar) {
2183 this->computeWellRatesWithBhp(simulator, 1.0 * unit::barsa, well_q_s, deferred_logger);
2184 rates_evaluated_at_1bar =
true;
2187 for (
auto& q : well_q_s) {
2188 q = std::min(q,
Scalar{0.0});
2193 if (nonzero_rate_index == -1) {
2197 const Scalar factor = rates_evaluated_at_1bar ? 0.5 : 1.0;
2198 for (
int p = 0; p < this->number_of_phases_; ++p) {
2199 ws.surface_rates[p] = factor * well_q_s[p];
2208 const Scalar initial_nonzero_rate = ws.surface_rates[nonzero_rate_index];
2209 const Scalar computed_rate = well_q_s[nonzero_rate_index];
2210 if (std::abs(initial_nonzero_rate) < std::abs(computed_rate)) {
2212 const Scalar factor = initial_nonzero_rate / computed_rate;
2213 assert(factor < 1.0);
2214 for (
int p = 0; p < this->number_of_phases_; ++p) {
2216 if (p != nonzero_rate_index) {
2217 ws.surface_rates[p] = factor * well_q_s[p];
2226 for (
int p = 0; p < this->number_of_phases_; ++p) {
2227 ws.surface_rates[p] = well_q_s[p];
2231 template <
typename TypeTag>
2232 template<
class Value>
2235 getTw(std::vector<Value>& Tw,
2238 const Value& trans_mult,
2241 OPM_TIMEFUNCTION_LOCAL(Subsystem::Wells);
2244 if (
static_cast<std::size_t
>(perf) >= this->well_cells_.size()) {
2245 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!");
2251 if (!this->well_index_fracture_.empty()) {
2252 const auto frac_wi = this->well_index_fracture_[perf]
2253 .wellIndex(ws.
perf_data.pressure[perf]);
2254 if (frac_wi > 0.0) {
2255 for (
auto& tw : Tw) {
2261 if constexpr (! Indices::gasEnabled) {
2265 const auto& wdfac = this->well_ecl_.getWDFAC();
2267 if (! wdfac.useDFactor() || (this->well_index_[perf] == 0.0)) {
2271 const Scalar d = this->computeConnectionDFactor(perf, intQuants, ws);
2278 const auto& connection = this->well_ecl_.getConnections()[ws.
perf_data.ecl_index[perf]];
2279 const Scalar Kh = connection.Kh();
2280 const Scalar scaling = std::numbers::pi * Kh * connection.wpimult();
2281 const unsigned gas_comp_idx = FluidSystem::canonicalToActiveCompIdx(FluidSystem::gasCompIdx);
2284 const Scalar cell_pressure = getValue(intQuants.fluidState().pressure(FluidSystem::gasPhaseIdx));
2285 const Scalar drawdown = cell_pressure - connection_pressure;
2286 const Scalar invB = getValue(intQuants.fluidState().invB(FluidSystem::gasPhaseIdx));
2287 const Scalar mob_g = getValue(intQuants.mobility(FluidSystem::gasPhaseIdx)) * invB;
2289 const Scalar b = 2 * scaling / getValue(Tw[gas_comp_idx]);
2290 const Scalar c = -2 * scaling * mob_g * drawdown;
2292 Scalar consistent_Q = -1.0e20;
2294 const Scalar r2n = b*b + 4*a*c;
2296 const Scalar rn = std::sqrt(r2n);
2297 const Scalar xn1 = (b-rn)*0.5/a;
2301 const Scalar xn2 = (b+rn)*0.5/a;
2302 if (xn2 <= 0 && xn2 > consistent_Q) {
2308 const Scalar r2p = b*b - 4*a*c;
2310 const Scalar rp = std::sqrt(r2p);
2311 const Scalar xp1 = (rp-b)*0.5/a;
2312 if (xp1 > 0 && xp1 < consistent_Q) {
2315 const Scalar xp2 = -(rp+b)*0.5/a;
2316 if (xp2 > 0 && xp2 < consistent_Q) {
2320 Tw[gas_comp_idx] = 1.0 / (1.0 / (trans_mult * this->well_index_[perf]) + (consistent_Q/2 * d / scaling));
2323 template <
typename TypeTag>
2329 if (! this->well_ecl_.getWDFAC().useDFactor()) {
2333 auto& d_factor = ws.
perf_data.connection_d_factor;
2335 for (
int perf = 0; perf < this->number_of_local_perforations_; ++perf) {
2336 const int cell_idx = this->well_cells_[perf];
2337 const auto& intQuants = simulator.model().intensiveQuantities(cell_idx, 0);
2339 d_factor[perf] = this->computeConnectionDFactor(perf, intQuants, ws);
2343 template <
typename TypeTag>
2350 auto rhoGS = [regIdx = this->pvtRegionIdx()]() {
2351 return FluidSystem::referenceDensity(FluidSystem::gasPhaseIdx, regIdx);
2355 auto gas_visc = [connection_pressure = ws.
perf_data.pressure[perf],
2357 regIdx = this->pvtRegionIdx(), &intQuants]()
2359 const auto rv = getValue(intQuants.fluidState().Rv());
2361 const auto& gasPvt = FluidSystem::gasPvt();
2366 const Scalar rv_sat = gasPvt.saturatedOilVaporizationFactor
2367 (regIdx, temperature, connection_pressure);
2369 if (! (rv < rv_sat)) {
2370 return gasPvt.saturatedViscosity(regIdx, temperature,
2371 connection_pressure);
2374 return gasPvt.viscosity(regIdx, temperature, connection_pressure,
2375 rv, getValue(intQuants.fluidState().Rvw()));
2378 const auto& connection = this->well_ecl_.getConnections()
2381 return this->well_ecl_.getWDFAC().getDFactor(rhoGS, gas_visc, connection);
2385 template <
typename TypeTag>
2391 auto connCF = [&connIx = std::as_const(ws.
perf_data.ecl_index),
2392 &conns = this->well_ecl_.getConnections()]
2395 return conns[connIx[perf]].CF();
2398 auto obtain = [](
const Eval& value)
2400 return getValue(value);
2403 auto& tmult = ws.
perf_data.connection_compaction_tmult;
2404 auto& ctf = ws.
perf_data.connection_transmissibility_factor;
2406 for (
int perf = 0; perf < this->number_of_local_perforations_; ++perf) {
2407 const int cell_idx = this->well_cells_[perf];
2409 getTransMult(trans_mult, simulator, cell_idx, obtain);
2410 tmult[perf] = trans_mult;
2412 ctf[perf] = connCF(perf) * tmult[perf];
2417 template<
typename TypeTag>
2421 if constexpr (Indices::oilEnabled) {
2422 return fs.pressure(FluidSystem::oilPhaseIdx);
2423 }
else if constexpr (Indices::gasEnabled) {
2424 return fs.pressure(FluidSystem::gasPhaseIdx);
2426 return fs.pressure(FluidSystem::waterPhaseIdx);
2430 template <
typename TypeTag>
2431 template<
class Value,
class Callback>
2437 Callback& extendEval)
const
2439 const auto& intQuants = simulator.model().intensiveQuantities(cell_idx, 0);
2440 trans_mult = simulator.problem().template wellTransMultiplier<Value>(intQuants, cell_idx, extendEval);
2443 template <
typename TypeTag>
2444 template<
class Value,
class Callback>
2448 const int local_perf_index,
2449 std::vector<Value>& mob,
2450 Callback& extendEval,
2453 auto relpermArray = []()
2455 if constexpr (std::is_same_v<Value, Scalar>) {
2456 return std::array<Scalar,3>{};
2458 return std::array<Eval,3>{};
2461 if (
static_cast<std::size_t
>(local_perf_index) >= this->well_cells_.size()) {
2462 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!");
2464 const int cell_idx = this->well_cells_[local_perf_index];
2465 assert (
int(mob.size()) == this->num_conservation_quantities_);
2466 const auto& intQuants = simulator.model().intensiveQuantities(cell_idx, 0);
2467 const auto& materialLawManager = simulator.problem().materialLawManager();
2471 const int satid = this->saturation_table_number_[local_perf_index] - 1;
2472 const int satid_elem = materialLawManager.satnumRegionIdx(cell_idx);
2473 if (satid == satid_elem) {
2474 for (
unsigned phaseIdx = 0; phaseIdx < FluidSystem::numPhases; ++phaseIdx) {
2475 if (!FluidSystem::phaseIsActive(phaseIdx)) {
2479 const unsigned activeCompIdx = FluidSystem::canonicalToActiveCompIdx(FluidSystem::solventComponentIndex(phaseIdx));
2480 mob[activeCompIdx] = extendEval(intQuants.mobility(phaseIdx));
2482 if constexpr (has_solvent) {
2483 mob[Indices::contiSolventEqIdx] = extendEval(intQuants.solventMobility());
2486 const auto& paramsCell = materialLawManager.connectionMaterialLawParams(satid, cell_idx);
2487 auto relativePerms = relpermArray();
2488 MaterialLaw::relativePermeabilities(relativePerms, paramsCell, intQuants.fluidState());
2491 materialLawManager.connectionMaterialLawParams(satid_elem, cell_idx);
2494 for (
unsigned phaseIdx = 0; phaseIdx < FluidSystem::numPhases; ++phaseIdx) {
2495 if (!FluidSystem::phaseIsActive(phaseIdx)) {
2499 const unsigned activeCompIdx = FluidSystem::canonicalToActiveCompIdx(FluidSystem::solventComponentIndex(phaseIdx));
2500 mob[activeCompIdx] = extendEval(relativePerms[phaseIdx] / intQuants.fluidState().viscosity(phaseIdx));
2503 if constexpr (has_solvent) {
2504 const auto Fsolgas = intQuants.solventSaturation() / (intQuants.solventSaturation() + intQuants.fluidState().saturation(FluidSystem::gasPhaseIdx));
2506 if (Fsolgas > SolventModule::cutOff) {
2507 const unsigned activeGasCompIdx = FluidSystem::canonicalToActiveCompIdx(FluidSystem::solventComponentIndex(FluidSystem::gasPhaseIdx));
2508 const auto& ssfnKrg = SolventModule::ssfnKrg(satid);
2509 const auto& ssfnKrs = SolventModule::ssfnKrs(satid);
2510 mob[activeGasCompIdx] *= extendEval(ssfnKrg.eval(1-Fsolgas,
true));
2511 mob[Indices::contiSolventEqIdx] = extendEval(ssfnKrs.eval(Fsolgas,
true) * relativePerms[activeGasCompIdx] / intQuants.solventViscosity());
2516 if (this->isInjector() && !this->inj_fc_multiplier_.empty()) {
2517 const auto perf_ecl_index = this->perforationData()[local_perf_index].ecl_index;
2518 const auto& connections = this->well_ecl_.getConnections();
2519 const auto& connection = connections[perf_ecl_index];
2520 if (connection.filterCakeActive()) {
2521 std::ranges::transform(mob, mob.begin(),
2522 [mult = this->inj_fc_multiplier_[local_perf_index]]
2524 { return val * mult; });
2530 template<
typename TypeTag>
2539 const auto& summary_state = simulator.vanguard().summaryState();
2541 auto bhp_at_thp_limit = computeBhpAtThpLimitProdWithAlq(
2542 simulator, groupStateHelper, summary_state, this->getALQ(well_state),
false);
2543 if (bhp_at_thp_limit) {
2544 std::vector<Scalar> rates(this->number_of_phases_, 0.0);
2545 if (thp_update_iterations) {
2546 computeWellRatesWithBhpIterations(simulator, *bhp_at_thp_limit,
2547 groupStateHelper, rates);
2549 computeWellRatesWithBhp(simulator, *bhp_at_thp_limit,
2550 rates, deferred_logger);
2552 auto& ws = well_state.
well(this->name());
2553 ws.surface_rates = rates;
2554 ws.bhp = *bhp_at_thp_limit;
2555 ws.thp = this->getTHPConstraint(summary_state);
2562 template<
typename TypeTag>
2563 std::optional<typename WellInterface<TypeTag>::Scalar>
2568 const SummaryState& summary_state,
2573 const auto& groupStateHelper = simulator.problem().wellModel().groupStateHelper();
2575 auto well_guard = groupStateHelper_copy.
pushWellState(well_state_copy);
2576 const double dt = simulator.timeStepSize();
2577 const bool converged = this->solveWellWithBhp(
2578 simulator, dt, bhp, groupStateHelper_copy, well_state_copy
2582 auto rates = well_state_copy.
well(this->index_of_well_).surface_rates;
2584 for (std::size_t p = 0; p < rates.size(); ++p) {
2585 zero_rates &= rates[p] == 0.0;
2589 if (zero_rates || !converged) {
2590 return this->computeBhpAtThpLimitProdWithAlq(simulator, groupStateHelper_copy, summary_state, alq_value,
false);
2592 this->updateIPRImplicit(simulator, groupStateHelper_copy, well_state_copy);
2593 this->adaptRatesForVFP(rates);
2597 template <
typename TypeTag>
2602 const std::vector<Scalar>& mobility,
2605 const int np = this->number_of_phases_;
2606 for (
int p = 0; p < np; ++p) {
2609 const int canonical_phase_idx = FluidSystem::activeToCanonicalPhaseIdx(p);
2610 const auto connMob =
2611 mobility[FluidSystem::activePhaseToActiveCompIdx(p)] * fs.invB(canonical_phase_idx).value();
2613 connPI[p] = connPICalc(connMob);
2616 if (FluidSystem::phaseIsActive(FluidSystem::oilPhaseIdx) &&
2617 FluidSystem::phaseIsActive(FluidSystem::gasPhaseIdx))
2619 const auto io = FluidSystem::canonicalToActivePhaseIdx(FluidSystem::oilPhaseIdx);
2620 const auto ig = FluidSystem::canonicalToActivePhaseIdx(FluidSystem::gasPhaseIdx);
2622 const auto vapoil = connPI[ig] * fs.Rv().value();
2623 const auto disgas = connPI[io] * fs.Rs().value();
2625 connPI[io] += vapoil;
2626 connPI[ig] += disgas;
2631 template <
typename TypeTag>
2635 const Phase preferred_phase,
2637 const std::vector<Scalar>& mobility,
2642 if (preferred_phase == Phase::GAS) {
2643 phase_pos = FluidSystem::canonicalToActivePhaseIdx(FluidSystem::gasPhaseIdx);
2645 else if (preferred_phase == Phase::OIL) {
2646 phase_pos = FluidSystem::canonicalToActivePhaseIdx(FluidSystem::oilPhaseIdx);
2648 else if (preferred_phase == Phase::WATER) {
2649 phase_pos = FluidSystem::canonicalToActivePhaseIdx(FluidSystem::waterPhaseIdx);
2653 fmt::format(
"Unsupported Injector Type ({}) "
2654 "for well {} during connection I.I. calculation",
2655 static_cast<int>(preferred_phase), this->name()),
2659 const auto mt = std::accumulate(mobility.begin(), mobility.end(), 0.0);
2660 const int canonicalPhaseIdx = FluidSystem::activeToCanonicalPhaseIdx(phase_pos);
2661 connII[phase_pos] = connIICalc(mt * fs.invB(canonicalPhaseIdx).value());
2664 template<
typename TypeTag>
2665 template<
class GasLiftSingleWell>
2666 std::unique_ptr<GasLiftSingleWell>
2675 auto& comm = simulator.vanguard().grid().comm();
2676 ecl_well_map.try_emplace(this->name(), &(this->wellEcl()), this->indexOfWell());
2677 const auto& iterCtx = simulator.problem().iterationContext();
2680 simulator.vanguard().schedule(),
2681 simulator.vanguard().summaryState(),
2682 simulator.episodeIndex(),
2689 simulator.problem().wellModel().groupStateHelper()
2693 std::set<int> sync_groups;
2694 const auto& summary_state = simulator.vanguard().summaryState();
2695 return std::make_unique<GasLiftSingleWell>(*
this,
2709 template <
typename TypeTag>
2716 if (this->well_cells_.size() > 0) {
2720 const int cell_idx = this->well_cells_[0];
2721 const auto& intQuants = simulator.model().intensiveQuantities(cell_idx, 0);
2722 const auto& fs = intQuants.fluidState();
2724 info.
temperature = getValue(fs.temperature(FluidSystem::oilPhaseIdx));
2725 info.saltConcentration = getValue(fs.saltConcentration());
2731 return this->parallel_well_info_.communication().size() == 1
2733 : this->parallel_well_info_.broadcastFirstPerforationValue(info);
#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)
void warning(const std::string &tag, const std::string &message)
Definition: GasLiftGroupInfo.hpp:49
Definition: GroupStateHelper.hpp:57
GroupState< Scalar > & groupState() const
Definition: GroupStateHelper.hpp:345
const SummaryState & summaryState() const
Definition: GroupStateHelper.hpp:490
const WellState< Scalar, IndexTraits > & wellState() const
Definition: GroupStateHelper.hpp:589
DeferredLogger & deferredLogger() const
Get the deferred logger.
Definition: GroupStateHelper.hpp:258
WellStateGuard pushWellState(WellState< Scalar, IndexTraits > &well_state)
Definition: GroupStateHelper.hpp:429
GroupStateGuard pushGroupState(GroupState< Scalar > &group_state)
Definition: GroupStateHelper.hpp:406
Definition: GroupState.hpp:42
Class encapsulating some information about parallel wells.
Definition: ParallelWellInfo.hpp:217
Definition: SingleWellState.hpp:44
Scalar temperature
Definition: SingleWellState.hpp:129
PerfData< Scalar > perf_data
Definition: SingleWellState.hpp:185
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
Well well_ecl_
Definition: WellInterfaceGeneric.hpp:486
int number_of_local_perforations_
Definition: WellInterfaceGeneric.hpp:528
FluidSystem::Scalar wsolvent_
Definition: WellInterfaceGeneric.hpp:568
Definition: WellInterfaceIndices.hpp:34
bool stoppedOrZeroRateTarget(const GroupStateHelperType &groupStateHelper) const
Definition: WellInterface_impl.hpp:2086
bool updateWellOperabilityFromWellEq(const Simulator &simulator, const GroupStateHelperType &groupStateHelper)
Definition: WellInterface_impl.hpp:1642
void checkWellOperability(const Simulator &simulator, const WellStateType &well_state, const GroupStateHelperType &groupStateHelper)
Definition: WellInterface_impl.hpp:1514
void updateWellOperability(const Simulator &simulator, const WellStateType &well_state, const GroupStateHelperType &groupStateHelper)
Definition: WellInterface_impl.hpp:1604
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:879
Scalar woxygen() const
Definition: WellInterface_impl.hpp:170
IndividualOrGroup
Definition: WellInterface.hpp:258
GetPropType< TypeTag, Properties::Simulator > Simulator
Definition: WellInterface.hpp:84
void assembleWellEqWithoutIteration(const Simulator &simulator, const GroupStateHelperType &groupStateHelper, const double dt, WellStateType &well_state, const bool solving_with_zero_rate)
Definition: WellInterface_impl.hpp:1252
void resetStoppedWell(const Simulator &simulator, const double dt, const GroupStateHelperType &groupStateHelper, WellStateType &well_state)
Make a stopped well consistent after the solve with zero rate failed.
Definition: WellInterface_impl.hpp:1446
Scalar computeConnectionDFactor(const int perf, const IntensiveQuantities &intQuants, const SingleWellStateType &ws) const
Definition: WellInterface_impl.hpp:2346
void updateWeldrawMaxRate(const Simulator &simulator, WellStateType &well_state, DeferredLogger &deferred_logger) const
Definition: WellInterface_impl.hpp:292
typename WellInterfaceFluidSystem< FluidSystem >::RateConverterType RateConverterType
Definition: WellInterface.hpp:110
Scalar wfoam() const
Definition: WellInterface_impl.hpp:132
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:384
void getTransMult(Value &trans_mult, const Simulator &simulator, const int cell_idx, Callback &extendEval) const
Definition: WellInterface_impl.hpp:2434
std::vector< RateVector > connectionRates_
Definition: WellInterface.hpp:460
bool solveWellForTesting(const Simulator &simulator, const GroupStateHelperType &groupStateHelper, WellStateType &well_state)
Definition: WellInterface_impl.hpp:1118
void computeConnLevelProdInd(const FluidState &fs, const std::function< Scalar(const Scalar)> &connPICalc, const std::vector< Scalar > &mobility, Scalar *connPI) const
Definition: WellInterface_impl.hpp:2600
void gliftBeginTimeStepWellTestUpdateALQ(const Simulator &simulator, WellStateType &well_state, const GroupState< Scalar > &group_state, GLiftEclWells &ecl_well_map, DeferredLogger &deferred_logger)
Definition: WellInterface_impl.hpp:1542
Scalar volumetricSurfaceRateForConnection(int cellIdx, int phaseIdx) const
Definition: WellInterface_impl.hpp:1494
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:100
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:2565
void getTw(std::vector< Value > &wi, const int perf, const IntensiveQuantities &intQuants, const Value &trans_mult, const SingleWellStateType &ws) const
Definition: WellInterface_impl.hpp:2235
void getMobility(const Simulator &simulator, const int local_perf_index, std::vector< Value > &mob, Callback &extendEval, DeferredLogger &deferred_logger) const
Definition: WellInterface_impl.hpp:2447
GetPropType< TypeTag, Properties::IntensiveQuantities > IntensiveQuantities
Definition: WellInterface.hpp:89
GetPropType< TypeTag, Properties::Scalar > Scalar
Definition: WellInterface.hpp:85
std::vector< Scalar > initialWellRateFractions(const Simulator &ebosSimulator, const WellStateType &well_state) const
Definition: WellInterface_impl.hpp:2097
void solveWellEquation(const Simulator &simulator, const GroupStateHelperType &groupStateHelper, WellStateType &well_state)
Definition: WellInterface_impl.hpp:1174
void updateConnectionDFactor(const Simulator &simulator, SingleWellStateType &ws) const
Definition: WellInterface_impl.hpp:2326
Eval getPerfCellPressure(const FluidState &fs) const
Definition: WellInterface_impl.hpp:2419
void initializeProducerWellState(const Simulator &simulator, WellStateType &well_state, DeferredLogger &deferred_logger) const
Definition: WellInterface_impl.hpp:2147
virtual void updateWellStateWithTarget(const Simulator &simulator, const GroupStateHelperType &groupStateHelper, WellStateType &well_state) const
Definition: WellInterface_impl.hpp:1672
void addCellRates(std::map< int, RateVector > &cellRates_) const
Definition: WellInterface_impl.hpp:1475
typename Base::ModelParameters ModelParameters
Definition: WellInterface.hpp:116
GetPropType< TypeTag, Properties::FluidSystem > FluidSystem
Definition: WellInterface.hpp:86
static constexpr bool has_solvent
Definition: WellInterface.hpp:118
bool wellUnderZeroRateTarget(const GroupStateHelperType &groupStateHelper) const
Definition: WellInterface_impl.hpp:2054
GetPropType< TypeTag, Properties::RateVector > RateVector
Definition: WellInterface.hpp:92
void updateConnectionTransmissibilityFactor(const Simulator &simulator, SingleWellStateType &ws) const
Definition: WellInterface_impl.hpp:2388
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:2634
typename GasLiftGroupInfo< Scalar, IndexTraits >::GLiftEclWells GLiftEclWells
Definition: WellInterface.hpp:94
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:2668
BlackOilFluidStateType< Eval > FluidState
Definition: WellInterface.hpp:148
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:999
Scalar wsalt() const
Definition: WellInterface_impl.hpp:146
void stopWellAndSolveWithZeroRate(const Simulator &simulator, const double dt, const GroupStateHelperType &groupStateHelper, WellStateType &well_state)
Stop the well and solve it with zero rate.
Definition: WellInterface_impl.hpp:1401
bool solveWellWithZeroRate(const Simulator &simulator, const double dt, const GroupStateHelperType &groupStateHelper, WellStateType &well_state)
Definition: WellInterface_impl.hpp:1086
bool wellUnderZeroGroupRateTarget(const GroupStateHelperType &groupStateHelper, const std::optional< bool > group_control=std::nullopt) const
Definition: WellInterface_impl.hpp:2071
bool solveWellWithBhp(const Simulator &simulator, const double dt, const Scalar bhp, const GroupStateHelperType &groupStateHelper, WellStateType &well_state)
Definition: WellInterface_impl.hpp:1036
void prepareWellBeforeAssembling(const Simulator &simulator, const double dt, const GroupStateHelperType &groupStateHelper, WellStateType &well_state)
Definition: WellInterface_impl.hpp:1289
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:503
typename Base::Eval Eval
Definition: WellInterface.hpp:98
WellInterface(const Well &well, const ParallelWellInfo< Scalar > &pw_info, const int time_step, const ModelParameters ¶m, 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:63
bool updateWellStateWithTHPTargetProd(const Simulator &simulator, WellStateType &well_state, const GroupStateHelperType &groupStateHelper) const
Definition: WellInterface_impl.hpp:2533
bool iterateWellEquations(const Simulator &simulator, const double dt, const GroupStateHelperType &groupStateHelper, WellStateType &well_state)
Definition: WellInterface_impl.hpp:660
Scalar wpolymer() const
Definition: WellInterface_impl.hpp:116
GetPropType< TypeTag, Properties::Indices > Indices
Definition: WellInterface.hpp:88
bool updateWellControl(const Simulator &simulator, const IndividualOrGroup iog, const GroupStateHelperType &groupStateHelper, WellStateType &well_state)
Definition: WellInterface_impl.hpp:194
Scalar wurea() const
Definition: WellInterface_impl.hpp:182
void updateGroupTargetFallbackFlag(WellStateType &well_state, DeferredLogger &deferred_logger) const
Definition: WellInterface_impl.hpp:1274
FSInfo getFirstPerfCellConditions(const Simulator &simulator) const
Temperature and salt concentration of the first perforated cell, broadcast so that all processes of a...
Definition: WellInterface_impl.hpp:2711
void assembleWellEq(const Simulator &simulator, const double dt, const GroupStateHelperType &groupStateHelper, WellStateType &well_state)
Definition: WellInterface_impl.hpp:1236
Scalar wmicrobes() const
Definition: WellInterface_impl.hpp:158
virtual void scaleSegmentRatesAndPressure(WellStateType &well_state) const
Definition: WellInterface_impl.hpp:1664
static constexpr bool has_zFraction
Definition: WellInterface.hpp:119
void consolidatePhaseMixingRates(WellStateType &well_state) const
Definition: WellInterface_impl.hpp:761
Definition: WellState.hpp:68
constexpr int numPhases() const
The number of phases present.
Definition: WellState.hpp:274
const SingleWellState< Scalar, IndexTraits > & well(std::size_t well_index) const
Definition: WellState.hpp:315
bool isOpen(const std::string &name) const
Definition: WellState.hpp:222
@ 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:184
Definition: blackoilbioeffectsmodules.hh:45
bool anyRank(const Communication &comm, const bool condition)
Whether a condition holds on any rank of the communicator.
Definition: WellSolveRecovery.hpp:35
const std::string & economicLimitMessageSeparator()
Separator line used to frame economic-limit workover messages. Built once and returned by reference (...
Definition: EconomicLimitsMessage.hpp:60
std::string economicLimitDateString(const time_point start_time, const double sim_time)
Calendar date (DD-Mon-YYYY, UTC) reached at start_time plus sim_time seconds.
Definition: EconomicLimitsMessage.hpp:40
std::string to_string(const ConvergenceReport::ReservoirFailure::Type t)
Reservoir temperature and salt concentration of the first perforated cell.
Definition: ParallelWellInfo.hpp:44
Scalar temperature
Definition: ParallelWellInfo.hpp:45
Static data associated with a well perforation.
Definition: PerforationData.hpp:30