21 #ifndef THUNDEREGG_PETSC_KSPSOLVER_H
22 #define THUNDEREGG_PETSC_KSPSOLVER_H
46 KSPType type = KSPGMRES;
53 Vec getPetscVecWithoutGhost(
const Vector<D>& vec)
const
68 void copyToPetscVec(
const Vector<D>& vec, Vec petsc_vec)
const
70 double* petsc_vec_view;
71 size_t curr_index = 0;
72 VecGetArray(petsc_vec, &petsc_vec_view);
74 for (
int c = 0; c < vec.getNumComponents(); c++) {
76 nested_loop<D>(ld.
getStart(), ld.
getEnd(), [&](
const std::array<int, D>& coord) {
77 petsc_vec_view[curr_index] = ld[coord];
82 VecRestoreArray(petsc_vec, &petsc_vec_view);
90 void copyToVec(Vec petsc_vec,
Vector<D>& vec)
const
92 const double* petsc_vec_view;
93 size_t curr_index = 0;
94 VecGetArrayRead(petsc_vec, &petsc_vec_view);
96 for (
int c = 0; c < vec.getNumComponents(); c++) {
98 nested_loop<D>(ld.
getStart(), ld.
getEnd(), [&](
const std::array<int, D>& coord) {
99 ld[coord] = petsc_vec_view[curr_index];
104 VecRestoreArrayRead(petsc_vec, &petsc_vec_view);
112 void destroyPetscVec(
const Vector<D>& vec, Vec petsc_vec)
const { VecDestroy(&petsc_vec); }
113 static int MonitorResidual(KSP ksp, PetscInt n, PetscReal rnorm, std::ostream* os)
116 sprintf(buf,
"%5d %16.8e\n", n, rnorm);
117 (*os) << std::string(buf);
133 void setType(KSPType new_type) { type = new_type; }
139 std::ostream& os = std::cout)
const override
143 PC Mr_PETSC =
nullptr;
147 Vec x_PETSC = getPetscVecWithoutGhost(x);
148 copyToPetscVec(x, x_PETSC);
150 Vec b_PETSC = getPetscVecWithoutGhost(x);
151 copyToPetscVec(b, b_PETSC);
154 KSPCreate(PETSC_COMM_WORLD, &ksp);
155 KSPSetType(ksp, type);
156 KSPSetOperators(ksp, A_PETSC, A_PETSC);
159 KSPSetPC(ksp, Mr_PETSC);
165 ksp, (PetscErrorCode(*)(KSP, PetscInt, PetscReal,
void*)) & MonitorResidual, &os,
nullptr);
168 KSPSolve(ksp, b_PETSC, x_PETSC);
171 KSPGetIterationNumber(ksp, &iterations);
173 const char* converged_reason;
174 KSPGetConvergedReasonString(ksp, &converged_reason);
175 os << converged_reason << std::endl;
178 VecDestroy(&x_PETSC);
179 VecDestroy(&b_PETSC);
180 PCDestroy(&Mr_PETSC);
181 MatDestroy(&A_PETSC);