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