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
69#include <fmt/format.h>
72 template<
typename TypeTag>
79 simulator.vanguard().summaryState(),
80 simulator.vanguard().eclState(),
82 simulator.gridView().comm())
83 , simulator_(simulator)
84 , guide_rate_handler_{
86 simulator.vanguard().schedule(),
87 simulator.vanguard().summaryState(),
88 simulator.vanguard().grid().comm()
90 , gaslift_(this->terminal_output_)
99 auto& parallel_wells =
simulator.vanguard().parallelWells();
102 for(
const auto& name_bool : parallel_wells) {
108 Parameters::Get<Parameters::AlternativeWellRateInit>();
110 using SourceDataSpan =
111 typename PAvgDynamicSourceData<Scalar>::template SourceDataSpan<Scalar>;
114 [
this](
const std::size_t globalIndex)
116 [
this](
const int localCell, SourceDataSpan sourceTerms)
118 using Item =
typename SourceDataSpan::Item;
120 const auto* intQuants = this->
simulator_.model()
121 .cachedIntensiveQuantities(localCell, 0);
122 const auto& fs = intQuants->fluidState();
125 .set(Item::PoreVol, intQuants->porosity().value() *
126 this->
simulator_.model().dofTotalVolume(localCell))
127 .set(Item::Depth, this->
depth_[localCell]);
129 constexpr auto io = FluidSystem::oilPhaseIdx;
130 constexpr auto ig = FluidSystem::gasPhaseIdx;
131 constexpr auto iw = FluidSystem::waterPhaseIdx;
134 const auto haveOil = FluidSystem::phaseIsActive(io);
135 const auto haveGas = FluidSystem::phaseIsActive(ig);
136 const auto haveWat = FluidSystem::phaseIsActive(iw);
138 auto weightedPhaseDensity = [&fs](
const auto ip)
140 return fs.saturation(ip).value() * fs.density(ip).value();
143 if (haveOil) { sourceTerms.set(Item::Pressure, fs.pressure(io).value()); }
144 else if (haveGas) { sourceTerms.set(Item::Pressure, fs.pressure(ig).value()); }
145 else { sourceTerms.set(Item::Pressure, fs.pressure(iw).value()); }
149 if (haveOil) { rho += weightedPhaseDensity(io); }
150 if (haveGas) { rho += weightedPhaseDensity(ig); }
151 if (haveWat) { rho += weightedPhaseDensity(iw); }
153 sourceTerms.set(Item::MixtureDensity, rho);
158 template<
typename TypeTag>
163 extractLegacyCellPvtRegionIndex_();
164 extractLegacyDepth_();
166 gravity_ = simulator_.problem().gravity()[2];
168 this->initial_step_ =
true;
171 simulator_.model().addAuxiliaryModule(
this);
173 is_cell_perforated_.resize(local_num_cells_,
false);
177 template<
typename TypeTag>
182 const uint64_t effective_events_mask = ScheduleEvents::WELL_STATUS_CHANGE
183 + ScheduleEvents::NEW_WELL;
184 const auto& events = this->schedule()[reportStepIdx].wellgroup_events();
185 for (
auto& wellPtr : this->well_container_) {
186 const bool well_opened_this_step = this->report_step_starts_ &&
187 events.hasEvent(wellPtr->name(),
188 effective_events_mask);
189 wellPtr->init(this->depth_, this->gravity_,
190 this->B_avg_, well_opened_this_step);
194 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());
233 "beginReportStep() failed: ",
234 this->terminal_output_, comm)
238 this->commitWGState();
240 this->wellStructureChangedDynamically_ =
false;
247 template <
typename TypeTag>
251 const bool enableWellPIScaling)
255 const auto& comm = this->simulator_.vanguard().grid().comm();
258 this->wells_ecl_ = this->getLocalWells(reportStepIdx);
259 this->local_parallel_well_info_ =
260 this->createLocalParallelWellInfo(this->wells_ecl_);
267 this->initializeWellPerfData();
268 this->initializeWellState(reportStepIdx);
269 this->wbp_.initializeWBPCalculationService();
271 if (this->param_.use_multisegment_well_ && this->anyMSWellOpenLocal()) {
272 this->wellState().initWellStateMSWell(this->wells_ecl_, &this->prevWellState());
275 this->initializeWellProdIndCalculators();
277 if (enableWellPIScaling && this->schedule()[reportStepIdx].events()
278 .hasEvent(ScheduleEvents::Events::WELL_PRODUCTIVITY_INDEX))
280 this->runWellPIScaling(reportStepIdx, local_deferredLogger);
284 "Failed to initialize local well structure: ",
285 this->terminal_output_, comm)
292 template <
typename TypeTag>
299 const auto& comm = this->simulator_.vanguard().grid().comm();
303 const auto& fieldGroup =
304 this->schedule().getGroup(
"FIELD", reportStepIdx);
306 this->groupStateHelper().setCmodeGroup(fieldGroup);
310 if (this->schedule()[reportStepIdx].has_gpmaint()) {
311 this->groupStateHelper().setRegionAveragePressureCalculator(
313 this->eclState_.fieldProps(),
314 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#ifdef RESERVOIR_COUPLING_ENABLED
340 auto rescoup_logger_guard = this->setupRescoupScopedLogger(local_deferredLogger);
342 this->switched_prod_groups_.clear();
343 this->switched_inj_groups_.clear();
345 if (this->wellStructureChangedDynamically_) {
350 const auto reportStepIdx =
351 this->simulator_.episodeIndex();
355 const auto enableWellPIScaling =
false;
357 this->initializeLocalWellStructure(reportStepIdx, enableWellPIScaling);
358 this->initializeGroupStructure(reportStepIdx);
360 this->commitWGState();
366 this->wellStructureChangedDynamically_ =
false;
369 this->resetWGState();
370 const int reportStepIdx = simulator_.episodeIndex();
372 this->wellState().updateWellsDefaultALQ(this->schedule(), reportStepIdx, this->summaryState());
373 this->wellState().gliftTimeStepInit();
375 const double simulationTime = simulator_.time();
379 wellTesting(reportStepIdx, simulationTime, local_deferredLogger);
382 createWellContainer(reportStepIdx);
384#ifdef RESERVOIR_COUPLING_ENABLED
386 if (this->isReservoirCouplingMaster()) {
387 this->receiveSlaveGroupData();
393 this->updateAndCommunicateGroupData(reportStepIdx,
394 simulator_.model().newtonMethod().numIterations(),
395 param_.nupcol_group_rate_tolerance_,
false,
396 local_deferredLogger);
399 const Grid& grid = simulator_.vanguard().grid();
400 this->wells_active_ = grid.comm().max(!this->well_container_.empty());
405 this->initWellContainer(reportStepIdx);
408 std::fill(is_cell_perforated_.begin(), is_cell_perforated_.end(),
false);
409 for (
auto& well : well_container_) {
410 well->updatePerforatedCell(is_cell_perforated_);
414 this->calculateEfficiencyFactors(reportStepIdx);
416 if constexpr (has_polymer_)
418 if (PolymerModule::hasPlyshlog() || getPropValue<TypeTag, Properties::EnablePolymerMW>() ) {
419 this->setRepRadiusPerfLength();
426 this->terminal_output_, simulator_.vanguard().grid().comm());
428 for (
auto& well : well_container_) {
429 well->setVFPProperties(this->vfp_properties_.get());
430 well->setGuideRate(&this->guideRate_);
433 this->updateFiltrationModelsPreStep(local_deferredLogger);
436 for (
auto& well : well_container_) {
437 well->closeCompletions(this->wellTestState());
443 if (alternative_well_rate_init_) {
448 for (
const auto& well : well_container_) {
449 if (well->isProducer() && !well->wellIsStopped()) {
450 well->initializeProducerWellState(simulator_, this->wellState(), local_deferredLogger);
455 for (
const auto& well : well_container_) {
456 if (well->isVFPActive(local_deferredLogger)){
457 well->setPrevSurfaceRates(this->wellState(), this->prevWellState());
461 this->updateWellPotentials(reportStepIdx,
463 simulator_.vanguard().summaryConfig(),
464 local_deferredLogger);
465 }
catch ( std::runtime_error& e ) {
466 const std::string msg =
"A zero well potential is returned for output purposes. ";
467 local_deferredLogger.
warning(
"WELL_POTENTIAL_CALCULATION_FAILED", msg);
469 this->guide_rate_handler_.setLogger(&local_deferredLogger);
471 this->guide_rate_handler_.updateGuideRates(
472 reportStepIdx, simulationTime, this->wellState(), this->groupState()
474#ifdef RESERVOIR_COUPLING_ENABLED
475 if (this->isReservoirCouplingSlave()) {
476 this->sendSlaveGroupDataToMaster();
482 if (this->schedule_[reportStepIdx].has_gpmaint()) {
483 for (
const auto& calculator : regionalAveragePressureCalculator_) {
484 calculator.second->template defineState<ElementContext>(simulator_);
486 const double dt = simulator_.timeStepSize();
487 const Group& fieldGroup = this->schedule().getGroup(
"FIELD", reportStepIdx);
488 this->groupStateHelper().updateGpMaintTargetForGroups(fieldGroup,
489 regionalAveragePressureCalculator_,
493 this->updateAndCommunicateGroupData(reportStepIdx,
494 simulator_.model().newtonMethod().numIterations(),
495 param_.nupcol_group_rate_tolerance_,
497 local_deferredLogger);
500 for (
auto& well : well_container_) {
501 const uint64_t effective_events_mask = ScheduleEvents::WELL_STATUS_CHANGE
502 + ScheduleEvents::INJECTION_TYPE_CHANGED
503 + ScheduleEvents::WELL_SWITCHED_INJECTOR_PRODUCER
504 + ScheduleEvents::NEW_WELL;
506 const auto& events = this->schedule()[reportStepIdx].wellgroup_events();
507 const bool event = this->report_step_starts_ && events.hasEvent(well->name(), effective_events_mask);
508 const bool dyn_status_change = this->wellState().well(well->name()).status
509 != this->prevWellState().well(well->name()).status;
511 if (event || dyn_status_change) {
513 well->scaleSegmentRatesAndPressure(this->wellState());
514 well->calculateExplicitQuantities(simulator_, this->groupStateHelper(), local_deferredLogger);
515 well->updateWellStateWithTarget(simulator_, this->groupStateHelper(), this->wellState(), local_deferredLogger);
516 well->updatePrimaryVariables(this->groupStateHelper(), local_deferredLogger);
517 well->solveWellEquation(
518 simulator_, this->groupStateHelper(), this->wellState(), local_deferredLogger
520 }
catch (
const std::exception& e) {
521 const std::string msg =
"Compute initial well solution for new well " + well->name() +
" failed. Continue with zero initial rates";
522 local_deferredLogger.
warning(
"WELL_INITIAL_SOLVE_FAILED", msg);
531 const std::string msg =
"Compute initial well solution for new wells failed. Continue with zero initial rates";
532 local_deferredLogger.
warning(
"WELL_INITIAL_SOLVE_FAILED", msg);
535 const auto& comm = simulator_.vanguard().grid().comm();
537 exc_type,
"beginTimeStep() failed: " + exc_msg, this->terminal_output_, comm);
541#ifdef RESERVOIR_COUPLING_ENABLED
551 template<
typename TypeTag>
552 std::optional<ReservoirCoupling::ScopedLoggerGuard>
555 if (this->isReservoirCouplingMaster()) {
557 this->reservoirCouplingMaster().getLogger(),
560 }
else if (this->isReservoirCouplingSlave()) {
561 return ReservoirCoupling::ScopedLoggerGuard{
562 this->reservoirCouplingSlave().getLogger(),
569 template<
typename TypeTag>
571 BlackoilWellModel<TypeTag>::
572 receiveSlaveGroupData()
574 assert(this->isReservoirCouplingMaster());
575 RescoupReceiveSlaveGroupData<Scalar, IndexTraits> slave_group_data_receiver{
576 this->groupStateHelper(),
578 slave_group_data_receiver.receiveSlaveGroupData();
581 template<
typename TypeTag>
583 BlackoilWellModel<TypeTag>::
584 sendSlaveGroupDataToMaster()
586 assert(this->isReservoirCouplingSlave());
587 RescoupSendSlaveGroupData<Scalar, IndexTraits> slave_group_data_sender{this->groupStateHelper()};
588 slave_group_data_sender.sendSlaveGroupDataToMaster();
592 template<
typename TypeTag>
595 const double simulationTime,
598 for (
const std::string& well_name : this->getWellsForTesting(timeStepIdx, simulationTime)) {
599 const Well& wellEcl = this->schedule().getWell(well_name, timeStepIdx);
600 if (wellEcl.getStatus() == Well::Status::SHUT)
603 WellInterfacePtr well = createWellForWellTest(well_name, timeStepIdx, deferred_logger);
605 well->init(depth_, gravity_, B_avg_,
true);
607 Scalar well_efficiency_factor = wellEcl.getEfficiencyFactor() *
608 this->wellState().getGlobalEfficiencyScalingFactor(well_name);
609 this->groupStateHelper().accumulateGroupEfficiencyFactor(
610 this->schedule().getGroup(wellEcl.groupName(), timeStepIdx),
611 well_efficiency_factor
614 well->setWellEfficiencyFactor(well_efficiency_factor);
615 well->setVFPProperties(this->vfp_properties_.get());
616 well->setGuideRate(&this->guideRate_);
619 if (well->isProducer() && alternative_well_rate_init_) {
620 well->initializeProducerWellState(simulator_, this->wellState(), deferred_logger);
622 if (well->isVFPActive(deferred_logger)) {
623 well->setPrevSurfaceRates(this->wellState(), this->prevWellState());
626 const auto& network = this->schedule()[timeStepIdx].network();
627 if (network.active()) {
628 this->network_.initializeWell(*well);
632 GLiftEclWells ecl_well_map;
633 gaslift_.initGliftEclWellMap(well_container_, ecl_well_map);
634 well->wellTesting(simulator_,
636 this->groupStateHelper(),
638 this->wellTestState(),
640 this->well_open_times_,
642 }
catch (
const std::exception& e) {
643 const std::string msg = fmt::format(
"Exception during testing of well: {}. The well will not open.\n Exception message: {}", wellEcl.name(), e.what());
644 deferred_logger.
warning(
"WELL_TESTING_FAILED", msg);
654 template<
typename TypeTag>
660 for (
auto&& pinfo : this->local_parallel_well_info_)
671 template<
typename TypeTag>
681 template<
typename TypeTag>
686 this->closed_this_step_.clear();
689 this->report_step_starts_ =
false;
690 const int reportStepIdx = simulator_.episodeIndex();
693 for (
const auto& well : well_container_) {
694 if (getPropValue<TypeTag, Properties::EnablePolymerMW>() && well->isInjector()) {
695 well->updateWaterThroughput(dt, this->wellState());
699 for (
const auto& well : well_container_) {
700 well->updateConnectionTransmissibilityFactor(simulator_, this->wellState().well(well->indexOfWell()));
701 well->updateConnectionDFactor(simulator_, this->wellState().well(well->indexOfWell()));
704 if (Indices::waterEnabled) {
705 this->updateFiltrationModelsPostStep(dt, FluidSystem::waterPhaseIdx, local_deferredLogger);
709 this->updateInjMult(local_deferredLogger);
712 for (
const auto& well : well_container_) {
713 well->reportWellSwitching(this->wellState().well(well->indexOfWell()), local_deferredLogger);
716 if (this->terminal_output_) {
717 this->reportGroupSwitching(local_deferredLogger);
721 rateConverter_->template defineState<ElementContext>(simulator_);
725 this->updateWellPotentials(reportStepIdx,
727 simulator_.vanguard().summaryConfig(),
728 local_deferredLogger);
729 }
catch ( std::runtime_error& e ) {
730 const std::string msg =
"A zero well potential is returned for output purposes. ";
731 local_deferredLogger.
warning(
"WELL_POTENTIAL_CALCULATION_FAILED", msg);
734 updateWellTestState(simulationTime, this->wellTestState());
737 const Group& fieldGroup = this->schedule_.getGroup(
"FIELD", reportStepIdx);
738 this->checkGEconLimits(fieldGroup, simulationTime,
739 simulator_.episodeIndex(), local_deferredLogger);
740 this->checkGconsaleLimits(fieldGroup, this->wellState(),
741 simulator_.episodeIndex(), local_deferredLogger);
743 this->calculateProductivityIndexValues(local_deferredLogger);
745 this->commitWGState();
749 if (this->terminal_output_) {
754 this->computeWellTemperature();
758 template<
typename TypeTag>
762 unsigned elemIdx)
const
766 if (!is_cell_perforated_[elemIdx] || cellRates_.count(elemIdx) == 0) {
770 rate = cellRates_.at(elemIdx);
774 template<
typename TypeTag>
775 template <
class Context>
779 const Context& context,
781 unsigned timeIdx)
const
784 int elemIdx = context.globalSpaceIndex(spaceIdx, timeIdx);
786 if (!is_cell_perforated_[elemIdx] || cellRates_.count(elemIdx) == 0) {
790 rate = cellRates_.at(elemIdx);
795 template<
typename TypeTag>
800 const auto pressIx = []()
802 if (Indices::oilEnabled) {
return FluidSystem::oilPhaseIdx; }
803 if (Indices::waterEnabled) {
return FluidSystem::waterPhaseIdx; }
805 return FluidSystem::gasPhaseIdx;
808 auto cellPressures = std::vector<Scalar>(this->local_num_cells_,
Scalar{0});
809 auto cellTemperatures = std::vector<Scalar>(this->local_num_cells_,
Scalar{0});
812 const auto& gridView = this->simulator_.vanguard().gridView();
815 for (
const auto& elem : elements(gridView, Dune::Partitions::interior)) {
816 elemCtx.updatePrimaryStencil(elem);
817 elemCtx.updatePrimaryIntensiveQuantities(0);
819 const auto ix = elemCtx.globalSpaceIndex(0, 0);
820 const auto& fs = elemCtx.intensiveQuantities(0, 0).fluidState();
822 cellPressures[ix] = fs.pressure(pressIx).value();
823 cellTemperatures[ix] = fs.temperature(0).value();
826 this->simulator_.vanguard().grid().comm());
828 this->wellState().init(cellPressures, cellTemperatures, this->schedule(), this->wells_ecl_,
829 this->local_parallel_well_info_, timeStepIdx,
830 &this->prevWellState(), this->well_perf_data_,
831 this->summaryState(), simulator_.vanguard().enableDistributedWells());
838 template<
typename TypeTag>
845 const int nw = this->numLocalWells();
847 well_container_.clear();
850 well_container_.reserve(nw);
852 const auto& wmatcher = this->schedule().wellMatcher(report_step);
853 const auto& wcycle = this->schedule()[report_step].wcycle.get();
857 std::for_each(this->wells_ecl_.begin(), this->wells_ecl_.end(),
858 [
this, &wg_events = this->report_step_start_events_](
const auto& well_ecl)
860 if (!well_ecl.hasConnections()) {
865 constexpr auto events_mask = ScheduleEvents::WELL_STATUS_CHANGE |
866 ScheduleEvents::REQUEST_OPEN_WELL |
867 ScheduleEvents::REQUEST_SHUT_WELL;
868 const bool well_event =
869 this->report_step_starts_ &&
870 wg_events.hasEvent(well_ecl.name(), events_mask);
879 if (well_ecl.getStatus() == WellStatus::OPEN) {
880 this->well_open_times_.insert_or_assign(well_ecl.name(),
881 this->simulator_.time());
882 this->well_close_times_.erase(well_ecl.name());
883 }
else if (well_ecl.getStatus() == WellStatus::SHUT) {
884 this->well_close_times_.insert_or_assign(well_ecl.name(),
885 this->simulator_.time());
886 this->well_open_times_.erase(well_ecl.name());
892 const auto cycle_states = wcycle.wellStatus(this->simulator_.time(),
894 this->well_open_times_,
895 this->well_close_times_);
897 for (
int w = 0; w < nw; ++w) {
898 const Well& well_ecl = this->wells_ecl_[w];
900 if (!well_ecl.hasConnections()) {
905 const std::string& well_name = well_ecl.name();
906 const auto well_status = this->schedule()
907 .getWell(well_name, report_step).getStatus();
909 const bool shut_event = this->wellState().well(w).events.hasEvent(ScheduleEvents::WELL_STATUS_CHANGE)
910 && well_status == Well::Status::SHUT;
911 const bool open_event = this->wellState().well(w).events.hasEvent(ScheduleEvents::WELL_STATUS_CHANGE)
912 && well_status == Well::Status::OPEN;
913 const auto& ws = this->wellState().well(well_name);
915 if (shut_event && ws.status != Well::Status::SHUT) {
916 this->closed_this_step_.insert(well_name);
917 this->wellState().shutWell(w);
918 }
else if (open_event && ws.status != Well::Status::OPEN) {
919 this->wellState().openWell(w);
923 if (this->wellTestState().well_is_closed(well_name)) {
928 const bool closed_this_step = (this->wellTestState().lastTestTime(well_name) == simulator_.time());
931 auto& events = this->wellState().well(w).events;
932 if (events.hasEvent(ScheduleEvents::REQUEST_OPEN_WELL)) {
933 if (!closed_this_step) {
934 this->wellTestState().open_well(well_name);
935 this->wellTestState().open_completions(well_name);
936 this->well_open_times_.insert_or_assign(well_name,
937 this->simulator_.time());
938 this->well_close_times_.erase(well_name);
940 events.clearEvent(ScheduleEvents::REQUEST_OPEN_WELL);
946 if (this->wellTestState().well_is_closed(well_name))
948 if (well_ecl.getAutomaticShutIn()) {
950 this->wellState().shutWell(w);
951 this->well_close_times_.erase(well_name);
952 this->well_open_times_.erase(well_name);
955 if (!well_ecl.getAllowCrossFlow()) {
958 this->wellState().shutWell(w);
959 this->well_close_times_.erase(well_name);
960 this->well_open_times_.erase(well_name);
964 this->wellState().stopWell(w);
969 if (!well_ecl.getAllowCrossFlow()) {
970 const bool any_zero_rate_constraint = well_ecl.isProducer()
971 ? well_ecl.productionControls(this->summaryState_).anyZeroRateConstraint()
972 : well_ecl.injectionControls(this->summaryState_).anyZeroRateConstraint();
973 if (any_zero_rate_constraint) {
975 local_deferredLogger.
debug(fmt::format(
" Well {} gets shut due to having zero rate constraint and disallowing crossflow ", well_ecl.name()) );
976 this->wellState().shutWell(w);
977 this->well_close_times_.erase(well_name);
978 this->well_open_times_.erase(well_name);
983 if (!wcycle.empty()) {
984 const auto it = cycle_states.find(well_name);
985 if (it != cycle_states.end()) {
986 if (!it->second || well_status == Well::Status::SHUT) {
988 if (well_status == Well::Status::SHUT) {
989 this->well_open_times_.erase(well_name);
990 this->well_close_times_.erase(well_name);
992 this->wellState().shutWell(w);
995 this->wellState().openWell(w);
1001 if (ws.status == Well::Status::SHUT) {
1005 well_container_.emplace_back(this->createWellPointer(w, report_step));
1007 if (ws.status == Well::Status::STOP) {
1008 well_container_.back()->stopWell();
1009 this->well_close_times_.erase(well_name);
1010 this->well_open_times_.erase(well_name);
1014 if (!wcycle.empty()) {
1015 const auto schedule_open =
1016 [&wg_events = this->report_step_start_events_](
const std::string& name)
1018 return wg_events.hasEvent(name, ScheduleEvents::REQUEST_OPEN_WELL);
1020 for (
const auto& [wname, wscale] : wcycle.efficiencyScale(this->simulator_.time(),
1021 this->simulator_.timeStepSize(),
1023 this->well_open_times_,
1026 this->wellState().updateEfficiencyScalingFactor(wname, wscale);
1027 this->schedule_.add_event(ScheduleEvents::WELLGROUP_EFFICIENCY_UPDATE, report_step);
1036 if (this->terminal_output_) {
1040 this->well_container_generic_.clear();
1041 for (
auto& w : well_container_) {
1042 this->well_container_generic_.push_back(w.get());
1045 this->network_.initialize(report_step);
1047 this->wbp_.registerOpenWellsForWBPCalculation();
1054 template <
typename TypeTag>
1055 typename BlackoilWellModel<TypeTag>::WellInterfacePtr
1059 const auto is_multiseg = this->wells_ecl_[wellID].isMultiSegment();
1061 if (! (this->param_.use_multisegment_well_ && is_multiseg)) {
1062 return this->
template createTypedWellPointer<StandardWell<TypeTag>>(wellID, report_step);
1065 return this->
template createTypedWellPointer<MultisegmentWell<TypeTag>>(wellID, report_step);
1073 template <
typename TypeTag>
1074 template <
typename WellType>
1075 std::unique_ptr<WellType>
1080 const auto& perf_data = this->well_perf_data_[wellID];
1083 const auto pvtreg = perf_data.
empty()
1084 ? 0 : this->pvt_region_idx_[perf_data.front().cell_index];
1086 const auto& parallel_well_info = this->local_parallel_well_info_[wellID].get();
1087 const auto global_pvtreg = parallel_well_info.broadcastFirstPerforationValue(pvtreg);
1089 return std::make_unique<WellType>(this->wells_ecl_[wellID],
1093 *this->rateConverter_,
1095 this->numConservationQuantities(),
1105 template<
typename TypeTag>
1109 const int report_step,
1113 const auto it = std::find_if(this->wells_ecl_.begin(),
1114 this->wells_ecl_.end(),
1115 [&well_name](
const auto& w)
1116 { return well_name == w.name(); });
1118 if (it == this->wells_ecl_.end()) {
1120 fmt::format(
"Could not find well {} in wells_ecl ", well_name),
1124 const int pos =
static_cast<int>(std::distance(this->wells_ecl_.begin(), it));
1125 return this->createWellPointer(pos, report_step);
1130 template<
typename TypeTag>
1139 this->guide_rate_handler_.setLogger(&local_deferredLogger);
1141 if (gaslift_.terminalOutput()) {
1142 const std::string msg =
1143 fmt::format(
"assemble() : iteration {}" , iterationIdx);
1144 gaslift_.gliftDebug(msg, local_deferredLogger);
1148 Dune::Timer perfTimer;
1150 this->closed_offending_wells_.clear();
1153 const int episodeIdx = simulator_.episodeIndex();
1154 const auto& network = this->schedule()[episodeIdx].network();
1155 if (!this->wellsActive() && !network.active()) {
1160 if (iterationIdx == 0 && this->wellsActive()) {
1161 OPM_TIMEBLOCK(firstIterationAssmble);
1168 calculateExplicitQuantities(local_deferredLogger);
1169 prepareTimeStep(local_deferredLogger);
1172 "assemble() failed (It=0): ",
1173 this->terminal_output_, grid().comm());
1176 const bool well_group_control_changed = updateWellControlsAndNetwork(
false, dt, local_deferredLogger);
1180 if ( ! this->wellsActive() ) {
1184 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 network_needs_more_balancing_force_another_newton_iteration_ =
false;
1215 while (do_network_update) {
1216 if (network_update_iteration >= max_iteration ) {
1218 const int episodeIdx = simulator_.episodeIndex();
1219 const int iterationIdx = simulator_.model().newtonMethod().numIterations();
1220 if (this->network_.shouldBalance(episodeIdx, iterationIdx + 1)) {
1221 if (this->terminal_output_) {
1222 const std::string msg = fmt::format(
"Maximum of {:d} network iterations has been used and we stop the update, \n"
1223 "and try again after the next Newton iteration (imbalance = {:.2e} bar, ctrl_change = {})",
1224 max_iteration, network_imbalance*1.0e-5, well_group_control_changed);
1225 local_deferredLogger.
debug(msg);
1229 network_needs_more_balancing_force_another_newton_iteration_ =
true;
1231 if (this->terminal_output_) {
1232 const std::string msg = fmt::format(
"Maximum of {:d} network iterations has been used and we stop the update. \n"
1233 "The simulator will continue with unconverged network results (imbalance = {:.2e} bar, ctrl_change = {})",
1234 max_iteration, network_imbalance*1.0e-5, well_group_control_changed);
1235 local_deferredLogger.
info(msg);
1240 if (this->terminal_output_ && (network_update_iteration == iteration_to_relax) ) {
1241 local_deferredLogger.
debug(
"We begin using relaxed tolerance for network update now after " +
std::to_string(iteration_to_relax) +
" iterations ");
1243 const bool relax_network_balance = network_update_iteration >= iteration_to_relax;
1245 const bool optimize_gas_lift = ( (network_update_iteration + 1) < std::max(max_iteration,
static_cast<std::size_t
>(2)) );
1246 std::tie(well_group_control_changed, do_network_update, network_imbalance) =
1247 updateWellControlsAndNetworkIteration(mandatory_network_balance, relax_network_balance, optimize_gas_lift, dt,local_deferredLogger);
1248 ++network_update_iteration;
1250 return well_group_control_changed;
1256 template<
typename TypeTag>
1257 std::tuple<bool, bool, typename BlackoilWellModel<TypeTag>::Scalar>
1260 const bool relax_network_tolerance,
1261 const bool optimize_gas_lift,
1266 const int iterationIdx = simulator_.model().newtonMethod().numIterations();
1267 const int reportStepIdx = simulator_.episodeIndex();
1268 this->updateAndCommunicateGroupData(reportStepIdx, iterationIdx,
1269 param_.nupcol_group_rate_tolerance_,
true, local_deferredLogger);
1274 bool well_group_control_changed = updateWellControls(local_deferredLogger);
1275 const auto [more_inner_network_update, network_imbalance] =
1276 this->network_.update(mandatory_network_balance,
1277 local_deferredLogger,
1278 relax_network_tolerance);
1280 bool alq_updated =
false;
1283 if (optimize_gas_lift) {
1286 const bool updatePotentials = (this->network_.shouldBalance(reportStepIdx, iterationIdx) ||
1287 mandatory_network_balance);
1288 alq_updated = gaslift_.maybeDoGasLiftOptimize(simulator_,
1290 this->network_.nodePressures(),
1294 local_deferredLogger);
1296 prepareWellsBeforeAssembling(dt, local_deferredLogger);
1299 "updateWellControlsAndNetworkIteration() failed: ",
1300 this->terminal_output_, grid().comm());
1304 guideRateUpdateIsNeeded(reportStepIdx)) {
1305 const double simulationTime = simulator_.time();
1309 this->guide_rate_handler_.updateGuideRates(
1310 reportStepIdx, simulationTime, this->wellState(), this->groupState()
1315 const bool more_network_update = this->network_.shouldBalance(reportStepIdx, iterationIdx) &&
1316 (more_inner_network_update || well_group_control_changed || alq_updated);
1317 return {well_group_control_changed, more_network_update, network_imbalance};
1320 template<
typename TypeTag>
1326 for (
auto& well : well_container_) {
1327 well->assembleWellEq(simulator_, dt, this->groupStateHelper(), deferred_logger);
1332 template<
typename TypeTag>
1338 for (
auto& well : well_container_) {
1339 well->prepareWellBeforeAssembling(
1340 simulator_, dt, this->groupStateHelper(), this->wellState(), deferred_logger
1346 template<
typename TypeTag>
1356 for (
auto& well: well_container_) {
1357 well->assembleWellEqWithoutIteration(simulator_, this->groupStateHelper(), dt, this->wellState(),
1362 this->terminal_output_, grid().comm());
1366 template<
typename TypeTag>
1373 for (
const auto& well : well_container_) {
1374 well->addCellRates(cellRates_);
1378 template<
typename TypeTag>
1385 for (
const auto& well : well_container_) {
1386 const auto it = well_domain_map.find(well->name());
1387 if (it != well_domain_map.end() && it->second == domainIndex) {
1388 well->addCellRates(cellRates_);
1393#if COMPILE_GPU_BRIDGE
1394 template<
typename TypeTag>
1402 for(
unsigned int i = 0; i < well_container_.size(); i++){
1403 auto& well = well_container_[i];
1406 wellContribs.
addNumBlocks(derived->linSys().getNumBlocks());
1411 wellContribs.
alloc();
1413 for(
unsigned int i = 0; i < well_container_.size(); i++){
1414 auto& well = well_container_[i];
1416 auto derived_std =
dynamic_cast<StandardWell<TypeTag>*
>(well.get());
1418 derived_std->linSys().extract(derived_std->numStaticWellEq, wellContribs);
1420 auto derived_ms =
dynamic_cast<MultisegmentWell<TypeTag>*
>(well.get());
1422 derived_ms->linSys().extract(wellContribs);
1424 OpmLog::warning(
"Warning unknown type of well");
1431 template<
typename TypeTag>
1436 for (
const auto& well: well_container_ ) {
1441 template<
typename TypeTag>
1446 const bool use_well_weights)
const
1448 int nw = this->numLocalWellsEnd();
1449 int rdofs = local_num_cells_;
1450 for (
int i = 0; i < nw; i++ ) {
1451 int wdof = rdofs + i;
1452 jacobian[wdof][wdof] = 1.0;
1455 for (
const auto& well : well_container_) {
1456 well->addWellPressureEquations(jacobian,
1464 template <
typename TypeTag>
1467 const std::vector<typename SparseMatrixAdapter::MatrixBlock*>& diagMatAddress)
const
1472 for (
const auto& well : well_container_) {
1473 if (!well->isOperableAndSolvable() && !well->wellIsStopped()) {
1476 const auto& cells = well->cells();
1477 const auto& rates = well->connectionRates();
1478 for (
unsigned perfIdx = 0; perfIdx < rates.size(); ++perfIdx) {
1479 unsigned cellIdx = cells[perfIdx];
1480 auto rate = rates[perfIdx];
1483 using MatrixBlockType =
typename SparseMatrixAdapter::MatrixBlock;
1484 MatrixBlockType bMat(0.0);
1485 simulator_.model().linearizer().setResAndJacobi(res, bMat, rate);
1486 residual[cellIdx] += res;
1487 *diagMatAddress[cellIdx] += bMat;
1493 template<
typename TypeTag>
1498 int nw = this->numLocalWellsEnd();
1499 int rdofs = local_num_cells_;
1500 for (
int i = 0; i < nw; ++i) {
1501 int wdof = rdofs + i;
1502 jacobian.entry(wdof,wdof) = 1.0;
1504 const auto wellconnections = this->getMaxWellConnections();
1505 for (
int i = 0; i < nw; ++i) {
1506 const auto& perfcells = wellconnections[i];
1507 for (
int perfcell : perfcells) {
1508 int wdof = rdofs + i;
1509 jacobian.entry(wdof, perfcell) = 0.0;
1510 jacobian.entry(perfcell, wdof) = 0.0;
1516 template<
typename TypeTag>
1524 for (
const auto& well : well_container_) {
1525 const auto& cells = well->cells();
1526 x_local_.resize(cells.size());
1528 for (
size_t i = 0; i < cells.size(); ++i) {
1529 x_local_[i] = x[cells[i]];
1531 well->recoverWellSolutionAndUpdateWellState(simulator_, x_local_,
1532 this->groupStateHelper(), this->wellState(), local_deferredLogger);
1536 "recoverWellSolutionAndUpdateWellState() failed: ",
1537 this->terminal_output_, simulator_.vanguard().grid().comm());
1541 template<
typename TypeTag>
1547 OPM_THROW(std::logic_error,
"Attempt to call NLDD method without a NLDD solver");
1550 return nldd_->recoverWellSolutionAndUpdateWellState(x, domainIdx);
1554 template<
typename TypeTag>
1557 getWellConvergence(
const std::vector<Scalar>& B_avg,
bool checkWellGroupControlsAndNetwork)
const
1563 const int iterationIdx = simulator_.model().newtonMethod().numIterations();
1564 for (
const auto& well : well_container_) {
1565 if (well->isOperableAndSolvable() || well->wellIsStopped()) {
1566 local_report += well->getWellConvergence(
1567 this->groupStateHelper(), B_avg, local_deferredLogger,
1568 iterationIdx > param_.strict_outer_iter_wells_);
1572 report.
setWellFailed({CR::WellFailure::Type::Unsolvable, CR::Severity::Normal, -1, well->name()});
1573 local_report += report;
1581 if (checkWellGroupControlsAndNetwork) {
1587 if (this->terminal_output_) {
1592 if (f.severity() == ConvergenceReport::Severity::NotANumber) {
1593 OpmLog::debug(
"NaN residual found with phase " +
std::to_string(f.phase()) +
" for well " + f.wellName());
1594 }
else if (f.severity() == ConvergenceReport::Severity::TooLarge) {
1595 OpmLog::debug(
"Too large residual found with phase " +
std::to_string(f.phase()) +
" for well " + f.wellName());
1606 template<
typename TypeTag>
1612 for (
auto& well : well_container_) {
1621 template<
typename TypeTag>
1627 if (!this->wellsActive()) {
1630 const int episodeIdx = simulator_.episodeIndex();
1631 const int iterationIdx = simulator_.model().newtonMethod().numIterations();
1632 const auto& comm = simulator_.vanguard().grid().comm();
1634 bool changed_well_group =
false;
1635 const Group& fieldGroup = this->schedule().getGroup(
"FIELD", episodeIdx);
1638 const std::size_t max_iter = param_.well_group_constraints_max_iterations_;
1639 while(!changed_well_group && iter < max_iter) {
1640 changed_well_group = updateGroupControls(fieldGroup, deferred_logger, episodeIdx, iterationIdx);
1643 bool changed_well_to_group =
false;
1645 OPM_TIMEBLOCK(UpdateWellControls);
1649 for (
const auto& well : well_container_) {
1652 simulator_, mode, this->groupStateHelper(), this->wellState(), deferred_logger
1655 changed_well_to_group = changed_well || changed_well_to_group;
1659 simulator_.gridView().comm());
1662 changed_well_to_group = comm.sum(
static_cast<int>(changed_well_to_group));
1663 if (changed_well_to_group) {
1664 updateAndCommunicate(episodeIdx, iterationIdx, deferred_logger);
1665 changed_well_group =
true;
1669 bool changed_well_individual =
false;
1674 for (
const auto& well : well_container_) {
1677 simulator_, mode, this->groupStateHelper(), this->wellState(), deferred_logger
1680 changed_well_individual = changed_well || changed_well_individual;
1684 simulator_.gridView().comm());
1687 changed_well_individual = comm.sum(
static_cast<int>(changed_well_individual));
1688 if (changed_well_individual) {
1689 updateAndCommunicate(episodeIdx, iterationIdx, deferred_logger);
1690 changed_well_group =
true;
1696 this->updateWsolvent(fieldGroup, episodeIdx, this->nupcolWellState());
1698 return changed_well_group;
1702 template<
typename TypeTag>
1706 const int iterationIdx,
1709 this->updateAndCommunicateGroupData(reportStepIdx,
1711 param_.nupcol_group_rate_tolerance_,
1719 for (
const auto& well : well_container_) {
1721 const auto& ws = this->wellState().well(well->indexOfWell());
1722 if (ws.production_cmode == Well::ProducerCMode::GRUP ||
1723 ws.injection_cmode == Well::InjectorCMode::GRUP)
1725 well->updateWellStateWithTarget(
1726 simulator_, this->groupStateHelper(), this->wellState(), deferred_logger
1731 simulator_.gridView().comm())
1732 this->updateAndCommunicateGroupData(reportStepIdx,
1734 param_.nupcol_group_rate_tolerance_,
1739 template<
typename TypeTag>
1744 const int reportStepIdx,
1745 const int iterationIdx)
1748 bool changed =
false;
1750 const int nupcol = this->schedule()[reportStepIdx].nupcol();
1751 const int max_number_of_group_switches = param_.max_number_of_group_switches_;
1752 const bool update_group_switching_log = iterationIdx >= nupcol;
1753 const bool changed_hc = this->checkGroupHigherConstraints(group, deferred_logger, reportStepIdx, max_number_of_group_switches, update_group_switching_log);
1756 updateAndCommunicate(reportStepIdx, iterationIdx, deferred_logger);
1759 bool changed_individual =
1761 updateGroupIndividualControl(group,
1763 max_number_of_group_switches,
1764 update_group_switching_log,
1765 this->switched_inj_groups_,
1766 this->switched_prod_groups_,
1767 this->closed_offending_wells_,
1772 if (changed_individual) {
1774 updateAndCommunicate(reportStepIdx, iterationIdx, deferred_logger);
1777 for (
const std::string& groupName : group.groups()) {
1778 bool changed_this = updateGroupControls( this->schedule().getGroup(groupName, reportStepIdx), deferred_logger, reportStepIdx,iterationIdx);
1779 changed = changed || changed_this;
1784 template<
typename TypeTag>
1791 for (
const auto& well : well_container_) {
1792 const auto& wname = well->name();
1793 const auto wasClosed = wellTestState.well_is_closed(wname);
1794 well->checkWellOperability(simulator_,
1796 this->groupStateHelper(),
1797 local_deferredLogger);
1798 const bool under_zero_target =
1799 well->wellUnderZeroGroupRateTarget(this->groupStateHelper(), local_deferredLogger);
1800 well->updateWellTestState(this->wellState().well(wname),
1805 local_deferredLogger);
1807 if (!wasClosed && wellTestState.well_is_closed(wname)) {
1808 this->closed_this_step_.insert(wname);
1811 const WellEconProductionLimits& econ_production_limits = well->wellEcl().getEconLimits();
1812 if (econ_production_limits.validFollowonWell()) {
1813 const auto episode_idx = simulator_.episodeIndex();
1814 const auto follow_on_well = econ_production_limits.followonWell();
1815 if (!this->schedule().hasWell(follow_on_well, episode_idx)) {
1816 const auto msg = fmt::format(
"Well {} was closed. But the given follow on well {} does not exist."
1817 "The simulator continues without opening a follow on well.",
1818 wname, follow_on_well);
1819 local_deferredLogger.
warning(msg);
1821 auto& ws = this->wellState().well(follow_on_well);
1822 const bool success = ws.updateStatus(WellStatus::OPEN);
1824 const auto msg = fmt::format(
"Well {} was closed. The follow on well {} opens instead.", wname, follow_on_well);
1825 local_deferredLogger.
info(msg);
1827 const auto msg = fmt::format(
"Well {} was closed. The follow on well {} is already open.", wname, follow_on_well);
1828 local_deferredLogger.
warning(msg);
1835 for (
const auto& [group_name, to] : this->closed_offending_wells_) {
1836 if (this->hasOpenLocalWell(to.second) &&
1837 !this->wasDynamicallyShutThisTimeStep(to.second))
1839 wellTestState.close_well(to.second,
1840 WellTestConfig::Reason::GROUP,
1842 this->updateClosedWellsThisStep(to.second);
1843 const std::string msg =
1844 fmt::format(
"Procedure on exceeding {} limit is WELL for group {}. "
1850 local_deferredLogger.
info(msg);
1858 if (this->terminal_output_) {
1864 template<
typename TypeTag>
1868 std::string& exc_msg,
1873 const int np = this->numPhases();
1874 std::vector<Scalar> potentials;
1875 const auto& well = well_container_[widx];
1876 std::string cur_exc_msg;
1879 well->computeWellPotentials(simulator_, well_state_copy, this->groupStateHelper(), potentials, deferred_logger);
1884 exc_msg += fmt::format(
"\nFor well {}: {}", well->name(), cur_exc_msg);
1886 exc_type = std::max(exc_type, cur_exc_type);
1890 auto& ws = this->wellState().well(well->indexOfWell());
1891 for (
int p = 0; p < np; ++p) {
1893 ws.well_potentials[p] = std::max(
Scalar{0.0}, potentials[p]);
1899 template <
typename TypeTag>
1904 for (
const auto& wellPtr : this->well_container_) {
1905 this->calculateProductivityIndexValues(wellPtr.get(), deferred_logger);
1913 template <
typename TypeTag>
1924 for (
const auto& shutWell : this->local_shut_wells_) {
1925 if (!this->wells_ecl_[shutWell].hasConnections()) {
1930 auto wellPtr = this->
template createTypedWellPointer
1933 wellPtr->
init(this->depth_, this->gravity_, this->B_avg_,
true);
1935 this->calculateProductivityIndexValues(wellPtr.get(), deferred_logger);
1943 template <
typename TypeTag>
1957 template<
typename TypeTag>
1963 const auto episodeIdx = simulator_.episodeIndex();
1964 this->network_.updateActiveState(episodeIdx);
1968 const bool do_prestep_network_rebalance =
1969 param_.pre_solve_network_ && this->network_.needPreStepRebalance(episodeIdx);
1971 for (
const auto& well : well_container_) {
1972 auto& events = this->wellState().well(well->indexOfWell()).events;
1974 well->updateWellStateWithTarget(
1975 simulator_, this->groupStateHelper(), this->wellState(), deferred_logger
1983 if (events.hasEvent(ScheduleEvents::REQUEST_OPEN_WELL)) {
1984 events.clearEvent(ScheduleEvents::REQUEST_OPEN_WELL);
1987 if (param_.solve_welleq_initially_ && well->isOperableAndSolvable()) {
1989 well->solveWellEquation(
1990 simulator_, this->groupStateHelper(), this->wellState(), deferred_logger
1992 }
catch (
const std::exception& e) {
1993 const std::string msg =
"Compute initial well solution for " + well->name() +
" initially failed. Continue with the previous rates";
1994 deferred_logger.
warning(
"WELL_INITIAL_SOLVE_FAILED", msg);
1999 well->resetWellOperability();
2001 updatePrimaryVariables(deferred_logger);
2004 if (do_prestep_network_rebalance) {
2005 network_.doPreStepRebalance(deferred_logger);
2009 template<
typename TypeTag>
2014 std::vector< Scalar > B_avg(numConservationQuantities(),
Scalar() );
2015 const auto& grid = simulator_.vanguard().grid();
2016 const auto& gridView = grid.leafGridView();
2020 for (
const auto& elem : elements(gridView, Dune::Partitions::interior)) {
2021 elemCtx.updatePrimaryStencil(elem);
2022 elemCtx.updatePrimaryIntensiveQuantities(0);
2024 const auto& intQuants = elemCtx.intensiveQuantities(0, 0);
2025 const auto& fs = intQuants.fluidState();
2027 for (
unsigned phaseIdx = 0; phaseIdx < FluidSystem::numPhases; ++phaseIdx)
2029 if (!FluidSystem::phaseIsActive(phaseIdx)) {
2033 const unsigned compIdx = FluidSystem::canonicalToActiveCompIdx(FluidSystem::solventComponentIndex(phaseIdx));
2034 auto& B = B_avg[ compIdx ];
2036 B += 1 / fs.invB(phaseIdx).value();
2038 if constexpr (has_solvent_) {
2039 auto& B = B_avg[solventSaturationIdx];
2040 B += 1 / intQuants.solventInverseFormationVolumeFactor().value();
2046 grid.comm().sum(B_avg.data(), B_avg.size());
2047 B_avg_.resize(B_avg.size());
2048 std::transform(B_avg.begin(), B_avg.end(), B_avg_.begin(),
2049 [gcells = global_num_cells_](
const auto bval)
2050 { return bval / gcells; });
2057 template<
typename TypeTag>
2062 for (
const auto& well : well_container_) {
2067 template<
typename TypeTag>
2071 const auto& grid = simulator_.vanguard().
grid();
2072 const auto& eclProblem = simulator_.problem();
2073 const unsigned numCells = grid.size(0);
2075 this->pvt_region_idx_.resize(numCells);
2076 for (
unsigned cellIdx = 0; cellIdx < numCells; ++cellIdx) {
2077 this->pvt_region_idx_[cellIdx] =
2078 eclProblem.pvtRegionIndex(cellIdx);
2083 template<
typename TypeTag>
2096 return this->numPhases() + has_solvent_;
2099 template<
typename TypeTag>
2103 const auto& eclProblem = simulator_.problem();
2104 depth_.resize(local_num_cells_);
2105 for (
unsigned cellIdx = 0; cellIdx < local_num_cells_; ++cellIdx) {
2106 depth_[cellIdx] = eclProblem.dofCenterDepth(cellIdx);
2110 template<
typename TypeTag>
2113 getWell(
const std::string& well_name)
const
2116 auto well = std::find_if(well_container_.begin(),
2117 well_container_.end(),
2119 return elem->name() == well_name;
2122 assert(well != well_container_.end());
2127 template <
typename TypeTag>
2132 return std::max(this->simulator_.episodeIndex(), 0);
2139 template<
typename TypeTag>
2144 const std::vector<Scalar>& production_rates,
2145 std::vector<Scalar>& resv_coeff)
2147 rateConverter_->calcCoeff(fipnum, pvtreg, production_rates, resv_coeff);
2150 template<
typename TypeTag>
2155 std::vector<Scalar>& resv_coeff)
2157 rateConverter_->calcInjCoeff(fipnum, pvtreg, resv_coeff);
2161 template <
typename TypeTag>
2166 if constexpr (energyModuleType_ == EnergyModules::FullyImplicitThermal ||
2167 energyModuleType_ == EnergyModules::SequentialImplicitThermal) {
2168 int np = this->numPhases();
2169 Scalar cellInternalEnergy;
2173 const int nw = this->numLocalWells();
2174 for (
auto wellID = 0*nw; wellID < nw; ++wellID) {
2175 const Well& well = this->wells_ecl_[wellID];
2176 auto& ws = this->wellState().well(wellID);
2177 if (well.isInjector()) {
2178 if (ws.status != WellStatus::STOP) {
2179 this->wellState().well(wellID).temperature = well.inj_temperature();
2184 std::array<Scalar,2> weighted{0.0,0.0};
2185 auto& [weighted_temperature, total_weight] = weighted;
2187 auto& well_info = this->local_parallel_well_info_[wellID].get();
2188 auto& perf_data = ws.perf_data;
2189 auto& perf_phase_rate = perf_data.phase_rates;
2191 using int_type =
decltype(this->well_perf_data_[wellID].size());
2192 for (int_type perf = 0, end_perf = this->well_perf_data_[wellID].size(); perf < end_perf; ++perf) {
2193 const int cell_idx = this->well_perf_data_[wellID][perf].cell_index;
2194 const auto& intQuants = simulator_.model().intensiveQuantities(cell_idx, 0);
2195 const auto& fs = intQuants.fluidState();
2198 Scalar cellTemperatures = fs.temperature(0).value();
2200 Scalar weight_factor = 0.0;
2201 for (
unsigned phaseIdx = 0; phaseIdx < FluidSystem::numPhases; ++phaseIdx) {
2202 if (!FluidSystem::phaseIsActive(phaseIdx)) {
2205 cellInternalEnergy = fs.enthalpy(phaseIdx).value() -
2206 fs.pressure(phaseIdx).value() / fs.density(phaseIdx).value();
2207 cellBinv = fs.invB(phaseIdx).value();
2208 cellDensity = fs.density(phaseIdx).value();
2209 perfPhaseRate = perf_phase_rate[perf*np + phaseIdx];
2210 weight_factor += cellDensity * perfPhaseRate / cellBinv * cellInternalEnergy / cellTemperatures;
2212 weight_factor = std::abs(weight_factor) + 1e-13;
2213 total_weight += weight_factor;
2214 weighted_temperature += weight_factor * cellTemperatures;
2216 well_info.communication().sum(weighted.data(), 2);
2217 this->wellState().well(wellID).temperature = weighted_temperature / total_weight;
2223 template <
typename TypeTag>
2227 const auto reportStepIdx =
static_cast<unsigned int>(this->reportStepIndex());
2228 const auto& trMod = this->simulator_.problem().tracerModel();
2234 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:96
const Parallel::Communication & comm() const
Definition: BlackoilWellModelGeneric.hpp:223
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:544
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:295
void init()
Definition: BlackoilWellModel_impl.hpp:161
const Simulator & simulator() const
Definition: BlackoilWellModel.hpp:371
std::vector< Scalar > depth_
Definition: BlackoilWellModel.hpp:478
std::size_t global_num_cells_
Definition: BlackoilWellModel.hpp:474
GetPropType< TypeTag, Properties::Scalar > Scalar
Definition: BlackoilWellModel.hpp:107
void initWellContainer(const int reportStepIdx) override
Definition: BlackoilWellModel_impl.hpp:180
void beginReportStep(const int time_step)
Definition: BlackoilWellModel_impl.hpp:197
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
GetPropType< TypeTag, Properties::Simulator > Simulator
Definition: BlackoilWellModel.hpp:106
void initializeWellState(const int timeStepIdx)
Definition: BlackoilWellModel_impl.hpp:798
const Grid & grid() const
Definition: BlackoilWellModel.hpp:368
const SimulatorReportSingle & lastReport() const
Definition: BlackoilWellModel_impl.hpp:674
void addWellContributions(SparseMatrixAdapter &jacobian) const
Definition: BlackoilWellModel_impl.hpp:1434
Dune::BCRSMatrix< Opm::MatrixBlock< Scalar, 1, 1 > > PressureMatrix
Definition: BlackoilWellModel.hpp:290
bool empty() const
Definition: BlackoilWellModel.hpp:335
void computeTotalRatesForDof(RateVector &rate, unsigned globalIdx) const
Definition: BlackoilWellModel_impl.hpp:761
void beginTimeStep()
Definition: BlackoilWellModel_impl.hpp:331
GetPropType< TypeTag, Properties::RateVector > RateVector
Definition: BlackoilWellModel.hpp:108
void calculateExplicitQuantities(DeferredLogger &deferred_logger) const
Definition: BlackoilWellModel_impl.hpp:1609
void updatePrimaryVariables(DeferredLogger &deferred_logger)
Definition: BlackoilWellModel_impl.hpp:2060
void initializeLocalWellStructure(const int reportStepIdx, const bool enableWellPIScaling)
Definition: BlackoilWellModel_impl.hpp:250
Dune::BlockVector< VectorBlockType > BVector
Definition: BlackoilWellModel.hpp:130
BlackoilWellModel(Simulator &simulator)
Definition: BlackoilWellModel_impl.hpp:74
void wellTesting(const int timeStepIdx, const double simulationTime, DeferredLogger &deferred_logger)
Definition: BlackoilWellModel_impl.hpp:594
typename FluidSystem::IndexTraitsType IndexTraits
Definition: BlackoilWellModel.hpp:114
std::size_t local_num_cells_
Definition: BlackoilWellModel.hpp:476
bool alternative_well_rate_init_
Definition: BlackoilWellModel.hpp:479
void timeStepSucceeded(const double simulationTime, const double dt)
Definition: BlackoilWellModel_impl.hpp:684
Simulator & simulator_
Definition: BlackoilWellModel.hpp:448
void createWellContainer(const int report_step) override
Definition: BlackoilWellModel_impl.hpp:841
std::unique_ptr< WellInterface< TypeTag > > WellInterfacePtr
Definition: BlackoilWellModel.hpp:187
int compressedIndexForInterior(int cartesian_cell_idx) const override
get compressed index for interior cells (-1, otherwise
Definition: BlackoilWellModel.hpp:343
void endReportStep()
Definition: BlackoilWellModel_impl.hpp:657
void initializeSources(typename ParallelWBPCalculation< Scalar >::GlobalToLocal index, typename ParallelWBPCalculation< Scalar >::Evaluator eval)
Definition: ConvergenceReport.hpp:38
void setWellFailed(const WellFailure &wf)
Definition: ConvergenceReport.hpp:272
void setWellGroupTargetsViolated(const bool wellGroupTargetsViolated)
Definition: ConvergenceReport.hpp:290
const std::vector< WellFailure > & wellFailures() const
Definition: ConvergenceReport.hpp:380
void setNetworkNotYetBalancedForceAnotherNewtonIteration(const bool network_needs_more_balancing_force_another_newton_iteration)
Definition: ConvergenceReport.hpp:295
Definition: DeferredLogger.hpp:57
void info(const std::string &tag, const std::string &message)
void warning(const std::string &tag, const std::string &message)
void debug(const std::string &tag, const std::string &message)
std::map< std::string, std::pair< const Well *, int > > GLiftEclWells
Definition: GasLiftGroupInfo.hpp:64
Guard for managing DeferredLogger lifecycle in ReservoirCoupling.
Definition: ReservoirCoupling.hpp:75
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
bool updateWellControl(const Simulator &simulator, const IndividualOrGroup iog, const GroupStateHelperType &groupStateHelper, WellStateType &well_state, DeferredLogger &deferred_logger)
Definition: WellInterface_impl.hpp:189
virtual void updateProductivityIndex(const Simulator &simulator, const WellProdIndexCalculator< Scalar > &wellPICalc, WellStateType &well_state, DeferredLogger &deferred_logger) const =0
Definition: WellState.hpp:66
ExcEnum
Definition: DeferredLogger.hpp:45
@ NONE
Definition: DeferredLogger.hpp:46
Dune::Communication< MPIComm > Communication
Definition: ParallelCommunication.hpp:30
Definition: blackoilbioeffectsmodules.hh:43
Opm::DeferredLogger gatherDeferredLogger(const Opm::DeferredLogger &local_deferredlogger, Parallel::Communication communicator)
Create a global log combining local logs.
ConvergenceReport gatherConvergenceReport(const ConvergenceReport &local_report, Parallel::Communication communicator)
std::string to_string(const ConvergenceReport::ReservoirFailure::Type t)
A struct for returning timing data from a simulator to its caller.
Definition: SimulatorReport.hpp:34