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