Actual source code: ex16opt_ic.c
petsc-3.10.5 2019-03-28
1: static char help[] = "Solves an ODE-constrained optimization problem -- finding the optimal initial conditions for the van der Pol equation.\n\
2: Input parameters include:\n\
3: -mu : stiffness parameter\n\n";
5: /*
6: Concepts: TS^time-dependent nonlinear problems
7: Concepts: TS^van der Pol equation
8: Concepts: Optimization using adjoint sensitivities
9: Processors: 1
10: */
11: /* ------------------------------------------------------------------------
13: Notes:
14: This code demonstrates how to solve an ODE-constrained optimization problem with TAO, TSAdjoint and TS.
15: The objective is to minimize the difference between observation and model prediction by finding optimal values for initial conditions.
16: The gradient is computed with the discrete adjoint of an explicit Runge-Kutta method, see ex16adj.c for details.
17: ------------------------------------------------------------------------- */
18: #include <petsctao.h>
19: #include <petscts.h>
20: #include <petscmat.h>
21: typedef struct _n_User *User;
22: struct _n_User {
23: PetscReal mu;
24: PetscReal next_output;
26: PetscInt steps;
27: PetscReal ftime,x_ob[2];
28: Mat A; /* Jacobian matrix */
29: Vec x,lambda[2]; /* adjoint variables */
30: };
32: PetscErrorCode FormFunctionGradient(Tao,Vec,PetscReal*,Vec,void*);
34: /*
35: * User-defined routines
36: */
37: static PetscErrorCode RHSFunction(TS ts,PetscReal t,Vec X,Vec F,void *ctx)
38: {
39: PetscErrorCode ierr;
40: User user = (User)ctx;
41: PetscScalar *f;
42: const PetscScalar *x;
45: VecGetArrayRead(X,&x);
46: VecGetArray(F,&f);
47: f[0] = x[1];
48: f[1] = user->mu*(1.-x[0]*x[0])*x[1]-x[0];
49: VecRestoreArrayRead(X,&x);
50: VecRestoreArray(F,&f);
51: return(0);
52: }
54: static PetscErrorCode RHSJacobian(TS ts,PetscReal t,Vec X,Mat A,Mat B,void *ctx)
55: {
56: PetscErrorCode ierr;
57: User user = (User)ctx;
58: PetscReal mu = user->mu;
59: PetscInt rowcol[] = {0,1};
60: PetscScalar J[2][2];
61: const PetscScalar *x;
64: VecGetArrayRead(X,&x);
65: J[0][0] = 0;
66: J[1][0] = -2.*mu*x[1]*x[0]-1;
67: J[0][1] = 1.0;
68: J[1][1] = mu*(1.0-x[0]*x[0]);
69: MatSetValues(A,2,rowcol,2,rowcol,&J[0][0],INSERT_VALUES);
70: MatAssemblyBegin(A,MAT_FINAL_ASSEMBLY);
71: MatAssemblyEnd(A,MAT_FINAL_ASSEMBLY);
72: if (A != B) {
73: MatAssemblyBegin(B,MAT_FINAL_ASSEMBLY);
74: MatAssemblyEnd(B,MAT_FINAL_ASSEMBLY);
75: }
76: VecRestoreArrayRead(X,&x);
77: return(0);
78: }
80: /* Monitor timesteps and use interpolation to output at integer multiples of 0.1 */
81: static PetscErrorCode Monitor(TS ts,PetscInt step,PetscReal t,Vec X,void *ctx)
82: {
83: PetscErrorCode ierr;
84: const PetscScalar *x;
85: PetscReal tfinal, dt, tprev;
86: User user = (User)ctx;
89: TSGetTimeStep(ts,&dt);
90: TSGetMaxTime(ts,&tfinal);
91: TSGetPrevTime(ts,&tprev);
92: VecGetArrayRead(X,&x);
93: 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]));
94: PetscPrintf(PETSC_COMM_WORLD,"t %.6f (tprev = %.6f) \n",(double)t,(double)tprev);
95: VecGetArrayRead(X,&x);
96: return(0);
97: }
99: int main(int argc,char **argv)
100: {
101: TS ts; /* nonlinear solver */
102: Vec ic;
103: PetscBool monitor = PETSC_FALSE;
104: PetscScalar *x_ptr;
105: PetscMPIInt size;
106: struct _n_User user;
107: PetscErrorCode ierr;
108: Tao tao;
109: KSP ksp;
110: PC pc;
112: /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
113: Initialize program
114: - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
115: PetscInitialize(&argc,&argv,NULL,help);
116: MPI_Comm_size(PETSC_COMM_WORLD,&size);
117: if (size != 1) SETERRQ(PETSC_COMM_SELF,1,"This is a uniprocessor example only!");
119: /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
120: Set runtime options
121: - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
122: user.mu = 1.0;
123: user.next_output = 0.0;
124: user.steps = 0;
125: user.ftime = 0.5;
127: PetscOptionsGetReal(NULL,NULL,"-mu",&user.mu,NULL);
128: PetscOptionsGetBool(NULL,NULL,"-monitor",&monitor,NULL);
130: /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
131: Create necessary matrix and vectors, solve same ODE on every process
132: - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
133: MatCreate(PETSC_COMM_WORLD,&user.A);
134: MatSetSizes(user.A,PETSC_DECIDE,PETSC_DECIDE,2,2);
135: MatSetFromOptions(user.A);
136: MatSetUp(user.A);
137: MatCreateVecs(user.A,&user.x,NULL);
139: /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
140: Create timestepping solver context
141: - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
142: TSCreate(PETSC_COMM_WORLD,&ts);
143: TSSetType(ts,TSRK);
144: TSSetRHSFunction(ts,NULL,RHSFunction,&user);
145: TSSetRHSJacobian(ts,user.A,user.A,RHSJacobian,&user);
146: TSSetMaxTime(ts,user.ftime);
147: TSSetExactFinalTime(ts,TS_EXACTFINALTIME_MATCHSTEP);
148: if (monitor) {
149: TSMonitorSet(ts,Monitor,&user,NULL);
150: }
152: /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
153: Set initial conditions
154: - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
155: VecGetArray(user.x,&x_ptr);
156: x_ptr[0] = 2.0; x_ptr[1] = 0.66666654321;
157: VecRestoreArray(user.x,&x_ptr);
158: TSSetTime(ts,0.0);
159: PetscPrintf(PETSC_COMM_WORLD,"mu %g, steps %D, ftime %g\n",(double)user.mu,user.steps,(double)(user.ftime));
161: /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
162: Save trajectory of solution so that TSAdjointSolve() may be used
163: - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
164: TSSetSaveTrajectory(ts);
166: /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
167: Set runtime options
168: - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
169: TSSetFromOptions(ts);
171: /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
172: Solve nonlinear system
173: - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
174: TSSolve(ts,user.x);
175: TSGetSolveTime(ts,&(user.ftime));
176: TSGetStepNumber(ts,&user.steps);
177: PetscPrintf(PETSC_COMM_WORLD,"mu %g, steps %D, ftime %g\n",(double)user.mu,user.steps,(double)user.ftime);
179: VecGetArray(user.x,&x_ptr);
180: user.x_ob[0] = x_ptr[0];
181: user.x_ob[1] = x_ptr[1];
182: VecRestoreArray(user.x,&x_ptr);
184: MatCreateVecs(user.A,&user.lambda[0],NULL);
186: /* Create TAO solver and set desired solution method */
187: TaoCreate(PETSC_COMM_WORLD,&tao);
188: TaoSetType(tao,TAOCG);
190: /* Set initial solution guess */
191: MatCreateVecs(user.A,&ic,NULL);
192: VecGetArray(ic,&x_ptr);
193: x_ptr[0] = 2.1;
194: x_ptr[1] = 0.7;
195: VecRestoreArray(ic,&x_ptr);
197: TaoSetInitialVector(tao,ic);
199: /* Set routine for function and gradient evaluation */
200: TaoSetObjectiveAndGradientRoutine(tao,FormFunctionGradient,(void *)&user);
202: /* Check for any TAO command line options */
203: TaoSetFromOptions(tao);
204: TaoGetKSP(tao,&ksp);
205: if (ksp) {
206: KSPGetPC(ksp,&pc);
207: PCSetType(pc,PCNONE);
208: }
210: TaoSetTolerances(tao,1e-10,PETSC_DEFAULT,PETSC_DEFAULT);
212: /* SOLVE THE APPLICATION */
213: TaoSolve(tao);
215: /* Free TAO data structures */
216: TaoDestroy(&tao);
218: /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
219: Free work space. All PETSc objects should be destroyed when they
220: are no longer needed.
221: - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
222: MatDestroy(&user.A);
223: VecDestroy(&user.x);
224: VecDestroy(&user.lambda[0]);
225: TSDestroy(&ts);
227: VecDestroy(&ic);
228: PetscFinalize();
229: return ierr;
230: }
232: /* ------------------------------------------------------------------ */
233: /*
234: FormFunctionGradient - Evaluates the function and corresponding gradient.
236: Input Parameters:
237: tao - the Tao context
238: X - the input vector
239: ptr - optional user-defined context, as set by TaoSetObjectiveAndGradientRoutine()
241: Output Parameters:
242: f - the newly evaluated function
243: G - the newly evaluated gradient
244: */
245: PetscErrorCode FormFunctionGradient(Tao tao,Vec IC,PetscReal *f,Vec G,void *ctx)
246: {
247: User user = (User)ctx;
248: TS ts;
249: PetscScalar *x_ptr,*y_ptr;
250: PetscErrorCode ierr;
253: VecCopy(IC,user->x);
255: /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
256: Create timestepping solver context
257: - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
258: TSCreate(PETSC_COMM_WORLD,&ts);
259: TSSetType(ts,TSRK);
260: TSSetRHSFunction(ts,NULL,RHSFunction,user);
261: /* Set RHS Jacobian for the adjoint integration */
262: TSSetRHSJacobian(ts,user->A,user->A,RHSJacobian,user);
264: /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
265: Set time
266: - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
267: TSSetTime(ts,0.0);
268: TSSetTimeStep(ts,.001);
269: TSSetMaxTime(ts,0.5);
270: TSSetExactFinalTime(ts,TS_EXACTFINALTIME_MATCHSTEP);
272: TSSetTolerances(ts,1e-7,NULL,1e-7,NULL);
274: /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
275: Save trajectory of solution so that TSAdjointSolve() may be used
276: - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
277: TSSetSaveTrajectory(ts);
279: /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
280: Set runtime options
281: - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
282: TSSetFromOptions(ts);
284: TSSolve(ts,user->x);
285: TSGetSolveTime(ts,&user->ftime);
286: TSGetStepNumber(ts,&user->steps);
287: PetscPrintf(PETSC_COMM_WORLD,"mu %.6f, steps %D, ftime %g\n",(double)user->mu,user->steps,(double)user->ftime);
289: VecGetArray(user->x,&x_ptr);
290: *f = (x_ptr[0]-user->x_ob[0])*(x_ptr[0]-user->x_ob[0])+(x_ptr[1]-user->x_ob[1])*(x_ptr[1]-user->x_ob[1]);
291: PetscPrintf(PETSC_COMM_WORLD,"Observed value y_ob=[%f; %f], ODE solution y=[%f;%f], Cost function f=%f\n",(double)user->x_ob[0],(double)user->x_ob[1],(double)x_ptr[0],(double)x_ptr[1],(double)(*f));
293: /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
294: Adjoint model starts here
295: - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
296: /* Redet initial conditions for the adjoint integration */
297: VecGetArray(user->lambda[0],&y_ptr);
298: y_ptr[0] = 2.*(x_ptr[0]-user->x_ob[0]);
299: y_ptr[1] = 2.*(x_ptr[1]-user->x_ob[1]);
300: VecRestoreArray(user->lambda[0],&y_ptr);
301: VecRestoreArray(user->x,&x_ptr);
302: TSSetCostGradients(ts,1,user->lambda,NULL);
305: TSAdjointSolve(ts);
307: VecCopy(user->lambda[0],G);
309: TSDestroy(&ts);
310: return(0);
311: }
313: /*TEST
314: build:
315: requires: !single !complex
317: test:
318: suffix: 1
319: args: -monitor 0 -viewer_binary_skip_info -tao_view -tao_monitor -tao_gttol 1.e-5 -ts_trajectory_dirname ex16opt_icdir
321: test:
322: suffix: 2
323: args: -ts_rhs_jacobian_test_mult_transpose -mat_shell_test_mult_transpose_view -tao_max_it 2 -ts_rhs_jacobian_test_mult -mat_shell_test_mult_view
325: TEST*/