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