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>
45#include <dune/common/version.hh>
54#include <fmt/format.h>
60 template<
typename TypeTag>
67 const int pvtRegionIdx,
68 const int num_conservation_quantities,
70 const int index_of_well,
78 num_conservation_quantities,
86 if (well.isInjector()) {
87 auto injectorType = this->
well_ecl_.injectorType();
88 if (injectorType == InjectorType::GAS) {
96 template<
typename TypeTag>
99 init(
const std::vector<Scalar>& ,
101 const std::vector<Scalar>& B_avg,
102 const bool changed_to_open_this_step)
104 this->gravity_ = gravity_arg;
106 this->changed_to_open_this_step_ = changed_to_open_this_step;
112 template<
typename TypeTag>
117 if constexpr (has_polymer) {
118 return this->wpolymer_();
128 template<
typename TypeTag>
133 if constexpr (has_foam) {
134 return this->wfoam_();
142 template<
typename TypeTag>
147 if constexpr (has_brine) {
148 return this->wsalt_();
154 template<
typename TypeTag>
159 if constexpr (has_micp) {
160 return this->wmicrobes_();
166 template<
typename TypeTag>
171 if constexpr (has_micp) {
172 return this->woxygen_();
178 template<
typename TypeTag>
183 if constexpr (has_micp) {
184 return this->wurea_();
190 template<
typename TypeTag>
200 if (stoppedOrZeroRateTarget(groupStateHelper)) {
204 const auto& summaryState = simulator.vanguard().summaryState();
205 const auto& schedule = simulator.vanguard().schedule();
206 const auto& well = this->well_ecl_;
207 auto& ws = well_state.
well(this->index_of_well_);
209 bool is_grup =
false;
210 if (well.isInjector()) {
211 from = WellInjectorCMode2String(ws.injection_cmode);
212 is_grup = ws.injection_cmode == Well::InjectorCMode::GRUP;
214 from = WellProducerCMode2String(ws.production_cmode);
215 is_grup = ws.production_cmode == Well::ProducerCMode::GRUP;
218 const int episodeIdx = simulator.episodeIndex();
219 const auto& iterCtx = simulator.problem().iterationContext();
220 const int nupcol = schedule[episodeIdx].nupcol();
221 const bool oscillating =
222 std::ranges::count(this->well_control_log_, from) >= this->param_.max_number_of_well_switches_;
223 if (oscillating && !is_grup) {
226 std::ranges::count(this->well_control_log_, from) == this->param_.max_number_of_well_switches_;
228 const auto msg = fmt::format(
" The control mode for well {} is oscillating. \n"
229 "We don't allow for more than {} switches after NUPCOL iterations. (NUPCOL = {}) \n"
230 "The control is kept at {}.",
231 this->name(), this->param_.max_number_of_well_switches_, nupcol, from);
232 deferred_logger.info(msg);
234 this->well_control_log_.push_back(from);
238 bool changed =
false;
239 if (iog == IndividualOrGroup::Individual) {
240 changed = this->checkIndividualConstraints(ws, summaryState, deferred_logger);
241 }
else if (iog == IndividualOrGroup::Group) {
242 changed = this->checkGroupConstraints(
243 groupStateHelper, schedule, summaryState,
true, well_state
246 assert(iog == IndividualOrGroup::Both);
247 changed = this->checkConstraints(groupStateHelper, schedule, summaryState, well_state);
253 if (well.isInjector()) {
254 to = WellInjectorCMode2String(ws.injection_cmode);
256 to = WellProducerCMode2String(ws.production_cmode);
258 std::ostringstream ss;
259 ss <<
" Switching control mode for well " << this->name()
262 if (iterCtx.inLocalSolve()) {
263 ss <<
" (NLDD domain solve)";
266 ss <<
" on rank " << cc.rank();
268 deferred_logger.debug(ss.str());
275 if (!iterCtx.inLocalSolve()) {
276 if (!iterCtx.withinNupcol(nupcol) || this->log_all_control_switches_
277 || this->well_control_log_.empty()) {
278 this->well_control_log_.push_back(from);
281 updateWellStateWithTarget(simulator, groupStateHelper, well_state);
282 updatePrimaryVariables(groupStateHelper);
288 template<
typename TypeTag>
295 if (!this->isProducer()) {
299 auto& ws = well_state.
well(this->index_of_well_);
300 const auto& weldraw = this->well_ecl_.getWELDRAW();
301 if (!weldraw.active()) {
302 ws.weldraw_max_rate.reset();
303 ws.weldraw_cmode.reset();
307 const auto& summary_state = simulator.vanguard().summaryState();
308 const Scalar max_draw = this->well_ecl_.weldrawMaxDrawdown(summary_state);
309 if (!(max_draw > 0.0)) {
310 ws.weldraw_max_rate.reset();
311 ws.weldraw_cmode.reset();
322 this->updateIPR(simulator, deferred_logger);
324 auto phase_coeff = [
this](
const unsigned phase_idx) ->
Scalar {
325 const unsigned comp_idx = FluidSystem::canonicalToActiveCompIdx(
326 FluidSystem::solventComponentIndex(phase_idx));
327 return this->ipr_b_[comp_idx];
331 const bool gas_target = (weldraw.targetPhase() == WELDRAW::TargetPhase::GAS);
333 if (FluidSystem::phaseIsActive(FluidSystem::gasPhaseIdx)) {
334 coeff += phase_coeff(FluidSystem::gasPhaseIdx);
338 if (FluidSystem::phaseIsActive(FluidSystem::oilPhaseIdx)) {
339 coeff += phase_coeff(FluidSystem::oilPhaseIdx);
341 if (FluidSystem::phaseIsActive(FluidSystem::waterPhaseIdx)) {
342 coeff += phase_coeff(FluidSystem::waterPhaseIdx);
346 if (!(coeff > 0.0)) {
352 deferred_logger.
warning(
"WELDRAW_NO_TARGET_PHASE_MOBILITY",
353 fmt::format(
"Well {}: the WELDRAW target phase ({}) has no "
354 "producible mobility; the drawdown limit is ignored.",
355 this->name(), gas_target ?
"GAS" :
"LIQ"));
356 ws.weldraw_max_rate.reset();
357 ws.weldraw_cmode.reset();
361 const Scalar max_rate = max_draw * coeff;
362 ws.weldraw_max_rate = max_rate;
367 const auto controls = this->well_ecl_.productionControls(summary_state);
368 const auto cmode = gas_target ? Well::ProducerCMode::GRAT
369 : Well::ProducerCMode::LRAT;
370 const Scalar own_target = gas_target ? controls.gas_rate
371 : controls.liquid_rate;
372 if (!controls.hasControl(cmode) || (max_rate <= own_target)) {
373 ws.weldraw_cmode = cmode;
376 ws.weldraw_cmode.reset();
380 template<
typename TypeTag>
385 const Well::InjectionControls& inj_controls,
386 const Well::ProductionControls& prod_controls,
389 const bool fixed_control,
390 const bool fixed_status,
391 const bool solving_with_zero_rate)
395 const auto& summary_state = simulator.vanguard().summaryState();
396 const auto& schedule = simulator.vanguard().schedule();
397 auto& ws = well_state.
well(this->index_of_well_);
399 if (this->isInjector()) {
400 from = WellInjectorCMode2String(ws.injection_cmode);
402 from = WellProducerCMode2String(ws.production_cmode);
404 const bool oscillating =
405 std::ranges::count(this->well_control_log_, from) >= this->param_.max_number_of_well_switches_;
407 if (oscillating || this->wellUnderZeroRateTarget(groupStateHelper) || !(well_state.
well(this->index_of_well_).status == WellStatus::OPEN)) {
411 const Scalar sgn = this->isInjector() ? 1.0 : -1.0;
412 if (!this->wellIsStopped()){
413 if (wqTotal*sgn <= 0.0 && !fixed_status){
417 bool changed =
false;
418 if (!fixed_control) {
421 if (solving_with_zero_rate) {
423 "Well {}: solving_with_zero_rate should not be true when fixed_control is false",
424 this->name()), deferred_logger);
430 const bool hasGroupControl = this->isInjector() ? inj_controls.hasControl(Well::InjectorCMode::GRUP) :
431 prod_controls.hasControl(Well::ProducerCMode::GRUP);
432 bool isGroupControl = ws.production_cmode == Well::ProducerCMode::GRUP || ws.injection_cmode == Well::InjectorCMode::GRUP;
433 if (! (isGroupControl && !this->param_.check_group_constraints_inner_well_iterations_)) {
434 changed = this->checkIndividualConstraints(ws, summary_state, deferred_logger, inj_controls, prod_controls);
436 if (hasGroupControl && this->param_.check_group_constraints_inner_well_iterations_) {
437 changed = changed || this->checkGroupConstraints(
438 groupStateHelper, schedule, summary_state,
false, well_state
443 const bool thp_controlled = this->isInjector() ? ws.injection_cmode == Well::InjectorCMode::THP :
444 ws.production_cmode == Well::ProducerCMode::THP;
446 ws.thp = this->getTHPConstraint(summary_state);
449 updateWellStateWithTarget(simulator, groupStateHelper, well_state);
451 updatePrimaryVariables(groupStateHelper);
456 }
else if (!fixed_status){
458 const Scalar bhp = well_state.
well(this->index_of_well_).bhp;
459 Scalar prod_limit = prod_controls.bhp_limit;
460 Scalar inj_limit = inj_controls.bhp_limit;
461 const bool has_thp = this->wellHasTHPConstraints(summary_state);
463 std::vector<Scalar> rates(this->num_conservation_quantities_);
464 if (this->isInjector()){
466 calculateBhpFromThp(well_state, rates,
469 this->getRefDensity(),
471 inj_limit = std::min(bhp_thp,
static_cast<Scalar>(inj_controls.bhp_limit));
476 calculateMinimumBhpFromThp(well_state,
479 this->getRefDensity());
480 prod_limit = std::max(bhp_min,
static_cast<Scalar>(prod_controls.bhp_limit));
483 const Scalar bhp_diff = (this->isInjector())? inj_limit - bhp: bhp - prod_limit;
486 well_state.
well(this->index_of_well_).bhp = (this->isInjector())? inj_limit : prod_limit;
488 well_state.
well(this->index_of_well_).thp = this->getTHPConstraint(summary_state);
499 template<
typename TypeTag>
503 const double simulation_time,
506 WellTestState& well_test_state,
508 std::map<std::string, double>& open_times)
512 const auto& group_state = groupStateHelper.
groupState();
516 const auto& unit_system = simulator.vanguard().eclState().getUnits();
517 const auto start_time = simulator.vanguard().schedule().getStartTime();
519 fmt::format(
"at time {:.2f} {} (date = {})",
520 unit_system.from_si(UnitSystem::measure::time, simulation_time),
521 unit_system.name(UnitSystem::measure::time),
524 deferred_logger.info(fmt::format(
"Well {} is being tested {}.", this->name(), when));
531 auto guard = groupStateHelper_copy.
pushWellState(well_state_copy);
532 auto& ws = well_state_copy.
well(this->indexOfWell());
534 const auto& summary_state = simulator.vanguard().summaryState();
535 const bool has_thp_limit = this->wellHasTHPConstraints(summary_state);
536 if (this->isProducer()) {
537 ws.production_cmode = has_thp_limit ? Well::ProducerCMode::THP : Well::ProducerCMode::BHP;
539 ws.injection_cmode = has_thp_limit ? Well::InjectorCMode::THP : Well::InjectorCMode::BHP;
544 scaleSegmentRatesAndPressure(well_state_copy);
545 calculateExplicitQuantities(simulator, groupStateHelper_copy);
546 updatePrimaryVariables(groupStateHelper_copy);
548 if (this->isProducer()) {
549 const auto& schedule = simulator.vanguard().schedule();
550 const auto report_step = simulator.episodeIndex();
551 const auto& glo = schedule.glo(report_step);
553 gliftBeginTimeStepWellTestUpdateALQ(simulator,
561 WellTestState welltest_state_temp;
563 std::string closure_reason;
569 auto notReopened = [
this, &when, &deferred_logger](
const std::string_view reason)
571 deferred_logger.info(
572 fmt::format(
"Well {} is not re-opened {}.", this->name(), when));
573 if (!reason.empty()) {
574 deferred_logger.debug(fmt::format(
"Because {}.", reason));
578 bool testWell =
true;
583 const std::size_t original_number_closed_completions = welltest_state_temp.num_closed_completions();
584 bool converged = solveWellForTesting(simulator, groupStateHelper_copy, well_state_copy);
586 notReopened(
"the well equations could not be solved");
591 updateWellOperability(simulator, well_state_copy, groupStateHelper_copy);
592 if ( !this->isOperableAndSolvable() ) {
593 notReopened(
"the well is not operable");
596 std::vector<Scalar> potentials;
598 computeWellPotentials(simulator, well_state_copy, groupStateHelper_copy, potentials);
599 }
catch (
const std::exception& e) {
600 notReopened(fmt::format(
"computing the well potentials failed: {}", e.what()));
603 const int np = well_state_copy.
numPhases();
604 for (
int p = 0; p < np; ++p) {
605 ws.well_potentials[p] = std::max(
Scalar{0.0}, potentials[p]);
607 const bool under_zero_target = this->wellUnderZeroGroupRateTarget(groupStateHelper_copy);
608 this->updateWellTestState(well_state_copy.
well(this->indexOfWell()),
614 simulator.vanguard().eclState().getUnits(),
615 simulator.vanguard().schedule().getStartTime(),
618 this->closeCompletions(welltest_state_temp);
624 if ( welltest_state_temp.num_closed_wells() > 0 ||
625 (original_number_closed_completions == welltest_state_temp.num_closed_completions()) ) {
631 if (!welltest_state_temp.well_is_closed(this->name())) {
632 well_test_state.open_well(this->name());
635 deferred_logger.info(
636 fmt::format(
"{}\nWell {} is re-opened {}.\n{}",
637 sep, this->name(), when, sep));
640 for (
const auto& completion : this->well_ecl_.getCompletions()) {
641 if (!welltest_state_temp.completion_is_closed(this->name(), completion.first))
642 well_test_state.open_completion(this->name(), completion.first);
644 well_state = well_state_copy;
645 open_times.try_emplace(this->name(), well_test_state.lastTestTime(this->name()));
649 notReopened(closure_reason);
656 template<
typename TypeTag>
667 const auto& summary_state = simulator.vanguard().summaryState();
668 const auto& ws = well_state.
well(this->indexOfWell());
669 const auto inj_controls = this->well_ecl_.isInjector() ? this->well_ecl_.injectionControls(summary_state) : Well::InjectionControls(0);
670 const auto prod_controls = this->well_ecl_.isProducer() ? this->productionControlsWithWeldraw(summary_state, ws) : Well::ProductionControls(0);
671 const auto pmode_orig = ws.production_cmode;
672 const auto imode_orig = ws.injection_cmode;
674 const auto ws_before_solve = ws;
675 bool converged =
false;
676 bool solve_threw =
false;
679 if (!this->param_.local_well_solver_control_switching_){
680 converged = this->iterateWellEqWithControl(simulator, dt, inj_controls, prod_controls, groupStateHelper, well_state);
682 if (this->param_.use_implicit_ipr_ && this->well_ecl_.isProducer() && (well_state.
well(this->index_of_well_).status == WellStatus::OPEN)) {
683 converged = solveWellWithOperabilityCheck(
684 simulator, dt, inj_controls, prod_controls, groupStateHelper, well_state
687 converged = this->iterateWellEqWithSwitching(
688 simulator, dt, inj_controls, prod_controls, groupStateHelper, well_state,
694 }
catch (NumericalProblem& e ) {
695 const std::string msg =
"Inner well iterations failed for well " + this->name() +
" Treat the well as unconverged. ";
696 deferred_logger.warning(
"INNER_ITERATION_FAILED", msg);
704 if (well_state.
well(this->indexOfWell()).restoreIfDiverged(ws_before_solve, solve_threw)) {
711 this->updatePrimaryVariables(groupStateHelper);
712 this->assembleWellEqWithoutIteration(simulator, groupStateHelper, dt, inj_controls, prod_controls,
714 }
catch (
const NumericalProblem&) {
720 if (ws.production_cmode != pmode_orig || ws.injection_cmode != imode_orig) {
722 if (this->isInjector()) {
723 from = WellInjectorCMode2String(imode_orig);
724 to = WellInjectorCMode2String(ws.injection_cmode);
726 from = WellProducerCMode2String(pmode_orig);
727 to = WellProducerCMode2String(ws.production_cmode);
729 const auto msg = fmt::format(
" Well {} switched from {} to {} during local solve", this->name(), from, to);
730 deferred_logger.debug(msg);
731 const int episodeIdx = simulator.episodeIndex();
732 const auto& iterCtx = simulator.problem().iterationContext();
733 const auto& schedule = simulator.vanguard().schedule();
734 const int nupcol = schedule[episodeIdx].nupcol();
738 if (!iterCtx.withinNupcol(nupcol) || this->log_all_control_switches_
739 || this->well_control_log_.empty()) {
740 this->well_control_log_.push_back(from);
745 if (this->isProducer() && ws.production_cmode == Well::ProducerCMode::GRUP && ws.use_group_target_fallback) {
746 assert(ws.group_target && ws.group_target_fallback);
747 const std::string cmode = Group::ProductionCMode2String(ws.group_target->production_cmode);
748 const std::string cmode_fallback = Group::ProductionCMode2String(ws.group_target_fallback->production_cmode);
749 const auto msg = fmt::format(
" Well {} was solved using group target fallback mode {} as current group mode {} was not feasible.",
750 this->name(), cmode_fallback, cmode);
751 deferred_logger.debug(msg);
757 template<
typename TypeTag>
762 auto& ws = well_state.
well(this->index_of_well_);
763 ws.rs_rep = ws.rv_rep = ws.rsw_rep = ws.rvw_rep = 0.0;
764 if (!this->isProducer()) {
768 const bool waterActive = FluidSystem::phaseIsActive(FluidSystem::waterPhaseIdx);
769 const bool oilActive = FluidSystem::phaseIsActive(FluidSystem::oilPhaseIdx);
770 const bool gasActive = FluidSystem::phaseIsActive(FluidSystem::gasPhaseIdx);
771 if (!gasActive || (!oilActive && !waterActive)) {
776 const int waterPos = waterActive ? FluidSystem::canonicalToActivePhaseIdx(FluidSystem::waterPhaseIdx) : -1;
777 const int oilPos = oilActive ? FluidSystem::canonicalToActivePhaseIdx(FluidSystem::oilPhaseIdx) : -1;
778 const int gasPos = FluidSystem::canonicalToActivePhaseIdx(FluidSystem::gasPhaseIdx);
782 const int numPhases = this->numPhases();
783 constexpr std::size_t numMixingRates = 4;
784 std::vector<Scalar> sums(numPhases + numMixingRates, 0.0);
785 const auto& perf_rates = ws.perf_data.phase_rates;
786 const auto& perf_mixing = ws.perf_data.phase_mixing_rates;
787 for (
int perf = 0; perf < this->numLocalPerfs(); ++perf) {
788 for (
int phase = 0; phase < numPhases; ++phase) {
789 sums[phase] += perf_rates[perf * numPhases + phase];
791 for (std::size_t mix = 0; mix < numMixingRates; ++mix) {
792 sums[numPhases + mix] += perf_mixing[perf][mix];
795 this->parallelWellInfo().communication().sum(sums.data(), sums.size());
797 const Scalar dis_gas = sums[numPhases + ws.dissolved_gas];
798 const Scalar dis_gas_water = sums[numPhases + ws.dissolved_gas_in_water];
799 const Scalar vap_oil = sums[numPhases + ws.vaporized_oil];
800 const Scalar vap_water = sums[numPhases + ws.vaporized_water];
804 const Scalar free_oil = oilActive ? sums[oilPos] - vap_oil : 0.0;
805 const Scalar free_water = waterActive ? sums[waterPos] - vap_water : 0.0;
806 const Scalar free_gas = sums[gasPos] - dis_gas - dis_gas_water;
807 const auto ratio = [](
const Scalar num,
const Scalar den) {
808 return (den != 0.0) ? num / den :
Scalar{0.0};
814 const Scalar surface_gas = std::abs(ws.surface_rates[gasPos]);
815 const Scalar solvent = has_solvent ? std::abs(ws.sum_solvent_rates()) :
Scalar{0.0};
816 const Scalar hydrocarbon_gas = std::max(surface_gas - solvent,
Scalar{0.0});
824 Scalar rvw = waterActive ? ratio(vap_water, free_gas) :
Scalar{0.0};
827 if (waterActive && FluidSystem::enableVaporizedWater()) {
828 const Scalar qw = std::abs(ws.surface_rates[waterPos]);
829 const Scalar qg = hydrocarbon_gas;
830 const Scalar rvw_max = FluidSystem::gasPvt()
831 .saturatedWaterVaporizationFactor(this->pvtRegionIdx(), ws.temperature, ws.bhp);
832 rvw = (qg > 0.0) ? std::min(qw / qg, rvw_max) :
Scalar{0.0};
837 const Scalar rs = ratio(dis_gas, free_oil);
838 const Scalar rv = ratio(vap_oil, free_gas);
839 if (rs >= 0.0 && rv >= 0.0 && rs * rv < 1.0) {
846 const Scalar qo = std::abs(ws.surface_rates[oilPos]);
847 const Scalar qg = hydrocarbon_gas;
848 const int pvtReg = this->pvtRegionIdx();
851 const Scalar rs_max = FluidSystem::enableDissolvedGas()
852 ? FluidSystem::oilPvt().saturatedGasDissolutionFactor(pvtReg, ws.temperature, ws.bhp)
854 const Scalar rv_max = FluidSystem::enableVaporizedOil()
855 ? FluidSystem::gasPvt().saturatedOilVaporizationFactor(pvtReg, ws.temperature, ws.bhp)
857 const Scalar rs_inf = (qo > 0.0) ? std::min(qg / qo, rs_max) :
Scalar{0.0};
858 const Scalar rv_inf = (qg > 0.0) ? std::min(qo / qg, rv_max) :
Scalar{0.0};
859 if (rs_inf * rv_inf < 1.0) {
869 const Scalar rsw = std::max(ratio(dis_gas_water, free_water),
Scalar{0.0});
871 ws.rvw_rep = (rsw * rvw < 1.0) ? rvw :
Scalar{0.0};
875 template<
typename TypeTag>
880 const Well::InjectionControls& inj_controls,
881 const Well::ProductionControls& prod_controls,
888 const auto& summary_state = simulator.vanguard().summaryState();
889 bool converged =
true;
890 auto& ws = well_state.
well(this->index_of_well_);
892 if (this->wellIsStopped()) {
894 const bool use_vfpexplicit = this->operability_status_.use_vfpexplicit;
895 this->operability_status_.use_vfpexplicit =
true;
896 auto bhp_target = estimateOperableBhp(simulator, dt, groupStateHelper, summary_state, well_state);
897 if (!bhp_target.has_value()) {
899 const auto msg = fmt::format(
"estimateOperableBhp: Did not find operable BHP for well {}", this->name());
900 deferred_logger.debug(msg);
903 converged = solveWellWithZeroRate(simulator, dt, groupStateHelper, well_state);
905 this->operability_status_.can_obtain_bhp_with_thp_limit =
false;
906 this->operability_status_.obey_thp_limit_under_bhp_limit =
false;
910 ws.thp = this->getTHPConstraint(summary_state);
911 const Scalar bhp = std::max(bhp_target.value(),
912 static_cast<Scalar>(prod_controls.bhp_limit));
913 solveWellWithBhp(simulator, dt, bhp, groupStateHelper, well_state);
914 this->operability_status_.use_vfpexplicit = use_vfpexplicit;
918 converged = this->iterateWellEqWithSwitching(
919 simulator, dt, inj_controls, prod_controls, groupStateHelper, well_state,
924 const bool isThp = ws.production_cmode == Well::ProducerCMode::THP;
926 if (converged && !stoppedOrZeroRateTarget(groupStateHelper) && isThp) {
927 auto rates = well_state.
well(this->index_of_well_).surface_rates;
928 this->adaptRatesForVFP(rates);
929 this->updateIPRImplicit(simulator, groupStateHelper, well_state);
933 this->operability_status_.use_vfpexplicit =
true;
936 const Scalar reltol = 1e-3;
937 const Scalar cur_bhp = ws.bhp;
938 if (bhp_stable.has_value() && cur_bhp - bhp_stable.value() > cur_bhp*reltol){
939 const auto msg = fmt::format(
"Well {} converged to an unstable solution, re-solving", this->name());
940 deferred_logger.debug(msg);
942 simulator, dt, bhp_stable.value(), groupStateHelper, well_state
945 ws.thp = this->getTHPConstraint(summary_state);
946 converged = this->iterateWellEqWithSwitching(
947 simulator, dt, inj_controls, prod_controls, groupStateHelper, well_state,
956 this->operability_status_.use_vfpexplicit =
true;
958 auto bhp_target = estimateOperableBhp(
959 simulator, dt, groupStateHelper, summary_state, well_state
961 if (!bhp_target.has_value()) {
964 converged = solveWellWithZeroRate(simulator, dt, groupStateHelper, well_state);
966 this->operability_status_.can_obtain_bhp_with_thp_limit =
false;
967 this->operability_status_.obey_thp_limit_under_bhp_limit =
false;
971 const Scalar bhp = std::max(bhp_target.value(),
972 static_cast<Scalar>(prod_controls.bhp_limit));
974 simulator, dt, bhp, groupStateHelper, well_state
976 ws.thp = this->getTHPConstraint(summary_state);
977 const auto msg = fmt::format(
"Well {} did not converge, re-solving with explicit fractions for VFP caculations.", this->name());
978 deferred_logger.debug(msg);
979 converged = this->iterateWellEqWithSwitching(simulator, dt,
990 this->operability_status_.can_obtain_bhp_with_thp_limit = !this->wellIsStopped();
991 this->operability_status_.obey_thp_limit_under_bhp_limit = !this->wellIsStopped();
995 template<
typename TypeTag>
996 std::optional<typename WellInterface<TypeTag>::Scalar>
1001 const SummaryState& summary_state,
1004 if (!this->wellHasTHPConstraints(summary_state)) {
1006 const bool converged = solveWellWithBhp(
1007 simulator, dt, bhp_limit, groupStateHelper, well_state
1009 if (!converged || this->wellIsStopped()) {
1010 return std::nullopt;
1020 const bool converged = solveWellWithBhp(
1021 simulator, dt, bhp_min, groupStateHelper, well_state
1023 if (!converged || this->wellIsStopped()) {
1024 return std::nullopt;
1026 this->updateIPRImplicit(simulator, groupStateHelper, well_state);
1027 auto rates = well_state.
well(this->index_of_well_).surface_rates;
1028 this->adaptRatesForVFP(rates);
1032 template<
typename TypeTag>
1049 auto group_guard = groupStateHelper_copy.
pushGroupState(group_state);
1051 auto inj_controls = Well::InjectionControls(0);
1052 auto prod_controls = Well::ProductionControls(0);
1053 auto& ws = well_state.
well(this->index_of_well_);
1054 auto cmode_inj = ws.injection_cmode;
1055 auto cmode_prod = ws.production_cmode;
1056 if (this->isInjector()) {
1057 inj_controls.addControl(Well::InjectorCMode::BHP);
1058 inj_controls.bhp_limit = bhp;
1059 inj_controls.cmode = Well::InjectorCMode::BHP;
1060 ws.injection_cmode = Well::InjectorCMode::BHP;
1062 prod_controls.addControl(Well::ProducerCMode::BHP);
1063 prod_controls.bhp_limit = bhp;
1064 prod_controls.cmode = Well::ProducerCMode::BHP;
1065 ws.production_cmode = Well::ProducerCMode::BHP;
1070 const bool converged = this->iterateWellEqWithSwitching(
1071 simulator, dt, inj_controls, prod_controls, groupStateHelper_copy,
1077 ws.injection_cmode = cmode_inj;
1078 ws.production_cmode = cmode_prod;
1082 template<
typename TypeTag>
1093 const auto well_status_orig = this->wellStatus_;
1096 auto inj_controls = Well::InjectionControls(0);
1097 auto prod_controls = Well::ProductionControls(0);
1102 const bool converged = this->iterateWellEqWithSwitching(
1103 simulator, dt, inj_controls, prod_controls,
1110 this->wellStatus_ = well_status_orig;
1114 template<
typename TypeTag>
1124 const double dt = simulator.timeStepSize();
1126 const auto& summary_state = simulator.vanguard().summaryState();
1127 auto inj_controls = this->well_ecl_.isInjector() ? this->well_ecl_.injectionControls(summary_state) : Well::InjectionControls(0);
1128 auto prod_controls = this->well_ecl_.isProducer() ? this->well_ecl_.productionControls(summary_state) : Well::ProductionControls(0);
1129 this->onlyKeepBHPandTHPcontrols(summary_state, well_state, inj_controls, prod_controls);
1131 bool converged =
false;
1134 if (!this->param_.local_well_solver_control_switching_){
1135 converged = this->iterateWellEqWithControl(
1136 simulator, dt, inj_controls, prod_controls, groupStateHelper, well_state
1139 if (this->param_.use_implicit_ipr_ && this->well_ecl_.isProducer() && (well_state.
well(this->index_of_well_).status == WellStatus::OPEN)) {
1140 converged = this->solveWellWithOperabilityCheck(
1141 simulator, dt, inj_controls, prod_controls, groupStateHelper, well_state
1144 converged = this->iterateWellEqWithSwitching(
1145 simulator, dt, inj_controls, prod_controls, groupStateHelper, well_state,
1153 }
catch (NumericalProblem& e ) {
1154 const std::string msg =
"Inner well iterations failed for well " + this->name() +
" Treat the well as unconverged. ";
1155 deferred_logger.warning(
"INNER_ITERATION_FAILED", msg);
1160 deferred_logger.debug(
"WellTest: Well equation for well " + this->name() +
" converged");
1163 const int max_iter = this->param_.max_welleq_iter_;
1164 deferred_logger.debug(
"WellTest: Well equation for well " + this->name() +
" failed converging in "
1170 template<
typename TypeTag>
1179 if (!this->isOperableAndSolvable() && !this->wellIsStopped())
1184 const double dt = simulator.timeStepSize();
1185 bool converged = iterateWellEquations(simulator, dt, groupStateHelper, well_state);
1195 auto& ws = well_state.
well(this->indexOfWell());
1196 bool thp_control =
false;
1197 if (this->well_ecl_.isInjector()) {
1198 thp_control = ws.injection_cmode == Well::InjectorCMode::THP;
1200 ws.injection_cmode = Well::InjectorCMode::BHP;
1201 if (this->well_control_log_.empty()) {
1202 this->well_control_log_.push_back(WellInjectorCMode2String(Well::InjectorCMode::THP));
1206 thp_control = ws.production_cmode == Well::ProducerCMode::THP;
1208 ws.production_cmode = Well::ProducerCMode::BHP;
1209 if (this->well_control_log_.empty()) {
1210 this->well_control_log_.push_back(WellProducerCMode2String(Well::ProducerCMode::THP));
1215 const std::string msg = std::string(
"The newly opened well ") + this->name()
1216 + std::string(
" with THP control did not converge during inner iterations, we try again with bhp control");
1217 deferred_logger.debug(msg);
1218 converged = this->iterateWellEquations(simulator, dt, groupStateHelper, well_state);
1223 const int max_iter = this->param_.max_welleq_iter_;
1224 deferred_logger.debug(
"Compute initial well solution for well " + this->name() +
". Failed to converge in "
1226 well_state = well_state0;
1232 template <
typename TypeTag>
1241 prepareWellBeforeAssembling(simulator, dt, groupStateHelper, well_state);
1242 assembleWellEqWithoutIteration(simulator, groupStateHelper, dt, well_state,
1248 template <
typename TypeTag>
1255 const bool solving_with_zero_rate)
1258 const auto& summary_state = simulator.vanguard().summaryState();
1259 const auto inj_controls = this->well_ecl_.isInjector() ? this->well_ecl_.injectionControls(summary_state) : Well::InjectionControls(0);
1260 const auto prod_controls = this->well_ecl_.isProducer()
1261 ? this->productionControlsWithWeldraw(summary_state, well_state.
well(this->index_of_well_))
1262 : Well::ProductionControls(0);
1265 assembleWellEqWithoutIteration(simulator, groupStateHelper, dt, inj_controls, prod_controls, well_state, solving_with_zero_rate);
1270 template<
typename TypeTag>
1277 std::vector<Scalar> scaled_well_fractions(FluidSystem::numPhases, 0.0);
1278 this->getScaledWellFractions(scaled_well_fractions, deferred_logger);
1280 this->Base::updateGroupTargetFallbackFlag(well_state, scaled_well_fractions, deferred_logger);
1285 template<
typename TypeTag>
1295 const bool old_well_operable = this->operability_status_.isOperableAndSolvable();
1297 if (this->param_.check_well_operability_iter_)
1298 checkWellOperability(simulator, well_state, groupStateHelper);
1301 const auto& iterCtx = simulator.problem().iterationContext();
1302 if (iterCtx.shouldRunInnerWellIterations(this->param_.max_niter_inner_well_iter_)) {
1303 const auto& ws = well_state.
well(this->indexOfWell());
1304 const bool nonzero_rate_original =
1305 std::any_of(ws.surface_rates.begin(),
1306 ws.surface_rates.begin() + well_state.
numPhases(),
1307 [](
Scalar rate) { return rate != Scalar(0.0); });
1309 this->operability_status_.solvable =
true;
1310 if (number_of_well_reopenings_ >= this->param_.max_well_status_switch_) {
1312 if (number_of_well_reopenings_ == this->param_.max_well_status_switch_) {
1313 const std::string msg = fmt::format(
"well {} is oscillating between open and stop. \n"
1314 "We don't allow for more than {} re-openings "
1315 "and the well is therefore kept stopped.",
1316 this->name(), number_of_well_reopenings_);
1317 deferred_logger.debug(msg);
1318 changed_to_stopped_this_step_ = old_well_operable;
1320 changed_to_stopped_this_step_ =
false;
1323 bool converged_zero_rate = this->solveWellWithZeroRate(
1324 simulator, dt, groupStateHelper, well_state
1326 if (this->param_.shut_unsolvable_wells_ && !converged_zero_rate ) {
1327 this->operability_status_.solvable =
false;
1329 this->operability_status_.can_obtain_bhp_with_thp_limit =
false;
1330 this->operability_status_.obey_thp_limit_under_bhp_limit =
false;
1333 number_of_well_reopenings_++;
1336 bool converged = this->iterateWellEquations(
1337 simulator, dt, groupStateHelper, well_state
1341 const bool zero_target = this->wellUnderZeroRateTarget(groupStateHelper);
1342 if (this->wellIsStopped() && !zero_target && nonzero_rate_original) {
1346 this->operability_status_.resetOperability();
1348 deferred_logger.debug(
" " + this->name() +
" is re-opened after being stopped during local solve");
1349 number_of_well_reopenings_++;
1353 if (this->param_.shut_unsolvable_wells_) {
1354 this->operability_status_.solvable =
false;
1358 if (this->operability_status_.has_negative_potentials) {
1359 auto well_state_copy = well_state;
1360 std::vector<Scalar> potentials;
1362 computeWellPotentials(simulator, well_state_copy, groupStateHelper, potentials);
1363 }
catch (
const std::exception& e) {
1364 const std::string msg = fmt::format(
"well {}: computeWellPotentials() failed "
1365 "during attempt to recompute potentials for well: ",
1366 this->name(), e.what());
1367 deferred_logger.info(msg);
1368 this->operability_status_.has_negative_potentials =
true;
1370 auto& ws = well_state.
well(this->indexOfWell());
1372 for (
int p = 0; p < np; ++p) {
1373 ws.well_potentials[p] = std::max(
Scalar{0.0}, potentials[p]);
1376 this->changed_to_open_this_step_ =
false;
1377 changed_to_stopped_this_step_ =
false;
1379 const bool well_operable = this->operability_status_.isOperableAndSolvable();
1380 if (!well_operable) {
1383 this->solveWellWithZeroRate(
1384 simulator, dt, groupStateHelper, well_state
1386 }
catch (
const std::exception& e) {
1387 const std::string msg = fmt::format(
"well {}: solveWellWithZeroRate() failed "
1388 "during attempt to solve with zero rate for well: ",
1389 this->name(), e.what());
1390 deferred_logger.info(msg);
1392 auto& ws = well_state.
well(this->indexOfWell());
1394 for (
int p = 0; p < np; ++p) {
1395 ws.surface_rates[p] =
Scalar{0.0};
1398 if (old_well_operable) {
1399 const std::string ctx = iterCtx.inLocalSolve() ?
" (NLDD domain solve)" :
"";
1400 deferred_logger.debug(
" well " + this->name() +
" gets STOPPED during iteration" + ctx);
1401 changed_to_stopped_this_step_ =
true;
1403 }
else if (well_state.
isOpen(this->name())) {
1405 if (!old_well_operable) {
1406 const std::string ctx = iterCtx.inLocalSolve() ?
" (NLDD domain solve)" :
"";
1407 deferred_logger.debug(
" well " + this->name() +
" gets REVIVED during iteration" + ctx);
1408 this->changed_to_open_this_step_ =
true;
1413 template<
typename TypeTag>
1417 if(!this->operability_status_.solvable)
1420 for (
int perfIdx = 0; perfIdx < this->number_of_local_perforations_; ++perfIdx) {
1421 const auto cellIdx = this->cells()[perfIdx];
1422 const auto it = cellRates_.find(cellIdx);
1423 RateVector rates = (it == cellRates_.end()) ? 0.0 : it->second;
1424 for (
auto i=0*RateVector::dimension; i < RateVector::dimension; ++i)
1426 rates[i] += connectionRates_[perfIdx][i];
1428 cellRates_.insert_or_assign(cellIdx, rates);
1432 template<
typename TypeTag>
1436 for (
int perfIdx = 0; perfIdx < this->number_of_local_perforations_; ++perfIdx) {
1437 if (this->cells()[perfIdx] == cellIdx) {
1438 const unsigned activeCompIdx = FluidSystem::canonicalToActiveCompIdx(FluidSystem::solventComponentIndex(phaseIdx));
1439 return connectionRates_[perfIdx][activeCompIdx].value();
1443 OPM_THROW(std::invalid_argument,
"The well with name " + this->name()
1451 template<
typename TypeTag>
1460 if (!this->param_.check_well_operability_) {
1464 if (this->wellIsStopped() && !changed_to_stopped_this_step_) {
1468 updateWellOperability(simulator, well_state, groupStateHelper);
1469 if (!this->operability_status_.isOperableAndSolvable()) {
1470 this->operability_status_.use_vfpexplicit =
true;
1471 deferred_logger.debug(
"EXPLICIT_LOOKUP_VFP",
1472 "well not operable, trying with explicit vfp lookup: " + this->name());
1473 updateWellOperability(simulator, well_state, groupStateHelper);
1479 template<
typename TypeTag>
1489 const auto& summary_state = simulator.vanguard().summaryState();
1490 const auto& well_name = this->name();
1491 if (!this->wellHasTHPConstraints(summary_state)) {
1492 const std::string msg = fmt::format(
"GLIFT WTEST: Well {} does not have THP constraints", well_name);
1493 deferred_logger.
info(msg);
1496 const auto& schedule = simulator.vanguard().schedule();
1497 const auto report_step_idx = simulator.episodeIndex();
1498 const auto& glo = schedule.glo(report_step_idx);
1499 if (!glo.has_well(well_name)) {
1500 const std::string msg = fmt::format(
1501 "GLIFT WTEST: Well {} : Gas lift not activated: "
1502 "WLIFTOPT is probably missing. Skipping.", well_name);
1503 deferred_logger.
info(msg);
1506 const auto& gl_well = glo.well(well_name);
1509 std::unique_ptr<GasLiftSingleWell> glift =
1510 initializeGliftWellTest_<GasLiftSingleWell>(simulator,
1515 auto [wtest_alq, success] = glift->wellTestALQ();
1517 const auto& unit_system = schedule.getUnits();
1519 well_state.
well(well_name).alq_state.set(wtest_alq);
1521 "GLIFT WTEST: Well {} : Setting ALQ to optimized value = {}",
1522 well_name, unit_system.from_si(UnitSystem::measure::gas_surface_rate, wtest_alq));
1525 if (!gl_well.use_glo()) {
1527 "GLIFT WTEST: Well {} : Gas lift optimization deactivated. Setting ALQ to WLIFTOPT item 3 = {}",
1529 unit_system.from_si(UnitSystem::measure::gas_surface_rate, well_state.
well(well_name).alq_state.get()));
1534 "GLIFT WTEST: Well {} : Gas lift optimization failed, no ALQ set.",
1538 deferred_logger.
info(msg);
1541 template<
typename TypeTag>
1550 if (this->param_.local_well_solver_control_switching_) {
1551 const bool success = updateWellOperabilityFromWellEq(simulator, groupStateHelper);
1553 this->operability_status_.solvable =
false;
1554 deferred_logger.debug(
"Operability check using well equations did not converge for well "
1555 + this->name() +
". Mark the well as unsolvable." );
1559 this->operability_status_.resetOperability();
1561 bool thp_controlled = this->isInjector() ? well_state.
well(this->index_of_well_).injection_cmode == Well::InjectorCMode::THP:
1562 well_state.
well(this->index_of_well_).production_cmode == Well::ProducerCMode::THP;
1563 bool bhp_controlled = this->isInjector() ? well_state.
well(this->index_of_well_).injection_cmode == Well::InjectorCMode::BHP:
1564 well_state.
well(this->index_of_well_).production_cmode == Well::ProducerCMode::BHP;
1568 bool check_thp = thp_controlled || this->operability_status_.thp_limit_violated_but_not_switched;
1569 if (check_thp || bhp_controlled) {
1570 updateIPR(simulator, deferred_logger);
1571 checkOperabilityUnderBHPLimit(well_state, simulator, deferred_logger);
1575 checkOperabilityUnderTHPLimit(simulator, well_state, groupStateHelper);
1579 template<
typename TypeTag>
1587 assert(this->param_.local_well_solver_control_switching_);
1588 this->operability_status_.resetOperability();
1591 const double dt = simulator.timeStepSize();
1595 auto guard = groupStateHelper_copy.
pushWellState(well_state_copy);
1597 bool converged = iterateWellEquations(simulator, dt, groupStateHelper_copy, well_state_copy);
1601 template<
typename TypeTag>
1609 template<
typename TypeTag>
1619 const auto& well = this->well_ecl_;
1620 const int well_index = this->index_of_well_;
1621 auto& ws = well_state.
well(well_index);
1623 const auto& summaryState = simulator.vanguard().summaryState();
1624 const auto& schedule = simulator.vanguard().schedule();
1628 ws.primaryvar.resize(0);
1630 if (this->wellIsStopped()) {
1631 for (
int p = 0; p<np; ++p) {
1632 ws.surface_rates[p] = 0;
1638 if (this->isInjector() )
1640 const auto& controls = well.injectionControls(summaryState);
1642 InjectorType injectorType = controls.injector_type;
1644 switch (injectorType) {
1645 case InjectorType::WATER:
1647 phasePos = FluidSystem::canonicalToActivePhaseIdx(FluidSystem::waterPhaseIdx);
1650 case InjectorType::OIL:
1652 phasePos = FluidSystem::canonicalToActivePhaseIdx(FluidSystem::oilPhaseIdx);
1655 case InjectorType::GAS:
1657 phasePos = FluidSystem::canonicalToActivePhaseIdx(FluidSystem::gasPhaseIdx);
1661 OPM_DEFLOG_THROW(std::runtime_error,
"Expected WATER, OIL or GAS as type for injectors " + this->name(), deferred_logger );
1664 const auto current = ws.injection_cmode;
1667 case Well::InjectorCMode::RATE:
1669 ws.surface_rates[phasePos] = (1.0 - this->rsRvInj()) * controls.surface_rate;
1670 if(this->rsRvInj() > 0) {
1671 if (injectorType == InjectorType::OIL && FluidSystem::phaseIsActive(FluidSystem::gasPhaseIdx)) {
1672 const int gas_pos = FluidSystem::canonicalToActivePhaseIdx(FluidSystem::gasPhaseIdx);
1673 ws.surface_rates[gas_pos] = controls.surface_rate * this->rsRvInj();
1674 }
else if (injectorType == InjectorType::GAS && FluidSystem::phaseIsActive(FluidSystem::oilPhaseIdx)) {
1675 const int oil_pos = FluidSystem::canonicalToActivePhaseIdx(FluidSystem::oilPhaseIdx);
1676 ws.surface_rates[oil_pos] = controls.surface_rate * this->rsRvInj();
1678 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 );
1684 case Well::InjectorCMode::RESV:
1686 std::vector<Scalar> convert_coeff(this->number_of_phases_, 1.0);
1687 this->rateConverter_.calcCoeff( 0, this->pvtRegionIdx_, convert_coeff);
1688 const Scalar coeff = convert_coeff[phasePos];
1689 ws.surface_rates[phasePos] = controls.reservoir_rate/coeff;
1693 case Well::InjectorCMode::THP:
1695 auto rates = ws.surface_rates;
1700 this->getRefDensity(),
1703 ws.thp = this->getTHPConstraint(summaryState);
1708 Scalar total_rate = std::accumulate(rates.begin(), rates.end(), 0.0);
1709 if (total_rate <= 0.0)
1710 ws.surface_rates = ws.well_potentials;
1714 case Well::InjectorCMode::BHP:
1716 ws.bhp = controls.bhp_limit;
1718 for (
int p = 0; p<np; ++p) {
1719 total_rate += ws.surface_rates[p];
1724 if (total_rate <= 0.0)
1725 ws.surface_rates = ws.well_potentials;
1729 case Well::InjectorCMode::GRUP:
1731 assert(well.isAvailableForGroupControl());
1732 const auto& group = schedule.getGroup(well.groupName(), this->currentStep());
1733 const Scalar efficiencyFactor = well.getEfficiencyFactor() *
1734 well_state[well.name()].efficiency_scaling_factor;
1735 std::optional<Scalar> target =
1736 this->getGroupInjectionTargetRate(group,
1741 ws.surface_rates[phasePos] = *target;
1744 case Well::InjectorCMode::CMODE_UNDEFINED:
1746 OPM_DEFLOG_THROW(std::runtime_error,
"Well control must be specified for well " + this->name(), deferred_logger );
1756 ws.surface_rates[phasePos] = std::max(
Scalar{1.e-7}, ws.surface_rates[phasePos]);
1759 ws.bhp = controls.bhp_limit;
1765 const auto current = ws.production_cmode;
1766 const auto controls = this->productionControlsWithWeldraw(summaryState, ws);
1768 case Well::ProducerCMode::ORAT:
1770 const int oil_pos = FluidSystem::canonicalToActivePhaseIdx(FluidSystem::oilPhaseIdx);
1771 Scalar current_rate = -ws.surface_rates[oil_pos];
1774 if (current_rate > 0.0) {
1775 for (
int p = 0; p<np; ++p) {
1776 ws.surface_rates[p] *= controls.oil_rate/current_rate;
1779 const std::vector<Scalar> fractions = initialWellRateFractions(simulator, well_state);
1780 double control_fraction = fractions[oil_pos];
1781 if (control_fraction != 0.0) {
1782 for (
int p = 0; p<np; ++p) {
1783 ws.surface_rates[p] = - fractions[p] * controls.oil_rate/control_fraction;
1789 case Well::ProducerCMode::WRAT:
1791 const int water_pos = FluidSystem::canonicalToActivePhaseIdx(FluidSystem::waterPhaseIdx);
1792 Scalar current_rate = -ws.surface_rates[water_pos];
1795 if (current_rate > 0.0) {
1796 for (
int p = 0; p<np; ++p) {
1797 ws.surface_rates[p] *= controls.water_rate/current_rate;
1800 const std::vector<Scalar> fractions = initialWellRateFractions(simulator, well_state);
1801 const Scalar control_fraction = fractions[water_pos];
1802 if (control_fraction != 0.0) {
1803 for (
int p = 0; p<np; ++p) {
1804 ws.surface_rates[p] = - fractions[p] * controls.water_rate / control_fraction;
1810 case Well::ProducerCMode::GRAT:
1812 const int gas_pos = FluidSystem::canonicalToActivePhaseIdx(FluidSystem::gasPhaseIdx);
1813 Scalar current_rate = -ws.surface_rates[gas_pos];
1816 if (current_rate > 0.0) {
1817 for (
int p = 0; p<np; ++p) {
1818 ws.surface_rates[p] *= controls.gas_rate/current_rate;
1821 const std::vector<Scalar > fractions = initialWellRateFractions(simulator, well_state);
1822 const Scalar control_fraction = fractions[gas_pos];
1823 if (control_fraction != 0.0) {
1824 for (
int p = 0; p<np; ++p) {
1825 ws.surface_rates[p] = - fractions[p] * controls.gas_rate / control_fraction;
1833 case Well::ProducerCMode::LRAT:
1835 const int water_pos = FluidSystem::canonicalToActivePhaseIdx(FluidSystem::waterPhaseIdx);
1836 const int oil_pos = FluidSystem::canonicalToActivePhaseIdx(FluidSystem::oilPhaseIdx);
1837 Scalar current_rate = - ws.surface_rates[water_pos]
1838 - ws.surface_rates[oil_pos];
1841 if (current_rate > 0.0) {
1842 for (
int p = 0; p<np; ++p) {
1843 ws.surface_rates[p] *= controls.liquid_rate/current_rate;
1846 const std::vector<Scalar> fractions = initialWellRateFractions(simulator, well_state);
1847 const Scalar control_fraction = fractions[water_pos] + fractions[oil_pos];
1848 if (control_fraction != 0.0) {
1849 for (
int p = 0; p<np; ++p) {
1850 ws.surface_rates[p] = - fractions[p] * controls.liquid_rate / control_fraction;
1856 case Well::ProducerCMode::CRAT:
1859 fmt::format(
"CRAT control not supported, well {}", this->name()),
1862 case Well::ProducerCMode::RESV:
1864 std::vector<Scalar> convert_coeff(this->number_of_phases_, 1.0);
1865 this->rateConverter_.calcCoeff( 0, this->pvtRegionIdx_, ws.surface_rates, convert_coeff);
1866 Scalar total_res_rate = 0.0;
1867 for (
int p = 0; p<np; ++p) {
1868 total_res_rate -= ws.surface_rates[p] * convert_coeff[p];
1870 if (controls.prediction_mode) {
1873 if (total_res_rate > 0.0) {
1874 for (
int p = 0; p<np; ++p) {
1875 ws.surface_rates[p] *= controls.resv_rate/total_res_rate;
1878 const std::vector<Scalar> fractions = initialWellRateFractions(simulator, well_state);
1879 for (
int p = 0; p<np; ++p) {
1880 ws.surface_rates[p] = - fractions[p] * controls.resv_rate / convert_coeff[p];
1884 std::vector<Scalar> hrates(this->number_of_phases_,0.);
1885 if (FluidSystem::phaseIsActive(FluidSystem::waterPhaseIdx)) {
1886 const int phase_pos = FluidSystem::canonicalToActivePhaseIdx(FluidSystem::waterPhaseIdx);
1887 hrates[phase_pos] = controls.water_rate;
1889 if (FluidSystem::phaseIsActive(FluidSystem::oilPhaseIdx)) {
1890 const int phase_pos = FluidSystem::canonicalToActivePhaseIdx(FluidSystem::oilPhaseIdx);
1891 hrates[phase_pos] = controls.oil_rate;
1893 if (FluidSystem::phaseIsActive(FluidSystem::gasPhaseIdx)) {
1894 const int phase_pos = FluidSystem::canonicalToActivePhaseIdx(FluidSystem::gasPhaseIdx);
1895 hrates[phase_pos] = controls.gas_rate;
1897 std::vector<Scalar> hrates_resv(this->number_of_phases_,0.);
1898 this->rateConverter_.calcReservoirVoidageRates( 0, this->pvtRegionIdx_, hrates, hrates_resv);
1899 Scalar target = std::accumulate(hrates_resv.begin(), hrates_resv.end(), 0.0);
1902 if (total_res_rate > 0.0) {
1903 for (
int p = 0; p<np; ++p) {
1904 ws.surface_rates[p] *= target/total_res_rate;
1907 const std::vector<Scalar> fractions = initialWellRateFractions(simulator, well_state);
1908 for (
int p = 0; p<np; ++p) {
1909 ws.surface_rates[p] = - fractions[p] * target / convert_coeff[p];
1915 case Well::ProducerCMode::BHP:
1917 ws.bhp = controls.bhp_limit;
1919 for (
int p = 0; p<np; ++p) {
1920 total_rate -= ws.surface_rates[p];
1925 if (total_rate <= 0.0){
1926 for (
int p = 0; p<np; ++p) {
1927 ws.surface_rates[p] = -ws.well_potentials[p];
1932 case Well::ProducerCMode::THP:
1934 const bool update_success = updateWellStateWithTHPTargetProd(simulator, well_state, groupStateHelper);
1936 if (!update_success) {
1940 auto rates = ws.surface_rates;
1941 this->adaptRatesForVFP(rates);
1943 well_state, rates, well, summaryState, this->getRefDensity(), deferred_logger);
1945 ws.thp = this->getTHPConstraint(summaryState);
1949 const Scalar total_rate = -std::accumulate(rates.begin(), rates.end(), 0.0);
1950 if (total_rate <= 0.0) {
1951 for (
int p = 0; p < this->number_of_phases_; ++p) {
1952 ws.surface_rates[p] = -ws.well_potentials[p];
1958 case Well::ProducerCMode::GRUP:
1960 assert(well.isAvailableForGroupControl());
1961 this->updateGroupTargetFallbackFlag(well_state, deferred_logger);
1962 const auto& group = schedule.getGroup(well.groupName(), this->currentStep());
1963 const Scalar efficiencyFactor = well.getEfficiencyFactor() *
1964 well_state[well.name()].efficiency_scaling_factor;
1965 Scalar scale = this->getGroupProductionTargetRate(group,
1971 for (
int p = 0; p<np; ++p) {
1972 ws.surface_rates[p] *= scale;
1977 case Well::ProducerCMode::CMODE_UNDEFINED:
1980 OPM_DEFLOG_THROW(std::runtime_error,
"Well control must be specified for well " + this->name() , deferred_logger);
1986 ws.bhp = controls.bhp_limit;
1991 template<
typename TypeTag>
1997 const auto& well_state = groupStateHelper.
wellState();
1999 const bool isGroupControlled = this->wellUnderGroupControl(well_state.well(this->index_of_well_));
2000 if (!isGroupControlled) {
2002 const auto& summaryState = groupStateHelper.
summaryState();
2003 return this->wellUnderZeroRateTargetIndividual(summaryState, well_state);
2005 return this->wellUnderZeroGroupRateTarget(groupStateHelper, isGroupControlled);
2009 template <
typename TypeTag>
2012 const std::optional<bool> group_control)
const
2014 const auto& well_state = groupStateHelper.
wellState();
2016 const bool isGroupControlled = group_control.value_or(this->wellUnderGroupControl(well_state.well(this->index_of_well_)));
2017 if (isGroupControlled) {
2018 return this->zeroGroupRateTarget(groupStateHelper);
2023 template<
typename TypeTag>
2030 return this->wellIsStopped()
2031 || this->wellUnderZeroRateTarget(groupStateHelper);
2034 template<
typename TypeTag>
2035 std::vector<typename WellInterface<TypeTag>::Scalar>
2041 const int np = this->number_of_phases_;
2042 std::vector<Scalar> scaling_factor(np);
2043 const auto& ws = well_state.
well(this->index_of_well_);
2045 Scalar total_potentials = 0.0;
2046 for (
int p = 0; p<np; ++p) {
2047 total_potentials += ws.well_potentials[p];
2049 if (total_potentials > 0) {
2050 for (
int p = 0; p<np; ++p) {
2051 scaling_factor[p] = ws.well_potentials[p] / total_potentials;
2053 return scaling_factor;
2058 const int nperf = this->number_of_local_perforations_;
2059 for (
int perf = 0; perf < nperf; ++perf) {
2060 total_tw += this->well_index_[perf];
2062 total_tw = this->parallelWellInfo().communication().sum(total_tw);
2064 for (
int perf = 0; perf < nperf; ++perf) {
2065 const int cell_idx = this->well_cells_[perf];
2066 const auto& intQuants = simulator.model().intensiveQuantities(cell_idx, 0);
2067 const auto& fs = intQuants.fluidState();
2068 const Scalar well_tw_fraction = this->well_index_[perf] / total_tw;
2069 Scalar total_mobility = 0.0;
2070 for (
int p = 0; p < np; ++p) {
2071 const int canonical_phase_idx = FluidSystem::activeToCanonicalPhaseIdx(p);
2072 total_mobility += fs.invB(canonical_phase_idx).value() * intQuants.mobility(canonical_phase_idx).value();
2074 for (
int p = 0; p < np; ++p) {
2075 const int canonical_phase_idx = FluidSystem::activeToCanonicalPhaseIdx(p);
2076 scaling_factor[p] += well_tw_fraction * fs.invB(canonical_phase_idx).value() * intQuants.mobility(canonical_phase_idx).value() / total_mobility;
2079 return scaling_factor;
2084 template <
typename TypeTag>
2091 assert(this->isProducer());
2095 auto& ws = well_state.
well(this->index_of_well_);
2096 int nonzero_rate_index = -1;
2097 const Scalar floating_point_error_epsilon = 1e-14;
2098 for (
int p = 0; p < this->number_of_phases_; ++p) {
2099 if (std::abs(ws.surface_rates[p]) > floating_point_error_epsilon) {
2100 if (nonzero_rate_index == -1) {
2101 nonzero_rate_index = p;
2110 std::vector<Scalar> well_q_s(this->number_of_phases_, 0.0);
2111 bool rates_evaluated_at_1bar =
false;
2113 const auto& summary_state = simulator.vanguard().summaryState();
2114 const auto& prod_controls = this->well_ecl_.productionControls(summary_state);
2115 const double bhp_limit = std::max(prod_controls.bhp_limit, 1.0 * unit::barsa);
2116 this->computeWellRatesWithBhp(simulator, bhp_limit, well_q_s, deferred_logger);
2118 rates_evaluated_at_1bar = (bhp_limit < 1.1 * unit::barsa);
2120 if (std::ranges::any_of(well_q_s, [](
Scalar q) {
return q > 0.0; })) {
2122 if (!rates_evaluated_at_1bar) {
2123 this->computeWellRatesWithBhp(simulator, 1.0 * unit::barsa, well_q_s, deferred_logger);
2124 rates_evaluated_at_1bar =
true;
2127 for (
auto& q : well_q_s) {
2128 q = std::min(q,
Scalar{0.0});
2133 if (nonzero_rate_index == -1) {
2137 const Scalar factor = rates_evaluated_at_1bar ? 0.5 : 1.0;
2138 for (
int p = 0; p < this->number_of_phases_; ++p) {
2139 ws.surface_rates[p] = factor * well_q_s[p];
2148 const Scalar initial_nonzero_rate = ws.surface_rates[nonzero_rate_index];
2149 const Scalar computed_rate = well_q_s[nonzero_rate_index];
2150 if (std::abs(initial_nonzero_rate) < std::abs(computed_rate)) {
2152 const Scalar factor = initial_nonzero_rate / computed_rate;
2153 assert(factor < 1.0);
2154 for (
int p = 0; p < this->number_of_phases_; ++p) {
2156 if (p != nonzero_rate_index) {
2157 ws.surface_rates[p] = factor * well_q_s[p];
2166 for (
int p = 0; p < this->number_of_phases_; ++p) {
2167 ws.surface_rates[p] = well_q_s[p];
2171 template <
typename TypeTag>
2172 template<
class Value>
2175 getTw(std::vector<Value>& Tw,
2178 const Value& trans_mult,
2181 OPM_TIMEFUNCTION_LOCAL(Subsystem::Wells);
2184 if (
static_cast<std::size_t
>(perf) >= this->well_cells_.size()) {
2185 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!");
2191 if (!this->well_index_fracture_.empty()) {
2192 const auto frac_wi = this->well_index_fracture_[perf]
2193 .wellIndex(ws.
perf_data.pressure[perf]);
2194 if (frac_wi > 0.0) {
2195 for (
auto& tw : Tw) {
2201 if constexpr (! Indices::gasEnabled) {
2205 const auto& wdfac = this->well_ecl_.getWDFAC();
2207 if (! wdfac.useDFactor() || (this->well_index_[perf] == 0.0)) {
2211 const Scalar d = this->computeConnectionDFactor(perf, intQuants, ws);
2218 const auto& connection = this->well_ecl_.getConnections()[ws.
perf_data.ecl_index[perf]];
2219 const Scalar Kh = connection.Kh();
2220 const Scalar scaling = std::numbers::pi * Kh * connection.wpimult();
2221 const unsigned gas_comp_idx = FluidSystem::canonicalToActiveCompIdx(FluidSystem::gasCompIdx);
2224 const Scalar cell_pressure = getValue(intQuants.fluidState().pressure(FluidSystem::gasPhaseIdx));
2225 const Scalar drawdown = cell_pressure - connection_pressure;
2226 const Scalar invB = getValue(intQuants.fluidState().invB(FluidSystem::gasPhaseIdx));
2227 const Scalar mob_g = getValue(intQuants.mobility(FluidSystem::gasPhaseIdx)) * invB;
2229 const Scalar b = 2 * scaling / getValue(Tw[gas_comp_idx]);
2230 const Scalar c = -2 * scaling * mob_g * drawdown;
2232 Scalar consistent_Q = -1.0e20;
2234 const Scalar r2n = b*b + 4*a*c;
2236 const Scalar rn = std::sqrt(r2n);
2237 const Scalar xn1 = (b-rn)*0.5/a;
2241 const Scalar xn2 = (b+rn)*0.5/a;
2242 if (xn2 <= 0 && xn2 > consistent_Q) {
2248 const Scalar r2p = b*b - 4*a*c;
2250 const Scalar rp = std::sqrt(r2p);
2251 const Scalar xp1 = (rp-b)*0.5/a;
2252 if (xp1 > 0 && xp1 < consistent_Q) {
2255 const Scalar xp2 = -(rp+b)*0.5/a;
2256 if (xp2 > 0 && xp2 < consistent_Q) {
2260 Tw[gas_comp_idx] = 1.0 / (1.0 / (trans_mult * this->well_index_[perf]) + (consistent_Q/2 * d / scaling));
2263 template <
typename TypeTag>
2269 if (! this->well_ecl_.getWDFAC().useDFactor()) {
2273 auto& d_factor = ws.
perf_data.connection_d_factor;
2275 for (
int perf = 0; perf < this->number_of_local_perforations_; ++perf) {
2276 const int cell_idx = this->well_cells_[perf];
2277 const auto& intQuants = simulator.model().intensiveQuantities(cell_idx, 0);
2279 d_factor[perf] = this->computeConnectionDFactor(perf, intQuants, ws);
2283 template <
typename TypeTag>
2290 auto rhoGS = [regIdx = this->pvtRegionIdx()]() {
2291 return FluidSystem::referenceDensity(FluidSystem::gasPhaseIdx, regIdx);
2295 auto gas_visc = [connection_pressure = ws.
perf_data.pressure[perf],
2297 regIdx = this->pvtRegionIdx(), &intQuants]()
2299 const auto rv = getValue(intQuants.fluidState().Rv());
2301 const auto& gasPvt = FluidSystem::gasPvt();
2306 const Scalar rv_sat = gasPvt.saturatedOilVaporizationFactor
2307 (regIdx, temperature, connection_pressure);
2309 if (! (rv < rv_sat)) {
2310 return gasPvt.saturatedViscosity(regIdx, temperature,
2311 connection_pressure);
2314 return gasPvt.viscosity(regIdx, temperature, connection_pressure,
2315 rv, getValue(intQuants.fluidState().Rvw()));
2318 const auto& connection = this->well_ecl_.getConnections()
2321 return this->well_ecl_.getWDFAC().getDFactor(rhoGS, gas_visc, connection);
2325 template <
typename TypeTag>
2331 auto connCF = [&connIx = std::as_const(ws.
perf_data.ecl_index),
2332 &conns = this->well_ecl_.getConnections()]
2335 return conns[connIx[perf]].CF();
2338 auto obtain = [](
const Eval& value)
2340 return getValue(value);
2343 auto& tmult = ws.
perf_data.connection_compaction_tmult;
2344 auto& ctf = ws.
perf_data.connection_transmissibility_factor;
2346 for (
int perf = 0; perf < this->number_of_local_perforations_; ++perf) {
2347 const int cell_idx = this->well_cells_[perf];
2349 getTransMult(trans_mult, simulator, cell_idx, obtain);
2350 tmult[perf] = trans_mult;
2352 ctf[perf] = connCF(perf) * tmult[perf];
2357 template<
typename TypeTag>
2361 if constexpr (Indices::oilEnabled) {
2362 return fs.pressure(FluidSystem::oilPhaseIdx);
2363 }
else if constexpr (Indices::gasEnabled) {
2364 return fs.pressure(FluidSystem::gasPhaseIdx);
2366 return fs.pressure(FluidSystem::waterPhaseIdx);
2370 template <
typename TypeTag>
2371 template<
class Value,
class Callback>
2377 Callback& extendEval)
const
2379 const auto& intQuants = simulator.model().intensiveQuantities(cell_idx, 0);
2380 trans_mult = simulator.problem().template wellTransMultiplier<Value>(intQuants, cell_idx, extendEval);
2383 template <
typename TypeTag>
2384 template<
class Value,
class Callback>
2388 const int local_perf_index,
2389 std::vector<Value>& mob,
2390 Callback& extendEval,
2393 auto relpermArray = []()
2395 if constexpr (std::is_same_v<Value, Scalar>) {
2396 return std::array<Scalar,3>{};
2398 return std::array<Eval,3>{};
2401 if (
static_cast<std::size_t
>(local_perf_index) >= this->well_cells_.size()) {
2402 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!");
2404 const int cell_idx = this->well_cells_[local_perf_index];
2405 assert (
int(mob.size()) == this->num_conservation_quantities_);
2406 const auto& intQuants = simulator.model().intensiveQuantities(cell_idx, 0);
2407 const auto& materialLawManager = simulator.problem().materialLawManager();
2411 const int satid = this->saturation_table_number_[local_perf_index] - 1;
2412 const int satid_elem = materialLawManager.satnumRegionIdx(cell_idx);
2413 if (satid == satid_elem) {
2414 for (
unsigned phaseIdx = 0; phaseIdx < FluidSystem::numPhases; ++phaseIdx) {
2415 if (!FluidSystem::phaseIsActive(phaseIdx)) {
2419 const unsigned activeCompIdx = FluidSystem::canonicalToActiveCompIdx(FluidSystem::solventComponentIndex(phaseIdx));
2420 mob[activeCompIdx] = extendEval(intQuants.mobility(phaseIdx));
2422 if constexpr (has_solvent) {
2423 mob[Indices::contiSolventEqIdx] = extendEval(intQuants.solventMobility());
2426 const auto& paramsCell = materialLawManager.connectionMaterialLawParams(satid, cell_idx);
2427 auto relativePerms = relpermArray();
2428 MaterialLaw::relativePermeabilities(relativePerms, paramsCell, intQuants.fluidState());
2431 materialLawManager.connectionMaterialLawParams(satid_elem, cell_idx);
2434 for (
unsigned phaseIdx = 0; phaseIdx < FluidSystem::numPhases; ++phaseIdx) {
2435 if (!FluidSystem::phaseIsActive(phaseIdx)) {
2439 const unsigned activeCompIdx = FluidSystem::canonicalToActiveCompIdx(FluidSystem::solventComponentIndex(phaseIdx));
2440 mob[activeCompIdx] = extendEval(relativePerms[phaseIdx] / intQuants.fluidState().viscosity(phaseIdx));
2443 if constexpr (has_solvent) {
2444 const auto Fsolgas = intQuants.solventSaturation() / (intQuants.solventSaturation() + intQuants.fluidState().saturation(FluidSystem::gasPhaseIdx));
2446 if (Fsolgas > SolventModule::cutOff) {
2447 const unsigned activeGasCompIdx = FluidSystem::canonicalToActiveCompIdx(FluidSystem::solventComponentIndex(FluidSystem::gasPhaseIdx));
2448 const auto& ssfnKrg = SolventModule::ssfnKrg(satid);
2449 const auto& ssfnKrs = SolventModule::ssfnKrs(satid);
2450 mob[activeGasCompIdx] *= extendEval(ssfnKrg.eval(1-Fsolgas,
true));
2451 mob[Indices::contiSolventEqIdx] = extendEval(ssfnKrs.eval(Fsolgas,
true) * relativePerms[activeGasCompIdx] / intQuants.solventViscosity());
2456 if (this->isInjector() && !this->inj_fc_multiplier_.empty()) {
2457 const auto perf_ecl_index = this->perforationData()[local_perf_index].ecl_index;
2458 const auto& connections = this->well_ecl_.getConnections();
2459 const auto& connection = connections[perf_ecl_index];
2460 if (connection.filterCakeActive()) {
2461 std::ranges::transform(mob, mob.begin(),
2462 [mult = this->inj_fc_multiplier_[local_perf_index]]
2464 { return val * mult; });
2470 template<
typename TypeTag>
2479 const auto& summary_state = simulator.vanguard().summaryState();
2481 auto bhp_at_thp_limit = computeBhpAtThpLimitProdWithAlq(
2482 simulator, groupStateHelper, summary_state, this->getALQ(well_state),
false);
2483 if (bhp_at_thp_limit) {
2484 std::vector<Scalar> rates(this->number_of_phases_, 0.0);
2485 if (thp_update_iterations) {
2486 computeWellRatesWithBhpIterations(simulator, *bhp_at_thp_limit,
2487 groupStateHelper, rates);
2489 computeWellRatesWithBhp(simulator, *bhp_at_thp_limit,
2490 rates, deferred_logger);
2492 auto& ws = well_state.
well(this->name());
2493 ws.surface_rates = rates;
2494 ws.bhp = *bhp_at_thp_limit;
2495 ws.thp = this->getTHPConstraint(summary_state);
2502 template<
typename TypeTag>
2503 std::optional<typename WellInterface<TypeTag>::Scalar>
2508 const SummaryState& summary_state,
2513 const auto& groupStateHelper = simulator.problem().wellModel().groupStateHelper();
2515 auto well_guard = groupStateHelper_copy.
pushWellState(well_state_copy);
2516 const double dt = simulator.timeStepSize();
2517 const bool converged = this->solveWellWithBhp(
2518 simulator, dt, bhp, groupStateHelper_copy, well_state_copy
2522 auto rates = well_state_copy.
well(this->index_of_well_).surface_rates;
2524 for (std::size_t p = 0; p < rates.size(); ++p) {
2525 zero_rates &= rates[p] == 0.0;
2529 if (zero_rates || !converged) {
2530 return this->computeBhpAtThpLimitProdWithAlq(simulator, groupStateHelper_copy, summary_state, alq_value,
false);
2532 this->updateIPRImplicit(simulator, groupStateHelper_copy, well_state_copy);
2533 this->adaptRatesForVFP(rates);
2537 template <
typename TypeTag>
2542 const std::vector<Scalar>& mobility,
2545 const int np = this->number_of_phases_;
2546 for (
int p = 0; p < np; ++p) {
2549 const int canonical_phase_idx = FluidSystem::activeToCanonicalPhaseIdx(p);
2550 const auto connMob =
2551 mobility[FluidSystem::activePhaseToActiveCompIdx(p)] * fs.invB(canonical_phase_idx).value();
2553 connPI[p] = connPICalc(connMob);
2556 if (FluidSystem::phaseIsActive(FluidSystem::oilPhaseIdx) &&
2557 FluidSystem::phaseIsActive(FluidSystem::gasPhaseIdx))
2559 const auto io = FluidSystem::canonicalToActivePhaseIdx(FluidSystem::oilPhaseIdx);
2560 const auto ig = FluidSystem::canonicalToActivePhaseIdx(FluidSystem::gasPhaseIdx);
2562 const auto vapoil = connPI[ig] * fs.Rv().value();
2563 const auto disgas = connPI[io] * fs.Rs().value();
2565 connPI[io] += vapoil;
2566 connPI[ig] += disgas;
2571 template <
typename TypeTag>
2575 const Phase preferred_phase,
2577 const std::vector<Scalar>& mobility,
2582 if (preferred_phase == Phase::GAS) {
2583 phase_pos = FluidSystem::canonicalToActivePhaseIdx(FluidSystem::gasPhaseIdx);
2585 else if (preferred_phase == Phase::OIL) {
2586 phase_pos = FluidSystem::canonicalToActivePhaseIdx(FluidSystem::oilPhaseIdx);
2588 else if (preferred_phase == Phase::WATER) {
2589 phase_pos = FluidSystem::canonicalToActivePhaseIdx(FluidSystem::waterPhaseIdx);
2593 fmt::format(
"Unsupported Injector Type ({}) "
2594 "for well {} during connection I.I. calculation",
2595 static_cast<int>(preferred_phase), this->name()),
2599 const auto mt = std::accumulate(mobility.begin(), mobility.end(), 0.0);
2600 const int canonicalPhaseIdx = FluidSystem::activeToCanonicalPhaseIdx(phase_pos);
2601 connII[phase_pos] = connIICalc(mt * fs.invB(canonicalPhaseIdx).value());
2604 template<
typename TypeTag>
2605 template<
class GasLiftSingleWell>
2606 std::unique_ptr<GasLiftSingleWell>
2615 auto& comm = simulator.vanguard().grid().comm();
2616 ecl_well_map.try_emplace(this->name(), &(this->wellEcl()), this->indexOfWell());
2617 const auto& iterCtx = simulator.problem().iterationContext();
2620 simulator.vanguard().schedule(),
2621 simulator.vanguard().summaryState(),
2622 simulator.episodeIndex(),
2629 simulator.problem().wellModel().groupStateHelper()
2633 std::set<int> sync_groups;
2634 const auto& summary_state = simulator.vanguard().summaryState();
2635 return std::make_unique<GasLiftSingleWell>(*
this,
2649 template <
typename TypeTag>
2656 if (this->well_cells_.size() > 0) {
2660 const int cell_idx = this->well_cells_[0];
2661 const auto& intQuants = simulator.model().intensiveQuantities(cell_idx, 0);
2662 const auto& fs = intQuants.fluidState();
2664 info.
temperature = getValue(fs.temperature(FluidSystem::oilPhaseIdx));
2665 info.saltConcentration = getValue(fs.saltConcentration());
2671 return this->parallel_well_info_.communication().size() == 1
2673 : 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:478
int number_of_local_perforations_
Definition: WellInterfaceGeneric.hpp:520
FluidSystem::Scalar wsolvent_
Definition: WellInterfaceGeneric.hpp:560
Definition: WellInterfaceIndices.hpp:34
bool stoppedOrZeroRateTarget(const GroupStateHelperType &groupStateHelper) const
Definition: WellInterface_impl.hpp:2026
bool updateWellOperabilityFromWellEq(const Simulator &simulator, const GroupStateHelperType &groupStateHelper)
Definition: WellInterface_impl.hpp:1582
void checkWellOperability(const Simulator &simulator, const WellStateType &well_state, const GroupStateHelperType &groupStateHelper)
Definition: WellInterface_impl.hpp:1454
void updateWellOperability(const Simulator &simulator, const WellStateType &well_state, const GroupStateHelperType &groupStateHelper)
Definition: WellInterface_impl.hpp:1544
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:878
Scalar woxygen() const
Definition: WellInterface_impl.hpp:169
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:1251
Scalar computeConnectionDFactor(const int perf, const IntensiveQuantities &intQuants, const SingleWellStateType &ws) const
Definition: WellInterface_impl.hpp:2286
void updateWeldrawMaxRate(const Simulator &simulator, WellStateType &well_state, DeferredLogger &deferred_logger) const
Definition: WellInterface_impl.hpp:291
typename WellInterfaceFluidSystem< FluidSystem >::RateConverterType RateConverterType
Definition: WellInterface.hpp:110
Scalar wfoam() const
Definition: WellInterface_impl.hpp:131
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:383
void getTransMult(Value &trans_mult, const Simulator &simulator, const int cell_idx, Callback &extendEval) const
Definition: WellInterface_impl.hpp:2374
std::vector< RateVector > connectionRates_
Definition: WellInterface.hpp:436
bool solveWellForTesting(const Simulator &simulator, const GroupStateHelperType &groupStateHelper, WellStateType &well_state)
Definition: WellInterface_impl.hpp:1117
void computeConnLevelProdInd(const FluidState &fs, const std::function< Scalar(const Scalar)> &connPICalc, const std::vector< Scalar > &mobility, Scalar *connPI) const
Definition: WellInterface_impl.hpp:2540
void gliftBeginTimeStepWellTestUpdateALQ(const Simulator &simulator, WellStateType &well_state, const GroupState< Scalar > &group_state, GLiftEclWells &ecl_well_map, DeferredLogger &deferred_logger)
Definition: WellInterface_impl.hpp:1482
Scalar volumetricSurfaceRateForConnection(int cellIdx, int phaseIdx) const
Definition: WellInterface_impl.hpp:1434
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:99
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:2505
void getTw(std::vector< Value > &wi, const int perf, const IntensiveQuantities &intQuants, const Value &trans_mult, const SingleWellStateType &ws) const
Definition: WellInterface_impl.hpp:2175
void getMobility(const Simulator &simulator, const int local_perf_index, std::vector< Value > &mob, Callback &extendEval, DeferredLogger &deferred_logger) const
Definition: WellInterface_impl.hpp:2387
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:2037
void solveWellEquation(const Simulator &simulator, const GroupStateHelperType &groupStateHelper, WellStateType &well_state)
Definition: WellInterface_impl.hpp:1173
void updateConnectionDFactor(const Simulator &simulator, SingleWellStateType &ws) const
Definition: WellInterface_impl.hpp:2266
Eval getPerfCellPressure(const FluidState &fs) const
Definition: WellInterface_impl.hpp:2359
void initializeProducerWellState(const Simulator &simulator, WellStateType &well_state, DeferredLogger &deferred_logger) const
Definition: WellInterface_impl.hpp:2087
virtual void updateWellStateWithTarget(const Simulator &simulator, const GroupStateHelperType &groupStateHelper, WellStateType &well_state) const
Definition: WellInterface_impl.hpp:1612
void addCellRates(std::map< int, RateVector > &cellRates_) const
Definition: WellInterface_impl.hpp:1415
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:1994
GetPropType< TypeTag, Properties::RateVector > RateVector
Definition: WellInterface.hpp:92
void updateConnectionTransmissibilityFactor(const Simulator &simulator, SingleWellStateType &ws) const
Definition: WellInterface_impl.hpp:2328
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:2574
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:2608
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:998
Scalar wsalt() const
Definition: WellInterface_impl.hpp:145
bool solveWellWithZeroRate(const Simulator &simulator, const double dt, const GroupStateHelperType &groupStateHelper, WellStateType &well_state)
Definition: WellInterface_impl.hpp:1085
bool wellUnderZeroGroupRateTarget(const GroupStateHelperType &groupStateHelper, const std::optional< bool > group_control=std::nullopt) const
Definition: WellInterface_impl.hpp:2011
bool solveWellWithBhp(const Simulator &simulator, const double dt, const Scalar bhp, const GroupStateHelperType &groupStateHelper, WellStateType &well_state)
Definition: WellInterface_impl.hpp:1035
void prepareWellBeforeAssembling(const Simulator &simulator, const double dt, const GroupStateHelperType &groupStateHelper, WellStateType &well_state)
Definition: WellInterface_impl.hpp:1288
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:502
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:62
bool updateWellStateWithTHPTargetProd(const Simulator &simulator, WellStateType &well_state, const GroupStateHelperType &groupStateHelper) const
Definition: WellInterface_impl.hpp:2473
bool iterateWellEquations(const Simulator &simulator, const double dt, const GroupStateHelperType &groupStateHelper, WellStateType &well_state)
Definition: WellInterface_impl.hpp:659
Scalar wpolymer() const
Definition: WellInterface_impl.hpp:115
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:193
Scalar wurea() const
Definition: WellInterface_impl.hpp:181
void updateGroupTargetFallbackFlag(WellStateType &well_state, DeferredLogger &deferred_logger) const
Definition: WellInterface_impl.hpp:1273
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:2651
void assembleWellEq(const Simulator &simulator, const double dt, const GroupStateHelperType &groupStateHelper, WellStateType &well_state)
Definition: WellInterface_impl.hpp:1235
Scalar wmicrobes() const
Definition: WellInterface_impl.hpp:157
virtual void scaleSegmentRatesAndPressure(WellStateType &well_state) const
Definition: WellInterface_impl.hpp:1604
static constexpr bool has_zFraction
Definition: WellInterface.hpp:119
void consolidatePhaseMixingRates(WellStateType &well_state) const
Definition: WellInterface_impl.hpp:760
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
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