Actual source code: ts.c

petsc-master 2019-11-20
Report Typos and Errors
  1:  #include <petsc/private/tsimpl.h>
  2:  #include <petscdmshell.h>
  3:  #include <petscdmda.h>
  4:  #include <petscviewer.h>
  5:  #include <petscdraw.h>
  6:  #include <petscconvest.h>

  8: #define SkipSmallValue(a,b,tol) if(PetscAbsScalar(a)< tol || PetscAbsScalar(b)< tol) continue;

 10: /* Logging support */
 11: PetscClassId  TS_CLASSID, DMTS_CLASSID;
 12: PetscLogEvent TS_Step, TS_PseudoComputeTimeStep, TS_FunctionEval, TS_JacobianEval;

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


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

 20:    Collective on TS

 22:    Input Parameters:
 23: +  ts - TS object you wish to monitor
 24: .  name - the monitor type one is seeking
 25: .  help - message indicating what monitoring is done
 26: .  manual - manual page for the monitor
 27: .  monitor - the monitor function
 28: -  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

 30:    Level: developer

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

 48:   PetscOptionsGetViewer(PetscObjectComm((PetscObject)ts),((PetscObject) ts)->options,((PetscObject)ts)->prefix,name,&viewer,&format,&flg);
 49:   if (flg) {
 50:     PetscViewerAndFormat *vf;
 51:     PetscViewerAndFormatCreate(viewer,format,&vf);
 52:     PetscObjectDereference((PetscObject)viewer);
 53:     if (monitorsetup) {
 54:       (*monitorsetup)(ts,vf);
 55:     }
 56:     TSMonitorSet(ts,(PetscErrorCode (*)(TS,PetscInt,PetscReal,Vec,void*))monitor,vf,(PetscErrorCode (*)(void**))PetscViewerAndFormatDestroy);
 57:   }
 58:   return(0);
 59: }

 61: static PetscErrorCode TSAdaptSetDefaultType(TSAdapt adapt,TSAdaptType default_type)
 62: {

 68:   if (!((PetscObject)adapt)->type_name) {
 69:     TSAdaptSetType(adapt,default_type);
 70:   }
 71:   return(0);
 72: }

 74: /*@
 75:    TSSetFromOptions - Sets various TS parameters from user options.

 77:    Collective on TS

 79:    Input Parameter:
 80: .  ts - the TS context obtained from TSCreate()

 82:    Options Database Keys:
 83: +  -ts_type <type> - TSEULER, TSBEULER, TSSUNDIALS, TSPSEUDO, TSCN, TSRK, TSTHETA, TSALPHA, TSGLLE, TSSSP, TSGLEE, TSBSYMP
 84: .  -ts_save_trajectory - checkpoint the solution at each time-step
 85: .  -ts_max_time <time> - maximum time to compute to
 86: .  -ts_max_steps <steps> - maximum number of time-steps to take
 87: .  -ts_init_time <time> - initial time to start computation
 88: .  -ts_final_time <time> - final time to compute to (deprecated: use -ts_max_time)
 89: .  -ts_dt <dt> - initial time step
 90: .  -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
 91: .  -ts_max_snes_failures <maxfailures> - Maximum number of nonlinear solve failures allowed
 92: .  -ts_max_reject <maxrejects> - Maximum number of step rejections before step fails
 93: .  -ts_error_if_step_fails <true,false> - Error if no step succeeds
 94: .  -ts_rtol <rtol> - relative tolerance for local truncation error
 95: .  -ts_atol <atol> Absolute tolerance for local truncation error
 96: .  -ts_rhs_jacobian_test_mult -mat_shell_test_mult_view - test the Jacobian at each iteration against finite difference with RHS function
 97: .  -ts_rhs_jacobian_test_mult_transpose -mat_shell_test_mult_transpose_view - test the Jacobian at each iteration against finite difference with RHS function
 98: .  -ts_adjoint_solve <yes,no> After solving the ODE/DAE solve the adjoint problem (requires -ts_save_trajectory)
 99: .  -ts_fd_color - Use finite differences with coloring to compute IJacobian
100: .  -ts_monitor - print information at each timestep
101: .  -ts_monitor_lg_solution - Monitor solution graphically
102: .  -ts_monitor_lg_error - Monitor error graphically
103: .  -ts_monitor_error - Monitors norm of error
104: .  -ts_monitor_lg_timestep - Monitor timestep size graphically
105: .  -ts_monitor_lg_timestep_log - Monitor log timestep size graphically
106: .  -ts_monitor_lg_snes_iterations - Monitor number nonlinear iterations for each timestep graphically
107: .  -ts_monitor_lg_ksp_iterations - Monitor number nonlinear iterations for each timestep graphically
108: .  -ts_monitor_sp_eig - Monitor eigenvalues of linearized operator graphically
109: .  -ts_monitor_draw_solution - Monitor solution graphically
110: .  -ts_monitor_draw_solution_phase  <xleft,yleft,xright,yright> - Monitor solution graphically with phase diagram, requires problem with exactly 2 degrees of freedom
111: .  -ts_monitor_draw_error - Monitor error graphically, requires use to have provided TSSetSolutionFunction()
112: .  -ts_monitor_solution [ascii binary draw][:filename][:viewerformat] - monitors the solution at each timestep
113: .  -ts_monitor_solution_vtk <filename.vts,filename.vtu> - Save each time step to a binary file, use filename-%%03D.vts (filename-%%03D.vtu)
114: -  -ts_monitor_envelope - determine maximum and minimum value of each component of the solution over the solution time

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

119:    Level: beginner

121: .seealso: TSGetType()
122: @*/
123: PetscErrorCode  TSSetFromOptions(TS ts)
124: {
125:   PetscBool              opt,flg,tflg;
126:   PetscErrorCode         ierr;
127:   char                   monfilename[PETSC_MAX_PATH_LEN];
128:   PetscReal              time_step;
129:   TSExactFinalTimeOption eftopt;
130:   char                   dir[16];
131:   TSIFunction            ifun;
132:   const char             *defaultType;
133:   char                   typeName[256];


138:   TSRegisterAll();
139:   TSGetIFunction(ts,NULL,&ifun,NULL);

141:   PetscObjectOptionsBegin((PetscObject)ts);
142:   if (((PetscObject)ts)->type_name) defaultType = ((PetscObject)ts)->type_name;
143:   else defaultType = ifun ? TSBEULER : TSEULER;
144:   PetscOptionsFList("-ts_type","TS method","TSSetType",TSList,defaultType,typeName,256,&opt);
145:   if (opt) {
146:     TSSetType(ts,typeName);
147:   } else {
148:     TSSetType(ts,defaultType);
149:   }

151:   /* Handle generic TS options */
152:   PetscOptionsDeprecated("-ts_final_time","-ts_max_time","3.10",NULL);
153:   PetscOptionsReal("-ts_max_time","Maximum time to run to","TSSetMaxTime",ts->max_time,&ts->max_time,NULL);
154:   PetscOptionsInt("-ts_max_steps","Maximum number of time steps","TSSetMaxSteps",ts->max_steps,&ts->max_steps,NULL);
155:   PetscOptionsReal("-ts_init_time","Initial time","TSSetTime",ts->ptime,&ts->ptime,NULL);
156:   PetscOptionsReal("-ts_dt","Initial time step","TSSetTimeStep",ts->time_step,&time_step,&flg);
157:   if (flg) {TSSetTimeStep(ts,time_step);}
158:   PetscOptionsEnum("-ts_exact_final_time","Option for handling of final time step","TSSetExactFinalTime",TSExactFinalTimeOptions,(PetscEnum)ts->exact_final_time,(PetscEnum*)&eftopt,&flg);
159:   if (flg) {TSSetExactFinalTime(ts,eftopt);}
160:   PetscOptionsInt("-ts_max_snes_failures","Maximum number of nonlinear solve failures","TSSetMaxSNESFailures",ts->max_snes_failures,&ts->max_snes_failures,NULL);
161:   PetscOptionsInt("-ts_max_reject","Maximum number of step rejections before step fails","TSSetMaxStepRejections",ts->max_reject,&ts->max_reject,NULL);
162:   PetscOptionsBool("-ts_error_if_step_fails","Error if no step succeeds","TSSetErrorIfStepFails",ts->errorifstepfailed,&ts->errorifstepfailed,NULL);
163:   PetscOptionsReal("-ts_rtol","Relative tolerance for local truncation error","TSSetTolerances",ts->rtol,&ts->rtol,NULL);
164:   PetscOptionsReal("-ts_atol","Absolute tolerance for local truncation error","TSSetTolerances",ts->atol,&ts->atol,NULL);

166:   PetscOptionsBool("-ts_rhs_jacobian_test_mult","Test the RHS Jacobian for consistency with RHS at each solve ","None",ts->testjacobian,&ts->testjacobian,NULL);
167:   PetscOptionsBool("-ts_rhs_jacobian_test_mult_transpose","Test the RHS Jacobian transpose for consistency with RHS at each solve ","None",ts->testjacobiantranspose,&ts->testjacobiantranspose,NULL);
168:   PetscOptionsBool("-ts_use_splitrhsfunction","Use the split RHS function for multirate solvers ","TSSetUseSplitRHSFunction",ts->use_splitrhsfunction,&ts->use_splitrhsfunction,NULL);
169: #if defined(PETSC_HAVE_SAWS)
170:   {
171:   PetscBool set;
172:   flg  = PETSC_FALSE;
173:   PetscOptionsBool("-ts_saws_block","Block for SAWs memory snooper at end of TSSolve","PetscObjectSAWsBlock",((PetscObject)ts)->amspublishblock,&flg,&set);
174:   if (set) {
175:     PetscObjectSAWsSetBlock((PetscObject)ts,flg);
176:   }
177:   }
178: #endif

180:   /* Monitor options */
181:   TSMonitorSetFromOptions(ts,"-ts_monitor","Monitor time and timestep size","TSMonitorDefault",TSMonitorDefault,NULL);
182:   TSMonitorSetFromOptions(ts,"-ts_monitor_extreme","Monitor extreme values of the solution","TSMonitorExtreme",TSMonitorExtreme,NULL);
183:   TSMonitorSetFromOptions(ts,"-ts_monitor_solution","View the solution at each timestep","TSMonitorSolution",TSMonitorSolution,NULL);

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

188:   PetscOptionsName("-ts_monitor_lg_solution","Monitor solution graphically","TSMonitorLGSolution",&opt);
189:   if (opt) {
190:     TSMonitorLGCtx ctx;
191:     PetscInt       howoften = 1;

193:     PetscOptionsInt("-ts_monitor_lg_solution","Monitor solution graphically","TSMonitorLGSolution",howoften,&howoften,NULL);
194:     TSMonitorLGCtxCreate(PETSC_COMM_SELF,0,0,PETSC_DECIDE,PETSC_DECIDE,400,300,howoften,&ctx);
195:     TSMonitorSet(ts,TSMonitorLGSolution,ctx,(PetscErrorCode (*)(void**))TSMonitorLGCtxDestroy);
196:   }

198:   PetscOptionsName("-ts_monitor_lg_error","Monitor error graphically","TSMonitorLGError",&opt);
199:   if (opt) {
200:     TSMonitorLGCtx ctx;
201:     PetscInt       howoften = 1;

203:     PetscOptionsInt("-ts_monitor_lg_error","Monitor error graphically","TSMonitorLGError",howoften,&howoften,NULL);
204:     TSMonitorLGCtxCreate(PETSC_COMM_SELF,0,0,PETSC_DECIDE,PETSC_DECIDE,400,300,howoften,&ctx);
205:     TSMonitorSet(ts,TSMonitorLGError,ctx,(PetscErrorCode (*)(void**))TSMonitorLGCtxDestroy);
206:   }
207:   TSMonitorSetFromOptions(ts,"-ts_monitor_error","View the error at each timestep","TSMonitorError",TSMonitorError,NULL);

209:   PetscOptionsName("-ts_monitor_lg_timestep","Monitor timestep size graphically","TSMonitorLGTimeStep",&opt);
210:   if (opt) {
211:     TSMonitorLGCtx ctx;
212:     PetscInt       howoften = 1;

214:     PetscOptionsInt("-ts_monitor_lg_timestep","Monitor timestep size graphically","TSMonitorLGTimeStep",howoften,&howoften,NULL);
215:     TSMonitorLGCtxCreate(PetscObjectComm((PetscObject)ts),NULL,NULL,PETSC_DECIDE,PETSC_DECIDE,400,300,howoften,&ctx);
216:     TSMonitorSet(ts,TSMonitorLGTimeStep,ctx,(PetscErrorCode (*)(void**))TSMonitorLGCtxDestroy);
217:   }
218:   PetscOptionsName("-ts_monitor_lg_timestep_log","Monitor log timestep size graphically","TSMonitorLGTimeStep",&opt);
219:   if (opt) {
220:     TSMonitorLGCtx ctx;
221:     PetscInt       howoften = 1;

223:     PetscOptionsInt("-ts_monitor_lg_timestep_log","Monitor log timestep size graphically","TSMonitorLGTimeStep",howoften,&howoften,NULL);
224:     TSMonitorLGCtxCreate(PetscObjectComm((PetscObject)ts),NULL,NULL,PETSC_DECIDE,PETSC_DECIDE,400,300,howoften,&ctx);
225:     TSMonitorSet(ts,TSMonitorLGTimeStep,ctx,(PetscErrorCode (*)(void**))TSMonitorLGCtxDestroy);
226:     ctx->semilogy = PETSC_TRUE;
227:   }

229:   PetscOptionsName("-ts_monitor_lg_snes_iterations","Monitor number nonlinear iterations for each timestep graphically","TSMonitorLGSNESIterations",&opt);
230:   if (opt) {
231:     TSMonitorLGCtx ctx;
232:     PetscInt       howoften = 1;

234:     PetscOptionsInt("-ts_monitor_lg_snes_iterations","Monitor number nonlinear iterations for each timestep graphically","TSMonitorLGSNESIterations",howoften,&howoften,NULL);
235:     TSMonitorLGCtxCreate(PetscObjectComm((PetscObject)ts),NULL,NULL,PETSC_DECIDE,PETSC_DECIDE,400,300,howoften,&ctx);
236:     TSMonitorSet(ts,TSMonitorLGSNESIterations,ctx,(PetscErrorCode (*)(void**))TSMonitorLGCtxDestroy);
237:   }
238:   PetscOptionsName("-ts_monitor_lg_ksp_iterations","Monitor number nonlinear iterations for each timestep graphically","TSMonitorLGKSPIterations",&opt);
239:   if (opt) {
240:     TSMonitorLGCtx ctx;
241:     PetscInt       howoften = 1;

243:     PetscOptionsInt("-ts_monitor_lg_ksp_iterations","Monitor number nonlinear iterations for each timestep graphically","TSMonitorLGKSPIterations",howoften,&howoften,NULL);
244:     TSMonitorLGCtxCreate(PetscObjectComm((PetscObject)ts),NULL,NULL,PETSC_DECIDE,PETSC_DECIDE,400,300,howoften,&ctx);
245:     TSMonitorSet(ts,TSMonitorLGKSPIterations,ctx,(PetscErrorCode (*)(void**))TSMonitorLGCtxDestroy);
246:   }
247:   PetscOptionsName("-ts_monitor_sp_eig","Monitor eigenvalues of linearized operator graphically","TSMonitorSPEig",&opt);
248:   if (opt) {
249:     TSMonitorSPEigCtx ctx;
250:     PetscInt          howoften = 1;

252:     PetscOptionsInt("-ts_monitor_sp_eig","Monitor eigenvalues of linearized operator graphically","TSMonitorSPEig",howoften,&howoften,NULL);
253:     TSMonitorSPEigCtxCreate(PETSC_COMM_SELF,0,0,PETSC_DECIDE,PETSC_DECIDE,300,300,howoften,&ctx);
254:     TSMonitorSet(ts,TSMonitorSPEig,ctx,(PetscErrorCode (*)(void**))TSMonitorSPEigCtxDestroy);
255:   }
256:   PetscOptionsName("-ts_monitor_sp_swarm","Display particle phase from the DMSwarm","TSMonitorSPSwarm",&opt);
257:   if (opt) {
258:     TSMonitorSPCtx  ctx;
259:     PetscInt        howoften = 1;
260:     PetscOptionsInt("-ts_monitor_sp_swarm","Display particles phase from the DMSwarm","TSMonitorSPSwarm",howoften,&howoften,NULL);
261:     TSMonitorSPCtxCreate(PETSC_COMM_SELF, NULL, NULL, PETSC_DECIDE, PETSC_DECIDE, 300, 300, howoften, &ctx);
262:     TSMonitorSet(ts, TSMonitorSPSwarmSolution, ctx, (PetscErrorCode (*)(void**))TSMonitorSPCtxDestroy);
263:   }
264:   opt  = PETSC_FALSE;
265:   PetscOptionsName("-ts_monitor_draw_solution","Monitor solution graphically","TSMonitorDrawSolution",&opt);
266:   if (opt) {
267:     TSMonitorDrawCtx ctx;
268:     PetscInt         howoften = 1;

270:     PetscOptionsInt("-ts_monitor_draw_solution","Monitor solution graphically","TSMonitorDrawSolution",howoften,&howoften,NULL);
271:     TSMonitorDrawCtxCreate(PetscObjectComm((PetscObject)ts),0,"Computed Solution",PETSC_DECIDE,PETSC_DECIDE,300,300,howoften,&ctx);
272:     TSMonitorSet(ts,TSMonitorDrawSolution,ctx,(PetscErrorCode (*)(void**))TSMonitorDrawCtxDestroy);
273:   }
274:   opt  = PETSC_FALSE;
275:   PetscOptionsName("-ts_monitor_draw_solution_phase","Monitor solution graphically","TSMonitorDrawSolutionPhase",&opt);
276:   if (opt) {
277:     TSMonitorDrawCtx ctx;
278:     PetscReal        bounds[4];
279:     PetscInt         n = 4;
280:     PetscDraw        draw;
281:     PetscDrawAxis    axis;

283:     PetscOptionsRealArray("-ts_monitor_draw_solution_phase","Monitor solution graphically","TSMonitorDrawSolutionPhase",bounds,&n,NULL);
284:     if (n != 4) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_ARG_WRONG,"Must provide bounding box of phase field");
285:     TSMonitorDrawCtxCreate(PetscObjectComm((PetscObject)ts),0,0,PETSC_DECIDE,PETSC_DECIDE,300,300,1,&ctx);
286:     PetscViewerDrawGetDraw(ctx->viewer,0,&draw);
287:     PetscViewerDrawGetDrawAxis(ctx->viewer,0,&axis);
288:     PetscDrawAxisSetLimits(axis,bounds[0],bounds[2],bounds[1],bounds[3]);
289:     PetscDrawAxisSetLabels(axis,"Phase Diagram","Variable 1","Variable 2");
290:     TSMonitorSet(ts,TSMonitorDrawSolutionPhase,ctx,(PetscErrorCode (*)(void**))TSMonitorDrawCtxDestroy);
291:   }
292:   opt  = PETSC_FALSE;
293:   PetscOptionsName("-ts_monitor_draw_error","Monitor error graphically","TSMonitorDrawError",&opt);
294:   if (opt) {
295:     TSMonitorDrawCtx ctx;
296:     PetscInt         howoften = 1;

298:     PetscOptionsInt("-ts_monitor_draw_error","Monitor error graphically","TSMonitorDrawError",howoften,&howoften,NULL);
299:     TSMonitorDrawCtxCreate(PetscObjectComm((PetscObject)ts),0,"Error",PETSC_DECIDE,PETSC_DECIDE,300,300,howoften,&ctx);
300:     TSMonitorSet(ts,TSMonitorDrawError,ctx,(PetscErrorCode (*)(void**))TSMonitorDrawCtxDestroy);
301:   }
302:   opt  = PETSC_FALSE;
303:   PetscOptionsName("-ts_monitor_draw_solution_function","Monitor solution provided by TSMonitorSetSolutionFunction() graphically","TSMonitorDrawSolutionFunction",&opt);
304:   if (opt) {
305:     TSMonitorDrawCtx ctx;
306:     PetscInt         howoften = 1;

308:     PetscOptionsInt("-ts_monitor_draw_solution_function","Monitor solution provided by TSMonitorSetSolutionFunction() graphically","TSMonitorDrawSolutionFunction",howoften,&howoften,NULL);
309:     TSMonitorDrawCtxCreate(PetscObjectComm((PetscObject)ts),0,"Solution provided by user function",PETSC_DECIDE,PETSC_DECIDE,300,300,howoften,&ctx);
310:     TSMonitorSet(ts,TSMonitorDrawSolutionFunction,ctx,(PetscErrorCode (*)(void**))TSMonitorDrawCtxDestroy);
311:   }

313:   opt  = PETSC_FALSE;
314:   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);
315:   if (flg) {
316:     const char *ptr,*ptr2;
317:     char       *filetemplate;
318:     if (!monfilename[0]) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_USER,"-ts_monitor_solution_vtk requires a file template, e.g. filename-%%03D.vts");
319:     /* Do some cursory validation of the input. */
320:     PetscStrstr(monfilename,"%",(char**)&ptr);
321:     if (!ptr) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_USER,"-ts_monitor_solution_vtk requires a file template, e.g. filename-%%03D.vts");
322:     for (ptr++; ptr && *ptr; ptr++) {
323:       PetscStrchr("DdiouxX",*ptr,(char**)&ptr2);
324:       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");
325:       if (ptr2) break;
326:     }
327:     PetscStrallocpy(monfilename,&filetemplate);
328:     TSMonitorSet(ts,TSMonitorSolutionVTK,filetemplate,(PetscErrorCode (*)(void**))TSMonitorSolutionVTKDestroy);
329:   }

331:   PetscOptionsString("-ts_monitor_dmda_ray","Display a ray of the solution","None","y=0",dir,16,&flg);
332:   if (flg) {
333:     TSMonitorDMDARayCtx *rayctx;
334:     int                  ray = 0;
335:     DMDirection          ddir;
336:     DM                   da;
337:     PetscMPIInt          rank;

339:     if (dir[1] != '=') SETERRQ1(PetscObjectComm((PetscObject)ts),PETSC_ERR_ARG_WRONG,"Unknown ray %s",dir);
340:     if (dir[0] == 'x') ddir = DM_X;
341:     else if (dir[0] == 'y') ddir = DM_Y;
342:     else SETERRQ1(PetscObjectComm((PetscObject)ts),PETSC_ERR_ARG_WRONG,"Unknown ray %s",dir);
343:     sscanf(dir+2,"%d",&ray);

345:     PetscInfo2(((PetscObject)ts),"Displaying DMDA ray %c = %d\n",dir[0],ray);
346:     PetscNew(&rayctx);
347:     TSGetDM(ts,&da);
348:     DMDAGetRay(da,ddir,ray,&rayctx->ray,&rayctx->scatter);
349:     MPI_Comm_rank(PetscObjectComm((PetscObject)ts),&rank);
350:     if (!rank) {
351:       PetscViewerDrawOpen(PETSC_COMM_SELF,0,0,0,0,600,300,&rayctx->viewer);
352:     }
353:     rayctx->lgctx = NULL;
354:     TSMonitorSet(ts,TSMonitorDMDARay,rayctx,TSMonitorDMDARayDestroy);
355:   }
356:   PetscOptionsString("-ts_monitor_lg_dmda_ray","Display a ray of the solution","None","x=0",dir,16,&flg);
357:   if (flg) {
358:     TSMonitorDMDARayCtx *rayctx;
359:     int                 ray = 0;
360:     DMDirection         ddir;
361:     DM                  da;
362:     PetscInt            howoften = 1;

364:     if (dir[1] != '=') SETERRQ1(PetscObjectComm((PetscObject) ts), PETSC_ERR_ARG_WRONG, "Malformed ray %s", dir);
365:     if      (dir[0] == 'x') ddir = DM_X;
366:     else if (dir[0] == 'y') ddir = DM_Y;
367:     else SETERRQ1(PetscObjectComm((PetscObject) ts), PETSC_ERR_ARG_WRONG, "Unknown ray direction %s", dir);
368:     sscanf(dir+2, "%d", &ray);

370:     PetscInfo2(((PetscObject) ts),"Displaying LG DMDA ray %c = %d\n", dir[0], ray);
371:     PetscNew(&rayctx);
372:     TSGetDM(ts, &da);
373:     DMDAGetRay(da, ddir, ray, &rayctx->ray, &rayctx->scatter);
374:     TSMonitorLGCtxCreate(PETSC_COMM_SELF,0,0,PETSC_DECIDE,PETSC_DECIDE,600,400,howoften,&rayctx->lgctx);
375:     TSMonitorSet(ts, TSMonitorLGDMDARay, rayctx, TSMonitorDMDARayDestroy);
376:   }

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

382:     TSMonitorEnvelopeCtxCreate(ts,&ctx);
383:     TSMonitorSet(ts,TSMonitorEnvelope,ctx,(PetscErrorCode (*)(void**))TSMonitorEnvelopeCtxDestroy);
384:   }

386:   flg  = PETSC_FALSE;
387:   PetscOptionsBool("-ts_fd_color", "Use finite differences with coloring to compute IJacobian", "TSComputeJacobianDefaultColor", flg, &flg, NULL);
388:   if (flg) {
389:     DM   dm;
390:     DMTS tdm;

392:     TSGetDM(ts, &dm);
393:     DMGetDMTS(dm, &tdm);
394:     tdm->ijacobianctx = NULL;
395:     TSSetIJacobian(ts, NULL, NULL, TSComputeIJacobianDefaultColor, 0);
396:     PetscInfo(ts, "Setting default finite difference coloring Jacobian matrix\n");
397:   }

399:   /* Handle specific TS options */
400:   if (ts->ops->setfromoptions) {
401:     (*ts->ops->setfromoptions)(PetscOptionsObject,ts);
402:   }

404:   /* Handle TSAdapt options */
405:   TSGetAdapt(ts,&ts->adapt);
406:   TSAdaptSetDefaultType(ts->adapt,ts->default_adapt_type);
407:   TSAdaptSetFromOptions(PetscOptionsObject,ts->adapt);

409:   /* TS trajectory must be set after TS, since it may use some TS options above */
410:   tflg = ts->trajectory ? PETSC_TRUE : PETSC_FALSE;
411:   PetscOptionsBool("-ts_save_trajectory","Save the solution at each timestep","TSSetSaveTrajectory",tflg,&tflg,NULL);
412:   if (tflg) {
413:     TSSetSaveTrajectory(ts);
414:   }

416:   TSAdjointSetFromOptions(PetscOptionsObject,ts);

418:   /* process any options handlers added with PetscObjectAddOptionsHandler() */
419:   PetscObjectProcessOptionsHandlers(PetscOptionsObject,(PetscObject)ts);
420:   PetscOptionsEnd();

422:   if (ts->trajectory) {
423:     TSTrajectorySetFromOptions(ts->trajectory,ts);
424:   }

426:   /* why do we have to do this here and not during TSSetUp? */
427:   TSGetSNES(ts,&ts->snes);
428:   if (ts->problem_type == TS_LINEAR) {
429:     PetscObjectTypeCompareAny((PetscObject)ts->snes,&flg,SNESKSPONLY,SNESKSPTRANSPOSEONLY,"");
430:     if (!flg) { SNESSetType(ts->snes,SNESKSPONLY); }
431:   }
432:   SNESSetFromOptions(ts->snes);
433:   return(0);
434: }

436: /*@
437:    TSGetTrajectory - Gets the trajectory from a TS if it exists

439:    Collective on TS

441:    Input Parameters:
442: .  ts - the TS context obtained from TSCreate()

444:    Output Parameters;
445: .  tr - the TSTrajectory object, if it exists

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

449:    Level: advanced

451: .seealso: TSGetTrajectory(), TSAdjointSolve(), TSTrajectory, TSTrajectoryCreate()

453: @*/
454: PetscErrorCode  TSGetTrajectory(TS ts,TSTrajectory *tr)
455: {
458:   *tr = ts->trajectory;
459:   return(0);
460: }

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

465:    Collective on TS

467:    Input Parameters:
468: .  ts - the TS context obtained from TSCreate()

470:    Options Database:
471: +  -ts_save_trajectory - saves the trajectory to a file
472: -  -ts_trajectory_type type

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

476:     The TSTRAJECTORYVISUALIZATION files can be loaded into Python with $PETSC_DIR/lib/petsc/bin/PetscBinaryIOTrajectory.py and
477:    MATLAB with $PETSC_DIR/share/petsc/matlab/PetscReadBinaryTrajectory.m

479:    Level: intermediate

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

483: @*/
484: PetscErrorCode  TSSetSaveTrajectory(TS ts)
485: {

490:   if (!ts->trajectory) {
491:     TSTrajectoryCreate(PetscObjectComm((PetscObject)ts),&ts->trajectory);
492:   }
493:   return(0);
494: }

496: /*@
497:    TSResetTrajectory - Destroys and recreates the internal TSTrajectory object

499:    Collective on TS

501:    Input Parameters:
502: .  ts - the TS context obtained from TSCreate()

504:    Level: intermediate

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

508: @*/
509: PetscErrorCode  TSResetTrajectory(TS ts)
510: {

515:   if (ts->trajectory) {
516:     TSTrajectoryDestroy(&ts->trajectory);
517:     TSTrajectoryCreate(PetscObjectComm((PetscObject)ts),&ts->trajectory);
518:   }
519:   return(0);
520: }

522: /*@
523:    TSComputeRHSJacobian - Computes the Jacobian matrix that has been
524:       set with TSSetRHSJacobian().

526:    Collective on TS

528:    Input Parameters:
529: +  ts - the TS context
530: .  t - current timestep
531: -  U - input vector

533:    Output Parameters:
534: +  A - Jacobian matrix
535: .  B - optional preconditioning matrix
536: -  flag - flag indicating matrix structure

538:    Notes:
539:    Most users should not need to explicitly call this routine, as it
540:    is used internally within the nonlinear solvers.

542:    See KSPSetOperators() for important information about setting the
543:    flag parameter.

545:    Level: developer

547: .seealso:  TSSetRHSJacobian(), KSPSetOperators()
548: @*/
549: PetscErrorCode  TSComputeRHSJacobian(TS ts,PetscReal t,Vec U,Mat A,Mat B)
550: {
551:   PetscErrorCode   ierr;
552:   PetscObjectState Ustate;
553:   PetscObjectId    Uid;
554:   DM               dm;
555:   DMTS             tsdm;
556:   TSRHSJacobian    rhsjacobianfunc;
557:   void             *ctx;
558:   TSIJacobian      ijacobianfunc;
559:   TSRHSFunction    rhsfunction;

565:   TSGetDM(ts,&dm);
566:   DMGetDMTS(dm,&tsdm);
567:   DMTSGetRHSJacobian(dm,&rhsjacobianfunc,&ctx);
568:   DMTSGetIJacobian(dm,&ijacobianfunc,NULL);
569:   DMTSGetRHSFunction(dm,&rhsfunction,&ctx);
570:   PetscObjectStateGet((PetscObject)U,&Ustate);
571:   PetscObjectGetId((PetscObject)U,&Uid);

573:   if (ts->rhsjacobian.time == t && (ts->problem_type == TS_LINEAR || (ts->rhsjacobian.Xid == Uid && ts->rhsjacobian.Xstate == Ustate)) && (rhsfunction != TSComputeRHSFunctionLinear)) {
574:     /* restore back RHS Jacobian matrices if they have been shifted/scaled */
575:     if (A == ts->Arhs) {
576:       if (ts->rhsjacobian.shift != 0) {
577:         MatShift(A,-ts->rhsjacobian.shift);
578:       }
579:       if (ts->rhsjacobian.scale != 1.) {
580:         MatScale(A,1./ts->rhsjacobian.scale);
581:       }
582:     }
583:     if (B && B == ts->Brhs && A != B) {
584:       if (ts->rhsjacobian.shift != 0) {
585:         MatShift(B,-ts->rhsjacobian.shift);
586:       }
587:       if (ts->rhsjacobian.scale != 1.) {
588:         MatScale(B,1./ts->rhsjacobian.scale);
589:       }
590:     }
591:     ts->rhsjacobian.shift = 0;
592:     ts->rhsjacobian.scale = 1.;
593:     return(0);
594:   }

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

598:   if (ts->rhsjacobian.reuse) {
599:     if (A == ts->Arhs) {
600:       /* MatScale has a short path for this case.
601:          However, this code path is taken the first time TSComputeRHSJacobian is called
602:          and the matrices have not assembled yet */
603:       if (ts->rhsjacobian.shift != 0) {
604:         MatShift(A,-ts->rhsjacobian.shift);
605:       }
606:       if (ts->rhsjacobian.scale != 1.) {
607:         MatScale(A,1./ts->rhsjacobian.scale);
608:       }
609:     }
610:     if (B && B == ts->Brhs && A != B) {
611:       if (ts->rhsjacobian.shift != 0) {
612:         MatShift(B,-ts->rhsjacobian.shift);
613:       }
614:       if (ts->rhsjacobian.scale != 1.) {
615:         MatScale(B,1./ts->rhsjacobian.scale);
616:       }
617:     }
618:   }

620:   if (rhsjacobianfunc) {
621:     PetscBool missing;
622:     PetscLogEventBegin(TS_JacobianEval,ts,U,A,B);
623:     PetscStackPush("TS user Jacobian function");
624:     (*rhsjacobianfunc)(ts,t,U,A,B,ctx);
625:     PetscStackPop;
626:     PetscLogEventEnd(TS_JacobianEval,ts,U,A,B);
627:     if (A) {
628:       MatMissingDiagonal(A,&missing,NULL);
629:       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");
630:     }
631:     if (B && B != A) {
632:       MatMissingDiagonal(B,&missing,NULL);
633:       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");
634:     }
635:   } else {
636:     MatZeroEntries(A);
637:     if (B && A != B) {MatZeroEntries(B);}
638:   }
639:   ts->rhsjacobian.time  = t;
640:   ts->rhsjacobian.shift = 0;
641:   ts->rhsjacobian.scale = 1.;
642:   PetscObjectGetId((PetscObject)U,&ts->rhsjacobian.Xid);
643:   PetscObjectStateGet((PetscObject)U,&ts->rhsjacobian.Xstate);
644:   return(0);
645: }

647: /*@
648:    TSComputeRHSFunction - Evaluates the right-hand-side function.

650:    Collective on TS

652:    Input Parameters:
653: +  ts - the TS context
654: .  t - current time
655: -  U - state vector

657:    Output Parameter:
658: .  y - right hand side

660:    Note:
661:    Most users should not need to explicitly call this routine, as it
662:    is used internally within the nonlinear solvers.

664:    Level: developer

666: .seealso: TSSetRHSFunction(), TSComputeIFunction()
667: @*/
668: PetscErrorCode TSComputeRHSFunction(TS ts,PetscReal t,Vec U,Vec y)
669: {
671:   TSRHSFunction  rhsfunction;
672:   TSIFunction    ifunction;
673:   void           *ctx;
674:   DM             dm;

680:   TSGetDM(ts,&dm);
681:   DMTSGetRHSFunction(dm,&rhsfunction,&ctx);
682:   DMTSGetIFunction(dm,&ifunction,NULL);

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

686:   PetscLogEventBegin(TS_FunctionEval,ts,U,y,0);
687:   if (rhsfunction) {
688:     PetscStackPush("TS user right-hand-side function");
689:     (*rhsfunction)(ts,t,U,y,ctx);
690:     PetscStackPop;
691:   } else {
692:     VecZeroEntries(y);
693:   }

695:   PetscLogEventEnd(TS_FunctionEval,ts,U,y,0);
696:   return(0);
697: }

699: /*@
700:    TSComputeSolutionFunction - Evaluates the solution function.

702:    Collective on TS

704:    Input Parameters:
705: +  ts - the TS context
706: -  t - current time

708:    Output Parameter:
709: .  U - the solution

711:    Note:
712:    Most users should not need to explicitly call this routine, as it
713:    is used internally within the nonlinear solvers.

715:    Level: developer

717: .seealso: TSSetSolutionFunction(), TSSetRHSFunction(), TSComputeIFunction()
718: @*/
719: PetscErrorCode TSComputeSolutionFunction(TS ts,PetscReal t,Vec U)
720: {
721:   PetscErrorCode     ierr;
722:   TSSolutionFunction solutionfunction;
723:   void               *ctx;
724:   DM                 dm;

729:   TSGetDM(ts,&dm);
730:   DMTSGetSolutionFunction(dm,&solutionfunction,&ctx);

732:   if (solutionfunction) {
733:     PetscStackPush("TS user solution function");
734:     (*solutionfunction)(ts,t,U,ctx);
735:     PetscStackPop;
736:   }
737:   return(0);
738: }
739: /*@
740:    TSComputeForcingFunction - Evaluates the forcing function.

742:    Collective on TS

744:    Input Parameters:
745: +  ts - the TS context
746: -  t - current time

748:    Output Parameter:
749: .  U - the function value

751:    Note:
752:    Most users should not need to explicitly call this routine, as it
753:    is used internally within the nonlinear solvers.

755:    Level: developer

757: .seealso: TSSetSolutionFunction(), TSSetRHSFunction(), TSComputeIFunction()
758: @*/
759: PetscErrorCode TSComputeForcingFunction(TS ts,PetscReal t,Vec U)
760: {
761:   PetscErrorCode     ierr, (*forcing)(TS,PetscReal,Vec,void*);
762:   void               *ctx;
763:   DM                 dm;

768:   TSGetDM(ts,&dm);
769:   DMTSGetForcingFunction(dm,&forcing,&ctx);

771:   if (forcing) {
772:     PetscStackPush("TS user forcing function");
773:     (*forcing)(ts,t,U,ctx);
774:     PetscStackPop;
775:   }
776:   return(0);
777: }

779: static PetscErrorCode TSGetRHSVec_Private(TS ts,Vec *Frhs)
780: {
781:   Vec            F;

785:   *Frhs = NULL;
786:   TSGetIFunction(ts,&F,NULL,NULL);
787:   if (!ts->Frhs) {
788:     VecDuplicate(F,&ts->Frhs);
789:   }
790:   *Frhs = ts->Frhs;
791:   return(0);
792: }

794: PetscErrorCode TSGetRHSMats_Private(TS ts,Mat *Arhs,Mat *Brhs)
795: {
796:   Mat            A,B;
798:   TSIJacobian    ijacobian;

801:   if (Arhs) *Arhs = NULL;
802:   if (Brhs) *Brhs = NULL;
803:   TSGetIJacobian(ts,&A,&B,&ijacobian,NULL);
804:   if (Arhs) {
805:     if (!ts->Arhs) {
806:       if (ijacobian) {
807:         MatDuplicate(A,MAT_DO_NOT_COPY_VALUES,&ts->Arhs);
808:       } else {
809:         ts->Arhs = A;
810:         PetscObjectReference((PetscObject)A);
811:       }
812:     } else {
813:       PetscBool flg;
814:       SNESGetUseMatrixFree(ts->snes,NULL,&flg);
815:       /* Handle case where user provided only RHSJacobian and used -snes_mf_operator */
816:       if (flg && !ijacobian && ts->Arhs == ts->Brhs){
817:         PetscObjectDereference((PetscObject)ts->Arhs);
818:         ts->Arhs = A;
819:         PetscObjectReference((PetscObject)A);
820:       }
821:     }
822:     *Arhs = ts->Arhs;
823:   }
824:   if (Brhs) {
825:     if (!ts->Brhs) {
826:       if (A != B) {
827:         if (ijacobian) {
828:           MatDuplicate(B,MAT_DO_NOT_COPY_VALUES,&ts->Brhs);
829:         } else {
830:           ts->Brhs = B;
831:           PetscObjectReference((PetscObject)B);
832:         }
833:       } else {
834:         PetscObjectReference((PetscObject)ts->Arhs);
835:         ts->Brhs = ts->Arhs;
836:       }
837:     }
838:     *Brhs = ts->Brhs;
839:   }
840:   return(0);
841: }

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

846:    Collective on TS

848:    Input Parameters:
849: +  ts - the TS context
850: .  t - current time
851: .  U - state vector
852: .  Udot - time derivative of state vector
853: -  imex - flag indicates if the method is IMEX so that the RHSFunction should be kept separate

855:    Output Parameter:
856: .  Y - right hand side

858:    Note:
859:    Most users should not need to explicitly call this routine, as it
860:    is used internally within the nonlinear solvers.

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

865:    Level: developer

867: .seealso: TSSetIFunction(), TSComputeRHSFunction()
868: @*/
869: PetscErrorCode TSComputeIFunction(TS ts,PetscReal t,Vec U,Vec Udot,Vec Y,PetscBool imex)
870: {
872:   TSIFunction    ifunction;
873:   TSRHSFunction  rhsfunction;
874:   void           *ctx;
875:   DM             dm;


883:   TSGetDM(ts,&dm);
884:   DMTSGetIFunction(dm,&ifunction,&ctx);
885:   DMTSGetRHSFunction(dm,&rhsfunction,NULL);

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

889:   PetscLogEventBegin(TS_FunctionEval,ts,U,Udot,Y);
890:   if (ifunction) {
891:     PetscStackPush("TS user implicit function");
892:     (*ifunction)(ts,t,U,Udot,Y,ctx);
893:     PetscStackPop;
894:   }
895:   if (imex) {
896:     if (!ifunction) {
897:       VecCopy(Udot,Y);
898:     }
899:   } else if (rhsfunction) {
900:     if (ifunction) {
901:       Vec Frhs;
902:       TSGetRHSVec_Private(ts,&Frhs);
903:       TSComputeRHSFunction(ts,t,U,Frhs);
904:       VecAXPY(Y,-1,Frhs);
905:     } else {
906:       TSComputeRHSFunction(ts,t,U,Y);
907:       VecAYPX(Y,-1,Udot);
908:     }
909:   }
910:   PetscLogEventEnd(TS_FunctionEval,ts,U,Udot,Y);
911:   return(0);
912: }

914: /*@
915:    TSComputeIJacobian - Evaluates the Jacobian of the DAE

917:    Collective on TS

919:    Input
920:       Input Parameters:
921: +  ts - the TS context
922: .  t - current timestep
923: .  U - state vector
924: .  Udot - time derivative of state vector
925: .  shift - shift to apply, see note below
926: -  imex - flag indicates if the method is IMEX so that the RHSJacobian should be kept separate

928:    Output Parameters:
929: +  A - Jacobian matrix
930: -  B - matrix from which the preconditioner is constructed; often the same as A

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

935:    dF/dU + shift*dF/dUdot

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

940:    Level: developer

942: .seealso:  TSSetIJacobian()
943: @*/
944: PetscErrorCode TSComputeIJacobian(TS ts,PetscReal t,Vec U,Vec Udot,PetscReal shift,Mat A,Mat B,PetscBool imex)
945: {
947:   TSIJacobian    ijacobian;
948:   TSRHSJacobian  rhsjacobian;
949:   DM             dm;
950:   void           *ctx;


961:   TSGetDM(ts,&dm);
962:   DMTSGetIJacobian(dm,&ijacobian,&ctx);
963:   DMTSGetRHSJacobian(dm,&rhsjacobian,NULL);

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

967:   PetscLogEventBegin(TS_JacobianEval,ts,U,A,B);
968:   if (ijacobian) {
969:     PetscBool missing;
970:     PetscStackPush("TS user implicit Jacobian");
971:     (*ijacobian)(ts,t,U,Udot,shift,A,B,ctx);
972:     PetscStackPop;
973:     MatMissingDiagonal(A,&missing,NULL);
974:     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");
975:     if (B != A) {
976:       MatMissingDiagonal(B,&missing,NULL);
977:       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");
978:     }
979:   }
980:   if (imex) {
981:     if (!ijacobian) {  /* system was written as Udot = G(t,U) */
982:       PetscBool assembled;
983:       if (rhsjacobian) {
984:         Mat Arhs = NULL;
985:         TSGetRHSMats_Private(ts,&Arhs,NULL);
986:         if (A == Arhs) {
987:           if (rhsjacobian == TSComputeRHSJacobianConstant) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"Unsupported operation! cannot use TSComputeRHSJacobianConstant");
988:           ts->rhsjacobian.time = PETSC_MIN_REAL;
989:         }
990:       }
991:       MatZeroEntries(A);
992:       MatAssembled(A,&assembled);
993:       if (!assembled) {
994:         MatAssemblyBegin(A,MAT_FINAL_ASSEMBLY);
995:         MatAssemblyEnd(A,MAT_FINAL_ASSEMBLY);
996:       }
997:       MatShift(A,shift);
998:       if (A != B) {
999:         MatZeroEntries(B);
1000:         MatAssembled(B,&assembled);
1001:         if (!assembled) {
1002:           MatAssemblyBegin(B,MAT_FINAL_ASSEMBLY);
1003:           MatAssemblyEnd(B,MAT_FINAL_ASSEMBLY);
1004:         }
1005:         MatShift(B,shift);
1006:       }
1007:     }
1008:   } else {
1009:     Mat Arhs = NULL,Brhs = NULL;
1010:     if (rhsjacobian) {
1011:       TSGetRHSMats_Private(ts,&Arhs,&Brhs);
1012:       TSComputeRHSJacobian(ts,t,U,Arhs,Brhs);
1013:     }
1014:     if (Arhs == A) {           /* No IJacobian, so we only have the RHS matrix */
1015:       PetscBool flg;
1016:       ts->rhsjacobian.scale = -1;
1017:       ts->rhsjacobian.shift = shift;
1018:       SNESGetUseMatrixFree(ts->snes,NULL,&flg);
1019:       /* since -snes_mf_operator uses the full SNES function it does not need to be shifted or scaled here */
1020:       if (!flg) {
1021:         MatScale(A,-1);
1022:         MatShift(A,shift);
1023:       }
1024:       if (A != B) {
1025:         MatScale(B,-1);
1026:         MatShift(B,shift);
1027:       }
1028:     } else if (Arhs) {          /* Both IJacobian and RHSJacobian */
1029:       MatStructure axpy = DIFFERENT_NONZERO_PATTERN;
1030:       if (!ijacobian) {         /* No IJacobian provided, but we have a separate RHS matrix */
1031:         MatZeroEntries(A);
1032:         MatShift(A,shift);
1033:         if (A != B) {
1034:           MatZeroEntries(B);
1035:           MatShift(B,shift);
1036:         }
1037:       }
1038:       MatAXPY(A,-1,Arhs,axpy);
1039:       if (A != B) {
1040:         MatAXPY(B,-1,Brhs,axpy);
1041:       }
1042:     }
1043:   }
1044:   PetscLogEventEnd(TS_JacobianEval,ts,U,A,B);
1045:   return(0);
1046: }

1048: /*@C
1049:     TSSetRHSFunction - Sets the routine for evaluating the function,
1050:     where U_t = G(t,u).

1052:     Logically Collective on TS

1054:     Input Parameters:
1055: +   ts - the TS context obtained from TSCreate()
1056: .   r - vector to put the computed right hand side (or NULL to have it created)
1057: .   f - routine for evaluating the right-hand-side function
1058: -   ctx - [optional] user-defined context for private data for the
1059:           function evaluation routine (may be NULL)

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

1064: +   t - current timestep
1065: .   u - input vector
1066: .   F - function vector
1067: -   ctx - [optional] user-defined function context

1069:     Level: beginner

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

1074: .seealso: TSSetRHSJacobian(), TSSetIJacobian(), TSSetIFunction()
1075: @*/
1076: PetscErrorCode  TSSetRHSFunction(TS ts,Vec r,PetscErrorCode (*f)(TS,PetscReal,Vec,Vec,void*),void *ctx)
1077: {
1079:   SNES           snes;
1080:   Vec            ralloc = NULL;
1081:   DM             dm;


1087:   TSGetDM(ts,&dm);
1088:   DMTSSetRHSFunction(dm,f,ctx);
1089:   TSGetSNES(ts,&snes);
1090:   if (!r && !ts->dm && ts->vec_sol) {
1091:     VecDuplicate(ts->vec_sol,&ralloc);
1092:     r = ralloc;
1093:   }
1094:   SNESSetFunction(snes,r,SNESTSFormFunction,ts);
1095:   VecDestroy(&ralloc);
1096:   return(0);
1097: }

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

1102:     Logically Collective on TS

1104:     Input Parameters:
1105: +   ts - the TS context obtained from TSCreate()
1106: .   f - routine for evaluating the solution
1107: -   ctx - [optional] user-defined context for private data for the
1108:           function evaluation routine (may be NULL)

1110:     Calling sequence of func:
1111: $     PetscErrorCode func (TS ts,PetscReal t,Vec u,void *ctx);

1113: +   t - current timestep
1114: .   u - output vector
1115: -   ctx - [optional] user-defined function context

1117:     Options Database:
1118: +  -ts_monitor_lg_error - create a graphical monitor of error history, requires user to have provided TSSetSolutionFunction()
1119: -  -ts_monitor_draw_error - Monitor error graphically, requires user to have provided TSSetSolutionFunction()

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

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

1128:     Level: beginner

1130: .seealso: TSSetRHSJacobian(), TSSetIJacobian(), TSComputeSolutionFunction(), TSSetForcingFunction(), TSSetSolution(), TSGetSolution(), TSMonitorLGError(), TSMonitorDrawError()
1131: @*/
1132: PetscErrorCode  TSSetSolutionFunction(TS ts,PetscErrorCode (*f)(TS,PetscReal,Vec,void*),void *ctx)
1133: {
1135:   DM             dm;

1139:   TSGetDM(ts,&dm);
1140:   DMTSSetSolutionFunction(dm,f,ctx);
1141:   return(0);
1142: }

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

1147:     Logically Collective on TS

1149:     Input Parameters:
1150: +   ts - the TS context obtained from TSCreate()
1151: .   func - routine for evaluating the forcing function
1152: -   ctx - [optional] user-defined context for private data for the
1153:           function evaluation routine (may be NULL)

1155:     Calling sequence of func:
1156: $     PetscErrorCode func (TS ts,PetscReal t,Vec f,void *ctx);

1158: +   t - current timestep
1159: .   f - output vector
1160: -   ctx - [optional] user-defined function context

1162:     Notes:
1163:     This routine is useful for testing accuracy of time integration schemes when using the Method of Manufactured Solutions to
1164:     create closed-form solutions with a non-physical forcing term. It allows you to use the Method of Manufactored Solution without directly editing the
1165:     definition of the problem you are solving and hence possibly introducing bugs.

1167:     This replaces the ODE F(u,u_t,t) = 0 the TS is solving with F(u,u_t,t) - func(t) = 0

1169:     This forcing function does not depend on the solution to the equations, it can only depend on spatial location, time, and possibly parameters, the
1170:     parameters can be passed in the ctx variable.

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

1174:     Level: beginner

1176: .seealso: TSSetRHSJacobian(), TSSetIJacobian(), TSComputeSolutionFunction(), TSSetSolutionFunction()
1177: @*/
1178: PetscErrorCode  TSSetForcingFunction(TS ts,TSForcingFunction func,void *ctx)
1179: {
1181:   DM             dm;

1185:   TSGetDM(ts,&dm);
1186:   DMTSSetForcingFunction(dm,func,ctx);
1187:   return(0);
1188: }

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

1194:    Logically Collective on TS

1196:    Input Parameters:
1197: +  ts  - the TS context obtained from TSCreate()
1198: .  Amat - (approximate) Jacobian matrix
1199: .  Pmat - matrix from which preconditioner is to be constructed (usually the same as Amat)
1200: .  f   - the Jacobian evaluation routine
1201: -  ctx - [optional] user-defined context for private data for the
1202:          Jacobian evaluation routine (may be NULL)

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

1207: +  t - current timestep
1208: .  u - input vector
1209: .  Amat - (approximate) Jacobian matrix
1210: .  Pmat - matrix from which preconditioner is to be constructed (usually the same as Amat)
1211: -  ctx - [optional] user-defined context for matrix evaluation routine

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

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

1219:    Level: beginner

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

1223: @*/
1224: PetscErrorCode  TSSetRHSJacobian(TS ts,Mat Amat,Mat Pmat,TSRHSJacobian f,void *ctx)
1225: {
1227:   SNES           snes;
1228:   DM             dm;
1229:   TSIJacobian    ijacobian;


1238:   TSGetDM(ts,&dm);
1239:   DMTSSetRHSJacobian(dm,f,ctx);
1240:   if (f == TSComputeRHSJacobianConstant) {
1241:     /* Handle this case automatically for the user; otherwise user should call themselves. */
1242:     TSRHSJacobianSetReuse(ts,PETSC_TRUE);
1243:   }
1244:   DMTSGetIJacobian(dm,&ijacobian,NULL);
1245:   TSGetSNES(ts,&snes);
1246:   if (!ijacobian) {
1247:     SNESSetJacobian(snes,Amat,Pmat,SNESTSFormJacobian,ts);
1248:   }
1249:   if (Amat) {
1250:     PetscObjectReference((PetscObject)Amat);
1251:     MatDestroy(&ts->Arhs);
1252:     ts->Arhs = Amat;
1253:   }
1254:   if (Pmat) {
1255:     PetscObjectReference((PetscObject)Pmat);
1256:     MatDestroy(&ts->Brhs);
1257:     ts->Brhs = Pmat;
1258:   }
1259:   return(0);
1260: }

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

1265:    Logically Collective on TS

1267:    Input Parameters:
1268: +  ts  - the TS context obtained from TSCreate()
1269: .  r   - vector to hold the residual (or NULL to have it created internally)
1270: .  f   - the function evaluation routine
1271: -  ctx - user-defined context for private data for the function evaluation routine (may be NULL)

1273:    Calling sequence of f:
1274: $     PetscErrorCode f(TS ts,PetscReal t,Vec u,Vec u_t,Vec F,ctx);

1276: +  t   - time at step/stage being solved
1277: .  u   - state vector
1278: .  u_t - time derivative of state vector
1279: .  F   - function vector
1280: -  ctx - [optional] user-defined context for matrix evaluation routine

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

1285:    Level: beginner

1287: .seealso: TSSetRHSJacobian(), TSSetRHSFunction(), TSSetIJacobian()
1288: @*/
1289: PetscErrorCode  TSSetIFunction(TS ts,Vec r,TSIFunction f,void *ctx)
1290: {
1292:   SNES           snes;
1293:   Vec            ralloc = NULL;
1294:   DM             dm;


1300:   TSGetDM(ts,&dm);
1301:   DMTSSetIFunction(dm,f,ctx);

1303:   TSGetSNES(ts,&snes);
1304:   if (!r && !ts->dm && ts->vec_sol) {
1305:     VecDuplicate(ts->vec_sol,&ralloc);
1306:     r  = ralloc;
1307:   }
1308:   SNESSetFunction(snes,r,SNESTSFormFunction,ts);
1309:   VecDestroy(&ralloc);
1310:   return(0);
1311: }

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

1316:    Not Collective

1318:    Input Parameter:
1319: .  ts - the TS context

1321:    Output Parameter:
1322: +  r - vector to hold residual (or NULL)
1323: .  func - the function to compute residual (or NULL)
1324: -  ctx - the function context (or NULL)

1326:    Level: advanced

1328: .seealso: TSSetIFunction(), SNESGetFunction()
1329: @*/
1330: PetscErrorCode TSGetIFunction(TS ts,Vec *r,TSIFunction *func,void **ctx)
1331: {
1333:   SNES           snes;
1334:   DM             dm;

1338:   TSGetSNES(ts,&snes);
1339:   SNESGetFunction(snes,r,NULL,NULL);
1340:   TSGetDM(ts,&dm);
1341:   DMTSGetIFunction(dm,func,ctx);
1342:   return(0);
1343: }

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

1348:    Not Collective

1350:    Input Parameter:
1351: .  ts - the TS context

1353:    Output Parameter:
1354: +  r - vector to hold computed right hand side (or NULL)
1355: .  func - the function to compute right hand side (or NULL)
1356: -  ctx - the function context (or NULL)

1358:    Level: advanced

1360: .seealso: TSSetRHSFunction(), SNESGetFunction()
1361: @*/
1362: PetscErrorCode TSGetRHSFunction(TS ts,Vec *r,TSRHSFunction *func,void **ctx)
1363: {
1365:   SNES           snes;
1366:   DM             dm;

1370:   TSGetSNES(ts,&snes);
1371:   SNESGetFunction(snes,r,NULL,NULL);
1372:   TSGetDM(ts,&dm);
1373:   DMTSGetRHSFunction(dm,func,ctx);
1374:   return(0);
1375: }

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

1381:    Logically Collective on TS

1383:    Input Parameters:
1384: +  ts  - the TS context obtained from TSCreate()
1385: .  Amat - (approximate) Jacobian matrix
1386: .  Pmat - matrix used to compute preconditioner (usually the same as Amat)
1387: .  f   - the Jacobian evaluation routine
1388: -  ctx - user-defined context for private data for the Jacobian evaluation routine (may be NULL)

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

1393: +  t    - time at step/stage being solved
1394: .  U    - state vector
1395: .  U_t  - time derivative of state vector
1396: .  a    - shift
1397: .  Amat - (approximate) Jacobian of F(t,U,W+a*U), equivalent to dF/dU + a*dF/dU_t
1398: .  Pmat - matrix used for constructing preconditioner, usually the same as Amat
1399: -  ctx  - [optional] user-defined context for matrix evaluation routine

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

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

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

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

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

1419:    Level: beginner

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

1423: @*/
1424: PetscErrorCode  TSSetIJacobian(TS ts,Mat Amat,Mat Pmat,TSIJacobian f,void *ctx)
1425: {
1427:   SNES           snes;
1428:   DM             dm;


1437:   TSGetDM(ts,&dm);
1438:   DMTSSetIJacobian(dm,f,ctx);

1440:   TSGetSNES(ts,&snes);
1441:   SNESSetJacobian(snes,Amat,Pmat,SNESTSFormJacobian,ts);
1442:   return(0);
1443: }

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

1451:    Logically Collective

1453:    Input Arguments:
1454: +  ts - TS context obtained from TSCreate()
1455: -  reuse - PETSC_TRUE if the RHS Jacobian

1457:    Level: intermediate

1459: .seealso: TSSetRHSJacobian(), TSComputeRHSJacobianConstant()
1460: @*/
1461: PetscErrorCode TSRHSJacobianSetReuse(TS ts,PetscBool reuse)
1462: {
1464:   ts->rhsjacobian.reuse = reuse;
1465:   return(0);
1466: }

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

1471:    Logically Collective on TS

1473:    Input Parameters:
1474: +  ts  - the TS context obtained from TSCreate()
1475: .  F   - vector to hold the residual (or NULL to have it created internally)
1476: .  fun - the function evaluation routine
1477: -  ctx - user-defined context for private data for the function evaluation routine (may be NULL)

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

1482: +  t    - time at step/stage being solved
1483: .  U    - state vector
1484: .  U_t  - time derivative of state vector
1485: .  U_tt - second time derivative of state vector
1486: .  F    - function vector
1487: -  ctx  - [optional] user-defined context for matrix evaluation routine (may be NULL)

1489:    Level: beginner

1491: .seealso: TSSetI2Jacobian()
1492: @*/
1493: PetscErrorCode TSSetI2Function(TS ts,Vec F,TSI2Function fun,void *ctx)
1494: {
1495:   DM             dm;

1501:   TSSetIFunction(ts,F,NULL,NULL);
1502:   TSGetDM(ts,&dm);
1503:   DMTSSetI2Function(dm,fun,ctx);
1504:   return(0);
1505: }

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

1510:   Not Collective

1512:   Input Parameter:
1513: . ts - the TS context

1515:   Output Parameter:
1516: + r - vector to hold residual (or NULL)
1517: . fun - the function to compute residual (or NULL)
1518: - ctx - the function context (or NULL)

1520:   Level: advanced

1522: .seealso: TSSetI2Function(), SNESGetFunction()
1523: @*/
1524: PetscErrorCode TSGetI2Function(TS ts,Vec *r,TSI2Function *fun,void **ctx)
1525: {
1527:   SNES           snes;
1528:   DM             dm;

1532:   TSGetSNES(ts,&snes);
1533:   SNESGetFunction(snes,r,NULL,NULL);
1534:   TSGetDM(ts,&dm);
1535:   DMTSGetI2Function(dm,fun,ctx);
1536:   return(0);
1537: }

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

1543:    Logically Collective on TS

1545:    Input Parameters:
1546: +  ts  - the TS context obtained from TSCreate()
1547: .  J   - Jacobian matrix
1548: .  P   - preconditioning matrix for J (may be same as J)
1549: .  jac - the Jacobian evaluation routine
1550: -  ctx - user-defined context for private data for the Jacobian evaluation routine (may be NULL)

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

1555: +  t    - time at step/stage being solved
1556: .  U    - state vector
1557: .  U_t  - time derivative of state vector
1558: .  U_tt - second time derivative of state vector
1559: .  v    - shift for U_t
1560: .  a    - shift for U_tt
1561: .  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
1562: .  P    - preconditioning matrix for J, may be same as J
1563: -  ctx  - [optional] user-defined context for matrix evaluation routine

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

1568:    The matrix dF/dU + v*dF/dU_t + a*dF/dU_tt you provide turns out to be
1569:    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.
1570:    The time integrator internally approximates U_t by W+v*U and U_tt by W'+a*U  where the positive "shift"
1571:    parameters 'v' and 'a' and vectors W, W' depend on the integration method, step size, and past states.

1573:    Level: beginner

1575: .seealso: TSSetI2Function()
1576: @*/
1577: PetscErrorCode TSSetI2Jacobian(TS ts,Mat J,Mat P,TSI2Jacobian jac,void *ctx)
1578: {
1579:   DM             dm;

1586:   TSSetIJacobian(ts,J,P,NULL,NULL);
1587:   TSGetDM(ts,&dm);
1588:   DMTSSetI2Jacobian(dm,jac,ctx);
1589:   return(0);
1590: }

1592: /*@C
1593:   TSGetI2Jacobian - Returns the implicit Jacobian at the present timestep.

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

1597:   Input Parameter:
1598: . ts  - The TS context obtained from TSCreate()

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

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

1609:   Level: advanced

1611: .seealso: TSGetTimeStep(), TSGetMatrices(), TSGetTime(), TSGetStepNumber()

1613: @*/
1614: PetscErrorCode  TSGetI2Jacobian(TS ts,Mat *J,Mat *P,TSI2Jacobian *jac,void **ctx)
1615: {
1617:   SNES           snes;
1618:   DM             dm;

1621:   TSGetSNES(ts,&snes);
1622:   SNESSetUpMatrices(snes);
1623:   SNESGetJacobian(snes,J,P,NULL,NULL);
1624:   TSGetDM(ts,&dm);
1625:   DMTSGetI2Jacobian(dm,jac,ctx);
1626:   return(0);
1627: }

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

1632:   Collective on TS

1634:   Input Parameters:
1635: + ts - the TS context
1636: . t - current time
1637: . U - state vector
1638: . V - time derivative of state vector (U_t)
1639: - A - second time derivative of state vector (U_tt)

1641:   Output Parameter:
1642: . F - the residual vector

1644:   Note:
1645:   Most users should not need to explicitly call this routine, as it
1646:   is used internally within the nonlinear solvers.

1648:   Level: developer

1650: .seealso: TSSetI2Function()
1651: @*/
1652: PetscErrorCode TSComputeI2Function(TS ts,PetscReal t,Vec U,Vec V,Vec A,Vec F)
1653: {
1654:   DM             dm;
1655:   TSI2Function   I2Function;
1656:   void           *ctx;
1657:   TSRHSFunction  rhsfunction;


1667:   TSGetDM(ts,&dm);
1668:   DMTSGetI2Function(dm,&I2Function,&ctx);
1669:   DMTSGetRHSFunction(dm,&rhsfunction,NULL);

1671:   if (!I2Function) {
1672:     TSComputeIFunction(ts,t,U,A,F,PETSC_FALSE);
1673:     return(0);
1674:   }

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

1678:   PetscStackPush("TS user implicit function");
1679:   I2Function(ts,t,U,V,A,F,ctx);
1680:   PetscStackPop;

1682:   if (rhsfunction) {
1683:     Vec Frhs;
1684:     TSGetRHSVec_Private(ts,&Frhs);
1685:     TSComputeRHSFunction(ts,t,U,Frhs);
1686:     VecAXPY(F,-1,Frhs);
1687:   }

1689:   PetscLogEventEnd(TS_FunctionEval,ts,U,V,F);
1690:   return(0);
1691: }

1693: /*@
1694:   TSComputeI2Jacobian - Evaluates the Jacobian of the DAE

1696:   Collective on TS

1698:   Input Parameters:
1699: + ts - the TS context
1700: . t - current timestep
1701: . U - state vector
1702: . V - time derivative of state vector
1703: . A - second time derivative of state vector
1704: . shiftV - shift to apply, see note below
1705: - shiftA - shift to apply, see note below

1707:   Output Parameters:
1708: + J - Jacobian matrix
1709: - P - optional preconditioning matrix

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

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

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

1719:   Level: developer

1721: .seealso:  TSSetI2Jacobian()
1722: @*/
1723: PetscErrorCode TSComputeI2Jacobian(TS ts,PetscReal t,Vec U,Vec V,Vec A,PetscReal shiftV,PetscReal shiftA,Mat J,Mat P)
1724: {
1725:   DM             dm;
1726:   TSI2Jacobian   I2Jacobian;
1727:   void           *ctx;
1728:   TSRHSJacobian  rhsjacobian;


1739:   TSGetDM(ts,&dm);
1740:   DMTSGetI2Jacobian(dm,&I2Jacobian,&ctx);
1741:   DMTSGetRHSJacobian(dm,&rhsjacobian,NULL);

1743:   if (!I2Jacobian) {
1744:     TSComputeIJacobian(ts,t,U,A,shiftA,J,P,PETSC_FALSE);
1745:     return(0);
1746:   }

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

1750:   PetscStackPush("TS user implicit Jacobian");
1751:   I2Jacobian(ts,t,U,V,A,shiftV,shiftA,J,P,ctx);
1752:   PetscStackPop;

1754:   if (rhsjacobian) {
1755:     Mat Jrhs,Prhs; MatStructure axpy = DIFFERENT_NONZERO_PATTERN;
1756:     TSGetRHSMats_Private(ts,&Jrhs,&Prhs);
1757:     TSComputeRHSJacobian(ts,t,U,Jrhs,Prhs);
1758:     MatAXPY(J,-1,Jrhs,axpy);
1759:     if (P != J) {MatAXPY(P,-1,Prhs,axpy);}
1760:   }

1762:   PetscLogEventEnd(TS_JacobianEval,ts,U,J,P);
1763:   return(0);
1764: }

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

1770:    Logically Collective on TS

1772:    Input Parameters:
1773: +  ts - the TS context obtained from TSCreate()
1774: .  u - the solution vector
1775: -  v - the time derivative vector

1777:    Level: beginner

1779: @*/
1780: PetscErrorCode  TS2SetSolution(TS ts,Vec u,Vec v)
1781: {

1788:   TSSetSolution(ts,u);
1789:   PetscObjectReference((PetscObject)v);
1790:   VecDestroy(&ts->vec_dot);
1791:   ts->vec_dot = v;
1792:   return(0);
1793: }

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

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

1803:    Input Parameter:
1804: .  ts - the TS context obtained from TSCreate()

1806:    Output Parameter:
1807: +  u - the vector containing the solution
1808: -  v - the vector containing the time derivative

1810:    Level: intermediate

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

1814: @*/
1815: PetscErrorCode  TS2GetSolution(TS ts,Vec *u,Vec *v)
1816: {
1821:   if (u) *u = ts->vec_sol;
1822:   if (v) *v = ts->vec_dot;
1823:   return(0);
1824: }

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

1829:   Collective on PetscViewer

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

1836:    Level: intermediate

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

1841:   Notes for advanced users:
1842:   Most users should not need to know the details of the binary storage
1843:   format, since TSLoad() and TSView() completely hide these details.
1844:   But for anyone who's interested, the standard binary matrix storage
1845:   format is
1846: .vb
1847:      has not yet been determined
1848: .ve

1850: .seealso: PetscViewerBinaryOpen(), TSView(), MatLoad(), VecLoad()
1851: @*/
1852: PetscErrorCode  TSLoad(TS ts, PetscViewer viewer)
1853: {
1855:   PetscBool      isbinary;
1856:   PetscInt       classid;
1857:   char           type[256];
1858:   DMTS           sdm;
1859:   DM             dm;

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

1867:   PetscViewerBinaryRead(viewer,&classid,1,NULL,PETSC_INT);
1868:   if (classid != TS_FILE_CLASSID) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_ARG_WRONG,"Not TS next in file");
1869:   PetscViewerBinaryRead(viewer,type,256,NULL,PETSC_CHAR);
1870:   TSSetType(ts, type);
1871:   if (ts->ops->load) {
1872:     (*ts->ops->load)(ts,viewer);
1873:   }
1874:   DMCreate(PetscObjectComm((PetscObject)ts),&dm);
1875:   DMLoad(dm,viewer);
1876:   TSSetDM(ts,dm);
1877:   DMCreateGlobalVector(ts->dm,&ts->vec_sol);
1878:   VecLoad(ts->vec_sol,viewer);
1879:   DMGetDMTS(ts->dm,&sdm);
1880:   DMTSLoad(sdm,viewer);
1881:   return(0);
1882: }

1884:  #include <petscdraw.h>
1885: #if defined(PETSC_HAVE_SAWS)
1886:  #include <petscviewersaws.h>
1887: #endif

1889: /*@C
1890:    TSViewFromOptions - View from Options

1892:    Collective on TS

1894:    Input Parameters:
1895: +  A - the application ordering context
1896: .  obj - Optional object
1897: -  name - command line option

1899:    Level: intermediate
1900: .seealso:  TS, TSView, PetscObjectViewFromOptions(), TSCreate()
1901: @*/
1902: PetscErrorCode  TSViewFromOptions(TS A,PetscObject obj,const char name[])
1903: {

1908:   PetscObjectViewFromOptions((PetscObject)A,obj,name);
1909:   return(0);
1910: }

1912: /*@C
1913:     TSView - Prints the TS data structure.

1915:     Collective on TS

1917:     Input Parameters:
1918: +   ts - the TS context obtained from TSCreate()
1919: -   viewer - visualization context

1921:     Options Database Key:
1922: .   -ts_view - calls TSView() at end of TSStep()

1924:     Notes:
1925:     The available visualization contexts include
1926: +     PETSC_VIEWER_STDOUT_SELF - standard output (default)
1927: -     PETSC_VIEWER_STDOUT_WORLD - synchronized standard
1928:          output where only the first processor opens
1929:          the file.  All other processors send their
1930:          data to the first processor to print.

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

1935:     Level: beginner

1937: .seealso: PetscViewerASCIIOpen()
1938: @*/
1939: PetscErrorCode  TSView(TS ts,PetscViewer viewer)
1940: {
1942:   TSType         type;
1943:   PetscBool      iascii,isstring,isundials,isbinary,isdraw;
1944:   DMTS           sdm;
1945: #if defined(PETSC_HAVE_SAWS)
1946:   PetscBool      issaws;
1947: #endif

1951:   if (!viewer) {
1952:     PetscViewerASCIIGetStdout(PetscObjectComm((PetscObject)ts),&viewer);
1953:   }

1957:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERASCII,&iascii);
1958:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERSTRING,&isstring);
1959:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERBINARY,&isbinary);
1960:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERDRAW,&isdraw);
1961: #if defined(PETSC_HAVE_SAWS)
1962:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERSAWS,&issaws);
1963: #endif
1964:   if (iascii) {
1965:     PetscObjectPrintClassNamePrefixType((PetscObject)ts,viewer);
1966:     if (ts->ops->view) {
1967:       PetscViewerASCIIPushTab(viewer);
1968:       (*ts->ops->view)(ts,viewer);
1969:       PetscViewerASCIIPopTab(viewer);
1970:     }
1971:     if (ts->max_steps < PETSC_MAX_INT) {
1972:       PetscViewerASCIIPrintf(viewer,"  maximum steps=%D\n",ts->max_steps);
1973:     }
1974:     if (ts->max_time < PETSC_MAX_REAL) {
1975:       PetscViewerASCIIPrintf(viewer,"  maximum time=%g\n",(double)ts->max_time);
1976:     }
1977:     if (ts->usessnes) {
1978:       PetscBool lin;
1979:       if (ts->problem_type == TS_NONLINEAR) {
1980:         PetscViewerASCIIPrintf(viewer,"  total number of nonlinear solver iterations=%D\n",ts->snes_its);
1981:       }
1982:       PetscViewerASCIIPrintf(viewer,"  total number of linear solver iterations=%D\n",ts->ksp_its);
1983:       PetscObjectTypeCompareAny((PetscObject)ts->snes,&lin,SNESKSPONLY,SNESKSPTRANSPOSEONLY,"");
1984:       PetscViewerASCIIPrintf(viewer,"  total number of %slinear solve failures=%D\n",lin ? "" : "non",ts->num_snes_failures);
1985:     }
1986:     PetscViewerASCIIPrintf(viewer,"  total number of rejected steps=%D\n",ts->reject);
1987:     if (ts->vrtol) {
1988:       PetscViewerASCIIPrintf(viewer,"  using vector of relative error tolerances, ");
1989:     } else {
1990:       PetscViewerASCIIPrintf(viewer,"  using relative error tolerance of %g, ",(double)ts->rtol);
1991:     }
1992:     if (ts->vatol) {
1993:       PetscViewerASCIIPrintf(viewer,"  using vector of absolute error tolerances\n");
1994:     } else {
1995:       PetscViewerASCIIPrintf(viewer,"  using absolute error tolerance of %g\n",(double)ts->atol);
1996:     }
1997:     PetscViewerASCIIPushTab(viewer);
1998:     TSAdaptView(ts->adapt,viewer);
1999:     PetscViewerASCIIPopTab(viewer);
2000:   } else if (isstring) {
2001:     TSGetType(ts,&type);
2002:     PetscViewerStringSPrintf(viewer," TSType: %-7.7s",type);
2003:     if (ts->ops->view) {(*ts->ops->view)(ts,viewer);}
2004:   } else if (isbinary) {
2005:     PetscInt    classid = TS_FILE_CLASSID;
2006:     MPI_Comm    comm;
2007:     PetscMPIInt rank;
2008:     char        type[256];

2010:     PetscObjectGetComm((PetscObject)ts,&comm);
2011:     MPI_Comm_rank(comm,&rank);
2012:     if (!rank) {
2013:       PetscViewerBinaryWrite(viewer,&classid,1,PETSC_INT,PETSC_FALSE);
2014:       PetscStrncpy(type,((PetscObject)ts)->type_name,256);
2015:       PetscViewerBinaryWrite(viewer,type,256,PETSC_CHAR,PETSC_FALSE);
2016:     }
2017:     if (ts->ops->view) {
2018:       (*ts->ops->view)(ts,viewer);
2019:     }
2020:     if (ts->adapt) {TSAdaptView(ts->adapt,viewer);}
2021:     DMView(ts->dm,viewer);
2022:     VecView(ts->vec_sol,viewer);
2023:     DMGetDMTS(ts->dm,&sdm);
2024:     DMTSView(sdm,viewer);
2025:   } else if (isdraw) {
2026:     PetscDraw draw;
2027:     char      str[36];
2028:     PetscReal x,y,bottom,h;

2030:     PetscViewerDrawGetDraw(viewer,0,&draw);
2031:     PetscDrawGetCurrentPoint(draw,&x,&y);
2032:     PetscStrcpy(str,"TS: ");
2033:     PetscStrcat(str,((PetscObject)ts)->type_name);
2034:     PetscDrawStringBoxed(draw,x,y,PETSC_DRAW_BLACK,PETSC_DRAW_BLACK,str,NULL,&h);
2035:     bottom = y - h;
2036:     PetscDrawPushCurrentPoint(draw,x,bottom);
2037:     if (ts->ops->view) {
2038:       (*ts->ops->view)(ts,viewer);
2039:     }
2040:     if (ts->adapt) {TSAdaptView(ts->adapt,viewer);}
2041:     if (ts->snes)  {SNESView(ts->snes,viewer);}
2042:     PetscDrawPopCurrentPoint(draw);
2043: #if defined(PETSC_HAVE_SAWS)
2044:   } else if (issaws) {
2045:     PetscMPIInt rank;
2046:     const char  *name;

2048:     PetscObjectGetName((PetscObject)ts,&name);
2049:     MPI_Comm_rank(PETSC_COMM_WORLD,&rank);
2050:     if (!((PetscObject)ts)->amsmem && !rank) {
2051:       char       dir[1024];

2053:       PetscObjectViewSAWs((PetscObject)ts,viewer);
2054:       PetscSNPrintf(dir,1024,"/PETSc/Objects/%s/time_step",name);
2055:       PetscStackCallSAWs(SAWs_Register,(dir,&ts->steps,1,SAWs_READ,SAWs_INT));
2056:       PetscSNPrintf(dir,1024,"/PETSc/Objects/%s/time",name);
2057:       PetscStackCallSAWs(SAWs_Register,(dir,&ts->ptime,1,SAWs_READ,SAWs_DOUBLE));
2058:     }
2059:     if (ts->ops->view) {
2060:       (*ts->ops->view)(ts,viewer);
2061:     }
2062: #endif
2063:   }
2064:   if (ts->snes && ts->usessnes)  {
2065:     PetscViewerASCIIPushTab(viewer);
2066:     SNESView(ts->snes,viewer);
2067:     PetscViewerASCIIPopTab(viewer);
2068:   }
2069:   DMGetDMTS(ts->dm,&sdm);
2070:   DMTSView(sdm,viewer);

2072:   PetscViewerASCIIPushTab(viewer);
2073:   PetscObjectTypeCompare((PetscObject)ts,TSSUNDIALS,&isundials);
2074:   PetscViewerASCIIPopTab(viewer);
2075:   return(0);
2076: }

2078: /*@
2079:    TSSetApplicationContext - Sets an optional user-defined context for
2080:    the timesteppers.

2082:    Logically Collective on TS

2084:    Input Parameters:
2085: +  ts - the TS context obtained from TSCreate()
2086: -  usrP - optional user context

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

2092:    Level: intermediate

2094: .seealso: TSGetApplicationContext()
2095: @*/
2096: PetscErrorCode  TSSetApplicationContext(TS ts,void *usrP)
2097: {
2100:   ts->user = usrP;
2101:   return(0);
2102: }

2104: /*@
2105:     TSGetApplicationContext - Gets the user-defined context for the
2106:     timestepper.

2108:     Not Collective

2110:     Input Parameter:
2111: .   ts - the TS context obtained from TSCreate()

2113:     Output Parameter:
2114: .   usrP - user context

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

2120:     Level: intermediate

2122: .seealso: TSSetApplicationContext()
2123: @*/
2124: PetscErrorCode  TSGetApplicationContext(TS ts,void *usrP)
2125: {
2128:   *(void**)usrP = ts->user;
2129:   return(0);
2130: }

2132: /*@
2133:    TSGetStepNumber - Gets the number of steps completed.

2135:    Not Collective

2137:    Input Parameter:
2138: .  ts - the TS context obtained from TSCreate()

2140:    Output Parameter:
2141: .  steps - number of steps completed so far

2143:    Level: intermediate

2145: .seealso: TSGetTime(), TSGetTimeStep(), TSSetPreStep(), TSSetPreStage(), TSSetPostStage(), TSSetPostStep()
2146: @*/
2147: PetscErrorCode TSGetStepNumber(TS ts,PetscInt *steps)
2148: {
2152:   *steps = ts->steps;
2153:   return(0);
2154: }

2156: /*@
2157:    TSSetStepNumber - Sets the number of steps completed.

2159:    Logically Collective on TS

2161:    Input Parameters:
2162: +  ts - the TS context
2163: -  steps - number of steps completed so far

2165:    Notes:
2166:    For most uses of the TS solvers the user need not explicitly call
2167:    TSSetStepNumber(), as the step counter is appropriately updated in
2168:    TSSolve()/TSStep()/TSRollBack(). Power users may call this routine to
2169:    reinitialize timestepping by setting the step counter to zero (and time
2170:    to the initial time) to solve a similar problem with different initial
2171:    conditions or parameters. Other possible use case is to continue
2172:    timestepping from a previously interrupted run in such a way that TS
2173:    monitors will be called with a initial nonzero step counter.

2175:    Level: advanced

2177: .seealso: TSGetStepNumber(), TSSetTime(), TSSetTimeStep(), TSSetSolution()
2178: @*/
2179: PetscErrorCode TSSetStepNumber(TS ts,PetscInt steps)
2180: {
2184:   if (steps < 0) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_ARG_OUTOFRANGE,"Step number must be non-negative");
2185:   ts->steps = steps;
2186:   return(0);
2187: }

2189: /*@
2190:    TSSetTimeStep - Allows one to reset the timestep at any time,
2191:    useful for simple pseudo-timestepping codes.

2193:    Logically Collective on TS

2195:    Input Parameters:
2196: +  ts - the TS context obtained from TSCreate()
2197: -  time_step - the size of the timestep

2199:    Level: intermediate

2201: .seealso: TSGetTimeStep(), TSSetTime()

2203: @*/
2204: PetscErrorCode  TSSetTimeStep(TS ts,PetscReal time_step)
2205: {
2209:   ts->time_step = time_step;
2210:   return(0);
2211: }

2213: /*@
2214:    TSSetExactFinalTime - Determines whether to adapt the final time step to
2215:      match the exact final time, interpolate solution to the exact final time,
2216:      or just return at the final time TS computed.

2218:   Logically Collective on TS

2220:    Input Parameter:
2221: +   ts - the time-step context
2222: -   eftopt - exact final time option

2224: $  TS_EXACTFINALTIME_STEPOVER    - Don't do anything if final time is exceeded
2225: $  TS_EXACTFINALTIME_INTERPOLATE - Interpolate back to final time
2226: $  TS_EXACTFINALTIME_MATCHSTEP - Adapt final time step to match the final time

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

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

2234:    Level: beginner

2236: .seealso: TSExactFinalTimeOption, TSGetExactFinalTime()
2237: @*/
2238: PetscErrorCode TSSetExactFinalTime(TS ts,TSExactFinalTimeOption eftopt)
2239: {
2243:   ts->exact_final_time = eftopt;
2244:   return(0);
2245: }

2247: /*@
2248:    TSGetExactFinalTime - Gets the exact final time option.

2250:    Not Collective

2252:    Input Parameter:
2253: .  ts - the TS context

2255:    Output Parameter:
2256: .  eftopt - exact final time option

2258:    Level: beginner

2260: .seealso: TSExactFinalTimeOption, TSSetExactFinalTime()
2261: @*/
2262: PetscErrorCode TSGetExactFinalTime(TS ts,TSExactFinalTimeOption *eftopt)
2263: {
2267:   *eftopt = ts->exact_final_time;
2268:   return(0);
2269: }

2271: /*@
2272:    TSGetTimeStep - Gets the current timestep size.

2274:    Not Collective

2276:    Input Parameter:
2277: .  ts - the TS context obtained from TSCreate()

2279:    Output Parameter:
2280: .  dt - the current timestep size

2282:    Level: intermediate

2284: .seealso: TSSetTimeStep(), TSGetTime()

2286: @*/
2287: PetscErrorCode  TSGetTimeStep(TS ts,PetscReal *dt)
2288: {
2292:   *dt = ts->time_step;
2293:   return(0);
2294: }

2296: /*@
2297:    TSGetSolution - Returns the solution at the present timestep. It
2298:    is valid to call this routine inside the function that you are evaluating
2299:    in order to move to the new timestep. This vector not changed until
2300:    the solution at the next timestep has been calculated.

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

2304:    Input Parameter:
2305: .  ts - the TS context obtained from TSCreate()

2307:    Output Parameter:
2308: .  v - the vector containing the solution

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

2313:    Level: intermediate

2315: .seealso: TSGetTimeStep(), TSGetTime(), TSGetSolveTime(), TSGetSolutionComponents(), TSSetSolutionFunction()

2317: @*/
2318: PetscErrorCode  TSGetSolution(TS ts,Vec *v)
2319: {
2323:   *v = ts->vec_sol;
2324:   return(0);
2325: }

2327: /*@
2328:    TSGetSolutionComponents - Returns any solution components at the present
2329:    timestep, if available for the time integration method being used.
2330:    Solution components are quantities that share the same size and
2331:    structure as the solution vector.

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

2335:    Parameters :
2336: +  ts - the TS context obtained from TSCreate() (input parameter).
2337: .  n - If v is PETSC_NULL, then the number of solution components is
2338:        returned through n, else the n-th solution component is
2339:        returned in v.
2340: -  v - the vector containing the n-th solution component
2341:        (may be PETSC_NULL to use this function to find out
2342:         the number of solutions components).

2344:    Level: advanced

2346: .seealso: TSGetSolution()

2348: @*/
2349: PetscErrorCode  TSGetSolutionComponents(TS ts,PetscInt *n,Vec *v)
2350: {

2355:   if (!ts->ops->getsolutioncomponents) *n = 0;
2356:   else {
2357:     (*ts->ops->getsolutioncomponents)(ts,n,v);
2358:   }
2359:   return(0);
2360: }

2362: /*@
2363:    TSGetAuxSolution - Returns an auxiliary solution at the present
2364:    timestep, if available for the time integration method being used.

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

2368:    Parameters :
2369: +  ts - the TS context obtained from TSCreate() (input parameter).
2370: -  v - the vector containing the auxiliary solution

2372:    Level: intermediate

2374: .seealso: TSGetSolution()

2376: @*/
2377: PetscErrorCode  TSGetAuxSolution(TS ts,Vec *v)
2378: {

2383:   if (ts->ops->getauxsolution) {
2384:     (*ts->ops->getauxsolution)(ts,v);
2385:   } else {
2386:     VecZeroEntries(*v);
2387:   }
2388:   return(0);
2389: }

2391: /*@
2392:    TSGetTimeError - Returns the estimated error vector, if the chosen
2393:    TSType has an error estimation functionality.

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

2397:    Note: MUST call after TSSetUp()

2399:    Parameters :
2400: +  ts - the TS context obtained from TSCreate() (input parameter).
2401: .  n - current estimate (n=0) or previous one (n=-1)
2402: -  v - the vector containing the error (same size as the solution).

2404:    Level: intermediate

2406: .seealso: TSGetSolution(), TSSetTimeError()

2408: @*/
2409: PetscErrorCode  TSGetTimeError(TS ts,PetscInt n,Vec *v)
2410: {

2415:   if (ts->ops->gettimeerror) {
2416:     (*ts->ops->gettimeerror)(ts,n,v);
2417:   } else {
2418:     VecZeroEntries(*v);
2419:   }
2420:   return(0);
2421: }

2423: /*@
2424:    TSSetTimeError - Sets the estimated error vector, if the chosen
2425:    TSType has an error estimation functionality. This can be used
2426:    to restart such a time integrator with a given error vector.

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

2430:    Parameters :
2431: +  ts - the TS context obtained from TSCreate() (input parameter).
2432: -  v - the vector containing the error (same size as the solution).

2434:    Level: intermediate

2436: .seealso: TSSetSolution(), TSGetTimeError)

2438: @*/
2439: PetscErrorCode  TSSetTimeError(TS ts,Vec v)
2440: {

2445:   if (!ts->setupcalled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Must call TSSetUp() first");
2446:   if (ts->ops->settimeerror) {
2447:     (*ts->ops->settimeerror)(ts,v);
2448:   }
2449:   return(0);
2450: }

2452: /* ----- Routines to initialize and destroy a timestepper ---- */
2453: /*@
2454:   TSSetProblemType - Sets the type of problem to be solved.

2456:   Not collective

2458:   Input Parameters:
2459: + ts   - The TS
2460: - type - One of TS_LINEAR, TS_NONLINEAR where these types refer to problems of the forms
2461: .vb
2462:          U_t - A U = 0      (linear)
2463:          U_t - A(t) U = 0   (linear)
2464:          F(t,U,U_t) = 0     (nonlinear)
2465: .ve

2467:    Level: beginner

2469: .seealso: TSSetUp(), TSProblemType, TS
2470: @*/
2471: PetscErrorCode  TSSetProblemType(TS ts, TSProblemType type)
2472: {

2477:   ts->problem_type = type;
2478:   if (type == TS_LINEAR) {
2479:     SNES snes;
2480:     TSGetSNES(ts,&snes);
2481:     SNESSetType(snes,SNESKSPONLY);
2482:   }
2483:   return(0);
2484: }

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

2489:   Not collective

2491:   Input Parameter:
2492: . ts   - The TS

2494:   Output Parameter:
2495: . type - One of TS_LINEAR, TS_NONLINEAR where these types refer to problems of the forms
2496: .vb
2497:          M U_t = A U
2498:          M(t) U_t = A(t) U
2499:          F(t,U,U_t)
2500: .ve

2502:    Level: beginner

2504: .seealso: TSSetUp(), TSProblemType, TS
2505: @*/
2506: PetscErrorCode  TSGetProblemType(TS ts, TSProblemType *type)
2507: {
2511:   *type = ts->problem_type;
2512:   return(0);
2513: }

2515: /*@
2516:    TSSetUp - Sets up the internal data structures for the later use
2517:    of a timestepper.

2519:    Collective on TS

2521:    Input Parameter:
2522: .  ts - the TS context obtained from TSCreate()

2524:    Notes:
2525:    For basic use of the TS solvers the user need not explicitly call
2526:    TSSetUp(), since these actions will automatically occur during
2527:    the call to TSStep() or TSSolve().  However, if one wishes to control this
2528:    phase separately, TSSetUp() should be called after TSCreate()
2529:    and optional routines of the form TSSetXXX(), but before TSStep() and TSSolve().

2531:    Level: advanced

2533: .seealso: TSCreate(), TSStep(), TSDestroy(), TSSolve()
2534: @*/
2535: PetscErrorCode  TSSetUp(TS ts)
2536: {
2538:   DM             dm;
2539:   PetscErrorCode (*func)(SNES,Vec,Vec,void*);
2540:   PetscErrorCode (*jac)(SNES,Vec,Mat,Mat,void*);
2541:   TSIFunction    ifun;
2542:   TSIJacobian    ijac;
2543:   TSI2Jacobian   i2jac;
2544:   TSRHSJacobian  rhsjac;
2545:   PetscBool      isnone;

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

2551:   if (!((PetscObject)ts)->type_name) {
2552:     TSGetIFunction(ts,NULL,&ifun,NULL);
2553:     TSSetType(ts,ifun ? TSBEULER : TSEULER);
2554:   }

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

2558:   if (!ts->Jacp && ts->Jacprhs) { /* IJacobianP shares the same matrix with RHSJacobianP if only RHSJacobianP is provided */
2559:     PetscObjectReference((PetscObject)ts->Jacprhs);
2560:     ts->Jacp = ts->Jacprhs;
2561:   }

2563:   if (ts->quadraturets) {
2564:     TSSetUp(ts->quadraturets);
2565:     VecDestroy(&ts->vec_costintegrand);
2566:     VecDuplicate(ts->quadraturets->vec_sol,&ts->vec_costintegrand);
2567:   }

2569:   TSGetRHSJacobian(ts,NULL,NULL,&rhsjac,NULL);
2570:   if (ts->rhsjacobian.reuse && rhsjac == TSComputeRHSJacobianConstant) {
2571:     Mat Amat,Pmat;
2572:     SNES snes;
2573:     TSGetSNES(ts,&snes);
2574:     SNESGetJacobian(snes,&Amat,&Pmat,NULL,NULL);
2575:     /* Matching matrices implies that an IJacobian is NOT set, because if it had been set, the IJacobian's matrix would
2576:      * have displaced the RHS matrix */
2577:     if (Amat && Amat == ts->Arhs) {
2578:       /* we need to copy the values of the matrix because for the constant Jacobian case the user will never set the numerical values in this new location */
2579:       MatDuplicate(ts->Arhs,MAT_COPY_VALUES,&Amat);
2580:       SNESSetJacobian(snes,Amat,NULL,NULL,NULL);
2581:       MatDestroy(&Amat);
2582:     }
2583:     if (Pmat && Pmat == ts->Brhs) {
2584:       MatDuplicate(ts->Brhs,MAT_COPY_VALUES,&Pmat);
2585:       SNESSetJacobian(snes,NULL,Pmat,NULL,NULL);
2586:       MatDestroy(&Pmat);
2587:     }
2588:   }

2590:   TSGetAdapt(ts,&ts->adapt);
2591:   TSAdaptSetDefaultType(ts->adapt,ts->default_adapt_type);

2593:   if (ts->ops->setup) {
2594:     (*ts->ops->setup)(ts);
2595:   }

2597:   /* Attempt to check/preset a default value for the exact final time option */
2598:   PetscObjectTypeCompare((PetscObject)ts->adapt,TSADAPTNONE,&isnone);
2599:   if (!isnone && ts->exact_final_time == TS_EXACTFINALTIME_UNSPECIFIED)
2600:     ts->exact_final_time = TS_EXACTFINALTIME_MATCHSTEP;

2602:   /* In the case where we've set a DMTSFunction or what have you, we need the default SNESFunction
2603:      to be set right but can't do it elsewhere due to the overreliance on ctx=ts.
2604:    */
2605:   TSGetDM(ts,&dm);
2606:   DMSNESGetFunction(dm,&func,NULL);
2607:   if (!func) {
2608:     DMSNESSetFunction(dm,SNESTSFormFunction,ts);
2609:   }
2610:   /* If the SNES doesn't have a jacobian set and the TS has an ijacobian or rhsjacobian set, set the SNES to use it.
2611:      Otherwise, the SNES will use coloring internally to form the Jacobian.
2612:    */
2613:   DMSNESGetJacobian(dm,&jac,NULL);
2614:   DMTSGetIJacobian(dm,&ijac,NULL);
2615:   DMTSGetI2Jacobian(dm,&i2jac,NULL);
2616:   DMTSGetRHSJacobian(dm,&rhsjac,NULL);
2617:   if (!jac && (ijac || i2jac || rhsjac)) {
2618:     DMSNESSetJacobian(dm,SNESTSFormJacobian,ts);
2619:   }

2621:   /* if time integration scheme has a starting method, call it */
2622:   if (ts->ops->startingmethod) {
2623:     (*ts->ops->startingmethod)(ts);
2624:   }

2626:   ts->setupcalled = PETSC_TRUE;
2627:   return(0);
2628: }

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

2633:    Collective on TS

2635:    Input Parameter:
2636: .  ts - the TS context obtained from TSCreate()

2638:    Level: beginner

2640: .seealso: TSCreate(), TSSetup(), TSDestroy()
2641: @*/
2642: PetscErrorCode  TSReset(TS ts)
2643: {
2644:   TS_RHSSplitLink ilink = ts->tsrhssplit,next;
2645:   PetscErrorCode  ierr;


2650:   if (ts->ops->reset) {
2651:     (*ts->ops->reset)(ts);
2652:   }
2653:   if (ts->snes) {SNESReset(ts->snes);}
2654:   if (ts->adapt) {TSAdaptReset(ts->adapt);}

2656:   MatDestroy(&ts->Arhs);
2657:   MatDestroy(&ts->Brhs);
2658:   VecDestroy(&ts->Frhs);
2659:   VecDestroy(&ts->vec_sol);
2660:   VecDestroy(&ts->vec_dot);
2661:   VecDestroy(&ts->vatol);
2662:   VecDestroy(&ts->vrtol);
2663:   VecDestroyVecs(ts->nwork,&ts->work);

2665:   MatDestroy(&ts->Jacprhs);
2666:   MatDestroy(&ts->Jacp);
2667:   if (ts->forward_solve) {
2668:     TSForwardReset(ts);
2669:   }
2670:   if (ts->quadraturets) {
2671:     TSReset(ts->quadraturets);
2672:     VecDestroy(&ts->vec_costintegrand);
2673:   }
2674:   while (ilink) {
2675:     next = ilink->next;
2676:     TSDestroy(&ilink->ts);
2677:     PetscFree(ilink->splitname);
2678:     ISDestroy(&ilink->is);
2679:     PetscFree(ilink);
2680:     ilink = next;
2681:   }
2682:   ts->num_rhs_splits = 0;
2683:   ts->setupcalled = PETSC_FALSE;
2684:   return(0);
2685: }

2687: /*@
2688:    TSDestroy - Destroys the timestepper context that was created
2689:    with TSCreate().

2691:    Collective on TS

2693:    Input Parameter:
2694: .  ts - the TS context obtained from TSCreate()

2696:    Level: beginner

2698: .seealso: TSCreate(), TSSetUp(), TSSolve()
2699: @*/
2700: PetscErrorCode  TSDestroy(TS *ts)
2701: {

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

2709:   TSReset(*ts);
2710:   TSAdjointReset(*ts);
2711:   if ((*ts)->forward_solve) {
2712:     TSForwardReset(*ts);
2713:   }
2714:   /* if memory was published with SAWs then destroy it */
2715:   PetscObjectSAWsViewOff((PetscObject)*ts);
2716:   if ((*ts)->ops->destroy) {(*(*ts)->ops->destroy)((*ts));}

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

2720:   TSAdaptDestroy(&(*ts)->adapt);
2721:   TSEventDestroy(&(*ts)->event);

2723:   SNESDestroy(&(*ts)->snes);
2724:   DMDestroy(&(*ts)->dm);
2725:   TSMonitorCancel((*ts));
2726:   TSAdjointMonitorCancel((*ts));

2728:   TSDestroy(&(*ts)->quadraturets);
2729:   PetscHeaderDestroy(ts);
2730:   return(0);
2731: }

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

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

2739:    Input Parameter:
2740: .  ts - the TS context obtained from TSCreate()

2742:    Output Parameter:
2743: .  snes - the nonlinear solver context

2745:    Notes:
2746:    The user can then directly manipulate the SNES context to set various
2747:    options, etc.  Likewise, the user can then extract and manipulate the
2748:    KSP, KSP, and PC contexts as well.

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

2753:    Level: beginner

2755: @*/
2756: PetscErrorCode  TSGetSNES(TS ts,SNES *snes)
2757: {

2763:   if (!ts->snes) {
2764:     SNESCreate(PetscObjectComm((PetscObject)ts),&ts->snes);
2765:     PetscObjectSetOptions((PetscObject)ts->snes,((PetscObject)ts)->options);
2766:     SNESSetFunction(ts->snes,NULL,SNESTSFormFunction,ts);
2767:     PetscLogObjectParent((PetscObject)ts,(PetscObject)ts->snes);
2768:     PetscObjectIncrementTabLevel((PetscObject)ts->snes,(PetscObject)ts,1);
2769:     if (ts->dm) {SNESSetDM(ts->snes,ts->dm);}
2770:     if (ts->problem_type == TS_LINEAR) {
2771:       SNESSetType(ts->snes,SNESKSPONLY);
2772:     }
2773:   }
2774:   *snes = ts->snes;
2775:   return(0);
2776: }

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

2781:    Collective

2783:    Input Parameter:
2784: +  ts - the TS context obtained from TSCreate()
2785: -  snes - the nonlinear solver context

2787:    Notes:
2788:    Most users should have the TS created by calling TSGetSNES()

2790:    Level: developer

2792: @*/
2793: PetscErrorCode TSSetSNES(TS ts,SNES snes)
2794: {
2796:   PetscErrorCode (*func)(SNES,Vec,Mat,Mat,void*);

2801:   PetscObjectReference((PetscObject)snes);
2802:   SNESDestroy(&ts->snes);

2804:   ts->snes = snes;

2806:   SNESSetFunction(ts->snes,NULL,SNESTSFormFunction,ts);
2807:   SNESGetJacobian(ts->snes,NULL,NULL,&func,NULL);
2808:   if (func == SNESTSFormJacobian) {
2809:     SNESSetJacobian(ts->snes,NULL,NULL,SNESTSFormJacobian,ts);
2810:   }
2811:   return(0);
2812: }

2814: /*@
2815:    TSGetKSP - Returns the KSP (linear solver) associated with
2816:    a TS (timestepper) context.

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

2820:    Input Parameter:
2821: .  ts - the TS context obtained from TSCreate()

2823:    Output Parameter:
2824: .  ksp - the nonlinear solver context

2826:    Notes:
2827:    The user can then directly manipulate the KSP context to set various
2828:    options, etc.  Likewise, the user can then extract and manipulate the
2829:    KSP and PC contexts as well.

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

2834:    Level: beginner

2836: @*/
2837: PetscErrorCode  TSGetKSP(TS ts,KSP *ksp)
2838: {
2840:   SNES           snes;

2845:   if (!((PetscObject)ts)->type_name) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_NULL,"KSP is not created yet. Call TSSetType() first");
2846:   if (ts->problem_type != TS_LINEAR) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,"Linear only; use TSGetSNES()");
2847:   TSGetSNES(ts,&snes);
2848:   SNESGetKSP(snes,ksp);
2849:   return(0);
2850: }

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

2854: /*@
2855:    TSSetMaxSteps - Sets the maximum number of steps to use.

2857:    Logically Collective on TS

2859:    Input Parameters:
2860: +  ts - the TS context obtained from TSCreate()
2861: -  maxsteps - maximum number of steps to use

2863:    Options Database Keys:
2864: .  -ts_max_steps <maxsteps> - Sets maxsteps

2866:    Notes:
2867:    The default maximum number of steps is 5000

2869:    Level: intermediate

2871: .seealso: TSGetMaxSteps(), TSSetMaxTime(), TSSetExactFinalTime()
2872: @*/
2873: PetscErrorCode TSSetMaxSteps(TS ts,PetscInt maxsteps)
2874: {
2878:   if (maxsteps < 0 ) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_ARG_OUTOFRANGE,"Maximum number of steps must be non-negative");
2879:   ts->max_steps = maxsteps;
2880:   return(0);
2881: }

2883: /*@
2884:    TSGetMaxSteps - Gets the maximum number of steps to use.

2886:    Not Collective

2888:    Input Parameters:
2889: .  ts - the TS context obtained from TSCreate()

2891:    Output Parameter:
2892: .  maxsteps - maximum number of steps to use

2894:    Level: advanced

2896: .seealso: TSSetMaxSteps(), TSGetMaxTime(), TSSetMaxTime()
2897: @*/
2898: PetscErrorCode TSGetMaxSteps(TS ts,PetscInt *maxsteps)
2899: {
2903:   *maxsteps = ts->max_steps;
2904:   return(0);
2905: }

2907: /*@
2908:    TSSetMaxTime - Sets the maximum (or final) time for timestepping.

2910:    Logically Collective on TS

2912:    Input Parameters:
2913: +  ts - the TS context obtained from TSCreate()
2914: -  maxtime - final time to step to

2916:    Options Database Keys:
2917: .  -ts_max_time <maxtime> - Sets maxtime

2919:    Notes:
2920:    The default maximum time is 5.0

2922:    Level: intermediate

2924: .seealso: TSGetMaxTime(), TSSetMaxSteps(), TSSetExactFinalTime()
2925: @*/
2926: PetscErrorCode TSSetMaxTime(TS ts,PetscReal maxtime)
2927: {
2931:   ts->max_time = maxtime;
2932:   return(0);
2933: }

2935: /*@
2936:    TSGetMaxTime - Gets the maximum (or final) time for timestepping.

2938:    Not Collective

2940:    Input Parameters:
2941: .  ts - the TS context obtained from TSCreate()

2943:    Output Parameter:
2944: .  maxtime - final time to step to

2946:    Level: advanced

2948: .seealso: TSSetMaxTime(), TSGetMaxSteps(), TSSetMaxSteps()
2949: @*/
2950: PetscErrorCode TSGetMaxTime(TS ts,PetscReal *maxtime)
2951: {
2955:   *maxtime = ts->max_time;
2956:   return(0);
2957: }

2959: /*@
2960:    TSSetInitialTimeStep - Deprecated, use TSSetTime() and TSSetTimeStep().

2962:    Level: deprecated

2964: @*/
2965: PetscErrorCode  TSSetInitialTimeStep(TS ts,PetscReal initial_time,PetscReal time_step)
2966: {
2970:   TSSetTime(ts,initial_time);
2971:   TSSetTimeStep(ts,time_step);
2972:   return(0);
2973: }

2975: /*@
2976:    TSGetDuration - Deprecated, use TSGetMaxSteps() and TSGetMaxTime().

2978:    Level: deprecated

2980: @*/
2981: PetscErrorCode TSGetDuration(TS ts, PetscInt *maxsteps, PetscReal *maxtime)
2982: {
2985:   if (maxsteps) {
2987:     *maxsteps = ts->max_steps;
2988:   }
2989:   if (maxtime) {
2991:     *maxtime = ts->max_time;
2992:   }
2993:   return(0);
2994: }

2996: /*@
2997:    TSSetDuration - Deprecated, use TSSetMaxSteps() and TSSetMaxTime().

2999:    Level: deprecated

3001: @*/
3002: PetscErrorCode TSSetDuration(TS ts,PetscInt maxsteps,PetscReal maxtime)
3003: {
3008:   if (maxsteps >= 0) ts->max_steps = maxsteps;
3009:   if (maxtime != PETSC_DEFAULT) ts->max_time = maxtime;
3010:   return(0);
3011: }

3013: /*@
3014:    TSGetTimeStepNumber - Deprecated, use TSGetStepNumber().

3016:    Level: deprecated

3018: @*/
3019: PetscErrorCode TSGetTimeStepNumber(TS ts,PetscInt *steps) { return TSGetStepNumber(ts,steps); }

3021: /*@
3022:    TSGetTotalSteps - Deprecated, use TSGetStepNumber().

3024:    Level: deprecated

3026: @*/
3027: PetscErrorCode TSGetTotalSteps(TS ts,PetscInt *steps) { return TSGetStepNumber(ts,steps); }

3029: /*@
3030:    TSSetSolution - Sets the initial solution vector
3031:    for use by the TS routines.

3033:    Logically Collective on TS

3035:    Input Parameters:
3036: +  ts - the TS context obtained from TSCreate()
3037: -  u - the solution vector

3039:    Level: beginner

3041: .seealso: TSSetSolutionFunction(), TSGetSolution(), TSCreate()
3042: @*/
3043: PetscErrorCode  TSSetSolution(TS ts,Vec u)
3044: {
3046:   DM             dm;

3051:   PetscObjectReference((PetscObject)u);
3052:   VecDestroy(&ts->vec_sol);
3053:   ts->vec_sol = u;

3055:   TSGetDM(ts,&dm);
3056:   DMShellSetGlobalVector(dm,u);
3057:   return(0);
3058: }

3060: /*@C
3061:   TSSetPreStep - Sets the general-purpose function
3062:   called once at the beginning of each time step.

3064:   Logically Collective on TS

3066:   Input Parameters:
3067: + ts   - The TS context obtained from TSCreate()
3068: - func - The function

3070:   Calling sequence of func:
3071: .   PetscErrorCode func (TS ts);

3073:   Level: intermediate

3075: .seealso: TSSetPreStage(), TSSetPostStage(), TSSetPostStep(), TSStep(), TSRestartStep()
3076: @*/
3077: PetscErrorCode  TSSetPreStep(TS ts, PetscErrorCode (*func)(TS))
3078: {
3081:   ts->prestep = func;
3082:   return(0);
3083: }

3085: /*@
3086:   TSPreStep - Runs the user-defined pre-step function.

3088:   Collective on TS

3090:   Input Parameters:
3091: . ts   - The TS context obtained from TSCreate()

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

3097:   Level: developer

3099: .seealso: TSSetPreStep(), TSPreStage(), TSPostStage(), TSPostStep()
3100: @*/
3101: PetscErrorCode  TSPreStep(TS ts)
3102: {

3107:   if (ts->prestep) {
3108:     Vec              U;
3109:     PetscObjectState sprev,spost;

3111:     TSGetSolution(ts,&U);
3112:     PetscObjectStateGet((PetscObject)U,&sprev);
3113:     PetscStackCallStandard((*ts->prestep),(ts));
3114:     PetscObjectStateGet((PetscObject)U,&spost);
3115:     if (sprev != spost) {TSRestartStep(ts);}
3116:   }
3117:   return(0);
3118: }

3120: /*@C
3121:   TSSetPreStage - Sets the general-purpose function
3122:   called once at the beginning of each stage.

3124:   Logically Collective on TS

3126:   Input Parameters:
3127: + ts   - The TS context obtained from TSCreate()
3128: - func - The function

3130:   Calling sequence of func:
3131: .    PetscErrorCode func(TS ts, PetscReal stagetime);

3133:   Level: intermediate

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

3140: .seealso: TSSetPostStage(), TSSetPreStep(), TSSetPostStep(), TSGetApplicationContext()
3141: @*/
3142: PetscErrorCode  TSSetPreStage(TS ts, PetscErrorCode (*func)(TS,PetscReal))
3143: {
3146:   ts->prestage = func;
3147:   return(0);
3148: }

3150: /*@C
3151:   TSSetPostStage - Sets the general-purpose function
3152:   called once at the end of each stage.

3154:   Logically Collective on TS

3156:   Input Parameters:
3157: + ts   - The TS context obtained from TSCreate()
3158: - func - The function

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

3163:   Level: intermediate

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

3170: .seealso: TSSetPreStage(), TSSetPreStep(), TSSetPostStep(), TSGetApplicationContext()
3171: @*/
3172: PetscErrorCode  TSSetPostStage(TS ts, PetscErrorCode (*func)(TS,PetscReal,PetscInt,Vec*))
3173: {
3176:   ts->poststage = func;
3177:   return(0);
3178: }

3180: /*@C
3181:   TSSetPostEvaluate - Sets the general-purpose function
3182:   called once at the end of each step evaluation.

3184:   Logically Collective on TS

3186:   Input Parameters:
3187: + ts   - The TS context obtained from TSCreate()
3188: - func - The function

3190:   Calling sequence of func:
3191: . PetscErrorCode func(TS ts);

3193:   Level: intermediate

3195:   Note:
3196:   Semantically, TSSetPostEvaluate() differs from TSSetPostStep() since the function it sets is called before event-handling
3197:   thus guaranteeing the same solution (computed by the time-stepper) will be passed to it. On the other hand, TSPostStep()
3198:   may be passed a different solution, possibly changed by the event handler. TSPostEvaluate() is called after the next step
3199:   solution is evaluated allowing to modify it, if need be. The solution can be obtained with TSGetSolution(), the time step
3200:   with TSGetTimeStep(), and the time at the start of the step is available via TSGetTime()

3202: .seealso: TSSetPreStage(), TSSetPreStep(), TSSetPostStep(), TSGetApplicationContext()
3203: @*/
3204: PetscErrorCode  TSSetPostEvaluate(TS ts, PetscErrorCode (*func)(TS))
3205: {
3208:   ts->postevaluate = func;
3209:   return(0);
3210: }

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

3215:   Collective on TS

3217:   Input Parameters:
3218: . ts          - The TS context obtained from TSCreate()
3219:   stagetime   - The absolute time of the current stage

3221:   Notes:
3222:   TSPreStage() is typically used within time stepping implementations,
3223:   most users would not generally call this routine themselves.

3225:   Level: developer

3227: .seealso: TSPostStage(), TSSetPreStep(), TSPreStep(), TSPostStep()
3228: @*/
3229: PetscErrorCode  TSPreStage(TS ts, PetscReal stagetime)
3230: {
3233:   if (ts->prestage) {
3234:     PetscStackCallStandard((*ts->prestage),(ts,stagetime));
3235:   }
3236:   return(0);
3237: }

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

3242:   Collective on TS

3244:   Input Parameters:
3245: . ts          - The TS context obtained from TSCreate()
3246:   stagetime   - The absolute time of the current stage
3247:   stageindex  - Stage number
3248:   Y           - Array of vectors (of size = total number
3249:                 of stages) with the stage solutions

3251:   Notes:
3252:   TSPostStage() is typically used within time stepping implementations,
3253:   most users would not generally call this routine themselves.

3255:   Level: developer

3257: .seealso: TSPreStage(), TSSetPreStep(), TSPreStep(), TSPostStep()
3258: @*/
3259: PetscErrorCode  TSPostStage(TS ts, PetscReal stagetime, PetscInt stageindex, Vec *Y)
3260: {
3263:   if (ts->poststage) {
3264:     PetscStackCallStandard((*ts->poststage),(ts,stagetime,stageindex,Y));
3265:   }
3266:   return(0);
3267: }

3269: /*@
3270:   TSPostEvaluate - Runs the user-defined post-evaluate function set using TSSetPostEvaluate()

3272:   Collective on TS

3274:   Input Parameters:
3275: . ts          - The TS context obtained from TSCreate()

3277:   Notes:
3278:   TSPostEvaluate() is typically used within time stepping implementations,
3279:   most users would not generally call this routine themselves.

3281:   Level: developer

3283: .seealso: TSSetPostEvaluate(), TSSetPreStep(), TSPreStep(), TSPostStep()
3284: @*/
3285: PetscErrorCode  TSPostEvaluate(TS ts)
3286: {

3291:   if (ts->postevaluate) {
3292:     Vec              U;
3293:     PetscObjectState sprev,spost;

3295:     TSGetSolution(ts,&U);
3296:     PetscObjectStateGet((PetscObject)U,&sprev);
3297:     PetscStackCallStandard((*ts->postevaluate),(ts));
3298:     PetscObjectStateGet((PetscObject)U,&spost);
3299:     if (sprev != spost) {TSRestartStep(ts);}
3300:   }
3301:   return(0);
3302: }

3304: /*@C
3305:   TSSetPostStep - Sets the general-purpose function
3306:   called once at the end of each time step.

3308:   Logically Collective on TS

3310:   Input Parameters:
3311: + ts   - The TS context obtained from TSCreate()
3312: - func - The function

3314:   Calling sequence of func:
3315: $ func (TS ts);

3317:   Notes:
3318:   The function set by TSSetPostStep() is called after each successful step. The solution vector X
3319:   obtained by TSGetSolution() may be different than that computed at the step end if the event handler
3320:   locates an event and TSPostEvent() modifies it. Use TSSetPostEvaluate() if an unmodified solution is needed instead.

3322:   Level: intermediate

3324: .seealso: TSSetPreStep(), TSSetPreStage(), TSSetPostEvaluate(), TSGetTimeStep(), TSGetStepNumber(), TSGetTime(), TSRestartStep()
3325: @*/
3326: PetscErrorCode  TSSetPostStep(TS ts, PetscErrorCode (*func)(TS))
3327: {
3330:   ts->poststep = func;
3331:   return(0);
3332: }

3334: /*@
3335:   TSPostStep - Runs the user-defined post-step function.

3337:   Collective on TS

3339:   Input Parameters:
3340: . ts   - The TS context obtained from TSCreate()

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

3346:   Level: developer

3348: @*/
3349: PetscErrorCode  TSPostStep(TS ts)
3350: {

3355:   if (ts->poststep) {
3356:     Vec              U;
3357:     PetscObjectState sprev,spost;

3359:     TSGetSolution(ts,&U);
3360:     PetscObjectStateGet((PetscObject)U,&sprev);
3361:     PetscStackCallStandard((*ts->poststep),(ts));
3362:     PetscObjectStateGet((PetscObject)U,&spost);
3363:     if (sprev != spost) {TSRestartStep(ts);}
3364:   }
3365:   return(0);
3366: }

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

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

3374:    Logically Collective on TS

3376:    Input Parameters:
3377: +  ts - the TS context obtained from TSCreate()
3378: .  monitor - monitoring routine
3379: .  mctx - [optional] user-defined context for private data for the
3380:              monitor routine (use NULL if no context is desired)
3381: -  monitordestroy - [optional] routine that frees monitor context
3382:           (may be NULL)

3384:    Calling sequence of monitor:
3385: $    PetscErrorCode monitor(TS ts,PetscInt steps,PetscReal time,Vec u,void *mctx)

3387: +    ts - the TS context
3388: .    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)
3389: .    time - current time
3390: .    u - current iterate
3391: -    mctx - [optional] monitoring context

3393:    Notes:
3394:    This routine adds an additional monitor to the list of monitors that
3395:    already has been loaded.

3397:    Fortran Notes:
3398:     Only a single monitor function can be set for each TS object

3400:    Level: intermediate

3402: .seealso: TSMonitorDefault(), TSMonitorCancel()
3403: @*/
3404: PetscErrorCode  TSMonitorSet(TS ts,PetscErrorCode (*monitor)(TS,PetscInt,PetscReal,Vec,void*),void *mctx,PetscErrorCode (*mdestroy)(void**))
3405: {
3407:   PetscInt       i;
3408:   PetscBool      identical;

3412:   for (i=0; i<ts->numbermonitors;i++) {
3413:     PetscMonitorCompare((PetscErrorCode (*)(void))monitor,mctx,mdestroy,(PetscErrorCode (*)(void))ts->monitor[i],ts->monitorcontext[i],ts->monitordestroy[i],&identical);
3414:     if (identical) return(0);
3415:   }
3416:   if (ts->numbermonitors >= MAXTSMONITORS) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Too many monitors set");
3417:   ts->monitor[ts->numbermonitors]          = monitor;
3418:   ts->monitordestroy[ts->numbermonitors]   = mdestroy;
3419:   ts->monitorcontext[ts->numbermonitors++] = (void*)mctx;
3420:   return(0);
3421: }

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

3426:    Logically Collective on TS

3428:    Input Parameters:
3429: .  ts - the TS context obtained from TSCreate()

3431:    Notes:
3432:    There is no way to remove a single, specific monitor.

3434:    Level: intermediate

3436: .seealso: TSMonitorDefault(), TSMonitorSet()
3437: @*/
3438: PetscErrorCode  TSMonitorCancel(TS ts)
3439: {
3441:   PetscInt       i;

3445:   for (i=0; i<ts->numbermonitors; i++) {
3446:     if (ts->monitordestroy[i]) {
3447:       (*ts->monitordestroy[i])(&ts->monitorcontext[i]);
3448:     }
3449:   }
3450:   ts->numbermonitors = 0;
3451:   return(0);
3452: }

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

3457:    Level: intermediate

3459: .seealso:  TSMonitorSet()
3460: @*/
3461: PetscErrorCode TSMonitorDefault(TS ts,PetscInt step,PetscReal ptime,Vec v,PetscViewerAndFormat *vf)
3462: {
3464:   PetscViewer    viewer =  vf->viewer;
3465:   PetscBool      iascii,ibinary;

3469:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERASCII,&iascii);
3470:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERBINARY,&ibinary);
3471:   PetscViewerPushFormat(viewer,vf->format);
3472:   if (iascii) {
3473:     PetscViewerASCIIAddTab(viewer,((PetscObject)ts)->tablevel);
3474:     if (step == -1){ /* this indicates it is an interpolated solution */
3475:       PetscViewerASCIIPrintf(viewer,"Interpolated solution at time %g between steps %D and %D\n",(double)ptime,ts->steps-1,ts->steps);
3476:     } else {
3477:       PetscViewerASCIIPrintf(viewer,"%D TS dt %g time %g%s",step,(double)ts->time_step,(double)ptime,ts->steprollback ? " (r)\n" : "\n");
3478:     }
3479:     PetscViewerASCIISubtractTab(viewer,((PetscObject)ts)->tablevel);
3480:   } else if (ibinary) {
3481:     PetscMPIInt rank;
3482:     MPI_Comm_rank(PetscObjectComm((PetscObject)viewer),&rank);
3483:     if (!rank) {
3484:       PetscBool skipHeader;
3485:       PetscInt  classid = REAL_FILE_CLASSID;

3487:       PetscViewerBinaryGetSkipHeader(viewer,&skipHeader);
3488:       if (!skipHeader) {
3489:          PetscViewerBinaryWrite(viewer,&classid,1,PETSC_INT,PETSC_FALSE);
3490:        }
3491:       PetscRealView(1,&ptime,viewer);
3492:     } else {
3493:       PetscRealView(0,&ptime,viewer);
3494:     }
3495:   }
3496:   PetscViewerPopFormat(viewer);
3497:   return(0);
3498: }

3500: /*@C
3501:    TSMonitorExtreme - Prints the extreme values of the solution at each timestep

3503:    Level: intermediate

3505: .seealso:  TSMonitorSet()
3506: @*/
3507: PetscErrorCode TSMonitorExtreme(TS ts,PetscInt step,PetscReal ptime,Vec v,PetscViewerAndFormat *vf)
3508: {
3510:   PetscViewer    viewer =  vf->viewer;
3511:   PetscBool      iascii;
3512:   PetscReal      max,min;


3517:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERASCII,&iascii);
3518:   PetscViewerPushFormat(viewer,vf->format);
3519:   if (iascii) {
3520:     VecMax(v,NULL,&max);
3521:     VecMin(v,NULL,&min);
3522:     PetscViewerASCIIAddTab(viewer,((PetscObject)ts)->tablevel);
3523:     PetscViewerASCIIPrintf(viewer,"%D TS dt %g time %g%s max %g min %g\n",step,(double)ts->time_step,(double)ptime,ts->steprollback ? " (r)" : "",(double)max,(double)min);
3524:     PetscViewerASCIISubtractTab(viewer,((PetscObject)ts)->tablevel);
3525:   }
3526:   PetscViewerPopFormat(viewer);
3527:   return(0);
3528: }

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

3533:    Collective on TS

3535:    Input Argument:
3536: +  ts - time stepping context
3537: -  t - time to interpolate to

3539:    Output Argument:
3540: .  U - state at given time

3542:    Level: intermediate

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

3547: .seealso: TSSetExactFinalTime(), TSSolve()
3548: @*/
3549: PetscErrorCode TSInterpolate(TS ts,PetscReal t,Vec U)
3550: {

3556:   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);
3557:   if (!ts->ops->interpolate) SETERRQ1(PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"%s does not provide interpolation",((PetscObject)ts)->type_name);
3558:   (*ts->ops->interpolate)(ts,t,U);
3559:   return(0);
3560: }

3562: /*@
3563:    TSStep - Steps one time step

3565:    Collective on TS

3567:    Input Parameter:
3568: .  ts - the TS context obtained from TSCreate()

3570:    Level: developer

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

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

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

3581: .seealso: TSCreate(), TSSetUp(), TSDestroy(), TSSolve(), TSSetPreStep(), TSSetPreStage(), TSSetPostStage(), TSInterpolate()
3582: @*/
3583: PetscErrorCode  TSStep(TS ts)
3584: {
3585:   PetscErrorCode   ierr;
3586:   static PetscBool cite = PETSC_FALSE;
3587:   PetscReal        ptime;

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

3599:   TSSetUp(ts);
3600:   TSTrajectorySetUp(ts->trajectory,ts);

3602:   if (ts->max_time >= PETSC_MAX_REAL && ts->max_steps == PETSC_MAX_INT) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_ARG_WRONGSTATE,"You must call TSSetMaxTime() or TSSetMaxSteps(), or use -ts_max_time <time> or -ts_max_steps <steps>");
3603:   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()");
3604:   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");

3606:   if (!ts->steps) ts->ptime_prev = ts->ptime;
3607:   ptime = ts->ptime; ts->ptime_prev_rollback = ts->ptime_prev;
3608:   ts->reason = TS_CONVERGED_ITERATING;
3609:   if (!ts->ops->step) SETERRQ1(PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"TSStep not implemented for type '%s'",((PetscObject)ts)->type_name);
3610:   PetscLogEventBegin(TS_Step,ts,0,0,0);
3611:   (*ts->ops->step)(ts);
3612:   PetscLogEventEnd(TS_Step,ts,0,0,0);
3613:   ts->ptime_prev = ptime;
3614:   ts->steps++;
3615:   ts->steprollback = PETSC_FALSE;
3616:   ts->steprestart  = PETSC_FALSE;

3618:   if (ts->reason < 0) {
3619:     if (ts->errorifstepfailed) {
3620:       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]);
3621:       else SETERRQ1(PetscObjectComm((PetscObject)ts),PETSC_ERR_NOT_CONVERGED,"TSStep has failed due to %s",TSConvergedReasons[ts->reason]);
3622:     }
3623:   } else if (!ts->reason) {
3624:     if (ts->steps >= ts->max_steps) ts->reason = TS_CONVERGED_ITS;
3625:     else if (ts->ptime >= ts->max_time) ts->reason = TS_CONVERGED_TIME;
3626:   }
3627:   return(0);
3628: }

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

3634:    Collective on TS

3636:    Input Arguments:
3637: +  ts - time stepping context
3638: .  wnormtype - norm type, either NORM_2 or NORM_INFINITY
3639: -  order - optional, desired order for the error evaluation or PETSC_DECIDE

3641:    Output Arguments:
3642: +  order - optional, the actual order of the error evaluation
3643: -  wlte - the weighted local truncation error norm

3645:    Level: advanced

3647:    Notes:
3648:    If the timestepper cannot evaluate the error in a particular step
3649:    (eg. in the first step or restart steps after event handling),
3650:    this routine returns wlte=-1.0 .

3652: .seealso: TSStep(), TSAdapt, TSErrorWeightedNorm()
3653: @*/
3654: PetscErrorCode TSEvaluateWLTE(TS ts,NormType wnormtype,PetscInt *order,PetscReal *wlte)
3655: {

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

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

3674:    Collective on TS

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

3681:    Output Arguments:
3682: .  U - state at the end of the current step

3684:    Level: advanced

3686:    Notes:
3687:    This function cannot be called until all stages have been evaluated.
3688:    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.

3690: .seealso: TSStep(), TSAdapt
3691: @*/
3692: PetscErrorCode TSEvaluateStep(TS ts,PetscInt order,Vec U,PetscBool *done)
3693: {

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

3705: /*@C
3706:   TSGetComputeInitialCondition - Get the function used to automatically compute an initial condition for the timestepping.

3708:   Not collective

3710:   Input Argument:
3711: . ts        - time stepping context

3713:   Output Argument:
3714: . initConditions - The function which computes an initial condition

3716:    Level: advanced

3718:    Notes:
3719:    The calling sequence for the function is
3720: $ initCondition(TS ts, Vec u)
3721: $ ts - The timestepping context
3722: $ u  - The input vector in which the initial condition is stored

3724: .seealso: TSSetComputeInitialCondition(), TSComputeInitialCondition()
3725: @*/
3726: PetscErrorCode TSGetComputeInitialCondition(TS ts, PetscErrorCode (**initCondition)(TS, Vec))
3727: {
3731:   *initCondition = ts->ops->initcondition;
3732:   return(0);
3733: }

3735: /*@C
3736:   TSSetComputeInitialCondition - Set the function used to automatically compute an initial condition for the timestepping.

3738:   Logically collective on ts

3740:   Input Arguments:
3741: + ts        - time stepping context
3742: - initCondition - The function which computes an initial condition

3744:   Level: advanced

3746:   Notes:
3747:   The calling sequence for the function is
3748: $ initCondition(TS ts, Vec u)
3749: $ ts - The timestepping context
3750: $ u  - The input vector in which the initial condition is stored

3752: .seealso: TSGetComputeInitialCondition(), TSComputeInitialCondition()
3753: @*/
3754: PetscErrorCode TSSetComputeInitialCondition(TS ts, PetscErrorCode (*initCondition)(TS, Vec))
3755: {
3759:   ts->ops->initcondition = initCondition;
3760:   return(0);
3761: }

3763: /*@
3764:   TSComputeInitialCondition - Compute an initial condition for the timestepping using the function previously set.

3766:   Collective on ts

3768:   Input Arguments:
3769: + ts - time stepping context
3770: - u  - The Vec to store the condition in which will be used in TSSolve()

3772:   Level: advanced

3774:   Notes:
3775:   The calling sequence for the function is
3776: $ initCondition(TS ts, Vec u)
3777: $ ts - The timestepping context
3778: $ u  - The input vector in which the initial condition is stored

3780: .seealso: TSGetComputeInitialCondition(), TSSetComputeInitialCondition(), TSSolve()
3781: @*/
3782: PetscErrorCode TSComputeInitialCondition(TS ts, Vec u)
3783: {

3789:   if (ts->ops->initcondition) {(*ts->ops->initcondition)(ts, u);}
3790:   return(0);
3791: }

3793: /*@C
3794:   TSGetComputeExactError - Get the function used to automatically compute the exact error for the timestepping.

3796:   Not collective

3798:   Input Argument:
3799: . ts         - time stepping context

3801:   Output Argument:
3802: . exactError - The function which computes the solution error

3804:   Level: advanced

3806:   Notes:
3807:   The calling sequence for the function is
3808: $ exactError(TS ts, Vec u)
3809: $ ts - The timestepping context
3810: $ u  - The approximate solution vector
3811: $ e  - The input vector in which the error is stored

3813: .seealso: TSGetComputeExactError(), TSComputeExactError()
3814: @*/
3815: PetscErrorCode TSGetComputeExactError(TS ts, PetscErrorCode (**exactError)(TS, Vec, Vec))
3816: {
3820:   *exactError = ts->ops->exacterror;
3821:   return(0);
3822: }

3824: /*@C
3825:   TSSetComputeExactError - Set the function used to automatically compute the exact error for the timestepping.

3827:   Logically collective on ts

3829:   Input Arguments:
3830: + ts         - time stepping context
3831: - exactError - The function which computes the solution error

3833:   Level: advanced

3835:   Notes:
3836:   The calling sequence for the function is
3837: $ exactError(TS ts, Vec u)
3838: $ ts - The timestepping context
3839: $ u  - The approximate solution vector
3840: $ e  - The input vector in which the error is stored

3842: .seealso: TSGetComputeExactError(), TSComputeExactError()
3843: @*/
3844: PetscErrorCode TSSetComputeExactError(TS ts, PetscErrorCode (*exactError)(TS, Vec, Vec))
3845: {
3849:   ts->ops->exacterror = exactError;
3850:   return(0);
3851: }

3853: /*@
3854:   TSComputeExactError - Compute the solution error for the timestepping using the function previously set.

3856:   Collective on ts

3858:   Input Arguments:
3859: + ts - time stepping context
3860: . u  - The approximate solution
3861: - e  - The Vec used to store the error

3863:   Level: advanced

3865:   Notes:
3866:   The calling sequence for the function is
3867: $ exactError(TS ts, Vec u)
3868: $ ts - The timestepping context
3869: $ u  - The approximate solution vector
3870: $ e  - The input vector in which the error is stored

3872: .seealso: TSGetComputeInitialCondition(), TSSetComputeInitialCondition(), TSSolve()
3873: @*/
3874: PetscErrorCode TSComputeExactError(TS ts, Vec u, Vec e)
3875: {

3882:   if (ts->ops->exacterror) {(*ts->ops->exacterror)(ts, u, e);}
3883:   return(0);
3884: }

3886: /*@
3887:    TSSolve - Steps the requested number of timesteps.

3889:    Collective on TS

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

3896:    Level: beginner

3898:    Notes:
3899:    The final time returned by this function may be different from the time of the internally
3900:    held state accessible by TSGetSolution() and TSGetTime() because the method may have
3901:    stepped over the final time.

3903: .seealso: TSCreate(), TSSetSolution(), TSStep(), TSGetTime(), TSGetSolveTime()
3904: @*/
3905: PetscErrorCode TSSolve(TS ts,Vec u)
3906: {
3907:   Vec               solution;
3908:   PetscErrorCode    ierr;


3914:   if (ts->exact_final_time == TS_EXACTFINALTIME_INTERPOLATE && u) {   /* Need ts->vec_sol to be distinct so it is not overwritten when we interpolate at the end */
3915:     if (!ts->vec_sol || u == ts->vec_sol) {
3916:       VecDuplicate(u,&solution);
3917:       TSSetSolution(ts,solution);
3918:       VecDestroy(&solution); /* grant ownership */
3919:     }
3920:     VecCopy(u,ts->vec_sol);
3921:     if (ts->forward_solve) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"Sensitivity analysis does not support the mode TS_EXACTFINALTIME_INTERPOLATE");
3922:   } else if (u) {
3923:     TSSetSolution(ts,u);
3924:   }
3925:   TSSetUp(ts);
3926:   TSTrajectorySetUp(ts->trajectory,ts);

3928:   if (ts->max_time >= PETSC_MAX_REAL && ts->max_steps == PETSC_MAX_INT) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_ARG_WRONGSTATE,"You must call TSSetMaxTime() or TSSetMaxSteps(), or use -ts_max_time <time> or -ts_max_steps <steps>");
3929:   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()");
3930:   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");

3932:   if (ts->forward_solve) {
3933:     TSForwardSetUp(ts);
3934:   }

3936:   /* reset number of steps only when the step is not restarted. ARKIMEX
3937:      restarts the step after an event. Resetting these counters in such case causes
3938:      TSTrajectory to incorrectly save the output files
3939:   */
3940:   /* reset time step and iteration counters */
3941:   if (!ts->steps) {
3942:     ts->ksp_its           = 0;
3943:     ts->snes_its          = 0;
3944:     ts->num_snes_failures = 0;
3945:     ts->reject            = 0;
3946:     ts->steprestart       = PETSC_TRUE;
3947:     ts->steprollback      = PETSC_FALSE;
3948:   }
3949:   if (ts->exact_final_time == TS_EXACTFINALTIME_MATCHSTEP && ts->ptime < ts->max_time && ts->ptime + ts->time_step > ts->max_time) ts->time_step = ts->max_time - ts->ptime;
3950:   ts->reason = TS_CONVERGED_ITERATING;

3952:   {
3953:     PetscViewer       viewer;
3954:     PetscViewerFormat format;
3955:     PetscBool         flg;
3956:     static PetscBool  incall = PETSC_FALSE;

3958:     if (!incall) {
3959:       /* Estimate the convergence rate of the time discretization */
3960:       PetscOptionsGetViewer(PetscObjectComm((PetscObject) ts),((PetscObject)ts)->options, ((PetscObject) ts)->prefix, "-ts_convergence_estimate", &viewer, &format, &flg);
3961:       if (flg) {
3962:         PetscConvEst conv;
3963:         DM           dm;
3964:         PetscReal   *alpha; /* Convergence rate of the solution error for each field in the L_2 norm */
3965:         PetscInt     Nf;

3967:         incall = PETSC_TRUE;
3968:         TSGetDM(ts, &dm);
3969:         DMGetNumFields(dm, &Nf);
3970:         PetscCalloc1(PetscMax(Nf, 1), &alpha);
3971:         PetscConvEstCreate(PetscObjectComm((PetscObject) ts), &conv);
3972:         PetscConvEstUseTS(conv);
3973:         PetscConvEstSetSolver(conv, (PetscObject) ts);
3974:         PetscConvEstSetFromOptions(conv);
3975:         PetscConvEstSetUp(conv);
3976:         PetscConvEstGetConvRate(conv, alpha);
3977:         PetscViewerPushFormat(viewer, format);
3978:         PetscConvEstRateView(conv, alpha, viewer);
3979:         PetscViewerPopFormat(viewer);
3980:         PetscViewerDestroy(&viewer);
3981:         PetscConvEstDestroy(&conv);
3982:         PetscFree(alpha);
3983:         incall = PETSC_FALSE;
3984:       }
3985:     }
3986:   }

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

3990:   if (ts->ops->solve) { /* This private interface is transitional and should be removed when all implementations are updated. */
3991:     (*ts->ops->solve)(ts);
3992:     if (u) {VecCopy(ts->vec_sol,u);}
3993:     ts->solvetime = ts->ptime;
3994:     solution = ts->vec_sol;
3995:   } else { /* Step the requested number of timesteps. */
3996:     if (ts->steps >= ts->max_steps) ts->reason = TS_CONVERGED_ITS;
3997:     else if (ts->ptime >= ts->max_time) ts->reason = TS_CONVERGED_TIME;

3999:     if (!ts->steps) {
4000:       TSTrajectorySet(ts->trajectory,ts,ts->steps,ts->ptime,ts->vec_sol);
4001:       TSEventInitialize(ts->event,ts,ts->ptime,ts->vec_sol);
4002:     }

4004:     while (!ts->reason) {
4005:       TSMonitor(ts,ts->steps,ts->ptime,ts->vec_sol);
4006:       if (!ts->steprollback) {
4007:         TSPreStep(ts);
4008:       }
4009:       TSStep(ts);
4010:       if (ts->testjacobian) {
4011:         TSRHSJacobianTest(ts,NULL);
4012:       }
4013:       if (ts->testjacobiantranspose) {
4014:         TSRHSJacobianTestTranspose(ts,NULL);
4015:       }
4016:       if (ts->quadraturets && ts->costintegralfwd) { /* Must evaluate the cost integral before event is handled. The cost integral value can also be rolled back. */
4017:         TSForwardCostIntegral(ts);
4018:       }
4019:       if (ts->forward_solve) { /* compute forward sensitivities before event handling because postevent() may change RHS and jump conditions may have to be applied */
4020:         TSForwardStep(ts);
4021:       }
4022:       TSPostEvaluate(ts);
4023:       TSEventHandler(ts); /* The right-hand side may be changed due to event. Be careful with Any computation using the RHS information after this point. */
4024:       if (ts->steprollback) {
4025:         TSPostEvaluate(ts);
4026:       }
4027:       if (!ts->steprollback) {
4028:         TSTrajectorySet(ts->trajectory,ts,ts->steps,ts->ptime,ts->vec_sol);
4029:         TSPostStep(ts);
4030:       }
4031:     }
4032:     TSMonitor(ts,ts->steps,ts->ptime,ts->vec_sol);

4034:     if (ts->exact_final_time == TS_EXACTFINALTIME_INTERPOLATE && ts->ptime > ts->max_time) {
4035:       TSInterpolate(ts,ts->max_time,u);
4036:       ts->solvetime = ts->max_time;
4037:       solution = u;
4038:       TSMonitor(ts,-1,ts->solvetime,solution);
4039:     } else {
4040:       if (u) {VecCopy(ts->vec_sol,u);}
4041:       ts->solvetime = ts->ptime;
4042:       solution = ts->vec_sol;
4043:     }
4044:   }

4046:   TSViewFromOptions(ts,NULL,"-ts_view");
4047:   VecViewFromOptions(solution,NULL,"-ts_view_solution");
4048:   PetscObjectSAWsBlock((PetscObject)ts);
4049:   if (ts->adjoint_solve) {
4050:     TSAdjointSolve(ts);
4051:   }
4052:   return(0);
4053: }

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

4058:    Collective on TS

4060:    Input Parameters:
4061: +  ts - time stepping context obtained from TSCreate()
4062: .  step - step number that has just completed
4063: .  ptime - model time of the state
4064: -  u - state at the current model time

4066:    Notes:
4067:    TSMonitor() is typically used automatically within the time stepping implementations.
4068:    Users would almost never call this routine directly.

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

4072:    Level: developer

4074: @*/
4075: PetscErrorCode TSMonitor(TS ts,PetscInt step,PetscReal ptime,Vec u)
4076: {
4077:   DM             dm;
4078:   PetscInt       i,n = ts->numbermonitors;


4085:   TSGetDM(ts,&dm);
4086:   DMSetOutputSequenceNumber(dm,step,ptime);

4088:   VecLockReadPush(u);
4089:   for (i=0; i<n; i++) {
4090:     (*ts->monitor[i])(ts,step,ptime,u,ts->monitorcontext[i]);
4091:   }
4092:   VecLockReadPop(u);
4093:   return(0);
4094: }

4096: /* ------------------------------------------------------------------------*/
4097: /*@C
4098:    TSMonitorLGCtxCreate - Creates a TSMonitorLGCtx context for use with
4099:    TS to monitor the solution process graphically in various ways

4101:    Collective on TS

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

4110:    Output Parameter:
4111: .  ctx - the context

4113:    Options Database Key:
4114: +  -ts_monitor_lg_timestep - automatically sets line graph monitor
4115: +  -ts_monitor_lg_timestep_log - automatically sets line graph monitor
4116: .  -ts_monitor_lg_solution - monitor the solution (or certain values of the solution by calling TSMonitorLGSetDisplayVariables() or TSMonitorLGCtxSetDisplayVariables())
4117: .  -ts_monitor_lg_error -  monitor the error
4118: .  -ts_monitor_lg_ksp_iterations - monitor the number of KSP iterations needed for each timestep
4119: .  -ts_monitor_lg_snes_iterations - monitor the number of SNES iterations needed for each timestep
4120: -  -lg_use_markers <true,false> - mark the data points (at each time step) on the plot; default is true

4122:    Notes:
4123:    Use TSMonitorLGCtxDestroy() to destroy.

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

4127:    Many of the functions that control the monitoring have two forms: TSMonitorLGSet/GetXXXX() and TSMonitorLGCtxSet/GetXXXX() the first take a TS object as the
4128:    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
4129:    as the first argument.

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

4133:    Level: intermediate

4135: .seealso: TSMonitorLGTimeStep(), TSMonitorSet(), TSMonitorLGSolution(), TSMonitorLGError(), TSMonitorDefault(), VecView(),
4136:            TSMonitorLGCtxCreate(), TSMonitorLGCtxSetVariableNames(), TSMonitorLGCtxGetVariableNames(),
4137:            TSMonitorLGSetVariableNames(), TSMonitorLGGetVariableNames(), TSMonitorLGSetDisplayVariables(), TSMonitorLGCtxSetDisplayVariables(),
4138:            TSMonitorLGCtxSetTransform(), TSMonitorLGSetTransform(), TSMonitorLGError(), TSMonitorLGSNESIterations(), TSMonitorLGKSPIterations(),
4139:            TSMonitorEnvelopeCtxCreate(), TSMonitorEnvelopeGetBounds(), TSMonitorEnvelopeCtxDestroy(), TSMonitorEnvelop()

4141: @*/
4142: PetscErrorCode  TSMonitorLGCtxCreate(MPI_Comm comm,const char host[],const char label[],int x,int y,int m,int n,PetscInt howoften,TSMonitorLGCtx *ctx)
4143: {
4144:   PetscDraw      draw;

4148:   PetscNew(ctx);
4149:   PetscDrawCreate(comm,host,label,x,y,m,n,&draw);
4150:   PetscDrawSetFromOptions(draw);
4151:   PetscDrawLGCreate(draw,1,&(*ctx)->lg);
4152:   PetscDrawLGSetFromOptions((*ctx)->lg);
4153:   PetscDrawDestroy(&draw);
4154:   (*ctx)->howoften = howoften;
4155:   return(0);
4156: }

4158: PetscErrorCode TSMonitorLGTimeStep(TS ts,PetscInt step,PetscReal ptime,Vec v,void *monctx)
4159: {
4160:   TSMonitorLGCtx ctx = (TSMonitorLGCtx) monctx;
4161:   PetscReal      x   = ptime,y;

4165:   if (step < 0) return(0); /* -1 indicates an interpolated solution */
4166:   if (!step) {
4167:     PetscDrawAxis axis;
4168:     const char *ylabel = ctx->semilogy ? "Log Time Step" : "Time Step";
4169:     PetscDrawLGGetAxis(ctx->lg,&axis);
4170:     PetscDrawAxisSetLabels(axis,"Timestep as function of time","Time",ylabel);
4171:     PetscDrawLGReset(ctx->lg);
4172:   }
4173:   TSGetTimeStep(ts,&y);
4174:   if (ctx->semilogy) y = PetscLog10Real(y);
4175:   PetscDrawLGAddPoint(ctx->lg,&x,&y);
4176:   if (((ctx->howoften > 0) && (!(step % ctx->howoften))) || ((ctx->howoften == -1) && ts->reason)) {
4177:     PetscDrawLGDraw(ctx->lg);
4178:     PetscDrawLGSave(ctx->lg);
4179:   }
4180:   return(0);
4181: }

4183: /*@C
4184:    TSMonitorLGCtxDestroy - Destroys a line graph context that was created
4185:    with TSMonitorLGCtxCreate().

4187:    Collective on TSMonitorLGCtx

4189:    Input Parameter:
4190: .  ctx - the monitor context

4192:    Level: intermediate

4194: .seealso: TSMonitorLGCtxCreate(),  TSMonitorSet(), TSMonitorLGTimeStep();
4195: @*/
4196: PetscErrorCode  TSMonitorLGCtxDestroy(TSMonitorLGCtx *ctx)
4197: {

4201:   if ((*ctx)->transformdestroy) {
4202:     ((*ctx)->transformdestroy)((*ctx)->transformctx);
4203:   }
4204:   PetscDrawLGDestroy(&(*ctx)->lg);
4205:   PetscStrArrayDestroy(&(*ctx)->names);
4206:   PetscStrArrayDestroy(&(*ctx)->displaynames);
4207:   PetscFree((*ctx)->displayvariables);
4208:   PetscFree((*ctx)->displayvalues);
4209:   PetscFree(*ctx);
4210:   return(0);
4211: }

4213: /*

4215:   Creates a TS Monitor SPCtx for use with DM Swarm particle visualizations

4217: */
4218: PetscErrorCode TSMonitorSPCtxCreate(MPI_Comm comm,const char host[],const char label[],int x,int y,int m,int n,PetscInt howoften,TSMonitorSPCtx *ctx)
4219: {
4220:   PetscDraw      draw;

4224:   PetscNew(ctx);
4225:   PetscDrawCreate(comm,host,label,x,y,m,n,&draw);
4226:   PetscDrawSetFromOptions(draw);
4227:   PetscDrawSPCreate(draw,1,&(*ctx)->sp);
4228:   PetscDrawDestroy(&draw);
4229:   (*ctx)->howoften = howoften;
4230:   return(0);

4232: }

4234: /*
4235:   Destroys a TSMonitorSPCtx that was created with TSMonitorSPCtxCreate
4236: */
4237: PetscErrorCode TSMonitorSPCtxDestroy(TSMonitorSPCtx *ctx)
4238: {


4243:   PetscDrawSPDestroy(&(*ctx)->sp);
4244:   PetscFree(*ctx);

4246:   return(0);

4248: }

4250: /*@
4251:    TSGetTime - Gets the time of the most recently completed step.

4253:    Not Collective

4255:    Input Parameter:
4256: .  ts - the TS context obtained from TSCreate()

4258:    Output Parameter:
4259: .  t  - the current time. This time may not corresponds to the final time set with TSSetMaxTime(), use TSGetSolveTime().

4261:    Level: beginner

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

4267: .seealso:  TSGetSolveTime(), TSSetTime(), TSGetTimeStep(), TSGetStepNumber()

4269: @*/
4270: PetscErrorCode  TSGetTime(TS ts,PetscReal *t)
4271: {
4275:   *t = ts->ptime;
4276:   return(0);
4277: }

4279: /*@
4280:    TSGetPrevTime - Gets the starting time of the previously completed step.

4282:    Not Collective

4284:    Input Parameter:
4285: .  ts - the TS context obtained from TSCreate()

4287:    Output Parameter:
4288: .  t  - the previous time

4290:    Level: beginner

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

4294: @*/
4295: PetscErrorCode  TSGetPrevTime(TS ts,PetscReal *t)
4296: {
4300:   *t = ts->ptime_prev;
4301:   return(0);
4302: }

4304: /*@
4305:    TSSetTime - Allows one to reset the time.

4307:    Logically Collective on TS

4309:    Input Parameters:
4310: +  ts - the TS context obtained from TSCreate()
4311: -  time - the time

4313:    Level: intermediate

4315: .seealso: TSGetTime(), TSSetMaxSteps()

4317: @*/
4318: PetscErrorCode  TSSetTime(TS ts, PetscReal t)
4319: {
4323:   ts->ptime = t;
4324:   return(0);
4325: }

4327: /*@C
4328:    TSSetOptionsPrefix - Sets the prefix used for searching for all
4329:    TS options in the database.

4331:    Logically Collective on TS

4333:    Input Parameter:
4334: +  ts     - The TS context
4335: -  prefix - The prefix to prepend to all option names

4337:    Notes:
4338:    A hyphen (-) must NOT be given at the beginning of the prefix name.
4339:    The first character of all runtime options is AUTOMATICALLY the
4340:    hyphen.

4342:    Level: advanced

4344: .seealso: TSSetFromOptions()

4346: @*/
4347: PetscErrorCode  TSSetOptionsPrefix(TS ts,const char prefix[])
4348: {
4350:   SNES           snes;

4354:   PetscObjectSetOptionsPrefix((PetscObject)ts,prefix);
4355:   TSGetSNES(ts,&snes);
4356:   SNESSetOptionsPrefix(snes,prefix);
4357:   return(0);
4358: }

4360: /*@C
4361:    TSAppendOptionsPrefix - Appends to the prefix used for searching for all
4362:    TS options in the database.

4364:    Logically Collective on TS

4366:    Input Parameter:
4367: +  ts     - The TS context
4368: -  prefix - The prefix to prepend to all option names

4370:    Notes:
4371:    A hyphen (-) must NOT be given at the beginning of the prefix name.
4372:    The first character of all runtime options is AUTOMATICALLY the
4373:    hyphen.

4375:    Level: advanced

4377: .seealso: TSGetOptionsPrefix()

4379: @*/
4380: PetscErrorCode  TSAppendOptionsPrefix(TS ts,const char prefix[])
4381: {
4383:   SNES           snes;

4387:   PetscObjectAppendOptionsPrefix((PetscObject)ts,prefix);
4388:   TSGetSNES(ts,&snes);
4389:   SNESAppendOptionsPrefix(snes,prefix);
4390:   return(0);
4391: }

4393: /*@C
4394:    TSGetOptionsPrefix - Sets the prefix used for searching for all
4395:    TS options in the database.

4397:    Not Collective

4399:    Input Parameter:
4400: .  ts - The TS context

4402:    Output Parameter:
4403: .  prefix - A pointer to the prefix string used

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

4409:    Level: intermediate

4411: .seealso: TSAppendOptionsPrefix()
4412: @*/
4413: PetscErrorCode  TSGetOptionsPrefix(TS ts,const char *prefix[])
4414: {

4420:   PetscObjectGetOptionsPrefix((PetscObject)ts,prefix);
4421:   return(0);
4422: }

4424: /*@C
4425:    TSGetRHSJacobian - Returns the Jacobian J at the present timestep.

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

4429:    Input Parameter:
4430: .  ts  - The TS context obtained from TSCreate()

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

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

4441:    Level: intermediate

4443: .seealso: TSGetTimeStep(), TSGetMatrices(), TSGetTime(), TSGetStepNumber()

4445: @*/
4446: PetscErrorCode  TSGetRHSJacobian(TS ts,Mat *Amat,Mat *Pmat,TSRHSJacobian *func,void **ctx)
4447: {
4449:   DM             dm;

4452:   if (Amat || Pmat) {
4453:     SNES snes;
4454:     TSGetSNES(ts,&snes);
4455:     SNESSetUpMatrices(snes);
4456:     SNESGetJacobian(snes,Amat,Pmat,NULL,NULL);
4457:   }
4458:   TSGetDM(ts,&dm);
4459:   DMTSGetRHSJacobian(dm,func,ctx);
4460:   return(0);
4461: }

4463: /*@C
4464:    TSGetIJacobian - Returns the implicit Jacobian at the present timestep.

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

4468:    Input Parameter:
4469: .  ts  - The TS context obtained from TSCreate()

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

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

4480:    Level: advanced

4482: .seealso: TSGetTimeStep(), TSGetRHSJacobian(), TSGetMatrices(), TSGetTime(), TSGetStepNumber()

4484: @*/
4485: PetscErrorCode  TSGetIJacobian(TS ts,Mat *Amat,Mat *Pmat,TSIJacobian *f,void **ctx)
4486: {
4488:   DM             dm;

4491:   if (Amat || Pmat) {
4492:     SNES snes;
4493:     TSGetSNES(ts,&snes);
4494:     SNESSetUpMatrices(snes);
4495:     SNESGetJacobian(snes,Amat,Pmat,NULL,NULL);
4496:   }
4497:   TSGetDM(ts,&dm);
4498:   DMTSGetIJacobian(dm,f,ctx);
4499:   return(0);
4500: }

4502: /*@C
4503:    TSMonitorDrawSolution - Monitors progress of the TS solvers by calling
4504:    VecView() for the solution at each timestep

4506:    Collective on TS

4508:    Input Parameters:
4509: +  ts - the TS context
4510: .  step - current time-step
4511: .  ptime - current time
4512: -  dummy - either a viewer or NULL

4514:    Options Database:
4515: .   -ts_monitor_draw_solution_initial - show initial solution as well as current solution

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

4521:    Level: intermediate

4523: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView()
4524: @*/
4525: PetscErrorCode  TSMonitorDrawSolution(TS ts,PetscInt step,PetscReal ptime,Vec u,void *dummy)
4526: {
4527:   PetscErrorCode   ierr;
4528:   TSMonitorDrawCtx ictx = (TSMonitorDrawCtx)dummy;
4529:   PetscDraw        draw;

4532:   if (!step && ictx->showinitial) {
4533:     if (!ictx->initialsolution) {
4534:       VecDuplicate(u,&ictx->initialsolution);
4535:     }
4536:     VecCopy(u,ictx->initialsolution);
4537:   }
4538:   if (!(((ictx->howoften > 0) && (!(step % ictx->howoften))) || ((ictx->howoften == -1) && ts->reason))) return(0);

4540:   if (ictx->showinitial) {
4541:     PetscReal pause;
4542:     PetscViewerDrawGetPause(ictx->viewer,&pause);
4543:     PetscViewerDrawSetPause(ictx->viewer,0.0);
4544:     VecView(ictx->initialsolution,ictx->viewer);
4545:     PetscViewerDrawSetPause(ictx->viewer,pause);
4546:     PetscViewerDrawSetHold(ictx->viewer,PETSC_TRUE);
4547:   }
4548:   VecView(u,ictx->viewer);
4549:   if (ictx->showtimestepandtime) {
4550:     PetscReal xl,yl,xr,yr,h;
4551:     char      time[32];

4553:     PetscViewerDrawGetDraw(ictx->viewer,0,&draw);
4554:     PetscSNPrintf(time,32,"Timestep %d Time %g",(int)step,(double)ptime);
4555:     PetscDrawGetCoordinates(draw,&xl,&yl,&xr,&yr);
4556:     h    = yl + .95*(yr - yl);
4557:     PetscDrawStringCentered(draw,.5*(xl+xr),h,PETSC_DRAW_BLACK,time);
4558:     PetscDrawFlush(draw);
4559:   }

4561:   if (ictx->showinitial) {
4562:     PetscViewerDrawSetHold(ictx->viewer,PETSC_FALSE);
4563:   }
4564:   return(0);
4565: }

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

4570:    Collective on TS

4572:    Input Parameters:
4573: +  ts - the TS context
4574: .  step - current time-step
4575: .  ptime - current time
4576: -  dummy - either a viewer or NULL

4578:    Level: intermediate

4580: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView()
4581: @*/
4582: PetscErrorCode  TSMonitorDrawSolutionPhase(TS ts,PetscInt step,PetscReal ptime,Vec u,void *dummy)
4583: {
4584:   PetscErrorCode    ierr;
4585:   TSMonitorDrawCtx  ictx = (TSMonitorDrawCtx)dummy;
4586:   PetscDraw         draw;
4587:   PetscDrawAxis     axis;
4588:   PetscInt          n;
4589:   PetscMPIInt       size;
4590:   PetscReal         U0,U1,xl,yl,xr,yr,h;
4591:   char              time[32];
4592:   const PetscScalar *U;

4595:   MPI_Comm_size(PetscObjectComm((PetscObject)ts),&size);
4596:   if (size != 1) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"Only allowed for sequential runs");
4597:   VecGetSize(u,&n);
4598:   if (n != 2) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"Only for ODEs with two unknowns");

4600:   PetscViewerDrawGetDraw(ictx->viewer,0,&draw);
4601:   PetscViewerDrawGetDrawAxis(ictx->viewer,0,&axis);
4602:   PetscDrawAxisGetLimits(axis,&xl,&xr,&yl,&yr);
4603:   if (!step) {
4604:     PetscDrawClear(draw);
4605:     PetscDrawAxisDraw(axis);
4606:   }

4608:   VecGetArrayRead(u,&U);
4609:   U0 = PetscRealPart(U[0]);
4610:   U1 = PetscRealPart(U[1]);
4611:   VecRestoreArrayRead(u,&U);
4612:   if ((U0 < xl) || (U1 < yl) || (U0 > xr) || (U1 > yr)) return(0);

4614:   PetscDrawCollectiveBegin(draw);
4615:   PetscDrawPoint(draw,U0,U1,PETSC_DRAW_BLACK);
4616:   if (ictx->showtimestepandtime) {
4617:     PetscDrawGetCoordinates(draw,&xl,&yl,&xr,&yr);
4618:     PetscSNPrintf(time,32,"Timestep %d Time %g",(int)step,(double)ptime);
4619:     h    = yl + .95*(yr - yl);
4620:     PetscDrawStringCentered(draw,.5*(xl+xr),h,PETSC_DRAW_BLACK,time);
4621:   }
4622:   PetscDrawCollectiveEnd(draw);
4623:   PetscDrawFlush(draw);
4624:   PetscDrawPause(draw);
4625:   PetscDrawSave(draw);
4626:   return(0);
4627: }

4629: /*@C
4630:    TSMonitorDrawCtxDestroy - Destroys the monitor context for TSMonitorDrawSolution()

4632:    Collective on TS

4634:    Input Parameters:
4635: .    ctx - the monitor context

4637:    Level: intermediate

4639: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorDrawSolution(), TSMonitorDrawError()
4640: @*/
4641: PetscErrorCode  TSMonitorDrawCtxDestroy(TSMonitorDrawCtx *ictx)
4642: {

4646:   PetscViewerDestroy(&(*ictx)->viewer);
4647:   VecDestroy(&(*ictx)->initialsolution);
4648:   PetscFree(*ictx);
4649:   return(0);
4650: }

4652: /*@C
4653:    TSMonitorDrawCtxCreate - Creates the monitor context for TSMonitorDrawCtx

4655:    Collective on TS

4657:    Input Parameter:
4658: .    ts - time-step context

4660:    Output Patameter:
4661: .    ctx - the monitor context

4663:    Options Database:
4664: .   -ts_monitor_draw_solution_initial - show initial solution as well as current solution

4666:    Level: intermediate

4668: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorDrawCtx()
4669: @*/
4670: PetscErrorCode  TSMonitorDrawCtxCreate(MPI_Comm comm,const char host[],const char label[],int x,int y,int m,int n,PetscInt howoften,TSMonitorDrawCtx *ctx)
4671: {
4672:   PetscErrorCode   ierr;

4675:   PetscNew(ctx);
4676:   PetscViewerDrawOpen(comm,host,label,x,y,m,n,&(*ctx)->viewer);
4677:   PetscViewerSetFromOptions((*ctx)->viewer);

4679:   (*ctx)->howoften    = howoften;
4680:   (*ctx)->showinitial = PETSC_FALSE;
4681:   PetscOptionsGetBool(NULL,NULL,"-ts_monitor_draw_solution_initial",&(*ctx)->showinitial,NULL);

4683:   (*ctx)->showtimestepandtime = PETSC_FALSE;
4684:   PetscOptionsGetBool(NULL,NULL,"-ts_monitor_draw_solution_show_time",&(*ctx)->showtimestepandtime,NULL);
4685:   return(0);
4686: }

4688: /*@C
4689:    TSMonitorDrawSolutionFunction - Monitors progress of the TS solvers by calling
4690:    VecView() for the solution provided by TSSetSolutionFunction() at each timestep

4692:    Collective on TS

4694:    Input Parameters:
4695: +  ts - the TS context
4696: .  step - current time-step
4697: .  ptime - current time
4698: -  dummy - either a viewer or NULL

4700:    Options Database:
4701: .  -ts_monitor_draw_solution_function - Monitor error graphically, requires user to have provided TSSetSolutionFunction()

4703:    Level: intermediate

4705: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSSetSolutionFunction()
4706: @*/
4707: PetscErrorCode  TSMonitorDrawSolutionFunction(TS ts,PetscInt step,PetscReal ptime,Vec u,void *dummy)
4708: {
4709:   PetscErrorCode   ierr;
4710:   TSMonitorDrawCtx ctx    = (TSMonitorDrawCtx)dummy;
4711:   PetscViewer      viewer = ctx->viewer;
4712:   Vec              work;

4715:   if (!(((ctx->howoften > 0) && (!(step % ctx->howoften))) || ((ctx->howoften == -1) && ts->reason))) return(0);
4716:   VecDuplicate(u,&work);
4717:   TSComputeSolutionFunction(ts,ptime,work);
4718:   VecView(work,viewer);
4719:   VecDestroy(&work);
4720:   return(0);
4721: }

4723: /*@C
4724:    TSMonitorDrawError - Monitors progress of the TS solvers by calling
4725:    VecView() for the error at each timestep

4727:    Collective on TS

4729:    Input Parameters:
4730: +  ts - the TS context
4731: .  step - current time-step
4732: .  ptime - current time
4733: -  dummy - either a viewer or NULL

4735:    Options Database:
4736: .  -ts_monitor_draw_error - Monitor error graphically, requires user to have provided TSSetSolutionFunction()

4738:    Level: intermediate

4740: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSSetSolutionFunction()
4741: @*/
4742: PetscErrorCode  TSMonitorDrawError(TS ts,PetscInt step,PetscReal ptime,Vec u,void *dummy)
4743: {
4744:   PetscErrorCode   ierr;
4745:   TSMonitorDrawCtx ctx    = (TSMonitorDrawCtx)dummy;
4746:   PetscViewer      viewer = ctx->viewer;
4747:   Vec              work;

4750:   if (!(((ctx->howoften > 0) && (!(step % ctx->howoften))) || ((ctx->howoften == -1) && ts->reason))) return(0);
4751:   VecDuplicate(u,&work);
4752:   TSComputeSolutionFunction(ts,ptime,work);
4753:   VecAXPY(work,-1.0,u);
4754:   VecView(work,viewer);
4755:   VecDestroy(&work);
4756:   return(0);
4757: }

4759:  #include <petsc/private/dmimpl.h>
4760: /*@
4761:    TSSetDM - Sets the DM that may be used by some nonlinear solvers or preconditioners under the TS

4763:    Logically Collective on ts

4765:    Input Parameters:
4766: +  ts - the ODE integrator object
4767: -  dm - the dm, cannot be NULL

4769:    Notes:
4770:    A DM can only be used for solving one problem at a time because information about the problem is stored on the DM,
4771:    even when not using interfaces like DMTSSetIFunction().  Use DMClone() to get a distinct DM when solving
4772:    different problems using the same function space.

4774:    Level: intermediate

4776: .seealso: TSGetDM(), SNESSetDM(), SNESGetDM()
4777: @*/
4778: PetscErrorCode  TSSetDM(TS ts,DM dm)
4779: {
4781:   SNES           snes;
4782:   DMTS           tsdm;

4787:   PetscObjectReference((PetscObject)dm);
4788:   if (ts->dm) {               /* Move the DMTS context over to the new DM unless the new DM already has one */
4789:     if (ts->dm->dmts && !dm->dmts) {
4790:       DMCopyDMTS(ts->dm,dm);
4791:       DMGetDMTS(ts->dm,&tsdm);
4792:       if (tsdm->originaldm == ts->dm) { /* Grant write privileges to the replacement DM */
4793:         tsdm->originaldm = dm;
4794:       }
4795:     }
4796:     DMDestroy(&ts->dm);
4797:   }
4798:   ts->dm = dm;

4800:   TSGetSNES(ts,&snes);
4801:   SNESSetDM(snes,dm);
4802:   return(0);
4803: }

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

4808:    Not Collective

4810:    Input Parameter:
4811: . ts - the preconditioner context

4813:    Output Parameter:
4814: .  dm - the dm

4816:    Level: intermediate

4818: .seealso: TSSetDM(), SNESSetDM(), SNESGetDM()
4819: @*/
4820: PetscErrorCode  TSGetDM(TS ts,DM *dm)
4821: {

4826:   if (!ts->dm) {
4827:     DMShellCreate(PetscObjectComm((PetscObject)ts),&ts->dm);
4828:     if (ts->snes) {SNESSetDM(ts->snes,ts->dm);}
4829:   }
4830:   *dm = ts->dm;
4831:   return(0);
4832: }

4834: /*@
4835:    SNESTSFormFunction - Function to evaluate nonlinear residual

4837:    Logically Collective on SNES

4839:    Input Parameter:
4840: + snes - nonlinear solver
4841: . U - the current state at which to evaluate the residual
4842: - ctx - user context, must be a TS

4844:    Output Parameter:
4845: . F - the nonlinear residual

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

4851:    Level: advanced

4853: .seealso: SNESSetFunction(), MatFDColoringSetFunction()
4854: @*/
4855: PetscErrorCode  SNESTSFormFunction(SNES snes,Vec U,Vec F,void *ctx)
4856: {
4857:   TS             ts = (TS)ctx;

4865:   (ts->ops->snesfunction)(snes,U,F,ts);
4866:   return(0);
4867: }

4869: /*@
4870:    SNESTSFormJacobian - Function to evaluate the Jacobian

4872:    Collective on SNES

4874:    Input Parameter:
4875: + snes - nonlinear solver
4876: . U - the current state at which to evaluate the residual
4877: - ctx - user context, must be a TS

4879:    Output Parameter:
4880: + A - the Jacobian
4881: . B - the preconditioning matrix (may be the same as A)
4882: - flag - indicates any structure change in the matrix

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

4887:    Level: developer

4889: .seealso: SNESSetJacobian()
4890: @*/
4891: PetscErrorCode  SNESTSFormJacobian(SNES snes,Vec U,Mat A,Mat B,void *ctx)
4892: {
4893:   TS             ts = (TS)ctx;

4904:   (ts->ops->snesjacobian)(snes,U,A,B,ts);
4905:   return(0);
4906: }

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

4911:    Collective on TS

4913:    Input Arguments:
4914: +  ts - time stepping context
4915: .  t - time at which to evaluate
4916: .  U - state at which to evaluate
4917: -  ctx - context

4919:    Output Arguments:
4920: .  F - right hand side

4922:    Level: intermediate

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

4928: .seealso: TSSetRHSFunction(), TSSetRHSJacobian(), TSComputeRHSJacobianConstant()
4929: @*/
4930: PetscErrorCode TSComputeRHSFunctionLinear(TS ts,PetscReal t,Vec U,Vec F,void *ctx)
4931: {
4933:   Mat            Arhs,Brhs;

4936:   TSGetRHSMats_Private(ts,&Arhs,&Brhs);
4937:   TSComputeRHSJacobian(ts,t,U,Arhs,Brhs);
4938:   MatMult(Arhs,U,F);
4939:   return(0);
4940: }

4942: /*@C
4943:    TSComputeRHSJacobianConstant - Reuses a Jacobian that is time-independent.

4945:    Collective on TS

4947:    Input Arguments:
4948: +  ts - time stepping context
4949: .  t - time at which to evaluate
4950: .  U - state at which to evaluate
4951: -  ctx - context

4953:    Output Arguments:
4954: +  A - pointer to operator
4955: .  B - pointer to preconditioning matrix
4956: -  flg - matrix structure flag

4958:    Level: intermediate

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

4963: .seealso: TSSetRHSFunction(), TSSetRHSJacobian(), TSComputeRHSFunctionLinear()
4964: @*/
4965: PetscErrorCode TSComputeRHSJacobianConstant(TS ts,PetscReal t,Vec U,Mat A,Mat B,void *ctx)
4966: {
4968:   return(0);
4969: }

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

4974:    Collective on TS

4976:    Input Arguments:
4977: +  ts - time stepping context
4978: .  t - time at which to evaluate
4979: .  U - state at which to evaluate
4980: .  Udot - time derivative of state vector
4981: -  ctx - context

4983:    Output Arguments:
4984: .  F - left hand side

4986:    Level: intermediate

4988:    Notes:
4989:    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
4990:    user is required to write their own TSComputeIFunction.
4991:    This function is intended to be passed to TSSetIFunction() to evaluate the left hand side for linear problems.
4992:    The matrix (and optionally the evaluation context) should be passed to TSSetIJacobian().

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

4996: .seealso: TSSetIFunction(), TSSetIJacobian(), TSComputeIJacobianConstant(), TSComputeRHSFunctionLinear()
4997: @*/
4998: PetscErrorCode TSComputeIFunctionLinear(TS ts,PetscReal t,Vec U,Vec Udot,Vec F,void *ctx)
4999: {
5001:   Mat            A,B;

5004:   TSGetIJacobian(ts,&A,&B,NULL,NULL);
5005:   TSComputeIJacobian(ts,t,U,Udot,1.0,A,B,PETSC_TRUE);
5006:   MatMult(A,Udot,F);
5007:   return(0);
5008: }

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

5013:    Collective on TS

5015:    Input Arguments:
5016: +  ts - time stepping context
5017: .  t - time at which to evaluate
5018: .  U - state at which to evaluate
5019: .  Udot - time derivative of state vector
5020: .  shift - shift to apply
5021: -  ctx - context

5023:    Output Arguments:
5024: +  A - pointer to operator
5025: .  B - pointer to preconditioning matrix
5026: -  flg - matrix structure flag

5028:    Level: advanced

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

5033:    It is only appropriate for problems of the form

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

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

5041: $    shift*M + J

5043:   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
5044:   a copy of M or reassemble it when requested.

5046: .seealso: TSSetIFunction(), TSSetIJacobian(), TSComputeIFunctionLinear()
5047: @*/
5048: PetscErrorCode TSComputeIJacobianConstant(TS ts,PetscReal t,Vec U,Vec Udot,PetscReal shift,Mat A,Mat B,void *ctx)
5049: {

5053:   MatScale(A, shift / ts->ijacobian.shift);
5054:   ts->ijacobian.shift = shift;
5055:   return(0);
5056: }

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

5061:    Not Collective

5063:    Input Parameter:
5064: .  ts - the TS context

5066:    Output Parameter:
5067: .  equation_type - see TSEquationType

5069:    Level: beginner

5071: .seealso: TSSetEquationType(), TSEquationType
5072: @*/
5073: PetscErrorCode  TSGetEquationType(TS ts,TSEquationType *equation_type)
5074: {
5078:   *equation_type = ts->equation_type;
5079:   return(0);
5080: }

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

5085:    Not Collective

5087:    Input Parameter:
5088: +  ts - the TS context
5089: -  equation_type - see TSEquationType

5091:    Level: advanced

5093: .seealso: TSGetEquationType(), TSEquationType
5094: @*/
5095: PetscErrorCode  TSSetEquationType(TS ts,TSEquationType equation_type)
5096: {
5099:   ts->equation_type = equation_type;
5100:   return(0);
5101: }

5103: /*@
5104:    TSGetConvergedReason - Gets the reason the TS iteration was stopped.

5106:    Not Collective

5108:    Input Parameter:
5109: .  ts - the TS context

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

5115:    Level: beginner

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

5120: .seealso: TSSetConvergenceTest(), TSConvergedReason
5121: @*/
5122: PetscErrorCode  TSGetConvergedReason(TS ts,TSConvergedReason *reason)
5123: {
5127:   *reason = ts->reason;
5128:   return(0);
5129: }

5131: /*@
5132:    TSSetConvergedReason - Sets the reason for handling the convergence of TSSolve.

5134:    Logically Collective; reason must contain common value

5136:    Input Parameters:
5137: +  ts - the TS context
5138: -  reason - negative value indicates diverged, positive value converged, see TSConvergedReason or the
5139:             manual pages for the individual convergence tests for complete lists

5141:    Level: advanced

5143:    Notes:
5144:    Can only be called while TSSolve() is active.

5146: .seealso: TSConvergedReason
5147: @*/
5148: PetscErrorCode  TSSetConvergedReason(TS ts,TSConvergedReason reason)
5149: {
5152:   ts->reason = reason;
5153:   return(0);
5154: }

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

5159:    Not Collective

5161:    Input Parameter:
5162: .  ts - the TS context

5164:    Output Parameter:
5165: .  ftime - the final time. This time corresponds to the final time set with TSSetMaxTime()

5167:    Level: beginner

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

5172: .seealso: TSSetConvergenceTest(), TSConvergedReason
5173: @*/
5174: PetscErrorCode  TSGetSolveTime(TS ts,PetscReal *ftime)
5175: {
5179:   *ftime = ts->solvetime;
5180:   return(0);
5181: }

5183: /*@
5184:    TSGetSNESIterations - Gets the total number of nonlinear iterations
5185:    used by the time integrator.

5187:    Not Collective

5189:    Input Parameter:
5190: .  ts - TS context

5192:    Output Parameter:
5193: .  nits - number of nonlinear iterations

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

5198:    Level: intermediate

5200: .seealso:  TSGetKSPIterations()
5201: @*/
5202: PetscErrorCode TSGetSNESIterations(TS ts,PetscInt *nits)
5203: {
5207:   *nits = ts->snes_its;
5208:   return(0);
5209: }

5211: /*@
5212:    TSGetKSPIterations - Gets the total number of linear iterations
5213:    used by the time integrator.

5215:    Not Collective

5217:    Input Parameter:
5218: .  ts - TS context

5220:    Output Parameter:
5221: .  lits - number of linear iterations

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

5226:    Level: intermediate

5228: .seealso:  TSGetSNESIterations(), SNESGetKSPIterations()
5229: @*/
5230: PetscErrorCode TSGetKSPIterations(TS ts,PetscInt *lits)
5231: {
5235:   *lits = ts->ksp_its;
5236:   return(0);
5237: }

5239: /*@
5240:    TSGetStepRejections - Gets the total number of rejected steps.

5242:    Not Collective

5244:    Input Parameter:
5245: .  ts - TS context

5247:    Output Parameter:
5248: .  rejects - number of steps rejected

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

5253:    Level: intermediate

5255: .seealso:  TSGetSNESIterations(), TSGetKSPIterations(), TSSetMaxStepRejections(), TSGetSNESFailures(), TSSetMaxSNESFailures(), TSSetErrorIfStepFails()
5256: @*/
5257: PetscErrorCode TSGetStepRejections(TS ts,PetscInt *rejects)
5258: {
5262:   *rejects = ts->reject;
5263:   return(0);
5264: }

5266: /*@
5267:    TSGetSNESFailures - Gets the total number of failed SNES solves

5269:    Not Collective

5271:    Input Parameter:
5272: .  ts - TS context

5274:    Output Parameter:
5275: .  fails - number of failed nonlinear solves

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

5280:    Level: intermediate

5282: .seealso:  TSGetSNESIterations(), TSGetKSPIterations(), TSSetMaxStepRejections(), TSGetStepRejections(), TSSetMaxSNESFailures()
5283: @*/
5284: PetscErrorCode TSGetSNESFailures(TS ts,PetscInt *fails)
5285: {
5289:   *fails = ts->num_snes_failures;
5290:   return(0);
5291: }

5293: /*@
5294:    TSSetMaxStepRejections - Sets the maximum number of step rejections before a step fails

5296:    Not Collective

5298:    Input Parameter:
5299: +  ts - TS context
5300: -  rejects - maximum number of rejected steps, pass -1 for unlimited

5302:    Notes:
5303:    The counter is reset to zero for each step

5305:    Options Database Key:
5306:  .  -ts_max_reject - Maximum number of step rejections before a step fails

5308:    Level: intermediate

5310: .seealso:  TSGetSNESIterations(), TSGetKSPIterations(), TSSetMaxSNESFailures(), TSGetStepRejections(), TSGetSNESFailures(), TSSetErrorIfStepFails(), TSGetConvergedReason()
5311: @*/
5312: PetscErrorCode TSSetMaxStepRejections(TS ts,PetscInt rejects)
5313: {
5316:   ts->max_reject = rejects;
5317:   return(0);
5318: }

5320: /*@
5321:    TSSetMaxSNESFailures - Sets the maximum number of failed SNES solves

5323:    Not Collective

5325:    Input Parameter:
5326: +  ts - TS context
5327: -  fails - maximum number of failed nonlinear solves, pass -1 for unlimited

5329:    Notes:
5330:    The counter is reset to zero for each successive call to TSSolve().

5332:    Options Database Key:
5333:  .  -ts_max_snes_failures - Maximum number of nonlinear solve failures

5335:    Level: intermediate

5337: .seealso:  TSGetSNESIterations(), TSGetKSPIterations(), TSSetMaxStepRejections(), TSGetStepRejections(), TSGetSNESFailures(), SNESGetConvergedReason(), TSGetConvergedReason()
5338: @*/
5339: PetscErrorCode TSSetMaxSNESFailures(TS ts,PetscInt fails)
5340: {
5343:   ts->max_snes_failures = fails;
5344:   return(0);
5345: }

5347: /*@
5348:    TSSetErrorIfStepFails - Error if no step succeeds

5350:    Not Collective

5352:    Input Parameter:
5353: +  ts - TS context
5354: -  err - PETSC_TRUE to error if no step succeeds, PETSC_FALSE to return without failure

5356:    Options Database Key:
5357:  .  -ts_error_if_step_fails - Error if no step succeeds

5359:    Level: intermediate

5361: .seealso:  TSGetSNESIterations(), TSGetKSPIterations(), TSSetMaxStepRejections(), TSGetStepRejections(), TSGetSNESFailures(), TSSetErrorIfStepFails(), TSGetConvergedReason()
5362: @*/
5363: PetscErrorCode TSSetErrorIfStepFails(TS ts,PetscBool err)
5364: {
5367:   ts->errorifstepfailed = err;
5368:   return(0);
5369: }

5371: /*@C
5372:    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

5374:    Collective on TS

5376:    Input Parameters:
5377: +  ts - the TS context
5378: .  step - current time-step
5379: .  ptime - current time
5380: .  u - current state
5381: -  vf - viewer and its format

5383:    Level: intermediate

5385: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView()
5386: @*/
5387: PetscErrorCode  TSMonitorSolution(TS ts,PetscInt step,PetscReal ptime,Vec u,PetscViewerAndFormat *vf)
5388: {

5392:   PetscViewerPushFormat(vf->viewer,vf->format);
5393:   VecView(u,vf->viewer);
5394:   PetscViewerPopFormat(vf->viewer);
5395:   return(0);
5396: }

5398: /*@C
5399:    TSMonitorSolutionVTK - Monitors progress of the TS solvers by VecView() for the solution at each timestep.

5401:    Collective on TS

5403:    Input Parameters:
5404: +  ts - the TS context
5405: .  step - current time-step
5406: .  ptime - current time
5407: .  u - current state
5408: -  filenametemplate - string containing a format specifier for the integer time step (e.g. %03D)

5410:    Level: intermediate

5412:    Notes:
5413:    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.
5414:    These are named according to the file name template.

5416:    This function is normally passed as an argument to TSMonitorSet() along with TSMonitorSolutionVTKDestroy().

5418: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView()
5419: @*/
5420: PetscErrorCode TSMonitorSolutionVTK(TS ts,PetscInt step,PetscReal ptime,Vec u,void *filenametemplate)
5421: {
5423:   char           filename[PETSC_MAX_PATH_LEN];
5424:   PetscViewer    viewer;

5427:   if (step < 0) return(0); /* -1 indicates interpolated solution */
5428:   PetscSNPrintf(filename,sizeof(filename),(const char*)filenametemplate,step);
5429:   PetscViewerVTKOpen(PetscObjectComm((PetscObject)ts),filename,FILE_MODE_WRITE,&viewer);
5430:   VecView(u,viewer);
5431:   PetscViewerDestroy(&viewer);
5432:   return(0);
5433: }

5435: /*@C
5436:    TSMonitorSolutionVTKDestroy - Destroy context for monitoring

5438:    Collective on TS

5440:    Input Parameters:
5441: .  filenametemplate - string containing a format specifier for the integer time step (e.g. %03D)

5443:    Level: intermediate

5445:    Note:
5446:    This function is normally passed to TSMonitorSet() along with TSMonitorSolutionVTK().

5448: .seealso: TSMonitorSet(), TSMonitorSolutionVTK()
5449: @*/
5450: PetscErrorCode TSMonitorSolutionVTKDestroy(void *filenametemplate)
5451: {

5455:   PetscFree(*(char**)filenametemplate);
5456:   return(0);
5457: }

5459: /*@
5460:    TSGetAdapt - Get the adaptive controller context for the current method

5462:    Collective on TS if controller has not been created yet

5464:    Input Arguments:
5465: .  ts - time stepping context

5467:    Output Arguments:
5468: .  adapt - adaptive controller

5470:    Level: intermediate

5472: .seealso: TSAdapt, TSAdaptSetType(), TSAdaptChoose()
5473: @*/
5474: PetscErrorCode TSGetAdapt(TS ts,TSAdapt *adapt)
5475: {

5481:   if (!ts->adapt) {
5482:     TSAdaptCreate(PetscObjectComm((PetscObject)ts),&ts->adapt);
5483:     PetscLogObjectParent((PetscObject)ts,(PetscObject)ts->adapt);
5484:     PetscObjectIncrementTabLevel((PetscObject)ts->adapt,(PetscObject)ts,1);
5485:   }
5486:   *adapt = ts->adapt;
5487:   return(0);
5488: }

5490: /*@
5491:    TSSetTolerances - Set tolerances for local truncation error when using adaptive controller

5493:    Logically Collective

5495:    Input Arguments:
5496: +  ts - time integration context
5497: .  atol - scalar absolute tolerances, PETSC_DECIDE to leave current value
5498: .  vatol - vector of absolute tolerances or NULL, used in preference to atol if present
5499: .  rtol - scalar relative tolerances, PETSC_DECIDE to leave current value
5500: -  vrtol - vector of relative tolerances or NULL, used in preference to atol if present

5502:    Options Database keys:
5503: +  -ts_rtol <rtol> - relative tolerance for local truncation error
5504: -  -ts_atol <atol> Absolute tolerance for local truncation error

5506:    Notes:
5507:    With PETSc's implicit schemes for DAE problems, the calculation of the local truncation error
5508:    (LTE) includes both the differential and the algebraic variables. If one wants the LTE to be
5509:    computed only for the differential or the algebraic part then this can be done using the vector of
5510:    tolerances vatol. For example, by setting the tolerance vector with the desired tolerance for the
5511:    differential part and infinity for the algebraic part, the LTE calculation will include only the
5512:    differential variables.

5514:    Level: beginner

5516: .seealso: TS, TSAdapt, TSVecNormWRMS(), TSGetTolerances()
5517: @*/
5518: PetscErrorCode TSSetTolerances(TS ts,PetscReal atol,Vec vatol,PetscReal rtol,Vec vrtol)
5519: {

5523:   if (atol != PETSC_DECIDE && atol != PETSC_DEFAULT) ts->atol = atol;
5524:   if (vatol) {
5525:     PetscObjectReference((PetscObject)vatol);
5526:     VecDestroy(&ts->vatol);
5527:     ts->vatol = vatol;
5528:   }
5529:   if (rtol != PETSC_DECIDE && rtol != PETSC_DEFAULT) ts->rtol = rtol;
5530:   if (vrtol) {
5531:     PetscObjectReference((PetscObject)vrtol);
5532:     VecDestroy(&ts->vrtol);
5533:     ts->vrtol = vrtol;
5534:   }
5535:   return(0);
5536: }

5538: /*@
5539:    TSGetTolerances - Get tolerances for local truncation error when using adaptive controller

5541:    Logically Collective

5543:    Input Arguments:
5544: .  ts - time integration context

5546:    Output Arguments:
5547: +  atol - scalar absolute tolerances, NULL to ignore
5548: .  vatol - vector of absolute tolerances, NULL to ignore
5549: .  rtol - scalar relative tolerances, NULL to ignore
5550: -  vrtol - vector of relative tolerances, NULL to ignore

5552:    Level: beginner

5554: .seealso: TS, TSAdapt, TSVecNormWRMS(), TSSetTolerances()
5555: @*/
5556: PetscErrorCode TSGetTolerances(TS ts,PetscReal *atol,Vec *vatol,PetscReal *rtol,Vec *vrtol)
5557: {
5559:   if (atol)  *atol  = ts->atol;
5560:   if (vatol) *vatol = ts->vatol;
5561:   if (rtol)  *rtol  = ts->rtol;
5562:   if (vrtol) *vrtol = ts->vrtol;
5563:   return(0);
5564: }

5566: /*@
5567:    TSErrorWeightedNorm2 - compute a weighted 2-norm of the difference between two state vectors

5569:    Collective on TS

5571:    Input Arguments:
5572: +  ts - time stepping context
5573: .  U - state vector, usually ts->vec_sol
5574: -  Y - state vector to be compared to U

5576:    Output Arguments:
5577: +  norm - weighted norm, a value of 1.0 means that the error matches the tolerances
5578: .  norma - weighted norm based on the absolute tolerance, a value of 1.0 means that the error matches the tolerances
5579: -  normr - weighted norm based on the relative tolerance, a value of 1.0 means that the error matches the tolerances

5581:    Level: developer

5583: .seealso: TSErrorWeightedNorm(), TSErrorWeightedNormInfinity()
5584: @*/
5585: PetscErrorCode TSErrorWeightedNorm2(TS ts,Vec U,Vec Y,PetscReal *norm,PetscReal *norma,PetscReal *normr)
5586: {
5587:   PetscErrorCode    ierr;
5588:   PetscInt          i,n,N,rstart;
5589:   PetscInt          n_loc,na_loc,nr_loc;
5590:   PetscReal         n_glb,na_glb,nr_glb;
5591:   const PetscScalar *u,*y;
5592:   PetscReal         sum,suma,sumr,gsum,gsuma,gsumr,diff;
5593:   PetscReal         tol,tola,tolr;
5594:   PetscReal         err_loc[6],err_glb[6];

5606:   if (U == Y) SETERRQ(PetscObjectComm((PetscObject)U),PETSC_ERR_ARG_IDN,"U and Y cannot be the same vector");

5608:   VecGetSize(U,&N);
5609:   VecGetLocalSize(U,&n);
5610:   VecGetOwnershipRange(U,&rstart,NULL);
5611:   VecGetArrayRead(U,&u);
5612:   VecGetArrayRead(Y,&y);
5613:   sum  = 0.; n_loc  = 0;
5614:   suma = 0.; na_loc = 0;
5615:   sumr = 0.; nr_loc = 0;
5616:   if (ts->vatol && ts->vrtol) {
5617:     const PetscScalar *atol,*rtol;
5618:     VecGetArrayRead(ts->vatol,&atol);
5619:     VecGetArrayRead(ts->vrtol,&rtol);
5620:     for (i=0; i<n; i++) {
5621:       SkipSmallValue(y[i],u[i],ts->adapt->ignore_max);
5622:       diff = PetscAbsScalar(y[i] - u[i]);
5623:       tola = PetscRealPart(atol[i]);
5624:       if(tola>0.){
5625:         suma  += PetscSqr(diff/tola);
5626:         na_loc++;
5627:       }
5628:       tolr = PetscRealPart(rtol[i]) * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
5629:       if(tolr>0.){
5630:         sumr  += PetscSqr(diff/tolr);
5631:         nr_loc++;
5632:       }
5633:       tol=tola+tolr;
5634:       if(tol>0.){
5635:         sum  += PetscSqr(diff/tol);
5636:         n_loc++;
5637:       }
5638:     }
5639:     VecRestoreArrayRead(ts->vatol,&atol);
5640:     VecRestoreArrayRead(ts->vrtol,&rtol);
5641:   } else if (ts->vatol) {       /* vector atol, scalar rtol */
5642:     const PetscScalar *atol;
5643:     VecGetArrayRead(ts->vatol,&atol);
5644:     for (i=0; i<n; i++) {
5645:       SkipSmallValue(y[i],u[i],ts->adapt->ignore_max);
5646:       diff = PetscAbsScalar(y[i] - u[i]);
5647:       tola = PetscRealPart(atol[i]);
5648:       if(tola>0.){
5649:         suma  += PetscSqr(diff/tola);
5650:         na_loc++;
5651:       }
5652:       tolr = ts->rtol * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
5653:       if(tolr>0.){
5654:         sumr  += PetscSqr(diff/tolr);
5655:         nr_loc++;
5656:       }
5657:       tol=tola+tolr;
5658:       if(tol>0.){
5659:         sum  += PetscSqr(diff/tol);
5660:         n_loc++;
5661:       }
5662:     }
5663:     VecRestoreArrayRead(ts->vatol,&atol);
5664:   } else if (ts->vrtol) {       /* scalar atol, vector rtol */
5665:     const PetscScalar *rtol;
5666:     VecGetArrayRead(ts->vrtol,&rtol);
5667:     for (i=0; i<n; i++) {
5668:       SkipSmallValue(y[i],u[i],ts->adapt->ignore_max);
5669:       diff = PetscAbsScalar(y[i] - u[i]);
5670:       tola = ts->atol;
5671:       if(tola>0.){
5672:         suma  += PetscSqr(diff/tola);
5673:         na_loc++;
5674:       }
5675:       tolr = PetscRealPart(rtol[i]) * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
5676:       if(tolr>0.){
5677:         sumr  += PetscSqr(diff/tolr);
5678:         nr_loc++;
5679:       }
5680:       tol=tola+tolr;
5681:       if(tol>0.){
5682:         sum  += PetscSqr(diff/tol);
5683:         n_loc++;
5684:       }
5685:     }
5686:     VecRestoreArrayRead(ts->vrtol,&rtol);
5687:   } else {                      /* scalar atol, scalar rtol */
5688:     for (i=0; i<n; i++) {
5689:       SkipSmallValue(y[i],u[i],ts->adapt->ignore_max);
5690:       diff = PetscAbsScalar(y[i] - u[i]);
5691:       tola = ts->atol;
5692:       if(tola>0.){
5693:         suma  += PetscSqr(diff/tola);
5694:         na_loc++;
5695:       }
5696:       tolr = ts->rtol * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
5697:       if(tolr>0.){
5698:         sumr  += PetscSqr(diff/tolr);
5699:         nr_loc++;
5700:       }
5701:       tol=tola+tolr;
5702:       if(tol>0.){
5703:         sum  += PetscSqr(diff/tol);
5704:         n_loc++;
5705:       }
5706:     }
5707:   }
5708:   VecRestoreArrayRead(U,&u);
5709:   VecRestoreArrayRead(Y,&y);

5711:   err_loc[0] = sum;
5712:   err_loc[1] = suma;
5713:   err_loc[2] = sumr;
5714:   err_loc[3] = (PetscReal)n_loc;
5715:   err_loc[4] = (PetscReal)na_loc;
5716:   err_loc[5] = (PetscReal)nr_loc;

5718:   MPIU_Allreduce(err_loc,err_glb,6,MPIU_REAL,MPIU_SUM,PetscObjectComm((PetscObject)ts));

5720:   gsum   = err_glb[0];
5721:   gsuma  = err_glb[1];
5722:   gsumr  = err_glb[2];
5723:   n_glb  = err_glb[3];
5724:   na_glb = err_glb[4];
5725:   nr_glb = err_glb[5];

5727:   *norm  = 0.;
5728:   if(n_glb>0. ){*norm  = PetscSqrtReal(gsum  / n_glb );}
5729:   *norma = 0.;
5730:   if(na_glb>0.){*norma = PetscSqrtReal(gsuma / na_glb);}
5731:   *normr = 0.;
5732:   if(nr_glb>0.){*normr = PetscSqrtReal(gsumr / nr_glb);}

5734:   if (PetscIsInfOrNanScalar(*norm)) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_FP,"Infinite or not-a-number generated in norm");
5735:   if (PetscIsInfOrNanScalar(*norma)) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_FP,"Infinite or not-a-number generated in norma");
5736:   if (PetscIsInfOrNanScalar(*normr)) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_FP,"Infinite or not-a-number generated in normr");
5737:   return(0);
5738: }

5740: /*@
5741:    TSErrorWeightedNormInfinity - compute a weighted infinity-norm of the difference between two state vectors

5743:    Collective on TS

5745:    Input Arguments:
5746: +  ts - time stepping context
5747: .  U - state vector, usually ts->vec_sol
5748: -  Y - state vector to be compared to U

5750:    Output Arguments:
5751: +  norm - weighted norm, a value of 1.0 means that the error matches the tolerances
5752: .  norma - weighted norm based on the absolute tolerance, a value of 1.0 means that the error matches the tolerances
5753: -  normr - weighted norm based on the relative tolerance, a value of 1.0 means that the error matches the tolerances

5755:    Level: developer

5757: .seealso: TSErrorWeightedNorm(), TSErrorWeightedNorm2()
5758: @*/
5759: PetscErrorCode TSErrorWeightedNormInfinity(TS ts,Vec U,Vec Y,PetscReal *norm,PetscReal *norma,PetscReal *normr)
5760: {
5761:   PetscErrorCode    ierr;
5762:   PetscInt          i,n,N,rstart;
5763:   const PetscScalar *u,*y;
5764:   PetscReal         max,gmax,maxa,gmaxa,maxr,gmaxr;
5765:   PetscReal         tol,tola,tolr,diff;
5766:   PetscReal         err_loc[3],err_glb[3];

5778:   if (U == Y) SETERRQ(PetscObjectComm((PetscObject)U),PETSC_ERR_ARG_IDN,"U and Y cannot be the same vector");

5780:   VecGetSize(U,&N);
5781:   VecGetLocalSize(U,&n);
5782:   VecGetOwnershipRange(U,&rstart,NULL);
5783:   VecGetArrayRead(U,&u);
5784:   VecGetArrayRead(Y,&y);

5786:   max=0.;
5787:   maxa=0.;
5788:   maxr=0.;

5790:   if (ts->vatol && ts->vrtol) {     /* vector atol, vector rtol */
5791:     const PetscScalar *atol,*rtol;
5792:     VecGetArrayRead(ts->vatol,&atol);
5793:     VecGetArrayRead(ts->vrtol,&rtol);

5795:     for (i=0; i<n; i++) {
5796:       SkipSmallValue(y[i],u[i],ts->adapt->ignore_max);
5797:       diff = PetscAbsScalar(y[i] - u[i]);
5798:       tola = PetscRealPart(atol[i]);
5799:       tolr = PetscRealPart(rtol[i]) * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
5800:       tol  = tola+tolr;
5801:       if(tola>0.){
5802:         maxa = PetscMax(maxa,diff / tola);
5803:       }
5804:       if(tolr>0.){
5805:         maxr = PetscMax(maxr,diff / tolr);
5806:       }
5807:       if(tol>0.){
5808:         max = PetscMax(max,diff / tol);
5809:       }
5810:     }
5811:     VecRestoreArrayRead(ts->vatol,&atol);
5812:     VecRestoreArrayRead(ts->vrtol,&rtol);
5813:   } else if (ts->vatol) {       /* vector atol, scalar rtol */
5814:     const PetscScalar *atol;
5815:     VecGetArrayRead(ts->vatol,&atol);
5816:     for (i=0; i<n; i++) {
5817:       SkipSmallValue(y[i],u[i],ts->adapt->ignore_max);
5818:       diff = PetscAbsScalar(y[i] - u[i]);
5819:       tola = PetscRealPart(atol[i]);
5820:       tolr = ts->rtol  * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
5821:       tol  = tola+tolr;
5822:       if(tola>0.){
5823:         maxa = PetscMax(maxa,diff / tola);
5824:       }
5825:       if(tolr>0.){
5826:         maxr = PetscMax(maxr,diff / tolr);
5827:       }
5828:       if(tol>0.){
5829:         max = PetscMax(max,diff / tol);
5830:       }
5831:     }
5832:     VecRestoreArrayRead(ts->vatol,&atol);
5833:   } else if (ts->vrtol) {       /* scalar atol, vector rtol */
5834:     const PetscScalar *rtol;
5835:     VecGetArrayRead(ts->vrtol,&rtol);

5837:     for (i=0; i<n; i++) {
5838:       SkipSmallValue(y[i],u[i],ts->adapt->ignore_max);
5839:       diff = PetscAbsScalar(y[i] - u[i]);
5840:       tola = ts->atol;
5841:       tolr = PetscRealPart(rtol[i]) * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
5842:       tol  = tola+tolr;
5843:       if(tola>0.){
5844:         maxa = PetscMax(maxa,diff / tola);
5845:       }
5846:       if(tolr>0.){
5847:         maxr = PetscMax(maxr,diff / tolr);
5848:       }
5849:       if(tol>0.){
5850:         max = PetscMax(max,diff / tol);
5851:       }
5852:     }
5853:     VecRestoreArrayRead(ts->vrtol,&rtol);
5854:   } else {                      /* scalar atol, scalar rtol */

5856:     for (i=0; i<n; i++) {
5857:       SkipSmallValue(y[i],u[i],ts->adapt->ignore_max);
5858:       diff = PetscAbsScalar(y[i] - u[i]);
5859:       tola = ts->atol;
5860:       tolr = ts->rtol * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
5861:       tol  = tola+tolr;
5862:       if(tola>0.){
5863:         maxa = PetscMax(maxa,diff / tola);
5864:       }
5865:       if(tolr>0.){
5866:         maxr = PetscMax(maxr,diff / tolr);
5867:       }
5868:       if(tol>0.){
5869:         max = PetscMax(max,diff / tol);
5870:       }
5871:     }
5872:   }
5873:   VecRestoreArrayRead(U,&u);
5874:   VecRestoreArrayRead(Y,&y);
5875:   err_loc[0] = max;
5876:   err_loc[1] = maxa;
5877:   err_loc[2] = maxr;
5878:   MPIU_Allreduce(err_loc,err_glb,3,MPIU_REAL,MPIU_MAX,PetscObjectComm((PetscObject)ts));
5879:   gmax   = err_glb[0];
5880:   gmaxa  = err_glb[1];
5881:   gmaxr  = err_glb[2];

5883:   *norm = gmax;
5884:   *norma = gmaxa;
5885:   *normr = gmaxr;
5886:   if (PetscIsInfOrNanScalar(*norm)) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_FP,"Infinite or not-a-number generated in norm");
5887:     if (PetscIsInfOrNanScalar(*norma)) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_FP,"Infinite or not-a-number generated in norma");
5888:     if (PetscIsInfOrNanScalar(*normr)) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_FP,"Infinite or not-a-number generated in normr");
5889:   return(0);
5890: }

5892: /*@
5893:    TSErrorWeightedNorm - compute a weighted norm of the difference between two state vectors based on supplied absolute and relative tolerances

5895:    Collective on TS

5897:    Input Arguments:
5898: +  ts - time stepping context
5899: .  U - state vector, usually ts->vec_sol
5900: .  Y - state vector to be compared to U
5901: -  wnormtype - norm type, either NORM_2 or NORM_INFINITY

5903:    Output Arguments:
5904: +  norm  - weighted norm, a value of 1.0 achieves a balance between absolute and relative tolerances
5905: .  norma - weighted norm, a value of 1.0 means that the error meets the absolute tolerance set by the user
5906: -  normr - weighted norm, a value of 1.0 means that the error meets the relative tolerance set by the user

5908:    Options Database Keys:
5909: .  -ts_adapt_wnormtype <wnormtype> - 2, INFINITY

5911:    Level: developer

5913: .seealso: TSErrorWeightedNormInfinity(), TSErrorWeightedNorm2(), TSErrorWeightedENorm
5914: @*/
5915: PetscErrorCode TSErrorWeightedNorm(TS ts,Vec U,Vec Y,NormType wnormtype,PetscReal *norm,PetscReal *norma,PetscReal *normr)
5916: {

5920:   if (wnormtype == NORM_2) {
5921:     TSErrorWeightedNorm2(ts,U,Y,norm,norma,normr);
5922:   } else if(wnormtype == NORM_INFINITY) {
5923:     TSErrorWeightedNormInfinity(ts,U,Y,norm,norma,normr);
5924:   } else SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"No support for norm type %s",NormTypes[wnormtype]);
5925:   return(0);
5926: }


5929: /*@
5930:    TSErrorWeightedENorm2 - compute a weighted 2 error norm based on supplied absolute and relative tolerances

5932:    Collective on TS

5934:    Input Arguments:
5935: +  ts - time stepping context
5936: .  E - error vector
5937: .  U - state vector, usually ts->vec_sol
5938: -  Y - state vector, previous time step

5940:    Output Arguments:
5941: +  norm - weighted norm, a value of 1.0 means that the error matches the tolerances
5942: .  norma - weighted norm based on the absolute tolerance, a value of 1.0 means that the error matches the tolerances
5943: -  normr - weighted norm based on the relative tolerance, a value of 1.0 means that the error matches the tolerances

5945:    Level: developer

5947: .seealso: TSErrorWeightedENorm(), TSErrorWeightedENormInfinity()
5948: @*/
5949: PetscErrorCode TSErrorWeightedENorm2(TS ts,Vec E,Vec U,Vec Y,PetscReal *norm,PetscReal *norma,PetscReal *normr)
5950: {
5951:   PetscErrorCode    ierr;
5952:   PetscInt          i,n,N,rstart;
5953:   PetscInt          n_loc,na_loc,nr_loc;
5954:   PetscReal         n_glb,na_glb,nr_glb;
5955:   const PetscScalar *e,*u,*y;
5956:   PetscReal         err,sum,suma,sumr,gsum,gsuma,gsumr;
5957:   PetscReal         tol,tola,tolr;
5958:   PetscReal         err_loc[6],err_glb[6];


5974:   VecGetSize(E,&N);
5975:   VecGetLocalSize(E,&n);
5976:   VecGetOwnershipRange(E,&rstart,NULL);
5977:   VecGetArrayRead(E,&e);
5978:   VecGetArrayRead(U,&u);
5979:   VecGetArrayRead(Y,&y);
5980:   sum  = 0.; n_loc  = 0;
5981:   suma = 0.; na_loc = 0;
5982:   sumr = 0.; nr_loc = 0;
5983:   if (ts->vatol && ts->vrtol) {
5984:     const PetscScalar *atol,*rtol;
5985:     VecGetArrayRead(ts->vatol,&atol);
5986:     VecGetArrayRead(ts->vrtol,&rtol);
5987:     for (i=0; i<n; i++) {
5988:       SkipSmallValue(y[i],u[i],ts->adapt->ignore_max);
5989:       err = PetscAbsScalar(e[i]);
5990:       tola = PetscRealPart(atol[i]);
5991:       if(tola>0.){
5992:         suma  += PetscSqr(err/tola);
5993:         na_loc++;
5994:       }
5995:       tolr = PetscRealPart(rtol[i]) * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
5996:       if(tolr>0.){
5997:         sumr  += PetscSqr(err/tolr);
5998:         nr_loc++;
5999:       }
6000:       tol=tola+tolr;
6001:       if(tol>0.){
6002:         sum  += PetscSqr(err/tol);
6003:         n_loc++;
6004:       }
6005:     }
6006:     VecRestoreArrayRead(ts->vatol,&atol);
6007:     VecRestoreArrayRead(ts->vrtol,&rtol);
6008:   } else if (ts->vatol) {       /* vector atol, scalar rtol */
6009:     const PetscScalar *atol;
6010:     VecGetArrayRead(ts->vatol,&atol);
6011:     for (i=0; i<n; i++) {
6012:       SkipSmallValue(y[i],u[i],ts->adapt->ignore_max);
6013:       err = PetscAbsScalar(e[i]);
6014:       tola = PetscRealPart(atol[i]);
6015:       if(tola>0.){
6016:         suma  += PetscSqr(err/tola);
6017:         na_loc++;
6018:       }
6019:       tolr = ts->rtol * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
6020:       if(tolr>0.){
6021:         sumr  += PetscSqr(err/tolr);
6022:         nr_loc++;
6023:       }
6024:       tol=tola+tolr;
6025:       if(tol>0.){
6026:         sum  += PetscSqr(err/tol);
6027:         n_loc++;
6028:       }
6029:     }
6030:     VecRestoreArrayRead(ts->vatol,&atol);
6031:   } else if (ts->vrtol) {       /* scalar atol, vector rtol */
6032:     const PetscScalar *rtol;
6033:     VecGetArrayRead(ts->vrtol,&rtol);
6034:     for (i=0; i<n; i++) {
6035:       SkipSmallValue(y[i],u[i],ts->adapt->ignore_max);
6036:       err = PetscAbsScalar(e[i]);
6037:       tola = ts->atol;
6038:       if(tola>0.){
6039:         suma  += PetscSqr(err/tola);
6040:         na_loc++;
6041:       }
6042:       tolr = PetscRealPart(rtol[i]) * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
6043:       if(tolr>0.){
6044:         sumr  += PetscSqr(err/tolr);
6045:         nr_loc++;
6046:       }
6047:       tol=tola+tolr;
6048:       if(tol>0.){
6049:         sum  += PetscSqr(err/tol);
6050:         n_loc++;
6051:       }
6052:     }
6053:     VecRestoreArrayRead(ts->vrtol,&rtol);
6054:   } else {                      /* scalar atol, scalar rtol */
6055:     for (i=0; i<n; i++) {
6056:       SkipSmallValue(y[i],u[i],ts->adapt->ignore_max);
6057:       err = PetscAbsScalar(e[i]);
6058:       tola = ts->atol;
6059:       if(tola>0.){
6060:         suma  += PetscSqr(err/tola);
6061:         na_loc++;
6062:       }
6063:       tolr = ts->rtol * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
6064:       if(tolr>0.){
6065:         sumr  += PetscSqr(err/tolr);
6066:         nr_loc++;
6067:       }
6068:       tol=tola+tolr;
6069:       if(tol>0.){
6070:         sum  += PetscSqr(err/tol);
6071:         n_loc++;
6072:       }
6073:     }
6074:   }
6075:   VecRestoreArrayRead(E,&e);
6076:   VecRestoreArrayRead(U,&u);
6077:   VecRestoreArrayRead(Y,&y);

6079:   err_loc[0] = sum;
6080:   err_loc[1] = suma;
6081:   err_loc[2] = sumr;
6082:   err_loc[3] = (PetscReal)n_loc;
6083:   err_loc[4] = (PetscReal)na_loc;
6084:   err_loc[5] = (PetscReal)nr_loc;

6086:   MPIU_Allreduce(err_loc,err_glb,6,MPIU_REAL,MPIU_SUM,PetscObjectComm((PetscObject)ts));

6088:   gsum   = err_glb[0];
6089:   gsuma  = err_glb[1];
6090:   gsumr  = err_glb[2];
6091:   n_glb  = err_glb[3];
6092:   na_glb = err_glb[4];
6093:   nr_glb = err_glb[5];

6095:   *norm  = 0.;
6096:   if(n_glb>0. ){*norm  = PetscSqrtReal(gsum  / n_glb );}
6097:   *norma = 0.;
6098:   if(na_glb>0.){*norma = PetscSqrtReal(gsuma / na_glb);}
6099:   *normr = 0.;
6100:   if(nr_glb>0.){*normr = PetscSqrtReal(gsumr / nr_glb);}

6102:   if (PetscIsInfOrNanScalar(*norm)) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_FP,"Infinite or not-a-number generated in norm");
6103:   if (PetscIsInfOrNanScalar(*norma)) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_FP,"Infinite or not-a-number generated in norma");
6104:   if (PetscIsInfOrNanScalar(*normr)) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_FP,"Infinite or not-a-number generated in normr");
6105:   return(0);
6106: }

6108: /*@
6109:    TSErrorWeightedENormInfinity - compute a weighted infinity error norm based on supplied absolute and relative tolerances
6110:    Collective on TS

6112:    Input Arguments:
6113: +  ts - time stepping context
6114: .  E - error vector
6115: .  U - state vector, usually ts->vec_sol
6116: -  Y - state vector, previous time step

6118:    Output Arguments:
6119: +  norm - weighted norm, a value of 1.0 means that the error matches the tolerances
6120: .  norma - weighted norm based on the absolute tolerance, a value of 1.0 means that the error matches the tolerances
6121: -  normr - weighted norm based on the relative tolerance, a value of 1.0 means that the error matches the tolerances

6123:    Level: developer

6125: .seealso: TSErrorWeightedENorm(), TSErrorWeightedENorm2()
6126: @*/
6127: PetscErrorCode TSErrorWeightedENormInfinity(TS ts,Vec E,Vec U,Vec Y,PetscReal *norm,PetscReal *norma,PetscReal *normr)
6128: {
6129:   PetscErrorCode    ierr;
6130:   PetscInt          i,n,N,rstart;
6131:   const PetscScalar *e,*u,*y;
6132:   PetscReal         err,max,gmax,maxa,gmaxa,maxr,gmaxr;
6133:   PetscReal         tol,tola,tolr;
6134:   PetscReal         err_loc[3],err_glb[3];


6150:   VecGetSize(E,&N);
6151:   VecGetLocalSize(E,&n);
6152:   VecGetOwnershipRange(E,&rstart,NULL);
6153:   VecGetArrayRead(E,&e);
6154:   VecGetArrayRead(U,&u);
6155:   VecGetArrayRead(Y,&y);

6157:   max=0.;
6158:   maxa=0.;
6159:   maxr=0.;

6161:   if (ts->vatol && ts->vrtol) {     /* vector atol, vector rtol */
6162:     const PetscScalar *atol,*rtol;
6163:     VecGetArrayRead(ts->vatol,&atol);
6164:     VecGetArrayRead(ts->vrtol,&rtol);

6166:     for (i=0; i<n; i++) {
6167:       SkipSmallValue(y[i],u[i],ts->adapt->ignore_max);
6168:       err = PetscAbsScalar(e[i]);
6169:       tola = PetscRealPart(atol[i]);
6170:       tolr = PetscRealPart(rtol[i]) * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
6171:       tol  = tola+tolr;
6172:       if(tola>0.){
6173:         maxa = PetscMax(maxa,err / tola);
6174:       }
6175:       if(tolr>0.){
6176:         maxr = PetscMax(maxr,err / tolr);
6177:       }
6178:       if(tol>0.){
6179:         max = PetscMax(max,err / tol);
6180:       }
6181:     }
6182:     VecRestoreArrayRead(ts->vatol,&atol);
6183:     VecRestoreArrayRead(ts->vrtol,&rtol);
6184:   } else if (ts->vatol) {       /* vector atol, scalar rtol */
6185:     const PetscScalar *atol;
6186:     VecGetArrayRead(ts->vatol,&atol);
6187:     for (i=0; i<n; i++) {
6188:       SkipSmallValue(y[i],u[i],ts->adapt->ignore_max);
6189:       err = PetscAbsScalar(e[i]);
6190:       tola = PetscRealPart(atol[i]);
6191:       tolr = ts->rtol  * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
6192:       tol  = tola+tolr;
6193:       if(tola>0.){
6194:         maxa = PetscMax(maxa,err / tola);
6195:       }
6196:       if(tolr>0.){
6197:         maxr = PetscMax(maxr,err / tolr);
6198:       }
6199:       if(tol>0.){
6200:         max = PetscMax(max,err / tol);
6201:       }
6202:     }
6203:     VecRestoreArrayRead(ts->vatol,&atol);
6204:   } else if (ts->vrtol) {       /* scalar atol, vector rtol */
6205:     const PetscScalar *rtol;
6206:     VecGetArrayRead(ts->vrtol,&rtol);

6208:     for (i=0; i<n; i++) {
6209:       SkipSmallValue(y[i],u[i],ts->adapt->ignore_max);
6210:       err = PetscAbsScalar(e[i]);
6211:       tola = ts->atol;
6212:       tolr = PetscRealPart(rtol[i]) * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
6213:       tol  = tola+tolr;
6214:       if(tola>0.){
6215:         maxa = PetscMax(maxa,err / tola);
6216:       }
6217:       if(tolr>0.){
6218:         maxr = PetscMax(maxr,err / tolr);
6219:       }
6220:       if(tol>0.){
6221:         max = PetscMax(max,err / tol);
6222:       }
6223:     }
6224:     VecRestoreArrayRead(ts->vrtol,&rtol);
6225:   } else {                      /* scalar atol, scalar rtol */

6227:     for (i=0; i<n; i++) {
6228:       SkipSmallValue(y[i],u[i],ts->adapt->ignore_max);
6229:       err = PetscAbsScalar(e[i]);
6230:       tola = ts->atol;
6231:       tolr = ts->rtol * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
6232:       tol  = tola+tolr;
6233:       if(tola>0.){
6234:         maxa = PetscMax(maxa,err / tola);
6235:       }
6236:       if(tolr>0.){
6237:         maxr = PetscMax(maxr,err / tolr);
6238:       }
6239:       if(tol>0.){
6240:         max = PetscMax(max,err / tol);
6241:       }
6242:     }
6243:   }
6244:   VecRestoreArrayRead(E,&e);
6245:   VecRestoreArrayRead(U,&u);
6246:   VecRestoreArrayRead(Y,&y);
6247:   err_loc[0] = max;
6248:   err_loc[1] = maxa;
6249:   err_loc[2] = maxr;
6250:   MPIU_Allreduce(err_loc,err_glb,3,MPIU_REAL,MPIU_MAX,PetscObjectComm((PetscObject)ts));
6251:   gmax   = err_glb[0];
6252:   gmaxa  = err_glb[1];
6253:   gmaxr  = err_glb[2];

6255:   *norm = gmax;
6256:   *norma = gmaxa;
6257:   *normr = gmaxr;
6258:   if (PetscIsInfOrNanScalar(*norm)) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_FP,"Infinite or not-a-number generated in norm");
6259:     if (PetscIsInfOrNanScalar(*norma)) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_FP,"Infinite or not-a-number generated in norma");
6260:     if (PetscIsInfOrNanScalar(*normr)) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_FP,"Infinite or not-a-number generated in normr");
6261:   return(0);
6262: }

6264: /*@
6265:    TSErrorWeightedENorm - compute a weighted error norm based on supplied absolute and relative tolerances

6267:    Collective on TS

6269:    Input Arguments:
6270: +  ts - time stepping context
6271: .  E - error vector
6272: .  U - state vector, usually ts->vec_sol
6273: .  Y - state vector, previous time step
6274: -  wnormtype - norm type, either NORM_2 or NORM_INFINITY

6276:    Output Arguments:
6277: +  norm  - weighted norm, a value of 1.0 achieves a balance between absolute and relative tolerances
6278: .  norma - weighted norm, a value of 1.0 means that the error meets the absolute tolerance set by the user
6279: -  normr - weighted norm, a value of 1.0 means that the error meets the relative tolerance set by the user

6281:    Options Database Keys:
6282: .  -ts_adapt_wnormtype <wnormtype> - 2, INFINITY

6284:    Level: developer

6286: .seealso: TSErrorWeightedENormInfinity(), TSErrorWeightedENorm2(), TSErrorWeightedNormInfinity(), TSErrorWeightedNorm2()
6287: @*/
6288: PetscErrorCode TSErrorWeightedENorm(TS ts,Vec E,Vec U,Vec Y,NormType wnormtype,PetscReal *norm,PetscReal *norma,PetscReal *normr)
6289: {

6293:   if (wnormtype == NORM_2) {
6294:     TSErrorWeightedENorm2(ts,E,U,Y,norm,norma,normr);
6295:   } else if(wnormtype == NORM_INFINITY) {
6296:     TSErrorWeightedENormInfinity(ts,E,U,Y,norm,norma,normr);
6297:   } else SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"No support for norm type %s",NormTypes[wnormtype]);
6298:   return(0);
6299: }


6302: /*@
6303:    TSSetCFLTimeLocal - Set the local CFL constraint relative to forward Euler

6305:    Logically Collective on TS

6307:    Input Arguments:
6308: +  ts - time stepping context
6309: -  cfltime - maximum stable time step if using forward Euler (value can be different on each process)

6311:    Note:
6312:    After calling this function, the global CFL time can be obtained by calling TSGetCFLTime()

6314:    Level: intermediate

6316: .seealso: TSGetCFLTime(), TSADAPTCFL
6317: @*/
6318: PetscErrorCode TSSetCFLTimeLocal(TS ts,PetscReal cfltime)
6319: {
6322:   ts->cfltime_local = cfltime;
6323:   ts->cfltime       = -1.;
6324:   return(0);
6325: }

6327: /*@
6328:    TSGetCFLTime - Get the maximum stable time step according to CFL criteria applied to forward Euler

6330:    Collective on TS

6332:    Input Arguments:
6333: .  ts - time stepping context

6335:    Output Arguments:
6336: .  cfltime - maximum stable time step for forward Euler

6338:    Level: advanced

6340: .seealso: TSSetCFLTimeLocal()
6341: @*/
6342: PetscErrorCode TSGetCFLTime(TS ts,PetscReal *cfltime)
6343: {

6347:   if (ts->cfltime < 0) {
6348:     MPIU_Allreduce(&ts->cfltime_local,&ts->cfltime,1,MPIU_REAL,MPIU_MIN,PetscObjectComm((PetscObject)ts));
6349:   }
6350:   *cfltime = ts->cfltime;
6351:   return(0);
6352: }

6354: /*@
6355:    TSVISetVariableBounds - Sets the lower and upper bounds for the solution vector. xl <= x <= xu

6357:    Input Parameters:
6358: +  ts   - the TS context.
6359: .  xl   - lower bound.
6360: -  xu   - upper bound.

6362:    Notes:
6363:    If this routine is not called then the lower and upper bounds are set to
6364:    PETSC_NINFINITY and PETSC_INFINITY respectively during SNESSetUp().

6366:    Level: advanced

6368: @*/
6369: PetscErrorCode TSVISetVariableBounds(TS ts, Vec xl, Vec xu)
6370: {
6372:   SNES           snes;

6375:   TSGetSNES(ts,&snes);
6376:   SNESVISetVariableBounds(snes,xl,xu);
6377:   return(0);
6378: }

6380: /*@C
6381:    TSMonitorLGSolution - Monitors progress of the TS solvers by plotting each component of the solution vector
6382:        in a time based line graph

6384:    Collective on TS

6386:    Input Parameters:
6387: +  ts - the TS context
6388: .  step - current time-step
6389: .  ptime - current time
6390: .  u - current solution
6391: -  dctx - the TSMonitorLGCtx object that contains all the options for the monitoring, this is created with TSMonitorLGCtxCreate()

6393:    Options Database:
6394: .   -ts_monitor_lg_solution_variables

6396:    Level: intermediate

6398:    Notes:
6399:     Each process in a parallel run displays its component solutions in a separate window

6401: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorLGCtxCreate(), TSMonitorLGCtxSetVariableNames(), TSMonitorLGCtxGetVariableNames(),
6402:            TSMonitorLGSetVariableNames(), TSMonitorLGGetVariableNames(), TSMonitorLGSetDisplayVariables(), TSMonitorLGCtxSetDisplayVariables(),
6403:            TSMonitorLGCtxSetTransform(), TSMonitorLGSetTransform(), TSMonitorLGError(), TSMonitorLGSNESIterations(), TSMonitorLGKSPIterations(),
6404:            TSMonitorEnvelopeCtxCreate(), TSMonitorEnvelopeGetBounds(), TSMonitorEnvelopeCtxDestroy(), TSMonitorEnvelop()
6405: @*/
6406: PetscErrorCode  TSMonitorLGSolution(TS ts,PetscInt step,PetscReal ptime,Vec u,void *dctx)
6407: {
6408:   PetscErrorCode    ierr;
6409:   TSMonitorLGCtx    ctx = (TSMonitorLGCtx)dctx;
6410:   const PetscScalar *yy;
6411:   Vec               v;

6414:   if (step < 0) return(0); /* -1 indicates interpolated solution */
6415:   if (!step) {
6416:     PetscDrawAxis axis;
6417:     PetscInt      dim;
6418:     PetscDrawLGGetAxis(ctx->lg,&axis);
6419:     PetscDrawAxisSetLabels(axis,"Solution as function of time","Time","Solution");
6420:     if (!ctx->names) {
6421:       PetscBool flg;
6422:       /* user provides names of variables to plot but no names has been set so assume names are integer values */
6423:       PetscOptionsHasName(((PetscObject)ts)->options,((PetscObject)ts)->prefix,"-ts_monitor_lg_solution_variables",&flg);
6424:       if (flg) {
6425:         PetscInt i,n;
6426:         char     **names;
6427:         VecGetSize(u,&n);
6428:         PetscMalloc1(n+1,&names);
6429:         for (i=0; i<n; i++) {
6430:           PetscMalloc1(5,&names[i]);
6431:           PetscSNPrintf(names[i],5,"%D",i);
6432:         }
6433:         names[n] = NULL;
6434:         ctx->names = names;
6435:       }
6436:     }
6437:     if (ctx->names && !ctx->displaynames) {
6438:       char      **displaynames;
6439:       PetscBool flg;
6440:       VecGetLocalSize(u,&dim);
6441:       PetscCalloc1(dim+1,&displaynames);
6442:       PetscOptionsGetStringArray(((PetscObject)ts)->options,((PetscObject)ts)->prefix,"-ts_monitor_lg_solution_variables",displaynames,&dim,&flg);
6443:       if (flg) {
6444:         TSMonitorLGCtxSetDisplayVariables(ctx,(const char *const *)displaynames);
6445:       }
6446:       PetscStrArrayDestroy(&displaynames);
6447:     }
6448:     if (ctx->displaynames) {
6449:       PetscDrawLGSetDimension(ctx->lg,ctx->ndisplayvariables);
6450:       PetscDrawLGSetLegend(ctx->lg,(const char *const *)ctx->displaynames);
6451:     } else if (ctx->names) {
6452:       VecGetLocalSize(u,&dim);
6453:       PetscDrawLGSetDimension(ctx->lg,dim);
6454:       PetscDrawLGSetLegend(ctx->lg,(const char *const *)ctx->names);
6455:     } else {
6456:       VecGetLocalSize(u,&dim);
6457:       PetscDrawLGSetDimension(ctx->lg,dim);
6458:     }
6459:     PetscDrawLGReset(ctx->lg);
6460:   }

6462:   if (!ctx->transform) v = u;
6463:   else {(*ctx->transform)(ctx->transformctx,u,&v);}
6464:   VecGetArrayRead(v,&yy);
6465:   if (ctx->displaynames) {
6466:     PetscInt i;
6467:     for (i=0; i<ctx->ndisplayvariables; i++)
6468:       ctx->displayvalues[i] = PetscRealPart(yy[ctx->displayvariables[i]]);
6469:     PetscDrawLGAddCommonPoint(ctx->lg,ptime,ctx->displayvalues);
6470:   } else {
6471: #if defined(PETSC_USE_COMPLEX)
6472:     PetscInt  i,n;
6473:     PetscReal *yreal;
6474:     VecGetLocalSize(v,&n);
6475:     PetscMalloc1(n,&yreal);
6476:     for (i=0; i<n; i++) yreal[i] = PetscRealPart(yy[i]);
6477:     PetscDrawLGAddCommonPoint(ctx->lg,ptime,yreal);
6478:     PetscFree(yreal);
6479: #else
6480:     PetscDrawLGAddCommonPoint(ctx->lg,ptime,yy);
6481: #endif
6482:   }
6483:   VecRestoreArrayRead(v,&yy);
6484:   if (ctx->transform) {VecDestroy(&v);}

6486:   if (((ctx->howoften > 0) && (!(step % ctx->howoften))) || ((ctx->howoften == -1) && ts->reason)) {
6487:     PetscDrawLGDraw(ctx->lg);
6488:     PetscDrawLGSave(ctx->lg);
6489:   }
6490:   return(0);
6491: }

6493: /*@C
6494:    TSMonitorLGSetVariableNames - Sets the name of each component in the solution vector so that it may be displayed in the plot

6496:    Collective on TS

6498:    Input Parameters:
6499: +  ts - the TS context
6500: -  names - the names of the components, final string must be NULL

6502:    Level: intermediate

6504:    Notes:
6505:     If the TS object does not have a TSMonitorLGCtx associated with it then this function is ignored

6507: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorLGSetDisplayVariables(), TSMonitorLGCtxSetVariableNames()
6508: @*/
6509: PetscErrorCode  TSMonitorLGSetVariableNames(TS ts,const char * const *names)
6510: {
6511:   PetscErrorCode    ierr;
6512:   PetscInt          i;

6515:   for (i=0; i<ts->numbermonitors; i++) {
6516:     if (ts->monitor[i] == TSMonitorLGSolution) {
6517:       TSMonitorLGCtxSetVariableNames((TSMonitorLGCtx)ts->monitorcontext[i],names);
6518:       break;
6519:     }
6520:   }
6521:   return(0);
6522: }

6524: /*@C
6525:    TSMonitorLGCtxSetVariableNames - Sets the name of each component in the solution vector so that it may be displayed in the plot

6527:    Collective on TS

6529:    Input Parameters:
6530: +  ts - the TS context
6531: -  names - the names of the components, final string must be NULL

6533:    Level: intermediate

6535: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorLGSetDisplayVariables(), TSMonitorLGSetVariableNames()
6536: @*/
6537: PetscErrorCode  TSMonitorLGCtxSetVariableNames(TSMonitorLGCtx ctx,const char * const *names)
6538: {
6539:   PetscErrorCode    ierr;

6542:   PetscStrArrayDestroy(&ctx->names);
6543:   PetscStrArrayallocpy(names,&ctx->names);
6544:   return(0);
6545: }

6547: /*@C
6548:    TSMonitorLGGetVariableNames - Gets the name of each component in the solution vector so that it may be displayed in the plot

6550:    Collective on TS

6552:    Input Parameter:
6553: .  ts - the TS context

6555:    Output Parameter:
6556: .  names - the names of the components, final string must be NULL

6558:    Level: intermediate

6560:    Notes:
6561:     If the TS object does not have a TSMonitorLGCtx associated with it then this function is ignored

6563: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorLGSetDisplayVariables()
6564: @*/
6565: PetscErrorCode  TSMonitorLGGetVariableNames(TS ts,const char *const **names)
6566: {
6567:   PetscInt       i;

6570:   *names = NULL;
6571:   for (i=0; i<ts->numbermonitors; i++) {
6572:     if (ts->monitor[i] == TSMonitorLGSolution) {
6573:       TSMonitorLGCtx  ctx = (TSMonitorLGCtx) ts->monitorcontext[i];
6574:       *names = (const char *const *)ctx->names;
6575:       break;
6576:     }
6577:   }
6578:   return(0);
6579: }

6581: /*@C
6582:    TSMonitorLGCtxSetDisplayVariables - Sets the variables that are to be display in the monitor

6584:    Collective on TS

6586:    Input Parameters:
6587: +  ctx - the TSMonitorLG context
6588: -  displaynames - the names of the components, final string must be NULL

6590:    Level: intermediate

6592: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorLGSetVariableNames()
6593: @*/
6594: PetscErrorCode  TSMonitorLGCtxSetDisplayVariables(TSMonitorLGCtx ctx,const char * const *displaynames)
6595: {
6596:   PetscInt          j = 0,k;
6597:   PetscErrorCode    ierr;

6600:   if (!ctx->names) return(0);
6601:   PetscStrArrayDestroy(&ctx->displaynames);
6602:   PetscStrArrayallocpy(displaynames,&ctx->displaynames);
6603:   while (displaynames[j]) j++;
6604:   ctx->ndisplayvariables = j;
6605:   PetscMalloc1(ctx->ndisplayvariables,&ctx->displayvariables);
6606:   PetscMalloc1(ctx->ndisplayvariables,&ctx->displayvalues);
6607:   j = 0;
6608:   while (displaynames[j]) {
6609:     k = 0;
6610:     while (ctx->names[k]) {
6611:       PetscBool flg;
6612:       PetscStrcmp(displaynames[j],ctx->names[k],&flg);
6613:       if (flg) {
6614:         ctx->displayvariables[j] = k;
6615:         break;
6616:       }
6617:       k++;
6618:     }
6619:     j++;
6620:   }
6621:   return(0);
6622: }

6624: /*@C
6625:    TSMonitorLGSetDisplayVariables - Sets the variables that are to be display in the monitor

6627:    Collective on TS

6629:    Input Parameters:
6630: +  ts - the TS context
6631: -  displaynames - the names of the components, final string must be NULL

6633:    Notes:
6634:     If the TS object does not have a TSMonitorLGCtx associated with it then this function is ignored

6636:    Level: intermediate

6638: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorLGSetVariableNames()
6639: @*/
6640: PetscErrorCode  TSMonitorLGSetDisplayVariables(TS ts,const char * const *displaynames)
6641: {
6642:   PetscInt          i;
6643:   PetscErrorCode    ierr;

6646:   for (i=0; i<ts->numbermonitors; i++) {
6647:     if (ts->monitor[i] == TSMonitorLGSolution) {
6648:       TSMonitorLGCtxSetDisplayVariables((TSMonitorLGCtx)ts->monitorcontext[i],displaynames);
6649:       break;
6650:     }
6651:   }
6652:   return(0);
6653: }

6655: /*@C
6656:    TSMonitorLGSetTransform - Solution vector will be transformed by provided function before being displayed

6658:    Collective on TS

6660:    Input Parameters:
6661: +  ts - the TS context
6662: .  transform - the transform function
6663: .  destroy - function to destroy the optional context
6664: -  ctx - optional context used by transform function

6666:    Notes:
6667:     If the TS object does not have a TSMonitorLGCtx associated with it then this function is ignored

6669:    Level: intermediate

6671: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorLGSetVariableNames(), TSMonitorLGCtxSetTransform()
6672: @*/
6673: PetscErrorCode  TSMonitorLGSetTransform(TS ts,PetscErrorCode (*transform)(void*,Vec,Vec*),PetscErrorCode (*destroy)(void*),void *tctx)
6674: {
6675:   PetscInt          i;
6676:   PetscErrorCode    ierr;

6679:   for (i=0; i<ts->numbermonitors; i++) {
6680:     if (ts->monitor[i] == TSMonitorLGSolution) {
6681:       TSMonitorLGCtxSetTransform((TSMonitorLGCtx)ts->monitorcontext[i],transform,destroy,tctx);
6682:     }
6683:   }
6684:   return(0);
6685: }

6687: /*@C
6688:    TSMonitorLGCtxSetTransform - Solution vector will be transformed by provided function before being displayed

6690:    Collective on TSLGCtx

6692:    Input Parameters:
6693: +  ts - the TS context
6694: .  transform - the transform function
6695: .  destroy - function to destroy the optional context
6696: -  ctx - optional context used by transform function

6698:    Level: intermediate

6700: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorLGSetVariableNames(), TSMonitorLGSetTransform()
6701: @*/
6702: PetscErrorCode  TSMonitorLGCtxSetTransform(TSMonitorLGCtx ctx,PetscErrorCode (*transform)(void*,Vec,Vec*),PetscErrorCode (*destroy)(void*),void *tctx)
6703: {
6705:   ctx->transform    = transform;
6706:   ctx->transformdestroy = destroy;
6707:   ctx->transformctx = tctx;
6708:   return(0);
6709: }

6711: /*@C
6712:    TSMonitorLGError - Monitors progress of the TS solvers by plotting each component of the error
6713:        in a time based line graph

6715:    Collective on TS

6717:    Input Parameters:
6718: +  ts - the TS context
6719: .  step - current time-step
6720: .  ptime - current time
6721: .  u - current solution
6722: -  dctx - TSMonitorLGCtx object created with TSMonitorLGCtxCreate()

6724:    Level: intermediate

6726:    Notes:
6727:     Each process in a parallel run displays its component errors in a separate window

6729:    The user must provide the solution using TSSetSolutionFunction() to use this monitor.

6731:    Options Database Keys:
6732: .  -ts_monitor_lg_error - create a graphical monitor of error history

6734: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSSetSolutionFunction()
6735: @*/
6736: PetscErrorCode  TSMonitorLGError(TS ts,PetscInt step,PetscReal ptime,Vec u,void *dummy)
6737: {
6738:   PetscErrorCode    ierr;
6739:   TSMonitorLGCtx    ctx = (TSMonitorLGCtx)dummy;
6740:   const PetscScalar *yy;
6741:   Vec               y;

6744:   if (!step) {
6745:     PetscDrawAxis axis;
6746:     PetscInt      dim;
6747:     PetscDrawLGGetAxis(ctx->lg,&axis);
6748:     PetscDrawAxisSetLabels(axis,"Error in solution as function of time","Time","Error");
6749:     VecGetLocalSize(u,&dim);
6750:     PetscDrawLGSetDimension(ctx->lg,dim);
6751:     PetscDrawLGReset(ctx->lg);
6752:   }
6753:   VecDuplicate(u,&y);
6754:   TSComputeSolutionFunction(ts,ptime,y);
6755:   VecAXPY(y,-1.0,u);
6756:   VecGetArrayRead(y,&yy);
6757: #if defined(PETSC_USE_COMPLEX)
6758:   {
6759:     PetscReal *yreal;
6760:     PetscInt  i,n;
6761:     VecGetLocalSize(y,&n);
6762:     PetscMalloc1(n,&yreal);
6763:     for (i=0; i<n; i++) yreal[i] = PetscRealPart(yy[i]);
6764:     PetscDrawLGAddCommonPoint(ctx->lg,ptime,yreal);
6765:     PetscFree(yreal);
6766:   }
6767: #else
6768:   PetscDrawLGAddCommonPoint(ctx->lg,ptime,yy);
6769: #endif
6770:   VecRestoreArrayRead(y,&yy);
6771:   VecDestroy(&y);
6772:   if (((ctx->howoften > 0) && (!(step % ctx->howoften))) || ((ctx->howoften == -1) && ts->reason)) {
6773:     PetscDrawLGDraw(ctx->lg);
6774:     PetscDrawLGSave(ctx->lg);
6775:   }
6776:   return(0);
6777: }

6779: /*@C
6780:    TSMonitorSPSwarmSolution - Graphically displays phase plots of DMSwarm particles on a scatter plot

6782:    Input Parameters:
6783: +  ts - the TS context
6784: .  step - current time-step
6785: .  ptime - current time
6786: .  u - current solution
6787: -  dctx - the TSMonitorSPCtx object that contains all the options for the monitoring, this is created with TSMonitorSPCtxCreate()

6789:    Options Database:
6790: .   -ts_monitor_sp_swarm

6792:    Level: intermediate

6794: @*/
6795: PetscErrorCode TSMonitorSPSwarmSolution(TS ts,PetscInt step,PetscReal ptime,Vec u,void *dctx)
6796: {
6797:   PetscErrorCode    ierr;
6798:   TSMonitorSPCtx    ctx = (TSMonitorSPCtx)dctx;
6799:   const PetscScalar *yy;
6800:   PetscReal       *y,*x;
6801:   PetscInt          Np, p, dim=2;
6802:   DM                dm;


6806:   if (step < 0) return(0); /* -1 indicates interpolated solution */
6807:   if (!step) {
6808:     PetscDrawAxis axis;
6809:     PetscDrawSPGetAxis(ctx->sp,&axis);
6810:     PetscDrawAxisSetLabels(axis,"Particles","X","Y");
6811:     PetscDrawAxisSetLimits(axis, -5, 5, -5, 5);
6812:     PetscDrawAxisSetHoldLimits(axis, PETSC_TRUE);
6813:     TSGetDM(ts, &dm);
6814:     DMGetDimension(dm, &dim);
6815:     if(dim!=2) SETERRQ(PETSC_COMM_SELF, ierr, "Dimensions improper for monitor arguments! Current support: two dimensions.");
6816:     VecGetLocalSize(u, &Np);
6817:     Np /= 2*dim;
6818:     PetscDrawSPSetDimension(ctx->sp, Np);
6819:     PetscDrawSPReset(ctx->sp);
6820:   }

6822:   VecGetLocalSize(u, &Np);
6823:   Np /= 2*dim;
6824:   VecGetArrayRead(u,&yy);
6825:   PetscMalloc2(Np, &x, Np, &y);
6826:   /* get points from solution vector */
6827:   for (p=0; p<Np; ++p){
6828:     x[p] = PetscRealPart(yy[2*dim*p]);
6829:     y[p] = PetscRealPart(yy[2*dim*p+1]);
6830:   }
6831:   VecRestoreArrayRead(u,&yy);

6833:   if (((ctx->howoften > 0) && (!(step % ctx->howoften))) || ((ctx->howoften == -1) && ts->reason)) {
6834:     PetscDrawSPAddPoint(ctx->sp,x,y);
6835:     PetscDrawSPDraw(ctx->sp,PETSC_FALSE);
6836:     PetscDrawSPSave(ctx->sp);
6837:   }

6839:   PetscFree2(x, y);

6841:   return(0);
6842: }



6846: /*@C
6847:    TSMonitorError - Monitors progress of the TS solvers by printing the 2 norm of the error at each timestep

6849:    Collective on TS

6851:    Input Parameters:
6852: +  ts - the TS context
6853: .  step - current time-step
6854: .  ptime - current time
6855: .  u - current solution
6856: -  dctx - unused context

6858:    Level: intermediate

6860:    The user must provide the solution using TSSetSolutionFunction() to use this monitor.

6862:    Options Database Keys:
6863: .  -ts_monitor_error - create a graphical monitor of error history

6865: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSSetSolutionFunction()
6866: @*/
6867: PetscErrorCode  TSMonitorError(TS ts,PetscInt step,PetscReal ptime,Vec u,PetscViewerAndFormat *vf)
6868: {
6869:   PetscErrorCode    ierr;
6870:   Vec               y;
6871:   PetscReal         nrm;
6872:   PetscBool         flg;

6875:   VecDuplicate(u,&y);
6876:   TSComputeSolutionFunction(ts,ptime,y);
6877:   VecAXPY(y,-1.0,u);
6878:   PetscObjectTypeCompare((PetscObject)vf->viewer,PETSCVIEWERASCII,&flg);
6879:   if (flg) {
6880:     VecNorm(y,NORM_2,&nrm);
6881:     PetscViewerASCIIPrintf(vf->viewer,"2-norm of error %g\n",(double)nrm);
6882:   }
6883:   PetscObjectTypeCompare((PetscObject)vf->viewer,PETSCVIEWERDRAW,&flg);
6884:   if (flg) {
6885:     VecView(y,vf->viewer);
6886:   }
6887:   VecDestroy(&y);
6888:   return(0);
6889: }

6891: PetscErrorCode TSMonitorLGSNESIterations(TS ts,PetscInt n,PetscReal ptime,Vec v,void *monctx)
6892: {
6893:   TSMonitorLGCtx ctx = (TSMonitorLGCtx) monctx;
6894:   PetscReal      x   = ptime,y;
6896:   PetscInt       its;

6899:   if (n < 0) return(0); /* -1 indicates interpolated solution */
6900:   if (!n) {
6901:     PetscDrawAxis axis;
6902:     PetscDrawLGGetAxis(ctx->lg,&axis);
6903:     PetscDrawAxisSetLabels(axis,"Nonlinear iterations as function of time","Time","SNES Iterations");
6904:     PetscDrawLGReset(ctx->lg);
6905:     ctx->snes_its = 0;
6906:   }
6907:   TSGetSNESIterations(ts,&its);
6908:   y    = its - ctx->snes_its;
6909:   PetscDrawLGAddPoint(ctx->lg,&x,&y);
6910:   if (((ctx->howoften > 0) && (!(n % ctx->howoften)) && (n > -1)) || ((ctx->howoften == -1) && (n == -1))) {
6911:     PetscDrawLGDraw(ctx->lg);
6912:     PetscDrawLGSave(ctx->lg);
6913:   }
6914:   ctx->snes_its = its;
6915:   return(0);
6916: }

6918: PetscErrorCode TSMonitorLGKSPIterations(TS ts,PetscInt n,PetscReal ptime,Vec v,void *monctx)
6919: {
6920:   TSMonitorLGCtx ctx = (TSMonitorLGCtx) monctx;
6921:   PetscReal      x   = ptime,y;
6923:   PetscInt       its;

6926:   if (n < 0) return(0); /* -1 indicates interpolated solution */
6927:   if (!n) {
6928:     PetscDrawAxis axis;
6929:     PetscDrawLGGetAxis(ctx->lg,&axis);
6930:     PetscDrawAxisSetLabels(axis,"Linear iterations as function of time","Time","KSP Iterations");
6931:     PetscDrawLGReset(ctx->lg);
6932:     ctx->ksp_its = 0;
6933:   }
6934:   TSGetKSPIterations(ts,&its);
6935:   y    = its - ctx->ksp_its;
6936:   PetscDrawLGAddPoint(ctx->lg,&x,&y);
6937:   if (((ctx->howoften > 0) && (!(n % ctx->howoften)) && (n > -1)) || ((ctx->howoften == -1) && (n == -1))) {
6938:     PetscDrawLGDraw(ctx->lg);
6939:     PetscDrawLGSave(ctx->lg);
6940:   }
6941:   ctx->ksp_its = its;
6942:   return(0);
6943: }

6945: /*@
6946:    TSComputeLinearStability - computes the linear stability function at a point

6948:    Collective on TS

6950:    Input Parameters:
6951: +  ts - the TS context
6952: -  xr,xi - real and imaginary part of input arguments

6954:    Output Parameters:
6955: .  yr,yi - real and imaginary part of function value

6957:    Level: developer

6959: .seealso: TSSetRHSFunction(), TSComputeIFunction()
6960: @*/
6961: PetscErrorCode TSComputeLinearStability(TS ts,PetscReal xr,PetscReal xi,PetscReal *yr,PetscReal *yi)
6962: {

6967:   if (!ts->ops->linearstability) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"Linearized stability function not provided for this method");
6968:   (*ts->ops->linearstability)(ts,xr,xi,yr,yi);
6969:   return(0);
6970: }

6972: /* ------------------------------------------------------------------------*/
6973: /*@C
6974:    TSMonitorEnvelopeCtxCreate - Creates a context for use with TSMonitorEnvelope()

6976:    Collective on TS

6978:    Input Parameters:
6979: .  ts  - the ODE solver object

6981:    Output Parameter:
6982: .  ctx - the context

6984:    Level: intermediate

6986: .seealso: TSMonitorLGTimeStep(), TSMonitorSet(), TSMonitorLGSolution(), TSMonitorLGError()

6988: @*/
6989: PetscErrorCode  TSMonitorEnvelopeCtxCreate(TS ts,TSMonitorEnvelopeCtx *ctx)
6990: {

6994:   PetscNew(ctx);
6995:   return(0);
6996: }

6998: /*@C
6999:    TSMonitorEnvelope - Monitors the maximum and minimum value of each component of the solution

7001:    Collective on TS

7003:    Input Parameters:
7004: +  ts - the TS context
7005: .  step - current time-step
7006: .  ptime - current time
7007: .  u  - current solution
7008: -  dctx - the envelope context

7010:    Options Database:
7011: .  -ts_monitor_envelope

7013:    Level: intermediate

7015:    Notes:
7016:     after a solve you can use TSMonitorEnvelopeGetBounds() to access the envelope

7018: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorEnvelopeGetBounds(), TSMonitorEnvelopeCtxCreate()
7019: @*/
7020: PetscErrorCode  TSMonitorEnvelope(TS ts,PetscInt step,PetscReal ptime,Vec u,void *dctx)
7021: {
7022:   PetscErrorCode       ierr;
7023:   TSMonitorEnvelopeCtx ctx = (TSMonitorEnvelopeCtx)dctx;

7026:   if (!ctx->max) {
7027:     VecDuplicate(u,&ctx->max);
7028:     VecDuplicate(u,&ctx->min);
7029:     VecCopy(u,ctx->max);
7030:     VecCopy(u,ctx->min);
7031:   } else {
7032:     VecPointwiseMax(ctx->max,u,ctx->max);
7033:     VecPointwiseMin(ctx->min,u,ctx->min);
7034:   }
7035:   return(0);
7036: }

7038: /*@C
7039:    TSMonitorEnvelopeGetBounds - Gets the bounds for the components of the solution

7041:    Collective on TS

7043:    Input Parameter:
7044: .  ts - the TS context

7046:    Output Parameter:
7047: +  max - the maximum values
7048: -  min - the minimum values

7050:    Notes:
7051:     If the TS does not have a TSMonitorEnvelopeCtx associated with it then this function is ignored

7053:    Level: intermediate

7055: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorLGSetDisplayVariables()
7056: @*/
7057: PetscErrorCode  TSMonitorEnvelopeGetBounds(TS ts,Vec *max,Vec *min)
7058: {
7059:   PetscInt i;

7062:   if (max) *max = NULL;
7063:   if (min) *min = NULL;
7064:   for (i=0; i<ts->numbermonitors; i++) {
7065:     if (ts->monitor[i] == TSMonitorEnvelope) {
7066:       TSMonitorEnvelopeCtx  ctx = (TSMonitorEnvelopeCtx) ts->monitorcontext[i];
7067:       if (max) *max = ctx->max;
7068:       if (min) *min = ctx->min;
7069:       break;
7070:     }
7071:   }
7072:   return(0);
7073: }

7075: /*@C
7076:    TSMonitorEnvelopeCtxDestroy - Destroys a context that was created  with TSMonitorEnvelopeCtxCreate().

7078:    Collective on TSMonitorEnvelopeCtx

7080:    Input Parameter:
7081: .  ctx - the monitor context

7083:    Level: intermediate

7085: .seealso: TSMonitorLGCtxCreate(),  TSMonitorSet(), TSMonitorLGTimeStep()
7086: @*/
7087: PetscErrorCode  TSMonitorEnvelopeCtxDestroy(TSMonitorEnvelopeCtx *ctx)
7088: {

7092:   VecDestroy(&(*ctx)->min);
7093:   VecDestroy(&(*ctx)->max);
7094:   PetscFree(*ctx);
7095:   return(0);
7096: }

7098: /*@
7099:    TSRestartStep - Flags the solver to restart the next step

7101:    Collective on TS

7103:    Input Parameter:
7104: .  ts - the TS context obtained from TSCreate()

7106:    Level: advanced

7108:    Notes:
7109:    Multistep methods like BDF or Runge-Kutta methods with FSAL property require restarting the solver in the event of
7110:    discontinuities. These discontinuities may be introduced as a consequence of explicitly modifications to the solution
7111:    vector (which PETSc attempts to detect and handle) or problem coefficients (which PETSc is not able to detect). For
7112:    the sake of correctness and maximum safety, users are expected to call TSRestart() whenever they introduce
7113:    discontinuities in callback routines (e.g. prestep and poststep routines, or implicit/rhs function routines with
7114:    discontinuous source terms).

7116: .seealso: TSSolve(), TSSetPreStep(), TSSetPostStep()
7117: @*/
7118: PetscErrorCode TSRestartStep(TS ts)
7119: {
7122:   ts->steprestart = PETSC_TRUE;
7123:   return(0);
7124: }

7126: /*@
7127:    TSRollBack - Rolls back one time step

7129:    Collective on TS

7131:    Input Parameter:
7132: .  ts - the TS context obtained from TSCreate()

7134:    Level: advanced

7136: .seealso: TSCreate(), TSSetUp(), TSDestroy(), TSSolve(), TSSetPreStep(), TSSetPreStage(), TSInterpolate()
7137: @*/
7138: PetscErrorCode  TSRollBack(TS ts)
7139: {

7144:   if (ts->steprollback) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_ARG_WRONGSTATE,"TSRollBack already called");
7145:   if (!ts->ops->rollback) SETERRQ1(PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"TSRollBack not implemented for type '%s'",((PetscObject)ts)->type_name);
7146:   (*ts->ops->rollback)(ts);
7147:   ts->time_step = ts->ptime - ts->ptime_prev;
7148:   ts->ptime = ts->ptime_prev;
7149:   ts->ptime_prev = ts->ptime_prev_rollback;
7150:   ts->steps--;
7151:   ts->steprollback = PETSC_TRUE;
7152:   return(0);
7153: }

7155: /*@
7156:    TSGetStages - Get the number of stages and stage values

7158:    Input Parameter:
7159: .  ts - the TS context obtained from TSCreate()

7161:    Output Parameters:
7162: +  ns - the number of stages
7163: -  Y - the current stage vectors

7165:    Level: advanced

7167:    Notes: Both ns and Y can be NULL.

7169: .seealso: TSCreate()
7170: @*/
7171: PetscErrorCode  TSGetStages(TS ts,PetscInt *ns,Vec **Y)
7172: {

7179:   if (!ts->ops->getstages) {
7180:     if (ns) *ns = 0;
7181:     if (Y) *Y = NULL;
7182:   } else {
7183:     (*ts->ops->getstages)(ts,ns,Y);
7184:   }
7185:   return(0);
7186: }

7188: /*@C
7189:   TSComputeIJacobianDefaultColor - Computes the Jacobian using finite differences and coloring to exploit matrix sparsity.

7191:   Collective on SNES

7193:   Input Parameters:
7194: + ts - the TS context
7195: . t - current timestep
7196: . U - state vector
7197: . Udot - time derivative of state vector
7198: . shift - shift to apply, see note below
7199: - ctx - an optional user context

7201:   Output Parameters:
7202: + J - Jacobian matrix (not altered in this routine)
7203: - B - newly computed Jacobian matrix to use with preconditioner (generally the same as J)

7205:   Level: intermediate

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

7210:   dF/dU + shift*dF/dUdot

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

7215:   This will first try to get the coloring from the DM.  If the DM type has no coloring
7216:   routine, then it will try to get the coloring from the matrix.  This requires that the
7217:   matrix have nonzero entries precomputed.

7219: .seealso: TSSetIJacobian(), MatFDColoringCreate(), MatFDColoringSetFunction()
7220: @*/
7221: PetscErrorCode TSComputeIJacobianDefaultColor(TS ts,PetscReal t,Vec U,Vec Udot,PetscReal shift,Mat J,Mat B,void *ctx)
7222: {
7223:   SNES           snes;
7224:   MatFDColoring  color;
7225:   PetscBool      hascolor, matcolor = PETSC_FALSE;

7229:   PetscOptionsGetBool(((PetscObject)ts)->options,((PetscObject) ts)->prefix, "-ts_fd_color_use_mat", &matcolor, NULL);
7230:   PetscObjectQuery((PetscObject) B, "TSMatFDColoring", (PetscObject *) &color);
7231:   if (!color) {
7232:     DM         dm;
7233:     ISColoring iscoloring;

7235:     TSGetDM(ts, &dm);
7236:     DMHasColoring(dm, &hascolor);
7237:     if (hascolor && !matcolor) {
7238:       DMCreateColoring(dm, IS_COLORING_GLOBAL, &iscoloring);
7239:       MatFDColoringCreate(B, iscoloring, &color);
7240:       MatFDColoringSetFunction(color, (PetscErrorCode (*)(void)) SNESTSFormFunction, (void *) ts);
7241:       MatFDColoringSetFromOptions(color);
7242:       MatFDColoringSetUp(B, iscoloring, color);
7243:       ISColoringDestroy(&iscoloring);
7244:     } else {
7245:       MatColoring mc;

7247:       MatColoringCreate(B, &mc);
7248:       MatColoringSetDistance(mc, 2);
7249:       MatColoringSetType(mc, MATCOLORINGSL);
7250:       MatColoringSetFromOptions(mc);
7251:       MatColoringApply(mc, &iscoloring);
7252:       MatColoringDestroy(&mc);
7253:       MatFDColoringCreate(B, iscoloring, &color);
7254:       MatFDColoringSetFunction(color, (PetscErrorCode (*)(void)) SNESTSFormFunction, (void *) ts);
7255:       MatFDColoringSetFromOptions(color);
7256:       MatFDColoringSetUp(B, iscoloring, color);
7257:       ISColoringDestroy(&iscoloring);
7258:     }
7259:     PetscObjectCompose((PetscObject) B, "TSMatFDColoring", (PetscObject) color);
7260:     PetscObjectDereference((PetscObject) color);
7261:   }
7262:   TSGetSNES(ts, &snes);
7263:   MatFDColoringApply(B, color, U, snes);
7264:   if (J != B) {
7265:     MatAssemblyBegin(J, MAT_FINAL_ASSEMBLY);
7266:     MatAssemblyEnd(J, MAT_FINAL_ASSEMBLY);
7267:   }
7268:   return(0);
7269: }

7271: /*@
7272:     TSSetFunctionDomainError - Set a function that tests if the current state vector is valid

7274:     Input Parameters:
7275: +    ts - the TS context
7276: -    func - function called within TSFunctionDomainError

7278:     Calling sequence of func:
7279: $     PetscErrorCode func(TS ts,PetscReal time,Vec state,PetscBool reject)

7281: +   ts - the TS context
7282: .   time - the current time (of the stage)
7283: .   state - the state to check if it is valid
7284: -   reject - (output parameter) PETSC_FALSE if the state is acceptable, PETSC_TRUE if not acceptable

7286:     Level: intermediate

7288:     Notes:
7289:       If an implicit ODE solver is being used then, in addition to providing this routine, the
7290:       user's code should call SNESSetFunctionDomainError() when domain errors occur during
7291:       function evaluations where the functions are provided by TSSetIFunction() or TSSetRHSFunction().
7292:       Use TSGetSNES() to obtain the SNES object

7294:     Developer Notes:
7295:       The naming of this function is inconsistent with the SNESSetFunctionDomainError()
7296:       since one takes a function pointer and the other does not.

7298: .seealso: TSAdaptCheckStage(), TSFunctionDomainError(), SNESSetFunctionDomainError(), TSGetSNES()
7299: @*/

7301: PetscErrorCode TSSetFunctionDomainError(TS ts, PetscErrorCode (*func)(TS,PetscReal,Vec,PetscBool*))
7302: {
7305:   ts->functiondomainerror = func;
7306:   return(0);
7307: }

7309: /*@
7310:     TSFunctionDomainError - Checks if the current state is valid

7312:     Input Parameters:
7313: +    ts - the TS context
7314: .    stagetime - time of the simulation
7315: -    Y - state vector to check.

7317:     Output Parameter:
7318: .    accept - Set to PETSC_FALSE if the current state vector is valid.

7320:     Note:
7321:     This function is called by the TS integration routines and calls the user provided function (set with TSSetFunctionDomainError())
7322:     to check if the current state is valid.

7324:     Level: developer

7326: .seealso: TSSetFunctionDomainError()
7327: @*/
7328: PetscErrorCode TSFunctionDomainError(TS ts,PetscReal stagetime,Vec Y,PetscBool* accept)
7329: {
7332:   *accept = PETSC_TRUE;
7333:   if (ts->functiondomainerror) {
7334:     PetscStackCallStandard((*ts->functiondomainerror),(ts,stagetime,Y,accept));
7335:   }
7336:   return(0);
7337: }

7339: /*@C
7340:   TSClone - This function clones a time step object.

7342:   Collective

7344:   Input Parameter:
7345: . tsin    - The input TS

7347:   Output Parameter:
7348: . tsout   - The output TS (cloned)

7350:   Notes:
7351:   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.

7353:   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);

7355:   Level: developer

7357: .seealso: TSCreate(), TSSetType(), TSSetUp(), TSDestroy(), TSSetProblemType()
7358: @*/
7359: PetscErrorCode  TSClone(TS tsin, TS *tsout)
7360: {
7361:   TS             t;
7363:   SNES           snes_start;
7364:   DM             dm;
7365:   TSType         type;

7369:   *tsout = NULL;

7371:   PetscHeaderCreate(t, TS_CLASSID, "TS", "Time stepping", "TS", PetscObjectComm((PetscObject)tsin), TSDestroy, TSView);

7373:   /* General TS description */
7374:   t->numbermonitors    = 0;
7375:   t->setupcalled       = 0;
7376:   t->ksp_its           = 0;
7377:   t->snes_its          = 0;
7378:   t->nwork             = 0;
7379:   t->rhsjacobian.time  = -1e20;
7380:   t->rhsjacobian.scale = 1.;
7381:   t->ijacobian.shift   = 1.;

7383:   TSGetSNES(tsin,&snes_start);
7384:   TSSetSNES(t,snes_start);

7386:   TSGetDM(tsin,&dm);
7387:   TSSetDM(t,dm);

7389:   t->adapt = tsin->adapt;
7390:   PetscObjectReference((PetscObject)t->adapt);

7392:   t->trajectory = tsin->trajectory;
7393:   PetscObjectReference((PetscObject)t->trajectory);

7395:   t->event = tsin->event;
7396:   if (t->event) t->event->refct++;

7398:   t->problem_type      = tsin->problem_type;
7399:   t->ptime             = tsin->ptime;
7400:   t->ptime_prev        = tsin->ptime_prev;
7401:   t->time_step         = tsin->time_step;
7402:   t->max_time          = tsin->max_time;
7403:   t->steps             = tsin->steps;
7404:   t->max_steps         = tsin->max_steps;
7405:   t->equation_type     = tsin->equation_type;
7406:   t->atol              = tsin->atol;
7407:   t->rtol              = tsin->rtol;
7408:   t->max_snes_failures = tsin->max_snes_failures;
7409:   t->max_reject        = tsin->max_reject;
7410:   t->errorifstepfailed = tsin->errorifstepfailed;

7412:   TSGetType(tsin,&type);
7413:   TSSetType(t,type);

7415:   t->vec_sol           = NULL;

7417:   t->cfltime          = tsin->cfltime;
7418:   t->cfltime_local    = tsin->cfltime_local;
7419:   t->exact_final_time = tsin->exact_final_time;

7421:   PetscMemcpy(t->ops,tsin->ops,sizeof(struct _TSOps));

7423:   if (((PetscObject)tsin)->fortran_func_pointers) {
7424:     PetscInt i;
7425:     PetscMalloc((10)*sizeof(void(*)(void)),&((PetscObject)t)->fortran_func_pointers);
7426:     for (i=0; i<10; i++) {
7427:       ((PetscObject)t)->fortran_func_pointers[i] = ((PetscObject)tsin)->fortran_func_pointers[i];
7428:     }
7429:   }
7430:   *tsout = t;
7431:   return(0);
7432: }

7434: static PetscErrorCode RHSWrapperFunction_TSRHSJacobianTest(void* ctx,Vec x,Vec y)
7435: {
7437:   TS             ts = (TS) ctx;

7440:   TSComputeRHSFunction(ts,0,x,y);
7441:   return(0);
7442: }

7444: /*@
7445:     TSRHSJacobianTest - Compares the multiply routine provided to the MATSHELL with differencing on the TS given RHS function.

7447:    Logically Collective on TS

7449:     Input Parameters:
7450:     TS - the time stepping routine

7452:    Output Parameter:
7453: .   flg - PETSC_TRUE if the multiply is likely correct

7455:    Options Database:
7456:  .   -ts_rhs_jacobian_test_mult -mat_shell_test_mult_view - run the test at each timestep of the integrator

7458:    Level: advanced

7460:    Notes:
7461:     This only works for problems defined only the RHS function and Jacobian NOT IFunction and IJacobian

7463: .seealso: MatCreateShell(), MatShellGetContext(), MatShellGetOperation(), MatShellTestMultTranspose(), TSRHSJacobianTestTranspose()
7464: @*/
7465: PetscErrorCode  TSRHSJacobianTest(TS ts,PetscBool *flg)
7466: {
7467:   Mat            J,B;
7469:   TSRHSJacobian  func;
7470:   void*          ctx;

7473:   TSGetRHSJacobian(ts,&J,&B,&func,&ctx);
7474:   (*func)(ts,0.0,ts->vec_sol,J,B,ctx);
7475:   MatShellTestMult(J,RHSWrapperFunction_TSRHSJacobianTest,ts->vec_sol,ts,flg);
7476:   return(0);
7477: }

7479: /*@C
7480:     TSRHSJacobianTestTranspose - Compares the multiply transpose routine provided to the MATSHELL with differencing on the TS given RHS function.

7482:    Logically Collective on TS

7484:     Input Parameters:
7485:     TS - the time stepping routine

7487:    Output Parameter:
7488: .   flg - PETSC_TRUE if the multiply is likely correct

7490:    Options Database:
7491: .   -ts_rhs_jacobian_test_mult_transpose -mat_shell_test_mult_transpose_view - run the test at each timestep of the integrator

7493:    Notes:
7494:     This only works for problems defined only the RHS function and Jacobian NOT IFunction and IJacobian

7496:    Level: advanced

7498: .seealso: MatCreateShell(), MatShellGetContext(), MatShellGetOperation(), MatShellTestMultTranspose(), TSRHSJacobianTest()
7499: @*/
7500: PetscErrorCode  TSRHSJacobianTestTranspose(TS ts,PetscBool *flg)
7501: {
7502:   Mat            J,B;
7504:   void           *ctx;
7505:   TSRHSJacobian  func;

7508:   TSGetRHSJacobian(ts,&J,&B,&func,&ctx);
7509:   (*func)(ts,0.0,ts->vec_sol,J,B,ctx);
7510:   MatShellTestMultTranspose(J,RHSWrapperFunction_TSRHSJacobianTest,ts->vec_sol,ts,flg);
7511:   return(0);
7512: }

7514: /*@
7515:   TSSetUseSplitRHSFunction - Use the split RHSFunction when a multirate method is used.

7517:   Logically collective

7519:   Input Parameter:
7520: +  ts - timestepping context
7521: -  use_splitrhsfunction - PETSC_TRUE indicates that the split RHSFunction will be used

7523:   Options Database:
7524: .   -ts_use_splitrhsfunction - <true,false>

7526:   Notes:
7527:     This is only useful for multirate methods

7529:   Level: intermediate

7531: .seealso: TSGetUseSplitRHSFunction()
7532: @*/
7533: PetscErrorCode TSSetUseSplitRHSFunction(TS ts, PetscBool use_splitrhsfunction)
7534: {
7537:   ts->use_splitrhsfunction = use_splitrhsfunction;
7538:   return(0);
7539: }

7541: /*@
7542:   TSGetUseSplitRHSFunction - Gets whether to use the split RHSFunction when a multirate method is used.

7544:   Not collective

7546:   Input Parameter:
7547: .  ts - timestepping context

7549:   Output Parameter:
7550: .  use_splitrhsfunction - PETSC_TRUE indicates that the split RHSFunction will be used

7552:   Level: intermediate

7554: .seealso: TSSetUseSplitRHSFunction()
7555: @*/
7556: PetscErrorCode TSGetUseSplitRHSFunction(TS ts, PetscBool *use_splitrhsfunction)
7557: {
7560:   *use_splitrhsfunction = ts->use_splitrhsfunction;
7561:   return(0);
7562: }