Actual source code: ex5f90t.F

petsc-master 2014-12-20
Report Typos and Errors
  1: !
  2: !  Description: 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 <parameter>, where <parameter> indicates the nonlinearity of the problem
  7: !       problem SFI:  <parameter> = Bratu parameter (0 <= par <= 6.81)
  8: !
  9: !/*T
 10: !  Concepts: SNES^parallel Bratu example
 11: !  Concepts: DMDA^using distributed arrays;
 12: !  Processors: n
 13: !T*/
 14: !
 15: !  --------------------------------------------------------------------------
 16: !
 17: !  Solid Fuel Ignition (SFI) problem.  This problem is modeled by
 18: !  the partial differential equation
 19: !
 20: !          -Laplacian u - lambda*exp(u) = 0,  0 < x,y < 1,
 21: !
 22: !  with boundary conditions
 23: !
 24: !           u = 0  for  x = 0, x = 1, y = 0, y = 1.
 25: !
 26: !  A finite difference approximation with the usual 5-point stencil
 27: !  is used to discretize the boundary value problem to obtain a nonlinear
 28: !  system of equations.
 29: !
 30: !  The uniprocessor version of this code is snes/examples/tutorials/ex4f.F
 31: !
 32: !  --------------------------------------------------------------------------
 33: !  The following define must be used before including any PETSc include files
 34: !  into a module or interface. This is because they can't handle declarations
 35: !  in them
 36: !

 38:       module f90module
 39: #include <finclude/petscdmdef.h>
 40:       use petscdmdef
 41:       type userctx
 42:         type(DM) da
 43:         PetscInt xs,xe,xm,gxs,gxe,gxm
 44:         PetscInt ys,ye,ym,gys,gye,gym
 45:         PetscInt mx,my
 46:         PetscMPIInt rank
 47:         PetscReal lambda
 48:       end type userctx

 50:       contains
 51: ! ---------------------------------------------------------------------
 52: !
 53: !  FormFunction - Evaluates nonlinear function, F(x).
 54: !
 55: !  Input Parameters:
 56: !  snes - the SNES context
 57: !  X - input vector
 58: !  dummy - optional user-defined context, as set by SNESSetFunction()
 59: !          (not used here)
 60: !
 61: !  Output Parameter:
 62: !  F - function vector
 63: !
 64: !  Notes:
 65: !  This routine serves as a wrapper for the lower-level routine
 66: !  "FormFunctionLocal", where the actual computations are
 67: !  done using the standard Fortran style of treating the local
 68: !  vector data as a multidimensional array over the local mesh.
 69: !  This routine merely handles ghost point scatters and accesses
 70: !  the local vector data via VecGetArrayF90() and VecRestoreArrayF90().
 71: !
 72:       subroutine FormFunction(snesIn,X,F,user,ierr)
 73: #include <finclude/petscsnesdef.h>
 74:       use petscsnes

 76: !  Input/output variables:
 77:       type(SNES)     snesIn
 78:       type(Vec)      X,F
 79:       PetscErrorCode ierr
 80:       type (userctx) user

 82: !  Declarations for use with local arrays:
 83:       PetscScalar,pointer :: lx_v(:),lf_v(:)
 84:       type(Vec)              localX

 86: !  Scatter ghost points to local vector, using the 2-step process
 87: !     DMGlobalToLocalBegin(), DMGlobalToLocalEnd().
 88: !  By placing code between these two statements, computations can
 89: !  be done while messages are in transition.
 90:       call DMGetLocalVector(user%da,localX,ierr)
 91:       call DMGlobalToLocalBegin(user%da,X,INSERT_VALUES,                &
 92:      &     localX,ierr)
 93:       call DMGlobalToLocalEnd(user%da,X,INSERT_VALUES,localX,ierr)

 95: !  Get a pointer to vector data.
 96: !    - For default PETSc vectors, VecGetArray90() returns a pointer to
 97: !      the data array. Otherwise, the routine is implementation dependent.
 98: !    - You MUST call VecRestoreArrayF90() when you no longer need access to
 99: !      the array.
100: !    - Note that the interface to VecGetArrayF90() differs from VecGetArray(),
101: !      and is useable from Fortran-90 Only.

103:       call VecGetArrayF90(localX,lx_v,ierr)
104:       call VecGetArrayF90(F,lf_v,ierr)

106: !  Compute function over the locally owned part of the grid
107:       call FormFunctionLocal(lx_v,lf_v,user,ierr)

109: !  Restore vectors
110:       call VecRestoreArrayF90(localX,lx_v,ierr)
111:       call VecRestoreArrayF90(F,lf_v,ierr)

113: !  Insert values into global vector

115:       call DMRestoreLocalVector(user%da,localX,ierr)
116:       call PetscLogFlops(11.0d0*user%ym*user%xm,ierr)

118: !      call VecView(X,PETSC_VIEWER_STDOUT_WORLD,ierr)
119: !      call VecView(F,PETSC_VIEWER_STDOUT_WORLD,ierr)
120:       return
121:       end subroutine formfunction
122:       end module f90module

124:       module f90moduleinterfaces
125:         use f90module

127:       Interface SNESSetApplicationContext
128:         Subroutine SNESSetApplicationContext(snesIn,ctx,ierr)
129: #include <finclude/petscsnesdef.h>
130:         use petscsnes
131:         use f90module
132:           type(SNES)    snesIn
133:           type(userctx) ctx
134:           PetscErrorCode ierr
135:         End Subroutine
136:       End Interface SNESSetApplicationContext

138:       Interface SNESGetApplicationContext
139:         Subroutine SNESGetApplicationContext(snesIn,ctx,ierr)
140: #include <finclude/petscsnesdef.h>
141:         use petscsnes
142:         use f90module
143:           type(SNES)     snesIn
144:           type(userctx), pointer :: ctx
145:           PetscErrorCode ierr
146:         End Subroutine
147:       End Interface SNESGetApplicationContext
148:       end module f90moduleinterfaces

150:       program main
151: #include <finclude/petscdmdef.h>
152: #include <finclude/petscsnesdef.h>
153:       use petscdm
154:       use petscsnes
155:       use f90module
156:       use f90moduleinterfaces
157: ! - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
158: !                   Variable declarations
159: ! - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
160: !
161: !  Variables:
162: !     mysnes      - nonlinear solver
163: !     x, r        - solution, residual vectors
164: !     J           - Jacobian matrix
165: !     its         - iterations for convergence
166: !     Nx, Ny      - number of preocessors in x- and y- directions
167: !     matrix_free - flag - 1 indicates matrix-free version
168: !
169:       type(SNES)       mysnes
170:       type(Vec)        x,r
171:       type(Mat)        J
172:       PetscErrorCode   ierr
173:       PetscInt         its
174:       PetscBool        flg,matrix_free
175:       PetscInt         ione,nfour
176:       PetscReal lambda_max,lambda_min
177:       type(userctx)    user
178:       type(userctx), pointer:: puser

180: !  Note: Any user-defined Fortran routines (such as FormJacobian)
181: !  MUST be declared as external.
182:       external FormInitialGuess,FormJacobian

184: ! - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
185: !  Initialize program
186: ! - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
187:       call PetscInitialize(PETSC_NULL_CHARACTER,ierr)
188:       call MPI_Comm_rank(PETSC_COMM_WORLD,user%rank,ierr)

190: !  Initialize problem parameters
191:       lambda_max  = 6.81
192:       lambda_min  = 0.0
193:       user%lambda = 6.0
194:       ione = 1
195:       nfour = -4
196:       call PetscOptionsGetReal(PETSC_NULL_CHARACTER,'-par',             &
197:      &     user%lambda,flg,ierr)
198:       if (user%lambda .ge. lambda_max .or. user%lambda .le. lambda_min) &
199:      &     then
200:          if (user%rank .eq. 0) write(6,*) 'Lambda is out of range'
201:          SETERRQ(PETSC_COMM_SELF,1,' ',ierr)
202:       endif

204: ! - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
205: !  Create nonlinear solver context
206: ! - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
207:       call SNESCreate(PETSC_COMM_WORLD,mysnes,ierr)

209: ! - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
210: !  Create vector data structures; set function evaluation routine
211: ! - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

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

215: ! This really needs only the star-type stencil, but we use the box
216: ! stencil temporarily.
217:       call DMDACreate2d(PETSC_COMM_WORLD,                               &
218:      &     DM_BOUNDARY_NONE, DM_BOUNDARY_NONE,                          &
219:      &     DMDA_STENCIL_BOX,nfour,nfour,PETSC_DECIDE,PETSC_DECIDE,          &
220:      &     ione,ione,PETSC_NULL_INTEGER,PETSC_NULL_INTEGER,user%da,ierr)
221:       call DMDAGetInfo(user%da,PETSC_NULL_INTEGER,user%mx,user%my,        &
222:      &               PETSC_NULL_INTEGER,                                &
223:      &               PETSC_NULL_INTEGER,PETSC_NULL_INTEGER,             &
224:      &               PETSC_NULL_INTEGER,PETSC_NULL_INTEGER,             &
225:      &               PETSC_NULL_INTEGER,PETSC_NULL_INTEGER,             &
226:      &               PETSC_NULL_INTEGER,PETSC_NULL_INTEGER,             &
227:      &               PETSC_NULL_INTEGER,ierr)

229: !
230: !   Visualize the distribution of the array across the processors
231: !
232: !     call DMView(user%da,PETSC_VIEWER_DRAW_WORLD,ierr)

234: !  Extract global and local vectors from DMDA; then duplicate for remaining
235: !  vectors that are the same types
236:       call DMCreateGlobalVector(user%da,x,ierr)
237:       call VecDuplicate(x,r,ierr)

239: !  Get local grid boundaries (for 2-dimensional DMDA)
240:       call DMDAGetCorners(user%da,user%xs,user%ys,PETSC_NULL_INTEGER,     &
241:      &     user%xm,user%ym,PETSC_NULL_INTEGER,ierr)
242:       call DMDAGetGhostCorners(user%da,user%gxs,user%gys,                 &
243:      &     PETSC_NULL_INTEGER,user%gxm,user%gym,                        &
244:      &     PETSC_NULL_INTEGER,ierr)

246: !  Here we shift the starting indices up by one so that we can easily
247: !  use the Fortran convention of 1-based indices (rather 0-based indices).
248:       user%xs  = user%xs+1
249:       user%ys  = user%ys+1
250:       user%gxs = user%gxs+1
251:       user%gys = user%gys+1

253:       user%ye  = user%ys+user%ym-1
254:       user%xe  = user%xs+user%xm-1
255:       user%gye = user%gys+user%gym-1
256:       user%gxe = user%gxs+user%gxm-1

258:       call SNESSetApplicationContext(mysnes,user,ierr)

260: !  Set function evaluation routine and vector
261:       call SNESSetFunction(mysnes,r,FormFunction,user,ierr)

263: ! - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
264: !  Create matrix data structure; set Jacobian evaluation routine
265: ! - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

267: !  Set Jacobian matrix data structure and default Jacobian evaluation
268: !  routine. User can override with:
269: !     -snes_fd : default finite differencing approximation of Jacobian
270: !     -snes_mf : matrix-free Newton-Krylov method with no preconditioning
271: !                (unless user explicitly sets preconditioner)
272: !     -snes_mf_operator : form preconditioning matrix as set by the user,
273: !                         but use matrix-free approx for Jacobian-vector
274: !                         products within Newton-Krylov method
275: !
276: !  Note:  For the parallel case, vectors and matrices MUST be partitioned
277: !     accordingly.  When using distributed arrays (DMDAs) to create vectors,
278: !     the DMDAs determine the problem partitioning.  We must explicitly
279: !     specify the local matrix dimensions upon its creation for compatibility
280: !     with the vector distribution.  Thus, the generic MatCreate() routine
281: !     is NOT sufficient when working with distributed arrays.
282: !
283: !     Note: Here we only approximately preallocate storage space for the
284: !     Jacobian.  See the users manual for a discussion of better techniques
285: !     for preallocating matrix memory.

287:       call PetscOptionsHasName(PETSC_NULL_CHARACTER,'-snes_mf',         &
288:      &     matrix_free,ierr)
289:       if (.not. matrix_free) then
290:         call DMSetMatType(user%da,MATAIJ,ierr)
291:         call DMCreateMatrix(user%da,J,ierr)
292:         call SNESSetJacobian(mysnes,J,J,FormJacobian,user,ierr)
293:       endif

295: ! - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
296: !  Customize nonlinear solver; set runtime options
297: ! - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
298: !  Set runtime options (e.g., -snes_monitor -snes_rtol <rtol> -ksp_type <type>)
299:       call SNESSetFromOptions(mysnes,ierr)

301: !     Test Fortran90 wrapper for SNESSet/Get ApplicationContext()
302:       call PetscOptionsGetBool(PETSC_NULL_CHARACTER,'-test_appctx',             &
303:      &     flg,PETSC_NULL_CHARACTER,ierr)
304:       if (flg) then
305:         call SNESGetApplicationContext(mysnes,puser,ierr)
306:       endif

308: ! - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
309: !  Evaluate initial guess; then solve nonlinear system.
310: ! - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
311: !  Note: The user should initialize the vector, x, with the initial guess
312: !  for the nonlinear solver prior to calling SNESSolve().  In particular,
313: !  to employ an initial guess of zero, the user should explicitly set
314: !  this vector to zero by calling VecSet().

316:       call FormInitialGuess(mysnes,x,ierr)
317:       call SNESSolve(mysnes,PETSC_NULL_OBJECT,x,ierr)
318:       call SNESGetIterationNumber(mysnes,its,ierr);
319:       if (user%rank .eq. 0) then
320:          write(6,100) its
321:       endif
322:   100 format('Number of SNES iterations = ',i5)

324: ! - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
325: !  Free work space.  All PETSc objects should be destroyed when they
326: !  are no longer needed.
327: ! - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
328:       if (.not. matrix_free) call MatDestroy(J,ierr)
329:       call VecDestroy(x,ierr)
330:       call VecDestroy(r,ierr)
331:       call SNESDestroy(mysnes,ierr)
332:       call DMDestroy(user%da,ierr)

334:       call PetscFinalize(ierr)
335:       end

337: ! ---------------------------------------------------------------------
338: !
339: !  FormInitialGuess - Forms initial approximation.
340: !
341: !  Input Parameters:
342: !  X - vector
343: !
344: !  Output Parameter:
345: !  X - vector
346: !
347: !  Notes:
348: !  This routine serves as a wrapper for the lower-level routine
349: !  "InitialGuessLocal", where the actual computations are
350: !  done using the standard Fortran style of treating the local
351: !  vector data as a multidimensional array over the local mesh.
352: !  This routine merely handles ghost point scatters and accesses
353: !  the local vector data via VecGetArrayF90() and VecRestoreArrayF90().
354: !
355:       subroutine FormInitialGuess(mysnes,X,ierr)
356: #include <finclude/petscsnesdef.h>
357:       use petscsnes
358:       use f90module
359:       use f90moduleinterfaces
360: !  Input/output variables:
361:       type(SNES)     mysnes
362:       type(userctx), pointer:: puser
363:       type(Vec)      X
364:       PetscErrorCode ierr

366: !  Declarations for use with local arrays:
367:       PetscScalar,pointer :: lx_v(:)

369:       0
370:       call SNESGetApplicationContext(mysnes,puser,ierr)
371: !  Get a pointer to vector data.
372: !    - For default PETSc vectors, VecGetArray90() returns a pointer to
373: !      the data array. Otherwise, the routine is implementation dependent.
374: !    - You MUST call VecRestoreArrayF90() when you no longer need access to
375: !      the array.
376: !    - Note that the interface to VecGetArrayF90() differs from VecGetArray(),
377: !      and is useable from Fortran-90 Only.

379:       call VecGetArrayF90(X,lx_v,ierr)

381: !  Compute initial guess over the locally owned part of the grid
382:       call InitialGuessLocal(puser,lx_v,ierr)

384: !  Restore vector
385:       call VecRestoreArrayF90(X,lx_v,ierr)

387: !  Insert values into global vector

389:       return
390:       end

392: ! ---------------------------------------------------------------------
393: !
394: !  InitialGuessLocal - Computes initial approximation, called by
395: !  the higher level routine FormInitialGuess().
396: !
397: !  Input Parameter:
398: !  x - local vector data
399: !
400: !  Output Parameters:
401: !  x - local vector data
402: !  ierr - error code
403: !
404: !  Notes:
405: !  This routine uses standard Fortran-style computations over a 2-dim array.
406: !
407:       subroutine InitialGuessLocal(user,x,ierr)
408: #include <finclude/petscsysdef.h>
409:       use petscsys
410:       use f90module
411: !  Input/output variables:
412:       type (userctx)         user
413:       PetscScalar  x(user%xs:user%xe,                                             &
414:      &              user%ys:user%ye)
415:       PetscErrorCode ierr

417: !  Local variables:
418:       PetscInt  i,j
419:       PetscScalar   temp1,temp,hx,hy
420:       PetscScalar   one

422: !  Set parameters

424:       0
425:       one    = 1.0
426:       hx     = one/(dble(user%mx-1))
427:       hy     = one/(dble(user%my-1))
428:       temp1  = user%lambda/(user%lambda + one)

430:       do 20 j=user%ys,user%ye
431:          temp = dble(min(j-1,user%my-j))*hy
432:          do 10 i=user%xs,user%xe
433:             if (i .eq. 1 .or. j .eq. 1                                  &
434:      &             .or. i .eq. user%mx .or. j .eq. user%my) then
435:               x(i,j) = 0.0
436:             else
437:               x(i,j) = temp1 *                                          &
438:      &          sqrt(min(dble(min(i-1,user%mx-i)*hx),dble(temp)))
439:             endif
440:  10      continue
441:  20   continue

443:       return
444:       end

446: ! ---------------------------------------------------------------------
447: !
448: !  FormFunctionLocal - Computes nonlinear function, called by
449: !  the higher level routine FormFunction().
450: !
451: !  Input Parameter:
452: !  x - local vector data
453: !
454: !  Output Parameters:
455: !  f - local vector data, f(x)
456: !  ierr - error code
457: !
458: !  Notes:
459: !  This routine uses standard Fortran-style computations over a 2-dim array.
460: !
461:       subroutine FormFunctionLocal(x,f,user,ierr)
462: #include <finclude/petscsysdef.h>
463:       use petscsys
464:       use f90module
465: !  Input/output variables:
466:       type (userctx) user
467:       PetscScalar  x(user%gxs:user%gxe,                                         &
468:      &              user%gys:user%gye)
469:       PetscScalar  f(user%xs:user%xe,                                           &
470:      &              user%ys:user%ye)
471:       PetscErrorCode ierr

473: !  Local variables:
474:       PetscScalar two,one,hx,hy,hxdhy,hydhx,sc
475:       PetscScalar u,uxx,uyy
476:       PetscInt  i,j

478:       one    = 1.0
479:       two    = 2.0
480:       hx     = one/dble(user%mx-1)
481:       hy     = one/dble(user%my-1)
482:       sc     = hx*hy*user%lambda
483:       hxdhy  = hx/hy
484:       hydhx  = hy/hx

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

488:       do 20 j=user%ys,user%ye
489:          do 10 i=user%xs,user%xe
490:             if (i .eq. 1 .or. j .eq. 1                                  &
491:      &             .or. i .eq. user%mx .or. j .eq. user%my) then
492:                f(i,j) = x(i,j)
493:             else
494:                u = x(i,j)
495:                uxx = hydhx * (two*u                                     &
496:      &                - x(i-1,j) - x(i+1,j))
497:                uyy = hxdhy * (two*u - x(i,j-1) - x(i,j+1))
498:                f(i,j) = uxx + uyy - sc*exp(u)
499:             endif
500:  10      continue
501:  20   continue
502:       0
503:       return
504:       end

506: ! ---------------------------------------------------------------------
507: !
508: !  FormJacobian - Evaluates Jacobian matrix.
509: !
510: !  Input Parameters:
511: !  snes     - the SNES context
512: !  x        - input vector
513: !  dummy    - optional user-defined context, as set by SNESSetJacobian()
514: !             (not used here)
515: !
516: !  Output Parameters:
517: !  jac      - Jacobian matrix
518: !  jac_prec - optionally different preconditioning matrix (not used here)
519: !  flag     - flag indicating matrix structure
520: !
521: !  Notes:
522: !  This routine serves as a wrapper for the lower-level routine
523: !  "FormJacobianLocal", where the actual computations are
524: !  done using the standard Fortran style of treating the local
525: !  vector data as a multidimensional array over the local mesh.
526: !  This routine merely accesses the local vector data via
527: !  VecGetArrayF90() and VecRestoreArrayF90().
528: !
529: !  Notes:
530: !  Due to grid point reordering with DMDAs, we must always work
531: !  with the local grid points, and then transform them to the new
532: !  global numbering with the "ltog" mapping
533: !  We cannot work directly with the global numbers for the original
534: !  uniprocessor grid!
535: !
536: !  Two methods are available for imposing this transformation
537: !  when setting matrix entries:
538: !    (A) MatSetValuesLocal(), using the local ordering (including
539: !        ghost points!)
540: !        - Set matrix entries using the local ordering
541: !          by calling MatSetValuesLocal()
542: !    (B) MatSetValues(), using the global ordering
543: !        - Use DMGetLocalToGlobalMapping() then
544: !          ISLocalToGlobalMappingGetIndicesF90() to extract the local-to-global map
545: !        - Then apply this map explicitly yourself
546: !        - Set matrix entries using the global ordering by calling
547: !          MatSetValues()
548: !  Option (A) seems cleaner/easier in many cases, and is the procedure
549: !  used in this example.
550: !
551:       subroutine FormJacobian(mysnes,X,jac,jac_prec,user,ierr)
552: #include <finclude/petscsnesdef.h>
553:       use petscsnes
554:       use f90module
555: !  Input/output variables:
556:       type(SNES)     mysnes
557:       type(Vec)      X
558:       type(Mat)      jac,jac_prec
559:       type(userctx)  user
560:       PetscErrorCode ierr

562: !  Declarations for use with local arrays:
563:       PetscScalar,pointer :: lx_v(:)
564:       type(Vec)      localX

566: !  Scatter ghost points to local vector, using the 2-step process
567: !     DMGlobalToLocalBegin(), DMGlobalToLocalEnd()
568: !  Computations can be done while messages are in transition,
569: !  by placing code between these two statements.

571:       call DMGetLocalVector(user%da,localX,ierr)
572:       call DMGlobalToLocalBegin(user%da,X,INSERT_VALUES,localX,            &
573:      &     ierr)
574:       call DMGlobalToLocalEnd(user%da,X,INSERT_VALUES,localX,ierr)

576: !  Get a pointer to vector data
577:       call VecGetArrayF90(localX,lx_v,ierr)

579: !  Compute entries for the locally owned part of the Jacobian preconditioner.
580:       call FormJacobianLocal(lx_v,jac_prec,user,ierr)

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

587:       call MatAssemblyBegin(jac,MAT_FINAL_ASSEMBLY,ierr)
588: !      if (jac .ne. jac_prec) then
589:          call MatAssemblyBegin(jac_prec,MAT_FINAL_ASSEMBLY,ierr)
590: !      endif
591:       call VecRestoreArrayF90(localX,lx_v,ierr)
592:       call DMRestoreLocalVector(user%da,localX,ierr)
593:       call MatAssemblyEnd(jac,MAT_FINAL_ASSEMBLY,ierr)
594: !      if (jac .ne. jac_prec) then
595:         call MatAssemblyEnd(jac_prec,MAT_FINAL_ASSEMBLY,ierr)
596: !      endif

598: !  Tell the matrix we will never add a new nonzero location to the
599: !  matrix. If we do it will generate an error.

601:       call MatSetOption(jac,MAT_NEW_NONZERO_LOCATION_ERR,PETSC_TRUE,      &
602:      &                  ierr)

604:       return
605:       end

607: ! ---------------------------------------------------------------------
608: !
609: !  FormJacobianLocal - Computes Jacobian preconditioner matrix,
610: !  called by the higher level routine FormJacobian().
611: !
612: !  Input Parameters:
613: !  x        - local vector data
614: !
615: !  Output Parameters:
616: !  jac_prec - Jacobian preconditioner matrix
617: !  ierr     - error code
618: !
619: !  Notes:
620: !  This routine uses standard Fortran-style computations over a 2-dim array.
621: !
622: !  Notes:
623: !  Due to grid point reordering with DMDAs, we must always work
624: !  with the local grid points, and then transform them to the new
625: !  global numbering with the "ltog" mapping
626: !  We cannot work directly with the global numbers for the original
627: !  uniprocessor grid!
628: !
629: !  Two methods are available for imposing this transformation
630: !  when setting matrix entries:
631: !    (A) MatSetValuesLocal(), using the local ordering (including
632: !        ghost points!)
633: !        - Set matrix entries using the local ordering
634: !          by calling MatSetValuesLocal()
635: !    (B) MatSetValues(), using the global ordering
636: !        - Set matrix entries using the global ordering by calling
637: !          MatSetValues()
638: !  Option (A) seems cleaner/easier in many cases, and is the procedure
639: !  used in this example.
640: !
641:       subroutine FormJacobianLocal(x,jac_prec,user,ierr)
642: #include <finclude/petscmatdef.h>
643:       use petscmat
644:       use f90module
645: !  Input/output variables:
646:       type (userctx) user
647:       PetscScalar    x(user%gxs:user%gxe,                                      &
648:      &               user%gys:user%gye)
649:       type(Mat)      jac_prec
650:       PetscErrorCode ierr

652: !  Local variables:
653:       PetscInt    row,col(5),i,j
654:       PetscInt    ione,ifive
655:       PetscScalar two,one,hx,hy,hxdhy
656:       PetscScalar hydhx,sc,v(5)

658: !  Set parameters
659:       ione   = 1
660:       ifive  = 5
661:       one    = 1.0
662:       two    = 2.0
663:       hx     = one/dble(user%mx-1)
664:       hy     = one/dble(user%my-1)
665:       sc     = hx*hy
666:       hxdhy  = hx/hy
667:       hydhx  = hy/hx

669: !  Compute entries for the locally owned part of the Jacobian.
670: !   - Currently, all PETSc parallel matrix formats are partitioned by
671: !     contiguous chunks of rows across the processors.
672: !   - Each processor needs to insert only elements that it owns
673: !     locally (but any non-local elements will be sent to the
674: !     appropriate processor during matrix assembly).
675: !   - Here, we set all entries for a particular row at once.
676: !   - We can set matrix entries either using either
677: !     MatSetValuesLocal() or MatSetValues(), as discussed above.
678: !   - Note that MatSetValues() uses 0-based row and column numbers
679: !     in Fortran as well as in C.

681:       do 20 j=user%ys,user%ye
682:          row = (j - user%gys)*user%gxm + user%xs - user%gxs - 1
683:          do 10 i=user%xs,user%xe
684:             row = row + 1
685: !           boundary points
686:             if (i .eq. 1 .or. j .eq. 1                                  &
687:      &             .or. i .eq. user%mx .or. j .eq. user%my) then
688:                col(1) = row
689:                v(1)   = one
690:                call MatSetValuesLocal(jac_prec,ione,row,ione,col,v,          &
691:      &                           INSERT_VALUES,ierr)
692: !           interior grid points
693:             else
694:                v(1) = -hxdhy
695:                v(2) = -hydhx
696:                v(3) = two*(hydhx + hxdhy)                               &
697:      &                  - sc*user%lambda*exp(x(i,j))
698:                v(4) = -hydhx
699:                v(5) = -hxdhy
700:                col(1) = row - user%gxm
701:                col(2) = row - 1
702:                col(3) = row
703:                col(4) = row + 1
704:                col(5) = row + user%gxm
705:                call MatSetValuesLocal(jac_prec,ione,row,ifive,col,v,         &
706:      &                                INSERT_VALUES,ierr)
707:             endif
708:  10      continue
709:  20   continue
710:       return
711:       end