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>
34#include <opm/input/eclipse/Schedule/Network/Balance.hpp>
35#include <opm/input/eclipse/Schedule/Network/ExtNetwork.hpp>
36#include <opm/input/eclipse/Schedule/Well/PAvgDynamicSourceData.hpp>
37#include <opm/input/eclipse/Schedule/Well/WellMatcher.hpp>
38#include <opm/input/eclipse/Schedule/Well/WellTestConfig.hpp>
39#include <opm/input/eclipse/Schedule/Well/WellEconProductionLimits.hpp>
41#include <opm/input/eclipse/Units/UnitSystem.hpp>
51#ifdef RESERVOIR_COUPLING_ENABLED
71#include <fmt/format.h>
74 template<
typename TypeTag>
81 simulator.vanguard().summaryState(),
82 simulator.vanguard().eclState(),
84 simulator.gridView().comm())
85 , simulator_(simulator)
86 , guide_rate_handler_{
88 simulator.vanguard().schedule(),
89 simulator.vanguard().summaryState(),
90 simulator.vanguard().grid().comm()
92 , gaslift_(this->terminal_output_)
101 auto& parallel_wells =
simulator.vanguard().parallelWells();
104 for(
const auto& name_bool : parallel_wells) {
110 Parameters::Get<Parameters::AlternativeWellRateInit>();
112 using SourceDataSpan =
113 typename PAvgDynamicSourceData<Scalar>::template SourceDataSpan<Scalar>;
116 [
this](
const std::size_t globalIndex)
118 [
this](
const int localCell, SourceDataSpan sourceTerms)
120 using Item =
typename SourceDataSpan::Item;
122 const auto* intQuants = this->
simulator_.model()
123 .cachedIntensiveQuantities(localCell, 0);
124 const auto& fs = intQuants->fluidState();
127 .set(Item::PoreVol, intQuants->porosity().value() *
128 this->
simulator_.model().dofTotalVolume(localCell))
129 .set(Item::Depth, this->
depth_[localCell]);
131 constexpr auto io = FluidSystem::oilPhaseIdx;
132 constexpr auto ig = FluidSystem::gasPhaseIdx;
133 constexpr auto iw = FluidSystem::waterPhaseIdx;
136 const auto haveOil = FluidSystem::phaseIsActive(io);
137 const auto haveGas = FluidSystem::phaseIsActive(ig);
138 const auto haveWat = FluidSystem::phaseIsActive(iw);
140 auto weightedPhaseDensity = [&fs](
const auto ip)
142 return fs.saturation(ip).value() * fs.density(ip).value();
145 if (haveOil) { sourceTerms.set(Item::Pressure, fs.pressure(io).value()); }
146 else if (haveGas) { sourceTerms.set(Item::Pressure, fs.pressure(ig).value()); }
147 else { sourceTerms.set(Item::Pressure, fs.pressure(iw).value()); }
151 if (haveOil) { rho += weightedPhaseDensity(io); }
152 if (haveGas) { rho += weightedPhaseDensity(ig); }
153 if (haveWat) { rho += weightedPhaseDensity(iw); }
155 sourceTerms.set(Item::MixtureDensity, rho);
160 template<
typename TypeTag>
165 extractLegacyCellPvtRegionIndex_();
166 extractLegacyDepth_();
168 gravity_ = simulator_.problem().gravity()[2];
170 this->initial_step_ =
true;
173 simulator_.model().addAuxiliaryModule(
this);
175 is_cell_perforated_.resize(local_num_cells_,
false);
179 template<
typename TypeTag>
184 const uint64_t effective_events_mask = ScheduleEvents::WELL_STATUS_CHANGE
185 + ScheduleEvents::NEW_WELL;
186 const auto& events = this->schedule()[reportStepIdx].wellgroup_events();
187 for (
auto& wellPtr : this->well_container_) {
188 const bool well_opened_this_step = this->report_step_starts_ &&
189 events.hasEvent(wellPtr->name(),
190 effective_events_mask);
191 wellPtr->init(this->depth_, this->gravity_,
192 this->B_avg_, well_opened_this_step);
196 template<
typename TypeTag>
201 this->groupStateHelper().setReportStep(timeStepIdx);
202 this->report_step_starts_ =
true;
203 this->report_step_start_events_ = this->schedule()[timeStepIdx].wellgroup_events();
205 this->rateConverter_ = std::make_unique<RateConverterType>
206 (std::vector<int>(this->local_num_cells_, 0));
210 const auto enableWellPIScaling =
true;
211 this->initializeLocalWellStructure(timeStepIdx, enableWellPIScaling);
214 this->initializeGroupStructure(timeStepIdx);
216 const auto& comm = this->simulator_.vanguard().grid().comm();
222 this->rateConverter_->template defineState<ElementContext>(this->simulator_);
226 const auto& sched_state = this->schedule()[timeStepIdx];
228 this->vfp_properties_ = std::make_unique<VFPProperties<Scalar, IndexTraits>>
229 (sched_state.vfpinj(), sched_state.vfpprod(), this->wellState());
236 this->commitWGState();
238 this->wellStructureChangedDynamically_ =
false;
245 template <
typename TypeTag>
249 const bool enableWellPIScaling)
251 auto logger_guard = this->groupStateHelper().pushLogger();
252 auto& local_deferredLogger = this->groupStateHelper().deferredLogger();
254 const auto& comm = this->simulator_.vanguard().grid().comm();
257 this->wells_ecl_ = this->getLocalWells(reportStepIdx);
258 this->local_parallel_well_info_ =
259 this->createLocalParallelWellInfo(this->wells_ecl_);
266 this->initializeWellPerfData();
267 this->initializeWellState(reportStepIdx);
268 this->wbp_.initializeWBPCalculationService();
270 if (this->param_.use_multisegment_well_ && this->anyMSWellOpenLocal()) {
271 this->wellState().initWellStateMSWell(this->wells_ecl_, &this->prevWellState());
274 this->initializeWellProdIndCalculators();
276 if (enableWellPIScaling && this->schedule()[reportStepIdx].events()
277 .hasEvent(ScheduleEvents::Events::WELL_PRODUCTIVITY_INDEX))
279 this->runWellPIScaling(reportStepIdx, local_deferredLogger);
283 "Failed to initialize local well structure: ",
284 this->terminal_output_, comm)
291 template <
typename TypeTag>
296 const auto& comm = this->simulator_.vanguard().grid().comm();
300 const auto& fieldGroup =
301 this->schedule().getGroup(
"FIELD", reportStepIdx);
303 this->groupStateHelper().setCmodeGroup(fieldGroup);
307 if (this->schedule()[reportStepIdx].has_gpmaint()) {
308 this->groupStateHelper().setRegionAveragePressureCalculator(
310 this->eclState_.fieldProps(),
311 this->regionalAveragePressureCalculator_
323 template<
typename TypeTag>
328 OPM_TIMEBLOCK(beginTimeStep);
330 this->updateAverageFormationFactor();
332 auto logger_guard = this->groupStateHelper().pushLogger();
333 auto& local_deferredLogger = this->groupStateHelper().deferredLogger();
335#ifdef RESERVOIR_COUPLING_ENABLED
336 auto rescoup_logger_guard = this->setupRescoupScopedLogger(local_deferredLogger);
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();
367 const int reportStepIdx = simulator_.episodeIndex();
369 this->wellState().updateWellsDefaultALQ(this->schedule(), reportStepIdx, this->summaryState());
370 this->wellState().gliftTimeStepInit();
372 const double simulationTime = simulator_.time();
376 wellTesting(reportStepIdx, simulationTime, local_deferredLogger);
379 createWellContainer(reportStepIdx);
381#ifdef RESERVOIR_COUPLING_ENABLED
382 if (this->isReservoirCouplingMaster()) {
383 if (this->reservoirCouplingMaster().isFirstSubstepOfSyncTimestep()) {
384 this->receiveSlaveGroupData();
391 const auto& iterCtx = simulator_.problem().iterationContext();
392 this->updateAndCommunicateGroupData(reportStepIdx,
394 param_.nupcol_group_rate_tolerance_,
false);
397 const Grid& grid = simulator_.vanguard().grid();
398 this->wells_active_ = grid.comm().max(!this->well_container_.empty());
403 this->initWellContainer(reportStepIdx);
406 std::fill(is_cell_perforated_.begin(), is_cell_perforated_.end(),
false);
407 for (
auto& well : well_container_) {
408 well->updatePerforatedCell(is_cell_perforated_);
412 this->calculateEfficiencyFactors(reportStepIdx);
414 if constexpr (has_polymer_)
416 if (PolymerModule::hasPlyshlog() || getPropValue<TypeTag, Properties::EnablePolymerMW>() ) {
417 this->setRepRadiusPerfLength();
424 this->terminal_output_, simulator_.vanguard().grid().comm());
426 for (
auto& well : well_container_) {
427 well->setVFPProperties(this->vfp_properties_.get());
428 well->setGuideRate(&this->guideRate_);
431 this->updateFiltrationModelsPreStep(local_deferredLogger);
434 for (
auto& well : well_container_) {
435 well->closeCompletions(this->wellTestState());
441 if (alternative_well_rate_init_) {
446 for (
const auto& well : well_container_) {
447 if (well->isProducer() && !well->wellIsStopped()) {
448 well->initializeProducerWellState(simulator_, this->wellState(), local_deferredLogger);
453 for (
const auto& well : well_container_) {
454 if (well->isVFPActive(local_deferredLogger)){
455 well->setPrevSurfaceRates(this->wellState(), this->prevWellState());
459 this->updateWellPotentials(reportStepIdx,
461 simulator_.vanguard().summaryConfig(),
462 local_deferredLogger);
463 }
catch ( std::runtime_error& e ) {
464 const std::string msg =
"A zero well potential is returned for output purposes. ";
465 local_deferredLogger.warning(
"WELL_POTENTIAL_CALCULATION_FAILED", msg);
468 this->guide_rate_handler_.updateGuideRates(
469 reportStepIdx, simulationTime, this->wellState(), this->groupState()
471#ifdef RESERVOIR_COUPLING_ENABLED
472 if (this->isReservoirCouplingSlave()) {
473 if (this->reservoirCouplingSlave().isFirstSubstepOfSyncTimestep()) {
474 this->sendSlaveGroupDataToMaster();
475 this->receiveGroupConstraintsFromMaster();
476 this->groupStateHelper().updateSlaveGroupCmodesFromMaster();
483 if (this->schedule_[reportStepIdx].has_gpmaint()) {
484 for (
const auto& calculator : regionalAveragePressureCalculator_) {
485 calculator.second->template defineState<ElementContext>(simulator_);
487 const double dt = simulator_.timeStepSize();
488 const Group& fieldGroup = this->schedule().getGroup(
"FIELD", reportStepIdx);
490 this->groupStateHelper().updateGpMaintTargetForGroups(fieldGroup,
491 regionalAveragePressureCalculator_,
498 const auto& iterCtx = simulator_.problem().iterationContext();
499 this->updateAndCommunicateGroupData(reportStepIdx,
501 param_.nupcol_group_rate_tolerance_,
506 for (
auto& well : well_container_) {
507 const uint64_t effective_events_mask = ScheduleEvents::WELL_STATUS_CHANGE
508 + ScheduleEvents::INJECTION_TYPE_CHANGED
509 + ScheduleEvents::WELL_SWITCHED_INJECTOR_PRODUCER
510 + ScheduleEvents::NEW_WELL;
512 const auto& events = this->schedule()[reportStepIdx].wellgroup_events();
513 const bool event = this->report_step_starts_ && events.hasEvent(well->name(), effective_events_mask);
514 const bool dyn_status_change = this->wellState().well(well->name()).status
515 != this->prevWellState().well(well->name()).status;
517 if (event || dyn_status_change) {
519 well->scaleSegmentRatesAndPressure(this->wellState());
520 well->calculateExplicitQuantities(simulator_, this->groupStateHelper());
521 well->updateWellStateWithTarget(simulator_, this->groupStateHelper(), this->wellState());
522 well->updatePrimaryVariables(this->groupStateHelper());
523 well->solveWellEquation(
524 simulator_, this->groupStateHelper(), this->wellState()
526 }
catch (
const std::exception& e) {
527 const std::string msg =
"Compute initial well solution for new well " + well->name() +
" failed. Continue with zero initial rates";
528 local_deferredLogger.warning(
"WELL_INITIAL_SOLVE_FAILED", msg);
536#ifdef RESERVOIR_COUPLING_ENABLED
537 if (this->isReservoirCouplingMaster()) {
538 if (this->reservoirCouplingMaster().isFirstSubstepOfSyncTimestep()) {
539 this->sendMasterGroupConstraintsToSlaves();
545 const std::string msg =
"Compute initial well solution for new wells failed. Continue with zero initial rates";
546 local_deferredLogger.warning(
"WELL_INITIAL_SOLVE_FAILED", msg);
549 const auto& comm = simulator_.vanguard().grid().comm();
551 exc_type,
"beginTimeStep() failed: " + exc_msg, this->terminal_output_, comm);
555#ifdef RESERVOIR_COUPLING_ENABLED
565 template<
typename TypeTag>
566 std::optional<ReservoirCoupling::ScopedLoggerGuard>
569 if (this->isReservoirCouplingMaster()) {
571 this->reservoirCouplingMaster().logger(),
574 }
else if (this->isReservoirCouplingSlave()) {
575 return ReservoirCoupling::ScopedLoggerGuard{
576 this->reservoirCouplingSlave().logger(),
583 template<
typename TypeTag>
585 BlackoilWellModel<TypeTag>::
586 receiveSlaveGroupData()
588 assert(this->isReservoirCouplingMaster());
589 RescoupReceiveSlaveGroupData<Scalar, IndexTraits> slave_group_data_receiver{
590 this->groupStateHelper(),
592 slave_group_data_receiver.receiveSlaveGroupData();
595 template<
typename TypeTag>
597 BlackoilWellModel<TypeTag>::
598 sendSlaveGroupDataToMaster()
600 assert(this->isReservoirCouplingSlave());
601 RescoupSendSlaveGroupData<Scalar, IndexTraits> slave_group_data_sender{this->groupStateHelper()};
602 slave_group_data_sender.sendSlaveGroupDataToMaster();
605 template<
typename TypeTag>
607 BlackoilWellModel<TypeTag>::
608 sendMasterGroupConstraintsToSlaves()
611 RescoupConstraintsCalculator<Scalar, IndexTraits> constraints_calculator{
612 this->guide_rate_handler_,
613 this->groupStateHelper()
615 constraints_calculator.calculateMasterGroupConstraintsAndSendToSlaves();
618 template<
typename TypeTag>
620 BlackoilWellModel<TypeTag>::
621 receiveGroupConstraintsFromMaster()
623 RescoupReceiveGroupConstraints<Scalar, IndexTraits> constraint_receiver{
624 this->guide_rate_handler_,
625 this->groupStateHelper()
627 constraint_receiver.receiveGroupConstraintsFromMaster();
632 template<
typename TypeTag>
635 const double simulationTime,
638 for (
const std::string& well_name : this->getWellsForTesting(timeStepIdx, simulationTime)) {
639 const Well& wellEcl = this->schedule().getWell(well_name, timeStepIdx);
640 if (wellEcl.getStatus() == Well::Status::SHUT)
643 WellInterfacePtr well = createWellForWellTest(well_name, timeStepIdx, deferred_logger);
645 well->init(depth_, gravity_, B_avg_,
true);
647 Scalar well_efficiency_factor = wellEcl.getEfficiencyFactor() *
648 this->wellState().getGlobalEfficiencyScalingFactor(well_name);
649 this->groupStateHelper().accumulateGroupEfficiencyFactor(
650 this->schedule().getGroup(wellEcl.groupName(), timeStepIdx),
651 well_efficiency_factor
654 well->setWellEfficiencyFactor(well_efficiency_factor);
655 well->setVFPProperties(this->vfp_properties_.get());
656 well->setGuideRate(&this->guideRate_);
659 if (well->isProducer() && alternative_well_rate_init_) {
660 well->initializeProducerWellState(simulator_, this->wellState(), deferred_logger);
662 if (well->isVFPActive(deferred_logger)) {
663 well->setPrevSurfaceRates(this->wellState(), this->prevWellState());
666 const auto& network = this->schedule()[timeStepIdx].network();
667 if (network.active()) {
668 this->network_.initializeWell(*well);
672 GLiftEclWells ecl_well_map;
673 gaslift_.initGliftEclWellMap(well_container_, ecl_well_map);
674 well->wellTesting(simulator_,
676 this->groupStateHelper(),
678 this->wellTestState(),
680 this->well_open_times_);
681 }
catch (
const std::exception& e) {
682 const std::string msg =
683 fmt::format(fmt::runtime(
"Exception during testing of well: {}. The well will not open.\n"
684 "Exception message: {}"), wellEcl.name(), e.what());
685 deferred_logger.
warning(
"WELL_TESTING_FAILED", msg);
691 template<
typename TypeTag>
697 for (
auto&& pinfo : this->local_parallel_well_info_)
708 template<
typename TypeTag>
718 template<
typename TypeTag>
723 this->closed_this_step_.clear();
726 this->report_step_starts_ =
false;
727 const int reportStepIdx = simulator_.episodeIndex();
729 auto logger_guard = this->groupStateHelper().pushLogger();
730 auto& local_deferredLogger = this->groupStateHelper().deferredLogger();
731 for (
const auto& well : well_container_) {
732 if (getPropValue<TypeTag, Properties::EnablePolymerMW>() && well->isInjector()) {
733 well->updateWaterThroughput(dt, this->wellState());
737 for (
const auto& well : well_container_) {
738 well->updateConnectionTransmissibilityFactor(simulator_, this->wellState().well(well->indexOfWell()));
739 well->updateConnectionDFactor(simulator_, this->wellState().well(well->indexOfWell()));
742 if (Indices::waterEnabled) {
743 this->updateFiltrationModelsPostStep(dt, FluidSystem::waterPhaseIdx, local_deferredLogger);
747 this->updateInjMult(local_deferredLogger);
750 for (
const auto& well : well_container_) {
751 well->reportWellSwitching(this->wellState().well(well->indexOfWell()), local_deferredLogger);
754 if (this->terminal_output_) {
755 this->reportGroupSwitching(local_deferredLogger);
759 rateConverter_->template defineState<ElementContext>(simulator_);
763 this->updateWellPotentials(reportStepIdx,
765 simulator_.vanguard().summaryConfig(),
766 local_deferredLogger);
767 }
catch ( std::runtime_error& e ) {
768 const std::string msg =
"A zero well potential is returned for output purposes. ";
769 local_deferredLogger.warning(
"WELL_POTENTIAL_CALCULATION_FAILED", msg);
772 updateWellTestState(simulationTime, this->wellTestState());
775 const Group& fieldGroup = this->schedule_.getGroup(
"FIELD", reportStepIdx);
776 this->checkGEconLimits(fieldGroup, simulationTime,
777 simulator_.episodeIndex(), local_deferredLogger);
778 this->checkGconsaleLimits(fieldGroup, this->wellState(),
779 simulator_.episodeIndex(), local_deferredLogger);
781 this->calculateProductivityIndexValues(local_deferredLogger);
783 this->groupStateHelper().updateNONEProductionGroups();
785 this->commitWGState();
788 this->computeWellTemperature();
792 template<
typename TypeTag>
796 unsigned elemIdx)
const
800 if (!is_cell_perforated_[elemIdx] || cellRates_.count(elemIdx) == 0) {
804 rate = cellRates_.at(elemIdx);
808 template<
typename TypeTag>
809 template <
class Context>
813 const Context& context,
815 unsigned timeIdx)
const
818 int elemIdx = context.globalSpaceIndex(spaceIdx, timeIdx);
820 if (!is_cell_perforated_[elemIdx] || cellRates_.count(elemIdx) == 0) {
824 rate = cellRates_.at(elemIdx);
829 template<
typename TypeTag>
834 const auto pressIx = []()
836 if (Indices::oilEnabled) {
return FluidSystem::oilPhaseIdx; }
837 if (Indices::waterEnabled) {
return FluidSystem::waterPhaseIdx; }
839 return FluidSystem::gasPhaseIdx;
842 auto cellPressures = std::vector<Scalar>(this->local_num_cells_,
Scalar{0});
843 auto cellTemperatures = std::vector<Scalar>(this->local_num_cells_,
Scalar{0});
846 const auto& gridView = this->simulator_.vanguard().gridView();
849 for (
const auto& elem : elements(gridView, Dune::Partitions::interior)) {
850 elemCtx.updatePrimaryStencil(elem);
851 elemCtx.updatePrimaryIntensiveQuantities(0);
853 const auto ix = elemCtx.globalSpaceIndex(0, 0);
854 const auto& fs = elemCtx.intensiveQuantities(0, 0).fluidState();
856 cellPressures[ix] = fs.pressure(pressIx).value();
857 cellTemperatures[ix] = fs.temperature(0).value();
860 this->simulator_.vanguard().grid().comm());
862 this->wellState().init(cellPressures, cellTemperatures, this->schedule(), this->wells_ecl_,
863 this->local_parallel_well_info_, timeStepIdx,
864 &this->prevWellState(), this->well_perf_data_,
865 this->summaryState(), simulator_.vanguard().enableDistributedWells());
872 template<
typename TypeTag>
877 auto logger_guard = this->groupStateHelper().pushLogger();
878 auto& local_deferredLogger = this->groupStateHelper().deferredLogger();
880 const int nw = this->numLocalWells();
882 well_container_.clear();
885 well_container_.reserve(nw);
887 const auto& wmatcher = this->schedule().wellMatcher(report_step);
888 const auto& wcycle = this->schedule()[report_step].wcycle.get();
892 std::ranges::for_each(this->wells_ecl_,
893 [
this, &wg_events = this->report_step_start_events_](
const auto& well_ecl)
895 if (!well_ecl.hasConnections()) {
900 constexpr auto events_mask = ScheduleEvents::WELL_STATUS_CHANGE |
901 ScheduleEvents::REQUEST_OPEN_WELL |
902 ScheduleEvents::REQUEST_SHUT_WELL;
903 const bool well_event =
904 this->report_step_starts_ &&
905 wg_events.hasEvent(well_ecl.name(), events_mask);
914 if (well_ecl.getStatus() == WellStatus::OPEN) {
915 this->well_open_times_.insert_or_assign(well_ecl.name(),
916 this->simulator_.time());
917 this->well_close_times_.erase(well_ecl.name());
918 }
else if (well_ecl.getStatus() == WellStatus::SHUT) {
919 this->well_close_times_.insert_or_assign(well_ecl.name(),
920 this->simulator_.time());
921 this->well_open_times_.erase(well_ecl.name());
927 const auto cycle_states = wcycle.wellStatus(this->simulator_.time(),
929 this->well_open_times_,
930 this->well_close_times_);
932 for (
int w = 0; w < nw; ++w) {
933 const Well& well_ecl = this->wells_ecl_[w];
935 if (!well_ecl.hasConnections()) {
940 const std::string& well_name = well_ecl.name();
941 const auto well_status = this->schedule()
942 .getWell(well_name, report_step).getStatus();
944 const bool shut_event = this->wellState().well(w).events.hasEvent(ScheduleEvents::WELL_STATUS_CHANGE)
945 && well_status == Well::Status::SHUT;
946 const bool open_event = this->wellState().well(w).events.hasEvent(ScheduleEvents::WELL_STATUS_CHANGE)
947 && well_status == Well::Status::OPEN;
948 const auto& ws = this->wellState().well(well_name);
950 if (shut_event && ws.status != Well::Status::SHUT) {
951 this->closed_this_step_.insert(well_name);
952 this->wellState().shutWell(w);
953 }
else if (open_event && ws.status != Well::Status::OPEN) {
954 this->wellState().openWell(w);
958 if (this->wellTestState().well_is_closed(well_name)) {
963 const bool closed_this_step = (this->wellTestState().lastTestTime(well_name) == simulator_.time());
966 auto& events = this->wellState().well(w).events;
967 if (events.hasEvent(ScheduleEvents::REQUEST_OPEN_WELL)) {
968 if (!closed_this_step) {
969 this->wellTestState().open_well(well_name);
970 this->wellTestState().open_completions(well_name);
971 this->well_open_times_.insert_or_assign(well_name,
972 this->simulator_.time());
973 this->well_close_times_.erase(well_name);
975 events.clearEvent(ScheduleEvents::REQUEST_OPEN_WELL);
981 if (this->wellTestState().well_is_closed(well_name))
983 if (well_ecl.getAutomaticShutIn()) {
985 this->wellState().shutWell(w);
986 this->well_close_times_.erase(well_name);
987 this->well_open_times_.erase(well_name);
990 if (!well_ecl.getAllowCrossFlow()) {
993 this->wellState().shutWell(w);
994 this->well_close_times_.erase(well_name);
995 this->well_open_times_.erase(well_name);
999 this->wellState().stopWell(w);
1004 if (!well_ecl.getAllowCrossFlow()) {
1005 const bool any_zero_rate_constraint = well_ecl.isProducer()
1006 ? well_ecl.productionControls(this->summaryState_).anyZeroRateConstraint()
1007 : well_ecl.injectionControls(this->summaryState_).anyZeroRateConstraint();
1008 if (any_zero_rate_constraint) {
1010 local_deferredLogger.debug(fmt::format(fmt::runtime(
" Well {} gets shut due to having zero rate constraint and disallowing crossflow "), well_ecl.name()));
1011 this->wellState().shutWell(w);
1012 this->well_close_times_.erase(well_name);
1013 this->well_open_times_.erase(well_name);
1018 if (!wcycle.empty()) {
1019 const auto it = cycle_states.find(well_name);
1020 if (it != cycle_states.end()) {
1021 if (!it->second || well_status == Well::Status::SHUT) {
1023 if (well_status == Well::Status::SHUT) {
1024 this->well_open_times_.erase(well_name);
1025 this->well_close_times_.erase(well_name);
1027 this->wellState().shutWell(w);
1030 this->wellState().openWell(w);
1036 if (ws.status == Well::Status::SHUT) {
1040 well_container_.emplace_back(this->createWellPointer(w, report_step));
1042 if (ws.status == Well::Status::STOP) {
1043 well_container_.back()->stopWell();
1044 this->well_close_times_.erase(well_name);
1045 this->well_open_times_.erase(well_name);
1049 if (!wcycle.empty()) {
1050 const auto schedule_open =
1051 [&wg_events = this->report_step_start_events_](
const std::string& name)
1053 return wg_events.hasEvent(name, ScheduleEvents::REQUEST_OPEN_WELL);
1055 for (
const auto& [wname, wscale] : wcycle.efficiencyScale(this->simulator_.time(),
1056 this->simulator_.timeStepSize(),
1058 this->well_open_times_,
1061 this->wellState().updateEfficiencyScalingFactor(wname, wscale);
1062 this->schedule_.add_event(ScheduleEvents::WELLGROUP_EFFICIENCY_UPDATE, report_step);
1067 this->well_container_generic_.clear();
1068 for (
auto& w : well_container_) {
1069 this->well_container_generic_.push_back(w.get());
1072 this->network_.initialize(report_step);
1074 this->wbp_.registerOpenWellsForWBPCalculation();
1081 template <
typename TypeTag>
1086 const auto is_multiseg = this->wells_ecl_[wellID].isMultiSegment();
1088 if (! (this->param_.use_multisegment_well_ && is_multiseg)) {
1089 return this->
template createTypedWellPointer<StandardWell<TypeTag>>(wellID, report_step);
1092 return this->
template createTypedWellPointer<MultisegmentWell<TypeTag>>(wellID, report_step);
1100 template <
typename TypeTag>
1101 template <
typename WellType>
1102 std::unique_ptr<WellType>
1107 const auto& perf_data = this->well_perf_data_[wellID];
1110 const auto pvtreg = perf_data.empty()
1111 ? 0 : this->pvt_region_idx_[perf_data.front().cell_index];
1113 const auto& parallel_well_info = this->local_parallel_well_info_[wellID].get();
1114 const auto global_pvtreg = parallel_well_info.broadcastFirstPerforationValue(pvtreg);
1116 return std::make_unique<WellType>(this->wells_ecl_[wellID],
1120 *this->rateConverter_,
1122 this->numConservationQuantities(),
1132 template<
typename TypeTag>
1136 const int report_step,
1141 std::ranges::find_if(this->wells_ecl_,
1142 [&well_name](
const auto& w)
1143 {
return well_name == w.name(); });
1145 if (it == this->wells_ecl_.end()) {
1147 fmt::format(fmt::runtime(
"Could not find well {} in wells_ecl"), well_name),
1151 const int pos =
static_cast<int>(std::distance(this->wells_ecl_.begin(), it));
1152 return this->createWellPointer(pos, report_step);
1157 template<
typename TypeTag>
1163 auto logger_guard = this->groupStateHelper().pushLogger();
1164 auto& local_deferredLogger = this->groupStateHelper().deferredLogger();
1166 const auto& iterCtx = simulator_.problem().iterationContext();
1169 if (gaslift_.terminalOutput()) {
1170 const std::string msg =
1171 fmt::format(fmt::runtime(
"assemble() : iteration {}"), iterCtx.iteration());
1172 gaslift_.gliftDebug(msg, local_deferredLogger);
1176 Dune::Timer perfTimer;
1178 this->closed_offending_wells_.clear();
1181 const int episodeIdx = simulator_.episodeIndex();
1182 const auto& network = this->schedule()[episodeIdx].network();
1183 if (!this->wellsActive() && !network.active()) {
1189 if (iterCtx.needsTimestepInit() && this->wellsActive()) {
1190 OPM_TIMEBLOCK(firstIterationAssemble);
1197 calculateExplicitQuantities();
1198 prepareTimeStep(local_deferredLogger);
1201 "assemble() failed during well initialization: ",
1202 this->terminal_output_, grid().comm());
1205 const bool well_group_control_changed = updateWellControlsAndNetwork(
false, dt, local_deferredLogger);
1209 if ( ! this->wellsActive() ) {
1213 assembleWellEqWithoutIteration(dt);
1219 last_report_.well_group_control_changed = well_group_control_changed;
1220 last_report_.assemble_time_well += perfTimer.stop();
1226 template<
typename TypeTag>
1235 bool do_network_update =
true;
1236 bool well_group_control_changed =
false;
1237 Scalar network_imbalance = 0.0;
1239 const std::size_t iteration_to_relax = param_.network_max_strict_outer_iterations_;
1241 const std::size_t max_iteration = param_.network_max_outer_iterations_;
1242 std::size_t network_update_iteration = 0;
1243 network_needs_more_balancing_force_another_newton_iteration_ =
false;
1244 while (do_network_update) {
1245 if (network_update_iteration >= max_iteration ) {
1247 const int episodeIdx = simulator_.episodeIndex();
1248 const auto& iterCtx = simulator_.problem().iterationContext();
1249 if (this->network_.willBalanceOnNextIteration(episodeIdx, iterCtx)) {
1250 if (this->terminal_output_) {
1251 const std::string msg = fmt::format(
"Maximum of {:d} network iterations has been used and we stop the update, \n"
1252 "and try again after the next Newton iteration (imbalance = {:.2e} bar)",
1253 max_iteration, network_imbalance*1.0e-5);
1254 local_deferredLogger.
debug(msg);
1258 network_needs_more_balancing_force_another_newton_iteration_ =
true;
1260 if (this->terminal_output_) {
1261 const std::string msg = fmt::format(
"Maximum of {:d} network iterations has been used and we stop the update. \n"
1262 "The simulator will continue with unconverged network results (imbalance = {:.2e} bar)",
1263 max_iteration, network_imbalance*1.0e-5);
1264 local_deferredLogger.
info(msg);
1269 if (this->terminal_output_ && (network_update_iteration == iteration_to_relax) ) {
1270 local_deferredLogger.
debug(
"We begin using relaxed tolerance for network update now after " +
std::to_string(iteration_to_relax) +
" iterations ");
1272 const bool relax_network_balance = network_update_iteration >= iteration_to_relax;
1274 const bool optimize_gas_lift = ( (network_update_iteration + 1) < std::max(max_iteration,
static_cast<std::size_t
>(2)) );
1275 std::tie(well_group_control_changed, do_network_update, network_imbalance) =
1276 updateWellControlsAndNetworkIteration(mandatory_network_balance, relax_network_balance, optimize_gas_lift, dt,local_deferredLogger);
1277 ++network_update_iteration;
1279 return well_group_control_changed;
1285 template<
typename TypeTag>
1286 std::tuple<bool, bool, typename BlackoilWellModel<TypeTag>::Scalar>
1289 const bool relax_network_tolerance,
1290 const bool optimize_gas_lift,
1295 const auto& iterCtx = simulator_.problem().iterationContext();
1296 const int reportStepIdx = simulator_.episodeIndex();
1297 this->updateAndCommunicateGroupData(reportStepIdx, iterCtx,
1298 param_.nupcol_group_rate_tolerance_,
true);
1303 bool well_group_control_changed = updateWellControls(local_deferredLogger);
1304 const auto [more_inner_network_update, network_imbalance] =
1305 this->network_.update(mandatory_network_balance,
1306 local_deferredLogger,
1307 relax_network_tolerance);
1309 bool alq_updated =
false;
1312 if (optimize_gas_lift) {
1315 const bool updatePotentials = (this->network_.shouldBalance(reportStepIdx, iterCtx) ||
1316 mandatory_network_balance);
1317 alq_updated = gaslift_.maybeDoGasLiftOptimize(simulator_,
1319 this->network_.nodePressures(),
1323 local_deferredLogger);
1325 prepareWellsBeforeAssembling(dt);
1328 "updateWellControlsAndNetworkIteration() failed: ",
1329 this->terminal_output_, grid().comm());
1333 guideRateUpdateIsNeeded(reportStepIdx)) {
1334 const double simulationTime = simulator_.time();
1338 this->guide_rate_handler_.updateGuideRates(
1339 reportStepIdx, simulationTime, this->wellState(), this->groupState()
1344 const bool more_network_update = this->network_.shouldBalance(reportStepIdx, iterCtx) &&
1345 (more_inner_network_update || alq_updated);
1346 return {well_group_control_changed, more_network_update, network_imbalance};
1349 template<
typename TypeTag>
1355 for (
auto& well : well_container_) {
1356 well->assembleWellEq(simulator_, dt, this->groupStateHelper(), this->wellState());
1361 template<
typename TypeTag>
1367 for (
auto& well : well_container_) {
1368 well->prepareWellBeforeAssembling(
1369 simulator_, dt, this->groupStateHelper(), this->wellState()
1375 template<
typename TypeTag>
1381 auto& deferred_logger = this->groupStateHelper().deferredLogger();
1386 for (
auto& well: well_container_) {
1387 well->assembleWellEqWithoutIteration(simulator_, this->groupStateHelper(), dt, this->wellState(),
1391 this->terminal_output_, grid().comm());
1395 template<
typename TypeTag>
1402 for (
const auto& well : well_container_) {
1403 well->addCellRates(cellRates_);
1407 template<
typename TypeTag>
1414 for (
const auto& well : well_container_) {
1415 const auto it = well_domain_map.find(well->name());
1416 if (it != well_domain_map.end() && it->second == domainIndex) {
1417 well->addCellRates(cellRates_);
1422#if COMPILE_GPU_BRIDGE
1423 template<
typename TypeTag>
1431 for(
unsigned int i = 0; i < well_container_.size(); i++){
1432 auto& well = well_container_[i];
1435 wellContribs.
addNumBlocks(derived->linSys().getNumBlocks());
1440 wellContribs.
alloc();
1442 for(
unsigned int i = 0; i < well_container_.size(); i++){
1443 auto& well = well_container_[i];
1445 auto derived_std =
dynamic_cast<StandardWell<TypeTag>*
>(well.get());
1447 derived_std->linSys().extract(derived_std->numStaticWellEq, wellContribs);
1449 auto derived_ms =
dynamic_cast<MultisegmentWell<TypeTag>*
>(well.get());
1451 derived_ms->linSys().extract(wellContribs);
1453 OpmLog::warning(
"Warning unknown type of well");
1460 template<
typename TypeTag>
1465 for (
const auto& well: well_container_ ) {
1466 well->addWellContributions(jacobian);
1470 template<
typename TypeTag>
1475 const bool use_well_weights)
const
1477 int nw = this->numLocalWellsEnd();
1478 int rdofs = local_num_cells_;
1479 for (
int i = 0; i < nw; i++ ) {
1480 int wdof = rdofs + i;
1481 jacobian[wdof][wdof] = 1.0;
1484 for (
const auto& well : well_container_) {
1485 well->addWellPressureEquations(jacobian,
1493 template <
typename TypeTag>
1496 const std::vector<typename SparseMatrixAdapter::MatrixBlock*>& diagMatAddress)
const
1501 for (
const auto& well : well_container_) {
1502 if (!well->isOperableAndSolvable() && !well->wellIsStopped()) {
1505 const auto& cells = well->cells();
1506 const auto& rates = well->connectionRates();
1507 for (
unsigned perfIdx = 0; perfIdx < rates.size(); ++perfIdx) {
1508 unsigned cellIdx = cells[perfIdx];
1509 auto rate = rates[perfIdx];
1512 using MatrixBlockType =
typename SparseMatrixAdapter::MatrixBlock;
1513 MatrixBlockType bMat(0.0);
1514 simulator_.model().linearizer().setResAndJacobi(res, bMat, rate);
1515 residual[cellIdx] += res;
1516 *diagMatAddress[cellIdx] += bMat;
1522 template<
typename TypeTag>
1527 int nw = this->numLocalWellsEnd();
1528 int rdofs = local_num_cells_;
1529 for (
int i = 0; i < nw; ++i) {
1530 int wdof = rdofs + i;
1531 jacobian.entry(wdof,wdof) = 1.0;
1533 const auto wellconnections = this->getMaxWellConnections();
1534 for (
int i = 0; i < nw; ++i) {
1535 const auto& perfcells = wellconnections[i];
1536 for (
int perfcell : perfcells) {
1537 int wdof = rdofs + i;
1538 jacobian.entry(wdof, perfcell) = 0.0;
1539 jacobian.entry(perfcell, wdof) = 0.0;
1545 template<
typename TypeTag>
1550 auto loggerGuard = this->groupStateHelper().pushLogger();
1553 for (
const auto& well : well_container_) {
1554 const auto& cells = well->cells();
1555 x_local_.resize(cells.size());
1557 for (
size_t i = 0; i < cells.size(); ++i) {
1558 x_local_[i] = x[cells[i]];
1560 well->recoverWellSolutionAndUpdateWellState(simulator_, x_local_,
1561 this->groupStateHelper(), this->wellState());
1565 simulator_.vanguard().grid().comm());
1569 template<
typename TypeTag>
1575 OPM_THROW(std::logic_error,
"Attempt to call NLDD method without a NLDD solver");
1578 return nldd_->recoverWellSolutionAndUpdateWellState(x, domainIdx);
1582 template<
typename TypeTag>
1585 getWellConvergence(
const std::vector<Scalar>& B_avg,
bool checkWellGroupControlsAndNetwork)
const
1589 const auto& iterCtx = simulator_.problem().iterationContext();
1590 const bool relaxTolerance = iterCtx.shouldRelax(param_.strict_outer_iter_wells_ + 1);
1592 auto logger_guard = this->groupStateHelper().pushLogger();
1593 for (
const auto& well : well_container_) {
1594 if (well->isOperableAndSolvable() || well->wellIsStopped()) {
1595 local_report += well->getWellConvergence(
1596 this->groupStateHelper(), B_avg,
1601 report.
setWellFailed({CR::WellFailure::Type::Unsolvable, CR::Severity::Normal, -1, well->name()});
1602 local_report += report;
1610 if (checkWellGroupControlsAndNetwork) {
1616 if (this->terminal_output_) {
1620 OpmLog::debug(
"NaN residual found with phase " +
std::to_string(f.phase()) +
" for well " + f.wellName());
1622 OpmLog::debug(
"Too large residual found with phase " +
std::to_string(f.phase()) +
" for well " + f.wellName());
1633 template<
typename TypeTag>
1639 for (
auto& well : well_container_) {
1640 well->calculateExplicitQuantities(simulator_, this->groupStateHelper());
1648 template<
typename TypeTag>
1654 if (!this->wellsActive()) {
1657 const int episodeIdx = simulator_.episodeIndex();
1658 const auto& comm = simulator_.vanguard().grid().comm();
1660 bool changed_well_group =
false;
1661 const Group& fieldGroup = this->schedule().getGroup(
"FIELD", episodeIdx);
1664 const std::size_t max_iter = param_.well_group_constraints_max_iterations_;
1665 while(!changed_well_group && iter < max_iter) {
1666 changed_well_group = updateGroupControls(fieldGroup, deferred_logger, episodeIdx);
1669 bool changed_well_to_group =
false;
1671 OPM_TIMEBLOCK(UpdateWellControls);
1675 for (
const auto& well : well_container_) {
1678 simulator_, mode, this->groupStateHelper(), this->wellState()
1681 changed_well_to_group = changed_well || changed_well_to_group;
1685 simulator_.gridView().comm());
1688 changed_well_to_group = comm.sum(
static_cast<int>(changed_well_to_group));
1689 if (changed_well_to_group) {
1690 updateAndCommunicate(episodeIdx);
1691 changed_well_group =
true;
1695 bool changed_well_individual =
false;
1700 for (
const auto& well : well_container_) {
1703 simulator_, mode, this->groupStateHelper(), this->wellState()
1706 changed_well_individual = changed_well || changed_well_individual;
1710 simulator_.gridView().comm());
1713 changed_well_individual = comm.sum(
static_cast<int>(changed_well_individual));
1714 if (changed_well_individual) {
1715 updateAndCommunicate(episodeIdx);
1716 changed_well_group =
true;
1722 this->updateWsolvent(fieldGroup, episodeIdx, this->nupcolWellState());
1724 return changed_well_group;
1728 template<
typename TypeTag>
1733 const auto& iterCtx = simulator_.problem().iterationContext();
1734 this->updateAndCommunicateGroupData(reportStepIdx,
1736 param_.nupcol_group_rate_tolerance_,
1743 for (
const auto& well : well_container_) {
1745 const auto& ws = this->wellState().well(well->indexOfWell());
1746 if (ws.production_cmode == Well::ProducerCMode::GRUP ||
1747 ws.injection_cmode == Well::InjectorCMode::GRUP)
1749 well->updateWellStateWithTarget(
1750 simulator_, this->groupStateHelper(), this->wellState()
1755 simulator_.gridView().comm())
1756 this->updateAndCommunicateGroupData(reportStepIdx,
1758 param_.nupcol_group_rate_tolerance_,
1762 template<
typename TypeTag>
1767 const int reportStepIdx)
1770 const auto& iterCtx = simulator_.problem().iterationContext();
1771 bool changed =
false;
1773 const int nupcol = this->schedule()[reportStepIdx].nupcol();
1774 const int max_number_of_group_switches = param_.max_number_of_group_switches_;
1775 const bool update_group_switching_log = !iterCtx.withinNupcol(nupcol);
1776 const bool changed_hc = this->checkGroupHigherConstraints(group, deferred_logger, reportStepIdx, max_number_of_group_switches, update_group_switching_log);
1779 updateAndCommunicate(reportStepIdx);
1782 bool changed_individual =
1784 updateGroupIndividualControl(group,
1786 max_number_of_group_switches,
1787 update_group_switching_log,
1788 this->switched_inj_groups_,
1789 this->switched_prod_groups_,
1790 this->closed_offending_wells_,
1795 if (changed_individual) {
1797 updateAndCommunicate(reportStepIdx);
1800 for (
const std::string& groupName : group.groups()) {
1801 bool changed_this = updateGroupControls(this->schedule().getGroup(groupName, reportStepIdx), deferred_logger, reportStepIdx);
1802 changed = changed || changed_this;
1807 template<
typename TypeTag>
1813 auto logger_guard = this->groupStateHelper().pushLogger();
1814 auto& local_deferredLogger = this->groupStateHelper().deferredLogger();
1815 for (
const auto& well : well_container_) {
1816 const auto& wname = well->name();
1817 const auto wasClosed = wellTestState.well_is_closed(wname);
1818 well->checkWellOperability(simulator_,
1820 this->groupStateHelper());
1821 const bool under_zero_target =
1822 well->wellUnderZeroGroupRateTarget(this->groupStateHelper());
1823 well->updateWellTestState(this->wellState().well(wname),
1828 local_deferredLogger);
1830 if (!wasClosed && wellTestState.well_is_closed(wname)) {
1831 this->closed_this_step_.insert(wname);
1834 const WellEconProductionLimits& econ_production_limits = well->wellEcl().getEconLimits();
1835 if (econ_production_limits.validFollowonWell()) {
1836 const auto episode_idx = simulator_.episodeIndex();
1837 const auto follow_on_well = econ_production_limits.followonWell();
1838 if (!this->schedule().hasWell(follow_on_well, episode_idx)) {
1839 const auto msg = fmt::format(
"Well {} was closed. But the given follow on well {} does not exist."
1840 "The simulator continues without opening a follow on well.",
1841 wname, follow_on_well);
1842 local_deferredLogger.warning(msg);
1844 auto& ws = this->wellState().well(follow_on_well);
1845 const bool success = ws.updateStatus(WellStatus::OPEN);
1847 const auto msg = fmt::format(
"Well {} was closed. The follow on well {} opens instead.", wname, follow_on_well);
1848 local_deferredLogger.info(msg);
1850 const auto msg = fmt::format(
"Well {} was closed. The follow on well {} is already open.", wname, follow_on_well);
1851 local_deferredLogger.warning(msg);
1858 for (
const auto& [group_name, to] : this->closed_offending_wells_) {
1859 if (this->hasOpenLocalWell(to.second) &&
1860 !this->wasDynamicallyShutThisTimeStep(to.second))
1862 wellTestState.close_well(to.second,
1863 WellTestConfig::Reason::GROUP,
1865 this->updateClosedWellsThisStep(to.second);
1866 const std::string msg =
1867 fmt::format(
"Procedure on exceeding {} limit is WELL for group {}. "
1873 local_deferredLogger.info(msg);
1879 template<
typename TypeTag>
1883 std::string& exc_msg,
1887 const int np = this->numPhases();
1888 std::vector<Scalar> potentials;
1889 const auto& well = well_container_[widx];
1890 std::string cur_exc_msg;
1893 well->computeWellPotentials(simulator_, well_state_copy, this->groupStateHelper(), potentials);
1898 exc_msg += fmt::format(
"\nFor well {}: {}", well->name(), cur_exc_msg);
1900 exc_type = std::max(exc_type, cur_exc_type);
1904 auto& ws = this->wellState().well(well->indexOfWell());
1905 for (
int p = 0; p < np; ++p) {
1907 ws.well_potentials[p] = std::max(
Scalar{0.0}, potentials[p]);
1913 template <
typename TypeTag>
1918 for (
const auto& wellPtr : this->well_container_) {
1919 this->calculateProductivityIndexValues(wellPtr.get(), deferred_logger);
1927 template <
typename TypeTag>
1938 for (
const auto& shutWell : this->local_shut_wells_) {
1939 if (!this->wells_ecl_[shutWell].hasConnections()) {
1944 auto wellPtr = this->
template createTypedWellPointer
1947 wellPtr->
init(this->depth_, this->gravity_, this->B_avg_,
true);
1949 this->calculateProductivityIndexValues(wellPtr.get(), deferred_logger);
1957 template <
typename TypeTag>
1971 template<
typename TypeTag>
1977 const auto episodeIdx = simulator_.episodeIndex();
1978 this->network_.updateActiveState(episodeIdx);
1982 const bool do_prestep_network_rebalance =
1983 param_.pre_solve_network_ && this->network_.needPreStepRebalance(episodeIdx);
1985 for (
const auto& well : well_container_) {
1986 auto& events = this->wellState().well(well->indexOfWell()).events;
1988 well->updateWellStateWithTarget(
1989 simulator_, this->groupStateHelper(), this->wellState()
1991 well->updatePrimaryVariables(this->groupStateHelper());
1997 if (events.hasEvent(ScheduleEvents::REQUEST_OPEN_WELL)) {
1998 events.clearEvent(ScheduleEvents::REQUEST_OPEN_WELL);
2001 if (param_.solve_welleq_initially_ && well->isOperableAndSolvable()) {
2003 well->solveWellEquation(
2004 simulator_, this->groupStateHelper(), this->wellState()
2006 }
catch (
const std::exception& e) {
2007 const std::string msg =
"Compute initial well solution for " + well->name() +
" initially failed. Continue with the previous rates";
2008 deferred_logger.
warning(
"WELL_INITIAL_SOLVE_FAILED", msg);
2013 well->resetWellOperability();
2015 updatePrimaryVariables();
2018 if (do_prestep_network_rebalance) {
2019 network_.doPreStepRebalance(deferred_logger);
2023 template<
typename TypeTag>
2028 std::vector< Scalar > B_avg(numConservationQuantities(),
Scalar() );
2029 const auto& grid = simulator_.vanguard().grid();
2030 const auto& gridView = grid.leafGridView();
2034 for (
const auto& elem : elements(gridView, Dune::Partitions::interior)) {
2035 elemCtx.updatePrimaryStencil(elem);
2036 elemCtx.updatePrimaryIntensiveQuantities(0);
2038 const auto& intQuants = elemCtx.intensiveQuantities(0, 0);
2039 const auto& fs = intQuants.fluidState();
2041 for (
unsigned phaseIdx = 0; phaseIdx < FluidSystem::numPhases; ++phaseIdx)
2043 if (!FluidSystem::phaseIsActive(phaseIdx)) {
2047 const unsigned compIdx = FluidSystem::canonicalToActiveCompIdx(FluidSystem::solventComponentIndex(phaseIdx));
2048 auto& B = B_avg[ compIdx ];
2050 B += 1 / fs.invB(phaseIdx).value();
2052 if constexpr (has_solvent_) {
2053 auto& B = B_avg[solventSaturationIdx];
2054 B += 1 / intQuants.solventInverseFormationVolumeFactor().value();
2060 grid.comm().sum(B_avg.data(), B_avg.size());
2061 B_avg_.resize(B_avg.size());
2062 std::ranges::transform(B_avg, B_avg_.begin(),
2063 [gcells = global_num_cells_](
const auto bval)
2064 { return bval / gcells; });
2071 template<
typename TypeTag>
2076 for (
const auto& well : well_container_) {
2077 well->updatePrimaryVariables(this->groupStateHelper());
2081 template<
typename TypeTag>
2085 const auto& grid = simulator_.vanguard().grid();
2086 const auto& eclProblem = simulator_.problem();
2087 const unsigned numCells = grid.size(0);
2089 this->pvt_region_idx_.resize(numCells);
2090 for (
unsigned cellIdx = 0; cellIdx < numCells; ++cellIdx) {
2091 this->pvt_region_idx_[cellIdx] =
2092 eclProblem.pvtRegionIndex(cellIdx);
2097 template<
typename TypeTag>
2110 return this->numPhases() + has_solvent_;
2113 template<
typename TypeTag>
2117 const auto& eclProblem = simulator_.problem();
2118 depth_.resize(local_num_cells_);
2119 for (
unsigned cellIdx = 0; cellIdx < local_num_cells_; ++cellIdx) {
2120 depth_[cellIdx] = eclProblem.dofCenterDepth(cellIdx);
2124 template<
typename TypeTag>
2127 getWell(
const std::string& well_name)
const
2131 std::ranges::find_if(well_container_,
2133 {
return elem->name() == well_name; });
2135 assert(well != well_container_.end());
2140 template <
typename TypeTag>
2145 return std::max(this->simulator_.episodeIndex(), 0);
2152 template<
typename TypeTag>
2157 const std::vector<Scalar>& production_rates,
2158 std::vector<Scalar>& resv_coeff)
const
2160 rateConverter_->calcCoeff(fipnum, pvtreg, production_rates, resv_coeff);
2163 template<
typename TypeTag>
2168 std::vector<Scalar>& resv_coeff)
const
2170 rateConverter_->calcInjCoeff(fipnum, pvtreg, resv_coeff);
2174 template <
typename TypeTag>
2179 if constexpr (energyModuleType_ == EnergyModules::FullyImplicitThermal) {
2180 const int np = this->numPhases();
2181 const int nw = this->numLocalWells();
2182 for (
auto wellID = 0*nw; wellID < nw; ++wellID) {
2183 const Well& well = this->wells_ecl_[wellID];
2184 auto& ws = this->wellState().well(wellID);
2185 if (well.isInjector()) {
2186 if (ws.status != WellStatus::STOP) {
2187 this->wellState().well(wellID).temperature = well.inj_temperature();
2191 std::array<Scalar,2> weighted{0.0,0.0};
2192 auto& [weighted_temperature, total_weight] = weighted;
2193 const auto& well_info = this->local_parallel_well_info_[wellID].get();
2194 using int_type =
decltype(this->well_perf_data_[wellID].size());
2195 for (int_type perf = 0, end_perf = this->well_perf_data_[wellID].size(); perf < end_perf; ++perf) {
2196 const int cell_idx = this->well_perf_data_[wellID][perf].cell_index;
2197 const auto& intQuants = simulator_.model().intensiveQuantities(cell_idx, 0);
2198 const auto& fs = intQuants.fluidState();
2199 Scalar weight_factor = computeTemperatureWeightFactor(perf, np, fs, ws);
2200 total_weight += weight_factor;
2201 weighted_temperature += weight_factor * fs.temperature(0).value();
2203 well_info.communication().sum(weighted.data(), 2);
2204 this->wellState().well(wellID).temperature = weighted_temperature / total_weight;
2210 template <
typename TypeTag>
2214 const auto reportStepIdx =
static_cast<unsigned int>(this->reportStepIndex());
2215 const auto& trMod = this->simulator_.problem().tracerModel();
2221 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:97
const Parallel::Communication & comm() const
Definition: BlackoilWellModelGeneric.hpp:224
BlackoilWellModelWBP< GetPropType< TypeTag, Properties::Scalar >, GetPropType< TypeTag, Properties::FluidSystem >::IndexTraitsType > wbp_
Definition: BlackoilWellModelGeneric.hpp:518
std::vector< ParallelWellInfo< GetPropType< TypeTag, Properties::Scalar > > > parallel_well_info_
Definition: BlackoilWellModelGeneric.hpp:545
void assignWellTracerRates(data::Wells &wsrpt, const WellTracerRates &wellTracerRates, const unsigned reportStep) const
Class for handling the guide rates in the blackoil well model.
Definition: BlackoilWellModelGuideRates.hpp:47
Class for handling the blackoil well model.
Definition: BlackoilWellModel.hpp:98
void initializeGroupStructure(const int reportStepIdx)
Definition: BlackoilWellModel_impl.hpp:294
void calcResvCoeff(const int fipnum, const int pvtreg, const std::vector< Scalar > &production_rates, std::vector< Scalar > &resv_coeff) const override
Definition: BlackoilWellModel_impl.hpp:2155
void prepareTimeStep(DeferredLogger &deferred_logger)
Definition: BlackoilWellModel_impl.hpp:1974
std::tuple< bool, bool, Scalar > updateWellControlsAndNetworkIteration(const bool mandatory_network_balance, const bool relax_network_tolerance, const bool optimize_gas_lift, const double dt, DeferredLogger &local_deferredLogger)
Definition: BlackoilWellModel_impl.hpp:1288
WellInterfacePtr createWellPointer(const int wellID, const int report_step) const
Definition: BlackoilWellModel_impl.hpp:1084
void prepareWellsBeforeAssembling(const double dt)
Definition: BlackoilWellModel_impl.hpp:1364
void init()
Definition: BlackoilWellModel_impl.hpp:163
const Simulator & simulator() const
Definition: BlackoilWellModel.hpp:366
std::vector< Scalar > depth_
Definition: BlackoilWellModel.hpp:512
std::size_t global_num_cells_
Definition: BlackoilWellModel.hpp:508
GetPropType< TypeTag, Properties::Scalar > Scalar
Definition: BlackoilWellModel.hpp:107
void initWellContainer(const int reportStepIdx) override
Definition: BlackoilWellModel_impl.hpp:182
void beginReportStep(const int time_step)
Definition: BlackoilWellModel_impl.hpp:199
const WellInterface< TypeTag > & getWell(const std::string &well_name) const
Definition: BlackoilWellModel_impl.hpp:2127
GetPropType< TypeTag, Properties::FluidSystem > FluidSystem
Definition: BlackoilWellModel.hpp:103
Dune::FieldVector< Scalar, numEq > VectorBlockType
Definition: BlackoilWellModel.hpp:129
GetPropType< TypeTag, Properties::ElementContext > ElementContext
Definition: BlackoilWellModel.hpp:104
GetPropType< TypeTag, Properties::Grid > Grid
Definition: BlackoilWellModel.hpp:101
int numConservationQuantities() const
Definition: BlackoilWellModel_impl.hpp:2099
bool updateWellControls(DeferredLogger &deferred_logger)
Definition: BlackoilWellModel_impl.hpp:1651
int reportStepIndex() const
Definition: BlackoilWellModel_impl.hpp:2143
void calculateProductivityIndexValues(DeferredLogger &deferred_logger) override
Definition: BlackoilWellModel_impl.hpp:1916
void extractLegacyDepth_()
Definition: BlackoilWellModel_impl.hpp:2115
void extractLegacyCellPvtRegionIndex_()
Definition: BlackoilWellModel_impl.hpp:2083
void recoverWellSolutionAndUpdateWellStateDomain(const BVector &x, const int domainIdx)
Definition: BlackoilWellModel_impl.hpp:1572
void updateAverageFormationFactor()
Definition: BlackoilWellModel_impl.hpp:2026
GetPropType< TypeTag, Properties::Simulator > Simulator
Definition: BlackoilWellModel.hpp:106
void initializeWellState(const int timeStepIdx)
Definition: BlackoilWellModel_impl.hpp:832
const Grid & grid() const
Definition: BlackoilWellModel.hpp:363
void updatePrimaryVariables()
Definition: BlackoilWellModel_impl.hpp:2074
void computeWellTemperature()
Definition: BlackoilWellModel_impl.hpp:2177
void addWellPressureEquations(PressureMatrix &jacobian, const BVector &weights, const bool use_well_weights) const
Definition: BlackoilWellModel_impl.hpp:1473
const SimulatorReportSingle & lastReport() const
Definition: BlackoilWellModel_impl.hpp:711
bool updateWellControlsAndNetwork(const bool mandatory_network_balance, const double dt, DeferredLogger &local_deferredLogger)
Definition: BlackoilWellModel_impl.hpp:1229
void addWellContributions(SparseMatrixAdapter &jacobian) const
Definition: BlackoilWellModel_impl.hpp:1463
void assembleWellEq(const double dt)
Definition: BlackoilWellModel_impl.hpp:1352
WellInterfacePtr createWellForWellTest(const std::string &well_name, const int report_step, DeferredLogger &deferred_logger) const
Definition: BlackoilWellModel_impl.hpp:1135
void calculateExplicitQuantities() const
Definition: BlackoilWellModel_impl.hpp:1636
void updateAndCommunicate(const int reportStepIdx)
Definition: BlackoilWellModel_impl.hpp:1731
Dune::BCRSMatrix< Opm::MatrixBlock< Scalar, 1, 1 > > PressureMatrix
Definition: BlackoilWellModel.hpp:285
void computeTotalRatesForDof(RateVector &rate, unsigned globalIdx) const
Definition: BlackoilWellModel_impl.hpp:795
void beginTimeStep()
Definition: BlackoilWellModel_impl.hpp:326
GetPropType< TypeTag, Properties::RateVector > RateVector
Definition: BlackoilWellModel.hpp:108
bool updateGroupControls(const Group &group, DeferredLogger &deferred_logger, const int reportStepIdx)
Definition: BlackoilWellModel_impl.hpp:1765
void calcInjResvCoeff(const int fipnum, const int pvtreg, std::vector< Scalar > &resv_coeff) const override
Definition: BlackoilWellModel_impl.hpp:2166
void initializeLocalWellStructure(const int reportStepIdx, const bool enableWellPIScaling)
Definition: BlackoilWellModel_impl.hpp:248
Dune::BlockVector< VectorBlockType > BVector
Definition: BlackoilWellModel.hpp:130
BlackoilWellModel(Simulator &simulator)
Definition: BlackoilWellModel_impl.hpp:76
void wellTesting(const int timeStepIdx, const double simulationTime, DeferredLogger &deferred_logger)
Definition: BlackoilWellModel_impl.hpp:634
ConvergenceReport getWellConvergence(const std::vector< Scalar > &B_avg, const bool checkWellGroupControlsAndNetwork=false) const
Definition: BlackoilWellModel_impl.hpp:1585
typename FluidSystem::IndexTraitsType IndexTraits
Definition: BlackoilWellModel.hpp:114
void updateCellRatesForDomain(int domainIndex, const std::map< std::string, int > &well_domain_map)
Definition: BlackoilWellModel_impl.hpp:1410
void assembleWellEqWithoutIteration(const double dt)
Definition: BlackoilWellModel_impl.hpp:1378
void updateCellRates()
Definition: BlackoilWellModel_impl.hpp:1398
void assemble(const double dt)
Definition: BlackoilWellModel_impl.hpp:1160
std::size_t local_num_cells_
Definition: BlackoilWellModel.hpp:510
bool alternative_well_rate_init_
Definition: BlackoilWellModel.hpp:513
void timeStepSucceeded(const double simulationTime, const double dt)
Definition: BlackoilWellModel_impl.hpp:721
std::unique_ptr< WellType > createTypedWellPointer(const int wellID, const int time_step) const
Definition: BlackoilWellModel_impl.hpp:1104
void computePotentials(const std::size_t widx, const WellState< Scalar, IndexTraits > &well_state_copy, std::string &exc_msg, ExceptionType::ExcEnum &exc_type) override
Definition: BlackoilWellModel_impl.hpp:1881
Simulator & simulator_
Definition: BlackoilWellModel.hpp:482
void createWellContainer(const int report_step) override
Definition: BlackoilWellModel_impl.hpp:875
std::unique_ptr< WellInterface< TypeTag > > WellInterfacePtr
Definition: BlackoilWellModel.hpp:186
void updateWellTestState(const double simulationTime, WellTestState &wellTestState)
upate the wellTestState related to economic limits
Definition: BlackoilWellModel_impl.hpp:1810
void addReservoirSourceTerms(GlobalEqVector &residual, const std::vector< typename SparseMatrixAdapter::MatrixBlock * > &diagMatAddress) const
Definition: BlackoilWellModel_impl.hpp:1495
int compressedIndexForInterior(int cartesian_cell_idx) const override
get compressed index for interior cells (-1, otherwise
Definition: BlackoilWellModel.hpp:338
void recoverWellSolutionAndUpdateWellState(const BVector &x)
Definition: BlackoilWellModel_impl.hpp:1548
void addWellPressureEquationsStruct(PressureMatrix &jacobian) const
Definition: BlackoilWellModel_impl.hpp:1525
void calculateProductivityIndexValuesShutWells(const int reportStepIdx, DeferredLogger &deferred_logger) override
Definition: BlackoilWellModel_impl.hpp:1930
void endReportStep()
Definition: BlackoilWellModel_impl.hpp:694
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:65
Guard for managing DeferredLogger lifecycle in ReservoirCoupling.
Definition: ReservoirCoupling.hpp:88
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: WellContributions.hpp:51
void alloc()
Allocate memory for the StandardWells.
void setBlockSize(unsigned int dim, unsigned int dim_wells)
void addNumBlocks(unsigned int numBlocks)
int indexOfWell() const
Index of well in the wells struct and wellState.
Definition: WellInterface.hpp:77
virtual void updateProductivityIndex(const Simulator &simulator, const WellProdIndexCalculator< Scalar > &wellPICalc, WellStateType &well_state, DeferredLogger &deferred_logger) const =0
bool updateWellControl(const Simulator &simulator, const IndividualOrGroup iog, const GroupStateHelperType &groupStateHelper, WellStateType &well_state)
Definition: WellInterface_impl.hpp:189
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:45
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