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>
45#include <fmt/format.h>
50 template<
typename TypeTag>
57 const int pvtRegionIdx,
58 const int num_conservation_quantities,
60 const int index_of_well,
62 :
Base(well, pw_info, time_step, param, rate_converter, pvtRegionIdx, num_conservation_quantities, num_phases, index_of_well, perf_data)
73 template<
typename TypeTag>
76 init(
const std::vector<Scalar>& depth_arg,
78 const std::vector< Scalar >& B_avg,
79 const bool changed_to_open_this_step)
81 Base::init(depth_arg, gravity_arg, B_avg, changed_to_open_this_step);
82 this->StdWellEval::init(this->perf_depth_, depth_arg, Base::has_polymermw);
89 template<
typename TypeTag>
94 const std::vector<Value>& mob,
96 const std::vector<Value>& Tw,
99 std::vector<Value>& cq_s,
103 auto obtain = [
this](
const Eval& value)
105 if constexpr (std::is_same_v<Value, Scalar>) {
106 static_cast<void>(
this);
107 return getValue(value);
109 return this->extendEval(value);
112 auto obtainN = [](
const auto& value)
114 if constexpr (std::is_same_v<Value, Scalar>) {
115 return getValue(value);
120 auto zeroElem = [
this]()
122 if constexpr (std::is_same_v<Value, Scalar>) {
123 static_cast<void>(
this);
126 return Value{this->primary_variables_.numWellEq() + Indices::numEq, 0.0};
130 const auto& fs = intQuants.fluidState();
131 const Value pressure = obtain(this->getPerfCellPressure(fs));
132 const Value rs = obtain(fs.Rs());
133 const Value rv = obtain(fs.Rv());
134 const Value rvw = obtain(fs.Rvw());
135 const Value rsw = obtain(fs.Rsw());
137 std::vector<Value> b_perfcells_dense(this->numConservationQuantities(), zeroElem());
138 for (
unsigned phaseIdx = 0; phaseIdx < FluidSystem::numPhases; ++phaseIdx) {
139 if (!FluidSystem::phaseIsActive(phaseIdx)) {
142 const unsigned compIdx = FluidSystem::canonicalToActiveCompIdx(FluidSystem::solventComponentIndex(phaseIdx));
143 b_perfcells_dense[compIdx] = obtain(fs.invB(phaseIdx));
145 if constexpr (has_solvent) {
146 b_perfcells_dense[Indices::contiSolventEqIdx] = obtain(intQuants.solventInverseFormationVolumeFactor());
149 if constexpr (has_zFraction) {
150 if (this->isInjector()) {
151 const unsigned gasCompIdx = FluidSystem::canonicalToActiveCompIdx(FluidSystem::gasCompIdx);
152 b_perfcells_dense[gasCompIdx] *= (1.0 - this->wsolvent());
153 b_perfcells_dense[gasCompIdx] += this->wsolvent()*intQuants.zPureInvFormationVolumeFactor().value();
157 Value skin_pressure = zeroElem();
159 if (this->isInjector()) {
160 const int pskin_index = Bhp + 1 + this->numLocalPerfs() + perf;
161 skin_pressure = obtainN(this->primary_variables_.eval(pskin_index));
166 std::vector<Value> cmix_s(this->numConservationQuantities(), zeroElem());
167 for (
int componentIdx = 0; componentIdx < this->numConservationQuantities(); ++componentIdx) {
168 cmix_s[componentIdx] = obtainN(this->primary_variables_.surfaceVolumeFraction(componentIdx));
191 template<
typename TypeTag>
192 template<
class Value>
196 const Value& pressure,
202 std::vector<Value>& b_perfcells_dense,
203 const std::vector<Value>& Tw,
206 const Value& skin_pressure,
207 const std::vector<Value>& cmix_s,
208 std::vector<Value>& cq_s,
213 const Value well_pressure = bhp + this->connections_.pressure_diff(perf);
214 Value drawdown = pressure - well_pressure;
215 if (this->isInjector()) {
216 drawdown += skin_pressure;
220 FluidSystem::phaseIsActive(FluidSystem::gasPhaseIdx)
221 ? FluidSystem::canonicalToActiveCompIdx(FluidSystem::gasCompIdx)
223 FluidSystem::phaseIsActive(FluidSystem::oilPhaseIdx)
224 ? FluidSystem::canonicalToActiveCompIdx(FluidSystem::oilCompIdx)
226 FluidSystem::phaseIsActive(FluidSystem::waterPhaseIdx)
227 ? FluidSystem::canonicalToActiveCompIdx(FluidSystem::waterCompIdx)
235 if (!allow_cf && this->isInjector()) {
240 for (
int componentIdx = 0; componentIdx < this->numConservationQuantities(); ++componentIdx) {
241 const Value cq_p = - Tw[componentIdx] * (mob[componentIdx] * drawdown);
242 cq_s[componentIdx] = b_perfcells_dense[componentIdx] * cq_p;
245 if (FluidSystem::phaseIsActive(FluidSystem::oilPhaseIdx) &&
246 FluidSystem::phaseIsActive(FluidSystem::gasPhaseIdx))
248 ratioCalc.gasOilPerfRateProd(cq_s, perf_rates, rv, rs, rvw,
249 FluidSystem::phaseIsActive(FluidSystem::waterPhaseIdx),
251 }
else if (FluidSystem::phaseIsActive(FluidSystem::waterPhaseIdx) &&
252 FluidSystem::phaseIsActive(FluidSystem::gasPhaseIdx))
254 ratioCalc.gasWaterPerfRateProd(cq_s, perf_rates, rvw, rsw, this->isProducer());
258 if (!allow_cf && this->isProducer()) {
263 Value total_mob_dense = mob[0];
264 for (
int componentIdx = 1; componentIdx < this->numConservationQuantities(); ++componentIdx) {
265 total_mob_dense += mob[componentIdx];
269 Value volumeRatio = bhp * 0.0;
271 if (FluidSystem::enableVaporizedWater() && FluidSystem::enableDissolvedGasInWater()) {
272 ratioCalc.disOilVapWatVolumeRatio(volumeRatio, rvw, rsw, pressure,
273 cmix_s, b_perfcells_dense, deferred_logger);
277 assert(FluidSystem::phaseIsActive(FluidSystem::gasPhaseIdx));
278 assert(FluidSystem::phaseIsActive(FluidSystem::waterPhaseIdx));
279 assert(!FluidSystem::phaseIsActive(FluidSystem::oilPhaseIdx));
282 if (FluidSystem::phaseIsActive(FluidSystem::waterPhaseIdx)) {
283 const unsigned waterCompIdx = FluidSystem::canonicalToActiveCompIdx(FluidSystem::waterCompIdx);
284 volumeRatio += cmix_s[waterCompIdx] / b_perfcells_dense[waterCompIdx];
287 if constexpr (Indices::enableSolvent) {
288 volumeRatio += cmix_s[Indices::contiSolventEqIdx] / b_perfcells_dense[Indices::contiSolventEqIdx];
291 if (FluidSystem::phaseIsActive(FluidSystem::oilPhaseIdx) &&
292 FluidSystem::phaseIsActive(FluidSystem::gasPhaseIdx))
294 ratioCalc.gasOilVolumeRatio(volumeRatio, rv, rs, pressure,
295 cmix_s, b_perfcells_dense,
298 if (FluidSystem::phaseIsActive(FluidSystem::oilPhaseIdx)) {
299 const unsigned oilCompIdx = FluidSystem::canonicalToActiveCompIdx(FluidSystem::oilCompIdx);
300 volumeRatio += cmix_s[oilCompIdx] / b_perfcells_dense[oilCompIdx];
302 if (FluidSystem::phaseIsActive(FluidSystem::gasPhaseIdx)) {
303 const unsigned gasCompIdx = FluidSystem::canonicalToActiveCompIdx(FluidSystem::gasCompIdx);
304 volumeRatio += cmix_s[gasCompIdx] / b_perfcells_dense[gasCompIdx];
310 for (
int componentIdx = 0; componentIdx < this->numConservationQuantities(); ++componentIdx) {
311 const Value cqt_i = - Tw[componentIdx] * (total_mob_dense * drawdown);
312 Value cqt_is = cqt_i / volumeRatio;
313 cq_s[componentIdx] = cmix_s[componentIdx] * cqt_is;
317 if (this->isProducer()) {
318 if (FluidSystem::phaseIsActive(FluidSystem::oilPhaseIdx) &&
319 FluidSystem::phaseIsActive(FluidSystem::gasPhaseIdx))
321 ratioCalc.gasOilPerfRateInj(cq_s, perf_rates,
322 rv, rs, pressure, rvw,
323 FluidSystem::phaseIsActive(FluidSystem::waterPhaseIdx),
326 if (FluidSystem::phaseIsActive(FluidSystem::gasPhaseIdx) &&
327 FluidSystem::phaseIsActive(FluidSystem::waterPhaseIdx))
330 ratioCalc.gasWaterPerfRateInj(cq_s, perf_rates, rvw, rsw,
331 pressure, deferred_logger);
338 template<
typename TypeTag>
344 const Well::InjectionControls& inj_controls,
345 const Well::ProductionControls& prod_controls,
347 const bool solving_with_zero_rate)
351 if (!this->isOperableAndSolvable() && !this->wellIsStopped())
return;
354 this->linSys_.clear();
356 assembleWellEqWithoutIterationImpl(simulator, groupStateHelper, dt, inj_controls,
357 prod_controls, well_state, solving_with_zero_rate);
363 template<
typename TypeTag>
369 const Well::InjectionControls& inj_controls,
370 const Well::ProductionControls& prod_controls,
372 const bool solving_with_zero_rate)
377 const Scalar regularization_factor = this->regularize_? this->param_.regularization_factor_wells_ : 1.0;
378 const Scalar volume = 0.1 * unit::cubic(unit::feet) * regularization_factor;
380 auto& ws = well_state.
well(this->index_of_well_);
381 ws.phase_mixing_rates.fill(0.0);
382 if constexpr (has_energy) {
383 ws.energy_rate = 0.0;
387 const int np = this->number_of_phases_;
389 std::vector<RateVector> connectionRates = this->connectionRates_;
391 auto& perf_data = ws.perf_data;
392 auto& perf_rates = perf_data.phase_rates;
393 for (
int perf = 0; perf < this->number_of_local_perforations_; ++perf) {
395 std::vector<EvalWell> cq_s(this->num_conservation_quantities_, 0.0);
398 calculateSinglePerf(simulator, perf, well_state, connectionRates,
399 cq_s, water_flux_s, cq_s_zfrac_effective, deferred_logger);
402 if constexpr (has_polymer && Base::has_polymermw) {
403 if (this->isInjector()) {
404 handleInjectivityEquations(simulator, well_state, perf,
405 water_flux_s, deferred_logger);
408 for (
int componentIdx = 0; componentIdx < this->num_conservation_quantities_; ++componentIdx) {
410 const EvalWell cq_s_effective = cq_s[componentIdx] * this->well_efficiency_factor_;
412 connectionRates[perf][componentIdx] = Base::restrictEval(cq_s_effective);
415 assemblePerforationEq(cq_s_effective,
418 this->primary_variables_.numWellEq(),
422 if (has_solvent && componentIdx == Indices::contiSolventEqIdx) {
423 auto& perf_rate_solvent = perf_data.solvent_rates;
424 perf_rate_solvent[perf] = cq_s[componentIdx].value();
426 perf_rates[perf*np + FluidSystem::activeCompToActivePhaseIdx(componentIdx)] = cq_s[componentIdx].value();
430 if constexpr (has_zFraction) {
432 assembleZFracEq(cq_s_zfrac_effective,
434 this->primary_variables_.numWellEq(),
439 this->connectionRates_ = connectionRates;
444 const auto& comm = this->parallel_well_info_.communication();
445 comm.sum(ws.phase_mixing_rates.data(), ws.phase_mixing_rates.size());
449 this->linSys_.sumDistributed(this->parallel_well_info_.communication());
452 for (
int componentIdx = 0; componentIdx < numWellConservationEq; ++componentIdx) {
456 if (FluidSystem::numActivePhases() > 1) {
458 resWell_loc += (this->primary_variables_.surfaceVolumeFraction(componentIdx) -
459 this->F0_[componentIdx]) * volume / dt;
461 resWell_loc -= this->primary_variables_.getQs(componentIdx) * this->well_efficiency_factor_;
463 assembleSourceEq(resWell_loc,
465 this->primary_variables_.numWellEq(),
469 const bool stopped_or_zero_target = this->stoppedOrZeroRateTarget(groupStateHelper);
475 auto& group_state = solving_with_zero_rate
479 auto group_guard = groupStateHelper_copy.
pushGroupState(group_state);
481 assembleControlEq(groupStateHelper_copy,
482 inj_controls, prod_controls,
483 this->primary_variables_,
484 this->getRefDensity(),
486 stopped_or_zero_target);
491 this->linSys_.invert();
493 OPM_DEFLOG_PROBLEM(NumericalProblem,
"Error when inverting local well equations for well " + name(), deferred_logger);
500 template<
typename TypeTag>
506 std::vector<RateVector>& connectionRates,
507 std::vector<EvalWell>& cq_s,
512 const bool allow_cf = this->getAllowCrossFlow() || openCrossFlowAvoidSingularity(simulator);
513 const EvalWell& bhp = this->primary_variables_.eval(Bhp);
514 const int cell_idx = this->well_cells_[perf];
515 const auto& intQuants = simulator.model().intensiveQuantities(cell_idx, 0);
516 std::vector<EvalWell> mob(this->num_conservation_quantities_, {0.});
517 getMobility(simulator, perf, mob, deferred_logger);
521 getTransMult(trans_mult, simulator, cell_idx);
522 const auto& wellstate_nupcol = simulator.problem().wellModel().nupcolWellState().well(this->index_of_well_);
523 std::vector<EvalWell> Tw(this->num_conservation_quantities_, this->well_index_[perf] * trans_mult);
524 this->getTw(Tw, perf, intQuants, trans_mult, wellstate_nupcol);
525 computePerfRate(intQuants, mob, bhp, Tw, perf, allow_cf,
526 cq_s, perf_rates, deferred_logger);
528 auto& ws = well_state.
well(this->index_of_well_);
529 auto& perf_data = ws.perf_data;
530 if constexpr (has_polymer && Base::has_polymermw) {
531 if (this->isInjector()) {
534 const unsigned water_comp_idx = FluidSystem::canonicalToActiveCompIdx(FluidSystem::waterCompIdx);
535 water_flux_s = cq_s[water_comp_idx];
538 handleInjectivityRate(simulator, perf, cq_s);
543 if (this->isProducer()) {
544 ws.phase_mixing_rates[ws.dissolved_gas] += perf_rates.
dis_gas;
545 ws.phase_mixing_rates[ws.dissolved_gas_in_water] += perf_rates.
dis_gas_in_water;
546 ws.phase_mixing_rates[ws.vaporized_oil] += perf_rates.
vap_oil;
547 ws.phase_mixing_rates[ws.vaporized_water] += perf_rates.
vap_wat;
548 perf_data.phase_mixing_rates[perf][ws.dissolved_gas] = perf_rates.
dis_gas;
549 perf_data.phase_mixing_rates[perf][ws.dissolved_gas_in_water] = perf_rates.
dis_gas_in_water;
550 perf_data.phase_mixing_rates[perf][ws.vaporized_oil] = perf_rates.
vap_oil;
551 perf_data.phase_mixing_rates[perf][ws.vaporized_water] = perf_rates.
vap_wat;
554 if constexpr (has_energy) {
555 connectionRates[perf][Indices::contiEnergyEqIdx] =
556 connectionRateEnergy(cq_s, intQuants, deferred_logger);
557 ws.energy_rate += getValue(connectionRates[perf][Indices::contiEnergyEqIdx]);
560 if constexpr (has_polymer) {
561 std::variant<Scalar,EvalWell> polymerConcentration;
562 if (this->isInjector()) {
563 polymerConcentration = this->wpolymer();
565 polymerConcentration = this->extendEval(intQuants.polymerConcentration() *
566 intQuants.polymerViscosityCorrection());
569 [[maybe_unused]]
EvalWell cq_s_poly;
570 std::tie(connectionRates[perf][Indices::contiPolymerEqIdx],
572 this->connections_.connectionRatePolymer(perf_data.polymer_rates[perf],
573 cq_s, polymerConcentration);
575 if constexpr (Base::has_polymermw) {
576 updateConnectionRatePolyMW(cq_s_poly, intQuants, well_state,
577 perf, connectionRates, deferred_logger);
581 if constexpr (has_foam) {
582 std::variant<Scalar,EvalWell> foamConcentration;
583 if (this->isInjector()) {
584 foamConcentration = this->wfoam();
586 foamConcentration = this->extendEval(intQuants.foamConcentration());
588 connectionRates[perf][Indices::contiFoamEqIdx] =
589 this->connections_.connectionRateFoam(cq_s, foamConcentration,
590 FoamModule::transportPhase(),
594 if constexpr (has_zFraction) {
595 std::variant<Scalar,std::array<EvalWell,2>> solventConcentration;
596 if (this->isInjector()) {
597 solventConcentration = this->wsolvent();
599 solventConcentration = std::array{this->extendEval(intQuants.xVolume()),
600 this->extendEval(intQuants.yVolume())};
602 std::tie(connectionRates[perf][Indices::contiZfracEqIdx],
603 cq_s_zfrac_effective) =
604 this->connections_.connectionRatezFraction(perf_data.solvent_rates[perf],
606 solventConcentration);
609 if constexpr (has_brine) {
610 std::variant<Scalar,EvalWell> saltConcentration;
611 if (this->isInjector()) {
612 saltConcentration = this->wsalt();
614 saltConcentration = this->extendEval(intQuants.fluidState().saltConcentration());
617 connectionRates[perf][Indices::contiBrineEqIdx] =
618 this->connections_.connectionRateBrine(perf_data.brine_rates[perf],
623 if constexpr (has_bioeffects) {
624 std::variant<Scalar,EvalWell> microbialConcentration;
625 if constexpr (has_micp) {
626 std::variant<Scalar,EvalWell> oxygenConcentration;
627 std::variant<Scalar,EvalWell> ureaConcentration;
628 if (this->isInjector()) {
629 microbialConcentration = this->wmicrobes();
630 oxygenConcentration = this->woxygen();
631 ureaConcentration = this->wurea();
633 microbialConcentration = this->extendEval(intQuants.microbialConcentration());
634 oxygenConcentration = this->extendEval(intQuants.oxygenConcentration());
635 ureaConcentration = this->extendEval(intQuants.ureaConcentration());
637 std::tie(connectionRates[perf][Indices::contiMicrobialEqIdx],
638 connectionRates[perf][Indices::contiOxygenEqIdx],
639 connectionRates[perf][Indices::contiUreaEqIdx]) =
640 this->connections_.connectionRatesMICP(perf_data.microbial_rates[perf],
641 perf_data.oxygen_rates[perf],
642 perf_data.urea_rates[perf],
644 microbialConcentration,
649 if (this->isProducer()) {
650 microbialConcentration = this->extendEval(intQuants.microbialConcentration());
651 connectionRates[perf][Indices::contiMicrobialEqIdx] =
652 this->connections_.connectionRateBioeffects(perf_data.microbial_rates[perf],
654 microbialConcentration);
660 perf_data.pressure[perf] = ws.bhp + this->connections_.pressure_diff(perf);
663 if (FluidSystem::phaseUsage().hasCO2orH2Store()) {
664 const unsigned gas_comp_idx = FluidSystem::canonicalToActiveCompIdx(FluidSystem::gasCompIdx);
665 const Scalar rho = FluidSystem::referenceDensity( FluidSystem::gasPhaseIdx, Base::pvtRegionIdx() );
666 perf_data.gas_mass_rates[perf] = cq_s[gas_comp_idx].value() * rho;
670 if (FluidSystem::phaseIsActive(FluidSystem::waterPhaseIdx)) {
671 const unsigned wat_comp_idx = FluidSystem::canonicalToActiveCompIdx(FluidSystem::waterCompIdx);
672 const Scalar rho = FluidSystem::referenceDensity( FluidSystem::waterPhaseIdx, Base::pvtRegionIdx() );
673 perf_data.wat_mass_rates[perf] = cq_s[wat_comp_idx].value() * rho;
677 template<
typename TypeTag>
678 template<
class Value>
683 const int cell_idx)
const
685 auto obtain = [
this](
const Eval& value)
687 if constexpr (std::is_same_v<Value, Scalar>) {
688 static_cast<void>(
this);
689 return getValue(value);
691 return this->extendEval(value);
697 template<
typename TypeTag>
698 template<
class Value>
703 std::vector<Value>& mob,
706 auto obtain = [
this](
const Eval& value)
708 if constexpr (std::is_same_v<Value, Scalar>) {
709 static_cast<void>(
this);
710 return getValue(value);
712 return this->extendEval(value);
716 obtain, deferred_logger);
719 if constexpr (has_polymer) {
720 if (!FluidSystem::phaseIsActive(FluidSystem::waterPhaseIdx)) {
721 OPM_DEFLOG_THROW(std::runtime_error,
"Water is required when polymer is active", deferred_logger);
726 if constexpr (!Base::has_polymermw) {
727 if constexpr (std::is_same_v<Value, Scalar>) {
728 std::vector<EvalWell> mob_eval(this->num_conservation_quantities_, 0.);
729 for (std::size_t i = 0; i < mob.size(); ++i) {
730 mob_eval[i].setValue(mob[i]);
732 updateWaterMobilityWithPolymer(simulator, perf, mob_eval, deferred_logger);
733 for (std::size_t i = 0; i < mob.size(); ++i) {
734 mob[i] = getValue(mob_eval[i]);
737 updateWaterMobilityWithPolymer(simulator, perf, mob, deferred_logger);
744 const Scalar bhp = this->primary_variables_.value(Bhp);
745 const Scalar perf_press = bhp + this->connections_.pressure_diff(perf);
746 const Scalar multiplier = this->getInjMult(perf, bhp, perf_press, deferred_logger);
747 for (std::size_t i = 0; i < mob.size(); ++i) {
748 mob[i] *= multiplier;
754 template<
typename TypeTag>
762 if (!this->isOperableAndSolvable() && !this->wellIsStopped())
return;
766 const bool stop_or_zero_rate_target = this->stoppedOrZeroRateTarget(groupStateHelper);
767 updatePrimaryVariablesNewton(dwells, stop_or_zero_rate_target, deferred_logger);
769 const auto& summary_state = simulator.vanguard().summaryState();
770 updateWellStateFromPrimaryVariables(well_state, summary_state, deferred_logger);
771 Base::calculateReservoirRates(simulator.vanguard().eclState().runspec().co2Storage(), well_state.
well(this->index_of_well_));
778 template<
typename TypeTag>
782 const bool stop_or_zero_rate_target,
785 const Scalar dFLimit = this->param_.dwell_fraction_max_;
786 const Scalar dBHPLimit = this->param_.dbhp_max_rel_;
787 this->primary_variables_.updateNewton(dwells, stop_or_zero_rate_target, dFLimit, dBHPLimit, deferred_logger);
790 if constexpr (Base::has_polymermw) {
791 this->primary_variables_.updateNewtonPolyMW(dwells);
794 this->primary_variables_.checkFinite(deferred_logger,
"Newton update");
801 template<
typename TypeTag>
805 const SummaryState& summary_state,
808 this->primary_variables_.copyToWellState(well_state, deferred_logger);
811 updateThp(getRefDensity(),
812 [
this,&well_state]() {
return this->baseif_.getALQ(well_state); },
813 well_state, summary_state, deferred_logger);
816 if constexpr (Base::has_polymermw) {
817 this->primary_variables_.copyToWellStatePolyMW(well_state);
825 template<
typename TypeTag>
833 std::fill(this->ipr_a_.begin(), this->ipr_a_.end(), 0.);
834 std::fill(this->ipr_b_.begin(), this->ipr_b_.end(), 0.);
836 for (
int perf = 0; perf < this->number_of_local_perforations_; ++perf) {
837 std::vector<Scalar> mob(this->num_conservation_quantities_, 0.0);
838 getMobility(simulator, perf, mob, deferred_logger);
840 const int cell_idx = this->well_cells_[perf];
841 const auto& int_quantities = simulator.model().intensiveQuantities(cell_idx, 0);
842 const auto& fs = int_quantities.fluidState();
844 Scalar p_r = this->getPerfCellPressure(fs).value();
847 std::vector<Scalar> b_perf(this->num_conservation_quantities_);
848 for (std::size_t phase = 0; phase < FluidSystem::numPhases; ++phase) {
849 if (!FluidSystem::phaseIsActive(phase)) {
852 const unsigned comp_idx = FluidSystem::canonicalToActiveCompIdx(FluidSystem::solventComponentIndex(phase));
853 b_perf[comp_idx] = fs.invB(phase).value();
855 if constexpr (has_solvent) {
856 b_perf[Indices::contiSolventEqIdx] = int_quantities.solventInverseFormationVolumeFactor().value();
860 const Scalar h_perf = this->connections_.pressure_diff(perf);
861 const Scalar pressure_diff = p_r - h_perf;
866 if ( (this->isProducer() && pressure_diff < 0.) || (this->isInjector() && pressure_diff > 0.) ) {
867 deferred_logger.
debug(
"CROSSFLOW_IPR",
868 "cross flow found when updateIPR for well " + name()
869 +
" . The connection is ignored in IPR calculations");
876 getTransMult(trans_mult, simulator, cell_idx);
877 const auto& wellstate_nupcol = simulator.problem().wellModel().nupcolWellState().well(this->index_of_well_);
878 std::vector<Scalar> tw_perf(this->num_conservation_quantities_, this->well_index_[perf] * trans_mult);
879 this->getTw(tw_perf, perf, int_quantities, trans_mult, wellstate_nupcol);
880 std::vector<Scalar> ipr_a_perf(this->ipr_a_.size());
881 std::vector<Scalar> ipr_b_perf(this->ipr_b_.size());
882 for (
int comp_idx = 0; comp_idx < this->num_conservation_quantities_; ++comp_idx) {
883 const Scalar tw_mob = tw_perf[comp_idx] * mob[comp_idx] * b_perf[comp_idx];
884 ipr_a_perf[comp_idx] += tw_mob * pressure_diff;
885 ipr_b_perf[comp_idx] += tw_mob;
889 if (FluidSystem::phaseIsActive(FluidSystem::oilPhaseIdx) && FluidSystem::phaseIsActive(FluidSystem::gasPhaseIdx)) {
890 const unsigned oil_comp_idx = FluidSystem::canonicalToActiveCompIdx(FluidSystem::oilCompIdx);
891 const unsigned gas_comp_idx = FluidSystem::canonicalToActiveCompIdx(FluidSystem::gasCompIdx);
892 const Scalar rs = (fs.Rs()).value();
893 const Scalar rv = (fs.Rv()).value();
895 const Scalar dis_gas_a = rs * ipr_a_perf[oil_comp_idx];
896 const Scalar vap_oil_a = rv * ipr_a_perf[gas_comp_idx];
898 ipr_a_perf[gas_comp_idx] += dis_gas_a;
899 ipr_a_perf[oil_comp_idx] += vap_oil_a;
901 const Scalar dis_gas_b = rs * ipr_b_perf[oil_comp_idx];
902 const Scalar vap_oil_b = rv * ipr_b_perf[gas_comp_idx];
904 ipr_b_perf[gas_comp_idx] += dis_gas_b;
905 ipr_b_perf[oil_comp_idx] += vap_oil_b;
908 for (std::size_t comp_idx = 0; comp_idx < ipr_a_perf.size(); ++comp_idx) {
909 this->ipr_a_[comp_idx] += ipr_a_perf[comp_idx];
910 this->ipr_b_[comp_idx] += ipr_b_perf[comp_idx];
913 this->parallel_well_info_.communication().sum(this->ipr_a_.data(), this->ipr_a_.size());
914 this->parallel_well_info_.communication().sum(this->ipr_b_.data(), this->ipr_b_.size());
917 template<
typename TypeTag>
932 auto rates = well_state.
well(this->index_of_well_).surface_rates;
934 for (std::size_t p = 0; p < rates.size(); ++p) {
935 zero_rates &= rates[p] == 0.0;
937 auto& ws = well_state.
well(this->index_of_well_);
939 const auto msg = fmt::format(
"updateIPRImplicit: Well {} has zero rate, IPRs might be problematic", this->name());
940 deferred_logger.debug(msg);
953 std::fill(ws.implicit_ipr_a.begin(), ws.implicit_ipr_a.end(), 0.);
954 std::fill(ws.implicit_ipr_b.begin(), ws.implicit_ipr_b.end(), 0.);
956 auto inj_controls = Well::InjectionControls(0);
957 auto prod_controls = Well::ProductionControls(0);
958 prod_controls.addControl(Well::ProducerCMode::BHP);
959 prod_controls.bhp_limit = well_state.
well(this->index_of_well_).bhp;
962 const auto cmode = ws.production_cmode;
963 ws.production_cmode = Well::ProducerCMode::BHP;
964 const double dt = simulator.timeStepSize();
965 assembleWellEqWithoutIteration(simulator, groupStateHelper, dt, inj_controls, prod_controls, well_state,
968 const size_t nEq = this->primary_variables_.numWellEq();
972 for (
size_t i=0; i < nEq; ++i){
978 x_well[0].resize(nEq);
979 this->linSys_.solve(rhs, x_well);
981 for (
int comp_idx = 0; comp_idx < this->num_conservation_quantities_; ++comp_idx){
982 EvalWell comp_rate = this->primary_variables_.getQs(comp_idx);
983 const int idx = FluidSystem::activeCompToActivePhaseIdx(comp_idx);
984 for (
size_t pvIdx = 0; pvIdx < nEq; ++pvIdx) {
986 ws.implicit_ipr_b[idx] -= x_well[0][pvIdx]*comp_rate.derivative(pvIdx+Indices::numEq);
988 ws.implicit_ipr_a[idx] = ws.implicit_ipr_b[idx]*ws.bhp - comp_rate.value();
991 ws.production_cmode = cmode;
994 template<
typename TypeTag>
1001 const auto& summaryState = simulator.vanguard().summaryState();
1005 const bool bhp_limit_not_defaulted = bhp_limit > 1.5 * unit::barsa;
1006 if ( bhp_limit_not_defaulted || !this->wellHasTHPConstraints(summaryState) ) {
1009 Scalar total_ipr_mass_rate = 0.0;
1010 for (
unsigned phaseIdx = 0; phaseIdx < FluidSystem::numPhases; ++phaseIdx)
1012 if (!FluidSystem::phaseIsActive(phaseIdx)) {
1016 const unsigned compIdx = FluidSystem::canonicalToActiveCompIdx(FluidSystem::solventComponentIndex(phaseIdx));
1017 const Scalar ipr_rate = this->ipr_a_[compIdx] - this->ipr_b_[compIdx] * bhp_limit;
1019 const Scalar rho = FluidSystem::referenceDensity( phaseIdx, Base::pvtRegionIdx() );
1020 total_ipr_mass_rate += ipr_rate * rho;
1022 if ( (this->isProducer() && total_ipr_mass_rate < 0.) || (this->isInjector() && total_ipr_mass_rate > 0.) ) {
1023 this->operability_status_.operable_under_only_bhp_limit =
false;
1027 if (this->operability_status_.operable_under_only_bhp_limit && this->wellHasTHPConstraints(summaryState)) {
1031 std::vector<Scalar> well_rates_bhp_limit;
1032 computeWellRatesWithBhp(simulator, bhp_limit, well_rates_bhp_limit, deferred_logger);
1034 this->adaptRatesForVFP(well_rates_bhp_limit);
1035 const Scalar thp_limit = this->getTHPConstraint(summaryState);
1038 this->getRefDensity(),
1039 this->getALQ(well_state),
1042 if ( (this->isProducer() && thp < thp_limit) || (this->isInjector() && thp > thp_limit) ) {
1043 this->operability_status_.obey_thp_limit_under_bhp_limit =
false;
1054 this->operability_status_.operable_under_only_bhp_limit =
true;
1055 this->operability_status_.obey_thp_limit_under_bhp_limit =
false;
1063 template<
typename TypeTag>
1071 const auto& summaryState = simulator.vanguard().summaryState();
1072 const auto obtain_bhp = this->isProducer() ? computeBhpAtThpLimitProd(well_state, simulator, groupStateHelper, summaryState)
1073 : computeBhpAtThpLimitInj(simulator, groupStateHelper, summaryState);
1076 this->operability_status_.can_obtain_bhp_with_thp_limit =
true;
1079 this->operability_status_.obey_bhp_limit_with_thp_limit = this->isProducer() ?
1080 *obtain_bhp >= bhp_limit : *obtain_bhp <= bhp_limit ;
1082 const Scalar thp_limit = this->getTHPConstraint(summaryState);
1083 if (this->isProducer() && *obtain_bhp < thp_limit) {
1084 const std::string msg =
" obtained bhp " +
std::to_string(unit::convert::to(*obtain_bhp, unit::barsa))
1085 +
" bars is SMALLER than thp limit "
1087 +
" bars as a producer for well " + name();
1088 deferred_logger.debug(msg);
1090 else if (this->isInjector() && *obtain_bhp > thp_limit) {
1091 const std::string msg =
" obtained bhp " +
std::to_string(unit::convert::to(*obtain_bhp, unit::barsa))
1092 +
" bars is LARGER than thp limit "
1094 +
" bars as a injector for well " + name();
1095 deferred_logger.debug(msg);
1098 this->operability_status_.can_obtain_bhp_with_thp_limit =
false;
1099 this->operability_status_.obey_bhp_limit_with_thp_limit =
false;
1100 if (!this->wellIsStopped()) {
1101 const Scalar thp_limit = this->getTHPConstraint(summaryState);
1102 deferred_logger.debug(
" could not find bhp value at thp limit "
1104 +
" bar for well " + name() +
", the well might need to be closed ");
1113 template<
typename TypeTag>
1118 bool all_drawdown_wrong_direction =
true;
1120 for (
int perf = 0; perf < this->number_of_local_perforations_; ++perf) {
1121 const int cell_idx = this->well_cells_[perf];
1122 const auto& intQuants = simulator.model().intensiveQuantities(cell_idx, 0);
1123 const auto& fs = intQuants.fluidState();
1125 const Scalar pressure = this->getPerfCellPressure(fs).value();
1126 const Scalar bhp = this->primary_variables_.eval(Bhp).value();
1129 const Scalar well_pressure = bhp + this->connections_.pressure_diff(perf);
1130 const Scalar drawdown = pressure - well_pressure;
1135 if ( (drawdown < 0. && this->isInjector()) ||
1136 (drawdown > 0. && this->isProducer()) ) {
1137 all_drawdown_wrong_direction =
false;
1142 const auto& comm = this->parallel_well_info_.communication();
1143 if (comm.size() > 1)
1145 all_drawdown_wrong_direction =
1146 (comm.min(all_drawdown_wrong_direction ? 1 : 0) == 1);
1149 return all_drawdown_wrong_direction;
1155 template<
typename TypeTag>
1160 return !this->getAllowCrossFlow() && allDrawDownWrongDirection(simulator);
1166 template<
typename TypeTag>
1172 auto prop_func =
typename StdWellEval::StdWellConnections::PressurePropertyFunctions {
1174 [&model = simulator.model()](
int cell_idx,
int phase_idx)
1176 return model.intensiveQuantities(cell_idx, 0)
1177 .fluidState().temperature(phase_idx).value();
1181 [&model = simulator.model()](
int cell_idx)
1183 return model.intensiveQuantities(cell_idx, 0)
1184 .fluidState().saltConcentration().value();
1188 [&model = simulator.model()](
int cell_idx)
1190 return model.intensiveQuantities(cell_idx, 0)
1191 .fluidState().pvtRegionIndex();
1195 if constexpr (Indices::enableSolvent) {
1196 prop_func.solventInverseFormationVolumeFactor =
1197 [&model = simulator.model()](
int cell_idx)
1199 return model.intensiveQuantities(cell_idx, 0)
1200 .solventInverseFormationVolumeFactor().value();
1203 prop_func.solventRefDensity = [&model = simulator.model()](
int cell_idx)
1205 return model.intensiveQuantities(cell_idx, 0)
1206 .solventRefDensity();
1210 return this->connections_.computePropertiesForPressures(well_state, prop_func);
1217 template<
typename TypeTag>
1221 const std::vector<Scalar>& B_avg,
1222 const bool relax_tolerance)
const
1226 assert((
int(B_avg.size()) == this->num_conservation_quantities_) || has_polymer || has_energy || has_foam || has_brine || has_zFraction || has_bioeffects);
1229 Scalar tol_wells = this->param_.tolerance_wells_;
1231 constexpr Scalar stopped_factor = 1.e-4;
1233 constexpr Scalar dynamic_thp_factor = 1.e-1;
1234 if (this->stoppedOrZeroRateTarget(groupStateHelper)) {
1235 tol_wells = tol_wells*stopped_factor;
1236 }
else if (this->getDynamicThpLimit()) {
1237 tol_wells = tol_wells*dynamic_thp_factor;
1240 std::vector<Scalar> res;
1243 this->param_.max_residual_allowed_,
1245 this->param_.relaxed_tolerance_flow_well_,
1247 this->wellIsStopped(),
1251 checkConvergenceExtraEqs(res, report);
1260 template<
typename TypeTag>
1268 auto fluidState = [&simulator,
this](
const int perf)
1270 const auto cell_idx = this->well_cells_[perf];
1271 return simulator.model()
1272 .intensiveQuantities(cell_idx, 0).fluidState();
1275 const int np = this->number_of_phases_;
1276 auto setToZero = [np](
Scalar* x) ->
void
1278 std::fill_n(x, np, 0.0);
1281 auto addVector = [np](
const Scalar* src,
Scalar* dest) ->
void
1283 std::transform(src, src + np, dest, dest, std::plus<>{});
1286 auto& ws = well_state.
well(this->index_of_well_);
1287 auto& perf_data = ws.perf_data;
1288 auto* wellPI = ws.productivity_index.data();
1289 auto* connPI = perf_data.prod_index.data();
1293 const auto preferred_phase = this->well_ecl_.getPreferredPhase();
1294 auto subsetPerfID = 0;
1296 for (
const auto& perf : *this->perf_data_) {
1297 auto allPerfID = perf.ecl_index;
1299 auto connPICalc = [&wellPICalc, allPerfID](
const Scalar mobility) ->
Scalar
1304 std::vector<Scalar> mob(this->num_conservation_quantities_, 0.0);
1305 getMobility(simulator,
static_cast<int>(subsetPerfID), mob, deferred_logger);
1307 const auto& fs = fluidState(subsetPerfID);
1310 if (this->isInjector()) {
1311 this->computeConnLevelInjInd(fs, preferred_phase, connPICalc,
1312 mob, connPI, deferred_logger);
1315 this->computeConnLevelProdInd(fs, connPICalc, mob, connPI);
1318 addVector(connPI, wellPI);
1325 const auto& comm = this->parallel_well_info_.communication();
1326 if (comm.size() > 1) {
1327 comm.sum(wellPI, np);
1330 assert ((
static_cast<int>(subsetPerfID) == this->number_of_local_perforations_) &&
1331 "Internal logic error in processing connections for PI/II");
1336 template<
typename TypeTag>
1343 const auto& well_state = groupStateHelper.
wellState();
1347 const auto prop_func =
typename StdWellEval::StdWellConnections::DensityPropertyFunctions {
1352 [&model = simulator.model()](
const int cell,
1353 const std::vector<int>& phases,
1354 std::vector<Scalar>& mob)
1356 const auto& iq = model.intensiveQuantities(cell, 0);
1358 std::transform(phases.begin(), phases.end(), mob.begin(),
1359 [&iq](
const int phase) { return iq.mobility(phase).value(); });
1364 [&model = simulator.model()](
const int cell,
1365 const std::vector<int>& phases,
1366 std::vector<Scalar>& rho)
1368 const auto& fs = model.intensiveQuantities(cell, 0).fluidState();
1370 std::transform(phases.begin(), phases.end(), rho.begin(),
1371 [&fs](
const int phase) { return fs.density(phase).value(); });
1375 const auto stopped_or_zero_rate_target = this->
1376 stoppedOrZeroRateTarget(groupStateHelper);
1379 .computeProperties(stopped_or_zero_rate_target, well_state,
1380 prop_func, props, deferred_logger);
1382 cachedRefDensity = this->connections_.rho(0);
1383 if (this->parallel_well_info_.communication().size() > 1) {
1384 cachedRefDensity = this->parallel_well_info_.broadcastFirstPerforationValue(cachedRefDensity);
1392 template<
typename TypeTag>
1398 const auto& well_state = groupStateHelper.
wellState();
1399 const auto props = computePropertiesForWellConnectionPressures
1400 (simulator, well_state);
1402 computeWellConnectionDensitesPressures(simulator, groupStateHelper, props);
1409 template<
typename TypeTag>
1416 if (!this->isOperableAndSolvable() && !this->wellIsStopped())
return;
1421 dx_well[0].resize(this->primary_variables_.numWellEq());
1422 this->linSys_.solve( dx_well);
1424 updateWellState(simulator, dx_well, groupStateHelper, well_state);
1431 template<
typename TypeTag>
1437 updatePrimaryVariables(groupStateHelper);
1438 computeWellConnectionPressures(simulator, groupStateHelper);
1439 this->computeAccumWell();
1444 template<
typename TypeTag>
1449 if (!this->isOperableAndSolvable() && !this->wellIsStopped())
return;
1451 if (this->param_.matrix_add_well_contributions_)
1457 this->linSys_.apply(x, Ax);
1463 template<
typename TypeTag>
1468 if (!this->isOperableAndSolvable() && !this->wellIsStopped())
return;
1470 this->linSys_.apply(r);
1476 template<
typename TypeTag>
1484 if (!this->isOperableAndSolvable() && !this->wellIsStopped())
return;
1487 xw[0].resize(this->primary_variables_.numWellEq());
1489 this->linSys_.recoverSolutionWell(x, xw);
1490 updateWellState(simulator, xw, groupStateHelper, well_state);
1496 template<
typename TypeTag>
1501 std::vector<Scalar>& well_flux,
1505 const int np = this->number_of_phases_;
1506 well_flux.resize(np, 0.0);
1508 const bool allow_cf = this->getAllowCrossFlow();
1510 for (
int perf = 0; perf < this->number_of_local_perforations_; ++perf) {
1511 const int cell_idx = this->well_cells_[perf];
1512 const auto& intQuants = simulator.model().intensiveQuantities(cell_idx, 0);
1514 std::vector<Scalar> mob(this->num_conservation_quantities_, 0.);
1515 getMobility(simulator, perf, mob, deferred_logger);
1517 getTransMult(trans_mult, simulator, cell_idx);
1518 const auto& wellstate_nupcol = simulator.problem().wellModel().nupcolWellState().well(this->index_of_well_);
1519 std::vector<Scalar> Tw(this->num_conservation_quantities_, this->well_index_[perf] * trans_mult);
1520 this->getTw(Tw, perf, intQuants, trans_mult, wellstate_nupcol);
1522 std::vector<Scalar> cq_s(this->num_conservation_quantities_, 0.);
1524 computePerfRate(intQuants, mob, bhp, Tw, perf, allow_cf,
1525 cq_s, perf_rates, deferred_logger);
1527 for(
int p = 0; p < np; ++p) {
1528 well_flux[FluidSystem::activeCompToActivePhaseIdx(p)] += cq_s[p];
1532 if constexpr (has_solvent) {
1533 assert(FluidSystem::phaseIsActive(FluidSystem::gasPhaseIdx));
1535 const int gas_pos = FluidSystem::canonicalToActivePhaseIdx(FluidSystem::gasPhaseIdx);
1536 well_flux[gas_pos] += cq_s[Indices::contiSolventEqIdx];
1539 this->parallel_well_info_.communication().sum(well_flux.data(), well_flux.size());
1544 template<
typename TypeTag>
1550 std::vector<Scalar>& well_flux)
const
1566 auto guard = groupStateHelper_copy.
pushWellState(well_state_copy);
1569 const auto& summary_state = simulator.vanguard().summaryState();
1570 auto inj_controls = well_copy.
well_ecl_.isInjector()
1571 ? well_copy.
well_ecl_.injectionControls(summary_state)
1572 : Well::InjectionControls(0);
1573 auto prod_controls = well_copy.
well_ecl_.isProducer()
1574 ? well_copy.
well_ecl_.productionControls(summary_state) :
1575 Well::ProductionControls(0);
1578 auto& ws = well_state_copy.
well(this->index_of_well_);
1580 inj_controls.bhp_limit = bhp;
1581 ws.injection_cmode = Well::InjectorCMode::BHP;
1583 prod_controls.bhp_limit = bhp;
1584 ws.production_cmode = Well::ProducerCMode::BHP;
1589 const int np = this->number_of_phases_;
1590 const Scalar sign = this->well_ecl_.isInjector() ? 1.0 : -1.0;
1591 for (
int phase = 0; phase < np; ++phase){
1592 well_state_copy.
wellRates(this->index_of_well_)[phase]
1593 = sign * ws.well_potentials[phase];
1598 const double dt = simulator.timeStepSize();
1600 simulator, dt, inj_controls, prod_controls, groupStateHelper_copy, well_state_copy
1603 const std::string msg =
" well " + name() +
" did not get converged during well potential calculations "
1604 " potentials are computed based on unconverged solution";
1605 deferred_logger.debug(msg);
1615 template<
typename TypeTag>
1616 std::vector<typename StandardWell<TypeTag>::Scalar>
1623 std::vector<Scalar> potentials(this->number_of_phases_, 0.0);
1624 const auto& summary_state = simulator.vanguard().summaryState();
1626 const auto& well = this->well_ecl_;
1627 if (well.isInjector()){
1628 const auto& controls = this->well_ecl_.injectionControls(summary_state);
1629 auto bhp_at_thp_limit = computeBhpAtThpLimitInj(simulator, groupStateHelper, summary_state);
1630 if (bhp_at_thp_limit) {
1631 const Scalar bhp = std::min(*bhp_at_thp_limit,
1632 static_cast<Scalar>(controls.bhp_limit));
1633 computeWellRatesWithBhp(simulator, bhp, potentials, deferred_logger);
1635 deferred_logger.warning(
"FAILURE_GETTING_CONVERGED_POTENTIAL",
1636 "Failed in getting converged thp based potential calculation for well "
1637 + name() +
". Instead the bhp based value is used");
1638 const Scalar bhp = controls.bhp_limit;
1639 computeWellRatesWithBhp(simulator, bhp, potentials, deferred_logger);
1642 computeWellRatesWithThpAlqProd(
1643 simulator, groupStateHelper, summary_state,
1644 potentials, this->getALQ(well_state)
1651 template<
typename TypeTag>
1656 std::vector<Scalar>& well_potentials)
const
1669 auto guard = groupStateHelper_copy.
pushWellState(well_state_copy);
1670 auto& ws = well_state_copy.
well(this->index_of_well_);
1673 const auto& summary_state = simulator.vanguard().summaryState();
1674 auto inj_controls = well_copy.
well_ecl_.isInjector()
1675 ? well_copy.
well_ecl_.injectionControls(summary_state)
1676 : Well::InjectionControls(0);
1677 auto prod_controls = well_copy.
well_ecl_.isProducer()
1678 ? well_copy.
well_ecl_.productionControls(summary_state) :
1679 Well::ProductionControls(0);
1685 const int num_perf = ws.perf_data.size();
1686 for (
int perf = 0; perf < num_perf; ++perf) {
1690 const int np = this->number_of_phases_;
1691 bool trivial =
true;
1692 for (
int phase = 0; phase < np; ++phase){
1693 trivial = trivial && (ws.well_potentials[phase] == 0.0) ;
1697 for (
int phase = 0; phase < np; ++phase) {
1698 ws.surface_rates[phase] = sign * ws.well_potentials[phase];
1703 const double dt = simulator.timeStepSize();
1705 bool converged =
false;
1706 if (this->well_ecl_.isProducer()) {
1708 simulator, dt, inj_controls, prod_controls, groupStateHelper_copy, well_state_copy
1712 simulator, dt, inj_controls, prod_controls, groupStateHelper_copy, well_state_copy,
1720 well_potentials.clear();
1721 well_potentials.resize(np, 0.0);
1722 for (
int comp_idx = 0; comp_idx < this->num_conservation_quantities_; ++comp_idx) {
1723 if (has_solvent && comp_idx == Indices::contiSolventEqIdx)
continue;
1725 well_potentials[FluidSystem::activeCompToActivePhaseIdx(comp_idx)] = rate.value();
1729 if constexpr (has_solvent) {
1730 assert(FluidSystem::phaseIsActive(FluidSystem::gasPhaseIdx));
1732 const int gas_pos = FluidSystem::canonicalToActivePhaseIdx(FluidSystem::gasPhaseIdx);
1734 well_potentials[gas_pos] += rate.value();
1740 template<
typename TypeTag>
1745 const SummaryState &summary_state,
1746 std::vector<Scalar>& potentials,
1751 auto bhp_at_thp_limit = computeBhpAtThpLimitProdWithAlq(
1752 simulator, groupStateHelper, summary_state, alq,
true);
1753 if (bhp_at_thp_limit) {
1754 const auto& controls = this->well_ecl_.productionControls(summary_state);
1755 bhp = std::max(*bhp_at_thp_limit,
1756 static_cast<Scalar>(controls.bhp_limit));
1757 computeWellRatesWithBhp(simulator, bhp, potentials, deferred_logger);
1760 deferred_logger.warning(
"FAILURE_GETTING_CONVERGED_POTENTIAL",
1761 "Failed in getting converged thp based potential calculation for well "
1762 + name() +
". Instead the bhp based value is used");
1763 const auto& controls = this->well_ecl_.productionControls(summary_state);
1764 bhp = controls.bhp_limit;
1765 computeWellRatesWithBhp(simulator, bhp, potentials, deferred_logger);
1770 template<
typename TypeTag>
1775 const SummaryState& summary_state,
1776 std::vector<Scalar>& potentials,
1780 computeWellRatesAndBhpWithThpAlqProd(simulator,
1787 template<
typename TypeTag>
1793 std::vector<Scalar>& well_potentials)
1796 const auto [compute_potential, bhp_controlled_well] =
1799 if (!compute_potential) {
1803 bool converged_implicit =
false;
1807 if (this->param_.local_well_solver_control_switching_ && !(this->changed_to_open_this_step_ && this->wellUnderZeroRateTarget(groupStateHelper))) {
1808 converged_implicit = computeWellPotentialsImplicit(
1809 simulator, groupStateHelper, well_potentials
1812 if (!converged_implicit) {
1814 const auto& summaryState = simulator.vanguard().summaryState();
1815 if (!Base::wellHasTHPConstraints(summaryState) || bhp_controlled_well) {
1825 const auto& ws = well_state.
well(this->index_of_well_);
1826 if (this->isInjector())
1827 bhp = std::max(ws.bhp, bhp);
1829 bhp = std::min(ws.bhp, bhp);
1831 assert(std::abs(bhp) != std::numeric_limits<Scalar>::max());
1832 computeWellRatesWithBhpIterations(simulator, bhp, groupStateHelper, well_potentials);
1835 well_potentials = computeWellPotentialWithTHP(simulator, groupStateHelper, well_state);
1839 this->checkNegativeWellPotentials(well_potentials,
1840 this->param_.check_well_operability_,
1850 template<
typename TypeTag>
1854 const int openConnIdx)
const
1856 return (openConnIdx < 0)
1858 : this->connections_.rho(openConnIdx);
1865 template<
typename TypeTag>
1870 if (!this->isOperableAndSolvable() && !this->wellIsStopped())
return;
1873 const auto& well_state = groupStateHelper.
wellState();
1874 const bool stop_or_zero_rate_target = this->stoppedOrZeroRateTarget(groupStateHelper);
1875 this->primary_variables_.update(well_state, stop_or_zero_rate_target, deferred_logger);
1878 if constexpr (Base::has_polymermw) {
1879 this->primary_variables_.updatePolyMW(well_state);
1882 this->primary_variables_.checkFinite(deferred_logger,
"updating from well state");
1888 template<
typename TypeTag>
1893 return cachedRefDensity;
1899 template<
typename TypeTag>
1904 std::vector<EvalWell>& mob,
1907 const int cell_idx = this->well_cells_[perf];
1908 const auto& int_quant = simulator.model().intensiveQuantities(cell_idx, 0);
1909 const EvalWell polymer_concentration = this->extendEval(int_quant.polymerConcentration());
1913 if (this->isInjector()) {
1915 const auto& visc_mult_table = PolymerModule::plyviscViscosityMultiplierTable(int_quant.pvtRegionIndex());
1916 const unsigned waterCompIdx = FluidSystem::canonicalToActiveCompIdx(FluidSystem::waterCompIdx);
1917 mob[waterCompIdx] /= (this->extendEval(int_quant.waterViscosityCorrection()) * visc_mult_table.eval(polymer_concentration,
true) );
1920 if (PolymerModule::hasPlyshlog()) {
1923 if (this->isInjector() && this->wpolymer() == 0.) {
1928 const bool allow_cf = this->getAllowCrossFlow() || openCrossFlowAvoidSingularity(simulator);
1929 const EvalWell& bhp = this->primary_variables_.eval(Bhp);
1931 std::vector<EvalWell> cq_s(this->num_conservation_quantities_, 0.);
1934 getTransMult(trans_mult, simulator, cell_idx);
1935 const auto& wellstate_nupcol = simulator.problem().wellModel().nupcolWellState().well(this->index_of_well_);
1936 std::vector<EvalWell> Tw(this->num_conservation_quantities_, this->well_index_[perf] * trans_mult);
1937 this->getTw(Tw, perf, int_quant, trans_mult, wellstate_nupcol);
1938 computePerfRate(int_quant, mob, bhp, Tw, perf, allow_cf, cq_s,
1939 perf_rates, deferred_logger);
1941 const Scalar area = 2 * M_PI * this->perf_rep_radius_[perf] * this->perf_length_[perf];
1942 const auto& material_law_manager = simulator.problem().materialLawManager();
1943 const auto& scaled_drainage_info =
1944 material_law_manager->oilWaterScaledEpsInfoDrainage(cell_idx);
1945 const Scalar swcr = scaled_drainage_info.Swcr;
1946 const EvalWell poro = this->extendEval(int_quant.porosity());
1947 const EvalWell sw = this->extendEval(int_quant.fluidState().saturation(FluidSystem::waterPhaseIdx));
1949 const EvalWell denom = max( (area * poro * (sw - swcr)), 1e-12);
1950 const unsigned waterCompIdx = FluidSystem::canonicalToActiveCompIdx(FluidSystem::waterCompIdx);
1951 EvalWell water_velocity = cq_s[waterCompIdx] / denom * this->extendEval(int_quant.fluidState().invB(FluidSystem::waterPhaseIdx));
1953 if (PolymerModule::hasShrate()) {
1956 water_velocity *= PolymerModule::shrate( int_quant.pvtRegionIndex() ) / this->bore_diameters_[perf];
1958 const EvalWell shear_factor = PolymerModule::computeShearFactor(polymer_concentration,
1959 int_quant.pvtRegionIndex(),
1962 mob[waterCompIdx] /= shear_factor;
1966 template<
typename TypeTag>
1970 this->linSys_.extract(jacobian);
1974 template <
typename TypeTag>
1978 const int pressureVarIndex,
1979 const bool use_well_weights,
1982 this->linSys_.extractCPRPressureMatrix(jacobian,
1993 template<
typename TypeTag>
2000 if constexpr (Base::has_polymermw) {
2001 const int water_table_id = this->polymerWaterTable_();
2002 if (water_table_id <= 0) {
2004 fmt::format(
"Unused SKPRWAT table id used for well {}", name()),
2007 const auto& water_table_func = PolymerModule::getSkprwatTable(water_table_id);
2008 const EvalWell throughput_eval{throughput};
2010 EvalWell pskin_water = water_table_func.eval(throughput_eval, water_velocity);
2014 fmt::format(
"Polymermw is not activated, while injecting "
2015 "skin pressure is requested for well {}", name()),
2024 template<
typename TypeTag>
2032 if constexpr (Base::has_polymermw) {
2033 const Scalar sign = water_velocity >= 0. ? 1.0 : -1.0;
2034 const EvalWell water_velocity_abs = abs(water_velocity);
2035 if (poly_inj_conc == 0.) {
2036 return sign * pskinwater(throughput, water_velocity_abs, deferred_logger);
2038 const int polymer_table_id = this->polymerTable_();
2039 if (polymer_table_id <= 0) {
2041 fmt::format(
"Unavailable SKPRPOLY table id used for well {}", name()),
2044 const auto& skprpolytable = PolymerModule::getSkprpolyTable(polymer_table_id);
2045 const Scalar reference_concentration = skprpolytable.refConcentration;
2046 const EvalWell throughput_eval{throughput};
2048 const EvalWell pskin_poly = skprpolytable.table_func.eval(throughput_eval, water_velocity_abs);
2049 if (poly_inj_conc == reference_concentration) {
2050 return sign * pskin_poly;
2053 const EvalWell pskin_water = pskinwater(throughput, water_velocity_abs, deferred_logger);
2054 const EvalWell pskin = pskin_water + (pskin_poly - pskin_water) / reference_concentration * poly_inj_conc;
2055 return sign * pskin;
2058 fmt::format(
"Polymermw is not activated, while injecting "
2059 "skin pressure is requested for well {}", name()),
2068 template<
typename TypeTag>
2075 if constexpr (Base::has_polymermw) {
2076 const int table_id = this->polymerInjTable_();
2077 const auto& table_func = PolymerModule::getPlymwinjTable(table_id);
2078 const EvalWell throughput_eval{throughput};
2080 if (this->wpolymer() == 0.) {
2081 return molecular_weight;
2083 molecular_weight = table_func.eval(throughput_eval, abs(water_velocity));
2084 return molecular_weight;
2087 fmt::format(
"Polymermw is not activated, while injecting "
2088 "polymer molecular weight is requested for well {}", name()),
2097 template<
typename TypeTag>
2103 if constexpr (Base::has_polymermw) {
2104 if (!this->isInjector()) {
2108 auto& perf_water_throughput = well_state.
well(this->index_of_well_)
2109 .perf_data.water_throughput;
2111 for (
int perf = 0; perf < this->number_of_local_perforations_; ++perf) {
2112 const Scalar perf_water_vel =
2113 this->primary_variables_.value(Bhp + 1 + perf);
2117 if (perf_water_vel >
Scalar{0}) {
2118 perf_water_throughput[perf] += perf_water_vel * dt;
2128 template<
typename TypeTag>
2133 std::vector<EvalWell>& cq_s)
const
2135 const int cell_idx = this->well_cells_[perf];
2136 const auto& int_quants = simulator.model().intensiveQuantities(cell_idx, 0);
2137 const auto& fs = int_quants.fluidState();
2138 const EvalWell b_w = this->extendEval(fs.invB(FluidSystem::waterPhaseIdx));
2139 const Scalar area = M_PI * this->bore_diameters_[perf] * this->perf_length_[perf];
2140 const int wat_vel_index = Bhp + 1 + perf;
2141 const unsigned water_comp_idx = FluidSystem::canonicalToActiveCompIdx(FluidSystem::waterCompIdx);
2145 cq_s[water_comp_idx] = area * this->primary_variables_.eval(wat_vel_index) * b_w;
2151 template<
typename TypeTag>
2160 const int cell_idx = this->well_cells_[perf];
2161 const auto& int_quants = simulator.model().intensiveQuantities(cell_idx, 0);
2162 const auto& fs = int_quants.fluidState();
2163 const EvalWell b_w = this->extendEval(fs.invB(FluidSystem::waterPhaseIdx));
2164 const EvalWell water_flux_r = water_flux_s / b_w;
2165 const Scalar area = M_PI * this->bore_diameters_[perf] * this->perf_length_[perf];
2166 const EvalWell water_velocity = water_flux_r / area;
2167 const int wat_vel_index = Bhp + 1 + perf;
2170 const EvalWell eq_wat_vel = this->primary_variables_.eval(wat_vel_index) - water_velocity;
2172 const auto& ws = well_state.
well(this->index_of_well_);
2173 const auto& perf_data = ws.perf_data;
2174 const auto& perf_water_throughput = perf_data.water_throughput;
2175 const Scalar throughput = perf_water_throughput[perf];
2176 const int pskin_index = Bhp + 1 + this->number_of_local_perforations_ + perf;
2178 const EvalWell poly_conc(this->wpolymer());
2181 const EvalWell eq_pskin = this->primary_variables_.eval(pskin_index)
2182 - pskin(throughput, this->primary_variables_.eval(wat_vel_index), poly_conc, deferred_logger);
2185 assembleInjectivityEq(eq_pskin,
2190 this->primary_variables_.numWellEq(),
2198 template<
typename TypeTag>
2207 if constexpr (Base::has_polymermw) {
2209 checkConvergencePolyMW(res, Bhp, this->param_.max_residual_allowed_, report);
2217 template<
typename TypeTag>
2224 std::vector<RateVector>& connectionRates,
2229 if (this->isInjector()) {
2230 const int wat_vel_index = Bhp + 1 + perf;
2231 const EvalWell water_velocity = this->primary_variables_.eval(wat_vel_index);
2232 if (water_velocity > 0.) {
2233 const auto& ws = well_state.
well(this->index_of_well_);
2234 const auto& perf_water_throughput = ws.perf_data.water_throughput;
2235 const Scalar throughput = perf_water_throughput[perf];
2236 const EvalWell molecular_weight = wpolymermw(throughput, water_velocity, deferred_logger);
2237 cq_s_polymw *= molecular_weight;
2243 }
else if (this->isProducer()) {
2244 if (cq_s_polymw < 0.) {
2245 cq_s_polymw *= this->extendEval(int_quants.polymerMoleWeight() );
2252 connectionRates[perf][Indices::contiPolymerMWEqIdx] = Base::restrictEval(cq_s_polymw);
2259 template<
typename TypeTag>
2260 std::optional<typename StandardWell<TypeTag>::Scalar>
2265 const SummaryState& summary_state)
const
2267 return computeBhpAtThpLimitProdWithAlq(simulator,
2270 this->getALQ(well_state),
2274 template<
typename TypeTag>
2275 std::optional<typename StandardWell<TypeTag>::Scalar>
2279 const SummaryState& summary_state,
2281 bool iterate_if_no_solution)
const
2286 auto frates = [
this, &simulator, &deferred_logger](
const Scalar bhp) {
2292 std::vector<Scalar> rates(3);
2293 computeWellRatesWithBhp(simulator, bhp, rates, deferred_logger);
2294 this->adaptRatesForVFP(rates);
2299 maxPerfPress(simulator),
2300 this->getRefDensity(),
2302 this->getTHPConstraint(summary_state),
2306 auto v = frates(*bhpAtLimit);
2307 if (std::all_of(v.cbegin(), v.cend(), [](
Scalar i){ return i <= 0; }) ) {
2312 if (!iterate_if_no_solution)
2313 return std::nullopt;
2315 auto fratesIter = [
this, &simulator, &groupStateHelper](
const Scalar bhp) {
2319 std::vector<Scalar> rates(3);
2320 computeWellRatesWithBhpIterations(simulator, bhp, groupStateHelper, rates);
2321 this->adaptRatesForVFP(rates);
2327 maxPerfPress(simulator),
2328 this->getRefDensity(),
2330 this->getTHPConstraint(summary_state),
2336 auto v = frates(*bhpAtLimit);
2337 if (std::all_of(v.cbegin(), v.cend(), [](
Scalar i){ return i <= 0; }) ) {
2343 return std::nullopt;
2348 template<
typename TypeTag>
2349 std::optional<typename StandardWell<TypeTag>::Scalar>
2353 const SummaryState& summary_state)
const
2357 auto frates = [
this, &simulator, &deferred_logger](
const Scalar bhp) {
2363 std::vector<Scalar> rates(3);
2364 computeWellRatesWithBhp(simulator, bhp, rates, deferred_logger);
2370 this->getRefDensity(),
2381 template<
typename TypeTag>
2386 const Well::InjectionControls& inj_controls,
2387 const Well::ProductionControls& prod_controls,
2393 updatePrimaryVariables(groupStateHelper);
2395 const int max_iter = this->param_.max_inner_iter_wells_;
2398 bool relax_convergence =
false;
2399 this->regularize_ =
false;
2401 assembleWellEqWithoutIteration(simulator, groupStateHelper, dt, inj_controls, prod_controls, well_state,
2404 if (it > this->param_.strict_inner_iter_wells_) {
2405 relax_convergence =
true;
2406 this->regularize_ =
true;
2409 auto report = getWellConvergence(groupStateHelper, Base::B_avg_, relax_convergence);
2411 converged = report.converged();
2417 solveEqAndUpdateWellState(simulator, groupStateHelper, well_state);
2424 }
while (it < max_iter);
2427 std::ostringstream sstr;
2428 sstr <<
" Well " << this->name() <<
" converged in " << it <<
" inner iterations.";
2429 if (relax_convergence)
2430 sstr <<
" (A relaxed tolerance was used after "<< this->param_.strict_inner_iter_wells_ <<
" iterations)";
2434 deferred_logger.debug(sstr.str(), OpmLog::defaultDebugVerbosityLevel + (it == 0));
2436 std::ostringstream sstr;
2437 sstr <<
" Well " << this->name() <<
" did not converge in " << it <<
" inner iterations.";
2438 deferred_logger.debug(sstr.str());
2445 template<
typename TypeTag>
2450 const Well::InjectionControls& inj_controls,
2451 const Well::ProductionControls& prod_controls,
2454 const bool fixed_control ,
2455 const bool fixed_status ,
2456 const bool solving_with_zero_rate )
2460 updatePrimaryVariables(groupStateHelper);
2462 const int max_iter = this->param_.max_inner_iter_wells_;
2464 bool converged =
false;
2465 bool relax_convergence =
false;
2466 this->regularize_ =
false;
2467 const auto& summary_state = groupStateHelper.
summaryState();
2472 constexpr int min_its_after_switch = 4;
2474 const int max_status_switch = this->param_.max_well_status_switch_inner_iter_;
2475 int its_since_last_switch = min_its_after_switch;
2476 int switch_count= 0;
2478 const auto well_status_orig = this->wellStatus_;
2479 const auto operability_orig = this->operability_status_;
2480 auto well_status_cur = well_status_orig;
2481 int status_switch_count = 0;
2483 const bool allow_open = well_state.
well(this->index_of_well_).status == WellStatus::OPEN;
2485 const bool allow_switching =
2486 !this->wellUnderZeroRateTarget(groupStateHelper) &&
2487 (!fixed_control || !fixed_status) && allow_open;
2489 bool changed =
false;
2490 bool final_check =
false;
2492 this->operability_status_.resetOperability();
2493 this->operability_status_.solvable =
true;
2495 its_since_last_switch++;
2496 if (allow_switching && its_since_last_switch >= min_its_after_switch && status_switch_count < max_status_switch){
2497 const Scalar wqTotal = this->primary_variables_.eval(WQTotal).value();
2498 changed = this->updateWellControlAndStatusLocalIteration(
2499 simulator, groupStateHelper, inj_controls, prod_controls, wqTotal,
2500 well_state, fixed_control, fixed_status,
2501 solving_with_zero_rate
2504 its_since_last_switch = 0;
2506 if (well_status_cur != this->wellStatus_) {
2507 well_status_cur = this->wellStatus_;
2508 status_switch_count++;
2511 if (!changed && final_check) {
2514 final_check =
false;
2516 if (status_switch_count == max_status_switch) {
2517 this->wellStatus_ = well_status_orig;
2521 assembleWellEqWithoutIteration(simulator, groupStateHelper, dt, inj_controls, prod_controls, well_state, solving_with_zero_rate);
2523 if (it > this->param_.strict_inner_iter_wells_) {
2524 relax_convergence =
true;
2525 this->regularize_ =
true;
2528 auto report = getWellConvergence(groupStateHelper, Base::B_avg_, relax_convergence);
2530 converged = report.converged();
2534 if (switch_count > 0 && its_since_last_switch < min_its_after_switch) {
2536 its_since_last_switch = min_its_after_switch;
2543 solveEqAndUpdateWellState(simulator, groupStateHelper, well_state);
2545 }
while (it < max_iter);
2548 if (allow_switching){
2550 const bool is_stopped = this->wellIsStopped();
2551 if (this->wellHasTHPConstraints(summary_state)){
2552 this->operability_status_.can_obtain_bhp_with_thp_limit = !is_stopped;
2553 this->operability_status_.obey_thp_limit_under_bhp_limit = !is_stopped;
2555 this->operability_status_.operable_under_only_bhp_limit = !is_stopped;
2558 std::string message = fmt::format(
" Well {} converged in {} inner iterations ("
2559 "{} control/status switches).", this->name(), it, switch_count);
2560 if (relax_convergence) {
2561 message.append(fmt::format(
" (A relaxed tolerance was used after {} iterations)",
2562 this->param_.strict_inner_iter_wells_));
2564 deferred_logger.debug(message, OpmLog::defaultDebugVerbosityLevel + ((it == 0) && (switch_count == 0)));
2567 this->wellStatus_ = well_status_orig;
2568 this->operability_status_ = operability_orig;
2569 const std::string message = fmt::format(
" Well {} did not converge in {} inner iterations ("
2570 "{} switches, {} status changes).", this->name(), it, switch_count, status_switch_count);
2571 deferred_logger.debug(message);
2577 template<
typename TypeTag>
2578 std::vector<typename StandardWell<TypeTag>::Scalar>
2584 std::vector<Scalar> well_q_s(this->num_conservation_quantities_, 0.);
2585 const EvalWell& bhp = this->primary_variables_.eval(Bhp);
2586 const bool allow_cf = this->getAllowCrossFlow() || openCrossFlowAvoidSingularity(simulator);
2587 for (
int perf = 0; perf < this->number_of_local_perforations_; ++perf) {
2588 const int cell_idx = this->well_cells_[perf];
2589 const auto& intQuants = simulator.model().intensiveQuantities(cell_idx, 0);
2590 std::vector<Scalar> mob(this->num_conservation_quantities_, 0.);
2591 getMobility(simulator, perf, mob, deferred_logger);
2592 std::vector<Scalar> cq_s(this->num_conservation_quantities_, 0.);
2594 getTransMult(trans_mult, simulator, cell_idx);
2595 const auto& wellstate_nupcol = simulator.problem().wellModel().nupcolWellState().well(this->index_of_well_);
2596 std::vector<Scalar> Tw(this->num_conservation_quantities_, this->well_index_[perf] * trans_mult);
2597 this->getTw(Tw, perf, intQuants, trans_mult, wellstate_nupcol);
2599 computePerfRate(intQuants, mob, bhp.value(), Tw, perf, allow_cf,
2600 cq_s, perf_rates, deferred_logger);
2601 for (
int comp = 0; comp < this->num_conservation_quantities_; ++comp) {
2602 well_q_s[comp] += cq_s[comp];
2605 const auto& comm = this->parallel_well_info_.communication();
2606 if (comm.size() > 1)
2608 comm.sum(well_q_s.data(), well_q_s.size());
2615 template <
typename TypeTag>
2616 std::vector<typename StandardWell<TypeTag>::Scalar>
2620 const int num_pri_vars = this->primary_variables_.numWellEq();
2621 std::vector<Scalar> retval(num_pri_vars);
2622 for (
int ii = 0; ii < num_pri_vars; ++ii) {
2623 retval[ii] = this->primary_variables_.value(ii);
2632 template <
typename TypeTag>
2637 const int num_pri_vars = this->primary_variables_.numWellEq();
2638 for (
int ii = 0; ii < num_pri_vars; ++ii) {
2639 this->primary_variables_.setValue(ii, it[ii]);
2641 return num_pri_vars;
2645 template <
typename TypeTag>
2649 const IntensiveQuantities& intQuants,
2652 auto fs = intQuants.fluidState();
2654 for (
unsigned phaseIdx = 0; phaseIdx < FluidSystem::numPhases; ++phaseIdx) {
2655 if (!FluidSystem::phaseIsActive(phaseIdx)) {
2660 EvalWell cq_r_thermal{0.};
2661 const unsigned activeCompIdx = FluidSystem::canonicalToActiveCompIdx(FluidSystem::solventComponentIndex(phaseIdx));
2662 const bool both_oil_gas = FluidSystem::phaseIsActive(FluidSystem::oilPhaseIdx) && FluidSystem::phaseIsActive(FluidSystem::gasPhaseIdx);
2663 if (!both_oil_gas || FluidSystem::waterPhaseIdx == phaseIdx) {
2664 cq_r_thermal = cq_s[activeCompIdx] / this->extendEval(fs.invB(phaseIdx));
2667 const unsigned oilCompIdx = FluidSystem::canonicalToActiveCompIdx(FluidSystem::oilCompIdx);
2668 const unsigned gasCompIdx = FluidSystem::canonicalToActiveCompIdx(FluidSystem::gasCompIdx);
2673 const EvalWell d = this->extendEval(1.0 - fs.Rv() * fs.Rs());
2675 deferred_logger.
debug(
2676 fmt::format(
"Problematic d value {} obtained for well {}"
2677 " during calculateSinglePerf with rs {}"
2678 ", rv {}. Continue as if no dissolution (rs = 0) and"
2679 " vaporization (rv = 0) for this connection.",
2680 d, this->name(), fs.Rs(), fs.Rv()));
2681 cq_r_thermal = cq_s[activeCompIdx] / this->extendEval(fs.invB(phaseIdx));
2683 if (FluidSystem::gasPhaseIdx == phaseIdx) {
2684 cq_r_thermal = (cq_s[gasCompIdx] -
2685 this->extendEval(fs.Rs()) * cq_s[oilCompIdx]) /
2686 (d * this->extendEval(fs.invB(phaseIdx)) );
2687 }
else if (FluidSystem::oilPhaseIdx == phaseIdx) {
2689 cq_r_thermal = (cq_s[oilCompIdx] - this->extendEval(fs.Rv()) *
2691 (d * this->extendEval(fs.invB(phaseIdx)) );
2697 if (this->isInjector() && !this->wellIsStopped() && cq_r_thermal > 0.0){
2699 assert(this->well_ecl_.injectorType() != InjectorType::MULTI);
2700 fs.setTemperature(this->well_ecl_.inj_temperature());
2701 typedef typename std::decay<
decltype(fs)>::type::Scalar FsScalar;
2702 typename FluidSystem::template ParameterCache<FsScalar> paramCache;
2703 const unsigned pvtRegionIdx = intQuants.pvtRegionIndex();
2704 paramCache.setRegionIndex(pvtRegionIdx);
2705 paramCache.updatePhase(fs, phaseIdx);
2707 const auto& rho = FluidSystem::density(fs, paramCache, phaseIdx);
2708 fs.setDensity(phaseIdx, rho);
2709 const auto& h = FluidSystem::enthalpy(fs, paramCache, phaseIdx);
2710 fs.setEnthalpy(phaseIdx, h);
2711 cq_r_thermal *= this->extendEval(fs.enthalpy(phaseIdx)) * this->extendEval(fs.density(phaseIdx));
2712 result += getValue(cq_r_thermal);
2713 }
else if (cq_r_thermal > 0.0) {
2714 cq_r_thermal *= getValue(fs.enthalpy(phaseIdx)) * getValue(fs.density(phaseIdx));
2715 result += Base::restrictEval(cq_r_thermal);
2718 cq_r_thermal *= this->extendEval(fs.enthalpy(phaseIdx)) * this->extendEval(fs.density(phaseIdx));
2719 result += Base::restrictEval(cq_r_thermal);
2723 return result * this->well_efficiency_factor_;
2726 template <
typename TypeTag>
2730 Scalar max_pressure = 0.0;
2731 for (
int perf = 0; perf < this->number_of_local_perforations_; ++perf) {
2732 const int cell_idx = this->well_cells_[perf];
2733 const auto& int_quants = simulator.model().intensiveQuantities(cell_idx, 0);
2734 const auto& fs = int_quants.fluidState();
2735 Scalar pressure_cell = this->getPerfCellPressure(fs).value();
2736 max_pressure = std::max(max_pressure, pressure_cell);
2738 const auto& comm = this->parallel_well_info_.communication();
2739 if (comm.size() > 1) {
2740 max_pressure = comm.max(max_pressure);
2742 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:54
GroupState< Scalar > & groupState() const
Definition: GroupStateHelper.hpp:272
const SummaryState & summaryState() const
Definition: GroupStateHelper.hpp:387
const WellState< Scalar, IndexTraits > & wellState() const
Definition: GroupStateHelper.hpp:440
DeferredLogger & deferredLogger() const
Get the deferred logger.
Definition: GroupStateHelper.hpp:226
WellStateGuard pushWellState(WellState< Scalar, IndexTraits > &well_state)
Definition: GroupStateHelper.hpp:326
GroupStateGuard pushGroupState(GroupState< Scalar > &group_state)
Definition: GroupStateHelper.hpp:303
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
EvalWell wpolymermw(const Scalar throughput, const EvalWell &water_velocity, DeferredLogger &deferred_logger) const
Definition: StandardWell_impl.hpp:2071
std::vector< Scalar > computeWellPotentialWithTHP(const Simulator &ebosSimulator, const GroupStateHelperType &groupStateHelper, const WellStateType &well_state) const
Definition: StandardWell_impl.hpp:1618
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:804
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:1220
WellConnectionProps computePropertiesForWellConnectionPressures(const Simulator &simulator, const WellStateType &well_state) const
Definition: StandardWell_impl.hpp:1169
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:2277
typename StdWellEval::BVectorWell BVectorWell
Definition: StandardWell.hpp:122
void addWellContributions(SparseMatrixAdapter &mat) const override
Definition: StandardWell_impl.hpp:1968
std::vector< Scalar > getPrimaryVars() const override
Definition: StandardWell_impl.hpp:2618
void updateWellState(const Simulator &simulator, const BVectorWell &dwells, const GroupStateHelperType &groupStateHelper, WellStateType &well_state)
Definition: StandardWell_impl.hpp:757
void updatePrimaryVariables(const GroupStateHelperType &groupStateHelper) override
Definition: StandardWell_impl.hpp:1868
void solveEqAndUpdateWellState(const Simulator &simulator, const GroupStateHelperType &groupStateHelper, WellStateType &well_state) override
Definition: StandardWell_impl.hpp:1412
void computeWellConnectionDensitesPressures(const Simulator &simulator, const GroupStateHelperType &groupStateHelper, const WellConnectionProps &props)
Definition: StandardWell_impl.hpp:1338
std::optional< Scalar > computeBhpAtThpLimitProd(const WellStateType &well_state, const Simulator &simulator, const GroupStateHelperType &groupStateHelper, const SummaryState &summary_state) const
Definition: StandardWell_impl.hpp:2262
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:1976
void updateWaterMobilityWithPolymer(const Simulator &simulator, const int perf, std::vector< EvalWell > &mob_water, DeferredLogger &deferred_logger) const
Definition: StandardWell_impl.hpp:1902
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:2384
std::vector< Scalar > computeCurrentWellRates(const Simulator &ebosSimulator, DeferredLogger &deferred_logger) const override
Definition: StandardWell_impl.hpp:2580
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:503
void computeWellConnectionPressures(const Simulator &simulator, const GroupStateHelperType &groupStateHelper)
Definition: StandardWell_impl.hpp:1395
void updatePrimaryVariablesNewton(const BVectorWell &dwells, const bool stop_or_zero_rate_target, DeferredLogger &deferred_logger)
Definition: StandardWell_impl.hpp:781
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:341
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:1790
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:52
std::optional< Scalar > computeBhpAtThpLimitInj(const Simulator &simulator, const GroupStateHelperType &groupStateHelper, const SummaryState &summary_state) const
Definition: StandardWell_impl.hpp:2351
typename StdWellEval::StdWellConnections::Properties WellConnectionProps
Definition: StandardWell.hpp:261
void computeWellRatesWithBhpIterations(const Simulator &ebosSimulator, const Scalar &bhp, const GroupStateHelperType &groupStateHelper, std::vector< Scalar > &well_flux) const override
Definition: StandardWell_impl.hpp:1547
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:2220
void computeWellRatesWithBhp(const Simulator &ebosSimulator, const Scalar &bhp, std::vector< Scalar > &well_flux, DeferredLogger &deferred_logger) const override
Definition: StandardWell_impl.hpp:1499
void updateIPRImplicit(const Simulator &simulator, const GroupStateHelperType &groupStateHelper, WellStateType &well_state) override
Definition: StandardWell_impl.hpp:920
void getMobility(const Simulator &simulator, const int perf, std::vector< Value > &mob, DeferredLogger &deferred_logger) const
Definition: StandardWell_impl.hpp:701
void getTransMult(Value &trans_mult, const Simulator &simulator, const int cell_indx) const
Definition: StandardWell_impl.hpp:681
void updateIPR(const Simulator &simulator, DeferredLogger &deferred_logger) const override
Definition: StandardWell_impl.hpp:828
void handleInjectivityEquations(const Simulator &simulator, const WellStateType &well_state, const int perf, const EvalWell &water_flux_s, DeferredLogger &deferred_logger)
Definition: StandardWell_impl.hpp:2154
virtual void apply(const BVector &x, BVector &Ax) const override
Ax = Ax - C D^-1 B x.
Definition: StandardWell_impl.hpp:1447
void checkConvergenceExtraEqs(const std::vector< Scalar > &res, ConvergenceReport &report) const
Definition: StandardWell_impl.hpp:2201
void computeWellRatesWithThpAlqProd(const Simulator &ebos_simulator, const GroupStateHelperType &groupStateHelper, const SummaryState &summary_state, std::vector< Scalar > &potentials, Scalar alq) const
Definition: StandardWell_impl.hpp:1773
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:1743
bool openCrossFlowAvoidSingularity(const Simulator &simulator) const
Definition: StandardWell_impl.hpp:1158
bool computeWellPotentialsImplicit(const Simulator &ebos_simulator, const GroupStateHelperType &groupStateHelper, std::vector< Scalar > &well_potentials) const
Definition: StandardWell_impl.hpp:1654
void recoverWellSolutionAndUpdateWellState(const Simulator &simulator, const BVector &x, const GroupStateHelperType &groupStateHelper, WellStateType &well_state) override
Definition: StandardWell_impl.hpp:1479
Scalar maxPerfPress(const Simulator &simulator) const override
Definition: StandardWell_impl.hpp:2729
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:2448
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:366
bool allDrawDownWrongDirection(const Simulator &simulator) const
Definition: StandardWell_impl.hpp:1116
EvalWell pskin(const Scalar throughput, const EvalWell &water_velocity, const EvalWell &poly_inj_conc, DeferredLogger &deferred_logger) const
Definition: StandardWell_impl.hpp:2027
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:93
static constexpr int numWellConservationEq
Definition: StandardWell.hpp:97
int setPrimaryVars(typename std::vector< Scalar >::const_iterator it) override
Definition: StandardWell_impl.hpp:2635
void updateWaterThroughput(const double dt, WellStateType &well_state) const override
Definition: StandardWell_impl.hpp:2100
void checkOperabilityUnderBHPLimit(const WellStateType &well_state, const Simulator &simulator, DeferredLogger &deferred_logger) override
Definition: StandardWell_impl.hpp:997
EvalWell pskinwater(const Scalar throughput, const EvalWell &water_velocity, DeferredLogger &deferred_logger) const
Definition: StandardWell_impl.hpp:1996
void handleInjectivityRate(const Simulator &simulator, const int perf, std::vector< EvalWell > &cq_s) const
Definition: StandardWell_impl.hpp:2131
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:76
void updateProductivityIndex(const Simulator &simulator, const WellProdIndexCalculator< Scalar > &wellPICalc, WellStateType &well_state, DeferredLogger &deferred_logger) const override
Definition: StandardWell_impl.hpp:1263
void calculateExplicitQuantities(const Simulator &simulator, const GroupStateHelperType &groupStateHelper) override
Definition: StandardWell_impl.hpp:1434
Scalar getRefDensity() const override
Definition: StandardWell_impl.hpp:1891
void checkOperabilityUnderTHPLimit(const Simulator &simulator, const WellStateType &well_state, const GroupStateHelperType &groupStateHelper) override
Definition: StandardWell_impl.hpp:1066
Scalar connectionDensity(const int globalConnIdx, const int openConnIdx) const override
Definition: StandardWell_impl.hpp:1853
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:314
Well well_ecl_
Definition: WellInterfaceGeneric.hpp:304
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:590
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:2053
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:2066
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:290
std::vector< Scalar > & wellRates(std::size_t well_index)
One rate per well and phase.
Definition: WellState.hpp:255
@ NONE
Definition: DeferredLogger.hpp:46
Definition: blackoilbioeffectsmodules.hh:43
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