xref: /petsc/src/snes/tests/ex5.c (revision d71ae5a4db6382e7f06317b8d368875286fe9008)
1c4762a1bSJed Brown 
2c4762a1bSJed Brown static char help[] = "Newton method to solve u'' + u^{2} = f, sequentially.\n\
3c4762a1bSJed Brown This example tests PCVPBJacobiSetBlocks().\n\n";
4c4762a1bSJed Brown 
5c4762a1bSJed Brown /*
6c4762a1bSJed Brown    Include "petscsnes.h" so that we can use SNES solvers.  Note that this
7c4762a1bSJed Brown    file automatically includes:
8c4762a1bSJed Brown      petscsys.h       - base PETSc routines   petscvec.h - vectors
9c4762a1bSJed Brown      petscmat.h - matrices
10c4762a1bSJed Brown      petscis.h     - index sets            petscksp.h - Krylov subspace methods
11c4762a1bSJed Brown      petscviewer.h - viewers               petscpc.h  - preconditioners
12c4762a1bSJed Brown      petscksp.h   - linear solvers
13c4762a1bSJed Brown */
14c4762a1bSJed Brown 
15c4762a1bSJed Brown #include <petscsnes.h>
16c4762a1bSJed Brown 
17c4762a1bSJed Brown /*
18c4762a1bSJed Brown    User-defined routines
19c4762a1bSJed Brown */
20c4762a1bSJed Brown extern PetscErrorCode FormJacobian(SNES, Vec, Mat, Mat, void *);
21c4762a1bSJed Brown extern PetscErrorCode FormFunction(SNES, Vec, Vec, void *);
22c4762a1bSJed Brown extern PetscErrorCode FormInitialGuess(Vec);
23c4762a1bSJed Brown 
24*d71ae5a4SJacob Faibussowitsch int main(int argc, char **argv)
25*d71ae5a4SJacob Faibussowitsch {
26c4762a1bSJed Brown   SNES        snes;       /* SNES context */
27c4762a1bSJed Brown   Vec         x, r, F, U; /* vectors */
28c4762a1bSJed Brown   Mat         J;          /* Jacobian matrix */
29c4762a1bSJed Brown   PetscInt    its, n = 5, i, maxit, maxf, lens[3] = {1, 2, 2};
30c4762a1bSJed Brown   PetscMPIInt size;
31c4762a1bSJed Brown   PetscScalar h, xp, v, none = -1.0;
32c4762a1bSJed Brown   PetscReal   abstol, rtol, stol, norm;
33c4762a1bSJed Brown   KSP         ksp;
34c4762a1bSJed Brown   PC          pc;
35c4762a1bSJed Brown 
36327415f7SBarry Smith   PetscFunctionBeginUser;
379566063dSJacob Faibussowitsch   PetscCall(PetscInitialize(&argc, &argv, (char *)0, help));
389566063dSJacob Faibussowitsch   PetscCallMPI(MPI_Comm_size(PETSC_COMM_WORLD, &size));
39be096a46SBarry Smith   PetscCheck(size == 1, PETSC_COMM_SELF, PETSC_ERR_WRONG_MPI_SIZE, "This is a uniprocessor example only!");
409566063dSJacob Faibussowitsch   PetscCall(PetscOptionsGetInt(NULL, NULL, "-n", &n, NULL));
41c4762a1bSJed Brown   h = 1.0 / (n - 1);
42c4762a1bSJed Brown 
43c4762a1bSJed Brown   /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
44c4762a1bSJed Brown      Create nonlinear solver context
45c4762a1bSJed Brown      - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
46c4762a1bSJed Brown 
479566063dSJacob Faibussowitsch   PetscCall(SNESCreate(PETSC_COMM_WORLD, &snes));
489566063dSJacob Faibussowitsch   PetscCall(SNESGetKSP(snes, &ksp));
499566063dSJacob Faibussowitsch   PetscCall(KSPGetPC(ksp, &pc));
509566063dSJacob Faibussowitsch   PetscCall(PCSetType(pc, PCVPBJACOBI));
51c4762a1bSJed Brown   /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
52c4762a1bSJed Brown      Create vector data structures; set function evaluation routine
53c4762a1bSJed Brown      - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
54c4762a1bSJed Brown   /*
55c4762a1bSJed Brown      Note that we form 1 vector from scratch and then duplicate as needed.
56c4762a1bSJed Brown   */
579566063dSJacob Faibussowitsch   PetscCall(VecCreate(PETSC_COMM_WORLD, &x));
589566063dSJacob Faibussowitsch   PetscCall(VecSetSizes(x, PETSC_DECIDE, n));
599566063dSJacob Faibussowitsch   PetscCall(VecSetFromOptions(x));
609566063dSJacob Faibussowitsch   PetscCall(VecDuplicate(x, &r));
619566063dSJacob Faibussowitsch   PetscCall(VecDuplicate(x, &F));
629566063dSJacob Faibussowitsch   PetscCall(VecDuplicate(x, &U));
63c4762a1bSJed Brown 
64c4762a1bSJed Brown   /*
65c4762a1bSJed Brown      Set function evaluation routine and vector
66c4762a1bSJed Brown   */
679566063dSJacob Faibussowitsch   PetscCall(SNESSetFunction(snes, r, FormFunction, (void *)F));
68c4762a1bSJed Brown 
69c4762a1bSJed Brown   /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
70c4762a1bSJed Brown      Create matrix data structure; set Jacobian evaluation routine
71c4762a1bSJed Brown      - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
72c4762a1bSJed Brown 
739566063dSJacob Faibussowitsch   PetscCall(MatCreate(PETSC_COMM_WORLD, &J));
749566063dSJacob Faibussowitsch   PetscCall(MatSetSizes(J, PETSC_DECIDE, PETSC_DECIDE, n, n));
759566063dSJacob Faibussowitsch   PetscCall(MatSetFromOptions(J));
769566063dSJacob Faibussowitsch   PetscCall(MatSeqAIJSetPreallocation(J, 3, NULL));
779566063dSJacob Faibussowitsch   PetscCall(MatSetVariableBlockSizes(J, 3, lens));
78c4762a1bSJed Brown 
79c4762a1bSJed Brown   /*
80c4762a1bSJed Brown      Set Jacobian matrix data structure and default Jacobian evaluation
81c4762a1bSJed Brown      routine. User can override with:
82c4762a1bSJed Brown      -snes_fd : default finite differencing approximation of Jacobian
83c4762a1bSJed Brown      -snes_mf : matrix-free Newton-Krylov method with no preconditioning
84c4762a1bSJed Brown                 (unless user explicitly sets preconditioner)
85c4762a1bSJed Brown      -snes_mf_operator : form preconditioning matrix as set by the user,
86c4762a1bSJed Brown                          but use matrix-free approx for Jacobian-vector
87c4762a1bSJed Brown                          products within Newton-Krylov method
88c4762a1bSJed Brown   */
89c4762a1bSJed Brown 
909566063dSJacob Faibussowitsch   PetscCall(SNESSetJacobian(snes, J, J, FormJacobian, NULL));
91c4762a1bSJed Brown 
92c4762a1bSJed Brown   /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
93c4762a1bSJed Brown      Customize nonlinear solver; set runtime options
94c4762a1bSJed Brown    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
95c4762a1bSJed Brown 
96c4762a1bSJed Brown   /*
97c4762a1bSJed Brown      Set names for some vectors to facilitate monitoring (optional)
98c4762a1bSJed Brown   */
999566063dSJacob Faibussowitsch   PetscCall(PetscObjectSetName((PetscObject)x, "Approximate Solution"));
1009566063dSJacob Faibussowitsch   PetscCall(PetscObjectSetName((PetscObject)U, "Exact Solution"));
101c4762a1bSJed Brown 
102c4762a1bSJed Brown   /*
103c4762a1bSJed Brown      Set SNES/KSP/KSP/PC runtime options, e.g.,
104c4762a1bSJed Brown          -snes_view -snes_monitor -ksp_type <ksp> -pc_type <pc>
105c4762a1bSJed Brown   */
1069566063dSJacob Faibussowitsch   PetscCall(SNESSetFromOptions(snes));
107c4762a1bSJed Brown 
108c4762a1bSJed Brown   /*
109c4762a1bSJed Brown      Print parameters used for convergence testing (optional) ... just
110c4762a1bSJed Brown      to demonstrate this routine; this information is also printed with
111c4762a1bSJed Brown      the option -snes_view
112c4762a1bSJed Brown   */
1139566063dSJacob Faibussowitsch   PetscCall(SNESGetTolerances(snes, &abstol, &rtol, &stol, &maxit, &maxf));
11463a3b9bcSJacob Faibussowitsch   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));
115c4762a1bSJed Brown 
116c4762a1bSJed Brown   /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
117c4762a1bSJed Brown      Initialize application:
118c4762a1bSJed Brown      Store right-hand-side of PDE and exact solution
119c4762a1bSJed Brown    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
120c4762a1bSJed Brown 
121c4762a1bSJed Brown   xp = 0.0;
122c4762a1bSJed Brown   for (i = 0; i < n; i++) {
123c4762a1bSJed Brown     v = 6.0 * xp + PetscPowScalar(xp + 1.e-12, 6.0); /* +1.e-12 is to prevent 0^6 */
1249566063dSJacob Faibussowitsch     PetscCall(VecSetValues(F, 1, &i, &v, INSERT_VALUES));
125c4762a1bSJed Brown     v = xp * xp * xp;
1269566063dSJacob Faibussowitsch     PetscCall(VecSetValues(U, 1, &i, &v, INSERT_VALUES));
127c4762a1bSJed Brown     xp += h;
128c4762a1bSJed Brown   }
129c4762a1bSJed Brown 
130c4762a1bSJed Brown   /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
131c4762a1bSJed Brown      Evaluate initial guess; then solve nonlinear system
132c4762a1bSJed Brown    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
133c4762a1bSJed Brown   /*
134c4762a1bSJed Brown      Note: The user should initialize the vector, x, with the initial guess
135c4762a1bSJed Brown      for the nonlinear solver prior to calling SNESSolve().  In particular,
136c4762a1bSJed Brown      to employ an initial guess of zero, the user should explicitly set
137c4762a1bSJed Brown      this vector to zero by calling VecSet().
138c4762a1bSJed Brown   */
1399566063dSJacob Faibussowitsch   PetscCall(FormInitialGuess(x));
1409566063dSJacob Faibussowitsch   PetscCall(SNESSolve(snes, NULL, x));
1419566063dSJacob Faibussowitsch   PetscCall(SNESGetIterationNumber(snes, &its));
14263a3b9bcSJacob Faibussowitsch   PetscCall(PetscPrintf(PETSC_COMM_WORLD, "number of SNES iterations = %" PetscInt_FMT "\n\n", its));
143c4762a1bSJed Brown 
144c4762a1bSJed Brown   /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
145c4762a1bSJed Brown      Check solution and clean up
146c4762a1bSJed Brown    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
147c4762a1bSJed Brown 
148c4762a1bSJed Brown   /*
149c4762a1bSJed Brown      Check the error
150c4762a1bSJed Brown   */
1519566063dSJacob Faibussowitsch   PetscCall(VecAXPY(x, none, U));
1529566063dSJacob Faibussowitsch   PetscCall(VecNorm(x, NORM_2, &norm));
15363a3b9bcSJacob Faibussowitsch   PetscCall(PetscPrintf(PETSC_COMM_WORLD, "Norm of error %g, Iterations %" PetscInt_FMT "\n", (double)norm, its));
154c4762a1bSJed Brown 
155c4762a1bSJed Brown   /*
156c4762a1bSJed Brown      Free work space.  All PETSc objects should be destroyed when they
157c4762a1bSJed Brown      are no longer needed.
158c4762a1bSJed Brown   */
1599371c9d4SSatish Balay   PetscCall(VecDestroy(&x));
1609371c9d4SSatish Balay   PetscCall(VecDestroy(&r));
1619371c9d4SSatish Balay   PetscCall(VecDestroy(&U));
1629371c9d4SSatish Balay   PetscCall(VecDestroy(&F));
1639371c9d4SSatish Balay   PetscCall(MatDestroy(&J));
1649371c9d4SSatish Balay   PetscCall(SNESDestroy(&snes));
1659566063dSJacob Faibussowitsch   PetscCall(PetscFinalize());
166b122ec5aSJacob Faibussowitsch   return 0;
167c4762a1bSJed Brown }
168f6dfbefdSBarry Smith 
169c4762a1bSJed Brown /*
170c4762a1bSJed Brown    FormInitialGuess - Computes initial guess.
171c4762a1bSJed Brown 
172c4762a1bSJed Brown    Input/Output Parameter:
173c4762a1bSJed Brown .  x - the solution vector
174c4762a1bSJed Brown */
175*d71ae5a4SJacob Faibussowitsch PetscErrorCode FormInitialGuess(Vec x)
176*d71ae5a4SJacob Faibussowitsch {
177c4762a1bSJed Brown   PetscScalar pfive = .50;
1789566063dSJacob Faibussowitsch   PetscCall(VecSet(x, pfive));
179c4762a1bSJed Brown   return 0;
180c4762a1bSJed Brown }
181f6dfbefdSBarry Smith 
182c4762a1bSJed Brown /*
183c4762a1bSJed Brown    FormFunction - Evaluates nonlinear function, F(x).
184c4762a1bSJed Brown 
185c4762a1bSJed Brown    Input Parameters:
186c4762a1bSJed Brown .  snes - the SNES context
187c4762a1bSJed Brown .  x - input vector
188c4762a1bSJed Brown .  ctx - optional user-defined context, as set by SNESSetFunction()
189c4762a1bSJed Brown 
190c4762a1bSJed Brown    Output Parameter:
191c4762a1bSJed Brown .  f - function vector
192c4762a1bSJed Brown 
193c4762a1bSJed Brown    Note:
194c4762a1bSJed Brown    The user-defined context can contain any application-specific data
195c4762a1bSJed Brown    needed for the function evaluation (such as various parameters, work
196c4762a1bSJed Brown    vectors, and grid information).  In this program the context is just
197c4762a1bSJed Brown    a vector containing the right-hand-side of the discretized PDE.
198c4762a1bSJed Brown  */
199c4762a1bSJed Brown 
200*d71ae5a4SJacob Faibussowitsch PetscErrorCode FormFunction(SNES snes, Vec x, Vec f, void *ctx)
201*d71ae5a4SJacob Faibussowitsch {
202c4762a1bSJed Brown   Vec                g = (Vec)ctx;
203c4762a1bSJed Brown   const PetscScalar *xx, *gg;
204c4762a1bSJed Brown   PetscScalar       *ff, d;
205c4762a1bSJed Brown   PetscInt           i, n;
206c4762a1bSJed Brown 
207c4762a1bSJed Brown   /*
208c4762a1bSJed Brown      Get pointers to vector data.
209c4762a1bSJed Brown        - For default PETSc vectors, VecGetArray() returns a pointer to
210c4762a1bSJed Brown          the data array.  Otherwise, the routine is implementation dependent.
211c4762a1bSJed Brown        - You MUST call VecRestoreArray() when you no longer need access to
212c4762a1bSJed Brown          the array.
213c4762a1bSJed Brown   */
2149566063dSJacob Faibussowitsch   PetscCall(VecGetArrayRead(x, &xx));
2159566063dSJacob Faibussowitsch   PetscCall(VecGetArray(f, &ff));
2169566063dSJacob Faibussowitsch   PetscCall(VecGetArrayRead(g, &gg));
217c4762a1bSJed Brown 
218c4762a1bSJed Brown   /*
219c4762a1bSJed Brown      Compute function
220c4762a1bSJed Brown   */
2219566063dSJacob Faibussowitsch   PetscCall(VecGetSize(x, &n));
2229371c9d4SSatish Balay   d     = (PetscReal)(n - 1);
2239371c9d4SSatish Balay   d     = d * d;
224c4762a1bSJed Brown   ff[0] = xx[0];
225c4762a1bSJed Brown   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];
226c4762a1bSJed Brown   ff[n - 1] = xx[n - 1] - 1.0;
227c4762a1bSJed Brown 
228c4762a1bSJed Brown   /*
229c4762a1bSJed Brown      Restore vectors
230c4762a1bSJed Brown   */
2319566063dSJacob Faibussowitsch   PetscCall(VecRestoreArrayRead(x, &xx));
2329566063dSJacob Faibussowitsch   PetscCall(VecRestoreArray(f, &ff));
2339566063dSJacob Faibussowitsch   PetscCall(VecRestoreArrayRead(g, &gg));
234c4762a1bSJed Brown   return 0;
235c4762a1bSJed Brown }
236f6dfbefdSBarry Smith 
237c4762a1bSJed Brown /*
238c4762a1bSJed Brown    FormJacobian - Evaluates Jacobian matrix.
239c4762a1bSJed Brown 
240c4762a1bSJed Brown    Input Parameters:
241c4762a1bSJed Brown .  snes - the SNES context
242c4762a1bSJed Brown .  x - input vector
243c4762a1bSJed Brown .  dummy - optional user-defined context (not used here)
244c4762a1bSJed Brown 
245c4762a1bSJed Brown    Output Parameters:
246c4762a1bSJed Brown .  jac - Jacobian matrix
247c4762a1bSJed Brown .  B - optionally different preconditioning matrix
248c4762a1bSJed Brown 
249c4762a1bSJed Brown */
250c4762a1bSJed Brown 
251*d71ae5a4SJacob Faibussowitsch PetscErrorCode FormJacobian(SNES snes, Vec x, Mat jac, Mat B, void *dummy)
252*d71ae5a4SJacob Faibussowitsch {
253c4762a1bSJed Brown   const PetscScalar *xx;
254c4762a1bSJed Brown   PetscScalar        A[3], d;
255c4762a1bSJed Brown   PetscInt           i, n, j[3];
256c4762a1bSJed Brown 
257c4762a1bSJed Brown   /*
258c4762a1bSJed Brown      Get pointer to vector data
259c4762a1bSJed Brown   */
2609566063dSJacob Faibussowitsch   PetscCall(VecGetArrayRead(x, &xx));
261c4762a1bSJed Brown 
262c4762a1bSJed Brown   /*
263c4762a1bSJed Brown      Compute Jacobian entries and insert into matrix.
264c4762a1bSJed Brown       - Note that in this case we set all elements for a particular
265c4762a1bSJed Brown         row at once.
266c4762a1bSJed Brown   */
2679566063dSJacob Faibussowitsch   PetscCall(VecGetSize(x, &n));
2689371c9d4SSatish Balay   d = (PetscReal)(n - 1);
2699371c9d4SSatish Balay   d = d * d;
270c4762a1bSJed Brown 
271c4762a1bSJed Brown   /*
272c4762a1bSJed Brown      Interior grid points
273c4762a1bSJed Brown   */
274c4762a1bSJed Brown   for (i = 1; i < n - 1; i++) {
2759371c9d4SSatish Balay     j[0] = i - 1;
2769371c9d4SSatish Balay     j[1] = i;
2779371c9d4SSatish Balay     j[2] = i + 1;
2789371c9d4SSatish Balay     A[0] = A[2] = d;
2799371c9d4SSatish Balay     A[1]        = -2.0 * d + 2.0 * xx[i];
2809566063dSJacob Faibussowitsch     PetscCall(MatSetValues(B, 1, &i, 3, j, A, INSERT_VALUES));
281c4762a1bSJed Brown   }
282c4762a1bSJed Brown 
283c4762a1bSJed Brown   /*
284c4762a1bSJed Brown      Boundary points
285c4762a1bSJed Brown   */
2869371c9d4SSatish Balay   i    = 0;
2879371c9d4SSatish Balay   A[0] = 1.0;
288c4762a1bSJed Brown 
2899566063dSJacob Faibussowitsch   PetscCall(MatSetValues(B, 1, &i, 1, &i, A, INSERT_VALUES));
290c4762a1bSJed Brown 
2919371c9d4SSatish Balay   i    = n - 1;
2929371c9d4SSatish Balay   A[0] = 1.0;
293c4762a1bSJed Brown 
2949566063dSJacob Faibussowitsch   PetscCall(MatSetValues(B, 1, &i, 1, &i, A, INSERT_VALUES));
295c4762a1bSJed Brown 
296c4762a1bSJed Brown   /*
297c4762a1bSJed Brown      Restore vector
298c4762a1bSJed Brown   */
2999566063dSJacob Faibussowitsch   PetscCall(VecRestoreArrayRead(x, &xx));
300c4762a1bSJed Brown 
301c4762a1bSJed Brown   /*
302c4762a1bSJed Brown      Assemble matrix
303c4762a1bSJed Brown   */
3049566063dSJacob Faibussowitsch   PetscCall(MatAssemblyBegin(B, MAT_FINAL_ASSEMBLY));
3059566063dSJacob Faibussowitsch   PetscCall(MatAssemblyEnd(B, MAT_FINAL_ASSEMBLY));
306c4762a1bSJed Brown   if (jac != B) {
3079566063dSJacob Faibussowitsch     PetscCall(MatAssemblyBegin(jac, MAT_FINAL_ASSEMBLY));
3089566063dSJacob Faibussowitsch     PetscCall(MatAssemblyEnd(jac, MAT_FINAL_ASSEMBLY));
309c4762a1bSJed Brown   }
310c4762a1bSJed Brown   return 0;
311c4762a1bSJed Brown }
312c4762a1bSJed Brown 
313c4762a1bSJed Brown /*TEST
314c4762a1bSJed Brown 
315f1be3500SJunchao Zhang    testset:
316c4762a1bSJed Brown      args: -snes_monitor_short -snes_view -ksp_monitor
317f1be3500SJunchao Zhang      output_file: output/ex5_1.out
318f1be3500SJunchao Zhang      filter: grep -v "type: seqaij"
319f1be3500SJunchao Zhang 
320f1be3500SJunchao Zhang      test:
321f1be3500SJunchao Zhang       suffix: 1
322f1be3500SJunchao Zhang 
323f1be3500SJunchao Zhang      test:
324f1be3500SJunchao Zhang       suffix: cuda
325f1be3500SJunchao Zhang       requires: cuda
326f1be3500SJunchao Zhang       args: -mat_type aijcusparse -vec_type cuda
327f1be3500SJunchao Zhang 
328f1be3500SJunchao Zhang      test:
329f1be3500SJunchao Zhang       suffix: kok
330f1be3500SJunchao Zhang       requires: kokkos_kernels
331f1be3500SJunchao Zhang       args: -mat_type aijkokkos -vec_type kokkos
332c4762a1bSJed Brown 
333c4762a1bSJed Brown    # this is just a test for SNESKSPTRASPOSEONLY and KSPSolveTranspose to behave properly
334c4762a1bSJed Brown    # the solution is wrong on purpose
335c4762a1bSJed Brown    test:
336c4762a1bSJed Brown       requires: !single !complex
337c4762a1bSJed Brown       suffix: transpose_only
338c4762a1bSJed Brown       args: -snes_monitor_short -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
339c4762a1bSJed Brown 
340c4762a1bSJed Brown TEST*/
341