xref: /petsc/src/ts/tutorials/ex24.c (revision 0e02354e4efb6ae7920bb0e7d191735ccbbd1e1e)
1 static char help[] = "Pseudotransient continuation to solve a many-variable system that comes from the 2 variable Rosenbrock function + trivial.\n\n";
2 
3 #include <petscts.h>
4 
5 static PetscErrorCode FormIJacobian(TS,PetscReal,Vec,Vec,PetscReal,Mat,Mat,void*);
6 static PetscErrorCode FormIFunction(TS,PetscReal,Vec,Vec,Vec,void*);
7 static PetscErrorCode MonitorObjective(TS,PetscInt,PetscReal,Vec,void*);
8 
9 typedef struct {
10   PetscInt  n;
11   PetscBool monitor_short;
12 } Ctx;
13 
14 int main(int argc,char **argv)
15 {
16   TS             ts;            /* time integration context */
17   Vec            X;             /* solution, residual vectors */
18   Mat            J;             /* Jacobian matrix */
19   PetscScalar    *x;
20   PetscReal      ftime;
21   PetscInt       i,steps,nits,lits;
22   PetscBool      view_final;
23   Ctx            ctx;
24 
25   PetscCall(PetscInitialize(&argc,&argv,(char*)0,help));
26   ctx.n = 3;
27   PetscCall(PetscOptionsGetInt(NULL,NULL,"-n",&ctx.n,NULL));
28   PetscCheck(ctx.n >= 2,PETSC_COMM_WORLD,PETSC_ERR_ARG_OUTOFRANGE,"The dimension specified with -n must be at least 2");
29 
30   view_final = PETSC_FALSE;
31   PetscCall(PetscOptionsGetBool(NULL,NULL,"-view_final",&view_final,NULL));
32 
33   ctx.monitor_short = PETSC_FALSE;
34   PetscCall(PetscOptionsGetBool(NULL,NULL,"-monitor_short",&ctx.monitor_short,NULL));
35 
36   /*
37      Create Jacobian matrix data structure and state vector
38   */
39   PetscCall(MatCreate(PETSC_COMM_WORLD,&J));
40   PetscCall(MatSetSizes(J,PETSC_DECIDE,PETSC_DECIDE,ctx.n,ctx.n));
41   PetscCall(MatSetFromOptions(J));
42   PetscCall(MatSetUp(J));
43   PetscCall(MatCreateVecs(J,&X,NULL));
44 
45   /* Create time integration context */
46   PetscCall(TSCreate(PETSC_COMM_WORLD,&ts));
47   PetscCall(TSSetType(ts,TSPSEUDO));
48   PetscCall(TSSetIFunction(ts,NULL,FormIFunction,&ctx));
49   PetscCall(TSSetIJacobian(ts,J,J,FormIJacobian,&ctx));
50   PetscCall(TSSetMaxSteps(ts,1000));
51   PetscCall(TSSetExactFinalTime(ts,TS_EXACTFINALTIME_STEPOVER));
52   PetscCall(TSSetTimeStep(ts,1e-3));
53   PetscCall(TSMonitorSet(ts,MonitorObjective,&ctx,NULL));
54 
55   /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
56      Customize time integrator; set runtime options
57    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
58   PetscCall(TSSetFromOptions(ts));
59 
60   /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
61      Evaluate initial guess; then solve nonlinear system
62    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
63   PetscCall(VecSet(X,0.0));
64   PetscCall(VecGetArray(X,&x));
65 #if 1
66   x[0] = 5.;
67   x[1] = -5.;
68   for (i=2; i<ctx.n; i++) x[i] = 5.;
69 #else
70   x[0] = 1.0;
71   x[1] = 15.0;
72   for (i=2; i<ctx.n; i++) x[i] = 10.0;
73 #endif
74   PetscCall(VecRestoreArray(X,&x));
75 
76   PetscCall(TSSolve(ts,X));
77   PetscCall(TSGetSolveTime(ts,&ftime));
78   PetscCall(TSGetStepNumber(ts,&steps));
79   PetscCall(TSGetSNESIterations(ts,&nits));
80   PetscCall(TSGetKSPIterations(ts,&lits));
81   PetscCall(PetscPrintf(PETSC_COMM_WORLD,"Time integrator took (%" PetscInt_FMT ",%" PetscInt_FMT ",%" PetscInt_FMT ") iterations to reach final time %g\n",steps,nits,lits,(double)ftime));
82   if (view_final) PetscCall(VecView(X,PETSC_VIEWER_STDOUT_WORLD));
83 
84   /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
85      Free work space.  All PETSc objects should be destroyed when they
86      are no longer needed.
87    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
88 
89   PetscCall(VecDestroy(&X));
90   PetscCall(MatDestroy(&J));
91   PetscCall(TSDestroy(&ts));
92   PetscCall(PetscFinalize());
93   return 0;
94 }
95 
96 static PetscErrorCode MonitorObjective(TS ts,PetscInt step,PetscReal t,Vec X,void *ictx)
97 {
98   Ctx               *ctx = (Ctx*)ictx;
99   const PetscScalar *x;
100   PetscScalar       f;
101   PetscReal         dt,gnorm;
102   PetscInt          i,snesit,linit;
103   SNES              snes;
104   Vec               Xdot,F;
105 
106   PetscFunctionBeginUser;
107   /* Compute objective functional */
108   PetscCall(VecGetArrayRead(X,&x));
109   f    = 0;
110   for (i=0; i<ctx->n-1; i++) f += PetscSqr(1. - x[i]) + 100. * PetscSqr(x[i+1] - PetscSqr(x[i]));
111   PetscCall(VecRestoreArrayRead(X,&x));
112 
113   /* Compute norm of gradient */
114   PetscCall(VecDuplicate(X,&Xdot));
115   PetscCall(VecDuplicate(X,&F));
116   PetscCall(VecZeroEntries(Xdot));
117   PetscCall(FormIFunction(ts,t,X,Xdot,F,ictx));
118   PetscCall(VecNorm(F,NORM_2,&gnorm));
119   PetscCall(VecDestroy(&Xdot));
120   PetscCall(VecDestroy(&F));
121 
122   PetscCall(TSGetTimeStep(ts,&dt));
123   PetscCall(TSGetSNES(ts,&snes));
124   PetscCall(SNESGetIterationNumber(snes,&snesit));
125   PetscCall(SNESGetLinearSolveIterations(snes,&linit));
126   PetscCall(PetscPrintf(PETSC_COMM_WORLD,(ctx->monitor_short ? "%3" PetscInt_FMT " t=%10.1e  dt=%10.1e  f=%10.1e  df=%10.1e  it=(%2" PetscInt_FMT ",%3" PetscInt_FMT ")\n"
127                                                              : "%3" PetscInt_FMT " t=%10.4e  dt=%10.4e  f=%10.4e  df=%10.4e  it=(%2" PetscInt_FMT ",%3" PetscInt_FMT ")\n"),
128                         step,(double)t,(double)dt,(double)PetscRealPart(f),(double)gnorm,snesit,linit));
129   PetscFunctionReturn(0);
130 }
131 
132 /* ------------------------------------------------------------------- */
133 /*
134    FormIFunction - Evaluates nonlinear function, F(X,Xdot) = Xdot + grad(objective(X))
135 
136    Input Parameters:
137 +  ts   - the TS context
138 .  t - time
139 .  X    - input vector
140 .  Xdot - time derivative
141 -  ctx  - optional user-defined context
142 
143    Output Parameter:
144 .  F - function vector
145  */
146 static PetscErrorCode FormIFunction(TS ts,PetscReal t,Vec X,Vec Xdot,Vec F,void *ictx)
147 {
148   const PetscScalar *x;
149   PetscScalar       *f;
150   PetscInt          i;
151   Ctx               *ctx = (Ctx*)ictx;
152 
153   PetscFunctionBeginUser;
154   /*
155     Get pointers to vector data.
156     - For default PETSc vectors, VecGetArray() returns a pointer to
157     the data array.  Otherwise, the routine is implementation dependent.
158     - You MUST call VecRestoreArray() when you no longer need access to
159     the array.
160   */
161   PetscCall(VecGetArrayRead(X,&x));
162   PetscCall(VecZeroEntries(F));
163   PetscCall(VecGetArray(F,&f));
164 
165   /* Compute gradient of objective */
166   for (i=0; i<ctx->n-1; i++) {
167     PetscScalar a,a0,a1;
168     a       = x[i+1] - PetscSqr(x[i]);
169     a0      = -2.*x[i];
170     a1      = 1.;
171     f[i]   += -2.*(1. - x[i]) + 200.*a*a0;
172     f[i+1] += 200.*a*a1;
173   }
174   /* Restore vectors */
175   PetscCall(VecRestoreArrayRead(X,&x));
176   PetscCall(VecRestoreArray(F,&f));
177   PetscCall(VecAXPY(F,1.0,Xdot));
178   PetscFunctionReturn(0);
179 }
180 /* ------------------------------------------------------------------- */
181 /*
182    FormIJacobian - Evaluates Jacobian matrix.
183 
184    Input Parameters:
185 +  ts - the TS context
186 .  t - pseudo-time
187 .  X - input vector
188 .  Xdot - time derivative
189 .  shift - multiplier for mass matrix
190 .  dummy - user-defined context
191 
192    Output Parameters:
193 .  J - Jacobian matrix
194 .  B - optionally different preconditioning matrix
195 .  flag - flag indicating matrix structure
196 */
197 static PetscErrorCode FormIJacobian(TS ts,PetscReal t,Vec X,Vec Xdot,PetscReal shift,Mat J,Mat B,void *ictx)
198 {
199   const PetscScalar *x;
200   PetscInt          i;
201   Ctx               *ctx = (Ctx*)ictx;
202 
203   PetscFunctionBeginUser;
204   PetscCall(MatZeroEntries(B));
205   /*
206      Get pointer to vector data
207   */
208   PetscCall(VecGetArrayRead(X,&x));
209 
210   /*
211      Compute Jacobian entries and insert into matrix.
212   */
213   for (i=0; i<ctx->n-1; i++) {
214     PetscInt    rowcol[2];
215     PetscScalar v[2][2],a,a0,a1,a00,a01,a10,a11;
216     rowcol[0] = i;
217     rowcol[1] = i+1;
218     a         = x[i+1] - PetscSqr(x[i]);
219     a0        = -2.*x[i];
220     a00       = -2.;
221     a01       = 0.;
222     a1        = 1.;
223     a10       = 0.;
224     a11       = 0.;
225     v[0][0]   = 2. + 200.*(a*a00 + a0*a0);
226     v[0][1]   = 200.*(a*a01 + a1*a0);
227     v[1][0]   = 200.*(a*a10 + a0*a1);
228     v[1][1]   = 200.*(a*a11 + a1*a1);
229     PetscCall(MatSetValues(B,2,rowcol,2,rowcol,&v[0][0],ADD_VALUES));
230   }
231   for (i=0; i<ctx->n; i++) {
232     PetscCall(MatSetValue(B,i,i,(PetscScalar)shift,ADD_VALUES));
233   }
234 
235   PetscCall(VecRestoreArrayRead(X,&x));
236 
237   /*
238      Assemble matrix
239   */
240   PetscCall(MatAssemblyBegin(B,MAT_FINAL_ASSEMBLY));
241   PetscCall(MatAssemblyEnd(B,MAT_FINAL_ASSEMBLY));
242   if (J != B) {
243     PetscCall(MatAssemblyBegin(J,MAT_FINAL_ASSEMBLY));
244     PetscCall(MatAssemblyEnd(J,MAT_FINAL_ASSEMBLY));
245   }
246   PetscFunctionReturn(0);
247 }
248 
249 /*TEST
250 
251     test:
252       requires: !single
253 
254     test:
255       args: -pc_type lu -ts_dt 1e-5 -ts_max_time 1e5 -n 50 -monitor_short -snes_max_it 5 -snes_type newtonls -ts_max_snes_failures -1
256       requires: !single
257       suffix: 2
258 
259 TEST*/
260