NonlinearSystemBlackOilReservoir_impl.hpp
Go to the documentation of this file.
1/*
2 Copyright 2013, 2015 SINTEF ICT, Applied Mathematics.
3 Copyright 2014, 2015 Dr. Blatt - HPC-Simulation-Software & Services
4 Copyright 2014, 2015 Statoil ASA.
5 Copyright 2015 NTNU
6 Copyright 2015, 2016, 2017 IRIS AS
7
8 This file is part of the Open Porous Media project (OPM).
9
10 OPM is free software: you can redistribute it and/or modify
11 it under the terms of the GNU General Public License as published by
12 the Free Software Foundation, either version 3 of the License, or
13 (at your option) any later version.
14
15 OPM is distributed in the hope that it will be useful,
16 but WITHOUT ANY WARRANTY; without even the implied warranty of
17 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 GNU General Public License for more details.
19
20 You should have received a copy of the GNU General Public License
21 along with OPM. If not, see <http://www.gnu.org/licenses/>.
22*/
23
24#ifndef OPM_NONLINEAR_SYSTEM_BLACK_OIL_RESERVOIR_IMPL_HEADER_INCLUDED
25#define OPM_NONLINEAR_SYSTEM_BLACK_OIL_RESERVOIR_IMPL_HEADER_INCLUDED
26
27#ifndef OPM_NONLINEAR_SYSTEM_BLACK_OIL_RESERVOIR_HEADER_INCLUDED
28#include <config.h>
30#endif
31
32#include <dune/common/timer.hh>
33
34#include <opm/common/ErrorMacros.hpp>
35#include <opm/common/OpmLog/OpmLog.hpp>
36
38
39#include <algorithm>
40#include <cmath>
41#include <filesystem>
42#include <functional>
43#include <iomanip>
44#include <limits>
45#include <memory>
46#include <numeric>
47#include <sstream>
48#include <stdexcept>
49#include <string>
50#include <string_view>
51#include <tuple>
52#include <utility>
53#include <vector>
54
55#include <fmt/format.h>
56
57namespace {
58 template <typename TypeTag>
59 std::string_view
61 {
63
64 switch (f) {
65 case F::Strict: return "Strict";
66 case F::Relaxed: return "Relaxed";
67 case F::TuningDP: return "TuningDP";
68 }
69
70 return "< ??? >";
71 }
72} // Anonymous namespace
73
74namespace Opm {
75
76template <class TypeTag>
79 const ModelParameters& param,
80 typename ParentType::WellModel& well_model,
81 const bool terminal_output)
82 : ParentType(simulator, param, well_model, terminal_output)
83 , conv_monitor_(param.monitor_params_)
84{
85 // compute global sum of number of cells
87 this->convergence_reports_.reserve(300); // Often insufficient, but avoids frequent moves.
88 // TODO: remember to fix!
89 if (this->param_.nonlinear_solver_ == "nldd") {
90 if constexpr (getPropValue<TypeTag, Properties::RunAssemblyOnGpu>()) {
91 OPM_THROW(std::invalid_argument, "GPU assembly does not support NLDD.");
92 }
93 if (terminal_output) {
94 OpmLog::info("Using Non-Linear Domain Decomposition solver (nldd).");
95 }
96 nlddSolver_ = std::make_unique<NonlinearSystemNldd<TypeTag>>(*this);
97 } else if (this->param_.nonlinear_solver_ == "newton") {
98 if (terminal_output) {
99 OpmLog::info("Using Newton nonlinear solver.");
100 }
101 } else {
102 OPM_THROW(std::runtime_error, "Unknown nonlinear solver option: " +
104 }
105}
106
107template <class TypeTag>
111{
112 OPM_TIMEFUNCTION();
113 if (this->enable_state_rollback_) {
114 auto& newtonMethod = this->simulator_.model().newtonMethod();
115 if (timer.lastStepFailed()) {
116 // Discard switching decisions made by the failed attempt.
117 newtonMethod.restorePrimaryVariableSwitches();
118 }
119 else {
120 newtonMethod.capturePrimaryVariableSwitches();
121 }
122 }
123
124 auto report = ParentType::prepareStep(timer);
125
126 Dune::Timer perfTimer;
127 perfTimer.start();
128
129 if (this->param_.update_equations_scaling_) {
130 OpmLog::error("Equation scaling not supported");
131 //updateEquationsScaling();
132 }
133
134 if (hasNlddSolver()) {
135 nlddSolver_->prepareStep();
136 }
137
138 report.pre_post_time += perfTimer.stop();
139
140 auto getIdx = [](unsigned phaseIdx) -> int
141 {
142 if (FluidSystem::phaseIsActive(phaseIdx)) {
143 const unsigned sIdx = FluidSystem::solventComponentIndex(phaseIdx);
144 return FluidSystem::canonicalToActiveCompIdx(sIdx);
145 }
146
147 return -1;
148 };
149 const auto& schedule = this->simulator_.vanguard().schedule();
150 auto& rst_conv = this->simulator_.problem().eclWriter().mutableOutputModule().getConv();
151 rst_conv.init(this->simulator_.vanguard().globalNumCells(),
152 schedule[timer.reportStepNum()].rst_config(),
153 {getIdx(FluidSystem::oilPhaseIdx),
154 getIdx(FluidSystem::gasPhaseIdx),
155 getIdx(FluidSystem::waterPhaseIdx),
156 contiPolymerEqIdx,
157 contiBrineEqIdx,
158 contiSolventEqIdx});
159
160 return report;
161}
162
163template <class TypeTag>
164void
167 const int minIter,
168 const int maxIter,
169 const SimulatorTimerInterface& timer)
170{
171 ParentType::initialLinearization(report,
172 minIter,
173 maxIter,
174 timer);
175
176 // ----------- Check if converged -----------
177 std::vector<Scalar> residual_norms;
178 Dune::Timer perfTimer;
179 perfTimer.reset();
180 perfTimer.start();
181 // the step is not considered converged until at least minIter iterations is done
182 {
183 auto convrep = getConvergence(timer, maxIter, residual_norms);
184 report.converged = convrep.converged() &&
185 this->simulator_.problem().iterationContext().iteration() >= minIter;
186 if (report.converged &&
187 convrep.cnvRelaxSource() != ConvergenceReport::CnvRelaxSource::None)
188 {
190 }
191 ConvergenceReport::Severity severity = convrep.severityOfWorstFailure();
192 this->convergence_reports_.back().report.push_back(std::move(convrep));
193
194 // Throw if any NaN or too large residual found.
196 this->failureReport_ += report;
197 OPM_THROW_PROBLEM(NumericalProblem, "NaN residual found!");
198 } else if (severity == ConvergenceReport::Severity::TooLarge) {
199 this->failureReport_ += report;
200 OPM_THROW_NOLOG(NumericalProblem, "Too large residual found!");
202 this->failureReport_ += report;
203 OPM_THROW_PROBLEM(ConvergenceMonitorFailure,
204 fmt::format(
205 "Total penalty count exceeded cut-off-limit of {}",
206 this->param_.monitor_params_.cutoff_
207 ));
208 }
209 }
210 report.update_time += perfTimer.stop();
211 this->residual_norms_history_.push_back(residual_norms);
212}
213
214template <class TypeTag>
215template <class NonlinearSolverType>
219 NonlinearSolverType& nonlinear_solver)
220{
221 // Model-level timestep initialization (once per timestep).
222 // markTimestepInitialized() is called later in initialLinearization(),
223 // after assembleReservoir() has triggered the well model's prepareTimeStep().
224 if (this->simulator_.problem().iterationContext().needsTimestepInit()) {
225 this->residual_norms_history_.clear();
226 this->conv_monitor_.reset();
227 this->current_relaxation_ = 1.0;
228 this->dx_old_ = 0.0;
229 this->convergence_reports_.push_back({timer.reportStepNum(), timer.currentStepNum(), {}});
230 this->convergence_reports_.back().report.reserve(11);
231 }
232
234 if (this->param_.nonlinear_solver_ != "nldd") {
235 result = this->nonlinearIterationNewton(timer, nonlinear_solver);
236 }
237 else {
238 result = this->nlddSolver_->nonlinearIterationNldd(timer, nonlinear_solver);
239 }
240
241 auto& rst_conv = this->simulator_.problem().eclWriter().mutableOutputModule().getConv();
242 rst_conv.update(this->simulator_.model().linearizer().residual());
243
244 this->simulator_.problem().advanceIteration();
245 return result;
246}
247
248template <class TypeTag>
249template <class NonlinearSolverType>
253 NonlinearSolverType& nonlinear_solver)
254{
255 OPM_TIMEFUNCTION();
256
258 Dune::Timer perfTimer;
259
260 this->initialLinearization(report,
261 this->param_.newton_min_iter_,
262 this->param_.newton_max_iter_,
263 timer);
264
265 if (!report.converged) {
266 perfTimer.reset();
267 perfTimer.start();
268 report.total_newton_iterations = 1;
269
270 const unsigned nc = this->simulator_.model().numGridDof();
271 BVector x(nc);
272
273 linear_solve_setup_time_ = 0.0;
274 try {
275 this->wellModel().linearize(this->simulator().model().linearizer().jacobian(),
276 this->simulator().model().linearizer().residual());
277
278 solveJacobianSystem(x);
279
280 report.linear_solve_setup_time += linear_solve_setup_time_;
281 report.linear_solve_time += perfTimer.stop();
282 report.total_linear_iterations += linearIterationsLastSolve();
283 }
284 catch (...) {
285 report.linear_solve_setup_time += linear_solve_setup_time_;
286 report.linear_solve_time += perfTimer.stop();
287 report.total_linear_iterations += linearIterationsLastSolve();
288
289 this->failureReport_ += report;
290 throw;
291 }
292
293 perfTimer.reset();
294 perfTimer.start();
295
296 this->wellModel().postSolve(x);
297
298 if (this->param_.use_update_stabilization_) {
299 bool isOscillate = false;
300 bool isStagnate = false;
301 nonlinear_solver.detectOscillations(this->residual_norms_history_,
302 this->residual_norms_history_.size() - 1,
303 isOscillate,
304 isStagnate);
305 if (isOscillate) {
306 this->current_relaxation_ -= nonlinear_solver.relaxIncrement();
307 this->current_relaxation_ = std::max(this->current_relaxation_, nonlinear_solver.relaxMax());
308 // The detector reads reservoir residual history and the response damps the
309 // reservoir update, but the oscillation may originate in the well/group
310 // control layer. Record what was unsatisfied here so the two can be told
311 // apart.
313 if (!this->convergence_reports_.empty() &&
314 !this->convergence_reports_.back().report.empty())
315 {
316 auto& convrep = this->convergence_reports_.back().report.back();
317 source = classifyOscillationSource(convrep);
318 convrep.setOscillationSource(source);
319 }
320 if (this->terminalOutputEnabled()) {
321 OpmLog::info(" Oscillating behavior detected (" + to_string(source)
322 + "): Relaxation set to "
323 + std::to_string(this->current_relaxation_));
324 }
325 }
326 nonlinear_solver.stabilizeNonlinearUpdate(x, this->dx_old_, this->current_relaxation_);
327 }
328
329 this->updateSolution(x);
330 report.update_time += perfTimer.stop();
331 }
332
333 return report;
334}
335
336template <class TypeTag>
339relativeChange() const
340{
341 Scalar resultDelta = 0.0;
342 Scalar resultDenom = 0.0;
343
344 const auto& elemMapper = this->simulator_.model().elementMapper();
345 const auto& gridView = this->simulator_.gridView();
346 for (const auto& elem : elements(gridView, Dune::Partitions::interior)) {
347 unsigned globalElemIdx = elemMapper.index(elem);
348 const auto& priVarsNew = this->simulator_.model().solution(/*timeIdx=*/0)[globalElemIdx];
349
350 Scalar pressureNew;
351 pressureNew = priVarsNew[Indices::pressureSwitchIdx];
352
353 Scalar saturationsNew[FluidSystem::numPhases] = { 0.0 };
354 Scalar oilSaturationNew = 1.0;
355 if (FluidSystem::phaseIsActive(FluidSystem::waterPhaseIdx) &&
356 FluidSystem::numActivePhases() > 1 &&
357 priVarsNew.primaryVarsMeaningWater() == PrimaryVariables::WaterMeaning::Sw)
358 {
359 saturationsNew[FluidSystem::waterPhaseIdx] = priVarsNew[Indices::waterSwitchIdx];
360 oilSaturationNew -= saturationsNew[FluidSystem::waterPhaseIdx];
361 }
362
363 if (FluidSystem::phaseIsActive(FluidSystem::gasPhaseIdx) &&
364 FluidSystem::phaseIsActive(FluidSystem::oilPhaseIdx) &&
365 priVarsNew.primaryVarsMeaningGas() == PrimaryVariables::GasMeaning::Sg)
366 {
367 assert(Indices::compositionSwitchIdx != std::numeric_limits<unsigned>::max());
368 saturationsNew[FluidSystem::gasPhaseIdx] = priVarsNew[Indices::compositionSwitchIdx];
369 oilSaturationNew -= saturationsNew[FluidSystem::gasPhaseIdx];
370 }
371
372 if (FluidSystem::phaseIsActive(FluidSystem::oilPhaseIdx)) {
373 saturationsNew[FluidSystem::oilPhaseIdx] = oilSaturationNew;
374 }
375
376 const auto& priVarsOld = this->simulator_.model().solution(/*timeIdx=*/1)[globalElemIdx];
377
378 Scalar pressureOld;
379 pressureOld = priVarsOld[Indices::pressureSwitchIdx];
380
381 Scalar saturationsOld[FluidSystem::numPhases] = { 0.0 };
382 Scalar oilSaturationOld = 1.0;
383
384 // NB fix me! adding pressures changes to saturation changes does not make sense
385 Scalar tmp = pressureNew - pressureOld;
386 resultDelta += tmp*tmp;
387 resultDenom += pressureNew*pressureNew;
388
389 if (FluidSystem::numActivePhases() > 1) {
390 if (priVarsOld.primaryVarsMeaningWater() == PrimaryVariables::WaterMeaning::Sw) {
391 saturationsOld[FluidSystem::waterPhaseIdx] =
392 priVarsOld[Indices::waterSwitchIdx];
393 oilSaturationOld -= saturationsOld[FluidSystem::waterPhaseIdx];
394 }
395
396 if (priVarsOld.primaryVarsMeaningGas() == PrimaryVariables::GasMeaning::Sg)
397 {
398 assert(Indices::compositionSwitchIdx != std::numeric_limits<unsigned>::max());
399 saturationsOld[FluidSystem::gasPhaseIdx] =
400 priVarsOld[Indices::compositionSwitchIdx];
401 oilSaturationOld -= saturationsOld[FluidSystem::gasPhaseIdx];
402 }
403
404 if (FluidSystem::phaseIsActive(FluidSystem::oilPhaseIdx)) {
405 saturationsOld[FluidSystem::oilPhaseIdx] = oilSaturationOld;
406 }
407 for (unsigned phaseIdx = 0; phaseIdx < FluidSystem::numPhases; ++ phaseIdx) {
408 Scalar tmpSat = saturationsNew[phaseIdx] - saturationsOld[phaseIdx];
409 resultDelta += tmpSat*tmpSat;
410 resultDenom += saturationsNew[phaseIdx]*saturationsNew[phaseIdx];
411 // Non-finite here comes from the solution, not from a broken
412 // invariant, so report it instead of vanishing in release.
413 if (!std::isfinite(resultDelta) || !std::isfinite(resultDenom)) {
414 OPM_THROW(std::runtime_error,
415 "Non-finite solution change in the convergence measure");
416 }
417 }
418 }
419 }
420
421 resultDelta = gridView.comm().sum(resultDelta);
422 resultDenom = gridView.comm().sum(resultDenom);
423
424 return resultDenom > 0.0 ? resultDelta / resultDenom : 0.0;
425}
426
427template <class TypeTag>
428void
431{
432 auto& jacobian = this->simulator_.model().linearizer().jacobian().istlMatrix();
433 auto& residual = this->simulator_.model().linearizer().residual();
434 auto& linSolver = this->simulator_.model().newtonMethod().linearSolver();
435
436#if HAVE_CUDA && OPM_IS_COMPILING_WITH_GPU_COMPILER
437 if constexpr (getPropValue<TypeTag, Properties::RunAssemblyOnGpu>()) {
438 if (this->simulator_.model().linearizer().gpuSystemActive()) {
439 auto& linearizer = this->simulator_.model().linearizer();
440 Dune::Timer perfTimer;
441 perfTimer.start();
442 if (linSolver.prepareGpu(linearizer.gpuJacobian(),
443 linearizer.flattenedGpuResidual()))
444 {
445 this->linear_solve_setup_time_ = perfTimer.stop();
446 x = 0.0;
447 linSolver.solveGpu(x);
448 return;
449 }
450 }
451 }
452#endif
453
454 const int numSolvers = linSolver.numAvailableSolvers();
455 if (numSolvers > 1 && (linSolver.getSolveCount() % 100 == 0)) {
456 if (this->terminal_output_) {
457 OpmLog::debug("\nRunning speed test for comparing available linear solvers.");
458 }
459
460 Dune::Timer perfTimer;
461 std::vector<double> times(numSolvers);
462 std::vector<double> setupTimes(numSolvers);
463
464 x = 0.0;
465 std::vector<BVector> x_trial(numSolvers, x);
466 for (int solver = 0; solver < numSolvers; ++solver) {
467 linSolver.setActiveSolver(solver);
468 perfTimer.start();
469 linSolver.prepare(jacobian, residual);
470 setupTimes[solver] = perfTimer.stop();
471 perfTimer.reset();
472 linSolver.setResidual(residual);
473 perfTimer.start();
474 linSolver.solve(x_trial[solver]);
475 times[solver] = setupTimes[solver] + perfTimer.stop();
476 perfTimer.reset();
477 if (this->terminal_output_) {
478 OpmLog::debug(fmt::format(fmt::runtime("Solver time {}: {}"), solver, times[solver]));
479 }
480 }
481
482 int fastest_solver = std::ranges::min_element(times) - times.begin();
483 // Use timing on rank 0 to determine fastest, must be consistent across ranks.
484 this->grid_.comm().broadcast(&fastest_solver, 1, 0);
485 this->linear_solve_setup_time_ = setupTimes[fastest_solver];
486 x = x_trial[fastest_solver];
487 linSolver.setActiveSolver(fastest_solver);
488 }
489 else {
490 x = 0.0;
491
492 Dune::Timer perfTimer;
493 perfTimer.start();
494 linSolver.prepare(jacobian, residual);
495 this->linear_solve_setup_time_ = perfTimer.stop();
496 linSolver.setResidual(residual);
497 // actually, the error needs to be calculated after setResidual in order to
498 // account for parallelization properly. since the residual of ECFV
499 // discretizations does not need to be synchronized across processes to be
500 // consistent, this is not relevant for OPM-flow...
501 linSolver.solve(x);
502 }
503}
504
505template <class TypeTag>
506bool
509{
510 return this->param_.tolerance_max_dp_ > 0.0 || this->param_.tolerance_max_ds_ > 0.0
511 || this->param_.tolerance_max_drs_ > 0.0 || this->param_.tolerance_max_drv_ > 0.0;
512}
513
514template <class TypeTag>
515void
518{
519 // Init. solution update vector
520 unsigned nc = this->simulator_.model().numGridDof();
521 solUpd_.resize(nc);
522
523 const auto& elemMapper = this->simulator_.model().elementMapper();
524 const auto& gridView = this->simulator_.gridView();
525 for (const auto& elem : elements(gridView, Dune::Partitions::interior)) {
526 // Copy solution vector to transfer primary variables meaning
527 unsigned globalElemIdx = elemMapper.index(elem);
528 solUpd_[globalElemIdx] = this->simulator_.model().solution(/*timeIdx=*/0)[globalElemIdx];
529
530 // Ensure each element is zero
531 std::ranges::fill(solUpd_[globalElemIdx], 0.0);
532 }
533}
534
535template <class TypeTag>
536void
539{
540 const auto& elemMapper = this->simulator_.model().elementMapper();
541 const auto& gridView = this->simulator_.gridView();
542 for (const auto& elem : elements(gridView, Dune::Partitions::interior)) {
543 // Get cell vectors
544 unsigned globalElemIdx = elemMapper.index(elem);
545 auto& value = solUpd_[globalElemIdx];
546 const auto& update = dx[globalElemIdx];
547 assert(value.size() == update.size());
548
549 // Transfer update from dx to solution update container (SolutionVector type)
550 std::ranges::copy(update, value.begin());
551 }
552}
553
554template <class TypeTag>
557getMaxSolutionUpdate(const std::vector<unsigned>& ixCells)
558{
559 static constexpr bool enableSolvent =
560 Indices::solventSaturationIdx != std::numeric_limits<unsigned>::max();
561 static constexpr bool enableBrine =
562 Indices::saltConcentrationIdx != std::numeric_limits<unsigned>::max();
563
564 // Init output
565 Scalar dPMax = 0.0;
566 Scalar dSMax = 0.0;
567 Scalar dRsMax = 0.0;
568 Scalar dRvMax = 0.0;
569
570 // Loop over solution update, get the correct variables and calculate max.
571 for (const auto& ix : ixCells) {
572 const auto& value = solUpd_[ix];
573 for (unsigned pvIdx = 0; pvIdx < value.size(); ++pvIdx) {
574 if (pvIdx == Indices::pressureSwitchIdx) {
575 dPMax = std::max(dPMax, std::abs(value[pvIdx]));
576 }
577 else if ((pvIdx == Indices::waterSwitchIdx
578 && value.primaryVarsMeaningWater() == PrimaryVariables::WaterMeaning::Sw)
579 || (pvIdx == Indices::compositionSwitchIdx
580 && value.primaryVarsMeaningGas() == PrimaryVariables::GasMeaning::Sg)
581 || (enableSolvent && pvIdx == Indices::solventSaturationIdx
582 && value.primaryVarsMeaningSolvent() == PrimaryVariables::SolventMeaning::Ss)
583 || (enableBrine && enableSaltPrecipitation && pvIdx == Indices::saltConcentrationIdx
584 && value.primaryVarsMeaningBrine() == PrimaryVariables::BrineMeaning::Sp) ) {
585 dSMax = std::max(dSMax, std::abs(value[pvIdx]));
586 }
587 else if (pvIdx == Indices::compositionSwitchIdx
588 && value.primaryVarsMeaningGas() == PrimaryVariables::GasMeaning::Rs) {
589 dRsMax = std::max(dRsMax, std::abs(value[pvIdx]));
590 }
591 else if (pvIdx == Indices::compositionSwitchIdx
592 && value.primaryVarsMeaningGas() == PrimaryVariables::GasMeaning::Rv) {
593 dRvMax = std::max(dRvMax, std::abs(value[pvIdx]));
594 }
595 }
596 }
597
598 // Communicate max values
599 dPMax = this->grid_.comm().max(dPMax);
600 dSMax = this->grid_.comm().max(dSMax);
601 dRsMax = this->grid_.comm().max(dRsMax);
602 dRvMax = this->grid_.comm().max(dRvMax);
603
604 return { dPMax, dSMax, dRsMax, dRvMax };
605}
606
607template <class TypeTag>
608std::tuple<typename NonlinearSystemBlackOilReservoir<TypeTag>::Scalar,
612 const Scalar pvSumLocal,
613 const Scalar numAquiferPvSumLocal,
614 std::vector< Scalar >& R_sum,
615 std::vector< Scalar >& maxCoeff,
616 std::vector< Scalar >& B_avg)
617{
618 return ParentType::convergenceReduction(comm,
619 pvSumLocal,
620 numAquiferPvSumLocal,
621 R_sum,
622 maxCoeff,
623 B_avg);
624}
625
626template <class TypeTag>
627std::pair<typename NonlinearSystemBlackOilReservoir<TypeTag>::Scalar,
630localConvergenceData(std::vector<Scalar>& R_sum,
631 std::vector<Scalar>& maxCoeff,
632 std::vector<Scalar>& B_avg,
633 std::vector<int>& maxCoeffCell)
634{
635 OPM_TIMEBLOCK(localConvergenceData);
636 Scalar pvSumLocal = 0.0;
637 Scalar numAquiferPvSumLocal = 0.0;
638 const auto& model = this->simulator_.model();
639 const auto& problem = this->simulator_.problem();
640
641 const auto& residual = this->simulator_.model().linearizer().residual();
642
643 ElementContext elemCtx(this->simulator_);
644 const auto& gridView = this->simulator().gridView();
645 IsNumericalAquiferCell isNumericalAquiferCell(gridView.grid());
647 for (const auto& elem : elements(gridView, Dune::Partitions::interior)) {
648 elemCtx.updatePrimaryStencil(elem);
649 elemCtx.updatePrimaryIntensiveQuantities(/*timeIdx=*/0);
650
651 const unsigned cell_idx = elemCtx.globalSpaceIndex(/*spaceIdx=*/0, /*timeIdx=*/0);
652 const auto& intQuants = elemCtx.intensiveQuantities(/*spaceIdx=*/0, /*timeIdx=*/0);
653 const auto& fs = intQuants.fluidState();
654
655 const auto pvValue = problem.referencePorosity(cell_idx, /*timeIdx=*/0) *
656 model.dofTotalVolume(cell_idx);
657 pvSumLocal += pvValue;
658
659 if (isNumericalAquiferCell(elem)) {
660 numAquiferPvSumLocal += pvValue;
661 }
662
663 this->getMaxCoeff(cell_idx, intQuants, fs, residual, pvValue,
664 B_avg, R_sum, maxCoeff, maxCoeffCell);
665 }
666
667 OPM_END_PARALLEL_TRY_CATCH("NonlinearSystemBlackOilReservoir::localConvergenceData() failed: ", this->grid_.comm());
668
669 // compute local average in terms of global number of elements
670 const int bSize = B_avg.size();
671 for (int i = 0; i < bSize; ++i) {
672 B_avg[i] /= Scalar(this->global_nc_);
673 }
674
675 return {pvSumLocal, numAquiferPvSumLocal};
676}
677
678template <class TypeTag>
681characteriseCnvPvSplit(const std::vector<Scalar>& B_avg, const double dt)
682{
683 OPM_TIMEBLOCK(computeCnvErrorPv);
684
685 // 0: cnv <= tolerance_cnv
686 // 1: tolerance_cnv < cnv <= tolerance_cnv_relaxed
687 // 2: tolerance_cnv_relaxed < cnv
688 constexpr auto numPvGroups = std::vector<double>::size_type{3};
689
690 auto cnvPvSplit = std::pair<std::vector<double>, std::vector<int>> {
691 std::piecewise_construct,
692 std::forward_as_tuple(numPvGroups),
693 std::forward_as_tuple(numPvGroups)
694 };
695
696 auto maxCNV = [&B_avg, dt](const auto& residual, const double pvol)
697 {
698 return (dt / pvol) *
699 std::inner_product(residual.begin(), residual.end(),
700 B_avg.begin(), Scalar{0},
701 [](const Scalar m, const auto& x)
702 {
703 using std::abs;
704 return std::max(m, abs(x));
705 }, std::multiplies<>{});
706 };
707
708 auto& [splitPV, cellCntPV] = cnvPvSplit;
709
710 const auto& model = this->simulator().model();
711 const auto& problem = this->simulator().problem();
712 const auto& residual = model.linearizer().residual();
713 const auto& gridView = this->simulator().gridView();
714
715 const IsNumericalAquiferCell isNumericalAquiferCell(gridView.grid());
716
717 ElementContext elemCtx(this->simulator());
718
719 std::vector<unsigned> ixCells;
720
722 for (const auto& elem : elements(gridView, Dune::Partitions::interior)) {
723 // Skip cells of numerical Aquifer
724 if (isNumericalAquiferCell(elem)) {
725 continue;
726 }
727
728 elemCtx.updatePrimaryStencil(elem);
729
730 const unsigned cell_idx = elemCtx.globalSpaceIndex(/*spaceIdx=*/0, /*timeIdx=*/0);
731 const auto pvValue = problem.referencePorosity(cell_idx, /*timeIdx=*/0)
732 * model.dofTotalVolume(cell_idx);
733
734 const auto maxCnv = maxCNV(residual[cell_idx], pvValue);
735
736 const auto ix = (maxCnv > this->param_.tolerance_cnv_)
737 + (maxCnv > this->param_.tolerance_cnv_relaxed_);
738
739 splitPV[ix] += static_cast<double>(pvValue);
740 ++cellCntPV[ix];
741
742 // For dP and dS check, we need cell indices of [1] violations
743 if ( ix > 0 &&
744 (this->param_.tolerance_max_dp_ > 0.0 || this->param_.tolerance_max_ds_ > 0.0
745 || this->param_.tolerance_max_drs_ > 0.0 || this->param_.tolerance_max_drv_ > 0.0 ) ) {
746 ixCells.push_back(cell_idx);
747 }
748 }
749
750 OPM_END_PARALLEL_TRY_CATCH("NonlinearSystemBlackOilReservoir::characteriseCnvPvSplit() failed: ",
751 this->grid_.comm());
752
753 this->grid_.comm().sum(splitPV .data(), splitPV .size());
754 this->grid_.comm().sum(cellCntPV.data(), cellCntPV.size());
755
756 return { cnvPvSplit, ixCells };
757}
758
759template <class TypeTag>
762getReservoirConvergence(const double reportTime,
763 const double dt,
764 const int maxIter,
765 std::vector<Scalar>& B_avg,
766 std::vector<Scalar>& residual_norms)
767{
768 OPM_TIMEBLOCK(getReservoirConvergence);
769 using Vector = std::vector<Scalar>;
770
771 const auto& iterCtx = this->simulator_.problem().iterationContext();
772
773 ConvergenceReport report{reportTime};
774
775 const int numComp = numEq;
776
777 Vector R_sum(numComp, Scalar{0});
778 Vector maxCoeff(numComp, std::numeric_limits<Scalar>::lowest());
779 std::vector<int> maxCoeffCell(numComp, -1);
780
781 const auto [pvSumLocal, numAquiferPvSumLocal] =
782 this->localConvergenceData(R_sum, maxCoeff, B_avg, maxCoeffCell);
783
784 // compute global sum and max of quantities
785 const auto& [pvSum, numAquiferPvSum] =
786 this->convergenceReduction(this->grid_.comm(),
787 pvSumLocal,
788 numAquiferPvSumLocal,
789 R_sum, maxCoeff, B_avg);
790
791 auto cnvSplitData = this->characteriseCnvPvSplit(B_avg, dt);
792 report.setCnvPoreVolSplit(cnvSplitData.cnvPvSplit,
793 pvSum - numAquiferPvSum);
794
795 // For each iteration, we need to determine whether to use the
796 // relaxed tolerances. To disable the usage of relaxed
797 // tolerances, you can set the relaxed tolerances as the strict
798 // tolerances. If min_strict_mb_iter = -1 (default) we use a
799 // relaxed tolerance for the mass balance for the last
800 // iterations. For positive values we use the relaxed tolerance
801 // after the given number of iterations
802 const bool relax_final_iteration_mb =
803 this->param_.min_strict_mb_iter_ < 0 && iterCtx.iteration() == maxIter;
804
805 const bool relax_iter_mb = this->param_.min_strict_mb_iter_ >= 0 &&
806 iterCtx.shouldRelax(this->param_.min_strict_mb_iter_);
807
808 const bool use_relaxed_mb = relax_final_iteration_mb
809 || relax_iter_mb;
810
811 // If min_strict_cnv_iter = -1 we use a relaxed tolerance for
812 // the cnv for the last iterations. For positive values we use
813 // the relaxed tolerance after the given number of iterations.
814 // We also use relaxed tolerances for cells with total
815 // pore-volume less than relaxed_max_pv_fraction_. Default
816 // value of relaxed_max_pv_fraction_ is 0.03
817 const bool relax_final_iteration_cnv =
818 this->param_.min_strict_cnv_iter_ < 0 && iterCtx.iteration() == maxIter;
819
820 const bool relax_iter_cnv = this->param_.min_strict_cnv_iter_ >= 0 &&
821 iterCtx.shouldRelax(this->param_.min_strict_cnv_iter_);
822
823 // Note trailing parentheses here, just before the final
824 // semicolon. This is an immediately invoked function
825 // expression which calculates a single boolean value.
826 const auto relax_pv_fraction_cnv =
827 [&report, this, eligible = pvSum - numAquiferPvSum]()
828 {
829 const auto& cnvPvSplit = report.cnvPvSplit().first;
830
831 // [1]: tol < cnv <= relaxed
832 // [2]: relaxed < cnv
833 Scalar cnvPvSum = static_cast<Scalar>(cnvPvSplit[1] + cnvPvSplit[2]);
834 return cnvPvSum < this->param_.relaxed_max_pv_fraction_ * eligible &&
835 cnvPvSum > 0.0;
836 }();
837
838 // If tolerances for solution changes are met, we use the
839 // relaxed cnv tolerance. Note that all tolerances > 0.0
840 // must be met to enable use of relaxed cnv tolerance.
841 MaxSolutionUpdateData maxSolUpd;
842 const bool use_dp_tol = this->param_.tolerance_max_dp_ > 0.0;
843 const bool use_ds_tol = this->param_.tolerance_max_ds_ > 0.0;
844 const bool use_drs_tol = this->param_.tolerance_max_drs_ > 0.0;
845 const bool use_drv_tol = this->param_.tolerance_max_drv_ > 0.0;
846 const bool use_dsol_tol = use_dp_tol || use_ds_tol || use_drs_tol || use_drv_tol;
847 bool relax_dsol_cnv = false;
848 if (!iterCtx.isFirstGlobalIteration() && use_dsol_tol) {
849 maxSolUpd = getMaxSolutionUpdate(cnvSplitData.ixCells);
850 relax_dsol_cnv =
851 (!use_dp_tol || (maxSolUpd.dPMax > 0.0 && maxSolUpd.dPMax < this->param_.tolerance_max_dp_)) &&
852 (!use_ds_tol || (maxSolUpd.dSMax > 0.0 && maxSolUpd.dSMax < this->param_.tolerance_max_ds_)) &&
853 (!use_drs_tol || (maxSolUpd.dRsMax > 0.0 && maxSolUpd.dRsMax < this->param_.tolerance_max_drs_)) &&
854 (!use_drv_tol || (maxSolUpd.dRvMax > 0.0 && maxSolUpd.dRvMax < this->param_.tolerance_max_drv_));
855 }
856
857 // Determine if relaxed CNV tolerances should be used
858 const bool use_relaxed_cnv = relax_final_iteration_cnv
859 || relax_pv_fraction_cnv
860 || relax_iter_cnv
861 || relax_dsol_cnv;
862
863 // Ensure that CNV convergence criteria is met when max.
864 // solution change tolerances have been fulfilled
865 Scalar tolerance_cnv_relaxed = relax_dsol_cnv ? 1e20 : this->param_.tolerance_cnv_relaxed_;
866
867 const auto tol_cnv = use_relaxed_cnv ? tolerance_cnv_relaxed : this->param_.tolerance_cnv_;
868 const auto tol_mb = use_relaxed_mb ? this->param_.tolerance_mb_relaxed_ : this->param_.tolerance_mb_;
869
870 // Record which condition granted the relaxation, so the accepted state's quality is
871 // visible in the output. Order mirrors the code's own precedence.
872 {
874 const auto source = relax_dsol_cnv ? RS::SolChange
875 : relax_pv_fraction_cnv ? RS::PvFraction
876 : relax_final_iteration_cnv ? RS::FinalIter
877 : relax_iter_cnv ? RS::IterCount
878 : RS::None;
879 report.setCnvRelaxation(source, static_cast<double>(tol_cnv));
880 }
881 const auto tol_cnv_energy = use_relaxed_cnv ? this->param_.tolerance_cnv_energy_relaxed_ : this->param_.tolerance_cnv_energy_;
882 const auto tol_eb = use_relaxed_mb ? this->param_.tolerance_energy_balance_relaxed_ : this->param_.tolerance_energy_balance_;
883
884 // Finish computation
885 std::vector<Scalar> CNV(numComp);
886 std::vector<Scalar> mass_balance_residual(numComp);
887 for (int compIdx = 0; compIdx < numComp; ++compIdx)
888 {
889 CNV[compIdx] = B_avg[compIdx] * dt * maxCoeff[compIdx];
890 mass_balance_residual[compIdx] = std::abs(B_avg[compIdx]*R_sum[compIdx]) * dt / pvSum;
891 residual_norms.push_back(CNV[compIdx]);
892 }
893
894 using CR = ConvergenceReport;
895 for (int compIdx = 0; compIdx < numComp; ++compIdx) {
896 const Scalar res[2] = {
897 mass_balance_residual[compIdx], CNV[compIdx],
898 };
899
900 const CR::ReservoirFailure::Type types[2] = {
901 CR::ReservoirFailure::Type::MassBalance,
902 CR::ReservoirFailure::Type::Cnv,
903 };
904
905 Scalar tol[2] = { tol_mb, tol_cnv, };
906 if (has_energy_ && compIdx == contiEnergyEqIdx) {
907 tol[0] = tol_eb;
908 tol[1] = tol_cnv_energy;
909 }
910
911 this->addReservoirConvergenceMetrics(
912 report,
913 compIdx,
914 this->compNames_.name(compIdx),
915 std::span<const Scalar>{res},
916 std::span<const CR::ReservoirFailure::Type>{types},
917 std::span<const Scalar>{tol},
918 maxResidualAllowed(),
919 [this](const std::string& message)
920 {
921 if (this->terminal_output_) {
922 OpmLog::debug(message);
923 }
924 });
925 }
926
927 // Compute the Newton convergence per cell.
928 this->convergencePerCell(B_avg, dt, tol_cnv, tol_cnv_energy);
929
930 // Output of residuals.
931 if (this->terminal_output_) {
932 // Only rank 0 does print to std::cout
933 if (iterCtx.isFirstGlobalIteration()) {
934 std::string msg = "Iter";
935 for (int compIdx = 0; compIdx < numComp; ++compIdx) {
936 msg += " MB(";
937 msg += this->compNames_.name(compIdx)[0];
938 msg += ") ";
939 }
940
941 for (int compIdx = 0; compIdx < numComp; ++compIdx) {
942 msg += " CNV(";
943 msg += this->compNames_.name(compIdx)[0];
944 msg += ") ";
945 }
946
947 if (use_dsol_tol) {
948 msg += use_dp_tol ? " DP " : "";
949 msg += use_ds_tol ? " DS " : "";
950 msg += use_drs_tol ? " DRS " : "";
951 msg += use_drv_tol ? " DRV " : "";
952 }
953
954 msg += " MBFLAG";
955 msg += " CNVFLAG";
956
957 OpmLog::debug(msg);
958 }
959
960 std::ostringstream ss;
961 const std::streamsize oprec = ss.precision(3);
962 const std::ios::fmtflags oflags = ss.setf(std::ios::scientific);
963
964 ss << std::setw(4) << iterCtx.iteration();
965 for (int compIdx = 0; compIdx < numComp; ++compIdx) {
966 ss << std::setw(11) << mass_balance_residual[compIdx];
967 }
968
969 for (int compIdx = 0; compIdx < numComp; ++compIdx) {
970 ss << std::setw(11) << CNV[compIdx];
971 }
972
973 if (use_dsol_tol) {
974 auto print_dsol =
975 [&] (bool use_tol, Scalar dsol) {
976 if (!use_tol) {
977 return;
978 }
979 if (iterCtx.isFirstGlobalIteration() || dsol <= 0.0) {
980 ss << std::string(5, ' ') << "-" << std::string(5, ' ');
981 }
982 else {
983 ss << std::setw(11) << dsol;
984 }
985 };
986 print_dsol(use_dp_tol, maxSolUpd.dPMax);
987 print_dsol(use_ds_tol, maxSolUpd.dSMax);
988 print_dsol(use_drs_tol, maxSolUpd.dRsMax);
989 print_dsol(use_drv_tol, maxSolUpd.dRvMax);
990 }
991
992 const auto mb_flag = use_relaxed_mb
993 ? DebugFlags::Relaxed
994 : DebugFlags::Strict;
995
996 const auto cnv_flag = relax_dsol_cnv ?
997 DebugFlags::TuningDP
998 : (use_relaxed_cnv
999 ? DebugFlags::Relaxed
1000 : DebugFlags::Strict);
1001
1002 ss << std::setw(9) << make_string<TypeTag>(mb_flag)
1003 << std::setw(9) << make_string<TypeTag>(cnv_flag);
1004
1005 ss.precision(oprec);
1006 ss.flags(oflags);
1007
1008 OpmLog::debug(ss.str());
1009 }
1010
1011 return report;
1012}
1013
1014template <class TypeTag>
1015void
1017convergencePerCell(const std::vector<Scalar>& B_avg,
1018 const double dt,
1019 const double tol_cnv,
1020 const double tol_cnv_energy)
1021{
1022 auto& rst_conv = this->simulator_.problem().eclWriter().mutableOutputModule().getConv();
1023 if (!rst_conv.hasConv()) {
1024 return;
1025 }
1026
1027 if (this->simulator_.problem().iterationContext().isFirstGlobalIteration()) {
1028 rst_conv.prepareConv();
1029 }
1030
1031 const auto& residual = this->simulator_.model().linearizer().residual();
1032 const auto& gridView = this->simulator_.gridView();
1033 const IsNumericalAquiferCell isNumericalAquiferCell(gridView.grid());
1034 ElementContext elemCtx(this->simulator());
1035 std::vector<int> convNewt(residual.size(), 0);
1037 unsigned idx = 0;
1038 const int numComp = B_avg.size();
1039 for (const auto& elem : elements(gridView, Dune::Partitions::interior)) {
1040 elemCtx.updatePrimaryStencil(elem);
1041
1042 const unsigned cell_idx = elemCtx.globalSpaceIndex(/*spaceIdx=*/0, /*timeIdx=*/0);
1043 const auto pvValue = this->simulator_.problem().referencePorosity(cell_idx, /*timeIdx=*/0) *
1044 this->simulator_.model().dofTotalVolume(cell_idx);
1045 for (int compIdx = 0; compIdx < numComp; ++compIdx) {
1046 const auto tol = (has_energy_ && compIdx == contiEnergyEqIdx) ? tol_cnv_energy : tol_cnv;
1047 const Scalar cnv = std::abs(B_avg[compIdx] * residual[cell_idx][compIdx]) * dt / pvValue;
1048 if (std::isnan(cnv) || cnv > maxResidualAllowed() || cnv < 0.0 || cnv > tol) {
1049 convNewt[idx] = 1;
1050 break;
1051 }
1052 }
1053 ++idx;
1054 }
1055 OPM_END_PARALLEL_TRY_CATCH("NonlinearSystemBlackOilReservoir::convergencePerCell() failed: ",
1056 this->grid_.comm());
1057 rst_conv.updateNewton(convNewt);
1058}
1059
1060template <class TypeTag>
1064 const int maxIter,
1065 std::vector<Scalar>& residual_norms)
1066{
1067 OPM_TIMEBLOCK(getConvergence);
1068 // Get convergence reports for reservoir and wells.
1069 std::vector<Scalar> B_avg(numEq, 0.0);
1070 auto report = getReservoirConvergence(timer.simulationTimeElapsed(),
1071 timer.currentStepLength(),
1072 maxIter, B_avg, residual_norms);
1073 {
1074 OPM_TIMEBLOCK(getWellConvergence);
1075 report += this->wellModel().getWellConvergence(B_avg,
1076 /*checkWellGroupControlsAndNetwork*/report.converged());
1077 }
1078
1079 conv_monitor_.checkPenaltyCard(report, this->simulator_.problem().iterationContext().iteration());
1080
1081 return report;
1082}
1083
1084template <class TypeTag>
1085std::vector<std::vector<typename NonlinearSystemBlackOilReservoir<TypeTag>::Scalar> >
1087computeFluidInPlace(const std::vector<int>& /*fipnum*/) const
1088{
1089 OPM_TIMEBLOCK(computeFluidInPlace);
1090 // assert(true)
1091 // return an empty vector
1092 std::vector<std::vector<Scalar> > regionValues(0, std::vector<Scalar>(0,0.0));
1093 return regionValues;
1094}
1095
1096template <class TypeTag>
1097const SimulatorReport&
1100{
1101 if (!hasNlddSolver()) {
1102 OPM_THROW(std::runtime_error, "Cannot get local reports from a model without NLDD solver");
1103 }
1104 return nlddSolver_->localAccumulatedReports();
1105}
1106
1107template <class TypeTag>
1108const std::vector<SimulatorReport>&
1111{
1112 if (!nlddSolver_)
1113 OPM_THROW(std::runtime_error, "Cannot get domain reports from a model without NLDD solver");
1114 return nlddSolver_->domainAccumulatedReports();
1115}
1116
1117template <class TypeTag>
1118void
1120writeNonlinearIterationsPerCell(const std::filesystem::path& odir) const
1121{
1122 if (hasNlddSolver()) {
1123 nlddSolver_->writeNonlinearIterationsPerCell(odir);
1124 }
1125}
1126
1127template <class TypeTag>
1128void
1130writePartitions(const std::filesystem::path& odir) const
1131{
1132 if (hasNlddSolver()) {
1133 nlddSolver_->writePartitions(odir);
1134 return;
1135 }
1136
1137 const auto& elementMapper = this->simulator().model().elementMapper();
1138 const auto& cartMapper = this->simulator().vanguard().cartesianIndexMapper();
1139
1140 const auto& grid = this->simulator().vanguard().grid();
1141 const auto& comm = grid.comm();
1142 const auto nDigit = 1 + static_cast<int>(std::floor(std::log10(comm.size())));
1143
1144 std::ofstream pfile {odir / fmt::format("{1:0>{0}}", nDigit, comm.rank())};
1145
1146 for (const auto& cell : elements(grid.leafGridView(), Dune::Partitions::interior)) {
1147 pfile << comm.rank() << ' '
1148 << cartMapper.cartesianIndex(elementMapper.index(cell)) << ' '
1149 << comm.rank() << '\n';
1150 }
1151}
1152
1153template <class TypeTag>
1154template<class FluidState, class Residual>
1155void
1157getMaxCoeff(const unsigned cell_idx,
1158 const IntensiveQuantities& intQuants,
1159 const FluidState& fs,
1160 const Residual& modelResid,
1161 const Scalar pvValue,
1162 std::vector<Scalar>& B_avg,
1163 std::vector<Scalar>& R_sum,
1164 std::vector<Scalar>& maxCoeff,
1165 std::vector<int>& maxCoeffCell)
1166{
1167 for (unsigned phaseIdx = 0; phaseIdx < FluidSystem::numPhases; ++phaseIdx)
1168 {
1169 if (!FluidSystem::phaseIsActive(phaseIdx)) {
1170 continue;
1171 }
1172
1173 const unsigned sIdx = FluidSystem::solventComponentIndex(phaseIdx);
1174 const unsigned compIdx = FluidSystem::canonicalToActiveCompIdx(sIdx);
1175
1176 B_avg[compIdx] += 1.0 / fs.invB(phaseIdx).value();
1177 const auto R2 = modelResid[cell_idx][compIdx];
1178
1179 R_sum[compIdx] += R2;
1180 const Scalar Rval = std::abs(R2) / pvValue;
1181 if (Rval > maxCoeff[compIdx]) {
1182 maxCoeff[compIdx] = Rval;
1183 maxCoeffCell[compIdx] = cell_idx;
1184 }
1185 }
1186
1187 if constexpr (has_solvent_) {
1188 B_avg[contiSolventEqIdx] +=
1189 1.0 / intQuants.solventInverseFormationVolumeFactor().value();
1190 const auto R2 = modelResid[cell_idx][contiSolventEqIdx];
1191 R_sum[contiSolventEqIdx] += R2;
1192 maxCoeff[contiSolventEqIdx] = std::max(maxCoeff[contiSolventEqIdx],
1193 std::abs(R2) / pvValue);
1194 }
1195 if constexpr (has_extbo_) {
1196 B_avg[contiZfracEqIdx] += 1.0 / fs.invB(FluidSystem::gasPhaseIdx).value();
1197 const auto R2 = modelResid[cell_idx][contiZfracEqIdx];
1198 R_sum[ contiZfracEqIdx ] += R2;
1199 maxCoeff[contiZfracEqIdx] = std::max(maxCoeff[contiZfracEqIdx],
1200 std::abs(R2) / pvValue);
1201 }
1202 if constexpr (has_polymer_) {
1203 B_avg[contiPolymerEqIdx] += 1.0 / fs.invB(FluidSystem::waterPhaseIdx).value();
1204 const auto R2 = modelResid[cell_idx][contiPolymerEqIdx];
1205 R_sum[contiPolymerEqIdx] += R2;
1206 maxCoeff[contiPolymerEqIdx] = std::max(maxCoeff[contiPolymerEqIdx],
1207 std::abs(R2) / pvValue);
1208 }
1209 if constexpr (has_foam_) {
1210 B_avg[ contiFoamEqIdx ] += 1.0 / fs.invB(FluidSystem::gasPhaseIdx).value();
1211 const auto R2 = modelResid[cell_idx][contiFoamEqIdx];
1212 R_sum[contiFoamEqIdx] += R2;
1213 maxCoeff[contiFoamEqIdx] = std::max(maxCoeff[contiFoamEqIdx],
1214 std::abs(R2) / pvValue);
1215 }
1216 if constexpr (has_brine_) {
1217 B_avg[ contiBrineEqIdx ] += 1.0 / fs.invB(FluidSystem::waterPhaseIdx).value();
1218 const auto R2 = modelResid[cell_idx][contiBrineEqIdx];
1219 R_sum[contiBrineEqIdx] += R2;
1220 maxCoeff[contiBrineEqIdx] = std::max(maxCoeff[contiBrineEqIdx],
1221 std::abs(R2) / pvValue);
1222 }
1223
1224 if constexpr (has_polymermw_) {
1225 static_assert(has_polymer_);
1226
1227 B_avg[contiPolymerMWEqIdx] += 1.0 / fs.invB(FluidSystem::waterPhaseIdx).value();
1228 // the residual of the polymer molecular equation is scaled down by a 100, since molecular weight
1229 // can be much bigger than 1, and this equation shares the same tolerance with other mass balance equations
1230 // TODO: there should be a more general way to determine the scaling-down coefficient
1231 const auto R2 = modelResid[cell_idx][contiPolymerMWEqIdx] / 100.;
1232 R_sum[contiPolymerMWEqIdx] += R2;
1233 maxCoeff[contiPolymerMWEqIdx] = std::max(maxCoeff[contiPolymerMWEqIdx],
1234 std::abs(R2) / pvValue);
1235 }
1236
1237 if constexpr (has_energy_) {
1238 B_avg[contiEnergyEqIdx] += 1.0;
1239 const auto R2 = modelResid[cell_idx][contiEnergyEqIdx];
1240 R_sum[contiEnergyEqIdx] += R2;
1241 maxCoeff[contiEnergyEqIdx] = std::max(maxCoeff[contiEnergyEqIdx],
1242 std::abs(R2) / pvValue);
1243 }
1244
1245 if constexpr (has_bioeffects_) {
1246 B_avg[contiMicrobialEqIdx] += 1.0 / fs.invB(FluidSystem::waterPhaseIdx).value();
1247 const auto R1 = modelResid[cell_idx][contiMicrobialEqIdx];
1248 R_sum[contiMicrobialEqIdx] += R1;
1249 maxCoeff[contiMicrobialEqIdx] = std::max(maxCoeff[contiMicrobialEqIdx],
1250 std::abs(R1) / pvValue);
1251 B_avg[contiBiofilmEqIdx] += 1.0 / fs.invB(FluidSystem::waterPhaseIdx).value();
1252 const auto R2 = modelResid[cell_idx][contiBiofilmEqIdx];
1253 R_sum[contiBiofilmEqIdx] += R2;
1254 maxCoeff[contiBiofilmEqIdx] = std::max(maxCoeff[contiBiofilmEqIdx],
1255 std::abs(R2) / pvValue);
1256 if constexpr (has_micp_) {
1257 B_avg[contiOxygenEqIdx] += 1.0 / fs.invB(FluidSystem::waterPhaseIdx).value();
1258 const auto R3 = modelResid[cell_idx][contiOxygenEqIdx];
1259 R_sum[contiOxygenEqIdx] += R3;
1260 maxCoeff[contiOxygenEqIdx] = std::max(maxCoeff[contiOxygenEqIdx],
1261 std::abs(R3) / pvValue);
1262 B_avg[contiUreaEqIdx] += 1.0 / fs.invB(FluidSystem::waterPhaseIdx).value();
1263 const auto R4 = modelResid[cell_idx][contiUreaEqIdx];
1264 R_sum[contiUreaEqIdx] += R4;
1265 maxCoeff[contiUreaEqIdx] = std::max(maxCoeff[contiUreaEqIdx],
1266 std::abs(R4) / pvValue);
1267 B_avg[contiCalciteEqIdx] += 1.0 / fs.invB(FluidSystem::waterPhaseIdx).value();
1268 const auto R5 = modelResid[cell_idx][contiCalciteEqIdx];
1269 R_sum[contiCalciteEqIdx] += R5;
1270 maxCoeff[contiCalciteEqIdx] = std::max(maxCoeff[contiCalciteEqIdx],
1271 std::abs(R5) / pvValue);
1272 }
1273 }
1274}
1275
1276} // namespace Opm
1277
1278#endif // OPM_NONLINEAR_SYSTEM_BLACK_OIL_RESERVOIR_IMPL_HEADER_INCLUDED
#define OPM_END_PARALLEL_TRY_CATCH(prefix, comm)
Catch exception and throw in a parallel try-catch clause.
Definition: DeferredLoggingErrorHelpers.hpp:197
#define OPM_BEGIN_PARALLEL_TRY_CATCH()
Macro to setup the try of a parallel try-catch.
Definition: DeferredLoggingErrorHelpers.hpp:160
Definition: ConvergenceReport.hpp:38
Severity
Definition: ConvergenceReport.hpp:49
CnvRelaxSource
Definition: ConvergenceReport.hpp:246
@ None
strict tolerance applied
void prepareSolutionUpdate() override
Definition: NonlinearSystemBlackOilReservoir_impl.hpp:517
SimulatorReportSingle prepareStep(const SimulatorTimerInterface &timer)
Definition: NonlinearSystemBlackOilReservoir_impl.hpp:110
GetPropType< TypeTag, Properties::ElementContext > ElementContext
Definition: NonlinearSystemBlackOilReservoir.hpp:70
void storeSolutionUpdate(const GlobalEqVector &dx) override
Definition: NonlinearSystemBlackOilReservoir_impl.hpp:538
GetPropType< TypeTag, Properties::IntensiveQuantities > IntensiveQuantities
Definition: NonlinearSystemBlackOilReservoir.hpp:71
Opm::BlockVector< VectorBlockType > BVector
Definition: NonlinearSystemBlackOilReservoir.hpp:114
std::tuple< Scalar, Scalar > convergenceReduction(Parallel::Communication comm, const Scalar pvSumLocal, const Scalar numAquiferPvSumLocal, std::vector< Scalar > &R_sum, std::vector< Scalar > &maxCoeff, std::vector< Scalar > &B_avg)
Definition: NonlinearSystemBlackOilReservoir_impl.hpp:611
GetPropType< TypeTag, Properties::Scalar > Scalar
Definition: NonlinearSystemBlackOilReservoir.hpp:79
std::pair< Scalar, Scalar > localConvergenceData(std::vector< Scalar > &R_sum, std::vector< Scalar > &maxCoeff, std::vector< Scalar > &B_avg, std::vector< int > &maxCoeffCell)
Get reservoir quantities on this process needed for convergence calculations.
Definition: NonlinearSystemBlackOilReservoir_impl.hpp:630
void convergencePerCell(const std::vector< Scalar > &B_avg, const double dt, const double tol_cnv, const double tol_cnv_energy)
Compute the number of Newtons required by each cell in order to satisfy the solution change convergen...
Definition: NonlinearSystemBlackOilReservoir_impl.hpp:1017
const SimulatorReport & localAccumulatedReports() const
return the statistics of local solves accumulated for this rank
Definition: NonlinearSystemBlackOilReservoir_impl.hpp:1099
SimulatorReportSingle nonlinearIteration(const SimulatorTimerInterface &timer, NonlinearSolverType &nonlinear_solver)
Definition: NonlinearSystemBlackOilReservoir_impl.hpp:218
MaxSolutionUpdateData getMaxSolutionUpdate(const std::vector< unsigned > &ixCells)
Definition: NonlinearSystemBlackOilReservoir_impl.hpp:557
const std::vector< SimulatorReport > & domainAccumulatedReports() const
return the statistics of local solves accumulated for each domain on this rank
Definition: NonlinearSystemBlackOilReservoir_impl.hpp:1110
bool shouldStoreSolutionUpdate() const override
Get solution update vector as a PrimaryVariable.
Definition: NonlinearSystemBlackOilReservoir_impl.hpp:508
ConvergenceReport getReservoirConvergence(const double reportTime, const double dt, const int maxIter, std::vector< Scalar > &B_avg, std::vector< Scalar > &residual_norms)
Definition: NonlinearSystemBlackOilReservoir_impl.hpp:762
std::unique_ptr< NonlinearSystemNldd< TypeTag > > nlddSolver_
Non-linear DD solver.
Definition: NonlinearSystemBlackOilReservoir.hpp:307
CnvPvSplitData characteriseCnvPvSplit(const std::vector< Scalar > &B_avg, const double dt)
Compute pore-volume/cell count split among "converged", "relaxed converged", "unconverged" cells base...
Definition: NonlinearSystemBlackOilReservoir_impl.hpp:681
ConvergenceReport getConvergence(const SimulatorTimerInterface &timer, const int maxIter, std::vector< Scalar > &residual_norms)
Definition: NonlinearSystemBlackOilReservoir_impl.hpp:1063
NonlinearSystemBlackOilReservoir(Simulator &simulator, const ModelParameters &param, typename ParentType::WellModel &well_model, const bool terminal_output)
Definition: NonlinearSystemBlackOilReservoir_impl.hpp:78
void writeNonlinearIterationsPerCell(const std::filesystem::path &odir) const
Write the number of nonlinear iterations per cell to a file in ResInsight compatible format.
Definition: NonlinearSystemBlackOilReservoir_impl.hpp:1120
Scalar relativeChange() const
Definition: NonlinearSystemBlackOilReservoir_impl.hpp:339
std::vector< std::vector< Scalar > > computeFluidInPlace(const T &, const std::vector< int > &fipnum) const
Wrapper required due to not following generic API.
Definition: NonlinearSystemBlackOilReservoir.hpp:250
long int global_nc_
The number of cells of the global grid.
Definition: NonlinearSystemBlackOilReservoir.hpp:303
DebugFlags
Definition: NonlinearSystemBlackOilReservoir.hpp:132
void initialLinearization(SimulatorReportSingle &report, const int minIter, const int maxIter, const SimulatorTimerInterface &timer) override
Definition: NonlinearSystemBlackOilReservoir_impl.hpp:166
void getMaxCoeff(const unsigned cell_idx, const IntensiveQuantities &intQuants, const FluidState &fs, const Residual &modelResid, const Scalar pvValue, std::vector< Scalar > &B_avg, std::vector< Scalar > &R_sum, std::vector< Scalar > &maxCoeff, std::vector< int > &maxCoeffCell)
Definition: NonlinearSystemBlackOilReservoir_impl.hpp:1157
void solveJacobianSystem(BVector &x)
Definition: NonlinearSystemBlackOilReservoir_impl.hpp:430
SimulatorReportSingle nonlinearIterationNewton(const SimulatorTimerInterface &timer, NonlinearSolverType &nonlinear_solver)
Definition: NonlinearSystemBlackOilReservoir_impl.hpp:252
void writePartitions(const std::filesystem::path &odir) const
Definition: NonlinearSystemBlackOilReservoir_impl.hpp:1130
Definition: NonlinearSystem.hpp:44
const Grid & grid_
Definition: NonlinearSystem.hpp:164
std::vector< StepReport > convergence_reports_
Definition: NonlinearSystem.hpp:170
ModelParameters param_
Definition: NonlinearSystem.hpp:167
GetPropType< TypeTag, Properties::Simulator > Simulator
Definition: NonlinearSystem.hpp:47
GetPropType< TypeTag, Properties::GlobalEqVector > GlobalEqVector
Definition: NonlinearSystem.hpp:52
GetPropType< TypeTag, Properties::WellModel > WellModel
Definition: NonlinearSystem.hpp:54
Interface class for SimulatorTimer objects, to be improved.
Definition: SimulatorTimerInterface.hpp:34
virtual int reportStepNum() const
Current report step number. This might differ from currentStepNum in case of sub stepping.
Definition: SimulatorTimerInterface.hpp:109
virtual bool lastStepFailed() const =0
Return true if last time step failed.
virtual double currentStepLength() const =0
virtual double simulationTimeElapsed() const =0
virtual int currentStepNum() const =0
Dune::Communication< MPIComm > Communication
Definition: ParallelCommunication.hpp:30
std::size_t countGlobalCells(const Grid &grid)
Get the number of cells of a global grid.
Definition: countGlobalCells.hpp:80
Definition: blackoilbioeffectsmodules.hh:45
ConvergenceReport::OscillationSource classifyOscillationSource(const ConvergenceReport &report)
Classify what was unsatisfied in a report, for oscillation-source reporting.
std::string to_string(const ConvergenceReport::ReservoirFailure::Type t)
Solver parameters for the NonlinearSystemBlackOilReservoir.
Definition: BlackoilModelParameters.hpp:208
std::string nonlinear_solver_
Nonlinear solver type: newton or nldd.
Definition: BlackoilModelParameters.hpp:379
Definition: AquiferGridUtils.hpp:35
Definition: NonlinearSystemBlackOilReservoir.hpp:119
Definition: NonlinearSystemBlackOilReservoir.hpp:124
Scalar dRsMax
Definition: NonlinearSystemBlackOilReservoir.hpp:127
Scalar dPMax
Definition: NonlinearSystemBlackOilReservoir.hpp:125
Scalar dSMax
Definition: NonlinearSystemBlackOilReservoir.hpp:126
Scalar dRvMax
Definition: NonlinearSystemBlackOilReservoir.hpp:128
Definition: SimulatorReport.hpp:202
A struct for returning timing data from a simulator to its caller.
Definition: SimulatorReport.hpp:34
double linear_solve_time
Definition: SimulatorReport.hpp:43
bool converged
Definition: SimulatorReport.hpp:57
double linear_solve_setup_time
Definition: SimulatorReport.hpp:42
unsigned int total_newton_iterations
Definition: SimulatorReport.hpp:50
double update_time
Definition: SimulatorReport.hpp:45
unsigned int relaxed_cnv_acceptances
Definition: SimulatorReport.hpp:55
unsigned int total_linear_iterations
Definition: SimulatorReport.hpp:51