Actual source code: ex15.c

  2: static char help[] = "Solves a linear system in parallel with KSP.  Also\n\
  3: illustrates setting a user-defined shell preconditioner and using the\n\
  4: macro __FUNCT__ to define routine names for use in error handling.\n\
  5: Input parameters include:\n\
  6:   -user_defined_pc : Activate a user-defined preconditioner\n\n";

  8: /*T
  9:    Concepts: KSP^basic parallel example
 10:    Concepts: PC^setting a user-defined shell preconditioner
 11:    Concepts: error handling^Using the macro __FUNCT__ to define routine names;
 12:    Processors: n
 13: T*/

 15: /* 
 16:   Include "petscksp.h" so that we can use KSP solvers.  Note that this file
 17:   automatically includes:
 18:      petsc.h       - base PETSc routines   petscvec.h - vectors
 19:      petscsys.h    - system routines       petscmat.h - matrices
 20:      petscis.h     - index sets            petscksp.h - Krylov subspace methods
 21:      petscviewer.h - viewers               petscpc.h  - preconditioners
 22: */
 23:  #include petscksp.h

 25: /* Define context for user-provided preconditioner */
 26: typedef struct {
 27:   Vec diag;
 28: } SampleShellPC;

 30: /* Declare routines for user-provided preconditioner */

 36: /* 
 37:    User-defined routines.  Note that immediately before each routine below,
 38:    we define the macro __FUNCT__ to be a string containing the routine name.
 39:    If defined, this macro is used in the PETSc error handlers to provide a
 40:    complete traceback of routine names.  All PETSc library routines use this
 41:    macro, and users can optionally employ it as well in their application
 42:    codes.  Note that users can get a traceback of PETSc errors regardless of
 43:    whether they define __FUNCT__ in application codes; this macro merely
 44:    provides the added traceback detail of the application routine names.
 45: */

 49: int main(int argc,char **args)
 50: {
 51:   Vec            x,b,u;   /* approx solution, RHS, exact solution */
 52:   Mat            A;         /* linear system matrix */
 53:   KSP            ksp;      /* linear solver context */
 54:   PC             pc;        /* preconditioner context */
 55:   PetscReal      norm;      /* norm of solution error */
 56:   SampleShellPC  *shell;    /* user-defined preconditioner context */
 57:   PetscScalar    v,one = 1.0,none = -1.0;
 58:   PetscInt       i,j,Ii,J,Istart,Iend,m = 8,n = 7,its;
 60:   PetscTruth     user_defined_pc;

 62:   PetscInitialize(&argc,&args,(char *)0,help);
 63:   PetscOptionsGetInt(PETSC_NULL,"-m",&m,PETSC_NULL);
 64:   PetscOptionsGetInt(PETSC_NULL,"-n",&n,PETSC_NULL);

 66:   /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
 67:          Compute the matrix and right-hand-side vector that define
 68:          the linear system, Ax = b.
 69:      - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
 70:   /* 
 71:      Create parallel matrix, specifying only its global dimensions.
 72:      When using MatCreate(), the matrix format can be specified at
 73:      runtime. Also, the parallel partioning of the matrix is
 74:      determined by PETSc at runtime.
 75:   */
 76:   MatCreate(PETSC_COMM_WORLD,&A);
 77:   MatSetSizes(A,PETSC_DECIDE,PETSC_DECIDE,m*n,m*n);
 78:   MatSetFromOptions(A);

 80:   /* 
 81:      Currently, all PETSc parallel matrix formats are partitioned by
 82:      contiguous chunks of rows across the processors.  Determine which
 83:      rows of the matrix are locally owned. 
 84:   */
 85:   MatGetOwnershipRange(A,&Istart,&Iend);

 87:   /* 
 88:      Set matrix elements for the 2-D, five-point stencil in parallel.
 89:       - Each processor needs to insert only elements that it owns
 90:         locally (but any non-local elements will be sent to the
 91:         appropriate processor during matrix assembly). 
 92:       - Always specify global rows and columns of matrix entries.
 93:    */
 94:   for (Ii=Istart; Ii<Iend; Ii++) {
 95:     v = -1.0; i = Ii/n; j = Ii - i*n;
 96:     if (i>0)   {J = Ii - n; MatSetValues(A,1,&Ii,1,&J,&v,INSERT_VALUES);}
 97:     if (i<m-1) {J = Ii + n; MatSetValues(A,1,&Ii,1,&J,&v,INSERT_VALUES);}
 98:     if (j>0)   {J = Ii - 1; MatSetValues(A,1,&Ii,1,&J,&v,INSERT_VALUES);}
 99:     if (j<n-1) {J = Ii + 1; MatSetValues(A,1,&Ii,1,&J,&v,INSERT_VALUES);}
100:     v = 4.0; MatSetValues(A,1,&Ii,1,&Ii,&v,INSERT_VALUES);
101:   }

103:   /* 
104:      Assemble matrix, using the 2-step process:
105:        MatAssemblyBegin(), MatAssemblyEnd()
106:      Computations can be done while messages are in transition
107:      by placing code between these two statements.
108:   */
109:   MatAssemblyBegin(A,MAT_FINAL_ASSEMBLY);
110:   MatAssemblyEnd(A,MAT_FINAL_ASSEMBLY);

112:   /* 
113:      Create parallel vectors.
114:       - When using VecCreate() VecSetSizes() and VecSetFromOptions(),
115:         we specify only the vector's global
116:         dimension; the parallel partitioning is determined at runtime. 
117:       - Note: We form 1 vector from scratch and then duplicate as needed.
118:   */
119:   VecCreate(PETSC_COMM_WORLD,&u);
120:   VecSetSizes(u,PETSC_DECIDE,m*n);
121:   VecSetFromOptions(u);
122:   VecDuplicate(u,&b);
123:   VecDuplicate(b,&x);

125:   /* 
126:      Set exact solution; then compute right-hand-side vector.
127:   */
128:   VecSet(u,one);
129:   MatMult(A,u,b);

131:   /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
132:                 Create the linear solver and set various options
133:      - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */

135:   /* 
136:      Create linear solver context
137:   */
138:   KSPCreate(PETSC_COMM_WORLD,&ksp);

140:   /* 
141:      Set operators. Here the matrix that defines the linear system
142:      also serves as the preconditioning matrix.
143:   */
144:   KSPSetOperators(ksp,A,A,DIFFERENT_NONZERO_PATTERN);

146:   /* 
147:      Set linear solver defaults for this problem (optional).
148:      - By extracting the KSP and PC contexts from the KSP context,
149:        we can then directly call any KSP and PC routines
150:        to set various options.
151:   */
152:   KSPGetPC(ksp,&pc);
153:   KSPSetTolerances(ksp,1.e-7,PETSC_DEFAULT,PETSC_DEFAULT,
154:          PETSC_DEFAULT);

156:   /*
157:      Set a user-defined "shell" preconditioner if desired
158:   */
159:   PetscOptionsHasName(PETSC_NULL,"-user_defined_pc",&user_defined_pc);
160:   if (user_defined_pc) {
161:     /* (Required) Indicate to PETSc that we're using a "shell" preconditioner */
162:     PCSetType(pc,PCSHELL);

164:     /* (Optional) Create a context for the user-defined preconditioner; this
165:        context can be used to contain any application-specific data. */
166:     SampleShellPCCreate(&shell);

168:     /* (Required) Set the user-defined routine for applying the preconditioner */
169:     PCShellSetApply(pc,SampleShellPCApply);
170:     PCShellSetContext(pc,shell);

172:     /* (Optional) Set a name for the preconditioner, used for PCView() */
173:     PCShellSetName(pc,"MyPreconditioner");

175:     /* (Optional) Do any setup required for the preconditioner */
176:     SampleShellPCSetUp(shell,A,x);

178:   } else {
179:     PCSetType(pc,PCJACOBI);
180:   }

182:   /* 
183:     Set runtime options, e.g.,
184:         -ksp_type <type> -pc_type <type> -ksp_monitor -ksp_rtol <rtol>
185:     These options will override those specified above as long as
186:     KSPSetFromOptions() is called _after_ any other customization
187:     routines.
188:   */
189:   KSPSetFromOptions(ksp);

191:   /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
192:                       Solve the linear system
193:      - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */

195:   KSPSolve(ksp,b,x);

197:   /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
198:                       Check solution and clean up
199:      - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */

201:   /* 
202:      Check the error
203:   */
204:   VecAXPY(x,none,u);
205:   VecNorm(x,NORM_2,&norm);
206:   KSPGetIterationNumber(ksp,&its);
207:   PetscPrintf(PETSC_COMM_WORLD,"Norm of error %A iterations %D\n",norm,its);

209:   /* 
210:      Free work space.  All PETSc objects should be destroyed when they
211:      are no longer needed.
212:   */
213:   KSPDestroy(ksp);
214:   VecDestroy(u);  VecDestroy(x);
215:   VecDestroy(b);  MatDestroy(A);

217:   if (user_defined_pc) {
218:     SampleShellPCDestroy(shell);
219:   }

221:   PetscFinalize();
222:   return 0;

224: }

226: /***********************************************************************/
227: /*          Routines for a user-defined shell preconditioner           */
228: /***********************************************************************/

232: /*
233:    SampleShellPCCreate - This routine creates a user-defined
234:    preconditioner context.

236:    Output Parameter:
237: .  shell - user-defined preconditioner context
238: */
239: PetscErrorCode SampleShellPCCreate(SampleShellPC **shell)
240: {
241:   SampleShellPC  *newctx;

244:   PetscNew(SampleShellPC,&newctx);
245:   newctx->diag = 0;
246:   *shell       = newctx;
247:   return 0;
248: }
249: /* ------------------------------------------------------------------- */
252: /*
253:    SampleShellPCSetUp - This routine sets up a user-defined
254:    preconditioner context.  

256:    Input Parameters:
257: .  shell - user-defined preconditioner context
258: .  pmat  - preconditioner matrix
259: .  x     - vector

261:    Output Parameter:
262: .  shell - fully set up user-defined preconditioner context

264:    Notes:
265:    In this example, we define the shell preconditioner to be Jacobi's
266:    method.  Thus, here we create a work vector for storing the reciprocal
267:    of the diagonal of the preconditioner matrix; this vector is then
268:    used within the routine SampleShellPCApply().
269: */
270: PetscErrorCode SampleShellPCSetUp(SampleShellPC *shell,Mat pmat,Vec x)
271: {
272:   Vec            diag;

275:   VecDuplicate(x,&diag);
276:   MatGetDiagonal(pmat,diag);
277:   VecReciprocal(diag);
278:   shell->diag = diag;

280:   return 0;
281: }
282: /* ------------------------------------------------------------------- */
285: /*
286:    SampleShellPCApply - This routine demonstrates the use of a
287:    user-provided preconditioner.

289:    Input Parameters:
290: .  ctx - optional user-defined context, as set by PCShellSetContext()
291: .  x - input vector

293:    Output Parameter:
294: .  y - preconditioned vector

296:    Notes:
297:    Note that the PCSHELL preconditioner passes a void pointer as the
298:    first input argument.  This can be cast to be the whatever the user
299:    has set (via PCSetShellApply()) the application-defined context to be.

301:    This code implements the Jacobi preconditioner, merely as an
302:    example of working with a PCSHELL.  Note that the Jacobi method
303:    is already provided within PETSc.
304: */
305: PetscErrorCode SampleShellPCApply(void *ctx,Vec x,Vec y)
306: {
307:   SampleShellPC   *shell = (SampleShellPC*)ctx;
308:   PetscErrorCode  ierr;

310:   VecPointwiseMult(y,x,shell->diag);

312:   return 0;
313: }
314: /* ------------------------------------------------------------------- */
317: /*
318:    SampleShellPCDestroy - This routine destroys a user-defined
319:    preconditioner context.

321:    Input Parameter:
322: .  shell - user-defined preconditioner context
323: */
324: PetscErrorCode SampleShellPCDestroy(SampleShellPC *shell)
325: {

328:   VecDestroy(shell->diag);
329:   PetscFree(shell);

331:   return 0;
332: }