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