BlackoilModel_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_BLACKOILMODEL_IMPL_HEADER_INCLUDED
25#define OPM_BLACKOILMODEL_IMPL_HEADER_INCLUDED
26
27#ifndef OPM_BLACKOILMODEL_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 <iomanip>
41#include <limits>
42#include <stdexcept>
43#include <sstream>
44
45#include <fmt/format.h>
46
47namespace Opm {
48
49template <class TypeTag>
51BlackoilModel(Simulator& simulator,
52 const ModelParameters& param,
54 const bool terminal_output)
55 : simulator_(simulator)
56 , grid_(simulator_.vanguard().grid())
57 , param_( param )
58 , well_model_ (well_model)
59 , terminal_output_ (terminal_output)
60 , current_relaxation_(1.0)
61 , dx_old_(simulator_.model().numGridDof())
62 , conv_monitor_(param_.monitor_params_)
63{
64 // compute global sum of number of cells
66 convergence_reports_.reserve(300); // Often insufficient, but avoids frequent moves.
67 // TODO: remember to fix!
68 if (param_.nonlinear_solver_ == "nldd") {
69 if (terminal_output) {
70 OpmLog::info("Using Non-Linear Domain Decomposition solver (nldd).");
71 }
72 nlddSolver_ = std::make_unique<BlackoilModelNldd<TypeTag>>(*this);
73 } else if (param_.nonlinear_solver_ == "newton") {
74 if (terminal_output) {
75 OpmLog::info("Using Newton nonlinear solver.");
76 }
77 } else {
78 OPM_THROW(std::runtime_error, "Unknown nonlinear solver option: " +
80 }
81}
82
83template <class TypeTag>
87{
89 Dune::Timer perfTimer;
90 perfTimer.start();
91 // update the solution variables in the model
92 int lastStepFailed = timer.lastStepFailed();
93 if (grid_.comm().size() > 1 && grid_.comm().max(lastStepFailed) != grid_.comm().min(lastStepFailed)) {
94 OPM_THROW(std::runtime_error, "Misalignment of the parallel simulation run in prepareStep " +
95 "- the previous step succeeded on some ranks but failed on others.");
96 }
97 if (lastStepFailed) {
98 simulator_.model().updateFailed();
99 }
100 else {
101 simulator_.model().advanceTimeLevel();
102 }
103
104 // Set the timestep size, episode index, and non-linear iteration index
105 // for the model explicitly. The model needs to know the report step/episode index
106 // because of timing dependent data despite the fact that flow uses its
107 // own time stepper. (The length of the episode does not matter, though.)
108 simulator_.setTime(timer.simulationTimeElapsed());
109 simulator_.setTimeStepSize(timer.currentStepLength());
110 simulator_.model().newtonMethod().setIterationIndex(0);
111
112 simulator_.problem().beginTimeStep();
113
114 unsigned numDof = simulator_.model().numGridDof();
115 wasSwitched_.resize(numDof);
116 std::fill(wasSwitched_.begin(), wasSwitched_.end(), false);
117
118 if (param_.update_equations_scaling_) {
119 OpmLog::error("Equation scaling not supported");
120 //updateEquationsScaling();
121 }
122
123 if (hasNlddSolver()) {
124 nlddSolver_->prepareStep();
125 }
126
127 report.pre_post_time += perfTimer.stop();
128
129 auto getIdx = [](unsigned phaseIdx) -> int
130 {
131 if (FluidSystem::phaseIsActive(phaseIdx)) {
132 const unsigned sIdx = FluidSystem::solventComponentIndex(phaseIdx);
133 return FluidSystem::canonicalToActiveCompIdx(sIdx);
134 }
135
136 return -1;
137 };
138 const auto& schedule = simulator_.vanguard().schedule();
139 auto& rst_conv = simulator_.problem().eclWriter().mutableOutputModule().getConv();
140 rst_conv.init(simulator_.vanguard().globalNumCells(),
141 schedule[timer.reportStepNum()].rst_config(),
142 {getIdx(FluidSystem::oilPhaseIdx),
143 getIdx(FluidSystem::gasPhaseIdx),
144 getIdx(FluidSystem::waterPhaseIdx),
145 contiPolymerEqIdx,
146 contiBrineEqIdx,
147 contiSolventEqIdx});
148
149 return report;
150}
151
152template <class TypeTag>
153void
156 const int iteration,
157 const int minIter,
158 const int maxIter,
159 const SimulatorTimerInterface& timer)
160{
161 // ----------- Set up reports and timer -----------
162 failureReport_ = SimulatorReportSingle();
163 Dune::Timer perfTimer;
164
165 perfTimer.start();
166 report.total_linearizations = 1;
167
168 // ----------- Assemble -----------
169 try {
170 report += assembleReservoir(timer, iteration);
171 report.assemble_time += perfTimer.stop();
172 }
173 catch (...) {
174 report.assemble_time += perfTimer.stop();
175 failureReport_ += report;
176 throw; // continue throwing the stick
177 }
178
179 // ----------- Check if converged -----------
180 std::vector<Scalar> residual_norms;
181 perfTimer.reset();
182 perfTimer.start();
183 // the step is not considered converged until at least minIter iterations is done
184 {
185 auto convrep = getConvergence(timer, iteration, maxIter, residual_norms);
186 report.converged = convrep.converged() && iteration >= minIter;
187 ConvergenceReport::Severity severity = convrep.severityOfWorstFailure();
188 convergence_reports_.back().report.push_back(std::move(convrep));
189
190 // Throw if any NaN or too large residual found.
192 failureReport_ += report;
193 OPM_THROW_PROBLEM(NumericalProblem, "NaN residual found!");
194 } else if (severity == ConvergenceReport::Severity::TooLarge) {
195 failureReport_ += report;
196 OPM_THROW_NOLOG(NumericalProblem, "Too large residual found!");
198 failureReport_ += report;
199 OPM_THROW_PROBLEM(ConvergenceMonitorFailure,
200 fmt::format(
201 "Total penalty count exceeded cut-off-limit of {}",
202 param_.monitor_params_.cutoff_
203 ));
204 }
205 }
206 report.update_time += perfTimer.stop();
207 residual_norms_history_.push_back(residual_norms);
208}
209
210template <class TypeTag>
211template <class NonlinearSolverType>
214nonlinearIteration(const int iteration,
215 const SimulatorTimerInterface& timer,
216 NonlinearSolverType& nonlinear_solver)
217{
218 if (iteration == 0) {
219 // For each iteration we store in a vector the norms of the residual of
220 // the mass balance for each active phase, the well flux and the well equations.
221 residual_norms_history_.clear();
222 conv_monitor_.reset();
223 current_relaxation_ = 1.0;
224 dx_old_ = 0.0;
225 convergence_reports_.push_back({timer.reportStepNum(), timer.currentStepNum(), {}});
226 convergence_reports_.back().report.reserve(11);
227 }
228
230 if (this->param_.nonlinear_solver_ != "nldd")
231 {
232 result = this->nonlinearIterationNewton(iteration,
233 timer,
234 nonlinear_solver);
235 }
236 else {
237 result = this->nlddSolver_->nonlinearIterationNldd(iteration,
238 timer,
239 nonlinear_solver);
240 }
241
242 auto& rst_conv = simulator_.problem().eclWriter().mutableOutputModule().getConv();
243 rst_conv.update(simulator_.model().linearizer().residual());
244
245 return result;
246}
247
248template <class TypeTag>
249template <class NonlinearSolverType>
252nonlinearIterationNewton(const int iteration,
253 const SimulatorTimerInterface& timer,
254 NonlinearSolverType& nonlinear_solver)
255{
256 // ----------- Set up reports and timer -----------
258 Dune::Timer perfTimer;
259
260 this->initialLinearization(report,
261 iteration,
262 this->param_.newton_min_iter_,
263 this->param_.newton_max_iter_,
264 timer);
265
266 // ----------- If not converged, solve linear system and do Newton update -----------
267 if (!report.converged) {
268 perfTimer.reset();
269 perfTimer.start();
270 report.total_newton_iterations = 1;
271
272 // Compute the nonlinear update.
273 unsigned nc = simulator_.model().numGridDof();
274 BVector x(nc);
275
276 // Solve the linear system.
277 linear_solve_setup_time_ = 0.0;
278 try {
279 // Apply the Schur complement of the well model to
280 // the reservoir linearized equations.
281 // Note that linearize may throw for MSwells.
282 wellModel().linearize(simulator().model().linearizer().jacobian(),
283 simulator().model().linearizer().residual());
284
285 // ---- Solve linear system ----
286 solveJacobianSystem(x);
287
288 report.linear_solve_setup_time += linear_solve_setup_time_;
289 report.linear_solve_time += perfTimer.stop();
290 report.total_linear_iterations += linearIterationsLastSolve();
291 }
292 catch (...) {
293 report.linear_solve_setup_time += linear_solve_setup_time_;
294 report.linear_solve_time += perfTimer.stop();
295 report.total_linear_iterations += linearIterationsLastSolve();
296
297 failureReport_ += report;
298 throw; // re-throw up
299 }
300
301 perfTimer.reset();
302 perfTimer.start();
303
304 // handling well state update before oscillation treatment is a decision based
305 // on observation to avoid some big performance degeneration under some circumstances.
306 // there is no theorectical explanation which way is better for sure.
307 wellModel().postSolve(x);
308
309 if (param_.use_update_stabilization_) {
310 // Stabilize the nonlinear update.
311 bool isOscillate = false;
312 bool isStagnate = false;
313 nonlinear_solver.detectOscillations(residual_norms_history_,
314 residual_norms_history_.size() - 1,
315 isOscillate,
316 isStagnate);
317 if (isOscillate) {
318 current_relaxation_ -= nonlinear_solver.relaxIncrement();
319 current_relaxation_ = std::max(current_relaxation_,
320 nonlinear_solver.relaxMax());
321 if (terminalOutputEnabled()) {
322 std::string msg = " Oscillating behavior detected: Relaxation set to "
323 + std::to_string(current_relaxation_);
324 OpmLog::info(msg);
325 }
326 }
327 nonlinear_solver.stabilizeNonlinearUpdate(x, dx_old_, current_relaxation_);
328 }
329
330 // ---- Newton update ----
331 // Apply the update, with considering model-dependent limitations and
332 // chopping of the update.
333 updateSolution(x);
334
335 report.update_time += perfTimer.stop();
336 }
337
338 return report;
339}
340
341template <class TypeTag>
345{
347 Dune::Timer perfTimer;
348 perfTimer.start();
349 simulator_.problem().endTimeStep();
350 report.pre_post_time += perfTimer.stop();
351 return report;
352}
353
354template <class TypeTag>
358 const int iterationIdx)
359{
360 // -------- Mass balance equations --------
361 simulator_.model().newtonMethod().setIterationIndex(iterationIdx);
362 simulator_.problem().beginIteration();
363 simulator_.model().linearizer().linearizeDomain();
364 simulator_.problem().endIteration();
365 return wellModel().lastReport();
366}
367
368template <class TypeTag>
371relativeChange() const
372{
373 Scalar resultDelta = 0.0;
374 Scalar resultDenom = 0.0;
375
376 const auto& elemMapper = simulator_.model().elementMapper();
377 const auto& gridView = simulator_.gridView();
378 for (const auto& elem : elements(gridView, Dune::Partitions::interior)) {
379 unsigned globalElemIdx = elemMapper.index(elem);
380 const auto& priVarsNew = simulator_.model().solution(/*timeIdx=*/0)[globalElemIdx];
381
382 Scalar pressureNew;
383 pressureNew = priVarsNew[Indices::pressureSwitchIdx];
384
385 Scalar saturationsNew[FluidSystem::numPhases] = { 0.0 };
386 Scalar oilSaturationNew = 1.0;
387 if (FluidSystem::phaseIsActive(FluidSystem::waterPhaseIdx) &&
388 FluidSystem::numActivePhases() > 1 &&
389 priVarsNew.primaryVarsMeaningWater() == PrimaryVariables::WaterMeaning::Sw)
390 {
391 saturationsNew[FluidSystem::waterPhaseIdx] = priVarsNew[Indices::waterSwitchIdx];
392 oilSaturationNew -= saturationsNew[FluidSystem::waterPhaseIdx];
393 }
394
395 if (FluidSystem::phaseIsActive(FluidSystem::gasPhaseIdx) &&
396 FluidSystem::phaseIsActive(FluidSystem::oilPhaseIdx) &&
397 priVarsNew.primaryVarsMeaningGas() == PrimaryVariables::GasMeaning::Sg)
398 {
399 assert(Indices::compositionSwitchIdx >= 0);
400 saturationsNew[FluidSystem::gasPhaseIdx] = priVarsNew[Indices::compositionSwitchIdx];
401 oilSaturationNew -= saturationsNew[FluidSystem::gasPhaseIdx];
402 }
403
404 if (FluidSystem::phaseIsActive(FluidSystem::oilPhaseIdx)) {
405 saturationsNew[FluidSystem::oilPhaseIdx] = oilSaturationNew;
406 }
407
408 const auto& priVarsOld = simulator_.model().solution(/*timeIdx=*/1)[globalElemIdx];
409
410 Scalar pressureOld;
411 pressureOld = priVarsOld[Indices::pressureSwitchIdx];
412
413 Scalar saturationsOld[FluidSystem::numPhases] = { 0.0 };
414 Scalar oilSaturationOld = 1.0;
415
416 // NB fix me! adding pressures changes to saturation changes does not make sense
417 Scalar tmp = pressureNew - pressureOld;
418 resultDelta += tmp*tmp;
419 resultDenom += pressureNew*pressureNew;
420
421 if (FluidSystem::numActivePhases() > 1) {
422 if (priVarsOld.primaryVarsMeaningWater() == PrimaryVariables::WaterMeaning::Sw) {
423 saturationsOld[FluidSystem::waterPhaseIdx] =
424 priVarsOld[Indices::waterSwitchIdx];
425 oilSaturationOld -= saturationsOld[FluidSystem::waterPhaseIdx];
426 }
427
428 if (priVarsOld.primaryVarsMeaningGas() == PrimaryVariables::GasMeaning::Sg)
429 {
430 assert(Indices::compositionSwitchIdx >= 0 );
431 saturationsOld[FluidSystem::gasPhaseIdx] =
432 priVarsOld[Indices::compositionSwitchIdx];
433 oilSaturationOld -= saturationsOld[FluidSystem::gasPhaseIdx];
434 }
435
436 if (FluidSystem::phaseIsActive(FluidSystem::oilPhaseIdx)) {
437 saturationsOld[FluidSystem::oilPhaseIdx] = oilSaturationOld;
438 }
439 for (unsigned phaseIdx = 0; phaseIdx < FluidSystem::numPhases; ++ phaseIdx) {
440 Scalar tmpSat = saturationsNew[phaseIdx] - saturationsOld[phaseIdx];
441 resultDelta += tmpSat*tmpSat;
442 resultDenom += saturationsNew[phaseIdx]*saturationsNew[phaseIdx];
443 assert(std::isfinite(resultDelta));
444 assert(std::isfinite(resultDenom));
445 }
446 }
447 }
448
449 resultDelta = gridView.comm().sum(resultDelta);
450 resultDenom = gridView.comm().sum(resultDenom);
451
452 return resultDenom > 0.0 ? resultDelta / resultDenom : 0.0;
453}
454
455template <class TypeTag>
456void
459{
460 auto& jacobian = simulator_.model().linearizer().jacobian().istlMatrix();
461 auto& residual = simulator_.model().linearizer().residual();
462 auto& linSolver = simulator_.model().newtonMethod().linearSolver();
463
464 const int numSolvers = linSolver.numAvailableSolvers();
465 if (numSolvers > 1 && (linSolver.getSolveCount() % 100 == 0)) {
466 if (terminal_output_) {
467 OpmLog::debug("\nRunning speed test for comparing available linear solvers.");
468 }
469
470 Dune::Timer perfTimer;
471 std::vector<double> times(numSolvers);
472 std::vector<double> setupTimes(numSolvers);
473
474 x = 0.0;
475 std::vector<BVector> x_trial(numSolvers, x);
476 for (int solver = 0; solver < numSolvers; ++solver) {
477 BVector x0(x);
478 linSolver.setActiveSolver(solver);
479 perfTimer.start();
480 linSolver.prepare(jacobian, residual);
481 setupTimes[solver] = perfTimer.stop();
482 perfTimer.reset();
483 linSolver.setResidual(residual);
484 perfTimer.start();
485 linSolver.solve(x_trial[solver]);
486 times[solver] = perfTimer.stop();
487 perfTimer.reset();
488 if (terminal_output_) {
489 OpmLog::debug(fmt::format("Solver time {}: {}", solver, times[solver]));
490 }
491 }
492
493 int fastest_solver = std::min_element(times.begin(), times.end()) - times.begin();
494 // Use timing on rank 0 to determine fastest, must be consistent across ranks.
495 grid_.comm().broadcast(&fastest_solver, 1, 0);
496 linear_solve_setup_time_ = setupTimes[fastest_solver];
497 x = x_trial[fastest_solver];
498 linSolver.setActiveSolver(fastest_solver);
499 }
500 else {
501 // set initial guess
502 x = 0.0;
503
504 Dune::Timer perfTimer;
505 perfTimer.start();
506 linSolver.prepare(jacobian, residual);
507 linear_solve_setup_time_ = perfTimer.stop();
508 linSolver.setResidual(residual);
509 // actually, the error needs to be calculated after setResidual in order to
510 // account for parallelization properly. since the residual of ECFV
511 // discretizations does not need to be synchronized across processes to be
512 // consistent, this is not relevant for OPM-flow...
513 linSolver.solve(x);
514 }
515}
516
517template <class TypeTag>
518void
520updateSolution(const BVector& dx)
521{
522 OPM_TIMEBLOCK(updateSolution);
523 auto& newtonMethod = simulator_.model().newtonMethod();
524 SolutionVector& solution = simulator_.model().solution(/*timeIdx=*/0);
525
526 newtonMethod.update_(/*nextSolution=*/solution,
527 /*curSolution=*/solution,
528 /*update=*/dx,
529 /*resid=*/dx); // the update routines of the black
530 // oil model do not care about the
531 // residual
532
533 // if the solution is updated, the intensive quantities need to be recalculated
534 {
535 OPM_TIMEBLOCK(invalidateAndUpdateIntensiveQuantities);
536 simulator_.model().invalidateAndUpdateIntensiveQuantities(/*timeIdx=*/0);
537 }
538}
539
540template <class TypeTag>
541std::tuple<typename BlackoilModel<TypeTag>::Scalar,
545 const Scalar pvSumLocal,
546 const Scalar numAquiferPvSumLocal,
547 std::vector< Scalar >& R_sum,
548 std::vector< Scalar >& maxCoeff,
549 std::vector< Scalar >& B_avg)
550{
551 OPM_TIMEBLOCK(convergenceReduction);
552 // Compute total pore volume (use only owned entries)
553 Scalar pvSum = pvSumLocal;
554 Scalar numAquiferPvSum = numAquiferPvSumLocal;
555
556 if (comm.size() > 1) {
557 // global reduction
558 std::vector< Scalar > sumBuffer;
559 std::vector< Scalar > maxBuffer;
560 const int numComp = B_avg.size();
561 sumBuffer.reserve( 2*numComp + 2 ); // +2 for (numAquifer)pvSum
562 maxBuffer.reserve( numComp );
563 for (int compIdx = 0; compIdx < numComp; ++compIdx) {
564 sumBuffer.push_back(B_avg[compIdx]);
565 sumBuffer.push_back(R_sum[compIdx]);
566 maxBuffer.push_back(maxCoeff[ compIdx]);
567 }
568
569 // Compute total pore volume
570 sumBuffer.push_back( pvSum );
571 sumBuffer.push_back( numAquiferPvSum );
572
573 // compute global sum
574 comm.sum( sumBuffer.data(), sumBuffer.size() );
575
576 // compute global max
577 comm.max( maxBuffer.data(), maxBuffer.size() );
578
579 // restore values to local variables
580 for (int compIdx = 0, buffIdx = 0; compIdx < numComp; ++compIdx, ++buffIdx) {
581 B_avg[compIdx] = sumBuffer[buffIdx];
582 ++buffIdx;
583
584 R_sum[compIdx] = sumBuffer[buffIdx];
585 }
586
587 for (int compIdx = 0; compIdx < numComp; ++compIdx) {
588 maxCoeff[compIdx] = maxBuffer[compIdx];
589 }
590
591 // restore global pore volume
592 pvSum = sumBuffer[sumBuffer.size()-2];
593 numAquiferPvSum = sumBuffer.back();
594 }
595
596 // return global pore volume
597 return {pvSum, numAquiferPvSum};
598}
599
600template <class TypeTag>
601std::pair<typename BlackoilModel<TypeTag>::Scalar,
604localConvergenceData(std::vector<Scalar>& R_sum,
605 std::vector<Scalar>& maxCoeff,
606 std::vector<Scalar>& B_avg,
607 std::vector<int>& maxCoeffCell)
608{
609 OPM_TIMEBLOCK(localConvergenceData);
610 Scalar pvSumLocal = 0.0;
611 Scalar numAquiferPvSumLocal = 0.0;
612 const auto& model = simulator_.model();
613 const auto& problem = simulator_.problem();
614
615 const auto& residual = simulator_.model().linearizer().residual();
616
617 ElementContext elemCtx(simulator_);
618 const auto& gridView = simulator().gridView();
619 IsNumericalAquiferCell isNumericalAquiferCell(gridView.grid());
621 for (const auto& elem : elements(gridView, Dune::Partitions::interior)) {
622 elemCtx.updatePrimaryStencil(elem);
623 elemCtx.updatePrimaryIntensiveQuantities(/*timeIdx=*/0);
624
625 const unsigned cell_idx = elemCtx.globalSpaceIndex(/*spaceIdx=*/0, /*timeIdx=*/0);
626 const auto& intQuants = elemCtx.intensiveQuantities(/*spaceIdx=*/0, /*timeIdx=*/0);
627 const auto& fs = intQuants.fluidState();
628
629 const auto pvValue = problem.referencePorosity(cell_idx, /*timeIdx=*/0) *
630 model.dofTotalVolume(cell_idx);
631 pvSumLocal += pvValue;
632
633 if (isNumericalAquiferCell(elem)) {
634 numAquiferPvSumLocal += pvValue;
635 }
636
637 this->getMaxCoeff(cell_idx, intQuants, fs, residual, pvValue,
638 B_avg, R_sum, maxCoeff, maxCoeffCell);
639 }
640
641 OPM_END_PARALLEL_TRY_CATCH("BlackoilModel::localConvergenceData() failed: ", grid_.comm());
642
643 // compute local average in terms of global number of elements
644 const int bSize = B_avg.size();
645 for (int i = 0; i < bSize; ++i) {
646 B_avg[i] /= Scalar(global_nc_);
647 }
648
649 return {pvSumLocal, numAquiferPvSumLocal};
650}
651
652template <class TypeTag>
653std::pair<std::vector<double>, std::vector<int>>
655characteriseCnvPvSplit(const std::vector<Scalar>& B_avg, const double dt)
656{
657 OPM_TIMEBLOCK(computeCnvErrorPv);
658
659 // 0: cnv <= tolerance_cnv
660 // 1: tolerance_cnv < cnv <= tolerance_cnv_relaxed
661 // 2: tolerance_cnv_relaxed < cnv
662 constexpr auto numPvGroups = std::vector<double>::size_type{3};
663
664 auto cnvPvSplit = std::pair<std::vector<double>, std::vector<int>> {
665 std::piecewise_construct,
666 std::forward_as_tuple(numPvGroups),
667 std::forward_as_tuple(numPvGroups)
668 };
669
670 auto maxCNV = [&B_avg, dt](const auto& residual, const double pvol)
671 {
672 return (dt / pvol) *
673 std::inner_product(residual.begin(), residual.end(),
674 B_avg.begin(), Scalar{0},
675 [](const Scalar m, const auto& x)
676 {
677 using std::abs;
678 return std::max(m, abs(x));
679 }, std::multiplies<>{});
680 };
681
682 auto& [splitPV, cellCntPV] = cnvPvSplit;
683
684 const auto& model = this->simulator().model();
685 const auto& problem = this->simulator().problem();
686 const auto& residual = model.linearizer().residual();
687 const auto& gridView = this->simulator().gridView();
688
689 const IsNumericalAquiferCell isNumericalAquiferCell(gridView.grid());
690
691 ElementContext elemCtx(this->simulator());
692
694 for (const auto& elem : elements(gridView, Dune::Partitions::interior)) {
695 // Skip cells of numerical Aquifer
696 if (isNumericalAquiferCell(elem)) {
697 continue;
698 }
699
700 elemCtx.updatePrimaryStencil(elem);
701
702 const unsigned cell_idx = elemCtx.globalSpaceIndex(/*spaceIdx=*/0, /*timeIdx=*/0);
703 const auto pvValue = problem.referencePorosity(cell_idx, /*timeIdx=*/0)
704 * model.dofTotalVolume(cell_idx);
705
706 const auto maxCnv = maxCNV(residual[cell_idx], pvValue);
707
708 const auto ix = (maxCnv > this->param_.tolerance_cnv_)
709 + (maxCnv > this->param_.tolerance_cnv_relaxed_);
710
711 splitPV[ix] += static_cast<double>(pvValue);
712 ++cellCntPV[ix];
713 }
714
715 OPM_END_PARALLEL_TRY_CATCH("BlackoilModel::characteriseCnvPvSplit() failed: ",
716 this->grid_.comm());
717
718 this->grid_.comm().sum(splitPV .data(), splitPV .size());
719 this->grid_.comm().sum(cellCntPV.data(), cellCntPV.size());
720
721 return cnvPvSplit;
722}
723
724template <class TypeTag>
725void
727updateTUNING(const Tuning& tuning)
728{
729 this->param_.tolerance_cnv_ = tuning.TRGCNV;
730 this->param_.tolerance_cnv_relaxed_ = tuning.XXXCNV;
731 this->param_.tolerance_mb_ = tuning.TRGMBE;
732 this->param_.tolerance_mb_relaxed_ = tuning.XXXMBE;
733 this->param_.newton_max_iter_ = tuning.NEWTMX;
734 this->param_.newton_min_iter_ = tuning.NEWTMN;
735}
736
737template <class TypeTag>
740getReservoirConvergence(const double reportTime,
741 const double dt,
742 const int iteration,
743 const int maxIter,
744 std::vector<Scalar>& B_avg,
745 std::vector<Scalar>& residual_norms)
746{
747 OPM_TIMEBLOCK(getReservoirConvergence);
748 using Vector = std::vector<Scalar>;
749
750 ConvergenceReport report{reportTime};
751
752 const int numComp = numEq;
753
754 Vector R_sum(numComp, Scalar{0});
755 Vector maxCoeff(numComp, std::numeric_limits<Scalar>::lowest());
756 std::vector<int> maxCoeffCell(numComp, -1);
757
758 const auto [pvSumLocal, numAquiferPvSumLocal] =
759 this->localConvergenceData(R_sum, maxCoeff, B_avg, maxCoeffCell);
760
761 // compute global sum and max of quantities
762 const auto& [pvSum, numAquiferPvSum] =
763 this->convergenceReduction(this->grid_.comm(),
764 pvSumLocal,
765 numAquiferPvSumLocal,
766 R_sum, maxCoeff, B_avg);
767
768 report.setCnvPoreVolSplit(this->characteriseCnvPvSplit(B_avg, dt),
769 pvSum - numAquiferPvSum);
770
771 // For each iteration, we need to determine whether to use the
772 // relaxed tolerances. To disable the usage of relaxed
773 // tolerances, you can set the relaxed tolerances as the strict
774 // tolerances. If min_strict_mb_iter = -1 (default) we use a
775 // relaxed tolerance for the mass balance for the last
776 // iterations. For positive values we use the relaxed tolerance
777 // after the given number of iterations
778 const bool relax_final_iteration_mb =
779 this->param_.min_strict_mb_iter_ < 0 && iteration == maxIter;
780
781 const bool use_relaxed_mb = relax_final_iteration_mb ||
782 (this->param_.min_strict_mb_iter_ >= 0 &&
783 iteration >= this->param_.min_strict_mb_iter_);
784
785 // If min_strict_cnv_iter = -1 we use a relaxed tolerance for
786 // the cnv for the last iterations. For positive values we use
787 // the relaxed tolerance after the given number of iterations.
788 // We also use relaxed tolerances for cells with total
789 // pore-volume less than relaxed_max_pv_fraction_. Default
790 // value of relaxed_max_pv_fraction_ is 0.03
791 const bool relax_final_iteration_cnv =
792 this->param_.min_strict_cnv_iter_ < 0 && iteration == maxIter;
793
794 const bool relax_iter_cnv =
795 this->param_.min_strict_cnv_iter_ >= 0 &&
796 iteration >= this->param_.min_strict_cnv_iter_;
797
798 // Note trailing parentheses here, just before the final
799 // semicolon. This is an immediately invoked function
800 // expression which calculates a single boolean value.
801 const auto relax_pv_fraction_cnv =
802 [&report, this, eligible = pvSum - numAquiferPvSum]()
803 {
804 const auto& cnvPvSplit = report.cnvPvSplit().first;
805
806 // [1]: tol < cnv <= relaxed
807 // [2]: relaxed < cnv
808 return static_cast<Scalar>(cnvPvSplit[1] + cnvPvSplit[2]) <
809 this->param_.relaxed_max_pv_fraction_ * eligible;
810 }();
811
812 const bool use_relaxed_cnv = relax_final_iteration_cnv
813 || relax_pv_fraction_cnv
814 || relax_iter_cnv;
815
816 if ((relax_final_iteration_mb || relax_final_iteration_cnv) &&
817 this->terminal_output_)
818 {
819 std::string message =
820 "Number of newton iterations reached its maximum "
821 "try to continue with relaxed tolerances:";
822
823 if (relax_final_iteration_mb) {
824 message += fmt::format(" MB: {:.1e}", param_.tolerance_mb_relaxed_);
825 }
826
827 if (relax_final_iteration_cnv) {
828 message += fmt::format(" CNV: {:.1e}", param_.tolerance_cnv_relaxed_);
829 }
830
831 OpmLog::debug(message);
832 }
833
834 const auto tol_cnv = use_relaxed_cnv ? param_.tolerance_cnv_relaxed_ : param_.tolerance_cnv_;
835 const auto tol_mb = use_relaxed_mb ? param_.tolerance_mb_relaxed_ : param_.tolerance_mb_;
836 const auto tol_cnv_energy = use_relaxed_cnv ? param_.tolerance_cnv_energy_relaxed_ : param_.tolerance_cnv_energy_;
837 const auto tol_eb = use_relaxed_mb ? param_.tolerance_energy_balance_relaxed_ : param_.tolerance_energy_balance_;
838
839 // Finish computation
840 std::vector<Scalar> CNV(numComp);
841 std::vector<Scalar> mass_balance_residual(numComp);
842 for (int compIdx = 0; compIdx < numComp; ++compIdx)
843 {
844 CNV[compIdx] = B_avg[compIdx] * dt * maxCoeff[compIdx];
845 mass_balance_residual[compIdx] = std::abs(B_avg[compIdx]*R_sum[compIdx]) * dt / pvSum;
846 residual_norms.push_back(CNV[compIdx]);
847 }
848
849 using CR = ConvergenceReport;
850 for (int compIdx = 0; compIdx < numComp; ++compIdx) {
851 const Scalar res[2] = {
852 mass_balance_residual[compIdx], CNV[compIdx],
853 };
854
855 const CR::ReservoirFailure::Type types[2] = {
856 CR::ReservoirFailure::Type::MassBalance,
857 CR::ReservoirFailure::Type::Cnv,
858 };
859
860 Scalar tol[2] = { tol_mb, tol_cnv, };
861 if (has_energy_ && compIdx == contiEnergyEqIdx) {
862 tol[0] = tol_eb;
863 tol[1] = tol_cnv_energy;
864 }
865
866 for (int ii : {0, 1}) {
867 if (std::isnan(res[ii])) {
868 report.setReservoirFailed({types[ii], CR::Severity::NotANumber, compIdx});
869 if (this->terminal_output_) {
870 OpmLog::debug("NaN residual for " + this->compNames_.name(compIdx) + " equation.");
871 }
872 }
873 else if (res[ii] > maxResidualAllowed()) {
874 report.setReservoirFailed({types[ii], CR::Severity::TooLarge, compIdx});
875 if (this->terminal_output_) {
876 OpmLog::debug("Too large residual for " + this->compNames_.name(compIdx) + " equation.");
877 }
878 }
879 else if (res[ii] < 0.0) {
880 report.setReservoirFailed({types[ii], CR::Severity::Normal, compIdx});
881 if (this->terminal_output_) {
882 OpmLog::debug("Negative residual for " + this->compNames_.name(compIdx) + " equation.");
883 }
884 }
885 else if (res[ii] > tol[ii]) {
886 report.setReservoirFailed({types[ii], CR::Severity::Normal, compIdx});
887 }
888
889 report.setReservoirConvergenceMetric(types[ii], compIdx, res[ii], tol[ii]);
890 }
891 }
892
893 // Compute the Newton convergence per cell.
894 this->convergencePerCell(B_avg, dt, tol_cnv, tol_cnv_energy, iteration);
895
896 // Output of residuals.
897 if (this->terminal_output_) {
898 // Only rank 0 does print to std::cout
899 if (iteration == 0) {
900 std::string msg = "Iter";
901 for (int compIdx = 0; compIdx < numComp; ++compIdx) {
902 msg += " MB(";
903 msg += this->compNames_.name(compIdx)[0];
904 msg += ") ";
905 }
906
907 for (int compIdx = 0; compIdx < numComp; ++compIdx) {
908 msg += " CNV(";
909 msg += this->compNames_.name(compIdx)[0];
910 msg += ") ";
911 }
912
913 OpmLog::debug(msg);
914 }
915
916 std::ostringstream ss;
917 const std::streamsize oprec = ss.precision(3);
918 const std::ios::fmtflags oflags = ss.setf(std::ios::scientific);
919
920 ss << std::setw(4) << iteration;
921 for (int compIdx = 0; compIdx < numComp; ++compIdx) {
922 ss << std::setw(11) << mass_balance_residual[compIdx];
923 }
924
925 for (int compIdx = 0; compIdx < numComp; ++compIdx) {
926 ss << std::setw(11) << CNV[compIdx];
927 }
928
929 ss.precision(oprec);
930 ss.flags(oflags);
931
932 OpmLog::debug(ss.str());
933 }
934
935 return report;
936}
937
938template <class TypeTag>
939void
941convergencePerCell(const std::vector<Scalar>& B_avg,
942 const double dt,
943 const double tol_cnv,
944 const double tol_cnv_energy,
945 const int iteration)
946{
947 auto& rst_conv = simulator_.problem().eclWriter().mutableOutputModule().getConv();
948 if (!rst_conv.hasConv()) {
949 return;
950 }
951
952 if (iteration == 0) {
953 rst_conv.prepareConv();
954 }
955
956 const auto& residual = simulator_.model().linearizer().residual();
957 const auto& gridView = this->simulator().gridView();
958 const IsNumericalAquiferCell isNumericalAquiferCell(gridView.grid());
959 ElementContext elemCtx(this->simulator());
960 std::vector<int> convNewt(residual.size(), 0);
962 unsigned idx = 0;
963 const int numComp = B_avg.size();
964 for (const auto& elem : elements(gridView, Dune::Partitions::interior)) {
965 elemCtx.updatePrimaryStencil(elem);
966
967 const unsigned cell_idx = elemCtx.globalSpaceIndex(/*spaceIdx=*/0, /*timeIdx=*/0);
968 const auto pvValue = simulator_.problem().referencePorosity(cell_idx, /*timeIdx=*/0) *
969 simulator_.model().dofTotalVolume(cell_idx);
970 for (int compIdx = 0; compIdx < numComp; ++compIdx) {
971 const auto tol = (has_energy_ && compIdx == contiEnergyEqIdx) ? tol_cnv_energy : tol_cnv;
972 const Scalar cnv = std::abs(B_avg[compIdx] * residual[cell_idx][compIdx]) * dt / pvValue;
973 if (std::isnan(cnv) || cnv > maxResidualAllowed() || cnv < 0.0 || cnv > tol) {
974 convNewt[idx] = 1;
975 break;
976 }
977 }
978 ++idx;
979 }
980 OPM_END_PARALLEL_TRY_CATCH("BlackoilModel::convergencePerCell() failed: ",
981 this->grid_.comm());
982 rst_conv.updateNewton(convNewt);
983}
984
985template <class TypeTag>
989 const int iteration,
990 const int maxIter,
991 std::vector<Scalar>& residual_norms)
992{
993 OPM_TIMEBLOCK(getConvergence);
994 // Get convergence reports for reservoir and wells.
995 std::vector<Scalar> B_avg(numEq, 0.0);
996 auto report = getReservoirConvergence(timer.simulationTimeElapsed(),
997 timer.currentStepLength(),
998 iteration, maxIter, B_avg, residual_norms);
999 {
1000 OPM_TIMEBLOCK(getWellConvergence);
1001 report += wellModel().getWellConvergence(B_avg,
1002 /*checkWellGroupControls*/report.converged());
1003 }
1004
1005 conv_monitor_.checkPenaltyCard(report, iteration);
1006
1007 return report;
1008}
1009
1010template <class TypeTag>
1011std::vector<std::vector<typename BlackoilModel<TypeTag>::Scalar> >
1013computeFluidInPlace(const std::vector<int>& /*fipnum*/) const
1014{
1015 OPM_TIMEBLOCK(computeFluidInPlace);
1016 // assert(true)
1017 // return an empty vector
1018 std::vector<std::vector<Scalar> > regionValues(0, std::vector<Scalar>(0,0.0));
1019 return regionValues;
1020}
1021
1022template <class TypeTag>
1023const SimulatorReport&
1026{
1027 if (!hasNlddSolver()) {
1028 OPM_THROW(std::runtime_error, "Cannot get local reports from a model without NLDD solver");
1029 }
1030 return nlddSolver_->localAccumulatedReports();
1031}
1032
1033template <class TypeTag>
1034const std::vector<SimulatorReport>&
1037{
1038 if (!nlddSolver_)
1039 OPM_THROW(std::runtime_error, "Cannot get domain reports from a model without NLDD solver");
1040 return nlddSolver_->domainAccumulatedReports();
1041}
1042
1043template <class TypeTag>
1044void
1046writeNonlinearIterationsPerCell(const std::filesystem::path& odir) const
1047{
1048 if (hasNlddSolver()) {
1049 nlddSolver_->writeNonlinearIterationsPerCell(odir);
1050 }
1051}
1052
1053template <class TypeTag>
1054void
1056writePartitions(const std::filesystem::path& odir) const
1057{
1058 if (hasNlddSolver()) {
1059 nlddSolver_->writePartitions(odir);
1060 return;
1061 }
1062
1063 const auto& elementMapper = this->simulator().model().elementMapper();
1064 const auto& cartMapper = this->simulator().vanguard().cartesianIndexMapper();
1065
1066 const auto& grid = this->simulator().vanguard().grid();
1067 const auto& comm = grid.comm();
1068 const auto nDigit = 1 + static_cast<int>(std::floor(std::log10(comm.size())));
1069
1070 std::ofstream pfile {odir / fmt::format("{1:0>{0}}", nDigit, comm.rank())};
1071
1072 for (const auto& cell : elements(grid.leafGridView(), Dune::Partitions::interior)) {
1073 pfile << comm.rank() << ' '
1074 << cartMapper.cartesianIndex(elementMapper.index(cell)) << ' '
1075 << comm.rank() << '\n';
1076 }
1077}
1078
1079template <class TypeTag>
1080template<class FluidState, class Residual>
1081void
1083getMaxCoeff(const unsigned cell_idx,
1084 const IntensiveQuantities& intQuants,
1085 const FluidState& fs,
1086 const Residual& modelResid,
1087 const Scalar pvValue,
1088 std::vector<Scalar>& B_avg,
1089 std::vector<Scalar>& R_sum,
1090 std::vector<Scalar>& maxCoeff,
1091 std::vector<int>& maxCoeffCell)
1092{
1093 for (unsigned phaseIdx = 0; phaseIdx < FluidSystem::numPhases; ++phaseIdx)
1094 {
1095 if (!FluidSystem::phaseIsActive(phaseIdx)) {
1096 continue;
1097 }
1098
1099 const unsigned sIdx = FluidSystem::solventComponentIndex(phaseIdx);
1100 const unsigned compIdx = FluidSystem::canonicalToActiveCompIdx(sIdx);
1101
1102 B_avg[compIdx] += 1.0 / fs.invB(phaseIdx).value();
1103 const auto R2 = modelResid[cell_idx][compIdx];
1104
1105 R_sum[compIdx] += R2;
1106 const Scalar Rval = std::abs(R2) / pvValue;
1107 if (Rval > maxCoeff[compIdx]) {
1108 maxCoeff[compIdx] = Rval;
1109 maxCoeffCell[compIdx] = cell_idx;
1110 }
1111 }
1112
1113 if constexpr (has_solvent_) {
1114 B_avg[contiSolventEqIdx] +=
1115 1.0 / intQuants.solventInverseFormationVolumeFactor().value();
1116 const auto R2 = modelResid[cell_idx][contiSolventEqIdx];
1117 R_sum[contiSolventEqIdx] += R2;
1118 maxCoeff[contiSolventEqIdx] = std::max(maxCoeff[contiSolventEqIdx],
1119 std::abs(R2) / pvValue);
1120 }
1121 if constexpr (has_extbo_) {
1122 B_avg[contiZfracEqIdx] += 1.0 / fs.invB(FluidSystem::gasPhaseIdx).value();
1123 const auto R2 = modelResid[cell_idx][contiZfracEqIdx];
1124 R_sum[ contiZfracEqIdx ] += R2;
1125 maxCoeff[contiZfracEqIdx] = std::max(maxCoeff[contiZfracEqIdx],
1126 std::abs(R2) / pvValue);
1127 }
1128 if constexpr (has_polymer_) {
1129 B_avg[contiPolymerEqIdx] += 1.0 / fs.invB(FluidSystem::waterPhaseIdx).value();
1130 const auto R2 = modelResid[cell_idx][contiPolymerEqIdx];
1131 R_sum[contiPolymerEqIdx] += R2;
1132 maxCoeff[contiPolymerEqIdx] = std::max(maxCoeff[contiPolymerEqIdx],
1133 std::abs(R2) / pvValue);
1134 }
1135 if constexpr (has_foam_) {
1136 B_avg[ contiFoamEqIdx ] += 1.0 / fs.invB(FluidSystem::gasPhaseIdx).value();
1137 const auto R2 = modelResid[cell_idx][contiFoamEqIdx];
1138 R_sum[contiFoamEqIdx] += R2;
1139 maxCoeff[contiFoamEqIdx] = std::max(maxCoeff[contiFoamEqIdx],
1140 std::abs(R2) / pvValue);
1141 }
1142 if constexpr (has_brine_) {
1143 B_avg[ contiBrineEqIdx ] += 1.0 / fs.invB(FluidSystem::waterPhaseIdx).value();
1144 const auto R2 = modelResid[cell_idx][contiBrineEqIdx];
1145 R_sum[contiBrineEqIdx] += R2;
1146 maxCoeff[contiBrineEqIdx] = std::max(maxCoeff[contiBrineEqIdx],
1147 std::abs(R2) / pvValue);
1148 }
1149
1150 if constexpr (has_polymermw_) {
1151 static_assert(has_polymer_);
1152
1153 B_avg[contiPolymerMWEqIdx] += 1.0 / fs.invB(FluidSystem::waterPhaseIdx).value();
1154 // the residual of the polymer molecular equation is scaled down by a 100, since molecular weight
1155 // can be much bigger than 1, and this equation shares the same tolerance with other mass balance equations
1156 // TODO: there should be a more general way to determine the scaling-down coefficient
1157 const auto R2 = modelResid[cell_idx][contiPolymerMWEqIdx] / 100.;
1158 R_sum[contiPolymerMWEqIdx] += R2;
1159 maxCoeff[contiPolymerMWEqIdx] = std::max(maxCoeff[contiPolymerMWEqIdx],
1160 std::abs(R2) / pvValue);
1161 }
1162
1163 if constexpr (has_energy_) {
1164 B_avg[contiEnergyEqIdx] += 1.0 / (4.182e1); // converting J -> RM3 (entalpy / (cp * deltaK * rho) assuming change of 1e-5K of water
1165 const auto R2 = modelResid[cell_idx][contiEnergyEqIdx];
1166 R_sum[contiEnergyEqIdx] += R2;
1167 maxCoeff[contiEnergyEqIdx] = std::max(maxCoeff[contiEnergyEqIdx],
1168 std::abs(R2) / pvValue);
1169 }
1170
1171 if constexpr (has_micp_) {
1172 B_avg[contiMicrobialEqIdx] += 1.0 / fs.invB(FluidSystem::waterPhaseIdx).value();
1173 const auto R1 = modelResid[cell_idx][contiMicrobialEqIdx];
1174 R_sum[contiMicrobialEqIdx] += R1;
1175 maxCoeff[contiMicrobialEqIdx] = std::max(maxCoeff[contiMicrobialEqIdx],
1176 std::abs(R1) / pvValue);
1177 B_avg[contiOxygenEqIdx] += 1.0 / fs.invB(FluidSystem::waterPhaseIdx).value();
1178 const auto R2 = modelResid[cell_idx][contiOxygenEqIdx];
1179 R_sum[contiOxygenEqIdx] += R2;
1180 maxCoeff[contiOxygenEqIdx] = std::max(maxCoeff[contiOxygenEqIdx],
1181 std::abs(R2) / pvValue);
1182 B_avg[contiUreaEqIdx] += 1.0 / fs.invB(FluidSystem::waterPhaseIdx).value();
1183 const auto R3 = modelResid[cell_idx][contiUreaEqIdx];
1184 R_sum[contiUreaEqIdx] += R3;
1185 maxCoeff[contiUreaEqIdx] = std::max(maxCoeff[contiUreaEqIdx],
1186 std::abs(R3) / pvValue);
1187 B_avg[contiBiofilmEqIdx] += 1.0 / fs.invB(FluidSystem::waterPhaseIdx).value();
1188 const auto R4 = modelResid[cell_idx][contiBiofilmEqIdx];
1189 R_sum[contiBiofilmEqIdx] += R4;
1190 maxCoeff[contiBiofilmEqIdx] = std::max(maxCoeff[contiBiofilmEqIdx],
1191 std::abs(R4) / pvValue);
1192 B_avg[contiCalciteEqIdx] += 1.0 / fs.invB(FluidSystem::waterPhaseIdx).value();
1193 const auto R5 = modelResid[cell_idx][contiCalciteEqIdx];
1194 R_sum[contiCalciteEqIdx] += R5;
1195 maxCoeff[contiCalciteEqIdx] = std::max(maxCoeff[contiCalciteEqIdx],
1196 std::abs(R5) / pvValue);
1197 }
1198}
1199
1200} // namespace Opm
1201
1202#endif // OPM_BLACKOILMODEL_IMPL_HEADER_INCLUDED
#define OPM_END_PARALLEL_TRY_CATCH(prefix, comm)
Catch exception and throw in a parallel try-catch clause.
Definition: DeferredLoggingErrorHelpers.hpp:192
#define OPM_BEGIN_PARALLEL_TRY_CATCH()
Macro to setup the try of a parallel try-catch.
Definition: DeferredLoggingErrorHelpers.hpp:158
BlackoilModel(Simulator &simulator, const ModelParameters &param, BlackoilWellModel< TypeTag > &well_model, const bool terminal_output)
Definition: BlackoilModel_impl.hpp:51
std::vector< std::vector< Scalar > > computeFluidInPlace(const T &, const std::vector< int > &fipnum) const
Wrapper required due to not following generic API.
Definition: BlackoilModel.hpp:249
ModelParameters param_
Definition: BlackoilModel.hpp:331
SimulatorReportSingle nonlinearIteration(const int iteration, const SimulatorTimerInterface &timer, NonlinearSolverType &nonlinear_solver)
Definition: BlackoilModel_impl.hpp:214
void writeNonlinearIterationsPerCell(const std::filesystem::path &odir) const
Write the number of nonlinear iterations per cell to a file in ResInsight compatible format.
Definition: BlackoilModel_impl.hpp:1046
SimulatorReportSingle assembleReservoir(const SimulatorTimerInterface &, const int iterationIdx)
Assemble the residual and Jacobian of the nonlinear system.
Definition: BlackoilModel_impl.hpp:357
ConvergenceReport getConvergence(const SimulatorTimerInterface &timer, const int iteration, const int maxIter, std::vector< Scalar > &residual_norms)
Definition: BlackoilModel_impl.hpp:988
ConvergenceReport getReservoirConvergence(const double reportTime, const double dt, const int iteration, const int maxIter, std::vector< Scalar > &B_avg, std::vector< Scalar > &residual_norms)
Definition: BlackoilModel_impl.hpp:740
GetPropType< TypeTag, Properties::IntensiveQuantities > IntensiveQuantities
Definition: BlackoilModel.hpp:67
const std::vector< SimulatorReport > & domainAccumulatedReports() const
return the statistics of local solves accumulated for each domain on this rank
Definition: BlackoilModel_impl.hpp:1036
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: BlackoilModel_impl.hpp:604
GetPropType< TypeTag, Properties::ElementContext > ElementContext
Definition: BlackoilModel.hpp:66
std::vector< StepReport > convergence_reports_
Definition: BlackoilModel.hpp:346
const SimulatorReport & localAccumulatedReports() const
return the statistics of local solves accumulated for this rank
Definition: BlackoilModel_impl.hpp:1025
SimulatorReportSingle afterStep(const SimulatorTimerInterface &)
Definition: BlackoilModel_impl.hpp:344
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: BlackoilModel_impl.hpp:544
const Grid & grid_
Definition: BlackoilModel.hpp:321
GetPropType< TypeTag, Properties::SolutionVector > SolutionVector
Definition: BlackoilModel.hpp:69
void initialLinearization(SimulatorReportSingle &report, const int iteration, const int minIter, const int maxIter, const SimulatorTimerInterface &timer)
Definition: BlackoilModel_impl.hpp:155
void updateSolution(const BVector &dx)
Apply an update to the primary variables.
Definition: BlackoilModel_impl.hpp:520
long int global_nc_
The number of cells of the global grid.
Definition: BlackoilModel.hpp:340
void updateTUNING(const Tuning &tuning)
Definition: BlackoilModel_impl.hpp:727
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: BlackoilModel_impl.hpp:1083
std::unique_ptr< BlackoilModelNldd< TypeTag > > nlddSolver_
Non-linear DD solver.
Definition: BlackoilModel.hpp:349
SimulatorReportSingle nonlinearIterationNewton(const int iteration, const SimulatorTimerInterface &timer, NonlinearSolverType &nonlinear_solver)
Definition: BlackoilModel_impl.hpp:252
void writePartitions(const std::filesystem::path &odir) const
Definition: BlackoilModel_impl.hpp:1056
std::pair< std::vector< double >, std::vector< int > > characteriseCnvPvSplit(const std::vector< Scalar > &B_avg, const double dt)
Compute pore-volume/cell count split among "converged", "relaxed converged", "unconverged" cells base...
Definition: BlackoilModel_impl.hpp:655
GetPropType< TypeTag, Properties::Simulator > Simulator
Definition: BlackoilModel.hpp:64
void solveJacobianSystem(BVector &x)
Definition: BlackoilModel_impl.hpp:458
SimulatorReportSingle prepareStep(const SimulatorTimerInterface &timer)
Definition: BlackoilModel_impl.hpp:86
void convergencePerCell(const std::vector< Scalar > &B_avg, const double dt, const double tol_cnv, const double tol_cnv_energy, const int iteration)
Compute the number of Newtons required by each cell in order to satisfy the solution change convergen...
Definition: BlackoilModel_impl.hpp:941
Dune::BlockVector< VectorBlockType > BVector
Definition: BlackoilModel.hpp:107
GetPropType< TypeTag, Properties::Scalar > Scalar
Definition: BlackoilModel.hpp:75
Scalar relativeChange() const
Definition: BlackoilModel_impl.hpp:371
Class for handling the blackoil well model.
Definition: BlackoilWellModel.hpp:102
Definition: ConvergenceReport.hpp:38
Severity
Definition: ConvergenceReport.hpp:49
void setReservoirFailed(const ReservoirFailure &rf)
Definition: ConvergenceReport.hpp:264
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: blackoilboundaryratevector.hh:39
std::string to_string(const ConvergenceReport::ReservoirFailure::Type t)
Solver parameters for the BlackoilModel.
Definition: BlackoilModelParameters.hpp:179
std::string nonlinear_solver_
Nonlinear solver type: newton or nldd.
Definition: BlackoilModelParameters.hpp:332
Definition: AquiferGridUtils.hpp:35
Definition: SimulatorReport.hpp:122
A struct for returning timing data from a simulator to its caller.
Definition: SimulatorReport.hpp:34
double linear_solve_time
Definition: SimulatorReport.hpp:43
double assemble_time
Definition: SimulatorReport.hpp:39
bool converged
Definition: SimulatorReport.hpp:55
double pre_post_time
Definition: SimulatorReport.hpp:40
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 total_linearizations
Definition: SimulatorReport.hpp:49
unsigned int total_linear_iterations
Definition: SimulatorReport.hpp:51