Actual source code: ex16opt_ic.c

petsc-3.11.3 2019-06-26
Report Typos and Errors
  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 (B && 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:   VecRestoreArrayRead(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);if (ierr) return ierr;
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);
178:   TSDestroy(&ts);

180:   VecGetArray(user.x,&x_ptr);
181:   user.x_ob[0] = x_ptr[0];
182:   user.x_ob[1] = x_ptr[1];
183:   VecRestoreArray(user.x,&x_ptr);

185:   MatCreateVecs(user.A,&user.lambda[0],NULL);

187:   /* Create TAO solver and set desired solution method */
188:   TaoCreate(PETSC_COMM_WORLD,&tao);
189:   TaoSetType(tao,TAOCG);

191:   /* Set initial solution guess */
192:   MatCreateVecs(user.A,&ic,NULL);
193:   VecGetArray(ic,&x_ptr);
194:   x_ptr[0]  = 2.1;
195:   x_ptr[1]  = 0.7;
196:   VecRestoreArray(ic,&x_ptr);

198:   TaoSetInitialVector(tao,ic);

200:   /* Set routine for function and gradient evaluation */
201:   TaoSetObjectiveAndGradientRoutine(tao,FormFunctionGradient,(void *)&user);

203:   /* Check for any TAO command line options */
204:   TaoSetFromOptions(tao);
205:   TaoGetKSP(tao,&ksp);
206:   if (ksp) {
207:     KSPGetPC(ksp,&pc);
208:     PCSetType(pc,PCNONE);
209:   }

211:   TaoSetTolerances(tao,1e-10,PETSC_DEFAULT,PETSC_DEFAULT);

213:   /* SOLVE THE APPLICATION */
214:   TaoSolve(tao);

216:   /* Free TAO data structures */
217:   TaoDestroy(&tao);

219:   /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
220:      Free work space.  All PETSc objects should be destroyed when they
221:      are no longer needed.
222:    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
223:   MatDestroy(&user.A);
224:   VecDestroy(&user.x);
225:   VecDestroy(&user.lambda[0]);

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       *y_ptr;
250:   const PetscScalar *x_ptr;
251:   PetscErrorCode    ierr;

254:   VecCopy(IC,user->x);

256:   /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
257:      Create timestepping solver context
258:      - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
259:   TSCreate(PETSC_COMM_WORLD,&ts);
260:   TSSetType(ts,TSRK);
261:   TSSetRHSFunction(ts,NULL,RHSFunction,user);
262:   /*   Set RHS Jacobian  for the adjoint integration */
263:   TSSetRHSJacobian(ts,user->A,user->A,RHSJacobian,user);

265:   /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
266:      Set time
267:    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
268:   TSSetTime(ts,0.0);
269:   TSSetTimeStep(ts,.001);
270:   TSSetMaxTime(ts,0.5);
271:   TSSetExactFinalTime(ts,TS_EXACTFINALTIME_MATCHSTEP);

273:   TSSetTolerances(ts,1e-7,NULL,1e-7,NULL);

275:   /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
276:     Save trajectory of solution so that TSAdjointSolve() may be used
277:    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
278:   TSSetSaveTrajectory(ts);

280:   /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
281:      Set runtime options
282:    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
283:   TSSetFromOptions(ts);

285:   TSSolve(ts,user->x);
286:   TSGetSolveTime(ts,&user->ftime);
287:   TSGetStepNumber(ts,&user->steps);
288:   PetscPrintf(PETSC_COMM_WORLD,"mu %.6f, steps %D, ftime %g\n",(double)user->mu,user->steps,(double)user->ftime);

290:   VecGetArrayRead(user->x,&x_ptr);
291:   *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]);
292:   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));

294:   /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
295:      Adjoint model starts here
296:      - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
297:   /*   Redet initial conditions for the adjoint integration */
298:   VecGetArray(user->lambda[0],&y_ptr);
299:   y_ptr[0] = 2.*(x_ptr[0]-user->x_ob[0]);
300:   y_ptr[1] = 2.*(x_ptr[1]-user->x_ob[1]);
301:   VecRestoreArray(user->lambda[0],&y_ptr);
302:   VecRestoreArrayRead(user->x,&x_ptr);
303:   TSSetCostGradients(ts,1,user->lambda,NULL);


306:   TSAdjointSolve(ts);

308:   VecCopy(user->lambda[0],G);

310:   TSDestroy(&ts);
311:   return(0);
312: }

314: /*TEST
315:     build:
316:       requires: !single !complex

318:     test:
319:       suffix: 1
320:       args: -monitor 0 -viewer_binary_skip_info -tao_view -tao_monitor  -tao_gttol 1.e-5 -ts_trajectory_dirname ex16opt_icdir

322:     test:
323:       suffix: 2
324:       args: -ts_rhs_jacobian_test_mult_transpose FALSE -tao_max_it 2 -ts_rhs_jacobian_test_mult FALSE

326: TEST*/