Actual source code: ts.c

petsc-3.7.3 2016-07-24
Report Typos and Errors
  2: #include <petsc/private/tsimpl.h>        /*I "petscts.h"  I*/
  3: #include <petscdmshell.h>
  4: #include <petscdmda.h>
  5: #include <petscviewer.h>
  6: #include <petscdraw.h>

  8: /* Logging support */
  9: PetscClassId  TS_CLASSID, DMTS_CLASSID;
 10: PetscLogEvent TS_AdjointStep, TS_Step, TS_PseudoComputeTimeStep, TS_FunctionEval, TS_JacobianEval;

 12: const char *const TSExactFinalTimeOptions[] = {"UNSPECIFIED","STEPOVER","INTERPOLATE","MATCHSTEP","TSExactFinalTimeOption","TS_EXACTFINALTIME_",0};

 14: struct _n_TSMonitorDrawCtx {
 15:   PetscViewer   viewer;
 16:   Vec           initialsolution;
 17:   PetscBool     showinitial;
 18:   PetscInt      howoften;  /* when > 0 uses step % howoften, when negative only final solution plotted */
 19:   PetscBool     showtimestepandtime;
 20: };

 24: /*@C
 25:    TSMonitorSetFromOptions - Sets a monitor function and viewer appropriate for the type indicated by the user

 27:    Collective on TS

 29:    Input Parameters:
 30: +  ts - TS object you wish to monitor
 31: .  name - the monitor type one is seeking
 32: .  help - message indicating what monitoring is done
 33: .  manual - manual page for the monitor
 34: .  monitor - the monitor function
 35: -  monitorsetup - a function that is called once ONLY if the user selected this monitor that may set additional features of the TS or PetscViewer objects

 37:    Level: developer

 39: .seealso: PetscOptionsGetViewer(), PetscOptionsGetReal(), PetscOptionsHasName(), PetscOptionsGetString(),
 40:           PetscOptionsGetIntArray(), PetscOptionsGetRealArray(), PetscOptionsBool()
 41:           PetscOptionsInt(), PetscOptionsString(), PetscOptionsReal(), PetscOptionsBool(),
 42:           PetscOptionsName(), PetscOptionsBegin(), PetscOptionsEnd(), PetscOptionsHead(),
 43:           PetscOptionsStringArray(),PetscOptionsRealArray(), PetscOptionsScalar(),
 44:           PetscOptionsBoolGroupBegin(), PetscOptionsBoolGroup(), PetscOptionsBoolGroupEnd(),
 45:           PetscOptionsFList(), PetscOptionsEList()
 46: @*/
 47: PetscErrorCode  TSMonitorSetFromOptions(TS ts,const char name[],const char help[], const char manual[],PetscErrorCode (*monitor)(TS,PetscInt,PetscReal,Vec,PetscViewerAndFormat*),PetscErrorCode (*monitorsetup)(TS,PetscViewerAndFormat*))
 48: {
 49:   PetscErrorCode    ierr;
 50:   PetscViewer       viewer;
 51:   PetscViewerFormat format;
 52:   PetscBool         flg;

 55:   PetscOptionsGetViewer(PetscObjectComm((PetscObject)ts),((PetscObject)ts)->prefix,name,&viewer,&format,&flg);
 56:   if (flg) {
 57:     PetscViewerAndFormat *vf;
 58:     PetscViewerAndFormatCreate(viewer,format,&vf);
 59:     PetscObjectDereference((PetscObject)viewer);
 60:     if (monitorsetup) {
 61:       (*monitorsetup)(ts,vf);
 62:     }
 63:     TSMonitorSet(ts,(PetscErrorCode (*)(TS,PetscInt,PetscReal,Vec,void*))monitor,vf,(PetscErrorCode (*)(void**))PetscViewerAndFormatDestroy);
 64:   }
 65:   return(0);
 66: }

 70: /*@C
 71:    TSAdjointMonitorSetFromOptions - Sets a monitor function and viewer appropriate for the type indicated by the user

 73:    Collective on TS

 75:    Input Parameters:
 76: +  ts - TS object you wish to monitor
 77: .  name - the monitor type one is seeking
 78: .  help - message indicating what monitoring is done
 79: .  manual - manual page for the monitor
 80: .  monitor - the monitor function
 81: -  monitorsetup - a function that is called once ONLY if the user selected this monitor that may set additional features of the TS or PetscViewer objects

 83:    Level: developer

 85: .seealso: PetscOptionsGetViewer(), PetscOptionsGetReal(), PetscOptionsHasName(), PetscOptionsGetString(),
 86:           PetscOptionsGetIntArray(), PetscOptionsGetRealArray(), PetscOptionsBool()
 87:           PetscOptionsInt(), PetscOptionsString(), PetscOptionsReal(), PetscOptionsBool(),
 88:           PetscOptionsName(), PetscOptionsBegin(), PetscOptionsEnd(), PetscOptionsHead(),
 89:           PetscOptionsStringArray(),PetscOptionsRealArray(), PetscOptionsScalar(),
 90:           PetscOptionsBoolGroupBegin(), PetscOptionsBoolGroup(), PetscOptionsBoolGroupEnd(),
 91:           PetscOptionsFList(), PetscOptionsEList()
 92: @*/
 93: PetscErrorCode  TSAdjointMonitorSetFromOptions(TS ts,const char name[],const char help[], const char manual[],PetscErrorCode (*monitor)(TS,PetscInt,PetscReal,Vec,PetscInt,Vec*,Vec*,PetscViewerAndFormat*),PetscErrorCode (*monitorsetup)(TS,PetscViewerAndFormat*))
 94: {
 95:   PetscErrorCode    ierr;
 96:   PetscViewer       viewer;
 97:   PetscViewerFormat format;
 98:   PetscBool         flg;

101:   PetscOptionsGetViewer(PetscObjectComm((PetscObject)ts),((PetscObject)ts)->prefix,name,&viewer,&format,&flg);
102:   if (flg) {
103:     PetscViewerAndFormat *vf;
104:     PetscViewerAndFormatCreate(viewer,format,&vf);
105:     PetscObjectDereference((PetscObject)viewer);
106:     if (monitorsetup) {
107:       (*monitorsetup)(ts,vf);
108:     }
109:     TSAdjointMonitorSet(ts,(PetscErrorCode (*)(TS,PetscInt,PetscReal,Vec,PetscInt,Vec*,Vec*,void*))monitor,vf,(PetscErrorCode (*)(void**))PetscViewerAndFormatDestroy);
110:   }
111:   return(0);
112: }

116: /*@
117:    TSSetFromOptions - Sets various TS parameters from user options.

119:    Collective on TS

121:    Input Parameter:
122: .  ts - the TS context obtained from TSCreate()

124:    Options Database Keys:
125: +  -ts_type <type> - TSEULER, TSBEULER, TSSUNDIALS, TSPSEUDO, TSCN, TSRK, TSTHETA, TSALPHA, TSGL, TSSSP
126: .  -ts_save_trajectory - checkpoint the solution at each time-step
127: .  -ts_max_steps <maxsteps> - maximum number of time-steps to take
128: .  -ts_final_time <time> - maximum time to compute to
129: .  -ts_dt <dt> - initial time step
130: .  -ts_exact_final_time <stepover,interpolate,matchstep> whether to stop at the exact given final time and how to compute the solution at that ti,e
131: .  -ts_max_snes_failures <maxfailures> - Maximum number of nonlinear solve failures allowed
132: .  -ts_max_reject <maxrejects> - Maximum number of step rejections before step fails
133: .  -ts_error_if_step_fails <true,false> - Error if no step succeeds
134: .  -ts_rtol <rtol> - relative tolerance for local truncation error
135: .  -ts_atol <atol> Absolute tolerance for local truncation error
136: .  -ts_adjoint_solve <yes,no> After solving the ODE/DAE solve the adjoint problem (requires -ts_save_trajectory)
137: .  -ts_fd_color - Use finite differences with coloring to compute IJacobian
138: .  -ts_monitor - print information at each timestep
139: .  -ts_monitor_lg_solution - Monitor solution graphically
140: .  -ts_monitor_lg_error - Monitor error graphically
141: .  -ts_monitor_lg_timestep - Monitor timestep size graphically
142: .  -ts_monitor_lg_snes_iterations - Monitor number nonlinear iterations for each timestep graphically
143: .  -ts_monitor_lg_ksp_iterations - Monitor number nonlinear iterations for each timestep graphically
144: .  -ts_monitor_sp_eig - Monitor eigenvalues of linearized operator graphically
145: .  -ts_monitor_draw_solution - Monitor solution graphically
146: .  -ts_monitor_draw_solution_phase  <xleft,yleft,xright,yright> - Monitor solution graphically with phase diagram, requires problem with exactly 2 degrees of freedom
147: .  -ts_monitor_draw_error - Monitor error graphically, requires use to have provided TSSetSolutionFunction()
148: .  -ts_monitor_solution [ascii binary draw][:filename][:viewerformat] - monitors the solution at each timestep
149: .  -ts_monitor_solution_vtk <filename.vts> - Save each time step to a binary file, use filename-%%03D.vts
150: .  -ts_monitor_envelope - determine maximum and minimum value of each component of the solution over the solution time
151: .  -ts_adjoint_monitor - print information at each adjoint time step
152: -  -ts_adjoint_monitor_draw_sensi - monitor the sensitivity of the first cost function wrt initial conditions (lambda[0]) graphically

154:    Developer Note: We should unify all the -ts_monitor options in the way that -xxx_view has been unified

156:    Level: beginner

158: .keywords: TS, timestep, set, options, database

160: .seealso: TSGetType()
161: @*/
162: PetscErrorCode  TSSetFromOptions(TS ts)
163: {
164:   PetscBool              opt,flg,tflg;
165:   PetscErrorCode         ierr;
166:   char                   monfilename[PETSC_MAX_PATH_LEN];
167:   PetscReal              time_step;
168:   TSExactFinalTimeOption eftopt;
169:   char                   dir[16];
170:   TSIFunction            ifun;
171:   const char             *defaultType;
172:   char                   typeName[256];


177:   TSRegisterAll();
178:   TSGetIFunction(ts,NULL,&ifun,NULL);

180:   PetscObjectOptionsBegin((PetscObject)ts);
181:   if (((PetscObject)ts)->type_name)
182:     defaultType = ((PetscObject)ts)->type_name;
183:   else
184:     defaultType = ifun ? TSBEULER : TSEULER;
185:   PetscOptionsFList("-ts_type","TS method","TSSetType",TSList,defaultType,typeName,256,&opt);
186:   if (opt) {
187:     TSSetType(ts,typeName);
188:   } else {
189:     TSSetType(ts,defaultType);
190:   }

192:   /* Handle generic TS options */
193:   PetscOptionsInt("-ts_max_steps","Maximum number of time steps","TSSetDuration",ts->max_steps,&ts->max_steps,NULL);
194:   PetscOptionsReal("-ts_final_time","Time to run to","TSSetDuration",ts->max_time,&ts->max_time,NULL);
195:   PetscOptionsReal("-ts_init_time","Initial time","TSSetTime",ts->ptime,&ts->ptime,NULL);
196:   PetscOptionsReal("-ts_dt","Initial time step","TSSetTimeStep",ts->time_step,&time_step,&flg);
197:   if (flg) {TSSetTimeStep(ts,time_step);}
198:   PetscOptionsEnum("-ts_exact_final_time","Option for handling of final time step","TSSetExactFinalTime",TSExactFinalTimeOptions,(PetscEnum)ts->exact_final_time,(PetscEnum*)&eftopt,&flg);
199:   if (flg) {TSSetExactFinalTime(ts,eftopt);}
200:   PetscOptionsInt("-ts_max_snes_failures","Maximum number of nonlinear solve failures","TSSetMaxSNESFailures",ts->max_snes_failures,&ts->max_snes_failures,NULL);
201:   PetscOptionsInt("-ts_max_reject","Maximum number of step rejections before step fails","TSSetMaxStepRejections",ts->max_reject,&ts->max_reject,NULL);
202:   PetscOptionsBool("-ts_error_if_step_fails","Error if no step succeeds","TSSetErrorIfStepFails",ts->errorifstepfailed,&ts->errorifstepfailed,NULL);
203:   PetscOptionsReal("-ts_rtol","Relative tolerance for local truncation error","TSSetTolerances",ts->rtol,&ts->rtol,NULL);
204:   PetscOptionsReal("-ts_atol","Absolute tolerance for local truncation error","TSSetTolerances",ts->atol,&ts->atol,NULL);

206: #if defined(PETSC_HAVE_SAWS)
207:   {
208:   PetscBool set;
209:   flg  = PETSC_FALSE;
210:   PetscOptionsBool("-ts_saws_block","Block for SAWs memory snooper at end of TSSolve","PetscObjectSAWsBlock",((PetscObject)ts)->amspublishblock,&flg,&set);
211:   if (set) {
212:     PetscObjectSAWsSetBlock((PetscObject)ts,flg);
213:   }
214:   }
215: #endif

217:   /* Monitor options */
218:   TSMonitorSetFromOptions(ts,"-ts_monitor","Monitor time and timestep size","TSMonitorDefault",TSMonitorDefault,NULL);
219:   TSMonitorSetFromOptions(ts,"-ts_monitor_solution","View the solution at each timestep","TSMonitorSolution",TSMonitorSolution,NULL);
220:   TSAdjointMonitorSetFromOptions(ts,"-ts_adjoint_monitor","Monitor adjoint timestep size","TSAdjointMonitorDefault",TSAdjointMonitorDefault,NULL);

222:   PetscOptionsString("-ts_monitor_python","Use Python function","TSMonitorSet",0,monfilename,PETSC_MAX_PATH_LEN,&flg);
223:   if (flg) {PetscPythonMonitorSet((PetscObject)ts,monfilename);}

225:   PetscOptionsName("-ts_monitor_lg_solution","Monitor solution graphically","TSMonitorLGSolution",&opt);
226:   if (opt) {
227:     TSMonitorLGCtx ctx;
228:     PetscInt       howoften = 1;

230:     PetscOptionsInt("-ts_monitor_lg_solution","Monitor solution graphically","TSMonitorLGSolution",howoften,&howoften,NULL);
231:     TSMonitorLGCtxCreate(PETSC_COMM_SELF,0,0,PETSC_DECIDE,PETSC_DECIDE,400,300,howoften,&ctx);
232:     TSMonitorSet(ts,TSMonitorLGSolution,ctx,(PetscErrorCode (*)(void**))TSMonitorLGCtxDestroy);
233:   }

235:   PetscOptionsName("-ts_monitor_lg_error","Monitor error graphically","TSMonitorLGError",&opt);
236:   if (opt) {
237:     TSMonitorLGCtx ctx;
238:     PetscInt       howoften = 1;

240:     PetscOptionsInt("-ts_monitor_lg_error","Monitor error graphically","TSMonitorLGError",howoften,&howoften,NULL);
241:     TSMonitorLGCtxCreate(PETSC_COMM_SELF,0,0,PETSC_DECIDE,PETSC_DECIDE,400,300,howoften,&ctx);
242:     TSMonitorSet(ts,TSMonitorLGError,ctx,(PetscErrorCode (*)(void**))TSMonitorLGCtxDestroy);
243:   }

245:   PetscOptionsName("-ts_monitor_lg_timestep","Monitor timestep size graphically","TSMonitorLGTimeStep",&opt);
246:   if (opt) {
247:     TSMonitorLGCtx ctx;
248:     PetscInt       howoften = 1;

250:     PetscOptionsInt("-ts_monitor_lg_timestep","Monitor timestep size graphically","TSMonitorLGTimeStep",howoften,&howoften,NULL);
251:     TSMonitorLGCtxCreate(PetscObjectComm((PetscObject)ts),NULL,NULL,PETSC_DECIDE,PETSC_DECIDE,400,300,howoften,&ctx);
252:     TSMonitorSet(ts,TSMonitorLGTimeStep,ctx,(PetscErrorCode (*)(void**))TSMonitorLGCtxDestroy);
253:   }
254:   PetscOptionsName("-ts_monitor_lg_snes_iterations","Monitor number nonlinear iterations for each timestep graphically","TSMonitorLGSNESIterations",&opt);
255:   if (opt) {
256:     TSMonitorLGCtx ctx;
257:     PetscInt       howoften = 1;

259:     PetscOptionsInt("-ts_monitor_lg_snes_iterations","Monitor number nonlinear iterations for each timestep graphically","TSMonitorLGSNESIterations",howoften,&howoften,NULL);
260:     TSMonitorLGCtxCreate(PetscObjectComm((PetscObject)ts),NULL,NULL,PETSC_DECIDE,PETSC_DECIDE,400,300,howoften,&ctx);
261:     TSMonitorSet(ts,TSMonitorLGSNESIterations,ctx,(PetscErrorCode (*)(void**))TSMonitorLGCtxDestroy);
262:   }
263:   PetscOptionsName("-ts_monitor_lg_ksp_iterations","Monitor number nonlinear iterations for each timestep graphically","TSMonitorLGKSPIterations",&opt);
264:   if (opt) {
265:     TSMonitorLGCtx ctx;
266:     PetscInt       howoften = 1;

268:     PetscOptionsInt("-ts_monitor_lg_ksp_iterations","Monitor number nonlinear iterations for each timestep graphically","TSMonitorLGKSPIterations",howoften,&howoften,NULL);
269:     TSMonitorLGCtxCreate(PetscObjectComm((PetscObject)ts),NULL,NULL,PETSC_DECIDE,PETSC_DECIDE,400,300,howoften,&ctx);
270:     TSMonitorSet(ts,TSMonitorLGKSPIterations,ctx,(PetscErrorCode (*)(void**))TSMonitorLGCtxDestroy);
271:   }
272:   PetscOptionsName("-ts_monitor_sp_eig","Monitor eigenvalues of linearized operator graphically","TSMonitorSPEig",&opt);
273:   if (opt) {
274:     TSMonitorSPEigCtx ctx;
275:     PetscInt          howoften = 1;

277:     PetscOptionsInt("-ts_monitor_sp_eig","Monitor eigenvalues of linearized operator graphically","TSMonitorSPEig",howoften,&howoften,NULL);
278:     TSMonitorSPEigCtxCreate(PETSC_COMM_SELF,0,0,PETSC_DECIDE,PETSC_DECIDE,300,300,howoften,&ctx);
279:     TSMonitorSet(ts,TSMonitorSPEig,ctx,(PetscErrorCode (*)(void**))TSMonitorSPEigCtxDestroy);
280:   }
281:   opt  = PETSC_FALSE;
282:   PetscOptionsName("-ts_monitor_draw_solution","Monitor solution graphically","TSMonitorDrawSolution",&opt);
283:   if (opt) {
284:     TSMonitorDrawCtx ctx;
285:     PetscInt         howoften = 1;

287:     PetscOptionsInt("-ts_monitor_draw_solution","Monitor solution graphically","TSMonitorDrawSolution",howoften,&howoften,NULL);
288:     TSMonitorDrawCtxCreate(PetscObjectComm((PetscObject)ts),0,0,PETSC_DECIDE,PETSC_DECIDE,300,300,howoften,&ctx);
289:     TSMonitorSet(ts,TSMonitorDrawSolution,ctx,(PetscErrorCode (*)(void**))TSMonitorDrawCtxDestroy);
290:   }
291:   opt  = PETSC_FALSE;
292:   PetscOptionsName("-ts_adjoint_monitor_draw_sensi","Monitor adjoint sensitivities (lambda only) graphically","TSAdjointMonitorDrawSensi",&opt);
293:   if (opt) {
294:     TSMonitorDrawCtx ctx;
295:     PetscInt         howoften = 1;

297:     PetscOptionsInt("-ts_adjoint_monitor_draw_sensi","Monitor adjoint sensitivities (lambda only) graphically","TSAdjointMonitorDrawSensi",howoften,&howoften,NULL);
298:     TSMonitorDrawCtxCreate(PetscObjectComm((PetscObject)ts),0,0,PETSC_DECIDE,PETSC_DECIDE,300,300,howoften,&ctx);
299:     TSAdjointMonitorSet(ts,TSAdjointMonitorDrawSensi,ctx,(PetscErrorCode (*)(void**))TSMonitorDrawCtxDestroy);
300:   }
301:   opt  = PETSC_FALSE;
302:   PetscOptionsName("-ts_monitor_draw_solution_phase","Monitor solution graphically","TSMonitorDrawSolutionPhase",&opt);
303:   if (opt) {
304:     TSMonitorDrawCtx ctx;
305:     PetscReal        bounds[4];
306:     PetscInt         n = 4;
307:     PetscDraw        draw;
308:     PetscDrawAxis    axis;

310:     PetscOptionsRealArray("-ts_monitor_draw_solution_phase","Monitor solution graphically","TSMonitorDrawSolutionPhase",bounds,&n,NULL);
311:     if (n != 4) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_ARG_WRONG,"Must provide bounding box of phase field");
312:     TSMonitorDrawCtxCreate(PetscObjectComm((PetscObject)ts),0,0,PETSC_DECIDE,PETSC_DECIDE,300,300,1,&ctx);
313:     PetscViewerDrawGetDraw(ctx->viewer,0,&draw);
314:     PetscViewerDrawGetDrawAxis(ctx->viewer,0,&axis);
315:     PetscDrawAxisSetLimits(axis,bounds[0],bounds[2],bounds[1],bounds[3]);
316:     PetscDrawAxisSetLabels(axis,"Phase Diagram","Variable 1","Variable 2");
317:     TSMonitorSet(ts,TSMonitorDrawSolutionPhase,ctx,(PetscErrorCode (*)(void**))TSMonitorDrawCtxDestroy);
318:   }
319:   opt  = PETSC_FALSE;
320:   PetscOptionsName("-ts_monitor_draw_error","Monitor error graphically","TSMonitorDrawError",&opt);
321:   if (opt) {
322:     TSMonitorDrawCtx ctx;
323:     PetscInt         howoften = 1;

325:     PetscOptionsInt("-ts_monitor_draw_error","Monitor error graphically","TSMonitorDrawError",howoften,&howoften,NULL);
326:     TSMonitorDrawCtxCreate(PetscObjectComm((PetscObject)ts),0,0,PETSC_DECIDE,PETSC_DECIDE,300,300,howoften,&ctx);
327:     TSMonitorSet(ts,TSMonitorDrawError,ctx,(PetscErrorCode (*)(void**))TSMonitorDrawCtxDestroy);
328:   }

330:   opt  = PETSC_FALSE;
331:   PetscOptionsString("-ts_monitor_solution_vtk","Save each time step to a binary file, use filename-%%03D.vts","TSMonitorSolutionVTK",0,monfilename,PETSC_MAX_PATH_LEN,&flg);
332:   if (flg) {
333:     const char *ptr,*ptr2;
334:     char       *filetemplate;
335:     if (!monfilename[0]) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_USER,"-ts_monitor_solution_vtk requires a file template, e.g. filename-%%03D.vts");
336:     /* Do some cursory validation of the input. */
337:     PetscStrstr(monfilename,"%",(char**)&ptr);
338:     if (!ptr) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_USER,"-ts_monitor_solution_vtk requires a file template, e.g. filename-%%03D.vts");
339:     for (ptr++; ptr && *ptr; ptr++) {
340:       PetscStrchr("DdiouxX",*ptr,(char**)&ptr2);
341:       if (!ptr2 && (*ptr < '0' || '9' < *ptr)) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_USER,"Invalid file template argument to -ts_monitor_solution_vtk, should look like filename-%%03D.vts");
342:       if (ptr2) break;
343:     }
344:     PetscStrallocpy(monfilename,&filetemplate);
345:     TSMonitorSet(ts,TSMonitorSolutionVTK,filetemplate,(PetscErrorCode (*)(void**))TSMonitorSolutionVTKDestroy);
346:   }

348:   PetscOptionsString("-ts_monitor_dmda_ray","Display a ray of the solution","None","y=0",dir,16,&flg);
349:   if (flg) {
350:     TSMonitorDMDARayCtx *rayctx;
351:     int                  ray = 0;
352:     DMDADirection        ddir;
353:     DM                   da;
354:     PetscMPIInt          rank;

356:     if (dir[1] != '=') SETERRQ1(PetscObjectComm((PetscObject)ts),PETSC_ERR_ARG_WRONG,"Unknown ray %s",dir);
357:     if (dir[0] == 'x') ddir = DMDA_X;
358:     else if (dir[0] == 'y') ddir = DMDA_Y;
359:     else SETERRQ1(PetscObjectComm((PetscObject)ts),PETSC_ERR_ARG_WRONG,"Unknown ray %s",dir);
360:     sscanf(dir+2,"%d",&ray);

362:     PetscInfo2(((PetscObject)ts),"Displaying DMDA ray %c = %D\n",dir[0],ray);
363:     PetscNew(&rayctx);
364:     TSGetDM(ts,&da);
365:     DMDAGetRay(da,ddir,ray,&rayctx->ray,&rayctx->scatter);
366:     MPI_Comm_rank(PetscObjectComm((PetscObject)ts),&rank);
367:     if (!rank) {
368:       PetscViewerDrawOpen(PETSC_COMM_SELF,0,0,0,0,600,300,&rayctx->viewer);
369:     }
370:     rayctx->lgctx = NULL;
371:     TSMonitorSet(ts,TSMonitorDMDARay,rayctx,TSMonitorDMDARayDestroy);
372:   }
373:   PetscOptionsString("-ts_monitor_lg_dmda_ray","Display a ray of the solution","None","x=0",dir,16,&flg);
374:   if (flg) {
375:     TSMonitorDMDARayCtx *rayctx;
376:     int                 ray = 0;
377:     DMDADirection       ddir;
378:     DM                  da;
379:     PetscInt            howoften = 1;

381:     if (dir[1] != '=') SETERRQ1(PetscObjectComm((PetscObject) ts), PETSC_ERR_ARG_WRONG, "Malformed ray %s", dir);
382:     if      (dir[0] == 'x') ddir = DMDA_X;
383:     else if (dir[0] == 'y') ddir = DMDA_Y;
384:     else SETERRQ1(PetscObjectComm((PetscObject) ts), PETSC_ERR_ARG_WRONG, "Unknown ray direction %s", dir);
385:     sscanf(dir+2, "%d", &ray);

387:     PetscInfo2(((PetscObject) ts),"Displaying LG DMDA ray %c = %D\n", dir[0], ray);
388:     PetscNew(&rayctx);
389:     TSGetDM(ts, &da);
390:     DMDAGetRay(da, ddir, ray, &rayctx->ray, &rayctx->scatter);
391:     TSMonitorLGCtxCreate(PETSC_COMM_SELF,0,0,PETSC_DECIDE,PETSC_DECIDE,600,400,howoften,&rayctx->lgctx);
392:     TSMonitorSet(ts, TSMonitorLGDMDARay, rayctx, TSMonitorDMDARayDestroy);
393:   }

395:   PetscOptionsName("-ts_monitor_envelope","Monitor maximum and minimum value of each component of the solution","TSMonitorEnvelope",&opt);
396:   if (opt) {
397:     TSMonitorEnvelopeCtx ctx;

399:     TSMonitorEnvelopeCtxCreate(ts,&ctx);
400:     TSMonitorSet(ts,TSMonitorEnvelope,ctx,(PetscErrorCode (*)(void**))TSMonitorEnvelopeCtxDestroy);
401:   }

403:   flg  = PETSC_FALSE;
404:   PetscOptionsBool("-ts_fd_color", "Use finite differences with coloring to compute IJacobian", "TSComputeJacobianDefaultColor", flg, &flg, NULL);
405:   if (flg) {
406:     DM   dm;
407:     DMTS tdm;

409:     TSGetDM(ts, &dm);
410:     DMGetDMTS(dm, &tdm);
411:     tdm->ijacobianctx = NULL;
412:     TSSetIJacobian(ts, NULL, NULL, TSComputeIJacobianDefaultColor, 0);
413:     PetscInfo(ts, "Setting default finite difference coloring Jacobian matrix\n");
414:   }

416:   if (ts->adapt) {
417:     TSAdaptSetFromOptions(PetscOptionsObject,ts->adapt);
418:   }

420:   /* Handle specific TS options */
421:   if (ts->ops->setfromoptions) {
422:     (*ts->ops->setfromoptions)(PetscOptionsObject,ts);
423:   }

425:   /* TS trajectory must be set after TS, since it may use some TS options above */
426:   tflg = ts->trajectory ? PETSC_TRUE : PETSC_FALSE;
427:   PetscOptionsBool("-ts_save_trajectory","Save the solution at each timestep","TSSetSaveTrajectory",tflg,&tflg,NULL);
428:   if (tflg) {
429:     TSSetSaveTrajectory(ts);
430:   }
431:   tflg = ts->adjoint_solve ? PETSC_TRUE : PETSC_FALSE;
432:   PetscOptionsBool("-ts_adjoint_solve","Solve the adjoint problem immediately after solving the forward problem","",tflg,&tflg,&flg);
433:   if (flg) {
434:     TSSetSaveTrajectory(ts);
435:     ts->adjoint_solve = tflg;
436:   }

438:   /* process any options handlers added with PetscObjectAddOptionsHandler() */
439:   PetscObjectProcessOptionsHandlers(PetscOptionsObject,(PetscObject)ts);
440:   PetscOptionsEnd();

442:   if (ts->trajectory) {
443:     TSTrajectorySetFromOptions(ts->trajectory,ts);
444:   }

446:   TSGetSNES(ts,&ts->snes);
447:   if (ts->problem_type == TS_LINEAR) {SNESSetType(ts->snes,SNESKSPONLY);}
448:   SNESSetFromOptions(ts->snes);
449:   return(0);
450: }

454: /*@
455:    TSSetSaveTrajectory - Causes the TS to save its solutions as it iterates forward in time in a TSTrajectory object

457:    Collective on TS

459:    Input Parameters:
460: .  ts - the TS context obtained from TSCreate()

462: Note: This routine should be called after all TS options have been set

464:    Level: intermediate

466: .seealso: TSGetTrajectory(), TSAdjointSolve()

468: .keywords: TS, set, checkpoint,
469: @*/
470: PetscErrorCode  TSSetSaveTrajectory(TS ts)
471: {

476:   if (!ts->trajectory) {
477:     TSTrajectoryCreate(PetscObjectComm((PetscObject)ts),&ts->trajectory);
478:     TSTrajectorySetFromOptions(ts->trajectory,ts);
479:   }
480:   return(0);
481: }

485: /*@
486:    TSComputeRHSJacobian - Computes the Jacobian matrix that has been
487:       set with TSSetRHSJacobian().

489:    Collective on TS and Vec

491:    Input Parameters:
492: +  ts - the TS context
493: .  t - current timestep
494: -  U - input vector

496:    Output Parameters:
497: +  A - Jacobian matrix
498: .  B - optional preconditioning matrix
499: -  flag - flag indicating matrix structure

501:    Notes:
502:    Most users should not need to explicitly call this routine, as it
503:    is used internally within the nonlinear solvers.

505:    See KSPSetOperators() for important information about setting the
506:    flag parameter.

508:    Level: developer

510: .keywords: SNES, compute, Jacobian, matrix

512: .seealso:  TSSetRHSJacobian(), KSPSetOperators()
513: @*/
514: PetscErrorCode  TSComputeRHSJacobian(TS ts,PetscReal t,Vec U,Mat A,Mat B)
515: {
517:   PetscObjectState Ustate;
518:   DM             dm;
519:   DMTS           tsdm;
520:   TSRHSJacobian  rhsjacobianfunc;
521:   void           *ctx;
522:   TSIJacobian    ijacobianfunc;
523:   TSRHSFunction  rhsfunction;

529:   TSGetDM(ts,&dm);
530:   DMGetDMTS(dm,&tsdm);
531:   DMTSGetRHSJacobian(dm,&rhsjacobianfunc,&ctx);
532:   DMTSGetIJacobian(dm,&ijacobianfunc,NULL);
533:   DMTSGetRHSFunction(dm,&rhsfunction,&ctx);
534:   PetscObjectStateGet((PetscObject)U,&Ustate);
535:   if (ts->rhsjacobian.time == t && (ts->problem_type == TS_LINEAR || (ts->rhsjacobian.X == U && ts->rhsjacobian.Xstate == Ustate)) && (rhsfunction != TSComputeRHSFunctionLinear)) {
536:     return(0);
537:   }

539:   if (!rhsjacobianfunc && !ijacobianfunc) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_USER,"Must call TSSetRHSJacobian() and / or TSSetIJacobian()");

541:   if (ts->rhsjacobian.reuse) {
542:     MatShift(A,-ts->rhsjacobian.shift);
543:     MatScale(A,1./ts->rhsjacobian.scale);
544:     if (A != B) {
545:       MatShift(B,-ts->rhsjacobian.shift);
546:       MatScale(B,1./ts->rhsjacobian.scale);
547:     }
548:     ts->rhsjacobian.shift = 0;
549:     ts->rhsjacobian.scale = 1.;
550:   }

552:   if (rhsjacobianfunc) {
553:     PetscBool missing;
554:     PetscLogEventBegin(TS_JacobianEval,ts,U,A,B);
555:     PetscStackPush("TS user Jacobian function");
556:     (*rhsjacobianfunc)(ts,t,U,A,B,ctx);
557:     PetscStackPop;
558:     PetscLogEventEnd(TS_JacobianEval,ts,U,A,B);
559:     if (A) {
560:       MatMissingDiagonal(A,&missing,NULL);
561:       if (missing) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Amat passed to TSSetRHSJacobian() must have all diagonal entries set, if they are zero you must still set them with a zero value");
562:     }
563:     if (B && B != A) {
564:       MatMissingDiagonal(B,&missing,NULL);
565:       if (missing) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Bmat passed to TSSetRHSJacobian() must have all diagonal entries set, if they are zero you must still set them with a zero value");
566:     }
567:   } else {
568:     MatZeroEntries(A);
569:     if (A != B) {MatZeroEntries(B);}
570:   }
571:   ts->rhsjacobian.time       = t;
572:   ts->rhsjacobian.X          = U;
573:   PetscObjectStateGet((PetscObject)U,&ts->rhsjacobian.Xstate);
574:   return(0);
575: }

579: /*@
580:    TSComputeRHSFunction - Evaluates the right-hand-side function.

582:    Collective on TS and Vec

584:    Input Parameters:
585: +  ts - the TS context
586: .  t - current time
587: -  U - state vector

589:    Output Parameter:
590: .  y - right hand side

592:    Note:
593:    Most users should not need to explicitly call this routine, as it
594:    is used internally within the nonlinear solvers.

596:    Level: developer

598: .keywords: TS, compute

600: .seealso: TSSetRHSFunction(), TSComputeIFunction()
601: @*/
602: PetscErrorCode TSComputeRHSFunction(TS ts,PetscReal t,Vec U,Vec y)
603: {
605:   TSRHSFunction  rhsfunction;
606:   TSIFunction    ifunction;
607:   void           *ctx;
608:   DM             dm;

614:   TSGetDM(ts,&dm);
615:   DMTSGetRHSFunction(dm,&rhsfunction,&ctx);
616:   DMTSGetIFunction(dm,&ifunction,NULL);

618:   if (!rhsfunction && !ifunction) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_USER,"Must call TSSetRHSFunction() and / or TSSetIFunction()");

620:   PetscLogEventBegin(TS_FunctionEval,ts,U,y,0);
621:   if (rhsfunction) {
622:     PetscStackPush("TS user right-hand-side function");
623:     (*rhsfunction)(ts,t,U,y,ctx);
624:     PetscStackPop;
625:   } else {
626:     VecZeroEntries(y);
627:   }

629:   PetscLogEventEnd(TS_FunctionEval,ts,U,y,0);
630:   return(0);
631: }

635: /*@
636:    TSComputeSolutionFunction - Evaluates the solution function.

638:    Collective on TS and Vec

640:    Input Parameters:
641: +  ts - the TS context
642: -  t - current time

644:    Output Parameter:
645: .  U - the solution

647:    Note:
648:    Most users should not need to explicitly call this routine, as it
649:    is used internally within the nonlinear solvers.

651:    Level: developer

653: .keywords: TS, compute

655: .seealso: TSSetSolutionFunction(), TSSetRHSFunction(), TSComputeIFunction()
656: @*/
657: PetscErrorCode TSComputeSolutionFunction(TS ts,PetscReal t,Vec U)
658: {
659:   PetscErrorCode     ierr;
660:   TSSolutionFunction solutionfunction;
661:   void               *ctx;
662:   DM                 dm;

667:   TSGetDM(ts,&dm);
668:   DMTSGetSolutionFunction(dm,&solutionfunction,&ctx);

670:   if (solutionfunction) {
671:     PetscStackPush("TS user solution function");
672:     (*solutionfunction)(ts,t,U,ctx);
673:     PetscStackPop;
674:   }
675:   return(0);
676: }
679: /*@
680:    TSComputeForcingFunction - Evaluates the forcing function.

682:    Collective on TS and Vec

684:    Input Parameters:
685: +  ts - the TS context
686: -  t - current time

688:    Output Parameter:
689: .  U - the function value

691:    Note:
692:    Most users should not need to explicitly call this routine, as it
693:    is used internally within the nonlinear solvers.

695:    Level: developer

697: .keywords: TS, compute

699: .seealso: TSSetSolutionFunction(), TSSetRHSFunction(), TSComputeIFunction()
700: @*/
701: PetscErrorCode TSComputeForcingFunction(TS ts,PetscReal t,Vec U)
702: {
703:   PetscErrorCode     ierr, (*forcing)(TS,PetscReal,Vec,void*);
704:   void               *ctx;
705:   DM                 dm;

710:   TSGetDM(ts,&dm);
711:   DMTSGetForcingFunction(dm,&forcing,&ctx);

713:   if (forcing) {
714:     PetscStackPush("TS user forcing function");
715:     (*forcing)(ts,t,U,ctx);
716:     PetscStackPop;
717:   }
718:   return(0);
719: }

723: static PetscErrorCode TSGetRHSVec_Private(TS ts,Vec *Frhs)
724: {
725:   Vec            F;

729:   *Frhs = NULL;
730:   TSGetIFunction(ts,&F,NULL,NULL);
731:   if (!ts->Frhs) {
732:     VecDuplicate(F,&ts->Frhs);
733:   }
734:   *Frhs = ts->Frhs;
735:   return(0);
736: }

740: static PetscErrorCode TSGetRHSMats_Private(TS ts,Mat *Arhs,Mat *Brhs)
741: {
742:   Mat            A,B;

746:   if (Arhs) *Arhs = NULL;
747:   if (Brhs) *Brhs = NULL;
748:   TSGetIJacobian(ts,&A,&B,NULL,NULL);
749:   if (Arhs) {
750:     if (!ts->Arhs) {
751:       MatDuplicate(A,MAT_DO_NOT_COPY_VALUES,&ts->Arhs);
752:     }
753:     *Arhs = ts->Arhs;
754:   }
755:   if (Brhs) {
756:     if (!ts->Brhs) {
757:       if (A != B) {
758:         MatDuplicate(B,MAT_DO_NOT_COPY_VALUES,&ts->Brhs);
759:       } else {
760:         PetscObjectReference((PetscObject)ts->Arhs);
761:         ts->Brhs = ts->Arhs;
762:       }
763:     }
764:     *Brhs = ts->Brhs;
765:   }
766:   return(0);
767: }

771: /*@
772:    TSComputeIFunction - Evaluates the DAE residual written in implicit form F(t,U,Udot)=0

774:    Collective on TS and Vec

776:    Input Parameters:
777: +  ts - the TS context
778: .  t - current time
779: .  U - state vector
780: .  Udot - time derivative of state vector
781: -  imex - flag indicates if the method is IMEX so that the RHSFunction should be kept separate

783:    Output Parameter:
784: .  Y - right hand side

786:    Note:
787:    Most users should not need to explicitly call this routine, as it
788:    is used internally within the nonlinear solvers.

790:    If the user did did not write their equations in implicit form, this
791:    function recasts them in implicit form.

793:    Level: developer

795: .keywords: TS, compute

797: .seealso: TSSetIFunction(), TSComputeRHSFunction()
798: @*/
799: PetscErrorCode TSComputeIFunction(TS ts,PetscReal t,Vec U,Vec Udot,Vec Y,PetscBool imex)
800: {
802:   TSIFunction    ifunction;
803:   TSRHSFunction  rhsfunction;
804:   void           *ctx;
805:   DM             dm;


813:   TSGetDM(ts,&dm);
814:   DMTSGetIFunction(dm,&ifunction,&ctx);
815:   DMTSGetRHSFunction(dm,&rhsfunction,NULL);

817:   if (!rhsfunction && !ifunction) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_USER,"Must call TSSetRHSFunction() and / or TSSetIFunction()");

819:   PetscLogEventBegin(TS_FunctionEval,ts,U,Udot,Y);
820:   if (ifunction) {
821:     PetscStackPush("TS user implicit function");
822:     (*ifunction)(ts,t,U,Udot,Y,ctx);
823:     PetscStackPop;
824:   }
825:   if (imex) {
826:     if (!ifunction) {
827:       VecCopy(Udot,Y);
828:     }
829:   } else if (rhsfunction) {
830:     if (ifunction) {
831:       Vec Frhs;
832:       TSGetRHSVec_Private(ts,&Frhs);
833:       TSComputeRHSFunction(ts,t,U,Frhs);
834:       VecAXPY(Y,-1,Frhs);
835:     } else {
836:       TSComputeRHSFunction(ts,t,U,Y);
837:       VecAYPX(Y,-1,Udot);
838:     }
839:   }
840:   PetscLogEventEnd(TS_FunctionEval,ts,U,Udot,Y);
841:   return(0);
842: }

846: /*@
847:    TSComputeIJacobian - Evaluates the Jacobian of the DAE

849:    Collective on TS and Vec

851:    Input
852:       Input Parameters:
853: +  ts - the TS context
854: .  t - current timestep
855: .  U - state vector
856: .  Udot - time derivative of state vector
857: .  shift - shift to apply, see note below
858: -  imex - flag indicates if the method is IMEX so that the RHSJacobian should be kept separate

860:    Output Parameters:
861: +  A - Jacobian matrix
862: .  B - optional preconditioning matrix
863: -  flag - flag indicating matrix structure

865:    Notes:
866:    If F(t,U,Udot)=0 is the DAE, the required Jacobian is

868:    dF/dU + shift*dF/dUdot

870:    Most users should not need to explicitly call this routine, as it
871:    is used internally within the nonlinear solvers.

873:    Level: developer

875: .keywords: TS, compute, Jacobian, matrix

877: .seealso:  TSSetIJacobian()
878: @*/
879: PetscErrorCode TSComputeIJacobian(TS ts,PetscReal t,Vec U,Vec Udot,PetscReal shift,Mat A,Mat B,PetscBool imex)
880: {
882:   TSIJacobian    ijacobian;
883:   TSRHSJacobian  rhsjacobian;
884:   DM             dm;
885:   void           *ctx;


896:   TSGetDM(ts,&dm);
897:   DMTSGetIJacobian(dm,&ijacobian,&ctx);
898:   DMTSGetRHSJacobian(dm,&rhsjacobian,NULL);

900:   if (!rhsjacobian && !ijacobian) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_USER,"Must call TSSetRHSJacobian() and / or TSSetIJacobian()");

902:   PetscLogEventBegin(TS_JacobianEval,ts,U,A,B);
903:   if (ijacobian) {
904:     PetscBool missing;
905:     PetscStackPush("TS user implicit Jacobian");
906:     (*ijacobian)(ts,t,U,Udot,shift,A,B,ctx);
907:     PetscStackPop;
908:     if (A) {
909:       MatMissingDiagonal(A,&missing,NULL);
910:       if (missing) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Amat passed to TSSetIJacobian() must have all diagonal entries set, if they are zero you must still set them with a zero value");
911:     }
912:     if (B && B != A) {
913:       MatMissingDiagonal(B,&missing,NULL);
914:       if (missing) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Bmat passed to TSSetIJacobian() must have all diagonal entries set, if they are zero you must still set them with a zero value");
915:     }
916:   }
917:   if (imex) {
918:     if (!ijacobian) {  /* system was written as Udot = G(t,U) */
919:       MatZeroEntries(A);
920:       MatShift(A,shift);
921:       if (A != B) {
922:         MatZeroEntries(B);
923:         MatShift(B,shift);
924:       }
925:     }
926:   } else {
927:     Mat Arhs = NULL,Brhs = NULL;
928:     if (rhsjacobian) {
929:       TSGetRHSMats_Private(ts,&Arhs,&Brhs);
930:       TSComputeRHSJacobian(ts,t,U,Arhs,Brhs);
931:     }
932:     if (Arhs == A) {           /* No IJacobian, so we only have the RHS matrix */
933:       ts->rhsjacobian.scale = -1;
934:       ts->rhsjacobian.shift = shift;
935:       MatScale(A,-1);
936:       MatShift(A,shift);
937:       if (A != B) {
938:         MatScale(B,-1);
939:         MatShift(B,shift);
940:       }
941:     } else if (Arhs) {          /* Both IJacobian and RHSJacobian */
942:       MatStructure axpy = DIFFERENT_NONZERO_PATTERN;
943:       if (!ijacobian) {         /* No IJacobian provided, but we have a separate RHS matrix */
944:         MatZeroEntries(A);
945:         MatShift(A,shift);
946:         if (A != B) {
947:           MatZeroEntries(B);
948:           MatShift(B,shift);
949:         }
950:       }
951:       MatAXPY(A,-1,Arhs,axpy);
952:       if (A != B) {
953:         MatAXPY(B,-1,Brhs,axpy);
954:       }
955:     }
956:   }
957:   PetscLogEventEnd(TS_JacobianEval,ts,U,A,B);
958:   return(0);
959: }

963: /*@C
964:     TSSetRHSFunction - Sets the routine for evaluating the function,
965:     where U_t = G(t,u).

967:     Logically Collective on TS

969:     Input Parameters:
970: +   ts - the TS context obtained from TSCreate()
971: .   r - vector to put the computed right hand side (or NULL to have it created)
972: .   f - routine for evaluating the right-hand-side function
973: -   ctx - [optional] user-defined context for private data for the
974:           function evaluation routine (may be NULL)

976:     Calling sequence of func:
977: $     func (TS ts,PetscReal t,Vec u,Vec F,void *ctx);

979: +   t - current timestep
980: .   u - input vector
981: .   F - function vector
982: -   ctx - [optional] user-defined function context

984:     Level: beginner

986:     Notes: You must call this function or TSSetIFunction() to define your ODE. You cannot use this function when solving a DAE.

988: .keywords: TS, timestep, set, right-hand-side, function

990: .seealso: TSSetRHSJacobian(), TSSetIJacobian(), TSSetIFunction()
991: @*/
992: PetscErrorCode  TSSetRHSFunction(TS ts,Vec r,PetscErrorCode (*f)(TS,PetscReal,Vec,Vec,void*),void *ctx)
993: {
995:   SNES           snes;
996:   Vec            ralloc = NULL;
997:   DM             dm;


1003:   TSGetDM(ts,&dm);
1004:   DMTSSetRHSFunction(dm,f,ctx);
1005:   TSGetSNES(ts,&snes);
1006:   if (!r && !ts->dm && ts->vec_sol) {
1007:     VecDuplicate(ts->vec_sol,&ralloc);
1008:     r = ralloc;
1009:   }
1010:   SNESSetFunction(snes,r,SNESTSFormFunction,ts);
1011:   VecDestroy(&ralloc);
1012:   return(0);
1013: }

1017: /*@C
1018:     TSSetSolutionFunction - Provide a function that computes the solution of the ODE or DAE

1020:     Logically Collective on TS

1022:     Input Parameters:
1023: +   ts - the TS context obtained from TSCreate()
1024: .   f - routine for evaluating the solution
1025: -   ctx - [optional] user-defined context for private data for the
1026:           function evaluation routine (may be NULL)

1028:     Calling sequence of func:
1029: $     func (TS ts,PetscReal t,Vec u,void *ctx);

1031: +   t - current timestep
1032: .   u - output vector
1033: -   ctx - [optional] user-defined function context

1035:     Notes:
1036:     This routine is used for testing accuracy of time integration schemes when you already know the solution.
1037:     If analytic solutions are not known for your system, consider using the Method of Manufactured Solutions to
1038:     create closed-form solutions with non-physical forcing terms.

1040:     For low-dimensional problems solved in serial, such as small discrete systems, TSMonitorLGError() can be used to monitor the error history.

1042:     Level: beginner

1044: .keywords: TS, timestep, set, right-hand-side, function

1046: .seealso: TSSetRHSJacobian(), TSSetIJacobian(), TSComputeSolutionFunction(), TSSetForcingFunction()
1047: @*/
1048: PetscErrorCode  TSSetSolutionFunction(TS ts,PetscErrorCode (*f)(TS,PetscReal,Vec,void*),void *ctx)
1049: {
1051:   DM             dm;

1055:   TSGetDM(ts,&dm);
1056:   DMTSSetSolutionFunction(dm,f,ctx);
1057:   return(0);
1058: }

1062: /*@C
1063:     TSSetForcingFunction - Provide a function that computes a forcing term for a ODE or PDE

1065:     Logically Collective on TS

1067:     Input Parameters:
1068: +   ts - the TS context obtained from TSCreate()
1069: .   f - routine for evaluating the forcing function
1070: -   ctx - [optional] user-defined context for private data for the
1071:           function evaluation routine (may be NULL)

1073:     Calling sequence of func:
1074: $     func (TS ts,PetscReal t,Vec u,void *ctx);

1076: +   t - current timestep
1077: .   u - output vector
1078: -   ctx - [optional] user-defined function context

1080:     Notes:
1081:     This routine is useful for testing accuracy of time integration schemes when using the Method of Manufactured Solutions to
1082:     create closed-form solutions with a non-physical forcing term.

1084:     For low-dimensional problems solved in serial, such as small discrete systems, TSMonitorLGError() can be used to monitor the error history.

1086:     Level: beginner

1088: .keywords: TS, timestep, set, right-hand-side, function

1090: .seealso: TSSetRHSJacobian(), TSSetIJacobian(), TSComputeSolutionFunction(), TSSetSolutionFunction()
1091: @*/
1092: PetscErrorCode  TSSetForcingFunction(TS ts,TSForcingFunction f,void *ctx)
1093: {
1095:   DM             dm;

1099:   TSGetDM(ts,&dm);
1100:   DMTSSetForcingFunction(dm,f,ctx);
1101:   return(0);
1102: }

1106: /*@C
1107:    TSSetRHSJacobian - Sets the function to compute the Jacobian of G,
1108:    where U_t = G(U,t), as well as the location to store the matrix.

1110:    Logically Collective on TS

1112:    Input Parameters:
1113: +  ts  - the TS context obtained from TSCreate()
1114: .  Amat - (approximate) Jacobian matrix
1115: .  Pmat - matrix from which preconditioner is to be constructed (usually the same as Amat)
1116: .  f   - the Jacobian evaluation routine
1117: -  ctx - [optional] user-defined context for private data for the
1118:          Jacobian evaluation routine (may be NULL)

1120:    Calling sequence of f:
1121: $     func (TS ts,PetscReal t,Vec u,Mat A,Mat B,void *ctx);

1123: +  t - current timestep
1124: .  u - input vector
1125: .  Amat - (approximate) Jacobian matrix
1126: .  Pmat - matrix from which preconditioner is to be constructed (usually the same as Amat)
1127: -  ctx - [optional] user-defined context for matrix evaluation routine

1129:    Notes:
1130:    You must set all the diagonal entries of the matrices, if they are zero you must still set them with a zero value

1132:    The TS solver may modify the nonzero structure and the entries of the matrices Amat and Pmat between the calls to f()
1133:    You should not assume the values are the same in the next call to f() as you set them in the previous call.

1135:    Level: beginner

1137: .keywords: TS, timestep, set, right-hand-side, Jacobian

1139: .seealso: SNESComputeJacobianDefaultColor(), TSSetRHSFunction(), TSRHSJacobianSetReuse(), TSSetIJacobian()

1141: @*/
1142: PetscErrorCode  TSSetRHSJacobian(TS ts,Mat Amat,Mat Pmat,TSRHSJacobian f,void *ctx)
1143: {
1145:   SNES           snes;
1146:   DM             dm;
1147:   TSIJacobian    ijacobian;


1156:   TSGetDM(ts,&dm);
1157:   DMTSSetRHSJacobian(dm,f,ctx);
1158:   if (f == TSComputeRHSJacobianConstant) {
1159:     /* Handle this case automatically for the user; otherwise user should call themselves. */
1160:     TSRHSJacobianSetReuse(ts,PETSC_TRUE);
1161:   }
1162:   DMTSGetIJacobian(dm,&ijacobian,NULL);
1163:   TSGetSNES(ts,&snes);
1164:   if (!ijacobian) {
1165:     SNESSetJacobian(snes,Amat,Pmat,SNESTSFormJacobian,ts);
1166:   }
1167:   if (Amat) {
1168:     PetscObjectReference((PetscObject)Amat);
1169:     MatDestroy(&ts->Arhs);
1170:     ts->Arhs = Amat;
1171:   }
1172:   if (Pmat) {
1173:     PetscObjectReference((PetscObject)Pmat);
1174:     MatDestroy(&ts->Brhs);
1175:     ts->Brhs = Pmat;
1176:   }
1177:   return(0);
1178: }


1183: /*@C
1184:    TSSetIFunction - Set the function to compute F(t,U,U_t) where F() = 0 is the DAE to be solved.

1186:    Logically Collective on TS

1188:    Input Parameters:
1189: +  ts  - the TS context obtained from TSCreate()
1190: .  r   - vector to hold the residual (or NULL to have it created internally)
1191: .  f   - the function evaluation routine
1192: -  ctx - user-defined context for private data for the function evaluation routine (may be NULL)

1194:    Calling sequence of f:
1195: $  f(TS ts,PetscReal t,Vec u,Vec u_t,Vec F,ctx);

1197: +  t   - time at step/stage being solved
1198: .  u   - state vector
1199: .  u_t - time derivative of state vector
1200: .  F   - function vector
1201: -  ctx - [optional] user-defined context for matrix evaluation routine

1203:    Important:
1204:    The user MUST call either this routine or TSSetRHSFunction() to define the ODE.  When solving DAEs you must use this function.

1206:    Level: beginner

1208: .keywords: TS, timestep, set, DAE, Jacobian

1210: .seealso: TSSetRHSJacobian(), TSSetRHSFunction(), TSSetIJacobian()
1211: @*/
1212: PetscErrorCode  TSSetIFunction(TS ts,Vec r,TSIFunction f,void *ctx)
1213: {
1215:   SNES           snes;
1216:   Vec            ralloc = NULL;
1217:   DM             dm;


1223:   TSGetDM(ts,&dm);
1224:   DMTSSetIFunction(dm,f,ctx);

1226:   TSGetSNES(ts,&snes);
1227:   if (!r && !ts->dm && ts->vec_sol) {
1228:     VecDuplicate(ts->vec_sol,&ralloc);
1229:     r  = ralloc;
1230:   }
1231:   SNESSetFunction(snes,r,SNESTSFormFunction,ts);
1232:   VecDestroy(&ralloc);
1233:   return(0);
1234: }

1238: /*@C
1239:    TSGetIFunction - Returns the vector where the implicit residual is stored and the function/contex to compute it.

1241:    Not Collective

1243:    Input Parameter:
1244: .  ts - the TS context

1246:    Output Parameter:
1247: +  r - vector to hold residual (or NULL)
1248: .  func - the function to compute residual (or NULL)
1249: -  ctx - the function context (or NULL)

1251:    Level: advanced

1253: .keywords: TS, nonlinear, get, function

1255: .seealso: TSSetIFunction(), SNESGetFunction()
1256: @*/
1257: PetscErrorCode TSGetIFunction(TS ts,Vec *r,TSIFunction *func,void **ctx)
1258: {
1260:   SNES           snes;
1261:   DM             dm;

1265:   TSGetSNES(ts,&snes);
1266:   SNESGetFunction(snes,r,NULL,NULL);
1267:   TSGetDM(ts,&dm);
1268:   DMTSGetIFunction(dm,func,ctx);
1269:   return(0);
1270: }

1274: /*@C
1275:    TSGetRHSFunction - Returns the vector where the right hand side is stored and the function/context to compute it.

1277:    Not Collective

1279:    Input Parameter:
1280: .  ts - the TS context

1282:    Output Parameter:
1283: +  r - vector to hold computed right hand side (or NULL)
1284: .  func - the function to compute right hand side (or NULL)
1285: -  ctx - the function context (or NULL)

1287:    Level: advanced

1289: .keywords: TS, nonlinear, get, function

1291: .seealso: TSSetRHSFunction(), SNESGetFunction()
1292: @*/
1293: PetscErrorCode TSGetRHSFunction(TS ts,Vec *r,TSRHSFunction *func,void **ctx)
1294: {
1296:   SNES           snes;
1297:   DM             dm;

1301:   TSGetSNES(ts,&snes);
1302:   SNESGetFunction(snes,r,NULL,NULL);
1303:   TSGetDM(ts,&dm);
1304:   DMTSGetRHSFunction(dm,func,ctx);
1305:   return(0);
1306: }

1310: /*@C
1311:    TSSetIJacobian - Set the function to compute the matrix dF/dU + a*dF/dU_t where F(t,U,U_t) is the function
1312:         provided with TSSetIFunction().

1314:    Logically Collective on TS

1316:    Input Parameters:
1317: +  ts  - the TS context obtained from TSCreate()
1318: .  Amat - (approximate) Jacobian matrix
1319: .  Pmat - matrix used to compute preconditioner (usually the same as Amat)
1320: .  f   - the Jacobian evaluation routine
1321: -  ctx - user-defined context for private data for the Jacobian evaluation routine (may be NULL)

1323:    Calling sequence of f:
1324: $  f(TS ts,PetscReal t,Vec U,Vec U_t,PetscReal a,Mat Amat,Mat Pmat,void *ctx);

1326: +  t    - time at step/stage being solved
1327: .  U    - state vector
1328: .  U_t  - time derivative of state vector
1329: .  a    - shift
1330: .  Amat - (approximate) Jacobian of F(t,U,W+a*U), equivalent to dF/dU + a*dF/dU_t
1331: .  Pmat - matrix used for constructing preconditioner, usually the same as Amat
1332: -  ctx  - [optional] user-defined context for matrix evaluation routine

1334:    Notes:
1335:    The matrices Amat and Pmat are exactly the matrices that are used by SNES for the nonlinear solve.

1337:    If you know the operator Amat has a null space you can use MatSetNullSpace() and MatSetTransposeNullSpace() to supply the null
1338:    space to Amat and the KSP solvers will automatically use that null space as needed during the solution process.

1340:    The matrix dF/dU + a*dF/dU_t you provide turns out to be
1341:    the Jacobian of F(t,U,W+a*U) where F(t,U,U_t) = 0 is the DAE to be solved.
1342:    The time integrator internally approximates U_t by W+a*U where the positive "shift"
1343:    a and vector W depend on the integration method, step size, and past states. For example with
1344:    the backward Euler method a = 1/dt and W = -a*U(previous timestep) so
1345:    W + a*U = a*(U - U(previous timestep)) = (U - U(previous timestep))/dt

1347:    You must set all the diagonal entries of the matrices, if they are zero you must still set them with a zero value

1349:    The TS solver may modify the nonzero structure and the entries of the matrices Amat and Pmat between the calls to f()
1350:    You should not assume the values are the same in the next call to f() as you set them in the previous call.

1352:    Level: beginner

1354: .keywords: TS, timestep, DAE, Jacobian

1356: .seealso: TSSetIFunction(), TSSetRHSJacobian(), SNESComputeJacobianDefaultColor(), SNESComputeJacobianDefault(), TSSetRHSFunction()

1358: @*/
1359: PetscErrorCode  TSSetIJacobian(TS ts,Mat Amat,Mat Pmat,TSIJacobian f,void *ctx)
1360: {
1362:   SNES           snes;
1363:   DM             dm;


1372:   TSGetDM(ts,&dm);
1373:   DMTSSetIJacobian(dm,f,ctx);

1375:   TSGetSNES(ts,&snes);
1376:   SNESSetJacobian(snes,Amat,Pmat,SNESTSFormJacobian,ts);
1377:   return(0);
1378: }

1382: /*@
1383:    TSRHSJacobianSetReuse - restore RHS Jacobian before re-evaluating.  Without this flag, TS will change the sign and
1384:    shift the RHS Jacobian for a finite-time-step implicit solve, in which case the user function will need to recompute
1385:    the entire Jacobian.  The reuse flag must be set if the evaluation function will assume that the matrix entries have
1386:    not been changed by the TS.

1388:    Logically Collective

1390:    Input Arguments:
1391: +  ts - TS context obtained from TSCreate()
1392: -  reuse - PETSC_TRUE if the RHS Jacobian

1394:    Level: intermediate

1396: .seealso: TSSetRHSJacobian(), TSComputeRHSJacobianConstant()
1397: @*/
1398: PetscErrorCode TSRHSJacobianSetReuse(TS ts,PetscBool reuse)
1399: {
1401:   ts->rhsjacobian.reuse = reuse;
1402:   return(0);
1403: }

1407: /*@C
1408:    TSSetI2Function - Set the function to compute F(t,U,U_t,U_tt) where F = 0 is the DAE to be solved.

1410:    Logically Collective on TS

1412:    Input Parameters:
1413: +  ts  - the TS context obtained from TSCreate()
1414: .  F   - vector to hold the residual (or NULL to have it created internally)
1415: .  fun - the function evaluation routine
1416: -  ctx - user-defined context for private data for the function evaluation routine (may be NULL)

1418:    Calling sequence of fun:
1419: $  fun(TS ts,PetscReal t,Vec U,Vec U_t,Vec U_tt,Vec F,ctx);

1421: +  t    - time at step/stage being solved
1422: .  U    - state vector
1423: .  U_t  - time derivative of state vector
1424: .  U_tt - second time derivative of state vector
1425: .  F    - function vector
1426: -  ctx  - [optional] user-defined context for matrix evaluation routine (may be NULL)

1428:    Level: beginner

1430: .keywords: TS, timestep, set, ODE, DAE, Function

1432: .seealso: TSSetI2Jacobian()
1433: @*/
1434: PetscErrorCode TSSetI2Function(TS ts,Vec F,TSI2Function fun,void *ctx)
1435: {
1436:   DM             dm;

1442:   TSSetIFunction(ts,F,NULL,NULL);
1443:   TSGetDM(ts,&dm);
1444:   DMTSSetI2Function(dm,fun,ctx);
1445:   return(0);
1446: }

1450: /*@C
1451:   TSGetI2Function - Returns the vector where the implicit residual is stored and the function/contex to compute it.

1453:   Not Collective

1455:   Input Parameter:
1456: . ts - the TS context

1458:   Output Parameter:
1459: + r - vector to hold residual (or NULL)
1460: . fun - the function to compute residual (or NULL)
1461: - ctx - the function context (or NULL)

1463:   Level: advanced

1465: .keywords: TS, nonlinear, get, function

1467: .seealso: TSSetI2Function(), SNESGetFunction()
1468: @*/
1469: PetscErrorCode TSGetI2Function(TS ts,Vec *r,TSI2Function *fun,void **ctx)
1470: {
1472:   SNES           snes;
1473:   DM             dm;

1477:   TSGetSNES(ts,&snes);
1478:   SNESGetFunction(snes,r,NULL,NULL);
1479:   TSGetDM(ts,&dm);
1480:   DMTSGetI2Function(dm,fun,ctx);
1481:   return(0);
1482: }

1486: /*@C
1487:    TSSetI2Jacobian - Set the function to compute the matrix dF/dU + v*dF/dU_t  + a*dF/dU_tt
1488:         where F(t,U,U_t,U_tt) is the function you provided with TSSetI2Function().

1490:    Logically Collective on TS

1492:    Input Parameters:
1493: +  ts  - the TS context obtained from TSCreate()
1494: .  J   - Jacobian matrix
1495: .  P   - preconditioning matrix for J (may be same as J)
1496: .  jac - the Jacobian evaluation routine
1497: -  ctx - user-defined context for private data for the Jacobian evaluation routine (may be NULL)

1499:    Calling sequence of jac:
1500: $  jac(TS ts,PetscReal t,Vec U,Vec U_t,Vec U_tt,PetscReal v,PetscReal a,Mat J,Mat P,void *ctx);

1502: +  t    - time at step/stage being solved
1503: .  U    - state vector
1504: .  U_t  - time derivative of state vector
1505: .  U_tt - second time derivative of state vector
1506: .  v    - shift for U_t
1507: .  a    - shift for U_tt
1508: .  J    - Jacobian of G(U) = F(t,U,W+v*U,W'+a*U), equivalent to dF/dU + v*dF/dU_t  + a*dF/dU_tt
1509: .  P    - preconditioning matrix for J, may be same as J
1510: -  ctx  - [optional] user-defined context for matrix evaluation routine

1512:    Notes:
1513:    The matrices J and P are exactly the matrices that are used by SNES for the nonlinear solve.

1515:    The matrix dF/dU + v*dF/dU_t + a*dF/dU_tt you provide turns out to be
1516:    the Jacobian of G(U) = F(t,U,W+v*U,W'+a*U) where F(t,U,U_t,U_tt) = 0 is the DAE to be solved.
1517:    The time integrator internally approximates U_t by W+v*U and U_tt by W'+a*U  where the positive "shift"
1518:    parameters 'v' and 'a' and vectors W, W' depend on the integration method, step size, and past states.

1520:    Level: beginner

1522: .keywords: TS, timestep, set, ODE, DAE, Jacobian

1524: .seealso: TSSetI2Function()
1525: @*/
1526: PetscErrorCode TSSetI2Jacobian(TS ts,Mat J,Mat P,TSI2Jacobian jac,void *ctx)
1527: {
1528:   DM             dm;

1535:   TSSetIJacobian(ts,J,P,NULL,NULL);
1536:   TSGetDM(ts,&dm);
1537:   DMTSSetI2Jacobian(dm,jac,ctx);
1538:   return(0);
1539: }

1543: /*@C
1544:   TSGetI2Jacobian - Returns the implicit Jacobian at the present timestep.

1546:   Not Collective, but parallel objects are returned if TS is parallel

1548:   Input Parameter:
1549: . ts  - The TS context obtained from TSCreate()

1551:   Output Parameters:
1552: + J  - The (approximate) Jacobian of F(t,U,U_t,U_tt)
1553: . P - The matrix from which the preconditioner is constructed, often the same as J
1554: . jac - The function to compute the Jacobian matrices
1555: - ctx - User-defined context for Jacobian evaluation routine

1557:   Notes: You can pass in NULL for any return argument you do not need.

1559:   Level: advanced

1561: .seealso: TSGetTimeStep(), TSGetMatrices(), TSGetTime(), TSGetTimeStepNumber()

1563: .keywords: TS, timestep, get, matrix, Jacobian
1564: @*/
1565: PetscErrorCode  TSGetI2Jacobian(TS ts,Mat *J,Mat *P,TSI2Jacobian *jac,void **ctx)
1566: {
1568:   SNES           snes;
1569:   DM             dm;

1572:   TSGetSNES(ts,&snes);
1573:   SNESSetUpMatrices(snes);
1574:   SNESGetJacobian(snes,J,P,NULL,NULL);
1575:   TSGetDM(ts,&dm);
1576:   DMTSGetI2Jacobian(dm,jac,ctx);
1577:   return(0);
1578: }

1582: /*@
1583:   TSComputeI2Function - Evaluates the DAE residual written in implicit form F(t,U,U_t,U_tt) = 0

1585:   Collective on TS and Vec

1587:   Input Parameters:
1588: + ts - the TS context
1589: . t - current time
1590: . U - state vector
1591: . V - time derivative of state vector (U_t)
1592: - A - second time derivative of state vector (U_tt)

1594:   Output Parameter:
1595: . F - the residual vector

1597:   Note:
1598:   Most users should not need to explicitly call this routine, as it
1599:   is used internally within the nonlinear solvers.

1601:   Level: developer

1603: .keywords: TS, compute, function, vector

1605: .seealso: TSSetI2Function()
1606: @*/
1607: PetscErrorCode TSComputeI2Function(TS ts,PetscReal t,Vec U,Vec V,Vec A,Vec F)
1608: {
1609:   DM             dm;
1610:   TSI2Function   I2Function;
1611:   void           *ctx;
1612:   TSRHSFunction  rhsfunction;


1622:   TSGetDM(ts,&dm);
1623:   DMTSGetI2Function(dm,&I2Function,&ctx);
1624:   DMTSGetRHSFunction(dm,&rhsfunction,NULL);

1626:   if (!I2Function) {
1627:     TSComputeIFunction(ts,t,U,A,F,PETSC_FALSE);
1628:     return(0);
1629:   }

1631:   PetscLogEventBegin(TS_FunctionEval,ts,U,V,F);

1633:   PetscStackPush("TS user implicit function");
1634:   I2Function(ts,t,U,V,A,F,ctx);
1635:   PetscStackPop;

1637:   if (rhsfunction) {
1638:     Vec Frhs;
1639:     TSGetRHSVec_Private(ts,&Frhs);
1640:     TSComputeRHSFunction(ts,t,U,Frhs);
1641:     VecAXPY(F,-1,Frhs);
1642:   }

1644:   PetscLogEventEnd(TS_FunctionEval,ts,U,V,F);
1645:   return(0);
1646: }

1650: /*@
1651:   TSComputeI2Jacobian - Evaluates the Jacobian of the DAE

1653:   Collective on TS and Vec

1655:   Input Parameters:
1656: + ts - the TS context
1657: . t - current timestep
1658: . U - state vector
1659: . V - time derivative of state vector
1660: . A - second time derivative of state vector
1661: . shiftV - shift to apply, see note below
1662: - shiftA - shift to apply, see note below

1664:   Output Parameters:
1665: + J - Jacobian matrix
1666: - P - optional preconditioning matrix

1668:   Notes:
1669:   If F(t,U,V,A)=0 is the DAE, the required Jacobian is

1671:   dF/dU + shiftV*dF/dV + shiftA*dF/dA

1673:   Most users should not need to explicitly call this routine, as it
1674:   is used internally within the nonlinear solvers.

1676:   Level: developer

1678: .keywords: TS, compute, Jacobian, matrix

1680: .seealso:  TSSetI2Jacobian()
1681: @*/
1682: PetscErrorCode TSComputeI2Jacobian(TS ts,PetscReal t,Vec U,Vec V,Vec A,PetscReal shiftV,PetscReal shiftA,Mat J,Mat P)
1683: {
1684:   DM             dm;
1685:   TSI2Jacobian   I2Jacobian;
1686:   void           *ctx;
1687:   TSRHSJacobian  rhsjacobian;


1698:   TSGetDM(ts,&dm);
1699:   DMTSGetI2Jacobian(dm,&I2Jacobian,&ctx);
1700:   DMTSGetRHSJacobian(dm,&rhsjacobian,NULL);

1702:   if (!I2Jacobian) {
1703:     TSComputeIJacobian(ts,t,U,A,shiftA,J,P,PETSC_FALSE);
1704:     return(0);
1705:   }

1707:   PetscLogEventBegin(TS_JacobianEval,ts,U,J,P);

1709:   PetscStackPush("TS user implicit Jacobian");
1710:   I2Jacobian(ts,t,U,V,A,shiftV,shiftA,J,P,ctx);
1711:   PetscStackPop;

1713:   if (rhsjacobian) {
1714:     Mat Jrhs,Prhs; MatStructure axpy = DIFFERENT_NONZERO_PATTERN;
1715:     TSGetRHSMats_Private(ts,&Jrhs,&Prhs);
1716:     TSComputeRHSJacobian(ts,t,U,Jrhs,Prhs);
1717:     MatAXPY(J,-1,Jrhs,axpy);
1718:     if (P != J) {MatAXPY(P,-1,Prhs,axpy);}
1719:   }

1721:   PetscLogEventEnd(TS_JacobianEval,ts,U,J,P);
1722:   return(0);
1723: }

1727: /*@
1728:    TS2SetSolution - Sets the initial solution and time derivative vectors
1729:    for use by the TS routines handling second order equations.

1731:    Logically Collective on TS and Vec

1733:    Input Parameters:
1734: +  ts - the TS context obtained from TSCreate()
1735: .  u - the solution vector
1736: -  v - the time derivative vector

1738:    Level: beginner

1740: .keywords: TS, timestep, set, solution, initial conditions
1741: @*/
1742: PetscErrorCode  TS2SetSolution(TS ts,Vec u,Vec v)
1743: {

1750:   TSSetSolution(ts,u);
1751:   PetscObjectReference((PetscObject)v);
1752:   VecDestroy(&ts->vec_dot);
1753:   ts->vec_dot = v;
1754:   return(0);
1755: }

1759: /*@
1760:    TS2GetSolution - Returns the solution and time derivative at the present timestep
1761:    for second order equations. It is valid to call this routine inside the function
1762:    that you are evaluating in order to move to the new timestep. This vector not
1763:    changed until the solution at the next timestep has been calculated.

1765:    Not Collective, but Vec returned is parallel if TS is parallel

1767:    Input Parameter:
1768: .  ts - the TS context obtained from TSCreate()

1770:    Output Parameter:
1771: +  u - the vector containing the solution
1772: -  v - the vector containing the time derivative

1774:    Level: intermediate

1776: .seealso: TS2SetSolution(), TSGetTimeStep(), TSGetTime()

1778: .keywords: TS, timestep, get, solution
1779: @*/
1780: PetscErrorCode  TS2GetSolution(TS ts,Vec *u,Vec *v)
1781: {
1786:   if (u) *u = ts->vec_sol;
1787:   if (v) *v = ts->vec_dot;
1788:   return(0);
1789: }

1793: /*@C
1794:   TSLoad - Loads a KSP that has been stored in binary  with KSPView().

1796:   Collective on PetscViewer

1798:   Input Parameters:
1799: + newdm - the newly loaded TS, this needs to have been created with TSCreate() or
1800:            some related function before a call to TSLoad().
1801: - viewer - binary file viewer, obtained from PetscViewerBinaryOpen()

1803:    Level: intermediate

1805:   Notes:
1806:    The type is determined by the data in the file, any type set into the TS before this call is ignored.

1808:   Notes for advanced users:
1809:   Most users should not need to know the details of the binary storage
1810:   format, since TSLoad() and TSView() completely hide these details.
1811:   But for anyone who's interested, the standard binary matrix storage
1812:   format is
1813: .vb
1814:      has not yet been determined
1815: .ve

1817: .seealso: PetscViewerBinaryOpen(), TSView(), MatLoad(), VecLoad()
1818: @*/
1819: PetscErrorCode  TSLoad(TS ts, PetscViewer viewer)
1820: {
1822:   PetscBool      isbinary;
1823:   PetscInt       classid;
1824:   char           type[256];
1825:   DMTS           sdm;
1826:   DM             dm;

1831:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERBINARY,&isbinary);
1832:   if (!isbinary) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,"Invalid viewer; open viewer with PetscViewerBinaryOpen()");

1834:   PetscViewerBinaryRead(viewer,&classid,1,NULL,PETSC_INT);
1835:   if (classid != TS_FILE_CLASSID) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_ARG_WRONG,"Not TS next in file");
1836:   PetscViewerBinaryRead(viewer,type,256,NULL,PETSC_CHAR);
1837:   TSSetType(ts, type);
1838:   if (ts->ops->load) {
1839:     (*ts->ops->load)(ts,viewer);
1840:   }
1841:   DMCreate(PetscObjectComm((PetscObject)ts),&dm);
1842:   DMLoad(dm,viewer);
1843:   TSSetDM(ts,dm);
1844:   DMCreateGlobalVector(ts->dm,&ts->vec_sol);
1845:   VecLoad(ts->vec_sol,viewer);
1846:   DMGetDMTS(ts->dm,&sdm);
1847:   DMTSLoad(sdm,viewer);
1848:   return(0);
1849: }

1851: #include <petscdraw.h>
1852: #if defined(PETSC_HAVE_SAWS)
1853: #include <petscviewersaws.h>
1854: #endif
1857: /*@C
1858:     TSView - Prints the TS data structure.

1860:     Collective on TS

1862:     Input Parameters:
1863: +   ts - the TS context obtained from TSCreate()
1864: -   viewer - visualization context

1866:     Options Database Key:
1867: .   -ts_view - calls TSView() at end of TSStep()

1869:     Notes:
1870:     The available visualization contexts include
1871: +     PETSC_VIEWER_STDOUT_SELF - standard output (default)
1872: -     PETSC_VIEWER_STDOUT_WORLD - synchronized standard
1873:          output where only the first processor opens
1874:          the file.  All other processors send their
1875:          data to the first processor to print.

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

1880:     Level: beginner

1882: .keywords: TS, timestep, view

1884: .seealso: PetscViewerASCIIOpen()
1885: @*/
1886: PetscErrorCode  TSView(TS ts,PetscViewer viewer)
1887: {
1889:   TSType         type;
1890:   PetscBool      iascii,isstring,isundials,isbinary,isdraw;
1891:   DMTS           sdm;
1892: #if defined(PETSC_HAVE_SAWS)
1893:   PetscBool      issaws;
1894: #endif

1898:   if (!viewer) {
1899:     PetscViewerASCIIGetStdout(PetscObjectComm((PetscObject)ts),&viewer);
1900:   }

1904:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERASCII,&iascii);
1905:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERSTRING,&isstring);
1906:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERBINARY,&isbinary);
1907:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERDRAW,&isdraw);
1908: #if defined(PETSC_HAVE_SAWS)
1909:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERSAWS,&issaws);
1910: #endif
1911:   if (iascii) {
1912:     PetscObjectPrintClassNamePrefixType((PetscObject)ts,viewer);
1913:     PetscViewerASCIIPrintf(viewer,"  maximum steps=%D\n",ts->max_steps);
1914:     PetscViewerASCIIPrintf(viewer,"  maximum time=%g\n",(double)ts->max_time);
1915:     if (ts->problem_type == TS_NONLINEAR) {
1916:       PetscViewerASCIIPrintf(viewer,"  total number of nonlinear solver iterations=%D\n",ts->snes_its);
1917:       PetscViewerASCIIPrintf(viewer,"  total number of nonlinear solve failures=%D\n",ts->num_snes_failures);
1918:     }
1919:     PetscViewerASCIIPrintf(viewer,"  total number of linear solver iterations=%D\n",ts->ksp_its);
1920:     PetscViewerASCIIPrintf(viewer,"  total number of rejected steps=%D\n",ts->reject);
1921:     DMGetDMTS(ts->dm,&sdm);
1922:     DMTSView(sdm,viewer);
1923:     if (ts->ops->view) {
1924:       PetscViewerASCIIPushTab(viewer);
1925:       (*ts->ops->view)(ts,viewer);
1926:       PetscViewerASCIIPopTab(viewer);
1927:     }
1928:   } else if (isstring) {
1929:     TSGetType(ts,&type);
1930:     PetscViewerStringSPrintf(viewer," %-7.7s",type);
1931:   } else if (isbinary) {
1932:     PetscInt    classid = TS_FILE_CLASSID;
1933:     MPI_Comm    comm;
1934:     PetscMPIInt rank;
1935:     char        type[256];

1937:     PetscObjectGetComm((PetscObject)ts,&comm);
1938:     MPI_Comm_rank(comm,&rank);
1939:     if (!rank) {
1940:       PetscViewerBinaryWrite(viewer,&classid,1,PETSC_INT,PETSC_FALSE);
1941:       PetscStrncpy(type,((PetscObject)ts)->type_name,256);
1942:       PetscViewerBinaryWrite(viewer,type,256,PETSC_CHAR,PETSC_FALSE);
1943:     }
1944:     if (ts->ops->view) {
1945:       (*ts->ops->view)(ts,viewer);
1946:     }
1947:     DMView(ts->dm,viewer);
1948:     VecView(ts->vec_sol,viewer);
1949:     DMGetDMTS(ts->dm,&sdm);
1950:     DMTSView(sdm,viewer);
1951:   } else if (isdraw) {
1952:     PetscDraw draw;
1953:     char      str[36];
1954:     PetscReal x,y,bottom,h;

1956:     PetscViewerDrawGetDraw(viewer,0,&draw);
1957:     PetscDrawGetCurrentPoint(draw,&x,&y);
1958:     PetscStrcpy(str,"TS: ");
1959:     PetscStrcat(str,((PetscObject)ts)->type_name);
1960:     PetscDrawStringBoxed(draw,x,y,PETSC_DRAW_BLACK,PETSC_DRAW_BLACK,str,NULL,&h);
1961:     bottom = y - h;
1962:     PetscDrawPushCurrentPoint(draw,x,bottom);
1963:     if (ts->ops->view) {
1964:       (*ts->ops->view)(ts,viewer);
1965:     }
1966:     PetscDrawPopCurrentPoint(draw);
1967: #if defined(PETSC_HAVE_SAWS)
1968:   } else if (issaws) {
1969:     PetscMPIInt rank;
1970:     const char  *name;

1972:     PetscObjectGetName((PetscObject)ts,&name);
1973:     MPI_Comm_rank(PETSC_COMM_WORLD,&rank);
1974:     if (!((PetscObject)ts)->amsmem && !rank) {
1975:       char       dir[1024];

1977:       PetscObjectViewSAWs((PetscObject)ts,viewer);
1978:       PetscSNPrintf(dir,1024,"/PETSc/Objects/%s/time_step",name);
1979:       PetscStackCallSAWs(SAWs_Register,(dir,&ts->steps,1,SAWs_READ,SAWs_INT));
1980:       PetscSNPrintf(dir,1024,"/PETSc/Objects/%s/time",name);
1981:       PetscStackCallSAWs(SAWs_Register,(dir,&ts->ptime,1,SAWs_READ,SAWs_DOUBLE));
1982:     }
1983:     if (ts->ops->view) {
1984:       (*ts->ops->view)(ts,viewer);
1985:     }
1986: #endif
1987:   }

1989:   PetscViewerASCIIPushTab(viewer);
1990:   PetscObjectTypeCompare((PetscObject)ts,TSSUNDIALS,&isundials);
1991:   PetscViewerASCIIPopTab(viewer);
1992:   return(0);
1993: }


1998: /*@
1999:    TSSetApplicationContext - Sets an optional user-defined context for
2000:    the timesteppers.

2002:    Logically Collective on TS

2004:    Input Parameters:
2005: +  ts - the TS context obtained from TSCreate()
2006: -  usrP - optional user context

2008:    Fortran Notes: To use this from Fortran you must write a Fortran interface definition for this
2009:     function that tells Fortran the Fortran derived data type that you are passing in as the ctx argument.

2011:    Level: intermediate

2013: .keywords: TS, timestep, set, application, context

2015: .seealso: TSGetApplicationContext()
2016: @*/
2017: PetscErrorCode  TSSetApplicationContext(TS ts,void *usrP)
2018: {
2021:   ts->user = usrP;
2022:   return(0);
2023: }

2027: /*@
2028:     TSGetApplicationContext - Gets the user-defined context for the
2029:     timestepper.

2031:     Not Collective

2033:     Input Parameter:
2034: .   ts - the TS context obtained from TSCreate()

2036:     Output Parameter:
2037: .   usrP - user context

2039:    Fortran Notes: To use this from Fortran you must write a Fortran interface definition for this
2040:     function that tells Fortran the Fortran derived data type that you are passing in as the ctx argument.

2042:     Level: intermediate

2044: .keywords: TS, timestep, get, application, context

2046: .seealso: TSSetApplicationContext()
2047: @*/
2048: PetscErrorCode  TSGetApplicationContext(TS ts,void *usrP)
2049: {
2052:   *(void**)usrP = ts->user;
2053:   return(0);
2054: }

2058: /*@
2059:    TSGetTimeStepNumber - Gets the number of time steps completed.

2061:    Not Collective

2063:    Input Parameter:
2064: .  ts - the TS context obtained from TSCreate()

2066:    Output Parameter:
2067: .  iter - number of steps completed so far

2069:    Level: intermediate

2071: .keywords: TS, timestep, get, iteration, number
2072: .seealso: TSGetTime(), TSGetTimeStep(), TSSetPreStep(), TSSetPreStage(), TSSetPostStage(), TSSetPostStep()
2073: @*/
2074: PetscErrorCode  TSGetTimeStepNumber(TS ts,PetscInt *iter)
2075: {
2079:   *iter = ts->steps;
2080:   return(0);
2081: }

2085: /*@
2086:    TSSetInitialTimeStep - Sets the initial timestep to be used,
2087:    as well as the initial time.

2089:    Logically Collective on TS

2091:    Input Parameters:
2092: +  ts - the TS context obtained from TSCreate()
2093: .  initial_time - the initial time
2094: -  time_step - the size of the timestep

2096:    Level: intermediate

2098: .seealso: TSSetTimeStep(), TSGetTimeStep()

2100: .keywords: TS, set, initial, timestep
2101: @*/
2102: PetscErrorCode  TSSetInitialTimeStep(TS ts,PetscReal initial_time,PetscReal time_step)
2103: {

2108:   TSSetTimeStep(ts,time_step);
2109:   TSSetTime(ts,initial_time);
2110:   return(0);
2111: }

2115: /*@
2116:    TSSetTimeStep - Allows one to reset the timestep at any time,
2117:    useful for simple pseudo-timestepping codes.

2119:    Logically Collective on TS

2121:    Input Parameters:
2122: +  ts - the TS context obtained from TSCreate()
2123: -  time_step - the size of the timestep

2125:    Level: intermediate

2127: .seealso: TSSetInitialTimeStep(), TSGetTimeStep()

2129: .keywords: TS, set, timestep
2130: @*/
2131: PetscErrorCode  TSSetTimeStep(TS ts,PetscReal time_step)
2132: {
2136:   ts->time_step = time_step;
2137:   return(0);
2138: }

2142: /*@
2143:    TSSetExactFinalTime - Determines whether to adapt the final time step to
2144:      match the exact final time, interpolate solution to the exact final time,
2145:      or just return at the final time TS computed.

2147:   Logically Collective on TS

2149:    Input Parameter:
2150: +   ts - the time-step context
2151: -   eftopt - exact final time option

2153: $  TS_EXACTFINALTIME_STEPOVER    - Don't do anything if final time is exceeded
2154: $  TS_EXACTFINALTIME_INTERPOLATE - Interpolate back to final time
2155: $  TS_EXACTFINALTIME_MATCHSTEP - Adapt final time step to match the final time

2157:    Options Database:
2158: .   -ts_exact_final_time <stepover,interpolate,matchstep> - select the final step at runtime

2160:    Warning: If you use the option TS_EXACTFINALTIME_STEPOVER the solution may be at a very different time
2161:     then the final time you selected.

2163:    Level: beginner

2165: .seealso: TSExactFinalTimeOption
2166: @*/
2167: PetscErrorCode  TSSetExactFinalTime(TS ts,TSExactFinalTimeOption eftopt)
2168: {
2172:   ts->exact_final_time = eftopt;
2173:   return(0);
2174: }

2178: /*@
2179:    TSGetTimeStep - Gets the current timestep size.

2181:    Not Collective

2183:    Input Parameter:
2184: .  ts - the TS context obtained from TSCreate()

2186:    Output Parameter:
2187: .  dt - the current timestep size

2189:    Level: intermediate

2191: .seealso: TSSetInitialTimeStep(), TSGetTimeStep()

2193: .keywords: TS, get, timestep
2194: @*/
2195: PetscErrorCode  TSGetTimeStep(TS ts,PetscReal *dt)
2196: {
2200:   *dt = ts->time_step;
2201:   return(0);
2202: }

2206: /*@
2207:    TSGetSolution - Returns the solution at the present timestep. It
2208:    is valid to call this routine inside the function that you are evaluating
2209:    in order to move to the new timestep. This vector not changed until
2210:    the solution at the next timestep has been calculated.

2212:    Not Collective, but Vec returned is parallel if TS is parallel

2214:    Input Parameter:
2215: .  ts - the TS context obtained from TSCreate()

2217:    Output Parameter:
2218: .  v - the vector containing the solution

2220:    Note: If you used TSSetExactFinalTime(ts,TS_EXACTFINALTIME_MATCHSTEP); this does not return the solution at the requested
2221:    final time. It returns the solution at the next timestep.

2223:    Level: intermediate

2225: .seealso: TSGetTimeStep(), TSGetTime(), TSGetSolveTime()

2227: .keywords: TS, timestep, get, solution
2228: @*/
2229: PetscErrorCode  TSGetSolution(TS ts,Vec *v)
2230: {
2234:   *v = ts->vec_sol;
2235:   return(0);
2236: }

2240: /*@
2241:    TSGetCostGradients - Returns the gradients from the TSAdjointSolve()

2243:    Not Collective, but Vec returned is parallel if TS is parallel

2245:    Input Parameter:
2246: .  ts - the TS context obtained from TSCreate()

2248:    Output Parameter:
2249: +  lambda - vectors containing the gradients of the cost functions with respect to the ODE/DAE solution variables
2250: -  mu - vectors containing the gradients of the cost functions with respect to the problem parameters

2252:    Level: intermediate

2254: .seealso: TSGetTimeStep()

2256: .keywords: TS, timestep, get, sensitivity
2257: @*/
2258: PetscErrorCode  TSGetCostGradients(TS ts,PetscInt *numcost,Vec **lambda,Vec **mu)
2259: {
2262:   if (numcost) *numcost = ts->numcost;
2263:   if (lambda)  *lambda  = ts->vecs_sensi;
2264:   if (mu)      *mu      = ts->vecs_sensip;
2265:   return(0);
2266: }

2268: /* ----- Routines to initialize and destroy a timestepper ---- */
2271: /*@
2272:   TSSetProblemType - Sets the type of problem to be solved.

2274:   Not collective

2276:   Input Parameters:
2277: + ts   - The TS
2278: - type - One of TS_LINEAR, TS_NONLINEAR where these types refer to problems of the forms
2279: .vb
2280:          U_t - A U = 0      (linear)
2281:          U_t - A(t) U = 0   (linear)
2282:          F(t,U,U_t) = 0     (nonlinear)
2283: .ve

2285:    Level: beginner

2287: .keywords: TS, problem type
2288: .seealso: TSSetUp(), TSProblemType, TS
2289: @*/
2290: PetscErrorCode  TSSetProblemType(TS ts, TSProblemType type)
2291: {

2296:   ts->problem_type = type;
2297:   if (type == TS_LINEAR) {
2298:     SNES snes;
2299:     TSGetSNES(ts,&snes);
2300:     SNESSetType(snes,SNESKSPONLY);
2301:   }
2302:   return(0);
2303: }

2307: /*@C
2308:   TSGetProblemType - Gets the type of problem to be solved.

2310:   Not collective

2312:   Input Parameter:
2313: . ts   - The TS

2315:   Output Parameter:
2316: . type - One of TS_LINEAR, TS_NONLINEAR where these types refer to problems of the forms
2317: .vb
2318:          M U_t = A U
2319:          M(t) U_t = A(t) U
2320:          F(t,U,U_t)
2321: .ve

2323:    Level: beginner

2325: .keywords: TS, problem type
2326: .seealso: TSSetUp(), TSProblemType, TS
2327: @*/
2328: PetscErrorCode  TSGetProblemType(TS ts, TSProblemType *type)
2329: {
2333:   *type = ts->problem_type;
2334:   return(0);
2335: }

2339: /*@
2340:    TSSetUp - Sets up the internal data structures for the later use
2341:    of a timestepper.

2343:    Collective on TS

2345:    Input Parameter:
2346: .  ts - the TS context obtained from TSCreate()

2348:    Notes:
2349:    For basic use of the TS solvers the user need not explicitly call
2350:    TSSetUp(), since these actions will automatically occur during
2351:    the call to TSStep().  However, if one wishes to control this
2352:    phase separately, TSSetUp() should be called after TSCreate()
2353:    and optional routines of the form TSSetXXX(), but before TSStep().

2355:    Level: advanced

2357: .keywords: TS, timestep, setup

2359: .seealso: TSCreate(), TSStep(), TSDestroy()
2360: @*/
2361: PetscErrorCode  TSSetUp(TS ts)
2362: {
2364:   DM             dm;
2365:   PetscErrorCode (*func)(SNES,Vec,Vec,void*);
2366:   PetscErrorCode (*jac)(SNES,Vec,Mat,Mat,void*);
2367:   TSIFunction    ifun;
2368:   TSIJacobian    ijac;
2369:   TSI2Jacobian   i2jac;
2370:   TSRHSJacobian  rhsjac;

2374:   if (ts->setupcalled) return(0);

2376:   ts->total_steps = 0;
2377:   if (!((PetscObject)ts)->type_name) {
2378:     TSGetIFunction(ts,NULL,&ifun,NULL);
2379:     TSSetType(ts,ifun ? TSBEULER : TSEULER);
2380:   }

2382:   if (!ts->vec_sol) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Must call TSSetSolution() first");

2384:   if (ts->rhsjacobian.reuse) {
2385:     Mat Amat,Pmat;
2386:     SNES snes;
2387:     TSGetSNES(ts,&snes);
2388:     SNESGetJacobian(snes,&Amat,&Pmat,NULL,NULL);
2389:     /* Matching matrices implies that an IJacobian is NOT set, because if it had been set, the IJacobian's matrix would
2390:      * have displaced the RHS matrix */
2391:     if (Amat == ts->Arhs) {
2392:       MatDuplicate(ts->Arhs,MAT_DO_NOT_COPY_VALUES,&Amat);
2393:       SNESSetJacobian(snes,Amat,NULL,NULL,NULL);
2394:       MatDestroy(&Amat);
2395:     }
2396:     if (Pmat == ts->Brhs) {
2397:       MatDuplicate(ts->Brhs,MAT_DO_NOT_COPY_VALUES,&Pmat);
2398:       SNESSetJacobian(snes,NULL,Pmat,NULL,NULL);
2399:       MatDestroy(&Pmat);
2400:     }
2401:   }
2402:   if (ts->ops->setup) {
2403:     (*ts->ops->setup)(ts);
2404:   }

2406:   /* In the case where we've set a DMTSFunction or what have you, we need the default SNESFunction
2407:      to be set right but can't do it elsewhere due to the overreliance on ctx=ts.
2408:    */
2409:   TSGetDM(ts,&dm);
2410:   DMSNESGetFunction(dm,&func,NULL);
2411:   if (!func) {
2412:     DMSNESSetFunction(dm,SNESTSFormFunction,ts);
2413:   }
2414:   /* If the SNES doesn't have a jacobian set and the TS has an ijacobian or rhsjacobian set, set the SNES to use it.
2415:      Otherwise, the SNES will use coloring internally to form the Jacobian.
2416:    */
2417:   DMSNESGetJacobian(dm,&jac,NULL);
2418:   DMTSGetIJacobian(dm,&ijac,NULL);
2419:   DMTSGetI2Jacobian(dm,&i2jac,NULL);
2420:   DMTSGetRHSJacobian(dm,&rhsjac,NULL);
2421:   if (!jac && (ijac || i2jac || rhsjac)) {
2422:     DMSNESSetJacobian(dm,SNESTSFormJacobian,ts);
2423:   }
2424:   ts->setupcalled = PETSC_TRUE;
2425:   return(0);
2426: }

2430: /*@
2431:    TSAdjointSetUp - Sets up the internal data structures for the later use
2432:    of an adjoint solver

2434:    Collective on TS

2436:    Input Parameter:
2437: .  ts - the TS context obtained from TSCreate()

2439:    Level: advanced

2441: .keywords: TS, timestep, setup

2443: .seealso: TSCreate(), TSAdjointStep(), TSSetCostGradients()
2444: @*/
2445: PetscErrorCode  TSAdjointSetUp(TS ts)
2446: {

2451:   if (ts->adjointsetupcalled) return(0);
2452:   if (!ts->vecs_sensi) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Must call TSSetCostGradients() first");

2454:   if (ts->vec_costintegral) { /* if there is integral in the cost function*/
2455:     VecDuplicateVecs(ts->vecs_sensi[0],ts->numcost,&ts->vecs_drdy);
2456:     if (ts->vecs_sensip){
2457:       VecDuplicateVecs(ts->vecs_sensip[0],ts->numcost,&ts->vecs_drdp);
2458:     }
2459:   }

2461:   if (ts->ops->adjointsetup) {
2462:     (*ts->ops->adjointsetup)(ts);
2463:   }
2464:   ts->adjointsetupcalled = PETSC_TRUE;
2465:   return(0);
2466: }

2470: /*@
2471:    TSReset - Resets a TS context and removes any allocated Vecs and Mats.

2473:    Collective on TS

2475:    Input Parameter:
2476: .  ts - the TS context obtained from TSCreate()

2478:    Level: beginner

2480: .keywords: TS, timestep, reset

2482: .seealso: TSCreate(), TSSetup(), TSDestroy()
2483: @*/
2484: PetscErrorCode  TSReset(TS ts)
2485: {


2491:   if (ts->ops->reset) {
2492:     (*ts->ops->reset)(ts);
2493:   }
2494:   if (ts->snes) {SNESReset(ts->snes);}
2495:   if (ts->adapt) {TSAdaptReset(ts->adapt);}

2497:   MatDestroy(&ts->Arhs);
2498:   MatDestroy(&ts->Brhs);
2499:   VecDestroy(&ts->Frhs);
2500:   VecDestroy(&ts->vec_sol);
2501:   VecDestroy(&ts->vec_dot);
2502:   VecDestroy(&ts->vatol);
2503:   VecDestroy(&ts->vrtol);
2504:   VecDestroyVecs(ts->nwork,&ts->work);

2506:  if (ts->vec_costintegral) {
2507:     VecDestroyVecs(ts->numcost,&ts->vecs_drdy);
2508:     if (ts->vecs_drdp){
2509:       VecDestroyVecs(ts->numcost,&ts->vecs_drdp);
2510:     }
2511:   }
2512:   ts->vecs_sensi  = NULL;
2513:   ts->vecs_sensip = NULL;
2514:   MatDestroy(&ts->Jacp);
2515:   VecDestroy(&ts->vec_costintegral);
2516:   VecDestroy(&ts->vec_costintegrand);
2517:   ts->setupcalled = PETSC_FALSE;
2518:   return(0);
2519: }

2523: /*@
2524:    TSDestroy - Destroys the timestepper context that was created
2525:    with TSCreate().

2527:    Collective on TS

2529:    Input Parameter:
2530: .  ts - the TS context obtained from TSCreate()

2532:    Level: beginner

2534: .keywords: TS, timestepper, destroy

2536: .seealso: TSCreate(), TSSetUp(), TSSolve()
2537: @*/
2538: PetscErrorCode  TSDestroy(TS *ts)
2539: {

2543:   if (!*ts) return(0);
2545:   if (--((PetscObject)(*ts))->refct > 0) {*ts = 0; return(0);}

2547:   TSReset((*ts));

2549:   /* if memory was published with SAWs then destroy it */
2550:   PetscObjectSAWsViewOff((PetscObject)*ts);
2551:   if ((*ts)->ops->destroy) {(*(*ts)->ops->destroy)((*ts));}

2553:   TSTrajectoryDestroy(&(*ts)->trajectory);

2555:   TSAdaptDestroy(&(*ts)->adapt);
2556:   TSEventDestroy(&(*ts)->event);

2558:   SNESDestroy(&(*ts)->snes);
2559:   DMDestroy(&(*ts)->dm);
2560:   TSMonitorCancel((*ts));
2561:   TSAdjointMonitorCancel((*ts));

2563:   PetscHeaderDestroy(ts);
2564:   return(0);
2565: }

2569: /*@
2570:    TSGetSNES - Returns the SNES (nonlinear solver) associated with
2571:    a TS (timestepper) context. Valid only for nonlinear problems.

2573:    Not Collective, but SNES is parallel if TS is parallel

2575:    Input Parameter:
2576: .  ts - the TS context obtained from TSCreate()

2578:    Output Parameter:
2579: .  snes - the nonlinear solver context

2581:    Notes:
2582:    The user can then directly manipulate the SNES context to set various
2583:    options, etc.  Likewise, the user can then extract and manipulate the
2584:    KSP, KSP, and PC contexts as well.

2586:    TSGetSNES() does not work for integrators that do not use SNES; in
2587:    this case TSGetSNES() returns NULL in snes.

2589:    Level: beginner

2591: .keywords: timestep, get, SNES
2592: @*/
2593: PetscErrorCode  TSGetSNES(TS ts,SNES *snes)
2594: {

2600:   if (!ts->snes) {
2601:     SNESCreate(PetscObjectComm((PetscObject)ts),&ts->snes);
2602:     SNESSetFunction(ts->snes,NULL,SNESTSFormFunction,ts);
2603:     PetscLogObjectParent((PetscObject)ts,(PetscObject)ts->snes);
2604:     PetscObjectIncrementTabLevel((PetscObject)ts->snes,(PetscObject)ts,1);
2605:     if (ts->dm) {SNESSetDM(ts->snes,ts->dm);}
2606:     if (ts->problem_type == TS_LINEAR) {
2607:       SNESSetType(ts->snes,SNESKSPONLY);
2608:     }
2609:   }
2610:   *snes = ts->snes;
2611:   return(0);
2612: }

2616: /*@
2617:    TSSetSNES - Set the SNES (nonlinear solver) to be used by the timestepping context

2619:    Collective

2621:    Input Parameter:
2622: +  ts - the TS context obtained from TSCreate()
2623: -  snes - the nonlinear solver context

2625:    Notes:
2626:    Most users should have the TS created by calling TSGetSNES()

2628:    Level: developer

2630: .keywords: timestep, set, SNES
2631: @*/
2632: PetscErrorCode TSSetSNES(TS ts,SNES snes)
2633: {
2635:   PetscErrorCode (*func)(SNES,Vec,Mat,Mat,void*);

2640:   PetscObjectReference((PetscObject)snes);
2641:   SNESDestroy(&ts->snes);

2643:   ts->snes = snes;

2645:   SNESSetFunction(ts->snes,NULL,SNESTSFormFunction,ts);
2646:   SNESGetJacobian(ts->snes,NULL,NULL,&func,NULL);
2647:   if (func == SNESTSFormJacobian) {
2648:     SNESSetJacobian(ts->snes,NULL,NULL,SNESTSFormJacobian,ts);
2649:   }
2650:   return(0);
2651: }

2655: /*@
2656:    TSGetKSP - Returns the KSP (linear solver) associated with
2657:    a TS (timestepper) context.

2659:    Not Collective, but KSP is parallel if TS is parallel

2661:    Input Parameter:
2662: .  ts - the TS context obtained from TSCreate()

2664:    Output Parameter:
2665: .  ksp - the nonlinear solver context

2667:    Notes:
2668:    The user can then directly manipulate the KSP context to set various
2669:    options, etc.  Likewise, the user can then extract and manipulate the
2670:    KSP and PC contexts as well.

2672:    TSGetKSP() does not work for integrators that do not use KSP;
2673:    in this case TSGetKSP() returns NULL in ksp.

2675:    Level: beginner

2677: .keywords: timestep, get, KSP
2678: @*/
2679: PetscErrorCode  TSGetKSP(TS ts,KSP *ksp)
2680: {
2682:   SNES           snes;

2687:   if (!((PetscObject)ts)->type_name) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_NULL,"KSP is not created yet. Call TSSetType() first");
2688:   if (ts->problem_type != TS_LINEAR) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,"Linear only; use TSGetSNES()");
2689:   TSGetSNES(ts,&snes);
2690:   SNESGetKSP(snes,ksp);
2691:   return(0);
2692: }

2694: /* ----------- Routines to set solver parameters ---------- */

2698: /*@
2699:    TSGetDuration - Gets the maximum number of timesteps to use and
2700:    maximum time for iteration.

2702:    Not Collective

2704:    Input Parameters:
2705: +  ts       - the TS context obtained from TSCreate()
2706: .  maxsteps - maximum number of iterations to use, or NULL
2707: -  maxtime  - final time to iterate to, or NULL

2709:    Level: intermediate

2711: .keywords: TS, timestep, get, maximum, iterations, time
2712: @*/
2713: PetscErrorCode  TSGetDuration(TS ts, PetscInt *maxsteps, PetscReal *maxtime)
2714: {
2717:   if (maxsteps) {
2719:     *maxsteps = ts->max_steps;
2720:   }
2721:   if (maxtime) {
2723:     *maxtime = ts->max_time;
2724:   }
2725:   return(0);
2726: }

2730: /*@
2731:    TSSetDuration - Sets the maximum number of timesteps to use and
2732:    maximum time for iteration.

2734:    Logically Collective on TS

2736:    Input Parameters:
2737: +  ts - the TS context obtained from TSCreate()
2738: .  maxsteps - maximum number of iterations to use
2739: -  maxtime - final time to iterate to

2741:    Options Database Keys:
2742: .  -ts_max_steps <maxsteps> - Sets maxsteps
2743: .  -ts_final_time <maxtime> - Sets maxtime

2745:    Notes:
2746:    The default maximum number of iterations is 5000. Default time is 5.0

2748:    Level: intermediate

2750: .keywords: TS, timestep, set, maximum, iterations

2752: .seealso: TSSetExactFinalTime()
2753: @*/
2754: PetscErrorCode  TSSetDuration(TS ts,PetscInt maxsteps,PetscReal maxtime)
2755: {
2760:   if (maxsteps >= 0) ts->max_steps = maxsteps;
2761:   if (maxtime != PETSC_DEFAULT) ts->max_time = maxtime;
2762:   return(0);
2763: }

2767: /*@
2768:    TSSetSolution - Sets the initial solution vector
2769:    for use by the TS routines.

2771:    Logically Collective on TS and Vec

2773:    Input Parameters:
2774: +  ts - the TS context obtained from TSCreate()
2775: -  u - the solution vector

2777:    Level: beginner

2779: .keywords: TS, timestep, set, solution, initial conditions
2780: @*/
2781: PetscErrorCode  TSSetSolution(TS ts,Vec u)
2782: {
2784:   DM             dm;

2789:   PetscObjectReference((PetscObject)u);
2790:   VecDestroy(&ts->vec_sol);
2791:   ts->vec_sol = u;

2793:   TSGetDM(ts,&dm);
2794:   DMShellSetGlobalVector(dm,u);
2795:   return(0);
2796: }

2800: /*@
2801:    TSAdjointSetSteps - Sets the number of steps the adjoint solver should take backward in time

2803:    Logically Collective on TS

2805:    Input Parameters:
2806: +  ts - the TS context obtained from TSCreate()
2807: .  steps - number of steps to use

2809:    Level: intermediate

2811:    Notes: Normally one does not call this and TSAdjointSolve() integrates back to the original timestep. One can call this
2812:           so as to integrate back to less than the original timestep

2814: .keywords: TS, timestep, set, maximum, iterations

2816: .seealso: TSSetExactFinalTime()
2817: @*/
2818: PetscErrorCode  TSAdjointSetSteps(TS ts,PetscInt steps)
2819: {
2823:   if (steps < 0) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_ARG_OUTOFRANGE,"Cannot step back a negative number of steps");
2824:   if (steps > ts->total_steps) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_ARG_OUTOFRANGE,"Cannot step back more than the total number of forward steps");
2825:   ts->adjoint_max_steps = steps;
2826:   return(0);
2827: }

2831: /*@
2832:    TSSetCostGradients - Sets the initial value of the gradients of the cost function w.r.t. initial conditions and w.r.t. the problem parameters 
2833:       for use by the TSAdjoint routines.

2835:    Logically Collective on TS and Vec

2837:    Input Parameters:
2838: +  ts - the TS context obtained from TSCreate()
2839: .  lambda - gradients with respect to the initial condition variables, the dimension and parallel layout of these vectors is the same as the ODE solution vector
2840: -  mu - gradients with respect to the parameters, the number of entries in these vectors is the same as the number of parameters

2842:    Level: beginner

2844:    Notes: the entries in these vectors must be correctly initialized with the values lamda_i = df/dy|finaltime  mu_i = df/dp|finaltime

2846: .keywords: TS, timestep, set, sensitivity, initial conditions
2847: @*/
2848: PetscErrorCode  TSSetCostGradients(TS ts,PetscInt numcost,Vec *lambda,Vec *mu)
2849: {
2853:   ts->vecs_sensi  = lambda;
2854:   ts->vecs_sensip = mu;
2855:   if (ts->numcost && ts->numcost!=numcost) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_USER,"The number of cost functions (2rd parameter of TSSetCostIntegrand()) is inconsistent with the one set by TSSetCostIntegrand");
2856:   ts->numcost  = numcost;
2857:   return(0);
2858: }

2862: /*@C
2863:   TSAdjointSetRHSJacobian - Sets the function that computes the Jacobian of G w.r.t. the parameters p where y_t = G(y,p,t), as well as the location to store the matrix.

2865:   Logically Collective on TS

2867:   Input Parameters:
2868: + ts   - The TS context obtained from TSCreate()
2869: - func - The function

2871:   Calling sequence of func:
2872: $ func (TS ts,PetscReal t,Vec y,Mat A,void *ctx);
2873: +   t - current timestep
2874: .   y - input vector (current ODE solution)
2875: .   A - output matrix
2876: -   ctx - [optional] user-defined function context

2878:   Level: intermediate

2880:   Notes: Amat has the same number of rows and the same row parallel layout as u, Amat has the same number of columns and parallel layout as p

2882: .keywords: TS, sensitivity
2883: .seealso:
2884: @*/
2885: PetscErrorCode  TSAdjointSetRHSJacobian(TS ts,Mat Amat,PetscErrorCode (*func)(TS,PetscReal,Vec,Mat,void*),void *ctx)
2886: {


2893:   ts->rhsjacobianp    = func;
2894:   ts->rhsjacobianpctx = ctx;
2895:   if(Amat) {
2896:     PetscObjectReference((PetscObject)Amat);
2897:     MatDestroy(&ts->Jacp);
2898:     ts->Jacp = Amat;
2899:   }
2900:   return(0);
2901: }

2905: /*@C
2906:   TSAdjointComputeRHSJacobian - Runs the user-defined Jacobian function.

2908:   Collective on TS

2910:   Input Parameters:
2911: . ts   - The TS context obtained from TSCreate()

2913:   Level: developer

2915: .keywords: TS, sensitivity
2916: .seealso: TSAdjointSetRHSJacobian()
2917: @*/
2918: PetscErrorCode  TSAdjointComputeRHSJacobian(TS ts,PetscReal t,Vec X,Mat Amat)
2919: {


2927:   PetscStackPush("TS user JacobianP function for sensitivity analysis");
2928:   (*ts->rhsjacobianp)(ts,t,X,Amat,ts->rhsjacobianpctx);
2929:   PetscStackPop;
2930:   return(0);
2931: }

2935: /*@C
2936:     TSSetCostIntegrand - Sets the routine for evaluating the integral term in one or more cost functions

2938:     Logically Collective on TS

2940:     Input Parameters:
2941: +   ts - the TS context obtained from TSCreate()
2942: .   numcost - number of gradients to be computed, this is the number of cost functions
2943: .   rf - routine for evaluating the integrand function
2944: .   drdyf - function that computes the gradients of the r's with respect to y,NULL if not a function y
2945: .   drdpf - function that computes the gradients of the r's with respect to p, NULL if not a function of p
2946: .   fwd ï flag indicating whether to evaluate cost integral in the forward run or the adjoint run
2947: -   ctx - [optional] user-defined context for private data for the function evaluation routine (may be NULL)

2949:     Calling sequence of rf:
2950: $     rf(TS ts,PetscReal t,Vec y,Vec f[],void *ctx);

2952: +   t - current timestep
2953: .   y - input vector
2954: .   f - function result; one vector entry for each cost function
2955: -   ctx - [optional] user-defined function context

2957:    Calling sequence of drdyf:
2958: $    PetscErroCode drdyf(TS ts,PetscReal t,Vec y,Vec *drdy,void *ctx);

2960:    Calling sequence of drdpf:
2961: $    PetscErroCode drdpf(TS ts,PetscReal t,Vec y,Vec *drdp,void *ctx);

2963:     Level: intermediate

2965:     Notes: For optimization there is generally a single cost function, numcost = 1. For sensitivities there may be multiple cost functions

2967: .keywords: TS, sensitivity analysis, timestep, set, quadrature, function

2969: .seealso: TSAdjointSetRHSJacobian(),TSGetCostGradients(), TSSetCostGradients()
2970: @*/
2971: PetscErrorCode  TSSetCostIntegrand(TS ts,PetscInt numcost,PetscErrorCode (*rf)(TS,PetscReal,Vec,Vec,void*),
2972:                                                           PetscErrorCode (*drdyf)(TS,PetscReal,Vec,Vec*,void*),
2973:                                                           PetscErrorCode (*drdpf)(TS,PetscReal,Vec,Vec*,void*),
2974:                                                           PetscBool fwd,void *ctx)
2975: {

2980:   if (ts->numcost && ts->numcost!=numcost) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_USER,"The number of cost functions (2rd parameter of TSSetCostIntegrand()) is inconsistent with the one set by TSSetCostGradients()");
2981:   if (!ts->numcost) ts->numcost=numcost;

2983:   ts->costintegralfwd  = fwd; /* Evaluate the cost integral in forward run if fwd is true */
2984:   VecCreateSeq(PETSC_COMM_SELF,numcost,&ts->vec_costintegral);
2985:   VecDuplicate(ts->vec_costintegral,&ts->vec_costintegrand);
2986:   ts->costintegrand    = rf;
2987:   ts->costintegrandctx = ctx;
2988:   ts->drdyfunction     = drdyf;
2989:   ts->drdpfunction     = drdpf;
2990:   return(0);
2991: }

2995: /*@
2996:    TSGetCostIntegral - Returns the values of the integral term in the cost functions.
2997:    It is valid to call the routine after a backward run.

2999:    Not Collective

3001:    Input Parameter:
3002: .  ts - the TS context obtained from TSCreate()

3004:    Output Parameter:
3005: .  v - the vector containing the integrals for each cost function

3007:    Level: intermediate

3009: .seealso: TSSetCostIntegrand()

3011: .keywords: TS, sensitivity analysis
3012: @*/
3013: PetscErrorCode  TSGetCostIntegral(TS ts,Vec *v)
3014: {
3018:   *v = ts->vec_costintegral;
3019:   return(0);
3020: }

3024: /*@
3025:    TSAdjointComputeCostIntegrand - Evaluates the integral function in the cost functions.

3027:    Input Parameters:
3028: +  ts - the TS context
3029: .  t - current time
3030: -  y - state vector, i.e. current solution

3032:    Output Parameter:
3033: .  q - vector of size numcost to hold the outputs

3035:    Note:
3036:    Most users should not need to explicitly call this routine, as it
3037:    is used internally within the sensitivity analysis context.

3039:    Level: developer

3041: .keywords: TS, compute

3043: .seealso: TSSetCostIntegrand()
3044: @*/
3045: PetscErrorCode TSAdjointComputeCostIntegrand(TS ts,PetscReal t,Vec y,Vec q)
3046: {


3054:   PetscLogEventBegin(TS_FunctionEval,ts,y,q,0);
3055:   if (ts->costintegrand) {
3056:     PetscStackPush("TS user integrand in the cost function");
3057:     (*ts->costintegrand)(ts,t,y,q,ts->costintegrandctx);
3058:     PetscStackPop;
3059:   } else {
3060:     VecZeroEntries(q);
3061:   }

3063:   PetscLogEventEnd(TS_FunctionEval,ts,y,q,0);
3064:   return(0);
3065: }

3069: /*@
3070:   TSAdjointComputeDRDYFunction - Runs the user-defined DRDY function.

3072:   Collective on TS

3074:   Input Parameters:
3075: . ts   - The TS context obtained from TSCreate()

3077:   Notes:
3078:   TSAdjointComputeDRDYFunction() is typically used for sensitivity implementation,
3079:   so most users would not generally call this routine themselves.

3081:   Level: developer

3083: .keywords: TS, sensitivity
3084: .seealso: TSAdjointComputeDRDYFunction()
3085: @*/
3086: PetscErrorCode  TSAdjointComputeDRDYFunction(TS ts,PetscReal t,Vec y,Vec *drdy)
3087: {


3094:   PetscStackPush("TS user DRDY function for sensitivity analysis");
3095:   (*ts->drdyfunction)(ts,t,y,drdy,ts->costintegrandctx);
3096:   PetscStackPop;
3097:   return(0);
3098: }

3102: /*@
3103:   TSAdjointComputeDRDPFunction - Runs the user-defined DRDP function.

3105:   Collective on TS

3107:   Input Parameters:
3108: . ts   - The TS context obtained from TSCreate()

3110:   Notes:
3111:   TSDRDPFunction() is typically used for sensitivity implementation,
3112:   so most users would not generally call this routine themselves.

3114:   Level: developer

3116: .keywords: TS, sensitivity
3117: .seealso: TSAdjointSetDRDPFunction()
3118: @*/
3119: PetscErrorCode  TSAdjointComputeDRDPFunction(TS ts,PetscReal t,Vec y,Vec *drdp)
3120: {


3127:   PetscStackPush("TS user DRDP function for sensitivity analysis");
3128:   (*ts->drdpfunction)(ts,t,y,drdp,ts->costintegrandctx);
3129:   PetscStackPop;
3130:   return(0);
3131: }

3135: /*@C
3136:   TSSetPreStep - Sets the general-purpose function
3137:   called once at the beginning of each time step.

3139:   Logically Collective on TS

3141:   Input Parameters:
3142: + ts   - The TS context obtained from TSCreate()
3143: - func - The function

3145:   Calling sequence of func:
3146: . func (TS ts);

3148:   Level: intermediate

3150:   Note:
3151:   If a step is rejected, TSStep() will call this routine again before each attempt.
3152:   The last completed time step number can be queried using TSGetTimeStepNumber(), the
3153:   size of the step being attempted can be obtained using TSGetTimeStep().

3155: .keywords: TS, timestep
3156: .seealso: TSSetPreStage(), TSSetPostStage(), TSSetPostStep(), TSStep()
3157: @*/
3158: PetscErrorCode  TSSetPreStep(TS ts, PetscErrorCode (*func)(TS))
3159: {
3162:   ts->prestep = func;
3163:   return(0);
3164: }

3168: /*@
3169:   TSPreStep - Runs the user-defined pre-step function.

3171:   Collective on TS

3173:   Input Parameters:
3174: . ts   - The TS context obtained from TSCreate()

3176:   Notes:
3177:   TSPreStep() is typically used within time stepping implementations,
3178:   so most users would not generally call this routine themselves.

3180:   Level: developer

3182: .keywords: TS, timestep
3183: .seealso: TSSetPreStep(), TSPreStage(), TSPostStage(), TSPostStep()
3184: @*/
3185: PetscErrorCode  TSPreStep(TS ts)
3186: {

3191:   if (ts->prestep) {
3192:     PetscStackCallStandard((*ts->prestep),(ts));
3193:   }
3194:   return(0);
3195: }

3199: /*@C
3200:   TSSetPreStage - Sets the general-purpose function
3201:   called once at the beginning of each stage.

3203:   Logically Collective on TS

3205:   Input Parameters:
3206: + ts   - The TS context obtained from TSCreate()
3207: - func - The function

3209:   Calling sequence of func:
3210: . PetscErrorCode func(TS ts, PetscReal stagetime);

3212:   Level: intermediate

3214:   Note:
3215:   There may be several stages per time step. If the solve for a given stage fails, the step may be rejected and retried.
3216:   The time step number being computed can be queried using TSGetTimeStepNumber() and the total size of the step being
3217:   attempted can be obtained using TSGetTimeStep(). The time at the start of the step is available via TSGetTime().

3219: .keywords: TS, timestep
3220: .seealso: TSSetPostStage(), TSSetPreStep(), TSSetPostStep(), TSGetApplicationContext()
3221: @*/
3222: PetscErrorCode  TSSetPreStage(TS ts, PetscErrorCode (*func)(TS,PetscReal))
3223: {
3226:   ts->prestage = func;
3227:   return(0);
3228: }

3232: /*@C
3233:   TSSetPostStage - Sets the general-purpose function
3234:   called once at the end of each stage.

3236:   Logically Collective on TS

3238:   Input Parameters:
3239: + ts   - The TS context obtained from TSCreate()
3240: - func - The function

3242:   Calling sequence of func:
3243: . PetscErrorCode func(TS ts, PetscReal stagetime, PetscInt stageindex, Vec* Y);

3245:   Level: intermediate

3247:   Note:
3248:   There may be several stages per time step. If the solve for a given stage fails, the step may be rejected and retried.
3249:   The time step number being computed can be queried using TSGetTimeStepNumber() and the total size of the step being
3250:   attempted can be obtained using TSGetTimeStep(). The time at the start of the step is available via TSGetTime().

3252: .keywords: TS, timestep
3253: .seealso: TSSetPreStage(), TSSetPreStep(), TSSetPostStep(), TSGetApplicationContext()
3254: @*/
3255: PetscErrorCode  TSSetPostStage(TS ts, PetscErrorCode (*func)(TS,PetscReal,PetscInt,Vec*))
3256: {
3259:   ts->poststage = func;
3260:   return(0);
3261: }

3265: /*@
3266:   TSPreStage - Runs the user-defined pre-stage function set using TSSetPreStage()

3268:   Collective on TS

3270:   Input Parameters:
3271: . ts          - The TS context obtained from TSCreate()
3272:   stagetime   - The absolute time of the current stage

3274:   Notes:
3275:   TSPreStage() is typically used within time stepping implementations,
3276:   most users would not generally call this routine themselves.

3278:   Level: developer

3280: .keywords: TS, timestep
3281: .seealso: TSPostStage(), TSSetPreStep(), TSPreStep(), TSPostStep()
3282: @*/
3283: PetscErrorCode  TSPreStage(TS ts, PetscReal stagetime)
3284: {

3289:   if (ts->prestage) {
3290:     PetscStackCallStandard((*ts->prestage),(ts,stagetime));
3291:   }
3292:   return(0);
3293: }

3297: /*@
3298:   TSPostStage - Runs the user-defined post-stage function set using TSSetPostStage()

3300:   Collective on TS

3302:   Input Parameters:
3303: . ts          - The TS context obtained from TSCreate()
3304:   stagetime   - The absolute time of the current stage
3305:   stageindex  - Stage number
3306:   Y           - Array of vectors (of size = total number
3307:                 of stages) with the stage solutions

3309:   Notes:
3310:   TSPostStage() is typically used within time stepping implementations,
3311:   most users would not generally call this routine themselves.

3313:   Level: developer

3315: .keywords: TS, timestep
3316: .seealso: TSPreStage(), TSSetPreStep(), TSPreStep(), TSPostStep()
3317: @*/
3318: PetscErrorCode  TSPostStage(TS ts, PetscReal stagetime, PetscInt stageindex, Vec *Y)
3319: {

3324:   if (ts->poststage) {
3325:     PetscStackCallStandard((*ts->poststage),(ts,stagetime,stageindex,Y));
3326:   }
3327:   return(0);
3328: }

3332: /*@C
3333:   TSSetPostStep - Sets the general-purpose function
3334:   called once at the end of each time step.

3336:   Logically Collective on TS

3338:   Input Parameters:
3339: + ts   - The TS context obtained from TSCreate()
3340: - func - The function

3342:   Calling sequence of func:
3343: $ func (TS ts);

3345:   Level: intermediate

3347: .keywords: TS, timestep
3348: .seealso: TSSetPreStep(), TSSetPreStage(), TSGetTimeStep(), TSGetTimeStepNumber(), TSGetTime()
3349: @*/
3350: PetscErrorCode  TSSetPostStep(TS ts, PetscErrorCode (*func)(TS))
3351: {
3354:   ts->poststep = func;
3355:   return(0);
3356: }

3360: /*@
3361:   TSPostStep - Runs the user-defined post-step function.

3363:   Collective on TS

3365:   Input Parameters:
3366: . ts   - The TS context obtained from TSCreate()

3368:   Notes:
3369:   TSPostStep() is typically used within time stepping implementations,
3370:   so most users would not generally call this routine themselves.

3372:   Level: developer

3374: .keywords: TS, timestep
3375: @*/
3376: PetscErrorCode  TSPostStep(TS ts)
3377: {

3382:   if (ts->poststep) {
3383:     PetscStackCallStandard((*ts->poststep),(ts));
3384:   }
3385:   return(0);
3386: }

3388: /* ------------ Routines to set performance monitoring options ----------- */

3392: /*@C
3393:    TSMonitorSet - Sets an ADDITIONAL function that is to be used at every
3394:    timestep to display the iteration's  progress.

3396:    Logically Collective on TS

3398:    Input Parameters:
3399: +  ts - the TS context obtained from TSCreate()
3400: .  monitor - monitoring routine
3401: .  mctx - [optional] user-defined context for private data for the
3402:              monitor routine (use NULL if no context is desired)
3403: -  monitordestroy - [optional] routine that frees monitor context
3404:           (may be NULL)

3406:    Calling sequence of monitor:
3407: $    int monitor(TS ts,PetscInt steps,PetscReal time,Vec u,void *mctx)

3409: +    ts - the TS context
3410: .    steps - iteration number (after the final time step the monitor routine may be called with a step of -1, this indicates the solution has been interpolated to this time)
3411: .    time - current time
3412: .    u - current iterate
3413: -    mctx - [optional] monitoring context

3415:    Notes:
3416:    This routine adds an additional monitor to the list of monitors that
3417:    already has been loaded.

3419:    Fortran notes: Only a single monitor function can be set for each TS object

3421:    Level: intermediate

3423: .keywords: TS, timestep, set, monitor

3425: .seealso: TSMonitorDefault(), TSMonitorCancel()
3426: @*/
3427: PetscErrorCode  TSMonitorSet(TS ts,PetscErrorCode (*monitor)(TS,PetscInt,PetscReal,Vec,void*),void *mctx,PetscErrorCode (*mdestroy)(void**))
3428: {
3430:   PetscInt       i;
3431:   PetscBool      identical;
3432: 
3435:   for (i=0; i<ts->numbermonitors;i++) {
3436:     PetscMonitorCompare((PetscErrorCode (*)(void))monitor,mctx,mdestroy,(PetscErrorCode (*)(void))ts->monitor[i],ts->monitorcontext[i],ts->monitordestroy[i],&identical);
3437:     if (identical) return(0);
3438:   }
3439:   if (ts->numbermonitors >= MAXTSMONITORS) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Too many monitors set");
3440:   ts->monitor[ts->numbermonitors]          = monitor;
3441:   ts->monitordestroy[ts->numbermonitors]   = mdestroy;
3442:   ts->monitorcontext[ts->numbermonitors++] = (void*)mctx;
3443:   return(0);
3444: }

3448: /*@C
3449:    TSMonitorCancel - Clears all the monitors that have been set on a time-step object.

3451:    Logically Collective on TS

3453:    Input Parameters:
3454: .  ts - the TS context obtained from TSCreate()

3456:    Notes:
3457:    There is no way to remove a single, specific monitor.

3459:    Level: intermediate

3461: .keywords: TS, timestep, set, monitor

3463: .seealso: TSMonitorDefault(), TSMonitorSet()
3464: @*/
3465: PetscErrorCode  TSMonitorCancel(TS ts)
3466: {
3468:   PetscInt       i;

3472:   for (i=0; i<ts->numbermonitors; i++) {
3473:     if (ts->monitordestroy[i]) {
3474:       (*ts->monitordestroy[i])(&ts->monitorcontext[i]);
3475:     }
3476:   }
3477:   ts->numbermonitors = 0;
3478:   return(0);
3479: }

3483: /*@C
3484:    TSMonitorDefault - The Default monitor, prints the timestep and time for each step

3486:    Level: intermediate

3488: .keywords: TS, set, monitor

3490: .seealso:  TSMonitorSet()
3491: @*/
3492: PetscErrorCode TSMonitorDefault(TS ts,PetscInt step,PetscReal ptime,Vec v,PetscViewerAndFormat *vf)
3493: {
3495:   PetscViewer    viewer =  vf->viewer;
3496:   PetscBool      iascii,ibinary;

3500:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERASCII,&iascii);
3501:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERBINARY,&ibinary);
3502:   PetscViewerPushFormat(viewer,vf->format);
3503:   if (iascii) {
3504:     PetscViewerASCIIAddTab(viewer,((PetscObject)ts)->tablevel);
3505:     if (step == -1){ /* this indicates it is an interpolated solution */
3506:       PetscViewerASCIIPrintf(viewer,"Interpolated solution at time %g between steps %D and %D\n",(double)ptime,ts->steps-1,ts->steps);
3507:     } else {
3508:       PetscViewerASCIIPrintf(viewer,"%D TS dt %g time %g%s",step,(double)ts->time_step,(double)ptime,ts->steprollback ? " (r)\n" : "\n");
3509:     }
3510:     PetscViewerASCIISubtractTab(viewer,((PetscObject)ts)->tablevel);
3511:   } else if (ibinary) {
3512:     PetscMPIInt rank;
3513:     MPI_Comm_rank(PetscObjectComm((PetscObject)viewer),&rank);
3514:     if (!rank) {
3515:       PetscRealView(1,&ptime,viewer);
3516:     } else {
3517:       PetscRealView(0,&ptime,viewer);
3518:     }
3519:   }
3520:   PetscViewerPopFormat(viewer);
3521:   return(0);
3522: }

3526: /*@C
3527:    TSAdjointMonitorSet - Sets an ADDITIONAL function that is to be used at every
3528:    timestep to display the iteration's  progress.

3530:    Logically Collective on TS

3532:    Input Parameters:
3533: +  ts - the TS context obtained from TSCreate()
3534: .  adjointmonitor - monitoring routine
3535: .  adjointmctx - [optional] user-defined context for private data for the
3536:              monitor routine (use NULL if no context is desired)
3537: -  adjointmonitordestroy - [optional] routine that frees monitor context
3538:           (may be NULL)

3540:    Calling sequence of monitor:
3541: $    int adjointmonitor(TS ts,PetscInt steps,PetscReal time,Vec u,PetscInt numcost,Vec *lambda, Vec *mu,void *adjointmctx)

3543: +    ts - the TS context
3544: .    steps - iteration number (after the final time step the monitor routine is called with a step of -1, this is at the final time which may have
3545:                                been interpolated to)
3546: .    time - current time
3547: .    u - current iterate
3548: .    numcost - number of cost functionos
3549: .    lambda - sensitivities to initial conditions
3550: .    mu - sensitivities to parameters
3551: -    adjointmctx - [optional] adjoint monitoring context

3553:    Notes:
3554:    This routine adds an additional monitor to the list of monitors that
3555:    already has been loaded.

3557:    Fortran notes: Only a single monitor function can be set for each TS object

3559:    Level: intermediate

3561: .keywords: TS, timestep, set, adjoint, monitor

3563: .seealso: TSAdjointMonitorCancel()
3564: @*/
3565: PetscErrorCode  TSAdjointMonitorSet(TS ts,PetscErrorCode (*adjointmonitor)(TS,PetscInt,PetscReal,Vec,PetscInt,Vec*,Vec*,void*),void *adjointmctx,PetscErrorCode (*adjointmdestroy)(void**))
3566: {
3568:   PetscInt       i;
3569:   PetscBool      identical;

3573:   for (i=0; i<ts->numbermonitors;i++) {
3574:     PetscMonitorCompare((PetscErrorCode (*)(void))adjointmonitor,adjointmctx,adjointmdestroy,(PetscErrorCode (*)(void))ts->adjointmonitor[i],ts->adjointmonitorcontext[i],ts->adjointmonitordestroy[i],&identical);
3575:     if (identical) return(0);
3576:   }
3577:   if (ts->numberadjointmonitors >= MAXTSMONITORS) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Too many adjoint monitors set");
3578:   ts->adjointmonitor[ts->numberadjointmonitors]          = adjointmonitor;
3579:   ts->adjointmonitordestroy[ts->numberadjointmonitors]   = adjointmdestroy;
3580:   ts->adjointmonitorcontext[ts->numberadjointmonitors++] = (void*)adjointmctx;
3581:   return(0);
3582: }

3586: /*@C
3587:    TSAdjointMonitorCancel - Clears all the adjoint monitors that have been set on a time-step object.

3589:    Logically Collective on TS

3591:    Input Parameters:
3592: .  ts - the TS context obtained from TSCreate()

3594:    Notes:
3595:    There is no way to remove a single, specific monitor.

3597:    Level: intermediate

3599: .keywords: TS, timestep, set, adjoint, monitor

3601: .seealso: TSAdjointMonitorSet()
3602: @*/
3603: PetscErrorCode  TSAdjointMonitorCancel(TS ts)
3604: {
3606:   PetscInt       i;

3610:   for (i=0; i<ts->numberadjointmonitors; i++) {
3611:     if (ts->adjointmonitordestroy[i]) {
3612:       (*ts->adjointmonitordestroy[i])(&ts->adjointmonitorcontext[i]);
3613:     }
3614:   }
3615:   ts->numberadjointmonitors = 0;
3616:   return(0);
3617: }

3621: /*@C
3622:    TSAdjointMonitorDefault - the default monitor of adjoint computations

3624:    Level: intermediate

3626: .keywords: TS, set, monitor

3628: .seealso: TSAdjointMonitorSet()
3629: @*/
3630: PetscErrorCode TSAdjointMonitorDefault(TS ts,PetscInt step,PetscReal ptime,Vec v,PetscInt numcost,Vec *lambda,Vec *mu,PetscViewerAndFormat *vf)
3631: {
3633:   PetscViewer    viewer = vf->viewer;

3637:   PetscViewerPushFormat(viewer,vf->format);
3638:   PetscViewerASCIIAddTab(viewer,((PetscObject)ts)->tablevel);
3639:   PetscViewerASCIIPrintf(viewer,"%D TS dt %g time %g%s",step,(double)ts->time_step,(double)ptime,ts->steprollback ? " (r)\n" : "\n");
3640:   PetscViewerASCIISubtractTab(viewer,((PetscObject)ts)->tablevel);
3641:   PetscViewerPopFormat(viewer);
3642:   return(0);
3643: }

3647: /*@
3648:    TSInterpolate - Interpolate the solution computed during the previous step to an arbitrary location in the interval

3650:    Collective on TS

3652:    Input Argument:
3653: +  ts - time stepping context
3654: -  t - time to interpolate to

3656:    Output Argument:
3657: .  U - state at given time

3659:    Level: intermediate

3661:    Developer Notes:
3662:    TSInterpolate() and the storing of previous steps/stages should be generalized to support delay differential equations and continuous adjoints.

3664: .keywords: TS, set

3666: .seealso: TSSetExactFinalTime(), TSSolve()
3667: @*/
3668: PetscErrorCode TSInterpolate(TS ts,PetscReal t,Vec U)
3669: {

3675:   if (t < ts->ptime_prev || t > ts->ptime) SETERRQ3(PetscObjectComm((PetscObject)ts),PETSC_ERR_ARG_OUTOFRANGE,"Requested time %g not in last time steps [%g,%g]",t,(double)ts->ptime_prev,(double)ts->ptime);
3676:   if (!ts->ops->interpolate) SETERRQ1(PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"%s does not provide interpolation",((PetscObject)ts)->type_name);
3677:   (*ts->ops->interpolate)(ts,t,U);
3678:   return(0);
3679: }

3683: /*@
3684:    TSStep - Steps one time step

3686:    Collective on TS

3688:    Input Parameter:
3689: .  ts - the TS context obtained from TSCreate()

3691:    Level: developer

3693:    Notes:
3694:    The public interface for the ODE/DAE solvers is TSSolve(), you should almost for sure be using that routine and not this routine.

3696:    The hook set using TSSetPreStep() is called before each attempt to take the step. In general, the time step size may
3697:    be changed due to adaptive error controller or solve failures. Note that steps may contain multiple stages.

3699:    This may over-step the final time provided in TSSetDuration() depending on the time-step used. TSSolve() interpolates to exactly the
3700:    time provided in TSSetDuration(). One can use TSInterpolate() to determine an interpolated solution within the final timestep.

3702: .keywords: TS, timestep, solve

3704: .seealso: TSCreate(), TSSetUp(), TSDestroy(), TSSolve(), TSSetPreStep(), TSSetPreStage(), TSSetPostStage(), TSInterpolate()
3705: @*/
3706: PetscErrorCode  TSStep(TS ts)
3707: {
3708:   PetscErrorCode   ierr;
3709:   static PetscBool cite = PETSC_FALSE;
3710:   PetscReal        ptime;

3714:   PetscCitationsRegister("@techreport{tspaper,\n"
3715:                                 "  title       = {{PETSc/TS}: A Modern Scalable {DAE/ODE} Solver Library},\n"
3716:                                 "  author      = {Shrirang Abhyankar and Jed Brown and Emil Constantinescu and Debojyoti Ghosh and Barry F. Smith},\n"
3717:                                 "  type        = {Preprint},\n"
3718:                                 "  number      = {ANL/MCS-P5061-0114},\n"
3719:                                 "  institution = {Argonne National Laboratory},\n"
3720:                                 "  year        = {2014}\n}\n",&cite);

3722:   TSSetUp(ts);
3723:   TSTrajectorySetUp(ts->trajectory,ts);

3725:   if (ts->exact_final_time == TS_EXACTFINALTIME_UNSPECIFIED) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_ARG_WRONGSTATE,"You must call TSSetExactFinalTime() or use -ts_exact_final_time <stepover,interpolate,matchstep> before calling TSStep()");
3726:   if (ts->exact_final_time == TS_EXACTFINALTIME_MATCHSTEP && !ts->adapt) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"Since TS is not adaptive you cannot use TS_EXACTFINALTIME_MATCHSTEP, suggest TS_EXACTFINALTIME_INTERPOLATE");

3728:   if (!ts->steps) ts->ptime_prev = ts->ptime;
3729:   ts->reason = TS_CONVERGED_ITERATING;
3730:   ptime = ts->ptime; ts->ptime_prev_rollback = ts->ptime_prev;
3731:   if (!ts->ops->step) SETERRQ1(PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"TSStep not implemented for type '%s'",((PetscObject)ts)->type_name);
3732:   PetscLogEventBegin(TS_Step,ts,0,0,0);
3733:   (*ts->ops->step)(ts);
3734:   PetscLogEventEnd(TS_Step,ts,0,0,0);
3735:   ts->ptime_prev = ptime;
3736:   ts->steps++; ts->total_steps++;
3737:   ts->steprollback = PETSC_FALSE;
3738:   ts->steprestart  = PETSC_FALSE;

3740:   if (ts->reason < 0) {
3741:     if (ts->errorifstepfailed) {
3742:       if (ts->reason == TS_DIVERGED_NONLINEAR_SOLVE) SETERRQ1(PetscObjectComm((PetscObject)ts),PETSC_ERR_NOT_CONVERGED,"TSStep has failed due to %s, increase -ts_max_snes_failures or make negative to attempt recovery",TSConvergedReasons[ts->reason]);
3743:       else SETERRQ1(PetscObjectComm((PetscObject)ts),PETSC_ERR_NOT_CONVERGED,"TSStep has failed due to %s",TSConvergedReasons[ts->reason]);
3744:     }
3745:   } else if (!ts->reason) {
3746:     if (ts->steps >= ts->max_steps)     ts->reason = TS_CONVERGED_ITS;
3747:     else if (ts->ptime >= ts->max_time) ts->reason = TS_CONVERGED_TIME;
3748:   }
3749:   return(0);
3750: }

3754: /*@
3755:    TSAdjointStep - Steps one time step backward in the adjoint run

3757:    Collective on TS

3759:    Input Parameter:
3760: .  ts - the TS context obtained from TSCreate()

3762:    Level: intermediate

3764: .keywords: TS, adjoint, step

3766: .seealso: TSAdjointSetUp(), TSAdjointSolve()
3767: @*/
3768: PetscErrorCode  TSAdjointStep(TS ts)
3769: {
3770:   DM               dm;
3771:   PetscErrorCode   ierr;

3775:   TSGetDM(ts,&dm);
3776:   TSAdjointSetUp(ts);

3778:   VecViewFromOptions(ts->vec_sol,(PetscObject)ts,"-ts_view_solution");

3780:   ts->reason = TS_CONVERGED_ITERATING;
3781:   ts->ptime_prev = ts->ptime;
3782:   if (!ts->ops->adjointstep) SETERRQ1(PetscObjectComm((PetscObject)ts),PETSC_ERR_NOT_CONVERGED,"TSStep has failed because the adjoint of  %s has not been implemented, try other time stepping methods for adjoint sensitivity analysis",((PetscObject)ts)->type_name);
3783:   PetscLogEventBegin(TS_AdjointStep,ts,0,0,0);
3784:   (*ts->ops->adjointstep)(ts);
3785:   PetscLogEventEnd(TS_AdjointStep,ts,0,0,0);
3786:   ts->steps++; ts->total_steps--;

3788:   if (ts->reason < 0) {
3789:     if (ts->errorifstepfailed) {
3790:       if (ts->reason == TS_DIVERGED_NONLINEAR_SOLVE) SETERRQ1(PetscObjectComm((PetscObject)ts),PETSC_ERR_NOT_CONVERGED,"TSStep has failed due to %s, increase -ts_max_snes_failures or make negative to attempt recovery",TSConvergedReasons[ts->reason]);
3791:       else if (ts->reason == TS_DIVERGED_STEP_REJECTED) SETERRQ1(PetscObjectComm((PetscObject)ts),PETSC_ERR_NOT_CONVERGED,"TSStep has failed due to %s, increase -ts_max_reject or make negative to attempt recovery",TSConvergedReasons[ts->reason]);
3792:       else SETERRQ1(PetscObjectComm((PetscObject)ts),PETSC_ERR_NOT_CONVERGED,"TSStep has failed due to %s",TSConvergedReasons[ts->reason]);
3793:     }
3794:   } else if (!ts->reason) {
3795:     if (ts->steps >= ts->adjoint_max_steps) ts->reason = TS_CONVERGED_ITS;
3796:   }
3797:   return(0);
3798: }

3802: /*@
3803:    TSEvaluateWLTE - Evaluate the weighted local truncation error norm
3804:    at the end of a time step with a given order of accuracy.

3806:    Collective on TS

3808:    Input Arguments:
3809: +  ts - time stepping context
3810: .  wnormtype - norm type, either NORM_2 or NORM_INFINITY
3811: -  order - optional, desired order for the error evaluation or PETSC_DECIDE

3813:    Output Arguments:
3814: +  order - optional, the actual order of the error evaluation
3815: -  wlte - the weighted local truncation error norm

3817:    Level: advanced

3819:    Notes:
3820:    If the timestepper cannot evaluate the error in a particular step
3821:    (eg. in the first step or restart steps after event handling),
3822:    this routine returns wlte=-1.0 .

3824: .seealso: TSStep(), TSAdapt, TSErrorWeightedNorm()
3825: @*/
3826: PetscErrorCode TSEvaluateWLTE(TS ts,NormType wnormtype,PetscInt *order,PetscReal *wlte)
3827: {

3837:   if (wnormtype != NORM_2 && wnormtype != NORM_INFINITY) SETERRQ1(PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"No support for norm type %s",NormTypes[wnormtype]);
3838:   if (!ts->ops->evaluatewlte) SETERRQ1(PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"TSEvaluateWLTE not implemented for type '%s'",((PetscObject)ts)->type_name);
3839:   (*ts->ops->evaluatewlte)(ts,wnormtype,order,wlte);
3840:   return(0);
3841: }

3845: /*@
3846:    TSEvaluateStep - Evaluate the solution at the end of a time step with a given order of accuracy.

3848:    Collective on TS

3850:    Input Arguments:
3851: +  ts - time stepping context
3852: .  order - desired order of accuracy
3853: -  done - whether the step was evaluated at this order (pass NULL to generate an error if not available)

3855:    Output Arguments:
3856: .  U - state at the end of the current step

3858:    Level: advanced

3860:    Notes:
3861:    This function cannot be called until all stages have been evaluated.
3862:    It is normally called by adaptive controllers before a step has been accepted and may also be called by the user after TSStep() has returned.

3864: .seealso: TSStep(), TSAdapt
3865: @*/
3866: PetscErrorCode TSEvaluateStep(TS ts,PetscInt order,Vec U,PetscBool *done)
3867: {

3874:   if (!ts->ops->evaluatestep) SETERRQ1(PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"TSEvaluateStep not implemented for type '%s'",((PetscObject)ts)->type_name);
3875:   (*ts->ops->evaluatestep)(ts,order,U,done);
3876:   return(0);
3877: }

3881: /*@
3882:  TSForwardCostIntegral - Evaluate the cost integral in the forward run.
3883:  
3884:  Collective on TS
3885:  
3886:  Input Arguments:
3887:  .  ts - time stepping context
3888:  
3889:  Level: advanced
3890:  
3891:  Notes:
3892:  This function cannot be called until TSStep() has been completed.
3893:  
3894:  .seealso: TSSolve(), TSAdjointCostIntegral()
3895:  @*/
3896: PetscErrorCode TSForwardCostIntegral(TS ts)
3897: {
3900:     if (!ts->ops->forwardintegral) SETERRQ1(PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"%s does not provide integral evaluation in the forward run",((PetscObject)ts)->type_name);
3901:     (*ts->ops->forwardintegral)(ts);
3902:     return(0);
3903: }

3907: /*@
3908:    TSSolve - Steps the requested number of timesteps.

3910:    Collective on TS

3912:    Input Parameter:
3913: +  ts - the TS context obtained from TSCreate()
3914: -  u - the solution vector  (can be null if TSSetSolution() was used and TSSetExactFinalTime(ts,TS_EXACTFINALTIME_MATCHSTEP) was not used,
3915:                              otherwise must contain the initial conditions and will contain the solution at the final requested time

3917:    Level: beginner

3919:    Notes:
3920:    The final time returned by this function may be different from the time of the internally
3921:    held state accessible by TSGetSolution() and TSGetTime() because the method may have
3922:    stepped over the final time.

3924: .keywords: TS, timestep, solve

3926: .seealso: TSCreate(), TSSetSolution(), TSStep(), TSGetTime(), TSGetSolveTime()
3927: @*/
3928: PetscErrorCode TSSolve(TS ts,Vec u)
3929: {
3930:   Vec               solution;
3931:   PetscErrorCode    ierr;


3937:   if (ts->exact_final_time == TS_EXACTFINALTIME_INTERPOLATE) {   /* Need ts->vec_sol to be distinct so it is not overwritten when we interpolate at the end */
3939:     if (!ts->vec_sol || u == ts->vec_sol) {
3940:       VecDuplicate(u,&solution);
3941:       TSSetSolution(ts,solution);
3942:       VecDestroy(&solution); /* grant ownership */
3943:     }
3944:     VecCopy(u,ts->vec_sol);
3945:   } else if (u) {
3946:     TSSetSolution(ts,u);
3947:   }
3948:   TSSetUp(ts);
3949:   TSTrajectorySetUp(ts->trajectory,ts);

3951:   if (ts->exact_final_time == TS_EXACTFINALTIME_UNSPECIFIED) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_ARG_WRONGSTATE,"You must call TSSetExactFinalTime() or use -ts_exact_final_time <stepover,interpolate,matchstep> before calling TSSolve()");
3952:   if (ts->exact_final_time == TS_EXACTFINALTIME_MATCHSTEP && !ts->adapt) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"Since TS is not adaptive you cannot use TS_EXACTFINALTIME_MATCHSTEP, suggest TS_EXACTFINALTIME_INTERPOLATE");

3954:   /* reset time step and iteration counters */
3955:   ts->steps             = 0;
3956:   ts->ksp_its           = 0;
3957:   ts->snes_its          = 0;
3958:   ts->num_snes_failures = 0;
3959:   ts->reject            = 0;
3960:   ts->reason            = TS_CONVERGED_ITERATING;

3962:   TSViewFromOptions(ts,NULL,"-ts_view_pre");

3964:   if (ts->ops->solve) { /* This private interface is transitional and should be removed when all implementations are updated. */
3965:     (*ts->ops->solve)(ts);
3966:     if (u) {VecCopy(ts->vec_sol,u);}
3967:     ts->solvetime = ts->ptime;
3968:     solution = ts->vec_sol;
3969:   } else { /* Step the requested number of timesteps. */
3970:     if (ts->steps >= ts->max_steps)     ts->reason = TS_CONVERGED_ITS;
3971:     else if (ts->ptime >= ts->max_time) ts->reason = TS_CONVERGED_TIME;
3972:     TSTrajectorySet(ts->trajectory,ts,ts->steps,ts->ptime,ts->vec_sol);
3973:     TSEventInitialize(ts->event,ts,ts->ptime,ts->vec_sol);
3974:     ts->steprollback = PETSC_FALSE;
3975:     ts->steprestart  = PETSC_TRUE;

3977:     while (!ts->reason) {
3978:       TSMonitor(ts,ts->steps,ts->ptime,ts->vec_sol);
3979:       if (!ts->steprollback) {
3980:         TSPreStep(ts);
3981:       }
3982:       TSStep(ts);
3983:       if (ts->vec_costintegral && ts->costintegralfwd) { /* Must evaluate the cost integral before event is handled. The cost integral value can also be rolled back. */
3984:         TSForwardCostIntegral(ts);
3985:       }
3986:       TSEventHandler(ts); /* The right-hand side may be changed due to event. Be careful with Any computation using the RHS information after this point. */
3987:       if (!ts->steprollback) {
3988:         TSTrajectorySet(ts->trajectory,ts,ts->steps,ts->ptime,ts->vec_sol);
3989:         TSPostStep(ts);
3990:       }
3991:     }
3992:     TSMonitor(ts,ts->steps,ts->ptime,ts->vec_sol);

3994:     if (ts->exact_final_time == TS_EXACTFINALTIME_INTERPOLATE && ts->ptime > ts->max_time) {
3995:       TSInterpolate(ts,ts->max_time,u);
3996:       ts->solvetime = ts->max_time;
3997:       solution = u;
3998:       TSMonitor(ts,-1,ts->solvetime,solution);
3999:     } else {
4000:       if (u) {VecCopy(ts->vec_sol,u);}
4001:       ts->solvetime = ts->ptime;
4002:       solution = ts->vec_sol;
4003:     }
4004:   }

4006:   TSViewFromOptions(ts,NULL,"-ts_view");
4007:   VecViewFromOptions(solution,NULL,"-ts_view_solution");
4008:   PetscObjectSAWsBlock((PetscObject)ts);
4009:   if (ts->adjoint_solve) {
4010:     TSAdjointSolve(ts);
4011:   }
4012:   return(0);
4013: }

4017: /*@
4018:  TSAdjointCostIntegral - Evaluate the cost integral in the adjoint run.
4019:  
4020:  Collective on TS
4021:  
4022:  Input Arguments:
4023:  .  ts - time stepping context
4024:  
4025:  Level: advanced
4026:  
4027:  Notes:
4028:  This function cannot be called until TSAdjointStep() has been completed.
4029:  
4030:  .seealso: TSAdjointSolve(), TSAdjointStep
4031:  @*/
4032: PetscErrorCode TSAdjointCostIntegral(TS ts)
4033: {
4036:     if (!ts->ops->adjointintegral) SETERRQ1(PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"%s does not provide integral evaluation in the adjoint run",((PetscObject)ts)->type_name);
4037:     (*ts->ops->adjointintegral)(ts);
4038:     return(0);
4039: }

4043: /*@
4044:    TSAdjointSolve - Solves the discrete ajoint problem for an ODE/DAE

4046:    Collective on TS

4048:    Input Parameter:
4049: .  ts - the TS context obtained from TSCreate()

4051:    Options Database:
4052: . -ts_adjoint_view_solution <viewerinfo> - views the first gradient with respect to the initial conditions

4054:    Level: intermediate

4056:    Notes:
4057:    This must be called after a call to TSSolve() that solves the forward problem

4059:    By default this will integrate back to the initial time, one can use TSAdjointSetSteps() to step back to a later time

4061: .keywords: TS, timestep, solve

4063: .seealso: TSCreate(), TSSetCostGradients(), TSSetSolution(), TSAdjointStep()
4064: @*/
4065: PetscErrorCode TSAdjointSolve(TS ts)
4066: {
4067:   PetscErrorCode    ierr;

4071:   TSAdjointSetUp(ts);

4073:   /* reset time step and iteration counters */
4074:   ts->steps             = 0;
4075:   ts->ksp_its           = 0;
4076:   ts->snes_its          = 0;
4077:   ts->num_snes_failures = 0;
4078:   ts->reject            = 0;
4079:   ts->reason            = TS_CONVERGED_ITERATING;

4081:   if (!ts->adjoint_max_steps) ts->adjoint_max_steps = ts->total_steps;

4083:   if (ts->steps >= ts->adjoint_max_steps)     ts->reason = TS_CONVERGED_ITS;
4084:   while (!ts->reason) {
4085:     TSTrajectoryGet(ts->trajectory,ts,ts->total_steps,&ts->ptime);
4086:     TSAdjointMonitor(ts,ts->total_steps,ts->ptime,ts->vec_sol,ts->numcost,ts->vecs_sensi,ts->vecs_sensip);
4087:     TSAdjointEventHandler(ts);
4088:     TSAdjointStep(ts);
4089:     if (ts->vec_costintegral && !ts->costintegralfwd) {
4090:       TSAdjointCostIntegral(ts);
4091:     }
4092:   }
4093:   TSTrajectoryGet(ts->trajectory,ts,ts->total_steps,&ts->ptime);
4094:   TSAdjointMonitor(ts,ts->total_steps,ts->ptime,ts->vec_sol,ts->numcost,ts->vecs_sensi,ts->vecs_sensip);
4095:   ts->solvetime = ts->ptime;
4096:   TSTrajectoryViewFromOptions(ts->trajectory,NULL,"-ts_trajectory_view");
4097:   VecViewFromOptions(ts->vecs_sensi[0],(PetscObject) ts, "-ts_adjoint_view_solution");
4098:   return(0);
4099: }

4103: /*@C
4104:    TSMonitor - Runs all user-provided monitor routines set using TSMonitorSet()

4106:    Collective on TS

4108:    Input Parameters:
4109: +  ts - time stepping context obtained from TSCreate()
4110: .  step - step number that has just completed
4111: .  ptime - model time of the state
4112: -  u - state at the current model time

4114:    Notes:
4115:    TSMonitor() is typically used automatically within the time stepping implementations.
4116:    Users would almost never call this routine directly.

4118:    A step of -1 indicates that the monitor is being called on a solution obtained by interpolating from computed solutions

4120:    Level: developer

4122: .keywords: TS, timestep
4123: @*/
4124: PetscErrorCode TSMonitor(TS ts,PetscInt step,PetscReal ptime,Vec u)
4125: {
4126:   DM             dm;
4127:   PetscInt       i,n = ts->numbermonitors;


4134:   TSGetDM(ts,&dm);
4135:   DMSetOutputSequenceNumber(dm,step,ptime);

4137:   VecLockPush(u);
4138:   for (i=0; i<n; i++) {
4139:     (*ts->monitor[i])(ts,step,ptime,u,ts->monitorcontext[i]);
4140:   }
4141:   VecLockPop(u);
4142:   return(0);
4143: }

4147: /*@C
4148:    TSAdjointMonitor - Runs all user-provided adjoint monitor routines set using TSAdjointMonitorSet()

4150:    Collective on TS

4152:    Input Parameters:
4153: +  ts - time stepping context obtained from TSCreate()
4154: .  step - step number that has just completed
4155: .  ptime - model time of the state
4156: .  u - state at the current model time
4157: .  numcost - number of cost functions (dimension of lambda  or mu)
4158: .  lambda - vectors containing the gradients of the cost functions with respect to the ODE/DAE solution variables
4159: -  mu - vectors containing the gradients of the cost functions with respect to the problem parameters

4161:    Notes:
4162:    TSAdjointMonitor() is typically used automatically within the time stepping implementations.
4163:    Users would almost never call this routine directly.

4165:    Level: developer

4167: .keywords: TS, timestep
4168: @*/
4169: PetscErrorCode TSAdjointMonitor(TS ts,PetscInt step,PetscReal ptime,Vec u,PetscInt numcost,Vec *lambda, Vec *mu)
4170: {
4172:   PetscInt       i,n = ts->numberadjointmonitors;

4177:   VecLockPush(u);
4178:   for (i=0; i<n; i++) {
4179:     (*ts->adjointmonitor[i])(ts,step,ptime,u,numcost,lambda,mu,ts->adjointmonitorcontext[i]);
4180:   }
4181:   VecLockPop(u);
4182:   return(0);
4183: }

4185: /* ------------------------------------------------------------------------*/
4188: /*@C
4189:    TSMonitorLGCtxCreate - Creates a TSMonitorLGCtx context for use with
4190:    TS to monitor the solution process graphically in various ways

4192:    Collective on TS

4194:    Input Parameters:
4195: +  host - the X display to open, or null for the local machine
4196: .  label - the title to put in the title bar
4197: .  x, y - the screen coordinates of the upper left coordinate of the window
4198: .  m, n - the screen width and height in pixels
4199: -  howoften - if positive then determines the frequency of the plotting, if -1 then only at the final time

4201:    Output Parameter:
4202: .  ctx - the context

4204:    Options Database Key:
4205: +  -ts_monitor_lg_timestep - automatically sets line graph monitor
4206: .  -ts_monitor_lg_solution - monitor the solution (or certain values of the solution by calling TSMonitorLGSetDisplayVariables() or TSMonitorLGCtxSetDisplayVariables())
4207: .  -ts_monitor_lg_error -  monitor the error
4208: .  -ts_monitor_lg_ksp_iterations - monitor the number of KSP iterations needed for each timestep
4209: .  -ts_monitor_lg_snes_iterations - monitor the number of SNES iterations needed for each timestep
4210: -  -lg_use_markers <true,false> - mark the data points (at each time step) on the plot; default is true

4212:    Notes:
4213:    Use TSMonitorLGCtxDestroy() to destroy.

4215:    One can provide a function that transforms the solution before plotting it with TSMonitorLGCtxSetTransform() or TSMonitorLGSetTransform()

4217:    Many of the functions that control the monitoring have two forms: TSMonitorLGSet/GetXXXX() and TSMonitorLGCtxSet/GetXXXX() the first take a TS object as the
4218:    first argument (if that TS object does not have a TSMonitorLGCtx associated with it the function call is ignored) and the second takes a TSMonitorLGCtx object
4219:    as the first argument.

4221:    One can control the names displayed for each solution or error variable with TSMonitorLGCtxSetVariableNames() or TSMonitorLGSetVariableNames()


4224:    Level: intermediate

4226: .keywords: TS, monitor, line graph, residual

4228: .seealso: TSMonitorLGTimeStep(), TSMonitorSet(), TSMonitorLGSolution(), TSMonitorLGError(), TSMonitorDefault(), VecView(), 
4229:            TSMonitorLGCtxCreate(), TSMonitorLGCtxSetVariableNames(), TSMonitorLGCtxGetVariableNames(),
4230:            TSMonitorLGSetVariableNames(), TSMonitorLGGetVariableNames(), TSMonitorLGSetDisplayVariables(), TSMonitorLGCtxSetDisplayVariables(),
4231:            TSMonitorLGCtxSetTransform(), TSMonitorLGSetTransform(), TSMonitorLGError(), TSMonitorLGSNESIterations(), TSMonitorLGKSPIterations(),
4232:            TSMonitorEnvelopeCtxCreate(), TSMonitorEnvelopeGetBounds(), TSMonitorEnvelopeCtxDestroy(), TSMonitorEnvelop()

4234: @*/
4235: PetscErrorCode  TSMonitorLGCtxCreate(MPI_Comm comm,const char host[],const char label[],int x,int y,int m,int n,PetscInt howoften,TSMonitorLGCtx *ctx)
4236: {
4237:   PetscDraw      draw;

4241:   PetscNew(ctx);
4242:   PetscDrawCreate(comm,host,label,x,y,m,n,&draw);
4243:   PetscDrawSetFromOptions(draw);
4244:   PetscDrawLGCreate(draw,1,&(*ctx)->lg);
4245:   PetscDrawLGSetFromOptions((*ctx)->lg);
4246:   PetscDrawDestroy(&draw);
4247:   (*ctx)->howoften = howoften;
4248:   return(0);
4249: }

4253: PetscErrorCode TSMonitorLGTimeStep(TS ts,PetscInt step,PetscReal ptime,Vec v,void *monctx)
4254: {
4255:   TSMonitorLGCtx ctx = (TSMonitorLGCtx) monctx;
4256:   PetscReal      x   = ptime,y;

4260:   if (step < 0) return(0); /* -1 indicates an interpolated solution */
4261:   if (!step) {
4262:     PetscDrawAxis axis;
4263:     PetscDrawLGGetAxis(ctx->lg,&axis);
4264:     PetscDrawAxisSetLabels(axis,"Timestep as function of time","Time","Time Step");
4265:     PetscDrawLGReset(ctx->lg);
4266:   }
4267:   TSGetTimeStep(ts,&y);
4268:   PetscDrawLGAddPoint(ctx->lg,&x,&y);
4269:   if (((ctx->howoften > 0) && (!(step % ctx->howoften))) || ((ctx->howoften == -1) && ts->reason)) {
4270:     PetscDrawLGDraw(ctx->lg);
4271:     PetscDrawLGSave(ctx->lg);
4272:   }
4273:   return(0);
4274: }

4278: /*@C
4279:    TSMonitorLGCtxDestroy - Destroys a line graph context that was created
4280:    with TSMonitorLGCtxCreate().

4282:    Collective on TSMonitorLGCtx

4284:    Input Parameter:
4285: .  ctx - the monitor context

4287:    Level: intermediate

4289: .keywords: TS, monitor, line graph, destroy

4291: .seealso: TSMonitorLGCtxCreate(),  TSMonitorSet(), TSMonitorLGTimeStep();
4292: @*/
4293: PetscErrorCode  TSMonitorLGCtxDestroy(TSMonitorLGCtx *ctx)
4294: {

4298:   if ((*ctx)->transformdestroy) {
4299:     ((*ctx)->transformdestroy)((*ctx)->transformctx);
4300:   }
4301:   PetscDrawLGDestroy(&(*ctx)->lg);
4302:   PetscStrArrayDestroy(&(*ctx)->names);
4303:   PetscStrArrayDestroy(&(*ctx)->displaynames);
4304:   PetscFree((*ctx)->displayvariables);
4305:   PetscFree((*ctx)->displayvalues);
4306:   PetscFree(*ctx);
4307:   return(0);
4308: }

4312: /*@
4313:    TSGetTime - Gets the time of the most recently completed step.

4315:    Not Collective

4317:    Input Parameter:
4318: .  ts - the TS context obtained from TSCreate()

4320:    Output Parameter:
4321: .  t  - the current time. This time may not corresponds to the final time set with TSSetDuration(), use TSGetSolveTime().

4323:    Level: beginner

4325:    Note:
4326:    When called during time step evaluation (e.g. during residual evaluation or via hooks set using TSSetPreStep(),
4327:    TSSetPreStage(), TSSetPostStage(), or TSSetPostStep()), the time is the time at the start of the step being evaluated.

4329: .seealso: TSSetInitialTimeStep(), TSGetTimeStep(), TSGetSolveTime()

4331: .keywords: TS, get, time
4332: @*/
4333: PetscErrorCode  TSGetTime(TS ts,PetscReal *t)
4334: {
4338:   *t = ts->ptime;
4339:   return(0);
4340: }

4344: /*@
4345:    TSGetPrevTime - Gets the starting time of the previously completed step.

4347:    Not Collective

4349:    Input Parameter:
4350: .  ts - the TS context obtained from TSCreate()

4352:    Output Parameter:
4353: .  t  - the previous time

4355:    Level: beginner

4357: .seealso: TSSetInitialTimeStep(), TSGetTimeStep()

4359: .keywords: TS, get, time
4360: @*/
4361: PetscErrorCode  TSGetPrevTime(TS ts,PetscReal *t)
4362: {
4366:   *t = ts->ptime_prev;
4367:   return(0);
4368: }

4372: /*@
4373:    TSSetTime - Allows one to reset the time.

4375:    Logically Collective on TS

4377:    Input Parameters:
4378: +  ts - the TS context obtained from TSCreate()
4379: -  time - the time

4381:    Level: intermediate

4383: .seealso: TSGetTime(), TSSetDuration()

4385: .keywords: TS, set, time
4386: @*/
4387: PetscErrorCode  TSSetTime(TS ts, PetscReal t)
4388: {
4392:   ts->ptime = t;
4393:   return(0);
4394: }

4398: /*@C
4399:    TSSetOptionsPrefix - Sets the prefix used for searching for all
4400:    TS options in the database.

4402:    Logically Collective on TS

4404:    Input Parameter:
4405: +  ts     - The TS context
4406: -  prefix - The prefix to prepend to all option names

4408:    Notes:
4409:    A hyphen (-) must NOT be given at the beginning of the prefix name.
4410:    The first character of all runtime options is AUTOMATICALLY the
4411:    hyphen.

4413:    Level: advanced

4415: .keywords: TS, set, options, prefix, database

4417: .seealso: TSSetFromOptions()

4419: @*/
4420: PetscErrorCode  TSSetOptionsPrefix(TS ts,const char prefix[])
4421: {
4423:   SNES           snes;

4427:   PetscObjectSetOptionsPrefix((PetscObject)ts,prefix);
4428:   TSGetSNES(ts,&snes);
4429:   SNESSetOptionsPrefix(snes,prefix);
4430:   return(0);
4431: }


4436: /*@C
4437:    TSAppendOptionsPrefix - Appends to the prefix used for searching for all
4438:    TS options in the database.

4440:    Logically Collective on TS

4442:    Input Parameter:
4443: +  ts     - The TS context
4444: -  prefix - The prefix to prepend to all option names

4446:    Notes:
4447:    A hyphen (-) must NOT be given at the beginning of the prefix name.
4448:    The first character of all runtime options is AUTOMATICALLY the
4449:    hyphen.

4451:    Level: advanced

4453: .keywords: TS, append, options, prefix, database

4455: .seealso: TSGetOptionsPrefix()

4457: @*/
4458: PetscErrorCode  TSAppendOptionsPrefix(TS ts,const char prefix[])
4459: {
4461:   SNES           snes;

4465:   PetscObjectAppendOptionsPrefix((PetscObject)ts,prefix);
4466:   TSGetSNES(ts,&snes);
4467:   SNESAppendOptionsPrefix(snes,prefix);
4468:   return(0);
4469: }

4473: /*@C
4474:    TSGetOptionsPrefix - Sets the prefix used for searching for all
4475:    TS options in the database.

4477:    Not Collective

4479:    Input Parameter:
4480: .  ts - The TS context

4482:    Output Parameter:
4483: .  prefix - A pointer to the prefix string used

4485:    Notes: On the fortran side, the user should pass in a string 'prifix' of
4486:    sufficient length to hold the prefix.

4488:    Level: intermediate

4490: .keywords: TS, get, options, prefix, database

4492: .seealso: TSAppendOptionsPrefix()
4493: @*/
4494: PetscErrorCode  TSGetOptionsPrefix(TS ts,const char *prefix[])
4495: {

4501:   PetscObjectGetOptionsPrefix((PetscObject)ts,prefix);
4502:   return(0);
4503: }

4507: /*@C
4508:    TSGetRHSJacobian - Returns the Jacobian J at the present timestep.

4510:    Not Collective, but parallel objects are returned if TS is parallel

4512:    Input Parameter:
4513: .  ts  - The TS context obtained from TSCreate()

4515:    Output Parameters:
4516: +  Amat - The (approximate) Jacobian J of G, where U_t = G(U,t)  (or NULL)
4517: .  Pmat - The matrix from which the preconditioner is constructed, usually the same as Amat  (or NULL)
4518: .  func - Function to compute the Jacobian of the RHS  (or NULL)
4519: -  ctx - User-defined context for Jacobian evaluation routine  (or NULL)

4521:    Notes: You can pass in NULL for any return argument you do not need.

4523:    Level: intermediate

4525: .seealso: TSGetTimeStep(), TSGetMatrices(), TSGetTime(), TSGetTimeStepNumber()

4527: .keywords: TS, timestep, get, matrix, Jacobian
4528: @*/
4529: PetscErrorCode  TSGetRHSJacobian(TS ts,Mat *Amat,Mat *Pmat,TSRHSJacobian *func,void **ctx)
4530: {
4532:   SNES           snes;
4533:   DM             dm;

4536:   TSGetSNES(ts,&snes);
4537:   SNESGetJacobian(snes,Amat,Pmat,NULL,NULL);
4538:   TSGetDM(ts,&dm);
4539:   DMTSGetRHSJacobian(dm,func,ctx);
4540:   return(0);
4541: }

4545: /*@C
4546:    TSGetIJacobian - Returns the implicit Jacobian at the present timestep.

4548:    Not Collective, but parallel objects are returned if TS is parallel

4550:    Input Parameter:
4551: .  ts  - The TS context obtained from TSCreate()

4553:    Output Parameters:
4554: +  Amat  - The (approximate) Jacobian of F(t,U,U_t)
4555: .  Pmat - The matrix from which the preconditioner is constructed, often the same as Amat
4556: .  f   - The function to compute the matrices
4557: - ctx - User-defined context for Jacobian evaluation routine

4559:    Notes: You can pass in NULL for any return argument you do not need.

4561:    Level: advanced

4563: .seealso: TSGetTimeStep(), TSGetRHSJacobian(), TSGetMatrices(), TSGetTime(), TSGetTimeStepNumber()

4565: .keywords: TS, timestep, get, matrix, Jacobian
4566: @*/
4567: PetscErrorCode  TSGetIJacobian(TS ts,Mat *Amat,Mat *Pmat,TSIJacobian *f,void **ctx)
4568: {
4570:   SNES           snes;
4571:   DM             dm;

4574:   TSGetSNES(ts,&snes);
4575:   SNESSetUpMatrices(snes);
4576:   SNESGetJacobian(snes,Amat,Pmat,NULL,NULL);
4577:   TSGetDM(ts,&dm);
4578:   DMTSGetIJacobian(dm,f,ctx);
4579:   return(0);
4580: }


4585: /*@C
4586:    TSMonitorDrawSolution - Monitors progress of the TS solvers by calling
4587:    VecView() for the solution at each timestep

4589:    Collective on TS

4591:    Input Parameters:
4592: +  ts - the TS context
4593: .  step - current time-step
4594: .  ptime - current time
4595: -  dummy - either a viewer or NULL

4597:    Options Database:
4598: .   -ts_monitor_draw_solution_initial - show initial solution as well as current solution

4600:    Notes: the initial solution and current solution are not display with a common axis scaling so generally the option -ts_monitor_draw_solution_initial
4601:        will look bad

4603:    Level: intermediate

4605: .keywords: TS,  vector, monitor, view

4607: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView()
4608: @*/
4609: PetscErrorCode  TSMonitorDrawSolution(TS ts,PetscInt step,PetscReal ptime,Vec u,void *dummy)
4610: {
4611:   PetscErrorCode   ierr;
4612:   TSMonitorDrawCtx ictx = (TSMonitorDrawCtx)dummy;
4613:   PetscDraw        draw;

4616:   if (!step && ictx->showinitial) {
4617:     if (!ictx->initialsolution) {
4618:       VecDuplicate(u,&ictx->initialsolution);
4619:     }
4620:     VecCopy(u,ictx->initialsolution);
4621:   }
4622:   if (!(((ictx->howoften > 0) && (!(step % ictx->howoften))) || ((ictx->howoften == -1) && ts->reason))) return(0);

4624:   if (ictx->showinitial) {
4625:     PetscReal pause;
4626:     PetscViewerDrawGetPause(ictx->viewer,&pause);
4627:     PetscViewerDrawSetPause(ictx->viewer,0.0);
4628:     VecView(ictx->initialsolution,ictx->viewer);
4629:     PetscViewerDrawSetPause(ictx->viewer,pause);
4630:     PetscViewerDrawSetHold(ictx->viewer,PETSC_TRUE);
4631:   }
4632:   VecView(u,ictx->viewer);
4633:   if (ictx->showtimestepandtime) {
4634:     PetscReal xl,yl,xr,yr,h;
4635:     char      time[32];

4637:     PetscViewerDrawGetDraw(ictx->viewer,0,&draw);
4638:     PetscSNPrintf(time,32,"Timestep %d Time %g",(int)step,(double)ptime);
4639:     PetscDrawGetCoordinates(draw,&xl,&yl,&xr,&yr);
4640:     h    = yl + .95*(yr - yl);
4641:     PetscDrawStringCentered(draw,.5*(xl+xr),h,PETSC_DRAW_BLACK,time);
4642:     PetscDrawFlush(draw);
4643:   }

4645:   if (ictx->showinitial) {
4646:     PetscViewerDrawSetHold(ictx->viewer,PETSC_FALSE);
4647:   }
4648:   return(0);
4649: }

4653: /*@C
4654:    TSAdjointMonitorDrawSensi - Monitors progress of the adjoint TS solvers by calling
4655:    VecView() for the sensitivities to initial states at each timestep

4657:    Collective on TS

4659:    Input Parameters:
4660: +  ts - the TS context
4661: .  step - current time-step
4662: .  ptime - current time
4663: .  u - current state
4664: .  numcost - number of cost functions
4665: .  lambda - sensitivities to initial conditions
4666: .  mu - sensitivities to parameters
4667: -  dummy - either a viewer or NULL

4669:    Level: intermediate

4671: .keywords: TS,  vector, adjoint, monitor, view

4673: .seealso: TSAdjointMonitorSet(), TSAdjointMonitorDefault(), VecView()
4674: @*/
4675: PetscErrorCode  TSAdjointMonitorDrawSensi(TS ts,PetscInt step,PetscReal ptime,Vec u,PetscInt numcost,Vec *lambda,Vec *mu,void *dummy)
4676: {
4677:   PetscErrorCode   ierr;
4678:   TSMonitorDrawCtx ictx = (TSMonitorDrawCtx)dummy;
4679:   PetscDraw        draw;
4680:   PetscReal        xl,yl,xr,yr,h;
4681:   char             time[32];

4684:   if (!(((ictx->howoften > 0) && (!(step % ictx->howoften))) || ((ictx->howoften == -1) && ts->reason))) return(0);

4686:   VecView(lambda[0],ictx->viewer);
4687:   PetscViewerDrawGetDraw(ictx->viewer,0,&draw);
4688:   PetscSNPrintf(time,32,"Timestep %d Time %g",(int)step,(double)ptime);
4689:   PetscDrawGetCoordinates(draw,&xl,&yl,&xr,&yr);
4690:   h    = yl + .95*(yr - yl);
4691:   PetscDrawStringCentered(draw,.5*(xl+xr),h,PETSC_DRAW_BLACK,time);
4692:   PetscDrawFlush(draw);
4693:   return(0);
4694: }

4698: /*@C
4699:    TSMonitorDrawSolutionPhase - Monitors progress of the TS solvers by plotting the solution as a phase diagram

4701:    Collective on TS

4703:    Input Parameters:
4704: +  ts - the TS context
4705: .  step - current time-step
4706: .  ptime - current time
4707: -  dummy - either a viewer or NULL

4709:    Level: intermediate

4711: .keywords: TS,  vector, monitor, view

4713: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView()
4714: @*/
4715: PetscErrorCode  TSMonitorDrawSolutionPhase(TS ts,PetscInt step,PetscReal ptime,Vec u,void *dummy)
4716: {
4717:   PetscErrorCode    ierr;
4718:   TSMonitorDrawCtx  ictx = (TSMonitorDrawCtx)dummy;
4719:   PetscDraw         draw;
4720:   PetscDrawAxis     axis;
4721:   PetscInt          n;
4722:   PetscMPIInt       size;
4723:   PetscReal         U0,U1,xl,yl,xr,yr,h;
4724:   char              time[32];
4725:   const PetscScalar *U;

4728:   MPI_Comm_size(PetscObjectComm((PetscObject)ts),&size);
4729:   if (size != 1) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"Only allowed for sequential runs");
4730:   VecGetSize(u,&n);
4731:   if (n != 2) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"Only for ODEs with two unknowns");

4733:   PetscViewerDrawGetDraw(ictx->viewer,0,&draw);
4734:   PetscViewerDrawGetDrawAxis(ictx->viewer,0,&axis);
4735:   PetscDrawAxisGetLimits(axis,&xl,&xr,&yl,&yr);
4736:   if (!step) {
4737:     PetscDrawClear(draw);
4738:     PetscDrawAxisDraw(axis);
4739:   }

4741:   VecGetArrayRead(u,&U);
4742:   U0 = PetscRealPart(U[0]);
4743:   U1 = PetscRealPart(U[1]);
4744:   VecRestoreArrayRead(u,&U);
4745:   if ((U0 < xl) || (U1 < yl) || (U0 > xr) || (U1 > yr)) return(0);

4747:   PetscDrawCollectiveBegin(draw);
4748:   PetscDrawPoint(draw,U0,U1,PETSC_DRAW_BLACK);
4749:   if (ictx->showtimestepandtime) {
4750:     PetscDrawGetCoordinates(draw,&xl,&yl,&xr,&yr);
4751:     PetscSNPrintf(time,32,"Timestep %d Time %g",(int)step,(double)ptime);
4752:     h    = yl + .95*(yr - yl);
4753:     PetscDrawStringCentered(draw,.5*(xl+xr),h,PETSC_DRAW_BLACK,time);
4754:   }
4755:   PetscDrawCollectiveEnd(draw);
4756:   PetscDrawFlush(draw);
4757:   PetscDrawSave(draw);
4758:   return(0);
4759: }


4764: /*@C
4765:    TSMonitorDrawCtxDestroy - Destroys the monitor context for TSMonitorDrawSolution()

4767:    Collective on TS

4769:    Input Parameters:
4770: .    ctx - the monitor context

4772:    Level: intermediate

4774: .keywords: TS,  vector, monitor, view

4776: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorDrawSolution(), TSMonitorDrawError()
4777: @*/
4778: PetscErrorCode  TSMonitorDrawCtxDestroy(TSMonitorDrawCtx *ictx)
4779: {

4783:   PetscViewerDestroy(&(*ictx)->viewer);
4784:   VecDestroy(&(*ictx)->initialsolution);
4785:   PetscFree(*ictx);
4786:   return(0);
4787: }

4791: /*@C
4792:    TSMonitorDrawCtxCreate - Creates the monitor context for TSMonitorDrawCtx

4794:    Collective on TS

4796:    Input Parameter:
4797: .    ts - time-step context

4799:    Output Patameter:
4800: .    ctx - the monitor context

4802:    Options Database:
4803: .   -ts_monitor_draw_solution_initial - show initial solution as well as current solution

4805:    Level: intermediate

4807: .keywords: TS,  vector, monitor, view

4809: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorDrawCtx()
4810: @*/
4811: PetscErrorCode  TSMonitorDrawCtxCreate(MPI_Comm comm,const char host[],const char label[],int x,int y,int m,int n,PetscInt howoften,TSMonitorDrawCtx *ctx)
4812: {
4813:   PetscErrorCode   ierr;

4816:   PetscNew(ctx);
4817:   PetscViewerDrawOpen(comm,host,label,x,y,m,n,&(*ctx)->viewer);
4818:   PetscViewerSetFromOptions((*ctx)->viewer);

4820:   (*ctx)->howoften    = howoften;
4821:   (*ctx)->showinitial = PETSC_FALSE;
4822:   PetscOptionsGetBool(NULL,NULL,"-ts_monitor_draw_solution_initial",&(*ctx)->showinitial,NULL);

4824:   (*ctx)->showtimestepandtime = PETSC_FALSE;
4825:   PetscOptionsGetBool(NULL,NULL,"-ts_monitor_draw_solution_show_time",&(*ctx)->showtimestepandtime,NULL);
4826:   return(0);
4827: }

4831: /*@C
4832:    TSMonitorDrawError - Monitors progress of the TS solvers by calling
4833:    VecView() for the error at each timestep

4835:    Collective on TS

4837:    Input Parameters:
4838: +  ts - the TS context
4839: .  step - current time-step
4840: .  ptime - current time
4841: -  dummy - either a viewer or NULL

4843:    Level: intermediate

4845: .keywords: TS,  vector, monitor, view

4847: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView()
4848: @*/
4849: PetscErrorCode  TSMonitorDrawError(TS ts,PetscInt step,PetscReal ptime,Vec u,void *dummy)
4850: {
4851:   PetscErrorCode   ierr;
4852:   TSMonitorDrawCtx ctx    = (TSMonitorDrawCtx)dummy;
4853:   PetscViewer      viewer = ctx->viewer;
4854:   Vec              work;

4857:   if (!(((ctx->howoften > 0) && (!(step % ctx->howoften))) || ((ctx->howoften == -1) && ts->reason))) return(0);
4858:   VecDuplicate(u,&work);
4859:   TSComputeSolutionFunction(ts,ptime,work);
4860:   VecAXPY(work,-1.0,u);
4861:   VecView(work,viewer);
4862:   VecDestroy(&work);
4863:   return(0);
4864: }

4866: #include <petsc/private/dmimpl.h>
4869: /*@
4870:    TSSetDM - Sets the DM that may be used by some preconditioners

4872:    Logically Collective on TS and DM

4874:    Input Parameters:
4875: +  ts - the preconditioner context
4876: -  dm - the dm

4878:    Level: intermediate


4881: .seealso: TSGetDM(), SNESSetDM(), SNESGetDM()
4882: @*/
4883: PetscErrorCode  TSSetDM(TS ts,DM dm)
4884: {
4886:   SNES           snes;
4887:   DMTS           tsdm;

4891:   PetscObjectReference((PetscObject)dm);
4892:   if (ts->dm) {               /* Move the DMTS context over to the new DM unless the new DM already has one */
4893:     if (ts->dm->dmts && !dm->dmts) {
4894:       DMCopyDMTS(ts->dm,dm);
4895:       DMGetDMTS(ts->dm,&tsdm);
4896:       if (tsdm->originaldm == ts->dm) { /* Grant write privileges to the replacement DM */
4897:         tsdm->originaldm = dm;
4898:       }
4899:     }
4900:     DMDestroy(&ts->dm);
4901:   }
4902:   ts->dm = dm;

4904:   TSGetSNES(ts,&snes);
4905:   SNESSetDM(snes,dm);
4906:   return(0);
4907: }

4911: /*@
4912:    TSGetDM - Gets the DM that may be used by some preconditioners

4914:    Not Collective

4916:    Input Parameter:
4917: . ts - the preconditioner context

4919:    Output Parameter:
4920: .  dm - the dm

4922:    Level: intermediate


4925: .seealso: TSSetDM(), SNESSetDM(), SNESGetDM()
4926: @*/
4927: PetscErrorCode  TSGetDM(TS ts,DM *dm)
4928: {

4933:   if (!ts->dm) {
4934:     DMShellCreate(PetscObjectComm((PetscObject)ts),&ts->dm);
4935:     if (ts->snes) {SNESSetDM(ts->snes,ts->dm);}
4936:   }
4937:   *dm = ts->dm;
4938:   return(0);
4939: }

4943: /*@
4944:    SNESTSFormFunction - Function to evaluate nonlinear residual

4946:    Logically Collective on SNES

4948:    Input Parameter:
4949: + snes - nonlinear solver
4950: . U - the current state at which to evaluate the residual
4951: - ctx - user context, must be a TS

4953:    Output Parameter:
4954: . F - the nonlinear residual

4956:    Notes:
4957:    This function is not normally called by users and is automatically registered with the SNES used by TS.
4958:    It is most frequently passed to MatFDColoringSetFunction().

4960:    Level: advanced

4962: .seealso: SNESSetFunction(), MatFDColoringSetFunction()
4963: @*/
4964: PetscErrorCode  SNESTSFormFunction(SNES snes,Vec U,Vec F,void *ctx)
4965: {
4966:   TS             ts = (TS)ctx;

4974:   (ts->ops->snesfunction)(snes,U,F,ts);
4975:   return(0);
4976: }

4980: /*@
4981:    SNESTSFormJacobian - Function to evaluate the Jacobian

4983:    Collective on SNES

4985:    Input Parameter:
4986: + snes - nonlinear solver
4987: . U - the current state at which to evaluate the residual
4988: - ctx - user context, must be a TS

4990:    Output Parameter:
4991: + A - the Jacobian
4992: . B - the preconditioning matrix (may be the same as A)
4993: - flag - indicates any structure change in the matrix

4995:    Notes:
4996:    This function is not normally called by users and is automatically registered with the SNES used by TS.

4998:    Level: developer

5000: .seealso: SNESSetJacobian()
5001: @*/
5002: PetscErrorCode  SNESTSFormJacobian(SNES snes,Vec U,Mat A,Mat B,void *ctx)
5003: {
5004:   TS             ts = (TS)ctx;

5015:   (ts->ops->snesjacobian)(snes,U,A,B,ts);
5016:   return(0);
5017: }

5021: /*@C
5022:    TSComputeRHSFunctionLinear - Evaluate the right hand side via the user-provided Jacobian, for linear problems Udot = A U only

5024:    Collective on TS

5026:    Input Arguments:
5027: +  ts - time stepping context
5028: .  t - time at which to evaluate
5029: .  U - state at which to evaluate
5030: -  ctx - context

5032:    Output Arguments:
5033: .  F - right hand side

5035:    Level: intermediate

5037:    Notes:
5038:    This function is intended to be passed to TSSetRHSFunction() to evaluate the right hand side for linear problems.
5039:    The matrix (and optionally the evaluation context) should be passed to TSSetRHSJacobian().

5041: .seealso: TSSetRHSFunction(), TSSetRHSJacobian(), TSComputeRHSJacobianConstant()
5042: @*/
5043: PetscErrorCode TSComputeRHSFunctionLinear(TS ts,PetscReal t,Vec U,Vec F,void *ctx)
5044: {
5046:   Mat            Arhs,Brhs;

5049:   TSGetRHSMats_Private(ts,&Arhs,&Brhs);
5050:   TSComputeRHSJacobian(ts,t,U,Arhs,Brhs);
5051:   MatMult(Arhs,U,F);
5052:   return(0);
5053: }

5057: /*@C
5058:    TSComputeRHSJacobianConstant - Reuses a Jacobian that is time-independent.

5060:    Collective on TS

5062:    Input Arguments:
5063: +  ts - time stepping context
5064: .  t - time at which to evaluate
5065: .  U - state at which to evaluate
5066: -  ctx - context

5068:    Output Arguments:
5069: +  A - pointer to operator
5070: .  B - pointer to preconditioning matrix
5071: -  flg - matrix structure flag

5073:    Level: intermediate

5075:    Notes:
5076:    This function is intended to be passed to TSSetRHSJacobian() to evaluate the Jacobian for linear time-independent problems.

5078: .seealso: TSSetRHSFunction(), TSSetRHSJacobian(), TSComputeRHSFunctionLinear()
5079: @*/
5080: PetscErrorCode TSComputeRHSJacobianConstant(TS ts,PetscReal t,Vec U,Mat A,Mat B,void *ctx)
5081: {
5083:   return(0);
5084: }

5088: /*@C
5089:    TSComputeIFunctionLinear - Evaluate the left hand side via the user-provided Jacobian, for linear problems only

5091:    Collective on TS

5093:    Input Arguments:
5094: +  ts - time stepping context
5095: .  t - time at which to evaluate
5096: .  U - state at which to evaluate
5097: .  Udot - time derivative of state vector
5098: -  ctx - context

5100:    Output Arguments:
5101: .  F - left hand side

5103:    Level: intermediate

5105:    Notes:
5106:    The assumption here is that the left hand side is of the form A*Udot (and not A*Udot + B*U). For other cases, the
5107:    user is required to write their own TSComputeIFunction.
5108:    This function is intended to be passed to TSSetIFunction() to evaluate the left hand side for linear problems.
5109:    The matrix (and optionally the evaluation context) should be passed to TSSetIJacobian().

5111:    Note that using this function is NOT equivalent to using TSComputeRHSFunctionLinear() since that solves Udot = A U

5113: .seealso: TSSetIFunction(), TSSetIJacobian(), TSComputeIJacobianConstant(), TSComputeRHSFunctionLinear()
5114: @*/
5115: PetscErrorCode TSComputeIFunctionLinear(TS ts,PetscReal t,Vec U,Vec Udot,Vec F,void *ctx)
5116: {
5118:   Mat            A,B;

5121:   TSGetIJacobian(ts,&A,&B,NULL,NULL);
5122:   TSComputeIJacobian(ts,t,U,Udot,1.0,A,B,PETSC_TRUE);
5123:   MatMult(A,Udot,F);
5124:   return(0);
5125: }

5129: /*@C
5130:    TSComputeIJacobianConstant - Reuses a time-independent for a semi-implicit DAE or ODE

5132:    Collective on TS

5134:    Input Arguments:
5135: +  ts - time stepping context
5136: .  t - time at which to evaluate
5137: .  U - state at which to evaluate
5138: .  Udot - time derivative of state vector
5139: .  shift - shift to apply
5140: -  ctx - context

5142:    Output Arguments:
5143: +  A - pointer to operator
5144: .  B - pointer to preconditioning matrix
5145: -  flg - matrix structure flag

5147:    Level: advanced

5149:    Notes:
5150:    This function is intended to be passed to TSSetIJacobian() to evaluate the Jacobian for linear time-independent problems.

5152:    It is only appropriate for problems of the form

5154: $     M Udot = F(U,t)

5156:   where M is constant and F is non-stiff.  The user must pass M to TSSetIJacobian().  The current implementation only
5157:   works with IMEX time integration methods such as TSROSW and TSARKIMEX, since there is no support for de-constructing
5158:   an implicit operator of the form

5160: $    shift*M + J

5162:   where J is the Jacobian of -F(U).  Support may be added in a future version of PETSc, but for now, the user must store
5163:   a copy of M or reassemble it when requested.

5165: .seealso: TSSetIFunction(), TSSetIJacobian(), TSComputeIFunctionLinear()
5166: @*/
5167: PetscErrorCode TSComputeIJacobianConstant(TS ts,PetscReal t,Vec U,Vec Udot,PetscReal shift,Mat A,Mat B,void *ctx)
5168: {

5172:   MatScale(A, shift / ts->ijacobian.shift);
5173:   ts->ijacobian.shift = shift;
5174:   return(0);
5175: }

5179: /*@
5180:    TSGetEquationType - Gets the type of the equation that TS is solving.

5182:    Not Collective

5184:    Input Parameter:
5185: .  ts - the TS context

5187:    Output Parameter:
5188: .  equation_type - see TSEquationType

5190:    Level: beginner

5192: .keywords: TS, equation type

5194: .seealso: TSSetEquationType(), TSEquationType
5195: @*/
5196: PetscErrorCode  TSGetEquationType(TS ts,TSEquationType *equation_type)
5197: {
5201:   *equation_type = ts->equation_type;
5202:   return(0);
5203: }

5207: /*@
5208:    TSSetEquationType - Sets the type of the equation that TS is solving.

5210:    Not Collective

5212:    Input Parameter:
5213: +  ts - the TS context
5214: -  equation_type - see TSEquationType

5216:    Level: advanced

5218: .keywords: TS, equation type

5220: .seealso: TSGetEquationType(), TSEquationType
5221: @*/
5222: PetscErrorCode  TSSetEquationType(TS ts,TSEquationType equation_type)
5223: {
5226:   ts->equation_type = equation_type;
5227:   return(0);
5228: }

5232: /*@
5233:    TSGetConvergedReason - Gets the reason the TS iteration was stopped.

5235:    Not Collective

5237:    Input Parameter:
5238: .  ts - the TS context

5240:    Output Parameter:
5241: .  reason - negative value indicates diverged, positive value converged, see TSConvergedReason or the
5242:             manual pages for the individual convergence tests for complete lists

5244:    Level: beginner

5246:    Notes:
5247:    Can only be called after the call to TSSolve() is complete.

5249: .keywords: TS, nonlinear, set, convergence, test

5251: .seealso: TSSetConvergenceTest(), TSConvergedReason
5252: @*/
5253: PetscErrorCode  TSGetConvergedReason(TS ts,TSConvergedReason *reason)
5254: {
5258:   *reason = ts->reason;
5259:   return(0);
5260: }

5264: /*@
5265:    TSSetConvergedReason - Sets the reason for handling the convergence of TSSolve.

5267:    Not Collective

5269:    Input Parameter:
5270: +  ts - the TS context
5271: .  reason - negative value indicates diverged, positive value converged, see TSConvergedReason or the
5272:             manual pages for the individual convergence tests for complete lists

5274:    Level: advanced

5276:    Notes:
5277:    Can only be called during TSSolve() is active.

5279: .keywords: TS, nonlinear, set, convergence, test

5281: .seealso: TSConvergedReason
5282: @*/
5283: PetscErrorCode  TSSetConvergedReason(TS ts,TSConvergedReason reason)
5284: {
5287:   ts->reason = reason;
5288:   return(0);
5289: }

5293: /*@
5294:    TSGetSolveTime - Gets the time after a call to TSSolve()

5296:    Not Collective

5298:    Input Parameter:
5299: .  ts - the TS context

5301:    Output Parameter:
5302: .  ftime - the final time. This time corresponds to the final time set with TSSetDuration()

5304:    Level: beginner

5306:    Notes:
5307:    Can only be called after the call to TSSolve() is complete.

5309: .keywords: TS, nonlinear, set, convergence, test

5311: .seealso: TSSetConvergenceTest(), TSConvergedReason
5312: @*/
5313: PetscErrorCode  TSGetSolveTime(TS ts,PetscReal *ftime)
5314: {
5318:   *ftime = ts->solvetime;
5319:   return(0);
5320: }

5324: /*@
5325:    TSGetTotalSteps - Gets the total number of steps done since the last call to TSSetUp() or TSCreate()

5327:    Not Collective

5329:    Input Parameter:
5330: .  ts - the TS context

5332:    Output Parameter:
5333: .  steps - the number of steps

5335:    Level: beginner

5337:    Notes:
5338:    Includes the number of steps for all calls to TSSolve() since TSSetUp() was called

5340: .keywords: TS, nonlinear, set, convergence, test

5342: .seealso: TSSetConvergenceTest(), TSConvergedReason
5343: @*/
5344: PetscErrorCode  TSGetTotalSteps(TS ts,PetscInt *steps)
5345: {
5349:   *steps = ts->total_steps;
5350:   return(0);
5351: }

5355: /*@
5356:    TSGetSNESIterations - Gets the total number of nonlinear iterations
5357:    used by the time integrator.

5359:    Not Collective

5361:    Input Parameter:
5362: .  ts - TS context

5364:    Output Parameter:
5365: .  nits - number of nonlinear iterations

5367:    Notes:
5368:    This counter is reset to zero for each successive call to TSSolve().

5370:    Level: intermediate

5372: .keywords: TS, get, number, nonlinear, iterations

5374: .seealso:  TSGetKSPIterations()
5375: @*/
5376: PetscErrorCode TSGetSNESIterations(TS ts,PetscInt *nits)
5377: {
5381:   *nits = ts->snes_its;
5382:   return(0);
5383: }

5387: /*@
5388:    TSGetKSPIterations - Gets the total number of linear iterations
5389:    used by the time integrator.

5391:    Not Collective

5393:    Input Parameter:
5394: .  ts - TS context

5396:    Output Parameter:
5397: .  lits - number of linear iterations

5399:    Notes:
5400:    This counter is reset to zero for each successive call to TSSolve().

5402:    Level: intermediate

5404: .keywords: TS, get, number, linear, iterations

5406: .seealso:  TSGetSNESIterations(), SNESGetKSPIterations()
5407: @*/
5408: PetscErrorCode TSGetKSPIterations(TS ts,PetscInt *lits)
5409: {
5413:   *lits = ts->ksp_its;
5414:   return(0);
5415: }

5419: /*@
5420:    TSGetStepRejections - Gets the total number of rejected steps.

5422:    Not Collective

5424:    Input Parameter:
5425: .  ts - TS context

5427:    Output Parameter:
5428: .  rejects - number of steps rejected

5430:    Notes:
5431:    This counter is reset to zero for each successive call to TSSolve().

5433:    Level: intermediate

5435: .keywords: TS, get, number

5437: .seealso:  TSGetSNESIterations(), TSGetKSPIterations(), TSSetMaxStepRejections(), TSGetSNESFailures(), TSSetMaxSNESFailures(), TSSetErrorIfStepFails()
5438: @*/
5439: PetscErrorCode TSGetStepRejections(TS ts,PetscInt *rejects)
5440: {
5444:   *rejects = ts->reject;
5445:   return(0);
5446: }

5450: /*@
5451:    TSGetSNESFailures - Gets the total number of failed SNES solves

5453:    Not Collective

5455:    Input Parameter:
5456: .  ts - TS context

5458:    Output Parameter:
5459: .  fails - number of failed nonlinear solves

5461:    Notes:
5462:    This counter is reset to zero for each successive call to TSSolve().

5464:    Level: intermediate

5466: .keywords: TS, get, number

5468: .seealso:  TSGetSNESIterations(), TSGetKSPIterations(), TSSetMaxStepRejections(), TSGetStepRejections(), TSSetMaxSNESFailures()
5469: @*/
5470: PetscErrorCode TSGetSNESFailures(TS ts,PetscInt *fails)
5471: {
5475:   *fails = ts->num_snes_failures;
5476:   return(0);
5477: }

5481: /*@
5482:    TSSetMaxStepRejections - Sets the maximum number of step rejections before a step fails

5484:    Not Collective

5486:    Input Parameter:
5487: +  ts - TS context
5488: -  rejects - maximum number of rejected steps, pass -1 for unlimited

5490:    Notes:
5491:    The counter is reset to zero for each step

5493:    Options Database Key:
5494:  .  -ts_max_reject - Maximum number of step rejections before a step fails

5496:    Level: intermediate

5498: .keywords: TS, set, maximum, number

5500: .seealso:  TSGetSNESIterations(), TSGetKSPIterations(), TSSetMaxSNESFailures(), TSGetStepRejections(), TSGetSNESFailures(), TSSetErrorIfStepFails(), TSGetConvergedReason()
5501: @*/
5502: PetscErrorCode TSSetMaxStepRejections(TS ts,PetscInt rejects)
5503: {
5506:   ts->max_reject = rejects;
5507:   return(0);
5508: }

5512: /*@
5513:    TSSetMaxSNESFailures - Sets the maximum number of failed SNES solves

5515:    Not Collective

5517:    Input Parameter:
5518: +  ts - TS context
5519: -  fails - maximum number of failed nonlinear solves, pass -1 for unlimited

5521:    Notes:
5522:    The counter is reset to zero for each successive call to TSSolve().

5524:    Options Database Key:
5525:  .  -ts_max_snes_failures - Maximum number of nonlinear solve failures

5527:    Level: intermediate

5529: .keywords: TS, set, maximum, number

5531: .seealso:  TSGetSNESIterations(), TSGetKSPIterations(), TSSetMaxStepRejections(), TSGetStepRejections(), TSGetSNESFailures(), SNESGetConvergedReason(), TSGetConvergedReason()
5532: @*/
5533: PetscErrorCode TSSetMaxSNESFailures(TS ts,PetscInt fails)
5534: {
5537:   ts->max_snes_failures = fails;
5538:   return(0);
5539: }

5543: /*@
5544:    TSSetErrorIfStepFails - Error if no step succeeds

5546:    Not Collective

5548:    Input Parameter:
5549: +  ts - TS context
5550: -  err - PETSC_TRUE to error if no step succeeds, PETSC_FALSE to return without failure

5552:    Options Database Key:
5553:  .  -ts_error_if_step_fails - Error if no step succeeds

5555:    Level: intermediate

5557: .keywords: TS, set, error

5559: .seealso:  TSGetSNESIterations(), TSGetKSPIterations(), TSSetMaxStepRejections(), TSGetStepRejections(), TSGetSNESFailures(), TSSetErrorIfStepFails(), TSGetConvergedReason()
5560: @*/
5561: PetscErrorCode TSSetErrorIfStepFails(TS ts,PetscBool err)
5562: {
5565:   ts->errorifstepfailed = err;
5566:   return(0);
5567: }

5571: /*@C
5572:    TSMonitorSolution - Monitors progress of the TS solvers by VecView() for the solution at each timestep. Normally the viewer is a binary file or a PetscDraw object

5574:    Collective on TS

5576:    Input Parameters:
5577: +  ts - the TS context
5578: .  step - current time-step
5579: .  ptime - current time
5580: .  u - current state
5581: -  vf - viewer and its format

5583:    Level: intermediate

5585: .keywords: TS,  vector, monitor, view

5587: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView()
5588: @*/
5589: PetscErrorCode  TSMonitorSolution(TS ts,PetscInt step,PetscReal ptime,Vec u,PetscViewerAndFormat *vf)
5590: {

5594:   PetscViewerPushFormat(vf->viewer,vf->format);
5595:   VecView(u,vf->viewer);
5596:   PetscViewerPopFormat(vf->viewer);
5597:   return(0);
5598: }

5602: /*@C
5603:    TSMonitorSolutionVTK - Monitors progress of the TS solvers by VecView() for the solution at each timestep.

5605:    Collective on TS

5607:    Input Parameters:
5608: +  ts - the TS context
5609: .  step - current time-step
5610: .  ptime - current time
5611: .  u - current state
5612: -  filenametemplate - string containing a format specifier for the integer time step (e.g. %03D)

5614:    Level: intermediate

5616:    Notes:
5617:    The VTK format does not allow writing multiple time steps in the same file, therefore a different file will be written for each time step.
5618:    These are named according to the file name template.

5620:    This function is normally passed as an argument to TSMonitorSet() along with TSMonitorSolutionVTKDestroy().

5622: .keywords: TS,  vector, monitor, view

5624: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView()
5625: @*/
5626: PetscErrorCode TSMonitorSolutionVTK(TS ts,PetscInt step,PetscReal ptime,Vec u,void *filenametemplate)
5627: {
5629:   char           filename[PETSC_MAX_PATH_LEN];
5630:   PetscViewer    viewer;

5633:   if (step < 0) return(0); /* -1 indicates interpolated solution */
5634:   PetscSNPrintf(filename,sizeof(filename),(const char*)filenametemplate,step);
5635:   PetscViewerVTKOpen(PetscObjectComm((PetscObject)ts),filename,FILE_MODE_WRITE,&viewer);
5636:   VecView(u,viewer);
5637:   PetscViewerDestroy(&viewer);
5638:   return(0);
5639: }

5643: /*@C
5644:    TSMonitorSolutionVTKDestroy - Destroy context for monitoring

5646:    Collective on TS

5648:    Input Parameters:
5649: .  filenametemplate - string containing a format specifier for the integer time step (e.g. %03D)

5651:    Level: intermediate

5653:    Note:
5654:    This function is normally passed to TSMonitorSet() along with TSMonitorSolutionVTK().

5656: .keywords: TS,  vector, monitor, view

5658: .seealso: TSMonitorSet(), TSMonitorSolutionVTK()
5659: @*/
5660: PetscErrorCode TSMonitorSolutionVTKDestroy(void *filenametemplate)
5661: {

5665:   PetscFree(*(char**)filenametemplate);
5666:   return(0);
5667: }

5671: /*@
5672:    TSGetAdapt - Get the adaptive controller context for the current method

5674:    Collective on TS if controller has not been created yet

5676:    Input Arguments:
5677: .  ts - time stepping context

5679:    Output Arguments:
5680: .  adapt - adaptive controller

5682:    Level: intermediate

5684: .seealso: TSAdapt, TSAdaptSetType(), TSAdaptChoose()
5685: @*/
5686: PetscErrorCode TSGetAdapt(TS ts,TSAdapt *adapt)
5687: {

5693:   if (!ts->adapt) {
5694:     TSAdaptCreate(PetscObjectComm((PetscObject)ts),&ts->adapt);
5695:     PetscLogObjectParent((PetscObject)ts,(PetscObject)ts->adapt);
5696:     PetscObjectIncrementTabLevel((PetscObject)ts->adapt,(PetscObject)ts,1);
5697:   }
5698:   *adapt = ts->adapt;
5699:   return(0);
5700: }

5704: /*@
5705:    TSSetTolerances - Set tolerances for local truncation error when using adaptive controller

5707:    Logically Collective

5709:    Input Arguments:
5710: +  ts - time integration context
5711: .  atol - scalar absolute tolerances, PETSC_DECIDE to leave current value
5712: .  vatol - vector of absolute tolerances or NULL, used in preference to atol if present
5713: .  rtol - scalar relative tolerances, PETSC_DECIDE to leave current value
5714: -  vrtol - vector of relative tolerances or NULL, used in preference to atol if present

5716:    Options Database keys:
5717: +  -ts_rtol <rtol> - relative tolerance for local truncation error
5718: -  -ts_atol <atol> Absolute tolerance for local truncation error

5720:    Notes:
5721:    With PETSc's implicit schemes for DAE problems, the calculation of the local truncation error
5722:    (LTE) includes both the differential and the algebraic variables. If one wants the LTE to be
5723:    computed only for the differential or the algebraic part then this can be done using the vector of
5724:    tolerances vatol. For example, by setting the tolerance vector with the desired tolerance for the 
5725:    differential part and infinity for the algebraic part, the LTE calculation will include only the
5726:    differential variables.

5728:    Level: beginner

5730: .seealso: TS, TSAdapt, TSVecNormWRMS(), TSGetTolerances()
5731: @*/
5732: PetscErrorCode TSSetTolerances(TS ts,PetscReal atol,Vec vatol,PetscReal rtol,Vec vrtol)
5733: {

5737:   if (atol != PETSC_DECIDE && atol != PETSC_DEFAULT) ts->atol = atol;
5738:   if (vatol) {
5739:     PetscObjectReference((PetscObject)vatol);
5740:     VecDestroy(&ts->vatol);
5741:     ts->vatol = vatol;
5742:   }
5743:   if (rtol != PETSC_DECIDE && rtol != PETSC_DEFAULT) ts->rtol = rtol;
5744:   if (vrtol) {
5745:     PetscObjectReference((PetscObject)vrtol);
5746:     VecDestroy(&ts->vrtol);
5747:     ts->vrtol = vrtol;
5748:   }
5749:   return(0);
5750: }

5754: /*@
5755:    TSGetTolerances - Get tolerances for local truncation error when using adaptive controller

5757:    Logically Collective

5759:    Input Arguments:
5760: .  ts - time integration context

5762:    Output Arguments:
5763: +  atol - scalar absolute tolerances, NULL to ignore
5764: .  vatol - vector of absolute tolerances, NULL to ignore
5765: .  rtol - scalar relative tolerances, NULL to ignore
5766: -  vrtol - vector of relative tolerances, NULL to ignore

5768:    Level: beginner

5770: .seealso: TS, TSAdapt, TSVecNormWRMS(), TSSetTolerances()
5771: @*/
5772: PetscErrorCode TSGetTolerances(TS ts,PetscReal *atol,Vec *vatol,PetscReal *rtol,Vec *vrtol)
5773: {
5775:   if (atol)  *atol  = ts->atol;
5776:   if (vatol) *vatol = ts->vatol;
5777:   if (rtol)  *rtol  = ts->rtol;
5778:   if (vrtol) *vrtol = ts->vrtol;
5779:   return(0);
5780: }

5784: /*@
5785:    TSErrorWeightedNorm2 - compute a weighted 2-norm of the difference between two state vectors

5787:    Collective on TS

5789:    Input Arguments:
5790: +  ts - time stepping context
5791: .  U - state vector, usually ts->vec_sol
5792: -  Y - state vector to be compared to U

5794:    Output Arguments:
5795: .  norm - weighted norm, a value of 1.0 is considered small

5797:    Level: developer

5799: .seealso: TSErrorWeightedNorm(), TSErrorWeightedNormInfinity()
5800: @*/
5801: PetscErrorCode TSErrorWeightedNorm2(TS ts,Vec U,Vec Y,PetscReal *norm)
5802: {
5803:   PetscErrorCode    ierr;
5804:   PetscInt          i,n,N,rstart;
5805:   const PetscScalar *u,*y;
5806:   PetscReal         sum,gsum;
5807:   PetscReal         tol;

5817:   if (U == Y) SETERRQ(PetscObjectComm((PetscObject)U),PETSC_ERR_ARG_IDN,"U and Y cannot be the same vector");

5819:   VecGetSize(U,&N);
5820:   VecGetLocalSize(U,&n);
5821:   VecGetOwnershipRange(U,&rstart,NULL);
5822:   VecGetArrayRead(U,&u);
5823:   VecGetArrayRead(Y,&y);
5824:   sum  = 0.;
5825:   if (ts->vatol && ts->vrtol) {
5826:     const PetscScalar *atol,*rtol;
5827:     VecGetArrayRead(ts->vatol,&atol);
5828:     VecGetArrayRead(ts->vrtol,&rtol);
5829:     for (i=0; i<n; i++) {
5830:       tol = PetscRealPart(atol[i]) + PetscRealPart(rtol[i]) * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
5831:       sum += PetscSqr(PetscAbsScalar(y[i] - u[i]) / tol);
5832:     }
5833:     VecRestoreArrayRead(ts->vatol,&atol);
5834:     VecRestoreArrayRead(ts->vrtol,&rtol);
5835:   } else if (ts->vatol) {       /* vector atol, scalar rtol */
5836:     const PetscScalar *atol;
5837:     VecGetArrayRead(ts->vatol,&atol);
5838:     for (i=0; i<n; i++) {
5839:       tol = PetscRealPart(atol[i]) + ts->rtol * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
5840:       sum += PetscSqr(PetscAbsScalar(y[i] - u[i]) / tol);
5841:     }
5842:     VecRestoreArrayRead(ts->vatol,&atol);
5843:   } else if (ts->vrtol) {       /* scalar atol, vector rtol */
5844:     const PetscScalar *rtol;
5845:     VecGetArrayRead(ts->vrtol,&rtol);
5846:     for (i=0; i<n; i++) {
5847:       tol = ts->atol + PetscRealPart(rtol[i]) * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
5848:       sum += PetscSqr(PetscAbsScalar(y[i] - u[i]) / tol);
5849:     }
5850:     VecRestoreArrayRead(ts->vrtol,&rtol);
5851:   } else {                      /* scalar atol, scalar rtol */
5852:     for (i=0; i<n; i++) {
5853:       tol = ts->atol + ts->rtol * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
5854:       sum += PetscSqr(PetscAbsScalar(y[i] - u[i]) / tol);
5855:     }
5856:   }
5857:   VecRestoreArrayRead(U,&u);
5858:   VecRestoreArrayRead(Y,&y);

5860:   MPIU_Allreduce(&sum,&gsum,1,MPIU_REAL,MPIU_SUM,PetscObjectComm((PetscObject)ts));
5861:   *norm = PetscSqrtReal(gsum / N);

5863:   if (PetscIsInfOrNanScalar(*norm)) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_FP,"Infinite or not-a-number generated in norm");
5864:   return(0);
5865: }

5869: /*@
5870:    TSErrorWeightedNormInfinity - compute a weighted infinity-norm of the difference between two state vectors

5872:    Collective on TS

5874:    Input Arguments:
5875: +  ts - time stepping context
5876: .  U - state vector, usually ts->vec_sol
5877: -  Y - state vector to be compared to U

5879:    Output Arguments:
5880: .  norm - weighted norm, a value of 1.0 is considered small

5882:    Level: developer

5884: .seealso: TSErrorWeightedNorm(), TSErrorWeightedNorm2()
5885: @*/
5886: PetscErrorCode TSErrorWeightedNormInfinity(TS ts,Vec U,Vec Y,PetscReal *norm)
5887: {
5888:   PetscErrorCode    ierr;
5889:   PetscInt          i,n,N,rstart,k;
5890:   const PetscScalar *u,*y;
5891:   PetscReal         max,gmax;
5892:   PetscReal         tol;

5902:   if (U == Y) SETERRQ(PetscObjectComm((PetscObject)U),PETSC_ERR_ARG_IDN,"U and Y cannot be the same vector");

5904:   VecGetSize(U,&N);
5905:   VecGetLocalSize(U,&n);
5906:   VecGetOwnershipRange(U,&rstart,NULL);
5907:   VecGetArrayRead(U,&u);
5908:   VecGetArrayRead(Y,&y);
5909:   if (ts->vatol && ts->vrtol) {
5910:     const PetscScalar *atol,*rtol;
5911:     VecGetArrayRead(ts->vatol,&atol);
5912:     VecGetArrayRead(ts->vrtol,&rtol);
5913:     k = 0;
5914:     tol = PetscRealPart(atol[k]) + PetscRealPart(rtol[k]) * PetscMax(PetscAbsScalar(u[k]),PetscAbsScalar(y[k]));
5915:     max = PetscAbsScalar(y[k] - u[k]) / tol;
5916:     for (i=1; i<n; i++) {
5917:       tol = PetscRealPart(atol[i]) + PetscRealPart(rtol[i]) * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
5918:       max = PetscMax(max,PetscAbsScalar(y[i] - u[i]) / tol);
5919:     }
5920:     VecRestoreArrayRead(ts->vatol,&atol);
5921:     VecRestoreArrayRead(ts->vrtol,&rtol);
5922:   } else if (ts->vatol) {       /* vector atol, scalar rtol */
5923:     const PetscScalar *atol;
5924:     VecGetArrayRead(ts->vatol,&atol);
5925:     k = 0;
5926:     tol = PetscRealPart(atol[k]) + ts->rtol * PetscMax(PetscAbsScalar(u[k]),PetscAbsScalar(y[k]));
5927:     max = PetscAbsScalar(y[k] - u[k]) / tol;
5928:     for (i=1; i<n; i++) {
5929:       tol = PetscRealPart(atol[i]) + ts->rtol * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
5930:       max = PetscMax(max,PetscAbsScalar(y[i] - u[i]) / tol);
5931:     }
5932:     VecRestoreArrayRead(ts->vatol,&atol);
5933:   } else if (ts->vrtol) {       /* scalar atol, vector rtol */
5934:     const PetscScalar *rtol;
5935:     VecGetArrayRead(ts->vrtol,&rtol);
5936:     k = 0;
5937:     tol = ts->atol + PetscRealPart(rtol[k]) * PetscMax(PetscAbsScalar(u[k]),PetscAbsScalar(y[k]));
5938:     max = PetscAbsScalar(y[k] - u[k]) / tol;
5939:     for (i=1; i<n; i++) {
5940:       tol = ts->atol + PetscRealPart(rtol[i]) * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
5941:       max = PetscMax(max,PetscAbsScalar(y[i] - u[i]) / tol);
5942:     }
5943:     VecRestoreArrayRead(ts->vrtol,&rtol);
5944:   } else {                      /* scalar atol, scalar rtol */
5945:     k = 0;
5946:     tol = ts->atol + ts->rtol * PetscMax(PetscAbsScalar(u[k]),PetscAbsScalar(y[k]));
5947:     max = PetscAbsScalar(y[k] - u[k]) / tol;
5948:     for (i=1; i<n; i++) {
5949:       tol = ts->atol + ts->rtol * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
5950:       max = PetscMax(max,PetscAbsScalar(y[i] - u[i]) / tol);
5951:     }
5952:   }
5953:   VecRestoreArrayRead(U,&u);
5954:   VecRestoreArrayRead(Y,&y);

5956:   MPIU_Allreduce(&max,&gmax,1,MPIU_REAL,MPIU_MAX,PetscObjectComm((PetscObject)ts));
5957:   *norm = gmax;

5959:   if (PetscIsInfOrNanScalar(*norm)) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_FP,"Infinite or not-a-number generated in norm");
5960:   return(0);
5961: }

5965: /*@
5966:    TSErrorWeightedNorm - compute a weighted norm of the difference between two state vectors

5968:    Collective on TS

5970:    Input Arguments:
5971: +  ts - time stepping context
5972: .  U - state vector, usually ts->vec_sol
5973: .  Y - state vector to be compared to U
5974: -  wnormtype - norm type, either NORM_2 or NORM_INFINITY

5976:    Output Arguments:
5977: .  norm - weighted norm, a value of 1.0 is considered small


5980:    Options Database Keys:
5981: .  -ts_adapt_wnormtype <wnormtype> - 2, INFINITY

5983:    Level: developer

5985: .seealso: TSErrorWeightedNormInfinity(), TSErrorWeightedNorm2()
5986: @*/
5987: PetscErrorCode TSErrorWeightedNorm(TS ts,Vec U,Vec Y,NormType wnormtype,PetscReal *norm)
5988: {

5992:   if (wnormtype == NORM_2) {
5993:     TSErrorWeightedNorm2(ts,U,Y,norm);
5994:   } else if(wnormtype == NORM_INFINITY) {
5995:     TSErrorWeightedNormInfinity(ts,U,Y,norm);
5996:   } else SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"No support for norm type %s",NormTypes[wnormtype]);
5997:   return(0);
5998: }

6002: /*@
6003:    TSSetCFLTimeLocal - Set the local CFL constraint relative to forward Euler

6005:    Logically Collective on TS

6007:    Input Arguments:
6008: +  ts - time stepping context
6009: -  cfltime - maximum stable time step if using forward Euler (value can be different on each process)

6011:    Note:
6012:    After calling this function, the global CFL time can be obtained by calling TSGetCFLTime()

6014:    Level: intermediate

6016: .seealso: TSGetCFLTime(), TSADAPTCFL
6017: @*/
6018: PetscErrorCode TSSetCFLTimeLocal(TS ts,PetscReal cfltime)
6019: {
6022:   ts->cfltime_local = cfltime;
6023:   ts->cfltime       = -1.;
6024:   return(0);
6025: }

6029: /*@
6030:    TSGetCFLTime - Get the maximum stable time step according to CFL criteria applied to forward Euler

6032:    Collective on TS

6034:    Input Arguments:
6035: .  ts - time stepping context

6037:    Output Arguments:
6038: .  cfltime - maximum stable time step for forward Euler

6040:    Level: advanced

6042: .seealso: TSSetCFLTimeLocal()
6043: @*/
6044: PetscErrorCode TSGetCFLTime(TS ts,PetscReal *cfltime)
6045: {

6049:   if (ts->cfltime < 0) {
6050:     MPIU_Allreduce(&ts->cfltime_local,&ts->cfltime,1,MPIU_REAL,MPIU_MIN,PetscObjectComm((PetscObject)ts));
6051:   }
6052:   *cfltime = ts->cfltime;
6053:   return(0);
6054: }

6058: /*@
6059:    TSVISetVariableBounds - Sets the lower and upper bounds for the solution vector. xl <= x <= xu

6061:    Input Parameters:
6062: .  ts   - the TS context.
6063: .  xl   - lower bound.
6064: .  xu   - upper bound.

6066:    Notes:
6067:    If this routine is not called then the lower and upper bounds are set to
6068:    PETSC_NINFINITY and PETSC_INFINITY respectively during SNESSetUp().

6070:    Level: advanced

6072: @*/
6073: PetscErrorCode TSVISetVariableBounds(TS ts, Vec xl, Vec xu)
6074: {
6076:   SNES           snes;

6079:   TSGetSNES(ts,&snes);
6080:   SNESVISetVariableBounds(snes,xl,xu);
6081:   return(0);
6082: }

6084: #if defined(PETSC_HAVE_MATLAB_ENGINE)
6085: #include <mex.h>

6087: typedef struct {char *funcname; mxArray *ctx;} TSMatlabContext;

6091: /*
6092:    TSComputeFunction_Matlab - Calls the function that has been set with
6093:                          TSSetFunctionMatlab().

6095:    Collective on TS

6097:    Input Parameters:
6098: +  snes - the TS context
6099: -  u - input vector

6101:    Output Parameter:
6102: .  y - function vector, as set by TSSetFunction()

6104:    Notes:
6105:    TSComputeFunction() is typically used within nonlinear solvers
6106:    implementations, so most users would not generally call this routine
6107:    themselves.

6109:    Level: developer

6111: .keywords: TS, nonlinear, compute, function

6113: .seealso: TSSetFunction(), TSGetFunction()
6114: */
6115: PetscErrorCode  TSComputeFunction_Matlab(TS snes,PetscReal time,Vec u,Vec udot,Vec y, void *ctx)
6116: {
6117:   PetscErrorCode  ierr;
6118:   TSMatlabContext *sctx = (TSMatlabContext*)ctx;
6119:   int             nlhs  = 1,nrhs = 7;
6120:   mxArray         *plhs[1],*prhs[7];
6121:   long long int   lx = 0,lxdot = 0,ly = 0,ls = 0;


6131:   PetscMemcpy(&ls,&snes,sizeof(snes));
6132:   PetscMemcpy(&lx,&u,sizeof(u));
6133:   PetscMemcpy(&lxdot,&udot,sizeof(udot));
6134:   PetscMemcpy(&ly,&y,sizeof(u));

6136:   prhs[0] =  mxCreateDoubleScalar((double)ls);
6137:   prhs[1] =  mxCreateDoubleScalar(time);
6138:   prhs[2] =  mxCreateDoubleScalar((double)lx);
6139:   prhs[3] =  mxCreateDoubleScalar((double)lxdot);
6140:   prhs[4] =  mxCreateDoubleScalar((double)ly);
6141:   prhs[5] =  mxCreateString(sctx->funcname);
6142:   prhs[6] =  sctx->ctx;
6143:    mexCallMATLAB(nlhs,plhs,nrhs,prhs,"PetscTSComputeFunctionInternal");
6144:    mxGetScalar(plhs[0]);
6145:   mxDestroyArray(prhs[0]);
6146:   mxDestroyArray(prhs[1]);
6147:   mxDestroyArray(prhs[2]);
6148:   mxDestroyArray(prhs[3]);
6149:   mxDestroyArray(prhs[4]);
6150:   mxDestroyArray(prhs[5]);
6151:   mxDestroyArray(plhs[0]);
6152:   return(0);
6153: }


6158: /*
6159:    TSSetFunctionMatlab - Sets the function evaluation routine and function
6160:    vector for use by the TS routines in solving ODEs
6161:    equations from MATLAB. Here the function is a string containing the name of a MATLAB function

6163:    Logically Collective on TS

6165:    Input Parameters:
6166: +  ts - the TS context
6167: -  func - function evaluation routine

6169:    Calling sequence of func:
6170: $    func (TS ts,PetscReal time,Vec u,Vec udot,Vec f,void *ctx);

6172:    Level: beginner

6174: .keywords: TS, nonlinear, set, function

6176: .seealso: TSGetFunction(), TSComputeFunction(), TSSetJacobian(), TSSetFunction()
6177: */
6178: PetscErrorCode  TSSetFunctionMatlab(TS ts,const char *func,mxArray *ctx)
6179: {
6180:   PetscErrorCode  ierr;
6181:   TSMatlabContext *sctx;

6184:   /* currently sctx is memory bleed */
6185:   PetscMalloc(sizeof(TSMatlabContext),&sctx);
6186:   PetscStrallocpy(func,&sctx->funcname);
6187:   /*
6188:      This should work, but it doesn't
6189:   sctx->ctx = ctx;
6190:   mexMakeArrayPersistent(sctx->ctx);
6191:   */
6192:   sctx->ctx = mxDuplicateArray(ctx);

6194:   TSSetIFunction(ts,NULL,TSComputeFunction_Matlab,sctx);
6195:   return(0);
6196: }

6200: /*
6201:    TSComputeJacobian_Matlab - Calls the function that has been set with
6202:                          TSSetJacobianMatlab().

6204:    Collective on TS

6206:    Input Parameters:
6207: +  ts - the TS context
6208: .  u - input vector
6209: .  A, B - the matrices
6210: -  ctx - user context

6212:    Level: developer

6214: .keywords: TS, nonlinear, compute, function

6216: .seealso: TSSetFunction(), TSGetFunction()
6217: @*/
6218: PetscErrorCode  TSComputeJacobian_Matlab(TS ts,PetscReal time,Vec u,Vec udot,PetscReal shift,Mat A,Mat B,void *ctx)
6219: {
6220:   PetscErrorCode  ierr;
6221:   TSMatlabContext *sctx = (TSMatlabContext*)ctx;
6222:   int             nlhs  = 2,nrhs = 9;
6223:   mxArray         *plhs[2],*prhs[9];
6224:   long long int   lx = 0,lxdot = 0,lA = 0,ls = 0, lB = 0;


6230:   /* call Matlab function in ctx with arguments u and y */

6232:   PetscMemcpy(&ls,&ts,sizeof(ts));
6233:   PetscMemcpy(&lx,&u,sizeof(u));
6234:   PetscMemcpy(&lxdot,&udot,sizeof(u));
6235:   PetscMemcpy(&lA,A,sizeof(u));
6236:   PetscMemcpy(&lB,B,sizeof(u));

6238:   prhs[0] =  mxCreateDoubleScalar((double)ls);
6239:   prhs[1] =  mxCreateDoubleScalar((double)time);
6240:   prhs[2] =  mxCreateDoubleScalar((double)lx);
6241:   prhs[3] =  mxCreateDoubleScalar((double)lxdot);
6242:   prhs[4] =  mxCreateDoubleScalar((double)shift);
6243:   prhs[5] =  mxCreateDoubleScalar((double)lA);
6244:   prhs[6] =  mxCreateDoubleScalar((double)lB);
6245:   prhs[7] =  mxCreateString(sctx->funcname);
6246:   prhs[8] =  sctx->ctx;
6247:    mexCallMATLAB(nlhs,plhs,nrhs,prhs,"PetscTSComputeJacobianInternal");
6248:    mxGetScalar(plhs[0]);
6249:   mxDestroyArray(prhs[0]);
6250:   mxDestroyArray(prhs[1]);
6251:   mxDestroyArray(prhs[2]);
6252:   mxDestroyArray(prhs[3]);
6253:   mxDestroyArray(prhs[4]);
6254:   mxDestroyArray(prhs[5]);
6255:   mxDestroyArray(prhs[6]);
6256:   mxDestroyArray(prhs[7]);
6257:   mxDestroyArray(plhs[0]);
6258:   mxDestroyArray(plhs[1]);
6259:   return(0);
6260: }


6265: /*
6266:    TSSetJacobianMatlab - Sets the Jacobian function evaluation routine and two empty Jacobian matrices
6267:    vector for use by the TS routines in solving ODEs from MATLAB. Here the function is a string containing the name of a MATLAB function

6269:    Logically Collective on TS

6271:    Input Parameters:
6272: +  ts - the TS context
6273: .  A,B - Jacobian matrices
6274: .  func - function evaluation routine
6275: -  ctx - user context

6277:    Calling sequence of func:
6278: $    flag = func (TS ts,PetscReal time,Vec u,Vec udot,Mat A,Mat B,void *ctx);


6281:    Level: developer

6283: .keywords: TS, nonlinear, set, function

6285: .seealso: TSGetFunction(), TSComputeFunction(), TSSetJacobian(), TSSetFunction()
6286: */
6287: PetscErrorCode  TSSetJacobianMatlab(TS ts,Mat A,Mat B,const char *func,mxArray *ctx)
6288: {
6289:   PetscErrorCode  ierr;
6290:   TSMatlabContext *sctx;

6293:   /* currently sctx is memory bleed */
6294:   PetscMalloc(sizeof(TSMatlabContext),&sctx);
6295:   PetscStrallocpy(func,&sctx->funcname);
6296:   /*
6297:      This should work, but it doesn't
6298:   sctx->ctx = ctx;
6299:   mexMakeArrayPersistent(sctx->ctx);
6300:   */
6301:   sctx->ctx = mxDuplicateArray(ctx);

6303:   TSSetIJacobian(ts,A,B,TSComputeJacobian_Matlab,sctx);
6304:   return(0);
6305: }

6309: /*
6310:    TSMonitor_Matlab - Calls the function that has been set with TSMonitorSetMatlab().

6312:    Collective on TS

6314: .seealso: TSSetFunction(), TSGetFunction()
6315: @*/
6316: PetscErrorCode  TSMonitor_Matlab(TS ts,PetscInt it, PetscReal time,Vec u, void *ctx)
6317: {
6318:   PetscErrorCode  ierr;
6319:   TSMatlabContext *sctx = (TSMatlabContext*)ctx;
6320:   int             nlhs  = 1,nrhs = 6;
6321:   mxArray         *plhs[1],*prhs[6];
6322:   long long int   lx = 0,ls = 0;


6328:   PetscMemcpy(&ls,&ts,sizeof(ts));
6329:   PetscMemcpy(&lx,&u,sizeof(u));

6331:   prhs[0] =  mxCreateDoubleScalar((double)ls);
6332:   prhs[1] =  mxCreateDoubleScalar((double)it);
6333:   prhs[2] =  mxCreateDoubleScalar((double)time);
6334:   prhs[3] =  mxCreateDoubleScalar((double)lx);
6335:   prhs[4] =  mxCreateString(sctx->funcname);
6336:   prhs[5] =  sctx->ctx;
6337:    mexCallMATLAB(nlhs,plhs,nrhs,prhs,"PetscTSMonitorInternal");
6338:    mxGetScalar(plhs[0]);
6339:   mxDestroyArray(prhs[0]);
6340:   mxDestroyArray(prhs[1]);
6341:   mxDestroyArray(prhs[2]);
6342:   mxDestroyArray(prhs[3]);
6343:   mxDestroyArray(prhs[4]);
6344:   mxDestroyArray(plhs[0]);
6345:   return(0);
6346: }


6351: /*
6352:    TSMonitorSetMatlab - Sets the monitor function from Matlab

6354:    Level: developer

6356: .keywords: TS, nonlinear, set, function

6358: .seealso: TSGetFunction(), TSComputeFunction(), TSSetJacobian(), TSSetFunction()
6359: */
6360: PetscErrorCode  TSMonitorSetMatlab(TS ts,const char *func,mxArray *ctx)
6361: {
6362:   PetscErrorCode  ierr;
6363:   TSMatlabContext *sctx;

6366:   /* currently sctx is memory bleed */
6367:   PetscMalloc(sizeof(TSMatlabContext),&sctx);
6368:   PetscStrallocpy(func,&sctx->funcname);
6369:   /*
6370:      This should work, but it doesn't
6371:   sctx->ctx = ctx;
6372:   mexMakeArrayPersistent(sctx->ctx);
6373:   */
6374:   sctx->ctx = mxDuplicateArray(ctx);

6376:   TSMonitorSet(ts,TSMonitor_Matlab,sctx,NULL);
6377:   return(0);
6378: }
6379: #endif

6383: /*@C
6384:    TSMonitorLGSolution - Monitors progress of the TS solvers by plotting each component of the solution vector
6385:        in a time based line graph

6387:    Collective on TS

6389:    Input Parameters:
6390: +  ts - the TS context
6391: .  step - current time-step
6392: .  ptime - current time
6393: .  u - current solution
6394: -  dctx - the TSMonitorLGCtx object that contains all the options for the monitoring, this is created with TSMonitorLGCtxCreate()

6396:    Options Database:
6397: .   -ts_monitor_lg_solution_variables

6399:    Level: intermediate

6401:    Notes: Each process in a parallel run displays its component solutions in a separate window

6403: .keywords: TS,  vector, monitor, view

6405: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorLGCtxCreate(), TSMonitorLGCtxSetVariableNames(), TSMonitorLGCtxGetVariableNames(),
6406:            TSMonitorLGSetVariableNames(), TSMonitorLGGetVariableNames(), TSMonitorLGSetDisplayVariables(), TSMonitorLGCtxSetDisplayVariables(),
6407:            TSMonitorLGCtxSetTransform(), TSMonitorLGSetTransform(), TSMonitorLGError(), TSMonitorLGSNESIterations(), TSMonitorLGKSPIterations(),
6408:            TSMonitorEnvelopeCtxCreate(), TSMonitorEnvelopeGetBounds(), TSMonitorEnvelopeCtxDestroy(), TSMonitorEnvelop()
6409: @*/
6410: PetscErrorCode  TSMonitorLGSolution(TS ts,PetscInt step,PetscReal ptime,Vec u,void *dctx)
6411: {
6412:   PetscErrorCode    ierr;
6413:   TSMonitorLGCtx    ctx = (TSMonitorLGCtx)dctx;
6414:   const PetscScalar *yy;
6415:   Vec               v;

6418:   if (step < 0) return(0); /* -1 indicates interpolated solution */
6419:   if (!step) {
6420:     PetscDrawAxis axis;
6421:     PetscInt      dim;
6422:     PetscDrawLGGetAxis(ctx->lg,&axis);
6423:     PetscDrawAxisSetLabels(axis,"Solution as function of time","Time","Solution");
6424:     if (ctx->names && !ctx->displaynames) {
6425:       char      **displaynames;
6426:       PetscBool flg;
6427:       VecGetLocalSize(u,&dim);
6428:       PetscMalloc((dim+1)*sizeof(char*),&displaynames);
6429:       PetscMemzero(displaynames,(dim+1)*sizeof(char*));
6430:       PetscOptionsGetStringArray(((PetscObject)ts)->options,((PetscObject)ts)->prefix,"-ts_monitor_lg_solution_variables",displaynames,&dim,&flg);
6431:       if (flg) {
6432:         TSMonitorLGCtxSetDisplayVariables(ctx,(const char *const *)displaynames);
6433:       }
6434:       PetscStrArrayDestroy(&displaynames);
6435:     }
6436:     if (ctx->displaynames) {
6437:       PetscDrawLGSetDimension(ctx->lg,ctx->ndisplayvariables);
6438:       PetscDrawLGSetLegend(ctx->lg,(const char *const *)ctx->displaynames);
6439:     } else if (ctx->names) {
6440:       VecGetLocalSize(u,&dim);
6441:       PetscDrawLGSetDimension(ctx->lg,dim);
6442:       PetscDrawLGSetLegend(ctx->lg,(const char *const *)ctx->names);
6443:     } else {
6444:       VecGetLocalSize(u,&dim);
6445:       PetscDrawLGSetDimension(ctx->lg,dim);
6446:     }
6447:     PetscDrawLGReset(ctx->lg);
6448:   }

6450:   if (!ctx->transform) v = u;
6451:   else {(*ctx->transform)(ctx->transformctx,u,&v);}
6452:   VecGetArrayRead(v,&yy);
6453:   if (ctx->displaynames) {
6454:     PetscInt i;
6455:     for (i=0; i<ctx->ndisplayvariables; i++)
6456:       ctx->displayvalues[i] = PetscRealPart(yy[ctx->displayvariables[i]]);
6457:     PetscDrawLGAddCommonPoint(ctx->lg,ptime,ctx->displayvalues);
6458:   } else {
6459: #if defined(PETSC_USE_COMPLEX)
6460:     PetscInt  i,n;
6461:     PetscReal *yreal;
6462:     VecGetLocalSize(v,&n);
6463:     PetscMalloc1(n,&yreal);
6464:     for (i=0; i<n; i++) yreal[i] = PetscRealPart(yy[i]);
6465:     PetscDrawLGAddCommonPoint(ctx->lg,ptime,yreal);
6466:     PetscFree(yreal);
6467: #else
6468:     PetscDrawLGAddCommonPoint(ctx->lg,ptime,yy);
6469: #endif
6470:   }
6471:   VecRestoreArrayRead(v,&yy);
6472:   if (ctx->transform) {VecDestroy(&v);}

6474:   if (((ctx->howoften > 0) && (!(step % ctx->howoften))) || ((ctx->howoften == -1) && ts->reason)) {
6475:     PetscDrawLGDraw(ctx->lg);
6476:     PetscDrawLGSave(ctx->lg);
6477:   }
6478:   return(0);
6479: }


6484: /*@C
6485:    TSMonitorLGSetVariableNames - Sets the name of each component in the solution vector so that it may be displayed in the plot

6487:    Collective on TS

6489:    Input Parameters:
6490: +  ts - the TS context
6491: -  names - the names of the components, final string must be NULL

6493:    Level: intermediate

6495:    Notes: If the TS object does not have a TSMonitorLGCtx associated with it then this function is ignored

6497: .keywords: TS,  vector, monitor, view

6499: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorLGSetDisplayVariables(), TSMonitorLGCtxSetVariableNames()
6500: @*/
6501: PetscErrorCode  TSMonitorLGSetVariableNames(TS ts,const char * const *names)
6502: {
6503:   PetscErrorCode    ierr;
6504:   PetscInt          i;

6507:   for (i=0; i<ts->numbermonitors; i++) {
6508:     if (ts->monitor[i] == TSMonitorLGSolution) {
6509:       TSMonitorLGCtxSetVariableNames((TSMonitorLGCtx)ts->monitorcontext[i],names);
6510:       break;
6511:     }
6512:   }
6513:   return(0);
6514: }

6518: /*@C
6519:    TSMonitorLGCtxSetVariableNames - Sets the name of each component in the solution vector so that it may be displayed in the plot

6521:    Collective on TS

6523:    Input Parameters:
6524: +  ts - the TS context
6525: -  names - the names of the components, final string must be NULL

6527:    Level: intermediate

6529: .keywords: TS,  vector, monitor, view

6531: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorLGSetDisplayVariables(), TSMonitorLGSetVariableNames()
6532: @*/
6533: PetscErrorCode  TSMonitorLGCtxSetVariableNames(TSMonitorLGCtx ctx,const char * const *names)
6534: {
6535:   PetscErrorCode    ierr;

6538:   PetscStrArrayDestroy(&ctx->names);
6539:   PetscStrArrayallocpy(names,&ctx->names);
6540:   return(0);
6541: }

6545: /*@C
6546:    TSMonitorLGGetVariableNames - Gets the name of each component in the solution vector so that it may be displayed in the plot

6548:    Collective on TS

6550:    Input Parameter:
6551: .  ts - the TS context

6553:    Output Parameter:
6554: .  names - the names of the components, final string must be NULL

6556:    Level: intermediate

6558:    Notes: If the TS object does not have a TSMonitorLGCtx associated with it then this function is ignored

6560: .keywords: TS,  vector, monitor, view

6562: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorLGSetDisplayVariables()
6563: @*/
6564: PetscErrorCode  TSMonitorLGGetVariableNames(TS ts,const char *const **names)
6565: {
6566:   PetscInt       i;

6569:   *names = NULL;
6570:   for (i=0; i<ts->numbermonitors; i++) {
6571:     if (ts->monitor[i] == TSMonitorLGSolution) {
6572:       TSMonitorLGCtx  ctx = (TSMonitorLGCtx) ts->monitorcontext[i];
6573:       *names = (const char *const *)ctx->names;
6574:       break;
6575:     }
6576:   }
6577:   return(0);
6578: }

6582: /*@C
6583:    TSMonitorLGCtxSetDisplayVariables - Sets the variables that are to be display in the monitor

6585:    Collective on TS

6587:    Input Parameters:
6588: +  ctx - the TSMonitorLG context
6589: .  displaynames - the names of the components, final string must be NULL

6591:    Level: intermediate

6593: .keywords: TS,  vector, monitor, view

6595: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorLGSetVariableNames()
6596: @*/
6597: PetscErrorCode  TSMonitorLGCtxSetDisplayVariables(TSMonitorLGCtx ctx,const char * const *displaynames)
6598: {
6599:   PetscInt          j = 0,k;
6600:   PetscErrorCode    ierr;

6603:   if (!ctx->names) return(0);
6604:   PetscStrArrayDestroy(&ctx->displaynames);
6605:   PetscStrArrayallocpy(displaynames,&ctx->displaynames);
6606:   while (displaynames[j]) j++;
6607:   ctx->ndisplayvariables = j;
6608:   PetscMalloc1(ctx->ndisplayvariables,&ctx->displayvariables);
6609:   PetscMalloc1(ctx->ndisplayvariables,&ctx->displayvalues);
6610:   j = 0;
6611:   while (displaynames[j]) {
6612:     k = 0;
6613:     while (ctx->names[k]) {
6614:       PetscBool flg;
6615:       PetscStrcmp(displaynames[j],ctx->names[k],&flg);
6616:       if (flg) {
6617:         ctx->displayvariables[j] = k;
6618:         break;
6619:       }
6620:       k++;
6621:     }
6622:     j++;
6623:   }
6624:   return(0);
6625: }


6630: /*@C
6631:    TSMonitorLGSetDisplayVariables - Sets the variables that are to be display in the monitor

6633:    Collective on TS

6635:    Input Parameters:
6636: +  ts - the TS context
6637: .  displaynames - the names of the components, final string must be NULL

6639:    Notes: If the TS object does not have a TSMonitorLGCtx associated with it then this function is ignored

6641:    Level: intermediate

6643: .keywords: TS,  vector, monitor, view

6645: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorLGSetVariableNames()
6646: @*/
6647: PetscErrorCode  TSMonitorLGSetDisplayVariables(TS ts,const char * const *displaynames)
6648: {
6649:   PetscInt          i;
6650:   PetscErrorCode    ierr;

6653:   for (i=0; i<ts->numbermonitors; i++) {
6654:     if (ts->monitor[i] == TSMonitorLGSolution) {
6655:       TSMonitorLGCtxSetDisplayVariables((TSMonitorLGCtx)ts->monitorcontext[i],displaynames);
6656:       break;
6657:     }
6658:   }
6659:   return(0);
6660: }

6664: /*@C
6665:    TSMonitorLGSetTransform - Solution vector will be transformed by provided function before being displayed

6667:    Collective on TS

6669:    Input Parameters:
6670: +  ts - the TS context
6671: .  transform - the transform function
6672: .  destroy - function to destroy the optional context
6673: -  ctx - optional context used by transform function

6675:    Notes: If the TS object does not have a TSMonitorLGCtx associated with it then this function is ignored

6677:    Level: intermediate

6679: .keywords: TS,  vector, monitor, view

6681: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorLGSetVariableNames(), TSMonitorLGCtxSetTransform()
6682: @*/
6683: PetscErrorCode  TSMonitorLGSetTransform(TS ts,PetscErrorCode (*transform)(void*,Vec,Vec*),PetscErrorCode (*destroy)(void*),void *tctx)
6684: {
6685:   PetscInt          i;
6686:   PetscErrorCode    ierr;

6689:   for (i=0; i<ts->numbermonitors; i++) {
6690:     if (ts->monitor[i] == TSMonitorLGSolution) {
6691:       TSMonitorLGCtxSetTransform((TSMonitorLGCtx)ts->monitorcontext[i],transform,destroy,tctx);
6692:     }
6693:   }
6694:   return(0);
6695: }

6699: /*@C
6700:    TSMonitorLGCtxSetTransform - Solution vector will be transformed by provided function before being displayed

6702:    Collective on TSLGCtx

6704:    Input Parameters:
6705: +  ts - the TS context
6706: .  transform - the transform function
6707: .  destroy - function to destroy the optional context
6708: -  ctx - optional context used by transform function

6710:    Level: intermediate

6712: .keywords: TS,  vector, monitor, view

6714: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorLGSetVariableNames(), TSMonitorLGSetTransform()
6715: @*/
6716: PetscErrorCode  TSMonitorLGCtxSetTransform(TSMonitorLGCtx ctx,PetscErrorCode (*transform)(void*,Vec,Vec*),PetscErrorCode (*destroy)(void*),void *tctx)
6717: {
6719:   ctx->transform    = transform;
6720:   ctx->transformdestroy = destroy;
6721:   ctx->transformctx = tctx;
6722:   return(0);
6723: }

6727: /*@C
6728:    TSMonitorLGError - Monitors progress of the TS solvers by plotting each component of the solution vector
6729:        in a time based line graph

6731:    Collective on TS

6733:    Input Parameters:
6734: +  ts - the TS context
6735: .  step - current time-step
6736: .  ptime - current time
6737: .  u - current solution
6738: -  dctx - TSMonitorLGCtx object created with TSMonitorLGCtxCreate()

6740:    Level: intermediate

6742:    Notes: Each process in a parallel run displays its component errors in a separate window

6744:    The user must provide the solution using TSSetSolutionFunction() to use this monitor.

6746:    Options Database Keys:
6747: .  -ts_monitor_lg_error - create a graphical monitor of error history

6749: .keywords: TS,  vector, monitor, view

6751: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSSetSolutionFunction()
6752: @*/
6753: PetscErrorCode  TSMonitorLGError(TS ts,PetscInt step,PetscReal ptime,Vec u,void *dummy)
6754: {
6755:   PetscErrorCode    ierr;
6756:   TSMonitorLGCtx    ctx = (TSMonitorLGCtx)dummy;
6757:   const PetscScalar *yy;
6758:   Vec               y;

6761:   if (!step) {
6762:     PetscDrawAxis axis;
6763:     PetscInt      dim;
6764:     PetscDrawLGGetAxis(ctx->lg,&axis);
6765:     PetscDrawAxisSetLabels(axis,"Error in solution as function of time","Time","Solution");
6766:     VecGetLocalSize(u,&dim);
6767:     PetscDrawLGSetDimension(ctx->lg,dim);
6768:     PetscDrawLGReset(ctx->lg);
6769:   }
6770:   VecDuplicate(u,&y);
6771:   TSComputeSolutionFunction(ts,ptime,y);
6772:   VecAXPY(y,-1.0,u);
6773:   VecGetArrayRead(y,&yy);
6774: #if defined(PETSC_USE_COMPLEX)
6775:   {
6776:     PetscReal *yreal;
6777:     PetscInt  i,n;
6778:     VecGetLocalSize(y,&n);
6779:     PetscMalloc1(n,&yreal);
6780:     for (i=0; i<n; i++) yreal[i] = PetscRealPart(yy[i]);
6781:     PetscDrawLGAddCommonPoint(ctx->lg,ptime,yreal);
6782:     PetscFree(yreal);
6783:   }
6784: #else
6785:   PetscDrawLGAddCommonPoint(ctx->lg,ptime,yy);
6786: #endif
6787:   VecRestoreArrayRead(y,&yy);
6788:   VecDestroy(&y);
6789:   if (((ctx->howoften > 0) && (!(step % ctx->howoften))) || ((ctx->howoften == -1) && ts->reason)) {
6790:     PetscDrawLGDraw(ctx->lg);
6791:     PetscDrawLGSave(ctx->lg);
6792:   }
6793:   return(0);
6794: }

6798: PetscErrorCode TSMonitorLGSNESIterations(TS ts,PetscInt n,PetscReal ptime,Vec v,void *monctx)
6799: {
6800:   TSMonitorLGCtx ctx = (TSMonitorLGCtx) monctx;
6801:   PetscReal      x   = ptime,y;
6803:   PetscInt       its;

6806:   if (n < 0) return(0); /* -1 indicates interpolated solution */
6807:   if (!n) {
6808:     PetscDrawAxis axis;
6809:     PetscDrawLGGetAxis(ctx->lg,&axis);
6810:     PetscDrawAxisSetLabels(axis,"Nonlinear iterations as function of time","Time","SNES Iterations");
6811:     PetscDrawLGReset(ctx->lg);
6812:     ctx->snes_its = 0;
6813:   }
6814:   TSGetSNESIterations(ts,&its);
6815:   y    = its - ctx->snes_its;
6816:   PetscDrawLGAddPoint(ctx->lg,&x,&y);
6817:   if (((ctx->howoften > 0) && (!(n % ctx->howoften)) && (n > -1)) || ((ctx->howoften == -1) && (n == -1))) {
6818:     PetscDrawLGDraw(ctx->lg);
6819:     PetscDrawLGSave(ctx->lg);
6820:   }
6821:   ctx->snes_its = its;
6822:   return(0);
6823: }

6827: PetscErrorCode TSMonitorLGKSPIterations(TS ts,PetscInt n,PetscReal ptime,Vec v,void *monctx)
6828: {
6829:   TSMonitorLGCtx ctx = (TSMonitorLGCtx) monctx;
6830:   PetscReal      x   = ptime,y;
6832:   PetscInt       its;

6835:   if (n < 0) return(0); /* -1 indicates interpolated solution */
6836:   if (!n) {
6837:     PetscDrawAxis axis;
6838:     PetscDrawLGGetAxis(ctx->lg,&axis);
6839:     PetscDrawAxisSetLabels(axis,"Linear iterations as function of time","Time","KSP Iterations");
6840:     PetscDrawLGReset(ctx->lg);
6841:     ctx->ksp_its = 0;
6842:   }
6843:   TSGetKSPIterations(ts,&its);
6844:   y    = its - ctx->ksp_its;
6845:   PetscDrawLGAddPoint(ctx->lg,&x,&y);
6846:   if (((ctx->howoften > 0) && (!(n % ctx->howoften)) && (n > -1)) || ((ctx->howoften == -1) && (n == -1))) {
6847:     PetscDrawLGDraw(ctx->lg);
6848:     PetscDrawLGSave(ctx->lg);
6849:   }
6850:   ctx->ksp_its = its;
6851:   return(0);
6852: }

6856: /*@
6857:    TSComputeLinearStability - computes the linear stability function at a point

6859:    Collective on TS and Vec

6861:    Input Parameters:
6862: +  ts - the TS context
6863: -  xr,xi - real and imaginary part of input arguments

6865:    Output Parameters:
6866: .  yr,yi - real and imaginary part of function value

6868:    Level: developer

6870: .keywords: TS, compute

6872: .seealso: TSSetRHSFunction(), TSComputeIFunction()
6873: @*/
6874: PetscErrorCode TSComputeLinearStability(TS ts,PetscReal xr,PetscReal xi,PetscReal *yr,PetscReal *yi)
6875: {

6880:   if (!ts->ops->linearstability) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"Linearized stability function not provided for this method");
6881:   (*ts->ops->linearstability)(ts,xr,xi,yr,yi);
6882:   return(0);
6883: }

6885: /* ------------------------------------------------------------------------*/
6888: /*@C
6889:    TSMonitorEnvelopeCtxCreate - Creates a context for use with TSMonitorEnvelope()

6891:    Collective on TS

6893:    Input Parameters:
6894: .  ts  - the ODE solver object

6896:    Output Parameter:
6897: .  ctx - the context

6899:    Level: intermediate

6901: .keywords: TS, monitor, line graph, residual, seealso

6903: .seealso: TSMonitorLGTimeStep(), TSMonitorSet(), TSMonitorLGSolution(), TSMonitorLGError()

6905: @*/
6906: PetscErrorCode  TSMonitorEnvelopeCtxCreate(TS ts,TSMonitorEnvelopeCtx *ctx)
6907: {

6911:   PetscNew(ctx);
6912:   return(0);
6913: }

6917: /*@C
6918:    TSMonitorEnvelope - Monitors the maximum and minimum value of each component of the solution

6920:    Collective on TS

6922:    Input Parameters:
6923: +  ts - the TS context
6924: .  step - current time-step
6925: .  ptime - current time
6926: .  u  - current solution
6927: -  dctx - the envelope context

6929:    Options Database:
6930: .  -ts_monitor_envelope

6932:    Level: intermediate

6934:    Notes: after a solve you can use TSMonitorEnvelopeGetBounds() to access the envelope

6936: .keywords: TS,  vector, monitor, view

6938: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorEnvelopeGetBounds(), TSMonitorEnvelopeCtxCreate()
6939: @*/
6940: PetscErrorCode  TSMonitorEnvelope(TS ts,PetscInt step,PetscReal ptime,Vec u,void *dctx)
6941: {
6942:   PetscErrorCode       ierr;
6943:   TSMonitorEnvelopeCtx ctx = (TSMonitorEnvelopeCtx)dctx;

6946:   if (!ctx->max) {
6947:     VecDuplicate(u,&ctx->max);
6948:     VecDuplicate(u,&ctx->min);
6949:     VecCopy(u,ctx->max);
6950:     VecCopy(u,ctx->min);
6951:   } else {
6952:     VecPointwiseMax(ctx->max,u,ctx->max);
6953:     VecPointwiseMin(ctx->min,u,ctx->min);
6954:   }
6955:   return(0);
6956: }


6961: /*@C
6962:    TSMonitorEnvelopeGetBounds - Gets the bounds for the components of the solution

6964:    Collective on TS

6966:    Input Parameter:
6967: .  ts - the TS context

6969:    Output Parameter:
6970: +  max - the maximum values
6971: -  min - the minimum values

6973:    Notes: If the TS does not have a TSMonitorEnvelopeCtx associated with it then this function is ignored

6975:    Level: intermediate

6977: .keywords: TS,  vector, monitor, view

6979: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorLGSetDisplayVariables()
6980: @*/
6981: PetscErrorCode  TSMonitorEnvelopeGetBounds(TS ts,Vec *max,Vec *min)
6982: {
6983:   PetscInt i;

6986:   if (max) *max = NULL;
6987:   if (min) *min = NULL;
6988:   for (i=0; i<ts->numbermonitors; i++) {
6989:     if (ts->monitor[i] == TSMonitorEnvelope) {
6990:       TSMonitorEnvelopeCtx  ctx = (TSMonitorEnvelopeCtx) ts->monitorcontext[i];
6991:       if (max) *max = ctx->max;
6992:       if (min) *min = ctx->min;
6993:       break;
6994:     }
6995:   }
6996:   return(0);
6997: }

7001: /*@C
7002:    TSMonitorEnvelopeCtxDestroy - Destroys a context that was created  with TSMonitorEnvelopeCtxCreate().

7004:    Collective on TSMonitorEnvelopeCtx

7006:    Input Parameter:
7007: .  ctx - the monitor context

7009:    Level: intermediate

7011: .keywords: TS, monitor, line graph, destroy

7013: .seealso: TSMonitorLGCtxCreate(),  TSMonitorSet(), TSMonitorLGTimeStep()
7014: @*/
7015: PetscErrorCode  TSMonitorEnvelopeCtxDestroy(TSMonitorEnvelopeCtx *ctx)
7016: {

7020:   VecDestroy(&(*ctx)->min);
7021:   VecDestroy(&(*ctx)->max);
7022:   PetscFree(*ctx);
7023:   return(0);
7024: }

7028: /*@
7029:    TSRollBack - Rolls back one time step

7031:    Collective on TS

7033:    Input Parameter:
7034: .  ts - the TS context obtained from TSCreate()

7036:    Level: advanced

7038: .keywords: TS, timestep, rollback

7040: .seealso: TSCreate(), TSSetUp(), TSDestroy(), TSSolve(), TSSetPreStep(), TSSetPreStage(), TSInterpolate()
7041: @*/
7042: PetscErrorCode  TSRollBack(TS ts)
7043: {

7048:   if (ts->steprollback) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_ARG_WRONGSTATE,"TSRollBack already called");
7049:   if (!ts->ops->rollback) SETERRQ1(PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"TSRollBack not implemented for type '%s'",((PetscObject)ts)->type_name);
7050:   (*ts->ops->rollback)(ts);
7051:   ts->time_step = ts->ptime - ts->ptime_prev;
7052:   ts->ptime = ts->ptime_prev;
7053:   ts->ptime_prev = ts->ptime_prev_rollback;
7054:   ts->steps--; ts->total_steps--;
7055:   ts->steprollback = PETSC_TRUE;
7056:   return(0);
7057: }

7061: /*@
7062:    TSGetStages - Get the number of stages and stage values

7064:    Input Parameter:
7065: .  ts - the TS context obtained from TSCreate()

7067:    Level: advanced

7069: .keywords: TS, getstages

7071: .seealso: TSCreate()
7072: @*/
7073: PetscErrorCode  TSGetStages(TS ts,PetscInt *ns,Vec **Y)
7074: {


7081:   if (!ts->ops->getstages) *ns=0;
7082:   else {
7083:     (*ts->ops->getstages)(ts,ns,Y);
7084:   }
7085:   return(0);
7086: }

7090: /*@C
7091:   TSComputeIJacobianDefaultColor - Computes the Jacobian using finite differences and coloring to exploit matrix sparsity.

7093:   Collective on SNES

7095:   Input Parameters:
7096: + ts - the TS context
7097: . t - current timestep
7098: . U - state vector
7099: . Udot - time derivative of state vector
7100: . shift - shift to apply, see note below
7101: - ctx - an optional user context

7103:   Output Parameters:
7104: + J - Jacobian matrix (not altered in this routine)
7105: - B - newly computed Jacobian matrix to use with preconditioner (generally the same as J)

7107:   Level: intermediate

7109:   Notes:
7110:   If F(t,U,Udot)=0 is the DAE, the required Jacobian is

7112:   dF/dU + shift*dF/dUdot

7114:   Most users should not need to explicitly call this routine, as it
7115:   is used internally within the nonlinear solvers.

7117:   This will first try to get the coloring from the DM.  If the DM type has no coloring
7118:   routine, then it will try to get the coloring from the matrix.  This requires that the
7119:   matrix have nonzero entries precomputed.

7121: .keywords: TS, finite differences, Jacobian, coloring, sparse
7122: .seealso: TSSetIJacobian(), MatFDColoringCreate(), MatFDColoringSetFunction()
7123: @*/
7124: PetscErrorCode TSComputeIJacobianDefaultColor(TS ts,PetscReal t,Vec U,Vec Udot,PetscReal shift,Mat J,Mat B,void *ctx)
7125: {
7126:   SNES           snes;
7127:   MatFDColoring  color;
7128:   PetscBool      hascolor, matcolor = PETSC_FALSE;

7132:   PetscOptionsGetBool(((PetscObject)ts)->options,((PetscObject) ts)->prefix, "-ts_fd_color_use_mat", &matcolor, NULL);
7133:   PetscObjectQuery((PetscObject) B, "TSMatFDColoring", (PetscObject *) &color);
7134:   if (!color) {
7135:     DM         dm;
7136:     ISColoring iscoloring;

7138:     TSGetDM(ts, &dm);
7139:     DMHasColoring(dm, &hascolor);
7140:     if (hascolor && !matcolor) {
7141:       DMCreateColoring(dm, IS_COLORING_GLOBAL, &iscoloring);
7142:       MatFDColoringCreate(B, iscoloring, &color);
7143:       MatFDColoringSetFunction(color, (PetscErrorCode (*)(void)) SNESTSFormFunction, (void *) ts);
7144:       MatFDColoringSetFromOptions(color);
7145:       MatFDColoringSetUp(B, iscoloring, color);
7146:       ISColoringDestroy(&iscoloring);
7147:     } else {
7148:       MatColoring mc;

7150:       MatColoringCreate(B, &mc);
7151:       MatColoringSetDistance(mc, 2);
7152:       MatColoringSetType(mc, MATCOLORINGSL);
7153:       MatColoringSetFromOptions(mc);
7154:       MatColoringApply(mc, &iscoloring);
7155:       MatColoringDestroy(&mc);
7156:       MatFDColoringCreate(B, iscoloring, &color);
7157:       MatFDColoringSetFunction(color, (PetscErrorCode (*)(void)) SNESTSFormFunction, (void *) ts);
7158:       MatFDColoringSetFromOptions(color);
7159:       MatFDColoringSetUp(B, iscoloring, color);
7160:       ISColoringDestroy(&iscoloring);
7161:     }
7162:     PetscObjectCompose((PetscObject) B, "TSMatFDColoring", (PetscObject) color);
7163:     PetscObjectDereference((PetscObject) color);
7164:   }
7165:   TSGetSNES(ts, &snes);
7166:   MatFDColoringApply(B, color, U, snes);
7167:   if (J != B) {
7168:     MatAssemblyBegin(J, MAT_FINAL_ASSEMBLY);
7169:     MatAssemblyEnd(J, MAT_FINAL_ASSEMBLY);
7170:   }
7171:   return(0);
7172: }

7176: /*@
7177:     TSSetFunctionDomainError - Set the function testing if the current state vector is valid

7179:     Input Parameters:
7180:     ts - the TS context
7181:     func - function called within TSFunctionDomainError

7183:     Level: intermediate

7185: .keywords: TS, state, domain
7186: .seealso: TSAdaptCheckStage(), TSFunctionDomainError()
7187: @*/

7189: PetscErrorCode TSSetFunctionDomainError(TS ts, PetscErrorCode (*func)(TS,PetscReal,Vec,PetscBool*))
7190: {
7193:   ts->functiondomainerror = func;
7194:   return(0);
7195: }

7199: /*@
7200:     TSFunctionDomainError - Check if the current state is valid

7202:     Input Parameters:
7203:     ts - the TS context
7204:     stagetime - time of the simulation
7205:     Y - state vector to check.

7207:     Output Parameter:
7208:     accept - Set to PETSC_FALSE if the current state vector is valid.

7210:     Note:
7211:     This function should be used to ensure the state is in a valid part of the space.
7212:     For example, one can ensure here all values are positive.

7214:     Level: advanced
7215: @*/
7216: PetscErrorCode TSFunctionDomainError(TS ts,PetscReal stagetime,Vec Y,PetscBool* accept)
7217: {


7223:   *accept = PETSC_TRUE;
7224:   if (ts->functiondomainerror) {
7225:     PetscStackCallStandard((*ts->functiondomainerror),(ts,stagetime,Y,accept));
7226:   }
7227:   return(0);
7228: }

7230: #undef  __FUNCT__
7232: /*@C
7233:   TSClone - This function clones a time step object. 

7235:   Collective on MPI_Comm

7237:   Input Parameter:
7238: . tsin    - The input TS

7240:   Output Parameter:
7241: . tsout   - The output TS (cloned)

7243:   Notes:
7244:   This function is used to create a clone of a TS object. It is used in ARKIMEX for initializing the slope for first stage explicit methods. It will likely be replaced in the future with a mechanism of switching methods on the fly. 

7246:   When using TSDestroy() on a clone the user has to first reset the correct TS reference in the embedded SNES object: e.g.: by running SNES snes_dup=NULL; TSGetSNES(ts,&snes_dup); TSSetSNES(ts,snes_dup);

7248:   Level: developer

7250: .keywords: TS, clone
7251: .seealso: TSCreate(), TSSetType(), TSSetUp(), TSDestroy(), TSSetProblemType()
7252: @*/
7253: PetscErrorCode  TSClone(TS tsin, TS *tsout)
7254: {
7255:   TS             t;
7257:   SNES           snes_start;
7258:   DM             dm;
7259:   TSType         type;

7263:   *tsout = NULL;

7265:   PetscHeaderCreate(t, TS_CLASSID, "TS", "Time stepping", "TS", PetscObjectComm((PetscObject)tsin), TSDestroy, TSView);

7267:   /* General TS description */
7268:   t->numbermonitors    = 0;
7269:   t->setupcalled       = 0;
7270:   t->ksp_its           = 0;
7271:   t->snes_its          = 0;
7272:   t->nwork             = 0;
7273:   t->rhsjacobian.time  = -1e20;
7274:   t->rhsjacobian.scale = 1.;
7275:   t->ijacobian.shift   = 1.;

7277:   TSGetSNES(tsin,&snes_start);
7278:   TSSetSNES(t,snes_start);

7280:   TSGetDM(tsin,&dm);
7281:   TSSetDM(t,dm);

7283:   t->adapt = tsin->adapt;
7284:   PetscObjectReference((PetscObject)t->adapt);

7286:   t->problem_type      = tsin->problem_type;
7287:   t->ptime             = tsin->ptime;
7288:   t->time_step         = tsin->time_step;
7289:   t->max_time          = tsin->max_time;
7290:   t->steps             = tsin->steps;
7291:   t->max_steps         = tsin->max_steps;
7292:   t->equation_type     = tsin->equation_type;
7293:   t->atol              = tsin->atol;
7294:   t->rtol              = tsin->rtol;
7295:   t->max_snes_failures = tsin->max_snes_failures;
7296:   t->max_reject        = tsin->max_reject;
7297:   t->errorifstepfailed = tsin->errorifstepfailed;

7299:   TSGetType(tsin,&type);
7300:   TSSetType(t,type);

7302:   t->vec_sol           = NULL;

7304:   t->cfltime          = tsin->cfltime;
7305:   t->cfltime_local    = tsin->cfltime_local;
7306:   t->exact_final_time = tsin->exact_final_time;

7308:   PetscMemcpy(t->ops,tsin->ops,sizeof(struct _TSOps));

7310:   if (((PetscObject)tsin)->fortran_func_pointers) {
7311:     PetscInt i;
7312:     PetscMalloc((10)*sizeof(void(*)(void)),&((PetscObject)t)->fortran_func_pointers);
7313:     for (i=0; i<10; i++) {
7314:       ((PetscObject)t)->fortran_func_pointers[i] = ((PetscObject)tsin)->fortran_func_pointers[i];
7315:     }
7316:   }
7317:   *tsout = t;
7318:   return(0);
7319: }