23#ifndef OPM_BLACKOILWELLMODEL_IMPL_HEADER_INCLUDED
24#define OPM_BLACKOILWELLMODEL_IMPL_HEADER_INCLUDED
27#ifndef OPM_BLACKOILWELLMODEL_HEADER_INCLUDED
32#include <opm/grid/utility/cartesianToCompressed.hpp>
34#include <opm/input/eclipse/Schedule/Network/Balance.hpp>
35#include <opm/input/eclipse/Schedule/Network/ExtNetwork.hpp>
36#include <opm/input/eclipse/Schedule/Well/PAvgDynamicSourceData.hpp>
37#include <opm/input/eclipse/Schedule/Well/WellMatcher.hpp>
38#include <opm/input/eclipse/Schedule/Well/WellTestConfig.hpp>
39#include <opm/input/eclipse/Schedule/Well/WellEconProductionLimits.hpp>
41#include <opm/input/eclipse/Units/UnitSystem.hpp>
68#include <fmt/format.h>
71 template<
typename TypeTag>
78 simulator.vanguard().summaryState(),
79 simulator.vanguard().eclState(),
81 simulator.gridView().comm(),
83 , simulator_(simulator)
84 , guide_rate_handler_{
86 simulator.vanguard().schedule(),
87 simulator.vanguard().summaryState(),
88 simulator.vanguard().grid().comm()
90 , gaslift_(this->terminal_output_)
93 , rescoupHelper_(*this)
102 auto& parallel_wells =
simulator.vanguard().parallelWells();
105 for(
const auto& name_bool : parallel_wells) {
113 Parameters::Get<Parameters::AlternativeWellRateInit>();
115 using SourceDataSpan =
116 typename PAvgDynamicSourceData<Scalar>::template SourceDataSpan<Scalar>;
118 this->
wbp_.initializeSources(
119 [
this](
const std::size_t globalIndex)
121 [
this](
const int localCell, SourceDataSpan sourceTerms)
123 using Item =
typename SourceDataSpan::Item;
125 const auto& intQuants = this->
simulator_.model()
126 .intensiveQuantities(localCell, 0);
127 const auto& fs = intQuants.fluidState();
130 .set(Item::PoreVol, intQuants.porosity().value() *
131 this->
simulator_.model().dofTotalVolume(localCell))
132 .set(Item::Depth, this->
depth_[localCell]);
134 constexpr auto io = FluidSystem::oilPhaseIdx;
135 constexpr auto ig = FluidSystem::gasPhaseIdx;
136 constexpr auto iw = FluidSystem::waterPhaseIdx;
139 const auto haveOil = FluidSystem::phaseIsActive(io);
140 const auto haveGas = FluidSystem::phaseIsActive(ig);
141 const auto haveWat = FluidSystem::phaseIsActive(iw);
143 auto weightedPhaseDensity = [&fs](
const auto ip)
145 return fs.saturation(ip).value() * fs.density(ip).value();
148 if (haveOil) { sourceTerms.set(Item::Pressure, fs.pressure(io).value()); }
149 else if (haveGas) { sourceTerms.set(Item::Pressure, fs.pressure(ig).value()); }
150 else { sourceTerms.set(Item::Pressure, fs.pressure(iw).value()); }
154 if (haveOil) { rho += weightedPhaseDensity(io); }
155 if (haveGas) { rho += weightedPhaseDensity(ig); }
156 if (haveWat) { rho += weightedPhaseDensity(iw); }
158 sourceTerms.set(Item::MixtureDensity, rho);
163 template<
typename TypeTag>
168 extractLegacyCellPvtRegionIndex_();
169 extractLegacyDepth_();
171 gravity_ = simulator_.problem().gravity()[2];
173 this->initial_step_ =
true;
176 simulator_.model().addAuxiliaryModule(
this);
178 is_cell_perforated_.resize(local_num_cells_,
false);
182 template<
typename TypeTag>
187 const uint64_t effective_events_mask = ScheduleEvents::WELL_STATUS_CHANGE
188 + ScheduleEvents::NEW_WELL;
189 const auto& events = this->schedule()[reportStepIdx].wellgroup_events();
190 for (
auto& wellPtr : this->well_container_) {
191 const bool well_opened_this_step = this->report_step_starts_ &&
192 events.hasEvent(wellPtr->name(),
193 effective_events_mask);
194 wellPtr->init(this->depth_, this->gravity_,
195 this->B_avg_, well_opened_this_step);
199 template<
typename TypeTag>
204 this->groupStateHelper().setReportStep(timeStepIdx);
205 this->report_step_starts_ =
true;
206 this->report_step_start_events_ = this->schedule()[timeStepIdx].wellgroup_events();
208 this->rateConverter_ = std::make_unique<RateConverterType>
209 (std::vector<int>(this->local_num_cells_, 0));
212 const bool initializeWellState = !this->deserialized_state_pending_;
213 const auto enableWellPIScaling =
true;
214 this->initializeLocalWellStructure(timeStepIdx,
216 initializeWellState);
217 this->deserialized_state_pending_ =
false;
220 this->initializeGroupStructure(timeStepIdx);
222 const auto& comm = this->simulator_.vanguard().grid().comm();
228 this->rateConverter_->template defineState<ElementContext>(this->simulator_);
232 const auto& sched_state = this->schedule()[timeStepIdx];
234 this->vfp_properties_ = std::make_unique<VFPProperties<Scalar, IndexTraits>>
235 (sched_state.vfpinj(), sched_state.vfpprod(), this->wellState());
242 this->commitWGState();
244 this->wellStructureChangedDynamically_ =
false;
251 template <
typename TypeTag>
255 const bool enableWellPIScaling,
256 const bool initializeWellState)
258 auto logger_guard = this->groupStateHelper().pushLogger();
259 auto& local_deferredLogger = this->groupStateHelper().deferredLogger();
261 const auto& comm = this->simulator_.vanguard().grid().comm();
266 this->registerNewParallelWells(reportStepIdx);
269 this->wells_ecl_ = this->getLocalWells(reportStepIdx);
270 this->local_parallel_well_info_ =
271 this->createLocalParallelWellInfo(this->wells_ecl_);
278 if (initializeWellState) {
279 this->initializeWellPerfData();
280 this->initializeWellState(reportStepIdx);
282 this->wbp_.initializeWBPCalculationService();
284 if (initializeWellState && this->param_.use_multisegment_well_ && this->anyMSWellOpenLocal()) {
285 this->wellState().initWellStateMSWell(this->wells_ecl_, &this->prevWellState(), has_energy_);
288 this->initializeWellProdIndCalculators();
290 if (enableWellPIScaling && this->schedule()[reportStepIdx].events()
291 .hasEvent(ScheduleEvents::Events::WELL_PRODUCTIVITY_INDEX))
293 this->runWellPIScaling(reportStepIdx, local_deferredLogger);
297 "Failed to initialize local well structure: ",
298 this->terminal_output_, comm)
305 template <
typename TypeTag>
310 const auto& comm = this->simulator_.vanguard().grid().comm();
314 const auto& fieldGroup =
315 this->schedule().getGroup(
"FIELD", reportStepIdx);
317 this->groupStateHelper().setCmodeGroup(fieldGroup);
321 if (this->schedule()[reportStepIdx].has_gpmaint()) {
322 this->groupStateHelper().setRegionAveragePressureCalculator(
324 this->eclState_.fieldProps(),
325 this->regionalAveragePressureCalculator_
337 template<
typename TypeTag>
342 OPM_TIMEBLOCK(beginTimeStep);
344 this->updateAverageFormationFactor();
346 auto logger_guard = this->groupStateHelper().pushLogger();
347 auto& local_deferredLogger = this->groupStateHelper().deferredLogger();
349#ifdef RESERVOIR_COUPLING_ENABLED
350 auto rescoup_logger_guard = this->rescoupHelper_.setupScopedLogger(local_deferredLogger);
353 this->switched_prod_groups_.clear();
354 this->switched_inj_groups_.clear();
356 if (this->wellStructureChangedDynamically_) {
361 const auto reportStepIdx =
362 this->simulator_.episodeIndex();
366 const auto enableWellPIScaling =
false;
368 this->initializeLocalWellStructure(reportStepIdx, enableWellPIScaling,
true);
369 this->initializeGroupStructure(reportStepIdx);
371 this->commitWGState();
377 this->wellStructureChangedDynamically_ =
false;
380 this->resetWGState();
381 const int reportStepIdx = simulator_.episodeIndex();
383 this->wellState().updateWellsDefaultALQ(this->schedule(), reportStepIdx, this->summaryState());
384 this->wellState().gliftTimeStepInit();
386 const double simulationTime = simulator_.time();
388 this->well_performance_event_tracker_.beginTimeStep(this->schedule(), reportStepIdx,
389 this->wellStatusSnapshot());
394 wellTesting(reportStepIdx, simulationTime, local_deferredLogger);
397 stashWellSolveStats();
401 this->well_performance_event_tracker_.accumulate(this->wellStatusSnapshot());
404 createWellContainer(reportStepIdx);
408 this->well_performance_event_tracker_.applyDeckChanges(this->wellStatusSnapshot());
410#ifdef RESERVOIR_COUPLING_ENABLED
411 if (this->isReservoirCouplingMaster()) {
412 if (this->reservoirCouplingMaster().isFirstSubstepOfSyncTimestep()) {
413 this->rescoupHelper_.receiveSlaveGroupData();
420 this->updateAndCommunicateGroupData(reportStepIdx,
false);
423 const Grid& grid = simulator_.vanguard().grid();
424 this->wells_active_ = grid.comm().max(!this->well_container_.empty());
429 this->initWellContainer(reportStepIdx);
432 std::fill(is_cell_perforated_.begin(), is_cell_perforated_.end(),
false);
433 for (
auto& well : well_container_) {
434 well->updatePerforatedCell(is_cell_perforated_);
438 this->calculateEfficiencyFactors(reportStepIdx);
440 if constexpr (has_polymer_)
442 if (PolymerModule::hasPlyshlog() || getPropValue<TypeTag, Properties::EnablePolymerMW>() ) {
443 this->setRepRadiusPerfLength();
450 this->terminal_output_, simulator_.vanguard().grid().comm());
452 for (
auto& well : well_container_) {
453 well->setVFPProperties(this->vfp_properties_.get());
454 well->setGuideRate(&this->guideRate_);
457 this->updateFiltrationModelsPreStep(local_deferredLogger);
460 for (
auto& well : well_container_) {
461 well->closeCompletions(this->wellTestState());
467 if (alternative_well_rate_init_) {
472 for (
const auto& well : well_container_) {
473 if (well->isProducer() && !well->wellIsStopped()) {
474 well->initializeProducerWellState(simulator_, this->wellState(), local_deferredLogger);
479 for (
const auto& well : well_container_) {
480 if (well->isVFPActive(local_deferredLogger)){
481 well->setPrevSurfaceRates(this->wellState(), this->prevWellState());
485 this->updateWellPotentials(reportStepIdx,
487 simulator_.vanguard().summaryConfig(),
488 local_deferredLogger);
489 }
catch ( std::runtime_error& e ) {
490 const std::string msg =
"A zero well potential is returned for output purposes. ";
491 local_deferredLogger.warning(
"WELL_POTENTIAL_CALCULATION_FAILED", msg);
494 this->guide_rate_handler_.updateGuideRates(
495 reportStepIdx, simulationTime, this->wellState(), this->groupState()
497 bool slave_needs_well_solution =
false;
498#ifdef RESERVOIR_COUPLING_ENABLED
499 if (this->isReservoirCouplingSlave()) {
500 if (this->reservoirCouplingSlave().isFirstSubstepOfSyncTimestep()) {
504 this->reservoirCouplingSlave().setWellsSolvedThisSyncStep(
false);
505 this->rescoupHelper_.sendSlaveGroupDataToMaster();
506 this->rescoupHelper_.receiveGroupConstraintsFromMaster();
507 this->rescoupHelper_.receiveCoupledNetworkActiveStatus();
508 this->groupStateHelper().updateSlaveGroupCmodesFromMaster();
509 this->reservoirCouplingSlave().markSlaveGroupsInSchedule(
510 this->schedule_, reportStepIdx);
511 this->rescoupHelper_.refreshSlaveGroupTargets();
512 slave_needs_well_solution =
true;
519 if (this->schedule_[reportStepIdx].has_gpmaint()) {
520 for (
const auto& calculator : regionalAveragePressureCalculator_) {
521 calculator.second->template defineState<ElementContext>(simulator_);
523 const double dt = simulator_.timeStepSize();
524 const Group& fieldGroup = this->schedule().getGroup(
"FIELD", reportStepIdx);
526 this->groupStateHelper().updateGpMaintTargetForGroups(fieldGroup,
527 regionalAveragePressureCalculator_,
533 this->updateAndCommunicateGroupData(reportStepIdx,
true);
536 for (
auto& well : well_container_) {
537 const uint64_t effective_events_mask = ScheduleEvents::WELL_STATUS_CHANGE
538 + ScheduleEvents::INJECTION_TYPE_CHANGED
539 + ScheduleEvents::WELL_SWITCHED_INJECTOR_PRODUCER
540 + ScheduleEvents::NEW_WELL;
542 const auto& events = this->schedule()[reportStepIdx].wellgroup_events();
543 const bool event = this->report_step_starts_ && events.hasEvent(well->name(), effective_events_mask);
544 const bool dyn_status_change = this->wellState().well(well->name()).status
545 != this->prevWellState().well(well->name()).status;
547 if (event || dyn_status_change || slave_needs_well_solution) {
549 well->scaleSegmentRatesAndPressure(this->wellState());
550 well->calculateExplicitQuantities(simulator_, this->groupStateHelper());
551 well->updateWellStateWithTarget(simulator_, this->groupStateHelper(), this->wellState());
552 well->updatePrimaryVariables(this->groupStateHelper());
553 well->solveWellEquation(
554 simulator_, this->groupStateHelper(), this->wellState()
556 }
catch (
const std::exception& e) {
557 const std::string msg =
"Compute initial well solution for new well " + well->name() +
" failed. Continue with zero initial rates";
558 local_deferredLogger.warning(
"WELL_INITIAL_SOLVE_FAILED", msg);
566#ifdef RESERVOIR_COUPLING_ENABLED
567 if (slave_needs_well_solution) {
569 this->reservoirCouplingSlave().setWellsSolvedThisSyncStep(
true);
571 this->updateAndCommunicateGroupData(reportStepIdx,
false);
572 this->rescoupHelper_.sendSlaveGroupDataToMaster();
574 this->rescoupHelper_.receiveRefreshedGroupConstraintsFromMaster();
576 else if (this->isReservoirCouplingMaster()) {
577 if (this->reservoirCouplingMaster().isFirstSubstepOfSyncTimestep()) {
578 this->rescoupHelper_.sendMasterGroupConstraintsToSlaves();
579 this->rescoupHelper_.sendCoupledNetworkActiveStatus();
580 this->rescoupHelper_.receiveSlaveGroupData();
583 this->rescoupHelper_.refreshAndSendGroupConstraints();
589 const std::string msg =
"Compute initial well solution for new wells failed. Continue with zero initial rates";
590 local_deferredLogger.warning(
"WELL_INITIAL_SOLVE_FAILED", msg);
593 const auto& comm = simulator_.vanguard().grid().comm();
595 exc_type,
"beginTimeStep() failed: " + exc_msg, this->terminal_output_, comm);
599 template<
typename TypeTag>
607 template<
typename TypeTag>
615 template<
typename TypeTag>
618 const double simulationTime,
621 for (
const std::string& well_name : this->getWellsForTesting(timeStepIdx, simulationTime)) {
622 const Well& wellEcl = this->schedule().getWell(well_name, timeStepIdx);
623 if (wellEcl.getStatus() == Well::Status::SHUT)
626 WellInterfacePtr well = createWellForWellTest(well_name, timeStepIdx, deferred_logger);
628 well->init(depth_, gravity_, B_avg_,
true);
630 Scalar well_efficiency_factor = wellEcl.getEfficiencyFactor() *
631 this->wellState().getGlobalEfficiencyScalingFactor(well_name);
632 this->groupStateHelper().accumulateGroupEfficiencyFactor(
633 this->schedule().getGroup(wellEcl.groupName(), timeStepIdx),
634 well_efficiency_factor
637 well->setWellEfficiencyFactor(well_efficiency_factor);
638 well->setVFPProperties(this->vfp_properties_.get());
639 well->setGuideRate(&this->guideRate_);
642 if (well->isProducer() && alternative_well_rate_init_) {
643 well->initializeProducerWellState(simulator_, this->wellState(), deferred_logger);
645 if (well->isVFPActive(deferred_logger)) {
646 well->setPrevSurfaceRates(this->wellState(), this->prevWellState());
649 this->network_.initializeWell(*well);
653 GLiftEclWells ecl_well_map;
654 gaslift_.initGliftEclWellMap(well_container_, ecl_well_map);
655 well->wellTesting(simulator_,
657 this->groupStateHelper(),
659 this->wellTestState(),
661 this->well_open_times_);
662 }
catch (
const std::exception& e) {
663 const std::string msg =
664 fmt::format(fmt::runtime(
"Exception during testing of well: {}. The well will not open.\n"
665 "Exception message: {}"), wellEcl.name(), e.what());
666 deferred_logger.
warning(
"WELL_TESTING_FAILED", msg);
669 addSolveStats(*well);
674 template<
typename TypeTag>
680 for (
auto&& pinfo : this->local_parallel_well_info_)
691 template<
typename TypeTag>
701 template<
typename TypeTag>
706 this->closed_this_step_.clear();
709 this->report_step_starts_ =
false;
710 const int reportStepIdx = simulator_.episodeIndex();
712 auto logger_guard = this->groupStateHelper().pushLogger();
713 auto& local_deferredLogger = this->groupStateHelper().deferredLogger();
714 for (
const auto& well : well_container_) {
715 if (getPropValue<TypeTag, Properties::EnablePolymerMW>() && well->isInjector()) {
716 well->updateWaterThroughput(dt, this->wellState());
720 for (
const auto& well : well_container_) {
721 well->updateConnectionTransmissibilityFactor(simulator_, this->wellState().well(well->indexOfWell()));
722 well->updateConnectionDFactor(simulator_, this->wellState().well(well->indexOfWell()));
725 if (Indices::waterEnabled) {
726 if constexpr (getPropValue<TypeTag, Properties::EnableMech>()) {
729 updateWellFractureFlowSplit<FluidSystem, Scalar>(
730 this->simulator_, this->well_container_,
731 this->wellState(), this->nupcolWellState());
733 this->updateFiltrationModelsPostStep(dt, FluidSystem::waterPhaseIdx, local_deferredLogger);
737 this->updateInjMult(local_deferredLogger);
740 for (
const auto& well : well_container_) {
741 well->reportWellSwitching(this->wellState().well(well->indexOfWell()), local_deferredLogger);
744 if (this->terminal_output_) {
745 this->reportGroupSwitching(local_deferredLogger);
749 rateConverter_->template defineState<ElementContext>(simulator_);
753 this->updateWellPotentials(reportStepIdx,
755 simulator_.vanguard().summaryConfig(),
756 local_deferredLogger);
757 }
catch ( std::runtime_error& e ) {
758 const std::string msg =
"A zero well potential is returned for output purposes. ";
759 local_deferredLogger.warning(
"WELL_POTENTIAL_CALCULATION_FAILED", msg);
766 const double closure_time = simulationTime + dt;
768 updateWellTestState(closure_time, this->wellTestState());
771 const Group& fieldGroup = this->schedule_.getGroup(
"FIELD", reportStepIdx);
772 this->checkGEconLimits(fieldGroup, closure_time,
773 simulator_.episodeIndex(), local_deferredLogger);
774 this->checkGconsaleLimits(fieldGroup, this->wellState(),
775 simulator_.episodeIndex(), local_deferredLogger);
777 this->well_performance_event_tracker_.accumulate(this->wellStatusSnapshot());
779 this->calculateProductivityIndexValues(local_deferredLogger);
781 this->groupStateHelper().updateNONEProductionGroups();
783#ifdef RESERVOIR_COUPLING_ENABLED
784 this->rescoupHelper_.rescoupSyncSummaryData();
786 this->well_performance_event_tracker_.commitTimeStep(this->schedule(), reportStepIdx);
787 this->commitWGState();
790 this->computeWellTemperature();
794 template<
typename TypeTag>
798 unsigned elemIdx)
const
802 if (!is_cell_perforated_[elemIdx] || cellRates_.count(elemIdx) == 0) {
806 rate = cellRates_.at(elemIdx);
810 template<
typename TypeTag>
811 template <
class Context>
815 const Context& context,
817 unsigned timeIdx)
const
820 int elemIdx = context.globalSpaceIndex(spaceIdx, timeIdx);
822 if (!is_cell_perforated_[elemIdx] || cellRates_.count(elemIdx) == 0) {
826 rate = cellRates_.at(elemIdx);
831 template<
typename TypeTag>
836 const auto pressIx = []()
838 if (Indices::oilEnabled) {
return FluidSystem::oilPhaseIdx; }
839 if (Indices::waterEnabled) {
return FluidSystem::waterPhaseIdx; }
841 return FluidSystem::gasPhaseIdx;
844 auto cellPressures = std::vector<Scalar>(this->local_num_cells_,
Scalar{0});
845 auto cellTemperatures = std::vector<Scalar>(this->local_num_cells_,
Scalar{0});
848 const auto& gridView = this->simulator_.vanguard().gridView();
851 for (
const auto& elem : elements(gridView, Dune::Partitions::interior)) {
852 elemCtx.updatePrimaryStencil(elem);
853 elemCtx.updatePrimaryIntensiveQuantities(0);
855 const auto ix = elemCtx.globalSpaceIndex(0, 0);
856 const auto& fs = elemCtx.intensiveQuantities(0, 0).fluidState();
858 cellPressures[ix] = fs.pressure(pressIx).value();
859 cellTemperatures[ix] = fs.temperature(0).value();
862 this->simulator_.vanguard().grid().comm());
864 this->wellState().init(cellPressures, cellTemperatures, this->schedule(), this->wells_ecl_,
865 this->local_parallel_well_info_, timeStepIdx,
866 &this->prevWellState(), this->well_perf_data_,
867 this->summaryState(), simulator_.vanguard().enableDistributedWells());
874 template<
typename TypeTag>
879 auto logger_guard = this->groupStateHelper().pushLogger();
880 auto& local_deferredLogger = this->groupStateHelper().deferredLogger();
882 const int nw = this->numLocalWells();
884 well_container_.clear();
887 well_container_.reserve(nw);
889 const auto& wmatcher = this->schedule().wellMatcher(report_step);
890 const auto& wcycle = this->schedule()[report_step].wcycle.get();
894 std::ranges::for_each(this->wells_ecl_,
895 [
this, &wg_events = this->report_step_start_events_](
const auto& well_ecl)
897 if (!well_ecl.hasConnections()) {
902 constexpr auto events_mask = ScheduleEvents::WELL_STATUS_CHANGE |
903 ScheduleEvents::REQUEST_OPEN_WELL |
904 ScheduleEvents::REQUEST_SHUT_WELL;
905 const bool well_event =
906 this->report_step_starts_ &&
907 wg_events.hasEvent(well_ecl.name(), events_mask);
916 if (well_ecl.getStatus() == WellStatus::OPEN) {
917 this->well_open_times_.insert_or_assign(well_ecl.name(),
918 this->simulator_.time());
919 this->well_close_times_.erase(well_ecl.name());
920 }
else if (well_ecl.getStatus() == WellStatus::SHUT) {
921 this->well_close_times_.insert_or_assign(well_ecl.name(),
922 this->simulator_.time());
923 this->well_open_times_.erase(well_ecl.name());
929 const auto cycle_states = wcycle.wellStatus(this->simulator_.time(),
931 this->well_open_times_,
932 this->well_close_times_);
934 for (
int w = 0; w < nw; ++w) {
935 const Well& well_ecl = this->wells_ecl_[w];
937 if (!well_ecl.hasConnections()) {
942 const std::string& well_name = well_ecl.name();
943 const auto well_status = this->schedule()
944 .getWell(well_name, report_step).getStatus();
946 const bool shut_event = this->wellState().well(w).events.hasEvent(ScheduleEvents::WELL_STATUS_CHANGE)
947 && well_status == Well::Status::SHUT;
948 const bool open_event = this->wellState().well(w).events.hasEvent(ScheduleEvents::WELL_STATUS_CHANGE)
949 && well_status == Well::Status::OPEN;
950 const auto& ws = this->wellState().well(well_name);
952 if (shut_event && ws.status != Well::Status::SHUT) {
953 this->closed_this_step_.insert(well_name);
954 this->wellState().shutWell(w);
955 }
else if (open_event && ws.status != Well::Status::OPEN) {
956 this->wellState().openWell(w);
960 if (this->wellTestState().well_is_closed(well_name)) {
973 const bool closed_this_step =
974 (this->wellTestState().lastTestTime(well_name) == simulator_.time()) &&
975 !this->wasDynamicallyShutThisTimeStep(well_name);
978 auto& events = this->wellState().well(w).events;
979 if (events.hasEvent(ScheduleEvents::REQUEST_OPEN_WELL)) {
980 if (!closed_this_step) {
981 this->wellTestState().open_well(well_name);
982 this->wellTestState().open_completions(well_name);
983 this->well_open_times_.insert_or_assign(well_name,
984 this->simulator_.time());
985 this->well_close_times_.erase(well_name);
987 events.clearEvent(ScheduleEvents::REQUEST_OPEN_WELL);
997 auto& well_test_state = this->wellTestState();
998 const auto& sched_state = this->schedule()[report_step];
999 const bool may_reopen_completions =
1000 ws.status == Well::Status::OPEN &&
1001 sched_state.events().hasEvent(ScheduleEvents::COMPLETION_CHANGE) &&
1002 well_test_state.num_closed_completions() > 0;
1004 if (may_reopen_completions) {
1005 const auto& completion_events = sched_state.wellcompletion_events();
1006 for (
const auto& connection : well_ecl.getConnections()) {
1007 const int complnum = connection.complnum();
1011 if (!well_test_state.completion_is_closed(well_name, complnum) ||
1012 !completion_events.hasEvent(well_name, complnum, ScheduleEvents::REQUEST_OPEN_COMPLETION)) {
1017 const bool closed_this_step =
1018 (well_test_state.lastCompletionCloseTime(well_name, complnum) == simulator_.time());
1019 if (closed_this_step) {
1023 well_test_state.open_completion(well_name, complnum);
1024 local_deferredLogger.info(
1025 fmt::format(
"Completion {} - block ({}, {}, {}) for well {} "
1026 "is reopened due to an explicit WELOPEN/COMPDAT "
1029 connection.getI() + 1,
1030 connection.getJ() + 1,
1031 connection.getK() + 1,
1038 if (this->wellTestState().well_is_closed(well_name))
1040 if (this->closedWellStatus(well_ecl) == WellStatus::SHUT)
1042 this->wellState().shutWell(w);
1043 this->well_close_times_.erase(well_name);
1044 this->well_open_times_.erase(well_name);
1048 this->wellState().stopWell(w);
1052 if (!well_ecl.getAllowCrossFlow()) {
1053 const bool any_zero_rate_constraint = well_ecl.isProducer()
1054 ? well_ecl.productionControls(this->summaryState_).anyZeroRateConstraint()
1055 : well_ecl.injectionControls(this->summaryState_).anyZeroRateConstraint();
1056 if (any_zero_rate_constraint) {
1058 local_deferredLogger.debug(fmt::format(fmt::runtime(
" Well {} gets shut due to having zero rate constraint and disallowing crossflow "), well_ecl.name()));
1059 this->wellState().shutWell(w);
1060 this->well_close_times_.erase(well_name);
1061 this->well_open_times_.erase(well_name);
1066 if (!wcycle.empty()) {
1067 const auto it = cycle_states.find(well_name);
1068 if (it != cycle_states.end()) {
1069 if (!it->second || well_status == Well::Status::SHUT) {
1071 if (well_status == Well::Status::SHUT) {
1072 this->well_open_times_.erase(well_name);
1073 this->well_close_times_.erase(well_name);
1075 this->wellState().shutWell(w);
1078 this->wellState().openWell(w);
1084 if (ws.status == Well::Status::SHUT) {
1088 well_container_.emplace_back(this->createWellPointer(w, report_step));
1090 if (ws.status == Well::Status::STOP) {
1091 well_container_.back()->stopWell();
1092 this->well_close_times_.erase(well_name);
1093 this->well_open_times_.erase(well_name);
1097 if (!wcycle.empty()) {
1098 const auto schedule_open =
1099 [&wg_events = this->report_step_start_events_](
const std::string& name)
1101 return wg_events.hasEvent(name, ScheduleEvents::REQUEST_OPEN_WELL);
1103 for (
const auto& [wname, wscale] : wcycle.efficiencyScale(this->simulator_.time(),
1104 this->simulator_.timeStepSize(),
1106 this->well_open_times_,
1109 this->wellState().updateEfficiencyScalingFactor(wname, wscale);
1110 this->schedule_.add_event(ScheduleEvents::WELLGROUP_EFFICIENCY_UPDATE, report_step);
1115 this->well_container_generic_.clear();
1116 for (
auto& w : well_container_) {
1117 this->well_container_generic_.push_back(w.get());
1120 this->network_.initialize(report_step);
1122 this->wbp_.registerOpenWellsForWBPCalculation();
1129 template <
typename TypeTag>
1134 const auto is_multiseg = this->wells_ecl_[wellID].isMultiSegment();
1136 if (! (this->param_.use_multisegment_well_ && is_multiseg)) {
1137 return this->
template createTypedWellPointer<StandardWell<TypeTag>>(wellID, report_step);
1140 return this->
template createTypedWellPointer<MultisegmentWell<TypeTag>>(wellID, report_step);
1148 template <
typename TypeTag>
1149 template <
typename WellType>
1150 std::unique_ptr<WellType>
1155 const auto& perf_data = this->well_perf_data_[wellID];
1158 const auto pvtreg = perf_data.empty()
1159 ? 0 : this->pvt_region_idx_[perf_data.front().cell_index];
1161 const auto& parallel_well_info = this->local_parallel_well_info_[wellID].get();
1162 const auto global_pvtreg = parallel_well_info.broadcastFirstPerforationValue(pvtreg);
1164 return std::make_unique<WellType>(this->wells_ecl_[wellID],
1168 *this->rateConverter_,
1170 this->numConservationQuantities(),
1180 template<
typename TypeTag>
1184 const int report_step,
1189 std::ranges::find_if(this->wells_ecl_,
1190 [&well_name](
const auto& w)
1191 {
return well_name == w.name(); });
1193 if (it == this->wells_ecl_.end()) {
1195 fmt::format(fmt::runtime(
"Could not find well {} in wells_ecl"), well_name),
1199 const int pos =
static_cast<int>(std::distance(this->wells_ecl_.begin(), it));
1200 return this->createWellPointer(pos, report_step);
1205 template<
typename TypeTag>
1211 auto logger_guard = this->groupStateHelper().pushLogger();
1212 auto& local_deferredLogger = this->groupStateHelper().deferredLogger();
1214 const auto& iterCtx = simulator_.problem().iterationContext();
1217 if (gaslift_.terminalOutput()) {
1218 const std::string msg =
1219 fmt::format(fmt::runtime(
"assemble() : iteration {}"), iterCtx.iteration());
1220 gaslift_.gliftDebug(msg, local_deferredLogger);
1224 Dune::Timer perfTimer;
1226 this->closed_offending_wells_.clear();
1229 if (iterCtx.needsTimestepInit()) {
1230 this->updateNetworkActiveState_();
1232 const int episodeIdx = simulator_.episodeIndex();
1239 if (iterCtx.needsTimestepInit() && this->wellsActive()) {
1240 OPM_TIMEBLOCK(firstIterationAssemble);
1241 Dune::Timer prepareTimer;
1242 prepareTimer.start();
1249 calculateExplicitQuantities();
1250 prepareTimeStep(local_deferredLogger);
1253 "assemble() failed during well initialization: ",
1254 this->terminal_output_, grid().comm());
1255 last_report_.well_facility_time += prepareTimer.stop();
1258 Dune::Timer networkTimer;
1259 networkTimer.start();
1260 const bool well_group_control_changed = updateWellControlsAndNetwork(
1263 local_deferredLogger);
1266 const double network_time = networkTimer.stop();
1267 last_report_.well_control_network_time += network_time;
1268 last_report_.well_facility_time += network_time;
1272 if ( ! this->wellsActive() ) {
1276 assembleWellEqWithoutIteration(dt);
1283 collectWellSolveStats();
1287 last_report_.well_group_control_changed = well_group_control_changed;
1288 last_report_.assemble_time_well += perfTimer.stop();
1294 template<
typename TypeTag>
1299 stashWellSolveStats();
1300 const auto& stats = pending_solve_stats_;
1301 last_report_.well_solve_time += stats.solve_time;
1302 last_report_.well_potential_solve_time += stats.potential_solve_time;
1303 last_report_.well_solve_assemble_time += stats.assemble_time;
1304 last_report_.well_solve_linear_solve_time += stats.linear_solve_time;
1305 last_report_.total_well_iterations += stats.iterations;
1306 last_report_.total_well_potential_iterations += stats.potential_iterations;
1307 pending_solve_stats_ = {};
1310 template<
typename TypeTag>
1315 for (
const auto& well : well_container_) {
1316 addSolveStats(*well);
1320 template<
typename TypeTag>
1325 auto& pending = pending_solve_stats_;
1327 pending.solve_time += stats.solve_time;
1328 pending.potential_solve_time += stats.potential_solve_time;
1329 pending.assemble_time += stats.assemble_time;
1330 pending.linear_solve_time += stats.linear_solve_time;
1331 pending.iterations += stats.iterations;
1332 pending.potential_iterations += stats.potential_iterations;
1339 template<
typename TypeTag>
1348 bool do_network_update =
true;
1349 bool well_group_control_changed =
false;
1350 Scalar network_imbalance = 0.0;
1352 const std::size_t iteration_to_relax = param_.network_max_strict_outer_iterations_;
1354 const std::size_t max_iteration = param_.network_max_outer_iterations_;
1355 std::size_t network_update_iteration = 0;
1356 network_needs_more_balancing_force_another_newton_iteration_ =
false;
1357 while (do_network_update) {
1358 if (!this->isRescoupSlaveCoupledNetworkIteration_()
1359 && network_update_iteration >= max_iteration ) {
1360 const int episodeIdx = simulator_.episodeIndex();
1361 const auto& balance = this->schedule()[episodeIdx].network_balance();
1365 if (network_imbalance <= balance.pressure_tolerance()) {
1369 if (this->network_.willBalanceOnNextIteration(episodeIdx)) {
1370 if (this->terminal_output_) {
1371 const std::string msg = fmt::format(
"Maximum of {:d} network iterations has been used and we stop the update, \n"
1372 "and try again after the next Newton iteration (imbalance = {:.2e} bar)",
1373 max_iteration, network_imbalance*1.0e-5);
1374 local_deferredLogger.
debug(msg);
1378 network_needs_more_balancing_force_another_newton_iteration_ =
true;
1380 if (this->terminal_output_) {
1381 const std::string msg = fmt::format(
"Maximum of {:d} network iterations has been used and we stop the update. \n"
1382 "The simulator will continue with unconverged network results (imbalance = {:.2e} bar)",
1383 max_iteration, network_imbalance*1.0e-5);
1384 local_deferredLogger.
info(msg);
1389 if (this->terminal_output_ && (network_update_iteration == iteration_to_relax) ) {
1390 local_deferredLogger.
debug(
"We begin using relaxed tolerance for network update now after " +
std::to_string(iteration_to_relax) +
" iterations ");
1392 const bool relax_network_balance = network_update_iteration >= iteration_to_relax;
1394 const bool optimize_gas_lift = ( (network_update_iteration + 1) < std::max(max_iteration,
static_cast<std::size_t
>(2)) );
1395 std::tie(well_group_control_changed, do_network_update, network_imbalance) =
1396 updateWellControlsAndNetworkIteration(mandatory_network_balance, relax_network_balance, optimize_gas_lift, dt,local_deferredLogger);
1397 ++network_update_iteration;
1399 if (this->isRescoupMasterCoupledNetworkIteration_()) {
1400 this->sendSlaveNetworkLoopTerminationSignal_();
1403 if (this->schedule()[simulator_.episodeIndex()].network().active()) {
1404 last_report_.total_network_iterations += network_update_iteration;
1406 return well_group_control_changed;
1412 template<
typename TypeTag>
1413 std::tuple<bool, bool, typename BlackoilWellModel<TypeTag>::Scalar>
1416 const bool relax_network_tolerance,
1417 const bool optimize_gas_lift,
1422 const int reportStepIdx = simulator_.episodeIndex();
1424#ifdef RESERVOIR_COUPLING_ENABLED
1425 if (this->isRescoupSlaveCoupledNetworkIteration_()) {
1426 this->rescoupHelper_.receiveMasterGroupNodePressuresFromMaster();
1429 Dune::Timer groupTimer;
1431 this->updateAndCommunicateGroupData(reportStepIdx,
true);
1436 bool well_group_control_changed = updateWellControls(local_deferredLogger);
1437 last_report_.group_control_time += groupTimer.stop();
1439 Dune::Timer networkBalanceTimer;
1440 networkBalanceTimer.start();
1441 const auto [more_inner_network_update, network_imbalance] =
1442 this->network_.update(mandatory_network_balance,
1443 local_deferredLogger,
1444 relax_network_tolerance);
1446 if (this->schedule()[reportStepIdx].network().active()) {
1447 last_report_.network_balance_time += networkBalanceTimer.stop();
1449#ifdef RESERVOIR_COUPLING_ENABLED
1450 if (this->isReservoirCouplingMaster()) {
1451 this->rescoupHelper_.maybeExchangeNetworkOuterIterationWithSlaves(more_inner_network_update);
1455 bool alq_updated =
false;
1458 if (optimize_gas_lift) {
1461 const bool updatePotentials = (this->network_.shouldBalance(reportStepIdx) ||
1462 mandatory_network_balance);
1463 Dune::Timer gliftTimer;
1465 alq_updated = gaslift_.maybeDoGasLiftOptimize(simulator_,
1467 this->network_.nodePressures(),
1471 local_deferredLogger);
1473 if (this->schedule().glo(reportStepIdx).active()) {
1474 last_report_.gaslift_time += gliftTimer.stop();
1479 Dune::Timer prepareWellsTimer;
1480 prepareWellsTimer.start();
1481 prepareWellsBeforeAssembling(dt);
1482 last_report_.control_well_solve_time += prepareWellsTimer.stop();
1485 "updateWellControlsAndNetworkIteration() failed: ",
1486 this->terminal_output_, grid().comm());
1490 guideRateUpdateIsNeeded(reportStepIdx)) {
1491 const double simulationTime = simulator_.time();
1492 Dune::Timer guideRateTimer;
1493 guideRateTimer.start();
1497 this->guide_rate_handler_.updateGuideRates(
1498 reportStepIdx, simulationTime, this->wellState(), this->groupState()
1500 last_report_.group_control_time += guideRateTimer.stop();
1504 bool more_network_update = this->network_.shouldBalance(reportStepIdx) &&
1505 (more_inner_network_update || alq_updated);
1507 if (this->isRescoupSlaveOnSyncStepFirstSubstep_()
1508 && this->isRescoupSlaveConnectedToMasterNetwork_()) {
1515 const bool more_cross_rescoup_update =
1516 this->maybeSendSlaveGroupFlowToMaster_(reportStepIdx);
1517 more_network_update = more_network_update || more_cross_rescoup_update;
1520 return {well_group_control_changed, more_network_update, network_imbalance};
1523 template<
typename TypeTag>
1529 for (
auto& well : well_container_) {
1530 well->assembleWellEq(simulator_, dt, this->groupStateHelper(), this->wellState());
1535 template<
typename TypeTag>
1541 for (
auto& well : well_container_) {
1542 well->prepareWellBeforeAssembling(
1543 simulator_, dt, this->groupStateHelper(), this->wellState()
1549 template<
typename TypeTag>
1555 auto& deferred_logger = this->groupStateHelper().deferredLogger();
1560 for (
auto& well: well_container_) {
1561 well->assembleWellEqWithoutIteration(simulator_, this->groupStateHelper(), dt, this->wellState(),
1565 this->terminal_output_, grid().comm());
1569 template<
typename TypeTag>
1576 for (
const auto& well : well_container_) {
1577 well->addCellRates(cellRates_);
1581 template<
typename TypeTag>
1588 for (
const auto& well : well_container_) {
1589 const auto it = well_domain_map.find(well->name());
1590 if (it != well_domain_map.end() && it->second ==
domainIndex) {
1591 well->addCellRates(cellRates_);
1596 template<
typename TypeTag>
1600 const std::map<std::string, int>& well_domain_map,
1601 const std::vector<int>& domain_cells,
1602 const std::vector<bool>& interior)
1607 const auto in_overlap = [&domain_cells, &interior](
const int cell)
1609 return !interior[cell] && std::ranges::binary_search(domain_cells, cell);
1611 for (
const auto& well : well_container_) {
1612 const auto it = well_domain_map.find(well->name());
1613 if (it != well_domain_map.end() && it->second !=
domainIndex) {
1614 well->addConstantCellRates(cellRates_, in_overlap);
1619#if COMPILE_GPU_BRIDGE
1620 template<
typename TypeTag>
1628 for(
unsigned int i = 0; i < well_container_.size(); i++){
1629 auto& well = well_container_[i];
1632 wellContribs.
addNumBlocks(derived->linSys().getNumBlocks());
1637 wellContribs.
alloc();
1639 for(
unsigned int i = 0; i < well_container_.size(); i++){
1640 auto& well = well_container_[i];
1642 auto derived_std =
dynamic_cast<StandardWell<TypeTag>*
>(well.get());
1644 derived_std->linSys().extract(derived_std->numStaticWellEq, wellContribs);
1646 auto derived_ms =
dynamic_cast<MultisegmentWell<TypeTag>*
>(well.get());
1648 derived_ms->linSys().extract(wellContribs);
1650 OpmLog::warning(
"Warning unknown type of well");
1657 template<
typename TypeTag>
1662 for (
const auto& well: well_container_ ) {
1663 well->addWellContributions(jacobian);
1667 template<
typename TypeTag>
1670 std::vector<CMatrix>& c_matrices,
1671 std::vector<DMatrix>& d_matrices,
1675 for (
const auto& well: well_container_ ) {
1676 well->addBCDMatrix(b_matrices, c_matrices, d_matrices, wcells);
1680 template<
typename TypeTag>
1685 const bool use_well_weights,
1686 const bool contract_d_diagonal)
const
1688 int nw = this->numLocalWellsEnd();
1689 int rdofs = local_num_cells_;
1690 for (
int i = 0; i < nw; i++ ) {
1691 int wdof = rdofs + i;
1692 jacobian[wdof][wdof] = 1.0;
1695 for (
const auto& well : well_container_) {
1696 well->addWellPressureEquations(jacobian,
1700 contract_d_diagonal,
1705 template <
typename TypeTag>
1708 const std::vector<typename SparseMatrixAdapter::MatrixBlock*>& diagMatAddress)
const
1713 for (
const auto& well : well_container_) {
1714 if (!well->isOperableAndSolvable() && !well->wellIsStopped()) {
1717 const auto& cells = well->cells();
1718 const auto& rates = well->connectionRates();
1719 for (
unsigned perfIdx = 0; perfIdx < rates.size(); ++perfIdx) {
1720 unsigned cellIdx = cells[perfIdx];
1721 auto rate = rates[perfIdx];
1724 using MatrixBlockType =
typename SparseMatrixAdapter::MatrixBlock;
1725 MatrixBlockType bMat(0.0);
1726 simulator_.model().linearizer().setResAndJacobi(res, bMat, rate);
1727 residual[cellIdx] += res;
1728 *diagMatAddress[cellIdx] += bMat;
1734 template<
typename TypeTag>
1739 int nw = this->numLocalWellsEnd();
1740 int rdofs = local_num_cells_;
1741 const auto wellconnections = this->getMaxWellConnections();
1742 for (
int i = 0; i < nw; ++i) {
1743 int wdof = rdofs + i;
1744 jacobian.entry(wdof,wdof) = 0.0;
1745 const auto& perfcells = wellconnections[i];
1746 for (
int perfcell : perfcells) {
1747 jacobian.entry(wdof, perfcell) = 0.0;
1748 jacobian.entry(perfcell, wdof) = 0.0;
1754 template<
typename TypeTag>
1759 auto loggerGuard = this->groupStateHelper().pushLogger();
1762 for (
const auto& well : well_container_) {
1763 const auto& cells = well->cells();
1764 x_local_.resize(cells.size());
1766 for (
size_t i = 0; i < cells.size(); ++i) {
1767 x_local_[i] = x[cells[i]];
1769 well->recoverWellSolutionAndUpdateWellState(simulator_, x_local_,
1770 this->groupStateHelper(), this->wellState());
1774 simulator_.vanguard().grid().comm());
1778 template<
typename TypeTag>
1784 OPM_THROW(std::logic_error,
"Attempt to call NLDD method without a NLDD solver");
1787 return nldd_->recoverWellSolutionAndUpdateWellState(x, domainIdx);
1791 template<
typename TypeTag>
1794 getWellConvergence(
const std::vector<Scalar>& B_avg,
bool checkWellGroupControlsAndNetwork)
const
1798 const auto& iterCtx = simulator_.problem().iterationContext();
1799 const bool relaxTolerance = iterCtx.shouldRelax(param_.strict_outer_iter_wells_ + 1);
1801 auto logger_guard = this->groupStateHelper().pushLogger();
1802 for (
const auto& well : well_container_) {
1803 if (well->isOperableAndSolvable() || well->wellIsStopped()) {
1804 local_report += well->getWellConvergence(
1805 this->groupStateHelper(), B_avg,
1810 report.
setWellFailed({CR::WellFailure::Type::Unsolvable, CR::Severity::Normal, -1, well->name()});
1811 local_report += report;
1819 if (checkWellGroupControlsAndNetwork) {
1825 if (this->terminal_output_) {
1829 OpmLog::debug(
"NaN residual found with phase " +
std::to_string(f.phase()) +
" for well " + f.wellName());
1831 OpmLog::debug(
"Too large residual found with phase " +
std::to_string(f.phase()) +
" for well " + f.wellName());
1842 template<
typename TypeTag>
1848 for (
auto& well : well_container_) {
1849 well->calculateExplicitQuantities(simulator_, this->groupStateHelper());
1857 template<
typename TypeTag>
1863 if (!this->wellsActive() && !this->isReservoirCouplingMaster()) {
1866 const int episodeIdx = simulator_.episodeIndex();
1867 const auto& comm = simulator_.vanguard().grid().comm();
1874 const auto nupcol = this->schedule()[episodeIdx].nupcol();
1875 const auto& iter_ctx = simulator_.problem().iterationContext();
1876 if (iter_ctx.withinNupcol(nupcol)) {
1878 for (
const auto& well : well_container_) {
1879 well->updateWeldrawMaxRate(simulator_, this->wellState(), deferred_logger);
1882 simulator_.gridView().comm());
1887 bool changed_well_group =
false;
1888 const Group& fieldGroup = this->schedule().getGroup(
"FIELD", episodeIdx);
1891 const std::size_t max_iter = param_.well_group_constraints_max_iterations_;
1892 while(!changed_well_group && iter < max_iter) {
1893 changed_well_group = updateGroupControls(fieldGroup, deferred_logger, episodeIdx);
1896 bool changed_well_to_group =
false;
1898 OPM_TIMEBLOCK(UpdateWellControls);
1902 for (
const auto& well : well_container_) {
1905 simulator_, mode, this->groupStateHelper(), this->wellState()
1908 changed_well_to_group = changed_well || changed_well_to_group;
1912 simulator_.gridView().comm());
1915 changed_well_to_group = comm.sum(
static_cast<int>(changed_well_to_group));
1916 if (changed_well_to_group) {
1917 updateAndCommunicate(episodeIdx);
1918 changed_well_group =
true;
1922 bool changed_well_individual =
false;
1927 for (
const auto& well : well_container_) {
1930 simulator_, mode, this->groupStateHelper(), this->wellState()
1933 changed_well_individual = changed_well || changed_well_individual;
1937 simulator_.gridView().comm());
1940 changed_well_individual = comm.sum(
static_cast<int>(changed_well_individual));
1941 if (changed_well_individual) {
1942 updateAndCommunicate(episodeIdx);
1943 changed_well_group =
true;
1949 this->updateWsolvent(fieldGroup, episodeIdx, this->nupcolWellState());
1951 return changed_well_group;
1955 template<
typename TypeTag>
1960 this->updateAndCommunicateGroupData(reportStepIdx,
true);
1966 for (
const auto& well : well_container_) {
1968 const auto& ws = this->wellState().well(well->indexOfWell());
1969 if (ws.production_cmode == Well::ProducerCMode::GRUP ||
1970 ws.injection_cmode == Well::InjectorCMode::GRUP)
1972 well->updateWellStateWithTarget(
1973 simulator_, this->groupStateHelper(), this->wellState()
1978 simulator_.gridView().comm())
1979 this->updateAndCommunicateGroupData(reportStepIdx,
true);
1982 template<
typename TypeTag>
1987 const int reportStepIdx)
1990 const auto& iterCtx = simulator_.problem().iterationContext();
1991 bool changed =
false;
1993 const int nupcol = this->schedule()[reportStepIdx].nupcol();
1994 const bool update_group_switching_log = !iterCtx.withinNupcol(nupcol);
1995 const bool changed_hc = this->checkGroupHigherConstraints(
1996 group, deferred_logger, reportStepIdx, update_group_switching_log);
1999 updateAndCommunicate(reportStepIdx);
2002 bool changed_individual =
2004 updateGroupIndividualControl(group,
2006 param_.max_number_of_group_switches_,
2007 update_group_switching_log,
2008 this->switched_inj_groups_,
2009 this->switched_prod_groups_,
2010 this->closed_offending_wells_,
2015 if (changed_individual) {
2017 updateAndCommunicate(reportStepIdx);
2020 for (
const std::string& groupName : group.groups()) {
2021 bool changed_this = updateGroupControls(this->schedule().getGroup(groupName, reportStepIdx), deferred_logger, reportStepIdx);
2022 changed = changed || changed_this;
2027 template<
typename TypeTag>
2033 auto logger_guard = this->groupStateHelper().pushLogger();
2034 auto& local_deferredLogger = this->groupStateHelper().deferredLogger();
2035 for (
const auto& well : well_container_) {
2036 const auto& wname = well->name();
2037 const auto wasClosed = wellTestState.well_is_closed(wname);
2038 well->checkWellOperability(simulator_,
2040 this->groupStateHelper());
2041 const bool under_zero_target =
2042 well->wellUnderZeroGroupRateTarget(this->groupStateHelper());
2043 well->updateWellTestState(this->wellState().well(wname),
2049 this->eclipseState().getUnits(),
2050 this->schedule().getStartTime(),
2051 local_deferredLogger);
2053 if (!wasClosed && wellTestState.well_is_closed(wname)) {
2054 this->closed_this_step_.insert(wname);
2057 const WellEconProductionLimits& econ_production_limits = well->wellEcl().getEconLimits();
2058 if (econ_production_limits.validFollowonWell()) {
2059 const auto episode_idx = simulator_.episodeIndex();
2060 const auto follow_on_well = econ_production_limits.followonWell();
2061 if (!this->schedule().hasWell(follow_on_well, episode_idx)) {
2062 const auto msg = fmt::format(
"Well {} was closed. But the given follow on well {} does not exist."
2063 "The simulator continues without opening a follow on well.",
2064 wname, follow_on_well);
2065 local_deferredLogger.warning(msg);
2067 auto& ws = this->wellState().well(follow_on_well);
2068 const bool success = ws.updateStatus(WellStatus::OPEN);
2070 const auto msg = fmt::format(
"Well {} was closed. The follow on well {} opens instead.", wname, follow_on_well);
2071 local_deferredLogger.info(msg);
2073 const auto msg = fmt::format(
"Well {} was closed. The follow on well {} is already open.", wname, follow_on_well);
2074 local_deferredLogger.warning(msg);
2081 for (
const auto& [group_name, to] : this->closed_offending_wells_) {
2082 if (this->hasOpenLocalWell(to.second) &&
2083 !this->wasDynamicallyShutThisTimeStep(to.second))
2085 wellTestState.close_well(to.second,
2086 WellTestConfig::Reason::GROUP,
2088 this->updateClosedWellsThisStep(to.second);
2089 const std::string msg =
2090 fmt::format(
"Procedure on exceeding {} limit is WELL for group {}. "
2096 local_deferredLogger.info(msg);
2102 template<
typename TypeTag>
2106 std::string& exc_msg,
2110 const int np = this->numPhases();
2111 std::vector<Scalar> potentials;
2112 const auto& well = well_container_[widx];
2113 std::string cur_exc_msg;
2116 well->computeWellPotentials(simulator_, well_state_copy, this->groupStateHelper(), potentials);
2121 exc_msg += fmt::format(
"\nFor well {}: {}", well->name(), cur_exc_msg);
2123 exc_type = std::max(exc_type, cur_exc_type);
2127 auto& ws = this->wellState().well(well->indexOfWell());
2128 for (
int p = 0; p < np; ++p) {
2130 ws.well_potentials[p] = std::max(
Scalar{0.0}, potentials[p]);
2136 template <
typename TypeTag>
2141 for (
const auto& wellPtr : this->well_container_) {
2142 this->calculateProductivityIndexValues(wellPtr.get(), deferred_logger);
2150 template <
typename TypeTag>
2161 for (
const auto& shutWell : this->local_shut_wells_) {
2162 if (!this->wells_ecl_[shutWell].hasConnections()) {
2167 auto wellPtr = this->
template createTypedWellPointer
2170 wellPtr->
init(this->depth_, this->gravity_, this->B_avg_,
true);
2172 this->calculateProductivityIndexValues(wellPtr.get(), deferred_logger);
2180 template <
typename TypeTag>
2194 template<
typename TypeTag>
2199 const auto episodeIdx = simulator_.episodeIndex();
2202 const bool do_prestep_network_rebalance = this->shouldDoPreStepNetworkRebalance_(episodeIdx);
2204 for (
const auto& well : well_container_) {
2205 auto& events = this->wellState().well(well->indexOfWell()).events;
2207 well->updateWellStateWithTarget(
2208 simulator_, this->groupStateHelper(), this->wellState()
2210 well->updatePrimaryVariables(this->groupStateHelper());
2216 if (events.hasEvent(ScheduleEvents::REQUEST_OPEN_WELL)) {
2217 events.clearEvent(ScheduleEvents::REQUEST_OPEN_WELL);
2220 if (param_.solve_welleq_initially_ && well->isOperableAndSolvable()) {
2222 well->solveWellEquation(
2223 simulator_, this->groupStateHelper(), this->wellState()
2225 }
catch (
const std::exception& e) {
2226 const std::string msg =
"Compute initial well solution for " + well->name() +
" initially failed. Continue with the previous rates";
2227 deferred_logger.
warning(
"WELL_INITIAL_SOLVE_FAILED", msg);
2232 well->resetWellOperability();
2234 updatePrimaryVariables();
2237 if (do_prestep_network_rebalance) {
2238 network_.doPreStepRebalance(deferred_logger);
2242 template<
typename TypeTag>
2247 std::vector< Scalar > B_avg(numConservationQuantities(),
Scalar() );
2248 const auto& grid = simulator_.vanguard().grid();
2249 const auto& gridView = grid.leafGridView();
2253 for (
const auto& elem : elements(gridView, Dune::Partitions::interior)) {
2254 elemCtx.updatePrimaryStencil(elem);
2255 elemCtx.updatePrimaryIntensiveQuantities(0);
2257 const auto& intQuants = elemCtx.intensiveQuantities(0, 0);
2258 const auto& fs = intQuants.fluidState();
2260 for (
unsigned phaseIdx = 0; phaseIdx < FluidSystem::numPhases; ++phaseIdx)
2262 if (!FluidSystem::phaseIsActive(phaseIdx)) {
2266 const unsigned compIdx = FluidSystem::canonicalToActiveCompIdx(FluidSystem::solventComponentIndex(phaseIdx));
2267 auto& B = B_avg[ compIdx ];
2269 B += 1 / fs.invB(phaseIdx).value();
2271 if constexpr (has_solvent_) {
2272 auto& B = B_avg[solventSaturationIdx];
2273 B += 1 / intQuants.solventInverseFormationVolumeFactor().value();
2279 grid.comm().sum(B_avg.data(), B_avg.size());
2280 B_avg_.resize(B_avg.size());
2281 std::ranges::transform(B_avg, B_avg_.begin(),
2282 [gcells = global_num_cells_](
const auto bval)
2283 { return bval / gcells; });
2290 template<
typename TypeTag>
2295 for (
const auto& well : well_container_) {
2296 well->updatePrimaryVariables(this->groupStateHelper());
2300 template<
typename TypeTag>
2304 const auto& grid = simulator_.vanguard().grid();
2305 const auto& eclProblem = simulator_.problem();
2306 const unsigned numCells = grid.size(0);
2308 this->pvt_region_idx_.resize(numCells);
2309 for (
unsigned cellIdx = 0; cellIdx < numCells; ++cellIdx) {
2310 this->pvt_region_idx_[cellIdx] =
2311 eclProblem.pvtRegionIndex(cellIdx);
2316 template<
typename TypeTag>
2332 return this->numPhases() + has_solvent_;
2335 template<
typename TypeTag>
2339 const auto& eclProblem = simulator_.problem();
2340 depth_.resize(local_num_cells_);
2341 for (
unsigned cellIdx = 0; cellIdx < local_num_cells_; ++cellIdx) {
2342 depth_[cellIdx] = eclProblem.dofCenterDepth(cellIdx);
2346 template<
typename TypeTag>
2349 getWell(
const std::string& well_name)
const
2353 std::ranges::find_if(well_container_,
2355 {
return elem->name() == well_name; });
2357 assert(well != well_container_.end());
2362 template <
typename TypeTag>
2367 return std::max(this->simulator_.episodeIndex(), 0);
2374 template<
typename TypeTag>
2379 const std::vector<Scalar>& production_rates,
2380 std::vector<Scalar>& resv_coeff)
const
2382 rateConverter_->calcCoeff(fipnum, pvtreg, production_rates, resv_coeff);
2385 template<
typename TypeTag>
2390 std::vector<Scalar>& resv_coeff)
const
2392 rateConverter_->calcInjCoeff(fipnum, pvtreg, resv_coeff);
2396 template <
typename TypeTag>
2401 if constexpr (energyModuleType_ == EnergyModules::FullyImplicitThermal) {
2402 const int np = this->numPhases();
2403 const int nw = this->numLocalWells();
2404 for (
auto wellID = 0*nw; wellID < nw; ++wellID) {
2405 const Well& well = this->wells_ecl_[wellID];
2406 auto& ws = this->wellState().well(wellID);
2407 if (well.isInjector()) {
2408 if (ws.status != WellStatus::STOP) {
2409 this->wellState().well(wellID).temperature = well.inj_temperature();
2413 std::array<Scalar,2> weighted{0.0,0.0};
2414 auto& [weighted_temperature, total_weight] = weighted;
2415 const auto& well_info = this->local_parallel_well_info_[wellID].get();
2416 using int_type =
decltype(this->well_perf_data_[wellID].size());
2417 for (int_type perf = 0, end_perf = this->well_perf_data_[wellID].size(); perf < end_perf; ++perf) {
2418 const int cell_idx = this->well_perf_data_[wellID][perf].cell_index;
2419 const auto& intQuants = simulator_.model().intensiveQuantities(cell_idx, 0);
2420 const auto& fs = intQuants.fluidState();
2421 Scalar weight_factor = computeTemperatureWeightFactor(perf, np, fs, ws);
2422 total_weight += weight_factor;
2423 weighted_temperature += weight_factor * fs.temperature(0).value();
2425 well_info.communication().sum(weighted.data(), 2);
2426 this->wellState().well(wellID).temperature = weighted_temperature / total_weight;
2432 template <
typename TypeTag>
2434 -> typename
WellState<Scalar,IndexTraits>::RsConstInfo
2436 if (! FluidSystem::phaseIsActive(FluidSystem::oilPhaseIdx) ||
2437 ! FluidSystem::enableConstantRs())
2442 const auto& rsConstTables = this->eclState_
2443 .getTableManager().getRsconstTables();
2445 if (rsConstTables.empty() ||
2446 (rsConstTables[0].numRows() != std::size_t{1}))
2451 const auto rsConst = rsConstTables[0].getColumn(0).front();
2453 return {
true,
static_cast<Scalar
>(rsConst) };
2459 template <
typename TypeTag>
2460 void BlackoilWellModel<TypeTag>::
2461 assignWellTracerRates_(data::Wells& wsrpt)
const
2463 const auto reportStepIdx =
static_cast<unsigned int>(this->reportStepIndex());
2464 const auto& trMod = this->simulator_.problem().tracerModel();
2470 this->assignMswTracerRates(wsrpt, trMod.getMswTracerRates(), reportStepIdx);
2473 template <
typename TypeTag>
2474 void BlackoilWellModel<TypeTag>::
2475 assignWellSpeciesRates_(data::Wells& wsrpt)
const
2477 const auto reportStepIdx =
static_cast<unsigned int>(this->reportStepIndex());
2478 const auto& geochemMod = this->simulator_.problem().geochemistryModel();
2482 this->assignMswTracerRates(wsrpt, geochemMod.getMswSpeciesRates(), reportStepIdx);
2485 template <
typename TypeTag>
2486 bool BlackoilWellModel<TypeTag>::isRescoupMasterCoupledNetworkIteration_()
const
2488#ifdef RESERVOIR_COUPLING_ENABLED
2489 return this->rescoupHelper_.masterIsInCoupledNetworkIteration();
2495 template <
typename TypeTag>
2496 bool BlackoilWellModel<TypeTag>::isRescoupSlaveCoupledNetworkIteration_()
const
2507#ifdef RESERVOIR_COUPLING_ENABLED
2508 return this->isRescoupSlaveOnSyncStepFirstSubstep_()
2509 && this->reservoirCouplingSlave().connectedToMasterCoupledNetwork()
2510 && !this->reservoirCouplingSlave().lastReceivedMasterGroupNodePressuresIsFinal();
2516 template <
typename TypeTag>
2517 bool BlackoilWellModel<TypeTag>::isRescoupSlaveOnSyncStepFirstSubstep_()
const
2524#ifdef RESERVOIR_COUPLING_ENABLED
2525 return this->isReservoirCouplingSlave()
2526 && this->reservoirCouplingSlave().isFirstSubstepOfSyncTimestep();
2532 template <
typename TypeTag>
2533 bool BlackoilWellModel<TypeTag>::isRescoupSlaveConnectedToMasterNetwork_()
const
2535#ifdef RESERVOIR_COUPLING_ENABLED
2536 return this->isReservoirCouplingSlave()
2537 && this->reservoirCouplingSlave().connectedToMasterCoupledNetwork();
2543 template <
typename TypeTag>
2544 bool BlackoilWellModel<TypeTag>::
2545 maybeSendSlaveGroupFlowToMaster_([[maybe_unused]]
const int reportStepIdx)
2547#ifdef RESERVOIR_COUPLING_ENABLED
2554 assert(this->isReservoirCouplingSlave());
2555 const bool is_final =
2556 this->reservoirCouplingSlave().lastReceivedMasterGroupNodePressuresIsFinal();
2558 this->updateAndCommunicateGroupData(reportStepIdx,
false);
2559 this->rescoupHelper_.sendSlaveGroupDataToMaster();
2563 this->rescoupHelper_.receiveRefreshedGroupConstraintsFromMaster();
2572 template <
typename TypeTag>
2573 void BlackoilWellModel<TypeTag>::
2574 sendSlaveNetworkLoopTerminationSignal_()
2576#ifdef RESERVOIR_COUPLING_ENABLED
2581 assert(this->isReservoirCouplingMaster());
2582 this->rescoupHelper_.sendMasterGroupNodePressuresToSlaves(
true);
2586 template <
typename TypeTag>
2587 bool BlackoilWellModel<TypeTag>::
2588 shouldDoPreStepNetworkRebalance_(
const int episodeIdx)
const
2601 return param_.pre_solve_network_
2602 && this->network_.needPreStepRebalance(episodeIdx)
2603 && !this->isRescoupCoupledNetworkParticipant_();
2606 template <
typename TypeTag>
2607 bool BlackoilWellModel<TypeTag>::isRescoupCoupledNetworkParticipant_()
const
2609#ifdef RESERVOIR_COUPLING_ENABLED
2610 if (this->isReservoirCouplingMaster()) {
2611 return this->rescoupHelper_.masterNetworkHasMasterGroupLeaves();
2613 if (this->isReservoirCouplingSlave()) {
2614 return this->reservoirCouplingSlave().connectedToMasterCoupledNetwork();
2622 template <
typename TypeTag>
2623 void BlackoilWellModel<TypeTag>::
2624 updateNetworkActiveState_()
2635 const int episodeIdx = this->simulator_.episodeIndex();
2636 this->network_.updateActiveState(episodeIdx);
#define OPM_END_PARALLEL_TRY_CATCH_LOG(obptc_logger, obptc_prefix, obptc_output, comm)
Catch exception, log, and throw in a parallel try-catch clause.
Definition: DeferredLoggingErrorHelpers.hpp:207
#define OPM_DEFLOG_THROW(Exception, message, deferred_logger)
Definition: DeferredLoggingErrorHelpers.hpp:47
#define OPM_END_PARALLEL_TRY_CATCH(prefix, comm)
Catch exception and throw in a parallel try-catch clause.
Definition: DeferredLoggingErrorHelpers.hpp:197
#define OPM_PARALLEL_CATCH_CLAUSE(obptc_exc_type, obptc_exc_msg)
Inserts catch classes for the parallel try-catch.
Definition: DeferredLoggingErrorHelpers.hpp:168
#define OPM_BEGIN_PARALLEL_TRY_CATCH()
Macro to setup the try of a parallel try-catch.
Definition: DeferredLoggingErrorHelpers.hpp:160
void logAndCheckForExceptionsAndThrow(Opm::DeferredLogger &deferred_logger, Opm::ExceptionType::ExcEnum exc_type, const std::string &message, const bool terminal_output, Opm::Parallel::Communication comm)
Definition: DeferredLoggingErrorHelpers.hpp:113
Class for handling constraints for the blackoil well model.
Definition: BlackoilWellModelConstraints.hpp:42
Class for handling the gaslift in the blackoil well model.
Definition: BlackoilWellModelGasLift.hpp:96
Class for handling the blackoil well model.
Definition: BlackoilWellModelGeneric.hpp:100
BlackoilWellModelWBP< Scalar, IndexTraits > wbp_
Definition: BlackoilWellModelGeneric.hpp:618
std::vector< std::unique_ptr< ParallelWellInfo< Scalar > > > parallel_well_info_
Definition: BlackoilWellModelGeneric.hpp:649
void updateFailed()
Restore the state captured at the start of the failing timestep.
Definition: BlackoilWellModelGeneric.hpp:241
void advanceTimeLevel()
Snapshot the mutable well-model state at the start of a timestep.
Definition: BlackoilWellModelGeneric.hpp:228
const Parallel::Communication & comm() const
Definition: BlackoilWellModelGeneric.hpp:266
void assignWellTracerRates(data::Wells &wsrpt, const WellTracerRates &wellTracerRates, const unsigned reportStep) const
Class for handling the guide rates in the blackoil well model.
Definition: BlackoilWellModelGuideRates.hpp:47
Class for handling the blackoil well model.
Definition: BlackoilWellModel.hpp:101
void initializeGroupStructure(const int reportStepIdx)
Definition: BlackoilWellModel_impl.hpp:308
void calcResvCoeff(const int fipnum, const int pvtreg, const std::vector< Scalar > &production_rates, std::vector< Scalar > &resv_coeff) const override
Definition: BlackoilWellModel_impl.hpp:2377
void prepareTimeStep(DeferredLogger &deferred_logger)
Definition: BlackoilWellModel_impl.hpp:2197
std::tuple< bool, bool, Scalar > updateWellControlsAndNetworkIteration(const bool mandatory_network_balance, const bool relax_network_tolerance, const bool optimize_gas_lift, const double dt, DeferredLogger &local_deferredLogger)
Definition: BlackoilWellModel_impl.hpp:1415
WellInterfacePtr createWellPointer(const int wellID, const int report_step) const
Definition: BlackoilWellModel_impl.hpp:1132
void prepareWellsBeforeAssembling(const double dt)
Definition: BlackoilWellModel_impl.hpp:1538
void init()
Definition: BlackoilWellModel_impl.hpp:166
const Simulator & simulator() const
Definition: BlackoilWellModel.hpp:400
std::vector< Scalar > depth_
Definition: BlackoilWellModel.hpp:610
std::size_t global_num_cells_
Definition: BlackoilWellModel.hpp:606
GetPropType< TypeTag, Properties::Scalar > Scalar
Definition: BlackoilWellModel.hpp:110
void addConstantCellRatesForOverlap(int domainIndex, const std::map< std::string, int > &well_domain_map, const std::vector< int > &domain_cells, const std::vector< bool > &interior)
Definition: BlackoilWellModel_impl.hpp:1599
void initWellContainer(const int reportStepIdx) override
Definition: BlackoilWellModel_impl.hpp:185
void beginReportStep(const int time_step)
Definition: BlackoilWellModel_impl.hpp:202
const WellInterface< TypeTag > & getWell(const std::string &well_name) const
Definition: BlackoilWellModel_impl.hpp:2349
GetPropType< TypeTag, Properties::FluidSystem > FluidSystem
Definition: BlackoilWellModel.hpp:106
Dune::FieldVector< Scalar, numEq > VectorBlockType
Definition: BlackoilWellModel.hpp:134
GetPropType< TypeTag, Properties::ElementContext > ElementContext
Definition: BlackoilWellModel.hpp:107
GetPropType< TypeTag, Properties::Grid > Grid
Definition: BlackoilWellModel.hpp:104
int numConservationQuantities() const
Definition: BlackoilWellModel_impl.hpp:2318
bool updateWellControls(DeferredLogger &deferred_logger)
Definition: BlackoilWellModel_impl.hpp:1860
int reportStepIndex() const
Definition: BlackoilWellModel_impl.hpp:2365
void calculateProductivityIndexValues(DeferredLogger &deferred_logger) override
Definition: BlackoilWellModel_impl.hpp:2139
void extractLegacyDepth_()
Definition: BlackoilWellModel_impl.hpp:2337
void extractLegacyCellPvtRegionIndex_()
Definition: BlackoilWellModel_impl.hpp:2302
void recoverWellSolutionAndUpdateWellStateDomain(const BVector &x, const int domainIdx)
Definition: BlackoilWellModel_impl.hpp:1781
void updateAverageFormationFactor()
Definition: BlackoilWellModel_impl.hpp:2245
GetPropType< TypeTag, Properties::Simulator > Simulator
Definition: BlackoilWellModel.hpp:109
BlackoilWellModel(Simulator &simulator, const NewtonIterationContext &iter_ctx)
Definition: BlackoilWellModel_impl.hpp:73
void initializeWellState(const int timeStepIdx)
Definition: BlackoilWellModel_impl.hpp:834
const Grid & grid() const
Definition: BlackoilWellModel.hpp:397
void updatePrimaryVariables()
Definition: BlackoilWellModel_impl.hpp:2293
void computeWellTemperature()
Definition: BlackoilWellModel_impl.hpp:2399
const SimulatorReportSingle & lastReport() const
Definition: BlackoilWellModel_impl.hpp:694
bool updateWellControlsAndNetwork(const bool mandatory_network_balance, const double dt, DeferredLogger &local_deferredLogger)
Definition: BlackoilWellModel_impl.hpp:1342
void addWellContributions(SparseMatrixAdapter &jacobian) const
Definition: BlackoilWellModel_impl.hpp:1660
void assembleWellEq(const double dt)
Definition: BlackoilWellModel_impl.hpp:1526
WellInterfacePtr createWellForWellTest(const std::string &well_name, const int report_step, DeferredLogger &deferred_logger) const
Definition: BlackoilWellModel_impl.hpp:1183
void calculateExplicitQuantities() const
Definition: BlackoilWellModel_impl.hpp:1845
void collectWellSolveStats()
Definition: BlackoilWellModel_impl.hpp:1297
void updateAndCommunicate(const int reportStepIdx)
Definition: BlackoilWellModel_impl.hpp:1958
Dune::BCRSMatrix< Opm::MatrixBlock< Scalar, 1, 1 > > PressureMatrix
Definition: BlackoilWellModel.hpp:309
void updateFailed()
Definition: BlackoilWellModel_impl.hpp:602
void computeTotalRatesForDof(RateVector &rate, unsigned globalIdx) const
Definition: BlackoilWellModel_impl.hpp:797
void stashWellSolveStats()
Definition: BlackoilWellModel_impl.hpp:1313
void beginTimeStep()
Definition: BlackoilWellModel_impl.hpp:340
GetPropType< TypeTag, Properties::RateVector > RateVector
Definition: BlackoilWellModel.hpp:111
bool updateGroupControls(const Group &group, DeferredLogger &deferred_logger, const int reportStepIdx)
Definition: BlackoilWellModel_impl.hpp:1985
void initializeLocalWellStructure(const int reportStepIdx, const bool enableWellPIScaling, const bool initializeWellState)
Definition: BlackoilWellModel_impl.hpp:254
void calcInjResvCoeff(const int fipnum, const int pvtreg, std::vector< Scalar > &resv_coeff) const override
Definition: BlackoilWellModel_impl.hpp:2388
Dune::BlockVector< VectorBlockType > BVector
Definition: BlackoilWellModel.hpp:135
void wellTesting(const int timeStepIdx, const double simulationTime, DeferredLogger &deferred_logger)
Definition: BlackoilWellModel_impl.hpp:617
ConvergenceReport getWellConvergence(const std::vector< Scalar > &B_avg, const bool checkWellGroupControlsAndNetwork=false) const
Definition: BlackoilWellModel_impl.hpp:1794
typename FluidSystem::IndexTraitsType IndexTraits
Definition: BlackoilWellModel.hpp:117
void updateCellRatesForDomain(int domainIndex, const std::map< std::string, int > &well_domain_map)
Definition: BlackoilWellModel_impl.hpp:1584
void assembleWellEqWithoutIteration(const double dt)
Definition: BlackoilWellModel_impl.hpp:1552
void updateCellRates()
Definition: BlackoilWellModel_impl.hpp:1572
void assemble(const double dt)
Definition: BlackoilWellModel_impl.hpp:1208
std::size_t local_num_cells_
Definition: BlackoilWellModel.hpp:608
bool alternative_well_rate_init_
Definition: BlackoilWellModel.hpp:611
void timeStepSucceeded(const double simulationTime, const double dt)
Definition: BlackoilWellModel_impl.hpp:704
std::unique_ptr< WellType > createTypedWellPointer(const int wellID, const int time_step) const
Definition: BlackoilWellModel_impl.hpp:1152
void computePotentials(const std::size_t widx, const WellState< Scalar, IndexTraits > &well_state_copy, std::string &exc_msg, ExceptionType::ExcEnum &exc_type) override
Definition: BlackoilWellModel_impl.hpp:2104
Simulator & simulator_
Definition: BlackoilWellModel.hpp:580
void createWellContainer(const int report_step) override
Definition: BlackoilWellModel_impl.hpp:877
std::unique_ptr< WellInterface< TypeTag > > WellInterfacePtr
Definition: BlackoilWellModel.hpp:195
void updateWellTestState(const double simulationTime, WellTestState &wellTestState)
upate the wellTestState related to economic limits
Definition: BlackoilWellModel_impl.hpp:2030
void addBCDMatrix(std::vector< BMatrix > &b_matrices, std::vector< CMatrix > &c_matrices, std::vector< DMatrix > &d_matrices, Opm::SparseTable< int > &wcells) const
Definition: BlackoilWellModel_impl.hpp:1669
void addSolveStats(const WellInterface< TypeTag > &well)
Definition: BlackoilWellModel_impl.hpp:1323
void addReservoirSourceTerms(GlobalEqVector &residual, const std::vector< typename SparseMatrixAdapter::MatrixBlock * > &diagMatAddress) const
Definition: BlackoilWellModel_impl.hpp:1707
int compressedIndexForInterior(int cartesian_cell_idx) const override
get compressed index for interior cells (-1, otherwise
Definition: BlackoilWellModel.hpp:365
void addWellPressureEquations(PressureMatrix &jacobian, const BVector &weights, const bool use_well_weights, const bool contract_d_diagonal) const
Definition: BlackoilWellModel_impl.hpp:1683
void recoverWellSolutionAndUpdateWellState(const BVector &x)
Definition: BlackoilWellModel_impl.hpp:1757
void addWellPressureEquationsStruct(PressureMatrix &jacobian) const
Definition: BlackoilWellModel_impl.hpp:1737
void calculateProductivityIndexValuesShutWells(const int reportStepIdx, DeferredLogger &deferred_logger) override
Definition: BlackoilWellModel_impl.hpp:2153
void advanceTimeLevel()
Definition: BlackoilWellModel_impl.hpp:610
void endReportStep()
Definition: BlackoilWellModel_impl.hpp:677
Definition: ConvergenceReport.hpp:38
void setWellFailed(const WellFailure &wf)
Definition: ConvergenceReport.hpp:296
void setWellGroupTargetsViolated(const bool wellGroupTargetsViolated)
Definition: ConvergenceReport.hpp:314
const std::vector< WellFailure > & wellFailures() const
Definition: ConvergenceReport.hpp:459
void setNetworkNotYetBalancedForceAnotherNewtonIteration(const bool network_needs_more_balancing_force_another_newton_iteration)
Definition: ConvergenceReport.hpp:319
Definition: DeferredLogger.hpp:57
void info(const std::string &tag, const std::string &message)
void warning(const std::string &tag, const std::string &message)
void debug(const std::string &tag, const std::string &message)
std::map< std::string, std::pair< const Well *, int > > GLiftEclWells
Definition: GasLiftGroupInfo.hpp:65
Class encapsulating some information about parallel wells.
Definition: ParallelWellInfo.hpp:217
Definition: StandardWell.hpp:55
virtual void init(const std::vector< Scalar > &depth_arg, const Scalar gravity_arg, const std::vector< Scalar > &B_avg, const bool changed_to_open_this_step) override
Definition: StandardWell_impl.hpp:77
Definition: WellContributions.hpp:51
void alloc()
Allocate memory for the StandardWells.
void setBlockSize(unsigned int dim, unsigned int dim_wells)
void addNumBlocks(unsigned int numBlocks)
const WellSolveStats & solveStats() const
Definition: WellInterfaceGeneric.hpp:293
void resetSolveStats() const
Definition: WellInterfaceGeneric.hpp:294
int indexOfWell() const
Index of well in the wells struct and wellState.
Definition: WellInterface.hpp:79
virtual void updateProductivityIndex(const Simulator &simulator, const WellProdIndexCalculator< Scalar > &wellPICalc, WellStateType &well_state, DeferredLogger &deferred_logger) const =0
bool updateWellControl(const Simulator &simulator, const IndividualOrGroup iog, const GroupStateHelperType &groupStateHelper, WellStateType &well_state)
Definition: WellInterface_impl.hpp:192
Definition: WellState.hpp:68
if(!linsolver_)
Definition: FlexibleSolver_impl.hpp:336
ExcEnum
Definition: DeferredLogger.hpp:45
@ NONE
Definition: DeferredLogger.hpp:46
Dune::Communication< MPIComm > Communication
Definition: ParallelCommunication.hpp:30
constexpr std::size_t domainIndex(const NetworkDomain domain)
Definition: BlackoilWellModelNetworkGeneric.hpp:60
bool anyNetworkActive(const Schedule &schedule, const int timeStepIdx)
Helper to check if any network (production, gas injection, water injection) is active at a given time...
Definition: blackoilbioeffectsmodules.hh:45
ConvergenceReport gatherConvergenceReport(const ConvergenceReport &local_report, Parallel::Communication communicator)
std::string to_string(const ConvergenceReport::ReservoirFailure::Type t)
#define RESERVOIR_COUPLING_ENABLED
Definition: simulator.hh:32
Context for iteration-dependent decisions in the Newton solver.
Definition: NewtonIterationContext.hpp:43
A struct for returning timing data from a simulator to its caller.
Definition: SimulatorReport.hpp:34