27#ifndef EWOMS_NEWTON_METHOD_HH
28#define EWOMS_NEWTON_METHOD_HH
30#include <dune/common/classname.hh>
31#include <dune/common/parallel/mpihelper.hh>
33#include <dune/istl/istlexception.hh>
35#include <opm/common/Exceptions.hpp>
37#include <opm/material/densead/Math.hpp>
62template <
class TypeTag>
78template<
class TypeTag>
82template<
class TypeTag>
97template <
class TypeTag>
115 using Communicator =
typename Dune::MPIHelper::MPICommunicator;
116 using CollectiveCommunication =
typename Dune::Communication<typename Dune::MPIHelper::MPICommunicator>;
125 ,
comm_(
Dune::MPIHelper::getCommunicator())
136 LinearSolverBackend::registerParameters();
192 {
params_.tolerance_ = value; }
202 const SolutionVector& currentSolution,
203 const GlobalEqVector& solutionUpdate,
204 const GlobalEqVector& currentResidual)
206 asImp_().update_(nextSolution, currentSolution, solutionUpdate, currentResidual);
217 const bool istty =
isTty(stdout);
222 const char* clearRemainingLine =
"\n";
224 static const char ansiClear[] = { 0x1b,
'[',
'K',
'\r', 0 };
225 clearRemainingLine = ansiClear;
234 SolutionVector& nextSolution =
model().solution(0);
235 SolutionVector currentSolution(nextSolution);
236 GlobalEqVector solutionUpdate(nextSolution.size());
238 Linearizer& linearizer =
model().linearizer();
244 asImp_().begin_(nextSolution);
261 asImp_().beginIteration_();
265 currentSolution = nextSolution;
268 std::cout <<
"Linearize: r(x^k) = dS/dt + div F - q; M = grad r"
269 << clearRemainingLine
275 asImp_().linearizeDomain_();
276 asImp_().linearizeAuxiliaryEquations_();
280 auto& residual = linearizer.residual();
281 const auto& jacobian = linearizer.jacobian();
282 bool preparedOnGpu =
false;
283#if HAVE_CUDA && OPM_IS_COMPILING_WITH_GPU_COMPILER
284 if constexpr (getPropValue<TypeTag, Properties::RunAssemblyOnGpu>()) {
285 if (linearizer.gpuSystemActive()) {
287 linearizer.gpuJacobian(), linearizer.flattenedGpuResidual());
291 if (!preparedOnGpu) {
302 asImp_().preSolve_(currentSolution, residual);
307 std::cout << clearRemainingLine << std::flush;
312 asImp_().endIteration_(nextSolution, currentSolution);
320 std::cout <<
"Solve: M deltax^k = r"
321 << clearRemainingLine
329 solutionUpdate = 0.0;
336 std::cout <<
"Newton: Linear solver did not converge\n" << std::flush;
348 std::cout <<
"Update: x^(k+1) = x^k - deltax^k"
349 << clearRemainingLine
356 asImp_().postSolve_(currentSolution,
359 asImp_().update_(nextSolution, currentSolution, solutionUpdate, residual);
364 std::cout << clearRemainingLine
370 asImp_().endIteration_(nextSolution, currentSolution);
374 catch (
const Dune::Exception& e)
377 std::cout <<
"Newton method caught exception: \""
378 << e.what() <<
"\"\n" << std::flush;
387 catch (
const NumericalProblem& e)
390 std::cout <<
"Newton method caught exception: \""
391 << e.what() <<
"\"\n" << std::flush;
403 std::cout << clearRemainingLine
418 std::cout <<
"Linearization/solve/update time: "
425 <<
"\n" << std::flush;
439 asImp_().succeeded_();
459 const int nit =
problem().iterationContext().iteration();
462 Scalar percent = Scalar(overshoot) /
params_.targetIterations_;
463 Scalar nextDt = std::max(
problem().minTimeStepSize(),
464 oldDt / (Scalar{1.0} + percent));
468 Scalar percent = Scalar(
params_.targetIterations_ - nit) /
params_.targetIterations_;
469 Scalar nextDt = std::max(
problem().minTimeStepSize(),
470 oldDt*(Scalar{1.0} + percent / Scalar{1.2}));
529 problem().resetIterationForNewTimestep();
531 if (
params_.writeConvergence_) {
543 const auto& comm =
simulator_.gridView().comm();
544 bool succeeded =
true;
548 catch (
const std::exception& e) {
551 std::cout <<
"rank " <<
simulator_.gridView().comm().rank()
552 <<
" caught an exception while pre-processing the problem:" << e.what()
553 <<
"\n" << std::flush;
556 succeeded = comm.min(succeeded);
559 throw NumericalProblem(
"pre processing of the problem failed");
570 {
model().linearizer().linearizeDomain(); }
574 model().linearizer().linearizeAuxiliaryEquations();
575 model().linearizer().finalize();
579 const GlobalEqVector& currentResidual)
581 const auto& constraintsMap =
model().linearizer().constraintsMap();
583 Scalar newtonMaxError =
params_.maxError_;
588 for (
unsigned dofIdx = 0; dofIdx < currentResidual.size(); ++dofIdx) {
590 if (dofIdx >=
model().numGridDof() ||
model().dofTotalVolume(dofIdx) <= 0.0) {
596 if (constraintsMap.count(dofIdx) > 0) {
601 const auto& r = currentResidual[dofIdx];
602 for (
unsigned eqIdx = 0; eqIdx < r.size(); ++eqIdx) {
612 if (
error_ > newtonMaxError) {
614 " is larger than maximum allowed error of " +
632 const GlobalEqVector&,
633 GlobalEqVector& solutionUpdate)
637 const auto& comm =
simulator_.gridView().comm();
638 for (
unsigned i = 0; i <
simulator_.model().numAuxiliaryModules(); ++i) {
639 bool succeeded =
true;
641 simulator_.model().auxiliaryModule(i)->postSolve(solutionUpdate);
643 catch (
const std::exception& e) {
646 std::cout <<
"rank " <<
simulator_.gridView().comm().rank()
647 <<
" caught an exception while post processing an auxiliary module:" << e.what()
648 <<
"\n" << std::flush;
651 succeeded = comm.min(succeeded);
654 throw NumericalProblem(
"post processing of an auxilary equation failed");
674 const SolutionVector& currentSolution,
675 const GlobalEqVector& solutionUpdate,
676 const GlobalEqVector& currentResidual)
678 const auto& constraintsMap =
model().linearizer().constraintsMap();
682 asImp_().writeConvergence_(currentSolution, solutionUpdate);
685 if (!std::isfinite(solutionUpdate.one_norm())) {
686 throw NumericalProblem(
"Non-finite update!");
689 std::size_t numGridDof =
model().numGridDof();
690 for (
unsigned dofIdx = 0; dofIdx < numGridDof; ++dofIdx) {
692 if (constraintsMap.count(dofIdx) > 0) {
693 const auto& constraints = constraintsMap.at(dofIdx);
694 asImp_().updateConstraintDof_(dofIdx,
695 nextSolution[dofIdx],
699 asImp_().updatePrimaryVariables_(dofIdx,
700 nextSolution[dofIdx],
701 currentSolution[dofIdx],
702 solutionUpdate[dofIdx],
703 currentResidual[dofIdx]);
707 asImp_().updatePrimaryVariables_(dofIdx,
708 nextSolution[dofIdx],
709 currentSolution[dofIdx],
710 solutionUpdate[dofIdx],
711 currentResidual[dofIdx]);
716 std::size_t numDof =
model().numTotalDof();
717 for (std::size_t dofIdx = numGridDof; dofIdx < numDof; ++dofIdx) {
718 nextSolution[dofIdx] = currentSolution[dofIdx];
719 nextSolution[dofIdx] -= solutionUpdate[dofIdx];
727 PrimaryVariables& nextValue,
728 const Constraints& constraints)
729 { nextValue = constraints; }
735 PrimaryVariables& nextValue,
736 const PrimaryVariables& currentValue,
737 const EqVector& update,
740 nextValue = currentValue;
751 const GlobalEqVector& solutionUpdate)
753 if (
params_.writeConvergence_) {
767 const SolutionVector&)
771 const auto& comm =
simulator_.gridView().comm();
772 bool succeeded =
true;
776 catch (
const std::exception& e) {
779 std::cout <<
"rank " <<
simulator_.gridView().comm().rank()
780 <<
" caught an exception while letting the problem post-process:" << e.what()
781 <<
"\n" << std::flush;
784 succeeded = comm.min(succeeded);
787 throw NumericalProblem(
"post processing of the problem failed");
791 std::cout <<
"Newton iteration " <<
problem().iterationContext().iteration() <<
""
802 if (
problem().iterationContext().iteration() < 1) {
810 else if (
problem().iterationContext().iteration() >=
params_.maxIterations_) {
827 if (
params_.writeConvergence_) {
849 {
return getPropValue<TypeTag, Properties::EnableConstraints>(); }
878 Implementation& asImp_()
879 {
return *
static_cast<Implementation *
>(
this); }
881 const Implementation& asImp_()
const
882 {
return *
static_cast<const Implementation *
>(
this); }
The multi-dimensional Newton method.
Definition: newtonmethod.hh:99
bool verbose_() const
Returns true if the Newton method ought to be chatty.
Definition: newtonmethod.hh:516
Timer linearizeTimer_
Definition: newtonmethod.hh:854
void end_()
Indicates that we're done solving the non-linear system of equations.
Definition: newtonmethod.hh:825
const Timer & updateTimer() const
Definition: newtonmethod.hh:509
const Timer & linearizeTimer() const
Definition: newtonmethod.hh:503
Timer solveTimer_
Definition: newtonmethod.hh:855
const Timer & solveTimer() const
Definition: newtonmethod.hh:506
bool proceed_() const
Returns true iff another Newton iteration should be done.
Definition: newtonmethod.hh:800
static bool enableConstraints_()
Definition: newtonmethod.hh:848
const LinearSolverBackend & linearSolver() const
Returns the linear solver backend object for external use.
Definition: newtonmethod.hh:497
void updatePrimaryVariables_(unsigned, PrimaryVariables &nextValue, const PrimaryVariables ¤tValue, const EqVector &update, const EqVector &)
Update a single primary variables object.
Definition: newtonmethod.hh:734
void setTolerance(Scalar value)
Set the current tolerance at which the Newton method considers itself to be converged.
Definition: newtonmethod.hh:191
std::ostringstream & endIterMsg()
Message that should be printed for the user after the end of an iteration.
Definition: newtonmethod.hh:478
static void registerParameters()
Register all run-time parameters for the Newton method.
Definition: newtonmethod.hh:134
Timer prePostProcessTimer_
Definition: newtonmethod.hh:853
void postSolve_(const SolutionVector &, const GlobalEqVector &, GlobalEqVector &solutionUpdate)
Update the error of the solution given the previous iteration.
Definition: newtonmethod.hh:631
const Timer & prePostProcessTimer() const
Definition: newtonmethod.hh:500
Scalar lastError_
Definition: newtonmethod.hh:861
bool apply()
Run the Newton method.
Definition: newtonmethod.hh:215
void writeConvergence_(const SolutionVector ¤tSolution, const GlobalEqVector &solutionUpdate)
Write the convergence behaviour of the newton method to disk.
Definition: newtonmethod.hh:750
Scalar error_
Definition: newtonmethod.hh:860
bool lastSolveFailed_
Definition: newtonmethod.hh:865
void begin_(const SolutionVector &)
Called before the Newton method is applied to an non-linear system of equations.
Definition: newtonmethod.hh:525
void failed_()
Called if the Newton method broke down.
Definition: newtonmethod.hh:837
void update_(SolutionVector &nextSolution, const SolutionVector ¤tSolution, const GlobalEqVector &solutionUpdate, const GlobalEqVector ¤tResidual)
Update the current solution with a delta vector.
Definition: newtonmethod.hh:673
void preSolve_(const SolutionVector &, const GlobalEqVector ¤tResidual)
Definition: newtonmethod.hh:578
Timer updateTimer_
Definition: newtonmethod.hh:856
const Model & model() const
Returns a reference to the numeric model.
Definition: newtonmethod.hh:177
LinearSolverBackend linearSolver_
Definition: newtonmethod.hh:867
void succeeded_()
Called if the Newton method was successful.
Definition: newtonmethod.hh:845
Scalar tolerance() const
Return the current tolerance at which the Newton method considers itself to be converged.
Definition: newtonmethod.hh:184
LinearSolverBackend & linearSolver()
Returns the linear solver backend object for external use.
Definition: newtonmethod.hh:491
void linearizeDomain_()
Linearize the global non-linear system of equations associated with the spatial domain.
Definition: newtonmethod.hh:569
const Problem & problem() const
Returns a reference to the object describing the current physical problem.
Definition: newtonmethod.hh:165
Scalar suggestTimeStepSize(Scalar oldDt) const
Suggest a new time-step size based on the old time-step size.
Definition: newtonmethod.hh:453
bool converged() const
Returns true if the error of the solution is below the tolerance.
Definition: newtonmethod.hh:153
CollectiveCommunication comm_
Definition: newtonmethod.hh:871
Problem & problem()
Returns a reference to the object describing the current physical problem.
Definition: newtonmethod.hh:159
NewtonMethodParams< Scalar > params_
Definition: newtonmethod.hh:862
void eraseMatrix()
Causes the solve() method to discared the structure of the linear system of equations the next time i...
Definition: newtonmethod.hh:485
void applyUpdate(SolutionVector &nextSolution, const SolutionVector ¤tSolution, const GlobalEqVector &solutionUpdate, const GlobalEqVector ¤tResidual)
Public wrapper for applying a Newton update to a solution vector.
Definition: newtonmethod.hh:201
void updateConstraintDof_(unsigned, PrimaryVariables &nextValue, const Constraints &constraints)
Update the primary variables for a degree of freedom which is constraint.
Definition: newtonmethod.hh:726
std::ostringstream endIterMsgStream_
Definition: newtonmethod.hh:858
ConvergenceWriter convergenceWriter_
Definition: newtonmethod.hh:875
NewtonMethod(Simulator &simulator)
Definition: newtonmethod.hh:119
void finishInit()
Finialize the construction of the object.
Definition: newtonmethod.hh:146
void linearizeAuxiliaryEquations_()
Definition: newtonmethod.hh:572
Model & model()
Returns a reference to the numeric model.
Definition: newtonmethod.hh:171
Simulator & simulator_
Definition: newtonmethod.hh:851
void beginIteration_()
Indicates the beginning of a Newton iteration.
Definition: newtonmethod.hh:539
void endIteration_(const SolutionVector &, const SolutionVector &)
Indicates that one Newton iteration was finished.
Definition: newtonmethod.hh:766
A convergence writer for the Newton method which does nothing.
Definition: nullconvergencewriter.hh:51
A simple class which makes sure that a timer gets stopped if an exception is thrown.
Definition: timerguard.hh:42
Provides an encapsulation to measure the system time.
Definition: timer.hpp:46
void start()
Start counting the time resources used by the simulation.
void halt()
Stop the measurement reset all timing values.
double realTimeElapsed() const
Return the real time [s] elapsed during the periods the timer was active since the last reset.
double stop()
Stop counting the time resources.
Declare the properties used by the infrastructure code of the finite volume discretizations.
Declares the properties required by the black oil model.
Definition: fvbaseprimaryvariables.hh:161
Definition: blackoilmodel.hh:74
Definition: blackoilbioeffectsmodules.hh:45
bool isTty(std::FILE *stream)
Is the given stream attached to a terminal?
typename Properties::Detail::GetPropImpl< TypeTag, Property >::type::type GetPropType
get the type alias defined in the property (equivalent to old macro GET_PROP_TYPE(....
Definition: propertysystem.hh:233
std::string to_string(const ConvergenceReport::ReservoirFailure::Type t)
Struct holding the parameters for NewtonMethod.
Definition: newtonmethodparams.hpp:71
static void registerParameters()
Registers the parameters in parameter system.
Specifies the type of the class which writes out the Newton convergence.
Definition: newtonmethodproperties.hh:40
Specifies the type of the actual Newton method.
Definition: newtonmethodproperties.hh:32
Definition: newtonmethod.hh:73