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 .intensiveQuantities(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_.refreshSlaveGroupTargets();
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 // The master recomputes the constraints from the solved rates.
574 this->rescoupHelper_.receiveRefreshedGroupConstraintsFromMaster();
575 }
576 else if (this->isReservoirCouplingMaster()) {
577 if (this->reservoirCouplingMaster().isFirstSubstepOfSyncTimestep()) {
578 this->rescoupHelper_.sendMasterGroupConstraintsToSlaves();
579 this->rescoupHelper_.sendCoupledNetworkActiveStatus();
580 this->rescoupHelper_.receiveSlaveGroupData();
581 // The rates just received are solved for this sync step, the
582 // ones the constraints above were computed from were not.
583 this->rescoupHelper_.refreshAndSendGroupConstraints();
584 }
585 }
586#endif
587
588 if (exc_type != ExceptionType::NONE) {
589 const std::string msg = "Compute initial well solution for new wells failed. Continue with zero initial rates";
590 local_deferredLogger.warning("WELL_INITIAL_SOLVE_FAILED", msg);
591 }
592
593 const auto& comm = simulator_.vanguard().grid().comm();
594 logAndCheckForExceptionsAndThrow(local_deferredLogger,
595 exc_type, "beginTimeStep() failed: " + exc_msg, this->terminal_output_, comm);
596
597 }
598
599 template<typename TypeTag>
600 void
603 {
605 }
606
607 template<typename TypeTag>
608 void
611 {
613 }
614
615 template<typename TypeTag>
616 void
618 const double simulationTime,
619 DeferredLogger& deferred_logger)
620 {
621 for (const std::string& well_name : this->getWellsForTesting(timeStepIdx, simulationTime)) {
622 const Well& wellEcl = this->schedule().getWell(well_name, timeStepIdx);
623 if (wellEcl.getStatus() == Well::Status::SHUT)
624 continue;
625
626 WellInterfacePtr well = createWellForWellTest(well_name, timeStepIdx, deferred_logger);
627 // some preparation before the well can be used
628 well->init(depth_, gravity_, B_avg_, true);
629
630 Scalar well_efficiency_factor = wellEcl.getEfficiencyFactor() *
631 this->wellState().getGlobalEfficiencyScalingFactor(well_name);
632 this->groupStateHelper().accumulateGroupEfficiencyFactor(
633 this->schedule().getGroup(wellEcl.groupName(), timeStepIdx),
634 well_efficiency_factor
635 );
636
637 well->setWellEfficiencyFactor(well_efficiency_factor);
638 well->setVFPProperties(this->vfp_properties_.get());
639 well->setGuideRate(&this->guideRate_);
640
641 // initialize rates/previous rates to prevent zero fractions in vfp-interpolation
642 if (well->isProducer() && alternative_well_rate_init_) {
643 well->initializeProducerWellState(simulator_, this->wellState(), deferred_logger);
644 }
645 if (well->isVFPActive(deferred_logger)) {
646 well->setPrevSurfaceRates(this->wellState(), this->prevWellState());
647 }
648
649 this->network_.initializeWell(*well);
650
651 try {
652 using GLiftEclWells = typename GasLiftGroupInfo<Scalar, IndexTraits>::GLiftEclWells;
653 GLiftEclWells ecl_well_map;
654 gaslift_.initGliftEclWellMap(well_container_, ecl_well_map);
655 well->wellTesting(simulator_,
656 simulationTime,
657 this->groupStateHelper(),
658 this->wellState(),
659 this->wellTestState(),
660 ecl_well_map,
661 this->well_open_times_);
662 } catch (const std::exception& e) {
663 const std::string msg =
664 fmt::format(fmt::runtime("Exception during testing of well: {}. The well will not open.\n"
665 "Exception message: {}"), wellEcl.name(), e.what());
666 deferred_logger.warning("WELL_TESTING_FAILED", msg);
667 }
668 // The tested well is a temporary; keep its solve statistics.
669 addSolveStats(*well);
670 }
671 }
672
673 // called at the end of a report step
674 template<typename TypeTag>
675 void
678 {
679 // Clear the communication data structures for above values.
680 for (auto&& pinfo : this->local_parallel_well_info_)
681 {
682 pinfo.get().clear();
683 }
684 }
685
686
687
688
689
690 // called at the end of a report step
691 template<typename TypeTag>
694 lastReport() const {return last_report_; }
695
696
697
698
699
700 // called at the end of a time step
701 template<typename TypeTag>
702 void
704 timeStepSucceeded(const double simulationTime, const double dt)
705 {
706 this->closed_this_step_.clear();
707
708 // time step is finished and we are not any more at the beginning of an report step
709 this->report_step_starts_ = false;
710 const int reportStepIdx = simulator_.episodeIndex();
711
712 auto logger_guard = this->groupStateHelper().pushLogger();
713 auto& local_deferredLogger = this->groupStateHelper().deferredLogger();
714 for (const auto& well : well_container_) {
715 if (getPropValue<TypeTag, Properties::EnablePolymerMW>() && well->isInjector()) {
716 well->updateWaterThroughput(dt, this->wellState());
717 }
718 }
719 // update connection transmissibility factor and d factor (if applicable) in the wellstate
720 for (const auto& well : well_container_) {
721 well->updateConnectionTransmissibilityFactor(simulator_, this->wellState().well(well->indexOfWell()));
722 well->updateConnectionDFactor(simulator_, this->wellState().well(well->indexOfWell()));
723 }
724
725 if (Indices::waterEnabled) {
726 if constexpr (getPropValue<TypeTag, Properties::EnableMech>()) {
727 // Split injector connection flow between matrix and fracture
728 // for wells with registered fracture contributions.
729 updateWellFractureFlowSplit<FluidSystem, Scalar>(
730 this->simulator_, this->well_container_,
731 this->wellState(), this->nupcolWellState());
732 }
733 this->updateFiltrationModelsPostStep(dt, FluidSystem::waterPhaseIdx, local_deferredLogger);
734 }
735
736 // WINJMULT: At the end of the time step, update the inj_multiplier saved in WellState for later use
737 this->updateInjMult(local_deferredLogger);
738
739 // report well switching
740 for (const auto& well : well_container_) {
741 well->reportWellSwitching(this->wellState().well(well->indexOfWell()), local_deferredLogger);
742 }
743 // report group switching
744 if (this->terminal_output_) {
745 this->reportGroupSwitching(local_deferredLogger);
746 }
747
748 // update the rate converter with current averages pressures etc in
749 rateConverter_->template defineState<ElementContext>(simulator_);
750
751 // calculate the well potentials
752 try {
753 this->updateWellPotentials(reportStepIdx,
754 /*onlyAfterEvent*/false,
755 simulator_.vanguard().summaryConfig(),
756 local_deferredLogger);
757 } catch ( std::runtime_error& e ) {
758 const std::string msg = "A zero well potential is returned for output purposes. ";
759 local_deferredLogger.warning("WELL_POTENTIAL_CALCULATION_FAILED", msg);
760 }
761
762 // simulationTime is the start of the step that has just been completed,
763 // but a well shut by the economic or physical limit checks below keeps
764 // flowing until its end. Record that instant as the closure time, so
765 // the WTEST re-test countdown starts when the well actually stops.
766 const double closure_time = simulationTime + dt;
767
768 updateWellTestState(closure_time, this->wellTestState());
769
770 // check group sales limits at the end of the timestep
771 const Group& fieldGroup = this->schedule_.getGroup("FIELD", reportStepIdx);
772 this->checkGEconLimits(fieldGroup, closure_time,
773 simulator_.episodeIndex(), local_deferredLogger);
774 this->checkGconsaleLimits(fieldGroup, this->wellState(),
775 simulator_.episodeIndex(), local_deferredLogger);
776
777 this->well_performance_event_tracker_.accumulate(this->wellStatusSnapshot());
778
779 this->calculateProductivityIndexValues(local_deferredLogger);
780
781 this->groupStateHelper().updateNONEProductionGroups();
782
783#ifdef RESERVOIR_COUPLING_ENABLED
784 this->rescoupHelper_.rescoupSyncSummaryData();
785#endif
786 this->well_performance_event_tracker_.commitTimeStep(this->schedule(), reportStepIdx);
787 this->commitWGState();
788
789 //reporting output temperatures
790 this->computeWellTemperature();
791 }
792
793
794 template<typename TypeTag>
795 void
798 unsigned elemIdx) const
799 {
800 rate = 0;
801
802 if (!is_cell_perforated_[elemIdx] || cellRates_.count(elemIdx) == 0) {
803 return;
804 }
805
806 rate = cellRates_.at(elemIdx);
807 }
808
809
810 template<typename TypeTag>
811 template <class Context>
812 void
815 const Context& context,
816 unsigned spaceIdx,
817 unsigned timeIdx) const
818 {
819 rate = 0;
820 int elemIdx = context.globalSpaceIndex(spaceIdx, timeIdx);
821
822 if (!is_cell_perforated_[elemIdx] || cellRates_.count(elemIdx) == 0) {
823 return;
824 }
825
826 rate = cellRates_.at(elemIdx);
827 }
828
829
830
831 template<typename TypeTag>
832 void
834 initializeWellState(const int timeStepIdx)
835 {
836 const auto pressIx = []()
837 {
838 if (Indices::oilEnabled) { return FluidSystem::oilPhaseIdx; }
839 if (Indices::waterEnabled) { return FluidSystem::waterPhaseIdx; }
840
841 return FluidSystem::gasPhaseIdx;
842 }();
843
844 auto cellPressures = std::vector<Scalar>(this->local_num_cells_, Scalar{0});
845 auto cellTemperatures = std::vector<Scalar>(this->local_num_cells_, Scalar{0});
846
847 auto elemCtx = ElementContext { this->simulator_ };
848 const auto& gridView = this->simulator_.vanguard().gridView();
849
851 for (const auto& elem : elements(gridView, Dune::Partitions::interior)) {
852 elemCtx.updatePrimaryStencil(elem);
853 elemCtx.updatePrimaryIntensiveQuantities(/*timeIdx=*/0);
854
855 const auto ix = elemCtx.globalSpaceIndex(/*spaceIdx=*/0, /*timeIdx=*/0);
856 const auto& fs = elemCtx.intensiveQuantities(/*spaceIdx=*/0, /*timeIdx=*/0).fluidState();
857
858 cellPressures[ix] = fs.pressure(pressIx).value();
859 cellTemperatures[ix] = fs.temperature(0).value();
860 }
861 OPM_END_PARALLEL_TRY_CATCH("BlackoilWellModel::initializeWellState() failed: ",
862 this->simulator_.vanguard().grid().comm());
863
864 this->wellState().init(cellPressures, cellTemperatures, this->schedule(), this->wells_ecl_,
865 this->local_parallel_well_info_, timeStepIdx,
866 &this->prevWellState(), this->well_perf_data_,
867 this->summaryState(), simulator_.vanguard().enableDistributedWells());
868 }
869
870
871
872
873
874 template<typename TypeTag>
875 void
877 createWellContainer(const int report_step)
878 {
879 auto logger_guard = this->groupStateHelper().pushLogger();
880 auto& local_deferredLogger = this->groupStateHelper().deferredLogger();
881
882 const int nw = this->numLocalWells();
883
884 well_container_.clear();
885
886 if (nw > 0) {
887 well_container_.reserve(nw);
888
889 const auto& wmatcher = this->schedule().wellMatcher(report_step);
890 const auto& wcycle = this->schedule()[report_step].wcycle.get();
891
892 // First loop and check for status changes. This is necessary
893 // as wcycle needs the updated open/close times.
894 std::ranges::for_each(this->wells_ecl_,
895 [this, &wg_events = this->report_step_start_events_](const auto& well_ecl)
896 {
897 if (!well_ecl.hasConnections()) {
898 // No connections in this well. Nothing to do.
899 return;
900 }
901
902 constexpr auto events_mask = ScheduleEvents::WELL_STATUS_CHANGE |
903 ScheduleEvents::REQUEST_OPEN_WELL |
904 ScheduleEvents::REQUEST_SHUT_WELL;
905 const bool well_event =
906 this->report_step_starts_ &&
907 wg_events.hasEvent(well_ecl.name(), events_mask);
908 // WCYCLE is suspendended by explicit SHUT events by the user.
909 // and restarted after explicit OPEN events.
910 // Note: OPEN or SHUT event does not necessary mean the well
911 // actually opened or shut at this point as the simulator could
912 // have done this by operabilty checks and well testing. This
913 // may need further testing and imply code changes to cope with
914 // these corner cases.
915 if (well_event) {
916 if (well_ecl.getStatus() == WellStatus::OPEN) {
917 this->well_open_times_.insert_or_assign(well_ecl.name(),
918 this->simulator_.time());
919 this->well_close_times_.erase(well_ecl.name());
920 } else if (well_ecl.getStatus() == WellStatus::SHUT) {
921 this->well_close_times_.insert_or_assign(well_ecl.name(),
922 this->simulator_.time());
923 this->well_open_times_.erase(well_ecl.name());
924 }
925 }
926 });
927
928 // Grab wcycle states. This needs to run before the schedule gets processed
929 const auto cycle_states = wcycle.wellStatus(this->simulator_.time(),
930 wmatcher,
931 this->well_open_times_,
932 this->well_close_times_);
933
934 for (int w = 0; w < nw; ++w) {
935 const Well& well_ecl = this->wells_ecl_[w];
936
937 if (!well_ecl.hasConnections()) {
938 // No connections in this well. Nothing to do.
939 continue;
940 }
941
942 const std::string& well_name = well_ecl.name();
943 const auto well_status = this->schedule()
944 .getWell(well_name, report_step).getStatus();
945
946 const bool shut_event = this->wellState().well(w).events.hasEvent(ScheduleEvents::WELL_STATUS_CHANGE)
947 && well_status == Well::Status::SHUT;
948 const bool open_event = this->wellState().well(w).events.hasEvent(ScheduleEvents::WELL_STATUS_CHANGE)
949 && well_status == Well::Status::OPEN;
950 const auto& ws = this->wellState().well(well_name);
951
952 if (shut_event && ws.status != Well::Status::SHUT) {
953 this->closed_this_step_.insert(well_name);
954 this->wellState().shutWell(w);
955 } else if (open_event && ws.status != Well::Status::OPEN) {
956 this->wellState().openWell(w);
957 }
958
959 // A new WCON keywords can re-open a well that was closed/shut due to Physical limit
960 if (this->wellTestState().well_is_closed(well_name)) {
961 // The well was shut this timestep, we are most likely retrying
962 // a timestep without the well in question, after it caused
963 // repeated timestep cuts. It should therefore not be opened,
964 // even if it was new or received new targets this report step.
965 //
966 // The time stamp alone cannot establish that, since a shut-in
967 // decided at the *end* of the previous step carries that
968 // step's end time, which coincides with the current step's
969 // start time. Such shut-ins are the ones a new WCON keyword
970 // may undo, and are exactly what wasDynamicallyShutThisTimeStep()
971 // reports; mid-step ones from forceShutWellByName() are not
972 // registered there, so they still block the re-open.
973 const bool closed_this_step =
974 (this->wellTestState().lastTestTime(well_name) == simulator_.time()) &&
975 !this->wasDynamicallyShutThisTimeStep(well_name);
976 // TODO: more checking here, to make sure this standard more specific and complete
977 // maybe there is some WCON keywords will not open the well
978 auto& events = this->wellState().well(w).events;
979 if (events.hasEvent(ScheduleEvents::REQUEST_OPEN_WELL)) {
980 if (!closed_this_step) {
981 this->wellTestState().open_well(well_name);
982 this->wellTestState().open_completions(well_name);
983 this->well_open_times_.insert_or_assign(well_name,
984 this->simulator_.time());
985 this->well_close_times_.erase(well_name);
986 }
987 events.clearEvent(ScheduleEvents::REQUEST_OPEN_WELL);
988 }
989 }
990
991 // WELOPEN/COMPDAT can reopen individual connections shut at run
992 // time by physical/economic limits, without touching the rest
993 // of the well. Act only when the well is open (a SHUT well
994 // would not flow) and the schedule changed completions this
995 // step (global COMPLETION_CHANGE, set by both COMPDAT and
996 // WELOPEN).
997 auto& well_test_state = this->wellTestState();
998 const auto& sched_state = this->schedule()[report_step];
999 const bool may_reopen_completions =
1000 ws.status == Well::Status::OPEN &&
1001 sched_state.events().hasEvent(ScheduleEvents::COMPLETION_CHANGE) &&
1002 well_test_state.num_closed_completions() > 0;
1003
1004 if (may_reopen_completions) {
1005 const auto& completion_events = sched_state.wellcompletion_events();
1006 for (const auto& connection : well_ecl.getConnections()) {
1007 const int complnum = connection.complnum();
1008
1009 // Reopen only connections currently shut at run time
1010 // that are explicitly requested OPEN this step.
1011 if (!well_test_state.completion_is_closed(well_name, complnum) ||
1012 !completion_events.hasEvent(well_name, complnum, ScheduleEvents::REQUEST_OPEN_COMPLETION)) {
1013 continue;
1014 }
1015
1016 // ... but not one closed during the current timestep
1017 const bool closed_this_step =
1018 (well_test_state.lastCompletionCloseTime(well_name, complnum) == simulator_.time());
1019 if (closed_this_step) {
1020 continue;
1021 }
1022
1023 well_test_state.open_completion(well_name, complnum);
1024 local_deferredLogger.info(
1025 fmt::format("Completion {} - block ({}, {}, {}) for well {} "
1026 "is reopened due to an explicit WELOPEN/COMPDAT "
1027 "OPEN request",
1028 complnum,
1029 connection.getI() + 1,
1030 connection.getJ() + 1,
1031 connection.getK() + 1,
1032 well_name));
1033 }
1034 }
1035
1036 // TODO: should we do this for all kinds of closing reasons?
1037 // something like wellTestState().hasWell(well_name)?
1038 if (this->wellTestState().well_is_closed(well_name))
1039 {
1040 if (this->closedWellStatus(well_ecl) == WellStatus::SHUT)
1041 {
1042 this->wellState().shutWell(w);
1043 this->well_close_times_.erase(well_name);
1044 this->well_open_times_.erase(well_name);
1045 continue;
1046 }
1047 // stopped wells are added to the container but marked as stopped
1048 this->wellState().stopWell(w);
1049 }
1050
1051 // shut wells with zero rante constraints and disallowing
1052 if (!well_ecl.getAllowCrossFlow()) {
1053 const bool any_zero_rate_constraint = well_ecl.isProducer()
1054 ? well_ecl.productionControls(this->summaryState_).anyZeroRateConstraint()
1055 : well_ecl.injectionControls(this->summaryState_).anyZeroRateConstraint();
1056 if (any_zero_rate_constraint) {
1057 // Treat as shut, do not add to container.
1058 local_deferredLogger.debug(fmt::format(fmt::runtime(" Well {} gets shut due to having zero rate constraint and disallowing crossflow "), well_ecl.name()));
1059 this->wellState().shutWell(w);
1060 this->well_close_times_.erase(well_name);
1061 this->well_open_times_.erase(well_name);
1062 continue;
1063 }
1064 }
1065
1066 if (!wcycle.empty()) {
1067 const auto it = cycle_states.find(well_name);
1068 if (it != cycle_states.end()) {
1069 if (!it->second || well_status == Well::Status::SHUT) {
1070 // If well is shut in schedule we keep it shut
1071 if (well_status == Well::Status::SHUT) {
1072 this->well_open_times_.erase(well_name);
1073 this->well_close_times_.erase(well_name);
1074 }
1075 this->wellState().shutWell(w);
1076 continue;
1077 } else {
1078 this->wellState().openWell(w);
1079 }
1080 }
1081 }
1082
1083 // We dont add SHUT wells to the container
1084 if (ws.status == Well::Status::SHUT) {
1085 continue;
1086 }
1087
1088 well_container_.emplace_back(this->createWellPointer(w, report_step));
1089
1090 if (ws.status == Well::Status::STOP) {
1091 well_container_.back()->stopWell();
1092 this->well_close_times_.erase(well_name);
1093 this->well_open_times_.erase(well_name);
1094 }
1095 }
1096
1097 if (!wcycle.empty()) {
1098 const auto schedule_open =
1099 [&wg_events = this->report_step_start_events_](const std::string& name)
1100 {
1101 return wg_events.hasEvent(name, ScheduleEvents::REQUEST_OPEN_WELL);
1102 };
1103 for (const auto& [wname, wscale] : wcycle.efficiencyScale(this->simulator_.time(),
1104 this->simulator_.timeStepSize(),
1105 wmatcher,
1106 this->well_open_times_,
1107 schedule_open))
1108 {
1109 this->wellState().updateEfficiencyScalingFactor(wname, wscale);
1110 this->schedule_.add_event(ScheduleEvents::WELLGROUP_EFFICIENCY_UPDATE, report_step);
1111 }
1112 }
1113 }
1114
1115 this->well_container_generic_.clear();
1116 for (auto& w : well_container_) {
1117 this->well_container_generic_.push_back(w.get());
1118 }
1119
1120 this->network_.initialize(report_step);
1121
1122 this->wbp_.registerOpenWellsForWBPCalculation();
1123 }
1124
1125
1126
1127
1128
1129 template <typename TypeTag>
1132 createWellPointer(const int wellID, const int report_step) const
1133 {
1134 const auto is_multiseg = this->wells_ecl_[wellID].isMultiSegment();
1135
1136 if (! (this->param_.use_multisegment_well_ && is_multiseg)) {
1137 return this->template createTypedWellPointer<StandardWell<TypeTag>>(wellID, report_step);
1138 }
1139 else {
1140 return this->template createTypedWellPointer<MultisegmentWell<TypeTag>>(wellID, report_step);
1141 }
1142 }
1143
1144
1145
1146
1147
1148 template <typename TypeTag>
1149 template <typename WellType>
1150 std::unique_ptr<WellType>
1152 createTypedWellPointer(const int wellID, const int time_step) const
1153 {
1154 // Use the pvtRegionIdx from the top cell
1155 const auto& perf_data = this->well_perf_data_[wellID];
1156
1157 // Cater for case where local part might have no perforations.
1158 const auto pvtreg = perf_data.empty()
1159 ? 0 : this->pvt_region_idx_[perf_data.front().cell_index];
1160
1161 const auto& parallel_well_info = this->local_parallel_well_info_[wellID].get();
1162 const auto global_pvtreg = parallel_well_info.broadcastFirstPerforationValue(pvtreg);
1163
1164 return std::make_unique<WellType>(this->wells_ecl_[wellID],
1165 parallel_well_info,
1166 time_step,
1167 this->param_,
1168 *this->rateConverter_,
1169 global_pvtreg,
1170 this->numConservationQuantities(),
1171 this->numPhases(),
1172 wellID,
1173 perf_data);
1174 }
1175
1176
1177
1178
1179
1180 template<typename TypeTag>
1183 createWellForWellTest(const std::string& well_name,
1184 const int report_step,
1185 DeferredLogger& deferred_logger) const
1186 {
1187 // Finding the location of the well in wells_ecl
1188 const auto it =
1189 std::ranges::find_if(this->wells_ecl_,
1190 [&well_name](const auto& w)
1191 { return well_name == w.name(); });
1192 // It should be able to find in wells_ecl.
1193 if (it == this->wells_ecl_.end()) {
1194 OPM_DEFLOG_THROW(std::logic_error,
1195 fmt::format(fmt::runtime("Could not find well {} in wells_ecl"), well_name),
1196 deferred_logger);
1197 }
1198
1199 const int pos = static_cast<int>(std::distance(this->wells_ecl_.begin(), it));
1200 return this->createWellPointer(pos, report_step);
1201 }
1202
1203
1204
1205 template<typename TypeTag>
1206 void
1208 assemble(const double dt)
1209 {
1210 OPM_TIMEFUNCTION();
1211 auto logger_guard = this->groupStateHelper().pushLogger();
1212 auto& local_deferredLogger = this->groupStateHelper().deferredLogger();
1213
1214 const auto& iterCtx = simulator_.problem().iterationContext();
1215
1217 if (gaslift_.terminalOutput()) {
1218 const std::string msg =
1219 fmt::format(fmt::runtime("assemble() : iteration {}"), iterCtx.iteration());
1220 gaslift_.gliftDebug(msg, local_deferredLogger);
1221 }
1222 }
1223 last_report_ = SimulatorReportSingle();
1224 Dune::Timer perfTimer;
1225 perfTimer.start();
1226 this->closed_offending_wells_.clear();
1227
1228 {
1229 if (iterCtx.needsTimestepInit()) {
1230 this->updateNetworkActiveState_();
1231 }
1232 const int episodeIdx = simulator_.episodeIndex();
1233 if (!this->wellsActive() && !details::anyNetworkActive(this->schedule(), episodeIdx)) {
1234 return;
1235 }
1236 }
1237
1238 // Timestep initialization: should run once at the start of each timestep.
1239 if (iterCtx.needsTimestepInit() && this->wellsActive()) {
1240 OPM_TIMEBLOCK(firstIterationAssemble);
1241 Dune::Timer prepareTimer;
1242 prepareTimer.start();
1243 // try-catch is needed here as updateWellControls
1244 // contains global communication and has either to
1245 // be reached by all processes or all need to abort
1246 // before.
1248 {
1249 calculateExplicitQuantities();
1250 prepareTimeStep(local_deferredLogger);
1251 }
1252 OPM_END_PARALLEL_TRY_CATCH_LOG(local_deferredLogger,
1253 "assemble() failed during well initialization: ",
1254 this->terminal_output_, grid().comm());
1255 last_report_.well_facility_time += prepareTimer.stop();
1256 }
1257
1258 Dune::Timer networkTimer;
1259 networkTimer.start();
1260 const bool well_group_control_changed = updateWellControlsAndNetwork(
1261 /*mandatory_network_balance=*/false,
1262 dt,
1263 local_deferredLogger);
1264 // the control/network update is part of the facility calculations,
1265 // together with the time step preparation of the wells above
1266 const double network_time = networkTimer.stop();
1267 last_report_.well_control_network_time += network_time;
1268 last_report_.well_facility_time += network_time;
1269
1270 // even when there is no wells active, the network nodal pressure still need to be updated through updateWellControlsAndNetwork()
1271 // but there is no need to assemble the well equations
1272 if ( ! this->wellsActive() ) {
1273 return;
1274 }
1275
1276 assembleWellEqWithoutIteration(dt);
1277 // Pre-compute cell rates to we don't have to do this for every cell during linearization...
1278 updateCellRates();
1279
1280 // collect the statistics for the standalone well solves done since
1281 // the last assembly (prepareTimeStep, well testing and well
1282 // potential calculations)
1283 collectWellSolveStats();
1284
1285 // if group or well control changes we don't consider the
1286 // case converged
1287 last_report_.well_group_control_changed = well_group_control_changed;
1288 last_report_.assemble_time_well += perfTimer.stop();
1289 }
1290
1291
1292
1293
1294 template<typename TypeTag>
1295 void
1298 {
1299 stashWellSolveStats();
1300 const auto& stats = pending_solve_stats_;
1301 last_report_.well_solve_time += stats.solve_time;
1302 last_report_.well_potential_solve_time += stats.potential_solve_time;
1303 last_report_.well_solve_assemble_time += stats.assemble_time;
1304 last_report_.well_solve_linear_solve_time += stats.linear_solve_time;
1305 last_report_.total_well_iterations += stats.iterations;
1306 last_report_.total_well_potential_iterations += stats.potential_iterations;
1307 pending_solve_stats_ = {};
1308 }
1309
1310 template<typename TypeTag>
1311 void
1314 {
1315 for (const auto& well : well_container_) {
1316 addSolveStats(*well);
1317 }
1318 }
1319
1320 template<typename TypeTag>
1321 void
1324 {
1325 auto& pending = pending_solve_stats_;
1326 const auto& stats = well.solveStats();
1327 pending.solve_time += stats.solve_time;
1328 pending.potential_solve_time += stats.potential_solve_time;
1329 pending.assemble_time += stats.assemble_time;
1330 pending.linear_solve_time += stats.linear_solve_time;
1331 pending.iterations += stats.iterations;
1332 pending.potential_iterations += stats.potential_iterations;
1333 well.resetSolveStats();
1334 }
1335
1336
1337
1338
1339 template<typename TypeTag>
1340 bool
1342 updateWellControlsAndNetwork(const bool mandatory_network_balance,
1343 const double dt,
1344 DeferredLogger& local_deferredLogger)
1345 {
1346 OPM_TIMEFUNCTION();
1347 // not necessarily that we always need to update once of the network solutions
1348 bool do_network_update = true;
1349 bool well_group_control_changed = false;
1350 Scalar network_imbalance = 0.0;
1351 // after certain number of the iterations, we use relaxed tolerance for the network update
1352 const std::size_t iteration_to_relax = param_.network_max_strict_outer_iterations_;
1353 // after certain number of the iterations, we terminate
1354 const std::size_t max_iteration = param_.network_max_outer_iterations_;
1355 std::size_t network_update_iteration = 0;
1356 network_needs_more_balancing_force_another_newton_iteration_ = false;
1357 while (do_network_update) {
1358 if (!this->isRescoupSlaveCoupledNetworkIteration_()
1359 && network_update_iteration >= max_iteration ) {
1360 const int episodeIdx = simulator_.episodeIndex();
1361 const auto& balance = this->schedule()[episodeIdx].network_balance();
1362 // If the imbalance is already within tolerance, the network is converged; the
1363 // outer loop continued only due to ALQ or control changes. Don't report this
1364 // as an unconverged result -- just break quietly.
1365 if (network_imbalance <= balance.pressure_tolerance()) {
1366 break;
1367 }
1368 // only output to terminal if we at the last newton iterations where we try to balance the network.
1369 if (this->network_.willBalanceOnNextIteration(episodeIdx)) {
1370 if (this->terminal_output_) {
1371 const std::string msg = fmt::format("Maximum of {:d} network iterations has been used and we stop the update, \n"
1372 "and try again after the next Newton iteration (imbalance = {:.2e} bar)",
1373 max_iteration, network_imbalance*1.0e-5);
1374 local_deferredLogger.debug(msg);
1375 }
1376 // To avoid stopping the newton iterations too early, before the network is converged,
1377 // we need to report it
1378 network_needs_more_balancing_force_another_newton_iteration_ = true;
1379 } else {
1380 if (this->terminal_output_) {
1381 const std::string msg = fmt::format("Maximum of {:d} network iterations has been used and we stop the update. \n"
1382 "The simulator will continue with unconverged network results (imbalance = {:.2e} bar)",
1383 max_iteration, network_imbalance*1.0e-5);
1384 local_deferredLogger.info(msg);
1385 }
1386 }
1387 break;
1388 }
1389 if (this->terminal_output_ && (network_update_iteration == iteration_to_relax) ) {
1390 local_deferredLogger.debug("We begin using relaxed tolerance for network update now after " + std::to_string(iteration_to_relax) + " iterations ");
1391 }
1392 const bool relax_network_balance = network_update_iteration >= iteration_to_relax;
1393 // Never optimize gas lift in last iteration, to allow network convergence (unless max_iter < 2)
1394 const bool optimize_gas_lift = ( (network_update_iteration + 1) < std::max(max_iteration, static_cast<std::size_t>(2)) );
1395 std::tie(well_group_control_changed, do_network_update, network_imbalance) =
1396 updateWellControlsAndNetworkIteration(mandatory_network_balance, relax_network_balance, optimize_gas_lift, dt,local_deferredLogger);
1397 ++network_update_iteration;
1398 }
1399 if (this->isRescoupMasterCoupledNetworkIteration_()) {
1400 this->sendSlaveNetworkLoopTerminationSignal_();
1401 }
1402 // only count the balancing iterations when a network is active
1403 if (this->schedule()[simulator_.episodeIndex()].network().active()) {
1404 last_report_.total_network_iterations += network_update_iteration;
1405 }
1406 return well_group_control_changed;
1407 }
1408
1409
1410
1411
1412 template<typename TypeTag>
1413 std::tuple<bool, bool, typename BlackoilWellModel<TypeTag>::Scalar>
1415 updateWellControlsAndNetworkIteration(const bool mandatory_network_balance,
1416 const bool relax_network_tolerance,
1417 const bool optimize_gas_lift,
1418 const double dt,
1419 DeferredLogger& local_deferredLogger)
1420 {
1421 OPM_TIMEFUNCTION();
1422 const int reportStepIdx = simulator_.episodeIndex();
1423
1424#ifdef RESERVOIR_COUPLING_ENABLED
1425 if (this->isRescoupSlaveCoupledNetworkIteration_()) {
1426 this->rescoupHelper_.receiveMasterGroupNodePressuresFromMaster();
1427 }
1428#endif
1429 Dune::Timer groupTimer;
1430 groupTimer.start();
1431 this->updateAndCommunicateGroupData(reportStepIdx, /*update_wellgrouptarget*/ true);
1432 // We need to call updateWellControls before we update the network as
1433 // network updates are only done on thp controlled wells.
1434 // Note that well controls are allowed to change during updateNetwork
1435 // and in prepareWellsBeforeAssembling during well solves.
1436 bool well_group_control_changed = updateWellControls(local_deferredLogger);
1437 last_report_.group_control_time += groupTimer.stop();
1438
1439 Dune::Timer networkBalanceTimer;
1440 networkBalanceTimer.start();
1441 const auto [more_inner_network_update, network_imbalance] =
1442 this->network_.update(mandatory_network_balance,
1443 local_deferredLogger,
1444 relax_network_tolerance);
1445 // only account for the time when a network is active
1446 if (this->schedule()[reportStepIdx].network().active()) {
1447 last_report_.network_balance_time += networkBalanceTimer.stop();
1448 }
1449#ifdef RESERVOIR_COUPLING_ENABLED
1450 if (this->isReservoirCouplingMaster()) {
1451 this->rescoupHelper_.maybeExchangeNetworkOuterIterationWithSlaves(more_inner_network_update);
1452 }
1453#endif
1454
1455 bool alq_updated = false;
1457 {
1458 if (optimize_gas_lift) {
1459 // we need to update the potentials if the thp limit as been modified by
1460 // the network balancing
1461 const bool updatePotentials = (this->network_.shouldBalance(reportStepIdx) ||
1462 mandatory_network_balance);
1463 Dune::Timer gliftTimer;
1464 gliftTimer.start();
1465 alq_updated = gaslift_.maybeDoGasLiftOptimize(simulator_,
1466 well_container_,
1467 this->network_.nodePressures(),
1468 updatePotentials,
1469 this->wellState(),
1470 this->groupState(),
1471 local_deferredLogger);
1472 // only account for the time when gas lift optimization is in use
1473 if (this->schedule().glo(reportStepIdx).active()) {
1474 last_report_.gaslift_time += gliftTimer.stop();
1475 }
1476 }
1477 // the well solves triggered by control changes are part of the
1478 // control/network update, keep track of the time separately
1479 Dune::Timer prepareWellsTimer;
1480 prepareWellsTimer.start();
1481 prepareWellsBeforeAssembling(dt);
1482 last_report_.control_well_solve_time += prepareWellsTimer.stop();
1483 }
1484 OPM_END_PARALLEL_TRY_CATCH_LOG(local_deferredLogger,
1485 "updateWellControlsAndNetworkIteration() failed: ",
1486 this->terminal_output_, grid().comm());
1487
1488 // update guide rates
1489 if (alq_updated || BlackoilWellModelGuideRates(*this).
1490 guideRateUpdateIsNeeded(reportStepIdx)) {
1491 const double simulationTime = simulator_.time();
1492 Dune::Timer guideRateTimer;
1493 guideRateTimer.start();
1494 // NOTE: For reservoir coupling: Slave group potentials are only communicated
1495 // at the start of the time step, see beginTimeStep(). Here, we assume those
1496 // potentials remain unchanged during the time step when updating guide rates below.
1497 this->guide_rate_handler_.updateGuideRates(
1498 reportStepIdx, simulationTime, this->wellState(), this->groupState()
1499 );
1500 last_report_.group_control_time += guideRateTimer.stop();
1501 }
1502 // we need to re-iterate the network when the well group controls changed or gaslift/alq is changed or
1503 // the inner iterations are did not converge
1504 bool more_network_update = this->network_.shouldBalance(reportStepIdx) &&
1505 (more_inner_network_update || alq_updated);
1506
1507 if (this->isRescoupSlaveOnSyncStepFirstSubstep_()
1508 && this->isRescoupSlaveConnectedToMasterNetwork_()) {
1509 // Connected slave: the call ships this slave's flow to the master
1510 // and reports whether the cross-rescoup exchange continues. OR
1511 // with the local decision so a connected slave that also has its
1512 // own network keeps iterating it. A slave not connected to the
1513 // master network skips this branch entirely and runs purely on its
1514 // local more_network_update.
1515 const bool more_cross_rescoup_update =
1516 this->maybeSendSlaveGroupFlowToMaster_(reportStepIdx);
1517 more_network_update = more_network_update || more_cross_rescoup_update;
1518 }
1519
1520 return {well_group_control_changed, more_network_update, network_imbalance};
1521 }
1522
1523 template<typename TypeTag>
1524 void
1526 assembleWellEq(const double dt)
1527 {
1528 OPM_TIMEFUNCTION();
1529 for (auto& well : well_container_) {
1530 well->assembleWellEq(simulator_, dt, this->groupStateHelper(), this->wellState());
1531 }
1532 }
1533
1534
1535 template<typename TypeTag>
1536 void
1538 prepareWellsBeforeAssembling(const double dt)
1539 {
1540 OPM_TIMEFUNCTION();
1541 for (auto& well : well_container_) {
1542 well->prepareWellBeforeAssembling(
1543 simulator_, dt, this->groupStateHelper(), this->wellState()
1544 );
1545 }
1546 }
1547
1548
1549 template<typename TypeTag>
1550 void
1552 assembleWellEqWithoutIteration(const double dt)
1553 {
1554 OPM_TIMEFUNCTION();
1555 auto& deferred_logger = this->groupStateHelper().deferredLogger();
1556 // We make sure that all processes throw in case there is an exception
1557 // on one of them (WetGasPvt::saturationPressure might throw if not converged)
1559
1560 for (auto& well: well_container_) {
1561 well->assembleWellEqWithoutIteration(simulator_, this->groupStateHelper(), dt, this->wellState(),
1562 /*solving_with_zero_rate=*/false);
1563 }
1564 OPM_END_PARALLEL_TRY_CATCH_LOG(deferred_logger, "BlackoilWellModel::assembleWellEqWithoutIteration failed: ",
1565 this->terminal_output_, grid().comm());
1566
1567 }
1568
1569 template<typename TypeTag>
1570 void
1573 {
1574 // Pre-compute cell rates for all wells
1575 cellRates_.clear();
1576 for (const auto& well : well_container_) {
1577 well->addCellRates(cellRates_);
1578 }
1579 }
1580
1581 template<typename TypeTag>
1582 void
1584 updateCellRatesForDomain(int domainIndex, const std::map<std::string, int>& well_domain_map)
1585 {
1586 // Pre-compute cell rates only for wells in the specified domain
1587 cellRates_.clear();
1588 for (const auto& well : well_container_) {
1589 const auto it = well_domain_map.find(well->name());
1590 if (it != well_domain_map.end() && it->second == domainIndex) {
1591 well->addCellRates(cellRates_);
1592 }
1593 }
1594 }
1595
1596 template<typename TypeTag>
1597 void
1600 const std::map<std::string, int>& well_domain_map,
1601 const std::vector<int>& domain_cells,
1602 const std::vector<bool>& interior)
1603 {
1604 // A well owned by another domain keeps its current connection
1605 // rates while this domain is solved, like any other value outside
1606 // the domain's owned cells.
1607 const auto in_overlap = [&domain_cells, &interior](const int cell)
1608 {
1609 return !interior[cell] && std::ranges::binary_search(domain_cells, cell);
1610 };
1611 for (const auto& well : well_container_) {
1612 const auto it = well_domain_map.find(well->name());
1613 if (it != well_domain_map.end() && it->second != domainIndex) {
1614 well->addConstantCellRates(cellRates_, in_overlap);
1615 }
1616 }
1617 }
1618
1619#if COMPILE_GPU_BRIDGE
1620 template<typename TypeTag>
1621 void
1624 {
1625 // prepare for StandardWells
1627
1628 for(unsigned int i = 0; i < well_container_.size(); i++){
1629 auto& well = well_container_[i];
1630 auto derived = dynamic_cast<StandardWell<TypeTag>*>(well.get());
1631 if (derived) {
1632 wellContribs.addNumBlocks(derived->linSys().getNumBlocks());
1633 }
1634 }
1635
1636 // allocate memory for data from StandardWells
1637 wellContribs.alloc();
1638
1639 for(unsigned int i = 0; i < well_container_.size(); i++){
1640 auto& well = well_container_[i];
1641 // maybe WellInterface could implement addWellContribution()
1642 auto derived_std = dynamic_cast<StandardWell<TypeTag>*>(well.get());
1643 if (derived_std) {
1644 derived_std->linSys().extract(derived_std->numStaticWellEq, wellContribs);
1645 } else {
1646 auto derived_ms = dynamic_cast<MultisegmentWell<TypeTag>*>(well.get());
1647 if (derived_ms) {
1648 derived_ms->linSys().extract(wellContribs);
1649 } else {
1650 OpmLog::warning("Warning unknown type of well");
1651 }
1652 }
1653 }
1654 }
1655#endif
1656
1657 template<typename TypeTag>
1658 void
1660 addWellContributions(SparseMatrixAdapter& jacobian) const
1661 {
1662 for ( const auto& well: well_container_ ) {
1663 well->addWellContributions(jacobian);
1664 }
1665 }
1666
1667 template<typename TypeTag>
1668 void
1669 BlackoilWellModel<TypeTag>::addBCDMatrix(std::vector<BMatrix>& b_matrices,
1670 std::vector<CMatrix>& c_matrices,
1671 std::vector<DMatrix>& d_matrices,
1672 Opm::SparseTable<int>& wcells) const
1673 {
1674 wcells.clear();
1675 for ( const auto& well: well_container_ ) {
1676 well->addBCDMatrix(b_matrices, c_matrices, d_matrices, wcells);
1677 }
1678 }
1679
1680 template<typename TypeTag>
1681 void
1684 const BVector& weights,
1685 const bool use_well_weights,
1686 const bool contract_d_diagonal) const
1687 {
1688 int nw = this->numLocalWellsEnd();
1689 int rdofs = local_num_cells_;
1690 for ( int i = 0; i < nw; i++ ) {
1691 int wdof = rdofs + i;
1692 jacobian[wdof][wdof] = 1.0;// better scaling ?
1693 }
1694
1695 for (const auto& well : well_container_) {
1696 well->addWellPressureEquations(jacobian,
1697 weights,
1698 pressureVarIndex,
1699 use_well_weights,
1700 contract_d_diagonal,
1701 this->wellState());
1702 }
1703 }
1704
1705 template <typename TypeTag>
1707 addReservoirSourceTerms(GlobalEqVector& residual,
1708 const std::vector<typename SparseMatrixAdapter::MatrixBlock*>& diagMatAddress) const
1709 {
1710 // NB this loop may write multiple times to the same element
1711 // if a cell is perforated by more than one well, so it should
1712 // not be OpenMP-parallelized.
1713 for (const auto& well : well_container_) {
1714 if (!well->isOperableAndSolvable() && !well->wellIsStopped()) {
1715 continue;
1716 }
1717 const auto& cells = well->cells();
1718 const auto& rates = well->connectionRates();
1719 for (unsigned perfIdx = 0; perfIdx < rates.size(); ++perfIdx) {
1720 unsigned cellIdx = cells[perfIdx];
1721 auto rate = rates[perfIdx];
1722 rate *= -1.0;
1723 VectorBlockType res(0.0);
1724 using MatrixBlockType = typename SparseMatrixAdapter::MatrixBlock;
1725 MatrixBlockType bMat(0.0);
1726 simulator_.model().linearizer().setResAndJacobi(res, bMat, rate);
1727 residual[cellIdx] += res;
1728 *diagMatAddress[cellIdx] += bMat;
1729 }
1730 }
1731 }
1732
1733
1734 template<typename TypeTag>
1735 void
1738 {
1739 int nw = this->numLocalWellsEnd();
1740 int rdofs = local_num_cells_;
1741 const auto wellconnections = this->getMaxWellConnections();
1742 for (int i = 0; i < nw; ++i) {
1743 int wdof = rdofs + i;
1744 jacobian.entry(wdof,wdof) = 0.0;
1745 const auto& perfcells = wellconnections[i];
1746 for (int perfcell : perfcells) {
1747 jacobian.entry(wdof, perfcell) = 0.0;
1748 jacobian.entry(perfcell, wdof) = 0.0;
1749 }
1750 }
1751 }
1752
1753
1754 template<typename TypeTag>
1755 void
1758 {
1759 auto loggerGuard = this->groupStateHelper().pushLogger();
1761 {
1762 for (const auto& well : well_container_) {
1763 const auto& cells = well->cells();
1764 x_local_.resize(cells.size());
1765
1766 for (size_t i = 0; i < cells.size(); ++i) {
1767 x_local_[i] = x[cells[i]];
1768 }
1769 well->recoverWellSolutionAndUpdateWellState(simulator_, x_local_,
1770 this->groupStateHelper(), this->wellState());
1771 }
1772 }
1773 OPM_END_PARALLEL_TRY_CATCH("recoverWellSolutionAndUpdateWellState() failed: ",
1774 simulator_.vanguard().grid().comm());
1775 }
1776
1777
1778 template<typename TypeTag>
1779 void
1781 recoverWellSolutionAndUpdateWellStateDomain(const BVector& x, const int domainIdx)
1782 {
1783 if (!nldd_) {
1784 OPM_THROW(std::logic_error, "Attempt to call NLDD method without a NLDD solver");
1785 }
1786
1787 return nldd_->recoverWellSolutionAndUpdateWellState(x, domainIdx);
1788 }
1789
1790
1791 template<typename TypeTag>
1794 getWellConvergence(const std::vector<Scalar>& B_avg, bool checkWellGroupControlsAndNetwork) const
1795 {
1796 // Get global (from all processes) convergence report.
1797 ConvergenceReport local_report;
1798 const auto& iterCtx = simulator_.problem().iterationContext();
1799 const bool relaxTolerance = iterCtx.shouldRelax(param_.strict_outer_iter_wells_ + 1);
1800 {
1801 auto logger_guard = this->groupStateHelper().pushLogger();
1802 for (const auto& well : well_container_) {
1803 if (well->isOperableAndSolvable() || well->wellIsStopped()) {
1804 local_report += well->getWellConvergence(
1805 this->groupStateHelper(), B_avg,
1806 relaxTolerance);
1807 } else {
1808 ConvergenceReport report;
1809 using CR = ConvergenceReport;
1810 report.setWellFailed({CR::WellFailure::Type::Unsolvable, CR::Severity::Normal, -1, well->name()});
1811 local_report += report;
1812 }
1813 }
1814 } // logger_guard goes out of scope here, before the OpmLog::debug() calls below
1815
1816 const Opm::Parallel::Communication comm = grid().comm();
1817 ConvergenceReport report = gatherConvergenceReport(local_report, comm);
1818
1819 if (checkWellGroupControlsAndNetwork) {
1820 // the well_group_control_changed info is already communicated
1821 report.setWellGroupTargetsViolated(this->lastReport().well_group_control_changed);
1822 report.setNetworkNotYetBalancedForceAnotherNewtonIteration(network_needs_more_balancing_force_another_newton_iteration_);
1823 }
1824
1825 if (this->terminal_output_) {
1826 // Log debug messages for NaN or too large residuals.
1827 for (const auto& f : report.wellFailures()) {
1828 if (f.severity() == ConvergenceReport::Severity::NotANumber) {
1829 OpmLog::debug("NaN residual found with phase " + std::to_string(f.phase()) + " for well " + f.wellName());
1830 } else if (f.severity() == ConvergenceReport::Severity::TooLarge) {
1831 OpmLog::debug("Too large residual found with phase " + std::to_string(f.phase()) + " for well " + f.wellName());
1832 }
1833 }
1834 }
1835 return report;
1836 }
1837
1838
1839
1840
1841
1842 template<typename TypeTag>
1843 void
1846 {
1847 // TODO: checking isOperableAndSolvable() ?
1848 for (auto& well : well_container_) {
1849 well->calculateExplicitQuantities(simulator_, this->groupStateHelper());
1850 }
1851 }
1852
1853
1854
1855
1856
1857 template<typename TypeTag>
1858 bool
1860 updateWellControls(DeferredLogger& deferred_logger)
1861 {
1862 OPM_TIMEFUNCTION();
1863 if (!this->wellsActive() && !this->isReservoirCouplingMaster()) {
1864 return false;
1865 }
1866 const int episodeIdx = simulator_.episodeIndex();
1867 const auto& comm = simulator_.vanguard().grid().comm();
1868
1869 // Convert WELDRAW drawdown limits into maximum production rates.
1870 // Like the rate targets of wells under group control, these are
1871 // only updated during the first NUPCOL iterations of each timestep
1872 // and kept frozen for the remaining iterations.
1873 {
1874 const auto nupcol = this->schedule()[episodeIdx].nupcol();
1875 const auto& iter_ctx = simulator_.problem().iterationContext();
1876 if (iter_ctx.withinNupcol(nupcol)) {
1878 for (const auto& well : well_container_) {
1879 well->updateWeldrawMaxRate(simulator_, this->wellState(), deferred_logger);
1880 }
1881 OPM_END_PARALLEL_TRY_CATCH("BlackoilWellModel: updating WELDRAW rate limits failed: ",
1882 simulator_.gridView().comm());
1883 }
1884 }
1885
1886 size_t iter = 0;
1887 bool changed_well_group = false;
1888 const Group& fieldGroup = this->schedule().getGroup("FIELD", episodeIdx);
1889 // Check group individual constraints.
1890 // iterate a few times to make sure all constraints are honored
1891 const std::size_t max_iter = param_.well_group_constraints_max_iterations_;
1892 while(!changed_well_group && iter < max_iter) {
1893 changed_well_group = updateGroupControls(fieldGroup, deferred_logger, episodeIdx);
1894
1895 // Check wells' group constraints and communicate.
1896 bool changed_well_to_group = false;
1897 {
1898 OPM_TIMEBLOCK(UpdateWellControls);
1899 // For MS Wells a linear solve is performed below and the matrix might be singular.
1900 // We need to communicate the exception thrown to the others and rethrow.
1902 for (const auto& well : well_container_) {
1904 const bool changed_well = well->updateWellControl(
1905 simulator_, mode, this->groupStateHelper(), this->wellState()
1906 );
1907 if (changed_well) {
1908 changed_well_to_group = changed_well || changed_well_to_group;
1909 }
1910 }
1911 OPM_END_PARALLEL_TRY_CATCH("BlackoilWellModel: updating well controls failed: ",
1912 simulator_.gridView().comm());
1913 }
1914
1915 changed_well_to_group = comm.sum(static_cast<int>(changed_well_to_group));
1916 if (changed_well_to_group) {
1917 updateAndCommunicate(episodeIdx);
1918 changed_well_group = true;
1919 }
1920
1921 // Check individual well constraints and communicate.
1922 bool changed_well_individual = false;
1923 {
1924 // For MS Wells a linear solve is performed below and the matrix might be singular.
1925 // We need to communicate the exception thrown to the others and rethrow.
1927 for (const auto& well : well_container_) {
1929 const bool changed_well = well->updateWellControl(
1930 simulator_, mode, this->groupStateHelper(), this->wellState()
1931 );
1932 if (changed_well) {
1933 changed_well_individual = changed_well || changed_well_individual;
1934 }
1935 }
1936 OPM_END_PARALLEL_TRY_CATCH("BlackoilWellModel: updating well controls failed: ",
1937 simulator_.gridView().comm());
1938 }
1939
1940 changed_well_individual = comm.sum(static_cast<int>(changed_well_individual));
1941 if (changed_well_individual) {
1942 updateAndCommunicate(episodeIdx);
1943 changed_well_group = true;
1944 }
1945 iter++;
1946 }
1947
1948 // update wsolvent fraction for REIN wells
1949 this->updateWsolvent(fieldGroup, episodeIdx, this->nupcolWellState());
1950
1951 return changed_well_group;
1952 }
1953
1954
1955 template<typename TypeTag>
1956 void
1958 updateAndCommunicate(const int reportStepIdx)
1959 {
1960 this->updateAndCommunicateGroupData(reportStepIdx, /*update_wellgrouptarget*/ true);
1961
1962 // updateWellStateWithTarget might throw for multisegment wells hence we
1963 // have a parallel try catch here to thrown on all processes.
1965 // if a well or group change control it affects all wells that are under the same group
1966 for (const auto& well : well_container_) {
1967 // We only want to update wells under group-control here
1968 const auto& ws = this->wellState().well(well->indexOfWell());
1969 if (ws.production_cmode == Well::ProducerCMode::GRUP ||
1970 ws.injection_cmode == Well::InjectorCMode::GRUP)
1971 {
1972 well->updateWellStateWithTarget(
1973 simulator_, this->groupStateHelper(), this->wellState()
1974 );
1975 }
1976 }
1977 OPM_END_PARALLEL_TRY_CATCH("BlackoilWellModel::updateAndCommunicate failed: ",
1978 simulator_.gridView().comm())
1979 this->updateAndCommunicateGroupData(reportStepIdx, /*update_wellgrouptarget*/ true);
1980 }
1981
1982 template<typename TypeTag>
1983 bool
1985 updateGroupControls(const Group& group,
1986 DeferredLogger& deferred_logger,
1987 const int reportStepIdx)
1988 {
1989 OPM_TIMEFUNCTION();
1990 const auto& iterCtx = simulator_.problem().iterationContext();
1991 bool changed = false;
1992 // restrict the number of group switches but only after nupcol iterations.
1993 const int nupcol = this->schedule()[reportStepIdx].nupcol();
1994 const bool update_group_switching_log = !iterCtx.withinNupcol(nupcol);
1995 const bool changed_hc = this->checkGroupHigherConstraints(
1996 group, deferred_logger, reportStepIdx, update_group_switching_log);
1997 if (changed_hc) {
1998 changed = true;
1999 updateAndCommunicate(reportStepIdx);
2000 }
2001
2002 bool changed_individual =
2004 updateGroupIndividualControl(group,
2005 reportStepIdx,
2006 param_.max_number_of_group_switches_,
2007 update_group_switching_log,
2008 this->switched_inj_groups_,
2009 this->switched_prod_groups_,
2010 this->closed_offending_wells_,
2011 this->groupState(),
2012 this->wellState(),
2013 deferred_logger);
2014
2015 if (changed_individual) {
2016 changed = true;
2017 updateAndCommunicate(reportStepIdx);
2018 }
2019 // call recursively down the group hierarchy
2020 for (const std::string& groupName : group.groups()) {
2021 bool changed_this = updateGroupControls(this->schedule().getGroup(groupName, reportStepIdx), deferred_logger, reportStepIdx);
2022 changed = changed || changed_this;
2023 }
2024 return changed;
2025 }
2026
2027 template<typename TypeTag>
2028 void
2030 updateWellTestState(const double simulationTime, WellTestState& wellTestState)
2031 {
2032 OPM_TIMEFUNCTION();
2033 auto logger_guard = this->groupStateHelper().pushLogger();
2034 auto& local_deferredLogger = this->groupStateHelper().deferredLogger();
2035 for (const auto& well : well_container_) {
2036 const auto& wname = well->name();
2037 const auto wasClosed = wellTestState.well_is_closed(wname);
2038 well->checkWellOperability(simulator_,
2039 this->wellState(),
2040 this->groupStateHelper());
2041 const bool under_zero_target =
2042 well->wellUnderZeroGroupRateTarget(this->groupStateHelper());
2043 well->updateWellTestState(this->wellState().well(wname),
2044 simulationTime,
2045 /*writeMessageToOPMLog=*/ true,
2046 /*during_well_test=*/ false,
2047 under_zero_target,
2048 wellTestState,
2049 this->eclipseState().getUnits(),
2050 this->schedule().getStartTime(),
2051 local_deferredLogger);
2052
2053 if (!wasClosed && wellTestState.well_is_closed(wname)) {
2054 this->closed_this_step_.insert(wname);
2055
2056 // maybe open a new well
2057 const WellEconProductionLimits& econ_production_limits = well->wellEcl().getEconLimits();
2058 if (econ_production_limits.validFollowonWell()) {
2059 const auto episode_idx = simulator_.episodeIndex();
2060 const auto follow_on_well = econ_production_limits.followonWell();
2061 if (!this->schedule().hasWell(follow_on_well, episode_idx)) {
2062 const auto msg = fmt::format("Well {} was closed. But the given follow on well {} does not exist."
2063 "The simulator continues without opening a follow on well.",
2064 wname, follow_on_well);
2065 local_deferredLogger.warning(msg);
2066 }
2067 auto& ws = this->wellState().well(follow_on_well);
2068 const bool success = ws.updateStatus(WellStatus::OPEN);
2069 if (success) {
2070 const auto msg = fmt::format("Well {} was closed. The follow on well {} opens instead.", wname, follow_on_well);
2071 local_deferredLogger.info(msg);
2072 } else {
2073 const auto msg = fmt::format("Well {} was closed. The follow on well {} is already open.", wname, follow_on_well);
2074 local_deferredLogger.warning(msg);
2075 }
2076 }
2077
2078 }
2079 }
2080
2081 for (const auto& [group_name, to] : this->closed_offending_wells_) {
2082 if (this->hasOpenLocalWell(to.second) &&
2083 !this->wasDynamicallyShutThisTimeStep(to.second))
2084 {
2085 wellTestState.close_well(to.second,
2086 WellTestConfig::Reason::GROUP,
2087 simulationTime);
2088 this->updateClosedWellsThisStep(to.second);
2089 const std::string msg =
2090 fmt::format("Procedure on exceeding {} limit is WELL for group {}. "
2091 "Well {} is {}.",
2092 to.first,
2093 group_name,
2094 to.second,
2095 "shut");
2096 local_deferredLogger.info(msg);
2097 }
2098 }
2099 }
2100
2101
2102 template<typename TypeTag>
2103 void
2105 const WellState<Scalar, IndexTraits>& well_state_copy,
2106 std::string& exc_msg,
2107 ExceptionType::ExcEnum& exc_type)
2108 {
2109 OPM_TIMEFUNCTION();
2110 const int np = this->numPhases();
2111 std::vector<Scalar> potentials;
2112 const auto& well = well_container_[widx];
2113 std::string cur_exc_msg;
2114 auto cur_exc_type = ExceptionType::NONE;
2115 try {
2116 well->computeWellPotentials(simulator_, well_state_copy, this->groupStateHelper(), potentials);
2117 }
2118 // catch all possible exception and store type and message.
2119 OPM_PARALLEL_CATCH_CLAUSE(cur_exc_type, cur_exc_msg);
2120 if (cur_exc_type != ExceptionType::NONE) {
2121 exc_msg += fmt::format("\nFor well {}: {}", well->name(), cur_exc_msg);
2122 }
2123 exc_type = std::max(exc_type, cur_exc_type);
2124 // Store it in the well state
2125 // potentials is resized and set to zero in the beginning of well->ComputeWellPotentials
2126 // and updated only if sucessfull. i.e. the potentials are zero for exceptions
2127 auto& ws = this->wellState().well(well->indexOfWell());
2128 for (int p = 0; p < np; ++p) {
2129 // make sure the potentials are positive
2130 ws.well_potentials[p] = std::max(Scalar{0.0}, potentials[p]);
2131 }
2132 }
2133
2134
2135
2136 template <typename TypeTag>
2137 void
2140 {
2141 for (const auto& wellPtr : this->well_container_) {
2142 this->calculateProductivityIndexValues(wellPtr.get(), deferred_logger);
2143 }
2144 }
2145
2146
2147
2148
2149
2150 template <typename TypeTag>
2151 void
2153 calculateProductivityIndexValuesShutWells(const int reportStepIdx,
2154 DeferredLogger& deferred_logger)
2155 {
2156 // For the purpose of computing PI/II values, it is sufficient to
2157 // construct StandardWell instances only. We don't need to form
2158 // well objects that honour the 'isMultisegment()' flag of the
2159 // corresponding "this->wells_ecl_[shutWell]".
2160
2161 for (const auto& shutWell : this->local_shut_wells_) {
2162 if (!this->wells_ecl_[shutWell].hasConnections()) {
2163 // No connections in this well. Nothing to do.
2164 continue;
2165 }
2166
2167 auto wellPtr = this->template createTypedWellPointer
2168 <StandardWell<TypeTag>>(shutWell, reportStepIdx);
2169
2170 wellPtr->init(this->depth_, this->gravity_, this->B_avg_, true);
2171
2172 this->calculateProductivityIndexValues(wellPtr.get(), deferred_logger);
2173 }
2174 }
2175
2176
2177
2178
2179
2180 template <typename TypeTag>
2181 void
2184 DeferredLogger& deferred_logger)
2185 {
2186 wellPtr->updateProductivityIndex(this->simulator_,
2187 this->prod_index_calc_[wellPtr->indexOfWell()],
2188 this->wellState(),
2189 deferred_logger);
2190 }
2191
2192
2193
2194 template<typename TypeTag>
2195 void
2197 prepareTimeStep(DeferredLogger& deferred_logger)
2198 {
2199 const auto episodeIdx = simulator_.episodeIndex();
2200
2201 // Need to check this before clearing events
2202 const bool do_prestep_network_rebalance = this->shouldDoPreStepNetworkRebalance_(episodeIdx);
2203
2204 for (const auto& well : well_container_) {
2205 auto& events = this->wellState().well(well->indexOfWell()).events;
2206 if (events.hasEvent(WellState<Scalar, IndexTraits>::event_mask)) {
2207 well->updateWellStateWithTarget(
2208 simulator_, this->groupStateHelper(), this->wellState()
2209 );
2210 well->updatePrimaryVariables(this->groupStateHelper());
2211 // There is no new well control change input within a report step,
2212 // so next time step, the well does not consider to have effective events anymore.
2214 }
2215 // these events only work for the first time step within the report step
2216 if (events.hasEvent(ScheduleEvents::REQUEST_OPEN_WELL)) {
2217 events.clearEvent(ScheduleEvents::REQUEST_OPEN_WELL);
2218 }
2219 // solve the well equation initially to improve the initial solution of the well model
2220 if (param_.solve_welleq_initially_ && well->isOperableAndSolvable()) {
2221 try {
2222 well->solveWellEquation(
2223 simulator_, this->groupStateHelper(), this->wellState()
2224 );
2225 } catch (const std::exception& e) {
2226 const std::string msg = "Compute initial well solution for " + well->name() + " initially failed. Continue with the previous rates";
2227 deferred_logger.warning("WELL_INITIAL_SOLVE_FAILED", msg);
2228 }
2229 }
2230 // If we're using local well solves that include control switches, they also update
2231 // operability, so reset before main iterations begin
2232 well->resetWellOperability();
2233 }
2234 updatePrimaryVariables();
2235
2236 // Actually do the pre-step network rebalance, using the updated well states and initial solutions
2237 if (do_prestep_network_rebalance) {
2238 network_.doPreStepRebalance(deferred_logger);
2239 }
2240 }
2241
2242 template<typename TypeTag>
2243 void
2246 {
2247 std::vector< Scalar > B_avg(numConservationQuantities(), Scalar() );
2248 const auto& grid = simulator_.vanguard().grid();
2249 const auto& gridView = grid.leafGridView();
2250 ElementContext elemCtx(simulator_);
2251
2253 for (const auto& elem : elements(gridView, Dune::Partitions::interior)) {
2254 elemCtx.updatePrimaryStencil(elem);
2255 elemCtx.updatePrimaryIntensiveQuantities(/*timeIdx=*/0);
2256
2257 const auto& intQuants = elemCtx.intensiveQuantities(/*spaceIdx=*/0, /*timeIdx=*/0);
2258 const auto& fs = intQuants.fluidState();
2259
2260 for (unsigned phaseIdx = 0; phaseIdx < FluidSystem::numPhases; ++phaseIdx)
2261 {
2262 if (!FluidSystem::phaseIsActive(phaseIdx)) {
2263 continue;
2264 }
2265
2266 const unsigned compIdx = FluidSystem::canonicalToActiveCompIdx(FluidSystem::solventComponentIndex(phaseIdx));
2267 auto& B = B_avg[ compIdx ];
2268
2269 B += 1 / fs.invB(phaseIdx).value();
2270 }
2271 if constexpr (has_solvent_) {
2272 auto& B = B_avg[solventSaturationIdx];
2273 B += 1 / intQuants.solventInverseFormationVolumeFactor().value();
2274 }
2275 }
2276 OPM_END_PARALLEL_TRY_CATCH("BlackoilWellModel::updateAverageFormationFactor() failed: ", grid.comm())
2277
2278 // compute global average
2279 grid.comm().sum(B_avg.data(), B_avg.size());
2280 B_avg_.resize(B_avg.size());
2281 std::ranges::transform(B_avg, B_avg_.begin(),
2282 [gcells = global_num_cells_](const auto bval)
2283 { return bval / gcells; });
2284 }
2285
2286
2287
2288
2289
2290 template<typename TypeTag>
2291 void
2294 {
2295 for (const auto& well : well_container_) {
2296 well->updatePrimaryVariables(this->groupStateHelper());
2297 }
2298 }
2299
2300 template<typename TypeTag>
2301 void
2303 {
2304 const auto& grid = simulator_.vanguard().grid();
2305 const auto& eclProblem = simulator_.problem();
2306 const unsigned numCells = grid.size(/*codim=*/0);
2307
2308 this->pvt_region_idx_.resize(numCells);
2309 for (unsigned cellIdx = 0; cellIdx < numCells; ++cellIdx) {
2310 this->pvt_region_idx_[cellIdx] =
2311 eclProblem.pvtRegionIndex(cellIdx);
2312 }
2313 }
2314
2315 // The number of components in the model.
2316 template<typename TypeTag>
2317 int
2319 {
2320 // TODO: energy is also a conservation equation, so numConservationQuantities()
2321 // may need refactoring once it is enabled outside MSW.
2322
2323 // The numPhases() functions returns 1-3, depending on which
2324 // of the (oil, water, gas) phases are active. For each of those phases,
2325 // if the phase is active the corresponding component is present and
2326 // conserved.
2327 // Apart from (oil, water, gas), in the current well model only solvent
2328 // is explicitly modelled as a conserved quantity (polymer, energy, salt
2329 // etc. are not), unlike the reservoir part where all such quantities are
2330 // conserved. This function must therefore be updated when/if we add
2331 // more conserved quantities in the well model.
2332 return this->numPhases() + has_solvent_;
2333 }
2334
2335 template<typename TypeTag>
2336 void
2338 {
2339 const auto& eclProblem = simulator_.problem();
2340 depth_.resize(local_num_cells_);
2341 for (unsigned cellIdx = 0; cellIdx < local_num_cells_; ++cellIdx) {
2342 depth_[cellIdx] = eclProblem.dofCenterDepth(cellIdx);
2343 }
2344 }
2345
2346 template<typename TypeTag>
2349 getWell(const std::string& well_name) const
2350 {
2351 // finding the iterator of the well in wells_ecl
2352 const auto well =
2353 std::ranges::find_if(well_container_,
2354 [&well_name](const WellInterfacePtr& elem) -> bool
2355 { return elem->name() == well_name; });
2356
2357 assert(well != well_container_.end());
2358
2359 return **well;
2360 }
2361
2362 template <typename TypeTag>
2363 int
2365 reportStepIndex() const
2366 {
2367 return std::max(this->simulator_.episodeIndex(), 0);
2368 }
2369
2370
2371
2372
2373
2374 template<typename TypeTag>
2375 void
2377 calcResvCoeff(const int fipnum,
2378 const int pvtreg,
2379 const std::vector<Scalar>& production_rates,
2380 std::vector<Scalar>& resv_coeff) const
2381 {
2382 rateConverter_->calcCoeff(fipnum, pvtreg, production_rates, resv_coeff);
2383 }
2384
2385 template<typename TypeTag>
2386 void
2388 calcInjResvCoeff(const int fipnum,
2389 const int pvtreg,
2390 std::vector<Scalar>& resv_coeff) const
2391 {
2392 rateConverter_->calcInjCoeff(fipnum, pvtreg, resv_coeff);
2393 }
2394
2395
2396 template <typename TypeTag>
2397 void
2400 {
2401 if constexpr (energyModuleType_ == EnergyModules::FullyImplicitThermal) {
2402 const int np = this->numPhases();
2403 const int nw = this->numLocalWells();
2404 for (auto wellID = 0*nw; wellID < nw; ++wellID) {
2405 const Well& well = this->wells_ecl_[wellID];
2406 auto& ws = this->wellState().well(wellID);
2407 if (well.isInjector()) {
2408 if (ws.status != WellStatus::STOP) {
2409 this->wellState().well(wellID).temperature = well.inj_temperature();
2410 continue;
2411 }
2412 }
2413 std::array<Scalar,2> weighted{0.0,0.0};
2414 auto& [weighted_temperature, total_weight] = weighted;
2415 const auto& well_info = this->local_parallel_well_info_[wellID].get();
2416 using int_type = decltype(this->well_perf_data_[wellID].size());
2417 for (int_type perf = 0, end_perf = this->well_perf_data_[wellID].size(); perf < end_perf; ++perf) {
2418 const int cell_idx = this->well_perf_data_[wellID][perf].cell_index;
2419 const auto& intQuants = simulator_.model().intensiveQuantities(cell_idx, /*timeIdx=*/0);
2420 const auto& fs = intQuants.fluidState();
2421 Scalar weight_factor = computeTemperatureWeightFactor(perf, np, fs, ws);
2422 total_weight += weight_factor;
2423 weighted_temperature += weight_factor * fs.temperature(/*phaseIdx*/0).value();
2424 }
2425 well_info.communication().sum(weighted.data(), 2);
2426 this->wellState().well(wellID).temperature = weighted_temperature / total_weight;
2427 }
2428 }
2429 }
2430
2431
2432 template <typename TypeTag>
2433 [[nodiscard]] auto BlackoilWellModel<TypeTag>::rsConstInfo() const
2434 -> typename WellState<Scalar,IndexTraits>::RsConstInfo
2435 {
2436 if (! FluidSystem::phaseIsActive(FluidSystem::oilPhaseIdx) ||
2437 ! FluidSystem::enableConstantRs())
2438 {
2439 return {};
2440 }
2441
2442 const auto& rsConstTables = this->eclState_
2443 .getTableManager().getRsconstTables();
2444
2445 if (rsConstTables.empty() ||
2446 (rsConstTables[0].numRows() != std::size_t{1}))
2447 {
2448 return {};
2449 }
2450
2451 const auto rsConst = rsConstTables[0].getColumn(0).front();
2452
2453 return { true, static_cast<Scalar>(rsConst) };
2454 }
2455
2456 // Private helper methods (alphabetical order)
2457 // --------------------------------------------
2458
2459 template <typename TypeTag>
2460 void BlackoilWellModel<TypeTag>::
2461 assignWellTracerRates_(data::Wells& wsrpt) const
2462 {
2463 const auto reportStepIdx = static_cast<unsigned int>(this->reportStepIndex());
2464 const auto& trMod = this->simulator_.problem().tracerModel();
2465
2466 BlackoilWellModelGeneric<Scalar, IndexTraits>::assignWellTracerRates(wsrpt, trMod.getWellTracerRates(), reportStepIdx);
2467 BlackoilWellModelGeneric<Scalar, IndexTraits>::assignWellTracerRates(wsrpt, trMod.getWellFreeTracerRates(), reportStepIdx);
2468 BlackoilWellModelGeneric<Scalar, IndexTraits>::assignWellTracerRates(wsrpt, trMod.getWellSolTracerRates(), reportStepIdx);
2469
2470 this->assignMswTracerRates(wsrpt, trMod.getMswTracerRates(), reportStepIdx);
2471 }
2472
2473 template <typename TypeTag>
2474 void BlackoilWellModel<TypeTag>::
2475 assignWellSpeciesRates_(data::Wells& wsrpt) const
2476 {
2477 const auto reportStepIdx = static_cast<unsigned int>(this->reportStepIndex());
2478 const auto& geochemMod = this->simulator_.problem().geochemistryModel();
2479
2480 BlackoilWellModelGeneric<Scalar, IndexTraits>::assignWellTracerRates(wsrpt, geochemMod.getWellSpeciesRates(), reportStepIdx);
2481
2482 this->assignMswTracerRates(wsrpt, geochemMod.getMswSpeciesRates(), reportStepIdx);
2483 }
2484
2485 template <typename TypeTag>
2486 bool BlackoilWellModel<TypeTag>::isRescoupMasterCoupledNetworkIteration_() const
2487 {
2488#ifdef RESERVOIR_COUPLING_ENABLED
2489 return this->rescoupHelper_.masterIsInCoupledNetworkIteration();
2490#else
2491 return false;
2492#endif
2493 }
2494
2495 template <typename TypeTag>
2496 bool BlackoilWellModel<TypeTag>::isRescoupSlaveCoupledNetworkIteration_() const
2497 {
2498 // True when the slave is on the first substep of a sync step AND the
2499 // master has not yet signaled termination. Gates the per-iteration
2500 // master->slave node-pressure receive at the top of
2501 // updateWellControlsAndNetworkIteration(). The outer loop exit on
2502 // the slave is driven by the master's is_final flag (propagated to
2503 // local variable "more_network_update" at the end of updateWellControlsAndNetworkIteration(),
2504 // not by the slave's local network convergence. The master's own max_iter
2505 // bounds the iteration count from above, so the slave skips the local max_iter check entirely
2506 // and lets the master signal termination.
2507#ifdef RESERVOIR_COUPLING_ENABLED
2508 return this->isRescoupSlaveOnSyncStepFirstSubstep_()
2509 && this->reservoirCouplingSlave().connectedToMasterCoupledNetwork()
2510 && !this->reservoirCouplingSlave().lastReceivedMasterGroupNodePressuresIsFinal();
2511#else
2512 return false;
2513#endif
2514 }
2515
2516 template <typename TypeTag>
2517 bool BlackoilWellModel<TypeTag>::isRescoupSlaveOnSyncStepFirstSubstep_() const
2518 {
2519 // True when the slave is on the first substep of a sync step,
2520 // regardless of is_final state. Gates post-Newton handling at the
2521 // end of updateWellControlsAndNetworkIteration(), which must run on
2522 // the terminating iteration too (so the slave can set
2523 // more_network_update = false and exit its outer loop).
2524#ifdef RESERVOIR_COUPLING_ENABLED
2525 return this->isReservoirCouplingSlave()
2526 && this->reservoirCouplingSlave().isFirstSubstepOfSyncTimestep();
2527#else
2528 return false;
2529#endif
2530 }
2531
2532 template <typename TypeTag>
2533 bool BlackoilWellModel<TypeTag>::isRescoupSlaveConnectedToMasterNetwork_() const
2534 {
2535#ifdef RESERVOIR_COUPLING_ENABLED
2536 return this->isReservoirCouplingSlave()
2537 && this->reservoirCouplingSlave().connectedToMasterCoupledNetwork();
2538#else
2539 return false;
2540#endif
2541 }
2542
2543 template <typename TypeTag>
2544 bool BlackoilWellModel<TypeTag>::
2545 maybeSendSlaveGroupFlowToMaster_([[maybe_unused]] const int reportStepIdx)
2546 {
2547#ifdef RESERVOIR_COUPLING_ENABLED
2548 // For a rescoup slave: after the well-solve in
2549 // prepareWellsBeforeAssembling() has produced fresh rates under the
2550 // new THP, ship them back to the master and force one more outer
2551 // iteration so we re-enter updateWellControlsAndNetworkIteration() to receive the next pressures.
2552 // When the just-received message had is_final = true, we skip the
2553 // send and let the slave's outer loop exit naturally.
2554 assert(this->isReservoirCouplingSlave());
2555 const bool is_final =
2556 this->reservoirCouplingSlave().lastReceivedMasterGroupNodePressuresIsFinal();
2557 if (!is_final) {
2558 this->updateAndCommunicateGroupData(reportStepIdx, /*update_wellgrouptarget=*/false);
2559 this->rescoupHelper_.sendSlaveGroupDataToMaster();
2560 // The master turns the rates just sent into fresh group constraints
2561 // and sends them straight back. See
2562 // BlackoilWellModelRescoup::refreshAndSendGroupConstraints().
2563 this->rescoupHelper_.receiveRefreshedGroupConstraintsFromMaster();
2564 return /*more_network_update=*/true;
2565 }
2566 return /*more_network_update=*/false;
2567#else
2568 return /*more_network_update=*/false;
2569#endif
2570 }
2571
2572 template <typename TypeTag>
2573 void BlackoilWellModel<TypeTag>::
2574 sendSlaveNetworkLoopTerminationSignal_()
2575 {
2576#ifdef RESERVOIR_COUPLING_ENABLED
2577 // When the master's outer loop exits without having sent is_final = true (e.g. max_iter
2578 // exceeded with the network still unconverged), the slave is stuck
2579 // waiting on its next receive. Fire one final pressure send to
2580 // unblock it.
2581 assert(this->isReservoirCouplingMaster());
2582 this->rescoupHelper_.sendMasterGroupNodePressuresToSlaves(/*is_final=*/true);
2583#endif
2584 }
2585
2586 template <typename TypeTag>
2587 bool BlackoilWellModel<TypeTag>::
2588 shouldDoPreStepNetworkRebalance_(const int episodeIdx) const
2589 {
2590 // Rebalance the network initially if any wells in the network have status changes
2591 //
2592 // The rebalance is skipped only for *coupled-network participants*: its
2593 // inner updateWellControlsAndNetwork call would run the cross-rescoup
2594 // pressure/rate exchange, but needPreStepRebalance is collectivised only
2595 // over the local OPM communicator -- not across the rescoup boundary --
2596 // so a coupled master and slave may disagree on whether to enter the
2597 // rebalance, deadlocking the exchange. A non-participant (a master with
2598 // no master-group network leaves, or a slave not connected to the master
2599 // network) does no cross-rescoup MPI in the network solve, so it is safe
2600 // to rebalance like a standalone process and we no longer skip it.
2601 return param_.pre_solve_network_
2602 && this->network_.needPreStepRebalance(episodeIdx)
2603 && !this->isRescoupCoupledNetworkParticipant_();
2604 }
2605
2606 template <typename TypeTag>
2607 bool BlackoilWellModel<TypeTag>::isRescoupCoupledNetworkParticipant_() const
2608 {
2609#ifdef RESERVOIR_COUPLING_ENABLED
2610 if (this->isReservoirCouplingMaster()) {
2611 return this->rescoupHelper_.masterNetworkHasMasterGroupLeaves();
2612 }
2613 if (this->isReservoirCouplingSlave()) {
2614 return this->reservoirCouplingSlave().connectedToMasterCoupledNetwork();
2615 }
2616 return false;
2617#else
2618 return false;
2619#endif
2620 }
2621
2622 template <typename TypeTag>
2623 void BlackoilWellModel<TypeTag>::
2624 updateNetworkActiveState_()
2625 {
2626 // Refresh the network's cached `active_` flag once per timestep
2627 // init. updateActiveState's inputs (Schedule network, well list,
2628 // per-well groupName/predictionMode, and rescoup master groups)
2629 // are constant within a substep; ACTIONX-driven well structure
2630 // changes propagate via wellStructureChangedDynamically_ at the
2631 // top of beginTimeStep, before the first assemble() of the new
2632 // substep. Doing this in assemble() rather than only in
2633 // prepareTimeStep() covers the case of a rescoup master with no
2634 // local wells, where prepareTimeStep() is skipped (gated on wellsActive()).
2635 const int episodeIdx = this->simulator_.episodeIndex();
2636 this->network_.updateActiveState(episodeIdx);
2637 }
2638
2639} // namespace Opm
2640
2641#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:649
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:2377
void prepareTimeStep(DeferredLogger &deferred_logger)
Definition: BlackoilWellModel_impl.hpp:2197
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:1415
WellInterfacePtr createWellPointer(const int wellID, const int report_step) const
Definition: BlackoilWellModel_impl.hpp:1132
void prepareWellsBeforeAssembling(const double dt)
Definition: BlackoilWellModel_impl.hpp:1538
void init()
Definition: BlackoilWellModel_impl.hpp:166
const Simulator & simulator() const
Definition: BlackoilWellModel.hpp:400
std::vector< Scalar > depth_
Definition: BlackoilWellModel.hpp:610
std::size_t global_num_cells_
Definition: BlackoilWellModel.hpp:606
GetPropType< TypeTag, Properties::Scalar > Scalar
Definition: BlackoilWellModel.hpp:110
void addConstantCellRatesForOverlap(int domainIndex, const std::map< std::string, int > &well_domain_map, const std::vector< int > &domain_cells, const std::vector< bool > &interior)
Definition: BlackoilWellModel_impl.hpp:1599
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:2349
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:2318
bool updateWellControls(DeferredLogger &deferred_logger)
Definition: BlackoilWellModel_impl.hpp:1860
int reportStepIndex() const
Definition: BlackoilWellModel_impl.hpp:2365
void calculateProductivityIndexValues(DeferredLogger &deferred_logger) override
Definition: BlackoilWellModel_impl.hpp:2139
void extractLegacyDepth_()
Definition: BlackoilWellModel_impl.hpp:2337
void extractLegacyCellPvtRegionIndex_()
Definition: BlackoilWellModel_impl.hpp:2302
void recoverWellSolutionAndUpdateWellStateDomain(const BVector &x, const int domainIdx)
Definition: BlackoilWellModel_impl.hpp:1781
void updateAverageFormationFactor()
Definition: BlackoilWellModel_impl.hpp:2245
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:834
const Grid & grid() const
Definition: BlackoilWellModel.hpp:397
void updatePrimaryVariables()
Definition: BlackoilWellModel_impl.hpp:2293
void computeWellTemperature()
Definition: BlackoilWellModel_impl.hpp:2399
const SimulatorReportSingle & lastReport() const
Definition: BlackoilWellModel_impl.hpp:694
bool updateWellControlsAndNetwork(const bool mandatory_network_balance, const double dt, DeferredLogger &local_deferredLogger)
Definition: BlackoilWellModel_impl.hpp:1342
void addWellContributions(SparseMatrixAdapter &jacobian) const
Definition: BlackoilWellModel_impl.hpp:1660
void assembleWellEq(const double dt)
Definition: BlackoilWellModel_impl.hpp:1526
WellInterfacePtr createWellForWellTest(const std::string &well_name, const int report_step, DeferredLogger &deferred_logger) const
Definition: BlackoilWellModel_impl.hpp:1183
void calculateExplicitQuantities() const
Definition: BlackoilWellModel_impl.hpp:1845
void collectWellSolveStats()
Definition: BlackoilWellModel_impl.hpp:1297
void updateAndCommunicate(const int reportStepIdx)
Definition: BlackoilWellModel_impl.hpp:1958
Dune::BCRSMatrix< Opm::MatrixBlock< Scalar, 1, 1 > > PressureMatrix
Definition: BlackoilWellModel.hpp:309
void updateFailed()
Definition: BlackoilWellModel_impl.hpp:602
void computeTotalRatesForDof(RateVector &rate, unsigned globalIdx) const
Definition: BlackoilWellModel_impl.hpp:797
void stashWellSolveStats()
Definition: BlackoilWellModel_impl.hpp:1313
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:1985
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:2388
Dune::BlockVector< VectorBlockType > BVector
Definition: BlackoilWellModel.hpp:135
void wellTesting(const int timeStepIdx, const double simulationTime, DeferredLogger &deferred_logger)
Definition: BlackoilWellModel_impl.hpp:617
ConvergenceReport getWellConvergence(const std::vector< Scalar > &B_avg, const bool checkWellGroupControlsAndNetwork=false) const
Definition: BlackoilWellModel_impl.hpp:1794
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:1584
void assembleWellEqWithoutIteration(const double dt)
Definition: BlackoilWellModel_impl.hpp:1552
void updateCellRates()
Definition: BlackoilWellModel_impl.hpp:1572
void assemble(const double dt)
Definition: BlackoilWellModel_impl.hpp:1208
std::size_t local_num_cells_
Definition: BlackoilWellModel.hpp:608
bool alternative_well_rate_init_
Definition: BlackoilWellModel.hpp:611
void timeStepSucceeded(const double simulationTime, const double dt)
Definition: BlackoilWellModel_impl.hpp:704
std::unique_ptr< WellType > createTypedWellPointer(const int wellID, const int time_step) const
Definition: BlackoilWellModel_impl.hpp:1152
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:2104
Simulator & simulator_
Definition: BlackoilWellModel.hpp:580
void createWellContainer(const int report_step) override
Definition: BlackoilWellModel_impl.hpp:877
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:2030
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:1669
void addSolveStats(const WellInterface< TypeTag > &well)
Definition: BlackoilWellModel_impl.hpp:1323
void addReservoirSourceTerms(GlobalEqVector &residual, const std::vector< typename SparseMatrixAdapter::MatrixBlock * > &diagMatAddress) const
Definition: BlackoilWellModel_impl.hpp:1707
int compressedIndexForInterior(int cartesian_cell_idx) const override
get compressed index for interior cells (-1, otherwise
Definition: BlackoilWellModel.hpp:365
void addWellPressureEquations(PressureMatrix &jacobian, const BVector &weights, const bool use_well_weights, const bool contract_d_diagonal) const
Definition: BlackoilWellModel_impl.hpp:1683
void recoverWellSolutionAndUpdateWellState(const BVector &x)
Definition: BlackoilWellModel_impl.hpp:1757
void addWellPressureEquationsStruct(PressureMatrix &jacobian) const
Definition: BlackoilWellModel_impl.hpp:1737
void calculateProductivityIndexValuesShutWells(const int reportStepIdx, DeferredLogger &deferred_logger) override
Definition: BlackoilWellModel_impl.hpp:2153
void advanceTimeLevel()
Definition: BlackoilWellModel_impl.hpp:610
void endReportStep()
Definition: BlackoilWellModel_impl.hpp:677
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:336
ExcEnum
Definition: DeferredLogger.hpp:45
@ NONE
Definition: DeferredLogger.hpp:46
Dune::Communication< MPIComm > Communication
Definition: ParallelCommunication.hpp:30
constexpr std::size_t domainIndex(const NetworkDomain domain)
Definition: BlackoilWellModelNetworkGeneric.hpp:60
bool anyNetworkActive(const Schedule &schedule, const int timeStepIdx)
Helper to check if any network (production, gas injection, water injection) is active at a given time...
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