BlackoilWellModel_impl.hpp
Go to the documentation of this file.
1/*
2 Copyright 2016 - 2019 SINTEF Digital, Mathematics & Cybernetics.
3 Copyright 2016 - 2018 Equinor ASA.
4 Copyright 2017 Dr. Blatt - HPC-Simulation-Software & Services
5 Copyright 2016 - 2018 Norce AS
6
7 This file is part of the Open Porous Media project (OPM).
8
9 OPM is free software: you can redistribute it and/or modify
10 it under the terms of the GNU General Public License as published by
11 the Free Software Foundation, either version 3 of the License, or
12 (at your option) any later version.
13
14 OPM is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 GNU General Public License for more details.
18
19 You should have received a copy of the GNU General Public License
20 along with OPM. If not, see <http://www.gnu.org/licenses/>.
21*/
22
23#ifndef OPM_BLACKOILWELLMODEL_IMPL_HEADER_INCLUDED
24#define OPM_BLACKOILWELLMODEL_IMPL_HEADER_INCLUDED
25
26// Improve IDE experience
27#ifndef OPM_BLACKOILWELLMODEL_HEADER_INCLUDED
28#include <config.h>
30#endif
31
32#include <opm/grid/utility/cartesianToCompressed.hpp>
33
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>
40
41#include <opm/input/eclipse/Units/UnitSystem.hpp>
42
51
53#if HAVE_MPI
55#endif
56
57#if COMPILE_GPU_BRIDGE
59#endif
60
61#include <algorithm>
62#include <cassert>
63#include <cstddef>
64#include <iomanip>
65#include <optional>
66#include <utility>
67
68#include <fmt/format.h>
69
70namespace Opm {
71 template<typename TypeTag>
73 BlackoilWellModel(Simulator& simulator, const NewtonIterationContext& iter_ctx)
74 : WellConnectionModule(*this, simulator.gridView().comm())
75 , BlackoilWellModelGeneric<Scalar, IndexTraits>(simulator.vanguard().schedule(),
76 gaslift_,
77 network_,
78 simulator.vanguard().summaryState(),
79 simulator.vanguard().eclState(),
80 FluidSystem::phaseUsage(),
81 simulator.gridView().comm(),
82 iter_ctx)
83 , simulator_(simulator)
84 , guide_rate_handler_{
85 *this,
86 simulator.vanguard().schedule(),
87 simulator.vanguard().summaryState(),
88 simulator.vanguard().grid().comm()
89 }
90 , gaslift_(this->terminal_output_)
91 , network_(*this)
93 , rescoupHelper_(*this)
94#endif
95 {
96 local_num_cells_ = simulator_.gridView().size(0);
97
98 // Number of cells the global grid view
99 global_num_cells_ = simulator_.vanguard().globalNumCells();
100
101 {
102 auto& parallel_wells = simulator.vanguard().parallelWells();
103
104 this->parallel_well_info_.reserve(parallel_wells.size());
105 for( const auto& name_bool : parallel_wells) {
106 this->parallel_well_info_.push_back
107 (std::make_unique<ParallelWellInfo<Scalar>>
108 (name_bool, grid().comm()));
109 }
110 }
111
113 Parameters::Get<Parameters::AlternativeWellRateInit>();
114
115 using SourceDataSpan =
116 typename PAvgDynamicSourceData<Scalar>::template SourceDataSpan<Scalar>;
117
118 this->wbp_.initializeSources(
119 [this](const std::size_t globalIndex)
120 { return this->compressedIndexForInterior(globalIndex); },
121 [this](const int localCell, SourceDataSpan sourceTerms)
122 {
123 using Item = typename SourceDataSpan::Item;
124
125 const auto* intQuants = this->simulator_.model()
126 .cachedIntensiveQuantities(localCell, /*timeIndex = */0);
127 const auto& fs = intQuants->fluidState();
128
129 sourceTerms
130 .set(Item::PoreVol, intQuants->porosity().value() *
131 this->simulator_.model().dofTotalVolume(localCell))
132 .set(Item::Depth, this->depth_[localCell]);
133
134 constexpr auto io = FluidSystem::oilPhaseIdx;
135 constexpr auto ig = FluidSystem::gasPhaseIdx;
136 constexpr auto iw = FluidSystem::waterPhaseIdx;
137
138 // Ideally, these would be 'constexpr'.
139 const auto haveOil = FluidSystem::phaseIsActive(io);
140 const auto haveGas = FluidSystem::phaseIsActive(ig);
141 const auto haveWat = FluidSystem::phaseIsActive(iw);
142
143 auto weightedPhaseDensity = [&fs](const auto ip)
144 {
145 return fs.saturation(ip).value() * fs.density(ip).value();
146 };
147
148 if (haveOil) { sourceTerms.set(Item::Pressure, fs.pressure(io).value()); }
149 else if (haveGas) { sourceTerms.set(Item::Pressure, fs.pressure(ig).value()); }
150 else { sourceTerms.set(Item::Pressure, fs.pressure(iw).value()); }
151
152 // Strictly speaking, assumes SUM(s[p]) == 1.
153 auto rho = 0.0;
154 if (haveOil) { rho += weightedPhaseDensity(io); }
155 if (haveGas) { rho += weightedPhaseDensity(ig); }
156 if (haveWat) { rho += weightedPhaseDensity(iw); }
157
158 sourceTerms.set(Item::MixtureDensity, rho);
159 }
160 );
161 }
162
163 template<typename TypeTag>
164 void
166 init()
167 {
168 extractLegacyCellPvtRegionIndex_();
169 extractLegacyDepth_();
170
171 gravity_ = simulator_.problem().gravity()[2];
172
173 this->initial_step_ = true;
174
175 // add the eWoms auxiliary module for the wells to the list
176 simulator_.model().addAuxiliaryModule(this);
177
178 is_cell_perforated_.resize(local_num_cells_, false);
179 }
180
181
182 template<typename TypeTag>
183 void
185 initWellContainer(const int reportStepIdx)
186 {
187 const uint64_t effective_events_mask = ScheduleEvents::WELL_STATUS_CHANGE
188 + ScheduleEvents::NEW_WELL;
189 const auto& events = this->schedule()[reportStepIdx].wellgroup_events();
190 for (auto& wellPtr : this->well_container_) {
191 const bool well_opened_this_step = this->report_step_starts_ &&
192 events.hasEvent(wellPtr->name(),
193 effective_events_mask);
194 wellPtr->init(this->depth_, this->gravity_,
195 this->B_avg_, well_opened_this_step);
196 }
197 }
198
199 template<typename TypeTag>
200 void
202 beginReportStep(const int timeStepIdx)
203 {
204 this->groupStateHelper().setReportStep(timeStepIdx);
205 this->report_step_starts_ = true;
206 this->report_step_start_events_ = this->schedule()[timeStepIdx].wellgroup_events();
207
208 this->rateConverter_ = std::make_unique<RateConverterType>
209 (std::vector<int>(this->local_num_cells_, 0));
210
211 {
212 const bool initializeWellState = !this->deserialized_state_pending_;
213 const auto enableWellPIScaling = true;
214 this->initializeLocalWellStructure(timeStepIdx,
215 enableWellPIScaling,
216 initializeWellState);
217 this->deserialized_state_pending_ = false;
218 }
219
220 this->initializeGroupStructure(timeStepIdx);
221
222 const auto& comm = this->simulator_.vanguard().grid().comm();
223
225 {
226 // Create facility for calculating reservoir voidage volumes for
227 // purpose of RESV controls.
228 this->rateConverter_->template defineState<ElementContext>(this->simulator_);
229
230 // Update VFP properties.
231 {
232 const auto& sched_state = this->schedule()[timeStepIdx];
233
234 this->vfp_properties_ = std::make_unique<VFPProperties<Scalar, IndexTraits>>
235 (sched_state.vfpinj(), sched_state.vfpprod(), this->wellState());
236 }
237 }
238 OPM_END_PARALLEL_TRY_CATCH("beginReportStep() failed: ", comm)
239
240 // Store the current well and group states in order to recover in
241 // the case of failed iterations
242 this->commitWGState();
243
244 this->wellStructureChangedDynamically_ = false;
245 }
246
247
248
249
250
251 template <typename TypeTag>
252 void
254 initializeLocalWellStructure(const int reportStepIdx,
255 const bool enableWellPIScaling,
256 const bool initializeWellState)
257 {
258 auto logger_guard = this->groupStateHelper().pushLogger();
259 auto& local_deferredLogger = this->groupStateHelper().deferredLogger();
260
261 const auto& comm = this->simulator_.vanguard().grid().comm();
262
263 // Wells drilled by an action are not part of the well set the
264 // parallel well bookkeeping was built from. Register them before
265 // anything looks them up. Collective, hence outside the try/catch.
266 this->registerNewParallelWells(reportStepIdx);
267
268 // Wells_ecl_ holds this rank's wells, both open and stopped/shut.
269 this->wells_ecl_ = this->getLocalWells(reportStepIdx);
270 this->local_parallel_well_info_ =
271 this->createLocalParallelWellInfo(this->wells_ecl_);
272
273 // At least initializeWellState() might be throw an exception in
274 // UniformTabulated2DFunction. Playing it safe by extending the
275 // scope a bit.
277 {
278 if (initializeWellState) {
279 this->initializeWellPerfData();
280 this->initializeWellState(reportStepIdx);
281 }
282 this->wbp_.initializeWBPCalculationService();
283
284 if (initializeWellState && this->param_.use_multisegment_well_ && this->anyMSWellOpenLocal()) {
285 this->wellState().initWellStateMSWell(this->wells_ecl_, &this->prevWellState(), has_energy_);
286 }
287
288 this->initializeWellProdIndCalculators();
289
290 if (enableWellPIScaling && this->schedule()[reportStepIdx].events()
291 .hasEvent(ScheduleEvents::Events::WELL_PRODUCTIVITY_INDEX))
292 {
293 this->runWellPIScaling(reportStepIdx, local_deferredLogger);
294 }
295 }
296 OPM_END_PARALLEL_TRY_CATCH_LOG(local_deferredLogger,
297 "Failed to initialize local well structure: ",
298 this->terminal_output_, comm)
299 }
300
301
302
303
304
305 template <typename TypeTag>
306 void
308 initializeGroupStructure(const int reportStepIdx)
309 {
310 const auto& comm = this->simulator_.vanguard().grid().comm();
311
313 {
314 const auto& fieldGroup =
315 this->schedule().getGroup("FIELD", reportStepIdx);
316
317 this->groupStateHelper().setCmodeGroup(fieldGroup);
318
319 // Define per region average pressure calculators for use by
320 // pressure maintenance groups (GPMAINT keyword).
321 if (this->schedule()[reportStepIdx].has_gpmaint()) {
322 this->groupStateHelper().setRegionAveragePressureCalculator(
323 fieldGroup,
324 this->eclState_.fieldProps(),
325 this->regionalAveragePressureCalculator_
326 );
327 }
328 }
329 OPM_END_PARALLEL_TRY_CATCH("Failed to initialize group structure: ", comm)
330 }
331
332
333
334
335
336 // called at the beginning of a time step
337 template<typename TypeTag>
338 void
341 {
342 OPM_TIMEBLOCK(beginTimeStep);
343
344 this->updateAverageFormationFactor();
345
346 auto logger_guard = this->groupStateHelper().pushLogger();
347 auto& local_deferredLogger = this->groupStateHelper().deferredLogger();
348
349#ifdef RESERVOIR_COUPLING_ENABLED
350 auto rescoup_logger_guard = this->rescoupHelper_.setupScopedLogger(local_deferredLogger);
351#endif
352
353 this->switched_prod_groups_.clear();
354 this->switched_inj_groups_.clear();
355
356 if (this->wellStructureChangedDynamically_) {
357 // Something altered the well structure/topology. Possibly
358 // WELSPECS/COMPDAT and/or WELOPEN run from an ACTIONX block.
359 // Reconstruct the local wells to account for the new well
360 // structure.
361 const auto reportStepIdx =
362 this->simulator_.episodeIndex();
363
364 // Disable WELPI scaling when well structure is updated in the
365 // middle of a report step.
366 const auto enableWellPIScaling = false;
367
368 this->initializeLocalWellStructure(reportStepIdx, enableWellPIScaling, true);
369 this->initializeGroupStructure(reportStepIdx);
370
371 this->commitWGState();
372
373 // Reset topology flag to signal that we've handled this
374 // structure change. That way we don't end up here in
375 // subsequent calls to beginTimeStep() unless there's a new
376 // dynamic change to the well structure during a report step.
377 this->wellStructureChangedDynamically_ = false;
378 }
379
380 this->resetWGState();
381 const int reportStepIdx = simulator_.episodeIndex();
382
383 this->wellState().updateWellsDefaultALQ(this->schedule(), reportStepIdx, this->summaryState());
384 this->wellState().gliftTimeStepInit();
385
386 const double simulationTime = simulator_.time();
387
388 this->well_performance_event_tracker_.beginTimeStep(this->schedule(), reportStepIdx,
389 this->wellStatusSnapshot());
390
392 {
393 // test wells
394 wellTesting(reportStepIdx, simulationTime, local_deferredLogger);
395
396 // Rebuilding the container discards the wells' solve statistics.
397 stashWellSolveStats();
398
399 // A WTEST reopen is the simulator's own decision, so record it
400 // before the deck is applied below.
401 this->well_performance_event_tracker_.accumulate(this->wellStatusSnapshot());
402
403 // create the well container
404 createWellContainer(reportStepIdx);
405
406 // The deck has now been applied for this time step. Its
407 // connection changes are events; its well status changes are not.
408 this->well_performance_event_tracker_.applyDeckChanges(this->wellStatusSnapshot());
409
410#ifdef RESERVOIR_COUPLING_ENABLED
411 if (this->isReservoirCouplingMaster()) {
412 if (this->reservoirCouplingMaster().isFirstSubstepOfSyncTimestep()) {
413 this->rescoupHelper_.receiveSlaveGroupData();
414 }
415 }
416#endif
417
418 // we need to update the group data after the well is created
419 // to make sure we get the correct mapping.
420 this->updateAndCommunicateGroupData(reportStepIdx, /*update_wellgrouptarget*/ false);
421
422 // Wells are active if they are active wells on at least one process.
423 const Grid& grid = simulator_.vanguard().grid();
424 this->wells_active_ = grid.comm().max(!this->well_container_.empty());
425
426 // do the initialization for all the wells
427 // TODO: to see whether we can postpone of the intialization of the well containers to
428 // optimize the usage of the following several member variables
429 this->initWellContainer(reportStepIdx);
430
431 // update the updated cell flag
432 std::fill(is_cell_perforated_.begin(), is_cell_perforated_.end(), false);
433 for (auto& well : well_container_) {
434 well->updatePerforatedCell(is_cell_perforated_);
435 }
436
437 // calculate the efficiency factors for each well
438 this->calculateEfficiencyFactors(reportStepIdx);
439
440 if constexpr (has_polymer_)
441 {
442 if (PolymerModule::hasPlyshlog() || getPropValue<TypeTag, Properties::EnablePolymerMW>() ) {
443 this->setRepRadiusPerfLength();
444 }
445 }
446
447 }
448
449 OPM_END_PARALLEL_TRY_CATCH_LOG(local_deferredLogger, "beginTimeStep() failed: ",
450 this->terminal_output_, simulator_.vanguard().grid().comm());
451
452 for (auto& well : well_container_) {
453 well->setVFPProperties(this->vfp_properties_.get());
454 well->setGuideRate(&this->guideRate_);
455 }
456
457 this->updateFiltrationModelsPreStep(local_deferredLogger);
458
459 // Close completions due to economic reasons
460 for (auto& well : well_container_) {
461 well->closeCompletions(this->wellTestState());
462 }
463
464 // we need the inj_multiplier from the previous time step
465 this->initInjMult();
466
467 if (alternative_well_rate_init_) {
468 // Update the well rates of well_state_, if only single-phase rates, to
469 // have proper multi-phase rates proportional to rates at bhp zero.
470 // This is done only for producers, as injectors will only have a single
471 // nonzero phase anyway.
472 for (const auto& well : well_container_) {
473 if (well->isProducer() && !well->wellIsStopped()) {
474 well->initializeProducerWellState(simulator_, this->wellState(), local_deferredLogger);
475 }
476 }
477 }
478
479 for (const auto& well : well_container_) {
480 if (well->isVFPActive(local_deferredLogger)){
481 well->setPrevSurfaceRates(this->wellState(), this->prevWellState());
482 }
483 }
484 try {
485 this->updateWellPotentials(reportStepIdx,
486 /*onlyAfterEvent*/true,
487 simulator_.vanguard().summaryConfig(),
488 local_deferredLogger);
489 } catch ( std::runtime_error& e ) {
490 const std::string msg = "A zero well potential is returned for output purposes. ";
491 local_deferredLogger.warning("WELL_POTENTIAL_CALCULATION_FAILED", msg);
492 }
493 //update guide rates
494 this->guide_rate_handler_.updateGuideRates(
495 reportStepIdx, simulationTime, this->wellState(), this->groupState()
496 );
497 bool slave_needs_well_solution = false;
498#ifdef RESERVOIR_COUPLING_ENABLED
499 if (this->isReservoirCouplingSlave()) {
500 if (this->reservoirCouplingSlave().isFirstSubstepOfSyncTimestep()) {
501 // The wells have not been solved for this sync step yet, so a well that
502 // opens in this report step still carries its WCONPROD target as its rate.
503 // See RescoupSendSlaveGroupData::collectSlaveGroupSurfaceProductionRates_().
504 this->reservoirCouplingSlave().setWellsSolvedThisSyncStep(false);
505 this->rescoupHelper_.sendSlaveGroupDataToMaster();
506 this->rescoupHelper_.receiveGroupConstraintsFromMaster();
507 this->rescoupHelper_.receiveCoupledNetworkActiveStatus();
508 this->groupStateHelper().updateSlaveGroupCmodesFromMaster();
509 this->reservoirCouplingSlave().markSlaveGroupsInSchedule(
510 this->schedule_, reportStepIdx);
511 this->rescoupHelper_.refreshSlaveGroupInjectionTargets();
512 slave_needs_well_solution = true;
513 }
514 }
515#endif
516 std::string exc_msg;
517 auto exc_type = ExceptionType::NONE;
518 // update gpmaint targets
519 if (this->schedule_[reportStepIdx].has_gpmaint()) {
520 for (const auto& calculator : regionalAveragePressureCalculator_) {
521 calculator.second->template defineState<ElementContext>(simulator_);
522 }
523 const double dt = simulator_.timeStepSize();
524 const Group& fieldGroup = this->schedule().getGroup("FIELD", reportStepIdx);
525 try {
526 this->groupStateHelper().updateGpMaintTargetForGroups(fieldGroup,
527 regionalAveragePressureCalculator_,
528 dt);
529 }
530 OPM_PARALLEL_CATCH_CLAUSE(exc_type, exc_msg);
531 }
532
533 this->updateAndCommunicateGroupData(reportStepIdx, /*update_wellgrouptarget*/ true);
534 try {
535 // Compute initial well solution for new wells and injectors that change injection type i.e. WAG.
536 for (auto& well : well_container_) {
537 const uint64_t effective_events_mask = ScheduleEvents::WELL_STATUS_CHANGE
538 + ScheduleEvents::INJECTION_TYPE_CHANGED
539 + ScheduleEvents::WELL_SWITCHED_INJECTOR_PRODUCER
540 + ScheduleEvents::NEW_WELL;
541
542 const auto& events = this->schedule()[reportStepIdx].wellgroup_events();
543 const bool event = this->report_step_starts_ && events.hasEvent(well->name(), effective_events_mask);
544 const bool dyn_status_change = this->wellState().well(well->name()).status
545 != this->prevWellState().well(well->name()).status;
546
547 if (event || dyn_status_change || slave_needs_well_solution) {
548 try {
549 well->scaleSegmentRatesAndPressure(this->wellState());
550 well->calculateExplicitQuantities(simulator_, this->groupStateHelper());
551 well->updateWellStateWithTarget(simulator_, this->groupStateHelper(), this->wellState());
552 well->updatePrimaryVariables(this->groupStateHelper());
553 well->solveWellEquation(
554 simulator_, this->groupStateHelper(), this->wellState()
555 );
556 } catch (const std::exception& e) {
557 const std::string msg = "Compute initial well solution for new well " + well->name() + " failed. Continue with zero initial rates";
558 local_deferredLogger.warning("WELL_INITIAL_SOLVE_FAILED", msg);
559 }
560 }
561 }
562 }
563 // Catch clauses for all errors setting exc_type and exc_msg
564 OPM_PARALLEL_CATCH_CLAUSE(exc_type, exc_msg);
565
566#ifdef RESERVOIR_COUPLING_ENABLED
567 if (slave_needs_well_solution) { // isReservoirCouplingSlave()
568 // The initial well solve above has run, so the well states now hold solved rates.
569 this->reservoirCouplingSlave().setWellsSolvedThisSyncStep(true);
570 // Need to update group data based on new well solution.
571 this->updateAndCommunicateGroupData(reportStepIdx, /*update_wellgrouptarget*/ false);
572 this->rescoupHelper_.sendSlaveGroupDataToMaster();
573 }
574 else if (this->isReservoirCouplingMaster()) {
575 if (this->reservoirCouplingMaster().isFirstSubstepOfSyncTimestep()) {
576 this->rescoupHelper_.sendMasterGroupConstraintsToSlaves();
577 this->rescoupHelper_.sendCoupledNetworkActiveStatus();
578 this->rescoupHelper_.receiveSlaveGroupData();
579 }
580 }
581#endif
582
583 if (exc_type != ExceptionType::NONE) {
584 const std::string msg = "Compute initial well solution for new wells failed. Continue with zero initial rates";
585 local_deferredLogger.warning("WELL_INITIAL_SOLVE_FAILED", msg);
586 }
587
588 const auto& comm = simulator_.vanguard().grid().comm();
589 logAndCheckForExceptionsAndThrow(local_deferredLogger,
590 exc_type, "beginTimeStep() failed: " + exc_msg, this->terminal_output_, comm);
591
592 }
593
594 template<typename TypeTag>
595 void
598 {
600 }
601
602 template<typename TypeTag>
603 void
606 {
608 }
609
610 template<typename TypeTag>
611 void
613 const double simulationTime,
614 DeferredLogger& deferred_logger)
615 {
616 for (const std::string& well_name : this->getWellsForTesting(timeStepIdx, simulationTime)) {
617 const Well& wellEcl = this->schedule().getWell(well_name, timeStepIdx);
618 if (wellEcl.getStatus() == Well::Status::SHUT)
619 continue;
620
621 WellInterfacePtr well = createWellForWellTest(well_name, timeStepIdx, deferred_logger);
622 // some preparation before the well can be used
623 well->init(depth_, gravity_, B_avg_, true);
624
625 Scalar well_efficiency_factor = wellEcl.getEfficiencyFactor() *
626 this->wellState().getGlobalEfficiencyScalingFactor(well_name);
627 this->groupStateHelper().accumulateGroupEfficiencyFactor(
628 this->schedule().getGroup(wellEcl.groupName(), timeStepIdx),
629 well_efficiency_factor
630 );
631
632 well->setWellEfficiencyFactor(well_efficiency_factor);
633 well->setVFPProperties(this->vfp_properties_.get());
634 well->setGuideRate(&this->guideRate_);
635
636 // initialize rates/previous rates to prevent zero fractions in vfp-interpolation
637 if (well->isProducer() && alternative_well_rate_init_) {
638 well->initializeProducerWellState(simulator_, this->wellState(), deferred_logger);
639 }
640 if (well->isVFPActive(deferred_logger)) {
641 well->setPrevSurfaceRates(this->wellState(), this->prevWellState());
642 }
643
644 this->network_.initializeWell(*well);
645 try {
646 using GLiftEclWells = typename GasLiftGroupInfo<Scalar, IndexTraits>::GLiftEclWells;
647 GLiftEclWells ecl_well_map;
648 gaslift_.initGliftEclWellMap(well_container_, ecl_well_map);
649 well->wellTesting(simulator_,
650 simulationTime,
651 this->groupStateHelper(),
652 this->wellState(),
653 this->wellTestState(),
654 ecl_well_map,
655 this->well_open_times_);
656 } catch (const std::exception& e) {
657 const std::string msg =
658 fmt::format(fmt::runtime("Exception during testing of well: {}. The well will not open.\n"
659 "Exception message: {}"), wellEcl.name(), e.what());
660 deferred_logger.warning("WELL_TESTING_FAILED", msg);
661 }
662 // The tested well is a temporary; keep its solve statistics.
663 addSolveStats(*well);
664 }
665 }
666
667 // called at the end of a report step
668 template<typename TypeTag>
669 void
672 {
673 // Clear the communication data structures for above values.
674 for (auto&& pinfo : this->local_parallel_well_info_)
675 {
676 pinfo.get().clear();
677 }
678 }
679
680
681
682
683
684 // called at the end of a report step
685 template<typename TypeTag>
688 lastReport() const {return last_report_; }
689
690
691
692
693
694 // called at the end of a time step
695 template<typename TypeTag>
696 void
698 timeStepSucceeded(const double simulationTime, const double dt)
699 {
700 this->closed_this_step_.clear();
701
702 // time step is finished and we are not any more at the beginning of an report step
703 this->report_step_starts_ = false;
704 const int reportStepIdx = simulator_.episodeIndex();
705
706 auto logger_guard = this->groupStateHelper().pushLogger();
707 auto& local_deferredLogger = this->groupStateHelper().deferredLogger();
708 for (const auto& well : well_container_) {
709 if (getPropValue<TypeTag, Properties::EnablePolymerMW>() && well->isInjector()) {
710 well->updateWaterThroughput(dt, this->wellState());
711 }
712 }
713 // update connection transmissibility factor and d factor (if applicable) in the wellstate
714 for (const auto& well : well_container_) {
715 well->updateConnectionTransmissibilityFactor(simulator_, this->wellState().well(well->indexOfWell()));
716 well->updateConnectionDFactor(simulator_, this->wellState().well(well->indexOfWell()));
717 }
718
719 if (Indices::waterEnabled) {
720 if constexpr (getPropValue<TypeTag, Properties::EnableMech>()) {
721 // Split injector connection flow between matrix and fracture
722 // for wells with registered fracture contributions.
723 updateWellFractureFlowSplit<FluidSystem, Scalar>(
724 this->simulator_, this->well_container_,
725 this->wellState(), this->nupcolWellState());
726 }
727 this->updateFiltrationModelsPostStep(dt, FluidSystem::waterPhaseIdx, local_deferredLogger);
728 }
729
730 // WINJMULT: At the end of the time step, update the inj_multiplier saved in WellState for later use
731 this->updateInjMult(local_deferredLogger);
732
733 // report well switching
734 for (const auto& well : well_container_) {
735 well->reportWellSwitching(this->wellState().well(well->indexOfWell()), local_deferredLogger);
736 }
737 // report group switching
738 if (this->terminal_output_) {
739 this->reportGroupSwitching(local_deferredLogger);
740 }
741
742 // update the rate converter with current averages pressures etc in
743 rateConverter_->template defineState<ElementContext>(simulator_);
744
745 // calculate the well potentials
746 try {
747 this->updateWellPotentials(reportStepIdx,
748 /*onlyAfterEvent*/false,
749 simulator_.vanguard().summaryConfig(),
750 local_deferredLogger);
751 } catch ( std::runtime_error& e ) {
752 const std::string msg = "A zero well potential is returned for output purposes. ";
753 local_deferredLogger.warning("WELL_POTENTIAL_CALCULATION_FAILED", msg);
754 }
755
756 // simulationTime is the start of the step that has just been completed,
757 // but a well shut by the economic or physical limit checks below keeps
758 // flowing until its end. Record that instant as the closure time, so
759 // the WTEST re-test countdown starts when the well actually stops.
760 const double closure_time = simulationTime + dt;
761
762 updateWellTestState(closure_time, this->wellTestState());
763
764 // check group sales limits at the end of the timestep
765 const Group& fieldGroup = this->schedule_.getGroup("FIELD", reportStepIdx);
766 this->checkGEconLimits(fieldGroup, closure_time,
767 simulator_.episodeIndex(), local_deferredLogger);
768 this->checkGconsaleLimits(fieldGroup, this->wellState(),
769 simulator_.episodeIndex(), local_deferredLogger);
770
771 this->well_performance_event_tracker_.accumulate(this->wellStatusSnapshot());
772
773 this->calculateProductivityIndexValues(local_deferredLogger);
774
775 this->groupStateHelper().updateNONEProductionGroups();
776
777#ifdef RESERVOIR_COUPLING_ENABLED
778 this->rescoupHelper_.rescoupSyncSummaryData();
779#endif
780 this->well_performance_event_tracker_.commitTimeStep(this->schedule(), reportStepIdx);
781 this->commitWGState();
782
783 //reporting output temperatures
784 this->computeWellTemperature();
785 }
786
787
788 template<typename TypeTag>
789 void
792 unsigned elemIdx) const
793 {
794 rate = 0;
795
796 if (!is_cell_perforated_[elemIdx] || cellRates_.count(elemIdx) == 0) {
797 return;
798 }
799
800 rate = cellRates_.at(elemIdx);
801 }
802
803
804 template<typename TypeTag>
805 template <class Context>
806 void
809 const Context& context,
810 unsigned spaceIdx,
811 unsigned timeIdx) const
812 {
813 rate = 0;
814 int elemIdx = context.globalSpaceIndex(spaceIdx, timeIdx);
815
816 if (!is_cell_perforated_[elemIdx] || cellRates_.count(elemIdx) == 0) {
817 return;
818 }
819
820 rate = cellRates_.at(elemIdx);
821 }
822
823
824
825 template<typename TypeTag>
826 void
828 initializeWellState(const int timeStepIdx)
829 {
830 const auto pressIx = []()
831 {
832 if (Indices::oilEnabled) { return FluidSystem::oilPhaseIdx; }
833 if (Indices::waterEnabled) { return FluidSystem::waterPhaseIdx; }
834
835 return FluidSystem::gasPhaseIdx;
836 }();
837
838 auto cellPressures = std::vector<Scalar>(this->local_num_cells_, Scalar{0});
839 auto cellTemperatures = std::vector<Scalar>(this->local_num_cells_, Scalar{0});
840
841 auto elemCtx = ElementContext { this->simulator_ };
842 const auto& gridView = this->simulator_.vanguard().gridView();
843
845 for (const auto& elem : elements(gridView, Dune::Partitions::interior)) {
846 elemCtx.updatePrimaryStencil(elem);
847 elemCtx.updatePrimaryIntensiveQuantities(/*timeIdx=*/0);
848
849 const auto ix = elemCtx.globalSpaceIndex(/*spaceIdx=*/0, /*timeIdx=*/0);
850 const auto& fs = elemCtx.intensiveQuantities(/*spaceIdx=*/0, /*timeIdx=*/0).fluidState();
851
852 cellPressures[ix] = fs.pressure(pressIx).value();
853 cellTemperatures[ix] = fs.temperature(0).value();
854 }
855 OPM_END_PARALLEL_TRY_CATCH("BlackoilWellModel::initializeWellState() failed: ",
856 this->simulator_.vanguard().grid().comm());
857
858 this->wellState().init(cellPressures, cellTemperatures, this->schedule(), this->wells_ecl_,
859 this->local_parallel_well_info_, timeStepIdx,
860 &this->prevWellState(), this->well_perf_data_,
861 this->summaryState(), simulator_.vanguard().enableDistributedWells());
862 }
863
864
865
866
867
868 template<typename TypeTag>
869 void
871 createWellContainer(const int report_step)
872 {
873 auto logger_guard = this->groupStateHelper().pushLogger();
874 auto& local_deferredLogger = this->groupStateHelper().deferredLogger();
875
876 const int nw = this->numLocalWells();
877
878 well_container_.clear();
879
880 if (nw > 0) {
881 well_container_.reserve(nw);
882
883 const auto& wmatcher = this->schedule().wellMatcher(report_step);
884 const auto& wcycle = this->schedule()[report_step].wcycle.get();
885
886 // First loop and check for status changes. This is necessary
887 // as wcycle needs the updated open/close times.
888 std::ranges::for_each(this->wells_ecl_,
889 [this, &wg_events = this->report_step_start_events_](const auto& well_ecl)
890 {
891 if (!well_ecl.hasConnections()) {
892 // No connections in this well. Nothing to do.
893 return;
894 }
895
896 constexpr auto events_mask = ScheduleEvents::WELL_STATUS_CHANGE |
897 ScheduleEvents::REQUEST_OPEN_WELL |
898 ScheduleEvents::REQUEST_SHUT_WELL;
899 const bool well_event =
900 this->report_step_starts_ &&
901 wg_events.hasEvent(well_ecl.name(), events_mask);
902 // WCYCLE is suspendended by explicit SHUT events by the user.
903 // and restarted after explicit OPEN events.
904 // Note: OPEN or SHUT event does not necessary mean the well
905 // actually opened or shut at this point as the simulator could
906 // have done this by operabilty checks and well testing. This
907 // may need further testing and imply code changes to cope with
908 // these corner cases.
909 if (well_event) {
910 if (well_ecl.getStatus() == WellStatus::OPEN) {
911 this->well_open_times_.insert_or_assign(well_ecl.name(),
912 this->simulator_.time());
913 this->well_close_times_.erase(well_ecl.name());
914 } else if (well_ecl.getStatus() == WellStatus::SHUT) {
915 this->well_close_times_.insert_or_assign(well_ecl.name(),
916 this->simulator_.time());
917 this->well_open_times_.erase(well_ecl.name());
918 }
919 }
920 });
921
922 // Grab wcycle states. This needs to run before the schedule gets processed
923 const auto cycle_states = wcycle.wellStatus(this->simulator_.time(),
924 wmatcher,
925 this->well_open_times_,
926 this->well_close_times_);
927
928 for (int w = 0; w < nw; ++w) {
929 const Well& well_ecl = this->wells_ecl_[w];
930
931 if (!well_ecl.hasConnections()) {
932 // No connections in this well. Nothing to do.
933 continue;
934 }
935
936 const std::string& well_name = well_ecl.name();
937 const auto well_status = this->schedule()
938 .getWell(well_name, report_step).getStatus();
939
940 const bool shut_event = this->wellState().well(w).events.hasEvent(ScheduleEvents::WELL_STATUS_CHANGE)
941 && well_status == Well::Status::SHUT;
942 const bool open_event = this->wellState().well(w).events.hasEvent(ScheduleEvents::WELL_STATUS_CHANGE)
943 && well_status == Well::Status::OPEN;
944 const auto& ws = this->wellState().well(well_name);
945
946 if (shut_event && ws.status != Well::Status::SHUT) {
947 this->closed_this_step_.insert(well_name);
948 this->wellState().shutWell(w);
949 } else if (open_event && ws.status != Well::Status::OPEN) {
950 this->wellState().openWell(w);
951 }
952
953 // A new WCON keywords can re-open a well that was closed/shut due to Physical limit
954 if (this->wellTestState().well_is_closed(well_name)) {
955 // The well was shut this timestep, we are most likely retrying
956 // a timestep without the well in question, after it caused
957 // repeated timestep cuts. It should therefore not be opened,
958 // even if it was new or received new targets this report step.
959 //
960 // The time stamp alone cannot establish that, since a shut-in
961 // decided at the *end* of the previous step carries that
962 // step's end time, which coincides with the current step's
963 // start time. Such shut-ins are the ones a new WCON keyword
964 // may undo, and are exactly what wasDynamicallyShutThisTimeStep()
965 // reports; mid-step ones from forceShutWellByName() are not
966 // registered there, so they still block the re-open.
967 const bool closed_this_step =
968 (this->wellTestState().lastTestTime(well_name) == simulator_.time()) &&
969 !this->wasDynamicallyShutThisTimeStep(well_name);
970 // TODO: more checking here, to make sure this standard more specific and complete
971 // maybe there is some WCON keywords will not open the well
972 auto& events = this->wellState().well(w).events;
973 if (events.hasEvent(ScheduleEvents::REQUEST_OPEN_WELL)) {
974 if (!closed_this_step) {
975 this->wellTestState().open_well(well_name);
976 this->wellTestState().open_completions(well_name);
977 this->well_open_times_.insert_or_assign(well_name,
978 this->simulator_.time());
979 this->well_close_times_.erase(well_name);
980 }
981 events.clearEvent(ScheduleEvents::REQUEST_OPEN_WELL);
982 }
983 }
984
985 // WELOPEN/COMPDAT can reopen individual connections shut at run
986 // time by physical/economic limits, without touching the rest
987 // of the well. Act only when the well is open (a SHUT well
988 // would not flow) and the schedule changed completions this
989 // step (global COMPLETION_CHANGE, set by both COMPDAT and
990 // WELOPEN).
991 auto& well_test_state = this->wellTestState();
992 const auto& sched_state = this->schedule()[report_step];
993 const bool may_reopen_completions =
994 ws.status == Well::Status::OPEN &&
995 sched_state.events().hasEvent(ScheduleEvents::COMPLETION_CHANGE) &&
996 well_test_state.num_closed_completions() > 0;
997
998 if (may_reopen_completions) {
999 const auto& completion_events = sched_state.wellcompletion_events();
1000 for (const auto& connection : well_ecl.getConnections()) {
1001 const int complnum = connection.complnum();
1002
1003 // Reopen only connections currently shut at run time
1004 // that are explicitly requested OPEN this step.
1005 if (!well_test_state.completion_is_closed(well_name, complnum) ||
1006 !completion_events.hasEvent(well_name, complnum, ScheduleEvents::REQUEST_OPEN_COMPLETION)) {
1007 continue;
1008 }
1009
1010 // ... but not one closed during the current timestep
1011 const bool closed_this_step =
1012 (well_test_state.lastCompletionCloseTime(well_name, complnum) == simulator_.time());
1013 if (closed_this_step) {
1014 continue;
1015 }
1016
1017 well_test_state.open_completion(well_name, complnum);
1018 local_deferredLogger.info(
1019 fmt::format("Completion {} - block ({}, {}, {}) for well {} "
1020 "is reopened due to an explicit WELOPEN/COMPDAT "
1021 "OPEN request",
1022 complnum,
1023 connection.getI() + 1,
1024 connection.getJ() + 1,
1025 connection.getK() + 1,
1026 well_name));
1027 }
1028 }
1029
1030 // TODO: should we do this for all kinds of closing reasons?
1031 // something like wellTestState().hasWell(well_name)?
1032 if (this->wellTestState().well_is_closed(well_name))
1033 {
1034 if (this->closedWellStatus(well_ecl) == WellStatus::SHUT)
1035 {
1036 this->wellState().shutWell(w);
1037 this->well_close_times_.erase(well_name);
1038 this->well_open_times_.erase(well_name);
1039 continue;
1040 }
1041 // stopped wells are added to the container but marked as stopped
1042 this->wellState().stopWell(w);
1043 }
1044
1045 // shut wells with zero rante constraints and disallowing
1046 if (!well_ecl.getAllowCrossFlow()) {
1047 const bool any_zero_rate_constraint = well_ecl.isProducer()
1048 ? well_ecl.productionControls(this->summaryState_).anyZeroRateConstraint()
1049 : well_ecl.injectionControls(this->summaryState_).anyZeroRateConstraint();
1050 if (any_zero_rate_constraint) {
1051 // Treat as shut, do not add to container.
1052 local_deferredLogger.debug(fmt::format(fmt::runtime(" Well {} gets shut due to having zero rate constraint and disallowing crossflow "), well_ecl.name()));
1053 this->wellState().shutWell(w);
1054 this->well_close_times_.erase(well_name);
1055 this->well_open_times_.erase(well_name);
1056 continue;
1057 }
1058 }
1059
1060 if (!wcycle.empty()) {
1061 const auto it = cycle_states.find(well_name);
1062 if (it != cycle_states.end()) {
1063 if (!it->second || well_status == Well::Status::SHUT) {
1064 // If well is shut in schedule we keep it shut
1065 if (well_status == Well::Status::SHUT) {
1066 this->well_open_times_.erase(well_name);
1067 this->well_close_times_.erase(well_name);
1068 }
1069 this->wellState().shutWell(w);
1070 continue;
1071 } else {
1072 this->wellState().openWell(w);
1073 }
1074 }
1075 }
1076
1077 // We dont add SHUT wells to the container
1078 if (ws.status == Well::Status::SHUT) {
1079 continue;
1080 }
1081
1082 well_container_.emplace_back(this->createWellPointer(w, report_step));
1083
1084 if (ws.status == Well::Status::STOP) {
1085 well_container_.back()->stopWell();
1086 this->well_close_times_.erase(well_name);
1087 this->well_open_times_.erase(well_name);
1088 }
1089 }
1090
1091 if (!wcycle.empty()) {
1092 const auto schedule_open =
1093 [&wg_events = this->report_step_start_events_](const std::string& name)
1094 {
1095 return wg_events.hasEvent(name, ScheduleEvents::REQUEST_OPEN_WELL);
1096 };
1097 for (const auto& [wname, wscale] : wcycle.efficiencyScale(this->simulator_.time(),
1098 this->simulator_.timeStepSize(),
1099 wmatcher,
1100 this->well_open_times_,
1101 schedule_open))
1102 {
1103 this->wellState().updateEfficiencyScalingFactor(wname, wscale);
1104 this->schedule_.add_event(ScheduleEvents::WELLGROUP_EFFICIENCY_UPDATE, report_step);
1105 }
1106 }
1107 }
1108
1109 this->well_container_generic_.clear();
1110 for (auto& w : well_container_) {
1111 this->well_container_generic_.push_back(w.get());
1112 }
1113
1114 this->network_.initialize(report_step);
1115
1116 this->wbp_.registerOpenWellsForWBPCalculation();
1117 }
1118
1119
1120
1121
1122
1123 template <typename TypeTag>
1126 createWellPointer(const int wellID, const int report_step) const
1127 {
1128 const auto is_multiseg = this->wells_ecl_[wellID].isMultiSegment();
1129
1130 if (! (this->param_.use_multisegment_well_ && is_multiseg)) {
1131 return this->template createTypedWellPointer<StandardWell<TypeTag>>(wellID, report_step);
1132 }
1133 else {
1134 return this->template createTypedWellPointer<MultisegmentWell<TypeTag>>(wellID, report_step);
1135 }
1136 }
1137
1138
1139
1140
1141
1142 template <typename TypeTag>
1143 template <typename WellType>
1144 std::unique_ptr<WellType>
1146 createTypedWellPointer(const int wellID, const int time_step) const
1147 {
1148 // Use the pvtRegionIdx from the top cell
1149 const auto& perf_data = this->well_perf_data_[wellID];
1150
1151 // Cater for case where local part might have no perforations.
1152 const auto pvtreg = perf_data.empty()
1153 ? 0 : this->pvt_region_idx_[perf_data.front().cell_index];
1154
1155 const auto& parallel_well_info = this->local_parallel_well_info_[wellID].get();
1156 const auto global_pvtreg = parallel_well_info.broadcastFirstPerforationValue(pvtreg);
1157
1158 return std::make_unique<WellType>(this->wells_ecl_[wellID],
1159 parallel_well_info,
1160 time_step,
1161 this->param_,
1162 *this->rateConverter_,
1163 global_pvtreg,
1164 this->numConservationQuantities(),
1165 this->numPhases(),
1166 wellID,
1167 perf_data);
1168 }
1169
1170
1171
1172
1173
1174 template<typename TypeTag>
1177 createWellForWellTest(const std::string& well_name,
1178 const int report_step,
1179 DeferredLogger& deferred_logger) const
1180 {
1181 // Finding the location of the well in wells_ecl
1182 const auto it =
1183 std::ranges::find_if(this->wells_ecl_,
1184 [&well_name](const auto& w)
1185 { return well_name == w.name(); });
1186 // It should be able to find in wells_ecl.
1187 if (it == this->wells_ecl_.end()) {
1188 OPM_DEFLOG_THROW(std::logic_error,
1189 fmt::format(fmt::runtime("Could not find well {} in wells_ecl"), well_name),
1190 deferred_logger);
1191 }
1192
1193 const int pos = static_cast<int>(std::distance(this->wells_ecl_.begin(), it));
1194 return this->createWellPointer(pos, report_step);
1195 }
1196
1197
1198
1199 template<typename TypeTag>
1200 void
1202 assemble(const double dt)
1203 {
1204 OPM_TIMEFUNCTION();
1205 auto logger_guard = this->groupStateHelper().pushLogger();
1206 auto& local_deferredLogger = this->groupStateHelper().deferredLogger();
1207
1208 const auto& iterCtx = simulator_.problem().iterationContext();
1209
1211 if (gaslift_.terminalOutput()) {
1212 const std::string msg =
1213 fmt::format(fmt::runtime("assemble() : iteration {}"), iterCtx.iteration());
1214 gaslift_.gliftDebug(msg, local_deferredLogger);
1215 }
1216 }
1217 last_report_ = SimulatorReportSingle();
1218 Dune::Timer perfTimer;
1219 perfTimer.start();
1220 this->closed_offending_wells_.clear();
1221
1222 {
1223 if (iterCtx.needsTimestepInit()) {
1224 this->updateNetworkActiveState_();
1225 }
1226 const int episodeIdx = simulator_.episodeIndex();
1227 const auto& network = this->schedule()[episodeIdx].network();
1228 if (!this->wellsActive() && !network.active()) {
1229 return;
1230 }
1231 }
1232
1233 // Timestep initialization: should run once at the start of each timestep.
1234 if (iterCtx.needsTimestepInit() && this->wellsActive()) {
1235 OPM_TIMEBLOCK(firstIterationAssemble);
1236 Dune::Timer prepareTimer;
1237 prepareTimer.start();
1238 // try-catch is needed here as updateWellControls
1239 // contains global communication and has either to
1240 // be reached by all processes or all need to abort
1241 // before.
1243 {
1244 calculateExplicitQuantities();
1245 prepareTimeStep(local_deferredLogger);
1246 }
1247 OPM_END_PARALLEL_TRY_CATCH_LOG(local_deferredLogger,
1248 "assemble() failed during well initialization: ",
1249 this->terminal_output_, grid().comm());
1250 last_report_.well_facility_time += prepareTimer.stop();
1251 }
1252
1253 Dune::Timer networkTimer;
1254 networkTimer.start();
1255 const bool well_group_control_changed = updateWellControlsAndNetwork(
1256 /*mandatory_network_balance=*/false,
1257 dt,
1258 local_deferredLogger);
1259 // the control/network update is part of the facility calculations,
1260 // together with the time step preparation of the wells above
1261 const double network_time = networkTimer.stop();
1262 last_report_.well_control_network_time += network_time;
1263 last_report_.well_facility_time += network_time;
1264
1265 // even when there is no wells active, the network nodal pressure still need to be updated through updateWellControlsAndNetwork()
1266 // but there is no need to assemble the well equations
1267 if ( ! this->wellsActive() ) {
1268 return;
1269 }
1270
1271 assembleWellEqWithoutIteration(dt);
1272 // Pre-compute cell rates to we don't have to do this for every cell during linearization...
1273 updateCellRates();
1274
1275 // collect the statistics for the standalone well solves done since
1276 // the last assembly (prepareTimeStep, well testing and well
1277 // potential calculations)
1278 collectWellSolveStats();
1279
1280 // if group or well control changes we don't consider the
1281 // case converged
1282 last_report_.well_group_control_changed = well_group_control_changed;
1283 last_report_.assemble_time_well += perfTimer.stop();
1284 }
1285
1286
1287
1288
1289 template<typename TypeTag>
1290 void
1293 {
1294 stashWellSolveStats();
1295 const auto& stats = pending_solve_stats_;
1296 last_report_.well_solve_time += stats.solve_time;
1297 last_report_.well_potential_solve_time += stats.potential_solve_time;
1298 last_report_.well_solve_assemble_time += stats.assemble_time;
1299 last_report_.well_solve_linear_solve_time += stats.linear_solve_time;
1300 last_report_.total_well_iterations += stats.iterations;
1301 last_report_.total_well_potential_iterations += stats.potential_iterations;
1302 pending_solve_stats_ = {};
1303 }
1304
1305 template<typename TypeTag>
1306 void
1309 {
1310 for (const auto& well : well_container_) {
1311 addSolveStats(*well);
1312 }
1313 }
1314
1315 template<typename TypeTag>
1316 void
1319 {
1320 auto& pending = pending_solve_stats_;
1321 const auto& stats = well.solveStats();
1322 pending.solve_time += stats.solve_time;
1323 pending.potential_solve_time += stats.potential_solve_time;
1324 pending.assemble_time += stats.assemble_time;
1325 pending.linear_solve_time += stats.linear_solve_time;
1326 pending.iterations += stats.iterations;
1327 pending.potential_iterations += stats.potential_iterations;
1328 well.resetSolveStats();
1329 }
1330
1331
1332
1333
1334 template<typename TypeTag>
1335 bool
1337 updateWellControlsAndNetwork(const bool mandatory_network_balance,
1338 const double dt,
1339 DeferredLogger& local_deferredLogger)
1340 {
1341 OPM_TIMEFUNCTION();
1342 // not necessarily that we always need to update once of the network solutions
1343 bool do_network_update = true;
1344 bool well_group_control_changed = false;
1345 Scalar network_imbalance = 0.0;
1346 // after certain number of the iterations, we use relaxed tolerance for the network update
1347 const std::size_t iteration_to_relax = param_.network_max_strict_outer_iterations_;
1348 // after certain number of the iterations, we terminate
1349 const std::size_t max_iteration = param_.network_max_outer_iterations_;
1350 std::size_t network_update_iteration = 0;
1351 network_needs_more_balancing_force_another_newton_iteration_ = false;
1352 while (do_network_update) {
1353 if (!this->isRescoupSlaveCoupledNetworkIteration_()
1354 && network_update_iteration >= max_iteration ) {
1355 // only output to terminal if we at the last newton iterations where we try to balance the network.
1356 const int episodeIdx = simulator_.episodeIndex();
1357 if (this->network_.willBalanceOnNextIteration(episodeIdx)) {
1358 if (this->terminal_output_) {
1359 const std::string msg = fmt::format("Maximum of {:d} network iterations has been used and we stop the update, \n"
1360 "and try again after the next Newton iteration (imbalance = {:.2e} bar)",
1361 max_iteration, network_imbalance*1.0e-5);
1362 local_deferredLogger.debug(msg);
1363 }
1364 // To avoid stopping the newton iterations too early, before the network is converged,
1365 // we need to report it
1366 network_needs_more_balancing_force_another_newton_iteration_ = true;
1367 } else {
1368 if (this->terminal_output_) {
1369 const std::string msg = fmt::format("Maximum of {:d} network iterations has been used and we stop the update. \n"
1370 "The simulator will continue with unconverged network results (imbalance = {:.2e} bar)",
1371 max_iteration, network_imbalance*1.0e-5);
1372 local_deferredLogger.info(msg);
1373 }
1374 }
1375 break;
1376 }
1377 if (this->terminal_output_ && (network_update_iteration == iteration_to_relax) ) {
1378 local_deferredLogger.debug("We begin using relaxed tolerance for network update now after " + std::to_string(iteration_to_relax) + " iterations ");
1379 }
1380 const bool relax_network_balance = network_update_iteration >= iteration_to_relax;
1381 // Never optimize gas lift in last iteration, to allow network convergence (unless max_iter < 2)
1382 const bool optimize_gas_lift = ( (network_update_iteration + 1) < std::max(max_iteration, static_cast<std::size_t>(2)) );
1383 std::tie(well_group_control_changed, do_network_update, network_imbalance) =
1384 updateWellControlsAndNetworkIteration(mandatory_network_balance, relax_network_balance, optimize_gas_lift, dt,local_deferredLogger);
1385 ++network_update_iteration;
1386 }
1387 if (this->isRescoupMasterCoupledNetworkIteration_()) {
1388 this->sendSlaveNetworkLoopTerminationSignal_();
1389 }
1390 // only count the balancing iterations when a network is active
1391 if (this->schedule()[simulator_.episodeIndex()].network().active()) {
1392 last_report_.total_network_iterations += network_update_iteration;
1393 }
1394 return well_group_control_changed;
1395 }
1396
1397
1398
1399
1400 template<typename TypeTag>
1401 std::tuple<bool, bool, typename BlackoilWellModel<TypeTag>::Scalar>
1403 updateWellControlsAndNetworkIteration(const bool mandatory_network_balance,
1404 const bool relax_network_tolerance,
1405 const bool optimize_gas_lift,
1406 const double dt,
1407 DeferredLogger& local_deferredLogger)
1408 {
1409 OPM_TIMEFUNCTION();
1410 const int reportStepIdx = simulator_.episodeIndex();
1411
1412#ifdef RESERVOIR_COUPLING_ENABLED
1413 if (this->isRescoupSlaveCoupledNetworkIteration_()) {
1414 this->rescoupHelper_.receiveMasterGroupNodePressuresFromMaster();
1415 }
1416#endif
1417 Dune::Timer groupTimer;
1418 groupTimer.start();
1419 this->updateAndCommunicateGroupData(reportStepIdx, /*update_wellgrouptarget*/ true);
1420 // We need to call updateWellControls before we update the network as
1421 // network updates are only done on thp controlled wells.
1422 // Note that well controls are allowed to change during updateNetwork
1423 // and in prepareWellsBeforeAssembling during well solves.
1424 bool well_group_control_changed = updateWellControls(local_deferredLogger);
1425 last_report_.group_control_time += groupTimer.stop();
1426
1427 Dune::Timer networkBalanceTimer;
1428 networkBalanceTimer.start();
1429 const auto [more_inner_network_update, network_imbalance] =
1430 this->network_.update(mandatory_network_balance,
1431 local_deferredLogger,
1432 relax_network_tolerance);
1433 // only account for the time when a network is active
1434 if (this->schedule()[reportStepIdx].network().active()) {
1435 last_report_.network_balance_time += networkBalanceTimer.stop();
1436 }
1437#ifdef RESERVOIR_COUPLING_ENABLED
1438 if (this->isReservoirCouplingMaster()) {
1439 this->rescoupHelper_.maybeExchangeNetworkOuterIterationWithSlaves(more_inner_network_update);
1440 }
1441#endif
1442
1443 bool alq_updated = false;
1445 {
1446 if (optimize_gas_lift) {
1447 // we need to update the potentials if the thp limit as been modified by
1448 // the network balancing
1449 const bool updatePotentials = (this->network_.shouldBalance(reportStepIdx) ||
1450 mandatory_network_balance);
1451 Dune::Timer gliftTimer;
1452 gliftTimer.start();
1453 alq_updated = gaslift_.maybeDoGasLiftOptimize(simulator_,
1454 well_container_,
1455 this->network_.nodePressures(),
1456 updatePotentials,
1457 this->wellState(),
1458 this->groupState(),
1459 local_deferredLogger);
1460 // only account for the time when gas lift optimization is in use
1461 if (this->schedule().glo(reportStepIdx).active()) {
1462 last_report_.gaslift_time += gliftTimer.stop();
1463 }
1464 }
1465 // the well solves triggered by control changes are part of the
1466 // control/network update, keep track of the time separately
1467 Dune::Timer prepareWellsTimer;
1468 prepareWellsTimer.start();
1469 prepareWellsBeforeAssembling(dt);
1470 last_report_.control_well_solve_time += prepareWellsTimer.stop();
1471 }
1472 OPM_END_PARALLEL_TRY_CATCH_LOG(local_deferredLogger,
1473 "updateWellControlsAndNetworkIteration() failed: ",
1474 this->terminal_output_, grid().comm());
1475
1476 // update guide rates
1477 if (alq_updated || BlackoilWellModelGuideRates(*this).
1478 guideRateUpdateIsNeeded(reportStepIdx)) {
1479 const double simulationTime = simulator_.time();
1480 Dune::Timer guideRateTimer;
1481 guideRateTimer.start();
1482 // NOTE: For reservoir coupling: Slave group potentials are only communicated
1483 // at the start of the time step, see beginTimeStep(). Here, we assume those
1484 // potentials remain unchanged during the time step when updating guide rates below.
1485 this->guide_rate_handler_.updateGuideRates(
1486 reportStepIdx, simulationTime, this->wellState(), this->groupState()
1487 );
1488 last_report_.group_control_time += guideRateTimer.stop();
1489 }
1490 // we need to re-iterate the network when the well group controls changed or gaslift/alq is changed or
1491 // the inner iterations are did not converge
1492 bool more_network_update = this->network_.shouldBalance(reportStepIdx) &&
1493 (more_inner_network_update || alq_updated);
1494
1495 if (this->isRescoupSlaveOnSyncStepFirstSubstep_()
1496 && this->isRescoupSlaveConnectedToMasterNetwork_()) {
1497 // Connected slave: the call ships this slave's flow to the master
1498 // and reports whether the cross-rescoup exchange continues. OR
1499 // with the local decision so a connected slave that also has its
1500 // own network keeps iterating it. A slave not connected to the
1501 // master network skips this branch entirely and runs purely on its
1502 // local more_network_update.
1503 const bool more_cross_rescoup_update =
1504 this->maybeSendSlaveGroupFlowToMaster_(reportStepIdx);
1505 more_network_update = more_network_update || more_cross_rescoup_update;
1506 }
1507
1508 return {well_group_control_changed, more_network_update, network_imbalance};
1509 }
1510
1511 template<typename TypeTag>
1512 void
1514 assembleWellEq(const double dt)
1515 {
1516 OPM_TIMEFUNCTION();
1517 for (auto& well : well_container_) {
1518 well->assembleWellEq(simulator_, dt, this->groupStateHelper(), this->wellState());
1519 }
1520 }
1521
1522
1523 template<typename TypeTag>
1524 void
1526 prepareWellsBeforeAssembling(const double dt)
1527 {
1528 OPM_TIMEFUNCTION();
1529 for (auto& well : well_container_) {
1530 well->prepareWellBeforeAssembling(
1531 simulator_, dt, this->groupStateHelper(), this->wellState()
1532 );
1533 }
1534 }
1535
1536
1537 template<typename TypeTag>
1538 void
1540 assembleWellEqWithoutIteration(const double dt)
1541 {
1542 OPM_TIMEFUNCTION();
1543 auto& deferred_logger = this->groupStateHelper().deferredLogger();
1544 // We make sure that all processes throw in case there is an exception
1545 // on one of them (WetGasPvt::saturationPressure might throw if not converged)
1547
1548 for (auto& well: well_container_) {
1549 well->assembleWellEqWithoutIteration(simulator_, this->groupStateHelper(), dt, this->wellState(),
1550 /*solving_with_zero_rate=*/false);
1551 }
1552 OPM_END_PARALLEL_TRY_CATCH_LOG(deferred_logger, "BlackoilWellModel::assembleWellEqWithoutIteration failed: ",
1553 this->terminal_output_, grid().comm());
1554
1555 }
1556
1557 template<typename TypeTag>
1558 void
1561 {
1562 // Pre-compute cell rates for all wells
1563 cellRates_.clear();
1564 for (const auto& well : well_container_) {
1565 well->addCellRates(cellRates_);
1566 }
1567 }
1568
1569 template<typename TypeTag>
1570 void
1572 updateCellRatesForDomain(int domainIndex, const std::map<std::string, int>& well_domain_map)
1573 {
1574 // Pre-compute cell rates only for wells in the specified domain
1575 cellRates_.clear();
1576 for (const auto& well : well_container_) {
1577 const auto it = well_domain_map.find(well->name());
1578 if (it != well_domain_map.end() && it->second == domainIndex) {
1579 well->addCellRates(cellRates_);
1580 }
1581 }
1582 }
1583
1584#if COMPILE_GPU_BRIDGE
1585 template<typename TypeTag>
1586 void
1589 {
1590 // prepare for StandardWells
1592
1593 for(unsigned int i = 0; i < well_container_.size(); i++){
1594 auto& well = well_container_[i];
1595 auto derived = dynamic_cast<StandardWell<TypeTag>*>(well.get());
1596 if (derived) {
1597 wellContribs.addNumBlocks(derived->linSys().getNumBlocks());
1598 }
1599 }
1600
1601 // allocate memory for data from StandardWells
1602 wellContribs.alloc();
1603
1604 for(unsigned int i = 0; i < well_container_.size(); i++){
1605 auto& well = well_container_[i];
1606 // maybe WellInterface could implement addWellContribution()
1607 auto derived_std = dynamic_cast<StandardWell<TypeTag>*>(well.get());
1608 if (derived_std) {
1609 derived_std->linSys().extract(derived_std->numStaticWellEq, wellContribs);
1610 } else {
1611 auto derived_ms = dynamic_cast<MultisegmentWell<TypeTag>*>(well.get());
1612 if (derived_ms) {
1613 derived_ms->linSys().extract(wellContribs);
1614 } else {
1615 OpmLog::warning("Warning unknown type of well");
1616 }
1617 }
1618 }
1619 }
1620#endif
1621
1622 template<typename TypeTag>
1623 void
1625 addWellContributions(SparseMatrixAdapter& jacobian) const
1626 {
1627 for ( const auto& well: well_container_ ) {
1628 well->addWellContributions(jacobian);
1629 }
1630 }
1631
1632 template<typename TypeTag>
1633 void
1634 BlackoilWellModel<TypeTag>::addBCDMatrix(std::vector<BMatrix>& b_matrices,
1635 std::vector<CMatrix>& c_matrices,
1636 std::vector<DMatrix>& d_matrices,
1637 Opm::SparseTable<int>& wcells) const
1638 {
1639 wcells.clear();
1640 for ( const auto& well: well_container_ ) {
1641 well->addBCDMatrix(b_matrices, c_matrices, d_matrices, wcells);
1642 }
1643 }
1644
1645 template<typename TypeTag>
1646 void
1649 const BVector& weights,
1650 const bool use_well_weights) const
1651 {
1652 int nw = this->numLocalWellsEnd();
1653 int rdofs = local_num_cells_;
1654 for ( int i = 0; i < nw; i++ ) {
1655 int wdof = rdofs + i;
1656 jacobian[wdof][wdof] = 1.0;// better scaling ?
1657 }
1658
1659 for (const auto& well : well_container_) {
1660 well->addWellPressureEquations(jacobian,
1661 weights,
1662 pressureVarIndex,
1663 use_well_weights,
1664 this->wellState());
1665 }
1666 }
1667
1668 template <typename TypeTag>
1670 addReservoirSourceTerms(GlobalEqVector& residual,
1671 const std::vector<typename SparseMatrixAdapter::MatrixBlock*>& diagMatAddress) const
1672 {
1673 // NB this loop may write multiple times to the same element
1674 // if a cell is perforated by more than one well, so it should
1675 // not be OpenMP-parallelized.
1676 for (const auto& well : well_container_) {
1677 if (!well->isOperableAndSolvable() && !well->wellIsStopped()) {
1678 continue;
1679 }
1680 const auto& cells = well->cells();
1681 const auto& rates = well->connectionRates();
1682 for (unsigned perfIdx = 0; perfIdx < rates.size(); ++perfIdx) {
1683 unsigned cellIdx = cells[perfIdx];
1684 auto rate = rates[perfIdx];
1685 rate *= -1.0;
1686 VectorBlockType res(0.0);
1687 using MatrixBlockType = typename SparseMatrixAdapter::MatrixBlock;
1688 MatrixBlockType bMat(0.0);
1689 simulator_.model().linearizer().setResAndJacobi(res, bMat, rate);
1690 residual[cellIdx] += res;
1691 *diagMatAddress[cellIdx] += bMat;
1692 }
1693 }
1694 }
1695
1696
1697 template<typename TypeTag>
1698 void
1701 {
1702 int nw = this->numLocalWellsEnd();
1703 int rdofs = local_num_cells_;
1704 const auto wellconnections = this->getMaxWellConnections();
1705 for (int i = 0; i < nw; ++i) {
1706 int wdof = rdofs + i;
1707 jacobian.entry(wdof,wdof) = 0.0;
1708 const auto& perfcells = wellconnections[i];
1709 for (int perfcell : perfcells) {
1710 jacobian.entry(wdof, perfcell) = 0.0;
1711 jacobian.entry(perfcell, wdof) = 0.0;
1712 }
1713 }
1714 }
1715
1716
1717 template<typename TypeTag>
1718 void
1721 {
1722 auto loggerGuard = this->groupStateHelper().pushLogger();
1724 {
1725 for (const auto& well : well_container_) {
1726 const auto& cells = well->cells();
1727 x_local_.resize(cells.size());
1728
1729 for (size_t i = 0; i < cells.size(); ++i) {
1730 x_local_[i] = x[cells[i]];
1731 }
1732 well->recoverWellSolutionAndUpdateWellState(simulator_, x_local_,
1733 this->groupStateHelper(), this->wellState());
1734 }
1735 }
1736 OPM_END_PARALLEL_TRY_CATCH("recoverWellSolutionAndUpdateWellState() failed: ",
1737 simulator_.vanguard().grid().comm());
1738 }
1739
1740
1741 template<typename TypeTag>
1742 void
1744 recoverWellSolutionAndUpdateWellStateDomain(const BVector& x, const int domainIdx)
1745 {
1746 if (!nldd_) {
1747 OPM_THROW(std::logic_error, "Attempt to call NLDD method without a NLDD solver");
1748 }
1749
1750 return nldd_->recoverWellSolutionAndUpdateWellState(x, domainIdx);
1751 }
1752
1753
1754 template<typename TypeTag>
1757 getWellConvergence(const std::vector<Scalar>& B_avg, bool checkWellGroupControlsAndNetwork) const
1758 {
1759 // Get global (from all processes) convergence report.
1760 ConvergenceReport local_report;
1761 const auto& iterCtx = simulator_.problem().iterationContext();
1762 const bool relaxTolerance = iterCtx.shouldRelax(param_.strict_outer_iter_wells_ + 1);
1763 {
1764 auto logger_guard = this->groupStateHelper().pushLogger();
1765 for (const auto& well : well_container_) {
1766 if (well->isOperableAndSolvable() || well->wellIsStopped()) {
1767 local_report += well->getWellConvergence(
1768 this->groupStateHelper(), B_avg,
1769 relaxTolerance);
1770 } else {
1771 ConvergenceReport report;
1772 using CR = ConvergenceReport;
1773 report.setWellFailed({CR::WellFailure::Type::Unsolvable, CR::Severity::Normal, -1, well->name()});
1774 local_report += report;
1775 }
1776 }
1777 } // logger_guard goes out of scope here, before the OpmLog::debug() calls below
1778
1779 const Opm::Parallel::Communication comm = grid().comm();
1780 ConvergenceReport report = gatherConvergenceReport(local_report, comm);
1781
1782 if (checkWellGroupControlsAndNetwork) {
1783 // the well_group_control_changed info is already communicated
1784 report.setWellGroupTargetsViolated(this->lastReport().well_group_control_changed);
1785 report.setNetworkNotYetBalancedForceAnotherNewtonIteration(network_needs_more_balancing_force_another_newton_iteration_);
1786 }
1787
1788 if (this->terminal_output_) {
1789 // Log debug messages for NaN or too large residuals.
1790 for (const auto& f : report.wellFailures()) {
1791 if (f.severity() == ConvergenceReport::Severity::NotANumber) {
1792 OpmLog::debug("NaN residual found with phase " + std::to_string(f.phase()) + " for well " + f.wellName());
1793 } else if (f.severity() == ConvergenceReport::Severity::TooLarge) {
1794 OpmLog::debug("Too large residual found with phase " + std::to_string(f.phase()) + " for well " + f.wellName());
1795 }
1796 }
1797 }
1798 return report;
1799 }
1800
1801
1802
1803
1804
1805 template<typename TypeTag>
1806 void
1809 {
1810 // TODO: checking isOperableAndSolvable() ?
1811 for (auto& well : well_container_) {
1812 well->calculateExplicitQuantities(simulator_, this->groupStateHelper());
1813 }
1814 }
1815
1816
1817
1818
1819
1820 template<typename TypeTag>
1821 bool
1823 updateWellControls(DeferredLogger& deferred_logger)
1824 {
1825 OPM_TIMEFUNCTION();
1826 if (!this->wellsActive() && !this->isReservoirCouplingMaster()) {
1827 return false;
1828 }
1829 const int episodeIdx = simulator_.episodeIndex();
1830 const auto& comm = simulator_.vanguard().grid().comm();
1831
1832 // Convert WELDRAW drawdown limits into maximum production rates.
1833 // Like the rate targets of wells under group control, these are
1834 // only updated during the first NUPCOL iterations of each timestep
1835 // and kept frozen for the remaining iterations.
1836 {
1837 const auto nupcol = this->schedule()[episodeIdx].nupcol();
1838 const auto& iter_ctx = simulator_.problem().iterationContext();
1839 if (iter_ctx.withinNupcol(nupcol)) {
1841 for (const auto& well : well_container_) {
1842 well->updateWeldrawMaxRate(simulator_, this->wellState(), deferred_logger);
1843 }
1844 OPM_END_PARALLEL_TRY_CATCH("BlackoilWellModel: updating WELDRAW rate limits failed: ",
1845 simulator_.gridView().comm());
1846 }
1847 }
1848
1849 size_t iter = 0;
1850 bool changed_well_group = false;
1851 const Group& fieldGroup = this->schedule().getGroup("FIELD", episodeIdx);
1852 // Check group individual constraints.
1853 // iterate a few times to make sure all constraints are honored
1854 const std::size_t max_iter = param_.well_group_constraints_max_iterations_;
1855 while(!changed_well_group && iter < max_iter) {
1856 changed_well_group = updateGroupControls(fieldGroup, deferred_logger, episodeIdx);
1857
1858 // Check wells' group constraints and communicate.
1859 bool changed_well_to_group = false;
1860 {
1861 OPM_TIMEBLOCK(UpdateWellControls);
1862 // For MS Wells a linear solve is performed below and the matrix might be singular.
1863 // We need to communicate the exception thrown to the others and rethrow.
1865 for (const auto& well : well_container_) {
1867 const bool changed_well = well->updateWellControl(
1868 simulator_, mode, this->groupStateHelper(), this->wellState()
1869 );
1870 if (changed_well) {
1871 changed_well_to_group = changed_well || changed_well_to_group;
1872 }
1873 }
1874 OPM_END_PARALLEL_TRY_CATCH("BlackoilWellModel: updating well controls failed: ",
1875 simulator_.gridView().comm());
1876 }
1877
1878 changed_well_to_group = comm.sum(static_cast<int>(changed_well_to_group));
1879 if (changed_well_to_group) {
1880 updateAndCommunicate(episodeIdx);
1881 changed_well_group = true;
1882 }
1883
1884 // Check individual well constraints and communicate.
1885 bool changed_well_individual = false;
1886 {
1887 // For MS Wells a linear solve is performed below and the matrix might be singular.
1888 // We need to communicate the exception thrown to the others and rethrow.
1890 for (const auto& well : well_container_) {
1892 const bool changed_well = well->updateWellControl(
1893 simulator_, mode, this->groupStateHelper(), this->wellState()
1894 );
1895 if (changed_well) {
1896 changed_well_individual = changed_well || changed_well_individual;
1897 }
1898 }
1899 OPM_END_PARALLEL_TRY_CATCH("BlackoilWellModel: updating well controls failed: ",
1900 simulator_.gridView().comm());
1901 }
1902
1903 changed_well_individual = comm.sum(static_cast<int>(changed_well_individual));
1904 if (changed_well_individual) {
1905 updateAndCommunicate(episodeIdx);
1906 changed_well_group = true;
1907 }
1908 iter++;
1909 }
1910
1911 // update wsolvent fraction for REIN wells
1912 this->updateWsolvent(fieldGroup, episodeIdx, this->nupcolWellState());
1913
1914 return changed_well_group;
1915 }
1916
1917
1918 template<typename TypeTag>
1919 void
1921 updateAndCommunicate(const int reportStepIdx)
1922 {
1923 this->updateAndCommunicateGroupData(reportStepIdx, /*update_wellgrouptarget*/ true);
1924
1925 // updateWellStateWithTarget might throw for multisegment wells hence we
1926 // have a parallel try catch here to thrown on all processes.
1928 // if a well or group change control it affects all wells that are under the same group
1929 for (const auto& well : well_container_) {
1930 // We only want to update wells under group-control here
1931 const auto& ws = this->wellState().well(well->indexOfWell());
1932 if (ws.production_cmode == Well::ProducerCMode::GRUP ||
1933 ws.injection_cmode == Well::InjectorCMode::GRUP)
1934 {
1935 well->updateWellStateWithTarget(
1936 simulator_, this->groupStateHelper(), this->wellState()
1937 );
1938 }
1939 }
1940 OPM_END_PARALLEL_TRY_CATCH("BlackoilWellModel::updateAndCommunicate failed: ",
1941 simulator_.gridView().comm())
1942 this->updateAndCommunicateGroupData(reportStepIdx, /*update_wellgrouptarget*/ true);
1943 }
1944
1945 template<typename TypeTag>
1946 bool
1948 updateGroupControls(const Group& group,
1949 DeferredLogger& deferred_logger,
1950 const int reportStepIdx)
1951 {
1952 OPM_TIMEFUNCTION();
1953 const auto& iterCtx = simulator_.problem().iterationContext();
1954 bool changed = false;
1955 // restrict the number of group switches but only after nupcol iterations.
1956 const int nupcol = this->schedule()[reportStepIdx].nupcol();
1957 const bool update_group_switching_log = !iterCtx.withinNupcol(nupcol);
1958 const bool changed_hc = this->checkGroupHigherConstraints(
1959 group, deferred_logger, reportStepIdx, update_group_switching_log);
1960 if (changed_hc) {
1961 changed = true;
1962 updateAndCommunicate(reportStepIdx);
1963 }
1964
1965 bool changed_individual =
1967 updateGroupIndividualControl(group,
1968 reportStepIdx,
1969 param_.max_number_of_group_switches_,
1970 update_group_switching_log,
1971 this->switched_inj_groups_,
1972 this->switched_prod_groups_,
1973 this->closed_offending_wells_,
1974 this->groupState(),
1975 this->wellState(),
1976 deferred_logger);
1977
1978 if (changed_individual) {
1979 changed = true;
1980 updateAndCommunicate(reportStepIdx);
1981 }
1982 // call recursively down the group hierarchy
1983 for (const std::string& groupName : group.groups()) {
1984 bool changed_this = updateGroupControls(this->schedule().getGroup(groupName, reportStepIdx), deferred_logger, reportStepIdx);
1985 changed = changed || changed_this;
1986 }
1987 return changed;
1988 }
1989
1990 template<typename TypeTag>
1991 void
1993 updateWellTestState(const double simulationTime, WellTestState& wellTestState)
1994 {
1995 OPM_TIMEFUNCTION();
1996 auto logger_guard = this->groupStateHelper().pushLogger();
1997 auto& local_deferredLogger = this->groupStateHelper().deferredLogger();
1998 for (const auto& well : well_container_) {
1999 const auto& wname = well->name();
2000 const auto wasClosed = wellTestState.well_is_closed(wname);
2001 well->checkWellOperability(simulator_,
2002 this->wellState(),
2003 this->groupStateHelper());
2004 const bool under_zero_target =
2005 well->wellUnderZeroGroupRateTarget(this->groupStateHelper());
2006 well->updateWellTestState(this->wellState().well(wname),
2007 simulationTime,
2008 /*writeMessageToOPMLog=*/ true,
2009 /*during_well_test=*/ false,
2010 under_zero_target,
2011 wellTestState,
2012 this->eclipseState().getUnits(),
2013 this->schedule().getStartTime(),
2014 local_deferredLogger);
2015
2016 if (!wasClosed && wellTestState.well_is_closed(wname)) {
2017 this->closed_this_step_.insert(wname);
2018
2019 // maybe open a new well
2020 const WellEconProductionLimits& econ_production_limits = well->wellEcl().getEconLimits();
2021 if (econ_production_limits.validFollowonWell()) {
2022 const auto episode_idx = simulator_.episodeIndex();
2023 const auto follow_on_well = econ_production_limits.followonWell();
2024 if (!this->schedule().hasWell(follow_on_well, episode_idx)) {
2025 const auto msg = fmt::format("Well {} was closed. But the given follow on well {} does not exist."
2026 "The simulator continues without opening a follow on well.",
2027 wname, follow_on_well);
2028 local_deferredLogger.warning(msg);
2029 }
2030 auto& ws = this->wellState().well(follow_on_well);
2031 const bool success = ws.updateStatus(WellStatus::OPEN);
2032 if (success) {
2033 const auto msg = fmt::format("Well {} was closed. The follow on well {} opens instead.", wname, follow_on_well);
2034 local_deferredLogger.info(msg);
2035 } else {
2036 const auto msg = fmt::format("Well {} was closed. The follow on well {} is already open.", wname, follow_on_well);
2037 local_deferredLogger.warning(msg);
2038 }
2039 }
2040
2041 }
2042 }
2043
2044 for (const auto& [group_name, to] : this->closed_offending_wells_) {
2045 if (this->hasOpenLocalWell(to.second) &&
2046 !this->wasDynamicallyShutThisTimeStep(to.second))
2047 {
2048 wellTestState.close_well(to.second,
2049 WellTestConfig::Reason::GROUP,
2050 simulationTime);
2051 this->updateClosedWellsThisStep(to.second);
2052 const std::string msg =
2053 fmt::format("Procedure on exceeding {} limit is WELL for group {}. "
2054 "Well {} is {}.",
2055 to.first,
2056 group_name,
2057 to.second,
2058 "shut");
2059 local_deferredLogger.info(msg);
2060 }
2061 }
2062 }
2063
2064
2065 template<typename TypeTag>
2066 void
2068 const WellState<Scalar, IndexTraits>& well_state_copy,
2069 std::string& exc_msg,
2070 ExceptionType::ExcEnum& exc_type)
2071 {
2072 OPM_TIMEFUNCTION();
2073 const int np = this->numPhases();
2074 std::vector<Scalar> potentials;
2075 const auto& well = well_container_[widx];
2076 std::string cur_exc_msg;
2077 auto cur_exc_type = ExceptionType::NONE;
2078 try {
2079 well->computeWellPotentials(simulator_, well_state_copy, this->groupStateHelper(), potentials);
2080 }
2081 // catch all possible exception and store type and message.
2082 OPM_PARALLEL_CATCH_CLAUSE(cur_exc_type, cur_exc_msg);
2083 if (cur_exc_type != ExceptionType::NONE) {
2084 exc_msg += fmt::format("\nFor well {}: {}", well->name(), cur_exc_msg);
2085 }
2086 exc_type = std::max(exc_type, cur_exc_type);
2087 // Store it in the well state
2088 // potentials is resized and set to zero in the beginning of well->ComputeWellPotentials
2089 // and updated only if sucessfull. i.e. the potentials are zero for exceptions
2090 auto& ws = this->wellState().well(well->indexOfWell());
2091 for (int p = 0; p < np; ++p) {
2092 // make sure the potentials are positive
2093 ws.well_potentials[p] = std::max(Scalar{0.0}, potentials[p]);
2094 }
2095 }
2096
2097
2098
2099 template <typename TypeTag>
2100 void
2103 {
2104 for (const auto& wellPtr : this->well_container_) {
2105 this->calculateProductivityIndexValues(wellPtr.get(), deferred_logger);
2106 }
2107 }
2108
2109
2110
2111
2112
2113 template <typename TypeTag>
2114 void
2116 calculateProductivityIndexValuesShutWells(const int reportStepIdx,
2117 DeferredLogger& deferred_logger)
2118 {
2119 // For the purpose of computing PI/II values, it is sufficient to
2120 // construct StandardWell instances only. We don't need to form
2121 // well objects that honour the 'isMultisegment()' flag of the
2122 // corresponding "this->wells_ecl_[shutWell]".
2123
2124 for (const auto& shutWell : this->local_shut_wells_) {
2125 if (!this->wells_ecl_[shutWell].hasConnections()) {
2126 // No connections in this well. Nothing to do.
2127 continue;
2128 }
2129
2130 auto wellPtr = this->template createTypedWellPointer
2131 <StandardWell<TypeTag>>(shutWell, reportStepIdx);
2132
2133 wellPtr->init(this->depth_, this->gravity_, this->B_avg_, true);
2134
2135 this->calculateProductivityIndexValues(wellPtr.get(), deferred_logger);
2136 }
2137 }
2138
2139
2140
2141
2142
2143 template <typename TypeTag>
2144 void
2147 DeferredLogger& deferred_logger)
2148 {
2149 wellPtr->updateProductivityIndex(this->simulator_,
2150 this->prod_index_calc_[wellPtr->indexOfWell()],
2151 this->wellState(),
2152 deferred_logger);
2153 }
2154
2155
2156
2157 template<typename TypeTag>
2158 void
2160 prepareTimeStep(DeferredLogger& deferred_logger)
2161 {
2162 const auto episodeIdx = simulator_.episodeIndex();
2163
2164 // Need to check this before clearing events
2165 const bool do_prestep_network_rebalance = this->shouldDoPreStepNetworkRebalance_(episodeIdx);
2166
2167 for (const auto& well : well_container_) {
2168 auto& events = this->wellState().well(well->indexOfWell()).events;
2169 if (events.hasEvent(WellState<Scalar, IndexTraits>::event_mask)) {
2170 well->updateWellStateWithTarget(
2171 simulator_, this->groupStateHelper(), this->wellState()
2172 );
2173 well->updatePrimaryVariables(this->groupStateHelper());
2174 // There is no new well control change input within a report step,
2175 // so next time step, the well does not consider to have effective events anymore.
2177 }
2178 // these events only work for the first time step within the report step
2179 if (events.hasEvent(ScheduleEvents::REQUEST_OPEN_WELL)) {
2180 events.clearEvent(ScheduleEvents::REQUEST_OPEN_WELL);
2181 }
2182 // solve the well equation initially to improve the initial solution of the well model
2183 if (param_.solve_welleq_initially_ && well->isOperableAndSolvable()) {
2184 try {
2185 well->solveWellEquation(
2186 simulator_, this->groupStateHelper(), this->wellState()
2187 );
2188 } catch (const std::exception& e) {
2189 const std::string msg = "Compute initial well solution for " + well->name() + " initially failed. Continue with the previous rates";
2190 deferred_logger.warning("WELL_INITIAL_SOLVE_FAILED", msg);
2191 }
2192 }
2193 // If we're using local well solves that include control switches, they also update
2194 // operability, so reset before main iterations begin
2195 well->resetWellOperability();
2196 }
2197 updatePrimaryVariables();
2198
2199 // Actually do the pre-step network rebalance, using the updated well states and initial solutions
2200 if (do_prestep_network_rebalance) {
2201 network_.doPreStepRebalance(deferred_logger);
2202 }
2203 }
2204
2205 template<typename TypeTag>
2206 void
2209 {
2210 std::vector< Scalar > B_avg(numConservationQuantities(), Scalar() );
2211 const auto& grid = simulator_.vanguard().grid();
2212 const auto& gridView = grid.leafGridView();
2213 ElementContext elemCtx(simulator_);
2214
2216 for (const auto& elem : elements(gridView, Dune::Partitions::interior)) {
2217 elemCtx.updatePrimaryStencil(elem);
2218 elemCtx.updatePrimaryIntensiveQuantities(/*timeIdx=*/0);
2219
2220 const auto& intQuants = elemCtx.intensiveQuantities(/*spaceIdx=*/0, /*timeIdx=*/0);
2221 const auto& fs = intQuants.fluidState();
2222
2223 for (unsigned phaseIdx = 0; phaseIdx < FluidSystem::numPhases; ++phaseIdx)
2224 {
2225 if (!FluidSystem::phaseIsActive(phaseIdx)) {
2226 continue;
2227 }
2228
2229 const unsigned compIdx = FluidSystem::canonicalToActiveCompIdx(FluidSystem::solventComponentIndex(phaseIdx));
2230 auto& B = B_avg[ compIdx ];
2231
2232 B += 1 / fs.invB(phaseIdx).value();
2233 }
2234 if constexpr (has_solvent_) {
2235 auto& B = B_avg[solventSaturationIdx];
2236 B += 1 / intQuants.solventInverseFormationVolumeFactor().value();
2237 }
2238 }
2239 OPM_END_PARALLEL_TRY_CATCH("BlackoilWellModel::updateAverageFormationFactor() failed: ", grid.comm())
2240
2241 // compute global average
2242 grid.comm().sum(B_avg.data(), B_avg.size());
2243 B_avg_.resize(B_avg.size());
2244 std::ranges::transform(B_avg, B_avg_.begin(),
2245 [gcells = global_num_cells_](const auto bval)
2246 { return bval / gcells; });
2247 }
2248
2249
2250
2251
2252
2253 template<typename TypeTag>
2254 void
2257 {
2258 for (const auto& well : well_container_) {
2259 well->updatePrimaryVariables(this->groupStateHelper());
2260 }
2261 }
2262
2263 template<typename TypeTag>
2264 void
2266 {
2267 const auto& grid = simulator_.vanguard().grid();
2268 const auto& eclProblem = simulator_.problem();
2269 const unsigned numCells = grid.size(/*codim=*/0);
2270
2271 this->pvt_region_idx_.resize(numCells);
2272 for (unsigned cellIdx = 0; cellIdx < numCells; ++cellIdx) {
2273 this->pvt_region_idx_[cellIdx] =
2274 eclProblem.pvtRegionIndex(cellIdx);
2275 }
2276 }
2277
2278 // The number of components in the model.
2279 template<typename TypeTag>
2280 int
2282 {
2283 // TODO: energy is also a conservation equation, so numConservationQuantities()
2284 // may need refactoring once it is enabled outside MSW.
2285
2286 // The numPhases() functions returns 1-3, depending on which
2287 // of the (oil, water, gas) phases are active. For each of those phases,
2288 // if the phase is active the corresponding component is present and
2289 // conserved.
2290 // Apart from (oil, water, gas), in the current well model only solvent
2291 // is explicitly modelled as a conserved quantity (polymer, energy, salt
2292 // etc. are not), unlike the reservoir part where all such quantities are
2293 // conserved. This function must therefore be updated when/if we add
2294 // more conserved quantities in the well model.
2295 return this->numPhases() + has_solvent_;
2296 }
2297
2298 template<typename TypeTag>
2299 void
2301 {
2302 const auto& eclProblem = simulator_.problem();
2303 depth_.resize(local_num_cells_);
2304 for (unsigned cellIdx = 0; cellIdx < local_num_cells_; ++cellIdx) {
2305 depth_[cellIdx] = eclProblem.dofCenterDepth(cellIdx);
2306 }
2307 }
2308
2309 template<typename TypeTag>
2312 getWell(const std::string& well_name) const
2313 {
2314 // finding the iterator of the well in wells_ecl
2315 const auto well =
2316 std::ranges::find_if(well_container_,
2317 [&well_name](const WellInterfacePtr& elem) -> bool
2318 { return elem->name() == well_name; });
2319
2320 assert(well != well_container_.end());
2321
2322 return **well;
2323 }
2324
2325 template <typename TypeTag>
2326 int
2328 reportStepIndex() const
2329 {
2330 return std::max(this->simulator_.episodeIndex(), 0);
2331 }
2332
2333
2334
2335
2336
2337 template<typename TypeTag>
2338 void
2340 calcResvCoeff(const int fipnum,
2341 const int pvtreg,
2342 const std::vector<Scalar>& production_rates,
2343 std::vector<Scalar>& resv_coeff) const
2344 {
2345 rateConverter_->calcCoeff(fipnum, pvtreg, production_rates, resv_coeff);
2346 }
2347
2348 template<typename TypeTag>
2349 void
2351 calcInjResvCoeff(const int fipnum,
2352 const int pvtreg,
2353 std::vector<Scalar>& resv_coeff) const
2354 {
2355 rateConverter_->calcInjCoeff(fipnum, pvtreg, resv_coeff);
2356 }
2357
2358
2359 template <typename TypeTag>
2360 void
2363 {
2364 if constexpr (energyModuleType_ == EnergyModules::FullyImplicitThermal) {
2365 const int np = this->numPhases();
2366 const int nw = this->numLocalWells();
2367 for (auto wellID = 0*nw; wellID < nw; ++wellID) {
2368 const Well& well = this->wells_ecl_[wellID];
2369 auto& ws = this->wellState().well(wellID);
2370 if (well.isInjector()) {
2371 if (ws.status != WellStatus::STOP) {
2372 this->wellState().well(wellID).temperature = well.inj_temperature();
2373 continue;
2374 }
2375 }
2376 std::array<Scalar,2> weighted{0.0,0.0};
2377 auto& [weighted_temperature, total_weight] = weighted;
2378 const auto& well_info = this->local_parallel_well_info_[wellID].get();
2379 using int_type = decltype(this->well_perf_data_[wellID].size());
2380 for (int_type perf = 0, end_perf = this->well_perf_data_[wellID].size(); perf < end_perf; ++perf) {
2381 const int cell_idx = this->well_perf_data_[wellID][perf].cell_index;
2382 const auto& intQuants = simulator_.model().intensiveQuantities(cell_idx, /*timeIdx=*/0);
2383 const auto& fs = intQuants.fluidState();
2384 Scalar weight_factor = computeTemperatureWeightFactor(perf, np, fs, ws);
2385 total_weight += weight_factor;
2386 weighted_temperature += weight_factor * fs.temperature(/*phaseIdx*/0).value();
2387 }
2388 well_info.communication().sum(weighted.data(), 2);
2389 this->wellState().well(wellID).temperature = weighted_temperature / total_weight;
2390 }
2391 }
2392 }
2393
2394
2395 template <typename TypeTag>
2396 [[nodiscard]] auto BlackoilWellModel<TypeTag>::rsConstInfo() const
2397 -> typename WellState<Scalar,IndexTraits>::RsConstInfo
2398 {
2399 if (! FluidSystem::phaseIsActive(FluidSystem::oilPhaseIdx) ||
2400 ! FluidSystem::enableConstantRs())
2401 {
2402 return {};
2403 }
2404
2405 const auto& rsConstTables = this->eclState_
2406 .getTableManager().getRsconstTables();
2407
2408 if (rsConstTables.empty() ||
2409 (rsConstTables[0].numRows() != std::size_t{1}))
2410 {
2411 return {};
2412 }
2413
2414 const auto rsConst = rsConstTables[0].getColumn(0).front();
2415
2416 return { true, static_cast<Scalar>(rsConst) };
2417 }
2418
2419 // Private helper methods (alphabetical order)
2420 // --------------------------------------------
2421
2422 template <typename TypeTag>
2423 void BlackoilWellModel<TypeTag>::
2424 assignWellTracerRates_(data::Wells& wsrpt) const
2425 {
2426 const auto reportStepIdx = static_cast<unsigned int>(this->reportStepIndex());
2427 const auto& trMod = this->simulator_.problem().tracerModel();
2428
2429 BlackoilWellModelGeneric<Scalar, IndexTraits>::assignWellTracerRates(wsrpt, trMod.getWellTracerRates(), reportStepIdx);
2430 BlackoilWellModelGeneric<Scalar, IndexTraits>::assignWellTracerRates(wsrpt, trMod.getWellFreeTracerRates(), reportStepIdx);
2431 BlackoilWellModelGeneric<Scalar, IndexTraits>::assignWellTracerRates(wsrpt, trMod.getWellSolTracerRates(), reportStepIdx);
2432
2433 this->assignMswTracerRates(wsrpt, trMod.getMswTracerRates(), reportStepIdx);
2434 }
2435
2436 template <typename TypeTag>
2437 void BlackoilWellModel<TypeTag>::
2438 assignWellSpeciesRates_(data::Wells& wsrpt) const
2439 {
2440 const auto reportStepIdx = static_cast<unsigned int>(this->reportStepIndex());
2441 const auto& geochemMod = this->simulator_.problem().geochemistryModel();
2442
2443 BlackoilWellModelGeneric<Scalar, IndexTraits>::assignWellTracerRates(wsrpt, geochemMod.getWellSpeciesRates(), reportStepIdx);
2444
2445 this->assignMswTracerRates(wsrpt, geochemMod.getMswSpeciesRates(), reportStepIdx);
2446 }
2447
2448 template <typename TypeTag>
2449 bool BlackoilWellModel<TypeTag>::isRescoupMasterCoupledNetworkIteration_() const
2450 {
2451#ifdef RESERVOIR_COUPLING_ENABLED
2452 return this->rescoupHelper_.masterIsInCoupledNetworkIteration();
2453#else
2454 return false;
2455#endif
2456 }
2457
2458 template <typename TypeTag>
2459 bool BlackoilWellModel<TypeTag>::isRescoupSlaveCoupledNetworkIteration_() const
2460 {
2461 // True when the slave is on the first substep of a sync step AND the
2462 // master has not yet signaled termination. Gates the per-iteration
2463 // master->slave node-pressure receive at the top of
2464 // updateWellControlsAndNetworkIteration(). The outer loop exit on
2465 // the slave is driven by the master's is_final flag (propagated to
2466 // local variable "more_network_update" at the end of updateWellControlsAndNetworkIteration(),
2467 // not by the slave's local network convergence. The master's own max_iter
2468 // bounds the iteration count from above, so the slave skips the local max_iter check entirely
2469 // and lets the master signal termination.
2470#ifdef RESERVOIR_COUPLING_ENABLED
2471 return this->isRescoupSlaveOnSyncStepFirstSubstep_()
2472 && this->reservoirCouplingSlave().connectedToMasterCoupledNetwork()
2473 && !this->reservoirCouplingSlave().lastReceivedMasterGroupNodePressuresIsFinal();
2474#else
2475 return false;
2476#endif
2477 }
2478
2479 template <typename TypeTag>
2480 bool BlackoilWellModel<TypeTag>::isRescoupSlaveOnSyncStepFirstSubstep_() const
2481 {
2482 // True when the slave is on the first substep of a sync step,
2483 // regardless of is_final state. Gates post-Newton handling at the
2484 // end of updateWellControlsAndNetworkIteration(), which must run on
2485 // the terminating iteration too (so the slave can set
2486 // more_network_update = false and exit its outer loop).
2487#ifdef RESERVOIR_COUPLING_ENABLED
2488 return this->isReservoirCouplingSlave()
2489 && this->reservoirCouplingSlave().isFirstSubstepOfSyncTimestep();
2490#else
2491 return false;
2492#endif
2493 }
2494
2495 template <typename TypeTag>
2496 bool BlackoilWellModel<TypeTag>::isRescoupSlaveConnectedToMasterNetwork_() const
2497 {
2498#ifdef RESERVOIR_COUPLING_ENABLED
2499 return this->isReservoirCouplingSlave()
2500 && this->reservoirCouplingSlave().connectedToMasterCoupledNetwork();
2501#else
2502 return false;
2503#endif
2504 }
2505
2506 template <typename TypeTag>
2507 bool BlackoilWellModel<TypeTag>::
2508 maybeSendSlaveGroupFlowToMaster_([[maybe_unused]] const int reportStepIdx)
2509 {
2510#ifdef RESERVOIR_COUPLING_ENABLED
2511 // For a rescoup slave: after the well-solve in
2512 // prepareWellsBeforeAssembling() has produced fresh rates under the
2513 // new THP, ship them back to the master and force one more outer
2514 // iteration so we re-enter updateWellControlsAndNetworkIteration() to receive the next pressures.
2515 // When the just-received message had is_final = true, we skip the
2516 // send and let the slave's outer loop exit naturally.
2517 assert(this->isReservoirCouplingSlave());
2518 const bool is_final =
2519 this->reservoirCouplingSlave().lastReceivedMasterGroupNodePressuresIsFinal();
2520 if (!is_final) {
2521 this->updateAndCommunicateGroupData(reportStepIdx, /*update_wellgrouptarget=*/false);
2522 this->rescoupHelper_.sendSlaveGroupDataToMaster();
2523 // The master turns the rates just sent into fresh injection targets
2524 // for the groups it controls through a derived GCONINJE mode, and
2525 // sends them straight back. See
2526 // BlackoilWellModelRescoup::refreshAndSendInjectionTargets_().
2527 this->rescoupHelper_.receiveGroupConstraintsFromMaster();
2528 // The targets in force, and the UDQs built on them, follow suit.
2529 this->rescoupHelper_.refreshSlaveGroupInjectionTargets();
2530 return /*more_network_update=*/true;
2531 }
2532 return /*more_network_update=*/false;
2533#else
2534 return /*more_network_update=*/false;
2535#endif
2536 }
2537
2538 template <typename TypeTag>
2539 void BlackoilWellModel<TypeTag>::
2540 sendSlaveNetworkLoopTerminationSignal_()
2541 {
2542#ifdef RESERVOIR_COUPLING_ENABLED
2543 // When the master's outer loop exits without having sent is_final = true (e.g. max_iter
2544 // exceeded with the network still unconverged), the slave is stuck
2545 // waiting on its next receive. Fire one final pressure send to
2546 // unblock it.
2547 assert(this->isReservoirCouplingMaster());
2548 this->rescoupHelper_.sendMasterGroupNodePressuresToSlaves(/*is_final=*/true);
2549#endif
2550 }
2551
2552 template <typename TypeTag>
2553 bool BlackoilWellModel<TypeTag>::
2554 shouldDoPreStepNetworkRebalance_(const int episodeIdx) const
2555 {
2556 // Rebalance the network initially if any wells in the network have status changes
2557 //
2558 // The rebalance is skipped only for *coupled-network participants*: its
2559 // inner updateWellControlsAndNetwork call would run the cross-rescoup
2560 // pressure/rate exchange, but needPreStepRebalance is collectivised only
2561 // over the local OPM communicator -- not across the rescoup boundary --
2562 // so a coupled master and slave may disagree on whether to enter the
2563 // rebalance, deadlocking the exchange. A non-participant (a master with
2564 // no master-group network leaves, or a slave not connected to the master
2565 // network) does no cross-rescoup MPI in the network solve, so it is safe
2566 // to rebalance like a standalone process and we no longer skip it.
2567 return param_.pre_solve_network_
2568 && this->network_.needPreStepRebalance(episodeIdx)
2569 && !this->isRescoupCoupledNetworkParticipant_();
2570 }
2571
2572 template <typename TypeTag>
2573 bool BlackoilWellModel<TypeTag>::isRescoupCoupledNetworkParticipant_() const
2574 {
2575#ifdef RESERVOIR_COUPLING_ENABLED
2576 if (this->isReservoirCouplingMaster()) {
2577 return this->rescoupHelper_.masterNetworkHasMasterGroupLeaves();
2578 }
2579 if (this->isReservoirCouplingSlave()) {
2580 return this->reservoirCouplingSlave().connectedToMasterCoupledNetwork();
2581 }
2582 return false;
2583#else
2584 return false;
2585#endif
2586 }
2587
2588 template <typename TypeTag>
2589 void BlackoilWellModel<TypeTag>::
2590 updateNetworkActiveState_()
2591 {
2592 // Refresh the network's cached `active_` flag once per timestep
2593 // init. updateActiveState's inputs (Schedule network, well list,
2594 // per-well groupName/predictionMode, and rescoup master groups)
2595 // are constant within a substep; ACTIONX-driven well structure
2596 // changes propagate via wellStructureChangedDynamically_ at the
2597 // top of beginTimeStep, before the first assemble() of the new
2598 // substep. Doing this in assemble() rather than only in
2599 // prepareTimeStep() covers the case of a rescoup master with no
2600 // local wells, where prepareTimeStep() is skipped (gated on wellsActive()).
2601 const int episodeIdx = this->simulator_.episodeIndex();
2602 this->network_.updateActiveState(episodeIdx);
2603 }
2604
2605} // namespace Opm
2606
2607#endif // OPM_BLACKOILWELLMODEL_IMPL_HEADER_INCLUDED
#define OPM_END_PARALLEL_TRY_CATCH_LOG(obptc_logger, obptc_prefix, obptc_output, comm)
Catch exception, log, and throw in a parallel try-catch clause.
Definition: DeferredLoggingErrorHelpers.hpp:207
#define OPM_DEFLOG_THROW(Exception, message, deferred_logger)
Definition: DeferredLoggingErrorHelpers.hpp:47
#define OPM_END_PARALLEL_TRY_CATCH(prefix, comm)
Catch exception and throw in a parallel try-catch clause.
Definition: DeferredLoggingErrorHelpers.hpp:197
#define OPM_PARALLEL_CATCH_CLAUSE(obptc_exc_type, obptc_exc_msg)
Inserts catch classes for the parallel try-catch.
Definition: DeferredLoggingErrorHelpers.hpp:168
#define OPM_BEGIN_PARALLEL_TRY_CATCH()
Macro to setup the try of a parallel try-catch.
Definition: DeferredLoggingErrorHelpers.hpp:160
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:113
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:100
std::vector< std::unique_ptr< ParallelWellInfo< Scalar > > > parallel_well_info_
Definition: BlackoilWellModelGeneric.hpp:640
void updateFailed()
Restore the state captured at the start of the failing timestep.
Definition: BlackoilWellModelGeneric.hpp:241
void advanceTimeLevel()
Snapshot the mutable well-model state at the start of a timestep.
Definition: BlackoilWellModelGeneric.hpp:228
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:101
void initializeGroupStructure(const int reportStepIdx)
Definition: BlackoilWellModel_impl.hpp:308
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:2340
void prepareTimeStep(DeferredLogger &deferred_logger)
Definition: BlackoilWellModel_impl.hpp:2160
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:1403
WellInterfacePtr createWellPointer(const int wellID, const int report_step) const
Definition: BlackoilWellModel_impl.hpp:1126
void prepareWellsBeforeAssembling(const double dt)
Definition: BlackoilWellModel_impl.hpp:1526
void init()
Definition: BlackoilWellModel_impl.hpp:166
const Simulator & simulator() const
Definition: BlackoilWellModel.hpp:390
std::vector< Scalar > depth_
Definition: BlackoilWellModel.hpp:600
std::size_t global_num_cells_
Definition: BlackoilWellModel.hpp:596
GetPropType< TypeTag, Properties::Scalar > Scalar
Definition: BlackoilWellModel.hpp:110
void initWellContainer(const int reportStepIdx) override
Definition: BlackoilWellModel_impl.hpp:185
void beginReportStep(const int time_step)
Definition: BlackoilWellModel_impl.hpp:202
const WellInterface< TypeTag > & getWell(const std::string &well_name) const
Definition: BlackoilWellModel_impl.hpp:2312
GetPropType< TypeTag, Properties::FluidSystem > FluidSystem
Definition: BlackoilWellModel.hpp:106
Dune::FieldVector< Scalar, numEq > VectorBlockType
Definition: BlackoilWellModel.hpp:134
GetPropType< TypeTag, Properties::ElementContext > ElementContext
Definition: BlackoilWellModel.hpp:107
GetPropType< TypeTag, Properties::Grid > Grid
Definition: BlackoilWellModel.hpp:104
int numConservationQuantities() const
Definition: BlackoilWellModel_impl.hpp:2281
bool updateWellControls(DeferredLogger &deferred_logger)
Definition: BlackoilWellModel_impl.hpp:1823
int reportStepIndex() const
Definition: BlackoilWellModel_impl.hpp:2328
void calculateProductivityIndexValues(DeferredLogger &deferred_logger) override
Definition: BlackoilWellModel_impl.hpp:2102
void extractLegacyDepth_()
Definition: BlackoilWellModel_impl.hpp:2300
void extractLegacyCellPvtRegionIndex_()
Definition: BlackoilWellModel_impl.hpp:2265
void recoverWellSolutionAndUpdateWellStateDomain(const BVector &x, const int domainIdx)
Definition: BlackoilWellModel_impl.hpp:1744
void updateAverageFormationFactor()
Definition: BlackoilWellModel_impl.hpp:2208
GetPropType< TypeTag, Properties::Simulator > Simulator
Definition: BlackoilWellModel.hpp:109
BlackoilWellModel(Simulator &simulator, const NewtonIterationContext &iter_ctx)
Definition: BlackoilWellModel_impl.hpp:73
void initializeWellState(const int timeStepIdx)
Definition: BlackoilWellModel_impl.hpp:828
const Grid & grid() const
Definition: BlackoilWellModel.hpp:387
void updatePrimaryVariables()
Definition: BlackoilWellModel_impl.hpp:2256
void computeWellTemperature()
Definition: BlackoilWellModel_impl.hpp:2362
void addWellPressureEquations(PressureMatrix &jacobian, const BVector &weights, const bool use_well_weights) const
Definition: BlackoilWellModel_impl.hpp:1648
const SimulatorReportSingle & lastReport() const
Definition: BlackoilWellModel_impl.hpp:688
bool updateWellControlsAndNetwork(const bool mandatory_network_balance, const double dt, DeferredLogger &local_deferredLogger)
Definition: BlackoilWellModel_impl.hpp:1337
void addWellContributions(SparseMatrixAdapter &jacobian) const
Definition: BlackoilWellModel_impl.hpp:1625
void assembleWellEq(const double dt)
Definition: BlackoilWellModel_impl.hpp:1514
WellInterfacePtr createWellForWellTest(const std::string &well_name, const int report_step, DeferredLogger &deferred_logger) const
Definition: BlackoilWellModel_impl.hpp:1177
void calculateExplicitQuantities() const
Definition: BlackoilWellModel_impl.hpp:1808
void collectWellSolveStats()
Definition: BlackoilWellModel_impl.hpp:1292
void updateAndCommunicate(const int reportStepIdx)
Definition: BlackoilWellModel_impl.hpp:1921
Dune::BCRSMatrix< Opm::MatrixBlock< Scalar, 1, 1 > > PressureMatrix
Definition: BlackoilWellModel.hpp:309
void updateFailed()
Definition: BlackoilWellModel_impl.hpp:597
void computeTotalRatesForDof(RateVector &rate, unsigned globalIdx) const
Definition: BlackoilWellModel_impl.hpp:791
void stashWellSolveStats()
Definition: BlackoilWellModel_impl.hpp:1308
void beginTimeStep()
Definition: BlackoilWellModel_impl.hpp:340
GetPropType< TypeTag, Properties::RateVector > RateVector
Definition: BlackoilWellModel.hpp:111
bool updateGroupControls(const Group &group, DeferredLogger &deferred_logger, const int reportStepIdx)
Definition: BlackoilWellModel_impl.hpp:1948
void initializeLocalWellStructure(const int reportStepIdx, const bool enableWellPIScaling, const bool initializeWellState)
Definition: BlackoilWellModel_impl.hpp:254
void calcInjResvCoeff(const int fipnum, const int pvtreg, std::vector< Scalar > &resv_coeff) const override
Definition: BlackoilWellModel_impl.hpp:2351
Dune::BlockVector< VectorBlockType > BVector
Definition: BlackoilWellModel.hpp:135
void wellTesting(const int timeStepIdx, const double simulationTime, DeferredLogger &deferred_logger)
Definition: BlackoilWellModel_impl.hpp:612
ConvergenceReport getWellConvergence(const std::vector< Scalar > &B_avg, const bool checkWellGroupControlsAndNetwork=false) const
Definition: BlackoilWellModel_impl.hpp:1757
typename FluidSystem::IndexTraitsType IndexTraits
Definition: BlackoilWellModel.hpp:117
void updateCellRatesForDomain(int domainIndex, const std::map< std::string, int > &well_domain_map)
Definition: BlackoilWellModel_impl.hpp:1572
void assembleWellEqWithoutIteration(const double dt)
Definition: BlackoilWellModel_impl.hpp:1540
void updateCellRates()
Definition: BlackoilWellModel_impl.hpp:1560
void assemble(const double dt)
Definition: BlackoilWellModel_impl.hpp:1202
std::size_t local_num_cells_
Definition: BlackoilWellModel.hpp:598
bool alternative_well_rate_init_
Definition: BlackoilWellModel.hpp:601
void timeStepSucceeded(const double simulationTime, const double dt)
Definition: BlackoilWellModel_impl.hpp:698
std::unique_ptr< WellType > createTypedWellPointer(const int wellID, const int time_step) const
Definition: BlackoilWellModel_impl.hpp:1146
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:2067
Simulator & simulator_
Definition: BlackoilWellModel.hpp:570
void createWellContainer(const int report_step) override
Definition: BlackoilWellModel_impl.hpp:871
std::unique_ptr< WellInterface< TypeTag > > WellInterfacePtr
Definition: BlackoilWellModel.hpp:195
void updateWellTestState(const double simulationTime, WellTestState &wellTestState)
upate the wellTestState related to economic limits
Definition: BlackoilWellModel_impl.hpp:1993
void addBCDMatrix(std::vector< BMatrix > &b_matrices, std::vector< CMatrix > &c_matrices, std::vector< DMatrix > &d_matrices, Opm::SparseTable< int > &wcells) const
Definition: BlackoilWellModel_impl.hpp:1634
void addSolveStats(const WellInterface< TypeTag > &well)
Definition: BlackoilWellModel_impl.hpp:1318
void addReservoirSourceTerms(GlobalEqVector &residual, const std::vector< typename SparseMatrixAdapter::MatrixBlock * > &diagMatAddress) const
Definition: BlackoilWellModel_impl.hpp:1670
int compressedIndexForInterior(int cartesian_cell_idx) const override
get compressed index for interior cells (-1, otherwise
Definition: BlackoilWellModel.hpp:362
void recoverWellSolutionAndUpdateWellState(const BVector &x)
Definition: BlackoilWellModel_impl.hpp:1720
void addWellPressureEquationsStruct(PressureMatrix &jacobian) const
Definition: BlackoilWellModel_impl.hpp:1700
void calculateProductivityIndexValuesShutWells(const int reportStepIdx, DeferredLogger &deferred_logger) override
Definition: BlackoilWellModel_impl.hpp:2116
void advanceTimeLevel()
Definition: BlackoilWellModel_impl.hpp:605
void endReportStep()
Definition: BlackoilWellModel_impl.hpp:671
Definition: ConvergenceReport.hpp:38
void setWellFailed(const WellFailure &wf)
Definition: ConvergenceReport.hpp:296
void setWellGroupTargetsViolated(const bool wellGroupTargetsViolated)
Definition: ConvergenceReport.hpp:314
const std::vector< WellFailure > & wellFailures() const
Definition: ConvergenceReport.hpp:459
void setNetworkNotYetBalancedForceAnotherNewtonIteration(const bool network_needs_more_balancing_force_another_newton_iteration)
Definition: ConvergenceReport.hpp:319
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
Class encapsulating some information about parallel wells.
Definition: ParallelWellInfo.hpp:217
Definition: StandardWell.hpp:55
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:77
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)
const WellSolveStats & solveStats() const
Definition: WellInterfaceGeneric.hpp:293
void resetSolveStats() const
Definition: WellInterfaceGeneric.hpp:294
int indexOfWell() const
Index of well in the wells struct and wellState.
Definition: WellInterface.hpp:79
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:192
Definition: WellState.hpp:68
if(!linsolver_)
Definition: FlexibleSolver_impl.hpp:326
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)
#define RESERVOIR_COUPLING_ENABLED
Definition: simulator.hh:32
Context for iteration-dependent decisions in the Newton solver.
Definition: NewtonIterationContext.hpp:43
A struct for returning timing data from a simulator to its caller.
Definition: SimulatorReport.hpp:34