Actual source code: ex2f.F
1: !
2: ! Description: Solves a linear system in parallel with KSP (Fortran code).
3: ! Also shows how to set a user-defined monitoring routine.
4: !
5: ! Program usage: mpirun -np <procs> ex2f [-help] [all PETSc options]
6: !
7: !/*T
8: ! Concepts: KSP^basic parallel example
9: ! Concepts: KSP^setting a user-defined monitoring routine
10: ! Processors: n
11: !T*/
12: !
13: ! -----------------------------------------------------------------------
15: program main
16: implicit none
18: ! - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
19: ! Include files
20: ! - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
21: !
22: ! This program uses CPP for preprocessing, as indicated by the use of
23: ! PETSc include files in the directory petsc/include/finclude. This
24: ! convention enables use of the CPP preprocessor, which allows the use
25: ! of the #include statements that define PETSc objects and variables.
26: !
27: ! Use of the conventional Fortran include statements is also supported
28: ! In this case, the PETsc include files are located in the directory
29: ! petsc/include/foldinclude.
30: !
31: ! Since one must be very careful to include each file no more than once
32: ! in a Fortran routine, application programmers must exlicitly list
33: ! each file needed for the various PETSc components within their
34: ! program (unlike the C/C++ interface).
35: !
36: ! See the Fortran section of the PETSc users manual for details.
37: !
38: ! The following include statements are required for KSP Fortran programs:
39: ! petsc.h - base PETSc routines
40: ! petscvec.h - vectors
41: ! petscmat.h - matrices
42: ! petscpc.h - preconditioners
43: ! petscksp.h - Krylov subspace methods
44: ! Include the following to use PETSc random numbers:
45: ! petscsys.h - system routines
46: ! Additional include statements may be needed if using additional
47: ! PETSc routines in a Fortran program, e.g.,
48: ! petscviewer.h - viewers
49: ! petscis.h - index sets
50: !
51: #include include/finclude/petsc.h
52: #include include/finclude/petscvec.h
53: #include include/finclude/petscmat.h
54: #include include/finclude/petscpc.h
55: #include include/finclude/petscksp.h
56: #include include/finclude/petscsys.h
57: !
58: ! - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
59: ! Variable declarations
60: ! - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
61: !
62: ! Variables:
63: ! ksp - linear solver context
64: ! ksp - Krylov subspace method context
65: ! pc - preconditioner context
66: ! x, b, u - approx solution, right-hand-side, exact solution vectors
67: ! A - matrix that defines linear system
68: ! its - iterations for convergence
69: ! norm - norm of error in solution
70: ! rctx - random number generator context
71: !
72: ! Note that vectors are declared as PETSc "Vec" objects. These vectors
73: ! are mathematical objects that contain more than just an array of
74: ! double precision numbers. I.e., vectors in PETSc are not just
75: ! double precision x(*).
76: ! However, local vector data can be easily accessed via VecGetArray().
77: ! See the Fortran section of the PETSc users manual for details.
78: !
79: double precision norm
80: PetscInt i,j,II,JJ,m,n,its,Istart,Iend,ione
81: PetscErrorCode ierr
82: PetscMPIInt rank,size
83: PetscTruth flg
84: PetscScalar v,one,neg_one
85: Vec x,b,u
86: Mat A
87: KSP ksp
88: PetscRandom rctx
89: ! These variables are not currently used.
90: ! PC pc
91: ! PCType ptype
92: ! double precision tol
95: ! Note: Any user-defined Fortran routines (such as MyKSPMonitor)
96: ! MUST be declared as external.
98: external MyKSPMonitor,MyKSPConverged
100: ! - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
101: ! Beginning of program
102: ! - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
104: call PetscInitialize(PETSC_NULL_CHARACTER,ierr)
105: m = 3
106: n = 3
107: one = 1.0
108: neg_one = -1.0
109: ione = 1
110: call PetscOptionsGetInt(PETSC_NULL_CHARACTER,'-m',m,flg,ierr)
111: call PetscOptionsGetInt(PETSC_NULL_CHARACTER,'-n',n,flg,ierr)
112: call MPI_Comm_rank(PETSC_COMM_WORLD,rank,ierr)
113: call MPI_Comm_size(PETSC_COMM_WORLD,size,ierr)
115: ! - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
116: ! Compute the matrix and right-hand-side vector that define
117: ! the linear system, Ax = b.
118: ! - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
120: ! Create parallel matrix, specifying only its global dimensions.
121: ! When using MatCreate(), the matrix format can be specified at
122: ! runtime. Also, the parallel partitioning of the matrix is
123: ! determined by PETSc at runtime.
125: call MatCreate(PETSC_COMM_WORLD,PETSC_DECIDE,PETSC_DECIDE,m*n, &
126: & m*n,A,ierr)
127: call MatSetFromOptions(A,ierr)
129: ! Currently, all PETSc parallel matrix formats are partitioned by
130: ! contiguous chunks of rows across the processors. Determine which
131: ! rows of the matrix are locally owned.
133: call MatGetOwnershipRange(A,Istart,Iend,ierr)
135: ! Set matrix elements for the 2-D, five-point stencil in parallel.
136: ! - Each processor needs to insert only elements that it owns
137: ! locally (but any non-local elements will be sent to the
138: ! appropriate processor during matrix assembly).
139: ! - Always specify global row and columns of matrix entries.
140: ! - Note that MatSetValues() uses 0-based row and column numbers
141: ! in Fortran as well as in C.
143: ! Note: this uses the less common natural ordering that orders first
144: ! all the unknowns for x = h then for x = 2h etc; Hence you see JH = II +- n
145: ! instead of JJ = II +- m as you might expect. The more standard ordering
146: ! would first do all variables for y = h, then y = 2h etc.
148: do 10, II=Istart,Iend-1
149: v = -1.0
150: i = II/n
151: j = II - i*n
152: if (i.gt.0) then
153: JJ = II - n
154: call MatSetValues(A,ione,II,ione,JJ,v,INSERT_VALUES,ierr)
155: endif
156: if (i.lt.m-1) then
157: JJ = II + n
158: call MatSetValues(A,ione,II,ione,JJ,v,INSERT_VALUES,ierr)
159: endif
160: if (j.gt.0) then
161: JJ = II - 1
162: call MatSetValues(A,ione,II,ione,JJ,v,INSERT_VALUES,ierr)
163: endif
164: if (j.lt.n-1) then
165: JJ = II + 1
166: call MatSetValues(A,ione,II,ione,JJ,v,INSERT_VALUES,ierr)
167: endif
168: v = 4.0
169: call MatSetValues(A,ione,II,ione,II,v,INSERT_VALUES,ierr)
170: 10 continue
172: ! Assemble matrix, using the 2-step process:
173: ! MatAssemblyBegin(), MatAssemblyEnd()
174: ! Computations can be done while messages are in transition,
175: ! by placing code between these two statements.
177: call MatAssemblyBegin(A,MAT_FINAL_ASSEMBLY,ierr)
178: call MatAssemblyEnd(A,MAT_FINAL_ASSEMBLY,ierr)
180: ! Create parallel vectors.
181: ! - Here, the parallel partitioning of the vector is determined by
182: ! PETSc at runtime. We could also specify the local dimensions
183: ! if desired -- or use the more general routine VecCreate().
184: ! - When solving a linear system, the vectors and matrices MUST
185: ! be partitioned accordingly. PETSc automatically generates
186: ! appropriately partitioned matrices and vectors when MatCreate()
187: ! and VecCreate() are used with the same communicator.
188: ! - Note: We form 1 vector from scratch and then duplicate as needed.
190: call VecCreateMPI(PETSC_COMM_WORLD,PETSC_DECIDE,m*n,u,ierr)
191: call VecSetFromOptions(u,ierr)
192: call VecDuplicate(u,b,ierr)
193: call VecDuplicate(b,x,ierr)
195: ! Set exact solution; then compute right-hand-side vector.
196: ! By default we use an exact solution of a vector with all
197: ! elements of 1.0; Alternatively, using the runtime option
198: ! -random_sol forms a solution vector with random components.
200: call PetscOptionsHasName(PETSC_NULL_CHARACTER, &
201: & "-random_exact_sol",flg,ierr)
202: if (flg .eq. 1) then
203: call PetscRandomCreate(PETSC_COMM_WORLD,RANDOM_DEFAULT, &
204: & rctx,ierr)
205: call VecSetRandom(rctx,u,ierr)
206: call PetscRandomDestroy(rctx,ierr)
207: else
208: call VecSet(one,u,ierr)
209: endif
210: call MatMult(A,u,b,ierr)
212: ! View the exact solution vector if desired
214: call PetscOptionsHasName(PETSC_NULL_CHARACTER, &
215: & "-view_exact_sol",flg,ierr)
216: if (flg .eq. 1) then
217: call VecView(u,PETSC_VIEWER_STDOUT_WORLD,ierr)
218: endif
219: ! - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
220: ! Create the linear solver and set various options
221: ! - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
223: ! Create linear solver context
225: call KSPCreate(PETSC_COMM_WORLD,ksp,ierr)
227: ! Set operators. Here the matrix that defines the linear system
228: ! also serves as the preconditioning matrix.
230: call KSPSetOperators(ksp,A,A,DIFFERENT_NONZERO_PATTERN,ierr)
232: ! Set linear solver defaults for this problem (optional).
233: ! - By extracting the KSP and PC contexts from the KSP context,
234: ! we can then directly directly call any KSP and PC routines
235: ! to set various options.
236: ! - The following four statements are optional; all of these
237: ! parameters could alternatively be specified at runtime via
238: ! KSPSetFromOptions(). All of these defaults can be
239: ! overridden at runtime, as indicated below.
241: ! We comment out this section of code since the Jacobi
242: ! preconditioner is not a good general default.
244: ! call KSPGetPC(ksp,pc,ierr)
245: ! ptype = PCJACOBI
246: ! call PCSetType(pc,ptype,ierr)
247: ! tol = 1.e-7
248: ! call KSPSetTolerances(ksp,tol,PETSC_DEFAULT_DOUBLE_PRECISION,
249: ! & PETSC_DEFAULT_DOUBLE_PRECISION,PETSC_DEFAULT_INTEGER,ierr)
251: ! Set user-defined monitoring routine if desired
253: call PetscOptionsHasName(PETSC_NULL_CHARACTER,'-my_ksp_monitor', &
254: & flg,ierr)
255: if (flg .eq. 1) then
256: call KSPSetMonitor(ksp,MyKSPMonitor,PETSC_NULL_OBJECT, &
257: & PETSC_NULL_FUNCTION,ierr)
258: endif
261: ! Set runtime options, e.g.,
262: ! -ksp_type <type> -pc_type <type> -ksp_monitor -ksp_rtol <rtol>
263: ! These options will override those specified above as long as
264: ! KSPSetFromOptions() is called _after_ any other customization
265: ! routines.
267: call KSPSetFromOptions(ksp,ierr)
269: ! Set convergence test routine if desired
271: call PetscOptionsHasName(PETSC_NULL_CHARACTER, &
272: & '-my_ksp_convergence',flg,ierr)
273: if (flg .eq. 1) then
274: call KSPSetConvergenceTest(ksp,MyKSPConverged, &
275: & PETSC_NULL_OBJECT,ierr)
276: endif
277: !
278: ! - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
279: ! Solve the linear system
280: ! - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
282: call KSPSolve(ksp,b,x,ierr)
284: ! - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
285: ! Check solution and clean up
286: ! - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
288: ! Check the error
290: call VecAXPY(neg_one,u,x,ierr)
291: call VecNorm(x,NORM_2,norm,ierr)
292: call KSPGetIterationNumber(ksp,its,ierr)
293: if (rank .eq. 0) then
294: if (norm .gt. 1.e-12) then
295: write(6,100) norm,its
296: else
297: write(6,110) its
298: endif
299: endif
300: 100 format('Norm of error ',e10.4,' iterations ',i5)
301: 110 format('Norm of error < 1.e-12,iterations ',i5)
303: ! Free work space. All PETSc objects should be destroyed when they
304: ! are no longer needed.
306: call KSPDestroy(ksp,ierr)
307: call VecDestroy(u,ierr)
308: call VecDestroy(x,ierr)
309: call VecDestroy(b,ierr)
310: call MatDestroy(A,ierr)
312: ! Always call PetscFinalize() before exiting a program. This routine
313: ! - finalizes the PETSc libraries as well as MPI
314: ! - provides summary and diagnostic information if certain runtime
315: ! options are chosen (e.g., -log_summary). See PetscFinalize()
316: ! manpage for more information.
318: call PetscFinalize(ierr)
319: end
320: ! --------------------------------------------------------------
321: !
322: ! MyKSPMonitor - This is a user-defined routine for monitoring
323: ! the KSP iterative solvers.
324: !
325: ! Input Parameters:
326: ! ksp - iterative context
327: ! n - iteration number
328: ! rnorm - 2-norm (preconditioned) residual value (may be estimated)
329: ! dummy - optional user-defined monitor context (unused here)
330: !
331: subroutine MyKSPMonitor(ksp,n,rnorm,dummy,ierr)
333: implicit none
335: #include include/finclude/petsc.h
336: #include include/finclude/petscvec.h
337: #include include/finclude/petscksp.h
339: KSP ksp
340: Vec x
341: PetscErrorCode ierr
342: PetscInt n,dummy
343: PetscMPIInt rank
344: double precision rnorm
346: ! Build the solution vector
348: call KSPBuildSolution(ksp,PETSC_NULL_OBJECT,x,ierr)
350: ! Write the solution vector and residual norm to stdout
351: ! - Note that the parallel viewer PETSC_VIEWER_STDOUT_WORLD
352: ! handles data from multiple processors so that the
353: ! output is not jumbled.
355: call MPI_Comm_rank(PETSC_COMM_WORLD,rank,ierr)
356: if (rank .eq. 0) write(6,100) n
357: call VecView(x,PETSC_VIEWER_STDOUT_WORLD,ierr)
358: if (rank .eq. 0) write(6,200) n,rnorm
360: 100 format('iteration ',i5,' solution vector:')
361: 200 format('iteration ',i5,' residual norm ',e10.4)
362: 0
363: end
365: ! --------------------------------------------------------------
366: !
367: ! MyKSPConverged - This is a user-defined routine for testing
368: ! convergence of the KSP iterative solvers.
369: !
370: ! Input Parameters:
371: ! ksp - iterative context
372: ! n - iteration number
373: ! rnorm - 2-norm (preconditioned) residual value (may be estimated)
374: ! dummy - optional user-defined monitor context (unused here)
375: !
376: subroutine MyKSPConverged(ksp,n,rnorm,flag,dummy,ierr)
378: implicit none
380: #include include/finclude/petsc.h
381: #include include/finclude/petscvec.h
382: #include include/finclude/petscksp.h
384: KSP ksp
385: PetscErrorCode ierr
386: PetscInt n,dummy
387: KSPConvergedReason flag
388: double precision rnorm
390: if (rnorm .le. .05) then
391: flag = 1
392: else
393: flag = 0
394: endif
395: 0
397: end