Actual source code: traj.c

  1: #include <petsc/private/tsimpl.h>
  2: #include <petsc/private/tshistoryimpl.h>
  3: #include <petscdm.h>

  5: PetscFunctionList TSTrajectoryList              = NULL;
  6: PetscBool         TSTrajectoryRegisterAllCalled = PETSC_FALSE;
  7: PetscClassId      TSTRAJECTORY_CLASSID;
  8: PetscLogEvent     TSTrajectory_Set, TSTrajectory_Get, TSTrajectory_GetVecs, TSTrajectory_SetUp;

 10: /*@
 11:   TSTrajectoryRegister - Adds a way of storing trajectories to the `TS` package

 13:   Not Collective, No Fortran Support

 15:   Input Parameters:
 16: + sname    - the name of a new user-defined creation routine
 17: - function - the creation routine itself

 19:   Level: developer

 21:   Note:
 22:   `TSTrajectoryRegister()` may be called multiple times to add several user-defined tses.

 24: .seealso: [](ch_ts), `TSTrajectoryRegisterAll()`
 25: @*/
 26: PetscErrorCode TSTrajectoryRegister(const char sname[], PetscErrorCode (*function)(TSTrajectory, TS))
 27: {
 28:   PetscFunctionBegin;
 29:   PetscCall(PetscFunctionListAdd(&TSTrajectoryList, sname, function));
 30:   PetscFunctionReturn(PETSC_SUCCESS);
 31: }

 33: /*@
 34:   TSTrajectorySet - Sets a vector of state in the trajectory object

 36:   Collective

 38:   Input Parameters:
 39: + tj      - the trajectory object
 40: . ts      - the time stepper object (optional)
 41: . stepnum - the step number
 42: . time    - the current time
 43: - X       - the current solution

 45:   Level: developer

 47:   Note:
 48:   Usually one does not call this routine, it is called automatically during `TSSolve()`

 50: .seealso: [](ch_ts), `TSTrajectorySetUp()`, `TSTrajectoryDestroy()`, `TSTrajectorySetType()`, `TSTrajectorySetVariableNames()`, `TSGetTrajectory()`, `TSTrajectoryGet()`, `TSTrajectoryGetVecs()`
 51: @*/
 52: PetscErrorCode TSTrajectorySet(TSTrajectory tj, TS ts, PetscInt stepnum, PetscReal time, Vec X)
 53: {
 54:   PetscFunctionBegin;
 55:   if (!tj) PetscFunctionReturn(PETSC_SUCCESS);
 61:   PetscCheck(tj->setupcalled, PetscObjectComm((PetscObject)tj), PETSC_ERR_ORDER, "TSTrajectorySetUp should be called first");
 62:   if (tj->monitor) PetscCall(PetscViewerASCIIPrintf(tj->monitor, "TSTrajectorySet: stepnum %" PetscInt_FMT ", time %g (stages %" PetscInt_FMT ")\n", stepnum, (double)time, (PetscInt)!tj->solution_only));
 63:   PetscCall(PetscLogEventBegin(TSTrajectory_Set, tj, ts, 0, 0));
 64:   PetscUseTypeMethod(tj, set, ts, stepnum, time, X);
 65:   PetscCall(PetscLogEventEnd(TSTrajectory_Set, tj, ts, 0, 0));
 66:   if (tj->usehistory) PetscCall(TSHistoryUpdate(tj->tsh, stepnum, time));
 67:   if (tj->lag.caching) tj->lag.Udotcached.time = PETSC_MIN_REAL;
 68:   PetscFunctionReturn(PETSC_SUCCESS);
 69: }

 71: /*@
 72:   TSTrajectoryGetNumSteps - Return the number of steps registered in the `TSTrajectory` via `TSTrajectorySet()`.

 74:   Not Collective.

 76:   Input Parameter:
 77: . tj - the trajectory object

 79:   Output Parameter:
 80: . steps - the number of steps

 82:   Level: developer

 84: .seealso: [](ch_ts), `TS`, `TSTrajectorySet()`
 85: @*/
 86: PetscErrorCode TSTrajectoryGetNumSteps(TSTrajectory tj, PetscInt *steps)
 87: {
 88:   PetscFunctionBegin;
 90:   PetscAssertPointer(steps, 2);
 91:   PetscCall(TSHistoryGetNumSteps(tj->tsh, steps));
 92:   PetscFunctionReturn(PETSC_SUCCESS);
 93: }

 95: /*@
 96:   TSTrajectoryGet - Updates the solution vector of a time stepper object by querying the `TSTrajectory`

 98:   Collective

100:   Input Parameters:
101: + tj      - the trajectory object
102: . ts      - the time stepper object
103: - stepnum - the step number

105:   Output Parameter:
106: . time - the time associated with the step number

108:   Level: developer

110:   Note:
111:   Usually one does not call this routine, it is called automatically during `TSSolve()`

113: .seealso: [](ch_ts), `TS`, `TSSolve()`, `TSTrajectorySetUp()`, `TSTrajectoryDestroy()`, `TSTrajectorySetType()`, `TSTrajectorySetVariableNames()`, `TSGetTrajectory()`, `TSTrajectorySet()`, `TSTrajectoryGetVecs()`, `TSGetSolution()`
114: @*/
115: PetscErrorCode TSTrajectoryGet(TSTrajectory tj, TS ts, PetscInt stepnum, PetscReal *time)
116: {
117:   PetscFunctionBegin;
118:   PetscCheck(tj, PetscObjectComm((PetscObject)ts), PETSC_ERR_ARG_WRONGSTATE, "TS solver did not save trajectory");
122:   PetscAssertPointer(time, 4);
123:   PetscCheck(tj->setupcalled, PetscObjectComm((PetscObject)tj), PETSC_ERR_ORDER, "TSTrajectorySetUp should be called first");
124:   PetscCheck(stepnum >= 0, PetscObjectComm((PetscObject)tj), PETSC_ERR_PLIB, "Requesting negative step number");
125:   if (tj->monitor) {
126:     PetscCall(PetscViewerASCIIPrintf(tj->monitor, "TSTrajectoryGet: stepnum %" PetscInt_FMT ", stages %" PetscInt_FMT "\n", stepnum, (PetscInt)!tj->solution_only));
127:     PetscCall(PetscViewerFlush(tj->monitor));
128:   }
129:   PetscCall(PetscLogEventBegin(TSTrajectory_Get, tj, ts, 0, 0));
130:   PetscUseTypeMethod(tj, get, ts, stepnum, time);
131:   PetscCall(PetscLogEventEnd(TSTrajectory_Get, tj, ts, 0, 0));
132:   PetscFunctionReturn(PETSC_SUCCESS);
133: }

135: /*@
136:   TSTrajectoryGetVecs - Reconstructs the vector of state and its time derivative using information from the `TSTrajectory` and, possibly, from the `TS`

138:   Collective

140:   Input Parameters:
141: + tj      - the trajectory object
142: . ts      - the time stepper object (optional)
143: - stepnum - the requested step number

145:   Output Parameters:
146: + time - On input time for the step if step number is `PETSC_DECIDE`, on output the time associated with the step number
147: . U    - state vector (can be `NULL`)
148: - Udot - time derivative of state vector (can be `NULL`)

150:   Level: developer

152:   Notes:
153:   If the step number is `PETSC_DECIDE`, the time argument is used to inquire the trajectory.
154:   If the requested time does not match any in the trajectory, Lagrangian interpolations are returned.

156: .seealso: [](ch_ts), `TS`, `TSTrajectory`, `TSTrajectorySetUp()`, `TSTrajectoryDestroy()`, `TSTrajectorySetType()`, `TSTrajectorySetVariableNames()`, `TSGetTrajectory()`, `TSTrajectorySet()`, `TSTrajectoryGet()`
157: @*/
158: PetscErrorCode TSTrajectoryGetVecs(TSTrajectory tj, TS ts, PetscInt stepnum, PetscReal *time, Vec U, Vec Udot)
159: {
160:   PetscFunctionBegin;
161:   PetscCheck(tj, PetscObjectComm((PetscObject)ts), PETSC_ERR_ARG_WRONGSTATE, "TS solver did not save trajectory");
165:   PetscAssertPointer(time, 4);
168:   if (!U && !Udot) PetscFunctionReturn(PETSC_SUCCESS);
169:   PetscCheck(tj->setupcalled, PetscObjectComm((PetscObject)tj), PETSC_ERR_ORDER, "TSTrajectorySetUp should be called first");
170:   PetscCall(PetscLogEventBegin(TSTrajectory_GetVecs, tj, ts, 0, 0));
171:   if (tj->monitor) {
172:     PetscInt pU, pUdot;
173:     pU    = U ? 1 : 0;
174:     pUdot = Udot ? 1 : 0;
175:     PetscCall(PetscViewerASCIIPrintf(tj->monitor, "Requested by GetVecs %" PetscInt_FMT " %" PetscInt_FMT ": stepnum %" PetscInt_FMT ", time %g\n", pU, pUdot, stepnum, (double)*time));
176:     PetscCall(PetscViewerFlush(tj->monitor));
177:   }
178:   if (U && tj->lag.caching) {
179:     VecState  state;
180:     PetscBool same;

182:     PetscCall(VecGetState(U, &state));
183:     PetscCall(VecStateCompare(state, tj->lag.Ucached.state, &same));
184:     if (stepnum == PETSC_DECIDE) {
185:       if (same && *time == tj->lag.Ucached.time) U = NULL;
186:     } else {
187:       if (same && stepnum == tj->lag.Ucached.step) U = NULL;
188:     }
189:     if (tj->monitor && !U) {
190:       PetscCall(PetscViewerASCIIPushTab(tj->monitor));
191:       PetscCall(PetscViewerASCIIPrintf(tj->monitor, "State vector cached\n"));
192:       PetscCall(PetscViewerASCIIPopTab(tj->monitor));
193:       PetscCall(PetscViewerFlush(tj->monitor));
194:     }
195:   }
196:   if (Udot && tj->lag.caching) {
197:     VecState  state;
198:     PetscBool same;

200:     PetscCall(VecGetState(Udot, &state));
201:     PetscCall(VecStateCompare(state, tj->lag.Udotcached.state, &same));
202:     if (stepnum == PETSC_DECIDE) {
203:       if (same && *time == tj->lag.Udotcached.time) Udot = NULL;
204:     } else {
205:       if (same && stepnum == tj->lag.Udotcached.step) Udot = NULL;
206:     }
207:     if (tj->monitor && !Udot) {
208:       PetscCall(PetscViewerASCIIPushTab(tj->monitor));
209:       PetscCall(PetscViewerASCIIPrintf(tj->monitor, "Derivative vector cached\n"));
210:       PetscCall(PetscViewerASCIIPopTab(tj->monitor));
211:       PetscCall(PetscViewerFlush(tj->monitor));
212:     }
213:   }
214:   if (!U && !Udot) {
215:     PetscCall(PetscLogEventEnd(TSTrajectory_GetVecs, tj, ts, 0, 0));
216:     PetscFunctionReturn(PETSC_SUCCESS);
217:   }

219:   if (stepnum == PETSC_DECIDE || Udot) { /* reverse search for requested time in TSHistory */
220:     if (tj->monitor) PetscCall(PetscViewerASCIIPushTab(tj->monitor));
221:     /* cached states will be updated in the function */
222:     PetscCall(TSTrajectoryReconstruct_Private(tj, ts, *time, U, Udot));
223:     if (tj->monitor) {
224:       PetscCall(PetscViewerASCIIPopTab(tj->monitor));
225:       PetscCall(PetscViewerFlush(tj->monitor));
226:     }
227:   } else if (U) { /* we were asked to load from stepnum, use TSTrajectoryGet */
228:     TS  fakets = ts;
229:     Vec U2;

231:     /* use a fake TS if ts is missing */
232:     if (!ts) {
233:       PetscCall(PetscObjectQuery((PetscObject)tj, "__fake_ts", (PetscObject *)&fakets));
234:       if (!fakets) {
235:         PetscCall(TSCreate(PetscObjectComm((PetscObject)tj), &fakets));
236:         PetscCall(PetscObjectCompose((PetscObject)tj, "__fake_ts", (PetscObject)fakets));
237:         PetscCall(PetscObjectDereference((PetscObject)fakets));
238:         PetscCall(VecDuplicate(U, &U2));
239:         PetscCall(TSSetSolution(fakets, U2));
240:         PetscCall(PetscObjectDereference((PetscObject)U2));
241:       }
242:     }
243:     PetscCall(TSTrajectoryGet(tj, fakets, stepnum, time));
244:     PetscCall(TSGetSolution(fakets, &U2));
245:     PetscCall(VecCopy(U2, U));
246:     PetscCall(VecGetState(U, &tj->lag.Ucached.state));
247:     tj->lag.Ucached.time = *time;
248:     tj->lag.Ucached.step = stepnum;
249:   }
250:   PetscCall(PetscLogEventEnd(TSTrajectory_GetVecs, tj, ts, 0, 0));
251:   PetscFunctionReturn(PETSC_SUCCESS);
252: }

254: /*@
255:   TSTrajectoryViewFromOptions - View a `TSTrajectory` based on values in the options database

257:   Collective

259:   Input Parameters:
260: + A    - the `TSTrajectory` context
261: . obj  - optional object that provides prefix used for option name, pass `NULL` to use the options prefix of `A`
262: - name - command line option

264:   Options Database Key:
265: . -name viewer_specification - See `PetscOptionsCreateViewer()` for the values of `viewer_specification`

267:   Level: intermediate

269:   Note:
270:   This checks the options database, creates the viewer on-the-fly, uses it and then destroys it. Hence it should not be called in heavily used routines,
271:   rather `PetscOptionsCreateViewer()` should be used to construct the viewer once which can then be utilized in the heavily used routine.

273: .seealso: [](ch_ts), `TSTrajectory`, `TSTrajectoryView()`, `PetscObjectViewFromOptions()`, `TSTrajectoryCreate()`, `PetscOptionsCreateViewer()`
274: @*/
275: PetscErrorCode TSTrajectoryViewFromOptions(TSTrajectory A, PetscObject obj, const char name[])
276: {
277:   PetscFunctionBegin;
279:   PetscCall(PetscObjectViewFromOptions((PetscObject)A, obj, name));
280:   PetscFunctionReturn(PETSC_SUCCESS);
281: }

283: /*@
284:   TSTrajectoryView - Prints information about the trajectory object

286:   Collective

288:   Input Parameters:
289: + tj     - the `TSTrajectory` context obtained from `TSTrajectoryCreate()`
290: - viewer - visualization context

292:   Options Database Key:
293: . -ts_trajectory_view - calls `TSTrajectoryView()` at end of `TSAdjointStep()`

295:   Level: developer

297:   Notes:
298:   The available visualization contexts include
299: +     `PETSC_VIEWER_STDOUT_SELF` - standard output (default)
300: -     `PETSC_VIEWER_STDOUT_WORLD` - synchronized standard
301:   output where only the first processor opens
302:   the file.  All other processors send their
303:   data to the first processor to print.

305:   The user can open an alternative visualization context with
306:   `PetscViewerASCIIOpen()` - output to a specified file.

308: .seealso: [](ch_ts), `TS`, `TSTrajectory`, `PetscViewer`, `PetscViewerASCIIOpen()`
309: @*/
310: PetscErrorCode TSTrajectoryView(TSTrajectory tj, PetscViewer viewer)
311: {
312:   PetscBool isascii;

314:   PetscFunctionBegin;
316:   if (!viewer) PetscCall(PetscViewerASCIIGetStdout(PetscObjectComm((PetscObject)tj), &viewer));
318:   PetscCheckSameComm(tj, 1, viewer, 2);

320:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERASCII, &isascii));
321:   if (isascii) {
322:     PetscCall(PetscObjectPrintClassNamePrefixType((PetscObject)tj, viewer));
323:     PetscCall(PetscViewerASCIIPrintf(viewer, "  total number of recomputations for adjoint calculation = %" PetscInt_FMT "\n", tj->recomps));
324:     PetscCall(PetscViewerASCIIPrintf(viewer, "  disk checkpoint reads = %" PetscInt_FMT "\n", tj->diskreads));
325:     PetscCall(PetscViewerASCIIPrintf(viewer, "  disk checkpoint writes = %" PetscInt_FMT "\n", tj->diskwrites));
326:     PetscCall(PetscViewerASCIIPushTab(viewer));
327:     PetscTryTypeMethod(tj, view, viewer);
328:     PetscCall(PetscViewerASCIIPopTab(viewer));
329:   }
330:   PetscFunctionReturn(PETSC_SUCCESS);
331: }

333: /*@
334:   TSTrajectorySetVariableNames - Sets the name of each component in the solution vector so that it may be saved with the trajectory

336:   Collective

338:   Input Parameters:
339: + ctx   - the trajectory context
340: - names - the names of the components, final string must be `NULL`

342:   Level: intermediate

344:   Fortran Notes:
345:   Fortran interface is not possible because of the string array argument

347: .seealso: [](ch_ts), `TSTrajectory`, `TSGetTrajectory()`
348: @*/
349: PetscErrorCode TSTrajectorySetVariableNames(TSTrajectory ctx, const char *const *names)
350: {
351:   PetscFunctionBegin;
353:   PetscAssertPointer(names, 2);
354:   PetscCall(PetscStrArrayDestroy(&ctx->names));
355:   PetscCall(PetscStrArrayallocpy(names, &ctx->names));
356:   PetscFunctionReturn(PETSC_SUCCESS);
357: }

359: /*@
360:   TSTrajectorySetTransform - Solution vector will be transformed by provided function before being saved to disk

362:   Collective

364:   Input Parameters:
365: + tj        - the `TSTrajectory` context
366: . transform - the transform function
367: . destroy   - function to destroy the optional context
368: - tctx      - optional context used by transform function

370:   Level: intermediate

372: .seealso: [](ch_ts), `TSTrajectorySetVariableNames()`, `TSTrajectory`, `TSMonitorLGSetTransform()`
373: @*/
374: PetscErrorCode TSTrajectorySetTransform(TSTrajectory tj, PetscErrorCode (*transform)(void *, Vec, Vec *), PetscCtxDestroyFn *destroy, void *tctx)
375: {
376:   PetscFunctionBegin;
378:   tj->transform        = transform;
379:   tj->transformdestroy = destroy;
380:   tj->transformctx     = tctx;
381:   PetscFunctionReturn(PETSC_SUCCESS);
382: }

384: /*@
385:   TSTrajectoryCreate - This function creates an empty trajectory object used to store the time dependent solution of an ODE/DAE

387:   Collective

389:   Input Parameter:
390: . comm - the communicator

392:   Output Parameter:
393: . tj - the trajectory object

395:   Level: developer

397:   Notes:
398:   Usually one does not call this routine, it is called automatically when one calls `TSSetSaveTrajectory()`.

400: .seealso: [](ch_ts), `TS`, `TSTrajectory`, `TSTrajectorySetUp()`, `TSTrajectoryDestroy()`, `TSTrajectorySetType()`, `TSTrajectorySetVariableNames()`, `TSGetTrajectory()`, `TSTrajectorySetKeepFiles()`
401: @*/
402: PetscErrorCode TSTrajectoryCreate(MPI_Comm comm, TSTrajectory *tj)
403: {
404:   TSTrajectory t;

406:   PetscFunctionBegin;
407:   PetscAssertPointer(tj, 2);
408:   PetscCall(TSInitializePackage());

410:   PetscCall(PetscHeaderCreate(t, TSTRAJECTORY_CLASSID, "TSTrajectory", "Time stepping", "TS", comm, TSTrajectoryDestroy, TSTrajectoryView));
411:   t->setupcalled = PETSC_FALSE;
412:   PetscCall(TSHistoryCreate(comm, &t->tsh));
413:   t->lag.order           = 1;
414:   t->lag.L               = NULL;
415:   t->lag.T               = NULL;
416:   t->lag.W               = NULL;
417:   t->lag.WW              = NULL;
418:   t->lag.TW              = NULL;
419:   t->lag.TT              = NULL;
420:   t->lag.caching         = PETSC_TRUE;
421:   t->lag.Ucached.time    = PETSC_MIN_REAL;
422:   t->lag.Ucached.step    = PETSC_INT_MAX;
423:   t->lag.Udotcached.time = PETSC_MIN_REAL;
424:   t->lag.Udotcached.step = PETSC_INT_MAX;
425:   t->adjoint_solve_mode  = PETSC_TRUE;
426:   t->solution_only       = PETSC_FALSE;
427:   t->keepfiles           = PETSC_FALSE;
428:   t->usehistory          = PETSC_TRUE;
429:   *tj                    = t;
430:   PetscCall(VecStateInvalidate(t->lag.Ucached.state));
431:   PetscCall(VecStateInvalidate(t->lag.Udotcached.state));
432:   PetscCall(TSTrajectorySetFiletemplate(t, "TS-%06" PetscInt_FMT ".bin"));
433:   PetscFunctionReturn(PETSC_SUCCESS);
434: }

436: /*@
437:   TSTrajectorySetType - Sets the storage method to be used as in a trajectory

439:   Collective

441:   Input Parameters:
442: + tj   - the `TSTrajectory` context
443: . ts   - the `TS` context
444: - type - a known method

446:   Options Database Key:
447: . -ts_trajectory_type (basic|singlefile|memory|visualization) - Sets the trajectory type

449:   Level: developer

451:   Developer Notes:
452:   Why does this option require access to the `TS`

454: .seealso: [](ch_ts), `TSTrajectory`, `TSTrajectoryType`, `TS`, `TSTrajectoryCreate()`, `TSTrajectorySetFromOptions()`, `TSTrajectoryDestroy()`, `TSTrajectoryGetType()`
455: @*/
456: PetscErrorCode TSTrajectorySetType(TSTrajectory tj, TS ts, TSTrajectoryType type)
457: {
458:   PetscErrorCode (*r)(TSTrajectory, TS);
459:   PetscBool match;

461:   PetscFunctionBegin;
463:   PetscCall(PetscObjectTypeCompare((PetscObject)tj, type, &match));
464:   if (match) PetscFunctionReturn(PETSC_SUCCESS);

466:   PetscCall(PetscFunctionListFind(TSTrajectoryList, type, &r));
467:   PetscCheck(r, PetscObjectComm((PetscObject)tj), PETSC_ERR_ARG_UNKNOWN_TYPE, "Unknown TSTrajectory type: %s", type);
468:   PetscTryTypeMethod(tj, destroy);
469:   tj->ops->destroy = NULL;
470:   PetscCall(PetscMemzero(tj->ops, sizeof(*tj->ops)));

472:   PetscCall(PetscObjectChangeTypeName((PetscObject)tj, type));
473:   PetscCall((*r)(tj, ts));
474:   PetscFunctionReturn(PETSC_SUCCESS);
475: }

477: /*@
478:   TSTrajectoryGetType - Gets the trajectory type

480:   Collective

482:   Input Parameters:
483: + tj - the `TSTrajectory` context
484: - ts - the `TS` context

486:   Output Parameter:
487: . type - a known method

489:   Level: developer

491: .seealso: [](ch_ts), `TS`, `TSTrajectory`, `TSTrajectoryCreate()`, `TSTrajectorySetFromOptions()`, `TSTrajectoryDestroy()`, `TSTrajectorySetType()`
492: @*/
493: PetscErrorCode TSTrajectoryGetType(TSTrajectory tj, TS ts, TSTrajectoryType *type)
494: {
495:   PetscFunctionBegin;
497:   if (type) *type = ((PetscObject)tj)->type_name;
498:   PetscFunctionReturn(PETSC_SUCCESS);
499: }

501: PETSC_EXTERN PetscErrorCode TSTrajectoryCreate_Basic(TSTrajectory, TS);
502: PETSC_EXTERN PetscErrorCode TSTrajectoryCreate_Singlefile(TSTrajectory, TS);
503: PETSC_EXTERN PetscErrorCode TSTrajectoryCreate_Memory(TSTrajectory, TS);
504: PETSC_EXTERN PetscErrorCode TSTrajectoryCreate_Visualization(TSTrajectory, TS);

506: /*@
507:   TSTrajectoryRegisterAll - Registers all of the `TSTrajectory` storage schecmes in the `TS` package.

509:   Not Collective

511:   Level: developer

513: .seealso: [](ch_ts), `TSTrajectory`, `TSTrajectoryRegister()`
514: @*/
515: PetscErrorCode TSTrajectoryRegisterAll(void)
516: {
517:   PetscFunctionBegin;
518:   if (TSTrajectoryRegisterAllCalled) PetscFunctionReturn(PETSC_SUCCESS);
519:   TSTrajectoryRegisterAllCalled = PETSC_TRUE;

521:   PetscCall(TSTrajectoryRegister(TSTRAJECTORYBASIC, TSTrajectoryCreate_Basic));
522:   PetscCall(TSTrajectoryRegister(TSTRAJECTORYSINGLEFILE, TSTrajectoryCreate_Singlefile));
523:   PetscCall(TSTrajectoryRegister(TSTRAJECTORYMEMORY, TSTrajectoryCreate_Memory));
524:   PetscCall(TSTrajectoryRegister(TSTRAJECTORYVISUALIZATION, TSTrajectoryCreate_Visualization));
525:   PetscFunctionReturn(PETSC_SUCCESS);
526: }

528: /*@
529:   TSTrajectoryReset - Resets a trajectory context

531:   Collective

533:   Input Parameter:
534: . tj - the `TSTrajectory` context obtained from `TSGetTrajectory()`

536:   Level: developer

538: .seealso: [](ch_ts), `TS`, `TSTrajectory`, `TSTrajectoryCreate()`, `TSTrajectorySetUp()`
539: @*/
540: PetscErrorCode TSTrajectoryReset(TSTrajectory tj)
541: {
542:   PetscFunctionBegin;
543:   if (!tj) PetscFunctionReturn(PETSC_SUCCESS);
545:   PetscTryTypeMethod(tj, reset);
546:   PetscCall(PetscFree(tj->dirfiletemplate));
547:   PetscCall(TSHistoryDestroy(&tj->tsh));
548:   PetscCall(TSHistoryCreate(PetscObjectComm((PetscObject)tj), &tj->tsh));
549:   tj->setupcalled = PETSC_FALSE;
550:   PetscFunctionReturn(PETSC_SUCCESS);
551: }

553: /*@
554:   TSTrajectoryDestroy - Destroys a trajectory context

556:   Collective

558:   Input Parameter:
559: . tj - the `TSTrajectory` context obtained from `TSTrajectoryCreate()`

561:   Level: developer

563: .seealso: [](ch_ts), `TSTrajectory`, `TSTrajectoryCreate()`, `TSTrajectorySetUp()`
564: @*/
565: PetscErrorCode TSTrajectoryDestroy(TSTrajectory *tj)
566: {
567:   PetscFunctionBegin;
568:   if (!*tj) PetscFunctionReturn(PETSC_SUCCESS);
570:   if (--((PetscObject)*tj)->refct > 0) {
571:     *tj = NULL;
572:     PetscFunctionReturn(PETSC_SUCCESS);
573:   }

575:   PetscCall(TSTrajectoryReset(*tj));
576:   PetscCall(TSHistoryDestroy(&(*tj)->tsh));
577:   PetscCall(VecDestroyVecs((*tj)->lag.order + 1, &(*tj)->lag.W));
578:   PetscCall(PetscFree5((*tj)->lag.L, (*tj)->lag.T, (*tj)->lag.WW, (*tj)->lag.TT, (*tj)->lag.TW));
579:   PetscCall(VecDestroy(&(*tj)->U));
580:   PetscCall(VecDestroy(&(*tj)->Udot));

582:   if ((*tj)->transformdestroy) PetscCall((*(*tj)->transformdestroy)(&(*tj)->transformctx));
583:   PetscTryTypeMethod(*tj, destroy);
584:   if (!(*tj)->keepfiles) {
585:     PetscMPIInt rank;
586:     MPI_Comm    comm;

588:     PetscCall(PetscObjectGetComm((PetscObject)*tj, &comm));
589:     PetscCallMPI(MPI_Comm_rank(comm, &rank));
590:     if (rank == 0 && (*tj)->dirname) { /* we own the directory, so we run PetscRMTree on it */
591:       PetscCall(PetscRMTree((*tj)->dirname));
592:     }
593:   }
594:   PetscCall(PetscStrArrayDestroy(&(*tj)->names));
595:   PetscCall(PetscFree((*tj)->dirname));
596:   PetscCall(PetscFree((*tj)->filetemplate));
597:   PetscCall(PetscHeaderDestroy(tj));
598:   PetscFunctionReturn(PETSC_SUCCESS);
599: }

601: /*
602:   TSTrajectorySetTypeFromOptions_Private - Sets the type of `TSTrajectory` from user options.

604:   Collective

606:   Input Parameter:
607: + tj - the `TSTrajectory` context
608: - ts - the TS context

610:   Options Database Key:
611: . -ts_trajectory_type (basic|memory|singlefile|visualization) - the method of storing the trajectory

613:   Level: developer

615: .seealso: [](ch_ts), `TSTrajectory`, `TSTrajectoryType`, `TSTrajectorySetFromOptions()`, `TSTrajectorySetType()`
616: */
617: static PetscErrorCode TSTrajectorySetTypeFromOptions_Private(PetscOptionItems PetscOptionsObject, TSTrajectory tj, TS ts)
618: {
619:   PetscBool   opt;
620:   const char *defaultType;
621:   char        typeName[256];

623:   PetscFunctionBegin;
624:   if (((PetscObject)tj)->type_name) defaultType = ((PetscObject)tj)->type_name;
625:   else defaultType = TSTRAJECTORYBASIC;

627:   PetscCall(TSTrajectoryRegisterAll());
628:   PetscCall(PetscOptionsFList("-ts_trajectory_type", "TSTrajectory method", "TSTrajectorySetType", TSTrajectoryList, defaultType, typeName, sizeof(typeName), &opt));
629:   if (opt) {
630:     PetscCall(TSTrajectorySetType(tj, ts, typeName));
631:   } else {
632:     PetscCall(TSTrajectorySetType(tj, ts, defaultType));
633:   }
634:   PetscFunctionReturn(PETSC_SUCCESS);
635: }

637: /*@
638:   TSTrajectorySetUseHistory - Use `TSHistory` in `TSTrajectory`

640:   Collective

642:   Input Parameters:
643: + tj  - the `TSTrajectory` context
644: - flg - `PETSC_TRUE` to save, `PETSC_FALSE` to disable

646:   Options Database Key:
647: . -ts_trajectory_use_history - have it use `TSHistory`

649:   Level: advanced

651: .seealso: [](ch_ts), `TSTrajectory`, `TSTrajectoryCreate()`, `TSTrajectoryDestroy()`, `TSTrajectorySetUp()`
652: @*/
653: PetscErrorCode TSTrajectorySetUseHistory(TSTrajectory tj, PetscBool flg)
654: {
655:   PetscFunctionBegin;
658:   tj->usehistory = flg;
659:   PetscFunctionReturn(PETSC_SUCCESS);
660: }

662: /*@
663:   TSTrajectorySetMonitor - Monitor the schedules generated by the `TSTrajectory` checkpointing controller

665:   Collective

667:   Input Parameters:
668: + tj  - the `TSTrajectory` context
669: - flg - `PETSC_TRUE` to active a monitor, `PETSC_FALSE` to disable

671:   Options Database Key:
672: . -ts_trajectory_monitor - print `TSTrajectory` information

674:   Level: developer

676: .seealso: [](ch_ts), `TSTrajectory`, `TSTrajectoryCreate()`, `TSTrajectoryDestroy()`, `TSTrajectorySetUp()`
677: @*/
678: PetscErrorCode TSTrajectorySetMonitor(TSTrajectory tj, PetscBool flg)
679: {
680:   PetscFunctionBegin;
683:   if (flg) tj->monitor = PETSC_VIEWER_STDOUT_(PetscObjectComm((PetscObject)tj));
684:   else tj->monitor = NULL;
685:   PetscFunctionReturn(PETSC_SUCCESS);
686: }

688: /*@
689:   TSTrajectorySetKeepFiles - Keep the files generated by the `TSTrajectory` once the program is done

691:   Collective

693:   Input Parameters:
694: + tj  - the `TSTrajectory` context
695: - flg - `PETSC_TRUE` to save, `PETSC_FALSE` to disable

697:   Options Database Key:
698: . -ts_trajectory_keep_files - have it keep the files

700:   Level: advanced

702:   Note:
703:   By default the `TSTrajectory` used for adjoint computations, `TSTRAJECTORYBASIC`, removes the files it generates at the end of the run. This causes the files to be kept.

705: .seealso: [](ch_ts), `TSTrajectoryCreate()`, `TSTrajectoryDestroy()`, `TSTrajectorySetUp()`, `TSTrajectorySetMonitor()`
706: @*/
707: PetscErrorCode TSTrajectorySetKeepFiles(TSTrajectory tj, PetscBool flg)
708: {
709:   PetscFunctionBegin;
712:   tj->keepfiles = flg;
713:   PetscFunctionReturn(PETSC_SUCCESS);
714: }

716: /*@
717:   TSTrajectorySetDirname - Specify the name of the directory where `TSTrajectory` disk checkpoints are stored.

719:   Collective

721:   Input Parameters:
722: + tj      - the `TSTrajectory` context
723: - dirname - the directory name

725:   Options Database Key:
726: . -ts_trajectory_dirname - set the directory name

728:   Level: developer

730:   Notes:
731:   The final location of the files is determined by dirname/filetemplate where filetemplate was provided by `TSTrajectorySetFiletemplate()`

733:   If this is not called `TSTrajectory` selects a unique new name for the directory

735: .seealso: [](ch_ts), `TSTrajectory`, `TSTrajectorySetFiletemplate()`, `TSTrajectorySetUp()`
736: @*/
737: PetscErrorCode TSTrajectorySetDirname(TSTrajectory tj, const char dirname[])
738: {
739:   PetscBool flg;

741:   PetscFunctionBegin;
743:   PetscCall(PetscStrcmp(tj->dirname, dirname, &flg));
744:   PetscCheck(flg || !tj->dirfiletemplate, PetscObjectComm((PetscObject)tj), PETSC_ERR_ARG_WRONGSTATE, "Cannot set directoryname after TSTrajectory has been setup");
745:   PetscCall(PetscFree(tj->dirname));
746:   PetscCall(PetscStrallocpy(dirname, &tj->dirname));
747:   PetscFunctionReturn(PETSC_SUCCESS);
748: }

750: /*@
751:   TSTrajectorySetFiletemplate - Specify the name template for the files storing `TSTrajectory` checkpoints.

753:   Collective

755:   Input Parameters:
756: + tj           - the `TSTrajectory` context
757: - filetemplate - the template

759:   Options Database Key:
760: . -ts_trajectory_file_template - set the file name template

762:   Level: developer

764:   Notes:
765:   The name template should be of the form, for example filename-%06" PetscInt_FMT ".bin It should not begin with a leading /

767:   The final location of the files is determined by dirname/filetemplate where dirname was provided by `TSTrajectorySetDirname()`. The %06" PetscInt_FMT " is replaced by the
768:   timestep counter

770: .seealso: [](ch_ts), `TSTrajectory`, `TSTrajectorySetDirname()`, `TSTrajectorySetUp()`
771: @*/
772: PetscErrorCode TSTrajectorySetFiletemplate(TSTrajectory tj, const char filetemplate[])
773: {
774:   const char *ptr = NULL, *ptr2 = NULL;

776:   PetscFunctionBegin;
778:   PetscAssertPointer(filetemplate, 2);
779:   PetscCheck(!tj->dirfiletemplate, PetscObjectComm((PetscObject)tj), PETSC_ERR_ARG_WRONGSTATE, "Cannot set filetemplate after TSTrajectory has been setup");

781:   PetscCheck(filetemplate[0], PetscObjectComm((PetscObject)tj), PETSC_ERR_USER, "-ts_trajectory_file_template requires a file name template, e.g. filename-%%06" PetscInt_FMT ".bin");
782:   /* Do some cursory validation of the input. */
783:   PetscCall(PetscStrstr(filetemplate, "%", (char **)&ptr));
784:   PetscCheck(ptr, PetscObjectComm((PetscObject)tj), PETSC_ERR_USER, "-ts_trajectory_file_template requires a file name template, e.g. filename-%%06" PetscInt_FMT ".bin");
785:   for (ptr++; ptr && *ptr; ptr++) {
786:     PetscCall(PetscStrchr(PetscInt_FMT "DiouxX", *ptr, (char **)&ptr2));
787:     PetscCheck(ptr2 || (*ptr >= '0' && *ptr <= '9'), PetscObjectComm((PetscObject)tj), PETSC_ERR_USER, "Invalid file template argument to -ts_trajectory_file_template, should look like filename-%%06" PetscInt_FMT ".bin");
788:     if (ptr2) break;
789:   }
790:   PetscCall(PetscFree(tj->filetemplate));
791:   PetscCall(PetscStrallocpy(filetemplate, &tj->filetemplate));
792:   PetscFunctionReturn(PETSC_SUCCESS);
793: }

795: /*@
796:   TSTrajectorySetFromOptions - Sets various `TSTrajectory` parameters from user options.

798:   Collective

800:   Input Parameters:
801: + tj - the `TSTrajectory` context obtained from `TSGetTrajectory()`
802: - ts - the `TS` context

804:   Options Database Keys:
805: + -ts_trajectory_type (basic|singlefile|memory|visualization) - how to manage the trajectory
806: . -ts_trajectory_keep_files (true|false)                      - keep the files generated by the code after the program ends. This is true by default for singlefile and visualization
807: - -ts_trajectory_monitor                                      - print `TSTrajectory` information

809:   Level: developer

811:   Note:
812:   This is not normally called directly by users

814: .seealso: [](ch_ts), `TSTrajectory`, `TSSetSaveTrajectory()`, `TSTrajectorySetUp()`
815: @*/
816: PetscErrorCode TSTrajectorySetFromOptions(TSTrajectory tj, TS ts)
817: {
818:   PetscBool set, flg;
819:   char      dirname[PETSC_MAX_PATH_LEN], filetemplate[PETSC_MAX_PATH_LEN];

821:   PetscFunctionBegin;
824:   PetscObjectOptionsBegin((PetscObject)tj);
825:   PetscCall(TSTrajectorySetTypeFromOptions_Private(PetscOptionsObject, tj, ts));
826:   PetscCall(PetscOptionsBool("-ts_trajectory_use_history", "Turn on/off usage of TSHistory", NULL, tj->usehistory, &tj->usehistory, NULL));
827:   PetscCall(PetscOptionsBool("-ts_trajectory_monitor", "Print checkpointing schedules", "TSTrajectorySetMonitor", tj->monitor ? PETSC_TRUE : PETSC_FALSE, &flg, &set));
828:   if (set) PetscCall(TSTrajectorySetMonitor(tj, flg));
829:   PetscCall(PetscOptionsInt("-ts_trajectory_reconstruction_order", "Interpolation order for reconstruction", NULL, tj->lag.order, &tj->lag.order, NULL));
830:   PetscCall(PetscOptionsBool("-ts_trajectory_reconstruction_caching", "Turn on/off caching of TSTrajectoryGetVecs input", NULL, tj->lag.caching, &tj->lag.caching, NULL));
831:   PetscCall(PetscOptionsBool("-ts_trajectory_adjointmode", "Instruct the trajectory that will be used in a TSAdjointSolve()", NULL, tj->adjoint_solve_mode, &tj->adjoint_solve_mode, NULL));
832:   PetscCall(PetscOptionsBool("-ts_trajectory_solution_only", "Checkpoint solution only", "TSTrajectorySetSolutionOnly", tj->solution_only, &tj->solution_only, NULL));
833:   PetscCall(PetscOptionsBool("-ts_trajectory_keep_files", "Keep any trajectory files generated during the run", "TSTrajectorySetKeepFiles", tj->keepfiles, &flg, &set));
834:   if (set) PetscCall(TSTrajectorySetKeepFiles(tj, flg));

836:   PetscCall(PetscOptionsString("-ts_trajectory_dirname", "Directory name for TSTrajectory file", "TSTrajectorySetDirname", NULL, dirname, sizeof(dirname) - 14, &set));
837:   if (set) PetscCall(TSTrajectorySetDirname(tj, dirname));

839:   PetscCall(PetscOptionsString("-ts_trajectory_file_template", "Template for TSTrajectory file name, use filename-%06" PetscInt_FMT ".bin", "TSTrajectorySetFiletemplate", NULL, filetemplate, sizeof(filetemplate), &set));
840:   if (set) PetscCall(TSTrajectorySetFiletemplate(tj, filetemplate));

842:   /* Handle specific TSTrajectory options */
843:   PetscTryTypeMethod(tj, setfromoptions, PetscOptionsObject);
844:   PetscOptionsEnd();
845:   PetscFunctionReturn(PETSC_SUCCESS);
846: }

848: /*@
849:   TSTrajectorySetUp - Sets up the internal data structures, e.g. stacks, for the later use
850:   of a `TS` `TSTrajectory`.

852:   Collective

854:   Input Parameters:
855: + tj - the `TSTrajectory` context
856: - ts - the TS context obtained from `TSCreate()`

858:   Level: developer

860: .seealso: [](ch_ts), `TSTrajectory`, `TSSetSaveTrajectory()`, `TSTrajectoryCreate()`, `TSTrajectoryDestroy()`
861: @*/
862: PetscErrorCode TSTrajectorySetUp(TSTrajectory tj, TS ts)
863: {
864:   size_t s1, s2;

866:   PetscFunctionBegin;
867:   if (!tj) PetscFunctionReturn(PETSC_SUCCESS);
870:   if (tj->setupcalled) PetscFunctionReturn(PETSC_SUCCESS);

872:   PetscCall(PetscLogEventBegin(TSTrajectory_SetUp, tj, ts, 0, 0));
873:   if (!((PetscObject)tj)->type_name) PetscCall(TSTrajectorySetType(tj, ts, TSTRAJECTORYBASIC));
874:   PetscTryTypeMethod(tj, setup, ts);

876:   tj->setupcalled = PETSC_TRUE;

878:   /* Set the counters to zero */
879:   tj->recomps    = 0;
880:   tj->diskreads  = 0;
881:   tj->diskwrites = 0;
882:   PetscCall(PetscStrlen(tj->dirname, &s1));
883:   PetscCall(PetscStrlen(tj->filetemplate, &s2));
884:   PetscCall(PetscFree(tj->dirfiletemplate));
885:   PetscCall(PetscMalloc((s1 + s2 + 10) * sizeof(char), &tj->dirfiletemplate));
886:   PetscCall(PetscSNPrintf(tj->dirfiletemplate, s1 + s2 + 10, "%s/%s", tj->dirname, tj->filetemplate));
887:   PetscCall(PetscLogEventEnd(TSTrajectory_SetUp, tj, ts, 0, 0));
888:   PetscFunctionReturn(PETSC_SUCCESS);
889: }

891: /*@
892:   TSTrajectorySetSolutionOnly - Tells the trajectory to store just the solution, and not any intermediate stage information

894:   Collective

896:   Input Parameters:
897: + tj            - the `TSTrajectory` context obtained with `TSGetTrajectory()`
898: - solution_only - the boolean flag

900:   Level: developer

902: .seealso: [](ch_ts), `TSTrajectory`, `TSSetSaveTrajectory()`, `TSTrajectoryCreate()`, `TSTrajectoryDestroy()`, `TSTrajectoryGetSolutionOnly()`
903: @*/
904: PetscErrorCode TSTrajectorySetSolutionOnly(TSTrajectory tj, PetscBool solution_only)
905: {
906:   PetscFunctionBegin;
909:   tj->solution_only = solution_only;
910:   PetscFunctionReturn(PETSC_SUCCESS);
911: }

913: /*@
914:   TSTrajectoryGetSolutionOnly - Gets the value set with `TSTrajectorySetSolutionOnly()`.

916:   Logically Collective

918:   Input Parameter:
919: . tj - the `TSTrajectory` context

921:   Output Parameter:
922: . solution_only - the boolean flag

924:   Level: developer

926: .seealso: [](ch_ts), `TSTrajectory`, `TSSetSaveTrajectory()`, `TSTrajectoryCreate()`, `TSTrajectoryDestroy()`, `TSTrajectorySetSolutionOnly()`
927: @*/
928: PetscErrorCode TSTrajectoryGetSolutionOnly(TSTrajectory tj, PetscBool *solution_only)
929: {
930:   PetscFunctionBegin;
932:   PetscAssertPointer(solution_only, 2);
933:   *solution_only = tj->solution_only;
934:   PetscFunctionReturn(PETSC_SUCCESS);
935: }

937: /*@
938:   TSTrajectoryGetUpdatedHistoryVecs - Get updated state and time-derivative history vectors.

940:   Collective

942:   Input Parameters:
943: + tj   - the `TSTrajectory` context
944: . ts   - the `TS` solver context
945: - time - the requested time

947:   Output Parameters:
948: + U    - state vector at given time (can be interpolated)
949: - Udot - time-derivative vector at given time (can be interpolated)

951:   Level: developer

953:   Notes:
954:   The vectors are interpolated if time does not match any time step stored in the `TSTrajectory()`. Pass NULL to not request a vector.

956:   This function differs from `TSTrajectoryGetVecs()` since the vectors obtained cannot be modified, and they need to be returned by
957:   calling `TSTrajectoryRestoreUpdatedHistoryVecs()`.

959: .seealso: [](ch_ts), `TSTrajectory`, `TSSetSaveTrajectory()`, `TSTrajectoryCreate()`, `TSTrajectoryDestroy()`, `TSTrajectoryRestoreUpdatedHistoryVecs()`, `TSTrajectoryGetVecs()`
960: @*/
961: PetscErrorCode TSTrajectoryGetUpdatedHistoryVecs(TSTrajectory tj, TS ts, PetscReal time, Vec *U, Vec *Udot)
962: {
963:   PetscFunctionBegin;
967:   if (U) PetscAssertPointer(U, 4);
968:   if (Udot) PetscAssertPointer(Udot, 5);
969:   if (U && !tj->U) {
970:     DM dm;

972:     PetscCall(TSGetDM(ts, &dm));
973:     PetscCall(DMCreateGlobalVector(dm, &tj->U));
974:   }
975:   if (Udot && !tj->Udot) {
976:     DM dm;

978:     PetscCall(TSGetDM(ts, &dm));
979:     PetscCall(DMCreateGlobalVector(dm, &tj->Udot));
980:   }
981:   PetscCall(TSTrajectoryGetVecs(tj, ts, PETSC_DECIDE, &time, U ? tj->U : NULL, Udot ? tj->Udot : NULL));
982:   if (U) {
983:     PetscCall(VecLockReadPush(tj->U));
984:     *U = tj->U;
985:   }
986:   if (Udot) {
987:     PetscCall(VecLockReadPush(tj->Udot));
988:     *Udot = tj->Udot;
989:   }
990:   PetscFunctionReturn(PETSC_SUCCESS);
991: }

993: /*@
994:   TSTrajectoryRestoreUpdatedHistoryVecs - Restores updated state and time-derivative history vectors obtained with `TSTrajectoryGetUpdatedHistoryVecs()`.

996:   Collective

998:   Input Parameters:
999: + tj   - the `TSTrajectory` context
1000: . U    - state vector at given time (can be interpolated)
1001: - Udot - time-derivative vector at given time (can be interpolated)

1003:   Level: developer

1005: .seealso: [](ch_ts), `TSTrajectory`, `TSTrajectoryGetUpdatedHistoryVecs()`
1006: @*/
1007: PetscErrorCode TSTrajectoryRestoreUpdatedHistoryVecs(TSTrajectory tj, Vec *U, Vec *Udot)
1008: {
1009:   PetscFunctionBegin;
1013:   PetscCheck(!U || *U == tj->U, PetscObjectComm((PetscObject)*U), PETSC_ERR_USER, "U was not obtained from TSTrajectoryGetUpdatedHistoryVecs()");
1014:   PetscCheck(!Udot || *Udot == tj->Udot, PetscObjectComm((PetscObject)*Udot), PETSC_ERR_USER, "Udot was not obtained from TSTrajectoryGetUpdatedHistoryVecs()");
1015:   if (U) {
1016:     PetscCall(VecLockReadPop(tj->U));
1017:     *U = NULL;
1018:   }
1019:   if (Udot) {
1020:     PetscCall(VecLockReadPop(tj->Udot));
1021:     *Udot = NULL;
1022:   }
1023:   PetscFunctionReturn(PETSC_SUCCESS);
1024: }