Actual source code: ts.c

petsc-3.14.6 2021-03-30
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_",NULL};


 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 time
 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:    Notes:
117:      See SNESSetFromOptions() and KSPSetFromOptions() for how to control the nonlinear and linear solves used by the time-stepper.

119:      Certain SNES options get reset for each new nonlinear solver, for example -snes_lag_jacobian <its> and -snes_lag_preconditioner <its>, in order
120:      to retain them over the multiple nonlinear solves that TS uses you mush also provide -snes_lag_jacobian_persists true and
121:      -snes_lag_preconditioner_persists true

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

126:    Level: beginner

128: .seealso: TSGetType()
129: @*/
130: PetscErrorCode  TSSetFromOptions(TS ts)
131: {
132:   PetscBool              opt,flg,tflg;
133:   PetscErrorCode         ierr;
134:   char                   monfilename[PETSC_MAX_PATH_LEN];
135:   PetscReal              time_step;
136:   TSExactFinalTimeOption eftopt;
137:   char                   dir[16];
138:   TSIFunction            ifun;
139:   const char             *defaultType;
140:   char                   typeName[256];


145:   TSRegisterAll();
146:   TSGetIFunction(ts,NULL,&ifun,NULL);

148:   PetscObjectOptionsBegin((PetscObject)ts);
149:   if (((PetscObject)ts)->type_name) defaultType = ((PetscObject)ts)->type_name;
150:   else defaultType = ifun ? TSBEULER : TSEULER;
151:   PetscOptionsFList("-ts_type","TS method","TSSetType",TSList,defaultType,typeName,256,&opt);
152:   if (opt) {
153:     TSSetType(ts,typeName);
154:   } else {
155:     TSSetType(ts,defaultType);
156:   }

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

173:   PetscOptionsBool("-ts_rhs_jacobian_test_mult","Test the RHS Jacobian for consistency with RHS at each solve ","None",ts->testjacobian,&ts->testjacobian,NULL);
174:   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);
175:   PetscOptionsBool("-ts_use_splitrhsfunction","Use the split RHS function for multirate solvers ","TSSetUseSplitRHSFunction",ts->use_splitrhsfunction,&ts->use_splitrhsfunction,NULL);
176: #if defined(PETSC_HAVE_SAWS)
177:   {
178:     PetscBool set;
179:     flg  = PETSC_FALSE;
180:     PetscOptionsBool("-ts_saws_block","Block for SAWs memory snooper at end of TSSolve","PetscObjectSAWsBlock",((PetscObject)ts)->amspublishblock,&flg,&set);
181:     if (set) {
182:       PetscObjectSAWsSetBlock((PetscObject)ts,flg);
183:     }
184:   }
185: #endif

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

192:   PetscOptionsString("-ts_monitor_python","Use Python function","TSMonitorSet",NULL,monfilename,sizeof(monfilename),&flg);
193:   if (flg) {PetscPythonMonitorSet((PetscObject)ts,monfilename);}

195:   PetscOptionsName("-ts_monitor_lg_solution","Monitor solution graphically","TSMonitorLGSolution",&opt);
196:   if (opt) {
197:     PetscInt       howoften = 1;
198:     DM             dm;
199:     PetscBool      net;

201:     PetscOptionsInt("-ts_monitor_lg_solution","Monitor solution graphically","TSMonitorLGSolution",howoften,&howoften,NULL);
202:     TSGetDM(ts,&dm);
203:     PetscObjectTypeCompare((PetscObject)dm,DMNETWORK,&net);
204:     if (net) {
205:       TSMonitorLGCtxNetwork ctx;
206:       TSMonitorLGCtxNetworkCreate(ts,NULL,NULL,PETSC_DECIDE,PETSC_DECIDE,600,400,howoften,&ctx);
207:       TSMonitorSet(ts,TSMonitorLGCtxNetworkSolution,ctx,(PetscErrorCode (*)(void**))TSMonitorLGCtxNetworkDestroy);
208:       PetscOptionsBool("-ts_monitor_lg_solution_semilogy","Plot the solution with a semi-log axis","",ctx->semilogy,&ctx->semilogy,NULL);
209:     } else {
210:       TSMonitorLGCtx ctx;
211:       TSMonitorLGCtxCreate(PETSC_COMM_SELF,NULL,NULL,PETSC_DECIDE,PETSC_DECIDE,400,300,howoften,&ctx);
212:       TSMonitorSet(ts,TSMonitorLGSolution,ctx,(PetscErrorCode (*)(void**))TSMonitorLGCtxDestroy);
213:     }
214:   }

216:   PetscOptionsName("-ts_monitor_lg_error","Monitor error graphically","TSMonitorLGError",&opt);
217:   if (opt) {
218:     TSMonitorLGCtx ctx;
219:     PetscInt       howoften = 1;

221:     PetscOptionsInt("-ts_monitor_lg_error","Monitor error graphically","TSMonitorLGError",howoften,&howoften,NULL);
222:     TSMonitorLGCtxCreate(PETSC_COMM_SELF,NULL,NULL,PETSC_DECIDE,PETSC_DECIDE,400,300,howoften,&ctx);
223:     TSMonitorSet(ts,TSMonitorLGError,ctx,(PetscErrorCode (*)(void**))TSMonitorLGCtxDestroy);
224:   }
225:   TSMonitorSetFromOptions(ts,"-ts_monitor_error","View the error at each timestep","TSMonitorError",TSMonitorError,NULL);

227:   PetscOptionsName("-ts_monitor_lg_timestep","Monitor timestep size graphically","TSMonitorLGTimeStep",&opt);
228:   if (opt) {
229:     TSMonitorLGCtx ctx;
230:     PetscInt       howoften = 1;

232:     PetscOptionsInt("-ts_monitor_lg_timestep","Monitor timestep size graphically","TSMonitorLGTimeStep",howoften,&howoften,NULL);
233:     TSMonitorLGCtxCreate(PetscObjectComm((PetscObject)ts),NULL,NULL,PETSC_DECIDE,PETSC_DECIDE,400,300,howoften,&ctx);
234:     TSMonitorSet(ts,TSMonitorLGTimeStep,ctx,(PetscErrorCode (*)(void**))TSMonitorLGCtxDestroy);
235:   }
236:   PetscOptionsName("-ts_monitor_lg_timestep_log","Monitor log timestep size graphically","TSMonitorLGTimeStep",&opt);
237:   if (opt) {
238:     TSMonitorLGCtx ctx;
239:     PetscInt       howoften = 1;

241:     PetscOptionsInt("-ts_monitor_lg_timestep_log","Monitor log timestep size graphically","TSMonitorLGTimeStep",howoften,&howoften,NULL);
242:     TSMonitorLGCtxCreate(PetscObjectComm((PetscObject)ts),NULL,NULL,PETSC_DECIDE,PETSC_DECIDE,400,300,howoften,&ctx);
243:     TSMonitorSet(ts,TSMonitorLGTimeStep,ctx,(PetscErrorCode (*)(void**))TSMonitorLGCtxDestroy);
244:     ctx->semilogy = PETSC_TRUE;
245:   }

247:   PetscOptionsName("-ts_monitor_lg_snes_iterations","Monitor number nonlinear iterations for each timestep graphically","TSMonitorLGSNESIterations",&opt);
248:   if (opt) {
249:     TSMonitorLGCtx ctx;
250:     PetscInt       howoften = 1;

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

261:     PetscOptionsInt("-ts_monitor_lg_ksp_iterations","Monitor number nonlinear iterations for each timestep graphically","TSMonitorLGKSPIterations",howoften,&howoften,NULL);
262:     TSMonitorLGCtxCreate(PetscObjectComm((PetscObject)ts),NULL,NULL,PETSC_DECIDE,PETSC_DECIDE,400,300,howoften,&ctx);
263:     TSMonitorSet(ts,TSMonitorLGKSPIterations,ctx,(PetscErrorCode (*)(void**))TSMonitorLGCtxDestroy);
264:   }
265:   PetscOptionsName("-ts_monitor_sp_eig","Monitor eigenvalues of linearized operator graphically","TSMonitorSPEig",&opt);
266:   if (opt) {
267:     TSMonitorSPEigCtx ctx;
268:     PetscInt          howoften = 1;

270:     PetscOptionsInt("-ts_monitor_sp_eig","Monitor eigenvalues of linearized operator graphically","TSMonitorSPEig",howoften,&howoften,NULL);
271:     TSMonitorSPEigCtxCreate(PETSC_COMM_SELF,NULL,NULL,PETSC_DECIDE,PETSC_DECIDE,300,300,howoften,&ctx);
272:     TSMonitorSet(ts,TSMonitorSPEig,ctx,(PetscErrorCode (*)(void**))TSMonitorSPEigCtxDestroy);
273:   }
274:   PetscOptionsName("-ts_monitor_sp_swarm","Display particle phase from the DMSwarm","TSMonitorSPSwarm",&opt);
275:   if (opt) {
276:     TSMonitorSPCtx  ctx;
277:     PetscInt        howoften = 1;
278:     PetscOptionsInt("-ts_monitor_sp_swarm","Display particles phase from the DMSwarm","TSMonitorSPSwarm",howoften,&howoften,NULL);
279:     TSMonitorSPCtxCreate(PETSC_COMM_SELF, NULL, NULL, PETSC_DECIDE, PETSC_DECIDE, 300, 300, howoften, &ctx);
280:     TSMonitorSet(ts, TSMonitorSPSwarmSolution, ctx, (PetscErrorCode (*)(void**))TSMonitorSPCtxDestroy);
281:   }
282:   opt  = PETSC_FALSE;
283:   PetscOptionsName("-ts_monitor_draw_solution","Monitor solution graphically","TSMonitorDrawSolution",&opt);
284:   if (opt) {
285:     TSMonitorDrawCtx ctx;
286:     PetscInt         howoften = 1;

288:     PetscOptionsInt("-ts_monitor_draw_solution","Monitor solution graphically","TSMonitorDrawSolution",howoften,&howoften,NULL);
289:     TSMonitorDrawCtxCreate(PetscObjectComm((PetscObject)ts),NULL,"Computed Solution",PETSC_DECIDE,PETSC_DECIDE,300,300,howoften,&ctx);
290:     TSMonitorSet(ts,TSMonitorDrawSolution,ctx,(PetscErrorCode (*)(void**))TSMonitorDrawCtxDestroy);
291:   }
292:   opt  = PETSC_FALSE;
293:   PetscOptionsName("-ts_monitor_draw_solution_phase","Monitor solution graphically","TSMonitorDrawSolutionPhase",&opt);
294:   if (opt) {
295:     TSMonitorDrawCtx ctx;
296:     PetscReal        bounds[4];
297:     PetscInt         n = 4;
298:     PetscDraw        draw;
299:     PetscDrawAxis    axis;

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

316:     PetscOptionsInt("-ts_monitor_draw_error","Monitor error graphically","TSMonitorDrawError",howoften,&howoften,NULL);
317:     TSMonitorDrawCtxCreate(PetscObjectComm((PetscObject)ts),NULL,"Error",PETSC_DECIDE,PETSC_DECIDE,300,300,howoften,&ctx);
318:     TSMonitorSet(ts,TSMonitorDrawError,ctx,(PetscErrorCode (*)(void**))TSMonitorDrawCtxDestroy);
319:   }
320:   opt  = PETSC_FALSE;
321:   PetscOptionsName("-ts_monitor_draw_solution_function","Monitor solution provided by TSMonitorSetSolutionFunction() graphically","TSMonitorDrawSolutionFunction",&opt);
322:   if (opt) {
323:     TSMonitorDrawCtx ctx;
324:     PetscInt         howoften = 1;

326:     PetscOptionsInt("-ts_monitor_draw_solution_function","Monitor solution provided by TSMonitorSetSolutionFunction() graphically","TSMonitorDrawSolutionFunction",howoften,&howoften,NULL);
327:     TSMonitorDrawCtxCreate(PetscObjectComm((PetscObject)ts),NULL,"Solution provided by user function",PETSC_DECIDE,PETSC_DECIDE,300,300,howoften,&ctx);
328:     TSMonitorSet(ts,TSMonitorDrawSolutionFunction,ctx,(PetscErrorCode (*)(void**))TSMonitorDrawCtxDestroy);
329:   }

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

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

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

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

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

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

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

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

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

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

417:   /* Handle specific TS options */
418:   if (ts->ops->setfromoptions) {
419:     (*ts->ops->setfromoptions)(PetscOptionsObject,ts);
420:   }

422:   /* Handle TSAdapt options */
423:   TSGetAdapt(ts,&ts->adapt);
424:   TSAdaptSetDefaultType(ts->adapt,ts->default_adapt_type);
425:   TSAdaptSetFromOptions(PetscOptionsObject,ts->adapt);

427:   /* TS trajectory must be set after TS, since it may use some TS options above */
428:   tflg = ts->trajectory ? PETSC_TRUE : PETSC_FALSE;
429:   PetscOptionsBool("-ts_save_trajectory","Save the solution at each timestep","TSSetSaveTrajectory",tflg,&tflg,NULL);
430:   if (tflg) {
431:     TSSetSaveTrajectory(ts);
432:   }

434:   TSAdjointSetFromOptions(PetscOptionsObject,ts);

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

440:   if (ts->trajectory) {
441:     TSTrajectorySetFromOptions(ts->trajectory,ts);
442:   }

444:   /* why do we have to do this here and not during TSSetUp? */
445:   TSGetSNES(ts,&ts->snes);
446:   if (ts->problem_type == TS_LINEAR) {
447:     PetscObjectTypeCompareAny((PetscObject)ts->snes,&flg,SNESKSPONLY,SNESKSPTRANSPOSEONLY,"");
448:     if (!flg) { SNESSetType(ts->snes,SNESKSPONLY); }
449:   }
450:   SNESSetFromOptions(ts->snes);
451:   return(0);
452: }

454: /*@
455:    TSGetTrajectory - Gets the trajectory from a TS if it exists

457:    Collective on TS

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

462:    Output Parameters:
463: .  tr - the TSTrajectory object, if it exists

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

467:    Level: advanced

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

471: @*/
472: PetscErrorCode  TSGetTrajectory(TS ts,TSTrajectory *tr)
473: {
476:   *tr = ts->trajectory;
477:   return(0);
478: }

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

483:    Collective on TS

485:    Input Parameters:
486: .  ts - the TS context obtained from TSCreate()

488:    Options Database:
489: +  -ts_save_trajectory - saves the trajectory to a file
490: -  -ts_trajectory_type type

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

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

497:    Level: intermediate

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

501: @*/
502: PetscErrorCode  TSSetSaveTrajectory(TS ts)
503: {

508:   if (!ts->trajectory) {
509:     TSTrajectoryCreate(PetscObjectComm((PetscObject)ts),&ts->trajectory);
510:   }
511:   return(0);
512: }

514: /*@
515:    TSResetTrajectory - Destroys and recreates the internal TSTrajectory object

517:    Collective on TS

519:    Input Parameters:
520: .  ts - the TS context obtained from TSCreate()

522:    Level: intermediate

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

526: @*/
527: PetscErrorCode  TSResetTrajectory(TS ts)
528: {

533:   if (ts->trajectory) {
534:     TSTrajectoryDestroy(&ts->trajectory);
535:     TSTrajectoryCreate(PetscObjectComm((PetscObject)ts),&ts->trajectory);
536:   }
537:   return(0);
538: }

540: /*@
541:    TSComputeRHSJacobian - Computes the Jacobian matrix that has been
542:       set with TSSetRHSJacobian().

544:    Collective on TS

546:    Input Parameters:
547: +  ts - the TS context
548: .  t - current timestep
549: -  U - input vector

551:    Output Parameters:
552: +  A - Jacobian matrix
553: .  B - optional preconditioning matrix
554: -  flag - flag indicating matrix structure

556:    Notes:
557:    Most users should not need to explicitly call this routine, as it
558:    is used internally within the nonlinear solvers.

560:    See KSPSetOperators() for important information about setting the
561:    flag parameter.

563:    Level: developer

565: .seealso:  TSSetRHSJacobian(), KSPSetOperators()
566: @*/
567: PetscErrorCode  TSComputeRHSJacobian(TS ts,PetscReal t,Vec U,Mat A,Mat B)
568: {
569:   PetscErrorCode   ierr;
570:   PetscObjectState Ustate;
571:   PetscObjectId    Uid;
572:   DM               dm;
573:   DMTS             tsdm;
574:   TSRHSJacobian    rhsjacobianfunc;
575:   void             *ctx;
576:   TSRHSFunction    rhsfunction;

582:   TSGetDM(ts,&dm);
583:   DMGetDMTS(dm,&tsdm);
584:   DMTSGetRHSFunction(dm,&rhsfunction,NULL);
585:   DMTSGetRHSJacobian(dm,&rhsjacobianfunc,&ctx);
586:   PetscObjectStateGet((PetscObject)U,&Ustate);
587:   PetscObjectGetId((PetscObject)U,&Uid);

589:   if (ts->rhsjacobian.time == t && (ts->problem_type == TS_LINEAR || (ts->rhsjacobian.Xid == Uid && ts->rhsjacobian.Xstate == Ustate)) && (rhsfunction != TSComputeRHSFunctionLinear)) return(0);

591:   if (ts->rhsjacobian.shift && ts->rhsjacobian.reuse) SETERRQ1(PetscObjectComm((PetscObject)ts),PETSC_ERR_USER,"Should not call TSComputeRHSJacobian() on a shifted matrix (shift=%lf) when RHSJacobian is reusable.",ts->rhsjacobian.shift);
592:   if (rhsjacobianfunc) {
593:     PetscLogEventBegin(TS_JacobianEval,ts,U,A,B);
594:     PetscStackPush("TS user Jacobian function");
595:     (*rhsjacobianfunc)(ts,t,U,A,B,ctx);
596:     PetscStackPop;
597:     PetscLogEventEnd(TS_JacobianEval,ts,U,A,B);
598:   } else {
599:     MatZeroEntries(A);
600:     if (B && A != B) {MatZeroEntries(B);}
601:   }
602:   ts->rhsjacobian.time  = t;
603:   ts->rhsjacobian.shift = 0;
604:   ts->rhsjacobian.scale = 1.;
605:   PetscObjectGetId((PetscObject)U,&ts->rhsjacobian.Xid);
606:   PetscObjectStateGet((PetscObject)U,&ts->rhsjacobian.Xstate);
607:   return(0);
608: }

610: /*@
611:    TSComputeRHSFunction - Evaluates the right-hand-side function.

613:    Collective on TS

615:    Input Parameters:
616: +  ts - the TS context
617: .  t - current time
618: -  U - state vector

620:    Output Parameter:
621: .  y - right hand side

623:    Note:
624:    Most users should not need to explicitly call this routine, as it
625:    is used internally within the nonlinear solvers.

627:    Level: developer

629: .seealso: TSSetRHSFunction(), TSComputeIFunction()
630: @*/
631: PetscErrorCode TSComputeRHSFunction(TS ts,PetscReal t,Vec U,Vec y)
632: {
634:   TSRHSFunction  rhsfunction;
635:   TSIFunction    ifunction;
636:   void           *ctx;
637:   DM             dm;

643:   TSGetDM(ts,&dm);
644:   DMTSGetRHSFunction(dm,&rhsfunction,&ctx);
645:   DMTSGetIFunction(dm,&ifunction,NULL);

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

649:   PetscLogEventBegin(TS_FunctionEval,ts,U,y,0);
650:   if (rhsfunction) {
651:     VecLockReadPush(U);
652:     PetscStackPush("TS user right-hand-side function");
653:     (*rhsfunction)(ts,t,U,y,ctx);
654:     PetscStackPop;
655:     VecLockReadPop(U);
656:   } else {
657:     VecZeroEntries(y);
658:   }

660:   PetscLogEventEnd(TS_FunctionEval,ts,U,y,0);
661:   return(0);
662: }

664: /*@
665:    TSComputeSolutionFunction - Evaluates the solution function.

667:    Collective on TS

669:    Input Parameters:
670: +  ts - the TS context
671: -  t - current time

673:    Output Parameter:
674: .  U - the solution

676:    Note:
677:    Most users should not need to explicitly call this routine, as it
678:    is used internally within the nonlinear solvers.

680:    Level: developer

682: .seealso: TSSetSolutionFunction(), TSSetRHSFunction(), TSComputeIFunction()
683: @*/
684: PetscErrorCode TSComputeSolutionFunction(TS ts,PetscReal t,Vec U)
685: {
686:   PetscErrorCode     ierr;
687:   TSSolutionFunction solutionfunction;
688:   void               *ctx;
689:   DM                 dm;

694:   TSGetDM(ts,&dm);
695:   DMTSGetSolutionFunction(dm,&solutionfunction,&ctx);

697:   if (solutionfunction) {
698:     PetscStackPush("TS user solution function");
699:     (*solutionfunction)(ts,t,U,ctx);
700:     PetscStackPop;
701:   }
702:   return(0);
703: }
704: /*@
705:    TSComputeForcingFunction - Evaluates the forcing function.

707:    Collective on TS

709:    Input Parameters:
710: +  ts - the TS context
711: -  t - current time

713:    Output Parameter:
714: .  U - the function value

716:    Note:
717:    Most users should not need to explicitly call this routine, as it
718:    is used internally within the nonlinear solvers.

720:    Level: developer

722: .seealso: TSSetSolutionFunction(), TSSetRHSFunction(), TSComputeIFunction()
723: @*/
724: PetscErrorCode TSComputeForcingFunction(TS ts,PetscReal t,Vec U)
725: {
726:   PetscErrorCode     ierr, (*forcing)(TS,PetscReal,Vec,void*);
727:   void               *ctx;
728:   DM                 dm;

733:   TSGetDM(ts,&dm);
734:   DMTSGetForcingFunction(dm,&forcing,&ctx);

736:   if (forcing) {
737:     PetscStackPush("TS user forcing function");
738:     (*forcing)(ts,t,U,ctx);
739:     PetscStackPop;
740:   }
741:   return(0);
742: }

744: static PetscErrorCode TSGetRHSVec_Private(TS ts,Vec *Frhs)
745: {
746:   Vec            F;

750:   *Frhs = NULL;
751:   TSGetIFunction(ts,&F,NULL,NULL);
752:   if (!ts->Frhs) {
753:     VecDuplicate(F,&ts->Frhs);
754:   }
755:   *Frhs = ts->Frhs;
756:   return(0);
757: }

759: PetscErrorCode TSGetRHSMats_Private(TS ts,Mat *Arhs,Mat *Brhs)
760: {
761:   Mat            A,B;
763:   TSIJacobian    ijacobian;

766:   if (Arhs) *Arhs = NULL;
767:   if (Brhs) *Brhs = NULL;
768:   TSGetIJacobian(ts,&A,&B,&ijacobian,NULL);
769:   if (Arhs) {
770:     if (!ts->Arhs) {
771:       if (ijacobian) {
772:         MatDuplicate(A,MAT_DO_NOT_COPY_VALUES,&ts->Arhs);
773:       } else {
774:         ts->Arhs = A;
775:         PetscObjectReference((PetscObject)A);
776:       }
777:     } else {
778:       PetscBool flg;
779:       SNESGetUseMatrixFree(ts->snes,NULL,&flg);
780:       /* Handle case where user provided only RHSJacobian and used -snes_mf_operator */
781:       if (flg && !ijacobian && ts->Arhs == ts->Brhs){
782:         PetscObjectDereference((PetscObject)ts->Arhs);
783:         ts->Arhs = A;
784:         PetscObjectReference((PetscObject)A);
785:       }
786:     }
787:     *Arhs = ts->Arhs;
788:   }
789:   if (Brhs) {
790:     if (!ts->Brhs) {
791:       if (A != B) {
792:         if (ijacobian) {
793:           MatDuplicate(B,MAT_DO_NOT_COPY_VALUES,&ts->Brhs);
794:         } else {
795:           ts->Brhs = B;
796:           PetscObjectReference((PetscObject)B);
797:         }
798:       } else {
799:         PetscObjectReference((PetscObject)ts->Arhs);
800:         ts->Brhs = ts->Arhs;
801:       }
802:     }
803:     *Brhs = ts->Brhs;
804:   }
805:   return(0);
806: }

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

811:    Collective on TS

813:    Input Parameters:
814: +  ts - the TS context
815: .  t - current time
816: .  U - state vector
817: .  Udot - time derivative of state vector
818: -  imex - flag indicates if the method is IMEX so that the RHSFunction should be kept separate

820:    Output Parameter:
821: .  Y - right hand side

823:    Note:
824:    Most users should not need to explicitly call this routine, as it
825:    is used internally within the nonlinear solvers.

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

830:    Level: developer

832: .seealso: TSSetIFunction(), TSComputeRHSFunction()
833: @*/
834: PetscErrorCode TSComputeIFunction(TS ts,PetscReal t,Vec U,Vec Udot,Vec Y,PetscBool imex)
835: {
837:   TSIFunction    ifunction;
838:   TSRHSFunction  rhsfunction;
839:   void           *ctx;
840:   DM             dm;


848:   TSGetDM(ts,&dm);
849:   DMTSGetIFunction(dm,&ifunction,&ctx);
850:   DMTSGetRHSFunction(dm,&rhsfunction,NULL);

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

854:   PetscLogEventBegin(TS_FunctionEval,ts,U,Udot,Y);
855:   if (ifunction) {
856:     PetscStackPush("TS user implicit function");
857:     (*ifunction)(ts,t,U,Udot,Y,ctx);
858:     PetscStackPop;
859:   }
860:   if (imex) {
861:     if (!ifunction) {
862:       VecCopy(Udot,Y);
863:     }
864:   } else if (rhsfunction) {
865:     if (ifunction) {
866:       Vec Frhs;
867:       TSGetRHSVec_Private(ts,&Frhs);
868:       TSComputeRHSFunction(ts,t,U,Frhs);
869:       VecAXPY(Y,-1,Frhs);
870:     } else {
871:       TSComputeRHSFunction(ts,t,U,Y);
872:       VecAYPX(Y,-1,Udot);
873:     }
874:   }
875:   PetscLogEventEnd(TS_FunctionEval,ts,U,Udot,Y);
876:   return(0);
877: }

879: /*
880:    TSRecoverRHSJacobian - Recover the Jacobian matrix so that one can call TSComputeRHSJacobian() on it.

882:    Note:
883:    This routine is needed when one switches from TSComputeIJacobian() to TSComputeRHSJacobian() because the Jacobian matrix may be shifted or scaled in TSComputeIJacobian().

885: */
886: static PetscErrorCode TSRecoverRHSJacobian(TS ts,Mat A,Mat B)
887: {
888:   PetscErrorCode   ierr;

892:   if (A != ts->Arhs) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"Invalid Amat");
893:   if (B != ts->Brhs) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"Invalid Bmat");

895:   if (ts->rhsjacobian.shift) {
896:     MatShift(A,-ts->rhsjacobian.shift);
897:   }
898:   if (ts->rhsjacobian.scale == -1.) {
899:     MatScale(A,-1);
900:   }
901:   if (B && B == ts->Brhs && A != B) {
902:     if (ts->rhsjacobian.shift) {
903:       MatShift(B,-ts->rhsjacobian.shift);
904:     }
905:     if (ts->rhsjacobian.scale == -1.) {
906:       MatScale(B,-1);
907:     }
908:   }
909:   ts->rhsjacobian.shift = 0;
910:   ts->rhsjacobian.scale = 1.;
911:   return(0);
912: }

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

917:    Collective on TS

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

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

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

935:    dF/dU + shift*dF/dUdot

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

940:    Level: developer

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


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

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

967:   PetscLogEventBegin(TS_JacobianEval,ts,U,A,B);
968:   if (ijacobian) {
969:     PetscStackPush("TS user implicit Jacobian");
970:     (*ijacobian)(ts,t,U,Udot,shift,A,B,ctx);
971:     PetscStackPop;
972:   }
973:   if (imex) {
974:     if (!ijacobian) {  /* system was written as Udot = G(t,U) */
975:       PetscBool assembled;
976:       if (rhsjacobian) {
977:         Mat Arhs = NULL;
978:         TSGetRHSMats_Private(ts,&Arhs,NULL);
979:         if (A == Arhs) {
980:           if (rhsjacobian == TSComputeRHSJacobianConstant) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"Unsupported operation! cannot use TSComputeRHSJacobianConstant"); /* there is no way to reconstruct shift*M-J since J cannot be reevaluated */
981:           ts->rhsjacobian.time = PETSC_MIN_REAL;
982:         }
983:       }
984:       MatZeroEntries(A);
985:       MatAssembled(A,&assembled);
986:       if (!assembled) {
987:         MatAssemblyBegin(A,MAT_FINAL_ASSEMBLY);
988:         MatAssemblyEnd(A,MAT_FINAL_ASSEMBLY);
989:       }
990:       MatShift(A,shift);
991:       if (A != B) {
992:         MatZeroEntries(B);
993:         MatAssembled(B,&assembled);
994:         if (!assembled) {
995:           MatAssemblyBegin(B,MAT_FINAL_ASSEMBLY);
996:           MatAssemblyEnd(B,MAT_FINAL_ASSEMBLY);
997:         }
998:         MatShift(B,shift);
999:       }
1000:     }
1001:   } else {
1002:     Mat Arhs = NULL,Brhs = NULL;
1003:     if (rhsjacobian) { /* RHSJacobian needs to be converted to part of IJacobian if exists */
1004:       TSGetRHSMats_Private(ts,&Arhs,&Brhs);
1005:     }
1006:     if (Arhs == A) { /* No IJacobian matrix, so we only have the RHS matrix */
1007:       PetscObjectState Ustate;
1008:       PetscObjectId    Uid;
1009:       TSRHSFunction    rhsfunction;

1011:       DMTSGetRHSFunction(dm,&rhsfunction,NULL);
1012:       PetscObjectStateGet((PetscObject)U,&Ustate);
1013:       PetscObjectGetId((PetscObject)U,&Uid);
1014:       if ((rhsjacobian == TSComputeRHSJacobianConstant || (ts->rhsjacobian.time == t && (ts->problem_type == TS_LINEAR || (ts->rhsjacobian.Xid == Uid && ts->rhsjacobian.Xstate == Ustate)) && rhsfunction != TSComputeRHSFunctionLinear)) && ts->rhsjacobian.scale == -1.) { /* No need to recompute RHSJacobian */
1015:         MatShift(A,shift-ts->rhsjacobian.shift); /* revert the old shift and add the new shift with a single call to MatShift */
1016:         if (A != B) {
1017:           MatShift(B,shift-ts->rhsjacobian.shift);
1018:         }
1019:       } else {
1020:         PetscBool flg;

1022:         if (ts->rhsjacobian.reuse) { /* Undo the damage */
1023:           /* MatScale has a short path for this case.
1024:              However, this code path is taken the first time TSComputeRHSJacobian is called
1025:              and the matrices have not been assembled yet */
1026:           TSRecoverRHSJacobian(ts,A,B);
1027:         }
1028:         TSComputeRHSJacobian(ts,t,U,A,B);
1029:         SNESGetUseMatrixFree(ts->snes,NULL,&flg);
1030:         /* since -snes_mf_operator uses the full SNES function it does not need to be shifted or scaled here */
1031:         if (!flg) {
1032:           MatScale(A,-1);
1033:           MatShift(A,shift);
1034:         }
1035:         if (A != B) {
1036:           MatScale(B,-1);
1037:           MatShift(B,shift);
1038:         }
1039:       }
1040:       ts->rhsjacobian.scale = -1;
1041:       ts->rhsjacobian.shift = shift;
1042:     } else if (Arhs) {  /* Both IJacobian and RHSJacobian exist or the RHS matrix provided (A) is different from the internal RHS matrix (Arhs) */
1043:       MatStructure axpy = DIFFERENT_NONZERO_PATTERN;

1045:       if (!ijacobian) { /* No IJacobian provided, but we have a separate RHS matrix */
1046:         MatZeroEntries(A);
1047:         MatShift(A,shift);
1048:         if (A != B) {
1049:           MatZeroEntries(B);
1050:           MatShift(B,shift);
1051:         }
1052:       }
1053:       TSComputeRHSJacobian(ts,t,U,Arhs,Brhs);
1054:       MatAXPY(A,-1,Arhs,axpy);
1055:       if (A != B) {
1056:         MatAXPY(B,-1,Brhs,axpy);
1057:       }
1058:     }
1059:   }
1060:   PetscLogEventEnd(TS_JacobianEval,ts,U,A,B);
1061:   return(0);
1062: }

1064: /*@C
1065:     TSSetRHSFunction - Sets the routine for evaluating the function,
1066:     where U_t = G(t,u).

1068:     Logically Collective on TS

1070:     Input Parameters:
1071: +   ts - the TS context obtained from TSCreate()
1072: .   r - vector to put the computed right hand side (or NULL to have it created)
1073: .   f - routine for evaluating the right-hand-side function
1074: -   ctx - [optional] user-defined context for private data for the
1075:           function evaluation routine (may be NULL)

1077:     Calling sequence of f:
1078: $     PetscErrorCode f(TS ts,PetscReal t,Vec u,Vec F,void *ctx);

1080: +   ts - timestep context
1081: .   t - current timestep
1082: .   u - input vector
1083: .   F - function vector
1084: -   ctx - [optional] user-defined function context

1086:     Level: beginner

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

1091: .seealso: TSSetRHSJacobian(), TSSetIJacobian(), TSSetIFunction()
1092: @*/
1093: PetscErrorCode  TSSetRHSFunction(TS ts,Vec r,PetscErrorCode (*f)(TS,PetscReal,Vec,Vec,void*),void *ctx)
1094: {
1096:   SNES           snes;
1097:   Vec            ralloc = NULL;
1098:   DM             dm;


1104:   TSGetDM(ts,&dm);
1105:   DMTSSetRHSFunction(dm,f,ctx);
1106:   TSGetSNES(ts,&snes);
1107:   if (!r && !ts->dm && ts->vec_sol) {
1108:     VecDuplicate(ts->vec_sol,&ralloc);
1109:     r = ralloc;
1110:   }
1111:   SNESSetFunction(snes,r,SNESTSFormFunction,ts);
1112:   VecDestroy(&ralloc);
1113:   return(0);
1114: }

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

1119:     Logically Collective on TS

1121:     Input Parameters:
1122: +   ts - the TS context obtained from TSCreate()
1123: .   f - routine for evaluating the solution
1124: -   ctx - [optional] user-defined context for private data for the
1125:           function evaluation routine (may be NULL)

1127:     Calling sequence of f:
1128: $     PetscErrorCode f(TS ts,PetscReal t,Vec u,void *ctx);

1130: +   t - current timestep
1131: .   u - output vector
1132: -   ctx - [optional] user-defined function context

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

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

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

1145:     Level: beginner

1147: .seealso: TSSetRHSJacobian(), TSSetIJacobian(), TSComputeSolutionFunction(), TSSetForcingFunction(), TSSetSolution(), TSGetSolution(), TSMonitorLGError(), TSMonitorDrawError()
1148: @*/
1149: PetscErrorCode  TSSetSolutionFunction(TS ts,PetscErrorCode (*f)(TS,PetscReal,Vec,void*),void *ctx)
1150: {
1152:   DM             dm;

1156:   TSGetDM(ts,&dm);
1157:   DMTSSetSolutionFunction(dm,f,ctx);
1158:   return(0);
1159: }

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

1164:     Logically Collective on TS

1166:     Input Parameters:
1167: +   ts - the TS context obtained from TSCreate()
1168: .   func - routine for evaluating the forcing function
1169: -   ctx - [optional] user-defined context for private data for the
1170:           function evaluation routine (may be NULL)

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

1175: +   t - current timestep
1176: .   f - output vector
1177: -   ctx - [optional] user-defined function context

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

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

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

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

1191:     Level: beginner

1193: .seealso: TSSetRHSJacobian(), TSSetIJacobian(), TSComputeSolutionFunction(), TSSetSolutionFunction()
1194: @*/
1195: PetscErrorCode  TSSetForcingFunction(TS ts,TSForcingFunction func,void *ctx)
1196: {
1198:   DM             dm;

1202:   TSGetDM(ts,&dm);
1203:   DMTSSetForcingFunction(dm,func,ctx);
1204:   return(0);
1205: }

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

1211:    Logically Collective on TS

1213:    Input Parameters:
1214: +  ts  - the TS context obtained from TSCreate()
1215: .  Amat - (approximate) Jacobian matrix
1216: .  Pmat - matrix from which preconditioner is to be constructed (usually the same as Amat)
1217: .  f   - the Jacobian evaluation routine
1218: -  ctx - [optional] user-defined context for private data for the
1219:          Jacobian evaluation routine (may be NULL)

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

1224: +  t - current timestep
1225: .  u - input vector
1226: .  Amat - (approximate) Jacobian matrix
1227: .  Pmat - matrix from which preconditioner is to be constructed (usually the same as Amat)
1228: -  ctx - [optional] user-defined context for matrix evaluation routine

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

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

1236:    Level: beginner

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

1240: @*/
1241: PetscErrorCode  TSSetRHSJacobian(TS ts,Mat Amat,Mat Pmat,TSRHSJacobian f,void *ctx)
1242: {
1244:   SNES           snes;
1245:   DM             dm;
1246:   TSIJacobian    ijacobian;


1255:   TSGetDM(ts,&dm);
1256:   DMTSSetRHSJacobian(dm,f,ctx);
1257:   DMTSGetIJacobian(dm,&ijacobian,NULL);
1258:   TSGetSNES(ts,&snes);
1259:   if (!ijacobian) {
1260:     SNESSetJacobian(snes,Amat,Pmat,SNESTSFormJacobian,ts);
1261:   }
1262:   if (Amat) {
1263:     PetscObjectReference((PetscObject)Amat);
1264:     MatDestroy(&ts->Arhs);
1265:     ts->Arhs = Amat;
1266:   }
1267:   if (Pmat) {
1268:     PetscObjectReference((PetscObject)Pmat);
1269:     MatDestroy(&ts->Brhs);
1270:     ts->Brhs = Pmat;
1271:   }
1272:   return(0);
1273: }

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

1278:    Logically Collective on TS

1280:    Input Parameters:
1281: +  ts  - the TS context obtained from TSCreate()
1282: .  r   - vector to hold the residual (or NULL to have it created internally)
1283: .  f   - the function evaluation routine
1284: -  ctx - user-defined context for private data for the function evaluation routine (may be NULL)

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

1289: +  t   - time at step/stage being solved
1290: .  u   - state vector
1291: .  u_t - time derivative of state vector
1292: .  F   - function vector
1293: -  ctx - [optional] user-defined context for matrix evaluation routine

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

1298:    Level: beginner

1300: .seealso: TSSetRHSJacobian(), TSSetRHSFunction(), TSSetIJacobian()
1301: @*/
1302: PetscErrorCode  TSSetIFunction(TS ts,Vec r,TSIFunction f,void *ctx)
1303: {
1305:   SNES           snes;
1306:   Vec            ralloc = NULL;
1307:   DM             dm;


1313:   TSGetDM(ts,&dm);
1314:   DMTSSetIFunction(dm,f,ctx);

1316:   TSGetSNES(ts,&snes);
1317:   if (!r && !ts->dm && ts->vec_sol) {
1318:     VecDuplicate(ts->vec_sol,&ralloc);
1319:     r  = ralloc;
1320:   }
1321:   SNESSetFunction(snes,r,SNESTSFormFunction,ts);
1322:   VecDestroy(&ralloc);
1323:   return(0);
1324: }

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

1329:    Not Collective

1331:    Input Parameter:
1332: .  ts - the TS context

1334:    Output Parameter:
1335: +  r - vector to hold residual (or NULL)
1336: .  func - the function to compute residual (or NULL)
1337: -  ctx - the function context (or NULL)

1339:    Level: advanced

1341: .seealso: TSSetIFunction(), SNESGetFunction()
1342: @*/
1343: PetscErrorCode TSGetIFunction(TS ts,Vec *r,TSIFunction *func,void **ctx)
1344: {
1346:   SNES           snes;
1347:   DM             dm;

1351:   TSGetSNES(ts,&snes);
1352:   SNESGetFunction(snes,r,NULL,NULL);
1353:   TSGetDM(ts,&dm);
1354:   DMTSGetIFunction(dm,func,ctx);
1355:   return(0);
1356: }

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

1361:    Not Collective

1363:    Input Parameter:
1364: .  ts - the TS context

1366:    Output Parameter:
1367: +  r - vector to hold computed right hand side (or NULL)
1368: .  func - the function to compute right hand side (or NULL)
1369: -  ctx - the function context (or NULL)

1371:    Level: advanced

1373: .seealso: TSSetRHSFunction(), SNESGetFunction()
1374: @*/
1375: PetscErrorCode TSGetRHSFunction(TS ts,Vec *r,TSRHSFunction *func,void **ctx)
1376: {
1378:   SNES           snes;
1379:   DM             dm;

1383:   TSGetSNES(ts,&snes);
1384:   SNESGetFunction(snes,r,NULL,NULL);
1385:   TSGetDM(ts,&dm);
1386:   DMTSGetRHSFunction(dm,func,ctx);
1387:   return(0);
1388: }

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

1394:    Logically Collective on TS

1396:    Input Parameters:
1397: +  ts  - the TS context obtained from TSCreate()
1398: .  Amat - (approximate) Jacobian matrix
1399: .  Pmat - matrix used to compute preconditioner (usually the same as Amat)
1400: .  f   - the Jacobian evaluation routine
1401: -  ctx - user-defined context for private data for the Jacobian evaluation routine (may be NULL)

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

1406: +  t    - time at step/stage being solved
1407: .  U    - state vector
1408: .  U_t  - time derivative of state vector
1409: .  a    - shift
1410: .  Amat - (approximate) Jacobian of F(t,U,W+a*U), equivalent to dF/dU + a*dF/dU_t
1411: .  Pmat - matrix used for constructing preconditioner, usually the same as Amat
1412: -  ctx  - [optional] user-defined context for matrix evaluation routine

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

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

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

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

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

1432:    Level: beginner

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

1436: @*/
1437: PetscErrorCode  TSSetIJacobian(TS ts,Mat Amat,Mat Pmat,TSIJacobian f,void *ctx)
1438: {
1440:   SNES           snes;
1441:   DM             dm;


1450:   TSGetDM(ts,&dm);
1451:   DMTSSetIJacobian(dm,f,ctx);

1453:   TSGetSNES(ts,&snes);
1454:   SNESSetJacobian(snes,Amat,Pmat,SNESTSFormJacobian,ts);
1455:   return(0);
1456: }

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

1464:    Logically Collective

1466:    Input Arguments:
1467: +  ts - TS context obtained from TSCreate()
1468: -  reuse - PETSC_TRUE if the RHS Jacobian

1470:    Level: intermediate

1472: .seealso: TSSetRHSJacobian(), TSComputeRHSJacobianConstant()
1473: @*/
1474: PetscErrorCode TSRHSJacobianSetReuse(TS ts,PetscBool reuse)
1475: {
1477:   ts->rhsjacobian.reuse = reuse;
1478:   return(0);
1479: }

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

1484:    Logically Collective on TS

1486:    Input Parameters:
1487: +  ts  - the TS context obtained from TSCreate()
1488: .  F   - vector to hold the residual (or NULL to have it created internally)
1489: .  fun - the function evaluation routine
1490: -  ctx - user-defined context for private data for the function evaluation routine (may be NULL)

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

1495: +  t    - time at step/stage being solved
1496: .  U    - state vector
1497: .  U_t  - time derivative of state vector
1498: .  U_tt - second time derivative of state vector
1499: .  F    - function vector
1500: -  ctx  - [optional] user-defined context for matrix evaluation routine (may be NULL)

1502:    Level: beginner

1504: .seealso: TSSetI2Jacobian(), TSSetIFunction(), TSCreate(), TSSetRHSFunction()
1505: @*/
1506: PetscErrorCode TSSetI2Function(TS ts,Vec F,TSI2Function fun,void *ctx)
1507: {
1508:   DM             dm;

1514:   TSSetIFunction(ts,F,NULL,NULL);
1515:   TSGetDM(ts,&dm);
1516:   DMTSSetI2Function(dm,fun,ctx);
1517:   return(0);
1518: }

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

1523:   Not Collective

1525:   Input Parameter:
1526: . ts - the TS context

1528:   Output Parameter:
1529: + r - vector to hold residual (or NULL)
1530: . fun - the function to compute residual (or NULL)
1531: - ctx - the function context (or NULL)

1533:   Level: advanced

1535: .seealso: TSSetIFunction(), SNESGetFunction(), TSCreate()
1536: @*/
1537: PetscErrorCode TSGetI2Function(TS ts,Vec *r,TSI2Function *fun,void **ctx)
1538: {
1540:   SNES           snes;
1541:   DM             dm;

1545:   TSGetSNES(ts,&snes);
1546:   SNESGetFunction(snes,r,NULL,NULL);
1547:   TSGetDM(ts,&dm);
1548:   DMTSGetI2Function(dm,fun,ctx);
1549:   return(0);
1550: }

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

1556:    Logically Collective on TS

1558:    Input Parameters:
1559: +  ts  - the TS context obtained from TSCreate()
1560: .  J   - Jacobian matrix
1561: .  P   - preconditioning matrix for J (may be same as J)
1562: .  jac - the Jacobian evaluation routine
1563: -  ctx - user-defined context for private data for the Jacobian evaluation routine (may be NULL)

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

1568: +  t    - time at step/stage being solved
1569: .  U    - state vector
1570: .  U_t  - time derivative of state vector
1571: .  U_tt - second time derivative of state vector
1572: .  v    - shift for U_t
1573: .  a    - shift for U_tt
1574: .  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
1575: .  P    - preconditioning matrix for J, may be same as J
1576: -  ctx  - [optional] user-defined context for matrix evaluation routine

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

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

1586:    Level: beginner

1588: .seealso: TSSetI2Function(), TSGetI2Jacobian()
1589: @*/
1590: PetscErrorCode TSSetI2Jacobian(TS ts,Mat J,Mat P,TSI2Jacobian jac,void *ctx)
1591: {
1592:   DM             dm;

1599:   TSSetIJacobian(ts,J,P,NULL,NULL);
1600:   TSGetDM(ts,&dm);
1601:   DMTSSetI2Jacobian(dm,jac,ctx);
1602:   return(0);
1603: }

1605: /*@C
1606:   TSGetI2Jacobian - Returns the implicit Jacobian at the present timestep.

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

1610:   Input Parameter:
1611: . ts  - The TS context obtained from TSCreate()

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

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

1622:   Level: advanced

1624: .seealso: TSGetTimeStep(), TSGetMatrices(), TSGetTime(), TSGetStepNumber(), TSSetI2Jacobian(), TSGetI2Function(), TSCreate()

1626: @*/
1627: PetscErrorCode  TSGetI2Jacobian(TS ts,Mat *J,Mat *P,TSI2Jacobian *jac,void **ctx)
1628: {
1630:   SNES           snes;
1631:   DM             dm;

1634:   TSGetSNES(ts,&snes);
1635:   SNESSetUpMatrices(snes);
1636:   SNESGetJacobian(snes,J,P,NULL,NULL);
1637:   TSGetDM(ts,&dm);
1638:   DMTSGetI2Jacobian(dm,jac,ctx);
1639:   return(0);
1640: }

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

1645:   Collective on TS

1647:   Input Parameters:
1648: + ts - the TS context
1649: . t - current time
1650: . U - state vector
1651: . V - time derivative of state vector (U_t)
1652: - A - second time derivative of state vector (U_tt)

1654:   Output Parameter:
1655: . F - the residual vector

1657:   Note:
1658:   Most users should not need to explicitly call this routine, as it
1659:   is used internally within the nonlinear solvers.

1661:   Level: developer

1663: .seealso: TSSetI2Function(), TSGetI2Function()
1664: @*/
1665: PetscErrorCode TSComputeI2Function(TS ts,PetscReal t,Vec U,Vec V,Vec A,Vec F)
1666: {
1667:   DM             dm;
1668:   TSI2Function   I2Function;
1669:   void           *ctx;
1670:   TSRHSFunction  rhsfunction;


1680:   TSGetDM(ts,&dm);
1681:   DMTSGetI2Function(dm,&I2Function,&ctx);
1682:   DMTSGetRHSFunction(dm,&rhsfunction,NULL);

1684:   if (!I2Function) {
1685:     TSComputeIFunction(ts,t,U,A,F,PETSC_FALSE);
1686:     return(0);
1687:   }

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

1691:   PetscStackPush("TS user implicit function");
1692:   I2Function(ts,t,U,V,A,F,ctx);
1693:   PetscStackPop;

1695:   if (rhsfunction) {
1696:     Vec Frhs;
1697:     TSGetRHSVec_Private(ts,&Frhs);
1698:     TSComputeRHSFunction(ts,t,U,Frhs);
1699:     VecAXPY(F,-1,Frhs);
1700:   }

1702:   PetscLogEventEnd(TS_FunctionEval,ts,U,V,F);
1703:   return(0);
1704: }

1706: /*@
1707:   TSComputeI2Jacobian - Evaluates the Jacobian of the DAE

1709:   Collective on TS

1711:   Input Parameters:
1712: + ts - the TS context
1713: . t - current timestep
1714: . U - state vector
1715: . V - time derivative of state vector
1716: . A - second time derivative of state vector
1717: . shiftV - shift to apply, see note below
1718: - shiftA - shift to apply, see note below

1720:   Output Parameters:
1721: + J - Jacobian matrix
1722: - P - optional preconditioning matrix

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

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

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

1732:   Level: developer

1734: .seealso:  TSSetI2Jacobian()
1735: @*/
1736: PetscErrorCode TSComputeI2Jacobian(TS ts,PetscReal t,Vec U,Vec V,Vec A,PetscReal shiftV,PetscReal shiftA,Mat J,Mat P)
1737: {
1738:   DM             dm;
1739:   TSI2Jacobian   I2Jacobian;
1740:   void           *ctx;
1741:   TSRHSJacobian  rhsjacobian;


1752:   TSGetDM(ts,&dm);
1753:   DMTSGetI2Jacobian(dm,&I2Jacobian,&ctx);
1754:   DMTSGetRHSJacobian(dm,&rhsjacobian,NULL);

1756:   if (!I2Jacobian) {
1757:     TSComputeIJacobian(ts,t,U,A,shiftA,J,P,PETSC_FALSE);
1758:     return(0);
1759:   }

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

1763:   PetscStackPush("TS user implicit Jacobian");
1764:   I2Jacobian(ts,t,U,V,A,shiftV,shiftA,J,P,ctx);
1765:   PetscStackPop;

1767:   if (rhsjacobian) {
1768:     Mat Jrhs,Prhs; MatStructure axpy = DIFFERENT_NONZERO_PATTERN;
1769:     TSGetRHSMats_Private(ts,&Jrhs,&Prhs);
1770:     TSComputeRHSJacobian(ts,t,U,Jrhs,Prhs);
1771:     MatAXPY(J,-1,Jrhs,axpy);
1772:     if (P != J) {MatAXPY(P,-1,Prhs,axpy);}
1773:   }

1775:   PetscLogEventEnd(TS_JacobianEval,ts,U,J,P);
1776:   return(0);
1777: }

1779: /*@C
1780:    TSSetTransientVariable - sets function to transform from state to transient variables

1782:    Logically Collective

1784:    Input Arguments:
1785: +  ts - time stepping context on which to change the transient variable
1786: .  tvar - a function that transforms to transient variables
1787: -  ctx - a context for tvar

1789:     Calling sequence of tvar:
1790: $     PetscErrorCode tvar(TS ts,Vec p,Vec c,void *ctx);

1792: +   ts - timestep context
1793: .   p - input vector (primative form)
1794: .   c - output vector, transient variables (conservative form)
1795: -   ctx - [optional] user-defined function context

1797:    Level: advanced

1799:    Notes:
1800:    This is typically used to transform from primitive to conservative variables so that a time integrator (e.g., TSBDF)
1801:    can be conservative.  In this context, primitive variables P are used to model the state (e.g., because they lead to
1802:    well-conditioned formulations even in limiting cases such as low-Mach or zero porosity).  The transient variable is
1803:    C(P), specified by calling this function.  An IFunction thus receives arguments (P, Cdot) and the IJacobian must be
1804:    evaluated via the chain rule, as in

1806:      dF/dP + shift * dF/dCdot dC/dP.

1808: .seealso: DMTSSetTransientVariable(), DMTSGetTransientVariable(), TSSetIFunction(), TSSetIJacobian()
1809: @*/
1810: PetscErrorCode TSSetTransientVariable(TS ts,TSTransientVariable tvar,void *ctx)
1811: {
1813:   DM             dm;

1817:   TSGetDM(ts,&dm);
1818:   DMTSSetTransientVariable(dm,tvar,ctx);
1819:   return(0);
1820: }

1822: /*@
1823:    TSComputeTransientVariable - transforms state (primitive) variables to transient (conservative) variables

1825:    Logically Collective

1827:    Input Parameters:
1828: +  ts - TS on which to compute
1829: -  U - state vector to be transformed to transient variables

1831:    Output Parameters:
1832: .  C - transient (conservative) variable

1834:    Developer Notes:
1835:    If DMTSSetTransientVariable() has not been called, then C is not modified in this routine and C=NULL is allowed.
1836:    This makes it safe to call without a guard.  One can use TSHasTransientVariable() to check if transient variables are
1837:    being used.

1839:    Level: developer

1841: .seealso: DMTSSetTransientVariable(), TSComputeIFunction(), TSComputeIJacobian()
1842: @*/
1843: PetscErrorCode TSComputeTransientVariable(TS ts,Vec U,Vec C)
1844: {
1846:   DM             dm;
1847:   DMTS           dmts;

1852:   TSGetDM(ts,&dm);
1853:   DMGetDMTS(dm,&dmts);
1854:   if (dmts->ops->transientvar) {
1856:     (*dmts->ops->transientvar)(ts,U,C,dmts->transientvarctx);
1857:   }
1858:   return(0);
1859: }

1861: /*@
1862:    TSHasTransientVariable - determine whether transient variables have been set

1864:    Logically Collective

1866:    Input Parameters:
1867: .  ts - TS on which to compute

1869:    Output Parameters:
1870: .  has - PETSC_TRUE if transient variables have been set

1872:    Level: developer

1874: .seealso: DMTSSetTransientVariable(), TSComputeTransientVariable()
1875: @*/
1876: PetscErrorCode TSHasTransientVariable(TS ts,PetscBool *has)
1877: {
1879:   DM             dm;
1880:   DMTS           dmts;

1884:   TSGetDM(ts,&dm);
1885:   DMGetDMTS(dm,&dmts);
1886:   *has = dmts->ops->transientvar ? PETSC_TRUE : PETSC_FALSE;
1887:   return(0);
1888: }

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

1894:    Logically Collective on TS

1896:    Input Parameters:
1897: +  ts - the TS context obtained from TSCreate()
1898: .  u - the solution vector
1899: -  v - the time derivative vector

1901:    Level: beginner

1903: @*/
1904: PetscErrorCode  TS2SetSolution(TS ts,Vec u,Vec v)
1905: {

1912:   TSSetSolution(ts,u);
1913:   PetscObjectReference((PetscObject)v);
1914:   VecDestroy(&ts->vec_dot);
1915:   ts->vec_dot = v;
1916:   return(0);
1917: }

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

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

1927:    Input Parameter:
1928: .  ts - the TS context obtained from TSCreate()

1930:    Output Parameter:
1931: +  u - the vector containing the solution
1932: -  v - the vector containing the time derivative

1934:    Level: intermediate

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

1938: @*/
1939: PetscErrorCode  TS2GetSolution(TS ts,Vec *u,Vec *v)
1940: {
1945:   if (u) *u = ts->vec_sol;
1946:   if (v) *v = ts->vec_dot;
1947:   return(0);
1948: }

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

1953:   Collective on PetscViewer

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

1960:    Level: intermediate

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

1965:   Notes for advanced users:
1966:   Most users should not need to know the details of the binary storage
1967:   format, since TSLoad() and TSView() completely hide these details.
1968:   But for anyone who's interested, the standard binary matrix storage
1969:   format is
1970: .vb
1971:      has not yet been determined
1972: .ve

1974: .seealso: PetscViewerBinaryOpen(), TSView(), MatLoad(), VecLoad()
1975: @*/
1976: PetscErrorCode  TSLoad(TS ts, PetscViewer viewer)
1977: {
1979:   PetscBool      isbinary;
1980:   PetscInt       classid;
1981:   char           type[256];
1982:   DMTS           sdm;
1983:   DM             dm;

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

1991:   PetscViewerBinaryRead(viewer,&classid,1,NULL,PETSC_INT);
1992:   if (classid != TS_FILE_CLASSID) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_ARG_WRONG,"Not TS next in file");
1993:   PetscViewerBinaryRead(viewer,type,256,NULL,PETSC_CHAR);
1994:   TSSetType(ts, type);
1995:   if (ts->ops->load) {
1996:     (*ts->ops->load)(ts,viewer);
1997:   }
1998:   DMCreate(PetscObjectComm((PetscObject)ts),&dm);
1999:   DMLoad(dm,viewer);
2000:   TSSetDM(ts,dm);
2001:   DMCreateGlobalVector(ts->dm,&ts->vec_sol);
2002:   VecLoad(ts->vec_sol,viewer);
2003:   DMGetDMTS(ts->dm,&sdm);
2004:   DMTSLoad(sdm,viewer);
2005:   return(0);
2006: }

2008: #include <petscdraw.h>
2009: #if defined(PETSC_HAVE_SAWS)
2010: #include <petscviewersaws.h>
2011: #endif

2013: /*@C
2014:    TSViewFromOptions - View from Options

2016:    Collective on TS

2018:    Input Parameters:
2019: +  A - the application ordering context
2020: .  obj - Optional object
2021: -  name - command line option

2023:    Level: intermediate
2024: .seealso:  TS, TSView, PetscObjectViewFromOptions(), TSCreate()
2025: @*/
2026: PetscErrorCode  TSViewFromOptions(TS A,PetscObject obj,const char name[])
2027: {

2032:   PetscObjectViewFromOptions((PetscObject)A,obj,name);
2033:   return(0);
2034: }

2036: /*@C
2037:     TSView - Prints the TS data structure.

2039:     Collective on TS

2041:     Input Parameters:
2042: +   ts - the TS context obtained from TSCreate()
2043: -   viewer - visualization context

2045:     Options Database Key:
2046: .   -ts_view - calls TSView() at end of TSStep()

2048:     Notes:
2049:     The available visualization contexts include
2050: +     PETSC_VIEWER_STDOUT_SELF - standard output (default)
2051: -     PETSC_VIEWER_STDOUT_WORLD - synchronized standard
2052:          output where only the first processor opens
2053:          the file.  All other processors send their
2054:          data to the first processor to print.

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

2059:     In the debugger you can do "call TSView(ts,0)" to display the TS solver. (The same holds for any PETSc object viewer).

2061:     Level: beginner

2063: .seealso: PetscViewerASCIIOpen()
2064: @*/
2065: PetscErrorCode  TSView(TS ts,PetscViewer viewer)
2066: {
2068:   TSType         type;
2069:   PetscBool      iascii,isstring,isundials,isbinary,isdraw;
2070:   DMTS           sdm;
2071: #if defined(PETSC_HAVE_SAWS)
2072:   PetscBool      issaws;
2073: #endif

2077:   if (!viewer) {
2078:     PetscViewerASCIIGetStdout(PetscObjectComm((PetscObject)ts),&viewer);
2079:   }

2083:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERASCII,&iascii);
2084:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERSTRING,&isstring);
2085:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERBINARY,&isbinary);
2086:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERDRAW,&isdraw);
2087: #if defined(PETSC_HAVE_SAWS)
2088:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERSAWS,&issaws);
2089: #endif
2090:   if (iascii) {
2091:     PetscObjectPrintClassNamePrefixType((PetscObject)ts,viewer);
2092:     if (ts->ops->view) {
2093:       PetscViewerASCIIPushTab(viewer);
2094:       (*ts->ops->view)(ts,viewer);
2095:       PetscViewerASCIIPopTab(viewer);
2096:     }
2097:     if (ts->max_steps < PETSC_MAX_INT) {
2098:       PetscViewerASCIIPrintf(viewer,"  maximum steps=%D\n",ts->max_steps);
2099:     }
2100:     if (ts->max_time < PETSC_MAX_REAL) {
2101:       PetscViewerASCIIPrintf(viewer,"  maximum time=%g\n",(double)ts->max_time);
2102:     }
2103:     if (ts->usessnes) {
2104:       PetscBool lin;
2105:       if (ts->problem_type == TS_NONLINEAR) {
2106:         PetscViewerASCIIPrintf(viewer,"  total number of nonlinear solver iterations=%D\n",ts->snes_its);
2107:       }
2108:       PetscViewerASCIIPrintf(viewer,"  total number of linear solver iterations=%D\n",ts->ksp_its);
2109:       PetscObjectTypeCompareAny((PetscObject)ts->snes,&lin,SNESKSPONLY,SNESKSPTRANSPOSEONLY,"");
2110:       PetscViewerASCIIPrintf(viewer,"  total number of %slinear solve failures=%D\n",lin ? "" : "non",ts->num_snes_failures);
2111:     }
2112:     PetscViewerASCIIPrintf(viewer,"  total number of rejected steps=%D\n",ts->reject);
2113:     if (ts->vrtol) {
2114:       PetscViewerASCIIPrintf(viewer,"  using vector of relative error tolerances, ");
2115:     } else {
2116:       PetscViewerASCIIPrintf(viewer,"  using relative error tolerance of %g, ",(double)ts->rtol);
2117:     }
2118:     if (ts->vatol) {
2119:       PetscViewerASCIIPrintf(viewer,"  using vector of absolute error tolerances\n");
2120:     } else {
2121:       PetscViewerASCIIPrintf(viewer,"  using absolute error tolerance of %g\n",(double)ts->atol);
2122:     }
2123:     PetscViewerASCIIPushTab(viewer);
2124:     TSAdaptView(ts->adapt,viewer);
2125:     PetscViewerASCIIPopTab(viewer);
2126:   } else if (isstring) {
2127:     TSGetType(ts,&type);
2128:     PetscViewerStringSPrintf(viewer," TSType: %-7.7s",type);
2129:     if (ts->ops->view) {(*ts->ops->view)(ts,viewer);}
2130:   } else if (isbinary) {
2131:     PetscInt    classid = TS_FILE_CLASSID;
2132:     MPI_Comm    comm;
2133:     PetscMPIInt rank;
2134:     char        type[256];

2136:     PetscObjectGetComm((PetscObject)ts,&comm);
2137:     MPI_Comm_rank(comm,&rank);
2138:     if (!rank) {
2139:       PetscViewerBinaryWrite(viewer,&classid,1,PETSC_INT);
2140:       PetscStrncpy(type,((PetscObject)ts)->type_name,256);
2141:       PetscViewerBinaryWrite(viewer,type,256,PETSC_CHAR);
2142:     }
2143:     if (ts->ops->view) {
2144:       (*ts->ops->view)(ts,viewer);
2145:     }
2146:     if (ts->adapt) {TSAdaptView(ts->adapt,viewer);}
2147:     DMView(ts->dm,viewer);
2148:     VecView(ts->vec_sol,viewer);
2149:     DMGetDMTS(ts->dm,&sdm);
2150:     DMTSView(sdm,viewer);
2151:   } else if (isdraw) {
2152:     PetscDraw draw;
2153:     char      str[36];
2154:     PetscReal x,y,bottom,h;

2156:     PetscViewerDrawGetDraw(viewer,0,&draw);
2157:     PetscDrawGetCurrentPoint(draw,&x,&y);
2158:     PetscStrcpy(str,"TS: ");
2159:     PetscStrcat(str,((PetscObject)ts)->type_name);
2160:     PetscDrawStringBoxed(draw,x,y,PETSC_DRAW_BLACK,PETSC_DRAW_BLACK,str,NULL,&h);
2161:     bottom = y - h;
2162:     PetscDrawPushCurrentPoint(draw,x,bottom);
2163:     if (ts->ops->view) {
2164:       (*ts->ops->view)(ts,viewer);
2165:     }
2166:     if (ts->adapt) {TSAdaptView(ts->adapt,viewer);}
2167:     if (ts->snes)  {SNESView(ts->snes,viewer);}
2168:     PetscDrawPopCurrentPoint(draw);
2169: #if defined(PETSC_HAVE_SAWS)
2170:   } else if (issaws) {
2171:     PetscMPIInt rank;
2172:     const char  *name;

2174:     PetscObjectGetName((PetscObject)ts,&name);
2175:     MPI_Comm_rank(PETSC_COMM_WORLD,&rank);
2176:     if (!((PetscObject)ts)->amsmem && !rank) {
2177:       char       dir[1024];

2179:       PetscObjectViewSAWs((PetscObject)ts,viewer);
2180:       PetscSNPrintf(dir,1024,"/PETSc/Objects/%s/time_step",name);
2181:       PetscStackCallSAWs(SAWs_Register,(dir,&ts->steps,1,SAWs_READ,SAWs_INT));
2182:       PetscSNPrintf(dir,1024,"/PETSc/Objects/%s/time",name);
2183:       PetscStackCallSAWs(SAWs_Register,(dir,&ts->ptime,1,SAWs_READ,SAWs_DOUBLE));
2184:     }
2185:     if (ts->ops->view) {
2186:       (*ts->ops->view)(ts,viewer);
2187:     }
2188: #endif
2189:   }
2190:   if (ts->snes && ts->usessnes)  {
2191:     PetscViewerASCIIPushTab(viewer);
2192:     SNESView(ts->snes,viewer);
2193:     PetscViewerASCIIPopTab(viewer);
2194:   }
2195:   DMGetDMTS(ts->dm,&sdm);
2196:   DMTSView(sdm,viewer);

2198:   PetscViewerASCIIPushTab(viewer);
2199:   PetscObjectTypeCompare((PetscObject)ts,TSSUNDIALS,&isundials);
2200:   PetscViewerASCIIPopTab(viewer);
2201:   return(0);
2202: }

2204: /*@
2205:    TSSetApplicationContext - Sets an optional user-defined context for
2206:    the timesteppers.

2208:    Logically Collective on TS

2210:    Input Parameters:
2211: +  ts - the TS context obtained from TSCreate()
2212: -  usrP - optional user context

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

2218:    Level: intermediate

2220: .seealso: TSGetApplicationContext()
2221: @*/
2222: PetscErrorCode  TSSetApplicationContext(TS ts,void *usrP)
2223: {
2226:   ts->user = usrP;
2227:   return(0);
2228: }

2230: /*@
2231:     TSGetApplicationContext - Gets the user-defined context for the
2232:     timestepper.

2234:     Not Collective

2236:     Input Parameter:
2237: .   ts - the TS context obtained from TSCreate()

2239:     Output Parameter:
2240: .   usrP - user context

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

2246:     Level: intermediate

2248: .seealso: TSSetApplicationContext()
2249: @*/
2250: PetscErrorCode  TSGetApplicationContext(TS ts,void *usrP)
2251: {
2254:   *(void**)usrP = ts->user;
2255:   return(0);
2256: }

2258: /*@
2259:    TSGetStepNumber - Gets the number of steps completed.

2261:    Not Collective

2263:    Input Parameter:
2264: .  ts - the TS context obtained from TSCreate()

2266:    Output Parameter:
2267: .  steps - number of steps completed so far

2269:    Level: intermediate

2271: .seealso: TSGetTime(), TSGetTimeStep(), TSSetPreStep(), TSSetPreStage(), TSSetPostStage(), TSSetPostStep()
2272: @*/
2273: PetscErrorCode TSGetStepNumber(TS ts,PetscInt *steps)
2274: {
2278:   *steps = ts->steps;
2279:   return(0);
2280: }

2282: /*@
2283:    TSSetStepNumber - Sets the number of steps completed.

2285:    Logically Collective on TS

2287:    Input Parameters:
2288: +  ts - the TS context
2289: -  steps - number of steps completed so far

2291:    Notes:
2292:    For most uses of the TS solvers the user need not explicitly call
2293:    TSSetStepNumber(), as the step counter is appropriately updated in
2294:    TSSolve()/TSStep()/TSRollBack(). Power users may call this routine to
2295:    reinitialize timestepping by setting the step counter to zero (and time
2296:    to the initial time) to solve a similar problem with different initial
2297:    conditions or parameters. Other possible use case is to continue
2298:    timestepping from a previously interrupted run in such a way that TS
2299:    monitors will be called with a initial nonzero step counter.

2301:    Level: advanced

2303: .seealso: TSGetStepNumber(), TSSetTime(), TSSetTimeStep(), TSSetSolution()
2304: @*/
2305: PetscErrorCode TSSetStepNumber(TS ts,PetscInt steps)
2306: {
2310:   if (steps < 0) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_ARG_OUTOFRANGE,"Step number must be non-negative");
2311:   ts->steps = steps;
2312:   return(0);
2313: }

2315: /*@
2316:    TSSetTimeStep - Allows one to reset the timestep at any time,
2317:    useful for simple pseudo-timestepping codes.

2319:    Logically Collective on TS

2321:    Input Parameters:
2322: +  ts - the TS context obtained from TSCreate()
2323: -  time_step - the size of the timestep

2325:    Level: intermediate

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

2329: @*/
2330: PetscErrorCode  TSSetTimeStep(TS ts,PetscReal time_step)
2331: {
2335:   ts->time_step = time_step;
2336:   return(0);
2337: }

2339: /*@
2340:    TSSetExactFinalTime - Determines whether to adapt the final time step to
2341:      match the exact final time, interpolate solution to the exact final time,
2342:      or just return at the final time TS computed.

2344:   Logically Collective on TS

2346:    Input Parameter:
2347: +   ts - the time-step context
2348: -   eftopt - exact final time option

2350: $  TS_EXACTFINALTIME_STEPOVER    - Don't do anything if final time is exceeded
2351: $  TS_EXACTFINALTIME_INTERPOLATE - Interpolate back to final time
2352: $  TS_EXACTFINALTIME_MATCHSTEP - Adapt final time step to match the final time

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

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

2360:    Level: beginner

2362: .seealso: TSExactFinalTimeOption, TSGetExactFinalTime()
2363: @*/
2364: PetscErrorCode TSSetExactFinalTime(TS ts,TSExactFinalTimeOption eftopt)
2365: {
2369:   ts->exact_final_time = eftopt;
2370:   return(0);
2371: }

2373: /*@
2374:    TSGetExactFinalTime - Gets the exact final time option.

2376:    Not Collective

2378:    Input Parameter:
2379: .  ts - the TS context

2381:    Output Parameter:
2382: .  eftopt - exact final time option

2384:    Level: beginner

2386: .seealso: TSExactFinalTimeOption, TSSetExactFinalTime()
2387: @*/
2388: PetscErrorCode TSGetExactFinalTime(TS ts,TSExactFinalTimeOption *eftopt)
2389: {
2393:   *eftopt = ts->exact_final_time;
2394:   return(0);
2395: }

2397: /*@
2398:    TSGetTimeStep - Gets the current timestep size.

2400:    Not Collective

2402:    Input Parameter:
2403: .  ts - the TS context obtained from TSCreate()

2405:    Output Parameter:
2406: .  dt - the current timestep size

2408:    Level: intermediate

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

2412: @*/
2413: PetscErrorCode  TSGetTimeStep(TS ts,PetscReal *dt)
2414: {
2418:   *dt = ts->time_step;
2419:   return(0);
2420: }

2422: /*@
2423:    TSGetSolution - Returns the solution at the present timestep. It
2424:    is valid to call this routine inside the function that you are evaluating
2425:    in order to move to the new timestep. This vector not changed until
2426:    the solution at the next timestep has been calculated.

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

2430:    Input Parameter:
2431: .  ts - the TS context obtained from TSCreate()

2433:    Output Parameter:
2434: .  v - the vector containing the solution

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

2439:    Level: intermediate

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

2443: @*/
2444: PetscErrorCode  TSGetSolution(TS ts,Vec *v)
2445: {
2449:   *v = ts->vec_sol;
2450:   return(0);
2451: }

2453: /*@
2454:    TSGetSolutionComponents - Returns any solution components at the present
2455:    timestep, if available for the time integration method being used.
2456:    Solution components are quantities that share the same size and
2457:    structure as the solution vector.

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

2461:    Parameters :
2462: +  ts - the TS context obtained from TSCreate() (input parameter).
2463: .  n - If v is PETSC_NULL, then the number of solution components is
2464:        returned through n, else the n-th solution component is
2465:        returned in v.
2466: -  v - the vector containing the n-th solution component
2467:        (may be PETSC_NULL to use this function to find out
2468:         the number of solutions components).

2470:    Level: advanced

2472: .seealso: TSGetSolution()

2474: @*/
2475: PetscErrorCode  TSGetSolutionComponents(TS ts,PetscInt *n,Vec *v)
2476: {

2481:   if (!ts->ops->getsolutioncomponents) *n = 0;
2482:   else {
2483:     (*ts->ops->getsolutioncomponents)(ts,n,v);
2484:   }
2485:   return(0);
2486: }

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

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

2494:    Parameters :
2495: +  ts - the TS context obtained from TSCreate() (input parameter).
2496: -  v - the vector containing the auxiliary solution

2498:    Level: intermediate

2500: .seealso: TSGetSolution()

2502: @*/
2503: PetscErrorCode  TSGetAuxSolution(TS ts,Vec *v)
2504: {

2509:   if (ts->ops->getauxsolution) {
2510:     (*ts->ops->getauxsolution)(ts,v);
2511:   } else {
2512:     VecZeroEntries(*v);
2513:   }
2514:   return(0);
2515: }

2517: /*@
2518:    TSGetTimeError - Returns the estimated error vector, if the chosen
2519:    TSType has an error estimation functionality.

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

2523:    Note: MUST call after TSSetUp()

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

2530:    Level: intermediate

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

2534: @*/
2535: PetscErrorCode  TSGetTimeError(TS ts,PetscInt n,Vec *v)
2536: {

2541:   if (ts->ops->gettimeerror) {
2542:     (*ts->ops->gettimeerror)(ts,n,v);
2543:   } else {
2544:     VecZeroEntries(*v);
2545:   }
2546:   return(0);
2547: }

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

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

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

2560:    Level: intermediate

2562: .seealso: TSSetSolution(), TSGetTimeError)

2564: @*/
2565: PetscErrorCode  TSSetTimeError(TS ts,Vec v)
2566: {

2571:   if (!ts->setupcalled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Must call TSSetUp() first");
2572:   if (ts->ops->settimeerror) {
2573:     (*ts->ops->settimeerror)(ts,v);
2574:   }
2575:   return(0);
2576: }

2578: /* ----- Routines to initialize and destroy a timestepper ---- */
2579: /*@
2580:   TSSetProblemType - Sets the type of problem to be solved.

2582:   Not collective

2584:   Input Parameters:
2585: + ts   - The TS
2586: - type - One of TS_LINEAR, TS_NONLINEAR where these types refer to problems of the forms
2587: .vb
2588:          U_t - A U = 0      (linear)
2589:          U_t - A(t) U = 0   (linear)
2590:          F(t,U,U_t) = 0     (nonlinear)
2591: .ve

2593:    Level: beginner

2595: .seealso: TSSetUp(), TSProblemType, TS
2596: @*/
2597: PetscErrorCode  TSSetProblemType(TS ts, TSProblemType type)
2598: {

2603:   ts->problem_type = type;
2604:   if (type == TS_LINEAR) {
2605:     SNES snes;
2606:     TSGetSNES(ts,&snes);
2607:     SNESSetType(snes,SNESKSPONLY);
2608:   }
2609:   return(0);
2610: }

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

2615:   Not collective

2617:   Input Parameter:
2618: . ts   - The TS

2620:   Output Parameter:
2621: . type - One of TS_LINEAR, TS_NONLINEAR where these types refer to problems of the forms
2622: .vb
2623:          M U_t = A U
2624:          M(t) U_t = A(t) U
2625:          F(t,U,U_t)
2626: .ve

2628:    Level: beginner

2630: .seealso: TSSetUp(), TSProblemType, TS
2631: @*/
2632: PetscErrorCode  TSGetProblemType(TS ts, TSProblemType *type)
2633: {
2637:   *type = ts->problem_type;
2638:   return(0);
2639: }

2641: /*
2642:     Attempt to check/preset a default value for the exact final time option. This is needed at the beginning of TSSolve() and in TSSetUp()
2643: */
2644: static PetscErrorCode TSSetExactFinalTimeDefault(TS ts)
2645: {
2647:   PetscBool      isnone;

2650:   TSGetAdapt(ts,&ts->adapt);
2651:   TSAdaptSetDefaultType(ts->adapt,ts->default_adapt_type);

2653:   PetscObjectTypeCompare((PetscObject)ts->adapt,TSADAPTNONE,&isnone);
2654:   if (!isnone && ts->exact_final_time == TS_EXACTFINALTIME_UNSPECIFIED) {
2655:     ts->exact_final_time = TS_EXACTFINALTIME_MATCHSTEP;
2656:   } else if (ts->exact_final_time == TS_EXACTFINALTIME_UNSPECIFIED) {
2657:     ts->exact_final_time = TS_EXACTFINALTIME_INTERPOLATE;
2658:   }
2659:   return(0);
2660: }


2663: /*@
2664:    TSSetUp - Sets up the internal data structures for the later use of a timestepper.

2666:    Collective on TS

2668:    Input Parameter:
2669: .  ts - the TS context obtained from TSCreate()

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

2678:    Level: advanced

2680: .seealso: TSCreate(), TSStep(), TSDestroy(), TSSolve()
2681: @*/
2682: PetscErrorCode  TSSetUp(TS ts)
2683: {
2685:   DM             dm;
2686:   PetscErrorCode (*func)(SNES,Vec,Vec,void*);
2687:   PetscErrorCode (*jac)(SNES,Vec,Mat,Mat,void*);
2688:   TSIFunction    ifun;
2689:   TSIJacobian    ijac;
2690:   TSI2Jacobian   i2jac;
2691:   TSRHSJacobian  rhsjac;

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

2697:   if (!((PetscObject)ts)->type_name) {
2698:     TSGetIFunction(ts,NULL,&ifun,NULL);
2699:     TSSetType(ts,ifun ? TSBEULER : TSEULER);
2700:   }

2702:   if (!ts->vec_sol) {
2703:     if (ts->dm) {
2704:       DMCreateGlobalVector(ts->dm,&ts->vec_sol);
2705:     } else SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Must call TSSetSolution() first");
2706:   }

2708:   if (!ts->Jacp && ts->Jacprhs) { /* IJacobianP shares the same matrix with RHSJacobianP if only RHSJacobianP is provided */
2709:     PetscObjectReference((PetscObject)ts->Jacprhs);
2710:     ts->Jacp = ts->Jacprhs;
2711:   }

2713:   if (ts->quadraturets) {
2714:     TSSetUp(ts->quadraturets);
2715:     VecDestroy(&ts->vec_costintegrand);
2716:     VecDuplicate(ts->quadraturets->vec_sol,&ts->vec_costintegrand);
2717:   }

2719:   TSGetRHSJacobian(ts,NULL,NULL,&rhsjac,NULL);
2720:   if (rhsjac == TSComputeRHSJacobianConstant) {
2721:     Mat Amat,Pmat;
2722:     SNES snes;
2723:     TSGetSNES(ts,&snes);
2724:     SNESGetJacobian(snes,&Amat,&Pmat,NULL,NULL);
2725:     /* Matching matrices implies that an IJacobian is NOT set, because if it had been set, the IJacobian's matrix would
2726:      * have displaced the RHS matrix */
2727:     if (Amat && Amat == ts->Arhs) {
2728:       /* 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 */
2729:       MatDuplicate(ts->Arhs,MAT_COPY_VALUES,&Amat);
2730:       SNESSetJacobian(snes,Amat,NULL,NULL,NULL);
2731:       MatDestroy(&Amat);
2732:     }
2733:     if (Pmat && Pmat == ts->Brhs) {
2734:       MatDuplicate(ts->Brhs,MAT_COPY_VALUES,&Pmat);
2735:       SNESSetJacobian(snes,NULL,Pmat,NULL,NULL);
2736:       MatDestroy(&Pmat);
2737:     }
2738:   }

2740:   TSGetAdapt(ts,&ts->adapt);
2741:   TSAdaptSetDefaultType(ts->adapt,ts->default_adapt_type);

2743:   if (ts->ops->setup) {
2744:     (*ts->ops->setup)(ts);
2745:   }

2747:   TSSetExactFinalTimeDefault(ts);

2749:   /* In the case where we've set a DMTSFunction or what have you, we need the default SNESFunction
2750:      to be set right but can't do it elsewhere due to the overreliance on ctx=ts.
2751:    */
2752:   TSGetDM(ts,&dm);
2753:   DMSNESGetFunction(dm,&func,NULL);
2754:   if (!func) {
2755:     DMSNESSetFunction(dm,SNESTSFormFunction,ts);
2756:   }
2757:   /* If the SNES doesn't have a jacobian set and the TS has an ijacobian or rhsjacobian set, set the SNES to use it.
2758:      Otherwise, the SNES will use coloring internally to form the Jacobian.
2759:    */
2760:   DMSNESGetJacobian(dm,&jac,NULL);
2761:   DMTSGetIJacobian(dm,&ijac,NULL);
2762:   DMTSGetI2Jacobian(dm,&i2jac,NULL);
2763:   DMTSGetRHSJacobian(dm,&rhsjac,NULL);
2764:   if (!jac && (ijac || i2jac || rhsjac)) {
2765:     DMSNESSetJacobian(dm,SNESTSFormJacobian,ts);
2766:   }

2768:   /* if time integration scheme has a starting method, call it */
2769:   if (ts->ops->startingmethod) {
2770:     (*ts->ops->startingmethod)(ts);
2771:   }

2773:   ts->setupcalled = PETSC_TRUE;
2774:   return(0);
2775: }

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

2780:    Collective on TS

2782:    Input Parameter:
2783: .  ts - the TS context obtained from TSCreate()

2785:    Level: beginner

2787: .seealso: TSCreate(), TSSetup(), TSDestroy()
2788: @*/
2789: PetscErrorCode  TSReset(TS ts)
2790: {
2791:   TS_RHSSplitLink ilink = ts->tsrhssplit,next;
2792:   PetscErrorCode  ierr;


2797:   if (ts->ops->reset) {
2798:     (*ts->ops->reset)(ts);
2799:   }
2800:   if (ts->snes) {SNESReset(ts->snes);}
2801:   if (ts->adapt) {TSAdaptReset(ts->adapt);}

2803:   MatDestroy(&ts->Arhs);
2804:   MatDestroy(&ts->Brhs);
2805:   VecDestroy(&ts->Frhs);
2806:   VecDestroy(&ts->vec_sol);
2807:   VecDestroy(&ts->vec_dot);
2808:   VecDestroy(&ts->vatol);
2809:   VecDestroy(&ts->vrtol);
2810:   VecDestroyVecs(ts->nwork,&ts->work);

2812:   MatDestroy(&ts->Jacprhs);
2813:   MatDestroy(&ts->Jacp);
2814:   if (ts->forward_solve) {
2815:     TSForwardReset(ts);
2816:   }
2817:   if (ts->quadraturets) {
2818:     TSReset(ts->quadraturets);
2819:     VecDestroy(&ts->vec_costintegrand);
2820:   }
2821:   while (ilink) {
2822:     next = ilink->next;
2823:     TSDestroy(&ilink->ts);
2824:     PetscFree(ilink->splitname);
2825:     ISDestroy(&ilink->is);
2826:     PetscFree(ilink);
2827:     ilink = next;
2828:   }
2829:   ts->num_rhs_splits = 0;
2830:   ts->setupcalled = PETSC_FALSE;
2831:   return(0);
2832: }

2834: /*@
2835:    TSDestroy - Destroys the timestepper context that was created
2836:    with TSCreate().

2838:    Collective on TS

2840:    Input Parameter:
2841: .  ts - the TS context obtained from TSCreate()

2843:    Level: beginner

2845: .seealso: TSCreate(), TSSetUp(), TSSolve()
2846: @*/
2847: PetscErrorCode  TSDestroy(TS *ts)
2848: {

2852:   if (!*ts) return(0);
2854:   if (--((PetscObject)(*ts))->refct > 0) {*ts = NULL; return(0);}

2856:   TSReset(*ts);
2857:   TSAdjointReset(*ts);
2858:   if ((*ts)->forward_solve) {
2859:     TSForwardReset(*ts);
2860:   }
2861:   /* if memory was published with SAWs then destroy it */
2862:   PetscObjectSAWsViewOff((PetscObject)*ts);
2863:   if ((*ts)->ops->destroy) {(*(*ts)->ops->destroy)((*ts));}

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

2867:   TSAdaptDestroy(&(*ts)->adapt);
2868:   TSEventDestroy(&(*ts)->event);

2870:   SNESDestroy(&(*ts)->snes);
2871:   DMDestroy(&(*ts)->dm);
2872:   TSMonitorCancel((*ts));
2873:   TSAdjointMonitorCancel((*ts));

2875:   TSDestroy(&(*ts)->quadraturets);
2876:   PetscHeaderDestroy(ts);
2877:   return(0);
2878: }

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

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

2886:    Input Parameter:
2887: .  ts - the TS context obtained from TSCreate()

2889:    Output Parameter:
2890: .  snes - the nonlinear solver context

2892:    Notes:
2893:    The user can then directly manipulate the SNES context to set various
2894:    options, etc.  Likewise, the user can then extract and manipulate the
2895:    KSP, KSP, and PC contexts as well.

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

2900:    Level: beginner

2902: @*/
2903: PetscErrorCode  TSGetSNES(TS ts,SNES *snes)
2904: {

2910:   if (!ts->snes) {
2911:     SNESCreate(PetscObjectComm((PetscObject)ts),&ts->snes);
2912:     PetscObjectSetOptions((PetscObject)ts->snes,((PetscObject)ts)->options);
2913:     SNESSetFunction(ts->snes,NULL,SNESTSFormFunction,ts);
2914:     PetscLogObjectParent((PetscObject)ts,(PetscObject)ts->snes);
2915:     PetscObjectIncrementTabLevel((PetscObject)ts->snes,(PetscObject)ts,1);
2916:     if (ts->dm) {SNESSetDM(ts->snes,ts->dm);}
2917:     if (ts->problem_type == TS_LINEAR) {
2918:       SNESSetType(ts->snes,SNESKSPONLY);
2919:     }
2920:   }
2921:   *snes = ts->snes;
2922:   return(0);
2923: }

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

2928:    Collective

2930:    Input Parameter:
2931: +  ts - the TS context obtained from TSCreate()
2932: -  snes - the nonlinear solver context

2934:    Notes:
2935:    Most users should have the TS created by calling TSGetSNES()

2937:    Level: developer

2939: @*/
2940: PetscErrorCode TSSetSNES(TS ts,SNES snes)
2941: {
2943:   PetscErrorCode (*func)(SNES,Vec,Mat,Mat,void*);

2948:   PetscObjectReference((PetscObject)snes);
2949:   SNESDestroy(&ts->snes);

2951:   ts->snes = snes;

2953:   SNESSetFunction(ts->snes,NULL,SNESTSFormFunction,ts);
2954:   SNESGetJacobian(ts->snes,NULL,NULL,&func,NULL);
2955:   if (func == SNESTSFormJacobian) {
2956:     SNESSetJacobian(ts->snes,NULL,NULL,SNESTSFormJacobian,ts);
2957:   }
2958:   return(0);
2959: }

2961: /*@
2962:    TSGetKSP - Returns the KSP (linear solver) associated with
2963:    a TS (timestepper) context.

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

2967:    Input Parameter:
2968: .  ts - the TS context obtained from TSCreate()

2970:    Output Parameter:
2971: .  ksp - the nonlinear solver context

2973:    Notes:
2974:    The user can then directly manipulate the KSP context to set various
2975:    options, etc.  Likewise, the user can then extract and manipulate the
2976:    KSP and PC contexts as well.

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

2981:    Level: beginner

2983: @*/
2984: PetscErrorCode  TSGetKSP(TS ts,KSP *ksp)
2985: {
2987:   SNES           snes;

2992:   if (!((PetscObject)ts)->type_name) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_NULL,"KSP is not created yet. Call TSSetType() first");
2993:   if (ts->problem_type != TS_LINEAR) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,"Linear only; use TSGetSNES()");
2994:   TSGetSNES(ts,&snes);
2995:   SNESGetKSP(snes,ksp);
2996:   return(0);
2997: }

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

3001: /*@
3002:    TSSetMaxSteps - Sets the maximum number of steps to use.

3004:    Logically Collective on TS

3006:    Input Parameters:
3007: +  ts - the TS context obtained from TSCreate()
3008: -  maxsteps - maximum number of steps to use

3010:    Options Database Keys:
3011: .  -ts_max_steps <maxsteps> - Sets maxsteps

3013:    Notes:
3014:    The default maximum number of steps is 5000

3016:    Level: intermediate

3018: .seealso: TSGetMaxSteps(), TSSetMaxTime(), TSSetExactFinalTime()
3019: @*/
3020: PetscErrorCode TSSetMaxSteps(TS ts,PetscInt maxsteps)
3021: {
3025:   if (maxsteps < 0) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_ARG_OUTOFRANGE,"Maximum number of steps must be non-negative");
3026:   ts->max_steps = maxsteps;
3027:   return(0);
3028: }

3030: /*@
3031:    TSGetMaxSteps - Gets the maximum number of steps to use.

3033:    Not Collective

3035:    Input Parameters:
3036: .  ts - the TS context obtained from TSCreate()

3038:    Output Parameter:
3039: .  maxsteps - maximum number of steps to use

3041:    Level: advanced

3043: .seealso: TSSetMaxSteps(), TSGetMaxTime(), TSSetMaxTime()
3044: @*/
3045: PetscErrorCode TSGetMaxSteps(TS ts,PetscInt *maxsteps)
3046: {
3050:   *maxsteps = ts->max_steps;
3051:   return(0);
3052: }

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

3057:    Logically Collective on TS

3059:    Input Parameters:
3060: +  ts - the TS context obtained from TSCreate()
3061: -  maxtime - final time to step to

3063:    Options Database Keys:
3064: .  -ts_max_time <maxtime> - Sets maxtime

3066:    Notes:
3067:    The default maximum time is 5.0

3069:    Level: intermediate

3071: .seealso: TSGetMaxTime(), TSSetMaxSteps(), TSSetExactFinalTime()
3072: @*/
3073: PetscErrorCode TSSetMaxTime(TS ts,PetscReal maxtime)
3074: {
3078:   ts->max_time = maxtime;
3079:   return(0);
3080: }

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

3085:    Not Collective

3087:    Input Parameters:
3088: .  ts - the TS context obtained from TSCreate()

3090:    Output Parameter:
3091: .  maxtime - final time to step to

3093:    Level: advanced

3095: .seealso: TSSetMaxTime(), TSGetMaxSteps(), TSSetMaxSteps()
3096: @*/
3097: PetscErrorCode TSGetMaxTime(TS ts,PetscReal *maxtime)
3098: {
3102:   *maxtime = ts->max_time;
3103:   return(0);
3104: }

3106: /*@
3107:    TSSetInitialTimeStep - Deprecated, use TSSetTime() and TSSetTimeStep().

3109:    Level: deprecated

3111: @*/
3112: PetscErrorCode  TSSetInitialTimeStep(TS ts,PetscReal initial_time,PetscReal time_step)
3113: {
3117:   TSSetTime(ts,initial_time);
3118:   TSSetTimeStep(ts,time_step);
3119:   return(0);
3120: }

3122: /*@
3123:    TSGetDuration - Deprecated, use TSGetMaxSteps() and TSGetMaxTime().

3125:    Level: deprecated

3127: @*/
3128: PetscErrorCode TSGetDuration(TS ts, PetscInt *maxsteps, PetscReal *maxtime)
3129: {
3132:   if (maxsteps) {
3134:     *maxsteps = ts->max_steps;
3135:   }
3136:   if (maxtime) {
3138:     *maxtime = ts->max_time;
3139:   }
3140:   return(0);
3141: }

3143: /*@
3144:    TSSetDuration - Deprecated, use TSSetMaxSteps() and TSSetMaxTime().

3146:    Level: deprecated

3148: @*/
3149: PetscErrorCode TSSetDuration(TS ts,PetscInt maxsteps,PetscReal maxtime)
3150: {
3155:   if (maxsteps >= 0) ts->max_steps = maxsteps;
3156:   if (maxtime != PETSC_DEFAULT) ts->max_time = maxtime;
3157:   return(0);
3158: }

3160: /*@
3161:    TSGetTimeStepNumber - Deprecated, use TSGetStepNumber().

3163:    Level: deprecated

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

3168: /*@
3169:    TSGetTotalSteps - Deprecated, use TSGetStepNumber().

3171:    Level: deprecated

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

3176: /*@
3177:    TSSetSolution - Sets the initial solution vector
3178:    for use by the TS routines.

3180:    Logically Collective on TS

3182:    Input Parameters:
3183: +  ts - the TS context obtained from TSCreate()
3184: -  u - the solution vector

3186:    Level: beginner

3188: .seealso: TSSetSolutionFunction(), TSGetSolution(), TSCreate()
3189: @*/
3190: PetscErrorCode  TSSetSolution(TS ts,Vec u)
3191: {
3193:   DM             dm;

3198:   PetscObjectReference((PetscObject)u);
3199:   VecDestroy(&ts->vec_sol);
3200:   ts->vec_sol = u;

3202:   TSGetDM(ts,&dm);
3203:   DMShellSetGlobalVector(dm,u);
3204:   return(0);
3205: }

3207: /*@C
3208:   TSSetPreStep - Sets the general-purpose function
3209:   called once at the beginning of each time step.

3211:   Logically Collective on TS

3213:   Input Parameters:
3214: + ts   - The TS context obtained from TSCreate()
3215: - func - The function

3217:   Calling sequence of func:
3218: .   PetscErrorCode func (TS ts);

3220:   Level: intermediate

3222: .seealso: TSSetPreStage(), TSSetPostStage(), TSSetPostStep(), TSStep(), TSRestartStep()
3223: @*/
3224: PetscErrorCode  TSSetPreStep(TS ts, PetscErrorCode (*func)(TS))
3225: {
3228:   ts->prestep = func;
3229:   return(0);
3230: }

3232: /*@
3233:   TSPreStep - Runs the user-defined pre-step function.

3235:   Collective on TS

3237:   Input Parameters:
3238: . ts   - The TS context obtained from TSCreate()

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

3244:   Level: developer

3246: .seealso: TSSetPreStep(), TSPreStage(), TSPostStage(), TSPostStep()
3247: @*/
3248: PetscErrorCode  TSPreStep(TS ts)
3249: {

3254:   if (ts->prestep) {
3255:     Vec              U;
3256:     PetscObjectState sprev,spost;

3258:     TSGetSolution(ts,&U);
3259:     PetscObjectStateGet((PetscObject)U,&sprev);
3260:     PetscStackCallStandard((*ts->prestep),(ts));
3261:     PetscObjectStateGet((PetscObject)U,&spost);
3262:     if (sprev != spost) {TSRestartStep(ts);}
3263:   }
3264:   return(0);
3265: }

3267: /*@C
3268:   TSSetPreStage - Sets the general-purpose function
3269:   called once at the beginning of each stage.

3271:   Logically Collective on TS

3273:   Input Parameters:
3274: + ts   - The TS context obtained from TSCreate()
3275: - func - The function

3277:   Calling sequence of func:
3278: .    PetscErrorCode func(TS ts, PetscReal stagetime);

3280:   Level: intermediate

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

3287: .seealso: TSSetPostStage(), TSSetPreStep(), TSSetPostStep(), TSGetApplicationContext()
3288: @*/
3289: PetscErrorCode  TSSetPreStage(TS ts, PetscErrorCode (*func)(TS,PetscReal))
3290: {
3293:   ts->prestage = func;
3294:   return(0);
3295: }

3297: /*@C
3298:   TSSetPostStage - Sets the general-purpose function
3299:   called once at the end of each stage.

3301:   Logically Collective on TS

3303:   Input Parameters:
3304: + ts   - The TS context obtained from TSCreate()
3305: - func - The function

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

3310:   Level: intermediate

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

3317: .seealso: TSSetPreStage(), TSSetPreStep(), TSSetPostStep(), TSGetApplicationContext()
3318: @*/
3319: PetscErrorCode  TSSetPostStage(TS ts, PetscErrorCode (*func)(TS,PetscReal,PetscInt,Vec*))
3320: {
3323:   ts->poststage = func;
3324:   return(0);
3325: }

3327: /*@C
3328:   TSSetPostEvaluate - Sets the general-purpose function
3329:   called once at the end of each step evaluation.

3331:   Logically Collective on TS

3333:   Input Parameters:
3334: + ts   - The TS context obtained from TSCreate()
3335: - func - The function

3337:   Calling sequence of func:
3338: . PetscErrorCode func(TS ts);

3340:   Level: intermediate

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

3349: .seealso: TSSetPreStage(), TSSetPreStep(), TSSetPostStep(), TSGetApplicationContext()
3350: @*/
3351: PetscErrorCode  TSSetPostEvaluate(TS ts, PetscErrorCode (*func)(TS))
3352: {
3355:   ts->postevaluate = func;
3356:   return(0);
3357: }

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

3362:   Collective on TS

3364:   Input Parameters:
3365: . ts          - The TS context obtained from TSCreate()
3366:   stagetime   - The absolute time of the current stage

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

3372:   Level: developer

3374: .seealso: TSPostStage(), TSSetPreStep(), TSPreStep(), TSPostStep()
3375: @*/
3376: PetscErrorCode  TSPreStage(TS ts, PetscReal stagetime)
3377: {
3380:   if (ts->prestage) {
3381:     PetscStackCallStandard((*ts->prestage),(ts,stagetime));
3382:   }
3383:   return(0);
3384: }

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

3389:   Collective on TS

3391:   Input Parameters:
3392: . ts          - The TS context obtained from TSCreate()
3393:   stagetime   - The absolute time of the current stage
3394:   stageindex  - Stage number
3395:   Y           - Array of vectors (of size = total number
3396:                 of stages) with the stage solutions

3398:   Notes:
3399:   TSPostStage() is typically used within time stepping implementations,
3400:   most users would not generally call this routine themselves.

3402:   Level: developer

3404: .seealso: TSPreStage(), TSSetPreStep(), TSPreStep(), TSPostStep()
3405: @*/
3406: PetscErrorCode  TSPostStage(TS ts, PetscReal stagetime, PetscInt stageindex, Vec *Y)
3407: {
3410:   if (ts->poststage) {
3411:     PetscStackCallStandard((*ts->poststage),(ts,stagetime,stageindex,Y));
3412:   }
3413:   return(0);
3414: }

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

3419:   Collective on TS

3421:   Input Parameters:
3422: . ts          - The TS context obtained from TSCreate()

3424:   Notes:
3425:   TSPostEvaluate() is typically used within time stepping implementations,
3426:   most users would not generally call this routine themselves.

3428:   Level: developer

3430: .seealso: TSSetPostEvaluate(), TSSetPreStep(), TSPreStep(), TSPostStep()
3431: @*/
3432: PetscErrorCode  TSPostEvaluate(TS ts)
3433: {

3438:   if (ts->postevaluate) {
3439:     Vec              U;
3440:     PetscObjectState sprev,spost;

3442:     TSGetSolution(ts,&U);
3443:     PetscObjectStateGet((PetscObject)U,&sprev);
3444:     PetscStackCallStandard((*ts->postevaluate),(ts));
3445:     PetscObjectStateGet((PetscObject)U,&spost);
3446:     if (sprev != spost) {TSRestartStep(ts);}
3447:   }
3448:   return(0);
3449: }

3451: /*@C
3452:   TSSetPostStep - Sets the general-purpose function
3453:   called once at the end of each time step.

3455:   Logically Collective on TS

3457:   Input Parameters:
3458: + ts   - The TS context obtained from TSCreate()
3459: - func - The function

3461:   Calling sequence of func:
3462: $ func (TS ts);

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

3469:   Level: intermediate

3471: .seealso: TSSetPreStep(), TSSetPreStage(), TSSetPostEvaluate(), TSGetTimeStep(), TSGetStepNumber(), TSGetTime(), TSRestartStep()
3472: @*/
3473: PetscErrorCode  TSSetPostStep(TS ts, PetscErrorCode (*func)(TS))
3474: {
3477:   ts->poststep = func;
3478:   return(0);
3479: }

3481: /*@
3482:   TSPostStep - Runs the user-defined post-step function.

3484:   Collective on TS

3486:   Input Parameters:
3487: . ts   - The TS context obtained from TSCreate()

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

3493:   Level: developer

3495: @*/
3496: PetscErrorCode  TSPostStep(TS ts)
3497: {

3502:   if (ts->poststep) {
3503:     Vec              U;
3504:     PetscObjectState sprev,spost;

3506:     TSGetSolution(ts,&U);
3507:     PetscObjectStateGet((PetscObject)U,&sprev);
3508:     PetscStackCallStandard((*ts->poststep),(ts));
3509:     PetscObjectStateGet((PetscObject)U,&spost);
3510:     if (sprev != spost) {TSRestartStep(ts);}
3511:   }
3512:   return(0);
3513: }

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

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

3521:    Logically Collective on TS

3523:    Input Parameters:
3524: +  ts - the TS context obtained from TSCreate()
3525: .  monitor - monitoring routine
3526: .  mctx - [optional] user-defined context for private data for the
3527:              monitor routine (use NULL if no context is desired)
3528: -  monitordestroy - [optional] routine that frees monitor context
3529:           (may be NULL)

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

3534: +    ts - the TS context
3535: .    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)
3536: .    time - current time
3537: .    u - current iterate
3538: -    mctx - [optional] monitoring context

3540:    Notes:
3541:    This routine adds an additional monitor to the list of monitors that
3542:    already has been loaded.

3544:    Fortran Notes:
3545:     Only a single monitor function can be set for each TS object

3547:    Level: intermediate

3549: .seealso: TSMonitorDefault(), TSMonitorCancel()
3550: @*/
3551: PetscErrorCode  TSMonitorSet(TS ts,PetscErrorCode (*monitor)(TS,PetscInt,PetscReal,Vec,void*),void *mctx,PetscErrorCode (*mdestroy)(void**))
3552: {
3554:   PetscInt       i;
3555:   PetscBool      identical;

3559:   for (i=0; i<ts->numbermonitors;i++) {
3560:     PetscMonitorCompare((PetscErrorCode (*)(void))monitor,mctx,mdestroy,(PetscErrorCode (*)(void))ts->monitor[i],ts->monitorcontext[i],ts->monitordestroy[i],&identical);
3561:     if (identical) return(0);
3562:   }
3563:   if (ts->numbermonitors >= MAXTSMONITORS) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Too many monitors set");
3564:   ts->monitor[ts->numbermonitors]          = monitor;
3565:   ts->monitordestroy[ts->numbermonitors]   = mdestroy;
3566:   ts->monitorcontext[ts->numbermonitors++] = (void*)mctx;
3567:   return(0);
3568: }

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

3573:    Logically Collective on TS

3575:    Input Parameters:
3576: .  ts - the TS context obtained from TSCreate()

3578:    Notes:
3579:    There is no way to remove a single, specific monitor.

3581:    Level: intermediate

3583: .seealso: TSMonitorDefault(), TSMonitorSet()
3584: @*/
3585: PetscErrorCode  TSMonitorCancel(TS ts)
3586: {
3588:   PetscInt       i;

3592:   for (i=0; i<ts->numbermonitors; i++) {
3593:     if (ts->monitordestroy[i]) {
3594:       (*ts->monitordestroy[i])(&ts->monitorcontext[i]);
3595:     }
3596:   }
3597:   ts->numbermonitors = 0;
3598:   return(0);
3599: }

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

3604:    Level: intermediate

3606: .seealso:  TSMonitorSet()
3607: @*/
3608: PetscErrorCode TSMonitorDefault(TS ts,PetscInt step,PetscReal ptime,Vec v,PetscViewerAndFormat *vf)
3609: {
3611:   PetscViewer    viewer =  vf->viewer;
3612:   PetscBool      iascii,ibinary;

3616:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERASCII,&iascii);
3617:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERBINARY,&ibinary);
3618:   PetscViewerPushFormat(viewer,vf->format);
3619:   if (iascii) {
3620:     PetscViewerASCIIAddTab(viewer,((PetscObject)ts)->tablevel);
3621:     if (step == -1){ /* this indicates it is an interpolated solution */
3622:       PetscViewerASCIIPrintf(viewer,"Interpolated solution at time %g between steps %D and %D\n",(double)ptime,ts->steps-1,ts->steps);
3623:     } else {
3624:       PetscViewerASCIIPrintf(viewer,"%D TS dt %g time %g%s",step,(double)ts->time_step,(double)ptime,ts->steprollback ? " (r)\n" : "\n");
3625:     }
3626:     PetscViewerASCIISubtractTab(viewer,((PetscObject)ts)->tablevel);
3627:   } else if (ibinary) {
3628:     PetscMPIInt rank;
3629:     MPI_Comm_rank(PetscObjectComm((PetscObject)viewer),&rank);
3630:     if (!rank) {
3631:       PetscBool skipHeader;
3632:       PetscInt  classid = REAL_FILE_CLASSID;

3634:       PetscViewerBinaryGetSkipHeader(viewer,&skipHeader);
3635:       if (!skipHeader) {
3636:          PetscViewerBinaryWrite(viewer,&classid,1,PETSC_INT);
3637:        }
3638:       PetscRealView(1,&ptime,viewer);
3639:     } else {
3640:       PetscRealView(0,&ptime,viewer);
3641:     }
3642:   }
3643:   PetscViewerPopFormat(viewer);
3644:   return(0);
3645: }

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

3650:    Level: intermediate

3652: .seealso:  TSMonitorSet()
3653: @*/
3654: PetscErrorCode TSMonitorExtreme(TS ts,PetscInt step,PetscReal ptime,Vec v,PetscViewerAndFormat *vf)
3655: {
3657:   PetscViewer    viewer =  vf->viewer;
3658:   PetscBool      iascii;
3659:   PetscReal      max,min;


3664:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERASCII,&iascii);
3665:   PetscViewerPushFormat(viewer,vf->format);
3666:   if (iascii) {
3667:     VecMax(v,NULL,&max);
3668:     VecMin(v,NULL,&min);
3669:     PetscViewerASCIIAddTab(viewer,((PetscObject)ts)->tablevel);
3670:     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);
3671:     PetscViewerASCIISubtractTab(viewer,((PetscObject)ts)->tablevel);
3672:   }
3673:   PetscViewerPopFormat(viewer);
3674:   return(0);
3675: }

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

3680:    Collective on TS

3682:    Input Argument:
3683: +  ts - time stepping context
3684: -  t - time to interpolate to

3686:    Output Argument:
3687: .  U - state at given time

3689:    Level: intermediate

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

3694: .seealso: TSSetExactFinalTime(), TSSolve()
3695: @*/
3696: PetscErrorCode TSInterpolate(TS ts,PetscReal t,Vec U)
3697: {

3703:   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);
3704:   if (!ts->ops->interpolate) SETERRQ1(PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"%s does not provide interpolation",((PetscObject)ts)->type_name);
3705:   (*ts->ops->interpolate)(ts,t,U);
3706:   return(0);
3707: }

3709: /*@
3710:    TSStep - Steps one time step

3712:    Collective on TS

3714:    Input Parameter:
3715: .  ts - the TS context obtained from TSCreate()

3717:    Level: developer

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

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

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

3728: .seealso: TSCreate(), TSSetUp(), TSDestroy(), TSSolve(), TSSetPreStep(), TSSetPreStage(), TSSetPostStage(), TSInterpolate()
3729: @*/
3730: PetscErrorCode  TSStep(TS ts)
3731: {
3732:   PetscErrorCode   ierr;
3733:   static PetscBool cite = PETSC_FALSE;
3734:   PetscReal        ptime;

3738:   PetscCitationsRegister("@article{tspaper,\n"
3739:                                 "  title         = {{PETSc/TS}: A Modern Scalable {DAE/ODE} Solver Library},\n"
3740:                                 "  author        = {Abhyankar, Shrirang and Brown, Jed and Constantinescu, Emil and Ghosh, Debojyoti and Smith, Barry F. and Zhang, Hong},\n"
3741:                                 "  journal       = {arXiv e-preprints},\n"
3742:                                 "  eprint        = {1806.01437},\n"
3743:                                 "  archivePrefix = {arXiv},\n"
3744:                                 "  year          = {2018}\n}\n",&cite);

3746:   TSSetUp(ts);
3747:   TSTrajectorySetUp(ts->trajectory,ts);

3749:   if (!ts->ops->step) SETERRQ1(PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"TSStep not implemented for type '%s'",((PetscObject)ts)->type_name);
3750:   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>");
3751:   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()");
3752:   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");

3754:   if (!ts->steps) ts->ptime_prev = ts->ptime;
3755:   ptime = ts->ptime; ts->ptime_prev_rollback = ts->ptime_prev;
3756:   ts->reason = TS_CONVERGED_ITERATING;

3758:   PetscLogEventBegin(TS_Step,ts,0,0,0);
3759:   (*ts->ops->step)(ts);
3760:   PetscLogEventEnd(TS_Step,ts,0,0,0);

3762:   if (ts->reason >= 0) {
3763:     ts->ptime_prev = ptime;
3764:     ts->steps++;
3765:     ts->steprollback = PETSC_FALSE;
3766:     ts->steprestart  = PETSC_FALSE;
3767:   }

3769:   if (!ts->reason) {
3770:     if (ts->steps >= ts->max_steps) ts->reason = TS_CONVERGED_ITS;
3771:     else if (ts->ptime >= ts->max_time) ts->reason = TS_CONVERGED_TIME;
3772:   }

3774:   if (ts->reason < 0 && ts->errorifstepfailed && 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]);
3775:   if (ts->reason < 0 && ts->errorifstepfailed) SETERRQ1(PetscObjectComm((PetscObject)ts),PETSC_ERR_NOT_CONVERGED,"TSStep has failed due to %s",TSConvergedReasons[ts->reason]);
3776:   return(0);
3777: }

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

3783:    Collective on TS

3785:    Input Arguments:
3786: +  ts - time stepping context
3787: .  wnormtype - norm type, either NORM_2 or NORM_INFINITY
3788: -  order - optional, desired order for the error evaluation or PETSC_DECIDE

3790:    Output Arguments:
3791: +  order - optional, the actual order of the error evaluation
3792: -  wlte - the weighted local truncation error norm

3794:    Level: advanced

3796:    Notes:
3797:    If the timestepper cannot evaluate the error in a particular step
3798:    (eg. in the first step or restart steps after event handling),
3799:    this routine returns wlte=-1.0 .

3801: .seealso: TSStep(), TSAdapt, TSErrorWeightedNorm()
3802: @*/
3803: PetscErrorCode TSEvaluateWLTE(TS ts,NormType wnormtype,PetscInt *order,PetscReal *wlte)
3804: {

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

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

3823:    Collective on TS

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

3830:    Output Arguments:
3831: .  U - state at the end of the current step

3833:    Level: advanced

3835:    Notes:
3836:    This function cannot be called until all stages have been evaluated.
3837:    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.

3839: .seealso: TSStep(), TSAdapt
3840: @*/
3841: PetscErrorCode TSEvaluateStep(TS ts,PetscInt order,Vec U,PetscBool *done)
3842: {

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

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

3857:   Not collective

3859:   Input Argument:
3860: . ts        - time stepping context

3862:   Output Argument:
3863: . initConditions - The function which computes an initial condition

3865:    Level: advanced

3867:    Notes:
3868:    The calling sequence for the function is
3869: $ initCondition(TS ts, Vec u)
3870: $ ts - The timestepping context
3871: $ u  - The input vector in which the initial condition is stored

3873: .seealso: TSSetComputeInitialCondition(), TSComputeInitialCondition()
3874: @*/
3875: PetscErrorCode TSGetComputeInitialCondition(TS ts, PetscErrorCode (**initCondition)(TS, Vec))
3876: {
3880:   *initCondition = ts->ops->initcondition;
3881:   return(0);
3882: }

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

3887:   Logically collective on ts

3889:   Input Arguments:
3890: + ts        - time stepping context
3891: - initCondition - The function which computes an initial condition

3893:   Level: advanced

3895:   Calling sequence for initCondition:
3896: $ PetscErrorCode initCondition(TS ts, Vec u)

3898: + ts - The timestepping context
3899: - u  - The input vector in which the initial condition is to be stored

3901: .seealso: TSGetComputeInitialCondition(), TSComputeInitialCondition()
3902: @*/
3903: PetscErrorCode TSSetComputeInitialCondition(TS ts, PetscErrorCode (*initCondition)(TS, Vec))
3904: {
3908:   ts->ops->initcondition = initCondition;
3909:   return(0);
3910: }

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

3915:   Collective on ts

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

3921:   Level: advanced

3923: .seealso: TSGetComputeInitialCondition(), TSSetComputeInitialCondition(), TSSolve()
3924: @*/
3925: PetscErrorCode TSComputeInitialCondition(TS ts, Vec u)
3926: {

3932:   if (ts->ops->initcondition) {(*ts->ops->initcondition)(ts, u);}
3933:   return(0);
3934: }

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

3939:   Not collective

3941:   Input Argument:
3942: . ts         - time stepping context

3944:   Output Argument:
3945: . exactError - The function which computes the solution error

3947:   Level: advanced

3949:   Calling sequence for exactError:
3950: $ PetscErrorCode exactError(TS ts, Vec u)

3952: + ts - The timestepping context
3953: . u  - The approximate solution vector
3954: - e  - The input vector in which the error is stored

3956: .seealso: TSGetComputeExactError(), TSComputeExactError()
3957: @*/
3958: PetscErrorCode TSGetComputeExactError(TS ts, PetscErrorCode (**exactError)(TS, Vec, Vec))
3959: {
3963:   *exactError = ts->ops->exacterror;
3964:   return(0);
3965: }

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

3970:   Logically collective on ts

3972:   Input Arguments:
3973: + ts         - time stepping context
3974: - exactError - The function which computes the solution error

3976:   Level: advanced

3978:   Calling sequence for exactError:
3979: $ PetscErrorCode exactError(TS ts, Vec u)

3981: + ts - The timestepping context
3982: . u  - The approximate solution vector
3983: - e  - The input vector in which the error is stored

3985: .seealso: TSGetComputeExactError(), TSComputeExactError()
3986: @*/
3987: PetscErrorCode TSSetComputeExactError(TS ts, PetscErrorCode (*exactError)(TS, Vec, Vec))
3988: {
3992:   ts->ops->exacterror = exactError;
3993:   return(0);
3994: }

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

3999:   Collective on ts

4001:   Input Arguments:
4002: + ts - time stepping context
4003: . u  - The approximate solution
4004: - e  - The Vec used to store the error

4006:   Level: advanced

4008: .seealso: TSGetComputeInitialCondition(), TSSetComputeInitialCondition(), TSSolve()
4009: @*/
4010: PetscErrorCode TSComputeExactError(TS ts, Vec u, Vec e)
4011: {

4018:   if (ts->ops->exacterror) {(*ts->ops->exacterror)(ts, u, e);}
4019:   return(0);
4020: }

4022: /*@
4023:    TSSolve - Steps the requested number of timesteps.

4025:    Collective on TS

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

4032:    Level: beginner

4034:    Notes:
4035:    The final time returned by this function may be different from the time of the internally
4036:    held state accessible by TSGetSolution() and TSGetTime() because the method may have
4037:    stepped over the final time.

4039: .seealso: TSCreate(), TSSetSolution(), TSStep(), TSGetTime(), TSGetSolveTime()
4040: @*/
4041: PetscErrorCode TSSolve(TS ts,Vec u)
4042: {
4043:   Vec               solution;
4044:   PetscErrorCode    ierr;


4050:   TSSetExactFinalTimeDefault(ts);
4051:   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 */
4052:     if (!ts->vec_sol || u == ts->vec_sol) {
4053:       VecDuplicate(u,&solution);
4054:       TSSetSolution(ts,solution);
4055:       VecDestroy(&solution); /* grant ownership */
4056:     }
4057:     VecCopy(u,ts->vec_sol);
4058:     if (ts->forward_solve) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"Sensitivity analysis does not support the mode TS_EXACTFINALTIME_INTERPOLATE");
4059:   } else if (u) {
4060:     TSSetSolution(ts,u);
4061:   }
4062:   TSSetUp(ts);
4063:   TSTrajectorySetUp(ts->trajectory,ts);

4065:   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>");
4066:   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()");
4067:   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");

4069:   if (ts->forward_solve) {
4070:     TSForwardSetUp(ts);
4071:   }

4073:   /* reset number of steps only when the step is not restarted. ARKIMEX
4074:      restarts the step after an event. Resetting these counters in such case causes
4075:      TSTrajectory to incorrectly save the output files
4076:   */
4077:   /* reset time step and iteration counters */
4078:   if (!ts->steps) {
4079:     ts->ksp_its           = 0;
4080:     ts->snes_its          = 0;
4081:     ts->num_snes_failures = 0;
4082:     ts->reject            = 0;
4083:     ts->steprestart       = PETSC_TRUE;
4084:     ts->steprollback      = PETSC_FALSE;
4085:     ts->rhsjacobian.time  = PETSC_MIN_REAL;
4086:   }

4088:   /* make sure initial time step does not overshoot final time */
4089:   if (ts->exact_final_time == TS_EXACTFINALTIME_MATCHSTEP) {
4090:     PetscReal maxdt = ts->max_time-ts->ptime;
4091:     PetscReal dt = ts->time_step;

4093:     ts->time_step = dt >= maxdt ? maxdt : (PetscIsCloseAtTol(dt,maxdt,10*PETSC_MACHINE_EPSILON,0) ? maxdt : dt);
4094:   }
4095:   ts->reason = TS_CONVERGED_ITERATING;

4097:   {
4098:     PetscViewer       viewer;
4099:     PetscViewerFormat format;
4100:     PetscBool         flg;
4101:     static PetscBool  incall = PETSC_FALSE;

4103:     if (!incall) {
4104:       /* Estimate the convergence rate of the time discretization */
4105:       PetscOptionsGetViewer(PetscObjectComm((PetscObject) ts),((PetscObject)ts)->options, ((PetscObject) ts)->prefix, "-ts_convergence_estimate", &viewer, &format, &flg);
4106:       if (flg) {
4107:         PetscConvEst conv;
4108:         DM           dm;
4109:         PetscReal   *alpha; /* Convergence rate of the solution error for each field in the L_2 norm */
4110:         PetscInt     Nf;
4111:         PetscBool    checkTemporal = PETSC_TRUE;

4113:         incall = PETSC_TRUE;
4114:         PetscOptionsGetBool(((PetscObject)ts)->options, ((PetscObject) ts)->prefix, "-ts_convergence_temporal", &checkTemporal, &flg);
4115:         TSGetDM(ts, &dm);
4116:         DMGetNumFields(dm, &Nf);
4117:         PetscCalloc1(PetscMax(Nf, 1), &alpha);
4118:         PetscConvEstCreate(PetscObjectComm((PetscObject) ts), &conv);
4119:         PetscConvEstUseTS(conv, checkTemporal);
4120:         PetscConvEstSetSolver(conv, (PetscObject) ts);
4121:         PetscConvEstSetFromOptions(conv);
4122:         PetscConvEstSetUp(conv);
4123:         PetscConvEstGetConvRate(conv, alpha);
4124:         PetscViewerPushFormat(viewer, format);
4125:         PetscConvEstRateView(conv, alpha, viewer);
4126:         PetscViewerPopFormat(viewer);
4127:         PetscViewerDestroy(&viewer);
4128:         PetscConvEstDestroy(&conv);
4129:         PetscFree(alpha);
4130:         incall = PETSC_FALSE;
4131:       }
4132:     }
4133:   }

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

4137:   if (ts->ops->solve) { /* This private interface is transitional and should be removed when all implementations are updated. */
4138:     (*ts->ops->solve)(ts);
4139:     if (u) {VecCopy(ts->vec_sol,u);}
4140:     ts->solvetime = ts->ptime;
4141:     solution = ts->vec_sol;
4142:   } else { /* Step the requested number of timesteps. */
4143:     if (ts->steps >= ts->max_steps) ts->reason = TS_CONVERGED_ITS;
4144:     else if (ts->ptime >= ts->max_time) ts->reason = TS_CONVERGED_TIME;

4146:     if (!ts->steps) {
4147:       TSTrajectorySet(ts->trajectory,ts,ts->steps,ts->ptime,ts->vec_sol);
4148:       TSEventInitialize(ts->event,ts,ts->ptime,ts->vec_sol);
4149:     }

4151:     while (!ts->reason) {
4152:       TSMonitor(ts,ts->steps,ts->ptime,ts->vec_sol);
4153:       if (!ts->steprollback) {
4154:         TSPreStep(ts);
4155:       }
4156:       TSStep(ts);
4157:       if (ts->testjacobian) {
4158:         TSRHSJacobianTest(ts,NULL);
4159:       }
4160:       if (ts->testjacobiantranspose) {
4161:         TSRHSJacobianTestTranspose(ts,NULL);
4162:       }
4163:       if (ts->quadraturets && ts->costintegralfwd) { /* Must evaluate the cost integral before event is handled. The cost integral value can also be rolled back. */
4164:         if (ts->reason >= 0) ts->steps--; /* Revert the step number changed by TSStep() */
4165:         TSForwardCostIntegral(ts);
4166:         if (ts->reason >= 0) ts->steps++;
4167:       }
4168:       if (ts->forward_solve) { /* compute forward sensitivities before event handling because postevent() may change RHS and jump conditions may have to be applied */
4169:         if (ts->reason >= 0) ts->steps--; /* Revert the step number changed by TSStep() */
4170:         TSForwardStep(ts);
4171:         if (ts->reason >= 0) ts->steps++;
4172:       }
4173:       TSPostEvaluate(ts);
4174:       TSEventHandler(ts); /* The right-hand side may be changed due to event. Be careful with Any computation using the RHS information after this point. */
4175:       if (ts->steprollback) {
4176:         TSPostEvaluate(ts);
4177:       }
4178:       if (!ts->steprollback) {
4179:         TSTrajectorySet(ts->trajectory,ts,ts->steps,ts->ptime,ts->vec_sol);
4180:         TSPostStep(ts);
4181:       }
4182:     }
4183:     TSMonitor(ts,ts->steps,ts->ptime,ts->vec_sol);

4185:     if (ts->exact_final_time == TS_EXACTFINALTIME_INTERPOLATE && ts->ptime > ts->max_time) {
4186:       TSInterpolate(ts,ts->max_time,u);
4187:       ts->solvetime = ts->max_time;
4188:       solution = u;
4189:       TSMonitor(ts,-1,ts->solvetime,solution);
4190:     } else {
4191:       if (u) {VecCopy(ts->vec_sol,u);}
4192:       ts->solvetime = ts->ptime;
4193:       solution = ts->vec_sol;
4194:     }
4195:   }

4197:   TSViewFromOptions(ts,NULL,"-ts_view");
4198:   VecViewFromOptions(solution,NULL,"-ts_view_solution");
4199:   PetscObjectSAWsBlock((PetscObject)ts);
4200:   if (ts->adjoint_solve) {
4201:     TSAdjointSolve(ts);
4202:   }
4203:   return(0);
4204: }

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

4209:    Collective on TS

4211:    Input Parameters:
4212: +  ts - time stepping context obtained from TSCreate()
4213: .  step - step number that has just completed
4214: .  ptime - model time of the state
4215: -  u - state at the current model time

4217:    Notes:
4218:    TSMonitor() is typically used automatically within the time stepping implementations.
4219:    Users would almost never call this routine directly.

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

4223:    Level: developer

4225: @*/
4226: PetscErrorCode TSMonitor(TS ts,PetscInt step,PetscReal ptime,Vec u)
4227: {
4228:   DM             dm;
4229:   PetscInt       i,n = ts->numbermonitors;


4236:   TSGetDM(ts,&dm);
4237:   DMSetOutputSequenceNumber(dm,step,ptime);

4239:   VecLockReadPush(u);
4240:   for (i=0; i<n; i++) {
4241:     (*ts->monitor[i])(ts,step,ptime,u,ts->monitorcontext[i]);
4242:   }
4243:   VecLockReadPop(u);
4244:   return(0);
4245: }

4247: /* ------------------------------------------------------------------------*/
4248: /*@C
4249:    TSMonitorLGCtxCreate - Creates a TSMonitorLGCtx context for use with
4250:    TS to monitor the solution process graphically in various ways

4252:    Collective on TS

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

4261:    Output Parameter:
4262: .  ctx - the context

4264:    Options Database Key:
4265: +  -ts_monitor_lg_timestep - automatically sets line graph monitor
4266: +  -ts_monitor_lg_timestep_log - automatically sets line graph monitor
4267: .  -ts_monitor_lg_solution - monitor the solution (or certain values of the solution by calling TSMonitorLGSetDisplayVariables() or TSMonitorLGCtxSetDisplayVariables())
4268: .  -ts_monitor_lg_error -  monitor the error
4269: .  -ts_monitor_lg_ksp_iterations - monitor the number of KSP iterations needed for each timestep
4270: .  -ts_monitor_lg_snes_iterations - monitor the number of SNES iterations needed for each timestep
4271: -  -lg_use_markers <true,false> - mark the data points (at each time step) on the plot; default is true

4273:    Notes:
4274:    Use TSMonitorLGCtxDestroy() to destroy.

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

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

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

4284:    Level: intermediate

4286: .seealso: TSMonitorLGTimeStep(), TSMonitorSet(), TSMonitorLGSolution(), TSMonitorLGError(), TSMonitorDefault(), VecView(),
4287:            TSMonitorLGCtxCreate(), TSMonitorLGCtxSetVariableNames(), TSMonitorLGCtxGetVariableNames(),
4288:            TSMonitorLGSetVariableNames(), TSMonitorLGGetVariableNames(), TSMonitorLGSetDisplayVariables(), TSMonitorLGCtxSetDisplayVariables(),
4289:            TSMonitorLGCtxSetTransform(), TSMonitorLGSetTransform(), TSMonitorLGError(), TSMonitorLGSNESIterations(), TSMonitorLGKSPIterations(),
4290:            TSMonitorEnvelopeCtxCreate(), TSMonitorEnvelopeGetBounds(), TSMonitorEnvelopeCtxDestroy(), TSMonitorEnvelop()

4292: @*/
4293: PetscErrorCode  TSMonitorLGCtxCreate(MPI_Comm comm,const char host[],const char label[],int x,int y,int m,int n,PetscInt howoften,TSMonitorLGCtx *ctx)
4294: {
4295:   PetscDraw      draw;

4299:   PetscNew(ctx);
4300:   PetscDrawCreate(comm,host,label,x,y,m,n,&draw);
4301:   PetscDrawSetFromOptions(draw);
4302:   PetscDrawLGCreate(draw,1,&(*ctx)->lg);
4303:   PetscDrawLGSetFromOptions((*ctx)->lg);
4304:   PetscDrawDestroy(&draw);
4305:   (*ctx)->howoften = howoften;
4306:   return(0);
4307: }

4309: PetscErrorCode TSMonitorLGTimeStep(TS ts,PetscInt step,PetscReal ptime,Vec v,void *monctx)
4310: {
4311:   TSMonitorLGCtx ctx = (TSMonitorLGCtx) monctx;
4312:   PetscReal      x   = ptime,y;

4316:   if (step < 0) return(0); /* -1 indicates an interpolated solution */
4317:   if (!step) {
4318:     PetscDrawAxis axis;
4319:     const char *ylabel = ctx->semilogy ? "Log Time Step" : "Time Step";
4320:     PetscDrawLGGetAxis(ctx->lg,&axis);
4321:     PetscDrawAxisSetLabels(axis,"Timestep as function of time","Time",ylabel);
4322:     PetscDrawLGReset(ctx->lg);
4323:   }
4324:   TSGetTimeStep(ts,&y);
4325:   if (ctx->semilogy) y = PetscLog10Real(y);
4326:   PetscDrawLGAddPoint(ctx->lg,&x,&y);
4327:   if (((ctx->howoften > 0) && (!(step % ctx->howoften))) || ((ctx->howoften == -1) && ts->reason)) {
4328:     PetscDrawLGDraw(ctx->lg);
4329:     PetscDrawLGSave(ctx->lg);
4330:   }
4331:   return(0);
4332: }

4334: /*@C
4335:    TSMonitorLGCtxDestroy - Destroys a line graph context that was created
4336:    with TSMonitorLGCtxCreate().

4338:    Collective on TSMonitorLGCtx

4340:    Input Parameter:
4341: .  ctx - the monitor context

4343:    Level: intermediate

4345: .seealso: TSMonitorLGCtxCreate(),  TSMonitorSet(), TSMonitorLGTimeStep();
4346: @*/
4347: PetscErrorCode  TSMonitorLGCtxDestroy(TSMonitorLGCtx *ctx)
4348: {

4352:   if ((*ctx)->transformdestroy) {
4353:     ((*ctx)->transformdestroy)((*ctx)->transformctx);
4354:   }
4355:   PetscDrawLGDestroy(&(*ctx)->lg);
4356:   PetscStrArrayDestroy(&(*ctx)->names);
4357:   PetscStrArrayDestroy(&(*ctx)->displaynames);
4358:   PetscFree((*ctx)->displayvariables);
4359:   PetscFree((*ctx)->displayvalues);
4360:   PetscFree(*ctx);
4361:   return(0);
4362: }

4364: /*

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

4368: */
4369: PetscErrorCode TSMonitorSPCtxCreate(MPI_Comm comm,const char host[],const char label[],int x,int y,int m,int n,PetscInt howoften,TSMonitorSPCtx *ctx)
4370: {
4371:   PetscDraw      draw;

4375:   PetscNew(ctx);
4376:   PetscDrawCreate(comm,host,label,x,y,m,n,&draw);
4377:   PetscDrawSetFromOptions(draw);
4378:   PetscDrawSPCreate(draw,1,&(*ctx)->sp);
4379:   PetscDrawDestroy(&draw);
4380:   (*ctx)->howoften = howoften;
4381:   return(0);

4383: }

4385: /*
4386:   Destroys a TSMonitorSPCtx that was created with TSMonitorSPCtxCreate
4387: */
4388: PetscErrorCode TSMonitorSPCtxDestroy(TSMonitorSPCtx *ctx)
4389: {


4394:   PetscDrawSPDestroy(&(*ctx)->sp);
4395:   PetscFree(*ctx);

4397:   return(0);

4399: }

4401: /*@
4402:    TSGetTime - Gets the time of the most recently completed step.

4404:    Not Collective

4406:    Input Parameter:
4407: .  ts - the TS context obtained from TSCreate()

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

4412:    Level: beginner

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

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

4420: @*/
4421: PetscErrorCode  TSGetTime(TS ts,PetscReal *t)
4422: {
4426:   *t = ts->ptime;
4427:   return(0);
4428: }

4430: /*@
4431:    TSGetPrevTime - Gets the starting time of the previously completed step.

4433:    Not Collective

4435:    Input Parameter:
4436: .  ts - the TS context obtained from TSCreate()

4438:    Output Parameter:
4439: .  t  - the previous time

4441:    Level: beginner

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

4445: @*/
4446: PetscErrorCode  TSGetPrevTime(TS ts,PetscReal *t)
4447: {
4451:   *t = ts->ptime_prev;
4452:   return(0);
4453: }

4455: /*@
4456:    TSSetTime - Allows one to reset the time.

4458:    Logically Collective on TS

4460:    Input Parameters:
4461: +  ts - the TS context obtained from TSCreate()
4462: -  time - the time

4464:    Level: intermediate

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

4468: @*/
4469: PetscErrorCode  TSSetTime(TS ts, PetscReal t)
4470: {
4474:   ts->ptime = t;
4475:   return(0);
4476: }

4478: /*@C
4479:    TSSetOptionsPrefix - Sets the prefix used for searching for all
4480:    TS options in the database.

4482:    Logically Collective on TS

4484:    Input Parameter:
4485: +  ts     - The TS context
4486: -  prefix - The prefix to prepend to all option names

4488:    Notes:
4489:    A hyphen (-) must NOT be given at the beginning of the prefix name.
4490:    The first character of all runtime options is AUTOMATICALLY the
4491:    hyphen.

4493:    Level: advanced

4495: .seealso: TSSetFromOptions()

4497: @*/
4498: PetscErrorCode  TSSetOptionsPrefix(TS ts,const char prefix[])
4499: {
4501:   SNES           snes;

4505:   PetscObjectSetOptionsPrefix((PetscObject)ts,prefix);
4506:   TSGetSNES(ts,&snes);
4507:   SNESSetOptionsPrefix(snes,prefix);
4508:   return(0);
4509: }

4511: /*@C
4512:    TSAppendOptionsPrefix - Appends to the prefix used for searching for all
4513:    TS options in the database.

4515:    Logically Collective on TS

4517:    Input Parameter:
4518: +  ts     - The TS context
4519: -  prefix - The prefix to prepend to all option names

4521:    Notes:
4522:    A hyphen (-) must NOT be given at the beginning of the prefix name.
4523:    The first character of all runtime options is AUTOMATICALLY the
4524:    hyphen.

4526:    Level: advanced

4528: .seealso: TSGetOptionsPrefix()

4530: @*/
4531: PetscErrorCode  TSAppendOptionsPrefix(TS ts,const char prefix[])
4532: {
4534:   SNES           snes;

4538:   PetscObjectAppendOptionsPrefix((PetscObject)ts,prefix);
4539:   TSGetSNES(ts,&snes);
4540:   SNESAppendOptionsPrefix(snes,prefix);
4541:   return(0);
4542: }

4544: /*@C
4545:    TSGetOptionsPrefix - Sets the prefix used for searching for all
4546:    TS options in the database.

4548:    Not Collective

4550:    Input Parameter:
4551: .  ts - The TS context

4553:    Output Parameter:
4554: .  prefix - A pointer to the prefix string used

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

4560:    Level: intermediate

4562: .seealso: TSAppendOptionsPrefix()
4563: @*/
4564: PetscErrorCode  TSGetOptionsPrefix(TS ts,const char *prefix[])
4565: {

4571:   PetscObjectGetOptionsPrefix((PetscObject)ts,prefix);
4572:   return(0);
4573: }

4575: /*@C
4576:    TSGetRHSJacobian - Returns the Jacobian J at the present timestep.

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

4580:    Input Parameter:
4581: .  ts  - The TS context obtained from TSCreate()

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

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

4592:    Level: intermediate

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

4596: @*/
4597: PetscErrorCode  TSGetRHSJacobian(TS ts,Mat *Amat,Mat *Pmat,TSRHSJacobian *func,void **ctx)
4598: {
4600:   DM             dm;

4603:   if (Amat || Pmat) {
4604:     SNES snes;
4605:     TSGetSNES(ts,&snes);
4606:     SNESSetUpMatrices(snes);
4607:     SNESGetJacobian(snes,Amat,Pmat,NULL,NULL);
4608:   }
4609:   TSGetDM(ts,&dm);
4610:   DMTSGetRHSJacobian(dm,func,ctx);
4611:   return(0);
4612: }

4614: /*@C
4615:    TSGetIJacobian - Returns the implicit Jacobian at the present timestep.

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

4619:    Input Parameter:
4620: .  ts  - The TS context obtained from TSCreate()

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

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

4631:    Level: advanced

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

4635: @*/
4636: PetscErrorCode  TSGetIJacobian(TS ts,Mat *Amat,Mat *Pmat,TSIJacobian *f,void **ctx)
4637: {
4639:   DM             dm;

4642:   if (Amat || Pmat) {
4643:     SNES snes;
4644:     TSGetSNES(ts,&snes);
4645:     SNESSetUpMatrices(snes);
4646:     SNESGetJacobian(snes,Amat,Pmat,NULL,NULL);
4647:   }
4648:   TSGetDM(ts,&dm);
4649:   DMTSGetIJacobian(dm,f,ctx);
4650:   return(0);
4651: }

4653: /*@C
4654:    TSMonitorDrawSolution - Monitors progress of the TS solvers by calling
4655:    VecView() for the solution at each timestep

4657:    Collective on TS

4659:    Input Parameters:
4660: +  ts - the TS context
4661: .  step - current time-step
4662: .  ptime - current time
4663: -  dummy - either a viewer or NULL

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

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

4672:    Level: intermediate

4674: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView()
4675: @*/
4676: PetscErrorCode  TSMonitorDrawSolution(TS ts,PetscInt step,PetscReal ptime,Vec u,void *dummy)
4677: {
4678:   PetscErrorCode   ierr;
4679:   TSMonitorDrawCtx ictx = (TSMonitorDrawCtx)dummy;
4680:   PetscDraw        draw;

4683:   if (!step && ictx->showinitial) {
4684:     if (!ictx->initialsolution) {
4685:       VecDuplicate(u,&ictx->initialsolution);
4686:     }
4687:     VecCopy(u,ictx->initialsolution);
4688:   }
4689:   if (!(((ictx->howoften > 0) && (!(step % ictx->howoften))) || ((ictx->howoften == -1) && ts->reason))) return(0);

4691:   if (ictx->showinitial) {
4692:     PetscReal pause;
4693:     PetscViewerDrawGetPause(ictx->viewer,&pause);
4694:     PetscViewerDrawSetPause(ictx->viewer,0.0);
4695:     VecView(ictx->initialsolution,ictx->viewer);
4696:     PetscViewerDrawSetPause(ictx->viewer,pause);
4697:     PetscViewerDrawSetHold(ictx->viewer,PETSC_TRUE);
4698:   }
4699:   VecView(u,ictx->viewer);
4700:   if (ictx->showtimestepandtime) {
4701:     PetscReal xl,yl,xr,yr,h;
4702:     char      time[32];

4704:     PetscViewerDrawGetDraw(ictx->viewer,0,&draw);
4705:     PetscSNPrintf(time,32,"Timestep %d Time %g",(int)step,(double)ptime);
4706:     PetscDrawGetCoordinates(draw,&xl,&yl,&xr,&yr);
4707:     h    = yl + .95*(yr - yl);
4708:     PetscDrawStringCentered(draw,.5*(xl+xr),h,PETSC_DRAW_BLACK,time);
4709:     PetscDrawFlush(draw);
4710:   }

4712:   if (ictx->showinitial) {
4713:     PetscViewerDrawSetHold(ictx->viewer,PETSC_FALSE);
4714:   }
4715:   return(0);
4716: }

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

4721:    Collective on TS

4723:    Input Parameters:
4724: +  ts - the TS context
4725: .  step - current time-step
4726: .  ptime - current time
4727: -  dummy - either a viewer or NULL

4729:    Level: intermediate

4731: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView()
4732: @*/
4733: PetscErrorCode  TSMonitorDrawSolutionPhase(TS ts,PetscInt step,PetscReal ptime,Vec u,void *dummy)
4734: {
4735:   PetscErrorCode    ierr;
4736:   TSMonitorDrawCtx  ictx = (TSMonitorDrawCtx)dummy;
4737:   PetscDraw         draw;
4738:   PetscDrawAxis     axis;
4739:   PetscInt          n;
4740:   PetscMPIInt       size;
4741:   PetscReal         U0,U1,xl,yl,xr,yr,h;
4742:   char              time[32];
4743:   const PetscScalar *U;

4746:   MPI_Comm_size(PetscObjectComm((PetscObject)ts),&size);
4747:   if (size != 1) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"Only allowed for sequential runs");
4748:   VecGetSize(u,&n);
4749:   if (n != 2) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"Only for ODEs with two unknowns");

4751:   PetscViewerDrawGetDraw(ictx->viewer,0,&draw);
4752:   PetscViewerDrawGetDrawAxis(ictx->viewer,0,&axis);
4753:   PetscDrawAxisGetLimits(axis,&xl,&xr,&yl,&yr);
4754:   if (!step) {
4755:     PetscDrawClear(draw);
4756:     PetscDrawAxisDraw(axis);
4757:   }

4759:   VecGetArrayRead(u,&U);
4760:   U0 = PetscRealPart(U[0]);
4761:   U1 = PetscRealPart(U[1]);
4762:   VecRestoreArrayRead(u,&U);
4763:   if ((U0 < xl) || (U1 < yl) || (U0 > xr) || (U1 > yr)) return(0);

4765:   PetscDrawCollectiveBegin(draw);
4766:   PetscDrawPoint(draw,U0,U1,PETSC_DRAW_BLACK);
4767:   if (ictx->showtimestepandtime) {
4768:     PetscDrawGetCoordinates(draw,&xl,&yl,&xr,&yr);
4769:     PetscSNPrintf(time,32,"Timestep %d Time %g",(int)step,(double)ptime);
4770:     h    = yl + .95*(yr - yl);
4771:     PetscDrawStringCentered(draw,.5*(xl+xr),h,PETSC_DRAW_BLACK,time);
4772:   }
4773:   PetscDrawCollectiveEnd(draw);
4774:   PetscDrawFlush(draw);
4775:   PetscDrawPause(draw);
4776:   PetscDrawSave(draw);
4777:   return(0);
4778: }

4780: /*@C
4781:    TSMonitorDrawCtxDestroy - Destroys the monitor context for TSMonitorDrawSolution()

4783:    Collective on TS

4785:    Input Parameters:
4786: .    ctx - the monitor context

4788:    Level: intermediate

4790: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorDrawSolution(), TSMonitorDrawError()
4791: @*/
4792: PetscErrorCode  TSMonitorDrawCtxDestroy(TSMonitorDrawCtx *ictx)
4793: {

4797:   PetscViewerDestroy(&(*ictx)->viewer);
4798:   VecDestroy(&(*ictx)->initialsolution);
4799:   PetscFree(*ictx);
4800:   return(0);
4801: }

4803: /*@C
4804:    TSMonitorDrawCtxCreate - Creates the monitor context for TSMonitorDrawCtx

4806:    Collective on TS

4808:    Input Parameter:
4809: .    ts - time-step context

4811:    Output Patameter:
4812: .    ctx - the monitor context

4814:    Options Database:
4815: .   -ts_monitor_draw_solution_initial - show initial solution as well as current solution

4817:    Level: intermediate

4819: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorDrawCtx()
4820: @*/
4821: PetscErrorCode  TSMonitorDrawCtxCreate(MPI_Comm comm,const char host[],const char label[],int x,int y,int m,int n,PetscInt howoften,TSMonitorDrawCtx *ctx)
4822: {
4823:   PetscErrorCode   ierr;

4826:   PetscNew(ctx);
4827:   PetscViewerDrawOpen(comm,host,label,x,y,m,n,&(*ctx)->viewer);
4828:   PetscViewerSetFromOptions((*ctx)->viewer);

4830:   (*ctx)->howoften    = howoften;
4831:   (*ctx)->showinitial = PETSC_FALSE;
4832:   PetscOptionsGetBool(NULL,NULL,"-ts_monitor_draw_solution_initial",&(*ctx)->showinitial,NULL);

4834:   (*ctx)->showtimestepandtime = PETSC_FALSE;
4835:   PetscOptionsGetBool(NULL,NULL,"-ts_monitor_draw_solution_show_time",&(*ctx)->showtimestepandtime,NULL);
4836:   return(0);
4837: }

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

4843:    Collective on TS

4845:    Input Parameters:
4846: +  ts - the TS context
4847: .  step - current time-step
4848: .  ptime - current time
4849: -  dummy - either a viewer or NULL

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

4854:    Level: intermediate

4856: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSSetSolutionFunction()
4857: @*/
4858: PetscErrorCode  TSMonitorDrawSolutionFunction(TS ts,PetscInt step,PetscReal ptime,Vec u,void *dummy)
4859: {
4860:   PetscErrorCode   ierr;
4861:   TSMonitorDrawCtx ctx    = (TSMonitorDrawCtx)dummy;
4862:   PetscViewer      viewer = ctx->viewer;
4863:   Vec              work;

4866:   if (!(((ctx->howoften > 0) && (!(step % ctx->howoften))) || ((ctx->howoften == -1) && ts->reason))) return(0);
4867:   VecDuplicate(u,&work);
4868:   TSComputeSolutionFunction(ts,ptime,work);
4869:   VecView(work,viewer);
4870:   VecDestroy(&work);
4871:   return(0);
4872: }

4874: /*@C
4875:    TSMonitorDrawError - Monitors progress of the TS solvers by calling
4876:    VecView() for the error at each timestep

4878:    Collective on TS

4880:    Input Parameters:
4881: +  ts - the TS context
4882: .  step - current time-step
4883: .  ptime - current time
4884: -  dummy - either a viewer or NULL

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

4889:    Level: intermediate

4891: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSSetSolutionFunction()
4892: @*/
4893: PetscErrorCode  TSMonitorDrawError(TS ts,PetscInt step,PetscReal ptime,Vec u,void *dummy)
4894: {
4895:   PetscErrorCode   ierr;
4896:   TSMonitorDrawCtx ctx    = (TSMonitorDrawCtx)dummy;
4897:   PetscViewer      viewer = ctx->viewer;
4898:   Vec              work;

4901:   if (!(((ctx->howoften > 0) && (!(step % ctx->howoften))) || ((ctx->howoften == -1) && ts->reason))) return(0);
4902:   VecDuplicate(u,&work);
4903:   TSComputeSolutionFunction(ts,ptime,work);
4904:   VecAXPY(work,-1.0,u);
4905:   VecView(work,viewer);
4906:   VecDestroy(&work);
4907:   return(0);
4908: }

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

4914:    Logically Collective on ts

4916:    Input Parameters:
4917: +  ts - the ODE integrator object
4918: -  dm - the dm, cannot be NULL

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

4925:    Level: intermediate

4927: .seealso: TSGetDM(), SNESSetDM(), SNESGetDM()
4928: @*/
4929: PetscErrorCode  TSSetDM(TS ts,DM dm)
4930: {
4932:   SNES           snes;
4933:   DMTS           tsdm;

4938:   PetscObjectReference((PetscObject)dm);
4939:   if (ts->dm) {               /* Move the DMTS context over to the new DM unless the new DM already has one */
4940:     if (ts->dm->dmts && !dm->dmts) {
4941:       DMCopyDMTS(ts->dm,dm);
4942:       DMGetDMTS(ts->dm,&tsdm);
4943:       if (tsdm->originaldm == ts->dm) { /* Grant write privileges to the replacement DM */
4944:         tsdm->originaldm = dm;
4945:       }
4946:     }
4947:     DMDestroy(&ts->dm);
4948:   }
4949:   ts->dm = dm;

4951:   TSGetSNES(ts,&snes);
4952:   SNESSetDM(snes,dm);
4953:   return(0);
4954: }

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

4959:    Not Collective

4961:    Input Parameter:
4962: . ts - the preconditioner context

4964:    Output Parameter:
4965: .  dm - the dm

4967:    Level: intermediate

4969: .seealso: TSSetDM(), SNESSetDM(), SNESGetDM()
4970: @*/
4971: PetscErrorCode  TSGetDM(TS ts,DM *dm)
4972: {

4977:   if (!ts->dm) {
4978:     DMShellCreate(PetscObjectComm((PetscObject)ts),&ts->dm);
4979:     if (ts->snes) {SNESSetDM(ts->snes,ts->dm);}
4980:   }
4981:   *dm = ts->dm;
4982:   return(0);
4983: }

4985: /*@
4986:    SNESTSFormFunction - Function to evaluate nonlinear residual

4988:    Logically Collective on SNES

4990:    Input Parameter:
4991: + snes - nonlinear solver
4992: . U - the current state at which to evaluate the residual
4993: - ctx - user context, must be a TS

4995:    Output Parameter:
4996: . F - the nonlinear residual

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

5002:    Level: advanced

5004: .seealso: SNESSetFunction(), MatFDColoringSetFunction()
5005: @*/
5006: PetscErrorCode  SNESTSFormFunction(SNES snes,Vec U,Vec F,void *ctx)
5007: {
5008:   TS             ts = (TS)ctx;

5016:   (ts->ops->snesfunction)(snes,U,F,ts);
5017:   return(0);
5018: }

5020: /*@
5021:    SNESTSFormJacobian - Function to evaluate the Jacobian

5023:    Collective on SNES

5025:    Input Parameter:
5026: + snes - nonlinear solver
5027: . U - the current state at which to evaluate the residual
5028: - ctx - user context, must be a TS

5030:    Output Parameter:
5031: + A - the Jacobian
5032: . B - the preconditioning matrix (may be the same as A)
5033: - flag - indicates any structure change in the matrix

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

5038:    Level: developer

5040: .seealso: SNESSetJacobian()
5041: @*/
5042: PetscErrorCode  SNESTSFormJacobian(SNES snes,Vec U,Mat A,Mat B,void *ctx)
5043: {
5044:   TS             ts = (TS)ctx;

5055:   (ts->ops->snesjacobian)(snes,U,A,B,ts);
5056:   return(0);
5057: }

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

5062:    Collective on TS

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

5070:    Output Arguments:
5071: .  F - right hand side

5073:    Level: intermediate

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

5079: .seealso: TSSetRHSFunction(), TSSetRHSJacobian(), TSComputeRHSJacobianConstant()
5080: @*/
5081: PetscErrorCode TSComputeRHSFunctionLinear(TS ts,PetscReal t,Vec U,Vec F,void *ctx)
5082: {
5084:   Mat            Arhs,Brhs;

5087:   TSGetRHSMats_Private(ts,&Arhs,&Brhs);
5088:   /* undo the damage caused by shifting */
5089:   TSRecoverRHSJacobian(ts,Arhs,Brhs);
5090:   TSComputeRHSJacobian(ts,t,U,Arhs,Brhs);
5091:   MatMult(Arhs,U,F);
5092:   return(0);
5093: }

5095: /*@C
5096:    TSComputeRHSJacobianConstant - Reuses a Jacobian that is time-independent.

5098:    Collective on TS

5100:    Input Arguments:
5101: +  ts - time stepping context
5102: .  t - time at which to evaluate
5103: .  U - state at which to evaluate
5104: -  ctx - context

5106:    Output Arguments:
5107: +  A - pointer to operator
5108: .  B - pointer to preconditioning matrix
5109: -  flg - matrix structure flag

5111:    Level: intermediate

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

5116: .seealso: TSSetRHSFunction(), TSSetRHSJacobian(), TSComputeRHSFunctionLinear()
5117: @*/
5118: PetscErrorCode TSComputeRHSJacobianConstant(TS ts,PetscReal t,Vec U,Mat A,Mat B,void *ctx)
5119: {
5121:   return(0);
5122: }

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

5127:    Collective on TS

5129:    Input Arguments:
5130: +  ts - time stepping context
5131: .  t - time at which to evaluate
5132: .  U - state at which to evaluate
5133: .  Udot - time derivative of state vector
5134: -  ctx - context

5136:    Output Arguments:
5137: .  F - left hand side

5139:    Level: intermediate

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

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

5149: .seealso: TSSetIFunction(), TSSetIJacobian(), TSComputeIJacobianConstant(), TSComputeRHSFunctionLinear()
5150: @*/
5151: PetscErrorCode TSComputeIFunctionLinear(TS ts,PetscReal t,Vec U,Vec Udot,Vec F,void *ctx)
5152: {
5154:   Mat            A,B;

5157:   TSGetIJacobian(ts,&A,&B,NULL,NULL);
5158:   TSComputeIJacobian(ts,t,U,Udot,1.0,A,B,PETSC_TRUE);
5159:   MatMult(A,Udot,F);
5160:   return(0);
5161: }

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

5166:    Collective on TS

5168:    Input Arguments:
5169: +  ts - time stepping context
5170: .  t - time at which to evaluate
5171: .  U - state at which to evaluate
5172: .  Udot - time derivative of state vector
5173: .  shift - shift to apply
5174: -  ctx - context

5176:    Output Arguments:
5177: +  A - pointer to operator
5178: .  B - pointer to preconditioning matrix
5179: -  flg - matrix structure flag

5181:    Level: advanced

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

5186:    It is only appropriate for problems of the form

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

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

5194: $    shift*M + J

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

5199: .seealso: TSSetIFunction(), TSSetIJacobian(), TSComputeIFunctionLinear()
5200: @*/
5201: PetscErrorCode TSComputeIJacobianConstant(TS ts,PetscReal t,Vec U,Vec Udot,PetscReal shift,Mat A,Mat B,void *ctx)
5202: {

5206:   MatScale(A, shift / ts->ijacobian.shift);
5207:   ts->ijacobian.shift = shift;
5208:   return(0);
5209: }

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

5214:    Not Collective

5216:    Input Parameter:
5217: .  ts - the TS context

5219:    Output Parameter:
5220: .  equation_type - see TSEquationType

5222:    Level: beginner

5224: .seealso: TSSetEquationType(), TSEquationType
5225: @*/
5226: PetscErrorCode  TSGetEquationType(TS ts,TSEquationType *equation_type)
5227: {
5231:   *equation_type = ts->equation_type;
5232:   return(0);
5233: }

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

5238:    Not Collective

5240:    Input Parameter:
5241: +  ts - the TS context
5242: -  equation_type - see TSEquationType

5244:    Level: advanced

5246: .seealso: TSGetEquationType(), TSEquationType
5247: @*/
5248: PetscErrorCode  TSSetEquationType(TS ts,TSEquationType equation_type)
5249: {
5252:   ts->equation_type = equation_type;
5253:   return(0);
5254: }

5256: /*@
5257:    TSGetConvergedReason - Gets the reason the TS iteration was stopped.

5259:    Not Collective

5261:    Input Parameter:
5262: .  ts - the TS context

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

5268:    Level: beginner

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

5273: .seealso: TSSetConvergenceTest(), TSConvergedReason
5274: @*/
5275: PetscErrorCode  TSGetConvergedReason(TS ts,TSConvergedReason *reason)
5276: {
5280:   *reason = ts->reason;
5281:   return(0);
5282: }

5284: /*@
5285:    TSSetConvergedReason - Sets the reason for handling the convergence of TSSolve.

5287:    Logically Collective; reason must contain common value

5289:    Input Parameters:
5290: +  ts - the TS context
5291: -  reason - negative value indicates diverged, positive value converged, see TSConvergedReason or the
5292:             manual pages for the individual convergence tests for complete lists

5294:    Level: advanced

5296:    Notes:
5297:    Can only be called while TSSolve() is active.

5299: .seealso: TSConvergedReason
5300: @*/
5301: PetscErrorCode  TSSetConvergedReason(TS ts,TSConvergedReason reason)
5302: {
5305:   ts->reason = reason;
5306:   return(0);
5307: }

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

5312:    Not Collective

5314:    Input Parameter:
5315: .  ts - the TS context

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

5320:    Level: beginner

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

5325: .seealso: TSSetConvergenceTest(), TSConvergedReason
5326: @*/
5327: PetscErrorCode  TSGetSolveTime(TS ts,PetscReal *ftime)
5328: {
5332:   *ftime = ts->solvetime;
5333:   return(0);
5334: }

5336: /*@
5337:    TSGetSNESIterations - Gets the total number of nonlinear iterations
5338:    used by the time integrator.

5340:    Not Collective

5342:    Input Parameter:
5343: .  ts - TS context

5345:    Output Parameter:
5346: .  nits - number of nonlinear iterations

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

5351:    Level: intermediate

5353: .seealso:  TSGetKSPIterations()
5354: @*/
5355: PetscErrorCode TSGetSNESIterations(TS ts,PetscInt *nits)
5356: {
5360:   *nits = ts->snes_its;
5361:   return(0);
5362: }

5364: /*@
5365:    TSGetKSPIterations - Gets the total number of linear iterations
5366:    used by the time integrator.

5368:    Not Collective

5370:    Input Parameter:
5371: .  ts - TS context

5373:    Output Parameter:
5374: .  lits - number of linear iterations

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

5379:    Level: intermediate

5381: .seealso:  TSGetSNESIterations(), SNESGetKSPIterations()
5382: @*/
5383: PetscErrorCode TSGetKSPIterations(TS ts,PetscInt *lits)
5384: {
5388:   *lits = ts->ksp_its;
5389:   return(0);
5390: }

5392: /*@
5393:    TSGetStepRejections - Gets the total number of rejected steps.

5395:    Not Collective

5397:    Input Parameter:
5398: .  ts - TS context

5400:    Output Parameter:
5401: .  rejects - number of steps rejected

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

5406:    Level: intermediate

5408: .seealso:  TSGetSNESIterations(), TSGetKSPIterations(), TSSetMaxStepRejections(), TSGetSNESFailures(), TSSetMaxSNESFailures(), TSSetErrorIfStepFails()
5409: @*/
5410: PetscErrorCode TSGetStepRejections(TS ts,PetscInt *rejects)
5411: {
5415:   *rejects = ts->reject;
5416:   return(0);
5417: }

5419: /*@
5420:    TSGetSNESFailures - Gets the total number of failed SNES solves

5422:    Not Collective

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

5427:    Output Parameter:
5428: .  fails - number of failed nonlinear solves

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

5433:    Level: intermediate

5435: .seealso:  TSGetSNESIterations(), TSGetKSPIterations(), TSSetMaxStepRejections(), TSGetStepRejections(), TSSetMaxSNESFailures()
5436: @*/
5437: PetscErrorCode TSGetSNESFailures(TS ts,PetscInt *fails)
5438: {
5442:   *fails = ts->num_snes_failures;
5443:   return(0);
5444: }

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

5449:    Not Collective

5451:    Input Parameter:
5452: +  ts - TS context
5453: -  rejects - maximum number of rejected steps, pass -1 for unlimited

5455:    Notes:
5456:    The counter is reset to zero for each step

5458:    Options Database Key:
5459:  .  -ts_max_reject - Maximum number of step rejections before a step fails

5461:    Level: intermediate

5463: .seealso:  TSGetSNESIterations(), TSGetKSPIterations(), TSSetMaxSNESFailures(), TSGetStepRejections(), TSGetSNESFailures(), TSSetErrorIfStepFails(), TSGetConvergedReason()
5464: @*/
5465: PetscErrorCode TSSetMaxStepRejections(TS ts,PetscInt rejects)
5466: {
5469:   ts->max_reject = rejects;
5470:   return(0);
5471: }

5473: /*@
5474:    TSSetMaxSNESFailures - Sets the maximum number of failed SNES solves

5476:    Not Collective

5478:    Input Parameter:
5479: +  ts - TS context
5480: -  fails - maximum number of failed nonlinear solves, pass -1 for unlimited

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

5485:    Options Database Key:
5486:  .  -ts_max_snes_failures - Maximum number of nonlinear solve failures

5488:    Level: intermediate

5490: .seealso:  TSGetSNESIterations(), TSGetKSPIterations(), TSSetMaxStepRejections(), TSGetStepRejections(), TSGetSNESFailures(), SNESGetConvergedReason(), TSGetConvergedReason()
5491: @*/
5492: PetscErrorCode TSSetMaxSNESFailures(TS ts,PetscInt fails)
5493: {
5496:   ts->max_snes_failures = fails;
5497:   return(0);
5498: }

5500: /*@
5501:    TSSetErrorIfStepFails - Error if no step succeeds

5503:    Not Collective

5505:    Input Parameter:
5506: +  ts - TS context
5507: -  err - PETSC_TRUE to error if no step succeeds, PETSC_FALSE to return without failure

5509:    Options Database Key:
5510:  .  -ts_error_if_step_fails - Error if no step succeeds

5512:    Level: intermediate

5514: .seealso:  TSGetSNESIterations(), TSGetKSPIterations(), TSSetMaxStepRejections(), TSGetStepRejections(), TSGetSNESFailures(), TSSetErrorIfStepFails(), TSGetConvergedReason()
5515: @*/
5516: PetscErrorCode TSSetErrorIfStepFails(TS ts,PetscBool err)
5517: {
5520:   ts->errorifstepfailed = err;
5521:   return(0);
5522: }

5524: /*@C
5525:    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

5527:    Collective on TS

5529:    Input Parameters:
5530: +  ts - the TS context
5531: .  step - current time-step
5532: .  ptime - current time
5533: .  u - current state
5534: -  vf - viewer and its format

5536:    Level: intermediate

5538: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView()
5539: @*/
5540: PetscErrorCode  TSMonitorSolution(TS ts,PetscInt step,PetscReal ptime,Vec u,PetscViewerAndFormat *vf)
5541: {

5545:   PetscViewerPushFormat(vf->viewer,vf->format);
5546:   VecView(u,vf->viewer);
5547:   PetscViewerPopFormat(vf->viewer);
5548:   return(0);
5549: }

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

5554:    Collective on TS

5556:    Input Parameters:
5557: +  ts - the TS context
5558: .  step - current time-step
5559: .  ptime - current time
5560: .  u - current state
5561: -  filenametemplate - string containing a format specifier for the integer time step (e.g. %03D)

5563:    Level: intermediate

5565:    Notes:
5566:    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.
5567:    These are named according to the file name template.

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

5571: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView()
5572: @*/
5573: PetscErrorCode TSMonitorSolutionVTK(TS ts,PetscInt step,PetscReal ptime,Vec u,void *filenametemplate)
5574: {
5576:   char           filename[PETSC_MAX_PATH_LEN];
5577:   PetscViewer    viewer;

5580:   if (step < 0) return(0); /* -1 indicates interpolated solution */
5581:   PetscSNPrintf(filename,sizeof(filename),(const char*)filenametemplate,step);
5582:   PetscViewerVTKOpen(PetscObjectComm((PetscObject)ts),filename,FILE_MODE_WRITE,&viewer);
5583:   VecView(u,viewer);
5584:   PetscViewerDestroy(&viewer);
5585:   return(0);
5586: }

5588: /*@C
5589:    TSMonitorSolutionVTKDestroy - Destroy context for monitoring

5591:    Collective on TS

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

5596:    Level: intermediate

5598:    Note:
5599:    This function is normally passed to TSMonitorSet() along with TSMonitorSolutionVTK().

5601: .seealso: TSMonitorSet(), TSMonitorSolutionVTK()
5602: @*/
5603: PetscErrorCode TSMonitorSolutionVTKDestroy(void *filenametemplate)
5604: {

5608:   PetscFree(*(char**)filenametemplate);
5609:   return(0);
5610: }

5612: /*@
5613:    TSGetAdapt - Get the adaptive controller context for the current method

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

5617:    Input Arguments:
5618: .  ts - time stepping context

5620:    Output Arguments:
5621: .  adapt - adaptive controller

5623:    Level: intermediate

5625: .seealso: TSAdapt, TSAdaptSetType(), TSAdaptChoose()
5626: @*/
5627: PetscErrorCode TSGetAdapt(TS ts,TSAdapt *adapt)
5628: {

5634:   if (!ts->adapt) {
5635:     TSAdaptCreate(PetscObjectComm((PetscObject)ts),&ts->adapt);
5636:     PetscLogObjectParent((PetscObject)ts,(PetscObject)ts->adapt);
5637:     PetscObjectIncrementTabLevel((PetscObject)ts->adapt,(PetscObject)ts,1);
5638:   }
5639:   *adapt = ts->adapt;
5640:   return(0);
5641: }

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

5646:    Logically Collective

5648:    Input Arguments:
5649: +  ts - time integration context
5650: .  atol - scalar absolute tolerances, PETSC_DECIDE to leave current value
5651: .  vatol - vector of absolute tolerances or NULL, used in preference to atol if present
5652: .  rtol - scalar relative tolerances, PETSC_DECIDE to leave current value
5653: -  vrtol - vector of relative tolerances or NULL, used in preference to atol if present

5655:    Options Database keys:
5656: +  -ts_rtol <rtol> - relative tolerance for local truncation error
5657: -  -ts_atol <atol> Absolute tolerance for local truncation error

5659:    Notes:
5660:    With PETSc's implicit schemes for DAE problems, the calculation of the local truncation error
5661:    (LTE) includes both the differential and the algebraic variables. If one wants the LTE to be
5662:    computed only for the differential or the algebraic part then this can be done using the vector of
5663:    tolerances vatol. For example, by setting the tolerance vector with the desired tolerance for the
5664:    differential part and infinity for the algebraic part, the LTE calculation will include only the
5665:    differential variables.

5667:    Level: beginner

5669: .seealso: TS, TSAdapt, TSErrorWeightedNorm(), TSGetTolerances()
5670: @*/
5671: PetscErrorCode TSSetTolerances(TS ts,PetscReal atol,Vec vatol,PetscReal rtol,Vec vrtol)
5672: {

5676:   if (atol != PETSC_DECIDE && atol != PETSC_DEFAULT) ts->atol = atol;
5677:   if (vatol) {
5678:     PetscObjectReference((PetscObject)vatol);
5679:     VecDestroy(&ts->vatol);
5680:     ts->vatol = vatol;
5681:   }
5682:   if (rtol != PETSC_DECIDE && rtol != PETSC_DEFAULT) ts->rtol = rtol;
5683:   if (vrtol) {
5684:     PetscObjectReference((PetscObject)vrtol);
5685:     VecDestroy(&ts->vrtol);
5686:     ts->vrtol = vrtol;
5687:   }
5688:   return(0);
5689: }

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

5694:    Logically Collective

5696:    Input Arguments:
5697: .  ts - time integration context

5699:    Output Arguments:
5700: +  atol - scalar absolute tolerances, NULL to ignore
5701: .  vatol - vector of absolute tolerances, NULL to ignore
5702: .  rtol - scalar relative tolerances, NULL to ignore
5703: -  vrtol - vector of relative tolerances, NULL to ignore

5705:    Level: beginner

5707: .seealso: TS, TSAdapt, TSErrorWeightedNorm(), TSSetTolerances()
5708: @*/
5709: PetscErrorCode TSGetTolerances(TS ts,PetscReal *atol,Vec *vatol,PetscReal *rtol,Vec *vrtol)
5710: {
5712:   if (atol)  *atol  = ts->atol;
5713:   if (vatol) *vatol = ts->vatol;
5714:   if (rtol)  *rtol  = ts->rtol;
5715:   if (vrtol) *vrtol = ts->vrtol;
5716:   return(0);
5717: }

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

5722:    Collective on TS

5724:    Input Arguments:
5725: +  ts - time stepping context
5726: .  U - state vector, usually ts->vec_sol
5727: -  Y - state vector to be compared to U

5729:    Output Arguments:
5730: +  norm - weighted norm, a value of 1.0 means that the error matches the tolerances
5731: .  norma - weighted norm based on the absolute tolerance, a value of 1.0 means that the error matches the tolerances
5732: -  normr - weighted norm based on the relative tolerance, a value of 1.0 means that the error matches the tolerances

5734:    Level: developer

5736: .seealso: TSErrorWeightedNorm(), TSErrorWeightedNormInfinity()
5737: @*/
5738: PetscErrorCode TSErrorWeightedNorm2(TS ts,Vec U,Vec Y,PetscReal *norm,PetscReal *norma,PetscReal *normr)
5739: {
5740:   PetscErrorCode    ierr;
5741:   PetscInt          i,n,N,rstart;
5742:   PetscInt          n_loc,na_loc,nr_loc;
5743:   PetscReal         n_glb,na_glb,nr_glb;
5744:   const PetscScalar *u,*y;
5745:   PetscReal         sum,suma,sumr,gsum,gsuma,gsumr,diff;
5746:   PetscReal         tol,tola,tolr;
5747:   PetscReal         err_loc[6],err_glb[6];

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

5761:   VecGetSize(U,&N);
5762:   VecGetLocalSize(U,&n);
5763:   VecGetOwnershipRange(U,&rstart,NULL);
5764:   VecGetArrayRead(U,&u);
5765:   VecGetArrayRead(Y,&y);
5766:   sum  = 0.; n_loc  = 0;
5767:   suma = 0.; na_loc = 0;
5768:   sumr = 0.; nr_loc = 0;
5769:   if (ts->vatol && ts->vrtol) {
5770:     const PetscScalar *atol,*rtol;
5771:     VecGetArrayRead(ts->vatol,&atol);
5772:     VecGetArrayRead(ts->vrtol,&rtol);
5773:     for (i=0; i<n; i++) {
5774:       SkipSmallValue(y[i],u[i],ts->adapt->ignore_max);
5775:       diff = PetscAbsScalar(y[i] - u[i]);
5776:       tola = PetscRealPart(atol[i]);
5777:       if (tola>0.){
5778:         suma  += PetscSqr(diff/tola);
5779:         na_loc++;
5780:       }
5781:       tolr = PetscRealPart(rtol[i]) * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
5782:       if (tolr>0.){
5783:         sumr  += PetscSqr(diff/tolr);
5784:         nr_loc++;
5785:       }
5786:       tol=tola+tolr;
5787:       if (tol>0.){
5788:         sum  += PetscSqr(diff/tol);
5789:         n_loc++;
5790:       }
5791:     }
5792:     VecRestoreArrayRead(ts->vatol,&atol);
5793:     VecRestoreArrayRead(ts->vrtol,&rtol);
5794:   } else if (ts->vatol) {       /* vector atol, scalar rtol */
5795:     const PetscScalar *atol;
5796:     VecGetArrayRead(ts->vatol,&atol);
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:       if (tola>0.){
5802:         suma  += PetscSqr(diff/tola);
5803:         na_loc++;
5804:       }
5805:       tolr = ts->rtol * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
5806:       if (tolr>0.){
5807:         sumr  += PetscSqr(diff/tolr);
5808:         nr_loc++;
5809:       }
5810:       tol=tola+tolr;
5811:       if (tol>0.){
5812:         sum  += PetscSqr(diff/tol);
5813:         n_loc++;
5814:       }
5815:     }
5816:     VecRestoreArrayRead(ts->vatol,&atol);
5817:   } else if (ts->vrtol) {       /* scalar atol, vector rtol */
5818:     const PetscScalar *rtol;
5819:     VecGetArrayRead(ts->vrtol,&rtol);
5820:     for (i=0; i<n; i++) {
5821:       SkipSmallValue(y[i],u[i],ts->adapt->ignore_max);
5822:       diff = PetscAbsScalar(y[i] - u[i]);
5823:       tola = ts->atol;
5824:       if (tola>0.){
5825:         suma  += PetscSqr(diff/tola);
5826:         na_loc++;
5827:       }
5828:       tolr = PetscRealPart(rtol[i]) * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
5829:       if (tolr>0.){
5830:         sumr  += PetscSqr(diff/tolr);
5831:         nr_loc++;
5832:       }
5833:       tol=tola+tolr;
5834:       if (tol>0.){
5835:         sum  += PetscSqr(diff/tol);
5836:         n_loc++;
5837:       }
5838:     }
5839:     VecRestoreArrayRead(ts->vrtol,&rtol);
5840:   } else {                      /* scalar atol, scalar rtol */
5841:     for (i=0; i<n; i++) {
5842:       SkipSmallValue(y[i],u[i],ts->adapt->ignore_max);
5843:       diff = PetscAbsScalar(y[i] - u[i]);
5844:       tola = ts->atol;
5845:       if (tola>0.){
5846:         suma  += PetscSqr(diff/tola);
5847:         na_loc++;
5848:       }
5849:       tolr = ts->rtol * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
5850:       if (tolr>0.){
5851:         sumr  += PetscSqr(diff/tolr);
5852:         nr_loc++;
5853:       }
5854:       tol=tola+tolr;
5855:       if (tol>0.){
5856:         sum  += PetscSqr(diff/tol);
5857:         n_loc++;
5858:       }
5859:     }
5860:   }
5861:   VecRestoreArrayRead(U,&u);
5862:   VecRestoreArrayRead(Y,&y);

5864:   err_loc[0] = sum;
5865:   err_loc[1] = suma;
5866:   err_loc[2] = sumr;
5867:   err_loc[3] = (PetscReal)n_loc;
5868:   err_loc[4] = (PetscReal)na_loc;
5869:   err_loc[5] = (PetscReal)nr_loc;

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

5873:   gsum   = err_glb[0];
5874:   gsuma  = err_glb[1];
5875:   gsumr  = err_glb[2];
5876:   n_glb  = err_glb[3];
5877:   na_glb = err_glb[4];
5878:   nr_glb = err_glb[5];

5880:   *norm  = 0.;
5881:   if (n_glb>0.){*norm  = PetscSqrtReal(gsum  / n_glb);}
5882:   *norma = 0.;
5883:   if (na_glb>0.){*norma = PetscSqrtReal(gsuma / na_glb);}
5884:   *normr = 0.;
5885:   if (nr_glb>0.){*normr = PetscSqrtReal(gsumr / nr_glb);}

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

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

5896:    Collective on TS

5898:    Input Arguments:
5899: +  ts - time stepping context
5900: .  U - state vector, usually ts->vec_sol
5901: -  Y - state vector to be compared to U

5903:    Output Arguments:
5904: +  norm - weighted norm, a value of 1.0 means that the error matches the tolerances
5905: .  norma - weighted norm based on the absolute tolerance, a value of 1.0 means that the error matches the tolerances
5906: -  normr - weighted norm based on the relative tolerance, a value of 1.0 means that the error matches the tolerances

5908:    Level: developer

5910: .seealso: TSErrorWeightedNorm(), TSErrorWeightedNorm2()
5911: @*/
5912: PetscErrorCode TSErrorWeightedNormInfinity(TS ts,Vec U,Vec Y,PetscReal *norm,PetscReal *norma,PetscReal *normr)
5913: {
5914:   PetscErrorCode    ierr;
5915:   PetscInt          i,n,N,rstart;
5916:   const PetscScalar *u,*y;
5917:   PetscReal         max,gmax,maxa,gmaxa,maxr,gmaxr;
5918:   PetscReal         tol,tola,tolr,diff;
5919:   PetscReal         err_loc[3],err_glb[3];

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

5933:   VecGetSize(U,&N);
5934:   VecGetLocalSize(U,&n);
5935:   VecGetOwnershipRange(U,&rstart,NULL);
5936:   VecGetArrayRead(U,&u);
5937:   VecGetArrayRead(Y,&y);

5939:   max=0.;
5940:   maxa=0.;
5941:   maxr=0.;

5943:   if (ts->vatol && ts->vrtol) {     /* vector atol, vector rtol */
5944:     const PetscScalar *atol,*rtol;
5945:     VecGetArrayRead(ts->vatol,&atol);
5946:     VecGetArrayRead(ts->vrtol,&rtol);

5948:     for (i=0; i<n; i++) {
5949:       SkipSmallValue(y[i],u[i],ts->adapt->ignore_max);
5950:       diff = PetscAbsScalar(y[i] - u[i]);
5951:       tola = PetscRealPart(atol[i]);
5952:       tolr = PetscRealPart(rtol[i]) * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
5953:       tol  = tola+tolr;
5954:       if (tola>0.){
5955:         maxa = PetscMax(maxa,diff / tola);
5956:       }
5957:       if (tolr>0.){
5958:         maxr = PetscMax(maxr,diff / tolr);
5959:       }
5960:       if (tol>0.){
5961:         max = PetscMax(max,diff / tol);
5962:       }
5963:     }
5964:     VecRestoreArrayRead(ts->vatol,&atol);
5965:     VecRestoreArrayRead(ts->vrtol,&rtol);
5966:   } else if (ts->vatol) {       /* vector atol, scalar rtol */
5967:     const PetscScalar *atol;
5968:     VecGetArrayRead(ts->vatol,&atol);
5969:     for (i=0; i<n; i++) {
5970:       SkipSmallValue(y[i],u[i],ts->adapt->ignore_max);
5971:       diff = PetscAbsScalar(y[i] - u[i]);
5972:       tola = PetscRealPart(atol[i]);
5973:       tolr = ts->rtol  * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
5974:       tol  = tola+tolr;
5975:       if (tola>0.){
5976:         maxa = PetscMax(maxa,diff / tola);
5977:       }
5978:       if (tolr>0.){
5979:         maxr = PetscMax(maxr,diff / tolr);
5980:       }
5981:       if (tol>0.){
5982:         max = PetscMax(max,diff / tol);
5983:       }
5984:     }
5985:     VecRestoreArrayRead(ts->vatol,&atol);
5986:   } else if (ts->vrtol) {       /* scalar atol, vector rtol */
5987:     const PetscScalar *rtol;
5988:     VecGetArrayRead(ts->vrtol,&rtol);

5990:     for (i=0; i<n; i++) {
5991:       SkipSmallValue(y[i],u[i],ts->adapt->ignore_max);
5992:       diff = PetscAbsScalar(y[i] - u[i]);
5993:       tola = ts->atol;
5994:       tolr = PetscRealPart(rtol[i]) * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
5995:       tol  = tola+tolr;
5996:       if (tola>0.){
5997:         maxa = PetscMax(maxa,diff / tola);
5998:       }
5999:       if (tolr>0.){
6000:         maxr = PetscMax(maxr,diff / tolr);
6001:       }
6002:       if (tol>0.){
6003:         max = PetscMax(max,diff / tol);
6004:       }
6005:     }
6006:     VecRestoreArrayRead(ts->vrtol,&rtol);
6007:   } else {                      /* scalar atol, scalar rtol */

6009:     for (i=0; i<n; i++) {
6010:       SkipSmallValue(y[i],u[i],ts->adapt->ignore_max);
6011:       diff = PetscAbsScalar(y[i] - u[i]);
6012:       tola = ts->atol;
6013:       tolr = ts->rtol * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
6014:       tol  = tola+tolr;
6015:       if (tola>0.){
6016:         maxa = PetscMax(maxa,diff / tola);
6017:       }
6018:       if (tolr>0.){
6019:         maxr = PetscMax(maxr,diff / tolr);
6020:       }
6021:       if (tol>0.){
6022:         max = PetscMax(max,diff / tol);
6023:       }
6024:     }
6025:   }
6026:   VecRestoreArrayRead(U,&u);
6027:   VecRestoreArrayRead(Y,&y);
6028:   err_loc[0] = max;
6029:   err_loc[1] = maxa;
6030:   err_loc[2] = maxr;
6031:   MPIU_Allreduce(err_loc,err_glb,3,MPIU_REAL,MPIU_MAX,PetscObjectComm((PetscObject)ts));
6032:   gmax   = err_glb[0];
6033:   gmaxa  = err_glb[1];
6034:   gmaxr  = err_glb[2];

6036:   *norm = gmax;
6037:   *norma = gmaxa;
6038:   *normr = gmaxr;
6039:   if (PetscIsInfOrNanScalar(*norm)) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_FP,"Infinite or not-a-number generated in norm");
6040:     if (PetscIsInfOrNanScalar(*norma)) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_FP,"Infinite or not-a-number generated in norma");
6041:     if (PetscIsInfOrNanScalar(*normr)) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_FP,"Infinite or not-a-number generated in normr");
6042:   return(0);
6043: }

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

6048:    Collective on TS

6050:    Input Arguments:
6051: +  ts - time stepping context
6052: .  U - state vector, usually ts->vec_sol
6053: .  Y - state vector to be compared to U
6054: -  wnormtype - norm type, either NORM_2 or NORM_INFINITY

6056:    Output Arguments:
6057: +  norm  - weighted norm, a value of 1.0 achieves a balance between absolute and relative tolerances
6058: .  norma - weighted norm, a value of 1.0 means that the error meets the absolute tolerance set by the user
6059: -  normr - weighted norm, a value of 1.0 means that the error meets the relative tolerance set by the user

6061:    Options Database Keys:
6062: .  -ts_adapt_wnormtype <wnormtype> - 2, INFINITY

6064:    Level: developer

6066: .seealso: TSErrorWeightedNormInfinity(), TSErrorWeightedNorm2(), TSErrorWeightedENorm
6067: @*/
6068: PetscErrorCode TSErrorWeightedNorm(TS ts,Vec U,Vec Y,NormType wnormtype,PetscReal *norm,PetscReal *norma,PetscReal *normr)
6069: {

6073:   if (wnormtype == NORM_2) {
6074:     TSErrorWeightedNorm2(ts,U,Y,norm,norma,normr);
6075:   } else if (wnormtype == NORM_INFINITY) {
6076:     TSErrorWeightedNormInfinity(ts,U,Y,norm,norma,normr);
6077:   } else SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"No support for norm type %s",NormTypes[wnormtype]);
6078:   return(0);
6079: }


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

6085:    Collective on TS

6087:    Input Arguments:
6088: +  ts - time stepping context
6089: .  E - error vector
6090: .  U - state vector, usually ts->vec_sol
6091: -  Y - state vector, previous time step

6093:    Output Arguments:
6094: +  norm - weighted norm, a value of 1.0 means that the error matches the tolerances
6095: .  norma - weighted norm based on the absolute tolerance, a value of 1.0 means that the error matches the tolerances
6096: -  normr - weighted norm based on the relative tolerance, a value of 1.0 means that the error matches the tolerances

6098:    Level: developer

6100: .seealso: TSErrorWeightedENorm(), TSErrorWeightedENormInfinity()
6101: @*/
6102: PetscErrorCode TSErrorWeightedENorm2(TS ts,Vec E,Vec U,Vec Y,PetscReal *norm,PetscReal *norma,PetscReal *normr)
6103: {
6104:   PetscErrorCode    ierr;
6105:   PetscInt          i,n,N,rstart;
6106:   PetscInt          n_loc,na_loc,nr_loc;
6107:   PetscReal         n_glb,na_glb,nr_glb;
6108:   const PetscScalar *e,*u,*y;
6109:   PetscReal         err,sum,suma,sumr,gsum,gsuma,gsumr;
6110:   PetscReal         tol,tola,tolr;
6111:   PetscReal         err_loc[6],err_glb[6];


6127:   VecGetSize(E,&N);
6128:   VecGetLocalSize(E,&n);
6129:   VecGetOwnershipRange(E,&rstart,NULL);
6130:   VecGetArrayRead(E,&e);
6131:   VecGetArrayRead(U,&u);
6132:   VecGetArrayRead(Y,&y);
6133:   sum  = 0.; n_loc  = 0;
6134:   suma = 0.; na_loc = 0;
6135:   sumr = 0.; nr_loc = 0;
6136:   if (ts->vatol && ts->vrtol) {
6137:     const PetscScalar *atol,*rtol;
6138:     VecGetArrayRead(ts->vatol,&atol);
6139:     VecGetArrayRead(ts->vrtol,&rtol);
6140:     for (i=0; i<n; i++) {
6141:       SkipSmallValue(y[i],u[i],ts->adapt->ignore_max);
6142:       err = PetscAbsScalar(e[i]);
6143:       tola = PetscRealPart(atol[i]);
6144:       if (tola>0.){
6145:         suma  += PetscSqr(err/tola);
6146:         na_loc++;
6147:       }
6148:       tolr = PetscRealPart(rtol[i]) * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
6149:       if (tolr>0.){
6150:         sumr  += PetscSqr(err/tolr);
6151:         nr_loc++;
6152:       }
6153:       tol=tola+tolr;
6154:       if (tol>0.){
6155:         sum  += PetscSqr(err/tol);
6156:         n_loc++;
6157:       }
6158:     }
6159:     VecRestoreArrayRead(ts->vatol,&atol);
6160:     VecRestoreArrayRead(ts->vrtol,&rtol);
6161:   } else if (ts->vatol) {       /* vector atol, scalar rtol */
6162:     const PetscScalar *atol;
6163:     VecGetArrayRead(ts->vatol,&atol);
6164:     for (i=0; i<n; i++) {
6165:       SkipSmallValue(y[i],u[i],ts->adapt->ignore_max);
6166:       err = PetscAbsScalar(e[i]);
6167:       tola = PetscRealPart(atol[i]);
6168:       if (tola>0.){
6169:         suma  += PetscSqr(err/tola);
6170:         na_loc++;
6171:       }
6172:       tolr = ts->rtol * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
6173:       if (tolr>0.){
6174:         sumr  += PetscSqr(err/tolr);
6175:         nr_loc++;
6176:       }
6177:       tol=tola+tolr;
6178:       if (tol>0.){
6179:         sum  += PetscSqr(err/tol);
6180:         n_loc++;
6181:       }
6182:     }
6183:     VecRestoreArrayRead(ts->vatol,&atol);
6184:   } else if (ts->vrtol) {       /* scalar atol, vector rtol */
6185:     const PetscScalar *rtol;
6186:     VecGetArrayRead(ts->vrtol,&rtol);
6187:     for (i=0; i<n; i++) {
6188:       SkipSmallValue(y[i],u[i],ts->adapt->ignore_max);
6189:       err = PetscAbsScalar(e[i]);
6190:       tola = ts->atol;
6191:       if (tola>0.){
6192:         suma  += PetscSqr(err/tola);
6193:         na_loc++;
6194:       }
6195:       tolr = PetscRealPart(rtol[i]) * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
6196:       if (tolr>0.){
6197:         sumr  += PetscSqr(err/tolr);
6198:         nr_loc++;
6199:       }
6200:       tol=tola+tolr;
6201:       if (tol>0.){
6202:         sum  += PetscSqr(err/tol);
6203:         n_loc++;
6204:       }
6205:     }
6206:     VecRestoreArrayRead(ts->vrtol,&rtol);
6207:   } else {                      /* scalar atol, scalar rtol */
6208:     for (i=0; i<n; i++) {
6209:       SkipSmallValue(y[i],u[i],ts->adapt->ignore_max);
6210:       err = PetscAbsScalar(e[i]);
6211:       tola = ts->atol;
6212:       if (tola>0.){
6213:         suma  += PetscSqr(err/tola);
6214:         na_loc++;
6215:       }
6216:       tolr = ts->rtol * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
6217:       if (tolr>0.){
6218:         sumr  += PetscSqr(err/tolr);
6219:         nr_loc++;
6220:       }
6221:       tol=tola+tolr;
6222:       if (tol>0.){
6223:         sum  += PetscSqr(err/tol);
6224:         n_loc++;
6225:       }
6226:     }
6227:   }
6228:   VecRestoreArrayRead(E,&e);
6229:   VecRestoreArrayRead(U,&u);
6230:   VecRestoreArrayRead(Y,&y);

6232:   err_loc[0] = sum;
6233:   err_loc[1] = suma;
6234:   err_loc[2] = sumr;
6235:   err_loc[3] = (PetscReal)n_loc;
6236:   err_loc[4] = (PetscReal)na_loc;
6237:   err_loc[5] = (PetscReal)nr_loc;

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

6241:   gsum   = err_glb[0];
6242:   gsuma  = err_glb[1];
6243:   gsumr  = err_glb[2];
6244:   n_glb  = err_glb[3];
6245:   na_glb = err_glb[4];
6246:   nr_glb = err_glb[5];

6248:   *norm  = 0.;
6249:   if (n_glb>0.){*norm  = PetscSqrtReal(gsum  / n_glb);}
6250:   *norma = 0.;
6251:   if (na_glb>0.){*norma = PetscSqrtReal(gsuma / na_glb);}
6252:   *normr = 0.;
6253:   if (nr_glb>0.){*normr = PetscSqrtReal(gsumr / nr_glb);}

6255:   if (PetscIsInfOrNanScalar(*norm)) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_FP,"Infinite or not-a-number generated in norm");
6256:   if (PetscIsInfOrNanScalar(*norma)) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_FP,"Infinite or not-a-number generated in norma");
6257:   if (PetscIsInfOrNanScalar(*normr)) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_FP,"Infinite or not-a-number generated in normr");
6258:   return(0);
6259: }

6261: /*@
6262:    TSErrorWeightedENormInfinity - compute a weighted infinity error norm based on supplied absolute and relative tolerances
6263:    Collective on TS

6265:    Input Arguments:
6266: +  ts - time stepping context
6267: .  E - error vector
6268: .  U - state vector, usually ts->vec_sol
6269: -  Y - state vector, previous time step

6271:    Output Arguments:
6272: +  norm - weighted norm, a value of 1.0 means that the error matches the tolerances
6273: .  norma - weighted norm based on the absolute tolerance, a value of 1.0 means that the error matches the tolerances
6274: -  normr - weighted norm based on the relative tolerance, a value of 1.0 means that the error matches the tolerances

6276:    Level: developer

6278: .seealso: TSErrorWeightedENorm(), TSErrorWeightedENorm2()
6279: @*/
6280: PetscErrorCode TSErrorWeightedENormInfinity(TS ts,Vec E,Vec U,Vec Y,PetscReal *norm,PetscReal *norma,PetscReal *normr)
6281: {
6282:   PetscErrorCode    ierr;
6283:   PetscInt          i,n,N,rstart;
6284:   const PetscScalar *e,*u,*y;
6285:   PetscReal         err,max,gmax,maxa,gmaxa,maxr,gmaxr;
6286:   PetscReal         tol,tola,tolr;
6287:   PetscReal         err_loc[3],err_glb[3];


6303:   VecGetSize(E,&N);
6304:   VecGetLocalSize(E,&n);
6305:   VecGetOwnershipRange(E,&rstart,NULL);
6306:   VecGetArrayRead(E,&e);
6307:   VecGetArrayRead(U,&u);
6308:   VecGetArrayRead(Y,&y);

6310:   max=0.;
6311:   maxa=0.;
6312:   maxr=0.;

6314:   if (ts->vatol && ts->vrtol) {     /* vector atol, vector rtol */
6315:     const PetscScalar *atol,*rtol;
6316:     VecGetArrayRead(ts->vatol,&atol);
6317:     VecGetArrayRead(ts->vrtol,&rtol);

6319:     for (i=0; i<n; i++) {
6320:       SkipSmallValue(y[i],u[i],ts->adapt->ignore_max);
6321:       err = PetscAbsScalar(e[i]);
6322:       tola = PetscRealPart(atol[i]);
6323:       tolr = PetscRealPart(rtol[i]) * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
6324:       tol  = tola+tolr;
6325:       if (tola>0.){
6326:         maxa = PetscMax(maxa,err / tola);
6327:       }
6328:       if (tolr>0.){
6329:         maxr = PetscMax(maxr,err / tolr);
6330:       }
6331:       if (tol>0.){
6332:         max = PetscMax(max,err / tol);
6333:       }
6334:     }
6335:     VecRestoreArrayRead(ts->vatol,&atol);
6336:     VecRestoreArrayRead(ts->vrtol,&rtol);
6337:   } else if (ts->vatol) {       /* vector atol, scalar rtol */
6338:     const PetscScalar *atol;
6339:     VecGetArrayRead(ts->vatol,&atol);
6340:     for (i=0; i<n; i++) {
6341:       SkipSmallValue(y[i],u[i],ts->adapt->ignore_max);
6342:       err = PetscAbsScalar(e[i]);
6343:       tola = PetscRealPart(atol[i]);
6344:       tolr = ts->rtol  * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
6345:       tol  = tola+tolr;
6346:       if (tola>0.){
6347:         maxa = PetscMax(maxa,err / tola);
6348:       }
6349:       if (tolr>0.){
6350:         maxr = PetscMax(maxr,err / tolr);
6351:       }
6352:       if (tol>0.){
6353:         max = PetscMax(max,err / tol);
6354:       }
6355:     }
6356:     VecRestoreArrayRead(ts->vatol,&atol);
6357:   } else if (ts->vrtol) {       /* scalar atol, vector rtol */
6358:     const PetscScalar *rtol;
6359:     VecGetArrayRead(ts->vrtol,&rtol);

6361:     for (i=0; i<n; i++) {
6362:       SkipSmallValue(y[i],u[i],ts->adapt->ignore_max);
6363:       err = PetscAbsScalar(e[i]);
6364:       tola = ts->atol;
6365:       tolr = PetscRealPart(rtol[i]) * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
6366:       tol  = tola+tolr;
6367:       if (tola>0.){
6368:         maxa = PetscMax(maxa,err / tola);
6369:       }
6370:       if (tolr>0.){
6371:         maxr = PetscMax(maxr,err / tolr);
6372:       }
6373:       if (tol>0.){
6374:         max = PetscMax(max,err / tol);
6375:       }
6376:     }
6377:     VecRestoreArrayRead(ts->vrtol,&rtol);
6378:   } else {                      /* scalar atol, scalar rtol */

6380:     for (i=0; i<n; i++) {
6381:       SkipSmallValue(y[i],u[i],ts->adapt->ignore_max);
6382:       err = PetscAbsScalar(e[i]);
6383:       tola = ts->atol;
6384:       tolr = ts->rtol * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
6385:       tol  = tola+tolr;
6386:       if (tola>0.){
6387:         maxa = PetscMax(maxa,err / tola);
6388:       }
6389:       if (tolr>0.){
6390:         maxr = PetscMax(maxr,err / tolr);
6391:       }
6392:       if (tol>0.){
6393:         max = PetscMax(max,err / tol);
6394:       }
6395:     }
6396:   }
6397:   VecRestoreArrayRead(E,&e);
6398:   VecRestoreArrayRead(U,&u);
6399:   VecRestoreArrayRead(Y,&y);
6400:   err_loc[0] = max;
6401:   err_loc[1] = maxa;
6402:   err_loc[2] = maxr;
6403:   MPIU_Allreduce(err_loc,err_glb,3,MPIU_REAL,MPIU_MAX,PetscObjectComm((PetscObject)ts));
6404:   gmax   = err_glb[0];
6405:   gmaxa  = err_glb[1];
6406:   gmaxr  = err_glb[2];

6408:   *norm = gmax;
6409:   *norma = gmaxa;
6410:   *normr = gmaxr;
6411:   if (PetscIsInfOrNanScalar(*norm)) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_FP,"Infinite or not-a-number generated in norm");
6412:     if (PetscIsInfOrNanScalar(*norma)) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_FP,"Infinite or not-a-number generated in norma");
6413:     if (PetscIsInfOrNanScalar(*normr)) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_FP,"Infinite or not-a-number generated in normr");
6414:   return(0);
6415: }

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

6420:    Collective on TS

6422:    Input Arguments:
6423: +  ts - time stepping context
6424: .  E - error vector
6425: .  U - state vector, usually ts->vec_sol
6426: .  Y - state vector, previous time step
6427: -  wnormtype - norm type, either NORM_2 or NORM_INFINITY

6429:    Output Arguments:
6430: +  norm  - weighted norm, a value of 1.0 achieves a balance between absolute and relative tolerances
6431: .  norma - weighted norm, a value of 1.0 means that the error meets the absolute tolerance set by the user
6432: -  normr - weighted norm, a value of 1.0 means that the error meets the relative tolerance set by the user

6434:    Options Database Keys:
6435: .  -ts_adapt_wnormtype <wnormtype> - 2, INFINITY

6437:    Level: developer

6439: .seealso: TSErrorWeightedENormInfinity(), TSErrorWeightedENorm2(), TSErrorWeightedNormInfinity(), TSErrorWeightedNorm2()
6440: @*/
6441: PetscErrorCode TSErrorWeightedENorm(TS ts,Vec E,Vec U,Vec Y,NormType wnormtype,PetscReal *norm,PetscReal *norma,PetscReal *normr)
6442: {

6446:   if (wnormtype == NORM_2) {
6447:     TSErrorWeightedENorm2(ts,E,U,Y,norm,norma,normr);
6448:   } else if (wnormtype == NORM_INFINITY) {
6449:     TSErrorWeightedENormInfinity(ts,E,U,Y,norm,norma,normr);
6450:   } else SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"No support for norm type %s",NormTypes[wnormtype]);
6451:   return(0);
6452: }


6455: /*@
6456:    TSSetCFLTimeLocal - Set the local CFL constraint relative to forward Euler

6458:    Logically Collective on TS

6460:    Input Arguments:
6461: +  ts - time stepping context
6462: -  cfltime - maximum stable time step if using forward Euler (value can be different on each process)

6464:    Note:
6465:    After calling this function, the global CFL time can be obtained by calling TSGetCFLTime()

6467:    Level: intermediate

6469: .seealso: TSGetCFLTime(), TSADAPTCFL
6470: @*/
6471: PetscErrorCode TSSetCFLTimeLocal(TS ts,PetscReal cfltime)
6472: {
6475:   ts->cfltime_local = cfltime;
6476:   ts->cfltime       = -1.;
6477:   return(0);
6478: }

6480: /*@
6481:    TSGetCFLTime - Get the maximum stable time step according to CFL criteria applied to forward Euler

6483:    Collective on TS

6485:    Input Arguments:
6486: .  ts - time stepping context

6488:    Output Arguments:
6489: .  cfltime - maximum stable time step for forward Euler

6491:    Level: advanced

6493: .seealso: TSSetCFLTimeLocal()
6494: @*/
6495: PetscErrorCode TSGetCFLTime(TS ts,PetscReal *cfltime)
6496: {

6500:   if (ts->cfltime < 0) {
6501:     MPIU_Allreduce(&ts->cfltime_local,&ts->cfltime,1,MPIU_REAL,MPIU_MIN,PetscObjectComm((PetscObject)ts));
6502:   }
6503:   *cfltime = ts->cfltime;
6504:   return(0);
6505: }

6507: /*@
6508:    TSVISetVariableBounds - Sets the lower and upper bounds for the solution vector. xl <= x <= xu

6510:    Input Parameters:
6511: +  ts   - the TS context.
6512: .  xl   - lower bound.
6513: -  xu   - upper bound.

6515:    Notes:
6516:    If this routine is not called then the lower and upper bounds are set to
6517:    PETSC_NINFINITY and PETSC_INFINITY respectively during SNESSetUp().

6519:    Level: advanced

6521: @*/
6522: PetscErrorCode TSVISetVariableBounds(TS ts, Vec xl, Vec xu)
6523: {
6525:   SNES           snes;

6528:   TSGetSNES(ts,&snes);
6529:   SNESVISetVariableBounds(snes,xl,xu);
6530:   return(0);
6531: }

6533: /*@C
6534:    TSMonitorLGSolution - Monitors progress of the TS solvers by plotting each component of the solution vector
6535:        in a time based line graph

6537:    Collective on TS

6539:    Input Parameters:
6540: +  ts - the TS context
6541: .  step - current time-step
6542: .  ptime - current time
6543: .  u - current solution
6544: -  dctx - the TSMonitorLGCtx object that contains all the options for the monitoring, this is created with TSMonitorLGCtxCreate()

6546:    Options Database:
6547: .   -ts_monitor_lg_solution_variables

6549:    Level: intermediate

6551:    Notes:
6552:     Each process in a parallel run displays its component solutions in a separate window

6554: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorLGCtxCreate(), TSMonitorLGCtxSetVariableNames(), TSMonitorLGCtxGetVariableNames(),
6555:            TSMonitorLGSetVariableNames(), TSMonitorLGGetVariableNames(), TSMonitorLGSetDisplayVariables(), TSMonitorLGCtxSetDisplayVariables(),
6556:            TSMonitorLGCtxSetTransform(), TSMonitorLGSetTransform(), TSMonitorLGError(), TSMonitorLGSNESIterations(), TSMonitorLGKSPIterations(),
6557:            TSMonitorEnvelopeCtxCreate(), TSMonitorEnvelopeGetBounds(), TSMonitorEnvelopeCtxDestroy(), TSMonitorEnvelop()
6558: @*/
6559: PetscErrorCode  TSMonitorLGSolution(TS ts,PetscInt step,PetscReal ptime,Vec u,void *dctx)
6560: {
6561:   PetscErrorCode    ierr;
6562:   TSMonitorLGCtx    ctx = (TSMonitorLGCtx)dctx;
6563:   const PetscScalar *yy;
6564:   Vec               v;

6567:   if (step < 0) return(0); /* -1 indicates interpolated solution */
6568:   if (!step) {
6569:     PetscDrawAxis axis;
6570:     PetscInt      dim;
6571:     PetscDrawLGGetAxis(ctx->lg,&axis);
6572:     PetscDrawAxisSetLabels(axis,"Solution as function of time","Time","Solution");
6573:     if (!ctx->names) {
6574:       PetscBool flg;
6575:       /* user provides names of variables to plot but no names has been set so assume names are integer values */
6576:       PetscOptionsHasName(((PetscObject)ts)->options,((PetscObject)ts)->prefix,"-ts_monitor_lg_solution_variables",&flg);
6577:       if (flg) {
6578:         PetscInt i,n;
6579:         char     **names;
6580:         VecGetSize(u,&n);
6581:         PetscMalloc1(n+1,&names);
6582:         for (i=0; i<n; i++) {
6583:           PetscMalloc1(5,&names[i]);
6584:           PetscSNPrintf(names[i],5,"%D",i);
6585:         }
6586:         names[n] = NULL;
6587:         ctx->names = names;
6588:       }
6589:     }
6590:     if (ctx->names && !ctx->displaynames) {
6591:       char      **displaynames;
6592:       PetscBool flg;
6593:       VecGetLocalSize(u,&dim);
6594:       PetscCalloc1(dim+1,&displaynames);
6595:       PetscOptionsGetStringArray(((PetscObject)ts)->options,((PetscObject)ts)->prefix,"-ts_monitor_lg_solution_variables",displaynames,&dim,&flg);
6596:       if (flg) {
6597:         TSMonitorLGCtxSetDisplayVariables(ctx,(const char *const *)displaynames);
6598:       }
6599:       PetscStrArrayDestroy(&displaynames);
6600:     }
6601:     if (ctx->displaynames) {
6602:       PetscDrawLGSetDimension(ctx->lg,ctx->ndisplayvariables);
6603:       PetscDrawLGSetLegend(ctx->lg,(const char *const *)ctx->displaynames);
6604:     } else if (ctx->names) {
6605:       VecGetLocalSize(u,&dim);
6606:       PetscDrawLGSetDimension(ctx->lg,dim);
6607:       PetscDrawLGSetLegend(ctx->lg,(const char *const *)ctx->names);
6608:     } else {
6609:       VecGetLocalSize(u,&dim);
6610:       PetscDrawLGSetDimension(ctx->lg,dim);
6611:     }
6612:     PetscDrawLGReset(ctx->lg);
6613:   }

6615:   if (!ctx->transform) v = u;
6616:   else {(*ctx->transform)(ctx->transformctx,u,&v);}
6617:   VecGetArrayRead(v,&yy);
6618:   if (ctx->displaynames) {
6619:     PetscInt i;
6620:     for (i=0; i<ctx->ndisplayvariables; i++)
6621:       ctx->displayvalues[i] = PetscRealPart(yy[ctx->displayvariables[i]]);
6622:     PetscDrawLGAddCommonPoint(ctx->lg,ptime,ctx->displayvalues);
6623:   } else {
6624: #if defined(PETSC_USE_COMPLEX)
6625:     PetscInt  i,n;
6626:     PetscReal *yreal;
6627:     VecGetLocalSize(v,&n);
6628:     PetscMalloc1(n,&yreal);
6629:     for (i=0; i<n; i++) yreal[i] = PetscRealPart(yy[i]);
6630:     PetscDrawLGAddCommonPoint(ctx->lg,ptime,yreal);
6631:     PetscFree(yreal);
6632: #else
6633:     PetscDrawLGAddCommonPoint(ctx->lg,ptime,yy);
6634: #endif
6635:   }
6636:   VecRestoreArrayRead(v,&yy);
6637:   if (ctx->transform) {VecDestroy(&v);}

6639:   if (((ctx->howoften > 0) && (!(step % ctx->howoften))) || ((ctx->howoften == -1) && ts->reason)) {
6640:     PetscDrawLGDraw(ctx->lg);
6641:     PetscDrawLGSave(ctx->lg);
6642:   }
6643:   return(0);
6644: }

6646: /*@C
6647:    TSMonitorLGSetVariableNames - Sets the name of each component in the solution vector so that it may be displayed in the plot

6649:    Collective on TS

6651:    Input Parameters:
6652: +  ts - the TS context
6653: -  names - the names of the components, final string must be NULL

6655:    Level: intermediate

6657:    Notes:
6658:     If the TS object does not have a TSMonitorLGCtx associated with it then this function is ignored

6660: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorLGSetDisplayVariables(), TSMonitorLGCtxSetVariableNames()
6661: @*/
6662: PetscErrorCode  TSMonitorLGSetVariableNames(TS ts,const char * const *names)
6663: {
6664:   PetscErrorCode    ierr;
6665:   PetscInt          i;

6668:   for (i=0; i<ts->numbermonitors; i++) {
6669:     if (ts->monitor[i] == TSMonitorLGSolution) {
6670:       TSMonitorLGCtxSetVariableNames((TSMonitorLGCtx)ts->monitorcontext[i],names);
6671:       break;
6672:     }
6673:   }
6674:   return(0);
6675: }

6677: /*@C
6678:    TSMonitorLGCtxSetVariableNames - Sets the name of each component in the solution vector so that it may be displayed in the plot

6680:    Collective on TS

6682:    Input Parameters:
6683: +  ts - the TS context
6684: -  names - the names of the components, final string must be NULL

6686:    Level: intermediate

6688: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorLGSetDisplayVariables(), TSMonitorLGSetVariableNames()
6689: @*/
6690: PetscErrorCode  TSMonitorLGCtxSetVariableNames(TSMonitorLGCtx ctx,const char * const *names)
6691: {
6692:   PetscErrorCode    ierr;

6695:   PetscStrArrayDestroy(&ctx->names);
6696:   PetscStrArrayallocpy(names,&ctx->names);
6697:   return(0);
6698: }

6700: /*@C
6701:    TSMonitorLGGetVariableNames - Gets the name of each component in the solution vector so that it may be displayed in the plot

6703:    Collective on TS

6705:    Input Parameter:
6706: .  ts - the TS context

6708:    Output Parameter:
6709: .  names - the names of the components, final string must be NULL

6711:    Level: intermediate

6713:    Notes:
6714:     If the TS object does not have a TSMonitorLGCtx associated with it then this function is ignored

6716: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorLGSetDisplayVariables()
6717: @*/
6718: PetscErrorCode  TSMonitorLGGetVariableNames(TS ts,const char *const **names)
6719: {
6720:   PetscInt       i;

6723:   *names = NULL;
6724:   for (i=0; i<ts->numbermonitors; i++) {
6725:     if (ts->monitor[i] == TSMonitorLGSolution) {
6726:       TSMonitorLGCtx  ctx = (TSMonitorLGCtx) ts->monitorcontext[i];
6727:       *names = (const char *const *)ctx->names;
6728:       break;
6729:     }
6730:   }
6731:   return(0);
6732: }

6734: /*@C
6735:    TSMonitorLGCtxSetDisplayVariables - Sets the variables that are to be display in the monitor

6737:    Collective on TS

6739:    Input Parameters:
6740: +  ctx - the TSMonitorLG context
6741: -  displaynames - the names of the components, final string must be NULL

6743:    Level: intermediate

6745: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorLGSetVariableNames()
6746: @*/
6747: PetscErrorCode  TSMonitorLGCtxSetDisplayVariables(TSMonitorLGCtx ctx,const char * const *displaynames)
6748: {
6749:   PetscInt          j = 0,k;
6750:   PetscErrorCode    ierr;

6753:   if (!ctx->names) return(0);
6754:   PetscStrArrayDestroy(&ctx->displaynames);
6755:   PetscStrArrayallocpy(displaynames,&ctx->displaynames);
6756:   while (displaynames[j]) j++;
6757:   ctx->ndisplayvariables = j;
6758:   PetscMalloc1(ctx->ndisplayvariables,&ctx->displayvariables);
6759:   PetscMalloc1(ctx->ndisplayvariables,&ctx->displayvalues);
6760:   j = 0;
6761:   while (displaynames[j]) {
6762:     k = 0;
6763:     while (ctx->names[k]) {
6764:       PetscBool flg;
6765:       PetscStrcmp(displaynames[j],ctx->names[k],&flg);
6766:       if (flg) {
6767:         ctx->displayvariables[j] = k;
6768:         break;
6769:       }
6770:       k++;
6771:     }
6772:     j++;
6773:   }
6774:   return(0);
6775: }

6777: /*@C
6778:    TSMonitorLGSetDisplayVariables - Sets the variables that are to be display in the monitor

6780:    Collective on TS

6782:    Input Parameters:
6783: +  ts - the TS context
6784: -  displaynames - the names of the components, final string must be NULL

6786:    Notes:
6787:     If the TS object does not have a TSMonitorLGCtx associated with it then this function is ignored

6789:    Level: intermediate

6791: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorLGSetVariableNames()
6792: @*/
6793: PetscErrorCode  TSMonitorLGSetDisplayVariables(TS ts,const char * const *displaynames)
6794: {
6795:   PetscInt          i;
6796:   PetscErrorCode    ierr;

6799:   for (i=0; i<ts->numbermonitors; i++) {
6800:     if (ts->monitor[i] == TSMonitorLGSolution) {
6801:       TSMonitorLGCtxSetDisplayVariables((TSMonitorLGCtx)ts->monitorcontext[i],displaynames);
6802:       break;
6803:     }
6804:   }
6805:   return(0);
6806: }

6808: /*@C
6809:    TSMonitorLGSetTransform - Solution vector will be transformed by provided function before being displayed

6811:    Collective on TS

6813:    Input Parameters:
6814: +  ts - the TS context
6815: .  transform - the transform function
6816: .  destroy - function to destroy the optional context
6817: -  ctx - optional context used by transform function

6819:    Notes:
6820:     If the TS object does not have a TSMonitorLGCtx associated with it then this function is ignored

6822:    Level: intermediate

6824: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorLGSetVariableNames(), TSMonitorLGCtxSetTransform()
6825: @*/
6826: PetscErrorCode  TSMonitorLGSetTransform(TS ts,PetscErrorCode (*transform)(void*,Vec,Vec*),PetscErrorCode (*destroy)(void*),void *tctx)
6827: {
6828:   PetscInt          i;
6829:   PetscErrorCode    ierr;

6832:   for (i=0; i<ts->numbermonitors; i++) {
6833:     if (ts->monitor[i] == TSMonitorLGSolution) {
6834:       TSMonitorLGCtxSetTransform((TSMonitorLGCtx)ts->monitorcontext[i],transform,destroy,tctx);
6835:     }
6836:   }
6837:   return(0);
6838: }

6840: /*@C
6841:    TSMonitorLGCtxSetTransform - Solution vector will be transformed by provided function before being displayed

6843:    Collective on TSLGCtx

6845:    Input Parameters:
6846: +  ts - the TS context
6847: .  transform - the transform function
6848: .  destroy - function to destroy the optional context
6849: -  ctx - optional context used by transform function

6851:    Level: intermediate

6853: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorLGSetVariableNames(), TSMonitorLGSetTransform()
6854: @*/
6855: PetscErrorCode  TSMonitorLGCtxSetTransform(TSMonitorLGCtx ctx,PetscErrorCode (*transform)(void*,Vec,Vec*),PetscErrorCode (*destroy)(void*),void *tctx)
6856: {
6858:   ctx->transform    = transform;
6859:   ctx->transformdestroy = destroy;
6860:   ctx->transformctx = tctx;
6861:   return(0);
6862: }

6864: /*@C
6865:    TSMonitorLGError - Monitors progress of the TS solvers by plotting each component of the error
6866:        in a time based line graph

6868:    Collective on TS

6870:    Input Parameters:
6871: +  ts - the TS context
6872: .  step - current time-step
6873: .  ptime - current time
6874: .  u - current solution
6875: -  dctx - TSMonitorLGCtx object created with TSMonitorLGCtxCreate()

6877:    Level: intermediate

6879:    Notes:
6880:     Each process in a parallel run displays its component errors in a separate window

6882:    The user must provide the solution using TSSetSolutionFunction() to use this monitor.

6884:    Options Database Keys:
6885: .  -ts_monitor_lg_error - create a graphical monitor of error history

6887: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSSetSolutionFunction()
6888: @*/
6889: PetscErrorCode  TSMonitorLGError(TS ts,PetscInt step,PetscReal ptime,Vec u,void *dummy)
6890: {
6891:   PetscErrorCode    ierr;
6892:   TSMonitorLGCtx    ctx = (TSMonitorLGCtx)dummy;
6893:   const PetscScalar *yy;
6894:   Vec               y;

6897:   if (!step) {
6898:     PetscDrawAxis axis;
6899:     PetscInt      dim;
6900:     PetscDrawLGGetAxis(ctx->lg,&axis);
6901:     PetscDrawAxisSetLabels(axis,"Error in solution as function of time","Time","Error");
6902:     VecGetLocalSize(u,&dim);
6903:     PetscDrawLGSetDimension(ctx->lg,dim);
6904:     PetscDrawLGReset(ctx->lg);
6905:   }
6906:   VecDuplicate(u,&y);
6907:   TSComputeSolutionFunction(ts,ptime,y);
6908:   VecAXPY(y,-1.0,u);
6909:   VecGetArrayRead(y,&yy);
6910: #if defined(PETSC_USE_COMPLEX)
6911:   {
6912:     PetscReal *yreal;
6913:     PetscInt  i,n;
6914:     VecGetLocalSize(y,&n);
6915:     PetscMalloc1(n,&yreal);
6916:     for (i=0; i<n; i++) yreal[i] = PetscRealPart(yy[i]);
6917:     PetscDrawLGAddCommonPoint(ctx->lg,ptime,yreal);
6918:     PetscFree(yreal);
6919:   }
6920: #else
6921:   PetscDrawLGAddCommonPoint(ctx->lg,ptime,yy);
6922: #endif
6923:   VecRestoreArrayRead(y,&yy);
6924:   VecDestroy(&y);
6925:   if (((ctx->howoften > 0) && (!(step % ctx->howoften))) || ((ctx->howoften == -1) && ts->reason)) {
6926:     PetscDrawLGDraw(ctx->lg);
6927:     PetscDrawLGSave(ctx->lg);
6928:   }
6929:   return(0);
6930: }

6932: /*@C
6933:    TSMonitorSPSwarmSolution - Graphically displays phase plots of DMSwarm particles on a scatter plot

6935:    Input Parameters:
6936: +  ts - the TS context
6937: .  step - current time-step
6938: .  ptime - current time
6939: .  u - current solution
6940: -  dctx - the TSMonitorSPCtx object that contains all the options for the monitoring, this is created with TSMonitorSPCtxCreate()

6942:    Options Database:
6943: .   -ts_monitor_sp_swarm

6945:    Level: intermediate

6947: @*/
6948: PetscErrorCode TSMonitorSPSwarmSolution(TS ts,PetscInt step,PetscReal ptime,Vec u,void *dctx)
6949: {
6950:   PetscErrorCode    ierr;
6951:   TSMonitorSPCtx    ctx = (TSMonitorSPCtx)dctx;
6952:   const PetscScalar *yy;
6953:   PetscReal       *y,*x;
6954:   PetscInt          Np, p, dim=2;
6955:   DM                dm;


6959:   if (step < 0) return(0); /* -1 indicates interpolated solution */
6960:   if (!step) {
6961:     PetscDrawAxis axis;
6962:     PetscDrawSPGetAxis(ctx->sp,&axis);
6963:     PetscDrawAxisSetLabels(axis,"Particles","X","Y");
6964:     PetscDrawAxisSetLimits(axis, -5, 5, -5, 5);
6965:     PetscDrawAxisSetHoldLimits(axis, PETSC_TRUE);
6966:     TSGetDM(ts, &dm);
6967:     DMGetDimension(dm, &dim);
6968:     if (dim!=2) SETERRQ(PETSC_COMM_SELF, ierr, "Dimensions improper for monitor arguments! Current support: two dimensions.");
6969:     VecGetLocalSize(u, &Np);
6970:     Np /= 2*dim;
6971:     PetscDrawSPSetDimension(ctx->sp, Np);
6972:     PetscDrawSPReset(ctx->sp);
6973:   }

6975:   VecGetLocalSize(u, &Np);
6976:   Np /= 2*dim;
6977:   VecGetArrayRead(u,&yy);
6978:   PetscMalloc2(Np, &x, Np, &y);
6979:   /* get points from solution vector */
6980:   for (p=0; p<Np; ++p){
6981:     x[p] = PetscRealPart(yy[2*dim*p]);
6982:     y[p] = PetscRealPart(yy[2*dim*p+1]);
6983:   }
6984:   VecRestoreArrayRead(u,&yy);

6986:   if (((ctx->howoften > 0) && (!(step % ctx->howoften))) || ((ctx->howoften == -1) && ts->reason)) {
6987:     PetscDrawSPAddPoint(ctx->sp,x,y);
6988:     PetscDrawSPDraw(ctx->sp,PETSC_FALSE);
6989:     PetscDrawSPSave(ctx->sp);
6990:   }

6992:   PetscFree2(x, y);

6994:   return(0);
6995: }



6999: /*@C
7000:    TSMonitorError - Monitors progress of the TS solvers by printing the 2 norm of the error at each timestep

7002:    Collective on TS

7004:    Input Parameters:
7005: +  ts - the TS context
7006: .  step - current time-step
7007: .  ptime - current time
7008: .  u - current solution
7009: -  dctx - unused context

7011:    Level: intermediate

7013:    The user must provide the solution using TSSetSolutionFunction() to use this monitor.

7015:    Options Database Keys:
7016: .  -ts_monitor_error - create a graphical monitor of error history

7018: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSSetSolutionFunction()
7019: @*/
7020: PetscErrorCode  TSMonitorError(TS ts,PetscInt step,PetscReal ptime,Vec u,PetscViewerAndFormat *vf)
7021: {
7022:   PetscErrorCode    ierr;
7023:   Vec               y;
7024:   PetscReal         nrm;
7025:   PetscBool         flg;

7028:   VecDuplicate(u,&y);
7029:   TSComputeSolutionFunction(ts,ptime,y);
7030:   VecAXPY(y,-1.0,u);
7031:   PetscObjectTypeCompare((PetscObject)vf->viewer,PETSCVIEWERASCII,&flg);
7032:   if (flg) {
7033:     VecNorm(y,NORM_2,&nrm);
7034:     PetscViewerASCIIPrintf(vf->viewer,"2-norm of error %g\n",(double)nrm);
7035:   }
7036:   PetscObjectTypeCompare((PetscObject)vf->viewer,PETSCVIEWERDRAW,&flg);
7037:   if (flg) {
7038:     VecView(y,vf->viewer);
7039:   }
7040:   VecDestroy(&y);
7041:   return(0);
7042: }

7044: PetscErrorCode TSMonitorLGSNESIterations(TS ts,PetscInt n,PetscReal ptime,Vec v,void *monctx)
7045: {
7046:   TSMonitorLGCtx ctx = (TSMonitorLGCtx) monctx;
7047:   PetscReal      x   = ptime,y;
7049:   PetscInt       its;

7052:   if (n < 0) return(0); /* -1 indicates interpolated solution */
7053:   if (!n) {
7054:     PetscDrawAxis axis;
7055:     PetscDrawLGGetAxis(ctx->lg,&axis);
7056:     PetscDrawAxisSetLabels(axis,"Nonlinear iterations as function of time","Time","SNES Iterations");
7057:     PetscDrawLGReset(ctx->lg);
7058:     ctx->snes_its = 0;
7059:   }
7060:   TSGetSNESIterations(ts,&its);
7061:   y    = its - ctx->snes_its;
7062:   PetscDrawLGAddPoint(ctx->lg,&x,&y);
7063:   if (((ctx->howoften > 0) && (!(n % ctx->howoften)) && (n > -1)) || ((ctx->howoften == -1) && (n == -1))) {
7064:     PetscDrawLGDraw(ctx->lg);
7065:     PetscDrawLGSave(ctx->lg);
7066:   }
7067:   ctx->snes_its = its;
7068:   return(0);
7069: }

7071: PetscErrorCode TSMonitorLGKSPIterations(TS ts,PetscInt n,PetscReal ptime,Vec v,void *monctx)
7072: {
7073:   TSMonitorLGCtx ctx = (TSMonitorLGCtx) monctx;
7074:   PetscReal      x   = ptime,y;
7076:   PetscInt       its;

7079:   if (n < 0) return(0); /* -1 indicates interpolated solution */
7080:   if (!n) {
7081:     PetscDrawAxis axis;
7082:     PetscDrawLGGetAxis(ctx->lg,&axis);
7083:     PetscDrawAxisSetLabels(axis,"Linear iterations as function of time","Time","KSP Iterations");
7084:     PetscDrawLGReset(ctx->lg);
7085:     ctx->ksp_its = 0;
7086:   }
7087:   TSGetKSPIterations(ts,&its);
7088:   y    = its - ctx->ksp_its;
7089:   PetscDrawLGAddPoint(ctx->lg,&x,&y);
7090:   if (((ctx->howoften > 0) && (!(n % ctx->howoften)) && (n > -1)) || ((ctx->howoften == -1) && (n == -1))) {
7091:     PetscDrawLGDraw(ctx->lg);
7092:     PetscDrawLGSave(ctx->lg);
7093:   }
7094:   ctx->ksp_its = its;
7095:   return(0);
7096: }

7098: /*@
7099:    TSComputeLinearStability - computes the linear stability function at a point

7101:    Collective on TS

7103:    Input Parameters:
7104: +  ts - the TS context
7105: -  xr,xi - real and imaginary part of input arguments

7107:    Output Parameters:
7108: .  yr,yi - real and imaginary part of function value

7110:    Level: developer

7112: .seealso: TSSetRHSFunction(), TSComputeIFunction()
7113: @*/
7114: PetscErrorCode TSComputeLinearStability(TS ts,PetscReal xr,PetscReal xi,PetscReal *yr,PetscReal *yi)
7115: {

7120:   if (!ts->ops->linearstability) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"Linearized stability function not provided for this method");
7121:   (*ts->ops->linearstability)(ts,xr,xi,yr,yi);
7122:   return(0);
7123: }

7125: /* ------------------------------------------------------------------------*/
7126: /*@C
7127:    TSMonitorEnvelopeCtxCreate - Creates a context for use with TSMonitorEnvelope()

7129:    Collective on TS

7131:    Input Parameters:
7132: .  ts  - the ODE solver object

7134:    Output Parameter:
7135: .  ctx - the context

7137:    Level: intermediate

7139: .seealso: TSMonitorLGTimeStep(), TSMonitorSet(), TSMonitorLGSolution(), TSMonitorLGError()

7141: @*/
7142: PetscErrorCode  TSMonitorEnvelopeCtxCreate(TS ts,TSMonitorEnvelopeCtx *ctx)
7143: {

7147:   PetscNew(ctx);
7148:   return(0);
7149: }

7151: /*@C
7152:    TSMonitorEnvelope - Monitors the maximum and minimum value of each component of the solution

7154:    Collective on TS

7156:    Input Parameters:
7157: +  ts - the TS context
7158: .  step - current time-step
7159: .  ptime - current time
7160: .  u  - current solution
7161: -  dctx - the envelope context

7163:    Options Database:
7164: .  -ts_monitor_envelope

7166:    Level: intermediate

7168:    Notes:
7169:     after a solve you can use TSMonitorEnvelopeGetBounds() to access the envelope

7171: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorEnvelopeGetBounds(), TSMonitorEnvelopeCtxCreate()
7172: @*/
7173: PetscErrorCode  TSMonitorEnvelope(TS ts,PetscInt step,PetscReal ptime,Vec u,void *dctx)
7174: {
7175:   PetscErrorCode       ierr;
7176:   TSMonitorEnvelopeCtx ctx = (TSMonitorEnvelopeCtx)dctx;

7179:   if (!ctx->max) {
7180:     VecDuplicate(u,&ctx->max);
7181:     VecDuplicate(u,&ctx->min);
7182:     VecCopy(u,ctx->max);
7183:     VecCopy(u,ctx->min);
7184:   } else {
7185:     VecPointwiseMax(ctx->max,u,ctx->max);
7186:     VecPointwiseMin(ctx->min,u,ctx->min);
7187:   }
7188:   return(0);
7189: }

7191: /*@C
7192:    TSMonitorEnvelopeGetBounds - Gets the bounds for the components of the solution

7194:    Collective on TS

7196:    Input Parameter:
7197: .  ts - the TS context

7199:    Output Parameter:
7200: +  max - the maximum values
7201: -  min - the minimum values

7203:    Notes:
7204:     If the TS does not have a TSMonitorEnvelopeCtx associated with it then this function is ignored

7206:    Level: intermediate

7208: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorLGSetDisplayVariables()
7209: @*/
7210: PetscErrorCode  TSMonitorEnvelopeGetBounds(TS ts,Vec *max,Vec *min)
7211: {
7212:   PetscInt i;

7215:   if (max) *max = NULL;
7216:   if (min) *min = NULL;
7217:   for (i=0; i<ts->numbermonitors; i++) {
7218:     if (ts->monitor[i] == TSMonitorEnvelope) {
7219:       TSMonitorEnvelopeCtx  ctx = (TSMonitorEnvelopeCtx) ts->monitorcontext[i];
7220:       if (max) *max = ctx->max;
7221:       if (min) *min = ctx->min;
7222:       break;
7223:     }
7224:   }
7225:   return(0);
7226: }

7228: /*@C
7229:    TSMonitorEnvelopeCtxDestroy - Destroys a context that was created  with TSMonitorEnvelopeCtxCreate().

7231:    Collective on TSMonitorEnvelopeCtx

7233:    Input Parameter:
7234: .  ctx - the monitor context

7236:    Level: intermediate

7238: .seealso: TSMonitorLGCtxCreate(),  TSMonitorSet(), TSMonitorLGTimeStep()
7239: @*/
7240: PetscErrorCode  TSMonitorEnvelopeCtxDestroy(TSMonitorEnvelopeCtx *ctx)
7241: {

7245:   VecDestroy(&(*ctx)->min);
7246:   VecDestroy(&(*ctx)->max);
7247:   PetscFree(*ctx);
7248:   return(0);
7249: }

7251: /*@
7252:    TSRestartStep - Flags the solver to restart the next step

7254:    Collective on TS

7256:    Input Parameter:
7257: .  ts - the TS context obtained from TSCreate()

7259:    Level: advanced

7261:    Notes:
7262:    Multistep methods like BDF or Runge-Kutta methods with FSAL property require restarting the solver in the event of
7263:    discontinuities. These discontinuities may be introduced as a consequence of explicitly modifications to the solution
7264:    vector (which PETSc attempts to detect and handle) or problem coefficients (which PETSc is not able to detect). For
7265:    the sake of correctness and maximum safety, users are expected to call TSRestart() whenever they introduce
7266:    discontinuities in callback routines (e.g. prestep and poststep routines, or implicit/rhs function routines with
7267:    discontinuous source terms).

7269: .seealso: TSSolve(), TSSetPreStep(), TSSetPostStep()
7270: @*/
7271: PetscErrorCode TSRestartStep(TS ts)
7272: {
7275:   ts->steprestart = PETSC_TRUE;
7276:   return(0);
7277: }

7279: /*@
7280:    TSRollBack - Rolls back one time step

7282:    Collective on TS

7284:    Input Parameter:
7285: .  ts - the TS context obtained from TSCreate()

7287:    Level: advanced

7289: .seealso: TSCreate(), TSSetUp(), TSDestroy(), TSSolve(), TSSetPreStep(), TSSetPreStage(), TSInterpolate()
7290: @*/
7291: PetscErrorCode  TSRollBack(TS ts)
7292: {

7297:   if (ts->steprollback) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_ARG_WRONGSTATE,"TSRollBack already called");
7298:   if (!ts->ops->rollback) SETERRQ1(PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"TSRollBack not implemented for type '%s'",((PetscObject)ts)->type_name);
7299:   (*ts->ops->rollback)(ts);
7300:   ts->time_step = ts->ptime - ts->ptime_prev;
7301:   ts->ptime = ts->ptime_prev;
7302:   ts->ptime_prev = ts->ptime_prev_rollback;
7303:   ts->steps--;
7304:   ts->steprollback = PETSC_TRUE;
7305:   return(0);
7306: }

7308: /*@
7309:    TSGetStages - Get the number of stages and stage values

7311:    Input Parameter:
7312: .  ts - the TS context obtained from TSCreate()

7314:    Output Parameters:
7315: +  ns - the number of stages
7316: -  Y - the current stage vectors

7318:    Level: advanced

7320:    Notes: Both ns and Y can be NULL.

7322: .seealso: TSCreate()
7323: @*/
7324: PetscErrorCode  TSGetStages(TS ts,PetscInt *ns,Vec **Y)
7325: {

7332:   if (!ts->ops->getstages) {
7333:     if (ns) *ns = 0;
7334:     if (Y) *Y = NULL;
7335:   } else {
7336:     (*ts->ops->getstages)(ts,ns,Y);
7337:   }
7338:   return(0);
7339: }

7341: /*@C
7342:   TSComputeIJacobianDefaultColor - Computes the Jacobian using finite differences and coloring to exploit matrix sparsity.

7344:   Collective on SNES

7346:   Input Parameters:
7347: + ts - the TS context
7348: . t - current timestep
7349: . U - state vector
7350: . Udot - time derivative of state vector
7351: . shift - shift to apply, see note below
7352: - ctx - an optional user context

7354:   Output Parameters:
7355: + J - Jacobian matrix (not altered in this routine)
7356: - B - newly computed Jacobian matrix to use with preconditioner (generally the same as J)

7358:   Level: intermediate

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

7363:   dF/dU + shift*dF/dUdot

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

7368:   This will first try to get the coloring from the DM.  If the DM type has no coloring
7369:   routine, then it will try to get the coloring from the matrix.  This requires that the
7370:   matrix have nonzero entries precomputed.

7372: .seealso: TSSetIJacobian(), MatFDColoringCreate(), MatFDColoringSetFunction()
7373: @*/
7374: PetscErrorCode TSComputeIJacobianDefaultColor(TS ts,PetscReal t,Vec U,Vec Udot,PetscReal shift,Mat J,Mat B,void *ctx)
7375: {
7376:   SNES           snes;
7377:   MatFDColoring  color;
7378:   PetscBool      hascolor, matcolor = PETSC_FALSE;

7382:   PetscOptionsGetBool(((PetscObject)ts)->options,((PetscObject) ts)->prefix, "-ts_fd_color_use_mat", &matcolor, NULL);
7383:   PetscObjectQuery((PetscObject) B, "TSMatFDColoring", (PetscObject *) &color);
7384:   if (!color) {
7385:     DM         dm;
7386:     ISColoring iscoloring;

7388:     TSGetDM(ts, &dm);
7389:     DMHasColoring(dm, &hascolor);
7390:     if (hascolor && !matcolor) {
7391:       DMCreateColoring(dm, IS_COLORING_GLOBAL, &iscoloring);
7392:       MatFDColoringCreate(B, iscoloring, &color);
7393:       MatFDColoringSetFunction(color, (PetscErrorCode (*)(void)) SNESTSFormFunction, (void *) ts);
7394:       MatFDColoringSetFromOptions(color);
7395:       MatFDColoringSetUp(B, iscoloring, color);
7396:       ISColoringDestroy(&iscoloring);
7397:     } else {
7398:       MatColoring mc;

7400:       MatColoringCreate(B, &mc);
7401:       MatColoringSetDistance(mc, 2);
7402:       MatColoringSetType(mc, MATCOLORINGSL);
7403:       MatColoringSetFromOptions(mc);
7404:       MatColoringApply(mc, &iscoloring);
7405:       MatColoringDestroy(&mc);
7406:       MatFDColoringCreate(B, iscoloring, &color);
7407:       MatFDColoringSetFunction(color, (PetscErrorCode (*)(void)) SNESTSFormFunction, (void *) ts);
7408:       MatFDColoringSetFromOptions(color);
7409:       MatFDColoringSetUp(B, iscoloring, color);
7410:       ISColoringDestroy(&iscoloring);
7411:     }
7412:     PetscObjectCompose((PetscObject) B, "TSMatFDColoring", (PetscObject) color);
7413:     PetscObjectDereference((PetscObject) color);
7414:   }
7415:   TSGetSNES(ts, &snes);
7416:   MatFDColoringApply(B, color, U, snes);
7417:   if (J != B) {
7418:     MatAssemblyBegin(J, MAT_FINAL_ASSEMBLY);
7419:     MatAssemblyEnd(J, MAT_FINAL_ASSEMBLY);
7420:   }
7421:   return(0);
7422: }

7424: /*@
7425:     TSSetFunctionDomainError - Set a function that tests if the current state vector is valid

7427:     Input Parameters:
7428: +    ts - the TS context
7429: -    func - function called within TSFunctionDomainError

7431:     Calling sequence of func:
7432: $     PetscErrorCode func(TS ts,PetscReal time,Vec state,PetscBool reject)

7434: +   ts - the TS context
7435: .   time - the current time (of the stage)
7436: .   state - the state to check if it is valid
7437: -   reject - (output parameter) PETSC_FALSE if the state is acceptable, PETSC_TRUE if not acceptable

7439:     Level: intermediate

7441:     Notes:
7442:       If an implicit ODE solver is being used then, in addition to providing this routine, the
7443:       user's code should call SNESSetFunctionDomainError() when domain errors occur during
7444:       function evaluations where the functions are provided by TSSetIFunction() or TSSetRHSFunction().
7445:       Use TSGetSNES() to obtain the SNES object

7447:     Developer Notes:
7448:       The naming of this function is inconsistent with the SNESSetFunctionDomainError()
7449:       since one takes a function pointer and the other does not.

7451: .seealso: TSAdaptCheckStage(), TSFunctionDomainError(), SNESSetFunctionDomainError(), TSGetSNES()
7452: @*/

7454: PetscErrorCode TSSetFunctionDomainError(TS ts, PetscErrorCode (*func)(TS,PetscReal,Vec,PetscBool*))
7455: {
7458:   ts->functiondomainerror = func;
7459:   return(0);
7460: }

7462: /*@
7463:     TSFunctionDomainError - Checks if the current state is valid

7465:     Input Parameters:
7466: +    ts - the TS context
7467: .    stagetime - time of the simulation
7468: -    Y - state vector to check.

7470:     Output Parameter:
7471: .    accept - Set to PETSC_FALSE if the current state vector is valid.

7473:     Note:
7474:     This function is called by the TS integration routines and calls the user provided function (set with TSSetFunctionDomainError())
7475:     to check if the current state is valid.

7477:     Level: developer

7479: .seealso: TSSetFunctionDomainError()
7480: @*/
7481: PetscErrorCode TSFunctionDomainError(TS ts,PetscReal stagetime,Vec Y,PetscBool* accept)
7482: {
7485:   *accept = PETSC_TRUE;
7486:   if (ts->functiondomainerror) {
7487:     PetscStackCallStandard((*ts->functiondomainerror),(ts,stagetime,Y,accept));
7488:   }
7489:   return(0);
7490: }

7492: /*@C
7493:   TSClone - This function clones a time step object.

7495:   Collective

7497:   Input Parameter:
7498: . tsin    - The input TS

7500:   Output Parameter:
7501: . tsout   - The output TS (cloned)

7503:   Notes:
7504:   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.

7506:   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);

7508:   Level: developer

7510: .seealso: TSCreate(), TSSetType(), TSSetUp(), TSDestroy(), TSSetProblemType()
7511: @*/
7512: PetscErrorCode  TSClone(TS tsin, TS *tsout)
7513: {
7514:   TS             t;
7516:   SNES           snes_start;
7517:   DM             dm;
7518:   TSType         type;

7522:   *tsout = NULL;

7524:   PetscHeaderCreate(t, TS_CLASSID, "TS", "Time stepping", "TS", PetscObjectComm((PetscObject)tsin), TSDestroy, TSView);

7526:   /* General TS description */
7527:   t->numbermonitors    = 0;
7528:   t->setupcalled       = 0;
7529:   t->ksp_its           = 0;
7530:   t->snes_its          = 0;
7531:   t->nwork             = 0;
7532:   t->rhsjacobian.time  = PETSC_MIN_REAL;
7533:   t->rhsjacobian.scale = 1.;
7534:   t->ijacobian.shift   = 1.;

7536:   TSGetSNES(tsin,&snes_start);
7537:   TSSetSNES(t,snes_start);

7539:   TSGetDM(tsin,&dm);
7540:   TSSetDM(t,dm);

7542:   t->adapt = tsin->adapt;
7543:   PetscObjectReference((PetscObject)t->adapt);

7545:   t->trajectory = tsin->trajectory;
7546:   PetscObjectReference((PetscObject)t->trajectory);

7548:   t->event = tsin->event;
7549:   if (t->event) t->event->refct++;

7551:   t->problem_type      = tsin->problem_type;
7552:   t->ptime             = tsin->ptime;
7553:   t->ptime_prev        = tsin->ptime_prev;
7554:   t->time_step         = tsin->time_step;
7555:   t->max_time          = tsin->max_time;
7556:   t->steps             = tsin->steps;
7557:   t->max_steps         = tsin->max_steps;
7558:   t->equation_type     = tsin->equation_type;
7559:   t->atol              = tsin->atol;
7560:   t->rtol              = tsin->rtol;
7561:   t->max_snes_failures = tsin->max_snes_failures;
7562:   t->max_reject        = tsin->max_reject;
7563:   t->errorifstepfailed = tsin->errorifstepfailed;

7565:   TSGetType(tsin,&type);
7566:   TSSetType(t,type);

7568:   t->vec_sol           = NULL;

7570:   t->cfltime          = tsin->cfltime;
7571:   t->cfltime_local    = tsin->cfltime_local;
7572:   t->exact_final_time = tsin->exact_final_time;

7574:   PetscMemcpy(t->ops,tsin->ops,sizeof(struct _TSOps));

7576:   if (((PetscObject)tsin)->fortran_func_pointers) {
7577:     PetscInt i;
7578:     PetscMalloc((10)*sizeof(void(*)(void)),&((PetscObject)t)->fortran_func_pointers);
7579:     for (i=0; i<10; i++) {
7580:       ((PetscObject)t)->fortran_func_pointers[i] = ((PetscObject)tsin)->fortran_func_pointers[i];
7581:     }
7582:   }
7583:   *tsout = t;
7584:   return(0);
7585: }

7587: static PetscErrorCode RHSWrapperFunction_TSRHSJacobianTest(void* ctx,Vec x,Vec y)
7588: {
7590:   TS             ts = (TS) ctx;

7593:   TSComputeRHSFunction(ts,0,x,y);
7594:   return(0);
7595: }

7597: /*@
7598:     TSRHSJacobianTest - Compares the multiply routine provided to the MATSHELL with differencing on the TS given RHS function.

7600:    Logically Collective on TS

7602:     Input Parameters:
7603:     TS - the time stepping routine

7605:    Output Parameter:
7606: .   flg - PETSC_TRUE if the multiply is likely correct

7608:    Options Database:
7609:  .   -ts_rhs_jacobian_test_mult -mat_shell_test_mult_view - run the test at each timestep of the integrator

7611:    Level: advanced

7613:    Notes:
7614:     This only works for problems defined only the RHS function and Jacobian NOT IFunction and IJacobian

7616: .seealso: MatCreateShell(), MatShellGetContext(), MatShellGetOperation(), MatShellTestMultTranspose(), TSRHSJacobianTestTranspose()
7617: @*/
7618: PetscErrorCode  TSRHSJacobianTest(TS ts,PetscBool *flg)
7619: {
7620:   Mat            J,B;
7622:   TSRHSJacobian  func;
7623:   void*          ctx;

7626:   TSGetRHSJacobian(ts,&J,&B,&func,&ctx);
7627:   (*func)(ts,0.0,ts->vec_sol,J,B,ctx);
7628:   MatShellTestMult(J,RHSWrapperFunction_TSRHSJacobianTest,ts->vec_sol,ts,flg);
7629:   return(0);
7630: }

7632: /*@C
7633:     TSRHSJacobianTestTranspose - Compares the multiply transpose routine provided to the MATSHELL with differencing on the TS given RHS function.

7635:    Logically Collective on TS

7637:     Input Parameters:
7638:     TS - the time stepping routine

7640:    Output Parameter:
7641: .   flg - PETSC_TRUE if the multiply is likely correct

7643:    Options Database:
7644: .   -ts_rhs_jacobian_test_mult_transpose -mat_shell_test_mult_transpose_view - run the test at each timestep of the integrator

7646:    Notes:
7647:     This only works for problems defined only the RHS function and Jacobian NOT IFunction and IJacobian

7649:    Level: advanced

7651: .seealso: MatCreateShell(), MatShellGetContext(), MatShellGetOperation(), MatShellTestMultTranspose(), TSRHSJacobianTest()
7652: @*/
7653: PetscErrorCode  TSRHSJacobianTestTranspose(TS ts,PetscBool *flg)
7654: {
7655:   Mat            J,B;
7657:   void           *ctx;
7658:   TSRHSJacobian  func;

7661:   TSGetRHSJacobian(ts,&J,&B,&func,&ctx);
7662:   (*func)(ts,0.0,ts->vec_sol,J,B,ctx);
7663:   MatShellTestMultTranspose(J,RHSWrapperFunction_TSRHSJacobianTest,ts->vec_sol,ts,flg);
7664:   return(0);
7665: }

7667: /*@
7668:   TSSetUseSplitRHSFunction - Use the split RHSFunction when a multirate method is used.

7670:   Logically collective

7672:   Input Parameter:
7673: +  ts - timestepping context
7674: -  use_splitrhsfunction - PETSC_TRUE indicates that the split RHSFunction will be used

7676:   Options Database:
7677: .   -ts_use_splitrhsfunction - <true,false>

7679:   Notes:
7680:     This is only useful for multirate methods

7682:   Level: intermediate

7684: .seealso: TSGetUseSplitRHSFunction()
7685: @*/
7686: PetscErrorCode TSSetUseSplitRHSFunction(TS ts, PetscBool use_splitrhsfunction)
7687: {
7690:   ts->use_splitrhsfunction = use_splitrhsfunction;
7691:   return(0);
7692: }

7694: /*@
7695:   TSGetUseSplitRHSFunction - Gets whether to use the split RHSFunction when a multirate method is used.

7697:   Not collective

7699:   Input Parameter:
7700: .  ts - timestepping context

7702:   Output Parameter:
7703: .  use_splitrhsfunction - PETSC_TRUE indicates that the split RHSFunction will be used

7705:   Level: intermediate

7707: .seealso: TSSetUseSplitRHSFunction()
7708: @*/
7709: PetscErrorCode TSGetUseSplitRHSFunction(TS ts, PetscBool *use_splitrhsfunction)
7710: {
7713:   *use_splitrhsfunction = ts->use_splitrhsfunction;
7714:   return(0);
7715: }