Actual source code: trajmemory.c

  1: #include <petsc/private/tsimpl.h>
  2: #include <petscsys.h>
  3: #if defined(PETSC_HAVE_REVOLVE)
  4: #include <revolve_c.h>

  6: /* Limit Revolve to 32-bits */
  7: #define PETSC_REVOLVE_INT_MAX  2147483647

  9: typedef int PetscRevolveInt;

 11: PETSC_STATIC_INLINE PetscErrorCode PetscRevolveIntCast(PetscInt a,PetscRevolveInt *b)
 12: {
 14: #if defined(PETSC_USE_64BIT_INDICES)
 15:   *b = 0;
 16:   if (a > PETSC_REVOLVE_INT_MAX) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Parameter is too large for Revolve, which is restricted to 32 bit integers");
 17: #endif
 18:   *b = (PetscRevolveInt)(a);
 19:   return(0);
 20: }
 21: #endif
 22: #if defined(PETSC_HAVE_CAMS)
 23: #include <offline_schedule.h>
 24: #endif

 26: PetscLogEvent TSTrajectory_DiskWrite, TSTrajectory_DiskRead;
 27: static PetscErrorCode TSTrajectorySet_Memory(TSTrajectory,TS,PetscInt,PetscReal,Vec);

 29: typedef enum {NONE,TWO_LEVEL_NOREVOLVE,TWO_LEVEL_REVOLVE,TWO_LEVEL_TWO_REVOLVE,REVOLVE_OFFLINE,REVOLVE_ONLINE,REVOLVE_MULTISTAGE,CAMS_OFFLINE} SchedulerType;

 31: typedef enum {UNSET=-1,SOLUTIONONLY=0,STAGESONLY=1,SOLUTION_STAGES=2} CheckpointType;

 33: typedef enum {TJ_REVOLVE, TJ_CAMS, TJ_PETSC} TSTrajectoryMemoryType;
 34: static const char *const TSTrajectoryMemoryTypes[] = {"REVOLVE","CAMS","PETSC","TSTrajectoryMemoryType","TJ_",NULL};

 36: #define HaveSolution(m) ((m) == SOLUTIONONLY || (m) == SOLUTION_STAGES)
 37: #define HaveStages(m)   ((m) == STAGESONLY || (m) == SOLUTION_STAGES)

 39: typedef struct _StackElement {
 40:   PetscInt       stepnum;
 41:   Vec            X;
 42:   Vec            *Y;
 43:   PetscReal      time;
 44:   PetscReal      timeprev; /* for no solution_only mode */
 45:   PetscReal      timenext; /* for solution_only mode */
 46:   CheckpointType cptype;
 47: } *StackElement;

 49: #if defined(PETSC_HAVE_REVOLVE)
 50: typedef struct _RevolveCTX {
 51:   PetscBool       reverseonestep;
 52:   PetscRevolveInt where;
 53:   PetscRevolveInt snaps_in;
 54:   PetscRevolveInt stepsleft;
 55:   PetscRevolveInt check;
 56:   PetscRevolveInt oldcapo;
 57:   PetscRevolveInt capo;
 58:   PetscRevolveInt fine;
 59:   PetscRevolveInt info;
 60: } RevolveCTX;
 61: #endif

 63: #if defined(PETSC_HAVE_CAMS)
 64: typedef struct _CAMSCTX {
 65:   PetscInt lastcheckpointstep;
 66:   PetscInt lastcheckpointtype;
 67:   PetscInt num_units_avail;
 68:   PetscInt endstep;
 69:   PetscInt num_stages;
 70:   PetscInt nextcheckpointstep;
 71:   PetscInt nextcheckpointtype; /* (0) solution only (1) stages (2) solution+stages */
 72:   PetscInt info;
 73: } CAMSCTX;
 74: #endif

 76: typedef struct _Stack {
 77:   PetscInt      stacksize;
 78:   PetscInt      top;
 79:   StackElement  *container;
 80:   PetscInt      nallocated;
 81:   PetscInt      numY;
 82:   PetscBool     solution_only;
 83:   PetscBool     use_dram;
 84: } Stack;

 86: typedef struct _DiskStack {
 87:   PetscInt  stacksize;
 88:   PetscInt  top;
 89:   PetscInt  *container;
 90: } DiskStack;

 92: typedef struct _TJScheduler {
 93:   SchedulerType stype;
 94:   TSTrajectoryMemoryType tj_memory_type;
 95: #if defined(PETSC_HAVE_REVOLVE)
 96:   RevolveCTX    *rctx,*rctx2;
 97:   PetscBool     use_online;
 98:   PetscInt      store_stride;
 99: #endif
100: #if defined(PETSC_HAVE_CAMS)
101:   CAMSCTX       *actx;
102: #endif
103:   PetscBool     recompute;
104:   PetscBool     skip_trajectory;
105:   PetscBool     save_stack;
106:   PetscInt      max_units_ram;  /* maximum checkpointing units in RAM */
107:   PetscInt      max_units_disk; /* maximum checkpointing units on disk */
108:   PetscInt      max_cps_ram;    /* maximum checkpoints in RAM */
109:   PetscInt      max_cps_disk;   /* maximum checkpoints on disk */
110:   PetscInt      stride;
111:   PetscInt      total_steps;    /* total number of steps */
112:   Stack         stack;
113:   DiskStack     diskstack;
114:   PetscViewer   viewer;
115: } TJScheduler;

117: static PetscErrorCode TurnForwardWithStepsize(TS ts,PetscReal nextstepsize)
118: {

122:   /* reverse the direction */
123:   TSSetTimeStep(ts,nextstepsize);
124:   return(0);
125: }

127: static PetscErrorCode TurnForward(TS ts)
128: {
129:   PetscReal      stepsize;

133:   /* reverse the direction */
134:   TSGetTimeStep(ts,&stepsize);
135:   TSSetTimeStep(ts,-stepsize);
136:   return(0);
137: }

139: static PetscErrorCode TurnBackward(TS ts)
140: {
141:   PetscReal      stepsize;

145:   if (!ts->trajectory->adjoint_solve_mode) return(0);
146:   /* reverse the direction */
147:   stepsize = ts->ptime_prev-ts->ptime;
148:   TSSetTimeStep(ts,stepsize);
149:   return(0);
150: }

152: static PetscErrorCode ElementCreate(TS ts,CheckpointType cptype,Stack *stack,StackElement *e)
153: {
154:   Vec            X;
155:   Vec            *Y;

159:   if (stack->top < stack->stacksize-1 && stack->container[stack->top+1]) {
160:     *e = stack->container[stack->top+1];
161:     if (HaveSolution(cptype) && !(*e)->X) {
162:       TSGetSolution(ts,&X);
163:       VecDuplicate(X,&(*e)->X);
164:     }
165:     if (cptype==1 && (*e)->X) {
166:       VecDestroy(&(*e)->X);
167:     }
168:     if (HaveStages(cptype) && !(*e)->Y) {
169:       TSGetStages(ts,&stack->numY,&Y);
170:       if (stack->numY) {
171:         VecDuplicateVecs(Y[0],stack->numY,&(*e)->Y);
172:       }
173:     }
174:     if (cptype==0 && (*e)->Y) {
175:       VecDestroyVecs(stack->numY,&(*e)->Y);
176:     }
177:     (*e)->cptype = cptype;
178:     return(0);
179:   }
180:   if (stack->use_dram) {
181:     PetscMallocSetDRAM();
182:   }
183:   PetscNew(e);
184:   if (HaveSolution(cptype)) {
185:     TSGetSolution(ts,&X);
186:     VecDuplicate(X,&(*e)->X);
187:   }
188:   if (HaveStages(cptype)) {
189:     TSGetStages(ts,&stack->numY,&Y);
190:     if (stack->numY) {
191:       VecDuplicateVecs(Y[0],stack->numY,&(*e)->Y);
192:     }
193:   }
194:   if (stack->use_dram) {
195:     PetscMallocResetDRAM();
196:   }
197:   stack->nallocated++;
198:   (*e)->cptype = cptype;
199:   return(0);
200: }

202: static PetscErrorCode ElementSet(TS ts, Stack *stack, StackElement *e, PetscInt stepnum, PetscReal time, Vec X)
203: {
204:   Vec            *Y;
205:   PetscInt       i;
206:   PetscReal      timeprev;

210:   if (HaveSolution((*e)->cptype)) {
211:     VecCopy(X,(*e)->X);
212:   }
213:   if (HaveStages((*e)->cptype)) {
214:     TSGetStages(ts,&stack->numY,&Y);
215:     for (i=0;i<stack->numY;i++) {
216:       VecCopy(Y[i],(*e)->Y[i]);
217:     }
218:   }
219:   (*e)->stepnum = stepnum;
220:   (*e)->time    = time;
221:   /* for consistency */
222:   if (stepnum == 0) {
223:     (*e)->timeprev = (*e)->time - ts->time_step;
224:   } else {
225:     TSGetPrevTime(ts,&timeprev);
226:     (*e)->timeprev = timeprev;
227:   }
228:   return(0);
229: }

231: static PetscErrorCode ElementDestroy(Stack *stack,StackElement e)
232: {

236:   if (stack->use_dram) {
237:     PetscMallocSetDRAM();
238:   }
239:   VecDestroy(&e->X);
240:   if (e->Y) {
241:     VecDestroyVecs(stack->numY,&e->Y);
242:   }
243:   PetscFree(e);
244:   if (stack->use_dram) {
245:     PetscMallocResetDRAM();
246:   }
247:   stack->nallocated--;
248:   return(0);
249: }

251: static PetscErrorCode StackResize(Stack *stack,PetscInt newsize)
252: {
253:   StackElement   *newcontainer;
254:   PetscInt       i;

258:   PetscCalloc1(newsize*sizeof(StackElement),&newcontainer);
259:   for (i=0;i<stack->stacksize;i++) {
260:     newcontainer[i] = stack->container[i];
261:   }
262:   PetscFree(stack->container);
263:   stack->container = newcontainer;
264:   stack->stacksize = newsize;
265:   return(0);
266: }

268: static PetscErrorCode StackPush(Stack *stack,StackElement e)
269: {
271:   if (stack->top+1 >= stack->stacksize) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_MEMC,"Maximum stack size (%D) exceeded",stack->stacksize);
272:   stack->container[++stack->top] = e;
273:   return(0);
274: }

276: static PetscErrorCode StackPop(Stack *stack,StackElement *e)
277: {
279:   *e = NULL;
280:   if (stack->top == -1) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_MEMC,"Empty stack");
281:   *e = stack->container[stack->top--];
282:   return(0);
283: }

285: static PetscErrorCode StackTop(Stack *stack,StackElement *e)
286: {
288:   *e = stack->container[stack->top];
289:   return(0);
290: }

292: static PetscErrorCode StackInit(Stack *stack,PetscInt size,PetscInt ny)
293: {

297:   stack->top  = -1;
298:   stack->numY = ny;

300:   if (!stack->container) {
301:     PetscCalloc1(size,&stack->container);
302:   }
303:   return(0);
304: }

306: static PetscErrorCode StackDestroy(Stack *stack)
307: {
308:   PetscInt       i,n = stack->nallocated;

312:   if (!stack->container) return(0);
313:   if (stack->top+1 > stack->nallocated) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_PLIB,"Stack size does not match element counter %D",stack->nallocated);
314:   for (i=0; i<n; i++) {
315:     ElementDestroy(stack,stack->container[i]);
316:   }
317:   PetscFree(stack->container);
318:   return(0);
319: }

321: static PetscErrorCode StackFind(Stack *stack,StackElement *e,PetscInt index)
322: {
324:   *e = NULL;
325:   if (index < 0 || index > stack->top) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_PLIB,"Invalid index %D",index);
326:   *e = stack->container[index];
327:   return(0);
328: }

330: static PetscErrorCode WriteToDisk(PetscBool stifflyaccurate,PetscInt stepnum,PetscReal time,PetscReal timeprev,Vec X,Vec *Y,PetscInt numY,CheckpointType cptype,PetscViewer viewer)
331: {
332:   PetscInt       i;

336:   PetscViewerBinaryWrite(viewer,&stepnum,1,PETSC_INT);
337:   if (HaveSolution(cptype)) {
338:     VecView(X,viewer);
339:   }
340:   if (HaveStages(cptype)) {
341:     for (i=0; i<numY; i++) {
342:       /* For stiffly accurate TS methods, the last stage Y[ns-1] is the same as the solution X, thus does not need to be saved again. */
343:       if (stifflyaccurate && i == numY-1 && HaveSolution(cptype)) continue;
344:       VecView(Y[i],viewer);
345:     }
346:   }
347:   PetscViewerBinaryWrite(viewer,&time,1,PETSC_REAL);
348:   PetscViewerBinaryWrite(viewer,&timeprev,1,PETSC_REAL);
349:   return(0);
350: }

352: static PetscErrorCode ReadFromDisk(PetscBool stifflyaccurate,PetscInt *stepnum,PetscReal *time,PetscReal *timeprev,Vec X,Vec *Y,PetscInt numY,CheckpointType cptype,PetscViewer viewer)
353: {
354:   PetscInt       i;

358:   PetscViewerBinaryRead(viewer,stepnum,1,NULL,PETSC_INT);
359:   if (HaveSolution(cptype)) {
360:     VecLoad(X,viewer);
361:   }
362:   if (HaveStages(cptype)) {
363:     for (i=0; i<numY; i++) {
364:       /* For stiffly accurate TS methods, the last stage Y[ns-1] is the same as the solution X, thus does not need to be loaded again. */
365:       if (stifflyaccurate && i == numY-1 && HaveSolution(cptype)) continue;
366:       VecLoad(Y[i],viewer);
367:     }
368:   }
369:   PetscViewerBinaryRead(viewer,time,1,NULL,PETSC_REAL);
370:   PetscViewerBinaryRead(viewer,timeprev,1,NULL,PETSC_REAL);
371:   return(0);
372: }

374: static PetscErrorCode StackDumpAll(TSTrajectory tj,TS ts,Stack *stack,PetscInt id)
375: {
376:   Vec            *Y;
377:   PetscInt       i,ndumped,cptype_int;
378:   StackElement   e = NULL;
379:   TJScheduler    *tjsch = (TJScheduler*)tj->data;
380:   char           filename[PETSC_MAX_PATH_LEN];
382:   MPI_Comm       comm;

385:   PetscObjectGetComm((PetscObject)ts,&comm);
386:   if (tj->monitor) {
387:     PetscViewerASCIIPushTab(tj->monitor);
388:     PetscViewerASCIIPrintf(tj->monitor,"Dump stack id %D to file\n",id);
389:     PetscViewerASCIIPopTab(tj->monitor);
390:   }
391:   PetscSNPrintf(filename,sizeof(filename),"%s/TS-STACK%06d.bin",tj->dirname,id);
392:   PetscViewerFileSetName(tjsch->viewer,filename);
393:   PetscViewerSetUp(tjsch->viewer);
394:   ndumped = stack->top+1;
395:   PetscViewerBinaryWrite(tjsch->viewer,&ndumped,1,PETSC_INT);
396:   for (i=0;i<ndumped;i++) {
397:     e = stack->container[i];
398:     cptype_int = (PetscInt)e->cptype;
399:     PetscViewerBinaryWrite(tjsch->viewer,&cptype_int,1,PETSC_INT);
400:     PetscLogEventBegin(TSTrajectory_DiskWrite,tj,ts,0,0);
401:     WriteToDisk(ts->stifflyaccurate,e->stepnum,e->time,e->timeprev,e->X,e->Y,stack->numY,e->cptype,tjsch->viewer);
402:     PetscLogEventEnd(TSTrajectory_DiskWrite,tj,ts,0,0);
403:     ts->trajectory->diskwrites++;
404:     StackPop(stack,&e);
405:   }
406:   /* save the last step for restart, the last step is in memory when using single level schemes, but not necessarily the case for multi level schemes */
407:   TSGetStages(ts,&stack->numY,&Y);
408:   PetscLogEventBegin(TSTrajectory_DiskWrite,tj,ts,0,0);
409:   WriteToDisk(ts->stifflyaccurate,ts->steps,ts->ptime,ts->ptime_prev,ts->vec_sol,Y,stack->numY,SOLUTION_STAGES,tjsch->viewer);
410:   PetscLogEventEnd(TSTrajectory_DiskWrite,tj,ts,0,0);
411:   ts->trajectory->diskwrites++;
412:   return(0);
413: }

415: static PetscErrorCode StackLoadAll(TSTrajectory tj,TS ts,Stack *stack,PetscInt id)
416: {
417:   Vec            *Y;
418:   PetscInt       i,nloaded,cptype_int;
419:   StackElement   e;
420:   PetscViewer    viewer;
421:   char           filename[PETSC_MAX_PATH_LEN];

425:   if (tj->monitor) {
426:     PetscViewerASCIIAddTab(tj->monitor,((PetscObject)tj)->tablevel);
427:     PetscViewerASCIIPrintf(tj->monitor,"Load stack from file\n");
428:     PetscViewerASCIISubtractTab(tj->monitor,((PetscObject)tj)->tablevel);
429:   }
430:   PetscSNPrintf(filename,sizeof filename,"%s/TS-STACK%06d.bin",tj->dirname,id);
431:   PetscViewerBinaryOpen(PetscObjectComm((PetscObject)tj),filename,FILE_MODE_READ,&viewer);
432:   PetscViewerBinarySetSkipInfo(viewer,PETSC_TRUE);
433:   PetscViewerPushFormat(viewer,PETSC_VIEWER_NATIVE);
434:   PetscViewerBinaryRead(viewer,&nloaded,1,NULL,PETSC_INT);
435:   for (i=0;i<nloaded;i++) {
436:     PetscViewerBinaryRead(viewer,&cptype_int,1,NULL,PETSC_INT);
437:     ElementCreate(ts,(CheckpointType)cptype_int,stack,&e);
438:     StackPush(stack,e);
439:     PetscLogEventBegin(TSTrajectory_DiskRead,tj,ts,0,0);
440:     ReadFromDisk(ts->stifflyaccurate,&e->stepnum,&e->time,&e->timeprev,e->X,e->Y,stack->numY,e->cptype,viewer);
441:     PetscLogEventEnd(TSTrajectory_DiskRead,tj,ts,0,0);
442:     ts->trajectory->diskreads++;
443:   }
444:   /* load the last step into TS */
445:   TSGetStages(ts,&stack->numY,&Y);
446:   PetscLogEventBegin(TSTrajectory_DiskRead,tj,ts,0,0);
447:   ReadFromDisk(ts->stifflyaccurate,&ts->steps,&ts->ptime,&ts->ptime_prev,ts->vec_sol,Y,stack->numY,SOLUTION_STAGES,viewer);
448:   PetscLogEventEnd(TSTrajectory_DiskRead,tj,ts,0,0);
449:   ts->trajectory->diskreads++;
450:   TurnBackward(ts);
451:   PetscViewerDestroy(&viewer);
452:   return(0);
453: }

455: #if defined(PETSC_HAVE_REVOLVE)
456: static PetscErrorCode StackLoadLast(TSTrajectory tj,TS ts,Stack *stack,PetscInt id)
457: {
458:   Vec            *Y;
459:   PetscInt       size;
460:   PetscViewer    viewer;
461:   char           filename[PETSC_MAX_PATH_LEN];
462: #if defined(PETSC_HAVE_MPIIO)
463:   PetscBool      usempiio;
464: #endif
465:   int            fd;
466:   off_t          off,offset;

470:   if (tj->monitor) {
471:     PetscViewerASCIIAddTab(tj->monitor,((PetscObject)tj)->tablevel);
472:     PetscViewerASCIIPrintf(tj->monitor,"Load last stack element from file\n");
473:     PetscViewerASCIISubtractTab(tj->monitor,((PetscObject)tj)->tablevel);
474:   }
475:   TSGetStages(ts,&stack->numY,&Y);
476:   VecGetSize(Y[0],&size);
477:   /* VecView writes to file two extra int's for class id and number of rows */
478:   off  = -((stack->solution_only?0:stack->numY)+1)*(size*PETSC_BINARY_SCALAR_SIZE+2*PETSC_BINARY_INT_SIZE)-PETSC_BINARY_INT_SIZE-2*PETSC_BINARY_SCALAR_SIZE;

480:   PetscSNPrintf(filename,sizeof filename,"%s/TS-STACK%06d.bin",tj->dirname,id);
481:   PetscViewerBinaryOpen(PetscObjectComm((PetscObject)tj),filename,FILE_MODE_READ,&viewer);
482:   PetscViewerBinarySetSkipInfo(viewer,PETSC_TRUE);
483:   PetscViewerPushFormat(viewer,PETSC_VIEWER_NATIVE);
484: #if defined(PETSC_HAVE_MPIIO)
485:   PetscViewerBinaryGetUseMPIIO(viewer,&usempiio);
486:   if (usempiio) {
487:     PetscViewerBinaryGetMPIIODescriptor(viewer,(MPI_File*)&fd);
488:     PetscBinarySynchronizedSeek(PetscObjectComm((PetscObject)tj),fd,off,PETSC_BINARY_SEEK_END,&offset);
489:   } else {
490: #endif
491:     PetscViewerBinaryGetDescriptor(viewer,&fd);
492:     PetscBinarySeek(fd,off,PETSC_BINARY_SEEK_END,&offset);
493: #if defined(PETSC_HAVE_MPIIO)
494:   }
495: #endif
496:   /* load the last step into TS */
497:   PetscLogEventBegin(TSTrajectory_DiskRead,tj,ts,0,0);
498:   ReadFromDisk(ts->stifflyaccurate,&ts->steps,&ts->ptime,&ts->ptime_prev,ts->vec_sol,Y,stack->numY,SOLUTION_STAGES,viewer);
499:   PetscLogEventEnd(TSTrajectory_DiskRead,tj,ts,0,0);
500:   ts->trajectory->diskreads++;
501:   PetscViewerDestroy(&viewer);
502:   TurnBackward(ts);
503:   return(0);
504: }
505: #endif

507: static PetscErrorCode DumpSingle(TSTrajectory tj,TS ts,Stack *stack,PetscInt id)
508: {
509:   Vec            *Y;
510:   PetscInt       stepnum;
511:   TJScheduler    *tjsch = (TJScheduler*)tj->data;
512:   char           filename[PETSC_MAX_PATH_LEN];
514:   MPI_Comm       comm;

517:   PetscObjectGetComm((PetscObject)ts,&comm);
518:   if (tj->monitor) {
519:     PetscViewerASCIIAddTab(tj->monitor,((PetscObject)tj)->tablevel);
520:     PetscViewerASCIIPrintf(tj->monitor,"Dump a single point from file\n");
521:     PetscViewerASCIISubtractTab(tj->monitor,((PetscObject)tj)->tablevel);
522:   }
523:   TSGetStepNumber(ts,&stepnum);
524:   PetscSNPrintf(filename,sizeof(filename),"%s/TS-CPS%06d.bin",tj->dirname,id);
525:   PetscViewerFileSetName(tjsch->viewer,filename);
526:   PetscViewerSetUp(tjsch->viewer);

528:   TSGetStages(ts,&stack->numY,&Y);
529:   PetscLogEventBegin(TSTrajectory_DiskWrite,tj,ts,0,0);
530:   WriteToDisk(ts->stifflyaccurate,stepnum,ts->ptime,ts->ptime_prev,ts->vec_sol,Y,stack->numY,SOLUTION_STAGES,tjsch->viewer);
531:   PetscLogEventEnd(TSTrajectory_DiskWrite,tj,ts,0,0);
532:   ts->trajectory->diskwrites++;
533:   return(0);
534: }

536: static PetscErrorCode LoadSingle(TSTrajectory tj,TS ts,Stack *stack,PetscInt id)
537: {
538:   Vec            *Y;
539:   PetscViewer    viewer;
540:   char           filename[PETSC_MAX_PATH_LEN];

544:   if (tj->monitor) {
545:     PetscViewerASCIIAddTab(tj->monitor,((PetscObject)tj)->tablevel);
546:     PetscViewerASCIIPrintf(tj->monitor,"Load a single point from file\n");
547:     PetscViewerASCIISubtractTab(tj->monitor,((PetscObject)tj)->tablevel);
548:   }
549:   PetscSNPrintf(filename,sizeof filename,"%s/TS-CPS%06d.bin",tj->dirname,id);
550:   PetscViewerBinaryOpen(PetscObjectComm((PetscObject)tj),filename,FILE_MODE_READ,&viewer);
551:   PetscViewerBinarySetSkipInfo(viewer,PETSC_TRUE);
552:   PetscViewerPushFormat(viewer,PETSC_VIEWER_NATIVE);
553:   TSGetStages(ts,&stack->numY,&Y);
554:   PetscLogEventBegin(TSTrajectory_DiskRead,tj,ts,0,0);
555:   ReadFromDisk(ts->stifflyaccurate,&ts->steps,&ts->ptime,&ts->ptime_prev,ts->vec_sol,Y,stack->numY,SOLUTION_STAGES,viewer);
556:   PetscLogEventEnd(TSTrajectory_DiskRead,tj,ts,0,0);
557:   ts->trajectory->diskreads++;
558:   PetscViewerDestroy(&viewer);
559:   return(0);
560: }

562: static PetscErrorCode UpdateTS(TS ts,Stack *stack,StackElement e,PetscInt stepnum,PetscBool adjoint_mode)
563: {
564:   Vec            *Y;
565:   PetscInt       i;

569:   /* In adjoint mode we do not need to copy solution if the stepnum is the same */
570:   if (!adjoint_mode || (HaveSolution(e->cptype) && e->stepnum!=stepnum)) {
571:     VecCopy(e->X,ts->vec_sol);
572:   }
573:   if (HaveStages(e->cptype)) {
574:     TSGetStages(ts,&stack->numY,&Y);
575:     if (e->stepnum && e->stepnum==stepnum) {
576:       for (i=0;i<stack->numY;i++) {
577:         VecCopy(e->Y[i],Y[i]);
578:       }
579:     } else if (ts->stifflyaccurate) {
580:       VecCopy(e->Y[stack->numY-1],ts->vec_sol);
581:     }
582:   }
583:   if (adjoint_mode) {
584:     TSSetTimeStep(ts,e->timeprev-e->time); /* stepsize will be negative */
585:   } else {
586:     TSSetTimeStep(ts,e->time-e->timeprev); /* stepsize will be positive */
587:   }
588:   ts->ptime      = e->time;
589:   ts->ptime_prev = e->timeprev;
590:   return(0);
591: }

593: static PetscErrorCode ReCompute(TS ts,TJScheduler *tjsch,PetscInt stepnumbegin,PetscInt stepnumend)
594: {
595:   Stack          *stack = &tjsch->stack;
596:   PetscInt       i;

600:   tjsch->recompute = PETSC_TRUE; /* hints TSTrajectorySet() that it is in recompute mode */
601:   TSSetStepNumber(ts,stepnumbegin);/* global step number */
602:   for (i=stepnumbegin;i<stepnumend;i++) { /* assume fixed step size */
603:     if (stack->solution_only && !tjsch->skip_trajectory) { /* revolve online need this */
604:       /* don't use the public interface as it will update the TSHistory: this need a better fix */
605:       TSTrajectorySet_Memory(ts->trajectory,ts,ts->steps,ts->ptime,ts->vec_sol);
606:     }
607:     TSMonitor(ts,ts->steps,ts->ptime,ts->vec_sol);
608:     TSStep(ts);
609:     if (!stack->solution_only && !tjsch->skip_trajectory) {
610:       /* don't use the public interface as it will update the TSHistory: this need a better fix */
611:       TSTrajectorySet_Memory(ts->trajectory,ts,ts->steps,ts->ptime,ts->vec_sol);
612:     }
613:     TSEventHandler(ts);
614:     if (!ts->steprollback) {
615:       TSPostStep(ts);
616:     }
617:   }
618:   TurnBackward(ts);
619:   ts->trajectory->recomps += stepnumend-stepnumbegin; /* recomputation counter */
620:   TSSetStepNumber(ts,stepnumend);
621:   tjsch->recompute = PETSC_FALSE; /* reset the flag for recompute mode */
622:   return(0);
623: }

625: static PetscErrorCode TopLevelStore(TSTrajectory tj,TS ts,TJScheduler *tjsch,PetscInt stepnum,PetscInt localstepnum,PetscInt laststridesize,PetscBool *done)
626: {
627:   Stack          *stack = &tjsch->stack;
628:   DiskStack      *diskstack = &tjsch->diskstack;
629:   PetscInt       stridenum;

633:   *done = PETSC_FALSE;
634:   stridenum    = stepnum/tjsch->stride;
635:   /* make sure saved checkpoint id starts from 1
636:      skip last stride when using stridenum+1
637:      skip first stride when using stridenum */
638:   if (stack->solution_only) {
639:     if (tjsch->save_stack) {
640:       if (localstepnum == tjsch->stride-1 && stepnum < tjsch->total_steps-laststridesize) { /* current step will be saved without going through stack */
641:         StackDumpAll(tj,ts,stack,stridenum+1);
642:         if (tjsch->stype == TWO_LEVEL_TWO_REVOLVE) diskstack->container[++diskstack->top] = stridenum+1;
643:         *done = PETSC_TRUE;
644:       }
645:     } else {
646:       if (localstepnum == 0 && stepnum < tjsch->total_steps-laststridesize) {
647:         DumpSingle(tj,ts,stack,stridenum+1);
648:         if (tjsch->stype == TWO_LEVEL_TWO_REVOLVE) diskstack->container[++diskstack->top] = stridenum+1;
649:         *done = PETSC_TRUE;
650:       }
651:     }
652:   } else {
653:     if (tjsch->save_stack) {
654:       if (localstepnum == 0 && stepnum < tjsch->total_steps && stepnum != 0) { /* skip the first stride */
655:         StackDumpAll(tj,ts,stack,stridenum);
656:         if (tjsch->stype == TWO_LEVEL_TWO_REVOLVE) diskstack->container[++diskstack->top] = stridenum;
657:         *done = PETSC_TRUE;
658:       }
659:     } else {
660:       if (localstepnum == 1 && stepnum < tjsch->total_steps-laststridesize) {
661:         DumpSingle(tj,ts,stack,stridenum+1);
662:         if (tjsch->stype == TWO_LEVEL_TWO_REVOLVE) diskstack->container[++diskstack->top] = stridenum+1;
663:         *done = PETSC_TRUE;
664:       }
665:     }
666:   }
667:   return(0);
668: }

670: static PetscErrorCode TSTrajectoryMemorySet_N(TS ts,TJScheduler *tjsch,PetscInt stepnum,PetscReal time,Vec X)
671: {
672:   Stack          *stack = &tjsch->stack;
673:   StackElement   e;
674:   CheckpointType cptype;

678:   /* skip the last step */
679:   if (ts->reason) { /* only affect the forward run */
680:     /* update total_steps in the end of forward run */
681:     if (stepnum != tjsch->total_steps) tjsch->total_steps = stepnum;
682:     if (stack->solution_only) {
683:       /* get rid of the solution at second last step */
684:       StackPop(stack,&e);
685:     }
686:     return(0);
687:   }
688:   /*  do not save trajectory at the recompute stage for solution_only mode */
689:   if (stack->solution_only && tjsch->recompute) return(0);
690:   /* skip the first step for no_solution_only mode */
691:   if (!stack->solution_only && stepnum == 0) return(0);

693:   /* resize the stack */
694:   if (stack->top+1 == stack->stacksize) {
695:     StackResize(stack,2*stack->stacksize);
696:   }
697:   /* update timenext for the previous step; necessary for step adaptivity */
698:   if (stack->top > -1) {
699:     StackTop(stack,&e);
700:     e->timenext = ts->ptime;
701:   }
702:   if (stepnum < stack->top) {
703:     SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_MEMC,"Illegal modification of a non-top stack element");
704:   }
705:   cptype = stack->solution_only ? SOLUTIONONLY : STAGESONLY;
706:   ElementCreate(ts,cptype,stack,&e);
707:   ElementSet(ts,stack,&e,stepnum,time,X);
708:   StackPush(stack,e);
709:   return(0);
710: }

712: static PetscErrorCode TSTrajectoryMemorySet_N_2(TS ts,TJScheduler *tjsch,PetscInt stepnum,PetscReal time,Vec X)
713: {
714:   Stack          *stack = &tjsch->stack;
715:   StackElement   e;
716:   CheckpointType cptype;

720:   if (stack->top+1 == stack->stacksize) {
721:     StackResize(stack,2*stack->stacksize);
722:   }
723:   /* update timenext for the previous step; necessary for step adaptivity */
724:   if (stack->top > -1) {
725:     StackTop(stack,&e);
726:     e->timenext = ts->ptime;
727:   }
728:   if (stepnum < stack->top) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_MEMC,"Illegal modification of a non-top stack element");
729:   cptype = stack->solution_only ? SOLUTIONONLY : SOLUTION_STAGES; /* Always include solution in a checkpoint in non-adjoint mode */
730:   ElementCreate(ts,cptype,stack,&e);
731:   ElementSet(ts,stack,&e,stepnum,time,X);
732:   StackPush(stack,e);
733:   return(0);
734: }

736: static PetscErrorCode TSTrajectoryMemoryGet_N(TS ts,TJScheduler *tjsch,PetscInt stepnum)
737: {
738:   Stack          *stack = &tjsch->stack;
739:   StackElement   e;
740:   PetscInt       ns;

744:   /* If TSTrajectoryGet() is called after TSAdjointSolve() converges (e.g. outside the while loop in TSAdjointSolve()), skip getting the checkpoint. */
745:   if (ts->reason) return(0);
746:   if (stepnum == tjsch->total_steps) {
747:     TurnBackward(ts);
748:     return(0);
749:   }
750:   /* restore a checkpoint */
751:   StackTop(stack,&e);
752:   UpdateTS(ts,stack,e,stepnum,PETSC_TRUE);
753:   TSGetStages(ts,&ns,PETSC_IGNORE);
754:   if (stack->solution_only && ns) { /* recompute one step */
755:     TurnForwardWithStepsize(ts,e->timenext-e->time);
756:     ReCompute(ts,tjsch,e->stepnum,stepnum);
757:   }
758:   StackPop(stack,&e);
759:   return(0);
760: }

762: static PetscErrorCode TSTrajectoryMemoryGet_N_2(TS ts,TJScheduler *tjsch,PetscInt stepnum)
763: {
764:   Stack          *stack = &tjsch->stack;
765:   StackElement   e = NULL;

769:   StackFind(stack,&e,stepnum);
770:   if (stepnum != e->stepnum) SETERRQ2(PetscObjectComm((PetscObject)ts),PETSC_ERR_PLIB,"Inconsistent steps! %D != %D",stepnum,e->stepnum);
771:   UpdateTS(ts,stack,e,stepnum,PETSC_FALSE);
772:   return(0);
773: }

775: static PetscErrorCode TSTrajectoryMemorySet_TLNR(TSTrajectory tj,TS ts,TJScheduler *tjsch,PetscInt stepnum,PetscReal time,Vec X)
776: {
777:   Stack          *stack = &tjsch->stack;
778:   PetscInt       localstepnum,laststridesize;
779:   StackElement   e;
780:   PetscBool      done;
781:   CheckpointType cptype;

785:   if (!stack->solution_only && stepnum == 0) return(0);
786:   if (stack->solution_only && stepnum == tjsch->total_steps) return(0);
787:   if (tjsch->save_stack && tjsch->recompute) return(0);

789:   localstepnum = stepnum%tjsch->stride;
790:   /* (stridesize-1) checkpoints are saved in each stride; an extra point is added by StackDumpAll() */
791:   laststridesize = tjsch->total_steps%tjsch->stride;
792:   if (!laststridesize) laststridesize = tjsch->stride;

794:   if (!tjsch->recompute) {
795:     TopLevelStore(tj,ts,tjsch,stepnum,localstepnum,laststridesize,&done);
796:     if (!tjsch->save_stack && stepnum < tjsch->total_steps-laststridesize) return(0);
797:   }
798:   if (!stack->solution_only && localstepnum == 0) return(0); /* skip last point in each stride at recompute stage or last stride */
799:   if (stack->solution_only && localstepnum == tjsch->stride-1) return(0); /* skip last step in each stride at recompute stage or last stride */

801:   cptype = stack->solution_only ? SOLUTIONONLY : STAGESONLY;
802:   ElementCreate(ts,cptype,stack,&e);
803:   ElementSet(ts,stack,&e,stepnum,time,X);
804:   StackPush(stack,e);
805:   return(0);
806: }

808: static PetscErrorCode TSTrajectoryMemoryGet_TLNR(TSTrajectory tj,TS ts,TJScheduler *tjsch,PetscInt stepnum)
809: {
810:   Stack          *stack = &tjsch->stack;
811:   PetscInt       id,localstepnum,laststridesize;
812:   StackElement   e;

816:   if (stepnum == tjsch->total_steps) {
817:     TurnBackward(ts);
818:     return(0);
819:   }

821:   localstepnum = stepnum%tjsch->stride;
822:   laststridesize = tjsch->total_steps%tjsch->stride;
823:   if (!laststridesize) laststridesize = tjsch->stride;
824:   if (stack->solution_only) {
825:     /* fill stack with info */
826:     if (localstepnum == 0 && tjsch->total_steps-stepnum >= laststridesize) {
827:       id = stepnum/tjsch->stride;
828:       if (tjsch->save_stack) {
829:         StackLoadAll(tj,ts,stack,id);
830:         tjsch->skip_trajectory = PETSC_TRUE;
831:         TurnForward(ts);
832:         ReCompute(ts,tjsch,id*tjsch->stride-1,id*tjsch->stride);
833:         tjsch->skip_trajectory = PETSC_FALSE;
834:       } else {
835:         LoadSingle(tj,ts,stack,id);
836:         TurnForward(ts);
837:         ReCompute(ts,tjsch,(id-1)*tjsch->stride,id*tjsch->stride);
838:       }
839:       return(0);
840:     }
841:     /* restore a checkpoint */
842:     StackPop(stack,&e);
843:     UpdateTS(ts,stack,e,stepnum,PETSC_TRUE);
844:     tjsch->skip_trajectory = PETSC_TRUE;
845:     TurnForward(ts);
846:     ReCompute(ts,tjsch,e->stepnum,stepnum);
847:     tjsch->skip_trajectory = PETSC_FALSE;
848:   } else {
849:     CheckpointType cptype = STAGESONLY;
850:     /* fill stack with info */
851:     if (localstepnum == 0 && tjsch->total_steps-stepnum >= laststridesize) {
852:       id = stepnum/tjsch->stride;
853:       if (tjsch->save_stack) {
854:         StackLoadAll(tj,ts,stack,id);
855:       } else {
856:         LoadSingle(tj,ts,stack,id);
857:         ElementCreate(ts,cptype,stack,&e);
858:         ElementSet(ts,stack,&e,(id-1)*tjsch->stride+1,ts->ptime,ts->vec_sol);
859:         StackPush(stack,e);
860:         TurnForward(ts);
861:         ReCompute(ts,tjsch,e->stepnum,id*tjsch->stride);
862:       }
863:       return(0);
864:     }
865:     /* restore a checkpoint */
866:     StackPop(stack,&e);
867:     UpdateTS(ts,stack,e,stepnum,PETSC_TRUE);
868:   }
869:   return(0);
870: }

872: #if defined(PETSC_HAVE_REVOLVE)
873: static PetscErrorCode printwhattodo(PetscViewer viewer,PetscRevolveInt whattodo,RevolveCTX *rctx,PetscRevolveInt shift)
874: {

878:   if (!viewer) return(0);

880:   switch(whattodo) {
881:     case 1:
882:       PetscViewerASCIIPrintf(viewer,"Advance from %D to %D\n",rctx->oldcapo+shift,rctx->capo+shift);
883:       break;
884:     case 2:
885:       PetscViewerASCIIPrintf(viewer,"Store in checkpoint number %D (located in RAM)\n",rctx->check);
886:       break;
887:     case 3:
888:       PetscViewerASCIIPrintf(viewer,"First turn: Initialize adjoints and reverse first step\n");
889:       break;
890:     case 4:
891:       PetscViewerASCIIPrintf(viewer,"Forward and reverse one step\n");
892:       break;
893:     case 5:
894:       PetscViewerASCIIPrintf(viewer,"Restore in checkpoint number %D (located in RAM)\n",rctx->check);
895:       break;
896:     case 7:
897:       PetscViewerASCIIPrintf(viewer,"Store in checkpoint number %D (located on disk)\n",rctx->check);
898:       break;
899:     case 8:
900:       PetscViewerASCIIPrintf(viewer,"Restore in checkpoint number %D (located on disk)\n",rctx->check);
901:       break;
902:     case -1:
903:       PetscViewerASCIIPrintf(viewer,"Error!");
904:       break;
905:   }
906:   return(0);
907: }

909: static PetscErrorCode printwhattodo2(PetscViewer viewer,PetscRevolveInt whattodo,RevolveCTX *rctx,PetscRevolveInt shift)
910: {

914:   if (!viewer) return(0);

916:   switch(whattodo) {
917:     case 1:
918:       PetscViewerASCIIPrintf(viewer,"[Top Level] Advance from stride %D to stride %D\n",rctx->oldcapo+shift,rctx->capo+shift);
919:       break;
920:     case 2:
921:       PetscViewerASCIIPrintf(viewer,"[Top Level] Store in checkpoint number %D\n",rctx->check);
922:       break;
923:     case 3:
924:       PetscViewerASCIIPrintf(viewer,"[Top Level] First turn: Initialize adjoints and reverse first stride\n");
925:       break;
926:     case 4:
927:       PetscViewerASCIIPrintf(viewer,"[Top Level] Forward and reverse one stride\n");
928:       break;
929:     case 5:
930:       PetscViewerASCIIPrintf(viewer,"[Top Level] Restore in checkpoint number %D\n",rctx->check);
931:       break;
932:     case 7:
933:       PetscViewerASCIIPrintf(viewer,"[Top Level] Store in top-level checkpoint number %D\n",rctx->check);
934:       break;
935:     case 8:
936:       PetscViewerASCIIPrintf(viewer,"[Top Level] Restore in top-level checkpoint number %D\n",rctx->check);
937:       break;
938:     case -1:
939:       PetscViewerASCIIPrintf(viewer,"[Top Level] Error!");
940:       break;
941:   }
942:   return(0);
943: }

945: static PetscErrorCode InitRevolve(PetscInt fine,PetscInt snaps,RevolveCTX *rctx)
946: {
947:   PetscRevolveInt rsnaps,rfine;
948:   PetscErrorCode  ierr;

951:   PetscRevolveIntCast(snaps,&rsnaps);
952:   PetscRevolveIntCast(fine,&rfine);
953:   revolve_reset();
954:   revolve_create_offline(rfine,rsnaps);
955:   rctx->snaps_in       = rsnaps;
956:   rctx->fine           = rfine;
957:   rctx->check          = 0;
958:   rctx->capo           = 0;
959:   rctx->reverseonestep = PETSC_FALSE;
960:   /* check stepsleft? */
961:   return(0);
962: }

964: static PetscErrorCode FastForwardRevolve(RevolveCTX *rctx)
965: {
966:   PetscRevolveInt whattodo;

969:   whattodo = 0;
970:   while (whattodo!=3) { /* we have to fast forward revolve to the beginning of the backward sweep due to unfriendly revolve interface */
971:     whattodo = revolve_action(&rctx->check,&rctx->capo,&rctx->fine,rctx->snaps_in,&rctx->info,&rctx->where);
972:   }
973:   return(0);
974: }

976: static PetscErrorCode ApplyRevolve(PetscViewer viewer,SchedulerType stype,RevolveCTX *rctx,PetscRevolveInt total_steps,PetscRevolveInt stepnum,PetscRevolveInt localstepnum,PetscBool toplevel,PetscInt *store)
977: {
978:   PetscErrorCode  ierr;
979:   PetscRevolveInt shift,whattodo;

982:   *store = 0;
983:   if (rctx->stepsleft > 0) { /* advance the solution without checkpointing anything as Revolve requires */
984:     rctx->stepsleft--;
985:     return(0);
986:   }
987:   /* let Revolve determine what to do next */
988:   shift         = stepnum-localstepnum;
989:   rctx->oldcapo = rctx->capo;
990:   rctx->capo    = localstepnum;

992:   if (!toplevel) whattodo = revolve_action(&rctx->check,&rctx->capo,&rctx->fine,rctx->snaps_in,&rctx->info,&rctx->where);
993:   else whattodo = revolve2_action(&rctx->check,&rctx->capo,&rctx->fine,rctx->snaps_in,&rctx->info,&rctx->where);
994:   if (stype == REVOLVE_ONLINE && whattodo == 8) whattodo = 5;
995:   if (stype == REVOLVE_ONLINE && whattodo == 7) whattodo = 2;
996:   if (!toplevel) {printwhattodo(viewer,whattodo,rctx,shift);}
997:   else {printwhattodo2(viewer,whattodo,rctx,shift);}
998:   if (whattodo == -1) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_LIB,"Error in the Revolve library");
999:   if (whattodo == 1) { /* advance some time steps */
1000:     if (stype == REVOLVE_ONLINE && rctx->capo >= total_steps-1) {
1001:       revolve_turn(total_steps,&rctx->capo,&rctx->fine);
1002:       if (!toplevel) {printwhattodo(viewer,whattodo,rctx,shift);}
1003:       else {printwhattodo2(viewer,whattodo,rctx,shift);}
1004:     }
1005:     rctx->stepsleft = rctx->capo-rctx->oldcapo-1;
1006:   }
1007:   if (whattodo == 3 || whattodo == 4) { /* ready for a reverse step */
1008:     rctx->reverseonestep = PETSC_TRUE;
1009:   }
1010:   if (whattodo == 5) { /* restore a checkpoint and ask Revolve what to do next */
1011:     rctx->oldcapo = rctx->capo;
1012:     if (!toplevel) whattodo = revolve_action(&rctx->check,&rctx->capo,&rctx->fine,rctx->snaps_in,&rctx->info,&rctx->where); /* must return 1 or 3 or 4*/
1013:     else whattodo = revolve2_action(&rctx->check,&rctx->capo,&rctx->fine,rctx->snaps_in,&rctx->info,&rctx->where);
1014:     if (!toplevel) {printwhattodo(viewer,whattodo,rctx,shift);}
1015:     else {printwhattodo2(viewer,whattodo,rctx,shift);}
1016:     if (whattodo == 3 || whattodo == 4) rctx->reverseonestep = PETSC_TRUE;
1017:     if (whattodo == 1) rctx->stepsleft = rctx->capo-rctx->oldcapo;
1018:   }
1019:   if (whattodo == 7) { /* save the checkpoint to disk */
1020:     *store = 2;
1021:     rctx->oldcapo = rctx->capo;
1022:     whattodo = revolve_action(&rctx->check,&rctx->capo,&rctx->fine,rctx->snaps_in,&rctx->info,&rctx->where); /* must return 1 */
1023:     printwhattodo(viewer,whattodo,rctx,shift);
1024:     rctx->stepsleft = rctx->capo-rctx->oldcapo-1;
1025:   }
1026:   if (whattodo == 2) { /* store a checkpoint to RAM and ask Revolve how many time steps to advance next */
1027:     *store = 1;
1028:     rctx->oldcapo = rctx->capo;
1029:     if (!toplevel) whattodo = revolve_action(&rctx->check,&rctx->capo,&rctx->fine,rctx->snaps_in,&rctx->info,&rctx->where); /* must return 1 */
1030:     else whattodo = revolve2_action(&rctx->check,&rctx->capo,&rctx->fine,rctx->snaps_in,&rctx->info,&rctx->where);
1031:     if (!toplevel) {printwhattodo(viewer,whattodo,rctx,shift);}
1032:     else {printwhattodo2(viewer,whattodo,rctx,shift);}
1033:     if (stype == REVOLVE_ONLINE && rctx->capo >= total_steps-1) {
1034:       revolve_turn(total_steps,&rctx->capo,&rctx->fine);
1035:       printwhattodo(viewer,whattodo,rctx,shift);
1036:     }
1037:     rctx->stepsleft = rctx->capo-rctx->oldcapo-1;
1038:   }
1039:   return(0);
1040: }

1042: static PetscErrorCode TSTrajectoryMemorySet_ROF(TSTrajectory tj,TS ts,TJScheduler *tjsch,PetscInt stepnum,PetscReal time,Vec X)
1043: {
1044:   Stack           *stack = &tjsch->stack;
1045:   PetscInt        store;
1046:   StackElement    e;
1047:   PetscRevolveInt rtotal_steps,rstepnum;
1048:   CheckpointType  cptype;
1049:   PetscErrorCode  ierr;

1052:   if (!stack->solution_only && stepnum == 0) return(0);
1053:   if (stack->solution_only && stepnum == tjsch->total_steps) return(0);
1054:   PetscRevolveIntCast(tjsch->total_steps,&rtotal_steps);
1055:   PetscRevolveIntCast(stepnum,&rstepnum);
1056:   ApplyRevolve(tj->monitor,tjsch->stype,tjsch->rctx,rtotal_steps,rstepnum,rstepnum,PETSC_FALSE,&store);
1057:   if (store == 1) {
1058:     if (stepnum < stack->top) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_MEMC,"Illegal modification of a non-top stack element");
1059:     cptype = stack->solution_only ? SOLUTIONONLY : SOLUTION_STAGES;
1060:     ElementCreate(ts,cptype,stack,&e);
1061:     ElementSet(ts,stack,&e,stepnum,time,X);
1062:     StackPush(stack,e);
1063:   }
1064:   return(0);
1065: }

1067: static PetscErrorCode TSTrajectoryMemoryGet_ROF(TSTrajectory tj,TS ts,TJScheduler *tjsch,PetscInt stepnum)
1068: {
1069:   Stack           *stack = &tjsch->stack;
1070:   PetscInt        store;
1071:   PetscRevolveInt whattodo,shift,rtotal_steps,rstepnum;
1072:   StackElement    e;
1073:   PetscErrorCode  ierr;

1076:   if (stepnum == 0 || stepnum == tjsch->total_steps) {
1077:     TurnBackward(ts);
1078:     tjsch->rctx->reverseonestep = PETSC_FALSE;
1079:     return(0);
1080:   }
1081:   /* restore a checkpoint */
1082:   StackTop(stack,&e);
1083:   UpdateTS(ts,stack,e,stepnum,PETSC_TRUE);
1084:   PetscRevolveIntCast(tjsch->total_steps,&rtotal_steps);
1085:   PetscRevolveIntCast(stepnum,&rstepnum);
1086:   if (stack->solution_only) { /* start with restoring a checkpoint */
1087:     tjsch->rctx->capo = rstepnum;
1088:     tjsch->rctx->oldcapo = tjsch->rctx->capo;
1089:     shift = 0;
1090:     whattodo = revolve_action(&tjsch->rctx->check,&tjsch->rctx->capo,&tjsch->rctx->fine,tjsch->rctx->snaps_in,&tjsch->rctx->info,&tjsch->rctx->where);
1091:     printwhattodo(tj->monitor,whattodo,tjsch->rctx,shift);
1092:   } else { /* 2 revolve actions: restore a checkpoint and then advance */
1093:     ApplyRevolve(tj->monitor,tjsch->stype,tjsch->rctx,rtotal_steps,rstepnum,rstepnum,PETSC_FALSE,&store);
1094:     if (tj->monitor) {
1095:       PetscViewerASCIIAddTab(tj->monitor,((PetscObject)tj)->tablevel);
1096:       PetscViewerASCIIPrintf(tj->monitor,"Skip the step from %D to %D (stage values already checkpointed)\n",tjsch->rctx->oldcapo,tjsch->rctx->oldcapo+1);
1097:       PetscViewerASCIISubtractTab(tj->monitor,((PetscObject)tj)->tablevel);
1098:     }
1099:     if (!tjsch->rctx->reverseonestep && tjsch->rctx->stepsleft > 0) tjsch->rctx->stepsleft--;
1100:   }
1101:   if (stack->solution_only || (!stack->solution_only && e->stepnum < stepnum)) {
1102:     TurnForward(ts);
1103:     ReCompute(ts,tjsch,e->stepnum,stepnum);
1104:   }
1105:   if ((stack->solution_only && e->stepnum+1 == stepnum) || (!stack->solution_only && e->stepnum == stepnum)) {
1106:     StackPop(stack,&e);
1107:   }
1108:   tjsch->rctx->reverseonestep = PETSC_FALSE;
1109:   return(0);
1110: }

1112: static PetscErrorCode TSTrajectoryMemorySet_RON(TSTrajectory tj,TS ts,TJScheduler *tjsch,PetscInt stepnum,PetscReal time,Vec X)
1113: {
1114:   Stack           *stack = &tjsch->stack;
1115:   Vec             *Y;
1116:   PetscInt        i,store;
1117:   PetscReal       timeprev;
1118:   StackElement    e;
1119:   RevolveCTX      *rctx = tjsch->rctx;
1120:   PetscRevolveInt rtotal_steps,rstepnum;
1121:   CheckpointType  cptype;
1122:   PetscErrorCode  ierr;

1125:   if (!stack->solution_only && stepnum == 0) return(0);
1126:   if (stack->solution_only && stepnum == tjsch->total_steps) return(0);
1127:   PetscRevolveIntCast(tjsch->total_steps,&rtotal_steps);
1128:   PetscRevolveIntCast(stepnum,&rstepnum);
1129:   ApplyRevolve(tj->monitor,tjsch->stype,rctx,rtotal_steps,rstepnum,rstepnum,PETSC_FALSE,&store);
1130:   if (store == 1) {
1131:     if (rctx->check != stack->top+1) { /* overwrite some non-top checkpoint in the stack */
1132:       StackFind(stack,&e,rctx->check);
1133:       if (HaveSolution(e->cptype)) {
1134:         VecCopy(X,e->X);
1135:       }
1136:       if (HaveStages(e->cptype)) {
1137:         TSGetStages(ts,&stack->numY,&Y);
1138:         for (i=0;i<stack->numY;i++) {
1139:           VecCopy(Y[i],e->Y[i]);
1140:         }
1141:       }
1142:       e->stepnum  = stepnum;
1143:       e->time     = time;
1144:       TSGetPrevTime(ts,&timeprev);
1145:       e->timeprev = timeprev;
1146:     } else {
1147:       if (stepnum < stack->top) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_MEMC,"Illegal modification of a non-top stack element");
1148:       cptype = stack->solution_only ? SOLUTIONONLY : SOLUTION_STAGES;
1149:       ElementCreate(ts,cptype,stack,&e);
1150:       ElementSet(ts,stack,&e,stepnum,time,X);
1151:       StackPush(stack,e);
1152:     }
1153:   }
1154:   return(0);
1155: }

1157: static PetscErrorCode TSTrajectoryMemoryGet_RON(TSTrajectory tj,TS ts,TJScheduler *tjsch,PetscInt stepnum)
1158: {
1159:   Stack           *stack = &tjsch->stack;
1160:   PetscRevolveInt whattodo,shift,rstepnum;
1161:   StackElement    e;
1162:   PetscErrorCode  ierr;

1165:   if (stepnum == 0 || stepnum == tjsch->total_steps) {
1166:     TurnBackward(ts);
1167:     tjsch->rctx->reverseonestep = PETSC_FALSE;
1168:     return(0);
1169:   }
1170:   PetscRevolveIntCast(stepnum,&rstepnum);
1171:   tjsch->rctx->capo = rstepnum;
1172:   tjsch->rctx->oldcapo = tjsch->rctx->capo;
1173:   shift = 0;
1174:   whattodo = revolve_action(&tjsch->rctx->check,&tjsch->rctx->capo,&tjsch->rctx->fine,tjsch->rctx->snaps_in,&tjsch->rctx->info,&tjsch->rctx->where); /* whattodo=restore */
1175:   if (whattodo == 8) whattodo = 5;
1176:   printwhattodo(tj->monitor,whattodo,tjsch->rctx,shift);
1177:   /* restore a checkpoint */
1178:   StackFind(stack,&e,tjsch->rctx->check);
1179:   UpdateTS(ts,stack,e,stepnum,PETSC_TRUE);
1180:   if (!stack->solution_only) { /* whattodo must be 5 */
1181:     /* ask Revolve what to do next */
1182:     tjsch->rctx->oldcapo = tjsch->rctx->capo;
1183:     whattodo = revolve_action(&tjsch->rctx->check,&tjsch->rctx->capo,&tjsch->rctx->fine,tjsch->rctx->snaps_in,&tjsch->rctx->info,&tjsch->rctx->where); /* must return 1 or 3 or 4*/
1184:     printwhattodo(tj->monitor,whattodo,tjsch->rctx,shift);
1185:     if (whattodo == 3 || whattodo == 4) tjsch->rctx->reverseonestep = PETSC_TRUE;
1186:     if (whattodo == 1) tjsch->rctx->stepsleft = tjsch->rctx->capo-tjsch->rctx->oldcapo;
1187:     if (tj->monitor) {
1188:       PetscViewerASCIIAddTab(tj->monitor,((PetscObject)tj)->tablevel);
1189:       PetscViewerASCIIPrintf(tj->monitor,"Skip the step from %D to %D (stage values already checkpointed)\n",tjsch->rctx->oldcapo,tjsch->rctx->oldcapo+1);
1190:       PetscViewerASCIISubtractTab(tj->monitor,((PetscObject)tj)->tablevel);
1191:     }
1192:     if (!tjsch->rctx->reverseonestep && tjsch->rctx->stepsleft > 0) tjsch->rctx->stepsleft--;
1193:   }
1194:   if (stack->solution_only || (!stack->solution_only && e->stepnum < stepnum)) {
1195:     TurnForward(ts);
1196:     ReCompute(ts,tjsch,e->stepnum,stepnum);
1197:   }
1198:   tjsch->rctx->reverseonestep = PETSC_FALSE;
1199:   return(0);
1200: }

1202: static PetscErrorCode TSTrajectoryMemorySet_TLR(TSTrajectory tj,TS ts,TJScheduler *tjsch,PetscInt stepnum,PetscReal time,Vec X)
1203: {
1204:   Stack           *stack = &tjsch->stack;
1205:   PetscInt        store,localstepnum,laststridesize;
1206:   StackElement    e;
1207:   PetscBool       done = PETSC_FALSE;
1208:   PetscRevolveInt rtotal_steps,rstepnum,rlocalstepnum;
1209:   CheckpointType  cptype;
1210:   PetscErrorCode  ierr;

1213:   if (!stack->solution_only && stepnum == 0) return(0);
1214:   if (stack->solution_only && stepnum == tjsch->total_steps) return(0);

1216:   localstepnum = stepnum%tjsch->stride;
1217:   laststridesize = tjsch->total_steps%tjsch->stride;
1218:   if (!laststridesize) laststridesize = tjsch->stride;

1220:   if (!tjsch->recompute) {
1221:     TopLevelStore(tj,ts,tjsch,stepnum,localstepnum,laststridesize,&done);
1222:     /* revolve is needed for the last stride; different starting points for last stride between solutin_only and !solutin_only */
1223:     if (!stack->solution_only && !tjsch->save_stack && stepnum <= tjsch->total_steps-laststridesize) return(0);
1224:     if (stack->solution_only && !tjsch->save_stack && stepnum < tjsch->total_steps-laststridesize) return(0);
1225:   }
1226:   if (tjsch->save_stack && done) {
1227:     InitRevolve(tjsch->stride,tjsch->max_cps_ram,tjsch->rctx);
1228:     return(0);
1229:   }
1230:   if (laststridesize < tjsch->stride) {
1231:     if (stack->solution_only && stepnum == tjsch->total_steps-laststridesize && !tjsch->recompute) { /* step tjsch->total_steps-laststridesize-1 is skipped, but the next step is not */
1232:       InitRevolve(laststridesize,tjsch->max_cps_ram,tjsch->rctx);
1233:     }
1234:     if (!stack->solution_only && stepnum == tjsch->total_steps-laststridesize+1 && !tjsch->recompute) { /* step tjsch->total_steps-laststridesize is skipped, but the next step is not */
1235:       InitRevolve(laststridesize,tjsch->max_cps_ram,tjsch->rctx);
1236:     }
1237:   }
1238:   PetscRevolveIntCast(tjsch->total_steps,&rtotal_steps);
1239:   PetscRevolveIntCast(stepnum,&rstepnum);
1240:   PetscRevolveIntCast(localstepnum,&rlocalstepnum);
1241:   ApplyRevolve(tj->monitor,tjsch->stype,tjsch->rctx,rtotal_steps,rstepnum,rlocalstepnum,PETSC_FALSE,&store);
1242:   if (store == 1) {
1243:     if (localstepnum < stack->top) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_MEMC,"Illegal modification of a non-top stack element");
1244:     cptype = stack->solution_only ? SOLUTIONONLY : SOLUTION_STAGES;
1245:     ElementCreate(ts,cptype,stack,&e);
1246:     ElementSet(ts,stack,&e,stepnum,time,X);
1247:     StackPush(stack,e);
1248:   }
1249:   return(0);
1250: }

1252: static PetscErrorCode TSTrajectoryMemoryGet_TLR(TSTrajectory tj,TS ts,TJScheduler *tjsch,PetscInt stepnum)
1253: {
1254:   Stack           *stack = &tjsch->stack;
1255:   PetscRevolveInt whattodo,shift,rstepnum,rlocalstepnum,rtotal_steps;
1256:   PetscInt        localstepnum,stridenum,laststridesize,store;
1257:   StackElement    e;
1258:   CheckpointType  cptype;
1259:   PetscErrorCode  ierr;

1262:   localstepnum = stepnum%tjsch->stride;
1263:   stridenum    = stepnum/tjsch->stride;
1264:   if (stepnum == tjsch->total_steps) {
1265:     TurnBackward(ts);
1266:     tjsch->rctx->reverseonestep = PETSC_FALSE;
1267:     return(0);
1268:   }
1269:   laststridesize = tjsch->total_steps%tjsch->stride;
1270:   if (!laststridesize) laststridesize = tjsch->stride;
1271:   PetscRevolveIntCast(tjsch->total_steps,&rtotal_steps);
1272:   PetscRevolveIntCast(stepnum,&rstepnum);
1273:   PetscRevolveIntCast(localstepnum,&rlocalstepnum);
1274:   if (stack->solution_only) {
1275:     /* fill stack */
1276:     if (localstepnum == 0 && stepnum <= tjsch->total_steps-laststridesize) {
1277:       if (tjsch->save_stack) {
1278:         StackLoadAll(tj,ts,stack,stridenum);
1279:         InitRevolve(tjsch->stride,tjsch->max_cps_ram,tjsch->rctx);
1280:         FastForwardRevolve(tjsch->rctx);
1281:         tjsch->skip_trajectory = PETSC_TRUE;
1282:         TurnForward(ts);
1283:         ReCompute(ts,tjsch,stridenum*tjsch->stride-1,stridenum*tjsch->stride);
1284:         tjsch->skip_trajectory = PETSC_FALSE;
1285:       } else {
1286:         LoadSingle(tj,ts,stack,stridenum);
1287:         InitRevolve(tjsch->stride,tjsch->max_cps_ram,tjsch->rctx);
1288:         TurnForward(ts);
1289:         ReCompute(ts,tjsch,(stridenum-1)*tjsch->stride,stridenum*tjsch->stride);
1290:       }
1291:       return(0);
1292:     }
1293:     /* restore a checkpoint */
1294:     StackTop(stack,&e);
1295:     UpdateTS(ts,stack,e,stepnum,PETSC_TRUE);
1296:     /* start with restoring a checkpoint */
1297:     tjsch->rctx->capo = rstepnum;
1298:     tjsch->rctx->oldcapo = tjsch->rctx->capo;
1299:     shift = rstepnum-rlocalstepnum;
1300:     whattodo = revolve_action(&tjsch->rctx->check,&tjsch->rctx->capo,&tjsch->rctx->fine,tjsch->rctx->snaps_in,&tjsch->rctx->info,&tjsch->rctx->where);
1301:     printwhattodo(tj->monitor,whattodo,tjsch->rctx,shift);
1302:     TurnForward(ts);
1303:     ReCompute(ts,tjsch,e->stepnum,stepnum);
1304:     if (e->stepnum+1 == stepnum) {
1305:       StackPop(stack,&e);
1306:     }
1307:   } else {
1308:     /* fill stack with info */
1309:     if (localstepnum == 0 && tjsch->total_steps-stepnum >= laststridesize) {
1310:       if (tjsch->save_stack) {
1311:         StackLoadAll(tj,ts,stack,stridenum);
1312:         InitRevolve(tjsch->stride,tjsch->max_cps_ram,tjsch->rctx);
1313:         FastForwardRevolve(tjsch->rctx);
1314:       } else {
1315:         PetscRevolveInt rnum;
1316:         LoadSingle(tj,ts,stack,stridenum);
1317:         InitRevolve(tjsch->stride,tjsch->max_cps_ram,tjsch->rctx);
1318:         PetscRevolveIntCast((stridenum-1)*tjsch->stride+1,&rnum);
1319:         ApplyRevolve(tj->monitor,tjsch->stype,tjsch->rctx,rtotal_steps,rnum,1,PETSC_FALSE,&store);
1320:         if (tj->monitor) {
1321:           PetscViewerASCIIAddTab(tj->monitor,((PetscObject)tj)->tablevel);
1322:           PetscViewerASCIIPrintf(tj->monitor,"Skip the step from %D to %D (stage values already checkpointed)\n",(stridenum-1)*tjsch->stride+tjsch->rctx->oldcapo,(stridenum-1)*tjsch->stride+tjsch->rctx->oldcapo+1);
1323:           PetscViewerASCIISubtractTab(tj->monitor,((PetscObject)tj)->tablevel);
1324:         }
1325:         cptype = SOLUTION_STAGES;
1326:         ElementCreate(ts,cptype,stack,&e);
1327:         ElementSet(ts,stack,&e,(stridenum-1)*tjsch->stride+1,ts->ptime,ts->vec_sol);
1328:         StackPush(stack,e);
1329:         TurnForward(ts);
1330:         ReCompute(ts,tjsch,e->stepnum,stridenum*tjsch->stride);
1331:       }
1332:       return(0);
1333:     }
1334:     /* restore a checkpoint */
1335:     StackTop(stack,&e);
1336:     UpdateTS(ts,stack,e,stepnum,PETSC_TRUE);
1337:     /* 2 revolve actions: restore a checkpoint and then advance */
1338:     ApplyRevolve(tj->monitor,tjsch->stype,tjsch->rctx,rtotal_steps,rstepnum,rlocalstepnum,PETSC_FALSE,&store);
1339:     if (tj->monitor) {
1340:       PetscViewerASCIIAddTab(tj->monitor,((PetscObject)tj)->tablevel);
1341:       PetscViewerASCIIPrintf(tj->monitor,"Skip the step from %D to %D (stage values already checkpointed)\n",stepnum-localstepnum+tjsch->rctx->oldcapo,stepnum-localstepnum+tjsch->rctx->oldcapo+1);
1342:       PetscViewerASCIISubtractTab(tj->monitor,((PetscObject)tj)->tablevel);
1343:     }
1344:     if (!tjsch->rctx->reverseonestep && tjsch->rctx->stepsleft > 0) tjsch->rctx->stepsleft--;
1345:     if (e->stepnum < stepnum) {
1346:       TurnForward(ts);
1347:       ReCompute(ts,tjsch,e->stepnum,stepnum);
1348:     }
1349:     if (e->stepnum == stepnum) {
1350:       StackPop(stack,&e);
1351:     }
1352:   }
1353:   tjsch->rctx->reverseonestep = PETSC_FALSE;
1354:   return(0);
1355: }

1357: static PetscErrorCode TSTrajectoryMemorySet_TLTR(TSTrajectory tj,TS ts,TJScheduler *tjsch,PetscInt stepnum,PetscReal time,Vec X)
1358: {
1359:   Stack           *stack = &tjsch->stack;
1360:   PetscInt        store,localstepnum,stridenum,laststridesize;
1361:   StackElement    e;
1362:   PetscBool       done = PETSC_FALSE;
1363:   PetscRevolveInt rlocalstepnum,rstepnum,rtotal_steps;
1364:   PetscErrorCode  ierr;

1367:   if (!stack->solution_only && stepnum == 0) return(0);
1368:   if (stack->solution_only && stepnum == tjsch->total_steps) return(0);

1370:   localstepnum = stepnum%tjsch->stride; /* index at the bottom level (inside a stride) */
1371:   stridenum    = stepnum/tjsch->stride; /* index at the top level */
1372:   laststridesize = tjsch->total_steps%tjsch->stride;
1373:   if (!laststridesize) laststridesize = tjsch->stride;
1374:   if (stack->solution_only && localstepnum == 0 && !tjsch->rctx2->reverseonestep) {
1375:     PetscRevolveIntCast((tjsch->total_steps+tjsch->stride-1)/tjsch->stride,&rtotal_steps);
1376:     PetscRevolveIntCast(stridenum,&rstepnum);
1377:     ApplyRevolve(tj->monitor,tjsch->stype,tjsch->rctx2,rtotal_steps,rstepnum,rstepnum,PETSC_TRUE,&tjsch->store_stride);
1378:     if (laststridesize < tjsch->stride && stepnum == tjsch->total_steps-laststridesize) {
1379:       InitRevolve(laststridesize,tjsch->max_cps_ram,tjsch->rctx);
1380:     }
1381:   }
1382:   if (!stack->solution_only && localstepnum == 1 && !tjsch->rctx2->reverseonestep) {
1383:     PetscRevolveIntCast((tjsch->total_steps+tjsch->stride-1)/tjsch->stride,&rtotal_steps);
1384:     PetscRevolveIntCast(stridenum,&rstepnum);
1385:     ApplyRevolve(tj->monitor,tjsch->stype,tjsch->rctx2,rtotal_steps,rstepnum,rstepnum,PETSC_TRUE,&tjsch->store_stride);
1386:     if (laststridesize < tjsch->stride && stepnum == tjsch->total_steps-laststridesize+1) {
1387:       InitRevolve(laststridesize,tjsch->max_cps_ram,tjsch->rctx);
1388:     }
1389:   }
1390:   if (tjsch->store_stride) {
1391:     TopLevelStore(tj,ts,tjsch,stepnum,localstepnum,laststridesize,&done);
1392:     if (done) {
1393:       InitRevolve(tjsch->stride,tjsch->max_cps_ram,tjsch->rctx);
1394:       return(0);
1395:     }
1396:   }
1397:   if (stepnum < tjsch->total_steps-laststridesize) {
1398:     if (tjsch->save_stack && !tjsch->store_stride && !tjsch->rctx2->reverseonestep) return(0); /* store or forward-and-reverse at top level trigger revolve at bottom level */
1399:     if (!tjsch->save_stack && !tjsch->rctx2->reverseonestep) return(0); /* store operation does not require revolve be called at bottom level */
1400:   }
1401:   /* Skipping stepnum=0 for !stack->only is enough for TLR, but not for TLTR. Here we skip the first step for each stride so that the top-level revolve is applied (always at localstepnum=1) ahead of the bottom-level revolve */
1402:   if (!stack->solution_only && localstepnum == 0 && stepnum != tjsch->total_steps && !tjsch->recompute) return(0);
1403:   PetscRevolveIntCast(tjsch->total_steps,&rtotal_steps);
1404:   PetscRevolveIntCast(stepnum,&rstepnum);
1405:   PetscRevolveIntCast(localstepnum,&rlocalstepnum);
1406:   ApplyRevolve(tj->monitor,tjsch->stype,tjsch->rctx,rtotal_steps,rstepnum,rlocalstepnum,PETSC_FALSE,&store);
1407:   if (store == 1) {
1408:     CheckpointType cptype;
1409:     if (localstepnum < stack->top) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_MEMC,"Illegal modification of a non-top stack element");
1410:     cptype = stack->solution_only ? SOLUTIONONLY : SOLUTION_STAGES;
1411:     ElementCreate(ts,cptype,stack,&e);
1412:     ElementSet(ts,stack,&e,stepnum,time,X);
1413:     StackPush(stack,e);
1414:   }
1415:   return(0);
1416: }

1418: static PetscErrorCode TSTrajectoryMemoryGet_TLTR(TSTrajectory tj,TS ts,TJScheduler *tjsch,PetscInt stepnum)
1419: {
1420:   Stack           *stack = &tjsch->stack;
1421:   DiskStack       *diskstack = &tjsch->diskstack;
1422:   PetscInt        localstepnum,stridenum,restoredstridenum,laststridesize,store;
1423:   StackElement    e;
1424:   PetscRevolveInt whattodo,shift;
1425:   PetscRevolveInt rtotal_steps,rstepnum,rlocalstepnum;
1426:   PetscErrorCode  ierr;

1429:   localstepnum = stepnum%tjsch->stride;
1430:   stridenum    = stepnum/tjsch->stride;
1431:   if (stepnum == tjsch->total_steps) {
1432:     TurnBackward(ts);
1433:     tjsch->rctx->reverseonestep = PETSC_FALSE;
1434:     return(0);
1435:   }
1436:   laststridesize = tjsch->total_steps%tjsch->stride;
1437:   if (!laststridesize) laststridesize = tjsch->stride;
1438:   /*
1439:    Last stride can be adjoined directly. All the other strides require that the stack in memory be ready before an adjoint step is taken (at the end of each stride). The following two cases need to be addressed differently:
1440:      Case 1 (save_stack)
1441:        Restore a disk checkpoint; update TS with the last element in the restored data; recompute to the current point.
1442:      Case 2 (!save_stack)
1443:        Restore a disk checkpoint; update TS with the restored point; recompute to the current point.
1444:   */
1445:   if (localstepnum == 0 && stepnum <= tjsch->total_steps-laststridesize) {
1446:     /* restore the top element in the stack for disk checkpoints */
1447:     restoredstridenum = diskstack->container[diskstack->top];
1448:     tjsch->rctx2->reverseonestep = PETSC_FALSE;
1449:     /* top-level revolve must be applied before current step, just like the solution_only mode for single-level revolve */
1450:     if (!tjsch->save_stack && stack->solution_only) { /* start with restoring a checkpoint */
1451:       PetscRevolveIntCast(stridenum,&rstepnum);
1452:       tjsch->rctx2->capo = rstepnum;
1453:       tjsch->rctx2->oldcapo = tjsch->rctx2->capo;
1454:       shift = 0;
1455:       whattodo = revolve2_action(&tjsch->rctx2->check,&tjsch->rctx2->capo,&tjsch->rctx2->fine,tjsch->rctx2->snaps_in,&tjsch->rctx2->info,&tjsch->rctx2->where);
1456:       printwhattodo2(tj->monitor,whattodo,tjsch->rctx2,shift);
1457:     } else { /* 2 revolve actions: restore a checkpoint and then advance */
1458:       PetscRevolveIntCast((tjsch->total_steps+tjsch->stride-1)/tjsch->stride,&rtotal_steps);
1459:       PetscRevolveIntCast(stridenum,&rstepnum);
1460:       ApplyRevolve(tj->monitor,tjsch->stype,tjsch->rctx2,rtotal_steps,rstepnum,rstepnum,PETSC_TRUE,&tjsch->store_stride);
1461:       if (tj->monitor) {
1462:         PetscViewerASCIIAddTab(tj->monitor,((PetscObject)tj)->tablevel);
1463:         PetscViewerASCIIPrintf(tj->monitor,"[Top Level] Skip the stride from %D to %D (stage values already checkpointed)\n",tjsch->rctx2->oldcapo,tjsch->rctx2->oldcapo+1);
1464:         PetscViewerASCIISubtractTab(tj->monitor,((PetscObject)tj)->tablevel);
1465:       }
1466:       if (!tjsch->rctx2->reverseonestep && tjsch->rctx2->stepsleft > 0) tjsch->rctx2->stepsleft--;
1467:     }
1468:     /* fill stack */
1469:     if (stack->solution_only) {
1470:       if (tjsch->save_stack) {
1471:         if (restoredstridenum < stridenum) {
1472:           StackLoadLast(tj,ts,stack,restoredstridenum);
1473:         } else {
1474:           StackLoadAll(tj,ts,stack,restoredstridenum);
1475:         }
1476:         /* recompute one step ahead */
1477:         tjsch->skip_trajectory = PETSC_TRUE;
1478:         TurnForward(ts);
1479:         ReCompute(ts,tjsch,stridenum*tjsch->stride-1,stridenum*tjsch->stride);
1480:         tjsch->skip_trajectory = PETSC_FALSE;
1481:         if (restoredstridenum < stridenum) {
1482:           InitRevolve(tjsch->stride,tjsch->max_cps_ram,tjsch->rctx);
1483:           TurnForward(ts);
1484:           ReCompute(ts,tjsch,restoredstridenum*tjsch->stride,stepnum);
1485:         } else { /* stack ready, fast forward revolve status */
1486:           InitRevolve(tjsch->stride,tjsch->max_cps_ram,tjsch->rctx);
1487:           FastForwardRevolve(tjsch->rctx);
1488:         }
1489:       } else {
1490:         LoadSingle(tj,ts,stack,restoredstridenum);
1491:         InitRevolve(tjsch->stride,tjsch->max_cps_ram,tjsch->rctx);
1492:         TurnForward(ts);
1493:         ReCompute(ts,tjsch,(restoredstridenum-1)*tjsch->stride,stepnum);
1494:       }
1495:     } else {
1496:       if (tjsch->save_stack) {
1497:         if (restoredstridenum < stridenum) {
1498:           StackLoadLast(tj,ts,stack,restoredstridenum);
1499:           /* reset revolve */
1500:           InitRevolve(tjsch->stride,tjsch->max_cps_ram,tjsch->rctx);
1501:           TurnForward(ts);
1502:           ReCompute(ts,tjsch,restoredstridenum*tjsch->stride,stepnum);
1503:         } else { /* stack ready, fast forward revolve status */
1504:           StackLoadAll(tj,ts,stack,restoredstridenum);
1505:           InitRevolve(tjsch->stride,tjsch->max_cps_ram,tjsch->rctx);
1506:           FastForwardRevolve(tjsch->rctx);
1507:         }
1508:       } else {
1509:         LoadSingle(tj,ts,stack,restoredstridenum);
1510:         InitRevolve(tjsch->stride,tjsch->max_cps_ram,tjsch->rctx);
1511:         /* push first element to stack */
1512:         if (tjsch->store_stride || tjsch->rctx2->reverseonestep) {
1513:           CheckpointType cptype = SOLUTION_STAGES;
1514:           shift = (restoredstridenum-1)*tjsch->stride-localstepnum;
1515:           PetscRevolveIntCast(tjsch->total_steps,&rtotal_steps);
1516:           PetscRevolveIntCast((restoredstridenum-1)*tjsch->stride+1,&rstepnum);
1517:           ApplyRevolve(tj->monitor,tjsch->stype,tjsch->rctx,rtotal_steps,rstepnum,1,PETSC_FALSE,&store);
1518:           if (tj->monitor) {
1519:             PetscViewerASCIIAddTab(tj->monitor,((PetscObject)tj)->tablevel);
1520:             PetscViewerASCIIPrintf(tj->monitor,"Skip the step from %D to %D (stage values already checkpointed)\n",(restoredstridenum-1)*tjsch->stride,(restoredstridenum-1)*tjsch->stride+1);
1521:             PetscViewerASCIISubtractTab(tj->monitor,((PetscObject)tj)->tablevel);
1522:           }
1523:           ElementCreate(ts,cptype,stack,&e);
1524:           ElementSet(ts,stack,&e,(restoredstridenum-1)*tjsch->stride+1,ts->ptime,ts->vec_sol);
1525:           StackPush(stack,e);
1526:         }
1527:         TurnForward(ts);
1528:         ReCompute(ts,tjsch,(restoredstridenum-1)*tjsch->stride+1,stepnum);
1529:       }
1530:     }
1531:     if (restoredstridenum == stridenum) diskstack->top--;
1532:     tjsch->rctx->reverseonestep = PETSC_FALSE;
1533:     return(0);
1534:   }

1536:   if (stack->solution_only) {
1537:     /* restore a checkpoint */
1538:     StackTop(stack,&e);
1539:     UpdateTS(ts,stack,e,stepnum,PETSC_TRUE);
1540:     /* start with restoring a checkpoint */
1541:     PetscRevolveIntCast(stepnum,&rstepnum);
1542:     PetscRevolveIntCast(localstepnum,&rlocalstepnum);
1543:     tjsch->rctx->capo = rstepnum;
1544:     tjsch->rctx->oldcapo = tjsch->rctx->capo;
1545:     shift = rstepnum-rlocalstepnum;
1546:     whattodo = revolve_action(&tjsch->rctx->check,&tjsch->rctx->capo,&tjsch->rctx->fine,tjsch->rctx->snaps_in,&tjsch->rctx->info,&tjsch->rctx->where);
1547:     printwhattodo(tj->monitor,whattodo,tjsch->rctx,shift);
1548:     TurnForward(ts);
1549:     ReCompute(ts,tjsch,e->stepnum,stepnum);
1550:     if (e->stepnum+1 == stepnum) {
1551:       StackPop(stack,&e);
1552:     }
1553:   } else {
1554:     PetscRevolveInt rlocalstepnum;
1555:     /* restore a checkpoint */
1556:     StackTop(stack,&e);
1557:     UpdateTS(ts,stack,e,stepnum,PETSC_TRUE);
1558:     /* 2 revolve actions: restore a checkpoint and then advance */
1559:     PetscRevolveIntCast(tjsch->total_steps,&rtotal_steps);
1560:     PetscRevolveIntCast(stridenum,&rstepnum);
1561:     PetscRevolveIntCast(localstepnum,&rlocalstepnum);
1562:     ApplyRevolve(tj->monitor,tjsch->stype,tjsch->rctx,rtotal_steps,rstepnum,rlocalstepnum,PETSC_FALSE,&store);
1563:     if (tj->monitor) {
1564:       PetscViewerASCIIAddTab(tj->monitor,((PetscObject)tj)->tablevel);
1565:       PetscViewerASCIIPrintf(tj->monitor,"Skip the step from %D to %D (stage values already checkpointed)\n",stepnum-localstepnum+tjsch->rctx->oldcapo,stepnum-localstepnum+tjsch->rctx->oldcapo+1);
1566:       PetscViewerASCIISubtractTab(tj->monitor,((PetscObject)tj)->tablevel);
1567:     }
1568:     if (!tjsch->rctx->reverseonestep && tjsch->rctx->stepsleft > 0) tjsch->rctx->stepsleft--;
1569:     if (e->stepnum < stepnum) {
1570:       TurnForward(ts);
1571:       ReCompute(ts,tjsch,e->stepnum,stepnum);
1572:     }
1573:     if (e->stepnum == stepnum) {
1574:       StackPop(stack,&e);
1575:     }
1576:   }
1577:   tjsch->rctx->reverseonestep = PETSC_FALSE;
1578:   return(0);
1579: }

1581: static PetscErrorCode TSTrajectoryMemorySet_RMS(TSTrajectory tj,TS ts,TJScheduler *tjsch,PetscInt stepnum,PetscReal time,Vec X)
1582: {
1583:   Stack           *stack = &tjsch->stack;
1584:   PetscInt        store;
1585:   StackElement    e;
1586:   PetscRevolveInt rtotal_steps,rstepnum;
1587:   PetscErrorCode  ierr;

1590:   if (!stack->solution_only && stepnum == 0) return(0);
1591:   if (stack->solution_only && stepnum == tjsch->total_steps) return(0);
1592:   PetscRevolveIntCast(tjsch->total_steps,&rtotal_steps);
1593:   PetscRevolveIntCast(stepnum,&rstepnum);
1594:   ApplyRevolve(tj->monitor,tjsch->stype,tjsch->rctx,rtotal_steps,rstepnum,rstepnum,PETSC_FALSE,&store);
1595:   if (store == 1) {
1596:     CheckpointType cptype;
1597:     if (stepnum < stack->top) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_MEMC,"Illegal modification of a non-top stack element");
1598:     cptype = stack->solution_only ? SOLUTIONONLY : SOLUTION_STAGES;
1599:     ElementCreate(ts,cptype,stack,&e);
1600:     ElementSet(ts,stack,&e,stepnum,time,X);
1601:     StackPush(stack,e);
1602:   } else if (store == 2) {
1603:     DumpSingle(tj,ts,stack,tjsch->rctx->check+1);
1604:   }
1605:   return(0);
1606: }

1608: static PetscErrorCode TSTrajectoryMemoryGet_RMS(TSTrajectory tj,TS ts,TJScheduler *tjsch,PetscInt stepnum)
1609: {
1610:   Stack           *stack = &tjsch->stack;
1611:   PetscRevolveInt whattodo,shift,rstepnum;
1612:   PetscInt        restart;
1613:   PetscBool       ondisk;
1614:   StackElement    e;
1615:   PetscErrorCode  ierr;

1618:   if (stepnum == 0 || stepnum == tjsch->total_steps) {
1619:     TurnBackward(ts);
1620:     tjsch->rctx->reverseonestep = PETSC_FALSE;
1621:     return(0);
1622:   }
1623:   PetscRevolveIntCast(stepnum,&rstepnum);
1624:   tjsch->rctx->capo = rstepnum;
1625:   tjsch->rctx->oldcapo = tjsch->rctx->capo;
1626:   shift = 0;
1627:   whattodo = revolve_action(&tjsch->rctx->check,&tjsch->rctx->capo,&tjsch->rctx->fine,tjsch->rctx->snaps_in,&tjsch->rctx->info,&tjsch->rctx->where); /* whattodo=restore */
1628:   printwhattodo(tj->monitor,whattodo,tjsch->rctx,shift);
1629:   /* restore a checkpoint */
1630:   restart = tjsch->rctx->capo;
1631:   if (!tjsch->rctx->where) {
1632:     ondisk = PETSC_TRUE;
1633:     LoadSingle(tj,ts,stack,tjsch->rctx->check+1);
1634:     TurnBackward(ts);
1635:   } else {
1636:     ondisk = PETSC_FALSE;
1637:     StackTop(stack,&e);
1638:     UpdateTS(ts,stack,e,stepnum,PETSC_TRUE);
1639:   }
1640:   if (!stack->solution_only) { /* whattodo must be 5 or 8 */
1641:     /* ask Revolve what to do next */
1642:     tjsch->rctx->oldcapo = tjsch->rctx->capo;
1643:     whattodo = revolve_action(&tjsch->rctx->check,&tjsch->rctx->capo,&tjsch->rctx->fine,tjsch->rctx->snaps_in,&tjsch->rctx->info,&tjsch->rctx->where); /* must return 1 or 3 or 4*/
1644:     printwhattodo(tj->monitor,whattodo,tjsch->rctx,shift);
1645:     if (whattodo == 3 || whattodo == 4) tjsch->rctx->reverseonestep = PETSC_TRUE;
1646:     if (whattodo == 1) tjsch->rctx->stepsleft = tjsch->rctx->capo-tjsch->rctx->oldcapo;
1647:     if (tj->monitor) {
1648:       PetscViewerASCIIAddTab(tj->monitor,((PetscObject)tj)->tablevel);
1649:       PetscViewerASCIIPrintf(tj->monitor,"Skip the step from %D to %D (stage values already checkpointed)\n",tjsch->rctx->oldcapo,tjsch->rctx->oldcapo+1);
1650:       PetscViewerASCIISubtractTab(tj->monitor,((PetscObject)tj)->tablevel);
1651:     }
1652:     if (!tjsch->rctx->reverseonestep && tjsch->rctx->stepsleft > 0) tjsch->rctx->stepsleft--;
1653:     restart++; /* skip one step */
1654:   }
1655:   if (stack->solution_only || (!stack->solution_only && restart < stepnum)) {
1656:     TurnForward(ts);
1657:     ReCompute(ts,tjsch,restart,stepnum);
1658:   }
1659:   if (!ondisk && ( (stack->solution_only && e->stepnum+1 == stepnum) || (!stack->solution_only && e->stepnum == stepnum))) {
1660:     StackPop(stack,&e);
1661:   }
1662:   tjsch->rctx->reverseonestep = PETSC_FALSE;
1663:   return(0);
1664: }
1665: #endif

1667: #if defined(PETSC_HAVE_CAMS)
1668: /* Optimal offline adjoint checkpointing for multistage time integration methods */
1669: static PetscErrorCode TSTrajectoryMemorySet_AOF(TSTrajectory tj,TS ts,TJScheduler *tjsch,PetscInt stepnum,PetscReal time,Vec X)
1670: {
1671:   Stack          *stack = &tjsch->stack;
1672:   StackElement   e;

1676:   /* skip if no checkpoint to use. This also avoids an error when num_units_avail=0  */
1677:   if (tjsch->actx->nextcheckpointstep == -1) return(0);
1678:   if (stepnum == 0) { /* When placing the first checkpoint, no need to change the units available */
1679:     if (stack->solution_only) {
1680:       offline_ca(tjsch->actx->lastcheckpointstep,tjsch->actx->num_units_avail,tjsch->actx->endstep,&tjsch->actx->nextcheckpointstep);
1681:     } else {
1682:       /* First two arguments must be -1 when first time calling cams */
1683:       offline_cams(tjsch->actx->lastcheckpointstep,tjsch->actx->lastcheckpointtype,tjsch->actx->num_units_avail,tjsch->actx->endstep,tjsch->actx->num_stages,&tjsch->actx->nextcheckpointstep,&tjsch->actx->nextcheckpointtype);
1684:     }
1685:   }

1687:   if (stack->solution_only && stepnum == tjsch->total_steps) return(0);

1689:   if (tjsch->actx->nextcheckpointstep == stepnum) {
1690:     if (stepnum < stack->top) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_MEMC,"Illegal modification of a non-top stack element");

1692:     if (tjsch->actx->nextcheckpointtype == 2) { /* solution + stage values */
1693:       if (tj->monitor) {
1694:         PetscViewerASCIIPrintf(tj->monitor,"Store in checkpoint number %D with stage values and solution (located in RAM)\n",stepnum);
1695:       }
1696:       ElementCreate(ts,SOLUTION_STAGES,stack,&e);
1697:       ElementSet(ts,stack,&e,stepnum,time,X);
1698:     }
1699:     if (tjsch->actx->nextcheckpointtype == 1) {
1700:       if (tj->monitor) {
1701:         PetscViewerASCIIPrintf(tj->monitor,"Store in checkpoint number %D with stage values (located in RAM)\n",stepnum);
1702:       }
1703:       ElementCreate(ts,STAGESONLY,stack,&e);
1704:       ElementSet(ts,stack,&e,stepnum,time,X);
1705:     }
1706:     if (tjsch->actx->nextcheckpointtype == 0) { /* solution only */
1707:       if (tj->monitor) {
1708:         PetscViewerASCIIPrintf(tj->monitor,"Store in checkpoint number %D (located in RAM)\n",stepnum);
1709:       }
1710:       ElementCreate(ts,SOLUTIONONLY,stack,&e);
1711:       ElementSet(ts,stack,&e,stepnum,time,X);
1712:     }
1713:     StackPush(stack,e);

1715:     tjsch->actx->lastcheckpointstep = stepnum;
1716:     if (stack->solution_only) {
1717:       offline_ca(tjsch->actx->lastcheckpointstep,tjsch->actx->num_units_avail,tjsch->actx->endstep,&tjsch->actx->nextcheckpointstep);
1718:       tjsch->actx->num_units_avail--;
1719:     } else {
1720:       tjsch->actx->lastcheckpointtype = tjsch->actx->nextcheckpointtype;
1721:       offline_cams(tjsch->actx->lastcheckpointstep,tjsch->actx->lastcheckpointtype,tjsch->actx->num_units_avail,tjsch->actx->endstep,tjsch->actx->num_stages,&tjsch->actx->nextcheckpointstep,&tjsch->actx->nextcheckpointtype);
1722:       if (tjsch->actx->lastcheckpointtype == 2) tjsch->actx->num_units_avail -= tjsch->actx->num_stages+1;
1723:       if (tjsch->actx->lastcheckpointtype == 1) tjsch->actx->num_units_avail -= tjsch->actx->num_stages;
1724:       if (tjsch->actx->lastcheckpointtype == 0) tjsch->actx->num_units_avail--;
1725:     }
1726:   }
1727:   return(0);
1728: }

1730: static PetscErrorCode TSTrajectoryMemoryGet_AOF(TSTrajectory tj,TS ts,TJScheduler *tjsch,PetscInt stepnum)
1731: {
1732:   Stack          *stack = &tjsch->stack;
1733:   StackElement   e;
1734:   PetscInt       estepnum;

1738:   if (stepnum == 0 || stepnum == tjsch->total_steps) {
1739:     TurnBackward(ts);
1740:     return(0);
1741:   }
1742:   /* Restore a checkpoint */
1743:   StackTop(stack,&e);
1744:   estepnum = e->stepnum;
1745:   if (estepnum == stepnum && e->cptype == SOLUTIONONLY) { /* discard the checkpoint if not useful (corner case) */
1746:     StackPop(stack,&e);
1747:     tjsch->actx->num_units_avail++;
1748:     StackTop(stack,&e);
1749:     estepnum = e->stepnum;
1750:   }
1751:   /* Update TS with stage values if an adjoint step can be taken immediately */
1752:   if (HaveStages(e->cptype)) {
1753:     if (tj->monitor) {
1754:       PetscViewerASCIIPrintf(tj->monitor,"Restore in checkpoint number %D with stage values (located in RAM)\n",e->stepnum);
1755:     }
1756:     if (e->cptype == STAGESONLY) tjsch->actx->num_units_avail += tjsch->actx->num_stages;
1757:     if (e->cptype == SOLUTION_STAGES) tjsch->actx->num_units_avail += tjsch->actx->num_stages+1;
1758:   } else {
1759:     if (tj->monitor) {
1760:       PetscViewerASCIIPrintf(tj->monitor,"Restore in checkpoint number %D (located in RAM)\n",e->stepnum);
1761:     }
1762:     tjsch->actx->num_units_avail++;
1763:   }
1764:   UpdateTS(ts,stack,e,stepnum,PETSC_TRUE);
1765:   /* Query the scheduler */
1766:   tjsch->actx->lastcheckpointstep = estepnum;
1767:   tjsch->actx->endstep = stepnum;
1768:   if (stack->solution_only) { /* start with restoring a checkpoint */
1769:     offline_ca(tjsch->actx->lastcheckpointstep,tjsch->actx->num_units_avail,tjsch->actx->endstep,&tjsch->actx->nextcheckpointstep);
1770:   } else { /* 2 revolve actions: restore a checkpoint and then advance */
1771:     tjsch->actx->lastcheckpointtype = e->cptype;
1772:     offline_cams(tjsch->actx->lastcheckpointstep,tjsch->actx->lastcheckpointtype,tjsch->actx->num_units_avail,tjsch->actx->endstep,tjsch->actx->num_stages,&tjsch->actx->nextcheckpointstep, &tjsch->actx->nextcheckpointtype);
1773:   }
1774:   /* Discard the checkpoint if not needed, decrease the number of available checkpoints if it still stays in stack */
1775:   if (HaveStages(e->cptype)) {
1776:     if (estepnum == stepnum) {
1777:       StackPop(stack,&e);
1778:     } else {
1779:       if (e->cptype == STAGESONLY) tjsch->actx->num_units_avail -= tjsch->actx->num_stages;
1780:       if (e->cptype == SOLUTION_STAGES) tjsch->actx->num_units_avail -= tjsch->actx->num_stages+1;
1781:     }
1782:   } else {
1783:     if (estepnum+1 == stepnum) {
1784:       StackPop(stack,&e);
1785:     } else {
1786:       tjsch->actx->num_units_avail--;
1787:     }
1788:   }
1789:   /* Recompute from the restored checkpoint */
1790:   if (stack->solution_only || (!stack->solution_only && estepnum < stepnum)) {
1791:     TurnForward(ts);
1792:     ReCompute(ts,tjsch,estepnum,stepnum);
1793:   }
1794:   return(0);
1795: }
1796: #endif

1798: static PetscErrorCode TSTrajectorySet_Memory(TSTrajectory tj,TS ts,PetscInt stepnum,PetscReal time,Vec X)
1799: {
1800:   TJScheduler *tjsch = (TJScheduler*)tj->data;

1804:   if (!tjsch->recompute) { /* use global stepnum in the forward sweep */
1805:     TSGetStepNumber(ts,&stepnum);
1806:   }
1807:   /* for consistency */
1808:   if (!tjsch->recompute && stepnum == 0) ts->ptime_prev = ts->ptime-ts->time_step;
1809:   switch (tjsch->stype) {
1810:     case NONE:
1811:       if (tj->adjoint_solve_mode) {
1812:         TSTrajectoryMemorySet_N(ts,tjsch,stepnum,time,X);
1813:       } else {
1814:         TSTrajectoryMemorySet_N_2(ts,tjsch,stepnum,time,X);
1815:       }
1816:       break;
1817:     case TWO_LEVEL_NOREVOLVE:
1818:       if (!tj->adjoint_solve_mode) SETERRQ(PetscObjectComm((PetscObject)tj),PETSC_ERR_SUP,"Not implemented");
1819:       TSTrajectoryMemorySet_TLNR(tj,ts,tjsch,stepnum,time,X);
1820:       break;
1821: #if defined(PETSC_HAVE_REVOLVE)
1822:     case TWO_LEVEL_REVOLVE:
1823:       if (!tj->adjoint_solve_mode) SETERRQ(PetscObjectComm((PetscObject)tj),PETSC_ERR_SUP,"Not implemented");
1824:       TSTrajectoryMemorySet_TLR(tj,ts,tjsch,stepnum,time,X);
1825:       break;
1826:     case TWO_LEVEL_TWO_REVOLVE:
1827:       if (!tj->adjoint_solve_mode) SETERRQ(PetscObjectComm((PetscObject)tj),PETSC_ERR_SUP,"Not implemented");
1828:       TSTrajectoryMemorySet_TLTR(tj,ts,tjsch,stepnum,time,X);
1829:       break;
1830:     case REVOLVE_OFFLINE:
1831:       if (!tj->adjoint_solve_mode) SETERRQ(PetscObjectComm((PetscObject)tj),PETSC_ERR_SUP,"Not implemented");
1832:       TSTrajectoryMemorySet_ROF(tj,ts,tjsch,stepnum,time,X);
1833:       break;
1834:     case REVOLVE_ONLINE:
1835:       if (!tj->adjoint_solve_mode) SETERRQ(PetscObjectComm((PetscObject)tj),PETSC_ERR_SUP,"Not implemented");
1836:       TSTrajectoryMemorySet_RON(tj,ts,tjsch,stepnum,time,X);
1837:       break;
1838:     case REVOLVE_MULTISTAGE:
1839:       if (!tj->adjoint_solve_mode) SETERRQ(PetscObjectComm((PetscObject)tj),PETSC_ERR_SUP,"Not implemented");
1840:       TSTrajectoryMemorySet_RMS(tj,ts,tjsch,stepnum,time,X);
1841:       break;
1842: #endif
1843: #if defined(PETSC_HAVE_CAMS)
1844:     case CAMS_OFFLINE:
1845:       if (!tj->adjoint_solve_mode) SETERRQ(PetscObjectComm((PetscObject)tj),PETSC_ERR_SUP,"Not implemented");
1846:       TSTrajectoryMemorySet_AOF(tj,ts,tjsch,stepnum,time,X);
1847:       break;
1848: #endif
1849:     default:
1850:       break;
1851:   }
1852:   return(0);
1853: }

1855: static PetscErrorCode TSTrajectoryGet_Memory(TSTrajectory tj,TS ts,PetscInt stepnum,PetscReal *t)
1856: {
1857:   TJScheduler *tjsch = (TJScheduler*)tj->data;

1861:   if (tj->adjoint_solve_mode && stepnum == 0) {
1862:     TSTrajectoryReset(tj); /* reset TSTrajectory so users do not need to reset TSTrajectory */
1863:     return(0);
1864:   }
1865:   switch (tjsch->stype) {
1866:     case NONE:
1867:       if (tj->adjoint_solve_mode) {
1868:         TSTrajectoryMemoryGet_N(ts,tjsch,stepnum);
1869:       } else {
1870:         TSTrajectoryMemoryGet_N_2(ts,tjsch,stepnum);
1871:       }
1872:       break;
1873:     case TWO_LEVEL_NOREVOLVE:
1874:       if (!tj->adjoint_solve_mode) SETERRQ(PetscObjectComm((PetscObject)tj),PETSC_ERR_SUP,"Not implemented");
1875:       TSTrajectoryMemoryGet_TLNR(tj,ts,tjsch,stepnum);
1876:       break;
1877: #if defined(PETSC_HAVE_REVOLVE)
1878:     case TWO_LEVEL_REVOLVE:
1879:       if (!tj->adjoint_solve_mode) SETERRQ(PetscObjectComm((PetscObject)tj),PETSC_ERR_SUP,"Not implemented");
1880:       TSTrajectoryMemoryGet_TLR(tj,ts,tjsch,stepnum);
1881:       break;
1882:     case TWO_LEVEL_TWO_REVOLVE:
1883:       if (!tj->adjoint_solve_mode) SETERRQ(PetscObjectComm((PetscObject)tj),PETSC_ERR_SUP,"Not implemented");
1884:       TSTrajectoryMemoryGet_TLTR(tj,ts,tjsch,stepnum);
1885:       break;
1886:     case REVOLVE_OFFLINE:
1887:       if (!tj->adjoint_solve_mode) SETERRQ(PetscObjectComm((PetscObject)tj),PETSC_ERR_SUP,"Not implemented");
1888:       TSTrajectoryMemoryGet_ROF(tj,ts,tjsch,stepnum);
1889:       break;
1890:     case REVOLVE_ONLINE:
1891:       if (!tj->adjoint_solve_mode) SETERRQ(PetscObjectComm((PetscObject)tj),PETSC_ERR_SUP,"Not implemented");
1892:       TSTrajectoryMemoryGet_RON(tj,ts,tjsch,stepnum);
1893:       break;
1894:     case REVOLVE_MULTISTAGE:
1895:       if (!tj->adjoint_solve_mode) SETERRQ(PetscObjectComm((PetscObject)tj),PETSC_ERR_SUP,"Not implemented");
1896:       TSTrajectoryMemoryGet_RMS(tj,ts,tjsch,stepnum);
1897:       break;
1898: #endif
1899: #if defined(PETSC_HAVE_CAMS)
1900:     case CAMS_OFFLINE:
1901:       if (!tj->adjoint_solve_mode) SETERRQ(PetscObjectComm((PetscObject)tj),PETSC_ERR_SUP,"Not implemented");
1902:       TSTrajectoryMemoryGet_AOF(tj,ts,tjsch,stepnum);
1903:       break;
1904: #endif
1905:     default:
1906:       break;
1907:   }
1908:   return(0);
1909: }

1911: PETSC_UNUSED static PetscErrorCode TSTrajectorySetStride_Memory(TSTrajectory tj,PetscInt stride)
1912: {
1913:   TJScheduler *tjsch = (TJScheduler*)tj->data;

1916:   tjsch->stride = stride;
1917:   return(0);
1918: }

1920: static PetscErrorCode TSTrajectorySetMaxCpsRAM_Memory(TSTrajectory tj,PetscInt max_cps_ram)
1921: {
1922:   TJScheduler *tjsch = (TJScheduler*)tj->data;

1925:   tjsch->max_cps_ram = max_cps_ram;
1926:   return(0);
1927: }

1929: static PetscErrorCode TSTrajectorySetMaxCpsDisk_Memory(TSTrajectory tj,PetscInt max_cps_disk)
1930: {
1931:   TJScheduler *tjsch = (TJScheduler*)tj->data;

1934:   tjsch->max_cps_disk = max_cps_disk;
1935:   return(0);
1936: }

1938: static PetscErrorCode TSTrajectorySetMaxUnitsRAM_Memory(TSTrajectory tj,PetscInt max_units_ram)
1939: {
1940:   TJScheduler *tjsch = (TJScheduler*)tj->data;

1943:   if (!tjsch->max_cps_ram) SETERRQ(PetscObjectComm((PetscObject)tj),PETSC_ERR_ARG_INCOMP,"Conflict with -ts_trjaectory_max_cps_ram or TSTrajectorySetMaxCpsRAM. You can set max_cps_ram or max_units_ram, but not both at the same time.");
1944:   tjsch->max_units_ram = max_units_ram;
1945:   return(0);
1946: }

1948: static PetscErrorCode TSTrajectorySetMaxUnitsDisk_Memory(TSTrajectory tj,PetscInt max_units_disk)
1949: {
1950:   TJScheduler *tjsch = (TJScheduler*)tj->data;

1953:   if (!tjsch->max_cps_disk) SETERRQ(PetscObjectComm((PetscObject)tj),PETSC_ERR_ARG_INCOMP,"Conflict with -ts_trjaectory_max_cps_disk or TSTrajectorySetMaxCpsDisk. You can set max_cps_disk or max_units_disk, but not both at the same time.");
1954:   tjsch->max_units_ram = max_units_disk;
1955:   return(0);
1956: }

1958: static PetscErrorCode TSTrajectoryMemorySetType_Memory(TSTrajectory tj,TSTrajectoryMemoryType tj_memory_type)
1959: {
1960:   TJScheduler *tjsch = (TJScheduler*)tj->data;

1963:   if (tj->setupcalled) SETERRQ(PetscObjectComm((PetscObject)tj),PETSC_ERR_ARG_WRONGSTATE,"Cannot change schedule software after TSTrajectory has been setup or used");
1964:   tjsch->tj_memory_type = tj_memory_type;
1965:   return(0);
1966: }

1968: #if defined(PETSC_HAVE_REVOLVE)
1969: PETSC_UNUSED static PetscErrorCode TSTrajectorySetRevolveOnline(TSTrajectory tj,PetscBool use_online)
1970: {
1971:   TJScheduler *tjsch = (TJScheduler*)tj->data;

1974:   tjsch->use_online = use_online;
1975:   return(0);
1976: }
1977: #endif

1979: PETSC_UNUSED static PetscErrorCode TSTrajectorySetSaveStack(TSTrajectory tj,PetscBool save_stack)
1980: {
1981:   TJScheduler *tjsch = (TJScheduler*)tj->data;

1984:   tjsch->save_stack = save_stack;
1985:   return(0);
1986: }

1988: PETSC_UNUSED static PetscErrorCode TSTrajectorySetUseDRAM(TSTrajectory tj,PetscBool use_dram)
1989: {
1990:   TJScheduler *tjsch = (TJScheduler*)tj->data;

1993:   tjsch->stack.use_dram = use_dram;
1994:   return(0);
1995: }

1997: /*@C
1998:    TSTrajectoryMemorySetType - sets the software that is used to generate the checkpointing schedule.

2000:    Logically Collective on TSTrajectory

2002:    Input Parameters:
2003: +  tj - the TSTrajectory context
2004: -  tj_memory_type - Revolve or CAMS

2006:    Options Database Key:
2007: .  -ts_trajectory_memory_type <tj_memory_type> - petsc, revolve, cams

2009:    Level: intermediate

2011:    Note:
2012:      By default this will use Revolve if it exists
2013: @*/
2014: PetscErrorCode TSTrajectoryMemorySetType(TSTrajectory tj,TSTrajectoryMemoryType tj_memory_type)
2015: {

2019:   PetscTryMethod(tj,"TSTrajectoryMemorySetType_C",(TSTrajectory,TSTrajectoryMemoryType),(tj,tj_memory_type));
2020:   return(0);
2021: }

2023: /*@C
2024:   TSTrajectorySetMaxCpsRAM - Set maximum number of checkpoints in RAM

2026:   Logically collective

2028:   Input Parameter:
2029: .  tj - tstrajectory context

2031:   Output Parameter:
2032: .  max_cps_ram - maximum number of checkpoints in RAM

2034:   Level: intermediate

2036: .seealso: TSTrajectorySetMaxUnitsRAM()
2037: @*/
2038: PetscErrorCode TSTrajectorySetMaxCpsRAM(TSTrajectory tj,PetscInt max_cps_ram)
2039: {

2043:   PetscUseMethod(tj,"TSTrajectorySetMaxCpsRAM_C",(TSTrajectory,PetscInt),(tj,max_cps_ram));
2044:   return(0);
2045: }

2047: /*@C
2048:   TSTrajectorySetMaxCpsDisk - Set maximum number of checkpoints on disk

2050:   Logically collective

2052:   Input Parameter:
2053: .  tj - tstrajectory context

2055:   Output Parameter:
2056: .  max_cps_disk - maximum number of checkpoints on disk

2058:   Level: intermediate

2060: .seealso: TSTrajectorySetMaxUnitsDisk(), TSTrajectorySetMaxUnitsRAM()
2061: @*/
2062: PetscErrorCode TSTrajectorySetMaxCpsDisk(TSTrajectory tj,PetscInt max_cps_disk)
2063: {

2067:   PetscUseMethod(tj,"TSTrajectorySetMaxCpsDisk_C",(TSTrajectory,PetscInt),(tj,max_cps_disk));
2068:   return(0);
2069: }

2071: /*@C
2072:   TSTrajectorySetMaxUnitsRAM - Set maximum number of checkpointing units in RAM

2074:   Logically collective

2076:   Input Parameter:
2077: .  tj - tstrajectory context

2079:   Output Parameter:
2080: .  max_units_ram - maximum number of checkpointing units in RAM

2082:   Level: intermediate

2084: .seealso: TSTrajectorySetMaxCpsRAM()
2085: @*/
2086: PetscErrorCode TSTrajectorySetMaxUnitsRAM(TSTrajectory tj,PetscInt max_units_ram)
2087: {

2091:   PetscUseMethod(tj,"TSTrajectorySetMaxUnitsRAM_C",(TSTrajectory,PetscInt),(tj,max_units_ram));
2092:   return(0);
2093: }

2095: /*@C
2096:   TSTrajectorySetMaxUnitsDisk - Set maximum number of checkpointing units on disk

2098:   Logically collective

2100:   Input Parameter:
2101: .  tj - tstrajectory context

2103:   Output Parameter:
2104: .  max_units_disk - maximum number of checkpointing units on disk

2106:   Level: intermediate

2108: .seealso: TSTrajectorySetMaxCpsDisk()
2109: @*/
2110: PetscErrorCode TSTrajectorySetMaxUnitsDisk(TSTrajectory tj,PetscInt max_units_disk)
2111: {

2115:   PetscUseMethod(tj,"TSTrajectorySetMaxUnitsDisk_C",(TSTrajectory,PetscInt),(tj,max_units_disk));
2116:   return(0);
2117: }

2119: static PetscErrorCode TSTrajectorySetFromOptions_Memory(PetscOptionItems *PetscOptionsObject,TSTrajectory tj)
2120: {
2121:   TJScheduler    *tjsch = (TJScheduler*)tj->data;
2122:   PetscEnum      etmp;
2123:   PetscInt       max_cps_ram,max_cps_disk,max_units_ram,max_units_disk;
2124:   PetscBool      flg;

2128:   PetscOptionsHead(PetscOptionsObject,"Memory based TS trajectory options");
2129:   {
2130:     PetscOptionsInt("-ts_trajectory_max_cps_ram","Maximum number of checkpoints in RAM","TSTrajectorySetMaxCpsRAM",tjsch->max_cps_ram,&max_cps_ram,&flg);
2131:     if (flg) {
2132:       TSTrajectorySetMaxCpsRAM(tj,max_cps_ram);
2133:     }
2134:     PetscOptionsInt("-ts_trajectory_max_cps_disk","Maximum number of checkpoints on disk","TSTrajectorySetMaxCpsDisk",tjsch->max_cps_disk,&max_cps_disk,&flg);
2135:     if (flg) {
2136:       TSTrajectorySetMaxCpsDisk(tj,max_cps_disk);
2137:     }
2138:     PetscOptionsInt("-ts_trajectory_max_units_ram","Maximum number of checkpointing units in RAM","TSTrajectorySetMaxUnitsRAM",tjsch->max_units_ram,&max_units_ram,&flg);
2139:     if (flg) {
2140:       TSTrajectorySetMaxUnitsRAM(tj,max_units_ram);
2141:     }
2142:     PetscOptionsInt("-ts_trajectory_max_units_disk","Maximum number of checkpointing units on disk","TSTrajectorySetMaxUnitsDisk",tjsch->max_units_disk,&max_units_disk,&flg);
2143:     if (flg) {
2144:       TSTrajectorySetMaxUnitsDisk(tj,max_units_disk);
2145:     }
2146:     PetscOptionsInt("-ts_trajectory_stride","Stride to save checkpoints to file","TSTrajectorySetStride",tjsch->stride,&tjsch->stride,NULL);
2147: #if defined(PETSC_HAVE_REVOLVE)
2148:     PetscOptionsBool("-ts_trajectory_revolve_online","Trick TS trajectory into using online mode of revolve","TSTrajectorySetRevolveOnline",tjsch->use_online,&tjsch->use_online,NULL);
2149: #endif
2150:     PetscOptionsBool("-ts_trajectory_save_stack","Save all stack to disk","TSTrajectorySetSaveStack",tjsch->save_stack,&tjsch->save_stack,NULL);
2151:     PetscOptionsBool("-ts_trajectory_use_dram","Use DRAM for checkpointing","TSTrajectorySetUseDRAM",tjsch->stack.use_dram,&tjsch->stack.use_dram,NULL);
2152:     PetscOptionsEnum("-ts_trajectory_memory_type","Checkpointing scchedule software to use","TSTrajectoryMemorySetType",TSTrajectoryMemoryTypes,(PetscEnum)(int)(tjsch->tj_memory_type),&etmp,&flg);
2153:     if (flg) {
2154:       TSTrajectoryMemorySetType(tj,(TSTrajectoryMemoryType)etmp);
2155:     }
2156:   }
2157:   PetscOptionsTail();
2158:   return(0);
2159: }

2161: static PetscErrorCode TSTrajectorySetUp_Memory(TSTrajectory tj,TS ts)
2162: {
2163:   TJScheduler    *tjsch = (TJScheduler*)tj->data;
2164:   Stack          *stack = &tjsch->stack;
2165: #if defined(PETSC_HAVE_REVOLVE)
2166:   RevolveCTX     *rctx,*rctx2;
2167:   DiskStack      *diskstack = &tjsch->diskstack;
2168:   PetscInt       diskblocks;
2169: #endif
2170:   PetscInt       numY,total_steps;
2171:   PetscBool      fixedtimestep;

2175:   if (ts->adapt) {
2176:     PetscObjectTypeCompare((PetscObject)ts->adapt,TSADAPTNONE,&fixedtimestep);
2177:   } else {
2178:     fixedtimestep = PETSC_TRUE;
2179:   }
2180:   total_steps = (PetscInt)(PetscCeilReal((ts->max_time-ts->ptime)/ts->time_step));
2181:   total_steps = total_steps < 0 ? PETSC_MAX_INT : total_steps;
2182:   if (fixedtimestep) tjsch->total_steps = PetscMin(ts->max_steps,total_steps);

2184:   tjsch->stack.solution_only = tj->solution_only;
2185:   TSGetStages(ts,&numY,PETSC_IGNORE);
2186:   if (stack->solution_only) {
2187:     if (tjsch->max_units_ram) tjsch->max_cps_ram = tjsch->max_units_ram;
2188:     else tjsch->max_units_ram = tjsch->max_cps_ram;
2189:     if (tjsch->max_units_disk) tjsch->max_cps_disk = tjsch->max_units_disk;
2190:   } else {
2191:     if (tjsch->max_units_ram) tjsch->max_cps_ram = (ts->stifflyaccurate) ? tjsch->max_units_ram/numY : tjsch->max_units_ram/(numY+1);
2192:     else tjsch->max_units_ram = (ts->stifflyaccurate) ? numY*tjsch->max_cps_ram : (numY+1)*tjsch->max_cps_ram;
2193:     if (tjsch->max_units_disk) tjsch->max_cps_disk = (ts->stifflyaccurate) ? tjsch->max_units_disk/numY : tjsch->max_units_disk/(numY+1);
2194:     else tjsch->max_units_disk = (ts->stifflyaccurate) ? numY*tjsch->max_cps_disk : (numY+1)*tjsch->max_cps_disk;
2195:   }
2196:   if (tjsch->max_cps_ram > 0) stack->stacksize = tjsch->max_units_ram; /* maximum stack size. Could be overallocated. */

2198:   /* Determine the scheduler type */
2199:   if (tjsch->stride > 1) { /* two level mode */
2200:     if (tjsch->save_stack && tjsch->max_cps_disk > 1 && tjsch->max_cps_disk <= tjsch->max_cps_ram) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_ARG_INCOMP,"The specified disk capacity is not enough to store a full stack of RAM checkpoints. You might want to change the disk capacity or use single level checkpointing instead.");
2201:     if (tjsch->max_cps_disk <= 1 && tjsch->max_cps_ram > 1 && tjsch->max_cps_ram <= tjsch->stride-1) tjsch->stype = TWO_LEVEL_REVOLVE; /* use revolve_offline for each stride */
2202:     if (tjsch->max_cps_disk > 1 && tjsch->max_cps_ram > 1 && tjsch->max_cps_ram <= tjsch->stride-1) tjsch->stype = TWO_LEVEL_TWO_REVOLVE;  /* use revolve_offline for each stride */
2203:     if (tjsch->max_cps_disk <= 1 && (tjsch->max_cps_ram >= tjsch->stride || tjsch->max_cps_ram == -1)) tjsch->stype = TWO_LEVEL_NOREVOLVE; /* can also be handled by TWO_LEVEL_REVOLVE */
2204:   } else { /* single level mode */
2205:     if (fixedtimestep) {
2206:       if (tjsch->max_cps_ram >= tjsch->total_steps-1 || tjsch->max_cps_ram == -1)
2207:         tjsch->stype = NONE; /* checkpoint all */
2208:       else { /* choose the schedule software for offline checkpointing */
2209:         switch (tjsch->tj_memory_type) {
2210:           case TJ_PETSC:
2211:             tjsch->stype = NONE;
2212:             break;
2213:           case TJ_CAMS:
2214:             tjsch->stype = CAMS_OFFLINE;
2215:             break;
2216:           case TJ_REVOLVE:
2217:             tjsch->stype = (tjsch->max_cps_disk>1) ? REVOLVE_MULTISTAGE : REVOLVE_OFFLINE;
2218:             break;
2219:           default:
2220:             break;
2221:         }
2222:       }
2223:     } else tjsch->stype = NONE; /* checkpoint all for adaptive time step */
2224: #if defined(PETSC_HAVE_REVOLVE)
2225:     if (tjsch->use_online) tjsch->stype = REVOLVE_ONLINE; /* trick into online (for testing purpose only) */
2226: #endif
2227:     if (tjsch->stype != NONE && tjsch->max_cps_ram < 1 && tjsch->max_cps_disk < 1) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_ARG_INCOMP,"The specified storage capacity is insufficient for one checkpoint, which is the minimum");
2228:   }
2229:   if (tjsch->stype >= CAMS_OFFLINE) {
2230: #ifndef PETSC_HAVE_CAMS
2231:     SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"CAMS is needed when there is not enough memory to checkpoint all time steps according to the user's settings, please reconfigure with the additional option --download-cams.");
2232: #else
2233:     CAMSCTX  *actx;
2234:     PetscInt ns = 0;
2235:     if (stack->solution_only) {
2236:       offline_ca_create(tjsch->total_steps,tjsch->max_cps_ram);
2237:     } else {
2238:       TSGetStages(ts,&ns,PETSC_IGNORE);
2239:       offline_cams_create(tjsch->total_steps,tjsch->max_units_ram,ns,ts->stifflyaccurate);
2240:     }
2241:     PetscNew(&actx);
2242:     actx->lastcheckpointstep    = -1; /* -1 can trigger the initialization of CAMS */
2243:     actx->lastcheckpointtype    = -1; /* -1 can trigger the initialization of CAMS */
2244:     actx->endstep               = tjsch->total_steps;
2245:     actx->num_units_avail       = tjsch->max_units_ram;
2246:     actx->num_stages            = ns;
2247:     tjsch->actx                 = actx;
2248: #endif
2249:   } else if (tjsch->stype > TWO_LEVEL_NOREVOLVE) {
2250: #ifndef PETSC_HAVE_REVOLVE
2251:     SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"revolve is needed when there is not enough memory to checkpoint all time steps according to the user's settings, please reconfigure with the additional option --download-revolve.");
2252: #else
2253:     PetscRevolveInt rfine,rsnaps,rsnaps2;

2255:     switch (tjsch->stype) {
2256:       case TWO_LEVEL_REVOLVE:
2257:         PetscRevolveIntCast(tjsch->stride,&rfine);
2258:         PetscRevolveIntCast(tjsch->max_cps_ram,&rsnaps);
2259:         revolve_create_offline(rfine,rsnaps);
2260:         break;
2261:       case TWO_LEVEL_TWO_REVOLVE:
2262:         diskblocks = tjsch->save_stack ? tjsch->max_cps_disk/(tjsch->max_cps_ram+1) : tjsch->max_cps_disk; /* The block size depends on whether the stack is saved. */
2263:         diskstack->stacksize = diskblocks;
2264:         PetscRevolveIntCast(tjsch->stride,&rfine);
2265:         PetscRevolveIntCast(tjsch->max_cps_ram,&rsnaps);
2266:         revolve_create_offline(rfine,rsnaps);
2267:         PetscRevolveIntCast((tjsch->total_steps+tjsch->stride-1)/tjsch->stride,&rfine);
2268:         PetscRevolveIntCast(diskblocks,&rsnaps);
2269:         revolve2_create_offline(rfine,rsnaps);
2270:         PetscNew(&rctx2);
2271:         rctx2->snaps_in       = rsnaps;
2272:         rctx2->reverseonestep = PETSC_FALSE;
2273:         rctx2->check          = 0;
2274:         rctx2->oldcapo        = 0;
2275:         rctx2->capo           = 0;
2276:         rctx2->info           = 2;
2277:         rctx2->fine           = rfine;
2278:         tjsch->rctx2          = rctx2;
2279:         diskstack->top        = -1;
2280:         PetscMalloc1(diskstack->stacksize*sizeof(PetscInt),&diskstack->container);
2281:         break;
2282:       case REVOLVE_OFFLINE:
2283:         PetscRevolveIntCast(tjsch->total_steps,&rfine);
2284:         PetscRevolveIntCast(tjsch->max_cps_ram,&rsnaps);
2285:         revolve_create_offline(rfine,rsnaps);
2286:         break;
2287:       case REVOLVE_ONLINE:
2288:         stack->stacksize = tjsch->max_cps_ram;
2289:         PetscRevolveIntCast(tjsch->max_cps_ram,&rsnaps);
2290:         revolve_create_online(rsnaps);
2291:         break;
2292:       case REVOLVE_MULTISTAGE:
2293:         PetscRevolveIntCast(tjsch->total_steps,&rfine);
2294:         PetscRevolveIntCast(tjsch->max_cps_ram,&rsnaps);
2295:         PetscRevolveIntCast(tjsch->max_cps_ram+tjsch->max_cps_disk,&rsnaps2);
2296:         revolve_create_multistage(rfine,rsnaps2,rsnaps);
2297:         break;
2298:       default:
2299:         break;
2300:     }
2301:     PetscNew(&rctx);
2302:     PetscRevolveIntCast(tjsch->max_cps_ram,&rsnaps);
2303:     rctx->snaps_in       = rsnaps; /* for theta methods snaps_in=2*max_cps_ram */
2304:     rctx->reverseonestep = PETSC_FALSE;
2305:     rctx->check          = 0;
2306:     rctx->oldcapo        = 0;
2307:     rctx->capo           = 0;
2308:     rctx->info           = 2;
2309:     if (tjsch->stride > 1) {
2310:       PetscRevolveIntCast(tjsch->stride,&rfine);
2311:     } else {
2312:       PetscRevolveIntCast(tjsch->total_steps,&rfine);
2313:     }
2314:     rctx->fine           = rfine;
2315:     tjsch->rctx          = rctx;
2316:     if (tjsch->stype == REVOLVE_ONLINE) rctx->fine = -1;
2317: #endif
2318:   } else {
2319:     if (tjsch->stype == TWO_LEVEL_NOREVOLVE) stack->stacksize = tjsch->stride-1; /* need tjsch->stride-1 at most */
2320:     if (tjsch->stype == NONE) {
2321:       if (fixedtimestep) stack->stacksize = stack->solution_only ? tjsch->total_steps : tjsch->total_steps-1;
2322:       else { /* adaptive time step */
2323:         /* if max_cps_ram is not specified, use maximal allowed number of steps for stack size */
2324:         if (tjsch->max_cps_ram == -1) stack->stacksize = ts->max_steps < PETSC_MAX_INT ? ts->max_steps : 10000;
2325:         tjsch->total_steps = stack->solution_only ? stack->stacksize : stack->stacksize+1; /* will be updated as time integration advances */
2326:       }
2327:     }
2328:   }

2330:   if ((tjsch->stype >= TWO_LEVEL_NOREVOLVE && tjsch->stype < REVOLVE_OFFLINE) || tjsch->stype == REVOLVE_MULTISTAGE) { /* these types need to use disk */
2331:     TSTrajectorySetUp_Basic(tj,ts);
2332:   }

2334:   stack->stacksize = PetscMax(stack->stacksize,1);
2335:   tjsch->recompute = PETSC_FALSE;
2336:   StackInit(stack,stack->stacksize,numY);
2337:   return(0);
2338: }

2340: static PetscErrorCode TSTrajectoryReset_Memory(TSTrajectory tj)
2341: {
2342: #if defined (PETSC_HAVE_REVOLVE) || defined (PETSC_HAVE_CAMS)
2343:   TJScheduler    *tjsch = (TJScheduler*)tj->data;
2345: #endif

2348: #if defined(PETSC_HAVE_REVOLVE)
2349:   if (tjsch->stype > TWO_LEVEL_NOREVOLVE) {
2350:     revolve_reset();
2351:     if (tjsch->stype == TWO_LEVEL_TWO_REVOLVE) {
2352:       revolve2_reset();
2353:       PetscFree(tjsch->diskstack.container);
2354:     }
2355:   }
2356:   if (tjsch->stype > TWO_LEVEL_NOREVOLVE) {
2357:     PetscFree(tjsch->rctx);
2358:     PetscFree(tjsch->rctx2);
2359:   }
2360: #endif
2361: #if defined(PETSC_HAVE_CAMS)
2362:   if (tjsch->stype == CAMS_OFFLINE) {
2363:     if (tjsch->stack.solution_only) offline_ca_destroy();
2364:     else offline_ca_destroy();
2365:     PetscFree(tjsch->actx);
2366:   }
2367: #endif
2368:   return(0);
2369: }

2371: static PetscErrorCode TSTrajectoryDestroy_Memory(TSTrajectory tj)
2372: {
2373:   TJScheduler    *tjsch = (TJScheduler*)tj->data;

2377:   StackDestroy(&tjsch->stack);
2378:   PetscViewerDestroy(&tjsch->viewer);
2379:   PetscObjectComposeFunction((PetscObject)tj,"TSTrajectorySetMaxCpsRAM_C",NULL);
2380:   PetscObjectComposeFunction((PetscObject)tj,"TSTrajectorySetMaxCpsDisk_C",NULL);
2381:   PetscObjectComposeFunction((PetscObject)tj,"TSTrajectorySetMaxUnitsRAM_C",NULL);
2382:   PetscObjectComposeFunction((PetscObject)tj,"TSTrajectorySetMaxUnitsDisk_C",NULL);
2383:   PetscObjectComposeFunction((PetscObject)tj,"TSTrajectoryMemorySetType_C",NULL);
2384:   PetscFree(tjsch);
2385:   return(0);
2386: }

2388: /*MC
2389:       TSTRAJECTORYMEMORY - Stores each solution of the ODE/ADE in memory

2391:   Level: intermediate

2393: .seealso:  TSTrajectoryCreate(), TS, TSTrajectorySetType()

2395: M*/
2396: PETSC_EXTERN PetscErrorCode TSTrajectoryCreate_Memory(TSTrajectory tj,TS ts)
2397: {
2398:   TJScheduler    *tjsch;

2402:   tj->ops->set            = TSTrajectorySet_Memory;
2403:   tj->ops->get            = TSTrajectoryGet_Memory;
2404:   tj->ops->setup          = TSTrajectorySetUp_Memory;
2405:   tj->ops->setfromoptions = TSTrajectorySetFromOptions_Memory;
2406:   tj->ops->reset          = TSTrajectoryReset_Memory;
2407:   tj->ops->destroy        = TSTrajectoryDestroy_Memory;

2409:   PetscNew(&tjsch);
2410:   tjsch->stype        = NONE;
2411:   tjsch->max_cps_ram  = -1; /* -1 indicates that it is not set */
2412:   tjsch->max_cps_disk = -1; /* -1 indicates that it is not set */
2413:   tjsch->stride       = 0; /* if not zero, two-level checkpointing will be used */
2414: #if defined(PETSC_HAVE_REVOLVE)
2415:   tjsch->use_online   = PETSC_FALSE;
2416: #endif
2417:   tjsch->save_stack   = PETSC_TRUE;

2419:   tjsch->stack.solution_only = tj->solution_only;
2420:   PetscViewerCreate(PetscObjectComm((PetscObject)tj),&tjsch->viewer);
2421:   PetscViewerSetType(tjsch->viewer,PETSCVIEWERBINARY);
2422:   PetscViewerPushFormat(tjsch->viewer,PETSC_VIEWER_NATIVE);
2423:   PetscViewerFileSetMode(tjsch->viewer,FILE_MODE_WRITE);

2425:   PetscObjectComposeFunction((PetscObject)tj,"TSTrajectorySetMaxCpsRAM_C",TSTrajectorySetMaxCpsRAM_Memory);
2426:   PetscObjectComposeFunction((PetscObject)tj,"TSTrajectorySetMaxCpsDisk_C",TSTrajectorySetMaxCpsDisk_Memory);
2427:   PetscObjectComposeFunction((PetscObject)tj,"TSTrajectorySetMaxUnitsRAM_C",TSTrajectorySetMaxUnitsRAM_Memory);
2428:   PetscObjectComposeFunction((PetscObject)tj,"TSTrajectorySetMaxUnitsDisk_C",TSTrajectorySetMaxUnitsDisk_Memory);
2429:   PetscObjectComposeFunction((PetscObject)tj,"TSTrajectoryMemorySetType_C",TSTrajectoryMemorySetType_Memory);
2430:   tj->data = tjsch;
2431:   return(0);
2432: }