22#ifndef OPM_MULTISEGMENTWELL_IMPL_HEADER_INCLUDED
23#define OPM_MULTISEGMENTWELL_IMPL_HEADER_INCLUDED
25#ifndef OPM_MULTISEGMENTWELL_HEADER_INCLUDED
27#include <opm/simulators/wells/MultisegmentWell.hpp>
30#include <opm/common/Exceptions.hpp>
31#include <opm/common/OpmLog/OpmLog.hpp>
33#include <opm/input/eclipse/Schedule/MSW/Segment.hpp>
34#include <opm/input/eclipse/Schedule/MSW/Valve.hpp>
35#include <opm/input/eclipse/Schedule/MSW/WellSegments.hpp>
36#include <opm/input/eclipse/Schedule/Well/Connection.hpp>
37#include <opm/input/eclipse/Schedule/Well/WellConnections.hpp>
39#include <opm/input/eclipse/Units/Units.hpp>
41#include <opm/material/densead/EvaluationFormat.hpp>
43#include <opm/simulators/wells/MultisegmentWellAssemble.hpp>
44#include <opm/simulators/wells/WellBhpThpCalculator.hpp>
45#include <opm/simulators/utils/DeferredLoggingErrorHelpers.hpp>
46#include <opm/simulators/wells/ParallelWellInfo.hpp>
52#if COMPILE_GPU_BRIDGE && (HAVE_CUDA || HAVE_OPENCL)
53#include <opm/simulators/linalg/gpubridge/WellContributions.hpp>
60 template <
typename TypeTag>
65 const ModelParameters& param,
66 const RateConverterType& rate_converter,
67 const int pvtRegionIdx,
68 const int num_conservation_quantities,
70 const int index_of_well,
72 : Base(well, pw_info, time_step, param, rate_converter, pvtRegionIdx, num_conservation_quantities, num_phases, index_of_well, perf_data)
75 , segment_fluid_initial_(this->numberOfSegments(), std::vector<Scalar>(this->num_conservation_quantities_, 0.0))
78 if constexpr (has_solvent) {
79 OPM_THROW(std::runtime_error,
"solvent is not supported by multisegment well yet");
82 if constexpr (has_polymer) {
83 OPM_THROW(std::runtime_error,
"polymer is not supported by multisegment well yet");
86 if constexpr (Base::has_energy) {
87 OPM_THROW(std::runtime_error,
"energy is not supported by multisegment well yet");
90 if constexpr (Base::has_foam) {
91 OPM_THROW(std::runtime_error,
"foam is not supported by multisegment well yet");
94 if constexpr (Base::has_brine) {
95 OPM_THROW(std::runtime_error,
"brine is not supported by multisegment well yet");
98 if constexpr (Base::has_watVapor) {
99 OPM_THROW(std::runtime_error,
"water evaporation is not supported by multisegment well yet");
102 if constexpr (Base::has_micp) {
103 OPM_THROW(std::runtime_error,
"MICP is not supported by multisegment well yet");
106 if(this->rsRvInj() > 0) {
107 OPM_THROW(std::runtime_error,
108 "dissolved gas/ vapporized oil in injected oil/gas not supported by multisegment well yet."
109 " \n See (WCONINJE item 10 / WCONHIST item 8)");
112 this->thp_update_iterations =
true;
119 template <
typename TypeTag>
121 MultisegmentWell<TypeTag>::
122 init(
const std::vector<Scalar>& depth_arg,
123 const Scalar gravity_arg,
124 const std::vector< Scalar >& B_avg,
125 const bool changed_to_open_this_step)
127 Base::init(depth_arg, gravity_arg, B_avg, changed_to_open_this_step);
139 this->initMatrixAndVectors(this->parallel_well_info_);
142 for (
int local_perf_index = 0; local_perf_index < this->number_of_local_perforations_; ++local_perf_index) {
144 const int cell_idx = this->well_cells_[local_perf_index];
146 this->cell_perforation_depth_diffs_[local_perf_index] = depth_arg[cell_idx] - this->perf_depth_[this->parallel_well_info_.localPerfToActivePerf(local_perf_index)];
154 template <
typename TypeTag>
156 MultisegmentWell<TypeTag>::
157 updatePrimaryVariables(
const GroupStateHelperType& groupStateHelper)
159 const auto& well_state = groupStateHelper.wellState();
160 const bool stop_or_zero_rate_target = this->stoppedOrZeroRateTarget(groupStateHelper);
161 this->primary_variables_.update(well_state, stop_or_zero_rate_target);
169 template <
typename TypeTag>
171 MultisegmentWell<TypeTag>::
172 scaleSegmentRatesAndPressure(WellStateType& well_state)
const
174 this->scaleSegmentRatesWithWellRates(this->
segments_.inlets(),
175 this->segments_.perforations(),
177 this->scaleSegmentPressuresWithBhp(well_state);
180 template <
typename TypeTag>
182 MultisegmentWell<TypeTag>::
183 updateWellStateWithTarget(
const Simulator& simulator,
184 const GroupStateHelperType& groupStateHelper,
185 WellStateType& well_state)
const
187 Base::updateWellStateWithTarget(simulator, groupStateHelper, well_state);
190 this->scaleSegmentRatesWithWellRates(this->
segments_.inlets(),
191 this->segments_.perforations(),
193 this->scaleSegmentPressuresWithBhp(well_state);
199 template <
typename TypeTag>
201 MultisegmentWell<TypeTag>::
202 getWellConvergence(
const GroupStateHelperType& groupStateHelper,
203 const std::vector<Scalar>& B_avg,
204 const bool relax_tolerance)
const
206 const auto& well_state = groupStateHelper.wellState();
211 this->param_.max_residual_allowed_,
212 this->param_.tolerance_wells_,
213 this->param_.relaxed_tolerance_flow_well_,
214 this->param_.tolerance_pressure_ms_wells_,
215 this->param_.relaxed_tolerance_pressure_ms_well_,
217 this->wellIsStopped());
225 template <
typename TypeTag>
227 MultisegmentWell<TypeTag>::
228 apply(
const BVector& x, BVector& Ax)
const
230 if (!this->isOperableAndSolvable() && !this->wellIsStopped()) {
234 if (this->param_.matrix_add_well_contributions_) {
246 template <
typename TypeTag>
248 MultisegmentWell<TypeTag>::
249 apply(BVector& r)
const
251 if (!this->isOperableAndSolvable() && !this->wellIsStopped()) {
260 template <
typename TypeTag>
262 MultisegmentWell<TypeTag>::
263 recoverWellSolutionAndUpdateWellState(
const Simulator& simulator,
265 const GroupStateHelperType& groupStateHelper,
266 WellStateType& well_state)
268 if (!this->isOperableAndSolvable() && !this->wellIsStopped()) {
275 this->
linSys_.recoverSolutionWell(x, xw);
277 updateWellState(simulator, xw, groupStateHelper, well_state);
279 catch (
const NumericalProblem& exp) {
283 deferred_logger.problem(
"In MultisegmentWell::recoverWellSolutionAndUpdateWellState for well "
284 + this->
name() +
": "+exp.what());
293 template <
typename TypeTag>
295 MultisegmentWell<TypeTag>::
296 computeWellPotentials(
const Simulator& simulator,
297 const WellStateType& well_state,
298 const GroupStateHelperType& groupStateHelper,
299 std::vector<Scalar>& well_potentials)
302 const auto [compute_potential, bhp_controlled_well] =
303 this->WellInterfaceGeneric<Scalar, IndexTraits>::computeWellPotentials(well_potentials, well_state);
305 if (!compute_potential) {
309 debug_cost_counter_ = 0;
310 bool converged_implicit =
false;
311 if (this->param_.local_well_solver_control_switching_) {
312 converged_implicit = computeWellPotentialsImplicit(simulator, groupStateHelper, well_potentials);
313 if (!converged_implicit) {
314 deferred_logger.debug(
"Implicit potential calculations failed for well "
315 + this->
name() +
", reverting to original aproach.");
318 if (!converged_implicit) {
320 const auto& summaryState = simulator.vanguard().summaryState();
322 computeWellRatesAtBhpLimit(simulator, groupStateHelper, well_potentials);
324 well_potentials = computeWellPotentialWithTHP(
325 well_state, simulator, groupStateHelper);
328 deferred_logger.debug(
"Cost in iterations of finding well potential for well "
329 + this->
name() +
": " + std::to_string(debug_cost_counter_));
331 this->checkNegativeWellPotentials(well_potentials,
332 this->param_.check_well_operability_,
339 template<
typename TypeTag>
343 const GroupStateHelperType& groupStateHelper,
344 std::vector<Scalar>& well_flux)
const
346 if (this->well_ecl_.isInjector()) {
347 const auto controls = this->well_ecl_.injectionControls(simulator.
vanguard().summaryState());
348 computeWellRatesWithBhpIterations(simulator, controls.bhp_limit, groupStateHelper, well_flux);
350 const auto controls = this->well_ecl_.productionControls(simulator.
vanguard().summaryState());
351 computeWellRatesWithBhpIterations(simulator, controls.bhp_limit, groupStateHelper, well_flux);
355 template<
typename TypeTag>
357 MultisegmentWell<TypeTag>::
358 computeWellRatesWithBhp(
const Simulator& simulator,
360 std::vector<Scalar>& well_flux,
361 DeferredLogger& deferred_logger)
const
363 const int np = this->number_of_phases_;
365 well_flux.resize(np, 0.0);
366 const bool allow_cf = this->getAllowCrossFlow();
367 const int nseg = this->numberOfSegments();
368 const WellStateType& well_state = simulator.problem().wellModel().wellState();
369 const auto& ws = well_state.well(this->indexOfWell());
370 auto segments_copy = ws.segments;
371 segments_copy.scale_pressure(bhp);
372 const auto& segment_pressure = segments_copy.pressure;
373 for (
int seg = 0; seg < nseg; ++seg) {
374 for (
const int perf : this->segments_.perforations()[seg]) {
375 const int local_perf_index = this->parallel_well_info_.activePerfToLocalPerf(perf);
376 if (local_perf_index < 0)
378 const int cell_idx = this->well_cells_[local_perf_index];
379 const auto& intQuants = simulator.model().intensiveQuantities(cell_idx, 0);
381 std::vector<Scalar> mob(this->num_conservation_quantities_, 0.);
382 getMobility(simulator, local_perf_index, mob, deferred_logger);
383 Scalar trans_mult(0.0);
384 getTransMult(trans_mult, simulator, cell_idx);
385 const auto& wellstate_nupcol = simulator.problem().wellModel().nupcolWellState().well(this->index_of_well_);
386 std::vector<Scalar> Tw(this->num_conservation_quantities_,
387 this->well_index_[local_perf_index] * trans_mult);
388 this->getTw(Tw, local_perf_index, intQuants, trans_mult, wellstate_nupcol);
389 const Scalar seg_pressure = segment_pressure[seg];
390 std::vector<Scalar> cq_s(this->num_conservation_quantities_, 0.);
391 Scalar perf_press = 0.0;
392 PerforationRates<Scalar> perf_rates;
393 computePerfRate(intQuants, mob, Tw, seg, perf, seg_pressure,
394 allow_cf, cq_s, perf_press, perf_rates, deferred_logger);
396 for(
int p = 0; p < np; ++p) {
397 well_flux[FluidSystem::activeCompToActivePhaseIdx(p)] += cq_s[p];
401 this->parallel_well_info_.communication().sum(well_flux.data(), well_flux.size());
405 template<
typename TypeTag>
407 MultisegmentWell<TypeTag>::
408 computeWellRatesWithBhpIterations(
const Simulator& simulator,
410 const GroupStateHelperType& groupStateHelper,
411 std::vector<Scalar>& well_flux)
const
416 MultisegmentWell<TypeTag> well_copy(*
this);
417 well_copy.resetDampening();
419 well_copy.debug_cost_counter_ = 0;
421 GroupStateHelperType groupStateHelper_copy = groupStateHelper;
423 WellStateType well_state_copy = groupStateHelper_copy.wellState();
424 auto guard = groupStateHelper_copy.pushWellState(well_state_copy);
425 auto& ws = well_state_copy.well(this->index_of_well_);
428 const auto& summary_state = simulator.vanguard().summaryState();
429 auto inj_controls = well_copy.well_ecl_.isInjector()
430 ? well_copy.well_ecl_.injectionControls(summary_state)
431 : Well::InjectionControls(0);
432 auto prod_controls = well_copy.well_ecl_.isProducer()
433 ? well_copy.well_ecl_.productionControls(summary_state) :
434 Well::ProductionControls(0);
437 if (well_copy.well_ecl_.isInjector()) {
438 inj_controls.bhp_limit = bhp;
439 ws.injection_cmode = Well::InjectorCMode::BHP;
441 prod_controls.bhp_limit = bhp;
442 ws.production_cmode = Well::ProducerCMode::BHP;
445 well_copy.scaleSegmentPressuresWithBhp(well_state_copy);
448 const int np = this->number_of_phases_;
450 for (
int phase = 0; phase < np; ++phase){
451 trivial = trivial && (ws.well_potentials[phase] == 0.0) ;
454 const Scalar sign = well_copy.well_ecl_.isInjector() ? 1.0 : -1.0;
455 for (
int phase = 0; phase < np; ++phase) {
456 ws.surface_rates[phase] = sign * ws.well_potentials[phase];
459 well_copy.scaleSegmentRatesWithWellRates(this->segments_.inlets(),
460 this->segments_.perforations(),
463 well_copy.calculateExplicitQuantities(simulator, groupStateHelper_copy);
464 const double dt = simulator.timeStepSize();
466 well_copy.iterateWellEqWithControl(simulator, dt, inj_controls, prod_controls, groupStateHelper_copy,
471 well_flux.resize(np, 0.0);
472 for (
int compIdx = 0; compIdx < this->num_conservation_quantities_; ++compIdx) {
473 const EvalWell rate = well_copy.primary_variables_.getQs(compIdx);
474 well_flux[FluidSystem::activeCompToActivePhaseIdx(compIdx)] = rate.value();
476 debug_cost_counter_ += well_copy.debug_cost_counter_;
481 template<
typename TypeTag>
482 std::vector<typename MultisegmentWell<TypeTag>::Scalar>
483 MultisegmentWell<TypeTag>::
484 computeWellPotentialWithTHP(
const WellStateType& well_state,
485 const Simulator& simulator,
486 const GroupStateHelperType& groupStateHelper)
const
488 auto& deferred_logger = groupStateHelper.deferredLogger();
489 std::vector<Scalar> potentials(this->number_of_phases_, 0.0);
490 const auto& summary_state = simulator.vanguard().summaryState();
492 const auto& well = this->well_ecl_;
493 if (well.isInjector()) {
494 auto bhp_at_thp_limit = computeBhpAtThpLimitInj(simulator, groupStateHelper, summary_state);
495 if (bhp_at_thp_limit) {
496 const auto& controls = well.injectionControls(summary_state);
497 const Scalar bhp = std::min(*bhp_at_thp_limit,
498 static_cast<Scalar
>(controls.bhp_limit));
499 computeWellRatesWithBhpIterations(simulator, bhp, groupStateHelper, potentials);
500 deferred_logger.debug(
"Converged thp based potential calculation for well "
501 + this->name() +
", at bhp = " + std::to_string(bhp));
503 deferred_logger.warning(
"FAILURE_GETTING_CONVERGED_POTENTIAL",
504 "Failed in getting converged thp based potential calculation for well "
505 + this->name() +
". Instead the bhp based value is used");
506 const auto& controls = well.injectionControls(summary_state);
507 const Scalar bhp = controls.bhp_limit;
508 computeWellRatesWithBhpIterations(simulator, bhp, groupStateHelper, potentials);
511 auto bhp_at_thp_limit = computeBhpAtThpLimitProd(
512 well_state, simulator, groupStateHelper, summary_state);
513 if (bhp_at_thp_limit) {
514 const auto& controls = well.productionControls(summary_state);
515 const Scalar bhp = std::max(*bhp_at_thp_limit,
516 static_cast<Scalar
>(controls.bhp_limit));
517 computeWellRatesWithBhpIterations(simulator, bhp, groupStateHelper, potentials);
518 deferred_logger.debug(
"Converged thp based potential calculation for well "
519 + this->name() +
", at bhp = " + std::to_string(bhp));
521 deferred_logger.warning(
"FAILURE_GETTING_CONVERGED_POTENTIAL",
522 "Failed in getting converged thp based potential calculation for well "
523 + this->name() +
". Instead the bhp based value is used");
524 const auto& controls = well.productionControls(summary_state);
525 const Scalar bhp = controls.bhp_limit;
526 computeWellRatesWithBhpIterations(simulator, bhp, groupStateHelper, potentials);
533 template<
typename TypeTag>
535 MultisegmentWell<TypeTag>::
536 computeWellPotentialsImplicit(
const Simulator& simulator,
537 const GroupStateHelperType& groupStateHelper,
538 std::vector<Scalar>& well_potentials)
const
543 MultisegmentWell<TypeTag> well_copy(*
this);
544 well_copy.debug_cost_counter_ = 0;
546 GroupStateHelperType groupStateHelper_copy = groupStateHelper;
548 WellStateType well_state_copy = groupStateHelper_copy.wellState();
549 auto guard = groupStateHelper_copy.pushWellState(well_state_copy);
550 auto& ws = well_state_copy.well(this->index_of_well_);
553 const auto& summary_state = simulator.vanguard().summaryState();
554 auto inj_controls = well_copy.well_ecl_.isInjector()
555 ? well_copy.well_ecl_.injectionControls(summary_state)
556 : Well::InjectionControls(0);
557 auto prod_controls = well_copy.well_ecl_.isProducer()
558 ? well_copy.well_ecl_.productionControls(summary_state)
559 : Well::ProductionControls(0);
562 well_copy.onlyKeepBHPandTHPcontrols(summary_state, well_state_copy, inj_controls, prod_controls);
564 well_copy.scaleSegmentPressuresWithBhp(well_state_copy);
567 const int np = this->number_of_phases_;
569 for (
int phase = 0; phase < np; ++phase){
570 trivial = trivial && (ws.well_potentials[phase] == 0.0) ;
573 const Scalar sign = well_copy.well_ecl_.isInjector() ? 1.0 : -1.0;
574 for (
int phase = 0; phase < np; ++phase) {
575 ws.surface_rates[phase] = sign * ws.well_potentials[phase];
578 well_copy.scaleSegmentRatesWithWellRates(this->segments_.inlets(),
579 this->segments_.perforations(),
582 well_copy.calculateExplicitQuantities(simulator, groupStateHelper_copy);
583 const double dt = simulator.timeStepSize();
585 bool converged =
false;
586 if (this->well_ecl_.isProducer()) {
587 converged = well_copy.solveWellWithOperabilityCheck(
588 simulator, dt, inj_controls, prod_controls, groupStateHelper_copy, well_state_copy
591 converged = well_copy.iterateWellEqWithSwitching(
592 simulator, dt, inj_controls, prod_controls, groupStateHelper_copy, well_state_copy,
600 well_potentials.clear();
601 well_potentials.resize(np, 0.0);
602 for (
int compIdx = 0; compIdx < this->num_conservation_quantities_; ++compIdx) {
603 const EvalWell rate = well_copy.primary_variables_.getQs(compIdx);
604 well_potentials[FluidSystem::activeCompToActivePhaseIdx(compIdx)] = rate.value();
606 debug_cost_counter_ += well_copy.debug_cost_counter_;
610 template <
typename TypeTag>
612 MultisegmentWell<TypeTag>::
613 solveEqAndUpdateWellState(
const Simulator& simulator,
614 const GroupStateHelperType& groupStateHelper,
615 WellStateType& well_state)
617 if (!this->isOperableAndSolvable() && !this->wellIsStopped())
return;
622 const BVectorWell dx_well = this->linSys_.solve();
623 updateWellState(simulator, dx_well, groupStateHelper, well_state);
625 catch(
const NumericalProblem& exp) {
629 auto& deferred_logger = groupStateHelper.deferredLogger();
630 deferred_logger.problem(
"In MultisegmentWell::solveEqAndUpdateWellState for well "
631 + this->name() +
": "+exp.what());
640 template <
typename TypeTag>
642 MultisegmentWell<TypeTag>::
643 computePerfCellPressDiffs(
const Simulator& simulator)
647 for (
int local_perf_index = 0; local_perf_index < this->number_of_local_perforations_; ++local_perf_index) {
650 std::vector<Scalar> kr(this->number_of_phases_, 0.0);
651 std::vector<Scalar> density(this->number_of_phases_, 0.0);
653 const int cell_idx = this->well_cells_[local_perf_index];
654 const auto& intQuants = simulator.model().intensiveQuantities(cell_idx, 0);
655 const auto& fs = intQuants.fluidState();
659 if (FluidSystem::phaseIsActive(FluidSystem::waterPhaseIdx)) {
660 const int water_pos = FluidSystem::canonicalToActivePhaseIdx(FluidSystem::waterPhaseIdx);
661 kr[water_pos] = intQuants.relativePermeability(FluidSystem::waterPhaseIdx).value();
662 sum_kr += kr[water_pos];
663 density[water_pos] = fs.density(FluidSystem::waterPhaseIdx).value();
666 if (FluidSystem::phaseIsActive(FluidSystem::oilPhaseIdx)) {
667 const int oil_pos = FluidSystem::canonicalToActivePhaseIdx(FluidSystem::oilPhaseIdx);
668 kr[oil_pos] = intQuants.relativePermeability(FluidSystem::oilPhaseIdx).value();
669 sum_kr += kr[oil_pos];
670 density[oil_pos] = fs.density(FluidSystem::oilPhaseIdx).value();
673 if (FluidSystem::phaseIsActive(FluidSystem::gasPhaseIdx)) {
674 const int gas_pos = FluidSystem::canonicalToActivePhaseIdx(FluidSystem::gasPhaseIdx);
675 kr[gas_pos] = intQuants.relativePermeability(FluidSystem::gasPhaseIdx).value();
676 sum_kr += kr[gas_pos];
677 density[gas_pos] = fs.density(FluidSystem::gasPhaseIdx).value();
680 assert(sum_kr != 0.);
683 Scalar average_density = 0.;
684 for (
int p = 0; p < this->number_of_phases_; ++p) {
685 average_density += kr[p] * density[p];
687 average_density /= sum_kr;
689 this->cell_perforation_pressure_diffs_[local_perf_index] = this->gravity_ * average_density * this->cell_perforation_depth_diffs_[local_perf_index];
697 template <
typename TypeTag>
699 MultisegmentWell<TypeTag>::
700 computeInitialSegmentFluids(
const Simulator& simulator,
701 DeferredLogger& deferred_logger)
703 for (
int seg = 0; seg < this->numberOfSegments(); ++seg) {
705 const Scalar surface_volume = getSegmentSurfaceVolume(simulator, seg, deferred_logger).value();
706 for (
int comp_idx = 0; comp_idx < this->num_conservation_quantities_; ++comp_idx) {
707 segment_fluid_initial_[seg][comp_idx] = surface_volume * this->primary_variables_.surfaceVolumeFraction(seg, comp_idx).value();
716 template <
typename TypeTag>
718 MultisegmentWell<TypeTag>::
719 updateWellState(
const Simulator& simulator,
720 const BVectorWell& dwells,
721 const GroupStateHelperType& groupStateHelper,
722 WellStateType& well_state,
723 const Scalar relaxation_factor)
725 if (!this->isOperableAndSolvable() && !this->wellIsStopped())
return;
727 auto& deferred_logger = groupStateHelper.deferredLogger();
729 const Scalar dFLimit = this->param_.dwell_fraction_max_;
730 const Scalar max_pressure_change = this->param_.max_pressure_change_ms_wells_;
731 const bool stop_or_zero_rate_target =
732 this->stoppedOrZeroRateTarget(groupStateHelper);
733 this->primary_variables_.updateNewton(dwells,
736 stop_or_zero_rate_target,
737 max_pressure_change);
739 const auto& summary_state = simulator.vanguard().summaryState();
740 this->primary_variables_.copyToWellState(*
this, getRefDensity(),
746 auto& ws = well_state.well(this->index_of_well_);
747 this->segments_.copyPhaseDensities(ws.segments);
751 const bool isThermal = simulator.vanguard().eclState().getSimulationConfig().isThermal();
752 const bool co2store = simulator.vanguard().eclState().runspec().co2Storage();
753 Base::calculateReservoirRates( (isThermal || co2store), well_state.well(this->index_of_well_));
760 template <
typename TypeTag>
762 MultisegmentWell<TypeTag>::
763 calculateExplicitQuantities(
const Simulator& simulator,
764 const GroupStateHelperType& groupStateHelper)
766 auto& deferred_logger = groupStateHelper.deferredLogger();
767 updatePrimaryVariables(groupStateHelper);
768 computePerfCellPressDiffs(simulator);
769 computeInitialSegmentFluids(simulator, deferred_logger);
776 template<
typename TypeTag>
778 MultisegmentWell<TypeTag>::
779 updateProductivityIndex(
const Simulator& simulator,
780 const WellProdIndexCalculator<Scalar>& wellPICalc,
781 WellStateType& well_state,
782 DeferredLogger& deferred_logger)
const
784 auto fluidState = [&simulator,
this](
const int local_perf_index)
786 const auto cell_idx = this->well_cells_[local_perf_index];
787 return simulator.model()
788 .intensiveQuantities(cell_idx, 0).fluidState();
791 const int np = this->number_of_phases_;
792 auto setToZero = [np](Scalar* x) ->
void
794 std::fill_n(x, np, 0.0);
797 auto addVector = [np](
const Scalar* src, Scalar* dest) ->
void
799 std::transform(src, src + np, dest, dest, std::plus<>{});
802 auto& ws = well_state.well(this->index_of_well_);
803 auto& perf_data = ws.perf_data;
804 auto* connPI = perf_data.prod_index.data();
805 auto* wellPI = ws.productivity_index.data();
809 const auto preferred_phase = this->well_ecl_.getPreferredPhase();
810 auto subsetPerfID = 0;
812 for (
const auto& perf : *this->perf_data_){
813 auto allPerfID = perf.ecl_index;
815 auto connPICalc = [&wellPICalc, allPerfID](
const Scalar mobility) -> Scalar
817 return wellPICalc.connectionProdIndStandard(allPerfID, mobility);
820 std::vector<Scalar> mob(this->num_conservation_quantities_, 0.0);
825 getMobility(simulator,
static_cast<int>(subsetPerfID), mob, deferred_logger);
827 const auto& fs = fluidState(subsetPerfID);
830 if (this->isInjector()) {
831 this->computeConnLevelInjInd(fs, preferred_phase, connPICalc,
832 mob, connPI, deferred_logger);
835 this->computeConnLevelProdInd(fs, connPICalc, mob, connPI);
838 addVector(connPI, wellPI);
845 const auto& comm = this->parallel_well_info_.communication();
846 if (comm.size() > 1) {
847 comm.sum(wellPI, np);
850 assert (
static_cast<int>(subsetPerfID) == this->number_of_local_perforations_ &&
851 "Internal logic error in processing connections for PI/II");
858 template<
typename TypeTag>
859 typename MultisegmentWell<TypeTag>::Scalar
860 MultisegmentWell<TypeTag>::
861 connectionDensity(
const int globalConnIdx,
862 [[maybe_unused]]
const int openConnIdx)
const
867 const auto segNum = this->wellEcl()
868 .getConnections()[globalConnIdx].segment();
870 const auto segIdx = this->wellEcl()
871 .getSegments().segmentNumberToIndex(segNum);
873 return this->segments_.density(segIdx).value();
880 template<
typename TypeTag>
882 MultisegmentWell<TypeTag>::
883 addWellContributions(SparseMatrixAdapter& jacobian)
const
885 if (this->number_of_local_perforations_ == 0) {
889 this->linSys_.extract(jacobian);
893 template<
typename TypeTag>
895 MultisegmentWell<TypeTag>::
896 addWellPressureEquations(PressureMatrix& jacobian,
897 const BVector& weights,
898 const int pressureVarIndex,
899 const bool use_well_weights,
900 const WellStateType& well_state)
const
902 if (this->number_of_local_perforations_ == 0) {
907 this->linSys_.extractCPRPressureMatrix(jacobian,
917 template<
typename TypeTag>
918 template<
class Value>
920 MultisegmentWell<TypeTag>::
921 computePerfRate(
const Value& pressure_cell,
924 const std::vector<Value>& b_perfcells,
925 const std::vector<Value>& mob_perfcells,
926 const std::vector<Value>& Tw,
928 const Value& segment_pressure,
929 const Value& segment_density,
930 const bool& allow_cf,
931 const std::vector<Value>& cmix_s,
932 std::vector<Value>& cq_s,
934 PerforationRates<Scalar>& perf_rates,
935 DeferredLogger& deferred_logger)
const
937 const int local_perf_index = this->parallel_well_info_.activePerfToLocalPerf(perf);
938 if (local_perf_index < 0)
942 const Value perf_seg_press_diff = this->gravity() * segment_density *
943 this->segments_.local_perforation_depth_diff(local_perf_index);
945 const Scalar cell_perf_press_diff = this->cell_perforation_pressure_diffs_[local_perf_index];
949 perf_press = segment_pressure + perf_seg_press_diff;
952 const Value cell_press_at_perf = pressure_cell - cell_perf_press_diff;
955 const Value drawdown = cell_press_at_perf - perf_press;
958 if (drawdown > 0.0) {
960 if (!allow_cf && this->isInjector()) {
965 for (
int comp_idx = 0; comp_idx < this->numConservationQuantities(); ++comp_idx) {
966 const Value cq_p = - Tw[comp_idx] * (mob_perfcells[comp_idx] * drawdown);
967 cq_s[comp_idx] = b_perfcells[comp_idx] * cq_p;
970 if (FluidSystem::phaseIsActive(FluidSystem::oilPhaseIdx) && FluidSystem::phaseIsActive(FluidSystem::gasPhaseIdx)) {
971 const unsigned oilCompIdx = FluidSystem::canonicalToActiveCompIdx(FluidSystem::oilCompIdx);
972 const unsigned gasCompIdx = FluidSystem::canonicalToActiveCompIdx(FluidSystem::gasCompIdx);
973 const Value cq_s_oil = cq_s[oilCompIdx];
974 const Value cq_s_gas = cq_s[gasCompIdx];
975 cq_s[gasCompIdx] += rs * cq_s_oil;
976 cq_s[oilCompIdx] += rv * cq_s_gas;
980 if (!allow_cf && this->isProducer()) {
985 Value total_mob = mob_perfcells[0];
986 for (
int comp_idx = 1; comp_idx < this->numConservationQuantities(); ++comp_idx) {
987 total_mob += mob_perfcells[comp_idx];
991 Value volume_ratio = 0.0;
992 if (FluidSystem::phaseIsActive(FluidSystem::waterPhaseIdx)) {
993 const unsigned waterCompIdx = FluidSystem::canonicalToActiveCompIdx(FluidSystem::waterCompIdx);
994 volume_ratio += cmix_s[waterCompIdx] / b_perfcells[waterCompIdx];
997 if (FluidSystem::phaseIsActive(FluidSystem::oilPhaseIdx) && FluidSystem::phaseIsActive(FluidSystem::gasPhaseIdx)) {
998 const unsigned oilCompIdx = FluidSystem::canonicalToActiveCompIdx(FluidSystem::oilCompIdx);
999 const unsigned gasCompIdx = FluidSystem::canonicalToActiveCompIdx(FluidSystem::gasCompIdx);
1004 const Value d = 1.0 - rv * rs;
1006 if (getValue(d) == 0.0) {
1007 OPM_DEFLOG_PROBLEM(NumericalProblem,
1008 fmt::format(
"Zero d value obtained for well {} "
1009 "during flux calculation with rs {} and rv {}",
1010 this->name(), rs, rv),
1014 const Value tmp_oil = (cmix_s[oilCompIdx] - rv * cmix_s[gasCompIdx]) / d;
1015 volume_ratio += tmp_oil / b_perfcells[oilCompIdx];
1017 const Value tmp_gas = (cmix_s[gasCompIdx] - rs * cmix_s[oilCompIdx]) / d;
1018 volume_ratio += tmp_gas / b_perfcells[gasCompIdx];
1020 if (FluidSystem::phaseIsActive(FluidSystem::oilPhaseIdx)) {
1021 const unsigned oilCompIdx = FluidSystem::canonicalToActiveCompIdx(FluidSystem::oilCompIdx);
1022 volume_ratio += cmix_s[oilCompIdx] / b_perfcells[oilCompIdx];
1024 if (FluidSystem::phaseIsActive(FluidSystem::gasPhaseIdx)) {
1025 const unsigned gasCompIdx = FluidSystem::canonicalToActiveCompIdx(FluidSystem::gasCompIdx);
1026 volume_ratio += cmix_s[gasCompIdx] / b_perfcells[gasCompIdx];
1030 for (
int componentIdx = 0; componentIdx < this->numConservationQuantities(); ++componentIdx) {
1031 const Value cqt_i = - Tw[componentIdx] * (total_mob * drawdown);
1032 Value cqt_is = cqt_i / volume_ratio;
1033 cq_s[componentIdx] = cmix_s[componentIdx] * cqt_is;
1038 if (this->isProducer()) {
1039 if (FluidSystem::phaseIsActive(FluidSystem::oilPhaseIdx) && FluidSystem::phaseIsActive(FluidSystem::gasPhaseIdx)) {
1040 const unsigned oilCompIdx = FluidSystem::canonicalToActiveCompIdx(FluidSystem::oilCompIdx);
1041 const unsigned gasCompIdx = FluidSystem::canonicalToActiveCompIdx(FluidSystem::gasCompIdx);
1050 const Scalar d = 1.0 - getValue(rv) * getValue(rs);
1053 perf_rates.vap_oil = getValue(rv) * (getValue(cq_s[gasCompIdx]) - getValue(rs) * getValue(cq_s[oilCompIdx])) / d;
1056 perf_rates.dis_gas = getValue(rs) * (getValue(cq_s[oilCompIdx]) - getValue(rv) * getValue(cq_s[gasCompIdx])) / d;
1061 template <
typename TypeTag>
1062 template<
class Value>
1064 MultisegmentWell<TypeTag>::
1065 computePerfRate(
const IntensiveQuantities& int_quants,
1066 const std::vector<Value>& mob_perfcells,
1067 const std::vector<Value>& Tw,
1070 const Value& segment_pressure,
1071 const bool& allow_cf,
1072 std::vector<Value>& cq_s,
1074 PerforationRates<Scalar>& perf_rates,
1075 DeferredLogger& deferred_logger)
const
1078 auto obtain = [
this](
const Eval& value)
1080 if constexpr (std::is_same_v<Value, Scalar>) {
1081 static_cast<void>(
this);
1082 return getValue(value);
1084 return this->extendEval(value);
1087 auto obtainN = [](
const auto& value)
1089 if constexpr (std::is_same_v<Value, Scalar>) {
1090 return getValue(value);
1095 const auto& fs = int_quants.fluidState();
1097 const Value pressure_cell = obtain(this->getPerfCellPressure(fs));
1098 const Value rs = obtain(fs.Rs());
1099 const Value rv = obtain(fs.Rv());
1102 std::vector<Value> b_perfcells(this->num_conservation_quantities_, 0.0);
1104 for (
unsigned phaseIdx = 0; phaseIdx < FluidSystem::numPhases; ++phaseIdx) {
1105 if (!FluidSystem::phaseIsActive(phaseIdx)) {
1109 const unsigned compIdx = FluidSystem::canonicalToActiveCompIdx(FluidSystem::solventComponentIndex(phaseIdx));
1110 b_perfcells[compIdx] = obtain(fs.invB(phaseIdx));
1113 std::vector<Value> cmix_s(this->numConservationQuantities(), 0.0);
1114 for (
int comp_idx = 0; comp_idx < this->numConservationQuantities(); ++comp_idx) {
1115 cmix_s[comp_idx] = obtainN(this->primary_variables_.surfaceVolumeFraction(seg, comp_idx));
1118 this->computePerfRate(pressure_cell,
1126 obtainN(this->segments_.density(seg)),
1135 template <
typename TypeTag>
1137 MultisegmentWell<TypeTag>::
1138 computeSegmentFluidProperties(
const Simulator& simulator, DeferredLogger& deferred_logger)
1147 EvalWell temperature;
1148 EvalWell saltConcentration;
1155 auto info = this->getFirstPerforationFluidStateInfo(simulator);
1156 temperature.setValue(std::get<0>(info));
1157 saltConcentration = this->extendEval(std::get<1>(info));
1159 this->segments_.computeFluidProperties(temperature,
1161 this->primary_variables_,
1165 template<
typename TypeTag>
1166 template<
class Value>
1168 MultisegmentWell<TypeTag>::
1169 getTransMult(Value& trans_mult,
1170 const Simulator& simulator,
1171 const int cell_idx)
const
1173 auto obtain = [
this](
const Eval& value)
1175 if constexpr (std::is_same_v<Value, Scalar>) {
1176 static_cast<void>(
this);
1177 return getValue(value);
1179 return this->extendEval(value);
1182 WellInterface<TypeTag>::getTransMult(trans_mult, simulator, cell_idx, obtain);
1185 template <
typename TypeTag>
1186 template<
class Value>
1188 MultisegmentWell<TypeTag>::
1189 getMobility(
const Simulator& simulator,
1190 const int local_perf_index,
1191 std::vector<Value>& mob,
1192 DeferredLogger& deferred_logger)
const
1194 auto obtain = [
this](
const Eval& value)
1196 if constexpr (std::is_same_v<Value, Scalar>) {
1197 static_cast<void>(
this);
1198 return getValue(value);
1200 return this->extendEval(value);
1204 WellInterface<TypeTag>::getMobility(simulator, local_perf_index, mob, obtain, deferred_logger);
1206 if (this->isInjector() && this->well_ecl_.getInjMultMode() != Well::InjMultMode::NONE) {
1207 const auto perf_ecl_index = this->perforationData()[local_perf_index].ecl_index;
1208 const Connection& con = this->well_ecl_.getConnections()[perf_ecl_index];
1209 const int seg = this->segmentNumberToIndex(con.segment());
1213 const Scalar segment_pres = this->primary_variables_.getSegmentPressure(seg).value();
1214 const Scalar perf_seg_press_diff = this->gravity() * this->segments_.density(seg).value()
1215 * this->segments_.local_perforation_depth_diff(local_perf_index);
1216 const Scalar perf_press = segment_pres + perf_seg_press_diff;
1217 const Scalar multiplier = this->getInjMult(local_perf_index, segment_pres, perf_press, deferred_logger);
1218 for (std::size_t i = 0; i < mob.size(); ++i) {
1219 mob[i] *= multiplier;
1226 template<
typename TypeTag>
1227 typename MultisegmentWell<TypeTag>::Scalar
1228 MultisegmentWell<TypeTag>::
1229 getRefDensity()
const
1231 return this->segments_.getRefDensity();
1234 template<
typename TypeTag>
1236 MultisegmentWell<TypeTag>::
1237 checkOperabilityUnderBHPLimit(
const WellStateType& ,
1238 const Simulator& simulator,
1239 DeferredLogger& deferred_logger)
1241 const auto& summaryState = simulator.vanguard().summaryState();
1242 const Scalar bhp_limit = WellBhpThpCalculator(*this).mostStrictBhpFromBhpLimits(summaryState);
1245 const bool bhp_limit_not_defaulted = bhp_limit > 1.5 * unit::barsa;
1246 if ( bhp_limit_not_defaulted || !this->wellHasTHPConstraints(summaryState) ) {
1249 Scalar total_ipr_mass_rate = 0.0;
1250 for (
unsigned phaseIdx = 0; phaseIdx < FluidSystem::numPhases; ++phaseIdx)
1252 if (!FluidSystem::phaseIsActive(phaseIdx)) {
1256 const unsigned compIdx = FluidSystem::canonicalToActiveCompIdx(FluidSystem::solventComponentIndex(phaseIdx));
1257 const Scalar ipr_rate = this->ipr_a_[compIdx] - this->ipr_b_[compIdx] * bhp_limit;
1259 const Scalar rho = FluidSystem::referenceDensity( phaseIdx, Base::pvtRegionIdx() );
1260 total_ipr_mass_rate += ipr_rate * rho;
1262 if ( (this->isProducer() && total_ipr_mass_rate < 0.) || (this->isInjector() && total_ipr_mass_rate > 0.) ) {
1263 this->operability_status_.operable_under_only_bhp_limit =
false;
1267 if (this->operability_status_.operable_under_only_bhp_limit && this->wellHasTHPConstraints(summaryState)) {
1271 std::vector<Scalar> well_rates_bhp_limit;
1272 computeWellRatesWithBhp(simulator, bhp_limit, well_rates_bhp_limit, deferred_logger);
1274 const Scalar thp_limit = this->getTHPConstraint(summaryState);
1275 const Scalar thp = WellBhpThpCalculator(*this).calculateThpFromBhp(well_rates_bhp_limit,
1277 this->getRefDensity(),
1278 this->wellEcl().alq_value(summaryState),
1281 if ( (this->isProducer() && thp < thp_limit) || (this->isInjector() && thp > thp_limit) ) {
1282 this->operability_status_.obey_thp_limit_under_bhp_limit =
false;
1293 this->operability_status_.operable_under_only_bhp_limit =
true;
1294 this->operability_status_.obey_thp_limit_under_bhp_limit =
false;
1300 template<
typename TypeTag>
1302 MultisegmentWell<TypeTag>::
1303 updateIPR(
const Simulator& simulator, DeferredLogger& deferred_logger)
const
1308 std::ranges::fill(this->ipr_a_, 0.0);
1309 std::ranges::fill(this->ipr_b_, 0.0);
1311 const int nseg = this->numberOfSegments();
1312 std::vector<Scalar> seg_dp(nseg, 0.0);
1313 for (
int seg = 0; seg < nseg; ++seg) {
1315 const Scalar dp = this->getSegmentDp(seg,
1316 this->segments_.density(seg).value(),
1319 for (
const int perf : this->segments_.perforations()[seg]) {
1320 const int local_perf_index = this->parallel_well_info_.activePerfToLocalPerf(perf);
1321 if (local_perf_index < 0)
1323 std::vector<Scalar> mob(this->num_conservation_quantities_, 0.0);
1326 getMobility(simulator, local_perf_index, mob, deferred_logger);
1328 const int cell_idx = this->well_cells_[local_perf_index];
1329 const auto& int_quantities = simulator.model().intensiveQuantities(cell_idx, 0);
1330 const auto& fs = int_quantities.fluidState();
1332 const Scalar perf_seg_press_diff = this->segments_.getPressureDiffSegLocalPerf(seg, local_perf_index);
1334 const Scalar cell_perf_press_diff = this->cell_perforation_pressure_diffs_[local_perf_index];
1335 const Scalar pressure_cell = this->getPerfCellPressure(fs).value();
1338 std::vector<Scalar> b_perf(this->num_conservation_quantities_);
1339 for (std::size_t phase = 0; phase < FluidSystem::numPhases; ++phase) {
1340 if (!FluidSystem::phaseIsActive(phase)) {
1343 const unsigned comp_idx = FluidSystem::canonicalToActiveCompIdx(FluidSystem::solventComponentIndex(phase));
1344 b_perf[comp_idx] = fs.invB(phase).value();
1348 const Scalar h_perf = cell_perf_press_diff + perf_seg_press_diff + dp;
1349 const Scalar pressure_diff = pressure_cell - h_perf;
1352 if ( (this->isProducer() && pressure_diff < 0.) || (this->isInjector() && pressure_diff > 0.) ) {
1353 deferred_logger.debug(
"CROSSFLOW_IPR",
1354 "cross flow found when updateIPR for well " + this->name());
1358 Scalar trans_mult(0.0);
1359 getTransMult(trans_mult, simulator, cell_idx);
1360 const auto& wellstate_nupcol = simulator.problem().wellModel().nupcolWellState().well(this->index_of_well_);
1361 std::vector<Scalar> tw_perf(this->num_conservation_quantities_, this->well_index_[perf] * trans_mult);
1362 this->getTw(tw_perf, local_perf_index, int_quantities, trans_mult, wellstate_nupcol);
1363 std::vector<Scalar> ipr_a_perf(this->ipr_a_.size());
1364 std::vector<Scalar> ipr_b_perf(this->ipr_b_.size());
1365 for (
int comp_idx = 0; comp_idx < this->num_conservation_quantities_; ++comp_idx) {
1366 const Scalar tw_mob = tw_perf[comp_idx] * mob[comp_idx] * b_perf[comp_idx];
1367 ipr_a_perf[comp_idx] += tw_mob * pressure_diff;
1368 ipr_b_perf[comp_idx] += tw_mob;
1372 if (FluidSystem::phaseIsActive(FluidSystem::oilPhaseIdx) && FluidSystem::phaseIsActive(FluidSystem::gasPhaseIdx)) {
1373 const unsigned oil_comp_idx = FluidSystem::canonicalToActiveCompIdx(FluidSystem::oilCompIdx);
1374 const unsigned gas_comp_idx = FluidSystem::canonicalToActiveCompIdx(FluidSystem::gasCompIdx);
1375 const Scalar rs = (fs.Rs()).value();
1376 const Scalar rv = (fs.Rv()).value();
1378 const Scalar dis_gas_a = rs * ipr_a_perf[oil_comp_idx];
1379 const Scalar vap_oil_a = rv * ipr_a_perf[gas_comp_idx];
1381 ipr_a_perf[gas_comp_idx] += dis_gas_a;
1382 ipr_a_perf[oil_comp_idx] += vap_oil_a;
1384 const Scalar dis_gas_b = rs * ipr_b_perf[oil_comp_idx];
1385 const Scalar vap_oil_b = rv * ipr_b_perf[gas_comp_idx];
1387 ipr_b_perf[gas_comp_idx] += dis_gas_b;
1388 ipr_b_perf[oil_comp_idx] += vap_oil_b;
1391 for (std::size_t comp_idx = 0; comp_idx < ipr_a_perf.size(); ++comp_idx) {
1392 this->ipr_a_[comp_idx] += ipr_a_perf[comp_idx];
1393 this->ipr_b_[comp_idx] += ipr_b_perf[comp_idx];
1397 this->parallel_well_info_.communication().sum(this->ipr_a_.data(), this->ipr_a_.size());
1398 this->parallel_well_info_.communication().sum(this->ipr_b_.data(), this->ipr_b_.size());
1401 template<
typename TypeTag>
1403 MultisegmentWell<TypeTag>::
1404 updateIPRImplicit(
const Simulator& simulator,
1405 const GroupStateHelperType& groupStateHelper,
1406 WellStateType& well_state)
1408 auto& deferred_logger = groupStateHelper.deferredLogger();
1416 auto rates = well_state.well(this->index_of_well_).surface_rates;
1418 for (std::size_t p = 0; p < rates.size(); ++p) {
1419 zero_rates &= rates[p] == 0.0;
1421 auto& ws = well_state.well(this->index_of_well_);
1423 const auto msg = fmt::format(
"updateIPRImplicit: Well {} has zero rate, IPRs might be problematic", this->name());
1424 deferred_logger.debug(msg);
1437 std::ranges::fill(ws.implicit_ipr_a, 0.0);
1438 std::ranges::fill(ws.implicit_ipr_b, 0.0);
1440 auto inj_controls = Well::InjectionControls(0);
1441 auto prod_controls = Well::ProductionControls(0);
1442 prod_controls.addControl(Well::ProducerCMode::BHP);
1443 prod_controls.bhp_limit = well_state.well(this->index_of_well_).bhp;
1446 const auto cmode = ws.production_cmode;
1447 ws.production_cmode = Well::ProducerCMode::BHP;
1448 const double dt = simulator.timeStepSize();
1449 assembleWellEqWithoutIteration(simulator, groupStateHelper, dt, inj_controls, prod_controls, well_state,
1452 BVectorWell rhs(this->numberOfSegments());
1454 rhs[0][SPres] = -1.0;
1456 const BVectorWell x_well = this->linSys_.solve(rhs);
1457 constexpr int num_eq = MSWEval::numWellEq;
1458 for (
int comp_idx = 0; comp_idx < this->num_conservation_quantities_; ++comp_idx){
1459 const EvalWell comp_rate = this->primary_variables_.getQs(comp_idx);
1460 const int idx = FluidSystem::activeCompToActivePhaseIdx(comp_idx);
1461 for (
size_t pvIdx = 0; pvIdx < num_eq; ++pvIdx) {
1463 ws.implicit_ipr_b[idx] -= x_well[0][pvIdx]*comp_rate.derivative(pvIdx+Indices::numEq);
1465 ws.implicit_ipr_a[idx] = ws.implicit_ipr_b[idx]*ws.bhp - comp_rate.value();
1468 ws.production_cmode = cmode;
1471 template<
typename TypeTag>
1473 MultisegmentWell<TypeTag>::
1474 checkOperabilityUnderTHPLimit(
const Simulator& simulator,
1475 const WellStateType& well_state,
1476 const GroupStateHelperType& groupStateHelper)
1478 auto& deferred_logger = groupStateHelper.deferredLogger();
1479 const auto& summaryState = simulator.vanguard().summaryState();
1480 const auto obtain_bhp = this->isProducer()
1481 ? computeBhpAtThpLimitProd(
1482 well_state, simulator, groupStateHelper, summaryState)
1483 : computeBhpAtThpLimitInj(simulator, groupStateHelper, summaryState);
1486 this->operability_status_.can_obtain_bhp_with_thp_limit =
true;
1488 const Scalar bhp_limit = WellBhpThpCalculator(*this).mostStrictBhpFromBhpLimits(summaryState);
1489 this->operability_status_.obey_bhp_limit_with_thp_limit = (*obtain_bhp >= bhp_limit);
1491 const Scalar thp_limit = this->getTHPConstraint(summaryState);
1492 if (this->isProducer() && *obtain_bhp < thp_limit) {
1493 const std::string msg =
" obtained bhp " + std::to_string(unit::convert::to(*obtain_bhp, unit::barsa))
1494 +
" bars is SMALLER than thp limit "
1495 + std::to_string(unit::convert::to(thp_limit, unit::barsa))
1496 +
" bars as a producer for well " + this->name();
1497 deferred_logger.debug(msg);
1499 else if (this->isInjector() && *obtain_bhp > thp_limit) {
1500 const std::string msg =
" obtained bhp " + std::to_string(unit::convert::to(*obtain_bhp, unit::barsa))
1501 +
" bars is LARGER than thp limit "
1502 + std::to_string(unit::convert::to(thp_limit, unit::barsa))
1503 +
" bars as a injector for well " + this->name();
1504 deferred_logger.debug(msg);
1509 this->operability_status_.can_obtain_bhp_with_thp_limit =
false;
1510 this->operability_status_.obey_bhp_limit_with_thp_limit =
false;
1511 if (!this->wellIsStopped()) {
1512 const Scalar thp_limit = this->getTHPConstraint(summaryState);
1513 deferred_logger.debug(
" could not find bhp value at thp limit "
1514 + std::to_string(unit::convert::to(thp_limit, unit::barsa))
1515 +
" bar for well " + this->name() +
", the well might need to be closed ");
1524 template<
typename TypeTag>
1526 MultisegmentWell<TypeTag>::
1527 iterateWellEqWithControl(
const Simulator& simulator,
1529 const Well::InjectionControls& inj_controls,
1530 const Well::ProductionControls& prod_controls,
1531 const GroupStateHelperType& groupStateHelper,
1532 WellStateType& well_state)
1534 if (!this->isOperableAndSolvable() && !this->wellIsStopped())
return true;
1536 auto& deferred_logger = groupStateHelper.deferredLogger();
1538 const int max_iter_number = this->param_.max_inner_iter_ms_wells_;
1542 const auto& [isFinite, residuals] = this->getFiniteWellResiduals(Base::B_avg_, deferred_logger);
1547 updatePrimaryVariables(groupStateHelper);
1549 std::vector<std::vector<Scalar> > residual_history;
1550 std::vector<Scalar> measure_history;
1553 Scalar relaxation_factor = 1.;
1554 bool converged =
false;
1555 bool relax_convergence =
false;
1556 this->regularize_ =
false;
1557 for (; it < max_iter_number; ++it, ++debug_cost_counter_) {
1559 if (it > this->param_.strict_inner_iter_wells_) {
1560 relax_convergence =
true;
1561 this->regularize_ =
true;
1564 assembleWellEqWithoutIteration(simulator, groupStateHelper, dt, inj_controls, prod_controls,
1568 const auto report = getWellConvergence(groupStateHelper, Base::B_avg_, relax_convergence);
1569 if (report.converged()) {
1576 const auto& [isFinite, residuals] = this->getFiniteWellResiduals(Base::B_avg_, deferred_logger);
1580 residual_history.push_back(residuals);
1581 measure_history.push_back(this->getResidualMeasureValue(well_state,
1582 residual_history[it],
1583 this->param_.tolerance_wells_,
1584 this->param_.tolerance_pressure_ms_wells_,
1587 bool min_relaxation_reached = this->update_relaxation_factor(measure_history, relaxation_factor, this->regularize_, deferred_logger);
1588 if (min_relaxation_reached || this->repeatedStagnation(measure_history, this->regularize_, deferred_logger)) {
1590 const auto reportStag = getWellConvergence(groupStateHelper, Base::B_avg_,
true);
1591 if (reportStag.converged()) {
1593 std::string message = fmt::format(
"Well stagnates/oscillates but {} manages to get converged with relaxed tolerances in {} inner iterations."
1595 deferred_logger.debug(message);
1602 BVectorWell dx_well;
1604 dx_well = this->linSys_.solve();
1605 updateWellState(simulator, dx_well, groupStateHelper, well_state, relaxation_factor);
1607 catch(
const NumericalProblem& exp) {
1611 deferred_logger.problem(
"In MultisegmentWell::iterateWellEqWithControl for well "
1612 + this->name() +
": "+exp.what());
1619 std::ostringstream sstr;
1620 sstr <<
" Well " << this->name() <<
" converged in " << it <<
" inner iterations.";
1621 if (relax_convergence)
1622 sstr <<
" (A relaxed tolerance was used after "<< this->param_.strict_inner_iter_wells_ <<
" iterations)";
1626 deferred_logger.debug(sstr.str(), OpmLog::defaultDebugVerbosityLevel + (it == 0));
1628 std::ostringstream sstr;
1629 sstr <<
" Well " << this->name() <<
" did not converge in " << it <<
" inner iterations.";
1630#define EXTRA_DEBUG_MSW 0
1632 sstr <<
"***** Outputting the residual history for well " << this->name() <<
" during inner iterations:";
1633 for (
int i = 0; i < it; ++i) {
1634 const auto& residual = residual_history[i];
1635 sstr <<
" residual at " << i <<
"th iteration ";
1636 for (
const auto& res : residual) {
1639 sstr <<
" " << measure_history[i] <<
" \n";
1642#undef EXTRA_DEBUG_MSW
1643 deferred_logger.debug(sstr.str());
1650 template<
typename TypeTag>
1652 MultisegmentWell<TypeTag>::
1653 iterateWellEqWithSwitching(
const Simulator& simulator,
1655 const Well::InjectionControls& inj_controls,
1656 const Well::ProductionControls& prod_controls,
1657 const GroupStateHelperType& groupStateHelper,
1658 WellStateType& well_state,
1659 const bool fixed_control ,
1660 const bool fixed_status ,
1661 const bool solving_with_zero_rate )
1663 auto& deferred_logger = groupStateHelper.deferredLogger();
1665 const int max_iter_number = this->param_.max_inner_iter_ms_wells_;
1669 const auto& [isFinite, residuals] = this->getFiniteWellResiduals(Base::B_avg_, deferred_logger);
1674 updatePrimaryVariables(groupStateHelper);
1676 std::vector<std::vector<Scalar> > residual_history;
1677 std::vector<Scalar> measure_history;
1680 Scalar relaxation_factor = 1.;
1681 bool converged =
false;
1682 bool relax_convergence =
false;
1683 this->regularize_ =
false;
1684 const auto& summary_state = groupStateHelper.summaryState();
1689 const int min_its_after_switch = 3;
1691 const int max_status_switch = this->param_.max_well_status_switch_inner_iter_;
1692 int its_since_last_switch = min_its_after_switch;
1693 int switch_count= 0;
1694 int status_switch_count = 0;
1696 const auto well_status_orig = this->wellStatus_;
1697 const auto operability_orig = this->operability_status_;
1698 auto well_status_cur = well_status_orig;
1700 const bool allow_open = well_state.well(this->index_of_well_).status == WellStatus::OPEN;
1702 const bool allow_switching = !this->wellUnderZeroRateTarget(groupStateHelper) &&
1703 (!fixed_control || !fixed_status) && allow_open;
1704 bool final_check =
false;
1706 this->operability_status_.resetOperability();
1707 this->operability_status_.solvable =
true;
1709 for (; it < max_iter_number; ++it, ++debug_cost_counter_) {
1710 ++its_since_last_switch;
1711 if (allow_switching && its_since_last_switch >= min_its_after_switch && status_switch_count < max_status_switch){
1712 const Scalar wqTotal = this->primary_variables_.getWQTotal().value();
1713 bool changed = this->updateWellControlAndStatusLocalIteration(
1714 simulator, groupStateHelper, inj_controls, prod_controls, wqTotal,
1715 well_state, fixed_control, fixed_status,
1716 solving_with_zero_rate
1719 its_since_last_switch = 0;
1721 if (well_status_cur != this->wellStatus_) {
1722 well_status_cur = this->wellStatus_;
1723 status_switch_count++;
1726 if (!changed && final_check) {
1729 final_check =
false;
1731 if (status_switch_count == max_status_switch) {
1732 this->wellStatus_ = well_status_orig;
1736 if (it > this->param_.strict_inner_iter_wells_) {
1737 relax_convergence =
true;
1738 this->regularize_ =
true;
1741 assembleWellEqWithoutIteration(simulator, groupStateHelper, dt, inj_controls, prod_controls,
1742 well_state, solving_with_zero_rate);
1745 const auto report = getWellConvergence(groupStateHelper, Base::B_avg_, relax_convergence);
1746 converged = report.converged();
1747 if (this->parallel_well_info_.communication().size() > 1 &&
1748 this->parallel_well_info_.communication().max(converged) != this->parallel_well_info_.communication().min(converged)) {
1749 OPM_THROW(std::runtime_error, fmt::format(
"Misalignment of the parallel simulation run in iterateWellEqWithSwitching - the well calculation for well {} succeeded some ranks but failed on other ranks.", this->name()));
1754 if (switch_count > 0 && its_since_last_switch < min_its_after_switch) {
1756 its_since_last_switch = min_its_after_switch;
1764 const auto& [isFinite, residuals] = this->getFiniteWellResiduals(Base::B_avg_, deferred_logger);
1770 residual_history.push_back(residuals);
1774 measure_history.push_back(this->getResidualMeasureValue(well_state,
1775 residual_history[it],
1776 this->param_.tolerance_wells_,
1777 this->param_.tolerance_pressure_ms_wells_,
1779 bool min_relaxation_reached = this->update_relaxation_factor(measure_history, relaxation_factor, this->regularize_, deferred_logger);
1780 if (min_relaxation_reached || this->repeatedStagnation(measure_history, this->regularize_, deferred_logger)) {
1786 const BVectorWell dx_well = this->linSys_.solve();
1787 updateWellState(simulator, dx_well, groupStateHelper, well_state, relaxation_factor);
1789 catch(
const NumericalProblem& exp) {
1793 deferred_logger.problem(
"In MultisegmentWell::iterateWellEqWithSwitching for well "
1794 + this->name() +
": "+exp.what());
1800 if (allow_switching){
1802 const bool is_stopped = this->wellIsStopped();
1803 if (this->wellHasTHPConstraints(summary_state)){
1804 this->operability_status_.can_obtain_bhp_with_thp_limit = !is_stopped;
1805 this->operability_status_.obey_thp_limit_under_bhp_limit = !is_stopped;
1807 this->operability_status_.operable_under_only_bhp_limit = !is_stopped;
1810 std::string message = fmt::format(
" Well {} converged in {} inner iterations ("
1811 "{} control/status switches).", this->name(), it, switch_count);
1812 if (relax_convergence) {
1813 message.append(fmt::format(
" (A relaxed tolerance was used after {} iterations)",
1814 this->param_.strict_inner_iter_wells_));
1816 deferred_logger.debug(message, OpmLog::defaultDebugVerbosityLevel + ((it == 0) && (switch_count == 0)));
1818 this->wellStatus_ = well_status_orig;
1819 this->operability_status_ = operability_orig;
1820 const std::string message = fmt::format(
" Well {} did not converge in {} inner iterations ("
1821 "{} switches, {} status changes).", this->name(), it, switch_count, status_switch_count);
1822 deferred_logger.debug(message);
1823 this->primary_variables_.outputLowLimitPressureSegments(deferred_logger);
1830 template<
typename TypeTag>
1832 MultisegmentWell<TypeTag>::
1833 assembleWellEqWithoutIteration(
const Simulator& simulator,
1834 const GroupStateHelperType& groupStateHelper,
1836 const Well::InjectionControls& inj_controls,
1837 const Well::ProductionControls& prod_controls,
1838 WellStateType& well_state,
1839 const bool solving_with_zero_rate)
1841 if (!this->isOperableAndSolvable() && !this->wellIsStopped())
return;
1843 auto& deferred_logger = groupStateHelper.deferredLogger();
1846 this->segments_.updateUpwindingSegments(this->primary_variables_);
1849 computeSegmentFluidProperties(simulator, deferred_logger);
1852 this->linSys_.clear();
1854 auto& ws = well_state.well(this->index_of_well_);
1855 ws.phase_mixing_rates.fill(0.0);
1862 const bool allow_cf = this->getAllowCrossFlow() || openCrossFlowAvoidSingularity(simulator);
1864 const int nseg = this->numberOfSegments();
1866 const Scalar rhow = FluidSystem::phaseIsActive(FluidSystem::waterPhaseIdx) ?
1867 FluidSystem::referenceDensity( FluidSystem::waterPhaseIdx, Base::pvtRegionIdx() ) : 0.0;
1868 const unsigned watCompIdx = FluidSystem::phaseIsActive(FluidSystem::waterPhaseIdx) ?
1869 FluidSystem::canonicalToActiveCompIdx(FluidSystem::waterCompIdx) : 0;
1871 for (
int seg = 0; seg < nseg; ++seg) {
1873 const EvalWell seg_pressure = this->primary_variables_.getSegmentPressure(seg);
1874 auto& perf_data = ws.perf_data;
1875 auto& perf_rates = perf_data.phase_rates;
1876 auto& perf_press_state = perf_data.pressure;
1877 for (
const int perf : this->segments_.perforations()[seg]) {
1878 const int local_perf_index = this->parallel_well_info_.activePerfToLocalPerf(perf);
1879 if (local_perf_index < 0)
1881 const int cell_idx = this->well_cells_[local_perf_index];
1882 const auto& int_quants = simulator.model().intensiveQuantities(cell_idx, 0);
1883 std::vector<EvalWell> mob(this->num_conservation_quantities_, 0.0);
1884 getMobility(simulator, local_perf_index, mob, deferred_logger);
1885 EvalWell trans_mult(0.0);
1886 getTransMult(trans_mult, simulator, cell_idx);
1887 const auto& wellstate_nupcol = simulator.problem().wellModel().nupcolWellState().well(this->index_of_well_);
1888 std::vector<EvalWell> Tw(this->num_conservation_quantities_, this->well_index_[local_perf_index] * trans_mult);
1889 this->getTw(Tw, local_perf_index, int_quants, trans_mult, wellstate_nupcol);
1890 std::vector<EvalWell> cq_s(this->num_conservation_quantities_, 0.0);
1891 EvalWell perf_press;
1892 PerforationRates<Scalar> perfRates;
1893 computePerfRate(int_quants, mob, Tw, seg, perf, seg_pressure,
1894 allow_cf, cq_s, perf_press, perfRates, deferred_logger);
1897 if (this->isProducer()) {
1898 ws.phase_mixing_rates[ws.dissolved_gas] += perfRates.dis_gas;
1899 ws.phase_mixing_rates[ws.vaporized_oil] += perfRates.vap_oil;
1900 perf_data.phase_mixing_rates[local_perf_index][ws.dissolved_gas] = perfRates.dis_gas;
1901 perf_data.phase_mixing_rates[local_perf_index][ws.vaporized_oil] = perfRates.vap_oil;
1905 for (
int comp_idx = 0; comp_idx < this->num_conservation_quantities_; ++comp_idx) {
1906 perf_rates[local_perf_index*this->number_of_phases_ + FluidSystem::activeCompToActivePhaseIdx(comp_idx)] = cq_s[comp_idx].value();
1908 perf_press_state[local_perf_index] = perf_press.value();
1911 if (FluidSystem::phaseIsActive(FluidSystem::waterPhaseIdx)) {
1912 perf_data.wat_mass_rates[local_perf_index] = cq_s[watCompIdx].value() * rhow;
1915 for (
int comp_idx = 0; comp_idx < this->num_conservation_quantities_; ++comp_idx) {
1917 const EvalWell cq_s_effective = cq_s[comp_idx] * this->well_efficiency_factor_;
1919 this->connectionRates_[local_perf_index][comp_idx] = Base::restrictEval(cq_s_effective);
1921 MultisegmentWellAssemble(*this).
1922 assemblePerforationEq(seg, local_perf_index, comp_idx, cq_s_effective, this->linSys_);
1928 const auto& comm = this->parallel_well_info_.communication();
1929 comm.sum(ws.phase_mixing_rates.data(), ws.phase_mixing_rates.size());
1932 if (this->parallel_well_info_.communication().size() > 1) {
1934 this->linSys_.sumDistributed(this->parallel_well_info_.communication());
1936 for (
int seg = 0; seg < nseg; ++seg) {
1940 const EvalWell segment_surface_volume = getSegmentSurfaceVolume(simulator, seg, deferred_logger);
1945 const Scalar regularization_factor = this->regularize_? this->param_.regularization_factor_wells_ : 1.0;
1947 for (
int comp_idx = 0; comp_idx < this->num_conservation_quantities_; ++comp_idx) {
1948 const EvalWell accumulation_term = regularization_factor * (segment_surface_volume * this->primary_variables_.surfaceVolumeFraction(seg, comp_idx)
1949 - segment_fluid_initial_[seg][comp_idx]) / dt;
1950 MultisegmentWellAssemble(*this).
1951 assembleAccumulationTerm(seg, comp_idx, accumulation_term, this->linSys_);
1956 const int seg_upwind = this->segments_.upwinding_segment(seg);
1957 for (
int comp_idx = 0; comp_idx < this->num_conservation_quantities_; ++comp_idx) {
1958 const EvalWell segment_rate =
1959 this->primary_variables_.getSegmentRateUpwinding(seg,
1962 this->well_efficiency_factor_;
1963 MultisegmentWellAssemble(*this).
1964 assembleOutflowTerm(seg, seg_upwind, comp_idx, segment_rate, this->linSys_);
1970 for (
const int inlet : this->segments_.inlets()[seg]) {
1971 const int inlet_upwind = this->segments_.upwinding_segment(inlet);
1972 for (
int comp_idx = 0; comp_idx < this->num_conservation_quantities_; ++comp_idx) {
1973 const EvalWell inlet_rate =
1974 this->primary_variables_.getSegmentRateUpwinding(inlet,
1977 this->well_efficiency_factor_;
1978 MultisegmentWellAssemble(*this).
1979 assembleInflowTerm(seg, inlet, inlet_upwind, comp_idx, inlet_rate, this->linSys_);
1986 const bool stopped_or_zero_target = this->stoppedOrZeroRateTarget(groupStateHelper);
1990 GroupState<Scalar> empty_group_state;
1994 auto& group_state = solving_with_zero_rate
1996 : groupStateHelper.groupState();
1997 GroupStateHelperType groupStateHelper_copy = groupStateHelper;
1998 auto group_guard = groupStateHelper_copy.pushGroupState(group_state);
1999 MultisegmentWellAssemble(*this).
2000 assembleControlEq(groupStateHelper_copy,
2003 this->getRefDensity(),
2004 this->primary_variables_,
2006 stopped_or_zero_target);
2008 const UnitSystem& unit_system = simulator.vanguard().eclState().getDeckUnitSystem();
2009 const auto& summary_state = simulator.vanguard().summaryState();
2010 this->assemblePressureEq(seg, unit_system, well_state, summary_state, this->param_.use_average_density_ms_wells_, deferred_logger);
2014 this->parallel_well_info_.communication().sum(this->ipr_a_.data(), this->ipr_a_.size());
2015 this->linSys_.createSolver();
2021 template<
typename TypeTag>
2023 MultisegmentWell<TypeTag>::
2024 openCrossFlowAvoidSingularity(
const Simulator& simulator)
const
2026 return !this->getAllowCrossFlow() && allDrawDownWrongDirection(simulator);
2030 template<
typename TypeTag>
2032 MultisegmentWell<TypeTag>::
2033 allDrawDownWrongDirection(
const Simulator& simulator)
const
2035 bool all_drawdown_wrong_direction =
true;
2036 const int nseg = this->numberOfSegments();
2038 for (
int seg = 0; seg < nseg; ++seg) {
2039 const EvalWell segment_pressure = this->primary_variables_.getSegmentPressure(seg);
2040 for (
const int perf : this->segments_.perforations()[seg]) {
2041 const int local_perf_index = this->parallel_well_info_.activePerfToLocalPerf(perf);
2042 if (local_perf_index < 0)
2045 const int cell_idx = this->well_cells_[local_perf_index];
2046 const auto& intQuants = simulator.model().intensiveQuantities(cell_idx, 0);
2047 const auto& fs = intQuants.fluidState();
2050 const EvalWell perf_seg_press_diff = this->segments_.getPressureDiffSegLocalPerf(seg, local_perf_index);
2052 const Scalar cell_perf_press_diff = this->cell_perforation_pressure_diffs_[local_perf_index];
2054 const Scalar pressure_cell = this->getPerfCellPressure(fs).value();
2055 const Scalar perf_press = pressure_cell - cell_perf_press_diff;
2058 const EvalWell drawdown = perf_press - (segment_pressure + perf_seg_press_diff);
2063 if ( (drawdown < 0. && this->isInjector()) ||
2064 (drawdown > 0. && this->isProducer()) ) {
2065 all_drawdown_wrong_direction =
false;
2070 const auto& comm = this->parallel_well_info_.communication();
2071 if (comm.size() > 1)
2073 all_drawdown_wrong_direction =
2074 (comm.min(all_drawdown_wrong_direction ? 1 : 0) == 1);
2077 return all_drawdown_wrong_direction;
2083 template<
typename TypeTag>
2085 MultisegmentWell<TypeTag>::
2086 updateWaterThroughput(
const double , WellStateType& )
const
2094 template<
typename TypeTag>
2095 typename MultisegmentWell<TypeTag>::EvalWell
2096 MultisegmentWell<TypeTag>::
2097 getSegmentSurfaceVolume(
const Simulator& simulator,
2099 DeferredLogger& deferred_logger)
const
2101 EvalWell temperature;
2102 EvalWell saltConcentration;
2104 auto info = this->getFirstPerforationFluidStateInfo(simulator);
2105 temperature.setValue(std::get<0>(info));
2106 saltConcentration = this->extendEval(std::get<1>(info));
2108 return this->segments_.getSurfaceVolume(temperature,
2110 this->primary_variables_,
2116 template<
typename TypeTag>
2117 std::optional<typename MultisegmentWell<TypeTag>::Scalar>
2118 MultisegmentWell<TypeTag>::
2119 computeBhpAtThpLimitProd(
const WellStateType& well_state,
2120 const Simulator& simulator,
2121 const GroupStateHelperType& groupStateHelper,
2122 const SummaryState& summary_state)
const
2124 return this->MultisegmentWell<TypeTag>::computeBhpAtThpLimitProdWithAlq(
2128 this->getALQ(well_state),
2134 template<
typename TypeTag>
2135 std::optional<typename MultisegmentWell<TypeTag>::Scalar>
2136 MultisegmentWell<TypeTag>::
2137 computeBhpAtThpLimitProdWithAlq(
const Simulator& simulator,
2138 const GroupStateHelperType& groupStateHelper,
2139 const SummaryState& summary_state,
2140 const Scalar alq_value,
2141 bool iterate_if_no_solution)
const
2144 auto& deferred_logger = groupStateHelper.deferredLogger();
2146 auto frates = [
this, &simulator, &deferred_logger](
const Scalar bhp) {
2152 std::vector<Scalar> rates(3);
2153 computeWellRatesWithBhp(simulator, bhp, rates, deferred_logger);
2157 auto bhpAtLimit = WellBhpThpCalculator(*this).
2158 computeBhpAtThpLimitProd(frates,
2160 maxPerfPress(simulator),
2161 this->getRefDensity(),
2163 this->getTHPConstraint(summary_state),
2169 if (!iterate_if_no_solution)
2170 return std::nullopt;
2172 auto fratesIter = [
this, &simulator, &groupStateHelper](
const Scalar bhp) {
2176 std::vector<Scalar> rates(3);
2177 computeWellRatesWithBhpIterations(simulator, bhp, groupStateHelper, rates);
2181 return WellBhpThpCalculator(*this).
2182 computeBhpAtThpLimitProd(fratesIter,
2184 maxPerfPress(simulator),
2185 this->getRefDensity(),
2187 this->getTHPConstraint(summary_state),
2191 template<
typename TypeTag>
2192 std::optional<typename MultisegmentWell<TypeTag>::Scalar>
2193 MultisegmentWell<TypeTag>::
2194 computeBhpAtThpLimitInj(
const Simulator& simulator,
2195 const GroupStateHelperType& groupStateHelper,
2196 const SummaryState& summary_state)
const
2198 auto& deferred_logger = groupStateHelper.deferredLogger();
2200 auto frates = [
this, &simulator, &deferred_logger](
const Scalar bhp) {
2206 std::vector<Scalar> rates(3);
2207 computeWellRatesWithBhp(simulator, bhp, rates, deferred_logger);
2211 auto bhpAtLimit = WellBhpThpCalculator(*this).
2212 computeBhpAtThpLimitInj(frates,
2214 this->getRefDensity(),
2223 auto fratesIter = [
this, &simulator, &groupStateHelper](
const Scalar bhp) {
2227 std::vector<Scalar> rates(3);
2228 computeWellRatesWithBhpIterations(simulator, bhp, groupStateHelper, rates);
2232 return WellBhpThpCalculator(*this).
2233 computeBhpAtThpLimitInj(fratesIter,
2235 this->getRefDensity(),
2246 template<
typename TypeTag>
2247 typename MultisegmentWell<TypeTag>::Scalar
2248 MultisegmentWell<TypeTag>::
2249 maxPerfPress(
const Simulator& simulator)
const
2251 Scalar max_pressure = 0.0;
2252 const int nseg = this->numberOfSegments();
2253 for (
int seg = 0; seg < nseg; ++seg) {
2254 for (
const int perf : this->segments_.perforations()[seg]) {
2255 const int local_perf_index = this->parallel_well_info_.activePerfToLocalPerf(perf);
2256 if (local_perf_index < 0)
2259 const int cell_idx = this->well_cells_[local_perf_index];
2260 const auto& int_quants = simulator.model().intensiveQuantities(cell_idx, 0);
2261 const auto& fs = int_quants.fluidState();
2262 Scalar pressure_cell = this->getPerfCellPressure(fs).value();
2263 max_pressure = std::max(max_pressure, pressure_cell);
2266 max_pressure = this->parallel_well_info_.communication().max(max_pressure);
2267 return max_pressure;
2274 template<
typename TypeTag>
2275 std::vector<typename MultisegmentWell<TypeTag>::Scalar>
2276 MultisegmentWell<TypeTag>::
2277 computeCurrentWellRates(
const Simulator& simulator,
2281 std::vector<Scalar> well_q_s(this->num_conservation_quantities_, 0.0);
2282 const bool allow_cf = this->getAllowCrossFlow() || openCrossFlowAvoidSingularity(simulator);
2284 for (
int seg = 0; seg < nseg; ++seg) {
2286 const Scalar seg_pressure = getValue(this->
primary_variables_.getSegmentPressure(seg));
2287 for (
const int perf : this->
segments_.perforations()[seg]) {
2288 const int local_perf_index = this->parallel_well_info_.activePerfToLocalPerf(perf);
2289 if (local_perf_index < 0)
2292 const int cell_idx = this->well_cells_[local_perf_index];
2293 const auto& int_quants = simulator.model().intensiveQuantities(cell_idx, 0);
2294 std::vector<Scalar> mob(this->num_conservation_quantities_, 0.0);
2295 getMobility(simulator, local_perf_index, mob, deferred_logger);
2296 Scalar trans_mult(0.0);
2297 getTransMult(trans_mult, simulator, cell_idx);
2298 const auto& wellstate_nupcol = simulator.problem().wellModel().nupcolWellState().well(this->index_of_well_);
2299 std::vector<Scalar> Tw(this->num_conservation_quantities_, this->well_index_[local_perf_index] * trans_mult);
2300 this->getTw(Tw, local_perf_index, int_quants, trans_mult, wellstate_nupcol);
2301 std::vector<Scalar> cq_s(this->num_conservation_quantities_, 0.0);
2302 Scalar perf_press = 0.0;
2304 computePerfRate(int_quants, mob, Tw, seg, perf, seg_pressure,
2305 allow_cf, cq_s, perf_press, perf_rates, deferred_logger);
2306 for (
int comp = 0; comp < this->num_conservation_quantities_; ++comp) {
2307 well_q_s[comp] += cq_s[comp];
2311 const auto& comm = this->parallel_well_info_.communication();
2312 if (comm.size() > 1)
2314 comm.sum(well_q_s.data(), well_q_s.size());
2320 template <
typename TypeTag>
2321 std::vector<typename MultisegmentWell<TypeTag>::Scalar>
2325 const int num_seg = this->numberOfSegments();
2326 constexpr int num_eq = MSWEval::numWellEq;
2327 std::vector<Scalar> retval(num_seg * num_eq);
2328 for (
int ii = 0; ii < num_seg; ++ii) {
2329 const auto& pv = this->primary_variables_.value(ii);
2330 std::ranges::copy(pv, retval.begin() + ii * num_eq);
2338 template <
typename TypeTag>
2340 MultisegmentWell<TypeTag>::
2341 setPrimaryVars(
typename std::vector<Scalar>::const_iterator it)
2343 const int num_seg = this->numberOfSegments();
2344 constexpr int num_eq = MSWEval::numWellEq;
2345 std::array<Scalar, num_eq> tmp;
2346 for (
int ii = 0; ii < num_seg; ++ii) {
2347 const auto start = it + ii * num_eq;
2348 std::copy_n(start, num_eq, tmp.begin());
2349 this->primary_variables_.setValue(ii, tmp);
2351 return num_seg * num_eq;
2354 template <
typename TypeTag>
2355 typename MultisegmentWell<TypeTag>::FSInfo
2356 MultisegmentWell<TypeTag>::
2357 getFirstPerforationFluidStateInfo(
const Simulator& simulator)
const
2359 Scalar fsTemperature = 0.0;
2360 using SaltConcType =
typename std::decay<
decltype(std::declval<
decltype(simulator.model().intensiveQuantities(0, 0).fluidState())>().saltConcentration())>::type;
2361 SaltConcType fsSaltConcentration{};
2364 if (this->well_cells_.size() > 0) {
2367 const int cell_idx = this->well_cells_[0];
2368 const auto& intQuants = simulator.model().intensiveQuantities(cell_idx, 0);
2369 const auto& fs = intQuants.fluidState();
2371 fsTemperature = fs.temperature(FluidSystem::oilPhaseIdx).value();
2372 fsSaltConcentration = fs.saltConcentration();
2375 auto info = std::make_tuple(fsTemperature, fsSaltConcentration);
2379 return this->parallel_well_info_.communication().size() == 1 ? info : this->parallel_well_info_.broadcastFirstPerforationValue(info);
Represents the convergence status of the whole simulator, to make it possible to query and store the ...
Definition ConvergenceReport.hpp:38
Definition DeferredLogger.hpp:57
DeferredLogger & deferredLogger() const
Get the deferred logger.
Definition GroupStateHelper.hpp:234
Equations linSys_
Definition MultisegmentWellEval.hpp:138
PrimaryVariables primary_variables_
Definition MultisegmentWellEval.hpp:139
MSWSegments segments_
Definition MultisegmentWellEval.hpp:140
ConvergenceReport getWellConvergence(const WellState< Scalar, IndexTraits > &well_state, const std::vector< Scalar > &B_avg, DeferredLogger &deferred_logger, const Scalar max_residual_allowed, const Scalar tolerance_wells, const Scalar relaxed_inner_tolerance_flow_ms_well, const Scalar tolerance_pressure_ms_wells, const Scalar relaxed_inner_tolerance_pressure_ms_well, const bool relax_tolerance, const bool well_is_stopped) const
int numberOfSegments() const
Definition MultisegmentWellGeneric.cpp:126
Definition MultisegmentWell.hpp:38
Class encapsulating some information about parallel wells.
Definition ParallelWellInfo.hpp:198
Manages the initializing and running of time dependent problems.
Definition simulator.hh:84
Vanguard & vanguard()
Return a reference to the grid manager of simulation.
Definition simulator.hh:234
const std::string & name() const
Definition WellInterfaceGeneric.cpp:167
bool wellHasTHPConstraints(const SummaryState &summaryState) const
Definition WellInterfaceGeneric.cpp:324
Definition WellInterfaceIndices.hpp:34
This file contains a set of helper functions used by VFPProd / VFPInj.
Definition blackoilbioeffectsmodules.hh:45
Static data associated with a well perforation.
Definition PerforationData.hpp:30
Definition PerforationData.hpp:41