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_components,
60 const int index_of_well,
62 :
Base(well, pw_info, time_step, param, rate_converter, pvtRegionIdx, num_components, num_phases, index_of_well, perf_data)
73 template<
typename TypeTag>
77 const std::vector<Scalar>& depth_arg,
79 const std::vector< Scalar >& B_avg,
80 const bool changed_to_open_this_step)
82 Base::init(phase_usage_arg, 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<Scalar>& 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->numComponents(), zeroElem());
139 for (
unsigned phaseIdx = 0; phaseIdx < FluidSystem::numPhases; ++phaseIdx) {
140 if (!FluidSystem::phaseIsActive(phaseIdx)) {
143 const unsigned compIdx = Indices::canonicalToActiveComponentIndex(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 = Indices::canonicalToActiveComponentIndex(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->numComponents(), zeroElem());
168 for (
int componentIdx = 0; componentIdx < this->numComponents(); ++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<Scalar>& 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 ? Indices::canonicalToActiveComponentIndex(FluidSystem::gasCompIdx)
224 FluidSystem::phaseIsActive(FluidSystem::oilPhaseIdx)
225 ? Indices::canonicalToActiveComponentIndex(FluidSystem::oilCompIdx)
227 FluidSystem::phaseIsActive(FluidSystem::waterPhaseIdx)
228 ? Indices::canonicalToActiveComponentIndex(FluidSystem::waterCompIdx)
236 if (!allow_cf && this->isInjector()) {
241 for (
int componentIdx = 0; componentIdx < this->numComponents(); ++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->numComponents(); ++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 = Indices::canonicalToActiveComponentIndex(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 = Indices::canonicalToActiveComponentIndex(FluidSystem::oilCompIdx);
301 volumeRatio += cmix_s[oilCompIdx] / b_perfcells_dense[oilCompIdx];
303 if (FluidSystem::phaseIsActive(FluidSystem::gasPhaseIdx)) {
304 const unsigned gasCompIdx = Indices::canonicalToActiveComponentIndex(FluidSystem::gasCompIdx);
305 volumeRatio += cmix_s[gasCompIdx] / b_perfcells_dense[gasCompIdx];
311 for (
int componentIdx = 0; componentIdx < this->numComponents(); ++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>
344 const Well::InjectionControls& inj_controls,
345 const Well::ProductionControls& prod_controls,
352 if (!this->isOperableAndSolvable() && !this->wellIsStopped())
return;
355 this->linSys_.clear();
357 assembleWellEqWithoutIterationImpl(simulator, dt, inj_controls,
358 prod_controls, well_state,
359 group_state, deferred_logger);
365 template<
typename TypeTag>
370 const Well::InjectionControls& inj_controls,
371 const Well::ProductionControls& prod_controls,
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);
384 const int np = this->number_of_phases_;
386 std::vector<RateVector> connectionRates = this->connectionRates_;
388 auto& perf_data = ws.perf_data;
389 auto& perf_rates = perf_data.phase_rates;
390 for (
int perf = 0; perf < this->number_of_local_perforations_; ++perf) {
392 std::vector<EvalWell> cq_s(this->num_components_, {this->primary_variables_.numWellEq() + Indices::numEq, 0.0});
393 EvalWell water_flux_s{this->primary_variables_.numWellEq() + Indices::numEq, 0.0};
394 EvalWell cq_s_zfrac_effective{this->primary_variables_.numWellEq() + Indices::numEq, 0.0};
395 calculateSinglePerf(simulator, perf, well_state, connectionRates,
396 cq_s, water_flux_s, cq_s_zfrac_effective, deferred_logger);
399 if constexpr (has_polymer && Base::has_polymermw) {
400 if (this->isInjector()) {
401 handleInjectivityEquations(simulator, well_state, perf,
402 water_flux_s, deferred_logger);
405 for (
int componentIdx = 0; componentIdx < this->num_components_; ++componentIdx) {
407 const EvalWell cq_s_effective = cq_s[componentIdx] * this->well_efficiency_factor_;
409 connectionRates[perf][componentIdx] = Base::restrictEval(cq_s_effective);
412 assemblePerforationEq(cq_s_effective,
415 this->primary_variables_.numWellEq(),
419 if (has_solvent && componentIdx == Indices::contiSolventEqIdx) {
420 auto& perf_rate_solvent = perf_data.solvent_rates;
421 perf_rate_solvent[perf] = cq_s[componentIdx].value();
423 perf_rates[perf*np + this->modelCompIdxToFlowCompIdx(componentIdx)] = cq_s[componentIdx].value();
427 if constexpr (has_zFraction) {
429 assembleZFracEq(cq_s_zfrac_effective,
431 this->primary_variables_.numWellEq(),
436 this->connectionRates_ = connectionRates;
441 const auto& comm = this->parallel_well_info_.communication();
442 comm.sum(ws.phase_mixing_rates.data(), ws.phase_mixing_rates.size());
446 this->linSys_.sumDistributed(this->parallel_well_info_.communication());
449 for (
int componentIdx = 0; componentIdx < numWellConservationEq; ++componentIdx) {
452 EvalWell resWell_loc(this->primary_variables_.numWellEq() + Indices::numEq, 0.0);
453 if (FluidSystem::numActivePhases() > 1) {
455 resWell_loc += (this->primary_variables_.surfaceVolumeFraction(componentIdx) -
456 this->F0_[componentIdx]) * volume / dt;
458 resWell_loc -= this->primary_variables_.getQs(componentIdx) * this->well_efficiency_factor_;
460 assembleSourceEq(resWell_loc,
462 this->primary_variables_.numWellEq(),
466 const auto& summaryState = simulator.vanguard().summaryState();
467 const Schedule& schedule = simulator.vanguard().schedule();
468 const bool stopped_or_zero_target = this->stoppedOrZeroRateTarget(simulator, well_state, deferred_logger);
470 assembleControlEq(well_state, group_state,
471 schedule, summaryState,
472 inj_controls, prod_controls,
473 this->primary_variables_,
474 this->connections_.rho(),
476 stopped_or_zero_target,
482 this->linSys_.invert();
484 OPM_DEFLOG_PROBLEM(NumericalProblem,
"Error when inverting local well equations for well " + name(), deferred_logger);
491 template<
typename TypeTag>
497 std::vector<RateVector>& connectionRates,
498 std::vector<EvalWell>& cq_s,
503 const bool allow_cf = this->getAllowCrossFlow() || openCrossFlowAvoidSingularity(simulator);
504 const EvalWell& bhp = this->primary_variables_.eval(Bhp);
505 const int cell_idx = this->well_cells_[perf];
506 const auto& intQuants = simulator.model().intensiveQuantities(cell_idx, 0);
507 std::vector<EvalWell> mob(this->num_components_, {this->primary_variables_.numWellEq() + Indices::numEq, 0.});
508 getMobility(simulator, perf, mob, deferred_logger);
511 Scalar trans_mult = simulator.problem().template wellTransMultiplier<Scalar>(intQuants, cell_idx);
512 const auto& wellstate_nupcol = simulator.problem().wellModel().nupcolWellState().well(this->index_of_well_);
513 const std::vector<Scalar> Tw = this->wellIndex(perf, intQuants, trans_mult, wellstate_nupcol);
514 computePerfRate(intQuants, mob, bhp, Tw, perf, allow_cf,
515 cq_s, perf_rates, deferred_logger);
517 auto& ws = well_state.
well(this->index_of_well_);
518 auto& perf_data = ws.perf_data;
519 if constexpr (has_polymer && Base::has_polymermw) {
520 if (this->isInjector()) {
523 const unsigned water_comp_idx = Indices::canonicalToActiveComponentIndex(FluidSystem::waterCompIdx);
524 water_flux_s = cq_s[water_comp_idx];
527 handleInjectivityRate(simulator, perf, cq_s);
532 if (this->isProducer()) {
533 ws.phase_mixing_rates[ws.dissolved_gas] += perf_rates.
dis_gas;
534 ws.phase_mixing_rates[ws.dissolved_gas_in_water] += perf_rates.
dis_gas_in_water;
535 ws.phase_mixing_rates[ws.vaporized_oil] += perf_rates.
vap_oil;
536 ws.phase_mixing_rates[ws.vaporized_water] += perf_rates.
vap_wat;
537 perf_data.phase_mixing_rates[perf][ws.dissolved_gas] = perf_rates.
dis_gas;
538 perf_data.phase_mixing_rates[perf][ws.dissolved_gas_in_water] = perf_rates.
dis_gas_in_water;
539 perf_data.phase_mixing_rates[perf][ws.vaporized_oil] = perf_rates.
vap_oil;
540 perf_data.phase_mixing_rates[perf][ws.vaporized_water] = perf_rates.
vap_wat;
543 if constexpr (has_energy) {
544 connectionRates[perf][Indices::contiEnergyEqIdx] =
545 connectionRateEnergy(simulator.problem().maxOilSaturation(cell_idx),
546 cq_s, intQuants, deferred_logger);
549 if constexpr (has_polymer) {
550 std::variant<Scalar,EvalWell> polymerConcentration;
551 if (this->isInjector()) {
552 polymerConcentration = this->wpolymer();
554 polymerConcentration = this->extendEval(intQuants.polymerConcentration() *
555 intQuants.polymerViscosityCorrection());
558 [[maybe_unused]]
EvalWell cq_s_poly;
559 std::tie(connectionRates[perf][Indices::contiPolymerEqIdx],
561 this->connections_.connectionRatePolymer(perf_data.polymer_rates[perf],
562 cq_s, polymerConcentration);
564 if constexpr (Base::has_polymermw) {
565 updateConnectionRatePolyMW(cq_s_poly, intQuants, well_state,
566 perf, connectionRates, deferred_logger);
570 if constexpr (has_foam) {
571 std::variant<Scalar,EvalWell> foamConcentration;
572 if (this->isInjector()) {
573 foamConcentration = this->wfoam();
575 foamConcentration = this->extendEval(intQuants.foamConcentration());
577 connectionRates[perf][Indices::contiFoamEqIdx] =
578 this->connections_.connectionRateFoam(cq_s, foamConcentration,
579 FoamModule::transportPhase(),
583 if constexpr (has_zFraction) {
584 std::variant<Scalar,std::array<EvalWell,2>> solventConcentration;
585 if (this->isInjector()) {
586 solventConcentration = this->wsolvent();
588 solventConcentration = std::array{this->extendEval(intQuants.xVolume()),
589 this->extendEval(intQuants.yVolume())};
591 std::tie(connectionRates[perf][Indices::contiZfracEqIdx],
592 cq_s_zfrac_effective) =
593 this->connections_.connectionRatezFraction(perf_data.solvent_rates[perf],
595 solventConcentration);
598 if constexpr (has_brine) {
599 std::variant<Scalar,EvalWell> saltConcentration;
600 if (this->isInjector()) {
601 saltConcentration = this->wsalt();
603 saltConcentration = this->extendEval(intQuants.fluidState().saltConcentration());
606 connectionRates[perf][Indices::contiBrineEqIdx] =
607 this->connections_.connectionRateBrine(perf_data.brine_rates[perf],
612 if constexpr (has_micp) {
613 std::variant<Scalar,EvalWell> microbialConcentration;
614 std::variant<Scalar,EvalWell> oxygenConcentration;
615 std::variant<Scalar,EvalWell> ureaConcentration;
616 if (this->isInjector()) {
617 microbialConcentration = this->wmicrobes();
618 oxygenConcentration = this->woxygen();
619 ureaConcentration = this->wurea();
621 microbialConcentration = this->extendEval(intQuants.microbialConcentration());
622 oxygenConcentration = this->extendEval(intQuants.oxygenConcentration());
623 ureaConcentration = this->extendEval(intQuants.ureaConcentration());
625 std::tie(connectionRates[perf][Indices::contiMicrobialEqIdx],
626 connectionRates[perf][Indices::contiOxygenEqIdx],
627 connectionRates[perf][Indices::contiUreaEqIdx]) =
628 this->connections_.connectionRatesMICP(perf_data.microbial_rates[perf],
629 perf_data.oxygen_rates[perf],
630 perf_data.urea_rates[perf],
632 microbialConcentration,
638 perf_data.pressure[perf] = ws.bhp + this->connections_.pressure_diff(perf);
642 if (pu.has_co2_or_h2store) {
643 const unsigned gas_comp_idx = Indices::canonicalToActiveComponentIndex(FluidSystem::gasCompIdx);
644 const Scalar rho = FluidSystem::referenceDensity( FluidSystem::gasPhaseIdx, Base::pvtRegionIdx() );
645 perf_data.gas_mass_rates[perf] = cq_s[gas_comp_idx].value() * rho;
649 if (FluidSystem::phaseIsActive(FluidSystem::waterPhaseIdx)) {
650 const unsigned wat_comp_idx = Indices::canonicalToActiveComponentIndex(FluidSystem::waterCompIdx);
651 const Scalar rho = FluidSystem::referenceDensity( FluidSystem::waterPhaseIdx, Base::pvtRegionIdx() );
652 perf_data.wat_mass_rates[perf] = cq_s[wat_comp_idx].value() * rho;
658 template<
typename TypeTag>
659 template<
class Value>
664 std::vector<Value>& mob,
667 auto obtain = [
this](
const Eval& value)
669 if constexpr (std::is_same_v<Value, Scalar>) {
670 static_cast<void>(
this);
671 return getValue(value);
673 return this->extendEval(value);
677 obtain, deferred_logger);
680 if constexpr (has_polymer) {
681 if (!FluidSystem::phaseIsActive(FluidSystem::waterPhaseIdx)) {
682 OPM_DEFLOG_THROW(std::runtime_error,
"Water is required when polymer is active", deferred_logger);
687 if constexpr (!Base::has_polymermw) {
688 if constexpr (std::is_same_v<Value, Scalar>) {
689 std::vector<EvalWell> mob_eval(this->num_components_, {this->primary_variables_.numWellEq() + Indices::numEq, 0.});
690 for (std::size_t i = 0; i < mob.size(); ++i) {
691 mob_eval[i].setValue(mob[i]);
693 updateWaterMobilityWithPolymer(simulator, perf, mob_eval, deferred_logger);
694 for (std::size_t i = 0; i < mob.size(); ++i) {
695 mob[i] = getValue(mob_eval[i]);
698 updateWaterMobilityWithPolymer(simulator, perf, mob, deferred_logger);
705 const Scalar bhp = this->primary_variables_.value(Bhp);
706 const Scalar perf_press = bhp + this->connections_.pressure_diff(perf);
707 const Scalar multiplier = this->getInjMult(perf, bhp, perf_press, deferred_logger);
708 for (std::size_t i = 0; i < mob.size(); ++i) {
709 mob[i] *= multiplier;
715 template<
typename TypeTag>
723 if (!this->isOperableAndSolvable() && !this->wellIsStopped())
return;
725 const bool stop_or_zero_rate_target = this->stoppedOrZeroRateTarget(simulator, well_state, deferred_logger);
726 updatePrimaryVariablesNewton(dwells, stop_or_zero_rate_target, deferred_logger);
728 const auto& summary_state = simulator.vanguard().summaryState();
729 updateWellStateFromPrimaryVariables(well_state, summary_state, deferred_logger);
730 Base::calculateReservoirRates(simulator.vanguard().eclState().runspec().co2Storage(), well_state.
well(this->index_of_well_));
737 template<
typename TypeTag>
741 const bool stop_or_zero_rate_target,
744 const Scalar dFLimit = this->param_.dwell_fraction_max_;
745 const Scalar dBHPLimit = this->param_.dbhp_max_rel_;
746 this->primary_variables_.updateNewton(dwells, stop_or_zero_rate_target, dFLimit, dBHPLimit, deferred_logger);
749 if constexpr (Base::has_polymermw) {
750 this->primary_variables_.updateNewtonPolyMW(dwells);
753 this->primary_variables_.checkFinite(deferred_logger);
760 template<
typename TypeTag>
764 const SummaryState& summary_state,
767 this->StdWellEval::updateWellStateFromPrimaryVariables(well_state, summary_state, deferred_logger);
770 if constexpr (Base::has_polymermw) {
771 this->primary_variables_.copyToWellStatePolyMW(well_state);
779 template<
typename TypeTag>
787 std::fill(this->ipr_a_.begin(), this->ipr_a_.end(), 0.);
788 std::fill(this->ipr_b_.begin(), this->ipr_b_.end(), 0.);
790 for (
int perf = 0; perf < this->number_of_local_perforations_; ++perf) {
791 std::vector<Scalar> mob(this->num_components_, 0.0);
792 getMobility(simulator, perf, mob, deferred_logger);
794 const int cell_idx = this->well_cells_[perf];
795 const auto& int_quantities = simulator.model().intensiveQuantities(cell_idx, 0);
796 const auto& fs = int_quantities.fluidState();
798 Scalar p_r = this->getPerfCellPressure(fs).value();
801 std::vector<Scalar> b_perf(this->num_components_);
802 for (std::size_t phase = 0; phase < FluidSystem::numPhases; ++phase) {
803 if (!FluidSystem::phaseIsActive(phase)) {
806 const unsigned comp_idx = Indices::canonicalToActiveComponentIndex(FluidSystem::solventComponentIndex(phase));
807 b_perf[comp_idx] = fs.invB(phase).value();
809 if constexpr (has_solvent) {
810 b_perf[Indices::contiSolventEqIdx] = int_quantities.solventInverseFormationVolumeFactor().value();
814 const Scalar h_perf = this->connections_.pressure_diff(perf);
815 const Scalar pressure_diff = p_r - h_perf;
820 if ( (this->isProducer() && pressure_diff < 0.) || (this->isInjector() && pressure_diff > 0.) ) {
821 deferred_logger.
debug(
"CROSSFLOW_IPR",
822 "cross flow found when updateIPR for well " + name()
823 +
" . The connection is ignored in IPR calculations");
829 Scalar trans_mult = simulator.problem().template wellTransMultiplier<Scalar>(int_quantities, cell_idx);
830 const auto& wellstate_nupcol = simulator.problem().wellModel().nupcolWellState().well(this->index_of_well_);
831 const std::vector<Scalar> tw_perf = this->wellIndex(perf,
835 std::vector<Scalar> ipr_a_perf(this->ipr_a_.size());
836 std::vector<Scalar> ipr_b_perf(this->ipr_b_.size());
837 for (
int comp_idx = 0; comp_idx < this->num_components_; ++comp_idx) {
838 const Scalar tw_mob = tw_perf[comp_idx] * mob[comp_idx] * b_perf[comp_idx];
839 ipr_a_perf[comp_idx] += tw_mob * pressure_diff;
840 ipr_b_perf[comp_idx] += tw_mob;
844 if (FluidSystem::phaseIsActive(FluidSystem::oilPhaseIdx) && FluidSystem::phaseIsActive(FluidSystem::gasPhaseIdx)) {
845 const unsigned oil_comp_idx = Indices::canonicalToActiveComponentIndex(FluidSystem::oilCompIdx);
846 const unsigned gas_comp_idx = Indices::canonicalToActiveComponentIndex(FluidSystem::gasCompIdx);
847 const Scalar rs = (fs.Rs()).value();
848 const Scalar rv = (fs.Rv()).value();
850 const Scalar dis_gas_a = rs * ipr_a_perf[oil_comp_idx];
851 const Scalar vap_oil_a = rv * ipr_a_perf[gas_comp_idx];
853 ipr_a_perf[gas_comp_idx] += dis_gas_a;
854 ipr_a_perf[oil_comp_idx] += vap_oil_a;
856 const Scalar dis_gas_b = rs * ipr_b_perf[oil_comp_idx];
857 const Scalar vap_oil_b = rv * ipr_b_perf[gas_comp_idx];
859 ipr_b_perf[gas_comp_idx] += dis_gas_b;
860 ipr_b_perf[oil_comp_idx] += vap_oil_b;
863 for (std::size_t comp_idx = 0; comp_idx < ipr_a_perf.size(); ++comp_idx) {
864 this->ipr_a_[comp_idx] += ipr_a_perf[comp_idx];
865 this->ipr_b_[comp_idx] += ipr_b_perf[comp_idx];
868 this->parallel_well_info_.communication().sum(this->ipr_a_.data(), this->ipr_a_.size());
869 this->parallel_well_info_.communication().sum(this->ipr_b_.data(), this->ipr_b_.size());
872 template<
typename TypeTag>
886 auto rates = well_state.
well(this->index_of_well_).surface_rates;
888 for (std::size_t p = 0; p < rates.size(); ++p) {
889 zero_rates &= rates[p] == 0.0;
891 auto& ws = well_state.
well(this->index_of_well_);
893 const auto msg = fmt::format(
"updateIPRImplicit: Well {} has zero rate, IPRs might be problematic", this->name());
894 deferred_logger.
debug(msg);
906 const auto& group_state = simulator.problem().wellModel().groupState();
908 std::fill(ws.implicit_ipr_a.begin(), ws.implicit_ipr_a.end(), 0.);
909 std::fill(ws.implicit_ipr_b.begin(), ws.implicit_ipr_b.end(), 0.);
911 auto inj_controls = Well::InjectionControls(0);
912 auto prod_controls = Well::ProductionControls(0);
913 prod_controls.addControl(Well::ProducerCMode::BHP);
914 prod_controls.bhp_limit = well_state.
well(this->index_of_well_).bhp;
917 const auto cmode = ws.production_cmode;
918 ws.production_cmode = Well::ProducerCMode::BHP;
919 const double dt = simulator.timeStepSize();
920 assembleWellEqWithoutIteration(simulator, dt, inj_controls, prod_controls, well_state, group_state, deferred_logger);
922 const size_t nEq = this->primary_variables_.numWellEq();
926 for (
size_t i=0; i < nEq; ++i){
932 x_well[0].resize(nEq);
933 this->linSys_.solve(rhs, x_well);
935 for (
int comp_idx = 0; comp_idx < this->num_components_; ++comp_idx){
936 EvalWell comp_rate = this->primary_variables_.getQs(comp_idx);
937 const int idx = this->modelCompIdxToFlowCompIdx(comp_idx);
938 for (
size_t pvIdx = 0; pvIdx < nEq; ++pvIdx) {
940 ws.implicit_ipr_b[idx] -= x_well[0][pvIdx]*comp_rate.derivative(pvIdx+Indices::numEq);
942 ws.implicit_ipr_a[idx] = ws.implicit_ipr_b[idx]*ws.bhp - comp_rate.value();
945 ws.production_cmode = cmode;
948 template<
typename TypeTag>
955 const auto& summaryState = simulator.vanguard().summaryState();
959 const bool bhp_limit_not_defaulted = bhp_limit > 1.5 * unit::barsa;
960 if ( bhp_limit_not_defaulted || !this->wellHasTHPConstraints(summaryState) ) {
963 Scalar total_ipr_mass_rate = 0.0;
964 for (
unsigned phaseIdx = 0; phaseIdx < FluidSystem::numPhases; ++phaseIdx)
966 if (!FluidSystem::phaseIsActive(phaseIdx)) {
970 const unsigned compIdx = Indices::canonicalToActiveComponentIndex(FluidSystem::solventComponentIndex(phaseIdx));
971 const Scalar ipr_rate = this->ipr_a_[compIdx] - this->ipr_b_[compIdx] * bhp_limit;
973 const Scalar rho = FluidSystem::referenceDensity( phaseIdx, Base::pvtRegionIdx() );
974 total_ipr_mass_rate += ipr_rate * rho;
976 if ( (this->isProducer() && total_ipr_mass_rate < 0.) || (this->isInjector() && total_ipr_mass_rate > 0.) ) {
977 this->operability_status_.operable_under_only_bhp_limit =
false;
981 if (this->operability_status_.operable_under_only_bhp_limit && this->wellHasTHPConstraints(summaryState)) {
985 std::vector<Scalar> well_rates_bhp_limit;
986 computeWellRatesWithBhp(simulator, bhp_limit, well_rates_bhp_limit, deferred_logger);
988 this->adaptRatesForVFP(well_rates_bhp_limit);
989 const Scalar thp_limit = this->getTHPConstraint(summaryState);
992 this->connections_.rho(),
993 this->getALQ(well_state),
996 if ( (this->isProducer() && thp < thp_limit) || (this->isInjector() && thp > thp_limit) ) {
997 this->operability_status_.obey_thp_limit_under_bhp_limit =
false;
1008 this->operability_status_.operable_under_only_bhp_limit =
true;
1009 this->operability_status_.obey_thp_limit_under_bhp_limit =
false;
1017 template<
typename TypeTag>
1024 const auto& summaryState = simulator.vanguard().summaryState();
1025 const auto obtain_bhp = this->isProducer() ? computeBhpAtThpLimitProd(well_state, simulator, summaryState, deferred_logger)
1026 : computeBhpAtThpLimitInj(simulator, summaryState, deferred_logger);
1029 this->operability_status_.can_obtain_bhp_with_thp_limit =
true;
1032 this->operability_status_.obey_bhp_limit_with_thp_limit = this->isProducer() ?
1033 *obtain_bhp >= bhp_limit : *obtain_bhp <= bhp_limit ;
1035 const Scalar thp_limit = this->getTHPConstraint(summaryState);
1036 if (this->isProducer() && *obtain_bhp < thp_limit) {
1037 const std::string msg =
" obtained bhp " +
std::to_string(unit::convert::to(*obtain_bhp, unit::barsa))
1038 +
" bars is SMALLER than thp limit "
1040 +
" bars as a producer for well " + name();
1041 deferred_logger.
debug(msg);
1043 else if (this->isInjector() && *obtain_bhp > thp_limit) {
1044 const std::string msg =
" obtained bhp " +
std::to_string(unit::convert::to(*obtain_bhp, unit::barsa))
1045 +
" bars is LARGER than thp limit "
1047 +
" bars as a injector for well " + name();
1048 deferred_logger.
debug(msg);
1051 this->operability_status_.can_obtain_bhp_with_thp_limit =
false;
1052 this->operability_status_.obey_bhp_limit_with_thp_limit =
false;
1053 if (!this->wellIsStopped()) {
1054 const Scalar thp_limit = this->getTHPConstraint(summaryState);
1055 deferred_logger.
debug(
" could not find bhp value at thp limit "
1057 +
" bar for well " + name() +
", the well might need to be closed ");
1066 template<
typename TypeTag>
1071 bool all_drawdown_wrong_direction =
true;
1073 for (
int perf = 0; perf < this->number_of_local_perforations_; ++perf) {
1074 const int cell_idx = this->well_cells_[perf];
1075 const auto& intQuants = simulator.model().intensiveQuantities(cell_idx, 0);
1076 const auto& fs = intQuants.fluidState();
1078 const Scalar pressure = this->getPerfCellPressure(fs).value();
1079 const Scalar bhp = this->primary_variables_.eval(Bhp).value();
1082 const Scalar well_pressure = bhp + this->connections_.pressure_diff(perf);
1083 const Scalar drawdown = pressure - well_pressure;
1088 if ( (drawdown < 0. && this->isInjector()) ||
1089 (drawdown > 0. && this->isProducer()) ) {
1090 all_drawdown_wrong_direction =
false;
1095 const auto& comm = this->parallel_well_info_.communication();
1096 if (comm.size() > 1)
1098 all_drawdown_wrong_direction =
1099 (comm.min(all_drawdown_wrong_direction ? 1 : 0) == 1);
1102 return all_drawdown_wrong_direction;
1108 template<
typename TypeTag>
1113 return !this->getAllowCrossFlow() && allDrawDownWrongDirection(simulator);
1119 template<
typename TypeTag>
1125 auto prop_func =
typename StdWellEval::StdWellConnections::PressurePropertyFunctions {
1127 [&model = simulator.model()](
int cell_idx,
int phase_idx)
1129 return model.intensiveQuantities(cell_idx, 0)
1130 .fluidState().temperature(phase_idx).value();
1134 [&model = simulator.model()](
int cell_idx)
1136 return model.intensiveQuantities(cell_idx, 0)
1137 .fluidState().saltConcentration().value();
1141 [&model = simulator.model()](
int cell_idx)
1143 return model.intensiveQuantities(cell_idx, 0)
1144 .fluidState().pvtRegionIndex();
1148 if constexpr (Indices::enableSolvent) {
1149 prop_func.solventInverseFormationVolumeFactor =
1150 [&model = simulator.model()](
int cell_idx)
1152 return model.intensiveQuantities(cell_idx, 0)
1153 .solventInverseFormationVolumeFactor().value();
1156 prop_func.solventRefDensity = [&model = simulator.model()](
int cell_idx)
1158 return model.intensiveQuantities(cell_idx, 0)
1159 .solventRefDensity();
1163 return this->connections_.computePropertiesForPressures(well_state, prop_func);
1170 template<
typename TypeTag>
1175 const std::vector<Scalar>& B_avg,
1177 const bool relax_tolerance)
const
1181 assert((
int(B_avg.size()) == this->num_components_) || has_polymer || has_energy || has_foam || has_brine || has_zFraction || has_micp);
1183 Scalar tol_wells = this->param_.tolerance_wells_;
1185 constexpr Scalar stopped_factor = 1.e-4;
1187 constexpr Scalar dynamic_thp_factor = 1.e-1;
1188 if (this->stoppedOrZeroRateTarget(simulator, well_state, deferred_logger)) {
1189 tol_wells = tol_wells*stopped_factor;
1190 }
else if (this->getDynamicThpLimit()) {
1191 tol_wells = tol_wells*dynamic_thp_factor;
1194 std::vector<Scalar> res;
1197 this->param_.max_residual_allowed_,
1199 this->param_.relaxed_tolerance_flow_well_,
1201 this->wellIsStopped(),
1205 checkConvergenceExtraEqs(res, report);
1214 template<
typename TypeTag>
1222 auto fluidState = [&simulator,
this](
const int perf)
1224 const auto cell_idx = this->well_cells_[perf];
1225 return simulator.model()
1226 .intensiveQuantities(cell_idx, 0).fluidState();
1229 const int np = this->number_of_phases_;
1230 auto setToZero = [np](
Scalar* x) ->
void
1232 std::fill_n(x, np, 0.0);
1235 auto addVector = [np](
const Scalar* src,
Scalar* dest) ->
void
1237 std::transform(src, src + np, dest, dest, std::plus<>{});
1240 auto& ws = well_state.
well(this->index_of_well_);
1241 auto& perf_data = ws.perf_data;
1242 auto* wellPI = ws.productivity_index.data();
1243 auto* connPI = perf_data.prod_index.data();
1247 const auto preferred_phase = this->well_ecl_.getPreferredPhase();
1248 auto subsetPerfID = 0;
1250 for (
const auto& perf : *this->perf_data_) {
1251 auto allPerfID = perf.ecl_index;
1253 auto connPICalc = [&wellPICalc, allPerfID](
const Scalar mobility) ->
Scalar
1258 std::vector<Scalar> mob(this->num_components_, 0.0);
1259 getMobility(simulator,
static_cast<int>(subsetPerfID), mob, deferred_logger);
1261 const auto& fs = fluidState(subsetPerfID);
1264 if (this->isInjector()) {
1265 this->computeConnLevelInjInd(fs, preferred_phase, connPICalc,
1266 mob, connPI, deferred_logger);
1269 this->computeConnLevelProdInd(fs, connPICalc, mob, connPI);
1272 addVector(connPI, wellPI);
1279 const auto& comm = this->parallel_well_info_.communication();
1280 if (comm.size() > 1) {
1281 comm.sum(wellPI, np);
1284 assert ((
static_cast<int>(subsetPerfID) == this->number_of_local_perforations_) &&
1285 "Internal logic error in processing connections for PI/II");
1290 template<
typename TypeTag>
1300 const auto prop_func =
typename StdWellEval::StdWellConnections::DensityPropertyFunctions {
1305 [&model = simulator.model()](
const int cell,
1306 const std::vector<int>& phases,
1307 std::vector<Scalar>& mob)
1309 const auto& iq = model.intensiveQuantities(cell, 0);
1311 std::transform(phases.begin(), phases.end(), mob.begin(),
1312 [&iq](
const int phase) { return iq.mobility(phase).value(); });
1317 [&model = simulator.model()](
const int cell,
1318 const std::vector<int>& phases,
1319 std::vector<Scalar>& rho)
1321 const auto& fs = model.intensiveQuantities(cell, 0).fluidState();
1323 std::transform(phases.begin(), phases.end(), rho.begin(),
1324 [&fs](
const int phase) { return fs.density(phase).value(); });
1328 const auto stopped_or_zero_rate_target = this->
1329 stoppedOrZeroRateTarget(simulator, well_state, deferred_logger);
1332 .computeProperties(stopped_or_zero_rate_target, well_state,
1333 prop_func, props, deferred_logger);
1340 template<
typename TypeTag>
1347 const auto props = computePropertiesForWellConnectionPressures
1348 (simulator, well_state);
1350 computeWellConnectionDensitesPressures(simulator, well_state,
1351 props, deferred_logger);
1358 template<
typename TypeTag>
1365 if (!this->isOperableAndSolvable() && !this->wellIsStopped())
return;
1370 dx_well[0].resize(this->primary_variables_.numWellEq());
1371 this->linSys_.solve( dx_well);
1373 updateWellState(simulator, dx_well, well_state, deferred_logger);
1380 template<
typename TypeTag>
1387 updatePrimaryVariables(simulator, well_state, deferred_logger);
1388 computeWellConnectionPressures(simulator, well_state, deferred_logger);
1389 this->computeAccumWell();
1394 template<
typename TypeTag>
1399 if (!this->isOperableAndSolvable() && !this->wellIsStopped())
return;
1401 if (this->param_.matrix_add_well_contributions_)
1407 this->linSys_.apply(x, Ax);
1413 template<
typename TypeTag>
1418 if (!this->isOperableAndSolvable() && !this->wellIsStopped())
return;
1420 this->linSys_.apply(r);
1426 template<
typename TypeTag>
1434 if (!this->isOperableAndSolvable() && !this->wellIsStopped())
return;
1437 xw[0].resize(this->primary_variables_.numWellEq());
1439 this->linSys_.recoverSolutionWell(x, xw);
1440 updateWellState(simulator, xw, well_state, deferred_logger);
1446 template<
typename TypeTag>
1451 std::vector<Scalar>& well_flux,
1455 const int np = this->number_of_phases_;
1456 well_flux.resize(np, 0.0);
1458 const bool allow_cf = this->getAllowCrossFlow();
1460 for (
int perf = 0; perf < this->number_of_local_perforations_; ++perf) {
1461 const int cell_idx = this->well_cells_[perf];
1462 const auto& intQuants = simulator.model().intensiveQuantities(cell_idx, 0);
1464 std::vector<Scalar> mob(this->num_components_, 0.);
1465 getMobility(simulator, perf, mob, deferred_logger);
1466 Scalar trans_mult = simulator.problem().template wellTransMultiplier<Scalar>(intQuants, cell_idx);
1467 const auto& wellstate_nupcol = simulator.problem().wellModel().nupcolWellState().well(this->index_of_well_);
1468 const std::vector<Scalar> Tw = this->wellIndex(perf, intQuants, trans_mult, wellstate_nupcol);
1470 std::vector<Scalar> cq_s(this->num_components_, 0.);
1472 computePerfRate(intQuants, mob, bhp, Tw, perf, allow_cf,
1473 cq_s, perf_rates, deferred_logger);
1475 for(
int p = 0; p < np; ++p) {
1476 well_flux[this->modelCompIdxToFlowCompIdx(p)] += cq_s[p];
1480 if constexpr (has_solvent) {
1482 assert(pu.phase_used[Gas]);
1483 const int gas_pos = pu.phase_pos[Gas];
1484 well_flux[gas_pos] += cq_s[Indices::contiSolventEqIdx];
1487 this->parallel_well_info_.communication().sum(well_flux.data(), well_flux.size());
1492 template<
typename TypeTag>
1497 std::vector<Scalar>& well_flux,
1508 WellState<Scalar> well_state_copy = simulator.problem().wellModel().wellState();
1509 const auto& group_state = simulator.problem().wellModel().groupState();
1512 const auto& summary_state = simulator.vanguard().summaryState();
1513 auto inj_controls = well_copy.
well_ecl_.isInjector()
1514 ? well_copy.
well_ecl_.injectionControls(summary_state)
1515 : Well::InjectionControls(0);
1516 auto prod_controls = well_copy.
well_ecl_.isProducer()
1517 ? well_copy.
well_ecl_.productionControls(summary_state) :
1518 Well::ProductionControls(0);
1521 auto& ws = well_state_copy.
well(this->index_of_well_);
1523 inj_controls.bhp_limit = bhp;
1524 ws.injection_cmode = Well::InjectorCMode::BHP;
1526 prod_controls.bhp_limit = bhp;
1527 ws.production_cmode = Well::ProducerCMode::BHP;
1532 const int np = this->number_of_phases_;
1533 const Scalar sign = this->well_ecl_.isInjector() ? 1.0 : -1.0;
1534 for (
int phase = 0; phase < np; ++phase){
1535 well_state_copy.
wellRates(this->index_of_well_)[phase]
1536 = sign * ws.well_potentials[phase];
1541 const double dt = simulator.timeStepSize();
1542 const bool converged = well_copy.
iterateWellEqWithControl(simulator, dt, inj_controls, prod_controls, well_state_copy, group_state, deferred_logger);
1544 const std::string msg =
" well " + name() +
" did not get converged during well potential calculations "
1545 " potentials are computed based on unconverged solution";
1546 deferred_logger.
debug(msg);
1556 template<
typename TypeTag>
1557 std::vector<typename StandardWell<TypeTag>::Scalar>
1563 std::vector<Scalar> potentials(this->number_of_phases_, 0.0);
1564 const auto& summary_state = simulator.vanguard().summaryState();
1566 const auto& well = this->well_ecl_;
1567 if (well.isInjector()){
1568 const auto& controls = this->well_ecl_.injectionControls(summary_state);
1569 auto bhp_at_thp_limit = computeBhpAtThpLimitInj(simulator, summary_state, deferred_logger);
1570 if (bhp_at_thp_limit) {
1571 const Scalar bhp = std::min(*bhp_at_thp_limit,
1572 static_cast<Scalar>(controls.bhp_limit));
1573 computeWellRatesWithBhp(simulator, bhp, potentials, deferred_logger);
1575 deferred_logger.
warning(
"FAILURE_GETTING_CONVERGED_POTENTIAL",
1576 "Failed in getting converged thp based potential calculation for well "
1577 + name() +
". Instead the bhp based value is used");
1578 const Scalar bhp = controls.bhp_limit;
1579 computeWellRatesWithBhp(simulator, bhp, potentials, deferred_logger);
1582 computeWellRatesWithThpAlqProd(
1583 simulator, summary_state,
1584 deferred_logger, potentials, this->getALQ(well_state)
1591 template<
typename TypeTag>
1596 std::vector<Scalar>& well_potentials,
1606 const auto& group_state = simulator.problem().wellModel().groupState();
1607 auto& ws = well_state_copy.
well(this->index_of_well_);
1610 const auto& summary_state = simulator.vanguard().summaryState();
1611 auto inj_controls = well_copy.
well_ecl_.isInjector()
1612 ? well_copy.
well_ecl_.injectionControls(summary_state)
1613 : Well::InjectionControls(0);
1614 auto prod_controls = well_copy.
well_ecl_.isProducer()
1615 ? well_copy.
well_ecl_.productionControls(summary_state) :
1616 Well::ProductionControls(0);
1622 const int num_perf = ws.perf_data.size();
1623 for (
int perf = 0; perf < num_perf; ++perf) {
1627 const int np = this->number_of_phases_;
1628 bool trivial =
true;
1629 for (
int phase = 0; phase < np; ++phase){
1630 trivial = trivial && (ws.well_potentials[phase] == 0.0) ;
1634 for (
int phase = 0; phase < np; ++phase) {
1635 ws.surface_rates[phase] = sign * ws.well_potentials[phase];
1640 const double dt = simulator.timeStepSize();
1642 bool converged =
false;
1643 if (this->well_ecl_.isProducer()) {
1644 converged = well_copy.
solveWellWithOperabilityCheck(simulator, dt, inj_controls, prod_controls, well_state_copy, group_state, deferred_logger);
1646 converged = well_copy.
iterateWellEqWithSwitching(simulator, dt, inj_controls, prod_controls, well_state_copy, group_state, deferred_logger);
1650 well_potentials.clear();
1651 well_potentials.resize(np, 0.0);
1652 for (
int comp_idx = 0; comp_idx < this->num_components_; ++comp_idx) {
1653 if (has_solvent && comp_idx == Indices::contiSolventEqIdx)
continue;
1655 well_potentials[this->modelCompIdxToFlowCompIdx(comp_idx)] = rate.value();
1659 if constexpr (has_solvent) {
1661 assert(pu.phase_used[Gas]);
1662 const int gas_pos = pu.phase_pos[Gas];
1664 well_potentials[gas_pos] += rate.value();
1670 template<
typename TypeTag>
1674 const SummaryState &summary_state,
1676 std::vector<Scalar>& potentials,
1680 auto bhp_at_thp_limit = computeBhpAtThpLimitProdWithAlq(
1681 simulator, summary_state, alq, deferred_logger,
true);
1682 if (bhp_at_thp_limit) {
1683 const auto& controls = this->well_ecl_.productionControls(summary_state);
1684 bhp = std::max(*bhp_at_thp_limit,
1685 static_cast<Scalar>(controls.bhp_limit));
1686 computeWellRatesWithBhp(simulator, bhp, potentials, deferred_logger);
1689 deferred_logger.
warning(
"FAILURE_GETTING_CONVERGED_POTENTIAL",
1690 "Failed in getting converged thp based potential calculation for well "
1691 + name() +
". Instead the bhp based value is used");
1692 const auto& controls = this->well_ecl_.productionControls(summary_state);
1693 bhp = controls.bhp_limit;
1694 computeWellRatesWithBhp(simulator, bhp, potentials, deferred_logger);
1699 template<
typename TypeTag>
1703 const SummaryState& summary_state,
1705 std::vector<Scalar>& potentials,
1709 computeWellRatesAndBhpWithThpAlqProd(simulator,
1716 template<
typename TypeTag>
1721 std::vector<Scalar>& well_potentials,
1724 const auto [compute_potential, bhp_controlled_well] =
1727 if (!compute_potential) {
1731 bool converged_implicit =
false;
1735 if (this->param_.local_well_solver_control_switching_ && !(this->changed_to_open_this_step_ && this->wellUnderZeroRateTarget(simulator, well_state, deferred_logger))) {
1736 converged_implicit = computeWellPotentialsImplicit(simulator, well_state, well_potentials, deferred_logger);
1738 if (!converged_implicit) {
1740 const auto& summaryState = simulator.vanguard().summaryState();
1741 if (!Base::wellHasTHPConstraints(summaryState) || bhp_controlled_well) {
1751 const auto& ws = well_state.
well(this->index_of_well_);
1752 if (this->isInjector())
1753 bhp = std::max(ws.bhp, bhp);
1755 bhp = std::min(ws.bhp, bhp);
1757 assert(std::abs(bhp) != std::numeric_limits<Scalar>::max());
1758 computeWellRatesWithBhpIterations(simulator, bhp, well_potentials, deferred_logger);
1761 well_potentials = computeWellPotentialWithTHP(simulator, deferred_logger, well_state);
1765 this->checkNegativeWellPotentials(well_potentials,
1766 this->param_.check_well_operability_,
1776 template<
typename TypeTag>
1780 const int openConnIdx)
const
1782 return (openConnIdx < 0)
1784 : this->connections_.rho(openConnIdx);
1791 template<
typename TypeTag>
1798 if (!this->isOperableAndSolvable() && !this->wellIsStopped())
return;
1800 const bool stop_or_zero_rate_target = this->stoppedOrZeroRateTarget(simulator, well_state, deferred_logger);
1801 this->primary_variables_.update(well_state, stop_or_zero_rate_target, deferred_logger);
1804 if constexpr (Base::has_polymermw) {
1805 this->primary_variables_.updatePolyMW(well_state);
1808 this->primary_variables_.checkFinite(deferred_logger);
1814 template<
typename TypeTag>
1819 return this->connections_.rho();
1825 template<
typename TypeTag>
1830 std::vector<EvalWell>& mob,
1833 const int cell_idx = this->well_cells_[perf];
1834 const auto& int_quant = simulator.model().intensiveQuantities(cell_idx, 0);
1835 const EvalWell polymer_concentration = this->extendEval(int_quant.polymerConcentration());
1839 if (this->isInjector()) {
1841 const auto& visc_mult_table = PolymerModule::plyviscViscosityMultiplierTable(int_quant.pvtRegionIndex());
1842 const unsigned waterCompIdx = Indices::canonicalToActiveComponentIndex(FluidSystem::waterCompIdx);
1843 mob[waterCompIdx] /= (this->extendEval(int_quant.waterViscosityCorrection()) * visc_mult_table.eval(polymer_concentration,
true) );
1846 if (PolymerModule::hasPlyshlog()) {
1849 if (this->isInjector() && this->wpolymer() == 0.) {
1854 const bool allow_cf = this->getAllowCrossFlow() || openCrossFlowAvoidSingularity(simulator);
1855 const EvalWell& bhp = this->primary_variables_.eval(Bhp);
1857 std::vector<EvalWell> cq_s(this->num_components_, {this->primary_variables_.numWellEq() + Indices::numEq, 0.});
1859 Scalar trans_mult = simulator.problem().template wellTransMultiplier<Scalar>(int_quant, cell_idx);
1860 const auto& wellstate_nupcol = simulator.problem().wellModel().nupcolWellState().well(this->index_of_well_);
1861 const std::vector<Scalar> Tw = this->wellIndex(perf, int_quant, trans_mult, wellstate_nupcol);
1862 computePerfRate(int_quant, mob, bhp, Tw, perf, allow_cf, cq_s,
1863 perf_rates, deferred_logger);
1865 const Scalar area = 2 * M_PI * this->perf_rep_radius_[perf] * this->perf_length_[perf];
1866 const auto& material_law_manager = simulator.problem().materialLawManager();
1867 const auto& scaled_drainage_info =
1868 material_law_manager->oilWaterScaledEpsInfoDrainage(cell_idx);
1869 const Scalar swcr = scaled_drainage_info.Swcr;
1870 const EvalWell poro = this->extendEval(int_quant.porosity());
1871 const EvalWell sw = this->extendEval(int_quant.fluidState().saturation(FluidSystem::waterPhaseIdx));
1873 const EvalWell denom = max( (area * poro * (sw - swcr)), 1e-12);
1874 const unsigned waterCompIdx = Indices::canonicalToActiveComponentIndex(FluidSystem::waterCompIdx);
1875 EvalWell water_velocity = cq_s[waterCompIdx] / denom * this->extendEval(int_quant.fluidState().invB(FluidSystem::waterPhaseIdx));
1877 if (PolymerModule::hasShrate()) {
1880 water_velocity *= PolymerModule::shrate( int_quant.pvtRegionIndex() ) / this->bore_diameters_[perf];
1882 const EvalWell shear_factor = PolymerModule::computeShearFactor(polymer_concentration,
1883 int_quant.pvtRegionIndex(),
1886 mob[waterCompIdx] /= shear_factor;
1890 template<
typename TypeTag>
1894 this->linSys_.extract(jacobian);
1898 template <
typename TypeTag>
1902 const int pressureVarIndex,
1903 const bool use_well_weights,
1906 this->linSys_.extractCPRPressureMatrix(jacobian,
1917 template<
typename TypeTag>
1924 if constexpr (Base::has_polymermw) {
1925 const int water_table_id = this->polymerWaterTable_();
1926 if (water_table_id <= 0) {
1928 fmt::format(
"Unused SKPRWAT table id used for well {}", name()),
1931 const auto& water_table_func = PolymerModule::getSkprwatTable(water_table_id);
1932 const EvalWell throughput_eval(this->primary_variables_.numWellEq() + Indices::numEq, throughput);
1934 EvalWell pskin_water(this->primary_variables_.numWellEq() + Indices::numEq, 0.0);
1935 pskin_water = water_table_func.eval(throughput_eval, water_velocity);
1939 fmt::format(
"Polymermw is not activated, while injecting "
1940 "skin pressure is requested for well {}", name()),
1949 template<
typename TypeTag>
1957 if constexpr (Base::has_polymermw) {
1958 const Scalar sign = water_velocity >= 0. ? 1.0 : -1.0;
1959 const EvalWell water_velocity_abs = abs(water_velocity);
1960 if (poly_inj_conc == 0.) {
1961 return sign * pskinwater(throughput, water_velocity_abs, deferred_logger);
1963 const int polymer_table_id = this->polymerTable_();
1964 if (polymer_table_id <= 0) {
1966 fmt::format(
"Unavailable SKPRPOLY table id used for well {}", name()),
1969 const auto& skprpolytable = PolymerModule::getSkprpolyTable(polymer_table_id);
1970 const Scalar reference_concentration = skprpolytable.refConcentration;
1971 const EvalWell throughput_eval(this->primary_variables_.numWellEq() + Indices::numEq, throughput);
1973 EvalWell pskin_poly(this->primary_variables_.numWellEq() + Indices::numEq, 0.0);
1974 pskin_poly = skprpolytable.table_func.eval(throughput_eval, water_velocity_abs);
1975 if (poly_inj_conc == reference_concentration) {
1976 return sign * pskin_poly;
1979 const EvalWell pskin_water = pskinwater(throughput, water_velocity_abs, deferred_logger);
1980 const EvalWell pskin = pskin_water + (pskin_poly - pskin_water) / reference_concentration * poly_inj_conc;
1981 return sign * pskin;
1984 fmt::format(
"Polymermw is not activated, while injecting "
1985 "skin pressure is requested for well {}", name()),
1994 template<
typename TypeTag>
2001 if constexpr (Base::has_polymermw) {
2002 const int table_id = this->polymerInjTable_();
2003 const auto& table_func = PolymerModule::getPlymwinjTable(table_id);
2004 const EvalWell throughput_eval(this->primary_variables_.numWellEq() + Indices::numEq, throughput);
2005 EvalWell molecular_weight(this->primary_variables_.numWellEq() + Indices::numEq, 0.);
2006 if (this->wpolymer() == 0.) {
2007 return molecular_weight;
2009 molecular_weight = table_func.eval(throughput_eval, abs(water_velocity));
2010 return molecular_weight;
2013 fmt::format(
"Polymermw is not activated, while injecting "
2014 "polymer molecular weight is requested for well {}", name()),
2023 template<
typename TypeTag>
2029 if constexpr (Base::has_polymermw) {
2030 if (!this->isInjector()) {
2034 auto& perf_water_throughput = well_state.
well(this->index_of_well_)
2035 .perf_data.water_throughput;
2037 for (
int perf = 0; perf < this->number_of_local_perforations_; ++perf) {
2038 const Scalar perf_water_vel =
2039 this->primary_variables_.value(Bhp + 1 + perf);
2043 if (perf_water_vel >
Scalar{0}) {
2044 perf_water_throughput[perf] += perf_water_vel * dt;
2054 template<
typename TypeTag>
2059 std::vector<EvalWell>& cq_s)
const
2061 const int cell_idx = this->well_cells_[perf];
2062 const auto& int_quants = simulator.model().intensiveQuantities(cell_idx, 0);
2063 const auto& fs = int_quants.fluidState();
2064 const EvalWell b_w = this->extendEval(fs.invB(FluidSystem::waterPhaseIdx));
2065 const Scalar area = M_PI * this->bore_diameters_[perf] * this->perf_length_[perf];
2066 const int wat_vel_index = Bhp + 1 + perf;
2067 const unsigned water_comp_idx = Indices::canonicalToActiveComponentIndex(FluidSystem::waterCompIdx);
2071 cq_s[water_comp_idx] = area * this->primary_variables_.eval(wat_vel_index) * b_w;
2077 template<
typename TypeTag>
2086 const int cell_idx = this->well_cells_[perf];
2087 const auto& int_quants = simulator.model().intensiveQuantities(cell_idx, 0);
2088 const auto& fs = int_quants.fluidState();
2089 const EvalWell b_w = this->extendEval(fs.invB(FluidSystem::waterPhaseIdx));
2090 const EvalWell water_flux_r = water_flux_s / b_w;
2091 const Scalar area = M_PI * this->bore_diameters_[perf] * this->perf_length_[perf];
2092 const EvalWell water_velocity = water_flux_r / area;
2093 const int wat_vel_index = Bhp + 1 + perf;
2096 const EvalWell eq_wat_vel = this->primary_variables_.eval(wat_vel_index) - water_velocity;
2098 const auto& ws = well_state.
well(this->index_of_well_);
2099 const auto& perf_data = ws.perf_data;
2100 const auto& perf_water_throughput = perf_data.water_throughput;
2101 const Scalar throughput = perf_water_throughput[perf];
2102 const int pskin_index = Bhp + 1 + this->number_of_local_perforations_ + perf;
2104 EvalWell poly_conc(this->primary_variables_.numWellEq() + Indices::numEq, 0.0);
2105 poly_conc.setValue(this->wpolymer());
2108 const EvalWell eq_pskin = this->primary_variables_.eval(pskin_index)
2109 - pskin(throughput, this->primary_variables_.eval(wat_vel_index), poly_conc, deferred_logger);
2112 assembleInjectivityEq(eq_pskin,
2117 this->primary_variables_.numWellEq(),
2125 template<
typename TypeTag>
2134 if constexpr (Base::has_polymermw) {
2136 checkConvergencePolyMW(res, Bhp, this->param_.max_residual_allowed_, report);
2144 template<
typename TypeTag>
2151 std::vector<RateVector>& connectionRates,
2156 if (this->isInjector()) {
2157 const int wat_vel_index = Bhp + 1 + perf;
2158 const EvalWell water_velocity = this->primary_variables_.eval(wat_vel_index);
2159 if (water_velocity > 0.) {
2160 const auto& ws = well_state.
well(this->index_of_well_);
2161 const auto& perf_water_throughput = ws.perf_data.water_throughput;
2162 const Scalar throughput = perf_water_throughput[perf];
2163 const EvalWell molecular_weight = wpolymermw(throughput, water_velocity, deferred_logger);
2164 cq_s_polymw *= molecular_weight;
2170 }
else if (this->isProducer()) {
2171 if (cq_s_polymw < 0.) {
2172 cq_s_polymw *= this->extendEval(int_quants.polymerMoleWeight() );
2179 connectionRates[perf][Indices::contiPolymerMWEqIdx] = Base::restrictEval(cq_s_polymw);
2187 template<
typename TypeTag>
2188 std::optional<typename StandardWell<TypeTag>::Scalar>
2192 const SummaryState& summary_state,
2195 return computeBhpAtThpLimitProdWithAlq(simulator,
2197 this->getALQ(well_state),
2202 template<
typename TypeTag>
2203 std::optional<typename StandardWell<TypeTag>::Scalar>
2206 const SummaryState& summary_state,
2209 bool iterate_if_no_solution)
const
2213 auto frates = [
this, &simulator, &deferred_logger](
const Scalar bhp) {
2219 std::vector<Scalar> rates(3);
2220 computeWellRatesWithBhp(simulator, bhp, rates, deferred_logger);
2221 this->adaptRatesForVFP(rates);
2225 Scalar max_pressure = 0.0;
2226 for (
int perf = 0; perf < this->number_of_local_perforations_; ++perf) {
2227 const int cell_idx = this->well_cells_[perf];
2228 const auto& int_quants = simulator.model().intensiveQuantities(cell_idx, 0);
2229 const auto& fs = int_quants.fluidState();
2230 Scalar pressure_cell = this->getPerfCellPressure(fs).value();
2231 max_pressure = std::max(max_pressure, pressure_cell);
2236 this->connections_.rho(),
2238 this->getTHPConstraint(summary_state),
2242 auto v = frates(*bhpAtLimit);
2243 if (std::all_of(v.cbegin(), v.cend(), [](
Scalar i){ return i <= 0; }) ) {
2248 if (!iterate_if_no_solution)
2249 return std::nullopt;
2251 auto fratesIter = [
this, &simulator, &deferred_logger](
const Scalar bhp) {
2255 std::vector<Scalar> rates(3);
2256 computeWellRatesWithBhpIterations(simulator, bhp, rates, deferred_logger);
2257 this->adaptRatesForVFP(rates);
2264 this->connections_.rho(),
2266 this->getTHPConstraint(summary_state),
2272 auto v = frates(*bhpAtLimit);
2273 if (std::all_of(v.cbegin(), v.cend(), [](
Scalar i){ return i <= 0; }) ) {
2279 return std::nullopt;
2284 template<
typename TypeTag>
2285 std::optional<typename StandardWell<TypeTag>::Scalar>
2288 const SummaryState& summary_state,
2292 auto frates = [
this, &simulator, &deferred_logger](
const Scalar bhp) {
2298 std::vector<Scalar> rates(3);
2299 computeWellRatesWithBhp(simulator, bhp, rates, deferred_logger);
2305 this->connections_.rho(),
2316 template<
typename TypeTag>
2321 const Well::InjectionControls& inj_controls,
2322 const Well::ProductionControls& prod_controls,
2327 updatePrimaryVariables(simulator, well_state, deferred_logger);
2329 const int max_iter = this->param_.max_inner_iter_wells_;
2332 bool relax_convergence =
false;
2333 this->regularize_ =
false;
2335 assembleWellEqWithoutIteration(simulator, dt, inj_controls, prod_controls, well_state, group_state, deferred_logger);
2337 if (it > this->param_.strict_inner_iter_wells_) {
2338 relax_convergence =
true;
2339 this->regularize_ =
true;
2342 auto report = getWellConvergence(simulator, well_state, Base::B_avg_, deferred_logger, relax_convergence);
2344 converged = report.converged();
2350 solveEqAndUpdateWellState(simulator, well_state, deferred_logger);
2357 }
while (it < max_iter);
2363 template<
typename TypeTag>
2368 const Well::InjectionControls& inj_controls,
2369 const Well::ProductionControls& prod_controls,
2373 const bool fixed_control ,
2374 const bool fixed_status )
2376 updatePrimaryVariables(simulator, well_state, deferred_logger);
2378 const int max_iter = this->param_.max_inner_iter_wells_;
2380 bool converged =
false;
2381 bool relax_convergence =
false;
2382 this->regularize_ =
false;
2383 const auto& summary_state = simulator.vanguard().summaryState();
2388 constexpr int min_its_after_switch = 4;
2389 int its_since_last_switch = min_its_after_switch;
2390 int switch_count= 0;
2392 const auto well_status_orig = this->wellStatus_;
2393 const auto operability_orig = this->operability_status_;
2394 auto well_status_cur = well_status_orig;
2395 int status_switch_count = 0;
2397 const bool allow_open = this->well_ecl_.getStatus() == WellStatus::OPEN &&
2398 well_state.
well(this->index_of_well_).status == WellStatus::OPEN;
2400 const bool allow_switching =
2401 !this->wellUnderZeroRateTarget(simulator, well_state, deferred_logger) &&
2402 (!fixed_control || !fixed_status) && allow_open;
2404 bool changed =
false;
2405 bool final_check =
false;
2407 this->operability_status_.resetOperability();
2408 this->operability_status_.solvable =
true;
2410 its_since_last_switch++;
2411 if (allow_switching && its_since_last_switch >= min_its_after_switch){
2412 const Scalar wqTotal = this->primary_variables_.eval(WQTotal).value();
2413 changed = this->updateWellControlAndStatusLocalIteration(simulator, well_state, group_state,
2414 inj_controls, prod_controls, wqTotal,
2415 deferred_logger, fixed_control, fixed_status);
2417 its_since_last_switch = 0;
2419 if (well_status_cur != this->wellStatus_) {
2420 well_status_cur = this->wellStatus_;
2421 status_switch_count++;
2424 if (!changed && final_check) {
2427 final_check =
false;
2431 assembleWellEqWithoutIteration(simulator, dt, inj_controls, prod_controls, well_state, group_state, deferred_logger);
2433 if (it > this->param_.strict_inner_iter_wells_) {
2434 relax_convergence =
true;
2435 this->regularize_ =
true;
2438 auto report = getWellConvergence(simulator, well_state, Base::B_avg_, deferred_logger, relax_convergence);
2440 converged = report.converged();
2444 if (switch_count > 0 && its_since_last_switch < min_its_after_switch) {
2446 its_since_last_switch = min_its_after_switch;
2453 solveEqAndUpdateWellState(simulator, well_state, deferred_logger);
2455 }
while (it < max_iter);
2458 if (allow_switching){
2460 const bool is_stopped = this->wellIsStopped();
2461 if (this->wellHasTHPConstraints(summary_state)){
2462 this->operability_status_.can_obtain_bhp_with_thp_limit = !is_stopped;
2463 this->operability_status_.obey_thp_limit_under_bhp_limit = !is_stopped;
2465 this->operability_status_.operable_under_only_bhp_limit = !is_stopped;
2469 this->wellStatus_ = well_status_orig;
2470 this->operability_status_ = operability_orig;
2471 const std::string message = fmt::format(
" Well {} did not converge in {} inner iterations ("
2472 "{} switches, {} status changes).", this->name(), it, switch_count, status_switch_count);
2473 deferred_logger.
debug(message);
2479 template<
typename TypeTag>
2480 std::vector<typename StandardWell<TypeTag>::Scalar>
2486 std::vector<Scalar> well_q_s(this->num_components_, 0.);
2487 const EvalWell& bhp = this->primary_variables_.eval(Bhp);
2488 const bool allow_cf = this->getAllowCrossFlow() || openCrossFlowAvoidSingularity(simulator);
2489 for (
int perf = 0; perf < this->number_of_local_perforations_; ++perf) {
2490 const int cell_idx = this->well_cells_[perf];
2491 const auto& intQuants = simulator.model().intensiveQuantities(cell_idx, 0);
2492 std::vector<Scalar> mob(this->num_components_, 0.);
2493 getMobility(simulator, perf, mob, deferred_logger);
2494 std::vector<Scalar> cq_s(this->num_components_, 0.);
2495 Scalar trans_mult = simulator.problem().template wellTransMultiplier<Scalar>(intQuants, cell_idx);
2496 const auto& wellstate_nupcol = simulator.problem().wellModel().nupcolWellState().well(this->index_of_well_);
2497 const std::vector<Scalar> Tw = this->wellIndex(perf, intQuants, trans_mult, wellstate_nupcol);
2499 computePerfRate(intQuants, mob, bhp.value(), Tw, perf, allow_cf,
2500 cq_s, perf_rates, deferred_logger);
2501 for (
int comp = 0; comp < this->num_components_; ++comp) {
2502 well_q_s[comp] += cq_s[comp];
2505 const auto& comm = this->parallel_well_info_.communication();
2506 if (comm.size() > 1)
2508 comm.sum(well_q_s.data(), well_q_s.size());
2515 template <
typename TypeTag>
2516 std::vector<typename StandardWell<TypeTag>::Scalar>
2520 const int num_pri_vars = this->primary_variables_.numWellEq();
2521 std::vector<Scalar> retval(num_pri_vars);
2522 for (
int ii = 0; ii < num_pri_vars; ++ii) {
2523 retval[ii] = this->primary_variables_.value(ii);
2532 template <
typename TypeTag>
2537 const int num_pri_vars = this->primary_variables_.numWellEq();
2538 for (
int ii = 0; ii < num_pri_vars; ++ii) {
2539 this->primary_variables_.setValue(ii, it[ii]);
2541 return num_pri_vars;
2545 template <
typename TypeTag>
2549 const std::vector<EvalWell>& cq_s,
2550 const IntensiveQuantities& intQuants,
2553 auto fs = intQuants.fluidState();
2555 for (
unsigned phaseIdx = 0; phaseIdx < FluidSystem::numPhases; ++phaseIdx) {
2556 if (!FluidSystem::phaseIsActive(phaseIdx)) {
2561 EvalWell cq_r_thermal(this->primary_variables_.numWellEq() + Indices::numEq, 0.);
2562 const unsigned activeCompIdx = Indices::canonicalToActiveComponentIndex(FluidSystem::solventComponentIndex(phaseIdx));
2563 const bool both_oil_gas = FluidSystem::phaseIsActive(FluidSystem::oilPhaseIdx) && FluidSystem::phaseIsActive(FluidSystem::gasPhaseIdx);
2564 if (!both_oil_gas || FluidSystem::waterPhaseIdx == phaseIdx) {
2565 cq_r_thermal = cq_s[activeCompIdx] / this->extendEval(fs.invB(phaseIdx));
2568 const unsigned oilCompIdx = Indices::canonicalToActiveComponentIndex(FluidSystem::oilCompIdx);
2569 const unsigned gasCompIdx = Indices::canonicalToActiveComponentIndex(FluidSystem::gasCompIdx);
2574 const EvalWell d = this->extendEval(1.0 - fs.Rv() * fs.Rs());
2576 deferred_logger.
debug(
2577 fmt::format(
"Problematic d value {} obtained for well {}"
2578 " during calculateSinglePerf with rs {}"
2579 ", rv {}. Continue as if no dissolution (rs = 0) and"
2580 " vaporization (rv = 0) for this connection.",
2581 d, this->name(), fs.Rs(), fs.Rv()));
2582 cq_r_thermal = cq_s[activeCompIdx] / this->extendEval(fs.invB(phaseIdx));
2584 if (FluidSystem::gasPhaseIdx == phaseIdx) {
2585 cq_r_thermal = (cq_s[gasCompIdx] -
2586 this->extendEval(fs.Rs()) * cq_s[oilCompIdx]) /
2587 (d * this->extendEval(fs.invB(phaseIdx)) );
2588 }
else if (FluidSystem::oilPhaseIdx == phaseIdx) {
2590 cq_r_thermal = (cq_s[oilCompIdx] - this->extendEval(fs.Rv()) *
2592 (d * this->extendEval(fs.invB(phaseIdx)) );
2598 if (this->isInjector() && !this->wellIsStopped() && cq_r_thermal > 0.0){
2600 assert(this->well_ecl_.injectorType() != InjectorType::MULTI);
2601 fs.setTemperature(this->well_ecl_.inj_temperature());
2602 typedef typename std::decay<
decltype(fs)>::type::Scalar FsScalar;
2603 typename FluidSystem::template ParameterCache<FsScalar> paramCache;
2604 const unsigned pvtRegionIdx = intQuants.pvtRegionIndex();
2605 paramCache.setRegionIndex(pvtRegionIdx);
2606 paramCache.setMaxOilSat(maxOilSaturation);
2607 paramCache.updatePhase(fs, phaseIdx);
2609 const auto& rho = FluidSystem::density(fs, paramCache, phaseIdx);
2610 fs.setDensity(phaseIdx, rho);
2611 const auto& h = FluidSystem::enthalpy(fs, paramCache, phaseIdx);
2612 fs.setEnthalpy(phaseIdx, h);
2613 cq_r_thermal *= this->extendEval(fs.enthalpy(phaseIdx)) * this->extendEval(fs.density(phaseIdx));
2614 result += getValue(cq_r_thermal);
2615 }
else if (cq_r_thermal > 0.0) {
2616 cq_r_thermal *= getValue(fs.enthalpy(phaseIdx)) * getValue(fs.density(phaseIdx));
2617 result += Base::restrictEval(cq_r_thermal);
2620 cq_r_thermal *= this->extendEval(fs.enthalpy(phaseIdx)) * this->extendEval(fs.density(phaseIdx));
2621 result += Base::restrictEval(cq_r_thermal);
2625 return result * this->well_efficiency_factor_;
#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 warning(const std::string &tag, const std::string &message)
void debug(const std::string &tag, const std::string &message)
Definition: GroupState.hpp:43
Class encapsulating some information about parallel wells.
Definition: ParallelWellInfo.hpp:195
Definition: RatioCalculator.hpp:38
Class handling assemble of the equation system for StandardWell.
Definition: StandardWellAssemble.hpp:43
Scalar pressure_diff(const unsigned perf) const
Returns pressure drop for a given perforation.
Definition: StandardWellConnections.hpp:105
StdWellConnections connections_
Connection level values.
Definition: StandardWellEval.hpp:104
PrimaryVariables primary_variables_
Primary variables for well.
Definition: StandardWellEval.hpp:98
Definition: StandardWell.hpp:60
virtual void init(const PhaseUsage *phase_usage_arg, 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 computeWellConnectionPressures(const Simulator &simulator, const WellState< Scalar > &well_state, DeferredLogger &deferred_logger)
Definition: StandardWell_impl.hpp:1343
EvalWell wpolymermw(const Scalar throughput, const EvalWell &water_velocity, DeferredLogger &deferred_logger) const
Definition: StandardWell_impl.hpp:1997
void computeWellPotentials(const Simulator &simulator, const WellState< Scalar > &well_state, std::vector< Scalar > &well_potentials, DeferredLogger &deferred_logger) override
computing the well potentials for group control
Definition: StandardWell_impl.hpp:1719
typename StdWellEval::EvalWell EvalWell
Definition: StandardWell.hpp:119
typename StdWellEval::BVectorWell BVectorWell
Definition: StandardWell.hpp:120
void checkOperabilityUnderBHPLimit(const WellState< Scalar > &well_state, const Simulator &simulator, DeferredLogger &deferred_logger) override
Definition: StandardWell_impl.hpp:951
bool iterateWellEqWithControl(const Simulator &simulator, const double dt, const Well::InjectionControls &inj_controls, const Well::ProductionControls &prod_controls, WellState< Scalar > &well_state, const GroupState< Scalar > &group_state, DeferredLogger &deferred_logger) override
Definition: StandardWell_impl.hpp:2319
void computeWellRatesWithThpAlqProd(const Simulator &ebos_simulator, const SummaryState &summary_state, DeferredLogger &deferred_logger, std::vector< Scalar > &potentials, Scalar alq) const
Definition: StandardWell_impl.hpp:1702
void addWellContributions(SparseMatrixAdapter &mat) const override
Definition: StandardWell_impl.hpp:1892
std::vector< Scalar > getPrimaryVars() const override
Definition: StandardWell_impl.hpp:2518
void updateIPRImplicit(const Simulator &simulator, WellState< Scalar > &well_state, DeferredLogger &deferred_logger) override
Definition: StandardWell_impl.hpp:875
void updateProductivityIndex(const Simulator &simulator, const WellProdIndexCalculator< Scalar > &wellPICalc, WellState< Scalar > &well_state, DeferredLogger &deferred_logger) const override
Definition: StandardWell_impl.hpp:1217
void updateWaterMobilityWithPolymer(const Simulator &simulator, const int perf, std::vector< EvalWell > &mob_water, DeferredLogger &deferred_logger) const
Definition: StandardWell_impl.hpp:1828
bool iterateWellEqWithSwitching(const Simulator &simulator, const double dt, const Well::InjectionControls &inj_controls, const Well::ProductionControls &prod_controls, WellState< Scalar > &well_state, const GroupState< Scalar > &group_state, DeferredLogger &deferred_logger, const bool fixed_control=false, const bool fixed_status=false) override
Definition: StandardWell_impl.hpp:2366
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_components, const int num_phases, const int index_of_well, const std::vector< PerforationData< Scalar > > &perf_data)
Definition: StandardWell_impl.hpp:52
void updateWaterThroughput(const double dt, WellState< Scalar > &well_state) const override
Definition: StandardWell_impl.hpp:2026
std::vector< Scalar > computeCurrentWellRates(const Simulator &ebosSimulator, DeferredLogger &deferred_logger) const override
Definition: StandardWell_impl.hpp:2482
void updatePrimaryVariablesNewton(const BVectorWell &dwells, const bool stop_or_zero_rate_target, DeferredLogger &deferred_logger)
Definition: StandardWell_impl.hpp:740
GetPropType< TypeTag, Properties::Scalar > Scalar
Definition: WellInterface.hpp:83
void calculateExplicitQuantities(const Simulator &simulator, const WellState< Scalar > &well_state, DeferredLogger &deferred_logger) override
Definition: StandardWell_impl.hpp:1383
void solveEqAndUpdateWellState(const Simulator &simulator, WellState< Scalar > &well_state, DeferredLogger &deferred_logger) override
Definition: StandardWell_impl.hpp:1361
void recoverWellSolutionAndUpdateWellState(const Simulator &simulator, const BVector &x, WellState< Scalar > &well_state, DeferredLogger &deferred_logger) override
Definition: StandardWell_impl.hpp:1429
void updateWellStateFromPrimaryVariables(WellState< Scalar > &well_state, const SummaryState &summary_state, DeferredLogger &deferred_logger) const
Definition: StandardWell_impl.hpp:763
typename StdWellEval::StdWellConnections::Properties WellConnectionProps
Definition: StandardWell.hpp:262
void computeWellRatesWithBhp(const Simulator &ebosSimulator, const Scalar &bhp, std::vector< Scalar > &well_flux, DeferredLogger &deferred_logger) const override
Definition: StandardWell_impl.hpp:1449
WellConnectionProps computePropertiesForWellConnectionPressures(const Simulator &simulator, const WellState< Scalar > &well_state) const
Definition: StandardWell_impl.hpp:1122
void getMobility(const Simulator &simulator, const int perf, std::vector< Value > &mob, DeferredLogger &deferred_logger) const
Definition: StandardWell_impl.hpp:662
void computeWellRatesWithBhpIterations(const Simulator &ebosSimulator, const Scalar &bhp, std::vector< Scalar > &well_flux, DeferredLogger &deferred_logger) const override
Definition: StandardWell_impl.hpp:1495
void updateIPR(const Simulator &simulator, DeferredLogger &deferred_logger) const override
Definition: StandardWell_impl.hpp:782
std::vector< Scalar > computeWellPotentialWithTHP(const Simulator &ebosSimulator, DeferredLogger &deferred_logger, const WellState< Scalar > &well_state) const
Definition: StandardWell_impl.hpp:1559
std::optional< Scalar > computeBhpAtThpLimitProdWithAlq(const Simulator &ebos_simulator, const SummaryState &summary_state, const Scalar alq_value, DeferredLogger &deferred_logger, bool iterate_if_no_solution) const override
Definition: StandardWell_impl.hpp:2205
void computePerfRate(const IntensiveQuantities &intQuants, const std::vector< Value > &mob, const Value &bhp, const std::vector< Scalar > &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
void updateWellState(const Simulator &simulator, const BVectorWell &dwells, WellState< Scalar > &well_state, DeferredLogger &deferred_logger)
Definition: StandardWell_impl.hpp:718
void assembleWellEqWithoutIteration(const Simulator &simulator, const double dt, const Well::InjectionControls &inj_controls, const Well::ProductionControls &prod_controls, WellState< Scalar > &well_state, const GroupState< Scalar > &group_state, DeferredLogger &deferred_logger) override
Definition: StandardWell_impl.hpp:342
void computeWellConnectionDensitesPressures(const Simulator &simulator, const WellState< Scalar > &well_state, const WellConnectionProps &props, DeferredLogger &deferred_logger)
Definition: StandardWell_impl.hpp:1292
virtual void apply(const BVector &x, BVector &Ax) const override
Ax = Ax - C D^-1 B x.
Definition: StandardWell_impl.hpp:1397
std::optional< Scalar > computeBhpAtThpLimitProd(const WellState< Scalar > &well_state, const Simulator &simulator, const SummaryState &summary_state, DeferredLogger &deferred_logger) const
Definition: StandardWell_impl.hpp:2190
void checkConvergenceExtraEqs(const std::vector< Scalar > &res, ConvergenceReport &report) const
Definition: StandardWell_impl.hpp:2128
typename StdWellEval::Eval Eval
Definition: StandardWell.hpp:118
Scalar computeWellRatesAndBhpWithThpAlqProd(const Simulator &ebos_simulator, const SummaryState &summary_state, DeferredLogger &deferred_logger, std::vector< Scalar > &potentials, Scalar alq) const
Definition: StandardWell_impl.hpp:1673
void updateConnectionRatePolyMW(const EvalWell &cq_s_poly, const IntensiveQuantities &int_quants, const WellState< Scalar > &well_state, const int perf, std::vector< RateVector > &connectionRates, DeferredLogger &deferred_logger) const
Definition: StandardWell_impl.hpp:2147
bool openCrossFlowAvoidSingularity(const Simulator &simulator) const
Definition: StandardWell_impl.hpp:1111
void updatePrimaryVariables(const Simulator &simulator, const WellState< Scalar > &well_state, DeferredLogger &deferred_logger) override
Definition: StandardWell_impl.hpp:1794
virtual ConvergenceReport getWellConvergence(const Simulator &simulator, const WellState< Scalar > &well_state, const std::vector< Scalar > &B_avg, DeferredLogger &deferred_logger, const bool relax_tolerance) const override
check whether the well equations get converged for this well
Definition: StandardWell_impl.hpp:1173
std::optional< Scalar > computeBhpAtThpLimitInj(const Simulator &simulator, const SummaryState &summary_state, DeferredLogger &deferred_logger) const
Definition: StandardWell_impl.hpp:2287
bool allDrawDownWrongDirection(const Simulator &simulator) const
Definition: StandardWell_impl.hpp:1069
EvalWell pskin(const Scalar throughput, const EvalWell &water_velocity, const EvalWell &poly_inj_conc, DeferredLogger &deferred_logger) const
Definition: StandardWell_impl.hpp:1952
static constexpr int numWellConservationEq
Definition: StandardWell.hpp:95
void handleInjectivityEquations(const Simulator &simulator, const WellState< Scalar > &well_state, const int perf, const EvalWell &water_flux_s, DeferredLogger &deferred_logger)
Definition: StandardWell_impl.hpp:2080
int setPrimaryVars(typename std::vector< Scalar >::const_iterator it) override
Definition: StandardWell_impl.hpp:2535
void assembleWellEqWithoutIterationImpl(const Simulator &simulator, const double dt, const Well::InjectionControls &inj_controls, const Well::ProductionControls &prod_controls, WellState< Scalar > &well_state, const GroupState< Scalar > &group_state, DeferredLogger &deferred_logger)
Definition: StandardWell_impl.hpp:368
void checkOperabilityUnderTHPLimit(const Simulator &simulator, const WellState< Scalar > &well_state, DeferredLogger &deferred_logger) override
Definition: StandardWell_impl.hpp:1020
void addWellPressureEquations(PressureMatrix &mat, const BVector &x, const int pressureVarIndex, const bool use_well_weights, const WellState< Scalar > &well_state) const override
Definition: StandardWell_impl.hpp:1900
EvalWell pskinwater(const Scalar throughput, const EvalWell &water_velocity, DeferredLogger &deferred_logger) const
Definition: StandardWell_impl.hpp:1920
void handleInjectivityRate(const Simulator &simulator, const int perf, std::vector< EvalWell > &cq_s) const
Definition: StandardWell_impl.hpp:2057
Scalar getRefDensity() const override
Definition: StandardWell_impl.hpp:1817
void calculateSinglePerf(const Simulator &simulator, const int perf, WellState< Scalar > &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:494
bool computeWellPotentialsImplicit(const Simulator &ebos_simulator, const WellState< Scalar > &well_state, std::vector< Scalar > &well_potentials, DeferredLogger &deferred_logger) const
Definition: StandardWell_impl.hpp:1594
Scalar connectionDensity(const int globalConnIdx, const int openConnIdx) const override
Definition: StandardWell_impl.hpp:1779
EvalWell getQs(const int compIdx) const
Returns scaled rate for a component.
Class for computing BHP limits.
Definition: WellBhpThpCalculator.hpp:41
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.
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.
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.
Scalar mostStrictBhpFromBhpLimits(const SummaryState &summaryState) const
Obtain the most strict BHP from BHP limits.
Definition: WellConvergence.hpp:38
void prepareForPotentialCalculations(const SummaryState &summary_state, WellState< Scalar > &well_state, Well::InjectionControls &inj_controls, Well::ProductionControls &prod_controls) const
std::pair< bool, bool > computeWellPotentials(std::vector< Scalar > &well_potentials, const WellState< Scalar > &well_state)
const int num_components_
Definition: WellInterfaceGeneric.hpp:307
void resetDampening()
Definition: WellInterfaceGeneric.hpp:240
Well well_ecl_
Definition: WellInterfaceGeneric.hpp:297
Definition: WellInterfaceIndices.hpp:34
Definition: WellInterface.hpp:77
GetPropType< TypeTag, Properties::Simulator > Simulator
Definition: WellInterface.hpp:82
typename WellInterfaceFluidSystem< FluidSystem >::RateConverterType RateConverterType
Definition: WellInterface.hpp:100
Dune::BCRSMatrix< Opm::MatrixBlock< Scalar, 1, 1 > > PressureMatrix
Definition: WellInterface.hpp:97
void getMobility(const Simulator &simulator, const int local_perf_index, std::vector< Value > &mob, Callback &extendEval, DeferredLogger &deferred_logger) const
Definition: WellInterface_impl.hpp:1895
GetPropType< TypeTag, Properties::IntensiveQuantities > IntensiveQuantities
Definition: WellInterface.hpp:86
GetPropType< TypeTag, Properties::Scalar > Scalar
Definition: WellInterface.hpp:83
bool solveWellWithOperabilityCheck(const Simulator &simulator, const double dt, const Well::InjectionControls &inj_controls, const Well::ProductionControls &prod_controls, WellState< Scalar > &well_state, const GroupState< Scalar > &group_state, DeferredLogger &deferred_logger)
Definition: WellInterface_impl.hpp:566
Dune::BlockVector< VectorBlockType > BVector
Definition: WellInterface.hpp:96
typename Base::ModelParameters ModelParameters
Definition: WellInterface.hpp:106
GetPropType< TypeTag, Properties::FluidSystem > FluidSystem
Definition: WellInterface.hpp:84
GetPropType< TypeTag, Properties::Indices > Indices
Definition: WellInterface.hpp:85
GetPropType< TypeTag, Properties::SparseMatrixAdapter > SparseMatrixAdapter
Definition: WellInterface.hpp:88
Definition: WellProdIndexCalculator.hpp:37
Scalar connectionProdIndStandard(const std::size_t connIdx, const Scalar connMobility) const
Definition: WellState.hpp:65
const SingleWellState< Scalar > & well(std::size_t well_index) const
Definition: WellState.hpp:285
const PhaseUsage & phaseUsage() const
Definition: WellState.hpp:244
std::vector< Scalar > & wellRates(std::size_t well_index)
One rate per well and phase.
Definition: WellState.hpp:250
@ NONE
Definition: DeferredLogger.hpp:46
Definition: blackoilboundaryratevector.hh:39
PhaseUsage phaseUsage(const Phases &phases)
Determine the active phases.
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
Definition: BlackoilPhases.hpp:46