20#ifndef OPM_BLACKOILWELLMODEL_RESCOUP_IMPL_HEADER_INCLUDED
21#define OPM_BLACKOILWELLMODEL_RESCOUP_IMPL_HEADER_INCLUDED
24#ifndef OPM_BLACKOILWELLMODEL_RESCOUP_HEADER_INCLUDED
29#ifdef RESERVOIR_COUPLING_ENABLED
31#include <opm/common/TimingMacros.hpp>
33#include <opm/input/eclipse/EclipseState/Grid/RegionSetMatcher.hpp>
34#include <opm/input/eclipse/Schedule/ResCoup/ReservoirCouplingInfo.hpp>
35#include <opm/input/eclipse/Schedule/Schedule.hpp>
36#include <opm/input/eclipse/Schedule/SummaryState.hpp>
37#include <opm/input/eclipse/Schedule/UDQ/UDQConfig.hpp>
38#include <opm/input/eclipse/Schedule/UDQ/UDQDefine.hpp>
39#include <opm/input/eclipse/Schedule/UDQ/UDQEnums.hpp>
40#include <opm/input/eclipse/Schedule/Well/WellMatcher.hpp>
41#include <opm/input/eclipse/Units/UnitSystem.hpp>
64template<
typename TypeTag>
65BlackoilWellModelRescoup<TypeTag>::
66BlackoilWellModelRescoup(BlackoilWellModel<TypeTag>& well_model)
67 : well_model_{well_model}
68 , network_{well_model.network()}
69 , simulator_{well_model.simulator()}
70 , param_{well_model.param()}
76template<
typename TypeTag>
78BlackoilWellModelRescoup<TypeTag>::
79evalGroupAndFieldUDQs()
81 const int reportStepIdx = this->groupStateHelper().reportStepIdx();
82 auto& deferred_logger = this->groupStateHelper().deferredLogger();
91 const auto select = [](
const UDQDefine& def) {
92 const auto var_type = def.var_type();
93 return ((var_type == UDQVarType::GROUP_VAR) || (var_type == UDQVarType::FIELD_VAR))
94 && (def.status().first != UDQUpdate::NEXT);
96 const auto& schedule = this->schedule();
99 schedule[reportStepIdx].udq().eval(
101 schedule.wellMatcher(reportStepIdx),
102 schedule[reportStepIdx].group_order(),
103 schedule.segmentMatcherFactory(reportStepIdx),
104 [es = std::cref(this->simulator_.vanguard().eclState())]() {
105 return std::make_unique<RegionSetMatcher>(es.get().fipRegionStatistics());
107 this->simulator_.vanguard().summaryState(),
108 this->simulator_.vanguard().udqState(),
112 "Failed to evaluate UDQs for reservoir coupling slave: ",
113 this->well_model_.terminalOutput(),
114 this->simulator_.vanguard().grid().comm())
117template<
typename TypeTag>
119BlackoilWellModelRescoup<TypeTag>::
120masterIsInCoupledNetworkIteration()
const
122 return this->isReservoirCouplingMaster()
123 && this->reservoirCouplingMaster().isFirstSubstepOfSyncTimestep()
124 && this->masterNetworkHasMasterGroupLeaves()
125 && !this->lastSentMasterGroupNodePressuresIsFinal();
129template<
typename TypeTag>
131BlackoilWellModelRescoup<TypeTag>::
132masterNetworkHasMasterGroupLeaves()
const
137 if (!this->isReservoirCouplingMaster())
return false;
138 const auto& rcm = this->reservoirCouplingMaster();
139 const auto num_slaves = rcm.numSlaves();
140 for (std::size_t s = 0; s < num_slaves; ++s) {
141 if (!rcm.slaveIsCoupled(s))
continue;
142 if (this->masterNetworkHasMasterGroupLeavesForSlave_(s)) {
149template<
typename TypeTag>
151BlackoilWellModelRescoup<TypeTag>::
152maybeExchangeNetworkOuterIterationWithSlaves(
bool more_network_update)
154 if (!this->masterIsInCoupledNetworkIteration()) {
157 const bool is_final = !more_network_update;
166 if (is_final || !this->well_model_.useTightRcNetworkCoupling()) {
168 this->sendMasterGroupNodePressuresToSlaves(is_final);
171 this->receiveSlaveGroupData();
172 this->refreshAndSendGroupConstraints();
177template<
typename TypeTag>
179BlackoilWellModelRescoup<TypeTag>::
180maybeExchangeNetworkSubIterationWithSlaves()
200 if (!this->well_model_.useTightRcNetworkCoupling()) {
203 if (!this->masterIsInCoupledNetworkIteration()) {
206 this->sendMasterGroupNodePressuresToSlaves(
false);
207 this->receiveSlaveGroupData();
208 this->refreshAndSendGroupConstraints();
211template<
typename TypeTag>
213BlackoilWellModelRescoup<TypeTag>::
214receiveCoupledNetworkActiveStatus()
217 assert(this->isReservoirCouplingSlave());
218 this->reservoirCouplingSlave().receiveCoupledNetworkActiveStatusFromMaster();
219 if (!this->reservoirCouplingSlave().connectedToMasterCoupledNetwork()) {
221 this->network_.setNodePressureOverrides({});
222 for (
auto& well : this->wellContainer()) {
223 well->setLogAllControlSwitches(
false);
228template<
typename TypeTag>
230BlackoilWellModelRescoup<TypeTag>::
231receiveGroupConstraintsFromMaster()
234 RescoupReceiveGroupConstraints<Scalar, IndexTraits> constraint_receiver{
235 this->well_model_.guideRateHandler(),
236 this->groupStateHelper()
238 constraint_receiver.receiveGroupConstraintsFromMaster();
241template<
typename TypeTag>
243BlackoilWellModelRescoup<TypeTag>::
244receiveMasterGroupNodePressuresFromMaster()
247 assert(this->isReservoirCouplingSlave());
248 auto& rescoup_slave = this->reservoirCouplingSlave();
249 const auto [num_pressures, is_final] =
250 rescoup_slave.receiveNumMasterGroupNodePressuresFromMaster();
251 if (num_pressures > 0) {
252 rescoup_slave.receiveMasterGroupNodePressuresFromMaster(num_pressures);
281 const auto& pressures = rescoup_slave.masterGroupNodePressures();
282 std::map<std::string, Scalar> overrides;
283 for (
const auto& [group_name, pressure] : pressures) {
284 if (this->slaveGroupIsFixedPressureNodeInOwnNetwork_(group_name)) {
285 overrides[group_name] = pressure;
288 this->network_.setNodePressureOverrides(overrides);
297 for (
auto& well : this->wellContainer()) {
298 well->setLogAllControlSwitches(
false);
300 if (pressures.empty())
return;
301 const auto& summary_state = this->well_model_.summaryState();
302 auto& well_state = this->wellState();
303 for (
auto& well : this->wellContainer()) {
304 if (!well->isProducer() || !well->wellEcl().predictionMode())
continue;
305 const auto& group_name = well->wellEcl().groupName();
306 if (this->wellIsBelowOverriddenNode_(group_name, overrides)) {
307 well->setLogAllControlSwitches(!is_final);
309 const auto it = pressures.find(group_name);
310 if (it == pressures.end())
continue;
311 if (!this->slaveGroupIsFixedPressureNodeInOwnNetwork_(group_name))
continue;
312 well->setDynamicThpLimit(it->second);
313 auto& ws = well_state[well->indexOfWell()];
318 ws.network_thp_limit = it->second;
319 if (ws.production_cmode == Well::ProducerCMode::THP) {
320 ws.thp = well->getTHPConstraint(summary_state);
325template<
typename TypeTag>
327BlackoilWellModelRescoup<TypeTag>::
328receiveRefreshedGroupConstraintsFromMaster()
334 this->receiveGroupConstraintsFromMaster();
335 this->groupStateHelper().updateSlaveGroupCmodesFromMaster();
336 this->refreshSlaveGroupTargets();
339template<
typename TypeTag>
341BlackoilWellModelRescoup<TypeTag>::
342receiveSlaveGroupData()
345 assert(this->isReservoirCouplingMaster());
346 RescoupReceiveSlaveGroupData<Scalar, IndexTraits> slave_group_data_receiver{
347 this->groupStateHelper(),
349 slave_group_data_receiver.receiveSlaveGroupData();
352template<
typename TypeTag>
354BlackoilWellModelRescoup<TypeTag>::
355refreshAndSendGroupConstraints()
371 const int report_step_idx = this->well_model_.simulator().episodeIndex();
372 this->well_model_.updateAndCommunicateGroupData(
373 report_step_idx,
false);
374 this->sendMasterGroupConstraintsToSlaves();
377template<
typename TypeTag>
379BlackoilWellModelRescoup<TypeTag>::
380refreshSlaveGroupTargets()
388 this->storeSlaveGroupInjectionTargets();
389 this->storeSlaveGroupProductionTargets();
390 this->evalGroupAndFieldUDQs();
391 this->storeSlaveGroupInjectionTargets();
392 this->storeSlaveGroupProductionTargets();
395template<
typename TypeTag>
397BlackoilWellModelRescoup<TypeTag>::
398rescoupSyncSummaryData()
418 if (this->isReservoirCouplingMaster()) {
419 if (this->reservoirCouplingMaster().needsSlaveDataReceive()) {
425 this->reservoirCouplingMaster().saveGroupFlowsAtStartOfSyncStep();
426 this->receiveSlaveGroupData();
429 this->well_model_.updateGasConsumptionFromWellState(
430 this->well_model_.simulator().episodeIndex());
431 this->reservoirCouplingMaster().updateFlowChangeTimeStepLimit();
432 this->reservoirCouplingMaster().setNeedsSlaveDataReceive(
false);
435 if (this->isReservoirCouplingSlave()) {
436 if (this->reservoirCouplingSlave().isLastSubstepOfSyncTimestep()) {
437 this->well_model_.updateGroupRatesFromWellState(
438 this->well_model_.simulator().episodeIndex());
439 this->sendSlaveGroupDataToMaster();
444template<
typename TypeTag>
446BlackoilWellModelRescoup<TypeTag>::
447sendCoupledNetworkActiveStatus()
450 assert(this->isReservoirCouplingMaster());
459 auto& rescoup_master = this->reservoirCouplingMaster();
460 const auto num_slaves = rescoup_master.numSlaves();
461 bool any_connected =
false;
462 for (std::size_t slave_idx = 0; slave_idx < num_slaves; ++slave_idx) {
463 if (rescoup_master.slaveIsCoupled(slave_idx)) {
464 const bool connected =
465 this->masterNetworkHasMasterGroupLeavesForSlave_(slave_idx);
466 any_connected = any_connected || connected;
467 rescoup_master.sendCoupledNetworkActiveStatusToSlave(slave_idx, connected);
474 this->last_sent_master_group_node_pressures_is_final_ = !any_connected;
477template<
typename TypeTag>
479BlackoilWellModelRescoup<TypeTag>::
480sendMasterGroupConstraintsToSlaves()
486 RescoupConstraintsCalculator<Scalar, IndexTraits> constraints_calculator{
487 this->well_model_.guideRateHandler(),
488 this->groupStateHelper()
490 constraints_calculator.calculateMasterGroupConstraintsAndSendToSlaves();
493template<
typename TypeTag>
495BlackoilWellModelRescoup<TypeTag>::
496sendMasterGroupNodePressuresToSlaves(
bool is_final)
499 assert(this->isReservoirCouplingMaster());
500 auto& rescoup_master = this->reservoirCouplingMaster();
501 const auto& node_pressures = this->network_.nodePressures();
502 const auto num_slaves = rescoup_master.numSlaves();
503 for (std::size_t slave_idx = 0; slave_idx < num_slaves; ++slave_idx) {
504 if (!rescoup_master.slaveIsCoupled(slave_idx))
continue;
505 std::vector<typename ReservoirCoupling::MasterGroupNodePressure<Scalar>> pressures;
506 const auto& master_groups = rescoup_master.getMasterGroupNamesForSlave(slave_idx);
507 for (std::size_t i = 0; i < master_groups.size(); ++i) {
508 const auto it = node_pressures.find(master_groups[i]);
509 if (it != node_pressures.end()) {
510 pressures.push_back({i, it->second});
513 rescoup_master.sendNumMasterGroupNodePressuresToSlave(
514 slave_idx, pressures.size(), is_final);
515 if (!pressures.empty()) {
516 rescoup_master.sendMasterGroupNodePressuresToSlave(slave_idx, pressures);
519 this->last_sent_master_group_node_pressures_is_final_ = is_final;
522template<
typename TypeTag>
524BlackoilWellModelRescoup<TypeTag>::
525sendSlaveGroupDataToMaster()
528 assert(this->isReservoirCouplingSlave());
529 RescoupSendSlaveGroupData<Scalar, IndexTraits> slave_group_data_sender{
530 this->groupStateHelper(), this->well_model_.nupcolWellState()};
531 slave_group_data_sender.sendSlaveGroupDataToMaster();
543template<
typename TypeTag>
544std::optional<ReservoirCoupling::ScopedLoggerGuard>
545BlackoilWellModelRescoup<TypeTag>::
546setupScopedLogger(DeferredLogger& local_logger)
548 if (this->isReservoirCouplingMaster()) {
549 return ReservoirCoupling::ScopedLoggerGuard{
550 this->reservoirCouplingMaster().logger(),
553 }
else if (this->isReservoirCouplingSlave()) {
554 return ReservoirCoupling::ScopedLoggerGuard{
555 this->reservoirCouplingSlave().logger(),
562template<
typename TypeTag>
564BlackoilWellModelRescoup<TypeTag>::
565storeSlaveGroupInjectionTargets()
567 const int reportStepIdx = this->groupStateHelper().reportStepIdx();
583 using M = UnitSystem::measure;
584 auto& summary_state = this->simulator_.vanguard().summaryState();
585 const auto& units = this->simulator_.vanguard().eclState().getUnits();
586 auto& slave = this->reservoirCouplingSlave();
587 const auto& rescoup = this->schedule()[reportStepIdx].rescoup();
597 const auto targets = std::array {
598 std::tuple { Phase::GAS, std::string{
"GGIRT"}, M::gas_surface_rate },
599 std::tuple { Phase::WATER, std::string{
"GWIRT"}, M::liquid_surface_rate },
601 auto& in_force = slave.effectiveInjectionTargets();
603 for (std::size_t i = 0; i < slave.numSlaveGroups(); ++i) {
604 const auto& gname = slave.slaveGroupIdxToGroupName(i);
605 for (
const auto& [phase, keyword, unit] : targets) {
606 const auto effective = this->effectiveSlaveGroupInjectionTarget_(
607 gname, phase, reportStepIdx, rescoup, summary_state);
608 if (effective.has_value()) {
609 in_force[gname][phase] = *effective;
610 summary_state.update_group_var(gname, keyword, units.from_si(unit, *effective));
613 summary_state.update_group_var(
615 units.from_si(unit, this->scheduleInjectionTarget_(gname, phase, reportStepIdx, summary_state)));
621template<
typename TypeTag>
623BlackoilWellModelRescoup<TypeTag>::
624storeSlaveGroupProductionTargets()
626 const int reportStepIdx = this->groupStateHelper().reportStepIdx();
639 using M = UnitSystem::measure;
640 using CMode = Group::ProductionCMode;
641 auto& summary_state = this->simulator_.vanguard().summaryState();
642 const auto& units = this->simulator_.vanguard().eclState().getUnits();
643 auto& slave = this->reservoirCouplingSlave();
644 const auto& rescoup = this->schedule()[reportStepIdx].rescoup();
645 const auto targets = std::array {
646 std::tuple { CMode::ORAT, std::string{
"GOPRT"}, M::rate },
647 std::tuple { CMode::WRAT, std::string{
"GWPRT"}, M::rate },
648 std::tuple { CMode::GRAT, std::string{
"GGPRT"}, M::gas_surface_rate },
649 std::tuple { CMode::LRAT, std::string{
"GLPRT"}, M::rate },
651 auto& in_force = slave.effectiveProductionTargets();
653 for (std::size_t i = 0; i < slave.numSlaveGroups(); ++i) {
654 const auto& gname = slave.slaveGroupIdxToGroupName(i);
655 for (
const auto& [cmode, keyword, unit] : targets) {
656 const auto effective = this->effectiveSlaveGroupProductionTarget_(
657 gname, cmode, reportStepIdx, rescoup, summary_state);
658 if (effective.has_value()) {
659 in_force[gname][cmode] = *effective;
660 summary_state.update_group_var(gname, keyword, units.from_si(unit, *effective));
663 summary_state.update_group_var(
665 units.from_si(unit, this->scheduleProductionTarget_(gname, cmode, reportStepIdx, summary_state)));
671template<
typename TypeTag>
673BlackoilWellModelRescoup<TypeTag>::
674updateSlaveGroupCmodesAfterStateReset()
687 this->groupStateHelper().updateSlaveGroupCmodesFromMaster();
693template<
typename TypeTag>
694std::optional<typename BlackoilWellModelRescoup<TypeTag>::Scalar>
695BlackoilWellModelRescoup<TypeTag>::
696effectiveSlaveGroupInjectionTarget_(
const std::string& gname,
698 const int reportStepIdx,
699 const ReservoirCoupling::CouplingInfo& rescoup,
700 const SummaryState& summary_state)
const
702 using FilterFlag = ReservoirCoupling::GrupSlav::FilterFlag;
703 const auto& slave = this->reservoirCouplingSlave();
704 if (! slave.hasMasterInjectionTarget(gname, phase)) {
707 const auto [master_target, cmode] = slave.masterInjectionTarget(gname, phase);
708 if (cmode != Group::InjectionCMode::RATE) {
714 auto filter = FilterFlag::MAST;
715 if (rescoup.hasGrupSlav(gname)) {
716 const auto& grup_slav = rescoup.grupSlav(gname);
717 filter = (phase == Phase::GAS) ? grup_slav.gasInjFlag()
718 : (phase == Phase::WATER) ? grup_slav.waterInjFlag()
719 : grup_slav.oilInjFlag();
721 if (filter == FilterFlag::SLAV) {
726 if (filter == FilterFlag::BOTH) {
730 const auto& group = this->schedule().getGroup(gname, reportStepIdx);
731 if (group.has_control(phase, Group::InjectionCMode::RATE)) {
732 return std::min(master_target,
733 this->scheduleInjectionTarget_(gname, phase, reportStepIdx, summary_state));
736 return master_target;
739template<
typename TypeTag>
740std::optional<typename BlackoilWellModelRescoup<TypeTag>::Scalar>
741BlackoilWellModelRescoup<TypeTag>::
742effectiveSlaveGroupProductionTarget_(
const std::string& gname,
743 const Group::ProductionCMode cmode,
744 const int reportStepIdx,
745 const ReservoirCoupling::CouplingInfo& rescoup,
746 const SummaryState& summary_state)
const
753 using CMode = Group::ProductionCMode;
754 using FilterFlag = ReservoirCoupling::GrupSlav::FilterFlag;
755 const auto& slave = this->reservoirCouplingSlave();
756 if (! slave.hasMasterProductionLimits(gname)) {
759 const auto& limits = slave.masterProductionLimits(gname);
760 const Scalar master_limit = (cmode == CMode::ORAT) ? limits.oil_limit
761 : (cmode == CMode::WRAT) ? limits.water_limit
762 : (cmode == CMode::GRAT) ? limits.gas_limit
763 : limits.liquid_limit;
764 if (master_limit < 0) {
773 auto filter = FilterFlag::MAST;
774 if (rescoup.hasGrupSlav(gname)) {
775 const auto& grup_slav = rescoup.grupSlav(gname);
776 filter = (cmode == CMode::ORAT) ? grup_slav.oilProdFlag()
777 : (cmode == CMode::GRAT) ? grup_slav.gasProdFlag()
778 : grup_slav.liquidProdFlag();
780 if (filter == FilterFlag::SLAV) {
783 if (filter == FilterFlag::BOTH) {
784 const auto& group = this->schedule().getGroup(gname, reportStepIdx);
785 if (group.has_control(cmode)) {
786 return std::min(master_limit,
787 this->scheduleProductionTarget_(gname, cmode, reportStepIdx, summary_state));
793template<
typename TypeTag>
795BlackoilWellModelRescoup<TypeTag>::
796masterNetworkHasMasterGroupLeavesForSlave_(std::size_t slave_idx)
const
800 if (!this->isReservoirCouplingMaster())
return false;
801 const int episodeIdx = this->simulator_.episodeIndex();
802 const auto& network = this->schedule()[episodeIdx].network();
803 if (!network.active())
return false;
804 const auto& rcm = this->reservoirCouplingMaster();
805 for (
const auto& mg : rcm.getMasterGroupNamesForSlave(slave_idx)) {
806 if (network.has_node(mg)) {
813template<
typename TypeTag>
814typename BlackoilWellModelRescoup<TypeTag>::Scalar
815BlackoilWellModelRescoup<TypeTag>::
816scheduleInjectionTarget_(
const std::string& gname,
818 const int reportStepIdx,
819 const SummaryState& summary_state)
const
821 const auto& group = this->schedule().getGroup(gname, reportStepIdx);
822 if (! group.hasInjectionControl(phase)) {
825 return static_cast<Scalar
>(group.injectionControls(phase, summary_state).surface_max_rate);
828template<
typename TypeTag>
829typename BlackoilWellModelRescoup<TypeTag>::Scalar
830BlackoilWellModelRescoup<TypeTag>::
831scheduleProductionTarget_(
const std::string& gname,
832 const Group::ProductionCMode cmode,
833 const int reportStepIdx,
834 const SummaryState& summary_state)
const
836 using CMode = Group::ProductionCMode;
837 const auto controls = this->schedule().getGroup(gname, reportStepIdx)
838 .productionControls(summary_state);
840 case CMode::ORAT:
return static_cast<Scalar
>(controls.oil_target);
841 case CMode::WRAT:
return static_cast<Scalar
>(controls.water_target);
842 case CMode::GRAT:
return static_cast<Scalar
>(controls.gas_target);
843 case CMode::LRAT:
return static_cast<Scalar
>(controls.liquid_target);
844 default:
return Scalar{0};
848template<
typename TypeTag>
850BlackoilWellModelRescoup<TypeTag>::
851slaveGroupIsFixedPressureNodeInOwnNetwork_(
const std::string& group_name)
const
853 const int episodeIdx = this->simulator_.episodeIndex();
854 const auto& network = this->schedule()[episodeIdx].network();
855 if (!network.active())
return false;
856 if (!network.has_node(group_name))
return false;
857 return network.node(group_name).terminal_pressure().has_value();
860template<
typename TypeTag>
862BlackoilWellModelRescoup<TypeTag>::
863wellIsBelowOverriddenNode_(
const std::string& group_name,
864 const std::map<std::string, Scalar>& overrides)
const
866 if (overrides.empty())
return false;
867 const int episodeIdx = this->simulator_.episodeIndex();
868 const auto& network = this->schedule()[episodeIdx].network();
869 if (!network.active() || !network.has_node(group_name))
return false;
#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:207
#define OPM_BEGIN_PARALLEL_TRY_CATCH()
Macro to setup the try of a parallel try-catch.
Definition: DeferredLoggingErrorHelpers.hpp:160
if(!linsolver_)
Definition: FlexibleSolver_impl.hpp:338
Phase
Phase indices for reservoir coupling, we currently only support black-oil phases (oil,...
Definition: ReservoirCoupling.hpp:184
Definition: blackoilbioeffectsmodules.hh:45
bool nodeFollowsOverriddenNode(const Network::ExtNetwork &network, std::string node, const std::map< std::string, Scalar > &overrides)
Whether the pressure of a node follows from one of the overridden nodes (see the terminal pressure ov...
Definition: BlackoilWellModelNetworkPressureComputation.hpp:304