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->report_step_starts_ =
true;
199 this->report_step_start_events_ = this->schedule()[timeStepIdx].wellgroup_events();
201 this->rateConverter_ = std::make_unique<RateConverterType>
202 (std::vector<int>(this->local_num_cells_, 0));
206 const auto enableWellPIScaling =
true;
207 this->initializeLocalWellStructure(timeStepIdx, enableWellPIScaling);
210 this->initializeGroupStructure(timeStepIdx);
212 const auto& comm = this->simulator_.vanguard().grid().comm();
218 this->rateConverter_->template defineState<ElementContext>(this->simulator_);
222 const auto& sched_state = this->schedule()[timeStepIdx];
224 this->vfp_properties_ = std::make_unique<VFPProperties<Scalar, IndexTraits>>
225 (sched_state.vfpinj(), sched_state.vfpprod(), this->wellState());
229 "beginReportStep() failed: ",
230 this->terminal_output_, comm)
234 this->commitWGState();
236 this->wellStructureChangedDynamically_ =
false;
243 template <
typename TypeTag>
247 const bool enableWellPIScaling)
251 const auto& comm = this->simulator_.vanguard().grid().comm();
254 this->wells_ecl_ = this->getLocalWells(reportStepIdx);
255 this->local_parallel_well_info_ =
256 this->createLocalParallelWellInfo(this->wells_ecl_);
263 this->initializeWellPerfData();
264 this->initializeWellState(reportStepIdx);
265 this->wbp_.initializeWBPCalculationService();
267 if (this->param_.use_multisegment_well_ && this->anyMSWellOpenLocal()) {
268 this->wellState().initWellStateMSWell(this->wells_ecl_, &this->prevWellState());
271 this->initializeWellProdIndCalculators();
273 if (enableWellPIScaling && this->schedule()[reportStepIdx].events()
274 .hasEvent(ScheduleEvents::Events::WELL_PRODUCTIVITY_INDEX))
276 this->runWellPIScaling(reportStepIdx, local_deferredLogger);
280 "Failed to initialize local well structure: ",
281 this->terminal_output_, comm)
288 template <
typename TypeTag>
295 const auto& comm = this->simulator_.vanguard().grid().comm();
299 const auto& fieldGroup =
300 this->schedule().getGroup(
"FIELD", reportStepIdx);
302 WellGroupHelpersType::setCmodeGroup(fieldGroup,
304 this->summaryState(),
310 if (this->schedule()[reportStepIdx].has_gpmaint()) {
311 WellGroupHelpersType::setRegionAveragePressureCalculator(fieldGroup,
314 this->eclState_.fieldProps(),
315 this->regionalAveragePressureCalculator_);
319 "Failed to initialize group structure: ",
320 this->terminal_output_, comm)
328 template<
typename TypeTag>
333 OPM_TIMEBLOCK(beginTimeStep);
335 this->updateAverageFormationFactor();
339 this->switched_prod_groups_.clear();
340 this->switched_inj_groups_.clear();
342 if (this->wellStructureChangedDynamically_) {
347 const auto reportStepIdx =
348 this->simulator_.episodeIndex();
352 const auto enableWellPIScaling =
false;
354 this->initializeLocalWellStructure(reportStepIdx, enableWellPIScaling);
355 this->initializeGroupStructure(reportStepIdx);
357 this->commitWGState();
363 this->wellStructureChangedDynamically_ =
false;
366 this->resetWGState();
368 const int reportStepIdx = simulator_.episodeIndex();
371 this->wellState().updateWellsDefaultALQ(this->schedule(), reportStepIdx, this->summaryState());
372 this->wellState().gliftTimeStepInit();
374 const double simulationTime = simulator_.time();
378 wellTesting(reportStepIdx, simulationTime, local_deferredLogger);
381 createWellContainer(reportStepIdx);
385 this->updateAndCommunicateGroupData(reportStepIdx,
386 simulator_.model().newtonMethod().numIterations(),
387 param_.nupcol_group_rate_tolerance_,
false,
388 local_deferredLogger);
391 const Grid& grid = simulator_.vanguard().grid();
392 this->wells_active_ = grid.comm().max(!this->well_container_.empty());
397 this->initWellContainer(reportStepIdx);
400 std::fill(is_cell_perforated_.begin(), is_cell_perforated_.end(),
false);
401 for (
auto& well : well_container_) {
402 well->updatePerforatedCell(is_cell_perforated_);
406 this->calculateEfficiencyFactors(reportStepIdx);
408 if constexpr (has_polymer_)
410 if (PolymerModule::hasPlyshlog() || getPropValue<TypeTag, Properties::EnablePolymerMW>() ) {
411 this->setRepRadiusPerfLength();
418 this->terminal_output_, simulator_.vanguard().grid().comm());
420 for (
auto& well : well_container_) {
421 well->setVFPProperties(this->vfp_properties_.get());
422 well->setGuideRate(&this->guideRate_);
425 this->updateFiltrationModelsPreStep(local_deferredLogger);
428 for (
auto& well : well_container_) {
429 well->closeCompletions(this->wellTestState());
435 if (alternative_well_rate_init_) {
440 for (
const auto& well : well_container_) {
441 if (well->isProducer() && !well->wellIsStopped()) {
442 well->initializeProducerWellState(simulator_, this->wellState(), local_deferredLogger);
447 for (
const auto& well : well_container_) {
448 if (well->isVFPActive(local_deferredLogger)){
449 well->setPrevSurfaceRates(this->wellState(), this->prevWellState());
453 this->updateWellPotentials(reportStepIdx,
455 simulator_.vanguard().summaryConfig(),
456 local_deferredLogger);
457 }
catch ( std::runtime_error& e ) {
458 const std::string msg =
"A zero well potential is returned for output purposes. ";
459 local_deferredLogger.
warning(
"WELL_POTENTIAL_CALCULATION_FAILED", msg);
461 this->guide_rate_handler_.setLogger(&local_deferredLogger);
462#ifdef RESERVOIR_COUPLING_ENABLED
463 if (this->isReservoirCouplingMaster()) {
464 this->guide_rate_handler_.receiveMasterGroupPotentialsFromSlaves();
468 this->guide_rate_handler_.updateGuideRates(
469 reportStepIdx, simulationTime, this->wellState(), this->groupState()
471#ifdef RESERVOIR_COUPLING_ENABLED
472 if (this->isReservoirCouplingSlave()) {
473 this->guide_rate_handler_.sendSlaveGroupPotentialsToMaster(this->groupState());
479 if (this->schedule_[reportStepIdx].has_gpmaint()) {
480 for (
const auto& calculator : regionalAveragePressureCalculator_) {
481 calculator.second->template defineState<ElementContext>(simulator_);
483 const double dt = simulator_.timeStepSize();
484 const Group& fieldGroup = this->schedule().getGroup(
"FIELD", reportStepIdx);
487 regionalAveragePressureCalculator_,
494 this->updateAndCommunicateGroupData(reportStepIdx,
495 simulator_.model().newtonMethod().numIterations(),
496 param_.nupcol_group_rate_tolerance_,
498 local_deferredLogger);
501 for (
auto& well : well_container_) {
502 const uint64_t effective_events_mask = ScheduleEvents::WELL_STATUS_CHANGE
503 + ScheduleEvents::INJECTION_TYPE_CHANGED
504 + ScheduleEvents::WELL_SWITCHED_INJECTOR_PRODUCER
505 + ScheduleEvents::NEW_WELL;
507 const auto& events = this->schedule()[reportStepIdx].wellgroup_events();
508 const bool event = this->report_step_starts_ && events.hasEvent(well->name(), effective_events_mask);
509 const bool dyn_status_change = this->wellState().well(well->name()).status
510 != this->prevWellState().well(well->name()).status;
512 if (event || dyn_status_change) {
514 well->scaleSegmentRatesAndPressure(this->wellState());
515 well->calculateExplicitQuantities(simulator_, this->wellState(), local_deferredLogger);
516 well->updateWellStateWithTarget(simulator_, this->groupState(), this->wellState(), local_deferredLogger);
517 well->updatePrimaryVariables(simulator_, this->wellState(), local_deferredLogger);
518 well->solveWellEquation(simulator_, this->wellState(), this->groupState(), local_deferredLogger);
519 }
catch (
const std::exception& e) {
520 const std::string msg =
"Compute initial well solution for new well " + well->name() +
" failed. Continue with zero initial rates";
521 local_deferredLogger.
warning(
"WELL_INITIAL_SOLVE_FAILED", msg);
530 const std::string msg =
"Compute initial well solution for new wells failed. Continue with zero initial rates";
531 local_deferredLogger.
warning(
"WELL_INITIAL_SOLVE_FAILED", msg);
534 const auto& comm = simulator_.vanguard().grid().comm();
536 exc_type,
"beginTimeStep() failed: " + exc_msg, this->terminal_output_, comm);
540 template<
typename TypeTag>
543 const double simulationTime,
546 for (
const std::string& well_name : this->getWellsForTesting(timeStepIdx, simulationTime)) {
547 const Well& wellEcl = this->schedule().getWell(well_name, timeStepIdx);
548 if (wellEcl.getStatus() == Well::Status::SHUT)
551 WellInterfacePtr well = createWellForWellTest(well_name, timeStepIdx, deferred_logger);
553 well->init(depth_, gravity_, B_avg_,
true);
555 Scalar well_efficiency_factor = wellEcl.getEfficiencyFactor() *
556 this->wellState().getGlobalEfficiencyScalingFactor(well_name);
557 WellGroupHelpersType::accumulateGroupEfficiencyFactor(this->schedule().getGroup(wellEcl.groupName(),
561 well_efficiency_factor);
563 well->setWellEfficiencyFactor(well_efficiency_factor);
564 well->setVFPProperties(this->vfp_properties_.get());
565 well->setGuideRate(&this->guideRate_);
568 if (well->isProducer() && alternative_well_rate_init_) {
569 well->initializeProducerWellState(simulator_, this->wellState(), deferred_logger);
571 if (well->isVFPActive(deferred_logger)) {
572 well->setPrevSurfaceRates(this->wellState(), this->prevWellState());
575 const auto& network = this->schedule()[timeStepIdx].network();
576 if (network.active() && !this->node_pressures_.empty()) {
577 if (well->isProducer()) {
578 const auto it = this->node_pressures_.find(well->wellEcl().groupName());
579 if (it != this->node_pressures_.end()) {
582 const Scalar nodal_pressure = it->second;
583 well->setDynamicThpLimit(nodal_pressure);
589 GLiftEclWells ecl_well_map;
590 gaslift_.initGliftEclWellMap(well_container_, ecl_well_map);
591 well->wellTesting(simulator_,
595 this->wellTestState(),
597 this->well_open_times_,
599 }
catch (
const std::exception& e) {
600 const std::string msg = fmt::format(
"Exception during testing of well: {}. The well will not open.\n Exception message: {}", wellEcl.name(), e.what());
601 deferred_logger.
warning(
"WELL_TESTING_FAILED", msg);
611 template<
typename TypeTag>
617 for (
auto&& pinfo : this->local_parallel_well_info_)
628 template<
typename TypeTag>
638 template<
typename TypeTag>
643 this->closed_this_step_.clear();
646 this->report_step_starts_ =
false;
647 const int reportStepIdx = simulator_.episodeIndex();
650 for (
const auto& well : well_container_) {
651 if (getPropValue<TypeTag, Properties::EnablePolymerMW>() && well->isInjector()) {
652 well->updateWaterThroughput(dt, this->wellState());
656 for (
const auto& well : well_container_) {
657 well->updateConnectionTransmissibilityFactor(simulator_, this->wellState().well(well->indexOfWell()));
658 well->updateConnectionDFactor(simulator_, this->wellState().well(well->indexOfWell()));
661 if (Indices::waterEnabled) {
662 this->updateFiltrationModelsPostStep(dt, FluidSystem::waterPhaseIdx, local_deferredLogger);
666 this->updateInjMult(local_deferredLogger);
669 for (
const auto& well : well_container_) {
670 well->reportWellSwitching(this->wellState().well(well->indexOfWell()), local_deferredLogger);
673 if (this->terminal_output_) {
674 this->reportGroupSwitching(local_deferredLogger);
678 rateConverter_->template defineState<ElementContext>(simulator_);
682 this->updateWellPotentials(reportStepIdx,
684 simulator_.vanguard().summaryConfig(),
685 local_deferredLogger);
686 }
catch ( std::runtime_error& e ) {
687 const std::string msg =
"A zero well potential is returned for output purposes. ";
688 local_deferredLogger.
warning(
"WELL_POTENTIAL_CALCULATION_FAILED", msg);
691 updateWellTestState(simulationTime, this->wellTestState());
694 const Group& fieldGroup = this->schedule_.getGroup(
"FIELD", reportStepIdx);
695 this->checkGEconLimits(fieldGroup, simulationTime,
696 simulator_.episodeIndex(), local_deferredLogger);
697 this->checkGconsaleLimits(fieldGroup, this->wellState(),
698 simulator_.episodeIndex(), local_deferredLogger);
700 this->calculateProductivityIndexValues(local_deferredLogger);
702 this->commitWGState();
706 if (this->terminal_output_) {
711 this->computeWellTemperature();
715 template<
typename TypeTag>
719 unsigned elemIdx)
const
723 if (!is_cell_perforated_[elemIdx]) {
727 for (
const auto& well : well_container_)
728 well->addCellRates(rate, elemIdx);
732 template<
typename TypeTag>
733 template <
class Context>
737 const Context& context,
739 unsigned timeIdx)
const
742 int elemIdx = context.globalSpaceIndex(spaceIdx, timeIdx);
744 if (!is_cell_perforated_[elemIdx]) {
748 for (
const auto& well : well_container_)
749 well->addCellRates(rate, elemIdx);
754 template<
typename TypeTag>
759 const auto pressIx = []()
761 if (Indices::oilEnabled) {
return FluidSystem::oilPhaseIdx; }
762 if (Indices::waterEnabled) {
return FluidSystem::waterPhaseIdx; }
764 return FluidSystem::gasPhaseIdx;
767 auto cellPressures = std::vector<Scalar>(this->local_num_cells_,
Scalar{0});
768 auto cellTemperatures = std::vector<Scalar>(this->local_num_cells_,
Scalar{0});
771 const auto& gridView = this->simulator_.vanguard().gridView();
774 for (
const auto& elem : elements(gridView, Dune::Partitions::interior)) {
775 elemCtx.updatePrimaryStencil(elem);
776 elemCtx.updatePrimaryIntensiveQuantities(0);
778 const auto ix = elemCtx.globalSpaceIndex(0, 0);
779 const auto& fs = elemCtx.intensiveQuantities(0, 0).fluidState();
781 cellPressures[ix] = fs.pressure(pressIx).value();
782 cellTemperatures[ix] = fs.temperature(0).value();
785 this->simulator_.vanguard().grid().comm());
787 this->wellState().init(cellPressures, cellTemperatures, this->schedule(), this->wells_ecl_,
788 this->local_parallel_well_info_, timeStepIdx,
789 &this->prevWellState(), this->well_perf_data_,
790 this->summaryState(), simulator_.vanguard().enableDistributedWells());
797 template<
typename TypeTag>
804 const int nw = this->numLocalWells();
806 well_container_.clear();
809 well_container_.reserve(nw);
811 const auto& wmatcher = this->schedule().wellMatcher(report_step);
812 const auto& wcycle = this->schedule()[report_step].wcycle.get();
816 std::for_each(this->wells_ecl_.begin(), this->wells_ecl_.end(),
817 [
this, &wg_events = this->report_step_start_events_](
const auto& well_ecl)
819 if (!well_ecl.hasConnections()) {
824 constexpr auto events_mask = ScheduleEvents::WELL_STATUS_CHANGE |
825 ScheduleEvents::REQUEST_OPEN_WELL |
826 ScheduleEvents::REQUEST_SHUT_WELL;
827 const bool well_event =
828 this->report_step_starts_ &&
829 wg_events.hasEvent(well_ecl.name(), events_mask);
838 if (well_ecl.getStatus() == WellStatus::OPEN) {
839 this->well_open_times_.insert_or_assign(well_ecl.name(),
840 this->simulator_.time());
841 this->well_close_times_.erase(well_ecl.name());
842 }
else if (well_ecl.getStatus() == WellStatus::SHUT) {
843 this->well_close_times_.insert_or_assign(well_ecl.name(),
844 this->simulator_.time());
845 this->well_open_times_.erase(well_ecl.name());
851 const auto cycle_states = wcycle.wellStatus(this->simulator_.time(),
853 this->well_open_times_,
854 this->well_close_times_);
856 for (
int w = 0; w < nw; ++w) {
857 const Well& well_ecl = this->wells_ecl_[w];
859 if (!well_ecl.hasConnections()) {
864 const std::string& well_name = well_ecl.name();
865 const auto well_status = this->schedule()
866 .getWell(well_name, report_step).getStatus();
868 const bool shut_event = this->wellState().well(w).events.hasEvent(ScheduleEvents::WELL_STATUS_CHANGE)
869 && well_status == Well::Status::SHUT;
870 const bool open_event = this->wellState().well(w).events.hasEvent(ScheduleEvents::WELL_STATUS_CHANGE)
871 && well_status == Well::Status::OPEN;
872 const auto& ws = this->wellState().well(well_name);
874 if (shut_event && ws.status != Well::Status::SHUT) {
875 this->closed_this_step_.insert(well_name);
876 this->wellState().shutWell(w);
877 }
else if (open_event && ws.status != Well::Status::OPEN) {
878 this->wellState().openWell(w);
882 if (this->wellTestState().well_is_closed(well_name)) {
887 const bool closed_this_step = (this->wellTestState().lastTestTime(well_name) == simulator_.time());
890 auto& events = this->wellState().well(w).events;
891 if (events.hasEvent(ScheduleEvents::REQUEST_OPEN_WELL)) {
892 if (!closed_this_step) {
893 this->wellTestState().open_well(well_name);
894 this->wellTestState().open_completions(well_name);
895 this->well_open_times_.insert_or_assign(well_name,
896 this->simulator_.time());
897 this->well_close_times_.erase(well_name);
899 events.clearEvent(ScheduleEvents::REQUEST_OPEN_WELL);
905 if (this->wellTestState().well_is_closed(well_name))
907 if (well_ecl.getAutomaticShutIn()) {
909 this->wellState().shutWell(w);
910 this->well_close_times_.erase(well_name);
911 this->well_open_times_.erase(well_name);
914 if (!well_ecl.getAllowCrossFlow()) {
917 this->wellState().shutWell(w);
918 this->well_close_times_.erase(well_name);
919 this->well_open_times_.erase(well_name);
923 this->wellState().stopWell(w);
928 if (!well_ecl.getAllowCrossFlow()) {
929 const bool any_zero_rate_constraint = well_ecl.isProducer()
930 ? well_ecl.productionControls(this->summaryState_).anyZeroRateConstraint()
931 : well_ecl.injectionControls(this->summaryState_).anyZeroRateConstraint();
932 if (any_zero_rate_constraint) {
934 local_deferredLogger.
debug(fmt::format(
" Well {} gets shut due to having zero rate constraint and disallowing crossflow ", well_ecl.name()) );
935 this->wellState().shutWell(w);
936 this->well_close_times_.erase(well_name);
937 this->well_open_times_.erase(well_name);
942 if (!wcycle.empty()) {
943 const auto it = cycle_states.find(well_name);
944 if (it != cycle_states.end()) {
945 if (!it->second || well_status == Well::Status::SHUT) {
947 if (well_status == Well::Status::SHUT) {
948 this->well_open_times_.erase(well_name);
949 this->well_close_times_.erase(well_name);
951 this->wellState().shutWell(w);
954 this->wellState().openWell(w);
960 if (ws.status == Well::Status::SHUT) {
964 well_container_.emplace_back(this->createWellPointer(w, report_step));
966 if (ws.status == Well::Status::STOP) {
967 well_container_.back()->stopWell();
968 this->well_close_times_.erase(well_name);
969 this->well_open_times_.erase(well_name);
973 if (!wcycle.empty()) {
974 const auto schedule_open =
975 [&wg_events = this->report_step_start_events_](
const std::string& name)
977 return wg_events.hasEvent(name, ScheduleEvents::REQUEST_OPEN_WELL);
979 for (
const auto& [wname, wscale] : wcycle.efficiencyScale(this->simulator_.time(),
980 this->simulator_.timeStepSize(),
982 this->well_open_times_,
985 this->wellState().updateEfficiencyScalingFactor(wname, wscale);
986 this->schedule_.add_event(ScheduleEvents::WELLGROUP_EFFICIENCY_UPDATE, report_step);
995 if (this->terminal_output_) {
999 this->well_container_generic_.clear();
1000 for (
auto& w : well_container_)
1001 this->well_container_generic_.push_back(w.get());
1003 const auto& network = this->schedule()[report_step].network();
1004 if (network.active() && !this->node_pressures_.empty()) {
1005 for (
auto& well: this->well_container_generic_) {
1009 if (well->isProducer()) {
1010 const auto it = this->node_pressures_.find(well->wellEcl().groupName());
1011 if (it != this->node_pressures_.end()) {
1014 const Scalar nodal_pressure = it->second;
1015 well->setDynamicThpLimit(nodal_pressure);
1021 this->wbp_.registerOpenWellsForWBPCalculation();
1028 template <
typename TypeTag>
1029 typename BlackoilWellModel<TypeTag>::WellInterfacePtr
1033 const auto is_multiseg = this->wells_ecl_[wellID].isMultiSegment();
1035 if (! (this->param_.use_multisegment_well_ && is_multiseg)) {
1036 return this->
template createTypedWellPointer<StandardWell<TypeTag>>(wellID, report_step);
1039 return this->
template createTypedWellPointer<MultisegmentWell<TypeTag>>(wellID, report_step);
1047 template <
typename TypeTag>
1048 template <
typename WellType>
1049 std::unique_ptr<WellType>
1054 const auto& perf_data = this->well_perf_data_[wellID];
1057 const auto pvtreg = perf_data.
empty()
1058 ? 0 : this->pvt_region_idx_[perf_data.front().cell_index];
1060 const auto& parallel_well_info = this->local_parallel_well_info_[wellID].get();
1061 const auto global_pvtreg = parallel_well_info.broadcastFirstPerforationValue(pvtreg);
1063 return std::make_unique<WellType>(this->wells_ecl_[wellID],
1067 *this->rateConverter_,
1069 this->numConservationQuantities(),
1079 template<
typename TypeTag>
1083 const int report_step,
1087 const auto it = std::find_if(this->wells_ecl_.begin(),
1088 this->wells_ecl_.end(),
1089 [&well_name](
const auto& w)
1090 { return well_name == w.name(); });
1092 if (it == this->wells_ecl_.end()) {
1094 fmt::format(
"Could not find well {} in wells_ecl ", well_name),
1098 const int pos =
static_cast<int>(std::distance(this->wells_ecl_.begin(), it));
1099 return this->createWellPointer(pos, report_step);
1104 template<
typename TypeTag>
1110 const double dt = this->simulator_.timeStepSize();
1112 auto& well_state = this->wellState();
1114 const bool changed_well_group = updateWellControlsAndNetwork(
true, dt, deferred_logger);
1115 assembleWellEqWithoutIteration(dt, deferred_logger);
1116 const bool converged = this->getWellConvergence(this->B_avg_,
true).converged() && !changed_well_group;
1119 for (
auto& well : this->well_container_) {
1120 well->solveEqAndUpdateWellState(simulator_, well_state, deferred_logger);
1123 this->simulator_.vanguard().grid().comm());
1126 const std::string msg = fmt::format(
"Initial (pre-step) network balance did not converge.");
1134 template<
typename TypeTag>
1143 this->guide_rate_handler_.setLogger(&local_deferredLogger);
1145 if (gaslift_.terminalOutput()) {
1146 const std::string msg =
1147 fmt::format(
"assemble() : iteration {}" , iterationIdx);
1148 gaslift_.gliftDebug(msg, local_deferredLogger);
1152 Dune::Timer perfTimer;
1154 this->closed_offending_wells_.clear();
1157 const int episodeIdx = simulator_.episodeIndex();
1158 const auto& network = this->schedule()[episodeIdx].network();
1159 if (!this->wellsActive() && !network.active()) {
1164 if (iterationIdx == 0 && this->wellsActive()) {
1165 OPM_TIMEBLOCK(firstIterationAssmble);
1172 calculateExplicitQuantities(local_deferredLogger);
1173 prepareTimeStep(local_deferredLogger);
1176 "assemble() failed (It=0): ",
1177 this->terminal_output_, grid().comm());
1180 const bool well_group_control_changed = updateWellControlsAndNetwork(
false, dt, local_deferredLogger);
1184 if ( ! this->wellsActive() ) {
1188 assembleWellEqWithoutIteration(dt, local_deferredLogger);
1192 last_report_.well_group_control_changed = well_group_control_changed;
1193 last_report_.assemble_time_well += perfTimer.stop();
1199 template<
typename TypeTag>
1208 bool do_network_update =
true;
1209 bool well_group_control_changed =
false;
1210 Scalar network_imbalance = 0.0;
1212 const std::size_t iteration_to_relax = param_.network_max_strict_outer_iterations_;
1214 const std::size_t max_iteration = param_.network_max_outer_iterations_;
1215 std::size_t network_update_iteration = 0;
1216 network_needs_more_balancing_force_another_newton_iteration_ =
false;
1217 while (do_network_update) {
1218 if (network_update_iteration >= max_iteration ) {
1220 const int episodeIdx = simulator_.episodeIndex();
1221 const int iterationIdx = simulator_.model().newtonMethod().numIterations();
1222 if (this->shouldBalanceNetwork(episodeIdx, iterationIdx + 1)) {
1223 if (this->terminal_output_) {
1224 const std::string msg = fmt::format(
"Maximum of {:d} network iterations has been used and we stop the update, \n"
1225 "and try again after the next Newton iteration (imbalance = {:.2e} bar, ctrl_change = {})",
1226 max_iteration, network_imbalance*1.0e-5, well_group_control_changed);
1227 local_deferredLogger.
debug(msg);
1231 network_needs_more_balancing_force_another_newton_iteration_ =
true;
1233 if (this->terminal_output_) {
1234 const std::string msg = fmt::format(
"Maximum of {:d} network iterations has been used and we stop the update. \n"
1235 "The simulator will continue with unconverged network results (imbalance = {:.2e} bar, ctrl_change = {})",
1236 max_iteration, network_imbalance*1.0e-5, well_group_control_changed);
1237 local_deferredLogger.
info(msg);
1242 if (this->terminal_output_ && (network_update_iteration == iteration_to_relax) ) {
1243 local_deferredLogger.
debug(
"We begin using relaxed tolerance for network update now after " +
std::to_string(iteration_to_relax) +
" iterations ");
1245 const bool relax_network_balance = network_update_iteration >= iteration_to_relax;
1247 const bool optimize_gas_lift = ( (network_update_iteration + 1) < std::max(max_iteration,
static_cast<std::size_t
>(2)) );
1248 std::tie(well_group_control_changed, do_network_update, network_imbalance) =
1249 updateWellControlsAndNetworkIteration(mandatory_network_balance, relax_network_balance, optimize_gas_lift, dt,local_deferredLogger);
1250 ++network_update_iteration;
1252 return well_group_control_changed;
1258 template<
typename TypeTag>
1259 std::tuple<bool, bool, typename BlackoilWellModel<TypeTag>::Scalar>
1262 const bool relax_network_tolerance,
1263 const bool optimize_gas_lift,
1268 const int iterationIdx = simulator_.model().newtonMethod().numIterations();
1269 const int reportStepIdx = simulator_.episodeIndex();
1270 this->updateAndCommunicateGroupData(reportStepIdx, iterationIdx,
1271 param_.nupcol_group_rate_tolerance_,
true, local_deferredLogger);
1276 bool well_group_control_changed = updateWellControls(local_deferredLogger);
1277 const auto [more_inner_network_update, network_imbalance] =
1278 updateNetworks(mandatory_network_balance,
1279 local_deferredLogger,
1280 relax_network_tolerance);
1283 bool alq_updated =
false;
1286 if (optimize_gas_lift) {
1289 const bool updatePotentials = (this->shouldBalanceNetwork(reportStepIdx, iterationIdx) || mandatory_network_balance);
1290 alq_updated = gaslift_.maybeDoGasLiftOptimize(simulator_,
1292 this->node_pressures_,
1296 local_deferredLogger);
1298 prepareWellsBeforeAssembling(dt, local_deferredLogger);
1301 "updateWellControlsAndNetworkIteration() failed: ",
1302 this->terminal_output_, grid().comm());
1306 guideRateUpdateIsNeeded(reportStepIdx)) {
1307 const double simulationTime = simulator_.time();
1311 this->guide_rate_handler_.updateGuideRates(
1312 reportStepIdx, simulationTime, this->wellState(), this->groupState()
1317 const bool more_network_update = this->shouldBalanceNetwork(reportStepIdx, iterationIdx) &&
1318 (more_inner_network_update || well_group_control_changed || alq_updated);
1319 return {well_group_control_changed, more_network_update, network_imbalance};
1325 template <
typename TypeTag>
1331 const int reportStepIdx = this->simulator_.episodeIndex();
1332 const auto& network = this->schedule()[reportStepIdx].network();
1333 const auto& balance = this->schedule()[reportStepIdx].network_balance();
1334 const Scalar thp_tolerance = balance.thp_tolerance();
1336 if (!network.active()) {
1340 auto& well_state = this->wellState();
1341 auto& group_state = this->groupState();
1343 bool well_group_thp_updated =
false;
1344 for (
const std::string& nodeName : network.node_names()) {
1345 const bool has_choke = network.node(nodeName).as_choke();
1347 const auto& summary_state = this->simulator_.vanguard().summaryState();
1348 const Group& group = this->schedule().getGroup(nodeName, reportStepIdx);
1351 std::vector<Scalar> resv_coeff(Indices::numPhases, 1.0);
1352 Scalar gratTargetFromSales = 0.0;
1353 if (group_state.has_grat_sales_target(group.name()))
1354 gratTargetFromSales = group_state.grat_sales_target(group.name());
1356 const auto ctrl = group.productionControls(summary_state);
1357 auto cmode_tmp = ctrl.cmode;
1359 bool fld_none =
false;
1364 const Scalar efficiencyFactor = 1.0;
1365 const Group& parentGroup = this->schedule().getGroup(group.parent(), reportStepIdx);
1377 local_deferredLogger);
1378 target_tmp = target.first;
1379 cmode_tmp = target.second;
1381 const auto cmode = cmode_tmp;
1383 TargetCalculatorType tcalc(cmode, FluidSystem::phaseUsage(), resv_coeff,
1384 gratTargetFromSales, nodeName, group_state,
1385 group.has_gpmaint_control(cmode));
1389 target_tmp = tcalc.groupTarget(ctrl, local_deferredLogger);
1392 const Scalar orig_target = target_tmp;
1394 auto mismatch = [&] (
auto group_thp) {
1397 for (
auto& well : this->well_container_) {
1398 std::string well_name = well->name();
1399 auto& ws = well_state.well(well_name);
1400 if (group.hasWell(well_name)) {
1401 well->setDynamicThpLimit(group_thp);
1402 const Well& well_ecl = this->wells_ecl_[well->indexOfWell()];
1403 const auto inj_controls = Well::InjectionControls(0);
1404 const auto prod_controls = well_ecl.productionControls(summary_state);
1405 well->iterateWellEqWithSwitching(this->simulator_, dt, inj_controls, prod_controls, well_state, group_state, local_deferredLogger,
false,
false);
1406 rate = -tcalc.calcModeRateFromRates(ws.surface_rates);
1410 return (group_rate - orig_target)/orig_target;
1413 const auto upbranch = network.uptree_branch(nodeName);
1414 const auto it = this->node_pressures_.find((*upbranch).uptree_node());
1415 const Scalar nodal_pressure = it->second;
1416 Scalar well_group_thp = nodal_pressure;
1418 std::optional<Scalar> autochoke_thp;
1419 if (
auto iter = this->well_group_thp_calc_.find(nodeName); iter != this->well_group_thp_calc_.end()) {
1420 autochoke_thp = this->well_group_thp_calc_.at(nodeName);
1425 std::array<Scalar, 2> range_initial;
1426 if (!autochoke_thp.has_value()){
1429 std::string node_name = nodeName;
1430 while (!network.node(node_name).terminal_pressure().has_value()) {
1431 auto branch = network.uptree_branch(node_name).value();
1432 node_name = branch.uptree_node();
1434 min_thp = network.node(node_name).terminal_pressure().value();
1435 WellBhpThpCalculatorType::bruteForceBracketCommonTHP(mismatch, min_thp, max_thp);
1438 std::array<Scalar, 2> range = {
Scalar{0.9}*min_thp,
Scalar{1.1}*max_thp};
1439 std::optional<Scalar> appr_sol;
1440 WellBhpThpCalculatorType::bruteForceBracketCommonTHP(mismatch, range, low1, high1, appr_sol, 0.0, local_deferredLogger);
1443 range_initial = {min_thp, max_thp};
1446 if (!autochoke_thp.has_value() || autochoke_thp.value() > nodal_pressure) {
1448 std::array<Scalar, 2> range = autochoke_thp.has_value() ?
1449 std::array<Scalar, 2>{
Scalar{0.9} * autochoke_thp.value(),
1450 Scalar{1.1} * autochoke_thp.value()} : range_initial;
1452 std::optional<Scalar> approximate_solution;
1453 const Scalar tolerance1 = thp_tolerance;
1454 local_deferredLogger.
debug(
"Using brute force search to bracket the group THP");
1455 const bool finding_bracket = WellBhpThpCalculatorType::bruteForceBracketCommonTHP(mismatch, range, low, high, approximate_solution, tolerance1, local_deferredLogger);
1457 if (approximate_solution.has_value()) {
1458 autochoke_thp = *approximate_solution;
1459 local_deferredLogger.
debug(
"Approximate group THP value found: " +
std::to_string(autochoke_thp.value()));
1460 }
else if (finding_bracket) {
1461 const Scalar tolerance2 = thp_tolerance;
1462 const int max_iteration_solve = 100;
1464 autochoke_thp = RegulaFalsiBisection<ThrowOnError>::
1465 solve(mismatch, low, high, max_iteration_solve, tolerance2, iteration);
1470 autochoke_thp.reset();
1471 local_deferredLogger.
debug(
"Group THP solve failed due to bracketing failure");
1474 if (autochoke_thp.has_value()) {
1475 well_group_thp_calc_[nodeName] = autochoke_thp.value();
1478 well_group_thp = std::max(autochoke_thp.value(), nodal_pressure);
1481 for (
auto& well : this->well_container_) {
1482 std::string well_name = well->name();
1484 if (well->isInjector() || !well->wellEcl().predictionMode())
1487 if (group.hasWell(well_name)) {
1488 well->setDynamicThpLimit(well_group_thp);
1490 const auto& ws = this->wellState().well(well->indexOfWell());
1491 const bool thp_is_limit = ws.production_cmode == Well::ProducerCMode::THP;
1493 well->prepareWellBeforeAssembling(this->simulator_, dt, this->wellState(), this->groupState(), local_deferredLogger);
1498 const auto& current_well_group_thp = group_state.is_autochoke_group(nodeName) ? group_state.well_group_thp(nodeName) : 1e30;
1499 if (std::abs(current_well_group_thp - well_group_thp) > balance.pressure_tolerance()) {
1500 well_group_thp_updated =
true;
1501 group_state.update_well_group_thp(nodeName, well_group_thp);
1505 return well_group_thp_updated;
1508 template<
typename TypeTag>
1514 for (
auto& well : well_container_) {
1515 well->assembleWellEq(simulator_, dt, this->wellState(), this->groupState(), deferred_logger);
1520 template<
typename TypeTag>
1526 for (
auto& well : well_container_) {
1527 well->prepareWellBeforeAssembling(simulator_, dt, this->wellState(), this->groupState(), 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];
1562 std::shared_ptr<StandardWell<TypeTag> > derived = std::dynamic_pointer_cast<StandardWell<TypeTag> >(well);
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 = std::dynamic_pointer_cast<StandardWell<TypeTag>>(well);
1576 derived_std->linSys().extract(derived_std->numStaticWellEq, wellContribs);
1578 auto derived_ms = std::dynamic_pointer_cast<MultisegmentWell<TypeTag> >(well);
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_) {
1809 const bool changed_well = well->
updateWellControl(simulator_, mode, this->wellState(), this->groupState(), deferred_logger);
1811 changed_well_to_group = changed_well || changed_well_to_group;
1815 simulator_.gridView().comm());
1818 changed_well_to_group = comm.sum(
static_cast<int>(changed_well_to_group));
1819 if (changed_well_to_group) {
1820 updateAndCommunicate(episodeIdx, iterationIdx, deferred_logger);
1821 changed_well_group =
true;
1825 bool changed_well_individual =
false;
1830 for (
const auto& well : well_container_) {
1832 const bool changed_well = well->
updateWellControl(simulator_, mode, this->wellState(), this->groupState(), deferred_logger);
1834 changed_well_individual = changed_well || changed_well_individual;
1838 simulator_.gridView().comm());
1841 changed_well_individual = comm.sum(
static_cast<int>(changed_well_individual));
1842 if (changed_well_individual) {
1843 updateAndCommunicate(episodeIdx, iterationIdx, deferred_logger);
1844 changed_well_group =
true;
1850 this->updateWsolvent(fieldGroup, episodeIdx, this->nupcolWellState());
1852 return changed_well_group;
1856 template<
typename TypeTag>
1857 std::tuple<bool, typename BlackoilWellModel<TypeTag>::Scalar>
1861 const bool relax_network_tolerance)
1864 const int episodeIdx = simulator_.episodeIndex();
1865 const auto& network = this->schedule()[episodeIdx].network();
1866 if (!this->wellsActive() && !network.active()) {
1867 return {
false, 0.0};
1870 const int iterationIdx = simulator_.model().newtonMethod().numIterations();
1871 const auto& comm = simulator_.vanguard().grid().comm();
1874 Scalar network_imbalance = 0.0;
1875 bool more_network_update =
false;
1876 if (this->shouldBalanceNetwork(episodeIdx, iterationIdx) || mandatory_network_balance) {
1877 OPM_TIMEBLOCK(BalanceNetwork);
1878 const double dt = this->simulator_.timeStepSize();
1880 const bool well_group_thp_updated = computeWellGroupThp(dt, deferred_logger);
1881 const int max_number_of_sub_iterations = param_.network_max_sub_iterations_;
1882 const Scalar network_pressure_update_damping_factor = param_.network_pressure_update_damping_factor_;
1883 const Scalar network_max_pressure_update = param_.network_max_pressure_update_in_bars_ * unit::barsa;
1884 bool more_network_sub_update =
false;
1885 for (
int i = 0; i < max_number_of_sub_iterations; i++) {
1886 const auto local_network_imbalance = this->updateNetworkPressures(episodeIdx, network_pressure_update_damping_factor, network_max_pressure_update);
1887 network_imbalance = comm.max(local_network_imbalance);
1888 const auto& balance = this->schedule()[episodeIdx].network_balance();
1889 constexpr Scalar relaxation_factor = 10.0;
1890 const Scalar tolerance = relax_network_tolerance ? relaxation_factor * balance.pressure_tolerance() : balance.pressure_tolerance();
1891 more_network_sub_update = this->networkActive() && network_imbalance > tolerance;
1892 if (!more_network_sub_update)
1895 for (
const auto& well : well_container_) {
1896 if (well->isInjector() || !well->wellEcl().predictionMode())
1899 const auto it = this->node_pressures_.find(well->wellEcl().groupName());
1900 if (it != this->node_pressures_.end()) {
1901 const auto& ws = this->wellState().well(well->indexOfWell());
1902 const bool thp_is_limit = ws.production_cmode == Well::ProducerCMode::THP;
1904 well->prepareWellBeforeAssembling(this->simulator_, dt, this->wellState(), this->groupState(), 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(simulator_, this->groupState(),
1941 this->wellState(), deferred_logger);
1945 simulator_.gridView().comm())
1946 this->updateAndCommunicateGroupData(reportStepIdx,
1948 param_.nupcol_group_rate_tolerance_,
1953 template<
typename TypeTag>
1958 const int reportStepIdx,
1959 const int iterationIdx)
1962 bool changed =
false;
1964 const int nupcol = this->schedule()[reportStepIdx].nupcol();
1965 const int max_number_of_group_switches = param_.max_number_of_group_switches_;
1966 const bool update_group_switching_log = iterationIdx >= nupcol;
1967 const bool changed_hc = this->checkGroupHigherConstraints(group, deferred_logger, reportStepIdx, max_number_of_group_switches, update_group_switching_log);
1970 updateAndCommunicate(reportStepIdx, iterationIdx, deferred_logger);
1973 bool changed_individual =
1975 updateGroupIndividualControl(group,
1977 max_number_of_group_switches,
1978 update_group_switching_log,
1979 this->switched_inj_groups_,
1980 this->switched_prod_groups_,
1981 this->closed_offending_wells_,
1986 if (changed_individual) {
1988 updateAndCommunicate(reportStepIdx, iterationIdx, deferred_logger);
1991 for (
const std::string& groupName : group.groups()) {
1992 bool changed_this = updateGroupControls( this->schedule().getGroup(groupName, reportStepIdx), deferred_logger, reportStepIdx,iterationIdx);
1993 changed = changed || changed_this;
1998 template<
typename TypeTag>
2005 for (
const auto& well : well_container_) {
2006 const auto& wname = well->name();
2007 const auto wasClosed = wellTestState.well_is_closed(wname);
2008 well->checkWellOperability(simulator_,
2010 local_deferredLogger);
2011 const bool under_zero_target =
2012 well->wellUnderZeroGroupRateTarget(this->simulator_,
2014 local_deferredLogger);
2015 well->updateWellTestState(this->wellState().well(wname),
2020 local_deferredLogger);
2022 if (!wasClosed && wellTestState.well_is_closed(wname)) {
2023 this->closed_this_step_.insert(wname);
2026 const WellEconProductionLimits& econ_production_limits = well->wellEcl().getEconLimits();
2027 if (econ_production_limits.validFollowonWell()) {
2028 const auto episode_idx = simulator_.episodeIndex();
2029 const auto follow_on_well = econ_production_limits.followonWell();
2030 if (!this->schedule().hasWell(follow_on_well, episode_idx)) {
2031 const auto msg = fmt::format(
"Well {} was closed. But the given follow on well {} does not exist."
2032 "The simulator continues without opening a follow on well.",
2033 wname, follow_on_well);
2034 local_deferredLogger.
warning(msg);
2036 auto& ws = this->wellState().well(follow_on_well);
2037 const bool success = ws.updateStatus(WellStatus::OPEN);
2039 const auto msg = fmt::format(
"Well {} was closed. The follow on well {} opens instead.", wname, follow_on_well);
2040 local_deferredLogger.
info(msg);
2042 const auto msg = fmt::format(
"Well {} was closed. The follow on well {} is already open.", wname, follow_on_well);
2043 local_deferredLogger.
warning(msg);
2050 for (
const auto& [group_name, to] : this->closed_offending_wells_) {
2051 if (this->hasOpenLocalWell(to.second) &&
2052 !this->wasDynamicallyShutThisTimeStep(to.second))
2054 wellTestState.close_well(to.second,
2055 WellTestConfig::Reason::GROUP,
2057 this->updateClosedWellsThisStep(to.second);
2058 const std::string msg =
2059 fmt::format(
"Procedure on exceeding {} limit is WELL for group {}. "
2065 local_deferredLogger.
info(msg);
2073 if (this->terminal_output_) {
2079 template<
typename TypeTag>
2083 std::string& exc_msg,
2088 const int np = this->numPhases();
2089 std::vector<Scalar> potentials;
2090 const auto& well = well_container_[widx];
2091 std::string cur_exc_msg;
2094 well->computeWellPotentials(simulator_, well_state_copy, potentials, deferred_logger);
2099 exc_msg += fmt::format(
"\nFor well {}: {}", well->name(), cur_exc_msg);
2101 exc_type = std::max(exc_type, cur_exc_type);
2105 auto& ws = this->wellState().well(well->indexOfWell());
2106 for (
int p = 0; p < np; ++p) {
2108 ws.well_potentials[p] = std::max(
Scalar{0.0}, potentials[p]);
2114 template <
typename TypeTag>
2119 for (
const auto& wellPtr : this->well_container_) {
2120 this->calculateProductivityIndexValues(wellPtr.get(), deferred_logger);
2128 template <
typename TypeTag>
2139 for (
const auto& shutWell : this->local_shut_wells_) {
2140 if (!this->wells_ecl_[shutWell].hasConnections()) {
2145 auto wellPtr = this->
template createTypedWellPointer
2148 wellPtr->
init(this->depth_, this->gravity_, this->B_avg_,
true);
2150 this->calculateProductivityIndexValues(wellPtr.get(), deferred_logger);
2158 template <
typename TypeTag>
2172 template<
typename TypeTag>
2178 const auto episodeIdx = simulator_.episodeIndex();
2179 this->updateNetworkActiveState(episodeIdx);
2183 const bool do_prestep_network_rebalance = param_.pre_solve_network_ && this->needPreStepNetworkRebalance(episodeIdx);
2185 for (
const auto& well : well_container_) {
2186 auto& events = this->wellState().well(well->indexOfWell()).events;
2188 well->updateWellStateWithTarget(simulator_, this->groupState(), this->wellState(), deferred_logger);
2189 well->updatePrimaryVariables(simulator_, this->wellState(), deferred_logger);
2195 if (events.hasEvent(ScheduleEvents::REQUEST_OPEN_WELL)) {
2196 events.clearEvent(ScheduleEvents::REQUEST_OPEN_WELL);
2199 if (param_.solve_welleq_initially_ && well->isOperableAndSolvable()) {
2201 well->solveWellEquation(simulator_, this->wellState(), this->groupState(), deferred_logger);
2202 }
catch (
const std::exception& e) {
2203 const std::string msg =
"Compute initial well solution for " + well->name() +
" initially failed. Continue with the previous rates";
2204 deferred_logger.
warning(
"WELL_INITIAL_SOLVE_FAILED", msg);
2209 well->resetWellOperability();
2211 updatePrimaryVariables(deferred_logger);
2214 if (do_prestep_network_rebalance) doPreStepNetworkRebalance(deferred_logger);
2217 template<
typename TypeTag>
2222 std::vector< Scalar > B_avg(numConservationQuantities(),
Scalar() );
2223 const auto& grid = simulator_.vanguard().grid();
2224 const auto& gridView = grid.leafGridView();
2228 for (
const auto& elem : elements(gridView, Dune::Partitions::interior)) {
2229 elemCtx.updatePrimaryStencil(elem);
2230 elemCtx.updatePrimaryIntensiveQuantities(0);
2232 const auto& intQuants = elemCtx.intensiveQuantities(0, 0);
2233 const auto& fs = intQuants.fluidState();
2235 for (
unsigned phaseIdx = 0; phaseIdx < FluidSystem::numPhases; ++phaseIdx)
2237 if (!FluidSystem::phaseIsActive(phaseIdx)) {
2241 const unsigned compIdx = FluidSystem::canonicalToActiveCompIdx(FluidSystem::solventComponentIndex(phaseIdx));
2242 auto& B = B_avg[ compIdx ];
2244 B += 1 / fs.invB(phaseIdx).value();
2246 if constexpr (has_solvent_) {
2247 auto& B = B_avg[solventSaturationIdx];
2248 B += 1 / intQuants.solventInverseFormationVolumeFactor().value();
2254 grid.comm().sum(B_avg.data(), B_avg.size());
2255 B_avg_.resize(B_avg.size());
2256 std::transform(B_avg.begin(), B_avg.end(), B_avg_.begin(),
2257 [gcells = global_num_cells_](
const auto bval)
2258 { return bval / gcells; });
2265 template<
typename TypeTag>
2270 for (
const auto& well : well_container_) {
2275 template<
typename TypeTag>
2279 const auto& grid = simulator_.vanguard().
grid();
2280 const auto& eclProblem = simulator_.problem();
2281 const unsigned numCells = grid.size(0);
2283 this->pvt_region_idx_.resize(numCells);
2284 for (
unsigned cellIdx = 0; cellIdx < numCells; ++cellIdx) {
2285 this->pvt_region_idx_[cellIdx] =
2286 eclProblem.pvtRegionIndex(cellIdx);
2291 template<
typename TypeTag>
2304 return this->numPhases() + has_solvent_;
2307 template<
typename TypeTag>
2311 const auto& eclProblem = simulator_.problem();
2312 depth_.resize(local_num_cells_);
2313 for (
unsigned cellIdx = 0; cellIdx < local_num_cells_; ++cellIdx) {
2314 depth_[cellIdx] = eclProblem.dofCenterDepth(cellIdx);
2318 template<
typename TypeTag>
2321 getWell(
const std::string& well_name)
const
2324 auto well = std::find_if(well_container_.begin(),
2325 well_container_.end(),
2327 return elem->name() == well_name;
2330 assert(well != well_container_.end());
2335 template <
typename TypeTag>
2340 return std::max(this->simulator_.episodeIndex(), 0);
2347 template<
typename TypeTag>
2352 const std::vector<Scalar>& production_rates,
2353 std::vector<Scalar>& resv_coeff)
2355 rateConverter_->calcCoeff(fipnum, pvtreg, production_rates, resv_coeff);
2358 template<
typename TypeTag>
2363 std::vector<Scalar>& resv_coeff)
2365 rateConverter_->calcInjCoeff(fipnum, pvtreg, resv_coeff);
2369 template <
typename TypeTag>
2374 if constexpr (has_energy_) {
2375 int np = this->numPhases();
2376 Scalar cellInternalEnergy;
2380 const int nw = this->numLocalWells();
2381 for (
auto wellID = 0*nw; wellID < nw; ++wellID) {
2382 const Well& well = this->wells_ecl_[wellID];
2383 auto& ws = this->wellState().well(wellID);
2384 if (well.isInjector()) {
2385 if (ws.status != WellStatus::STOP) {
2386 this->wellState().well(wellID).temperature = well.inj_temperature();
2391 std::array<Scalar,2> weighted{0.0,0.0};
2392 auto& [weighted_temperature, total_weight] = weighted;
2394 auto& well_info = this->local_parallel_well_info_[wellID].get();
2395 auto& perf_data = ws.perf_data;
2396 auto& perf_phase_rate = perf_data.phase_rates;
2398 using int_type =
decltype(this->well_perf_data_[wellID].size());
2399 for (int_type perf = 0, end_perf = this->well_perf_data_[wellID].size(); perf < end_perf; ++perf) {
2400 const int cell_idx = this->well_perf_data_[wellID][perf].cell_index;
2401 const auto& intQuants = simulator_.model().intensiveQuantities(cell_idx, 0);
2402 const auto& fs = intQuants.fluidState();
2405 Scalar cellTemperatures = fs.temperature(0).value();
2407 Scalar weight_factor = 0.0;
2408 for (
unsigned phaseIdx = 0; phaseIdx < FluidSystem::numPhases; ++phaseIdx) {
2409 if (!FluidSystem::phaseIsActive(phaseIdx)) {
2412 cellInternalEnergy = fs.enthalpy(phaseIdx).value() -
2413 fs.pressure(phaseIdx).value() / fs.density(phaseIdx).value();
2414 cellBinv = fs.invB(phaseIdx).value();
2415 cellDensity = fs.density(phaseIdx).value();
2416 perfPhaseRate = perf_phase_rate[perf*np + phaseIdx];
2417 weight_factor += cellDensity * perfPhaseRate / cellBinv * cellInternalEnergy / cellTemperatures;
2419 weight_factor = std::abs(weight_factor) + 1e-13;
2420 total_weight += weight_factor;
2421 weighted_temperature += weight_factor * cellTemperatures;
2423 well_info.communication().sum(weighted.data(), 2);
2424 this->wellState().well(wellID).temperature = weighted_temperature / total_weight;
2430 template <
typename TypeTag>
2434 const auto reportStepIdx =
static_cast<unsigned int>(this->reportStepIndex());
2435 const auto& trMod = this->simulator_.problem().tracerModel();
2441 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:291
void init()
Definition: BlackoilWellModel_impl.hpp:158
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: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:757
const Grid & grid() const
Definition: BlackoilWellModel.hpp:371
const SimulatorReportSingle & lastReport() const
Definition: BlackoilWellModel_impl.hpp:631
void addWellContributions(SparseMatrixAdapter &jacobian) const
Definition: BlackoilWellModel_impl.hpp:1592
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:718
void beginTimeStep()
Definition: BlackoilWellModel_impl.hpp:331
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:2268
void initializeLocalWellStructure(const int reportStepIdx, const bool enableWellPIScaling)
Definition: BlackoilWellModel_impl.hpp:246
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:542
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:641
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:800
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:614
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: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: 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