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
74#include <fmt/format.h>
77 template<
typename TypeTag>
84 simulator.vanguard().summaryState(),
85 simulator.vanguard().eclState(),
87 simulator.gridView().comm())
88 , simulator_(simulator)
89 , guide_rate_handler_{
91 simulator.vanguard().schedule(),
92 simulator.vanguard().summaryState(),
93 simulator.vanguard().grid().comm()
95 , gaslift_(this->terminal_output_)
104 auto& parallel_wells =
simulator.vanguard().parallelWells();
107 for(
const auto& name_bool : parallel_wells) {
113 Parameters::Get<Parameters::AlternativeWellRateInit>();
115 using SourceDataSpan =
116 typename PAvgDynamicSourceData<Scalar>::template SourceDataSpan<Scalar>;
119 [
this](
const std::size_t globalIndex)
121 [
this](
const int localCell, SourceDataSpan sourceTerms)
123 using Item =
typename SourceDataSpan::Item;
125 const auto* intQuants = this->
simulator_.model()
126 .cachedIntensiveQuantities(localCell, 0);
127 const auto& fs = intQuants->fluidState();
130 .set(Item::PoreVol, intQuants->porosity().value() *
131 this->
simulator_.model().dofTotalVolume(localCell))
132 .set(Item::Depth, this->
depth_[localCell]);
134 constexpr auto io = FluidSystem::oilPhaseIdx;
135 constexpr auto ig = FluidSystem::gasPhaseIdx;
136 constexpr auto iw = FluidSystem::waterPhaseIdx;
139 const auto haveOil = FluidSystem::phaseIsActive(io);
140 const auto haveGas = FluidSystem::phaseIsActive(ig);
141 const auto haveWat = FluidSystem::phaseIsActive(iw);
143 auto weightedPhaseDensity = [&fs](
const auto ip)
145 return fs.saturation(ip).value() * fs.density(ip).value();
148 if (haveOil) { sourceTerms.set(Item::Pressure, fs.pressure(io).value()); }
149 else if (haveGas) { sourceTerms.set(Item::Pressure, fs.pressure(ig).value()); }
150 else { sourceTerms.set(Item::Pressure, fs.pressure(iw).value()); }
154 if (haveOil) { rho += weightedPhaseDensity(io); }
155 if (haveGas) { rho += weightedPhaseDensity(ig); }
156 if (haveWat) { rho += weightedPhaseDensity(iw); }
158 sourceTerms.set(Item::MixtureDensity, rho);
163 template<
typename TypeTag>
168 extractLegacyCellPvtRegionIndex_();
169 extractLegacyDepth_();
171 gravity_ = simulator_.problem().gravity()[2];
173 this->initial_step_ =
true;
176 simulator_.model().addAuxiliaryModule(
this);
178 is_cell_perforated_.resize(local_num_cells_,
false);
182 template<
typename TypeTag>
187 const uint64_t effective_events_mask = ScheduleEvents::WELL_STATUS_CHANGE
188 + ScheduleEvents::NEW_WELL;
189 const auto& events = this->schedule()[reportStepIdx].wellgroup_events();
190 for (
auto& wellPtr : this->well_container_) {
191 const bool well_opened_this_step = this->report_step_starts_ &&
192 events.hasEvent(wellPtr->name(),
193 effective_events_mask);
194 wellPtr->init(this->depth_, this->gravity_,
195 this->B_avg_, well_opened_this_step);
199 template<
typename TypeTag>
204 this->groupStateHelper().setReportStep(timeStepIdx);
205 this->report_step_starts_ =
true;
206 this->report_step_start_events_ = this->schedule()[timeStepIdx].wellgroup_events();
208 this->rateConverter_ = std::make_unique<RateConverterType>
209 (std::vector<int>(this->local_num_cells_, 0));
213 const auto enableWellPIScaling =
true;
214 this->initializeLocalWellStructure(timeStepIdx, enableWellPIScaling);
217 this->initializeGroupStructure(timeStepIdx);
219 const auto& comm = this->simulator_.vanguard().grid().comm();
225 this->rateConverter_->template defineState<ElementContext>(this->simulator_);
229 const auto& sched_state = this->schedule()[timeStepIdx];
231 this->vfp_properties_ = std::make_unique<VFPProperties<Scalar, IndexTraits>>
232 (sched_state.vfpinj(), sched_state.vfpprod(), this->wellState());
239 this->commitWGState();
241 this->wellStructureChangedDynamically_ =
false;
248 template <
typename TypeTag>
252 const bool enableWellPIScaling)
254 auto logger_guard = this->groupStateHelper().pushLogger();
255 auto& local_deferredLogger = this->groupStateHelper().deferredLogger();
257 const auto& comm = this->simulator_.vanguard().grid().comm();
260 this->wells_ecl_ = this->getLocalWells(reportStepIdx);
261 this->local_parallel_well_info_ =
262 this->createLocalParallelWellInfo(this->wells_ecl_);
269 this->initializeWellPerfData();
270 this->initializeWellState(reportStepIdx);
271 this->wbp_.initializeWBPCalculationService();
273 if (this->param_.use_multisegment_well_ && this->anyMSWellOpenLocal()) {
274 this->wellState().initWellStateMSWell(this->wells_ecl_, &this->prevWellState());
277 this->initializeWellProdIndCalculators();
279 if (enableWellPIScaling && this->schedule()[reportStepIdx].events()
280 .hasEvent(ScheduleEvents::Events::WELL_PRODUCTIVITY_INDEX))
282 this->runWellPIScaling(reportStepIdx, local_deferredLogger);
286 "Failed to initialize local well structure: ",
287 this->terminal_output_, comm)
294 template <
typename TypeTag>
299 const auto& comm = this->simulator_.vanguard().grid().comm();
303 const auto& fieldGroup =
304 this->schedule().getGroup(
"FIELD", reportStepIdx);
306 this->groupStateHelper().setCmodeGroup(fieldGroup);
310 if (this->schedule()[reportStepIdx].has_gpmaint()) {
311 this->groupStateHelper().setRegionAveragePressureCalculator(
313 this->eclState_.fieldProps(),
314 this->regionalAveragePressureCalculator_
326 template<
typename TypeTag>
331 OPM_TIMEBLOCK(beginTimeStep);
333 this->updateAverageFormationFactor();
335 auto logger_guard = this->groupStateHelper().pushLogger();
336 auto& local_deferredLogger = this->groupStateHelper().deferredLogger();
338#ifdef RESERVOIR_COUPLING_ENABLED
339 auto rescoup_logger_guard = this->setupRescoupScopedLogger(local_deferredLogger);
342 this->switched_prod_groups_.clear();
343 this->switched_inj_groups_.clear();
345 if (this->wellStructureChangedDynamically_) {
350 const auto reportStepIdx =
351 this->simulator_.episodeIndex();
355 const auto enableWellPIScaling =
false;
357 this->initializeLocalWellStructure(reportStepIdx, enableWellPIScaling);
358 this->initializeGroupStructure(reportStepIdx);
360 this->commitWGState();
366 this->wellStructureChangedDynamically_ =
false;
369 this->resetWGState();
370 const int reportStepIdx = simulator_.episodeIndex();
372 this->wellState().updateWellsDefaultALQ(this->schedule(), reportStepIdx, this->summaryState());
373 this->wellState().gliftTimeStepInit();
375 const double simulationTime = simulator_.time();
376 const auto& iterCtx = simulator_.problem().iterationContext();
380 wellTesting(reportStepIdx, simulationTime, local_deferredLogger);
383 createWellContainer(reportStepIdx);
385#ifdef RESERVOIR_COUPLING_ENABLED
386 if (this->isReservoirCouplingMaster()) {
387 if (this->reservoirCouplingMaster().isFirstSubstepOfSyncTimestep()) {
388 this->receiveSlaveGroupData();
395 this->updateAndCommunicateGroupData(reportStepIdx,
397 param_.nupcol_group_rate_tolerance_,
false);
400 const Grid& grid = simulator_.vanguard().grid();
401 this->wells_active_ = grid.comm().max(!this->well_container_.empty());
406 this->initWellContainer(reportStepIdx);
409 std::fill(is_cell_perforated_.begin(), is_cell_perforated_.end(),
false);
410 for (
auto& well : well_container_) {
411 well->updatePerforatedCell(is_cell_perforated_);
415 this->calculateEfficiencyFactors(reportStepIdx);
417 if constexpr (has_polymer_)
419 if (PolymerModule::hasPlyshlog() || getPropValue<TypeTag, Properties::EnablePolymerMW>() ) {
420 this->setRepRadiusPerfLength();
427 this->terminal_output_, simulator_.vanguard().grid().comm());
429 for (
auto& well : well_container_) {
430 well->setVFPProperties(this->vfp_properties_.get());
431 well->setGuideRate(&this->guideRate_);
434 this->updateFiltrationModelsPreStep(local_deferredLogger);
437 for (
auto& well : well_container_) {
438 well->closeCompletions(this->wellTestState());
444 if (alternative_well_rate_init_) {
449 for (
const auto& well : well_container_) {
450 if (well->isProducer() && !well->wellIsStopped()) {
451 well->initializeProducerWellState(simulator_, this->wellState(), local_deferredLogger);
456 for (
const auto& well : well_container_) {
457 if (well->isVFPActive(local_deferredLogger)){
458 well->setPrevSurfaceRates(this->wellState(), this->prevWellState());
462 this->updateWellPotentials(reportStepIdx,
464 simulator_.vanguard().summaryConfig(),
465 local_deferredLogger);
466 }
catch ( std::runtime_error& e ) {
467 const std::string msg =
"A zero well potential is returned for output purposes. ";
468 local_deferredLogger.warning(
"WELL_POTENTIAL_CALCULATION_FAILED", msg);
471 this->guide_rate_handler_.updateGuideRates(
472 reportStepIdx, simulationTime, this->wellState(), this->groupState()
474 bool slave_needs_well_solution =
false;
475#ifdef RESERVOIR_COUPLING_ENABLED
476 if (this->isReservoirCouplingSlave()) {
477 if (this->reservoirCouplingSlave().isFirstSubstepOfSyncTimestep()) {
478 this->sendSlaveGroupDataToMaster();
479 this->receiveGroupConstraintsFromMaster();
480 this->groupStateHelper().updateSlaveGroupCmodesFromMaster();
481 slave_needs_well_solution =
true;
488 if (this->schedule_[reportStepIdx].has_gpmaint()) {
489 for (
const auto& calculator : regionalAveragePressureCalculator_) {
490 calculator.second->template defineState<ElementContext>(simulator_);
492 const double dt = simulator_.timeStepSize();
493 const Group& fieldGroup = this->schedule().getGroup(
"FIELD", reportStepIdx);
495 this->groupStateHelper().updateGpMaintTargetForGroups(fieldGroup,
496 regionalAveragePressureCalculator_,
502 this->updateAndCommunicateGroupData(reportStepIdx,
504 param_.nupcol_group_rate_tolerance_,
508 for (
auto& well : well_container_) {
509 const uint64_t effective_events_mask = ScheduleEvents::WELL_STATUS_CHANGE
510 + ScheduleEvents::INJECTION_TYPE_CHANGED
511 + ScheduleEvents::WELL_SWITCHED_INJECTOR_PRODUCER
512 + ScheduleEvents::NEW_WELL;
514 const auto& events = this->schedule()[reportStepIdx].wellgroup_events();
515 const bool event = this->report_step_starts_ && events.hasEvent(well->name(), effective_events_mask);
516 const bool dyn_status_change = this->wellState().well(well->name()).status
517 != this->prevWellState().well(well->name()).status;
519 if (event || dyn_status_change || slave_needs_well_solution) {
521 well->scaleSegmentRatesAndPressure(this->wellState());
522 well->calculateExplicitQuantities(simulator_, this->groupStateHelper());
523 well->updateWellStateWithTarget(simulator_, this->groupStateHelper(), this->wellState());
524 well->updatePrimaryVariables(this->groupStateHelper());
525 well->solveWellEquation(
526 simulator_, this->groupStateHelper(), this->wellState()
528 }
catch (
const std::exception& e) {
529 const std::string msg =
"Compute initial well solution for new well " + well->name() +
" failed. Continue with zero initial rates";
530 local_deferredLogger.warning(
"WELL_INITIAL_SOLVE_FAILED", msg);
538#ifdef RESERVOIR_COUPLING_ENABLED
539 if (this->isReservoirCouplingSlave()) {
540 if (slave_needs_well_solution) {
541 this->updateAndCommunicateGroupData(reportStepIdx,
543 param_.nupcol_group_rate_tolerance_,
545 this->sendSlaveGroupDataToMaster();
550#ifdef RESERVOIR_COUPLING_ENABLED
551 if (this->isReservoirCouplingMaster()) {
552 if (this->reservoirCouplingMaster().isFirstSubstepOfSyncTimestep()) {
553 this->sendMasterGroupConstraintsToSlaves();
554 this->receiveSlaveGroupData();
560 const std::string msg =
"Compute initial well solution for new wells failed. Continue with zero initial rates";
561 local_deferredLogger.warning(
"WELL_INITIAL_SOLVE_FAILED", msg);
564 const auto& comm = simulator_.vanguard().grid().comm();
566 exc_type,
"beginTimeStep() failed: " + exc_msg, this->terminal_output_, comm);
570#ifdef RESERVOIR_COUPLING_ENABLED
580 template<
typename TypeTag>
581 std::optional<ReservoirCoupling::ScopedLoggerGuard>
584 if (this->isReservoirCouplingMaster()) {
586 this->reservoirCouplingMaster().logger(),
589 }
else if (this->isReservoirCouplingSlave()) {
590 return ReservoirCoupling::ScopedLoggerGuard{
591 this->reservoirCouplingSlave().logger(),
598 template<
typename TypeTag>
600 BlackoilWellModel<TypeTag>::
601 receiveSlaveGroupData()
603 assert(this->isReservoirCouplingMaster());
604 RescoupReceiveSlaveGroupData<Scalar, IndexTraits> slave_group_data_receiver{
605 this->groupStateHelper(),
607 slave_group_data_receiver.receiveSlaveGroupData();
610 template<
typename TypeTag>
612 BlackoilWellModel<TypeTag>::
613 sendSlaveGroupDataToMaster()
615 assert(this->isReservoirCouplingSlave());
616 RescoupSendSlaveGroupData<Scalar, IndexTraits> slave_group_data_sender{this->groupStateHelper()};
617 slave_group_data_sender.sendSlaveGroupDataToMaster();
620 template<
typename TypeTag>
622 BlackoilWellModel<TypeTag>::
623 sendMasterGroupConstraintsToSlaves()
626 RescoupConstraintsCalculator<Scalar, IndexTraits> constraints_calculator{
627 this->guide_rate_handler_,
628 this->groupStateHelper()
630 constraints_calculator.calculateMasterGroupConstraintsAndSendToSlaves();
633 template<
typename TypeTag>
635 BlackoilWellModel<TypeTag>::
636 receiveGroupConstraintsFromMaster()
638 RescoupReceiveGroupConstraints<Scalar, IndexTraits> constraint_receiver{
639 this->guide_rate_handler_,
640 this->groupStateHelper()
642 constraint_receiver.receiveGroupConstraintsFromMaster();
645 template<
typename TypeTag>
647 BlackoilWellModel<TypeTag>::
648 rescoupSyncSummaryData()
660 if (this->isReservoirCouplingMaster()) {
661 if (this->reservoirCouplingMaster().needsSlaveDataReceive()) {
662 this->receiveSlaveGroupData();
663 this->reservoirCouplingMaster().setNeedsSlaveDataReceive(
false);
666 if (this->isReservoirCouplingSlave()) {
667 if (this->reservoirCouplingSlave().isLastSubstepOfSyncTimestep()) {
668 this->sendSlaveGroupDataToMaster();
675 template<
typename TypeTag>
678 const double simulationTime,
681 for (
const std::string& well_name : this->getWellsForTesting(timeStepIdx, simulationTime)) {
682 const Well& wellEcl = this->schedule().getWell(well_name, timeStepIdx);
683 if (wellEcl.getStatus() == Well::Status::SHUT)
686 WellInterfacePtr well = createWellForWellTest(well_name, timeStepIdx, deferred_logger);
688 well->init(depth_, gravity_, B_avg_,
true);
690 Scalar well_efficiency_factor = wellEcl.getEfficiencyFactor() *
691 this->wellState().getGlobalEfficiencyScalingFactor(well_name);
692 this->groupStateHelper().accumulateGroupEfficiencyFactor(
693 this->schedule().getGroup(wellEcl.groupName(), timeStepIdx),
694 well_efficiency_factor
697 well->setWellEfficiencyFactor(well_efficiency_factor);
698 well->setVFPProperties(this->vfp_properties_.get());
699 well->setGuideRate(&this->guideRate_);
702 if (well->isProducer() && alternative_well_rate_init_) {
703 well->initializeProducerWellState(simulator_, this->wellState(), deferred_logger);
705 if (well->isVFPActive(deferred_logger)) {
706 well->setPrevSurfaceRates(this->wellState(), this->prevWellState());
709 const auto& network = this->schedule()[timeStepIdx].network();
710 if (network.active()) {
711 this->network_.initializeWell(*well);
715 GLiftEclWells ecl_well_map;
716 gaslift_.initGliftEclWellMap(well_container_, ecl_well_map);
717 well->wellTesting(simulator_,
719 this->groupStateHelper(),
721 this->wellTestState(),
723 this->well_open_times_);
724 }
catch (
const std::exception& e) {
725 const std::string msg =
726 fmt::format(fmt::runtime(
"Exception during testing of well: {}. The well will not open.\n"
727 "Exception message: {}"), wellEcl.name(), e.what());
728 deferred_logger.
warning(
"WELL_TESTING_FAILED", msg);
734 template<
typename TypeTag>
740 for (
auto&& pinfo : this->local_parallel_well_info_)
751 template<
typename TypeTag>
761 template<
typename TypeTag>
766 this->closed_this_step_.clear();
769 this->report_step_starts_ =
false;
770 const int reportStepIdx = simulator_.episodeIndex();
772 auto logger_guard = this->groupStateHelper().pushLogger();
773 auto& local_deferredLogger = this->groupStateHelper().deferredLogger();
774 for (
const auto& well : well_container_) {
775 if (getPropValue<TypeTag, Properties::EnablePolymerMW>() && well->isInjector()) {
776 well->updateWaterThroughput(dt, this->wellState());
780 for (
const auto& well : well_container_) {
781 well->updateConnectionTransmissibilityFactor(simulator_, this->wellState().well(well->indexOfWell()));
782 well->updateConnectionDFactor(simulator_, this->wellState().well(well->indexOfWell()));
785 if (Indices::waterEnabled) {
786 this->updateFiltrationModelsPostStep(dt, FluidSystem::waterPhaseIdx, local_deferredLogger);
790 this->updateInjMult(local_deferredLogger);
793 for (
const auto& well : well_container_) {
794 well->reportWellSwitching(this->wellState().well(well->indexOfWell()), local_deferredLogger);
797 if (this->terminal_output_) {
798 this->reportGroupSwitching(local_deferredLogger);
802 rateConverter_->template defineState<ElementContext>(simulator_);
806 this->updateWellPotentials(reportStepIdx,
808 simulator_.vanguard().summaryConfig(),
809 local_deferredLogger);
810 }
catch ( std::runtime_error& e ) {
811 const std::string msg =
"A zero well potential is returned for output purposes. ";
812 local_deferredLogger.warning(
"WELL_POTENTIAL_CALCULATION_FAILED", msg);
815 updateWellTestState(simulationTime, this->wellTestState());
818 const Group& fieldGroup = this->schedule_.getGroup(
"FIELD", reportStepIdx);
819 this->checkGEconLimits(fieldGroup, simulationTime,
820 simulator_.episodeIndex(), local_deferredLogger);
821 this->checkGconsaleLimits(fieldGroup, this->wellState(),
822 simulator_.episodeIndex(), local_deferredLogger);
824 this->calculateProductivityIndexValues(local_deferredLogger);
826 this->groupStateHelper().updateNONEProductionGroups();
828#ifdef RESERVOIR_COUPLING_ENABLED
829 this->rescoupSyncSummaryData();
831 this->commitWGState();
834 this->computeWellTemperature();
838 template<
typename TypeTag>
842 unsigned elemIdx)
const
846 if (!is_cell_perforated_[elemIdx] || cellRates_.count(elemIdx) == 0) {
850 rate = cellRates_.at(elemIdx);
854 template<
typename TypeTag>
855 template <
class Context>
859 const Context& context,
861 unsigned timeIdx)
const
864 int elemIdx = context.globalSpaceIndex(spaceIdx, timeIdx);
866 if (!is_cell_perforated_[elemIdx] || cellRates_.count(elemIdx) == 0) {
870 rate = cellRates_.at(elemIdx);
875 template<
typename TypeTag>
880 const auto pressIx = []()
882 if (Indices::oilEnabled) {
return FluidSystem::oilPhaseIdx; }
883 if (Indices::waterEnabled) {
return FluidSystem::waterPhaseIdx; }
885 return FluidSystem::gasPhaseIdx;
888 auto cellPressures = std::vector<Scalar>(this->local_num_cells_,
Scalar{0});
889 auto cellTemperatures = std::vector<Scalar>(this->local_num_cells_,
Scalar{0});
892 const auto& gridView = this->simulator_.vanguard().gridView();
895 for (
const auto& elem : elements(gridView, Dune::Partitions::interior)) {
896 elemCtx.updatePrimaryStencil(elem);
897 elemCtx.updatePrimaryIntensiveQuantities(0);
899 const auto ix = elemCtx.globalSpaceIndex(0, 0);
900 const auto& fs = elemCtx.intensiveQuantities(0, 0).fluidState();
902 cellPressures[ix] = fs.pressure(pressIx).value();
903 cellTemperatures[ix] = fs.temperature(0).value();
906 this->simulator_.vanguard().grid().comm());
908 this->wellState().init(cellPressures, cellTemperatures, this->schedule(), this->wells_ecl_,
909 this->local_parallel_well_info_, timeStepIdx,
910 &this->prevWellState(), this->well_perf_data_,
911 this->summaryState(), simulator_.vanguard().enableDistributedWells());
918 template<
typename TypeTag>
923 auto logger_guard = this->groupStateHelper().pushLogger();
924 auto& local_deferredLogger = this->groupStateHelper().deferredLogger();
926 const int nw = this->numLocalWells();
928 well_container_.clear();
931 well_container_.reserve(nw);
933 const auto& wmatcher = this->schedule().wellMatcher(report_step);
934 const auto& wcycle = this->schedule()[report_step].wcycle.get();
938 std::ranges::for_each(this->wells_ecl_,
939 [
this, &wg_events = this->report_step_start_events_](
const auto& well_ecl)
941 if (!well_ecl.hasConnections()) {
946 constexpr auto events_mask = ScheduleEvents::WELL_STATUS_CHANGE |
947 ScheduleEvents::REQUEST_OPEN_WELL |
948 ScheduleEvents::REQUEST_SHUT_WELL;
949 const bool well_event =
950 this->report_step_starts_ &&
951 wg_events.hasEvent(well_ecl.name(), events_mask);
960 if (well_ecl.getStatus() == WellStatus::OPEN) {
961 this->well_open_times_.insert_or_assign(well_ecl.name(),
962 this->simulator_.time());
963 this->well_close_times_.erase(well_ecl.name());
964 }
else if (well_ecl.getStatus() == WellStatus::SHUT) {
965 this->well_close_times_.insert_or_assign(well_ecl.name(),
966 this->simulator_.time());
967 this->well_open_times_.erase(well_ecl.name());
973 const auto cycle_states = wcycle.wellStatus(this->simulator_.time(),
975 this->well_open_times_,
976 this->well_close_times_);
978 for (
int w = 0; w < nw; ++w) {
979 const Well& well_ecl = this->wells_ecl_[w];
981 if (!well_ecl.hasConnections()) {
986 const std::string& well_name = well_ecl.name();
987 const auto well_status = this->schedule()
988 .getWell(well_name, report_step).getStatus();
990 const bool shut_event = this->wellState().well(w).events.hasEvent(ScheduleEvents::WELL_STATUS_CHANGE)
991 && well_status == Well::Status::SHUT;
992 const bool open_event = this->wellState().well(w).events.hasEvent(ScheduleEvents::WELL_STATUS_CHANGE)
993 && well_status == Well::Status::OPEN;
994 const auto& ws = this->wellState().well(well_name);
996 if (shut_event && ws.status != Well::Status::SHUT) {
997 this->closed_this_step_.insert(well_name);
998 this->wellState().shutWell(w);
999 }
else if (open_event && ws.status != Well::Status::OPEN) {
1000 this->wellState().openWell(w);
1004 if (this->wellTestState().well_is_closed(well_name)) {
1009 const bool closed_this_step = (this->wellTestState().lastTestTime(well_name) == simulator_.time());
1012 auto& events = this->wellState().well(w).events;
1013 if (events.hasEvent(ScheduleEvents::REQUEST_OPEN_WELL)) {
1014 if (!closed_this_step) {
1015 this->wellTestState().open_well(well_name);
1016 this->wellTestState().open_completions(well_name);
1017 this->well_open_times_.insert_or_assign(well_name,
1018 this->simulator_.time());
1019 this->well_close_times_.erase(well_name);
1021 events.clearEvent(ScheduleEvents::REQUEST_OPEN_WELL);
1027 if (this->wellTestState().well_is_closed(well_name))
1029 if (well_ecl.getAutomaticShutIn()) {
1031 this->wellState().shutWell(w);
1032 this->well_close_times_.erase(well_name);
1033 this->well_open_times_.erase(well_name);
1036 if (!well_ecl.getAllowCrossFlow()) {
1039 this->wellState().shutWell(w);
1040 this->well_close_times_.erase(well_name);
1041 this->well_open_times_.erase(well_name);
1045 this->wellState().stopWell(w);
1050 if (!well_ecl.getAllowCrossFlow()) {
1051 const bool any_zero_rate_constraint = well_ecl.isProducer()
1052 ? well_ecl.productionControls(this->summaryState_).anyZeroRateConstraint()
1053 : well_ecl.injectionControls(this->summaryState_).anyZeroRateConstraint();
1054 if (any_zero_rate_constraint) {
1056 local_deferredLogger.debug(fmt::format(fmt::runtime(
" Well {} gets shut due to having zero rate constraint and disallowing crossflow "), well_ecl.name()));
1057 this->wellState().shutWell(w);
1058 this->well_close_times_.erase(well_name);
1059 this->well_open_times_.erase(well_name);
1064 if (!wcycle.empty()) {
1065 const auto it = cycle_states.find(well_name);
1066 if (it != cycle_states.end()) {
1067 if (!it->second || well_status == Well::Status::SHUT) {
1069 if (well_status == Well::Status::SHUT) {
1070 this->well_open_times_.erase(well_name);
1071 this->well_close_times_.erase(well_name);
1073 this->wellState().shutWell(w);
1076 this->wellState().openWell(w);
1082 if (ws.status == Well::Status::SHUT) {
1086 well_container_.emplace_back(this->createWellPointer(w, report_step));
1088 if (ws.status == Well::Status::STOP) {
1089 well_container_.back()->stopWell();
1090 this->well_close_times_.erase(well_name);
1091 this->well_open_times_.erase(well_name);
1095 if (!wcycle.empty()) {
1096 const auto schedule_open =
1097 [&wg_events = this->report_step_start_events_](
const std::string& name)
1099 return wg_events.hasEvent(name, ScheduleEvents::REQUEST_OPEN_WELL);
1101 for (
const auto& [wname, wscale] : wcycle.efficiencyScale(this->simulator_.time(),
1102 this->simulator_.timeStepSize(),
1104 this->well_open_times_,
1107 this->wellState().updateEfficiencyScalingFactor(wname, wscale);
1108 this->schedule_.add_event(ScheduleEvents::WELLGROUP_EFFICIENCY_UPDATE, report_step);
1113 this->well_container_generic_.clear();
1114 for (
auto& w : well_container_) {
1115 this->well_container_generic_.push_back(w.get());
1118 this->network_.initialize(report_step);
1120 this->wbp_.registerOpenWellsForWBPCalculation();
1127 template <
typename TypeTag>
1132 const auto is_multiseg = this->wells_ecl_[wellID].isMultiSegment();
1134 if (! (this->param_.use_multisegment_well_ && is_multiseg)) {
1135 return this->
template createTypedWellPointer<StandardWell<TypeTag>>(wellID, report_step);
1138 return this->
template createTypedWellPointer<MultisegmentWell<TypeTag>>(wellID, report_step);
1146 template <
typename TypeTag>
1147 template <
typename WellType>
1148 std::unique_ptr<WellType>
1153 const auto& perf_data = this->well_perf_data_[wellID];
1156 const auto pvtreg = perf_data.empty()
1157 ? 0 : this->pvt_region_idx_[perf_data.front().cell_index];
1159 const auto& parallel_well_info = this->local_parallel_well_info_[wellID].get();
1160 const auto global_pvtreg = parallel_well_info.broadcastFirstPerforationValue(pvtreg);
1162 return std::make_unique<WellType>(this->wells_ecl_[wellID],
1166 *this->rateConverter_,
1168 this->numConservationQuantities(),
1178 template<
typename TypeTag>
1182 const int report_step,
1187 std::ranges::find_if(this->wells_ecl_,
1188 [&well_name](
const auto& w)
1189 {
return well_name == w.name(); });
1191 if (it == this->wells_ecl_.end()) {
1193 fmt::format(fmt::runtime(
"Could not find well {} in wells_ecl"), well_name),
1197 const int pos =
static_cast<int>(std::distance(this->wells_ecl_.begin(), it));
1198 return this->createWellPointer(pos, report_step);
1203 template<
typename TypeTag>
1209 auto logger_guard = this->groupStateHelper().pushLogger();
1210 auto& local_deferredLogger = this->groupStateHelper().deferredLogger();
1212 const auto& iterCtx = simulator_.problem().iterationContext();
1215 if (gaslift_.terminalOutput()) {
1216 const std::string msg =
1217 fmt::format(fmt::runtime(
"assemble() : iteration {}"), iterCtx.iteration());
1218 gaslift_.gliftDebug(msg, local_deferredLogger);
1222 Dune::Timer perfTimer;
1224 this->closed_offending_wells_.clear();
1227 const int episodeIdx = simulator_.episodeIndex();
1228 const auto& network = this->schedule()[episodeIdx].network();
1229 if (!this->wellsActive() && !network.active()) {
1235 if (iterCtx.needsTimestepInit() && this->wellsActive()) {
1236 OPM_TIMEBLOCK(firstIterationAssemble);
1243 calculateExplicitQuantities();
1244 prepareTimeStep(local_deferredLogger);
1247 "assemble() failed during well initialization: ",
1248 this->terminal_output_, grid().comm());
1251 const bool well_group_control_changed = updateWellControlsAndNetwork(
false, dt, local_deferredLogger);
1255 if ( ! this->wellsActive() ) {
1259 assembleWellEqWithoutIteration(dt);
1265 last_report_.well_group_control_changed = well_group_control_changed;
1266 last_report_.assemble_time_well += perfTimer.stop();
1272 template<
typename TypeTag>
1281 bool do_network_update =
true;
1282 bool well_group_control_changed =
false;
1283 Scalar network_imbalance = 0.0;
1285 const std::size_t iteration_to_relax = param_.network_max_strict_outer_iterations_;
1287 const std::size_t max_iteration = param_.network_max_outer_iterations_;
1288 std::size_t network_update_iteration = 0;
1289 network_needs_more_balancing_force_another_newton_iteration_ =
false;
1290 while (do_network_update) {
1291 if (network_update_iteration >= max_iteration ) {
1293 const int episodeIdx = simulator_.episodeIndex();
1294 const auto& iterCtx = simulator_.problem().iterationContext();
1295 if (this->network_.willBalanceOnNextIteration(episodeIdx, iterCtx)) {
1296 if (this->terminal_output_) {
1297 const std::string msg = fmt::format(
"Maximum of {:d} network iterations has been used and we stop the update, \n"
1298 "and try again after the next Newton iteration (imbalance = {:.2e} bar)",
1299 max_iteration, network_imbalance*1.0e-5);
1300 local_deferredLogger.
debug(msg);
1304 network_needs_more_balancing_force_another_newton_iteration_ =
true;
1306 if (this->terminal_output_) {
1307 const std::string msg = fmt::format(
"Maximum of {:d} network iterations has been used and we stop the update. \n"
1308 "The simulator will continue with unconverged network results (imbalance = {:.2e} bar)",
1309 max_iteration, network_imbalance*1.0e-5);
1310 local_deferredLogger.
info(msg);
1315 if (this->terminal_output_ && (network_update_iteration == iteration_to_relax) ) {
1316 local_deferredLogger.
debug(
"We begin using relaxed tolerance for network update now after " +
std::to_string(iteration_to_relax) +
" iterations ");
1318 const bool relax_network_balance = network_update_iteration >= iteration_to_relax;
1320 const bool optimize_gas_lift = ( (network_update_iteration + 1) < std::max(max_iteration,
static_cast<std::size_t
>(2)) );
1321 std::tie(well_group_control_changed, do_network_update, network_imbalance) =
1322 updateWellControlsAndNetworkIteration(mandatory_network_balance, relax_network_balance, optimize_gas_lift, dt,local_deferredLogger);
1323 ++network_update_iteration;
1325 return well_group_control_changed;
1331 template<
typename TypeTag>
1332 std::tuple<bool, bool, typename BlackoilWellModel<TypeTag>::Scalar>
1335 const bool relax_network_tolerance,
1336 const bool optimize_gas_lift,
1341 const auto& iterCtx = simulator_.problem().iterationContext();
1342 const int reportStepIdx = simulator_.episodeIndex();
1343 this->updateAndCommunicateGroupData(reportStepIdx, iterCtx,
1344 param_.nupcol_group_rate_tolerance_,
true);
1349 bool well_group_control_changed = updateWellControls(local_deferredLogger);
1350 const auto [more_inner_network_update, network_imbalance] =
1351 this->network_.update(mandatory_network_balance,
1352 local_deferredLogger,
1353 relax_network_tolerance);
1355 bool alq_updated =
false;
1358 if (optimize_gas_lift) {
1361 const bool updatePotentials = (this->network_.shouldBalance(reportStepIdx, iterCtx) ||
1362 mandatory_network_balance);
1363 alq_updated = gaslift_.maybeDoGasLiftOptimize(simulator_,
1365 this->network_.nodePressures(),
1369 local_deferredLogger);
1371 prepareWellsBeforeAssembling(dt);
1374 "updateWellControlsAndNetworkIteration() failed: ",
1375 this->terminal_output_, grid().comm());
1379 guideRateUpdateIsNeeded(reportStepIdx)) {
1380 const double simulationTime = simulator_.time();
1384 this->guide_rate_handler_.updateGuideRates(
1385 reportStepIdx, simulationTime, this->wellState(), this->groupState()
1390 const bool more_network_update = this->network_.shouldBalance(reportStepIdx, iterCtx) &&
1391 (more_inner_network_update || alq_updated);
1392 return {well_group_control_changed, more_network_update, network_imbalance};
1395 template<
typename TypeTag>
1401 for (
auto& well : well_container_) {
1402 well->assembleWellEq(simulator_, dt, this->groupStateHelper(), this->wellState());
1407 template<
typename TypeTag>
1413 for (
auto& well : well_container_) {
1414 well->prepareWellBeforeAssembling(
1415 simulator_, dt, this->groupStateHelper(), this->wellState()
1421 template<
typename TypeTag>
1427 auto& deferred_logger = this->groupStateHelper().deferredLogger();
1432 for (
auto& well: well_container_) {
1433 well->assembleWellEqWithoutIteration(simulator_, this->groupStateHelper(), dt, this->wellState(),
1437 this->terminal_output_, grid().comm());
1441 template<
typename TypeTag>
1448 for (
const auto& well : well_container_) {
1449 well->addCellRates(cellRates_);
1453 template<
typename TypeTag>
1460 for (
const auto& well : well_container_) {
1461 const auto it = well_domain_map.find(well->name());
1462 if (it != well_domain_map.end() && it->second == domainIndex) {
1463 well->addCellRates(cellRates_);
1468#if COMPILE_GPU_BRIDGE
1469 template<
typename TypeTag>
1477 for(
unsigned int i = 0; i < well_container_.size(); i++){
1478 auto& well = well_container_[i];
1481 wellContribs.
addNumBlocks(derived->linSys().getNumBlocks());
1486 wellContribs.
alloc();
1488 for(
unsigned int i = 0; i < well_container_.size(); i++){
1489 auto& well = well_container_[i];
1491 auto derived_std =
dynamic_cast<StandardWell<TypeTag>*
>(well.get());
1493 derived_std->linSys().extract(derived_std->numStaticWellEq, wellContribs);
1495 auto derived_ms =
dynamic_cast<MultisegmentWell<TypeTag>*
>(well.get());
1497 derived_ms->linSys().extract(wellContribs);
1499 OpmLog::warning(
"Warning unknown type of well");
1506 template<
typename TypeTag>
1511 for (
const auto& well: well_container_ ) {
1512 well->addWellContributions(jacobian);
1516 template<
typename TypeTag>
1521 const bool use_well_weights)
const
1523 int nw = this->numLocalWellsEnd();
1524 int rdofs = local_num_cells_;
1525 for (
int i = 0; i < nw; i++ ) {
1526 int wdof = rdofs + i;
1527 jacobian[wdof][wdof] = 1.0;
1530 for (
const auto& well : well_container_) {
1531 well->addWellPressureEquations(jacobian,
1539 template <
typename TypeTag>
1542 const std::vector<typename SparseMatrixAdapter::MatrixBlock*>& diagMatAddress)
const
1547 for (
const auto& well : well_container_) {
1548 if (!well->isOperableAndSolvable() && !well->wellIsStopped()) {
1551 const auto& cells = well->cells();
1552 const auto& rates = well->connectionRates();
1553 for (
unsigned perfIdx = 0; perfIdx < rates.size(); ++perfIdx) {
1554 unsigned cellIdx = cells[perfIdx];
1555 auto rate = rates[perfIdx];
1558 using MatrixBlockType =
typename SparseMatrixAdapter::MatrixBlock;
1559 MatrixBlockType bMat(0.0);
1560 simulator_.model().linearizer().setResAndJacobi(res, bMat, rate);
1561 residual[cellIdx] += res;
1562 *diagMatAddress[cellIdx] += bMat;
1568 template<
typename TypeTag>
1573 int nw = this->numLocalWellsEnd();
1574 int rdofs = local_num_cells_;
1575 for (
int i = 0; i < nw; ++i) {
1576 int wdof = rdofs + i;
1577 jacobian.entry(wdof,wdof) = 1.0;
1579 const auto wellconnections = this->getMaxWellConnections();
1580 for (
int i = 0; i < nw; ++i) {
1581 const auto& perfcells = wellconnections[i];
1582 for (
int perfcell : perfcells) {
1583 int wdof = rdofs + i;
1584 jacobian.entry(wdof, perfcell) = 0.0;
1585 jacobian.entry(perfcell, wdof) = 0.0;
1591 template<
typename TypeTag>
1596 auto loggerGuard = this->groupStateHelper().pushLogger();
1599 for (
const auto& well : well_container_) {
1600 const auto& cells = well->cells();
1601 x_local_.resize(cells.size());
1603 for (
size_t i = 0; i < cells.size(); ++i) {
1604 x_local_[i] = x[cells[i]];
1606 well->recoverWellSolutionAndUpdateWellState(simulator_, x_local_,
1607 this->groupStateHelper(), this->wellState());
1611 simulator_.vanguard().grid().comm());
1615 template<
typename TypeTag>
1621 OPM_THROW(std::logic_error,
"Attempt to call NLDD method without a NLDD solver");
1624 return nldd_->recoverWellSolutionAndUpdateWellState(x, domainIdx);
1628 template<
typename TypeTag>
1631 getWellConvergence(
const std::vector<Scalar>& B_avg,
bool checkWellGroupControlsAndNetwork)
const
1635 const auto& iterCtx = simulator_.problem().iterationContext();
1636 const bool relaxTolerance = iterCtx.shouldRelax(param_.strict_outer_iter_wells_ + 1);
1638 auto logger_guard = this->groupStateHelper().pushLogger();
1639 for (
const auto& well : well_container_) {
1640 if (well->isOperableAndSolvable() || well->wellIsStopped()) {
1641 local_report += well->getWellConvergence(
1642 this->groupStateHelper(), B_avg,
1647 report.
setWellFailed({CR::WellFailure::Type::Unsolvable, CR::Severity::Normal, -1, well->name()});
1648 local_report += report;
1656 if (checkWellGroupControlsAndNetwork) {
1662 if (this->terminal_output_) {
1666 OpmLog::debug(
"NaN residual found with phase " +
std::to_string(f.phase()) +
" for well " + f.wellName());
1668 OpmLog::debug(
"Too large residual found with phase " +
std::to_string(f.phase()) +
" for well " + f.wellName());
1679 template<
typename TypeTag>
1685 for (
auto& well : well_container_) {
1686 well->calculateExplicitQuantities(simulator_, this->groupStateHelper());
1694 template<
typename TypeTag>
1700 if (!this->wellsActive()) {
1703 const int episodeIdx = simulator_.episodeIndex();
1704 const auto& comm = simulator_.vanguard().grid().comm();
1706 bool changed_well_group =
false;
1707 const Group& fieldGroup = this->schedule().getGroup(
"FIELD", episodeIdx);
1710 const std::size_t max_iter = param_.well_group_constraints_max_iterations_;
1711 while(!changed_well_group && iter < max_iter) {
1712 changed_well_group = updateGroupControls(fieldGroup, deferred_logger, episodeIdx);
1715 bool changed_well_to_group =
false;
1717 OPM_TIMEBLOCK(UpdateWellControls);
1721 for (
const auto& well : well_container_) {
1724 simulator_, mode, this->groupStateHelper(), this->wellState()
1727 changed_well_to_group = changed_well || changed_well_to_group;
1731 simulator_.gridView().comm());
1734 changed_well_to_group = comm.sum(
static_cast<int>(changed_well_to_group));
1735 if (changed_well_to_group) {
1736 updateAndCommunicate(episodeIdx);
1737 changed_well_group =
true;
1741 bool changed_well_individual =
false;
1746 for (
const auto& well : well_container_) {
1749 simulator_, mode, this->groupStateHelper(), this->wellState()
1752 changed_well_individual = changed_well || changed_well_individual;
1756 simulator_.gridView().comm());
1759 changed_well_individual = comm.sum(
static_cast<int>(changed_well_individual));
1760 if (changed_well_individual) {
1761 updateAndCommunicate(episodeIdx);
1762 changed_well_group =
true;
1768 this->updateWsolvent(fieldGroup, episodeIdx, this->nupcolWellState());
1770 return changed_well_group;
1774 template<
typename TypeTag>
1779 const auto& iterCtx = simulator_.problem().iterationContext();
1780 this->updateAndCommunicateGroupData(reportStepIdx,
1782 param_.nupcol_group_rate_tolerance_,
1789 for (
const auto& well : well_container_) {
1791 const auto& ws = this->wellState().well(well->indexOfWell());
1792 if (ws.production_cmode == Well::ProducerCMode::GRUP ||
1793 ws.injection_cmode == Well::InjectorCMode::GRUP)
1795 well->updateWellStateWithTarget(
1796 simulator_, this->groupStateHelper(), this->wellState()
1801 simulator_.gridView().comm())
1802 this->updateAndCommunicateGroupData(reportStepIdx,
1804 param_.nupcol_group_rate_tolerance_,
1808 template<
typename TypeTag>
1813 const int reportStepIdx)
1816 const auto& iterCtx = simulator_.problem().iterationContext();
1817 bool changed =
false;
1819 const int nupcol = this->schedule()[reportStepIdx].nupcol();
1820 const int max_number_of_group_switches = param_.max_number_of_group_switches_;
1821 const bool update_group_switching_log = !iterCtx.withinNupcol(nupcol);
1822 const bool changed_hc = this->checkGroupHigherConstraints(group, deferred_logger, reportStepIdx, max_number_of_group_switches, update_group_switching_log);
1825 updateAndCommunicate(reportStepIdx);
1828 bool changed_individual =
1830 updateGroupIndividualControl(group,
1832 max_number_of_group_switches,
1833 update_group_switching_log,
1834 this->switched_inj_groups_,
1835 this->switched_prod_groups_,
1836 this->closed_offending_wells_,
1841 if (changed_individual) {
1843 updateAndCommunicate(reportStepIdx);
1846 for (
const std::string& groupName : group.groups()) {
1847 bool changed_this = updateGroupControls(this->schedule().getGroup(groupName, reportStepIdx), deferred_logger, reportStepIdx);
1848 changed = changed || changed_this;
1853 template<
typename TypeTag>
1859 auto logger_guard = this->groupStateHelper().pushLogger();
1860 auto& local_deferredLogger = this->groupStateHelper().deferredLogger();
1861 for (
const auto& well : well_container_) {
1862 const auto& wname = well->name();
1863 const auto wasClosed = wellTestState.well_is_closed(wname);
1864 well->checkWellOperability(simulator_,
1866 this->groupStateHelper());
1867 const bool under_zero_target =
1868 well->wellUnderZeroGroupRateTarget(this->groupStateHelper());
1869 well->updateWellTestState(this->wellState().well(wname),
1874 local_deferredLogger);
1876 if (!wasClosed && wellTestState.well_is_closed(wname)) {
1877 this->closed_this_step_.insert(wname);
1880 const WellEconProductionLimits& econ_production_limits = well->wellEcl().getEconLimits();
1881 if (econ_production_limits.validFollowonWell()) {
1882 const auto episode_idx = simulator_.episodeIndex();
1883 const auto follow_on_well = econ_production_limits.followonWell();
1884 if (!this->schedule().hasWell(follow_on_well, episode_idx)) {
1885 const auto msg = fmt::format(
"Well {} was closed. But the given follow on well {} does not exist."
1886 "The simulator continues without opening a follow on well.",
1887 wname, follow_on_well);
1888 local_deferredLogger.warning(msg);
1890 auto& ws = this->wellState().well(follow_on_well);
1891 const bool success = ws.updateStatus(WellStatus::OPEN);
1893 const auto msg = fmt::format(
"Well {} was closed. The follow on well {} opens instead.", wname, follow_on_well);
1894 local_deferredLogger.info(msg);
1896 const auto msg = fmt::format(
"Well {} was closed. The follow on well {} is already open.", wname, follow_on_well);
1897 local_deferredLogger.warning(msg);
1904 for (
const auto& [group_name, to] : this->closed_offending_wells_) {
1905 if (this->hasOpenLocalWell(to.second) &&
1906 !this->wasDynamicallyShutThisTimeStep(to.second))
1908 wellTestState.close_well(to.second,
1909 WellTestConfig::Reason::GROUP,
1911 this->updateClosedWellsThisStep(to.second);
1912 const std::string msg =
1913 fmt::format(
"Procedure on exceeding {} limit is WELL for group {}. "
1919 local_deferredLogger.info(msg);
1925 template<
typename TypeTag>
1929 std::string& exc_msg,
1933 const int np = this->numPhases();
1934 std::vector<Scalar> potentials;
1935 const auto& well = well_container_[widx];
1936 std::string cur_exc_msg;
1939 well->computeWellPotentials(simulator_, well_state_copy, this->groupStateHelper(), potentials);
1944 exc_msg += fmt::format(
"\nFor well {}: {}", well->name(), cur_exc_msg);
1946 exc_type = std::max(exc_type, cur_exc_type);
1950 auto& ws = this->wellState().well(well->indexOfWell());
1951 for (
int p = 0; p < np; ++p) {
1953 ws.well_potentials[p] = std::max(
Scalar{0.0}, potentials[p]);
1959 template <
typename TypeTag>
1964 for (
const auto& wellPtr : this->well_container_) {
1965 this->calculateProductivityIndexValues(wellPtr.get(), deferred_logger);
1973 template <
typename TypeTag>
1984 for (
const auto& shutWell : this->local_shut_wells_) {
1985 if (!this->wells_ecl_[shutWell].hasConnections()) {
1990 auto wellPtr = this->
template createTypedWellPointer
1993 wellPtr->
init(this->depth_, this->gravity_, this->B_avg_,
true);
1995 this->calculateProductivityIndexValues(wellPtr.get(), deferred_logger);
2003 template <
typename TypeTag>
2017 template<
typename TypeTag>
2023 const auto episodeIdx = simulator_.episodeIndex();
2024 this->network_.updateActiveState(episodeIdx);
2028 const bool do_prestep_network_rebalance =
2029 param_.pre_solve_network_ && this->network_.needPreStepRebalance(episodeIdx);
2031 for (
const auto& well : well_container_) {
2032 auto& events = this->wellState().well(well->indexOfWell()).events;
2034 well->updateWellStateWithTarget(
2035 simulator_, this->groupStateHelper(), this->wellState()
2037 well->updatePrimaryVariables(this->groupStateHelper());
2043 if (events.hasEvent(ScheduleEvents::REQUEST_OPEN_WELL)) {
2044 events.clearEvent(ScheduleEvents::REQUEST_OPEN_WELL);
2047 if (param_.solve_welleq_initially_ && well->isOperableAndSolvable()) {
2049 well->solveWellEquation(
2050 simulator_, this->groupStateHelper(), this->wellState()
2052 }
catch (
const std::exception& e) {
2053 const std::string msg =
"Compute initial well solution for " + well->name() +
" initially failed. Continue with the previous rates";
2054 deferred_logger.
warning(
"WELL_INITIAL_SOLVE_FAILED", msg);
2059 well->resetWellOperability();
2061 updatePrimaryVariables();
2064 if (do_prestep_network_rebalance) {
2065 network_.doPreStepRebalance(deferred_logger);
2069 template<
typename TypeTag>
2074 std::vector< Scalar > B_avg(numConservationQuantities(),
Scalar() );
2075 const auto& grid = simulator_.vanguard().grid();
2076 const auto& gridView = grid.leafGridView();
2080 for (
const auto& elem : elements(gridView, Dune::Partitions::interior)) {
2081 elemCtx.updatePrimaryStencil(elem);
2082 elemCtx.updatePrimaryIntensiveQuantities(0);
2084 const auto& intQuants = elemCtx.intensiveQuantities(0, 0);
2085 const auto& fs = intQuants.fluidState();
2087 for (
unsigned phaseIdx = 0; phaseIdx < FluidSystem::numPhases; ++phaseIdx)
2089 if (!FluidSystem::phaseIsActive(phaseIdx)) {
2093 const unsigned compIdx = FluidSystem::canonicalToActiveCompIdx(FluidSystem::solventComponentIndex(phaseIdx));
2094 auto& B = B_avg[ compIdx ];
2096 B += 1 / fs.invB(phaseIdx).value();
2098 if constexpr (has_solvent_) {
2099 auto& B = B_avg[solventSaturationIdx];
2100 B += 1 / intQuants.solventInverseFormationVolumeFactor().value();
2106 grid.comm().sum(B_avg.data(), B_avg.size());
2107 B_avg_.resize(B_avg.size());
2108 std::ranges::transform(B_avg, B_avg_.begin(),
2109 [gcells = global_num_cells_](
const auto bval)
2110 { return bval / gcells; });
2117 template<
typename TypeTag>
2122 for (
const auto& well : well_container_) {
2123 well->updatePrimaryVariables(this->groupStateHelper());
2127 template<
typename TypeTag>
2131 const auto& grid = simulator_.vanguard().grid();
2132 const auto& eclProblem = simulator_.problem();
2133 const unsigned numCells = grid.size(0);
2135 this->pvt_region_idx_.resize(numCells);
2136 for (
unsigned cellIdx = 0; cellIdx < numCells; ++cellIdx) {
2137 this->pvt_region_idx_[cellIdx] =
2138 eclProblem.pvtRegionIndex(cellIdx);
2143 template<
typename TypeTag>
2156 return this->numPhases() + has_solvent_;
2159 template<
typename TypeTag>
2163 const auto& eclProblem = simulator_.problem();
2164 depth_.resize(local_num_cells_);
2165 for (
unsigned cellIdx = 0; cellIdx < local_num_cells_; ++cellIdx) {
2166 depth_[cellIdx] = eclProblem.dofCenterDepth(cellIdx);
2170 template<
typename TypeTag>
2173 getWell(
const std::string& well_name)
const
2177 std::ranges::find_if(well_container_,
2179 {
return elem->name() == well_name; });
2181 assert(well != well_container_.end());
2186 template <
typename TypeTag>
2191 return std::max(this->simulator_.episodeIndex(), 0);
2198 template<
typename TypeTag>
2203 const std::vector<Scalar>& production_rates,
2204 std::vector<Scalar>& resv_coeff)
const
2206 rateConverter_->calcCoeff(fipnum, pvtreg, production_rates, resv_coeff);
2209 template<
typename TypeTag>
2214 std::vector<Scalar>& resv_coeff)
const
2216 rateConverter_->calcInjCoeff(fipnum, pvtreg, resv_coeff);
2220 template <
typename TypeTag>
2225 if constexpr (energyModuleType_ == EnergyModules::FullyImplicitThermal) {
2226 const int np = this->numPhases();
2227 const int nw = this->numLocalWells();
2228 for (
auto wellID = 0*nw; wellID < nw; ++wellID) {
2229 const Well& well = this->wells_ecl_[wellID];
2230 auto& ws = this->wellState().well(wellID);
2231 if (well.isInjector()) {
2232 if (ws.status != WellStatus::STOP) {
2233 this->wellState().well(wellID).temperature = well.inj_temperature();
2237 std::array<Scalar,2> weighted{0.0,0.0};
2238 auto& [weighted_temperature, total_weight] = weighted;
2239 const auto& well_info = this->local_parallel_well_info_[wellID].get();
2240 using int_type =
decltype(this->well_perf_data_[wellID].size());
2241 for (int_type perf = 0, end_perf = this->well_perf_data_[wellID].size(); perf < end_perf; ++perf) {
2242 const int cell_idx = this->well_perf_data_[wellID][perf].cell_index;
2243 const auto& intQuants = simulator_.model().intensiveQuantities(cell_idx, 0);
2244 const auto& fs = intQuants.fluidState();
2245 Scalar weight_factor = computeTemperatureWeightFactor(perf, np, fs, ws);
2246 total_weight += weight_factor;
2247 weighted_temperature += weight_factor * fs.temperature(0).value();
2249 well_info.communication().sum(weighted.data(), 2);
2250 this->wellState().well(wellID).temperature = weighted_temperature / total_weight;
2256 template <
typename TypeTag>
2260 const auto reportStepIdx =
static_cast<unsigned int>(this->reportStepIndex());
2261 const auto& trMod = this->simulator_.problem().tracerModel();
2267 this->assignMswTracerRates(wsrpt, trMod.getMswTracerRates(), reportStepIdx);
2270 template <
typename TypeTag>
2271 void BlackoilWellModel<TypeTag>::
2272 assignWellSpeciesRates(data::Wells& wsrpt)
const
2274 const auto reportStepIdx =
static_cast<unsigned int>(this->reportStepIndex());
2275 const auto& geochemMod = this->simulator_.problem().geochemistryModel();
2279 this->assignMswTracerRates(wsrpt, geochemMod.getMswSpeciesRates(), reportStepIdx);
2282 template <
typename TypeTag>
2283 [[nodiscard]]
auto BlackoilWellModel<TypeTag>::rsConstInfo() const
2284 -> typename WellState<Scalar,IndexTraits>::RsConstInfo
2286 if (! FluidSystem::phaseIsActive(FluidSystem::oilPhaseIdx) ||
2287 ! FluidSystem::enableConstantRs())
2292 const auto& rsConstTables = this->eclState_
2293 .getTableManager().getRsconstTables();
2295 if (rsConstTables.empty() ||
2296 (rsConstTables[0].numRows() != std::size_t{1}))
2301 const auto rsConst = rsConstTables[0].getColumn(0).front();
2303 return {
true,
static_cast<Scalar
>(rsConst) };
#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:297
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:2201
void prepareTimeStep(DeferredLogger &deferred_logger)
Definition: BlackoilWellModel_impl.hpp:2020
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:1334
WellInterfacePtr createWellPointer(const int wellID, const int report_step) const
Definition: BlackoilWellModel_impl.hpp:1130
void prepareWellsBeforeAssembling(const double dt)
Definition: BlackoilWellModel_impl.hpp:1410
void init()
Definition: BlackoilWellModel_impl.hpp:166
const Simulator & simulator() const
Definition: BlackoilWellModel.hpp:370
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:185
void beginReportStep(const int time_step)
Definition: BlackoilWellModel_impl.hpp:202
const WellInterface< TypeTag > & getWell(const std::string &well_name) const
Definition: BlackoilWellModel_impl.hpp:2173
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:2145
bool updateWellControls(DeferredLogger &deferred_logger)
Definition: BlackoilWellModel_impl.hpp:1697
int reportStepIndex() const
Definition: BlackoilWellModel_impl.hpp:2189
void calculateProductivityIndexValues(DeferredLogger &deferred_logger) override
Definition: BlackoilWellModel_impl.hpp:1962
void extractLegacyDepth_()
Definition: BlackoilWellModel_impl.hpp:2161
void extractLegacyCellPvtRegionIndex_()
Definition: BlackoilWellModel_impl.hpp:2129
void recoverWellSolutionAndUpdateWellStateDomain(const BVector &x, const int domainIdx)
Definition: BlackoilWellModel_impl.hpp:1618
void updateAverageFormationFactor()
Definition: BlackoilWellModel_impl.hpp:2072
GetPropType< TypeTag, Properties::Simulator > Simulator
Definition: BlackoilWellModel.hpp:106
void initializeWellState(const int timeStepIdx)
Definition: BlackoilWellModel_impl.hpp:878
const Grid & grid() const
Definition: BlackoilWellModel.hpp:367
void updatePrimaryVariables()
Definition: BlackoilWellModel_impl.hpp:2120
void computeWellTemperature()
Definition: BlackoilWellModel_impl.hpp:2223
void addWellPressureEquations(PressureMatrix &jacobian, const BVector &weights, const bool use_well_weights) const
Definition: BlackoilWellModel_impl.hpp:1519
const SimulatorReportSingle & lastReport() const
Definition: BlackoilWellModel_impl.hpp:754
bool updateWellControlsAndNetwork(const bool mandatory_network_balance, const double dt, DeferredLogger &local_deferredLogger)
Definition: BlackoilWellModel_impl.hpp:1275
void addWellContributions(SparseMatrixAdapter &jacobian) const
Definition: BlackoilWellModel_impl.hpp:1509
void assembleWellEq(const double dt)
Definition: BlackoilWellModel_impl.hpp:1398
WellInterfacePtr createWellForWellTest(const std::string &well_name, const int report_step, DeferredLogger &deferred_logger) const
Definition: BlackoilWellModel_impl.hpp:1181
void calculateExplicitQuantities() const
Definition: BlackoilWellModel_impl.hpp:1682
void updateAndCommunicate(const int reportStepIdx)
Definition: BlackoilWellModel_impl.hpp:1777
Dune::BCRSMatrix< Opm::MatrixBlock< Scalar, 1, 1 > > PressureMatrix
Definition: BlackoilWellModel.hpp:289
void computeTotalRatesForDof(RateVector &rate, unsigned globalIdx) const
Definition: BlackoilWellModel_impl.hpp:841
void beginTimeStep()
Definition: BlackoilWellModel_impl.hpp:329
GetPropType< TypeTag, Properties::RateVector > RateVector
Definition: BlackoilWellModel.hpp:108
bool updateGroupControls(const Group &group, DeferredLogger &deferred_logger, const int reportStepIdx)
Definition: BlackoilWellModel_impl.hpp:1811
void calcInjResvCoeff(const int fipnum, const int pvtreg, std::vector< Scalar > &resv_coeff) const override
Definition: BlackoilWellModel_impl.hpp:2212
void initializeLocalWellStructure(const int reportStepIdx, const bool enableWellPIScaling)
Definition: BlackoilWellModel_impl.hpp:251
Dune::BlockVector< VectorBlockType > BVector
Definition: BlackoilWellModel.hpp:131
BlackoilWellModel(Simulator &simulator)
Definition: BlackoilWellModel_impl.hpp:79
void wellTesting(const int timeStepIdx, const double simulationTime, DeferredLogger &deferred_logger)
Definition: BlackoilWellModel_impl.hpp:677
ConvergenceReport getWellConvergence(const std::vector< Scalar > &B_avg, const bool checkWellGroupControlsAndNetwork=false) const
Definition: BlackoilWellModel_impl.hpp:1631
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:1456
void assembleWellEqWithoutIteration(const double dt)
Definition: BlackoilWellModel_impl.hpp:1424
void updateCellRates()
Definition: BlackoilWellModel_impl.hpp:1444
void assemble(const double dt)
Definition: BlackoilWellModel_impl.hpp:1206
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:764
std::unique_ptr< WellType > createTypedWellPointer(const int wellID, const int time_step) const
Definition: BlackoilWellModel_impl.hpp:1150
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:1927
Simulator & simulator_
Definition: BlackoilWellModel.hpp:487
void createWellContainer(const int report_step) override
Definition: BlackoilWellModel_impl.hpp:921
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:1856
void addReservoirSourceTerms(GlobalEqVector &residual, const std::vector< typename SparseMatrixAdapter::MatrixBlock * > &diagMatAddress) const
Definition: BlackoilWellModel_impl.hpp:1541
int compressedIndexForInterior(int cartesian_cell_idx) const override
get compressed index for interior cells (-1, otherwise
Definition: BlackoilWellModel.hpp:342
void recoverWellSolutionAndUpdateWellState(const BVector &x)
Definition: BlackoilWellModel_impl.hpp:1594
void addWellPressureEquationsStruct(PressureMatrix &jacobian) const
Definition: BlackoilWellModel_impl.hpp:1571
void calculateProductivityIndexValuesShutWells(const int reportStepIdx, DeferredLogger &deferred_logger) override
Definition: BlackoilWellModel_impl.hpp:1976
void endReportStep()
Definition: BlackoilWellModel_impl.hpp:737
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