Actual source code: ex5.c

  1: static char help[] = "Newton method to solve u'' + u^{2} = f, sequentially.\n\
  2: This example tests PCVPBJacobiSetBlocks().\n\n";

  4: /*
  5:    Include "petscsnes.h" so that we can use SNES solvers.  Note that this
  6:    file automatically includes:
  7:      petscsys.h - base PETSc routines
  8:      petscvec.h - vectors
  9:      petscmat.h - matrices
 10:      petscis.h  - index sets
 11:      petscpc.h  - preconditioners
 12:      petscksp.h - linear solvers
 13: */

 15: #include <petscsnes.h>

 17: /*
 18:    User-defined routines
 19: */
 20: extern PetscErrorCode FormJacobian(SNES, Vec, Mat, Mat, void *);
 21: extern PetscErrorCode FormFunction(SNES, Vec, Vec, void *);
 22: extern PetscErrorCode FormInitialGuess(Vec);

 24: int main(int argc, char **argv)
 25: {
 26:   SNES        snes;       /* SNES context */
 27:   Vec         x, r, F, U; /* vectors */
 28:   Mat         J;          /* Jacobian matrix */
 29:   PetscInt    its, n = 5, nb, maxit, maxf, *lens;
 30:   PetscMPIInt size;
 31:   PetscScalar h, xp, v, none = -1.0;
 32:   PetscReal   abstol, rtol, stol, norm;
 33:   KSP         ksp;
 34:   PC          pc;

 36:   PetscFunctionBeginUser;
 37:   PetscCall(PetscInitialize(&argc, &argv, NULL, help));
 38:   PetscCallMPI(MPI_Comm_size(PETSC_COMM_WORLD, &size));
 39:   PetscCheck(size == 1, PETSC_COMM_SELF, PETSC_ERR_WRONG_MPI_SIZE, "This is a uniprocessor example only");
 40:   PetscCall(PetscOptionsGetInt(NULL, NULL, "-n", &n, NULL));
 41:   PetscCheck(n % 5 == 0, PETSC_COMM_SELF, PETSC_ERR_SUP, "n must be a multiple of 5");
 42:   h = 1.0 / (n - 1);

 44:   /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
 45:      Create vector data structures
 46:      - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
 47:   /*
 48:      Note that we form 1 vector from scratch and then duplicate as needed.
 49:   */
 50:   PetscCall(VecCreate(PETSC_COMM_WORLD, &x));
 51:   PetscCall(VecSetSizes(x, PETSC_DECIDE, n));
 52:   PetscCall(VecSetFromOptions(x));
 53:   PetscCall(VecDuplicate(x, &r));
 54:   PetscCall(VecDuplicate(x, &F));
 55:   PetscCall(VecDuplicate(x, &U));

 57:   /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
 58:      Create matrix data structure
 59:      - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */

 61:   PetscCall(MatCreate(PETSC_COMM_WORLD, &J));
 62:   PetscCall(MatSetSizes(J, PETSC_DECIDE, PETSC_DECIDE, n, n));
 63:   PetscCall(MatSetFromOptions(J));
 64:   PetscCall(MatSeqAIJSetPreallocation(J, 3, NULL));
 65:   PetscCall(MatSetBlockSize(J, 5));

 67:   nb = 3 * n / 5;
 68:   PetscCall(PetscMalloc1(nb, &lens));
 69:   for (PetscInt i = 0; i < nb / 3; i++) {
 70:     lens[3 * i + 0] = 1;
 71:     lens[3 * i + 1] = 2;
 72:     lens[3 * i + 2] = 2;
 73:   }
 74:   PetscCall(MatSetVariableBlockSizes(J, nb, lens));
 75:   PetscCall(PetscFree(lens));

 77:   /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
 78:      Create nonlinear solver context
 79:      - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */

 81:   PetscCall(SNESCreate(PETSC_COMM_WORLD, &snes));
 82:   PetscCall(SNESGetKSP(snes, &ksp));
 83:   PetscCall(KSPGetPC(ksp, &pc));
 84:   PetscCall(PCSetType(pc, PCVPBJACOBI));

 86:   /*
 87:      Set function evaluation routine and vector
 88:   */
 89:   PetscCall(SNESSetFunction(snes, r, FormFunction, (void *)F));

 91:   /*
 92:      Set Jacobian matrix data structure and default Jacobian evaluation
 93:      routine. User can override with:
 94:      -snes_fd : default finite differencing approximation of Jacobian
 95:      -snes_mf : matrix-free Newton-Krylov method with no preconditioning
 96:                 (unless user explicitly sets preconditioner)
 97:      -snes_mf_operator : form matrix used to construct the preconditioner as set by the user,
 98:                          but use matrix-free approx for Jacobian-vector
 99:                          products within Newton-Krylov method
100:   */

102:   PetscCall(SNESSetJacobian(snes, J, J, FormJacobian, NULL));

104:   /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
105:      Customize nonlinear solver; set runtime options
106:    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */

108:   /*
109:      Set names for some vectors to facilitate monitoring (optional)
110:   */
111:   PetscCall(PetscObjectSetName((PetscObject)x, "Approximate Solution"));
112:   PetscCall(PetscObjectSetName((PetscObject)U, "Exact Solution"));

114:   /*
115:      Set SNES/KSP/KSP/PC runtime options, e.g.,
116:          -snes_view -snes_monitor -ksp_type <ksp> -pc_type <pc>
117:   */
118:   PetscCall(SNESSetFromOptions(snes));

120:   /*
121:      Print parameters used for convergence testing (optional) ... just
122:      to demonstrate this routine; this information is also printed with
123:      the option -snes_view
124:   */
125:   PetscCall(SNESGetTolerances(snes, &abstol, &rtol, &stol, &maxit, &maxf));
126:   PetscCall(PetscPrintf(PETSC_COMM_WORLD, "atol=%g, rtol=%g, stol=%g, maxit=%" PetscInt_FMT ", maxf=%" PetscInt_FMT "\n", (double)abstol, (double)rtol, (double)stol, maxit, maxf));

128:   /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
129:      Initialize application:
130:      Store right-hand side of PDE and exact solution
131:    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */

133:   xp = 0.0;
134:   for (PetscInt i = 0; i < n; i++) {
135:     v = 6.0 * xp + PetscPowScalar(xp + 1.e-12, 6.0); /* +1.e-12 is to prevent 0^6 */
136:     PetscCall(VecSetValues(F, 1, &i, &v, INSERT_VALUES));
137:     v = xp * xp * xp;
138:     PetscCall(VecSetValues(U, 1, &i, &v, INSERT_VALUES));
139:     xp += h;
140:   }

142:   /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
143:      Evaluate initial guess; then solve nonlinear system
144:    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
145:   /*
146:      Note: The user should initialize the vector, x, with the initial guess
147:      for the nonlinear solver prior to calling SNESSolve().  In particular,
148:      to employ an initial guess of zero, the user should explicitly set
149:      this vector to zero by calling VecSet().
150:   */
151:   PetscCall(FormInitialGuess(x));
152:   PetscCall(SNESSolve(snes, NULL, x));
153:   PetscCall(SNESGetIterationNumber(snes, &its));
154:   PetscCall(PetscPrintf(PETSC_COMM_WORLD, "number of SNES iterations = %" PetscInt_FMT "\n\n", its));

156:   /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
157:      Check solution and clean up
158:    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */

160:   /*
161:      Check the error
162:   */
163:   PetscCall(VecAXPY(x, none, U));
164:   PetscCall(VecNorm(x, NORM_2, &norm));
165:   PetscCall(PetscPrintf(PETSC_COMM_WORLD, "Norm of error %g, Iterations %" PetscInt_FMT "\n", (double)norm, its));

167:   /*
168:      Free work space.  All PETSc objects should be destroyed when they
169:      are no longer needed.
170:   */
171:   PetscCall(VecDestroy(&x));
172:   PetscCall(VecDestroy(&r));
173:   PetscCall(VecDestroy(&U));
174:   PetscCall(VecDestroy(&F));
175:   PetscCall(MatDestroy(&J));
176:   PetscCall(SNESDestroy(&snes));
177:   PetscCall(PetscFinalize());
178:   return 0;
179: }

181: /*
182:    FormInitialGuess - Computes initial guess.

184:    Input/Output Parameter:
185: .  x - the solution vector
186: */
187: PetscErrorCode FormInitialGuess(Vec x)
188: {
189:   PetscScalar pfive = .50;

191:   PetscFunctionBeginUser;
192:   PetscCall(VecSet(x, pfive));
193:   PetscFunctionReturn(PETSC_SUCCESS);
194: }

196: /*
197:    FormFunction - Evaluates nonlinear function, F(x).

199:    Input Parameters:
200: .  snes - the SNES context
201: .  x - input vector
202: .  ctx - optional user-defined context, as set by SNESSetFunction()

204:    Output Parameter:
205: .  f - function vector

207:    Note:
208:    The user-defined context can contain any application-specific data
209:    needed for the function evaluation (such as various parameters, work
210:    vectors, and grid information).  In this program the context is just
211:    a vector containing the right-hand side of the discretized PDE.
212:  */

214: PetscErrorCode FormFunction(SNES snes, Vec x, Vec f, PetscCtx ctx)
215: {
216:   Vec                g = (Vec)ctx;
217:   const PetscScalar *xx, *gg;
218:   PetscScalar       *ff, d;
219:   PetscInt           i, n;

221:   PetscFunctionBeginUser;
222:   /*
223:      Get pointers to vector data.
224:        - For default PETSc vectors, VecGetArray() returns a pointer to
225:          the data array.  Otherwise, the routine is implementation dependent.
226:        - You MUST call VecRestoreArray() when you no longer need access to
227:          the array.
228:   */
229:   PetscCall(VecGetArrayRead(x, &xx));
230:   PetscCall(VecGetArray(f, &ff));
231:   PetscCall(VecGetArrayRead(g, &gg));

233:   /*
234:      Compute function
235:   */
236:   PetscCall(VecGetSize(x, &n));
237:   d     = (PetscReal)(n - 1);
238:   d     = d * d;
239:   ff[0] = xx[0];
240:   for (i = 1; i < n - 1; i++) ff[i] = d * (xx[i - 1] - 2.0 * xx[i] + xx[i + 1]) + xx[i] * xx[i] - gg[i];
241:   ff[n - 1] = xx[n - 1] - 1.0;

243:   /*
244:      Restore vectors
245:   */
246:   PetscCall(VecRestoreArrayRead(x, &xx));
247:   PetscCall(VecRestoreArray(f, &ff));
248:   PetscCall(VecRestoreArrayRead(g, &gg));
249:   PetscFunctionReturn(PETSC_SUCCESS);
250: }

252: /*
253:    FormJacobian - Evaluates Jacobian matrix.

255:    Input Parameters:
256: .  snes - the SNES context
257: .  x - input vector
258: .  dummy - optional user-defined context (not used here)

260:    Output Parameters:
261: .  jac - Jacobian matrix
262: .  B - optionally different matrix used to construct the preconditioner

264: */

266: PetscErrorCode FormJacobian(SNES snes, Vec x, Mat jac, Mat B, void *dummy)
267: {
268:   const PetscScalar *xx;
269:   PetscScalar        A[3], d;
270:   PetscInt           i, n, j[3];

272:   PetscFunctionBeginUser;
273:   /*
274:      Get pointer to vector data
275:   */
276:   PetscCall(VecGetArrayRead(x, &xx));

278:   /*
279:      Compute Jacobian entries and insert into matrix.
280:       - Note that in this case we set all elements for a particular
281:         row at once.
282:   */
283:   PetscCall(VecGetSize(x, &n));
284:   d = (PetscReal)(n - 1);
285:   d = d * d;

287:   /*
288:      Interior grid points
289:   */
290:   for (i = 1; i < n - 1; i++) {
291:     j[0] = i - 1;
292:     j[1] = i;
293:     j[2] = i + 1;
294:     A[0] = d;
295:     A[1] = -2.0 * d + 2.0 * xx[i];
296:     A[2] = d;
297:     PetscCall(MatSetValues(B, 1, &i, 3, j, A, INSERT_VALUES));
298:   }

300:   /*
301:      Boundary points
302:   */
303:   i    = 0;
304:   A[0] = 1.0;

306:   PetscCall(MatSetValues(B, 1, &i, 1, &i, A, INSERT_VALUES));

308:   i    = n - 1;
309:   A[0] = 1.0;

311:   PetscCall(MatSetValues(B, 1, &i, 1, &i, A, INSERT_VALUES));

313:   /*
314:      Restore vector
315:   */
316:   PetscCall(VecRestoreArrayRead(x, &xx));

318:   /*
319:      Assemble matrix
320:   */
321:   PetscCall(MatAssemblyBegin(B, MAT_FINAL_ASSEMBLY));
322:   PetscCall(MatAssemblyEnd(B, MAT_FINAL_ASSEMBLY));
323:   if (jac != B) {
324:     PetscCall(MatAssemblyBegin(jac, MAT_FINAL_ASSEMBLY));
325:     PetscCall(MatAssemblyEnd(jac, MAT_FINAL_ASSEMBLY));
326:   }
327:   PetscFunctionReturn(PETSC_SUCCESS);
328: }

330: /*TEST

332:    testset:
333:      args: -snes_monitor -snes_view -ksp_monitor
334:      output_file: output/ex5_1.out
335:      filter: grep -v "type: seqaij"

337:      test:
338:       suffix: 1

340:      test:
341:       suffix: cuda
342:       requires: cuda
343:       args: -mat_type aijcusparse -vec_type cuda

345:      test:
346:       suffix: kok
347:       requires: kokkos_kernels
348:       args: -mat_type aijkokkos -vec_type kokkos

350:    # this is just a test for SNESKSPTRANSPOSEONLY and KSPSolveTranspose() to behave properly
351:    # the solution is wrong on purpose
352:    test:
353:       requires: !single !complex
354:       suffix: transpose_only
355:       args: -snes_monitor -snes_view -ksp_monitor -snes_type ksptransposeonly -pc_type ilu -snes_test_jacobian -snes_test_jacobian_view -ksp_view_rhs -ksp_view_solution -ksp_view_mat_explicit -ksp_view_preconditioned_operator_explicit

357:    test:
358:       requires: mumps
359:       suffix: mumps
360:       args: -pc_type lu -pc_factor_mat_solver_type mumps -mat_mumps_icntl_15 1 -snes_monitor -ksp_monitor

362:    test:
363:       suffix: fieldsplit_1
364:       args: -snes_monitor -snes_view -ksp_monitor -pc_type fieldsplit -pc_fieldsplit_0_fields 0,1 -pc_fieldsplit_1_fields 2,3,4

366:    test:
367:       suffix: fieldsplit_2
368:       args: -snes_monitor -snes_view -ksp_monitor -pc_type fieldsplit -pc_fieldsplit_0_fields 1,0 -pc_fieldsplit_1_fields 2,3,4

370: TEST*/