Actual source code: ex5.c
2: static char help[] = "Solves a nonlinear system in parallel with SNES.\n\
3: We solve the modified Bratu problem in a 2D rectangular domain,\n\
4: using distributed arrays (DAs) to partition the parallel grid.\n\
5: The command line options include:\n\
6: -lambda <parameter>, where <parameter> indicates the problem's nonlinearity\n\
7: -kappa <parameter>, where <parameter> indicates the problem's nonlinearity\n\
8: -mx <xg>, where <xg> = number of grid points in the x-direction\n\
9: -my <yg>, where <yg> = number of grid points in the y-direction\n\
10: -Nx <npx>, where <npx> = number of processors in the x-direction\n\
11: -Ny <npy>, where <npy> = number of processors in the y-direction\n\n";
13: /*T
14: Concepts: SNES^solving a system of nonlinear equations (parallel Bratu example);
15: Concepts: DA^using distributed arrays;
16: Processors: n
17: T*/
19: /* ------------------------------------------------------------------------
21: Modified Solid Fuel Ignition problem. This problem is modeled by
22: the partial differential equation
24: -Laplacian u - kappa*\PartDer{u}{x} - lambda*exp(u) = 0,
26: where
28: 0 < x,y < 1,
29:
30: with boundary conditions
31:
32: u = 0 for x = 0, x = 1, y = 0, y = 1.
33:
34: A finite difference approximation with the usual 5-point stencil
35: is used to discretize the boundary value problem to obtain a nonlinear
36: system of equations.
38: ------------------------------------------------------------------------- */
40: /*
41: Include "petscda.h" so that we can use distributed arrays (DAs).
42: Include "petscsnes.h" so that we can use SNES solvers. Note that this
43: file automatically includes:
44: petsc.h - base PETSc routines petscvec.h - vectors
45: petscsys.h - system routines petscmat.h - matrices
46: petscis.h - index sets petscksp.h - Krylov subspace methods
47: petscviewer.h - viewers petscpc.h - preconditioners
48: petscksp.h - linear solvers
49: */
50: #include petscda.h
51: #include petscsnes.h
53: /*
54: User-defined application context - contains data needed by the
55: application-provided call-back routines, FormJacobian() and
56: FormFunction().
57: */
58: typedef struct {
59: PetscReal param; /* test problem parameter */
60: PetscReal param2; /* test problem parameter */
61: PetscInt mx,my; /* discretization in x, y directions */
62: Vec localX,localF; /* ghosted local vector */
63: DA da; /* distributed array data structure */
64: PetscMPIInt rank; /* processor rank */
65: } AppCtx;
67: /*
68: User-defined routines
69: */
75: int main(int argc,char **argv)
76: {
77: SNES snes; /* nonlinear solver */
78: Vec x,r; /* solution, residual vectors */
79: Mat J; /* Jacobian matrix */
80: AppCtx user; /* user-defined work context */
81: PetscInt its; /* iterations for convergence */
82: PetscInt Nx,Ny; /* number of preocessors in x- and y- directions */
83: PetscTruth matrix_free; /* flag - 1 indicates matrix-free version */
84: PetscMPIInt size; /* number of processors */
85: PetscInt m,N;
87: PetscReal bratu_lambda_max = 6.81,bratu_lambda_min = 0.;
88: PetscReal bratu_kappa_max = 10000,bratu_kappa_min = 0.;
90: PetscInitialize(&argc,&argv,(char *)0,help);
91: MPI_Comm_rank(PETSC_COMM_WORLD,&user.rank);
93: /*
94: Initialize problem parameters
95: */
96: user.mx = 4; user.my = 4; user.param = 6.0; user.param2 = 0.0;
97: PetscOptionsGetInt(PETSC_NULL,"-mx",&user.mx,PETSC_NULL);
98: PetscOptionsGetInt(PETSC_NULL,"-my",&user.my,PETSC_NULL);
99: PetscOptionsGetReal(PETSC_NULL,"-lambda",&user.param,PETSC_NULL);
100: if (user.param >= bratu_lambda_max || user.param <= bratu_lambda_min) {
101: SETERRQ(1,"Lambda is out of range");
102: }
103: PetscOptionsGetReal(PETSC_NULL,"-kappa",&user.param2,PETSC_NULL);
104: if (user.param2 >= bratu_kappa_max || user.param2 < bratu_kappa_min) {
105: SETERRQ(1,"Kappa is out of range");
106: }
107: PetscPrintf(PETSC_COMM_WORLD,"Solving the Bratu problem with lambda=%G, kappa=%G\n",user.param,user.param2);
109: N = user.mx*user.my;
111: /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
112: Create nonlinear solver context
113: - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
115: SNESCreate(PETSC_COMM_WORLD,&snes);
117: /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
118: Create vector data structures; set function evaluation routine
119: - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
121: /*
122: Create distributed array (DA) to manage parallel grid and vectors
123: */
124: MPI_Comm_size(PETSC_COMM_WORLD,&size);
125: Nx = PETSC_DECIDE; Ny = PETSC_DECIDE;
126: PetscOptionsGetInt(PETSC_NULL,"-Nx",&Nx,PETSC_NULL);
127: PetscOptionsGetInt(PETSC_NULL,"-Ny",&Ny,PETSC_NULL);
128: if (Nx*Ny != size && (Nx != PETSC_DECIDE || Ny != PETSC_DECIDE))
129: SETERRQ(1,"Incompatible number of processors: Nx * Ny != size");
130: DACreate2d(PETSC_COMM_WORLD,DA_NONPERIODIC,DA_STENCIL_STAR,user.mx,user.my,Nx,Ny,1,1,PETSC_NULL,PETSC_NULL,&user.da);
132: /*
133: Visualize the distribution of the array across the processors
134: */
135: /* DAView(user.da,PETSC_VIEWER_DRAW_WORLD); */
138: /*
139: Extract global and local vectors from DA; then duplicate for remaining
140: vectors that are the same types
141: */
142: DACreateGlobalVector(user.da,&x);
143: DACreateLocalVector(user.da,&user.localX);
144: VecDuplicate(x,&r);
145: VecDuplicate(user.localX,&user.localF);
147: /*
148: Set function evaluation routine and vector
149: */
150: SNESSetFunction(snes,r,FormFunction,(void*)&user);
152: /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
153: Create matrix data structure; set Jacobian evaluation routine
154: - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
156: /*
157: Set Jacobian matrix data structure and default Jacobian evaluation
158: routine. User can override with:
159: -snes_fd : default finite differencing approximation of Jacobian
160: -snes_mf : matrix-free Newton-Krylov method with no preconditioning
161: (unless user explicitly sets preconditioner)
162: -snes_mf_operator : form preconditioning matrix as set by the user,
163: but use matrix-free approx for Jacobian-vector
164: products within Newton-Krylov method
166: Note: For the parallel case, vectors and matrices MUST be partitioned
167: accordingly. When using distributed arrays (DAs) to create vectors,
168: the DAs determine the problem partitioning. We must explicitly
169: specify the local matrix dimensions upon its creation for compatibility
170: with the vector distribution. Thus, the generic MatCreate() routine
171: is NOT sufficient when working with distributed arrays.
173: Note: Here we only approximately preallocate storage space for the
174: Jacobian. See the users manual for a discussion of better techniques
175: for preallocating matrix memory.
176: */
177: PetscOptionsHasName(PETSC_NULL,"-snes_mf",&matrix_free);
178: if (!matrix_free) {
179: if (size == 1) {
180: MatCreateSeqAIJ(PETSC_COMM_WORLD,N,N,5,PETSC_NULL,&J);
181: } else {
182: VecGetLocalSize(x,&m);
183: MatCreateMPIAIJ(PETSC_COMM_WORLD,m,m,N,N,5,PETSC_NULL,3,PETSC_NULL,&J);
184: }
185: SNESSetJacobian(snes,J,J,FormJacobian,&user);
186: }
188: /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
189: Customize nonlinear solver; set runtime options
190: - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
192: /*
193: Set runtime options (e.g., -snes_monitor -snes_rtol <rtol> -ksp_type <type>)
194: */
195: SNESSetFromOptions(snes);
197: /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
198: Evaluate initial guess; then solve nonlinear system
199: - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
200: /*
201: Note: The user should initialize the vector, x, with the initial guess
202: for the nonlinear solver prior to calling SNESSolve(). In particular,
203: to employ an initial guess of zero, the user should explicitly set
204: this vector to zero by calling VecSet().
205: */
206: FormInitialGuess(&user,x);
207: SNESSolve(snes,PETSC_NULL,x);
208: SNESGetIterationNumber(snes,&its);
209: PetscPrintf(PETSC_COMM_WORLD,"Number of Newton iterations = %D\n",its);
211: /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
212: Free work space. All PETSc objects should be destroyed when they
213: are no longer needed.
214: - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
216: if (!matrix_free) {
217: MatDestroy(J);
218: }
219: VecDestroy(user.localX); VecDestroy(x);
220: VecDestroy(user.localF); VecDestroy(r);
221: SNESDestroy(snes); DADestroy(user.da);
222: PetscFinalize();
224: return 0;
225: }
226: /* ------------------------------------------------------------------- */
229: /*
230: FormInitialGuess - Forms initial approximation.
232: Input Parameters:
233: user - user-defined application context
234: X - vector
236: Output Parameter:
237: X - vector
238: */
239: PetscErrorCode FormInitialGuess(AppCtx *user,Vec X)
240: {
241: PetscInt i,j,row,mx,my,xs,ys,xm,ym,gxm,gym,gxs,gys;
243: PetscReal one = 1.0,lambda,temp1,temp,hx,hy,hxdhy,hydhx,sc;
244: PetscScalar *x;
245: Vec localX = user->localX;
247: mx = user->mx; my = user->my; lambda = user->param;
248: hx = one/(PetscReal)(mx-1); hy = one/(PetscReal)(my-1);
249: sc = hx*hy*lambda; hxdhy = hx/hy; hydhx = hy/hx;
250: temp1 = lambda/(lambda + one);
252: /*
253: Get a pointer to vector data.
254: - For default PETSc vectors,VecGetArray() returns a pointer to
255: the data array. Otherwise, the routine is implementation dependent.
256: - You MUST call VecRestoreArray() when you no longer need access to
257: the array.
258: */
259: VecGetArray(localX,&x);
261: /*
262: Get local grid boundaries (for 2-dimensional DA):
263: xs, ys - starting grid indices (no ghost points)
264: xm, ym - widths of local grid (no ghost points)
265: gxs, gys - starting grid indices (including ghost points)
266: gxm, gym - widths of local grid (including ghost points)
267: */
268: DAGetCorners(user->da,&xs,&ys,PETSC_NULL,&xm,&ym,PETSC_NULL);
269: DAGetGhostCorners(user->da,&gxs,&gys,PETSC_NULL,&gxm,&gym,PETSC_NULL);
271: /*
272: Compute initial guess over the locally owned part of the grid
273: */
274: for (j=ys; j<ys+ym; j++) {
275: temp = (PetscReal)(PetscMin(j,my-j-1))*hy;
276: for (i=xs; i<xs+xm; i++) {
277: row = i - gxs + (j - gys)*gxm;
278: if (i == 0 || j == 0 || i == mx-1 || j == my-1) {
279: x[row] = 0.0;
280: continue;
281: }
282: x[row] = temp1*sqrt(PetscMin((PetscReal)(PetscMin(i,mx-i-1))*hx,temp));
283: }
284: }
286: /*
287: Restore vector
288: */
289: VecRestoreArray(localX,&x);
291: /*
292: Insert values into global vector
293: */
294: DALocalToGlobal(user->da,localX,INSERT_VALUES,X);
295: return 0;
296: }
297: /* ------------------------------------------------------------------- */
300: /*
301: FormFunction - Evaluates nonlinear function, F(x).
303: Input Parameters:
304: . snes - the SNES context
305: . X - input vector
306: . ptr - optional user-defined context, as set by SNESSetFunction()
308: Output Parameter:
309: . F - function vector
310: */
311: PetscErrorCode FormFunction(SNES snes,Vec X,Vec F,void *ptr)
312: {
313: AppCtx *user = (AppCtx*)ptr;
315: PetscInt i,j,row,mx,my,xs,ys,xm,ym,gxs,gys,gxm,gym;
316: PetscReal two = 2.0,one = 1.0,half = 0.5;
317: PetscReal lambda,hx,hy,hxdhy,hydhx,sc;
318: PetscScalar u,ux,uxx,uyy,*x,*f,kappa;
319: Vec localX = user->localX,localF = user->localF;
321: mx = user->mx; my = user->my; lambda = user->param;
322: hx = one/(PetscReal)(mx-1); hy = one/(PetscReal)(my-1);
323: sc = hx*hy*lambda; hxdhy = hx/hy; hydhx = hy/hx;
324: kappa = user->param2;
326: /*
327: Scatter ghost points to local vector, using the 2-step process
328: DAGlobalToLocalBegin(), DAGlobalToLocalEnd().
329: By placing code between these two statements, computations can be
330: done while messages are in transition.
331: */
332: DAGlobalToLocalBegin(user->da,X,INSERT_VALUES,localX);
333: DAGlobalToLocalEnd(user->da,X,INSERT_VALUES,localX);
335: /*
336: Get pointers to vector data
337: */
338: VecGetArray(localX,&x);
339: VecGetArray(localF,&f);
341: /*
342: Get local grid boundaries
343: */
344: DAGetCorners(user->da,&xs,&ys,PETSC_NULL,&xm,&ym,PETSC_NULL);
345: DAGetGhostCorners(user->da,&gxs,&gys,PETSC_NULL,&gxm,&gym,PETSC_NULL);
347: /*
348: Compute function over the locally owned part of the grid
349: */
350: for (j=ys; j<ys+ym; j++) {
351: row = (j - gys)*gxm + xs - gxs - 1;
352: for (i=xs; i<xs+xm; i++) {
353: row++;
354: if (i == 0 || j == 0 || i == mx-1 || j == my-1) {
355: f[row] = x[row];
356: continue;
357: }
358: u = x[row];
359: ux = (x[row+1] - x[row-1])*half*hy;
360: uxx = (two*u - x[row-1] - x[row+1])*hydhx;
361: uyy = (two*u - x[row-gxm] - x[row+gxm])*hxdhy;
362: f[row] = uxx + uyy - kappa*ux - sc*exp(u);
363: }
364: }
366: /*
367: Restore vectors
368: */
369: VecRestoreArray(localX,&x);
370: VecRestoreArray(localF,&f);
372: /*
373: Insert values into global vector
374: */
375: DALocalToGlobal(user->da,localF,INSERT_VALUES,F);
376: PetscLogFlops(11*ym*xm);
377: return 0;
378: }
379: /* ------------------------------------------------------------------- */
382: /*
383: FormJacobian - Evaluates Jacobian matrix.
385: Input Parameters:
386: . snes - the SNES context
387: . x - input vector
388: . ptr - optional user-defined context, as set by SNESSetJacobian()
390: Output Parameters:
391: . A - Jacobian matrix
392: . B - optionally different preconditioning matrix
393: . flag - flag indicating matrix structure
395: Notes:
396: Due to grid point reordering with DAs, we must always work
397: with the local grid points, and then transform them to the new
398: global numbering with the "ltog" mapping (via DAGetGlobalIndices()).
399: We cannot work directly with the global numbers for the original
400: uniprocessor grid!
401: */
402: PetscErrorCode FormJacobian(SNES snes,Vec X,Mat *J,Mat *B,MatStructure *flag,void *ptr)
403: {
404: AppCtx *user = (AppCtx*)ptr; /* user-defined application context */
405: Mat jac = *B; /* Jacobian matrix */
406: Vec localX = user->localX; /* local vector */
408: PetscInt *ltog; /* local-to-global mapping */
409: PetscInt i,j,row,mx,my,col[5];
410: PetscInt nloc,xs,ys,xm,ym,gxs,gys,gxm,gym,grow;
411: PetscScalar two = 2.0,one = 1.0,lambda,v[5],hx,hy,hxdhy,hydhx,sc,*x;
413: mx = user->mx; my = user->my; lambda = user->param;
414: hx = one/(PetscReal)(mx-1); hy = one/(PetscReal)(my-1);
415: sc = hx*hy; hxdhy = hx/hy; hydhx = hy/hx;
417: /*
418: Scatter ghost points to local vector,using the 2-step process
419: DAGlobalToLocalBegin(),DAGlobalToLocalEnd().
420: By placing code between these two statements, computations can be
421: done while messages are in transition.
422: */
423: DAGlobalToLocalBegin(user->da,X,INSERT_VALUES,localX);
424: DAGlobalToLocalEnd(user->da,X,INSERT_VALUES,localX);
426: /*
427: Get pointer to vector data
428: */
429: VecGetArray(localX,&x);
431: /*
432: Get local grid boundaries
433: */
434: DAGetCorners(user->da,&xs,&ys,PETSC_NULL,&xm,&ym,PETSC_NULL);
435: DAGetGhostCorners(user->da,&gxs,&gys,PETSC_NULL,&gxm,&gym,PETSC_NULL);
437: /*
438: Get the global node numbers for all local nodes, including ghost points
439: */
440: DAGetGlobalIndices(user->da,&nloc,<og);
442: /*
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. The "grow"
446: parameter computed below specifies the global row number
447: corresponding to each local grid point.
448: - Each processor needs to insert only elements that it owns
449: locally (but any non-local elements will be sent to the
450: appropriate processor during matrix assembly).
451: - Always specify global row and columns of matrix entries.
452: - Here, we set all entries for a particular row at once.
453: */
454: for (j=ys; j<ys+ym; j++) {
455: row = (j - gys)*gxm + xs - gxs - 1;
456: for (i=xs; i<xs+xm; i++) {
457: row++;
458: grow = ltog[row];
459: /* boundary points */
460: if (i == 0 || j == 0 || i == mx-1 || j == my-1) {
461: MatSetValues(jac,1,&grow,1,&grow,&one,INSERT_VALUES);
462: continue;
463: }
464: /* interior grid points */
465: v[0] = -hxdhy; col[0] = ltog[row - gxm];
466: v[1] = -hydhx; col[1] = ltog[row - 1];
467: v[2] = two*(hydhx + hxdhy) - sc*lambda*exp(x[row]); col[2] = grow;
468: v[3] = -hydhx; col[3] = ltog[row + 1];
469: v[4] = -hxdhy; col[4] = ltog[row + gxm];
470: MatSetValues(jac,1,&grow,5,col,v,INSERT_VALUES);
471: }
472: }
474: /*
475: Assemble matrix, using the 2-step process:
476: MatAssemblyBegin(), MatAssemblyEnd().
477: By placing code between these two statements, computations can be
478: done while messages are in transition.
479: */
480: MatAssemblyBegin(jac,MAT_FINAL_ASSEMBLY);
481: VecRestoreArray(localX,&x);
482: MatAssemblyEnd(jac,MAT_FINAL_ASSEMBLY);
484: /*
485: Set flag to indicate that the Jacobian matrix retains an identical
486: nonzero structure throughout all nonlinear iterations (although the
487: values of the entries change). Thus, we can save some work in setting
488: up the preconditioner (e.g., no need to redo symbolic factorization for
489: ILU/ICC preconditioners).
490: - If the nonzero structure of the matrix is different during
491: successive linear solves, then the flag DIFFERENT_NONZERO_PATTERN
492: must be used instead. If you are unsure whether the matrix
493: structure has changed or not, use the flag DIFFERENT_NONZERO_PATTERN.
494: - Caution: If you specify SAME_NONZERO_PATTERN, PETSc
495: believes your assertion and does not check the structure
496: of the matrix. If you erroneously claim that the structure
497: is the same when it actually is not, the new preconditioner
498: will not function correctly. Thus, use this optimization
499: feature with caution!
500: */
501: *flag = SAME_NONZERO_PATTERN;
502: /*
503: Tell the matrix we will never add a new nonzero location to the
504: matrix. If we do it will generate an error.
505: */
506: /* MatSetOption(jac,MAT_NEW_NONZERO_LOCATION_ERR); */
507: return 0;
508: }