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/Action/Actions.hpp>
35#include <opm/input/eclipse/Schedule/Network/Balance.hpp>
36#include <opm/input/eclipse/Schedule/Network/ExtNetwork.hpp>
37#include <opm/input/eclipse/Schedule/Well/PAvgDynamicSourceData.hpp>
38#include <opm/input/eclipse/Schedule/Well/WellMatcher.hpp>
39#include <opm/input/eclipse/Schedule/Well/WellTestConfig.hpp>
40#include <opm/input/eclipse/Schedule/Well/WellEconProductionLimits.hpp>
42#include <opm/input/eclipse/Units/UnitSystem.hpp>
69#include <fmt/format.h>
72 template<
typename TypeTag>
79 simulator.vanguard().summaryState(),
80 simulator.vanguard().eclState(),
82 simulator.gridView().comm(),
84 , simulator_(simulator)
85 , guide_rate_handler_{
87 simulator.vanguard().schedule(),
88 simulator.vanguard().summaryState(),
89 simulator.vanguard().grid().comm()
91 , gaslift_(this->terminal_output_)
94 , rescoupHelper_(*this)
103 auto& parallel_wells =
simulator.vanguard().parallelWells();
106 for(
const auto& name_bool : parallel_wells) {
114 Parameters::Get<Parameters::AlternativeWellRateInit>();
116 using SourceDataSpan =
117 typename PAvgDynamicSourceData<Scalar>::template SourceDataSpan<Scalar>;
119 this->
wbp_.initializeSources(
120 [
this](
const std::size_t globalIndex)
122 [
this](
const int localCell, SourceDataSpan sourceTerms)
124 using Item =
typename SourceDataSpan::Item;
126 const auto& intQuants = this->
simulator_.model()
127 .intensiveQuantities(localCell, 0);
128 const auto& fs = intQuants.fluidState();
131 .set(Item::PoreVol, intQuants.porosity().value() *
132 this->
simulator_.model().dofTotalVolume(localCell))
133 .set(Item::Depth, this->
depth_[localCell]);
135 constexpr auto io = FluidSystem::oilPhaseIdx;
136 constexpr auto ig = FluidSystem::gasPhaseIdx;
137 constexpr auto iw = FluidSystem::waterPhaseIdx;
140 const auto haveOil = FluidSystem::phaseIsActive(io);
141 const auto haveGas = FluidSystem::phaseIsActive(ig);
142 const auto haveWat = FluidSystem::phaseIsActive(iw);
144 auto weightedPhaseDensity = [&fs](
const auto ip)
146 return fs.saturation(ip).value() * fs.density(ip).value();
149 if (haveOil) { sourceTerms.set(Item::Pressure, fs.pressure(io).value()); }
150 else if (haveGas) { sourceTerms.set(Item::Pressure, fs.pressure(ig).value()); }
151 else { sourceTerms.set(Item::Pressure, fs.pressure(iw).value()); }
155 if (haveOil) { rho += weightedPhaseDensity(io); }
156 if (haveGas) { rho += weightedPhaseDensity(ig); }
157 if (haveWat) { rho += weightedPhaseDensity(iw); }
159 sourceTerms.set(Item::MixtureDensity, rho);
164 template<
typename TypeTag>
169 extractLegacyCellPvtRegionIndex_();
170 extractLegacyDepth_();
172 gravity_ = simulator_.problem().gravity()[2];
174 this->initial_step_ =
true;
177 simulator_.model().addAuxiliaryModule(
this);
179 is_cell_perforated_.resize(local_num_cells_,
false);
183 template<
typename TypeTag>
188 const uint64_t effective_events_mask = ScheduleEvents::WELL_STATUS_CHANGE
189 + ScheduleEvents::NEW_WELL;
190 const auto& events = this->schedule()[reportStepIdx].wellgroup_events();
191 for (
auto& wellPtr : this->well_container_) {
192 const bool well_opened_this_step = this->report_step_starts_ &&
193 events.hasEvent(wellPtr->name(),
194 effective_events_mask);
195 wellPtr->init(this->depth_, this->gravity_,
196 this->B_avg_, well_opened_this_step);
200 template<
typename TypeTag>
205 this->groupStateHelper().setReportStep(timeStepIdx);
206 this->report_step_starts_ =
true;
207 this->report_step_start_events_ = this->schedule()[timeStepIdx].wellgroup_events();
209 this->rateConverter_ = std::make_unique<RateConverterType>
210 (std::vector<int>(this->local_num_cells_, 0));
213 const bool initializeWellState = !this->deserialized_state_pending_;
214 const auto enableWellPIScaling =
true;
215 this->initializeLocalWellStructure(timeStepIdx,
217 initializeWellState);
218 this->deserialized_state_pending_ =
false;
221 this->initializeGroupStructure(timeStepIdx);
223 const auto& comm = this->simulator_.vanguard().grid().comm();
229 this->rateConverter_->template defineState<ElementContext>(this->simulator_);
233 const auto& sched_state = this->schedule()[timeStepIdx];
235 this->vfp_properties_ = std::make_unique<VFPProperties<Scalar, IndexTraits>>
236 (sched_state.vfpinj(), sched_state.vfpprod(), this->wellState());
243 this->commitWGState();
245 this->wellStructureChangedDynamically_ =
false;
252 template <
typename TypeTag>
256 const bool enableWellPIScaling,
257 const bool initializeWellState)
259 auto logger_guard = this->groupStateHelper().pushLogger();
260 auto& local_deferredLogger = this->groupStateHelper().deferredLogger();
262 const auto& comm = this->simulator_.vanguard().grid().comm();
267 this->registerNewParallelWells(reportStepIdx);
270 this->wells_ecl_ = this->getLocalWells(reportStepIdx);
271 this->local_parallel_well_info_ =
272 this->createLocalParallelWellInfo(this->wells_ecl_);
279 if (initializeWellState) {
280 this->initializeWellPerfData();
281 this->initializeWellState(reportStepIdx);
283 this->wbp_.initializeWBPCalculationService();
285 if (initializeWellState && this->param_.use_multisegment_well_ && this->anyMSWellOpenLocal()) {
286 this->wellState().initWellStateMSWell(this->wells_ecl_, &this->prevWellState(), has_energy_);
289 this->initializeWellProdIndCalculators();
291 if (enableWellPIScaling && this->schedule()[reportStepIdx].events()
292 .hasEvent(ScheduleEvents::Events::WELL_PRODUCTIVITY_INDEX))
294 this->runWellPIScaling(reportStepIdx, local_deferredLogger);
298 "Failed to initialize local well structure: ",
299 this->terminal_output_, comm)
306 template <
typename TypeTag>
311 const auto& comm = this->simulator_.vanguard().grid().comm();
315 const auto& fieldGroup =
316 this->schedule().getGroup(
"FIELD", reportStepIdx);
318 this->groupStateHelper().setCmodeGroup(fieldGroup);
322 if (this->schedule()[reportStepIdx].has_gpmaint()) {
323 this->groupStateHelper().setRegionAveragePressureCalculator(
325 this->eclState_.fieldProps(),
326 this->regionalAveragePressureCalculator_
338 template<
typename TypeTag>
343 OPM_TIMEBLOCK(beginTimeStep);
345 const auto reportStep = simulator_.episodeIndex();
346 if (this->schedule_.numWells(reportStep) != 0
347 || !this->schedule_[reportStep].actions().empty()) {
348 this->updateAverageFormationFactor();
351 auto logger_guard = this->groupStateHelper().pushLogger();
352 auto& local_deferredLogger = this->groupStateHelper().deferredLogger();
354#ifdef RESERVOIR_COUPLING_ENABLED
355 auto rescoup_logger_guard = this->rescoupHelper_.setupScopedLogger(local_deferredLogger);
358 this->switched_prod_groups_.clear();
359 this->switched_inj_groups_.clear();
361 if (this->wellStructureChangedDynamically_) {
366 const auto reportStepIdx =
367 this->simulator_.episodeIndex();
371 const auto enableWellPIScaling =
false;
373 this->initializeLocalWellStructure(reportStepIdx, enableWellPIScaling,
true);
374 this->initializeGroupStructure(reportStepIdx);
376 this->commitWGState();
382 this->wellStructureChangedDynamically_ =
false;
385 this->resetWGState();
386#ifdef RESERVOIR_COUPLING_ENABLED
387 if (this->isReservoirCouplingSlave()) {
388 this->rescoupHelper_.updateSlaveGroupCmodesAfterStateReset();
391 const int reportStepIdx = simulator_.episodeIndex();
393 this->wellState().updateWellsDefaultALQ(this->schedule(), reportStepIdx, this->summaryState());
394 this->wellState().gliftTimeStepInit();
396 const double simulationTime = simulator_.time();
398 this->well_performance_event_tracker_.beginTimeStep(this->schedule(), reportStepIdx,
399 this->wellStatusSnapshot());
404 wellTesting(reportStepIdx, simulationTime, local_deferredLogger);
407 stashWellSolveStats();
411 this->well_performance_event_tracker_.accumulate(this->wellStatusSnapshot());
414 createWellContainer(reportStepIdx);
418 this->well_performance_event_tracker_.applyDeckChanges(this->wellStatusSnapshot());
420#ifdef RESERVOIR_COUPLING_ENABLED
421 if (this->isReservoirCouplingMaster()) {
422 if (this->reservoirCouplingMaster().isFirstSubstepOfSyncTimestep()) {
423 this->rescoupHelper_.receiveSlaveGroupData();
430 this->updateAndCommunicateGroupData(reportStepIdx,
false);
433 const Grid& grid = simulator_.vanguard().grid();
434 this->wells_active_ = grid.comm().max(!this->well_container_.empty());
439 this->initWellContainer(reportStepIdx);
442 std::fill(is_cell_perforated_.begin(), is_cell_perforated_.end(),
false);
443 for (
auto& well : well_container_) {
444 well->updatePerforatedCell(is_cell_perforated_);
448 this->calculateEfficiencyFactors(reportStepIdx);
450 if constexpr (has_polymer_)
452 if (PolymerModule::hasPlyshlog() || getPropValue<TypeTag, Properties::EnablePolymerMW>() ) {
453 this->setRepRadiusPerfLength();
460 this->terminal_output_, simulator_.vanguard().grid().comm());
462 for (
auto& well : well_container_) {
463 well->setVFPProperties(this->vfp_properties_.get());
464 well->setGuideRate(&this->guideRate_);
467 this->updateFiltrationModelsPreStep(local_deferredLogger);
470 for (
auto& well : well_container_) {
471 well->closeCompletions(this->wellTestState());
477 if (alternative_well_rate_init_) {
482 for (
const auto& well : well_container_) {
483 if (well->isProducer() && !well->wellIsStopped()) {
484 well->initializeProducerWellState(simulator_, this->wellState(), local_deferredLogger);
489 for (
const auto& well : well_container_) {
490 if (well->isVFPActive(local_deferredLogger)){
491 well->setPrevSurfaceRates(this->wellState(), this->prevWellState());
495 this->updateWellPotentials(reportStepIdx,
497 simulator_.vanguard().summaryConfig(),
498 local_deferredLogger);
499 }
catch ( std::runtime_error& e ) {
500 const std::string msg =
"A zero well potential is returned for output purposes. ";
501 local_deferredLogger.warning(
"WELL_POTENTIAL_CALCULATION_FAILED", msg);
504 this->guide_rate_handler_.updateGuideRates(
505 reportStepIdx, simulationTime, this->wellState(), this->groupState()
507 bool slave_needs_well_solution =
false;
508#ifdef RESERVOIR_COUPLING_ENABLED
509 if (this->isReservoirCouplingSlave()) {
510 if (this->reservoirCouplingSlave().isFirstSubstepOfSyncTimestep()) {
514 this->reservoirCouplingSlave().setWellsSolvedThisSyncStep(
false);
515 this->rescoupHelper_.sendSlaveGroupDataToMaster();
516 this->rescoupHelper_.receiveGroupConstraintsFromMaster();
517 this->rescoupHelper_.receiveCoupledNetworkActiveStatus();
518 this->groupStateHelper().updateSlaveGroupCmodesFromMaster();
519 this->reservoirCouplingSlave().markSlaveGroupsInSchedule(
520 this->schedule_, reportStepIdx);
521 this->rescoupHelper_.refreshSlaveGroupTargets();
522 slave_needs_well_solution =
true;
529 if (this->schedule_[reportStepIdx].has_gpmaint()) {
530 for (
const auto& calculator : regionalAveragePressureCalculator_) {
531 calculator.second->template defineState<ElementContext>(simulator_);
533 const double dt = simulator_.timeStepSize();
534 const Group& fieldGroup = this->schedule().getGroup(
"FIELD", reportStepIdx);
536 this->groupStateHelper().updateGpMaintTargetForGroups(fieldGroup,
537 regionalAveragePressureCalculator_,
543 this->updateAndCommunicateGroupData(reportStepIdx,
true);
546 for (
auto& well : well_container_) {
547 const uint64_t effective_events_mask = ScheduleEvents::WELL_STATUS_CHANGE
548 + ScheduleEvents::INJECTION_TYPE_CHANGED
549 + ScheduleEvents::WELL_SWITCHED_INJECTOR_PRODUCER
550 + ScheduleEvents::NEW_WELL;
552 const auto& events = this->schedule()[reportStepIdx].wellgroup_events();
553 const bool event = this->report_step_starts_ && events.hasEvent(well->name(), effective_events_mask);
554 const bool dyn_status_change = this->wellState().well(well->name()).status
555 != this->prevWellState().well(well->name()).status;
557 if (event || dyn_status_change || slave_needs_well_solution) {
559 well->scaleSegmentRatesAndPressure(this->wellState());
560 well->calculateExplicitQuantities(simulator_, this->groupStateHelper());
561 well->updateWellStateWithTarget(simulator_, this->groupStateHelper(), this->wellState());
562 well->updatePrimaryVariables(this->groupStateHelper());
563 well->solveWellEquation(
564 simulator_, this->groupStateHelper(), this->wellState()
566 }
catch (
const std::exception& e) {
567 const std::string msg =
"Compute initial well solution for new well " + well->name() +
" failed. Continue with zero initial rates";
568 local_deferredLogger.warning(
"WELL_INITIAL_SOLVE_FAILED", msg);
576#ifdef RESERVOIR_COUPLING_ENABLED
577 if (slave_needs_well_solution) {
579 this->reservoirCouplingSlave().setWellsSolvedThisSyncStep(
true);
581 this->updateAndCommunicateGroupData(reportStepIdx,
false);
582 this->rescoupHelper_.sendSlaveGroupDataToMaster();
584 this->rescoupHelper_.receiveRefreshedGroupConstraintsFromMaster();
586 else if (this->isReservoirCouplingMaster()) {
587 if (this->reservoirCouplingMaster().isFirstSubstepOfSyncTimestep()) {
588 this->rescoupHelper_.sendMasterGroupConstraintsToSlaves();
589 this->rescoupHelper_.sendCoupledNetworkActiveStatus();
590 this->rescoupHelper_.receiveSlaveGroupData();
593 this->rescoupHelper_.refreshAndSendGroupConstraints();
599 const std::string msg =
"Compute initial well solution for new wells failed. Continue with zero initial rates";
600 local_deferredLogger.warning(
"WELL_INITIAL_SOLVE_FAILED", msg);
603 const auto& comm = simulator_.vanguard().grid().comm();
605 exc_type,
"beginTimeStep() failed: " + exc_msg, this->terminal_output_, comm);
609 template<
typename TypeTag>
617 template<
typename TypeTag>
625 template<
typename TypeTag>
628 const double simulationTime,
631 for (
const std::string& well_name : this->getWellsForTesting(timeStepIdx, simulationTime)) {
632 const Well& wellEcl = this->schedule().getWell(well_name, timeStepIdx);
633 if (wellEcl.getStatus() == Well::Status::SHUT)
636 WellInterfacePtr well = createWellForWellTest(well_name, timeStepIdx, deferred_logger);
638 well->init(depth_, gravity_, B_avg_,
true);
640 Scalar well_efficiency_factor = wellEcl.getEfficiencyFactor() *
641 this->wellState().getGlobalEfficiencyScalingFactor(well_name);
642 this->groupStateHelper().accumulateGroupEfficiencyFactor(
643 this->schedule().getGroup(wellEcl.groupName(), timeStepIdx),
644 well_efficiency_factor
647 well->setWellEfficiencyFactor(well_efficiency_factor);
648 well->setVFPProperties(this->vfp_properties_.get());
649 well->setGuideRate(&this->guideRate_);
652 if (well->isProducer() && alternative_well_rate_init_) {
653 well->initializeProducerWellState(simulator_, this->wellState(), deferred_logger);
655 if (well->isVFPActive(deferred_logger)) {
656 well->setPrevSurfaceRates(this->wellState(), this->prevWellState());
659 this->network_.initializeWell(*well);
663 GLiftEclWells ecl_well_map;
664 gaslift_.initGliftEclWellMap(well_container_, ecl_well_map);
665 well->wellTesting(simulator_,
667 this->groupStateHelper(),
669 this->wellTestState(),
671 this->well_open_times_);
672 }
catch (
const std::exception& e) {
673 const std::string msg =
674 fmt::format(fmt::runtime(
"Exception during testing of well: {}. The well will not open.\n"
675 "Exception message: {}"), wellEcl.name(), e.what());
676 deferred_logger.
warning(
"WELL_TESTING_FAILED", msg);
679 addSolveStats(*well);
684 template<
typename TypeTag>
690 for (
auto&& pinfo : this->local_parallel_well_info_)
701 template<
typename TypeTag>
711 template<
typename TypeTag>
716 this->closed_this_step_.clear();
717 this->retry_shut_wells_.clear();
720 this->report_step_starts_ =
false;
721 const int reportStepIdx = simulator_.episodeIndex();
723 auto logger_guard = this->groupStateHelper().pushLogger();
724 auto& local_deferredLogger = this->groupStateHelper().deferredLogger();
725 for (
const auto& well : well_container_) {
726 if (getPropValue<TypeTag, Properties::EnablePolymerMW>() && well->isInjector()) {
727 well->updateWaterThroughput(dt, this->wellState());
731 for (
const auto& well : well_container_) {
732 well->updateConnectionTransmissibilityFactor(simulator_, this->wellState().well(well->indexOfWell()));
733 well->updateConnectionDFactor(simulator_, this->wellState().well(well->indexOfWell()));
736 if constexpr (getPropValue<TypeTag, Properties::EnableMech>()) {
739 updateWellFractureFlowSplit<FluidSystem, Scalar>(
740 this->simulator_, this->well_container_,
741 this->wellState(), this->nupcolWellState());
746 const auto inv_b = [
this](
const int cell_index,
const unsigned canonical_phase) ->
Scalar
748 if (!FluidSystem::phaseIsActive(canonical_phase)) {
751 const auto& intQuants = this->simulator_.model()
752 .intensiveQuantities(cell_index, 0);
753 return getValue(intQuants.fluidState().invB(canonical_phase));
755 this->updateFiltrationModelsPostStep(dt, inv_b, local_deferredLogger);
759 this->updateInjMult(local_deferredLogger);
762 for (
const auto& well : well_container_) {
763 well->reportWellSwitching(this->wellState().well(well->indexOfWell()), local_deferredLogger);
766 if (this->terminal_output_) {
767 this->reportGroupSwitching(local_deferredLogger);
774 if (this->schedule_.numWells(reportStepIdx) != 0
775 || !this->schedule_[reportStepIdx].actions().empty()
776 || this->isReservoirCouplingMaster()) {
777 rateConverter_->template defineState<ElementContext>(simulator_);
782 this->updateWellPotentials(reportStepIdx,
784 simulator_.vanguard().summaryConfig(),
785 local_deferredLogger);
786 }
catch ( std::runtime_error& e ) {
787 const std::string msg =
"A zero well potential is returned for output purposes. ";
788 local_deferredLogger.warning(
"WELL_POTENTIAL_CALCULATION_FAILED", msg);
795 const double closure_time = simulationTime + dt;
797 updateWellTestState(closure_time, this->wellTestState());
800 const Group& fieldGroup = this->schedule_.getGroup(
"FIELD", reportStepIdx);
801 this->checkGEconLimits(fieldGroup, closure_time,
802 simulator_.episodeIndex(), local_deferredLogger);
803 this->checkGconsaleLimits(fieldGroup, this->wellState(),
804 simulator_.episodeIndex(), local_deferredLogger);
806 this->well_performance_event_tracker_.accumulate(this->wellStatusSnapshot());
808 this->calculateProductivityIndexValues(local_deferredLogger);
811 for (
const auto& well : well_container_) {
812 well->consolidatePhaseMixingRates(this->wellState());
815 this->groupStateHelper().updateNONEProductionGroups();
817#ifdef RESERVOIR_COUPLING_ENABLED
818 this->rescoupHelper_.rescoupSyncSummaryData();
820 this->well_performance_event_tracker_.commitTimeStep(this->schedule(), reportStepIdx);
821 this->commitWGState();
824 this->computeWellTemperature();
828 template<
typename TypeTag>
832 unsigned elemIdx)
const
836 if (!is_cell_perforated_[elemIdx] || cellRates_.count(elemIdx) == 0) {
840 rate = cellRates_.at(elemIdx);
844 template<
typename TypeTag>
845 template <
class Context>
849 const Context& context,
851 unsigned timeIdx)
const
854 int elemIdx = context.globalSpaceIndex(spaceIdx, timeIdx);
856 if (!is_cell_perforated_[elemIdx] || cellRates_.count(elemIdx) == 0) {
860 rate = cellRates_.at(elemIdx);
865 template<
typename TypeTag>
870 const auto pressIx = []()
872 if (Indices::oilEnabled) {
return FluidSystem::oilPhaseIdx; }
873 if (Indices::waterEnabled) {
return FluidSystem::waterPhaseIdx; }
875 return FluidSystem::gasPhaseIdx;
878 auto cellPressures = std::vector<Scalar>(this->local_num_cells_,
Scalar{0});
879 auto cellTemperatures = std::vector<Scalar>(this->local_num_cells_,
Scalar{0});
882 const auto& gridView = this->simulator_.vanguard().gridView();
885 for (
const auto& elem : elements(gridView, Dune::Partitions::interior)) {
886 elemCtx.updatePrimaryStencil(elem);
887 elemCtx.updatePrimaryIntensiveQuantities(0);
889 const auto ix = elemCtx.globalSpaceIndex(0, 0);
890 const auto& fs = elemCtx.intensiveQuantities(0, 0).fluidState();
892 cellPressures[ix] = fs.pressure(pressIx).value();
893 cellTemperatures[ix] = fs.temperature(0).value();
896 this->simulator_.vanguard().grid().comm());
898 this->wellState().init(cellPressures, cellTemperatures, this->schedule(), this->wells_ecl_,
899 this->local_parallel_well_info_, timeStepIdx,
900 &this->prevWellState(), this->well_perf_data_,
901 this->summaryState(), simulator_.vanguard().enableDistributedWells());
908 template<
typename TypeTag>
913 auto logger_guard = this->groupStateHelper().pushLogger();
914 auto& local_deferredLogger = this->groupStateHelper().deferredLogger();
916 const int nw = this->numLocalWells();
918 well_container_.clear();
921 well_container_.reserve(nw);
923 const auto& wmatcher = this->schedule().wellMatcher(report_step);
924 const auto& wcycle = this->schedule()[report_step].wcycle.get();
928 std::ranges::for_each(this->wells_ecl_,
929 [
this, &wg_events = this->report_step_start_events_](
const auto& well_ecl)
931 if (!well_ecl.hasConnections()) {
936 constexpr auto events_mask = ScheduleEvents::WELL_STATUS_CHANGE |
937 ScheduleEvents::REQUEST_OPEN_WELL |
938 ScheduleEvents::REQUEST_SHUT_WELL;
939 const bool well_event =
940 this->report_step_starts_ &&
941 wg_events.hasEvent(well_ecl.name(), events_mask);
950 if (well_ecl.getStatus() == WellStatus::OPEN) {
951 this->well_open_times_.insert_or_assign(well_ecl.name(),
952 this->simulator_.time());
953 this->well_close_times_.erase(well_ecl.name());
954 }
else if (well_ecl.getStatus() == WellStatus::SHUT) {
955 this->well_close_times_.insert_or_assign(well_ecl.name(),
956 this->simulator_.time());
957 this->well_open_times_.erase(well_ecl.name());
963 const auto cycle_states = wcycle.wellStatus(this->simulator_.time(),
965 this->well_open_times_,
966 this->well_close_times_);
968 for (
int w = 0; w < nw; ++w) {
969 const Well& well_ecl = this->wells_ecl_[w];
971 if (!well_ecl.hasConnections()) {
976 const std::string& well_name = well_ecl.name();
977 const auto well_status = this->schedule()
978 .getWell(well_name, report_step).getStatus();
980 const bool shut_event = this->wellState().well(w).events.hasEvent(ScheduleEvents::WELL_STATUS_CHANGE)
981 && well_status == Well::Status::SHUT;
982 const bool open_event = this->wellState().well(w).events.hasEvent(ScheduleEvents::WELL_STATUS_CHANGE)
983 && well_status == Well::Status::OPEN;
984 const auto& ws = this->wellState().well(well_name);
986 if (shut_event && ws.status != Well::Status::SHUT) {
987 this->closed_this_step_.insert(well_name);
988 this->wellState().shutWell(w);
989 }
else if (open_event && ws.status != Well::Status::OPEN) {
990 this->wellState().openWell(w);
994 this->honorOpenRequest(well_name, this->wellState().well(w).events,
995 this->simulator_.time());
1003 auto& well_test_state = this->wellTestState();
1004 const auto& sched_state = this->schedule()[report_step];
1005 const bool may_reopen_completions =
1006 ws.status == Well::Status::OPEN &&
1007 sched_state.events().hasEvent(ScheduleEvents::COMPLETION_CHANGE) &&
1008 well_test_state.num_closed_completions() > 0;
1010 if (may_reopen_completions) {
1011 const auto& completion_events = sched_state.wellcompletion_events();
1012 for (
const auto& connection : well_ecl.getConnections()) {
1013 const int complnum = connection.complnum();
1017 if (!well_test_state.completion_is_closed(well_name, complnum) ||
1018 !completion_events.hasEvent(well_name, complnum, ScheduleEvents::REQUEST_OPEN_COMPLETION)) {
1023 const bool closed_this_step =
1024 (well_test_state.lastCompletionCloseTime(well_name, complnum) == simulator_.time());
1025 if (closed_this_step) {
1029 well_test_state.open_completion(well_name, complnum);
1030 local_deferredLogger.info(
1031 fmt::format(
"Completion {} - block ({}, {}, {}) for well {} "
1032 "is reopened due to an explicit WELOPEN/COMPDAT "
1035 connection.getI() + 1,
1036 connection.getJ() + 1,
1037 connection.getK() + 1,
1044 if (this->wellTestState().well_is_closed(well_name))
1046 if (this->closedWellStatus(well_ecl) == WellStatus::SHUT)
1048 this->wellState().shutWell(w);
1049 this->well_close_times_.erase(well_name);
1050 this->well_open_times_.erase(well_name);
1054 this->wellState().stopWell(w);
1058 if (!well_ecl.getAllowCrossFlow()) {
1059 const bool any_zero_rate_constraint = well_ecl.isProducer()
1060 ? well_ecl.productionControls(this->summaryState_).anyZeroRateConstraint()
1061 : well_ecl.injectionControls(this->summaryState_).anyZeroRateConstraint();
1062 if (any_zero_rate_constraint) {
1064 local_deferredLogger.debug(fmt::format(fmt::runtime(
" Well {} gets shut due to having zero rate constraint and disallowing crossflow "), well_ecl.name()));
1065 this->wellState().shutWell(w);
1066 this->well_close_times_.erase(well_name);
1067 this->well_open_times_.erase(well_name);
1072 if (!wcycle.empty()) {
1073 const auto it = cycle_states.find(well_name);
1074 if (it != cycle_states.end()) {
1075 if (!it->second || well_status == Well::Status::SHUT) {
1077 if (well_status == Well::Status::SHUT) {
1078 this->well_open_times_.erase(well_name);
1079 this->well_close_times_.erase(well_name);
1081 this->wellState().shutWell(w);
1084 this->wellState().openWell(w);
1090 if (ws.status == Well::Status::SHUT) {
1094 well_container_.emplace_back(this->createWellPointer(w, report_step));
1096 if (ws.status == Well::Status::STOP) {
1097 well_container_.back()->stopWell();
1098 this->well_close_times_.erase(well_name);
1099 this->well_open_times_.erase(well_name);
1103 if (!wcycle.empty()) {
1104 const auto schedule_open =
1105 [&wg_events = this->report_step_start_events_](
const std::string& name)
1107 return wg_events.hasEvent(name, ScheduleEvents::REQUEST_OPEN_WELL);
1109 for (
const auto& [wname, wscale] : wcycle.efficiencyScale(this->simulator_.time(),
1110 this->simulator_.timeStepSize(),
1112 this->well_open_times_,
1115 this->wellState().updateEfficiencyScalingFactor(wname, wscale);
1116 this->schedule_.add_event(ScheduleEvents::WELLGROUP_EFFICIENCY_UPDATE, report_step);
1121 this->well_container_generic_.clear();
1122 for (
auto& w : well_container_) {
1123 this->well_container_generic_.push_back(w.get());
1126 this->network_.initialize(report_step);
1128 this->wbp_.registerOpenWellsForWBPCalculation();
1135 template <
typename TypeTag>
1140 const auto is_multiseg = this->wells_ecl_[wellID].isMultiSegment();
1142 if (! (this->param_.use_multisegment_well_ && is_multiseg)) {
1143 return this->
template createTypedWellPointer<StandardWell<TypeTag>>(wellID, report_step);
1146 return this->
template createTypedWellPointer<MultisegmentWell<TypeTag>>(wellID, report_step);
1154 template <
typename TypeTag>
1155 template <
typename WellType>
1156 std::unique_ptr<WellType>
1161 const auto& perf_data = this->well_perf_data_[wellID];
1164 const auto pvtreg = perf_data.empty()
1165 ? 0 : this->pvt_region_idx_[perf_data.front().cell_index];
1167 const auto& parallel_well_info = this->local_parallel_well_info_[wellID].get();
1168 const auto global_pvtreg = parallel_well_info.broadcastFirstPerforationValue(pvtreg);
1170 return std::make_unique<WellType>(this->wells_ecl_[wellID],
1174 *this->rateConverter_,
1176 this->numConservationQuantities(),
1186 template<
typename TypeTag>
1190 const int report_step,
1195 std::ranges::find_if(this->wells_ecl_,
1196 [&well_name](
const auto& w)
1197 {
return well_name == w.name(); });
1199 if (it == this->wells_ecl_.end()) {
1201 fmt::format(fmt::runtime(
"Could not find well {} in wells_ecl"), well_name),
1205 const int pos =
static_cast<int>(std::distance(this->wells_ecl_.begin(), it));
1206 return this->createWellPointer(pos, report_step);
1211 template<
typename TypeTag>
1217 auto logger_guard = this->groupStateHelper().pushLogger();
1218 auto& local_deferredLogger = this->groupStateHelper().deferredLogger();
1220 const auto& iterCtx = simulator_.problem().iterationContext();
1223 if (gaslift_.terminalOutput()) {
1224 const std::string msg =
1225 fmt::format(fmt::runtime(
"assemble() : iteration {}"), iterCtx.iteration());
1226 gaslift_.gliftDebug(msg, local_deferredLogger);
1230 Dune::Timer perfTimer;
1232 this->closed_offending_wells_.clear();
1235 if (iterCtx.needsTimestepInit()) {
1236 this->updateNetworkActiveState_();
1238 const int episodeIdx = simulator_.episodeIndex();
1245 if (iterCtx.needsTimestepInit() && this->wellsActive()) {
1246 OPM_TIMEBLOCK(firstIterationAssemble);
1247 Dune::Timer prepareTimer;
1248 prepareTimer.start();
1255 calculateExplicitQuantities();
1256 prepareTimeStep(local_deferredLogger);
1259 "assemble() failed during well initialization: ",
1260 this->terminal_output_, grid().comm());
1261 last_report_.well_facility_time += prepareTimer.stop();
1264 Dune::Timer networkTimer;
1265 networkTimer.start();
1266 const bool well_group_control_changed = updateWellControlsAndNetwork(
1269 local_deferredLogger);
1272 const double network_time = networkTimer.stop();
1273 last_report_.well_control_network_time += network_time;
1274 last_report_.well_facility_time += network_time;
1278 if ( ! this->wellsActive() ) {
1282 assembleWellEqWithoutIteration(dt);
1289 collectWellSolveStats();
1293 last_report_.well_group_control_changed = well_group_control_changed;
1294 last_report_.assemble_time_well += perfTimer.stop();
1300 template<
typename TypeTag>
1305 stashWellSolveStats();
1306 const auto& stats = pending_solve_stats_;
1307 last_report_.well_solve_time += stats.solve_time;
1308 last_report_.well_potential_solve_time += stats.potential_solve_time;
1309 last_report_.well_solve_assemble_time += stats.assemble_time;
1310 last_report_.well_solve_linear_solve_time += stats.linear_solve_time;
1311 last_report_.total_well_iterations += stats.iterations;
1312 last_report_.total_well_potential_iterations += stats.potential_iterations;
1313 pending_solve_stats_ = {};
1316 template<
typename TypeTag>
1321 for (
const auto& well : well_container_) {
1322 addSolveStats(*well);
1326 template<
typename TypeTag>
1331 auto& pending = pending_solve_stats_;
1333 pending.solve_time += stats.solve_time;
1334 pending.potential_solve_time += stats.potential_solve_time;
1335 pending.assemble_time += stats.assemble_time;
1336 pending.linear_solve_time += stats.linear_solve_time;
1337 pending.iterations += stats.iterations;
1338 pending.potential_iterations += stats.potential_iterations;
1345 template<
typename TypeTag>
1354 bool do_network_update =
true;
1355 bool well_group_control_changed =
false;
1356 Scalar network_imbalance = 0.0;
1358 const std::size_t iteration_to_relax = param_.network_max_strict_outer_iterations_;
1360 const std::size_t max_iteration = param_.network_max_outer_iterations_;
1361 std::size_t network_update_iteration = 0;
1362 network_needs_more_balancing_force_another_newton_iteration_ =
false;
1363 while (do_network_update) {
1364 if (!this->isRescoupSlaveCoupledNetworkIteration_()
1365 && network_update_iteration >= max_iteration ) {
1366 const int episodeIdx = simulator_.episodeIndex();
1367 const auto& balance = this->schedule()[episodeIdx].network_balance();
1371 if (network_imbalance <= balance.pressure_tolerance()) {
1375 if (this->network_.willBalanceOnNextIteration(episodeIdx)) {
1376 if (this->terminal_output_) {
1377 const std::string msg = fmt::format(
"Maximum of {:d} network iterations has been used and we stop the update, \n"
1378 "and try again after the next Newton iteration (imbalance = {:.2e} bar)",
1379 max_iteration, network_imbalance*1.0e-5);
1380 local_deferredLogger.
debug(msg);
1384 network_needs_more_balancing_force_another_newton_iteration_ =
true;
1386 if (this->terminal_output_) {
1387 const std::string msg = fmt::format(
"Maximum of {:d} network iterations has been used and we stop the update. \n"
1388 "The simulator will continue with unconverged network results (imbalance = {:.2e} bar)",
1389 max_iteration, network_imbalance*1.0e-5);
1390 local_deferredLogger.
info(msg);
1395 if (this->terminal_output_ && (network_update_iteration == iteration_to_relax) ) {
1396 local_deferredLogger.
debug(
"We begin using relaxed tolerance for network update now after " +
std::to_string(iteration_to_relax) +
" iterations ");
1398 const bool relax_network_balance = network_update_iteration >= iteration_to_relax;
1400 const bool optimize_gas_lift = ( (network_update_iteration + 1) < std::max(max_iteration,
static_cast<std::size_t
>(2)) );
1401 std::tie(well_group_control_changed, do_network_update, network_imbalance) =
1402 updateWellControlsAndNetworkIteration(mandatory_network_balance, relax_network_balance, optimize_gas_lift, dt,local_deferredLogger);
1403 ++network_update_iteration;
1405 if (this->isRescoupMasterCoupledNetworkIteration_()) {
1406 this->sendSlaveNetworkLoopTerminationSignal_();
1409 if (this->schedule()[simulator_.episodeIndex()].network().active()) {
1410 last_report_.total_network_iterations += network_update_iteration;
1412 return well_group_control_changed;
1418 template<
typename TypeTag>
1419 std::tuple<bool, bool, typename BlackoilWellModel<TypeTag>::Scalar>
1422 const bool relax_network_tolerance,
1423 const bool optimize_gas_lift,
1428 const int reportStepIdx = simulator_.episodeIndex();
1430#ifdef RESERVOIR_COUPLING_ENABLED
1431 if (this->isRescoupSlaveCoupledNetworkIteration_()) {
1432 this->rescoupHelper_.receiveMasterGroupNodePressuresFromMaster();
1435 Dune::Timer groupTimer;
1437 this->updateAndCommunicateGroupData(reportStepIdx,
true);
1442 bool well_group_control_changed = updateWellControls(local_deferredLogger);
1443 last_report_.group_control_time += groupTimer.stop();
1445 Dune::Timer networkBalanceTimer;
1446 networkBalanceTimer.start();
1447 const auto [more_inner_network_update, network_imbalance] =
1448 this->network_.update(mandatory_network_balance,
1449 local_deferredLogger,
1450 relax_network_tolerance);
1452 if (this->schedule()[reportStepIdx].network().active()) {
1453 last_report_.network_balance_time += networkBalanceTimer.stop();
1455#ifdef RESERVOIR_COUPLING_ENABLED
1456 if (this->isReservoirCouplingMaster()) {
1457 this->rescoupHelper_.maybeExchangeNetworkOuterIterationWithSlaves(more_inner_network_update);
1461 bool alq_updated =
false;
1464 if (optimize_gas_lift) {
1467 const bool updatePotentials = (this->network_.shouldBalance(reportStepIdx) ||
1468 mandatory_network_balance);
1469 Dune::Timer gliftTimer;
1471 alq_updated = gaslift_.maybeDoGasLiftOptimize(simulator_,
1473 this->network_.nodePressures(),
1477 local_deferredLogger);
1479 if (this->schedule().glo(reportStepIdx).active()) {
1480 last_report_.gaslift_time += gliftTimer.stop();
1485 Dune::Timer prepareWellsTimer;
1486 prepareWellsTimer.start();
1487 prepareWellsBeforeAssembling(dt);
1488 last_report_.control_well_solve_time += prepareWellsTimer.stop();
1491 "updateWellControlsAndNetworkIteration() failed: ",
1492 this->terminal_output_, grid().comm());
1496 guideRateUpdateIsNeeded(reportStepIdx)) {
1497 const double simulationTime = simulator_.time();
1498 Dune::Timer guideRateTimer;
1499 guideRateTimer.start();
1503 this->guide_rate_handler_.updateGuideRates(
1504 reportStepIdx, simulationTime, this->wellState(), this->groupState()
1506 last_report_.group_control_time += guideRateTimer.stop();
1510 bool more_network_update = this->network_.shouldBalance(reportStepIdx) &&
1511 (more_inner_network_update || alq_updated);
1513 if (this->isRescoupSlaveOnSyncStepFirstSubstep_()
1514 && this->isRescoupSlaveConnectedToMasterNetwork_()) {
1521 const bool more_cross_rescoup_update =
1522 this->maybeSendSlaveGroupFlowToMaster_(reportStepIdx);
1523 more_network_update = more_network_update || more_cross_rescoup_update;
1526 return {well_group_control_changed, more_network_update, network_imbalance};
1529 template<
typename TypeTag>
1535 for (
auto& well : well_container_) {
1536 well->assembleWellEq(simulator_, dt, this->groupStateHelper(), this->wellState());
1541 template<
typename TypeTag>
1547 for (
auto& well : well_container_) {
1548 well->prepareWellBeforeAssembling(
1549 simulator_, dt, this->groupStateHelper(), this->wellState()
1555 template<
typename TypeTag>
1561 auto& deferred_logger = this->groupStateHelper().deferredLogger();
1566 for (
auto& well: well_container_) {
1567 well->assembleWellEqWithoutIteration(simulator_, this->groupStateHelper(), dt, this->wellState(),
1571 this->terminal_output_, grid().comm());
1575 template<
typename TypeTag>
1582 for (
const auto& well : well_container_) {
1583 well->addCellRates(cellRates_);
1587 template<
typename TypeTag>
1594 for (
const auto& well : well_container_) {
1595 const auto it = well_domain_map.find(well->name());
1596 if (it != well_domain_map.end() && it->second ==
domainIndex) {
1597 well->addCellRates(cellRates_);
1602 template<
typename TypeTag>
1606 const std::map<std::string, int>& well_domain_map,
1607 const std::vector<int>& domain_cells,
1608 const std::vector<bool>& interior)
1613 const auto in_overlap = [&domain_cells, &interior](
const int cell)
1615 return !interior[cell] && std::ranges::binary_search(domain_cells, cell);
1617 for (
const auto& well : well_container_) {
1618 const auto it = well_domain_map.find(well->name());
1619 if (it != well_domain_map.end() && it->second !=
domainIndex) {
1620 well->addConstantCellRates(cellRates_, in_overlap);
1625#if COMPILE_GPU_BRIDGE
1626 template<
typename TypeTag>
1634 for(
unsigned int i = 0; i < well_container_.size(); i++){
1635 auto& well = well_container_[i];
1638 wellContribs.
addNumBlocks(derived->linSys().getNumBlocks());
1643 wellContribs.
alloc();
1645 for(
unsigned int i = 0; i < well_container_.size(); i++){
1646 auto& well = well_container_[i];
1648 auto derived_std =
dynamic_cast<StandardWell<TypeTag>*
>(well.get());
1650 derived_std->linSys().extract(derived_std->numStaticWellEq, wellContribs);
1652 auto derived_ms =
dynamic_cast<MultisegmentWell<TypeTag>*
>(well.get());
1654 derived_ms->linSys().extract(wellContribs);
1656 OpmLog::warning(
"Warning unknown type of well");
1663 template<
typename TypeTag>
1668 for (
const auto& well: well_container_ ) {
1669 well->addWellContributions(jacobian);
1673 template<
typename TypeTag>
1676 std::vector<CMatrix>& c_matrices,
1677 std::vector<DMatrix>& d_matrices,
1678 Opm::SparseTable<int>& wcells)
const
1681 for (
const auto& well: well_container_ ) {
1682 well->addBCDMatrix(b_matrices, c_matrices, d_matrices, wcells);
1686 template<
typename TypeTag>
1691 const bool use_well_weights,
1692 const bool contract_d_diagonal)
const
1694 int nw = this->numLocalWellsEnd();
1695 int rdofs = local_num_cells_;
1696 for (
int i = 0; i < nw; i++ ) {
1697 int wdof = rdofs + i;
1698 jacobian[wdof][wdof] = 1.0;
1701 for (
const auto& well : well_container_) {
1702 well->addWellPressureEquations(jacobian,
1706 contract_d_diagonal,
1711 template <
typename TypeTag>
1714 const std::vector<typename SparseMatrixAdapter::MatrixBlock*>& diagMatAddress)
const
1719 for (
const auto& well : well_container_) {
1720 if (!well->isOperableAndSolvable() && !well->wellIsStopped()) {
1723 const auto& cells = well->cells();
1724 const auto& rates = well->connectionRates();
1725 for (
unsigned perfIdx = 0; perfIdx < rates.size(); ++perfIdx) {
1726 unsigned cellIdx = cells[perfIdx];
1727 auto rate = rates[perfIdx];
1730 using MatrixBlockType =
typename SparseMatrixAdapter::MatrixBlock;
1731 MatrixBlockType bMat(0.0);
1732 simulator_.model().linearizer().setResAndJacobi(res, bMat, rate);
1733 residual[cellIdx] += res;
1734 *diagMatAddress[cellIdx] += bMat;
1740 template<
typename TypeTag>
1745 int nw = this->numLocalWellsEnd();
1746 int rdofs = local_num_cells_;
1747 const auto wellconnections = this->getMaxWellConnections();
1748 for (
int i = 0; i < nw; ++i) {
1749 int wdof = rdofs + i;
1750 jacobian.entry(wdof,wdof) = 0.0;
1751 const auto& perfcells = wellconnections[i];
1752 for (
int perfcell : perfcells) {
1753 jacobian.entry(wdof, perfcell) = 0.0;
1754 jacobian.entry(perfcell, wdof) = 0.0;
1760 template<
typename TypeTag>
1765 auto loggerGuard = this->groupStateHelper().pushLogger();
1768 for (
const auto& well : well_container_) {
1769 const auto& cells = well->cells();
1770 x_local_.resize(cells.size());
1772 for (
size_t i = 0; i < cells.size(); ++i) {
1773 x_local_[i] = x[cells[i]];
1775 well->recoverWellSolutionAndUpdateWellState(simulator_, x_local_,
1776 this->groupStateHelper(), this->wellState());
1780 simulator_.vanguard().grid().comm());
1784 template<
typename TypeTag>
1790 OPM_THROW(std::logic_error,
"Attempt to call NLDD method without a NLDD solver");
1793 return nldd_->recoverWellSolutionAndUpdateWellState(x, domainIdx);
1797 template<
typename TypeTag>
1800 getWellConvergence(
const std::vector<Scalar>& B_avg,
bool checkWellGroupControlsAndNetwork)
const
1804 const auto& iterCtx = simulator_.problem().iterationContext();
1805 const bool relaxTolerance = iterCtx.shouldRelax(param_.strict_outer_iter_wells_ + 1);
1807 auto logger_guard = this->groupStateHelper().pushLogger();
1808 for (
const auto& well : well_container_) {
1809 if (well->isOperableAndSolvable() || well->wellIsStopped()) {
1810 local_report += well->getWellConvergence(
1811 this->groupStateHelper(), B_avg,
1816 report.
setWellFailed({CR::WellFailure::Type::Unsolvable, CR::Severity::Normal, -1, well->name()});
1817 local_report += report;
1825 if (checkWellGroupControlsAndNetwork) {
1831 if (this->terminal_output_) {
1835 OpmLog::debug(
"NaN residual found with phase " +
std::to_string(f.phase()) +
" for well " + f.wellName());
1837 OpmLog::debug(
"Too large residual found with phase " +
std::to_string(f.phase()) +
" for well " + f.wellName());
1848 template<
typename TypeTag>
1854 for (
auto& well : well_container_) {
1855 well->calculateExplicitQuantities(simulator_, this->groupStateHelper());
1863 template<
typename TypeTag>
1869 if (!this->wellsActive() && !this->isReservoirCouplingMaster()) {
1872 const int episodeIdx = simulator_.episodeIndex();
1873 const auto& comm = simulator_.vanguard().grid().comm();
1880 const auto nupcol = this->schedule()[episodeIdx].nupcol();
1881 const auto& iter_ctx = simulator_.problem().iterationContext();
1882 if (iter_ctx.withinNupcol(nupcol)) {
1884 for (
const auto& well : well_container_) {
1885 well->updateWeldrawMaxRate(simulator_, this->wellState(), deferred_logger);
1888 simulator_.gridView().comm());
1893 bool changed_well_group =
false;
1894 const Group& fieldGroup = this->schedule().getGroup(
"FIELD", episodeIdx);
1897 const std::size_t max_iter = param_.well_group_constraints_max_iterations_;
1898 while(!changed_well_group && iter < max_iter) {
1899 changed_well_group = updateGroupControls(fieldGroup, deferred_logger, episodeIdx);
1902 bool changed_well_to_group =
false;
1904 OPM_TIMEBLOCK(UpdateWellControls);
1908 for (
const auto& well : well_container_) {
1911 simulator_, mode, this->groupStateHelper(), this->wellState()
1914 changed_well_to_group = changed_well || changed_well_to_group;
1918 simulator_.gridView().comm());
1921 changed_well_to_group = comm.sum(
static_cast<int>(changed_well_to_group));
1922 if (changed_well_to_group) {
1923 updateAndCommunicate(episodeIdx);
1924 changed_well_group =
true;
1928 bool changed_well_individual =
false;
1933 for (
const auto& well : well_container_) {
1936 simulator_, mode, this->groupStateHelper(), this->wellState()
1939 changed_well_individual = changed_well || changed_well_individual;
1943 simulator_.gridView().comm());
1946 changed_well_individual = comm.sum(
static_cast<int>(changed_well_individual));
1947 if (changed_well_individual) {
1948 updateAndCommunicate(episodeIdx);
1949 changed_well_group =
true;
1955 this->updateWsolvent(fieldGroup, episodeIdx, this->nupcolWellState());
1957 return changed_well_group;
1961 template<
typename TypeTag>
1966 this->updateAndCommunicateGroupData(reportStepIdx,
true);
1972 for (
const auto& well : well_container_) {
1974 const auto& ws = this->wellState().well(well->indexOfWell());
1975 if (ws.production_cmode == Well::ProducerCMode::GRUP ||
1976 ws.injection_cmode == Well::InjectorCMode::GRUP)
1978 well->updateWellStateWithTarget(
1979 simulator_, this->groupStateHelper(), this->wellState()
1984 simulator_.gridView().comm())
1985 this->updateAndCommunicateGroupData(reportStepIdx,
true);
1988 template<
typename TypeTag>
1993 const int reportStepIdx)
1996 const auto& iterCtx = simulator_.problem().iterationContext();
1997 bool changed =
false;
1999 const int nupcol = this->schedule()[reportStepIdx].nupcol();
2000 const bool update_group_switching_log = !iterCtx.withinNupcol(nupcol);
2001 const bool changed_hc = this->checkGroupHigherConstraints(
2002 group, deferred_logger, reportStepIdx, update_group_switching_log);
2005 updateAndCommunicate(reportStepIdx);
2008 bool changed_individual =
2010 updateGroupIndividualControl(group,
2012 param_.max_number_of_group_switches_,
2013 update_group_switching_log,
2014 this->switched_inj_groups_,
2015 this->switched_prod_groups_,
2016 this->closed_offending_wells_,
2021 if (changed_individual) {
2023 updateAndCommunicate(reportStepIdx);
2026 for (
const std::string& groupName : group.groups()) {
2027 bool changed_this = updateGroupControls(this->schedule().getGroup(groupName, reportStepIdx), deferred_logger, reportStepIdx);
2028 changed = changed || changed_this;
2033 template<
typename TypeTag>
2039 auto logger_guard = this->groupStateHelper().pushLogger();
2040 auto& local_deferredLogger = this->groupStateHelper().deferredLogger();
2041 for (
const auto& well : well_container_) {
2042 const auto& wname = well->name();
2043 const auto wasClosed = wellTestState.well_is_closed(wname);
2044 well->checkWellOperability(simulator_,
2046 this->groupStateHelper());
2047 const bool under_zero_target =
2048 well->wellUnderZeroGroupRateTarget(this->groupStateHelper());
2049 well->updateWellTestState(this->wellState().well(wname),
2055 this->eclipseState().getUnits(),
2056 this->schedule().getStartTime(),
2057 local_deferredLogger);
2059 if (!wasClosed && wellTestState.well_is_closed(wname)) {
2060 this->closed_this_step_.insert(wname);
2063 const WellEconProductionLimits& econ_production_limits = well->wellEcl().getEconLimits();
2064 if (econ_production_limits.validFollowonWell()) {
2065 const auto episode_idx = simulator_.episodeIndex();
2066 const auto follow_on_well = econ_production_limits.followonWell();
2067 if (!this->schedule().hasWell(follow_on_well, episode_idx)) {
2068 const auto msg = fmt::format(
"Well {} was closed. But the given follow on well {} does not exist."
2069 "The simulator continues without opening a follow on well.",
2070 wname, follow_on_well);
2071 local_deferredLogger.warning(msg);
2073 auto& ws = this->wellState().well(follow_on_well);
2074 const bool success = ws.updateStatus(WellStatus::OPEN);
2076 const auto msg = fmt::format(
"Well {} was closed. The follow on well {} opens instead.", wname, follow_on_well);
2077 local_deferredLogger.info(msg);
2079 const auto msg = fmt::format(
"Well {} was closed. The follow on well {} is already open.", wname, follow_on_well);
2080 local_deferredLogger.warning(msg);
2087 for (
const auto& [group_name, to] : this->closed_offending_wells_) {
2088 if (this->hasOpenLocalWell(to.second) &&
2089 !this->wasDynamicallyShutThisTimeStep(to.second))
2091 wellTestState.close_well(to.second,
2092 WellTestConfig::Reason::GROUP,
2094 this->updateClosedWellsThisStep(to.second);
2095 const std::string msg =
2096 fmt::format(
"Procedure on exceeding {} limit is WELL for group {}. "
2102 local_deferredLogger.info(msg);
2108 template<
typename TypeTag>
2112 std::string& exc_msg,
2116 const int np = this->numPhases();
2117 std::vector<Scalar> potentials;
2118 const auto& well = well_container_[widx];
2119 std::string cur_exc_msg;
2122 well->computeWellPotentials(simulator_, well_state_copy, this->groupStateHelper(), potentials);
2127 exc_msg += fmt::format(
"\nFor well {}: {}", well->name(), cur_exc_msg);
2129 exc_type = std::max(exc_type, cur_exc_type);
2133 auto& ws = this->wellState().well(well->indexOfWell());
2134 for (
int p = 0; p < np; ++p) {
2136 ws.well_potentials[p] = std::max(
Scalar{0.0}, potentials[p]);
2142 template <
typename TypeTag>
2147 for (
const auto& wellPtr : this->well_container_) {
2148 this->calculateProductivityIndexValues(wellPtr.get(), deferred_logger);
2156 template <
typename TypeTag>
2167 for (
const auto& shutWell : this->local_shut_wells_) {
2168 if (!this->wells_ecl_[shutWell].hasConnections()) {
2173 auto wellPtr = this->
template createTypedWellPointer
2176 wellPtr->
init(this->depth_, this->gravity_, this->B_avg_,
true);
2178 this->calculateProductivityIndexValues(wellPtr.get(), deferred_logger);
2186 template <
typename TypeTag>
2200 template<
typename TypeTag>
2205 const auto episodeIdx = simulator_.episodeIndex();
2208 const bool do_prestep_network_rebalance = this->shouldDoPreStepNetworkRebalance_(episodeIdx);
2210 for (
const auto& well : well_container_) {
2211 auto& events = this->wellState().well(well->indexOfWell()).events;
2213 well->updateWellStateWithTarget(
2214 simulator_, this->groupStateHelper(), this->wellState()
2216 well->updatePrimaryVariables(this->groupStateHelper());
2222 if (events.hasEvent(ScheduleEvents::REQUEST_OPEN_WELL)) {
2223 events.clearEvent(ScheduleEvents::REQUEST_OPEN_WELL);
2226 if (param_.solve_welleq_initially_ && well->isOperableAndSolvable()) {
2228 well->solveWellEquation(
2229 simulator_, this->groupStateHelper(), this->wellState()
2231 }
catch (
const std::exception& e) {
2232 const std::string msg =
"Compute initial well solution for " + well->name() +
" initially failed. Continue with the previous rates";
2233 deferred_logger.
warning(
"WELL_INITIAL_SOLVE_FAILED", msg);
2238 well->resetWellOperability();
2240 updatePrimaryVariables();
2243 if (do_prestep_network_rebalance) {
2244 network_.doPreStepRebalance(deferred_logger);
2248 template<
typename TypeTag>
2253 std::vector< Scalar > B_avg(numConservationQuantities(),
Scalar() );
2254 const auto& grid = simulator_.vanguard().grid();
2255 const auto& gridView = grid.leafGridView();
2259 for (
const auto& elem : elements(gridView, Dune::Partitions::interior)) {
2260 elemCtx.updatePrimaryStencil(elem);
2261 elemCtx.updatePrimaryIntensiveQuantities(0);
2263 const auto& intQuants = elemCtx.intensiveQuantities(0, 0);
2264 const auto& fs = intQuants.fluidState();
2266 for (
unsigned phaseIdx = 0; phaseIdx < FluidSystem::numPhases; ++phaseIdx)
2268 if (!FluidSystem::phaseIsActive(phaseIdx)) {
2272 const unsigned compIdx = FluidSystem::canonicalToActiveCompIdx(FluidSystem::solventComponentIndex(phaseIdx));
2273 auto& B = B_avg[ compIdx ];
2275 B += 1 / fs.invB(phaseIdx).value();
2277 if constexpr (has_solvent_) {
2278 auto& B = B_avg[solventSaturationIdx];
2279 B += 1 / intQuants.solventInverseFormationVolumeFactor().value();
2285 grid.comm().sum(B_avg.data(), B_avg.size());
2286 B_avg_.resize(B_avg.size());
2287 std::ranges::transform(B_avg, B_avg_.begin(),
2288 [gcells = global_num_cells_](
const auto bval)
2289 { return bval / gcells; });
2296 template<
typename TypeTag>
2301 for (
const auto& well : well_container_) {
2302 well->updatePrimaryVariables(this->groupStateHelper());
2306 template<
typename TypeTag>
2310 const auto& grid = simulator_.vanguard().grid();
2311 const auto& eclProblem = simulator_.problem();
2312 const unsigned numCells = grid.size(0);
2314 this->pvt_region_idx_.resize(numCells);
2315 for (
unsigned cellIdx = 0; cellIdx < numCells; ++cellIdx) {
2316 this->pvt_region_idx_[cellIdx] =
2317 eclProblem.pvtRegionIndex(cellIdx);
2322 template<
typename TypeTag>
2338 return this->numPhases() + has_solvent_;
2341 template<
typename TypeTag>
2345 const auto& eclProblem = simulator_.problem();
2346 depth_.resize(local_num_cells_);
2347 for (
unsigned cellIdx = 0; cellIdx < local_num_cells_; ++cellIdx) {
2348 depth_[cellIdx] = eclProblem.dofCenterDepth(cellIdx);
2352 template<
typename TypeTag>
2355 getWell(
const std::string& well_name)
const
2359 std::ranges::find_if(well_container_,
2361 {
return elem->name() == well_name; });
2363 assert(well != well_container_.end());
2368 template <
typename TypeTag>
2373 return std::max(this->simulator_.episodeIndex(), 0);
2380 template<
typename TypeTag>
2385 const std::vector<Scalar>& production_rates,
2386 std::vector<Scalar>& resv_coeff)
const
2388 rateConverter_->calcCoeff(fipnum, pvtreg, production_rates, resv_coeff);
2391 template<
typename TypeTag>
2396 std::vector<Scalar>& resv_coeff)
const
2398 rateConverter_->calcInjCoeff(fipnum, pvtreg, resv_coeff);
2402 template <
typename TypeTag>
2407 if constexpr (energyModuleType_ == EnergyModules::FullyImplicitThermal) {
2408 const int np = this->numPhases();
2409 const int nw = this->numLocalWells();
2410 for (
auto wellID = 0*nw; wellID < nw; ++wellID) {
2411 const Well& well = this->wells_ecl_[wellID];
2412 auto& ws = this->wellState().well(wellID);
2413 if (well.isInjector()) {
2414 if (ws.status != WellStatus::STOP) {
2415 this->wellState().well(wellID).temperature = well.inj_temperature();
2419 std::array<Scalar,2> weighted{0.0,0.0};
2420 auto& [weighted_temperature, total_weight] = weighted;
2421 const auto& well_info = this->local_parallel_well_info_[wellID].get();
2422 using int_type =
decltype(this->well_perf_data_[wellID].size());
2423 for (int_type perf = 0, end_perf = this->well_perf_data_[wellID].size(); perf < end_perf; ++perf) {
2424 const int cell_idx = this->well_perf_data_[wellID][perf].cell_index;
2425 const auto& intQuants = simulator_.model().intensiveQuantities(cell_idx, 0);
2426 const auto& fs = intQuants.fluidState();
2427 Scalar weight_factor = computeTemperatureWeightFactor(perf, np, fs, ws);
2428 total_weight += weight_factor;
2429 weighted_temperature += weight_factor * fs.temperature(0).value();
2431 well_info.communication().sum(weighted.data(), 2);
2432 this->wellState().well(wellID).temperature = weighted_temperature / total_weight;
2438 template <
typename TypeTag>
2440 -> typename
WellState<Scalar,IndexTraits>::RsConstInfo
2442 if (! FluidSystem::phaseIsActive(FluidSystem::oilPhaseIdx) ||
2443 ! FluidSystem::enableConstantRs())
2448 const auto& rsConstTables = this->eclState_
2449 .getTableManager().getRsconstTables();
2451 if (rsConstTables.empty() ||
2452 (rsConstTables[0].numRows() != std::size_t{1}))
2457 const auto rsConst = rsConstTables[0].getColumn(0).front();
2459 return {
true,
static_cast<Scalar
>(rsConst) };
2465 template <
typename TypeTag>
2466 void BlackoilWellModel<TypeTag>::
2467 assignWellTracerRates_(data::Wells& wsrpt)
const
2469 const auto reportStepIdx =
static_cast<unsigned int>(this->reportStepIndex());
2470 const auto& trMod = this->simulator_.problem().tracerModel();
2476 this->assignMswTracerRates(wsrpt, trMod.getMswTracerRates(), reportStepIdx);
2479 template <
typename TypeTag>
2480 void BlackoilWellModel<TypeTag>::
2481 assignWellSpeciesRates_(data::Wells& wsrpt)
const
2483 const auto reportStepIdx =
static_cast<unsigned int>(this->reportStepIndex());
2484 const auto& geochemMod = this->simulator_.problem().geochemistryModel();
2488 this->assignMswTracerRates(wsrpt, geochemMod.getMswSpeciesRates(), reportStepIdx);
2491 template <
typename TypeTag>
2492 bool BlackoilWellModel<TypeTag>::isRescoupMasterCoupledNetworkIteration_()
const
2494#ifdef RESERVOIR_COUPLING_ENABLED
2495 return this->rescoupHelper_.masterIsInCoupledNetworkIteration();
2501 template <
typename TypeTag>
2502 bool BlackoilWellModel<TypeTag>::isRescoupSlaveCoupledNetworkIteration_()
const
2513#ifdef RESERVOIR_COUPLING_ENABLED
2514 return this->isRescoupSlaveOnSyncStepFirstSubstep_()
2515 && this->reservoirCouplingSlave().connectedToMasterCoupledNetwork()
2516 && !this->reservoirCouplingSlave().lastReceivedMasterGroupNodePressuresIsFinal();
2522 template <
typename TypeTag>
2523 bool BlackoilWellModel<TypeTag>::isRescoupSlaveOnSyncStepFirstSubstep_()
const
2530#ifdef RESERVOIR_COUPLING_ENABLED
2531 return this->isReservoirCouplingSlave()
2532 && this->reservoirCouplingSlave().isFirstSubstepOfSyncTimestep();
2538 template <
typename TypeTag>
2539 bool BlackoilWellModel<TypeTag>::isRescoupSlaveConnectedToMasterNetwork_()
const
2541#ifdef RESERVOIR_COUPLING_ENABLED
2542 return this->isReservoirCouplingSlave()
2543 && this->reservoirCouplingSlave().connectedToMasterCoupledNetwork();
2549 template <
typename TypeTag>
2550 bool BlackoilWellModel<TypeTag>::
2551 maybeSendSlaveGroupFlowToMaster_([[maybe_unused]]
const int reportStepIdx)
2553#ifdef RESERVOIR_COUPLING_ENABLED
2560 assert(this->isReservoirCouplingSlave());
2561 const bool is_final =
2562 this->reservoirCouplingSlave().lastReceivedMasterGroupNodePressuresIsFinal();
2564 this->updateAndCommunicateGroupData(reportStepIdx,
false);
2565 this->rescoupHelper_.sendSlaveGroupDataToMaster();
2569 this->rescoupHelper_.receiveRefreshedGroupConstraintsFromMaster();
2578 template <
typename TypeTag>
2579 void BlackoilWellModel<TypeTag>::
2580 sendSlaveNetworkLoopTerminationSignal_()
2582#ifdef RESERVOIR_COUPLING_ENABLED
2587 assert(this->isReservoirCouplingMaster());
2588 this->rescoupHelper_.sendMasterGroupNodePressuresToSlaves(
true);
2592 template <
typename TypeTag>
2593 bool BlackoilWellModel<TypeTag>::
2594 shouldDoPreStepNetworkRebalance_(
const int episodeIdx)
const
2607 return param_.pre_solve_network_
2608 && this->network_.needPreStepRebalance(episodeIdx)
2609 && !this->isRescoupCoupledNetworkParticipant_();
2612 template <
typename TypeTag>
2613 bool BlackoilWellModel<TypeTag>::isRescoupCoupledNetworkParticipant_()
const
2615#ifdef RESERVOIR_COUPLING_ENABLED
2616 if (this->isReservoirCouplingMaster()) {
2617 return this->rescoupHelper_.masterNetworkHasMasterGroupLeaves();
2619 if (this->isReservoirCouplingSlave()) {
2620 return this->reservoirCouplingSlave().connectedToMasterCoupledNetwork();
2628 template <
typename TypeTag>
2629 void BlackoilWellModel<TypeTag>::
2630 updateNetworkActiveState_()
2641 const int episodeIdx = this->simulator_.episodeIndex();
2642 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:101
BlackoilWellModelWBP< Scalar, IndexTraits > wbp_
Definition: BlackoilWellModelGeneric.hpp:630
std::vector< std::unique_ptr< ParallelWellInfo< Scalar > > > parallel_well_info_
Definition: BlackoilWellModelGeneric.hpp:661
void updateFailed()
Restore the state captured at the start of the failing timestep.
Definition: BlackoilWellModelGeneric.hpp:242
void advanceTimeLevel()
Snapshot the mutable well-model state at the start of a timestep.
Definition: BlackoilWellModelGeneric.hpp:229
const Parallel::Communication & comm() const
Definition: BlackoilWellModelGeneric.hpp:267
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:100
void initializeGroupStructure(const int reportStepIdx)
Definition: BlackoilWellModel_impl.hpp:309
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:2383
void prepareTimeStep(DeferredLogger &deferred_logger)
Definition: BlackoilWellModel_impl.hpp:2203
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:1421
WellInterfacePtr createWellPointer(const int wellID, const int report_step) const
Definition: BlackoilWellModel_impl.hpp:1138
void prepareWellsBeforeAssembling(const double dt)
Definition: BlackoilWellModel_impl.hpp:1544
void init()
Definition: BlackoilWellModel_impl.hpp:167
const Simulator & simulator() const
Definition: BlackoilWellModel.hpp:399
std::vector< Scalar > depth_
Definition: BlackoilWellModel.hpp:609
std::size_t global_num_cells_
Definition: BlackoilWellModel.hpp:605
GetPropType< TypeTag, Properties::Scalar > Scalar
Definition: BlackoilWellModel.hpp:109
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:1605
void initWellContainer(const int reportStepIdx) override
Definition: BlackoilWellModel_impl.hpp:186
void beginReportStep(const int time_step)
Definition: BlackoilWellModel_impl.hpp:203
const WellInterface< TypeTag > & getWell(const std::string &well_name) const
Definition: BlackoilWellModel_impl.hpp:2355
GetPropType< TypeTag, Properties::FluidSystem > FluidSystem
Definition: BlackoilWellModel.hpp:105
Dune::FieldVector< Scalar, numEq > VectorBlockType
Definition: BlackoilWellModel.hpp:133
GetPropType< TypeTag, Properties::ElementContext > ElementContext
Definition: BlackoilWellModel.hpp:106
GetPropType< TypeTag, Properties::Grid > Grid
Definition: BlackoilWellModel.hpp:103
int numConservationQuantities() const
Definition: BlackoilWellModel_impl.hpp:2324
bool updateWellControls(DeferredLogger &deferred_logger)
Definition: BlackoilWellModel_impl.hpp:1866
int reportStepIndex() const
Definition: BlackoilWellModel_impl.hpp:2371
void calculateProductivityIndexValues(DeferredLogger &deferred_logger) override
Definition: BlackoilWellModel_impl.hpp:2145
void extractLegacyDepth_()
Definition: BlackoilWellModel_impl.hpp:2343
void extractLegacyCellPvtRegionIndex_()
Definition: BlackoilWellModel_impl.hpp:2308
void recoverWellSolutionAndUpdateWellStateDomain(const BVector &x, const int domainIdx)
Definition: BlackoilWellModel_impl.hpp:1787
void updateAverageFormationFactor()
Definition: BlackoilWellModel_impl.hpp:2251
GetPropType< TypeTag, Properties::Simulator > Simulator
Definition: BlackoilWellModel.hpp:108
BlackoilWellModel(Simulator &simulator, const NewtonIterationContext &iter_ctx)
Definition: BlackoilWellModel_impl.hpp:74
void initializeWellState(const int timeStepIdx)
Definition: BlackoilWellModel_impl.hpp:868
const Grid & grid() const
Definition: BlackoilWellModel.hpp:396
void updatePrimaryVariables()
Definition: BlackoilWellModel_impl.hpp:2299
void computeWellTemperature()
Definition: BlackoilWellModel_impl.hpp:2405
const SimulatorReportSingle & lastReport() const
Definition: BlackoilWellModel_impl.hpp:704
bool updateWellControlsAndNetwork(const bool mandatory_network_balance, const double dt, DeferredLogger &local_deferredLogger)
Definition: BlackoilWellModel_impl.hpp:1348
void addWellContributions(SparseMatrixAdapter &jacobian) const
Definition: BlackoilWellModel_impl.hpp:1666
void assembleWellEq(const double dt)
Definition: BlackoilWellModel_impl.hpp:1532
WellInterfacePtr createWellForWellTest(const std::string &well_name, const int report_step, DeferredLogger &deferred_logger) const
Definition: BlackoilWellModel_impl.hpp:1189
void calculateExplicitQuantities() const
Definition: BlackoilWellModel_impl.hpp:1851
void collectWellSolveStats()
Definition: BlackoilWellModel_impl.hpp:1303
void updateAndCommunicate(const int reportStepIdx)
Definition: BlackoilWellModel_impl.hpp:1964
Dune::BCRSMatrix< Opm::MatrixBlock< Scalar, 1, 1 > > PressureMatrix
Definition: BlackoilWellModel.hpp:308
void updateFailed()
Definition: BlackoilWellModel_impl.hpp:612
void computeTotalRatesForDof(RateVector &rate, unsigned globalIdx) const
Definition: BlackoilWellModel_impl.hpp:831
void stashWellSolveStats()
Definition: BlackoilWellModel_impl.hpp:1319
void beginTimeStep()
Definition: BlackoilWellModel_impl.hpp:341
GetPropType< TypeTag, Properties::RateVector > RateVector
Definition: BlackoilWellModel.hpp:110
bool updateGroupControls(const Group &group, DeferredLogger &deferred_logger, const int reportStepIdx)
Definition: BlackoilWellModel_impl.hpp:1991
void initializeLocalWellStructure(const int reportStepIdx, const bool enableWellPIScaling, const bool initializeWellState)
Definition: BlackoilWellModel_impl.hpp:255
void calcInjResvCoeff(const int fipnum, const int pvtreg, std::vector< Scalar > &resv_coeff) const override
Definition: BlackoilWellModel_impl.hpp:2394
Dune::BlockVector< VectorBlockType > BVector
Definition: BlackoilWellModel.hpp:134
void wellTesting(const int timeStepIdx, const double simulationTime, DeferredLogger &deferred_logger)
Definition: BlackoilWellModel_impl.hpp:627
ConvergenceReport getWellConvergence(const std::vector< Scalar > &B_avg, const bool checkWellGroupControlsAndNetwork=false) const
Definition: BlackoilWellModel_impl.hpp:1800
typename FluidSystem::IndexTraitsType IndexTraits
Definition: BlackoilWellModel.hpp:116
void updateCellRatesForDomain(int domainIndex, const std::map< std::string, int > &well_domain_map)
Definition: BlackoilWellModel_impl.hpp:1590
void assembleWellEqWithoutIteration(const double dt)
Definition: BlackoilWellModel_impl.hpp:1558
void updateCellRates()
Definition: BlackoilWellModel_impl.hpp:1578
void assemble(const double dt)
Definition: BlackoilWellModel_impl.hpp:1214
std::size_t local_num_cells_
Definition: BlackoilWellModel.hpp:607
bool alternative_well_rate_init_
Definition: BlackoilWellModel.hpp:610
void timeStepSucceeded(const double simulationTime, const double dt)
Definition: BlackoilWellModel_impl.hpp:714
std::unique_ptr< WellType > createTypedWellPointer(const int wellID, const int time_step) const
Definition: BlackoilWellModel_impl.hpp:1158
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:2110
Simulator & simulator_
Definition: BlackoilWellModel.hpp:579
void createWellContainer(const int report_step) override
Definition: BlackoilWellModel_impl.hpp:911
std::unique_ptr< WellInterface< TypeTag > > WellInterfacePtr
Definition: BlackoilWellModel.hpp:194
void updateWellTestState(const double simulationTime, WellTestState &wellTestState)
upate the wellTestState related to economic limits
Definition: BlackoilWellModel_impl.hpp:2036
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:1675
void addSolveStats(const WellInterface< TypeTag > &well)
Definition: BlackoilWellModel_impl.hpp:1329
void addReservoirSourceTerms(GlobalEqVector &residual, const std::vector< typename SparseMatrixAdapter::MatrixBlock * > &diagMatAddress) const
Definition: BlackoilWellModel_impl.hpp:1713
int compressedIndexForInterior(int cartesian_cell_idx) const override
get compressed index for interior cells (-1, otherwise
Definition: BlackoilWellModel.hpp:364
void addWellPressureEquations(PressureMatrix &jacobian, const BVector &weights, const bool use_well_weights, const bool contract_d_diagonal) const
Definition: BlackoilWellModel_impl.hpp:1689
void recoverWellSolutionAndUpdateWellState(const BVector &x)
Definition: BlackoilWellModel_impl.hpp:1763
void addWellPressureEquationsStruct(PressureMatrix &jacobian) const
Definition: BlackoilWellModel_impl.hpp:1743
void calculateProductivityIndexValuesShutWells(const int reportStepIdx, DeferredLogger &deferred_logger) override
Definition: BlackoilWellModel_impl.hpp:2159
void advanceTimeLevel()
Definition: BlackoilWellModel_impl.hpp:620
void endReportStep()
Definition: BlackoilWellModel_impl.hpp:687
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:67
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:298
void resetSolveStats() const
Definition: WellInterfaceGeneric.hpp:299
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:194
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