Actual source code: ts.c

petsc-master 2019-12-13
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:     VecLockReadPush(U);
689:     PetscStackPush("TS user right-hand-side function");
690:     (*rhsfunction)(ts,t,U,y,ctx);
691:     PetscStackPop;
692:     VecLockReadPop(U);
693:   } else {
694:     VecZeroEntries(y);
695:   }

697:   PetscLogEventEnd(TS_FunctionEval,ts,U,y,0);
698:   return(0);
699: }

701: /*@
702:    TSComputeSolutionFunction - Evaluates the solution function.

704:    Collective on TS

706:    Input Parameters:
707: +  ts - the TS context
708: -  t - current time

710:    Output Parameter:
711: .  U - the solution

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

717:    Level: developer

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

731:   TSGetDM(ts,&dm);
732:   DMTSGetSolutionFunction(dm,&solutionfunction,&ctx);

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

744:    Collective on TS

746:    Input Parameters:
747: +  ts - the TS context
748: -  t - current time

750:    Output Parameter:
751: .  U - the function value

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

757:    Level: developer

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

770:   TSGetDM(ts,&dm);
771:   DMTSGetForcingFunction(dm,&forcing,&ctx);

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

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

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

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

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

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

848:    Collective on TS

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

857:    Output Parameter:
858: .  Y - right hand side

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

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

867:    Level: developer

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


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

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

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

916: /*@
917:    TSComputeIJacobian - Evaluates the Jacobian of the DAE

919:    Collective on TS

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

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

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

937:    dF/dU + shift*dF/dUdot

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

942:    Level: developer

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


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

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

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

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

1054:     Logically Collective on TS

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

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

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

1071:     Level: beginner

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

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


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

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

1104:     Logically Collective on TS

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

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

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

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

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

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

1130:     Level: beginner

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

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

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

1149:     Logically Collective on TS

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

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

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

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

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

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

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

1176:     Level: beginner

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

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

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

1196:    Logically Collective on TS

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

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

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

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

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

1221:    Level: beginner

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

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


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

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

1267:    Logically Collective on TS

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

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

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

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

1287:    Level: beginner

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


1302:   TSGetDM(ts,&dm);
1303:   DMTSSetIFunction(dm,f,ctx);

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

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

1318:    Not Collective

1320:    Input Parameter:
1321: .  ts - the TS context

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

1328:    Level: advanced

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

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

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

1350:    Not Collective

1352:    Input Parameter:
1353: .  ts - the TS context

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

1360:    Level: advanced

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

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

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

1383:    Logically Collective on TS

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

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

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

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

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

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

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

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

1421:    Level: beginner

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

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


1439:   TSGetDM(ts,&dm);
1440:   DMTSSetIJacobian(dm,f,ctx);

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

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

1453:    Logically Collective

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

1459:    Level: intermediate

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

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

1473:    Logically Collective on TS

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

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

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

1491:    Level: beginner

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

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

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

1512:   Not Collective

1514:   Input Parameter:
1515: . ts - the TS context

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

1522:   Level: advanced

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

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

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

1545:    Logically Collective on TS

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

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

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

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

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

1575:    Level: beginner

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

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

1594: /*@C
1595:   TSGetI2Jacobian - Returns the implicit Jacobian at the present timestep.

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

1599:   Input Parameter:
1600: . ts  - The TS context obtained from TSCreate()

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

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

1611:   Level: advanced

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

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

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

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

1634:   Collective on TS

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

1643:   Output Parameter:
1644: . F - the residual vector

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

1650:   Level: developer

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


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

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

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

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

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

1691:   PetscLogEventEnd(TS_FunctionEval,ts,U,V,F);
1692:   return(0);
1693: }

1695: /*@
1696:   TSComputeI2Jacobian - Evaluates the Jacobian of the DAE

1698:   Collective on TS

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

1709:   Output Parameters:
1710: + J - Jacobian matrix
1711: - P - optional preconditioning matrix

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

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

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

1721:   Level: developer

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


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

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

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

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

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

1764:   PetscLogEventEnd(TS_JacobianEval,ts,U,J,P);
1765:   return(0);
1766: }

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

1772:    Logically Collective on TS

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

1779:    Level: beginner

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

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

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

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

1805:    Input Parameter:
1806: .  ts - the TS context obtained from TSCreate()

1808:    Output Parameter:
1809: +  u - the vector containing the solution
1810: -  v - the vector containing the time derivative

1812:    Level: intermediate

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

1816: @*/
1817: PetscErrorCode  TS2GetSolution(TS ts,Vec *u,Vec *v)
1818: {
1823:   if (u) *u = ts->vec_sol;
1824:   if (v) *v = ts->vec_dot;
1825:   return(0);
1826: }

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

1831:   Collective on PetscViewer

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

1838:    Level: intermediate

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

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

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

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

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

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

1891: /*@C
1892:    TSViewFromOptions - View from Options

1894:    Collective on TS

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

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

1910:   PetscObjectViewFromOptions((PetscObject)A,obj,name);
1911:   return(0);
1912: }

1914: /*@C
1915:     TSView - Prints the TS data structure.

1917:     Collective on TS

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

1923:     Options Database Key:
1924: .   -ts_view - calls TSView() at end of TSStep()

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

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

1937:     Level: beginner

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

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

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

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

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

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

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

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

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

2084:    Logically Collective on TS

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

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

2094:    Level: intermediate

2096: .seealso: TSGetApplicationContext()
2097: @*/
2098: PetscErrorCode  TSSetApplicationContext(TS ts,void *usrP)
2099: {
2102:   ts->user = usrP;
2103:   return(0);
2104: }

2106: /*@
2107:     TSGetApplicationContext - Gets the user-defined context for the
2108:     timestepper.

2110:     Not Collective

2112:     Input Parameter:
2113: .   ts - the TS context obtained from TSCreate()

2115:     Output Parameter:
2116: .   usrP - user context

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

2122:     Level: intermediate

2124: .seealso: TSSetApplicationContext()
2125: @*/
2126: PetscErrorCode  TSGetApplicationContext(TS ts,void *usrP)
2127: {
2130:   *(void**)usrP = ts->user;
2131:   return(0);
2132: }

2134: /*@
2135:    TSGetStepNumber - Gets the number of steps completed.

2137:    Not Collective

2139:    Input Parameter:
2140: .  ts - the TS context obtained from TSCreate()

2142:    Output Parameter:
2143: .  steps - number of steps completed so far

2145:    Level: intermediate

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

2158: /*@
2159:    TSSetStepNumber - Sets the number of steps completed.

2161:    Logically Collective on TS

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

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

2177:    Level: advanced

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

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

2195:    Logically Collective on TS

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

2201:    Level: intermediate

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

2205: @*/
2206: PetscErrorCode  TSSetTimeStep(TS ts,PetscReal time_step)
2207: {
2211:   ts->time_step = time_step;
2212:   return(0);
2213: }

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

2220:   Logically Collective on TS

2222:    Input Parameter:
2223: +   ts - the time-step context
2224: -   eftopt - exact final time option

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

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

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

2236:    Level: beginner

2238: .seealso: TSExactFinalTimeOption, TSGetExactFinalTime()
2239: @*/
2240: PetscErrorCode TSSetExactFinalTime(TS ts,TSExactFinalTimeOption eftopt)
2241: {
2245:   ts->exact_final_time = eftopt;
2246:   return(0);
2247: }

2249: /*@
2250:    TSGetExactFinalTime - Gets the exact final time option.

2252:    Not Collective

2254:    Input Parameter:
2255: .  ts - the TS context

2257:    Output Parameter:
2258: .  eftopt - exact final time option

2260:    Level: beginner

2262: .seealso: TSExactFinalTimeOption, TSSetExactFinalTime()
2263: @*/
2264: PetscErrorCode TSGetExactFinalTime(TS ts,TSExactFinalTimeOption *eftopt)
2265: {
2269:   *eftopt = ts->exact_final_time;
2270:   return(0);
2271: }

2273: /*@
2274:    TSGetTimeStep - Gets the current timestep size.

2276:    Not Collective

2278:    Input Parameter:
2279: .  ts - the TS context obtained from TSCreate()

2281:    Output Parameter:
2282: .  dt - the current timestep size

2284:    Level: intermediate

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

2288: @*/
2289: PetscErrorCode  TSGetTimeStep(TS ts,PetscReal *dt)
2290: {
2294:   *dt = ts->time_step;
2295:   return(0);
2296: }

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

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

2306:    Input Parameter:
2307: .  ts - the TS context obtained from TSCreate()

2309:    Output Parameter:
2310: .  v - the vector containing the solution

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

2315:    Level: intermediate

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

2319: @*/
2320: PetscErrorCode  TSGetSolution(TS ts,Vec *v)
2321: {
2325:   *v = ts->vec_sol;
2326:   return(0);
2327: }

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

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

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

2346:    Level: advanced

2348: .seealso: TSGetSolution()

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

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

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

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

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

2374:    Level: intermediate

2376: .seealso: TSGetSolution()

2378: @*/
2379: PetscErrorCode  TSGetAuxSolution(TS ts,Vec *v)
2380: {

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

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

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

2399:    Note: MUST call after TSSetUp()

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

2406:    Level: intermediate

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

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

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

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

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

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

2436:    Level: intermediate

2438: .seealso: TSSetSolution(), TSGetTimeError)

2440: @*/
2441: PetscErrorCode  TSSetTimeError(TS ts,Vec v)
2442: {

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

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

2458:   Not collective

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

2469:    Level: beginner

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

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

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

2491:   Not collective

2493:   Input Parameter:
2494: . ts   - The TS

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

2504:    Level: beginner

2506: .seealso: TSSetUp(), TSProblemType, TS
2507: @*/
2508: PetscErrorCode  TSGetProblemType(TS ts, TSProblemType *type)
2509: {
2513:   *type = ts->problem_type;
2514:   return(0);
2515: }

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

2521:    Collective on TS

2523:    Input Parameter:
2524: .  ts - the TS context obtained from TSCreate()

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

2533:    Level: advanced

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

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

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

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

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

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

2571:   TSGetRHSJacobian(ts,NULL,NULL,&rhsjac,NULL);
2572:   if (ts->rhsjacobian.reuse && rhsjac == TSComputeRHSJacobianConstant) {
2573:     Mat Amat,Pmat;
2574:     SNES snes;
2575:     TSGetSNES(ts,&snes);
2576:     SNESGetJacobian(snes,&Amat,&Pmat,NULL,NULL);
2577:     /* Matching matrices implies that an IJacobian is NOT set, because if it had been set, the IJacobian's matrix would
2578:      * have displaced the RHS matrix */
2579:     if (Amat && Amat == ts->Arhs) {
2580:       /* 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 */
2581:       MatDuplicate(ts->Arhs,MAT_COPY_VALUES,&Amat);
2582:       SNESSetJacobian(snes,Amat,NULL,NULL,NULL);
2583:       MatDestroy(&Amat);
2584:     }
2585:     if (Pmat && Pmat == ts->Brhs) {
2586:       MatDuplicate(ts->Brhs,MAT_COPY_VALUES,&Pmat);
2587:       SNESSetJacobian(snes,NULL,Pmat,NULL,NULL);
2588:       MatDestroy(&Pmat);
2589:     }
2590:   }

2592:   TSGetAdapt(ts,&ts->adapt);
2593:   TSAdaptSetDefaultType(ts->adapt,ts->default_adapt_type);

2595:   if (ts->ops->setup) {
2596:     (*ts->ops->setup)(ts);
2597:   }

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

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

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

2628:   ts->setupcalled = PETSC_TRUE;
2629:   return(0);
2630: }

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

2635:    Collective on TS

2637:    Input Parameter:
2638: .  ts - the TS context obtained from TSCreate()

2640:    Level: beginner

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


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

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

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

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

2693:    Collective on TS

2695:    Input Parameter:
2696: .  ts - the TS context obtained from TSCreate()

2698:    Level: beginner

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

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

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

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

2722:   TSAdaptDestroy(&(*ts)->adapt);
2723:   TSEventDestroy(&(*ts)->event);

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

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

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

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

2741:    Input Parameter:
2742: .  ts - the TS context obtained from TSCreate()

2744:    Output Parameter:
2745: .  snes - the nonlinear solver context

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

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

2755:    Level: beginner

2757: @*/
2758: PetscErrorCode  TSGetSNES(TS ts,SNES *snes)
2759: {

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

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

2783:    Collective

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

2789:    Notes:
2790:    Most users should have the TS created by calling TSGetSNES()

2792:    Level: developer

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

2803:   PetscObjectReference((PetscObject)snes);
2804:   SNESDestroy(&ts->snes);

2806:   ts->snes = snes;

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

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

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

2822:    Input Parameter:
2823: .  ts - the TS context obtained from TSCreate()

2825:    Output Parameter:
2826: .  ksp - the nonlinear solver context

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

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

2836:    Level: beginner

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

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

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

2856: /*@
2857:    TSSetMaxSteps - Sets the maximum number of steps to use.

2859:    Logically Collective on TS

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

2865:    Options Database Keys:
2866: .  -ts_max_steps <maxsteps> - Sets maxsteps

2868:    Notes:
2869:    The default maximum number of steps is 5000

2871:    Level: intermediate

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

2885: /*@
2886:    TSGetMaxSteps - Gets the maximum number of steps to use.

2888:    Not Collective

2890:    Input Parameters:
2891: .  ts - the TS context obtained from TSCreate()

2893:    Output Parameter:
2894: .  maxsteps - maximum number of steps to use

2896:    Level: advanced

2898: .seealso: TSSetMaxSteps(), TSGetMaxTime(), TSSetMaxTime()
2899: @*/
2900: PetscErrorCode TSGetMaxSteps(TS ts,PetscInt *maxsteps)
2901: {
2905:   *maxsteps = ts->max_steps;
2906:   return(0);
2907: }

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

2912:    Logically Collective on TS

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

2918:    Options Database Keys:
2919: .  -ts_max_time <maxtime> - Sets maxtime

2921:    Notes:
2922:    The default maximum time is 5.0

2924:    Level: intermediate

2926: .seealso: TSGetMaxTime(), TSSetMaxSteps(), TSSetExactFinalTime()
2927: @*/
2928: PetscErrorCode TSSetMaxTime(TS ts,PetscReal maxtime)
2929: {
2933:   ts->max_time = maxtime;
2934:   return(0);
2935: }

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

2940:    Not Collective

2942:    Input Parameters:
2943: .  ts - the TS context obtained from TSCreate()

2945:    Output Parameter:
2946: .  maxtime - final time to step to

2948:    Level: advanced

2950: .seealso: TSSetMaxTime(), TSGetMaxSteps(), TSSetMaxSteps()
2951: @*/
2952: PetscErrorCode TSGetMaxTime(TS ts,PetscReal *maxtime)
2953: {
2957:   *maxtime = ts->max_time;
2958:   return(0);
2959: }

2961: /*@
2962:    TSSetInitialTimeStep - Deprecated, use TSSetTime() and TSSetTimeStep().

2964:    Level: deprecated

2966: @*/
2967: PetscErrorCode  TSSetInitialTimeStep(TS ts,PetscReal initial_time,PetscReal time_step)
2968: {
2972:   TSSetTime(ts,initial_time);
2973:   TSSetTimeStep(ts,time_step);
2974:   return(0);
2975: }

2977: /*@
2978:    TSGetDuration - Deprecated, use TSGetMaxSteps() and TSGetMaxTime().

2980:    Level: deprecated

2982: @*/
2983: PetscErrorCode TSGetDuration(TS ts, PetscInt *maxsteps, PetscReal *maxtime)
2984: {
2987:   if (maxsteps) {
2989:     *maxsteps = ts->max_steps;
2990:   }
2991:   if (maxtime) {
2993:     *maxtime = ts->max_time;
2994:   }
2995:   return(0);
2996: }

2998: /*@
2999:    TSSetDuration - Deprecated, use TSSetMaxSteps() and TSSetMaxTime().

3001:    Level: deprecated

3003: @*/
3004: PetscErrorCode TSSetDuration(TS ts,PetscInt maxsteps,PetscReal maxtime)
3005: {
3010:   if (maxsteps >= 0) ts->max_steps = maxsteps;
3011:   if (maxtime != PETSC_DEFAULT) ts->max_time = maxtime;
3012:   return(0);
3013: }

3015: /*@
3016:    TSGetTimeStepNumber - Deprecated, use TSGetStepNumber().

3018:    Level: deprecated

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

3023: /*@
3024:    TSGetTotalSteps - Deprecated, use TSGetStepNumber().

3026:    Level: deprecated

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

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

3035:    Logically Collective on TS

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

3041:    Level: beginner

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

3053:   PetscObjectReference((PetscObject)u);
3054:   VecDestroy(&ts->vec_sol);
3055:   ts->vec_sol = u;

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

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

3066:   Logically Collective on TS

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

3072:   Calling sequence of func:
3073: .   PetscErrorCode func (TS ts);

3075:   Level: intermediate

3077: .seealso: TSSetPreStage(), TSSetPostStage(), TSSetPostStep(), TSStep(), TSRestartStep()
3078: @*/
3079: PetscErrorCode  TSSetPreStep(TS ts, PetscErrorCode (*func)(TS))
3080: {
3083:   ts->prestep = func;
3084:   return(0);
3085: }

3087: /*@
3088:   TSPreStep - Runs the user-defined pre-step function.

3090:   Collective on TS

3092:   Input Parameters:
3093: . ts   - The TS context obtained from TSCreate()

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

3099:   Level: developer

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

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

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

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

3126:   Logically Collective on TS

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

3132:   Calling sequence of func:
3133: .    PetscErrorCode func(TS ts, PetscReal stagetime);

3135:   Level: intermediate

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

3142: .seealso: TSSetPostStage(), TSSetPreStep(), TSSetPostStep(), TSGetApplicationContext()
3143: @*/
3144: PetscErrorCode  TSSetPreStage(TS ts, PetscErrorCode (*func)(TS,PetscReal))
3145: {
3148:   ts->prestage = func;
3149:   return(0);
3150: }

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

3156:   Logically Collective on TS

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

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

3165:   Level: intermediate

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

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

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

3186:   Logically Collective on TS

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

3192:   Calling sequence of func:
3193: . PetscErrorCode func(TS ts);

3195:   Level: intermediate

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

3204: .seealso: TSSetPreStage(), TSSetPreStep(), TSSetPostStep(), TSGetApplicationContext()
3205: @*/
3206: PetscErrorCode  TSSetPostEvaluate(TS ts, PetscErrorCode (*func)(TS))
3207: {
3210:   ts->postevaluate = func;
3211:   return(0);
3212: }

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

3217:   Collective on TS

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

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

3227:   Level: developer

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

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

3244:   Collective on TS

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

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

3257:   Level: developer

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

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

3274:   Collective on TS

3276:   Input Parameters:
3277: . ts          - The TS context obtained from TSCreate()

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

3283:   Level: developer

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

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

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

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

3310:   Logically Collective on TS

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

3316:   Calling sequence of func:
3317: $ func (TS ts);

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

3324:   Level: intermediate

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

3336: /*@
3337:   TSPostStep - Runs the user-defined post-step function.

3339:   Collective on TS

3341:   Input Parameters:
3342: . ts   - The TS context obtained from TSCreate()

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

3348:   Level: developer

3350: @*/
3351: PetscErrorCode  TSPostStep(TS ts)
3352: {

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

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

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

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

3376:    Logically Collective on TS

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

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

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

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

3399:    Fortran Notes:
3400:     Only a single monitor function can be set for each TS object

3402:    Level: intermediate

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

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

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

3428:    Logically Collective on TS

3430:    Input Parameters:
3431: .  ts - the TS context obtained from TSCreate()

3433:    Notes:
3434:    There is no way to remove a single, specific monitor.

3436:    Level: intermediate

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

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

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

3459:    Level: intermediate

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

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

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

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

3505:    Level: intermediate

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


3519:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERASCII,&iascii);
3520:   PetscViewerPushFormat(viewer,vf->format);
3521:   if (iascii) {
3522:     VecMax(v,NULL,&max);
3523:     VecMin(v,NULL,&min);
3524:     PetscViewerASCIIAddTab(viewer,((PetscObject)ts)->tablevel);
3525:     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);
3526:     PetscViewerASCIISubtractTab(viewer,((PetscObject)ts)->tablevel);
3527:   }
3528:   PetscViewerPopFormat(viewer);
3529:   return(0);
3530: }

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

3535:    Collective on TS

3537:    Input Argument:
3538: +  ts - time stepping context
3539: -  t - time to interpolate to

3541:    Output Argument:
3542: .  U - state at given time

3544:    Level: intermediate

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

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

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

3564: /*@
3565:    TSStep - Steps one time step

3567:    Collective on TS

3569:    Input Parameter:
3570: .  ts - the TS context obtained from TSCreate()

3572:    Level: developer

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

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

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

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

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

3601:   TSSetUp(ts);
3602:   TSTrajectorySetUp(ts->trajectory,ts);

3604:   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>");
3605:   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()");
3606:   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");

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

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

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

3636:    Collective on TS

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

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

3647:    Level: advanced

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

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

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

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

3676:    Collective on TS

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

3683:    Output Arguments:
3684: .  U - state at the end of the current step

3686:    Level: advanced

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

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

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

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

3710:   Not collective

3712:   Input Argument:
3713: . ts        - time stepping context

3715:   Output Argument:
3716: . initConditions - The function which computes an initial condition

3718:    Level: advanced

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

3726: .seealso: TSSetComputeInitialCondition(), TSComputeInitialCondition()
3727: @*/
3728: PetscErrorCode TSGetComputeInitialCondition(TS ts, PetscErrorCode (**initCondition)(TS, Vec))
3729: {
3733:   *initCondition = ts->ops->initcondition;
3734:   return(0);
3735: }

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

3740:   Logically collective on ts

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

3746:   Level: advanced

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

3754: .seealso: TSGetComputeInitialCondition(), TSComputeInitialCondition()
3755: @*/
3756: PetscErrorCode TSSetComputeInitialCondition(TS ts, PetscErrorCode (*initCondition)(TS, Vec))
3757: {
3761:   ts->ops->initcondition = initCondition;
3762:   return(0);
3763: }

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

3768:   Collective on ts

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

3774:   Level: advanced

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

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

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

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

3798:   Not collective

3800:   Input Argument:
3801: . ts         - time stepping context

3803:   Output Argument:
3804: . exactError - The function which computes the solution error

3806:   Level: advanced

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

3815: .seealso: TSGetComputeExactError(), TSComputeExactError()
3816: @*/
3817: PetscErrorCode TSGetComputeExactError(TS ts, PetscErrorCode (**exactError)(TS, Vec, Vec))
3818: {
3822:   *exactError = ts->ops->exacterror;
3823:   return(0);
3824: }

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

3829:   Logically collective on ts

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

3835:   Level: advanced

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

3844: .seealso: TSGetComputeExactError(), TSComputeExactError()
3845: @*/
3846: PetscErrorCode TSSetComputeExactError(TS ts, PetscErrorCode (*exactError)(TS, Vec, Vec))
3847: {
3851:   ts->ops->exacterror = exactError;
3852:   return(0);
3853: }

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

3858:   Collective on ts

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

3865:   Level: advanced

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

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

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

3888: /*@
3889:    TSSolve - Steps the requested number of timesteps.

3891:    Collective on TS

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

3898:    Level: beginner

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

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


3916:   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 */
3917:     if (!ts->vec_sol || u == ts->vec_sol) {
3918:       VecDuplicate(u,&solution);
3919:       TSSetSolution(ts,solution);
3920:       VecDestroy(&solution); /* grant ownership */
3921:     }
3922:     VecCopy(u,ts->vec_sol);
3923:     if (ts->forward_solve) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"Sensitivity analysis does not support the mode TS_EXACTFINALTIME_INTERPOLATE");
3924:   } else if (u) {
3925:     TSSetSolution(ts,u);
3926:   }
3927:   TSSetUp(ts);
3928:   TSTrajectorySetUp(ts->trajectory,ts);

3930:   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>");
3931:   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()");
3932:   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");

3934:   if (ts->forward_solve) {
3935:     TSForwardSetUp(ts);
3936:   }

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

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

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

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

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

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

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

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

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

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

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

4060:    Collective on TS

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

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

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

4074:    Level: developer

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


4087:   TSGetDM(ts,&dm);
4088:   DMSetOutputSequenceNumber(dm,step,ptime);

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

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

4103:    Collective on TS

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

4112:    Output Parameter:
4113: .  ctx - the context

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

4124:    Notes:
4125:    Use TSMonitorLGCtxDestroy() to destroy.

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

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

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

4135:    Level: intermediate

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

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

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

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

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

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

4189:    Collective on TSMonitorLGCtx

4191:    Input Parameter:
4192: .  ctx - the monitor context

4194:    Level: intermediate

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

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

4215: /*

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

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

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

4234: }

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


4245:   PetscDrawSPDestroy(&(*ctx)->sp);
4246:   PetscFree(*ctx);

4248:   return(0);

4250: }

4252: /*@
4253:    TSGetTime - Gets the time of the most recently completed step.

4255:    Not Collective

4257:    Input Parameter:
4258: .  ts - the TS context obtained from TSCreate()

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

4263:    Level: beginner

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

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

4271: @*/
4272: PetscErrorCode  TSGetTime(TS ts,PetscReal *t)
4273: {
4277:   *t = ts->ptime;
4278:   return(0);
4279: }

4281: /*@
4282:    TSGetPrevTime - Gets the starting time of the previously completed step.

4284:    Not Collective

4286:    Input Parameter:
4287: .  ts - the TS context obtained from TSCreate()

4289:    Output Parameter:
4290: .  t  - the previous time

4292:    Level: beginner

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

4296: @*/
4297: PetscErrorCode  TSGetPrevTime(TS ts,PetscReal *t)
4298: {
4302:   *t = ts->ptime_prev;
4303:   return(0);
4304: }

4306: /*@
4307:    TSSetTime - Allows one to reset the time.

4309:    Logically Collective on TS

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

4315:    Level: intermediate

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

4319: @*/
4320: PetscErrorCode  TSSetTime(TS ts, PetscReal t)
4321: {
4325:   ts->ptime = t;
4326:   return(0);
4327: }

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

4333:    Logically Collective on TS

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

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

4344:    Level: advanced

4346: .seealso: TSSetFromOptions()

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

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

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

4366:    Logically Collective on TS

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

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

4377:    Level: advanced

4379: .seealso: TSGetOptionsPrefix()

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

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

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

4399:    Not Collective

4401:    Input Parameter:
4402: .  ts - The TS context

4404:    Output Parameter:
4405: .  prefix - A pointer to the prefix string used

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

4411:    Level: intermediate

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

4422:   PetscObjectGetOptionsPrefix((PetscObject)ts,prefix);
4423:   return(0);
4424: }

4426: /*@C
4427:    TSGetRHSJacobian - Returns the Jacobian J at the present timestep.

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

4431:    Input Parameter:
4432: .  ts  - The TS context obtained from TSCreate()

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

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

4443:    Level: intermediate

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

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

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

4465: /*@C
4466:    TSGetIJacobian - Returns the implicit Jacobian at the present timestep.

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

4470:    Input Parameter:
4471: .  ts  - The TS context obtained from TSCreate()

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

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

4482:    Level: advanced

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

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

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

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

4508:    Collective on TS

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

4516:    Options Database:
4517: .   -ts_monitor_draw_solution_initial - show initial solution as well as current solution

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

4523:    Level: intermediate

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

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

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

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

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

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

4572:    Collective on TS

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

4580:    Level: intermediate

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

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

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

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

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

4631: /*@C
4632:    TSMonitorDrawCtxDestroy - Destroys the monitor context for TSMonitorDrawSolution()

4634:    Collective on TS

4636:    Input Parameters:
4637: .    ctx - the monitor context

4639:    Level: intermediate

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

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

4654: /*@C
4655:    TSMonitorDrawCtxCreate - Creates the monitor context for TSMonitorDrawCtx

4657:    Collective on TS

4659:    Input Parameter:
4660: .    ts - time-step context

4662:    Output Patameter:
4663: .    ctx - the monitor context

4665:    Options Database:
4666: .   -ts_monitor_draw_solution_initial - show initial solution as well as current solution

4668:    Level: intermediate

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

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

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

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

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

4694:    Collective on TS

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

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

4705:    Level: intermediate

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

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

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

4729:    Collective on TS

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

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

4740:    Level: intermediate

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

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

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

4765:    Logically Collective on ts

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

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

4776:    Level: intermediate

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

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

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

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

4810:    Not Collective

4812:    Input Parameter:
4813: . ts - the preconditioner context

4815:    Output Parameter:
4816: .  dm - the dm

4818:    Level: intermediate

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

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

4836: /*@
4837:    SNESTSFormFunction - Function to evaluate nonlinear residual

4839:    Logically Collective on SNES

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

4846:    Output Parameter:
4847: . F - the nonlinear residual

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

4853:    Level: advanced

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

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

4871: /*@
4872:    SNESTSFormJacobian - Function to evaluate the Jacobian

4874:    Collective on SNES

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

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

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

4889:    Level: developer

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

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

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

4913:    Collective on TS

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

4921:    Output Arguments:
4922: .  F - right hand side

4924:    Level: intermediate

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

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

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

4944: /*@C
4945:    TSComputeRHSJacobianConstant - Reuses a Jacobian that is time-independent.

4947:    Collective on TS

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

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

4960:    Level: intermediate

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

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

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

4976:    Collective on TS

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

4985:    Output Arguments:
4986: .  F - left hand side

4988:    Level: intermediate

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

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

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

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

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

5015:    Collective on TS

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

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

5030:    Level: advanced

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

5035:    It is only appropriate for problems of the form

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

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

5043: $    shift*M + J

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

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

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

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

5063:    Not Collective

5065:    Input Parameter:
5066: .  ts - the TS context

5068:    Output Parameter:
5069: .  equation_type - see TSEquationType

5071:    Level: beginner

5073: .seealso: TSSetEquationType(), TSEquationType
5074: @*/
5075: PetscErrorCode  TSGetEquationType(TS ts,TSEquationType *equation_type)
5076: {
5080:   *equation_type = ts->equation_type;
5081:   return(0);
5082: }

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

5087:    Not Collective

5089:    Input Parameter:
5090: +  ts - the TS context
5091: -  equation_type - see TSEquationType

5093:    Level: advanced

5095: .seealso: TSGetEquationType(), TSEquationType
5096: @*/
5097: PetscErrorCode  TSSetEquationType(TS ts,TSEquationType equation_type)
5098: {
5101:   ts->equation_type = equation_type;
5102:   return(0);
5103: }

5105: /*@
5106:    TSGetConvergedReason - Gets the reason the TS iteration was stopped.

5108:    Not Collective

5110:    Input Parameter:
5111: .  ts - the TS context

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

5117:    Level: beginner

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

5122: .seealso: TSSetConvergenceTest(), TSConvergedReason
5123: @*/
5124: PetscErrorCode  TSGetConvergedReason(TS ts,TSConvergedReason *reason)
5125: {
5129:   *reason = ts->reason;
5130:   return(0);
5131: }

5133: /*@
5134:    TSSetConvergedReason - Sets the reason for handling the convergence of TSSolve.

5136:    Logically Collective; reason must contain common value

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

5143:    Level: advanced

5145:    Notes:
5146:    Can only be called while TSSolve() is active.

5148: .seealso: TSConvergedReason
5149: @*/
5150: PetscErrorCode  TSSetConvergedReason(TS ts,TSConvergedReason reason)
5151: {
5154:   ts->reason = reason;
5155:   return(0);
5156: }

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

5161:    Not Collective

5163:    Input Parameter:
5164: .  ts - the TS context

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

5169:    Level: beginner

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

5174: .seealso: TSSetConvergenceTest(), TSConvergedReason
5175: @*/
5176: PetscErrorCode  TSGetSolveTime(TS ts,PetscReal *ftime)
5177: {
5181:   *ftime = ts->solvetime;
5182:   return(0);
5183: }

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

5189:    Not Collective

5191:    Input Parameter:
5192: .  ts - TS context

5194:    Output Parameter:
5195: .  nits - number of nonlinear iterations

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

5200:    Level: intermediate

5202: .seealso:  TSGetKSPIterations()
5203: @*/
5204: PetscErrorCode TSGetSNESIterations(TS ts,PetscInt *nits)
5205: {
5209:   *nits = ts->snes_its;
5210:   return(0);
5211: }

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

5217:    Not Collective

5219:    Input Parameter:
5220: .  ts - TS context

5222:    Output Parameter:
5223: .  lits - number of linear iterations

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

5228:    Level: intermediate

5230: .seealso:  TSGetSNESIterations(), SNESGetKSPIterations()
5231: @*/
5232: PetscErrorCode TSGetKSPIterations(TS ts,PetscInt *lits)
5233: {
5237:   *lits = ts->ksp_its;
5238:   return(0);
5239: }

5241: /*@
5242:    TSGetStepRejections - Gets the total number of rejected steps.

5244:    Not Collective

5246:    Input Parameter:
5247: .  ts - TS context

5249:    Output Parameter:
5250: .  rejects - number of steps rejected

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

5255:    Level: intermediate

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

5268: /*@
5269:    TSGetSNESFailures - Gets the total number of failed SNES solves

5271:    Not Collective

5273:    Input Parameter:
5274: .  ts - TS context

5276:    Output Parameter:
5277: .  fails - number of failed nonlinear solves

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

5282:    Level: intermediate

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

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

5298:    Not Collective

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

5304:    Notes:
5305:    The counter is reset to zero for each step

5307:    Options Database Key:
5308:  .  -ts_max_reject - Maximum number of step rejections before a step fails

5310:    Level: intermediate

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

5322: /*@
5323:    TSSetMaxSNESFailures - Sets the maximum number of failed SNES solves

5325:    Not Collective

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

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

5334:    Options Database Key:
5335:  .  -ts_max_snes_failures - Maximum number of nonlinear solve failures

5337:    Level: intermediate

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

5349: /*@
5350:    TSSetErrorIfStepFails - Error if no step succeeds

5352:    Not Collective

5354:    Input Parameter:
5355: +  ts - TS context
5356: -  err - PETSC_TRUE to error if no step succeeds, PETSC_FALSE to return without failure

5358:    Options Database Key:
5359:  .  -ts_error_if_step_fails - Error if no step succeeds

5361:    Level: intermediate

5363: .seealso:  TSGetSNESIterations(), TSGetKSPIterations(), TSSetMaxStepRejections(), TSGetStepRejections(), TSGetSNESFailures(), TSSetErrorIfStepFails(), TSGetConvergedReason()
5364: @*/
5365: PetscErrorCode TSSetErrorIfStepFails(TS ts,PetscBool err)
5366: {
5369:   ts->errorifstepfailed = err;
5370:   return(0);
5371: }

5373: /*@C
5374:    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

5376:    Collective on TS

5378:    Input Parameters:
5379: +  ts - the TS context
5380: .  step - current time-step
5381: .  ptime - current time
5382: .  u - current state
5383: -  vf - viewer and its format

5385:    Level: intermediate

5387: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView()
5388: @*/
5389: PetscErrorCode  TSMonitorSolution(TS ts,PetscInt step,PetscReal ptime,Vec u,PetscViewerAndFormat *vf)
5390: {

5394:   PetscViewerPushFormat(vf->viewer,vf->format);
5395:   VecView(u,vf->viewer);
5396:   PetscViewerPopFormat(vf->viewer);
5397:   return(0);
5398: }

5400: /*@C
5401:    TSMonitorSolutionVTK - Monitors progress of the TS solvers by VecView() for the solution at each timestep.

5403:    Collective on TS

5405:    Input Parameters:
5406: +  ts - the TS context
5407: .  step - current time-step
5408: .  ptime - current time
5409: .  u - current state
5410: -  filenametemplate - string containing a format specifier for the integer time step (e.g. %03D)

5412:    Level: intermediate

5414:    Notes:
5415:    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.
5416:    These are named according to the file name template.

5418:    This function is normally passed as an argument to TSMonitorSet() along with TSMonitorSolutionVTKDestroy().

5420: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView()
5421: @*/
5422: PetscErrorCode TSMonitorSolutionVTK(TS ts,PetscInt step,PetscReal ptime,Vec u,void *filenametemplate)
5423: {
5425:   char           filename[PETSC_MAX_PATH_LEN];
5426:   PetscViewer    viewer;

5429:   if (step < 0) return(0); /* -1 indicates interpolated solution */
5430:   PetscSNPrintf(filename,sizeof(filename),(const char*)filenametemplate,step);
5431:   PetscViewerVTKOpen(PetscObjectComm((PetscObject)ts),filename,FILE_MODE_WRITE,&viewer);
5432:   VecView(u,viewer);
5433:   PetscViewerDestroy(&viewer);
5434:   return(0);
5435: }

5437: /*@C
5438:    TSMonitorSolutionVTKDestroy - Destroy context for monitoring

5440:    Collective on TS

5442:    Input Parameters:
5443: .  filenametemplate - string containing a format specifier for the integer time step (e.g. %03D)

5445:    Level: intermediate

5447:    Note:
5448:    This function is normally passed to TSMonitorSet() along with TSMonitorSolutionVTK().

5450: .seealso: TSMonitorSet(), TSMonitorSolutionVTK()
5451: @*/
5452: PetscErrorCode TSMonitorSolutionVTKDestroy(void *filenametemplate)
5453: {

5457:   PetscFree(*(char**)filenametemplate);
5458:   return(0);
5459: }

5461: /*@
5462:    TSGetAdapt - Get the adaptive controller context for the current method

5464:    Collective on TS if controller has not been created yet

5466:    Input Arguments:
5467: .  ts - time stepping context

5469:    Output Arguments:
5470: .  adapt - adaptive controller

5472:    Level: intermediate

5474: .seealso: TSAdapt, TSAdaptSetType(), TSAdaptChoose()
5475: @*/
5476: PetscErrorCode TSGetAdapt(TS ts,TSAdapt *adapt)
5477: {

5483:   if (!ts->adapt) {
5484:     TSAdaptCreate(PetscObjectComm((PetscObject)ts),&ts->adapt);
5485:     PetscLogObjectParent((PetscObject)ts,(PetscObject)ts->adapt);
5486:     PetscObjectIncrementTabLevel((PetscObject)ts->adapt,(PetscObject)ts,1);
5487:   }
5488:   *adapt = ts->adapt;
5489:   return(0);
5490: }

5492: /*@
5493:    TSSetTolerances - Set tolerances for local truncation error when using adaptive controller

5495:    Logically Collective

5497:    Input Arguments:
5498: +  ts - time integration context
5499: .  atol - scalar absolute tolerances, PETSC_DECIDE to leave current value
5500: .  vatol - vector of absolute tolerances or NULL, used in preference to atol if present
5501: .  rtol - scalar relative tolerances, PETSC_DECIDE to leave current value
5502: -  vrtol - vector of relative tolerances or NULL, used in preference to atol if present

5504:    Options Database keys:
5505: +  -ts_rtol <rtol> - relative tolerance for local truncation error
5506: -  -ts_atol <atol> Absolute tolerance for local truncation error

5508:    Notes:
5509:    With PETSc's implicit schemes for DAE problems, the calculation of the local truncation error
5510:    (LTE) includes both the differential and the algebraic variables. If one wants the LTE to be
5511:    computed only for the differential or the algebraic part then this can be done using the vector of
5512:    tolerances vatol. For example, by setting the tolerance vector with the desired tolerance for the
5513:    differential part and infinity for the algebraic part, the LTE calculation will include only the
5514:    differential variables.

5516:    Level: beginner

5518: .seealso: TS, TSAdapt, TSVecNormWRMS(), TSGetTolerances()
5519: @*/
5520: PetscErrorCode TSSetTolerances(TS ts,PetscReal atol,Vec vatol,PetscReal rtol,Vec vrtol)
5521: {

5525:   if (atol != PETSC_DECIDE && atol != PETSC_DEFAULT) ts->atol = atol;
5526:   if (vatol) {
5527:     PetscObjectReference((PetscObject)vatol);
5528:     VecDestroy(&ts->vatol);
5529:     ts->vatol = vatol;
5530:   }
5531:   if (rtol != PETSC_DECIDE && rtol != PETSC_DEFAULT) ts->rtol = rtol;
5532:   if (vrtol) {
5533:     PetscObjectReference((PetscObject)vrtol);
5534:     VecDestroy(&ts->vrtol);
5535:     ts->vrtol = vrtol;
5536:   }
5537:   return(0);
5538: }

5540: /*@
5541:    TSGetTolerances - Get tolerances for local truncation error when using adaptive controller

5543:    Logically Collective

5545:    Input Arguments:
5546: .  ts - time integration context

5548:    Output Arguments:
5549: +  atol - scalar absolute tolerances, NULL to ignore
5550: .  vatol - vector of absolute tolerances, NULL to ignore
5551: .  rtol - scalar relative tolerances, NULL to ignore
5552: -  vrtol - vector of relative tolerances, NULL to ignore

5554:    Level: beginner

5556: .seealso: TS, TSAdapt, TSVecNormWRMS(), TSSetTolerances()
5557: @*/
5558: PetscErrorCode TSGetTolerances(TS ts,PetscReal *atol,Vec *vatol,PetscReal *rtol,Vec *vrtol)
5559: {
5561:   if (atol)  *atol  = ts->atol;
5562:   if (vatol) *vatol = ts->vatol;
5563:   if (rtol)  *rtol  = ts->rtol;
5564:   if (vrtol) *vrtol = ts->vrtol;
5565:   return(0);
5566: }

5568: /*@
5569:    TSErrorWeightedNorm2 - compute a weighted 2-norm of the difference between two state vectors

5571:    Collective on TS

5573:    Input Arguments:
5574: +  ts - time stepping context
5575: .  U - state vector, usually ts->vec_sol
5576: -  Y - state vector to be compared to U

5578:    Output Arguments:
5579: +  norm - weighted norm, a value of 1.0 means that the error matches the tolerances
5580: .  norma - weighted norm based on the absolute tolerance, a value of 1.0 means that the error matches the tolerances
5581: -  normr - weighted norm based on the relative tolerance, a value of 1.0 means that the error matches the tolerances

5583:    Level: developer

5585: .seealso: TSErrorWeightedNorm(), TSErrorWeightedNormInfinity()
5586: @*/
5587: PetscErrorCode TSErrorWeightedNorm2(TS ts,Vec U,Vec Y,PetscReal *norm,PetscReal *norma,PetscReal *normr)
5588: {
5589:   PetscErrorCode    ierr;
5590:   PetscInt          i,n,N,rstart;
5591:   PetscInt          n_loc,na_loc,nr_loc;
5592:   PetscReal         n_glb,na_glb,nr_glb;
5593:   const PetscScalar *u,*y;
5594:   PetscReal         sum,suma,sumr,gsum,gsuma,gsumr,diff;
5595:   PetscReal         tol,tola,tolr;
5596:   PetscReal         err_loc[6],err_glb[6];

5608:   if (U == Y) SETERRQ(PetscObjectComm((PetscObject)U),PETSC_ERR_ARG_IDN,"U and Y cannot be the same vector");

5610:   VecGetSize(U,&N);
5611:   VecGetLocalSize(U,&n);
5612:   VecGetOwnershipRange(U,&rstart,NULL);
5613:   VecGetArrayRead(U,&u);
5614:   VecGetArrayRead(Y,&y);
5615:   sum  = 0.; n_loc  = 0;
5616:   suma = 0.; na_loc = 0;
5617:   sumr = 0.; nr_loc = 0;
5618:   if (ts->vatol && ts->vrtol) {
5619:     const PetscScalar *atol,*rtol;
5620:     VecGetArrayRead(ts->vatol,&atol);
5621:     VecGetArrayRead(ts->vrtol,&rtol);
5622:     for (i=0; i<n; i++) {
5623:       SkipSmallValue(y[i],u[i],ts->adapt->ignore_max);
5624:       diff = PetscAbsScalar(y[i] - u[i]);
5625:       tola = PetscRealPart(atol[i]);
5626:       if(tola>0.){
5627:         suma  += PetscSqr(diff/tola);
5628:         na_loc++;
5629:       }
5630:       tolr = PetscRealPart(rtol[i]) * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
5631:       if(tolr>0.){
5632:         sumr  += PetscSqr(diff/tolr);
5633:         nr_loc++;
5634:       }
5635:       tol=tola+tolr;
5636:       if(tol>0.){
5637:         sum  += PetscSqr(diff/tol);
5638:         n_loc++;
5639:       }
5640:     }
5641:     VecRestoreArrayRead(ts->vatol,&atol);
5642:     VecRestoreArrayRead(ts->vrtol,&rtol);
5643:   } else if (ts->vatol) {       /* vector atol, scalar rtol */
5644:     const PetscScalar *atol;
5645:     VecGetArrayRead(ts->vatol,&atol);
5646:     for (i=0; i<n; i++) {
5647:       SkipSmallValue(y[i],u[i],ts->adapt->ignore_max);
5648:       diff = PetscAbsScalar(y[i] - u[i]);
5649:       tola = PetscRealPart(atol[i]);
5650:       if(tola>0.){
5651:         suma  += PetscSqr(diff/tola);
5652:         na_loc++;
5653:       }
5654:       tolr = ts->rtol * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
5655:       if(tolr>0.){
5656:         sumr  += PetscSqr(diff/tolr);
5657:         nr_loc++;
5658:       }
5659:       tol=tola+tolr;
5660:       if(tol>0.){
5661:         sum  += PetscSqr(diff/tol);
5662:         n_loc++;
5663:       }
5664:     }
5665:     VecRestoreArrayRead(ts->vatol,&atol);
5666:   } else if (ts->vrtol) {       /* scalar atol, vector rtol */
5667:     const PetscScalar *rtol;
5668:     VecGetArrayRead(ts->vrtol,&rtol);
5669:     for (i=0; i<n; i++) {
5670:       SkipSmallValue(y[i],u[i],ts->adapt->ignore_max);
5671:       diff = PetscAbsScalar(y[i] - u[i]);
5672:       tola = ts->atol;
5673:       if(tola>0.){
5674:         suma  += PetscSqr(diff/tola);
5675:         na_loc++;
5676:       }
5677:       tolr = PetscRealPart(rtol[i]) * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
5678:       if(tolr>0.){
5679:         sumr  += PetscSqr(diff/tolr);
5680:         nr_loc++;
5681:       }
5682:       tol=tola+tolr;
5683:       if(tol>0.){
5684:         sum  += PetscSqr(diff/tol);
5685:         n_loc++;
5686:       }
5687:     }
5688:     VecRestoreArrayRead(ts->vrtol,&rtol);
5689:   } else {                      /* scalar atol, scalar rtol */
5690:     for (i=0; i<n; i++) {
5691:       SkipSmallValue(y[i],u[i],ts->adapt->ignore_max);
5692:       diff = PetscAbsScalar(y[i] - u[i]);
5693:       tola = ts->atol;
5694:       if(tola>0.){
5695:         suma  += PetscSqr(diff/tola);
5696:         na_loc++;
5697:       }
5698:       tolr = ts->rtol * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
5699:       if(tolr>0.){
5700:         sumr  += PetscSqr(diff/tolr);
5701:         nr_loc++;
5702:       }
5703:       tol=tola+tolr;
5704:       if(tol>0.){
5705:         sum  += PetscSqr(diff/tol);
5706:         n_loc++;
5707:       }
5708:     }
5709:   }
5710:   VecRestoreArrayRead(U,&u);
5711:   VecRestoreArrayRead(Y,&y);

5713:   err_loc[0] = sum;
5714:   err_loc[1] = suma;
5715:   err_loc[2] = sumr;
5716:   err_loc[3] = (PetscReal)n_loc;
5717:   err_loc[4] = (PetscReal)na_loc;
5718:   err_loc[5] = (PetscReal)nr_loc;

5720:   MPIU_Allreduce(err_loc,err_glb,6,MPIU_REAL,MPIU_SUM,PetscObjectComm((PetscObject)ts));

5722:   gsum   = err_glb[0];
5723:   gsuma  = err_glb[1];
5724:   gsumr  = err_glb[2];
5725:   n_glb  = err_glb[3];
5726:   na_glb = err_glb[4];
5727:   nr_glb = err_glb[5];

5729:   *norm  = 0.;
5730:   if(n_glb>0. ){*norm  = PetscSqrtReal(gsum  / n_glb );}
5731:   *norma = 0.;
5732:   if(na_glb>0.){*norma = PetscSqrtReal(gsuma / na_glb);}
5733:   *normr = 0.;
5734:   if(nr_glb>0.){*normr = PetscSqrtReal(gsumr / nr_glb);}

5736:   if (PetscIsInfOrNanScalar(*norm)) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_FP,"Infinite or not-a-number generated in norm");
5737:   if (PetscIsInfOrNanScalar(*norma)) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_FP,"Infinite or not-a-number generated in norma");
5738:   if (PetscIsInfOrNanScalar(*normr)) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_FP,"Infinite or not-a-number generated in normr");
5739:   return(0);
5740: }

5742: /*@
5743:    TSErrorWeightedNormInfinity - compute a weighted infinity-norm of the difference between two state vectors

5745:    Collective on TS

5747:    Input Arguments:
5748: +  ts - time stepping context
5749: .  U - state vector, usually ts->vec_sol
5750: -  Y - state vector to be compared to U

5752:    Output Arguments:
5753: +  norm - weighted norm, a value of 1.0 means that the error matches the tolerances
5754: .  norma - weighted norm based on the absolute tolerance, a value of 1.0 means that the error matches the tolerances
5755: -  normr - weighted norm based on the relative tolerance, a value of 1.0 means that the error matches the tolerances

5757:    Level: developer

5759: .seealso: TSErrorWeightedNorm(), TSErrorWeightedNorm2()
5760: @*/
5761: PetscErrorCode TSErrorWeightedNormInfinity(TS ts,Vec U,Vec Y,PetscReal *norm,PetscReal *norma,PetscReal *normr)
5762: {
5763:   PetscErrorCode    ierr;
5764:   PetscInt          i,n,N,rstart;
5765:   const PetscScalar *u,*y;
5766:   PetscReal         max,gmax,maxa,gmaxa,maxr,gmaxr;
5767:   PetscReal         tol,tola,tolr,diff;
5768:   PetscReal         err_loc[3],err_glb[3];

5780:   if (U == Y) SETERRQ(PetscObjectComm((PetscObject)U),PETSC_ERR_ARG_IDN,"U and Y cannot be the same vector");

5782:   VecGetSize(U,&N);
5783:   VecGetLocalSize(U,&n);
5784:   VecGetOwnershipRange(U,&rstart,NULL);
5785:   VecGetArrayRead(U,&u);
5786:   VecGetArrayRead(Y,&y);

5788:   max=0.;
5789:   maxa=0.;
5790:   maxr=0.;

5792:   if (ts->vatol && ts->vrtol) {     /* vector atol, vector rtol */
5793:     const PetscScalar *atol,*rtol;
5794:     VecGetArrayRead(ts->vatol,&atol);
5795:     VecGetArrayRead(ts->vrtol,&rtol);

5797:     for (i=0; i<n; i++) {
5798:       SkipSmallValue(y[i],u[i],ts->adapt->ignore_max);
5799:       diff = PetscAbsScalar(y[i] - u[i]);
5800:       tola = PetscRealPart(atol[i]);
5801:       tolr = PetscRealPart(rtol[i]) * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
5802:       tol  = tola+tolr;
5803:       if(tola>0.){
5804:         maxa = PetscMax(maxa,diff / tola);
5805:       }
5806:       if(tolr>0.){
5807:         maxr = PetscMax(maxr,diff / tolr);
5808:       }
5809:       if(tol>0.){
5810:         max = PetscMax(max,diff / tol);
5811:       }
5812:     }
5813:     VecRestoreArrayRead(ts->vatol,&atol);
5814:     VecRestoreArrayRead(ts->vrtol,&rtol);
5815:   } else if (ts->vatol) {       /* vector atol, scalar rtol */
5816:     const PetscScalar *atol;
5817:     VecGetArrayRead(ts->vatol,&atol);
5818:     for (i=0; i<n; i++) {
5819:       SkipSmallValue(y[i],u[i],ts->adapt->ignore_max);
5820:       diff = PetscAbsScalar(y[i] - u[i]);
5821:       tola = PetscRealPart(atol[i]);
5822:       tolr = ts->rtol  * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
5823:       tol  = tola+tolr;
5824:       if(tola>0.){
5825:         maxa = PetscMax(maxa,diff / tola);
5826:       }
5827:       if(tolr>0.){
5828:         maxr = PetscMax(maxr,diff / tolr);
5829:       }
5830:       if(tol>0.){
5831:         max = PetscMax(max,diff / tol);
5832:       }
5833:     }
5834:     VecRestoreArrayRead(ts->vatol,&atol);
5835:   } else if (ts->vrtol) {       /* scalar atol, vector rtol */
5836:     const PetscScalar *rtol;
5837:     VecGetArrayRead(ts->vrtol,&rtol);

5839:     for (i=0; i<n; i++) {
5840:       SkipSmallValue(y[i],u[i],ts->adapt->ignore_max);
5841:       diff = PetscAbsScalar(y[i] - u[i]);
5842:       tola = ts->atol;
5843:       tolr = PetscRealPart(rtol[i]) * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
5844:       tol  = tola+tolr;
5845:       if(tola>0.){
5846:         maxa = PetscMax(maxa,diff / tola);
5847:       }
5848:       if(tolr>0.){
5849:         maxr = PetscMax(maxr,diff / tolr);
5850:       }
5851:       if(tol>0.){
5852:         max = PetscMax(max,diff / tol);
5853:       }
5854:     }
5855:     VecRestoreArrayRead(ts->vrtol,&rtol);
5856:   } else {                      /* scalar atol, scalar rtol */

5858:     for (i=0; i<n; i++) {
5859:       SkipSmallValue(y[i],u[i],ts->adapt->ignore_max);
5860:       diff = PetscAbsScalar(y[i] - u[i]);
5861:       tola = ts->atol;
5862:       tolr = ts->rtol * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
5863:       tol  = tola+tolr;
5864:       if(tola>0.){
5865:         maxa = PetscMax(maxa,diff / tola);
5866:       }
5867:       if(tolr>0.){
5868:         maxr = PetscMax(maxr,diff / tolr);
5869:       }
5870:       if(tol>0.){
5871:         max = PetscMax(max,diff / tol);
5872:       }
5873:     }
5874:   }
5875:   VecRestoreArrayRead(U,&u);
5876:   VecRestoreArrayRead(Y,&y);
5877:   err_loc[0] = max;
5878:   err_loc[1] = maxa;
5879:   err_loc[2] = maxr;
5880:   MPIU_Allreduce(err_loc,err_glb,3,MPIU_REAL,MPIU_MAX,PetscObjectComm((PetscObject)ts));
5881:   gmax   = err_glb[0];
5882:   gmaxa  = err_glb[1];
5883:   gmaxr  = err_glb[2];

5885:   *norm = gmax;
5886:   *norma = gmaxa;
5887:   *normr = gmaxr;
5888:   if (PetscIsInfOrNanScalar(*norm)) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_FP,"Infinite or not-a-number generated in norm");
5889:     if (PetscIsInfOrNanScalar(*norma)) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_FP,"Infinite or not-a-number generated in norma");
5890:     if (PetscIsInfOrNanScalar(*normr)) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_FP,"Infinite or not-a-number generated in normr");
5891:   return(0);
5892: }

5894: /*@
5895:    TSErrorWeightedNorm - compute a weighted norm of the difference between two state vectors based on supplied absolute and relative tolerances

5897:    Collective on TS

5899:    Input Arguments:
5900: +  ts - time stepping context
5901: .  U - state vector, usually ts->vec_sol
5902: .  Y - state vector to be compared to U
5903: -  wnormtype - norm type, either NORM_2 or NORM_INFINITY

5905:    Output Arguments:
5906: +  norm  - weighted norm, a value of 1.0 achieves a balance between absolute and relative tolerances
5907: .  norma - weighted norm, a value of 1.0 means that the error meets the absolute tolerance set by the user
5908: -  normr - weighted norm, a value of 1.0 means that the error meets the relative tolerance set by the user

5910:    Options Database Keys:
5911: .  -ts_adapt_wnormtype <wnormtype> - 2, INFINITY

5913:    Level: developer

5915: .seealso: TSErrorWeightedNormInfinity(), TSErrorWeightedNorm2(), TSErrorWeightedENorm
5916: @*/
5917: PetscErrorCode TSErrorWeightedNorm(TS ts,Vec U,Vec Y,NormType wnormtype,PetscReal *norm,PetscReal *norma,PetscReal *normr)
5918: {

5922:   if (wnormtype == NORM_2) {
5923:     TSErrorWeightedNorm2(ts,U,Y,norm,norma,normr);
5924:   } else if(wnormtype == NORM_INFINITY) {
5925:     TSErrorWeightedNormInfinity(ts,U,Y,norm,norma,normr);
5926:   } else SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"No support for norm type %s",NormTypes[wnormtype]);
5927:   return(0);
5928: }


5931: /*@
5932:    TSErrorWeightedENorm2 - compute a weighted 2 error norm based on supplied absolute and relative tolerances

5934:    Collective on TS

5936:    Input Arguments:
5937: +  ts - time stepping context
5938: .  E - error vector
5939: .  U - state vector, usually ts->vec_sol
5940: -  Y - state vector, previous time step

5942:    Output Arguments:
5943: +  norm - weighted norm, a value of 1.0 means that the error matches the tolerances
5944: .  norma - weighted norm based on the absolute tolerance, a value of 1.0 means that the error matches the tolerances
5945: -  normr - weighted norm based on the relative tolerance, a value of 1.0 means that the error matches the tolerances

5947:    Level: developer

5949: .seealso: TSErrorWeightedENorm(), TSErrorWeightedENormInfinity()
5950: @*/
5951: PetscErrorCode TSErrorWeightedENorm2(TS ts,Vec E,Vec U,Vec Y,PetscReal *norm,PetscReal *norma,PetscReal *normr)
5952: {
5953:   PetscErrorCode    ierr;
5954:   PetscInt          i,n,N,rstart;
5955:   PetscInt          n_loc,na_loc,nr_loc;
5956:   PetscReal         n_glb,na_glb,nr_glb;
5957:   const PetscScalar *e,*u,*y;
5958:   PetscReal         err,sum,suma,sumr,gsum,gsuma,gsumr;
5959:   PetscReal         tol,tola,tolr;
5960:   PetscReal         err_loc[6],err_glb[6];


5976:   VecGetSize(E,&N);
5977:   VecGetLocalSize(E,&n);
5978:   VecGetOwnershipRange(E,&rstart,NULL);
5979:   VecGetArrayRead(E,&e);
5980:   VecGetArrayRead(U,&u);
5981:   VecGetArrayRead(Y,&y);
5982:   sum  = 0.; n_loc  = 0;
5983:   suma = 0.; na_loc = 0;
5984:   sumr = 0.; nr_loc = 0;
5985:   if (ts->vatol && ts->vrtol) {
5986:     const PetscScalar *atol,*rtol;
5987:     VecGetArrayRead(ts->vatol,&atol);
5988:     VecGetArrayRead(ts->vrtol,&rtol);
5989:     for (i=0; i<n; i++) {
5990:       SkipSmallValue(y[i],u[i],ts->adapt->ignore_max);
5991:       err = PetscAbsScalar(e[i]);
5992:       tola = PetscRealPart(atol[i]);
5993:       if(tola>0.){
5994:         suma  += PetscSqr(err/tola);
5995:         na_loc++;
5996:       }
5997:       tolr = PetscRealPart(rtol[i]) * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
5998:       if(tolr>0.){
5999:         sumr  += PetscSqr(err/tolr);
6000:         nr_loc++;
6001:       }
6002:       tol=tola+tolr;
6003:       if(tol>0.){
6004:         sum  += PetscSqr(err/tol);
6005:         n_loc++;
6006:       }
6007:     }
6008:     VecRestoreArrayRead(ts->vatol,&atol);
6009:     VecRestoreArrayRead(ts->vrtol,&rtol);
6010:   } else if (ts->vatol) {       /* vector atol, scalar rtol */
6011:     const PetscScalar *atol;
6012:     VecGetArrayRead(ts->vatol,&atol);
6013:     for (i=0; i<n; i++) {
6014:       SkipSmallValue(y[i],u[i],ts->adapt->ignore_max);
6015:       err = PetscAbsScalar(e[i]);
6016:       tola = PetscRealPart(atol[i]);
6017:       if(tola>0.){
6018:         suma  += PetscSqr(err/tola);
6019:         na_loc++;
6020:       }
6021:       tolr = ts->rtol * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
6022:       if(tolr>0.){
6023:         sumr  += PetscSqr(err/tolr);
6024:         nr_loc++;
6025:       }
6026:       tol=tola+tolr;
6027:       if(tol>0.){
6028:         sum  += PetscSqr(err/tol);
6029:         n_loc++;
6030:       }
6031:     }
6032:     VecRestoreArrayRead(ts->vatol,&atol);
6033:   } else if (ts->vrtol) {       /* scalar atol, vector rtol */
6034:     const PetscScalar *rtol;
6035:     VecGetArrayRead(ts->vrtol,&rtol);
6036:     for (i=0; i<n; i++) {
6037:       SkipSmallValue(y[i],u[i],ts->adapt->ignore_max);
6038:       err = PetscAbsScalar(e[i]);
6039:       tola = ts->atol;
6040:       if(tola>0.){
6041:         suma  += PetscSqr(err/tola);
6042:         na_loc++;
6043:       }
6044:       tolr = PetscRealPart(rtol[i]) * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
6045:       if(tolr>0.){
6046:         sumr  += PetscSqr(err/tolr);
6047:         nr_loc++;
6048:       }
6049:       tol=tola+tolr;
6050:       if(tol>0.){
6051:         sum  += PetscSqr(err/tol);
6052:         n_loc++;
6053:       }
6054:     }
6055:     VecRestoreArrayRead(ts->vrtol,&rtol);
6056:   } else {                      /* scalar atol, scalar rtol */
6057:     for (i=0; i<n; i++) {
6058:       SkipSmallValue(y[i],u[i],ts->adapt->ignore_max);
6059:       err = PetscAbsScalar(e[i]);
6060:       tola = ts->atol;
6061:       if(tola>0.){
6062:         suma  += PetscSqr(err/tola);
6063:         na_loc++;
6064:       }
6065:       tolr = ts->rtol * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
6066:       if(tolr>0.){
6067:         sumr  += PetscSqr(err/tolr);
6068:         nr_loc++;
6069:       }
6070:       tol=tola+tolr;
6071:       if(tol>0.){
6072:         sum  += PetscSqr(err/tol);
6073:         n_loc++;
6074:       }
6075:     }
6076:   }
6077:   VecRestoreArrayRead(E,&e);
6078:   VecRestoreArrayRead(U,&u);
6079:   VecRestoreArrayRead(Y,&y);

6081:   err_loc[0] = sum;
6082:   err_loc[1] = suma;
6083:   err_loc[2] = sumr;
6084:   err_loc[3] = (PetscReal)n_loc;
6085:   err_loc[4] = (PetscReal)na_loc;
6086:   err_loc[5] = (PetscReal)nr_loc;

6088:   MPIU_Allreduce(err_loc,err_glb,6,MPIU_REAL,MPIU_SUM,PetscObjectComm((PetscObject)ts));

6090:   gsum   = err_glb[0];
6091:   gsuma  = err_glb[1];
6092:   gsumr  = err_glb[2];
6093:   n_glb  = err_glb[3];
6094:   na_glb = err_glb[4];
6095:   nr_glb = err_glb[5];

6097:   *norm  = 0.;
6098:   if(n_glb>0. ){*norm  = PetscSqrtReal(gsum  / n_glb );}
6099:   *norma = 0.;
6100:   if(na_glb>0.){*norma = PetscSqrtReal(gsuma / na_glb);}
6101:   *normr = 0.;
6102:   if(nr_glb>0.){*normr = PetscSqrtReal(gsumr / nr_glb);}

6104:   if (PetscIsInfOrNanScalar(*norm)) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_FP,"Infinite or not-a-number generated in norm");
6105:   if (PetscIsInfOrNanScalar(*norma)) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_FP,"Infinite or not-a-number generated in norma");
6106:   if (PetscIsInfOrNanScalar(*normr)) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_FP,"Infinite or not-a-number generated in normr");
6107:   return(0);
6108: }

6110: /*@
6111:    TSErrorWeightedENormInfinity - compute a weighted infinity error norm based on supplied absolute and relative tolerances
6112:    Collective on TS

6114:    Input Arguments:
6115: +  ts - time stepping context
6116: .  E - error vector
6117: .  U - state vector, usually ts->vec_sol
6118: -  Y - state vector, previous time step

6120:    Output Arguments:
6121: +  norm - weighted norm, a value of 1.0 means that the error matches the tolerances
6122: .  norma - weighted norm based on the absolute tolerance, a value of 1.0 means that the error matches the tolerances
6123: -  normr - weighted norm based on the relative tolerance, a value of 1.0 means that the error matches the tolerances

6125:    Level: developer

6127: .seealso: TSErrorWeightedENorm(), TSErrorWeightedENorm2()
6128: @*/
6129: PetscErrorCode TSErrorWeightedENormInfinity(TS ts,Vec E,Vec U,Vec Y,PetscReal *norm,PetscReal *norma,PetscReal *normr)
6130: {
6131:   PetscErrorCode    ierr;
6132:   PetscInt          i,n,N,rstart;
6133:   const PetscScalar *e,*u,*y;
6134:   PetscReal         err,max,gmax,maxa,gmaxa,maxr,gmaxr;
6135:   PetscReal         tol,tola,tolr;
6136:   PetscReal         err_loc[3],err_glb[3];


6152:   VecGetSize(E,&N);
6153:   VecGetLocalSize(E,&n);
6154:   VecGetOwnershipRange(E,&rstart,NULL);
6155:   VecGetArrayRead(E,&e);
6156:   VecGetArrayRead(U,&u);
6157:   VecGetArrayRead(Y,&y);

6159:   max=0.;
6160:   maxa=0.;
6161:   maxr=0.;

6163:   if (ts->vatol && ts->vrtol) {     /* vector atol, vector rtol */
6164:     const PetscScalar *atol,*rtol;
6165:     VecGetArrayRead(ts->vatol,&atol);
6166:     VecGetArrayRead(ts->vrtol,&rtol);

6168:     for (i=0; i<n; i++) {
6169:       SkipSmallValue(y[i],u[i],ts->adapt->ignore_max);
6170:       err = PetscAbsScalar(e[i]);
6171:       tola = PetscRealPart(atol[i]);
6172:       tolr = PetscRealPart(rtol[i]) * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
6173:       tol  = tola+tolr;
6174:       if(tola>0.){
6175:         maxa = PetscMax(maxa,err / tola);
6176:       }
6177:       if(tolr>0.){
6178:         maxr = PetscMax(maxr,err / tolr);
6179:       }
6180:       if(tol>0.){
6181:         max = PetscMax(max,err / tol);
6182:       }
6183:     }
6184:     VecRestoreArrayRead(ts->vatol,&atol);
6185:     VecRestoreArrayRead(ts->vrtol,&rtol);
6186:   } else if (ts->vatol) {       /* vector atol, scalar rtol */
6187:     const PetscScalar *atol;
6188:     VecGetArrayRead(ts->vatol,&atol);
6189:     for (i=0; i<n; i++) {
6190:       SkipSmallValue(y[i],u[i],ts->adapt->ignore_max);
6191:       err = PetscAbsScalar(e[i]);
6192:       tola = PetscRealPart(atol[i]);
6193:       tolr = ts->rtol  * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
6194:       tol  = tola+tolr;
6195:       if(tola>0.){
6196:         maxa = PetscMax(maxa,err / tola);
6197:       }
6198:       if(tolr>0.){
6199:         maxr = PetscMax(maxr,err / tolr);
6200:       }
6201:       if(tol>0.){
6202:         max = PetscMax(max,err / tol);
6203:       }
6204:     }
6205:     VecRestoreArrayRead(ts->vatol,&atol);
6206:   } else if (ts->vrtol) {       /* scalar atol, vector rtol */
6207:     const PetscScalar *rtol;
6208:     VecGetArrayRead(ts->vrtol,&rtol);

6210:     for (i=0; i<n; i++) {
6211:       SkipSmallValue(y[i],u[i],ts->adapt->ignore_max);
6212:       err = PetscAbsScalar(e[i]);
6213:       tola = ts->atol;
6214:       tolr = PetscRealPart(rtol[i]) * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
6215:       tol  = tola+tolr;
6216:       if(tola>0.){
6217:         maxa = PetscMax(maxa,err / tola);
6218:       }
6219:       if(tolr>0.){
6220:         maxr = PetscMax(maxr,err / tolr);
6221:       }
6222:       if(tol>0.){
6223:         max = PetscMax(max,err / tol);
6224:       }
6225:     }
6226:     VecRestoreArrayRead(ts->vrtol,&rtol);
6227:   } else {                      /* scalar atol, scalar rtol */

6229:     for (i=0; i<n; i++) {
6230:       SkipSmallValue(y[i],u[i],ts->adapt->ignore_max);
6231:       err = PetscAbsScalar(e[i]);
6232:       tola = ts->atol;
6233:       tolr = ts->rtol * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
6234:       tol  = tola+tolr;
6235:       if(tola>0.){
6236:         maxa = PetscMax(maxa,err / tola);
6237:       }
6238:       if(tolr>0.){
6239:         maxr = PetscMax(maxr,err / tolr);
6240:       }
6241:       if(tol>0.){
6242:         max = PetscMax(max,err / tol);
6243:       }
6244:     }
6245:   }
6246:   VecRestoreArrayRead(E,&e);
6247:   VecRestoreArrayRead(U,&u);
6248:   VecRestoreArrayRead(Y,&y);
6249:   err_loc[0] = max;
6250:   err_loc[1] = maxa;
6251:   err_loc[2] = maxr;
6252:   MPIU_Allreduce(err_loc,err_glb,3,MPIU_REAL,MPIU_MAX,PetscObjectComm((PetscObject)ts));
6253:   gmax   = err_glb[0];
6254:   gmaxa  = err_glb[1];
6255:   gmaxr  = err_glb[2];

6257:   *norm = gmax;
6258:   *norma = gmaxa;
6259:   *normr = gmaxr;
6260:   if (PetscIsInfOrNanScalar(*norm)) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_FP,"Infinite or not-a-number generated in norm");
6261:     if (PetscIsInfOrNanScalar(*norma)) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_FP,"Infinite or not-a-number generated in norma");
6262:     if (PetscIsInfOrNanScalar(*normr)) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_FP,"Infinite or not-a-number generated in normr");
6263:   return(0);
6264: }

6266: /*@
6267:    TSErrorWeightedENorm - compute a weighted error norm based on supplied absolute and relative tolerances

6269:    Collective on TS

6271:    Input Arguments:
6272: +  ts - time stepping context
6273: .  E - error vector
6274: .  U - state vector, usually ts->vec_sol
6275: .  Y - state vector, previous time step
6276: -  wnormtype - norm type, either NORM_2 or NORM_INFINITY

6278:    Output Arguments:
6279: +  norm  - weighted norm, a value of 1.0 achieves a balance between absolute and relative tolerances
6280: .  norma - weighted norm, a value of 1.0 means that the error meets the absolute tolerance set by the user
6281: -  normr - weighted norm, a value of 1.0 means that the error meets the relative tolerance set by the user

6283:    Options Database Keys:
6284: .  -ts_adapt_wnormtype <wnormtype> - 2, INFINITY

6286:    Level: developer

6288: .seealso: TSErrorWeightedENormInfinity(), TSErrorWeightedENorm2(), TSErrorWeightedNormInfinity(), TSErrorWeightedNorm2()
6289: @*/
6290: PetscErrorCode TSErrorWeightedENorm(TS ts,Vec E,Vec U,Vec Y,NormType wnormtype,PetscReal *norm,PetscReal *norma,PetscReal *normr)
6291: {

6295:   if (wnormtype == NORM_2) {
6296:     TSErrorWeightedENorm2(ts,E,U,Y,norm,norma,normr);
6297:   } else if(wnormtype == NORM_INFINITY) {
6298:     TSErrorWeightedENormInfinity(ts,E,U,Y,norm,norma,normr);
6299:   } else SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"No support for norm type %s",NormTypes[wnormtype]);
6300:   return(0);
6301: }


6304: /*@
6305:    TSSetCFLTimeLocal - Set the local CFL constraint relative to forward Euler

6307:    Logically Collective on TS

6309:    Input Arguments:
6310: +  ts - time stepping context
6311: -  cfltime - maximum stable time step if using forward Euler (value can be different on each process)

6313:    Note:
6314:    After calling this function, the global CFL time can be obtained by calling TSGetCFLTime()

6316:    Level: intermediate

6318: .seealso: TSGetCFLTime(), TSADAPTCFL
6319: @*/
6320: PetscErrorCode TSSetCFLTimeLocal(TS ts,PetscReal cfltime)
6321: {
6324:   ts->cfltime_local = cfltime;
6325:   ts->cfltime       = -1.;
6326:   return(0);
6327: }

6329: /*@
6330:    TSGetCFLTime - Get the maximum stable time step according to CFL criteria applied to forward Euler

6332:    Collective on TS

6334:    Input Arguments:
6335: .  ts - time stepping context

6337:    Output Arguments:
6338: .  cfltime - maximum stable time step for forward Euler

6340:    Level: advanced

6342: .seealso: TSSetCFLTimeLocal()
6343: @*/
6344: PetscErrorCode TSGetCFLTime(TS ts,PetscReal *cfltime)
6345: {

6349:   if (ts->cfltime < 0) {
6350:     MPIU_Allreduce(&ts->cfltime_local,&ts->cfltime,1,MPIU_REAL,MPIU_MIN,PetscObjectComm((PetscObject)ts));
6351:   }
6352:   *cfltime = ts->cfltime;
6353:   return(0);
6354: }

6356: /*@
6357:    TSVISetVariableBounds - Sets the lower and upper bounds for the solution vector. xl <= x <= xu

6359:    Input Parameters:
6360: +  ts   - the TS context.
6361: .  xl   - lower bound.
6362: -  xu   - upper bound.

6364:    Notes:
6365:    If this routine is not called then the lower and upper bounds are set to
6366:    PETSC_NINFINITY and PETSC_INFINITY respectively during SNESSetUp().

6368:    Level: advanced

6370: @*/
6371: PetscErrorCode TSVISetVariableBounds(TS ts, Vec xl, Vec xu)
6372: {
6374:   SNES           snes;

6377:   TSGetSNES(ts,&snes);
6378:   SNESVISetVariableBounds(snes,xl,xu);
6379:   return(0);
6380: }

6382: /*@C
6383:    TSMonitorLGSolution - Monitors progress of the TS solvers by plotting each component of the solution vector
6384:        in a time based line graph

6386:    Collective on TS

6388:    Input Parameters:
6389: +  ts - the TS context
6390: .  step - current time-step
6391: .  ptime - current time
6392: .  u - current solution
6393: -  dctx - the TSMonitorLGCtx object that contains all the options for the monitoring, this is created with TSMonitorLGCtxCreate()

6395:    Options Database:
6396: .   -ts_monitor_lg_solution_variables

6398:    Level: intermediate

6400:    Notes:
6401:     Each process in a parallel run displays its component solutions in a separate window

6403: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorLGCtxCreate(), TSMonitorLGCtxSetVariableNames(), TSMonitorLGCtxGetVariableNames(),
6404:            TSMonitorLGSetVariableNames(), TSMonitorLGGetVariableNames(), TSMonitorLGSetDisplayVariables(), TSMonitorLGCtxSetDisplayVariables(),
6405:            TSMonitorLGCtxSetTransform(), TSMonitorLGSetTransform(), TSMonitorLGError(), TSMonitorLGSNESIterations(), TSMonitorLGKSPIterations(),
6406:            TSMonitorEnvelopeCtxCreate(), TSMonitorEnvelopeGetBounds(), TSMonitorEnvelopeCtxDestroy(), TSMonitorEnvelop()
6407: @*/
6408: PetscErrorCode  TSMonitorLGSolution(TS ts,PetscInt step,PetscReal ptime,Vec u,void *dctx)
6409: {
6410:   PetscErrorCode    ierr;
6411:   TSMonitorLGCtx    ctx = (TSMonitorLGCtx)dctx;
6412:   const PetscScalar *yy;
6413:   Vec               v;

6416:   if (step < 0) return(0); /* -1 indicates interpolated solution */
6417:   if (!step) {
6418:     PetscDrawAxis axis;
6419:     PetscInt      dim;
6420:     PetscDrawLGGetAxis(ctx->lg,&axis);
6421:     PetscDrawAxisSetLabels(axis,"Solution as function of time","Time","Solution");
6422:     if (!ctx->names) {
6423:       PetscBool flg;
6424:       /* user provides names of variables to plot but no names has been set so assume names are integer values */
6425:       PetscOptionsHasName(((PetscObject)ts)->options,((PetscObject)ts)->prefix,"-ts_monitor_lg_solution_variables",&flg);
6426:       if (flg) {
6427:         PetscInt i,n;
6428:         char     **names;
6429:         VecGetSize(u,&n);
6430:         PetscMalloc1(n+1,&names);
6431:         for (i=0; i<n; i++) {
6432:           PetscMalloc1(5,&names[i]);
6433:           PetscSNPrintf(names[i],5,"%D",i);
6434:         }
6435:         names[n] = NULL;
6436:         ctx->names = names;
6437:       }
6438:     }
6439:     if (ctx->names && !ctx->displaynames) {
6440:       char      **displaynames;
6441:       PetscBool flg;
6442:       VecGetLocalSize(u,&dim);
6443:       PetscCalloc1(dim+1,&displaynames);
6444:       PetscOptionsGetStringArray(((PetscObject)ts)->options,((PetscObject)ts)->prefix,"-ts_monitor_lg_solution_variables",displaynames,&dim,&flg);
6445:       if (flg) {
6446:         TSMonitorLGCtxSetDisplayVariables(ctx,(const char *const *)displaynames);
6447:       }
6448:       PetscStrArrayDestroy(&displaynames);
6449:     }
6450:     if (ctx->displaynames) {
6451:       PetscDrawLGSetDimension(ctx->lg,ctx->ndisplayvariables);
6452:       PetscDrawLGSetLegend(ctx->lg,(const char *const *)ctx->displaynames);
6453:     } else if (ctx->names) {
6454:       VecGetLocalSize(u,&dim);
6455:       PetscDrawLGSetDimension(ctx->lg,dim);
6456:       PetscDrawLGSetLegend(ctx->lg,(const char *const *)ctx->names);
6457:     } else {
6458:       VecGetLocalSize(u,&dim);
6459:       PetscDrawLGSetDimension(ctx->lg,dim);
6460:     }
6461:     PetscDrawLGReset(ctx->lg);
6462:   }

6464:   if (!ctx->transform) v = u;
6465:   else {(*ctx->transform)(ctx->transformctx,u,&v);}
6466:   VecGetArrayRead(v,&yy);
6467:   if (ctx->displaynames) {
6468:     PetscInt i;
6469:     for (i=0; i<ctx->ndisplayvariables; i++)
6470:       ctx->displayvalues[i] = PetscRealPart(yy[ctx->displayvariables[i]]);
6471:     PetscDrawLGAddCommonPoint(ctx->lg,ptime,ctx->displayvalues);
6472:   } else {
6473: #if defined(PETSC_USE_COMPLEX)
6474:     PetscInt  i,n;
6475:     PetscReal *yreal;
6476:     VecGetLocalSize(v,&n);
6477:     PetscMalloc1(n,&yreal);
6478:     for (i=0; i<n; i++) yreal[i] = PetscRealPart(yy[i]);
6479:     PetscDrawLGAddCommonPoint(ctx->lg,ptime,yreal);
6480:     PetscFree(yreal);
6481: #else
6482:     PetscDrawLGAddCommonPoint(ctx->lg,ptime,yy);
6483: #endif
6484:   }
6485:   VecRestoreArrayRead(v,&yy);
6486:   if (ctx->transform) {VecDestroy(&v);}

6488:   if (((ctx->howoften > 0) && (!(step % ctx->howoften))) || ((ctx->howoften == -1) && ts->reason)) {
6489:     PetscDrawLGDraw(ctx->lg);
6490:     PetscDrawLGSave(ctx->lg);
6491:   }
6492:   return(0);
6493: }

6495: /*@C
6496:    TSMonitorLGSetVariableNames - Sets the name of each component in the solution vector so that it may be displayed in the plot

6498:    Collective on TS

6500:    Input Parameters:
6501: +  ts - the TS context
6502: -  names - the names of the components, final string must be NULL

6504:    Level: intermediate

6506:    Notes:
6507:     If the TS object does not have a TSMonitorLGCtx associated with it then this function is ignored

6509: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorLGSetDisplayVariables(), TSMonitorLGCtxSetVariableNames()
6510: @*/
6511: PetscErrorCode  TSMonitorLGSetVariableNames(TS ts,const char * const *names)
6512: {
6513:   PetscErrorCode    ierr;
6514:   PetscInt          i;

6517:   for (i=0; i<ts->numbermonitors; i++) {
6518:     if (ts->monitor[i] == TSMonitorLGSolution) {
6519:       TSMonitorLGCtxSetVariableNames((TSMonitorLGCtx)ts->monitorcontext[i],names);
6520:       break;
6521:     }
6522:   }
6523:   return(0);
6524: }

6526: /*@C
6527:    TSMonitorLGCtxSetVariableNames - Sets the name of each component in the solution vector so that it may be displayed in the plot

6529:    Collective on TS

6531:    Input Parameters:
6532: +  ts - the TS context
6533: -  names - the names of the components, final string must be NULL

6535:    Level: intermediate

6537: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorLGSetDisplayVariables(), TSMonitorLGSetVariableNames()
6538: @*/
6539: PetscErrorCode  TSMonitorLGCtxSetVariableNames(TSMonitorLGCtx ctx,const char * const *names)
6540: {
6541:   PetscErrorCode    ierr;

6544:   PetscStrArrayDestroy(&ctx->names);
6545:   PetscStrArrayallocpy(names,&ctx->names);
6546:   return(0);
6547: }

6549: /*@C
6550:    TSMonitorLGGetVariableNames - Gets the name of each component in the solution vector so that it may be displayed in the plot

6552:    Collective on TS

6554:    Input Parameter:
6555: .  ts - the TS context

6557:    Output Parameter:
6558: .  names - the names of the components, final string must be NULL

6560:    Level: intermediate

6562:    Notes:
6563:     If the TS object does not have a TSMonitorLGCtx associated with it then this function is ignored

6565: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorLGSetDisplayVariables()
6566: @*/
6567: PetscErrorCode  TSMonitorLGGetVariableNames(TS ts,const char *const **names)
6568: {
6569:   PetscInt       i;

6572:   *names = NULL;
6573:   for (i=0; i<ts->numbermonitors; i++) {
6574:     if (ts->monitor[i] == TSMonitorLGSolution) {
6575:       TSMonitorLGCtx  ctx = (TSMonitorLGCtx) ts->monitorcontext[i];
6576:       *names = (const char *const *)ctx->names;
6577:       break;
6578:     }
6579:   }
6580:   return(0);
6581: }

6583: /*@C
6584:    TSMonitorLGCtxSetDisplayVariables - Sets the variables that are to be display in the monitor

6586:    Collective on TS

6588:    Input Parameters:
6589: +  ctx - the TSMonitorLG context
6590: -  displaynames - the names of the components, final string must be NULL

6592:    Level: intermediate

6594: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorLGSetVariableNames()
6595: @*/
6596: PetscErrorCode  TSMonitorLGCtxSetDisplayVariables(TSMonitorLGCtx ctx,const char * const *displaynames)
6597: {
6598:   PetscInt          j = 0,k;
6599:   PetscErrorCode    ierr;

6602:   if (!ctx->names) return(0);
6603:   PetscStrArrayDestroy(&ctx->displaynames);
6604:   PetscStrArrayallocpy(displaynames,&ctx->displaynames);
6605:   while (displaynames[j]) j++;
6606:   ctx->ndisplayvariables = j;
6607:   PetscMalloc1(ctx->ndisplayvariables,&ctx->displayvariables);
6608:   PetscMalloc1(ctx->ndisplayvariables,&ctx->displayvalues);
6609:   j = 0;
6610:   while (displaynames[j]) {
6611:     k = 0;
6612:     while (ctx->names[k]) {
6613:       PetscBool flg;
6614:       PetscStrcmp(displaynames[j],ctx->names[k],&flg);
6615:       if (flg) {
6616:         ctx->displayvariables[j] = k;
6617:         break;
6618:       }
6619:       k++;
6620:     }
6621:     j++;
6622:   }
6623:   return(0);
6624: }

6626: /*@C
6627:    TSMonitorLGSetDisplayVariables - Sets the variables that are to be display in the monitor

6629:    Collective on TS

6631:    Input Parameters:
6632: +  ts - the TS context
6633: -  displaynames - the names of the components, final string must be NULL

6635:    Notes:
6636:     If the TS object does not have a TSMonitorLGCtx associated with it then this function is ignored

6638:    Level: intermediate

6640: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorLGSetVariableNames()
6641: @*/
6642: PetscErrorCode  TSMonitorLGSetDisplayVariables(TS ts,const char * const *displaynames)
6643: {
6644:   PetscInt          i;
6645:   PetscErrorCode    ierr;

6648:   for (i=0; i<ts->numbermonitors; i++) {
6649:     if (ts->monitor[i] == TSMonitorLGSolution) {
6650:       TSMonitorLGCtxSetDisplayVariables((TSMonitorLGCtx)ts->monitorcontext[i],displaynames);
6651:       break;
6652:     }
6653:   }
6654:   return(0);
6655: }

6657: /*@C
6658:    TSMonitorLGSetTransform - Solution vector will be transformed by provided function before being displayed

6660:    Collective on TS

6662:    Input Parameters:
6663: +  ts - the TS context
6664: .  transform - the transform function
6665: .  destroy - function to destroy the optional context
6666: -  ctx - optional context used by transform function

6668:    Notes:
6669:     If the TS object does not have a TSMonitorLGCtx associated with it then this function is ignored

6671:    Level: intermediate

6673: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorLGSetVariableNames(), TSMonitorLGCtxSetTransform()
6674: @*/
6675: PetscErrorCode  TSMonitorLGSetTransform(TS ts,PetscErrorCode (*transform)(void*,Vec,Vec*),PetscErrorCode (*destroy)(void*),void *tctx)
6676: {
6677:   PetscInt          i;
6678:   PetscErrorCode    ierr;

6681:   for (i=0; i<ts->numbermonitors; i++) {
6682:     if (ts->monitor[i] == TSMonitorLGSolution) {
6683:       TSMonitorLGCtxSetTransform((TSMonitorLGCtx)ts->monitorcontext[i],transform,destroy,tctx);
6684:     }
6685:   }
6686:   return(0);
6687: }

6689: /*@C
6690:    TSMonitorLGCtxSetTransform - Solution vector will be transformed by provided function before being displayed

6692:    Collective on TSLGCtx

6694:    Input Parameters:
6695: +  ts - the TS context
6696: .  transform - the transform function
6697: .  destroy - function to destroy the optional context
6698: -  ctx - optional context used by transform function

6700:    Level: intermediate

6702: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorLGSetVariableNames(), TSMonitorLGSetTransform()
6703: @*/
6704: PetscErrorCode  TSMonitorLGCtxSetTransform(TSMonitorLGCtx ctx,PetscErrorCode (*transform)(void*,Vec,Vec*),PetscErrorCode (*destroy)(void*),void *tctx)
6705: {
6707:   ctx->transform    = transform;
6708:   ctx->transformdestroy = destroy;
6709:   ctx->transformctx = tctx;
6710:   return(0);
6711: }

6713: /*@C
6714:    TSMonitorLGError - Monitors progress of the TS solvers by plotting each component of the error
6715:        in a time based line graph

6717:    Collective on TS

6719:    Input Parameters:
6720: +  ts - the TS context
6721: .  step - current time-step
6722: .  ptime - current time
6723: .  u - current solution
6724: -  dctx - TSMonitorLGCtx object created with TSMonitorLGCtxCreate()

6726:    Level: intermediate

6728:    Notes:
6729:     Each process in a parallel run displays its component errors in a separate window

6731:    The user must provide the solution using TSSetSolutionFunction() to use this monitor.

6733:    Options Database Keys:
6734: .  -ts_monitor_lg_error - create a graphical monitor of error history

6736: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSSetSolutionFunction()
6737: @*/
6738: PetscErrorCode  TSMonitorLGError(TS ts,PetscInt step,PetscReal ptime,Vec u,void *dummy)
6739: {
6740:   PetscErrorCode    ierr;
6741:   TSMonitorLGCtx    ctx = (TSMonitorLGCtx)dummy;
6742:   const PetscScalar *yy;
6743:   Vec               y;

6746:   if (!step) {
6747:     PetscDrawAxis axis;
6748:     PetscInt      dim;
6749:     PetscDrawLGGetAxis(ctx->lg,&axis);
6750:     PetscDrawAxisSetLabels(axis,"Error in solution as function of time","Time","Error");
6751:     VecGetLocalSize(u,&dim);
6752:     PetscDrawLGSetDimension(ctx->lg,dim);
6753:     PetscDrawLGReset(ctx->lg);
6754:   }
6755:   VecDuplicate(u,&y);
6756:   TSComputeSolutionFunction(ts,ptime,y);
6757:   VecAXPY(y,-1.0,u);
6758:   VecGetArrayRead(y,&yy);
6759: #if defined(PETSC_USE_COMPLEX)
6760:   {
6761:     PetscReal *yreal;
6762:     PetscInt  i,n;
6763:     VecGetLocalSize(y,&n);
6764:     PetscMalloc1(n,&yreal);
6765:     for (i=0; i<n; i++) yreal[i] = PetscRealPart(yy[i]);
6766:     PetscDrawLGAddCommonPoint(ctx->lg,ptime,yreal);
6767:     PetscFree(yreal);
6768:   }
6769: #else
6770:   PetscDrawLGAddCommonPoint(ctx->lg,ptime,yy);
6771: #endif
6772:   VecRestoreArrayRead(y,&yy);
6773:   VecDestroy(&y);
6774:   if (((ctx->howoften > 0) && (!(step % ctx->howoften))) || ((ctx->howoften == -1) && ts->reason)) {
6775:     PetscDrawLGDraw(ctx->lg);
6776:     PetscDrawLGSave(ctx->lg);
6777:   }
6778:   return(0);
6779: }

6781: /*@C
6782:    TSMonitorSPSwarmSolution - Graphically displays phase plots of DMSwarm particles on a scatter plot

6784:    Input Parameters:
6785: +  ts - the TS context
6786: .  step - current time-step
6787: .  ptime - current time
6788: .  u - current solution
6789: -  dctx - the TSMonitorSPCtx object that contains all the options for the monitoring, this is created with TSMonitorSPCtxCreate()

6791:    Options Database:
6792: .   -ts_monitor_sp_swarm

6794:    Level: intermediate

6796: @*/
6797: PetscErrorCode TSMonitorSPSwarmSolution(TS ts,PetscInt step,PetscReal ptime,Vec u,void *dctx)
6798: {
6799:   PetscErrorCode    ierr;
6800:   TSMonitorSPCtx    ctx = (TSMonitorSPCtx)dctx;
6801:   const PetscScalar *yy;
6802:   PetscReal       *y,*x;
6803:   PetscInt          Np, p, dim=2;
6804:   DM                dm;


6808:   if (step < 0) return(0); /* -1 indicates interpolated solution */
6809:   if (!step) {
6810:     PetscDrawAxis axis;
6811:     PetscDrawSPGetAxis(ctx->sp,&axis);
6812:     PetscDrawAxisSetLabels(axis,"Particles","X","Y");
6813:     PetscDrawAxisSetLimits(axis, -5, 5, -5, 5);
6814:     PetscDrawAxisSetHoldLimits(axis, PETSC_TRUE);
6815:     TSGetDM(ts, &dm);
6816:     DMGetDimension(dm, &dim);
6817:     if(dim!=2) SETERRQ(PETSC_COMM_SELF, ierr, "Dimensions improper for monitor arguments! Current support: two dimensions.");
6818:     VecGetLocalSize(u, &Np);
6819:     Np /= 2*dim;
6820:     PetscDrawSPSetDimension(ctx->sp, Np);
6821:     PetscDrawSPReset(ctx->sp);
6822:   }

6824:   VecGetLocalSize(u, &Np);
6825:   Np /= 2*dim;
6826:   VecGetArrayRead(u,&yy);
6827:   PetscMalloc2(Np, &x, Np, &y);
6828:   /* get points from solution vector */
6829:   for (p=0; p<Np; ++p){
6830:     x[p] = PetscRealPart(yy[2*dim*p]);
6831:     y[p] = PetscRealPart(yy[2*dim*p+1]);
6832:   }
6833:   VecRestoreArrayRead(u,&yy);

6835:   if (((ctx->howoften > 0) && (!(step % ctx->howoften))) || ((ctx->howoften == -1) && ts->reason)) {
6836:     PetscDrawSPAddPoint(ctx->sp,x,y);
6837:     PetscDrawSPDraw(ctx->sp,PETSC_FALSE);
6838:     PetscDrawSPSave(ctx->sp);
6839:   }

6841:   PetscFree2(x, y);

6843:   return(0);
6844: }



6848: /*@C
6849:    TSMonitorError - Monitors progress of the TS solvers by printing the 2 norm of the error at each timestep

6851:    Collective on TS

6853:    Input Parameters:
6854: +  ts - the TS context
6855: .  step - current time-step
6856: .  ptime - current time
6857: .  u - current solution
6858: -  dctx - unused context

6860:    Level: intermediate

6862:    The user must provide the solution using TSSetSolutionFunction() to use this monitor.

6864:    Options Database Keys:
6865: .  -ts_monitor_error - create a graphical monitor of error history

6867: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSSetSolutionFunction()
6868: @*/
6869: PetscErrorCode  TSMonitorError(TS ts,PetscInt step,PetscReal ptime,Vec u,PetscViewerAndFormat *vf)
6870: {
6871:   PetscErrorCode    ierr;
6872:   Vec               y;
6873:   PetscReal         nrm;
6874:   PetscBool         flg;

6877:   VecDuplicate(u,&y);
6878:   TSComputeSolutionFunction(ts,ptime,y);
6879:   VecAXPY(y,-1.0,u);
6880:   PetscObjectTypeCompare((PetscObject)vf->viewer,PETSCVIEWERASCII,&flg);
6881:   if (flg) {
6882:     VecNorm(y,NORM_2,&nrm);
6883:     PetscViewerASCIIPrintf(vf->viewer,"2-norm of error %g\n",(double)nrm);
6884:   }
6885:   PetscObjectTypeCompare((PetscObject)vf->viewer,PETSCVIEWERDRAW,&flg);
6886:   if (flg) {
6887:     VecView(y,vf->viewer);
6888:   }
6889:   VecDestroy(&y);
6890:   return(0);
6891: }

6893: PetscErrorCode TSMonitorLGSNESIterations(TS ts,PetscInt n,PetscReal ptime,Vec v,void *monctx)
6894: {
6895:   TSMonitorLGCtx ctx = (TSMonitorLGCtx) monctx;
6896:   PetscReal      x   = ptime,y;
6898:   PetscInt       its;

6901:   if (n < 0) return(0); /* -1 indicates interpolated solution */
6902:   if (!n) {
6903:     PetscDrawAxis axis;
6904:     PetscDrawLGGetAxis(ctx->lg,&axis);
6905:     PetscDrawAxisSetLabels(axis,"Nonlinear iterations as function of time","Time","SNES Iterations");
6906:     PetscDrawLGReset(ctx->lg);
6907:     ctx->snes_its = 0;
6908:   }
6909:   TSGetSNESIterations(ts,&its);
6910:   y    = its - ctx->snes_its;
6911:   PetscDrawLGAddPoint(ctx->lg,&x,&y);
6912:   if (((ctx->howoften > 0) && (!(n % ctx->howoften)) && (n > -1)) || ((ctx->howoften == -1) && (n == -1))) {
6913:     PetscDrawLGDraw(ctx->lg);
6914:     PetscDrawLGSave(ctx->lg);
6915:   }
6916:   ctx->snes_its = its;
6917:   return(0);
6918: }

6920: PetscErrorCode TSMonitorLGKSPIterations(TS ts,PetscInt n,PetscReal ptime,Vec v,void *monctx)
6921: {
6922:   TSMonitorLGCtx ctx = (TSMonitorLGCtx) monctx;
6923:   PetscReal      x   = ptime,y;
6925:   PetscInt       its;

6928:   if (n < 0) return(0); /* -1 indicates interpolated solution */
6929:   if (!n) {
6930:     PetscDrawAxis axis;
6931:     PetscDrawLGGetAxis(ctx->lg,&axis);
6932:     PetscDrawAxisSetLabels(axis,"Linear iterations as function of time","Time","KSP Iterations");
6933:     PetscDrawLGReset(ctx->lg);
6934:     ctx->ksp_its = 0;
6935:   }
6936:   TSGetKSPIterations(ts,&its);
6937:   y    = its - ctx->ksp_its;
6938:   PetscDrawLGAddPoint(ctx->lg,&x,&y);
6939:   if (((ctx->howoften > 0) && (!(n % ctx->howoften)) && (n > -1)) || ((ctx->howoften == -1) && (n == -1))) {
6940:     PetscDrawLGDraw(ctx->lg);
6941:     PetscDrawLGSave(ctx->lg);
6942:   }
6943:   ctx->ksp_its = its;
6944:   return(0);
6945: }

6947: /*@
6948:    TSComputeLinearStability - computes the linear stability function at a point

6950:    Collective on TS

6952:    Input Parameters:
6953: +  ts - the TS context
6954: -  xr,xi - real and imaginary part of input arguments

6956:    Output Parameters:
6957: .  yr,yi - real and imaginary part of function value

6959:    Level: developer

6961: .seealso: TSSetRHSFunction(), TSComputeIFunction()
6962: @*/
6963: PetscErrorCode TSComputeLinearStability(TS ts,PetscReal xr,PetscReal xi,PetscReal *yr,PetscReal *yi)
6964: {

6969:   if (!ts->ops->linearstability) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"Linearized stability function not provided for this method");
6970:   (*ts->ops->linearstability)(ts,xr,xi,yr,yi);
6971:   return(0);
6972: }

6974: /* ------------------------------------------------------------------------*/
6975: /*@C
6976:    TSMonitorEnvelopeCtxCreate - Creates a context for use with TSMonitorEnvelope()

6978:    Collective on TS

6980:    Input Parameters:
6981: .  ts  - the ODE solver object

6983:    Output Parameter:
6984: .  ctx - the context

6986:    Level: intermediate

6988: .seealso: TSMonitorLGTimeStep(), TSMonitorSet(), TSMonitorLGSolution(), TSMonitorLGError()

6990: @*/
6991: PetscErrorCode  TSMonitorEnvelopeCtxCreate(TS ts,TSMonitorEnvelopeCtx *ctx)
6992: {

6996:   PetscNew(ctx);
6997:   return(0);
6998: }

7000: /*@C
7001:    TSMonitorEnvelope - Monitors the maximum and minimum value of each component of the solution

7003:    Collective on TS

7005:    Input Parameters:
7006: +  ts - the TS context
7007: .  step - current time-step
7008: .  ptime - current time
7009: .  u  - current solution
7010: -  dctx - the envelope context

7012:    Options Database:
7013: .  -ts_monitor_envelope

7015:    Level: intermediate

7017:    Notes:
7018:     after a solve you can use TSMonitorEnvelopeGetBounds() to access the envelope

7020: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorEnvelopeGetBounds(), TSMonitorEnvelopeCtxCreate()
7021: @*/
7022: PetscErrorCode  TSMonitorEnvelope(TS ts,PetscInt step,PetscReal ptime,Vec u,void *dctx)
7023: {
7024:   PetscErrorCode       ierr;
7025:   TSMonitorEnvelopeCtx ctx = (TSMonitorEnvelopeCtx)dctx;

7028:   if (!ctx->max) {
7029:     VecDuplicate(u,&ctx->max);
7030:     VecDuplicate(u,&ctx->min);
7031:     VecCopy(u,ctx->max);
7032:     VecCopy(u,ctx->min);
7033:   } else {
7034:     VecPointwiseMax(ctx->max,u,ctx->max);
7035:     VecPointwiseMin(ctx->min,u,ctx->min);
7036:   }
7037:   return(0);
7038: }

7040: /*@C
7041:    TSMonitorEnvelopeGetBounds - Gets the bounds for the components of the solution

7043:    Collective on TS

7045:    Input Parameter:
7046: .  ts - the TS context

7048:    Output Parameter:
7049: +  max - the maximum values
7050: -  min - the minimum values

7052:    Notes:
7053:     If the TS does not have a TSMonitorEnvelopeCtx associated with it then this function is ignored

7055:    Level: intermediate

7057: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorLGSetDisplayVariables()
7058: @*/
7059: PetscErrorCode  TSMonitorEnvelopeGetBounds(TS ts,Vec *max,Vec *min)
7060: {
7061:   PetscInt i;

7064:   if (max) *max = NULL;
7065:   if (min) *min = NULL;
7066:   for (i=0; i<ts->numbermonitors; i++) {
7067:     if (ts->monitor[i] == TSMonitorEnvelope) {
7068:       TSMonitorEnvelopeCtx  ctx = (TSMonitorEnvelopeCtx) ts->monitorcontext[i];
7069:       if (max) *max = ctx->max;
7070:       if (min) *min = ctx->min;
7071:       break;
7072:     }
7073:   }
7074:   return(0);
7075: }

7077: /*@C
7078:    TSMonitorEnvelopeCtxDestroy - Destroys a context that was created  with TSMonitorEnvelopeCtxCreate().

7080:    Collective on TSMonitorEnvelopeCtx

7082:    Input Parameter:
7083: .  ctx - the monitor context

7085:    Level: intermediate

7087: .seealso: TSMonitorLGCtxCreate(),  TSMonitorSet(), TSMonitorLGTimeStep()
7088: @*/
7089: PetscErrorCode  TSMonitorEnvelopeCtxDestroy(TSMonitorEnvelopeCtx *ctx)
7090: {

7094:   VecDestroy(&(*ctx)->min);
7095:   VecDestroy(&(*ctx)->max);
7096:   PetscFree(*ctx);
7097:   return(0);
7098: }

7100: /*@
7101:    TSRestartStep - Flags the solver to restart the next step

7103:    Collective on TS

7105:    Input Parameter:
7106: .  ts - the TS context obtained from TSCreate()

7108:    Level: advanced

7110:    Notes:
7111:    Multistep methods like BDF or Runge-Kutta methods with FSAL property require restarting the solver in the event of
7112:    discontinuities. These discontinuities may be introduced as a consequence of explicitly modifications to the solution
7113:    vector (which PETSc attempts to detect and handle) or problem coefficients (which PETSc is not able to detect). For
7114:    the sake of correctness and maximum safety, users are expected to call TSRestart() whenever they introduce
7115:    discontinuities in callback routines (e.g. prestep and poststep routines, or implicit/rhs function routines with
7116:    discontinuous source terms).

7118: .seealso: TSSolve(), TSSetPreStep(), TSSetPostStep()
7119: @*/
7120: PetscErrorCode TSRestartStep(TS ts)
7121: {
7124:   ts->steprestart = PETSC_TRUE;
7125:   return(0);
7126: }

7128: /*@
7129:    TSRollBack - Rolls back one time step

7131:    Collective on TS

7133:    Input Parameter:
7134: .  ts - the TS context obtained from TSCreate()

7136:    Level: advanced

7138: .seealso: TSCreate(), TSSetUp(), TSDestroy(), TSSolve(), TSSetPreStep(), TSSetPreStage(), TSInterpolate()
7139: @*/
7140: PetscErrorCode  TSRollBack(TS ts)
7141: {

7146:   if (ts->steprollback) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_ARG_WRONGSTATE,"TSRollBack already called");
7147:   if (!ts->ops->rollback) SETERRQ1(PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"TSRollBack not implemented for type '%s'",((PetscObject)ts)->type_name);
7148:   (*ts->ops->rollback)(ts);
7149:   ts->time_step = ts->ptime - ts->ptime_prev;
7150:   ts->ptime = ts->ptime_prev;
7151:   ts->ptime_prev = ts->ptime_prev_rollback;
7152:   ts->steps--;
7153:   ts->steprollback = PETSC_TRUE;
7154:   return(0);
7155: }

7157: /*@
7158:    TSGetStages - Get the number of stages and stage values

7160:    Input Parameter:
7161: .  ts - the TS context obtained from TSCreate()

7163:    Output Parameters:
7164: +  ns - the number of stages
7165: -  Y - the current stage vectors

7167:    Level: advanced

7169:    Notes: Both ns and Y can be NULL.

7171: .seealso: TSCreate()
7172: @*/
7173: PetscErrorCode  TSGetStages(TS ts,PetscInt *ns,Vec **Y)
7174: {

7181:   if (!ts->ops->getstages) {
7182:     if (ns) *ns = 0;
7183:     if (Y) *Y = NULL;
7184:   } else {
7185:     (*ts->ops->getstages)(ts,ns,Y);
7186:   }
7187:   return(0);
7188: }

7190: /*@C
7191:   TSComputeIJacobianDefaultColor - Computes the Jacobian using finite differences and coloring to exploit matrix sparsity.

7193:   Collective on SNES

7195:   Input Parameters:
7196: + ts - the TS context
7197: . t - current timestep
7198: . U - state vector
7199: . Udot - time derivative of state vector
7200: . shift - shift to apply, see note below
7201: - ctx - an optional user context

7203:   Output Parameters:
7204: + J - Jacobian matrix (not altered in this routine)
7205: - B - newly computed Jacobian matrix to use with preconditioner (generally the same as J)

7207:   Level: intermediate

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

7212:   dF/dU + shift*dF/dUdot

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

7217:   This will first try to get the coloring from the DM.  If the DM type has no coloring
7218:   routine, then it will try to get the coloring from the matrix.  This requires that the
7219:   matrix have nonzero entries precomputed.

7221: .seealso: TSSetIJacobian(), MatFDColoringCreate(), MatFDColoringSetFunction()
7222: @*/
7223: PetscErrorCode TSComputeIJacobianDefaultColor(TS ts,PetscReal t,Vec U,Vec Udot,PetscReal shift,Mat J,Mat B,void *ctx)
7224: {
7225:   SNES           snes;
7226:   MatFDColoring  color;
7227:   PetscBool      hascolor, matcolor = PETSC_FALSE;

7231:   PetscOptionsGetBool(((PetscObject)ts)->options,((PetscObject) ts)->prefix, "-ts_fd_color_use_mat", &matcolor, NULL);
7232:   PetscObjectQuery((PetscObject) B, "TSMatFDColoring", (PetscObject *) &color);
7233:   if (!color) {
7234:     DM         dm;
7235:     ISColoring iscoloring;

7237:     TSGetDM(ts, &dm);
7238:     DMHasColoring(dm, &hascolor);
7239:     if (hascolor && !matcolor) {
7240:       DMCreateColoring(dm, IS_COLORING_GLOBAL, &iscoloring);
7241:       MatFDColoringCreate(B, iscoloring, &color);
7242:       MatFDColoringSetFunction(color, (PetscErrorCode (*)(void)) SNESTSFormFunction, (void *) ts);
7243:       MatFDColoringSetFromOptions(color);
7244:       MatFDColoringSetUp(B, iscoloring, color);
7245:       ISColoringDestroy(&iscoloring);
7246:     } else {
7247:       MatColoring mc;

7249:       MatColoringCreate(B, &mc);
7250:       MatColoringSetDistance(mc, 2);
7251:       MatColoringSetType(mc, MATCOLORINGSL);
7252:       MatColoringSetFromOptions(mc);
7253:       MatColoringApply(mc, &iscoloring);
7254:       MatColoringDestroy(&mc);
7255:       MatFDColoringCreate(B, iscoloring, &color);
7256:       MatFDColoringSetFunction(color, (PetscErrorCode (*)(void)) SNESTSFormFunction, (void *) ts);
7257:       MatFDColoringSetFromOptions(color);
7258:       MatFDColoringSetUp(B, iscoloring, color);
7259:       ISColoringDestroy(&iscoloring);
7260:     }
7261:     PetscObjectCompose((PetscObject) B, "TSMatFDColoring", (PetscObject) color);
7262:     PetscObjectDereference((PetscObject) color);
7263:   }
7264:   TSGetSNES(ts, &snes);
7265:   MatFDColoringApply(B, color, U, snes);
7266:   if (J != B) {
7267:     MatAssemblyBegin(J, MAT_FINAL_ASSEMBLY);
7268:     MatAssemblyEnd(J, MAT_FINAL_ASSEMBLY);
7269:   }
7270:   return(0);
7271: }

7273: /*@
7274:     TSSetFunctionDomainError - Set a function that tests if the current state vector is valid

7276:     Input Parameters:
7277: +    ts - the TS context
7278: -    func - function called within TSFunctionDomainError

7280:     Calling sequence of func:
7281: $     PetscErrorCode func(TS ts,PetscReal time,Vec state,PetscBool reject)

7283: +   ts - the TS context
7284: .   time - the current time (of the stage)
7285: .   state - the state to check if it is valid
7286: -   reject - (output parameter) PETSC_FALSE if the state is acceptable, PETSC_TRUE if not acceptable

7288:     Level: intermediate

7290:     Notes:
7291:       If an implicit ODE solver is being used then, in addition to providing this routine, the
7292:       user's code should call SNESSetFunctionDomainError() when domain errors occur during
7293:       function evaluations where the functions are provided by TSSetIFunction() or TSSetRHSFunction().
7294:       Use TSGetSNES() to obtain the SNES object

7296:     Developer Notes:
7297:       The naming of this function is inconsistent with the SNESSetFunctionDomainError()
7298:       since one takes a function pointer and the other does not.

7300: .seealso: TSAdaptCheckStage(), TSFunctionDomainError(), SNESSetFunctionDomainError(), TSGetSNES()
7301: @*/

7303: PetscErrorCode TSSetFunctionDomainError(TS ts, PetscErrorCode (*func)(TS,PetscReal,Vec,PetscBool*))
7304: {
7307:   ts->functiondomainerror = func;
7308:   return(0);
7309: }

7311: /*@
7312:     TSFunctionDomainError - Checks if the current state is valid

7314:     Input Parameters:
7315: +    ts - the TS context
7316: .    stagetime - time of the simulation
7317: -    Y - state vector to check.

7319:     Output Parameter:
7320: .    accept - Set to PETSC_FALSE if the current state vector is valid.

7322:     Note:
7323:     This function is called by the TS integration routines and calls the user provided function (set with TSSetFunctionDomainError())
7324:     to check if the current state is valid.

7326:     Level: developer

7328: .seealso: TSSetFunctionDomainError()
7329: @*/
7330: PetscErrorCode TSFunctionDomainError(TS ts,PetscReal stagetime,Vec Y,PetscBool* accept)
7331: {
7334:   *accept = PETSC_TRUE;
7335:   if (ts->functiondomainerror) {
7336:     PetscStackCallStandard((*ts->functiondomainerror),(ts,stagetime,Y,accept));
7337:   }
7338:   return(0);
7339: }

7341: /*@C
7342:   TSClone - This function clones a time step object.

7344:   Collective

7346:   Input Parameter:
7347: . tsin    - The input TS

7349:   Output Parameter:
7350: . tsout   - The output TS (cloned)

7352:   Notes:
7353:   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.

7355:   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);

7357:   Level: developer

7359: .seealso: TSCreate(), TSSetType(), TSSetUp(), TSDestroy(), TSSetProblemType()
7360: @*/
7361: PetscErrorCode  TSClone(TS tsin, TS *tsout)
7362: {
7363:   TS             t;
7365:   SNES           snes_start;
7366:   DM             dm;
7367:   TSType         type;

7371:   *tsout = NULL;

7373:   PetscHeaderCreate(t, TS_CLASSID, "TS", "Time stepping", "TS", PetscObjectComm((PetscObject)tsin), TSDestroy, TSView);

7375:   /* General TS description */
7376:   t->numbermonitors    = 0;
7377:   t->setupcalled       = 0;
7378:   t->ksp_its           = 0;
7379:   t->snes_its          = 0;
7380:   t->nwork             = 0;
7381:   t->rhsjacobian.time  = -1e20;
7382:   t->rhsjacobian.scale = 1.;
7383:   t->ijacobian.shift   = 1.;

7385:   TSGetSNES(tsin,&snes_start);
7386:   TSSetSNES(t,snes_start);

7388:   TSGetDM(tsin,&dm);
7389:   TSSetDM(t,dm);

7391:   t->adapt = tsin->adapt;
7392:   PetscObjectReference((PetscObject)t->adapt);

7394:   t->trajectory = tsin->trajectory;
7395:   PetscObjectReference((PetscObject)t->trajectory);

7397:   t->event = tsin->event;
7398:   if (t->event) t->event->refct++;

7400:   t->problem_type      = tsin->problem_type;
7401:   t->ptime             = tsin->ptime;
7402:   t->ptime_prev        = tsin->ptime_prev;
7403:   t->time_step         = tsin->time_step;
7404:   t->max_time          = tsin->max_time;
7405:   t->steps             = tsin->steps;
7406:   t->max_steps         = tsin->max_steps;
7407:   t->equation_type     = tsin->equation_type;
7408:   t->atol              = tsin->atol;
7409:   t->rtol              = tsin->rtol;
7410:   t->max_snes_failures = tsin->max_snes_failures;
7411:   t->max_reject        = tsin->max_reject;
7412:   t->errorifstepfailed = tsin->errorifstepfailed;

7414:   TSGetType(tsin,&type);
7415:   TSSetType(t,type);

7417:   t->vec_sol           = NULL;

7419:   t->cfltime          = tsin->cfltime;
7420:   t->cfltime_local    = tsin->cfltime_local;
7421:   t->exact_final_time = tsin->exact_final_time;

7423:   PetscMemcpy(t->ops,tsin->ops,sizeof(struct _TSOps));

7425:   if (((PetscObject)tsin)->fortran_func_pointers) {
7426:     PetscInt i;
7427:     PetscMalloc((10)*sizeof(void(*)(void)),&((PetscObject)t)->fortran_func_pointers);
7428:     for (i=0; i<10; i++) {
7429:       ((PetscObject)t)->fortran_func_pointers[i] = ((PetscObject)tsin)->fortran_func_pointers[i];
7430:     }
7431:   }
7432:   *tsout = t;
7433:   return(0);
7434: }

7436: static PetscErrorCode RHSWrapperFunction_TSRHSJacobianTest(void* ctx,Vec x,Vec y)
7437: {
7439:   TS             ts = (TS) ctx;

7442:   TSComputeRHSFunction(ts,0,x,y);
7443:   return(0);
7444: }

7446: /*@
7447:     TSRHSJacobianTest - Compares the multiply routine provided to the MATSHELL with differencing on the TS given RHS function.

7449:    Logically Collective on TS

7451:     Input Parameters:
7452:     TS - the time stepping routine

7454:    Output Parameter:
7455: .   flg - PETSC_TRUE if the multiply is likely correct

7457:    Options Database:
7458:  .   -ts_rhs_jacobian_test_mult -mat_shell_test_mult_view - run the test at each timestep of the integrator

7460:    Level: advanced

7462:    Notes:
7463:     This only works for problems defined only the RHS function and Jacobian NOT IFunction and IJacobian

7465: .seealso: MatCreateShell(), MatShellGetContext(), MatShellGetOperation(), MatShellTestMultTranspose(), TSRHSJacobianTestTranspose()
7466: @*/
7467: PetscErrorCode  TSRHSJacobianTest(TS ts,PetscBool *flg)
7468: {
7469:   Mat            J,B;
7471:   TSRHSJacobian  func;
7472:   void*          ctx;

7475:   TSGetRHSJacobian(ts,&J,&B,&func,&ctx);
7476:   (*func)(ts,0.0,ts->vec_sol,J,B,ctx);
7477:   MatShellTestMult(J,RHSWrapperFunction_TSRHSJacobianTest,ts->vec_sol,ts,flg);
7478:   return(0);
7479: }

7481: /*@C
7482:     TSRHSJacobianTestTranspose - Compares the multiply transpose routine provided to the MATSHELL with differencing on the TS given RHS function.

7484:    Logically Collective on TS

7486:     Input Parameters:
7487:     TS - the time stepping routine

7489:    Output Parameter:
7490: .   flg - PETSC_TRUE if the multiply is likely correct

7492:    Options Database:
7493: .   -ts_rhs_jacobian_test_mult_transpose -mat_shell_test_mult_transpose_view - run the test at each timestep of the integrator

7495:    Notes:
7496:     This only works for problems defined only the RHS function and Jacobian NOT IFunction and IJacobian

7498:    Level: advanced

7500: .seealso: MatCreateShell(), MatShellGetContext(), MatShellGetOperation(), MatShellTestMultTranspose(), TSRHSJacobianTest()
7501: @*/
7502: PetscErrorCode  TSRHSJacobianTestTranspose(TS ts,PetscBool *flg)
7503: {
7504:   Mat            J,B;
7506:   void           *ctx;
7507:   TSRHSJacobian  func;

7510:   TSGetRHSJacobian(ts,&J,&B,&func,&ctx);
7511:   (*func)(ts,0.0,ts->vec_sol,J,B,ctx);
7512:   MatShellTestMultTranspose(J,RHSWrapperFunction_TSRHSJacobianTest,ts->vec_sol,ts,flg);
7513:   return(0);
7514: }

7516: /*@
7517:   TSSetUseSplitRHSFunction - Use the split RHSFunction when a multirate method is used.

7519:   Logically collective

7521:   Input Parameter:
7522: +  ts - timestepping context
7523: -  use_splitrhsfunction - PETSC_TRUE indicates that the split RHSFunction will be used

7525:   Options Database:
7526: .   -ts_use_splitrhsfunction - <true,false>

7528:   Notes:
7529:     This is only useful for multirate methods

7531:   Level: intermediate

7533: .seealso: TSGetUseSplitRHSFunction()
7534: @*/
7535: PetscErrorCode TSSetUseSplitRHSFunction(TS ts, PetscBool use_splitrhsfunction)
7536: {
7539:   ts->use_splitrhsfunction = use_splitrhsfunction;
7540:   return(0);
7541: }

7543: /*@
7544:   TSGetUseSplitRHSFunction - Gets whether to use the split RHSFunction when a multirate method is used.

7546:   Not collective

7548:   Input Parameter:
7549: .  ts - timestepping context

7551:   Output Parameter:
7552: .  use_splitrhsfunction - PETSC_TRUE indicates that the split RHSFunction will be used

7554:   Level: intermediate

7556: .seealso: TSSetUseSplitRHSFunction()
7557: @*/
7558: PetscErrorCode TSGetUseSplitRHSFunction(TS ts, PetscBool *use_splitrhsfunction)
7559: {
7562:   *use_splitrhsfunction = ts->use_splitrhsfunction;
7563:   return(0);
7564: }