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

 90: !  These variables are not currently used.
 91: !      PC          pc
 92: !      PCType      ptype
 93: !      double precision tol


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

 99:       external MyKSPMonitor,MyKSPConverged

101: ! - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
102: !                 Beginning of program
103: ! - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

105:       call PetscInitialize(PETSC_NULL_CHARACTER,ierr)
106:       m = 3
107:       n = 3
108:       one  = 1.0
109:       neg_one = -1.0
110:       ione    = 1
111:       call PetscOptionsGetInt(PETSC_NULL_CHARACTER,'-m',m,flg,ierr)
112:       call PetscOptionsGetInt(PETSC_NULL_CHARACTER,'-n',n,flg,ierr)
113:       call MPI_Comm_rank(PETSC_COMM_WORLD,rank,ierr)
114:       call MPI_Comm_size(PETSC_COMM_WORLD,size,ierr)

116: ! - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
117: !      Compute the matrix and right-hand-side vector that define
118: !      the linear system, Ax = b.
119: ! - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

121: !  Create parallel matrix, specifying only its global dimensions.
122: !  When using MatCreate(), the matrix format can be specified at
123: !  runtime. Also, the parallel partitioning of the matrix is
124: !  determined by PETSc at runtime.

126:       call MatCreate(PETSC_COMM_WORLD,A,ierr)
127:       call MatSetSizes(A,PETSC_DECIDE,PETSC_DECIDE,m*n,m*n,ierr)
128:       call MatSetFromOptions(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_CHARACTER,                    &
202:      &             "-random_exact_sol",flg,ierr)
203:       if (flg .eq. 1) then
204:          call PetscRandomCreate(PETSC_COMM_WORLD,RANDOM_DEFAULT,        &
205:      &                          rctx,ierr)
206:          call VecSetRandom(rctx,u,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_CHARACTER,                    &
216:      &             "-view_exact_sol",flg,ierr)
217:       if (flg .eq. 1) 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,DIFFERENT_NONZERO_PATTERN,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_DOUBLE_PRECISION,
251: !     &     PETSC_DEFAULT_DOUBLE_PRECISION,PETSC_DEFAULT_INTEGER,ierr)

253: !  Set user-defined monitoring routine if desired

255:       call PetscOptionsHasName(PETSC_NULL_CHARACTER,'-my_ksp_monitor',  &
256:      &                    flg,ierr)
257:       if (flg .eq. 1) then
258:         call KSPSetMonitor(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_CHARACTER,                    &
274:      &     '-my_ksp_convergence',flg,ierr)
275:       if (flg .eq. 1) then
276:         call KSPSetConvergenceTest(ksp,MyKSPConverged,                  &
277:      &          PETSC_NULL_OBJECT,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

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

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

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

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

320:       call PetscFinalize(ierr)
321:       end

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

336:       implicit none

338:  #include include/finclude/petsc.h
339:  #include include/finclude/petscvec.h
340:  #include include/finclude/petscksp.h

342:       KSP              ksp
343:       Vec              x
344:       PetscErrorCode ierr
345:       PetscInt n,dummy
346:       PetscMPIInt rank
347:       double precision rnorm

349: !  Build the solution vector

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

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

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

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

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

381:       implicit none

383:  #include include/finclude/petsc.h
384:  #include include/finclude/petscvec.h
385:  #include include/finclude/petscksp.h

387:       KSP              ksp
388:       PetscErrorCode ierr
389:       PetscInt n,dummy
390:       KSPConvergedReason flag
391:       double precision rnorm

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

400:       end