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->updateWellStateWithTarget(simulator_, this->groupState(), this->wellState(), local_deferredLogger);
515 well->calculateExplicitQuantities(simulator_, this->wellState(), local_deferredLogger);
516 well->solveWellEquation(simulator_, this->wellState(), this->groupState(), local_deferredLogger);
517 }
catch (
const std::exception& e) {
518 const std::string msg =
"Compute initial well solution for new well " + well->name() +
" failed. Continue with zero initial rates";
519 local_deferredLogger.
warning(
"WELL_INITIAL_SOLVE_FAILED", msg);
528 const std::string msg =
"Compute initial well solution for new wells failed. Continue with zero initial rates";
529 local_deferredLogger.
warning(
"WELL_INITIAL_SOLVE_FAILED", msg);
532 const auto& comm = simulator_.vanguard().grid().comm();
534 exc_type,
"beginTimeStep() failed: " + exc_msg, this->terminal_output_, comm);
538 template<
typename TypeTag>
541 const double simulationTime,
544 for (
const std::string& well_name : this->getWellsForTesting(timeStepIdx, simulationTime)) {
545 const Well& wellEcl = this->schedule().getWell(well_name, timeStepIdx);
546 if (wellEcl.getStatus() == Well::Status::SHUT)
549 WellInterfacePtr well = createWellForWellTest(well_name, timeStepIdx, deferred_logger);
551 well->init(depth_, gravity_, B_avg_,
true);
553 Scalar well_efficiency_factor = wellEcl.getEfficiencyFactor() *
554 this->wellState().getGlobalEfficiencyScalingFactor(well_name);
555 WellGroupHelpersType::accumulateGroupEfficiencyFactor(this->schedule().getGroup(wellEcl.groupName(),
559 well_efficiency_factor);
561 well->setWellEfficiencyFactor(well_efficiency_factor);
562 well->setVFPProperties(this->vfp_properties_.get());
563 well->setGuideRate(&this->guideRate_);
566 if (well->isProducer() && alternative_well_rate_init_) {
567 well->initializeProducerWellState(simulator_, this->wellState(), deferred_logger);
569 if (well->isVFPActive(deferred_logger)) {
570 well->setPrevSurfaceRates(this->wellState(), this->prevWellState());
573 const auto& network = this->schedule()[timeStepIdx].network();
574 if (network.active() && !this->node_pressures_.empty()) {
575 if (well->isProducer()) {
576 const auto it = this->node_pressures_.find(well->wellEcl().groupName());
577 if (it != this->node_pressures_.end()) {
580 const Scalar nodal_pressure = it->second;
581 well->setDynamicThpLimit(nodal_pressure);
587 GLiftEclWells ecl_well_map;
588 gaslift_.initGliftEclWellMap(well_container_, ecl_well_map);
589 well->wellTesting(simulator_,
593 this->wellTestState(),
595 this->well_open_times_,
597 }
catch (
const std::exception& e) {
598 const std::string msg = fmt::format(
"Exception during testing of well: {}. The well will not open.\n Exception message: {}", wellEcl.name(), e.what());
599 deferred_logger.
warning(
"WELL_TESTING_FAILED", msg);
609 template<
typename TypeTag>
615 for (
auto&& pinfo : this->local_parallel_well_info_)
626 template<
typename TypeTag>
636 template<
typename TypeTag>
641 this->closed_this_step_.clear();
644 this->report_step_starts_ =
false;
645 const int reportStepIdx = simulator_.episodeIndex();
648 for (
const auto& well : well_container_) {
649 if (getPropValue<TypeTag, Properties::EnablePolymerMW>() && well->isInjector()) {
650 well->updateWaterThroughput(dt, this->wellState());
654 for (
const auto& well : well_container_) {
655 well->updateConnectionTransmissibilityFactor(simulator_, this->wellState().well(well->indexOfWell()));
656 well->updateConnectionDFactor(simulator_, this->wellState().well(well->indexOfWell()));
659 if (Indices::waterEnabled) {
660 this->updateFiltrationModelsPostStep(dt, FluidSystem::waterPhaseIdx, local_deferredLogger);
664 this->updateInjMult(local_deferredLogger);
667 for (
const auto& well : well_container_) {
668 well->reportWellSwitching(this->wellState().well(well->indexOfWell()), local_deferredLogger);
671 if (this->terminal_output_) {
672 this->reportGroupSwitching(local_deferredLogger);
676 rateConverter_->template defineState<ElementContext>(simulator_);
680 this->updateWellPotentials(reportStepIdx,
682 simulator_.vanguard().summaryConfig(),
683 local_deferredLogger);
684 }
catch ( std::runtime_error& e ) {
685 const std::string msg =
"A zero well potential is returned for output purposes. ";
686 local_deferredLogger.
warning(
"WELL_POTENTIAL_CALCULATION_FAILED", msg);
689 updateWellTestState(simulationTime, this->wellTestState());
692 const Group& fieldGroup = this->schedule_.getGroup(
"FIELD", reportStepIdx);
693 this->checkGEconLimits(fieldGroup, simulationTime,
694 simulator_.episodeIndex(), local_deferredLogger);
695 this->checkGconsaleLimits(fieldGroup, this->wellState(),
696 simulator_.episodeIndex(), local_deferredLogger);
698 this->calculateProductivityIndexValues(local_deferredLogger);
700 this->commitWGState();
704 if (this->terminal_output_) {
709 this->computeWellTemperature();
713 template<
typename TypeTag>
717 unsigned elemIdx)
const
721 if (!is_cell_perforated_[elemIdx]) {
725 for (
const auto& well : well_container_)
726 well->addCellRates(rate, elemIdx);
730 template<
typename TypeTag>
731 template <
class Context>
735 const Context& context,
737 unsigned timeIdx)
const
740 int elemIdx = context.globalSpaceIndex(spaceIdx, timeIdx);
742 if (!is_cell_perforated_[elemIdx]) {
746 for (
const auto& well : well_container_)
747 well->addCellRates(rate, elemIdx);
752 template<
typename TypeTag>
757 const auto pressIx = []()
759 if (Indices::oilEnabled) {
return FluidSystem::oilPhaseIdx; }
760 if (Indices::waterEnabled) {
return FluidSystem::waterPhaseIdx; }
762 return FluidSystem::gasPhaseIdx;
765 auto cellPressures = std::vector<Scalar>(this->local_num_cells_,
Scalar{0});
766 auto cellTemperatures = std::vector<Scalar>(this->local_num_cells_,
Scalar{0});
769 const auto& gridView = this->simulator_.vanguard().gridView();
772 for (
const auto& elem : elements(gridView, Dune::Partitions::interior)) {
773 elemCtx.updatePrimaryStencil(elem);
774 elemCtx.updatePrimaryIntensiveQuantities(0);
776 const auto ix = elemCtx.globalSpaceIndex(0, 0);
777 const auto& fs = elemCtx.intensiveQuantities(0, 0).fluidState();
779 cellPressures[ix] = fs.pressure(pressIx).value();
780 cellTemperatures[ix] = fs.temperature(0).value();
783 this->simulator_.vanguard().grid().comm());
785 this->wellState().init(cellPressures, cellTemperatures, this->schedule(), this->wells_ecl_,
786 this->local_parallel_well_info_, timeStepIdx,
787 &this->prevWellState(), this->well_perf_data_,
788 this->summaryState(), simulator_.vanguard().enableDistributedWells());
795 template<
typename TypeTag>
802 const int nw = this->numLocalWells();
804 well_container_.clear();
807 well_container_.reserve(nw);
809 const auto& wmatcher = this->schedule().wellMatcher(report_step);
810 const auto& wcycle = this->schedule()[report_step].wcycle.get();
814 std::for_each(this->wells_ecl_.begin(), this->wells_ecl_.end(),
815 [
this, &wg_events = this->report_step_start_events_](
const auto& well_ecl)
817 if (!well_ecl.hasConnections()) {
822 constexpr auto events_mask = ScheduleEvents::WELL_STATUS_CHANGE |
823 ScheduleEvents::REQUEST_OPEN_WELL |
824 ScheduleEvents::REQUEST_SHUT_WELL;
825 const bool well_event =
826 this->report_step_starts_ &&
827 wg_events.hasEvent(well_ecl.name(), events_mask);
836 if (well_ecl.getStatus() == WellStatus::OPEN) {
837 this->well_open_times_.insert_or_assign(well_ecl.name(),
838 this->simulator_.time());
839 this->well_close_times_.erase(well_ecl.name());
840 }
else if (well_ecl.getStatus() == WellStatus::SHUT) {
841 this->well_close_times_.insert_or_assign(well_ecl.name(),
842 this->simulator_.time());
843 this->well_open_times_.erase(well_ecl.name());
849 const auto cycle_states = wcycle.wellStatus(this->simulator_.time(),
851 this->well_open_times_,
852 this->well_close_times_);
854 for (
int w = 0; w < nw; ++w) {
855 const Well& well_ecl = this->wells_ecl_[w];
857 if (!well_ecl.hasConnections()) {
862 const std::string& well_name = well_ecl.name();
863 const auto well_status = this->schedule()
864 .getWell(well_name, report_step).getStatus();
866 const bool shut_event = this->wellState().well(w).events.hasEvent(ScheduleEvents::WELL_STATUS_CHANGE)
867 && well_status == Well::Status::SHUT;
868 const bool open_event = this->wellState().well(w).events.hasEvent(ScheduleEvents::WELL_STATUS_CHANGE)
869 && well_status == Well::Status::OPEN;
870 const auto& ws = this->wellState().well(well_name);
872 if (shut_event && ws.status != Well::Status::SHUT) {
873 this->closed_this_step_.insert(well_name);
874 this->wellState().shutWell(w);
875 }
else if (open_event && ws.status != Well::Status::OPEN) {
876 this->wellState().openWell(w);
880 if (this->wellTestState().well_is_closed(well_name)) {
885 const bool closed_this_step = (this->wellTestState().lastTestTime(well_name) == simulator_.time());
888 auto& events = this->wellState().well(w).events;
889 if (events.hasEvent(ScheduleEvents::REQUEST_OPEN_WELL)) {
890 if (!closed_this_step) {
891 this->wellTestState().open_well(well_name);
892 this->wellTestState().open_completions(well_name);
893 this->well_open_times_.insert_or_assign(well_name,
894 this->simulator_.time());
895 this->well_close_times_.erase(well_name);
897 events.clearEvent(ScheduleEvents::REQUEST_OPEN_WELL);
903 if (this->wellTestState().well_is_closed(well_name))
905 if (well_ecl.getAutomaticShutIn()) {
907 this->wellState().shutWell(w);
908 this->well_close_times_.erase(well_name);
909 this->well_open_times_.erase(well_name);
912 if (!well_ecl.getAllowCrossFlow()) {
915 this->wellState().shutWell(w);
916 this->well_close_times_.erase(well_name);
917 this->well_open_times_.erase(well_name);
921 this->wellState().stopWell(w);
926 if (!well_ecl.getAllowCrossFlow()) {
927 const bool any_zero_rate_constraint = well_ecl.isProducer()
928 ? well_ecl.productionControls(this->summaryState_).anyZeroRateConstraint()
929 : well_ecl.injectionControls(this->summaryState_).anyZeroRateConstraint();
930 if (any_zero_rate_constraint) {
932 local_deferredLogger.
debug(fmt::format(
" Well {} gets shut due to having zero rate constraint and disallowing crossflow ", well_ecl.name()) );
933 this->wellState().shutWell(w);
934 this->well_close_times_.erase(well_name);
935 this->well_open_times_.erase(well_name);
940 if (!wcycle.empty()) {
941 const auto it = cycle_states.find(well_name);
942 if (it != cycle_states.end()) {
943 if (!it->second || well_status == Well::Status::SHUT) {
945 if (well_status == Well::Status::SHUT) {
946 this->well_open_times_.erase(well_name);
947 this->well_close_times_.erase(well_name);
949 this->wellState().shutWell(w);
952 this->wellState().openWell(w);
958 if (ws.status == Well::Status::SHUT) {
962 well_container_.emplace_back(this->createWellPointer(w, report_step));
964 if (ws.status == Well::Status::STOP) {
965 well_container_.back()->stopWell();
966 this->well_close_times_.erase(well_name);
967 this->well_open_times_.erase(well_name);
971 if (!wcycle.empty()) {
972 const auto schedule_open =
973 [&wg_events = this->report_step_start_events_](
const std::string& name)
975 return wg_events.hasEvent(name, ScheduleEvents::REQUEST_OPEN_WELL);
977 for (
const auto& [wname, wscale] : wcycle.efficiencyScale(this->simulator_.time(),
978 this->simulator_.timeStepSize(),
980 this->well_open_times_,
983 this->wellState().updateEfficiencyScalingFactor(wname, wscale);
984 this->schedule_.add_event(ScheduleEvents::WELLGROUP_EFFICIENCY_UPDATE, report_step);
993 if (this->terminal_output_) {
997 this->well_container_generic_.clear();
998 for (
auto& w : well_container_)
999 this->well_container_generic_.push_back(w.get());
1001 const auto& network = this->schedule()[report_step].network();
1002 if (network.active() && !this->node_pressures_.empty()) {
1003 for (
auto& well: this->well_container_generic_) {
1007 if (well->isProducer()) {
1008 const auto it = this->node_pressures_.find(well->wellEcl().groupName());
1009 if (it != this->node_pressures_.end()) {
1012 const Scalar nodal_pressure = it->second;
1013 well->setDynamicThpLimit(nodal_pressure);
1019 this->wbp_.registerOpenWellsForWBPCalculation();
1026 template <
typename TypeTag>
1027 typename BlackoilWellModel<TypeTag>::WellInterfacePtr
1031 const auto is_multiseg = this->wells_ecl_[wellID].isMultiSegment();
1033 if (! (this->param_.use_multisegment_well_ && is_multiseg)) {
1034 return this->
template createTypedWellPointer<StandardWell<TypeTag>>(wellID, report_step);
1037 return this->
template createTypedWellPointer<MultisegmentWell<TypeTag>>(wellID, report_step);
1045 template <
typename TypeTag>
1046 template <
typename WellType>
1047 std::unique_ptr<WellType>
1052 const auto& perf_data = this->well_perf_data_[wellID];
1055 const auto pvtreg = perf_data.
empty()
1056 ? 0 : this->pvt_region_idx_[perf_data.front().cell_index];
1058 const auto& parallel_well_info = this->local_parallel_well_info_[wellID].get();
1059 const auto global_pvtreg = parallel_well_info.broadcastFirstPerforationValue(pvtreg);
1061 return std::make_unique<WellType>(this->wells_ecl_[wellID],
1065 *this->rateConverter_,
1067 this->numConservationQuantities(),
1077 template<
typename TypeTag>
1081 const int report_step,
1085 const auto it = std::find_if(this->wells_ecl_.begin(),
1086 this->wells_ecl_.end(),
1087 [&well_name](
const auto& w)
1088 { return well_name == w.name(); });
1090 if (it == this->wells_ecl_.end()) {
1092 fmt::format(
"Could not find well {} in wells_ecl ", well_name),
1096 const int pos =
static_cast<int>(std::distance(this->wells_ecl_.begin(), it));
1097 return this->createWellPointer(pos, report_step);
1102 template<
typename TypeTag>
1108 const double dt = this->simulator_.timeStepSize();
1110 auto& well_state = this->wellState();
1112 const bool changed_well_group = updateWellControlsAndNetwork(
true, dt, deferred_logger);
1113 assembleWellEqWithoutIteration(dt, deferred_logger);
1114 const bool converged = this->getWellConvergence(this->B_avg_,
true).converged() && !changed_well_group;
1117 for (
auto& well : this->well_container_) {
1118 well->solveEqAndUpdateWellState(simulator_, well_state, deferred_logger);
1121 this->simulator_.vanguard().grid().comm());
1124 const std::string msg = fmt::format(
"Initial (pre-step) network balance did not converge.");
1132 template<
typename TypeTag>
1141 this->guide_rate_handler_.setLogger(&local_deferredLogger);
1143 if (gaslift_.terminalOutput()) {
1144 const std::string msg =
1145 fmt::format(
"assemble() : iteration {}" , iterationIdx);
1146 gaslift_.gliftDebug(msg, local_deferredLogger);
1150 Dune::Timer perfTimer;
1152 this->closed_offending_wells_.clear();
1155 const int episodeIdx = simulator_.episodeIndex();
1156 const auto& network = this->schedule()[episodeIdx].network();
1157 if (!this->wellsActive() && !network.active()) {
1162 if (iterationIdx == 0 && this->wellsActive()) {
1163 OPM_TIMEBLOCK(firstIterationAssmble);
1170 calculateExplicitQuantities(local_deferredLogger);
1171 prepareTimeStep(local_deferredLogger);
1174 "assemble() failed (It=0): ",
1175 this->terminal_output_, grid().comm());
1178 const bool well_group_control_changed = updateWellControlsAndNetwork(
false, dt, local_deferredLogger);
1182 if ( ! this->wellsActive() ) {
1186 assembleWellEqWithoutIteration(dt, local_deferredLogger);
1190 last_report_.well_group_control_changed = well_group_control_changed;
1191 last_report_.assemble_time_well += perfTimer.stop();
1197 template<
typename TypeTag>
1206 bool do_network_update =
true;
1207 bool well_group_control_changed =
false;
1208 Scalar network_imbalance = 0.0;
1210 const std::size_t iteration_to_relax = param_.network_max_strict_outer_iterations_;
1212 const std::size_t max_iteration = param_.network_max_outer_iterations_;
1213 std::size_t network_update_iteration = 0;
1214 while (do_network_update) {
1215 if (network_update_iteration >= max_iteration ) {
1217 const int episodeIdx = simulator_.episodeIndex();
1218 const int iterationIdx = simulator_.model().newtonMethod().numIterations();
1219 if (this->shouldBalanceNetwork(episodeIdx, iterationIdx + 1)) {
1220 const std::string msg = fmt::format(
"Maximum of {:d} network iterations has been used and we stop the update, \n"
1221 "and try again after the next Newton iteration (imbalance = {:.2e} bar, ctrl_change = {})",
1222 max_iteration, network_imbalance*1.0e-5, well_group_control_changed);
1223 local_deferredLogger.
debug(msg);
1225 if (this->terminal_output_) {
1226 const std::string msg = fmt::format(
"Maximum of {:d} network iterations has been used and we stop the update. \n"
1227 "The simulator will continue with unconverged network results (imbalance = {:.2e} bar, ctrl_change = {})",
1228 max_iteration, network_imbalance*1.0e-5, well_group_control_changed);
1229 local_deferredLogger.
info(msg);
1234 if (this->terminal_output_ && (network_update_iteration == iteration_to_relax) ) {
1235 local_deferredLogger.
debug(
"We begin using relaxed tolerance for network update now after " +
std::to_string(iteration_to_relax) +
" iterations ");
1237 const bool relax_network_balance = network_update_iteration >= iteration_to_relax;
1239 const bool optimize_gas_lift = ( (network_update_iteration + 1) < std::max(max_iteration,
static_cast<std::size_t
>(2)) );
1240 std::tie(well_group_control_changed, do_network_update, network_imbalance) =
1241 updateWellControlsAndNetworkIteration(mandatory_network_balance, relax_network_balance, optimize_gas_lift, dt,local_deferredLogger);
1242 ++network_update_iteration;
1244 return well_group_control_changed;
1250 template<
typename TypeTag>
1251 std::tuple<bool, bool, typename BlackoilWellModel<TypeTag>::Scalar>
1254 const bool relax_network_tolerance,
1255 const bool optimize_gas_lift,
1260 const int iterationIdx = simulator_.model().newtonMethod().numIterations();
1261 const int reportStepIdx = simulator_.episodeIndex();
1262 this->updateAndCommunicateGroupData(reportStepIdx, iterationIdx,
1263 param_.nupcol_group_rate_tolerance_,
true, local_deferredLogger);
1264 const auto [more_inner_network_update, network_imbalance] =
1265 updateNetworks(mandatory_network_balance,
1266 local_deferredLogger,
1267 relax_network_tolerance);
1269 bool well_group_control_changed = updateWellControls(local_deferredLogger);
1271 bool alq_updated =
false;
1274 if (optimize_gas_lift) {
1277 const bool updatePotentials = (this->shouldBalanceNetwork(reportStepIdx, iterationIdx) || mandatory_network_balance);
1278 alq_updated = gaslift_.maybeDoGasLiftOptimize(simulator_,
1280 this->node_pressures_,
1284 local_deferredLogger);
1286 prepareWellsBeforeAssembling(dt, local_deferredLogger);
1289 "updateWellControlsAndNetworkIteration() failed: ",
1290 this->terminal_output_, grid().comm());
1294 guideRateUpdateIsNeeded(reportStepIdx)) {
1295 const double simulationTime = simulator_.time();
1299 this->guide_rate_handler_.updateGuideRates(
1300 reportStepIdx, simulationTime, this->wellState(), this->groupState()
1305 const bool more_network_update = this->shouldBalanceNetwork(reportStepIdx, iterationIdx) &&
1306 (more_inner_network_update || well_group_control_changed || alq_updated);
1307 return {well_group_control_changed, more_network_update, network_imbalance};
1313 template <
typename TypeTag>
1319 const int reportStepIdx = this->simulator_.episodeIndex();
1320 const auto& network = this->schedule()[reportStepIdx].network();
1321 const auto& balance = this->schedule()[reportStepIdx].network_balance();
1322 const Scalar thp_tolerance = balance.thp_tolerance();
1324 if (!network.active()) {
1328 auto& well_state = this->wellState();
1329 auto& group_state = this->groupState();
1331 bool well_group_thp_updated =
false;
1332 for (
const std::string& nodeName : network.node_names()) {
1333 const bool has_choke = network.node(nodeName).as_choke();
1335 const auto& summary_state = this->simulator_.vanguard().summaryState();
1336 const Group& group = this->schedule().getGroup(nodeName, reportStepIdx);
1339 std::vector<Scalar> resv_coeff(Indices::numPhases, 1.0);
1340 Scalar gratTargetFromSales = 0.0;
1341 if (group_state.has_grat_sales_target(group.name()))
1342 gratTargetFromSales = group_state.grat_sales_target(group.name());
1344 const auto ctrl = group.productionControls(summary_state);
1345 auto cmode_tmp = ctrl.cmode;
1347 bool fld_none =
false;
1352 const Scalar efficiencyFactor = 1.0;
1353 const Group& parentGroup = this->schedule().getGroup(group.parent(), reportStepIdx);
1365 local_deferredLogger);
1366 target_tmp = target.first;
1367 cmode_tmp = target.second;
1369 const auto cmode = cmode_tmp;
1371 TargetCalculatorType tcalc(cmode, FluidSystem::phaseUsage(), resv_coeff,
1372 gratTargetFromSales, nodeName, group_state,
1373 group.has_gpmaint_control(cmode));
1377 target_tmp = tcalc.groupTarget(ctrl, local_deferredLogger);
1380 const Scalar orig_target = target_tmp;
1382 auto mismatch = [&] (
auto group_thp) {
1385 for (
auto& well : this->well_container_) {
1386 std::string well_name = well->name();
1387 auto& ws = well_state.well(well_name);
1388 if (group.hasWell(well_name)) {
1389 well->setDynamicThpLimit(group_thp);
1390 const Well& well_ecl = this->wells_ecl_[well->indexOfWell()];
1391 const auto inj_controls = Well::InjectionControls(0);
1392 const auto prod_controls = well_ecl.productionControls(summary_state);
1393 well->iterateWellEqWithSwitching(this->simulator_, dt, inj_controls, prod_controls, well_state, group_state, local_deferredLogger,
false,
false);
1394 rate = -tcalc.calcModeRateFromRates(ws.surface_rates);
1398 return (group_rate - orig_target)/orig_target;
1401 const auto upbranch = network.uptree_branch(nodeName);
1402 const auto it = this->node_pressures_.find((*upbranch).uptree_node());
1403 const Scalar nodal_pressure = it->second;
1404 Scalar well_group_thp = nodal_pressure;
1406 std::optional<Scalar> autochoke_thp;
1407 if (
auto iter = this->well_group_thp_calc_.find(nodeName); iter != this->well_group_thp_calc_.end()) {
1408 autochoke_thp = this->well_group_thp_calc_.at(nodeName);
1413 std::array<Scalar, 2> range_initial;
1414 if (!autochoke_thp.has_value()){
1417 std::string node_name = nodeName;
1418 while (!network.node(node_name).terminal_pressure().has_value()) {
1419 auto branch = network.uptree_branch(node_name).value();
1420 node_name = branch.uptree_node();
1422 min_thp = network.node(node_name).terminal_pressure().value();
1423 WellBhpThpCalculatorType::bruteForceBracketCommonTHP(mismatch, min_thp, max_thp);
1426 std::array<Scalar, 2> range = {
Scalar{0.9}*min_thp,
Scalar{1.1}*max_thp};
1427 std::optional<Scalar> appr_sol;
1428 WellBhpThpCalculatorType::bruteForceBracketCommonTHP(mismatch, range, low1, high1, appr_sol, 0.0, local_deferredLogger);
1431 range_initial = {min_thp, max_thp};
1434 if (!autochoke_thp.has_value() || autochoke_thp.value() > nodal_pressure) {
1436 std::array<Scalar, 2> range = autochoke_thp.has_value() ?
1437 std::array<Scalar, 2>{
Scalar{0.9} * autochoke_thp.value(),
1438 Scalar{1.1} * autochoke_thp.value()} : range_initial;
1440 std::optional<Scalar> approximate_solution;
1441 const Scalar tolerance1 = thp_tolerance;
1442 local_deferredLogger.
debug(
"Using brute force search to bracket the group THP");
1443 const bool finding_bracket = WellBhpThpCalculatorType::bruteForceBracketCommonTHP(mismatch, range, low, high, approximate_solution, tolerance1, local_deferredLogger);
1445 if (approximate_solution.has_value()) {
1446 autochoke_thp = *approximate_solution;
1447 local_deferredLogger.
debug(
"Approximate group THP value found: " +
std::to_string(autochoke_thp.value()));
1448 }
else if (finding_bracket) {
1449 const Scalar tolerance2 = thp_tolerance;
1450 const int max_iteration_solve = 100;
1452 autochoke_thp = RegulaFalsiBisection<ThrowOnError>::
1453 solve(mismatch, low, high, max_iteration_solve, tolerance2, iteration);
1458 autochoke_thp.reset();
1459 local_deferredLogger.
debug(
"Group THP solve failed due to bracketing failure");
1462 if (autochoke_thp.has_value()) {
1463 well_group_thp_calc_[nodeName] = autochoke_thp.value();
1466 well_group_thp = std::max(autochoke_thp.value(), nodal_pressure);
1469 for (
auto& well : this->well_container_) {
1470 std::string well_name = well->name();
1472 if (well->isInjector() || !well->wellEcl().predictionMode())
1475 if (group.hasWell(well_name)) {
1476 well->setDynamicThpLimit(well_group_thp);
1478 const auto& ws = this->wellState().well(well->indexOfWell());
1479 const bool thp_is_limit = ws.production_cmode == Well::ProducerCMode::THP;
1481 well->prepareWellBeforeAssembling(this->simulator_, dt, this->wellState(), this->groupState(), local_deferredLogger);
1486 const auto& current_well_group_thp = group_state.is_autochoke_group(nodeName) ? group_state.well_group_thp(nodeName) : 1e30;
1487 if (std::abs(current_well_group_thp - well_group_thp) > balance.pressure_tolerance()) {
1488 well_group_thp_updated =
true;
1489 group_state.update_well_group_thp(nodeName, well_group_thp);
1493 return well_group_thp_updated;
1496 template<
typename TypeTag>
1502 for (
auto& well : well_container_) {
1503 well->assembleWellEq(simulator_, dt, this->wellState(), this->groupState(), deferred_logger);
1508 template<
typename TypeTag>
1514 for (
auto& well : well_container_) {
1515 well->prepareWellBeforeAssembling(simulator_, dt, this->wellState(), this->groupState(), deferred_logger);
1520 template<
typename TypeTag>
1530 for (
auto& well: well_container_) {
1531 well->assembleWellEqWithoutIteration(simulator_, dt, this->wellState(), this->groupState(),
1535 this->terminal_output_, grid().comm());
1539#if COMPILE_GPU_BRIDGE
1540 template<
typename TypeTag>
1548 for(
unsigned int i = 0; i < well_container_.size(); i++){
1549 auto& well = well_container_[i];
1550 std::shared_ptr<StandardWell<TypeTag> > derived = std::dynamic_pointer_cast<StandardWell<TypeTag> >(well);
1552 wellContribs.
addNumBlocks(derived->linSys().getNumBlocks());
1557 wellContribs.
alloc();
1559 for(
unsigned int i = 0; i < well_container_.size(); i++){
1560 auto& well = well_container_[i];
1562 auto derived_std = std::dynamic_pointer_cast<StandardWell<TypeTag>>(well);
1564 derived_std->linSys().extract(derived_std->numStaticWellEq, wellContribs);
1566 auto derived_ms = std::dynamic_pointer_cast<MultisegmentWell<TypeTag> >(well);
1568 derived_ms->linSys().extract(wellContribs);
1570 OpmLog::warning(
"Warning unknown type of well");
1577 template<
typename TypeTag>
1582 for (
const auto& well: well_container_ ) {
1587 template<
typename TypeTag>
1592 const bool use_well_weights)
const
1594 int nw = this->numLocalWellsEnd();
1595 int rdofs = local_num_cells_;
1596 for (
int i = 0; i < nw; i++ ) {
1597 int wdof = rdofs + i;
1598 jacobian[wdof][wdof] = 1.0;
1601 for (
const auto& well : well_container_) {
1602 well->addWellPressureEquations(jacobian,
1610 template <
typename TypeTag>
1613 const std::vector<typename SparseMatrixAdapter::MatrixBlock*>& diagMatAddress)
const
1618 for (
const auto& well : well_container_) {
1619 if (!well->isOperableAndSolvable() && !well->wellIsStopped()) {
1622 const auto& cells = well->cells();
1623 const auto& rates = well->connectionRates();
1624 for (
unsigned perfIdx = 0; perfIdx < rates.size(); ++perfIdx) {
1625 unsigned cellIdx = cells[perfIdx];
1626 auto rate = rates[perfIdx];
1629 using MatrixBlockType =
typename SparseMatrixAdapter::MatrixBlock;
1630 MatrixBlockType bMat(0.0);
1631 simulator_.model().linearizer().setResAndJacobi(res, bMat, rate);
1632 residual[cellIdx] += res;
1633 *diagMatAddress[cellIdx] += bMat;
1639 template<
typename TypeTag>
1644 int nw = this->numLocalWellsEnd();
1645 int rdofs = local_num_cells_;
1646 for (
int i = 0; i < nw; ++i) {
1647 int wdof = rdofs + i;
1648 jacobian.entry(wdof,wdof) = 1.0;
1650 const auto wellconnections = this->getMaxWellConnections();
1651 for (
int i = 0; i < nw; ++i) {
1652 const auto& perfcells = wellconnections[i];
1653 for (
int perfcell : perfcells) {
1654 int wdof = rdofs + i;
1655 jacobian.entry(wdof, perfcell) = 0.0;
1656 jacobian.entry(perfcell, wdof) = 0.0;
1662 template<
typename TypeTag>
1670 for (
const auto& well : well_container_) {
1671 const auto& cells = well->cells();
1672 x_local_.resize(cells.size());
1674 for (
size_t i = 0; i < cells.size(); ++i) {
1675 x_local_[i] = x[cells[i]];
1677 well->recoverWellSolutionAndUpdateWellState(simulator_, x_local_,
1678 this->wellState(), local_deferredLogger);
1682 "recoverWellSolutionAndUpdateWellState() failed: ",
1683 this->terminal_output_, simulator_.vanguard().grid().comm());
1687 template<
typename TypeTag>
1693 OPM_THROW(std::logic_error,
"Attempt to call NLDD method without a NLDD solver");
1696 return nldd_->recoverWellSolutionAndUpdateWellState(x, domainIdx);
1700 template<
typename TypeTag>
1703 getWellConvergence(
const std::vector<Scalar>& B_avg,
bool checkWellGroupControls)
const
1709 const int iterationIdx = simulator_.model().newtonMethod().numIterations();
1710 for (
const auto& well : well_container_) {
1711 if (well->isOperableAndSolvable() || well->wellIsStopped()) {
1712 local_report += well->getWellConvergence(
1713 simulator_, this->wellState(), B_avg, local_deferredLogger,
1714 iterationIdx > param_.strict_outer_iter_wells_);
1718 report.
setWellFailed({CR::WellFailure::Type::Unsolvable, CR::Severity::Normal, -1, well->name()});
1719 local_report += report;
1728 if (checkWellGroupControls) {
1732 if (this->terminal_output_) {
1737 if (f.severity() == ConvergenceReport::Severity::NotANumber) {
1738 OpmLog::debug(
"NaN residual found with phase " +
std::to_string(f.phase()) +
" for well " + f.wellName());
1739 }
else if (f.severity() == ConvergenceReport::Severity::TooLarge) {
1740 OpmLog::debug(
"Too large residual found with phase " +
std::to_string(f.phase()) +
" for well " + f.wellName());
1751 template<
typename TypeTag>
1757 for (
auto& well : well_container_) {
1766 template<
typename TypeTag>
1772 if (!this->wellsActive()) {
1775 const int episodeIdx = simulator_.episodeIndex();
1776 const int iterationIdx = simulator_.model().newtonMethod().numIterations();
1777 const auto& comm = simulator_.vanguard().grid().comm();
1779 bool changed_well_group =
false;
1780 const Group& fieldGroup = this->schedule().getGroup(
"FIELD", episodeIdx);
1783 const std::size_t max_iter = param_.well_group_constraints_max_iterations_;
1784 while(!changed_well_group && iter < max_iter) {
1785 changed_well_group = updateGroupControls(fieldGroup, deferred_logger, episodeIdx, iterationIdx);
1788 bool changed_well_to_group =
false;
1790 OPM_TIMEBLOCK(UpdateWellControls);
1794 for (
const auto& well : well_container_) {
1796 const bool changed_well = well->
updateWellControl(simulator_, mode, this->wellState(), this->groupState(), deferred_logger);
1798 changed_well_to_group = changed_well || changed_well_to_group;
1802 simulator_.gridView().comm());
1805 changed_well_to_group = comm.sum(
static_cast<int>(changed_well_to_group));
1806 if (changed_well_to_group) {
1807 updateAndCommunicate(episodeIdx, iterationIdx, deferred_logger);
1808 changed_well_group =
true;
1812 bool changed_well_individual =
false;
1817 for (
const auto& well : well_container_) {
1819 const bool changed_well = well->
updateWellControl(simulator_, mode, this->wellState(), this->groupState(), deferred_logger);
1821 changed_well_individual = changed_well || changed_well_individual;
1825 simulator_.gridView().comm());
1828 changed_well_individual = comm.sum(
static_cast<int>(changed_well_individual));
1829 if (changed_well_individual) {
1830 updateAndCommunicate(episodeIdx, iterationIdx, deferred_logger);
1831 changed_well_group =
true;
1837 this->updateWsolvent(fieldGroup, episodeIdx, this->nupcolWellState());
1839 return changed_well_group;
1843 template<
typename TypeTag>
1844 std::tuple<bool, typename BlackoilWellModel<TypeTag>::Scalar>
1848 const bool relax_network_tolerance)
1851 const int episodeIdx = simulator_.episodeIndex();
1852 const auto& network = this->schedule()[episodeIdx].network();
1853 if (!this->wellsActive() && !network.active()) {
1854 return {
false, 0.0};
1857 const int iterationIdx = simulator_.model().newtonMethod().numIterations();
1858 const auto& comm = simulator_.vanguard().grid().comm();
1861 Scalar network_imbalance = 0.0;
1862 bool more_network_update =
false;
1863 if (this->shouldBalanceNetwork(episodeIdx, iterationIdx) || mandatory_network_balance) {
1864 OPM_TIMEBLOCK(BalanceNetwork);
1865 const double dt = this->simulator_.timeStepSize();
1867 const bool well_group_thp_updated = computeWellGroupThp(dt, deferred_logger);
1868 const int max_number_of_sub_iterations = param_.network_max_sub_iterations_;
1869 const Scalar network_pressure_update_damping_factor = param_.network_pressure_update_damping_factor_;
1870 const Scalar network_max_pressure_update = param_.network_max_pressure_update_in_bars_ * unit::barsa;
1871 bool more_network_sub_update =
false;
1872 for (
int i = 0; i < max_number_of_sub_iterations; i++) {
1873 const auto local_network_imbalance = this->updateNetworkPressures(episodeIdx, network_pressure_update_damping_factor, network_max_pressure_update);
1874 network_imbalance = comm.max(local_network_imbalance);
1875 const auto& balance = this->schedule()[episodeIdx].network_balance();
1876 constexpr Scalar relaxation_factor = 10.0;
1877 const Scalar tolerance = relax_network_tolerance ? relaxation_factor * balance.pressure_tolerance() : balance.pressure_tolerance();
1878 more_network_sub_update = this->networkActive() && network_imbalance > tolerance;
1879 if (!more_network_sub_update)
1882 for (
const auto& well : well_container_) {
1883 if (well->isInjector() || !well->wellEcl().predictionMode())
1886 const auto it = this->node_pressures_.find(well->wellEcl().groupName());
1887 if (it != this->node_pressures_.end()) {
1888 const auto& ws = this->wellState().well(well->indexOfWell());
1889 const bool thp_is_limit = ws.production_cmode == Well::ProducerCMode::THP;
1891 well->prepareWellBeforeAssembling(this->simulator_, dt, this->wellState(), this->groupState(), deferred_logger);
1895 this->updateAndCommunicateGroupData(episodeIdx, iterationIdx, param_.nupcol_group_rate_tolerance_,
1896 true, deferred_logger);
1898 more_network_update = more_network_sub_update || well_group_thp_updated;
1900 return { more_network_update, network_imbalance };
1904 template<
typename TypeTag>
1908 const int iterationIdx,
1911 this->updateAndCommunicateGroupData(reportStepIdx,
1913 param_.nupcol_group_rate_tolerance_,
1921 for (
const auto& well : well_container_) {
1923 const auto& ws = this->wellState().well(well->indexOfWell());
1924 if (ws.production_cmode == Well::ProducerCMode::GRUP ||
1925 ws.injection_cmode == Well::InjectorCMode::GRUP)
1927 well->updateWellStateWithTarget(simulator_, this->groupState(),
1928 this->wellState(), deferred_logger);
1932 simulator_.gridView().comm())
1933 this->updateAndCommunicateGroupData(reportStepIdx,
1935 param_.nupcol_group_rate_tolerance_,
1940 template<
typename TypeTag>
1945 const int reportStepIdx,
1946 const int iterationIdx)
1949 bool changed =
false;
1951 const int nupcol = this->schedule()[reportStepIdx].nupcol();
1952 const int max_number_of_group_switches = param_.max_number_of_group_switches_;
1953 const bool update_group_switching_log = iterationIdx >= nupcol;
1954 const bool changed_hc = this->checkGroupHigherConstraints(group, deferred_logger, reportStepIdx, max_number_of_group_switches, update_group_switching_log);
1957 updateAndCommunicate(reportStepIdx, iterationIdx, deferred_logger);
1960 bool changed_individual =
1962 updateGroupIndividualControl(group,
1964 max_number_of_group_switches,
1965 update_group_switching_log,
1966 this->switched_inj_groups_,
1967 this->switched_prod_groups_,
1968 this->closed_offending_wells_,
1973 if (changed_individual) {
1975 updateAndCommunicate(reportStepIdx, iterationIdx, deferred_logger);
1978 for (
const std::string& groupName : group.groups()) {
1979 bool changed_this = updateGroupControls( this->schedule().getGroup(groupName, reportStepIdx), deferred_logger, reportStepIdx,iterationIdx);
1980 changed = changed || changed_this;
1985 template<
typename TypeTag>
1992 for (
const auto& well : well_container_) {
1993 const auto& wname = well->name();
1994 const auto wasClosed = wellTestState.well_is_closed(wname);
1995 well->checkWellOperability(simulator_,
1997 local_deferredLogger);
1998 const bool under_zero_target =
1999 well->wellUnderZeroGroupRateTarget(this->simulator_,
2001 local_deferredLogger);
2002 well->updateWellTestState(this->wellState().well(wname),
2007 local_deferredLogger);
2009 if (!wasClosed && wellTestState.well_is_closed(wname)) {
2010 this->closed_this_step_.insert(wname);
2013 const WellEconProductionLimits& econ_production_limits = well->wellEcl().getEconLimits();
2014 if (econ_production_limits.validFollowonWell()) {
2015 const auto episode_idx = simulator_.episodeIndex();
2016 const auto follow_on_well = econ_production_limits.followonWell();
2017 if (!this->schedule().hasWell(follow_on_well, episode_idx)) {
2018 const auto msg = fmt::format(
"Well {} was closed. But the given follow on well {} does not exist."
2019 "The simulator continues without opening a follow on well.",
2020 wname, follow_on_well);
2021 local_deferredLogger.
warning(msg);
2023 auto& ws = this->wellState().well(follow_on_well);
2024 const bool success = ws.updateStatus(WellStatus::OPEN);
2026 const auto msg = fmt::format(
"Well {} was closed. The follow on well {} opens instead.", wname, follow_on_well);
2027 local_deferredLogger.
info(msg);
2029 const auto msg = fmt::format(
"Well {} was closed. The follow on well {} is already open.", wname, follow_on_well);
2030 local_deferredLogger.
warning(msg);
2037 for (
const auto& [group_name, to] : this->closed_offending_wells_) {
2038 if (this->hasOpenLocalWell(to.second) &&
2039 !this->wasDynamicallyShutThisTimeStep(to.second))
2041 wellTestState.close_well(to.second,
2042 WellTestConfig::Reason::GROUP,
2044 this->updateClosedWellsThisStep(to.second);
2045 const std::string msg =
2046 fmt::format(
"Procedure on exceeding {} limit is WELL for group {}. "
2052 local_deferredLogger.
info(msg);
2060 if (this->terminal_output_) {
2066 template<
typename TypeTag>
2070 std::string& exc_msg,
2075 const int np = this->numPhases();
2076 std::vector<Scalar> potentials;
2077 const auto& well = well_container_[widx];
2078 std::string cur_exc_msg;
2081 well->computeWellPotentials(simulator_, well_state_copy, potentials, deferred_logger);
2086 exc_msg += fmt::format(
"\nFor well {}: {}", well->name(), cur_exc_msg);
2088 exc_type = std::max(exc_type, cur_exc_type);
2092 auto& ws = this->wellState().well(well->indexOfWell());
2093 for (
int p = 0; p < np; ++p) {
2095 ws.well_potentials[p] = std::max(
Scalar{0.0}, potentials[p]);
2101 template <
typename TypeTag>
2106 for (
const auto& wellPtr : this->well_container_) {
2107 this->calculateProductivityIndexValues(wellPtr.get(), deferred_logger);
2115 template <
typename TypeTag>
2126 for (
const auto& shutWell : this->local_shut_wells_) {
2127 if (!this->wells_ecl_[shutWell].hasConnections()) {
2132 auto wellPtr = this->
template createTypedWellPointer
2135 wellPtr->
init(this->depth_, this->gravity_, this->B_avg_,
true);
2137 this->calculateProductivityIndexValues(wellPtr.get(), deferred_logger);
2145 template <
typename TypeTag>
2159 template<
typename TypeTag>
2165 const auto episodeIdx = simulator_.episodeIndex();
2166 this->updateNetworkActiveState(episodeIdx);
2170 const bool do_prestep_network_rebalance = param_.pre_solve_network_ && this->needPreStepNetworkRebalance(episodeIdx);
2172 for (
const auto& well : well_container_) {
2173 auto& events = this->wellState().well(well->indexOfWell()).events;
2175 well->updateWellStateWithTarget(simulator_, this->groupState(), this->wellState(), deferred_logger);
2176 well->updatePrimaryVariables(simulator_, this->wellState(), deferred_logger);
2182 if (events.hasEvent(ScheduleEvents::REQUEST_OPEN_WELL)) {
2183 events.clearEvent(ScheduleEvents::REQUEST_OPEN_WELL);
2186 if (param_.solve_welleq_initially_ && well->isOperableAndSolvable()) {
2188 well->solveWellEquation(simulator_, this->wellState(), this->groupState(), deferred_logger);
2189 }
catch (
const std::exception& e) {
2190 const std::string msg =
"Compute initial well solution for " + well->name() +
" initially failed. Continue with the previous rates";
2191 deferred_logger.
warning(
"WELL_INITIAL_SOLVE_FAILED", msg);
2196 well->resetWellOperability();
2198 updatePrimaryVariables(deferred_logger);
2201 if (do_prestep_network_rebalance) doPreStepNetworkRebalance(deferred_logger);
2204 template<
typename TypeTag>
2209 std::vector< Scalar > B_avg(numConservationQuantities(),
Scalar() );
2210 const auto& grid = simulator_.vanguard().grid();
2211 const auto& gridView = grid.leafGridView();
2215 for (
const auto& elem : elements(gridView, Dune::Partitions::interior)) {
2216 elemCtx.updatePrimaryStencil(elem);
2217 elemCtx.updatePrimaryIntensiveQuantities(0);
2219 const auto& intQuants = elemCtx.intensiveQuantities(0, 0);
2220 const auto& fs = intQuants.fluidState();
2222 for (
unsigned phaseIdx = 0; phaseIdx < FluidSystem::numPhases; ++phaseIdx)
2224 if (!FluidSystem::phaseIsActive(phaseIdx)) {
2228 const unsigned compIdx = FluidSystem::canonicalToActiveCompIdx(FluidSystem::solventComponentIndex(phaseIdx));
2229 auto& B = B_avg[ compIdx ];
2231 B += 1 / fs.invB(phaseIdx).value();
2233 if constexpr (has_solvent_) {
2234 auto& B = B_avg[solventSaturationIdx];
2235 B += 1 / intQuants.solventInverseFormationVolumeFactor().value();
2241 grid.comm().sum(B_avg.data(), B_avg.size());
2242 B_avg_.resize(B_avg.size());
2243 std::transform(B_avg.begin(), B_avg.end(), B_avg_.begin(),
2244 [gcells = global_num_cells_](
const auto bval)
2245 { return bval / gcells; });
2252 template<
typename TypeTag>
2257 for (
const auto& well : well_container_) {
2262 template<
typename TypeTag>
2266 const auto& grid = simulator_.vanguard().
grid();
2267 const auto& eclProblem = simulator_.problem();
2268 const unsigned numCells = grid.size(0);
2270 this->pvt_region_idx_.resize(numCells);
2271 for (
unsigned cellIdx = 0; cellIdx < numCells; ++cellIdx) {
2272 this->pvt_region_idx_[cellIdx] =
2273 eclProblem.pvtRegionIndex(cellIdx);
2278 template<
typename TypeTag>
2291 return this->numPhases() + has_solvent_;
2294 template<
typename TypeTag>
2298 const auto& eclProblem = simulator_.problem();
2299 depth_.resize(local_num_cells_);
2300 for (
unsigned cellIdx = 0; cellIdx < local_num_cells_; ++cellIdx) {
2301 depth_[cellIdx] = eclProblem.dofCenterDepth(cellIdx);
2305 template<
typename TypeTag>
2308 getWell(
const std::string& well_name)
const
2311 auto well = std::find_if(well_container_.begin(),
2312 well_container_.end(),
2314 return elem->name() == well_name;
2317 assert(well != well_container_.end());
2322 template <
typename TypeTag>
2327 return std::max(this->simulator_.episodeIndex(), 0);
2334 template<
typename TypeTag>
2339 const std::vector<Scalar>& production_rates,
2340 std::vector<Scalar>& resv_coeff)
2342 rateConverter_->calcCoeff(fipnum, pvtreg, production_rates, resv_coeff);
2345 template<
typename TypeTag>
2350 std::vector<Scalar>& resv_coeff)
2352 rateConverter_->calcInjCoeff(fipnum, pvtreg, resv_coeff);
2356 template <
typename TypeTag>
2361 if constexpr (has_energy_) {
2362 int np = this->numPhases();
2363 Scalar cellInternalEnergy;
2367 const int nw = this->numLocalWells();
2368 for (
auto wellID = 0*nw; wellID < nw; ++wellID) {
2369 const Well& well = this->wells_ecl_[wellID];
2370 auto& ws = this->wellState().well(wellID);
2371 if (well.isInjector()) {
2372 if (ws.status != WellStatus::STOP) {
2373 this->wellState().well(wellID).temperature = well.inj_temperature();
2378 std::array<Scalar,2> weighted{0.0,0.0};
2379 auto& [weighted_temperature, total_weight] = weighted;
2381 auto& well_info = this->local_parallel_well_info_[wellID].get();
2382 auto& perf_data = ws.perf_data;
2383 auto& perf_phase_rate = perf_data.phase_rates;
2385 using int_type =
decltype(this->well_perf_data_[wellID].size());
2386 for (int_type perf = 0, end_perf = this->well_perf_data_[wellID].size(); perf < end_perf; ++perf) {
2387 const int cell_idx = this->well_perf_data_[wellID][perf].cell_index;
2388 const auto& intQuants = simulator_.model().intensiveQuantities(cell_idx, 0);
2389 const auto& fs = intQuants.fluidState();
2392 Scalar cellTemperatures = fs.temperature(0).value();
2394 Scalar weight_factor = 0.0;
2395 for (
unsigned phaseIdx = 0; phaseIdx < FluidSystem::numPhases; ++phaseIdx) {
2396 if (!FluidSystem::phaseIsActive(phaseIdx)) {
2399 cellInternalEnergy = fs.enthalpy(phaseIdx).value() -
2400 fs.pressure(phaseIdx).value() / fs.density(phaseIdx).value();
2401 cellBinv = fs.invB(phaseIdx).value();
2402 cellDensity = fs.density(phaseIdx).value();
2403 perfPhaseRate = perf_phase_rate[perf*np + phaseIdx];
2404 weight_factor += cellDensity * perfPhaseRate / cellBinv * cellInternalEnergy / cellTemperatures;
2406 weight_factor = std::abs(weight_factor) + 1e-13;
2407 total_weight += weight_factor;
2408 weighted_temperature += weight_factor * cellTemperatures;
2410 well_info.communication().sum(weighted.data(), 2);
2411 this->wellState().well(wellID).temperature = weighted_temperature / total_weight;
2417 template <
typename TypeTag>
2421 const auto reportStepIdx =
static_cast<unsigned int>(this->reportStepIndex());
2422 const auto& trMod = this->simulator_.problem().tracerModel();
2428 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:755
const Grid & grid() const
Definition: BlackoilWellModel.hpp:371
const SimulatorReportSingle & lastReport() const
Definition: BlackoilWellModel_impl.hpp:629
void addWellContributions(SparseMatrixAdapter &jacobian) const
Definition: BlackoilWellModel_impl.hpp:1580
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:716
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:1754
void updatePrimaryVariables(DeferredLogger &deferred_logger)
Definition: BlackoilWellModel_impl.hpp:2255
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:540
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:639
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:798
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:612
void initializeSources(typename ParallelWBPCalculation< Scalar >::GlobalToLocal index, typename ParallelWBPCalculation< Scalar >::Evaluator eval)
Definition: ConvergenceReport.hpp:38
void setWellFailed(const WellFailure &wf)
Definition: ConvergenceReport.hpp:270
void setWellGroupTargetsViolated(const bool wellGroupTargetsViolated)
Definition: ConvergenceReport.hpp:288
const std::vector< WellFailure > & wellFailures() const
Definition: ConvergenceReport.hpp:369
Definition: DeferredLogger.hpp:57
void info(const std::string &tag, const std::string &message)
void warning(const std::string &tag, const std::string &message)
void debug(const std::string &tag, const std::string &message)
std::map< std::string, std::pair< const Well *, int > > GLiftEclWells
Definition: GasLiftGroupInfo.hpp:64
Definition: StandardWell.hpp:60
virtual void init(const std::vector< Scalar > &depth_arg, const Scalar gravity_arg, const std::vector< Scalar > &B_avg, const bool changed_to_open_this_step) override
Definition: StandardWell_impl.hpp:76
Definition: TargetCalculator.hpp:43
Class for computing BHP limits.
Definition: WellBhpThpCalculator.hpp:41
Definition: WellContributions.hpp:51
void alloc()
Allocate memory for the StandardWells.
void setBlockSize(unsigned int dim, unsigned int dim_wells)
void addNumBlocks(unsigned int numBlocks)
Class for computing well group controls.
Definition: WellGroupControls.hpp:48
static void updateGpMaintTargetForGroups(const Group &group, const Schedule &schedule, const RegionalValues ®ional_values, const int reportStepIdx, const double dt, const WellStateType &well_state, GroupState< Scalar > &group_state)
int indexOfWell() const
Index of well in the wells struct and wellState.
Definition: WellInterface.hpp:76
bool updateWellControl(const Simulator &simulator, const IndividualOrGroup iog, WellStateType &well_state, const GroupState< Scalar > &group_state, DeferredLogger &deferred_logger)
Definition: WellInterface_impl.hpp:189
virtual void updateProductivityIndex(const Simulator &simulator, const WellProdIndexCalculator< Scalar > &wellPICalc, WellStateType &well_state, DeferredLogger &deferred_logger) const =0
Definition: WellState.hpp:66
ExcEnum
Definition: DeferredLogger.hpp:45
@ NONE
Definition: DeferredLogger.hpp:46
Dune::Communication< MPIComm > Communication
Definition: ParallelCommunication.hpp:30
Definition: blackoilboundaryratevector.hh:39
Opm::DeferredLogger gatherDeferredLogger(const Opm::DeferredLogger &local_deferredlogger, Parallel::Communication communicator)
Create a global log combining local logs.
ConvergenceReport gatherConvergenceReport(const ConvergenceReport &local_report, Parallel::Communication communicator)
std::string to_string(const ConvergenceReport::ReservoirFailure::Type t)
A struct for returning timing data from a simulator to its caller.
Definition: SimulatorReport.hpp:34