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>
51#ifdef RESERVOIR_COUPLING_ENABLED
73#include <fmt/format.h>
76 template<
typename TypeTag>
83 simulator.vanguard().summaryState(),
84 simulator.vanguard().eclState(),
86 simulator.gridView().comm())
87 , simulator_(simulator)
88 , guide_rate_handler_{
90 simulator.vanguard().schedule(),
91 simulator.vanguard().summaryState(),
92 simulator.vanguard().grid().comm()
94 , gaslift_(this->terminal_output_)
103 auto& parallel_wells =
simulator.vanguard().parallelWells();
106 for(
const auto& name_bool : parallel_wells) {
112 Parameters::Get<Parameters::AlternativeWellRateInit>();
114 using SourceDataSpan =
115 typename PAvgDynamicSourceData<Scalar>::template SourceDataSpan<Scalar>;
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();
259 this->wells_ecl_ = this->getLocalWells(reportStepIdx);
260 this->local_parallel_well_info_ =
261 this->createLocalParallelWellInfo(this->wells_ecl_);
268 this->initializeWellPerfData();
269 this->initializeWellState(reportStepIdx);
270 this->wbp_.initializeWBPCalculationService();
272 if (this->param_.use_multisegment_well_ && this->anyMSWellOpenLocal()) {
273 this->wellState().initWellStateMSWell(this->wells_ecl_, &this->prevWellState());
276 this->initializeWellProdIndCalculators();
278 if (enableWellPIScaling && this->schedule()[reportStepIdx].events()
279 .hasEvent(ScheduleEvents::Events::WELL_PRODUCTIVITY_INDEX))
281 this->runWellPIScaling(reportStepIdx, local_deferredLogger);
285 "Failed to initialize local well structure: ",
286 this->terminal_output_, comm)
293 template <
typename TypeTag>
298 const auto& comm = this->simulator_.vanguard().grid().comm();
302 const auto& fieldGroup =
303 this->schedule().getGroup(
"FIELD", reportStepIdx);
305 this->groupStateHelper().setCmodeGroup(fieldGroup);
309 if (this->schedule()[reportStepIdx].has_gpmaint()) {
310 this->groupStateHelper().setRegionAveragePressureCalculator(
312 this->eclState_.fieldProps(),
313 this->regionalAveragePressureCalculator_
325 template<
typename TypeTag>
330 OPM_TIMEBLOCK(beginTimeStep);
332 this->updateAverageFormationFactor();
334 auto logger_guard = this->groupStateHelper().pushLogger();
335 auto& local_deferredLogger = this->groupStateHelper().deferredLogger();
337#ifdef RESERVOIR_COUPLING_ENABLED
338 auto rescoup_logger_guard = this->setupRescoupScopedLogger(local_deferredLogger);
341 this->switched_prod_groups_.clear();
342 this->switched_inj_groups_.clear();
344 if (this->wellStructureChangedDynamically_) {
349 const auto reportStepIdx =
350 this->simulator_.episodeIndex();
354 const auto enableWellPIScaling =
false;
356 this->initializeLocalWellStructure(reportStepIdx, enableWellPIScaling);
357 this->initializeGroupStructure(reportStepIdx);
359 this->commitWGState();
365 this->wellStructureChangedDynamically_ =
false;
368 this->resetWGState();
369 const int reportStepIdx = simulator_.episodeIndex();
371 this->wellState().updateWellsDefaultALQ(this->schedule(), reportStepIdx, this->summaryState());
372 this->wellState().gliftTimeStepInit();
374 const double simulationTime = simulator_.time();
375 const auto& iterCtx = simulator_.problem().iterationContext();
379 wellTesting(reportStepIdx, simulationTime, local_deferredLogger);
382 createWellContainer(reportStepIdx);
384#ifdef RESERVOIR_COUPLING_ENABLED
385 if (this->isReservoirCouplingMaster()) {
386 if (this->reservoirCouplingMaster().isFirstSubstepOfSyncTimestep()) {
387 this->receiveSlaveGroupData();
394 this->updateAndCommunicateGroupData(reportStepIdx,
396 param_.nupcol_group_rate_tolerance_,
false);
399 const Grid& grid = simulator_.vanguard().grid();
400 this->wells_active_ = grid.comm().max(!this->well_container_.empty());
405 this->initWellContainer(reportStepIdx);
408 std::fill(is_cell_perforated_.begin(), is_cell_perforated_.end(),
false);
409 for (
auto& well : well_container_) {
410 well->updatePerforatedCell(is_cell_perforated_);
414 this->calculateEfficiencyFactors(reportStepIdx);
416 if constexpr (has_polymer_)
418 if (PolymerModule::hasPlyshlog() || getPropValue<TypeTag, Properties::EnablePolymerMW>() ) {
419 this->setRepRadiusPerfLength();
426 this->terminal_output_, simulator_.vanguard().grid().comm());
428 for (
auto& well : well_container_) {
429 well->setVFPProperties(this->vfp_properties_.get());
430 well->setGuideRate(&this->guideRate_);
433 this->updateFiltrationModelsPreStep(local_deferredLogger);
436 for (
auto& well : well_container_) {
437 well->closeCompletions(this->wellTestState());
443 if (alternative_well_rate_init_) {
448 for (
const auto& well : well_container_) {
449 if (well->isProducer() && !well->wellIsStopped()) {
450 well->initializeProducerWellState(simulator_, this->wellState(), local_deferredLogger);
455 for (
const auto& well : well_container_) {
456 if (well->isVFPActive(local_deferredLogger)){
457 well->setPrevSurfaceRates(this->wellState(), this->prevWellState());
461 this->updateWellPotentials(reportStepIdx,
463 simulator_.vanguard().summaryConfig(),
464 local_deferredLogger);
465 }
catch ( std::runtime_error& e ) {
466 const std::string msg =
"A zero well potential is returned for output purposes. ";
467 local_deferredLogger.warning(
"WELL_POTENTIAL_CALCULATION_FAILED", msg);
470 this->guide_rate_handler_.updateGuideRates(
471 reportStepIdx, simulationTime, this->wellState(), this->groupState()
473 bool slave_needs_well_solution =
false;
474#ifdef RESERVOIR_COUPLING_ENABLED
475 if (this->isReservoirCouplingSlave()) {
476 if (this->reservoirCouplingSlave().isFirstSubstepOfSyncTimestep()) {
477 this->sendSlaveGroupDataToMaster();
478 this->receiveGroupConstraintsFromMaster();
479 this->groupStateHelper().updateSlaveGroupCmodesFromMaster();
480 slave_needs_well_solution =
true;
487 if (this->schedule_[reportStepIdx].has_gpmaint()) {
488 for (
const auto& calculator : regionalAveragePressureCalculator_) {
489 calculator.second->template defineState<ElementContext>(simulator_);
491 const double dt = simulator_.timeStepSize();
492 const Group& fieldGroup = this->schedule().getGroup(
"FIELD", reportStepIdx);
494 this->groupStateHelper().updateGpMaintTargetForGroups(fieldGroup,
495 regionalAveragePressureCalculator_,
501 this->updateAndCommunicateGroupData(reportStepIdx,
503 param_.nupcol_group_rate_tolerance_,
507 for (
auto& well : well_container_) {
508 const uint64_t effective_events_mask = ScheduleEvents::WELL_STATUS_CHANGE
509 + ScheduleEvents::INJECTION_TYPE_CHANGED
510 + ScheduleEvents::WELL_SWITCHED_INJECTOR_PRODUCER
511 + ScheduleEvents::NEW_WELL;
513 const auto& events = this->schedule()[reportStepIdx].wellgroup_events();
514 const bool event = this->report_step_starts_ && events.hasEvent(well->name(), effective_events_mask);
515 const bool dyn_status_change = this->wellState().well(well->name()).status
516 != this->prevWellState().well(well->name()).status;
518 if (event || dyn_status_change || slave_needs_well_solution) {
520 well->scaleSegmentRatesAndPressure(this->wellState());
521 well->calculateExplicitQuantities(simulator_, this->groupStateHelper());
522 well->updateWellStateWithTarget(simulator_, this->groupStateHelper(), this->wellState());
523 well->updatePrimaryVariables(this->groupStateHelper());
524 well->solveWellEquation(
525 simulator_, this->groupStateHelper(), this->wellState()
527 }
catch (
const std::exception& e) {
528 const std::string msg =
"Compute initial well solution for new well " + well->name() +
" failed. Continue with zero initial rates";
529 local_deferredLogger.warning(
"WELL_INITIAL_SOLVE_FAILED", msg);
537#ifdef RESERVOIR_COUPLING_ENABLED
538 if (this->isReservoirCouplingSlave()) {
539 if (slave_needs_well_solution) {
540 this->updateAndCommunicateGroupData(reportStepIdx,
542 param_.nupcol_group_rate_tolerance_,
544 this->sendSlaveGroupDataToMaster();
549#ifdef RESERVOIR_COUPLING_ENABLED
550 if (this->isReservoirCouplingMaster()) {
551 if (this->reservoirCouplingMaster().isFirstSubstepOfSyncTimestep()) {
552 this->sendMasterGroupConstraintsToSlaves();
553 this->receiveSlaveGroupData();
559 const std::string msg =
"Compute initial well solution for new wells failed. Continue with zero initial rates";
560 local_deferredLogger.warning(
"WELL_INITIAL_SOLVE_FAILED", msg);
563 const auto& comm = simulator_.vanguard().grid().comm();
565 exc_type,
"beginTimeStep() failed: " + exc_msg, this->terminal_output_, comm);
569#ifdef RESERVOIR_COUPLING_ENABLED
579 template<
typename TypeTag>
580 std::optional<ReservoirCoupling::ScopedLoggerGuard>
583 if (this->isReservoirCouplingMaster()) {
585 this->reservoirCouplingMaster().logger(),
588 }
else if (this->isReservoirCouplingSlave()) {
589 return ReservoirCoupling::ScopedLoggerGuard{
590 this->reservoirCouplingSlave().logger(),
597 template<
typename TypeTag>
599 BlackoilWellModel<TypeTag>::
600 receiveSlaveGroupData()
602 assert(this->isReservoirCouplingMaster());
603 RescoupReceiveSlaveGroupData<Scalar, IndexTraits> slave_group_data_receiver{
604 this->groupStateHelper(),
606 slave_group_data_receiver.receiveSlaveGroupData();
609 template<
typename TypeTag>
611 BlackoilWellModel<TypeTag>::
612 sendSlaveGroupDataToMaster()
614 assert(this->isReservoirCouplingSlave());
615 RescoupSendSlaveGroupData<Scalar, IndexTraits> slave_group_data_sender{this->groupStateHelper()};
616 slave_group_data_sender.sendSlaveGroupDataToMaster();
619 template<
typename TypeTag>
621 BlackoilWellModel<TypeTag>::
622 sendMasterGroupConstraintsToSlaves()
625 RescoupConstraintsCalculator<Scalar, IndexTraits> constraints_calculator{
626 this->guide_rate_handler_,
627 this->groupStateHelper()
629 constraints_calculator.calculateMasterGroupConstraintsAndSendToSlaves();
632 template<
typename TypeTag>
634 BlackoilWellModel<TypeTag>::
635 receiveGroupConstraintsFromMaster()
637 RescoupReceiveGroupConstraints<Scalar, IndexTraits> constraint_receiver{
638 this->guide_rate_handler_,
639 this->groupStateHelper()
641 constraint_receiver.receiveGroupConstraintsFromMaster();
646 template<
typename TypeTag>
649 const double simulationTime,
652 for (
const std::string& well_name : this->getWellsForTesting(timeStepIdx, simulationTime)) {
653 const Well& wellEcl = this->schedule().getWell(well_name, timeStepIdx);
654 if (wellEcl.getStatus() == Well::Status::SHUT)
657 WellInterfacePtr well = createWellForWellTest(well_name, timeStepIdx, deferred_logger);
659 well->init(depth_, gravity_, B_avg_,
true);
661 Scalar well_efficiency_factor = wellEcl.getEfficiencyFactor() *
662 this->wellState().getGlobalEfficiencyScalingFactor(well_name);
663 this->groupStateHelper().accumulateGroupEfficiencyFactor(
664 this->schedule().getGroup(wellEcl.groupName(), timeStepIdx),
665 well_efficiency_factor
668 well->setWellEfficiencyFactor(well_efficiency_factor);
669 well->setVFPProperties(this->vfp_properties_.get());
670 well->setGuideRate(&this->guideRate_);
673 if (well->isProducer() && alternative_well_rate_init_) {
674 well->initializeProducerWellState(simulator_, this->wellState(), deferred_logger);
676 if (well->isVFPActive(deferred_logger)) {
677 well->setPrevSurfaceRates(this->wellState(), this->prevWellState());
680 const auto& network = this->schedule()[timeStepIdx].network();
681 if (network.active()) {
682 this->network_.initializeWell(*well);
686 GLiftEclWells ecl_well_map;
687 gaslift_.initGliftEclWellMap(well_container_, ecl_well_map);
688 well->wellTesting(simulator_,
690 this->groupStateHelper(),
692 this->wellTestState(),
694 this->well_open_times_);
695 }
catch (
const std::exception& e) {
696 const std::string msg =
697 fmt::format(fmt::runtime(
"Exception during testing of well: {}. The well will not open.\n"
698 "Exception message: {}"), wellEcl.name(), e.what());
699 deferred_logger.
warning(
"WELL_TESTING_FAILED", msg);
705 template<
typename TypeTag>
711 for (
auto&& pinfo : this->local_parallel_well_info_)
722 template<
typename TypeTag>
732 template<
typename TypeTag>
737 this->closed_this_step_.clear();
740 this->report_step_starts_ =
false;
741 const int reportStepIdx = simulator_.episodeIndex();
743 auto logger_guard = this->groupStateHelper().pushLogger();
744 auto& local_deferredLogger = this->groupStateHelper().deferredLogger();
745 for (
const auto& well : well_container_) {
746 if (getPropValue<TypeTag, Properties::EnablePolymerMW>() && well->isInjector()) {
747 well->updateWaterThroughput(dt, this->wellState());
751 for (
const auto& well : well_container_) {
752 well->updateConnectionTransmissibilityFactor(simulator_, this->wellState().well(well->indexOfWell()));
753 well->updateConnectionDFactor(simulator_, this->wellState().well(well->indexOfWell()));
756 if (Indices::waterEnabled) {
757 this->updateFiltrationModelsPostStep(dt, FluidSystem::waterPhaseIdx, local_deferredLogger);
761 this->updateInjMult(local_deferredLogger);
764 for (
const auto& well : well_container_) {
765 well->reportWellSwitching(this->wellState().well(well->indexOfWell()), local_deferredLogger);
768 if (this->terminal_output_) {
769 this->reportGroupSwitching(local_deferredLogger);
773 rateConverter_->template defineState<ElementContext>(simulator_);
777 this->updateWellPotentials(reportStepIdx,
779 simulator_.vanguard().summaryConfig(),
780 local_deferredLogger);
781 }
catch ( std::runtime_error& e ) {
782 const std::string msg =
"A zero well potential is returned for output purposes. ";
783 local_deferredLogger.warning(
"WELL_POTENTIAL_CALCULATION_FAILED", msg);
786 updateWellTestState(simulationTime, this->wellTestState());
789 const Group& fieldGroup = this->schedule_.getGroup(
"FIELD", reportStepIdx);
790 this->checkGEconLimits(fieldGroup, simulationTime,
791 simulator_.episodeIndex(), local_deferredLogger);
792 this->checkGconsaleLimits(fieldGroup, this->wellState(),
793 simulator_.episodeIndex(), local_deferredLogger);
795 this->calculateProductivityIndexValues(local_deferredLogger);
797 this->groupStateHelper().updateNONEProductionGroups();
799 this->commitWGState();
802 this->computeWellTemperature();
806 template<
typename TypeTag>
810 unsigned elemIdx)
const
814 if (!is_cell_perforated_[elemIdx] || cellRates_.count(elemIdx) == 0) {
818 rate = cellRates_.at(elemIdx);
822 template<
typename TypeTag>
823 template <
class Context>
827 const Context& context,
829 unsigned timeIdx)
const
832 int elemIdx = context.globalSpaceIndex(spaceIdx, timeIdx);
834 if (!is_cell_perforated_[elemIdx] || cellRates_.count(elemIdx) == 0) {
838 rate = cellRates_.at(elemIdx);
843 template<
typename TypeTag>
848 const auto pressIx = []()
850 if (Indices::oilEnabled) {
return FluidSystem::oilPhaseIdx; }
851 if (Indices::waterEnabled) {
return FluidSystem::waterPhaseIdx; }
853 return FluidSystem::gasPhaseIdx;
856 auto cellPressures = std::vector<Scalar>(this->local_num_cells_,
Scalar{0});
857 auto cellTemperatures = std::vector<Scalar>(this->local_num_cells_,
Scalar{0});
860 const auto& gridView = this->simulator_.vanguard().gridView();
863 for (
const auto& elem : elements(gridView, Dune::Partitions::interior)) {
864 elemCtx.updatePrimaryStencil(elem);
865 elemCtx.updatePrimaryIntensiveQuantities(0);
867 const auto ix = elemCtx.globalSpaceIndex(0, 0);
868 const auto& fs = elemCtx.intensiveQuantities(0, 0).fluidState();
870 cellPressures[ix] = fs.pressure(pressIx).value();
871 cellTemperatures[ix] = fs.temperature(0).value();
874 this->simulator_.vanguard().grid().comm());
876 this->wellState().init(cellPressures, cellTemperatures, this->schedule(), this->wells_ecl_,
877 this->local_parallel_well_info_, timeStepIdx,
878 &this->prevWellState(), this->well_perf_data_,
879 this->summaryState(), simulator_.vanguard().enableDistributedWells());
886 template<
typename TypeTag>
891 auto logger_guard = this->groupStateHelper().pushLogger();
892 auto& local_deferredLogger = this->groupStateHelper().deferredLogger();
894 const int nw = this->numLocalWells();
896 well_container_.clear();
899 well_container_.reserve(nw);
901 const auto& wmatcher = this->schedule().wellMatcher(report_step);
902 const auto& wcycle = this->schedule()[report_step].wcycle.get();
906 std::ranges::for_each(this->wells_ecl_,
907 [
this, &wg_events = this->report_step_start_events_](
const auto& well_ecl)
909 if (!well_ecl.hasConnections()) {
914 constexpr auto events_mask = ScheduleEvents::WELL_STATUS_CHANGE |
915 ScheduleEvents::REQUEST_OPEN_WELL |
916 ScheduleEvents::REQUEST_SHUT_WELL;
917 const bool well_event =
918 this->report_step_starts_ &&
919 wg_events.hasEvent(well_ecl.name(), events_mask);
928 if (well_ecl.getStatus() == WellStatus::OPEN) {
929 this->well_open_times_.insert_or_assign(well_ecl.name(),
930 this->simulator_.time());
931 this->well_close_times_.erase(well_ecl.name());
932 }
else if (well_ecl.getStatus() == WellStatus::SHUT) {
933 this->well_close_times_.insert_or_assign(well_ecl.name(),
934 this->simulator_.time());
935 this->well_open_times_.erase(well_ecl.name());
941 const auto cycle_states = wcycle.wellStatus(this->simulator_.time(),
943 this->well_open_times_,
944 this->well_close_times_);
946 for (
int w = 0; w < nw; ++w) {
947 const Well& well_ecl = this->wells_ecl_[w];
949 if (!well_ecl.hasConnections()) {
954 const std::string& well_name = well_ecl.name();
955 const auto well_status = this->schedule()
956 .getWell(well_name, report_step).getStatus();
958 const bool shut_event = this->wellState().well(w).events.hasEvent(ScheduleEvents::WELL_STATUS_CHANGE)
959 && well_status == Well::Status::SHUT;
960 const bool open_event = this->wellState().well(w).events.hasEvent(ScheduleEvents::WELL_STATUS_CHANGE)
961 && well_status == Well::Status::OPEN;
962 const auto& ws = this->wellState().well(well_name);
964 if (shut_event && ws.status != Well::Status::SHUT) {
965 this->closed_this_step_.insert(well_name);
966 this->wellState().shutWell(w);
967 }
else if (open_event && ws.status != Well::Status::OPEN) {
968 this->wellState().openWell(w);
972 if (this->wellTestState().well_is_closed(well_name)) {
977 const bool closed_this_step = (this->wellTestState().lastTestTime(well_name) == simulator_.time());
980 auto& events = this->wellState().well(w).events;
981 if (events.hasEvent(ScheduleEvents::REQUEST_OPEN_WELL)) {
982 if (!closed_this_step) {
983 this->wellTestState().open_well(well_name);
984 this->wellTestState().open_completions(well_name);
985 this->well_open_times_.insert_or_assign(well_name,
986 this->simulator_.time());
987 this->well_close_times_.erase(well_name);
989 events.clearEvent(ScheduleEvents::REQUEST_OPEN_WELL);
995 if (this->wellTestState().well_is_closed(well_name))
997 if (well_ecl.getAutomaticShutIn()) {
999 this->wellState().shutWell(w);
1000 this->well_close_times_.erase(well_name);
1001 this->well_open_times_.erase(well_name);
1004 if (!well_ecl.getAllowCrossFlow()) {
1007 this->wellState().shutWell(w);
1008 this->well_close_times_.erase(well_name);
1009 this->well_open_times_.erase(well_name);
1013 this->wellState().stopWell(w);
1018 if (!well_ecl.getAllowCrossFlow()) {
1019 const bool any_zero_rate_constraint = well_ecl.isProducer()
1020 ? well_ecl.productionControls(this->summaryState_).anyZeroRateConstraint()
1021 : well_ecl.injectionControls(this->summaryState_).anyZeroRateConstraint();
1022 if (any_zero_rate_constraint) {
1024 local_deferredLogger.debug(fmt::format(fmt::runtime(
" Well {} gets shut due to having zero rate constraint and disallowing crossflow "), well_ecl.name()));
1025 this->wellState().shutWell(w);
1026 this->well_close_times_.erase(well_name);
1027 this->well_open_times_.erase(well_name);
1032 if (!wcycle.empty()) {
1033 const auto it = cycle_states.find(well_name);
1034 if (it != cycle_states.end()) {
1035 if (!it->second || well_status == Well::Status::SHUT) {
1037 if (well_status == Well::Status::SHUT) {
1038 this->well_open_times_.erase(well_name);
1039 this->well_close_times_.erase(well_name);
1041 this->wellState().shutWell(w);
1044 this->wellState().openWell(w);
1050 if (ws.status == Well::Status::SHUT) {
1054 well_container_.emplace_back(this->createWellPointer(w, report_step));
1056 if (ws.status == Well::Status::STOP) {
1057 well_container_.back()->stopWell();
1058 this->well_close_times_.erase(well_name);
1059 this->well_open_times_.erase(well_name);
1063 if (!wcycle.empty()) {
1064 const auto schedule_open =
1065 [&wg_events = this->report_step_start_events_](
const std::string& name)
1067 return wg_events.hasEvent(name, ScheduleEvents::REQUEST_OPEN_WELL);
1069 for (
const auto& [wname, wscale] : wcycle.efficiencyScale(this->simulator_.time(),
1070 this->simulator_.timeStepSize(),
1072 this->well_open_times_,
1075 this->wellState().updateEfficiencyScalingFactor(wname, wscale);
1076 this->schedule_.add_event(ScheduleEvents::WELLGROUP_EFFICIENCY_UPDATE, report_step);
1081 this->well_container_generic_.clear();
1082 for (
auto& w : well_container_) {
1083 this->well_container_generic_.push_back(w.get());
1086 this->network_.initialize(report_step);
1088 this->wbp_.registerOpenWellsForWBPCalculation();
1095 template <
typename TypeTag>
1100 const auto is_multiseg = this->wells_ecl_[wellID].isMultiSegment();
1102 if (! (this->param_.use_multisegment_well_ && is_multiseg)) {
1103 return this->
template createTypedWellPointer<StandardWell<TypeTag>>(wellID, report_step);
1106 return this->
template createTypedWellPointer<MultisegmentWell<TypeTag>>(wellID, report_step);
1114 template <
typename TypeTag>
1115 template <
typename WellType>
1116 std::unique_ptr<WellType>
1121 const auto& perf_data = this->well_perf_data_[wellID];
1124 const auto pvtreg = perf_data.empty()
1125 ? 0 : this->pvt_region_idx_[perf_data.front().cell_index];
1127 const auto& parallel_well_info = this->local_parallel_well_info_[wellID].get();
1128 const auto global_pvtreg = parallel_well_info.broadcastFirstPerforationValue(pvtreg);
1130 return std::make_unique<WellType>(this->wells_ecl_[wellID],
1134 *this->rateConverter_,
1136 this->numConservationQuantities(),
1146 template<
typename TypeTag>
1150 const int report_step,
1155 std::ranges::find_if(this->wells_ecl_,
1156 [&well_name](
const auto& w)
1157 {
return well_name == w.name(); });
1159 if (it == this->wells_ecl_.end()) {
1161 fmt::format(fmt::runtime(
"Could not find well {} in wells_ecl"), well_name),
1165 const int pos =
static_cast<int>(std::distance(this->wells_ecl_.begin(), it));
1166 return this->createWellPointer(pos, report_step);
1171 template<
typename TypeTag>
1177 auto logger_guard = this->groupStateHelper().pushLogger();
1178 auto& local_deferredLogger = this->groupStateHelper().deferredLogger();
1180 const auto& iterCtx = simulator_.problem().iterationContext();
1183 if (gaslift_.terminalOutput()) {
1184 const std::string msg =
1185 fmt::format(fmt::runtime(
"assemble() : iteration {}"), iterCtx.iteration());
1186 gaslift_.gliftDebug(msg, local_deferredLogger);
1190 Dune::Timer perfTimer;
1192 this->closed_offending_wells_.clear();
1195 const int episodeIdx = simulator_.episodeIndex();
1196 const auto& network = this->schedule()[episodeIdx].network();
1197 if (!this->wellsActive() && !network.active()) {
1203 if (iterCtx.needsTimestepInit() && this->wellsActive()) {
1204 OPM_TIMEBLOCK(firstIterationAssemble);
1211 calculateExplicitQuantities();
1212 prepareTimeStep(local_deferredLogger);
1215 "assemble() failed during well initialization: ",
1216 this->terminal_output_, grid().comm());
1219 const bool well_group_control_changed = updateWellControlsAndNetwork(
false, dt, local_deferredLogger);
1223 if ( ! this->wellsActive() ) {
1227 assembleWellEqWithoutIteration(dt);
1233 last_report_.well_group_control_changed = well_group_control_changed;
1234 last_report_.assemble_time_well += perfTimer.stop();
1240 template<
typename TypeTag>
1249 bool do_network_update =
true;
1250 bool well_group_control_changed =
false;
1251 Scalar network_imbalance = 0.0;
1253 const std::size_t iteration_to_relax = param_.network_max_strict_outer_iterations_;
1255 const std::size_t max_iteration = param_.network_max_outer_iterations_;
1256 std::size_t network_update_iteration = 0;
1257 network_needs_more_balancing_force_another_newton_iteration_ =
false;
1258 while (do_network_update) {
1259 if (network_update_iteration >= max_iteration ) {
1261 const int episodeIdx = simulator_.episodeIndex();
1262 const auto& iterCtx = simulator_.problem().iterationContext();
1263 if (this->network_.willBalanceOnNextIteration(episodeIdx, iterCtx)) {
1264 if (this->terminal_output_) {
1265 const std::string msg = fmt::format(
"Maximum of {:d} network iterations has been used and we stop the update, \n"
1266 "and try again after the next Newton iteration (imbalance = {:.2e} bar)",
1267 max_iteration, network_imbalance*1.0e-5);
1268 local_deferredLogger.
debug(msg);
1272 network_needs_more_balancing_force_another_newton_iteration_ =
true;
1274 if (this->terminal_output_) {
1275 const std::string msg = fmt::format(
"Maximum of {:d} network iterations has been used and we stop the update. \n"
1276 "The simulator will continue with unconverged network results (imbalance = {:.2e} bar)",
1277 max_iteration, network_imbalance*1.0e-5);
1278 local_deferredLogger.
info(msg);
1283 if (this->terminal_output_ && (network_update_iteration == iteration_to_relax) ) {
1284 local_deferredLogger.
debug(
"We begin using relaxed tolerance for network update now after " +
std::to_string(iteration_to_relax) +
" iterations ");
1286 const bool relax_network_balance = network_update_iteration >= iteration_to_relax;
1288 const bool optimize_gas_lift = ( (network_update_iteration + 1) < std::max(max_iteration,
static_cast<std::size_t
>(2)) );
1289 std::tie(well_group_control_changed, do_network_update, network_imbalance) =
1290 updateWellControlsAndNetworkIteration(mandatory_network_balance, relax_network_balance, optimize_gas_lift, dt,local_deferredLogger);
1291 ++network_update_iteration;
1293 return well_group_control_changed;
1299 template<
typename TypeTag>
1300 std::tuple<bool, bool, typename BlackoilWellModel<TypeTag>::Scalar>
1303 const bool relax_network_tolerance,
1304 const bool optimize_gas_lift,
1309 const auto& iterCtx = simulator_.problem().iterationContext();
1310 const int reportStepIdx = simulator_.episodeIndex();
1311 this->updateAndCommunicateGroupData(reportStepIdx, iterCtx,
1312 param_.nupcol_group_rate_tolerance_,
true);
1317 bool well_group_control_changed = updateWellControls(local_deferredLogger);
1318 const auto [more_inner_network_update, network_imbalance] =
1319 this->network_.update(mandatory_network_balance,
1320 local_deferredLogger,
1321 relax_network_tolerance);
1323 bool alq_updated =
false;
1326 if (optimize_gas_lift) {
1329 const bool updatePotentials = (this->network_.shouldBalance(reportStepIdx, iterCtx) ||
1330 mandatory_network_balance);
1331 alq_updated = gaslift_.maybeDoGasLiftOptimize(simulator_,
1333 this->network_.nodePressures(),
1337 local_deferredLogger);
1339 prepareWellsBeforeAssembling(dt);
1342 "updateWellControlsAndNetworkIteration() failed: ",
1343 this->terminal_output_, grid().comm());
1347 guideRateUpdateIsNeeded(reportStepIdx)) {
1348 const double simulationTime = simulator_.time();
1352 this->guide_rate_handler_.updateGuideRates(
1353 reportStepIdx, simulationTime, this->wellState(), this->groupState()
1358 const bool more_network_update = this->network_.shouldBalance(reportStepIdx, iterCtx) &&
1359 (more_inner_network_update || alq_updated);
1360 return {well_group_control_changed, more_network_update, network_imbalance};
1363 template<
typename TypeTag>
1369 for (
auto& well : well_container_) {
1370 well->assembleWellEq(simulator_, dt, this->groupStateHelper(), this->wellState());
1375 template<
typename TypeTag>
1381 for (
auto& well : well_container_) {
1382 well->prepareWellBeforeAssembling(
1383 simulator_, dt, this->groupStateHelper(), this->wellState()
1389 template<
typename TypeTag>
1395 auto& deferred_logger = this->groupStateHelper().deferredLogger();
1400 for (
auto& well: well_container_) {
1401 well->assembleWellEqWithoutIteration(simulator_, this->groupStateHelper(), dt, this->wellState(),
1405 this->terminal_output_, grid().comm());
1409 template<
typename TypeTag>
1416 for (
const auto& well : well_container_) {
1417 well->addCellRates(cellRates_);
1421 template<
typename TypeTag>
1428 for (
const auto& well : well_container_) {
1429 const auto it = well_domain_map.find(well->name());
1430 if (it != well_domain_map.end() && it->second == domainIndex) {
1431 well->addCellRates(cellRates_);
1436#if COMPILE_GPU_BRIDGE
1437 template<
typename TypeTag>
1445 for(
unsigned int i = 0; i < well_container_.size(); i++){
1446 auto& well = well_container_[i];
1449 wellContribs.
addNumBlocks(derived->linSys().getNumBlocks());
1454 wellContribs.
alloc();
1456 for(
unsigned int i = 0; i < well_container_.size(); i++){
1457 auto& well = well_container_[i];
1459 auto derived_std =
dynamic_cast<StandardWell<TypeTag>*
>(well.get());
1461 derived_std->linSys().extract(derived_std->numStaticWellEq, wellContribs);
1463 auto derived_ms =
dynamic_cast<MultisegmentWell<TypeTag>*
>(well.get());
1465 derived_ms->linSys().extract(wellContribs);
1467 OpmLog::warning(
"Warning unknown type of well");
1474 template<
typename TypeTag>
1479 for (
const auto& well: well_container_ ) {
1480 well->addWellContributions(jacobian);
1484 template<
typename TypeTag>
1489 const bool use_well_weights)
const
1491 int nw = this->numLocalWellsEnd();
1492 int rdofs = local_num_cells_;
1493 for (
int i = 0; i < nw; i++ ) {
1494 int wdof = rdofs + i;
1495 jacobian[wdof][wdof] = 1.0;
1498 for (
const auto& well : well_container_) {
1499 well->addWellPressureEquations(jacobian,
1507 template <
typename TypeTag>
1510 const std::vector<typename SparseMatrixAdapter::MatrixBlock*>& diagMatAddress)
const
1515 for (
const auto& well : well_container_) {
1516 if (!well->isOperableAndSolvable() && !well->wellIsStopped()) {
1519 const auto& cells = well->cells();
1520 const auto& rates = well->connectionRates();
1521 for (
unsigned perfIdx = 0; perfIdx < rates.size(); ++perfIdx) {
1522 unsigned cellIdx = cells[perfIdx];
1523 auto rate = rates[perfIdx];
1526 using MatrixBlockType =
typename SparseMatrixAdapter::MatrixBlock;
1527 MatrixBlockType bMat(0.0);
1528 simulator_.model().linearizer().setResAndJacobi(res, bMat, rate);
1529 residual[cellIdx] += res;
1530 *diagMatAddress[cellIdx] += bMat;
1536 template<
typename TypeTag>
1541 int nw = this->numLocalWellsEnd();
1542 int rdofs = local_num_cells_;
1543 for (
int i = 0; i < nw; ++i) {
1544 int wdof = rdofs + i;
1545 jacobian.entry(wdof,wdof) = 1.0;
1547 const auto wellconnections = this->getMaxWellConnections();
1548 for (
int i = 0; i < nw; ++i) {
1549 const auto& perfcells = wellconnections[i];
1550 for (
int perfcell : perfcells) {
1551 int wdof = rdofs + i;
1552 jacobian.entry(wdof, perfcell) = 0.0;
1553 jacobian.entry(perfcell, wdof) = 0.0;
1559 template<
typename TypeTag>
1564 auto loggerGuard = this->groupStateHelper().pushLogger();
1567 for (
const auto& well : well_container_) {
1568 const auto& cells = well->cells();
1569 x_local_.resize(cells.size());
1571 for (
size_t i = 0; i < cells.size(); ++i) {
1572 x_local_[i] = x[cells[i]];
1574 well->recoverWellSolutionAndUpdateWellState(simulator_, x_local_,
1575 this->groupStateHelper(), this->wellState());
1579 simulator_.vanguard().grid().comm());
1583 template<
typename TypeTag>
1589 OPM_THROW(std::logic_error,
"Attempt to call NLDD method without a NLDD solver");
1592 return nldd_->recoverWellSolutionAndUpdateWellState(x, domainIdx);
1596 template<
typename TypeTag>
1599 getWellConvergence(
const std::vector<Scalar>& B_avg,
bool checkWellGroupControlsAndNetwork)
const
1603 const auto& iterCtx = simulator_.problem().iterationContext();
1604 const bool relaxTolerance = iterCtx.shouldRelax(param_.strict_outer_iter_wells_ + 1);
1606 auto logger_guard = this->groupStateHelper().pushLogger();
1607 for (
const auto& well : well_container_) {
1608 if (well->isOperableAndSolvable() || well->wellIsStopped()) {
1609 local_report += well->getWellConvergence(
1610 this->groupStateHelper(), B_avg,
1615 report.
setWellFailed({CR::WellFailure::Type::Unsolvable, CR::Severity::Normal, -1, well->name()});
1616 local_report += report;
1624 if (checkWellGroupControlsAndNetwork) {
1630 if (this->terminal_output_) {
1634 OpmLog::debug(
"NaN residual found with phase " +
std::to_string(f.phase()) +
" for well " + f.wellName());
1636 OpmLog::debug(
"Too large residual found with phase " +
std::to_string(f.phase()) +
" for well " + f.wellName());
1647 template<
typename TypeTag>
1653 for (
auto& well : well_container_) {
1654 well->calculateExplicitQuantities(simulator_, this->groupStateHelper());
1662 template<
typename TypeTag>
1668 if (!this->wellsActive()) {
1671 const int episodeIdx = simulator_.episodeIndex();
1672 const auto& comm = simulator_.vanguard().grid().comm();
1674 bool changed_well_group =
false;
1675 const Group& fieldGroup = this->schedule().getGroup(
"FIELD", episodeIdx);
1678 const std::size_t max_iter = param_.well_group_constraints_max_iterations_;
1679 while(!changed_well_group && iter < max_iter) {
1680 changed_well_group = updateGroupControls(fieldGroup, deferred_logger, episodeIdx);
1683 bool changed_well_to_group =
false;
1685 OPM_TIMEBLOCK(UpdateWellControls);
1689 for (
const auto& well : well_container_) {
1692 simulator_, mode, this->groupStateHelper(), this->wellState()
1695 changed_well_to_group = changed_well || changed_well_to_group;
1699 simulator_.gridView().comm());
1702 changed_well_to_group = comm.sum(
static_cast<int>(changed_well_to_group));
1703 if (changed_well_to_group) {
1704 updateAndCommunicate(episodeIdx);
1705 changed_well_group =
true;
1709 bool changed_well_individual =
false;
1714 for (
const auto& well : well_container_) {
1717 simulator_, mode, this->groupStateHelper(), this->wellState()
1720 changed_well_individual = changed_well || changed_well_individual;
1724 simulator_.gridView().comm());
1727 changed_well_individual = comm.sum(
static_cast<int>(changed_well_individual));
1728 if (changed_well_individual) {
1729 updateAndCommunicate(episodeIdx);
1730 changed_well_group =
true;
1736 this->updateWsolvent(fieldGroup, episodeIdx, this->nupcolWellState());
1738 return changed_well_group;
1742 template<
typename TypeTag>
1747 const auto& iterCtx = simulator_.problem().iterationContext();
1748 this->updateAndCommunicateGroupData(reportStepIdx,
1750 param_.nupcol_group_rate_tolerance_,
1757 for (
const auto& well : well_container_) {
1759 const auto& ws = this->wellState().well(well->indexOfWell());
1760 if (ws.production_cmode == Well::ProducerCMode::GRUP ||
1761 ws.injection_cmode == Well::InjectorCMode::GRUP)
1763 well->updateWellStateWithTarget(
1764 simulator_, this->groupStateHelper(), this->wellState()
1769 simulator_.gridView().comm())
1770 this->updateAndCommunicateGroupData(reportStepIdx,
1772 param_.nupcol_group_rate_tolerance_,
1776 template<
typename TypeTag>
1781 const int reportStepIdx)
1784 const auto& iterCtx = simulator_.problem().iterationContext();
1785 bool changed =
false;
1787 const int nupcol = this->schedule()[reportStepIdx].nupcol();
1788 const int max_number_of_group_switches = param_.max_number_of_group_switches_;
1789 const bool update_group_switching_log = !iterCtx.withinNupcol(nupcol);
1790 const bool changed_hc = this->checkGroupHigherConstraints(group, deferred_logger, reportStepIdx, max_number_of_group_switches, update_group_switching_log);
1793 updateAndCommunicate(reportStepIdx);
1796 bool changed_individual =
1798 updateGroupIndividualControl(group,
1800 max_number_of_group_switches,
1801 update_group_switching_log,
1802 this->switched_inj_groups_,
1803 this->switched_prod_groups_,
1804 this->closed_offending_wells_,
1809 if (changed_individual) {
1811 updateAndCommunicate(reportStepIdx);
1814 for (
const std::string& groupName : group.groups()) {
1815 bool changed_this = updateGroupControls(this->schedule().getGroup(groupName, reportStepIdx), deferred_logger, reportStepIdx);
1816 changed = changed || changed_this;
1821 template<
typename TypeTag>
1827 auto logger_guard = this->groupStateHelper().pushLogger();
1828 auto& local_deferredLogger = this->groupStateHelper().deferredLogger();
1829 for (
const auto& well : well_container_) {
1830 const auto& wname = well->name();
1831 const auto wasClosed = wellTestState.well_is_closed(wname);
1832 well->checkWellOperability(simulator_,
1834 this->groupStateHelper());
1835 const bool under_zero_target =
1836 well->wellUnderZeroGroupRateTarget(this->groupStateHelper());
1837 well->updateWellTestState(this->wellState().well(wname),
1842 local_deferredLogger);
1844 if (!wasClosed && wellTestState.well_is_closed(wname)) {
1845 this->closed_this_step_.insert(wname);
1848 const WellEconProductionLimits& econ_production_limits = well->wellEcl().getEconLimits();
1849 if (econ_production_limits.validFollowonWell()) {
1850 const auto episode_idx = simulator_.episodeIndex();
1851 const auto follow_on_well = econ_production_limits.followonWell();
1852 if (!this->schedule().hasWell(follow_on_well, episode_idx)) {
1853 const auto msg = fmt::format(
"Well {} was closed. But the given follow on well {} does not exist."
1854 "The simulator continues without opening a follow on well.",
1855 wname, follow_on_well);
1856 local_deferredLogger.warning(msg);
1858 auto& ws = this->wellState().well(follow_on_well);
1859 const bool success = ws.updateStatus(WellStatus::OPEN);
1861 const auto msg = fmt::format(
"Well {} was closed. The follow on well {} opens instead.", wname, follow_on_well);
1862 local_deferredLogger.info(msg);
1864 const auto msg = fmt::format(
"Well {} was closed. The follow on well {} is already open.", wname, follow_on_well);
1865 local_deferredLogger.warning(msg);
1872 for (
const auto& [group_name, to] : this->closed_offending_wells_) {
1873 if (this->hasOpenLocalWell(to.second) &&
1874 !this->wasDynamicallyShutThisTimeStep(to.second))
1876 wellTestState.close_well(to.second,
1877 WellTestConfig::Reason::GROUP,
1879 this->updateClosedWellsThisStep(to.second);
1880 const std::string msg =
1881 fmt::format(
"Procedure on exceeding {} limit is WELL for group {}. "
1887 local_deferredLogger.info(msg);
1893 template<
typename TypeTag>
1897 std::string& exc_msg,
1901 const int np = this->numPhases();
1902 std::vector<Scalar> potentials;
1903 const auto& well = well_container_[widx];
1904 std::string cur_exc_msg;
1907 well->computeWellPotentials(simulator_, well_state_copy, this->groupStateHelper(), potentials);
1912 exc_msg += fmt::format(
"\nFor well {}: {}", well->name(), cur_exc_msg);
1914 exc_type = std::max(exc_type, cur_exc_type);
1918 auto& ws = this->wellState().well(well->indexOfWell());
1919 for (
int p = 0; p < np; ++p) {
1921 ws.well_potentials[p] = std::max(
Scalar{0.0}, potentials[p]);
1927 template <
typename TypeTag>
1932 for (
const auto& wellPtr : this->well_container_) {
1933 this->calculateProductivityIndexValues(wellPtr.get(), deferred_logger);
1941 template <
typename TypeTag>
1952 for (
const auto& shutWell : this->local_shut_wells_) {
1953 if (!this->wells_ecl_[shutWell].hasConnections()) {
1958 auto wellPtr = this->
template createTypedWellPointer
1961 wellPtr->
init(this->depth_, this->gravity_, this->B_avg_,
true);
1963 this->calculateProductivityIndexValues(wellPtr.get(), deferred_logger);
1971 template <
typename TypeTag>
1985 template<
typename TypeTag>
1991 const auto episodeIdx = simulator_.episodeIndex();
1992 this->network_.updateActiveState(episodeIdx);
1996 const bool do_prestep_network_rebalance =
1997 param_.pre_solve_network_ && this->network_.needPreStepRebalance(episodeIdx);
1999 for (
const auto& well : well_container_) {
2000 auto& events = this->wellState().well(well->indexOfWell()).events;
2002 well->updateWellStateWithTarget(
2003 simulator_, this->groupStateHelper(), this->wellState()
2005 well->updatePrimaryVariables(this->groupStateHelper());
2011 if (events.hasEvent(ScheduleEvents::REQUEST_OPEN_WELL)) {
2012 events.clearEvent(ScheduleEvents::REQUEST_OPEN_WELL);
2015 if (param_.solve_welleq_initially_ && well->isOperableAndSolvable()) {
2017 well->solveWellEquation(
2018 simulator_, this->groupStateHelper(), this->wellState()
2020 }
catch (
const std::exception& e) {
2021 const std::string msg =
"Compute initial well solution for " + well->name() +
" initially failed. Continue with the previous rates";
2022 deferred_logger.
warning(
"WELL_INITIAL_SOLVE_FAILED", msg);
2027 well->resetWellOperability();
2029 updatePrimaryVariables();
2032 if (do_prestep_network_rebalance) {
2033 network_.doPreStepRebalance(deferred_logger);
2037 template<
typename TypeTag>
2042 std::vector< Scalar > B_avg(numConservationQuantities(),
Scalar() );
2043 const auto& grid = simulator_.vanguard().grid();
2044 const auto& gridView = grid.leafGridView();
2048 for (
const auto& elem : elements(gridView, Dune::Partitions::interior)) {
2049 elemCtx.updatePrimaryStencil(elem);
2050 elemCtx.updatePrimaryIntensiveQuantities(0);
2052 const auto& intQuants = elemCtx.intensiveQuantities(0, 0);
2053 const auto& fs = intQuants.fluidState();
2055 for (
unsigned phaseIdx = 0; phaseIdx < FluidSystem::numPhases; ++phaseIdx)
2057 if (!FluidSystem::phaseIsActive(phaseIdx)) {
2061 const unsigned compIdx = FluidSystem::canonicalToActiveCompIdx(FluidSystem::solventComponentIndex(phaseIdx));
2062 auto& B = B_avg[ compIdx ];
2064 B += 1 / fs.invB(phaseIdx).value();
2066 if constexpr (has_solvent_) {
2067 auto& B = B_avg[solventSaturationIdx];
2068 B += 1 / intQuants.solventInverseFormationVolumeFactor().value();
2074 grid.comm().sum(B_avg.data(), B_avg.size());
2075 B_avg_.resize(B_avg.size());
2076 std::ranges::transform(B_avg, B_avg_.begin(),
2077 [gcells = global_num_cells_](
const auto bval)
2078 { return bval / gcells; });
2085 template<
typename TypeTag>
2090 for (
const auto& well : well_container_) {
2091 well->updatePrimaryVariables(this->groupStateHelper());
2095 template<
typename TypeTag>
2099 const auto& grid = simulator_.vanguard().grid();
2100 const auto& eclProblem = simulator_.problem();
2101 const unsigned numCells = grid.size(0);
2103 this->pvt_region_idx_.resize(numCells);
2104 for (
unsigned cellIdx = 0; cellIdx < numCells; ++cellIdx) {
2105 this->pvt_region_idx_[cellIdx] =
2106 eclProblem.pvtRegionIndex(cellIdx);
2111 template<
typename TypeTag>
2124 return this->numPhases() + has_solvent_;
2127 template<
typename TypeTag>
2131 const auto& eclProblem = simulator_.problem();
2132 depth_.resize(local_num_cells_);
2133 for (
unsigned cellIdx = 0; cellIdx < local_num_cells_; ++cellIdx) {
2134 depth_[cellIdx] = eclProblem.dofCenterDepth(cellIdx);
2138 template<
typename TypeTag>
2141 getWell(
const std::string& well_name)
const
2145 std::ranges::find_if(well_container_,
2147 {
return elem->name() == well_name; });
2149 assert(well != well_container_.end());
2154 template <
typename TypeTag>
2159 return std::max(this->simulator_.episodeIndex(), 0);
2166 template<
typename TypeTag>
2171 const std::vector<Scalar>& production_rates,
2172 std::vector<Scalar>& resv_coeff)
const
2174 rateConverter_->calcCoeff(fipnum, pvtreg, production_rates, resv_coeff);
2177 template<
typename TypeTag>
2182 std::vector<Scalar>& resv_coeff)
const
2184 rateConverter_->calcInjCoeff(fipnum, pvtreg, resv_coeff);
2188 template <
typename TypeTag>
2193 if constexpr (energyModuleType_ == EnergyModules::FullyImplicitThermal) {
2194 const int np = this->numPhases();
2195 const int nw = this->numLocalWells();
2196 for (
auto wellID = 0*nw; wellID < nw; ++wellID) {
2197 const Well& well = this->wells_ecl_[wellID];
2198 auto& ws = this->wellState().well(wellID);
2199 if (well.isInjector()) {
2200 if (ws.status != WellStatus::STOP) {
2201 this->wellState().well(wellID).temperature = well.inj_temperature();
2205 std::array<Scalar,2> weighted{0.0,0.0};
2206 auto& [weighted_temperature, total_weight] = weighted;
2207 const auto& well_info = this->local_parallel_well_info_[wellID].get();
2208 using int_type =
decltype(this->well_perf_data_[wellID].size());
2209 for (int_type perf = 0, end_perf = this->well_perf_data_[wellID].size(); perf < end_perf; ++perf) {
2210 const int cell_idx = this->well_perf_data_[wellID][perf].cell_index;
2211 const auto& intQuants = simulator_.model().intensiveQuantities(cell_idx, 0);
2212 const auto& fs = intQuants.fluidState();
2213 Scalar weight_factor = computeTemperatureWeightFactor(perf, np, fs, ws);
2214 total_weight += weight_factor;
2215 weighted_temperature += weight_factor * fs.temperature(0).value();
2217 well_info.communication().sum(weighted.data(), 2);
2218 this->wellState().well(wellID).temperature = weighted_temperature / total_weight;
2224 template <
typename TypeTag>
2228 const auto reportStepIdx =
static_cast<unsigned int>(this->reportStepIndex());
2229 const auto& trMod = this->simulator_.problem().tracerModel();
2235 this->assignMswTracerRates(wsrpt, trMod.getMswTracerRates(), reportStepIdx);
2238 template <
typename TypeTag>
2239 void BlackoilWellModel<TypeTag>::
2240 assignWellSpeciesRates(data::Wells& wsrpt)
const
2242 const auto reportStepIdx =
static_cast<unsigned int>(this->reportStepIndex());
2243 const auto& geochemMod = this->simulator_.problem().geochemistryModel();
2247 this->assignMswTracerRates(wsrpt, geochemMod.getMswSpeciesRates(), reportStepIdx);
#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:202
#define OPM_DEFLOG_THROW(Exception, message, deferred_logger)
Definition: DeferredLoggingErrorHelpers.hpp:45
#define OPM_END_PARALLEL_TRY_CATCH(prefix, comm)
Catch exception and throw in a parallel try-catch clause.
Definition: DeferredLoggingErrorHelpers.hpp:192
#define OPM_PARALLEL_CATCH_CLAUSE(obptc_exc_type, obptc_exc_msg)
Inserts catch classes for the parallel try-catch.
Definition: DeferredLoggingErrorHelpers.hpp:166
#define OPM_BEGIN_PARALLEL_TRY_CATCH()
Macro to setup the try of a parallel try-catch.
Definition: DeferredLoggingErrorHelpers.hpp:158
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:111
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:97
const Parallel::Communication & comm() const
Definition: BlackoilWellModelGeneric.hpp:224
BlackoilWellModelWBP< GetPropType< TypeTag, Properties::Scalar >, GetPropType< TypeTag, Properties::FluidSystem >::IndexTraitsType > wbp_
Definition: BlackoilWellModelGeneric.hpp:518
std::vector< ParallelWellInfo< GetPropType< TypeTag, Properties::Scalar > > > parallel_well_info_
Definition: BlackoilWellModelGeneric.hpp:545
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:98
void initializeGroupStructure(const int reportStepIdx)
Definition: BlackoilWellModel_impl.hpp:296
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:2169
void prepareTimeStep(DeferredLogger &deferred_logger)
Definition: BlackoilWellModel_impl.hpp:1988
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:1302
WellInterfacePtr createWellPointer(const int wellID, const int report_step) const
Definition: BlackoilWellModel_impl.hpp:1098
void prepareWellsBeforeAssembling(const double dt)
Definition: BlackoilWellModel_impl.hpp:1378
void init()
Definition: BlackoilWellModel_impl.hpp:165
const Simulator & simulator() const
Definition: BlackoilWellModel.hpp:371
std::vector< Scalar > depth_
Definition: BlackoilWellModel.hpp:517
std::size_t global_num_cells_
Definition: BlackoilWellModel.hpp:513
GetPropType< TypeTag, Properties::Scalar > Scalar
Definition: BlackoilWellModel.hpp:107
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:2141
GetPropType< TypeTag, Properties::FluidSystem > FluidSystem
Definition: BlackoilWellModel.hpp:103
Dune::FieldVector< Scalar, numEq > VectorBlockType
Definition: BlackoilWellModel.hpp:130
GetPropType< TypeTag, Properties::ElementContext > ElementContext
Definition: BlackoilWellModel.hpp:104
GetPropType< TypeTag, Properties::Grid > Grid
Definition: BlackoilWellModel.hpp:101
int numConservationQuantities() const
Definition: BlackoilWellModel_impl.hpp:2113
bool updateWellControls(DeferredLogger &deferred_logger)
Definition: BlackoilWellModel_impl.hpp:1665
int reportStepIndex() const
Definition: BlackoilWellModel_impl.hpp:2157
void calculateProductivityIndexValues(DeferredLogger &deferred_logger) override
Definition: BlackoilWellModel_impl.hpp:1930
void extractLegacyDepth_()
Definition: BlackoilWellModel_impl.hpp:2129
void extractLegacyCellPvtRegionIndex_()
Definition: BlackoilWellModel_impl.hpp:2097
void recoverWellSolutionAndUpdateWellStateDomain(const BVector &x, const int domainIdx)
Definition: BlackoilWellModel_impl.hpp:1586
void updateAverageFormationFactor()
Definition: BlackoilWellModel_impl.hpp:2040
GetPropType< TypeTag, Properties::Simulator > Simulator
Definition: BlackoilWellModel.hpp:106
void initializeWellState(const int timeStepIdx)
Definition: BlackoilWellModel_impl.hpp:846
const Grid & grid() const
Definition: BlackoilWellModel.hpp:368
void updatePrimaryVariables()
Definition: BlackoilWellModel_impl.hpp:2088
void computeWellTemperature()
Definition: BlackoilWellModel_impl.hpp:2191
void addWellPressureEquations(PressureMatrix &jacobian, const BVector &weights, const bool use_well_weights) const
Definition: BlackoilWellModel_impl.hpp:1487
const SimulatorReportSingle & lastReport() const
Definition: BlackoilWellModel_impl.hpp:725
bool updateWellControlsAndNetwork(const bool mandatory_network_balance, const double dt, DeferredLogger &local_deferredLogger)
Definition: BlackoilWellModel_impl.hpp:1243
void addWellContributions(SparseMatrixAdapter &jacobian) const
Definition: BlackoilWellModel_impl.hpp:1477
void assembleWellEq(const double dt)
Definition: BlackoilWellModel_impl.hpp:1366
WellInterfacePtr createWellForWellTest(const std::string &well_name, const int report_step, DeferredLogger &deferred_logger) const
Definition: BlackoilWellModel_impl.hpp:1149
void calculateExplicitQuantities() const
Definition: BlackoilWellModel_impl.hpp:1650
void updateAndCommunicate(const int reportStepIdx)
Definition: BlackoilWellModel_impl.hpp:1745
Dune::BCRSMatrix< Opm::MatrixBlock< Scalar, 1, 1 > > PressureMatrix
Definition: BlackoilWellModel.hpp:290
void computeTotalRatesForDof(RateVector &rate, unsigned globalIdx) const
Definition: BlackoilWellModel_impl.hpp:809
void beginTimeStep()
Definition: BlackoilWellModel_impl.hpp:328
GetPropType< TypeTag, Properties::RateVector > RateVector
Definition: BlackoilWellModel.hpp:108
bool updateGroupControls(const Group &group, DeferredLogger &deferred_logger, const int reportStepIdx)
Definition: BlackoilWellModel_impl.hpp:1779
void calcInjResvCoeff(const int fipnum, const int pvtreg, std::vector< Scalar > &resv_coeff) const override
Definition: BlackoilWellModel_impl.hpp:2180
void initializeLocalWellStructure(const int reportStepIdx, const bool enableWellPIScaling)
Definition: BlackoilWellModel_impl.hpp:250
Dune::BlockVector< VectorBlockType > BVector
Definition: BlackoilWellModel.hpp:131
BlackoilWellModel(Simulator &simulator)
Definition: BlackoilWellModel_impl.hpp:78
void wellTesting(const int timeStepIdx, const double simulationTime, DeferredLogger &deferred_logger)
Definition: BlackoilWellModel_impl.hpp:648
ConvergenceReport getWellConvergence(const std::vector< Scalar > &B_avg, const bool checkWellGroupControlsAndNetwork=false) const
Definition: BlackoilWellModel_impl.hpp:1599
typename FluidSystem::IndexTraitsType IndexTraits
Definition: BlackoilWellModel.hpp:114
void updateCellRatesForDomain(int domainIndex, const std::map< std::string, int > &well_domain_map)
Definition: BlackoilWellModel_impl.hpp:1424
void assembleWellEqWithoutIteration(const double dt)
Definition: BlackoilWellModel_impl.hpp:1392
void updateCellRates()
Definition: BlackoilWellModel_impl.hpp:1412
void assemble(const double dt)
Definition: BlackoilWellModel_impl.hpp:1174
std::size_t local_num_cells_
Definition: BlackoilWellModel.hpp:515
bool alternative_well_rate_init_
Definition: BlackoilWellModel.hpp:518
void timeStepSucceeded(const double simulationTime, const double dt)
Definition: BlackoilWellModel_impl.hpp:735
std::unique_ptr< WellType > createTypedWellPointer(const int wellID, const int time_step) const
Definition: BlackoilWellModel_impl.hpp:1118
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:1895
Simulator & simulator_
Definition: BlackoilWellModel.hpp:487
void createWellContainer(const int report_step) override
Definition: BlackoilWellModel_impl.hpp:889
std::unique_ptr< WellInterface< TypeTag > > WellInterfacePtr
Definition: BlackoilWellModel.hpp:187
void updateWellTestState(const double simulationTime, WellTestState &wellTestState)
upate the wellTestState related to economic limits
Definition: BlackoilWellModel_impl.hpp:1824
void addReservoirSourceTerms(GlobalEqVector &residual, const std::vector< typename SparseMatrixAdapter::MatrixBlock * > &diagMatAddress) const
Definition: BlackoilWellModel_impl.hpp:1509
int compressedIndexForInterior(int cartesian_cell_idx) const override
get compressed index for interior cells (-1, otherwise
Definition: BlackoilWellModel.hpp:343
void recoverWellSolutionAndUpdateWellState(const BVector &x)
Definition: BlackoilWellModel_impl.hpp:1562
void addWellPressureEquationsStruct(PressureMatrix &jacobian) const
Definition: BlackoilWellModel_impl.hpp:1539
void calculateProductivityIndexValuesShutWells(const int reportStepIdx, DeferredLogger &deferred_logger) override
Definition: BlackoilWellModel_impl.hpp:1944
void endReportStep()
Definition: BlackoilWellModel_impl.hpp:708
void initializeSources(typename ParallelWBPCalculation< Scalar >::GlobalToLocal index, typename ParallelWBPCalculation< Scalar >::Evaluator eval)
Definition: ConvergenceReport.hpp:38
void setWellFailed(const WellFailure &wf)
Definition: ConvergenceReport.hpp:272
void setWellGroupTargetsViolated(const bool wellGroupTargetsViolated)
Definition: ConvergenceReport.hpp:290
const std::vector< WellFailure > & wellFailures() const
Definition: ConvergenceReport.hpp:380
void setNetworkNotYetBalancedForceAnotherNewtonIteration(const bool network_needs_more_balancing_force_another_newton_iteration)
Definition: ConvergenceReport.hpp:295
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
Guard for managing DeferredLogger lifecycle in ReservoirCoupling.
Definition: ReservoirCoupling.hpp:88
Definition: StandardWell.hpp:60
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:77
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:190
Definition: WellState.hpp:66
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)
A struct for returning timing data from a simulator to its caller.
Definition: SimulatorReport.hpp:34