00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022
00023
00024
00025
00026
00027
00028
00029
00030
00031
00032
00033
00034
00035
00040 #include <sstream>
00041 #include "petscsnes.h"
00042 #include "SimplePetscNonlinearSolver.hpp"
00043 #include "Exception.hpp"
00044 #include "PetscTools.hpp"
00045
00046 Vec SimplePetscNonlinearSolver::Solve(PetscErrorCode (*pComputeResidual)(SNES,Vec,Vec,void*),
00047 PetscErrorCode (*pComputeJacobian)(SNES,Vec,Mat*,Mat*,MatStructure*,void*),
00048 Vec initialGuess,
00049 unsigned fill,
00050 void* pContext)
00051 {
00052 SNES snes;
00053
00054
00055 Vec residual;
00056 VecDuplicate(initialGuess, &residual);
00057
00058 Mat jacobian;
00059
00060 PetscInt N;
00061
00062
00063 VecGetSize(initialGuess,&N);
00064
00065
00066 PetscTools::SetupMat(jacobian, N, N, fill, PETSC_DECIDE, PETSC_DECIDE, true, false );
00067
00068 SNESCreate(PETSC_COMM_WORLD, &snes);
00069 SNESSetFunction(snes, residual, pComputeResidual, pContext);
00070 SNESSetJacobian(snes, jacobian, jacobian, pComputeJacobian, pContext);
00071 #if (PETSC_VERSION_MAJOR == 3 && PETSC_VERSION_MINOR >= 4) //PETSc 3.4 or later
00072 SNESSetType(snes, SNESNEWTONLS);
00073 #else
00074 SNESSetType(snes, SNESLS);
00075 #endif
00076 SNESSetTolerances(snes,1.0e-5,1.0e-5,1.0e-5,PETSC_DEFAULT,PETSC_DEFAULT);
00077 #if (PETSC_VERSION_MAJOR == 3 && PETSC_VERSION_MINOR == 3) //PETSc 3.3
00078 SNESLineSearch linesearch;
00079 SNESGetSNESLineSearch(snes, &linesearch);
00080 SNESLineSearchSetType(linesearch, "bt");
00081 #endif
00082 #if (PETSC_VERSION_MAJOR == 3 && PETSC_VERSION_MINOR >= 4) //PETSc 3.4 or later
00083 SNESLineSearch linesearch;
00084 SNESGetLineSearch(snes, &linesearch);
00085 SNESLineSearchSetType(linesearch, "bt");
00086 #endif
00087
00088
00089 Vec x;
00090 VecDuplicate(initialGuess, &x);
00091 VecCopy(initialGuess, x);
00092
00093 #if (PETSC_VERSION_MAJOR == 2 && PETSC_VERSION_MINOR == 2) //PETSc 2.2
00094 SNESSolve(snes, x);
00095 #else
00096 SNESSolve(snes, PETSC_NULL, x);
00097 #endif
00098
00099 PetscTools::Destroy(residual);
00100 PetscTools::Destroy(jacobian);
00101
00102 SNESConvergedReason reason;
00103 SNESGetConvergedReason(snes,&reason);
00104 #define COVERAGE_IGNORE
00105 if (reason < 0)
00106 {
00107 std::stringstream reason_stream;
00108 reason_stream << reason;
00109 PetscTools::Destroy(x);
00110 SNESDestroy(PETSC_DESTROY_PARAM(snes));
00111 EXCEPTION("Nonlinear Solver did not converge. PETSc reason code:"
00112 +reason_stream.str()+" .");
00113 }
00114 #undef COVERAGE_IGNORE
00115 SNESDestroy(PETSC_DESTROY_PARAM(snes));
00116
00117 return x;
00118 }