Actual source code: ex4.c
petsc-3.7.3 2016-08-01
2: static char help[] ="Solves a simple time-dependent linear PDE (the heat equation).\n\
3: Input parameters include:\n\
4: -m <points>, where <points> = number of grid points\n\
5: -time_dependent_rhs : Treat the problem as having a time-dependent right-hand side\n\
6: -debug : Activate debugging printouts\n\
7: -nox : Deactivate x-window graphics\n\n";
9: /*
10: Concepts: TS^time-dependent linear problems
11: Concepts: TS^heat equation
12: Concepts: TS^diffusion equation
13: Processors: n
14: */
16: /* ------------------------------------------------------------------------
18: This program solves the one-dimensional heat equation (also called the
19: diffusion equation),
20: u_t = u_xx,
21: on the domain 0 <= x <= 1, with the boundary conditions
22: u(t,0) = 0, u(t,1) = 0,
23: and the initial condition
24: u(0,x) = sin(6*pi*x) + 3*sin(2*pi*x).
25: This is a linear, second-order, parabolic equation.
27: We discretize the right-hand side using finite differences with
28: uniform grid spacing h:
29: u_xx = (u_{i+1} - 2u_{i} + u_{i-1})/(h^2)
30: We then demonstrate time evolution using the various TS methods by
31: running the program via
32: mpiexec -n <procs> ex3 -ts_type <timestepping solver>
34: We compare the approximate solution with the exact solution, given by
35: u_exact(x,t) = exp(-36*pi*pi*t) * sin(6*pi*x) +
36: 3*exp(-4*pi*pi*t) * sin(2*pi*x)
38: Notes:
39: This code demonstrates the TS solver interface to two variants of
40: linear problems, u_t = f(u,t), namely
41: - time-dependent f: f(u,t) is a function of t
42: - time-independent f: f(u,t) is simply f(u)
44: The uniprocessor version of this code is ts/examples/tutorials/ex3.c
46: ------------------------------------------------------------------------- */
48: /*
49: Include "petscdmda.h" so that we can use distributed arrays (DMDAs) to manage
50: the parallel grid. Include "petscts.h" so that we can use TS solvers.
51: Note that this file automatically includes:
52: petscsys.h - base PETSc routines petscvec.h - vectors
53: petscmat.h - matrices
54: petscis.h - index sets petscksp.h - Krylov subspace methods
55: petscviewer.h - viewers petscpc.h - preconditioners
56: petscksp.h - linear solvers petscsnes.h - nonlinear solvers
57: */
59: #include <petscdm.h>
60: #include <petscdmda.h>
61: #include <petscts.h>
62: #include <petscdraw.h>
64: /*
65: User-defined application context - contains data needed by the
66: application-provided call-back routines.
67: */
68: typedef struct {
69: MPI_Comm comm; /* communicator */
70: DM da; /* distributed array data structure */
71: Vec localwork; /* local ghosted work vector */
72: Vec u_local; /* local ghosted approximate solution vector */
73: Vec solution; /* global exact solution vector */
74: PetscInt m; /* total number of grid points */
75: PetscReal h; /* mesh width h = 1/(m-1) */
76: PetscBool debug; /* flag (1 indicates activation of debugging printouts) */
77: PetscViewer viewer1,viewer2; /* viewers for the solution and error */
78: PetscReal norm_2,norm_max; /* error norms */
79: } AppCtx;
81: /*
82: User-defined routines
83: */
84: extern PetscErrorCode InitialConditions(Vec,AppCtx*);
85: extern PetscErrorCode RHSMatrixHeat(TS,PetscReal,Vec,Mat,Mat,void*);
86: extern PetscErrorCode RHSFunctionHeat(TS,PetscReal,Vec,Vec,void*);
87: extern PetscErrorCode Monitor(TS,PetscInt,PetscReal,Vec,void*);
88: extern PetscErrorCode ExactSolution(PetscReal,Vec,AppCtx*);
92: int main(int argc,char **argv)
93: {
94: AppCtx appctx; /* user-defined application context */
95: TS ts; /* timestepping context */
96: Mat A; /* matrix data structure */
97: Vec u; /* approximate solution vector */
98: PetscReal time_total_max = 1.0; /* default max total time */
99: PetscInt time_steps_max = 100; /* default max timesteps */
100: PetscDraw draw; /* drawing context */
102: PetscInt steps,m;
103: PetscMPIInt size;
104: PetscReal dt,ftime;
105: PetscBool flg;
106: TSProblemType tsproblem = TS_LINEAR;
108: /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
109: Initialize program and set problem parameters
110: - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
112: PetscInitialize(&argc,&argv,(char*)0,help);
113: appctx.comm = PETSC_COMM_WORLD;
115: m = 60;
116: PetscOptionsGetInt(NULL,NULL,"-m",&m,NULL);
117: PetscOptionsHasName(NULL,NULL,"-debug",&appctx.debug);
118: appctx.m = m;
119: appctx.h = 1.0/(m-1.0);
120: appctx.norm_2 = 0.0;
121: appctx.norm_max = 0.0;
123: MPI_Comm_size(PETSC_COMM_WORLD,&size);
124: PetscPrintf(PETSC_COMM_WORLD,"Solving a linear TS problem, number of processors = %d\n",size);
126: /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
127: Create vector data structures
128: - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
129: /*
130: Create distributed array (DMDA) to manage parallel grid and vectors
131: and to set up the ghost point communication pattern. There are M
132: total grid values spread equally among all the processors.
133: */
135: DMDACreate1d(PETSC_COMM_WORLD,DM_BOUNDARY_NONE,m,1,1,NULL,&appctx.da);
137: /*
138: Extract global and local vectors from DMDA; we use these to store the
139: approximate solution. Then duplicate these for remaining vectors that
140: have the same types.
141: */
142: DMCreateGlobalVector(appctx.da,&u);
143: DMCreateLocalVector(appctx.da,&appctx.u_local);
145: /*
146: Create local work vector for use in evaluating right-hand-side function;
147: create global work vector for storing exact solution.
148: */
149: VecDuplicate(appctx.u_local,&appctx.localwork);
150: VecDuplicate(u,&appctx.solution);
152: /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
153: Set up displays to show graphs of the solution and error
154: - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
156: PetscViewerDrawOpen(PETSC_COMM_WORLD,0,"",80,380,400,160,&appctx.viewer1);
157: PetscViewerDrawGetDraw(appctx.viewer1,0,&draw);
158: PetscDrawSetDoubleBuffer(draw);
159: PetscViewerDrawOpen(PETSC_COMM_WORLD,0,"",80,0,400,160,&appctx.viewer2);
160: PetscViewerDrawGetDraw(appctx.viewer2,0,&draw);
161: PetscDrawSetDoubleBuffer(draw);
163: /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
164: Create timestepping solver context
165: - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
167: TSCreate(PETSC_COMM_WORLD,&ts);
169: flg = PETSC_FALSE;
170: PetscOptionsGetBool(NULL,NULL,"-nonlinear",&flg,NULL);
171: TSSetProblemType(ts,flg ? TS_NONLINEAR : TS_LINEAR);
173: /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
174: Set optional user-defined monitoring routine
175: - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
176: TSMonitorSet(ts,Monitor,&appctx,NULL);
178: /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
180: Create matrix data structure; set matrix evaluation routine.
181: - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
183: MatCreate(PETSC_COMM_WORLD,&A);
184: MatSetSizes(A,PETSC_DECIDE,PETSC_DECIDE,m,m);
185: MatSetFromOptions(A);
186: MatSetUp(A);
188: flg = PETSC_FALSE;
189: PetscOptionsGetBool(NULL,NULL,"-time_dependent_rhs",&flg,NULL);
190: if (flg) {
191: /*
192: For linear problems with a time-dependent f(u,t) in the equation
193: u_t = f(u,t), the user provides the discretized right-hand-side
194: as a time-dependent matrix.
195: */
196: TSSetRHSFunction(ts,NULL,TSComputeRHSFunctionLinear,&appctx);
197: TSSetRHSJacobian(ts,A,A,RHSMatrixHeat,&appctx);
198: } else {
199: /*
200: For linear problems with a time-independent f(u) in the equation
201: u_t = f(u), the user provides the discretized right-hand-side
202: as a matrix only once, and then sets a null matrix evaluation
203: routine.
204: */
205: RHSMatrixHeat(ts,0.0,u,A,A,&appctx);
206: TSSetRHSFunction(ts,NULL,TSComputeRHSFunctionLinear,&appctx);
207: TSSetRHSJacobian(ts,A,A,TSComputeRHSJacobianConstant,&appctx);
208: }
210: if (tsproblem == TS_NONLINEAR) {
211: SNES snes;
212: TSSetRHSFunction(ts,NULL,RHSFunctionHeat,&appctx);
213: TSGetSNES(ts,&snes);
214: SNESSetJacobian(snes,NULL,NULL,SNESComputeJacobianDefault,NULL);
215: }
217: /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
218: Set solution vector and initial timestep
219: - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
221: dt = appctx.h*appctx.h/2.0;
222: TSSetInitialTimeStep(ts,0.0,dt);
223: TSSetSolution(ts,u);
225: /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
226: Customize timestepping solver:
227: - Set the solution method to be the Backward Euler method.
228: - Set timestepping duration info
229: Then set runtime options, which can override these defaults.
230: For example,
231: -ts_max_steps <maxsteps> -ts_final_time <maxtime>
232: to override the defaults set by TSSetDuration().
233: - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
235: TSSetDuration(ts,time_steps_max,time_total_max);
236: TSSetExactFinalTime(ts,TS_EXACTFINALTIME_STEPOVER);
237: TSSetFromOptions(ts);
239: /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
240: Solve the problem
241: - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
243: /*
244: Evaluate initial conditions
245: */
246: InitialConditions(u,&appctx);
248: /*
249: Run the timestepping solver
250: */
251: TSSolve(ts,u);
252: TSGetSolveTime(ts,&ftime);
253: TSGetTimeStepNumber(ts,&steps);
255: /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
256: View timestepping solver info
257: - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
258: PetscPrintf(PETSC_COMM_WORLD,"Total timesteps %D, Final time %g\n",steps,(double)ftime);
259: PetscPrintf(PETSC_COMM_WORLD,"Avg. error (2 norm) = %g Avg. error (max norm) = %g\n",(double)(appctx.norm_2/steps),(double)(appctx.norm_max/steps));
261: /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
262: Free work space. All PETSc objects should be destroyed when they
263: are no longer needed.
264: - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
266: TSDestroy(&ts);
267: MatDestroy(&A);
268: VecDestroy(&u);
269: PetscViewerDestroy(&appctx.viewer1);
270: PetscViewerDestroy(&appctx.viewer2);
271: VecDestroy(&appctx.localwork);
272: VecDestroy(&appctx.solution);
273: VecDestroy(&appctx.u_local);
274: DMDestroy(&appctx.da);
276: /*
277: Always call PetscFinalize() before exiting a program. This routine
278: - finalizes the PETSc libraries as well as MPI
279: - provides summary and diagnostic information if certain runtime
280: options are chosen (e.g., -log_summary).
281: */
282: PetscFinalize();
283: return 0;
284: }
285: /* --------------------------------------------------------------------- */
288: /*
289: InitialConditions - Computes the solution at the initial time.
291: Input Parameter:
292: u - uninitialized solution vector (global)
293: appctx - user-defined application context
295: Output Parameter:
296: u - vector with solution at initial time (global)
297: */
298: PetscErrorCode InitialConditions(Vec u,AppCtx *appctx)
299: {
300: PetscScalar *u_localptr,h = appctx->h;
301: PetscInt i,mybase,myend;
304: /*
305: Determine starting point of each processor's range of
306: grid values.
307: */
308: VecGetOwnershipRange(u,&mybase,&myend);
310: /*
311: Get a pointer to vector data.
312: - For default PETSc vectors, VecGetArray() returns a pointer to
313: the data array. Otherwise, the routine is implementation dependent.
314: - You MUST call VecRestoreArray() when you no longer need access to
315: the array.
316: - Note that the Fortran interface to VecGetArray() differs from the
317: C version. See the users manual for details.
318: */
319: VecGetArray(u,&u_localptr);
321: /*
322: We initialize the solution array by simply writing the solution
323: directly into the array locations. Alternatively, we could use
324: VecSetValues() or VecSetValuesLocal().
325: */
326: for (i=mybase; i<myend; i++) u_localptr[i-mybase] = PetscSinScalar(PETSC_PI*i*6.*h) + 3.*PetscSinScalar(PETSC_PI*i*2.*h);
328: /*
329: Restore vector
330: */
331: VecRestoreArray(u,&u_localptr);
333: /*
334: Print debugging information if desired
335: */
336: if (appctx->debug) {
337: PetscPrintf(appctx->comm,"initial guess vector\n");
338: VecView(u,PETSC_VIEWER_STDOUT_WORLD);
339: }
341: return 0;
342: }
343: /* --------------------------------------------------------------------- */
346: /*
347: ExactSolution - Computes the exact solution at a given time.
349: Input Parameters:
350: t - current time
351: solution - vector in which exact solution will be computed
352: appctx - user-defined application context
354: Output Parameter:
355: solution - vector with the newly computed exact solution
356: */
357: PetscErrorCode ExactSolution(PetscReal t,Vec solution,AppCtx *appctx)
358: {
359: PetscScalar *s_localptr,h = appctx->h,ex1,ex2,sc1,sc2;
360: PetscInt i,mybase,myend;
363: /*
364: Determine starting and ending points of each processor's
365: range of grid values
366: */
367: VecGetOwnershipRange(solution,&mybase,&myend);
369: /*
370: Get a pointer to vector data.
371: */
372: VecGetArray(solution,&s_localptr);
374: /*
375: Simply write the solution directly into the array locations.
376: Alternatively, we culd use VecSetValues() or VecSetValuesLocal().
377: */
378: ex1 = PetscExpReal(-36.*PETSC_PI*PETSC_PI*t); ex2 = PetscExpReal(-4.*PETSC_PI*PETSC_PI*t);
379: sc1 = PETSC_PI*6.*h; sc2 = PETSC_PI*2.*h;
380: for (i=mybase; i<myend; i++) s_localptr[i-mybase] = PetscSinScalar(sc1*(PetscReal)i)*ex1 + 3.*PetscSinScalar(sc2*(PetscReal)i)*ex2;
382: /*
383: Restore vector
384: */
385: VecRestoreArray(solution,&s_localptr);
386: return 0;
387: }
388: /* --------------------------------------------------------------------- */
391: /*
392: Monitor - User-provided routine to monitor the solution computed at
393: each timestep. This example plots the solution and computes the
394: error in two different norms.
396: Input Parameters:
397: ts - the timestep context
398: step - the count of the current step (with 0 meaning the
399: initial condition)
400: time - the current time
401: u - the solution at this timestep
402: ctx - the user-provided context for this monitoring routine.
403: In this case we use the application context which contains
404: information about the problem size, workspace and the exact
405: solution.
406: */
407: PetscErrorCode Monitor(TS ts,PetscInt step,PetscReal time,Vec u,void *ctx)
408: {
409: AppCtx *appctx = (AppCtx*) ctx; /* user-defined application context */
411: PetscReal norm_2,norm_max;
413: /*
414: View a graph of the current iterate
415: */
416: VecView(u,appctx->viewer2);
418: /*
419: Compute the exact solution
420: */
421: ExactSolution(time,appctx->solution,appctx);
423: /*
424: Print debugging information if desired
425: */
426: if (appctx->debug) {
427: PetscPrintf(appctx->comm,"Computed solution vector\n");
428: VecView(u,PETSC_VIEWER_STDOUT_WORLD);
429: PetscPrintf(appctx->comm,"Exact solution vector\n");
430: VecView(appctx->solution,PETSC_VIEWER_STDOUT_WORLD);
431: }
433: /*
434: Compute the 2-norm and max-norm of the error
435: */
436: VecAXPY(appctx->solution,-1.0,u);
437: VecNorm(appctx->solution,NORM_2,&norm_2);
438: norm_2 = PetscSqrtReal(appctx->h)*norm_2;
439: VecNorm(appctx->solution,NORM_MAX,&norm_max);
440: if (norm_2 < 1e-14) norm_2 = 0;
441: if (norm_max < 1e-14) norm_max = 0;
443: /*
444: PetscPrintf() causes only the first processor in this
445: communicator to print the timestep information.
446: */
447: PetscPrintf(appctx->comm,"Timestep %D: time = %g 2-norm error = %g max norm error = %g\n",step,(double)time,(double)norm_2,(double)norm_max);
448: appctx->norm_2 += norm_2;
449: appctx->norm_max += norm_max;
451: /*
452: View a graph of the error
453: */
454: VecView(appctx->solution,appctx->viewer1);
456: /*
457: Print debugging information if desired
458: */
459: if (appctx->debug) {
460: PetscPrintf(appctx->comm,"Error vector\n");
461: VecView(appctx->solution,PETSC_VIEWER_STDOUT_WORLD);
462: }
464: return 0;
465: }
467: /* --------------------------------------------------------------------- */
470: /*
471: RHSMatrixHeat - User-provided routine to compute the right-hand-side
472: matrix for the heat equation.
474: Input Parameters:
475: ts - the TS context
476: t - current time
477: global_in - global input vector
478: dummy - optional user-defined context, as set by TSetRHSJacobian()
480: Output Parameters:
481: AA - Jacobian matrix
482: BB - optionally different preconditioning matrix
483: str - flag indicating matrix structure
485: Notes:
486: RHSMatrixHeat computes entries for the locally owned part of the system.
487: - Currently, all PETSc parallel matrix formats are partitioned by
488: contiguous chunks of rows across the processors.
489: - Each processor needs to insert only elements that it owns
490: locally (but any non-local elements will be sent to the
491: appropriate processor during matrix assembly).
492: - Always specify global row and columns of matrix entries when
493: using MatSetValues(); we could alternatively use MatSetValuesLocal().
494: - Here, we set all entries for a particular row at once.
495: - Note that MatSetValues() uses 0-based row and column numbers
496: in Fortran as well as in C.
497: */
498: PetscErrorCode RHSMatrixHeat(TS ts,PetscReal t,Vec X,Mat AA,Mat BB,void *ctx)
499: {
500: Mat A = AA; /* Jacobian matrix */
501: AppCtx *appctx = (AppCtx*)ctx; /* user-defined application context */
503: PetscInt i,mstart,mend,idx[3];
504: PetscScalar v[3],stwo = -2./(appctx->h*appctx->h),sone = -.5*stwo;
506: /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
507: Compute entries for the locally owned part of the matrix
508: - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
510: MatGetOwnershipRange(A,&mstart,&mend);
512: /*
513: Set matrix rows corresponding to boundary data
514: */
516: if (mstart == 0) { /* first processor only */
517: v[0] = 1.0;
518: MatSetValues(A,1,&mstart,1,&mstart,v,INSERT_VALUES);
519: mstart++;
520: }
522: if (mend == appctx->m) { /* last processor only */
523: mend--;
524: v[0] = 1.0;
525: MatSetValues(A,1,&mend,1,&mend,v,INSERT_VALUES);
526: }
528: /*
529: Set matrix rows corresponding to interior data. We construct the
530: matrix one row at a time.
531: */
532: v[0] = sone; v[1] = stwo; v[2] = sone;
533: for (i=mstart; i<mend; i++) {
534: idx[0] = i-1; idx[1] = i; idx[2] = i+1;
535: MatSetValues(A,1,&i,3,idx,v,INSERT_VALUES);
536: }
538: /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
539: Complete the matrix assembly process and set some options
540: - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
541: /*
542: Assemble matrix, using the 2-step process:
543: MatAssemblyBegin(), MatAssemblyEnd()
544: Computations can be done while messages are in transition
545: by placing code between these two statements.
546: */
547: MatAssemblyBegin(A,MAT_FINAL_ASSEMBLY);
548: MatAssemblyEnd(A,MAT_FINAL_ASSEMBLY);
550: /*
551: Set and option to indicate that we will never add a new nonzero location
552: to the matrix. If we do, it will generate an error.
553: */
554: MatSetOption(A,MAT_NEW_NONZERO_LOCATION_ERR,PETSC_TRUE);
556: return 0;
557: }
561: PetscErrorCode RHSFunctionHeat(TS ts,PetscReal t,Vec globalin,Vec globalout,void *ctx)
562: {
564: Mat A;
567: TSGetRHSJacobian(ts,&A,NULL,NULL,&ctx);
568: RHSMatrixHeat(ts,t,globalin,A,NULL,ctx);
569: /* MatView(A,PETSC_VIEWER_STDOUT_WORLD); */
570: MatMult(A,globalin,globalout);
571: return(0);
572: }