Actual source code: ex15.c
1: static const char help[] = "p-Bratu nonlinear PDE in 2d.\n\
2: We solve the p-Laplacian (nonlinear diffusion) combined with\n\
3: the Bratu (solid fuel ignition) nonlinearity in a 2D rectangular\n\
4: domain, using distributed arrays (DAs) to partition the parallel grid.\n\
5: The command line options include:\n\
6: -p <2>: `p' in p-Laplacian term\n\
7: -epsilon <1e-05>: Strain-regularization in p-Laplacian\n\
8: -lambda <6>: Bratu parameter\n\
9: -blocks <bx,by>: number of coefficient interfaces in x and y direction\n\
10: -kappa <1e-3>: diffusivity in odd regions\n\
11: \n";
13: /*F
14: The $p$-Bratu problem is a combination of the $p$-Laplacian (nonlinear diffusion) and the Bratu solid fuel ignition problem.
15: This problem is modeled by the partial differential equation
17: \begin{equation*}
18: -\nabla\cdot (\eta \nabla u) - \lambda \exp(u) = 0
19: \end{equation*}
21: on $\Omega = (-1,1)^2$ with closure
23: \begin{align*}
24: \eta(\gamma) &= (\epsilon^2 + \gamma)^{(p-2)/2} & \gamma &= \frac 1 2 |\nabla u|^2
25: \end{align*}
27: and boundary conditions $u = 0$ for $(x,y) \in \partial \Omega$
29: A 9-point finite difference stencil is used to discretize
30: the boundary value problem to obtain a nonlinear system of equations.
31: This would be a 5-point stencil if not for the $p$-Laplacian's nonlinearity.
32: F*/
34: /*
35: mpiexec -n 2 ./ex15 -snes_monitor -ksp_monitor log_view
36: */
38: /*
39: Include "petscdmda.h" so that we can use distributed arrays (DMDAs).
40: Include "petscsnes.h" so that we can use SNES solvers. Note that this
41: file automatically includes:
42: petscsys.h - system routines
43: petscvec.h - vectors
44: petscmat.h - matrices
45: petscis.h - index sets
46: petscpc.h - preconditioners
47: petscksp.h - linear solvers
48: */
50: #include <petscdm.h>
51: #include <petscdmda.h>
52: #include <petscsnes.h>
54: typedef enum {
55: JAC_BRATU,
56: JAC_PICARD,
57: JAC_STAR,
58: JAC_NEWTON
59: } JacType;
60: static const char *const JacTypes[] = {"BRATU", "PICARD", "STAR", "NEWTON", "JacType", "JAC_", NULL};
62: /*
63: User-defined application context - contains data needed by the
64: application-provided call-back routines, FormJacobianLocal() and
65: FormFunctionLocal().
66: */
67: typedef struct {
68: PetscReal lambda; /* Bratu parameter */
69: PetscReal p; /* Exponent in p-Laplacian */
70: PetscReal epsilon; /* Regularization */
71: PetscReal source; /* Source term */
72: JacType jtype; /* What type of Jacobian to assemble */
73: PetscBool picard;
74: PetscInt blocks[2];
75: PetscReal kappa;
76: PetscInt initial; /* initial conditions type */
77: } AppCtx;
79: /*
80: User-defined routines
81: */
82: static PetscErrorCode FormRHS(AppCtx *, DM, Vec);
83: static PetscErrorCode FormInitialGuess(AppCtx *, DM, Vec);
84: static PetscErrorCode FormFunctionLocal(DMDALocalInfo *, PetscScalar **, PetscScalar **, AppCtx *);
85: static PetscErrorCode FormFunctionPicardLocal(DMDALocalInfo *, PetscScalar **, PetscScalar **, AppCtx *);
86: static PetscErrorCode FormJacobianLocal(DMDALocalInfo *, PetscScalar **, Mat, Mat, AppCtx *);
87: static PetscErrorCode NonlinearGS(SNES, Vec, Vec, void *);
89: typedef struct _n_PreCheck *PreCheck;
90: struct _n_PreCheck {
91: MPI_Comm comm;
92: PetscReal angle;
93: Vec Ylast;
94: PetscViewer monitor;
95: };
96: PetscErrorCode PreCheckCreate(MPI_Comm, PreCheck *);
97: PetscErrorCode PreCheckDestroy(PreCheck *);
98: PetscErrorCode PreCheckFunction(SNESLineSearch, Vec, Vec, PetscBool *, void *);
99: PetscErrorCode PreCheckSetFromOptions(PreCheck);
101: int main(int argc, char **argv)
102: {
103: SNES snes; /* nonlinear solver */
104: Vec x, r, b; /* solution, residual, rhs vectors */
105: AppCtx user; /* user-defined work context */
106: PetscInt its; /* iterations for convergence */
107: SNESConvergedReason reason; /* Check convergence */
108: PetscBool alloc_star; /* Only allocate for the STAR stencil */
109: PetscBool write_output;
110: char filename[PETSC_MAX_PATH_LEN] = "ex15.vts";
111: PetscReal bratu_lambda_max = 6.81, bratu_lambda_min = 0.;
112: DM da; /* distributed array data structure */
113: PreCheck precheck = NULL; /* precheck context for version in this file */
114: PetscInt use_precheck; /* 0=none, 1=version in this file, 2=SNES-provided version */
115: PetscReal precheck_angle; /* When manually setting the SNES-provided precheck function */
116: SNESLineSearch linesearch;
118: /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
119: Initialize program
120: - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
122: PetscFunctionBeginUser;
123: PetscCall(PetscInitialize(&argc, &argv, NULL, help));
125: /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
126: Initialize problem parameters
127: - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
128: user.lambda = 0.0;
129: user.p = 2.0;
130: user.epsilon = 1e-5;
131: user.source = 0.1;
132: user.jtype = JAC_NEWTON;
133: user.initial = -1;
134: user.blocks[0] = 1;
135: user.blocks[1] = 1;
136: user.kappa = 1e-3;
137: alloc_star = PETSC_FALSE;
138: use_precheck = 0;
139: precheck_angle = 10.;
140: user.picard = PETSC_FALSE;
141: PetscOptionsBegin(PETSC_COMM_WORLD, NULL, "p-Bratu options", __FILE__);
142: {
143: PetscInt two = 2;
144: PetscCall(PetscOptionsReal("-lambda", "Bratu parameter", "", user.lambda, &user.lambda, NULL));
145: PetscCall(PetscOptionsReal("-p", "Exponent `p' in p-Laplacian", "", user.p, &user.p, NULL));
146: PetscCall(PetscOptionsReal("-epsilon", "Strain-regularization in p-Laplacian", "", user.epsilon, &user.epsilon, NULL));
147: PetscCall(PetscOptionsReal("-source", "Constant source term", "", user.source, &user.source, NULL));
148: PetscCall(PetscOptionsEnum("-jtype", "Jacobian approximation to assemble", "", JacTypes, (PetscEnum)user.jtype, (PetscEnum *)&user.jtype, NULL));
149: PetscCall(PetscOptionsName("-picard", "Solve with defect-correction Picard iteration", "", &user.picard));
150: if (user.picard) {
151: user.jtype = JAC_PICARD;
152: PetscCheck(user.p == 3, PETSC_COMM_WORLD, PETSC_ERR_SUP, "Picard iteration is only supported for p == 3");
153: /* the Picard linearization only requires a 5 point stencil, while the Newton linearization requires a 9 point stencil */
154: /* hence allocating the 5 point stencil gives the same convergence as the 9 point stencil since the extra stencil points are not used */
155: PetscCall(PetscOptionsBool("-alloc_star", "Allocate for STAR stencil (5-point)", "", alloc_star, &alloc_star, NULL));
156: }
157: PetscCall(PetscOptionsInt("-precheck", "Use a pre-check correction intended for use with Picard iteration 1=this version, 2=library", "", use_precheck, &use_precheck, NULL));
158: PetscCall(PetscOptionsInt("-initial", "Initial conditions type (-1: default, 0: zero-valued, 1: peaked guess)", "", user.initial, &user.initial, NULL));
159: if (use_precheck == 2) { /* Using library version, get the angle */
160: PetscCall(PetscOptionsReal("-precheck_angle", "Angle in degrees between successive search directions necessary to activate step correction", "", precheck_angle, &precheck_angle, NULL));
161: }
162: PetscCall(PetscOptionsIntArray("-blocks", "number of coefficient interfaces in x and y direction", "", user.blocks, &two, NULL));
163: PetscCall(PetscOptionsReal("-kappa", "diffusivity in odd regions", "", user.kappa, &user.kappa, NULL));
164: PetscCall(PetscOptionsString("-o", "Output solution in vts format", "", filename, filename, sizeof(filename), &write_output));
165: }
166: PetscOptionsEnd();
167: if (user.lambda > bratu_lambda_max || user.lambda < bratu_lambda_min) PetscCall(PetscPrintf(PETSC_COMM_WORLD, "WARNING: lambda %g out of range for p=2\n", (double)user.lambda));
169: /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
170: Create nonlinear solver context
171: - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
172: PetscCall(SNESCreate(PETSC_COMM_WORLD, &snes));
174: /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
175: Create distributed array (DMDA) to manage parallel grid and vectors
176: - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
177: PetscCall(DMDACreate2d(PETSC_COMM_WORLD, DM_BOUNDARY_NONE, DM_BOUNDARY_NONE, alloc_star ? DMDA_STENCIL_STAR : DMDA_STENCIL_BOX, 4, 4, PETSC_DECIDE, PETSC_DECIDE, 1, 1, NULL, NULL, &da));
178: PetscCall(DMSetFromOptions(da));
179: PetscCall(DMSetUp(da));
181: /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
182: Extract global vectors from DM; then duplicate for remaining
183: vectors that are the same types
184: - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
185: PetscCall(DMCreateGlobalVector(da, &x));
186: PetscCall(VecDuplicate(x, &r));
187: PetscCall(VecDuplicate(x, &b));
189: /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
190: User can override with:
191: -snes_mf : matrix-free Newton-Krylov method with no preconditioning
192: (unless user explicitly sets preconditioner)
193: -snes_mf_operator : form matrix used to construct the preconditioner as set by the user,
194: but use matrix-free approx for Jacobian-vector
195: products within Newton-Krylov method
197: - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
199: /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
200: Set local function evaluation routine
201: - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
202: PetscCall(DMSetApplicationContext(da, &user));
203: PetscCall(SNESSetDM(snes, da));
204: if (user.picard) {
205: /*
206: This is not really right requiring the user to call SNESSetFunction/Jacobian but the DMDASNESSetPicardLocal() cannot access
207: the SNES to set it
208: */
209: PetscCall(DMDASNESSetPicardLocal(da, INSERT_VALUES, (PetscErrorCode (*)(DMDALocalInfo *, void *, void *, PetscCtx))FormFunctionPicardLocal, (PetscErrorCode (*)(DMDALocalInfo *, void *, Mat, Mat, PetscCtx))FormJacobianLocal, &user));
210: PetscCall(SNESSetFunction(snes, NULL, SNESPicardComputeFunction, &user));
211: PetscCall(SNESSetJacobian(snes, NULL, NULL, SNESPicardComputeJacobian, &user));
212: } else {
213: PetscCall(DMDASNESSetFunctionLocal(da, INSERT_VALUES, (DMDASNESFunctionFn *)FormFunctionLocal, &user));
214: PetscCall(DMDASNESSetJacobianLocal(da, (DMDASNESJacobianFn *)FormJacobianLocal, &user));
215: }
217: /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
218: Customize nonlinear solver; set runtime options
219: - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
220: PetscCall(SNESSetFromOptions(snes));
221: PetscCall(SNESSetNGS(snes, NonlinearGS, &user));
222: PetscCall(SNESGetLineSearch(snes, &linesearch));
223: /* Set up the precheck context if requested */
224: if (use_precheck == 1) { /* Use the precheck routines in this file */
225: PetscCall(PreCheckCreate(PETSC_COMM_WORLD, &precheck));
226: PetscCall(PreCheckSetFromOptions(precheck));
227: PetscCall(SNESLineSearchSetPreCheck(linesearch, PreCheckFunction, precheck));
228: } else if (use_precheck == 2) { /* Use the version provided by the library */
229: PetscCall(SNESLineSearchSetPreCheck(linesearch, SNESLineSearchPreCheckPicard, &precheck_angle));
230: }
232: /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
233: Evaluate initial guess
234: Note: The user should initialize the vector, x, with the initial guess
235: for the nonlinear solver prior to calling SNESSolve(). In particular,
236: to employ an initial guess of zero, the user should explicitly set
237: this vector to zero by calling VecSet().
238: */
240: PetscCall(FormInitialGuess(&user, da, x));
241: PetscCall(FormRHS(&user, da, b));
243: /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
244: Solve nonlinear system
245: - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
246: PetscCall(SNESSolve(snes, b, x));
247: PetscCall(SNESGetIterationNumber(snes, &its));
248: PetscCall(SNESGetConvergedReason(snes, &reason));
250: PetscCall(PetscPrintf(PETSC_COMM_WORLD, "%s Number of nonlinear iterations = %" PetscInt_FMT "\n", SNESConvergedReasons[reason], its));
252: if (write_output) {
253: PetscViewer viewer;
254: PetscCall(PetscViewerVTKOpen(PETSC_COMM_WORLD, filename, FILE_MODE_WRITE, &viewer));
255: PetscCall(VecView(x, viewer));
256: PetscCall(PetscViewerDestroy(&viewer));
257: }
259: /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
260: Free work space. All PETSc objects should be destroyed when they
261: are no longer needed.
262: - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
264: PetscCall(VecDestroy(&x));
265: PetscCall(VecDestroy(&r));
266: PetscCall(VecDestroy(&b));
267: PetscCall(SNESDestroy(&snes));
268: PetscCall(DMDestroy(&da));
269: PetscCall(PreCheckDestroy(&precheck));
270: PetscCall(PetscFinalize());
271: return 0;
272: }
274: /* ------------------------------------------------------------------- */
275: /*
276: FormInitialGuess - Forms initial approximation.
278: Input Parameters:
279: user - user-defined application context
280: X - vector
282: Output Parameter:
283: X - vector
284: */
285: static PetscErrorCode FormInitialGuess(AppCtx *user, DM da, Vec X)
286: {
287: PetscInt i, j, Mx, My, xs, ys, xm, ym;
288: PetscReal temp1, temp, hx, hy;
289: PetscScalar **x;
291: PetscFunctionBeginUser;
292: PetscCall(DMDAGetInfo(da, PETSC_IGNORE, &Mx, &My, PETSC_IGNORE, PETSC_IGNORE, PETSC_IGNORE, PETSC_IGNORE, PETSC_IGNORE, PETSC_IGNORE, PETSC_IGNORE, PETSC_IGNORE, PETSC_IGNORE, PETSC_IGNORE));
294: hx = 1.0 / (PetscReal)(Mx - 1);
295: hy = 1.0 / (PetscReal)(My - 1);
296: temp1 = user->lambda / (user->lambda + 1.);
298: /*
299: Get a pointer to vector data.
300: - For default PETSc vectors, VecGetArray() returns a pointer to
301: the data array. Otherwise, the routine is implementation dependent.
302: - You MUST call VecRestoreArray() when you no longer need access to
303: the array.
304: */
305: PetscCall(DMDAVecGetArray(da, X, &x));
307: /*
308: Get local grid boundaries (for 2-dimensional DA):
309: xs, ys - starting grid indices (no ghost points)
310: xm, ym - widths of local grid (no ghost points)
312: */
313: PetscCall(DMDAGetCorners(da, &xs, &ys, NULL, &xm, &ym, NULL));
315: /*
316: Compute initial guess over the locally owned part of the grid
317: */
318: for (j = ys; j < ys + ym; j++) {
319: temp = (PetscReal)(PetscMin(j, My - j - 1)) * hy;
320: for (i = xs; i < xs + xm; i++) {
321: if (i == 0 || j == 0 || i == Mx - 1 || j == My - 1) {
322: /* boundary conditions are all zero Dirichlet */
323: x[j][i] = 0.0;
324: } else {
325: if (user->initial == -1) {
326: if (user->lambda != 0) {
327: x[j][i] = temp1 * PetscSqrtReal(PetscMin((PetscReal)(PetscMin(i, Mx - i - 1)) * hx, temp));
328: } else {
329: /* The solution above is an exact solution for lambda=0, this avoids "accidentally" starting
330: * with an exact solution. */
331: const PetscReal xx = 2 * (PetscReal)i / (Mx - 1) - 1, yy = 2 * (PetscReal)j / (My - 1) - 1;
332: x[j][i] = (1 - xx * xx) * (1 - yy * yy) * xx * yy;
333: }
334: } else if (user->initial == 0) {
335: x[j][i] = 0.;
336: } else if (user->initial == 1) {
337: const PetscReal xx = 2 * (PetscReal)i / (Mx - 1) - 1, yy = 2 * (PetscReal)j / (My - 1) - 1;
338: x[j][i] = (1 - xx * xx) * (1 - yy * yy) * xx * yy;
339: } else {
340: if (user->lambda != 0) {
341: x[j][i] = temp1 * PetscSqrtReal(PetscMin((PetscReal)(PetscMin(i, Mx - i - 1)) * hx, temp));
342: } else {
343: x[j][i] = 0.5 * PetscSqrtReal(PetscMin((PetscReal)(PetscMin(i, Mx - i - 1)) * hx, temp));
344: }
345: }
346: }
347: }
348: }
349: /*
350: Restore vector
351: */
352: PetscCall(DMDAVecRestoreArray(da, X, &x));
353: PetscFunctionReturn(PETSC_SUCCESS);
354: }
356: /*
357: FormRHS - Forms constant RHS for the problem.
359: Input Parameters:
360: user - user-defined application context
361: B - RHS vector
363: Output Parameter:
364: B - vector
365: */
366: static PetscErrorCode FormRHS(AppCtx *user, DM da, Vec B)
367: {
368: PetscInt i, j, Mx, My, xs, ys, xm, ym;
369: PetscReal hx, hy;
370: PetscScalar **b;
372: PetscFunctionBeginUser;
373: PetscCall(DMDAGetInfo(da, PETSC_IGNORE, &Mx, &My, PETSC_IGNORE, PETSC_IGNORE, PETSC_IGNORE, PETSC_IGNORE, PETSC_IGNORE, PETSC_IGNORE, PETSC_IGNORE, PETSC_IGNORE, PETSC_IGNORE, PETSC_IGNORE));
375: hx = 1.0 / (PetscReal)(Mx - 1);
376: hy = 1.0 / (PetscReal)(My - 1);
377: PetscCall(DMDAVecGetArray(da, B, &b));
378: PetscCall(DMDAGetCorners(da, &xs, &ys, NULL, &xm, &ym, NULL));
379: for (j = ys; j < ys + ym; j++) {
380: for (i = xs; i < xs + xm; i++) {
381: if (i == 0 || j == 0 || i == Mx - 1 || j == My - 1) {
382: b[j][i] = 0.0;
383: } else {
384: b[j][i] = hx * hy * user->source;
385: }
386: }
387: }
388: PetscCall(DMDAVecRestoreArray(da, B, &b));
389: PetscFunctionReturn(PETSC_SUCCESS);
390: }
392: static inline PetscReal kappa(const AppCtx *ctx, PetscReal x, PetscReal y)
393: {
394: return (((PetscInt)(x * ctx->blocks[0])) + ((PetscInt)(y * ctx->blocks[1]))) % 2 ? ctx->kappa : 1.0;
395: }
396: /* p-Laplacian diffusivity */
397: static inline PetscScalar eta(const AppCtx *ctx, PetscReal x, PetscReal y, PetscScalar ux, PetscScalar uy)
398: {
399: return kappa(ctx, x, y) * PetscPowScalar(PetscSqr(ctx->epsilon) + 0.5 * (ux * ux + uy * uy), 0.5 * (ctx->p - 2.));
400: }
401: static inline PetscScalar deta(const AppCtx *ctx, PetscReal x, PetscReal y, PetscScalar ux, PetscScalar uy)
402: {
403: return (ctx->p == 2) ? 0 : kappa(ctx, x, y) * PetscPowScalar(PetscSqr(ctx->epsilon) + 0.5 * (ux * ux + uy * uy), 0.5 * (ctx->p - 4)) * 0.5 * (ctx->p - 2.);
404: }
406: /* ------------------------------------------------------------------- */
407: /*
408: FormFunctionLocal - Evaluates nonlinear function, F(x).
409: */
410: static PetscErrorCode FormFunctionLocal(DMDALocalInfo *info, PetscScalar **x, PetscScalar **f, AppCtx *user)
411: {
412: PetscReal hx, hy, dhx, dhy, sc;
413: PetscInt i, j;
414: PetscScalar eu;
416: PetscFunctionBeginUser;
417: hx = 1.0 / (PetscReal)(info->mx - 1);
418: hy = 1.0 / (PetscReal)(info->my - 1);
419: sc = hx * hy * user->lambda;
420: dhx = 1 / hx;
421: dhy = 1 / hy;
422: /*
423: Compute function over the locally owned part of the grid
424: */
425: for (j = info->ys; j < info->ys + info->ym; j++) {
426: for (i = info->xs; i < info->xs + info->xm; i++) {
427: PetscReal xx = i * hx, yy = j * hy;
428: if (i == 0 || j == 0 || i == info->mx - 1 || j == info->my - 1) {
429: f[j][i] = x[j][i];
430: } else {
431: const PetscScalar u = x[j][i], ux_E = dhx * (x[j][i + 1] - x[j][i]), uy_E = 0.25 * dhy * (x[j + 1][i] + x[j + 1][i + 1] - x[j - 1][i] - x[j - 1][i + 1]), ux_W = dhx * (x[j][i] - x[j][i - 1]), uy_W = 0.25 * dhy * (x[j + 1][i - 1] + x[j + 1][i] - x[j - 1][i - 1] - x[j - 1][i]), ux_N = 0.25 * dhx * (x[j][i + 1] + x[j + 1][i + 1] - x[j][i - 1] - x[j + 1][i - 1]), uy_N = dhy * (x[j + 1][i] - x[j][i]), ux_S = 0.25 * dhx * (x[j - 1][i + 1] + x[j][i + 1] - x[j - 1][i - 1] - x[j][i - 1]), uy_S = dhy * (x[j][i] - x[j - 1][i]), e_E = eta(user, xx, yy, ux_E, uy_E), e_W = eta(user, xx, yy, ux_W, uy_W), e_N = eta(user, xx, yy, ux_N, uy_N), e_S = eta(user, xx, yy, ux_S, uy_S), uxx = -hy * (e_E * ux_E - e_W * ux_W), uyy = -hx * (e_N * uy_N - e_S * uy_S);
432: if (sc) eu = PetscExpScalar(u);
433: else eu = 0.;
434: /* For p=2, these terms decay to:
435: uxx = (2.0*u - x[j][i-1] - x[j][i+1])*hydhx
436: uyy = (2.0*u - x[j-1][i] - x[j+1][i])*hxdhy
437: */
438: f[j][i] = uxx + uyy - sc * eu;
439: }
440: }
441: }
442: PetscCall(PetscLogFlops(info->xm * info->ym * (72.0)));
443: PetscFunctionReturn(PETSC_SUCCESS);
444: }
446: /*
447: This is the opposite sign of the part of FormFunctionLocal that excludes the A(x) x part of the operation,
448: that is FormFunction applies A(x) x - b(x) while this applies b(x) because for Picard we think of it as solving A(x) x = b(x)
450: */
451: static PetscErrorCode FormFunctionPicardLocal(DMDALocalInfo *info, PetscScalar **x, PetscScalar **f, AppCtx *user)
452: {
453: PetscReal hx, hy, sc;
454: PetscInt i, j;
456: PetscFunctionBeginUser;
457: hx = 1.0 / (PetscReal)(info->mx - 1);
458: hy = 1.0 / (PetscReal)(info->my - 1);
459: sc = hx * hy * user->lambda;
460: /*
461: Compute function over the locally owned part of the grid
462: */
463: for (j = info->ys; j < info->ys + info->ym; j++) {
464: for (i = info->xs; i < info->xs + info->xm; i++) {
465: if (!(i == 0 || j == 0 || i == info->mx - 1 || j == info->my - 1)) {
466: const PetscScalar u = x[j][i];
467: f[j][i] = sc * PetscExpScalar(u);
468: } else {
469: f[j][i] = 0.0; /* this is zero because the A(x) x term forces the x to be zero on the boundary */
470: }
471: }
472: }
473: PetscCall(PetscLogFlops(info->xm * info->ym * 2.0));
474: PetscFunctionReturn(PETSC_SUCCESS);
475: }
477: /*
478: FormJacobianLocal - Evaluates Jacobian matrix.
479: */
480: static PetscErrorCode FormJacobianLocal(DMDALocalInfo *info, PetscScalar **x, Mat J, Mat B, AppCtx *user)
481: {
482: PetscInt i, j;
483: MatStencil col[9], row;
484: PetscScalar v[9];
485: PetscReal hx, hy, hxdhy, hydhx, dhx, dhy, sc;
487: PetscFunctionBeginUser;
488: PetscCall(MatZeroEntries(B));
489: hx = 1.0 / (PetscReal)(info->mx - 1);
490: hy = 1.0 / (PetscReal)(info->my - 1);
491: sc = hx * hy * user->lambda;
492: dhx = 1 / hx;
493: dhy = 1 / hy;
494: hxdhy = hx / hy;
495: hydhx = hy / hx;
497: /*
498: Compute entries for the locally owned part of the Jacobian.
499: - PETSc parallel matrix formats are partitioned by
500: contiguous chunks of rows across the processors.
501: - Each processor needs to insert only elements that it owns
502: locally (but any non-local elements will be sent to the
503: appropriate processor during matrix assembly).
504: - Here, we set all entries for a particular row at once.
505: */
506: for (j = info->ys; j < info->ys + info->ym; j++) {
507: for (i = info->xs; i < info->xs + info->xm; i++) {
508: PetscReal xx = i * hx, yy = j * hy;
509: row.j = j;
510: row.i = i;
511: /* boundary points */
512: if (i == 0 || j == 0 || i == info->mx - 1 || j == info->my - 1) {
513: v[0] = 1.0;
514: PetscCall(MatSetValuesStencil(B, 1, &row, 1, &row, v, INSERT_VALUES));
515: } else {
516: /* interior grid points */
517: const PetscScalar ux_E = dhx * (x[j][i + 1] - x[j][i]), uy_E = 0.25 * dhy * (x[j + 1][i] + x[j + 1][i + 1] - x[j - 1][i] - x[j - 1][i + 1]), ux_W = dhx * (x[j][i] - x[j][i - 1]), uy_W = 0.25 * dhy * (x[j + 1][i - 1] + x[j + 1][i] - x[j - 1][i - 1] - x[j - 1][i]), ux_N = 0.25 * dhx * (x[j][i + 1] + x[j + 1][i + 1] - x[j][i - 1] - x[j + 1][i - 1]), uy_N = dhy * (x[j + 1][i] - x[j][i]), ux_S = 0.25 * dhx * (x[j - 1][i + 1] + x[j][i + 1] - x[j - 1][i - 1] - x[j][i - 1]), uy_S = dhy * (x[j][i] - x[j - 1][i]), u = x[j][i], e_E = eta(user, xx, yy, ux_E, uy_E), e_W = eta(user, xx, yy, ux_W, uy_W), e_N = eta(user, xx, yy, ux_N, uy_N), e_S = eta(user, xx, yy, ux_S, uy_S), de_E = deta(user, xx, yy, ux_E, uy_E), de_W = deta(user, xx, yy, ux_W, uy_W), de_N = deta(user, xx, yy, ux_N, uy_N), de_S = deta(user, xx, yy, ux_S, uy_S), skew_E = de_E * ux_E * uy_E, skew_W = de_W * ux_W * uy_W, skew_N = de_N * ux_N * uy_N, skew_S = de_S * ux_S * uy_S, cross_EW = 0.25 * (skew_E - skew_W), cross_NS = 0.25 * (skew_N - skew_S), newt_E = e_E + de_E * PetscSqr(ux_E), newt_W = e_W + de_W * PetscSqr(ux_W), newt_N = e_N + de_N * PetscSqr(uy_N), newt_S = e_S + de_S * PetscSqr(uy_S);
518: /* interior grid points */
519: switch (user->jtype) {
520: case JAC_BRATU:
521: /* Jacobian from p=2 */
522: v[0] = -hxdhy;
523: col[0].j = j - 1;
524: col[0].i = i;
525: v[1] = -hydhx;
526: col[1].j = j;
527: col[1].i = i - 1;
528: v[2] = 2.0 * (hydhx + hxdhy) - sc * PetscExpScalar(u);
529: col[2].j = row.j;
530: col[2].i = row.i;
531: v[3] = -hydhx;
532: col[3].j = j;
533: col[3].i = i + 1;
534: v[4] = -hxdhy;
535: col[4].j = j + 1;
536: col[4].i = i;
537: PetscCall(MatSetValuesStencil(B, 1, &row, 5, col, v, INSERT_VALUES));
538: break;
539: case JAC_PICARD:
540: /* Jacobian arising from Picard linearization */
541: v[0] = -hxdhy * e_S;
542: col[0].j = j - 1;
543: col[0].i = i;
544: v[1] = -hydhx * e_W;
545: col[1].j = j;
546: col[1].i = i - 1;
547: v[2] = (e_W + e_E) * hydhx + (e_S + e_N) * hxdhy;
548: col[2].j = row.j;
549: col[2].i = row.i;
550: v[3] = -hydhx * e_E;
551: col[3].j = j;
552: col[3].i = i + 1;
553: v[4] = -hxdhy * e_N;
554: col[4].j = j + 1;
555: col[4].i = i;
556: PetscCall(MatSetValuesStencil(B, 1, &row, 5, col, v, INSERT_VALUES));
557: break;
558: case JAC_STAR:
559: /* Full Jacobian, but only a star stencil */
560: col[0].j = j - 1;
561: col[0].i = i;
562: col[1].j = j;
563: col[1].i = i - 1;
564: col[2].j = j;
565: col[2].i = i;
566: col[3].j = j;
567: col[3].i = i + 1;
568: col[4].j = j + 1;
569: col[4].i = i;
570: v[0] = -hxdhy * newt_S + cross_EW;
571: v[1] = -hydhx * newt_W + cross_NS;
572: v[2] = hxdhy * (newt_N + newt_S) + hydhx * (newt_E + newt_W) - sc * PetscExpScalar(u);
573: v[3] = -hydhx * newt_E - cross_NS;
574: v[4] = -hxdhy * newt_N - cross_EW;
575: PetscCall(MatSetValuesStencil(B, 1, &row, 5, col, v, INSERT_VALUES));
576: break;
577: case JAC_NEWTON:
578: /* The Jacobian is
580: -div [ eta (grad u) + deta (grad u0 . grad u) grad u0 ] - (eE u0) u
582: */
583: col[0].j = j - 1;
584: col[0].i = i - 1;
585: col[1].j = j - 1;
586: col[1].i = i;
587: col[2].j = j - 1;
588: col[2].i = i + 1;
589: col[3].j = j;
590: col[3].i = i - 1;
591: col[4].j = j;
592: col[4].i = i;
593: col[5].j = j;
594: col[5].i = i + 1;
595: col[6].j = j + 1;
596: col[6].i = i - 1;
597: col[7].j = j + 1;
598: col[7].i = i;
599: col[8].j = j + 1;
600: col[8].i = i + 1;
601: v[0] = -0.25 * (skew_S + skew_W);
602: v[1] = -hxdhy * newt_S + cross_EW;
603: v[2] = 0.25 * (skew_S + skew_E);
604: v[3] = -hydhx * newt_W + cross_NS;
605: v[4] = hxdhy * (newt_N + newt_S) + hydhx * (newt_E + newt_W) - sc * PetscExpScalar(u);
606: v[5] = -hydhx * newt_E - cross_NS;
607: v[6] = 0.25 * (skew_N + skew_W);
608: v[7] = -hxdhy * newt_N - cross_EW;
609: v[8] = -0.25 * (skew_N + skew_E);
610: PetscCall(MatSetValuesStencil(B, 1, &row, 9, col, v, INSERT_VALUES));
611: break;
612: default:
613: SETERRQ(PetscObjectComm((PetscObject)info->da), PETSC_ERR_SUP, "Jacobian type %d not implemented", user->jtype);
614: }
615: }
616: }
617: }
619: /*
620: Assemble matrix, using the 2-step process:
621: MatAssemblyBegin(), MatAssemblyEnd().
622: */
623: PetscCall(MatAssemblyBegin(B, MAT_FINAL_ASSEMBLY));
624: PetscCall(MatAssemblyEnd(B, MAT_FINAL_ASSEMBLY));
626: if (J != B) {
627: PetscCall(MatAssemblyBegin(J, MAT_FINAL_ASSEMBLY));
628: PetscCall(MatAssemblyEnd(J, MAT_FINAL_ASSEMBLY));
629: }
631: /*
632: Tell the matrix we will never add a new nonzero location to the
633: matrix. If we do, it will generate an error.
634: */
635: if (user->jtype == JAC_NEWTON) PetscCall(PetscLogFlops(info->xm * info->ym * (131.0)));
636: PetscFunctionReturn(PETSC_SUCCESS);
637: }
639: /***********************************************************
640: * PreCheck implementation
641: ***********************************************************/
642: PetscErrorCode PreCheckSetFromOptions(PreCheck precheck)
643: {
644: PetscBool flg;
646: PetscFunctionBeginUser;
647: PetscOptionsBegin(precheck->comm, NULL, "PreCheck Options", "none");
648: PetscCall(PetscOptionsReal("-precheck_angle", "Angle in degrees between successive search directions necessary to activate step correction", "", precheck->angle, &precheck->angle, NULL));
649: flg = PETSC_FALSE;
650: PetscCall(PetscOptionsBool("-precheck_monitor", "Monitor choices made by precheck routine", "", flg, &flg, NULL));
651: if (flg) PetscCall(PetscViewerASCIIOpen(precheck->comm, "stdout", &precheck->monitor));
652: PetscOptionsEnd();
653: PetscFunctionReturn(PETSC_SUCCESS);
654: }
656: /*
657: Compare the direction of the current and previous step, modify the current step accordingly
658: */
659: PetscErrorCode PreCheckFunction(SNESLineSearch linesearch, Vec X, Vec Y, PetscBool *changed, PetscCtx ctx)
660: {
661: PreCheck precheck;
662: Vec Ylast;
663: PetscScalar dot;
664: PetscInt iter;
665: PetscReal ynorm, ylastnorm, theta, angle_radians;
666: SNES snes;
668: PetscFunctionBeginUser;
669: PetscCall(SNESLineSearchGetSNES(linesearch, &snes));
670: precheck = (PreCheck)ctx;
671: if (!precheck->Ylast) PetscCall(VecDuplicate(Y, &precheck->Ylast));
672: Ylast = precheck->Ylast;
673: PetscCall(SNESGetIterationNumber(snes, &iter));
674: if (iter < 1) {
675: PetscCall(VecCopy(Y, Ylast));
676: *changed = PETSC_FALSE;
677: PetscFunctionReturn(PETSC_SUCCESS);
678: }
680: PetscCall(VecDot(Y, Ylast, &dot));
681: PetscCall(VecNorm(Y, NORM_2, &ynorm));
682: PetscCall(VecNorm(Ylast, NORM_2, &ylastnorm));
683: /* Compute the angle between the vectors Y and Ylast, clip to keep inside the domain of acos() */
684: theta = PetscAcosReal((PetscReal)PetscClipInterval(PetscAbsScalar(dot) / (ynorm * ylastnorm), -1.0, 1.0));
685: angle_radians = precheck->angle * PETSC_PI / 180.;
686: if (PetscAbsReal(theta) < angle_radians || PetscAbsReal(theta - PETSC_PI) < angle_radians) {
687: /* Modify the step Y */
688: PetscReal alpha, ydiffnorm;
689: PetscCall(VecAXPY(Ylast, -1.0, Y));
690: PetscCall(VecNorm(Ylast, NORM_2, &ydiffnorm));
691: alpha = ylastnorm / ydiffnorm;
692: PetscCall(VecCopy(Y, Ylast));
693: PetscCall(VecScale(Y, alpha));
694: if (precheck->monitor) PetscCall(PetscViewerASCIIPrintf(precheck->monitor, "Angle %g degrees less than threshold %g, corrected step by alpha=%g\n", (double)(theta * 180. / PETSC_PI), (double)precheck->angle, (double)alpha));
695: } else {
696: PetscCall(VecCopy(Y, Ylast));
697: *changed = PETSC_FALSE;
698: if (precheck->monitor) PetscCall(PetscViewerASCIIPrintf(precheck->monitor, "Angle %g degrees exceeds threshold %g, no correction applied\n", (double)(theta * 180. / PETSC_PI), (double)precheck->angle));
699: }
700: PetscFunctionReturn(PETSC_SUCCESS);
701: }
703: PetscErrorCode PreCheckDestroy(PreCheck *precheck)
704: {
705: PetscFunctionBeginUser;
706: if (!*precheck) PetscFunctionReturn(PETSC_SUCCESS);
707: PetscCall(VecDestroy(&(*precheck)->Ylast));
708: PetscCall(PetscViewerDestroy(&(*precheck)->monitor));
709: PetscCall(PetscFree(*precheck));
710: PetscFunctionReturn(PETSC_SUCCESS);
711: }
713: PetscErrorCode PreCheckCreate(MPI_Comm comm, PreCheck *precheck)
714: {
715: PetscFunctionBeginUser;
716: PetscCall(PetscNew(precheck));
718: (*precheck)->comm = comm;
719: (*precheck)->angle = 10.; /* only active if angle is less than 10 degrees */
720: PetscFunctionReturn(PETSC_SUCCESS);
721: }
723: /*
724: Applies some sweeps on nonlinear Gauss-Seidel on each process
726: */
727: PetscErrorCode NonlinearGS(SNES snes, Vec X, Vec B, PetscCtx ctx)
728: {
729: PetscInt i, j, k, xs, ys, xm, ym, its, tot_its, sweeps, l, m;
730: PetscReal hx, hy, hxdhy, hydhx, dhx, dhy, sc;
731: PetscScalar **x, **b, bij, F, F0 = 0, J, y, u, eu;
732: PetscReal atol, rtol, stol;
733: DM da;
734: AppCtx *user = (AppCtx *)ctx;
735: Vec localX, localB;
736: DMDALocalInfo info;
738: PetscFunctionBeginUser;
739: PetscCall(SNESGetDM(snes, &da));
740: PetscCall(DMDAGetLocalInfo(da, &info));
742: hx = 1.0 / (PetscReal)(info.mx - 1);
743: hy = 1.0 / (PetscReal)(info.my - 1);
744: sc = hx * hy * user->lambda;
745: dhx = 1 / hx;
746: dhy = 1 / hy;
747: hxdhy = hx / hy;
748: hydhx = hy / hx;
750: tot_its = 0;
751: PetscCall(SNESNGSGetSweeps(snes, &sweeps));
752: PetscCall(SNESNGSGetTolerances(snes, &atol, &rtol, &stol, &its));
753: PetscCall(DMGetLocalVector(da, &localX));
754: if (B) PetscCall(DMGetLocalVector(da, &localB));
755: if (B) {
756: PetscCall(DMGlobalToLocalBegin(da, B, INSERT_VALUES, localB));
757: PetscCall(DMGlobalToLocalEnd(da, B, INSERT_VALUES, localB));
758: }
759: if (B) PetscCall(DMDAVecGetArrayRead(da, localB, &b));
760: PetscCall(DMGlobalToLocalBegin(da, X, INSERT_VALUES, localX));
761: PetscCall(DMGlobalToLocalEnd(da, X, INSERT_VALUES, localX));
762: PetscCall(DMDAVecGetArray(da, localX, &x));
763: for (l = 0; l < sweeps; l++) {
764: /*
765: Get local grid boundaries (for 2-dimensional DMDA):
766: xs, ys - starting grid indices (no ghost points)
767: xm, ym - widths of local grid (no ghost points)
768: */
769: PetscCall(DMDAGetCorners(da, &xs, &ys, NULL, &xm, &ym, NULL));
770: for (m = 0; m < 2; m++) {
771: for (j = ys; j < ys + ym; j++) {
772: for (i = xs + (m + j) % 2; i < xs + xm; i += 2) {
773: PetscReal xx = i * hx, yy = j * hy;
774: if (B) bij = b[j][i];
775: else bij = 0.;
777: if (i == 0 || j == 0 || i == info.mx - 1 || j == info.my - 1) {
778: /* boundary conditions are all zero Dirichlet */
779: x[j][i] = 0.0 + bij;
780: } else {
781: const PetscScalar u_E = x[j][i + 1], u_W = x[j][i - 1], u_N = x[j + 1][i], u_S = x[j - 1][i];
782: const PetscScalar uy_E = 0.25 * dhy * (x[j + 1][i] + x[j + 1][i + 1] - x[j - 1][i] - x[j - 1][i + 1]), uy_W = 0.25 * dhy * (x[j + 1][i - 1] + x[j + 1][i] - x[j - 1][i - 1] - x[j - 1][i]), ux_N = 0.25 * dhx * (x[j][i + 1] + x[j + 1][i + 1] - x[j][i - 1] - x[j + 1][i - 1]), ux_S = 0.25 * dhx * (x[j - 1][i + 1] + x[j][i + 1] - x[j - 1][i - 1] - x[j][i - 1]);
783: u = x[j][i];
784: for (k = 0; k < its; k++) {
785: const PetscScalar ux_E = dhx * (u_E - u), ux_W = dhx * (u - u_W), uy_N = dhy * (u_N - u), uy_S = dhy * (u - u_S), e_E = eta(user, xx, yy, ux_E, uy_E), e_W = eta(user, xx, yy, ux_W, uy_W), e_N = eta(user, xx, yy, ux_N, uy_N), e_S = eta(user, xx, yy, ux_S, uy_S), de_E = deta(user, xx, yy, ux_E, uy_E), de_W = deta(user, xx, yy, ux_W, uy_W), de_N = deta(user, xx, yy, ux_N, uy_N), de_S = deta(user, xx, yy, ux_S, uy_S), newt_E = e_E + de_E * PetscSqr(ux_E), newt_W = e_W + de_W * PetscSqr(ux_W), newt_N = e_N + de_N * PetscSqr(uy_N), newt_S = e_S + de_S * PetscSqr(uy_S), uxx = -hy * (e_E * ux_E - e_W * ux_W), uyy = -hx * (e_N * uy_N - e_S * uy_S);
787: if (sc) eu = PetscExpScalar(u);
788: else eu = 0;
790: F = uxx + uyy - sc * eu - bij;
791: if (k == 0) F0 = F;
792: J = hxdhy * (newt_N + newt_S) + hydhx * (newt_E + newt_W) - sc * eu;
793: y = F / J;
794: u -= y;
795: tot_its++;
796: if (atol > PetscAbsReal(PetscRealPart(F)) || rtol * PetscAbsReal(PetscRealPart(F0)) > PetscAbsReal(PetscRealPart(F)) || stol * PetscAbsReal(PetscRealPart(u)) > PetscAbsReal(PetscRealPart(y))) break;
797: }
798: x[j][i] = u;
799: }
800: }
801: }
802: }
803: /*
804: Restore vector
805: */
806: }
807: PetscCall(DMDAVecRestoreArray(da, localX, &x));
808: PetscCall(DMLocalToGlobalBegin(da, localX, INSERT_VALUES, X));
809: PetscCall(DMLocalToGlobalEnd(da, localX, INSERT_VALUES, X));
810: PetscCall(PetscLogFlops(tot_its * (118.0)));
811: PetscCall(DMRestoreLocalVector(da, &localX));
812: if (B) {
813: PetscCall(DMDAVecRestoreArrayRead(da, localB, &b));
814: PetscCall(DMRestoreLocalVector(da, &localB));
815: }
816: PetscFunctionReturn(PETSC_SUCCESS);
817: }
819: /*TEST
821: test:
822: nsize: 2
823: args: -snes_monitor -da_grid_x 20 -da_grid_y 20 -p 1.3 -lambda 1 -jtype NEWTON
824: requires: !single
826: test:
827: suffix: 2
828: nsize: 2
829: args: -snes_monitor -da_grid_x 20 -da_grid_y 20 -p 1.3 -lambda 1 -jtype PICARD -precheck 1
830: requires: !single
832: test:
833: suffix: 3
834: nsize: 2
835: args: -snes_monitor -da_grid_x 20 -da_grid_y 20 -p 1.3 -lambda 1 -jtype PICARD -picard -precheck 1 -p 3
836: requires: !single
838: test:
839: suffix: 3_star
840: nsize: 2
841: args: -snes_monitor -da_grid_x 20 -da_grid_y 20 -p 1.3 -lambda 1 -jtype PICARD -picard -precheck 1 -p 3 -alloc_star
842: output_file: output/ex15_3.out
843: requires: !single
845: test:
846: suffix: 4
847: args: -snes_monitor -snes_type newtonls -npc_snes_type ngs -snes_npc_side left -da_grid_x 20 -da_grid_y 20 -p 1.3 -lambda 1 -ksp_monitor -pc_type none
848: requires: !single
850: test:
851: suffix: 5
852: args: -snes_monitor -snes_type newtontr -npc_snes_type ngs -snes_npc_side right -da_grid_x 20 -da_grid_y 20 -p 1.3 -lambda 1 -ksp_converged_reason -pc_type ilu
853: requires: !single
855: test:
856: suffix: lag_jac
857: nsize: 4
858: args: -snes_monitor -da_grid_x 20 -da_grid_y 20 -p 6.0 -lambda 0 -jtype NEWTON -snes_type ngmres -npc_snes_type newtonls -npc_snes_lag_jacobian 5 -npc_pc_type asm -npc_ksp_converged_reason -npc_snes_lag_jacobian_persists
859: requires: !single
861: test:
862: suffix: lag_pc
863: nsize: 4
864: args: -snes_monitor -da_grid_x 20 -da_grid_y 20 -p 6.0 -lambda 0 -jtype NEWTON -snes_type ngmres -npc_snes_type newtonls -npc_snes_lag_preconditioner 5 -npc_pc_type asm -npc_ksp_converged_reason -npc_snes_lag_preconditioner_persists
865: requires: !single
867: test:
868: suffix: nleqerr
869: args: -snes_monitor -snes_type newtonls -da_grid_x 20 -da_grid_y 20 -p 1.3 -lambda 1 -snes_linesearch_monitor -pc_type lu -snes_linesearch_type nleqerr
870: requires: !single
872: test:
873: suffix: mf
874: args: -snes_monitor -pc_type lu -da_refine 4 -p 3 -ksp_rtol 1.e-12 -snes_mf_operator
875: requires: !single
877: test:
878: suffix: mf_picard
879: args: -snes_monitor -pc_type lu -da_refine 4 -p 3 -ksp_rtol 1.e-12 -snes_mf_operator -picard
880: requires: !single
881: output_file: output/ex15_mf.out
883: test:
884: suffix: fd_picard
885: args: -snes_monitor -pc_type lu -da_refine 2 -p 3 -ksp_rtol 1.e-12 -snes_fd -picard
886: requires: !single
888: test:
889: suffix: fd_color_picard
890: args: -snes_monitor -pc_type lu -da_refine 4 -p 3 -ksp_rtol 1.e-12 -snes_fd_color -picard
891: requires: !single
892: output_file: output/ex15_mf.out
894: TEST*/