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>
53#include <fmt/format.h>
59 template<
typename TypeTag>
66 const int pvtRegionIdx,
67 const int num_conservation_quantities,
69 const int index_of_well,
77 num_conservation_quantities,
85 if (well.isInjector()) {
86 auto injectorType = this->
well_ecl_.injectorType();
87 if (injectorType == InjectorType::GAS) {
95 template<
typename TypeTag>
98 init(
const std::vector<Scalar>& ,
100 const std::vector<Scalar>& B_avg,
101 const bool changed_to_open_this_step)
103 this->gravity_ = gravity_arg;
105 this->changed_to_open_this_step_ = changed_to_open_this_step;
111 template<
typename TypeTag>
116 if constexpr (has_polymer) {
117 return this->wpolymer_();
127 template<
typename TypeTag>
132 if constexpr (has_foam) {
133 return this->wfoam_();
141 template<
typename TypeTag>
146 if constexpr (has_brine) {
147 return this->wsalt_();
153 template<
typename TypeTag>
158 if constexpr (has_micp) {
159 return this->wmicrobes_();
165 template<
typename TypeTag>
170 if constexpr (has_micp) {
171 return this->woxygen_();
177 template<
typename TypeTag>
182 if constexpr (has_micp) {
183 return this->wurea_();
189 template<
typename TypeTag>
199 if (stoppedOrZeroRateTarget(groupStateHelper)) {
203 const auto& summaryState = simulator.vanguard().summaryState();
204 const auto& schedule = simulator.vanguard().schedule();
205 const auto& well = this->well_ecl_;
206 auto& ws = well_state.
well(this->index_of_well_);
208 bool is_grup =
false;
209 if (well.isInjector()) {
210 from = WellInjectorCMode2String(ws.injection_cmode);
211 is_grup = ws.injection_cmode == Well::InjectorCMode::GRUP;
213 from = WellProducerCMode2String(ws.production_cmode);
214 is_grup = ws.production_cmode == Well::ProducerCMode::GRUP;
217 const int episodeIdx = simulator.episodeIndex();
218 const auto& iterCtx = simulator.problem().iterationContext();
219 const int nupcol = schedule[episodeIdx].nupcol();
220 const bool oscillating =
221 std::ranges::count(this->well_control_log_, from) >= this->param_.max_number_of_well_switches_;
222 if (oscillating && !is_grup) {
225 std::ranges::count(this->well_control_log_, from) == this->param_.max_number_of_well_switches_;
227 const auto msg = fmt::format(
" The control mode for well {} is oscillating. \n"
228 "We don't allow for more than {} switches after NUPCOL iterations. (NUPCOL = {}) \n"
229 "The control is kept at {}.",
230 this->name(), this->param_.max_number_of_well_switches_, nupcol, from);
231 deferred_logger.info(msg);
233 this->well_control_log_.push_back(from);
237 bool changed =
false;
238 if (iog == IndividualOrGroup::Individual) {
239 changed = this->checkIndividualConstraints(ws, summaryState, deferred_logger);
240 }
else if (iog == IndividualOrGroup::Group) {
241 changed = this->checkGroupConstraints(
242 groupStateHelper, schedule, summaryState,
true, well_state
245 assert(iog == IndividualOrGroup::Both);
246 changed = this->checkConstraints(groupStateHelper, schedule, summaryState, well_state);
252 if (well.isInjector()) {
253 to = WellInjectorCMode2String(ws.injection_cmode);
255 to = WellProducerCMode2String(ws.production_cmode);
257 std::ostringstream ss;
258 ss <<
" Switching control mode for well " << this->name()
261 if (iterCtx.inLocalSolve()) {
262 ss <<
" (NLDD domain solve)";
265 ss <<
" on rank " << cc.rank();
267 deferred_logger.debug(ss.str());
274 if (!iterCtx.inLocalSolve()) {
275 if (!iterCtx.withinNupcol(nupcol) || this->log_all_control_switches_
276 || this->well_control_log_.empty()) {
277 this->well_control_log_.push_back(from);
280 updateWellStateWithTarget(simulator, groupStateHelper, well_state);
281 updatePrimaryVariables(groupStateHelper);
287 template<
typename TypeTag>
294 if (!this->isProducer()) {
298 auto& ws = well_state.
well(this->index_of_well_);
299 const auto& weldraw = this->well_ecl_.getWELDRAW();
300 if (!weldraw.active()) {
301 ws.weldraw_max_rate.reset();
302 ws.weldraw_cmode.reset();
306 const auto& summary_state = simulator.vanguard().summaryState();
307 const Scalar max_draw = this->well_ecl_.weldrawMaxDrawdown(summary_state);
308 if (!(max_draw > 0.0)) {
309 ws.weldraw_max_rate.reset();
310 ws.weldraw_cmode.reset();
321 this->updateIPR(simulator, deferred_logger);
323 auto phase_coeff = [
this](
const unsigned phase_idx) ->
Scalar {
324 const unsigned comp_idx = FluidSystem::canonicalToActiveCompIdx(
325 FluidSystem::solventComponentIndex(phase_idx));
326 return this->ipr_b_[comp_idx];
330 const bool gas_target = (weldraw.targetPhase() == WELDRAW::TargetPhase::GAS);
332 if (FluidSystem::phaseIsActive(FluidSystem::gasPhaseIdx)) {
333 coeff += phase_coeff(FluidSystem::gasPhaseIdx);
337 if (FluidSystem::phaseIsActive(FluidSystem::oilPhaseIdx)) {
338 coeff += phase_coeff(FluidSystem::oilPhaseIdx);
340 if (FluidSystem::phaseIsActive(FluidSystem::waterPhaseIdx)) {
341 coeff += phase_coeff(FluidSystem::waterPhaseIdx);
345 if (!(coeff > 0.0)) {
351 deferred_logger.
warning(
"WELDRAW_NO_TARGET_PHASE_MOBILITY",
352 fmt::format(
"Well {}: the WELDRAW target phase ({}) has no "
353 "producible mobility; the drawdown limit is ignored.",
354 this->name(), gas_target ?
"GAS" :
"LIQ"));
355 ws.weldraw_max_rate.reset();
356 ws.weldraw_cmode.reset();
360 const Scalar max_rate = max_draw * coeff;
361 ws.weldraw_max_rate = max_rate;
366 const auto controls = this->well_ecl_.productionControls(summary_state);
367 const auto cmode = gas_target ? Well::ProducerCMode::GRAT
368 : Well::ProducerCMode::LRAT;
369 const Scalar own_target = gas_target ? controls.gas_rate
370 : controls.liquid_rate;
371 if (!controls.hasControl(cmode) || (max_rate <= own_target)) {
372 ws.weldraw_cmode = cmode;
375 ws.weldraw_cmode.reset();
379 template<
typename TypeTag>
384 const Well::InjectionControls& inj_controls,
385 const Well::ProductionControls& prod_controls,
388 const bool fixed_control,
389 const bool fixed_status,
390 const bool solving_with_zero_rate)
394 const auto& summary_state = simulator.vanguard().summaryState();
395 const auto& schedule = simulator.vanguard().schedule();
396 auto& ws = well_state.
well(this->index_of_well_);
398 if (this->isInjector()) {
399 from = WellInjectorCMode2String(ws.injection_cmode);
401 from = WellProducerCMode2String(ws.production_cmode);
403 const bool oscillating =
404 std::ranges::count(this->well_control_log_, from) >= this->param_.max_number_of_well_switches_;
406 if (oscillating || this->wellUnderZeroRateTarget(groupStateHelper) || !(well_state.
well(this->index_of_well_).status == WellStatus::OPEN)) {
410 const Scalar sgn = this->isInjector() ? 1.0 : -1.0;
411 if (!this->wellIsStopped()){
412 if (wqTotal*sgn <= 0.0 && !fixed_status){
416 bool changed =
false;
417 if (!fixed_control) {
420 if (solving_with_zero_rate) {
422 "Well {}: solving_with_zero_rate should not be true when fixed_control is false",
423 this->name()), deferred_logger);
429 const bool hasGroupControl = this->isInjector() ? inj_controls.hasControl(Well::InjectorCMode::GRUP) :
430 prod_controls.hasControl(Well::ProducerCMode::GRUP);
431 bool isGroupControl = ws.production_cmode == Well::ProducerCMode::GRUP || ws.injection_cmode == Well::InjectorCMode::GRUP;
432 if (! (isGroupControl && !this->param_.check_group_constraints_inner_well_iterations_)) {
433 changed = this->checkIndividualConstraints(ws, summary_state, deferred_logger, inj_controls, prod_controls);
435 if (hasGroupControl && this->param_.check_group_constraints_inner_well_iterations_) {
436 changed = changed || this->checkGroupConstraints(
437 groupStateHelper, schedule, summary_state,
false, well_state
442 const bool thp_controlled = this->isInjector() ? ws.injection_cmode == Well::InjectorCMode::THP :
443 ws.production_cmode == Well::ProducerCMode::THP;
445 ws.thp = this->getTHPConstraint(summary_state);
448 updateWellStateWithTarget(simulator, groupStateHelper, well_state);
450 updatePrimaryVariables(groupStateHelper);
455 }
else if (!fixed_status){
457 const Scalar bhp = well_state.
well(this->index_of_well_).bhp;
458 Scalar prod_limit = prod_controls.bhp_limit;
459 Scalar inj_limit = inj_controls.bhp_limit;
460 const bool has_thp = this->wellHasTHPConstraints(summary_state);
462 std::vector<Scalar> rates(this->num_conservation_quantities_);
463 if (this->isInjector()){
465 calculateBhpFromThp(well_state, rates,
468 this->getRefDensity(),
470 inj_limit = std::min(bhp_thp,
static_cast<Scalar>(inj_controls.bhp_limit));
475 calculateMinimumBhpFromThp(well_state,
478 this->getRefDensity());
479 prod_limit = std::max(bhp_min,
static_cast<Scalar>(prod_controls.bhp_limit));
482 const Scalar bhp_diff = (this->isInjector())? inj_limit - bhp: bhp - prod_limit;
485 well_state.
well(this->index_of_well_).bhp = (this->isInjector())? inj_limit : prod_limit;
487 well_state.
well(this->index_of_well_).thp = this->getTHPConstraint(summary_state);
498 template<
typename TypeTag>
502 const double simulation_time,
505 WellTestState& well_test_state,
507 std::map<std::string, double>& open_times)
511 const auto& group_state = groupStateHelper.
groupState();
515 const auto& unit_system = simulator.vanguard().eclState().getUnits();
516 const auto start_time = simulator.vanguard().schedule().getStartTime();
518 fmt::format(
"at time {:.2f} {} (date = {})",
519 unit_system.from_si(UnitSystem::measure::time, simulation_time),
520 unit_system.name(UnitSystem::measure::time),
523 deferred_logger.info(fmt::format(
"Well {} is being tested {}.", this->name(), when));
530 auto guard = groupStateHelper_copy.
pushWellState(well_state_copy);
531 auto& ws = well_state_copy.
well(this->indexOfWell());
533 const auto& summary_state = simulator.vanguard().summaryState();
534 const bool has_thp_limit = this->wellHasTHPConstraints(summary_state);
535 if (this->isProducer()) {
536 ws.production_cmode = has_thp_limit ? Well::ProducerCMode::THP : Well::ProducerCMode::BHP;
538 ws.injection_cmode = has_thp_limit ? Well::InjectorCMode::THP : Well::InjectorCMode::BHP;
543 scaleSegmentRatesAndPressure(well_state_copy);
544 calculateExplicitQuantities(simulator, groupStateHelper_copy);
545 updatePrimaryVariables(groupStateHelper_copy);
547 if (this->isProducer()) {
548 const auto& schedule = simulator.vanguard().schedule();
549 const auto report_step = simulator.episodeIndex();
550 const auto& glo = schedule.glo(report_step);
552 gliftBeginTimeStepWellTestUpdateALQ(simulator,
560 WellTestState welltest_state_temp;
562 std::string closure_reason;
568 auto notReopened = [
this, &when, &deferred_logger](
const std::string_view reason)
570 deferred_logger.info(
571 fmt::format(
"Well {} is not re-opened {}.", this->name(), when));
572 if (!reason.empty()) {
573 deferred_logger.debug(fmt::format(
"Because {}.", reason));
577 bool testWell =
true;
582 const std::size_t original_number_closed_completions = welltest_state_temp.num_closed_completions();
583 bool converged = solveWellForTesting(simulator, groupStateHelper_copy, well_state_copy);
585 notReopened(
"the well equations could not be solved");
590 updateWellOperability(simulator, well_state_copy, groupStateHelper_copy);
591 if ( !this->isOperableAndSolvable() ) {
592 notReopened(
"the well is not operable");
595 std::vector<Scalar> potentials;
597 computeWellPotentials(simulator, well_state_copy, groupStateHelper_copy, potentials);
598 }
catch (
const std::exception& e) {
599 notReopened(fmt::format(
"computing the well potentials failed: {}", e.what()));
602 const int np = well_state_copy.
numPhases();
603 for (
int p = 0; p < np; ++p) {
604 ws.well_potentials[p] = std::max(
Scalar{0.0}, potentials[p]);
606 const bool under_zero_target = this->wellUnderZeroGroupRateTarget(groupStateHelper_copy);
607 this->updateWellTestState(well_state_copy.
well(this->indexOfWell()),
613 simulator.vanguard().eclState().getUnits(),
614 simulator.vanguard().schedule().getStartTime(),
617 this->closeCompletions(welltest_state_temp);
623 if ( welltest_state_temp.num_closed_wells() > 0 ||
624 (original_number_closed_completions == welltest_state_temp.num_closed_completions()) ) {
630 if (!welltest_state_temp.well_is_closed(this->name())) {
631 well_test_state.open_well(this->name());
634 deferred_logger.info(
635 fmt::format(
"{}\nWell {} is re-opened {}.\n{}",
636 sep, this->name(), when, sep));
639 for (
const auto& completion : this->well_ecl_.getCompletions()) {
640 if (!welltest_state_temp.completion_is_closed(this->name(), completion.first))
641 well_test_state.open_completion(this->name(), completion.first);
643 well_state = well_state_copy;
644 open_times.try_emplace(this->name(), well_test_state.lastTestTime(this->name()));
648 notReopened(closure_reason);
655 template<
typename TypeTag>
666 const auto& summary_state = simulator.vanguard().summaryState();
667 const auto& ws = well_state.
well(this->indexOfWell());
668 const auto inj_controls = this->well_ecl_.isInjector() ? this->well_ecl_.injectionControls(summary_state) : Well::InjectionControls(0);
669 const auto prod_controls = this->well_ecl_.isProducer() ? this->productionControlsWithWeldraw(summary_state, ws) : Well::ProductionControls(0);
670 const auto pmode_orig = ws.production_cmode;
671 const auto imode_orig = ws.injection_cmode;
672 bool converged =
false;
675 if (!this->param_.local_well_solver_control_switching_){
676 converged = this->iterateWellEqWithControl(simulator, dt, inj_controls, prod_controls, groupStateHelper, well_state);
678 if (this->param_.use_implicit_ipr_ && this->well_ecl_.isProducer() && (well_state.
well(this->index_of_well_).status == WellStatus::OPEN)) {
679 converged = solveWellWithOperabilityCheck(
680 simulator, dt, inj_controls, prod_controls, groupStateHelper, well_state
683 converged = this->iterateWellEqWithSwitching(
684 simulator, dt, inj_controls, prod_controls, groupStateHelper, well_state,
690 }
catch (NumericalProblem& e ) {
691 const std::string msg =
"Inner well iterations failed for well " + this->name() +
" Treat the well as unconverged. ";
692 deferred_logger.warning(
"INNER_ITERATION_FAILED", msg);
697 if (ws.production_cmode != pmode_orig || ws.injection_cmode != imode_orig) {
699 if (this->isInjector()) {
700 from = WellInjectorCMode2String(imode_orig);
701 to = WellInjectorCMode2String(ws.injection_cmode);
703 from = WellProducerCMode2String(pmode_orig);
704 to = WellProducerCMode2String(ws.production_cmode);
706 const auto msg = fmt::format(
" Well {} switched from {} to {} during local solve", this->name(), from, to);
707 deferred_logger.debug(msg);
708 const int episodeIdx = simulator.episodeIndex();
709 const auto& iterCtx = simulator.problem().iterationContext();
710 const auto& schedule = simulator.vanguard().schedule();
711 const int nupcol = schedule[episodeIdx].nupcol();
715 if (!iterCtx.withinNupcol(nupcol) || this->log_all_control_switches_
716 || this->well_control_log_.empty()) {
717 this->well_control_log_.push_back(from);
722 if (this->isProducer() && ws.production_cmode == Well::ProducerCMode::GRUP && ws.use_group_target_fallback) {
723 assert(ws.group_target && ws.group_target_fallback);
724 const std::string cmode = Group::ProductionCMode2String(ws.group_target->production_cmode);
725 const std::string cmode_fallback = Group::ProductionCMode2String(ws.group_target_fallback->production_cmode);
726 const auto msg = fmt::format(
" Well {} was solved using group target fallback mode {} as current group mode {} was not feasible.",
727 this->name(), cmode_fallback, cmode);
728 deferred_logger.debug(msg);
734 template<
typename TypeTag>
739 auto& ws = well_state.
well(this->index_of_well_);
740 ws.rs_rep = ws.rv_rep = ws.rsw_rep = ws.rvw_rep = 0.0;
741 if (!this->isProducer()) {
745 const bool waterActive = FluidSystem::phaseIsActive(FluidSystem::waterPhaseIdx);
746 const bool oilActive = FluidSystem::phaseIsActive(FluidSystem::oilPhaseIdx);
747 const bool gasActive = FluidSystem::phaseIsActive(FluidSystem::gasPhaseIdx);
748 if (!gasActive || (!oilActive && !waterActive)) {
753 const int waterPos = waterActive ? FluidSystem::canonicalToActivePhaseIdx(FluidSystem::waterPhaseIdx) : -1;
754 const int oilPos = oilActive ? FluidSystem::canonicalToActivePhaseIdx(FluidSystem::oilPhaseIdx) : -1;
755 const int gasPos = FluidSystem::canonicalToActivePhaseIdx(FluidSystem::gasPhaseIdx);
759 const int numPhases = this->numPhases();
760 constexpr std::size_t numMixingRates = 4;
761 std::vector<Scalar> sums(numPhases + numMixingRates, 0.0);
762 const auto& perf_rates = ws.perf_data.phase_rates;
763 const auto& perf_mixing = ws.perf_data.phase_mixing_rates;
764 for (
int perf = 0; perf < this->numLocalPerfs(); ++perf) {
765 for (
int phase = 0; phase < numPhases; ++phase) {
766 sums[phase] += perf_rates[perf * numPhases + phase];
768 for (std::size_t mix = 0; mix < numMixingRates; ++mix) {
769 sums[numPhases + mix] += perf_mixing[perf][mix];
772 this->parallelWellInfo().communication().sum(sums.data(), sums.size());
774 const Scalar dis_gas = sums[numPhases + ws.dissolved_gas];
775 const Scalar dis_gas_water = sums[numPhases + ws.dissolved_gas_in_water];
776 const Scalar vap_oil = sums[numPhases + ws.vaporized_oil];
777 const Scalar vap_water = sums[numPhases + ws.vaporized_water];
781 const Scalar free_oil = oilActive ? sums[oilPos] - vap_oil : 0.0;
782 const Scalar free_water = waterActive ? sums[waterPos] - vap_water : 0.0;
783 const Scalar free_gas = sums[gasPos] - dis_gas - dis_gas_water;
784 const auto ratio = [](
const Scalar num,
const Scalar den) {
785 return (den != 0.0) ? num / den :
Scalar{0.0};
791 const Scalar surface_gas = std::abs(ws.surface_rates[gasPos]);
792 const Scalar solvent = has_solvent ? std::abs(ws.sum_solvent_rates()) :
Scalar{0.0};
793 const Scalar hydrocarbon_gas = std::max(surface_gas - solvent,
Scalar{0.0});
801 Scalar rvw = waterActive ? ratio(vap_water, free_gas) :
Scalar{0.0};
804 if (waterActive && FluidSystem::enableVaporizedWater()) {
805 const Scalar qw = std::abs(ws.surface_rates[waterPos]);
806 const Scalar qg = hydrocarbon_gas;
807 const Scalar rvw_max = FluidSystem::gasPvt()
808 .saturatedWaterVaporizationFactor(this->pvtRegionIdx(), ws.temperature, ws.bhp);
809 rvw = (qg > 0.0) ? std::min(qw / qg, rvw_max) :
Scalar{0.0};
814 const Scalar rs = ratio(dis_gas, free_oil);
815 const Scalar rv = ratio(vap_oil, free_gas);
816 if (rs >= 0.0 && rv >= 0.0 && rs * rv < 1.0) {
823 const Scalar qo = std::abs(ws.surface_rates[oilPos]);
824 const Scalar qg = hydrocarbon_gas;
825 const int pvtReg = this->pvtRegionIdx();
828 const Scalar rs_max = FluidSystem::enableDissolvedGas()
829 ? FluidSystem::oilPvt().saturatedGasDissolutionFactor(pvtReg, ws.temperature, ws.bhp)
831 const Scalar rv_max = FluidSystem::enableVaporizedOil()
832 ? FluidSystem::gasPvt().saturatedOilVaporizationFactor(pvtReg, ws.temperature, ws.bhp)
834 const Scalar rs_inf = (qo > 0.0) ? std::min(qg / qo, rs_max) :
Scalar{0.0};
835 const Scalar rv_inf = (qg > 0.0) ? std::min(qo / qg, rv_max) :
Scalar{0.0};
836 if (rs_inf * rv_inf < 1.0) {
846 const Scalar rsw = std::max(ratio(dis_gas_water, free_water),
Scalar{0.0});
848 ws.rvw_rep = (rsw * rvw < 1.0) ? rvw :
Scalar{0.0};
852 template<
typename TypeTag>
857 const Well::InjectionControls& inj_controls,
858 const Well::ProductionControls& prod_controls,
865 const auto& summary_state = simulator.vanguard().summaryState();
866 bool converged =
true;
867 auto& ws = well_state.
well(this->index_of_well_);
869 if (this->wellIsStopped()) {
871 const bool use_vfpexplicit = this->operability_status_.use_vfpexplicit;
872 this->operability_status_.use_vfpexplicit =
true;
873 auto bhp_target = estimateOperableBhp(simulator, dt, groupStateHelper, summary_state, well_state);
874 if (!bhp_target.has_value()) {
876 const auto msg = fmt::format(
"estimateOperableBhp: Did not find operable BHP for well {}", this->name());
877 deferred_logger.debug(msg);
880 converged = solveWellWithZeroRate(simulator, dt, groupStateHelper, well_state);
882 this->operability_status_.can_obtain_bhp_with_thp_limit =
false;
883 this->operability_status_.obey_thp_limit_under_bhp_limit =
false;
887 ws.thp = this->getTHPConstraint(summary_state);
888 const Scalar bhp = std::max(bhp_target.value(),
889 static_cast<Scalar>(prod_controls.bhp_limit));
890 solveWellWithBhp(simulator, dt, bhp, groupStateHelper, well_state);
891 this->operability_status_.use_vfpexplicit = use_vfpexplicit;
895 converged = this->iterateWellEqWithSwitching(
896 simulator, dt, inj_controls, prod_controls, groupStateHelper, well_state,
901 const bool isThp = ws.production_cmode == Well::ProducerCMode::THP;
903 if (converged && !stoppedOrZeroRateTarget(groupStateHelper) && isThp) {
904 auto rates = well_state.
well(this->index_of_well_).surface_rates;
905 this->adaptRatesForVFP(rates);
906 this->updateIPRImplicit(simulator, groupStateHelper, well_state);
910 this->operability_status_.use_vfpexplicit =
true;
913 const Scalar reltol = 1e-3;
914 const Scalar cur_bhp = ws.bhp;
915 if (bhp_stable.has_value() && cur_bhp - bhp_stable.value() > cur_bhp*reltol){
916 const auto msg = fmt::format(
"Well {} converged to an unstable solution, re-solving", this->name());
917 deferred_logger.debug(msg);
919 simulator, dt, bhp_stable.value(), groupStateHelper, well_state
922 ws.thp = this->getTHPConstraint(summary_state);
923 converged = this->iterateWellEqWithSwitching(
924 simulator, dt, inj_controls, prod_controls, groupStateHelper, well_state,
933 this->operability_status_.use_vfpexplicit =
true;
935 auto bhp_target = estimateOperableBhp(
936 simulator, dt, groupStateHelper, summary_state, well_state
938 if (!bhp_target.has_value()) {
941 converged = solveWellWithZeroRate(simulator, dt, groupStateHelper, well_state);
943 this->operability_status_.can_obtain_bhp_with_thp_limit =
false;
944 this->operability_status_.obey_thp_limit_under_bhp_limit =
false;
948 const Scalar bhp = std::max(bhp_target.value(),
949 static_cast<Scalar>(prod_controls.bhp_limit));
951 simulator, dt, bhp, groupStateHelper, well_state
953 ws.thp = this->getTHPConstraint(summary_state);
954 const auto msg = fmt::format(
"Well {} did not converge, re-solving with explicit fractions for VFP caculations.", this->name());
955 deferred_logger.debug(msg);
956 converged = this->iterateWellEqWithSwitching(simulator, dt,
967 this->operability_status_.can_obtain_bhp_with_thp_limit = !this->wellIsStopped();
968 this->operability_status_.obey_thp_limit_under_bhp_limit = !this->wellIsStopped();
972 template<
typename TypeTag>
973 std::optional<typename WellInterface<TypeTag>::Scalar>
978 const SummaryState& summary_state,
981 if (!this->wellHasTHPConstraints(summary_state)) {
983 const bool converged = solveWellWithBhp(
984 simulator, dt, bhp_limit, groupStateHelper, well_state
986 if (!converged || this->wellIsStopped()) {
997 const bool converged = solveWellWithBhp(
998 simulator, dt, bhp_min, groupStateHelper, well_state
1000 if (!converged || this->wellIsStopped()) {
1001 return std::nullopt;
1003 this->updateIPRImplicit(simulator, groupStateHelper, well_state);
1004 auto rates = well_state.
well(this->index_of_well_).surface_rates;
1005 this->adaptRatesForVFP(rates);
1009 template<
typename TypeTag>
1026 auto group_guard = groupStateHelper_copy.
pushGroupState(group_state);
1028 auto inj_controls = Well::InjectionControls(0);
1029 auto prod_controls = Well::ProductionControls(0);
1030 auto& ws = well_state.
well(this->index_of_well_);
1031 auto cmode_inj = ws.injection_cmode;
1032 auto cmode_prod = ws.production_cmode;
1033 if (this->isInjector()) {
1034 inj_controls.addControl(Well::InjectorCMode::BHP);
1035 inj_controls.bhp_limit = bhp;
1036 inj_controls.cmode = Well::InjectorCMode::BHP;
1037 ws.injection_cmode = Well::InjectorCMode::BHP;
1039 prod_controls.addControl(Well::ProducerCMode::BHP);
1040 prod_controls.bhp_limit = bhp;
1041 prod_controls.cmode = Well::ProducerCMode::BHP;
1042 ws.production_cmode = Well::ProducerCMode::BHP;
1047 const bool converged = this->iterateWellEqWithSwitching(
1048 simulator, dt, inj_controls, prod_controls, groupStateHelper_copy,
1054 ws.injection_cmode = cmode_inj;
1055 ws.production_cmode = cmode_prod;
1059 template<
typename TypeTag>
1070 const auto well_status_orig = this->wellStatus_;
1073 auto inj_controls = Well::InjectionControls(0);
1074 auto prod_controls = Well::ProductionControls(0);
1079 const bool converged = this->iterateWellEqWithSwitching(
1080 simulator, dt, inj_controls, prod_controls,
1087 this->wellStatus_ = well_status_orig;
1091 template<
typename TypeTag>
1101 const double dt = simulator.timeStepSize();
1103 const auto& summary_state = simulator.vanguard().summaryState();
1104 auto inj_controls = this->well_ecl_.isInjector() ? this->well_ecl_.injectionControls(summary_state) : Well::InjectionControls(0);
1105 auto prod_controls = this->well_ecl_.isProducer() ? this->well_ecl_.productionControls(summary_state) : Well::ProductionControls(0);
1106 this->onlyKeepBHPandTHPcontrols(summary_state, well_state, inj_controls, prod_controls);
1108 bool converged =
false;
1111 if (!this->param_.local_well_solver_control_switching_){
1112 converged = this->iterateWellEqWithControl(
1113 simulator, dt, inj_controls, prod_controls, groupStateHelper, well_state
1116 if (this->param_.use_implicit_ipr_ && this->well_ecl_.isProducer() && (well_state.
well(this->index_of_well_).status == WellStatus::OPEN)) {
1117 converged = this->solveWellWithOperabilityCheck(
1118 simulator, dt, inj_controls, prod_controls, groupStateHelper, well_state
1121 converged = this->iterateWellEqWithSwitching(
1122 simulator, dt, inj_controls, prod_controls, groupStateHelper, well_state,
1130 }
catch (NumericalProblem& e ) {
1131 const std::string msg =
"Inner well iterations failed for well " + this->name() +
" Treat the well as unconverged. ";
1132 deferred_logger.warning(
"INNER_ITERATION_FAILED", msg);
1137 deferred_logger.debug(
"WellTest: Well equation for well " + this->name() +
" converged");
1140 const int max_iter = this->param_.max_welleq_iter_;
1141 deferred_logger.debug(
"WellTest: Well equation for well " + this->name() +
" failed converging in "
1147 template<
typename TypeTag>
1156 if (!this->isOperableAndSolvable() && !this->wellIsStopped())
1161 const double dt = simulator.timeStepSize();
1162 bool converged = iterateWellEquations(simulator, dt, groupStateHelper, well_state);
1172 auto& ws = well_state.
well(this->indexOfWell());
1173 bool thp_control =
false;
1174 if (this->well_ecl_.isInjector()) {
1175 thp_control = ws.injection_cmode == Well::InjectorCMode::THP;
1177 ws.injection_cmode = Well::InjectorCMode::BHP;
1178 if (this->well_control_log_.empty()) {
1179 this->well_control_log_.push_back(WellInjectorCMode2String(Well::InjectorCMode::THP));
1183 thp_control = ws.production_cmode == Well::ProducerCMode::THP;
1185 ws.production_cmode = Well::ProducerCMode::BHP;
1186 if (this->well_control_log_.empty()) {
1187 this->well_control_log_.push_back(WellProducerCMode2String(Well::ProducerCMode::THP));
1192 const std::string msg = std::string(
"The newly opened well ") + this->name()
1193 + std::string(
" with THP control did not converge during inner iterations, we try again with bhp control");
1194 deferred_logger.debug(msg);
1195 converged = this->iterateWellEquations(simulator, dt, groupStateHelper, well_state);
1200 const int max_iter = this->param_.max_welleq_iter_;
1201 deferred_logger.debug(
"Compute initial well solution for well " + this->name() +
". Failed to converge in "
1203 well_state = well_state0;
1209 template <
typename TypeTag>
1218 prepareWellBeforeAssembling(simulator, dt, groupStateHelper, well_state);
1219 assembleWellEqWithoutIteration(simulator, groupStateHelper, dt, well_state,
1225 template <
typename TypeTag>
1232 const bool solving_with_zero_rate)
1235 const auto& summary_state = simulator.vanguard().summaryState();
1236 const auto inj_controls = this->well_ecl_.isInjector() ? this->well_ecl_.injectionControls(summary_state) : Well::InjectionControls(0);
1237 const auto prod_controls = this->well_ecl_.isProducer()
1238 ? this->productionControlsWithWeldraw(summary_state, well_state.
well(this->index_of_well_))
1239 : Well::ProductionControls(0);
1242 assembleWellEqWithoutIteration(simulator, groupStateHelper, dt, inj_controls, prod_controls, well_state, solving_with_zero_rate);
1247 template<
typename TypeTag>
1254 std::vector<Scalar> scaled_well_fractions(FluidSystem::numPhases, 0.0);
1255 this->getScaledWellFractions(scaled_well_fractions, deferred_logger);
1257 this->Base::updateGroupTargetFallbackFlag(well_state, scaled_well_fractions, deferred_logger);
1262 template<
typename TypeTag>
1272 const bool old_well_operable = this->operability_status_.isOperableAndSolvable();
1274 if (this->param_.check_well_operability_iter_)
1275 checkWellOperability(simulator, well_state, groupStateHelper);
1278 const auto& iterCtx = simulator.problem().iterationContext();
1279 if (iterCtx.shouldRunInnerWellIterations(this->param_.max_niter_inner_well_iter_)) {
1280 const auto& ws = well_state.
well(this->indexOfWell());
1281 const bool nonzero_rate_original =
1282 std::any_of(ws.surface_rates.begin(),
1283 ws.surface_rates.begin() + well_state.
numPhases(),
1284 [](
Scalar rate) { return rate != Scalar(0.0); });
1286 this->operability_status_.solvable =
true;
1287 if (number_of_well_reopenings_ >= this->param_.max_well_status_switch_) {
1289 if (number_of_well_reopenings_ == this->param_.max_well_status_switch_) {
1290 const std::string msg = fmt::format(
"well {} is oscillating between open and stop. \n"
1291 "We don't allow for more than {} re-openings "
1292 "and the well is therefore kept stopped.",
1293 this->name(), number_of_well_reopenings_);
1294 deferred_logger.debug(msg);
1295 changed_to_stopped_this_step_ = old_well_operable;
1297 changed_to_stopped_this_step_ =
false;
1300 bool converged_zero_rate = this->solveWellWithZeroRate(
1301 simulator, dt, groupStateHelper, well_state
1303 if (this->param_.shut_unsolvable_wells_ && !converged_zero_rate ) {
1304 this->operability_status_.solvable =
false;
1306 this->operability_status_.can_obtain_bhp_with_thp_limit =
false;
1307 this->operability_status_.obey_thp_limit_under_bhp_limit =
false;
1310 number_of_well_reopenings_++;
1313 bool converged = this->iterateWellEquations(
1314 simulator, dt, groupStateHelper, well_state
1318 const bool zero_target = this->wellUnderZeroRateTarget(groupStateHelper);
1319 if (this->wellIsStopped() && !zero_target && nonzero_rate_original) {
1323 this->operability_status_.resetOperability();
1325 deferred_logger.debug(
" " + this->name() +
" is re-opened after being stopped during local solve");
1326 number_of_well_reopenings_++;
1330 if (this->param_.shut_unsolvable_wells_) {
1331 this->operability_status_.solvable =
false;
1335 if (this->operability_status_.has_negative_potentials) {
1336 auto well_state_copy = well_state;
1337 std::vector<Scalar> potentials;
1339 computeWellPotentials(simulator, well_state_copy, groupStateHelper, potentials);
1340 }
catch (
const std::exception& e) {
1341 const std::string msg = fmt::format(
"well {}: computeWellPotentials() failed "
1342 "during attempt to recompute potentials for well: ",
1343 this->name(), e.what());
1344 deferred_logger.info(msg);
1345 this->operability_status_.has_negative_potentials =
true;
1347 auto& ws = well_state.
well(this->indexOfWell());
1349 for (
int p = 0; p < np; ++p) {
1350 ws.well_potentials[p] = std::max(
Scalar{0.0}, potentials[p]);
1353 this->changed_to_open_this_step_ =
false;
1354 changed_to_stopped_this_step_ =
false;
1356 const bool well_operable = this->operability_status_.isOperableAndSolvable();
1357 if (!well_operable) {
1360 this->solveWellWithZeroRate(
1361 simulator, dt, groupStateHelper, well_state
1363 }
catch (
const std::exception& e) {
1364 const std::string msg = fmt::format(
"well {}: solveWellWithZeroRate() failed "
1365 "during attempt to solve with zero rate for well: ",
1366 this->name(), e.what());
1367 deferred_logger.info(msg);
1369 auto& ws = well_state.
well(this->indexOfWell());
1371 for (
int p = 0; p < np; ++p) {
1372 ws.surface_rates[p] =
Scalar{0.0};
1375 if (old_well_operable) {
1376 const std::string ctx = iterCtx.inLocalSolve() ?
" (NLDD domain solve)" :
"";
1377 deferred_logger.debug(
" well " + this->name() +
" gets STOPPED during iteration" + ctx);
1378 changed_to_stopped_this_step_ =
true;
1380 }
else if (well_state.
isOpen(this->name())) {
1382 if (!old_well_operable) {
1383 const std::string ctx = iterCtx.inLocalSolve() ?
" (NLDD domain solve)" :
"";
1384 deferred_logger.debug(
" well " + this->name() +
" gets REVIVED during iteration" + ctx);
1385 this->changed_to_open_this_step_ =
true;
1390 template<
typename TypeTag>
1394 if(!this->operability_status_.solvable)
1397 for (
int perfIdx = 0; perfIdx < this->number_of_local_perforations_; ++perfIdx) {
1398 const auto cellIdx = this->cells()[perfIdx];
1399 const auto it = cellRates_.find(cellIdx);
1400 RateVector rates = (it == cellRates_.end()) ? 0.0 : it->second;
1401 for (
auto i=0*RateVector::dimension; i < RateVector::dimension; ++i)
1403 rates[i] += connectionRates_[perfIdx][i];
1405 cellRates_.insert_or_assign(cellIdx, rates);
1409 template<
typename TypeTag>
1413 for (
int perfIdx = 0; perfIdx < this->number_of_local_perforations_; ++perfIdx) {
1414 if (this->cells()[perfIdx] == cellIdx) {
1415 const unsigned activeCompIdx = FluidSystem::canonicalToActiveCompIdx(FluidSystem::solventComponentIndex(phaseIdx));
1416 return connectionRates_[perfIdx][activeCompIdx].value();
1420 OPM_THROW(std::invalid_argument,
"The well with name " + this->name()
1428 template<
typename TypeTag>
1437 if (!this->param_.check_well_operability_) {
1441 if (this->wellIsStopped() && !changed_to_stopped_this_step_) {
1445 updateWellOperability(simulator, well_state, groupStateHelper);
1446 if (!this->operability_status_.isOperableAndSolvable()) {
1447 this->operability_status_.use_vfpexplicit =
true;
1448 deferred_logger.debug(
"EXPLICIT_LOOKUP_VFP",
1449 "well not operable, trying with explicit vfp lookup: " + this->name());
1450 updateWellOperability(simulator, well_state, groupStateHelper);
1456 template<
typename TypeTag>
1466 const auto& summary_state = simulator.vanguard().summaryState();
1467 const auto& well_name = this->name();
1468 if (!this->wellHasTHPConstraints(summary_state)) {
1469 const std::string msg = fmt::format(
"GLIFT WTEST: Well {} does not have THP constraints", well_name);
1470 deferred_logger.
info(msg);
1473 const auto& schedule = simulator.vanguard().schedule();
1474 const auto report_step_idx = simulator.episodeIndex();
1475 const auto& glo = schedule.glo(report_step_idx);
1476 if (!glo.has_well(well_name)) {
1477 const std::string msg = fmt::format(
1478 "GLIFT WTEST: Well {} : Gas lift not activated: "
1479 "WLIFTOPT is probably missing. Skipping.", well_name);
1480 deferred_logger.
info(msg);
1483 const auto& gl_well = glo.well(well_name);
1486 std::unique_ptr<GasLiftSingleWell> glift =
1487 initializeGliftWellTest_<GasLiftSingleWell>(simulator,
1492 auto [wtest_alq, success] = glift->wellTestALQ();
1494 const auto& unit_system = schedule.getUnits();
1496 well_state.
well(well_name).alq_state.set(wtest_alq);
1498 "GLIFT WTEST: Well {} : Setting ALQ to optimized value = {}",
1499 well_name, unit_system.from_si(UnitSystem::measure::gas_surface_rate, wtest_alq));
1502 if (!gl_well.use_glo()) {
1504 "GLIFT WTEST: Well {} : Gas lift optimization deactivated. Setting ALQ to WLIFTOPT item 3 = {}",
1506 unit_system.from_si(UnitSystem::measure::gas_surface_rate, well_state.
well(well_name).alq_state.get()));
1511 "GLIFT WTEST: Well {} : Gas lift optimization failed, no ALQ set.",
1515 deferred_logger.
info(msg);
1518 template<
typename TypeTag>
1527 if (this->param_.local_well_solver_control_switching_) {
1528 const bool success = updateWellOperabilityFromWellEq(simulator, groupStateHelper);
1530 this->operability_status_.solvable =
false;
1531 deferred_logger.debug(
"Operability check using well equations did not converge for well "
1532 + this->name() +
". Mark the well as unsolvable." );
1536 this->operability_status_.resetOperability();
1538 bool thp_controlled = this->isInjector() ? well_state.
well(this->index_of_well_).injection_cmode == Well::InjectorCMode::THP:
1539 well_state.
well(this->index_of_well_).production_cmode == Well::ProducerCMode::THP;
1540 bool bhp_controlled = this->isInjector() ? well_state.
well(this->index_of_well_).injection_cmode == Well::InjectorCMode::BHP:
1541 well_state.
well(this->index_of_well_).production_cmode == Well::ProducerCMode::BHP;
1545 bool check_thp = thp_controlled || this->operability_status_.thp_limit_violated_but_not_switched;
1546 if (check_thp || bhp_controlled) {
1547 updateIPR(simulator, deferred_logger);
1548 checkOperabilityUnderBHPLimit(well_state, simulator, deferred_logger);
1552 checkOperabilityUnderTHPLimit(simulator, well_state, groupStateHelper);
1556 template<
typename TypeTag>
1564 assert(this->param_.local_well_solver_control_switching_);
1565 this->operability_status_.resetOperability();
1568 const double dt = simulator.timeStepSize();
1572 auto guard = groupStateHelper_copy.
pushWellState(well_state_copy);
1574 bool converged = iterateWellEquations(simulator, dt, groupStateHelper_copy, well_state_copy);
1578 template<
typename TypeTag>
1586 template<
typename TypeTag>
1596 const auto& well = this->well_ecl_;
1597 const int well_index = this->index_of_well_;
1598 auto& ws = well_state.
well(well_index);
1600 const auto& summaryState = simulator.vanguard().summaryState();
1601 const auto& schedule = simulator.vanguard().schedule();
1605 ws.primaryvar.resize(0);
1607 if (this->wellIsStopped()) {
1608 for (
int p = 0; p<np; ++p) {
1609 ws.surface_rates[p] = 0;
1615 if (this->isInjector() )
1617 const auto& controls = well.injectionControls(summaryState);
1619 InjectorType injectorType = controls.injector_type;
1621 switch (injectorType) {
1622 case InjectorType::WATER:
1624 phasePos = FluidSystem::canonicalToActivePhaseIdx(FluidSystem::waterPhaseIdx);
1627 case InjectorType::OIL:
1629 phasePos = FluidSystem::canonicalToActivePhaseIdx(FluidSystem::oilPhaseIdx);
1632 case InjectorType::GAS:
1634 phasePos = FluidSystem::canonicalToActivePhaseIdx(FluidSystem::gasPhaseIdx);
1638 OPM_DEFLOG_THROW(std::runtime_error,
"Expected WATER, OIL or GAS as type for injectors " + this->name(), deferred_logger );
1641 const auto current = ws.injection_cmode;
1644 case Well::InjectorCMode::RATE:
1646 ws.surface_rates[phasePos] = (1.0 - this->rsRvInj()) * controls.surface_rate;
1647 if(this->rsRvInj() > 0) {
1648 if (injectorType == InjectorType::OIL && FluidSystem::phaseIsActive(FluidSystem::gasPhaseIdx)) {
1649 const int gas_pos = FluidSystem::canonicalToActivePhaseIdx(FluidSystem::gasPhaseIdx);
1650 ws.surface_rates[gas_pos] = controls.surface_rate * this->rsRvInj();
1651 }
else if (injectorType == InjectorType::GAS && FluidSystem::phaseIsActive(FluidSystem::oilPhaseIdx)) {
1652 const int oil_pos = FluidSystem::canonicalToActivePhaseIdx(FluidSystem::oilPhaseIdx);
1653 ws.surface_rates[oil_pos] = controls.surface_rate * this->rsRvInj();
1655 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 );
1661 case Well::InjectorCMode::RESV:
1663 std::vector<Scalar> convert_coeff(this->number_of_phases_, 1.0);
1664 this->rateConverter_.calcCoeff( 0, this->pvtRegionIdx_, convert_coeff);
1665 const Scalar coeff = convert_coeff[phasePos];
1666 ws.surface_rates[phasePos] = controls.reservoir_rate/coeff;
1670 case Well::InjectorCMode::THP:
1672 auto rates = ws.surface_rates;
1677 this->getRefDensity(),
1680 ws.thp = this->getTHPConstraint(summaryState);
1685 Scalar total_rate = std::accumulate(rates.begin(), rates.end(), 0.0);
1686 if (total_rate <= 0.0)
1687 ws.surface_rates = ws.well_potentials;
1691 case Well::InjectorCMode::BHP:
1693 ws.bhp = controls.bhp_limit;
1695 for (
int p = 0; p<np; ++p) {
1696 total_rate += ws.surface_rates[p];
1701 if (total_rate <= 0.0)
1702 ws.surface_rates = ws.well_potentials;
1706 case Well::InjectorCMode::GRUP:
1708 assert(well.isAvailableForGroupControl());
1709 const auto& group = schedule.getGroup(well.groupName(), this->currentStep());
1710 const Scalar efficiencyFactor = well.getEfficiencyFactor() *
1711 well_state[well.name()].efficiency_scaling_factor;
1712 std::optional<Scalar> target =
1713 this->getGroupInjectionTargetRate(group,
1718 ws.surface_rates[phasePos] = *target;
1721 case Well::InjectorCMode::CMODE_UNDEFINED:
1723 OPM_DEFLOG_THROW(std::runtime_error,
"Well control must be specified for well " + this->name(), deferred_logger );
1733 ws.surface_rates[phasePos] = std::max(
Scalar{1.e-7}, ws.surface_rates[phasePos]);
1736 ws.bhp = controls.bhp_limit;
1742 const auto current = ws.production_cmode;
1743 const auto controls = this->productionControlsWithWeldraw(summaryState, ws);
1745 case Well::ProducerCMode::ORAT:
1747 const int oil_pos = FluidSystem::canonicalToActivePhaseIdx(FluidSystem::oilPhaseIdx);
1748 Scalar current_rate = -ws.surface_rates[oil_pos];
1751 if (current_rate > 0.0) {
1752 for (
int p = 0; p<np; ++p) {
1753 ws.surface_rates[p] *= controls.oil_rate/current_rate;
1756 const std::vector<Scalar> fractions = initialWellRateFractions(simulator, well_state);
1757 double control_fraction = fractions[oil_pos];
1758 if (control_fraction != 0.0) {
1759 for (
int p = 0; p<np; ++p) {
1760 ws.surface_rates[p] = - fractions[p] * controls.oil_rate/control_fraction;
1766 case Well::ProducerCMode::WRAT:
1768 const int water_pos = FluidSystem::canonicalToActivePhaseIdx(FluidSystem::waterPhaseIdx);
1769 Scalar current_rate = -ws.surface_rates[water_pos];
1772 if (current_rate > 0.0) {
1773 for (
int p = 0; p<np; ++p) {
1774 ws.surface_rates[p] *= controls.water_rate/current_rate;
1777 const std::vector<Scalar> fractions = initialWellRateFractions(simulator, well_state);
1778 const Scalar control_fraction = fractions[water_pos];
1779 if (control_fraction != 0.0) {
1780 for (
int p = 0; p<np; ++p) {
1781 ws.surface_rates[p] = - fractions[p] * controls.water_rate / control_fraction;
1787 case Well::ProducerCMode::GRAT:
1789 const int gas_pos = FluidSystem::canonicalToActivePhaseIdx(FluidSystem::gasPhaseIdx);
1790 Scalar current_rate = -ws.surface_rates[gas_pos];
1793 if (current_rate > 0.0) {
1794 for (
int p = 0; p<np; ++p) {
1795 ws.surface_rates[p] *= controls.gas_rate/current_rate;
1798 const std::vector<Scalar > fractions = initialWellRateFractions(simulator, well_state);
1799 const Scalar control_fraction = fractions[gas_pos];
1800 if (control_fraction != 0.0) {
1801 for (
int p = 0; p<np; ++p) {
1802 ws.surface_rates[p] = - fractions[p] * controls.gas_rate / control_fraction;
1810 case Well::ProducerCMode::LRAT:
1812 const int water_pos = FluidSystem::canonicalToActivePhaseIdx(FluidSystem::waterPhaseIdx);
1813 const int oil_pos = FluidSystem::canonicalToActivePhaseIdx(FluidSystem::oilPhaseIdx);
1814 Scalar current_rate = - ws.surface_rates[water_pos]
1815 - ws.surface_rates[oil_pos];
1818 if (current_rate > 0.0) {
1819 for (
int p = 0; p<np; ++p) {
1820 ws.surface_rates[p] *= controls.liquid_rate/current_rate;
1823 const std::vector<Scalar> fractions = initialWellRateFractions(simulator, well_state);
1824 const Scalar control_fraction = fractions[water_pos] + fractions[oil_pos];
1825 if (control_fraction != 0.0) {
1826 for (
int p = 0; p<np; ++p) {
1827 ws.surface_rates[p] = - fractions[p] * controls.liquid_rate / control_fraction;
1833 case Well::ProducerCMode::CRAT:
1836 fmt::format(
"CRAT control not supported, well {}", this->name()),
1839 case Well::ProducerCMode::RESV:
1841 std::vector<Scalar> convert_coeff(this->number_of_phases_, 1.0);
1842 this->rateConverter_.calcCoeff( 0, this->pvtRegionIdx_, ws.surface_rates, convert_coeff);
1843 Scalar total_res_rate = 0.0;
1844 for (
int p = 0; p<np; ++p) {
1845 total_res_rate -= ws.surface_rates[p] * convert_coeff[p];
1847 if (controls.prediction_mode) {
1850 if (total_res_rate > 0.0) {
1851 for (
int p = 0; p<np; ++p) {
1852 ws.surface_rates[p] *= controls.resv_rate/total_res_rate;
1855 const std::vector<Scalar> fractions = initialWellRateFractions(simulator, well_state);
1856 for (
int p = 0; p<np; ++p) {
1857 ws.surface_rates[p] = - fractions[p] * controls.resv_rate / convert_coeff[p];
1861 std::vector<Scalar> hrates(this->number_of_phases_,0.);
1862 if (FluidSystem::phaseIsActive(FluidSystem::waterPhaseIdx)) {
1863 const int phase_pos = FluidSystem::canonicalToActivePhaseIdx(FluidSystem::waterPhaseIdx);
1864 hrates[phase_pos] = controls.water_rate;
1866 if (FluidSystem::phaseIsActive(FluidSystem::oilPhaseIdx)) {
1867 const int phase_pos = FluidSystem::canonicalToActivePhaseIdx(FluidSystem::oilPhaseIdx);
1868 hrates[phase_pos] = controls.oil_rate;
1870 if (FluidSystem::phaseIsActive(FluidSystem::gasPhaseIdx)) {
1871 const int phase_pos = FluidSystem::canonicalToActivePhaseIdx(FluidSystem::gasPhaseIdx);
1872 hrates[phase_pos] = controls.gas_rate;
1874 std::vector<Scalar> hrates_resv(this->number_of_phases_,0.);
1875 this->rateConverter_.calcReservoirVoidageRates( 0, this->pvtRegionIdx_, hrates, hrates_resv);
1876 Scalar target = std::accumulate(hrates_resv.begin(), hrates_resv.end(), 0.0);
1879 if (total_res_rate > 0.0) {
1880 for (
int p = 0; p<np; ++p) {
1881 ws.surface_rates[p] *= target/total_res_rate;
1884 const std::vector<Scalar> fractions = initialWellRateFractions(simulator, well_state);
1885 for (
int p = 0; p<np; ++p) {
1886 ws.surface_rates[p] = - fractions[p] * target / convert_coeff[p];
1892 case Well::ProducerCMode::BHP:
1894 ws.bhp = controls.bhp_limit;
1896 for (
int p = 0; p<np; ++p) {
1897 total_rate -= ws.surface_rates[p];
1902 if (total_rate <= 0.0){
1903 for (
int p = 0; p<np; ++p) {
1904 ws.surface_rates[p] = -ws.well_potentials[p];
1909 case Well::ProducerCMode::THP:
1911 const bool update_success = updateWellStateWithTHPTargetProd(simulator, well_state, groupStateHelper);
1913 if (!update_success) {
1917 auto rates = ws.surface_rates;
1918 this->adaptRatesForVFP(rates);
1920 well_state, rates, well, summaryState, this->getRefDensity(), deferred_logger);
1922 ws.thp = this->getTHPConstraint(summaryState);
1926 const Scalar total_rate = -std::accumulate(rates.begin(), rates.end(), 0.0);
1927 if (total_rate <= 0.0) {
1928 for (
int p = 0; p < this->number_of_phases_; ++p) {
1929 ws.surface_rates[p] = -ws.well_potentials[p];
1935 case Well::ProducerCMode::GRUP:
1937 assert(well.isAvailableForGroupControl());
1938 this->updateGroupTargetFallbackFlag(well_state, deferred_logger);
1939 const auto& group = schedule.getGroup(well.groupName(), this->currentStep());
1940 const Scalar efficiencyFactor = well.getEfficiencyFactor() *
1941 well_state[well.name()].efficiency_scaling_factor;
1942 Scalar scale = this->getGroupProductionTargetRate(group,
1948 for (
int p = 0; p<np; ++p) {
1949 ws.surface_rates[p] *= scale;
1954 case Well::ProducerCMode::CMODE_UNDEFINED:
1957 OPM_DEFLOG_THROW(std::runtime_error,
"Well control must be specified for well " + this->name() , deferred_logger);
1963 ws.bhp = controls.bhp_limit;
1968 template<
typename TypeTag>
1974 const auto& well_state = groupStateHelper.
wellState();
1976 const bool isGroupControlled = this->wellUnderGroupControl(well_state.well(this->index_of_well_));
1977 if (!isGroupControlled) {
1979 const auto& summaryState = groupStateHelper.
summaryState();
1980 return this->wellUnderZeroRateTargetIndividual(summaryState, well_state);
1982 return this->wellUnderZeroGroupRateTarget(groupStateHelper, isGroupControlled);
1986 template <
typename TypeTag>
1989 const std::optional<bool> group_control)
const
1991 const auto& well_state = groupStateHelper.
wellState();
1993 const bool isGroupControlled = group_control.value_or(this->wellUnderGroupControl(well_state.well(this->index_of_well_)));
1994 if (isGroupControlled) {
1995 return this->zeroGroupRateTarget(groupStateHelper);
2000 template<
typename TypeTag>
2007 return this->wellIsStopped()
2008 || this->wellUnderZeroRateTarget(groupStateHelper);
2011 template<
typename TypeTag>
2012 std::vector<typename WellInterface<TypeTag>::Scalar>
2018 const int np = this->number_of_phases_;
2019 std::vector<Scalar> scaling_factor(np);
2020 const auto& ws = well_state.
well(this->index_of_well_);
2022 Scalar total_potentials = 0.0;
2023 for (
int p = 0; p<np; ++p) {
2024 total_potentials += ws.well_potentials[p];
2026 if (total_potentials > 0) {
2027 for (
int p = 0; p<np; ++p) {
2028 scaling_factor[p] = ws.well_potentials[p] / total_potentials;
2030 return scaling_factor;
2035 const int nperf = this->number_of_local_perforations_;
2036 for (
int perf = 0; perf < nperf; ++perf) {
2037 total_tw += this->well_index_[perf];
2039 total_tw = this->parallelWellInfo().communication().sum(total_tw);
2041 for (
int perf = 0; perf < nperf; ++perf) {
2042 const int cell_idx = this->well_cells_[perf];
2043 const auto& intQuants = simulator.model().intensiveQuantities(cell_idx, 0);
2044 const auto& fs = intQuants.fluidState();
2045 const Scalar well_tw_fraction = this->well_index_[perf] / total_tw;
2046 Scalar total_mobility = 0.0;
2047 for (
int p = 0; p < np; ++p) {
2048 const int canonical_phase_idx = FluidSystem::activeToCanonicalPhaseIdx(p);
2049 total_mobility += fs.invB(canonical_phase_idx).value() * intQuants.mobility(canonical_phase_idx).value();
2051 for (
int p = 0; p < np; ++p) {
2052 const int canonical_phase_idx = FluidSystem::activeToCanonicalPhaseIdx(p);
2053 scaling_factor[p] += well_tw_fraction * fs.invB(canonical_phase_idx).value() * intQuants.mobility(canonical_phase_idx).value() / total_mobility;
2056 return scaling_factor;
2061 template <
typename TypeTag>
2068 assert(this->isProducer());
2072 auto& ws = well_state.
well(this->index_of_well_);
2073 int nonzero_rate_index = -1;
2074 const Scalar floating_point_error_epsilon = 1e-14;
2075 for (
int p = 0; p < this->number_of_phases_; ++p) {
2076 if (std::abs(ws.surface_rates[p]) > floating_point_error_epsilon) {
2077 if (nonzero_rate_index == -1) {
2078 nonzero_rate_index = p;
2087 std::vector<Scalar> well_q_s(this->number_of_phases_, 0.0);
2088 bool rates_evaluated_at_1bar =
false;
2090 const auto& summary_state = simulator.vanguard().summaryState();
2091 const auto& prod_controls = this->well_ecl_.productionControls(summary_state);
2092 const double bhp_limit = std::max(prod_controls.bhp_limit, 1.0 * unit::barsa);
2093 this->computeWellRatesWithBhp(simulator, bhp_limit, well_q_s, deferred_logger);
2095 rates_evaluated_at_1bar = (bhp_limit < 1.1 * unit::barsa);
2097 if (std::ranges::any_of(well_q_s, [](
Scalar q) {
return q > 0.0; })) {
2099 if (!rates_evaluated_at_1bar) {
2100 this->computeWellRatesWithBhp(simulator, 1.0 * unit::barsa, well_q_s, deferred_logger);
2101 rates_evaluated_at_1bar =
true;
2104 for (
auto& q : well_q_s) {
2105 q = std::min(q,
Scalar{0.0});
2110 if (nonzero_rate_index == -1) {
2114 const Scalar factor = rates_evaluated_at_1bar ? 0.5 : 1.0;
2115 for (
int p = 0; p < this->number_of_phases_; ++p) {
2116 ws.surface_rates[p] = factor * well_q_s[p];
2125 const Scalar initial_nonzero_rate = ws.surface_rates[nonzero_rate_index];
2126 const Scalar computed_rate = well_q_s[nonzero_rate_index];
2127 if (std::abs(initial_nonzero_rate) < std::abs(computed_rate)) {
2129 const Scalar factor = initial_nonzero_rate / computed_rate;
2130 assert(factor < 1.0);
2131 for (
int p = 0; p < this->number_of_phases_; ++p) {
2133 if (p != nonzero_rate_index) {
2134 ws.surface_rates[p] = factor * well_q_s[p];
2143 for (
int p = 0; p < this->number_of_phases_; ++p) {
2144 ws.surface_rates[p] = well_q_s[p];
2148 template <
typename TypeTag>
2149 template<
class Value>
2152 getTw(std::vector<Value>& Tw,
2155 const Value& trans_mult,
2158 OPM_TIMEFUNCTION_LOCAL(Subsystem::Wells);
2161 if (
static_cast<std::size_t
>(perf) >= this->well_cells_.size()) {
2162 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!");
2168 if (!this->well_index_fracture_.empty()) {
2169 const auto frac_wi = this->well_index_fracture_[perf]
2170 .wellIndex(ws.
perf_data.pressure[perf]);
2171 if (frac_wi > 0.0) {
2172 for (
auto& tw : Tw) {
2178 if constexpr (! Indices::gasEnabled) {
2182 const auto& wdfac = this->well_ecl_.getWDFAC();
2184 if (! wdfac.useDFactor() || (this->well_index_[perf] == 0.0)) {
2188 const Scalar d = this->computeConnectionDFactor(perf, intQuants, ws);
2195 const auto& connection = this->well_ecl_.getConnections()[ws.
perf_data.ecl_index[perf]];
2196 const Scalar Kh = connection.Kh();
2197 const Scalar scaling = std::numbers::pi * Kh * connection.wpimult();
2198 const unsigned gas_comp_idx = FluidSystem::canonicalToActiveCompIdx(FluidSystem::gasCompIdx);
2201 const Scalar cell_pressure = getValue(intQuants.fluidState().pressure(FluidSystem::gasPhaseIdx));
2202 const Scalar drawdown = cell_pressure - connection_pressure;
2203 const Scalar invB = getValue(intQuants.fluidState().invB(FluidSystem::gasPhaseIdx));
2204 const Scalar mob_g = getValue(intQuants.mobility(FluidSystem::gasPhaseIdx)) * invB;
2206 const Scalar b = 2 * scaling / getValue(Tw[gas_comp_idx]);
2207 const Scalar c = -2 * scaling * mob_g * drawdown;
2209 Scalar consistent_Q = -1.0e20;
2211 const Scalar r2n = b*b + 4*a*c;
2213 const Scalar rn = std::sqrt(r2n);
2214 const Scalar xn1 = (b-rn)*0.5/a;
2218 const Scalar xn2 = (b+rn)*0.5/a;
2219 if (xn2 <= 0 && xn2 > consistent_Q) {
2225 const Scalar r2p = b*b - 4*a*c;
2227 const Scalar rp = std::sqrt(r2p);
2228 const Scalar xp1 = (rp-b)*0.5/a;
2229 if (xp1 > 0 && xp1 < consistent_Q) {
2232 const Scalar xp2 = -(rp+b)*0.5/a;
2233 if (xp2 > 0 && xp2 < consistent_Q) {
2237 Tw[gas_comp_idx] = 1.0 / (1.0 / (trans_mult * this->well_index_[perf]) + (consistent_Q/2 * d / scaling));
2240 template <
typename TypeTag>
2246 if (! this->well_ecl_.getWDFAC().useDFactor()) {
2250 auto& d_factor = ws.
perf_data.connection_d_factor;
2252 for (
int perf = 0; perf < this->number_of_local_perforations_; ++perf) {
2253 const int cell_idx = this->well_cells_[perf];
2254 const auto& intQuants = simulator.model().intensiveQuantities(cell_idx, 0);
2256 d_factor[perf] = this->computeConnectionDFactor(perf, intQuants, ws);
2260 template <
typename TypeTag>
2267 auto rhoGS = [regIdx = this->pvtRegionIdx()]() {
2268 return FluidSystem::referenceDensity(FluidSystem::gasPhaseIdx, regIdx);
2272 auto gas_visc = [connection_pressure = ws.
perf_data.pressure[perf],
2274 regIdx = this->pvtRegionIdx(), &intQuants]()
2276 const auto rv = getValue(intQuants.fluidState().Rv());
2278 const auto& gasPvt = FluidSystem::gasPvt();
2283 const Scalar rv_sat = gasPvt.saturatedOilVaporizationFactor
2284 (regIdx, temperature, connection_pressure);
2286 if (! (rv < rv_sat)) {
2287 return gasPvt.saturatedViscosity(regIdx, temperature,
2288 connection_pressure);
2291 return gasPvt.viscosity(regIdx, temperature, connection_pressure,
2292 rv, getValue(intQuants.fluidState().Rvw()));
2295 const auto& connection = this->well_ecl_.getConnections()
2298 return this->well_ecl_.getWDFAC().getDFactor(rhoGS, gas_visc, connection);
2302 template <
typename TypeTag>
2308 auto connCF = [&connIx = std::as_const(ws.
perf_data.ecl_index),
2309 &conns = this->well_ecl_.getConnections()]
2312 return conns[connIx[perf]].CF();
2315 auto obtain = [](
const Eval& value)
2317 return getValue(value);
2320 auto& tmult = ws.
perf_data.connection_compaction_tmult;
2321 auto& ctf = ws.
perf_data.connection_transmissibility_factor;
2323 for (
int perf = 0; perf < this->number_of_local_perforations_; ++perf) {
2324 const int cell_idx = this->well_cells_[perf];
2326 getTransMult(trans_mult, simulator, cell_idx, obtain);
2327 tmult[perf] = trans_mult;
2329 ctf[perf] = connCF(perf) * tmult[perf];
2334 template<
typename TypeTag>
2338 if constexpr (Indices::oilEnabled) {
2339 return fs.pressure(FluidSystem::oilPhaseIdx);
2340 }
else if constexpr (Indices::gasEnabled) {
2341 return fs.pressure(FluidSystem::gasPhaseIdx);
2343 return fs.pressure(FluidSystem::waterPhaseIdx);
2347 template <
typename TypeTag>
2348 template<
class Value,
class Callback>
2354 Callback& extendEval)
const
2356 const auto& intQuants = simulator.model().intensiveQuantities(cell_idx, 0);
2357 trans_mult = simulator.problem().template wellTransMultiplier<Value>(intQuants, cell_idx, extendEval);
2360 template <
typename TypeTag>
2361 template<
class Value,
class Callback>
2365 const int local_perf_index,
2366 std::vector<Value>& mob,
2367 Callback& extendEval,
2370 auto relpermArray = []()
2372 if constexpr (std::is_same_v<Value, Scalar>) {
2373 return std::array<Scalar,3>{};
2375 return std::array<Eval,3>{};
2378 if (
static_cast<std::size_t
>(local_perf_index) >= this->well_cells_.size()) {
2379 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!");
2381 const int cell_idx = this->well_cells_[local_perf_index];
2382 assert (
int(mob.size()) == this->num_conservation_quantities_);
2383 const auto& intQuants = simulator.model().intensiveQuantities(cell_idx, 0);
2384 const auto& materialLawManager = simulator.problem().materialLawManager();
2388 const int satid = this->saturation_table_number_[local_perf_index] - 1;
2389 const int satid_elem = materialLawManager.satnumRegionIdx(cell_idx);
2390 if (satid == satid_elem) {
2391 for (
unsigned phaseIdx = 0; phaseIdx < FluidSystem::numPhases; ++phaseIdx) {
2392 if (!FluidSystem::phaseIsActive(phaseIdx)) {
2396 const unsigned activeCompIdx = FluidSystem::canonicalToActiveCompIdx(FluidSystem::solventComponentIndex(phaseIdx));
2397 mob[activeCompIdx] = extendEval(intQuants.mobility(phaseIdx));
2399 if constexpr (has_solvent) {
2400 mob[Indices::contiSolventEqIdx] = extendEval(intQuants.solventMobility());
2403 const auto& paramsCell = materialLawManager.connectionMaterialLawParams(satid, cell_idx);
2404 auto relativePerms = relpermArray();
2405 MaterialLaw::relativePermeabilities(relativePerms, paramsCell, intQuants.fluidState());
2408 materialLawManager.connectionMaterialLawParams(satid_elem, cell_idx);
2411 for (
unsigned phaseIdx = 0; phaseIdx < FluidSystem::numPhases; ++phaseIdx) {
2412 if (!FluidSystem::phaseIsActive(phaseIdx)) {
2416 const unsigned activeCompIdx = FluidSystem::canonicalToActiveCompIdx(FluidSystem::solventComponentIndex(phaseIdx));
2417 mob[activeCompIdx] = extendEval(relativePerms[phaseIdx] / intQuants.fluidState().viscosity(phaseIdx));
2420 if constexpr (has_solvent) {
2421 const auto Fsolgas = intQuants.solventSaturation() / (intQuants.solventSaturation() + intQuants.fluidState().saturation(FluidSystem::gasPhaseIdx));
2423 if (Fsolgas > SolventModule::cutOff) {
2424 const unsigned activeGasCompIdx = FluidSystem::canonicalToActiveCompIdx(FluidSystem::solventComponentIndex(FluidSystem::gasPhaseIdx));
2425 const auto& ssfnKrg = SolventModule::ssfnKrg(satid);
2426 const auto& ssfnKrs = SolventModule::ssfnKrs(satid);
2427 mob[activeGasCompIdx] *= extendEval(ssfnKrg.eval(1-Fsolgas,
true));
2428 mob[Indices::contiSolventEqIdx] = extendEval(ssfnKrs.eval(Fsolgas,
true) * relativePerms[activeGasCompIdx] / intQuants.solventViscosity());
2433 if (this->isInjector() && !this->inj_fc_multiplier_.empty()) {
2434 const auto perf_ecl_index = this->perforationData()[local_perf_index].ecl_index;
2435 const auto& connections = this->well_ecl_.getConnections();
2436 const auto& connection = connections[perf_ecl_index];
2437 if (connection.filterCakeActive()) {
2438 std::ranges::transform(mob, mob.begin(),
2439 [mult = this->inj_fc_multiplier_[local_perf_index]]
2441 { return val * mult; });
2447 template<
typename TypeTag>
2456 const auto& summary_state = simulator.vanguard().summaryState();
2458 auto bhp_at_thp_limit = computeBhpAtThpLimitProdWithAlq(
2459 simulator, groupStateHelper, summary_state, this->getALQ(well_state),
false);
2460 if (bhp_at_thp_limit) {
2461 std::vector<Scalar> rates(this->number_of_phases_, 0.0);
2462 if (thp_update_iterations) {
2463 computeWellRatesWithBhpIterations(simulator, *bhp_at_thp_limit,
2464 groupStateHelper, rates);
2466 computeWellRatesWithBhp(simulator, *bhp_at_thp_limit,
2467 rates, deferred_logger);
2469 auto& ws = well_state.
well(this->name());
2470 ws.surface_rates = rates;
2471 ws.bhp = *bhp_at_thp_limit;
2472 ws.thp = this->getTHPConstraint(summary_state);
2479 template<
typename TypeTag>
2480 std::optional<typename WellInterface<TypeTag>::Scalar>
2485 const SummaryState& summary_state,
2490 const auto& groupStateHelper = simulator.problem().wellModel().groupStateHelper();
2492 auto well_guard = groupStateHelper_copy.
pushWellState(well_state_copy);
2493 const double dt = simulator.timeStepSize();
2494 const bool converged = this->solveWellWithBhp(
2495 simulator, dt, bhp, groupStateHelper_copy, well_state_copy
2499 auto rates = well_state_copy.
well(this->index_of_well_).surface_rates;
2501 for (std::size_t p = 0; p < rates.size(); ++p) {
2502 zero_rates &= rates[p] == 0.0;
2506 if (zero_rates || !converged) {
2507 return this->computeBhpAtThpLimitProdWithAlq(simulator, groupStateHelper_copy, summary_state, alq_value,
false);
2509 this->updateIPRImplicit(simulator, groupStateHelper_copy, well_state_copy);
2510 this->adaptRatesForVFP(rates);
2514 template <
typename TypeTag>
2519 const std::vector<Scalar>& mobility,
2522 const int np = this->number_of_phases_;
2523 for (
int p = 0; p < np; ++p) {
2526 const int canonical_phase_idx = FluidSystem::activeToCanonicalPhaseIdx(p);
2527 const auto connMob =
2528 mobility[FluidSystem::activePhaseToActiveCompIdx(p)] * fs.invB(canonical_phase_idx).value();
2530 connPI[p] = connPICalc(connMob);
2533 if (FluidSystem::phaseIsActive(FluidSystem::oilPhaseIdx) &&
2534 FluidSystem::phaseIsActive(FluidSystem::gasPhaseIdx))
2536 const auto io = FluidSystem::canonicalToActivePhaseIdx(FluidSystem::oilPhaseIdx);
2537 const auto ig = FluidSystem::canonicalToActivePhaseIdx(FluidSystem::gasPhaseIdx);
2539 const auto vapoil = connPI[ig] * fs.Rv().value();
2540 const auto disgas = connPI[io] * fs.Rs().value();
2542 connPI[io] += vapoil;
2543 connPI[ig] += disgas;
2548 template <
typename TypeTag>
2552 const Phase preferred_phase,
2554 const std::vector<Scalar>& mobility,
2559 if (preferred_phase == Phase::GAS) {
2560 phase_pos = FluidSystem::canonicalToActivePhaseIdx(FluidSystem::gasPhaseIdx);
2562 else if (preferred_phase == Phase::OIL) {
2563 phase_pos = FluidSystem::canonicalToActivePhaseIdx(FluidSystem::oilPhaseIdx);
2565 else if (preferred_phase == Phase::WATER) {
2566 phase_pos = FluidSystem::canonicalToActivePhaseIdx(FluidSystem::waterPhaseIdx);
2570 fmt::format(
"Unsupported Injector Type ({}) "
2571 "for well {} during connection I.I. calculation",
2572 static_cast<int>(preferred_phase), this->name()),
2576 const auto mt = std::accumulate(mobility.begin(), mobility.end(), 0.0);
2577 const int canonicalPhaseIdx = FluidSystem::activeToCanonicalPhaseIdx(phase_pos);
2578 connII[phase_pos] = connIICalc(mt * fs.invB(canonicalPhaseIdx).value());
2581 template<
typename TypeTag>
2582 template<
class GasLiftSingleWell>
2583 std::unique_ptr<GasLiftSingleWell>
2592 auto& comm = simulator.vanguard().grid().comm();
2593 ecl_well_map.try_emplace(this->name(), &(this->wellEcl()), this->indexOfWell());
2594 const auto& iterCtx = simulator.problem().iterationContext();
2597 simulator.vanguard().schedule(),
2598 simulator.vanguard().summaryState(),
2599 simulator.episodeIndex(),
2609 std::set<int> sync_groups;
2610 const auto& summary_state = simulator.vanguard().summaryState();
2611 return std::make_unique<GasLiftSingleWell>(*
this,
2625 template <
typename TypeTag>
2632 if (this->well_cells_.size() > 0) {
2636 const int cell_idx = this->well_cells_[0];
2637 const auto& intQuants = simulator.model().intensiveQuantities(cell_idx, 0);
2638 const auto& fs = intQuants.fluidState();
2640 info.
temperature = getValue(fs.temperature(FluidSystem::oilPhaseIdx));
2641 info.saltConcentration = getValue(fs.saltConcentration());
2647 return this->parallel_well_info_.communication().size() == 1
2649 : 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:47
Definition: GroupStateHelper.hpp:56
GroupState< Scalar > & groupState() const
Definition: GroupStateHelper.hpp:325
const SummaryState & summaryState() const
Definition: GroupStateHelper.hpp:465
const WellState< Scalar, IndexTraits > & wellState() const
Definition: GroupStateHelper.hpp:546
DeferredLogger & deferredLogger() const
Get the deferred logger.
Definition: GroupStateHelper.hpp:257
WellStateGuard pushWellState(WellState< Scalar, IndexTraits > &well_state)
Definition: GroupStateHelper.hpp:404
GroupStateGuard pushGroupState(GroupState< Scalar > &group_state)
Definition: GroupStateHelper.hpp:381
Definition: GroupState.hpp:42
Class encapsulating some information about parallel wells.
Definition: ParallelWellInfo.hpp:217
Definition: SingleWellState.hpp:44
Scalar temperature
Definition: SingleWellState.hpp:116
PerfData< Scalar > perf_data
Definition: SingleWellState.hpp:172
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:2003
bool updateWellOperabilityFromWellEq(const Simulator &simulator, const GroupStateHelperType &groupStateHelper)
Definition: WellInterface_impl.hpp:1559
void checkWellOperability(const Simulator &simulator, const WellStateType &well_state, const GroupStateHelperType &groupStateHelper)
Definition: WellInterface_impl.hpp:1431
void updateWellOperability(const Simulator &simulator, const WellStateType &well_state, const GroupStateHelperType &groupStateHelper)
Definition: WellInterface_impl.hpp:1521
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:855
Scalar woxygen() const
Definition: WellInterface_impl.hpp:168
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:1228
Scalar computeConnectionDFactor(const int perf, const IntensiveQuantities &intQuants, const SingleWellStateType &ws) const
Definition: WellInterface_impl.hpp:2263
void updateWeldrawMaxRate(const Simulator &simulator, WellStateType &well_state, DeferredLogger &deferred_logger) const
Definition: WellInterface_impl.hpp:290
typename WellInterfaceFluidSystem< FluidSystem >::RateConverterType RateConverterType
Definition: WellInterface.hpp:110
Scalar wfoam() const
Definition: WellInterface_impl.hpp:130
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:382
void getTransMult(Value &trans_mult, const Simulator &simulator, const int cell_idx, Callback &extendEval) const
Definition: WellInterface_impl.hpp:2351
std::vector< RateVector > connectionRates_
Definition: WellInterface.hpp:436
bool solveWellForTesting(const Simulator &simulator, const GroupStateHelperType &groupStateHelper, WellStateType &well_state)
Definition: WellInterface_impl.hpp:1094
void computeConnLevelProdInd(const FluidState &fs, const std::function< Scalar(const Scalar)> &connPICalc, const std::vector< Scalar > &mobility, Scalar *connPI) const
Definition: WellInterface_impl.hpp:2517
void gliftBeginTimeStepWellTestUpdateALQ(const Simulator &simulator, WellStateType &well_state, const GroupState< Scalar > &group_state, GLiftEclWells &ecl_well_map, DeferredLogger &deferred_logger)
Definition: WellInterface_impl.hpp:1459
Scalar volumetricSurfaceRateForConnection(int cellIdx, int phaseIdx) const
Definition: WellInterface_impl.hpp:1411
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:98
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:2482
void getTw(std::vector< Value > &wi, const int perf, const IntensiveQuantities &intQuants, const Value &trans_mult, const SingleWellStateType &ws) const
Definition: WellInterface_impl.hpp:2152
void getMobility(const Simulator &simulator, const int local_perf_index, std::vector< Value > &mob, Callback &extendEval, DeferredLogger &deferred_logger) const
Definition: WellInterface_impl.hpp:2364
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:2014
void solveWellEquation(const Simulator &simulator, const GroupStateHelperType &groupStateHelper, WellStateType &well_state)
Definition: WellInterface_impl.hpp:1150
void updateConnectionDFactor(const Simulator &simulator, SingleWellStateType &ws) const
Definition: WellInterface_impl.hpp:2243
Eval getPerfCellPressure(const FluidState &fs) const
Definition: WellInterface_impl.hpp:2336
void initializeProducerWellState(const Simulator &simulator, WellStateType &well_state, DeferredLogger &deferred_logger) const
Definition: WellInterface_impl.hpp:2064
virtual void updateWellStateWithTarget(const Simulator &simulator, const GroupStateHelperType &groupStateHelper, WellStateType &well_state) const
Definition: WellInterface_impl.hpp:1589
void addCellRates(std::map< int, RateVector > &cellRates_) const
Definition: WellInterface_impl.hpp:1392
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:1971
GetPropType< TypeTag, Properties::RateVector > RateVector
Definition: WellInterface.hpp:92
void updateConnectionTransmissibilityFactor(const Simulator &simulator, SingleWellStateType &ws) const
Definition: WellInterface_impl.hpp:2305
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:2551
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:2585
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:975
Scalar wsalt() const
Definition: WellInterface_impl.hpp:144
bool solveWellWithZeroRate(const Simulator &simulator, const double dt, const GroupStateHelperType &groupStateHelper, WellStateType &well_state)
Definition: WellInterface_impl.hpp:1062
bool wellUnderZeroGroupRateTarget(const GroupStateHelperType &groupStateHelper, const std::optional< bool > group_control=std::nullopt) const
Definition: WellInterface_impl.hpp:1988
bool solveWellWithBhp(const Simulator &simulator, const double dt, const Scalar bhp, const GroupStateHelperType &groupStateHelper, WellStateType &well_state)
Definition: WellInterface_impl.hpp:1012
void prepareWellBeforeAssembling(const Simulator &simulator, const double dt, const GroupStateHelperType &groupStateHelper, WellStateType &well_state)
Definition: WellInterface_impl.hpp:1265
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:501
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:61
bool updateWellStateWithTHPTargetProd(const Simulator &simulator, WellStateType &well_state, const GroupStateHelperType &groupStateHelper) const
Definition: WellInterface_impl.hpp:2450
bool iterateWellEquations(const Simulator &simulator, const double dt, const GroupStateHelperType &groupStateHelper, WellStateType &well_state)
Definition: WellInterface_impl.hpp:658
Scalar wpolymer() const
Definition: WellInterface_impl.hpp:114
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:192
Scalar wurea() const
Definition: WellInterface_impl.hpp:180
void updateGroupTargetFallbackFlag(WellStateType &well_state, DeferredLogger &deferred_logger) const
Definition: WellInterface_impl.hpp:1250
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:2627
void assembleWellEq(const Simulator &simulator, const double dt, const GroupStateHelperType &groupStateHelper, WellStateType &well_state)
Definition: WellInterface_impl.hpp:1212
Scalar wmicrobes() const
Definition: WellInterface_impl.hpp:156
virtual void scaleSegmentRatesAndPressure(WellStateType &well_state) const
Definition: WellInterface_impl.hpp:1581
static constexpr bool has_zFraction
Definition: WellInterface.hpp:119
void consolidatePhaseMixingRates(WellStateType &well_state) const
Definition: WellInterface_impl.hpp:737
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:183
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