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>
33#include <opm/common/utility/numeric/RootFinders.hpp>
35#include <opm/input/eclipse/Schedule/Network/Balance.hpp>
36#include <opm/input/eclipse/Schedule/Network/ExtNetwork.hpp>
37#include <opm/input/eclipse/Schedule/Well/PAvgDynamicSourceData.hpp>
38#include <opm/input/eclipse/Schedule/Well/WellMatcher.hpp>
39#include <opm/input/eclipse/Schedule/Well/WellTestConfig.hpp>
41#include <opm/input/eclipse/Units/UnitSystem.hpp>
67#include <fmt/format.h>
70 template<
typename TypeTag>
76 simulator.vanguard().summaryState(),
77 simulator.vanguard().eclState(),
79 simulator.gridView().comm())
80 , simulator_(simulator)
81 , guide_rate_handler_{
83 simulator.vanguard().schedule(),
84 simulator.vanguard().summaryState(),
85 simulator.vanguard().grid().comm()
87 , gaslift_(this->terminal_output_)
95 auto& parallel_wells =
simulator.vanguard().parallelWells();
98 for(
const auto& name_bool : parallel_wells) {
104 Parameters::Get<Parameters::AlternativeWellRateInit>();
106 using SourceDataSpan =
107 typename PAvgDynamicSourceData<Scalar>::template SourceDataSpan<Scalar>;
110 [
this](
const std::size_t globalIndex)
112 [
this](
const int localCell, SourceDataSpan sourceTerms)
114 using Item =
typename SourceDataSpan::Item;
116 const auto* intQuants = this->
simulator_.model()
117 .cachedIntensiveQuantities(localCell, 0);
118 const auto& fs = intQuants->fluidState();
121 .set(Item::PoreVol, intQuants->porosity().value() *
122 this->
simulator_.model().dofTotalVolume(localCell))
123 .set(Item::Depth, this->
depth_[localCell]);
125 constexpr auto io = FluidSystem::oilPhaseIdx;
126 constexpr auto ig = FluidSystem::gasPhaseIdx;
127 constexpr auto iw = FluidSystem::waterPhaseIdx;
130 const auto haveOil = FluidSystem::phaseIsActive(io);
131 const auto haveGas = FluidSystem::phaseIsActive(ig);
132 const auto haveWat = FluidSystem::phaseIsActive(iw);
134 auto weightedPhaseDensity = [&fs](
const auto ip)
136 return fs.saturation(ip).value() * fs.density(ip).value();
139 if (haveOil) { sourceTerms.set(Item::Pressure, fs.pressure(io).value()); }
140 else if (haveGas) { sourceTerms.set(Item::Pressure, fs.pressure(ig).value()); }
141 else { sourceTerms.set(Item::Pressure, fs.pressure(iw).value()); }
145 if (haveOil) { rho += weightedPhaseDensity(io); }
146 if (haveGas) { rho += weightedPhaseDensity(ig); }
147 if (haveWat) { rho += weightedPhaseDensity(iw); }
149 sourceTerms.set(Item::MixtureDensity, rho);
154 template<
typename TypeTag>
159 extractLegacyCellPvtRegionIndex_();
160 extractLegacyDepth_();
162 gravity_ = simulator_.problem().gravity()[2];
164 this->initial_step_ =
true;
167 simulator_.model().addAuxiliaryModule(
this);
169 is_cell_perforated_.resize(local_num_cells_,
false);
173 template<
typename TypeTag>
178 const uint64_t effective_events_mask = ScheduleEvents::WELL_STATUS_CHANGE
179 + ScheduleEvents::NEW_WELL;
180 const auto& events = this->schedule()[reportStepIdx].wellgroup_events();
181 for (
auto& wellPtr : this->well_container_) {
182 const bool well_opened_this_step = this->report_step_starts_ &&
183 events.hasEvent(wellPtr->name(),
184 effective_events_mask);
185 wellPtr->init(this->depth_, this->gravity_,
186 this->B_avg_, well_opened_this_step);
190 template<
typename TypeTag>
197 this->report_step_starts_ =
true;
198 this->report_step_start_events_ = this->schedule()[timeStepIdx].wellgroup_events();
200 this->rateConverter_ = std::make_unique<RateConverterType>
201 (std::vector<int>(this->local_num_cells_, 0));
205 const auto enableWellPIScaling =
true;
206 this->initializeLocalWellStructure(timeStepIdx, enableWellPIScaling);
209 this->initializeGroupStructure(timeStepIdx);
211 const auto& comm = this->simulator_.vanguard().grid().comm();
217 this->rateConverter_->template defineState<ElementContext>(this->simulator_);
221 const auto& sched_state = this->schedule()[timeStepIdx];
223 this->vfp_properties_ = std::make_unique<VFPProperties<Scalar, IndexTraits>>
224 (sched_state.vfpinj(), sched_state.vfpprod(), this->wellState());
228 "beginReportStep() failed: ",
229 this->terminal_output_, comm)
233 this->commitWGState();
235 this->wellStructureChangedDynamically_ =
false;
242 template <
typename TypeTag>
246 const bool enableWellPIScaling)
250 const auto& comm = this->simulator_.vanguard().grid().comm();
253 this->wells_ecl_ = this->getLocalWells(reportStepIdx);
254 this->local_parallel_well_info_ =
255 this->createLocalParallelWellInfo(this->wells_ecl_);
262 this->initializeWellPerfData();
263 this->initializeWellState(reportStepIdx);
264 this->wbp_.initializeWBPCalculationService();
266 if (this->param_.use_multisegment_well_ && this->anyMSWellOpenLocal()) {
267 this->wellState().initWellStateMSWell(this->wells_ecl_, &this->prevWellState());
270 this->initializeWellProdIndCalculators();
272 if (enableWellPIScaling && this->schedule()[reportStepIdx].events()
273 .hasEvent(ScheduleEvents::Events::WELL_PRODUCTIVITY_INDEX))
275 this->runWellPIScaling(reportStepIdx, local_deferredLogger);
279 "Failed to initialize local well structure: ",
280 this->terminal_output_, comm)
287 template <
typename TypeTag>
294 const auto& comm = this->simulator_.vanguard().grid().comm();
298 const auto& fieldGroup =
299 this->schedule().getGroup(
"FIELD", reportStepIdx);
301 WellGroupHelpersType::setCmodeGroup(fieldGroup,
303 this->summaryState(),
309 if (this->schedule()[reportStepIdx].has_gpmaint()) {
310 WellGroupHelpersType::setRegionAveragePressureCalculator(fieldGroup,
313 this->eclState_.fieldProps(),
314 this->regionalAveragePressureCalculator_);
318 "Failed to initialize group structure: ",
319 this->terminal_output_, comm)
327 template<
typename TypeTag>
332 OPM_TIMEBLOCK(beginTimeStep);
334 this->updateAverageFormationFactor();
338 this->switched_prod_groups_.clear();
339 this->switched_inj_groups_.clear();
341 if (this->wellStructureChangedDynamically_) {
346 const auto reportStepIdx =
347 this->simulator_.episodeIndex();
351 const auto enableWellPIScaling =
false;
353 this->initializeLocalWellStructure(reportStepIdx, enableWellPIScaling);
354 this->initializeGroupStructure(reportStepIdx);
356 this->commitWGState();
362 this->wellStructureChangedDynamically_ =
false;
365 this->resetWGState();
367 const int reportStepIdx = simulator_.episodeIndex();
368 this->updateAndCommunicateGroupData(reportStepIdx,
369 simulator_.model().newtonMethod().numIterations(),
370 param_.nupcol_group_rate_tolerance_,
false,
371 local_deferredLogger);
373 this->wellState().updateWellsDefaultALQ(this->schedule(), reportStepIdx, this->summaryState());
374 this->wellState().gliftTimeStepInit();
376 const double simulationTime = simulator_.time();
380 wellTesting(reportStepIdx, simulationTime, local_deferredLogger);
383 createWellContainer(reportStepIdx);
386 const Grid& grid = simulator_.vanguard().grid();
387 this->wells_active_ = grid.comm().max(!this->well_container_.empty());
392 this->initWellContainer(reportStepIdx);
395 std::fill(is_cell_perforated_.begin(), is_cell_perforated_.end(),
false);
396 for (
auto& well : well_container_) {
397 well->updatePerforatedCell(is_cell_perforated_);
401 this->calculateEfficiencyFactors(reportStepIdx);
403 if constexpr (has_polymer_)
405 if (PolymerModule::hasPlyshlog() || getPropValue<TypeTag, Properties::EnablePolymerMW>() ) {
406 this->setRepRadiusPerfLength();
413 this->terminal_output_, simulator_.vanguard().grid().comm());
415 for (
auto& well : well_container_) {
416 well->setVFPProperties(this->vfp_properties_.get());
417 well->setGuideRate(&this->guideRate_);
420 this->updateFiltrationModelsPreStep(local_deferredLogger);
423 for (
auto& well : well_container_) {
424 well->closeCompletions(this->wellTestState());
430 if (alternative_well_rate_init_) {
435 for (
const auto& well : well_container_) {
436 if (well->isProducer() && !well->wellIsStopped()) {
437 well->initializeProducerWellState(simulator_, this->wellState(), local_deferredLogger);
442 for (
const auto& well : well_container_) {
443 if (well->isVFPActive(local_deferredLogger)){
444 well->setPrevSurfaceRates(this->wellState(), this->prevWellState());
448 this->updateWellPotentials(reportStepIdx,
450 simulator_.vanguard().summaryConfig(),
451 local_deferredLogger);
452 }
catch ( std::runtime_error& e ) {
453 const std::string msg =
"A zero well potential is returned for output purposes. ";
454 local_deferredLogger.
warning(
"WELL_POTENTIAL_CALCULATION_FAILED", msg);
456 this->guide_rate_handler_.setLogger(&local_deferredLogger);
457#ifdef RESERVOIR_COUPLING_ENABLED
458 if (this->isReservoirCouplingMaster()) {
459 this->guide_rate_handler_.receiveMasterGroupPotentialsFromSlaves();
463 this->guide_rate_handler_.updateGuideRates(
464 reportStepIdx, simulationTime, this->wellState(), this->groupState()
466#ifdef RESERVOIR_COUPLING_ENABLED
467 if (this->isReservoirCouplingSlave()) {
468 this->guide_rate_handler_.sendSlaveGroupPotentialsToMaster(this->groupState());
474 if (this->schedule_[reportStepIdx].has_gpmaint()) {
475 for (
const auto& calculator : regionalAveragePressureCalculator_) {
476 calculator.second->template defineState<ElementContext>(simulator_);
478 const double dt = simulator_.timeStepSize();
479 const Group& fieldGroup = this->schedule().getGroup(
"FIELD", reportStepIdx);
482 regionalAveragePressureCalculator_,
489 this->updateAndCommunicateGroupData(reportStepIdx,
490 simulator_.model().newtonMethod().numIterations(),
491 param_.nupcol_group_rate_tolerance_,
493 local_deferredLogger);
496 for (
auto& well : well_container_) {
497 const uint64_t effective_events_mask = ScheduleEvents::WELL_STATUS_CHANGE
498 + ScheduleEvents::INJECTION_TYPE_CHANGED
499 + ScheduleEvents::WELL_SWITCHED_INJECTOR_PRODUCER
500 + ScheduleEvents::NEW_WELL;
502 const auto& events = this->schedule()[reportStepIdx].wellgroup_events();
503 const bool event = this->report_step_starts_ && events.hasEvent(well->name(), effective_events_mask);
504 const bool dyn_status_change = this->wellState().well(well->name()).status
505 != this->prevWellState().well(well->name()).status;
507 if (event || dyn_status_change) {
509 well->updateWellStateWithTarget(simulator_, this->groupState(), this->wellState(), local_deferredLogger);
510 well->calculateExplicitQuantities(simulator_, this->wellState(), local_deferredLogger);
511 well->solveWellEquation(simulator_, this->wellState(), this->groupState(), local_deferredLogger);
512 }
catch (
const std::exception& e) {
513 const std::string msg =
"Compute initial well solution for new well " + well->name() +
" failed. Continue with zero initial rates";
514 local_deferredLogger.
warning(
"WELL_INITIAL_SOLVE_FAILED", msg);
523 const std::string msg =
"Compute initial well solution for new wells failed. Continue with zero initial rates";
524 local_deferredLogger.
warning(
"WELL_INITIAL_SOLVE_FAILED", msg);
527 const auto& comm = simulator_.vanguard().grid().comm();
529 exc_type,
"beginTimeStep() failed: " + exc_msg, this->terminal_output_, comm);
533 template<
typename TypeTag>
536 const double simulationTime,
539 for (
const std::string& well_name : this->getWellsForTesting(timeStepIdx, simulationTime)) {
540 const Well& wellEcl = this->schedule().getWell(well_name, timeStepIdx);
541 if (wellEcl.getStatus() == Well::Status::SHUT)
544 WellInterfacePtr well = createWellForWellTest(well_name, timeStepIdx, deferred_logger);
546 well->init(depth_, gravity_, B_avg_,
true);
548 Scalar well_efficiency_factor = wellEcl.getEfficiencyFactor() *
549 this->wellState().getGlobalEfficiencyScalingFactor(well_name);
550 WellGroupHelpersType::accumulateGroupEfficiencyFactor(this->schedule().getGroup(wellEcl.groupName(),
554 well_efficiency_factor);
556 well->setWellEfficiencyFactor(well_efficiency_factor);
557 well->setVFPProperties(this->vfp_properties_.get());
558 well->setGuideRate(&this->guideRate_);
561 if (well->isProducer() && alternative_well_rate_init_) {
562 well->initializeProducerWellState(simulator_, this->wellState(), deferred_logger);
564 if (well->isVFPActive(deferred_logger)) {
565 well->setPrevSurfaceRates(this->wellState(), this->prevWellState());
568 const auto& network = this->schedule()[timeStepIdx].network();
569 if (network.active() && !this->node_pressures_.empty()) {
570 if (well->isProducer()) {
571 const auto it = this->node_pressures_.find(well->wellEcl().groupName());
572 if (it != this->node_pressures_.end()) {
575 const Scalar nodal_pressure = it->second;
576 well->setDynamicThpLimit(nodal_pressure);
582 GLiftEclWells ecl_well_map;
583 gaslift_.initGliftEclWellMap(well_container_, ecl_well_map);
584 well->wellTesting(simulator_,
588 this->wellTestState(),
590 this->well_open_times_,
592 }
catch (
const std::exception& e) {
593 const std::string msg = fmt::format(
"Exception during testing of well: {}. The well will not open.\n Exception message: {}", wellEcl.name(), e.what());
594 deferred_logger.
warning(
"WELL_TESTING_FAILED", msg);
604 template<
typename TypeTag>
610 for (
auto&& pinfo : this->local_parallel_well_info_)
621 template<
typename TypeTag>
631 template<
typename TypeTag>
636 this->closed_this_step_.clear();
639 this->report_step_starts_ =
false;
640 const int reportStepIdx = simulator_.episodeIndex();
643 for (
const auto& well : well_container_) {
644 if (getPropValue<TypeTag, Properties::EnablePolymerMW>() && well->isInjector()) {
645 well->updateWaterThroughput(dt, this->wellState());
649 for (
const auto& well : well_container_) {
650 well->updateConnectionTransmissibilityFactor(simulator_, this->wellState().well(well->indexOfWell()));
651 well->updateConnectionDFactor(simulator_, this->wellState().well(well->indexOfWell()));
654 if (Indices::waterEnabled) {
655 this->updateFiltrationModelsPostStep(dt, FluidSystem::waterPhaseIdx, local_deferredLogger);
659 this->updateInjMult(local_deferredLogger);
662 for (
const auto& well : well_container_) {
663 well->reportWellSwitching(this->wellState().well(well->indexOfWell()), local_deferredLogger);
666 if (this->terminal_output_) {
667 this->reportGroupSwitching(local_deferredLogger);
671 rateConverter_->template defineState<ElementContext>(simulator_);
675 this->updateWellPotentials(reportStepIdx,
677 simulator_.vanguard().summaryConfig(),
678 local_deferredLogger);
679 }
catch ( std::runtime_error& e ) {
680 const std::string msg =
"A zero well potential is returned for output purposes. ";
681 local_deferredLogger.
warning(
"WELL_POTENTIAL_CALCULATION_FAILED", msg);
684 updateWellTestState(simulationTime, this->wellTestState());
687 const Group& fieldGroup = this->schedule_.getGroup(
"FIELD", reportStepIdx);
688 this->checkGEconLimits(fieldGroup, simulationTime,
689 simulator_.episodeIndex(), local_deferredLogger);
690 this->checkGconsaleLimits(fieldGroup, this->wellState(),
691 simulator_.episodeIndex(), local_deferredLogger);
693 this->calculateProductivityIndexValues(local_deferredLogger);
695 this->commitWGState();
699 if (this->terminal_output_) {
704 this->computeWellTemperature();
708 template<
typename TypeTag>
712 unsigned elemIdx)
const
716 if (!is_cell_perforated_[elemIdx]) {
720 for (
const auto& well : well_container_)
721 well->addCellRates(rate, elemIdx);
725 template<
typename TypeTag>
726 template <
class Context>
730 const Context& context,
732 unsigned timeIdx)
const
735 int elemIdx = context.globalSpaceIndex(spaceIdx, timeIdx);
737 if (!is_cell_perforated_[elemIdx]) {
741 for (
const auto& well : well_container_)
742 well->addCellRates(rate, elemIdx);
747 template<
typename TypeTag>
752 const auto pressIx = []()
754 if (Indices::oilEnabled) {
return FluidSystem::oilPhaseIdx; }
755 if (Indices::waterEnabled) {
return FluidSystem::waterPhaseIdx; }
757 return FluidSystem::gasPhaseIdx;
760 auto cellPressures = std::vector<Scalar>(this->local_num_cells_,
Scalar{0});
761 auto cellTemperatures = std::vector<Scalar>(this->local_num_cells_,
Scalar{0});
764 const auto& gridView = this->simulator_.vanguard().gridView();
767 for (
const auto& elem : elements(gridView, Dune::Partitions::interior)) {
768 elemCtx.updatePrimaryStencil(elem);
769 elemCtx.updatePrimaryIntensiveQuantities(0);
771 const auto ix = elemCtx.globalSpaceIndex(0, 0);
772 const auto& fs = elemCtx.intensiveQuantities(0, 0).fluidState();
774 cellPressures[ix] = fs.pressure(pressIx).value();
775 cellTemperatures[ix] = fs.temperature(0).value();
778 this->simulator_.vanguard().grid().comm());
780 this->wellState().init(cellPressures, cellTemperatures, this->schedule(), this->wells_ecl_,
781 this->local_parallel_well_info_, timeStepIdx,
782 &this->prevWellState(), this->well_perf_data_,
783 this->summaryState(), simulator_.vanguard().enableDistributedWells());
790 template<
typename TypeTag>
797 const int nw = this->numLocalWells();
799 well_container_.clear();
802 well_container_.reserve(nw);
804 const auto& wmatcher = this->schedule().wellMatcher(report_step);
805 const auto& wcycle = this->schedule()[report_step].wcycle.get();
809 std::for_each(this->wells_ecl_.begin(), this->wells_ecl_.end(),
810 [
this, &wg_events = this->report_step_start_events_](
const auto& well_ecl)
812 if (!well_ecl.hasConnections()) {
817 constexpr auto events_mask = ScheduleEvents::WELL_STATUS_CHANGE |
818 ScheduleEvents::REQUEST_OPEN_WELL;
819 const bool well_status_change =
820 this->report_step_starts_ &&
821 wg_events.hasEvent(well_ecl.name(), events_mask);
822 if (well_status_change) {
823 if (well_ecl.getStatus() == WellStatus::OPEN) {
824 this->well_open_times_.insert_or_assign(well_ecl.name(),
825 this->simulator_.time());
826 this->well_close_times_.erase(well_ecl.name());
827 }
else if (well_ecl.getStatus() == WellStatus::SHUT) {
828 this->well_close_times_.insert_or_assign(well_ecl.name(),
829 this->simulator_.time());
830 this->well_open_times_.erase(well_ecl.name());
836 const auto cycle_states = wcycle.wellStatus(this->simulator_.time(),
838 this->well_open_times_,
839 this->well_close_times_);
841 for (
int w = 0; w < nw; ++w) {
842 const Well& well_ecl = this->wells_ecl_[w];
844 if (!well_ecl.hasConnections()) {
849 const std::string& well_name = well_ecl.name();
850 const auto well_status = this->schedule()
851 .getWell(well_name, report_step).getStatus();
853 if ((well_ecl.getStatus() == Well::Status::SHUT) ||
854 (well_status == Well::Status::SHUT))
857 if (well_ecl.getStatus() != Well::Status::SHUT) {
858 this->closed_this_step_.insert(well_name);
859 this->wellState().shutWell(w);
862 this->well_open_times_.erase(well_name);
863 this->well_close_times_.erase(well_name);
868 if (this->wellTestState().well_is_closed(well_name)) {
873 const bool closed_this_step = (this->wellTestState().lastTestTime(well_name) == simulator_.time());
876 auto& events = this->wellState().well(w).events;
877 if (events.hasEvent(ScheduleEvents::REQUEST_OPEN_WELL)) {
878 if (!closed_this_step) {
879 this->wellTestState().open_well(well_name);
880 this->wellTestState().open_completions(well_name);
881 this->well_open_times_.insert_or_assign(well_name,
882 this->simulator_.time());
883 this->well_close_times_.erase(well_name);
885 events.clearEvent(ScheduleEvents::REQUEST_OPEN_WELL);
891 bool wellIsStopped =
false;
892 if (this->wellTestState().well_is_closed(well_name))
894 if (well_ecl.getAutomaticShutIn()) {
896 this->wellState().shutWell(w);
897 this->well_close_times_.erase(well_name);
898 this->well_open_times_.erase(well_name);
901 if (!well_ecl.getAllowCrossFlow()) {
904 this->wellState().shutWell(w);
905 this->well_close_times_.erase(well_name);
906 this->well_open_times_.erase(well_name);
910 this->wellState().stopWell(w);
911 wellIsStopped =
true;
916 if (!well_ecl.getAllowCrossFlow()) {
917 const bool any_zero_rate_constraint = well_ecl.isProducer()
918 ? well_ecl.productionControls(this->summaryState_).anyZeroRateConstraint()
919 : well_ecl.injectionControls(this->summaryState_).anyZeroRateConstraint();
920 if (any_zero_rate_constraint) {
922 local_deferredLogger.
debug(fmt::format(
" Well {} gets shut due to having zero rate constraint and disallowing crossflow ", well_ecl.name()) );
923 this->wellState().shutWell(w);
924 this->well_close_times_.erase(well_name);
925 this->well_open_times_.erase(well_name);
930 if (well_status == Well::Status::STOP) {
931 this->wellState().stopWell(w);
932 this->well_close_times_.erase(well_name);
933 this->well_open_times_.erase(well_name);
934 wellIsStopped =
true;
937 if (!wcycle.empty()) {
938 const auto it = cycle_states.find(well_name);
939 if (it != cycle_states.end()) {
941 this->wellState().shutWell(w);
944 this->wellState().openWell(w);
949 well_container_.emplace_back(this->createWellPointer(w, report_step));
952 well_container_.back()->stopWell();
953 this->well_close_times_.erase(well_name);
954 this->well_open_times_.erase(well_name);
958 if (!wcycle.empty()) {
959 const auto schedule_open =
960 [&wg_events = this->report_step_start_events_](
const std::string& name)
962 return wg_events.hasEvent(name, ScheduleEvents::REQUEST_OPEN_WELL);
964 for (
const auto& [wname, wscale] : wcycle.efficiencyScale(this->simulator_.time(),
965 this->simulator_.timeStepSize(),
967 this->well_open_times_,
970 this->wellState().updateEfficiencyScalingFactor(wname, wscale);
971 this->schedule_.add_event(ScheduleEvents::WELLGROUP_EFFICIENCY_UPDATE, report_step);
980 if (this->terminal_output_) {
984 this->well_container_generic_.clear();
985 for (
auto& w : well_container_)
986 this->well_container_generic_.push_back(w.get());
988 const auto& network = this->schedule()[report_step].network();
989 if (network.active() && !this->node_pressures_.empty()) {
990 for (
auto& well: this->well_container_generic_) {
994 if (well->isProducer()) {
995 const auto it = this->node_pressures_.find(well->wellEcl().groupName());
996 if (it != this->node_pressures_.end()) {
999 const Scalar nodal_pressure = it->second;
1000 well->setDynamicThpLimit(nodal_pressure);
1006 this->wbp_.registerOpenWellsForWBPCalculation();
1013 template <
typename TypeTag>
1014 typename BlackoilWellModel<TypeTag>::WellInterfacePtr
1018 const auto is_multiseg = this->wells_ecl_[wellID].isMultiSegment();
1020 if (! (this->param_.use_multisegment_well_ && is_multiseg)) {
1021 return this->
template createTypedWellPointer<StandardWell<TypeTag>>(wellID, report_step);
1024 return this->
template createTypedWellPointer<MultisegmentWell<TypeTag>>(wellID, report_step);
1032 template <
typename TypeTag>
1033 template <
typename WellType>
1034 std::unique_ptr<WellType>
1039 const auto& perf_data = this->well_perf_data_[wellID];
1042 const auto pvtreg = perf_data.
empty()
1043 ? 0 : this->pvt_region_idx_[perf_data.front().cell_index];
1045 const auto& parallel_well_info = this->local_parallel_well_info_[wellID].get();
1046 const auto global_pvtreg = parallel_well_info.broadcastFirstPerforationValue(pvtreg);
1048 return std::make_unique<WellType>(this->wells_ecl_[wellID],
1052 *this->rateConverter_,
1054 this->numConservationQuantities(),
1064 template<
typename TypeTag>
1068 const int report_step,
1072 const auto it = std::find_if(this->wells_ecl_.begin(),
1073 this->wells_ecl_.end(),
1074 [&well_name](
const auto& w)
1075 { return well_name == w.name(); });
1077 if (it == this->wells_ecl_.end()) {
1079 fmt::format(
"Could not find well {} in wells_ecl ", well_name),
1083 const int pos =
static_cast<int>(std::distance(this->wells_ecl_.begin(), it));
1084 return this->createWellPointer(pos, report_step);
1089 template<
typename TypeTag>
1095 const double dt = this->simulator_.timeStepSize();
1097 auto& well_state = this->wellState();
1099 const bool changed_well_group = updateWellControlsAndNetwork(
true, dt, deferred_logger);
1100 assembleWellEqWithoutIteration(dt, deferred_logger);
1101 const bool converged = this->getWellConvergence(this->B_avg_,
true).converged() && !changed_well_group;
1104 for (
auto& well : this->well_container_) {
1105 well->solveEqAndUpdateWellState(simulator_, well_state, deferred_logger);
1108 this->simulator_.vanguard().grid().comm());
1111 const std::string msg = fmt::format(
"Initial (pre-step) network balance did not converge.");
1119 template<
typename TypeTag>
1128 this->guide_rate_handler_.setLogger(&local_deferredLogger);
1130 if (gaslift_.terminalOutput()) {
1131 const std::string msg =
1132 fmt::format(
"assemble() : iteration {}" , iterationIdx);
1133 gaslift_.gliftDebug(msg, local_deferredLogger);
1137 Dune::Timer perfTimer;
1139 this->closed_offending_wells_.clear();
1142 const int episodeIdx = simulator_.episodeIndex();
1143 const auto& network = this->schedule()[episodeIdx].network();
1144 if (!this->wellsActive() && !network.active()) {
1149 if (iterationIdx == 0 && this->wellsActive()) {
1150 OPM_TIMEBLOCK(firstIterationAssmble);
1157 calculateExplicitQuantities(local_deferredLogger);
1158 prepareTimeStep(local_deferredLogger);
1161 "assemble() failed (It=0): ",
1162 this->terminal_output_, grid().comm());
1165 const bool well_group_control_changed = updateWellControlsAndNetwork(
false, dt, local_deferredLogger);
1169 if ( ! this->wellsActive() ) {
1173 assembleWellEqWithoutIteration(dt, local_deferredLogger);
1177 last_report_.well_group_control_changed = well_group_control_changed;
1178 last_report_.assemble_time_well += perfTimer.stop();
1184 template<
typename TypeTag>
1193 bool do_network_update =
true;
1194 bool well_group_control_changed =
false;
1195 Scalar network_imbalance = 0.0;
1197 const std::size_t iteration_to_relax = param_.network_max_strict_outer_iterations_;
1199 const std::size_t max_iteration = param_.network_max_outer_iterations_;
1200 std::size_t network_update_iteration = 0;
1201 while (do_network_update) {
1202 if (network_update_iteration >= max_iteration ) {
1204 const int episodeIdx = simulator_.episodeIndex();
1205 const int iterationIdx = simulator_.model().newtonMethod().numIterations();
1206 if (this->shouldBalanceNetwork(episodeIdx, iterationIdx + 1)) {
1207 const std::string msg = fmt::format(
"Maximum of {:d} network iterations has been used and we stop the update, \n"
1208 "and try again after the next Newton iteration (imbalance = {:.2e} bar, ctrl_change = {})",
1209 max_iteration, network_imbalance*1.0e-5, well_group_control_changed);
1210 local_deferredLogger.
debug(msg);
1212 if (this->terminal_output_) {
1213 const std::string msg = fmt::format(
"Maximum of {:d} network iterations has been used and we stop the update. \n"
1214 "The simulator will continue with unconverged network results (imbalance = {:.2e} bar, ctrl_change = {})",
1215 max_iteration, network_imbalance*1.0e-5, well_group_control_changed);
1216 local_deferredLogger.
info(msg);
1221 if (this->terminal_output_ && (network_update_iteration == iteration_to_relax) ) {
1222 local_deferredLogger.
debug(
"We begin using relaxed tolerance for network update now after " +
std::to_string(iteration_to_relax) +
" iterations ");
1224 const bool relax_network_balance = network_update_iteration >= iteration_to_relax;
1226 const bool optimize_gas_lift = ( (network_update_iteration + 1) < std::max(max_iteration,
static_cast<std::size_t
>(2)) );
1227 std::tie(well_group_control_changed, do_network_update, network_imbalance) =
1228 updateWellControlsAndNetworkIteration(mandatory_network_balance, relax_network_balance, optimize_gas_lift, dt,local_deferredLogger);
1229 ++network_update_iteration;
1231 return well_group_control_changed;
1237 template<
typename TypeTag>
1238 std::tuple<bool, bool, typename BlackoilWellModel<TypeTag>::Scalar>
1241 const bool relax_network_tolerance,
1242 const bool optimize_gas_lift,
1247 const int iterationIdx = simulator_.model().newtonMethod().numIterations();
1248 const int reportStepIdx = simulator_.episodeIndex();
1249 this->updateAndCommunicateGroupData(reportStepIdx, iterationIdx,
1250 param_.nupcol_group_rate_tolerance_,
true, local_deferredLogger);
1251 const auto [more_inner_network_update, network_imbalance] =
1252 updateNetworks(mandatory_network_balance,
1253 local_deferredLogger,
1254 relax_network_tolerance);
1256 bool well_group_control_changed = updateWellControls(local_deferredLogger);
1258 bool alq_updated =
false;
1261 if (optimize_gas_lift) {
1264 const bool updatePotentials = (this->shouldBalanceNetwork(reportStepIdx, iterationIdx) || mandatory_network_balance);
1265 alq_updated = gaslift_.maybeDoGasLiftOptimize(simulator_,
1267 this->node_pressures_,
1271 local_deferredLogger);
1273 prepareWellsBeforeAssembling(dt, local_deferredLogger);
1276 "updateWellControlsAndNetworkIteration() failed: ",
1277 this->terminal_output_, grid().comm());
1281 guideRateUpdateIsNeeded(reportStepIdx)) {
1282 const double simulationTime = simulator_.time();
1286 this->guide_rate_handler_.updateGuideRates(
1287 reportStepIdx, simulationTime, this->wellState(), this->groupState()
1292 const bool more_network_update = this->shouldBalanceNetwork(reportStepIdx, iterationIdx) &&
1293 (more_inner_network_update || well_group_control_changed || alq_updated);
1294 return {well_group_control_changed, more_network_update, network_imbalance};
1300 template <
typename TypeTag>
1306 const int reportStepIdx = this->simulator_.episodeIndex();
1307 const auto& network = this->schedule()[reportStepIdx].network();
1308 const auto& balance = this->schedule()[reportStepIdx].network_balance();
1309 const Scalar thp_tolerance = balance.thp_tolerance();
1311 if (!network.active()) {
1315 auto& well_state = this->wellState();
1316 auto& group_state = this->groupState();
1318 bool well_group_thp_updated =
false;
1319 for (
const std::string& nodeName : network.node_names()) {
1320 const bool has_choke = network.node(nodeName).as_choke();
1322 const auto& summary_state = this->simulator_.vanguard().summaryState();
1323 const Group& group = this->schedule().getGroup(nodeName, reportStepIdx);
1326 std::vector<Scalar> resv_coeff(Indices::numPhases, 1.0);
1327 Scalar gratTargetFromSales = 0.0;
1328 if (group_state.has_grat_sales_target(group.name()))
1329 gratTargetFromSales = group_state.grat_sales_target(group.name());
1331 const auto ctrl = group.productionControls(summary_state);
1332 auto cmode_tmp = ctrl.cmode;
1334 bool fld_none =
false;
1339 const Scalar efficiencyFactor = 1.0;
1340 const Group& parentGroup = this->schedule().getGroup(group.parent(), reportStepIdx);
1352 local_deferredLogger);
1353 target_tmp = target.first;
1354 cmode_tmp = target.second;
1356 const auto cmode = cmode_tmp;
1358 TargetCalculatorType tcalc(cmode, FluidSystem::phaseUsage(), resv_coeff,
1359 gratTargetFromSales, nodeName, group_state,
1360 group.has_gpmaint_control(cmode));
1364 target_tmp = tcalc.groupTarget(ctrl, local_deferredLogger);
1367 const Scalar orig_target = target_tmp;
1369 auto mismatch = [&] (
auto group_thp) {
1372 for (
auto& well : this->well_container_) {
1373 std::string well_name = well->name();
1374 auto& ws = well_state.well(well_name);
1375 if (group.hasWell(well_name)) {
1376 well->setDynamicThpLimit(group_thp);
1377 const Well& well_ecl = this->wells_ecl_[well->indexOfWell()];
1378 const auto inj_controls = Well::InjectionControls(0);
1379 const auto prod_controls = well_ecl.productionControls(summary_state);
1380 well->iterateWellEqWithSwitching(this->simulator_, dt, inj_controls, prod_controls, well_state, group_state, local_deferredLogger,
false,
false);
1381 rate = -tcalc.calcModeRateFromRates(ws.surface_rates);
1385 return (group_rate - orig_target)/orig_target;
1388 const auto upbranch = network.uptree_branch(nodeName);
1389 const auto it = this->node_pressures_.find((*upbranch).uptree_node());
1390 const Scalar nodal_pressure = it->second;
1391 Scalar well_group_thp = nodal_pressure;
1393 std::optional<Scalar> autochoke_thp;
1394 if (
auto iter = this->well_group_thp_calc_.find(nodeName); iter != this->well_group_thp_calc_.end()) {
1395 autochoke_thp = this->well_group_thp_calc_.at(nodeName);
1400 std::array<Scalar, 2> range_initial;
1401 if (!autochoke_thp.has_value()){
1404 std::string node_name = nodeName;
1405 while (!network.node(node_name).terminal_pressure().has_value()) {
1406 auto branch = network.uptree_branch(node_name).value();
1407 node_name = branch.uptree_node();
1409 min_thp = network.node(node_name).terminal_pressure().value();
1410 WellBhpThpCalculatorType::bruteForceBracketCommonTHP(mismatch, min_thp, max_thp);
1413 std::array<Scalar, 2> range = {
Scalar{0.9}*min_thp,
Scalar{1.1}*max_thp};
1414 std::optional<Scalar> appr_sol;
1415 WellBhpThpCalculatorType::bruteForceBracketCommonTHP(mismatch, range, low1, high1, appr_sol, 0.0, local_deferredLogger);
1418 range_initial = {min_thp, max_thp};
1421 if (!autochoke_thp.has_value() || autochoke_thp.value() > nodal_pressure) {
1423 std::array<Scalar, 2> range = autochoke_thp.has_value() ?
1424 std::array<Scalar, 2>{
Scalar{0.9} * autochoke_thp.value(),
1425 Scalar{1.1} * autochoke_thp.value()} : range_initial;
1427 std::optional<Scalar> approximate_solution;
1428 const Scalar tolerance1 = thp_tolerance;
1429 local_deferredLogger.
debug(
"Using brute force search to bracket the group THP");
1430 const bool finding_bracket = WellBhpThpCalculatorType::bruteForceBracketCommonTHP(mismatch, range, low, high, approximate_solution, tolerance1, local_deferredLogger);
1432 if (approximate_solution.has_value()) {
1433 autochoke_thp = *approximate_solution;
1434 local_deferredLogger.
debug(
"Approximate group THP value found: " +
std::to_string(autochoke_thp.value()));
1435 }
else if (finding_bracket) {
1436 const Scalar tolerance2 = thp_tolerance;
1437 const int max_iteration_solve = 100;
1439 autochoke_thp = RegulaFalsiBisection<ThrowOnError>::
1440 solve(mismatch, low, high, max_iteration_solve, tolerance2, iteration);
1445 autochoke_thp.reset();
1446 local_deferredLogger.
debug(
"Group THP solve failed due to bracketing failure");
1449 if (autochoke_thp.has_value()) {
1450 well_group_thp_calc_[nodeName] = autochoke_thp.value();
1453 well_group_thp = std::max(autochoke_thp.value(), nodal_pressure);
1456 for (
auto& well : this->well_container_) {
1457 std::string well_name = well->name();
1459 if (well->isInjector() || !well->wellEcl().predictionMode())
1462 if (group.hasWell(well_name)) {
1463 well->setDynamicThpLimit(well_group_thp);
1465 const auto& ws = this->wellState().well(well->indexOfWell());
1466 const bool thp_is_limit = ws.production_cmode == Well::ProducerCMode::THP;
1468 well->prepareWellBeforeAssembling(this->simulator_, dt, this->wellState(), this->groupState(), local_deferredLogger);
1473 const auto& current_well_group_thp = group_state.is_autochoke_group(nodeName) ? group_state.well_group_thp(nodeName) : 1e30;
1474 if (std::abs(current_well_group_thp - well_group_thp) > balance.pressure_tolerance()) {
1475 well_group_thp_updated =
true;
1476 group_state.update_well_group_thp(nodeName, well_group_thp);
1480 return well_group_thp_updated;
1483 template<
typename TypeTag>
1489 for (
auto& well : well_container_) {
1490 well->assembleWellEq(simulator_, dt, this->wellState(), this->groupState(), deferred_logger);
1495 template<
typename TypeTag>
1501 for (
auto& well : well_container_) {
1502 well->prepareWellBeforeAssembling(simulator_, dt, this->wellState(), this->groupState(), deferred_logger);
1507 template<
typename TypeTag>
1517 for (
auto& well: well_container_) {
1518 well->assembleWellEqWithoutIteration(simulator_, dt, this->wellState(), this->groupState(),
1522 this->terminal_output_, grid().comm());
1526#if COMPILE_GPU_BRIDGE
1527 template<
typename TypeTag>
1535 for(
unsigned int i = 0; i < well_container_.size(); i++){
1536 auto& well = well_container_[i];
1537 std::shared_ptr<StandardWell<TypeTag> > derived = std::dynamic_pointer_cast<StandardWell<TypeTag> >(well);
1539 wellContribs.
addNumBlocks(derived->linSys().getNumBlocks());
1544 wellContribs.
alloc();
1546 for(
unsigned int i = 0; i < well_container_.size(); i++){
1547 auto& well = well_container_[i];
1549 auto derived_std = std::dynamic_pointer_cast<StandardWell<TypeTag>>(well);
1551 derived_std->linSys().extract(derived_std->numStaticWellEq, wellContribs);
1553 auto derived_ms = std::dynamic_pointer_cast<MultisegmentWell<TypeTag> >(well);
1555 derived_ms->linSys().extract(wellContribs);
1557 OpmLog::warning(
"Warning unknown type of well");
1564 template<
typename TypeTag>
1569 for (
const auto& well: well_container_ ) {
1574 template<
typename TypeTag>
1579 const bool use_well_weights)
const
1581 int nw = this->numLocalWellsEnd();
1582 int rdofs = local_num_cells_;
1583 for (
int i = 0; i < nw; i++ ) {
1584 int wdof = rdofs + i;
1585 jacobian[wdof][wdof] = 1.0;
1588 for (
const auto& well : well_container_) {
1589 well->addWellPressureEquations(jacobian,
1597 template <
typename TypeTag>
1600 const std::vector<typename SparseMatrixAdapter::MatrixBlock*>& diagMatAddress)
const
1605 for (
const auto& well : well_container_) {
1606 if (!well->isOperableAndSolvable() && !well->wellIsStopped()) {
1609 const auto& cells = well->cells();
1610 const auto& rates = well->connectionRates();
1611 for (
unsigned perfIdx = 0; perfIdx < rates.size(); ++perfIdx) {
1612 unsigned cellIdx = cells[perfIdx];
1613 auto rate = rates[perfIdx];
1616 using MatrixBlockType =
typename SparseMatrixAdapter::MatrixBlock;
1617 MatrixBlockType bMat(0.0);
1618 simulator_.model().linearizer().setResAndJacobi(res, bMat, rate);
1619 residual[cellIdx] += res;
1620 *diagMatAddress[cellIdx] += bMat;
1626 template<
typename TypeTag>
1631 int nw = this->numLocalWellsEnd();
1632 int rdofs = local_num_cells_;
1633 for (
int i = 0; i < nw; ++i) {
1634 int wdof = rdofs + i;
1635 jacobian.entry(wdof,wdof) = 1.0;
1637 const auto wellconnections = this->getMaxWellConnections();
1638 for (
int i = 0; i < nw; ++i) {
1639 const auto& perfcells = wellconnections[i];
1640 for (
int perfcell : perfcells) {
1641 int wdof = rdofs + i;
1642 jacobian.entry(wdof, perfcell) = 0.0;
1643 jacobian.entry(perfcell, wdof) = 0.0;
1649 template<
typename TypeTag>
1657 for (
const auto& well : well_container_) {
1658 const auto& cells = well->cells();
1659 x_local_.resize(cells.size());
1661 for (
size_t i = 0; i < cells.size(); ++i) {
1662 x_local_[i] = x[cells[i]];
1664 well->recoverWellSolutionAndUpdateWellState(simulator_, x_local_,
1665 this->wellState(), local_deferredLogger);
1669 "recoverWellSolutionAndUpdateWellState() failed: ",
1670 this->terminal_output_, simulator_.vanguard().grid().comm());
1674 template<
typename TypeTag>
1680 OPM_THROW(std::logic_error,
"Attempt to call NLDD method without a NLDD solver");
1683 return nldd_->recoverWellSolutionAndUpdateWellState(x, domainIdx);
1687 template<
typename TypeTag>
1690 getWellConvergence(
const std::vector<Scalar>& B_avg,
bool checkWellGroupControls)
const
1696 const int iterationIdx = simulator_.model().newtonMethod().numIterations();
1697 for (
const auto& well : well_container_) {
1698 if (well->isOperableAndSolvable() || well->wellIsStopped()) {
1699 local_report += well->getWellConvergence(
1700 simulator_, this->wellState(), B_avg, local_deferredLogger,
1701 iterationIdx > param_.strict_outer_iter_wells_);
1705 report.
setWellFailed({CR::WellFailure::Type::Unsolvable, CR::Severity::Normal, -1, well->name()});
1706 local_report += report;
1715 if (checkWellGroupControls) {
1719 if (this->terminal_output_) {
1724 if (f.severity() == ConvergenceReport::Severity::NotANumber) {
1725 OpmLog::debug(
"NaN residual found with phase " +
std::to_string(f.phase()) +
" for well " + f.wellName());
1726 }
else if (f.severity() == ConvergenceReport::Severity::TooLarge) {
1727 OpmLog::debug(
"Too large residual found with phase " +
std::to_string(f.phase()) +
" for well " + f.wellName());
1738 template<
typename TypeTag>
1744 for (
auto& well : well_container_) {
1753 template<
typename TypeTag>
1759 if (!this->wellsActive()) {
1762 const int episodeIdx = simulator_.episodeIndex();
1763 const int iterationIdx = simulator_.model().newtonMethod().numIterations();
1764 const auto& comm = simulator_.vanguard().grid().comm();
1766 bool changed_well_group =
false;
1767 const Group& fieldGroup = this->schedule().getGroup(
"FIELD", episodeIdx);
1770 const std::size_t max_iter = param_.well_group_constraints_max_iterations_;
1771 while(!changed_well_group && iter < max_iter) {
1772 changed_well_group = updateGroupControls(fieldGroup, deferred_logger, episodeIdx, iterationIdx);
1775 bool changed_well_to_group =
false;
1777 OPM_TIMEBLOCK(UpdateWellControls);
1781 for (
const auto& well : well_container_) {
1783 const bool changed_well = well->
updateWellControl(simulator_, mode, this->wellState(), this->groupState(), deferred_logger);
1785 changed_well_to_group = changed_well || changed_well_to_group;
1789 simulator_.gridView().comm());
1792 changed_well_to_group = comm.sum(
static_cast<int>(changed_well_to_group));
1793 if (changed_well_to_group) {
1794 updateAndCommunicate(episodeIdx, iterationIdx, deferred_logger);
1795 changed_well_group =
true;
1799 bool changed_well_individual =
false;
1804 for (
const auto& well : well_container_) {
1806 const bool changed_well = well->
updateWellControl(simulator_, mode, this->wellState(), this->groupState(), deferred_logger);
1808 changed_well_individual = changed_well || changed_well_individual;
1812 simulator_.gridView().comm());
1815 changed_well_individual = comm.sum(
static_cast<int>(changed_well_individual));
1816 if (changed_well_individual) {
1817 updateAndCommunicate(episodeIdx, iterationIdx, deferred_logger);
1818 changed_well_group =
true;
1824 this->updateWsolvent(fieldGroup, episodeIdx, this->nupcolWellState());
1826 return changed_well_group;
1830 template<
typename TypeTag>
1831 std::tuple<bool, typename BlackoilWellModel<TypeTag>::Scalar>
1835 const bool relax_network_tolerance)
1838 const int episodeIdx = simulator_.episodeIndex();
1839 const auto& network = this->schedule()[episodeIdx].network();
1840 if (!this->wellsActive() && !network.active()) {
1841 return {
false, 0.0};
1844 const int iterationIdx = simulator_.model().newtonMethod().numIterations();
1845 const auto& comm = simulator_.vanguard().grid().comm();
1848 Scalar network_imbalance = 0.0;
1849 bool more_network_update =
false;
1850 if (this->shouldBalanceNetwork(episodeIdx, iterationIdx) || mandatory_network_balance) {
1851 OPM_TIMEBLOCK(BalanceNetwork);
1852 const double dt = this->simulator_.timeStepSize();
1854 const bool well_group_thp_updated = computeWellGroupThp(dt, deferred_logger);
1855 const int max_number_of_sub_iterations = param_.network_max_sub_iterations_;
1856 const Scalar network_pressure_update_damping_factor = param_.network_pressure_update_damping_factor_;
1857 const Scalar network_max_pressure_update = param_.network_max_pressure_update_in_bars_ * unit::barsa;
1858 bool more_network_sub_update =
false;
1859 for (
int i = 0; i < max_number_of_sub_iterations; i++) {
1860 const auto local_network_imbalance = this->updateNetworkPressures(episodeIdx, network_pressure_update_damping_factor, network_max_pressure_update);
1861 network_imbalance = comm.max(local_network_imbalance);
1862 const auto& balance = this->schedule()[episodeIdx].network_balance();
1863 constexpr Scalar relaxation_factor = 10.0;
1864 const Scalar tolerance = relax_network_tolerance ? relaxation_factor * balance.pressure_tolerance() : balance.pressure_tolerance();
1865 more_network_sub_update = this->networkActive() && network_imbalance > tolerance;
1866 if (!more_network_sub_update)
1869 for (
const auto& well : well_container_) {
1870 if (well->isInjector() || !well->wellEcl().predictionMode())
1873 const auto it = this->node_pressures_.find(well->wellEcl().groupName());
1874 if (it != this->node_pressures_.end()) {
1875 const auto& ws = this->wellState().well(well->indexOfWell());
1876 const bool thp_is_limit = ws.production_cmode == Well::ProducerCMode::THP;
1878 well->prepareWellBeforeAssembling(this->simulator_, dt, this->wellState(), this->groupState(), deferred_logger);
1882 this->updateAndCommunicateGroupData(episodeIdx, iterationIdx, param_.nupcol_group_rate_tolerance_,
1883 true, deferred_logger);
1885 more_network_update = more_network_sub_update || well_group_thp_updated;
1887 return { more_network_update, network_imbalance };
1891 template<
typename TypeTag>
1895 const int iterationIdx,
1898 this->updateAndCommunicateGroupData(reportStepIdx,
1900 param_.nupcol_group_rate_tolerance_,
1908 for (
const auto& well : well_container_) {
1910 const auto& ws = this->wellState().well(well->indexOfWell());
1911 if (ws.production_cmode == Well::ProducerCMode::GRUP ||
1912 ws.injection_cmode == Well::InjectorCMode::GRUP)
1914 well->updateWellStateWithTarget(simulator_, this->groupState(),
1915 this->wellState(), deferred_logger);
1919 simulator_.gridView().comm())
1920 this->updateAndCommunicateGroupData(reportStepIdx,
1922 param_.nupcol_group_rate_tolerance_,
1927 template<
typename TypeTag>
1932 const int reportStepIdx,
1933 const int iterationIdx)
1936 bool changed =
false;
1938 const int nupcol = this->schedule()[reportStepIdx].nupcol();
1939 const int max_number_of_group_switches = param_.max_number_of_group_switches_;
1940 const bool update_group_switching_log = iterationIdx >= nupcol;
1941 const bool changed_hc = this->checkGroupHigherConstraints(group, deferred_logger, reportStepIdx, max_number_of_group_switches, update_group_switching_log);
1944 updateAndCommunicate(reportStepIdx, iterationIdx, deferred_logger);
1947 bool changed_individual =
1949 updateGroupIndividualControl(group,
1951 max_number_of_group_switches,
1952 update_group_switching_log,
1953 this->switched_inj_groups_,
1954 this->switched_prod_groups_,
1955 this->closed_offending_wells_,
1960 if (changed_individual) {
1962 updateAndCommunicate(reportStepIdx, iterationIdx, deferred_logger);
1965 for (
const std::string& groupName : group.groups()) {
1966 bool changed_this = updateGroupControls( this->schedule().getGroup(groupName, reportStepIdx), deferred_logger, reportStepIdx,iterationIdx);
1967 changed = changed || changed_this;
1972 template<
typename TypeTag>
1979 for (
const auto& well : well_container_) {
1980 const auto& wname = well->name();
1981 const auto wasClosed = wellTestState.well_is_closed(wname);
1982 well->checkWellOperability(simulator_,
1984 local_deferredLogger);
1985 const bool under_zero_target =
1986 well->wellUnderZeroGroupRateTarget(this->simulator_,
1988 local_deferredLogger);
1989 well->updateWellTestState(this->wellState().well(wname),
1994 local_deferredLogger);
1996 if (!wasClosed && wellTestState.well_is_closed(wname)) {
1997 this->closed_this_step_.insert(wname);
2001 for (
const auto& [group_name, to] : this->closed_offending_wells_) {
2002 if (this->hasOpenLocalWell(to.second) &&
2003 !this->wasDynamicallyShutThisTimeStep(to.second))
2005 wellTestState.close_well(to.second,
2006 WellTestConfig::Reason::GROUP,
2008 this->updateClosedWellsThisStep(to.second);
2009 const std::string msg =
2010 fmt::format(
"Procedure on exceeding {} limit is WELL for group {}. "
2016 local_deferredLogger.
info(msg);
2024 if (this->terminal_output_) {
2030 template<
typename TypeTag>
2034 std::string& exc_msg,
2039 const int np = this->numPhases();
2040 std::vector<Scalar> potentials;
2041 const auto& well = well_container_[widx];
2042 std::string cur_exc_msg;
2045 well->computeWellPotentials(simulator_, well_state_copy, potentials, deferred_logger);
2050 exc_msg += fmt::format(
"\nFor well {}: {}", well->name(), cur_exc_msg);
2052 exc_type = std::max(exc_type, cur_exc_type);
2056 auto& ws = this->wellState().well(well->indexOfWell());
2057 for (
int p = 0; p < np; ++p) {
2059 ws.well_potentials[p] = std::max(
Scalar{0.0}, potentials[p]);
2065 template <
typename TypeTag>
2070 for (
const auto& wellPtr : this->well_container_) {
2071 this->calculateProductivityIndexValues(wellPtr.get(), deferred_logger);
2079 template <
typename TypeTag>
2090 for (
const auto& shutWell : this->local_shut_wells_) {
2091 if (!this->wells_ecl_[shutWell].hasConnections()) {
2096 auto wellPtr = this->
template createTypedWellPointer
2099 wellPtr->
init(this->depth_, this->gravity_, this->B_avg_,
true);
2101 this->calculateProductivityIndexValues(wellPtr.get(), deferred_logger);
2109 template <
typename TypeTag>
2123 template<
typename TypeTag>
2129 const auto episodeIdx = simulator_.episodeIndex();
2130 this->updateNetworkActiveState(episodeIdx);
2134 const bool do_prestep_network_rebalance = param_.pre_solve_network_ && this->needPreStepNetworkRebalance(episodeIdx);
2136 for (
const auto& well : well_container_) {
2137 auto& events = this->wellState().well(well->indexOfWell()).events;
2139 well->updateWellStateWithTarget(simulator_, this->groupState(), this->wellState(), deferred_logger);
2140 well->updatePrimaryVariables(simulator_, this->wellState(), deferred_logger);
2146 if (events.hasEvent(ScheduleEvents::REQUEST_OPEN_WELL)) {
2147 events.clearEvent(ScheduleEvents::REQUEST_OPEN_WELL);
2150 if (param_.solve_welleq_initially_ && well->isOperableAndSolvable()) {
2152 well->solveWellEquation(simulator_, this->wellState(), this->groupState(), deferred_logger);
2153 }
catch (
const std::exception& e) {
2154 const std::string msg =
"Compute initial well solution for " + well->name() +
" initially failed. Continue with the previous rates";
2155 deferred_logger.
warning(
"WELL_INITIAL_SOLVE_FAILED", msg);
2160 well->resetWellOperability();
2162 updatePrimaryVariables(deferred_logger);
2165 if (do_prestep_network_rebalance) doPreStepNetworkRebalance(deferred_logger);
2168 template<
typename TypeTag>
2173 std::vector< Scalar > B_avg(numConservationQuantities(),
Scalar() );
2174 const auto& grid = simulator_.vanguard().grid();
2175 const auto& gridView = grid.leafGridView();
2179 for (
const auto& elem : elements(gridView, Dune::Partitions::interior)) {
2180 elemCtx.updatePrimaryStencil(elem);
2181 elemCtx.updatePrimaryIntensiveQuantities(0);
2183 const auto& intQuants = elemCtx.intensiveQuantities(0, 0);
2184 const auto& fs = intQuants.fluidState();
2186 for (
unsigned phaseIdx = 0; phaseIdx < FluidSystem::numPhases; ++phaseIdx)
2188 if (!FluidSystem::phaseIsActive(phaseIdx)) {
2192 const unsigned compIdx = FluidSystem::canonicalToActiveCompIdx(FluidSystem::solventComponentIndex(phaseIdx));
2193 auto& B = B_avg[ compIdx ];
2195 B += 1 / fs.invB(phaseIdx).value();
2197 if constexpr (has_solvent_) {
2198 auto& B = B_avg[solventSaturationIdx];
2199 B += 1 / intQuants.solventInverseFormationVolumeFactor().value();
2205 grid.comm().sum(B_avg.data(), B_avg.size());
2206 B_avg_.resize(B_avg.size());
2207 std::transform(B_avg.begin(), B_avg.end(), B_avg_.begin(),
2208 [gcells = global_num_cells_](
const auto bval)
2209 { return bval / gcells; });
2216 template<
typename TypeTag>
2221 for (
const auto& well : well_container_) {
2226 template<
typename TypeTag>
2230 const auto& grid = simulator_.vanguard().
grid();
2231 const auto& eclProblem = simulator_.problem();
2232 const unsigned numCells = grid.size(0);
2234 this->pvt_region_idx_.resize(numCells);
2235 for (
unsigned cellIdx = 0; cellIdx < numCells; ++cellIdx) {
2236 this->pvt_region_idx_[cellIdx] =
2237 eclProblem.pvtRegionIndex(cellIdx);
2242 template<
typename TypeTag>
2255 return this->numPhases() + has_solvent_;
2258 template<
typename TypeTag>
2262 const auto& eclProblem = simulator_.problem();
2263 depth_.resize(local_num_cells_);
2264 for (
unsigned cellIdx = 0; cellIdx < local_num_cells_; ++cellIdx) {
2265 depth_[cellIdx] = eclProblem.dofCenterDepth(cellIdx);
2269 template<
typename TypeTag>
2272 getWell(
const std::string& well_name)
const
2275 auto well = std::find_if(well_container_.begin(),
2276 well_container_.end(),
2278 return elem->name() == well_name;
2281 assert(well != well_container_.end());
2286 template <
typename TypeTag>
2291 return std::max(this->simulator_.episodeIndex(), 0);
2298 template<
typename TypeTag>
2303 const std::vector<Scalar>& production_rates,
2304 std::vector<Scalar>& resv_coeff)
2306 rateConverter_->calcCoeff(fipnum, pvtreg, production_rates, resv_coeff);
2309 template<
typename TypeTag>
2314 std::vector<Scalar>& resv_coeff)
2316 rateConverter_->calcInjCoeff(fipnum, pvtreg, resv_coeff);
2320 template <
typename TypeTag>
2325 if constexpr (has_energy_) {
2326 int np = this->numPhases();
2327 Scalar cellInternalEnergy;
2331 const int nw = this->numLocalWells();
2332 for (
auto wellID = 0*nw; wellID < nw; ++wellID) {
2333 const Well& well = this->wells_ecl_[wellID];
2334 auto& ws = this->wellState().well(wellID);
2335 if (well.isInjector()) {
2336 if (ws.status != WellStatus::STOP) {
2337 this->wellState().well(wellID).temperature = well.inj_temperature();
2342 std::array<Scalar,2> weighted{0.0,0.0};
2343 auto& [weighted_temperature, total_weight] = weighted;
2345 auto& well_info = this->local_parallel_well_info_[wellID].get();
2346 auto& perf_data = ws.perf_data;
2347 auto& perf_phase_rate = perf_data.phase_rates;
2349 using int_type =
decltype(this->well_perf_data_[wellID].size());
2350 for (int_type perf = 0, end_perf = this->well_perf_data_[wellID].size(); perf < end_perf; ++perf) {
2351 const int cell_idx = this->well_perf_data_[wellID][perf].cell_index;
2352 const auto& intQuants = simulator_.model().intensiveQuantities(cell_idx, 0);
2353 const auto& fs = intQuants.fluidState();
2356 Scalar cellTemperatures = fs.temperature(0).value();
2358 Scalar weight_factor = 0.0;
2359 for (
unsigned phaseIdx = 0; phaseIdx < FluidSystem::numPhases; ++phaseIdx) {
2360 if (!FluidSystem::phaseIsActive(phaseIdx)) {
2363 cellInternalEnergy = fs.enthalpy(phaseIdx).value() -
2364 fs.pressure(phaseIdx).value() / fs.density(phaseIdx).value();
2365 cellBinv = fs.invB(phaseIdx).value();
2366 cellDensity = fs.density(phaseIdx).value();
2367 perfPhaseRate = perf_phase_rate[perf*np + phaseIdx];
2368 weight_factor += cellDensity * perfPhaseRate / cellBinv * cellInternalEnergy / cellTemperatures;
2370 weight_factor = std::abs(weight_factor) + 1e-13;
2371 total_weight += weight_factor;
2372 weighted_temperature += weight_factor * cellTemperatures;
2374 well_info.communication().sum(weighted.data(), 2);
2375 this->wellState().well(wellID).temperature = weighted_temperature / total_weight;
2381 template <
typename TypeTag>
2385 const auto reportStepIdx =
static_cast<unsigned int>(this->reportStepIndex());
2386 const auto& trMod = this->simulator_.problem().tracerModel();
2392 this->assignMswTracerRates(wsrpt, trMod.getMswTracerRates(), 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:95
const Parallel::Communication & comm() const
Definition: BlackoilWellModelGeneric.hpp:228
BlackoilWellModelWBP< GetPropType< TypeTag, Properties::Scalar >, GetPropType< TypeTag, Properties::FluidSystem >::IndexTraitsType > wbp_
Definition: BlackoilWellModelGeneric.hpp:517
std::vector< ParallelWellInfo< GetPropType< TypeTag, Properties::Scalar > > > parallel_well_info_
Definition: BlackoilWellModelGeneric.hpp:546
Class for handling the guide rates in the blackoil well model.
Definition: BlackoilWellModelGuideRates.hpp:46
Class for handling the blackoil well model.
Definition: BlackoilWellModel.hpp:102
void initializeGroupStructure(const int reportStepIdx)
Definition: BlackoilWellModel_impl.hpp:290
void init()
Definition: BlackoilWellModel_impl.hpp:157
const Simulator & simulator() const
Definition: BlackoilWellModel.hpp:374
std::vector< Scalar > depth_
Definition: BlackoilWellModel.hpp:433
std::size_t global_num_cells_
Definition: BlackoilWellModel.hpp:429
GetPropType< TypeTag, Properties::Scalar > Scalar
Definition: BlackoilWellModel.hpp:111
void initWellContainer(const int reportStepIdx) override
Definition: BlackoilWellModel_impl.hpp:176
void beginReportStep(const int time_step)
Definition: BlackoilWellModel_impl.hpp:193
GetPropType< TypeTag, Properties::FluidSystem > FluidSystem
Definition: BlackoilWellModel.hpp:107
Dune::FieldVector< Scalar, numEq > VectorBlockType
Definition: BlackoilWellModel.hpp:132
GetPropType< TypeTag, Properties::ElementContext > ElementContext
Definition: BlackoilWellModel.hpp:108
GetPropType< TypeTag, Properties::Grid > Grid
Definition: BlackoilWellModel.hpp:105
GetPropType< TypeTag, Properties::Simulator > Simulator
Definition: BlackoilWellModel.hpp:110
void initializeWellState(const int timeStepIdx)
Definition: BlackoilWellModel_impl.hpp:750
const Grid & grid() const
Definition: BlackoilWellModel.hpp:371
const SimulatorReportSingle & lastReport() const
Definition: BlackoilWellModel_impl.hpp:624
void addWellContributions(SparseMatrixAdapter &jacobian) const
Definition: BlackoilWellModel_impl.hpp:1567
Dune::BCRSMatrix< Opm::MatrixBlock< Scalar, 1, 1 > > PressureMatrix
Definition: BlackoilWellModel.hpp:299
bool empty() const
Definition: BlackoilWellModel.hpp:344
void computeTotalRatesForDof(RateVector &rate, unsigned globalIdx) const
Definition: BlackoilWellModel_impl.hpp:711
void beginTimeStep()
Definition: BlackoilWellModel_impl.hpp:330
GetPropType< TypeTag, Properties::RateVector > RateVector
Definition: BlackoilWellModel.hpp:112
void calculateExplicitQuantities(DeferredLogger &deferred_logger) const
Definition: BlackoilWellModel_impl.hpp:1741
void updatePrimaryVariables(DeferredLogger &deferred_logger)
Definition: BlackoilWellModel_impl.hpp:2219
void initializeLocalWellStructure(const int reportStepIdx, const bool enableWellPIScaling)
Definition: BlackoilWellModel_impl.hpp:245
Dune::BlockVector< VectorBlockType > BVector
Definition: BlackoilWellModel.hpp:133
BlackoilWellModel(Simulator &simulator)
Definition: BlackoilWellModel_impl.hpp:72
void wellTesting(const int timeStepIdx, const double simulationTime, DeferredLogger &deferred_logger)
Definition: BlackoilWellModel_impl.hpp:535
typename FluidSystem::IndexTraitsType IndexTraits
Definition: BlackoilWellModel.hpp:119
std::size_t local_num_cells_
Definition: BlackoilWellModel.hpp:431
bool alternative_well_rate_init_
Definition: BlackoilWellModel.hpp:434
void timeStepSucceeded(const double simulationTime, const double dt)
Definition: BlackoilWellModel_impl.hpp:634
Simulator & simulator_
Definition: BlackoilWellModel.hpp:403
std::shared_ptr< WellInterface< TypeTag > > WellInterfacePtr
Definition: BlackoilWellModel.hpp:192
void createWellContainer(const int report_step) override
Definition: BlackoilWellModel_impl.hpp:793
int compressedIndexForInterior(int cartesian_cell_idx) const override
get compressed index for interior cells (-1, otherwise
Definition: BlackoilWellModel.hpp:352
void endReportStep()
Definition: BlackoilWellModel_impl.hpp:607
void initializeSources(typename ParallelWBPCalculation< Scalar >::GlobalToLocal index, typename ParallelWBPCalculation< Scalar >::Evaluator eval)
Definition: ConvergenceReport.hpp:38
void setWellFailed(const WellFailure &wf)
Definition: ConvergenceReport.hpp:270
void setWellGroupTargetsViolated(const bool wellGroupTargetsViolated)
Definition: ConvergenceReport.hpp:288
const std::vector< WellFailure > & wellFailures() const
Definition: ConvergenceReport.hpp:369
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:64
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:76
Definition: TargetCalculator.hpp:43
Class for computing BHP limits.
Definition: WellBhpThpCalculator.hpp:41
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)
Class for computing well group controls.
Definition: WellGroupControls.hpp:48
static void updateGpMaintTargetForGroups(const Group &group, const Schedule &schedule, const RegionalValues ®ional_values, const int reportStepIdx, const double dt, const WellStateType &well_state, GroupState< Scalar > &group_state)
int indexOfWell() const
Index of well in the wells struct and wellState.
Definition: WellInterface.hpp:76
bool updateWellControl(const Simulator &simulator, const IndividualOrGroup iog, WellStateType &well_state, const GroupState< Scalar > &group_state, DeferredLogger &deferred_logger)
Definition: WellInterface_impl.hpp:189
virtual void updateProductivityIndex(const Simulator &simulator, const WellProdIndexCalculator< Scalar > &wellPICalc, WellStateType &well_state, DeferredLogger &deferred_logger) const =0
Definition: WellState.hpp:66
ExcEnum
Definition: DeferredLogger.hpp:45
@ NONE
Definition: DeferredLogger.hpp:46
Dune::Communication< MPIComm > Communication
Definition: ParallelCommunication.hpp:30
Definition: blackoilboundaryratevector.hh:39
Opm::DeferredLogger gatherDeferredLogger(const Opm::DeferredLogger &local_deferredlogger, Parallel::Communication communicator)
Create a global log combining local logs.
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