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>
40#include <opm/input/eclipse/Schedule/Well/WellEconProductionLimits.hpp>
42#include <opm/input/eclipse/Units/UnitSystem.hpp>
68#include <fmt/format.h>
71 template<
typename TypeTag>
77 simulator.vanguard().summaryState(),
78 simulator.vanguard().eclState(),
80 simulator.gridView().comm())
81 , simulator_(simulator)
82 , guide_rate_handler_{
84 simulator.vanguard().schedule(),
85 simulator.vanguard().summaryState(),
86 simulator.vanguard().grid().comm()
88 , gaslift_(this->terminal_output_)
96 auto& parallel_wells =
simulator.vanguard().parallelWells();
99 for(
const auto& name_bool : parallel_wells) {
105 Parameters::Get<Parameters::AlternativeWellRateInit>();
107 using SourceDataSpan =
108 typename PAvgDynamicSourceData<Scalar>::template SourceDataSpan<Scalar>;
111 [
this](
const std::size_t globalIndex)
113 [
this](
const int localCell, SourceDataSpan sourceTerms)
115 using Item =
typename SourceDataSpan::Item;
117 const auto* intQuants = this->
simulator_.model()
118 .cachedIntensiveQuantities(localCell, 0);
119 const auto& fs = intQuants->fluidState();
122 .set(Item::PoreVol, intQuants->porosity().value() *
123 this->
simulator_.model().dofTotalVolume(localCell))
124 .set(Item::Depth, this->
depth_[localCell]);
126 constexpr auto io = FluidSystem::oilPhaseIdx;
127 constexpr auto ig = FluidSystem::gasPhaseIdx;
128 constexpr auto iw = FluidSystem::waterPhaseIdx;
131 const auto haveOil = FluidSystem::phaseIsActive(io);
132 const auto haveGas = FluidSystem::phaseIsActive(ig);
133 const auto haveWat = FluidSystem::phaseIsActive(iw);
135 auto weightedPhaseDensity = [&fs](
const auto ip)
137 return fs.saturation(ip).value() * fs.density(ip).value();
140 if (haveOil) { sourceTerms.set(Item::Pressure, fs.pressure(io).value()); }
141 else if (haveGas) { sourceTerms.set(Item::Pressure, fs.pressure(ig).value()); }
142 else { sourceTerms.set(Item::Pressure, fs.pressure(iw).value()); }
146 if (haveOil) { rho += weightedPhaseDensity(io); }
147 if (haveGas) { rho += weightedPhaseDensity(ig); }
148 if (haveWat) { rho += weightedPhaseDensity(iw); }
150 sourceTerms.set(Item::MixtureDensity, rho);
155 template<
typename TypeTag>
160 extractLegacyCellPvtRegionIndex_();
161 extractLegacyDepth_();
163 gravity_ = simulator_.problem().gravity()[2];
165 this->initial_step_ =
true;
168 simulator_.model().addAuxiliaryModule(
this);
170 is_cell_perforated_.resize(local_num_cells_,
false);
174 template<
typename TypeTag>
179 const uint64_t effective_events_mask = ScheduleEvents::WELL_STATUS_CHANGE
180 + ScheduleEvents::NEW_WELL;
181 const auto& events = this->schedule()[reportStepIdx].wellgroup_events();
182 for (
auto& wellPtr : this->well_container_) {
183 const bool well_opened_this_step = this->report_step_starts_ &&
184 events.hasEvent(wellPtr->name(),
185 effective_events_mask);
186 wellPtr->init(this->depth_, this->gravity_,
187 this->B_avg_, well_opened_this_step);
191 template<
typename TypeTag>
198 this->wgHelper().setReportStep(timeStepIdx);
199 this->report_step_starts_ =
true;
200 this->report_step_start_events_ = this->schedule()[timeStepIdx].wellgroup_events();
202 this->rateConverter_ = std::make_unique<RateConverterType>
203 (std::vector<int>(this->local_num_cells_, 0));
207 const auto enableWellPIScaling =
true;
208 this->initializeLocalWellStructure(timeStepIdx, enableWellPIScaling);
211 this->initializeGroupStructure(timeStepIdx);
213 const auto& comm = this->simulator_.vanguard().grid().comm();
219 this->rateConverter_->template defineState<ElementContext>(this->simulator_);
223 const auto& sched_state = this->schedule()[timeStepIdx];
225 this->vfp_properties_ = std::make_unique<VFPProperties<Scalar, IndexTraits>>
226 (sched_state.vfpinj(), sched_state.vfpprod(), this->wellState());
230 "beginReportStep() failed: ",
231 this->terminal_output_, comm)
235 this->commitWGState();
237 this->wellStructureChangedDynamically_ =
false;
244 template <
typename TypeTag>
248 const bool enableWellPIScaling)
252 const auto& comm = this->simulator_.vanguard().grid().comm();
255 this->wells_ecl_ = this->getLocalWells(reportStepIdx);
256 this->local_parallel_well_info_ =
257 this->createLocalParallelWellInfo(this->wells_ecl_);
264 this->initializeWellPerfData();
265 this->initializeWellState(reportStepIdx);
266 this->wbp_.initializeWBPCalculationService();
268 if (this->param_.use_multisegment_well_ && this->anyMSWellOpenLocal()) {
269 this->wellState().initWellStateMSWell(this->wells_ecl_, &this->prevWellState());
272 this->initializeWellProdIndCalculators();
274 if (enableWellPIScaling && this->schedule()[reportStepIdx].events()
275 .hasEvent(ScheduleEvents::Events::WELL_PRODUCTIVITY_INDEX))
277 this->runWellPIScaling(reportStepIdx, local_deferredLogger);
281 "Failed to initialize local well structure: ",
282 this->terminal_output_, comm)
289 template <
typename TypeTag>
296 const auto& comm = this->simulator_.vanguard().grid().comm();
300 const auto& fieldGroup =
301 this->schedule().getGroup(
"FIELD", reportStepIdx);
303 this->wgHelper().setCmodeGroup(fieldGroup, this->groupState());
307 if (this->schedule()[reportStepIdx].has_gpmaint()) {
308 this->wgHelper().setRegionAveragePressureCalculator(
310 this->eclState_.fieldProps(),
311 this->regionalAveragePressureCalculator_
316 "Failed to initialize group structure: ",
317 this->terminal_output_, comm)
325 template<
typename TypeTag>
330 OPM_TIMEBLOCK(beginTimeStep);
332 this->updateAverageFormationFactor();
336 this->switched_prod_groups_.clear();
337 this->switched_inj_groups_.clear();
339 if (this->wellStructureChangedDynamically_) {
344 const auto reportStepIdx =
345 this->simulator_.episodeIndex();
349 const auto enableWellPIScaling =
false;
351 this->initializeLocalWellStructure(reportStepIdx, enableWellPIScaling);
352 this->initializeGroupStructure(reportStepIdx);
354 this->commitWGState();
360 this->wellStructureChangedDynamically_ =
false;
363 this->resetWGState();
364 const int reportStepIdx = simulator_.episodeIndex();
366 this->wellState().updateWellsDefaultALQ(this->schedule(), reportStepIdx, this->summaryState());
367 this->wellState().gliftTimeStepInit();
369 const double simulationTime = simulator_.time();
373 wellTesting(reportStepIdx, simulationTime, local_deferredLogger);
376 createWellContainer(reportStepIdx);
380 this->updateAndCommunicateGroupData(reportStepIdx,
381 simulator_.model().newtonMethod().numIterations(),
382 param_.nupcol_group_rate_tolerance_,
false,
383 local_deferredLogger);
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);
480 this->wgHelper().updateGpMaintTargetForGroups(fieldGroup,
481 regionalAveragePressureCalculator_,
486 this->updateAndCommunicateGroupData(reportStepIdx,
487 simulator_.model().newtonMethod().numIterations(),
488 param_.nupcol_group_rate_tolerance_,
490 local_deferredLogger);
493 for (
auto& well : well_container_) {
494 const uint64_t effective_events_mask = ScheduleEvents::WELL_STATUS_CHANGE
495 + ScheduleEvents::INJECTION_TYPE_CHANGED
496 + ScheduleEvents::WELL_SWITCHED_INJECTOR_PRODUCER
497 + ScheduleEvents::NEW_WELL;
499 const auto& events = this->schedule()[reportStepIdx].wellgroup_events();
500 const bool event = this->report_step_starts_ && events.hasEvent(well->name(), effective_events_mask);
501 const bool dyn_status_change = this->wellState().well(well->name()).status
502 != this->prevWellState().well(well->name()).status;
504 if (event || dyn_status_change) {
506 well->scaleSegmentRatesAndPressure(this->wellState());
507 well->calculateExplicitQuantities(simulator_, this->wellState(), local_deferredLogger);
508 well->updateWellStateWithTarget(simulator_, this->wgHelper(), this->wellState(), local_deferredLogger);
509 well->updatePrimaryVariables(simulator_, this->wellState(), local_deferredLogger);
510 well->solveWellEquation(
511 simulator_, this->wgHelper(), this->wellState(), local_deferredLogger
513 }
catch (
const std::exception& e) {
514 const std::string msg =
"Compute initial well solution for new well " + well->name() +
" failed. Continue with zero initial rates";
515 local_deferredLogger.
warning(
"WELL_INITIAL_SOLVE_FAILED", msg);
524 const std::string msg =
"Compute initial well solution for new wells failed. Continue with zero initial rates";
525 local_deferredLogger.
warning(
"WELL_INITIAL_SOLVE_FAILED", msg);
528 const auto& comm = simulator_.vanguard().grid().comm();
530 exc_type,
"beginTimeStep() failed: " + exc_msg, this->terminal_output_, comm);
534 template<
typename TypeTag>
537 const double simulationTime,
540 for (
const std::string& well_name : this->getWellsForTesting(timeStepIdx, simulationTime)) {
541 const Well& wellEcl = this->schedule().getWell(well_name, timeStepIdx);
542 if (wellEcl.getStatus() == Well::Status::SHUT)
545 WellInterfacePtr well = createWellForWellTest(well_name, timeStepIdx, deferred_logger);
547 well->init(depth_, gravity_, B_avg_,
true);
549 Scalar well_efficiency_factor = wellEcl.getEfficiencyFactor() *
550 this->wellState().getGlobalEfficiencyScalingFactor(well_name);
551 this->wgHelper().accumulateGroupEfficiencyFactor(
552 this->schedule().getGroup(wellEcl.groupName(), timeStepIdx),
553 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] || cellRates_.count(elemIdx) == 0) {
720 rate = cellRates_.at(elemIdx);
724 template<
typename TypeTag>
725 template <
class Context>
729 const Context& context,
731 unsigned timeIdx)
const
734 int elemIdx = context.globalSpaceIndex(spaceIdx, timeIdx);
736 if (!is_cell_perforated_[elemIdx] || cellRates_.count(elemIdx) == 0) {
740 rate = cellRates_.at(elemIdx);
745 template<
typename TypeTag>
750 const auto pressIx = []()
752 if (Indices::oilEnabled) {
return FluidSystem::oilPhaseIdx; }
753 if (Indices::waterEnabled) {
return FluidSystem::waterPhaseIdx; }
755 return FluidSystem::gasPhaseIdx;
758 auto cellPressures = std::vector<Scalar>(this->local_num_cells_,
Scalar{0});
759 auto cellTemperatures = std::vector<Scalar>(this->local_num_cells_,
Scalar{0});
762 const auto& gridView = this->simulator_.vanguard().gridView();
765 for (
const auto& elem : elements(gridView, Dune::Partitions::interior)) {
766 elemCtx.updatePrimaryStencil(elem);
767 elemCtx.updatePrimaryIntensiveQuantities(0);
769 const auto ix = elemCtx.globalSpaceIndex(0, 0);
770 const auto& fs = elemCtx.intensiveQuantities(0, 0).fluidState();
772 cellPressures[ix] = fs.pressure(pressIx).value();
773 cellTemperatures[ix] = fs.temperature(0).value();
776 this->simulator_.vanguard().grid().comm());
778 this->wellState().init(cellPressures, cellTemperatures, this->schedule(), this->wells_ecl_,
779 this->local_parallel_well_info_, timeStepIdx,
780 &this->prevWellState(), this->well_perf_data_,
781 this->summaryState(), simulator_.vanguard().enableDistributedWells());
788 template<
typename TypeTag>
795 const int nw = this->numLocalWells();
797 well_container_.clear();
800 well_container_.reserve(nw);
802 const auto& wmatcher = this->schedule().wellMatcher(report_step);
803 const auto& wcycle = this->schedule()[report_step].wcycle.get();
807 std::for_each(this->wells_ecl_.begin(), this->wells_ecl_.end(),
808 [
this, &wg_events = this->report_step_start_events_](
const auto& well_ecl)
810 if (!well_ecl.hasConnections()) {
815 constexpr auto events_mask = ScheduleEvents::WELL_STATUS_CHANGE |
816 ScheduleEvents::REQUEST_OPEN_WELL |
817 ScheduleEvents::REQUEST_SHUT_WELL;
818 const bool well_event =
819 this->report_step_starts_ &&
820 wg_events.hasEvent(well_ecl.name(), events_mask);
829 if (well_ecl.getStatus() == WellStatus::OPEN) {
830 this->well_open_times_.insert_or_assign(well_ecl.name(),
831 this->simulator_.time());
832 this->well_close_times_.erase(well_ecl.name());
833 }
else if (well_ecl.getStatus() == WellStatus::SHUT) {
834 this->well_close_times_.insert_or_assign(well_ecl.name(),
835 this->simulator_.time());
836 this->well_open_times_.erase(well_ecl.name());
842 const auto cycle_states = wcycle.wellStatus(this->simulator_.time(),
844 this->well_open_times_,
845 this->well_close_times_);
847 for (
int w = 0; w < nw; ++w) {
848 const Well& well_ecl = this->wells_ecl_[w];
850 if (!well_ecl.hasConnections()) {
855 const std::string& well_name = well_ecl.name();
856 const auto well_status = this->schedule()
857 .getWell(well_name, report_step).getStatus();
859 const bool shut_event = this->wellState().well(w).events.hasEvent(ScheduleEvents::WELL_STATUS_CHANGE)
860 && well_status == Well::Status::SHUT;
861 const bool open_event = this->wellState().well(w).events.hasEvent(ScheduleEvents::WELL_STATUS_CHANGE)
862 && well_status == Well::Status::OPEN;
863 const auto& ws = this->wellState().well(well_name);
865 if (shut_event && ws.status != Well::Status::SHUT) {
866 this->closed_this_step_.insert(well_name);
867 this->wellState().shutWell(w);
868 }
else if (open_event && ws.status != Well::Status::OPEN) {
869 this->wellState().openWell(w);
873 if (this->wellTestState().well_is_closed(well_name)) {
878 const bool closed_this_step = (this->wellTestState().lastTestTime(well_name) == simulator_.time());
881 auto& events = this->wellState().well(w).events;
882 if (events.hasEvent(ScheduleEvents::REQUEST_OPEN_WELL)) {
883 if (!closed_this_step) {
884 this->wellTestState().open_well(well_name);
885 this->wellTestState().open_completions(well_name);
886 this->well_open_times_.insert_or_assign(well_name,
887 this->simulator_.time());
888 this->well_close_times_.erase(well_name);
890 events.clearEvent(ScheduleEvents::REQUEST_OPEN_WELL);
896 if (this->wellTestState().well_is_closed(well_name))
898 if (well_ecl.getAutomaticShutIn()) {
900 this->wellState().shutWell(w);
901 this->well_close_times_.erase(well_name);
902 this->well_open_times_.erase(well_name);
905 if (!well_ecl.getAllowCrossFlow()) {
908 this->wellState().shutWell(w);
909 this->well_close_times_.erase(well_name);
910 this->well_open_times_.erase(well_name);
914 this->wellState().stopWell(w);
919 if (!well_ecl.getAllowCrossFlow()) {
920 const bool any_zero_rate_constraint = well_ecl.isProducer()
921 ? well_ecl.productionControls(this->summaryState_).anyZeroRateConstraint()
922 : well_ecl.injectionControls(this->summaryState_).anyZeroRateConstraint();
923 if (any_zero_rate_constraint) {
925 local_deferredLogger.
debug(fmt::format(
" Well {} gets shut due to having zero rate constraint and disallowing crossflow ", well_ecl.name()) );
926 this->wellState().shutWell(w);
927 this->well_close_times_.erase(well_name);
928 this->well_open_times_.erase(well_name);
933 if (!wcycle.empty()) {
934 const auto it = cycle_states.find(well_name);
935 if (it != cycle_states.end()) {
936 if (!it->second || well_status == Well::Status::SHUT) {
938 if (well_status == Well::Status::SHUT) {
939 this->well_open_times_.erase(well_name);
940 this->well_close_times_.erase(well_name);
942 this->wellState().shutWell(w);
945 this->wellState().openWell(w);
951 if (ws.status == Well::Status::SHUT) {
955 well_container_.emplace_back(this->createWellPointer(w, report_step));
957 if (ws.status == Well::Status::STOP) {
958 well_container_.back()->stopWell();
959 this->well_close_times_.erase(well_name);
960 this->well_open_times_.erase(well_name);
964 if (!wcycle.empty()) {
965 const auto schedule_open =
966 [&wg_events = this->report_step_start_events_](
const std::string& name)
968 return wg_events.hasEvent(name, ScheduleEvents::REQUEST_OPEN_WELL);
970 for (
const auto& [wname, wscale] : wcycle.efficiencyScale(this->simulator_.time(),
971 this->simulator_.timeStepSize(),
973 this->well_open_times_,
976 this->wellState().updateEfficiencyScalingFactor(wname, wscale);
977 this->schedule_.add_event(ScheduleEvents::WELLGROUP_EFFICIENCY_UPDATE, report_step);
986 if (this->terminal_output_) {
990 this->well_container_generic_.clear();
991 for (
auto& w : well_container_)
992 this->well_container_generic_.push_back(w.get());
994 const auto& network = this->schedule()[report_step].network();
995 if (network.active() && !this->node_pressures_.empty()) {
996 for (
auto& well: this->well_container_generic_) {
1000 if (well->isProducer()) {
1001 const auto it = this->node_pressures_.find(well->wellEcl().groupName());
1002 if (it != this->node_pressures_.end()) {
1005 const Scalar nodal_pressure = it->second;
1006 well->setDynamicThpLimit(nodal_pressure);
1012 this->wbp_.registerOpenWellsForWBPCalculation();
1019 template <
typename TypeTag>
1020 typename BlackoilWellModel<TypeTag>::WellInterfacePtr
1024 const auto is_multiseg = this->wells_ecl_[wellID].isMultiSegment();
1026 if (! (this->param_.use_multisegment_well_ && is_multiseg)) {
1027 return this->
template createTypedWellPointer<StandardWell<TypeTag>>(wellID, report_step);
1030 return this->
template createTypedWellPointer<MultisegmentWell<TypeTag>>(wellID, report_step);
1038 template <
typename TypeTag>
1039 template <
typename WellType>
1040 std::unique_ptr<WellType>
1045 const auto& perf_data = this->well_perf_data_[wellID];
1048 const auto pvtreg = perf_data.
empty()
1049 ? 0 : this->pvt_region_idx_[perf_data.front().cell_index];
1051 const auto& parallel_well_info = this->local_parallel_well_info_[wellID].get();
1052 const auto global_pvtreg = parallel_well_info.broadcastFirstPerforationValue(pvtreg);
1054 return std::make_unique<WellType>(this->wells_ecl_[wellID],
1058 *this->rateConverter_,
1060 this->numConservationQuantities(),
1070 template<
typename TypeTag>
1074 const int report_step,
1078 const auto it = std::find_if(this->wells_ecl_.begin(),
1079 this->wells_ecl_.end(),
1080 [&well_name](
const auto& w)
1081 { return well_name == w.name(); });
1083 if (it == this->wells_ecl_.end()) {
1085 fmt::format(
"Could not find well {} in wells_ecl ", well_name),
1089 const int pos =
static_cast<int>(std::distance(this->wells_ecl_.begin(), it));
1090 return this->createWellPointer(pos, report_step);
1095 template<
typename TypeTag>
1101 const double dt = this->simulator_.timeStepSize();
1103 auto& well_state = this->wellState();
1105 const bool changed_well_group = updateWellControlsAndNetwork(
true, dt, deferred_logger);
1106 assembleWellEqWithoutIteration(dt, deferred_logger);
1107 const bool converged = this->getWellConvergence(this->B_avg_,
true).converged() && !changed_well_group;
1110 for (
auto& well : this->well_container_) {
1111 well->solveEqAndUpdateWellState(simulator_, well_state, deferred_logger);
1114 this->simulator_.vanguard().grid().comm());
1117 const std::string msg = fmt::format(
"Initial (pre-step) network balance did not converge.");
1125 template<
typename TypeTag>
1134 this->guide_rate_handler_.setLogger(&local_deferredLogger);
1136 if (gaslift_.terminalOutput()) {
1137 const std::string msg =
1138 fmt::format(
"assemble() : iteration {}" , iterationIdx);
1139 gaslift_.gliftDebug(msg, local_deferredLogger);
1143 Dune::Timer perfTimer;
1145 this->closed_offending_wells_.clear();
1148 const int episodeIdx = simulator_.episodeIndex();
1149 const auto& network = this->schedule()[episodeIdx].network();
1150 if (!this->wellsActive() && !network.active()) {
1155 if (iterationIdx == 0 && this->wellsActive()) {
1156 OPM_TIMEBLOCK(firstIterationAssmble);
1163 calculateExplicitQuantities(local_deferredLogger);
1164 prepareTimeStep(local_deferredLogger);
1167 "assemble() failed (It=0): ",
1168 this->terminal_output_, grid().comm());
1171 const bool well_group_control_changed = updateWellControlsAndNetwork(
false, dt, local_deferredLogger);
1175 if ( ! this->wellsActive() ) {
1179 assembleWellEqWithoutIteration(dt, local_deferredLogger);
1182 for (
const auto& well : well_container_)
1183 well->addCellRates(cellRates_);
1187 last_report_.well_group_control_changed = well_group_control_changed;
1188 last_report_.assemble_time_well += perfTimer.stop();
1194 template<
typename TypeTag>
1203 bool do_network_update =
true;
1204 bool well_group_control_changed =
false;
1205 Scalar network_imbalance = 0.0;
1207 const std::size_t iteration_to_relax = param_.network_max_strict_outer_iterations_;
1209 const std::size_t max_iteration = param_.network_max_outer_iterations_;
1210 std::size_t network_update_iteration = 0;
1211 network_needs_more_balancing_force_another_newton_iteration_ =
false;
1212 while (do_network_update) {
1213 if (network_update_iteration >= max_iteration ) {
1215 const int episodeIdx = simulator_.episodeIndex();
1216 const int iterationIdx = simulator_.model().newtonMethod().numIterations();
1217 if (this->shouldBalanceNetwork(episodeIdx, iterationIdx + 1)) {
1218 if (this->terminal_output_) {
1219 const std::string msg = fmt::format(
"Maximum of {:d} network iterations has been used and we stop the update, \n"
1220 "and try again after the next Newton iteration (imbalance = {:.2e} bar, ctrl_change = {})",
1221 max_iteration, network_imbalance*1.0e-5, well_group_control_changed);
1222 local_deferredLogger.
debug(msg);
1226 network_needs_more_balancing_force_another_newton_iteration_ =
true;
1228 if (this->terminal_output_) {
1229 const std::string msg = fmt::format(
"Maximum of {:d} network iterations has been used and we stop the update. \n"
1230 "The simulator will continue with unconverged network results (imbalance = {:.2e} bar, ctrl_change = {})",
1231 max_iteration, network_imbalance*1.0e-5, well_group_control_changed);
1232 local_deferredLogger.
info(msg);
1237 if (this->terminal_output_ && (network_update_iteration == iteration_to_relax) ) {
1238 local_deferredLogger.
debug(
"We begin using relaxed tolerance for network update now after " +
std::to_string(iteration_to_relax) +
" iterations ");
1240 const bool relax_network_balance = network_update_iteration >= iteration_to_relax;
1242 const bool optimize_gas_lift = ( (network_update_iteration + 1) < std::max(max_iteration,
static_cast<std::size_t
>(2)) );
1243 std::tie(well_group_control_changed, do_network_update, network_imbalance) =
1244 updateWellControlsAndNetworkIteration(mandatory_network_balance, relax_network_balance, optimize_gas_lift, dt,local_deferredLogger);
1245 ++network_update_iteration;
1247 return well_group_control_changed;
1253 template<
typename TypeTag>
1254 std::tuple<bool, bool, typename BlackoilWellModel<TypeTag>::Scalar>
1257 const bool relax_network_tolerance,
1258 const bool optimize_gas_lift,
1263 const int iterationIdx = simulator_.model().newtonMethod().numIterations();
1264 const int reportStepIdx = simulator_.episodeIndex();
1265 this->updateAndCommunicateGroupData(reportStepIdx, iterationIdx,
1266 param_.nupcol_group_rate_tolerance_,
true, local_deferredLogger);
1271 bool well_group_control_changed = updateWellControls(local_deferredLogger);
1272 const auto [more_inner_network_update, network_imbalance] =
1273 updateNetworks(mandatory_network_balance,
1274 local_deferredLogger,
1275 relax_network_tolerance);
1278 bool alq_updated =
false;
1281 if (optimize_gas_lift) {
1284 const bool updatePotentials = (this->shouldBalanceNetwork(reportStepIdx, iterationIdx) || mandatory_network_balance);
1285 alq_updated = gaslift_.maybeDoGasLiftOptimize(simulator_,
1287 this->node_pressures_,
1291 local_deferredLogger);
1293 prepareWellsBeforeAssembling(dt, local_deferredLogger);
1296 "updateWellControlsAndNetworkIteration() failed: ",
1297 this->terminal_output_, grid().comm());
1301 guideRateUpdateIsNeeded(reportStepIdx)) {
1302 const double simulationTime = simulator_.time();
1306 this->guide_rate_handler_.updateGuideRates(
1307 reportStepIdx, simulationTime, this->wellState(), this->groupState()
1312 const bool more_network_update = this->shouldBalanceNetwork(reportStepIdx, iterationIdx) &&
1313 (more_inner_network_update || well_group_control_changed || alq_updated);
1314 return {well_group_control_changed, more_network_update, network_imbalance};
1320 template <
typename TypeTag>
1326 const int reportStepIdx = this->simulator_.episodeIndex();
1327 const auto& network = this->schedule()[reportStepIdx].network();
1328 const auto& balance = this->schedule()[reportStepIdx].network_balance();
1329 const Scalar thp_tolerance = balance.thp_tolerance();
1331 if (!network.active()) {
1335 auto& well_state = this->wellState();
1336 auto& group_state = this->groupState();
1338 bool well_group_thp_updated =
false;
1339 for (
const std::string& nodeName : network.node_names()) {
1340 const bool has_choke = network.node(nodeName).as_choke();
1342 const auto& summary_state = this->simulator_.vanguard().summaryState();
1343 const Group& group = this->schedule().getGroup(nodeName, reportStepIdx);
1346 std::vector<Scalar> resv_coeff(Indices::numPhases, 1.0);
1347 Scalar gratTargetFromSales = 0.0;
1348 if (group_state.has_grat_sales_target(group.name()))
1349 gratTargetFromSales = group_state.grat_sales_target(group.name());
1351 const auto ctrl = group.productionControls(summary_state);
1352 auto cmode_tmp = ctrl.cmode;
1354 bool fld_none =
false;
1359 const Scalar efficiencyFactor = 1.0;
1360 const Group& parentGroup = this->schedule().getGroup(group.parent(), reportStepIdx);
1371 local_deferredLogger);
1372 target_tmp = target.first;
1373 cmode_tmp = target.second;
1375 const auto cmode = cmode_tmp;
1377 TargetCalculatorType tcalc(cmode, FluidSystem::phaseUsage(), resv_coeff,
1378 gratTargetFromSales, nodeName, group_state,
1379 group.has_gpmaint_control(cmode));
1383 target_tmp = tcalc.groupTarget(ctrl, local_deferredLogger);
1386 const Scalar orig_target = target_tmp;
1388 auto mismatch = [&] (
auto group_thp) {
1391 for (
auto& well : this->well_container_) {
1392 std::string well_name = well->name();
1393 auto& ws = well_state.well(well_name);
1394 if (group.hasWell(well_name)) {
1395 well->setDynamicThpLimit(group_thp);
1396 const Well& well_ecl = this->wells_ecl_[well->indexOfWell()];
1397 const auto inj_controls = Well::InjectionControls(0);
1398 const auto prod_controls = well_ecl.productionControls(summary_state);
1399 well->iterateWellEqWithSwitching(
1400 this->simulator_, dt, inj_controls, prod_controls, this->wgHelper(), this->wellState(), local_deferredLogger,
false,
false
1402 rate = -tcalc.calcModeRateFromRates(ws.surface_rates);
1406 return (group_rate - orig_target)/orig_target;
1409 const auto upbranch = network.uptree_branch(nodeName);
1410 const auto it = this->node_pressures_.find((*upbranch).uptree_node());
1411 const Scalar nodal_pressure = it->second;
1412 Scalar well_group_thp = nodal_pressure;
1414 std::optional<Scalar> autochoke_thp;
1415 if (
auto iter = this->well_group_thp_calc_.find(nodeName); iter != this->well_group_thp_calc_.end()) {
1416 autochoke_thp = this->well_group_thp_calc_.at(nodeName);
1421 std::array<Scalar, 2> range_initial;
1422 if (!autochoke_thp.has_value()){
1425 std::string node_name = nodeName;
1426 while (!network.node(node_name).terminal_pressure().has_value()) {
1427 auto branch = network.uptree_branch(node_name).value();
1428 node_name = branch.uptree_node();
1430 min_thp = network.node(node_name).terminal_pressure().value();
1431 WellBhpThpCalculatorType::bruteForceBracketCommonTHP(mismatch, min_thp, max_thp);
1434 std::array<Scalar, 2> range = {
Scalar{0.9}*min_thp,
Scalar{1.1}*max_thp};
1435 std::optional<Scalar> appr_sol;
1436 WellBhpThpCalculatorType::bruteForceBracketCommonTHP(mismatch, range, low1, high1, appr_sol, 0.0, local_deferredLogger);
1439 range_initial = {min_thp, max_thp};
1442 if (!autochoke_thp.has_value() || autochoke_thp.value() > nodal_pressure) {
1444 std::array<Scalar, 2> range = autochoke_thp.has_value() ?
1445 std::array<Scalar, 2>{
Scalar{0.9} * autochoke_thp.value(),
1446 Scalar{1.1} * autochoke_thp.value()} : range_initial;
1448 std::optional<Scalar> approximate_solution;
1449 const Scalar tolerance1 = thp_tolerance;
1450 local_deferredLogger.
debug(
"Using brute force search to bracket the group THP");
1451 const bool finding_bracket = WellBhpThpCalculatorType::bruteForceBracketCommonTHP(mismatch, range, low, high, approximate_solution, tolerance1, local_deferredLogger);
1453 if (approximate_solution.has_value()) {
1454 autochoke_thp = *approximate_solution;
1455 local_deferredLogger.
debug(
"Approximate group THP value found: " +
std::to_string(autochoke_thp.value()));
1456 }
else if (finding_bracket) {
1457 const Scalar tolerance2 = thp_tolerance;
1458 const int max_iteration_solve = 100;
1460 autochoke_thp = RegulaFalsiBisection<ThrowOnError>::
1461 solve(mismatch, low, high, max_iteration_solve, tolerance2, iteration);
1466 autochoke_thp.reset();
1467 local_deferredLogger.
debug(
"Group THP solve failed due to bracketing failure");
1470 if (autochoke_thp.has_value()) {
1471 well_group_thp_calc_[nodeName] = autochoke_thp.value();
1474 well_group_thp = std::max(autochoke_thp.value(), nodal_pressure);
1477 for (
auto& well : this->well_container_) {
1478 std::string well_name = well->name();
1480 if (well->isInjector() || !well->wellEcl().predictionMode())
1483 if (group.hasWell(well_name)) {
1484 well->setDynamicThpLimit(well_group_thp);
1486 const auto& ws = this->wellState().well(well->indexOfWell());
1487 const bool thp_is_limit = ws.production_cmode == Well::ProducerCMode::THP;
1489 well->prepareWellBeforeAssembling(
1490 this->simulator_, dt, this->wgHelper(), this->wellState(), local_deferredLogger
1496 const auto& current_well_group_thp = group_state.is_autochoke_group(nodeName) ? group_state.well_group_thp(nodeName) : 1e30;
1497 if (std::abs(current_well_group_thp - well_group_thp) > balance.pressure_tolerance()) {
1498 well_group_thp_updated =
true;
1499 group_state.update_well_group_thp(nodeName, well_group_thp);
1503 return well_group_thp_updated;
1506 template<
typename TypeTag>
1512 for (
auto& well : well_container_) {
1513 well->assembleWellEq(simulator_, dt, this->wgHelper(), deferred_logger);
1518 template<
typename TypeTag>
1524 for (
auto& well : well_container_) {
1525 well->prepareWellBeforeAssembling(
1526 simulator_, dt, this->wgHelper(), this->wellState(), deferred_logger
1532 template<
typename TypeTag>
1542 for (
auto& well: well_container_) {
1543 well->assembleWellEqWithoutIteration(simulator_, dt, this->wellState(), this->groupState(),
1547 this->terminal_output_, grid().comm());
1551#if COMPILE_GPU_BRIDGE
1552 template<
typename TypeTag>
1560 for(
unsigned int i = 0; i < well_container_.size(); i++){
1561 auto& well = well_container_[i];
1564 wellContribs.
addNumBlocks(derived->linSys().getNumBlocks());
1569 wellContribs.
alloc();
1571 for(
unsigned int i = 0; i < well_container_.size(); i++){
1572 auto& well = well_container_[i];
1574 auto derived_std =
dynamic_cast<StandardWell<TypeTag>*
>(well.get());
1576 derived_std->linSys().extract(derived_std->numStaticWellEq, wellContribs);
1578 auto derived_ms =
dynamic_cast<MultisegmentWell<TypeTag>*
>(well.get());
1580 derived_ms->linSys().extract(wellContribs);
1582 OpmLog::warning(
"Warning unknown type of well");
1589 template<
typename TypeTag>
1594 for (
const auto& well: well_container_ ) {
1599 template<
typename TypeTag>
1604 const bool use_well_weights)
const
1606 int nw = this->numLocalWellsEnd();
1607 int rdofs = local_num_cells_;
1608 for (
int i = 0; i < nw; i++ ) {
1609 int wdof = rdofs + i;
1610 jacobian[wdof][wdof] = 1.0;
1613 for (
const auto& well : well_container_) {
1614 well->addWellPressureEquations(jacobian,
1622 template <
typename TypeTag>
1625 const std::vector<typename SparseMatrixAdapter::MatrixBlock*>& diagMatAddress)
const
1630 for (
const auto& well : well_container_) {
1631 if (!well->isOperableAndSolvable() && !well->wellIsStopped()) {
1634 const auto& cells = well->cells();
1635 const auto& rates = well->connectionRates();
1636 for (
unsigned perfIdx = 0; perfIdx < rates.size(); ++perfIdx) {
1637 unsigned cellIdx = cells[perfIdx];
1638 auto rate = rates[perfIdx];
1641 using MatrixBlockType =
typename SparseMatrixAdapter::MatrixBlock;
1642 MatrixBlockType bMat(0.0);
1643 simulator_.model().linearizer().setResAndJacobi(res, bMat, rate);
1644 residual[cellIdx] += res;
1645 *diagMatAddress[cellIdx] += bMat;
1651 template<
typename TypeTag>
1656 int nw = this->numLocalWellsEnd();
1657 int rdofs = local_num_cells_;
1658 for (
int i = 0; i < nw; ++i) {
1659 int wdof = rdofs + i;
1660 jacobian.entry(wdof,wdof) = 1.0;
1662 const auto wellconnections = this->getMaxWellConnections();
1663 for (
int i = 0; i < nw; ++i) {
1664 const auto& perfcells = wellconnections[i];
1665 for (
int perfcell : perfcells) {
1666 int wdof = rdofs + i;
1667 jacobian.entry(wdof, perfcell) = 0.0;
1668 jacobian.entry(perfcell, wdof) = 0.0;
1674 template<
typename TypeTag>
1682 for (
const auto& well : well_container_) {
1683 const auto& cells = well->cells();
1684 x_local_.resize(cells.size());
1686 for (
size_t i = 0; i < cells.size(); ++i) {
1687 x_local_[i] = x[cells[i]];
1689 well->recoverWellSolutionAndUpdateWellState(simulator_, x_local_,
1690 this->wellState(), local_deferredLogger);
1694 "recoverWellSolutionAndUpdateWellState() failed: ",
1695 this->terminal_output_, simulator_.vanguard().grid().comm());
1699 template<
typename TypeTag>
1705 OPM_THROW(std::logic_error,
"Attempt to call NLDD method without a NLDD solver");
1708 return nldd_->recoverWellSolutionAndUpdateWellState(x, domainIdx);
1712 template<
typename TypeTag>
1715 getWellConvergence(
const std::vector<Scalar>& B_avg,
bool checkWellGroupControlsAndNetwork)
const
1721 const int iterationIdx = simulator_.model().newtonMethod().numIterations();
1722 for (
const auto& well : well_container_) {
1723 if (well->isOperableAndSolvable() || well->wellIsStopped()) {
1724 local_report += well->getWellConvergence(
1725 simulator_, this->wellState(), B_avg, local_deferredLogger,
1726 iterationIdx > param_.strict_outer_iter_wells_);
1730 report.
setWellFailed({CR::WellFailure::Type::Unsolvable, CR::Severity::Normal, -1, well->name()});
1731 local_report += report;
1739 if (checkWellGroupControlsAndNetwork) {
1745 if (this->terminal_output_) {
1750 if (f.severity() == ConvergenceReport::Severity::NotANumber) {
1751 OpmLog::debug(
"NaN residual found with phase " +
std::to_string(f.phase()) +
" for well " + f.wellName());
1752 }
else if (f.severity() == ConvergenceReport::Severity::TooLarge) {
1753 OpmLog::debug(
"Too large residual found with phase " +
std::to_string(f.phase()) +
" for well " + f.wellName());
1764 template<
typename TypeTag>
1770 for (
auto& well : well_container_) {
1779 template<
typename TypeTag>
1785 if (!this->wellsActive()) {
1788 const int episodeIdx = simulator_.episodeIndex();
1789 const int iterationIdx = simulator_.model().newtonMethod().numIterations();
1790 const auto& comm = simulator_.vanguard().grid().comm();
1792 bool changed_well_group =
false;
1793 const Group& fieldGroup = this->schedule().getGroup(
"FIELD", episodeIdx);
1796 const std::size_t max_iter = param_.well_group_constraints_max_iterations_;
1797 while(!changed_well_group && iter < max_iter) {
1798 changed_well_group = updateGroupControls(fieldGroup, deferred_logger, episodeIdx, iterationIdx);
1801 bool changed_well_to_group =
false;
1803 OPM_TIMEBLOCK(UpdateWellControls);
1807 for (
const auto& well : well_container_) {
1810 simulator_, mode, this->wgHelper(), this->wellState(), deferred_logger
1813 changed_well_to_group = changed_well || changed_well_to_group;
1817 simulator_.gridView().comm());
1820 changed_well_to_group = comm.sum(
static_cast<int>(changed_well_to_group));
1821 if (changed_well_to_group) {
1822 updateAndCommunicate(episodeIdx, iterationIdx, deferred_logger);
1823 changed_well_group =
true;
1827 bool changed_well_individual =
false;
1832 for (
const auto& well : well_container_) {
1835 simulator_, mode, this->wgHelper(), this->wellState(), deferred_logger
1838 changed_well_individual = changed_well || changed_well_individual;
1842 simulator_.gridView().comm());
1845 changed_well_individual = comm.sum(
static_cast<int>(changed_well_individual));
1846 if (changed_well_individual) {
1847 updateAndCommunicate(episodeIdx, iterationIdx, deferred_logger);
1848 changed_well_group =
true;
1854 this->updateWsolvent(fieldGroup, episodeIdx, this->nupcolWellState());
1856 return changed_well_group;
1860 template<
typename TypeTag>
1861 std::tuple<bool, typename BlackoilWellModel<TypeTag>::Scalar>
1865 const bool relax_network_tolerance)
1868 const int episodeIdx = simulator_.episodeIndex();
1869 const auto& network = this->schedule()[episodeIdx].network();
1870 if (!this->wellsActive() && !network.active()) {
1871 return {
false, 0.0};
1874 const int iterationIdx = simulator_.model().newtonMethod().numIterations();
1875 const auto& comm = simulator_.vanguard().grid().comm();
1878 Scalar network_imbalance = 0.0;
1879 bool more_network_update =
false;
1880 if (this->shouldBalanceNetwork(episodeIdx, iterationIdx) || mandatory_network_balance) {
1881 OPM_TIMEBLOCK(BalanceNetwork);
1882 const double dt = this->simulator_.timeStepSize();
1884 const bool well_group_thp_updated = computeWellGroupThp(dt, deferred_logger);
1885 const int max_number_of_sub_iterations = param_.network_max_sub_iterations_;
1886 const Scalar network_pressure_update_damping_factor = param_.network_pressure_update_damping_factor_;
1887 const Scalar network_max_pressure_update = param_.network_max_pressure_update_in_bars_ * unit::barsa;
1888 bool more_network_sub_update =
false;
1889 for (
int i = 0; i < max_number_of_sub_iterations; i++) {
1890 const auto local_network_imbalance = this->updateNetworkPressures(episodeIdx, network_pressure_update_damping_factor, network_max_pressure_update);
1891 network_imbalance = comm.max(local_network_imbalance);
1892 const auto& balance = this->schedule()[episodeIdx].network_balance();
1893 constexpr Scalar relaxation_factor = 10.0;
1894 const Scalar tolerance = relax_network_tolerance ? relaxation_factor * balance.pressure_tolerance() : balance.pressure_tolerance();
1895 more_network_sub_update = this->networkActive() && network_imbalance > tolerance;
1896 if (!more_network_sub_update)
1899 for (
const auto& well : well_container_) {
1900 if (well->isInjector() || !well->wellEcl().predictionMode())
1903 const auto it = this->node_pressures_.find(well->wellEcl().groupName());
1904 if (it != this->node_pressures_.end()) {
1905 well->prepareWellBeforeAssembling(this->simulator_, dt, this->wgHelper(), this->wellState(), deferred_logger);
1908 this->updateAndCommunicateGroupData(episodeIdx, iterationIdx, param_.nupcol_group_rate_tolerance_,
1909 true, deferred_logger);
1911 more_network_update = more_network_sub_update || well_group_thp_updated;
1913 return { more_network_update, network_imbalance };
1917 template<
typename TypeTag>
1921 const int iterationIdx,
1924 this->updateAndCommunicateGroupData(reportStepIdx,
1926 param_.nupcol_group_rate_tolerance_,
1934 for (
const auto& well : well_container_) {
1936 const auto& ws = this->wellState().well(well->indexOfWell());
1937 if (ws.production_cmode == Well::ProducerCMode::GRUP ||
1938 ws.injection_cmode == Well::InjectorCMode::GRUP)
1940 well->updateWellStateWithTarget(
1941 simulator_, this->wgHelper(), this->wellState(), deferred_logger
1946 simulator_.gridView().comm())
1947 this->updateAndCommunicateGroupData(reportStepIdx,
1949 param_.nupcol_group_rate_tolerance_,
1954 template<
typename TypeTag>
1959 const int reportStepIdx,
1960 const int iterationIdx)
1963 bool changed =
false;
1965 const int nupcol = this->schedule()[reportStepIdx].nupcol();
1966 const int max_number_of_group_switches = param_.max_number_of_group_switches_;
1967 const bool update_group_switching_log = iterationIdx >= nupcol;
1968 const bool changed_hc = this->checkGroupHigherConstraints(group, deferred_logger, reportStepIdx, max_number_of_group_switches, update_group_switching_log);
1971 updateAndCommunicate(reportStepIdx, iterationIdx, deferred_logger);
1974 bool changed_individual =
1976 updateGroupIndividualControl(group,
1978 max_number_of_group_switches,
1979 update_group_switching_log,
1980 this->switched_inj_groups_,
1981 this->switched_prod_groups_,
1982 this->closed_offending_wells_,
1987 if (changed_individual) {
1989 updateAndCommunicate(reportStepIdx, iterationIdx, deferred_logger);
1992 for (
const std::string& groupName : group.groups()) {
1993 bool changed_this = updateGroupControls( this->schedule().getGroup(groupName, reportStepIdx), deferred_logger, reportStepIdx,iterationIdx);
1994 changed = changed || changed_this;
1999 template<
typename TypeTag>
2006 for (
const auto& well : well_container_) {
2007 const auto& wname = well->name();
2008 const auto wasClosed = wellTestState.well_is_closed(wname);
2009 well->checkWellOperability(simulator_,
2012 local_deferredLogger);
2013 const bool under_zero_target =
2014 well->wellUnderZeroGroupRateTarget(this->simulator_,
2016 local_deferredLogger);
2017 well->updateWellTestState(this->wellState().well(wname),
2022 local_deferredLogger);
2024 if (!wasClosed && wellTestState.well_is_closed(wname)) {
2025 this->closed_this_step_.insert(wname);
2028 const WellEconProductionLimits& econ_production_limits = well->wellEcl().getEconLimits();
2029 if (econ_production_limits.validFollowonWell()) {
2030 const auto episode_idx = simulator_.episodeIndex();
2031 const auto follow_on_well = econ_production_limits.followonWell();
2032 if (!this->schedule().hasWell(follow_on_well, episode_idx)) {
2033 const auto msg = fmt::format(
"Well {} was closed. But the given follow on well {} does not exist."
2034 "The simulator continues without opening a follow on well.",
2035 wname, follow_on_well);
2036 local_deferredLogger.
warning(msg);
2038 auto& ws = this->wellState().well(follow_on_well);
2039 const bool success = ws.updateStatus(WellStatus::OPEN);
2041 const auto msg = fmt::format(
"Well {} was closed. The follow on well {} opens instead.", wname, follow_on_well);
2042 local_deferredLogger.
info(msg);
2044 const auto msg = fmt::format(
"Well {} was closed. The follow on well {} is already open.", wname, follow_on_well);
2045 local_deferredLogger.
warning(msg);
2052 for (
const auto& [group_name, to] : this->closed_offending_wells_) {
2053 if (this->hasOpenLocalWell(to.second) &&
2054 !this->wasDynamicallyShutThisTimeStep(to.second))
2056 wellTestState.close_well(to.second,
2057 WellTestConfig::Reason::GROUP,
2059 this->updateClosedWellsThisStep(to.second);
2060 const std::string msg =
2061 fmt::format(
"Procedure on exceeding {} limit is WELL for group {}. "
2067 local_deferredLogger.
info(msg);
2075 if (this->terminal_output_) {
2081 template<
typename TypeTag>
2085 std::string& exc_msg,
2090 const int np = this->numPhases();
2091 std::vector<Scalar> potentials;
2092 const auto& well = well_container_[widx];
2093 std::string cur_exc_msg;
2096 well->computeWellPotentials(simulator_, well_state_copy, this->wgHelper(), potentials, deferred_logger);
2101 exc_msg += fmt::format(
"\nFor well {}: {}", well->name(), cur_exc_msg);
2103 exc_type = std::max(exc_type, cur_exc_type);
2107 auto& ws = this->wellState().well(well->indexOfWell());
2108 for (
int p = 0; p < np; ++p) {
2110 ws.well_potentials[p] = std::max(
Scalar{0.0}, potentials[p]);
2116 template <
typename TypeTag>
2121 for (
const auto& wellPtr : this->well_container_) {
2122 this->calculateProductivityIndexValues(wellPtr.get(), deferred_logger);
2130 template <
typename TypeTag>
2141 for (
const auto& shutWell : this->local_shut_wells_) {
2142 if (!this->wells_ecl_[shutWell].hasConnections()) {
2147 auto wellPtr = this->
template createTypedWellPointer
2150 wellPtr->
init(this->depth_, this->gravity_, this->B_avg_,
true);
2152 this->calculateProductivityIndexValues(wellPtr.get(), deferred_logger);
2160 template <
typename TypeTag>
2174 template<
typename TypeTag>
2180 const auto episodeIdx = simulator_.episodeIndex();
2181 this->updateNetworkActiveState(episodeIdx);
2185 const bool do_prestep_network_rebalance = param_.pre_solve_network_ && this->needPreStepNetworkRebalance(episodeIdx);
2187 for (
const auto& well : well_container_) {
2188 auto& events = this->wellState().well(well->indexOfWell()).events;
2190 well->updateWellStateWithTarget(
2191 simulator_, this->wgHelper(), this->wellState(), deferred_logger
2193 well->updatePrimaryVariables(simulator_, this->wellState(), deferred_logger);
2199 if (events.hasEvent(ScheduleEvents::REQUEST_OPEN_WELL)) {
2200 events.clearEvent(ScheduleEvents::REQUEST_OPEN_WELL);
2203 if (param_.solve_welleq_initially_ && well->isOperableAndSolvable()) {
2205 well->solveWellEquation(
2206 simulator_, this->wgHelper(), this->wellState(), deferred_logger
2208 }
catch (
const std::exception& e) {
2209 const std::string msg =
"Compute initial well solution for " + well->name() +
" initially failed. Continue with the previous rates";
2210 deferred_logger.
warning(
"WELL_INITIAL_SOLVE_FAILED", msg);
2215 well->resetWellOperability();
2217 updatePrimaryVariables(deferred_logger);
2220 if (do_prestep_network_rebalance) doPreStepNetworkRebalance(deferred_logger);
2223 template<
typename TypeTag>
2228 std::vector< Scalar > B_avg(numConservationQuantities(),
Scalar() );
2229 const auto& grid = simulator_.vanguard().grid();
2230 const auto& gridView = grid.leafGridView();
2234 for (
const auto& elem : elements(gridView, Dune::Partitions::interior)) {
2235 elemCtx.updatePrimaryStencil(elem);
2236 elemCtx.updatePrimaryIntensiveQuantities(0);
2238 const auto& intQuants = elemCtx.intensiveQuantities(0, 0);
2239 const auto& fs = intQuants.fluidState();
2241 for (
unsigned phaseIdx = 0; phaseIdx < FluidSystem::numPhases; ++phaseIdx)
2243 if (!FluidSystem::phaseIsActive(phaseIdx)) {
2247 const unsigned compIdx = FluidSystem::canonicalToActiveCompIdx(FluidSystem::solventComponentIndex(phaseIdx));
2248 auto& B = B_avg[ compIdx ];
2250 B += 1 / fs.invB(phaseIdx).value();
2252 if constexpr (has_solvent_) {
2253 auto& B = B_avg[solventSaturationIdx];
2254 B += 1 / intQuants.solventInverseFormationVolumeFactor().value();
2260 grid.comm().sum(B_avg.data(), B_avg.size());
2261 B_avg_.resize(B_avg.size());
2262 std::transform(B_avg.begin(), B_avg.end(), B_avg_.begin(),
2263 [gcells = global_num_cells_](
const auto bval)
2264 { return bval / gcells; });
2271 template<
typename TypeTag>
2276 for (
const auto& well : well_container_) {
2281 template<
typename TypeTag>
2285 const auto& grid = simulator_.vanguard().
grid();
2286 const auto& eclProblem = simulator_.problem();
2287 const unsigned numCells = grid.size(0);
2289 this->pvt_region_idx_.resize(numCells);
2290 for (
unsigned cellIdx = 0; cellIdx < numCells; ++cellIdx) {
2291 this->pvt_region_idx_[cellIdx] =
2292 eclProblem.pvtRegionIndex(cellIdx);
2297 template<
typename TypeTag>
2310 return this->numPhases() + has_solvent_;
2313 template<
typename TypeTag>
2317 const auto& eclProblem = simulator_.problem();
2318 depth_.resize(local_num_cells_);
2319 for (
unsigned cellIdx = 0; cellIdx < local_num_cells_; ++cellIdx) {
2320 depth_[cellIdx] = eclProblem.dofCenterDepth(cellIdx);
2324 template<
typename TypeTag>
2327 getWell(
const std::string& well_name)
const
2330 auto well = std::find_if(well_container_.begin(),
2331 well_container_.end(),
2333 return elem->name() == well_name;
2336 assert(well != well_container_.end());
2341 template <
typename TypeTag>
2346 return std::max(this->simulator_.episodeIndex(), 0);
2353 template<
typename TypeTag>
2358 const std::vector<Scalar>& production_rates,
2359 std::vector<Scalar>& resv_coeff)
2361 rateConverter_->calcCoeff(fipnum, pvtreg, production_rates, resv_coeff);
2364 template<
typename TypeTag>
2369 std::vector<Scalar>& resv_coeff)
2371 rateConverter_->calcInjCoeff(fipnum, pvtreg, resv_coeff);
2375 template <
typename TypeTag>
2380 if constexpr (has_energy_) {
2381 int np = this->numPhases();
2382 Scalar cellInternalEnergy;
2386 const int nw = this->numLocalWells();
2387 for (
auto wellID = 0*nw; wellID < nw; ++wellID) {
2388 const Well& well = this->wells_ecl_[wellID];
2389 auto& ws = this->wellState().well(wellID);
2390 if (well.isInjector()) {
2391 if (ws.status != WellStatus::STOP) {
2392 this->wellState().well(wellID).temperature = well.inj_temperature();
2397 std::array<Scalar,2> weighted{0.0,0.0};
2398 auto& [weighted_temperature, total_weight] = weighted;
2400 auto& well_info = this->local_parallel_well_info_[wellID].get();
2401 auto& perf_data = ws.perf_data;
2402 auto& perf_phase_rate = perf_data.phase_rates;
2404 using int_type =
decltype(this->well_perf_data_[wellID].size());
2405 for (int_type perf = 0, end_perf = this->well_perf_data_[wellID].size(); perf < end_perf; ++perf) {
2406 const int cell_idx = this->well_perf_data_[wellID][perf].cell_index;
2407 const auto& intQuants = simulator_.model().intensiveQuantities(cell_idx, 0);
2408 const auto& fs = intQuants.fluidState();
2411 Scalar cellTemperatures = fs.temperature(0).value();
2413 Scalar weight_factor = 0.0;
2414 for (
unsigned phaseIdx = 0; phaseIdx < FluidSystem::numPhases; ++phaseIdx) {
2415 if (!FluidSystem::phaseIsActive(phaseIdx)) {
2418 cellInternalEnergy = fs.enthalpy(phaseIdx).value() -
2419 fs.pressure(phaseIdx).value() / fs.density(phaseIdx).value();
2420 cellBinv = fs.invB(phaseIdx).value();
2421 cellDensity = fs.density(phaseIdx).value();
2422 perfPhaseRate = perf_phase_rate[perf*np + phaseIdx];
2423 weight_factor += cellDensity * perfPhaseRate / cellBinv * cellInternalEnergy / cellTemperatures;
2425 weight_factor = std::abs(weight_factor) + 1e-13;
2426 total_weight += weight_factor;
2427 weighted_temperature += weight_factor * cellTemperatures;
2429 well_info.communication().sum(weighted.data(), 2);
2430 this->wellState().well(wellID).temperature = weighted_temperature / total_weight;
2436 template <
typename TypeTag>
2440 const auto reportStepIdx =
static_cast<unsigned int>(this->reportStepIndex());
2441 const auto& trMod = this->simulator_.problem().tracerModel();
2447 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:236
BlackoilWellModelWBP< GetPropType< TypeTag, Properties::Scalar >, GetPropType< TypeTag, Properties::FluidSystem >::IndexTraitsType > wbp_
Definition: BlackoilWellModelGeneric.hpp:530
std::vector< ParallelWellInfo< GetPropType< TypeTag, Properties::Scalar > > > parallel_well_info_
Definition: BlackoilWellModelGeneric.hpp:559
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:102
void initializeGroupStructure(const int reportStepIdx)
Definition: BlackoilWellModel_impl.hpp:292
void init()
Definition: BlackoilWellModel_impl.hpp:158
const Simulator & simulator() const
Definition: BlackoilWellModel.hpp:372
std::vector< Scalar > depth_
Definition: BlackoilWellModel.hpp:431
std::size_t global_num_cells_
Definition: BlackoilWellModel.hpp:427
GetPropType< TypeTag, Properties::Scalar > Scalar
Definition: BlackoilWellModel.hpp:111
void initWellContainer(const int reportStepIdx) override
Definition: BlackoilWellModel_impl.hpp:177
void beginReportStep(const int time_step)
Definition: BlackoilWellModel_impl.hpp:194
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:748
const Grid & grid() const
Definition: BlackoilWellModel.hpp:369
const SimulatorReportSingle & lastReport() const
Definition: BlackoilWellModel_impl.hpp:624
void addWellContributions(SparseMatrixAdapter &jacobian) const
Definition: BlackoilWellModel_impl.hpp:1592
Dune::BCRSMatrix< Opm::MatrixBlock< Scalar, 1, 1 > > PressureMatrix
Definition: BlackoilWellModel.hpp:297
bool empty() const
Definition: BlackoilWellModel.hpp:342
void computeTotalRatesForDof(RateVector &rate, unsigned globalIdx) const
Definition: BlackoilWellModel_impl.hpp:711
void beginTimeStep()
Definition: BlackoilWellModel_impl.hpp:328
GetPropType< TypeTag, Properties::RateVector > RateVector
Definition: BlackoilWellModel.hpp:112
void calculateExplicitQuantities(DeferredLogger &deferred_logger) const
Definition: BlackoilWellModel_impl.hpp:1767
void updatePrimaryVariables(DeferredLogger &deferred_logger)
Definition: BlackoilWellModel_impl.hpp:2274
void initializeLocalWellStructure(const int reportStepIdx, const bool enableWellPIScaling)
Definition: BlackoilWellModel_impl.hpp:247
Dune::BlockVector< VectorBlockType > BVector
Definition: BlackoilWellModel.hpp:133
BlackoilWellModel(Simulator &simulator)
Definition: BlackoilWellModel_impl.hpp:73
void wellTesting(const int timeStepIdx, const double simulationTime, DeferredLogger &deferred_logger)
Definition: BlackoilWellModel_impl.hpp:536
typename FluidSystem::IndexTraitsType IndexTraits
Definition: BlackoilWellModel.hpp:118
std::size_t local_num_cells_
Definition: BlackoilWellModel.hpp:429
bool alternative_well_rate_init_
Definition: BlackoilWellModel.hpp:432
void timeStepSucceeded(const double simulationTime, const double dt)
Definition: BlackoilWellModel_impl.hpp:634
Simulator & simulator_
Definition: BlackoilWellModel.hpp:401
void createWellContainer(const int report_step) override
Definition: BlackoilWellModel_impl.hpp:791
std::unique_ptr< WellInterface< TypeTag > > WellInterfacePtr
Definition: BlackoilWellModel.hpp:190
int compressedIndexForInterior(int cartesian_cell_idx) const override
get compressed index for interior cells (-1, otherwise
Definition: BlackoilWellModel.hpp:350
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: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: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:49
int indexOfWell() const
Index of well in the wells struct and wellState.
Definition: WellInterface.hpp:77
bool updateWellControl(const Simulator &simulator, const IndividualOrGroup iog, const WellGroupHelperType &wgHelper, WellStateType &well_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: blackoilbioeffectsmodules.hh:43
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