Actual source code: ex5f.F

petsc-master 2017-05-25
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:  #include <petsc/finclude/petscsnes.h>
35:       use petscdmda
36:       use petscsnes
37:       implicit none
38: !
39: !  We place common blocks, variable declarations, and other include files
40: !  needed for this code in the single file ex5f.h.  We then need to include
41: !  only this file throughout the various routines in this program.  See
43: !
44: #include "ex5f.h"

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

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

68:       external FormInitialGuess
69:       external FormFunctionLocal,FormJacobianLocal

71: ! - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
72: !  Initialize program
73: ! - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

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

83: !  Initialize problem parameters

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

97: ! - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
98: !  Create nonlinear solver context
99: ! - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

101:       call SNESCreate(PETSC_COMM_WORLD,snes,ierr)

103: ! - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
104: !  Create vector data structures; set function evaluation routine
105: ! - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

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

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

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

121:       call DMCreateGlobalVector(da,x,ierr)
122:       call VecDuplicate(x,r,ierr)

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

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

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

140:       xs  = xs+1
141:       ys  = ys+1
142:       gxs = gxs+1
143:       gys = gys+1

145:       ye  = ys+ym-1
146:       xe  = xs+xm-1
147:       gye = gys+gym-1
148:       gxe = gxs+gxm-1

150: !  Set function evaluation routine and vector

152:       call DMDASNESSetFunctionLocal(da,INSERT_VALUES,FormFunctionLocal,            &
153:      &                              0,ierr)
154:       call DMDASNESSetJacobianLocal(da,FormJacobianLocal,                          &
155:      &                              0,ierr)
156:       call SNESSetDM(snes,da,ierr)

158: ! - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
159: !  Customize nonlinear solver; set runtime options
160: ! - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

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

164:           call SNESSetFromOptions(snes,ierr)
165: ! - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
166: !  Evaluate initial guess; then solve nonlinear system.
167: ! - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

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

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

183: ! - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
184: !  Free work space.  All PETSc objects should be destroyed when they
185: !  are no longer needed.
186: ! - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

188:       call VecDestroy(x,ierr)
189:       call VecDestroy(r,ierr)
190:       call SNESDestroy(snes,ierr)
191:       call DMDestroy(da,ierr)
192:       call PetscFinalize(ierr)
193:       end

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

217: #include "ex5f.h"

219: !  Input/output variables:
220:       Vec      X
221:       PetscErrorCode  ierr

223: !  Declarations for use with local arrays:
224:       PetscScalar lx_v(0:1)
225:       PetscOffset lx_i

227:       0

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

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

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

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

243: !  Restore vector

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

247:       return
248:       end

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

269: #include "ex5f.h"

271: !  Input/output variables:
272:       PetscScalar    x(xs:xe,ys:ye)
273:       PetscErrorCode ierr

275: !  Local variables:
276:       PetscInt  i,j
277:       PetscReal temp1,temp,one,hx,hy

279: !  Set parameters

281:       0
282:       one    = 1.0
283:       hx     = one/((mx-1))
284:       hy     = one/((my-1))
285:       temp1  = lambda/(lambda + one)

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

300:       return
301:       end

303: ! ---------------------------------------------------------------------
304: !
305: !  FormFunctionLocal - Computes nonlinear function, called by
306: !  the higher level routine FormFunction().
307: !
308: !  Input Parameter:
309: !  x - local vector data
310: !
311: !  Output Parameters:
312: !  f - local vector data, f(x)
313: !  ierr - error code
314: !
315: !  Notes:
316: !  This routine uses standard Fortran-style computations over a 2-dim array.
317: !
318: !
319:       subroutine FormFunctionLocal(info,x,f,dummy,ierr)
320:  #include <petsc/finclude/petscdmda.h>
321:       use petscsnes
322:       implicit none

324: #include "ex5f.h"

326: !  Input/output variables:
327:       DMDALocalInfo info(DMDA_LOCAL_INFO_SIZE)
328:       PetscScalar x(gxs:gxe,gys:gye)
329:       PetscScalar f(xs:xe,ys:ye)
330:       PetscErrorCode     ierr
331:       PetscObject dummy

333: !  Local variables:
334:       PetscScalar two,one,hx,hy
335:       PetscScalar hxdhy,hydhx,sc
336:       PetscScalar u,uxx,uyy
337:       PetscInt  i,j

339:       xs     = info(DMDA_LOCAL_INFO_XS)+1
340:       xe     = xs+info(DMDA_LOCAL_INFO_XM)-1
341:       ys     = info(DMDA_LOCAL_INFO_YS)+1
342:       ye     = ys+info(DMDA_LOCAL_INFO_YM)-1
343:       mx     = info(DMDA_LOCAL_INFO_MX)
344:       my     = info(DMDA_LOCAL_INFO_MY)

346:       one    = 1.0
347:       two    = 2.0
348:       hx     = one/(mx-1)
349:       hy     = one/(my-1)
350:       sc     = hx*hy*lambda
351:       hxdhy  = hx/hy
352:       hydhx  = hy/hx

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

356:       do 20 j=ys,ye
357:          do 10 i=xs,xe
358:             if (i .eq. 1 .or. j .eq. 1                                  &
359:      &             .or. i .eq. mx .or. j .eq. my) then
360:                f(i,j) = x(i,j)
361:             else
362:                u = x(i,j)
363:                uxx = hydhx * (two*u                                     &
364:      &                - x(i-1,j) - x(i+1,j))
365:                uyy = hxdhy * (two*u - x(i,j-1) - x(i,j+1))
366:                f(i,j) = uxx + uyy - sc*exp(u)
367:             endif
368:  10      continue
369:  20   continue

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

373:       return
374:       end

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

416: #include "ex5f.h"

418: !  Input/output variables:
419:       PetscScalar x(gxs:gxe,gys:gye)
420:       Mat         A,jac
421:       PetscErrorCode  ierr
422:       integer ctx
423:       DMDALocalInfo info(DMDA_LOCAL_INFO_SIZE)

426: !  Local variables:
427:       PetscInt  row,col(5),i,j,i1,i5
428:       PetscScalar two,one,hx,hy,v(5)
429:       PetscScalar hxdhy,hydhx,sc

431: !  Set parameters

433:       i1     = 1
434:       i5     = 5
435:       one    = 1.0
436:       two    = 2.0
437:       hx     = one/(mx-1)
438:       hy     = one/(my-1)
439:       sc     = hx*hy
440:       hxdhy  = hx/hy
441:       hydhx  = hy/hx

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

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

```