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<Scalar>& 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<Scalar>& 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>
343 const Well::InjectionControls& inj_controls,
344 const Well::ProductionControls& prod_controls,
351 if (!this->isOperableAndSolvable() && !this->wellIsStopped())
return;
354 this->linSys_.clear();
356 assembleWellEqWithoutIterationImpl(simulator, dt, inj_controls,
357 prod_controls, well_state,
358 group_state, deferred_logger);
364 template<
typename TypeTag>
369 const Well::InjectionControls& inj_controls,
370 const Well::ProductionControls& prod_controls,
376 const Scalar regularization_factor = this->regularize_? this->param_.regularization_factor_wells_ : 1.0;
377 const Scalar volume = 0.1 * unit::cubic(unit::feet) * regularization_factor;
379 auto& ws = well_state.
well(this->index_of_well_);
380 ws.phase_mixing_rates.fill(0.0);
381 if constexpr (has_energy) {
382 ws.energy_rate = 0.0;
386 const int np = this->number_of_phases_;
388 std::vector<RateVector> connectionRates = this->connectionRates_;
390 auto& perf_data = ws.perf_data;
391 auto& perf_rates = perf_data.phase_rates;
392 for (
int perf = 0; perf < this->number_of_local_perforations_; ++perf) {
394 std::vector<EvalWell> cq_s(this->num_conservation_quantities_, {this->primary_variables_.numWellEq() + Indices::numEq, 0.0});
395 EvalWell water_flux_s{this->primary_variables_.numWellEq() + Indices::numEq, 0.0};
396 EvalWell cq_s_zfrac_effective{this->primary_variables_.numWellEq() + Indices::numEq, 0.0};
397 calculateSinglePerf(simulator, perf, well_state, connectionRates,
398 cq_s, water_flux_s, cq_s_zfrac_effective, deferred_logger);
401 if constexpr (has_polymer && Base::has_polymermw) {
402 if (this->isInjector()) {
403 handleInjectivityEquations(simulator, well_state, perf,
404 water_flux_s, deferred_logger);
407 for (
int componentIdx = 0; componentIdx < this->num_conservation_quantities_; ++componentIdx) {
409 const EvalWell cq_s_effective = cq_s[componentIdx] * this->well_efficiency_factor_;
411 connectionRates[perf][componentIdx] = Base::restrictEval(cq_s_effective);
414 assemblePerforationEq(cq_s_effective,
417 this->primary_variables_.numWellEq(),
421 if (has_solvent && componentIdx == Indices::contiSolventEqIdx) {
422 auto& perf_rate_solvent = perf_data.solvent_rates;
423 perf_rate_solvent[perf] = cq_s[componentIdx].value();
425 perf_rates[perf*np + FluidSystem::activeCompToActivePhaseIdx(componentIdx)] = cq_s[componentIdx].value();
429 if constexpr (has_zFraction) {
431 assembleZFracEq(cq_s_zfrac_effective,
433 this->primary_variables_.numWellEq(),
438 this->connectionRates_ = connectionRates;
443 const auto& comm = this->parallel_well_info_.communication();
444 comm.sum(ws.phase_mixing_rates.data(), ws.phase_mixing_rates.size());
448 this->linSys_.sumDistributed(this->parallel_well_info_.communication());
451 for (
int componentIdx = 0; componentIdx < numWellConservationEq; ++componentIdx) {
454 EvalWell resWell_loc(this->primary_variables_.numWellEq() + Indices::numEq, 0.0);
455 if (FluidSystem::numActivePhases() > 1) {
457 resWell_loc += (this->primary_variables_.surfaceVolumeFraction(componentIdx) -
458 this->F0_[componentIdx]) * volume / dt;
460 resWell_loc -= this->primary_variables_.getQs(componentIdx) * this->well_efficiency_factor_;
462 assembleSourceEq(resWell_loc,
464 this->primary_variables_.numWellEq(),
468 const auto& summaryState = simulator.vanguard().summaryState();
469 const Schedule& schedule = simulator.vanguard().schedule();
470 const bool stopped_or_zero_target = this->stoppedOrZeroRateTarget(simulator, well_state, deferred_logger);
472 assembleControlEq(well_state, group_state,
473 schedule, summaryState,
474 inj_controls, prod_controls,
475 this->primary_variables_,
476 this->getRefDensity(),
478 stopped_or_zero_target,
484 this->linSys_.invert();
486 OPM_DEFLOG_PROBLEM(NumericalProblem,
"Error when inverting local well equations for well " + name(), deferred_logger);
493 template<
typename TypeTag>
499 std::vector<RateVector>& connectionRates,
500 std::vector<EvalWell>& cq_s,
505 const bool allow_cf = this->getAllowCrossFlow() || openCrossFlowAvoidSingularity(simulator);
506 const EvalWell& bhp = this->primary_variables_.eval(Bhp);
507 const int cell_idx = this->well_cells_[perf];
508 const auto& intQuants = simulator.model().intensiveQuantities(cell_idx, 0);
509 std::vector<EvalWell> mob(this->num_conservation_quantities_, {this->primary_variables_.numWellEq() + Indices::numEq, 0.});
510 getMobility(simulator, perf, mob, deferred_logger);
513 Scalar trans_mult = simulator.problem().template wellTransMultiplier<Scalar>(intQuants, cell_idx);
514 const auto& wellstate_nupcol = simulator.problem().wellModel().nupcolWellState().well(this->index_of_well_);
515 const std::vector<Scalar> Tw = this->wellIndex(perf, intQuants, trans_mult, wellstate_nupcol);
516 computePerfRate(intQuants, mob, bhp, Tw, perf, allow_cf,
517 cq_s, perf_rates, deferred_logger);
519 auto& ws = well_state.
well(this->index_of_well_);
520 auto& perf_data = ws.perf_data;
521 if constexpr (has_polymer && Base::has_polymermw) {
522 if (this->isInjector()) {
525 const unsigned water_comp_idx = FluidSystem::canonicalToActiveCompIdx(FluidSystem::waterCompIdx);
526 water_flux_s = cq_s[water_comp_idx];
529 handleInjectivityRate(simulator, perf, cq_s);
534 if (this->isProducer()) {
535 ws.phase_mixing_rates[ws.dissolved_gas] += perf_rates.
dis_gas;
536 ws.phase_mixing_rates[ws.dissolved_gas_in_water] += perf_rates.
dis_gas_in_water;
537 ws.phase_mixing_rates[ws.vaporized_oil] += perf_rates.
vap_oil;
538 ws.phase_mixing_rates[ws.vaporized_water] += perf_rates.
vap_wat;
539 perf_data.phase_mixing_rates[perf][ws.dissolved_gas] = perf_rates.
dis_gas;
540 perf_data.phase_mixing_rates[perf][ws.dissolved_gas_in_water] = perf_rates.
dis_gas_in_water;
541 perf_data.phase_mixing_rates[perf][ws.vaporized_oil] = perf_rates.
vap_oil;
542 perf_data.phase_mixing_rates[perf][ws.vaporized_water] = perf_rates.
vap_wat;
545 if constexpr (has_energy) {
546 connectionRates[perf][Indices::contiEnergyEqIdx] =
547 connectionRateEnergy(cq_s, intQuants, deferred_logger);
548 ws.energy_rate += getValue(connectionRates[perf][Indices::contiEnergyEqIdx]);
551 if constexpr (has_polymer) {
552 std::variant<Scalar,EvalWell> polymerConcentration;
553 if (this->isInjector()) {
554 polymerConcentration = this->wpolymer();
556 polymerConcentration = this->extendEval(intQuants.polymerConcentration() *
557 intQuants.polymerViscosityCorrection());
560 [[maybe_unused]]
EvalWell cq_s_poly;
561 std::tie(connectionRates[perf][Indices::contiPolymerEqIdx],
563 this->connections_.connectionRatePolymer(perf_data.polymer_rates[perf],
564 cq_s, polymerConcentration);
566 if constexpr (Base::has_polymermw) {
567 updateConnectionRatePolyMW(cq_s_poly, intQuants, well_state,
568 perf, connectionRates, deferred_logger);
572 if constexpr (has_foam) {
573 std::variant<Scalar,EvalWell> foamConcentration;
574 if (this->isInjector()) {
575 foamConcentration = this->wfoam();
577 foamConcentration = this->extendEval(intQuants.foamConcentration());
579 connectionRates[perf][Indices::contiFoamEqIdx] =
580 this->connections_.connectionRateFoam(cq_s, foamConcentration,
581 FoamModule::transportPhase(),
585 if constexpr (has_zFraction) {
586 std::variant<Scalar,std::array<EvalWell,2>> solventConcentration;
587 if (this->isInjector()) {
588 solventConcentration = this->wsolvent();
590 solventConcentration = std::array{this->extendEval(intQuants.xVolume()),
591 this->extendEval(intQuants.yVolume())};
593 std::tie(connectionRates[perf][Indices::contiZfracEqIdx],
594 cq_s_zfrac_effective) =
595 this->connections_.connectionRatezFraction(perf_data.solvent_rates[perf],
597 solventConcentration);
600 if constexpr (has_brine) {
601 std::variant<Scalar,EvalWell> saltConcentration;
602 if (this->isInjector()) {
603 saltConcentration = this->wsalt();
605 saltConcentration = this->extendEval(intQuants.fluidState().saltConcentration());
608 connectionRates[perf][Indices::contiBrineEqIdx] =
609 this->connections_.connectionRateBrine(perf_data.brine_rates[perf],
614 if constexpr (has_bioeffects) {
615 std::variant<Scalar,EvalWell> microbialConcentration;
616 if constexpr (has_micp) {
617 std::variant<Scalar,EvalWell> oxygenConcentration;
618 std::variant<Scalar,EvalWell> ureaConcentration;
619 if (this->isInjector()) {
620 microbialConcentration = this->wmicrobes();
621 oxygenConcentration = this->woxygen();
622 ureaConcentration = this->wurea();
624 microbialConcentration = this->extendEval(intQuants.microbialConcentration());
625 oxygenConcentration = this->extendEval(intQuants.oxygenConcentration());
626 ureaConcentration = this->extendEval(intQuants.ureaConcentration());
628 std::tie(connectionRates[perf][Indices::contiMicrobialEqIdx],
629 connectionRates[perf][Indices::contiOxygenEqIdx],
630 connectionRates[perf][Indices::contiUreaEqIdx]) =
631 this->connections_.connectionRatesMICP(perf_data.microbial_rates[perf],
632 perf_data.oxygen_rates[perf],
633 perf_data.urea_rates[perf],
635 microbialConcentration,
640 if (this->isProducer()) {
641 microbialConcentration = this->extendEval(intQuants.microbialConcentration());
642 connectionRates[perf][Indices::contiMicrobialEqIdx] =
643 this->connections_.connectionRateBioeffects(perf_data.microbial_rates[perf],
645 microbialConcentration);
651 perf_data.pressure[perf] = ws.bhp + this->connections_.pressure_diff(perf);
654 if (FluidSystem::phaseUsage().hasCO2orH2Store()) {
655 const unsigned gas_comp_idx = FluidSystem::canonicalToActiveCompIdx(FluidSystem::gasCompIdx);
656 const Scalar rho = FluidSystem::referenceDensity( FluidSystem::gasPhaseIdx, Base::pvtRegionIdx() );
657 perf_data.gas_mass_rates[perf] = cq_s[gas_comp_idx].value() * rho;
661 if (FluidSystem::phaseIsActive(FluidSystem::waterPhaseIdx)) {
662 const unsigned wat_comp_idx = FluidSystem::canonicalToActiveCompIdx(FluidSystem::waterCompIdx);
663 const Scalar rho = FluidSystem::referenceDensity( FluidSystem::waterPhaseIdx, Base::pvtRegionIdx() );
664 perf_data.wat_mass_rates[perf] = cq_s[wat_comp_idx].value() * rho;
670 template<
typename TypeTag>
671 template<
class Value>
676 std::vector<Value>& mob,
679 auto obtain = [
this](
const Eval& value)
681 if constexpr (std::is_same_v<Value, Scalar>) {
682 static_cast<void>(
this);
683 return getValue(value);
685 return this->extendEval(value);
689 obtain, deferred_logger);
692 if constexpr (has_polymer) {
693 if (!FluidSystem::phaseIsActive(FluidSystem::waterPhaseIdx)) {
694 OPM_DEFLOG_THROW(std::runtime_error,
"Water is required when polymer is active", deferred_logger);
699 if constexpr (!Base::has_polymermw) {
700 if constexpr (std::is_same_v<Value, Scalar>) {
701 std::vector<EvalWell> mob_eval(this->num_conservation_quantities_, {this->primary_variables_.numWellEq() + Indices::numEq, 0.});
702 for (std::size_t i = 0; i < mob.size(); ++i) {
703 mob_eval[i].setValue(mob[i]);
705 updateWaterMobilityWithPolymer(simulator, perf, mob_eval, deferred_logger);
706 for (std::size_t i = 0; i < mob.size(); ++i) {
707 mob[i] = getValue(mob_eval[i]);
710 updateWaterMobilityWithPolymer(simulator, perf, mob, deferred_logger);
717 const Scalar bhp = this->primary_variables_.value(Bhp);
718 const Scalar perf_press = bhp + this->connections_.pressure_diff(perf);
719 const Scalar multiplier = this->getInjMult(perf, bhp, perf_press, deferred_logger);
720 for (std::size_t i = 0; i < mob.size(); ++i) {
721 mob[i] *= multiplier;
727 template<
typename TypeTag>
735 if (!this->isOperableAndSolvable() && !this->wellIsStopped())
return;
737 const bool stop_or_zero_rate_target = this->stoppedOrZeroRateTarget(simulator, well_state, deferred_logger);
738 updatePrimaryVariablesNewton(dwells, stop_or_zero_rate_target, deferred_logger);
740 const auto& summary_state = simulator.vanguard().summaryState();
741 updateWellStateFromPrimaryVariables(well_state, summary_state, deferred_logger);
742 Base::calculateReservoirRates(simulator.vanguard().eclState().runspec().co2Storage(), well_state.
well(this->index_of_well_));
749 template<
typename TypeTag>
753 const bool stop_or_zero_rate_target,
756 const Scalar dFLimit = this->param_.dwell_fraction_max_;
757 const Scalar dBHPLimit = this->param_.dbhp_max_rel_;
758 this->primary_variables_.updateNewton(dwells, stop_or_zero_rate_target, dFLimit, dBHPLimit, deferred_logger);
761 if constexpr (Base::has_polymermw) {
762 this->primary_variables_.updateNewtonPolyMW(dwells);
765 this->primary_variables_.checkFinite(deferred_logger);
772 template<
typename TypeTag>
776 const SummaryState& summary_state,
779 this->primary_variables_.copyToWellState(well_state, deferred_logger);
782 updateThp(getRefDensity(),
783 [
this,&well_state]() {
return this->baseif_.getALQ(well_state); },
784 well_state, summary_state, deferred_logger);
787 if constexpr (Base::has_polymermw) {
788 this->primary_variables_.copyToWellStatePolyMW(well_state);
796 template<
typename TypeTag>
804 std::fill(this->ipr_a_.begin(), this->ipr_a_.end(), 0.);
805 std::fill(this->ipr_b_.begin(), this->ipr_b_.end(), 0.);
807 for (
int perf = 0; perf < this->number_of_local_perforations_; ++perf) {
808 std::vector<Scalar> mob(this->num_conservation_quantities_, 0.0);
809 getMobility(simulator, perf, mob, deferred_logger);
811 const int cell_idx = this->well_cells_[perf];
812 const auto& int_quantities = simulator.model().intensiveQuantities(cell_idx, 0);
813 const auto& fs = int_quantities.fluidState();
815 Scalar p_r = this->getPerfCellPressure(fs).value();
818 std::vector<Scalar> b_perf(this->num_conservation_quantities_);
819 for (std::size_t phase = 0; phase < FluidSystem::numPhases; ++phase) {
820 if (!FluidSystem::phaseIsActive(phase)) {
823 const unsigned comp_idx = FluidSystem::canonicalToActiveCompIdx(FluidSystem::solventComponentIndex(phase));
824 b_perf[comp_idx] = fs.invB(phase).value();
826 if constexpr (has_solvent) {
827 b_perf[Indices::contiSolventEqIdx] = int_quantities.solventInverseFormationVolumeFactor().value();
831 const Scalar h_perf = this->connections_.pressure_diff(perf);
832 const Scalar pressure_diff = p_r - h_perf;
837 if ( (this->isProducer() && pressure_diff < 0.) || (this->isInjector() && pressure_diff > 0.) ) {
838 deferred_logger.
debug(
"CROSSFLOW_IPR",
839 "cross flow found when updateIPR for well " + name()
840 +
" . The connection is ignored in IPR calculations");
846 Scalar trans_mult = simulator.problem().template wellTransMultiplier<Scalar>(int_quantities, cell_idx);
847 const auto& wellstate_nupcol = simulator.problem().wellModel().nupcolWellState().well(this->index_of_well_);
848 const std::vector<Scalar> tw_perf = this->wellIndex(perf,
852 std::vector<Scalar> ipr_a_perf(this->ipr_a_.size());
853 std::vector<Scalar> ipr_b_perf(this->ipr_b_.size());
854 for (
int comp_idx = 0; comp_idx < this->num_conservation_quantities_; ++comp_idx) {
855 const Scalar tw_mob = tw_perf[comp_idx] * mob[comp_idx] * b_perf[comp_idx];
856 ipr_a_perf[comp_idx] += tw_mob * pressure_diff;
857 ipr_b_perf[comp_idx] += tw_mob;
861 if (FluidSystem::phaseIsActive(FluidSystem::oilPhaseIdx) && FluidSystem::phaseIsActive(FluidSystem::gasPhaseIdx)) {
862 const unsigned oil_comp_idx = FluidSystem::canonicalToActiveCompIdx(FluidSystem::oilCompIdx);
863 const unsigned gas_comp_idx = FluidSystem::canonicalToActiveCompIdx(FluidSystem::gasCompIdx);
864 const Scalar rs = (fs.Rs()).value();
865 const Scalar rv = (fs.Rv()).value();
867 const Scalar dis_gas_a = rs * ipr_a_perf[oil_comp_idx];
868 const Scalar vap_oil_a = rv * ipr_a_perf[gas_comp_idx];
870 ipr_a_perf[gas_comp_idx] += dis_gas_a;
871 ipr_a_perf[oil_comp_idx] += vap_oil_a;
873 const Scalar dis_gas_b = rs * ipr_b_perf[oil_comp_idx];
874 const Scalar vap_oil_b = rv * ipr_b_perf[gas_comp_idx];
876 ipr_b_perf[gas_comp_idx] += dis_gas_b;
877 ipr_b_perf[oil_comp_idx] += vap_oil_b;
880 for (std::size_t comp_idx = 0; comp_idx < ipr_a_perf.size(); ++comp_idx) {
881 this->ipr_a_[comp_idx] += ipr_a_perf[comp_idx];
882 this->ipr_b_[comp_idx] += ipr_b_perf[comp_idx];
885 this->parallel_well_info_.communication().sum(this->ipr_a_.data(), this->ipr_a_.size());
886 this->parallel_well_info_.communication().sum(this->ipr_b_.data(), this->ipr_b_.size());
889 template<
typename TypeTag>
903 auto rates = well_state.
well(this->index_of_well_).surface_rates;
905 for (std::size_t p = 0; p < rates.size(); ++p) {
906 zero_rates &= rates[p] == 0.0;
908 auto& ws = well_state.
well(this->index_of_well_);
910 const auto msg = fmt::format(
"updateIPRImplicit: Well {} has zero rate, IPRs might be problematic", this->name());
911 deferred_logger.
debug(msg);
923 const auto& group_state = simulator.problem().wellModel().groupState();
925 std::fill(ws.implicit_ipr_a.begin(), ws.implicit_ipr_a.end(), 0.);
926 std::fill(ws.implicit_ipr_b.begin(), ws.implicit_ipr_b.end(), 0.);
928 auto inj_controls = Well::InjectionControls(0);
929 auto prod_controls = Well::ProductionControls(0);
930 prod_controls.addControl(Well::ProducerCMode::BHP);
931 prod_controls.bhp_limit = well_state.
well(this->index_of_well_).bhp;
934 const auto cmode = ws.production_cmode;
935 ws.production_cmode = Well::ProducerCMode::BHP;
936 const double dt = simulator.timeStepSize();
937 assembleWellEqWithoutIteration(simulator, dt, inj_controls, prod_controls, well_state, group_state, deferred_logger);
939 const size_t nEq = this->primary_variables_.numWellEq();
943 for (
size_t i=0; i < nEq; ++i){
949 x_well[0].resize(nEq);
950 this->linSys_.solve(rhs, x_well);
952 for (
int comp_idx = 0; comp_idx < this->num_conservation_quantities_; ++comp_idx){
953 EvalWell comp_rate = this->primary_variables_.getQs(comp_idx);
954 const int idx = FluidSystem::activeCompToActivePhaseIdx(comp_idx);
955 for (
size_t pvIdx = 0; pvIdx < nEq; ++pvIdx) {
957 ws.implicit_ipr_b[idx] -= x_well[0][pvIdx]*comp_rate.derivative(pvIdx+Indices::numEq);
959 ws.implicit_ipr_a[idx] = ws.implicit_ipr_b[idx]*ws.bhp - comp_rate.value();
962 ws.production_cmode = cmode;
965 template<
typename TypeTag>
972 const auto& summaryState = simulator.vanguard().summaryState();
976 const bool bhp_limit_not_defaulted = bhp_limit > 1.5 * unit::barsa;
977 if ( bhp_limit_not_defaulted || !this->wellHasTHPConstraints(summaryState) ) {
980 Scalar total_ipr_mass_rate = 0.0;
981 for (
unsigned phaseIdx = 0; phaseIdx < FluidSystem::numPhases; ++phaseIdx)
983 if (!FluidSystem::phaseIsActive(phaseIdx)) {
987 const unsigned compIdx = FluidSystem::canonicalToActiveCompIdx(FluidSystem::solventComponentIndex(phaseIdx));
988 const Scalar ipr_rate = this->ipr_a_[compIdx] - this->ipr_b_[compIdx] * bhp_limit;
990 const Scalar rho = FluidSystem::referenceDensity( phaseIdx, Base::pvtRegionIdx() );
991 total_ipr_mass_rate += ipr_rate * rho;
993 if ( (this->isProducer() && total_ipr_mass_rate < 0.) || (this->isInjector() && total_ipr_mass_rate > 0.) ) {
994 this->operability_status_.operable_under_only_bhp_limit =
false;
998 if (this->operability_status_.operable_under_only_bhp_limit && this->wellHasTHPConstraints(summaryState)) {
1002 std::vector<Scalar> well_rates_bhp_limit;
1003 computeWellRatesWithBhp(simulator, bhp_limit, well_rates_bhp_limit, deferred_logger);
1005 this->adaptRatesForVFP(well_rates_bhp_limit);
1006 const Scalar thp_limit = this->getTHPConstraint(summaryState);
1009 this->getRefDensity(),
1010 this->getALQ(well_state),
1013 if ( (this->isProducer() && thp < thp_limit) || (this->isInjector() && thp > thp_limit) ) {
1014 this->operability_status_.obey_thp_limit_under_bhp_limit =
false;
1025 this->operability_status_.operable_under_only_bhp_limit =
true;
1026 this->operability_status_.obey_thp_limit_under_bhp_limit =
false;
1034 template<
typename TypeTag>
1041 const auto& summaryState = simulator.vanguard().summaryState();
1042 const auto obtain_bhp = this->isProducer() ? computeBhpAtThpLimitProd(well_state, simulator, summaryState, deferred_logger)
1043 : computeBhpAtThpLimitInj(simulator, summaryState, deferred_logger);
1046 this->operability_status_.can_obtain_bhp_with_thp_limit =
true;
1049 this->operability_status_.obey_bhp_limit_with_thp_limit = this->isProducer() ?
1050 *obtain_bhp >= bhp_limit : *obtain_bhp <= bhp_limit ;
1052 const Scalar thp_limit = this->getTHPConstraint(summaryState);
1053 if (this->isProducer() && *obtain_bhp < thp_limit) {
1054 const std::string msg =
" obtained bhp " +
std::to_string(unit::convert::to(*obtain_bhp, unit::barsa))
1055 +
" bars is SMALLER than thp limit "
1057 +
" bars as a producer for well " + name();
1058 deferred_logger.
debug(msg);
1060 else if (this->isInjector() && *obtain_bhp > thp_limit) {
1061 const std::string msg =
" obtained bhp " +
std::to_string(unit::convert::to(*obtain_bhp, unit::barsa))
1062 +
" bars is LARGER than thp limit "
1064 +
" bars as a injector for well " + name();
1065 deferred_logger.
debug(msg);
1068 this->operability_status_.can_obtain_bhp_with_thp_limit =
false;
1069 this->operability_status_.obey_bhp_limit_with_thp_limit =
false;
1070 if (!this->wellIsStopped()) {
1071 const Scalar thp_limit = this->getTHPConstraint(summaryState);
1072 deferred_logger.
debug(
" could not find bhp value at thp limit "
1074 +
" bar for well " + name() +
", the well might need to be closed ");
1083 template<
typename TypeTag>
1088 bool all_drawdown_wrong_direction =
true;
1090 for (
int perf = 0; perf < this->number_of_local_perforations_; ++perf) {
1091 const int cell_idx = this->well_cells_[perf];
1092 const auto& intQuants = simulator.model().intensiveQuantities(cell_idx, 0);
1093 const auto& fs = intQuants.fluidState();
1095 const Scalar pressure = this->getPerfCellPressure(fs).value();
1096 const Scalar bhp = this->primary_variables_.eval(Bhp).value();
1099 const Scalar well_pressure = bhp + this->connections_.pressure_diff(perf);
1100 const Scalar drawdown = pressure - well_pressure;
1105 if ( (drawdown < 0. && this->isInjector()) ||
1106 (drawdown > 0. && this->isProducer()) ) {
1107 all_drawdown_wrong_direction =
false;
1112 const auto& comm = this->parallel_well_info_.communication();
1113 if (comm.size() > 1)
1115 all_drawdown_wrong_direction =
1116 (comm.min(all_drawdown_wrong_direction ? 1 : 0) == 1);
1119 return all_drawdown_wrong_direction;
1125 template<
typename TypeTag>
1130 return !this->getAllowCrossFlow() && allDrawDownWrongDirection(simulator);
1136 template<
typename TypeTag>
1142 auto prop_func =
typename StdWellEval::StdWellConnections::PressurePropertyFunctions {
1144 [&model = simulator.model()](
int cell_idx,
int phase_idx)
1146 return model.intensiveQuantities(cell_idx, 0)
1147 .fluidState().temperature(phase_idx).value();
1151 [&model = simulator.model()](
int cell_idx)
1153 return model.intensiveQuantities(cell_idx, 0)
1154 .fluidState().saltConcentration().value();
1158 [&model = simulator.model()](
int cell_idx)
1160 return model.intensiveQuantities(cell_idx, 0)
1161 .fluidState().pvtRegionIndex();
1165 if constexpr (Indices::enableSolvent) {
1166 prop_func.solventInverseFormationVolumeFactor =
1167 [&model = simulator.model()](
int cell_idx)
1169 return model.intensiveQuantities(cell_idx, 0)
1170 .solventInverseFormationVolumeFactor().value();
1173 prop_func.solventRefDensity = [&model = simulator.model()](
int cell_idx)
1175 return model.intensiveQuantities(cell_idx, 0)
1176 .solventRefDensity();
1180 return this->connections_.computePropertiesForPressures(well_state, prop_func);
1187 template<
typename TypeTag>
1192 const std::vector<Scalar>& B_avg,
1194 const bool relax_tolerance)
const
1198 assert((
int(B_avg.size()) == this->num_conservation_quantities_) || has_polymer || has_energy || has_foam || has_brine || has_zFraction || has_bioeffects);
1200 Scalar tol_wells = this->param_.tolerance_wells_;
1202 constexpr Scalar stopped_factor = 1.e-4;
1204 constexpr Scalar dynamic_thp_factor = 1.e-1;
1205 if (this->stoppedOrZeroRateTarget(simulator, well_state, deferred_logger)) {
1206 tol_wells = tol_wells*stopped_factor;
1207 }
else if (this->getDynamicThpLimit()) {
1208 tol_wells = tol_wells*dynamic_thp_factor;
1211 std::vector<Scalar> res;
1214 this->param_.max_residual_allowed_,
1216 this->param_.relaxed_tolerance_flow_well_,
1218 this->wellIsStopped(),
1222 checkConvergenceExtraEqs(res, report);
1231 template<
typename TypeTag>
1239 auto fluidState = [&simulator,
this](
const int perf)
1241 const auto cell_idx = this->well_cells_[perf];
1242 return simulator.model()
1243 .intensiveQuantities(cell_idx, 0).fluidState();
1246 const int np = this->number_of_phases_;
1247 auto setToZero = [np](
Scalar* x) ->
void
1249 std::fill_n(x, np, 0.0);
1252 auto addVector = [np](
const Scalar* src,
Scalar* dest) ->
void
1254 std::transform(src, src + np, dest, dest, std::plus<>{});
1257 auto& ws = well_state.
well(this->index_of_well_);
1258 auto& perf_data = ws.perf_data;
1259 auto* wellPI = ws.productivity_index.data();
1260 auto* connPI = perf_data.prod_index.data();
1264 const auto preferred_phase = this->well_ecl_.getPreferredPhase();
1265 auto subsetPerfID = 0;
1267 for (
const auto& perf : *this->perf_data_) {
1268 auto allPerfID = perf.ecl_index;
1270 auto connPICalc = [&wellPICalc, allPerfID](
const Scalar mobility) ->
Scalar
1275 std::vector<Scalar> mob(this->num_conservation_quantities_, 0.0);
1276 getMobility(simulator,
static_cast<int>(subsetPerfID), mob, deferred_logger);
1278 const auto& fs = fluidState(subsetPerfID);
1281 if (this->isInjector()) {
1282 this->computeConnLevelInjInd(fs, preferred_phase, connPICalc,
1283 mob, connPI, deferred_logger);
1286 this->computeConnLevelProdInd(fs, connPICalc, mob, connPI);
1289 addVector(connPI, wellPI);
1296 const auto& comm = this->parallel_well_info_.communication();
1297 if (comm.size() > 1) {
1298 comm.sum(wellPI, np);
1301 assert ((
static_cast<int>(subsetPerfID) == this->number_of_local_perforations_) &&
1302 "Internal logic error in processing connections for PI/II");
1307 template<
typename TypeTag>
1317 const auto prop_func =
typename StdWellEval::StdWellConnections::DensityPropertyFunctions {
1322 [&model = simulator.model()](
const int cell,
1323 const std::vector<int>& phases,
1324 std::vector<Scalar>& mob)
1326 const auto& iq = model.intensiveQuantities(cell, 0);
1328 std::transform(phases.begin(), phases.end(), mob.begin(),
1329 [&iq](
const int phase) { return iq.mobility(phase).value(); });
1334 [&model = simulator.model()](
const int cell,
1335 const std::vector<int>& phases,
1336 std::vector<Scalar>& rho)
1338 const auto& fs = model.intensiveQuantities(cell, 0).fluidState();
1340 std::transform(phases.begin(), phases.end(), rho.begin(),
1341 [&fs](
const int phase) { return fs.density(phase).value(); });
1345 const auto stopped_or_zero_rate_target = this->
1346 stoppedOrZeroRateTarget(simulator, well_state, deferred_logger);
1349 .computeProperties(stopped_or_zero_rate_target, well_state,
1350 prop_func, props, deferred_logger);
1352 cachedRefDensity = this->connections_.rho(0);
1353 if (this->parallel_well_info_.communication().size() > 1) {
1354 cachedRefDensity = this->parallel_well_info_.broadcastFirstPerforationValue(cachedRefDensity);
1362 template<
typename TypeTag>
1369 const auto props = computePropertiesForWellConnectionPressures
1370 (simulator, well_state);
1372 computeWellConnectionDensitesPressures(simulator, well_state,
1373 props, deferred_logger);
1380 template<
typename TypeTag>
1387 if (!this->isOperableAndSolvable() && !this->wellIsStopped())
return;
1392 dx_well[0].resize(this->primary_variables_.numWellEq());
1393 this->linSys_.solve( dx_well);
1395 updateWellState(simulator, dx_well, well_state, deferred_logger);
1402 template<
typename TypeTag>
1409 updatePrimaryVariables(simulator, well_state, deferred_logger);
1410 computeWellConnectionPressures(simulator, well_state, deferred_logger);
1411 this->computeAccumWell();
1416 template<
typename TypeTag>
1421 if (!this->isOperableAndSolvable() && !this->wellIsStopped())
return;
1423 if (this->param_.matrix_add_well_contributions_)
1429 this->linSys_.apply(x, Ax);
1435 template<
typename TypeTag>
1440 if (!this->isOperableAndSolvable() && !this->wellIsStopped())
return;
1442 this->linSys_.apply(r);
1448 template<
typename TypeTag>
1456 if (!this->isOperableAndSolvable() && !this->wellIsStopped())
return;
1459 xw[0].resize(this->primary_variables_.numWellEq());
1461 this->linSys_.recoverSolutionWell(x, xw);
1462 updateWellState(simulator, xw, well_state, deferred_logger);
1468 template<
typename TypeTag>
1473 std::vector<Scalar>& well_flux,
1477 const int np = this->number_of_phases_;
1478 well_flux.resize(np, 0.0);
1480 const bool allow_cf = this->getAllowCrossFlow();
1482 for (
int perf = 0; perf < this->number_of_local_perforations_; ++perf) {
1483 const int cell_idx = this->well_cells_[perf];
1484 const auto& intQuants = simulator.model().intensiveQuantities(cell_idx, 0);
1486 std::vector<Scalar> mob(this->num_conservation_quantities_, 0.);
1487 getMobility(simulator, perf, mob, deferred_logger);
1488 Scalar trans_mult = simulator.problem().template wellTransMultiplier<Scalar>(intQuants, cell_idx);
1489 const auto& wellstate_nupcol = simulator.problem().wellModel().nupcolWellState().well(this->index_of_well_);
1490 const std::vector<Scalar> Tw = this->wellIndex(perf, intQuants, trans_mult, wellstate_nupcol);
1492 std::vector<Scalar> cq_s(this->num_conservation_quantities_, 0.);
1494 computePerfRate(intQuants, mob, bhp, Tw, perf, allow_cf,
1495 cq_s, perf_rates, deferred_logger);
1497 for(
int p = 0; p < np; ++p) {
1498 well_flux[FluidSystem::activeCompToActivePhaseIdx(p)] += cq_s[p];
1502 if constexpr (has_solvent) {
1503 assert(FluidSystem::phaseIsActive(FluidSystem::gasPhaseIdx));
1505 const int gas_pos = FluidSystem::canonicalToActivePhaseIdx(FluidSystem::gasPhaseIdx);
1506 well_flux[gas_pos] += cq_s[Indices::contiSolventEqIdx];
1509 this->parallel_well_info_.communication().sum(well_flux.data(), well_flux.size());
1514 template<
typename TypeTag>
1519 std::vector<Scalar>& well_flux,
1530 WellStateType well_state_copy = simulator.problem().wellModel().wellState();
1531 const auto& group_state = simulator.problem().wellModel().groupState();
1534 const auto& summary_state = simulator.vanguard().summaryState();
1535 auto inj_controls = well_copy.
well_ecl_.isInjector()
1536 ? well_copy.
well_ecl_.injectionControls(summary_state)
1537 : Well::InjectionControls(0);
1538 auto prod_controls = well_copy.
well_ecl_.isProducer()
1539 ? well_copy.
well_ecl_.productionControls(summary_state) :
1540 Well::ProductionControls(0);
1543 auto& ws = well_state_copy.
well(this->index_of_well_);
1545 inj_controls.bhp_limit = bhp;
1546 ws.injection_cmode = Well::InjectorCMode::BHP;
1548 prod_controls.bhp_limit = bhp;
1549 ws.production_cmode = Well::ProducerCMode::BHP;
1554 const int np = this->number_of_phases_;
1555 const Scalar sign = this->well_ecl_.isInjector() ? 1.0 : -1.0;
1556 for (
int phase = 0; phase < np; ++phase){
1557 well_state_copy.
wellRates(this->index_of_well_)[phase]
1558 = sign * ws.well_potentials[phase];
1563 const double dt = simulator.timeStepSize();
1564 const bool converged = well_copy.
iterateWellEqWithControl(simulator, dt, inj_controls, prod_controls, well_state_copy, group_state, deferred_logger);
1566 const std::string msg =
" well " + name() +
" did not get converged during well potential calculations "
1567 " potentials are computed based on unconverged solution";
1568 deferred_logger.
debug(msg);
1578 template<
typename TypeTag>
1579 std::vector<typename StandardWell<TypeTag>::Scalar>
1585 std::vector<Scalar> potentials(this->number_of_phases_, 0.0);
1586 const auto& summary_state = simulator.vanguard().summaryState();
1588 const auto& well = this->well_ecl_;
1589 if (well.isInjector()){
1590 const auto& controls = this->well_ecl_.injectionControls(summary_state);
1591 auto bhp_at_thp_limit = computeBhpAtThpLimitInj(simulator, summary_state, deferred_logger);
1592 if (bhp_at_thp_limit) {
1593 const Scalar bhp = std::min(*bhp_at_thp_limit,
1594 static_cast<Scalar>(controls.bhp_limit));
1595 computeWellRatesWithBhp(simulator, bhp, potentials, deferred_logger);
1597 deferred_logger.
warning(
"FAILURE_GETTING_CONVERGED_POTENTIAL",
1598 "Failed in getting converged thp based potential calculation for well "
1599 + name() +
". Instead the bhp based value is used");
1600 const Scalar bhp = controls.bhp_limit;
1601 computeWellRatesWithBhp(simulator, bhp, potentials, deferred_logger);
1604 computeWellRatesWithThpAlqProd(
1605 simulator, summary_state,
1606 deferred_logger, potentials, this->getALQ(well_state)
1613 template<
typename TypeTag>
1618 std::vector<Scalar>& well_potentials,
1628 const auto& group_state = simulator.problem().wellModel().groupState();
1629 auto& ws = well_state_copy.
well(this->index_of_well_);
1632 const auto& summary_state = simulator.vanguard().summaryState();
1633 auto inj_controls = well_copy.
well_ecl_.isInjector()
1634 ? well_copy.
well_ecl_.injectionControls(summary_state)
1635 : Well::InjectionControls(0);
1636 auto prod_controls = well_copy.
well_ecl_.isProducer()
1637 ? well_copy.
well_ecl_.productionControls(summary_state) :
1638 Well::ProductionControls(0);
1644 const int num_perf = ws.perf_data.size();
1645 for (
int perf = 0; perf < num_perf; ++perf) {
1649 const int np = this->number_of_phases_;
1650 bool trivial =
true;
1651 for (
int phase = 0; phase < np; ++phase){
1652 trivial = trivial && (ws.well_potentials[phase] == 0.0) ;
1656 for (
int phase = 0; phase < np; ++phase) {
1657 ws.surface_rates[phase] = sign * ws.well_potentials[phase];
1662 const double dt = simulator.timeStepSize();
1664 bool converged =
false;
1665 if (this->well_ecl_.isProducer()) {
1666 converged = well_copy.
solveWellWithOperabilityCheck(simulator, dt, inj_controls, prod_controls, well_state_copy, group_state, deferred_logger);
1668 converged = well_copy.
iterateWellEqWithSwitching(simulator, dt, inj_controls, prod_controls, well_state_copy, group_state, deferred_logger);
1672 well_potentials.clear();
1673 well_potentials.resize(np, 0.0);
1674 for (
int comp_idx = 0; comp_idx < this->num_conservation_quantities_; ++comp_idx) {
1675 if (has_solvent && comp_idx == Indices::contiSolventEqIdx)
continue;
1677 well_potentials[FluidSystem::activeCompToActivePhaseIdx(comp_idx)] = rate.value();
1681 if constexpr (has_solvent) {
1682 assert(FluidSystem::phaseIsActive(FluidSystem::gasPhaseIdx));
1684 const int gas_pos = FluidSystem::canonicalToActivePhaseIdx(FluidSystem::gasPhaseIdx);
1686 well_potentials[gas_pos] += rate.value();
1692 template<
typename TypeTag>
1696 const SummaryState &summary_state,
1698 std::vector<Scalar>& potentials,
1702 auto bhp_at_thp_limit = computeBhpAtThpLimitProdWithAlq(
1703 simulator, summary_state, alq, deferred_logger,
true);
1704 if (bhp_at_thp_limit) {
1705 const auto& controls = this->well_ecl_.productionControls(summary_state);
1706 bhp = std::max(*bhp_at_thp_limit,
1707 static_cast<Scalar>(controls.bhp_limit));
1708 computeWellRatesWithBhp(simulator, bhp, potentials, deferred_logger);
1711 deferred_logger.
warning(
"FAILURE_GETTING_CONVERGED_POTENTIAL",
1712 "Failed in getting converged thp based potential calculation for well "
1713 + name() +
". Instead the bhp based value is used");
1714 const auto& controls = this->well_ecl_.productionControls(summary_state);
1715 bhp = controls.bhp_limit;
1716 computeWellRatesWithBhp(simulator, bhp, potentials, deferred_logger);
1721 template<
typename TypeTag>
1725 const SummaryState& summary_state,
1727 std::vector<Scalar>& potentials,
1731 computeWellRatesAndBhpWithThpAlqProd(simulator,
1738 template<
typename TypeTag>
1743 std::vector<Scalar>& well_potentials,
1746 const auto [compute_potential, bhp_controlled_well] =
1749 if (!compute_potential) {
1753 bool converged_implicit =
false;
1757 if (this->param_.local_well_solver_control_switching_ && !(this->changed_to_open_this_step_ && this->wellUnderZeroRateTarget(simulator, well_state, deferred_logger))) {
1758 converged_implicit = computeWellPotentialsImplicit(simulator, well_state, well_potentials, deferred_logger);
1760 if (!converged_implicit) {
1762 const auto& summaryState = simulator.vanguard().summaryState();
1763 if (!Base::wellHasTHPConstraints(summaryState) || bhp_controlled_well) {
1773 const auto& ws = well_state.
well(this->index_of_well_);
1774 if (this->isInjector())
1775 bhp = std::max(ws.bhp, bhp);
1777 bhp = std::min(ws.bhp, bhp);
1779 assert(std::abs(bhp) != std::numeric_limits<Scalar>::max());
1780 computeWellRatesWithBhpIterations(simulator, bhp, well_potentials, deferred_logger);
1783 well_potentials = computeWellPotentialWithTHP(simulator, deferred_logger, well_state);
1787 this->checkNegativeWellPotentials(well_potentials,
1788 this->param_.check_well_operability_,
1798 template<
typename TypeTag>
1802 const int openConnIdx)
const
1804 return (openConnIdx < 0)
1806 : this->connections_.rho(openConnIdx);
1813 template<
typename TypeTag>
1820 if (!this->isOperableAndSolvable() && !this->wellIsStopped())
return;
1822 const bool stop_or_zero_rate_target = this->stoppedOrZeroRateTarget(simulator, well_state, deferred_logger);
1823 this->primary_variables_.update(well_state, stop_or_zero_rate_target, deferred_logger);
1826 if constexpr (Base::has_polymermw) {
1827 this->primary_variables_.updatePolyMW(well_state);
1830 this->primary_variables_.checkFinite(deferred_logger);
1836 template<
typename TypeTag>
1841 return cachedRefDensity;
1847 template<
typename TypeTag>
1852 std::vector<EvalWell>& mob,
1855 const int cell_idx = this->well_cells_[perf];
1856 const auto& int_quant = simulator.model().intensiveQuantities(cell_idx, 0);
1857 const EvalWell polymer_concentration = this->extendEval(int_quant.polymerConcentration());
1861 if (this->isInjector()) {
1863 const auto& visc_mult_table = PolymerModule::plyviscViscosityMultiplierTable(int_quant.pvtRegionIndex());
1864 const unsigned waterCompIdx = FluidSystem::canonicalToActiveCompIdx(FluidSystem::waterCompIdx);
1865 mob[waterCompIdx] /= (this->extendEval(int_quant.waterViscosityCorrection()) * visc_mult_table.eval(polymer_concentration,
true) );
1868 if (PolymerModule::hasPlyshlog()) {
1871 if (this->isInjector() && this->wpolymer() == 0.) {
1876 const bool allow_cf = this->getAllowCrossFlow() || openCrossFlowAvoidSingularity(simulator);
1877 const EvalWell& bhp = this->primary_variables_.eval(Bhp);
1879 std::vector<EvalWell> cq_s(this->num_conservation_quantities_, {this->primary_variables_.numWellEq() + Indices::numEq, 0.});
1881 Scalar trans_mult = simulator.problem().template wellTransMultiplier<Scalar>(int_quant, cell_idx);
1882 const auto& wellstate_nupcol = simulator.problem().wellModel().nupcolWellState().well(this->index_of_well_);
1883 const std::vector<Scalar> Tw = this->wellIndex(perf, int_quant, trans_mult, wellstate_nupcol);
1884 computePerfRate(int_quant, mob, bhp, Tw, perf, allow_cf, cq_s,
1885 perf_rates, deferred_logger);
1887 const Scalar area = 2 * M_PI * this->perf_rep_radius_[perf] * this->perf_length_[perf];
1888 const auto& material_law_manager = simulator.problem().materialLawManager();
1889 const auto& scaled_drainage_info =
1890 material_law_manager->oilWaterScaledEpsInfoDrainage(cell_idx);
1891 const Scalar swcr = scaled_drainage_info.Swcr;
1892 const EvalWell poro = this->extendEval(int_quant.porosity());
1893 const EvalWell sw = this->extendEval(int_quant.fluidState().saturation(FluidSystem::waterPhaseIdx));
1895 const EvalWell denom = max( (area * poro * (sw - swcr)), 1e-12);
1896 const unsigned waterCompIdx = FluidSystem::canonicalToActiveCompIdx(FluidSystem::waterCompIdx);
1897 EvalWell water_velocity = cq_s[waterCompIdx] / denom * this->extendEval(int_quant.fluidState().invB(FluidSystem::waterPhaseIdx));
1899 if (PolymerModule::hasShrate()) {
1902 water_velocity *= PolymerModule::shrate( int_quant.pvtRegionIndex() ) / this->bore_diameters_[perf];
1904 const EvalWell shear_factor = PolymerModule::computeShearFactor(polymer_concentration,
1905 int_quant.pvtRegionIndex(),
1908 mob[waterCompIdx] /= shear_factor;
1912 template<
typename TypeTag>
1916 this->linSys_.extract(jacobian);
1920 template <
typename TypeTag>
1924 const int pressureVarIndex,
1925 const bool use_well_weights,
1928 this->linSys_.extractCPRPressureMatrix(jacobian,
1939 template<
typename TypeTag>
1946 if constexpr (Base::has_polymermw) {
1947 const int water_table_id = this->polymerWaterTable_();
1948 if (water_table_id <= 0) {
1950 fmt::format(
"Unused SKPRWAT table id used for well {}", name()),
1953 const auto& water_table_func = PolymerModule::getSkprwatTable(water_table_id);
1954 const EvalWell throughput_eval(this->primary_variables_.numWellEq() + Indices::numEq, throughput);
1956 EvalWell pskin_water(this->primary_variables_.numWellEq() + Indices::numEq, 0.0);
1957 pskin_water = water_table_func.eval(throughput_eval, water_velocity);
1961 fmt::format(
"Polymermw is not activated, while injecting "
1962 "skin pressure is requested for well {}", name()),
1971 template<
typename TypeTag>
1979 if constexpr (Base::has_polymermw) {
1980 const Scalar sign = water_velocity >= 0. ? 1.0 : -1.0;
1981 const EvalWell water_velocity_abs = abs(water_velocity);
1982 if (poly_inj_conc == 0.) {
1983 return sign * pskinwater(throughput, water_velocity_abs, deferred_logger);
1985 const int polymer_table_id = this->polymerTable_();
1986 if (polymer_table_id <= 0) {
1988 fmt::format(
"Unavailable SKPRPOLY table id used for well {}", name()),
1991 const auto& skprpolytable = PolymerModule::getSkprpolyTable(polymer_table_id);
1992 const Scalar reference_concentration = skprpolytable.refConcentration;
1993 const EvalWell throughput_eval(this->primary_variables_.numWellEq() + Indices::numEq, throughput);
1995 EvalWell pskin_poly(this->primary_variables_.numWellEq() + Indices::numEq, 0.0);
1996 pskin_poly = skprpolytable.table_func.eval(throughput_eval, water_velocity_abs);
1997 if (poly_inj_conc == reference_concentration) {
1998 return sign * pskin_poly;
2001 const EvalWell pskin_water = pskinwater(throughput, water_velocity_abs, deferred_logger);
2002 const EvalWell pskin = pskin_water + (pskin_poly - pskin_water) / reference_concentration * poly_inj_conc;
2003 return sign * pskin;
2006 fmt::format(
"Polymermw is not activated, while injecting "
2007 "skin pressure is requested for well {}", name()),
2016 template<
typename TypeTag>
2023 if constexpr (Base::has_polymermw) {
2024 const int table_id = this->polymerInjTable_();
2025 const auto& table_func = PolymerModule::getPlymwinjTable(table_id);
2026 const EvalWell throughput_eval(this->primary_variables_.numWellEq() + Indices::numEq, throughput);
2027 EvalWell molecular_weight(this->primary_variables_.numWellEq() + Indices::numEq, 0.);
2028 if (this->wpolymer() == 0.) {
2029 return molecular_weight;
2031 molecular_weight = table_func.eval(throughput_eval, abs(water_velocity));
2032 return molecular_weight;
2035 fmt::format(
"Polymermw is not activated, while injecting "
2036 "polymer molecular weight is requested for well {}", name()),
2045 template<
typename TypeTag>
2051 if constexpr (Base::has_polymermw) {
2052 if (!this->isInjector()) {
2056 auto& perf_water_throughput = well_state.
well(this->index_of_well_)
2057 .perf_data.water_throughput;
2059 for (
int perf = 0; perf < this->number_of_local_perforations_; ++perf) {
2060 const Scalar perf_water_vel =
2061 this->primary_variables_.value(Bhp + 1 + perf);
2065 if (perf_water_vel >
Scalar{0}) {
2066 perf_water_throughput[perf] += perf_water_vel * dt;
2076 template<
typename TypeTag>
2081 std::vector<EvalWell>& cq_s)
const
2083 const int cell_idx = this->well_cells_[perf];
2084 const auto& int_quants = simulator.model().intensiveQuantities(cell_idx, 0);
2085 const auto& fs = int_quants.fluidState();
2086 const EvalWell b_w = this->extendEval(fs.invB(FluidSystem::waterPhaseIdx));
2087 const Scalar area = M_PI * this->bore_diameters_[perf] * this->perf_length_[perf];
2088 const int wat_vel_index = Bhp + 1 + perf;
2089 const unsigned water_comp_idx = FluidSystem::canonicalToActiveCompIdx(FluidSystem::waterCompIdx);
2093 cq_s[water_comp_idx] = area * this->primary_variables_.eval(wat_vel_index) * b_w;
2099 template<
typename TypeTag>
2108 const int cell_idx = this->well_cells_[perf];
2109 const auto& int_quants = simulator.model().intensiveQuantities(cell_idx, 0);
2110 const auto& fs = int_quants.fluidState();
2111 const EvalWell b_w = this->extendEval(fs.invB(FluidSystem::waterPhaseIdx));
2112 const EvalWell water_flux_r = water_flux_s / b_w;
2113 const Scalar area = M_PI * this->bore_diameters_[perf] * this->perf_length_[perf];
2114 const EvalWell water_velocity = water_flux_r / area;
2115 const int wat_vel_index = Bhp + 1 + perf;
2118 const EvalWell eq_wat_vel = this->primary_variables_.eval(wat_vel_index) - water_velocity;
2120 const auto& ws = well_state.
well(this->index_of_well_);
2121 const auto& perf_data = ws.perf_data;
2122 const auto& perf_water_throughput = perf_data.water_throughput;
2123 const Scalar throughput = perf_water_throughput[perf];
2124 const int pskin_index = Bhp + 1 + this->number_of_local_perforations_ + perf;
2126 EvalWell poly_conc(this->primary_variables_.numWellEq() + Indices::numEq, 0.0);
2127 poly_conc.setValue(this->wpolymer());
2130 const EvalWell eq_pskin = this->primary_variables_.eval(pskin_index)
2131 - pskin(throughput, this->primary_variables_.eval(wat_vel_index), poly_conc, deferred_logger);
2134 assembleInjectivityEq(eq_pskin,
2139 this->primary_variables_.numWellEq(),
2147 template<
typename TypeTag>
2156 if constexpr (Base::has_polymermw) {
2158 checkConvergencePolyMW(res, Bhp, this->param_.max_residual_allowed_, report);
2166 template<
typename TypeTag>
2173 std::vector<RateVector>& connectionRates,
2178 if (this->isInjector()) {
2179 const int wat_vel_index = Bhp + 1 + perf;
2180 const EvalWell water_velocity = this->primary_variables_.eval(wat_vel_index);
2181 if (water_velocity > 0.) {
2182 const auto& ws = well_state.
well(this->index_of_well_);
2183 const auto& perf_water_throughput = ws.perf_data.water_throughput;
2184 const Scalar throughput = perf_water_throughput[perf];
2185 const EvalWell molecular_weight = wpolymermw(throughput, water_velocity, deferred_logger);
2186 cq_s_polymw *= molecular_weight;
2192 }
else if (this->isProducer()) {
2193 if (cq_s_polymw < 0.) {
2194 cq_s_polymw *= this->extendEval(int_quants.polymerMoleWeight() );
2201 connectionRates[perf][Indices::contiPolymerMWEqIdx] = Base::restrictEval(cq_s_polymw);
2208 template<
typename TypeTag>
2209 std::optional<typename StandardWell<TypeTag>::Scalar>
2213 const SummaryState& summary_state,
2216 return computeBhpAtThpLimitProdWithAlq(simulator,
2218 this->getALQ(well_state),
2223 template<
typename TypeTag>
2224 std::optional<typename StandardWell<TypeTag>::Scalar>
2227 const SummaryState& summary_state,
2230 bool iterate_if_no_solution)
const
2234 auto frates = [
this, &simulator, &deferred_logger](
const Scalar bhp) {
2240 std::vector<Scalar> rates(3);
2241 computeWellRatesWithBhp(simulator, bhp, rates, deferred_logger);
2242 this->adaptRatesForVFP(rates);
2246 Scalar max_pressure = 0.0;
2247 for (
int perf = 0; perf < this->number_of_local_perforations_; ++perf) {
2248 const int cell_idx = this->well_cells_[perf];
2249 const auto& int_quants = simulator.model().intensiveQuantities(cell_idx, 0);
2250 const auto& fs = int_quants.fluidState();
2251 Scalar pressure_cell = this->getPerfCellPressure(fs).value();
2252 max_pressure = std::max(max_pressure, pressure_cell);
2254 const auto& comm = this->parallel_well_info_.communication();
2255 if (comm.size() > 1) {
2256 max_pressure = comm.max(max_pressure);
2261 this->getRefDensity(),
2263 this->getTHPConstraint(summary_state),
2267 auto v = frates(*bhpAtLimit);
2268 if (std::all_of(v.cbegin(), v.cend(), [](
Scalar i){ return i <= 0; }) ) {
2273 if (!iterate_if_no_solution)
2274 return std::nullopt;
2276 auto fratesIter = [
this, &simulator, &deferred_logger](
const Scalar bhp) {
2280 std::vector<Scalar> rates(3);
2281 computeWellRatesWithBhpIterations(simulator, bhp, rates, deferred_logger);
2282 this->adaptRatesForVFP(rates);
2289 this->getRefDensity(),
2291 this->getTHPConstraint(summary_state),
2297 auto v = frates(*bhpAtLimit);
2298 if (std::all_of(v.cbegin(), v.cend(), [](
Scalar i){ return i <= 0; }) ) {
2304 return std::nullopt;
2309 template<
typename TypeTag>
2310 std::optional<typename StandardWell<TypeTag>::Scalar>
2313 const SummaryState& summary_state,
2317 auto frates = [
this, &simulator, &deferred_logger](
const Scalar bhp) {
2323 std::vector<Scalar> rates(3);
2324 computeWellRatesWithBhp(simulator, bhp, rates, deferred_logger);
2330 this->getRefDensity(),
2341 template<
typename TypeTag>
2346 const Well::InjectionControls& inj_controls,
2347 const Well::ProductionControls& prod_controls,
2352 updatePrimaryVariables(simulator, well_state, deferred_logger);
2354 const int max_iter = this->param_.max_inner_iter_wells_;
2357 bool relax_convergence =
false;
2358 this->regularize_ =
false;
2360 assembleWellEqWithoutIteration(simulator, dt, inj_controls, prod_controls, well_state, group_state, deferred_logger);
2362 if (it > this->param_.strict_inner_iter_wells_) {
2363 relax_convergence =
true;
2364 this->regularize_ =
true;
2367 auto report = getWellConvergence(simulator, well_state, Base::B_avg_, deferred_logger, relax_convergence);
2369 converged = report.converged();
2375 solveEqAndUpdateWellState(simulator, well_state, deferred_logger);
2382 }
while (it < max_iter);
2388 template<
typename TypeTag>
2393 const Well::InjectionControls& inj_controls,
2394 const Well::ProductionControls& prod_controls,
2398 const bool fixed_control ,
2399 const bool fixed_status )
2401 updatePrimaryVariables(simulator, well_state, deferred_logger);
2403 const int max_iter = this->param_.max_inner_iter_wells_;
2405 bool converged =
false;
2406 bool relax_convergence =
false;
2407 this->regularize_ =
false;
2408 const auto& summary_state = simulator.vanguard().summaryState();
2413 constexpr int min_its_after_switch = 4;
2415 const int max_status_switch = this->param_.max_well_status_switch_inner_iter_;
2416 int its_since_last_switch = min_its_after_switch;
2417 int switch_count= 0;
2419 const auto well_status_orig = this->wellStatus_;
2420 const auto operability_orig = this->operability_status_;
2421 auto well_status_cur = well_status_orig;
2422 int status_switch_count = 0;
2424 const bool allow_open = well_state.
well(this->index_of_well_).status == WellStatus::OPEN;
2426 const bool allow_switching =
2427 !this->wellUnderZeroRateTarget(simulator, well_state, deferred_logger) &&
2428 (!fixed_control || !fixed_status) && allow_open;
2430 bool changed =
false;
2431 bool final_check =
false;
2433 this->operability_status_.resetOperability();
2434 this->operability_status_.solvable =
true;
2436 its_since_last_switch++;
2437 if (allow_switching && its_since_last_switch >= min_its_after_switch && status_switch_count < max_status_switch){
2438 const Scalar wqTotal = this->primary_variables_.eval(WQTotal).value();
2439 changed = this->updateWellControlAndStatusLocalIteration(simulator, well_state, group_state,
2440 inj_controls, prod_controls, wqTotal,
2441 deferred_logger, fixed_control, fixed_status);
2443 its_since_last_switch = 0;
2445 if (well_status_cur != this->wellStatus_) {
2446 well_status_cur = this->wellStatus_;
2447 status_switch_count++;
2450 if (!changed && final_check) {
2453 final_check =
false;
2455 if (status_switch_count == max_status_switch) {
2456 this->wellStatus_ = well_status_orig;
2460 assembleWellEqWithoutIteration(simulator, dt, inj_controls, prod_controls, well_state, group_state, deferred_logger);
2462 if (it > this->param_.strict_inner_iter_wells_) {
2463 relax_convergence =
true;
2464 this->regularize_ =
true;
2467 auto report = getWellConvergence(simulator, well_state, Base::B_avg_, deferred_logger, relax_convergence);
2469 converged = report.converged();
2473 if (switch_count > 0 && its_since_last_switch < min_its_after_switch) {
2475 its_since_last_switch = min_its_after_switch;
2482 solveEqAndUpdateWellState(simulator, well_state, deferred_logger);
2484 }
while (it < max_iter);
2487 if (allow_switching){
2489 const bool is_stopped = this->wellIsStopped();
2490 if (this->wellHasTHPConstraints(summary_state)){
2491 this->operability_status_.can_obtain_bhp_with_thp_limit = !is_stopped;
2492 this->operability_status_.obey_thp_limit_under_bhp_limit = !is_stopped;
2494 this->operability_status_.operable_under_only_bhp_limit = !is_stopped;
2498 this->wellStatus_ = well_status_orig;
2499 this->operability_status_ = operability_orig;
2500 const std::string message = fmt::format(
" Well {} did not converge in {} inner iterations ("
2501 "{} switches, {} status changes).", this->name(), it, switch_count, status_switch_count);
2502 deferred_logger.
debug(message);
2508 template<
typename TypeTag>
2509 std::vector<typename StandardWell<TypeTag>::Scalar>
2515 std::vector<Scalar> well_q_s(this->num_conservation_quantities_, 0.);
2516 const EvalWell& bhp = this->primary_variables_.eval(Bhp);
2517 const bool allow_cf = this->getAllowCrossFlow() || openCrossFlowAvoidSingularity(simulator);
2518 for (
int perf = 0; perf < this->number_of_local_perforations_; ++perf) {
2519 const int cell_idx = this->well_cells_[perf];
2520 const auto& intQuants = simulator.model().intensiveQuantities(cell_idx, 0);
2521 std::vector<Scalar> mob(this->num_conservation_quantities_, 0.);
2522 getMobility(simulator, perf, mob, deferred_logger);
2523 std::vector<Scalar> cq_s(this->num_conservation_quantities_, 0.);
2524 Scalar trans_mult = simulator.problem().template wellTransMultiplier<Scalar>(intQuants, cell_idx);
2525 const auto& wellstate_nupcol = simulator.problem().wellModel().nupcolWellState().well(this->index_of_well_);
2526 const std::vector<Scalar> Tw = this->wellIndex(perf, intQuants, trans_mult, wellstate_nupcol);
2528 computePerfRate(intQuants, mob, bhp.value(), Tw, perf, allow_cf,
2529 cq_s, perf_rates, deferred_logger);
2530 for (
int comp = 0; comp < this->num_conservation_quantities_; ++comp) {
2531 well_q_s[comp] += cq_s[comp];
2534 const auto& comm = this->parallel_well_info_.communication();
2535 if (comm.size() > 1)
2537 comm.sum(well_q_s.data(), well_q_s.size());
2544 template <
typename TypeTag>
2545 std::vector<typename StandardWell<TypeTag>::Scalar>
2549 const int num_pri_vars = this->primary_variables_.numWellEq();
2550 std::vector<Scalar> retval(num_pri_vars);
2551 for (
int ii = 0; ii < num_pri_vars; ++ii) {
2552 retval[ii] = this->primary_variables_.value(ii);
2561 template <
typename TypeTag>
2566 const int num_pri_vars = this->primary_variables_.numWellEq();
2567 for (
int ii = 0; ii < num_pri_vars; ++ii) {
2568 this->primary_variables_.setValue(ii, it[ii]);
2570 return num_pri_vars;
2574 template <
typename TypeTag>
2578 const IntensiveQuantities& intQuants,
2581 auto fs = intQuants.fluidState();
2583 for (
unsigned phaseIdx = 0; phaseIdx < FluidSystem::numPhases; ++phaseIdx) {
2584 if (!FluidSystem::phaseIsActive(phaseIdx)) {
2589 EvalWell cq_r_thermal(this->primary_variables_.numWellEq() + Indices::numEq, 0.);
2590 const unsigned activeCompIdx = FluidSystem::canonicalToActiveCompIdx(FluidSystem::solventComponentIndex(phaseIdx));
2591 const bool both_oil_gas = FluidSystem::phaseIsActive(FluidSystem::oilPhaseIdx) && FluidSystem::phaseIsActive(FluidSystem::gasPhaseIdx);
2592 if (!both_oil_gas || FluidSystem::waterPhaseIdx == phaseIdx) {
2593 cq_r_thermal = cq_s[activeCompIdx] / this->extendEval(fs.invB(phaseIdx));
2596 const unsigned oilCompIdx = FluidSystem::canonicalToActiveCompIdx(FluidSystem::oilCompIdx);
2597 const unsigned gasCompIdx = FluidSystem::canonicalToActiveCompIdx(FluidSystem::gasCompIdx);
2602 const EvalWell d = this->extendEval(1.0 - fs.Rv() * fs.Rs());
2604 deferred_logger.
debug(
2605 fmt::format(
"Problematic d value {} obtained for well {}"
2606 " during calculateSinglePerf with rs {}"
2607 ", rv {}. Continue as if no dissolution (rs = 0) and"
2608 " vaporization (rv = 0) for this connection.",
2609 d, this->name(), fs.Rs(), fs.Rv()));
2610 cq_r_thermal = cq_s[activeCompIdx] / this->extendEval(fs.invB(phaseIdx));
2612 if (FluidSystem::gasPhaseIdx == phaseIdx) {
2613 cq_r_thermal = (cq_s[gasCompIdx] -
2614 this->extendEval(fs.Rs()) * cq_s[oilCompIdx]) /
2615 (d * this->extendEval(fs.invB(phaseIdx)) );
2616 }
else if (FluidSystem::oilPhaseIdx == phaseIdx) {
2618 cq_r_thermal = (cq_s[oilCompIdx] - this->extendEval(fs.Rv()) *
2620 (d * this->extendEval(fs.invB(phaseIdx)) );
2626 if (this->isInjector() && !this->wellIsStopped() && cq_r_thermal > 0.0){
2628 assert(this->well_ecl_.injectorType() != InjectorType::MULTI);
2629 fs.setTemperature(this->well_ecl_.inj_temperature());
2630 typedef typename std::decay<
decltype(fs)>::type::Scalar FsScalar;
2631 typename FluidSystem::template ParameterCache<FsScalar> paramCache;
2632 const unsigned pvtRegionIdx = intQuants.pvtRegionIndex();
2633 paramCache.setRegionIndex(pvtRegionIdx);
2634 paramCache.updatePhase(fs, phaseIdx);
2636 const auto& rho = FluidSystem::density(fs, paramCache, phaseIdx);
2637 fs.setDensity(phaseIdx, rho);
2638 const auto& h = FluidSystem::enthalpy(fs, paramCache, phaseIdx);
2639 fs.setEnthalpy(phaseIdx, h);
2640 cq_r_thermal *= this->extendEval(fs.enthalpy(phaseIdx)) * this->extendEval(fs.density(phaseIdx));
2641 result += getValue(cq_r_thermal);
2642 }
else if (cq_r_thermal > 0.0) {
2643 cq_r_thermal *= getValue(fs.enthalpy(phaseIdx)) * getValue(fs.density(phaseIdx));
2644 result += Base::restrictEval(cq_r_thermal);
2647 cq_r_thermal *= this->extendEval(fs.enthalpy(phaseIdx)) * this->extendEval(fs.density(phaseIdx));
2648 result += Base::restrictEval(cq_r_thermal);
2652 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: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:43
Scalar pressure_diff(const unsigned perf) const
Returns pressure drop for a given perforation.
Definition: StandardWellConnections.hpp:100
StdWellConnections connections_
Connection level values.
Definition: StandardWellEval.hpp:101
PrimaryVariables primary_variables_
Primary variables for well.
Definition: StandardWellEval.hpp:95
Definition: StandardWell.hpp:60
void calculateExplicitQuantities(const Simulator &simulator, const WellStateType &well_state, DeferredLogger &deferred_logger) override
Definition: StandardWell_impl.hpp:1405
EvalWell wpolymermw(const Scalar throughput, const EvalWell &water_velocity, DeferredLogger &deferred_logger) const
Definition: StandardWell_impl.hpp:2019
typename StdWellEval::EvalWell EvalWell
Definition: StandardWell.hpp:120
void updateWellStateFromPrimaryVariables(WellStateType &well_state, const SummaryState &summary_state, DeferredLogger &deferred_logger) const
Definition: StandardWell_impl.hpp:775
WellConnectionProps computePropertiesForWellConnectionPressures(const Simulator &simulator, const WellStateType &well_state) const
Definition: StandardWell_impl.hpp:1139
typename StdWellEval::BVectorWell BVectorWell
Definition: StandardWell.hpp:121
std::optional< Scalar > computeBhpAtThpLimitProd(const WellStateType &well_state, const Simulator &simulator, const SummaryState &summary_state, DeferredLogger &deferred_logger) const
Definition: StandardWell_impl.hpp:2211
void computeWellRatesWithThpAlqProd(const Simulator &ebos_simulator, const SummaryState &summary_state, DeferredLogger &deferred_logger, std::vector< Scalar > &potentials, Scalar alq) const
Definition: StandardWell_impl.hpp:1724
void addWellContributions(SparseMatrixAdapter &mat) const override
Definition: StandardWell_impl.hpp:1914
std::vector< Scalar > getPrimaryVars() const override
Definition: StandardWell_impl.hpp:2547
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:1922
void updateWaterMobilityWithPolymer(const Simulator &simulator, const int perf, std::vector< EvalWell > &mob_water, DeferredLogger &deferred_logger) const
Definition: StandardWell_impl.hpp:1850
void assembleWellEqWithoutIteration(const Simulator &simulator, const double dt, const Well::InjectionControls &inj_controls, const Well::ProductionControls &prod_controls, WellStateType &well_state, const GroupState< Scalar > &group_state, DeferredLogger &deferred_logger) override
Definition: StandardWell_impl.hpp:341
std::vector< Scalar > computeCurrentWellRates(const Simulator &ebosSimulator, DeferredLogger &deferred_logger) const override
Definition: StandardWell_impl.hpp:2511
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:496
void updatePrimaryVariablesNewton(const BVectorWell &dwells, const bool stop_or_zero_rate_target, DeferredLogger &deferred_logger)
Definition: StandardWell_impl.hpp:752
GetPropType< TypeTag, Properties::Scalar > Scalar
Definition: WellInterface.hpp:82
void computeWellConnectionPressures(const Simulator &simulator, const WellStateType &well_state, DeferredLogger &deferred_logger)
Definition: StandardWell_impl.hpp:1365
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
typename StdWellEval::StdWellConnections::Properties WellConnectionProps
Definition: StandardWell.hpp:264
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:2169
bool iterateWellEqWithSwitching(const Simulator &simulator, const double dt, const Well::InjectionControls &inj_controls, const Well::ProductionControls &prod_controls, WellStateType &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:2391
void computeWellRatesWithBhp(const Simulator &ebosSimulator, const Scalar &bhp, std::vector< Scalar > &well_flux, DeferredLogger &deferred_logger) const override
Definition: StandardWell_impl.hpp:1471
void getMobility(const Simulator &simulator, const int perf, std::vector< Value > &mob, DeferredLogger &deferred_logger) const
Definition: StandardWell_impl.hpp:674
void computeWellRatesWithBhpIterations(const Simulator &ebosSimulator, const Scalar &bhp, std::vector< Scalar > &well_flux, DeferredLogger &deferred_logger) const override
Definition: StandardWell_impl.hpp:1517
void updateIPR(const Simulator &simulator, DeferredLogger &deferred_logger) const override
Definition: StandardWell_impl.hpp:799
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:2226
void updateIPRImplicit(const Simulator &simulator, WellStateType &well_state, DeferredLogger &deferred_logger) override
Definition: StandardWell_impl.hpp:892
void computeWellConnectionDensitesPressures(const Simulator &simulator, const WellStateType &well_state, const WellConnectionProps &props, DeferredLogger &deferred_logger)
Definition: StandardWell_impl.hpp:1309
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:93
void updateWellState(const Simulator &simulator, const BVectorWell &dwells, WellStateType &well_state, DeferredLogger &deferred_logger)
Definition: StandardWell_impl.hpp:730
void handleInjectivityEquations(const Simulator &simulator, const WellStateType &well_state, const int perf, const EvalWell &water_flux_s, DeferredLogger &deferred_logger)
Definition: StandardWell_impl.hpp:2102
virtual void apply(const BVector &x, BVector &Ax) const override
Ax = Ax - C D^-1 B x.
Definition: StandardWell_impl.hpp:1419
virtual ConvergenceReport getWellConvergence(const Simulator &simulator, const WellStateType &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:1190
void checkConvergenceExtraEqs(const std::vector< Scalar > &res, ConvergenceReport &report) const
Definition: StandardWell_impl.hpp:2150
typename StdWellEval::Eval Eval
Definition: StandardWell.hpp:119
Scalar computeWellRatesAndBhpWithThpAlqProd(const Simulator &ebos_simulator, const SummaryState &summary_state, DeferredLogger &deferred_logger, std::vector< Scalar > &potentials, Scalar alq) const
Definition: StandardWell_impl.hpp:1695
bool openCrossFlowAvoidSingularity(const Simulator &simulator) const
Definition: StandardWell_impl.hpp:1128
std::optional< Scalar > computeBhpAtThpLimitInj(const Simulator &simulator, const SummaryState &summary_state, DeferredLogger &deferred_logger) const
Definition: StandardWell_impl.hpp:2312
bool allDrawDownWrongDirection(const Simulator &simulator) const
Definition: StandardWell_impl.hpp:1086
EvalWell pskin(const Scalar throughput, const EvalWell &water_velocity, const EvalWell &poly_inj_conc, DeferredLogger &deferred_logger) const
Definition: StandardWell_impl.hpp:1974
static constexpr int numWellConservationEq
Definition: StandardWell.hpp:96
int setPrimaryVars(typename std::vector< Scalar >::const_iterator it) override
Definition: StandardWell_impl.hpp:2564
void checkOperabilityUnderTHPLimit(const Simulator &simulator, const WellStateType &well_state, DeferredLogger &deferred_logger) override
Definition: StandardWell_impl.hpp:1037
void computeWellPotentials(const Simulator &simulator, const WellStateType &well_state, std::vector< Scalar > &well_potentials, DeferredLogger &deferred_logger) override
computing the well potentials for group control
Definition: StandardWell_impl.hpp:1741
bool computeWellPotentialsImplicit(const Simulator &ebos_simulator, const WellStateType &well_state, std::vector< Scalar > &well_potentials, DeferredLogger &deferred_logger) const
Definition: StandardWell_impl.hpp:1616
void updateWaterThroughput(const double dt, WellStateType &well_state) const override
Definition: StandardWell_impl.hpp:2048
void checkOperabilityUnderBHPLimit(const WellStateType &well_state, const Simulator &simulator, DeferredLogger &deferred_logger) override
Definition: StandardWell_impl.hpp:968
void recoverWellSolutionAndUpdateWellState(const Simulator &simulator, const BVector &x, WellStateType &well_state, DeferredLogger &deferred_logger) override
Definition: StandardWell_impl.hpp:1451
void assembleWellEqWithoutIterationImpl(const Simulator &simulator, const double dt, const Well::InjectionControls &inj_controls, const Well::ProductionControls &prod_controls, WellStateType &well_state, const GroupState< Scalar > &group_state, DeferredLogger &deferred_logger)
Definition: StandardWell_impl.hpp:367
bool iterateWellEqWithControl(const Simulator &simulator, const double dt, const Well::InjectionControls &inj_controls, const Well::ProductionControls &prod_controls, WellStateType &well_state, const GroupState< Scalar > &group_state, DeferredLogger &deferred_logger) override
Definition: StandardWell_impl.hpp:2344
EvalWell pskinwater(const Scalar throughput, const EvalWell &water_velocity, DeferredLogger &deferred_logger) const
Definition: StandardWell_impl.hpp:1942
void solveEqAndUpdateWellState(const Simulator &simulator, WellStateType &well_state, DeferredLogger &deferred_logger) override
Definition: StandardWell_impl.hpp:1383
void handleInjectivityRate(const Simulator &simulator, const int perf, std::vector< EvalWell > &cq_s) const
Definition: StandardWell_impl.hpp:2079
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
std::vector< Scalar > computeWellPotentialWithTHP(const Simulator &ebosSimulator, DeferredLogger &deferred_logger, const WellStateType &well_state) const
Definition: StandardWell_impl.hpp:1581
void updateProductivityIndex(const Simulator &simulator, const WellProdIndexCalculator< Scalar > &wellPICalc, WellStateType &well_state, DeferredLogger &deferred_logger) const override
Definition: StandardWell_impl.hpp:1234
void updatePrimaryVariables(const Simulator &simulator, const WellStateType &well_state, DeferredLogger &deferred_logger) override
Definition: StandardWell_impl.hpp:1816
Scalar getRefDensity() const override
Definition: StandardWell_impl.hpp:1839
Scalar connectionDensity(const int globalConnIdx, const int openConnIdx) const override
Definition: StandardWell_impl.hpp:1801
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:76
GetPropType< TypeTag, Properties::Simulator > Simulator
Definition: WellInterface.hpp:81
typename WellInterfaceFluidSystem< FluidSystem >::RateConverterType RateConverterType
Definition: WellInterface.hpp:103
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:1960
GetPropType< TypeTag, Properties::IntensiveQuantities > IntensiveQuantities
Definition: WellInterface.hpp:86
GetPropType< TypeTag, Properties::Scalar > Scalar
Definition: WellInterface.hpp:82
Dune::BlockVector< VectorBlockType > BVector
Definition: WellInterface.hpp:96
typename Base::ModelParameters ModelParameters
Definition: WellInterface.hpp:109
GetPropType< TypeTag, Properties::FluidSystem > FluidSystem
Definition: WellInterface.hpp:83
bool solveWellWithOperabilityCheck(const Simulator &simulator, const double dt, const Well::InjectionControls &inj_controls, const Well::ProductionControls &prod_controls, WellStateType &well_state, const GroupState< Scalar > &group_state, DeferredLogger &deferred_logger)
Definition: WellInterface_impl.hpp:566
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: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