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
395 if (this->isReservoirCouplingSlave()) {
396 this->groupStateHelper().updateSlaveGroupCmodesFromMaster();
399 const int reportStepIdx = simulator_.episodeIndex();
401 this->wellState().updateWellsDefaultALQ(this->schedule(), reportStepIdx, this->summaryState());
402 this->wellState().gliftTimeStepInit();
404 const double simulationTime = simulator_.time();
406 this->well_performance_event_tracker_.beginTimeStep(this->schedule(), reportStepIdx,
407 this->wellStatusSnapshot());
412 wellTesting(reportStepIdx, simulationTime, local_deferredLogger);
415 stashWellSolveStats();
419 this->well_performance_event_tracker_.accumulate(this->wellStatusSnapshot());
422 createWellContainer(reportStepIdx);
426 this->well_performance_event_tracker_.applyDeckChanges(this->wellStatusSnapshot());
428#ifdef RESERVOIR_COUPLING_ENABLED
429 if (this->isReservoirCouplingMaster()) {
430 if (this->reservoirCouplingMaster().isFirstSubstepOfSyncTimestep()) {
431 this->rescoupHelper_.receiveSlaveGroupData();
438 this->updateAndCommunicateGroupData(reportStepIdx,
false);
441 const Grid& grid = simulator_.vanguard().grid();
442 this->wells_active_ = grid.comm().max(!this->well_container_.empty());
447 this->initWellContainer(reportStepIdx);
450 std::fill(is_cell_perforated_.begin(), is_cell_perforated_.end(),
false);
451 for (
auto& well : well_container_) {
452 well->updatePerforatedCell(is_cell_perforated_);
456 this->calculateEfficiencyFactors(reportStepIdx);
458 if constexpr (has_polymer_)
460 if (PolymerModule::hasPlyshlog() || getPropValue<TypeTag, Properties::EnablePolymerMW>() ) {
461 this->setRepRadiusPerfLength();
468 this->terminal_output_, simulator_.vanguard().grid().comm());
470 for (
auto& well : well_container_) {
471 well->setVFPProperties(this->vfp_properties_.get());
472 well->setGuideRate(&this->guideRate_);
475 this->updateFiltrationModelsPreStep(local_deferredLogger);
478 for (
auto& well : well_container_) {
479 well->closeCompletions(this->wellTestState());
485 if (alternative_well_rate_init_) {
490 for (
const auto& well : well_container_) {
491 if (well->isProducer() && !well->wellIsStopped()) {
492 well->initializeProducerWellState(simulator_, this->wellState(), local_deferredLogger);
497 for (
const auto& well : well_container_) {
498 if (well->isVFPActive(local_deferredLogger)){
499 well->setPrevSurfaceRates(this->wellState(), this->prevWellState());
503 this->updateWellPotentials(reportStepIdx,
505 simulator_.vanguard().summaryConfig(),
506 local_deferredLogger);
507 }
catch ( std::runtime_error& e ) {
508 const std::string msg =
"A zero well potential is returned for output purposes. ";
509 local_deferredLogger.warning(
"WELL_POTENTIAL_CALCULATION_FAILED", msg);
512 this->guide_rate_handler_.updateGuideRates(
513 reportStepIdx, simulationTime, this->wellState(), this->groupState()
515 bool slave_needs_well_solution =
false;
516#ifdef RESERVOIR_COUPLING_ENABLED
517 if (this->isReservoirCouplingSlave()) {
518 if (this->reservoirCouplingSlave().isFirstSubstepOfSyncTimestep()) {
522 this->reservoirCouplingSlave().setWellsSolvedThisSyncStep(
false);
523 this->rescoupHelper_.sendSlaveGroupDataToMaster();
524 this->rescoupHelper_.receiveGroupConstraintsFromMaster();
525 this->rescoupHelper_.receiveCoupledNetworkActiveStatus();
526 this->groupStateHelper().updateSlaveGroupCmodesFromMaster();
527 this->reservoirCouplingSlave().markSlaveGroupsInSchedule(
528 this->schedule_, reportStepIdx);
529 this->rescoupHelper_.refreshSlaveGroupTargets();
530 slave_needs_well_solution =
true;
537 if (this->schedule_[reportStepIdx].has_gpmaint()) {
538 for (
const auto& calculator : regionalAveragePressureCalculator_) {
539 calculator.second->template defineState<ElementContext>(simulator_);
541 const double dt = simulator_.timeStepSize();
542 const Group& fieldGroup = this->schedule().getGroup(
"FIELD", reportStepIdx);
544 this->groupStateHelper().updateGpMaintTargetForGroups(fieldGroup,
545 regionalAveragePressureCalculator_,
551 this->updateAndCommunicateGroupData(reportStepIdx,
true);
554 for (
auto& well : well_container_) {
555 const uint64_t effective_events_mask = ScheduleEvents::WELL_STATUS_CHANGE
556 + ScheduleEvents::INJECTION_TYPE_CHANGED
557 + ScheduleEvents::WELL_SWITCHED_INJECTOR_PRODUCER
558 + ScheduleEvents::NEW_WELL;
560 const auto& events = this->schedule()[reportStepIdx].wellgroup_events();
561 const bool event = this->report_step_starts_ && events.hasEvent(well->name(), effective_events_mask);
562 const bool dyn_status_change = this->wellState().well(well->name()).status
563 != this->prevWellState().well(well->name()).status;
565 if (event || dyn_status_change || slave_needs_well_solution) {
567 well->scaleSegmentRatesAndPressure(this->wellState());
568 well->calculateExplicitQuantities(simulator_, this->groupStateHelper());
569 well->updateWellStateWithTarget(simulator_, this->groupStateHelper(), this->wellState());
570 well->updatePrimaryVariables(this->groupStateHelper());
571 well->solveWellEquation(
572 simulator_, this->groupStateHelper(), this->wellState()
574 }
catch (
const std::exception& e) {
575 const std::string msg =
"Compute initial well solution for new well " + well->name() +
" failed. Continue with zero initial rates";
576 local_deferredLogger.warning(
"WELL_INITIAL_SOLVE_FAILED", msg);
584#ifdef RESERVOIR_COUPLING_ENABLED
585 if (slave_needs_well_solution) {
587 this->reservoirCouplingSlave().setWellsSolvedThisSyncStep(
true);
589 this->updateAndCommunicateGroupData(reportStepIdx,
false);
590 this->rescoupHelper_.sendSlaveGroupDataToMaster();
592 this->rescoupHelper_.receiveRefreshedGroupConstraintsFromMaster();
594 else if (this->isReservoirCouplingMaster()) {
595 if (this->reservoirCouplingMaster().isFirstSubstepOfSyncTimestep()) {
596 this->rescoupHelper_.sendMasterGroupConstraintsToSlaves();
597 this->rescoupHelper_.sendCoupledNetworkActiveStatus();
598 this->rescoupHelper_.receiveSlaveGroupData();
601 this->rescoupHelper_.refreshAndSendGroupConstraints();
607 const std::string msg =
"Compute initial well solution for new wells failed. Continue with zero initial rates";
608 local_deferredLogger.warning(
"WELL_INITIAL_SOLVE_FAILED", msg);
611 const auto& comm = simulator_.vanguard().grid().comm();
613 exc_type,
"beginTimeStep() failed: " + exc_msg, this->terminal_output_, comm);
617 template<
typename TypeTag>
625 template<
typename TypeTag>
633 template<
typename TypeTag>
636 const double simulationTime,
639 for (
const std::string& well_name : this->getWellsForTesting(timeStepIdx, simulationTime)) {
640 const Well& wellEcl = this->schedule().getWell(well_name, timeStepIdx);
641 if (wellEcl.getStatus() == Well::Status::SHUT)
644 WellInterfacePtr well = createWellForWellTest(well_name, timeStepIdx, deferred_logger);
646 well->init(depth_, gravity_, B_avg_,
true);
648 Scalar well_efficiency_factor = wellEcl.getEfficiencyFactor() *
649 this->wellState().getGlobalEfficiencyScalingFactor(well_name);
650 this->groupStateHelper().accumulateGroupEfficiencyFactor(
651 this->schedule().getGroup(wellEcl.groupName(), timeStepIdx),
652 well_efficiency_factor
655 well->setWellEfficiencyFactor(well_efficiency_factor);
656 well->setVFPProperties(this->vfp_properties_.get());
657 well->setGuideRate(&this->guideRate_);
660 if (well->isProducer() && alternative_well_rate_init_) {
661 well->initializeProducerWellState(simulator_, this->wellState(), deferred_logger);
663 if (well->isVFPActive(deferred_logger)) {
664 well->setPrevSurfaceRates(this->wellState(), this->prevWellState());
667 this->network_.initializeWell(*well);
671 GLiftEclWells ecl_well_map;
672 gaslift_.initGliftEclWellMap(well_container_, ecl_well_map);
673 well->wellTesting(simulator_,
675 this->groupStateHelper(),
677 this->wellTestState(),
679 this->well_open_times_);
680 }
catch (
const std::exception& e) {
681 const std::string msg =
682 fmt::format(fmt::runtime(
"Exception during testing of well: {}. The well will not open.\n"
683 "Exception message: {}"), wellEcl.name(), e.what());
684 deferred_logger.
warning(
"WELL_TESTING_FAILED", msg);
687 addSolveStats(*well);
692 template<
typename TypeTag>
698 for (
auto&& pinfo : this->local_parallel_well_info_)
709 template<
typename TypeTag>
719 template<
typename TypeTag>
724 this->closed_this_step_.clear();
725 this->retry_shut_wells_.clear();
728 this->report_step_starts_ =
false;
729 const int reportStepIdx = simulator_.episodeIndex();
731 auto logger_guard = this->groupStateHelper().pushLogger();
732 auto& local_deferredLogger = this->groupStateHelper().deferredLogger();
733 for (
const auto& well : well_container_) {
734 if (getPropValue<TypeTag, Properties::EnablePolymerMW>() && well->isInjector()) {
735 well->updateWaterThroughput(dt, this->wellState());
739 for (
const auto& well : well_container_) {
740 well->updateConnectionTransmissibilityFactor(simulator_, this->wellState().well(well->indexOfWell()));
741 well->updateConnectionDFactor(simulator_, this->wellState().well(well->indexOfWell()));
744 if constexpr (getPropValue<TypeTag, Properties::EnableMech>()) {
747 updateWellFractureFlowSplit<FluidSystem, Scalar>(
748 this->simulator_, this->well_container_,
749 this->wellState(), this->nupcolWellState());
754 const auto inv_b = [
this](
const int cell_index,
const unsigned canonical_phase) ->
Scalar
756 if (!FluidSystem::phaseIsActive(canonical_phase)) {
759 const auto& intQuants = this->simulator_.model()
760 .intensiveQuantities(cell_index, 0);
761 return getValue(intQuants.fluidState().invB(canonical_phase));
763 this->updateFiltrationModelsPostStep(dt, inv_b, local_deferredLogger);
767 this->updateInjMult(local_deferredLogger);
770 for (
const auto& well : well_container_) {
771 well->reportWellSwitching(this->wellState().well(well->indexOfWell()), local_deferredLogger);
774 if (this->terminal_output_) {
775 this->reportGroupSwitching(local_deferredLogger);
782 if (this->schedule_.numWells(reportStepIdx) != 0
783 || !this->schedule_[reportStepIdx].actions().empty()
784 || this->isReservoirCouplingMaster()) {
785 rateConverter_->template defineState<ElementContext>(simulator_);
790 this->updateWellPotentials(reportStepIdx,
792 simulator_.vanguard().summaryConfig(),
793 local_deferredLogger);
794 }
catch ( std::runtime_error& e ) {
795 const std::string msg =
"A zero well potential is returned for output purposes. ";
796 local_deferredLogger.warning(
"WELL_POTENTIAL_CALCULATION_FAILED", msg);
803 const double closure_time = simulationTime + dt;
805 updateWellTestState(closure_time, this->wellTestState());
808 const Group& fieldGroup = this->schedule_.getGroup(
"FIELD", reportStepIdx);
809 this->checkGEconLimits(fieldGroup, closure_time,
810 simulator_.episodeIndex(), local_deferredLogger);
811 this->checkGconsaleLimits(fieldGroup, this->wellState(),
812 simulator_.episodeIndex(), local_deferredLogger);
814 this->well_performance_event_tracker_.accumulate(this->wellStatusSnapshot());
816 this->calculateProductivityIndexValues(local_deferredLogger);
819 for (
const auto& well : well_container_) {
820 well->consolidatePhaseMixingRates(this->wellState());
823 this->groupStateHelper().updateNONEProductionGroups();
825#ifdef RESERVOIR_COUPLING_ENABLED
826 this->rescoupHelper_.rescoupSyncSummaryData();
828 this->well_performance_event_tracker_.commitTimeStep(this->schedule(), reportStepIdx);
829 this->commitWGState();
832 this->computeWellTemperature();
836 template<
typename TypeTag>
840 unsigned elemIdx)
const
844 if (!is_cell_perforated_[elemIdx] || cellRates_.count(elemIdx) == 0) {
848 rate = cellRates_.at(elemIdx);
852 template<
typename TypeTag>
853 template <
class Context>
857 const Context& context,
859 unsigned timeIdx)
const
862 int elemIdx = context.globalSpaceIndex(spaceIdx, timeIdx);
864 if (!is_cell_perforated_[elemIdx] || cellRates_.count(elemIdx) == 0) {
868 rate = cellRates_.at(elemIdx);
873 template<
typename TypeTag>
878 const auto pressIx = []()
880 if (Indices::oilEnabled) {
return FluidSystem::oilPhaseIdx; }
881 if (Indices::waterEnabled) {
return FluidSystem::waterPhaseIdx; }
883 return FluidSystem::gasPhaseIdx;
886 auto cellPressures = std::vector<Scalar>(this->local_num_cells_,
Scalar{0});
887 auto cellTemperatures = std::vector<Scalar>(this->local_num_cells_,
Scalar{0});
890 const auto& gridView = this->simulator_.vanguard().gridView();
893 for (
const auto& elem : elements(gridView, Dune::Partitions::interior)) {
894 elemCtx.updatePrimaryStencil(elem);
895 elemCtx.updatePrimaryIntensiveQuantities(0);
897 const auto ix = elemCtx.globalSpaceIndex(0, 0);
898 const auto& fs = elemCtx.intensiveQuantities(0, 0).fluidState();
900 cellPressures[ix] = fs.pressure(pressIx).value();
901 cellTemperatures[ix] = fs.temperature(0).value();
904 this->simulator_.vanguard().grid().comm());
906 this->wellState().init(cellPressures, cellTemperatures, this->schedule(), this->wells_ecl_,
907 this->local_parallel_well_info_, timeStepIdx,
908 &this->prevWellState(), this->well_perf_data_,
909 this->summaryState(), simulator_.vanguard().enableDistributedWells());
916 template<
typename TypeTag>
921 auto logger_guard = this->groupStateHelper().pushLogger();
922 auto& local_deferredLogger = this->groupStateHelper().deferredLogger();
924 const int nw = this->numLocalWells();
926 well_container_.clear();
929 well_container_.reserve(nw);
931 const auto& wmatcher = this->schedule().wellMatcher(report_step);
932 const auto& wcycle = this->schedule()[report_step].wcycle.get();
936 std::ranges::for_each(this->wells_ecl_,
937 [
this, &wg_events = this->report_step_start_events_](
const auto& well_ecl)
939 if (!well_ecl.hasConnections()) {
944 constexpr auto events_mask = ScheduleEvents::WELL_STATUS_CHANGE |
945 ScheduleEvents::REQUEST_OPEN_WELL |
946 ScheduleEvents::REQUEST_SHUT_WELL;
947 const bool well_event =
948 this->report_step_starts_ &&
949 wg_events.hasEvent(well_ecl.name(), events_mask);
958 if (well_ecl.getStatus() == WellStatus::OPEN) {
959 this->well_open_times_.insert_or_assign(well_ecl.name(),
960 this->simulator_.time());
961 this->well_close_times_.erase(well_ecl.name());
962 }
else if (well_ecl.getStatus() == WellStatus::SHUT) {
963 this->well_close_times_.insert_or_assign(well_ecl.name(),
964 this->simulator_.time());
965 this->well_open_times_.erase(well_ecl.name());
971 const auto cycle_states = wcycle.wellStatus(this->simulator_.time(),
973 this->well_open_times_,
974 this->well_close_times_);
976 for (
int w = 0; w < nw; ++w) {
977 const Well& well_ecl = this->wells_ecl_[w];
979 if (!well_ecl.hasConnections()) {
984 const std::string& well_name = well_ecl.name();
985 const auto well_status = this->schedule()
986 .getWell(well_name, report_step).getStatus();
988 const bool shut_event = this->wellState().well(w).events.hasEvent(ScheduleEvents::WELL_STATUS_CHANGE)
989 && well_status == Well::Status::SHUT;
990 const bool open_event = this->wellState().well(w).events.hasEvent(ScheduleEvents::WELL_STATUS_CHANGE)
991 && well_status == Well::Status::OPEN;
992 const auto& ws = this->wellState().well(well_name);
994 if (shut_event && ws.status != Well::Status::SHUT) {
995 this->closed_this_step_.insert(well_name);
996 this->wellState().shutWell(w);
997 }
else if (open_event && ws.status != Well::Status::OPEN) {
998 this->wellState().openWell(w);
1002 this->honorOpenRequest(well_name, this->wellState().well(w).events,
1003 this->simulator_.time());
1011 auto& well_test_state = this->wellTestState();
1012 const auto& sched_state = this->schedule()[report_step];
1013 const bool may_reopen_completions =
1014 ws.status == Well::Status::OPEN &&
1015 sched_state.events().hasEvent(ScheduleEvents::COMPLETION_CHANGE) &&
1016 well_test_state.num_closed_completions() > 0;
1018 if (may_reopen_completions) {
1019 const auto& completion_events = sched_state.wellcompletion_events();
1020 for (
const auto& connection : well_ecl.getConnections()) {
1021 const int complnum = connection.complnum();
1025 if (!well_test_state.completion_is_closed(well_name, complnum) ||
1026 !completion_events.hasEvent(well_name, complnum, ScheduleEvents::REQUEST_OPEN_COMPLETION)) {
1031 const bool closed_this_step =
1032 (well_test_state.lastCompletionCloseTime(well_name, complnum) == simulator_.time());
1033 if (closed_this_step) {
1037 well_test_state.open_completion(well_name, complnum);
1038 local_deferredLogger.info(
1039 fmt::format(
"Completion {} - block ({}, {}, {}) for well {} "
1040 "is reopened due to an explicit WELOPEN/COMPDAT "
1043 connection.getI() + 1,
1044 connection.getJ() + 1,
1045 connection.getK() + 1,
1052 if (this->wellTestState().well_is_closed(well_name))
1054 if (this->closedWellStatus(well_ecl) == WellStatus::SHUT)
1056 this->wellState().shutWell(w);
1057 this->well_close_times_.erase(well_name);
1058 this->well_open_times_.erase(well_name);
1062 this->wellState().stopWell(w);
1066 if (!well_ecl.getAllowCrossFlow()) {
1067 const bool any_zero_rate_constraint = well_ecl.isProducer()
1068 ? well_ecl.productionControls(this->summaryState_).anyZeroRateConstraint()
1069 : well_ecl.injectionControls(this->summaryState_).anyZeroRateConstraint();
1070 if (any_zero_rate_constraint) {
1072 local_deferredLogger.debug(fmt::format(fmt::runtime(
" Well {} gets shut due to having zero rate constraint and disallowing crossflow "), well_ecl.name()));
1073 this->wellState().shutWell(w);
1074 this->well_close_times_.erase(well_name);
1075 this->well_open_times_.erase(well_name);
1080 if (!wcycle.empty()) {
1081 const auto it = cycle_states.find(well_name);
1082 if (it != cycle_states.end()) {
1083 if (!it->second || well_status == Well::Status::SHUT) {
1085 if (well_status == Well::Status::SHUT) {
1086 this->well_open_times_.erase(well_name);
1087 this->well_close_times_.erase(well_name);
1089 this->wellState().shutWell(w);
1092 this->wellState().openWell(w);
1098 if (ws.status == Well::Status::SHUT) {
1102 well_container_.emplace_back(this->createWellPointer(w, report_step));
1104 if (ws.status == Well::Status::STOP) {
1105 well_container_.back()->stopWell();
1106 this->well_close_times_.erase(well_name);
1107 this->well_open_times_.erase(well_name);
1111 if (!wcycle.empty()) {
1112 const auto schedule_open =
1113 [&wg_events = this->report_step_start_events_](
const std::string& name)
1115 return wg_events.hasEvent(name, ScheduleEvents::REQUEST_OPEN_WELL);
1117 for (
const auto& [wname, wscale] : wcycle.efficiencyScale(this->simulator_.time(),
1118 this->simulator_.timeStepSize(),
1120 this->well_open_times_,
1123 this->wellState().updateEfficiencyScalingFactor(wname, wscale);
1124 this->schedule_.add_event(ScheduleEvents::WELLGROUP_EFFICIENCY_UPDATE, report_step);
1129 this->well_container_generic_.clear();
1130 for (
auto& w : well_container_) {
1131 this->well_container_generic_.push_back(w.get());
1134 this->network_.initialize(report_step);
1136 this->wbp_.registerOpenWellsForWBPCalculation();
1143 template <
typename TypeTag>
1148 const auto is_multiseg = this->wells_ecl_[wellID].isMultiSegment();
1150 if (! (this->param_.use_multisegment_well_ && is_multiseg)) {
1151 return this->
template createTypedWellPointer<StandardWell<TypeTag>>(wellID, report_step);
1154 return this->
template createTypedWellPointer<MultisegmentWell<TypeTag>>(wellID, report_step);
1162 template <
typename TypeTag>
1163 template <
typename WellType>
1164 std::unique_ptr<WellType>
1169 const auto& perf_data = this->well_perf_data_[wellID];
1172 const auto pvtreg = perf_data.empty()
1173 ? 0 : this->pvt_region_idx_[perf_data.front().cell_index];
1175 const auto& parallel_well_info = this->local_parallel_well_info_[wellID].get();
1176 const auto global_pvtreg = parallel_well_info.broadcastFirstPerforationValue(pvtreg);
1178 return std::make_unique<WellType>(this->wells_ecl_[wellID],
1182 *this->rateConverter_,
1184 this->numConservationQuantities(),
1194 template<
typename TypeTag>
1198 const int report_step,
1203 std::ranges::find_if(this->wells_ecl_,
1204 [&well_name](
const auto& w)
1205 {
return well_name == w.name(); });
1207 if (it == this->wells_ecl_.end()) {
1209 fmt::format(fmt::runtime(
"Could not find well {} in wells_ecl"), well_name),
1213 const int pos =
static_cast<int>(std::distance(this->wells_ecl_.begin(), it));
1214 return this->createWellPointer(pos, report_step);
1219 template<
typename TypeTag>
1225 auto logger_guard = this->groupStateHelper().pushLogger();
1226 auto& local_deferredLogger = this->groupStateHelper().deferredLogger();
1228 const auto& iterCtx = simulator_.problem().iterationContext();
1231 if (gaslift_.terminalOutput()) {
1232 const std::string msg =
1233 fmt::format(fmt::runtime(
"assemble() : iteration {}"), iterCtx.iteration());
1234 gaslift_.gliftDebug(msg, local_deferredLogger);
1238 Dune::Timer perfTimer;
1240 this->closed_offending_wells_.clear();
1243 if (iterCtx.needsTimestepInit()) {
1244 this->updateNetworkActiveState_();
1246 const int episodeIdx = simulator_.episodeIndex();
1253 if (iterCtx.needsTimestepInit() && this->wellsActive()) {
1254 OPM_TIMEBLOCK(firstIterationAssemble);
1255 Dune::Timer prepareTimer;
1256 prepareTimer.start();
1263 calculateExplicitQuantities();
1264 prepareTimeStep(local_deferredLogger);
1267 "assemble() failed during well initialization: ",
1268 this->terminal_output_, grid().comm());
1269 last_report_.well_facility_time += prepareTimer.stop();
1272 Dune::Timer networkTimer;
1273 networkTimer.start();
1274 const bool well_group_control_changed = updateWellControlsAndNetwork(
1277 local_deferredLogger);
1280 const double network_time = networkTimer.stop();
1281 last_report_.well_control_network_time += network_time;
1282 last_report_.well_facility_time += network_time;
1286 if ( ! this->wellsActive() ) {
1290 assembleWellEqWithoutIteration(dt);
1297 collectWellSolveStats();
1301 last_report_.well_group_control_changed = well_group_control_changed;
1302 last_report_.assemble_time_well += perfTimer.stop();
1308 template<
typename TypeTag>
1313 stashWellSolveStats();
1314 const auto& stats = pending_solve_stats_;
1315 last_report_.well_solve_time += stats.solve_time;
1316 last_report_.well_potential_solve_time += stats.potential_solve_time;
1317 last_report_.well_solve_assemble_time += stats.assemble_time;
1318 last_report_.well_solve_linear_solve_time += stats.linear_solve_time;
1319 last_report_.total_well_iterations += stats.iterations;
1320 last_report_.total_well_potential_iterations += stats.potential_iterations;
1321 pending_solve_stats_ = {};
1324 template<
typename TypeTag>
1329 for (
const auto& well : well_container_) {
1330 addSolveStats(*well);
1334 template<
typename TypeTag>
1339 auto& pending = pending_solve_stats_;
1341 pending.solve_time += stats.solve_time;
1342 pending.potential_solve_time += stats.potential_solve_time;
1343 pending.assemble_time += stats.assemble_time;
1344 pending.linear_solve_time += stats.linear_solve_time;
1345 pending.iterations += stats.iterations;
1346 pending.potential_iterations += stats.potential_iterations;
1353 template<
typename TypeTag>
1362 bool do_network_update =
true;
1363 bool well_group_control_changed =
false;
1364 Scalar network_imbalance = 0.0;
1366 const std::size_t iteration_to_relax = param_.network_max_strict_outer_iterations_;
1368 const std::size_t max_iteration = param_.network_max_outer_iterations_;
1369 std::size_t network_update_iteration = 0;
1370 network_needs_more_balancing_force_another_newton_iteration_ =
false;
1371 while (do_network_update) {
1372 if (!this->isRescoupSlaveCoupledNetworkIteration_()
1373 && network_update_iteration >= max_iteration ) {
1374 const int episodeIdx = simulator_.episodeIndex();
1375 const auto& balance = this->schedule()[episodeIdx].network_balance();
1379 if (network_imbalance <= balance.pressure_tolerance()) {
1383 if (this->network_.willBalanceOnNextIteration(episodeIdx)) {
1384 if (this->terminal_output_) {
1385 const std::string msg = fmt::format(
"Maximum of {:d} network iterations has been used and we stop the update, \n"
1386 "and try again after the next Newton iteration (imbalance = {:.2e} bar)",
1387 max_iteration, network_imbalance*1.0e-5);
1388 local_deferredLogger.
debug(msg);
1392 network_needs_more_balancing_force_another_newton_iteration_ =
true;
1394 if (this->terminal_output_) {
1395 const std::string msg = fmt::format(
"Maximum of {:d} network iterations has been used and we stop the update. \n"
1396 "The simulator will continue with unconverged network results (imbalance = {:.2e} bar)",
1397 max_iteration, network_imbalance*1.0e-5);
1398 local_deferredLogger.
info(msg);
1403 if (this->terminal_output_ && (network_update_iteration == iteration_to_relax) ) {
1404 local_deferredLogger.
debug(
"We begin using relaxed tolerance for network update now after " +
std::to_string(iteration_to_relax) +
" iterations ");
1406 const bool relax_network_balance = network_update_iteration >= iteration_to_relax;
1408 const bool optimize_gas_lift = ( (network_update_iteration + 1) < std::max(max_iteration,
static_cast<std::size_t
>(2)) );
1409 std::tie(well_group_control_changed, do_network_update, network_imbalance) =
1410 updateWellControlsAndNetworkIteration(mandatory_network_balance, relax_network_balance, optimize_gas_lift, dt,local_deferredLogger);
1411 ++network_update_iteration;
1413 if (this->isRescoupMasterCoupledNetworkIteration_()) {
1414 this->sendSlaveNetworkLoopTerminationSignal_();
1417 if (this->schedule()[simulator_.episodeIndex()].network().active()) {
1418 last_report_.total_network_iterations += network_update_iteration;
1420 return well_group_control_changed;
1426 template<
typename TypeTag>
1427 std::tuple<bool, bool, typename BlackoilWellModel<TypeTag>::Scalar>
1430 const bool relax_network_tolerance,
1431 const bool optimize_gas_lift,
1436 const int reportStepIdx = simulator_.episodeIndex();
1438#ifdef RESERVOIR_COUPLING_ENABLED
1439 if (this->isRescoupSlaveCoupledNetworkIteration_()) {
1440 this->rescoupHelper_.receiveMasterGroupNodePressuresFromMaster();
1443 Dune::Timer groupTimer;
1445 this->updateAndCommunicateGroupData(reportStepIdx,
true);
1450 bool well_group_control_changed = updateWellControls(local_deferredLogger);
1451 last_report_.group_control_time += groupTimer.stop();
1453 Dune::Timer networkBalanceTimer;
1454 networkBalanceTimer.start();
1455 const auto [more_inner_network_update, network_imbalance] =
1456 this->network_.update(mandatory_network_balance,
1457 local_deferredLogger,
1458 relax_network_tolerance);
1460 if (this->schedule()[reportStepIdx].network().active()) {
1461 last_report_.network_balance_time += networkBalanceTimer.stop();
1463#ifdef RESERVOIR_COUPLING_ENABLED
1464 if (this->isReservoirCouplingMaster()) {
1465 this->rescoupHelper_.maybeExchangeNetworkOuterIterationWithSlaves(more_inner_network_update);
1469 bool alq_updated =
false;
1472 if (optimize_gas_lift) {
1475 const bool updatePotentials = (this->network_.shouldBalance(reportStepIdx) ||
1476 mandatory_network_balance);
1477 Dune::Timer gliftTimer;
1479 alq_updated = gaslift_.maybeDoGasLiftOptimize(simulator_,
1481 this->network_.nodePressures(),
1485 local_deferredLogger);
1487 if (this->schedule().glo(reportStepIdx).active()) {
1488 last_report_.gaslift_time += gliftTimer.stop();
1493 Dune::Timer prepareWellsTimer;
1494 prepareWellsTimer.start();
1495 prepareWellsBeforeAssembling(dt);
1496 last_report_.control_well_solve_time += prepareWellsTimer.stop();
1499 "updateWellControlsAndNetworkIteration() failed: ",
1500 this->terminal_output_, grid().comm());
1504 guideRateUpdateIsNeeded(reportStepIdx)) {
1505 const double simulationTime = simulator_.time();
1506 Dune::Timer guideRateTimer;
1507 guideRateTimer.start();
1511 this->guide_rate_handler_.updateGuideRates(
1512 reportStepIdx, simulationTime, this->wellState(), this->groupState()
1514 last_report_.group_control_time += guideRateTimer.stop();
1518 bool more_network_update = this->network_.shouldBalance(reportStepIdx) &&
1519 (more_inner_network_update || alq_updated);
1521 if (this->isRescoupSlaveOnSyncStepFirstSubstep_()
1522 && this->isRescoupSlaveConnectedToMasterNetwork_()) {
1529 const bool more_cross_rescoup_update =
1530 this->maybeSendSlaveGroupFlowToMaster_(reportStepIdx);
1531 more_network_update = more_network_update || more_cross_rescoup_update;
1534 return {well_group_control_changed, more_network_update, network_imbalance};
1537 template<
typename TypeTag>
1543 for (
auto& well : well_container_) {
1544 well->assembleWellEq(simulator_, dt, this->groupStateHelper(), this->wellState());
1549 template<
typename TypeTag>
1555 for (
auto& well : well_container_) {
1556 well->prepareWellBeforeAssembling(
1557 simulator_, dt, this->groupStateHelper(), this->wellState()
1563 template<
typename TypeTag>
1569 auto& deferred_logger = this->groupStateHelper().deferredLogger();
1574 for (
auto& well: well_container_) {
1575 well->assembleWellEqWithoutIteration(simulator_, this->groupStateHelper(), dt, this->wellState(),
1579 this->terminal_output_, grid().comm());
1583 template<
typename TypeTag>
1590 for (
const auto& well : well_container_) {
1591 well->addCellRates(cellRates_);
1595 template<
typename TypeTag>
1602 for (
const auto& well : well_container_) {
1603 const auto it = well_domain_map.find(well->name());
1604 if (it != well_domain_map.end() && it->second ==
domainIndex) {
1605 well->addCellRates(cellRates_);
1610 template<
typename TypeTag>
1614 const std::map<std::string, int>& well_domain_map,
1615 const std::vector<int>& domain_cells,
1616 const std::vector<bool>& interior)
1621 const auto in_overlap = [&domain_cells, &interior](
const int cell)
1623 return !interior[cell] && std::ranges::binary_search(domain_cells, cell);
1625 for (
const auto& well : well_container_) {
1626 const auto it = well_domain_map.find(well->name());
1627 if (it != well_domain_map.end() && it->second !=
domainIndex) {
1628 well->addConstantCellRates(cellRates_, in_overlap);
1633#if COMPILE_GPU_BRIDGE
1634 template<
typename TypeTag>
1642 for(
unsigned int i = 0; i < well_container_.size(); i++){
1643 auto& well = well_container_[i];
1646 wellContribs.
addNumBlocks(derived->linSys().getNumBlocks());
1651 wellContribs.
alloc();
1653 for(
unsigned int i = 0; i < well_container_.size(); i++){
1654 auto& well = well_container_[i];
1656 auto derived_std =
dynamic_cast<StandardWell<TypeTag>*
>(well.get());
1658 derived_std->linSys().extract(derived_std->numStaticWellEq, wellContribs);
1660 auto derived_ms =
dynamic_cast<MultisegmentWell<TypeTag>*
>(well.get());
1662 derived_ms->linSys().extract(wellContribs);
1664 OpmLog::warning(
"Warning unknown type of well");
1671 template<
typename TypeTag>
1676 for (
const auto& well: well_container_ ) {
1677 well->addWellContributions(jacobian);
1681 template<
typename TypeTag>
1684 std::vector<CMatrix>& c_matrices,
1685 std::vector<DMatrix>& d_matrices,
1686 Opm::SparseTable<int>& wcells)
const
1689 for (
const auto& well: well_container_ ) {
1690 well->addBCDMatrix(b_matrices, c_matrices, d_matrices, wcells);
1694 template<
typename TypeTag>
1699 const bool use_well_weights,
1700 const bool contract_d_diagonal)
const
1702 int nw = this->numLocalWellsEnd();
1703 int rdofs = local_num_cells_;
1704 for (
int i = 0; i < nw; i++ ) {
1705 int wdof = rdofs + i;
1706 jacobian[wdof][wdof] = 1.0;
1709 for (
const auto& well : well_container_) {
1710 well->addWellPressureEquations(jacobian,
1714 contract_d_diagonal,
1719 template <
typename TypeTag>
1722 const std::vector<typename SparseMatrixAdapter::MatrixBlock*>& diagMatAddress)
const
1727 for (
const auto& well : well_container_) {
1728 if (!well->isOperableAndSolvable() && !well->wellIsStopped()) {
1731 const auto& cells = well->cells();
1732 const auto& rates = well->connectionRates();
1733 for (
unsigned perfIdx = 0; perfIdx < rates.size(); ++perfIdx) {
1734 unsigned cellIdx = cells[perfIdx];
1735 auto rate = rates[perfIdx];
1738 using MatrixBlockType =
typename SparseMatrixAdapter::MatrixBlock;
1739 MatrixBlockType bMat(0.0);
1740 simulator_.model().linearizer().setResAndJacobi(res, bMat, rate);
1741 residual[cellIdx] += res;
1742 *diagMatAddress[cellIdx] += bMat;
1748 template<
typename TypeTag>
1753 int nw = this->numLocalWellsEnd();
1754 int rdofs = local_num_cells_;
1755 const auto wellconnections = this->getMaxWellConnections();
1756 for (
int i = 0; i < nw; ++i) {
1757 int wdof = rdofs + i;
1758 jacobian.entry(wdof,wdof) = 0.0;
1759 const auto& perfcells = wellconnections[i];
1760 for (
int perfcell : perfcells) {
1761 jacobian.entry(wdof, perfcell) = 0.0;
1762 jacobian.entry(perfcell, wdof) = 0.0;
1768 template<
typename TypeTag>
1773 auto loggerGuard = this->groupStateHelper().pushLogger();
1776 for (
const auto& well : well_container_) {
1777 const auto& cells = well->cells();
1778 x_local_.resize(cells.size());
1780 for (
size_t i = 0; i < cells.size(); ++i) {
1781 x_local_[i] = x[cells[i]];
1783 well->recoverWellSolutionAndUpdateWellState(simulator_, x_local_,
1784 this->groupStateHelper(), this->wellState());
1788 simulator_.vanguard().grid().comm());
1792 template<
typename TypeTag>
1798 OPM_THROW(std::logic_error,
"Attempt to call NLDD method without a NLDD solver");
1801 return nldd_->recoverWellSolutionAndUpdateWellState(x, domainIdx);
1805 template<
typename TypeTag>
1808 getWellConvergence(
const std::vector<Scalar>& B_avg,
bool checkWellGroupControlsAndNetwork)
const
1812 const auto& iterCtx = simulator_.problem().iterationContext();
1813 const bool relaxTolerance = iterCtx.shouldRelax(param_.strict_outer_iter_wells_ + 1);
1815 auto logger_guard = this->groupStateHelper().pushLogger();
1816 for (
const auto& well : well_container_) {
1817 if (well->isOperableAndSolvable() || well->wellIsStopped()) {
1818 local_report += well->getWellConvergence(
1819 this->groupStateHelper(), B_avg,
1824 report.
setWellFailed({CR::WellFailure::Type::Unsolvable, CR::Severity::Normal, -1, well->name()});
1825 local_report += report;
1833 if (checkWellGroupControlsAndNetwork) {
1839 if (this->terminal_output_) {
1843 OpmLog::debug(
"NaN residual found with phase " +
std::to_string(f.phase()) +
" for well " + f.wellName());
1845 OpmLog::debug(
"Too large residual found with phase " +
std::to_string(f.phase()) +
" for well " + f.wellName());
1856 template<
typename TypeTag>
1862 for (
auto& well : well_container_) {
1863 well->calculateExplicitQuantities(simulator_, this->groupStateHelper());
1871 template<
typename TypeTag>
1877 if (!this->wellsActive() && !this->isReservoirCouplingMaster()) {
1880 const int episodeIdx = simulator_.episodeIndex();
1881 const auto& comm = simulator_.vanguard().grid().comm();
1888 const auto nupcol = this->schedule()[episodeIdx].nupcol();
1889 const auto& iter_ctx = simulator_.problem().iterationContext();
1890 if (iter_ctx.withinNupcol(nupcol)) {
1892 for (
const auto& well : well_container_) {
1893 well->updateWeldrawMaxRate(simulator_, this->wellState(), deferred_logger);
1896 simulator_.gridView().comm());
1901 bool changed_well_group =
false;
1902 const Group& fieldGroup = this->schedule().getGroup(
"FIELD", episodeIdx);
1905 const std::size_t max_iter = param_.well_group_constraints_max_iterations_;
1906 while(!changed_well_group && iter < max_iter) {
1907 changed_well_group = updateGroupControls(fieldGroup, deferred_logger, episodeIdx);
1910 bool changed_well_to_group =
false;
1912 OPM_TIMEBLOCK(UpdateWellControls);
1916 for (
const auto& well : well_container_) {
1919 simulator_, mode, this->groupStateHelper(), this->wellState()
1922 changed_well_to_group = changed_well || changed_well_to_group;
1926 simulator_.gridView().comm());
1929 changed_well_to_group = comm.sum(
static_cast<int>(changed_well_to_group));
1930 if (changed_well_to_group) {
1931 updateAndCommunicate(episodeIdx);
1932 changed_well_group =
true;
1936 bool changed_well_individual =
false;
1941 for (
const auto& well : well_container_) {
1944 simulator_, mode, this->groupStateHelper(), this->wellState()
1947 changed_well_individual = changed_well || changed_well_individual;
1951 simulator_.gridView().comm());
1954 changed_well_individual = comm.sum(
static_cast<int>(changed_well_individual));
1955 if (changed_well_individual) {
1956 updateAndCommunicate(episodeIdx);
1957 changed_well_group =
true;
1963 this->updateWsolvent(fieldGroup, episodeIdx, this->nupcolWellState());
1965 return changed_well_group;
1969 template<
typename TypeTag>
1974 this->updateAndCommunicateGroupData(reportStepIdx,
true);
1980 for (
const auto& well : well_container_) {
1982 const auto& ws = this->wellState().well(well->indexOfWell());
1983 if (ws.production_cmode == Well::ProducerCMode::GRUP ||
1984 ws.injection_cmode == Well::InjectorCMode::GRUP)
1986 well->updateWellStateWithTarget(
1987 simulator_, this->groupStateHelper(), this->wellState()
1992 simulator_.gridView().comm())
1993 this->updateAndCommunicateGroupData(reportStepIdx,
true);
1996 template<
typename TypeTag>
2001 const int reportStepIdx)
2004 const auto& iterCtx = simulator_.problem().iterationContext();
2005 bool changed =
false;
2007 const int nupcol = this->schedule()[reportStepIdx].nupcol();
2008 const bool update_group_switching_log = !iterCtx.withinNupcol(nupcol);
2009 const bool changed_hc = this->checkGroupHigherConstraints(
2010 group, deferred_logger, reportStepIdx, update_group_switching_log);
2013 updateAndCommunicate(reportStepIdx);
2016 bool changed_individual =
2018 updateGroupIndividualControl(group,
2020 param_.max_number_of_group_switches_,
2021 update_group_switching_log,
2022 this->switched_inj_groups_,
2023 this->switched_prod_groups_,
2024 this->closed_offending_wells_,
2029 if (changed_individual) {
2031 updateAndCommunicate(reportStepIdx);
2034 for (
const std::string& groupName : group.groups()) {
2035 bool changed_this = updateGroupControls(this->schedule().getGroup(groupName, reportStepIdx), deferred_logger, reportStepIdx);
2036 changed = changed || changed_this;
2041 template<
typename TypeTag>
2047 auto logger_guard = this->groupStateHelper().pushLogger();
2048 auto& local_deferredLogger = this->groupStateHelper().deferredLogger();
2049 for (
const auto& well : well_container_) {
2050 const auto& wname = well->name();
2051 const auto wasClosed = wellTestState.well_is_closed(wname);
2052 well->checkWellOperability(simulator_,
2054 this->groupStateHelper());
2055 const bool under_zero_target =
2056 well->wellUnderZeroGroupRateTarget(this->groupStateHelper());
2057 well->updateWellTestState(this->wellState().well(wname),
2063 this->eclipseState().getUnits(),
2064 this->schedule().getStartTime(),
2065 local_deferredLogger);
2067 if (!wasClosed && wellTestState.well_is_closed(wname)) {
2068 this->closed_this_step_.insert(wname);
2071 const WellEconProductionLimits& econ_production_limits = well->wellEcl().getEconLimits();
2072 if (econ_production_limits.validFollowonWell()) {
2073 const auto episode_idx = simulator_.episodeIndex();
2074 const auto follow_on_well = econ_production_limits.followonWell();
2075 if (!this->schedule().hasWell(follow_on_well, episode_idx)) {
2076 const auto msg = fmt::format(
"Well {} was closed. But the given follow on well {} does not exist."
2077 "The simulator continues without opening a follow on well.",
2078 wname, follow_on_well);
2079 local_deferredLogger.warning(msg);
2081 auto& ws = this->wellState().well(follow_on_well);
2082 const bool success = ws.updateStatus(WellStatus::OPEN);
2084 const auto msg = fmt::format(
"Well {} was closed. The follow on well {} opens instead.", wname, follow_on_well);
2085 local_deferredLogger.info(msg);
2087 const auto msg = fmt::format(
"Well {} was closed. The follow on well {} is already open.", wname, follow_on_well);
2088 local_deferredLogger.warning(msg);
2095 for (
const auto& [group_name, to] : this->closed_offending_wells_) {
2096 if (this->hasOpenLocalWell(to.second) &&
2097 !this->wasDynamicallyShutThisTimeStep(to.second))
2099 wellTestState.close_well(to.second,
2100 WellTestConfig::Reason::GROUP,
2102 this->updateClosedWellsThisStep(to.second);
2103 const std::string msg =
2104 fmt::format(
"Procedure on exceeding {} limit is WELL for group {}. "
2110 local_deferredLogger.info(msg);
2116 template<
typename TypeTag>
2120 std::string& exc_msg,
2124 const int np = this->numPhases();
2125 std::vector<Scalar> potentials;
2126 const auto& well = well_container_[widx];
2127 std::string cur_exc_msg;
2130 well->computeWellPotentials(simulator_, well_state_copy, this->groupStateHelper(), potentials);
2135 exc_msg += fmt::format(
"\nFor well {}: {}", well->name(), cur_exc_msg);
2137 exc_type = std::max(exc_type, cur_exc_type);
2141 auto& ws = this->wellState().well(well->indexOfWell());
2142 for (
int p = 0; p < np; ++p) {
2144 ws.well_potentials[p] = std::max(
Scalar{0.0}, potentials[p]);
2150 template <
typename TypeTag>
2155 for (
const auto& wellPtr : this->well_container_) {
2156 this->calculateProductivityIndexValues(wellPtr.get(), deferred_logger);
2164 template <
typename TypeTag>
2175 for (
const auto& shutWell : this->local_shut_wells_) {
2176 if (!this->wells_ecl_[shutWell].hasConnections()) {
2181 auto wellPtr = this->
template createTypedWellPointer
2184 wellPtr->
init(this->depth_, this->gravity_, this->B_avg_,
true);
2186 this->calculateProductivityIndexValues(wellPtr.get(), deferred_logger);
2194 template <
typename TypeTag>
2208 template<
typename TypeTag>
2213 const auto episodeIdx = simulator_.episodeIndex();
2216 const bool do_prestep_network_rebalance = this->shouldDoPreStepNetworkRebalance_(episodeIdx);
2218 for (
const auto& well : well_container_) {
2219 auto& events = this->wellState().well(well->indexOfWell()).events;
2221 well->updateWellStateWithTarget(
2222 simulator_, this->groupStateHelper(), this->wellState()
2224 well->updatePrimaryVariables(this->groupStateHelper());
2230 if (events.hasEvent(ScheduleEvents::REQUEST_OPEN_WELL)) {
2231 events.clearEvent(ScheduleEvents::REQUEST_OPEN_WELL);
2234 if (param_.solve_welleq_initially_ && well->isOperableAndSolvable()) {
2236 well->solveWellEquation(
2237 simulator_, this->groupStateHelper(), this->wellState()
2239 }
catch (
const std::exception& e) {
2240 const std::string msg =
"Compute initial well solution for " + well->name() +
" initially failed. Continue with the previous rates";
2241 deferred_logger.
warning(
"WELL_INITIAL_SOLVE_FAILED", msg);
2246 well->resetWellOperability();
2248 updatePrimaryVariables();
2251 if (do_prestep_network_rebalance) {
2252 network_.doPreStepRebalance(deferred_logger);
2256 template<
typename TypeTag>
2261 std::vector< Scalar > B_avg(numConservationQuantities(),
Scalar() );
2262 const auto& grid = simulator_.vanguard().grid();
2263 const auto& gridView = grid.leafGridView();
2267 for (
const auto& elem : elements(gridView, Dune::Partitions::interior)) {
2268 elemCtx.updatePrimaryStencil(elem);
2269 elemCtx.updatePrimaryIntensiveQuantities(0);
2271 const auto& intQuants = elemCtx.intensiveQuantities(0, 0);
2272 const auto& fs = intQuants.fluidState();
2274 for (
unsigned phaseIdx = 0; phaseIdx < FluidSystem::numPhases; ++phaseIdx)
2276 if (!FluidSystem::phaseIsActive(phaseIdx)) {
2280 const unsigned compIdx = FluidSystem::canonicalToActiveCompIdx(FluidSystem::solventComponentIndex(phaseIdx));
2281 auto& B = B_avg[ compIdx ];
2283 B += 1 / fs.invB(phaseIdx).value();
2285 if constexpr (has_solvent_) {
2286 auto& B = B_avg[solventSaturationIdx];
2287 B += 1 / intQuants.solventInverseFormationVolumeFactor().value();
2293 grid.comm().sum(B_avg.data(), B_avg.size());
2294 B_avg_.resize(B_avg.size());
2295 std::ranges::transform(B_avg, B_avg_.begin(),
2296 [gcells = global_num_cells_](
const auto bval)
2297 { return bval / gcells; });
2304 template<
typename TypeTag>
2309 for (
const auto& well : well_container_) {
2310 well->updatePrimaryVariables(this->groupStateHelper());
2314 template<
typename TypeTag>
2318 const auto& grid = simulator_.vanguard().grid();
2319 const auto& eclProblem = simulator_.problem();
2320 const unsigned numCells = grid.size(0);
2322 this->pvt_region_idx_.resize(numCells);
2323 for (
unsigned cellIdx = 0; cellIdx < numCells; ++cellIdx) {
2324 this->pvt_region_idx_[cellIdx] =
2325 eclProblem.pvtRegionIndex(cellIdx);
2330 template<
typename TypeTag>
2346 return this->numPhases() + has_solvent_;
2349 template<
typename TypeTag>
2353 const auto& eclProblem = simulator_.problem();
2354 depth_.resize(local_num_cells_);
2355 for (
unsigned cellIdx = 0; cellIdx < local_num_cells_; ++cellIdx) {
2356 depth_[cellIdx] = eclProblem.dofCenterDepth(cellIdx);
2360 template<
typename TypeTag>
2363 getWell(
const std::string& well_name)
const
2367 std::ranges::find_if(well_container_,
2369 {
return elem->name() == well_name; });
2371 assert(well != well_container_.end());
2376 template <
typename TypeTag>
2381 return std::max(this->simulator_.episodeIndex(), 0);
2388 template<
typename TypeTag>
2393 const std::vector<Scalar>& production_rates,
2394 std::vector<Scalar>& resv_coeff)
const
2396 rateConverter_->calcCoeff(fipnum, pvtreg, production_rates, resv_coeff);
2399 template<
typename TypeTag>
2404 std::vector<Scalar>& resv_coeff)
const
2406 rateConverter_->calcInjCoeff(fipnum, pvtreg, resv_coeff);
2410 template <
typename TypeTag>
2415 if constexpr (energyModuleType_ == EnergyModules::FullyImplicitThermal) {
2416 const int np = this->numPhases();
2417 const int nw = this->numLocalWells();
2418 for (
auto wellID = 0*nw; wellID < nw; ++wellID) {
2419 const Well& well = this->wells_ecl_[wellID];
2420 auto& ws = this->wellState().well(wellID);
2421 if (well.isInjector()) {
2422 if (ws.status != WellStatus::STOP) {
2423 this->wellState().well(wellID).temperature = well.inj_temperature();
2427 std::array<Scalar,2> weighted{0.0,0.0};
2428 auto& [weighted_temperature, total_weight] = weighted;
2429 const auto& well_info = this->local_parallel_well_info_[wellID].get();
2430 using int_type =
decltype(this->well_perf_data_[wellID].size());
2431 for (int_type perf = 0, end_perf = this->well_perf_data_[wellID].size(); perf < end_perf; ++perf) {
2432 const int cell_idx = this->well_perf_data_[wellID][perf].cell_index;
2433 const auto& intQuants = simulator_.model().intensiveQuantities(cell_idx, 0);
2434 const auto& fs = intQuants.fluidState();
2435 Scalar weight_factor = computeTemperatureWeightFactor(perf, np, fs, ws);
2436 total_weight += weight_factor;
2437 weighted_temperature += weight_factor * fs.temperature(0).value();
2439 well_info.communication().sum(weighted.data(), 2);
2440 this->wellState().well(wellID).temperature = weighted_temperature / total_weight;
2446 template <
typename TypeTag>
2448 -> typename
WellState<Scalar,IndexTraits>::RsConstInfo
2450 if (! FluidSystem::phaseIsActive(FluidSystem::oilPhaseIdx) ||
2451 ! FluidSystem::enableConstantRs())
2456 const auto& rsConstTables = this->eclState_
2457 .getTableManager().getRsconstTables();
2459 if (rsConstTables.empty() ||
2460 (rsConstTables[0].numRows() != std::size_t{1}))
2465 const auto rsConst = rsConstTables[0].getColumn(0).front();
2467 return {
true,
static_cast<Scalar
>(rsConst) };
2473 template <
typename TypeTag>
2474 void BlackoilWellModel<TypeTag>::
2475 assignWellTracerRates_(data::Wells& wsrpt)
const
2477 const auto reportStepIdx =
static_cast<unsigned int>(this->reportStepIndex());
2478 const auto& trMod = this->simulator_.problem().tracerModel();
2484 this->assignMswTracerRates(wsrpt, trMod.getMswTracerRates(), reportStepIdx);
2487 template <
typename TypeTag>
2488 void BlackoilWellModel<TypeTag>::
2489 assignWellSpeciesRates_(data::Wells& wsrpt)
const
2491 const auto reportStepIdx =
static_cast<unsigned int>(this->reportStepIndex());
2492 const auto& geochemMod = this->simulator_.problem().geochemistryModel();
2496 this->assignMswTracerRates(wsrpt, geochemMod.getMswSpeciesRates(), reportStepIdx);
2499 template <
typename TypeTag>
2500 bool BlackoilWellModel<TypeTag>::isRescoupMasterCoupledNetworkIteration_()
const
2502#ifdef RESERVOIR_COUPLING_ENABLED
2503 return this->rescoupHelper_.masterIsInCoupledNetworkIteration();
2509 template <
typename TypeTag>
2510 bool BlackoilWellModel<TypeTag>::isRescoupSlaveCoupledNetworkIteration_()
const
2521#ifdef RESERVOIR_COUPLING_ENABLED
2522 return this->isRescoupSlaveOnSyncStepFirstSubstep_()
2523 && this->reservoirCouplingSlave().connectedToMasterCoupledNetwork()
2524 && !this->reservoirCouplingSlave().lastReceivedMasterGroupNodePressuresIsFinal();
2530 template <
typename TypeTag>
2531 bool BlackoilWellModel<TypeTag>::isRescoupSlaveOnSyncStepFirstSubstep_()
const
2538#ifdef RESERVOIR_COUPLING_ENABLED
2539 return this->isReservoirCouplingSlave()
2540 && this->reservoirCouplingSlave().isFirstSubstepOfSyncTimestep();
2546 template <
typename TypeTag>
2547 bool BlackoilWellModel<TypeTag>::isRescoupSlaveConnectedToMasterNetwork_()
const
2549#ifdef RESERVOIR_COUPLING_ENABLED
2550 return this->isReservoirCouplingSlave()
2551 && this->reservoirCouplingSlave().connectedToMasterCoupledNetwork();
2557 template <
typename TypeTag>
2558 bool BlackoilWellModel<TypeTag>::
2559 maybeSendSlaveGroupFlowToMaster_([[maybe_unused]]
const int reportStepIdx)
2561#ifdef RESERVOIR_COUPLING_ENABLED
2568 assert(this->isReservoirCouplingSlave());
2569 const bool is_final =
2570 this->reservoirCouplingSlave().lastReceivedMasterGroupNodePressuresIsFinal();
2572 this->updateAndCommunicateGroupData(reportStepIdx,
false);
2573 this->rescoupHelper_.sendSlaveGroupDataToMaster();
2577 this->rescoupHelper_.receiveRefreshedGroupConstraintsFromMaster();
2586 template <
typename TypeTag>
2587 void BlackoilWellModel<TypeTag>::
2588 sendSlaveNetworkLoopTerminationSignal_()
2590#ifdef RESERVOIR_COUPLING_ENABLED
2595 assert(this->isReservoirCouplingMaster());
2596 this->rescoupHelper_.sendMasterGroupNodePressuresToSlaves(
true);
2600 template <
typename TypeTag>
2601 bool BlackoilWellModel<TypeTag>::
2602 shouldDoPreStepNetworkRebalance_(
const int episodeIdx)
const
2615 return param_.pre_solve_network_
2616 && this->network_.needPreStepRebalance(episodeIdx)
2617 && !this->isRescoupCoupledNetworkParticipant_();
2620 template <
typename TypeTag>
2621 bool BlackoilWellModel<TypeTag>::isRescoupCoupledNetworkParticipant_()
const
2623#ifdef RESERVOIR_COUPLING_ENABLED
2624 if (this->isReservoirCouplingMaster()) {
2625 return this->rescoupHelper_.masterNetworkHasMasterGroupLeaves();
2627 if (this->isReservoirCouplingSlave()) {
2628 return this->reservoirCouplingSlave().connectedToMasterCoupledNetwork();
2636 template <
typename TypeTag>
2637 void BlackoilWellModel<TypeTag>::
2638 updateNetworkActiveState_()
2649 const int episodeIdx = this->simulator_.episodeIndex();
2650 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:2391
void prepareTimeStep(DeferredLogger &deferred_logger)
Definition: BlackoilWellModel_impl.hpp:2211
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:1429
WellInterfacePtr createWellPointer(const int wellID, const int report_step) const
Definition: BlackoilWellModel_impl.hpp:1146
void prepareWellsBeforeAssembling(const double dt)
Definition: BlackoilWellModel_impl.hpp:1552
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:1613
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:2363
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:2332
bool updateWellControls(DeferredLogger &deferred_logger)
Definition: BlackoilWellModel_impl.hpp:1874
int reportStepIndex() const
Definition: BlackoilWellModel_impl.hpp:2379
void calculateProductivityIndexValues(DeferredLogger &deferred_logger) override
Definition: BlackoilWellModel_impl.hpp:2153
void extractLegacyDepth_()
Definition: BlackoilWellModel_impl.hpp:2351
void extractLegacyCellPvtRegionIndex_()
Definition: BlackoilWellModel_impl.hpp:2316
void recoverWellSolutionAndUpdateWellStateDomain(const BVector &x, const int domainIdx)
Definition: BlackoilWellModel_impl.hpp:1795
void updateAverageFormationFactor()
Definition: BlackoilWellModel_impl.hpp:2259
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:876
const Grid & grid() const
Definition: BlackoilWellModel.hpp:396
void updatePrimaryVariables()
Definition: BlackoilWellModel_impl.hpp:2307
void computeWellTemperature()
Definition: BlackoilWellModel_impl.hpp:2413
const SimulatorReportSingle & lastReport() const
Definition: BlackoilWellModel_impl.hpp:712
bool updateWellControlsAndNetwork(const bool mandatory_network_balance, const double dt, DeferredLogger &local_deferredLogger)
Definition: BlackoilWellModel_impl.hpp:1356
void addWellContributions(SparseMatrixAdapter &jacobian) const
Definition: BlackoilWellModel_impl.hpp:1674
void assembleWellEq(const double dt)
Definition: BlackoilWellModel_impl.hpp:1540
WellInterfacePtr createWellForWellTest(const std::string &well_name, const int report_step, DeferredLogger &deferred_logger) const
Definition: BlackoilWellModel_impl.hpp:1197
void calculateExplicitQuantities() const
Definition: BlackoilWellModel_impl.hpp:1859
void collectWellSolveStats()
Definition: BlackoilWellModel_impl.hpp:1311
void updateAndCommunicate(const int reportStepIdx)
Definition: BlackoilWellModel_impl.hpp:1972
Dune::BCRSMatrix< Opm::MatrixBlock< Scalar, 1, 1 > > PressureMatrix
Definition: BlackoilWellModel.hpp:308
void updateFailed()
Definition: BlackoilWellModel_impl.hpp:620
void computeTotalRatesForDof(RateVector &rate, unsigned globalIdx) const
Definition: BlackoilWellModel_impl.hpp:839
void stashWellSolveStats()
Definition: BlackoilWellModel_impl.hpp:1327
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:1999
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:2402
Dune::BlockVector< VectorBlockType > BVector
Definition: BlackoilWellModel.hpp:134
void wellTesting(const int timeStepIdx, const double simulationTime, DeferredLogger &deferred_logger)
Definition: BlackoilWellModel_impl.hpp:635
ConvergenceReport getWellConvergence(const std::vector< Scalar > &B_avg, const bool checkWellGroupControlsAndNetwork=false) const
Definition: BlackoilWellModel_impl.hpp:1808
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:1598
void assembleWellEqWithoutIteration(const double dt)
Definition: BlackoilWellModel_impl.hpp:1566
void updateCellRates()
Definition: BlackoilWellModel_impl.hpp:1586
void assemble(const double dt)
Definition: BlackoilWellModel_impl.hpp:1222
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:722
std::unique_ptr< WellType > createTypedWellPointer(const int wellID, const int time_step) const
Definition: BlackoilWellModel_impl.hpp:1166
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:2118
Simulator & simulator_
Definition: BlackoilWellModel.hpp:579
void createWellContainer(const int report_step) override
Definition: BlackoilWellModel_impl.hpp:919
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:2044
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:1683
void addSolveStats(const WellInterface< TypeTag > &well)
Definition: BlackoilWellModel_impl.hpp:1337
void addReservoirSourceTerms(GlobalEqVector &residual, const std::vector< typename SparseMatrixAdapter::MatrixBlock * > &diagMatAddress) const
Definition: BlackoilWellModel_impl.hpp:1721
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:1697
void recoverWellSolutionAndUpdateWellState(const BVector &x)
Definition: BlackoilWellModel_impl.hpp:1771
void addWellPressureEquationsStruct(PressureMatrix &jacobian) const
Definition: BlackoilWellModel_impl.hpp:1751
void calculateProductivityIndexValuesShutWells(const int reportStepIdx, DeferredLogger &deferred_logger) override
Definition: BlackoilWellModel_impl.hpp:2167
void advanceTimeLevel()
Definition: BlackoilWellModel_impl.hpp:628
void endReportStep()
Definition: BlackoilWellModel_impl.hpp:695
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