Actual source code: spectraladjointassimilation.c

  1: static char help[] = "Solves a simple data assimilation problem with one dimensional advection diffusion equation using TSAdjoint\n\n";

  3: /*

  5:     Not yet tested in parallel

  7: */

  9: /* ------------------------------------------------------------------------

 11:    This program uses the one-dimensional advection-diffusion equation),
 12:        u_t = mu*u_xx - a u_x,
 13:    on the domain 0 <= x <= 1, with periodic boundary conditions

 15:    to demonstrate solving a data assimilation problem of finding the initial conditions
 16:    to produce a given solution at a fixed time.

 18:    The operators are discretized with the spectral element method

 20:   ------------------------------------------------------------------------- */

 22: /*
 23:    Include "petscts.h" so that we can use the TS ODE integrators. Note that this file
 24:    automatically includes:
 25:      petscsys.h  - base PETSc routines
 26:      petscis.h   - index sets
 27:      petscvec.h  - vectors
 28:      petscmat.h  - matrices
 29:      petscpc.h   - preconditioners
 30:      petscksp.h  - linear solvers
 31:      petscsnes.h - nonlinear solvers
 32: */

 34: #include <petsctao.h>
 35: #include <petscts.h>
 36: #include <petscdt.h>
 37: #include <petscdmda.h>

 39: /*
 40:    User-defined application context - contains data needed by the
 41:    application-provided call-back routines.
 42: */

 44: typedef struct {
 45:   PetscInt   n;       /* number of nodes */
 46:   PetscReal *nodes;   /* GLL nodes */
 47:   PetscReal *weights; /* GLL weights */
 48: } PetscGLL;

 50: typedef struct {
 51:   PetscInt  N;               /* grid points per elements*/
 52:   PetscInt  E;               /* number of elements */
 53:   PetscReal tol_L2, tol_max; /* error norms */
 54:   PetscInt  steps;           /* number of timesteps */
 55:   PetscReal Tend;            /* endtime */
 56:   PetscReal mu;              /* viscosity */
 57:   PetscReal a;               /* advection speed */
 58:   PetscReal L;               /* total length of domain */
 59:   PetscReal Le;
 60:   PetscReal Tadj;
 61: } PetscParam;

 63: typedef struct {
 64:   Vec reference; /* desired end state */
 65:   Vec grid;      /* total grid */
 66:   Vec grad;
 67:   Vec ic;
 68:   Vec curr_sol;
 69:   Vec joe;
 70:   Vec true_solution; /* actual initial conditions for the final solution */
 71: } PetscData;

 73: typedef struct {
 74:   Vec      grid;  /* total grid */
 75:   Vec      mass;  /* mass matrix for total integration */
 76:   Mat      stiff; /* stiffness matrix */
 77:   Mat      advec;
 78:   Mat      keptstiff;
 79:   PetscGLL gll;
 80: } PetscSEMOperators;

 82: typedef struct {
 83:   DM                da; /* distributed array data structure */
 84:   PetscSEMOperators SEMop;
 85:   PetscParam        param;
 86:   PetscData         dat;
 87:   TS                ts;
 88:   PetscReal         initial_dt;
 89:   PetscReal        *solutioncoefficients;
 90:   PetscInt          ncoeff;
 91: } AppCtx;

 93: /*
 94:    User-defined routines
 95: */
 96: extern PetscErrorCode FormFunctionGradient(Tao, Vec, PetscReal *, Vec, void *);
 97: extern PetscErrorCode RHSLaplacian(TS, PetscReal, Vec, Mat, Mat, void *);
 98: extern PetscErrorCode RHSAdvection(TS, PetscReal, Vec, Mat, Mat, void *);
 99: extern PetscErrorCode InitialConditions(Vec, AppCtx *);
100: extern PetscErrorCode ComputeReference(TS, PetscReal, Vec, AppCtx *);
101: extern PetscErrorCode MonitorError(Tao, void *);
102: extern PetscErrorCode MonitorDestroy(PetscCtxRt);
103: extern PetscErrorCode ComputeSolutionCoefficients(AppCtx *);
104: extern PetscErrorCode RHSFunction(TS, PetscReal, Vec, Vec, void *);
105: extern PetscErrorCode RHSJacobian(TS, PetscReal, Vec, Mat, Mat, void *);

107: int main(int argc, char **argv)
108: {
109:   AppCtx       appctx; /* user-defined application context */
110:   Tao          tao;
111:   Vec          u; /* approximate solution vector */
112:   PetscInt     i, xs, xm, ind, j, lenglob;
113:   PetscReal    x, *wrk_ptr1, *wrk_ptr2;
114:   MatNullSpace nsp;

116:   /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
117:      Initialize program and set problem parameters
118:      - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
119:   PetscFunctionBeginUser;
120:   PetscCall(PetscInitialize(&argc, &argv, NULL, help));

122:   /*initialize parameters */
123:   appctx.param.N     = 10;      /* order of the spectral element */
124:   appctx.param.E     = 8;       /* number of elements */
125:   appctx.param.L     = 1.0;     /* length of the domain */
126:   appctx.param.mu    = 0.00001; /* diffusion coefficient */
127:   appctx.param.a     = 0.0;     /* advection speed */
128:   appctx.initial_dt  = 1e-4;
129:   appctx.param.steps = PETSC_INT_MAX;
130:   appctx.param.Tend  = 0.01;
131:   appctx.ncoeff      = 2;

133:   PetscCall(PetscOptionsGetInt(NULL, NULL, "-N", &appctx.param.N, NULL));
134:   PetscCall(PetscOptionsGetInt(NULL, NULL, "-E", &appctx.param.E, NULL));
135:   PetscCall(PetscOptionsGetInt(NULL, NULL, "-ncoeff", &appctx.ncoeff, NULL));
136:   PetscCall(PetscOptionsGetReal(NULL, NULL, "-Tend", &appctx.param.Tend, NULL));
137:   PetscCall(PetscOptionsGetReal(NULL, NULL, "-mu", &appctx.param.mu, NULL));
138:   PetscCall(PetscOptionsGetReal(NULL, NULL, "-a", &appctx.param.a, NULL));
139:   appctx.param.Le = appctx.param.L / appctx.param.E;

141:   /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
142:      Create GLL data structures
143:      - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
144:   PetscCall(PetscMalloc2(appctx.param.N, &appctx.SEMop.gll.nodes, appctx.param.N, &appctx.SEMop.gll.weights));
145:   PetscCall(PetscDTGaussLobattoLegendreQuadrature(appctx.param.N, PETSCGAUSSLOBATTOLEGENDRE_VIA_LINEAR_ALGEBRA, appctx.SEMop.gll.nodes, appctx.SEMop.gll.weights));
146:   appctx.SEMop.gll.n = appctx.param.N;
147:   lenglob            = appctx.param.E * (appctx.param.N - 1);

149:   /*
150:      Create distributed array (DMDA) to manage parallel grid and vectors
151:      and to set up the ghost point communication pattern.  There are E*(Nl-1)+1
152:      total grid values spread equally among all the processors, except first and last
153:   */

155:   PetscCall(DMDACreate1d(PETSC_COMM_WORLD, DM_BOUNDARY_PERIODIC, lenglob, 1, 1, NULL, &appctx.da));
156:   PetscCall(DMSetFromOptions(appctx.da));
157:   PetscCall(DMSetUp(appctx.da));

159:   /*
160:      Extract global and local vectors from DMDA; we use these to store the
161:      approximate solution.  Then duplicate these for remaining vectors that
162:      have the same types.
163:   */

165:   PetscCall(DMCreateGlobalVector(appctx.da, &u));
166:   PetscCall(VecDuplicate(u, &appctx.dat.ic));
167:   PetscCall(VecDuplicate(u, &appctx.dat.true_solution));
168:   PetscCall(VecDuplicate(u, &appctx.dat.reference));
169:   PetscCall(VecDuplicate(u, &appctx.SEMop.grid));
170:   PetscCall(VecDuplicate(u, &appctx.SEMop.mass));
171:   PetscCall(VecDuplicate(u, &appctx.dat.curr_sol));
172:   PetscCall(VecDuplicate(u, &appctx.dat.joe));

174:   PetscCall(DMDAGetCorners(appctx.da, &xs, NULL, NULL, &xm, NULL, NULL));
175:   PetscCall(DMDAVecGetArray(appctx.da, appctx.SEMop.grid, &wrk_ptr1));
176:   PetscCall(DMDAVecGetArray(appctx.da, appctx.SEMop.mass, &wrk_ptr2));

178:   /* Compute function over the locally owned part of the grid */

180:   xs = xs / (appctx.param.N - 1);
181:   xm = xm / (appctx.param.N - 1);

183:   /*
184:      Build total grid and mass over entire mesh (multi-elemental)
185:   */

187:   for (i = xs; i < xs + xm; i++) {
188:     for (j = 0; j < appctx.param.N - 1; j++) {
189:       x             = (appctx.param.Le / 2.0) * (appctx.SEMop.gll.nodes[j] + 1.0) + appctx.param.Le * i;
190:       ind           = i * (appctx.param.N - 1) + j;
191:       wrk_ptr1[ind] = x;
192:       wrk_ptr2[ind] = .5 * appctx.param.Le * appctx.SEMop.gll.weights[j];
193:       if (j == 0) wrk_ptr2[ind] += .5 * appctx.param.Le * appctx.SEMop.gll.weights[j];
194:     }
195:   }
196:   PetscCall(DMDAVecRestoreArray(appctx.da, appctx.SEMop.grid, &wrk_ptr1));
197:   PetscCall(DMDAVecRestoreArray(appctx.da, appctx.SEMop.mass, &wrk_ptr2));

199:   /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
200:    Create matrix data structure; set matrix evaluation routine.
201:    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
202:   PetscCall(DMSetMatrixPreallocateOnly(appctx.da, PETSC_TRUE));
203:   PetscCall(DMCreateMatrix(appctx.da, &appctx.SEMop.stiff));
204:   PetscCall(DMCreateMatrix(appctx.da, &appctx.SEMop.advec));

206:   /*
207:    For linear problems with a time-dependent f(u,t) in the equation
208:    u_t = f(u,t), the user provides the discretized right-hand side
209:    as a time-dependent matrix.
210:    */
211:   PetscCall(RHSLaplacian(appctx.ts, 0.0, u, appctx.SEMop.stiff, appctx.SEMop.stiff, &appctx));
212:   PetscCall(RHSAdvection(appctx.ts, 0.0, u, appctx.SEMop.advec, appctx.SEMop.advec, &appctx));
213:   PetscCall(MatAXPY(appctx.SEMop.stiff, -1.0, appctx.SEMop.advec, DIFFERENT_NONZERO_PATTERN));
214:   PetscCall(MatDuplicate(appctx.SEMop.stiff, MAT_COPY_VALUES, &appctx.SEMop.keptstiff));

216:   /* attach the null space to the matrix, this probably is not needed but does no harm */
217:   PetscCall(MatNullSpaceCreate(PETSC_COMM_WORLD, PETSC_TRUE, 0, NULL, &nsp));
218:   PetscCall(MatSetNullSpace(appctx.SEMop.stiff, nsp));
219:   PetscCall(MatNullSpaceTest(nsp, appctx.SEMop.stiff, NULL));
220:   PetscCall(MatNullSpaceDestroy(&nsp));

222:   /* Create the TS solver that solves the ODE and its adjoint; set its options */
223:   PetscCall(TSCreate(PETSC_COMM_WORLD, &appctx.ts));
224:   PetscCall(TSSetSolutionFunction(appctx.ts, (PetscErrorCode (*)(TS, PetscReal, Vec, void *))ComputeReference, &appctx));
225:   PetscCall(TSSetProblemType(appctx.ts, TS_LINEAR));
226:   PetscCall(TSSetType(appctx.ts, TSRK));
227:   PetscCall(TSSetDM(appctx.ts, appctx.da));
228:   PetscCall(TSSetTime(appctx.ts, 0.0));
229:   PetscCall(TSSetTimeStep(appctx.ts, appctx.initial_dt));
230:   PetscCall(TSSetMaxSteps(appctx.ts, appctx.param.steps));
231:   PetscCall(TSSetMaxTime(appctx.ts, appctx.param.Tend));
232:   PetscCall(TSSetExactFinalTime(appctx.ts, TS_EXACTFINALTIME_MATCHSTEP));
233:   PetscCall(TSSetTolerances(appctx.ts, 1e-7, NULL, 1e-7, NULL));
234:   PetscCall(TSSetFromOptions(appctx.ts));
235:   /* Need to save initial timestep user may have set with -ts_time_step so it can be reset for each new TSSolve() */
236:   PetscCall(TSGetTimeStep(appctx.ts, &appctx.initial_dt));
237:   PetscCall(TSSetRHSFunction(appctx.ts, NULL, TSComputeRHSFunctionLinear, &appctx));
238:   PetscCall(TSSetRHSJacobian(appctx.ts, appctx.SEMop.stiff, appctx.SEMop.stiff, TSComputeRHSJacobianConstant, &appctx));
239:   /*  PetscCall(TSSetRHSFunction(appctx.ts,NULL,RHSFunction,&appctx));
240:       PetscCall(TSSetRHSJacobian(appctx.ts,appctx.SEMop.stiff,appctx.SEMop.stiff,RHSJacobian,&appctx)); */

242:   /* Set random initial conditions as initial guess, compute analytic reference solution and analytic (true) initial conditions */
243:   PetscCall(ComputeSolutionCoefficients(&appctx));
244:   PetscCall(InitialConditions(appctx.dat.ic, &appctx));
245:   PetscCall(ComputeReference(appctx.ts, appctx.param.Tend, appctx.dat.reference, &appctx));
246:   PetscCall(ComputeReference(appctx.ts, 0.0, appctx.dat.true_solution, &appctx));

248:   /* Set up to save trajectory before TSSetFromOptions() so that TSTrajectory options can be captured */
249:   PetscCall(TSSetSaveTrajectory(appctx.ts));
250:   PetscCall(TSSetFromOptions(appctx.ts));

252:   /* Create TAO solver and set desired solution method  */
253:   PetscCall(TaoCreate(PETSC_COMM_WORLD, &tao));
254:   PetscCall(TaoMonitorSet(tao, MonitorError, &appctx, MonitorDestroy));
255:   PetscCall(TaoSetType(tao, TAOBQNLS));
256:   PetscCall(TaoSetSolution(tao, appctx.dat.ic));
257:   /* Set routine for function and gradient evaluation  */
258:   PetscCall(TaoSetObjectiveAndGradient(tao, NULL, FormFunctionGradient, (void *)&appctx));
259:   /* Check for any TAO command line options  */
260:   PetscCall(TaoSetTolerances(tao, 1e-8, PETSC_CURRENT, PETSC_CURRENT));
261:   PetscCall(TaoSetFromOptions(tao));
262:   PetscCall(TaoSolve(tao));

264:   PetscCall(TaoDestroy(&tao));
265:   PetscCall(PetscFree(appctx.solutioncoefficients));
266:   PetscCall(MatDestroy(&appctx.SEMop.advec));
267:   PetscCall(MatDestroy(&appctx.SEMop.stiff));
268:   PetscCall(MatDestroy(&appctx.SEMop.keptstiff));
269:   PetscCall(VecDestroy(&u));
270:   PetscCall(VecDestroy(&appctx.dat.ic));
271:   PetscCall(VecDestroy(&appctx.dat.joe));
272:   PetscCall(VecDestroy(&appctx.dat.true_solution));
273:   PetscCall(VecDestroy(&appctx.dat.reference));
274:   PetscCall(VecDestroy(&appctx.SEMop.grid));
275:   PetscCall(VecDestroy(&appctx.SEMop.mass));
276:   PetscCall(VecDestroy(&appctx.dat.curr_sol));
277:   PetscCall(PetscFree2(appctx.SEMop.gll.nodes, appctx.SEMop.gll.weights));
278:   PetscCall(DMDestroy(&appctx.da));
279:   PetscCall(TSDestroy(&appctx.ts));

281:   /*
282:      Always call PetscFinalize() before exiting a program.  This routine
283:        - finalizes the PETSc libraries as well as MPI
284:        - provides summary and diagnostic information if certain runtime
285:          options are chosen (e.g., -log_view).
286:   */
287:   PetscCall(PetscFinalize());
288:   return 0;
289: }

291: /*
292:     Computes the coefficients for the analytic solution to the PDE
293: */
294: PetscErrorCode ComputeSolutionCoefficients(AppCtx *appctx)
295: {
296:   PetscRandom rand;
297:   PetscInt    i;

299:   PetscFunctionBegin;
300:   PetscCall(PetscMalloc1(appctx->ncoeff, &appctx->solutioncoefficients));
301:   PetscCall(PetscRandomCreate(PETSC_COMM_WORLD, &rand));
302:   PetscCall(PetscRandomSetInterval(rand, .9, 1.0));
303:   for (i = 0; i < appctx->ncoeff; i++) PetscCall(PetscRandomGetValue(rand, &appctx->solutioncoefficients[i]));
304:   PetscCall(PetscRandomDestroy(&rand));
305:   PetscFunctionReturn(PETSC_SUCCESS);
306: }

308: /* --------------------------------------------------------------------- */
309: /*
310:    InitialConditions - Computes the (random) initial conditions for the Tao optimization solve (these are also initial conditions for the first TSSolve()

312:    Input Parameter:
313:    u - uninitialized solution vector (global)
314:    appctx - user-defined application context

316:    Output Parameter:
317:    u - vector with solution at initial time (global)
318: */
319: PetscErrorCode InitialConditions(Vec u, AppCtx *appctx)
320: {
321:   PetscScalar       *s;
322:   const PetscScalar *xg;
323:   PetscInt           i, j, lenglob;
324:   PetscReal          sum, val;
325:   PetscRandom        rand;

327:   PetscFunctionBegin;
328:   PetscCall(PetscRandomCreate(PETSC_COMM_WORLD, &rand));
329:   PetscCall(PetscRandomSetInterval(rand, .9, 1.0));
330:   PetscCall(DMDAVecGetArray(appctx->da, u, &s));
331:   PetscCall(DMDAVecGetArrayRead(appctx->da, appctx->SEMop.grid, (void *)&xg));
332:   lenglob = appctx->param.E * (appctx->param.N - 1);
333:   for (i = 0; i < lenglob; i++) {
334:     s[i] = 0;
335:     for (j = 0; j < appctx->ncoeff; j++) {
336:       PetscCall(PetscRandomGetValue(rand, &val));
337:       s[i] += val * PetscSinScalar(2 * (j + 1) * PETSC_PI * xg[i]);
338:     }
339:   }
340:   PetscCall(PetscRandomDestroy(&rand));
341:   PetscCall(DMDAVecRestoreArray(appctx->da, u, &s));
342:   PetscCall(DMDAVecRestoreArrayRead(appctx->da, appctx->SEMop.grid, (void *)&xg));
343:   /* make sure initial conditions do not contain the constant functions, since with periodic boundary conditions the constant functions introduce a null space */
344:   PetscCall(VecSum(u, &sum));
345:   PetscCall(VecShift(u, -sum / lenglob));
346:   PetscFunctionReturn(PETSC_SUCCESS);
347: }

349: /*
350:    TrueSolution() computes the true solution for the Tao optimization solve which means they are the initial conditions for the objective function.

352:              InitialConditions() computes the initial conditions for the beginning of the Tao iterations

354:    Input Parameter:
355:    u - uninitialized solution vector (global)
356:    appctx - user-defined application context

358:    Output Parameter:
359:    u - vector with solution at initial time (global)
360: */
361: PetscErrorCode TrueSolution(Vec u, AppCtx *appctx)
362: {
363:   PetscScalar       *s;
364:   const PetscScalar *xg;
365:   PetscInt           i, j, lenglob;
366:   PetscReal          sum;

368:   PetscFunctionBegin;
369:   PetscCall(DMDAVecGetArray(appctx->da, u, &s));
370:   PetscCall(DMDAVecGetArrayRead(appctx->da, appctx->SEMop.grid, (void *)&xg));
371:   lenglob = appctx->param.E * (appctx->param.N - 1);
372:   for (i = 0; i < lenglob; i++) {
373:     s[i] = 0;
374:     for (j = 0; j < appctx->ncoeff; j++) s[i] += appctx->solutioncoefficients[j] * PetscSinScalar(2 * (j + 1) * PETSC_PI * xg[i]);
375:   }
376:   PetscCall(DMDAVecRestoreArray(appctx->da, u, &s));
377:   PetscCall(DMDAVecRestoreArrayRead(appctx->da, appctx->SEMop.grid, (void *)&xg));
378:   /* make sure initial conditions do not contain the constant functions, since with periodic boundary conditions the constant functions introduce a null space */
379:   PetscCall(VecSum(u, &sum));
380:   PetscCall(VecShift(u, -sum / lenglob));
381:   PetscFunctionReturn(PETSC_SUCCESS);
382: }
383: /* --------------------------------------------------------------------- */
384: /*
385:    Sets the desired profile for the final end time

387:    Input Parameters:
388:    t - final time
389:    obj - vector storing the desired profile
390:    appctx - user-defined application context

392: */
393: PetscErrorCode ComputeReference(TS ts, PetscReal t, Vec obj, AppCtx *appctx)
394: {
395:   PetscScalar       *s, tc;
396:   const PetscScalar *xg;
397:   PetscInt           i, j, lenglob;

399:   PetscFunctionBegin;
400:   PetscCall(DMDAVecGetArray(appctx->da, obj, &s));
401:   PetscCall(DMDAVecGetArrayRead(appctx->da, appctx->SEMop.grid, (void *)&xg));
402:   lenglob = appctx->param.E * (appctx->param.N - 1);
403:   for (i = 0; i < lenglob; i++) {
404:     s[i] = 0;
405:     for (j = 0; j < appctx->ncoeff; j++) {
406:       tc = -appctx->param.mu * (j + 1) * (j + 1) * 4.0 * PETSC_PI * PETSC_PI * t;
407:       s[i] += appctx->solutioncoefficients[j] * PetscSinScalar(2 * (j + 1) * PETSC_PI * (xg[i] + appctx->param.a * t)) * PetscExpReal(tc);
408:     }
409:   }
410:   PetscCall(DMDAVecRestoreArray(appctx->da, obj, &s));
411:   PetscCall(DMDAVecRestoreArrayRead(appctx->da, appctx->SEMop.grid, (void *)&xg));
412:   PetscFunctionReturn(PETSC_SUCCESS);
413: }

415: PetscErrorCode RHSFunction(TS ts, PetscReal t, Vec globalin, Vec globalout, PetscCtx ctx)
416: {
417:   AppCtx *appctx = (AppCtx *)ctx;

419:   PetscFunctionBegin;
420:   PetscCall(MatMult(appctx->SEMop.keptstiff, globalin, globalout));
421:   PetscFunctionReturn(PETSC_SUCCESS);
422: }

424: PetscErrorCode RHSJacobian(TS ts, PetscReal t, Vec globalin, Mat A, Mat B, PetscCtx ctx)
425: {
426:   AppCtx *appctx = (AppCtx *)ctx;

428:   PetscFunctionBegin;
429:   PetscCall(MatCopy(appctx->SEMop.keptstiff, A, DIFFERENT_NONZERO_PATTERN));
430:   PetscFunctionReturn(PETSC_SUCCESS);
431: }

433: /* --------------------------------------------------------------------- */

435: /*
436:    RHSLaplacian -   matrix for diffusion

438:    Input Parameters:
439:    ts - the TS context
440:    t - current time  (ignored)
441:    X - current solution (ignored)
442:    dummy - optional user-defined context, as set by TSetRHSJacobian()

444:    Output Parameters:
445:    AA - Jacobian matrix
446:    BB - optionally different matrix from which the preconditioner is built

448:    Scales by the inverse of the mass matrix (perhaps that should be pulled out)

450: */
451: PetscErrorCode RHSLaplacian(TS ts, PetscReal t, Vec X, Mat A, Mat BB, PetscCtx ctx)
452: {
453:   PetscReal **temp;
454:   PetscReal   vv;
455:   AppCtx     *appctx = (AppCtx *)ctx; /* user-defined application context */
456:   PetscInt    i, xs, xn, l, j;
457:   PetscInt   *rowsDM;

459:   PetscFunctionBegin;
460:   /*
461:    Creates the element stiffness matrix for the given gll
462:    */
463:   PetscCall(PetscGaussLobattoLegendreElementLaplacianCreate(appctx->SEMop.gll.n, appctx->SEMop.gll.nodes, appctx->SEMop.gll.weights, &temp));

465:   /* scale by the size of the element */
466:   for (i = 0; i < appctx->param.N; i++) {
467:     vv = -appctx->param.mu * 2.0 / appctx->param.Le;
468:     for (j = 0; j < appctx->param.N; j++) temp[i][j] = temp[i][j] * vv;
469:   }

471:   PetscCall(MatSetOption(A, MAT_NEW_NONZERO_ALLOCATION_ERR, PETSC_FALSE));
472:   PetscCall(DMDAGetCorners(appctx->da, &xs, NULL, NULL, &xn, NULL, NULL));

474:   PetscCheck(appctx->param.N - 1 >= 1, PETSC_COMM_WORLD, PETSC_ERR_ARG_OUTOFRANGE, "Polynomial order must be at least 2");
475:   xs = xs / (appctx->param.N - 1);
476:   xn = xn / (appctx->param.N - 1);

478:   PetscCall(PetscMalloc1(appctx->param.N, &rowsDM));
479:   /*
480:    loop over local elements
481:    */
482:   for (j = xs; j < xs + xn; j++) {
483:     for (l = 0; l < appctx->param.N; l++) rowsDM[l] = 1 + (j - xs) * (appctx->param.N - 1) + l;
484:     PetscCall(MatSetValuesLocal(A, appctx->param.N, rowsDM, appctx->param.N, rowsDM, &temp[0][0], ADD_VALUES));
485:   }
486:   PetscCall(PetscFree(rowsDM));
487:   PetscCall(MatAssemblyBegin(A, MAT_FINAL_ASSEMBLY));
488:   PetscCall(MatAssemblyEnd(A, MAT_FINAL_ASSEMBLY));
489:   PetscCall(VecReciprocal(appctx->SEMop.mass));
490:   PetscCall(MatDiagonalScale(A, appctx->SEMop.mass, NULL));
491:   PetscCall(VecReciprocal(appctx->SEMop.mass));

493:   PetscCall(PetscGaussLobattoLegendreElementLaplacianDestroy(appctx->SEMop.gll.n, appctx->SEMop.gll.nodes, appctx->SEMop.gll.weights, &temp));
494:   PetscFunctionReturn(PETSC_SUCCESS);
495: }

497: /*
498:     Almost identical to Laplacian

500:     Note that the element matrix is NOT scaled by the size of element like the Laplacian term.
501:  */
502: PetscErrorCode RHSAdvection(TS ts, PetscReal t, Vec X, Mat A, Mat BB, PetscCtx ctx)
503: {
504:   PetscReal **temp;
505:   PetscReal   vv;
506:   AppCtx     *appctx = (AppCtx *)ctx; /* user-defined application context */
507:   PetscInt    i, xs, xn, l, j;
508:   PetscInt   *rowsDM;

510:   PetscFunctionBegin;
511:   /*
512:    Creates the element stiffness matrix for the given gll
513:    */
514:   PetscCall(PetscGaussLobattoLegendreElementAdvectionCreate(appctx->SEMop.gll.n, appctx->SEMop.gll.nodes, appctx->SEMop.gll.weights, &temp));

516:   /* scale by the size of the element */
517:   for (i = 0; i < appctx->param.N; i++) {
518:     vv = -appctx->param.a;
519:     for (j = 0; j < appctx->param.N; j++) temp[i][j] = temp[i][j] * vv;
520:   }

522:   PetscCall(MatSetOption(A, MAT_NEW_NONZERO_ALLOCATION_ERR, PETSC_FALSE));
523:   PetscCall(DMDAGetCorners(appctx->da, &xs, NULL, NULL, &xn, NULL, NULL));

525:   PetscCheck(appctx->param.N - 1 >= 1, PETSC_COMM_WORLD, PETSC_ERR_ARG_OUTOFRANGE, "Polynomial order must be at least 2");
526:   xs = xs / (appctx->param.N - 1);
527:   xn = xn / (appctx->param.N - 1);

529:   PetscCall(PetscMalloc1(appctx->param.N, &rowsDM));
530:   /*
531:    loop over local elements
532:    */
533:   for (j = xs; j < xs + xn; j++) {
534:     for (l = 0; l < appctx->param.N; l++) rowsDM[l] = 1 + (j - xs) * (appctx->param.N - 1) + l;
535:     PetscCall(MatSetValuesLocal(A, appctx->param.N, rowsDM, appctx->param.N, rowsDM, &temp[0][0], ADD_VALUES));
536:   }
537:   PetscCall(PetscFree(rowsDM));
538:   PetscCall(MatAssemblyBegin(A, MAT_FINAL_ASSEMBLY));
539:   PetscCall(MatAssemblyEnd(A, MAT_FINAL_ASSEMBLY));
540:   PetscCall(VecReciprocal(appctx->SEMop.mass));
541:   PetscCall(MatDiagonalScale(A, appctx->SEMop.mass, NULL));
542:   PetscCall(VecReciprocal(appctx->SEMop.mass));

544:   PetscCall(PetscGaussLobattoLegendreElementAdvectionDestroy(appctx->SEMop.gll.n, appctx->SEMop.gll.nodes, appctx->SEMop.gll.weights, &temp));
545:   PetscFunctionReturn(PETSC_SUCCESS);
546: }

548: /* ------------------------------------------------------------------ */
549: /*
550:    FormFunctionGradient - Evaluates the function and corresponding gradient.

552:    Input Parameters:
553:    tao - the Tao context
554:    ic   - the input vector
555:    ctx - optional user-defined context, as set when calling TaoSetObjectiveAndGradient()

557:    Output Parameters:
558:    f   - the newly evaluated function
559:    G   - the newly evaluated gradient

561:    Notes:

563:           The forward equation is
564:               M u_t = F(U)
565:           which is converted to
566:                 u_t = M^{-1} F(u)
567:           in the user code since TS has no direct way of providing a mass matrix. The Jacobian of this is
568:                  M^{-1} J
569:           where J is the Jacobian of F. Now the adjoint equation is
570:                 M v_t = J^T v
571:           but TSAdjoint does not solve this since it can only solve the transposed system for the
572:           Jacobian the user provided. Hence TSAdjoint solves
573:                  w_t = J^T M^{-1} w  (where w = M v)
574:           since there is no way to indicate the mass matrix as a separate entity to TS. Thus one
575:           must be careful in initializing the "adjoint equation" and using the result. This is
576:           why
577:               G = -2 M(u(T) - u_d)
578:           below (instead of -2(u(T) - u_d)

580: */
581: PetscErrorCode FormFunctionGradient(Tao tao, Vec ic, PetscReal *f, Vec G, PetscCtx ctx)
582: {
583:   AppCtx *appctx = (AppCtx *)ctx; /* user-defined application context */
584:   Vec     temp;

586:   PetscFunctionBegin;
587:   PetscCall(TSSetTime(appctx->ts, 0.0));
588:   PetscCall(TSSetStepNumber(appctx->ts, 0));
589:   PetscCall(TSSetTimeStep(appctx->ts, appctx->initial_dt));
590:   PetscCall(VecCopy(ic, appctx->dat.curr_sol));

592:   PetscCall(TSSolve(appctx->ts, appctx->dat.curr_sol));
593:   PetscCall(VecCopy(appctx->dat.curr_sol, appctx->dat.joe));

595:   /*     Compute the difference between the current ODE solution and target ODE solution */
596:   PetscCall(VecWAXPY(G, -1.0, appctx->dat.curr_sol, appctx->dat.reference));

598:   /*     Compute the objective/cost function   */
599:   PetscCall(VecDuplicate(G, &temp));
600:   PetscCall(VecPointwiseMult(temp, G, G));
601:   PetscCall(VecDot(temp, appctx->SEMop.mass, f));
602:   PetscCall(VecDestroy(&temp));

604:   /*     Compute initial conditions for the adjoint integration. See Notes above  */
605:   PetscCall(VecScale(G, -2.0));
606:   PetscCall(VecPointwiseMult(G, G, appctx->SEMop.mass));
607:   PetscCall(TSSetCostGradients(appctx->ts, 1, &G, NULL));

609:   PetscCall(TSAdjointSolve(appctx->ts));
610:   /* PetscCall(VecPointwiseDivide(G,G,appctx->SEMop.mass));*/
611:   PetscFunctionReturn(PETSC_SUCCESS);
612: }

614: PetscErrorCode MonitorError(Tao tao, PetscCtx ctx)
615: {
616:   AppCtx   *appctx = (AppCtx *)ctx;
617:   Vec       temp, grad;
618:   PetscReal nrm;
619:   PetscInt  its;
620:   PetscReal fct, gnorm;

622:   PetscFunctionBegin;
623:   PetscCall(VecDuplicate(appctx->dat.ic, &temp));
624:   PetscCall(VecWAXPY(temp, -1.0, appctx->dat.ic, appctx->dat.true_solution));
625:   PetscCall(VecPointwiseMult(temp, temp, temp));
626:   PetscCall(VecDot(temp, appctx->SEMop.mass, &nrm));
627:   nrm = PetscSqrtReal(nrm);
628:   PetscCall(TaoGetGradient(tao, &grad, NULL, NULL));
629:   PetscCall(VecPointwiseMult(temp, temp, temp));
630:   PetscCall(VecDot(temp, appctx->SEMop.mass, &gnorm));
631:   gnorm = PetscSqrtReal(gnorm);
632:   PetscCall(VecDestroy(&temp));
633:   PetscCall(TaoGetIterationNumber(tao, &its));
634:   PetscCall(TaoGetSolutionStatus(tao, NULL, &fct, NULL, NULL, NULL, NULL));
635:   if (!its) {
636:     PetscCall(PetscPrintf(PETSC_COMM_WORLD, "%% Iteration Error Objective Gradient-norm\n"));
637:     PetscCall(PetscPrintf(PETSC_COMM_WORLD, "history = [\n"));
638:   }
639:   PetscCall(PetscPrintf(PETSC_COMM_WORLD, "%3" PetscInt_FMT " %g %g %g\n", its, (double)nrm, (double)fct, (double)gnorm));
640:   PetscFunctionReturn(PETSC_SUCCESS);
641: }

643: PetscErrorCode MonitorDestroy(PetscCtxRt ctx)
644: {
645:   PetscFunctionBegin;
646:   PetscCall(PetscPrintf(PETSC_COMM_WORLD, "];\n"));
647:   PetscFunctionReturn(PETSC_SUCCESS);
648: }

650: /*TEST

652:    build:
653:      requires: !complex

655:    test:
656:      requires: !single
657:      args: -ts_adapt_dt_max 3.e-3 -E 10 -N 8 -ncoeff 5 -tao_bqnls_mat_lmvm_scale_type none

659:    test:
660:      suffix: cn
661:      requires: !single
662:      args: -ts_type cn -ts_time_step .003 -pc_type lu -E 10 -N 8 -ncoeff 5 -tao_bqnls_mat_lmvm_scale_type none

664:    test:
665:      suffix: 2
666:      requires: !single
667:      args: -ts_adapt_dt_max 3.e-3 -E 10 -N 8 -ncoeff 5 -a .1 -tao_bqnls_mat_lmvm_scale_type none

669: TEST*/