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;
354 const auto assemble_timer = this->solveAssembleTimer();
357 this->linSys_.clear();
359 assembleWellEqWithoutIterationImpl(simulator, groupStateHelper, dt, inj_controls,
360 prod_controls, well_state, solving_with_zero_rate);
366 template<
typename TypeTag>
372 const Well::InjectionControls& inj_controls,
373 const Well::ProductionControls& prod_controls,
375 const bool solving_with_zero_rate)
380 const Scalar regularization_factor = this->regularize_? this->param_.regularization_factor_wells_ : 1.0;
381 const Scalar volume = 0.1 * unit::cubic(unit::feet) * regularization_factor;
383 auto& ws = well_state.
well(this->index_of_well_);
384 ws.phase_mixing_rates.fill(0.0);
385 if constexpr (has_energy) {
386 ws.energy_rate = 0.0;
390 const int np = this->number_of_phases_;
392 std::vector<RateVector> connectionRates = this->connectionRates_;
394 auto& perf_data = ws.perf_data;
395 auto& perf_rates = perf_data.phase_rates;
396 for (
int perf = 0; perf < this->number_of_local_perforations_; ++perf) {
398 std::vector<EvalWell> cq_s(this->num_conservation_quantities_, 0.0);
401 calculateSinglePerf(simulator, perf, well_state, connectionRates,
402 cq_s, water_flux_s, cq_s_zfrac_effective, deferred_logger);
405 if constexpr (has_polymer && Base::has_polymermw) {
406 if (this->isInjector()) {
407 handleInjectivityEquations(simulator, well_state, perf,
408 water_flux_s, deferred_logger);
411 for (
int componentIdx = 0; componentIdx < this->num_conservation_quantities_; ++componentIdx) {
413 const EvalWell cq_s_effective = cq_s[componentIdx] * this->well_efficiency_factor_;
415 connectionRates[perf][componentIdx] = Base::restrictEval(cq_s_effective);
418 assemblePerforationEq(cq_s_effective,
422 this->primary_variables_.numWellEq(),
426 if (has_solvent && componentIdx == Indices::contiSolventEqIdx) {
427 auto& perf_rate_solvent = perf_data.solvent_rates;
428 perf_rate_solvent[perf] = cq_s[componentIdx].value();
430 perf_rates[perf*np + FluidSystem::activeCompToActivePhaseIdx(componentIdx)] = cq_s[componentIdx].value();
434 if constexpr (has_zFraction) {
436 assembleZFracEq(cq_s_zfrac_effective,
438 this->primary_variables_.numWellEq(),
443 this->connectionRates_ = connectionRates;
448 const auto& comm = this->parallel_well_info_.communication();
449 comm.sum(ws.phase_mixing_rates.data(), ws.phase_mixing_rates.size());
453 this->linSys_.sumDistributed(this->parallel_well_info_.communication());
456 for (
int componentIdx = 0; componentIdx < numWellConservationEq; ++componentIdx) {
460 if (FluidSystem::numActivePhases() > 1) {
462 resWell_loc += (this->primary_variables_.surfaceVolumeFraction(componentIdx) -
463 this->F0_[componentIdx]) * volume / dt;
465 resWell_loc -= this->primary_variables_.getQs(componentIdx) * this->well_efficiency_factor_;
467 assembleSourceEq(resWell_loc,
469 this->primary_variables_.numWellEq(),
473 const bool stopped_or_zero_target = this->stoppedOrZeroRateTarget(groupStateHelper);
479 auto& group_state = solving_with_zero_rate
483 if (this->wellUnderGroupControl(ws) && this->isProducer() && !stopped_or_zero_target) {
484 this->updateGroupTargetFallbackFlag(well_state, deferred_logger);
487 auto group_guard = groupStateHelper_copy.
pushGroupState(group_state);
489 assembleControlEq(groupStateHelper_copy,
490 inj_controls, prod_controls,
491 this->primary_variables_,
492 this->getRefDensity(),
494 stopped_or_zero_target);
499 this->linSys_.invert();
501 OPM_DEFLOG_PROBLEM(NumericalProblem,
"Error when inverting local well equations for well " + name(), deferred_logger);
508 template<
typename TypeTag>
514 std::vector<RateVector>& connectionRates,
515 std::vector<EvalWell>& cq_s,
520 const bool allow_cf = this->getAllowCrossFlow() || openCrossFlowAvoidSingularity(simulator);
521 const EvalWell& bhp = this->primary_variables_.eval(Bhp);
522 const int cell_idx = this->well_cells_[perf];
523 const auto& intQuants = simulator.model().intensiveQuantities(cell_idx, 0);
524 std::vector<EvalWell> mob(this->num_conservation_quantities_, {0.});
525 getMobility(simulator, perf, mob, deferred_logger);
529 getTransMult(trans_mult, simulator, cell_idx);
530 const auto& wellstate_nupcol = simulator.problem().wellModel().nupcolWellState().well(this->index_of_well_);
531 std::vector<EvalWell> Tw(this->num_conservation_quantities_, this->well_index_[perf] * trans_mult);
532 this->getTw(Tw, perf, intQuants, trans_mult, wellstate_nupcol);
533 computePerfRate(intQuants, mob, bhp, Tw, perf, allow_cf,
534 cq_s, perf_rates, deferred_logger);
536 auto& ws = well_state.
well(this->index_of_well_);
537 auto& perf_data = ws.perf_data;
538 if constexpr (has_polymer && Base::has_polymermw) {
539 if (this->isInjector()) {
542 const unsigned water_comp_idx = FluidSystem::canonicalToActiveCompIdx(FluidSystem::waterCompIdx);
543 water_flux_s = cq_s[water_comp_idx];
546 handleInjectivityRate(simulator, perf, cq_s);
551 if (this->isProducer()) {
552 ws.phase_mixing_rates[ws.dissolved_gas] += perf_rates.
dis_gas;
553 ws.phase_mixing_rates[ws.dissolved_gas_in_water] += perf_rates.
dis_gas_in_water;
554 ws.phase_mixing_rates[ws.vaporized_oil] += perf_rates.
vap_oil;
555 ws.phase_mixing_rates[ws.vaporized_water] += perf_rates.
vap_wat;
556 perf_data.phase_mixing_rates[perf][ws.dissolved_gas] = perf_rates.
dis_gas;
557 perf_data.phase_mixing_rates[perf][ws.dissolved_gas_in_water] = perf_rates.
dis_gas_in_water;
558 perf_data.phase_mixing_rates[perf][ws.vaporized_oil] = perf_rates.
vap_oil;
559 perf_data.phase_mixing_rates[perf][ws.vaporized_water] = perf_rates.
vap_wat;
562 if constexpr (has_energy) {
563 connectionRates[perf][Indices::contiEnergyEqIdx] =
564 connectionRateEnergy(cq_s, intQuants, deferred_logger);
565 ws.energy_rate += getValue(connectionRates[perf][Indices::contiEnergyEqIdx]);
568 if constexpr (has_polymer) {
569 std::variant<Scalar,EvalWell> polymerConcentration;
570 if (this->isInjector()) {
571 polymerConcentration = this->wpolymer();
573 polymerConcentration = this->extendEval(intQuants.polymerConcentration() *
574 intQuants.polymerViscosityCorrection());
577 [[maybe_unused]]
EvalWell cq_s_poly;
578 std::tie(connectionRates[perf][Indices::contiPolymerEqIdx],
580 this->connections_.connectionRatePolymer(perf_data.polymer_rates[perf],
581 cq_s, polymerConcentration);
583 if constexpr (Base::has_polymermw) {
584 updateConnectionRatePolyMW(cq_s_poly, intQuants, well_state,
585 perf, connectionRates, deferred_logger);
589 if constexpr (has_foam) {
590 std::variant<Scalar,EvalWell> foamConcentration;
591 if (this->isInjector()) {
592 foamConcentration = this->wfoam();
594 foamConcentration = this->extendEval(intQuants.foamConcentration());
596 connectionRates[perf][Indices::contiFoamEqIdx] =
597 this->connections_.connectionRateFoam(cq_s, foamConcentration,
598 FoamModule::transportPhase(),
602 if constexpr (has_zFraction) {
603 std::variant<Scalar,std::array<EvalWell,2>> solventConcentration;
604 if (this->isInjector()) {
605 solventConcentration = this->wsolvent();
607 solventConcentration = std::array{this->extendEval(intQuants.xVolume()),
608 this->extendEval(intQuants.yVolume())};
610 std::tie(connectionRates[perf][Indices::contiZfracEqIdx],
611 cq_s_zfrac_effective) =
612 this->connections_.connectionRatezFraction(perf_data.solvent_rates[perf],
614 solventConcentration);
617 if constexpr (has_brine) {
618 std::variant<Scalar,EvalWell> saltConcentration;
619 if (this->isInjector()) {
620 saltConcentration = this->wsalt();
622 saltConcentration = this->extendEval(intQuants.fluidState().saltConcentration());
625 connectionRates[perf][Indices::contiBrineEqIdx] =
626 this->connections_.connectionRateBrine(perf_data.brine_rates[perf],
631 if constexpr (has_bioeffects) {
632 std::variant<Scalar,EvalWell> microbialConcentration;
633 if constexpr (has_micp) {
634 std::variant<Scalar,EvalWell> oxygenConcentration;
635 std::variant<Scalar,EvalWell> ureaConcentration;
636 if (this->isInjector()) {
637 microbialConcentration = this->wmicrobes();
638 oxygenConcentration = this->woxygen();
639 ureaConcentration = this->wurea();
641 microbialConcentration = this->extendEval(intQuants.microbialConcentration());
642 oxygenConcentration = this->extendEval(intQuants.oxygenConcentration());
643 ureaConcentration = this->extendEval(intQuants.ureaConcentration());
645 std::tie(connectionRates[perf][Indices::contiMicrobialEqIdx],
646 connectionRates[perf][Indices::contiOxygenEqIdx],
647 connectionRates[perf][Indices::contiUreaEqIdx]) =
648 this->connections_.connectionRatesMICP(perf_data.microbial_rates[perf],
649 perf_data.oxygen_rates[perf],
650 perf_data.urea_rates[perf],
652 microbialConcentration,
657 if (this->isProducer()) {
658 microbialConcentration = this->extendEval(intQuants.microbialConcentration());
659 connectionRates[perf][Indices::contiMicrobialEqIdx] =
660 this->connections_.connectionRateBioeffects(perf_data.microbial_rates[perf],
662 microbialConcentration);
668 perf_data.pressure[perf] = ws.bhp + this->connections_.pressure_diff(perf);
671 if (FluidSystem::phaseUsage().hasCO2orH2Store()) {
672 const unsigned gas_comp_idx = FluidSystem::canonicalToActiveCompIdx(FluidSystem::gasCompIdx);
673 const Scalar rho = FluidSystem::referenceDensity( FluidSystem::gasPhaseIdx, Base::pvtRegionIdx() );
674 perf_data.gas_mass_rates[perf] = cq_s[gas_comp_idx].value() * rho;
678 if (FluidSystem::phaseIsActive(FluidSystem::waterPhaseIdx)) {
679 const unsigned wat_comp_idx = FluidSystem::canonicalToActiveCompIdx(FluidSystem::waterCompIdx);
680 const Scalar rho = FluidSystem::referenceDensity( FluidSystem::waterPhaseIdx, Base::pvtRegionIdx() );
681 perf_data.wat_mass_rates[perf] = cq_s[wat_comp_idx].value() * rho;
685 template<
typename TypeTag>
686 template<
class Value>
691 const int cell_idx)
const
693 auto obtain = [
this](
const Eval& value)
695 if constexpr (std::is_same_v<Value, Scalar>) {
696 static_cast<void>(
this);
697 return getValue(value);
699 return this->extendEval(value);
705 template<
typename TypeTag>
706 template<
class Value>
711 std::vector<Value>& mob,
714 auto obtain = [
this](
const Eval& value)
716 if constexpr (std::is_same_v<Value, Scalar>) {
717 static_cast<void>(
this);
718 return getValue(value);
720 return this->extendEval(value);
724 obtain, deferred_logger);
727 if constexpr (has_polymer) {
728 if (!FluidSystem::phaseIsActive(FluidSystem::waterPhaseIdx)) {
729 OPM_DEFLOG_THROW(std::runtime_error,
"Water is required when polymer is active", deferred_logger);
734 if constexpr (!Base::has_polymermw) {
735 if constexpr (std::is_same_v<Value, Scalar>) {
736 std::vector<EvalWell> mob_eval(this->num_conservation_quantities_, 0.);
737 for (std::size_t i = 0; i < mob.size(); ++i) {
738 mob_eval[i].setValue(mob[i]);
740 updateWaterMobilityWithPolymer(simulator, perf, mob_eval, deferred_logger);
741 for (std::size_t i = 0; i < mob.size(); ++i) {
742 mob[i] = getValue(mob_eval[i]);
745 updateWaterMobilityWithPolymer(simulator, perf, mob, deferred_logger);
752 const Scalar bhp = this->primary_variables_.value(Bhp);
753 const Scalar perf_press = bhp + this->connections_.pressure_diff(perf);
754 const Scalar multiplier = this->getInjMult(perf, bhp, perf_press, deferred_logger);
755 for (std::size_t i = 0; i < mob.size(); ++i) {
756 mob[i] *= multiplier;
762 template<
typename TypeTag>
770 if (!this->isOperableAndSolvable() && !this->wellIsStopped())
return;
774 const bool stop_or_zero_rate_target = this->stoppedOrZeroRateTarget(groupStateHelper);
775 updatePrimaryVariablesNewton(dwells, stop_or_zero_rate_target, deferred_logger);
777 const auto& summary_state = simulator.vanguard().summaryState();
778 updateWellStateFromPrimaryVariables(well_state, summary_state, deferred_logger);
782 const bool isThermal = simulator.vanguard().eclState().getSimulationConfig().isThermal();
783 const bool co2store = simulator.vanguard().eclState().runspec().co2Storage();
784 Base::calculateReservoirRates( (isThermal || co2store), well_state.
well(this->index_of_well_));
791 template<
typename TypeTag>
795 const bool stop_or_zero_rate_target,
798 const Scalar dFLimit = this->param_.dwell_fraction_max_;
799 const Scalar dBHPLimit = this->param_.dbhp_max_rel_;
800 this->primary_variables_.updateNewton(dwells, stop_or_zero_rate_target, dFLimit, dBHPLimit, deferred_logger);
803 if constexpr (Base::has_polymermw) {
804 this->primary_variables_.updateNewtonPolyMW(dwells);
807 this->primary_variables_.checkFinite(deferred_logger,
"Newton update");
814 template<
typename TypeTag>
818 const SummaryState& summary_state,
821 this->primary_variables_.copyToWellState(well_state, deferred_logger);
824 updateThp(getRefDensity(),
825 [
this,&well_state]() {
return this->baseif_.getALQ(well_state); },
826 well_state, summary_state, deferred_logger);
829 if constexpr (Base::has_polymermw) {
830 this->primary_variables_.copyToWellStatePolyMW(well_state);
838 template<
typename TypeTag>
846 std::ranges::fill(this->ipr_a_, 0.0);
847 std::ranges::fill(this->ipr_b_, 0.0);
849 for (
int perf = 0; perf < this->number_of_local_perforations_; ++perf) {
850 std::vector<Scalar> mob(this->num_conservation_quantities_, 0.0);
851 getMobility(simulator, perf, mob, deferred_logger);
853 const int cell_idx = this->well_cells_[perf];
854 const auto& int_quantities = simulator.model().intensiveQuantities(cell_idx, 0);
855 const auto& fs = int_quantities.fluidState();
857 Scalar p_r = this->getPerfCellPressure(fs).value();
860 std::vector<Scalar> b_perf(this->num_conservation_quantities_);
861 for (std::size_t phase = 0; phase < FluidSystem::numPhases; ++phase) {
862 if (!FluidSystem::phaseIsActive(phase)) {
865 const unsigned comp_idx = FluidSystem::canonicalToActiveCompIdx(FluidSystem::solventComponentIndex(phase));
866 b_perf[comp_idx] = fs.invB(phase).value();
868 if constexpr (has_solvent) {
869 b_perf[Indices::contiSolventEqIdx] = int_quantities.solventInverseFormationVolumeFactor().value();
873 const Scalar h_perf = this->connections_.pressure_diff(perf);
874 const Scalar pressure_diff = p_r - h_perf;
879 if ( (this->isProducer() && pressure_diff < 0.) || (this->isInjector() && pressure_diff > 0.) ) {
880 deferred_logger.
debug(
"CROSSFLOW_IPR",
881 "cross flow found when updateIPR for well " + name()
882 +
" . The connection is ignored in IPR calculations");
889 getTransMult(trans_mult, simulator, cell_idx);
890 const auto& wellstate_nupcol = simulator.problem().wellModel().nupcolWellState().well(this->index_of_well_);
891 std::vector<Scalar> tw_perf(this->num_conservation_quantities_, this->well_index_[perf] * trans_mult);
892 this->getTw(tw_perf, perf, int_quantities, trans_mult, wellstate_nupcol);
893 std::vector<Scalar> ipr_a_perf(this->ipr_a_.size());
894 std::vector<Scalar> ipr_b_perf(this->ipr_b_.size());
895 for (
int comp_idx = 0; comp_idx < this->num_conservation_quantities_; ++comp_idx) {
896 const Scalar tw_mob = tw_perf[comp_idx] * mob[comp_idx] * b_perf[comp_idx];
897 ipr_a_perf[comp_idx] += tw_mob * pressure_diff;
898 ipr_b_perf[comp_idx] += tw_mob;
902 if (FluidSystem::phaseIsActive(FluidSystem::oilPhaseIdx) && FluidSystem::phaseIsActive(FluidSystem::gasPhaseIdx)) {
903 const unsigned oil_comp_idx = FluidSystem::canonicalToActiveCompIdx(FluidSystem::oilCompIdx);
904 const unsigned gas_comp_idx = FluidSystem::canonicalToActiveCompIdx(FluidSystem::gasCompIdx);
905 const Scalar rs = (fs.Rs()).value();
906 const Scalar rv = (fs.Rv()).value();
908 const Scalar dis_gas_a = rs * ipr_a_perf[oil_comp_idx];
909 const Scalar vap_oil_a = rv * ipr_a_perf[gas_comp_idx];
911 ipr_a_perf[gas_comp_idx] += dis_gas_a;
912 ipr_a_perf[oil_comp_idx] += vap_oil_a;
914 const Scalar dis_gas_b = rs * ipr_b_perf[oil_comp_idx];
915 const Scalar vap_oil_b = rv * ipr_b_perf[gas_comp_idx];
917 ipr_b_perf[gas_comp_idx] += dis_gas_b;
918 ipr_b_perf[oil_comp_idx] += vap_oil_b;
921 for (std::size_t comp_idx = 0; comp_idx < ipr_a_perf.size(); ++comp_idx) {
922 this->ipr_a_[comp_idx] += ipr_a_perf[comp_idx];
923 this->ipr_b_[comp_idx] += ipr_b_perf[comp_idx];
926 this->parallel_well_info_.communication().sum(this->ipr_a_.data(), this->ipr_a_.size());
927 this->parallel_well_info_.communication().sum(this->ipr_b_.data(), this->ipr_b_.size());
930 template<
typename TypeTag>
945 auto rates = well_state.
well(this->index_of_well_).surface_rates;
947 for (std::size_t p = 0; p < rates.size(); ++p) {
948 zero_rates &= rates[p] == 0.0;
950 auto& ws = well_state.
well(this->index_of_well_);
952 const auto msg = fmt::format(
"updateIPRImplicit: Well {} has zero rate, IPRs might be problematic", this->name());
953 deferred_logger.debug(msg);
966 std::ranges::fill(ws.implicit_ipr_a, 0.0);
967 std::ranges::fill(ws.implicit_ipr_b, 0.0);
969 auto inj_controls = Well::InjectionControls(0);
970 auto prod_controls = Well::ProductionControls(0);
971 prod_controls.addControl(Well::ProducerCMode::BHP);
972 prod_controls.bhp_limit = well_state.
well(this->index_of_well_).bhp;
975 const auto cmode = ws.production_cmode;
976 ws.production_cmode = Well::ProducerCMode::BHP;
977 const double dt = simulator.timeStepSize();
978 assembleWellEqWithoutIteration(simulator, groupStateHelper, dt, inj_controls, prod_controls, well_state,
981 const size_t nEq = this->primary_variables_.numWellEq();
985 for (
size_t i=0; i < nEq; ++i){
991 x_well[0].resize(nEq);
992 this->linSys_.solve(rhs, x_well);
994 for (
int comp_idx = 0; comp_idx < this->num_conservation_quantities_; ++comp_idx){
995 EvalWell comp_rate = this->primary_variables_.getQs(comp_idx);
996 const int idx = FluidSystem::activeCompToActivePhaseIdx(comp_idx);
997 for (
size_t pvIdx = 0; pvIdx < nEq; ++pvIdx) {
999 ws.implicit_ipr_b[idx] -= x_well[0][pvIdx]*comp_rate.derivative(pvIdx+Indices::numEq);
1001 ws.implicit_ipr_a[idx] = ws.implicit_ipr_b[idx]*ws.bhp - comp_rate.value();
1004 ws.production_cmode = cmode;
1007 template<
typename TypeTag>
1014 const auto& summaryState = simulator.vanguard().summaryState();
1018 const bool bhp_limit_not_defaulted = bhp_limit > 1.5 * unit::barsa;
1019 if ( bhp_limit_not_defaulted || !this->wellHasTHPConstraints(summaryState) ) {
1022 Scalar total_ipr_mass_rate = 0.0;
1023 for (
unsigned phaseIdx = 0; phaseIdx < FluidSystem::numPhases; ++phaseIdx)
1025 if (!FluidSystem::phaseIsActive(phaseIdx)) {
1029 const unsigned compIdx = FluidSystem::canonicalToActiveCompIdx(FluidSystem::solventComponentIndex(phaseIdx));
1030 const Scalar ipr_rate = this->ipr_a_[compIdx] - this->ipr_b_[compIdx] * bhp_limit;
1032 const Scalar rho = FluidSystem::referenceDensity( phaseIdx, Base::pvtRegionIdx() );
1033 total_ipr_mass_rate += ipr_rate * rho;
1035 if ( (this->isProducer() && total_ipr_mass_rate < 0.) || (this->isInjector() && total_ipr_mass_rate > 0.) ) {
1036 this->operability_status_.operable_under_only_bhp_limit =
false;
1040 if (this->operability_status_.operable_under_only_bhp_limit && this->wellHasTHPConstraints(summaryState)) {
1044 std::vector<Scalar> well_rates_bhp_limit;
1045 computeWellRatesWithBhp(simulator, bhp_limit, well_rates_bhp_limit, deferred_logger);
1047 this->adaptRatesForVFP(well_rates_bhp_limit);
1048 const Scalar thp_limit = this->getTHPConstraint(summaryState);
1051 this->getRefDensity(),
1052 this->getALQ(well_state),
1055 if ( (this->isProducer() && thp < thp_limit) || (this->isInjector() && thp > thp_limit) ) {
1056 this->operability_status_.obey_thp_limit_under_bhp_limit =
false;
1067 this->operability_status_.operable_under_only_bhp_limit =
true;
1068 this->operability_status_.obey_thp_limit_under_bhp_limit =
false;
1076 template<
typename TypeTag>
1084 const auto& summaryState = simulator.vanguard().summaryState();
1085 const auto obtain_bhp = this->isProducer() ? computeBhpAtThpLimitProd(well_state, simulator, groupStateHelper, summaryState)
1086 : computeBhpAtThpLimitInj(simulator, groupStateHelper, summaryState);
1089 this->operability_status_.can_obtain_bhp_with_thp_limit =
true;
1092 this->operability_status_.obey_bhp_limit_with_thp_limit = this->isProducer() ?
1093 *obtain_bhp >= bhp_limit : *obtain_bhp <= bhp_limit ;
1095 const Scalar thp_limit = this->getTHPConstraint(summaryState);
1096 if (this->isProducer() && *obtain_bhp < thp_limit) {
1097 const std::string msg =
" obtained bhp " +
std::to_string(unit::convert::to(*obtain_bhp, unit::barsa))
1098 +
" bars is SMALLER than thp limit "
1100 +
" bars as a producer for well " + name();
1101 deferred_logger.debug(msg);
1103 else if (this->isInjector() && *obtain_bhp > thp_limit) {
1104 const std::string msg =
" obtained bhp " +
std::to_string(unit::convert::to(*obtain_bhp, unit::barsa))
1105 +
" bars is LARGER than thp limit "
1107 +
" bars as a injector for well " + name();
1108 deferred_logger.debug(msg);
1111 this->operability_status_.can_obtain_bhp_with_thp_limit =
false;
1112 this->operability_status_.obey_bhp_limit_with_thp_limit =
false;
1113 if (!this->wellIsStopped()) {
1114 const Scalar thp_limit = this->getTHPConstraint(summaryState);
1115 deferred_logger.debug(
" could not find bhp value at thp limit "
1117 +
" bar for well " + name() +
", the well might need to be closed ");
1126 template<
typename TypeTag>
1131 bool all_drawdown_wrong_direction =
true;
1133 for (
int perf = 0; perf < this->number_of_local_perforations_; ++perf) {
1134 const int cell_idx = this->well_cells_[perf];
1135 const auto& intQuants = simulator.model().intensiveQuantities(cell_idx, 0);
1136 const auto& fs = intQuants.fluidState();
1138 const Scalar pressure = this->getPerfCellPressure(fs).value();
1139 const Scalar bhp = this->primary_variables_.eval(Bhp).value();
1142 const Scalar well_pressure = bhp + this->connections_.pressure_diff(perf);
1143 const Scalar drawdown = pressure - well_pressure;
1148 if ( (drawdown < 0. && this->isInjector()) ||
1149 (drawdown > 0. && this->isProducer()) ) {
1150 all_drawdown_wrong_direction =
false;
1155 const auto& comm = this->parallel_well_info_.communication();
1156 if (comm.size() > 1)
1158 all_drawdown_wrong_direction =
1159 (comm.min(all_drawdown_wrong_direction ? 1 : 0) == 1);
1162 return all_drawdown_wrong_direction;
1168 template<
typename TypeTag>
1173 return !this->getAllowCrossFlow() && allDrawDownWrongDirection(simulator);
1179 template<
typename TypeTag>
1185 auto prop_func =
typename StdWellEval::StdWellConnections::PressurePropertyFunctions {
1187 [&model = simulator.model()](
int cell_idx,
int phase_idx)
1189 return model.intensiveQuantities(cell_idx, 0)
1190 .fluidState().temperature(phase_idx).value();
1194 [&model = simulator.model()](
int cell_idx)
1196 return model.intensiveQuantities(cell_idx, 0)
1197 .fluidState().saltConcentration().value();
1201 [&model = simulator.model()](
int cell_idx)
1203 return model.intensiveQuantities(cell_idx, 0)
1204 .fluidState().pvtRegionIndex();
1208 if constexpr (Indices::enableSolvent) {
1209 prop_func.solventInverseFormationVolumeFactor =
1210 [&model = simulator.model()](
int cell_idx)
1212 return model.intensiveQuantities(cell_idx, 0)
1213 .solventInverseFormationVolumeFactor().value();
1216 prop_func.solventRefDensity = [&model = simulator.model()](
int cell_idx)
1218 return model.intensiveQuantities(cell_idx, 0)
1219 .solventRefDensity();
1223 return this->connections_.computePropertiesForPressures(well_state, prop_func);
1230 template<
typename TypeTag>
1234 const std::vector<Scalar>& B_avg,
1235 const bool relax_tolerance)
const
1239 assert((
int(B_avg.size()) == this->num_conservation_quantities_) || has_polymer || has_energy || has_foam || has_brine || has_zFraction || has_bioeffects);
1242 Scalar tol_wells = this->param_.tolerance_wells_;
1244 constexpr Scalar stopped_factor = 1.e-4;
1246 constexpr Scalar dynamic_thp_factor = 1.e-1;
1247 if (this->stoppedOrZeroRateTarget(groupStateHelper)) {
1248 tol_wells = tol_wells*stopped_factor;
1249 }
else if (this->getDynamicThpLimit()) {
1250 tol_wells = tol_wells*dynamic_thp_factor;
1253 std::vector<Scalar> res;
1256 this->param_.max_residual_allowed_,
1258 this->param_.relaxed_tolerance_flow_well_,
1260 this->wellIsStopped(),
1264 checkConvergenceExtraEqs(res, report);
1273 template<
typename TypeTag>
1281 auto fluidState = [&simulator,
this](
const int perf)
1283 const auto cell_idx = this->well_cells_[perf];
1284 return simulator.model()
1285 .intensiveQuantities(cell_idx, 0).fluidState();
1288 const int np = this->number_of_phases_;
1289 auto setToZero = [np](
Scalar* x) ->
void
1291 std::fill_n(x, np, 0.0);
1294 auto addVector = [np](
const Scalar* src,
Scalar* dest) ->
void
1296 std::transform(src, src + np, dest, dest, std::plus<>{});
1299 auto& ws = well_state.
well(this->index_of_well_);
1300 auto& perf_data = ws.perf_data;
1301 auto* wellPI = ws.productivity_index.data();
1302 auto* connPI = perf_data.prod_index.data();
1306 const auto preferred_phase = this->well_ecl_.getPreferredPhase();
1307 auto subsetPerfID = 0;
1309 for (
const auto& perf : *this->perf_data_) {
1310 auto allPerfID = perf.ecl_index;
1312 auto connPICalc = [&wellPICalc, allPerfID](
const Scalar mobility) ->
Scalar
1317 std::vector<Scalar> mob(this->num_conservation_quantities_, 0.0);
1318 getMobility(simulator,
static_cast<int>(subsetPerfID), mob, deferred_logger);
1320 const auto& fs = fluidState(subsetPerfID);
1323 if (this->isInjector()) {
1324 this->computeConnLevelInjInd(fs, preferred_phase, connPICalc,
1325 mob, connPI, deferred_logger);
1328 this->computeConnLevelProdInd(fs, connPICalc, mob, connPI);
1331 addVector(connPI, wellPI);
1338 const auto& comm = this->parallel_well_info_.communication();
1339 if (comm.size() > 1) {
1340 comm.sum(wellPI, np);
1343 assert ((
static_cast<int>(subsetPerfID) == this->number_of_local_perforations_) &&
1344 "Internal logic error in processing connections for PI/II");
1349 template<
typename TypeTag>
1356 const auto& well_state = groupStateHelper.
wellState();
1360 const auto prop_func =
typename StdWellEval::StdWellConnections::DensityPropertyFunctions {
1365 [&model = simulator.model()](
const int cell,
1366 const std::vector<int>& phases,
1367 std::vector<Scalar>& mob)
1369 const auto& iq = model.intensiveQuantities(cell, 0);
1371 std::ranges::transform(phases, mob.begin(),
1372 [&iq](
const int phase) { return iq.mobility(phase).value(); });
1377 [&model = simulator.model()](
const int cell,
1378 const std::vector<int>& phases,
1379 std::vector<Scalar>& rho)
1381 const auto& fs = model.intensiveQuantities(cell, 0).fluidState();
1383 std::ranges::transform(phases, rho.begin(),
1384 [&fs](
const int phase) { return fs.density(phase).value(); });
1388 const auto stopped_or_zero_rate_target = this->
1389 stoppedOrZeroRateTarget(groupStateHelper);
1392 .computeProperties(stopped_or_zero_rate_target, well_state,
1393 prop_func, props, deferred_logger);
1395 cachedRefDensity = this->connections_.rho(0);
1396 if (this->parallel_well_info_.communication().size() > 1) {
1397 cachedRefDensity = this->parallel_well_info_.broadcastFirstPerforationValue(cachedRefDensity);
1405 template<
typename TypeTag>
1411 const auto& well_state = groupStateHelper.
wellState();
1412 const auto props = computePropertiesForWellConnectionPressures
1413 (simulator, well_state);
1415 computeWellConnectionDensitesPressures(simulator, groupStateHelper, props);
1422 template<
typename TypeTag>
1429 if (!this->isOperableAndSolvable() && !this->wellIsStopped())
return;
1434 dx_well[0].resize(this->primary_variables_.numWellEq());
1436 const auto linear_solve_timer = this->solveLinearSolveTimer();
1437 this->linSys_.solve( dx_well);
1440 updateWellState(simulator, dx_well, groupStateHelper, well_state);
1447 template<
typename TypeTag>
1453 updatePrimaryVariables(groupStateHelper);
1454 computeWellConnectionPressures(simulator, groupStateHelper);
1455 this->computeAccumWell();
1460 template<
typename TypeTag>
1465 if (!this->isOperableAndSolvable() && !this->wellIsStopped())
return;
1467 if (this->param_.matrix_add_well_contributions_)
1473 this->linSys_.apply(x, Ax);
1479 template<
typename TypeTag>
1484 if (!this->isOperableAndSolvable() && !this->wellIsStopped())
return;
1486 this->linSys_.apply(r);
1492 template<
typename TypeTag>
1500 if (!this->isOperableAndSolvable() && !this->wellIsStopped())
return;
1503 xw[0].resize(this->primary_variables_.numWellEq());
1505 this->linSys_.recoverSolutionWell(x, xw);
1506 updateWellState(simulator, xw, groupStateHelper, well_state);
1512 template<
typename TypeTag>
1517 std::vector<Scalar>& well_flux,
1521 const int np = this->number_of_phases_;
1522 well_flux.resize(np, 0.0);
1524 const bool allow_cf = this->getAllowCrossFlow();
1526 for (
int perf = 0; perf < this->number_of_local_perforations_; ++perf) {
1527 const int cell_idx = this->well_cells_[perf];
1528 const auto& intQuants = simulator.model().intensiveQuantities(cell_idx, 0);
1530 std::vector<Scalar> mob(this->num_conservation_quantities_, 0.);
1531 getMobility(simulator, perf, mob, deferred_logger);
1533 getTransMult(trans_mult, simulator, cell_idx);
1534 const auto& wellstate_nupcol = simulator.problem().wellModel().nupcolWellState().well(this->index_of_well_);
1535 std::vector<Scalar> Tw(this->num_conservation_quantities_, this->well_index_[perf] * trans_mult);
1536 this->getTw(Tw, perf, intQuants, trans_mult, wellstate_nupcol);
1538 std::vector<Scalar> cq_s(this->num_conservation_quantities_, 0.);
1540 computePerfRate(intQuants, mob, bhp, Tw, perf, allow_cf,
1541 cq_s, perf_rates, deferred_logger);
1543 for(
int p = 0; p < np; ++p) {
1544 well_flux[FluidSystem::activeCompToActivePhaseIdx(p)] += cq_s[p];
1548 if constexpr (has_solvent) {
1549 assert(FluidSystem::phaseIsActive(FluidSystem::gasPhaseIdx));
1551 const int gas_pos = FluidSystem::canonicalToActivePhaseIdx(FluidSystem::gasPhaseIdx);
1552 well_flux[gas_pos] += cq_s[Indices::contiSolventEqIdx];
1555 this->parallel_well_info_.communication().sum(well_flux.data(), well_flux.size());
1560 template<
typename TypeTag>
1566 std::vector<Scalar>& well_flux)
const
1582 auto guard = groupStateHelper_copy.
pushWellState(well_state_copy);
1585 const auto& summary_state = simulator.vanguard().summaryState();
1586 auto inj_controls = well_copy.
well_ecl_.isInjector()
1587 ? well_copy.
well_ecl_.injectionControls(summary_state)
1588 : Well::InjectionControls(0);
1589 auto prod_controls = well_copy.
well_ecl_.isProducer()
1590 ? well_copy.
well_ecl_.productionControls(summary_state) :
1591 Well::ProductionControls(0);
1594 auto& ws = well_state_copy.
well(this->index_of_well_);
1596 inj_controls.bhp_limit = bhp;
1597 ws.injection_cmode = Well::InjectorCMode::BHP;
1599 prod_controls.bhp_limit = bhp;
1600 ws.production_cmode = Well::ProducerCMode::BHP;
1605 const int np = this->number_of_phases_;
1606 const Scalar sign = this->well_ecl_.isInjector() ? 1.0 : -1.0;
1607 for (
int phase = 0; phase < np; ++phase){
1608 well_state_copy.
wellRates(this->index_of_well_)[phase]
1609 = sign * ws.well_potentials[phase];
1614 const double dt = simulator.timeStepSize();
1616 simulator, dt, inj_controls, prod_controls, groupStateHelper_copy, well_state_copy
1619 const std::string msg =
" well " + name() +
" did not get converged during well potential calculations "
1620 " potentials are computed based on unconverged solution";
1621 deferred_logger.debug(msg);
1631 template<
typename TypeTag>
1632 std::vector<typename StandardWell<TypeTag>::Scalar>
1639 std::vector<Scalar> potentials(this->number_of_phases_, 0.0);
1640 const auto& summary_state = simulator.vanguard().summaryState();
1642 const auto& well = this->well_ecl_;
1643 if (well.isInjector()){
1644 const auto& controls = this->well_ecl_.injectionControls(summary_state);
1645 auto bhp_at_thp_limit = computeBhpAtThpLimitInj(simulator, groupStateHelper, summary_state);
1646 if (bhp_at_thp_limit) {
1647 const Scalar bhp = std::min(*bhp_at_thp_limit,
1648 static_cast<Scalar>(controls.bhp_limit));
1649 computeWellRatesWithBhp(simulator, bhp, potentials, deferred_logger);
1651 deferred_logger.warning(
"FAILURE_GETTING_CONVERGED_POTENTIAL",
1652 "Failed in getting converged thp based potential calculation for well "
1653 + name() +
". Instead the bhp based value is used");
1654 const Scalar bhp = controls.bhp_limit;
1655 computeWellRatesWithBhp(simulator, bhp, potentials, deferred_logger);
1658 computeWellRatesWithThpAlqProd(
1659 simulator, groupStateHelper, summary_state,
1660 potentials, this->getALQ(well_state)
1667 template<
typename TypeTag>
1672 std::vector<Scalar>& well_potentials)
const
1685 auto guard = groupStateHelper_copy.
pushWellState(well_state_copy);
1686 auto& ws = well_state_copy.
well(this->index_of_well_);
1689 const auto& summary_state = simulator.vanguard().summaryState();
1690 auto inj_controls = well_copy.
well_ecl_.isInjector()
1691 ? well_copy.
well_ecl_.injectionControls(summary_state)
1692 : Well::InjectionControls(0);
1693 auto prod_controls = well_copy.
well_ecl_.isProducer()
1694 ? well_copy.
well_ecl_.productionControls(summary_state) :
1695 Well::ProductionControls(0);
1701 const int num_perf = ws.perf_data.size();
1702 for (
int perf = 0; perf < num_perf; ++perf) {
1706 const int np = this->number_of_phases_;
1707 bool trivial =
true;
1708 for (
int phase = 0; phase < np; ++phase){
1709 trivial = trivial && (ws.well_potentials[phase] == 0.0) ;
1713 for (
int phase = 0; phase < np; ++phase) {
1714 ws.surface_rates[phase] = sign * ws.well_potentials[phase];
1719 const double dt = simulator.timeStepSize();
1721 bool converged =
false;
1722 if (this->well_ecl_.isProducer()) {
1724 simulator, dt, inj_controls, prod_controls, groupStateHelper_copy, well_state_copy
1728 simulator, dt, inj_controls, prod_controls, groupStateHelper_copy, well_state_copy,
1736 well_potentials.clear();
1737 well_potentials.resize(np, 0.0);
1738 for (
int comp_idx = 0; comp_idx < this->num_conservation_quantities_; ++comp_idx) {
1739 if (has_solvent && comp_idx == Indices::contiSolventEqIdx)
continue;
1741 well_potentials[FluidSystem::activeCompToActivePhaseIdx(comp_idx)] = rate.value();
1745 if constexpr (has_solvent) {
1746 assert(FluidSystem::phaseIsActive(FluidSystem::gasPhaseIdx));
1748 const int gas_pos = FluidSystem::canonicalToActivePhaseIdx(FluidSystem::gasPhaseIdx);
1750 well_potentials[gas_pos] += rate.value();
1756 template<
typename TypeTag>
1761 const SummaryState &summary_state,
1762 std::vector<Scalar>& potentials,
1767 auto bhp_at_thp_limit = computeBhpAtThpLimitProdWithAlq(
1768 simulator, groupStateHelper, summary_state, alq,
true);
1769 if (bhp_at_thp_limit) {
1770 const auto& controls = this->well_ecl_.productionControls(summary_state);
1771 bhp = std::max(*bhp_at_thp_limit,
1772 static_cast<Scalar>(controls.bhp_limit));
1773 computeWellRatesWithBhp(simulator, bhp, potentials, deferred_logger);
1776 deferred_logger.warning(
"FAILURE_GETTING_CONVERGED_POTENTIAL",
1777 "Failed in getting converged thp based potential calculation for well "
1778 + name() +
". Instead the bhp based value is used");
1779 const auto& controls = this->well_ecl_.productionControls(summary_state);
1780 bhp = controls.bhp_limit;
1781 computeWellRatesWithBhp(simulator, bhp, potentials, deferred_logger);
1786 template<
typename TypeTag>
1791 const SummaryState& summary_state,
1792 std::vector<Scalar>& potentials,
1796 computeWellRatesAndBhpWithThpAlqProd(simulator,
1803 template<
typename TypeTag>
1809 std::vector<Scalar>& well_potentials)
1812 const auto [compute_potential, bhp_controlled_well] =
1815 if (!compute_potential) {
1821 const auto potential_scope = this->potentialCalculationScope();
1823 bool converged_implicit =
false;
1827 if (this->param_.local_well_solver_control_switching_ && !(this->changed_to_open_this_step_ && this->wellUnderZeroRateTarget(groupStateHelper))) {
1828 converged_implicit = computeWellPotentialsImplicit(
1829 simulator, groupStateHelper, well_potentials
1832 if (!converged_implicit) {
1834 const auto& summaryState = simulator.vanguard().summaryState();
1835 if (!Base::wellHasTHPConstraints(summaryState) || bhp_controlled_well) {
1845 const auto& ws = well_state.
well(this->index_of_well_);
1846 if (this->isInjector())
1847 bhp = std::max(ws.bhp, bhp);
1849 bhp = std::min(ws.bhp, bhp);
1851 assert(std::abs(bhp) != std::numeric_limits<Scalar>::max());
1852 computeWellRatesWithBhpIterations(simulator, bhp, groupStateHelper, well_potentials);
1855 well_potentials = computeWellPotentialWithTHP(simulator, groupStateHelper, well_state);
1859 this->checkNegativeWellPotentials(well_potentials,
1860 this->param_.check_well_operability_,
1870 template<
typename TypeTag>
1874 const int openConnIdx)
const
1876 return (openConnIdx < 0)
1878 : this->connections_.rho(openConnIdx);
1885 template<
typename TypeTag>
1890 if (!this->isOperableAndSolvable() && !this->wellIsStopped())
return;
1893 const auto& well_state = groupStateHelper.
wellState();
1894 const bool stop_or_zero_rate_target = this->stoppedOrZeroRateTarget(groupStateHelper);
1895 this->primary_variables_.update(well_state, stop_or_zero_rate_target, deferred_logger);
1898 if constexpr (Base::has_polymermw) {
1899 this->primary_variables_.updatePolyMW(well_state);
1902 this->primary_variables_.checkFinite(deferred_logger,
"updating from well state");
1908 template<
typename TypeTag>
1913 return cachedRefDensity;
1919 template<
typename TypeTag>
1924 std::vector<EvalWell>& mob,
1927 const int cell_idx = this->well_cells_[perf];
1928 const auto& int_quant = simulator.model().intensiveQuantities(cell_idx, 0);
1929 const EvalWell polymer_concentration = this->extendEval(int_quant.polymerConcentration());
1933 if (this->isInjector()) {
1935 const auto& visc_mult_table = PolymerModule::plyviscViscosityMultiplierTable(int_quant.pvtRegionIndex());
1936 const unsigned waterCompIdx = FluidSystem::canonicalToActiveCompIdx(FluidSystem::waterCompIdx);
1937 mob[waterCompIdx] /= (this->extendEval(int_quant.waterViscosityCorrection()) * visc_mult_table.eval(polymer_concentration,
true) );
1940 if (PolymerModule::hasPlyshlog()) {
1943 if (this->isInjector() && this->wpolymer() == 0.) {
1948 const bool allow_cf = this->getAllowCrossFlow() || openCrossFlowAvoidSingularity(simulator);
1949 const EvalWell& bhp = this->primary_variables_.eval(Bhp);
1951 std::vector<EvalWell> cq_s(this->num_conservation_quantities_, 0.);
1954 getTransMult(trans_mult, simulator, cell_idx);
1955 const auto& wellstate_nupcol = simulator.problem().wellModel().nupcolWellState().well(this->index_of_well_);
1956 std::vector<EvalWell> Tw(this->num_conservation_quantities_, this->well_index_[perf] * trans_mult);
1957 this->getTw(Tw, perf, int_quant, trans_mult, wellstate_nupcol);
1958 computePerfRate(int_quant, mob, bhp, Tw, perf, allow_cf, cq_s,
1959 perf_rates, deferred_logger);
1961 const Scalar area = 2 * std::numbers::pi_v<Scalar> * this->perf_rep_radius_[perf] * this->perf_length_[perf];
1962 const auto& material_law_manager = simulator.problem().materialLawManager();
1963 const auto& scaled_drainage_info =
1964 material_law_manager->oilWaterScaledEpsInfoDrainage(cell_idx);
1965 const Scalar swcr = scaled_drainage_info.Swcr;
1966 const EvalWell poro = this->extendEval(int_quant.porosity());
1967 const EvalWell sw = this->extendEval(int_quant.fluidState().saturation(FluidSystem::waterPhaseIdx));
1969 const EvalWell denom = max( (area * poro * (sw - swcr)), 1e-12);
1970 const unsigned waterCompIdx = FluidSystem::canonicalToActiveCompIdx(FluidSystem::waterCompIdx);
1971 EvalWell water_velocity = cq_s[waterCompIdx] / denom * this->extendEval(int_quant.fluidState().invB(FluidSystem::waterPhaseIdx));
1973 if (PolymerModule::hasShrate()) {
1976 water_velocity *= PolymerModule::shrate( int_quant.pvtRegionIndex() ) / this->bore_diameters_[perf];
1978 const EvalWell shear_factor = PolymerModule::computeShearFactor(polymer_concentration,
1979 int_quant.pvtRegionIndex(),
1982 mob[waterCompIdx] /= shear_factor;
1986 template<
typename TypeTag>
1990 this->linSys_.extract(jacobian);
1994 template <
typename TypeTag>
1998 const int pressureVarIndex,
1999 const bool use_well_weights,
2002 this->linSys_.extractCPRPressureMatrix(jacobian,
2013 template<
typename TypeTag>
2020 if constexpr (Base::has_polymermw) {
2021 const int water_table_id = this->polymerWaterTable_();
2022 if (water_table_id <= 0) {
2024 fmt::format(
"Unused SKPRWAT table id used for well {}", name()),
2027 const auto& water_table_func = PolymerModule::getSkprwatTable(water_table_id);
2028 const EvalWell throughput_eval{throughput};
2030 EvalWell pskin_water = water_table_func.eval(throughput_eval, water_velocity);
2034 fmt::format(
"Polymermw is not activated, while injecting "
2035 "skin pressure is requested for well {}", name()),
2044 template<
typename TypeTag>
2052 if constexpr (Base::has_polymermw) {
2053 const Scalar sign = water_velocity >= 0. ? 1.0 : -1.0;
2054 const EvalWell water_velocity_abs = abs(water_velocity);
2055 if (poly_inj_conc == 0.) {
2056 return sign * pskinwater(throughput, water_velocity_abs, deferred_logger);
2058 const int polymer_table_id = this->polymerTable_();
2059 if (polymer_table_id <= 0) {
2061 fmt::format(
"Unavailable SKPRPOLY table id used for well {}", name()),
2064 const auto& skprpolytable = PolymerModule::getSkprpolyTable(polymer_table_id);
2065 const Scalar reference_concentration = skprpolytable.refConcentration;
2066 const EvalWell throughput_eval{throughput};
2068 const EvalWell pskin_poly = skprpolytable.table_func.eval(throughput_eval, water_velocity_abs);
2069 if (poly_inj_conc == reference_concentration) {
2070 return sign * pskin_poly;
2073 const EvalWell pskin_water = pskinwater(throughput, water_velocity_abs, deferred_logger);
2074 const EvalWell pskin = pskin_water + (pskin_poly - pskin_water) / reference_concentration * poly_inj_conc;
2075 return sign * pskin;
2078 fmt::format(
"Polymermw is not activated, while injecting "
2079 "skin pressure is requested for well {}", name()),
2088 template<
typename TypeTag>
2095 if constexpr (Base::has_polymermw) {
2096 const int table_id = this->polymerInjTable_();
2097 const auto& table_func = PolymerModule::getPlymwinjTable(table_id);
2098 const EvalWell throughput_eval{throughput};
2100 if (this->wpolymer() == 0.) {
2101 return molecular_weight;
2103 molecular_weight = table_func.eval(throughput_eval, abs(water_velocity));
2104 return molecular_weight;
2107 fmt::format(
"Polymermw is not activated, while injecting "
2108 "polymer molecular weight is requested for well {}", name()),
2117 template<
typename TypeTag>
2123 if constexpr (Base::has_polymermw) {
2124 if (!this->isInjector()) {
2128 auto& perf_water_throughput = well_state.
well(this->index_of_well_)
2129 .perf_data.water_throughput;
2131 for (
int perf = 0; perf < this->number_of_local_perforations_; ++perf) {
2132 const Scalar perf_water_vel =
2133 this->primary_variables_.value(Bhp + 1 + perf);
2137 if (perf_water_vel >
Scalar{0}) {
2138 perf_water_throughput[perf] += perf_water_vel * dt;
2148 template<
typename TypeTag>
2153 std::vector<EvalWell>& cq_s)
const
2155 const int cell_idx = this->well_cells_[perf];
2156 const auto& int_quants = simulator.model().intensiveQuantities(cell_idx, 0);
2157 const auto& fs = int_quants.fluidState();
2158 const EvalWell b_w = this->extendEval(fs.invB(FluidSystem::waterPhaseIdx));
2159 const Scalar area = std::numbers::pi_v<Scalar> * this->bore_diameters_[perf] * this->perf_length_[perf];
2160 const int wat_vel_index = Bhp + 1 + perf;
2161 const unsigned water_comp_idx = FluidSystem::canonicalToActiveCompIdx(FluidSystem::waterCompIdx);
2165 cq_s[water_comp_idx] = area * this->primary_variables_.eval(wat_vel_index) * b_w;
2171 template<
typename TypeTag>
2180 const int cell_idx = this->well_cells_[perf];
2181 const auto& int_quants = simulator.model().intensiveQuantities(cell_idx, 0);
2182 const auto& fs = int_quants.fluidState();
2183 const EvalWell b_w = this->extendEval(fs.invB(FluidSystem::waterPhaseIdx));
2184 const EvalWell water_flux_r = water_flux_s / b_w;
2185 const Scalar area = std::numbers::pi_v<Scalar> * this->bore_diameters_[perf] * this->perf_length_[perf];
2186 const EvalWell water_velocity = water_flux_r / area;
2187 const int wat_vel_index = Bhp + 1 + perf;
2190 const EvalWell eq_wat_vel = this->primary_variables_.eval(wat_vel_index) - water_velocity;
2192 const auto& ws = well_state.
well(this->index_of_well_);
2193 const auto& perf_data = ws.perf_data;
2194 const auto& perf_water_throughput = perf_data.water_throughput;
2195 const Scalar throughput = perf_water_throughput[perf];
2196 const int pskin_index = Bhp + 1 + this->number_of_local_perforations_ + perf;
2198 const EvalWell poly_conc(this->wpolymer());
2201 const EvalWell eq_pskin = this->primary_variables_.eval(pskin_index)
2202 - pskin(throughput, this->primary_variables_.eval(wat_vel_index), poly_conc, deferred_logger);
2205 assembleInjectivityEq(eq_pskin,
2210 this->primary_variables_.numWellEq(),
2218 template<
typename TypeTag>
2227 if constexpr (Base::has_polymermw) {
2229 checkConvergencePolyMW(res, Bhp, this->param_.max_residual_allowed_, report);
2237 template<
typename TypeTag>
2244 std::vector<RateVector>& connectionRates,
2249 if (this->isInjector()) {
2250 const int wat_vel_index = Bhp + 1 + perf;
2251 const EvalWell water_velocity = this->primary_variables_.eval(wat_vel_index);
2252 if (water_velocity > 0.) {
2253 const auto& ws = well_state.
well(this->index_of_well_);
2254 const auto& perf_water_throughput = ws.perf_data.water_throughput;
2255 const Scalar throughput = perf_water_throughput[perf];
2256 const EvalWell molecular_weight = wpolymermw(throughput, water_velocity, deferred_logger);
2257 cq_s_polymw *= molecular_weight;
2263 }
else if (this->isProducer()) {
2264 if (cq_s_polymw < 0.) {
2265 cq_s_polymw *= this->extendEval(int_quants.polymerMoleWeight() );
2272 connectionRates[perf][Indices::contiPolymerMWEqIdx] = Base::restrictEval(cq_s_polymw);
2279 template<
typename TypeTag>
2280 std::optional<typename StandardWell<TypeTag>::Scalar>
2285 const SummaryState& summary_state)
const
2287 return computeBhpAtThpLimitProdWithAlq(simulator,
2290 this->getALQ(well_state),
2294 template<
typename TypeTag>
2295 std::optional<typename StandardWell<TypeTag>::Scalar>
2299 const SummaryState& summary_state,
2301 bool iterate_if_no_solution)
const
2306 auto frates = [
this, &simulator, &deferred_logger](
const Scalar bhp) {
2312 std::vector<Scalar> rates(3);
2313 computeWellRatesWithBhp(simulator, bhp, rates, deferred_logger);
2314 this->adaptRatesForVFP(rates);
2319 maxPerfPress(simulator),
2320 this->getRefDensity(),
2322 this->getTHPConstraint(summary_state),
2326 auto v = frates(*bhpAtLimit);
2327 if (std::ranges::all_of(v, [](
Scalar i) {
return i <= 0; })) {
2332 if (!iterate_if_no_solution)
2333 return std::nullopt;
2335 auto fratesIter = [
this, &simulator, &groupStateHelper](
const Scalar bhp) {
2339 std::vector<Scalar> rates(3);
2340 computeWellRatesWithBhpIterations(simulator, bhp, groupStateHelper, rates);
2341 this->adaptRatesForVFP(rates);
2347 maxPerfPress(simulator),
2348 this->getRefDensity(),
2350 this->getTHPConstraint(summary_state),
2356 auto v = frates(*bhpAtLimit);
2357 if (std::ranges::all_of(v, [](
Scalar i) {
return i <= 0; })) {
2363 return std::nullopt;
2368 template<
typename TypeTag>
2369 std::optional<typename StandardWell<TypeTag>::Scalar>
2373 const SummaryState& summary_state)
const
2377 auto frates = [
this, &simulator, &deferred_logger](
const Scalar bhp) {
2383 std::vector<Scalar> rates(3);
2384 computeWellRatesWithBhp(simulator, bhp, rates, deferred_logger);
2390 this->getRefDensity(),
2401 template<
typename TypeTag>
2406 const Well::InjectionControls& inj_controls,
2407 const Well::ProductionControls& prod_controls,
2413 updatePrimaryVariables(groupStateHelper);
2415 const int max_iter = this->param_.max_inner_iter_wells_;
2417 const auto solve_scope = this->solveScope(it);
2419 bool relax_convergence =
false;
2420 this->regularize_ =
false;
2422 assembleWellEqWithoutIteration(simulator, groupStateHelper, dt, inj_controls, prod_controls, well_state,
2425 if (it > this->param_.strict_inner_iter_wells_) {
2426 relax_convergence =
true;
2427 this->regularize_ =
true;
2430 auto report = getWellConvergence(groupStateHelper, Base::B_avg_, relax_convergence);
2432 converged = report.converged();
2438 solveEqAndUpdateWellState(simulator, groupStateHelper, well_state);
2445 }
while (it < max_iter);
2448 std::ostringstream sstr;
2449 sstr <<
" Well " << this->name() <<
" converged in " << it <<
" inner iterations.";
2450 if (relax_convergence)
2451 sstr <<
" (A relaxed tolerance was used after "<< this->param_.strict_inner_iter_wells_ <<
" iterations)";
2455 deferred_logger.debug(sstr.str(), OpmLog::defaultDebugVerbosityLevel + (it == 0));
2457 std::ostringstream sstr;
2458 sstr <<
" Well " << this->name() <<
" did not converge in " << it <<
" inner iterations.";
2459 deferred_logger.debug(sstr.str());
2466 template<
typename TypeTag>
2471 const Well::InjectionControls& inj_controls,
2472 const Well::ProductionControls& prod_controls,
2475 const bool fixed_control ,
2476 const bool fixed_status ,
2477 const bool solving_with_zero_rate )
2481 updatePrimaryVariables(groupStateHelper);
2483 const int max_iter = this->param_.max_inner_iter_wells_;
2485 const auto solve_scope = this->solveScope(it);
2486 bool converged =
false;
2487 bool relax_convergence =
false;
2488 this->regularize_ =
false;
2489 const auto& summary_state = groupStateHelper.
summaryState();
2494 constexpr int min_its_after_switch = 4;
2496 const int max_status_switch = this->param_.max_well_status_switch_inner_iter_;
2497 int its_since_last_switch = min_its_after_switch;
2498 int switch_count= 0;
2500 const auto well_status_orig = this->wellStatus_;
2501 const auto operability_orig = this->operability_status_;
2502 auto well_status_cur = well_status_orig;
2503 int status_switch_count = 0;
2505 const bool allow_open = well_state.
well(this->index_of_well_).status == WellStatus::OPEN;
2507 const bool allow_switching =
2508 !this->wellUnderZeroRateTarget(groupStateHelper) &&
2509 (!fixed_control || !fixed_status) && allow_open;
2511 bool changed =
false;
2512 bool final_check =
false;
2514 this->operability_status_.resetOperability();
2515 this->operability_status_.solvable =
true;
2517 its_since_last_switch++;
2518 if (allow_switching && its_since_last_switch >= min_its_after_switch && status_switch_count < max_status_switch){
2519 const Scalar wqTotal = this->primary_variables_.eval(WQTotal).value();
2520 changed = this->updateWellControlAndStatusLocalIteration(
2521 simulator, groupStateHelper, inj_controls, prod_controls, wqTotal,
2522 well_state, fixed_control, fixed_status,
2523 solving_with_zero_rate
2526 its_since_last_switch = 0;
2528 if (well_status_cur != this->wellStatus_) {
2529 well_status_cur = this->wellStatus_;
2530 status_switch_count++;
2533 if (!changed && final_check) {
2536 final_check =
false;
2538 if (status_switch_count == max_status_switch) {
2539 this->wellStatus_ = well_status_orig;
2543 assembleWellEqWithoutIteration(simulator, groupStateHelper, dt, inj_controls, prod_controls, well_state, solving_with_zero_rate);
2545 if (it > this->param_.strict_inner_iter_wells_) {
2546 relax_convergence =
true;
2547 this->regularize_ =
true;
2550 auto report = getWellConvergence(groupStateHelper, Base::B_avg_, relax_convergence);
2552 converged = report.converged();
2556 if (switch_count > 0 && its_since_last_switch < min_its_after_switch) {
2558 its_since_last_switch = min_its_after_switch;
2565 solveEqAndUpdateWellState(simulator, groupStateHelper, well_state);
2567 }
while (it < max_iter);
2570 if (allow_switching){
2572 const bool is_stopped = this->wellIsStopped();
2573 if (this->wellHasTHPConstraints(summary_state)){
2574 this->operability_status_.can_obtain_bhp_with_thp_limit = !is_stopped;
2575 this->operability_status_.obey_thp_limit_under_bhp_limit = !is_stopped;
2577 this->operability_status_.operable_under_only_bhp_limit = !is_stopped;
2580 std::string message = fmt::format(
" Well {} converged in {} inner iterations ("
2581 "{} control/status switches).", this->name(), it, switch_count);
2582 if (relax_convergence) {
2583 message.append(fmt::format(
" (A relaxed tolerance was used after {} iterations)",
2584 this->param_.strict_inner_iter_wells_));
2586 deferred_logger.debug(message, OpmLog::defaultDebugVerbosityLevel + ((it == 0) && (switch_count == 0)));
2589 this->wellStatus_ = well_status_orig;
2590 this->operability_status_ = operability_orig;
2591 const std::string message = fmt::format(
" Well {} did not converge in {} inner iterations ("
2592 "{} switches, {} status changes).", this->name(), it, switch_count, status_switch_count);
2593 deferred_logger.debug(message);
2599 template<
typename TypeTag>
2600 std::vector<typename StandardWell<TypeTag>::Scalar>
2606 std::vector<Scalar> well_q_s(this->num_conservation_quantities_, 0.);
2607 const EvalWell& bhp = this->primary_variables_.eval(Bhp);
2608 const bool allow_cf = this->getAllowCrossFlow() || openCrossFlowAvoidSingularity(simulator);
2609 for (
int perf = 0; perf < this->number_of_local_perforations_; ++perf) {
2610 const int cell_idx = this->well_cells_[perf];
2611 const auto& intQuants = simulator.model().intensiveQuantities(cell_idx, 0);
2612 std::vector<Scalar> mob(this->num_conservation_quantities_, 0.);
2613 getMobility(simulator, perf, mob, deferred_logger);
2614 std::vector<Scalar> cq_s(this->num_conservation_quantities_, 0.);
2616 getTransMult(trans_mult, simulator, cell_idx);
2617 const auto& wellstate_nupcol = simulator.problem().wellModel().nupcolWellState().well(this->index_of_well_);
2618 std::vector<Scalar> Tw(this->num_conservation_quantities_, this->well_index_[perf] * trans_mult);
2619 this->getTw(Tw, perf, intQuants, trans_mult, wellstate_nupcol);
2621 computePerfRate(intQuants, mob, bhp.value(), Tw, perf, allow_cf,
2622 cq_s, perf_rates, deferred_logger);
2623 for (
int comp = 0; comp < this->num_conservation_quantities_; ++comp) {
2624 well_q_s[comp] += cq_s[comp];
2627 const auto& comm = this->parallel_well_info_.communication();
2628 if (comm.size() > 1)
2630 comm.sum(well_q_s.data(), well_q_s.size());
2637 template <
typename TypeTag>
2638 std::vector<typename StandardWell<TypeTag>::Scalar>
2642 const int num_pri_vars = this->primary_variables_.numWellEq();
2643 std::vector<Scalar> retval(num_pri_vars);
2644 for (
int ii = 0; ii < num_pri_vars; ++ii) {
2645 retval[ii] = this->primary_variables_.value(ii);
2654 template <
typename TypeTag>
2659 const int num_pri_vars = this->primary_variables_.numWellEq();
2660 for (
int ii = 0; ii < num_pri_vars; ++ii) {
2661 this->primary_variables_.setValue(ii, it[ii]);
2663 return num_pri_vars;
2667 template <
typename TypeTag>
2673 this->primary_variables_.scaledWellFractions(scaled_fractions, deferred_logger);
2677 template <
typename TypeTag>
2681 const IntensiveQuantities& intQuants,
2684 auto fs = intQuants.fluidState();
2686 for (
unsigned phaseIdx = 0; phaseIdx < FluidSystem::numPhases; ++phaseIdx) {
2687 if (!FluidSystem::phaseIsActive(phaseIdx)) {
2692 EvalWell cq_r_thermal{0.};
2693 const unsigned activeCompIdx = FluidSystem::canonicalToActiveCompIdx(FluidSystem::solventComponentIndex(phaseIdx));
2694 const bool both_oil_gas = FluidSystem::phaseIsActive(FluidSystem::oilPhaseIdx) && FluidSystem::phaseIsActive(FluidSystem::gasPhaseIdx);
2695 if (!both_oil_gas || FluidSystem::waterPhaseIdx == phaseIdx) {
2696 cq_r_thermal = cq_s[activeCompIdx] / this->extendEval(fs.invB(phaseIdx));
2699 const unsigned oilCompIdx = FluidSystem::canonicalToActiveCompIdx(FluidSystem::oilCompIdx);
2700 const unsigned gasCompIdx = FluidSystem::canonicalToActiveCompIdx(FluidSystem::gasCompIdx);
2705 const EvalWell d = this->extendEval(1.0 - fs.Rv() * fs.Rs());
2707 deferred_logger.
debug(
2708 fmt::format(
"Problematic d value {} obtained for well {}"
2709 " during calculateSinglePerf with rs {}"
2710 ", rv {}. Continue as if no dissolution (rs = 0) and"
2711 " vaporization (rv = 0) for this connection.",
2712 d, this->name(), fs.Rs(), fs.Rv()));
2713 cq_r_thermal = cq_s[activeCompIdx] / this->extendEval(fs.invB(phaseIdx));
2715 if (FluidSystem::gasPhaseIdx == phaseIdx) {
2716 cq_r_thermal = (cq_s[gasCompIdx] -
2717 this->extendEval(fs.Rs()) * cq_s[oilCompIdx]) /
2718 (d * this->extendEval(fs.invB(phaseIdx)) );
2719 }
else if (FluidSystem::oilPhaseIdx == phaseIdx) {
2721 cq_r_thermal = (cq_s[oilCompIdx] - this->extendEval(fs.Rv()) *
2723 (d * this->extendEval(fs.invB(phaseIdx)) );
2729 if (this->isInjector() && !this->wellIsStopped() && cq_r_thermal > 0.0){
2731 assert(this->well_ecl_.injectorType() != InjectorType::MULTI);
2732 fs.setTemperature(this->well_ecl_.inj_temperature());
2733 typedef typename std::decay<
decltype(fs)>::type::ValueType FsValueType;
2734 typename FluidSystem::template ParameterCache<FsValueType> paramCache;
2735 const unsigned pvtRegionIdx = intQuants.pvtRegionIndex();
2736 paramCache.setRegionIndex(pvtRegionIdx);
2737 paramCache.updatePhase(fs, phaseIdx);
2739 const auto& rho = FluidSystem::density(fs, paramCache, phaseIdx);
2740 fs.setDensity(phaseIdx, rho);
2741 const auto& h = FluidSystem::enthalpy(fs, paramCache, phaseIdx);
2742 fs.setEnthalpy(phaseIdx, h);
2743 cq_r_thermal *= this->extendEval(fs.enthalpy(phaseIdx)) * this->extendEval(fs.density(phaseIdx));
2744 result += getValue(cq_r_thermal);
2745 }
else if (cq_r_thermal > 0.0) {
2746 cq_r_thermal *= getValue(fs.enthalpy(phaseIdx)) * getValue(fs.density(phaseIdx));
2747 result += Base::restrictEval(cq_r_thermal);
2750 cq_r_thermal *= this->extendEval(fs.enthalpy(phaseIdx)) * this->extendEval(fs.density(phaseIdx));
2751 result += Base::restrictEval(cq_r_thermal);
2755 return result * this->well_efficiency_factor_;
2758 template <
typename TypeTag>
2762 Scalar max_pressure = 0.0;
2763 for (
int perf = 0; perf < this->number_of_local_perforations_; ++perf) {
2764 const int cell_idx = this->well_cells_[perf];
2765 const auto& int_quants = simulator.model().intensiveQuantities(cell_idx, 0);
2766 const auto& fs = int_quants.fluidState();
2767 Scalar pressure_cell = this->getPerfCellPressure(fs).value();
2768 max_pressure = std::max(max_pressure, pressure_cell);
2770 const auto& comm = this->parallel_well_info_.communication();
2771 if (comm.size() > 1) {
2772 max_pressure = comm.max(max_pressure);
2774 return max_pressure;
#define OPM_DEFLOG_THROW(Exception, message, deferred_logger)
Definition: DeferredLoggingErrorHelpers.hpp:47
#define OPM_DEFLOG_PROBLEM(Exception, message, deferred_logger)
Definition: DeferredLoggingErrorHelpers.hpp:63
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:441
const WellState< Scalar, IndexTraits > & wellState() const
Definition: GroupStateHelper.hpp:522
DeferredLogger & deferredLogger() const
Get the deferred logger.
Definition: GroupStateHelper.hpp:233
WellStateGuard pushWellState(WellState< Scalar, IndexTraits > &well_state)
Definition: GroupStateHelper.hpp:380
GroupStateGuard pushGroupState(GroupState< Scalar > &group_state)
Definition: GroupStateHelper.hpp:357
Definition: GroupState.hpp:42
Class encapsulating some information about parallel wells.
Definition: ParallelWellInfo.hpp:217
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:120
PrimaryVariables primary_variables_
Primary variables for well.
Definition: StandardWellEval.hpp:114
Definition: StandardWell.hpp:55
void getScaledWellFractions(std::vector< Scalar > &scaled_fractions, DeferredLogger &deferred_logger) const override
Definition: StandardWell_impl.hpp:2670
EvalWell wpolymermw(const Scalar throughput, const EvalWell &water_velocity, DeferredLogger &deferred_logger) const
Definition: StandardWell_impl.hpp:2091
std::vector< Scalar > computeWellPotentialWithTHP(const Simulator &ebosSimulator, const GroupStateHelperType &groupStateHelper, const WellStateType &well_state) const
Definition: StandardWell_impl.hpp:1634
typename StdWellEval::EvalWell EvalWell
Definition: StandardWell.hpp:116
void updateWellStateFromPrimaryVariables(WellStateType &well_state, const SummaryState &summary_state, DeferredLogger &deferred_logger) const
Definition: StandardWell_impl.hpp:817
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:1233
WellConnectionProps computePropertiesForWellConnectionPressures(const Simulator &simulator, const WellStateType &well_state) const
Definition: StandardWell_impl.hpp:1182
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:2297
typename StdWellEval::BVectorWell BVectorWell
Definition: StandardWell.hpp:117
void addWellContributions(SparseMatrixAdapter &mat) const override
Definition: StandardWell_impl.hpp:1988
std::vector< Scalar > getPrimaryVars() const override
Definition: StandardWell_impl.hpp:2640
void updateWellState(const Simulator &simulator, const BVectorWell &dwells, const GroupStateHelperType &groupStateHelper, WellStateType &well_state)
Definition: StandardWell_impl.hpp:765
void updatePrimaryVariables(const GroupStateHelperType &groupStateHelper) override
Definition: StandardWell_impl.hpp:1888
void solveEqAndUpdateWellState(const Simulator &simulator, const GroupStateHelperType &groupStateHelper, WellStateType &well_state) override
Definition: StandardWell_impl.hpp:1425
void computeWellConnectionDensitesPressures(const Simulator &simulator, const GroupStateHelperType &groupStateHelper, const WellConnectionProps &props)
Definition: StandardWell_impl.hpp:1351
std::optional< Scalar > computeBhpAtThpLimitProd(const WellStateType &well_state, const Simulator &simulator, const GroupStateHelperType &groupStateHelper, const SummaryState &summary_state) const
Definition: StandardWell_impl.hpp:2282
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:1996
void updateWaterMobilityWithPolymer(const Simulator &simulator, const int perf, std::vector< EvalWell > &mob_water, DeferredLogger &deferred_logger) const
Definition: StandardWell_impl.hpp:1922
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:2404
std::vector< Scalar > computeCurrentWellRates(const Simulator &ebosSimulator, DeferredLogger &deferred_logger) const override
Definition: StandardWell_impl.hpp:2602
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:511
void computeWellConnectionPressures(const Simulator &simulator, const GroupStateHelperType &groupStateHelper)
Definition: StandardWell_impl.hpp:1408
void updatePrimaryVariablesNewton(const BVectorWell &dwells, const bool stop_or_zero_rate_target, DeferredLogger &deferred_logger)
Definition: StandardWell_impl.hpp:794
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:85
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:1806
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:2371
typename StdWellEval::StdWellConnections::Properties WellConnectionProps
Definition: StandardWell.hpp:276
void computeWellRatesWithBhpIterations(const Simulator &ebosSimulator, const Scalar &bhp, const GroupStateHelperType &groupStateHelper, std::vector< Scalar > &well_flux) const override
Definition: StandardWell_impl.hpp:1563
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:2240
void computeWellRatesWithBhp(const Simulator &ebosSimulator, const Scalar &bhp, std::vector< Scalar > &well_flux, DeferredLogger &deferred_logger) const override
Definition: StandardWell_impl.hpp:1515
void updateIPRImplicit(const Simulator &simulator, const GroupStateHelperType &groupStateHelper, WellStateType &well_state) override
Definition: StandardWell_impl.hpp:933
void getMobility(const Simulator &simulator, const int perf, std::vector< Value > &mob, DeferredLogger &deferred_logger) const
Definition: StandardWell_impl.hpp:709
void getTransMult(Value &trans_mult, const Simulator &simulator, const int cell_indx) const
Definition: StandardWell_impl.hpp:689
void updateIPR(const Simulator &simulator, DeferredLogger &deferred_logger) const override
Definition: StandardWell_impl.hpp:841
void handleInjectivityEquations(const Simulator &simulator, const WellStateType &well_state, const int perf, const EvalWell &water_flux_s, DeferredLogger &deferred_logger)
Definition: StandardWell_impl.hpp:2174
virtual void apply(const BVector &x, BVector &Ax) const override
Ax = Ax - C D^-1 B x.
Definition: StandardWell_impl.hpp:1463
void checkConvergenceExtraEqs(const std::vector< Scalar > &res, ConvergenceReport &report) const
Definition: StandardWell_impl.hpp:2221
void computeWellRatesWithThpAlqProd(const Simulator &ebos_simulator, const GroupStateHelperType &groupStateHelper, const SummaryState &summary_state, std::vector< Scalar > &potentials, Scalar alq) const
Definition: StandardWell_impl.hpp:1789
typename StdWellEval::Eval Eval
Definition: StandardWell.hpp:115
Scalar computeWellRatesAndBhpWithThpAlqProd(const Simulator &ebos_simulator, const GroupStateHelperType &groupStateHelper, const SummaryState &summary_state, std::vector< Scalar > &potentials, Scalar alq) const
Definition: StandardWell_impl.hpp:1759
bool openCrossFlowAvoidSingularity(const Simulator &simulator) const
Definition: StandardWell_impl.hpp:1171
bool computeWellPotentialsImplicit(const Simulator &ebos_simulator, const GroupStateHelperType &groupStateHelper, std::vector< Scalar > &well_potentials) const
Definition: StandardWell_impl.hpp:1670
void recoverWellSolutionAndUpdateWellState(const Simulator &simulator, const BVector &x, const GroupStateHelperType &groupStateHelper, WellStateType &well_state) override
Definition: StandardWell_impl.hpp:1495
Scalar maxPerfPress(const Simulator &simulator) const override
Definition: StandardWell_impl.hpp:2761
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:2469
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:369
bool allDrawDownWrongDirection(const Simulator &simulator) const
Definition: StandardWell_impl.hpp:1129
EvalWell pskin(const Scalar throughput, const EvalWell &water_velocity, const EvalWell &poly_inj_conc, DeferredLogger &deferred_logger) const
Definition: StandardWell_impl.hpp:2047
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:92
int setPrimaryVars(typename std::vector< Scalar >::const_iterator it) override
Definition: StandardWell_impl.hpp:2657
void updateWaterThroughput(const double dt, WellStateType &well_state) const override
Definition: StandardWell_impl.hpp:2120
void checkOperabilityUnderBHPLimit(const WellStateType &well_state, const Simulator &simulator, DeferredLogger &deferred_logger) override
Definition: StandardWell_impl.hpp:1010
EvalWell pskinwater(const Scalar throughput, const EvalWell &water_velocity, DeferredLogger &deferred_logger) const
Definition: StandardWell_impl.hpp:2016
void handleInjectivityRate(const Simulator &simulator, const int perf, std::vector< EvalWell > &cq_s) const
Definition: StandardWell_impl.hpp:2151
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:1276
void calculateExplicitQuantities(const Simulator &simulator, const GroupStateHelperType &groupStateHelper) override
Definition: StandardWell_impl.hpp:1450
Scalar getRefDensity() const override
Definition: StandardWell_impl.hpp:1911
void checkOperabilityUnderTHPLimit(const Simulator &simulator, const WellStateType &well_state, const GroupStateHelperType &groupStateHelper) override
Definition: StandardWell_impl.hpp:1079
Scalar connectionDensity(const int globalConnIdx, const int openConnIdx) const override
Definition: StandardWell_impl.hpp:1873
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:486
Well well_ecl_
Definition: WellInterfaceGeneric.hpp:474
void onlyKeepBHPandTHPcontrols(const SummaryState &summary_state, WellStateType &well_state, Well::InjectionControls &inj_controls, Well::ProductionControls &prod_controls) const
void resetDampening()
Definition: WellInterfaceGeneric.hpp:412
std::pair< bool, bool > computeWellPotentials(std::vector< Scalar > &well_potentials, const WellStateType &well_state)
Definition: WellInterfaceIndices.hpp:34
Definition: WellInterface.hpp:79
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:735
GetPropType< TypeTag, Properties::Simulator > Simulator
Definition: WellInterface.hpp:84
typename WellInterfaceFluidSystem< FluidSystem >::RateConverterType RateConverterType
Definition: WellInterface.hpp:110
void getTransMult(Value &trans_mult, const Simulator &simulator, const int cell_idx, Callback &extendEval) const
Definition: WellInterface_impl.hpp:2231
Dune::BCRSMatrix< Opm::MatrixBlock< Scalar, 1, 1 > > PressureMatrix
Definition: WellInterface.hpp:100
void getMobility(const Simulator &simulator, const int local_perf_index, std::vector< Value > &mob, Callback &extendEval, DeferredLogger &deferred_logger) const
Definition: WellInterface_impl.hpp:2244
GetPropType< TypeTag, Properties::IntensiveQuantities > IntensiveQuantities
Definition: WellInterface.hpp:89
GetPropType< TypeTag, Properties::Scalar > Scalar
Definition: WellInterface.hpp:85
Dune::BlockVector< VectorBlockType > BVector
Definition: WellInterface.hpp:99
typename Base::ModelParameters ModelParameters
Definition: WellInterface.hpp:116
GetPropType< TypeTag, Properties::FluidSystem > FluidSystem
Definition: WellInterface.hpp:86
GetPropType< TypeTag, Properties::Indices > Indices
Definition: WellInterface.hpp:88
GetPropType< TypeTag, Properties::SparseMatrixAdapter > SparseMatrixAdapter
Definition: WellInterface.hpp:91
Definition: WellProdIndexCalculator.hpp:37
Scalar connectionProdIndStandard(const std::size_t connIdx, const Scalar connMobility) const
Definition: WellState.hpp:68
const SingleWellState< Scalar, IndexTraits > & well(std::size_t well_index) const
Definition: WellState.hpp:315
std::vector< Scalar > & wellRates(std::size_t well_index)
One rate per well and phase.
Definition: WellState.hpp:280
@ 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:72
Scalar dis_gas
Definition: PerforationData.hpp:73
Scalar vap_wat
Definition: PerforationData.hpp:76
Scalar vap_oil
Definition: PerforationData.hpp:75
Scalar dis_gas_in_water
Definition: PerforationData.hpp:74