Debian Codegraph @

packages/trilinoscouplings/examples/epetraext/EpetraExt_petsc.cpp

raw
1 // @HEADER
2 // *****************************************************************************
3 // Trilinos: An Object-Oriented Solver Framework
4 //
5 // Copyright 2001-2024 NTESS and the Trilinos contributors.
6 // SPDX-License-Identifier: BSD-3-Clause
7 // *****************************************************************************
8 // @HEADER
9
10 #include "ml_config.h"
11 #include "EpetraExt_config.h"
12 #if defined(HAVE_PETSC) && defined(HAVE_ML_EPETRA) && defined(HAVE_ML_TEUCHOS) && defined(HAVE_ML_AZTECOO) && defined(HAVE_MPI)
13 #include "petscksp.h"
14 #include "EpetraExt_PETScAIJMatrix.h"
15 #include "Epetra_Vector.h"
16 #include "Epetra_Map.h"
17 #include "ml_MultiLevelPreconditioner.h"
18 #include "AztecOO.h"
19 #include "Epetra_LinearProblem.h"
20
21 /*
22 This example demonstrates how to apply a Trilinos preconditioner to a PETSc
23 linear system.
24
25 For information on configuring and building Trilinos with the PETSc aij
26 interface enabled, please see EpetraExt's doxygen documentation at
27 http://trilinos.sandia.gov/packages/epetraext, development version
28 or release 9.0 or later.
29
30 The PETSc matrix is a 2D 5-point Laplace operator stored in AIJ format.
31 This matrix is wrapped as an Epetra_PETScAIJMatrix, and an ML AMG
32 preconditioner is created for it. The associated linear system is solved twice,
33 the first time using AztecOO's preconditioned CG, the second time using PETSc's.
34
35 To invoke this example, use something like:
36
37 mpirun -np 5 ./TrilinosCouplings_petsc.exe -m 150 -n 150 -petsc_smoother -ksp_monitor_true_residual
38 */
39
40 static char help[] = "Demonstrates how to solve a PETSc linear system with KSP\
41 and a Trilinos AMG preconditioner. In particular, it shows how to wrap a PETSc\
42 AIJ matrix as an Epetra matrix, create the AMG preconditioner, and wrap it as a\
43 shell preconditioner for a PETSc Krylov method.\
44 Input parameters include:\n\
45 -random_exact_sol : use a random exact solution vector\n\
46 -view_exact_sol : write exact solution vector to stdout\n\
47 -m <mesh_x> : number of mesh points in x-direction\n\
48 -n <mesh_n> : number of mesh points in y-direction\n\n";
49
50 #if (PETSC_VERSION_MAJOR < 3) || (PETSC_VERSION_MAJOR == 3 && PETSC_VERSION_MINOR < 1)
51 extern PetscErrorCode ShellApplyML(void*,Vec,Vec);
52 #else
53 extern PetscErrorCode ShellApplyML(PC,Vec,Vec);
54 #endif
55
56 #undef __FUNCT__
57 #define __FUNCT__ "main"
58 int main(int argc,char **args)
59 {
60 Vec x,b,u; /* approx solution, RHS, exact solution */
61 Mat A; /* linear system matrix */
62 KSP ksp; /* linear solver context */
63 KSP kspSmoother=0; /* solver context for PETSc fine grid smoother */
64 PC pc;
65 PetscRandom rctx; /* random number generator context */
66 PetscReal norm; /* norm of solution error */
67 PetscInt i,j,Ii,J,Istart,Iend,its;
68 PetscInt m = 50,n = 50; /* #mesh points in x & y directions, resp. */
69 PetscErrorCode ierr;
70 PetscBool flg;
71 PetscScalar v,one = 1.0,neg_one = -1.0;
72 PetscInt rank=0;
73 MPI_Comm comm;
74
75 PetscInitialize(&argc,&args,(char *)0,help);
76 ierr = PetscOptionsGetInt(PETSC_NULL,"-m",&m,PETSC_NULL);CHKERRQ(ierr);
77 ierr = PetscOptionsGetInt(PETSC_NULL,"-n",&n,PETSC_NULL);CHKERRQ(ierr);
78
79 ierr = MatCreate(PETSC_COMM_WORLD,&A);CHKERRQ(ierr);
80 ierr = MatSetSizes(A,PETSC_DECIDE,PETSC_DECIDE,m*n,m*n);CHKERRQ(ierr);
81 ierr = MatSetType(A, MATAIJ);CHKERRQ(ierr);
82 ierr = MatSetFromOptions(A);CHKERRQ(ierr);
83 ierr = MatMPIAIJSetPreallocation(A,5,PETSC_NULL,5,PETSC_NULL);CHKERRQ(ierr);
84 ierr = MatSetUp(A);CHKERRQ(ierr);
85 PetscObjectGetComm( (PetscObject)A, &comm);
86 ierr = MPI_Comm_rank(comm,&rank);CHKERRQ(ierr);
87 if (!rank) printf("Matrix has %d (%dx%d) rows\n",m*n,m,n);
88
89 ierr = MatGetOwnershipRange(A,&Istart,&Iend);CHKERRQ(ierr);
90
91 for (Ii=Istart; Ii<Iend; Ii++) {
92 v = -1.0; i = Ii/n; j = Ii - i*n;
93 if (i>0) {J = Ii - n; ierr = MatSetValues(A,1,&Ii,1,&J,&v,INSERT_VALUES);CHKERRQ(ierr);}
94 if (i<m-1) {J = Ii + n; ierr = MatSetValues(A,1,&Ii,1,&J,&v,INSERT_VALUES);CHKERRQ(ierr);}
95 if (j>0) {J = Ii - 1; ierr = MatSetValues(A,1,&Ii,1,&J,&v,INSERT_VALUES);CHKERRQ(ierr);}
96 if (j<n-1) {J = Ii + 1; ierr = MatSetValues(A,1,&Ii,1,&J,&v,INSERT_VALUES);CHKERRQ(ierr);}
97 v = 4.0; ierr = MatSetValues(A,1,&Ii,1,&Ii,&v,INSERT_VALUES);CHKERRQ(ierr);
98 }
99
100 ierr = MatAssemblyBegin(A,MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);
101 ierr = MatAssemblyEnd(A,MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);
102
103 /* Wrap the PETSc matrix as an Epetra_PETScAIJMatrix. This is lightweight,
104 i.e., no deep data copies. */
105 Epetra_PETScAIJMatrix epA(A);
106
107 ierr = VecCreate(PETSC_COMM_WORLD,&u);CHKERRQ(ierr);
108 ierr = VecSetSizes(u,PETSC_DECIDE,m*n);CHKERRQ(ierr);
109 ierr = VecSetFromOptions(u);CHKERRQ(ierr);
110 ierr = VecDuplicate(u,&b);CHKERRQ(ierr);
111
112 ierr = VecDuplicate(b,&x);CHKERRQ(ierr);
113
114 ierr = PetscOptionsHasName(PETSC_NULL,"-random_exact_sol",&flg);CHKERRQ(ierr);
115 if (flg) {
116 ierr = PetscRandomCreate(PETSC_COMM_WORLD,&rctx);CHKERRQ(ierr);
117 ierr = PetscRandomSetFromOptions(rctx);CHKERRQ(ierr);
118 ierr = VecSetRandom(u,rctx);CHKERRQ(ierr);
119 ierr = PetscRandomDestroy(&rctx);CHKERRQ(ierr);
120 } else {
121 ierr = VecSet(u,one);CHKERRQ(ierr);
122 }
123 ierr = MatMult(A,u,b);CHKERRQ(ierr);
124 ierr = VecNorm(b,NORM_2,&norm);CHKERRQ(ierr);
125 if (rank==0) printf("||b|| = %f\n",norm);
126
127 /* Copy the PETSc vectors to Epetra vectors. */
128 Epetra_Vector epu(epA.Map()), epb(epA.Map());
129 PetscScalar *vals;
130 ierr = VecGetArray(u,&vals);CHKERRQ(ierr);
131 PetscInt length;
132 ierr = VecGetLocalSize(u,&length);CHKERRQ(ierr);
133 for (int j=0; j<length; j++) epu[j] = vals[j];
134 ierr = VecRestoreArray(u,&vals);CHKERRQ(ierr);
135 epA.Multiply(false, epu, epb);
136
137 /* Check norms of the Epetra and PETSc vectors. */
138 epu.Norm2(&norm);
139 if (rank == 0) printf("||epetra u||_2 = %f\n",norm);
140 ierr = VecNorm(u,NORM_2,&norm);CHKERRQ(ierr);
141 if (rank == 0) printf("||petsc u||_2 = %f\n",norm);
142 epb.Norm2(&norm);
143 if (rank == 0) printf("||epetra b||_2 = %f\n",norm);
144 ierr = VecNorm(b,NORM_2,&norm);CHKERRQ(ierr);
145 if (rank == 0) printf("||petsc b||_2 = %f\n",norm);
146
147 /* Create the ML AMG preconditioner. */
148
149 /* Parameter list that holds options for AMG preconditioner. */
150 Teuchos::ParameterList mlList;
151 /* Set recommended defaults for Poisson-like problems. */
152 ML_Epetra::SetDefaults("SA",mlList);
153 /* Specify how much information ML prints to screen.
154 0 is the minimum (no output), 10 is the maximum. */
155 mlList.set("ML output",10);
156 /* Set the fine grid smoother. PETSc will be much faster for any
157 smoother requiring row access, e.g., SOR. For any smoother whose
158 kernel is a matvec, Trilinos/PETSc performance should be comparable,
159 as Trilinos simply calls the PETSc matvec.
160
161 To use a PETSc smoother, create a KSP object, set the KSP type to
162 KSPRICHARDSON, and set the desired smoother as the KSP preconditioner.
163 It is important that you call KSPSetInitialGuessNonzero. Otherwise, the
164 post-smoother phase will incorrectly ignore the current approximate
165 solution. The KSP pointer must be cast to void* and passed to ML via
166 the parameter list.
167
168 You are responsible for freeing the KSP object.
169 */
170 ierr = PetscOptionsHasName(PETSC_NULL,"-petsc_smoother",&flg);CHKERRQ(ierr);
171 if (flg) {
172 ierr = KSPCreate(comm,&kspSmoother);CHKERRQ(ierr);
173 ierr = KSPSetOperators(kspSmoother,A,A);CHKERRQ(ierr);
174 ierr = KSPSetType(kspSmoother,KSPRICHARDSON);CHKERRQ(ierr);
175 ierr = KSPSetTolerances(kspSmoother, 1e-12, 1e-50, 1e7,1);
176 ierr = KSPSetInitialGuessNonzero(kspSmoother,PETSC_TRUE);CHKERRQ(ierr);
177 ierr = KSPGetPC(kspSmoother,&pc);CHKERRQ(ierr);
178 ierr = PCSetType(pc, PCSOR);CHKERRQ(ierr);
179 ierr = PCSORSetSymmetric(pc,SOR_LOCAL_SYMMETRIC_SWEEP);CHKERRQ(ierr);
180 ierr = PCSetFromOptions(pc);CHKERRQ(ierr);
181 ierr = KSPSetUp(kspSmoother);CHKERRQ(ierr);
182 mlList.set("smoother: type (level 0)","petsc");
183 mlList.set("smoother: petsc ksp (level 0)",(void*)kspSmoother);
184 } else {
185 mlList.set("smoother: type (level 0)","symmetric Gauss-Seidel");
186 }
187
188 /* how many fine grid pre- or post-smoothing sweeps to do */
189 mlList.set("smoother: sweeps (level 0)",2);
190
191 ML_Epetra::MultiLevelPreconditioner *Prec = new ML_Epetra::MultiLevelPreconditioner(epA,mlList);
192
193 /* Trilinos CG */
194 epu.PutScalar(0.0);
195 Epetra_LinearProblem Problem(&epA, &epu, &epb);
196 AztecOO solver(Problem);
197 solver.SetAztecOption(AZ_solver, AZ_cg);
198 solver.SetAztecOption(AZ_output, 1);
199 solver.SetAztecOption(AZ_conv, AZ_noscaled);
200 solver.SetPrecOperator(Prec);
201 solver.Iterate(30, 1e-12);
202
203 /* PETSc CG */
204 ierr = KSPCreate(PETSC_COMM_WORLD,&ksp);CHKERRQ(ierr);
205 ierr = KSPSetOperators(ksp,A,A);CHKERRQ(ierr);
206 ierr = KSPSetTolerances(ksp,1e-12,1.e-50,PETSC_DEFAULT,
207 PETSC_DEFAULT);CHKERRQ(ierr);
208 ierr = KSPSetType(ksp,KSPCG);CHKERRQ(ierr);
209
210 /* Wrap the ML preconditioner as a PETSc shell preconditioner. */
211 ierr = KSPGetPC(ksp,&pc);CHKERRQ(ierr);
212 ierr = PCSetType(pc,PCSHELL);CHKERRQ(ierr);
213 ierr = PCShellSetApply(pc,ShellApplyML);CHKERRQ(ierr);
214 ierr = PCShellSetContext(pc,(void*)Prec);CHKERRQ(ierr);
215 ierr = PCShellSetName(pc,"ML AMG");CHKERRQ(ierr);
216
217 ierr = KSPSetFromOptions(ksp);CHKERRQ(ierr);
218
219 ierr = KSPSolve(ksp,b,x);CHKERRQ(ierr);
220
221 ierr = KSPView(ksp,PETSC_VIEWER_STDOUT_WORLD);CHKERRQ(ierr);
222
223 ierr = VecAXPY(x,neg_one,u);CHKERRQ(ierr);
224 ierr = VecNorm(x,NORM_2,&norm);CHKERRQ(ierr);
225 ierr = KSPGetIterationNumber(ksp,&its);CHKERRQ(ierr);
226
227 ierr = PetscPrintf(PETSC_COMM_WORLD,"Norm of error %e iterations %D\n",
228 norm,its);CHKERRQ(ierr);
229
230 ierr = KSPDestroy(&ksp);CHKERRQ(ierr);
231 ierr = VecDestroy(&u);CHKERRQ(ierr); ierr = VecDestroy(&x);CHKERRQ(ierr);
232 ierr = VecDestroy(&b);CHKERRQ(ierr); ierr = MatDestroy(&A);CHKERRQ(ierr);
233
234 if (kspSmoother) {ierr = KSPDestroy(&kspSmoother);CHKERRQ(ierr);}
235 if (Prec) delete Prec;
236
237 ierr = PetscFinalize();CHKERRQ(ierr);
238 return 0;
239 } /*main*/
240
241 /* ***************************************************************** */
242
243 #if (PETSC_VERSION_MAJOR < 3) || (PETSC_VERSION_MAJOR == 3 && PETSC_VERSION_MINOR < 1)
244 PetscErrorCode ShellApplyML(void *ctx,Vec x,Vec y)
245 #else
246 PetscErrorCode ShellApplyML(PC pc,Vec x,Vec y)
247 {
248 PetscErrorCode ierr;
249 ML_Epetra::MultiLevelPreconditioner *mlp = 0;
250 void* ctx;
251
252 ierr = PCShellGetContext(pc,&ctx); CHKERRQ(ierr);
253 mlp = (ML_Epetra::MultiLevelPreconditioner*)ctx;
254 #endif
255
256 /* Wrap x and y as Epetra_Vectors. */
257 // NOTE: We should not be const casting xvals, but we do promise not to modify the entries.
258 const PetscScalar *xvals;
259 PetscScalar *nonconst_xvals, *yvals;
260 ierr = VecGetArrayRead(x,&xvals);CHKERRQ(ierr);
261 nonconst_xvals = const_cast<PetscScalar*>(xvals);
262 Epetra_Vector epx(View,mlp->OperatorDomainMap(),nonconst_xvals);
263 ierr = VecGetArray(y,&yvals);CHKERRQ(ierr);
264 Epetra_Vector epy(View,mlp->OperatorRangeMap(),yvals);
265
266 /* Apply ML. */
267 mlp->ApplyInverse(epx,epy);
268
269 /* Clean up and return. */
270 ierr = VecRestoreArrayRead(x,&xvals);CHKERRQ(ierr);
271 ierr = VecRestoreArray(y,&yvals);CHKERRQ(ierr);
272 return 0;
273 } /*ShellApplyML*/
274 #else
275
276 #include <stdlib.h>
277 #include <stdio.h>
278 #ifdef HAVE_MPI
279 #include "mpi.h"
280 #endif
281
282 int main(int argc, char *argv[])
283 {
284 #ifdef HAVE_MPI
285 MPI_Init(&argc,&argv);
286 #endif
287
288 printf("Please configure EpetraExt with:");
289 #if !defined(HAVE_PETSC)
290 printf("--enable-petsc");
291 #endif
292 #if !defined(HAVE_ML_EPETRA)
293 printf("--enable-epetra");
294 #endif
295 #if !defined(HAVE_ML_TEUCHOS)
296 printf("--enable-teuchos");
297 #endif
298 #if !defined(HAVE_ML_AZTECOO)
299 printf("--enable-aztecoo");
300 #endif
301
302 #ifdef HAVE_MPI
303 MPI_Finalize();
304 #endif
305
306 return(EXIT_SUCCESS);
307 }
308 #endif