Actual source code: ex35.c

petsc-3.4.5 2014-06-29
  1: static const char help[] = "-Laplacian u = b as a nonlinear problem.\n\n";

  3: /*T
  4:    Concepts: SNES^parallel Bratu example
  5:    Concepts: DMDA^using distributed arrays;
  6:    Concepts: IS coloirng types;
  7:    Processors: n
  8: T*/

 10: /*

 12:     The linear and nonlinear versions of these should give almost identical results on this problem

 14:     Richardson
 15:       Nonlinear:
 16:         -snes_rtol 1.e-12 -snes_monitor -snes_type nrichardson -snes_linesearch_monitor

 18:       Linear:
 19:         -snes_rtol 1.e-12 -snes_monitor -ksp_rtol 1.e-12  -ksp_monitor -ksp_type richardson -pc_type none -ksp_richardson_self_scale -info

 21:     GMRES
 22:       Nonlinear:
 23:        -snes_rtol 1.e-12 -snes_monitor  -snes_type ngmres

 25:       Linear:
 26:        -snes_rtol 1.e-12 -snes_monitor  -ksp_type gmres -ksp_monitor -ksp_rtol 1.e-12 -pc_type none

 28:     CG
 29:        Nonlinear:
 30:             -snes_rtol 1.e-12 -snes_monitor  -snes_type ncg -snes_linesearch_monitor

 32:        Linear:
 33:              -snes_rtol 1.e-12 -snes_monitor  -ksp_type cg -ksp_monitor -ksp_rtol 1.e-12 -pc_type none

 35:     Multigrid
 36:        Linear:
 37:           1 level:
 38:             -snes_rtol 1.e-12 -snes_monitor  -pc_type mg -mg_levels_ksp_type richardson -mg_levels_pc_type none -mg_levels_ksp_monitor
 39:             -mg_levels_ksp_richardson_self_scale -ksp_type richardson -ksp_monitor -ksp_rtol 1.e-12  -ksp_monitor_true_residual

 41:           n levels:
 42:             -da_refine n

 44:        Nonlinear:
 45:          1 level:
 46:            -snes_rtol 1.e-12 -snes_monitor  -snes_type fas -fas_levels_snes_monitor

 48:           n levels:
 49:             -da_refine n  -fas_coarse_snes_type newtonls -fas_coarse_pc_type lu -fas_coarse_ksp_type preonly

 51: */

 53: /*
 54:    Include "petscdmda.h" so that we can use distributed arrays (DMDAs).
 55:    Include "petscsnes.h" so that we can use SNES solvers.  Note that this
 56: */
 57: #include <petscdmda.h>
 58: #include <petscsnes.h>

 60: /*
 61:    User-defined routines
 62: */
 63: extern PetscErrorCode FormMatrix(DM,Mat);
 64: extern PetscErrorCode MyComputeFunction(SNES,Vec,Vec,void*);
 65: extern PetscErrorCode MyComputeJacobian(SNES,Vec,Mat*,Mat*,MatStructure*,void*);
 66: extern PetscErrorCode NonlinearGS(SNES,Vec);

 70: int main(int argc,char **argv)
 71: {
 72:   SNES           snes;                                 /* nonlinear solver */
 73:   SNES           psnes;                                /* nonlinear Gauss-Seidel approximate solver */
 74:   Vec            x,b;                                  /* solution vector */
 75:   PetscInt       its;                                  /* iterations for convergence */
 77:   DM             da;
 78:   PetscBool      use_ngs = PETSC_FALSE;                /* use the nonlinear Gauss-Seidel approximate solver */

 80:   /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
 81:      Initialize program
 82:      - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */

 84:   PetscInitialize(&argc,&argv,(char*)0,help);

 86:   /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
 87:      Create nonlinear solver context
 88:      - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
 89:   SNESCreate(PETSC_COMM_WORLD,&snes);

 91:   PetscOptionsGetBool(NULL,"-use_ngs",&use_ngs,0);

 93:   if (use_ngs) {
 94:     SNESGetPC(snes,&psnes);
 95:     SNESSetType(psnes,SNESSHELL);
 96:     SNESShellSetSolve(psnes,NonlinearGS);
 97:   }

 99:   /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
100:      Create distributed array (DMDA) to manage parallel grid and vectors
101:   - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
102:   DMDACreate2d(PETSC_COMM_WORLD, DMDA_BOUNDARY_NONE, DMDA_BOUNDARY_NONE,DMDA_STENCIL_STAR,-4,-4,PETSC_DECIDE,PETSC_DECIDE,1,1,NULL,NULL,&da);
103:   DMDASetUniformCoordinates(da, 0.0, 1.0, 0.0, 1.0, 0.0, 1.0);
104:   SNESSetDM(snes,da);
105:   if (use_ngs) {
106:     SNESShellSetContext(psnes,da);
107:   }
108:   /*  - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
109:      Extract global vectors from DMDA; then duplicate for remaining
110:      vectors that are the same types
111:    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
112:   DMCreateGlobalVector(da,&x);
113:   DMCreateGlobalVector(da,&b);
114:   VecSetRandom(b,NULL);

116:   SNESSetFunction(snes,NULL,MyComputeFunction,NULL);
117:   SNESSetJacobian(snes,NULL,NULL,MyComputeJacobian,NULL);

119:   /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
120:      Customize nonlinear solver; set runtime options
121:    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
122:   SNESSetFromOptions(snes);

124:   /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
125:      Solve nonlinear system
126:      - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
127:   SNESSolve(snes,b,x);
128:   SNESGetIterationNumber(snes,&its);

130:   /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
131:    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */

133:   /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
134:      Free work space.  All PETSc objects should be destroyed when they
135:      are no longer needed.
136:    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
137:   VecDestroy(&x);
138:   VecDestroy(&b);
139:   SNESDestroy(&snes);
140:   DMDestroy(&da);
141:   PetscFinalize();
142:   return(0);
143: }

145: /* ------------------------------------------------------------------- */
148: PetscErrorCode MyComputeFunction(SNES snes,Vec x,Vec F,void *ctx)
149: {
151:   Mat            J;
152:   DM             dm;

155:   SNESGetDM(snes,&dm);
156:   DMGetApplicationContext(dm,&J);
157:   if (!J) {
158:     DMCreateMatrix(dm,MATAIJ,&J);
159:     MatSetDM(J, NULL);
160:     FormMatrix(dm,J);
161:     DMSetApplicationContext(dm,J);
162:     DMSetApplicationContextDestroy(dm,(PetscErrorCode (*)(void**))MatDestroy);
163:   }
164:   MatMult(J,x,F);
165:   return(0);
166: }

170: PetscErrorCode MyComputeJacobian(SNES snes,Vec x,Mat *J,Mat *Jp,MatStructure *str,void *ctx)
171: {
173:   DM             dm;

176:   SNESGetDM(snes,&dm);
177:   FormMatrix(dm,*Jp);
178:   *str = SAME_NONZERO_PATTERN;
179:   return(0);
180: }

184: PetscErrorCode FormMatrix(DM da,Mat jac)
185: {
187:   PetscInt       i,j,nrows = 0;
188:   MatStencil     col[5],row,*rows;
189:   PetscScalar    v[5],hx,hy,hxdhy,hydhx;
190:   DMDALocalInfo  info;

193:   DMDAGetLocalInfo(da,&info);
194:   hx    = 1.0/(PetscReal)(info.mx-1);
195:   hy    = 1.0/(PetscReal)(info.my-1);
196:   hxdhy = hx/hy;
197:   hydhx = hy/hx;

199:   PetscMalloc(info.ym*info.xm*sizeof(MatStencil),&rows);
200:   /*
201:      Compute entries for the locally owned part of the Jacobian.
202:       - Currently, all PETSc parallel matrix formats are partitioned by
203:         contiguous chunks of rows across the processors.
204:       - Each processor needs to insert only elements that it owns
205:         locally (but any non-local elements will be sent to the
206:         appropriate processor during matrix assembly).
207:       - Here, we set all entries for a particular row at once.
208:       - We can set matrix entries either using either
209:         MatSetValuesLocal() or MatSetValues(), as discussed above.
210:   */
211:   for (j=info.ys; j<info.ys+info.ym; j++) {
212:     for (i=info.xs; i<info.xs+info.xm; i++) {
213:       row.j = j; row.i = i;
214:       /* boundary points */
215:       if (i == 0 || j == 0 || i == info.mx-1 || j == info.my-1) {
216:         v[0]            = 2.0*(hydhx + hxdhy);
217:         MatSetValuesStencil(jac,1,&row,1,&row,v,INSERT_VALUES);
218:         rows[nrows].i   = i;
219:         rows[nrows++].j = j;
220:       } else {
221:         /* interior grid points */
222:         v[0] = -hxdhy;                                           col[0].j = j - 1; col[0].i = i;
223:         v[1] = -hydhx;                                           col[1].j = j;     col[1].i = i-1;
224:         v[2] = 2.0*(hydhx + hxdhy);                              col[2].j = row.j; col[2].i = row.i;
225:         v[3] = -hydhx;                                           col[3].j = j;     col[3].i = i+1;
226:         v[4] = -hxdhy;                                           col[4].j = j + 1; col[4].i = i;
227:         MatSetValuesStencil(jac,1,&row,5,col,v,INSERT_VALUES);
228:       }
229:     }
230:   }

232:   /*
233:      Assemble matrix, using the 2-step process:
234:        MatAssemblyBegin(), MatAssemblyEnd().
235:   */
236:   MatAssemblyBegin(jac,MAT_FINAL_ASSEMBLY);
237:   MatAssemblyEnd(jac,MAT_FINAL_ASSEMBLY);
238:   MatZeroRowsColumnsStencil(jac,nrows,rows,2.0*(hydhx + hxdhy),NULL,NULL);
239:   PetscFree(rows);
240:   /*
241:      Tell the matrix we will never add a new nonzero location to the
242:      matrix. If we do, it will generate an error.
243:   */
244:   MatSetOption(jac,MAT_NEW_NONZERO_LOCATION_ERR,PETSC_TRUE);
245:   return(0);
246: }



250: /* ------------------------------------------------------------------- */
253: /*
254:       Applies some sweeps on nonlinear Gauss-Seidel on each process

256:  */
257: PetscErrorCode NonlinearGS(SNES snes,Vec X)
258: {
259:   PetscInt       i,j,Mx,My,xs,ys,xm,ym,its,l;
261:   PetscReal      hx,hy,hxdhy,hydhx;
262:   PetscScalar    **x,F,J,u,uxx,uyy;
263:   DM             da;
264:   Vec            localX;

267:   SNESGetTolerances(snes,NULL,NULL,NULL,&its,NULL);
268:   SNESShellGetContext(snes,(void**)&da);

270:   DMDAGetInfo(da,PETSC_IGNORE,&Mx,&My,PETSC_IGNORE,PETSC_IGNORE,PETSC_IGNORE,
271:                      PETSC_IGNORE,PETSC_IGNORE,PETSC_IGNORE,PETSC_IGNORE,PETSC_IGNORE,PETSC_IGNORE,PETSC_IGNORE);

273:   hx    = 1.0/(PetscReal)(Mx-1);
274:   hy    = 1.0/(PetscReal)(My-1);
275:   hxdhy = hx/hy;
276:   hydhx = hy/hx;


279:   DMGetLocalVector(da,&localX);

281:   for (l=0; l<its; l++) {

283:     DMGlobalToLocalBegin(da,X,INSERT_VALUES,localX);
284:     DMGlobalToLocalEnd(da,X,INSERT_VALUES,localX);
285:     /*
286:      Get a pointer to vector data.
287:      - For default PETSc vectors, VecGetArray() returns a pointer to
288:      the data array.  Otherwise, the routine is implementation dependent.
289:      - You MUST call VecRestoreArray() when you no longer need access to
290:      the array.
291:      */
292:     DMDAVecGetArray(da,localX,&x);

294:     /*
295:      Get local grid boundaries (for 2-dimensional DMDA):
296:      xs, ys   - starting grid indices (no ghost points)
297:      xm, ym   - widths of local grid (no ghost points)

299:      */
300:     DMDAGetCorners(da,&xs,&ys,NULL,&xm,&ym,NULL);

302:     for (j=ys; j<ys+ym; j++) {
303:       for (i=xs; i<xs+xm; i++) {
304:         if (i == 0 || j == 0 || i == Mx-1 || j == My-1) {
305:           /* boundary conditions are all zero Dirichlet */
306:           x[j][i] = 0.0;
307:         } else {
308:           u   = x[j][i];
309:           uxx = (2.0*u - x[j][i-1] - x[j][i+1])*hydhx;
310:           uyy = (2.0*u - x[j-1][i] - x[j+1][i])*hxdhy;
311:           F   = uxx + uyy;
312:           J   = 2.0*(hydhx + hxdhy);
313:           u   = u - F/J;

315:           x[j][i] = u;
316:         }
317:       }
318:     }

320:     /*
321:      Restore vector
322:      */
323:     DMDAVecRestoreArray(da,localX,&x);
324:     DMLocalToGlobalBegin(da,localX,INSERT_VALUES,X);
325:     DMLocalToGlobalEnd(da,localX,INSERT_VALUES,X);
326:   }
327:   DMRestoreLocalVector(da,&localX);
328:   return(0);
329: }