Actual source code: ex13f90.F

petsc-3.3-p7 2013-05-11
  1: !
  2: !
  3: !/*T
  4: !   Concepts: KSP^basic sequential example
  5: !   Concepts: KSP^Laplacian, 2d
  6: !   Concepts: Laplacian, 2d
  7: !   Processors: 1
  8: !T*/
  9: ! -----------------------------------------------------------------------

 11:       program main
 12:       implicit none

 14: ! - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
 15: !                    Include files
 16: ! - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
 17: !
 18: !  The following include statements are required for KSP Fortran programs:
 19: !     petscsys.h  - base PETSc routines
 20: !     petscvec.h    - vectors
 21: !     petscmat.h    - matrices
 22: !     petscksp.h    - Krylov subspace methods
 23: !     petscpc.h     - preconditioners
 24: !
 25: #include <finclude/petscsys.h>
 26: #include <finclude/petscvec.h>
 27: #include <finclude/petscmat.h>
 28: #include <finclude/petscksp.h>
 29: #include <finclude/petscpc.h>

 31: !    User-defined context that contains all the data structures used
 32: !    in the linear solution process.

 34: !   Vec    x,b      /* solution vector, right hand side vector and work vector */
 35: !   Mat    A        /* sparse matrix */
 36: !   KSP   ksp     /* linear solver context */
 37: !   int    m,n      /* grid dimensions */
 38: !
 39: !   Since we cannot store Scalars and integers in the same context,
 40: !   we store the integers/pointers in the user-defined context, and
 41: !   the scalar values are carried in the common block.
 42: !   The scalar values in this simplistic example could easily
 43: !   be recalculated in each routine, where they are needed.
 44: !
 45: !   Scalar hx2,hy2  /* 1/(m+1)*(m+1) and 1/(n+1)*(n+1) */

 47: !  Note: Any user-defined Fortran routines MUST be declared as external.

 49:       external UserInitializeLinearSolver
 50:       external UserFinalizeLinearSolver
 51:       external UserDoLinearSolver

 53: ! - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
 54: !                   Variable declarations
 55: ! - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

 57:       PetscScalar  hx,hy,x,y
 58:       PetscFortranAddr userctx(6)
 59:       PetscErrorCode ierr
 60:       PetscInt m,n,t,tmax,i,j
 61:       PetscBool  flg
 62:       PetscMPIInt size,rank
 63:       PetscReal  enorm
 64:       PetscScalar cnorm
 65:       PetscScalar,ALLOCATABLE :: userx(:,:)
 66:       PetscScalar,ALLOCATABLE :: userb(:,:)
 67:       PetscScalar,ALLOCATABLE :: solution(:,:)
 68:       PetscScalar,ALLOCATABLE :: rho(:,:)

 70:       double precision hx2,hy2
 71:       common /param/ hx2,hy2

 73:       tmax = 2
 74:       m = 6
 75:       n = 7

 77: ! - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
 78: !                 Beginning of program
 79: ! - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

 81:       call PetscInitialize(PETSC_NULL_CHARACTER,ierr)
 82:       call MPI_Comm_size(PETSC_COMM_WORLD,size,ierr)
 83:       if (size .ne. 1) then
 84:          call MPI_Comm_rank(PETSC_COMM_WORLD,rank,ierr)
 85:          if (rank .eq. 0) then
 86:             write(6,*) 'This is a uniprocessor example only!'
 87:          endif
 88:          SETERRQ(PETSC_COMM_WORLD,1,' ',ierr)
 89:       endif

 91: !  The next two lines are for testing only; these allow the user to
 92: !  decide the grid size at runtime.

 94:       call PetscOptionsGetInt(PETSC_NULL_CHARACTER,'-m',m,flg,ierr)
 95:       call PetscOptionsGetInt(PETSC_NULL_CHARACTER,'-n',n,flg,ierr)

 97: !  Create the empty sparse matrix and linear solver data structures

 99:       call UserInitializeLinearSolver(m,n,userctx,ierr)

101: !  Allocate arrays to hold the solution to the linear system.  This
102: !  approach is not normally done in PETSc programs, but in this case,
103: !  since we are calling these routines from a non-PETSc program, we
104: !  would like to reuse the data structures from another code. So in
105: !  the context of a larger application these would be provided by
106: !  other (non-PETSc) parts of the application code.

108:       ALLOCATE (userx(m,n),userb(m,n),solution(m,n))

110: !  Allocate an array to hold the coefficients in the elliptic operator

112:        ALLOCATE (rho(m,n))

114: !  Fill up the array rho[] with the function rho(x,y) = x; fill the
115: !  right-hand-side b[] and the solution with a known problem for testing.

117:       hx = 1.0/(m+1)
118:       hy = 1.0/(n+1)
119:       y  = hy
120:       do 20 j=1,n
121:          x = hx
122:          do 10 i=1,m
123:             rho(i,j)      = x
124:             solution(i,j) = sin(2.*PETSC_PI*x)*sin(2.*PETSC_PI*y)
125:             userb(i,j)    = -2.*PETSC_PI*cos(2.*PETSC_PI*x)*              &
126:      &                sin(2.*PETSC_PI*y) +                                &
127:      &                8*PETSC_PI*PETSC_PI*x*                              &
128:      &                sin(2.*PETSC_PI*x)*sin(2.*PETSC_PI*y)
129:            x = x + hx
130:  10      continue
131:          y = y + hy
132:  20   continue

134: !  Loop over a bunch of timesteps, setting up and solver the linear
135: !  system for each time-step.
136: !  Note that this loop is somewhat artificial. It is intended to
137: !  demonstrate how one may reuse the linear solvers in each time-step.

139:       do 100 t=1,tmax
140:          call UserDoLinearSolver(rho,userctx,userb,userx,ierr)

142: !        Compute error: Note that this could (and usually should) all be done
143: !        using the PETSc vector operations. Here we demonstrate using more
144: !        standard programming practices to show how they may be mixed with
145: !        PETSc.
146:          cnorm = 0.0
147:          do 90 j=1,n
148:             do 80 i=1,m
149:                cnorm = cnorm +                                           &
150:      &    PetscConj(solution(i,j)-userx(i,j))*                                            &
151:      &                             (solution(i,j)-userx(i,j))
152:  80         continue
153:  90      continue
154:          enorm =  PetscRealPart(cnorm*hx*hy)
155:          write(6,115) m,n,enorm
156:  115     format ('m = ',I2,' n = ',I2,' error norm = ',1PE11.4)
157:  100  continue

159: !  We are finished solving linear systems, so we clean up the
160: !  data structures.

162:       DEALLOCATE (userx,userb,solution,rho)

164:       call UserFinalizeLinearSolver(userctx,ierr)
165:       call PetscFinalize(ierr)
166:       end

168: ! ----------------------------------------------------------------
169:       subroutine UserInitializeLinearSolver(m,n,userctx,ierr)

171:       implicit none

173: #include <finclude/petscsys.h>
174: #include <finclude/petscvec.h>
175: #include <finclude/petscmat.h>
176: #include <finclude/petscksp.h>
177: #include <finclude/petscpc.h>

179:       PetscInt m,n
180:       PetscErrorCode ierr
181:       PetscFortranAddr userctx(*)

183:       common /param/ hx2,hy2
184:       double precision hx2,hy2

186: !  Local variable declararions
187:       Mat     A
188:       Vec     b,x
189:       KSP    ksp
190:       PetscInt Ntot


193: !  Here we assume use of a grid of size m x n, with all points on the
194: !  interior of the domain, i.e., we do not include the points corresponding
195: !  to homogeneous Dirichlet boundary conditions.  We assume that the domain
196: !  is [0,1]x[0,1].

198:       hx2 = (m+1)*(m+1)
199:       hy2 = (n+1)*(n+1)
200:       Ntot = m*n

202: !  Create the sparse matrix. Preallocate 5 nonzeros per row.

204:       call MatCreateSeqAIJ(PETSC_COMM_SELF,Ntot,Ntot,5,                  &
205:      &     PETSC_NULL_INTEGER,A,ierr)
206: !
207: !  Create vectors. Here we create vectors with no memory allocated.
208: !  This way, we can use the data structures already in the program
209: !  by using VecPlaceArray() subroutine at a later stage.
210: !
211:       call VecCreateSeqWithArray(PETSC_COMM_SELF,1,Ntot,                  &
212:      &     PETSC_NULL_SCALAR,b,ierr)
213:       call VecDuplicate(b,x,ierr)

215: !  Create linear solver context. This will be used repeatedly for all
216: !  the linear solves needed.

218:       call KSPCreate(PETSC_COMM_SELF,ksp,ierr)

220:       userctx(1) = x
221:       userctx(2) = b
222:       userctx(3) = A
223:       userctx(4) = ksp
224:       userctx(5) = m
225:       userctx(6) = n

227:       return
228:       end
229: ! -----------------------------------------------------------------------

231: !   Solves -div (rho grad psi) = F using finite differences.
232: !   rho is a 2-dimensional array of size m by n, stored in Fortran
233: !   style by columns. userb is a standard one-dimensional array.

235:       subroutine UserDoLinearSolver(rho,userctx,userb,userx,ierr)

237:       implicit none

239: #include <finclude/petscsys.h>
240: #include <finclude/petscvec.h>
241: #include <finclude/petscmat.h>
242: #include <finclude/petscksp.h>
243: #include <finclude/petscpc.h>

245:       PetscErrorCode ierr
246:       PetscFortranAddr userctx(*)
247:       PetscScalar rho(*),userb(*),userx(*)


250:       common /param/ hx2,hy2
251:       double precision hx2,hy2

253:       PC   pc
254:       KSP ksp
255:       Vec  b,x
256:       Mat  A
257:       PetscInt m,n,one
258:       PetscInt i,j,II,JJ
259:       PetscScalar  v

261: !      PetscScalar tmpx(*),tmpb(*)

263:       one  = 1
264:       x    = userctx(1)
265:       b    = userctx(2)
266:       A    = userctx(3)
267:       ksp  = userctx(4)
268:       m    = int(userctx(5))
269:       n    = int(userctx(6))

271: !  This is not the most efficient way of generating the matrix,
272: !  but let's not worry about it.  We should have separate code for
273: !  the four corners, each edge and then the interior. Then we won't
274: !  have the slow if-tests inside the loop.
275: !
276: !  Compute the operator
277: !          -div rho grad
278: !  on an m by n grid with zero Dirichlet boundary conditions. The rho
279: !  is assumed to be given on the same grid as the finite difference
280: !  stencil is applied.  For a staggered grid, one would have to change
281: !  things slightly.

283:       II = 0
284:       do 110 j=1,n
285:          do 100 i=1,m
286:             if (j .gt. 1) then
287:                JJ = II - m
288:                v = -0.5*(rho(II+1) + rho(JJ+1))*hy2
289:                call MatSetValues(A,one,II,one,JJ,v,INSERT_VALUES,ierr)
290:             endif
291:             if (j .lt. n) then
292:                JJ = II + m
293:                v = -0.5*(rho(II+1) + rho(JJ+1))*hy2
294:                call MatSetValues(A,one,II,one,JJ,v,INSERT_VALUES,ierr)
295:             endif
296:             if (i .gt. 1) then
297:                JJ = II - 1
298:                v = -0.5*(rho(II+1) + rho(JJ+1))*hx2
299:                call MatSetValues(A,one,II,one,JJ,v,INSERT_VALUES,ierr)
300:             endif
301:             if (i .lt. m) then
302:                JJ = II + 1
303:                v = -0.5*(rho(II+1) + rho(JJ+1))*hx2
304:                call MatSetValues(A,one,II,one,JJ,v,INSERT_VALUES,ierr)
305:             endif
306:             v = 2*rho(II+1)*(hx2+hy2)
307:             call MatSetValues(A,one,II,one,II,v,INSERT_VALUES,ierr)
308:             II = II+1
309:  100     continue
310:  110  continue
311: !
312: !     Assemble matrix
313: !
314:       call MatAssemblyBegin(A,MAT_FINAL_ASSEMBLY,ierr)
315:       call MatAssemblyEnd(A,MAT_FINAL_ASSEMBLY,ierr)

317: !
318: !     Set operators. Here the matrix that defines the linear system
319: !     also serves as the preconditioning matrix. Since all the matrices
320: !     will have the same nonzero pattern here, we indicate this so the
321: !     linear solvers can take advantage of this.
322: !
323:       call KSPSetOperators(ksp,A,A,SAME_NONZERO_PATTERN,ierr)

325: !
326: !     Set linear solver defaults for this problem (optional).
327: !     - Here we set it to use direct LU factorization for the solution
328: !
329:       call KSPGetPC(ksp,pc,ierr)
330:       call PCSetType(pc,PCLU,ierr)

332: !
333: !     Set runtime options, e.g.,
334: !        -ksp_type <type> -pc_type <type> -ksp_monitor -ksp_rtol <rtol>
335: !     These options will override those specified above as long as
336: !     KSPSetFromOptions() is called _after_ any other customization
337: !     routines.
338: !
339: !     Run the program with the option -help to see all the possible
340: !     linear solver options.
341: !
342:       call KSPSetFromOptions(ksp,ierr)

344: !
345: !     This allows the PETSc linear solvers to compute the solution
346: !     directly in the user's array rather than in the PETSc vector.
347: !
348: !     This is essentially a hack and not highly recommend unless you
349: !     are quite comfortable with using PETSc. In general, users should
350: !     write their entire application using PETSc vectors rather than
351: !     arrays.
352: !
353:       call VecPlaceArray(x,userx,ierr)
354:       call VecPlaceArray(b,userb,ierr)

356: ! - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
357: !                      Solve the linear system
358: ! - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

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

362:       call VecResetArray(x,ierr)
363:       call VecResetArray(b,ierr)

365:       return
366:       end

368: ! ------------------------------------------------------------------------

370:       subroutine UserFinalizeLinearSolver(userctx,ierr)

372:       implicit none

374: #include <finclude/petscsys.h>
375: #include <finclude/petscvec.h>
376: #include <finclude/petscmat.h>
377: #include <finclude/petscksp.h>
378: #include <finclude/petscpc.h>

380:       PetscErrorCode ierr
381:       PetscFortranAddr userctx(*)

383: !  Local variable declararions

385:       Vec  x,b
386:       Mat  A
387:       KSP ksp
388: !
389: !     We are all done and don't need to solve any more linear systems, so
390: !     we free the work space.  All PETSc objects should be destroyed when
391: !     they are no longer needed.
392: !
393:       x    = userctx(1)
394:       b    = userctx(2)
395:       A    = userctx(3)
396:       ksp = userctx(4)

398:       call VecDestroy(x,ierr)
399:       call VecDestroy(b,ierr)
400:       call MatDestroy(A,ierr)
401:       call KSPDestroy(ksp,ierr)

403:       return
404:       end