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