Actual source code: ex9opt.c


  2: static char help[] = "Basic equation for generator stability analysis.\n";

  4: /*F

  6: \begin{eqnarray}
  7:                  \frac{d \theta}{dt} = \omega_b (\omega - \omega_s)
  8:                  \frac{2 H}{\omega_s}\frac{d \omega}{dt} & = & P_m - P_max \sin(\theta) -D(\omega - \omega_s)\\
  9: \end{eqnarray}

 11:   Ensemble of initial conditions
 12:    ./ex2 -ensemble -ts_monitor_draw_solution_phase -1,-3,3,3      -ts_adapt_dt_max .01  -ts_monitor -ts_type rosw -pc_type lu -ksp_type preonly

 14:   Fault at .1 seconds
 15:    ./ex2           -ts_monitor_draw_solution_phase .42,.95,.6,1.05 -ts_adapt_dt_max .01  -ts_monitor -ts_type rosw -pc_type lu -ksp_type preonly

 17:   Initial conditions same as when fault is ended
 18:    ./ex2 -u 0.496792,1.00932 -ts_monitor_draw_solution_phase .42,.95,.6,1.05  -ts_adapt_dt_max .01  -ts_monitor -ts_type rosw -pc_type lu -ksp_type preonly

 20: F*/

 22: /*
 23:    Include "petscts.h" so that we can use TS solvers.  Note that this
 24:    file automatically includes:
 25:      petscsys.h       - base PETSc routines   petscvec.h - vectors
 26:      petscmat.h - matrices
 27:      petscis.h     - index sets            petscksp.h - Krylov subspace methods
 28:      petscviewer.h - viewers               petscpc.h  - preconditioners
 29:      petscksp.h   - linear solvers
 30: */

 32: #include <petsctao.h>
 33: #include <petscts.h>

 35: typedef struct {
 36:   TS          ts;
 37:   PetscScalar H, D, omega_b, omega_s, Pmax, Pm, E, V, X, u_s, c;
 38:   PetscInt    beta;
 39:   PetscReal   tf, tcl, dt;
 40: } AppCtx;

 42: PetscErrorCode FormFunction(Tao, Vec, PetscReal *, void *);
 43: PetscErrorCode FormGradient(Tao, Vec, Vec, void *);

 45: /*
 46:      Defines the ODE passed to the ODE solver
 47: */
 48: static PetscErrorCode RHSFunction(TS ts, PetscReal t, Vec U, Vec F, AppCtx *ctx)
 49: {
 50:   PetscScalar       *f, Pmax;
 51:   const PetscScalar *u;

 53:   /*  The next three lines allow us to access the entries of the vectors directly */
 54:   VecGetArrayRead(U, &u);
 55:   VecGetArray(F, &f);
 56:   if ((t > ctx->tf) && (t < ctx->tcl)) Pmax = 0.0; /* A short-circuit on the generator terminal that drives the electrical power output (Pmax*sin(delta)) to 0 */
 57:   else Pmax = ctx->Pmax;

 59:   f[0] = ctx->omega_b * (u[1] - ctx->omega_s);
 60:   f[1] = (-Pmax * PetscSinScalar(u[0]) - ctx->D * (u[1] - ctx->omega_s) + ctx->Pm) * ctx->omega_s / (2.0 * ctx->H);

 62:   VecRestoreArrayRead(U, &u);
 63:   VecRestoreArray(F, &f);
 64:   return 0;
 65: }

 67: /*
 68:      Defines the Jacobian of the ODE passed to the ODE solver. See TSSetIJacobian() for the meaning of a and the Jacobian.
 69: */
 70: static PetscErrorCode RHSJacobian(TS ts, PetscReal t, Vec U, Mat A, Mat B, AppCtx *ctx)
 71: {
 72:   PetscInt           rowcol[] = {0, 1};
 73:   PetscScalar        J[2][2], Pmax;
 74:   const PetscScalar *u;

 76:   VecGetArrayRead(U, &u);
 77:   if ((t > ctx->tf) && (t < ctx->tcl)) Pmax = 0.0; /* A short-circuit on the generator terminal that drives the electrical power output (Pmax*sin(delta)) to 0 */
 78:   else Pmax = ctx->Pmax;

 80:   J[0][0] = 0;
 81:   J[0][1] = ctx->omega_b;
 82:   J[1][1] = -ctx->D * ctx->omega_s / (2.0 * ctx->H);
 83:   J[1][0] = -Pmax * PetscCosScalar(u[0]) * ctx->omega_s / (2.0 * ctx->H);

 85:   MatSetValues(A, 2, rowcol, 2, rowcol, &J[0][0], INSERT_VALUES);
 86:   VecRestoreArrayRead(U, &u);

 88:   MatAssemblyBegin(A, MAT_FINAL_ASSEMBLY);
 89:   MatAssemblyEnd(A, MAT_FINAL_ASSEMBLY);
 90:   if (A != B) {
 91:     MatAssemblyBegin(B, MAT_FINAL_ASSEMBLY);
 92:     MatAssemblyEnd(B, MAT_FINAL_ASSEMBLY);
 93:   }
 94:   return 0;
 95: }

 97: static PetscErrorCode RHSJacobianP(TS ts, PetscReal t, Vec X, Mat A, void *ctx0)
 98: {
 99:   PetscInt    row[] = {0, 1}, col[] = {0};
100:   PetscScalar J[2][1];
101:   AppCtx     *ctx = (AppCtx *)ctx0;

104:   J[0][0] = 0;
105:   J[1][0] = ctx->omega_s / (2.0 * ctx->H);
106:   MatSetValues(A, 2, row, 1, col, &J[0][0], INSERT_VALUES);
107:   MatAssemblyBegin(A, MAT_FINAL_ASSEMBLY);
108:   MatAssemblyEnd(A, MAT_FINAL_ASSEMBLY);
109:   return 0;
110: }

112: static PetscErrorCode CostIntegrand(TS ts, PetscReal t, Vec U, Vec R, AppCtx *ctx)
113: {
114:   PetscScalar       *r;
115:   const PetscScalar *u;

117:   VecGetArrayRead(U, &u);
118:   VecGetArray(R, &r);
119:   r[0] = ctx->c * PetscPowScalarInt(PetscMax(0., u[0] - ctx->u_s), ctx->beta);
120:   VecRestoreArray(R, &r);
121:   VecRestoreArrayRead(U, &u);
122:   return 0;
123: }

125: static PetscErrorCode DRDUJacobianTranspose(TS ts, PetscReal t, Vec U, Mat DRDU, Mat B, AppCtx *ctx)
126: {
127:   PetscScalar        ru[1];
128:   const PetscScalar *u;
129:   PetscInt           row[] = {0}, col[] = {0};

131:   VecGetArrayRead(U, &u);
132:   ru[0] = ctx->c * ctx->beta * PetscPowScalarInt(PetscMax(0., u[0] - ctx->u_s), ctx->beta - 1);
133:   VecRestoreArrayRead(U, &u);
134:   MatSetValues(DRDU, 1, row, 1, col, ru, INSERT_VALUES);
135:   MatAssemblyBegin(DRDU, MAT_FINAL_ASSEMBLY);
136:   MatAssemblyEnd(DRDU, MAT_FINAL_ASSEMBLY);
137:   return 0;
138: }

140: static PetscErrorCode DRDPJacobianTranspose(TS ts, PetscReal t, Vec U, Mat DRDP, AppCtx *ctx)
141: {
142:   MatZeroEntries(DRDP);
143:   MatAssemblyBegin(DRDP, MAT_FINAL_ASSEMBLY);
144:   MatAssemblyEnd(DRDP, MAT_FINAL_ASSEMBLY);
145:   return 0;
146: }

148: PetscErrorCode ComputeSensiP(Vec lambda, Vec mu, AppCtx *ctx)
149: {
150:   PetscScalar       *y, sensip;
151:   const PetscScalar *x;

153:   VecGetArrayRead(lambda, &x);
154:   VecGetArray(mu, &y);
155:   sensip = 1. / PetscSqrtScalar(1. - (ctx->Pm / ctx->Pmax) * (ctx->Pm / ctx->Pmax)) / ctx->Pmax * x[0] + y[0];
156:   y[0]   = sensip;
157:   VecRestoreArray(mu, &y);
158:   VecRestoreArrayRead(lambda, &x);
159:   return 0;
160: }

162: int main(int argc, char **argv)
163: {
164:   Vec          p;
165:   PetscScalar *x_ptr;
166:   PetscMPIInt  size;
167:   AppCtx       ctx;
168:   Vec          lowerb, upperb;
169:   Tao          tao;
170:   KSP          ksp;
171:   PC           pc;
172:   Vec          U, lambda[1], mu[1];
173:   Mat          A;    /* Jacobian matrix */
174:   Mat          Jacp; /* Jacobian matrix */
175:   Mat          DRDU, DRDP;
176:   PetscInt     n = 2;
177:   TS           quadts;

179:   /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
180:      Initialize program
181:      - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
183:   PetscInitialize(&argc, &argv, NULL, help);
185:   MPI_Comm_size(PETSC_COMM_WORLD, &size);

188:   /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
189:     Set runtime options
190:     - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
191:   PetscOptionsBegin(PETSC_COMM_WORLD, NULL, "Swing equation options", "");
192:   {
193:     ctx.beta    = 2;
194:     ctx.c       = PetscRealConstant(10000.0);
195:     ctx.u_s     = PetscRealConstant(1.0);
196:     ctx.omega_s = PetscRealConstant(1.0);
197:     ctx.omega_b = PetscRealConstant(120.0) * PETSC_PI;
198:     ctx.H       = PetscRealConstant(5.0);
199:     PetscOptionsScalar("-Inertia", "", "", ctx.H, &ctx.H, NULL);
200:     ctx.D = PetscRealConstant(5.0);
201:     PetscOptionsScalar("-D", "", "", ctx.D, &ctx.D, NULL);
202:     ctx.E    = PetscRealConstant(1.1378);
203:     ctx.V    = PetscRealConstant(1.0);
204:     ctx.X    = PetscRealConstant(0.545);
205:     ctx.Pmax = ctx.E * ctx.V / ctx.X;
206:     PetscOptionsScalar("-Pmax", "", "", ctx.Pmax, &ctx.Pmax, NULL);
207:     ctx.Pm = PetscRealConstant(1.0194);
208:     PetscOptionsScalar("-Pm", "", "", ctx.Pm, &ctx.Pm, NULL);
209:     ctx.tf  = PetscRealConstant(0.1);
210:     ctx.tcl = PetscRealConstant(0.2);
211:     PetscOptionsReal("-tf", "Time to start fault", "", ctx.tf, &ctx.tf, NULL);
212:     PetscOptionsReal("-tcl", "Time to end fault", "", ctx.tcl, &ctx.tcl, NULL);
213:   }
214:   PetscOptionsEnd();

216:   /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
217:     Create necessary matrix and vectors
218:     - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
219:   MatCreate(PETSC_COMM_WORLD, &A);
220:   MatSetSizes(A, n, n, PETSC_DETERMINE, PETSC_DETERMINE);
221:   MatSetType(A, MATDENSE);
222:   MatSetFromOptions(A);
223:   MatSetUp(A);

225:   MatCreateVecs(A, &U, NULL);

227:   MatCreate(PETSC_COMM_WORLD, &Jacp);
228:   MatSetSizes(Jacp, PETSC_DECIDE, PETSC_DECIDE, 2, 1);
229:   MatSetFromOptions(Jacp);
230:   MatSetUp(Jacp);
231:   MatCreateDense(PETSC_COMM_WORLD, PETSC_DECIDE, PETSC_DECIDE, 1, 1, NULL, &DRDP);
232:   MatSetUp(DRDP);
233:   MatCreateDense(PETSC_COMM_WORLD, PETSC_DECIDE, PETSC_DECIDE, 1, 2, NULL, &DRDU);
234:   MatSetUp(DRDU);

236:   /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
237:      Create timestepping solver context
238:      - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
239:   TSCreate(PETSC_COMM_WORLD, &ctx.ts);
240:   TSSetProblemType(ctx.ts, TS_NONLINEAR);
241:   TSSetEquationType(ctx.ts, TS_EQ_ODE_EXPLICIT); /* less Jacobian evaluations when adjoint BEuler is used, otherwise no effect */
242:   TSSetType(ctx.ts, TSRK);
243:   TSSetRHSFunction(ctx.ts, NULL, (TSRHSFunction)RHSFunction, &ctx);
244:   TSSetRHSJacobian(ctx.ts, A, A, (TSRHSJacobian)RHSJacobian, &ctx);
245:   TSSetExactFinalTime(ctx.ts, TS_EXACTFINALTIME_MATCHSTEP);

247:   MatCreateVecs(A, &lambda[0], NULL);
248:   MatCreateVecs(Jacp, &mu[0], NULL);
249:   TSSetCostGradients(ctx.ts, 1, lambda, mu);
250:   TSSetRHSJacobianP(ctx.ts, Jacp, RHSJacobianP, &ctx);

252:   /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
253:      Set solver options
254:    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
255:   TSSetMaxTime(ctx.ts, PetscRealConstant(1.0));
256:   TSSetTimeStep(ctx.ts, PetscRealConstant(0.01));
257:   TSSetFromOptions(ctx.ts);

259:   TSGetTimeStep(ctx.ts, &ctx.dt); /* save the stepsize */

261:   TSCreateQuadratureTS(ctx.ts, PETSC_TRUE, &quadts);
262:   TSSetRHSFunction(quadts, NULL, (TSRHSFunction)CostIntegrand, &ctx);
263:   TSSetRHSJacobian(quadts, DRDU, DRDU, (TSRHSJacobian)DRDUJacobianTranspose, &ctx);
264:   TSSetRHSJacobianP(quadts, DRDP, (TSRHSJacobianP)DRDPJacobianTranspose, &ctx);
265:   TSSetSolution(ctx.ts, U);

267:   /* Create TAO solver and set desired solution method */
268:   TaoCreate(PETSC_COMM_WORLD, &tao);
269:   TaoSetType(tao, TAOBLMVM);

271:   /*
272:      Optimization starts
273:   */
274:   /* Set initial solution guess */
275:   VecCreateSeq(PETSC_COMM_WORLD, 1, &p);
276:   VecGetArray(p, &x_ptr);
277:   x_ptr[0] = ctx.Pm;
278:   VecRestoreArray(p, &x_ptr);

280:   TaoSetSolution(tao, p);
281:   /* Set routine for function and gradient evaluation */
282:   TaoSetObjective(tao, FormFunction, (void *)&ctx);
283:   TaoSetGradient(tao, NULL, FormGradient, (void *)&ctx);

285:   /* Set bounds for the optimization */
286:   VecDuplicate(p, &lowerb);
287:   VecDuplicate(p, &upperb);
288:   VecGetArray(lowerb, &x_ptr);
289:   x_ptr[0] = 0.;
290:   VecRestoreArray(lowerb, &x_ptr);
291:   VecGetArray(upperb, &x_ptr);
292:   x_ptr[0] = PetscRealConstant(1.1);
293:   VecRestoreArray(upperb, &x_ptr);
294:   TaoSetVariableBounds(tao, lowerb, upperb);

296:   /* Check for any TAO command line options */
297:   TaoSetFromOptions(tao);
298:   TaoGetKSP(tao, &ksp);
299:   if (ksp) {
300:     KSPGetPC(ksp, &pc);
301:     PCSetType(pc, PCNONE);
302:   }

304:   /* SOLVE THE APPLICATION */
305:   TaoSolve(tao);

307:   VecView(p, PETSC_VIEWER_STDOUT_WORLD);
308:   /* Free TAO data structures */
309:   TaoDestroy(&tao);
310:   VecDestroy(&p);
311:   VecDestroy(&lowerb);
312:   VecDestroy(&upperb);

314:   TSDestroy(&ctx.ts);
315:   VecDestroy(&U);
316:   MatDestroy(&A);
317:   MatDestroy(&Jacp);
318:   MatDestroy(&DRDU);
319:   MatDestroy(&DRDP);
320:   VecDestroy(&lambda[0]);
321:   VecDestroy(&mu[0]);
322:   PetscFinalize();
323:   return 0;
324: }

326: /* ------------------------------------------------------------------ */
327: /*
328:    FormFunction - Evaluates the function

330:    Input Parameters:
331:    tao - the Tao context
332:    X   - the input vector
333:    ptr - optional user-defined context, as set by TaoSetObjectiveAndGradient()

335:    Output Parameters:
336:    f   - the newly evaluated function
337: */
338: PetscErrorCode FormFunction(Tao tao, Vec P, PetscReal *f, void *ctx0)
339: {
340:   AppCtx      *ctx = (AppCtx *)ctx0;
341:   TS           ts  = ctx->ts;
342:   Vec          U; /* solution will be stored here */
343:   PetscScalar *u;
344:   PetscScalar *x_ptr;
345:   Vec          q;

347:   VecGetArrayRead(P, (const PetscScalar **)&x_ptr);
348:   ctx->Pm = x_ptr[0];
349:   VecRestoreArrayRead(P, (const PetscScalar **)&x_ptr);

351:   /* reset time */
352:   TSSetTime(ts, 0.0);
353:   /* reset step counter, this is critical for adjoint solver */
354:   TSSetStepNumber(ts, 0);
355:   /* reset step size, the step size becomes negative after TSAdjointSolve */
356:   TSSetTimeStep(ts, ctx->dt);
357:   /* reinitialize the integral value */
358:   TSGetCostIntegral(ts, &q);
359:   VecSet(q, 0.0);

361:   /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
362:      Set initial conditions
363:    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
364:   TSGetSolution(ts, &U);
365:   VecGetArray(U, &u);
366:   u[0] = PetscAsinScalar(ctx->Pm / ctx->Pmax);
367:   u[1] = PetscRealConstant(1.0);
368:   VecRestoreArray(U, &u);

370:   /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
371:      Solve nonlinear system
372:      - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
373:   TSSolve(ts, U);
374:   TSGetCostIntegral(ts, &q);
375:   VecGetArray(q, &x_ptr);
376:   *f = -ctx->Pm + x_ptr[0];
377:   VecRestoreArray(q, &x_ptr);
378:   return 0;
379: }

381: PetscErrorCode FormGradient(Tao tao, Vec P, Vec G, void *ctx0)
382: {
383:   AppCtx      *ctx = (AppCtx *)ctx0;
384:   TS           ts  = ctx->ts;
385:   Vec          U; /* solution will be stored here */
386:   PetscReal    ftime;
387:   PetscInt     steps;
388:   PetscScalar *u;
389:   PetscScalar *x_ptr, *y_ptr;
390:   Vec         *lambda, q, *mu;

392:   VecGetArrayRead(P, (const PetscScalar **)&x_ptr);
393:   ctx->Pm = x_ptr[0];
394:   VecRestoreArrayRead(P, (const PetscScalar **)&x_ptr);

396:   /* reset time */
397:   TSSetTime(ts, 0.0);
398:   /* reset step counter, this is critical for adjoint solver */
399:   TSSetStepNumber(ts, 0);
400:   /* reset step size, the step size becomes negative after TSAdjointSolve */
401:   TSSetTimeStep(ts, ctx->dt);
402:   /* reinitialize the integral value */
403:   TSGetCostIntegral(ts, &q);
404:   VecSet(q, 0.0);

406:   /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
407:      Set initial conditions
408:    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
409:   TSGetSolution(ts, &U);
410:   VecGetArray(U, &u);
411:   u[0] = PetscAsinScalar(ctx->Pm / ctx->Pmax);
412:   u[1] = PetscRealConstant(1.0);
413:   VecRestoreArray(U, &u);

415:   /* Set up to save trajectory before TSSetFromOptions() so that TSTrajectory options can be captured */
416:   TSSetSaveTrajectory(ts);
417:   TSSetFromOptions(ts);

419:   /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
420:      Solve nonlinear system
421:      - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
422:   TSSolve(ts, U);

424:   TSGetSolveTime(ts, &ftime);
425:   TSGetStepNumber(ts, &steps);

427:   /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
428:      Adjoint model starts here
429:      - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
430:   TSGetCostGradients(ts, NULL, &lambda, &mu);
431:   /*   Set initial conditions for the adjoint integration */
432:   VecGetArray(lambda[0], &y_ptr);
433:   y_ptr[0] = 0.0;
434:   y_ptr[1] = 0.0;
435:   VecRestoreArray(lambda[0], &y_ptr);
436:   VecGetArray(mu[0], &x_ptr);
437:   x_ptr[0] = PetscRealConstant(-1.0);
438:   VecRestoreArray(mu[0], &x_ptr);

440:   TSAdjointSolve(ts);
441:   TSGetCostIntegral(ts, &q);
442:   ComputeSensiP(lambda[0], mu[0], ctx);
443:   VecCopy(mu[0], G);
444:   return 0;
445: }

447: /*TEST

449:    build:
450:       requires: !complex

452:    test:
453:       args: -viewer_binary_skip_info -ts_adapt_type none -tao_monitor -tao_gatol 0.0 -tao_grtol 1.e-3 -tao_converged_reason

455:    test:
456:       suffix: 2
457:       args: -viewer_binary_skip_info -ts_adapt_type none -tao_monitor -tao_gatol 0.0 -tao_grtol 1.e-3 -tao_converged_reason -tao_test_gradient

459: TEST*/