41 #include "petscsnes.h" 42 #include "SimplePetscNonlinearSolver.hpp" 47 #
if (PETSC_VERSION_MAJOR==3 && PETSC_VERSION_MINOR>=5)
48 PetscErrorCode (*pComputeJacobian)(SNES,
Vec,
Mat,
Mat,
void*),
50 PetscErrorCode (*pComputeJacobian)(SNES,
Vec,
Mat*,
Mat*,MatStructure*,
void*),
60 VecDuplicate(initialGuess, &residual);
66 VecGetSize(initialGuess, &N);
71 SNESCreate(PETSC_COMM_WORLD, &snes);
73 SNESSetFunction(snes, residual, pComputeResidual, pContext);
74 SNESSetJacobian(snes, jacobian, jacobian, pComputeJacobian, pContext);
76 #if (PETSC_VERSION_MAJOR == 3 && PETSC_VERSION_MINOR >= 4) //PETSc 3.4 or later 77 SNESSetType(snes, SNESNEWTONLS);
79 SNESSetType(snes, SNESLS);
82 SNESSetTolerances(snes,1.0e-5,1.0e-5,1.0e-5,PETSC_DEFAULT,PETSC_DEFAULT);
83 #if (PETSC_VERSION_MAJOR == 3 && PETSC_VERSION_MINOR == 3) //PETSc 3.3 84 SNESLineSearch linesearch;
85 SNESGetSNESLineSearch(snes, &linesearch);
86 SNESLineSearchSetType(linesearch,
"bt");
87 #elif (PETSC_VERSION_MAJOR == 3 && PETSC_VERSION_MINOR >= 4) //PETSc 3.4 or later 88 SNESLineSearch linesearch;
89 SNESGetLineSearch(snes, &linesearch);
90 SNESLineSearchSetType(linesearch,
"bt");
96 VecDuplicate(initialGuess, &x);
97 VecCopy(initialGuess, x);
99 #if (PETSC_VERSION_MAJOR == 3 && PETSC_VERSION_MINOR >= 5) 105 SNESGetKSP(snes,&ksp);
108 PCSetType(pc,PCNONE);
111 #if (PETSC_VERSION_MAJOR == 2 && PETSC_VERSION_MINOR == 2) //PETSc 2.2 114 SNESSolve(snes, PETSC_NULL, x);
119 SNESConvergedReason reason;
120 SNESGetConvergedReason(snes,&reason);
124 std::stringstream reason_stream;
125 reason_stream << reason;
128 EXCEPTION(
"Nonlinear Solver did not converge. PETSc reason code:" 129 +reason_stream.str()+
" .");
#define EXCEPTION(message)
Vec Solve(PetscErrorCode(*pComputeResidual)(SNES, Vec, Vec, void *), PetscErrorCode(*pComputeJacobian)(SNES, Vec, Mat *, Mat *, MatStructure *, void *), Vec initialGuess, unsigned fill, void *pContext)