Actual source code: ex1.c
petsc-3.4.2 2013-07-02
2: static char help[] = "Solves the nonlinear system, the Bratu (SFI - solid fuel ignition) problem in a 2D rectangular domain.\n\
3: This example also illustrates the use of matrix coloring. Runtime options include:\n\
4: -par <parameter>, where <parameter> indicates the problem's nonlinearity\n\
5: problem SFI: <parameter> = Bratu parameter (0 <= par <= 6.81)\n\
6: -mx <xg>, where <xg> = number of grid points in the x-direction\n\
7: -my <yg>, where <yg> = number of grid points in the y-direction\n\n";
9: /*T
10: Concepts: SNES^sequential Bratu example
11: Processors: 1
12: T*/
14: /* ------------------------------------------------------------------------
16: Solid Fuel Ignition (SFI) problem. This problem is modeled by
17: the partial differential equation
19: -Laplacian u - lambda*exp(u) = 0, 0 < x,y < 1,
21: with boundary conditions
23: u = 0 for x = 0, x = 1, y = 0, y = 1.
25: A finite difference approximation with the usual 5-point stencil
26: is used to discretize the boundary value problem to obtain a nonlinear
27: system of equations.
29: The parallel version of this code is snes/examples/tutorials/ex5.c
31: ------------------------------------------------------------------------- */
33: /*
34: Include "petscsnes.h" so that we can use SNES solvers. Note that
35: this file automatically includes:
36: petscsys.h - base PETSc routines petscvec.h - vectors
37: petscmat.h - matrices
38: petscis.h - index sets petscksp.h - Krylov subspace methods
39: petscviewer.h - viewers petscpc.h - preconditioners
40: petscksp.h - linear solvers
41: */
43: #include <petscsnes.h>
45: /*
46: User-defined application context - contains data needed by the
47: application-provided call-back routines, FormJacobian() and
48: FormFunction().
49: */
50: typedef struct {
51: PetscReal param; /* test problem parameter */
52: PetscInt mx; /* Discretization in x-direction */
53: PetscInt my; /* Discretization in y-direction */
54: } AppCtx;
56: /*
57: User-defined routines
58: */
59: extern PetscErrorCode FormJacobian(SNES,Vec,Mat*,Mat*,MatStructure*,void*);
60: extern PetscErrorCode FormFunction(SNES,Vec,Vec,void*);
61: extern PetscErrorCode FormInitialGuess(AppCtx*,Vec);
65: int main(int argc,char **argv)
66: {
67: SNES snes; /* nonlinear solver context */
68: Vec x,r; /* solution, residual vectors */
69: Mat J; /* Jacobian matrix */
70: AppCtx user; /* user-defined application context */
72: PetscInt i,its,N,hist_its[50];
73: PetscMPIInt size;
74: PetscReal bratu_lambda_max = 6.81,bratu_lambda_min = 0.,history[50];
75: MatFDColoring fdcoloring;
76: PetscBool matrix_free = PETSC_FALSE,flg,fd_coloring = PETSC_FALSE;
78: PetscInitialize(&argc,&argv,(char*)0,help);
79: MPI_Comm_size(PETSC_COMM_WORLD,&size);
80: if (size != 1) SETERRQ(PETSC_COMM_SELF,1,"This is a uniprocessor example only!");
82: /*
83: Initialize problem parameters
84: */
85: user.mx = 4; user.my = 4; user.param = 6.0;
86: PetscOptionsGetInt(NULL,"-mx",&user.mx,NULL);
87: PetscOptionsGetInt(NULL,"-my",&user.my,NULL);
88: PetscOptionsGetReal(NULL,"-par",&user.param,NULL);
89: if (user.param >= bratu_lambda_max || user.param <= bratu_lambda_min) SETERRQ(PETSC_COMM_SELF,1,"Lambda is out of range");
90: N = user.mx*user.my;
92: /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
93: Create nonlinear solver context
94: - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
96: SNESCreate(PETSC_COMM_WORLD,&snes);
98: /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
99: Create vector data structures; set function evaluation routine
100: - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
102: VecCreate(PETSC_COMM_WORLD,&x);
103: VecSetSizes(x,PETSC_DECIDE,N);
104: VecSetFromOptions(x);
105: VecDuplicate(x,&r);
107: /*
108: Set function evaluation routine and vector. Whenever the nonlinear
109: solver needs to evaluate the nonlinear function, it will call this
110: routine.
111: - Note that the final routine argument is the user-defined
112: context that provides application-specific data for the
113: function evaluation routine.
114: */
115: SNESSetFunction(snes,r,FormFunction,(void*)&user);
117: /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
118: Create matrix data structure; set Jacobian evaluation routine
119: - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
121: /*
122: Create matrix. Here we only approximately preallocate storage space
123: for the Jacobian. See the users manual for a discussion of better
124: techniques for preallocating matrix memory.
125: */
126: PetscOptionsGetBool(NULL,"-snes_mf",&matrix_free,NULL);
127: if (!matrix_free) {
128: PetscBool matrix_free_operator = PETSC_FALSE;
129: PetscOptionsGetBool(NULL,"-snes_mf_operator",&matrix_free_operator,NULL);
130: if (matrix_free_operator) matrix_free = PETSC_FALSE;
131: }
132: if (!matrix_free) {
133: MatCreateSeqAIJ(PETSC_COMM_WORLD,N,N,5,NULL,&J);
134: }
136: /*
137: This option will cause the Jacobian to be computed via finite differences
138: efficiently using a coloring of the columns of the matrix.
139: */
140: PetscOptionsGetBool(NULL,"-snes_fd_coloring",&fd_coloring,NULL);
141: if (matrix_free && fd_coloring) SETERRQ(PETSC_COMM_SELF,1,"Use only one of -snes_mf, -snes_fd_coloring options!\nYou can do -snes_mf_operator -snes_fd_coloring");
143: if (fd_coloring) {
144: ISColoring iscoloring;
145: MatStructure str;
147: /*
148: This initializes the nonzero structure of the Jacobian. This is artificial
149: because clearly if we had a routine to compute the Jacobian we won't need
150: to use finite differences.
151: */
152: FormJacobian(snes,x,&J,&J,&str,&user);
154: /*
155: Color the matrix, i.e. determine groups of columns that share no common
156: rows. These columns in the Jacobian can all be computed simulataneously.
157: */
158: MatGetColoring(J,MATCOLORINGNATURAL,&iscoloring);
159: /*
160: Create the data structure that SNESComputeJacobianDefaultColor() uses
161: to compute the actual Jacobians via finite differences.
162: */
163: MatFDColoringCreate(J,iscoloring,&fdcoloring);
164: MatFDColoringSetFunction(fdcoloring,(PetscErrorCode (*)(void))FormFunction,&user);
165: MatFDColoringSetFromOptions(fdcoloring);
166: /*
167: Tell SNES to use the routine SNESComputeJacobianDefaultColor()
168: to compute Jacobians.
169: */
170: SNESSetJacobian(snes,J,J,SNESComputeJacobianDefaultColor,fdcoloring);
171: ISColoringDestroy(&iscoloring);
172: }
173: /*
174: Set Jacobian matrix data structure and default Jacobian evaluation
175: routine. Whenever the nonlinear solver needs to compute the
176: Jacobian matrix, it will call this routine.
177: - Note that the final routine argument is the user-defined
178: context that provides application-specific data for the
179: Jacobian evaluation routine.
180: - The user can override with:
181: -snes_fd : default finite differencing approximation of Jacobian
182: -snes_mf : matrix-free Newton-Krylov method with no preconditioning
183: (unless user explicitly sets preconditioner)
184: -snes_mf_operator : form preconditioning matrix as set by the user,
185: but use matrix-free approx for Jacobian-vector
186: products within Newton-Krylov method
187: */
188: else if (!matrix_free) {
189: SNESSetJacobian(snes,J,J,FormJacobian,(void*)&user);
190: }
192: /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
193: Customize nonlinear solver; set runtime options
194: - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
196: /*
197: Set runtime options (e.g., -snes_monitor -snes_rtol <rtol> -ksp_type <type>)
198: */
199: SNESSetFromOptions(snes);
201: /*
202: Set array that saves the function norms. This array is intended
203: when the user wants to save the convergence history for later use
204: rather than just to view the function norms via -snes_monitor.
205: */
206: SNESSetConvergenceHistory(snes,history,hist_its,50,PETSC_TRUE);
208: /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
209: Evaluate initial guess; then solve nonlinear system
210: - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
211: /*
212: Note: The user should initialize the vector, x, with the initial guess
213: for the nonlinear solver prior to calling SNESSolve(). In particular,
214: to employ an initial guess of zero, the user should explicitly set
215: this vector to zero by calling VecSet().
216: */
217: FormInitialGuess(&user,x);
218: SNESSolve(snes,NULL,x);
219: SNESGetIterationNumber(snes,&its);
220: PetscPrintf(PETSC_COMM_WORLD,"Number of SNES iterations = %D\n",its);
223: /*
224: Print the convergence history. This is intended just to demonstrate
225: use of the data attained via SNESSetConvergenceHistory().
226: */
227: PetscOptionsHasName(NULL,"-print_history",&flg);
228: if (flg) {
229: for (i=0; i<its+1; i++) {
230: PetscPrintf(PETSC_COMM_WORLD,"iteration %D: Linear iterations %D Function norm = %G\n",i,hist_its[i],history[i]);
231: }
232: }
234: /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
235: Free work space. All PETSc objects should be destroyed when they
236: are no longer needed.
237: - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
239: if (!matrix_free) {
240: MatDestroy(&J);
241: }
242: if (fd_coloring) {
243: MatFDColoringDestroy(&fdcoloring);
244: }
245: VecDestroy(&x);
246: VecDestroy(&r);
247: SNESDestroy(&snes);
248: PetscFinalize();
250: return 0;
251: }
252: /* ------------------------------------------------------------------- */
255: /*
256: FormInitialGuess - Forms initial approximation.
258: Input Parameters:
259: user - user-defined application context
260: X - vector
262: Output Parameter:
263: X - vector
264: */
265: PetscErrorCode FormInitialGuess(AppCtx *user,Vec X)
266: {
267: PetscInt i,j,row,mx,my;
269: PetscReal lambda,temp1,temp,hx,hy;
270: PetscScalar *x;
272: mx = user->mx;
273: my = user->my;
274: lambda = user->param;
276: hx = 1.0 / (PetscReal)(mx-1);
277: hy = 1.0 / (PetscReal)(my-1);
279: /*
280: Get a pointer to vector data.
281: - For default PETSc vectors, VecGetArray() returns a pointer to
282: the data array. Otherwise, the routine is implementation dependent.
283: - You MUST call VecRestoreArray() when you no longer need access to
284: the array.
285: */
286: VecGetArray(X,&x);
287: temp1 = lambda/(lambda + 1.0);
288: for (j=0; j<my; j++) {
289: temp = (PetscReal)(PetscMin(j,my-j-1))*hy;
290: for (i=0; i<mx; i++) {
291: row = i + j*mx;
292: if (i == 0 || j == 0 || i == mx-1 || j == my-1) {
293: x[row] = 0.0;
294: continue;
295: }
296: x[row] = temp1*PetscSqrtReal(PetscMin((PetscReal)(PetscMin(i,mx-i-1))*hx,temp));
297: }
298: }
300: /*
301: Restore vector
302: */
303: VecRestoreArray(X,&x);
304: return 0;
305: }
306: /* ------------------------------------------------------------------- */
309: /*
310: FormFunction - Evaluates nonlinear function, F(x).
312: Input Parameters:
313: . snes - the SNES context
314: . X - input vector
315: . ptr - optional user-defined context, as set by SNESSetFunction()
317: Output Parameter:
318: . F - function vector
319: */
320: PetscErrorCode FormFunction(SNES snes,Vec X,Vec F,void *ptr)
321: {
322: AppCtx *user = (AppCtx*)ptr;
323: PetscInt i,j,row,mx,my;
325: PetscReal two = 2.0,one = 1.0,lambda,hx,hy,hxdhy,hydhx;
326: PetscScalar ut,ub,ul,ur,u,uxx,uyy,sc,*x,*f;
328: mx = user->mx;
329: my = user->my;
330: lambda = user->param;
331: hx = one / (PetscReal)(mx-1);
332: hy = one / (PetscReal)(my-1);
333: sc = hx*hy;
334: hxdhy = hx/hy;
335: hydhx = hy/hx;
337: /*
338: Get pointers to vector data
339: */
340: VecGetArray(X,&x);
341: VecGetArray(F,&f);
343: /*
344: Compute function
345: */
346: for (j=0; j<my; j++) {
347: for (i=0; i<mx; i++) {
348: row = i + j*mx;
349: if (i == 0 || j == 0 || i == mx-1 || j == my-1) {
350: f[row] = x[row];
351: continue;
352: }
353: u = x[row];
354: ub = x[row - mx];
355: ul = x[row - 1];
356: ut = x[row + mx];
357: ur = x[row + 1];
358: uxx = (-ur + two*u - ul)*hydhx;
359: uyy = (-ut + two*u - ub)*hxdhy;
360: f[row] = uxx + uyy - sc*lambda*PetscExpScalar(u);
361: }
362: }
364: /*
365: Restore vectors
366: */
367: VecRestoreArray(X,&x);
368: VecRestoreArray(F,&f);
369: return 0;
370: }
371: /* ------------------------------------------------------------------- */
374: /*
375: FormJacobian - Evaluates Jacobian matrix.
377: Input Parameters:
378: . snes - the SNES context
379: . x - input vector
380: . ptr - optional user-defined context, as set by SNESSetJacobian()
382: Output Parameters:
383: . A - Jacobian matrix
384: . B - optionally different preconditioning matrix
385: . flag - flag indicating matrix structure
386: */
387: PetscErrorCode FormJacobian(SNES snes,Vec X,Mat *J,Mat *B,MatStructure *flag,void *ptr)
388: {
389: AppCtx *user = (AppCtx*)ptr; /* user-defined applicatin context */
390: Mat jac = *B; /* Jacobian matrix */
391: PetscInt i,j,row,mx,my,col[5];
393: PetscScalar two = 2.0,one = 1.0,lambda,v[5],sc,*x;
394: PetscReal hx,hy,hxdhy,hydhx;
396: mx = user->mx;
397: my = user->my;
398: lambda = user->param;
399: hx = 1.0 / (PetscReal)(mx-1);
400: hy = 1.0 / (PetscReal)(my-1);
401: sc = hx*hy;
402: hxdhy = hx/hy;
403: hydhx = hy/hx;
405: /*
406: Get pointer to vector data
407: */
408: VecGetArray(X,&x);
410: /*
411: Compute entries of the Jacobian
412: */
413: for (j=0; j<my; j++) {
414: for (i=0; i<mx; i++) {
415: row = i + j*mx;
416: if (i == 0 || j == 0 || i == mx-1 || j == my-1) {
417: MatSetValues(jac,1,&row,1,&row,&one,INSERT_VALUES);
418: continue;
419: }
420: v[0] = -hxdhy; col[0] = row - mx;
421: v[1] = -hydhx; col[1] = row - 1;
422: v[2] = two*(hydhx + hxdhy) - sc*lambda*PetscExpScalar(x[row]); col[2] = row;
423: v[3] = -hydhx; col[3] = row + 1;
424: v[4] = -hxdhy; col[4] = row + mx;
425: MatSetValues(jac,1,&row,5,col,v,INSERT_VALUES);
426: }
427: }
429: /*
430: Restore vector
431: */
432: VecRestoreArray(X,&x);
434: /*
435: Assemble matrix
436: */
437: MatAssemblyBegin(jac,MAT_FINAL_ASSEMBLY);
438: MatAssemblyEnd(jac,MAT_FINAL_ASSEMBLY);
440: if (jac != *J) {
441: MatAssemblyBegin(*J,MAT_FINAL_ASSEMBLY);
442: MatAssemblyEnd(*J,MAT_FINAL_ASSEMBLY);
443: }
445: /*
446: Set flag to indicate that the Jacobian matrix retains an identical
447: nonzero structure throughout all nonlinear iterations (although the
448: values of the entries change). Thus, we can save some work in setting
449: up the preconditioner (e.g., no need to redo symbolic factorization for
450: ILU/ICC preconditioners).
451: - If the nonzero structure of the matrix is different during
452: successive linear solves, then the flag DIFFERENT_NONZERO_PATTERN
453: must be used instead. If you are unsure whether the matrix
454: structure has changed or not, use the flag DIFFERENT_NONZERO_PATTERN.
455: - Caution: If you specify SAME_NONZERO_PATTERN, PETSc
456: believes your assertion and does not check the structure
457: of the matrix. If you erroneously claim that the structure
458: is the same when it actually is not, the new preconditioner
459: will not function correctly. Thus, use this optimization
460: feature with caution!
461: */
462: *flag = SAME_NONZERO_PATTERN;
463: return 0;
464: }