xref: /petsc/src/ts/tutorials/ex15.c (revision 811af0c4b09a35de4306c442f88bd09fdc09897d)
1 
2 static char help[] = "Time-dependent PDE in 2d. Modified from ex13.c for illustrating how to solve DAEs. \n";
3 /*
4    u_t = uxx + uyy
5    0 < x < 1, 0 < y < 1;
6    At t=0: u(x,y) = exp(c*r*r*r), if r=PetscSqrtReal((x-.5)*(x-.5) + (y-.5)*(y-.5)) < .125
7            u(x,y) = 0.0           if r >= .125
8 
9    Boundary conditions:
10    Drichlet BC:
11    At x=0, x=1, y=0, y=1: u = 0.0
12 
13    Neumann BC:
14    At x=0, x=1: du(x,y,t)/dx = 0
15    At y=0, y=1: du(x,y,t)/dy = 0
16 
17    mpiexec -n 2 ./ex15 -da_grid_x 40 -da_grid_y 40 -ts_max_steps 2 -snes_monitor -ksp_monitor
18          ./ex15 -da_grid_x 40 -da_grid_y 40  -draw_pause .1 -boundary 1 -ts_monitor_draw_solution
19          ./ex15 -da_grid_x 40 -da_grid_y 40  -draw_pause .1 -boundary 1 -Jtype 2 -nstencilpts 9
20 
21 */
22 
23 #include <petscdm.h>
24 #include <petscdmda.h>
25 #include <petscts.h>
26 
27 /*
28    User-defined data structures and routines
29 */
30 
31 /* AppCtx: used by FormIFunction() and FormIJacobian() */
32 typedef struct {
33   DM        da;
34   PetscInt  nstencilpts; /* number of stencil points: 5 or 9 */
35   PetscReal c;
36   PetscInt  boundary; /* Type of boundary condition */
37   PetscBool viewJacobian;
38 } AppCtx;
39 
40 extern PetscErrorCode FormIFunction(TS, PetscReal, Vec, Vec, Vec, void *);
41 extern PetscErrorCode FormIJacobian(TS, PetscReal, Vec, Vec, PetscReal, Mat, Mat, void *);
42 extern PetscErrorCode FormInitialSolution(Vec, void *);
43 
44 int main(int argc, char **argv) {
45   TS        ts;            /* nonlinear solver */
46   Vec       u, r;          /* solution, residual vectors */
47   Mat       J, Jmf = NULL; /* Jacobian matrices */
48   DM        da;
49   PetscReal dt;
50   AppCtx    user; /* user-defined work context */
51   SNES      snes;
52   PetscInt  Jtype; /* Jacobian type
53                             0: user provide Jacobian;
54                             1: slow finite difference;
55                             2: fd with coloring; */
56 
57   PetscFunctionBeginUser;
58   PetscCall(PetscInitialize(&argc, &argv, (char *)0, help));
59   /* Initialize user application context */
60   user.da           = NULL;
61   user.nstencilpts  = 5;
62   user.c            = -30.0;
63   user.boundary     = 0; /* 0: Drichlet BC; 1: Neumann BC */
64   user.viewJacobian = PETSC_FALSE;
65 
66   PetscCall(PetscOptionsGetInt(NULL, NULL, "-nstencilpts", &user.nstencilpts, NULL));
67   PetscCall(PetscOptionsGetInt(NULL, NULL, "-boundary", &user.boundary, NULL));
68   PetscCall(PetscOptionsHasName(NULL, NULL, "-viewJacobian", &user.viewJacobian));
69 
70   /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
71      Create distributed array (DMDA) to manage parallel grid and vectors
72   - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
73   if (user.nstencilpts == 5) {
74     PetscCall(DMDACreate2d(PETSC_COMM_WORLD, DM_BOUNDARY_NONE, DM_BOUNDARY_NONE, DMDA_STENCIL_STAR, 11, 11, PETSC_DECIDE, PETSC_DECIDE, 1, 1, NULL, NULL, &da));
75   } else if (user.nstencilpts == 9) {
76     PetscCall(DMDACreate2d(PETSC_COMM_WORLD, DM_BOUNDARY_NONE, DM_BOUNDARY_NONE, DMDA_STENCIL_BOX, 11, 11, PETSC_DECIDE, PETSC_DECIDE, 1, 1, NULL, NULL, &da));
77   } else SETERRQ(PETSC_COMM_WORLD, PETSC_ERR_SUP, "nstencilpts %" PetscInt_FMT " is not supported", user.nstencilpts);
78   PetscCall(DMSetFromOptions(da));
79   PetscCall(DMSetUp(da));
80   user.da = da;
81 
82   /*  - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
83      Extract global vectors from DMDA;
84    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
85   PetscCall(DMCreateGlobalVector(da, &u));
86   PetscCall(VecDuplicate(u, &r));
87 
88   /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
89      Create timestepping solver context
90      - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
91   PetscCall(TSCreate(PETSC_COMM_WORLD, &ts));
92   PetscCall(TSSetProblemType(ts, TS_NONLINEAR));
93   PetscCall(TSSetType(ts, TSBEULER));
94   PetscCall(TSSetDM(ts, da));
95   PetscCall(TSSetIFunction(ts, r, FormIFunction, &user));
96   PetscCall(TSSetMaxTime(ts, 1.0));
97   PetscCall(TSSetExactFinalTime(ts, TS_EXACTFINALTIME_STEPOVER));
98 
99   /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
100      Set initial conditions
101    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
102   PetscCall(FormInitialSolution(u, &user));
103   PetscCall(TSSetSolution(ts, u));
104   dt = .01;
105   PetscCall(TSSetTimeStep(ts, dt));
106 
107   /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
108    Set Jacobian evaluation routine
109   - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
110   PetscCall(DMSetMatType(da, MATAIJ));
111   PetscCall(DMCreateMatrix(da, &J));
112   Jtype = 0;
113   PetscCall(PetscOptionsGetInt(NULL, NULL, "-Jtype", &Jtype, NULL));
114   if (Jtype == 0) { /* use user provided Jacobian evaluation routine */
115     PetscCheck(user.nstencilpts == 5, PETSC_COMM_WORLD, PETSC_ERR_SUP, "user Jacobian routine FormIJacobian() does not support nstencilpts=%" PetscInt_FMT, user.nstencilpts);
116     PetscCall(TSSetIJacobian(ts, J, J, FormIJacobian, &user));
117   } else { /* use finite difference Jacobian J as preconditioner and '-snes_mf_operator' for Mat*vec */
118     PetscCall(TSGetSNES(ts, &snes));
119     PetscCall(MatCreateSNESMF(snes, &Jmf));
120     if (Jtype == 1) { /* slow finite difference J; */
121       PetscCall(SNESSetJacobian(snes, Jmf, J, SNESComputeJacobianDefault, NULL));
122     } else if (Jtype == 2) { /* Use coloring to compute  finite difference J efficiently */
123       PetscCall(SNESSetJacobian(snes, Jmf, J, SNESComputeJacobianDefaultColor, 0));
124     } else SETERRQ(PETSC_COMM_SELF, PETSC_ERR_SUP, "Jtype is not supported");
125   }
126 
127   /*  - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
128    Sets various TS parameters from user options
129    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
130   PetscCall(TSSetFromOptions(ts));
131 
132   /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
133      Solve nonlinear system
134      - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
135   PetscCall(TSSolve(ts, u));
136 
137   /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
138      Free work space.
139    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
140   PetscCall(MatDestroy(&J));
141   PetscCall(MatDestroy(&Jmf));
142   PetscCall(VecDestroy(&u));
143   PetscCall(VecDestroy(&r));
144   PetscCall(TSDestroy(&ts));
145   PetscCall(DMDestroy(&da));
146 
147   PetscCall(PetscFinalize());
148   return 0;
149 }
150 
151 /* --------------------------------------------------------------------- */
152 /*
153   FormIFunction = Udot - RHSFunction
154 */
155 PetscErrorCode FormIFunction(TS ts, PetscReal t, Vec U, Vec Udot, Vec F, void *ctx) {
156   AppCtx     *user = (AppCtx *)ctx;
157   DM          da   = (DM)user->da;
158   PetscInt    i, j, Mx, My, xs, ys, xm, ym;
159   PetscReal   hx, hy, sx, sy;
160   PetscScalar u, uxx, uyy, **uarray, **f, **udot;
161   Vec         localU;
162 
163   PetscFunctionBeginUser;
164   PetscCall(DMGetLocalVector(da, &localU));
165   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));
166 
167   hx = 1.0 / (PetscReal)(Mx - 1);
168   sx = 1.0 / (hx * hx);
169   hy = 1.0 / (PetscReal)(My - 1);
170   sy = 1.0 / (hy * hy);
171   PetscCheck(user->nstencilpts != 9 || hx == hy, PETSC_COMM_WORLD, PETSC_ERR_SUP, "hx must equal hy when nstencilpts = 9 for this example");
172 
173   /*
174      Scatter ghost points to local vector,using the 2-step process
175         DMGlobalToLocalBegin(),DMGlobalToLocalEnd().
176      By placing code between these two statements, computations can be
177      done while messages are in transition.
178   */
179   PetscCall(DMGlobalToLocalBegin(da, U, INSERT_VALUES, localU));
180   PetscCall(DMGlobalToLocalEnd(da, U, INSERT_VALUES, localU));
181 
182   /* Get pointers to vector data */
183   PetscCall(DMDAVecGetArrayRead(da, localU, &uarray));
184   PetscCall(DMDAVecGetArray(da, F, &f));
185   PetscCall(DMDAVecGetArray(da, Udot, &udot));
186 
187   /* Get local grid boundaries */
188   PetscCall(DMDAGetCorners(da, &xs, &ys, NULL, &xm, &ym, NULL));
189 
190   /* Compute function over the locally owned part of the grid */
191   for (j = ys; j < ys + ym; j++) {
192     for (i = xs; i < xs + xm; i++) {
193       /* Boundary conditions */
194       if (i == 0 || j == 0 || i == Mx - 1 || j == My - 1) {
195         if (user->boundary == 0) { /* Drichlet BC */
196           f[j][i] = uarray[j][i];  /* F = U */
197         } else {                   /* Neumann BC */
198           if (i == 0 && j == 0) {  /* SW corner */
199             f[j][i] = uarray[j][i] - uarray[j + 1][i + 1];
200           } else if (i == Mx - 1 && j == 0) { /* SE corner */
201             f[j][i] = uarray[j][i] - uarray[j + 1][i - 1];
202           } else if (i == 0 && j == My - 1) { /* NW corner */
203             f[j][i] = uarray[j][i] - uarray[j - 1][i + 1];
204           } else if (i == Mx - 1 && j == My - 1) { /* NE corner */
205             f[j][i] = uarray[j][i] - uarray[j - 1][i - 1];
206           } else if (i == 0) { /* Left */
207             f[j][i] = uarray[j][i] - uarray[j][i + 1];
208           } else if (i == Mx - 1) { /* Right */
209             f[j][i] = uarray[j][i] - uarray[j][i - 1];
210           } else if (j == 0) { /* Bottom */
211             f[j][i] = uarray[j][i] - uarray[j + 1][i];
212           } else if (j == My - 1) { /* Top */
213             f[j][i] = uarray[j][i] - uarray[j - 1][i];
214           }
215         }
216       } else { /* Interior */
217         u   = uarray[j][i];
218         /* 5-point stencil */
219         uxx = (-2.0 * u + uarray[j][i - 1] + uarray[j][i + 1]);
220         uyy = (-2.0 * u + uarray[j - 1][i] + uarray[j + 1][i]);
221         if (user->nstencilpts == 9) {
222           /* 9-point stencil: assume hx=hy */
223           uxx = 2.0 * uxx / 3.0 + (0.5 * (uarray[j - 1][i - 1] + uarray[j - 1][i + 1] + uarray[j + 1][i - 1] + uarray[j + 1][i + 1]) - 2.0 * u) / 6.0;
224           uyy = 2.0 * uyy / 3.0 + (0.5 * (uarray[j - 1][i - 1] + uarray[j - 1][i + 1] + uarray[j + 1][i - 1] + uarray[j + 1][i + 1]) - 2.0 * u) / 6.0;
225         }
226         f[j][i] = udot[j][i] - (uxx * sx + uyy * sy);
227       }
228     }
229   }
230 
231   /* Restore vectors */
232   PetscCall(DMDAVecRestoreArrayRead(da, localU, &uarray));
233   PetscCall(DMDAVecRestoreArray(da, F, &f));
234   PetscCall(DMDAVecRestoreArray(da, Udot, &udot));
235   PetscCall(DMRestoreLocalVector(da, &localU));
236   PetscCall(PetscLogFlops(11.0 * ym * xm));
237   PetscFunctionReturn(0);
238 }
239 
240 /* --------------------------------------------------------------------- */
241 /*
242   FormIJacobian() - Compute IJacobian = dF/dU + a dF/dUdot
243   This routine is not used with option '-use_coloring'
244 */
245 PetscErrorCode FormIJacobian(TS ts, PetscReal t, Vec U, Vec Udot, PetscReal a, Mat J, Mat Jpre, void *ctx) {
246   PetscInt    i, j, Mx, My, xs, ys, xm, ym, nc;
247   AppCtx     *user = (AppCtx *)ctx;
248   DM          da   = (DM)user->da;
249   MatStencil  col[5], row;
250   PetscScalar vals[5], hx, hy, sx, sy;
251 
252   PetscFunctionBeginUser;
253   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));
254   PetscCall(DMDAGetCorners(da, &xs, &ys, NULL, &xm, &ym, NULL));
255 
256   hx = 1.0 / (PetscReal)(Mx - 1);
257   sx = 1.0 / (hx * hx);
258   hy = 1.0 / (PetscReal)(My - 1);
259   sy = 1.0 / (hy * hy);
260 
261   for (j = ys; j < ys + ym; j++) {
262     for (i = xs; i < xs + xm; i++) {
263       nc    = 0;
264       row.j = j;
265       row.i = i;
266       if (user->boundary == 0 && (i == 0 || i == Mx - 1 || j == 0 || j == My - 1)) {
267         col[nc].j  = j;
268         col[nc].i  = i;
269         vals[nc++] = 1.0;
270 
271       } else if (user->boundary > 0 && i == 0) { /* Left Neumann */
272         col[nc].j  = j;
273         col[nc].i  = i;
274         vals[nc++] = 1.0;
275         col[nc].j  = j;
276         col[nc].i  = i + 1;
277         vals[nc++] = -1.0;
278       } else if (user->boundary > 0 && i == Mx - 1) { /* Right Neumann */
279         col[nc].j  = j;
280         col[nc].i  = i;
281         vals[nc++] = 1.0;
282         col[nc].j  = j;
283         col[nc].i  = i - 1;
284         vals[nc++] = -1.0;
285       } else if (user->boundary > 0 && j == 0) { /* Bottom Neumann */
286         col[nc].j  = j;
287         col[nc].i  = i;
288         vals[nc++] = 1.0;
289         col[nc].j  = j + 1;
290         col[nc].i  = i;
291         vals[nc++] = -1.0;
292       } else if (user->boundary > 0 && j == My - 1) { /* Top Neumann */
293         col[nc].j  = j;
294         col[nc].i  = i;
295         vals[nc++] = 1.0;
296         col[nc].j  = j - 1;
297         col[nc].i  = i;
298         vals[nc++] = -1.0;
299       } else { /* Interior */
300         col[nc].j  = j - 1;
301         col[nc].i  = i;
302         vals[nc++] = -sy;
303         col[nc].j  = j;
304         col[nc].i  = i - 1;
305         vals[nc++] = -sx;
306         col[nc].j  = j;
307         col[nc].i  = i;
308         vals[nc++] = 2.0 * (sx + sy) + a;
309         col[nc].j  = j;
310         col[nc].i  = i + 1;
311         vals[nc++] = -sx;
312         col[nc].j  = j + 1;
313         col[nc].i  = i;
314         vals[nc++] = -sy;
315       }
316       PetscCall(MatSetValuesStencil(Jpre, 1, &row, nc, col, vals, INSERT_VALUES));
317     }
318   }
319   PetscCall(MatAssemblyBegin(Jpre, MAT_FINAL_ASSEMBLY));
320   PetscCall(MatAssemblyEnd(Jpre, MAT_FINAL_ASSEMBLY));
321   if (J != Jpre) {
322     PetscCall(MatAssemblyBegin(J, MAT_FINAL_ASSEMBLY));
323     PetscCall(MatAssemblyEnd(J, MAT_FINAL_ASSEMBLY));
324   }
325 
326   if (user->viewJacobian) {
327     PetscCall(PetscPrintf(PetscObjectComm((PetscObject)Jpre), "Jpre:\n"));
328     PetscCall(MatView(Jpre, PETSC_VIEWER_STDOUT_WORLD));
329   }
330   PetscFunctionReturn(0);
331 }
332 
333 /* ------------------------------------------------------------------- */
334 PetscErrorCode FormInitialSolution(Vec U, void *ptr) {
335   AppCtx       *user = (AppCtx *)ptr;
336   DM            da   = user->da;
337   PetscReal     c    = user->c;
338   PetscInt      i, j, xs, ys, xm, ym, Mx, My;
339   PetscScalar **u;
340   PetscReal     hx, hy, x, y, r;
341 
342   PetscFunctionBeginUser;
343   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));
344 
345   hx = 1.0 / (PetscReal)(Mx - 1);
346   hy = 1.0 / (PetscReal)(My - 1);
347 
348   /* Get pointers to vector data */
349   PetscCall(DMDAVecGetArray(da, U, &u));
350 
351   /* Get local grid boundaries */
352   PetscCall(DMDAGetCorners(da, &xs, &ys, NULL, &xm, &ym, NULL));
353 
354   /* Compute function over the locally owned part of the grid */
355   for (j = ys; j < ys + ym; j++) {
356     y = j * hy;
357     for (i = xs; i < xs + xm; i++) {
358       x = i * hx;
359       r = PetscSqrtReal((x - .5) * (x - .5) + (y - .5) * (y - .5));
360       if (r < .125) u[j][i] = PetscExpReal(c * r * r * r);
361       else u[j][i] = 0.0;
362     }
363   }
364 
365   /* Restore vectors */
366   PetscCall(DMDAVecRestoreArray(da, U, &u));
367   PetscFunctionReturn(0);
368 }
369 
370 /*TEST
371 
372     test:
373       args: -da_grid_x 20 -da_grid_y 20 -boundary 0 -ts_max_steps 10 -ts_monitor
374 
375     test:
376       suffix: 2
377       args: -da_grid_x 20 -da_grid_y 20 -boundary 0 -ts_max_steps 10 -Jtype 2 -ts_monitor
378 
379     test:
380       suffix: 3
381       requires: !single
382       args: -da_grid_x 20 -da_grid_y 20 -boundary 1 -ts_max_steps 10 -ts_monitor
383 
384     test:
385       suffix: 4
386       requires: !single
387       nsize: 2
388       args: -da_grid_x 20 -da_grid_y 20 -boundary 1 -ts_max_steps 10 -ts_monitor
389 
390     test:
391       suffix: 5
392       nsize: 1
393       args: -da_grid_x 20 -da_grid_y 20 -boundary 0 -ts_max_steps 10 -Jtype 1 -ts_monitor
394 
395 TEST*/
396