Actual source code: ex5.c
1: static char help[] = "Solves a simple time-dependent linear PDE (the heat equation).\n\
2: Input parameters include:\n\
3: -m <points>, where <points> = number of grid points\n\
4: -time_dependent_rhs : Treat the problem as having a time-dependent right-hand side\n\
5: -debug : Activate debugging printouts\n\
6: -nox : Deactivate x-window graphics\n\n";
8: /* ------------------------------------------------------------------------
10: This program solves the one-dimensional heat equation (also called the
11: diffusion equation),
12: u_t = u_xx,
13: on the domain 0 <= x <= 1, with the boundary conditions
14: u(t,0) = 1, u(t,1) = 1,
15: and the initial condition
16: u(0,x) = cos(6*pi*x) + 3*cos(2*pi*x).
17: This is a linear, second-order, parabolic equation.
19: We discretize the right-hand side using finite differences with
20: uniform grid spacing h:
21: u_xx = (u_{i+1} - 2u_{i} + u_{i-1})/(h^2)
22: We then demonstrate time evolution using the various TS methods by
23: running the program via
24: ex3 -ts_type <timestepping solver>
26: We compare the approximate solution with the exact solution, given by
27: u_exact(x,t) = exp(-36*pi*pi*t) * cos(6*pi*x) +
28: 3*exp(-4*pi*pi*t) * cos(2*pi*x)
30: Notes:
31: This code demonstrates the TS solver interface to two variants of
32: linear problems, u_t = f(u,t), namely
33: - time-dependent f: f(u,t) is a function of t
34: - time-independent f: f(u,t) is simply just f(u)
36: The parallel version of this code is ts/tutorials/ex4.c
38: ------------------------------------------------------------------------- */
40: /*
41: Include "petscts.h" so that we can use the PETSc TS ODE integrators. Note that this file
42: automatically includes:
43: petscsys.h - base PETSc routines
44: petscis.h - index sets
45: petscvec.h - vectors
46: petscmat.h - matrices
47: petscpc.h - preconditioners
48: petscksp.h - linear solvers
49: petscsnes.h - nonlinear solvers
50: */
51: #include <petscts.h>
52: #include <petscdraw.h>
54: /*
55: User-defined application context - contains data needed by the
56: application-provided call-back routines.
57: */
58: typedef struct {
59: Vec solution; /* global exact solution vector */
60: PetscInt m; /* total number of grid points */
61: PetscReal h; /* mesh width h = 1/(m-1) */
62: PetscBool debug; /* flag (1 indicates activation of debugging printouts) */
63: PetscViewer viewer1, viewer2; /* viewers for the solution and error */
64: PetscReal norm_2, norm_max; /* error norms */
65: } AppCtx;
67: /*
68: User-defined routines
69: */
70: extern PetscErrorCode InitialConditions(Vec, AppCtx *);
71: extern PetscErrorCode RHSMatrixHeat(TS, PetscReal, Vec, Mat, Mat, void *);
72: extern PetscErrorCode Monitor(TS, PetscInt, PetscReal, Vec, void *);
73: extern PetscErrorCode ExactSolution(PetscReal, Vec, AppCtx *);
75: int main(int argc, char **argv)
76: {
77: AppCtx appctx; /* user-defined application context */
78: TS ts; /* timestepping context */
79: Mat A; /* matrix data structure */
80: Vec u; /* approximate solution vector */
81: PetscReal time_total_max = 100.0; /* default max total time */
82: PetscInt time_steps_max = 100; /* default max timesteps */
83: PetscDraw draw; /* drawing context */
84: PetscInt steps, m;
85: PetscMPIInt size;
86: PetscBool flg;
87: PetscReal dt, ftime;
89: /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
90: Initialize program and set problem parameters
91: - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
93: PetscFunctionBeginUser;
94: PetscCall(PetscInitialize(&argc, &argv, NULL, help));
95: PetscCallMPI(MPI_Comm_size(PETSC_COMM_WORLD, &size));
96: PetscCheck(size == 1, PETSC_COMM_WORLD, PETSC_ERR_WRONG_MPI_SIZE, "This is a uniprocessor example only!");
98: m = 60;
99: PetscCall(PetscOptionsGetInt(NULL, NULL, "-m", &m, NULL));
100: PetscCall(PetscOptionsHasName(NULL, NULL, "-debug", &appctx.debug));
101: appctx.m = m;
102: appctx.h = 1.0 / (m - 1.0);
103: appctx.norm_2 = 0.0;
104: appctx.norm_max = 0.0;
106: PetscCall(PetscPrintf(PETSC_COMM_SELF, "Solving a linear TS problem on 1 processor\n"));
108: /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
109: Create vector data structures
110: - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
112: /*
113: Create vector data structures for approximate and exact solutions
114: */
115: PetscCall(VecCreateSeq(PETSC_COMM_SELF, m, &u));
116: PetscCall(VecDuplicate(u, &appctx.solution));
118: /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
119: Set up displays to show graphs of the solution and error
120: - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
122: PetscCall(PetscViewerDrawOpen(PETSC_COMM_SELF, NULL, "", 80, 380, 400, 160, &appctx.viewer1));
123: PetscCall(PetscViewerDrawGetDraw(appctx.viewer1, 0, &draw));
124: PetscCall(PetscDrawSetDoubleBuffer(draw));
125: PetscCall(PetscViewerDrawOpen(PETSC_COMM_SELF, NULL, "", 80, 0, 400, 160, &appctx.viewer2));
126: PetscCall(PetscViewerDrawGetDraw(appctx.viewer2, 0, &draw));
127: PetscCall(PetscDrawSetDoubleBuffer(draw));
129: /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
130: Create timestepping solver context
131: - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
133: PetscCall(TSCreate(PETSC_COMM_SELF, &ts));
134: PetscCall(TSSetProblemType(ts, TS_LINEAR));
136: /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
137: Set optional user-defined monitoring routine
138: - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
140: PetscCall(TSMonitorSet(ts, Monitor, &appctx, NULL));
142: /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
144: Create matrix data structure; set matrix evaluation routine.
145: - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
147: PetscCall(MatCreate(PETSC_COMM_SELF, &A));
148: PetscCall(MatSetSizes(A, PETSC_DECIDE, PETSC_DECIDE, m, m));
149: PetscCall(MatSetFromOptions(A));
150: PetscCall(MatSetUp(A));
152: PetscCall(PetscOptionsHasName(NULL, NULL, "-time_dependent_rhs", &flg));
153: if (flg) {
154: /*
155: For linear problems with a time-dependent f(u,t) in the equation
156: u_t = f(u,t), the user provides the discretized right-hand side
157: as a time-dependent matrix.
158: */
159: PetscCall(TSSetRHSFunction(ts, NULL, TSComputeRHSFunctionLinear, &appctx));
160: PetscCall(TSSetRHSJacobian(ts, A, A, RHSMatrixHeat, &appctx));
161: } else {
162: /*
163: For linear problems with a time-independent f(u) in the equation
164: u_t = f(u), the user provides the discretized right-hand side
165: as a matrix only once, and then sets a null matrix evaluation
166: routine.
167: */
168: PetscCall(RHSMatrixHeat(ts, 0.0, u, A, A, &appctx));
169: PetscCall(TSSetRHSFunction(ts, NULL, TSComputeRHSFunctionLinear, &appctx));
170: PetscCall(TSSetRHSJacobian(ts, A, A, TSComputeRHSJacobianConstant, &appctx));
171: }
173: /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
174: Set solution vector and initial timestep
175: - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
177: dt = appctx.h * appctx.h / 2.0;
178: PetscCall(TSSetTimeStep(ts, dt));
179: PetscCall(TSSetSolution(ts, u));
181: /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
182: Customize timestepping solver:
183: - Set the solution method to be the Backward Euler method.
184: - Set timestepping duration info
185: Then set runtime options, which can override these defaults.
186: For example,
187: -ts_max_steps <maxsteps> -ts_max_time <maxtime>
188: to override the defaults set by TSSetMaxSteps()/TSSetMaxTime().
189: - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
191: PetscCall(TSSetMaxSteps(ts, time_steps_max));
192: PetscCall(TSSetMaxTime(ts, time_total_max));
193: PetscCall(TSSetExactFinalTime(ts, TS_EXACTFINALTIME_STEPOVER));
194: PetscCall(TSSetFromOptions(ts));
196: /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
197: Solve the problem
198: - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
200: /*
201: Evaluate initial conditions
202: */
203: PetscCall(InitialConditions(u, &appctx));
205: /*
206: Run the timestepping solver
207: */
208: PetscCall(TSSolve(ts, u));
209: PetscCall(TSGetSolveTime(ts, &ftime));
210: PetscCall(TSGetStepNumber(ts, &steps));
212: /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
213: View timestepping solver info
214: - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
216: PetscCall(PetscPrintf(PETSC_COMM_SELF, "avg. error (2 norm) = %g, avg. error (max norm) = %g\n", (double)(appctx.norm_2 / steps), (double)(appctx.norm_max / steps)));
217: PetscCall(TSView(ts, PETSC_VIEWER_STDOUT_SELF));
219: /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
220: Free work space. All PETSc objects should be destroyed when they
221: are no longer needed.
222: - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
224: PetscCall(TSDestroy(&ts));
225: PetscCall(MatDestroy(&A));
226: PetscCall(VecDestroy(&u));
227: PetscCall(PetscViewerDestroy(&appctx.viewer1));
228: PetscCall(PetscViewerDestroy(&appctx.viewer2));
229: PetscCall(VecDestroy(&appctx.solution));
231: /*
232: Always call PetscFinalize() before exiting a program. This routine
233: - finalizes the PETSc libraries as well as MPI
234: - provides summary and diagnostic information if certain runtime
235: options are chosen (e.g., -log_view).
236: */
237: PetscCall(PetscFinalize());
238: return 0;
239: }
240: /* --------------------------------------------------------------------- */
241: /*
242: InitialConditions - Computes the solution at the initial time.
244: Input Parameter:
245: u - uninitialized solution vector (global)
246: appctx - user-defined application context
248: Output Parameter:
249: u - vector with solution at initial time (global)
250: */
251: PetscErrorCode InitialConditions(Vec u, AppCtx *appctx)
252: {
253: PetscScalar *u_localptr, h = appctx->h;
254: PetscInt i;
256: PetscFunctionBeginUser;
257: /*
258: Get a pointer to vector data.
259: - For default PETSc vectors, VecGetArray() returns a pointer to
260: the data array. Otherwise, the routine is implementation dependent.
261: - You MUST call VecRestoreArray() when you no longer need access to
262: the array.
263: - Note that the Fortran interface to VecGetArray() differs from the
264: C version. See the users manual for details.
265: */
266: PetscCall(VecGetArray(u, &u_localptr));
268: /*
269: We initialize the solution array by simply writing the solution
270: directly into the array locations. Alternatively, we could use
271: VecSetValues() or VecSetValuesLocal().
272: */
273: for (i = 0; i < appctx->m; i++) u_localptr[i] = PetscCosScalar(PETSC_PI * i * 6. * h) + 3. * PetscCosScalar(PETSC_PI * i * 2. * h);
275: /*
276: Restore vector
277: */
278: PetscCall(VecRestoreArray(u, &u_localptr));
280: /*
281: Print debugging information if desired
282: */
283: if (appctx->debug) {
284: printf("initial guess vector\n");
285: PetscCall(VecView(u, PETSC_VIEWER_STDOUT_SELF));
286: }
287: PetscFunctionReturn(PETSC_SUCCESS);
288: }
289: /* --------------------------------------------------------------------- */
290: /*
291: ExactSolution - Computes the exact solution at a given time.
293: Input Parameters:
294: t - current time
295: solution - vector in which exact solution will be computed
296: appctx - user-defined application context
298: Output Parameter:
299: solution - vector with the newly computed exact solution
300: */
301: PetscErrorCode ExactSolution(PetscReal t, Vec solution, AppCtx *appctx)
302: {
303: PetscScalar *s_localptr, h = appctx->h, ex1, ex2, sc1, sc2, tc = t;
304: PetscInt i;
306: PetscFunctionBeginUser;
307: /*
308: Get a pointer to vector data.
309: */
310: PetscCall(VecGetArray(solution, &s_localptr));
312: /*
313: Simply write the solution directly into the array locations.
314: Alternatively, we culd use VecSetValues() or VecSetValuesLocal().
315: */
316: ex1 = PetscExpScalar(-36. * PETSC_PI * PETSC_PI * tc);
317: ex2 = PetscExpScalar(-4. * PETSC_PI * PETSC_PI * tc);
318: sc1 = PETSC_PI * 6. * h;
319: sc2 = PETSC_PI * 2. * h;
320: for (i = 0; i < appctx->m; i++) s_localptr[i] = PetscCosScalar(sc1 * (PetscReal)i) * ex1 + 3. * PetscCosScalar(sc2 * (PetscReal)i) * ex2;
322: /*
323: Restore vector
324: */
325: PetscCall(VecRestoreArray(solution, &s_localptr));
326: PetscFunctionReturn(PETSC_SUCCESS);
327: }
328: /* --------------------------------------------------------------------- */
329: /*
330: Monitor - User-provided routine to monitor the solution computed at
331: each timestep. This example plots the solution and computes the
332: error in two different norms.
334: Input Parameters:
335: ts - the timestep context
336: step - the count of the current step (with 0 meaning the
337: initial condition)
338: time - the current time
339: u - the solution at this timestep
340: ctx - the user-provided context for this monitoring routine.
341: In this case we use the application context which contains
342: information about the problem size, workspace and the exact
343: solution.
344: */
345: PetscErrorCode Monitor(TS ts, PetscInt step, PetscReal time, Vec u, PetscCtx ctx)
346: {
347: AppCtx *appctx = (AppCtx *)ctx; /* user-defined application context */
348: PetscReal norm_2, norm_max;
350: PetscFunctionBeginUser;
351: /*
352: View a graph of the current iterate
353: */
354: PetscCall(VecView(u, appctx->viewer2));
356: /*
357: Compute the exact solution
358: */
359: PetscCall(ExactSolution(time, appctx->solution, appctx));
361: /*
362: Print debugging information if desired
363: */
364: if (appctx->debug) {
365: printf("Computed solution vector\n");
366: PetscCall(VecView(u, PETSC_VIEWER_STDOUT_SELF));
367: printf("Exact solution vector\n");
368: PetscCall(VecView(appctx->solution, PETSC_VIEWER_STDOUT_SELF));
369: }
371: /*
372: Compute the 2-norm and max-norm of the error
373: */
374: PetscCall(VecAXPY(appctx->solution, -1.0, u));
375: PetscCall(VecNorm(appctx->solution, NORM_2, &norm_2));
376: norm_2 = PetscSqrtReal(appctx->h) * norm_2;
377: PetscCall(VecNorm(appctx->solution, NORM_MAX, &norm_max));
378: if (norm_2 < 1e-14) norm_2 = 0;
379: if (norm_max < 1e-14) norm_max = 0;
381: PetscCall(PetscPrintf(PETSC_COMM_WORLD, "Timestep %" PetscInt_FMT ": time = %g, 2-norm error = %g, max norm error = %g\n", step, (double)time, (double)norm_2, (double)norm_max));
382: appctx->norm_2 += norm_2;
383: appctx->norm_max += norm_max;
385: /*
386: View a graph of the error
387: */
388: PetscCall(VecView(appctx->solution, appctx->viewer1));
390: /*
391: Print debugging information if desired
392: */
393: if (appctx->debug) {
394: printf("Error vector\n");
395: PetscCall(VecView(appctx->solution, PETSC_VIEWER_STDOUT_SELF));
396: }
397: PetscFunctionReturn(PETSC_SUCCESS);
398: }
399: /* --------------------------------------------------------------------- */
400: /*
401: RHSMatrixHeat - User-provided routine to compute the right-hand-side
402: matrix for the heat equation.
404: Input Parameters:
405: ts - the TS context
406: t - current time
407: global_in - global input vector
408: dummy - optional user-defined context, as set by TSetRHSJacobian()
410: Output Parameters:
411: AA - Jacobian matrix
412: BB - optionally different matrix used to construct the preconditioner
414: Notes:
415: Recall that MatSetValues() uses 0-based row and column numbers
416: in Fortran as well as in C.
417: */
418: PetscErrorCode RHSMatrixHeat(TS ts, PetscReal t, Vec X, Mat AA, Mat BB, PetscCtx ctx)
419: {
420: Mat A = AA; /* Jacobian matrix */
421: AppCtx *appctx = (AppCtx *)ctx; /* user-defined application context */
422: PetscInt mstart = 0;
423: PetscInt mend = appctx->m;
424: PetscInt i, idx[3];
425: PetscScalar v[3], stwo = -2. / (appctx->h * appctx->h), sone = -.5 * stwo;
427: PetscFunctionBeginUser;
428: /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
429: Compute entries for the locally owned part of the matrix
430: - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
431: /*
432: Set matrix rows corresponding to boundary data
433: */
435: mstart = 0;
436: v[0] = 1.0;
437: PetscCall(MatSetValues(A, 1, &mstart, 1, &mstart, v, INSERT_VALUES));
438: mstart++;
440: mend--;
441: v[0] = 1.0;
442: PetscCall(MatSetValues(A, 1, &mend, 1, &mend, v, INSERT_VALUES));
444: /*
445: Set matrix rows corresponding to interior data. We construct the
446: matrix one row at a time.
447: */
448: v[0] = sone;
449: v[1] = stwo;
450: v[2] = sone;
451: for (i = mstart; i < mend; i++) {
452: idx[0] = i - 1;
453: idx[1] = i;
454: idx[2] = i + 1;
455: PetscCall(MatSetValues(A, 1, &i, 3, idx, v, INSERT_VALUES));
456: }
458: /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
459: Complete the matrix assembly process and set some options
460: - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
461: /*
462: Assemble matrix, using the 2-step process:
463: MatAssemblyBegin(), MatAssemblyEnd()
464: Computations can be done while messages are in transition
465: by placing code between these two statements.
466: */
467: PetscCall(MatAssemblyBegin(A, MAT_FINAL_ASSEMBLY));
468: PetscCall(MatAssemblyEnd(A, MAT_FINAL_ASSEMBLY));
470: /*
471: Set and option to indicate that we will never add a new nonzero location
472: to the matrix. If we do, it will generate an error.
473: */
474: PetscCall(MatSetOption(A, MAT_NEW_NONZERO_LOCATION_ERR, PETSC_TRUE));
475: PetscFunctionReturn(PETSC_SUCCESS);
476: }
478: /*TEST
480: test:
481: requires: x
483: test:
484: suffix: nox
485: args: -nox
487: TEST*/