22#ifndef OPM_STANDARDWELL_IMPL_HEADER_INCLUDED
23#define OPM_STANDARDWELL_IMPL_HEADER_INCLUDED
26#ifndef OPM_STANDARDWELL_HEADER_INCLUDED
31#include <opm/common/Exceptions.hpp>
33#include <opm/input/eclipse/Units/Units.hpp>
46#include <fmt/format.h>
51 template<
typename TypeTag>
58 const int pvtRegionIdx,
59 const int num_conservation_quantities,
61 const int index_of_well,
63 :
Base(well, pw_info, time_step, param, rate_converter, pvtRegionIdx, num_conservation_quantities, num_phases, index_of_well, perf_data)
74 template<
typename TypeTag>
77 init(
const std::vector<Scalar>& depth_arg,
79 const std::vector< Scalar >& B_avg,
80 const bool changed_to_open_this_step)
82 Base::init(depth_arg, gravity_arg, B_avg, changed_to_open_this_step);
83 this->StdWellEval::init(this->perf_depth_, depth_arg, Base::has_polymermw);
90 template<
typename TypeTag>
95 const std::vector<Value>& mob,
97 const std::vector<Value>& Tw,
100 std::vector<Value>& cq_s,
104 auto obtain = [
this](
const Eval& value)
106 if constexpr (std::is_same_v<Value, Scalar>) {
107 static_cast<void>(
this);
108 return getValue(value);
110 return this->extendEval(value);
113 auto obtainN = [](
const auto& value)
115 if constexpr (std::is_same_v<Value, Scalar>) {
116 return getValue(value);
121 auto zeroElem = [
this]()
123 if constexpr (std::is_same_v<Value, Scalar>) {
124 static_cast<void>(
this);
127 return Value{this->primary_variables_.numWellEq() + Indices::numEq, 0.0};
131 const auto& fs = intQuants.fluidState();
132 const Value pressure = obtain(this->getPerfCellPressure(fs));
133 const Value rs = obtain(fs.Rs());
134 const Value rv = obtain(fs.Rv());
135 const Value rvw = obtain(fs.Rvw());
136 const Value rsw = obtain(fs.Rsw());
138 std::vector<Value> b_perfcells_dense(this->numConservationQuantities(), zeroElem());
139 for (
unsigned phaseIdx = 0; phaseIdx < FluidSystem::numPhases; ++phaseIdx) {
140 if (!FluidSystem::phaseIsActive(phaseIdx)) {
143 const unsigned compIdx = FluidSystem::canonicalToActiveCompIdx(FluidSystem::solventComponentIndex(phaseIdx));
144 b_perfcells_dense[compIdx] = obtain(fs.invB(phaseIdx));
146 if constexpr (has_solvent) {
147 b_perfcells_dense[Indices::contiSolventEqIdx] = obtain(intQuants.solventInverseFormationVolumeFactor());
150 if constexpr (has_zFraction) {
151 if (this->isInjector()) {
152 const unsigned gasCompIdx = FluidSystem::canonicalToActiveCompIdx(FluidSystem::gasCompIdx);
153 b_perfcells_dense[gasCompIdx] *= (1.0 - this->wsolvent());
154 b_perfcells_dense[gasCompIdx] += this->wsolvent()*intQuants.zPureInvFormationVolumeFactor().value();
158 Value skin_pressure = zeroElem();
160 if (this->isInjector()) {
161 const int pskin_index = Bhp + 1 + this->numLocalPerfs() + perf;
162 skin_pressure = obtainN(this->primary_variables_.eval(pskin_index));
167 std::vector<Value> cmix_s(this->numConservationQuantities(), zeroElem());
168 for (
int componentIdx = 0; componentIdx < this->numConservationQuantities(); ++componentIdx) {
169 cmix_s[componentIdx] = obtainN(this->primary_variables_.surfaceVolumeFraction(componentIdx));
192 template<
typename TypeTag>
193 template<
class Value>
197 const Value& pressure,
203 std::vector<Value>& b_perfcells_dense,
204 const std::vector<Value>& Tw,
207 const Value& skin_pressure,
208 const std::vector<Value>& cmix_s,
209 std::vector<Value>& cq_s,
214 const Value well_pressure = bhp + this->connections_.pressure_diff(perf);
215 Value drawdown = pressure - well_pressure;
216 if (this->isInjector()) {
217 drawdown += skin_pressure;
221 FluidSystem::phaseIsActive(FluidSystem::gasPhaseIdx)
222 ? FluidSystem::canonicalToActiveCompIdx(FluidSystem::gasCompIdx)
224 FluidSystem::phaseIsActive(FluidSystem::oilPhaseIdx)
225 ? FluidSystem::canonicalToActiveCompIdx(FluidSystem::oilCompIdx)
227 FluidSystem::phaseIsActive(FluidSystem::waterPhaseIdx)
228 ? FluidSystem::canonicalToActiveCompIdx(FluidSystem::waterCompIdx)
236 if (!allow_cf && this->isInjector()) {
241 for (
int componentIdx = 0; componentIdx < this->numConservationQuantities(); ++componentIdx) {
242 const Value cq_p = - Tw[componentIdx] * (mob[componentIdx] * drawdown);
243 cq_s[componentIdx] = b_perfcells_dense[componentIdx] * cq_p;
246 if (FluidSystem::phaseIsActive(FluidSystem::oilPhaseIdx) &&
247 FluidSystem::phaseIsActive(FluidSystem::gasPhaseIdx))
249 ratioCalc.gasOilPerfRateProd(cq_s, perf_rates, rv, rs, rvw,
250 FluidSystem::phaseIsActive(FluidSystem::waterPhaseIdx),
252 }
else if (FluidSystem::phaseIsActive(FluidSystem::waterPhaseIdx) &&
253 FluidSystem::phaseIsActive(FluidSystem::gasPhaseIdx))
255 ratioCalc.gasWaterPerfRateProd(cq_s, perf_rates, rvw, rsw, this->isProducer());
259 if (!allow_cf && this->isProducer()) {
264 Value total_mob_dense = mob[0];
265 for (
int componentIdx = 1; componentIdx < this->numConservationQuantities(); ++componentIdx) {
266 total_mob_dense += mob[componentIdx];
270 Value volumeRatio = bhp * 0.0;
272 if (FluidSystem::enableVaporizedWater() && FluidSystem::enableDissolvedGasInWater()) {
273 ratioCalc.disOilVapWatVolumeRatio(volumeRatio, rvw, rsw, pressure,
274 cmix_s, b_perfcells_dense, deferred_logger);
278 assert(FluidSystem::phaseIsActive(FluidSystem::gasPhaseIdx));
279 assert(FluidSystem::phaseIsActive(FluidSystem::waterPhaseIdx));
280 assert(!FluidSystem::phaseIsActive(FluidSystem::oilPhaseIdx));
283 if (FluidSystem::phaseIsActive(FluidSystem::waterPhaseIdx)) {
284 const unsigned waterCompIdx = FluidSystem::canonicalToActiveCompIdx(FluidSystem::waterCompIdx);
285 volumeRatio += cmix_s[waterCompIdx] / b_perfcells_dense[waterCompIdx];
288 if constexpr (Indices::enableSolvent) {
289 volumeRatio += cmix_s[Indices::contiSolventEqIdx] / b_perfcells_dense[Indices::contiSolventEqIdx];
292 if (FluidSystem::phaseIsActive(FluidSystem::oilPhaseIdx) &&
293 FluidSystem::phaseIsActive(FluidSystem::gasPhaseIdx))
295 ratioCalc.gasOilVolumeRatio(volumeRatio, rv, rs, pressure,
296 cmix_s, b_perfcells_dense,
299 if (FluidSystem::phaseIsActive(FluidSystem::oilPhaseIdx)) {
300 const unsigned oilCompIdx = FluidSystem::canonicalToActiveCompIdx(FluidSystem::oilCompIdx);
301 volumeRatio += cmix_s[oilCompIdx] / b_perfcells_dense[oilCompIdx];
303 if (FluidSystem::phaseIsActive(FluidSystem::gasPhaseIdx)) {
304 const unsigned gasCompIdx = FluidSystem::canonicalToActiveCompIdx(FluidSystem::gasCompIdx);
305 volumeRatio += cmix_s[gasCompIdx] / b_perfcells_dense[gasCompIdx];
311 for (
int componentIdx = 0; componentIdx < this->numConservationQuantities(); ++componentIdx) {
312 const Value cqt_i = - Tw[componentIdx] * (total_mob_dense * drawdown);
313 Value cqt_is = cqt_i / volumeRatio;
314 cq_s[componentIdx] = cmix_s[componentIdx] * cqt_is;
318 if (this->isProducer()) {
319 if (FluidSystem::phaseIsActive(FluidSystem::oilPhaseIdx) &&
320 FluidSystem::phaseIsActive(FluidSystem::gasPhaseIdx))
322 ratioCalc.gasOilPerfRateInj(cq_s, perf_rates,
323 rv, rs, pressure, rvw,
324 FluidSystem::phaseIsActive(FluidSystem::waterPhaseIdx),
327 if (FluidSystem::phaseIsActive(FluidSystem::gasPhaseIdx) &&
328 FluidSystem::phaseIsActive(FluidSystem::waterPhaseIdx))
331 ratioCalc.gasWaterPerfRateInj(cq_s, perf_rates, rvw, rsw,
332 pressure, deferred_logger);
339 template<
typename TypeTag>
345 const Well::InjectionControls& inj_controls,
346 const Well::ProductionControls& prod_controls,
348 const bool solving_with_zero_rate)
352 if (!this->isOperableAndSolvable() && !this->wellIsStopped())
return;
355 this->linSys_.clear();
357 assembleWellEqWithoutIterationImpl(simulator, groupStateHelper, dt, inj_controls,
358 prod_controls, well_state, solving_with_zero_rate);
364 template<
typename TypeTag>
370 const Well::InjectionControls& inj_controls,
371 const Well::ProductionControls& prod_controls,
373 const bool solving_with_zero_rate)
378 const Scalar regularization_factor = this->regularize_? this->param_.regularization_factor_wells_ : 1.0;
379 const Scalar volume = 0.1 * unit::cubic(unit::feet) * regularization_factor;
381 auto& ws = well_state.
well(this->index_of_well_);
382 ws.phase_mixing_rates.fill(0.0);
383 if constexpr (has_energy) {
384 ws.energy_rate = 0.0;
388 const int np = this->number_of_phases_;
390 std::vector<RateVector> connectionRates = this->connectionRates_;
392 auto& perf_data = ws.perf_data;
393 auto& perf_rates = perf_data.phase_rates;
394 for (
int perf = 0; perf < this->number_of_local_perforations_; ++perf) {
396 std::vector<EvalWell> cq_s(this->num_conservation_quantities_, 0.0);
399 calculateSinglePerf(simulator, perf, well_state, connectionRates,
400 cq_s, water_flux_s, cq_s_zfrac_effective, deferred_logger);
403 if constexpr (has_polymer && Base::has_polymermw) {
404 if (this->isInjector()) {
405 handleInjectivityEquations(simulator, well_state, perf,
406 water_flux_s, deferred_logger);
409 for (
int componentIdx = 0; componentIdx < this->num_conservation_quantities_; ++componentIdx) {
411 const EvalWell cq_s_effective = cq_s[componentIdx] * this->well_efficiency_factor_;
413 connectionRates[perf][componentIdx] = Base::restrictEval(cq_s_effective);
416 assemblePerforationEq(cq_s_effective,
419 this->primary_variables_.numWellEq(),
423 if (has_solvent && componentIdx == Indices::contiSolventEqIdx) {
424 auto& perf_rate_solvent = perf_data.solvent_rates;
425 perf_rate_solvent[perf] = cq_s[componentIdx].value();
427 perf_rates[perf*np + FluidSystem::activeCompToActivePhaseIdx(componentIdx)] = cq_s[componentIdx].value();
431 if constexpr (has_zFraction) {
433 assembleZFracEq(cq_s_zfrac_effective,
435 this->primary_variables_.numWellEq(),
440 this->connectionRates_ = connectionRates;
445 const auto& comm = this->parallel_well_info_.communication();
446 comm.sum(ws.phase_mixing_rates.data(), ws.phase_mixing_rates.size());
450 this->linSys_.sumDistributed(this->parallel_well_info_.communication());
453 for (
int componentIdx = 0; componentIdx < numWellConservationEq; ++componentIdx) {
457 if (FluidSystem::numActivePhases() > 1) {
459 resWell_loc += (this->primary_variables_.surfaceVolumeFraction(componentIdx) -
460 this->F0_[componentIdx]) * volume / dt;
462 resWell_loc -= this->primary_variables_.getQs(componentIdx) * this->well_efficiency_factor_;
464 assembleSourceEq(resWell_loc,
466 this->primary_variables_.numWellEq(),
470 const bool stopped_or_zero_target = this->stoppedOrZeroRateTarget(groupStateHelper);
476 auto& group_state = solving_with_zero_rate
480 if (this->wellUnderGroupControl(ws) && this->isProducer() && !stopped_or_zero_target) {
481 this->updateGroupTargetFallbackFlag(well_state, deferred_logger);
484 auto group_guard = groupStateHelper_copy.
pushGroupState(group_state);
486 assembleControlEq(groupStateHelper_copy,
487 inj_controls, prod_controls,
488 this->primary_variables_,
489 this->getRefDensity(),
491 stopped_or_zero_target);
496 this->linSys_.invert();
498 OPM_DEFLOG_PROBLEM(NumericalProblem,
"Error when inverting local well equations for well " + name(), deferred_logger);
505 template<
typename TypeTag>
511 std::vector<RateVector>& connectionRates,
512 std::vector<EvalWell>& cq_s,
517 const bool allow_cf = this->getAllowCrossFlow() || openCrossFlowAvoidSingularity(simulator);
518 const EvalWell& bhp = this->primary_variables_.eval(Bhp);
519 const int cell_idx = this->well_cells_[perf];
520 const auto& intQuants = simulator.model().intensiveQuantities(cell_idx, 0);
521 std::vector<EvalWell> mob(this->num_conservation_quantities_, {0.});
522 getMobility(simulator, perf, mob, deferred_logger);
526 getTransMult(trans_mult, simulator, cell_idx);
527 const auto& wellstate_nupcol = simulator.problem().wellModel().nupcolWellState().well(this->index_of_well_);
528 std::vector<EvalWell> Tw(this->num_conservation_quantities_, this->well_index_[perf] * trans_mult);
529 this->getTw(Tw, perf, intQuants, trans_mult, wellstate_nupcol);
530 computePerfRate(intQuants, mob, bhp, Tw, perf, allow_cf,
531 cq_s, perf_rates, deferred_logger);
533 auto& ws = well_state.
well(this->index_of_well_);
534 auto& perf_data = ws.perf_data;
535 if constexpr (has_polymer && Base::has_polymermw) {
536 if (this->isInjector()) {
539 const unsigned water_comp_idx = FluidSystem::canonicalToActiveCompIdx(FluidSystem::waterCompIdx);
540 water_flux_s = cq_s[water_comp_idx];
543 handleInjectivityRate(simulator, perf, cq_s);
548 if (this->isProducer()) {
549 ws.phase_mixing_rates[ws.dissolved_gas] += perf_rates.
dis_gas;
550 ws.phase_mixing_rates[ws.dissolved_gas_in_water] += perf_rates.
dis_gas_in_water;
551 ws.phase_mixing_rates[ws.vaporized_oil] += perf_rates.
vap_oil;
552 ws.phase_mixing_rates[ws.vaporized_water] += perf_rates.
vap_wat;
553 perf_data.phase_mixing_rates[perf][ws.dissolved_gas] = perf_rates.
dis_gas;
554 perf_data.phase_mixing_rates[perf][ws.dissolved_gas_in_water] = perf_rates.
dis_gas_in_water;
555 perf_data.phase_mixing_rates[perf][ws.vaporized_oil] = perf_rates.
vap_oil;
556 perf_data.phase_mixing_rates[perf][ws.vaporized_water] = perf_rates.
vap_wat;
559 if constexpr (has_energy) {
560 connectionRates[perf][Indices::contiEnergyEqIdx] =
561 connectionRateEnergy(cq_s, intQuants, deferred_logger);
562 ws.energy_rate += getValue(connectionRates[perf][Indices::contiEnergyEqIdx]);
565 if constexpr (has_polymer) {
566 std::variant<Scalar,EvalWell> polymerConcentration;
567 if (this->isInjector()) {
568 polymerConcentration = this->wpolymer();
570 polymerConcentration = this->extendEval(intQuants.polymerConcentration() *
571 intQuants.polymerViscosityCorrection());
574 [[maybe_unused]]
EvalWell cq_s_poly;
575 std::tie(connectionRates[perf][Indices::contiPolymerEqIdx],
577 this->connections_.connectionRatePolymer(perf_data.polymer_rates[perf],
578 cq_s, polymerConcentration);
580 if constexpr (Base::has_polymermw) {
581 updateConnectionRatePolyMW(cq_s_poly, intQuants, well_state,
582 perf, connectionRates, deferred_logger);
586 if constexpr (has_foam) {
587 std::variant<Scalar,EvalWell> foamConcentration;
588 if (this->isInjector()) {
589 foamConcentration = this->wfoam();
591 foamConcentration = this->extendEval(intQuants.foamConcentration());
593 connectionRates[perf][Indices::contiFoamEqIdx] =
594 this->connections_.connectionRateFoam(cq_s, foamConcentration,
595 FoamModule::transportPhase(),
599 if constexpr (has_zFraction) {
600 std::variant<Scalar,std::array<EvalWell,2>> solventConcentration;
601 if (this->isInjector()) {
602 solventConcentration = this->wsolvent();
604 solventConcentration = std::array{this->extendEval(intQuants.xVolume()),
605 this->extendEval(intQuants.yVolume())};
607 std::tie(connectionRates[perf][Indices::contiZfracEqIdx],
608 cq_s_zfrac_effective) =
609 this->connections_.connectionRatezFraction(perf_data.solvent_rates[perf],
611 solventConcentration);
614 if constexpr (has_brine) {
615 std::variant<Scalar,EvalWell> saltConcentration;
616 if (this->isInjector()) {
617 saltConcentration = this->wsalt();
619 saltConcentration = this->extendEval(intQuants.fluidState().saltConcentration());
622 connectionRates[perf][Indices::contiBrineEqIdx] =
623 this->connections_.connectionRateBrine(perf_data.brine_rates[perf],
628 if constexpr (has_bioeffects) {
629 std::variant<Scalar,EvalWell> microbialConcentration;
630 if constexpr (has_micp) {
631 std::variant<Scalar,EvalWell> oxygenConcentration;
632 std::variant<Scalar,EvalWell> ureaConcentration;
633 if (this->isInjector()) {
634 microbialConcentration = this->wmicrobes();
635 oxygenConcentration = this->woxygen();
636 ureaConcentration = this->wurea();
638 microbialConcentration = this->extendEval(intQuants.microbialConcentration());
639 oxygenConcentration = this->extendEval(intQuants.oxygenConcentration());
640 ureaConcentration = this->extendEval(intQuants.ureaConcentration());
642 std::tie(connectionRates[perf][Indices::contiMicrobialEqIdx],
643 connectionRates[perf][Indices::contiOxygenEqIdx],
644 connectionRates[perf][Indices::contiUreaEqIdx]) =
645 this->connections_.connectionRatesMICP(perf_data.microbial_rates[perf],
646 perf_data.oxygen_rates[perf],
647 perf_data.urea_rates[perf],
649 microbialConcentration,
654 if (this->isProducer()) {
655 microbialConcentration = this->extendEval(intQuants.microbialConcentration());
656 connectionRates[perf][Indices::contiMicrobialEqIdx] =
657 this->connections_.connectionRateBioeffects(perf_data.microbial_rates[perf],
659 microbialConcentration);
665 perf_data.pressure[perf] = ws.bhp + this->connections_.pressure_diff(perf);
668 if (FluidSystem::phaseUsage().hasCO2orH2Store()) {
669 const unsigned gas_comp_idx = FluidSystem::canonicalToActiveCompIdx(FluidSystem::gasCompIdx);
670 const Scalar rho = FluidSystem::referenceDensity( FluidSystem::gasPhaseIdx, Base::pvtRegionIdx() );
671 perf_data.gas_mass_rates[perf] = cq_s[gas_comp_idx].value() * rho;
675 if (FluidSystem::phaseIsActive(FluidSystem::waterPhaseIdx)) {
676 const unsigned wat_comp_idx = FluidSystem::canonicalToActiveCompIdx(FluidSystem::waterCompIdx);
677 const Scalar rho = FluidSystem::referenceDensity( FluidSystem::waterPhaseIdx, Base::pvtRegionIdx() );
678 perf_data.wat_mass_rates[perf] = cq_s[wat_comp_idx].value() * rho;
682 template<
typename TypeTag>
683 template<
class Value>
688 const int cell_idx)
const
690 auto obtain = [
this](
const Eval& value)
692 if constexpr (std::is_same_v<Value, Scalar>) {
693 static_cast<void>(
this);
694 return getValue(value);
696 return this->extendEval(value);
702 template<
typename TypeTag>
703 template<
class Value>
708 std::vector<Value>& mob,
711 auto obtain = [
this](
const Eval& value)
713 if constexpr (std::is_same_v<Value, Scalar>) {
714 static_cast<void>(
this);
715 return getValue(value);
717 return this->extendEval(value);
721 obtain, deferred_logger);
724 if constexpr (has_polymer) {
725 if (!FluidSystem::phaseIsActive(FluidSystem::waterPhaseIdx)) {
726 OPM_DEFLOG_THROW(std::runtime_error,
"Water is required when polymer is active", deferred_logger);
731 if constexpr (!Base::has_polymermw) {
732 if constexpr (std::is_same_v<Value, Scalar>) {
733 std::vector<EvalWell> mob_eval(this->num_conservation_quantities_, 0.);
734 for (std::size_t i = 0; i < mob.size(); ++i) {
735 mob_eval[i].setValue(mob[i]);
737 updateWaterMobilityWithPolymer(simulator, perf, mob_eval, deferred_logger);
738 for (std::size_t i = 0; i < mob.size(); ++i) {
739 mob[i] = getValue(mob_eval[i]);
742 updateWaterMobilityWithPolymer(simulator, perf, mob, deferred_logger);
749 const Scalar bhp = this->primary_variables_.value(Bhp);
750 const Scalar perf_press = bhp + this->connections_.pressure_diff(perf);
751 const Scalar multiplier = this->getInjMult(perf, bhp, perf_press, deferred_logger);
752 for (std::size_t i = 0; i < mob.size(); ++i) {
753 mob[i] *= multiplier;
759 template<
typename TypeTag>
767 if (!this->isOperableAndSolvable() && !this->wellIsStopped())
return;
771 const bool stop_or_zero_rate_target = this->stoppedOrZeroRateTarget(groupStateHelper);
772 updatePrimaryVariablesNewton(dwells, stop_or_zero_rate_target, deferred_logger);
774 const auto& summary_state = simulator.vanguard().summaryState();
775 updateWellStateFromPrimaryVariables(well_state, summary_state, deferred_logger);
779 const bool isThermal = simulator.vanguard().eclState().getSimulationConfig().isThermal();
780 const bool co2store = simulator.vanguard().eclState().runspec().co2Storage();
781 Base::calculateReservoirRates( (isThermal || co2store), well_state.
well(this->index_of_well_));
788 template<
typename TypeTag>
792 const bool stop_or_zero_rate_target,
795 const Scalar dFLimit = this->param_.dwell_fraction_max_;
796 const Scalar dBHPLimit = this->param_.dbhp_max_rel_;
797 this->primary_variables_.updateNewton(dwells, stop_or_zero_rate_target, dFLimit, dBHPLimit, deferred_logger);
800 if constexpr (Base::has_polymermw) {
801 this->primary_variables_.updateNewtonPolyMW(dwells);
804 this->primary_variables_.checkFinite(deferred_logger,
"Newton update");
811 template<
typename TypeTag>
815 const SummaryState& summary_state,
818 this->primary_variables_.copyToWellState(well_state, deferred_logger);
821 updateThp(getRefDensity(),
822 [
this,&well_state]() {
return this->baseif_.getALQ(well_state); },
823 well_state, summary_state, deferred_logger);
826 if constexpr (Base::has_polymermw) {
827 this->primary_variables_.copyToWellStatePolyMW(well_state);
835 template<
typename TypeTag>
843 std::ranges::fill(this->ipr_a_, 0.0);
844 std::ranges::fill(this->ipr_b_, 0.0);
846 for (
int perf = 0; perf < this->number_of_local_perforations_; ++perf) {
847 std::vector<Scalar> mob(this->num_conservation_quantities_, 0.0);
848 getMobility(simulator, perf, mob, deferred_logger);
850 const int cell_idx = this->well_cells_[perf];
851 const auto& int_quantities = simulator.model().intensiveQuantities(cell_idx, 0);
852 const auto& fs = int_quantities.fluidState();
854 Scalar p_r = this->getPerfCellPressure(fs).value();
857 std::vector<Scalar> b_perf(this->num_conservation_quantities_);
858 for (std::size_t phase = 0; phase < FluidSystem::numPhases; ++phase) {
859 if (!FluidSystem::phaseIsActive(phase)) {
862 const unsigned comp_idx = FluidSystem::canonicalToActiveCompIdx(FluidSystem::solventComponentIndex(phase));
863 b_perf[comp_idx] = fs.invB(phase).value();
865 if constexpr (has_solvent) {
866 b_perf[Indices::contiSolventEqIdx] = int_quantities.solventInverseFormationVolumeFactor().value();
870 const Scalar h_perf = this->connections_.pressure_diff(perf);
871 const Scalar pressure_diff = p_r - h_perf;
876 if ( (this->isProducer() && pressure_diff < 0.) || (this->isInjector() && pressure_diff > 0.) ) {
877 deferred_logger.
debug(
"CROSSFLOW_IPR",
878 "cross flow found when updateIPR for well " + name()
879 +
" . The connection is ignored in IPR calculations");
886 getTransMult(trans_mult, simulator, cell_idx);
887 const auto& wellstate_nupcol = simulator.problem().wellModel().nupcolWellState().well(this->index_of_well_);
888 std::vector<Scalar> tw_perf(this->num_conservation_quantities_, this->well_index_[perf] * trans_mult);
889 this->getTw(tw_perf, perf, int_quantities, trans_mult, wellstate_nupcol);
890 std::vector<Scalar> ipr_a_perf(this->ipr_a_.size());
891 std::vector<Scalar> ipr_b_perf(this->ipr_b_.size());
892 for (
int comp_idx = 0; comp_idx < this->num_conservation_quantities_; ++comp_idx) {
893 const Scalar tw_mob = tw_perf[comp_idx] * mob[comp_idx] * b_perf[comp_idx];
894 ipr_a_perf[comp_idx] += tw_mob * pressure_diff;
895 ipr_b_perf[comp_idx] += tw_mob;
899 if (FluidSystem::phaseIsActive(FluidSystem::oilPhaseIdx) && FluidSystem::phaseIsActive(FluidSystem::gasPhaseIdx)) {
900 const unsigned oil_comp_idx = FluidSystem::canonicalToActiveCompIdx(FluidSystem::oilCompIdx);
901 const unsigned gas_comp_idx = FluidSystem::canonicalToActiveCompIdx(FluidSystem::gasCompIdx);
902 const Scalar rs = (fs.Rs()).value();
903 const Scalar rv = (fs.Rv()).value();
905 const Scalar dis_gas_a = rs * ipr_a_perf[oil_comp_idx];
906 const Scalar vap_oil_a = rv * ipr_a_perf[gas_comp_idx];
908 ipr_a_perf[gas_comp_idx] += dis_gas_a;
909 ipr_a_perf[oil_comp_idx] += vap_oil_a;
911 const Scalar dis_gas_b = rs * ipr_b_perf[oil_comp_idx];
912 const Scalar vap_oil_b = rv * ipr_b_perf[gas_comp_idx];
914 ipr_b_perf[gas_comp_idx] += dis_gas_b;
915 ipr_b_perf[oil_comp_idx] += vap_oil_b;
918 for (std::size_t comp_idx = 0; comp_idx < ipr_a_perf.size(); ++comp_idx) {
919 this->ipr_a_[comp_idx] += ipr_a_perf[comp_idx];
920 this->ipr_b_[comp_idx] += ipr_b_perf[comp_idx];
923 this->parallel_well_info_.communication().sum(this->ipr_a_.data(), this->ipr_a_.size());
924 this->parallel_well_info_.communication().sum(this->ipr_b_.data(), this->ipr_b_.size());
927 template<
typename TypeTag>
942 auto rates = well_state.
well(this->index_of_well_).surface_rates;
944 for (std::size_t p = 0; p < rates.size(); ++p) {
945 zero_rates &= rates[p] == 0.0;
947 auto& ws = well_state.
well(this->index_of_well_);
949 const auto msg = fmt::format(
"updateIPRImplicit: Well {} has zero rate, IPRs might be problematic", this->name());
950 deferred_logger.debug(msg);
963 std::ranges::fill(ws.implicit_ipr_a, 0.0);
964 std::ranges::fill(ws.implicit_ipr_b, 0.0);
966 auto inj_controls = Well::InjectionControls(0);
967 auto prod_controls = Well::ProductionControls(0);
968 prod_controls.addControl(Well::ProducerCMode::BHP);
969 prod_controls.bhp_limit = well_state.
well(this->index_of_well_).bhp;
972 const auto cmode = ws.production_cmode;
973 ws.production_cmode = Well::ProducerCMode::BHP;
974 const double dt = simulator.timeStepSize();
975 assembleWellEqWithoutIteration(simulator, groupStateHelper, dt, inj_controls, prod_controls, well_state,
978 const size_t nEq = this->primary_variables_.numWellEq();
982 for (
size_t i=0; i < nEq; ++i){
988 x_well[0].resize(nEq);
989 this->linSys_.solve(rhs, x_well);
991 for (
int comp_idx = 0; comp_idx < this->num_conservation_quantities_; ++comp_idx){
992 EvalWell comp_rate = this->primary_variables_.getQs(comp_idx);
993 const int idx = FluidSystem::activeCompToActivePhaseIdx(comp_idx);
994 for (
size_t pvIdx = 0; pvIdx < nEq; ++pvIdx) {
996 ws.implicit_ipr_b[idx] -= x_well[0][pvIdx]*comp_rate.derivative(pvIdx+Indices::numEq);
998 ws.implicit_ipr_a[idx] = ws.implicit_ipr_b[idx]*ws.bhp - comp_rate.value();
1001 ws.production_cmode = cmode;
1004 template<
typename TypeTag>
1011 const auto& summaryState = simulator.vanguard().summaryState();
1015 const bool bhp_limit_not_defaulted = bhp_limit > 1.5 * unit::barsa;
1016 if ( bhp_limit_not_defaulted || !this->wellHasTHPConstraints(summaryState) ) {
1019 Scalar total_ipr_mass_rate = 0.0;
1020 for (
unsigned phaseIdx = 0; phaseIdx < FluidSystem::numPhases; ++phaseIdx)
1022 if (!FluidSystem::phaseIsActive(phaseIdx)) {
1026 const unsigned compIdx = FluidSystem::canonicalToActiveCompIdx(FluidSystem::solventComponentIndex(phaseIdx));
1027 const Scalar ipr_rate = this->ipr_a_[compIdx] - this->ipr_b_[compIdx] * bhp_limit;
1029 const Scalar rho = FluidSystem::referenceDensity( phaseIdx, Base::pvtRegionIdx() );
1030 total_ipr_mass_rate += ipr_rate * rho;
1032 if ( (this->isProducer() && total_ipr_mass_rate < 0.) || (this->isInjector() && total_ipr_mass_rate > 0.) ) {
1033 this->operability_status_.operable_under_only_bhp_limit =
false;
1037 if (this->operability_status_.operable_under_only_bhp_limit && this->wellHasTHPConstraints(summaryState)) {
1041 std::vector<Scalar> well_rates_bhp_limit;
1042 computeWellRatesWithBhp(simulator, bhp_limit, well_rates_bhp_limit, deferred_logger);
1044 this->adaptRatesForVFP(well_rates_bhp_limit);
1045 const Scalar thp_limit = this->getTHPConstraint(summaryState);
1048 this->getRefDensity(),
1049 this->getALQ(well_state),
1052 if ( (this->isProducer() && thp < thp_limit) || (this->isInjector() && thp > thp_limit) ) {
1053 this->operability_status_.obey_thp_limit_under_bhp_limit =
false;
1064 this->operability_status_.operable_under_only_bhp_limit =
true;
1065 this->operability_status_.obey_thp_limit_under_bhp_limit =
false;
1073 template<
typename TypeTag>
1081 const auto& summaryState = simulator.vanguard().summaryState();
1082 const auto obtain_bhp = this->isProducer() ? computeBhpAtThpLimitProd(well_state, simulator, groupStateHelper, summaryState)
1083 : computeBhpAtThpLimitInj(simulator, groupStateHelper, summaryState);
1086 this->operability_status_.can_obtain_bhp_with_thp_limit =
true;
1089 this->operability_status_.obey_bhp_limit_with_thp_limit = this->isProducer() ?
1090 *obtain_bhp >= bhp_limit : *obtain_bhp <= bhp_limit ;
1092 const Scalar thp_limit = this->getTHPConstraint(summaryState);
1093 if (this->isProducer() && *obtain_bhp < thp_limit) {
1094 const std::string msg =
" obtained bhp " +
std::to_string(unit::convert::to(*obtain_bhp, unit::barsa))
1095 +
" bars is SMALLER than thp limit "
1097 +
" bars as a producer for well " + name();
1098 deferred_logger.debug(msg);
1100 else if (this->isInjector() && *obtain_bhp > thp_limit) {
1101 const std::string msg =
" obtained bhp " +
std::to_string(unit::convert::to(*obtain_bhp, unit::barsa))
1102 +
" bars is LARGER than thp limit "
1104 +
" bars as a injector for well " + name();
1105 deferred_logger.debug(msg);
1108 this->operability_status_.can_obtain_bhp_with_thp_limit =
false;
1109 this->operability_status_.obey_bhp_limit_with_thp_limit =
false;
1110 if (!this->wellIsStopped()) {
1111 const Scalar thp_limit = this->getTHPConstraint(summaryState);
1112 deferred_logger.debug(
" could not find bhp value at thp limit "
1114 +
" bar for well " + name() +
", the well might need to be closed ");
1123 template<
typename TypeTag>
1128 bool all_drawdown_wrong_direction =
true;
1130 for (
int perf = 0; perf < this->number_of_local_perforations_; ++perf) {
1131 const int cell_idx = this->well_cells_[perf];
1132 const auto& intQuants = simulator.model().intensiveQuantities(cell_idx, 0);
1133 const auto& fs = intQuants.fluidState();
1135 const Scalar pressure = this->getPerfCellPressure(fs).value();
1136 const Scalar bhp = this->primary_variables_.eval(Bhp).value();
1139 const Scalar well_pressure = bhp + this->connections_.pressure_diff(perf);
1140 const Scalar drawdown = pressure - well_pressure;
1145 if ( (drawdown < 0. && this->isInjector()) ||
1146 (drawdown > 0. && this->isProducer()) ) {
1147 all_drawdown_wrong_direction =
false;
1152 const auto& comm = this->parallel_well_info_.communication();
1153 if (comm.size() > 1)
1155 all_drawdown_wrong_direction =
1156 (comm.min(all_drawdown_wrong_direction ? 1 : 0) == 1);
1159 return all_drawdown_wrong_direction;
1165 template<
typename TypeTag>
1170 return !this->getAllowCrossFlow() && allDrawDownWrongDirection(simulator);
1176 template<
typename TypeTag>
1182 auto prop_func =
typename StdWellEval::StdWellConnections::PressurePropertyFunctions {
1184 [&model = simulator.model()](
int cell_idx,
int phase_idx)
1186 return model.intensiveQuantities(cell_idx, 0)
1187 .fluidState().temperature(phase_idx).value();
1191 [&model = simulator.model()](
int cell_idx)
1193 return model.intensiveQuantities(cell_idx, 0)
1194 .fluidState().saltConcentration().value();
1198 [&model = simulator.model()](
int cell_idx)
1200 return model.intensiveQuantities(cell_idx, 0)
1201 .fluidState().pvtRegionIndex();
1205 if constexpr (Indices::enableSolvent) {
1206 prop_func.solventInverseFormationVolumeFactor =
1207 [&model = simulator.model()](
int cell_idx)
1209 return model.intensiveQuantities(cell_idx, 0)
1210 .solventInverseFormationVolumeFactor().value();
1213 prop_func.solventRefDensity = [&model = simulator.model()](
int cell_idx)
1215 return model.intensiveQuantities(cell_idx, 0)
1216 .solventRefDensity();
1220 return this->connections_.computePropertiesForPressures(well_state, prop_func);
1227 template<
typename TypeTag>
1231 const std::vector<Scalar>& B_avg,
1232 const bool relax_tolerance)
const
1236 assert((
int(B_avg.size()) == this->num_conservation_quantities_) || has_polymer || has_energy || has_foam || has_brine || has_zFraction || has_bioeffects);
1239 Scalar tol_wells = this->param_.tolerance_wells_;
1241 constexpr Scalar stopped_factor = 1.e-4;
1243 constexpr Scalar dynamic_thp_factor = 1.e-1;
1244 if (this->stoppedOrZeroRateTarget(groupStateHelper)) {
1245 tol_wells = tol_wells*stopped_factor;
1246 }
else if (this->getDynamicThpLimit()) {
1247 tol_wells = tol_wells*dynamic_thp_factor;
1250 std::vector<Scalar> res;
1253 this->param_.max_residual_allowed_,
1255 this->param_.relaxed_tolerance_flow_well_,
1257 this->wellIsStopped(),
1261 checkConvergenceExtraEqs(res, report);
1270 template<
typename TypeTag>
1278 auto fluidState = [&simulator,
this](
const int perf)
1280 const auto cell_idx = this->well_cells_[perf];
1281 return simulator.model()
1282 .intensiveQuantities(cell_idx, 0).fluidState();
1285 const int np = this->number_of_phases_;
1286 auto setToZero = [np](
Scalar* x) ->
void
1288 std::fill_n(x, np, 0.0);
1291 auto addVector = [np](
const Scalar* src,
Scalar* dest) ->
void
1293 std::transform(src, src + np, dest, dest, std::plus<>{});
1296 auto& ws = well_state.
well(this->index_of_well_);
1297 auto& perf_data = ws.perf_data;
1298 auto* wellPI = ws.productivity_index.data();
1299 auto* connPI = perf_data.prod_index.data();
1303 const auto preferred_phase = this->well_ecl_.getPreferredPhase();
1304 auto subsetPerfID = 0;
1306 for (
const auto& perf : *this->perf_data_) {
1307 auto allPerfID = perf.ecl_index;
1309 auto connPICalc = [&wellPICalc, allPerfID](
const Scalar mobility) ->
Scalar
1314 std::vector<Scalar> mob(this->num_conservation_quantities_, 0.0);
1315 getMobility(simulator,
static_cast<int>(subsetPerfID), mob, deferred_logger);
1317 const auto& fs = fluidState(subsetPerfID);
1320 if (this->isInjector()) {
1321 this->computeConnLevelInjInd(fs, preferred_phase, connPICalc,
1322 mob, connPI, deferred_logger);
1325 this->computeConnLevelProdInd(fs, connPICalc, mob, connPI);
1328 addVector(connPI, wellPI);
1335 const auto& comm = this->parallel_well_info_.communication();
1336 if (comm.size() > 1) {
1337 comm.sum(wellPI, np);
1340 assert ((
static_cast<int>(subsetPerfID) == this->number_of_local_perforations_) &&
1341 "Internal logic error in processing connections for PI/II");
1346 template<
typename TypeTag>
1353 const auto& well_state = groupStateHelper.
wellState();
1357 const auto prop_func =
typename StdWellEval::StdWellConnections::DensityPropertyFunctions {
1362 [&model = simulator.model()](
const int cell,
1363 const std::vector<int>& phases,
1364 std::vector<Scalar>& mob)
1366 const auto& iq = model.intensiveQuantities(cell, 0);
1368 std::ranges::transform(phases, mob.begin(),
1369 [&iq](
const int phase) { return iq.mobility(phase).value(); });
1374 [&model = simulator.model()](
const int cell,
1375 const std::vector<int>& phases,
1376 std::vector<Scalar>& rho)
1378 const auto& fs = model.intensiveQuantities(cell, 0).fluidState();
1380 std::ranges::transform(phases, rho.begin(),
1381 [&fs](
const int phase) { return fs.density(phase).value(); });
1385 const auto stopped_or_zero_rate_target = this->
1386 stoppedOrZeroRateTarget(groupStateHelper);
1389 .computeProperties(stopped_or_zero_rate_target, well_state,
1390 prop_func, props, deferred_logger);
1392 cachedRefDensity = this->connections_.rho(0);
1393 if (this->parallel_well_info_.communication().size() > 1) {
1394 cachedRefDensity = this->parallel_well_info_.broadcastFirstPerforationValue(cachedRefDensity);
1402 template<
typename TypeTag>
1408 const auto& well_state = groupStateHelper.
wellState();
1409 const auto props = computePropertiesForWellConnectionPressures
1410 (simulator, well_state);
1412 computeWellConnectionDensitesPressures(simulator, groupStateHelper, props);
1419 template<
typename TypeTag>
1426 if (!this->isOperableAndSolvable() && !this->wellIsStopped())
return;
1431 dx_well[0].resize(this->primary_variables_.numWellEq());
1432 this->linSys_.solve( dx_well);
1434 updateWellState(simulator, dx_well, groupStateHelper, well_state);
1441 template<
typename TypeTag>
1447 updatePrimaryVariables(groupStateHelper);
1448 computeWellConnectionPressures(simulator, groupStateHelper);
1449 this->computeAccumWell();
1454 template<
typename TypeTag>
1459 if (!this->isOperableAndSolvable() && !this->wellIsStopped())
return;
1461 if (this->param_.matrix_add_well_contributions_)
1467 this->linSys_.apply(x, Ax);
1473 template<
typename TypeTag>
1478 if (!this->isOperableAndSolvable() && !this->wellIsStopped())
return;
1480 this->linSys_.apply(r);
1486 template<
typename TypeTag>
1494 if (!this->isOperableAndSolvable() && !this->wellIsStopped())
return;
1497 xw[0].resize(this->primary_variables_.numWellEq());
1499 this->linSys_.recoverSolutionWell(x, xw);
1500 updateWellState(simulator, xw, groupStateHelper, well_state);
1506 template<
typename TypeTag>
1511 std::vector<Scalar>& well_flux,
1515 const int np = this->number_of_phases_;
1516 well_flux.resize(np, 0.0);
1518 const bool allow_cf = this->getAllowCrossFlow();
1520 for (
int perf = 0; perf < this->number_of_local_perforations_; ++perf) {
1521 const int cell_idx = this->well_cells_[perf];
1522 const auto& intQuants = simulator.model().intensiveQuantities(cell_idx, 0);
1524 std::vector<Scalar> mob(this->num_conservation_quantities_, 0.);
1525 getMobility(simulator, perf, mob, deferred_logger);
1527 getTransMult(trans_mult, simulator, cell_idx);
1528 const auto& wellstate_nupcol = simulator.problem().wellModel().nupcolWellState().well(this->index_of_well_);
1529 std::vector<Scalar> Tw(this->num_conservation_quantities_, this->well_index_[perf] * trans_mult);
1530 this->getTw(Tw, perf, intQuants, trans_mult, wellstate_nupcol);
1532 std::vector<Scalar> cq_s(this->num_conservation_quantities_, 0.);
1534 computePerfRate(intQuants, mob, bhp, Tw, perf, allow_cf,
1535 cq_s, perf_rates, deferred_logger);
1537 for(
int p = 0; p < np; ++p) {
1538 well_flux[FluidSystem::activeCompToActivePhaseIdx(p)] += cq_s[p];
1542 if constexpr (has_solvent) {
1543 assert(FluidSystem::phaseIsActive(FluidSystem::gasPhaseIdx));
1545 const int gas_pos = FluidSystem::canonicalToActivePhaseIdx(FluidSystem::gasPhaseIdx);
1546 well_flux[gas_pos] += cq_s[Indices::contiSolventEqIdx];
1549 this->parallel_well_info_.communication().sum(well_flux.data(), well_flux.size());
1554 template<
typename TypeTag>
1560 std::vector<Scalar>& well_flux)
const
1576 auto guard = groupStateHelper_copy.
pushWellState(well_state_copy);
1579 const auto& summary_state = simulator.vanguard().summaryState();
1580 auto inj_controls = well_copy.
well_ecl_.isInjector()
1581 ? well_copy.
well_ecl_.injectionControls(summary_state)
1582 : Well::InjectionControls(0);
1583 auto prod_controls = well_copy.
well_ecl_.isProducer()
1584 ? well_copy.
well_ecl_.productionControls(summary_state) :
1585 Well::ProductionControls(0);
1588 auto& ws = well_state_copy.
well(this->index_of_well_);
1590 inj_controls.bhp_limit = bhp;
1591 ws.injection_cmode = Well::InjectorCMode::BHP;
1593 prod_controls.bhp_limit = bhp;
1594 ws.production_cmode = Well::ProducerCMode::BHP;
1599 const int np = this->number_of_phases_;
1600 const Scalar sign = this->well_ecl_.isInjector() ? 1.0 : -1.0;
1601 for (
int phase = 0; phase < np; ++phase){
1602 well_state_copy.
wellRates(this->index_of_well_)[phase]
1603 = sign * ws.well_potentials[phase];
1608 const double dt = simulator.timeStepSize();
1610 simulator, dt, inj_controls, prod_controls, groupStateHelper_copy, well_state_copy
1613 const std::string msg =
" well " + name() +
" did not get converged during well potential calculations "
1614 " potentials are computed based on unconverged solution";
1615 deferred_logger.debug(msg);
1625 template<
typename TypeTag>
1626 std::vector<typename StandardWell<TypeTag>::Scalar>
1633 std::vector<Scalar> potentials(this->number_of_phases_, 0.0);
1634 const auto& summary_state = simulator.vanguard().summaryState();
1636 const auto& well = this->well_ecl_;
1637 if (well.isInjector()){
1638 const auto& controls = this->well_ecl_.injectionControls(summary_state);
1639 auto bhp_at_thp_limit = computeBhpAtThpLimitInj(simulator, groupStateHelper, summary_state);
1640 if (bhp_at_thp_limit) {
1641 const Scalar bhp = std::min(*bhp_at_thp_limit,
1642 static_cast<Scalar>(controls.bhp_limit));
1643 computeWellRatesWithBhp(simulator, bhp, potentials, deferred_logger);
1645 deferred_logger.warning(
"FAILURE_GETTING_CONVERGED_POTENTIAL",
1646 "Failed in getting converged thp based potential calculation for well "
1647 + name() +
". Instead the bhp based value is used");
1648 const Scalar bhp = controls.bhp_limit;
1649 computeWellRatesWithBhp(simulator, bhp, potentials, deferred_logger);
1652 computeWellRatesWithThpAlqProd(
1653 simulator, groupStateHelper, summary_state,
1654 potentials, this->getALQ(well_state)
1661 template<
typename TypeTag>
1666 std::vector<Scalar>& well_potentials)
const
1679 auto guard = groupStateHelper_copy.
pushWellState(well_state_copy);
1680 auto& ws = well_state_copy.
well(this->index_of_well_);
1683 const auto& summary_state = simulator.vanguard().summaryState();
1684 auto inj_controls = well_copy.
well_ecl_.isInjector()
1685 ? well_copy.
well_ecl_.injectionControls(summary_state)
1686 : Well::InjectionControls(0);
1687 auto prod_controls = well_copy.
well_ecl_.isProducer()
1688 ? well_copy.
well_ecl_.productionControls(summary_state) :
1689 Well::ProductionControls(0);
1695 const int num_perf = ws.perf_data.size();
1696 for (
int perf = 0; perf < num_perf; ++perf) {
1700 const int np = this->number_of_phases_;
1701 bool trivial =
true;
1702 for (
int phase = 0; phase < np; ++phase){
1703 trivial = trivial && (ws.well_potentials[phase] == 0.0) ;
1707 for (
int phase = 0; phase < np; ++phase) {
1708 ws.surface_rates[phase] = sign * ws.well_potentials[phase];
1713 const double dt = simulator.timeStepSize();
1715 bool converged =
false;
1716 if (this->well_ecl_.isProducer()) {
1718 simulator, dt, inj_controls, prod_controls, groupStateHelper_copy, well_state_copy
1722 simulator, dt, inj_controls, prod_controls, groupStateHelper_copy, well_state_copy,
1730 well_potentials.clear();
1731 well_potentials.resize(np, 0.0);
1732 for (
int comp_idx = 0; comp_idx < this->num_conservation_quantities_; ++comp_idx) {
1733 if (has_solvent && comp_idx == Indices::contiSolventEqIdx)
continue;
1735 well_potentials[FluidSystem::activeCompToActivePhaseIdx(comp_idx)] = rate.value();
1739 if constexpr (has_solvent) {
1740 assert(FluidSystem::phaseIsActive(FluidSystem::gasPhaseIdx));
1742 const int gas_pos = FluidSystem::canonicalToActivePhaseIdx(FluidSystem::gasPhaseIdx);
1744 well_potentials[gas_pos] += rate.value();
1750 template<
typename TypeTag>
1755 const SummaryState &summary_state,
1756 std::vector<Scalar>& potentials,
1761 auto bhp_at_thp_limit = computeBhpAtThpLimitProdWithAlq(
1762 simulator, groupStateHelper, summary_state, alq,
true);
1763 if (bhp_at_thp_limit) {
1764 const auto& controls = this->well_ecl_.productionControls(summary_state);
1765 bhp = std::max(*bhp_at_thp_limit,
1766 static_cast<Scalar>(controls.bhp_limit));
1767 computeWellRatesWithBhp(simulator, bhp, potentials, deferred_logger);
1770 deferred_logger.warning(
"FAILURE_GETTING_CONVERGED_POTENTIAL",
1771 "Failed in getting converged thp based potential calculation for well "
1772 + name() +
". Instead the bhp based value is used");
1773 const auto& controls = this->well_ecl_.productionControls(summary_state);
1774 bhp = controls.bhp_limit;
1775 computeWellRatesWithBhp(simulator, bhp, potentials, deferred_logger);
1780 template<
typename TypeTag>
1785 const SummaryState& summary_state,
1786 std::vector<Scalar>& potentials,
1790 computeWellRatesAndBhpWithThpAlqProd(simulator,
1797 template<
typename TypeTag>
1803 std::vector<Scalar>& well_potentials)
1806 const auto [compute_potential, bhp_controlled_well] =
1809 if (!compute_potential) {
1813 bool converged_implicit =
false;
1817 if (this->param_.local_well_solver_control_switching_ && !(this->changed_to_open_this_step_ && this->wellUnderZeroRateTarget(groupStateHelper))) {
1818 converged_implicit = computeWellPotentialsImplicit(
1819 simulator, groupStateHelper, well_potentials
1822 if (!converged_implicit) {
1824 const auto& summaryState = simulator.vanguard().summaryState();
1825 if (!Base::wellHasTHPConstraints(summaryState) || bhp_controlled_well) {
1835 const auto& ws = well_state.
well(this->index_of_well_);
1836 if (this->isInjector())
1837 bhp = std::max(ws.bhp, bhp);
1839 bhp = std::min(ws.bhp, bhp);
1841 assert(std::abs(bhp) != std::numeric_limits<Scalar>::max());
1842 computeWellRatesWithBhpIterations(simulator, bhp, groupStateHelper, well_potentials);
1845 well_potentials = computeWellPotentialWithTHP(simulator, groupStateHelper, well_state);
1849 this->checkNegativeWellPotentials(well_potentials,
1850 this->param_.check_well_operability_,
1860 template<
typename TypeTag>
1864 const int openConnIdx)
const
1866 return (openConnIdx < 0)
1868 : this->connections_.rho(openConnIdx);
1875 template<
typename TypeTag>
1880 if (!this->isOperableAndSolvable() && !this->wellIsStopped())
return;
1883 const auto& well_state = groupStateHelper.
wellState();
1884 const bool stop_or_zero_rate_target = this->stoppedOrZeroRateTarget(groupStateHelper);
1885 this->primary_variables_.update(well_state, stop_or_zero_rate_target, deferred_logger);
1888 if constexpr (Base::has_polymermw) {
1889 this->primary_variables_.updatePolyMW(well_state);
1892 this->primary_variables_.checkFinite(deferred_logger,
"updating from well state");
1898 template<
typename TypeTag>
1903 return cachedRefDensity;
1909 template<
typename TypeTag>
1914 std::vector<EvalWell>& mob,
1917 const int cell_idx = this->well_cells_[perf];
1918 const auto& int_quant = simulator.model().intensiveQuantities(cell_idx, 0);
1919 const EvalWell polymer_concentration = this->extendEval(int_quant.polymerConcentration());
1923 if (this->isInjector()) {
1925 const auto& visc_mult_table = PolymerModule::plyviscViscosityMultiplierTable(int_quant.pvtRegionIndex());
1926 const unsigned waterCompIdx = FluidSystem::canonicalToActiveCompIdx(FluidSystem::waterCompIdx);
1927 mob[waterCompIdx] /= (this->extendEval(int_quant.waterViscosityCorrection()) * visc_mult_table.eval(polymer_concentration,
true) );
1930 if (PolymerModule::hasPlyshlog()) {
1933 if (this->isInjector() && this->wpolymer() == 0.) {
1938 const bool allow_cf = this->getAllowCrossFlow() || openCrossFlowAvoidSingularity(simulator);
1939 const EvalWell& bhp = this->primary_variables_.eval(Bhp);
1941 std::vector<EvalWell> cq_s(this->num_conservation_quantities_, 0.);
1944 getTransMult(trans_mult, simulator, cell_idx);
1945 const auto& wellstate_nupcol = simulator.problem().wellModel().nupcolWellState().well(this->index_of_well_);
1946 std::vector<EvalWell> Tw(this->num_conservation_quantities_, this->well_index_[perf] * trans_mult);
1947 this->getTw(Tw, perf, int_quant, trans_mult, wellstate_nupcol);
1948 computePerfRate(int_quant, mob, bhp, Tw, perf, allow_cf, cq_s,
1949 perf_rates, deferred_logger);
1951 const Scalar area = 2 * std::numbers::pi_v<Scalar> * this->perf_rep_radius_[perf] * this->perf_length_[perf];
1952 const auto& material_law_manager = simulator.problem().materialLawManager();
1953 const auto& scaled_drainage_info =
1954 material_law_manager->oilWaterScaledEpsInfoDrainage(cell_idx);
1955 const Scalar swcr = scaled_drainage_info.Swcr;
1956 const EvalWell poro = this->extendEval(int_quant.porosity());
1957 const EvalWell sw = this->extendEval(int_quant.fluidState().saturation(FluidSystem::waterPhaseIdx));
1959 const EvalWell denom = max( (area * poro * (sw - swcr)), 1e-12);
1960 const unsigned waterCompIdx = FluidSystem::canonicalToActiveCompIdx(FluidSystem::waterCompIdx);
1961 EvalWell water_velocity = cq_s[waterCompIdx] / denom * this->extendEval(int_quant.fluidState().invB(FluidSystem::waterPhaseIdx));
1963 if (PolymerModule::hasShrate()) {
1966 water_velocity *= PolymerModule::shrate( int_quant.pvtRegionIndex() ) / this->bore_diameters_[perf];
1968 const EvalWell shear_factor = PolymerModule::computeShearFactor(polymer_concentration,
1969 int_quant.pvtRegionIndex(),
1972 mob[waterCompIdx] /= shear_factor;
1976 template<
typename TypeTag>
1980 this->linSys_.extract(jacobian);
1984 template <
typename TypeTag>
1988 const int pressureVarIndex,
1989 const bool use_well_weights,
1992 this->linSys_.extractCPRPressureMatrix(jacobian,
2003 template<
typename TypeTag>
2010 if constexpr (Base::has_polymermw) {
2011 const int water_table_id = this->polymerWaterTable_();
2012 if (water_table_id <= 0) {
2014 fmt::format(
"Unused SKPRWAT table id used for well {}", name()),
2017 const auto& water_table_func = PolymerModule::getSkprwatTable(water_table_id);
2018 const EvalWell throughput_eval{throughput};
2020 EvalWell pskin_water = water_table_func.eval(throughput_eval, water_velocity);
2024 fmt::format(
"Polymermw is not activated, while injecting "
2025 "skin pressure is requested for well {}", name()),
2034 template<
typename TypeTag>
2042 if constexpr (Base::has_polymermw) {
2043 const Scalar sign = water_velocity >= 0. ? 1.0 : -1.0;
2044 const EvalWell water_velocity_abs = abs(water_velocity);
2045 if (poly_inj_conc == 0.) {
2046 return sign * pskinwater(throughput, water_velocity_abs, deferred_logger);
2048 const int polymer_table_id = this->polymerTable_();
2049 if (polymer_table_id <= 0) {
2051 fmt::format(
"Unavailable SKPRPOLY table id used for well {}", name()),
2054 const auto& skprpolytable = PolymerModule::getSkprpolyTable(polymer_table_id);
2055 const Scalar reference_concentration = skprpolytable.refConcentration;
2056 const EvalWell throughput_eval{throughput};
2058 const EvalWell pskin_poly = skprpolytable.table_func.eval(throughput_eval, water_velocity_abs);
2059 if (poly_inj_conc == reference_concentration) {
2060 return sign * pskin_poly;
2063 const EvalWell pskin_water = pskinwater(throughput, water_velocity_abs, deferred_logger);
2064 const EvalWell pskin = pskin_water + (pskin_poly - pskin_water) / reference_concentration * poly_inj_conc;
2065 return sign * pskin;
2068 fmt::format(
"Polymermw is not activated, while injecting "
2069 "skin pressure is requested for well {}", name()),
2078 template<
typename TypeTag>
2085 if constexpr (Base::has_polymermw) {
2086 const int table_id = this->polymerInjTable_();
2087 const auto& table_func = PolymerModule::getPlymwinjTable(table_id);
2088 const EvalWell throughput_eval{throughput};
2090 if (this->wpolymer() == 0.) {
2091 return molecular_weight;
2093 molecular_weight = table_func.eval(throughput_eval, abs(water_velocity));
2094 return molecular_weight;
2097 fmt::format(
"Polymermw is not activated, while injecting "
2098 "polymer molecular weight is requested for well {}", name()),
2107 template<
typename TypeTag>
2113 if constexpr (Base::has_polymermw) {
2114 if (!this->isInjector()) {
2118 auto& perf_water_throughput = well_state.
well(this->index_of_well_)
2119 .perf_data.water_throughput;
2121 for (
int perf = 0; perf < this->number_of_local_perforations_; ++perf) {
2122 const Scalar perf_water_vel =
2123 this->primary_variables_.value(Bhp + 1 + perf);
2127 if (perf_water_vel >
Scalar{0}) {
2128 perf_water_throughput[perf] += perf_water_vel * dt;
2138 template<
typename TypeTag>
2143 std::vector<EvalWell>& cq_s)
const
2145 const int cell_idx = this->well_cells_[perf];
2146 const auto& int_quants = simulator.model().intensiveQuantities(cell_idx, 0);
2147 const auto& fs = int_quants.fluidState();
2148 const EvalWell b_w = this->extendEval(fs.invB(FluidSystem::waterPhaseIdx));
2149 const Scalar area = std::numbers::pi_v<Scalar> * this->bore_diameters_[perf] * this->perf_length_[perf];
2150 const int wat_vel_index = Bhp + 1 + perf;
2151 const unsigned water_comp_idx = FluidSystem::canonicalToActiveCompIdx(FluidSystem::waterCompIdx);
2155 cq_s[water_comp_idx] = area * this->primary_variables_.eval(wat_vel_index) * b_w;
2161 template<
typename TypeTag>
2170 const int cell_idx = this->well_cells_[perf];
2171 const auto& int_quants = simulator.model().intensiveQuantities(cell_idx, 0);
2172 const auto& fs = int_quants.fluidState();
2173 const EvalWell b_w = this->extendEval(fs.invB(FluidSystem::waterPhaseIdx));
2174 const EvalWell water_flux_r = water_flux_s / b_w;
2175 const Scalar area = std::numbers::pi_v<Scalar> * this->bore_diameters_[perf] * this->perf_length_[perf];
2176 const EvalWell water_velocity = water_flux_r / area;
2177 const int wat_vel_index = Bhp + 1 + perf;
2180 const EvalWell eq_wat_vel = this->primary_variables_.eval(wat_vel_index) - water_velocity;
2182 const auto& ws = well_state.
well(this->index_of_well_);
2183 const auto& perf_data = ws.perf_data;
2184 const auto& perf_water_throughput = perf_data.water_throughput;
2185 const Scalar throughput = perf_water_throughput[perf];
2186 const int pskin_index = Bhp + 1 + this->number_of_local_perforations_ + perf;
2188 const EvalWell poly_conc(this->wpolymer());
2191 const EvalWell eq_pskin = this->primary_variables_.eval(pskin_index)
2192 - pskin(throughput, this->primary_variables_.eval(wat_vel_index), poly_conc, deferred_logger);
2195 assembleInjectivityEq(eq_pskin,
2200 this->primary_variables_.numWellEq(),
2208 template<
typename TypeTag>
2217 if constexpr (Base::has_polymermw) {
2219 checkConvergencePolyMW(res, Bhp, this->param_.max_residual_allowed_, report);
2227 template<
typename TypeTag>
2234 std::vector<RateVector>& connectionRates,
2239 if (this->isInjector()) {
2240 const int wat_vel_index = Bhp + 1 + perf;
2241 const EvalWell water_velocity = this->primary_variables_.eval(wat_vel_index);
2242 if (water_velocity > 0.) {
2243 const auto& ws = well_state.
well(this->index_of_well_);
2244 const auto& perf_water_throughput = ws.perf_data.water_throughput;
2245 const Scalar throughput = perf_water_throughput[perf];
2246 const EvalWell molecular_weight = wpolymermw(throughput, water_velocity, deferred_logger);
2247 cq_s_polymw *= molecular_weight;
2253 }
else if (this->isProducer()) {
2254 if (cq_s_polymw < 0.) {
2255 cq_s_polymw *= this->extendEval(int_quants.polymerMoleWeight() );
2262 connectionRates[perf][Indices::contiPolymerMWEqIdx] = Base::restrictEval(cq_s_polymw);
2269 template<
typename TypeTag>
2270 std::optional<typename StandardWell<TypeTag>::Scalar>
2275 const SummaryState& summary_state)
const
2277 return computeBhpAtThpLimitProdWithAlq(simulator,
2280 this->getALQ(well_state),
2284 template<
typename TypeTag>
2285 std::optional<typename StandardWell<TypeTag>::Scalar>
2289 const SummaryState& summary_state,
2291 bool iterate_if_no_solution)
const
2296 auto frates = [
this, &simulator, &deferred_logger](
const Scalar bhp) {
2302 std::vector<Scalar> rates(3);
2303 computeWellRatesWithBhp(simulator, bhp, rates, deferred_logger);
2304 this->adaptRatesForVFP(rates);
2309 maxPerfPress(simulator),
2310 this->getRefDensity(),
2312 this->getTHPConstraint(summary_state),
2316 auto v = frates(*bhpAtLimit);
2317 if (std::ranges::all_of(v, [](
Scalar i) {
return i <= 0; })) {
2322 if (!iterate_if_no_solution)
2323 return std::nullopt;
2325 auto fratesIter = [
this, &simulator, &groupStateHelper](
const Scalar bhp) {
2329 std::vector<Scalar> rates(3);
2330 computeWellRatesWithBhpIterations(simulator, bhp, groupStateHelper, rates);
2331 this->adaptRatesForVFP(rates);
2337 maxPerfPress(simulator),
2338 this->getRefDensity(),
2340 this->getTHPConstraint(summary_state),
2346 auto v = frates(*bhpAtLimit);
2347 if (std::ranges::all_of(v, [](
Scalar i) {
return i <= 0; })) {
2353 return std::nullopt;
2358 template<
typename TypeTag>
2359 std::optional<typename StandardWell<TypeTag>::Scalar>
2363 const SummaryState& summary_state)
const
2367 auto frates = [
this, &simulator, &deferred_logger](
const Scalar bhp) {
2373 std::vector<Scalar> rates(3);
2374 computeWellRatesWithBhp(simulator, bhp, rates, deferred_logger);
2380 this->getRefDensity(),
2391 template<
typename TypeTag>
2396 const Well::InjectionControls& inj_controls,
2397 const Well::ProductionControls& prod_controls,
2403 updatePrimaryVariables(groupStateHelper);
2405 const int max_iter = this->param_.max_inner_iter_wells_;
2408 bool relax_convergence =
false;
2409 this->regularize_ =
false;
2411 assembleWellEqWithoutIteration(simulator, groupStateHelper, dt, inj_controls, prod_controls, well_state,
2414 if (it > this->param_.strict_inner_iter_wells_) {
2415 relax_convergence =
true;
2416 this->regularize_ =
true;
2419 auto report = getWellConvergence(groupStateHelper, Base::B_avg_, relax_convergence);
2421 converged = report.converged();
2427 solveEqAndUpdateWellState(simulator, groupStateHelper, well_state);
2434 }
while (it < max_iter);
2437 std::ostringstream sstr;
2438 sstr <<
" Well " << this->name() <<
" converged in " << it <<
" inner iterations.";
2439 if (relax_convergence)
2440 sstr <<
" (A relaxed tolerance was used after "<< this->param_.strict_inner_iter_wells_ <<
" iterations)";
2444 deferred_logger.debug(sstr.str(), OpmLog::defaultDebugVerbosityLevel + (it == 0));
2446 std::ostringstream sstr;
2447 sstr <<
" Well " << this->name() <<
" did not converge in " << it <<
" inner iterations.";
2448 deferred_logger.debug(sstr.str());
2455 template<
typename TypeTag>
2460 const Well::InjectionControls& inj_controls,
2461 const Well::ProductionControls& prod_controls,
2464 const bool fixed_control ,
2465 const bool fixed_status ,
2466 const bool solving_with_zero_rate )
2470 updatePrimaryVariables(groupStateHelper);
2472 const int max_iter = this->param_.max_inner_iter_wells_;
2474 bool converged =
false;
2475 bool relax_convergence =
false;
2476 this->regularize_ =
false;
2477 const auto& summary_state = groupStateHelper.
summaryState();
2482 constexpr int min_its_after_switch = 4;
2484 const int max_status_switch = this->param_.max_well_status_switch_inner_iter_;
2485 int its_since_last_switch = min_its_after_switch;
2486 int switch_count= 0;
2488 const auto well_status_orig = this->wellStatus_;
2489 const auto operability_orig = this->operability_status_;
2490 auto well_status_cur = well_status_orig;
2491 int status_switch_count = 0;
2493 const bool allow_open = well_state.
well(this->index_of_well_).status == WellStatus::OPEN;
2495 const bool allow_switching =
2496 !this->wellUnderZeroRateTarget(groupStateHelper) &&
2497 (!fixed_control || !fixed_status) && allow_open;
2499 bool changed =
false;
2500 bool final_check =
false;
2502 this->operability_status_.resetOperability();
2503 this->operability_status_.solvable =
true;
2505 its_since_last_switch++;
2506 if (allow_switching && its_since_last_switch >= min_its_after_switch && status_switch_count < max_status_switch){
2507 const Scalar wqTotal = this->primary_variables_.eval(WQTotal).value();
2508 changed = this->updateWellControlAndStatusLocalIteration(
2509 simulator, groupStateHelper, inj_controls, prod_controls, wqTotal,
2510 well_state, fixed_control, fixed_status,
2511 solving_with_zero_rate
2514 its_since_last_switch = 0;
2516 if (well_status_cur != this->wellStatus_) {
2517 well_status_cur = this->wellStatus_;
2518 status_switch_count++;
2521 if (!changed && final_check) {
2524 final_check =
false;
2526 if (status_switch_count == max_status_switch) {
2527 this->wellStatus_ = well_status_orig;
2531 assembleWellEqWithoutIteration(simulator, groupStateHelper, dt, inj_controls, prod_controls, well_state, solving_with_zero_rate);
2533 if (it > this->param_.strict_inner_iter_wells_) {
2534 relax_convergence =
true;
2535 this->regularize_ =
true;
2538 auto report = getWellConvergence(groupStateHelper, Base::B_avg_, relax_convergence);
2540 converged = report.converged();
2544 if (switch_count > 0 && its_since_last_switch < min_its_after_switch) {
2546 its_since_last_switch = min_its_after_switch;
2553 solveEqAndUpdateWellState(simulator, groupStateHelper, well_state);
2555 }
while (it < max_iter);
2558 if (allow_switching){
2560 const bool is_stopped = this->wellIsStopped();
2561 if (this->wellHasTHPConstraints(summary_state)){
2562 this->operability_status_.can_obtain_bhp_with_thp_limit = !is_stopped;
2563 this->operability_status_.obey_thp_limit_under_bhp_limit = !is_stopped;
2565 this->operability_status_.operable_under_only_bhp_limit = !is_stopped;
2568 std::string message = fmt::format(
" Well {} converged in {} inner iterations ("
2569 "{} control/status switches).", this->name(), it, switch_count);
2570 if (relax_convergence) {
2571 message.append(fmt::format(
" (A relaxed tolerance was used after {} iterations)",
2572 this->param_.strict_inner_iter_wells_));
2574 deferred_logger.debug(message, OpmLog::defaultDebugVerbosityLevel + ((it == 0) && (switch_count == 0)));
2577 this->wellStatus_ = well_status_orig;
2578 this->operability_status_ = operability_orig;
2579 const std::string message = fmt::format(
" Well {} did not converge in {} inner iterations ("
2580 "{} switches, {} status changes).", this->name(), it, switch_count, status_switch_count);
2581 deferred_logger.debug(message);
2587 template<
typename TypeTag>
2588 std::vector<typename StandardWell<TypeTag>::Scalar>
2594 std::vector<Scalar> well_q_s(this->num_conservation_quantities_, 0.);
2595 const EvalWell& bhp = this->primary_variables_.eval(Bhp);
2596 const bool allow_cf = this->getAllowCrossFlow() || openCrossFlowAvoidSingularity(simulator);
2597 for (
int perf = 0; perf < this->number_of_local_perforations_; ++perf) {
2598 const int cell_idx = this->well_cells_[perf];
2599 const auto& intQuants = simulator.model().intensiveQuantities(cell_idx, 0);
2600 std::vector<Scalar> mob(this->num_conservation_quantities_, 0.);
2601 getMobility(simulator, perf, mob, deferred_logger);
2602 std::vector<Scalar> cq_s(this->num_conservation_quantities_, 0.);
2604 getTransMult(trans_mult, simulator, cell_idx);
2605 const auto& wellstate_nupcol = simulator.problem().wellModel().nupcolWellState().well(this->index_of_well_);
2606 std::vector<Scalar> Tw(this->num_conservation_quantities_, this->well_index_[perf] * trans_mult);
2607 this->getTw(Tw, perf, intQuants, trans_mult, wellstate_nupcol);
2609 computePerfRate(intQuants, mob, bhp.value(), Tw, perf, allow_cf,
2610 cq_s, perf_rates, deferred_logger);
2611 for (
int comp = 0; comp < this->num_conservation_quantities_; ++comp) {
2612 well_q_s[comp] += cq_s[comp];
2615 const auto& comm = this->parallel_well_info_.communication();
2616 if (comm.size() > 1)
2618 comm.sum(well_q_s.data(), well_q_s.size());
2625 template <
typename TypeTag>
2626 std::vector<typename StandardWell<TypeTag>::Scalar>
2630 const int num_pri_vars = this->primary_variables_.numWellEq();
2631 std::vector<Scalar> retval(num_pri_vars);
2632 for (
int ii = 0; ii < num_pri_vars; ++ii) {
2633 retval[ii] = this->primary_variables_.value(ii);
2642 template <
typename TypeTag>
2647 const int num_pri_vars = this->primary_variables_.numWellEq();
2648 for (
int ii = 0; ii < num_pri_vars; ++ii) {
2649 this->primary_variables_.setValue(ii, it[ii]);
2651 return num_pri_vars;
2655 template <
typename TypeTag>
2661 this->primary_variables_.scaledWellFractions(scaled_fractions, deferred_logger);
2665 template <
typename TypeTag>
2669 const IntensiveQuantities& intQuants,
2672 auto fs = intQuants.fluidState();
2674 for (
unsigned phaseIdx = 0; phaseIdx < FluidSystem::numPhases; ++phaseIdx) {
2675 if (!FluidSystem::phaseIsActive(phaseIdx)) {
2680 EvalWell cq_r_thermal{0.};
2681 const unsigned activeCompIdx = FluidSystem::canonicalToActiveCompIdx(FluidSystem::solventComponentIndex(phaseIdx));
2682 const bool both_oil_gas = FluidSystem::phaseIsActive(FluidSystem::oilPhaseIdx) && FluidSystem::phaseIsActive(FluidSystem::gasPhaseIdx);
2683 if (!both_oil_gas || FluidSystem::waterPhaseIdx == phaseIdx) {
2684 cq_r_thermal = cq_s[activeCompIdx] / this->extendEval(fs.invB(phaseIdx));
2687 const unsigned oilCompIdx = FluidSystem::canonicalToActiveCompIdx(FluidSystem::oilCompIdx);
2688 const unsigned gasCompIdx = FluidSystem::canonicalToActiveCompIdx(FluidSystem::gasCompIdx);
2693 const EvalWell d = this->extendEval(1.0 - fs.Rv() * fs.Rs());
2695 deferred_logger.
debug(
2696 fmt::format(
"Problematic d value {} obtained for well {}"
2697 " during calculateSinglePerf with rs {}"
2698 ", rv {}. Continue as if no dissolution (rs = 0) and"
2699 " vaporization (rv = 0) for this connection.",
2700 d, this->name(), fs.Rs(), fs.Rv()));
2701 cq_r_thermal = cq_s[activeCompIdx] / this->extendEval(fs.invB(phaseIdx));
2703 if (FluidSystem::gasPhaseIdx == phaseIdx) {
2704 cq_r_thermal = (cq_s[gasCompIdx] -
2705 this->extendEval(fs.Rs()) * cq_s[oilCompIdx]) /
2706 (d * this->extendEval(fs.invB(phaseIdx)) );
2707 }
else if (FluidSystem::oilPhaseIdx == phaseIdx) {
2709 cq_r_thermal = (cq_s[oilCompIdx] - this->extendEval(fs.Rv()) *
2711 (d * this->extendEval(fs.invB(phaseIdx)) );
2717 if (this->isInjector() && !this->wellIsStopped() && cq_r_thermal > 0.0){
2719 assert(this->well_ecl_.injectorType() != InjectorType::MULTI);
2720 fs.setTemperature(this->well_ecl_.inj_temperature());
2721 typedef typename std::decay<
decltype(fs)>::type::ValueType FsValueType;
2722 typename FluidSystem::template ParameterCache<FsValueType> paramCache;
2723 const unsigned pvtRegionIdx = intQuants.pvtRegionIndex();
2724 paramCache.setRegionIndex(pvtRegionIdx);
2725 paramCache.updatePhase(fs, phaseIdx);
2727 const auto& rho = FluidSystem::density(fs, paramCache, phaseIdx);
2728 fs.setDensity(phaseIdx, rho);
2729 const auto& h = FluidSystem::enthalpy(fs, paramCache, phaseIdx);
2730 fs.setEnthalpy(phaseIdx, h);
2731 cq_r_thermal *= this->extendEval(fs.enthalpy(phaseIdx)) * this->extendEval(fs.density(phaseIdx));
2732 result += getValue(cq_r_thermal);
2733 }
else if (cq_r_thermal > 0.0) {
2734 cq_r_thermal *= getValue(fs.enthalpy(phaseIdx)) * getValue(fs.density(phaseIdx));
2735 result += Base::restrictEval(cq_r_thermal);
2738 cq_r_thermal *= this->extendEval(fs.enthalpy(phaseIdx)) * this->extendEval(fs.density(phaseIdx));
2739 result += Base::restrictEval(cq_r_thermal);
2743 return result * this->well_efficiency_factor_;
2746 template <
typename TypeTag>
2750 Scalar max_pressure = 0.0;
2751 for (
int perf = 0; perf < this->number_of_local_perforations_; ++perf) {
2752 const int cell_idx = this->well_cells_[perf];
2753 const auto& int_quants = simulator.model().intensiveQuantities(cell_idx, 0);
2754 const auto& fs = int_quants.fluidState();
2755 Scalar pressure_cell = this->getPerfCellPressure(fs).value();
2756 max_pressure = std::max(max_pressure, pressure_cell);
2758 const auto& comm = this->parallel_well_info_.communication();
2759 if (comm.size() > 1) {
2760 max_pressure = comm.max(max_pressure);
2762 return max_pressure;
#define OPM_DEFLOG_THROW(Exception, message, deferred_logger)
Definition: DeferredLoggingErrorHelpers.hpp:45
#define OPM_DEFLOG_PROBLEM(Exception, message, deferred_logger)
Definition: DeferredLoggingErrorHelpers.hpp:61
Definition: ConvergenceReport.hpp:38
Definition: DeferredLogger.hpp:57
void debug(const std::string &tag, const std::string &message)
Definition: GroupStateHelper.hpp:56
GroupState< Scalar > & groupState() const
Definition: GroupStateHelper.hpp:301
const SummaryState & summaryState() const
Definition: GroupStateHelper.hpp:418
const WellState< Scalar, IndexTraits > & wellState() const
Definition: GroupStateHelper.hpp:499
DeferredLogger & deferredLogger() const
Get the deferred logger.
Definition: GroupStateHelper.hpp:233
WellStateGuard pushWellState(WellState< Scalar, IndexTraits > &well_state)
Definition: GroupStateHelper.hpp:357
GroupStateGuard pushGroupState(GroupState< Scalar > &group_state)
Definition: GroupStateHelper.hpp:334
Definition: GroupState.hpp:41
Class encapsulating some information about parallel wells.
Definition: ParallelWellInfo.hpp:198
Definition: RatioCalculator.hpp:38
Class handling assemble of the equation system for StandardWell.
Definition: StandardWellAssemble.hpp:44
Scalar pressure_diff(const unsigned perf) const
Returns pressure drop for a given perforation.
Definition: StandardWellConnections.hpp:101
StdWellConnections connections_
Connection level values.
Definition: StandardWellEval.hpp:101
PrimaryVariables primary_variables_
Primary variables for well.
Definition: StandardWellEval.hpp:95
Definition: StandardWell.hpp:60
void getScaledWellFractions(std::vector< Scalar > &scaled_fractions, DeferredLogger &deferred_logger) const override
Definition: StandardWell_impl.hpp:2658
EvalWell wpolymermw(const Scalar throughput, const EvalWell &water_velocity, DeferredLogger &deferred_logger) const
Definition: StandardWell_impl.hpp:2081
std::vector< Scalar > computeWellPotentialWithTHP(const Simulator &ebosSimulator, const GroupStateHelperType &groupStateHelper, const WellStateType &well_state) const
Definition: StandardWell_impl.hpp:1628
typename StdWellEval::EvalWell EvalWell
Definition: StandardWell.hpp:121
void updateWellStateFromPrimaryVariables(WellStateType &well_state, const SummaryState &summary_state, DeferredLogger &deferred_logger) const
Definition: StandardWell_impl.hpp:814
virtual ConvergenceReport getWellConvergence(const GroupStateHelperType &groupStateHelper, const std::vector< Scalar > &B_avg, const bool relax_tolerance) const override
check whether the well equations get converged for this well
Definition: StandardWell_impl.hpp:1230
WellConnectionProps computePropertiesForWellConnectionPressures(const Simulator &simulator, const WellStateType &well_state) const
Definition: StandardWell_impl.hpp:1179
std::optional< Scalar > computeBhpAtThpLimitProdWithAlq(const Simulator &ebos_simulator, const GroupStateHelperType &groupStateHelper, const SummaryState &summary_state, const Scalar alq_value, bool iterate_if_no_solution) const override
Definition: StandardWell_impl.hpp:2287
typename StdWellEval::BVectorWell BVectorWell
Definition: StandardWell.hpp:122
void addWellContributions(SparseMatrixAdapter &mat) const override
Definition: StandardWell_impl.hpp:1978
std::vector< Scalar > getPrimaryVars() const override
Definition: StandardWell_impl.hpp:2628
void updateWellState(const Simulator &simulator, const BVectorWell &dwells, const GroupStateHelperType &groupStateHelper, WellStateType &well_state)
Definition: StandardWell_impl.hpp:762
void updatePrimaryVariables(const GroupStateHelperType &groupStateHelper) override
Definition: StandardWell_impl.hpp:1878
void solveEqAndUpdateWellState(const Simulator &simulator, const GroupStateHelperType &groupStateHelper, WellStateType &well_state) override
Definition: StandardWell_impl.hpp:1422
void computeWellConnectionDensitesPressures(const Simulator &simulator, const GroupStateHelperType &groupStateHelper, const WellConnectionProps &props)
Definition: StandardWell_impl.hpp:1348
std::optional< Scalar > computeBhpAtThpLimitProd(const WellStateType &well_state, const Simulator &simulator, const GroupStateHelperType &groupStateHelper, const SummaryState &summary_state) const
Definition: StandardWell_impl.hpp:2272
void addWellPressureEquations(PressureMatrix &mat, const BVector &x, const int pressureVarIndex, const bool use_well_weights, const WellStateType &well_state) const override
Definition: StandardWell_impl.hpp:1986
void updateWaterMobilityWithPolymer(const Simulator &simulator, const int perf, std::vector< EvalWell > &mob_water, DeferredLogger &deferred_logger) const
Definition: StandardWell_impl.hpp:1912
bool iterateWellEqWithControl(const Simulator &simulator, const double dt, const Well::InjectionControls &inj_controls, const Well::ProductionControls &prod_controls, const GroupStateHelperType &groupStateHelper, WellStateType &well_state) override
Definition: StandardWell_impl.hpp:2394
std::vector< Scalar > computeCurrentWellRates(const Simulator &ebosSimulator, DeferredLogger &deferred_logger) const override
Definition: StandardWell_impl.hpp:2590
void calculateSinglePerf(const Simulator &simulator, const int perf, WellStateType &well_state, std::vector< RateVector > &connectionRates, std::vector< EvalWell > &cq_s, EvalWell &water_flux_s, EvalWell &cq_s_zfrac_effective, DeferredLogger &deferred_logger) const
Definition: StandardWell_impl.hpp:508
void computeWellConnectionPressures(const Simulator &simulator, const GroupStateHelperType &groupStateHelper)
Definition: StandardWell_impl.hpp:1405
void updatePrimaryVariablesNewton(const BVectorWell &dwells, const bool stop_or_zero_rate_target, DeferredLogger &deferred_logger)
Definition: StandardWell_impl.hpp:791
void assembleWellEqWithoutIteration(const Simulator &simulator, const GroupStateHelperType &groupStateHelper, const double dt, const Well::InjectionControls &inj_controls, const Well::ProductionControls &prod_controls, WellStateType &well_state, const bool solving_with_zero_rate) override
Definition: StandardWell_impl.hpp:342
GetPropType< TypeTag, Properties::Scalar > Scalar
Definition: WellInterface.hpp:83
void computeWellPotentials(const Simulator &simulator, const WellStateType &well_state, const GroupStateHelperType &groupStateHelper, std::vector< Scalar > &well_potentials) override
computing the well potentials for group control
Definition: StandardWell_impl.hpp:1800
StandardWell(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)
Definition: StandardWell_impl.hpp:53
std::optional< Scalar > computeBhpAtThpLimitInj(const Simulator &simulator, const GroupStateHelperType &groupStateHelper, const SummaryState &summary_state) const
Definition: StandardWell_impl.hpp:2361
typename StdWellEval::StdWellConnections::Properties WellConnectionProps
Definition: StandardWell.hpp:264
void computeWellRatesWithBhpIterations(const Simulator &ebosSimulator, const Scalar &bhp, const GroupStateHelperType &groupStateHelper, std::vector< Scalar > &well_flux) const override
Definition: StandardWell_impl.hpp:1557
void updateConnectionRatePolyMW(const EvalWell &cq_s_poly, const IntensiveQuantities &int_quants, const WellStateType &well_state, const int perf, std::vector< RateVector > &connectionRates, DeferredLogger &deferred_logger) const
Definition: StandardWell_impl.hpp:2230
void computeWellRatesWithBhp(const Simulator &ebosSimulator, const Scalar &bhp, std::vector< Scalar > &well_flux, DeferredLogger &deferred_logger) const override
Definition: StandardWell_impl.hpp:1509
void updateIPRImplicit(const Simulator &simulator, const GroupStateHelperType &groupStateHelper, WellStateType &well_state) override
Definition: StandardWell_impl.hpp:930
void getMobility(const Simulator &simulator, const int perf, std::vector< Value > &mob, DeferredLogger &deferred_logger) const
Definition: StandardWell_impl.hpp:706
void getTransMult(Value &trans_mult, const Simulator &simulator, const int cell_indx) const
Definition: StandardWell_impl.hpp:686
void updateIPR(const Simulator &simulator, DeferredLogger &deferred_logger) const override
Definition: StandardWell_impl.hpp:838
void handleInjectivityEquations(const Simulator &simulator, const WellStateType &well_state, const int perf, const EvalWell &water_flux_s, DeferredLogger &deferred_logger)
Definition: StandardWell_impl.hpp:2164
virtual void apply(const BVector &x, BVector &Ax) const override
Ax = Ax - C D^-1 B x.
Definition: StandardWell_impl.hpp:1457
void checkConvergenceExtraEqs(const std::vector< Scalar > &res, ConvergenceReport &report) const
Definition: StandardWell_impl.hpp:2211
void computeWellRatesWithThpAlqProd(const Simulator &ebos_simulator, const GroupStateHelperType &groupStateHelper, const SummaryState &summary_state, std::vector< Scalar > &potentials, Scalar alq) const
Definition: StandardWell_impl.hpp:1783
typename StdWellEval::Eval Eval
Definition: StandardWell.hpp:120
Scalar computeWellRatesAndBhpWithThpAlqProd(const Simulator &ebos_simulator, const GroupStateHelperType &groupStateHelper, const SummaryState &summary_state, std::vector< Scalar > &potentials, Scalar alq) const
Definition: StandardWell_impl.hpp:1753
bool openCrossFlowAvoidSingularity(const Simulator &simulator) const
Definition: StandardWell_impl.hpp:1168
bool computeWellPotentialsImplicit(const Simulator &ebos_simulator, const GroupStateHelperType &groupStateHelper, std::vector< Scalar > &well_potentials) const
Definition: StandardWell_impl.hpp:1664
void recoverWellSolutionAndUpdateWellState(const Simulator &simulator, const BVector &x, const GroupStateHelperType &groupStateHelper, WellStateType &well_state) override
Definition: StandardWell_impl.hpp:1489
Scalar maxPerfPress(const Simulator &simulator) const override
Definition: StandardWell_impl.hpp:2749
bool iterateWellEqWithSwitching(const Simulator &simulator, const double dt, const Well::InjectionControls &inj_controls, const Well::ProductionControls &prod_controls, const GroupStateHelperType &groupStateHelper, WellStateType &well_state, const bool fixed_control, const bool fixed_status, const bool solving_with_zero_rate) override
Definition: StandardWell_impl.hpp:2458
void assembleWellEqWithoutIterationImpl(const Simulator &simulator, const GroupStateHelperType &groupStateHelper, const double dt, const Well::InjectionControls &inj_controls, const Well::ProductionControls &prod_controls, WellStateType &well_state, const bool solving_with_zero_rate)
Definition: StandardWell_impl.hpp:367
bool allDrawDownWrongDirection(const Simulator &simulator) const
Definition: StandardWell_impl.hpp:1126
EvalWell pskin(const Scalar throughput, const EvalWell &water_velocity, const EvalWell &poly_inj_conc, DeferredLogger &deferred_logger) const
Definition: StandardWell_impl.hpp:2037
void computePerfRate(const IntensiveQuantities &intQuants, const std::vector< Value > &mob, const Value &bhp, const std::vector< Value > &Tw, const int perf, const bool allow_cf, std::vector< Value > &cq_s, PerforationRates< Scalar > &perf_rates, DeferredLogger &deferred_logger) const
Definition: StandardWell_impl.hpp:94
static constexpr int numWellConservationEq
Definition: StandardWell.hpp:97
int setPrimaryVars(typename std::vector< Scalar >::const_iterator it) override
Definition: StandardWell_impl.hpp:2645
void updateWaterThroughput(const double dt, WellStateType &well_state) const override
Definition: StandardWell_impl.hpp:2110
void checkOperabilityUnderBHPLimit(const WellStateType &well_state, const Simulator &simulator, DeferredLogger &deferred_logger) override
Definition: StandardWell_impl.hpp:1007
EvalWell pskinwater(const Scalar throughput, const EvalWell &water_velocity, DeferredLogger &deferred_logger) const
Definition: StandardWell_impl.hpp:2006
void handleInjectivityRate(const Simulator &simulator, const int perf, std::vector< EvalWell > &cq_s) const
Definition: StandardWell_impl.hpp:2141
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) override
Definition: StandardWell_impl.hpp:77
void updateProductivityIndex(const Simulator &simulator, const WellProdIndexCalculator< Scalar > &wellPICalc, WellStateType &well_state, DeferredLogger &deferred_logger) const override
Definition: StandardWell_impl.hpp:1273
void calculateExplicitQuantities(const Simulator &simulator, const GroupStateHelperType &groupStateHelper) override
Definition: StandardWell_impl.hpp:1444
Scalar getRefDensity() const override
Definition: StandardWell_impl.hpp:1901
void checkOperabilityUnderTHPLimit(const Simulator &simulator, const WellStateType &well_state, const GroupStateHelperType &groupStateHelper) override
Definition: StandardWell_impl.hpp:1076
Scalar connectionDensity(const int globalConnIdx, const int openConnIdx) const override
Definition: StandardWell_impl.hpp:1863
EvalWell getQs(const int compIdx) const
Returns scaled rate for a component.
Class for computing BHP limits.
Definition: WellBhpThpCalculator.hpp:41
Scalar calculateThpFromBhp(const std::vector< Scalar > &rates, const Scalar bhp, const Scalar rho, const std::optional< Scalar > &alq, const Scalar thp_limit, DeferredLogger &deferred_logger) const
Calculates THP from BHP.
std::optional< Scalar > computeBhpAtThpLimitProd(const std::function< std::vector< Scalar >(const Scalar)> &frates, const SummaryState &summary_state, const Scalar maxPerfPress, const Scalar rho, const Scalar alq_value, const Scalar thp_limit, DeferredLogger &deferred_logger) const
Compute BHP from THP limit for a producer.
Scalar mostStrictBhpFromBhpLimits(const SummaryState &summaryState) const
Obtain the most strict BHP from BHP limits.
std::optional< Scalar > computeBhpAtThpLimitInj(const std::function< std::vector< Scalar >(const Scalar)> &frates, const SummaryState &summary_state, const Scalar rho, const Scalar flo_rel_tol, const int max_iteration, const bool throwOnError, DeferredLogger &deferred_logger) const
Compute BHP from THP limit for an injector.
Definition: WellConvergence.hpp:38
const int num_conservation_quantities_
Definition: WellInterfaceGeneric.hpp:319
Well well_ecl_
Definition: WellInterfaceGeneric.hpp:309
void onlyKeepBHPandTHPcontrols(const SummaryState &summary_state, WellStateType &well_state, Well::InjectionControls &inj_controls, Well::ProductionControls &prod_controls) const
void resetDampening()
Definition: WellInterfaceGeneric.hpp:247
std::pair< bool, bool > computeWellPotentials(std::vector< Scalar > &well_potentials, const WellStateType &well_state)
Definition: WellInterfaceIndices.hpp:34
Definition: WellInterface.hpp:77
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:610
GetPropType< TypeTag, Properties::Simulator > Simulator
Definition: WellInterface.hpp:82
typename WellInterfaceFluidSystem< FluidSystem >::RateConverterType RateConverterType
Definition: WellInterface.hpp:105
void getTransMult(Value &trans_mult, const Simulator &simulator, const int cell_idx, Callback &extendEval) const
Definition: WellInterface_impl.hpp:2096
Dune::BCRSMatrix< Opm::MatrixBlock< Scalar, 1, 1 > > PressureMatrix
Definition: WellInterface.hpp:98
void getMobility(const Simulator &simulator, const int local_perf_index, std::vector< Value > &mob, Callback &extendEval, DeferredLogger &deferred_logger) const
Definition: WellInterface_impl.hpp:2109
GetPropType< TypeTag, Properties::IntensiveQuantities > IntensiveQuantities
Definition: WellInterface.hpp:87
GetPropType< TypeTag, Properties::Scalar > Scalar
Definition: WellInterface.hpp:83
Dune::BlockVector< VectorBlockType > BVector
Definition: WellInterface.hpp:97
typename Base::ModelParameters ModelParameters
Definition: WellInterface.hpp:111
GetPropType< TypeTag, Properties::FluidSystem > FluidSystem
Definition: WellInterface.hpp:84
GetPropType< TypeTag, Properties::Indices > Indices
Definition: WellInterface.hpp:86
GetPropType< TypeTag, Properties::SparseMatrixAdapter > SparseMatrixAdapter
Definition: WellInterface.hpp:89
Definition: WellProdIndexCalculator.hpp:37
Scalar connectionProdIndStandard(const std::size_t connIdx, const Scalar connMobility) const
Definition: WellState.hpp:66
const SingleWellState< Scalar, IndexTraits > & well(std::size_t well_index) const
Definition: WellState.hpp:306
std::vector< Scalar > & wellRates(std::size_t well_index)
One rate per well and phase.
Definition: WellState.hpp:271
@ NONE
Definition: DeferredLogger.hpp:46
Definition: blackoilbioeffectsmodules.hh:45
std::string to_string(const ConvergenceReport::ReservoirFailure::Type t)
Static data associated with a well perforation.
Definition: PerforationData.hpp:30
Definition: PerforationData.hpp:41
Scalar dis_gas
Definition: PerforationData.hpp:42
Scalar vap_wat
Definition: PerforationData.hpp:45
Scalar vap_oil
Definition: PerforationData.hpp:44
Scalar dis_gas_in_water
Definition: PerforationData.hpp:43