Actual source code: ex13.c

petsc-master 2016-08-30
Report Typos and Errors
  2: static char help[] = "Solves a variable Poisson problem with KSP.\n\n";

  4: /*T
  5:    Concepts: KSP^basic sequential example
  6:    Concepts: KSP^Laplacian, 2d
  7:    Concepts: Laplacian, 2d
  8:    Processors: 1
  9: T*/

 11: /*
 12:   Include "petscksp.h" so that we can use KSP solvers.  Note that this file
 13:   automatically includes:
 14:      petscsys.h       - base PETSc routines   petscvec.h - vectors
 15:      petscmat.h - matrices
 16:      petscis.h     - index sets            petscksp.h - Krylov subspace methods
 17:      petscviewer.h - viewers               petscpc.h  - preconditioners
 18: */
 19:  #include <petscksp.h>

 21: /*
 22:     User-defined context that contains all the data structures used
 23:     in the linear solution process.
 24: */
 25: typedef struct {
 26:   Vec         x,b;       /* solution vector, right-hand-side vector */
 27:   Mat         A;          /* sparse matrix */
 28:   KSP         ksp;       /* linear solver context */
 29:   PetscInt    m,n;       /* grid dimensions */
 30:   PetscScalar hx2,hy2;   /* 1/(m+1)*(m+1) and 1/(n+1)*(n+1) */
 31: } UserCtx;

 33: extern PetscErrorCode UserInitializeLinearSolver(PetscInt,PetscInt,UserCtx*);
 34: extern PetscErrorCode UserFinalizeLinearSolver(UserCtx*);
 35: extern PetscErrorCode UserDoLinearSolver(PetscScalar*,UserCtx *userctx,PetscScalar *b,PetscScalar *x);

 39: int main(int argc,char **args)
 40: {
 41:   UserCtx        userctx;
 43:   PetscInt       m = 6,n = 7,t,tmax = 2,i,Ii,j,N;
 44:   PetscScalar    *userx,*rho,*solution,*userb,hx,hy,x,y;
 45:   PetscReal      enorm;

 47:   /*
 48:      Initialize the PETSc libraries
 49:   */
 50:   PetscInitialize(&argc,&args,(char*)0,help);if (ierr) return ierr;
 51:   /*
 52:      The next two lines are for testing only; these allow the user to
 53:      decide the grid size at runtime.
 54:   */
 55:   PetscOptionsGetInt(NULL,NULL,"-m",&m,NULL);
 56:   PetscOptionsGetInt(NULL,NULL,"-n",&n,NULL);

 58:   /*
 59:      Create the empty sparse matrix and linear solver data structures
 60:   */
 61:   UserInitializeLinearSolver(m,n,&userctx);
 62:   N    = m*n;

 64:   /*
 65:      Allocate arrays to hold the solution to the linear system.
 66:      This is not normally done in PETSc programs, but in this case,
 67:      since we are calling these routines from a non-PETSc program, we
 68:      would like to reuse the data structures from another code. So in
 69:      the context of a larger application these would be provided by
 70:      other (non-PETSc) parts of the application code.
 71:   */
 72:   PetscMalloc1(N,&userx);
 73:   PetscMalloc1(N,&userb);
 74:   PetscMalloc1(N,&solution);

 76:   /*
 77:       Allocate an array to hold the coefficients in the elliptic operator
 78:   */
 79:   PetscMalloc1(N,&rho);

 81:   /*
 82:      Fill up the array rho[] with the function rho(x,y) = x; fill the
 83:      right-hand-side b[] and the solution with a known problem for testing.
 84:   */
 85:   hx = 1.0/(m+1);
 86:   hy = 1.0/(n+1);
 87:   y  = hy;
 88:   Ii = 0;
 89:   for (j=0; j<n; j++) {
 90:     x = hx;
 91:     for (i=0; i<m; i++) {
 92:       rho[Ii]      = x;
 93:       solution[Ii] = PetscSinScalar(2.*PETSC_PI*x)*PetscSinScalar(2.*PETSC_PI*y);
 94:       userb[Ii]    = -2*PETSC_PI*PetscCosScalar(2*PETSC_PI *x)*PetscSinScalar(2*PETSC_PI*y) +
 95:                      8*PETSC_PI*PETSC_PI*x*PetscSinScalar(2*PETSC_PI *x)*PetscSinScalar(2*PETSC_PI*y);
 96:       x += hx;
 97:       Ii++;
 98:     }
 99:     y += hy;
100:   }

102:   /*
103:      Loop over a bunch of timesteps, setting up and solver the linear
104:      system for each time-step.

106:      Note this is somewhat artificial. It is intended to demonstrate how
107:      one may reuse the linear solver stuff in each time-step.
108:   */
109:   for (t=0; t<tmax; t++) {
110:      UserDoLinearSolver(rho,&userctx,userb,userx);

112:     /*
113:         Compute error: Note that this could (and usually should) all be done
114:         using the PETSc vector operations. Here we demonstrate using more
115:         standard programming practices to show how they may be mixed with
116:         PETSc.
117:     */
118:     enorm = 0.0;
119:     for (i=0; i<N; i++) enorm += PetscRealPart(PetscConj(solution[i]-userx[i])*(solution[i]-userx[i]));
120:     enorm *= PetscRealPart(hx*hy);
121:     PetscPrintf(PETSC_COMM_WORLD,"m %D n %D error norm %g\n",m,n,(double)enorm);
122:   }

124:   /*
125:      We are all finished solving linear systems, so we clean up the
126:      data structures.
127:   */
128:   PetscFree(rho);
129:   PetscFree(solution);
130:   PetscFree(userx);
131:   PetscFree(userb);
132:   UserFinalizeLinearSolver(&userctx);
133:   PetscFinalize();
134:   return ierr;
135: }

137: /* ------------------------------------------------------------------------*/
140: PetscErrorCode UserInitializeLinearSolver(PetscInt m,PetscInt n,UserCtx *userctx)
141: {
143:   PetscInt       N;

145:   /*
146:      Here we assume use of a grid of size m x n, with all points on the
147:      interior of the domain, i.e., we do not include the points corresponding
148:      to homogeneous Dirichlet boundary conditions.  We assume that the domain
149:      is [0,1]x[0,1].
150:   */
151:   userctx->m   = m;
152:   userctx->n   = n;
153:   userctx->hx2 = (m+1)*(m+1);
154:   userctx->hy2 = (n+1)*(n+1);
155:   N            = m*n;

157:   /*
158:      Create the sparse matrix. Preallocate 5 nonzeros per row.
159:   */
160:   MatCreateSeqAIJ(PETSC_COMM_SELF,N,N,5,0,&userctx->A);

162:   /*
163:      Create vectors. Here we create vectors with no memory allocated.
164:      This way, we can use the data structures already in the program
165:      by using VecPlaceArray() subroutine at a later stage.
166:   */
167:   VecCreateSeqWithArray(PETSC_COMM_SELF,1,N,NULL,&userctx->b);
168:   VecDuplicate(userctx->b,&userctx->x);

170:   /*
171:      Create linear solver context. This will be used repeatedly for all
172:      the linear solves needed.
173:   */
174:   KSPCreate(PETSC_COMM_SELF,&userctx->ksp);

176:   return 0;
177: }

181: /*
182:    Solves -div (rho grad psi) = F using finite differences.
183:    rho is a 2-dimensional array of size m by n, stored in Fortran
184:    style by columns. userb is a standard one-dimensional array.
185: */
186: /* ------------------------------------------------------------------------*/
187: PetscErrorCode UserDoLinearSolver(PetscScalar *rho,UserCtx *userctx,PetscScalar *userb,PetscScalar *userx)
188: {
190:   PetscInt       i,j,Ii,J,m = userctx->m,n = userctx->n;
191:   Mat            A = userctx->A;
192:   PC             pc;
193:   PetscScalar    v,hx2 = userctx->hx2,hy2 = userctx->hy2;

195:   /*
196:      This is not the most efficient way of generating the matrix
197:      but let's not worry about it. We should have separate code for
198:      the four corners, each edge and then the interior. Then we won't
199:      have the slow if-tests inside the loop.

201:      Computes the operator
202:              -div rho grad
203:      on an m by n grid with zero Dirichlet boundary conditions. The rho
204:      is assumed to be given on the same grid as the finite difference
205:      stencil is applied.  For a staggered grid, one would have to change
206:      things slightly.
207:   */
208:   Ii = 0;
209:   for (j=0; j<n; j++) {
210:     for (i=0; i<m; i++) {
211:       if (j>0) {
212:         J    = Ii - m;
213:         v    = -.5*(rho[Ii] + rho[J])*hy2;
214:         MatSetValues(A,1,&Ii,1,&J,&v,INSERT_VALUES);
215:       }
216:       if (j<n-1) {
217:         J    = Ii + m;
218:         v    = -.5*(rho[Ii] + rho[J])*hy2;
219:         MatSetValues(A,1,&Ii,1,&J,&v,INSERT_VALUES);
220:       }
221:       if (i>0) {
222:         J    = Ii - 1;
223:         v    = -.5*(rho[Ii] + rho[J])*hx2;
224:         MatSetValues(A,1,&Ii,1,&J,&v,INSERT_VALUES);
225:       }
226:       if (i<m-1) {
227:         J    = Ii + 1;
228:         v    = -.5*(rho[Ii] + rho[J])*hx2;
229:         MatSetValues(A,1,&Ii,1,&J,&v,INSERT_VALUES);
230:       }
231:       v    = 2.0*rho[Ii]*(hx2+hy2);
232:       MatSetValues(A,1,&Ii,1,&Ii,&v,INSERT_VALUES);
233:       Ii++;
234:     }
235:   }

237:   /*
238:      Assemble matrix
239:   */
240:   MatAssemblyBegin(A,MAT_FINAL_ASSEMBLY);
241:   MatAssemblyEnd(A,MAT_FINAL_ASSEMBLY);

243:   /*
244:      Set operators. Here the matrix that defines the linear system
245:      also serves as the preconditioning matrix. Since all the matrices
246:      will have the same nonzero pattern here, we indicate this so the
247:      linear solvers can take advantage of this.
248:   */
249:   KSPSetOperators(userctx->ksp,A,A);

251:   /*
252:      Set linear solver defaults for this problem (optional).
253:      - Here we set it to use direct LU factorization for the solution
254:   */
255:   KSPGetPC(userctx->ksp,&pc);
256:   PCSetType(pc,PCLU);

258:   /*
259:      Set runtime options, e.g.,
260:         -ksp_type <type> -pc_type <type> -ksp_monitor -ksp_rtol <rtol>
261:      These options will override those specified above as long as
262:      KSPSetFromOptions() is called _after_ any other customization
263:      routines.

265:      Run the program with the option -help to see all the possible
266:      linear solver options.
267:   */
268:   KSPSetFromOptions(userctx->ksp);

270:   /*
271:      This allows the PETSc linear solvers to compute the solution
272:      directly in the user's array rather than in the PETSc vector.

274:      This is essentially a hack and not highly recommend unless you
275:      are quite comfortable with using PETSc. In general, users should
276:      write their entire application using PETSc vectors rather than
277:      arrays.
278:   */
279:   VecPlaceArray(userctx->x,userx);
280:   VecPlaceArray(userctx->b,userb);

282:   /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
283:                       Solve the linear system
284:      - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */

286:   KSPSolve(userctx->ksp,userctx->b,userctx->x);

288:   /*
289:     Put back the PETSc array that belongs in the vector xuserctx->x
290:   */
291:   VecResetArray(userctx->x);
292:   VecResetArray(userctx->b);

294:   return 0;
295: }

297: /* ------------------------------------------------------------------------*/
300: PetscErrorCode UserFinalizeLinearSolver(UserCtx *userctx)
301: {
303:   /*
304:      We are all done and don't need to solve any more linear systems, so
305:      we free the work space.  All PETSc objects should be destroyed when
306:      they are no longer needed.
307:   */
308:   KSPDestroy(&userctx->ksp);
309:   VecDestroy(&userctx->x);
310:   VecDestroy(&userctx->b);
311:   MatDestroy(&userctx->A);
312:   return 0;
313: }