Actual source code: ex2f.F

petsc-master 2016-02-10
Report Typos and Errors
  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: !
  6: !/*T
  7: !  Concepts: KSP^basic parallel example
  8: !  Concepts: KSP^setting a user-defined monitoring routine
  9: !  Processors: n
 10: !T*/
 11: !
 12: ! -----------------------------------------------------------------------

 14:       program main
 15:       implicit none

 17: ! - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
 18: !                    Include files
 19: ! - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
 20: !
 21: !  This program uses CPP for preprocessing, as indicated by the use of
 22: !  PETSc include files in the directory petsc/include/petsc/finclude.  This
 23: !  convention enables use of the CPP preprocessor, which allows the use
 24: !  of the #include statements that define PETSc objects and variables.
 25: !
 26: !  Use of the conventional Fortran include statements is also supported
 27: !  In this case, the PETsc include files are located in the directory
 28: !  petsc/include/foldinclude.
 29: !
 30: !  Since one must be very careful to include each file no more than once
 31: !  in a Fortran routine, application programmers must exlicitly list
 32: !  each file needed for the various PETSc components within their
 33: !  program (unlike the C/C++ interface).
 34: !
 35: !  See the Fortran section of the PETSc users manual for details.
 36: !
 37: !  The following include statements are required for KSP Fortran programs:
 38: !     petscsys.h       - base PETSc routines
 39: !     petscvec.h    - vectors
 40: !     petscmat.h    - matrices
 41: !     petscpc.h     - preconditioners
 42: !     petscksp.h    - Krylov subspace methods
 43: !  Additional include statements may be needed if using additional
 44: !  PETSc routines in a Fortran program, e.g.,
 45: !     petscviewer.h - viewers
 46: !     petscis.h     - index sets
 47: !
 48: #include <petsc/finclude/petscsys.h>
 49: #include <petsc/finclude/petscvec.h>
 50: #include <petsc/finclude/petscmat.h>
 51: #include <petsc/finclude/petscpc.h>
 52: #include <petsc/finclude/petscksp.h>
 53: !
 54: ! - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
 55: !                   Variable declarations
 56: ! - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
 57: !
 58: !  Variables:
 59: !     ksp     - linear solver context
 60: !     ksp      - Krylov subspace method context
 61: !     pc       - preconditioner context
 62: !     x, b, u  - approx solution, right-hand-side, exact solution vectors
 63: !     A        - matrix that defines linear system
 64: !     its      - iterations for convergence
 65: !     norm     - norm of error in solution
 66: !     rctx     - random number generator context
 67: !
 68: !  Note that vectors are declared as PETSc "Vec" objects.  These vectors
 69: !  are mathematical objects that contain more than just an array of
 70: !  double precision numbers. I.e., vectors in PETSc are not just
 71: !        double precision x(*).
 72: !  However, local vector data can be easily accessed via VecGetArray().
 73: !  See the Fortran section of the PETSc users manual for details.
 74: !
 75:       PetscReal  norm
 76:       PetscInt  i,j,II,JJ,m,n,its
 77:       PetscInt  Istart,Iend,ione
 78:       PetscErrorCode ierr
 79:       PetscMPIInt     rank,size
 80:       PetscBool   flg
 81:       PetscScalar v,one,neg_one
 82:       Vec         x,b,u
 83:       Mat         A
 84:       KSP         ksp
 85:       PetscRandom rctx

 87: !  These variables are not currently used.
 88: !      PC          pc
 89: !      PCType      ptype
 90: !      PetscReal tol


 93: !  Note: Any user-defined Fortran routines (such as MyKSPMonitor)
 94: !  MUST be declared as external.

 96:       external MyKSPMonitor,MyKSPConverged

 98: ! - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
 99: !                 Beginning of program
100: ! - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

102:       call PetscInitialize(PETSC_NULL_CHARACTER,ierr)
103:       m = 3
104:       n = 3
105:       one  = 1.0
106:       neg_one = -1.0
107:       ione    = 1
108:       call PetscOptionsGetInt(PETSC_NULL_OBJECT,PETSC_NULL_CHARACTER,    &
109:      &                        '-m',m,flg,ierr)
110:       call PetscOptionsGetInt(PETSC_NULL_OBJECT,PETSC_NULL_CHARACTER,    &
111:      &                        '-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,A,ierr)
126:       call MatSetSizes(A,PETSC_DECIDE,PETSC_DECIDE,m*n,m*n,ierr)
127:       call MatSetFromOptions(A,ierr)
128:       call MatSetUp(A,ierr)

130: !  Currently, all PETSc parallel matrix formats are partitioned by
131: !  contiguous chunks of rows across the processors.  Determine which
132: !  rows of the matrix are locally owned.

134:       call MatGetOwnershipRange(A,Istart,Iend,ierr)

136: !  Set matrix elements for the 2-D, five-point stencil in parallel.
137: !   - Each processor needs to insert only elements that it owns
138: !     locally (but any non-local elements will be sent to the
139: !     appropriate processor during matrix assembly).
140: !   - Always specify global row and columns of matrix entries.
141: !   - Note that MatSetValues() uses 0-based row and column numbers
142: !     in Fortran as well as in C.

144: !     Note: this uses the less common natural ordering that orders first
145: !     all the unknowns for x = h then for x = 2h etc; Hence you see JH = II +- n
146: !     instead of JJ = II +- m as you might expect. The more standard ordering
147: !     would first do all variables for y = h, then y = 2h etc.

149:       do 10, II=Istart,Iend-1
150:         v = -1.0
151:         i = II/n
152:         j = II - i*n
153:         if (i.gt.0) then
154:           JJ = II - n
155:           call MatSetValues(A,ione,II,ione,JJ,v,INSERT_VALUES,ierr)
156:         endif
157:         if (i.lt.m-1) then
158:           JJ = II + n
159:           call MatSetValues(A,ione,II,ione,JJ,v,INSERT_VALUES,ierr)
160:         endif
161:         if (j.gt.0) then
162:           JJ = II - 1
163:           call MatSetValues(A,ione,II,ione,JJ,v,INSERT_VALUES,ierr)
164:         endif
165:         if (j.lt.n-1) then
166:           JJ = II + 1
167:           call MatSetValues(A,ione,II,ione,JJ,v,INSERT_VALUES,ierr)
168:         endif
169:         v = 4.0
170:         call  MatSetValues(A,ione,II,ione,II,v,INSERT_VALUES,ierr)
171:  10   continue

173: !  Assemble matrix, using the 2-step process:
174: !       MatAssemblyBegin(), MatAssemblyEnd()
175: !  Computations can be done while messages are in transition,
176: !  by placing code between these two statements.

178:       call MatAssemblyBegin(A,MAT_FINAL_ASSEMBLY,ierr)
179:       call MatAssemblyEnd(A,MAT_FINAL_ASSEMBLY,ierr)

181: !  Create parallel vectors.
182: !   - Here, the parallel partitioning of the vector is determined by
183: !     PETSc at runtime.  We could also specify the local dimensions
184: !     if desired -- or use the more general routine VecCreate().
185: !   - When solving a linear system, the vectors and matrices MUST
186: !     be partitioned accordingly.  PETSc automatically generates
187: !     appropriately partitioned matrices and vectors when MatCreate()
188: !     and VecCreate() are used with the same communicator.
189: !   - Note: We form 1 vector from scratch and then duplicate as needed.

191:       call VecCreateMPI(PETSC_COMM_WORLD,PETSC_DECIDE,m*n,u,ierr)
192:       call VecSetFromOptions(u,ierr)
193:       call VecDuplicate(u,b,ierr)
194:       call VecDuplicate(b,x,ierr)

196: !  Set exact solution; then compute right-hand-side vector.
197: !  By default we use an exact solution of a vector with all
198: !  elements of 1.0;  Alternatively, using the runtime option
199: !  -random_sol forms a solution vector with random components.

201:       call PetscOptionsHasName(PETSC_NULL_OBJECT,PETSC_NULL_CHARACTER,                    &
202:      &             '-random_exact_sol',flg,ierr)
203:       if (flg) then
204:          call PetscRandomCreate(PETSC_COMM_WORLD,rctx,ierr)
205:          call PetscRandomSetFromOptions(rctx,ierr)
206:          call VecSetRandom(u,rctx,ierr)
207:          call PetscRandomDestroy(rctx,ierr)
208:       else
209:          call VecSet(u,one,ierr)
210:       endif
211:       call MatMult(A,u,b,ierr)

213: !  View the exact solution vector if desired

215:       call PetscOptionsHasName(PETSC_NULL_OBJECT,PETSC_NULL_CHARACTER,                    &
216:      &             '-view_exact_sol',flg,ierr)
217:       if (flg) then
218:          call VecView(u,PETSC_VIEWER_STDOUT_WORLD,ierr)
219:       endif

221: ! - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
222: !         Create the linear solver and set various options
223: ! - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

225: !  Create linear solver context

227:       call KSPCreate(PETSC_COMM_WORLD,ksp,ierr)

229: !  Set operators. Here the matrix that defines the linear system
230: !  also serves as the preconditioning matrix.

232:       call KSPSetOperators(ksp,A,A,ierr)

234: !  Set linear solver defaults for this problem (optional).
235: !   - By extracting the KSP and PC contexts from the KSP context,
236: !     we can then directly directly call any KSP and PC routines
237: !     to set various options.
238: !   - The following four statements are optional; all of these
239: !     parameters could alternatively be specified at runtime via
240: !     KSPSetFromOptions(). All of these defaults can be
241: !     overridden at runtime, as indicated below.

243: !     We comment out this section of code since the Jacobi
244: !     preconditioner is not a good general default.

246: !      call KSPGetPC(ksp,pc,ierr)
247: !      ptype = PCJACOBI
248: !      call PCSetType(pc,ptype,ierr)
249: !      tol = 1.e-7
250: !      call KSPSetTolerances(ksp,tol,PETSC_DEFAULT_REAL,
251: !     &     PETSC_DEFAULT_REAL,PETSC_DEFAULT_INTEGER,ierr)

253: !  Set user-defined monitoring routine if desired

255:       call PetscOptionsHasName(PETSC_NULL_OBJECT,PETSC_NULL_CHARACTER,       &
256:      &                         '-my_ksp_monitor',flg,ierr)
257:       if (flg) then
258:         call KSPMonitorSet(ksp,MyKSPMonitor,PETSC_NULL_OBJECT,          &
259:      &                     PETSC_NULL_FUNCTION,ierr)
260:       endif


263: !  Set runtime options, e.g.,
264: !      -ksp_type <type> -pc_type <type> -ksp_monitor -ksp_rtol <rtol>
265: !  These options will override those specified above as long as
266: !  KSPSetFromOptions() is called _after_ any other customization
267: !  routines.

269:       call KSPSetFromOptions(ksp,ierr)

271: !  Set convergence test routine if desired

273:       call PetscOptionsHasName(PETSC_NULL_OBJECT,PETSC_NULL_CHARACTER,       &
274:      &                         '-my_ksp_convergence',flg,ierr)
275:       if (flg) then
276:         call KSPSetConvergenceTest(ksp,MyKSPConverged,                  &
277:      &          PETSC_NULL_OBJECT,PETSC_NULL_FUNCTION,ierr)
278:       endif
279: !
280: ! - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
281: !                      Solve the linear system
282: ! - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

284:       call KSPSolve(ksp,b,x,ierr)

286: ! - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
287: !                     Check solution and clean up
288: ! - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

290: !  Check the error
291:       call VecAXPY(x,neg_one,u,ierr)
292:       call VecNorm(x,NORM_2,norm,ierr)
293:       call KSPGetIterationNumber(ksp,its,ierr)
294:       if (rank .eq. 0) then
295:         if (norm .gt. 1.e-12) then
296:            write(6,100) norm,its
297:         else
298:            write(6,110) its
299:         endif
300:       endif
301:   100 format('Norm of error ',e11.4,' iterations ',i5)
302:   110 format('Norm of error < 1.e-12 iterations ',i5)

304: !  Free work space.  All PETSc objects should be destroyed when they
305: !  are no longer needed.

307:       call KSPDestroy(ksp,ierr)
308:       call VecDestroy(u,ierr)
309:       call VecDestroy(x,ierr)
310:       call VecDestroy(b,ierr)
311:       call MatDestroy(A,ierr)

313: !  Always call PetscFinalize() before exiting a program.  This routine
314: !    - finalizes the PETSc libraries as well as MPI
315: !    - provides summary and diagnostic information if certain runtime
316: !      options are chosen (e.g., -log_summary).  See PetscFinalize()
317: !      manpage for more information.

319:       call PetscFinalize(ierr)
320:       end

322: ! --------------------------------------------------------------
323: !
324: !  MyKSPMonitor - This is a user-defined routine for monitoring
325: !  the KSP iterative solvers.
326: !
327: !  Input Parameters:
328: !    ksp   - iterative context
329: !    n     - iteration number
330: !    rnorm - 2-norm (preconditioned) residual value (may be estimated)
331: !    dummy - optional user-defined monitor context (unused here)
332: !
333:       subroutine MyKSPMonitor(ksp,n,rnorm,dummy,ierr)

335:       implicit none

337: #include <petsc/finclude/petscsys.h>
338: #include <petsc/finclude/petscvec.h>
339: #include <petsc/finclude/petscksp.h>

341:       KSP              ksp
342:       Vec              x
343:       PetscErrorCode ierr
344:       PetscInt n,dummy
345:       PetscMPIInt rank
346:       PetscReal rnorm

348: !  Build the solution vector

350:       call KSPBuildSolution(ksp,PETSC_NULL_OBJECT,x,ierr)

352: !  Write the solution vector and residual norm to stdout
353: !   - Note that the parallel viewer PETSC_VIEWER_STDOUT_WORLD
354: !     handles data from multiple processors so that the
355: !     output is not jumbled.

357:       call MPI_Comm_rank(PETSC_COMM_WORLD,rank,ierr)
358:       if (rank .eq. 0) write(6,100) n
359:       call VecView(x,PETSC_VIEWER_STDOUT_WORLD,ierr)
360:       if (rank .eq. 0) write(6,200) n,rnorm

362:  100  format('iteration ',i5,' solution vector:')
363:  200  format('iteration ',i5,' residual norm ',e11.4)
364:       0
365:       end

367: ! --------------------------------------------------------------
368: !
369: !  MyKSPConverged - This is a user-defined routine for testing
370: !  convergence of the KSP iterative solvers.
371: !
372: !  Input Parameters:
373: !    ksp   - iterative context
374: !    n     - iteration number
375: !    rnorm - 2-norm (preconditioned) residual value (may be estimated)
376: !    dummy - optional user-defined monitor context (unused here)
377: !
378:       subroutine MyKSPConverged(ksp,n,rnorm,flag,dummy,ierr)

380:       implicit none

382: #include <petsc/finclude/petscsys.h>
383: #include <petsc/finclude/petscvec.h>
384: #include <petsc/finclude/petscksp.h>

386:       KSP              ksp
387:       PetscErrorCode ierr
388:       PetscInt n,dummy
389:       KSPConvergedReason flag
390:       PetscReal rnorm

392:       if (rnorm .le. .05) then
393:         flag = 1
394:       else
395:         flag = 0
396:       endif
397:       0

399:       end