Actual source code: ex5f.F

petsc-master 2016-12-02
Report Typos and Errors
  1: !
  2: !  Description: This example solves a nonlinear system in parallel with SNES.
  3: !  We solve the  Bratu (SFI - solid fuel ignition) problem in a 2D rectangular
  4: !  domain, using distributed arrays (DMDAs) to partition the parallel grid.
  5: !  The command line options include:
  6: !    -par <param>, where <param> indicates the nonlinearity of the problem
  7: !       problem SFI:  <parameter> = Bratu parameter (0 <= par <= 6.81)
  8: !
  9: !
 10: !/*T
 11: !  Concepts: SNES^parallel Bratu example
 12: !  Concepts: DMDA^using distributed arrays;
 13: !  Processors: n
 14: !T*/
 15: !
 16: !  --------------------------------------------------------------------------
 17: !
 18: !  Solid Fuel Ignition (SFI) problem.  This problem is modeled by
 19: !  the partial differential equation
 20: !
 21: !          -Laplacian u - lambda*exp(u) = 0,  0 < x,y < 1,
 22: !
 23: !  with boundary conditions
 24: !
 25: !           u = 0  for  x = 0, x = 1, y = 0, y = 1.
 26: !
 27: !  A finite difference approximation with the usual 5-point stencil
 28: !  is used to discretize the boundary value problem to obtain a nonlinear
 29: !  system of equations.
 30: !
 31: !  --------------------------------------------------------------------------

 33:       program main
 34:       implicit none
 35: !
 36: !  We place common blocks, variable declarations, and other include files
 37: !  needed for this code in the single file ex5f.h.  We then need to include
 38: !  only this file throughout the various routines in this program.  See
 39: !  additional comments in the file ex5f.h.
 40: !
 41: #include "ex5f.h"

 43: ! - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
 44: !                   Variable declarations
 45: ! - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
 46: !
 47: !  Variables:
 48: !     snes        - nonlinear solver
 49: !     x, r        - solution, residual vectors
 50: !     its         - iterations for convergence
 51: !
 52: !  See additional variable declarations in the file ex5f.h
 53: !
 54:       SNES           snes
 55:       Vec            x,r
 56:       PetscInt       its,i1,i4
 57:       PetscErrorCode ierr
 58:       PetscReal      lambda_max,lambda_min
 59:       PetscBool      flg


 62: !  Note: Any user-defined Fortran routines (such as FormJacobianLocal)
 63: !  MUST be declared as external.

 65:       external FormInitialGuess
 66:       external FormFunctionLocal,FormJacobianLocal

 68: ! - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
 69: !  Initialize program
 70: ! - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

 72:       call PetscInitialize(PETSC_NULL_CHARACTER,ierr)
 73:       if (ierr .ne. 0) then
 74:         print*,'Unable to initialize PETSc'
 75:         stop
 76:       endif
 77:       call MPI_Comm_size(PETSC_COMM_WORLD,size,ierr)
 78:       call MPI_Comm_rank(PETSC_COMM_WORLD,rank,ierr)

 80: !  Initialize problem parameters

 82:       i1 = 1
 83:       i4 = 4
 84:       lambda_max = 6.81
 85:       lambda_min = 0.0
 86:       lambda     = 6.0
 87:       call PetscOptionsGetReal(PETSC_NULL_OBJECT,                        &
 88:      &             PETSC_NULL_CHARACTER,'-par',lambda,flg,ierr)
 89:       if (lambda .ge. lambda_max .or. lambda .le. lambda_min) then
 90:          if (rank .eq. 0) write(6,*) 'Lambda is out of range'
 91:          SETERRQ(PETSC_COMM_SELF,1,' ',ierr)
 92:       endif

 94: ! - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
 95: !  Create nonlinear solver context
 96: ! - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

 98:       call SNESCreate(PETSC_COMM_WORLD,snes,ierr)

100: ! - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
101: !  Create vector data structures; set function evaluation routine
102: ! - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

104: !  Create distributed array (DMDA) to manage parallel grid and vectors

106: ! This really needs only the star-type stencil, but we use the box
107: ! stencil temporarily.
108:       call DMDACreate2d(PETSC_COMM_WORLD,DM_BOUNDARY_NONE,              &
109:      &     DM_BOUNDARY_NONE,                                            &
110:      &     DMDA_STENCIL_STAR,i4,i4,PETSC_DECIDE,PETSC_DECIDE,i1,i1,                &
111:      &     PETSC_NULL_INTEGER,PETSC_NULL_INTEGER,da,ierr)
112:       call DMSetFromOptions(da,ierr)
113:       call DMSetUp(da,ierr)

115: !  Extract global and local vectors from DMDA; then duplicate for remaining
116: !  vectors that are the same types

118:       call DMCreateGlobalVector(da,x,ierr)
119:       call VecDuplicate(x,r,ierr)

121: !  Get local grid boundaries (for 2-dimensional DMDA)

123:       call DMDAGetInfo(da,PETSC_NULL_INTEGER,mx,my,PETSC_NULL_INTEGER,            &
124:      &               PETSC_NULL_INTEGER,PETSC_NULL_INTEGER,                     &
125:      &               PETSC_NULL_INTEGER,PETSC_NULL_INTEGER,                     &
126:      &               PETSC_NULL_INTEGER,PETSC_NULL_INTEGER,                     &
127:      &               PETSC_NULL_INTEGER,PETSC_NULL_INTEGER,                     &
128:      &               PETSC_NULL_INTEGER,ierr)
129:       call DMDAGetCorners(da,xs,ys,PETSC_NULL_INTEGER,xm,ym,                      &
130:      &     PETSC_NULL_INTEGER,ierr)
131:       call DMDAGetGhostCorners(da,gxs,gys,PETSC_NULL_INTEGER,gxm,gym,             &
132:      &     PETSC_NULL_INTEGER,ierr)

134: !  Here we shift the starting indices up by one so that we can easily
135: !  use the Fortran convention of 1-based indices (rather 0-based indices).

137:       xs  = xs+1
138:       ys  = ys+1
139:       gxs = gxs+1
140:       gys = gys+1

142:       ye  = ys+ym-1
143:       xe  = xs+xm-1
144:       gye = gys+gym-1
145:       gxe = gxs+gxm-1

147: !  Set function evaluation routine and vector

149:       call DMDASNESSetFunctionLocal(da,INSERT_VALUES,FormFunctionLocal,            &
150:      &                              PETSC_NULL_OBJECT,ierr)
151:       call DMDASNESSetJacobianLocal(da,FormJacobianLocal,                          &
152:      &                              PETSC_NULL_OBJECT,ierr)
153:       call SNESSetDM(snes,da,ierr)

155: ! - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
156: !  Customize nonlinear solver; set runtime options
157: ! - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

159: !  Set runtime options (e.g., -snes_monitor -snes_rtol <rtol> -ksp_type <type>)

161:           call SNESSetFromOptions(snes,ierr)
162: ! - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
163: !  Evaluate initial guess; then solve nonlinear system.
164: ! - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

166: !  Note: The user should initialize the vector, x, with the initial guess
167: !  for the nonlinear solver prior to calling SNESSolve().  In particular,
168: !  to employ an initial guess of zero, the user should explicitly set
169: !  this vector to zero by calling VecSet().

171:       call FormInitialGuess(x,ierr)
172:       call SNESSolve(snes,PETSC_NULL_OBJECT,x,ierr)
173:       call SNESGetIterationNumber(snes,its,ierr)
174:       if (rank .eq. 0) then
175:          write(6,100) its
176:       endif
177:   100 format('Number of SNES iterations = ',i5)


180: ! - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
181: !  Free work space.  All PETSc objects should be destroyed when they
182: !  are no longer needed.
183: ! - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

185:       call VecDestroy(x,ierr)
186:       call VecDestroy(r,ierr)
187:       call SNESDestroy(snes,ierr)
188:       call DMDestroy(da,ierr)
189:       call PetscFinalize(ierr)
190:       end

192: ! ---------------------------------------------------------------------
193: !
194: !  FormInitialGuess - Forms initial approximation.
195: !
196: !  Input Parameters:
197: !  X - vector
198: !
199: !  Output Parameter:
200: !  X - vector
201: !
202: !  Notes:
203: !  This routine serves as a wrapper for the lower-level routine
204: !  "ApplicationInitialGuess", where the actual computations are
205: !  done using the standard Fortran style of treating the local
206: !  vector data as a multidimensional array over the local mesh.
207: !  This routine merely handles ghost point scatters and accesses
208: !  the local vector data via VecGetArray() and VecRestoreArray().
209: !
210:       subroutine FormInitialGuess(X,ierr)
211:       implicit none

213: #include "ex5f.h"

215: !  Input/output variables:
216:       Vec      X
217:       PetscErrorCode  ierr

219: !  Declarations for use with local arrays:
220:       PetscScalar lx_v(0:1)
221:       PetscOffset lx_i

223:       0

225: !  Get a pointer to vector data.
226: !    - For default PETSc vectors, VecGetArray() returns a pointer to
227: !      the data array.  Otherwise, the routine is implementation dependent.
228: !    - You MUST call VecRestoreArray() when you no longer need access to
229: !      the array.
230: !    - Note that the Fortran interface to VecGetArray() differs from the
231: !      C version.  See the users manual for details.

233:       call VecGetArray(X,lx_v,lx_i,ierr)

235: !  Compute initial guess over the locally owned part of the grid

237:       call InitialGuessLocal(lx_v(lx_i),ierr)

239: !  Restore vector

241:       call VecRestoreArray(X,lx_v,lx_i,ierr)

243:       return
244:       end

246: ! ---------------------------------------------------------------------
247: !
248: !  InitialGuessLocal - Computes initial approximation, called by
249: !  the higher level routine FormInitialGuess().
250: !
251: !  Input Parameter:
252: !  x - local vector data
253: !
254: !  Output Parameters:
255: !  x - local vector data
256: !  ierr - error code
257: !
258: !  Notes:
259: !  This routine uses standard Fortran-style computations over a 2-dim array.
260: !
261:       subroutine InitialGuessLocal(x,ierr)
262:       implicit none

264: #include "ex5f.h"

266: !  Input/output variables:
267:       PetscScalar    x(xs:xe,ys:ye)
268:       PetscErrorCode ierr

270: !  Local variables:
271:       PetscInt  i,j
272:       PetscReal temp1,temp,one,hx,hy

274: !  Set parameters

276:       0
277:       one    = 1.0
278:       hx     = one/((mx-1))
279:       hy     = one/((my-1))
280:       temp1  = lambda/(lambda + one)

282:       do 20 j=ys,ye
283:          temp = (min(j-1,my-j))*hy
284:          do 10 i=xs,xe
285:             if (i .eq. 1 .or. j .eq. 1                                  &
286:      &             .or. i .eq. mx .or. j .eq. my) then
287:               x(i,j) = 0.0
288:             else
289:               x(i,j) = temp1 *                                          &
290:      &          sqrt(min(min(i-1,mx-i)*hx,(temp)))
291:             endif
292:  10      continue
293:  20   continue

295:       return
296:       end

298: ! ---------------------------------------------------------------------
299: !
300: !  FormFunctionLocal - Computes nonlinear function, called by
301: !  the higher level routine FormFunction().
302: !
303: !  Input Parameter:
304: !  x - local vector data
305: !
306: !  Output Parameters:
307: !  f - local vector data, f(x)
308: !  ierr - error code
309: !
310: !  Notes:
311: !  This routine uses standard Fortran-style computations over a 2-dim array.
312: !
313: !
314:       subroutine FormFunctionLocal(info,x,f,dummy,ierr)

316:       implicit none

318: #include "ex5f.h"

320: !  Input/output variables:
321:       DMDALocalInfo info(DMDA_LOCAL_INFO_SIZE)
322:       PetscScalar x(gxs:gxe,gys:gye)
323:       PetscScalar f(xs:xe,ys:ye)
324:       PetscErrorCode     ierr
325:       PetscObject dummy

327: !  Local variables:
328:       PetscScalar two,one,hx,hy
329:       PetscScalar hxdhy,hydhx,sc
330:       PetscScalar u,uxx,uyy
331:       PetscInt  i,j

333:       xs     = info(DMDA_LOCAL_INFO_XS)+1
334:       xe     = xs+info(DMDA_LOCAL_INFO_XM)-1
335:       ys     = info(DMDA_LOCAL_INFO_YS)+1
336:       ye     = ys+info(DMDA_LOCAL_INFO_YM)-1
337:       mx     = info(DMDA_LOCAL_INFO_MX)
338:       my     = info(DMDA_LOCAL_INFO_MY)

340:       one    = 1.0
341:       two    = 2.0
342:       hx     = one/(mx-1)
343:       hy     = one/(my-1)
344:       sc     = hx*hy*lambda
345:       hxdhy  = hx/hy
346:       hydhx  = hy/hx

348: !  Compute function over the locally owned part of the grid

350:       do 20 j=ys,ye
351:          do 10 i=xs,xe
352:             if (i .eq. 1 .or. j .eq. 1                                  &
353:      &             .or. i .eq. mx .or. j .eq. my) then
354:                f(i,j) = x(i,j)
355:             else
356:                u = x(i,j)
357:                uxx = hydhx * (two*u                                     &
358:      &                - x(i-1,j) - x(i+1,j))
359:                uyy = hxdhy * (two*u - x(i,j-1) - x(i,j+1))
360:                f(i,j) = uxx + uyy - sc*exp(u)
361:             endif
362:  10      continue
363:  20   continue

365:       call PetscLogFlops(11.0d0*ym*xm,ierr)

367:       return
368:       end

370: ! ---------------------------------------------------------------------
371: !
372: !  FormJacobianLocal - Computes Jacobian matrix, called by
373: !  the higher level routine FormJacobian().
374: !
375: !  Input Parameters:
376: !  x        - local vector data
377: !
378: !  Output Parameters:
379: !  jac      - Jacobian matrix
380: !  jac_prec - optionally different preconditioning matrix (not used here)
381: !  ierr     - error code
382: !
383: !  Notes:
384: !  This routine uses standard Fortran-style computations over a 2-dim array.
385: !
386: !  Notes:
387: !  Due to grid point reordering with DMDAs, we must always work
388: !  with the local grid points, and then transform them to the new
389: !  global numbering with the "ltog" mapping
390: !  We cannot work directly with the global numbers for the original
391: !  uniprocessor grid!
392: !
393: !  Two methods are available for imposing this transformation
394: !  when setting matrix entries:
395: !    (A) MatSetValuesLocal(), using the local ordering (including
396: !        ghost points!)
397: !          by calling MatSetValuesLocal()
398: !    (B) MatSetValues(), using the global ordering
399: !        - Use DMDAGetGlobalIndices() to extract the local-to-global map
400: !        - Then apply this map explicitly yourself
401: !        - Set matrix entries using the global ordering by calling
402: !          MatSetValues()
403: !  Option (A) seems cleaner/easier in many cases, and is the procedure
404: !  used in this example.
405: !
406:       subroutine FormJacobianLocal(info,x,A,jac,ctx,ierr)
407:       implicit none

409: #include "ex5f.h"

411: !  Input/output variables:
412:       PetscScalar x(gxs:gxe,gys:gye)
413:       Mat         A,jac
414:       PetscErrorCode  ierr
415:       integer ctx
416:       DMDALocalInfo info(DMDA_LOCAL_INFO_SIZE)


419: !  Local variables:
420:       PetscInt  row,col(5),i,j,i1,i5
421:       PetscScalar two,one,hx,hy,v(5)
422:       PetscScalar hxdhy,hydhx,sc

424: !  Set parameters

426:       i1     = 1
427:       i5     = 5
428:       one    = 1.0
429:       two    = 2.0
430:       hx     = one/(mx-1)
431:       hy     = one/(my-1)
432:       sc     = hx*hy
433:       hxdhy  = hx/hy
434:       hydhx  = hy/hx

436: !  Compute entries for the locally owned part of the Jacobian.
437: !   - Currently, all PETSc parallel matrix formats are partitioned by
438: !     contiguous chunks of rows across the processors.
439: !   - Each processor needs to insert only elements that it owns
440: !     locally (but any non-local elements will be sent to the
441: !     appropriate processor during matrix assembly).
442: !   - Here, we set all entries for a particular row at once.
443: !   - We can set matrix entries either using either
444: !     MatSetValuesLocal() or MatSetValues(), as discussed above.
445: !   - Note that MatSetValues() uses 0-based row and column numbers
446: !     in Fortran as well as in C.

448:       do 20 j=ys,ye
449:          row = (j - gys)*gxm + xs - gxs - 1
450:          do 10 i=xs,xe
451:             row = row + 1
452: !           boundary points
453:             if (i .eq. 1 .or. j .eq. 1                                  &
454:      &             .or. i .eq. mx .or. j .eq. my) then
455: !       Some f90 compilers need 4th arg to be of same type in both calls
456:                col(1) = row
457:                v(1)   = one
458:                call MatSetValuesLocal(jac,i1,row,i1,col,v,                &
459:      &                           INSERT_VALUES,ierr)
460: !           interior grid points
461:             else
462:                v(1) = -hxdhy
463:                v(2) = -hydhx
464:                v(3) = two*(hydhx + hxdhy)                               &
465:      &                  - sc*lambda*exp(x(i,j))
466:                v(4) = -hydhx
467:                v(5) = -hxdhy
468:                col(1) = row - gxm
469:                col(2) = row - 1
470:                col(3) = row
471:                col(4) = row + 1
472:                col(5) = row + gxm
473:                call MatSetValuesLocal(jac,i1,row,i5,col,v,                &
474:      &                                INSERT_VALUES,ierr)
475:             endif
476:  10      continue
477:  20   continue
478:       call MatAssemblyBegin(jac,MAT_FINAL_ASSEMBLY,ierr)
479:       call MatAssemblyEnd(jac,MAT_FINAL_ASSEMBLY,ierr)
480:       if (A .ne. jac) then
481:          call MatAssemblyBegin(A,MAT_FINAL_ASSEMBLY,ierr)
482:          call MatAssemblyEnd(A,MAT_FINAL_ASSEMBLY,ierr)
483:       endif
484:       return
485:       end