xref: /petsc/src/ts/tutorials/autodiff/ex16adj.cxx (revision c3b5f7ba6bc5ce25a01a67bb37ba5d34b02bbbd7)
1 static char help[] = "Demonstrates automatic Jacobian generation using ADOL-C for an adjoint sensitivity analysis of the van der Pol equation.\n\
2 Input parameters include:\n\
3       -mu : stiffness parameter\n\n";
4 
5 /*
6    REQUIRES configuration of PETSc with option --download-adolc.
7 
8    For documentation on ADOL-C, see
9      $PETSC_ARCH/externalpackages/ADOL-C-2.6.0/ADOL-C/doc/adolc-manual.pdf
10 */
11 /* ------------------------------------------------------------------------
12    See ex16adj for a description of the problem being solved.
13   ------------------------------------------------------------------------- */
14 
15 #include <petscts.h>
16 #include <petscmat.h>
17 #include "adolc-utils/drivers.cxx"
18 #include <adolc/adolc.h>
19 
20 typedef struct _n_User *User;
21 struct _n_User {
22   PetscReal mu;
23   PetscReal next_output;
24   PetscReal tprev;
25 
26   /* Automatic differentiation support */
27   AdolcCtx  *adctx;
28 };
29 
30 /*
31   'Passive' RHS function, used in residual evaluations during the time integration.
32 */
33 static PetscErrorCode RHSFunctionPassive(TS ts,PetscReal t,Vec X,Vec F,void *ctx)
34 {
35   User              user = (User)ctx;
36   PetscScalar       *f;
37   const PetscScalar *x;
38 
39   PetscFunctionBeginUser;
40   PetscCall(VecGetArrayRead(X,&x));
41   PetscCall(VecGetArray(F,&f));
42   f[0] = x[1];
43   f[1] = user->mu*(1.-x[0]*x[0])*x[1]-x[0];
44   PetscCall(VecRestoreArrayRead(X,&x));
45   PetscCall(VecRestoreArray(F,&f));
46   PetscFunctionReturn(0);
47 }
48 
49 /*
50   Trace RHS to mark on tape 1 the dependence of f upon x. This tape is used in generating the
51   Jacobian transform.
52 */
53 static PetscErrorCode RHSFunctionActive(TS ts,PetscReal t,Vec X,Vec F,void *ctx)
54 {
55   User              user = (User)ctx;
56   PetscScalar       *f;
57   const PetscScalar *x;
58 
59   adouble           f_a[2]; /* 'active' double for dependent variables */
60   adouble           x_a[2]; /* 'active' double for independent variables */
61 
62   PetscFunctionBeginUser;
63   PetscCall(VecGetArrayRead(X,&x));
64   PetscCall(VecGetArray(F,&f));
65 
66   /* Start of active section */
67   trace_on(1);
68   x_a[0] <<= x[0];x_a[1] <<= x[1]; /* Mark independence */
69   f_a[0] = x_a[1];
70   f_a[1] = user->mu*(1.-x_a[0]*x_a[0])*x_a[1]-x_a[0];
71   f_a[0] >>= f[0];f_a[1] >>= f[1]; /* Mark dependence */
72   trace_off();
73   /* End of active section */
74 
75   PetscCall(VecRestoreArrayRead(X,&x));
76   PetscCall(VecRestoreArray(F,&f));
77   PetscFunctionReturn(0);
78 }
79 
80 /*
81   Trace RHS again to mark on tape 2 the dependence of f upon the parameter mu. This tape is used in
82   generating JacobianP.
83 */
84 static PetscErrorCode RHSFunctionActiveP(TS ts,PetscReal t,Vec X,Vec F,void *ctx)
85 {
86   User              user = (User)ctx;
87   PetscScalar       *f;
88   const PetscScalar *x;
89 
90   adouble           f_a[2];      /* 'active' double for dependent variables */
91   adouble           x_a[2],mu_a; /* 'active' double for independent variables */
92 
93   PetscFunctionBeginUser;
94   PetscCall(VecGetArrayRead(X,&x));
95   PetscCall(VecGetArray(F,&f));
96 
97   /* Start of active section */
98   trace_on(3);
99   x_a[0] <<= x[0];x_a[1] <<= x[1];mu_a <<= user->mu; /* Mark independence */
100   f_a[0] = x_a[1];
101   f_a[1] = mu_a*(1.-x_a[0]*x_a[0])*x_a[1]-x_a[0];
102   f_a[0] >>= f[0];f_a[1] >>= f[1];                   /* Mark dependence */
103   trace_off();
104   /* End of active section */
105 
106   PetscCall(VecRestoreArrayRead(X,&x));
107   PetscCall(VecRestoreArray(F,&f));
108   PetscFunctionReturn(0);
109 }
110 
111 /*
112   Compute the Jacobian w.r.t. x using PETSc-ADOL-C driver for explicit TS.
113 */
114 static PetscErrorCode RHSJacobian(TS ts,PetscReal t,Vec X,Mat A,Mat B,void *ctx)
115 {
116   User              user = (User)ctx;
117   const PetscScalar *x;
118 
119   PetscFunctionBeginUser;
120   PetscCall(VecGetArrayRead(X,&x));
121   PetscCall(PetscAdolcComputeRHSJacobian(1,A,x,user->adctx));
122   PetscCall(VecRestoreArrayRead(X,&x));
123   PetscFunctionReturn(0);
124 }
125 
126 /*
127   Compute the Jacobian w.r.t. mu using PETSc-ADOL-C driver for explicit TS.
128 */
129 static PetscErrorCode RHSJacobianP(TS ts,PetscReal t,Vec X,Mat A,void *ctx)
130 {
131   User              user = (User)ctx;
132   const PetscScalar *x;
133 
134   PetscFunctionBeginUser;
135   PetscCall(VecGetArrayRead(X,&x));
136   PetscCall(PetscAdolcComputeRHSJacobianP(3,A,x,&user->mu,user->adctx));
137   PetscCall(VecRestoreArrayRead(X,&x));
138   PetscFunctionReturn(0);
139 }
140 
141 /*
142   Monitor timesteps and use interpolation to output at integer multiples of 0.1
143 */
144 static PetscErrorCode Monitor(TS ts,PetscInt step,PetscReal t,Vec X,void *ctx)
145 {
146   const PetscScalar *x;
147   PetscReal         tfinal, dt, tprev;
148   User              user = (User)ctx;
149 
150   PetscFunctionBeginUser;
151   PetscCall(TSGetTimeStep(ts,&dt));
152   PetscCall(TSGetMaxTime(ts,&tfinal));
153   PetscCall(TSGetPrevTime(ts,&tprev));
154   PetscCall(VecGetArrayRead(X,&x));
155   PetscCall(PetscPrintf(PETSC_COMM_WORLD,"[%.1f] %D TS %.6f (dt = %.6f) X % 12.6e % 12.6e\n",(double)user->next_output,step,(double)t,(double)dt,(double)PetscRealPart(x[0]),(double)PetscRealPart(x[1])));
156   PetscCall(PetscPrintf(PETSC_COMM_WORLD,"t %.6f (tprev = %.6f) \n",(double)t,(double)tprev));
157   PetscCall(VecRestoreArrayRead(X,&x));
158   PetscFunctionReturn(0);
159 }
160 
161 int main(int argc,char **argv)
162 {
163   TS             ts;            /* nonlinear solver */
164   Vec            x;             /* solution, residual vectors */
165   Mat            A;             /* Jacobian matrix */
166   Mat            Jacp;          /* JacobianP matrix */
167   PetscInt       steps;
168   PetscReal      ftime   = 0.5;
169   PetscBool      monitor = PETSC_FALSE;
170   PetscScalar    *x_ptr;
171   PetscMPIInt    size;
172   struct _n_User user;
173   AdolcCtx       *adctx;
174   Vec            lambda[2],mu[2],r;
175 
176   /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
177      Initialize program
178      - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
179   PetscCall(PetscInitialize(&argc,&argv,NULL,help));
180   PetscCallMPI(MPI_Comm_size(PETSC_COMM_WORLD,&size));
181   PetscCheckFalse(size != 1,PETSC_COMM_WORLD,PETSC_ERR_WRONG_MPI_SIZE,"This is a uniprocessor example only!");
182 
183   /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
184     Set runtime options and create AdolcCtx
185     - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
186   PetscCall(PetscNew(&adctx));
187   user.mu          = 1;
188   user.next_output = 0.0;
189   adctx->m = 2;adctx->n = 2;adctx->p = 2;adctx->num_params = 1;
190   user.adctx = adctx;
191 
192   PetscCall(PetscOptionsGetReal(NULL,NULL,"-mu",&user.mu,NULL));
193   PetscCall(PetscOptionsGetBool(NULL,NULL,"-monitor",&monitor,NULL));
194 
195   /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
196     Create necessary matrix and vectors, solve same ODE on every process
197     - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
198   PetscCall(MatCreate(PETSC_COMM_WORLD,&A));
199   PetscCall(MatSetSizes(A,PETSC_DECIDE,PETSC_DECIDE,2,2));
200   PetscCall(MatSetFromOptions(A));
201   PetscCall(MatSetUp(A));
202   PetscCall(MatCreateVecs(A,&x,NULL));
203 
204   PetscCall(MatCreate(PETSC_COMM_WORLD,&Jacp));
205   PetscCall(MatSetSizes(Jacp,PETSC_DECIDE,PETSC_DECIDE,2,1));
206   PetscCall(MatSetFromOptions(Jacp));
207   PetscCall(MatSetUp(Jacp));
208 
209   /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
210      Create timestepping solver context
211      - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
212   PetscCall(TSCreate(PETSC_COMM_WORLD,&ts));
213   PetscCall(TSSetType(ts,TSRK));
214   PetscCall(TSSetRHSFunction(ts,NULL,RHSFunctionPassive,&user));
215 
216   /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
217      Set initial conditions
218    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
219   PetscCall(VecGetArray(x,&x_ptr));
220   x_ptr[0] = 2;   x_ptr[1] = 0.66666654321;
221   PetscCall(VecRestoreArray(x,&x_ptr));
222 
223   /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
224      Trace just once on each tape and put zeros on Jacobian diagonal
225      - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
226   PetscCall(VecDuplicate(x,&r));
227   PetscCall(RHSFunctionActive(ts,0.,x,r,&user));
228   PetscCall(RHSFunctionActiveP(ts,0.,x,r,&user));
229   PetscCall(VecSet(r,0));
230   PetscCall(MatDiagonalSet(A,r,INSERT_VALUES));
231   PetscCall(VecDestroy(&r));
232 
233   /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
234      Set RHS Jacobian for the adjoint integration
235      - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
236   PetscCall(TSSetRHSJacobian(ts,A,A,RHSJacobian,&user));
237   PetscCall(TSSetMaxTime(ts,ftime));
238   PetscCall(TSSetExactFinalTime(ts,TS_EXACTFINALTIME_MATCHSTEP));
239   if (monitor) {
240     PetscCall(TSMonitorSet(ts,Monitor,&user,NULL));
241   }
242   PetscCall(TSSetTimeStep(ts,.001));
243 
244   /*
245     Have the TS save its trajectory so that TSAdjointSolve() may be used
246   */
247   PetscCall(TSSetSaveTrajectory(ts));
248 
249   /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
250      Set runtime options
251    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
252   PetscCall(TSSetFromOptions(ts));
253 
254   /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
255      Solve nonlinear system
256      - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
257   PetscCall(TSSolve(ts,x));
258   PetscCall(TSGetSolveTime(ts,&ftime));
259   PetscCall(TSGetStepNumber(ts,&steps));
260   PetscCall(PetscPrintf(PETSC_COMM_WORLD,"mu %g, steps %D, ftime %g\n",(double)user.mu,steps,(double)ftime));
261   PetscCall(VecView(x,PETSC_VIEWER_STDOUT_WORLD));
262 
263   /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
264      Start the Adjoint model
265      - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
266   PetscCall(MatCreateVecs(A,&lambda[0],NULL));
267   PetscCall(MatCreateVecs(A,&lambda[1],NULL));
268   /*   Reset initial conditions for the adjoint integration */
269   PetscCall(VecGetArray(lambda[0],&x_ptr));
270   x_ptr[0] = 1.0;   x_ptr[1] = 0.0;
271   PetscCall(VecRestoreArray(lambda[0],&x_ptr));
272   PetscCall(VecGetArray(lambda[1],&x_ptr));
273   x_ptr[0] = 0.0;   x_ptr[1] = 1.0;
274   PetscCall(VecRestoreArray(lambda[1],&x_ptr));
275 
276   PetscCall(MatCreateVecs(Jacp,&mu[0],NULL));
277   PetscCall(MatCreateVecs(Jacp,&mu[1],NULL));
278   PetscCall(VecGetArray(mu[0],&x_ptr));
279   x_ptr[0] = 0.0;
280   PetscCall(VecRestoreArray(mu[0],&x_ptr));
281   PetscCall(VecGetArray(mu[1],&x_ptr));
282   x_ptr[0] = 0.0;
283   PetscCall(VecRestoreArray(mu[1],&x_ptr));
284   PetscCall(TSSetCostGradients(ts,2,lambda,mu));
285 
286   /*   Set RHS JacobianP */
287   PetscCall(TSSetRHSJacobianP(ts,Jacp,RHSJacobianP,&user));
288 
289   PetscCall(TSAdjointSolve(ts));
290 
291   PetscCall(VecView(lambda[0],PETSC_VIEWER_STDOUT_WORLD));
292   PetscCall(VecView(lambda[1],PETSC_VIEWER_STDOUT_WORLD));
293   PetscCall(VecView(mu[0],PETSC_VIEWER_STDOUT_WORLD));
294   PetscCall(VecView(mu[1],PETSC_VIEWER_STDOUT_WORLD));
295 
296   /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
297      Free work space.  All PETSc objects should be destroyed when they
298      are no longer needed.
299    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
300   PetscCall(MatDestroy(&A));
301   PetscCall(MatDestroy(&Jacp));
302   PetscCall(VecDestroy(&x));
303   PetscCall(VecDestroy(&lambda[0]));
304   PetscCall(VecDestroy(&lambda[1]));
305   PetscCall(VecDestroy(&mu[0]));
306   PetscCall(VecDestroy(&mu[1]));
307   PetscCall(TSDestroy(&ts));
308   PetscCall(PetscFree(adctx));
309   PetscCall(PetscFinalize());
310   return 0;
311 }
312 
313 /*TEST
314 
315   build:
316     requires: double !complex adolc
317 
318   test:
319     suffix: 1
320     args: -ts_max_steps 10 -ts_monitor -ts_adjoint_monitor
321     output_file: output/ex16adj_1.out
322 
323   test:
324     suffix: 2
325     args: -ts_max_steps 10 -ts_monitor -ts_adjoint_monitor -mu 5
326     output_file: output/ex16adj_2.out
327 
328   test:
329     suffix: 3
330     args: -ts_max_steps 10 -monitor
331     output_file: output/ex16adj_3.out
332 
333   test:
334     suffix: 4
335     args: -ts_max_steps 10 -monitor -mu 5
336     output_file: output/ex16adj_4.out
337 
338 TEST*/
339