Actual source code: ts.c

petsc-master 2020-08-04
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 ti,e
 91: .  -ts_max_snes_failures <maxfailures> - Maximum number of nonlinear solve failures allowed
 92: .  -ts_max_reject <maxrejects> - Maximum number of step rejections before step fails
 93: .  -ts_error_if_step_fails <true,false> - Error if no step succeeds
 94: .  -ts_rtol <rtol> - relative tolerance for local truncation error
 95: .  -ts_atol <atol> Absolute tolerance for local truncation error
 96: .  -ts_rhs_jacobian_test_mult -mat_shell_test_mult_view - test the Jacobian at each iteration against finite difference with RHS function
 97: .  -ts_rhs_jacobian_test_mult_transpose -mat_shell_test_mult_transpose_view - test the Jacobian at each iteration against finite difference with RHS function
 98: .  -ts_adjoint_solve <yes,no> After solving the ODE/DAE solve the adjoint problem (requires -ts_save_trajectory)
 99: .  -ts_fd_color - Use finite differences with coloring to compute IJacobian
100: .  -ts_monitor - print information at each timestep
101: .  -ts_monitor_lg_solution - Monitor solution graphically
102: .  -ts_monitor_lg_error - Monitor error graphically
103: .  -ts_monitor_error - Monitors norm of error
104: .  -ts_monitor_lg_timestep - Monitor timestep size graphically
105: .  -ts_monitor_lg_timestep_log - Monitor log timestep size graphically
106: .  -ts_monitor_lg_snes_iterations - Monitor number nonlinear iterations for each timestep graphically
107: .  -ts_monitor_lg_ksp_iterations - Monitor number nonlinear iterations for each timestep graphically
108: .  -ts_monitor_sp_eig - Monitor eigenvalues of linearized operator graphically
109: .  -ts_monitor_draw_solution - Monitor solution graphically
110: .  -ts_monitor_draw_solution_phase  <xleft,yleft,xright,yright> - Monitor solution graphically with phase diagram, requires problem with exactly 2 degrees of freedom
111: .  -ts_monitor_draw_error - Monitor error graphically, requires use to have provided TSSetSolutionFunction()
112: .  -ts_monitor_solution [ascii binary draw][:filename][:viewerformat] - monitors the solution at each timestep
113: .  -ts_monitor_solution_vtk <filename.vts,filename.vtu> - Save each time step to a binary file, use filename-%%03D.vts (filename-%%03D.vtu)
114: -  -ts_monitor_envelope - determine maximum and minimum value of each component of the solution over the solution time

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

119:    Level: beginner

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


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

313:   opt  = PETSC_FALSE;
314:   PetscOptionsString("-ts_monitor_solution_vtk","Save each time step to a binary file, use filename-%%03D.vts","TSMonitorSolutionVTK",NULL,monfilename,sizeof(monfilename),&flg);
315:   if (flg) {
316:     const char *ptr,*ptr2;
317:     char       *filetemplate;
318:     if (!monfilename[0]) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_USER,"-ts_monitor_solution_vtk requires a file template, e.g. filename-%%03D.vts");
319:     /* Do some cursory validation of the input. */
320:     PetscStrstr(monfilename,"%",(char**)&ptr);
321:     if (!ptr) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_USER,"-ts_monitor_solution_vtk requires a file template, e.g. filename-%%03D.vts");
322:     for (ptr++; ptr && *ptr; ptr++) {
323:       PetscStrchr("DdiouxX",*ptr,(char**)&ptr2);
324:       if (!ptr2 && (*ptr < '0' || '9' < *ptr)) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_USER,"Invalid file template argument to -ts_monitor_solution_vtk, should look like filename-%%03D.vts");
325:       if (ptr2) break;
326:     }
327:     PetscStrallocpy(monfilename,&filetemplate);
328:     TSMonitorSet(ts,TSMonitorSolutionVTK,filetemplate,(PetscErrorCode (*)(void**))TSMonitorSolutionVTKDestroy);
329:   }

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

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

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

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

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

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

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

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

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

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

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

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

416:   TSAdjointSetFromOptions(PetscOptionsObject,ts);

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

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

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

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

439:    Collective on TS

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

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

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

449:    Level: advanced

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

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

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

465:    Collective on TS

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

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

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

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

479:    Level: intermediate

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

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

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

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

499:    Collective on TS

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

504:    Level: intermediate

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

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

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

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

526:    Collective on TS

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

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

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

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

545:    Level: developer

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

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

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

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

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

620:   if (rhsjacobianfunc) {
621:     PetscLogEventBegin(TS_JacobianEval,ts,U,A,B);
622:     PetscStackPush("TS user Jacobian function");
623:     (*rhsjacobianfunc)(ts,t,U,A,B,ctx);
624:     PetscStackPop;
625:     PetscLogEventEnd(TS_JacobianEval,ts,U,A,B);
626:   } else {
627:     MatZeroEntries(A);
628:     if (B && A != B) {MatZeroEntries(B);}
629:   }
630:   ts->rhsjacobian.time  = t;
631:   ts->rhsjacobian.shift = 0;
632:   ts->rhsjacobian.scale = 1.;
633:   PetscObjectGetId((PetscObject)U,&ts->rhsjacobian.Xid);
634:   PetscObjectStateGet((PetscObject)U,&ts->rhsjacobian.Xstate);
635:   return(0);
636: }

638: /*@
639:    TSComputeRHSFunction - Evaluates the right-hand-side function.

641:    Collective on TS

643:    Input Parameters:
644: +  ts - the TS context
645: .  t - current time
646: -  U - state vector

648:    Output Parameter:
649: .  y - right hand side

651:    Note:
652:    Most users should not need to explicitly call this routine, as it
653:    is used internally within the nonlinear solvers.

655:    Level: developer

657: .seealso: TSSetRHSFunction(), TSComputeIFunction()
658: @*/
659: PetscErrorCode TSComputeRHSFunction(TS ts,PetscReal t,Vec U,Vec y)
660: {
662:   TSRHSFunction  rhsfunction;
663:   TSIFunction    ifunction;
664:   void           *ctx;
665:   DM             dm;

671:   TSGetDM(ts,&dm);
672:   DMTSGetRHSFunction(dm,&rhsfunction,&ctx);
673:   DMTSGetIFunction(dm,&ifunction,NULL);

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

677:   PetscLogEventBegin(TS_FunctionEval,ts,U,y,0);
678:   if (rhsfunction) {
679:     VecLockReadPush(U);
680:     PetscStackPush("TS user right-hand-side function");
681:     (*rhsfunction)(ts,t,U,y,ctx);
682:     PetscStackPop;
683:     VecLockReadPop(U);
684:   } else {
685:     VecZeroEntries(y);
686:   }

688:   PetscLogEventEnd(TS_FunctionEval,ts,U,y,0);
689:   return(0);
690: }

692: /*@
693:    TSComputeSolutionFunction - Evaluates the solution function.

695:    Collective on TS

697:    Input Parameters:
698: +  ts - the TS context
699: -  t - current time

701:    Output Parameter:
702: .  U - the solution

704:    Note:
705:    Most users should not need to explicitly call this routine, as it
706:    is used internally within the nonlinear solvers.

708:    Level: developer

710: .seealso: TSSetSolutionFunction(), TSSetRHSFunction(), TSComputeIFunction()
711: @*/
712: PetscErrorCode TSComputeSolutionFunction(TS ts,PetscReal t,Vec U)
713: {
714:   PetscErrorCode     ierr;
715:   TSSolutionFunction solutionfunction;
716:   void               *ctx;
717:   DM                 dm;

722:   TSGetDM(ts,&dm);
723:   DMTSGetSolutionFunction(dm,&solutionfunction,&ctx);

725:   if (solutionfunction) {
726:     PetscStackPush("TS user solution function");
727:     (*solutionfunction)(ts,t,U,ctx);
728:     PetscStackPop;
729:   }
730:   return(0);
731: }
732: /*@
733:    TSComputeForcingFunction - Evaluates the forcing function.

735:    Collective on TS

737:    Input Parameters:
738: +  ts - the TS context
739: -  t - current time

741:    Output Parameter:
742: .  U - the function value

744:    Note:
745:    Most users should not need to explicitly call this routine, as it
746:    is used internally within the nonlinear solvers.

748:    Level: developer

750: .seealso: TSSetSolutionFunction(), TSSetRHSFunction(), TSComputeIFunction()
751: @*/
752: PetscErrorCode TSComputeForcingFunction(TS ts,PetscReal t,Vec U)
753: {
754:   PetscErrorCode     ierr, (*forcing)(TS,PetscReal,Vec,void*);
755:   void               *ctx;
756:   DM                 dm;

761:   TSGetDM(ts,&dm);
762:   DMTSGetForcingFunction(dm,&forcing,&ctx);

764:   if (forcing) {
765:     PetscStackPush("TS user forcing function");
766:     (*forcing)(ts,t,U,ctx);
767:     PetscStackPop;
768:   }
769:   return(0);
770: }

772: static PetscErrorCode TSGetRHSVec_Private(TS ts,Vec *Frhs)
773: {
774:   Vec            F;

778:   *Frhs = NULL;
779:   TSGetIFunction(ts,&F,NULL,NULL);
780:   if (!ts->Frhs) {
781:     VecDuplicate(F,&ts->Frhs);
782:   }
783:   *Frhs = ts->Frhs;
784:   return(0);
785: }

787: PetscErrorCode TSGetRHSMats_Private(TS ts,Mat *Arhs,Mat *Brhs)
788: {
789:   Mat            A,B;
791:   TSIJacobian    ijacobian;

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

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

839:    Collective on TS

841:    Input Parameters:
842: +  ts - the TS context
843: .  t - current time
844: .  U - state vector
845: .  Udot - time derivative of state vector
846: -  imex - flag indicates if the method is IMEX so that the RHSFunction should be kept separate

848:    Output Parameter:
849: .  Y - right hand side

851:    Note:
852:    Most users should not need to explicitly call this routine, as it
853:    is used internally within the nonlinear solvers.

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

858:    Level: developer

860: .seealso: TSSetIFunction(), TSComputeRHSFunction()
861: @*/
862: PetscErrorCode TSComputeIFunction(TS ts,PetscReal t,Vec U,Vec Udot,Vec Y,PetscBool imex)
863: {
865:   TSIFunction    ifunction;
866:   TSRHSFunction  rhsfunction;
867:   void           *ctx;
868:   DM             dm;


876:   TSGetDM(ts,&dm);
877:   DMTSGetIFunction(dm,&ifunction,&ctx);
878:   DMTSGetRHSFunction(dm,&rhsfunction,NULL);

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

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

907: /*@
908:    TSComputeIJacobian - Evaluates the Jacobian of the DAE

910:    Collective on TS

912:    Input
913:       Input Parameters:
914: +  ts - the TS context
915: .  t - current timestep
916: .  U - state vector
917: .  Udot - time derivative of state vector
918: .  shift - shift to apply, see note below
919: -  imex - flag indicates if the method is IMEX so that the RHSJacobian should be kept separate

921:    Output Parameters:
922: +  A - Jacobian matrix
923: -  B - matrix from which the preconditioner is constructed; often the same as A

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

928:    dF/dU + shift*dF/dUdot

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

933:    Level: developer

935: .seealso:  TSSetIJacobian()
936: @*/
937: PetscErrorCode TSComputeIJacobian(TS ts,PetscReal t,Vec U,Vec Udot,PetscReal shift,Mat A,Mat B,PetscBool imex)
938: {
940:   TSIJacobian    ijacobian;
941:   TSRHSJacobian  rhsjacobian;
942:   DM             dm;
943:   void           *ctx;


954:   TSGetDM(ts,&dm);
955:   DMTSGetIJacobian(dm,&ijacobian,&ctx);
956:   DMTSGetRHSJacobian(dm,&rhsjacobian,NULL);

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

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

1034: /*@C
1035:     TSSetRHSFunction - Sets the routine for evaluating the function,
1036:     where U_t = G(t,u).

1038:     Logically Collective on TS

1040:     Input Parameters:
1041: +   ts - the TS context obtained from TSCreate()
1042: .   r - vector to put the computed right hand side (or NULL to have it created)
1043: .   f - routine for evaluating the right-hand-side function
1044: -   ctx - [optional] user-defined context for private data for the
1045:           function evaluation routine (may be NULL)

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

1050: +   t - current timestep
1051: .   u - input vector
1052: .   F - function vector
1053: -   ctx - [optional] user-defined function context

1055:     Level: beginner

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

1060: .seealso: TSSetRHSJacobian(), TSSetIJacobian(), TSSetIFunction()
1061: @*/
1062: PetscErrorCode  TSSetRHSFunction(TS ts,Vec r,PetscErrorCode (*f)(TS,PetscReal,Vec,Vec,void*),void *ctx)
1063: {
1065:   SNES           snes;
1066:   Vec            ralloc = NULL;
1067:   DM             dm;


1073:   TSGetDM(ts,&dm);
1074:   DMTSSetRHSFunction(dm,f,ctx);
1075:   TSGetSNES(ts,&snes);
1076:   if (!r && !ts->dm && ts->vec_sol) {
1077:     VecDuplicate(ts->vec_sol,&ralloc);
1078:     r = ralloc;
1079:   }
1080:   SNESSetFunction(snes,r,SNESTSFormFunction,ts);
1081:   VecDestroy(&ralloc);
1082:   return(0);
1083: }

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

1088:     Logically Collective on TS

1090:     Input Parameters:
1091: +   ts - the TS context obtained from TSCreate()
1092: .   f - routine for evaluating the solution
1093: -   ctx - [optional] user-defined context for private data for the
1094:           function evaluation routine (may be NULL)

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

1099: +   t - current timestep
1100: .   u - output vector
1101: -   ctx - [optional] user-defined function context

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

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

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

1114:     Level: beginner

1116: .seealso: TSSetRHSJacobian(), TSSetIJacobian(), TSComputeSolutionFunction(), TSSetForcingFunction(), TSSetSolution(), TSGetSolution(), TSMonitorLGError(), TSMonitorDrawError()
1117: @*/
1118: PetscErrorCode  TSSetSolutionFunction(TS ts,PetscErrorCode (*f)(TS,PetscReal,Vec,void*),void *ctx)
1119: {
1121:   DM             dm;

1125:   TSGetDM(ts,&dm);
1126:   DMTSSetSolutionFunction(dm,f,ctx);
1127:   return(0);
1128: }

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

1133:     Logically Collective on TS

1135:     Input Parameters:
1136: +   ts - the TS context obtained from TSCreate()
1137: .   func - routine for evaluating the forcing function
1138: -   ctx - [optional] user-defined context for private data for the
1139:           function evaluation routine (may be NULL)

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

1144: +   t - current timestep
1145: .   f - output vector
1146: -   ctx - [optional] user-defined function context

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

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

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

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

1160:     Level: beginner

1162: .seealso: TSSetRHSJacobian(), TSSetIJacobian(), TSComputeSolutionFunction(), TSSetSolutionFunction()
1163: @*/
1164: PetscErrorCode  TSSetForcingFunction(TS ts,TSForcingFunction func,void *ctx)
1165: {
1167:   DM             dm;

1171:   TSGetDM(ts,&dm);
1172:   DMTSSetForcingFunction(dm,func,ctx);
1173:   return(0);
1174: }

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

1180:    Logically Collective on TS

1182:    Input Parameters:
1183: +  ts  - the TS context obtained from TSCreate()
1184: .  Amat - (approximate) Jacobian matrix
1185: .  Pmat - matrix from which preconditioner is to be constructed (usually the same as Amat)
1186: .  f   - the Jacobian evaluation routine
1187: -  ctx - [optional] user-defined context for private data for the
1188:          Jacobian evaluation routine (may be NULL)

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

1193: +  t - current timestep
1194: .  u - input vector
1195: .  Amat - (approximate) Jacobian matrix
1196: .  Pmat - matrix from which preconditioner is to be constructed (usually the same as Amat)
1197: -  ctx - [optional] user-defined context for matrix evaluation routine

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

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

1205:    Level: beginner

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

1209: @*/
1210: PetscErrorCode  TSSetRHSJacobian(TS ts,Mat Amat,Mat Pmat,TSRHSJacobian f,void *ctx)
1211: {
1213:   SNES           snes;
1214:   DM             dm;
1215:   TSIJacobian    ijacobian;


1224:   TSGetDM(ts,&dm);
1225:   DMTSSetRHSJacobian(dm,f,ctx);
1226:   if (f == TSComputeRHSJacobianConstant) {
1227:     /* Handle this case automatically for the user; otherwise user should call themselves. */
1228:     TSRHSJacobianSetReuse(ts,PETSC_TRUE);
1229:   }
1230:   DMTSGetIJacobian(dm,&ijacobian,NULL);
1231:   TSGetSNES(ts,&snes);
1232:   if (!ijacobian) {
1233:     SNESSetJacobian(snes,Amat,Pmat,SNESTSFormJacobian,ts);
1234:   }
1235:   if (Amat) {
1236:     PetscObjectReference((PetscObject)Amat);
1237:     MatDestroy(&ts->Arhs);
1238:     ts->Arhs = Amat;
1239:   }
1240:   if (Pmat) {
1241:     PetscObjectReference((PetscObject)Pmat);
1242:     MatDestroy(&ts->Brhs);
1243:     ts->Brhs = Pmat;
1244:   }
1245:   return(0);
1246: }

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

1251:    Logically Collective on TS

1253:    Input Parameters:
1254: +  ts  - the TS context obtained from TSCreate()
1255: .  r   - vector to hold the residual (or NULL to have it created internally)
1256: .  f   - the function evaluation routine
1257: -  ctx - user-defined context for private data for the function evaluation routine (may be NULL)

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

1262: +  t   - time at step/stage being solved
1263: .  u   - state vector
1264: .  u_t - time derivative of state vector
1265: .  F   - function vector
1266: -  ctx - [optional] user-defined context for matrix evaluation routine

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

1271:    Level: beginner

1273: .seealso: TSSetRHSJacobian(), TSSetRHSFunction(), TSSetIJacobian()
1274: @*/
1275: PetscErrorCode  TSSetIFunction(TS ts,Vec r,TSIFunction f,void *ctx)
1276: {
1278:   SNES           snes;
1279:   Vec            ralloc = NULL;
1280:   DM             dm;


1286:   TSGetDM(ts,&dm);
1287:   DMTSSetIFunction(dm,f,ctx);

1289:   TSGetSNES(ts,&snes);
1290:   if (!r && !ts->dm && ts->vec_sol) {
1291:     VecDuplicate(ts->vec_sol,&ralloc);
1292:     r  = ralloc;
1293:   }
1294:   SNESSetFunction(snes,r,SNESTSFormFunction,ts);
1295:   VecDestroy(&ralloc);
1296:   return(0);
1297: }

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

1302:    Not Collective

1304:    Input Parameter:
1305: .  ts - the TS context

1307:    Output Parameter:
1308: +  r - vector to hold residual (or NULL)
1309: .  func - the function to compute residual (or NULL)
1310: -  ctx - the function context (or NULL)

1312:    Level: advanced

1314: .seealso: TSSetIFunction(), SNESGetFunction()
1315: @*/
1316: PetscErrorCode TSGetIFunction(TS ts,Vec *r,TSIFunction *func,void **ctx)
1317: {
1319:   SNES           snes;
1320:   DM             dm;

1324:   TSGetSNES(ts,&snes);
1325:   SNESGetFunction(snes,r,NULL,NULL);
1326:   TSGetDM(ts,&dm);
1327:   DMTSGetIFunction(dm,func,ctx);
1328:   return(0);
1329: }

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

1334:    Not Collective

1336:    Input Parameter:
1337: .  ts - the TS context

1339:    Output Parameter:
1340: +  r - vector to hold computed right hand side (or NULL)
1341: .  func - the function to compute right hand side (or NULL)
1342: -  ctx - the function context (or NULL)

1344:    Level: advanced

1346: .seealso: TSSetRHSFunction(), SNESGetFunction()
1347: @*/
1348: PetscErrorCode TSGetRHSFunction(TS ts,Vec *r,TSRHSFunction *func,void **ctx)
1349: {
1351:   SNES           snes;
1352:   DM             dm;

1356:   TSGetSNES(ts,&snes);
1357:   SNESGetFunction(snes,r,NULL,NULL);
1358:   TSGetDM(ts,&dm);
1359:   DMTSGetRHSFunction(dm,func,ctx);
1360:   return(0);
1361: }

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

1367:    Logically Collective on TS

1369:    Input Parameters:
1370: +  ts  - the TS context obtained from TSCreate()
1371: .  Amat - (approximate) Jacobian matrix
1372: .  Pmat - matrix used to compute preconditioner (usually the same as Amat)
1373: .  f   - the Jacobian evaluation routine
1374: -  ctx - user-defined context for private data for the Jacobian evaluation routine (may be NULL)

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

1379: +  t    - time at step/stage being solved
1380: .  U    - state vector
1381: .  U_t  - time derivative of state vector
1382: .  a    - shift
1383: .  Amat - (approximate) Jacobian of F(t,U,W+a*U), equivalent to dF/dU + a*dF/dU_t
1384: .  Pmat - matrix used for constructing preconditioner, usually the same as Amat
1385: -  ctx  - [optional] user-defined context for matrix evaluation routine

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

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

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

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

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

1405:    Level: beginner

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

1409: @*/
1410: PetscErrorCode  TSSetIJacobian(TS ts,Mat Amat,Mat Pmat,TSIJacobian f,void *ctx)
1411: {
1413:   SNES           snes;
1414:   DM             dm;


1423:   TSGetDM(ts,&dm);
1424:   DMTSSetIJacobian(dm,f,ctx);

1426:   TSGetSNES(ts,&snes);
1427:   SNESSetJacobian(snes,Amat,Pmat,SNESTSFormJacobian,ts);
1428:   return(0);
1429: }

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

1437:    Logically Collective

1439:    Input Arguments:
1440: +  ts - TS context obtained from TSCreate()
1441: -  reuse - PETSC_TRUE if the RHS Jacobian

1443:    Level: intermediate

1445: .seealso: TSSetRHSJacobian(), TSComputeRHSJacobianConstant()
1446: @*/
1447: PetscErrorCode TSRHSJacobianSetReuse(TS ts,PetscBool reuse)
1448: {
1450:   ts->rhsjacobian.reuse = reuse;
1451:   return(0);
1452: }

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

1457:    Logically Collective on TS

1459:    Input Parameters:
1460: +  ts  - the TS context obtained from TSCreate()
1461: .  F   - vector to hold the residual (or NULL to have it created internally)
1462: .  fun - the function evaluation routine
1463: -  ctx - user-defined context for private data for the function evaluation routine (may be NULL)

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

1468: +  t    - time at step/stage being solved
1469: .  U    - state vector
1470: .  U_t  - time derivative of state vector
1471: .  U_tt - second time derivative of state vector
1472: .  F    - function vector
1473: -  ctx  - [optional] user-defined context for matrix evaluation routine (may be NULL)

1475:    Level: beginner

1477: .seealso: TSSetI2Jacobian()
1478: @*/
1479: PetscErrorCode TSSetI2Function(TS ts,Vec F,TSI2Function fun,void *ctx)
1480: {
1481:   DM             dm;

1487:   TSSetIFunction(ts,F,NULL,NULL);
1488:   TSGetDM(ts,&dm);
1489:   DMTSSetI2Function(dm,fun,ctx);
1490:   return(0);
1491: }

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

1496:   Not Collective

1498:   Input Parameter:
1499: . ts - the TS context

1501:   Output Parameter:
1502: + r - vector to hold residual (or NULL)
1503: . fun - the function to compute residual (or NULL)
1504: - ctx - the function context (or NULL)

1506:   Level: advanced

1508: .seealso: TSSetI2Function(), SNESGetFunction()
1509: @*/
1510: PetscErrorCode TSGetI2Function(TS ts,Vec *r,TSI2Function *fun,void **ctx)
1511: {
1513:   SNES           snes;
1514:   DM             dm;

1518:   TSGetSNES(ts,&snes);
1519:   SNESGetFunction(snes,r,NULL,NULL);
1520:   TSGetDM(ts,&dm);
1521:   DMTSGetI2Function(dm,fun,ctx);
1522:   return(0);
1523: }

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

1529:    Logically Collective on TS

1531:    Input Parameters:
1532: +  ts  - the TS context obtained from TSCreate()
1533: .  J   - Jacobian matrix
1534: .  P   - preconditioning matrix for J (may be same as J)
1535: .  jac - the Jacobian evaluation routine
1536: -  ctx - user-defined context for private data for the Jacobian evaluation routine (may be NULL)

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

1541: +  t    - time at step/stage being solved
1542: .  U    - state vector
1543: .  U_t  - time derivative of state vector
1544: .  U_tt - second time derivative of state vector
1545: .  v    - shift for U_t
1546: .  a    - shift for U_tt
1547: .  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
1548: .  P    - preconditioning matrix for J, may be same as J
1549: -  ctx  - [optional] user-defined context for matrix evaluation routine

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

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

1559:    Level: beginner

1561: .seealso: TSSetI2Function()
1562: @*/
1563: PetscErrorCode TSSetI2Jacobian(TS ts,Mat J,Mat P,TSI2Jacobian jac,void *ctx)
1564: {
1565:   DM             dm;

1572:   TSSetIJacobian(ts,J,P,NULL,NULL);
1573:   TSGetDM(ts,&dm);
1574:   DMTSSetI2Jacobian(dm,jac,ctx);
1575:   return(0);
1576: }

1578: /*@C
1579:   TSGetI2Jacobian - Returns the implicit Jacobian at the present timestep.

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

1583:   Input Parameter:
1584: . ts  - The TS context obtained from TSCreate()

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

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

1595:   Level: advanced

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

1599: @*/
1600: PetscErrorCode  TSGetI2Jacobian(TS ts,Mat *J,Mat *P,TSI2Jacobian *jac,void **ctx)
1601: {
1603:   SNES           snes;
1604:   DM             dm;

1607:   TSGetSNES(ts,&snes);
1608:   SNESSetUpMatrices(snes);
1609:   SNESGetJacobian(snes,J,P,NULL,NULL);
1610:   TSGetDM(ts,&dm);
1611:   DMTSGetI2Jacobian(dm,jac,ctx);
1612:   return(0);
1613: }

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

1618:   Collective on TS

1620:   Input Parameters:
1621: + ts - the TS context
1622: . t - current time
1623: . U - state vector
1624: . V - time derivative of state vector (U_t)
1625: - A - second time derivative of state vector (U_tt)

1627:   Output Parameter:
1628: . F - the residual vector

1630:   Note:
1631:   Most users should not need to explicitly call this routine, as it
1632:   is used internally within the nonlinear solvers.

1634:   Level: developer

1636: .seealso: TSSetI2Function()
1637: @*/
1638: PetscErrorCode TSComputeI2Function(TS ts,PetscReal t,Vec U,Vec V,Vec A,Vec F)
1639: {
1640:   DM             dm;
1641:   TSI2Function   I2Function;
1642:   void           *ctx;
1643:   TSRHSFunction  rhsfunction;


1653:   TSGetDM(ts,&dm);
1654:   DMTSGetI2Function(dm,&I2Function,&ctx);
1655:   DMTSGetRHSFunction(dm,&rhsfunction,NULL);

1657:   if (!I2Function) {
1658:     TSComputeIFunction(ts,t,U,A,F,PETSC_FALSE);
1659:     return(0);
1660:   }

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

1664:   PetscStackPush("TS user implicit function");
1665:   I2Function(ts,t,U,V,A,F,ctx);
1666:   PetscStackPop;

1668:   if (rhsfunction) {
1669:     Vec Frhs;
1670:     TSGetRHSVec_Private(ts,&Frhs);
1671:     TSComputeRHSFunction(ts,t,U,Frhs);
1672:     VecAXPY(F,-1,Frhs);
1673:   }

1675:   PetscLogEventEnd(TS_FunctionEval,ts,U,V,F);
1676:   return(0);
1677: }

1679: /*@
1680:   TSComputeI2Jacobian - Evaluates the Jacobian of the DAE

1682:   Collective on TS

1684:   Input Parameters:
1685: + ts - the TS context
1686: . t - current timestep
1687: . U - state vector
1688: . V - time derivative of state vector
1689: . A - second time derivative of state vector
1690: . shiftV - shift to apply, see note below
1691: - shiftA - shift to apply, see note below

1693:   Output Parameters:
1694: + J - Jacobian matrix
1695: - P - optional preconditioning matrix

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

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

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

1705:   Level: developer

1707: .seealso:  TSSetI2Jacobian()
1708: @*/
1709: PetscErrorCode TSComputeI2Jacobian(TS ts,PetscReal t,Vec U,Vec V,Vec A,PetscReal shiftV,PetscReal shiftA,Mat J,Mat P)
1710: {
1711:   DM             dm;
1712:   TSI2Jacobian   I2Jacobian;
1713:   void           *ctx;
1714:   TSRHSJacobian  rhsjacobian;


1725:   TSGetDM(ts,&dm);
1726:   DMTSGetI2Jacobian(dm,&I2Jacobian,&ctx);
1727:   DMTSGetRHSJacobian(dm,&rhsjacobian,NULL);

1729:   if (!I2Jacobian) {
1730:     TSComputeIJacobian(ts,t,U,A,shiftA,J,P,PETSC_FALSE);
1731:     return(0);
1732:   }

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

1736:   PetscStackPush("TS user implicit Jacobian");
1737:   I2Jacobian(ts,t,U,V,A,shiftV,shiftA,J,P,ctx);
1738:   PetscStackPop;

1740:   if (rhsjacobian) {
1741:     Mat Jrhs,Prhs; MatStructure axpy = DIFFERENT_NONZERO_PATTERN;
1742:     TSGetRHSMats_Private(ts,&Jrhs,&Prhs);
1743:     TSComputeRHSJacobian(ts,t,U,Jrhs,Prhs);
1744:     MatAXPY(J,-1,Jrhs,axpy);
1745:     if (P != J) {MatAXPY(P,-1,Prhs,axpy);}
1746:   }

1748:   PetscLogEventEnd(TS_JacobianEval,ts,U,J,P);
1749:   return(0);
1750: }

1752: /*@C
1753:    TSSetTransientVariable - sets function to transform from state to transient variables

1755:    Logically Collective

1757:    Input Arguments:
1758: +  ts - time stepping context on which to change the transient variable
1759: .  tvar - a function that transforms in-place to transient variables
1760: -  ctx - a context for tvar

1762:    Level: advanced

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

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

1773: .seealso: DMTSSetTransientVariable(), DMTSGetTransientVariable(), TSSetIFunction(), TSSetIJacobian()
1774: @*/
1775: PetscErrorCode TSSetTransientVariable(TS ts,TSTransientVariable tvar,void *ctx)
1776: {
1778:   DM             dm;

1782:   TSGetDM(ts,&dm);
1783:   DMTSSetTransientVariable(dm,tvar,ctx);
1784:   return(0);
1785: }

1787: /*@
1788:    TSComputeTransientVariable - transforms state (primitive) variables to transient (conservative) variables

1790:    Logically Collective

1792:    Input Parameters:
1793: +  ts - TS on which to compute
1794: -  U - state vector to be transformed to transient variables

1796:    Output Parameters:
1797: .  C - transient (conservative) variable

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

1804:    Level: developer

1806: .seealso: DMTSSetTransientVariable(), TSComputeIFunction(), TSComputeIJacobian()
1807: @*/
1808: PetscErrorCode TSComputeTransientVariable(TS ts,Vec U,Vec C)
1809: {
1811:   DM             dm;
1812:   DMTS           dmts;

1817:   TSGetDM(ts,&dm);
1818:   DMGetDMTS(dm,&dmts);
1819:   if (dmts->ops->transientvar) {
1821:     (*dmts->ops->transientvar)(ts,U,C,dmts->transientvarctx);
1822:   }
1823:   return(0);
1824: }

1826: /*@
1827:    TSHasTransientVariable - determine whether transient variables have been set

1829:    Logically Collective

1831:    Input Parameters:
1832: .  ts - TS on which to compute

1834:    Output Parameters:
1835: .  has - PETSC_TRUE if transient variables have been set

1837:    Level: developer

1839: .seealso: DMTSSetTransientVariable(), TSComputeTransientVariable()
1840: @*/
1841: PetscErrorCode TSHasTransientVariable(TS ts,PetscBool *has)
1842: {
1844:   DM             dm;
1845:   DMTS           dmts;

1849:   TSGetDM(ts,&dm);
1850:   DMGetDMTS(dm,&dmts);
1851:   *has = dmts->ops->transientvar ? PETSC_TRUE : PETSC_FALSE;
1852:   return(0);
1853: }

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

1859:    Logically Collective on TS

1861:    Input Parameters:
1862: +  ts - the TS context obtained from TSCreate()
1863: .  u - the solution vector
1864: -  v - the time derivative vector

1866:    Level: beginner

1868: @*/
1869: PetscErrorCode  TS2SetSolution(TS ts,Vec u,Vec v)
1870: {

1877:   TSSetSolution(ts,u);
1878:   PetscObjectReference((PetscObject)v);
1879:   VecDestroy(&ts->vec_dot);
1880:   ts->vec_dot = v;
1881:   return(0);
1882: }

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

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

1892:    Input Parameter:
1893: .  ts - the TS context obtained from TSCreate()

1895:    Output Parameter:
1896: +  u - the vector containing the solution
1897: -  v - the vector containing the time derivative

1899:    Level: intermediate

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

1903: @*/
1904: PetscErrorCode  TS2GetSolution(TS ts,Vec *u,Vec *v)
1905: {
1910:   if (u) *u = ts->vec_sol;
1911:   if (v) *v = ts->vec_dot;
1912:   return(0);
1913: }

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

1918:   Collective on PetscViewer

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

1925:    Level: intermediate

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

1930:   Notes for advanced users:
1931:   Most users should not need to know the details of the binary storage
1932:   format, since TSLoad() and TSView() completely hide these details.
1933:   But for anyone who's interested, the standard binary matrix storage
1934:   format is
1935: .vb
1936:      has not yet been determined
1937: .ve

1939: .seealso: PetscViewerBinaryOpen(), TSView(), MatLoad(), VecLoad()
1940: @*/
1941: PetscErrorCode  TSLoad(TS ts, PetscViewer viewer)
1942: {
1944:   PetscBool      isbinary;
1945:   PetscInt       classid;
1946:   char           type[256];
1947:   DMTS           sdm;
1948:   DM             dm;

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

1956:   PetscViewerBinaryRead(viewer,&classid,1,NULL,PETSC_INT);
1957:   if (classid != TS_FILE_CLASSID) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_ARG_WRONG,"Not TS next in file");
1958:   PetscViewerBinaryRead(viewer,type,256,NULL,PETSC_CHAR);
1959:   TSSetType(ts, type);
1960:   if (ts->ops->load) {
1961:     (*ts->ops->load)(ts,viewer);
1962:   }
1963:   DMCreate(PetscObjectComm((PetscObject)ts),&dm);
1964:   DMLoad(dm,viewer);
1965:   TSSetDM(ts,dm);
1966:   DMCreateGlobalVector(ts->dm,&ts->vec_sol);
1967:   VecLoad(ts->vec_sol,viewer);
1968:   DMGetDMTS(ts->dm,&sdm);
1969:   DMTSLoad(sdm,viewer);
1970:   return(0);
1971: }

1973:  #include <petscdraw.h>
1974: #if defined(PETSC_HAVE_SAWS)
1975:  #include <petscviewersaws.h>
1976: #endif

1978: /*@C
1979:    TSViewFromOptions - View from Options

1981:    Collective on TS

1983:    Input Parameters:
1984: +  A - the Section 1.5 Writing Application Codes with PETSc ordering context
1985: .  obj - Optional object
1986: -  name - command line option

1988:    Level: intermediate
1989: .seealso:  TS, TSView, PetscObjectViewFromOptions(), TSCreate()
1990: @*/
1991: PetscErrorCode  TSViewFromOptions(TS A,PetscObject obj,const char name[])
1992: {

1997:   PetscObjectViewFromOptions((PetscObject)A,obj,name);
1998:   return(0);
1999: }

2001: /*@C
2002:     TSView - Prints the TS data structure.

2004:     Collective on TS

2006:     Input Parameters:
2007: +   ts - the TS context obtained from TSCreate()
2008: -   viewer - visualization context

2010:     Options Database Key:
2011: .   -ts_view - calls TSView() at end of TSStep()

2013:     Notes:
2014:     The available visualization contexts include
2015: +     PETSC_VIEWER_STDOUT_SELF - standard output (default)
2016: -     PETSC_VIEWER_STDOUT_WORLD - synchronized standard
2017:          output where only the first processor opens
2018:          the file.  All other processors send their
2019:          data to the first processor to print.

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

2024:     Level: beginner

2026: .seealso: PetscViewerASCIIOpen()
2027: @*/
2028: PetscErrorCode  TSView(TS ts,PetscViewer viewer)
2029: {
2031:   TSType         type;
2032:   PetscBool      iascii,isstring,isundials,isbinary,isdraw;
2033:   DMTS           sdm;
2034: #if defined(PETSC_HAVE_SAWS)
2035:   PetscBool      issaws;
2036: #endif

2040:   if (!viewer) {
2041:     PetscViewerASCIIGetStdout(PetscObjectComm((PetscObject)ts),&viewer);
2042:   }

2046:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERASCII,&iascii);
2047:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERSTRING,&isstring);
2048:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERBINARY,&isbinary);
2049:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERDRAW,&isdraw);
2050: #if defined(PETSC_HAVE_SAWS)
2051:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERSAWS,&issaws);
2052: #endif
2053:   if (iascii) {
2054:     PetscObjectPrintClassNamePrefixType((PetscObject)ts,viewer);
2055:     if (ts->ops->view) {
2056:       PetscViewerASCIIPushTab(viewer);
2057:       (*ts->ops->view)(ts,viewer);
2058:       PetscViewerASCIIPopTab(viewer);
2059:     }
2060:     if (ts->max_steps < PETSC_MAX_INT) {
2061:       PetscViewerASCIIPrintf(viewer,"  maximum steps=%D\n",ts->max_steps);
2062:     }
2063:     if (ts->max_time < PETSC_MAX_REAL) {
2064:       PetscViewerASCIIPrintf(viewer,"  maximum time=%g\n",(double)ts->max_time);
2065:     }
2066:     if (ts->usessnes) {
2067:       PetscBool lin;
2068:       if (ts->problem_type == TS_NONLINEAR) {
2069:         PetscViewerASCIIPrintf(viewer,"  total number of nonlinear solver iterations=%D\n",ts->snes_its);
2070:       }
2071:       PetscViewerASCIIPrintf(viewer,"  total number of linear solver iterations=%D\n",ts->ksp_its);
2072:       PetscObjectTypeCompareAny((PetscObject)ts->snes,&lin,SNESKSPONLY,SNESKSPTRANSPOSEONLY,"");
2073:       PetscViewerASCIIPrintf(viewer,"  total number of %slinear solve failures=%D\n",lin ? "" : "non",ts->num_snes_failures);
2074:     }
2075:     PetscViewerASCIIPrintf(viewer,"  total number of rejected steps=%D\n",ts->reject);
2076:     if (ts->vrtol) {
2077:       PetscViewerASCIIPrintf(viewer,"  using vector of relative error tolerances, ");
2078:     } else {
2079:       PetscViewerASCIIPrintf(viewer,"  using relative error tolerance of %g, ",(double)ts->rtol);
2080:     }
2081:     if (ts->vatol) {
2082:       PetscViewerASCIIPrintf(viewer,"  using vector of absolute error tolerances\n");
2083:     } else {
2084:       PetscViewerASCIIPrintf(viewer,"  using absolute error tolerance of %g\n",(double)ts->atol);
2085:     }
2086:     PetscViewerASCIIPushTab(viewer);
2087:     TSAdaptView(ts->adapt,viewer);
2088:     PetscViewerASCIIPopTab(viewer);
2089:   } else if (isstring) {
2090:     TSGetType(ts,&type);
2091:     PetscViewerStringSPrintf(viewer," TSType: %-7.7s",type);
2092:     if (ts->ops->view) {(*ts->ops->view)(ts,viewer);}
2093:   } else if (isbinary) {
2094:     PetscInt    classid = TS_FILE_CLASSID;
2095:     MPI_Comm    comm;
2096:     PetscMPIInt rank;
2097:     char        type[256];

2099:     PetscObjectGetComm((PetscObject)ts,&comm);
2100:     MPI_Comm_rank(comm,&rank);
2101:     if (!rank) {
2102:       PetscViewerBinaryWrite(viewer,&classid,1,PETSC_INT);
2103:       PetscStrncpy(type,((PetscObject)ts)->type_name,256);
2104:       PetscViewerBinaryWrite(viewer,type,256,PETSC_CHAR);
2105:     }
2106:     if (ts->ops->view) {
2107:       (*ts->ops->view)(ts,viewer);
2108:     }
2109:     if (ts->adapt) {TSAdaptView(ts->adapt,viewer);}
2110:     DMView(ts->dm,viewer);
2111:     VecView(ts->vec_sol,viewer);
2112:     DMGetDMTS(ts->dm,&sdm);
2113:     DMTSView(sdm,viewer);
2114:   } else if (isdraw) {
2115:     PetscDraw draw;
2116:     char      str[36];
2117:     PetscReal x,y,bottom,h;

2119:     PetscViewerDrawGetDraw(viewer,0,&draw);
2120:     PetscDrawGetCurrentPoint(draw,&x,&y);
2121:     PetscStrcpy(str,"TS: ");
2122:     PetscStrcat(str,((PetscObject)ts)->type_name);
2123:     PetscDrawStringBoxed(draw,x,y,PETSC_DRAW_BLACK,PETSC_DRAW_BLACK,str,NULL,&h);
2124:     bottom = y - h;
2125:     PetscDrawPushCurrentPoint(draw,x,bottom);
2126:     if (ts->ops->view) {
2127:       (*ts->ops->view)(ts,viewer);
2128:     }
2129:     if (ts->adapt) {TSAdaptView(ts->adapt,viewer);}
2130:     if (ts->snes)  {SNESView(ts->snes,viewer);}
2131:     PetscDrawPopCurrentPoint(draw);
2132: #if defined(PETSC_HAVE_SAWS)
2133:   } else if (issaws) {
2134:     PetscMPIInt rank;
2135:     const char  *name;

2137:     PetscObjectGetName((PetscObject)ts,&name);
2138:     MPI_Comm_rank(PETSC_COMM_WORLD,&rank);
2139:     if (!((PetscObject)ts)->amsmem && !rank) {
2140:       char       dir[1024];

2142:       PetscObjectViewSAWs((PetscObject)ts,viewer);
2143:       PetscSNPrintf(dir,1024,"/PETSc/Objects/%s/time_step",name);
2144:       PetscStackCallSAWs(SAWs_Register,(dir,&ts->steps,1,SAWs_READ,SAWs_INT));
2145:       PetscSNPrintf(dir,1024,"/PETSc/Objects/%s/time",name);
2146:       PetscStackCallSAWs(SAWs_Register,(dir,&ts->ptime,1,SAWs_READ,SAWs_DOUBLE));
2147:     }
2148:     if (ts->ops->view) {
2149:       (*ts->ops->view)(ts,viewer);
2150:     }
2151: #endif
2152:   }
2153:   if (ts->snes && ts->usessnes)  {
2154:     PetscViewerASCIIPushTab(viewer);
2155:     SNESView(ts->snes,viewer);
2156:     PetscViewerASCIIPopTab(viewer);
2157:   }
2158:   DMGetDMTS(ts->dm,&sdm);
2159:   DMTSView(sdm,viewer);

2161:   PetscViewerASCIIPushTab(viewer);
2162:   PetscObjectTypeCompare((PetscObject)ts,TSSUNDIALS,&isundials);
2163:   PetscViewerASCIIPopTab(viewer);
2164:   return(0);
2165: }

2167: /*@
2168:    TSSetApplicationContext - Sets an optional user-defined context for
2169:    the timesteppers.

2171:    Logically Collective on TS

2173:    Input Parameters:
2174: +  ts - the TS context obtained from TSCreate()
2175: -  usrP - optional user context

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

2181:    Level: intermediate

2183: .seealso: TSGetApplicationContext()
2184: @*/
2185: PetscErrorCode  TSSetApplicationContext(TS ts,void *usrP)
2186: {
2189:   ts->user = usrP;
2190:   return(0);
2191: }

2193: /*@
2194:     TSGetApplicationContext - Gets the user-defined context for the
2195:     timestepper.

2197:     Not Collective

2199:     Input Parameter:
2200: .   ts - the TS context obtained from TSCreate()

2202:     Output Parameter:
2203: .   usrP - user context

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

2209:     Level: intermediate

2211: .seealso: TSSetApplicationContext()
2212: @*/
2213: PetscErrorCode  TSGetApplicationContext(TS ts,void *usrP)
2214: {
2217:   *(void**)usrP = ts->user;
2218:   return(0);
2219: }

2221: /*@
2222:    TSGetStepNumber - Gets the number of steps completed.

2224:    Not Collective

2226:    Input Parameter:
2227: .  ts - the TS context obtained from TSCreate()

2229:    Output Parameter:
2230: .  steps - number of steps completed so far

2232:    Level: intermediate

2234: .seealso: TSGetTime(), TSGetTimeStep(), TSSetPreStep(), TSSetPreStage(), TSSetPostStage(), TSSetPostStep()
2235: @*/
2236: PetscErrorCode TSGetStepNumber(TS ts,PetscInt *steps)
2237: {
2241:   *steps = ts->steps;
2242:   return(0);
2243: }

2245: /*@
2246:    TSSetStepNumber - Sets the number of steps completed.

2248:    Logically Collective on TS

2250:    Input Parameters:
2251: +  ts - the TS context
2252: -  steps - number of steps completed so far

2254:    Notes:
2255:    For most uses of the TS solvers the user need not explicitly call
2256:    TSSetStepNumber(), as the step counter is appropriately updated in
2257:    TSSolve()/TSStep()/TSRollBack(). Power users may call this routine to
2258:    reinitialize timestepping by setting the step counter to zero (and time
2259:    to the initial time) to solve a similar problem with different initial
2260:    conditions or parameters. Other possible use case is to continue
2261:    timestepping from a previously interrupted run in such a way that TS
2262:    monitors will be called with a initial nonzero step counter.

2264:    Level: advanced

2266: .seealso: TSGetStepNumber(), TSSetTime(), TSSetTimeStep(), TSSetSolution()
2267: @*/
2268: PetscErrorCode TSSetStepNumber(TS ts,PetscInt steps)
2269: {
2273:   if (steps < 0) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_ARG_OUTOFRANGE,"Step number must be non-negative");
2274:   ts->steps = steps;
2275:   return(0);
2276: }

2278: /*@
2279:    TSSetTimeStep - Allows one to reset the timestep at any time,
2280:    useful for simple pseudo-timestepping codes.

2282:    Logically Collective on TS

2284:    Input Parameters:
2285: +  ts - the TS context obtained from TSCreate()
2286: -  time_step - the size of the timestep

2288:    Level: intermediate

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

2292: @*/
2293: PetscErrorCode  TSSetTimeStep(TS ts,PetscReal time_step)
2294: {
2298:   ts->time_step = time_step;
2299:   return(0);
2300: }

2302: /*@
2303:    TSSetExactFinalTime - Determines whether to adapt the final time step to
2304:      match the exact final time, interpolate solution to the exact final time,
2305:      or just return at the final time TS computed.

2307:   Logically Collective on TS

2309:    Input Parameter:
2310: +   ts - the time-step context
2311: -   eftopt - exact final time option

2313: $  TS_EXACTFINALTIME_STEPOVER    - Don't do anything if final time is exceeded
2314: $  TS_EXACTFINALTIME_INTERPOLATE - Interpolate back to final time
2315: $  TS_EXACTFINALTIME_MATCHSTEP - Adapt final time step to match the final time

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

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

2323:    Level: beginner

2325: .seealso: TSExactFinalTimeOption, TSGetExactFinalTime()
2326: @*/
2327: PetscErrorCode TSSetExactFinalTime(TS ts,TSExactFinalTimeOption eftopt)
2328: {
2332:   ts->exact_final_time = eftopt;
2333:   return(0);
2334: }

2336: /*@
2337:    TSGetExactFinalTime - Gets the exact final time option.

2339:    Not Collective

2341:    Input Parameter:
2342: .  ts - the TS context

2344:    Output Parameter:
2345: .  eftopt - exact final time option

2347:    Level: beginner

2349: .seealso: TSExactFinalTimeOption, TSSetExactFinalTime()
2350: @*/
2351: PetscErrorCode TSGetExactFinalTime(TS ts,TSExactFinalTimeOption *eftopt)
2352: {
2356:   *eftopt = ts->exact_final_time;
2357:   return(0);
2358: }

2360: /*@
2361:    TSGetTimeStep - Gets the current timestep size.

2363:    Not Collective

2365:    Input Parameter:
2366: .  ts - the TS context obtained from TSCreate()

2368:    Output Parameter:
2369: .  dt - the current timestep size

2371:    Level: intermediate

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

2375: @*/
2376: PetscErrorCode  TSGetTimeStep(TS ts,PetscReal *dt)
2377: {
2381:   *dt = ts->time_step;
2382:   return(0);
2383: }

2385: /*@
2386:    TSGetSolution - Returns the solution at the present timestep. It
2387:    is valid to call this routine inside the function that you are evaluating
2388:    in order to move to the new timestep. This vector not changed until
2389:    the solution at the next timestep has been calculated.

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

2393:    Input Parameter:
2394: .  ts - the TS context obtained from TSCreate()

2396:    Output Parameter:
2397: .  v - the vector containing the solution

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

2402:    Level: intermediate

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

2406: @*/
2407: PetscErrorCode  TSGetSolution(TS ts,Vec *v)
2408: {
2412:   *v = ts->vec_sol;
2413:   return(0);
2414: }

2416: /*@
2417:    TSGetSolutionComponents - Returns any solution components at the present
2418:    timestep, if available for the time integration method being used.
2419:    Solution components are quantities that share the same size and
2420:    structure as the solution vector.

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

2424:    Parameters :
2425: +  ts - the TS context obtained from TSCreate() (input parameter).
2426: .  n - If v is PETSC_NULL, then the number of solution components is
2427:        returned through n, else the n-th solution component is
2428:        returned in v.
2429: -  v - the vector containing the n-th solution component
2430:        (may be PETSC_NULL to use this function to find out
2431:         the number of solutions components).

2433:    Level: advanced

2435: .seealso: TSGetSolution()

2437: @*/
2438: PetscErrorCode  TSGetSolutionComponents(TS ts,PetscInt *n,Vec *v)
2439: {

2444:   if (!ts->ops->getsolutioncomponents) *n = 0;
2445:   else {
2446:     (*ts->ops->getsolutioncomponents)(ts,n,v);
2447:   }
2448:   return(0);
2449: }

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

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

2457:    Parameters :
2458: +  ts - the TS context obtained from TSCreate() (input parameter).
2459: -  v - the vector containing the auxiliary solution

2461:    Level: intermediate

2463: .seealso: TSGetSolution()

2465: @*/
2466: PetscErrorCode  TSGetAuxSolution(TS ts,Vec *v)
2467: {

2472:   if (ts->ops->getauxsolution) {
2473:     (*ts->ops->getauxsolution)(ts,v);
2474:   } else {
2475:     VecZeroEntries(*v); 
2476:   }
2477:   return(0);
2478: }

2480: /*@
2481:    TSGetTimeError - Returns the estimated error vector, if the chosen
2482:    TSType has an error estimation functionality.

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

2486:    Note: MUST call after TSSetUp()

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

2493:    Level: intermediate

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

2497: @*/
2498: PetscErrorCode  TSGetTimeError(TS ts,PetscInt n,Vec *v)
2499: {

2504:   if (ts->ops->gettimeerror) {
2505:     (*ts->ops->gettimeerror)(ts,n,v);
2506:   } else {
2507:     VecZeroEntries(*v);
2508:   }
2509:   return(0);
2510: }

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

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

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

2523:    Level: intermediate

2525: .seealso: TSSetSolution(), TSGetTimeError)

2527: @*/
2528: PetscErrorCode  TSSetTimeError(TS ts,Vec v)
2529: {

2534:   if (!ts->setupcalled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Must call TSSetUp() first");
2535:   if (ts->ops->settimeerror) {
2536:     (*ts->ops->settimeerror)(ts,v);
2537:   }
2538:   return(0);
2539: }

2541: /* ----- Routines to initialize and destroy a timestepper ---- */
2542: /*@
2543:   TSSetProblemType - Sets the type of problem to be solved.

2545:   Not collective

2547:   Input Parameters:
2548: + ts   - The TS
2549: - type - One of TS_LINEAR, TS_NONLINEAR where these types refer to problems of the forms
2550: .vb
2551:          U_t - A U = 0      (linear)
2552:          U_t - A(t) U = 0   (linear)
2553:          F(t,U,U_t) = 0     (nonlinear)
2554: .ve

2556:    Level: beginner

2558: .seealso: TSSetUp(), TSProblemType, TS
2559: @*/
2560: PetscErrorCode  TSSetProblemType(TS ts, TSProblemType type)
2561: {

2566:   ts->problem_type = type;
2567:   if (type == TS_LINEAR) {
2568:     SNES snes;
2569:     TSGetSNES(ts,&snes);
2570:     SNESSetType(snes,SNESKSPONLY);
2571:   }
2572:   return(0);
2573: }

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

2578:   Not collective

2580:   Input Parameter:
2581: . ts   - The TS

2583:   Output Parameter:
2584: . type - One of TS_LINEAR, TS_NONLINEAR where these types refer to problems of the forms
2585: .vb
2586:          M U_t = A U
2587:          M(t) U_t = A(t) U
2588:          F(t,U,U_t)
2589: .ve

2591:    Level: beginner

2593: .seealso: TSSetUp(), TSProblemType, TS
2594: @*/
2595: PetscErrorCode  TSGetProblemType(TS ts, TSProblemType *type)
2596: {
2600:   *type = ts->problem_type;
2601:   return(0);
2602: }

2604: /*@
2605:    TSSetUp - Sets up the internal data structures for the later use
2606:    of a timestepper.

2608:    Collective on TS

2610:    Input Parameter:
2611: .  ts - the TS context obtained from TSCreate()

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

2620:    Level: advanced

2622: .seealso: TSCreate(), TSStep(), TSDestroy(), TSSolve()
2623: @*/
2624: PetscErrorCode  TSSetUp(TS ts)
2625: {
2627:   DM             dm;
2628:   PetscErrorCode (*func)(SNES,Vec,Vec,void*);
2629:   PetscErrorCode (*jac)(SNES,Vec,Mat,Mat,void*);
2630:   TSIFunction    ifun;
2631:   TSIJacobian    ijac;
2632:   TSI2Jacobian   i2jac;
2633:   TSRHSJacobian  rhsjac;
2634:   PetscBool      isnone;

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

2640:   if (!((PetscObject)ts)->type_name) {
2641:     TSGetIFunction(ts,NULL,&ifun,NULL);
2642:     TSSetType(ts,ifun ? TSBEULER : TSEULER);
2643:   }

2645:   if (!ts->vec_sol) {
2646:     if (ts->dm) {
2647:       DMCreateGlobalVector(ts->dm,&ts->vec_sol);
2648:     } else SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Must call TSSetSolution() first");
2649:   }

2651:   if (!ts->Jacp && ts->Jacprhs) { /* IJacobianP shares the same matrix with RHSJacobianP if only RHSJacobianP is provided */
2652:     PetscObjectReference((PetscObject)ts->Jacprhs);
2653:     ts->Jacp = ts->Jacprhs;
2654:   }

2656:   if (ts->quadraturets) {
2657:     TSSetUp(ts->quadraturets);
2658:     VecDestroy(&ts->vec_costintegrand);
2659:     VecDuplicate(ts->quadraturets->vec_sol,&ts->vec_costintegrand);
2660:   }

2662:   TSGetRHSJacobian(ts,NULL,NULL,&rhsjac,NULL);
2663:   if (ts->rhsjacobian.reuse && rhsjac == TSComputeRHSJacobianConstant) {
2664:     Mat Amat,Pmat;
2665:     SNES snes;
2666:     TSGetSNES(ts,&snes);
2667:     SNESGetJacobian(snes,&Amat,&Pmat,NULL,NULL);
2668:     /* Matching matrices implies that an IJacobian is NOT set, because if it had been set, the IJacobian's matrix would
2669:      * have displaced the RHS matrix */
2670:     if (Amat && Amat == ts->Arhs) {
2671:       /* 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 */
2672:       MatDuplicate(ts->Arhs,MAT_COPY_VALUES,&Amat);
2673:       SNESSetJacobian(snes,Amat,NULL,NULL,NULL);
2674:       MatDestroy(&Amat);
2675:     }
2676:     if (Pmat && Pmat == ts->Brhs) {
2677:       MatDuplicate(ts->Brhs,MAT_COPY_VALUES,&Pmat);
2678:       SNESSetJacobian(snes,NULL,Pmat,NULL,NULL);
2679:       MatDestroy(&Pmat);
2680:     }
2681:   }

2683:   TSGetAdapt(ts,&ts->adapt);
2684:   TSAdaptSetDefaultType(ts->adapt,ts->default_adapt_type);

2686:   if (ts->ops->setup) {
2687:     (*ts->ops->setup)(ts);
2688:   }

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

2695:   /* In the case where we've set a DMTSFunction or what have you, we need the default SNESFunction
2696:      to be set right but can't do it elsewhere due to the overreliance on ctx=ts.
2697:    */
2698:   TSGetDM(ts,&dm);
2699:   DMSNESGetFunction(dm,&func,NULL);
2700:   if (!func) {
2701:     DMSNESSetFunction(dm,SNESTSFormFunction,ts);
2702:   }
2703:   /* If the SNES doesn't have a jacobian set and the TS has an ijacobian or rhsjacobian set, set the SNES to use it.
2704:      Otherwise, the SNES will use coloring internally to form the Jacobian.
2705:    */
2706:   DMSNESGetJacobian(dm,&jac,NULL);
2707:   DMTSGetIJacobian(dm,&ijac,NULL);
2708:   DMTSGetI2Jacobian(dm,&i2jac,NULL);
2709:   DMTSGetRHSJacobian(dm,&rhsjac,NULL);
2710:   if (!jac && (ijac || i2jac || rhsjac)) {
2711:     DMSNESSetJacobian(dm,SNESTSFormJacobian,ts);
2712:   }

2714:   /* if time integration scheme has a starting method, call it */
2715:   if (ts->ops->startingmethod) {
2716:     (*ts->ops->startingmethod)(ts);
2717:   }

2719:   ts->setupcalled = PETSC_TRUE;
2720:   return(0);
2721: }

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

2726:    Collective on TS

2728:    Input Parameter:
2729: .  ts - the TS context obtained from TSCreate()

2731:    Level: beginner

2733: .seealso: TSCreate(), TSSetup(), TSDestroy()
2734: @*/
2735: PetscErrorCode  TSReset(TS ts)
2736: {
2737:   TS_RHSSplitLink ilink = ts->tsrhssplit,next;
2738:   PetscErrorCode  ierr;


2743:   if (ts->ops->reset) {
2744:     (*ts->ops->reset)(ts);
2745:   }
2746:   if (ts->snes) {SNESReset(ts->snes);}
2747:   if (ts->adapt) {TSAdaptReset(ts->adapt);}

2749:   MatDestroy(&ts->Arhs);
2750:   MatDestroy(&ts->Brhs);
2751:   VecDestroy(&ts->Frhs);
2752:   VecDestroy(&ts->vec_sol);
2753:   VecDestroy(&ts->vec_dot);
2754:   VecDestroy(&ts->vatol);
2755:   VecDestroy(&ts->vrtol);
2756:   VecDestroyVecs(ts->nwork,&ts->work);

2758:   MatDestroy(&ts->Jacprhs);
2759:   MatDestroy(&ts->Jacp);
2760:   if (ts->forward_solve) {
2761:     TSForwardReset(ts);
2762:   }
2763:   if (ts->quadraturets) {
2764:     TSReset(ts->quadraturets);
2765:     VecDestroy(&ts->vec_costintegrand);
2766:   }
2767:   while (ilink) {
2768:     next = ilink->next;
2769:     TSDestroy(&ilink->ts);
2770:     PetscFree(ilink->splitname);
2771:     ISDestroy(&ilink->is);
2772:     PetscFree(ilink);
2773:     ilink = next;
2774:   }
2775:   ts->num_rhs_splits = 0;
2776:   ts->setupcalled = PETSC_FALSE;
2777:   return(0);
2778: }

2780: /*@
2781:    TSDestroy - Destroys the timestepper context that was created
2782:    with TSCreate().

2784:    Collective on TS

2786:    Input Parameter:
2787: .  ts - the TS context obtained from TSCreate()

2789:    Level: beginner

2791: .seealso: TSCreate(), TSSetUp(), TSSolve()
2792: @*/
2793: PetscErrorCode  TSDestroy(TS *ts)
2794: {

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

2802:   TSReset(*ts);
2803:   TSAdjointReset(*ts);
2804:   if ((*ts)->forward_solve) {
2805:     TSForwardReset(*ts);
2806:   }
2807:   /* if memory was published with SAWs then destroy it */
2808:   PetscObjectSAWsViewOff((PetscObject)*ts);
2809:   if ((*ts)->ops->destroy) {(*(*ts)->ops->destroy)((*ts));}

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

2813:   TSAdaptDestroy(&(*ts)->adapt);
2814:   TSEventDestroy(&(*ts)->event);

2816:   SNESDestroy(&(*ts)->snes);
2817:   DMDestroy(&(*ts)->dm);
2818:   TSMonitorCancel((*ts));
2819:   TSAdjointMonitorCancel((*ts));

2821:   TSDestroy(&(*ts)->quadraturets);
2822:   PetscHeaderDestroy(ts);
2823:   return(0);
2824: }

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

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

2832:    Input Parameter:
2833: .  ts - the TS context obtained from TSCreate()

2835:    Output Parameter:
2836: .  snes - the nonlinear solver context

2838:    Notes:
2839:    The user can then directly manipulate the SNES context to set various
2840:    options, etc.  Likewise, the user can then extract and manipulate the
2841:    KSP, KSP, and PC contexts as well.

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

2846:    Level: beginner

2848: @*/
2849: PetscErrorCode  TSGetSNES(TS ts,SNES *snes)
2850: {

2856:   if (!ts->snes) {
2857:     SNESCreate(PetscObjectComm((PetscObject)ts),&ts->snes);
2858:     PetscObjectSetOptions((PetscObject)ts->snes,((PetscObject)ts)->options);
2859:     SNESSetFunction(ts->snes,NULL,SNESTSFormFunction,ts);
2860:     PetscLogObjectParent((PetscObject)ts,(PetscObject)ts->snes);
2861:     PetscObjectIncrementTabLevel((PetscObject)ts->snes,(PetscObject)ts,1);
2862:     if (ts->dm) {SNESSetDM(ts->snes,ts->dm);}
2863:     if (ts->problem_type == TS_LINEAR) {
2864:       SNESSetType(ts->snes,SNESKSPONLY);
2865:     }
2866:   }
2867:   *snes = ts->snes;
2868:   return(0);
2869: }

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

2874:    Collective

2876:    Input Parameter:
2877: +  ts - the TS context obtained from TSCreate()
2878: -  snes - the nonlinear solver context

2880:    Notes:
2881:    Most users should have the TS created by calling TSGetSNES()

2883:    Level: developer

2885: @*/
2886: PetscErrorCode TSSetSNES(TS ts,SNES snes)
2887: {
2889:   PetscErrorCode (*func)(SNES,Vec,Mat,Mat,void*);

2894:   PetscObjectReference((PetscObject)snes);
2895:   SNESDestroy(&ts->snes);

2897:   ts->snes = snes;

2899:   SNESSetFunction(ts->snes,NULL,SNESTSFormFunction,ts);
2900:   SNESGetJacobian(ts->snes,NULL,NULL,&func,NULL);
2901:   if (func == SNESTSFormJacobian) {
2902:     SNESSetJacobian(ts->snes,NULL,NULL,SNESTSFormJacobian,ts);
2903:   }
2904:   return(0);
2905: }

2907: /*@
2908:    TSGetKSP - Returns the KSP (linear solver) associated with
2909:    a TS (timestepper) context.

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

2913:    Input Parameter:
2914: .  ts - the TS context obtained from TSCreate()

2916:    Output Parameter:
2917: .  ksp - the nonlinear solver context

2919:    Notes:
2920:    The user can then directly manipulate the KSP context to set various
2921:    options, etc.  Likewise, the user can then extract and manipulate the
2922:    KSP and PC contexts as well.

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

2927:    Level: beginner

2929: @*/
2930: PetscErrorCode  TSGetKSP(TS ts,KSP *ksp)
2931: {
2933:   SNES           snes;

2938:   if (!((PetscObject)ts)->type_name) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_NULL,"KSP is not created yet. Call TSSetType() first");
2939:   if (ts->problem_type != TS_LINEAR) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,"Linear only; use TSGetSNES()");
2940:   TSGetSNES(ts,&snes);
2941:   SNESGetKSP(snes,ksp);
2942:   return(0);
2943: }

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

2947: /*@
2948:    TSSetMaxSteps - Sets the maximum number of steps to use.

2950:    Logically Collective on TS

2952:    Input Parameters:
2953: +  ts - the TS context obtained from TSCreate()
2954: -  maxsteps - maximum number of steps to use

2956:    Options Database Keys:
2957: .  -ts_max_steps <maxsteps> - Sets maxsteps

2959:    Notes:
2960:    The default maximum number of steps is 5000

2962:    Level: intermediate

2964: .seealso: TSGetMaxSteps(), TSSetMaxTime(), TSSetExactFinalTime()
2965: @*/
2966: PetscErrorCode TSSetMaxSteps(TS ts,PetscInt maxsteps)
2967: {
2971:   if (maxsteps < 0 ) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_ARG_OUTOFRANGE,"Maximum number of steps must be non-negative");
2972:   ts->max_steps = maxsteps;
2973:   return(0);
2974: }

2976: /*@
2977:    TSGetMaxSteps - Gets the maximum number of steps to use.

2979:    Not Collective

2981:    Input Parameters:
2982: .  ts - the TS context obtained from TSCreate()

2984:    Output Parameter:
2985: .  maxsteps - maximum number of steps to use

2987:    Level: advanced

2989: .seealso: TSSetMaxSteps(), TSGetMaxTime(), TSSetMaxTime()
2990: @*/
2991: PetscErrorCode TSGetMaxSteps(TS ts,PetscInt *maxsteps)
2992: {
2996:   *maxsteps = ts->max_steps;
2997:   return(0);
2998: }

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

3003:    Logically Collective on TS

3005:    Input Parameters:
3006: +  ts - the TS context obtained from TSCreate()
3007: -  maxtime - final time to step to

3009:    Options Database Keys:
3010: .  -ts_max_time <maxtime> - Sets maxtime

3012:    Notes:
3013:    The default maximum time is 5.0

3015:    Level: intermediate

3017: .seealso: TSGetMaxTime(), TSSetMaxSteps(), TSSetExactFinalTime()
3018: @*/
3019: PetscErrorCode TSSetMaxTime(TS ts,PetscReal maxtime)
3020: {
3024:   ts->max_time = maxtime;
3025:   return(0);
3026: }

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

3031:    Not Collective

3033:    Input Parameters:
3034: .  ts - the TS context obtained from TSCreate()

3036:    Output Parameter:
3037: .  maxtime - final time to step to

3039:    Level: advanced

3041: .seealso: TSSetMaxTime(), TSGetMaxSteps(), TSSetMaxSteps()
3042: @*/
3043: PetscErrorCode TSGetMaxTime(TS ts,PetscReal *maxtime)
3044: {
3048:   *maxtime = ts->max_time;
3049:   return(0);
3050: }

3052: /*@
3053:    TSSetInitialTimeStep - Deprecated, use TSSetTime() and TSSetTimeStep().

3055:    Level: deprecated

3057: @*/
3058: PetscErrorCode  TSSetInitialTimeStep(TS ts,PetscReal initial_time,PetscReal time_step)
3059: {
3063:   TSSetTime(ts,initial_time);
3064:   TSSetTimeStep(ts,time_step);
3065:   return(0);
3066: }

3068: /*@
3069:    TSGetDuration - Deprecated, use TSGetMaxSteps() and TSGetMaxTime().

3071:    Level: deprecated

3073: @*/
3074: PetscErrorCode TSGetDuration(TS ts, PetscInt *maxsteps, PetscReal *maxtime)
3075: {
3078:   if (maxsteps) {
3080:     *maxsteps = ts->max_steps;
3081:   }
3082:   if (maxtime) {
3084:     *maxtime = ts->max_time;
3085:   }
3086:   return(0);
3087: }

3089: /*@
3090:    TSSetDuration - Deprecated, use TSSetMaxSteps() and TSSetMaxTime().

3092:    Level: deprecated

3094: @*/
3095: PetscErrorCode TSSetDuration(TS ts,PetscInt maxsteps,PetscReal maxtime)
3096: {
3101:   if (maxsteps >= 0) ts->max_steps = maxsteps;
3102:   if (maxtime != PETSC_DEFAULT) ts->max_time = maxtime;
3103:   return(0);
3104: }

3106: /*@
3107:    TSGetTimeStepNumber - Deprecated, use TSGetStepNumber().

3109:    Level: deprecated

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

3114: /*@
3115:    TSGetTotalSteps - Deprecated, use TSGetStepNumber().

3117:    Level: deprecated

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

3122: /*@
3123:    TSSetSolution - Sets the initial solution vector
3124:    for use by the TS routines.

3126:    Logically Collective on TS

3128:    Input Parameters:
3129: +  ts - the TS context obtained from TSCreate()
3130: -  u - the solution vector

3132:    Level: beginner

3134: .seealso: TSSetSolutionFunction(), TSGetSolution(), TSCreate()
3135: @*/
3136: PetscErrorCode  TSSetSolution(TS ts,Vec u)
3137: {
3139:   DM             dm;

3144:   PetscObjectReference((PetscObject)u);
3145:   VecDestroy(&ts->vec_sol);
3146:   ts->vec_sol = u;

3148:   TSGetDM(ts,&dm);
3149:   DMShellSetGlobalVector(dm,u);
3150:   return(0);
3151: }

3153: /*@C
3154:   TSSetPreStep - Sets the general-purpose function
3155:   called once at the beginning of each time step.

3157:   Logically Collective on TS

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

3163:   Calling sequence of func:
3164: .   PetscErrorCode func (TS ts);

3166:   Level: intermediate

3168: .seealso: TSSetPreStage(), TSSetPostStage(), TSSetPostStep(), TSStep(), TSRestartStep()
3169: @*/
3170: PetscErrorCode  TSSetPreStep(TS ts, PetscErrorCode (*func)(TS))
3171: {
3174:   ts->prestep = func;
3175:   return(0);
3176: }

3178: /*@
3179:   TSPreStep - Runs the user-defined pre-step function.

3181:   Collective on TS

3183:   Input Parameters:
3184: . ts   - The TS context obtained from TSCreate()

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

3190:   Level: developer

3192: .seealso: TSSetPreStep(), TSPreStage(), TSPostStage(), TSPostStep()
3193: @*/
3194: PetscErrorCode  TSPreStep(TS ts)
3195: {

3200:   if (ts->prestep) {
3201:     Vec              U;
3202:     PetscObjectState sprev,spost;

3204:     TSGetSolution(ts,&U);
3205:     PetscObjectStateGet((PetscObject)U,&sprev);
3206:     PetscStackCallStandard((*ts->prestep),(ts));
3207:     PetscObjectStateGet((PetscObject)U,&spost);
3208:     if (sprev != spost) {TSRestartStep(ts);}
3209:   }
3210:   return(0);
3211: }

3213: /*@C
3214:   TSSetPreStage - Sets the general-purpose function
3215:   called once at the beginning of each stage.

3217:   Logically Collective on TS

3219:   Input Parameters:
3220: + ts   - The TS context obtained from TSCreate()
3221: - func - The function

3223:   Calling sequence of func:
3224: .    PetscErrorCode func(TS ts, PetscReal stagetime);

3226:   Level: intermediate

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

3233: .seealso: TSSetPostStage(), TSSetPreStep(), TSSetPostStep(), TSGetApplicationContext()
3234: @*/
3235: PetscErrorCode  TSSetPreStage(TS ts, PetscErrorCode (*func)(TS,PetscReal))
3236: {
3239:   ts->prestage = func;
3240:   return(0);
3241: }

3243: /*@C
3244:   TSSetPostStage - Sets the general-purpose function
3245:   called once at the end of each stage.

3247:   Logically Collective on TS

3249:   Input Parameters:
3250: + ts   - The TS context obtained from TSCreate()
3251: - func - The function

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

3256:   Level: intermediate

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

3263: .seealso: TSSetPreStage(), TSSetPreStep(), TSSetPostStep(), TSGetApplicationContext()
3264: @*/
3265: PetscErrorCode  TSSetPostStage(TS ts, PetscErrorCode (*func)(TS,PetscReal,PetscInt,Vec*))
3266: {
3269:   ts->poststage = func;
3270:   return(0);
3271: }

3273: /*@C
3274:   TSSetPostEvaluate - Sets the general-purpose function
3275:   called once at the end of each step evaluation.

3277:   Logically Collective on TS

3279:   Input Parameters:
3280: + ts   - The TS context obtained from TSCreate()
3281: - func - The function

3283:   Calling sequence of func:
3284: . PetscErrorCode func(TS ts);

3286:   Level: intermediate

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

3295: .seealso: TSSetPreStage(), TSSetPreStep(), TSSetPostStep(), TSGetApplicationContext()
3296: @*/
3297: PetscErrorCode  TSSetPostEvaluate(TS ts, PetscErrorCode (*func)(TS))
3298: {
3301:   ts->postevaluate = func;
3302:   return(0);
3303: }

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

3308:   Collective on TS

3310:   Input Parameters:
3311: . ts          - The TS context obtained from TSCreate()
3312:   stagetime   - The absolute time of the current stage

3314:   Notes:
3315:   TSPreStage() is typically used within time stepping implementations,
3316:   most users would not generally call this routine themselves.

3318:   Level: developer

3320: .seealso: TSPostStage(), TSSetPreStep(), TSPreStep(), TSPostStep()
3321: @*/
3322: PetscErrorCode  TSPreStage(TS ts, PetscReal stagetime)
3323: {
3326:   if (ts->prestage) {
3327:     PetscStackCallStandard((*ts->prestage),(ts,stagetime));
3328:   }
3329:   return(0);
3330: }

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

3335:   Collective on TS

3337:   Input Parameters:
3338: . ts          - The TS context obtained from TSCreate()
3339:   stagetime   - The absolute time of the current stage
3340:   stageindex  - Stage number
3341:   Y           - Array of vectors (of size = total number
3342:                 of stages) with the stage solutions

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

3348:   Level: developer

3350: .seealso: TSPreStage(), TSSetPreStep(), TSPreStep(), TSPostStep()
3351: @*/
3352: PetscErrorCode  TSPostStage(TS ts, PetscReal stagetime, PetscInt stageindex, Vec *Y)
3353: {
3356:   if (ts->poststage) {
3357:     PetscStackCallStandard((*ts->poststage),(ts,stagetime,stageindex,Y));
3358:   }
3359:   return(0);
3360: }

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

3365:   Collective on TS

3367:   Input Parameters:
3368: . ts          - The TS context obtained from TSCreate()

3370:   Notes:
3371:   TSPostEvaluate() is typically used within time stepping implementations,
3372:   most users would not generally call this routine themselves.

3374:   Level: developer

3376: .seealso: TSSetPostEvaluate(), TSSetPreStep(), TSPreStep(), TSPostStep()
3377: @*/
3378: PetscErrorCode  TSPostEvaluate(TS ts)
3379: {

3384:   if (ts->postevaluate) {
3385:     Vec              U;
3386:     PetscObjectState sprev,spost;

3388:     TSGetSolution(ts,&U);
3389:     PetscObjectStateGet((PetscObject)U,&sprev);
3390:     PetscStackCallStandard((*ts->postevaluate),(ts));
3391:     PetscObjectStateGet((PetscObject)U,&spost);
3392:     if (sprev != spost) {TSRestartStep(ts);}
3393:   }
3394:   return(0);
3395: }

3397: /*@C
3398:   TSSetPostStep - Sets the general-purpose function
3399:   called once at the end of each time step.

3401:   Logically Collective on TS

3403:   Input Parameters:
3404: + ts   - The TS context obtained from TSCreate()
3405: - func - The function

3407:   Calling sequence of func:
3408: $ func (TS ts);

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

3415:   Level: intermediate

3417: .seealso: TSSetPreStep(), TSSetPreStage(), TSSetPostEvaluate(), TSGetTimeStep(), TSGetStepNumber(), TSGetTime(), TSRestartStep()
3418: @*/
3419: PetscErrorCode  TSSetPostStep(TS ts, PetscErrorCode (*func)(TS))
3420: {
3423:   ts->poststep = func;
3424:   return(0);
3425: }

3427: /*@
3428:   TSPostStep - Runs the user-defined post-step function.

3430:   Collective on TS

3432:   Input Parameters:
3433: . ts   - The TS context obtained from TSCreate()

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

3439:   Level: developer

3441: @*/
3442: PetscErrorCode  TSPostStep(TS ts)
3443: {

3448:   if (ts->poststep) {
3449:     Vec              U;
3450:     PetscObjectState sprev,spost;

3452:     TSGetSolution(ts,&U);
3453:     PetscObjectStateGet((PetscObject)U,&sprev);
3454:     PetscStackCallStandard((*ts->poststep),(ts));
3455:     PetscObjectStateGet((PetscObject)U,&spost);
3456:     if (sprev != spost) {TSRestartStep(ts);}
3457:   }
3458:   return(0);
3459: }

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

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

3467:    Logically Collective on TS

3469:    Input Parameters:
3470: +  ts - the TS context obtained from TSCreate()
3471: .  monitor - monitoring routine
3472: .  mctx - [optional] user-defined context for private data for the
3473:              monitor routine (use NULL if no context is desired)
3474: -  monitordestroy - [optional] routine that frees monitor context
3475:           (may be NULL)

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

3480: +    ts - the TS context
3481: .    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)
3482: .    time - current time
3483: .    u - current iterate
3484: -    mctx - [optional] monitoring context

3486:    Notes:
3487:    This routine adds an additional monitor to the list of monitors that
3488:    already has been loaded.

3490:    Fortran Notes:
3491:     Only a single monitor function can be set for each TS object

3493:    Level: intermediate

3495: .seealso: TSMonitorDefault(), TSMonitorCancel()
3496: @*/
3497: PetscErrorCode  TSMonitorSet(TS ts,PetscErrorCode (*monitor)(TS,PetscInt,PetscReal,Vec,void*),void *mctx,PetscErrorCode (*mdestroy)(void**))
3498: {
3500:   PetscInt       i;
3501:   PetscBool      identical;

3505:   for (i=0; i<ts->numbermonitors;i++) {
3506:     PetscMonitorCompare((PetscErrorCode (*)(void))monitor,mctx,mdestroy,(PetscErrorCode (*)(void))ts->monitor[i],ts->monitorcontext[i],ts->monitordestroy[i],&identical);
3507:     if (identical) return(0);
3508:   }
3509:   if (ts->numbermonitors >= MAXTSMONITORS) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Too many monitors set");
3510:   ts->monitor[ts->numbermonitors]          = monitor;
3511:   ts->monitordestroy[ts->numbermonitors]   = mdestroy;
3512:   ts->monitorcontext[ts->numbermonitors++] = (void*)mctx;
3513:   return(0);
3514: }

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

3519:    Logically Collective on TS

3521:    Input Parameters:
3522: .  ts - the TS context obtained from TSCreate()

3524:    Notes:
3525:    There is no way to remove a single, specific monitor.

3527:    Level: intermediate

3529: .seealso: TSMonitorDefault(), TSMonitorSet()
3530: @*/
3531: PetscErrorCode  TSMonitorCancel(TS ts)
3532: {
3534:   PetscInt       i;

3538:   for (i=0; i<ts->numbermonitors; i++) {
3539:     if (ts->monitordestroy[i]) {
3540:       (*ts->monitordestroy[i])(&ts->monitorcontext[i]);
3541:     }
3542:   }
3543:   ts->numbermonitors = 0;
3544:   return(0);
3545: }

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

3550:    Level: intermediate

3552: .seealso:  TSMonitorSet()
3553: @*/
3554: PetscErrorCode TSMonitorDefault(TS ts,PetscInt step,PetscReal ptime,Vec v,PetscViewerAndFormat *vf)
3555: {
3557:   PetscViewer    viewer =  vf->viewer;
3558:   PetscBool      iascii,ibinary;

3562:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERASCII,&iascii);
3563:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERBINARY,&ibinary);
3564:   PetscViewerPushFormat(viewer,vf->format);
3565:   if (iascii) {
3566:     PetscViewerASCIIAddTab(viewer,((PetscObject)ts)->tablevel);
3567:     if (step == -1){ /* this indicates it is an interpolated solution */
3568:       PetscViewerASCIIPrintf(viewer,"Interpolated solution at time %g between steps %D and %D\n",(double)ptime,ts->steps-1,ts->steps);
3569:     } else {
3570:       PetscViewerASCIIPrintf(viewer,"%D TS dt %g time %g%s",step,(double)ts->time_step,(double)ptime,ts->steprollback ? " (r)\n" : "\n");
3571:     }
3572:     PetscViewerASCIISubtractTab(viewer,((PetscObject)ts)->tablevel);
3573:   } else if (ibinary) {
3574:     PetscMPIInt rank;
3575:     MPI_Comm_rank(PetscObjectComm((PetscObject)viewer),&rank);
3576:     if (!rank) {
3577:       PetscBool skipHeader;
3578:       PetscInt  classid = REAL_FILE_CLASSID;

3580:       PetscViewerBinaryGetSkipHeader(viewer,&skipHeader);
3581:       if (!skipHeader) {
3582:          PetscViewerBinaryWrite(viewer,&classid,1,PETSC_INT);
3583:        }
3584:       PetscRealView(1,&ptime,viewer);
3585:     } else {
3586:       PetscRealView(0,&ptime,viewer);
3587:     }
3588:   }
3589:   PetscViewerPopFormat(viewer);
3590:   return(0);
3591: }

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

3596:    Level: intermediate

3598: .seealso:  TSMonitorSet()
3599: @*/
3600: PetscErrorCode TSMonitorExtreme(TS ts,PetscInt step,PetscReal ptime,Vec v,PetscViewerAndFormat *vf)
3601: {
3603:   PetscViewer    viewer =  vf->viewer;
3604:   PetscBool      iascii;
3605:   PetscReal      max,min;


3610:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERASCII,&iascii);
3611:   PetscViewerPushFormat(viewer,vf->format);
3612:   if (iascii) {
3613:     VecMax(v,NULL,&max);
3614:     VecMin(v,NULL,&min);
3615:     PetscViewerASCIIAddTab(viewer,((PetscObject)ts)->tablevel);
3616:     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);
3617:     PetscViewerASCIISubtractTab(viewer,((PetscObject)ts)->tablevel);
3618:   }
3619:   PetscViewerPopFormat(viewer);
3620:   return(0);
3621: }

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

3626:    Collective on TS

3628:    Input Argument:
3629: +  ts - time stepping context
3630: -  t - time to interpolate to

3632:    Output Argument:
3633: .  U - state at given time

3635:    Level: intermediate

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

3640: .seealso: TSSetExactFinalTime(), TSSolve()
3641: @*/
3642: PetscErrorCode TSInterpolate(TS ts,PetscReal t,Vec U)
3643: {

3649:   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);
3650:   if (!ts->ops->interpolate) SETERRQ1(PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"%s does not provide interpolation",((PetscObject)ts)->type_name);
3651:   (*ts->ops->interpolate)(ts,t,U);
3652:   return(0);
3653: }

3655: /*@
3656:    TSStep - Steps one time step

3658:    Collective on TS

3660:    Input Parameter:
3661: .  ts - the TS context obtained from TSCreate()

3663:    Level: developer

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

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

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

3674: .seealso: TSCreate(), TSSetUp(), TSDestroy(), TSSolve(), TSSetPreStep(), TSSetPreStage(), TSSetPostStage(), TSInterpolate()
3675: @*/
3676: PetscErrorCode  TSStep(TS ts)
3677: {
3678:   PetscErrorCode   ierr;
3679:   static PetscBool cite = PETSC_FALSE;
3680:   PetscReal        ptime;

3684:   PetscCitationsRegister("@article{tspaper,\n"
3685:                                 "  title         = {{PETSc/TS}: A Modern Scalable {DAE/ODE} Solver Library},\n"
3686:                                 "  author        = {Abhyankar, Shrirang and Brown, Jed and Constantinescu, Emil and Ghosh, Debojyoti and Smith, Barry F. and Zhang, Hong},\n"
3687:                                 "  journal       = {arXiv e-preprints},\n"
3688:                                 "  eprint        = {1806.01437},\n"
3689:                                 "  archivePrefix = {arXiv},\n"
3690:                                 "  year          = {2018}\n}\n",&cite);

3692:   TSSetUp(ts);
3693:   TSTrajectorySetUp(ts->trajectory,ts);

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

3700:   if (!ts->steps) ts->ptime_prev = ts->ptime;
3701:   ptime = ts->ptime; ts->ptime_prev_rollback = ts->ptime_prev;
3702:   ts->reason = TS_CONVERGED_ITERATING;

3704:   PetscLogEventBegin(TS_Step,ts,0,0,0);
3705:   (*ts->ops->step)(ts);
3706:   PetscLogEventEnd(TS_Step,ts,0,0,0);

3708:   if (ts->reason >= 0) {
3709:     ts->ptime_prev = ptime;
3710:     ts->steps++;
3711:     ts->steprollback = PETSC_FALSE;
3712:     ts->steprestart  = PETSC_FALSE;
3713:   }

3715:   if (!ts->reason) {
3716:     if (ts->steps >= ts->max_steps) ts->reason = TS_CONVERGED_ITS;
3717:     else if (ts->ptime >= ts->max_time) ts->reason = TS_CONVERGED_TIME;
3718:   }

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

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

3729:    Collective on TS

3731:    Input Arguments:
3732: +  ts - time stepping context
3733: .  wnormtype - norm type, either NORM_2 or NORM_INFINITY
3734: -  order - optional, desired order for the error evaluation or PETSC_DECIDE

3736:    Output Arguments:
3737: +  order - optional, the actual order of the error evaluation
3738: -  wlte - the weighted local truncation error norm

3740:    Level: advanced

3742:    Notes:
3743:    If the timestepper cannot evaluate the error in a particular step
3744:    (eg. in the first step or restart steps after event handling),
3745:    this routine returns wlte=-1.0 .

3747: .seealso: TSStep(), TSAdapt, TSErrorWeightedNorm()
3748: @*/
3749: PetscErrorCode TSEvaluateWLTE(TS ts,NormType wnormtype,PetscInt *order,PetscReal *wlte)
3750: {

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

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

3769:    Collective on TS

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

3776:    Output Arguments:
3777: .  U - state at the end of the current step

3779:    Level: advanced

3781:    Notes:
3782:    This function cannot be called until all stages have been evaluated.
3783:    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.

3785: .seealso: TSStep(), TSAdapt
3786: @*/
3787: PetscErrorCode TSEvaluateStep(TS ts,PetscInt order,Vec U,PetscBool *done)
3788: {

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

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

3803:   Not collective

3805:   Input Argument:
3806: . ts        - time stepping context

3808:   Output Argument:
3809: . initConditions - The function which computes an initial condition

3811:    Level: advanced

3813:    Notes:
3814:    The calling sequence for the function is
3815: $ initCondition(TS ts, Vec u)
3816: $ ts - The timestepping context
3817: $ u  - The input vector in which the initial condition is stored

3819: .seealso: TSSetComputeInitialCondition(), TSComputeInitialCondition()
3820: @*/
3821: PetscErrorCode TSGetComputeInitialCondition(TS ts, PetscErrorCode (**initCondition)(TS, Vec))
3822: {
3826:   *initCondition = ts->ops->initcondition;
3827:   return(0);
3828: }

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

3833:   Logically collective on ts

3835:   Input Arguments:
3836: + ts        - time stepping context
3837: - initCondition - The function which computes an initial condition

3839:   Level: advanced

3841:   Notes:
3842:   The calling sequence for the function is
3843: $ initCondition(TS ts, Vec u)
3844: $ ts - The timestepping context
3845: $ u  - The input vector in which the initial condition is stored

3847: .seealso: TSGetComputeInitialCondition(), TSComputeInitialCondition()
3848: @*/
3849: PetscErrorCode TSSetComputeInitialCondition(TS ts, PetscErrorCode (*initCondition)(TS, Vec))
3850: {
3854:   ts->ops->initcondition = initCondition;
3855:   return(0);
3856: }

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

3861:   Collective on ts

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

3867:   Level: advanced

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

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

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

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

3891:   Not collective

3893:   Input Argument:
3894: . ts         - time stepping context

3896:   Output Argument:
3897: . exactError - The function which computes the solution error

3899:   Level: advanced

3901:   Notes:
3902:   The calling sequence for the function is
3903: $ exactError(TS ts, Vec u)
3904: $ ts - The timestepping context
3905: $ u  - The approximate solution vector
3906: $ e  - The input vector in which the error is stored

3908: .seealso: TSGetComputeExactError(), TSComputeExactError()
3909: @*/
3910: PetscErrorCode TSGetComputeExactError(TS ts, PetscErrorCode (**exactError)(TS, Vec, Vec))
3911: {
3915:   *exactError = ts->ops->exacterror;
3916:   return(0);
3917: }

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

3922:   Logically collective on ts

3924:   Input Arguments:
3925: + ts         - time stepping context
3926: - exactError - The function which computes the solution error

3928:   Level: advanced

3930:   Notes:
3931:   The calling sequence for the function is
3932: $ exactError(TS ts, Vec u)
3933: $ ts - The timestepping context
3934: $ u  - The approximate solution vector
3935: $ e  - The input vector in which the error is stored

3937: .seealso: TSGetComputeExactError(), TSComputeExactError()
3938: @*/
3939: PetscErrorCode TSSetComputeExactError(TS ts, PetscErrorCode (*exactError)(TS, Vec, Vec))
3940: {
3944:   ts->ops->exacterror = exactError;
3945:   return(0);
3946: }

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

3951:   Collective on ts

3953:   Input Arguments:
3954: + ts - time stepping context
3955: . u  - The approximate solution
3956: - e  - The Vec used to store the error

3958:   Level: advanced

3960:   Notes:
3961:   The calling sequence for the function is
3962: $ exactError(TS ts, Vec u)
3963: $ ts - The timestepping context
3964: $ u  - The approximate solution vector
3965: $ e  - The input vector in which the error is stored

3967: .seealso: TSGetComputeInitialCondition(), TSSetComputeInitialCondition(), TSSolve()
3968: @*/
3969: PetscErrorCode TSComputeExactError(TS ts, Vec u, Vec e)
3970: {

3977:   if (ts->ops->exacterror) {(*ts->ops->exacterror)(ts, u, e);}
3978:   return(0);
3979: }

3981: /*@
3982:    TSSolve - Steps the requested number of timesteps.

3984:    Collective on TS

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

3991:    Level: beginner

3993:    Notes:
3994:    The final time returned by this function may be different from the time of the internally
3995:    held state accessible by TSGetSolution() and TSGetTime() because the method may have
3996:    stepped over the final time.

3998: .seealso: TSCreate(), TSSetSolution(), TSStep(), TSGetTime(), TSGetSolveTime()
3999: @*/
4000: PetscErrorCode TSSolve(TS ts,Vec u)
4001: {
4002:   Vec               solution;
4003:   PetscErrorCode    ierr;

4008:   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 */
4009:     if (!ts->vec_sol || u == ts->vec_sol) {
4010:       VecDuplicate(u,&solution);
4011:       TSSetSolution(ts,solution);
4012:       VecDestroy(&solution); /* grant ownership */
4013:     }
4014:     VecCopy(u,ts->vec_sol);
4015:     if (ts->forward_solve) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"Sensitivity analysis does not support the mode TS_EXACTFINALTIME_INTERPOLATE");
4016:   } else if (u) {
4017:     TSSetSolution(ts,u);
4018:   }
4019:   TSSetUp(ts);
4020:   TSTrajectorySetUp(ts->trajectory,ts);

4022:   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>");
4023:   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()");
4024:   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");

4026:   if (ts->forward_solve) {
4027:     TSForwardSetUp(ts);
4028:   }

4030:   /* reset number of steps only when the step is not restarted. ARKIMEX
4031:      restarts the step after an event. Resetting these counters in such case causes
4032:      TSTrajectory to incorrectly save the output files
4033:   */
4034:   /* reset time step and iteration counters */
4035:   if (!ts->steps) {
4036:     ts->ksp_its           = 0;
4037:     ts->snes_its          = 0;
4038:     ts->num_snes_failures = 0;
4039:     ts->reject            = 0;
4040:     ts->steprestart       = PETSC_TRUE;
4041:     ts->steprollback      = PETSC_FALSE;
4042:     ts->rhsjacobian.time  = PETSC_MIN_REAL;
4043:   }

4045:   /* make sure initial time step does not overshoot final time */
4046:   if (ts->exact_final_time == TS_EXACTFINALTIME_MATCHSTEP) {
4047:     PetscReal maxdt = ts->max_time-ts->ptime;
4048:     PetscReal dt = ts->time_step;

4050:     ts->time_step = dt >= maxdt ? maxdt : (PetscIsCloseAtTol(dt,maxdt,10*PETSC_MACHINE_EPSILON,0) ? maxdt : dt);
4051:   }
4052:   ts->reason = TS_CONVERGED_ITERATING;

4054:   {
4055:     PetscViewer       viewer;
4056:     PetscViewerFormat format;
4057:     PetscBool         flg;
4058:     static PetscBool  incall = PETSC_FALSE;

4060:     if (!incall) {
4061:       /* Estimate the convergence rate of the time discretization */
4062:       PetscOptionsGetViewer(PetscObjectComm((PetscObject) ts),((PetscObject)ts)->options, ((PetscObject) ts)->prefix, "-ts_convergence_estimate", &viewer, &format, &flg);
4063:       if (flg) {
4064:         PetscConvEst conv;
4065:         DM           dm;
4066:         PetscReal   *alpha; /* Convergence rate of the solution error for each field in the L_2 norm */
4067:         PetscInt     Nf;
4068:         PetscBool    checkTemporal = PETSC_TRUE;

4070:         incall = PETSC_TRUE;
4071:         PetscOptionsGetBool(((PetscObject)ts)->options, ((PetscObject) ts)->prefix, "-ts_convergence_temporal", &checkTemporal, &flg);
4072:         TSGetDM(ts, &dm);
4073:         DMGetNumFields(dm, &Nf);
4074:         PetscCalloc1(PetscMax(Nf, 1), &alpha);
4075:         PetscConvEstCreate(PetscObjectComm((PetscObject) ts), &conv);
4076:         PetscConvEstUseTS(conv, checkTemporal);
4077:         PetscConvEstSetSolver(conv, (PetscObject) ts);
4078:         PetscConvEstSetFromOptions(conv);
4079:         PetscConvEstSetUp(conv);
4080:         PetscConvEstGetConvRate(conv, alpha);
4081:         PetscViewerPushFormat(viewer, format);
4082:         PetscConvEstRateView(conv, alpha, viewer);
4083:         PetscViewerPopFormat(viewer);
4084:         PetscViewerDestroy(&viewer);
4085:         PetscConvEstDestroy(&conv);
4086:         PetscFree(alpha);
4087:         incall = PETSC_FALSE;
4088:       }
4089:     }
4090:   }

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

4094:   if (ts->ops->solve) { /* This private interface is transitional and should be removed when all implementations are updated. */
4095:     (*ts->ops->solve)(ts);
4096:     if (u) {VecCopy(ts->vec_sol,u);}
4097:     ts->solvetime = ts->ptime;
4098:     solution = ts->vec_sol;
4099:   } else { /* Step the requested number of timesteps. */
4100:     if (ts->steps >= ts->max_steps) ts->reason = TS_CONVERGED_ITS;
4101:     else if (ts->ptime >= ts->max_time) ts->reason = TS_CONVERGED_TIME;

4103:     if (!ts->steps) {
4104:       TSTrajectorySet(ts->trajectory,ts,ts->steps,ts->ptime,ts->vec_sol);
4105:       TSEventInitialize(ts->event,ts,ts->ptime,ts->vec_sol);
4106:     }

4108:     while (!ts->reason) {
4109:       TSMonitor(ts,ts->steps,ts->ptime,ts->vec_sol);
4110:       if (!ts->steprollback) {
4111:         TSPreStep(ts);
4112:       }
4113:       TSStep(ts);
4114:       if (ts->testjacobian) {
4115:         TSRHSJacobianTest(ts,NULL);
4116:       }
4117:       if (ts->testjacobiantranspose) {
4118:         TSRHSJacobianTestTranspose(ts,NULL);
4119:       }
4120:       if (ts->quadraturets && ts->costintegralfwd) { /* Must evaluate the cost integral before event is handled. The cost integral value can also be rolled back. */
4121:         if (ts->reason >= 0) ts->steps--; /* Revert the step number changed by TSStep() */
4122:         TSForwardCostIntegral(ts);
4123:         if (ts->reason >= 0) ts->steps++;
4124:       }
4125:       if (ts->forward_solve) { /* compute forward sensitivities before event handling because postevent() may change RHS and jump conditions may have to be applied */
4126:         if (ts->reason >= 0) ts->steps--; /* Revert the step number changed by TSStep() */
4127:         TSForwardStep(ts);
4128:         if (ts->reason >= 0) ts->steps++;
4129:       }
4130:       TSPostEvaluate(ts);
4131:       TSEventHandler(ts); /* The right-hand side may be changed due to event. Be careful with Any computation using the RHS information after this point. */
4132:       if (ts->steprollback) {
4133:         TSPostEvaluate(ts);
4134:       }
4135:       if (!ts->steprollback) {
4136:         TSTrajectorySet(ts->trajectory,ts,ts->steps,ts->ptime,ts->vec_sol);
4137:         TSPostStep(ts);
4138:       }
4139:     }
4140:     TSMonitor(ts,ts->steps,ts->ptime,ts->vec_sol);

4142:     if (ts->exact_final_time == TS_EXACTFINALTIME_INTERPOLATE && ts->ptime > ts->max_time) {
4143:       TSInterpolate(ts,ts->max_time,u);
4144:       ts->solvetime = ts->max_time;
4145:       solution = u;
4146:       TSMonitor(ts,-1,ts->solvetime,solution);
4147:     } else {
4148:       if (u) {VecCopy(ts->vec_sol,u);}
4149:       ts->solvetime = ts->ptime;
4150:       solution = ts->vec_sol;
4151:     }
4152:   }

4154:   TSViewFromOptions(ts,NULL,"-ts_view");
4155:   VecViewFromOptions(solution,NULL,"-ts_view_solution");
4156:   PetscObjectSAWsBlock((PetscObject)ts);
4157:   if (ts->adjoint_solve) {
4158:     TSAdjointSolve(ts);
4159:   }
4160:   return(0);
4161: }

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

4166:    Collective on TS

4168:    Input Parameters:
4169: +  ts - time stepping context obtained from TSCreate()
4170: .  step - step number that has just completed
4171: .  ptime - model time of the state
4172: -  u - state at the current model time

4174:    Notes:
4175:    TSMonitor() is typically used automatically within the time stepping implementations.
4176:    Users would almost never call this routine directly.

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

4180:    Level: developer

4182: @*/
4183: PetscErrorCode TSMonitor(TS ts,PetscInt step,PetscReal ptime,Vec u)
4184: {
4185:   DM             dm;
4186:   PetscInt       i,n = ts->numbermonitors;


4193:   TSGetDM(ts,&dm);
4194:   DMSetOutputSequenceNumber(dm,step,ptime);

4196:   VecLockReadPush(u);
4197:   for (i=0; i<n; i++) {
4198:     (*ts->monitor[i])(ts,step,ptime,u,ts->monitorcontext[i]);
4199:   }
4200:   VecLockReadPop(u);
4201:   return(0);
4202: }

4204: /* ------------------------------------------------------------------------*/
4205: /*@C
4206:    TSMonitorLGCtxCreate - Creates a TSMonitorLGCtx context for use with
4207:    TS to monitor the solution process graphically in various ways

4209:    Collective on TS

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

4218:    Output Parameter:
4219: .  ctx - the context

4221:    Options Database Key:
4222: +  -ts_monitor_lg_timestep - automatically sets line graph monitor
4223: +  -ts_monitor_lg_timestep_log - automatically sets line graph monitor
4224: .  -ts_monitor_lg_solution - monitor the solution (or certain values of the solution by calling TSMonitorLGSetDisplayVariables() or TSMonitorLGCtxSetDisplayVariables())
4225: .  -ts_monitor_lg_error -  monitor the error
4226: .  -ts_monitor_lg_ksp_iterations - monitor the number of KSP iterations needed for each timestep
4227: .  -ts_monitor_lg_snes_iterations - monitor the number of SNES iterations needed for each timestep
4228: -  -lg_use_markers <true,false> - mark the data points (at each time step) on the plot; default is true

4230:    Notes:
4231:    Use TSMonitorLGCtxDestroy() to destroy.

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

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

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

4241:    Level: intermediate

4243: .seealso: TSMonitorLGTimeStep(), TSMonitorSet(), TSMonitorLGSolution(), TSMonitorLGError(), TSMonitorDefault(), VecView(),
4244:            TSMonitorLGCtxCreate(), TSMonitorLGCtxSetVariableNames(), TSMonitorLGCtxGetVariableNames(),
4245:            TSMonitorLGSetVariableNames(), TSMonitorLGGetVariableNames(), TSMonitorLGSetDisplayVariables(), TSMonitorLGCtxSetDisplayVariables(),
4246:            TSMonitorLGCtxSetTransform(), TSMonitorLGSetTransform(), TSMonitorLGError(), TSMonitorLGSNESIterations(), TSMonitorLGKSPIterations(),
4247:            TSMonitorEnvelopeCtxCreate(), TSMonitorEnvelopeGetBounds(), TSMonitorEnvelopeCtxDestroy(), TSMonitorEnvelop()

4249: @*/
4250: PetscErrorCode  TSMonitorLGCtxCreate(MPI_Comm comm,const char host[],const char label[],int x,int y,int m,int n,PetscInt howoften,TSMonitorLGCtx *ctx)
4251: {
4252:   PetscDraw      draw;

4256:   PetscNew(ctx);
4257:   PetscDrawCreate(comm,host,label,x,y,m,n,&draw);
4258:   PetscDrawSetFromOptions(draw);
4259:   PetscDrawLGCreate(draw,1,&(*ctx)->lg);
4260:   PetscDrawLGSetFromOptions((*ctx)->lg);
4261:   PetscDrawDestroy(&draw);
4262:   (*ctx)->howoften = howoften;
4263:   return(0);
4264: }

4266: PetscErrorCode TSMonitorLGTimeStep(TS ts,PetscInt step,PetscReal ptime,Vec v,void *monctx)
4267: {
4268:   TSMonitorLGCtx ctx = (TSMonitorLGCtx) monctx;
4269:   PetscReal      x   = ptime,y;

4273:   if (step < 0) return(0); /* -1 indicates an interpolated solution */
4274:   if (!step) {
4275:     PetscDrawAxis axis;
4276:     const char *ylabel = ctx->semilogy ? "Log Time Step" : "Time Step";
4277:     PetscDrawLGGetAxis(ctx->lg,&axis);
4278:     PetscDrawAxisSetLabels(axis,"Timestep as function of time","Time",ylabel);
4279:     PetscDrawLGReset(ctx->lg);
4280:   }
4281:   TSGetTimeStep(ts,&y);
4282:   if (ctx->semilogy) y = PetscLog10Real(y);
4283:   PetscDrawLGAddPoint(ctx->lg,&x,&y);
4284:   if (((ctx->howoften > 0) && (!(step % ctx->howoften))) || ((ctx->howoften == -1) && ts->reason)) {
4285:     PetscDrawLGDraw(ctx->lg);
4286:     PetscDrawLGSave(ctx->lg);
4287:   }
4288:   return(0);
4289: }

4291: /*@C
4292:    TSMonitorLGCtxDestroy - Destroys a line graph context that was created
4293:    with TSMonitorLGCtxCreate().

4295:    Collective on TSMonitorLGCtx

4297:    Input Parameter:
4298: .  ctx - the monitor context

4300:    Level: intermediate

4302: .seealso: TSMonitorLGCtxCreate(),  TSMonitorSet(), TSMonitorLGTimeStep();
4303: @*/
4304: PetscErrorCode  TSMonitorLGCtxDestroy(TSMonitorLGCtx *ctx)
4305: {

4309:   if ((*ctx)->transformdestroy) {
4310:     ((*ctx)->transformdestroy)((*ctx)->transformctx);
4311:   }
4312:   PetscDrawLGDestroy(&(*ctx)->lg);
4313:   PetscStrArrayDestroy(&(*ctx)->names);
4314:   PetscStrArrayDestroy(&(*ctx)->displaynames);
4315:   PetscFree((*ctx)->displayvariables);
4316:   PetscFree((*ctx)->displayvalues);
4317:   PetscFree(*ctx);
4318:   return(0);
4319: }

4321: /*

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

4325: */
4326: PetscErrorCode TSMonitorSPCtxCreate(MPI_Comm comm,const char host[],const char label[],int x,int y,int m,int n,PetscInt howoften,TSMonitorSPCtx *ctx)
4327: {
4328:   PetscDraw      draw;

4332:   PetscNew(ctx);
4333:   PetscDrawCreate(comm,host,label,x,y,m,n,&draw);
4334:   PetscDrawSetFromOptions(draw);
4335:   PetscDrawSPCreate(draw,1,&(*ctx)->sp);
4336:   PetscDrawDestroy(&draw);
4337:   (*ctx)->howoften = howoften;
4338:   return(0);

4340: }

4342: /*
4343:   Destroys a TSMonitorSPCtx that was created with TSMonitorSPCtxCreate
4344: */
4345: PetscErrorCode TSMonitorSPCtxDestroy(TSMonitorSPCtx *ctx)
4346: {


4351:   PetscDrawSPDestroy(&(*ctx)->sp);
4352:   PetscFree(*ctx);

4354:   return(0);

4356: }

4358: /*@
4359:    TSGetTime - Gets the time of the most recently completed step.

4361:    Not Collective

4363:    Input Parameter:
4364: .  ts - the TS context obtained from TSCreate()

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

4369:    Level: beginner

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

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

4377: @*/
4378: PetscErrorCode  TSGetTime(TS ts,PetscReal *t)
4379: {
4383:   *t = ts->ptime;
4384:   return(0);
4385: }

4387: /*@
4388:    TSGetPrevTime - Gets the starting time of the previously completed step.

4390:    Not Collective

4392:    Input Parameter:
4393: .  ts - the TS context obtained from TSCreate()

4395:    Output Parameter:
4396: .  t  - the previous time

4398:    Level: beginner

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

4402: @*/
4403: PetscErrorCode  TSGetPrevTime(TS ts,PetscReal *t)
4404: {
4408:   *t = ts->ptime_prev;
4409:   return(0);
4410: }

4412: /*@
4413:    TSSetTime - Allows one to reset the time.

4415:    Logically Collective on TS

4417:    Input Parameters:
4418: +  ts - the TS context obtained from TSCreate()
4419: -  time - the time

4421:    Level: intermediate

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

4425: @*/
4426: PetscErrorCode  TSSetTime(TS ts, PetscReal t)
4427: {
4431:   ts->ptime = t;
4432:   return(0);
4433: }

4435: /*@C
4436:    TSSetOptionsPrefix - Sets the prefix used for searching for all
4437:    TS options in the database.

4439:    Logically Collective on TS

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

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

4450:    Level: advanced

4452: .seealso: TSSetFromOptions()

4454: @*/
4455: PetscErrorCode  TSSetOptionsPrefix(TS ts,const char prefix[])
4456: {
4458:   SNES           snes;

4462:   PetscObjectSetOptionsPrefix((PetscObject)ts,prefix);
4463:   TSGetSNES(ts,&snes);
4464:   SNESSetOptionsPrefix(snes,prefix);
4465:   return(0);
4466: }

4468: /*@C
4469:    TSAppendOptionsPrefix - Appends to the prefix used for searching for all
4470:    TS options in the database.

4472:    Logically Collective on TS

4474:    Input Parameter:
4475: +  ts     - The TS context
4476: -  prefix - The prefix to prepend to all option names

4478:    Notes:
4479:    A hyphen (-) must NOT be given at the beginning of the prefix name.
4480:    The first character of all runtime options is AUTOMATICALLY the
4481:    hyphen.

4483:    Level: advanced

4485: .seealso: TSGetOptionsPrefix()

4487: @*/
4488: PetscErrorCode  TSAppendOptionsPrefix(TS ts,const char prefix[])
4489: {
4491:   SNES           snes;

4495:   PetscObjectAppendOptionsPrefix((PetscObject)ts,prefix);
4496:   TSGetSNES(ts,&snes);
4497:   SNESAppendOptionsPrefix(snes,prefix);
4498:   return(0);
4499: }

4501: /*@C
4502:    TSGetOptionsPrefix - Sets the prefix used for searching for all
4503:    TS options in the database.

4505:    Not Collective

4507:    Input Parameter:
4508: .  ts - The TS context

4510:    Output Parameter:
4511: .  prefix - A pointer to the prefix string used

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

4517:    Level: intermediate

4519: .seealso: TSAppendOptionsPrefix()
4520: @*/
4521: PetscErrorCode  TSGetOptionsPrefix(TS ts,const char *prefix[])
4522: {

4528:   PetscObjectGetOptionsPrefix((PetscObject)ts,prefix);
4529:   return(0);
4530: }

4532: /*@C
4533:    TSGetRHSJacobian - Returns the Jacobian J at the present timestep.

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

4537:    Input Parameter:
4538: .  ts  - The TS context obtained from TSCreate()

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

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

4549:    Level: intermediate

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

4553: @*/
4554: PetscErrorCode  TSGetRHSJacobian(TS ts,Mat *Amat,Mat *Pmat,TSRHSJacobian *func,void **ctx)
4555: {
4557:   DM             dm;

4560:   if (Amat || Pmat) {
4561:     SNES snes;
4562:     TSGetSNES(ts,&snes);
4563:     SNESSetUpMatrices(snes);
4564:     SNESGetJacobian(snes,Amat,Pmat,NULL,NULL);
4565:   }
4566:   TSGetDM(ts,&dm);
4567:   DMTSGetRHSJacobian(dm,func,ctx);
4568:   return(0);
4569: }

4571: /*@C
4572:    TSGetIJacobian - Returns the implicit Jacobian at the present timestep.

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

4576:    Input Parameter:
4577: .  ts  - The TS context obtained from TSCreate()

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

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

4588:    Level: advanced

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

4592: @*/
4593: PetscErrorCode  TSGetIJacobian(TS ts,Mat *Amat,Mat *Pmat,TSIJacobian *f,void **ctx)
4594: {
4596:   DM             dm;

4599:   if (Amat || Pmat) {
4600:     SNES snes;
4601:     TSGetSNES(ts,&snes);
4602:     SNESSetUpMatrices(snes);
4603:     SNESGetJacobian(snes,Amat,Pmat,NULL,NULL);
4604:   }
4605:   TSGetDM(ts,&dm);
4606:   DMTSGetIJacobian(dm,f,ctx);
4607:   return(0);
4608: }

4610: /*@C
4611:    TSMonitorDrawSolution - Monitors progress of the TS solvers by calling
4612:    VecView() for the solution at each timestep

4614:    Collective on TS

4616:    Input Parameters:
4617: +  ts - the TS context
4618: .  step - current time-step
4619: .  ptime - current time
4620: -  dummy - either a viewer or NULL

4622:    Options Database:
4623: .   -ts_monitor_draw_solution_initial - show initial solution as well as current solution

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

4629:    Level: intermediate

4631: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView()
4632: @*/
4633: PetscErrorCode  TSMonitorDrawSolution(TS ts,PetscInt step,PetscReal ptime,Vec u,void *dummy)
4634: {
4635:   PetscErrorCode   ierr;
4636:   TSMonitorDrawCtx ictx = (TSMonitorDrawCtx)dummy;
4637:   PetscDraw        draw;

4640:   if (!step && ictx->showinitial) {
4641:     if (!ictx->initialsolution) {
4642:       VecDuplicate(u,&ictx->initialsolution);
4643:     }
4644:     VecCopy(u,ictx->initialsolution);
4645:   }
4646:   if (!(((ictx->howoften > 0) && (!(step % ictx->howoften))) || ((ictx->howoften == -1) && ts->reason))) return(0);

4648:   if (ictx->showinitial) {
4649:     PetscReal pause;
4650:     PetscViewerDrawGetPause(ictx->viewer,&pause);
4651:     PetscViewerDrawSetPause(ictx->viewer,0.0);
4652:     VecView(ictx->initialsolution,ictx->viewer);
4653:     PetscViewerDrawSetPause(ictx->viewer,pause);
4654:     PetscViewerDrawSetHold(ictx->viewer,PETSC_TRUE);
4655:   }
4656:   VecView(u,ictx->viewer);
4657:   if (ictx->showtimestepandtime) {
4658:     PetscReal xl,yl,xr,yr,h;
4659:     char      time[32];

4661:     PetscViewerDrawGetDraw(ictx->viewer,0,&draw);
4662:     PetscSNPrintf(time,32,"Timestep %d Time %g",(int)step,(double)ptime);
4663:     PetscDrawGetCoordinates(draw,&xl,&yl,&xr,&yr);
4664:     h    = yl + .95*(yr - yl);
4665:     PetscDrawStringCentered(draw,.5*(xl+xr),h,PETSC_DRAW_BLACK,time);
4666:     PetscDrawFlush(draw);
4667:   }

4669:   if (ictx->showinitial) {
4670:     PetscViewerDrawSetHold(ictx->viewer,PETSC_FALSE);
4671:   }
4672:   return(0);
4673: }

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

4678:    Collective on TS

4680:    Input Parameters:
4681: +  ts - the TS context
4682: .  step - current time-step
4683: .  ptime - current time
4684: -  dummy - either a viewer or NULL

4686:    Level: intermediate

4688: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView()
4689: @*/
4690: PetscErrorCode  TSMonitorDrawSolutionPhase(TS ts,PetscInt step,PetscReal ptime,Vec u,void *dummy)
4691: {
4692:   PetscErrorCode    ierr;
4693:   TSMonitorDrawCtx  ictx = (TSMonitorDrawCtx)dummy;
4694:   PetscDraw         draw;
4695:   PetscDrawAxis     axis;
4696:   PetscInt          n;
4697:   PetscMPIInt       size;
4698:   PetscReal         U0,U1,xl,yl,xr,yr,h;
4699:   char              time[32];
4700:   const PetscScalar *U;

4703:   MPI_Comm_size(PetscObjectComm((PetscObject)ts),&size);
4704:   if (size != 1) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"Only allowed for sequential runs");
4705:   VecGetSize(u,&n);
4706:   if (n != 2) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"Only for ODEs with two unknowns");

4708:   PetscViewerDrawGetDraw(ictx->viewer,0,&draw);
4709:   PetscViewerDrawGetDrawAxis(ictx->viewer,0,&axis);
4710:   PetscDrawAxisGetLimits(axis,&xl,&xr,&yl,&yr);
4711:   if (!step) {
4712:     PetscDrawClear(draw);
4713:     PetscDrawAxisDraw(axis);
4714:   }

4716:   VecGetArrayRead(u,&U);
4717:   U0 = PetscRealPart(U[0]);
4718:   U1 = PetscRealPart(U[1]);
4719:   VecRestoreArrayRead(u,&U);
4720:   if ((U0 < xl) || (U1 < yl) || (U0 > xr) || (U1 > yr)) return(0);

4722:   PetscDrawCollectiveBegin(draw);
4723:   PetscDrawPoint(draw,U0,U1,PETSC_DRAW_BLACK);
4724:   if (ictx->showtimestepandtime) {
4725:     PetscDrawGetCoordinates(draw,&xl,&yl,&xr,&yr);
4726:     PetscSNPrintf(time,32,"Timestep %d Time %g",(int)step,(double)ptime);
4727:     h    = yl + .95*(yr - yl);
4728:     PetscDrawStringCentered(draw,.5*(xl+xr),h,PETSC_DRAW_BLACK,time);
4729:   }
4730:   PetscDrawCollectiveEnd(draw);
4731:   PetscDrawFlush(draw);
4732:   PetscDrawPause(draw);
4733:   PetscDrawSave(draw);
4734:   return(0);
4735: }

4737: /*@C
4738:    TSMonitorDrawCtxDestroy - Destroys the monitor context for TSMonitorDrawSolution()

4740:    Collective on TS

4742:    Input Parameters:
4743: .    ctx - the monitor context

4745:    Level: intermediate

4747: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorDrawSolution(), TSMonitorDrawError()
4748: @*/
4749: PetscErrorCode  TSMonitorDrawCtxDestroy(TSMonitorDrawCtx *ictx)
4750: {

4754:   PetscViewerDestroy(&(*ictx)->viewer);
4755:   VecDestroy(&(*ictx)->initialsolution);
4756:   PetscFree(*ictx);
4757:   return(0);
4758: }

4760: /*@C
4761:    TSMonitorDrawCtxCreate - Creates the monitor context for TSMonitorDrawCtx

4763:    Collective on TS

4765:    Input Parameter:
4766: .    ts - time-step context

4768:    Output Patameter:
4769: .    ctx - the monitor context

4771:    Options Database:
4772: .   -ts_monitor_draw_solution_initial - show initial solution as well as current solution

4774:    Level: intermediate

4776: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorDrawCtx()
4777: @*/
4778: PetscErrorCode  TSMonitorDrawCtxCreate(MPI_Comm comm,const char host[],const char label[],int x,int y,int m,int n,PetscInt howoften,TSMonitorDrawCtx *ctx)
4779: {
4780:   PetscErrorCode   ierr;

4783:   PetscNew(ctx);
4784:   PetscViewerDrawOpen(comm,host,label,x,y,m,n,&(*ctx)->viewer);
4785:   PetscViewerSetFromOptions((*ctx)->viewer);

4787:   (*ctx)->howoften    = howoften;
4788:   (*ctx)->showinitial = PETSC_FALSE;
4789:   PetscOptionsGetBool(NULL,NULL,"-ts_monitor_draw_solution_initial",&(*ctx)->showinitial,NULL);

4791:   (*ctx)->showtimestepandtime = PETSC_FALSE;
4792:   PetscOptionsGetBool(NULL,NULL,"-ts_monitor_draw_solution_show_time",&(*ctx)->showtimestepandtime,NULL);
4793:   return(0);
4794: }

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

4800:    Collective on TS

4802:    Input Parameters:
4803: +  ts - the TS context
4804: .  step - current time-step
4805: .  ptime - current time
4806: -  dummy - either a viewer or NULL

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

4811:    Level: intermediate

4813: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSSetSolutionFunction()
4814: @*/
4815: PetscErrorCode  TSMonitorDrawSolutionFunction(TS ts,PetscInt step,PetscReal ptime,Vec u,void *dummy)
4816: {
4817:   PetscErrorCode   ierr;
4818:   TSMonitorDrawCtx ctx    = (TSMonitorDrawCtx)dummy;
4819:   PetscViewer      viewer = ctx->viewer;
4820:   Vec              work;

4823:   if (!(((ctx->howoften > 0) && (!(step % ctx->howoften))) || ((ctx->howoften == -1) && ts->reason))) return(0);
4824:   VecDuplicate(u,&work);
4825:   TSComputeSolutionFunction(ts,ptime,work);
4826:   VecView(work,viewer);
4827:   VecDestroy(&work);
4828:   return(0);
4829: }

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

4835:    Collective on TS

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

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

4846:    Level: intermediate

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

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

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

4871:    Logically Collective on ts

4873:    Input Parameters:
4874: +  ts - the ODE integrator object
4875: -  dm - the dm, cannot be NULL

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

4882:    Level: intermediate

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

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

4908:   TSGetSNES(ts,&snes);
4909:   SNESSetDM(snes,dm);
4910:   return(0);
4911: }

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

4916:    Not Collective

4918:    Input Parameter:
4919: . ts - the preconditioner context

4921:    Output Parameter:
4922: .  dm - the dm

4924:    Level: intermediate

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

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

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

4945:    Logically Collective on SNES

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

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

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

4959:    Level: advanced

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

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

4977: /*@
4978:    SNESTSFormJacobian - Function to evaluate the Jacobian

4980:    Collective on SNES

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

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

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

4995:    Level: developer

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

5012:   (ts->ops->snesjacobian)(snes,U,A,B,ts);
5013:   return(0);
5014: }

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

5019:    Collective on TS

5021:    Input Arguments:
5022: +  ts - time stepping context
5023: .  t - time at which to evaluate
5024: .  U - state at which to evaluate
5025: -  ctx - context

5027:    Output Arguments:
5028: .  F - right hand side

5030:    Level: intermediate

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

5036: .seealso: TSSetRHSFunction(), TSSetRHSJacobian(), TSComputeRHSJacobianConstant()
5037: @*/
5038: PetscErrorCode TSComputeRHSFunctionLinear(TS ts,PetscReal t,Vec U,Vec F,void *ctx)
5039: {
5041:   Mat            Arhs,Brhs;

5044:   TSGetRHSMats_Private(ts,&Arhs,&Brhs);
5045:   TSComputeRHSJacobian(ts,t,U,Arhs,Brhs);
5046:   MatMult(Arhs,U,F);
5047:   return(0);
5048: }

5050: /*@C
5051:    TSComputeRHSJacobianConstant - Reuses a Jacobian that is time-independent.

5053:    Collective on TS

5055:    Input Arguments:
5056: +  ts - time stepping context
5057: .  t - time at which to evaluate
5058: .  U - state at which to evaluate
5059: -  ctx - context

5061:    Output Arguments:
5062: +  A - pointer to operator
5063: .  B - pointer to preconditioning matrix
5064: -  flg - matrix structure flag

5066:    Level: intermediate

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

5071: .seealso: TSSetRHSFunction(), TSSetRHSJacobian(), TSComputeRHSFunctionLinear()
5072: @*/
5073: PetscErrorCode TSComputeRHSJacobianConstant(TS ts,PetscReal t,Vec U,Mat A,Mat B,void *ctx)
5074: {
5076:   return(0);
5077: }

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

5082:    Collective on TS

5084:    Input Arguments:
5085: +  ts - time stepping context
5086: .  t - time at which to evaluate
5087: .  U - state at which to evaluate
5088: .  Udot - time derivative of state vector
5089: -  ctx - context

5091:    Output Arguments:
5092: .  F - left hand side

5094:    Level: intermediate

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

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

5104: .seealso: TSSetIFunction(), TSSetIJacobian(), TSComputeIJacobianConstant(), TSComputeRHSFunctionLinear()
5105: @*/
5106: PetscErrorCode TSComputeIFunctionLinear(TS ts,PetscReal t,Vec U,Vec Udot,Vec F,void *ctx)
5107: {
5109:   Mat            A,B;

5112:   TSGetIJacobian(ts,&A,&B,NULL,NULL);
5113:   TSComputeIJacobian(ts,t,U,Udot,1.0,A,B,PETSC_TRUE);
5114:   MatMult(A,Udot,F);
5115:   return(0);
5116: }

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

5121:    Collective on TS

5123:    Input Arguments:
5124: +  ts - time stepping context
5125: .  t - time at which to evaluate
5126: .  U - state at which to evaluate
5127: .  Udot - time derivative of state vector
5128: .  shift - shift to apply
5129: -  ctx - context

5131:    Output Arguments:
5132: +  A - pointer to operator
5133: .  B - pointer to preconditioning matrix
5134: -  flg - matrix structure flag

5136:    Level: advanced

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

5141:    It is only appropriate for problems of the form

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

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

5149: $    shift*M + J

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

5154: .seealso: TSSetIFunction(), TSSetIJacobian(), TSComputeIFunctionLinear()
5155: @*/
5156: PetscErrorCode TSComputeIJacobianConstant(TS ts,PetscReal t,Vec U,Vec Udot,PetscReal shift,Mat A,Mat B,void *ctx)
5157: {

5161:   MatScale(A, shift / ts->ijacobian.shift);
5162:   ts->ijacobian.shift = shift;
5163:   return(0);
5164: }

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

5169:    Not Collective

5171:    Input Parameter:
5172: .  ts - the TS context

5174:    Output Parameter:
5175: .  equation_type - see TSEquationType

5177:    Level: beginner

5179: .seealso: TSSetEquationType(), TSEquationType
5180: @*/
5181: PetscErrorCode  TSGetEquationType(TS ts,TSEquationType *equation_type)
5182: {
5186:   *equation_type = ts->equation_type;
5187:   return(0);
5188: }

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

5193:    Not Collective

5195:    Input Parameter:
5196: +  ts - the TS context
5197: -  equation_type - see TSEquationType

5199:    Level: advanced

5201: .seealso: TSGetEquationType(), TSEquationType
5202: @*/
5203: PetscErrorCode  TSSetEquationType(TS ts,TSEquationType equation_type)
5204: {
5207:   ts->equation_type = equation_type;
5208:   return(0);
5209: }

5211: /*@
5212:    TSGetConvergedReason - Gets the reason the TS iteration was stopped.

5214:    Not Collective

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

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

5223:    Level: beginner

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

5228: .seealso: TSSetConvergenceTest(), TSConvergedReason
5229: @*/
5230: PetscErrorCode  TSGetConvergedReason(TS ts,TSConvergedReason *reason)
5231: {
5235:   *reason = ts->reason;
5236:   return(0);
5237: }

5239: /*@
5240:    TSSetConvergedReason - Sets the reason for handling the convergence of TSSolve.

5242:    Logically Collective; reason must contain common value

5244:    Input Parameters:
5245: +  ts - the TS context
5246: -  reason - negative value indicates diverged, positive value converged, see TSConvergedReason or the
5247:             manual pages for the individual convergence tests for complete lists

5249:    Level: advanced

5251:    Notes:
5252:    Can only be called while TSSolve() is active.

5254: .seealso: TSConvergedReason
5255: @*/
5256: PetscErrorCode  TSSetConvergedReason(TS ts,TSConvergedReason reason)
5257: {
5260:   ts->reason = reason;
5261:   return(0);
5262: }

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

5267:    Not Collective

5269:    Input Parameter:
5270: .  ts - the TS context

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

5275:    Level: beginner

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

5280: .seealso: TSSetConvergenceTest(), TSConvergedReason
5281: @*/
5282: PetscErrorCode  TSGetSolveTime(TS ts,PetscReal *ftime)
5283: {
5287:   *ftime = ts->solvetime;
5288:   return(0);
5289: }

5291: /*@
5292:    TSGetSNESIterations - Gets the total number of nonlinear iterations
5293:    used by the time integrator.

5295:    Not Collective

5297:    Input Parameter:
5298: .  ts - TS context

5300:    Output Parameter:
5301: .  nits - number of nonlinear iterations

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

5306:    Level: intermediate

5308: .seealso:  TSGetKSPIterations()
5309: @*/
5310: PetscErrorCode TSGetSNESIterations(TS ts,PetscInt *nits)
5311: {
5315:   *nits = ts->snes_its;
5316:   return(0);
5317: }

5319: /*@
5320:    TSGetKSPIterations - Gets the total number of linear iterations
5321:    used by the time integrator.

5323:    Not Collective

5325:    Input Parameter:
5326: .  ts - TS context

5328:    Output Parameter:
5329: .  lits - number of linear iterations

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

5334:    Level: intermediate

5336: .seealso:  TSGetSNESIterations(), SNESGetKSPIterations()
5337: @*/
5338: PetscErrorCode TSGetKSPIterations(TS ts,PetscInt *lits)
5339: {
5343:   *lits = ts->ksp_its;
5344:   return(0);
5345: }

5347: /*@
5348:    TSGetStepRejections - Gets the total number of rejected steps.

5350:    Not Collective

5352:    Input Parameter:
5353: .  ts - TS context

5355:    Output Parameter:
5356: .  rejects - number of steps rejected

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

5361:    Level: intermediate

5363: .seealso:  TSGetSNESIterations(), TSGetKSPIterations(), TSSetMaxStepRejections(), TSGetSNESFailures(), TSSetMaxSNESFailures(), TSSetErrorIfStepFails()
5364: @*/
5365: PetscErrorCode TSGetStepRejections(TS ts,PetscInt *rejects)
5366: {
5370:   *rejects = ts->reject;
5371:   return(0);
5372: }

5374: /*@
5375:    TSGetSNESFailures - Gets the total number of failed SNES solves

5377:    Not Collective

5379:    Input Parameter:
5380: .  ts - TS context

5382:    Output Parameter:
5383: .  fails - number of failed nonlinear solves

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

5388:    Level: intermediate

5390: .seealso:  TSGetSNESIterations(), TSGetKSPIterations(), TSSetMaxStepRejections(), TSGetStepRejections(), TSSetMaxSNESFailures()
5391: @*/
5392: PetscErrorCode TSGetSNESFailures(TS ts,PetscInt *fails)
5393: {
5397:   *fails = ts->num_snes_failures;
5398:   return(0);
5399: }

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

5404:    Not Collective

5406:    Input Parameter:
5407: +  ts - TS context
5408: -  rejects - maximum number of rejected steps, pass -1 for unlimited

5410:    Notes:
5411:    The counter is reset to zero for each step

5413:    Options Database Key:
5414:  .  -ts_max_reject - Maximum number of step rejections before a step fails

5416:    Level: intermediate

5418: .seealso:  TSGetSNESIterations(), TSGetKSPIterations(), TSSetMaxSNESFailures(), TSGetStepRejections(), TSGetSNESFailures(), TSSetErrorIfStepFails(), TSGetConvergedReason()
5419: @*/
5420: PetscErrorCode TSSetMaxStepRejections(TS ts,PetscInt rejects)
5421: {
5424:   ts->max_reject = rejects;
5425:   return(0);
5426: }

5428: /*@
5429:    TSSetMaxSNESFailures - Sets the maximum number of failed SNES solves

5431:    Not Collective

5433:    Input Parameter:
5434: +  ts - TS context
5435: -  fails - maximum number of failed nonlinear solves, pass -1 for unlimited

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

5440:    Options Database Key:
5441:  .  -ts_max_snes_failures - Maximum number of nonlinear solve failures

5443:    Level: intermediate

5445: .seealso:  TSGetSNESIterations(), TSGetKSPIterations(), TSSetMaxStepRejections(), TSGetStepRejections(), TSGetSNESFailures(), SNESGetConvergedReason(), TSGetConvergedReason()
5446: @*/
5447: PetscErrorCode TSSetMaxSNESFailures(TS ts,PetscInt fails)
5448: {
5451:   ts->max_snes_failures = fails;
5452:   return(0);
5453: }

5455: /*@
5456:    TSSetErrorIfStepFails - Error if no step succeeds

5458:    Not Collective

5460:    Input Parameter:
5461: +  ts - TS context
5462: -  err - PETSC_TRUE to error if no step succeeds, PETSC_FALSE to return without failure

5464:    Options Database Key:
5465:  .  -ts_error_if_step_fails - Error if no step succeeds

5467:    Level: intermediate

5469: .seealso:  TSGetSNESIterations(), TSGetKSPIterations(), TSSetMaxStepRejections(), TSGetStepRejections(), TSGetSNESFailures(), TSSetErrorIfStepFails(), TSGetConvergedReason()
5470: @*/
5471: PetscErrorCode TSSetErrorIfStepFails(TS ts,PetscBool err)
5472: {
5475:   ts->errorifstepfailed = err;
5476:   return(0);
5477: }

5479: /*@C
5480:    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

5482:    Collective on TS

5484:    Input Parameters:
5485: +  ts - the TS context
5486: .  step - current time-step
5487: .  ptime - current time
5488: .  u - current state
5489: -  vf - viewer and its format

5491:    Level: intermediate

5493: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView()
5494: @*/
5495: PetscErrorCode  TSMonitorSolution(TS ts,PetscInt step,PetscReal ptime,Vec u,PetscViewerAndFormat *vf)
5496: {

5500:   PetscViewerPushFormat(vf->viewer,vf->format);
5501:   VecView(u,vf->viewer);
5502:   PetscViewerPopFormat(vf->viewer);
5503:   return(0);
5504: }

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

5509:    Collective on TS

5511:    Input Parameters:
5512: +  ts - the TS context
5513: .  step - current time-step
5514: .  ptime - current time
5515: .  u - current state
5516: -  filenametemplate - string containing a format specifier for the integer time step (e.g. %03D)

5518:    Level: intermediate

5520:    Notes:
5521:    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.
5522:    These are named according to the file name template.

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

5526: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView()
5527: @*/
5528: PetscErrorCode TSMonitorSolutionVTK(TS ts,PetscInt step,PetscReal ptime,Vec u,void *filenametemplate)
5529: {
5531:   char           filename[PETSC_MAX_PATH_LEN];
5532:   PetscViewer    viewer;

5535:   if (step < 0) return(0); /* -1 indicates interpolated solution */
5536:   PetscSNPrintf(filename,sizeof(filename),(const char*)filenametemplate,step);
5537:   PetscViewerVTKOpen(PetscObjectComm((PetscObject)ts),filename,FILE_MODE_WRITE,&viewer);
5538:   VecView(u,viewer);
5539:   PetscViewerDestroy(&viewer);
5540:   return(0);
5541: }

5543: /*@C
5544:    TSMonitorSolutionVTKDestroy - Destroy context for monitoring

5546:    Collective on TS

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

5551:    Level: intermediate

5553:    Note:
5554:    This function is normally passed to TSMonitorSet() along with TSMonitorSolutionVTK().

5556: .seealso: TSMonitorSet(), TSMonitorSolutionVTK()
5557: @*/
5558: PetscErrorCode TSMonitorSolutionVTKDestroy(void *filenametemplate)
5559: {

5563:   PetscFree(*(char**)filenametemplate);
5564:   return(0);
5565: }

5567: /*@
5568:    TSGetAdapt - Get the adaptive controller context for the current method

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

5572:    Input Arguments:
5573: .  ts - time stepping context

5575:    Output Arguments:
5576: .  adapt - adaptive controller

5578:    Level: intermediate

5580: .seealso: TSAdapt, TSAdaptSetType(), TSAdaptChoose()
5581: @*/
5582: PetscErrorCode TSGetAdapt(TS ts,TSAdapt *adapt)
5583: {

5589:   if (!ts->adapt) {
5590:     TSAdaptCreate(PetscObjectComm((PetscObject)ts),&ts->adapt);
5591:     PetscLogObjectParent((PetscObject)ts,(PetscObject)ts->adapt);
5592:     PetscObjectIncrementTabLevel((PetscObject)ts->adapt,(PetscObject)ts,1);
5593:   }
5594:   *adapt = ts->adapt;
5595:   return(0);
5596: }

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

5601:    Logically Collective

5603:    Input Arguments:
5604: +  ts - time integration context
5605: .  atol - scalar absolute tolerances, PETSC_DECIDE to leave current value
5606: .  vatol - vector of absolute tolerances or NULL, used in preference to atol if present
5607: .  rtol - scalar relative tolerances, PETSC_DECIDE to leave current value
5608: -  vrtol - vector of relative tolerances or NULL, used in preference to atol if present

5610:    Options Database keys:
5611: +  -ts_rtol <rtol> - relative tolerance for local truncation error
5612: -  -ts_atol <atol> Absolute tolerance for local truncation error

5614:    Notes:
5615:    With PETSc's implicit schemes for DAE problems, the calculation of the local truncation error
5616:    (LTE) includes both the differential and the algebraic variables. If one wants the LTE to be
5617:    computed only for the differential or the algebraic part then this can be done using the vector of
5618:    tolerances vatol. For example, by setting the tolerance vector with the desired tolerance for the
5619:    differential part and infinity for the algebraic part, the LTE calculation will include only the
5620:    differential variables.

5622:    Level: beginner

5624: .seealso: TS, TSAdapt, TSErrorWeightedNorm(), TSGetTolerances()
5625: @*/
5626: PetscErrorCode TSSetTolerances(TS ts,PetscReal atol,Vec vatol,PetscReal rtol,Vec vrtol)
5627: {

5631:   if (atol != PETSC_DECIDE && atol != PETSC_DEFAULT) ts->atol = atol;
5632:   if (vatol) {
5633:     PetscObjectReference((PetscObject)vatol);
5634:     VecDestroy(&ts->vatol);
5635:     ts->vatol = vatol;
5636:   }
5637:   if (rtol != PETSC_DECIDE && rtol != PETSC_DEFAULT) ts->rtol = rtol;
5638:   if (vrtol) {
5639:     PetscObjectReference((PetscObject)vrtol);
5640:     VecDestroy(&ts->vrtol);
5641:     ts->vrtol = vrtol;
5642:   }
5643:   return(0);
5644: }

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

5649:    Logically Collective

5651:    Input Arguments:
5652: .  ts - time integration context

5654:    Output Arguments:
5655: +  atol - scalar absolute tolerances, NULL to ignore
5656: .  vatol - vector of absolute tolerances, NULL to ignore
5657: .  rtol - scalar relative tolerances, NULL to ignore
5658: -  vrtol - vector of relative tolerances, NULL to ignore

5660:    Level: beginner

5662: .seealso: TS, TSAdapt, TSErrorWeightedNorm(), TSSetTolerances()
5663: @*/
5664: PetscErrorCode TSGetTolerances(TS ts,PetscReal *atol,Vec *vatol,PetscReal *rtol,Vec *vrtol)
5665: {
5667:   if (atol)  *atol  = ts->atol;
5668:   if (vatol) *vatol = ts->vatol;
5669:   if (rtol)  *rtol  = ts->rtol;
5670:   if (vrtol) *vrtol = ts->vrtol;
5671:   return(0);
5672: }

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

5677:    Collective on TS

5679:    Input Arguments:
5680: +  ts - time stepping context
5681: .  U - state vector, usually ts->vec_sol
5682: -  Y - state vector to be compared to U

5684:    Output Arguments:
5685: +  norm - weighted norm, a value of 1.0 means that the error matches the tolerances
5686: .  norma - weighted norm based on the absolute tolerance, a value of 1.0 means that the error matches the tolerances
5687: -  normr - weighted norm based on the relative tolerance, a value of 1.0 means that the error matches the tolerances

5689:    Level: developer

5691: .seealso: TSErrorWeightedNorm(), TSErrorWeightedNormInfinity()
5692: @*/
5693: PetscErrorCode TSErrorWeightedNorm2(TS ts,Vec U,Vec Y,PetscReal *norm,PetscReal *norma,PetscReal *normr)
5694: {
5695:   PetscErrorCode    ierr;
5696:   PetscInt          i,n,N,rstart;
5697:   PetscInt          n_loc,na_loc,nr_loc;
5698:   PetscReal         n_glb,na_glb,nr_glb;
5699:   const PetscScalar *u,*y;
5700:   PetscReal         sum,suma,sumr,gsum,gsuma,gsumr,diff;
5701:   PetscReal         tol,tola,tolr;
5702:   PetscReal         err_loc[6],err_glb[6];

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

5716:   VecGetSize(U,&N);
5717:   VecGetLocalSize(U,&n);
5718:   VecGetOwnershipRange(U,&rstart,NULL);
5719:   VecGetArrayRead(U,&u);
5720:   VecGetArrayRead(Y,&y);
5721:   sum  = 0.; n_loc  = 0;
5722:   suma = 0.; na_loc = 0;
5723:   sumr = 0.; nr_loc = 0;
5724:   if (ts->vatol && ts->vrtol) {
5725:     const PetscScalar *atol,*rtol;
5726:     VecGetArrayRead(ts->vatol,&atol);
5727:     VecGetArrayRead(ts->vrtol,&rtol);
5728:     for (i=0; i<n; i++) {
5729:       SkipSmallValue(y[i],u[i],ts->adapt->ignore_max);
5730:       diff = PetscAbsScalar(y[i] - u[i]);
5731:       tola = PetscRealPart(atol[i]);
5732:       if(tola>0.){
5733:         suma  += PetscSqr(diff/tola);
5734:         na_loc++;
5735:       }
5736:       tolr = PetscRealPart(rtol[i]) * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
5737:       if(tolr>0.){
5738:         sumr  += PetscSqr(diff/tolr);
5739:         nr_loc++;
5740:       }
5741:       tol=tola+tolr;
5742:       if(tol>0.){
5743:         sum  += PetscSqr(diff/tol);
5744:         n_loc++;
5745:       }
5746:     }
5747:     VecRestoreArrayRead(ts->vatol,&atol);
5748:     VecRestoreArrayRead(ts->vrtol,&rtol);
5749:   } else if (ts->vatol) {       /* vector atol, scalar rtol */
5750:     const PetscScalar *atol;
5751:     VecGetArrayRead(ts->vatol,&atol);
5752:     for (i=0; i<n; i++) {
5753:       SkipSmallValue(y[i],u[i],ts->adapt->ignore_max);
5754:       diff = PetscAbsScalar(y[i] - u[i]);
5755:       tola = PetscRealPart(atol[i]);
5756:       if(tola>0.){
5757:         suma  += PetscSqr(diff/tola);
5758:         na_loc++;
5759:       }
5760:       tolr = ts->rtol * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
5761:       if(tolr>0.){
5762:         sumr  += PetscSqr(diff/tolr);
5763:         nr_loc++;
5764:       }
5765:       tol=tola+tolr;
5766:       if(tol>0.){
5767:         sum  += PetscSqr(diff/tol);
5768:         n_loc++;
5769:       }
5770:     }
5771:     VecRestoreArrayRead(ts->vatol,&atol);
5772:   } else if (ts->vrtol) {       /* scalar atol, vector rtol */
5773:     const PetscScalar *rtol;
5774:     VecGetArrayRead(ts->vrtol,&rtol);
5775:     for (i=0; i<n; i++) {
5776:       SkipSmallValue(y[i],u[i],ts->adapt->ignore_max);
5777:       diff = PetscAbsScalar(y[i] - u[i]);
5778:       tola = ts->atol;
5779:       if(tola>0.){
5780:         suma  += PetscSqr(diff/tola);
5781:         na_loc++;
5782:       }
5783:       tolr = PetscRealPart(rtol[i]) * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
5784:       if(tolr>0.){
5785:         sumr  += PetscSqr(diff/tolr);
5786:         nr_loc++;
5787:       }
5788:       tol=tola+tolr;
5789:       if(tol>0.){
5790:         sum  += PetscSqr(diff/tol);
5791:         n_loc++;
5792:       }
5793:     }
5794:     VecRestoreArrayRead(ts->vrtol,&rtol);
5795:   } else {                      /* scalar atol, scalar rtol */
5796:     for (i=0; i<n; i++) {
5797:       SkipSmallValue(y[i],u[i],ts->adapt->ignore_max);
5798:       diff = PetscAbsScalar(y[i] - u[i]);
5799:       tola = ts->atol;
5800:       if(tola>0.){
5801:         suma  += PetscSqr(diff/tola);
5802:         na_loc++;
5803:       }
5804:       tolr = ts->rtol * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
5805:       if(tolr>0.){
5806:         sumr  += PetscSqr(diff/tolr);
5807:         nr_loc++;
5808:       }
5809:       tol=tola+tolr;
5810:       if(tol>0.){
5811:         sum  += PetscSqr(diff/tol);
5812:         n_loc++;
5813:       }
5814:     }
5815:   }
5816:   VecRestoreArrayRead(U,&u);
5817:   VecRestoreArrayRead(Y,&y);

5819:   err_loc[0] = sum;
5820:   err_loc[1] = suma;
5821:   err_loc[2] = sumr;
5822:   err_loc[3] = (PetscReal)n_loc;
5823:   err_loc[4] = (PetscReal)na_loc;
5824:   err_loc[5] = (PetscReal)nr_loc;

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

5828:   gsum   = err_glb[0];
5829:   gsuma  = err_glb[1];
5830:   gsumr  = err_glb[2];
5831:   n_glb  = err_glb[3];
5832:   na_glb = err_glb[4];
5833:   nr_glb = err_glb[5];

5835:   *norm  = 0.;
5836:   if(n_glb>0. ){*norm  = PetscSqrtReal(gsum  / n_glb );}
5837:   *norma = 0.;
5838:   if(na_glb>0.){*norma = PetscSqrtReal(gsuma / na_glb);}
5839:   *normr = 0.;
5840:   if(nr_glb>0.){*normr = PetscSqrtReal(gsumr / nr_glb);}

5842:   if (PetscIsInfOrNanScalar(*norm)) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_FP,"Infinite or not-a-number generated in norm");
5843:   if (PetscIsInfOrNanScalar(*norma)) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_FP,"Infinite or not-a-number generated in norma");
5844:   if (PetscIsInfOrNanScalar(*normr)) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_FP,"Infinite or not-a-number generated in normr");
5845:   return(0);
5846: }

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

5851:    Collective on TS

5853:    Input Arguments:
5854: +  ts - time stepping context
5855: .  U - state vector, usually ts->vec_sol
5856: -  Y - state vector to be compared to U

5858:    Output Arguments:
5859: +  norm - weighted norm, a value of 1.0 means that the error matches the tolerances
5860: .  norma - weighted norm based on the absolute tolerance, a value of 1.0 means that the error matches the tolerances
5861: -  normr - weighted norm based on the relative tolerance, a value of 1.0 means that the error matches the tolerances

5863:    Level: developer

5865: .seealso: TSErrorWeightedNorm(), TSErrorWeightedNorm2()
5866: @*/
5867: PetscErrorCode TSErrorWeightedNormInfinity(TS ts,Vec U,Vec Y,PetscReal *norm,PetscReal *norma,PetscReal *normr)
5868: {
5869:   PetscErrorCode    ierr;
5870:   PetscInt          i,n,N,rstart;
5871:   const PetscScalar *u,*y;
5872:   PetscReal         max,gmax,maxa,gmaxa,maxr,gmaxr;
5873:   PetscReal         tol,tola,tolr,diff;
5874:   PetscReal         err_loc[3],err_glb[3];

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

5888:   VecGetSize(U,&N);
5889:   VecGetLocalSize(U,&n);
5890:   VecGetOwnershipRange(U,&rstart,NULL);
5891:   VecGetArrayRead(U,&u);
5892:   VecGetArrayRead(Y,&y);

5894:   max=0.;
5895:   maxa=0.;
5896:   maxr=0.;

5898:   if (ts->vatol && ts->vrtol) {     /* vector atol, vector rtol */
5899:     const PetscScalar *atol,*rtol;
5900:     VecGetArrayRead(ts->vatol,&atol);
5901:     VecGetArrayRead(ts->vrtol,&rtol);

5903:     for (i=0; i<n; i++) {
5904:       SkipSmallValue(y[i],u[i],ts->adapt->ignore_max);
5905:       diff = PetscAbsScalar(y[i] - u[i]);
5906:       tola = PetscRealPart(atol[i]);
5907:       tolr = PetscRealPart(rtol[i]) * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
5908:       tol  = tola+tolr;
5909:       if(tola>0.){
5910:         maxa = PetscMax(maxa,diff / tola);
5911:       }
5912:       if(tolr>0.){
5913:         maxr = PetscMax(maxr,diff / tolr);
5914:       }
5915:       if(tol>0.){
5916:         max = PetscMax(max,diff / tol);
5917:       }
5918:     }
5919:     VecRestoreArrayRead(ts->vatol,&atol);
5920:     VecRestoreArrayRead(ts->vrtol,&rtol);
5921:   } else if (ts->vatol) {       /* vector atol, scalar rtol */
5922:     const PetscScalar *atol;
5923:     VecGetArrayRead(ts->vatol,&atol);
5924:     for (i=0; i<n; i++) {
5925:       SkipSmallValue(y[i],u[i],ts->adapt->ignore_max);
5926:       diff = PetscAbsScalar(y[i] - u[i]);
5927:       tola = PetscRealPart(atol[i]);
5928:       tolr = ts->rtol  * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
5929:       tol  = tola+tolr;
5930:       if(tola>0.){
5931:         maxa = PetscMax(maxa,diff / tola);
5932:       }
5933:       if(tolr>0.){
5934:         maxr = PetscMax(maxr,diff / tolr);
5935:       }
5936:       if(tol>0.){
5937:         max = PetscMax(max,diff / tol);
5938:       }
5939:     }
5940:     VecRestoreArrayRead(ts->vatol,&atol);
5941:   } else if (ts->vrtol) {       /* scalar atol, vector rtol */
5942:     const PetscScalar *rtol;
5943:     VecGetArrayRead(ts->vrtol,&rtol);

5945:     for (i=0; i<n; i++) {
5946:       SkipSmallValue(y[i],u[i],ts->adapt->ignore_max);
5947:       diff = PetscAbsScalar(y[i] - u[i]);
5948:       tola = ts->atol;
5949:       tolr = PetscRealPart(rtol[i]) * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
5950:       tol  = tola+tolr;
5951:       if(tola>0.){
5952:         maxa = PetscMax(maxa,diff / tola);
5953:       }
5954:       if(tolr>0.){
5955:         maxr = PetscMax(maxr,diff / tolr);
5956:       }
5957:       if(tol>0.){
5958:         max = PetscMax(max,diff / tol);
5959:       }
5960:     }
5961:     VecRestoreArrayRead(ts->vrtol,&rtol);
5962:   } else {                      /* scalar atol, scalar rtol */

5964:     for (i=0; i<n; i++) {
5965:       SkipSmallValue(y[i],u[i],ts->adapt->ignore_max);
5966:       diff = PetscAbsScalar(y[i] - u[i]);
5967:       tola = ts->atol;
5968:       tolr = ts->rtol * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
5969:       tol  = tola+tolr;
5970:       if(tola>0.){
5971:         maxa = PetscMax(maxa,diff / tola);
5972:       }
5973:       if(tolr>0.){
5974:         maxr = PetscMax(maxr,diff / tolr);
5975:       }
5976:       if(tol>0.){
5977:         max = PetscMax(max,diff / tol);
5978:       }
5979:     }
5980:   }
5981:   VecRestoreArrayRead(U,&u);
5982:   VecRestoreArrayRead(Y,&y);
5983:   err_loc[0] = max;
5984:   err_loc[1] = maxa;
5985:   err_loc[2] = maxr;
5986:   MPIU_Allreduce(err_loc,err_glb,3,MPIU_REAL,MPIU_MAX,PetscObjectComm((PetscObject)ts));
5987:   gmax   = err_glb[0];
5988:   gmaxa  = err_glb[1];
5989:   gmaxr  = err_glb[2];

5991:   *norm = gmax;
5992:   *norma = gmaxa;
5993:   *normr = gmaxr;
5994:   if (PetscIsInfOrNanScalar(*norm)) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_FP,"Infinite or not-a-number generated in norm");
5995:     if (PetscIsInfOrNanScalar(*norma)) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_FP,"Infinite or not-a-number generated in norma");
5996:     if (PetscIsInfOrNanScalar(*normr)) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_FP,"Infinite or not-a-number generated in normr");
5997:   return(0);
5998: }

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

6003:    Collective on TS

6005:    Input Arguments:
6006: +  ts - time stepping context
6007: .  U - state vector, usually ts->vec_sol
6008: .  Y - state vector to be compared to U
6009: -  wnormtype - norm type, either NORM_2 or NORM_INFINITY

6011:    Output Arguments:
6012: +  norm  - weighted norm, a value of 1.0 achieves a balance between absolute and relative tolerances
6013: .  norma - weighted norm, a value of 1.0 means that the error meets the absolute tolerance set by the user
6014: -  normr - weighted norm, a value of 1.0 means that the error meets the relative tolerance set by the user

6016:    Options Database Keys:
6017: .  -ts_adapt_wnormtype <wnormtype> - 2, INFINITY

6019:    Level: developer

6021: .seealso: TSErrorWeightedNormInfinity(), TSErrorWeightedNorm2(), TSErrorWeightedENorm
6022: @*/
6023: PetscErrorCode TSErrorWeightedNorm(TS ts,Vec U,Vec Y,NormType wnormtype,PetscReal *norm,PetscReal *norma,PetscReal *normr)
6024: {

6028:   if (wnormtype == NORM_2) {
6029:     TSErrorWeightedNorm2(ts,U,Y,norm,norma,normr);
6030:   } else if(wnormtype == NORM_INFINITY) {
6031:     TSErrorWeightedNormInfinity(ts,U,Y,norm,norma,normr);
6032:   } else SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"No support for norm type %s",NormTypes[wnormtype]);
6033:   return(0);
6034: }


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

6040:    Collective on TS

6042:    Input Arguments:
6043: +  ts - time stepping context
6044: .  E - error vector
6045: .  U - state vector, usually ts->vec_sol
6046: -  Y - state vector, previous time step

6048:    Output Arguments:
6049: +  norm - weighted norm, a value of 1.0 means that the error matches the tolerances
6050: .  norma - weighted norm based on the absolute tolerance, a value of 1.0 means that the error matches the tolerances
6051: -  normr - weighted norm based on the relative tolerance, a value of 1.0 means that the error matches the tolerances

6053:    Level: developer

6055: .seealso: TSErrorWeightedENorm(), TSErrorWeightedENormInfinity()
6056: @*/
6057: PetscErrorCode TSErrorWeightedENorm2(TS ts,Vec E,Vec U,Vec Y,PetscReal *norm,PetscReal *norma,PetscReal *normr)
6058: {
6059:   PetscErrorCode    ierr;
6060:   PetscInt          i,n,N,rstart;
6061:   PetscInt          n_loc,na_loc,nr_loc;
6062:   PetscReal         n_glb,na_glb,nr_glb;
6063:   const PetscScalar *e,*u,*y;
6064:   PetscReal         err,sum,suma,sumr,gsum,gsuma,gsumr;
6065:   PetscReal         tol,tola,tolr;
6066:   PetscReal         err_loc[6],err_glb[6];


6082:   VecGetSize(E,&N);
6083:   VecGetLocalSize(E,&n);
6084:   VecGetOwnershipRange(E,&rstart,NULL);
6085:   VecGetArrayRead(E,&e);
6086:   VecGetArrayRead(U,&u);
6087:   VecGetArrayRead(Y,&y);
6088:   sum  = 0.; n_loc  = 0;
6089:   suma = 0.; na_loc = 0;
6090:   sumr = 0.; nr_loc = 0;
6091:   if (ts->vatol && ts->vrtol) {
6092:     const PetscScalar *atol,*rtol;
6093:     VecGetArrayRead(ts->vatol,&atol);
6094:     VecGetArrayRead(ts->vrtol,&rtol);
6095:     for (i=0; i<n; i++) {
6096:       SkipSmallValue(y[i],u[i],ts->adapt->ignore_max);
6097:       err = PetscAbsScalar(e[i]);
6098:       tola = PetscRealPart(atol[i]);
6099:       if(tola>0.){
6100:         suma  += PetscSqr(err/tola);
6101:         na_loc++;
6102:       }
6103:       tolr = PetscRealPart(rtol[i]) * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
6104:       if(tolr>0.){
6105:         sumr  += PetscSqr(err/tolr);
6106:         nr_loc++;
6107:       }
6108:       tol=tola+tolr;
6109:       if(tol>0.){
6110:         sum  += PetscSqr(err/tol);
6111:         n_loc++;
6112:       }
6113:     }
6114:     VecRestoreArrayRead(ts->vatol,&atol);
6115:     VecRestoreArrayRead(ts->vrtol,&rtol);
6116:   } else if (ts->vatol) {       /* vector atol, scalar rtol */
6117:     const PetscScalar *atol;
6118:     VecGetArrayRead(ts->vatol,&atol);
6119:     for (i=0; i<n; i++) {
6120:       SkipSmallValue(y[i],u[i],ts->adapt->ignore_max);
6121:       err = PetscAbsScalar(e[i]);
6122:       tola = PetscRealPart(atol[i]);
6123:       if(tola>0.){
6124:         suma  += PetscSqr(err/tola);
6125:         na_loc++;
6126:       }
6127:       tolr = ts->rtol * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
6128:       if(tolr>0.){
6129:         sumr  += PetscSqr(err/tolr);
6130:         nr_loc++;
6131:       }
6132:       tol=tola+tolr;
6133:       if(tol>0.){
6134:         sum  += PetscSqr(err/tol);
6135:         n_loc++;
6136:       }
6137:     }
6138:     VecRestoreArrayRead(ts->vatol,&atol);
6139:   } else if (ts->vrtol) {       /* scalar atol, vector rtol */
6140:     const PetscScalar *rtol;
6141:     VecGetArrayRead(ts->vrtol,&rtol);
6142:     for (i=0; i<n; i++) {
6143:       SkipSmallValue(y[i],u[i],ts->adapt->ignore_max);
6144:       err = PetscAbsScalar(e[i]);
6145:       tola = ts->atol;
6146:       if(tola>0.){
6147:         suma  += PetscSqr(err/tola);
6148:         na_loc++;
6149:       }
6150:       tolr = PetscRealPart(rtol[i]) * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
6151:       if(tolr>0.){
6152:         sumr  += PetscSqr(err/tolr);
6153:         nr_loc++;
6154:       }
6155:       tol=tola+tolr;
6156:       if(tol>0.){
6157:         sum  += PetscSqr(err/tol);
6158:         n_loc++;
6159:       }
6160:     }
6161:     VecRestoreArrayRead(ts->vrtol,&rtol);
6162:   } else {                      /* scalar atol, scalar rtol */
6163:     for (i=0; i<n; i++) {
6164:       SkipSmallValue(y[i],u[i],ts->adapt->ignore_max);
6165:       err = PetscAbsScalar(e[i]);
6166:       tola = ts->atol;
6167:       if(tola>0.){
6168:         suma  += PetscSqr(err/tola);
6169:         na_loc++;
6170:       }
6171:       tolr = ts->rtol * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
6172:       if(tolr>0.){
6173:         sumr  += PetscSqr(err/tolr);
6174:         nr_loc++;
6175:       }
6176:       tol=tola+tolr;
6177:       if(tol>0.){
6178:         sum  += PetscSqr(err/tol);
6179:         n_loc++;
6180:       }
6181:     }
6182:   }
6183:   VecRestoreArrayRead(E,&e);
6184:   VecRestoreArrayRead(U,&u);
6185:   VecRestoreArrayRead(Y,&y);

6187:   err_loc[0] = sum;
6188:   err_loc[1] = suma;
6189:   err_loc[2] = sumr;
6190:   err_loc[3] = (PetscReal)n_loc;
6191:   err_loc[4] = (PetscReal)na_loc;
6192:   err_loc[5] = (PetscReal)nr_loc;

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

6196:   gsum   = err_glb[0];
6197:   gsuma  = err_glb[1];
6198:   gsumr  = err_glb[2];
6199:   n_glb  = err_glb[3];
6200:   na_glb = err_glb[4];
6201:   nr_glb = err_glb[5];

6203:   *norm  = 0.;
6204:   if(n_glb>0. ){*norm  = PetscSqrtReal(gsum  / n_glb );}
6205:   *norma = 0.;
6206:   if(na_glb>0.){*norma = PetscSqrtReal(gsuma / na_glb);}
6207:   *normr = 0.;
6208:   if(nr_glb>0.){*normr = PetscSqrtReal(gsumr / nr_glb);}

6210:   if (PetscIsInfOrNanScalar(*norm)) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_FP,"Infinite or not-a-number generated in norm");
6211:   if (PetscIsInfOrNanScalar(*norma)) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_FP,"Infinite or not-a-number generated in norma");
6212:   if (PetscIsInfOrNanScalar(*normr)) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_FP,"Infinite or not-a-number generated in normr");
6213:   return(0);
6214: }

6216: /*@
6217:    TSErrorWeightedENormInfinity - compute a weighted infinity error norm based on supplied absolute and relative tolerances
6218:    Collective on TS

6220:    Input Arguments:
6221: +  ts - time stepping context
6222: .  E - error vector
6223: .  U - state vector, usually ts->vec_sol
6224: -  Y - state vector, previous time step

6226:    Output Arguments:
6227: +  norm - weighted norm, a value of 1.0 means that the error matches the tolerances
6228: .  norma - weighted norm based on the absolute tolerance, a value of 1.0 means that the error matches the tolerances
6229: -  normr - weighted norm based on the relative tolerance, a value of 1.0 means that the error matches the tolerances

6231:    Level: developer

6233: .seealso: TSErrorWeightedENorm(), TSErrorWeightedENorm2()
6234: @*/
6235: PetscErrorCode TSErrorWeightedENormInfinity(TS ts,Vec E,Vec U,Vec Y,PetscReal *norm,PetscReal *norma,PetscReal *normr)
6236: {
6237:   PetscErrorCode    ierr;
6238:   PetscInt          i,n,N,rstart;
6239:   const PetscScalar *e,*u,*y;
6240:   PetscReal         err,max,gmax,maxa,gmaxa,maxr,gmaxr;
6241:   PetscReal         tol,tola,tolr;
6242:   PetscReal         err_loc[3],err_glb[3];


6258:   VecGetSize(E,&N);
6259:   VecGetLocalSize(E,&n);
6260:   VecGetOwnershipRange(E,&rstart,NULL);
6261:   VecGetArrayRead(E,&e);
6262:   VecGetArrayRead(U,&u);
6263:   VecGetArrayRead(Y,&y);

6265:   max=0.;
6266:   maxa=0.;
6267:   maxr=0.;

6269:   if (ts->vatol && ts->vrtol) {     /* vector atol, vector rtol */
6270:     const PetscScalar *atol,*rtol;
6271:     VecGetArrayRead(ts->vatol,&atol);
6272:     VecGetArrayRead(ts->vrtol,&rtol);

6274:     for (i=0; i<n; i++) {
6275:       SkipSmallValue(y[i],u[i],ts->adapt->ignore_max);
6276:       err = PetscAbsScalar(e[i]);
6277:       tola = PetscRealPart(atol[i]);
6278:       tolr = PetscRealPart(rtol[i]) * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
6279:       tol  = tola+tolr;
6280:       if(tola>0.){
6281:         maxa = PetscMax(maxa,err / tola);
6282:       }
6283:       if(tolr>0.){
6284:         maxr = PetscMax(maxr,err / tolr);
6285:       }
6286:       if(tol>0.){
6287:         max = PetscMax(max,err / tol);
6288:       }
6289:     }
6290:     VecRestoreArrayRead(ts->vatol,&atol);
6291:     VecRestoreArrayRead(ts->vrtol,&rtol);
6292:   } else if (ts->vatol) {       /* vector atol, scalar rtol */
6293:     const PetscScalar *atol;
6294:     VecGetArrayRead(ts->vatol,&atol);
6295:     for (i=0; i<n; i++) {
6296:       SkipSmallValue(y[i],u[i],ts->adapt->ignore_max);
6297:       err = PetscAbsScalar(e[i]);
6298:       tola = PetscRealPart(atol[i]);
6299:       tolr = ts->rtol  * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
6300:       tol  = tola+tolr;
6301:       if(tola>0.){
6302:         maxa = PetscMax(maxa,err / tola);
6303:       }
6304:       if(tolr>0.){
6305:         maxr = PetscMax(maxr,err / tolr);
6306:       }
6307:       if(tol>0.){
6308:         max = PetscMax(max,err / tol);
6309:       }
6310:     }
6311:     VecRestoreArrayRead(ts->vatol,&atol);
6312:   } else if (ts->vrtol) {       /* scalar atol, vector rtol */
6313:     const PetscScalar *rtol;
6314:     VecGetArrayRead(ts->vrtol,&rtol);

6316:     for (i=0; i<n; i++) {
6317:       SkipSmallValue(y[i],u[i],ts->adapt->ignore_max);
6318:       err = PetscAbsScalar(e[i]);
6319:       tola = ts->atol;
6320:       tolr = PetscRealPart(rtol[i]) * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
6321:       tol  = tola+tolr;
6322:       if(tola>0.){
6323:         maxa = PetscMax(maxa,err / tola);
6324:       }
6325:       if(tolr>0.){
6326:         maxr = PetscMax(maxr,err / tolr);
6327:       }
6328:       if(tol>0.){
6329:         max = PetscMax(max,err / tol);
6330:       }
6331:     }
6332:     VecRestoreArrayRead(ts->vrtol,&rtol);
6333:   } else {                      /* scalar atol, scalar rtol */

6335:     for (i=0; i<n; i++) {
6336:       SkipSmallValue(y[i],u[i],ts->adapt->ignore_max);
6337:       err = PetscAbsScalar(e[i]);
6338:       tola = ts->atol;
6339:       tolr = ts->rtol * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
6340:       tol  = tola+tolr;
6341:       if(tola>0.){
6342:         maxa = PetscMax(maxa,err / tola);
6343:       }
6344:       if(tolr>0.){
6345:         maxr = PetscMax(maxr,err / tolr);
6346:       }
6347:       if(tol>0.){
6348:         max = PetscMax(max,err / tol);
6349:       }
6350:     }
6351:   }
6352:   VecRestoreArrayRead(E,&e);
6353:   VecRestoreArrayRead(U,&u);
6354:   VecRestoreArrayRead(Y,&y);
6355:   err_loc[0] = max;
6356:   err_loc[1] = maxa;
6357:   err_loc[2] = maxr;
6358:   MPIU_Allreduce(err_loc,err_glb,3,MPIU_REAL,MPIU_MAX,PetscObjectComm((PetscObject)ts));
6359:   gmax   = err_glb[0];
6360:   gmaxa  = err_glb[1];
6361:   gmaxr  = err_glb[2];

6363:   *norm = gmax;
6364:   *norma = gmaxa;
6365:   *normr = gmaxr;
6366:   if (PetscIsInfOrNanScalar(*norm)) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_FP,"Infinite or not-a-number generated in norm");
6367:     if (PetscIsInfOrNanScalar(*norma)) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_FP,"Infinite or not-a-number generated in norma");
6368:     if (PetscIsInfOrNanScalar(*normr)) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_FP,"Infinite or not-a-number generated in normr");
6369:   return(0);
6370: }

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

6375:    Collective on TS

6377:    Input Arguments:
6378: +  ts - time stepping context
6379: .  E - error vector
6380: .  U - state vector, usually ts->vec_sol
6381: .  Y - state vector, previous time step
6382: -  wnormtype - norm type, either NORM_2 or NORM_INFINITY

6384:    Output Arguments:
6385: +  norm  - weighted norm, a value of 1.0 achieves a balance between absolute and relative tolerances
6386: .  norma - weighted norm, a value of 1.0 means that the error meets the absolute tolerance set by the user
6387: -  normr - weighted norm, a value of 1.0 means that the error meets the relative tolerance set by the user

6389:    Options Database Keys:
6390: .  -ts_adapt_wnormtype <wnormtype> - 2, INFINITY

6392:    Level: developer

6394: .seealso: TSErrorWeightedENormInfinity(), TSErrorWeightedENorm2(), TSErrorWeightedNormInfinity(), TSErrorWeightedNorm2()
6395: @*/
6396: PetscErrorCode TSErrorWeightedENorm(TS ts,Vec E,Vec U,Vec Y,NormType wnormtype,PetscReal *norm,PetscReal *norma,PetscReal *normr)
6397: {

6401:   if (wnormtype == NORM_2) {
6402:     TSErrorWeightedENorm2(ts,E,U,Y,norm,norma,normr);
6403:   } else if(wnormtype == NORM_INFINITY) {
6404:     TSErrorWeightedENormInfinity(ts,E,U,Y,norm,norma,normr);
6405:   } else SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"No support for norm type %s",NormTypes[wnormtype]);
6406:   return(0);
6407: }


6410: /*@
6411:    TSSetCFLTimeLocal - Set the local CFL constraint relative to forward Euler

6413:    Logically Collective on TS

6415:    Input Arguments:
6416: +  ts - time stepping context
6417: -  cfltime - maximum stable time step if using forward Euler (value can be different on each process)

6419:    Note:
6420:    After calling this function, the global CFL time can be obtained by calling TSGetCFLTime()

6422:    Level: intermediate

6424: .seealso: TSGetCFLTime(), TSADAPTCFL
6425: @*/
6426: PetscErrorCode TSSetCFLTimeLocal(TS ts,PetscReal cfltime)
6427: {
6430:   ts->cfltime_local = cfltime;
6431:   ts->cfltime       = -1.;
6432:   return(0);
6433: }

6435: /*@
6436:    TSGetCFLTime - Get the maximum stable time step according to CFL criteria applied to forward Euler

6438:    Collective on TS

6440:    Input Arguments:
6441: .  ts - time stepping context

6443:    Output Arguments:
6444: .  cfltime - maximum stable time step for forward Euler

6446:    Level: advanced

6448: .seealso: TSSetCFLTimeLocal()
6449: @*/
6450: PetscErrorCode TSGetCFLTime(TS ts,PetscReal *cfltime)
6451: {

6455:   if (ts->cfltime < 0) {
6456:     MPIU_Allreduce(&ts->cfltime_local,&ts->cfltime,1,MPIU_REAL,MPIU_MIN,PetscObjectComm((PetscObject)ts));
6457:   }
6458:   *cfltime = ts->cfltime;
6459:   return(0);
6460: }

6462: /*@
6463:    TSVISetVariableBounds - Sets the lower and upper bounds for the solution vector. xl <= x <= xu

6465:    Input Parameters:
6466: +  ts   - the TS context.
6467: .  xl   - lower bound.
6468: -  xu   - upper bound.

6470:    Notes:
6471:    If this routine is not called then the lower and upper bounds are set to
6472:    PETSC_NINFINITY and PETSC_INFINITY respectively during SNESSetUp().

6474:    Level: advanced

6476: @*/
6477: PetscErrorCode TSVISetVariableBounds(TS ts, Vec xl, Vec xu)
6478: {
6480:   SNES           snes;

6483:   TSGetSNES(ts,&snes);
6484:   SNESVISetVariableBounds(snes,xl,xu);
6485:   return(0);
6486: }

6488: /*@C
6489:    TSMonitorLGSolution - Monitors progress of the TS solvers by plotting each component of the solution vector
6490:        in a time based line graph

6492:    Collective on TS

6494:    Input Parameters:
6495: +  ts - the TS context
6496: .  step - current time-step
6497: .  ptime - current time
6498: .  u - current solution
6499: -  dctx - the TSMonitorLGCtx object that contains all the options for the monitoring, this is created with TSMonitorLGCtxCreate()

6501:    Options Database:
6502: .   -ts_monitor_lg_solution_variables

6504:    Level: intermediate

6506:    Notes:
6507:     Each process in a parallel run displays its component solutions in a separate window

6509: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorLGCtxCreate(), TSMonitorLGCtxSetVariableNames(), TSMonitorLGCtxGetVariableNames(),
6510:            TSMonitorLGSetVariableNames(), TSMonitorLGGetVariableNames(), TSMonitorLGSetDisplayVariables(), TSMonitorLGCtxSetDisplayVariables(),
6511:            TSMonitorLGCtxSetTransform(), TSMonitorLGSetTransform(), TSMonitorLGError(), TSMonitorLGSNESIterations(), TSMonitorLGKSPIterations(),
6512:            TSMonitorEnvelopeCtxCreate(), TSMonitorEnvelopeGetBounds(), TSMonitorEnvelopeCtxDestroy(), TSMonitorEnvelop()
6513: @*/
6514: PetscErrorCode  TSMonitorLGSolution(TS ts,PetscInt step,PetscReal ptime,Vec u,void *dctx)
6515: {
6516:   PetscErrorCode    ierr;
6517:   TSMonitorLGCtx    ctx = (TSMonitorLGCtx)dctx;
6518:   const PetscScalar *yy;
6519:   Vec               v;

6522:   if (step < 0) return(0); /* -1 indicates interpolated solution */
6523:   if (!step) {
6524:     PetscDrawAxis axis;
6525:     PetscInt      dim;
6526:     PetscDrawLGGetAxis(ctx->lg,&axis);
6527:     PetscDrawAxisSetLabels(axis,"Solution as function of time","Time","Solution");
6528:     if (!ctx->names) {
6529:       PetscBool flg;
6530:       /* user provides names of variables to plot but no names has been set so assume names are integer values */
6531:       PetscOptionsHasName(((PetscObject)ts)->options,((PetscObject)ts)->prefix,"-ts_monitor_lg_solution_variables",&flg);
6532:       if (flg) {
6533:         PetscInt i,n;
6534:         char     **names;
6535:         VecGetSize(u,&n);
6536:         PetscMalloc1(n+1,&names);
6537:         for (i=0; i<n; i++) {
6538:           PetscMalloc1(5,&names[i]);
6539:           PetscSNPrintf(names[i],5,"%D",i);
6540:         }
6541:         names[n] = NULL;
6542:         ctx->names = names;
6543:       }
6544:     }
6545:     if (ctx->names && !ctx->displaynames) {
6546:       char      **displaynames;
6547:       PetscBool flg;
6548:       VecGetLocalSize(u,&dim);
6549:       PetscCalloc1(dim+1,&displaynames);
6550:       PetscOptionsGetStringArray(((PetscObject)ts)->options,((PetscObject)ts)->prefix,"-ts_monitor_lg_solution_variables",displaynames,&dim,&flg);
6551:       if (flg) {
6552:         TSMonitorLGCtxSetDisplayVariables(ctx,(const char *const *)displaynames);
6553:       }
6554:       PetscStrArrayDestroy(&displaynames);
6555:     }
6556:     if (ctx->displaynames) {
6557:       PetscDrawLGSetDimension(ctx->lg,ctx->ndisplayvariables);
6558:       PetscDrawLGSetLegend(ctx->lg,(const char *const *)ctx->displaynames);
6559:     } else if (ctx->names) {
6560:       VecGetLocalSize(u,&dim);
6561:       PetscDrawLGSetDimension(ctx->lg,dim);
6562:       PetscDrawLGSetLegend(ctx->lg,(const char *const *)ctx->names);
6563:     } else {
6564:       VecGetLocalSize(u,&dim);
6565:       PetscDrawLGSetDimension(ctx->lg,dim);
6566:     }
6567:     PetscDrawLGReset(ctx->lg);
6568:   }

6570:   if (!ctx->transform) v = u;
6571:   else {(*ctx->transform)(ctx->transformctx,u,&v);}
6572:   VecGetArrayRead(v,&yy);
6573:   if (ctx->displaynames) {
6574:     PetscInt i;
6575:     for (i=0; i<ctx->ndisplayvariables; i++)
6576:       ctx->displayvalues[i] = PetscRealPart(yy[ctx->displayvariables[i]]);
6577:     PetscDrawLGAddCommonPoint(ctx->lg,ptime,ctx->displayvalues);
6578:   } else {
6579: #if defined(PETSC_USE_COMPLEX)
6580:     PetscInt  i,n;
6581:     PetscReal *yreal;
6582:     VecGetLocalSize(v,&n);
6583:     PetscMalloc1(n,&yreal);
6584:     for (i=0; i<n; i++) yreal[i] = PetscRealPart(yy[i]);
6585:     PetscDrawLGAddCommonPoint(ctx->lg,ptime,yreal);
6586:     PetscFree(yreal);
6587: #else
6588:     PetscDrawLGAddCommonPoint(ctx->lg,ptime,yy);
6589: #endif
6590:   }
6591:   VecRestoreArrayRead(v,&yy);
6592:   if (ctx->transform) {VecDestroy(&v);}

6594:   if (((ctx->howoften > 0) && (!(step % ctx->howoften))) || ((ctx->howoften == -1) && ts->reason)) {
6595:     PetscDrawLGDraw(ctx->lg);
6596:     PetscDrawLGSave(ctx->lg);
6597:   }
6598:   return(0);
6599: }

6601: /*@C
6602:    TSMonitorLGSetVariableNames - Sets the name of each component in the solution vector so that it may be displayed in the plot

6604:    Collective on TS

6606:    Input Parameters:
6607: +  ts - the TS context
6608: -  names - the names of the components, final string must be NULL

6610:    Level: intermediate

6612:    Notes:
6613:     If the TS object does not have a TSMonitorLGCtx associated with it then this function is ignored

6615: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorLGSetDisplayVariables(), TSMonitorLGCtxSetVariableNames()
6616: @*/
6617: PetscErrorCode  TSMonitorLGSetVariableNames(TS ts,const char * const *names)
6618: {
6619:   PetscErrorCode    ierr;
6620:   PetscInt          i;

6623:   for (i=0; i<ts->numbermonitors; i++) {
6624:     if (ts->monitor[i] == TSMonitorLGSolution) {
6625:       TSMonitorLGCtxSetVariableNames((TSMonitorLGCtx)ts->monitorcontext[i],names);
6626:       break;
6627:     }
6628:   }
6629:   return(0);
6630: }

6632: /*@C
6633:    TSMonitorLGCtxSetVariableNames - Sets the name of each component in the solution vector so that it may be displayed in the plot

6635:    Collective on TS

6637:    Input Parameters:
6638: +  ts - the TS context
6639: -  names - the names of the components, final string must be NULL

6641:    Level: intermediate

6643: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorLGSetDisplayVariables(), TSMonitorLGSetVariableNames()
6644: @*/
6645: PetscErrorCode  TSMonitorLGCtxSetVariableNames(TSMonitorLGCtx ctx,const char * const *names)
6646: {
6647:   PetscErrorCode    ierr;

6650:   PetscStrArrayDestroy(&ctx->names);
6651:   PetscStrArrayallocpy(names,&ctx->names);
6652:   return(0);
6653: }

6655: /*@C
6656:    TSMonitorLGGetVariableNames - Gets the name of each component in the solution vector so that it may be displayed in the plot

6658:    Collective on TS

6660:    Input Parameter:
6661: .  ts - the TS context

6663:    Output Parameter:
6664: .  names - the names of the components, final string must be NULL

6666:    Level: intermediate

6668:    Notes:
6669:     If the TS object does not have a TSMonitorLGCtx associated with it then this function is ignored

6671: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorLGSetDisplayVariables()
6672: @*/
6673: PetscErrorCode  TSMonitorLGGetVariableNames(TS ts,const char *const **names)
6674: {
6675:   PetscInt       i;

6678:   *names = NULL;
6679:   for (i=0; i<ts->numbermonitors; i++) {
6680:     if (ts->monitor[i] == TSMonitorLGSolution) {
6681:       TSMonitorLGCtx  ctx = (TSMonitorLGCtx) ts->monitorcontext[i];
6682:       *names = (const char *const *)ctx->names;
6683:       break;
6684:     }
6685:   }
6686:   return(0);
6687: }

6689: /*@C
6690:    TSMonitorLGCtxSetDisplayVariables - Sets the variables that are to be display in the monitor

6692:    Collective on TS

6694:    Input Parameters:
6695: +  ctx - the TSMonitorLG context
6696: -  displaynames - the names of the components, final string must be NULL

6698:    Level: intermediate

6700: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorLGSetVariableNames()
6701: @*/
6702: PetscErrorCode  TSMonitorLGCtxSetDisplayVariables(TSMonitorLGCtx ctx,const char * const *displaynames)
6703: {
6704:   PetscInt          j = 0,k;
6705:   PetscErrorCode    ierr;

6708:   if (!ctx->names) return(0);
6709:   PetscStrArrayDestroy(&ctx->displaynames);
6710:   PetscStrArrayallocpy(displaynames,&ctx->displaynames);
6711:   while (displaynames[j]) j++;
6712:   ctx->ndisplayvariables = j;
6713:   PetscMalloc1(ctx->ndisplayvariables,&ctx->displayvariables);
6714:   PetscMalloc1(ctx->ndisplayvariables,&ctx->displayvalues);
6715:   j = 0;
6716:   while (displaynames[j]) {
6717:     k = 0;
6718:     while (ctx->names[k]) {
6719:       PetscBool flg;
6720:       PetscStrcmp(displaynames[j],ctx->names[k],&flg);
6721:       if (flg) {
6722:         ctx->displayvariables[j] = k;
6723:         break;
6724:       }
6725:       k++;
6726:     }
6727:     j++;
6728:   }
6729:   return(0);
6730: }

6732: /*@C
6733:    TSMonitorLGSetDisplayVariables - Sets the variables that are to be display in the monitor

6735:    Collective on TS

6737:    Input Parameters:
6738: +  ts - the TS context
6739: -  displaynames - the names of the components, final string must be NULL

6741:    Notes:
6742:     If the TS object does not have a TSMonitorLGCtx associated with it then this function is ignored

6744:    Level: intermediate

6746: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorLGSetVariableNames()
6747: @*/
6748: PetscErrorCode  TSMonitorLGSetDisplayVariables(TS ts,const char * const *displaynames)
6749: {
6750:   PetscInt          i;
6751:   PetscErrorCode    ierr;

6754:   for (i=0; i<ts->numbermonitors; i++) {
6755:     if (ts->monitor[i] == TSMonitorLGSolution) {
6756:       TSMonitorLGCtxSetDisplayVariables((TSMonitorLGCtx)ts->monitorcontext[i],displaynames);
6757:       break;
6758:     }
6759:   }
6760:   return(0);
6761: }

6763: /*@C
6764:    TSMonitorLGSetTransform - Solution vector will be transformed by provided function before being displayed

6766:    Collective on TS

6768:    Input Parameters:
6769: +  ts - the TS context
6770: .  transform - the transform function
6771: .  destroy - function to destroy the optional context
6772: -  ctx - optional context used by transform function

6774:    Notes:
6775:     If the TS object does not have a TSMonitorLGCtx associated with it then this function is ignored

6777:    Level: intermediate

6779: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorLGSetVariableNames(), TSMonitorLGCtxSetTransform()
6780: @*/
6781: PetscErrorCode  TSMonitorLGSetTransform(TS ts,PetscErrorCode (*transform)(void*,Vec,Vec*),PetscErrorCode (*destroy)(void*),void *tctx)
6782: {
6783:   PetscInt          i;
6784:   PetscErrorCode    ierr;

6787:   for (i=0; i<ts->numbermonitors; i++) {
6788:     if (ts->monitor[i] == TSMonitorLGSolution) {
6789:       TSMonitorLGCtxSetTransform((TSMonitorLGCtx)ts->monitorcontext[i],transform,destroy,tctx);
6790:     }
6791:   }
6792:   return(0);
6793: }

6795: /*@C
6796:    TSMonitorLGCtxSetTransform - Solution vector will be transformed by provided function before being displayed

6798:    Collective on TSLGCtx

6800:    Input Parameters:
6801: +  ts - the TS context
6802: .  transform - the transform function
6803: .  destroy - function to destroy the optional context
6804: -  ctx - optional context used by transform function

6806:    Level: intermediate

6808: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorLGSetVariableNames(), TSMonitorLGSetTransform()
6809: @*/
6810: PetscErrorCode  TSMonitorLGCtxSetTransform(TSMonitorLGCtx ctx,PetscErrorCode (*transform)(void*,Vec,Vec*),PetscErrorCode (*destroy)(void*),void *tctx)
6811: {
6813:   ctx->transform    = transform;
6814:   ctx->transformdestroy = destroy;
6815:   ctx->transformctx = tctx;
6816:   return(0);
6817: }

6819: /*@C
6820:    TSMonitorLGError - Monitors progress of the TS solvers by plotting each component of the error
6821:        in a time based line graph

6823:    Collective on TS

6825:    Input Parameters:
6826: +  ts - the TS context
6827: .  step - current time-step
6828: .  ptime - current time
6829: .  u - current solution
6830: -  dctx - TSMonitorLGCtx object created with TSMonitorLGCtxCreate()

6832:    Level: intermediate

6834:    Notes:
6835:     Each process in a parallel run displays its component errors in a separate window

6837:    The user must provide the solution using TSSetSolutionFunction() to use this monitor.

6839:    Options Database Keys:
6840: .  -ts_monitor_lg_error - create a graphical monitor of error history

6842: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSSetSolutionFunction()
6843: @*/
6844: PetscErrorCode  TSMonitorLGError(TS ts,PetscInt step,PetscReal ptime,Vec u,void *dummy)
6845: {
6846:   PetscErrorCode    ierr;
6847:   TSMonitorLGCtx    ctx = (TSMonitorLGCtx)dummy;
6848:   const PetscScalar *yy;
6849:   Vec               y;

6852:   if (!step) {
6853:     PetscDrawAxis axis;
6854:     PetscInt      dim;
6855:     PetscDrawLGGetAxis(ctx->lg,&axis);
6856:     PetscDrawAxisSetLabels(axis,"Error in solution as function of time","Time","Error");
6857:     VecGetLocalSize(u,&dim);
6858:     PetscDrawLGSetDimension(ctx->lg,dim);
6859:     PetscDrawLGReset(ctx->lg);
6860:   }
6861:   VecDuplicate(u,&y);
6862:   TSComputeSolutionFunction(ts,ptime,y);
6863:   VecAXPY(y,-1.0,u);
6864:   VecGetArrayRead(y,&yy);
6865: #if defined(PETSC_USE_COMPLEX)
6866:   {
6867:     PetscReal *yreal;
6868:     PetscInt  i,n;
6869:     VecGetLocalSize(y,&n);
6870:     PetscMalloc1(n,&yreal);
6871:     for (i=0; i<n; i++) yreal[i] = PetscRealPart(yy[i]);
6872:     PetscDrawLGAddCommonPoint(ctx->lg,ptime,yreal);
6873:     PetscFree(yreal);
6874:   }
6875: #else
6876:   PetscDrawLGAddCommonPoint(ctx->lg,ptime,yy);
6877: #endif
6878:   VecRestoreArrayRead(y,&yy);
6879:   VecDestroy(&y);
6880:   if (((ctx->howoften > 0) && (!(step % ctx->howoften))) || ((ctx->howoften == -1) && ts->reason)) {
6881:     PetscDrawLGDraw(ctx->lg);
6882:     PetscDrawLGSave(ctx->lg);
6883:   }
6884:   return(0);
6885: }

6887: /*@C
6888:    TSMonitorSPSwarmSolution - Graphically displays phase plots of DMSwarm particles on a scatter plot

6890:    Input Parameters:
6891: +  ts - the TS context
6892: .  step - current time-step
6893: .  ptime - current time
6894: .  u - current solution
6895: -  dctx - the TSMonitorSPCtx object that contains all the options for the monitoring, this is created with TSMonitorSPCtxCreate()

6897:    Options Database:
6898: .   -ts_monitor_sp_swarm

6900:    Level: intermediate

6902: @*/
6903: PetscErrorCode TSMonitorSPSwarmSolution(TS ts,PetscInt step,PetscReal ptime,Vec u,void *dctx)
6904: {
6905:   PetscErrorCode    ierr;
6906:   TSMonitorSPCtx    ctx = (TSMonitorSPCtx)dctx;
6907:   const PetscScalar *yy;
6908:   PetscReal       *y,*x;
6909:   PetscInt          Np, p, dim=2;
6910:   DM                dm;


6914:   if (step < 0) return(0); /* -1 indicates interpolated solution */
6915:   if (!step) {
6916:     PetscDrawAxis axis;
6917:     PetscDrawSPGetAxis(ctx->sp,&axis);
6918:     PetscDrawAxisSetLabels(axis,"Particles","X","Y");
6919:     PetscDrawAxisSetLimits(axis, -5, 5, -5, 5);
6920:     PetscDrawAxisSetHoldLimits(axis, PETSC_TRUE);
6921:     TSGetDM(ts, &dm);
6922:     DMGetDimension(dm, &dim);
6923:     if(dim!=2) SETERRQ(PETSC_COMM_SELF, ierr, "Dimensions improper for monitor arguments! Current support: two dimensions.");
6924:     VecGetLocalSize(u, &Np);
6925:     Np /= 2*dim;
6926:     PetscDrawSPSetDimension(ctx->sp, Np);
6927:     PetscDrawSPReset(ctx->sp);
6928:   }

6930:   VecGetLocalSize(u, &Np);
6931:   Np /= 2*dim;
6932:   VecGetArrayRead(u,&yy);
6933:   PetscMalloc2(Np, &x, Np, &y);
6934:   /* get points from solution vector */
6935:   for (p=0; p<Np; ++p){
6936:     x[p] = PetscRealPart(yy[2*dim*p]);
6937:     y[p] = PetscRealPart(yy[2*dim*p+1]);
6938:   }
6939:   VecRestoreArrayRead(u,&yy);

6941:   if (((ctx->howoften > 0) && (!(step % ctx->howoften))) || ((ctx->howoften == -1) && ts->reason)) {
6942:     PetscDrawSPAddPoint(ctx->sp,x,y);
6943:     PetscDrawSPDraw(ctx->sp,PETSC_FALSE);
6944:     PetscDrawSPSave(ctx->sp);
6945:   }

6947:   PetscFree2(x, y);

6949:   return(0);
6950: }



6954: /*@C
6955:    TSMonitorError - Monitors progress of the TS solvers by printing the 2 norm of the error at each timestep

6957:    Collective on TS

6959:    Input Parameters:
6960: +  ts - the TS context
6961: .  step - current time-step
6962: .  ptime - current time
6963: .  u - current solution
6964: -  dctx - unused context

6966:    Level: intermediate

6968:    The user must provide the solution using TSSetSolutionFunction() to use this monitor.

6970:    Options Database Keys:
6971: .  -ts_monitor_error - create a graphical monitor of error history

6973: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSSetSolutionFunction()
6974: @*/
6975: PetscErrorCode  TSMonitorError(TS ts,PetscInt step,PetscReal ptime,Vec u,PetscViewerAndFormat *vf)
6976: {
6977:   PetscErrorCode    ierr;
6978:   Vec               y;
6979:   PetscReal         nrm;
6980:   PetscBool         flg;

6983:   VecDuplicate(u,&y);
6984:   TSComputeSolutionFunction(ts,ptime,y);
6985:   VecAXPY(y,-1.0,u);
6986:   PetscObjectTypeCompare((PetscObject)vf->viewer,PETSCVIEWERASCII,&flg);
6987:   if (flg) {
6988:     VecNorm(y,NORM_2,&nrm);
6989:     PetscViewerASCIIPrintf(vf->viewer,"2-norm of error %g\n",(double)nrm);
6990:   }
6991:   PetscObjectTypeCompare((PetscObject)vf->viewer,PETSCVIEWERDRAW,&flg);
6992:   if (flg) {
6993:     VecView(y,vf->viewer);
6994:   }
6995:   VecDestroy(&y);
6996:   return(0);
6997: }

6999: PetscErrorCode TSMonitorLGSNESIterations(TS ts,PetscInt n,PetscReal ptime,Vec v,void *monctx)
7000: {
7001:   TSMonitorLGCtx ctx = (TSMonitorLGCtx) monctx;
7002:   PetscReal      x   = ptime,y;
7004:   PetscInt       its;

7007:   if (n < 0) return(0); /* -1 indicates interpolated solution */
7008:   if (!n) {
7009:     PetscDrawAxis axis;
7010:     PetscDrawLGGetAxis(ctx->lg,&axis);
7011:     PetscDrawAxisSetLabels(axis,"Nonlinear iterations as function of time","Time","SNES Iterations");
7012:     PetscDrawLGReset(ctx->lg);
7013:     ctx->snes_its = 0;
7014:   }
7015:   TSGetSNESIterations(ts,&its);
7016:   y    = its - ctx->snes_its;
7017:   PetscDrawLGAddPoint(ctx->lg,&x,&y);
7018:   if (((ctx->howoften > 0) && (!(n % ctx->howoften)) && (n > -1)) || ((ctx->howoften == -1) && (n == -1))) {
7019:     PetscDrawLGDraw(ctx->lg);
7020:     PetscDrawLGSave(ctx->lg);
7021:   }
7022:   ctx->snes_its = its;
7023:   return(0);
7024: }

7026: PetscErrorCode TSMonitorLGKSPIterations(TS ts,PetscInt n,PetscReal ptime,Vec v,void *monctx)
7027: {
7028:   TSMonitorLGCtx ctx = (TSMonitorLGCtx) monctx;
7029:   PetscReal      x   = ptime,y;
7031:   PetscInt       its;

7034:   if (n < 0) return(0); /* -1 indicates interpolated solution */
7035:   if (!n) {
7036:     PetscDrawAxis axis;
7037:     PetscDrawLGGetAxis(ctx->lg,&axis);
7038:     PetscDrawAxisSetLabels(axis,"Linear iterations as function of time","Time","KSP Iterations");
7039:     PetscDrawLGReset(ctx->lg);
7040:     ctx->ksp_its = 0;
7041:   }
7042:   TSGetKSPIterations(ts,&its);
7043:   y    = its - ctx->ksp_its;
7044:   PetscDrawLGAddPoint(ctx->lg,&x,&y);
7045:   if (((ctx->howoften > 0) && (!(n % ctx->howoften)) && (n > -1)) || ((ctx->howoften == -1) && (n == -1))) {
7046:     PetscDrawLGDraw(ctx->lg);
7047:     PetscDrawLGSave(ctx->lg);
7048:   }
7049:   ctx->ksp_its = its;
7050:   return(0);
7051: }

7053: /*@
7054:    TSComputeLinearStability - computes the linear stability function at a point

7056:    Collective on TS

7058:    Input Parameters:
7059: +  ts - the TS context
7060: -  xr,xi - real and imaginary part of input arguments

7062:    Output Parameters:
7063: .  yr,yi - real and imaginary part of function value

7065:    Level: developer

7067: .seealso: TSSetRHSFunction(), TSComputeIFunction()
7068: @*/
7069: PetscErrorCode TSComputeLinearStability(TS ts,PetscReal xr,PetscReal xi,PetscReal *yr,PetscReal *yi)
7070: {

7075:   if (!ts->ops->linearstability) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"Linearized stability function not provided for this method");
7076:   (*ts->ops->linearstability)(ts,xr,xi,yr,yi);
7077:   return(0);
7078: }

7080: /* ------------------------------------------------------------------------*/
7081: /*@C
7082:    TSMonitorEnvelopeCtxCreate - Creates a context for use with TSMonitorEnvelope()

7084:    Collective on TS

7086:    Input Parameters:
7087: .  ts  - the ODE solver object

7089:    Output Parameter:
7090: .  ctx - the context

7092:    Level: intermediate

7094: .seealso: TSMonitorLGTimeStep(), TSMonitorSet(), TSMonitorLGSolution(), TSMonitorLGError()

7096: @*/
7097: PetscErrorCode  TSMonitorEnvelopeCtxCreate(TS ts,TSMonitorEnvelopeCtx *ctx)
7098: {

7102:   PetscNew(ctx);
7103:   return(0);
7104: }

7106: /*@C
7107:    TSMonitorEnvelope - Monitors the maximum and minimum value of each component of the solution

7109:    Collective on TS

7111:    Input Parameters:
7112: +  ts - the TS context
7113: .  step - current time-step
7114: .  ptime - current time
7115: .  u  - current solution
7116: -  dctx - the envelope context

7118:    Options Database:
7119: .  -ts_monitor_envelope

7121:    Level: intermediate

7123:    Notes:
7124:     after a solve you can use TSMonitorEnvelopeGetBounds() to access the envelope

7126: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorEnvelopeGetBounds(), TSMonitorEnvelopeCtxCreate()
7127: @*/
7128: PetscErrorCode  TSMonitorEnvelope(TS ts,PetscInt step,PetscReal ptime,Vec u,void *dctx)
7129: {
7130:   PetscErrorCode       ierr;
7131:   TSMonitorEnvelopeCtx ctx = (TSMonitorEnvelopeCtx)dctx;

7134:   if (!ctx->max) {
7135:     VecDuplicate(u,&ctx->max);
7136:     VecDuplicate(u,&ctx->min);
7137:     VecCopy(u,ctx->max);
7138:     VecCopy(u,ctx->min);
7139:   } else {
7140:     VecPointwiseMax(ctx->max,u,ctx->max);
7141:     VecPointwiseMin(ctx->min,u,ctx->min);
7142:   }
7143:   return(0);
7144: }

7146: /*@C
7147:    TSMonitorEnvelopeGetBounds - Gets the bounds for the components of the solution

7149:    Collective on TS

7151:    Input Parameter:
7152: .  ts - the TS context

7154:    Output Parameter:
7155: +  max - the maximum values
7156: -  min - the minimum values

7158:    Notes:
7159:     If the TS does not have a TSMonitorEnvelopeCtx associated with it then this function is ignored

7161:    Level: intermediate

7163: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorLGSetDisplayVariables()
7164: @*/
7165: PetscErrorCode  TSMonitorEnvelopeGetBounds(TS ts,Vec *max,Vec *min)
7166: {
7167:   PetscInt i;

7170:   if (max) *max = NULL;
7171:   if (min) *min = NULL;
7172:   for (i=0; i<ts->numbermonitors; i++) {
7173:     if (ts->monitor[i] == TSMonitorEnvelope) {
7174:       TSMonitorEnvelopeCtx  ctx = (TSMonitorEnvelopeCtx) ts->monitorcontext[i];
7175:       if (max) *max = ctx->max;
7176:       if (min) *min = ctx->min;
7177:       break;
7178:     }
7179:   }
7180:   return(0);
7181: }

7183: /*@C
7184:    TSMonitorEnvelopeCtxDestroy - Destroys a context that was created  with TSMonitorEnvelopeCtxCreate().

7186:    Collective on TSMonitorEnvelopeCtx

7188:    Input Parameter:
7189: .  ctx - the monitor context

7191:    Level: intermediate

7193: .seealso: TSMonitorLGCtxCreate(),  TSMonitorSet(), TSMonitorLGTimeStep()
7194: @*/
7195: PetscErrorCode  TSMonitorEnvelopeCtxDestroy(TSMonitorEnvelopeCtx *ctx)
7196: {

7200:   VecDestroy(&(*ctx)->min);
7201:   VecDestroy(&(*ctx)->max);
7202:   PetscFree(*ctx);
7203:   return(0);
7204: }

7206: /*@
7207:    TSRestartStep - Flags the solver to restart the next step

7209:    Collective on TS

7211:    Input Parameter:
7212: .  ts - the TS context obtained from TSCreate()

7214:    Level: advanced

7216:    Notes:
7217:    Multistep methods like BDF or Runge-Kutta methods with FSAL property require restarting the solver in the event of
7218:    discontinuities. These discontinuities may be introduced as a consequence of explicitly modifications to the solution
7219:    vector (which PETSc attempts to detect and handle) or problem coefficients (which PETSc is not able to detect). For
7220:    the sake of correctness and maximum safety, users are expected to call TSRestart() whenever they introduce
7221:    discontinuities in callback routines (e.g. prestep and poststep routines, or implicit/rhs function routines with
7222:    discontinuous source terms).

7224: .seealso: TSSolve(), TSSetPreStep(), TSSetPostStep()
7225: @*/
7226: PetscErrorCode TSRestartStep(TS ts)
7227: {
7230:   ts->steprestart = PETSC_TRUE;
7231:   return(0);
7232: }

7234: /*@
7235:    TSRollBack - Rolls back one time step

7237:    Collective on TS

7239:    Input Parameter:
7240: .  ts - the TS context obtained from TSCreate()

7242:    Level: advanced

7244: .seealso: TSCreate(), TSSetUp(), TSDestroy(), TSSolve(), TSSetPreStep(), TSSetPreStage(), TSInterpolate()
7245: @*/
7246: PetscErrorCode  TSRollBack(TS ts)
7247: {

7252:   if (ts->steprollback) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_ARG_WRONGSTATE,"TSRollBack already called");
7253:   if (!ts->ops->rollback) SETERRQ1(PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"TSRollBack not implemented for type '%s'",((PetscObject)ts)->type_name);
7254:   (*ts->ops->rollback)(ts);
7255:   ts->time_step = ts->ptime - ts->ptime_prev;
7256:   ts->ptime = ts->ptime_prev;
7257:   ts->ptime_prev = ts->ptime_prev_rollback;
7258:   ts->steps--;
7259:   ts->steprollback = PETSC_TRUE;
7260:   return(0);
7261: }

7263: /*@
7264:    TSGetStages - Get the number of stages and stage values

7266:    Input Parameter:
7267: .  ts - the TS context obtained from TSCreate()

7269:    Output Parameters:
7270: +  ns - the number of stages
7271: -  Y - the current stage vectors

7273:    Level: advanced

7275:    Notes: Both ns and Y can be NULL.

7277: .seealso: TSCreate()
7278: @*/
7279: PetscErrorCode  TSGetStages(TS ts,PetscInt *ns,Vec **Y)
7280: {

7287:   if (!ts->ops->getstages) {
7288:     if (ns) *ns = 0;
7289:     if (Y) *Y = NULL;
7290:   } else {
7291:     (*ts->ops->getstages)(ts,ns,Y);
7292:   }
7293:   return(0);
7294: }

7296: /*@C
7297:   TSComputeIJacobianDefaultColor - Computes the Jacobian using finite differences and coloring to exploit matrix sparsity.

7299:   Collective on SNES

7301:   Input Parameters:
7302: + ts - the TS context
7303: . t - current timestep
7304: . U - state vector
7305: . Udot - time derivative of state vector
7306: . shift - shift to apply, see note below
7307: - ctx - an optional user context

7309:   Output Parameters:
7310: + J - Jacobian matrix (not altered in this routine)
7311: - B - newly computed Jacobian matrix to use with preconditioner (generally the same as J)

7313:   Level: intermediate

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

7318:   dF/dU + shift*dF/dUdot

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

7323:   This will first try to get the coloring from the DM.  If the DM type has no coloring
7324:   routine, then it will try to get the coloring from the matrix.  This requires that the
7325:   matrix have nonzero entries precomputed.

7327: .seealso: TSSetIJacobian(), MatFDColoringCreate(), MatFDColoringSetFunction()
7328: @*/
7329: PetscErrorCode TSComputeIJacobianDefaultColor(TS ts,PetscReal t,Vec U,Vec Udot,PetscReal shift,Mat J,Mat B,void *ctx)
7330: {
7331:   SNES           snes;
7332:   MatFDColoring  color;
7333:   PetscBool      hascolor, matcolor = PETSC_FALSE;

7337:   PetscOptionsGetBool(((PetscObject)ts)->options,((PetscObject) ts)->prefix, "-ts_fd_color_use_mat", &matcolor, NULL);
7338:   PetscObjectQuery((PetscObject) B, "TSMatFDColoring", (PetscObject *) &color);
7339:   if (!color) {
7340:     DM         dm;
7341:     ISColoring iscoloring;

7343:     TSGetDM(ts, &dm);
7344:     DMHasColoring(dm, &hascolor);
7345:     if (hascolor && !matcolor) {
7346:       DMCreateColoring(dm, IS_COLORING_GLOBAL, &iscoloring);
7347:       MatFDColoringCreate(B, iscoloring, &color);
7348:       MatFDColoringSetFunction(color, (PetscErrorCode (*)(void)) SNESTSFormFunction, (void *) ts);
7349:       MatFDColoringSetFromOptions(color);
7350:       MatFDColoringSetUp(B, iscoloring, color);
7351:       ISColoringDestroy(&iscoloring);
7352:     } else {
7353:       MatColoring mc;

7355:       MatColoringCreate(B, &mc);
7356:       MatColoringSetDistance(mc, 2);
7357:       MatColoringSetType(mc, MATCOLORINGSL);
7358:       MatColoringSetFromOptions(mc);
7359:       MatColoringApply(mc, &iscoloring);
7360:       MatColoringDestroy(&mc);
7361:       MatFDColoringCreate(B, iscoloring, &color);
7362:       MatFDColoringSetFunction(color, (PetscErrorCode (*)(void)) SNESTSFormFunction, (void *) ts);
7363:       MatFDColoringSetFromOptions(color);
7364:       MatFDColoringSetUp(B, iscoloring, color);
7365:       ISColoringDestroy(&iscoloring);
7366:     }
7367:     PetscObjectCompose((PetscObject) B, "TSMatFDColoring", (PetscObject) color);
7368:     PetscObjectDereference((PetscObject) color);
7369:   }
7370:   TSGetSNES(ts, &snes);
7371:   MatFDColoringApply(B, color, U, snes);
7372:   if (J != B) {
7373:     MatAssemblyBegin(J, MAT_FINAL_ASSEMBLY);
7374:     MatAssemblyEnd(J, MAT_FINAL_ASSEMBLY);
7375:   }
7376:   return(0);
7377: }

7379: /*@
7380:     TSSetFunctionDomainError - Set a function that tests if the current state vector is valid

7382:     Input Parameters:
7383: +    ts - the TS context
7384: -    func - function called within TSFunctionDomainError

7386:     Calling sequence of func:
7387: $     PetscErrorCode func(TS ts,PetscReal time,Vec state,PetscBool reject)

7389: +   ts - the TS context
7390: .   time - the current time (of the stage)
7391: .   state - the state to check if it is valid
7392: -   reject - (output parameter) PETSC_FALSE if the state is acceptable, PETSC_TRUE if not acceptable

7394:     Level: intermediate

7396:     Notes:
7397:       If an implicit ODE solver is being used then, in addition to providing this routine, the
7398:       user's code should call SNESSetFunctionDomainError() when domain errors occur during
7399:       function evaluations where the functions are provided by TSSetIFunction() or TSSetRHSFunction().
7400:       Use TSGetSNES() to obtain the SNES object

7402:     Developer Notes:
7403:       The naming of this function is inconsistent with the SNESSetFunctionDomainError()
7404:       since one takes a function pointer and the other does not.

7406: .seealso: TSAdaptCheckStage(), TSFunctionDomainError(), SNESSetFunctionDomainError(), TSGetSNES()
7407: @*/

7409: PetscErrorCode TSSetFunctionDomainError(TS ts, PetscErrorCode (*func)(TS,PetscReal,Vec,PetscBool*))
7410: {
7413:   ts->functiondomainerror = func;
7414:   return(0);
7415: }

7417: /*@
7418:     TSFunctionDomainError - Checks if the current state is valid

7420:     Input Parameters:
7421: +    ts - the TS context
7422: .    stagetime - time of the simulation
7423: -    Y - state vector to check.

7425:     Output Parameter:
7426: .    accept - Set to PETSC_FALSE if the current state vector is valid.

7428:     Note:
7429:     This function is called by the TS integration routines and calls the user provided function (set with TSSetFunctionDomainError())
7430:     to check if the current state is valid.

7432:     Level: developer

7434: .seealso: TSSetFunctionDomainError()
7435: @*/
7436: PetscErrorCode TSFunctionDomainError(TS ts,PetscReal stagetime,Vec Y,PetscBool* accept)
7437: {
7440:   *accept = PETSC_TRUE;
7441:   if (ts->functiondomainerror) {
7442:     PetscStackCallStandard((*ts->functiondomainerror),(ts,stagetime,Y,accept));
7443:   }
7444:   return(0);
7445: }

7447: /*@C
7448:   TSClone - This function clones a time step object.

7450:   Collective

7452:   Input Parameter:
7453: . tsin    - The input TS

7455:   Output Parameter:
7456: . tsout   - The output TS (cloned)

7458:   Notes:
7459:   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.

7461:   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);

7463:   Level: developer

7465: .seealso: TSCreate(), TSSetType(), TSSetUp(), TSDestroy(), TSSetProblemType()
7466: @*/
7467: PetscErrorCode  TSClone(TS tsin, TS *tsout)
7468: {
7469:   TS             t;
7471:   SNES           snes_start;
7472:   DM             dm;
7473:   TSType         type;

7477:   *tsout = NULL;

7479:   PetscHeaderCreate(t, TS_CLASSID, "TS", "Time stepping", "TS", PetscObjectComm((PetscObject)tsin), TSDestroy, TSView);

7481:   /* General TS description */
7482:   t->numbermonitors    = 0;
7483:   t->setupcalled       = 0;
7484:   t->ksp_its           = 0;
7485:   t->snes_its          = 0;
7486:   t->nwork             = 0;
7487:   t->rhsjacobian.time  = PETSC_MIN_REAL;
7488:   t->rhsjacobian.scale = 1.;
7489:   t->ijacobian.shift   = 1.;

7491:   TSGetSNES(tsin,&snes_start);
7492:   TSSetSNES(t,snes_start);

7494:   TSGetDM(tsin,&dm);
7495:   TSSetDM(t,dm);

7497:   t->adapt = tsin->adapt;
7498:   PetscObjectReference((PetscObject)t->adapt);

7500:   t->trajectory = tsin->trajectory;
7501:   PetscObjectReference((PetscObject)t->trajectory);

7503:   t->event = tsin->event;
7504:   if (t->event) t->event->refct++;

7506:   t->problem_type      = tsin->problem_type;
7507:   t->ptime             = tsin->ptime;
7508:   t->ptime_prev        = tsin->ptime_prev;
7509:   t->time_step         = tsin->time_step;
7510:   t->max_time          = tsin->max_time;
7511:   t->steps             = tsin->steps;
7512:   t->max_steps         = tsin->max_steps;
7513:   t->equation_type     = tsin->equation_type;
7514:   t->atol              = tsin->atol;
7515:   t->rtol              = tsin->rtol;
7516:   t->max_snes_failures = tsin->max_snes_failures;
7517:   t->max_reject        = tsin->max_reject;
7518:   t->errorifstepfailed = tsin->errorifstepfailed;

7520:   TSGetType(tsin,&type);
7521:   TSSetType(t,type);

7523:   t->vec_sol           = NULL;

7525:   t->cfltime          = tsin->cfltime;
7526:   t->cfltime_local    = tsin->cfltime_local;
7527:   t->exact_final_time = tsin->exact_final_time;

7529:   PetscMemcpy(t->ops,tsin->ops,sizeof(struct _TSOps));

7531:   if (((PetscObject)tsin)->fortran_func_pointers) {
7532:     PetscInt i;
7533:     PetscMalloc((10)*sizeof(void(*)(void)),&((PetscObject)t)->fortran_func_pointers);
7534:     for (i=0; i<10; i++) {
7535:       ((PetscObject)t)->fortran_func_pointers[i] = ((PetscObject)tsin)->fortran_func_pointers[i];
7536:     }
7537:   }
7538:   *tsout = t;
7539:   return(0);
7540: }

7542: static PetscErrorCode RHSWrapperFunction_TSRHSJacobianTest(void* ctx,Vec x,Vec y)
7543: {
7545:   TS             ts = (TS) ctx;

7548:   TSComputeRHSFunction(ts,0,x,y);
7549:   return(0);
7550: }

7552: /*@
7553:     TSRHSJacobianTest - Compares the multiply routine provided to the MATSHELL with differencing on the TS given RHS function.

7555:    Logically Collective on TS

7557:     Input Parameters:
7558:     TS - the time stepping routine

7560:    Output Parameter:
7561: .   flg - PETSC_TRUE if the multiply is likely correct

7563:    Options Database:
7564:  .   -ts_rhs_jacobian_test_mult -mat_shell_test_mult_view - run the test at each timestep of the integrator

7566:    Level: advanced

7568:    Notes:
7569:     This only works for problems defined only the RHS function and Jacobian NOT IFunction and IJacobian

7571: .seealso: MatCreateShell(), MatShellGetContext(), MatShellGetOperation(), MatShellTestMultTranspose(), TSRHSJacobianTestTranspose()
7572: @*/
7573: PetscErrorCode  TSRHSJacobianTest(TS ts,PetscBool *flg)
7574: {
7575:   Mat            J,B;
7577:   TSRHSJacobian  func;
7578:   void*          ctx;

7581:   TSGetRHSJacobian(ts,&J,&B,&func,&ctx);
7582:   (*func)(ts,0.0,ts->vec_sol,J,B,ctx);
7583:   MatShellTestMult(J,RHSWrapperFunction_TSRHSJacobianTest,ts->vec_sol,ts,flg);
7584:   return(0);
7585: }

7587: /*@C
7588:     TSRHSJacobianTestTranspose - Compares the multiply transpose routine provided to the MATSHELL with differencing on the TS given RHS function.

7590:    Logically Collective on TS

7592:     Input Parameters:
7593:     TS - the time stepping routine

7595:    Output Parameter:
7596: .   flg - PETSC_TRUE if the multiply is likely correct

7598:    Options Database:
7599: .   -ts_rhs_jacobian_test_mult_transpose -mat_shell_test_mult_transpose_view - run the test at each timestep of the integrator

7601:    Notes:
7602:     This only works for problems defined only the RHS function and Jacobian NOT IFunction and IJacobian

7604:    Level: advanced

7606: .seealso: MatCreateShell(), MatShellGetContext(), MatShellGetOperation(), MatShellTestMultTranspose(), TSRHSJacobianTest()
7607: @*/
7608: PetscErrorCode  TSRHSJacobianTestTranspose(TS ts,PetscBool *flg)
7609: {
7610:   Mat            J,B;
7612:   void           *ctx;
7613:   TSRHSJacobian  func;

7616:   TSGetRHSJacobian(ts,&J,&B,&func,&ctx);
7617:   (*func)(ts,0.0,ts->vec_sol,J,B,ctx);
7618:   MatShellTestMultTranspose(J,RHSWrapperFunction_TSRHSJacobianTest,ts->vec_sol,ts,flg);
7619:   return(0);
7620: }

7622: /*@
7623:   TSSetUseSplitRHSFunction - Use the split RHSFunction when a multirate method is used.

7625:   Logically collective

7627:   Input Parameter:
7628: +  ts - timestepping context
7629: -  use_splitrhsfunction - PETSC_TRUE indicates that the split RHSFunction will be used

7631:   Options Database:
7632: .   -ts_use_splitrhsfunction - <true,false>

7634:   Notes:
7635:     This is only useful for multirate methods

7637:   Level: intermediate

7639: .seealso: TSGetUseSplitRHSFunction()
7640: @*/
7641: PetscErrorCode TSSetUseSplitRHSFunction(TS ts, PetscBool use_splitrhsfunction)
7642: {
7645:   ts->use_splitrhsfunction = use_splitrhsfunction;
7646:   return(0);
7647: }

7649: /*@
7650:   TSGetUseSplitRHSFunction - Gets whether to use the split RHSFunction when a multirate method is used.

7652:   Not collective

7654:   Input Parameter:
7655: .  ts - timestepping context

7657:   Output Parameter:
7658: .  use_splitrhsfunction - PETSC_TRUE indicates that the split RHSFunction will be used

7660:   Level: intermediate

7662: .seealso: TSSetUseSplitRHSFunction()
7663: @*/
7664: PetscErrorCode TSGetUseSplitRHSFunction(TS ts, PetscBool *use_splitrhsfunction)
7665: {
7668:   *use_splitrhsfunction = ts->use_splitrhsfunction;
7669:   return(0);
7670: }