23#ifndef OPM_BLACKOILWELLMODEL_IMPL_HEADER_INCLUDED
24#define OPM_BLACKOILWELLMODEL_IMPL_HEADER_INCLUDED
27#ifndef OPM_BLACKOILWELLMODEL_HEADER_INCLUDED
32#include <opm/grid/utility/cartesianToCompressed.hpp>
34#include <opm/input/eclipse/Schedule/Network/Balance.hpp>
35#include <opm/input/eclipse/Schedule/Network/ExtNetwork.hpp>
36#include <opm/input/eclipse/Schedule/Well/PAvgDynamicSourceData.hpp>
37#include <opm/input/eclipse/Schedule/Well/WellMatcher.hpp>
38#include <opm/input/eclipse/Schedule/Well/WellTestConfig.hpp>
39#include <opm/input/eclipse/Schedule/Well/WellEconProductionLimits.hpp>
41#include <opm/input/eclipse/Units/UnitSystem.hpp>
67#include <fmt/format.h>
70 template<
typename TypeTag>
77 simulator.vanguard().summaryState(),
78 simulator.vanguard().eclState(),
80 simulator.gridView().comm(),
82 , simulator_(simulator)
83 , guide_rate_handler_{
85 simulator.vanguard().schedule(),
86 simulator.vanguard().summaryState(),
87 simulator.vanguard().grid().comm()
89 , gaslift_(this->terminal_output_)
92 , rescoupHelper_(*this)
101 auto& parallel_wells =
simulator.vanguard().parallelWells();
104 for(
const auto& name_bool : parallel_wells) {
112 Parameters::Get<Parameters::AlternativeWellRateInit>();
114 using SourceDataSpan =
115 typename PAvgDynamicSourceData<Scalar>::template SourceDataSpan<Scalar>;
117 this->
wbp_.initializeSources(
118 [
this](
const std::size_t globalIndex)
120 [
this](
const int localCell, SourceDataSpan sourceTerms)
122 using Item =
typename SourceDataSpan::Item;
124 const auto* intQuants = this->
simulator_.model()
125 .cachedIntensiveQuantities(localCell, 0);
126 const auto& fs = intQuants->fluidState();
129 .set(Item::PoreVol, intQuants->porosity().value() *
130 this->
simulator_.model().dofTotalVolume(localCell))
131 .set(Item::Depth, this->
depth_[localCell]);
133 constexpr auto io = FluidSystem::oilPhaseIdx;
134 constexpr auto ig = FluidSystem::gasPhaseIdx;
135 constexpr auto iw = FluidSystem::waterPhaseIdx;
138 const auto haveOil = FluidSystem::phaseIsActive(io);
139 const auto haveGas = FluidSystem::phaseIsActive(ig);
140 const auto haveWat = FluidSystem::phaseIsActive(iw);
142 auto weightedPhaseDensity = [&fs](
const auto ip)
144 return fs.saturation(ip).value() * fs.density(ip).value();
147 if (haveOil) { sourceTerms.set(Item::Pressure, fs.pressure(io).value()); }
148 else if (haveGas) { sourceTerms.set(Item::Pressure, fs.pressure(ig).value()); }
149 else { sourceTerms.set(Item::Pressure, fs.pressure(iw).value()); }
153 if (haveOil) { rho += weightedPhaseDensity(io); }
154 if (haveGas) { rho += weightedPhaseDensity(ig); }
155 if (haveWat) { rho += weightedPhaseDensity(iw); }
157 sourceTerms.set(Item::MixtureDensity, rho);
162 template<
typename TypeTag>
167 extractLegacyCellPvtRegionIndex_();
168 extractLegacyDepth_();
170 gravity_ = simulator_.problem().gravity()[2];
172 this->initial_step_ =
true;
175 simulator_.model().addAuxiliaryModule(
this);
177 is_cell_perforated_.resize(local_num_cells_,
false);
181 template<
typename TypeTag>
186 const uint64_t effective_events_mask = ScheduleEvents::WELL_STATUS_CHANGE
187 + ScheduleEvents::NEW_WELL;
188 const auto& events = this->schedule()[reportStepIdx].wellgroup_events();
189 for (
auto& wellPtr : this->well_container_) {
190 const bool well_opened_this_step = this->report_step_starts_ &&
191 events.hasEvent(wellPtr->name(),
192 effective_events_mask);
193 wellPtr->init(this->depth_, this->gravity_,
194 this->B_avg_, well_opened_this_step);
198 template<
typename TypeTag>
203 this->groupStateHelper().setReportStep(timeStepIdx);
204 this->report_step_starts_ =
true;
205 this->report_step_start_events_ = this->schedule()[timeStepIdx].wellgroup_events();
207 this->rateConverter_ = std::make_unique<RateConverterType>
208 (std::vector<int>(this->local_num_cells_, 0));
212 const auto enableWellPIScaling =
true;
213 this->initializeLocalWellStructure(timeStepIdx, enableWellPIScaling);
216 this->initializeGroupStructure(timeStepIdx);
218 const auto& comm = this->simulator_.vanguard().grid().comm();
224 this->rateConverter_->template defineState<ElementContext>(this->simulator_);
228 const auto& sched_state = this->schedule()[timeStepIdx];
230 this->vfp_properties_ = std::make_unique<VFPProperties<Scalar, IndexTraits>>
231 (sched_state.vfpinj(), sched_state.vfpprod(), this->wellState());
238 this->commitWGState();
240 this->wellStructureChangedDynamically_ =
false;
247 template <
typename TypeTag>
251 const bool enableWellPIScaling)
253 auto logger_guard = this->groupStateHelper().pushLogger();
254 auto& local_deferredLogger = this->groupStateHelper().deferredLogger();
256 const auto& comm = this->simulator_.vanguard().grid().comm();
261 this->registerNewParallelWells(reportStepIdx);
264 this->wells_ecl_ = this->getLocalWells(reportStepIdx);
265 this->local_parallel_well_info_ =
266 this->createLocalParallelWellInfo(this->wells_ecl_);
273 this->initializeWellPerfData();
274 this->initializeWellState(reportStepIdx);
275 this->wbp_.initializeWBPCalculationService();
277 if (this->param_.use_multisegment_well_ && this->anyMSWellOpenLocal()) {
278 this->wellState().initWellStateMSWell(this->wells_ecl_, &this->prevWellState(), has_energy_);
281 this->initializeWellProdIndCalculators();
283 if (enableWellPIScaling && this->schedule()[reportStepIdx].events()
284 .hasEvent(ScheduleEvents::Events::WELL_PRODUCTIVITY_INDEX))
286 this->runWellPIScaling(reportStepIdx, local_deferredLogger);
290 "Failed to initialize local well structure: ",
291 this->terminal_output_, comm)
298 template <
typename TypeTag>
303 const auto& comm = this->simulator_.vanguard().grid().comm();
307 const auto& fieldGroup =
308 this->schedule().getGroup(
"FIELD", reportStepIdx);
310 this->groupStateHelper().setCmodeGroup(fieldGroup);
314 if (this->schedule()[reportStepIdx].has_gpmaint()) {
315 this->groupStateHelper().setRegionAveragePressureCalculator(
317 this->eclState_.fieldProps(),
318 this->regionalAveragePressureCalculator_
330 template<
typename TypeTag>
335 OPM_TIMEBLOCK(beginTimeStep);
337 this->updateAverageFormationFactor();
339 auto logger_guard = this->groupStateHelper().pushLogger();
340 auto& local_deferredLogger = this->groupStateHelper().deferredLogger();
342#ifdef RESERVOIR_COUPLING_ENABLED
343 auto rescoup_logger_guard = this->rescoupHelper_.setupScopedLogger(local_deferredLogger);
346 this->switched_prod_groups_.clear();
347 this->switched_inj_groups_.clear();
349 if (this->wellStructureChangedDynamically_) {
354 const auto reportStepIdx =
355 this->simulator_.episodeIndex();
359 const auto enableWellPIScaling =
false;
361 this->initializeLocalWellStructure(reportStepIdx, enableWellPIScaling);
362 this->initializeGroupStructure(reportStepIdx);
364 this->commitWGState();
370 this->wellStructureChangedDynamically_ =
false;
373 this->resetWGState();
374 const int reportStepIdx = simulator_.episodeIndex();
376 this->wellState().updateWellsDefaultALQ(this->schedule(), reportStepIdx, this->summaryState());
377 this->wellState().gliftTimeStepInit();
379 const double simulationTime = simulator_.time();
383 wellTesting(reportStepIdx, simulationTime, local_deferredLogger);
386 createWellContainer(reportStepIdx);
388#ifdef RESERVOIR_COUPLING_ENABLED
389 if (this->isReservoirCouplingMaster()) {
390 if (this->reservoirCouplingMaster().isFirstSubstepOfSyncTimestep()) {
391 this->rescoupHelper_.receiveSlaveGroupData();
398 this->updateAndCommunicateGroupData(reportStepIdx,
false);
401 const Grid& grid = simulator_.vanguard().grid();
402 this->wells_active_ = grid.comm().max(!this->well_container_.empty());
407 this->initWellContainer(reportStepIdx);
410 std::fill(is_cell_perforated_.begin(), is_cell_perforated_.end(),
false);
411 for (
auto& well : well_container_) {
412 well->updatePerforatedCell(is_cell_perforated_);
416 this->calculateEfficiencyFactors(reportStepIdx);
418 if constexpr (has_polymer_)
420 if (PolymerModule::hasPlyshlog() || getPropValue<TypeTag, Properties::EnablePolymerMW>() ) {
421 this->setRepRadiusPerfLength();
428 this->terminal_output_, simulator_.vanguard().grid().comm());
430 for (
auto& well : well_container_) {
431 well->setVFPProperties(this->vfp_properties_.get());
432 well->setGuideRate(&this->guideRate_);
435 this->updateFiltrationModelsPreStep(local_deferredLogger);
438 for (
auto& well : well_container_) {
439 well->closeCompletions(this->wellTestState());
445 if (alternative_well_rate_init_) {
450 for (
const auto& well : well_container_) {
451 if (well->isProducer() && !well->wellIsStopped()) {
452 well->initializeProducerWellState(simulator_, this->wellState(), local_deferredLogger);
457 for (
const auto& well : well_container_) {
458 if (well->isVFPActive(local_deferredLogger)){
459 well->setPrevSurfaceRates(this->wellState(), this->prevWellState());
463 this->updateWellPotentials(reportStepIdx,
465 simulator_.vanguard().summaryConfig(),
466 local_deferredLogger);
467 }
catch ( std::runtime_error& e ) {
468 const std::string msg =
"A zero well potential is returned for output purposes. ";
469 local_deferredLogger.warning(
"WELL_POTENTIAL_CALCULATION_FAILED", msg);
472 this->guide_rate_handler_.updateGuideRates(
473 reportStepIdx, simulationTime, this->wellState(), this->groupState()
475 bool slave_needs_well_solution =
false;
476#ifdef RESERVOIR_COUPLING_ENABLED
477 if (this->isReservoirCouplingSlave()) {
478 if (this->reservoirCouplingSlave().isFirstSubstepOfSyncTimestep()) {
479 this->rescoupHelper_.sendSlaveGroupDataToMaster();
480 this->rescoupHelper_.receiveGroupConstraintsFromMaster();
481 this->rescoupHelper_.receiveCoupledNetworkActiveStatus();
482 this->groupStateHelper().updateSlaveGroupCmodesFromMaster();
483 this->reservoirCouplingSlave().markSlaveGroupsInSchedule(
484 this->schedule_, reportStepIdx);
485 slave_needs_well_solution =
true;
492 if (this->schedule_[reportStepIdx].has_gpmaint()) {
493 for (
const auto& calculator : regionalAveragePressureCalculator_) {
494 calculator.second->template defineState<ElementContext>(simulator_);
496 const double dt = simulator_.timeStepSize();
497 const Group& fieldGroup = this->schedule().getGroup(
"FIELD", reportStepIdx);
499 this->groupStateHelper().updateGpMaintTargetForGroups(fieldGroup,
500 regionalAveragePressureCalculator_,
506 this->updateAndCommunicateGroupData(reportStepIdx,
true);
509 for (
auto& well : well_container_) {
510 const uint64_t effective_events_mask = ScheduleEvents::WELL_STATUS_CHANGE
511 + ScheduleEvents::INJECTION_TYPE_CHANGED
512 + ScheduleEvents::WELL_SWITCHED_INJECTOR_PRODUCER
513 + ScheduleEvents::NEW_WELL;
515 const auto& events = this->schedule()[reportStepIdx].wellgroup_events();
516 const bool event = this->report_step_starts_ && events.hasEvent(well->name(), effective_events_mask);
517 const bool dyn_status_change = this->wellState().well(well->name()).status
518 != this->prevWellState().well(well->name()).status;
520 if (event || dyn_status_change || slave_needs_well_solution) {
522 well->scaleSegmentRatesAndPressure(this->wellState());
523 well->calculateExplicitQuantities(simulator_, this->groupStateHelper());
524 well->updateWellStateWithTarget(simulator_, this->groupStateHelper(), this->wellState());
525 well->updatePrimaryVariables(this->groupStateHelper());
526 well->solveWellEquation(
527 simulator_, this->groupStateHelper(), this->wellState()
529 }
catch (
const std::exception& e) {
530 const std::string msg =
"Compute initial well solution for new well " + well->name() +
" failed. Continue with zero initial rates";
531 local_deferredLogger.warning(
"WELL_INITIAL_SOLVE_FAILED", msg);
539#ifdef RESERVOIR_COUPLING_ENABLED
540 if (slave_needs_well_solution) {
542 this->updateAndCommunicateGroupData(reportStepIdx,
false);
543 this->rescoupHelper_.sendSlaveGroupDataToMaster();
545 else if (this->isReservoirCouplingMaster()) {
546 if (this->reservoirCouplingMaster().isFirstSubstepOfSyncTimestep()) {
547 this->rescoupHelper_.sendMasterGroupConstraintsToSlaves();
548 this->rescoupHelper_.sendCoupledNetworkActiveStatus();
549 this->rescoupHelper_.receiveSlaveGroupData();
555 const std::string msg =
"Compute initial well solution for new wells failed. Continue with zero initial rates";
556 local_deferredLogger.warning(
"WELL_INITIAL_SOLVE_FAILED", msg);
559 const auto& comm = simulator_.vanguard().grid().comm();
561 exc_type,
"beginTimeStep() failed: " + exc_msg, this->terminal_output_, comm);
565 template<
typename TypeTag>
568 const double simulationTime,
571 for (
const std::string& well_name : this->getWellsForTesting(timeStepIdx, simulationTime)) {
572 const Well& wellEcl = this->schedule().getWell(well_name, timeStepIdx);
573 if (wellEcl.getStatus() == Well::Status::SHUT)
576 WellInterfacePtr well = createWellForWellTest(well_name, timeStepIdx, deferred_logger);
578 well->init(depth_, gravity_, B_avg_,
true);
580 Scalar well_efficiency_factor = wellEcl.getEfficiencyFactor() *
581 this->wellState().getGlobalEfficiencyScalingFactor(well_name);
582 this->groupStateHelper().accumulateGroupEfficiencyFactor(
583 this->schedule().getGroup(wellEcl.groupName(), timeStepIdx),
584 well_efficiency_factor
587 well->setWellEfficiencyFactor(well_efficiency_factor);
588 well->setVFPProperties(this->vfp_properties_.get());
589 well->setGuideRate(&this->guideRate_);
592 if (well->isProducer() && alternative_well_rate_init_) {
593 well->initializeProducerWellState(simulator_, this->wellState(), deferred_logger);
595 if (well->isVFPActive(deferred_logger)) {
596 well->setPrevSurfaceRates(this->wellState(), this->prevWellState());
599 const auto& network = this->schedule()[timeStepIdx].network();
600 if (network.active()) {
601 this->network_.initializeWell(*well);
605 GLiftEclWells ecl_well_map;
606 gaslift_.initGliftEclWellMap(well_container_, ecl_well_map);
607 well->wellTesting(simulator_,
609 this->groupStateHelper(),
611 this->wellTestState(),
613 this->well_open_times_);
614 }
catch (
const std::exception& e) {
615 const std::string msg =
616 fmt::format(fmt::runtime(
"Exception during testing of well: {}. The well will not open.\n"
617 "Exception message: {}"), wellEcl.name(), e.what());
618 deferred_logger.
warning(
"WELL_TESTING_FAILED", msg);
624 template<
typename TypeTag>
630 for (
auto&& pinfo : this->local_parallel_well_info_)
641 template<
typename TypeTag>
651 template<
typename TypeTag>
656 this->closed_this_step_.clear();
659 this->report_step_starts_ =
false;
660 const int reportStepIdx = simulator_.episodeIndex();
662 auto logger_guard = this->groupStateHelper().pushLogger();
663 auto& local_deferredLogger = this->groupStateHelper().deferredLogger();
664 for (
const auto& well : well_container_) {
665 if (getPropValue<TypeTag, Properties::EnablePolymerMW>() && well->isInjector()) {
666 well->updateWaterThroughput(dt, this->wellState());
670 for (
const auto& well : well_container_) {
671 well->updateConnectionTransmissibilityFactor(simulator_, this->wellState().well(well->indexOfWell()));
672 well->updateConnectionDFactor(simulator_, this->wellState().well(well->indexOfWell()));
675 if (Indices::waterEnabled) {
676 this->updateFiltrationModelsPostStep(dt, FluidSystem::waterPhaseIdx, local_deferredLogger);
680 this->updateInjMult(local_deferredLogger);
683 for (
const auto& well : well_container_) {
684 well->reportWellSwitching(this->wellState().well(well->indexOfWell()), local_deferredLogger);
687 if (this->terminal_output_) {
688 this->reportGroupSwitching(local_deferredLogger);
692 rateConverter_->template defineState<ElementContext>(simulator_);
696 this->updateWellPotentials(reportStepIdx,
698 simulator_.vanguard().summaryConfig(),
699 local_deferredLogger);
700 }
catch ( std::runtime_error& e ) {
701 const std::string msg =
"A zero well potential is returned for output purposes. ";
702 local_deferredLogger.warning(
"WELL_POTENTIAL_CALCULATION_FAILED", msg);
709 const double closure_time = simulationTime + dt;
711 updateWellTestState(closure_time, this->wellTestState());
714 const Group& fieldGroup = this->schedule_.getGroup(
"FIELD", reportStepIdx);
715 this->checkGEconLimits(fieldGroup, closure_time,
716 simulator_.episodeIndex(), local_deferredLogger);
717 this->checkGconsaleLimits(fieldGroup, this->wellState(),
718 simulator_.episodeIndex(), local_deferredLogger);
720 this->calculateProductivityIndexValues(local_deferredLogger);
722 this->groupStateHelper().updateNONEProductionGroups();
724#ifdef RESERVOIR_COUPLING_ENABLED
725 this->rescoupHelper_.rescoupSyncSummaryData();
727 this->commitWGState();
730 this->computeWellTemperature();
734 template<
typename TypeTag>
738 unsigned elemIdx)
const
742 if (!is_cell_perforated_[elemIdx] || cellRates_.count(elemIdx) == 0) {
746 rate = cellRates_.at(elemIdx);
750 template<
typename TypeTag>
751 template <
class Context>
755 const Context& context,
757 unsigned timeIdx)
const
760 int elemIdx = context.globalSpaceIndex(spaceIdx, timeIdx);
762 if (!is_cell_perforated_[elemIdx] || cellRates_.count(elemIdx) == 0) {
766 rate = cellRates_.at(elemIdx);
771 template<
typename TypeTag>
776 const auto pressIx = []()
778 if (Indices::oilEnabled) {
return FluidSystem::oilPhaseIdx; }
779 if (Indices::waterEnabled) {
return FluidSystem::waterPhaseIdx; }
781 return FluidSystem::gasPhaseIdx;
784 auto cellPressures = std::vector<Scalar>(this->local_num_cells_,
Scalar{0});
785 auto cellTemperatures = std::vector<Scalar>(this->local_num_cells_,
Scalar{0});
788 const auto& gridView = this->simulator_.vanguard().gridView();
791 for (
const auto& elem : elements(gridView, Dune::Partitions::interior)) {
792 elemCtx.updatePrimaryStencil(elem);
793 elemCtx.updatePrimaryIntensiveQuantities(0);
795 const auto ix = elemCtx.globalSpaceIndex(0, 0);
796 const auto& fs = elemCtx.intensiveQuantities(0, 0).fluidState();
798 cellPressures[ix] = fs.pressure(pressIx).value();
799 cellTemperatures[ix] = fs.temperature(0).value();
802 this->simulator_.vanguard().grid().comm());
804 this->wellState().init(cellPressures, cellTemperatures, this->schedule(), this->wells_ecl_,
805 this->local_parallel_well_info_, timeStepIdx,
806 &this->prevWellState(), this->well_perf_data_,
807 this->summaryState(), simulator_.vanguard().enableDistributedWells());
814 template<
typename TypeTag>
819 auto logger_guard = this->groupStateHelper().pushLogger();
820 auto& local_deferredLogger = this->groupStateHelper().deferredLogger();
822 const int nw = this->numLocalWells();
824 well_container_.clear();
827 well_container_.reserve(nw);
829 const auto& wmatcher = this->schedule().wellMatcher(report_step);
830 const auto& wcycle = this->schedule()[report_step].wcycle.get();
834 std::ranges::for_each(this->wells_ecl_,
835 [
this, &wg_events = this->report_step_start_events_](
const auto& well_ecl)
837 if (!well_ecl.hasConnections()) {
842 constexpr auto events_mask = ScheduleEvents::WELL_STATUS_CHANGE |
843 ScheduleEvents::REQUEST_OPEN_WELL |
844 ScheduleEvents::REQUEST_SHUT_WELL;
845 const bool well_event =
846 this->report_step_starts_ &&
847 wg_events.hasEvent(well_ecl.name(), events_mask);
856 if (well_ecl.getStatus() == WellStatus::OPEN) {
857 this->well_open_times_.insert_or_assign(well_ecl.name(),
858 this->simulator_.time());
859 this->well_close_times_.erase(well_ecl.name());
860 }
else if (well_ecl.getStatus() == WellStatus::SHUT) {
861 this->well_close_times_.insert_or_assign(well_ecl.name(),
862 this->simulator_.time());
863 this->well_open_times_.erase(well_ecl.name());
869 const auto cycle_states = wcycle.wellStatus(this->simulator_.time(),
871 this->well_open_times_,
872 this->well_close_times_);
874 for (
int w = 0; w < nw; ++w) {
875 const Well& well_ecl = this->wells_ecl_[w];
877 if (!well_ecl.hasConnections()) {
882 const std::string& well_name = well_ecl.name();
883 const auto well_status = this->schedule()
884 .getWell(well_name, report_step).getStatus();
886 const bool shut_event = this->wellState().well(w).events.hasEvent(ScheduleEvents::WELL_STATUS_CHANGE)
887 && well_status == Well::Status::SHUT;
888 const bool open_event = this->wellState().well(w).events.hasEvent(ScheduleEvents::WELL_STATUS_CHANGE)
889 && well_status == Well::Status::OPEN;
890 const auto& ws = this->wellState().well(well_name);
892 if (shut_event && ws.status != Well::Status::SHUT) {
893 this->closed_this_step_.insert(well_name);
894 this->wellState().shutWell(w);
895 }
else if (open_event && ws.status != Well::Status::OPEN) {
896 this->wellState().openWell(w);
900 if (this->wellTestState().well_is_closed(well_name)) {
913 const bool closed_this_step =
914 (this->wellTestState().lastTestTime(well_name) == simulator_.time()) &&
915 !this->wasDynamicallyShutThisTimeStep(well_name);
918 auto& events = this->wellState().well(w).events;
919 if (events.hasEvent(ScheduleEvents::REQUEST_OPEN_WELL)) {
920 if (!closed_this_step) {
921 this->wellTestState().open_well(well_name);
922 this->wellTestState().open_completions(well_name);
923 this->well_open_times_.insert_or_assign(well_name,
924 this->simulator_.time());
925 this->well_close_times_.erase(well_name);
927 events.clearEvent(ScheduleEvents::REQUEST_OPEN_WELL);
937 auto& well_test_state = this->wellTestState();
938 const auto& sched_state = this->schedule()[report_step];
939 const bool may_reopen_completions =
940 ws.status == Well::Status::OPEN &&
941 sched_state.events().hasEvent(ScheduleEvents::COMPLETION_CHANGE) &&
942 well_test_state.num_closed_completions() > 0;
944 if (may_reopen_completions) {
945 const auto& completion_events = sched_state.wellcompletion_events();
946 for (
const auto& connection : well_ecl.getConnections()) {
947 const int complnum = connection.complnum();
951 if (!well_test_state.completion_is_closed(well_name, complnum) ||
952 !completion_events.hasEvent(well_name, complnum, ScheduleEvents::REQUEST_OPEN_COMPLETION)) {
957 const bool closed_this_step =
958 (well_test_state.lastCompletionCloseTime(well_name, complnum) == simulator_.time());
959 if (closed_this_step) {
963 well_test_state.open_completion(well_name, complnum);
964 local_deferredLogger.info(
965 fmt::format(
"Completion {} - block ({}, {}, {}) for well {} "
966 "is reopened due to an explicit WELOPEN/COMPDAT "
969 connection.getI() + 1,
970 connection.getJ() + 1,
971 connection.getK() + 1,
978 if (this->wellTestState().well_is_closed(well_name))
980 if (well_ecl.getAutomaticShutIn() ||
981 !well_ecl.getAllowCrossFlow() ||
982 this->allConnectionsClosed(well_ecl))
984 this->wellState().shutWell(w);
985 this->well_close_times_.erase(well_name);
986 this->well_open_times_.erase(well_name);
990 this->wellState().stopWell(w);
994 if (!well_ecl.getAllowCrossFlow()) {
995 const bool any_zero_rate_constraint = well_ecl.isProducer()
996 ? well_ecl.productionControls(this->summaryState_).anyZeroRateConstraint()
997 : well_ecl.injectionControls(this->summaryState_).anyZeroRateConstraint();
998 if (any_zero_rate_constraint) {
1000 local_deferredLogger.debug(fmt::format(fmt::runtime(
" Well {} gets shut due to having zero rate constraint and disallowing crossflow "), well_ecl.name()));
1001 this->wellState().shutWell(w);
1002 this->well_close_times_.erase(well_name);
1003 this->well_open_times_.erase(well_name);
1008 if (!wcycle.empty()) {
1009 const auto it = cycle_states.find(well_name);
1010 if (it != cycle_states.end()) {
1011 if (!it->second || well_status == Well::Status::SHUT) {
1013 if (well_status == Well::Status::SHUT) {
1014 this->well_open_times_.erase(well_name);
1015 this->well_close_times_.erase(well_name);
1017 this->wellState().shutWell(w);
1020 this->wellState().openWell(w);
1026 if (ws.status == Well::Status::SHUT) {
1030 well_container_.emplace_back(this->createWellPointer(w, report_step));
1032 if (ws.status == Well::Status::STOP) {
1033 well_container_.back()->stopWell();
1034 this->well_close_times_.erase(well_name);
1035 this->well_open_times_.erase(well_name);
1039 if (!wcycle.empty()) {
1040 const auto schedule_open =
1041 [&wg_events = this->report_step_start_events_](
const std::string& name)
1043 return wg_events.hasEvent(name, ScheduleEvents::REQUEST_OPEN_WELL);
1045 for (
const auto& [wname, wscale] : wcycle.efficiencyScale(this->simulator_.time(),
1046 this->simulator_.timeStepSize(),
1048 this->well_open_times_,
1051 this->wellState().updateEfficiencyScalingFactor(wname, wscale);
1052 this->schedule_.add_event(ScheduleEvents::WELLGROUP_EFFICIENCY_UPDATE, report_step);
1057 this->well_container_generic_.clear();
1058 for (
auto& w : well_container_) {
1059 this->well_container_generic_.push_back(w.get());
1062 this->network_.initialize(report_step);
1064 this->wbp_.registerOpenWellsForWBPCalculation();
1071 template <
typename TypeTag>
1076 const auto is_multiseg = this->wells_ecl_[wellID].isMultiSegment();
1078 if (! (this->param_.use_multisegment_well_ && is_multiseg)) {
1079 return this->
template createTypedWellPointer<StandardWell<TypeTag>>(wellID, report_step);
1082 return this->
template createTypedWellPointer<MultisegmentWell<TypeTag>>(wellID, report_step);
1090 template <
typename TypeTag>
1091 template <
typename WellType>
1092 std::unique_ptr<WellType>
1097 const auto& perf_data = this->well_perf_data_[wellID];
1100 const auto pvtreg = perf_data.empty()
1101 ? 0 : this->pvt_region_idx_[perf_data.front().cell_index];
1103 const auto& parallel_well_info = this->local_parallel_well_info_[wellID].get();
1104 const auto global_pvtreg = parallel_well_info.broadcastFirstPerforationValue(pvtreg);
1106 return std::make_unique<WellType>(this->wells_ecl_[wellID],
1110 *this->rateConverter_,
1112 this->numConservationQuantities(),
1122 template<
typename TypeTag>
1126 const int report_step,
1131 std::ranges::find_if(this->wells_ecl_,
1132 [&well_name](
const auto& w)
1133 {
return well_name == w.name(); });
1135 if (it == this->wells_ecl_.end()) {
1137 fmt::format(fmt::runtime(
"Could not find well {} in wells_ecl"), well_name),
1141 const int pos =
static_cast<int>(std::distance(this->wells_ecl_.begin(), it));
1142 return this->createWellPointer(pos, report_step);
1147 template<
typename TypeTag>
1153 auto logger_guard = this->groupStateHelper().pushLogger();
1154 auto& local_deferredLogger = this->groupStateHelper().deferredLogger();
1156 const auto& iterCtx = simulator_.problem().iterationContext();
1159 if (gaslift_.terminalOutput()) {
1160 const std::string msg =
1161 fmt::format(fmt::runtime(
"assemble() : iteration {}"), iterCtx.iteration());
1162 gaslift_.gliftDebug(msg, local_deferredLogger);
1166 Dune::Timer perfTimer;
1168 this->closed_offending_wells_.clear();
1171 if (iterCtx.needsTimestepInit()) {
1172 this->updateNetworkActiveState_();
1174 const int episodeIdx = simulator_.episodeIndex();
1175 const auto& network = this->schedule()[episodeIdx].network();
1176 if (!this->wellsActive() && !network.active()) {
1182 if (iterCtx.needsTimestepInit() && this->wellsActive()) {
1183 OPM_TIMEBLOCK(firstIterationAssemble);
1190 calculateExplicitQuantities();
1191 prepareTimeStep(local_deferredLogger);
1194 "assemble() failed during well initialization: ",
1195 this->terminal_output_, grid().comm());
1198 const bool well_group_control_changed = updateWellControlsAndNetwork(
1201 local_deferredLogger);
1205 if ( ! this->wellsActive() ) {
1209 assembleWellEqWithoutIteration(dt);
1215 last_report_.well_group_control_changed = well_group_control_changed;
1216 last_report_.assemble_time_well += perfTimer.stop();
1222 template<
typename TypeTag>
1231 bool do_network_update =
true;
1232 bool well_group_control_changed =
false;
1233 Scalar network_imbalance = 0.0;
1235 const std::size_t iteration_to_relax = param_.network_max_strict_outer_iterations_;
1237 const std::size_t max_iteration = param_.network_max_outer_iterations_;
1238 std::size_t network_update_iteration = 0;
1239 network_needs_more_balancing_force_another_newton_iteration_ =
false;
1240 while (do_network_update) {
1241 if (!this->isRescoupSlaveCoupledNetworkIteration_()
1242 && network_update_iteration >= max_iteration ) {
1244 const int episodeIdx = simulator_.episodeIndex();
1245 if (this->network_.willBalanceOnNextIteration(episodeIdx)) {
1246 if (this->terminal_output_) {
1247 const std::string msg = fmt::format(
"Maximum of {:d} network iterations has been used and we stop the update, \n"
1248 "and try again after the next Newton iteration (imbalance = {:.2e} bar)",
1249 max_iteration, network_imbalance*1.0e-5);
1250 local_deferredLogger.
debug(msg);
1254 network_needs_more_balancing_force_another_newton_iteration_ =
true;
1256 if (this->terminal_output_) {
1257 const std::string msg = fmt::format(
"Maximum of {:d} network iterations has been used and we stop the update. \n"
1258 "The simulator will continue with unconverged network results (imbalance = {:.2e} bar)",
1259 max_iteration, network_imbalance*1.0e-5);
1260 local_deferredLogger.
info(msg);
1265 if (this->terminal_output_ && (network_update_iteration == iteration_to_relax) ) {
1266 local_deferredLogger.
debug(
"We begin using relaxed tolerance for network update now after " +
std::to_string(iteration_to_relax) +
" iterations ");
1268 const bool relax_network_balance = network_update_iteration >= iteration_to_relax;
1270 const bool optimize_gas_lift = ( (network_update_iteration + 1) < std::max(max_iteration,
static_cast<std::size_t
>(2)) );
1271 std::tie(well_group_control_changed, do_network_update, network_imbalance) =
1272 updateWellControlsAndNetworkIteration(mandatory_network_balance, relax_network_balance, optimize_gas_lift, dt,local_deferredLogger);
1273 ++network_update_iteration;
1275 if (this->isRescoupMasterCoupledNetworkIteration_()) {
1276 this->sendSlaveNetworkLoopTerminationSignal_();
1278 return well_group_control_changed;
1284 template<
typename TypeTag>
1285 std::tuple<bool, bool, typename BlackoilWellModel<TypeTag>::Scalar>
1288 const bool relax_network_tolerance,
1289 const bool optimize_gas_lift,
1294 const int reportStepIdx = simulator_.episodeIndex();
1296#ifdef RESERVOIR_COUPLING_ENABLED
1297 if (this->isRescoupSlaveCoupledNetworkIteration_()) {
1298 this->rescoupHelper_.receiveMasterGroupNodePressuresFromMaster();
1301 this->updateAndCommunicateGroupData(reportStepIdx,
true);
1306 bool well_group_control_changed = updateWellControls(local_deferredLogger);
1307 const auto [more_inner_network_update, network_imbalance] =
1308 this->network_.update(mandatory_network_balance,
1309 local_deferredLogger,
1310 relax_network_tolerance);
1311#ifdef RESERVOIR_COUPLING_ENABLED
1312 if (this->isReservoirCouplingMaster()) {
1313 this->rescoupHelper_.maybeExchangeNetworkOuterIterationWithSlaves(more_inner_network_update);
1317 bool alq_updated =
false;
1320 if (optimize_gas_lift) {
1323 const bool updatePotentials = (this->network_.shouldBalance(reportStepIdx) ||
1324 mandatory_network_balance);
1325 alq_updated = gaslift_.maybeDoGasLiftOptimize(simulator_,
1327 this->network_.nodePressures(),
1331 local_deferredLogger);
1333 prepareWellsBeforeAssembling(dt);
1336 "updateWellControlsAndNetworkIteration() failed: ",
1337 this->terminal_output_, grid().comm());
1341 guideRateUpdateIsNeeded(reportStepIdx)) {
1342 const double simulationTime = simulator_.time();
1346 this->guide_rate_handler_.updateGuideRates(
1347 reportStepIdx, simulationTime, this->wellState(), this->groupState()
1352 bool more_network_update = this->network_.shouldBalance(reportStepIdx) &&
1353 (more_inner_network_update || alq_updated);
1355 if (this->isRescoupSlaveOnSyncStepFirstSubstep_()
1356 && this->isRescoupSlaveConnectedToMasterNetwork_()) {
1363 const bool more_cross_rescoup_update =
1364 this->maybeSendSlaveGroupFlowToMaster_(reportStepIdx);
1365 more_network_update = more_network_update || more_cross_rescoup_update;
1368 return {well_group_control_changed, more_network_update, network_imbalance};
1371 template<
typename TypeTag>
1377 for (
auto& well : well_container_) {
1378 well->assembleWellEq(simulator_, dt, this->groupStateHelper(), this->wellState());
1383 template<
typename TypeTag>
1389 for (
auto& well : well_container_) {
1390 well->prepareWellBeforeAssembling(
1391 simulator_, dt, this->groupStateHelper(), this->wellState()
1397 template<
typename TypeTag>
1403 auto& deferred_logger = this->groupStateHelper().deferredLogger();
1408 for (
auto& well: well_container_) {
1409 well->assembleWellEqWithoutIteration(simulator_, this->groupStateHelper(), dt, this->wellState(),
1413 this->terminal_output_, grid().comm());
1417 template<
typename TypeTag>
1424 for (
const auto& well : well_container_) {
1425 well->addCellRates(cellRates_);
1429 template<
typename TypeTag>
1436 for (
const auto& well : well_container_) {
1437 const auto it = well_domain_map.find(well->name());
1438 if (it != well_domain_map.end() && it->second == domainIndex) {
1439 well->addCellRates(cellRates_);
1444#if COMPILE_GPU_BRIDGE
1445 template<
typename TypeTag>
1453 for(
unsigned int i = 0; i < well_container_.size(); i++){
1454 auto& well = well_container_[i];
1457 wellContribs.
addNumBlocks(derived->linSys().getNumBlocks());
1462 wellContribs.
alloc();
1464 for(
unsigned int i = 0; i < well_container_.size(); i++){
1465 auto& well = well_container_[i];
1467 auto derived_std =
dynamic_cast<StandardWell<TypeTag>*
>(well.get());
1469 derived_std->linSys().extract(derived_std->numStaticWellEq, wellContribs);
1471 auto derived_ms =
dynamic_cast<MultisegmentWell<TypeTag>*
>(well.get());
1473 derived_ms->linSys().extract(wellContribs);
1475 OpmLog::warning(
"Warning unknown type of well");
1482 template<
typename TypeTag>
1487 for (
const auto& well: well_container_ ) {
1488 well->addWellContributions(jacobian);
1492 template<
typename TypeTag>
1495 std::vector<CMatrix>& c_matrices,
1496 std::vector<DMatrix>& d_matrices,
1500 for (
const auto& well: well_container_ ) {
1501 well->addBCDMatrix(b_matrices, c_matrices, d_matrices, wcells);
1505 template<
typename TypeTag>
1510 const bool use_well_weights)
const
1512 int nw = this->numLocalWellsEnd();
1513 int rdofs = local_num_cells_;
1514 for (
int i = 0; i < nw; i++ ) {
1515 int wdof = rdofs + i;
1516 jacobian[wdof][wdof] = 1.0;
1519 for (
const auto& well : well_container_) {
1520 well->addWellPressureEquations(jacobian,
1528 template <
typename TypeTag>
1531 const std::vector<typename SparseMatrixAdapter::MatrixBlock*>& diagMatAddress)
const
1536 for (
const auto& well : well_container_) {
1537 if (!well->isOperableAndSolvable() && !well->wellIsStopped()) {
1540 const auto& cells = well->cells();
1541 const auto& rates = well->connectionRates();
1542 for (
unsigned perfIdx = 0; perfIdx < rates.size(); ++perfIdx) {
1543 unsigned cellIdx = cells[perfIdx];
1544 auto rate = rates[perfIdx];
1547 using MatrixBlockType =
typename SparseMatrixAdapter::MatrixBlock;
1548 MatrixBlockType bMat(0.0);
1549 simulator_.model().linearizer().setResAndJacobi(res, bMat, rate);
1550 residual[cellIdx] += res;
1551 *diagMatAddress[cellIdx] += bMat;
1557 template<
typename TypeTag>
1562 int nw = this->numLocalWellsEnd();
1563 int rdofs = local_num_cells_;
1564 const auto wellconnections = this->getMaxWellConnections();
1565 for (
int i = 0; i < nw; ++i) {
1566 int wdof = rdofs + i;
1567 jacobian.entry(wdof,wdof) = 0.0;
1568 const auto& perfcells = wellconnections[i];
1569 for (
int perfcell : perfcells) {
1570 jacobian.entry(wdof, perfcell) = 0.0;
1571 jacobian.entry(perfcell, wdof) = 0.0;
1577 template<
typename TypeTag>
1582 auto loggerGuard = this->groupStateHelper().pushLogger();
1585 for (
const auto& well : well_container_) {
1586 const auto& cells = well->cells();
1587 x_local_.resize(cells.size());
1589 for (
size_t i = 0; i < cells.size(); ++i) {
1590 x_local_[i] = x[cells[i]];
1592 well->recoverWellSolutionAndUpdateWellState(simulator_, x_local_,
1593 this->groupStateHelper(), this->wellState());
1597 simulator_.vanguard().grid().comm());
1601 template<
typename TypeTag>
1607 OPM_THROW(std::logic_error,
"Attempt to call NLDD method without a NLDD solver");
1610 return nldd_->recoverWellSolutionAndUpdateWellState(x, domainIdx);
1614 template<
typename TypeTag>
1617 getWellConvergence(
const std::vector<Scalar>& B_avg,
bool checkWellGroupControlsAndNetwork)
const
1621 const auto& iterCtx = simulator_.problem().iterationContext();
1622 const bool relaxTolerance = iterCtx.shouldRelax(param_.strict_outer_iter_wells_ + 1);
1624 auto logger_guard = this->groupStateHelper().pushLogger();
1625 for (
const auto& well : well_container_) {
1626 if (well->isOperableAndSolvable() || well->wellIsStopped()) {
1627 local_report += well->getWellConvergence(
1628 this->groupStateHelper(), B_avg,
1633 report.
setWellFailed({CR::WellFailure::Type::Unsolvable, CR::Severity::Normal, -1, well->name()});
1634 local_report += report;
1642 if (checkWellGroupControlsAndNetwork) {
1648 if (this->terminal_output_) {
1652 OpmLog::debug(
"NaN residual found with phase " +
std::to_string(f.phase()) +
" for well " + f.wellName());
1654 OpmLog::debug(
"Too large residual found with phase " +
std::to_string(f.phase()) +
" for well " + f.wellName());
1665 template<
typename TypeTag>
1671 for (
auto& well : well_container_) {
1672 well->calculateExplicitQuantities(simulator_, this->groupStateHelper());
1680 template<
typename TypeTag>
1686 if (!this->wellsActive()) {
1689 const int episodeIdx = simulator_.episodeIndex();
1690 const auto& comm = simulator_.vanguard().grid().comm();
1692 bool changed_well_group =
false;
1693 const Group& fieldGroup = this->schedule().getGroup(
"FIELD", episodeIdx);
1696 const std::size_t max_iter = param_.well_group_constraints_max_iterations_;
1697 while(!changed_well_group && iter < max_iter) {
1698 changed_well_group = updateGroupControls(fieldGroup, deferred_logger, episodeIdx);
1701 bool changed_well_to_group =
false;
1703 OPM_TIMEBLOCK(UpdateWellControls);
1707 for (
const auto& well : well_container_) {
1710 simulator_, mode, this->groupStateHelper(), this->wellState()
1713 changed_well_to_group = changed_well || changed_well_to_group;
1717 simulator_.gridView().comm());
1720 changed_well_to_group = comm.sum(
static_cast<int>(changed_well_to_group));
1721 if (changed_well_to_group) {
1722 updateAndCommunicate(episodeIdx);
1723 changed_well_group =
true;
1727 bool changed_well_individual =
false;
1732 for (
const auto& well : well_container_) {
1735 simulator_, mode, this->groupStateHelper(), this->wellState()
1738 changed_well_individual = changed_well || changed_well_individual;
1742 simulator_.gridView().comm());
1745 changed_well_individual = comm.sum(
static_cast<int>(changed_well_individual));
1746 if (changed_well_individual) {
1747 updateAndCommunicate(episodeIdx);
1748 changed_well_group =
true;
1754 this->updateWsolvent(fieldGroup, episodeIdx, this->nupcolWellState());
1756 return changed_well_group;
1760 template<
typename TypeTag>
1765 this->updateAndCommunicateGroupData(reportStepIdx,
true);
1771 for (
const auto& well : well_container_) {
1773 const auto& ws = this->wellState().well(well->indexOfWell());
1774 if (ws.production_cmode == Well::ProducerCMode::GRUP ||
1775 ws.injection_cmode == Well::InjectorCMode::GRUP)
1777 well->updateWellStateWithTarget(
1778 simulator_, this->groupStateHelper(), this->wellState()
1783 simulator_.gridView().comm())
1784 this->updateAndCommunicateGroupData(reportStepIdx,
true);
1787 template<
typename TypeTag>
1792 const int reportStepIdx)
1801 if (this->isReservoirCouplingMasterGroup(group.name())) {
1804 const auto& iterCtx = simulator_.problem().iterationContext();
1805 bool changed =
false;
1807 const int nupcol = this->schedule()[reportStepIdx].nupcol();
1808 const bool update_group_switching_log = !iterCtx.withinNupcol(nupcol);
1809 const bool changed_hc = this->checkGroupHigherConstraints(
1810 group, deferred_logger, reportStepIdx, update_group_switching_log);
1813 updateAndCommunicate(reportStepIdx);
1816 bool changed_individual =
1818 updateGroupIndividualControl(group,
1820 param_.max_number_of_group_switches_,
1821 update_group_switching_log,
1822 this->switched_inj_groups_,
1823 this->switched_prod_groups_,
1824 this->closed_offending_wells_,
1829 if (changed_individual) {
1831 updateAndCommunicate(reportStepIdx);
1834 for (
const std::string& groupName : group.groups()) {
1835 bool changed_this = updateGroupControls(this->schedule().getGroup(groupName, reportStepIdx), deferred_logger, reportStepIdx);
1836 changed = changed || changed_this;
1841 template<
typename TypeTag>
1847 auto logger_guard = this->groupStateHelper().pushLogger();
1848 auto& local_deferredLogger = this->groupStateHelper().deferredLogger();
1849 for (
const auto& well : well_container_) {
1850 const auto& wname = well->name();
1851 const auto wasClosed = wellTestState.well_is_closed(wname);
1852 well->checkWellOperability(simulator_,
1854 this->groupStateHelper());
1855 const bool under_zero_target =
1856 well->wellUnderZeroGroupRateTarget(this->groupStateHelper());
1857 well->updateWellTestState(this->wellState().well(wname),
1863 this->eclipseState().getUnits(),
1864 this->schedule().getStartTime(),
1865 local_deferredLogger);
1867 if (!wasClosed && wellTestState.well_is_closed(wname)) {
1868 this->closed_this_step_.insert(wname);
1871 const WellEconProductionLimits& econ_production_limits = well->wellEcl().getEconLimits();
1872 if (econ_production_limits.validFollowonWell()) {
1873 const auto episode_idx = simulator_.episodeIndex();
1874 const auto follow_on_well = econ_production_limits.followonWell();
1875 if (!this->schedule().hasWell(follow_on_well, episode_idx)) {
1876 const auto msg = fmt::format(
"Well {} was closed. But the given follow on well {} does not exist."
1877 "The simulator continues without opening a follow on well.",
1878 wname, follow_on_well);
1879 local_deferredLogger.warning(msg);
1881 auto& ws = this->wellState().well(follow_on_well);
1882 const bool success = ws.updateStatus(WellStatus::OPEN);
1884 const auto msg = fmt::format(
"Well {} was closed. The follow on well {} opens instead.", wname, follow_on_well);
1885 local_deferredLogger.info(msg);
1887 const auto msg = fmt::format(
"Well {} was closed. The follow on well {} is already open.", wname, follow_on_well);
1888 local_deferredLogger.warning(msg);
1895 for (
const auto& [group_name, to] : this->closed_offending_wells_) {
1896 if (this->hasOpenLocalWell(to.second) &&
1897 !this->wasDynamicallyShutThisTimeStep(to.second))
1899 wellTestState.close_well(to.second,
1900 WellTestConfig::Reason::GROUP,
1902 this->updateClosedWellsThisStep(to.second);
1903 const std::string msg =
1904 fmt::format(
"Procedure on exceeding {} limit is WELL for group {}. "
1910 local_deferredLogger.info(msg);
1916 template<
typename TypeTag>
1920 std::string& exc_msg,
1924 const int np = this->numPhases();
1925 std::vector<Scalar> potentials;
1926 const auto& well = well_container_[widx];
1927 std::string cur_exc_msg;
1930 well->computeWellPotentials(simulator_, well_state_copy, this->groupStateHelper(), potentials);
1935 exc_msg += fmt::format(
"\nFor well {}: {}", well->name(), cur_exc_msg);
1937 exc_type = std::max(exc_type, cur_exc_type);
1941 auto& ws = this->wellState().well(well->indexOfWell());
1942 for (
int p = 0; p < np; ++p) {
1944 ws.well_potentials[p] = std::max(
Scalar{0.0}, potentials[p]);
1950 template <
typename TypeTag>
1955 for (
const auto& wellPtr : this->well_container_) {
1956 this->calculateProductivityIndexValues(wellPtr.get(), deferred_logger);
1964 template <
typename TypeTag>
1975 for (
const auto& shutWell : this->local_shut_wells_) {
1976 if (!this->wells_ecl_[shutWell].hasConnections()) {
1981 auto wellPtr = this->
template createTypedWellPointer
1984 wellPtr->
init(this->depth_, this->gravity_, this->B_avg_,
true);
1986 this->calculateProductivityIndexValues(wellPtr.get(), deferred_logger);
1994 template <
typename TypeTag>
2008 template<
typename TypeTag>
2013 const auto episodeIdx = simulator_.episodeIndex();
2016 const bool do_prestep_network_rebalance = this->shouldDoPreStepNetworkRebalance_(episodeIdx);
2018 for (
const auto& well : well_container_) {
2019 auto& events = this->wellState().well(well->indexOfWell()).events;
2021 well->updateWellStateWithTarget(
2022 simulator_, this->groupStateHelper(), this->wellState()
2024 well->updatePrimaryVariables(this->groupStateHelper());
2030 if (events.hasEvent(ScheduleEvents::REQUEST_OPEN_WELL)) {
2031 events.clearEvent(ScheduleEvents::REQUEST_OPEN_WELL);
2034 if (param_.solve_welleq_initially_ && well->isOperableAndSolvable()) {
2036 well->solveWellEquation(
2037 simulator_, this->groupStateHelper(), this->wellState()
2039 }
catch (
const std::exception& e) {
2040 const std::string msg =
"Compute initial well solution for " + well->name() +
" initially failed. Continue with the previous rates";
2041 deferred_logger.
warning(
"WELL_INITIAL_SOLVE_FAILED", msg);
2046 well->resetWellOperability();
2048 updatePrimaryVariables();
2051 if (do_prestep_network_rebalance) {
2052 network_.doPreStepRebalance(deferred_logger);
2056 template<
typename TypeTag>
2061 std::vector< Scalar > B_avg(numConservationQuantities(),
Scalar() );
2062 const auto& grid = simulator_.vanguard().grid();
2063 const auto& gridView = grid.leafGridView();
2067 for (
const auto& elem : elements(gridView, Dune::Partitions::interior)) {
2068 elemCtx.updatePrimaryStencil(elem);
2069 elemCtx.updatePrimaryIntensiveQuantities(0);
2071 const auto& intQuants = elemCtx.intensiveQuantities(0, 0);
2072 const auto& fs = intQuants.fluidState();
2074 for (
unsigned phaseIdx = 0; phaseIdx < FluidSystem::numPhases; ++phaseIdx)
2076 if (!FluidSystem::phaseIsActive(phaseIdx)) {
2080 const unsigned compIdx = FluidSystem::canonicalToActiveCompIdx(FluidSystem::solventComponentIndex(phaseIdx));
2081 auto& B = B_avg[ compIdx ];
2083 B += 1 / fs.invB(phaseIdx).value();
2085 if constexpr (has_solvent_) {
2086 auto& B = B_avg[solventSaturationIdx];
2087 B += 1 / intQuants.solventInverseFormationVolumeFactor().value();
2093 grid.comm().sum(B_avg.data(), B_avg.size());
2094 B_avg_.resize(B_avg.size());
2095 std::ranges::transform(B_avg, B_avg_.begin(),
2096 [gcells = global_num_cells_](
const auto bval)
2097 { return bval / gcells; });
2104 template<
typename TypeTag>
2109 for (
const auto& well : well_container_) {
2110 well->updatePrimaryVariables(this->groupStateHelper());
2114 template<
typename TypeTag>
2118 const auto& grid = simulator_.vanguard().grid();
2119 const auto& eclProblem = simulator_.problem();
2120 const unsigned numCells = grid.size(0);
2122 this->pvt_region_idx_.resize(numCells);
2123 for (
unsigned cellIdx = 0; cellIdx < numCells; ++cellIdx) {
2124 this->pvt_region_idx_[cellIdx] =
2125 eclProblem.pvtRegionIndex(cellIdx);
2130 template<
typename TypeTag>
2146 return this->numPhases() + has_solvent_;
2149 template<
typename TypeTag>
2153 const auto& eclProblem = simulator_.problem();
2154 depth_.resize(local_num_cells_);
2155 for (
unsigned cellIdx = 0; cellIdx < local_num_cells_; ++cellIdx) {
2156 depth_[cellIdx] = eclProblem.dofCenterDepth(cellIdx);
2160 template<
typename TypeTag>
2163 getWell(
const std::string& well_name)
const
2167 std::ranges::find_if(well_container_,
2169 {
return elem->name() == well_name; });
2171 assert(well != well_container_.end());
2176 template <
typename TypeTag>
2181 return std::max(this->simulator_.episodeIndex(), 0);
2188 template<
typename TypeTag>
2193 const std::vector<Scalar>& production_rates,
2194 std::vector<Scalar>& resv_coeff)
const
2196 rateConverter_->calcCoeff(fipnum, pvtreg, production_rates, resv_coeff);
2199 template<
typename TypeTag>
2204 std::vector<Scalar>& resv_coeff)
const
2206 rateConverter_->calcInjCoeff(fipnum, pvtreg, resv_coeff);
2210 template <
typename TypeTag>
2215 if constexpr (energyModuleType_ == EnergyModules::FullyImplicitThermal) {
2216 const int np = this->numPhases();
2217 const int nw = this->numLocalWells();
2218 for (
auto wellID = 0*nw; wellID < nw; ++wellID) {
2219 const Well& well = this->wells_ecl_[wellID];
2220 auto& ws = this->wellState().well(wellID);
2221 if (well.isInjector()) {
2222 if (ws.status != WellStatus::STOP) {
2223 this->wellState().well(wellID).temperature = well.inj_temperature();
2227 std::array<Scalar,2> weighted{0.0,0.0};
2228 auto& [weighted_temperature, total_weight] = weighted;
2229 const auto& well_info = this->local_parallel_well_info_[wellID].get();
2230 using int_type =
decltype(this->well_perf_data_[wellID].size());
2231 for (int_type perf = 0, end_perf = this->well_perf_data_[wellID].size(); perf < end_perf; ++perf) {
2232 const int cell_idx = this->well_perf_data_[wellID][perf].cell_index;
2233 const auto& intQuants = simulator_.model().intensiveQuantities(cell_idx, 0);
2234 const auto& fs = intQuants.fluidState();
2235 Scalar weight_factor = computeTemperatureWeightFactor(perf, np, fs, ws);
2236 total_weight += weight_factor;
2237 weighted_temperature += weight_factor * fs.temperature(0).value();
2239 well_info.communication().sum(weighted.data(), 2);
2240 this->wellState().well(wellID).temperature = weighted_temperature / total_weight;
2246 template <
typename TypeTag>
2248 -> typename
WellState<Scalar,IndexTraits>::RsConstInfo
2250 if (! FluidSystem::phaseIsActive(FluidSystem::oilPhaseIdx) ||
2251 ! FluidSystem::enableConstantRs())
2256 const auto& rsConstTables = this->eclState_
2257 .getTableManager().getRsconstTables();
2259 if (rsConstTables.empty() ||
2260 (rsConstTables[0].numRows() != std::size_t{1}))
2265 const auto rsConst = rsConstTables[0].getColumn(0).front();
2267 return {
true,
static_cast<Scalar
>(rsConst) };
2273 template <
typename TypeTag>
2274 void BlackoilWellModel<TypeTag>::
2275 assignWellTracerRates_(data::Wells& wsrpt)
const
2277 const auto reportStepIdx =
static_cast<unsigned int>(this->reportStepIndex());
2278 const auto& trMod = this->simulator_.problem().tracerModel();
2284 this->assignMswTracerRates(wsrpt, trMod.getMswTracerRates(), reportStepIdx);
2287 template <
typename TypeTag>
2288 void BlackoilWellModel<TypeTag>::
2289 assignWellSpeciesRates_(data::Wells& wsrpt)
const
2291 const auto reportStepIdx =
static_cast<unsigned int>(this->reportStepIndex());
2292 const auto& geochemMod = this->simulator_.problem().geochemistryModel();
2296 this->assignMswTracerRates(wsrpt, geochemMod.getMswSpeciesRates(), reportStepIdx);
2299 template <
typename TypeTag>
2300 bool BlackoilWellModel<TypeTag>::isRescoupMasterCoupledNetworkIteration_()
const
2302#ifdef RESERVOIR_COUPLING_ENABLED
2303 return this->rescoupHelper_.masterIsInCoupledNetworkIteration();
2309 template <
typename TypeTag>
2310 bool BlackoilWellModel<TypeTag>::isRescoupSlaveCoupledNetworkIteration_()
const
2321#ifdef RESERVOIR_COUPLING_ENABLED
2322 return this->isRescoupSlaveOnSyncStepFirstSubstep_()
2323 && this->reservoirCouplingSlave().connectedToMasterCoupledNetwork()
2324 && !this->reservoirCouplingSlave().lastReceivedMasterGroupNodePressuresIsFinal();
2330 template <
typename TypeTag>
2331 bool BlackoilWellModel<TypeTag>::isRescoupSlaveOnSyncStepFirstSubstep_()
const
2338#ifdef RESERVOIR_COUPLING_ENABLED
2339 return this->isReservoirCouplingSlave()
2340 && this->reservoirCouplingSlave().isFirstSubstepOfSyncTimestep();
2346 template <
typename TypeTag>
2347 bool BlackoilWellModel<TypeTag>::isRescoupSlaveConnectedToMasterNetwork_()
const
2349#ifdef RESERVOIR_COUPLING_ENABLED
2350 return this->isReservoirCouplingSlave()
2351 && this->reservoirCouplingSlave().connectedToMasterCoupledNetwork();
2357 template <
typename TypeTag>
2358 bool BlackoilWellModel<TypeTag>::
2359 maybeSendSlaveGroupFlowToMaster_([[maybe_unused]]
const int reportStepIdx)
2361#ifdef RESERVOIR_COUPLING_ENABLED
2368 assert(this->isReservoirCouplingSlave());
2369 const bool is_final =
2370 this->reservoirCouplingSlave().lastReceivedMasterGroupNodePressuresIsFinal();
2372 this->updateAndCommunicateGroupData(reportStepIdx,
false);
2373 this->rescoupHelper_.sendSlaveGroupDataToMaster();
2382 template <
typename TypeTag>
2383 void BlackoilWellModel<TypeTag>::
2384 sendSlaveNetworkLoopTerminationSignal_()
2386#ifdef RESERVOIR_COUPLING_ENABLED
2391 assert(this->isReservoirCouplingMaster());
2392 this->rescoupHelper_.sendMasterGroupNodePressuresToSlaves(
true);
2396 template <
typename TypeTag>
2397 bool BlackoilWellModel<TypeTag>::
2398 shouldDoPreStepNetworkRebalance_(
const int episodeIdx)
const
2411 return param_.pre_solve_network_
2412 && this->network_.needPreStepRebalance(episodeIdx)
2413 && !this->isRescoupCoupledNetworkParticipant_();
2416 template <
typename TypeTag>
2417 bool BlackoilWellModel<TypeTag>::isRescoupCoupledNetworkParticipant_()
const
2419#ifdef RESERVOIR_COUPLING_ENABLED
2420 if (this->isReservoirCouplingMaster()) {
2421 return this->rescoupHelper_.masterNetworkHasMasterGroupLeaves();
2423 if (this->isReservoirCouplingSlave()) {
2424 return this->reservoirCouplingSlave().connectedToMasterCoupledNetwork();
2432 template <
typename TypeTag>
2433 void BlackoilWellModel<TypeTag>::
2434 updateNetworkActiveState_()
2445 const int episodeIdx = this->simulator_.episodeIndex();
2446 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:98
BlackoilWellModelWBP< Scalar, IndexTraits > wbp_
Definition: BlackoilWellModelGeneric.hpp:554
std::vector< std::unique_ptr< ParallelWellInfo< Scalar > > > parallel_well_info_
Definition: BlackoilWellModelGeneric.hpp:584
const Parallel::Communication & comm() const
Definition: BlackoilWellModelGeneric.hpp:227
void assignWellTracerRates(data::Wells &wsrpt, const WellTracerRates &wellTracerRates, const unsigned reportStep) const
Class for handling the guide rates in the blackoil well model.
Definition: BlackoilWellModelGuideRates.hpp:47
Class for handling the blackoil well model.
Definition: BlackoilWellModel.hpp:101
void initializeGroupStructure(const int reportStepIdx)
Definition: BlackoilWellModel_impl.hpp:301
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:2191
void prepareTimeStep(DeferredLogger &deferred_logger)
Definition: BlackoilWellModel_impl.hpp:2011
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:1287
WellInterfacePtr createWellPointer(const int wellID, const int report_step) const
Definition: BlackoilWellModel_impl.hpp:1074
void prepareWellsBeforeAssembling(const double dt)
Definition: BlackoilWellModel_impl.hpp:1386
void init()
Definition: BlackoilWellModel_impl.hpp:165
const Simulator & simulator() const
Definition: BlackoilWellModel.hpp:384
std::vector< Scalar > depth_
Definition: BlackoilWellModel.hpp:594
std::size_t global_num_cells_
Definition: BlackoilWellModel.hpp:590
GetPropType< TypeTag, Properties::Scalar > Scalar
Definition: BlackoilWellModel.hpp:110
void initWellContainer(const int reportStepIdx) override
Definition: BlackoilWellModel_impl.hpp:184
void beginReportStep(const int time_step)
Definition: BlackoilWellModel_impl.hpp:201
const WellInterface< TypeTag > & getWell(const std::string &well_name) const
Definition: BlackoilWellModel_impl.hpp:2163
GetPropType< TypeTag, Properties::FluidSystem > FluidSystem
Definition: BlackoilWellModel.hpp:106
Dune::FieldVector< Scalar, numEq > VectorBlockType
Definition: BlackoilWellModel.hpp:134
GetPropType< TypeTag, Properties::ElementContext > ElementContext
Definition: BlackoilWellModel.hpp:107
GetPropType< TypeTag, Properties::Grid > Grid
Definition: BlackoilWellModel.hpp:104
int numConservationQuantities() const
Definition: BlackoilWellModel_impl.hpp:2132
bool updateWellControls(DeferredLogger &deferred_logger)
Definition: BlackoilWellModel_impl.hpp:1683
int reportStepIndex() const
Definition: BlackoilWellModel_impl.hpp:2179
void calculateProductivityIndexValues(DeferredLogger &deferred_logger) override
Definition: BlackoilWellModel_impl.hpp:1953
void extractLegacyDepth_()
Definition: BlackoilWellModel_impl.hpp:2151
void extractLegacyCellPvtRegionIndex_()
Definition: BlackoilWellModel_impl.hpp:2116
void recoverWellSolutionAndUpdateWellStateDomain(const BVector &x, const int domainIdx)
Definition: BlackoilWellModel_impl.hpp:1604
void updateAverageFormationFactor()
Definition: BlackoilWellModel_impl.hpp:2059
GetPropType< TypeTag, Properties::Simulator > Simulator
Definition: BlackoilWellModel.hpp:109
BlackoilWellModel(Simulator &simulator, const NewtonIterationContext &iter_ctx)
Definition: BlackoilWellModel_impl.hpp:72
void initializeWellState(const int timeStepIdx)
Definition: BlackoilWellModel_impl.hpp:774
const Grid & grid() const
Definition: BlackoilWellModel.hpp:381
void updatePrimaryVariables()
Definition: BlackoilWellModel_impl.hpp:2107
void computeWellTemperature()
Definition: BlackoilWellModel_impl.hpp:2213
void addWellPressureEquations(PressureMatrix &jacobian, const BVector &weights, const bool use_well_weights) const
Definition: BlackoilWellModel_impl.hpp:1508
const SimulatorReportSingle & lastReport() const
Definition: BlackoilWellModel_impl.hpp:644
bool updateWellControlsAndNetwork(const bool mandatory_network_balance, const double dt, DeferredLogger &local_deferredLogger)
Definition: BlackoilWellModel_impl.hpp:1225
void addWellContributions(SparseMatrixAdapter &jacobian) const
Definition: BlackoilWellModel_impl.hpp:1485
void assembleWellEq(const double dt)
Definition: BlackoilWellModel_impl.hpp:1374
WellInterfacePtr createWellForWellTest(const std::string &well_name, const int report_step, DeferredLogger &deferred_logger) const
Definition: BlackoilWellModel_impl.hpp:1125
void calculateExplicitQuantities() const
Definition: BlackoilWellModel_impl.hpp:1668
void updateAndCommunicate(const int reportStepIdx)
Definition: BlackoilWellModel_impl.hpp:1763
Dune::BCRSMatrix< Opm::MatrixBlock< Scalar, 1, 1 > > PressureMatrix
Definition: BlackoilWellModel.hpp:303
void computeTotalRatesForDof(RateVector &rate, unsigned globalIdx) const
Definition: BlackoilWellModel_impl.hpp:737
void beginTimeStep()
Definition: BlackoilWellModel_impl.hpp:333
GetPropType< TypeTag, Properties::RateVector > RateVector
Definition: BlackoilWellModel.hpp:111
bool updateGroupControls(const Group &group, DeferredLogger &deferred_logger, const int reportStepIdx)
Definition: BlackoilWellModel_impl.hpp:1790
void calcInjResvCoeff(const int fipnum, const int pvtreg, std::vector< Scalar > &resv_coeff) const override
Definition: BlackoilWellModel_impl.hpp:2202
void initializeLocalWellStructure(const int reportStepIdx, const bool enableWellPIScaling)
Definition: BlackoilWellModel_impl.hpp:250
Dune::BlockVector< VectorBlockType > BVector
Definition: BlackoilWellModel.hpp:135
void wellTesting(const int timeStepIdx, const double simulationTime, DeferredLogger &deferred_logger)
Definition: BlackoilWellModel_impl.hpp:567
ConvergenceReport getWellConvergence(const std::vector< Scalar > &B_avg, const bool checkWellGroupControlsAndNetwork=false) const
Definition: BlackoilWellModel_impl.hpp:1617
typename FluidSystem::IndexTraitsType IndexTraits
Definition: BlackoilWellModel.hpp:117
void updateCellRatesForDomain(int domainIndex, const std::map< std::string, int > &well_domain_map)
Definition: BlackoilWellModel_impl.hpp:1432
void assembleWellEqWithoutIteration(const double dt)
Definition: BlackoilWellModel_impl.hpp:1400
void updateCellRates()
Definition: BlackoilWellModel_impl.hpp:1420
void assemble(const double dt)
Definition: BlackoilWellModel_impl.hpp:1150
std::size_t local_num_cells_
Definition: BlackoilWellModel.hpp:592
bool alternative_well_rate_init_
Definition: BlackoilWellModel.hpp:595
void timeStepSucceeded(const double simulationTime, const double dt)
Definition: BlackoilWellModel_impl.hpp:654
std::unique_ptr< WellType > createTypedWellPointer(const int wellID, const int time_step) const
Definition: BlackoilWellModel_impl.hpp:1094
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:1918
Simulator & simulator_
Definition: BlackoilWellModel.hpp:564
void createWellContainer(const int report_step) override
Definition: BlackoilWellModel_impl.hpp:817
std::unique_ptr< WellInterface< TypeTag > > WellInterfacePtr
Definition: BlackoilWellModel.hpp:191
void updateWellTestState(const double simulationTime, WellTestState &wellTestState)
upate the wellTestState related to economic limits
Definition: BlackoilWellModel_impl.hpp:1844
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:1494
void addReservoirSourceTerms(GlobalEqVector &residual, const std::vector< typename SparseMatrixAdapter::MatrixBlock * > &diagMatAddress) const
Definition: BlackoilWellModel_impl.hpp:1530
int compressedIndexForInterior(int cartesian_cell_idx) const override
get compressed index for interior cells (-1, otherwise
Definition: BlackoilWellModel.hpp:356
void recoverWellSolutionAndUpdateWellState(const BVector &x)
Definition: BlackoilWellModel_impl.hpp:1580
void addWellPressureEquationsStruct(PressureMatrix &jacobian) const
Definition: BlackoilWellModel_impl.hpp:1560
void calculateProductivityIndexValuesShutWells(const int reportStepIdx, DeferredLogger &deferred_logger) override
Definition: BlackoilWellModel_impl.hpp:1967
void endReportStep()
Definition: BlackoilWellModel_impl.hpp:627
Definition: ConvergenceReport.hpp:38
void setWellFailed(const WellFailure &wf)
Definition: ConvergenceReport.hpp:296
void setWellGroupTargetsViolated(const bool wellGroupTargetsViolated)
Definition: ConvergenceReport.hpp:314
const std::vector< WellFailure > & wellFailures() const
Definition: ConvergenceReport.hpp:459
void setNetworkNotYetBalancedForceAnotherNewtonIteration(const bool network_needs_more_balancing_force_another_newton_iteration)
Definition: ConvergenceReport.hpp:319
Definition: DeferredLogger.hpp:57
void info(const std::string &tag, const std::string &message)
void warning(const std::string &tag, const std::string &message)
void debug(const std::string &tag, const std::string &message)
std::map< std::string, std::pair< const Well *, int > > GLiftEclWells
Definition: GasLiftGroupInfo.hpp:65
Class encapsulating some information about parallel wells.
Definition: ParallelWellInfo.hpp:198
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)
int indexOfWell() const
Index of well in the wells struct and wellState.
Definition: WellInterface.hpp:78
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:191
Definition: WellState.hpp:68
if(!linsolver_)
Definition: FlexibleSolver_impl.hpp:326
ExcEnum
Definition: DeferredLogger.hpp:45
@ NONE
Definition: DeferredLogger.hpp:46
Dune::Communication< MPIComm > Communication
Definition: ParallelCommunication.hpp:30
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