Actual source code: ts.c

  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};

 16: static PetscErrorCode TSAdaptSetDefaultType(TSAdapt adapt,TSAdaptType default_type)
 17: {

 23:   if (!((PetscObject)adapt)->type_name) {
 24:     TSAdaptSetType(adapt,default_type);
 25:   }
 26:   return(0);
 27: }

 29: /*@
 30:    TSSetFromOptions - Sets various TS parameters from user options.

 32:    Collective on TS

 34:    Input Parameter:
 35: .  ts - the TS context obtained from TSCreate()

 37:    Options Database Keys:
 38: +  -ts_type <type> - TSEULER, TSBEULER, TSSUNDIALS, TSPSEUDO, TSCN, TSRK, TSTHETA, TSALPHA, TSGLLE, TSSSP, TSGLEE, TSBSYMP, TSIRK
 39: .  -ts_save_trajectory - checkpoint the solution at each time-step
 40: .  -ts_max_time <time> - maximum time to compute to
 41: .  -ts_max_steps <steps> - maximum number of time-steps to take
 42: .  -ts_init_time <time> - initial time to start computation
 43: .  -ts_final_time <time> - final time to compute to (deprecated: use -ts_max_time)
 44: .  -ts_dt <dt> - initial time step
 45: .  -ts_exact_final_time <stepover,interpolate,matchstep> - whether to stop at the exact given final time and how to compute the solution at that time
 46: .  -ts_max_snes_failures <maxfailures> - Maximum number of nonlinear solve failures allowed
 47: .  -ts_max_reject <maxrejects> - Maximum number of step rejections before step fails
 48: .  -ts_error_if_step_fails <true,false> - Error if no step succeeds
 49: .  -ts_rtol <rtol> - relative tolerance for local truncation error
 50: .  -ts_atol <atol> Absolute tolerance for local truncation error
 51: .  -ts_rhs_jacobian_test_mult -mat_shell_test_mult_view - test the Jacobian at each iteration against finite difference with RHS function
 52: .  -ts_rhs_jacobian_test_mult_transpose -mat_shell_test_mult_transpose_view - test the Jacobian at each iteration against finite difference with RHS function
 53: .  -ts_adjoint_solve <yes,no> After solving the ODE/DAE solve the adjoint problem (requires -ts_save_trajectory)
 54: .  -ts_fd_color - Use finite differences with coloring to compute IJacobian
 55: .  -ts_monitor - print information at each timestep
 56: .  -ts_monitor_cancel - Cancel all monitors
 57: .  -ts_monitor_lg_solution - Monitor solution graphically
 58: .  -ts_monitor_lg_error - Monitor error graphically
 59: .  -ts_monitor_error - Monitors norm of error
 60: .  -ts_monitor_lg_timestep - Monitor timestep size graphically
 61: .  -ts_monitor_lg_timestep_log - Monitor log timestep size graphically
 62: .  -ts_monitor_lg_snes_iterations - Monitor number nonlinear iterations for each timestep graphically
 63: .  -ts_monitor_lg_ksp_iterations - Monitor number nonlinear iterations for each timestep graphically
 64: .  -ts_monitor_sp_eig - Monitor eigenvalues of linearized operator graphically
 65: .  -ts_monitor_draw_solution - Monitor solution graphically
 66: .  -ts_monitor_draw_solution_phase  <xleft,yleft,xright,yright> - Monitor solution graphically with phase diagram, requires problem with exactly 2 degrees of freedom
 67: .  -ts_monitor_draw_error - Monitor error graphically, requires use to have provided TSSetSolutionFunction()
 68: .  -ts_monitor_solution [ascii binary draw][:filename][:viewerformat] - monitors the solution at each timestep
 69: .  -ts_monitor_solution_vtk <filename.vts,filename.vtu> - Save each time step to a binary file, use filename-%%03D.vts (filename-%%03D.vtu)
 70: -  -ts_monitor_envelope - determine maximum and minimum value of each component of the solution over the solution time

 72:    Notes:
 73:      See SNESSetFromOptions() and KSPSetFromOptions() for how to control the nonlinear and linear solves used by the time-stepper.

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

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

 82:    Level: beginner

 84: .seealso: TSGetType()
 85: @*/
 86: PetscErrorCode  TSSetFromOptions(TS ts)
 87: {
 88:   PetscBool              opt,flg,tflg;
 89:   PetscErrorCode         ierr;
 90:   char                   monfilename[PETSC_MAX_PATH_LEN];
 91:   PetscReal              time_step;
 92:   TSExactFinalTimeOption eftopt;
 93:   char                   dir[16];
 94:   TSIFunction            ifun;
 95:   const char             *defaultType;
 96:   char                   typeName[256];


101:   TSRegisterAll();
102:   TSGetIFunction(ts,NULL,&ifun,NULL);

104:   PetscObjectOptionsBegin((PetscObject)ts);
105:   if (((PetscObject)ts)->type_name) defaultType = ((PetscObject)ts)->type_name;
106:   else defaultType = ifun ? TSBEULER : TSEULER;
107:   PetscOptionsFList("-ts_type","TS method","TSSetType",TSList,defaultType,typeName,256,&opt);
108:   if (opt) {
109:     TSSetType(ts,typeName);
110:   } else {
111:     TSSetType(ts,defaultType);
112:   }

114:   /* Handle generic TS options */
115:   PetscOptionsDeprecated("-ts_final_time","-ts_max_time","3.10",NULL);
116:   PetscOptionsReal("-ts_max_time","Maximum time to run to","TSSetMaxTime",ts->max_time,&ts->max_time,NULL);
117:   PetscOptionsInt("-ts_max_steps","Maximum number of time steps","TSSetMaxSteps",ts->max_steps,&ts->max_steps,NULL);
118:   PetscOptionsReal("-ts_init_time","Initial time","TSSetTime",ts->ptime,&ts->ptime,NULL);
119:   PetscOptionsReal("-ts_dt","Initial time step","TSSetTimeStep",ts->time_step,&time_step,&flg);
120:   if (flg) {TSSetTimeStep(ts,time_step);}
121:   PetscOptionsEnum("-ts_exact_final_time","Option for handling of final time step","TSSetExactFinalTime",TSExactFinalTimeOptions,(PetscEnum)ts->exact_final_time,(PetscEnum*)&eftopt,&flg);
122:   if (flg) {TSSetExactFinalTime(ts,eftopt);}
123:   PetscOptionsInt("-ts_max_snes_failures","Maximum number of nonlinear solve failures","TSSetMaxSNESFailures",ts->max_snes_failures,&ts->max_snes_failures,NULL);
124:   PetscOptionsInt("-ts_max_reject","Maximum number of step rejections before step fails","TSSetMaxStepRejections",ts->max_reject,&ts->max_reject,NULL);
125:   PetscOptionsBool("-ts_error_if_step_fails","Error if no step succeeds","TSSetErrorIfStepFails",ts->errorifstepfailed,&ts->errorifstepfailed,NULL);
126:   PetscOptionsReal("-ts_rtol","Relative tolerance for local truncation error","TSSetTolerances",ts->rtol,&ts->rtol,NULL);
127:   PetscOptionsReal("-ts_atol","Absolute tolerance for local truncation error","TSSetTolerances",ts->atol,&ts->atol,NULL);

129:   PetscOptionsBool("-ts_rhs_jacobian_test_mult","Test the RHS Jacobian for consistency with RHS at each solve ","None",ts->testjacobian,&ts->testjacobian,NULL);
130:   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);
131:   PetscOptionsBool("-ts_use_splitrhsfunction","Use the split RHS function for multirate solvers ","TSSetUseSplitRHSFunction",ts->use_splitrhsfunction,&ts->use_splitrhsfunction,NULL);
132: #if defined(PETSC_HAVE_SAWS)
133:   {
134:     PetscBool set;
135:     flg  = PETSC_FALSE;
136:     PetscOptionsBool("-ts_saws_block","Block for SAWs memory snooper at end of TSSolve","PetscObjectSAWsBlock",((PetscObject)ts)->amspublishblock,&flg,&set);
137:     if (set) {
138:       PetscObjectSAWsSetBlock((PetscObject)ts,flg);
139:     }
140:   }
141: #endif

143:   /* Monitor options */
144:   PetscOptionsInt("-ts_monitor_frequency", "Number of time steps between monitor output", "TSMonitorSetFrequency", ts->monitorFrequency, &ts->monitorFrequency, NULL);
145:   TSMonitorSetFromOptions(ts,"-ts_monitor","Monitor time and timestep size","TSMonitorDefault",TSMonitorDefault,NULL);
146:   TSMonitorSetFromOptions(ts,"-ts_monitor_extreme","Monitor extreme values of the solution","TSMonitorExtreme",TSMonitorExtreme,NULL);
147:   TSMonitorSetFromOptions(ts,"-ts_monitor_solution","View the solution at each timestep","TSMonitorSolution",TSMonitorSolution,NULL);
148:   TSMonitorSetFromOptions(ts,"-ts_dmswarm_monitor_moments","Monitor moments of particle distribution","TSDMSwarmMonitorMoments",TSDMSwarmMonitorMoments,NULL);

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

153:   PetscOptionsName("-ts_monitor_lg_solution","Monitor solution graphically","TSMonitorLGSolution",&opt);
154:   if (opt) {
155:     PetscInt       howoften = 1;
156:     DM             dm;
157:     PetscBool      net;

159:     PetscOptionsInt("-ts_monitor_lg_solution","Monitor solution graphically","TSMonitorLGSolution",howoften,&howoften,NULL);
160:     TSGetDM(ts,&dm);
161:     PetscObjectTypeCompare((PetscObject)dm,DMNETWORK,&net);
162:     if (net) {
163:       TSMonitorLGCtxNetwork ctx;
164:       TSMonitorLGCtxNetworkCreate(ts,NULL,NULL,PETSC_DECIDE,PETSC_DECIDE,600,400,howoften,&ctx);
165:       TSMonitorSet(ts,TSMonitorLGCtxNetworkSolution,ctx,(PetscErrorCode (*)(void**))TSMonitorLGCtxNetworkDestroy);
166:       PetscOptionsBool("-ts_monitor_lg_solution_semilogy","Plot the solution with a semi-log axis","",ctx->semilogy,&ctx->semilogy,NULL);
167:     } else {
168:       TSMonitorLGCtx ctx;
169:       TSMonitorLGCtxCreate(PETSC_COMM_SELF,NULL,NULL,PETSC_DECIDE,PETSC_DECIDE,400,300,howoften,&ctx);
170:       TSMonitorSet(ts,TSMonitorLGSolution,ctx,(PetscErrorCode (*)(void**))TSMonitorLGCtxDestroy);
171:     }
172:   }

174:   PetscOptionsName("-ts_monitor_lg_error","Monitor error graphically","TSMonitorLGError",&opt);
175:   if (opt) {
176:     TSMonitorLGCtx ctx;
177:     PetscInt       howoften = 1;

179:     PetscOptionsInt("-ts_monitor_lg_error","Monitor error graphically","TSMonitorLGError",howoften,&howoften,NULL);
180:     TSMonitorLGCtxCreate(PETSC_COMM_SELF,NULL,NULL,PETSC_DECIDE,PETSC_DECIDE,400,300,howoften,&ctx);
181:     TSMonitorSet(ts,TSMonitorLGError,ctx,(PetscErrorCode (*)(void**))TSMonitorLGCtxDestroy);
182:   }
183:   TSMonitorSetFromOptions(ts,"-ts_monitor_error","View the error at each timestep","TSMonitorError",TSMonitorError,NULL);

185:   PetscOptionsName("-ts_monitor_lg_timestep","Monitor timestep size graphically","TSMonitorLGTimeStep",&opt);
186:   if (opt) {
187:     TSMonitorLGCtx ctx;
188:     PetscInt       howoften = 1;

190:     PetscOptionsInt("-ts_monitor_lg_timestep","Monitor timestep size graphically","TSMonitorLGTimeStep",howoften,&howoften,NULL);
191:     TSMonitorLGCtxCreate(PetscObjectComm((PetscObject)ts),NULL,NULL,PETSC_DECIDE,PETSC_DECIDE,400,300,howoften,&ctx);
192:     TSMonitorSet(ts,TSMonitorLGTimeStep,ctx,(PetscErrorCode (*)(void**))TSMonitorLGCtxDestroy);
193:   }
194:   PetscOptionsName("-ts_monitor_lg_timestep_log","Monitor log timestep size graphically","TSMonitorLGTimeStep",&opt);
195:   if (opt) {
196:     TSMonitorLGCtx ctx;
197:     PetscInt       howoften = 1;

199:     PetscOptionsInt("-ts_monitor_lg_timestep_log","Monitor log timestep size graphically","TSMonitorLGTimeStep",howoften,&howoften,NULL);
200:     TSMonitorLGCtxCreate(PetscObjectComm((PetscObject)ts),NULL,NULL,PETSC_DECIDE,PETSC_DECIDE,400,300,howoften,&ctx);
201:     TSMonitorSet(ts,TSMonitorLGTimeStep,ctx,(PetscErrorCode (*)(void**))TSMonitorLGCtxDestroy);
202:     ctx->semilogy = PETSC_TRUE;
203:   }

205:   PetscOptionsName("-ts_monitor_lg_snes_iterations","Monitor number nonlinear iterations for each timestep graphically","TSMonitorLGSNESIterations",&opt);
206:   if (opt) {
207:     TSMonitorLGCtx ctx;
208:     PetscInt       howoften = 1;

210:     PetscOptionsInt("-ts_monitor_lg_snes_iterations","Monitor number nonlinear iterations for each timestep graphically","TSMonitorLGSNESIterations",howoften,&howoften,NULL);
211:     TSMonitorLGCtxCreate(PetscObjectComm((PetscObject)ts),NULL,NULL,PETSC_DECIDE,PETSC_DECIDE,400,300,howoften,&ctx);
212:     TSMonitorSet(ts,TSMonitorLGSNESIterations,ctx,(PetscErrorCode (*)(void**))TSMonitorLGCtxDestroy);
213:   }
214:   PetscOptionsName("-ts_monitor_lg_ksp_iterations","Monitor number nonlinear iterations for each timestep graphically","TSMonitorLGKSPIterations",&opt);
215:   if (opt) {
216:     TSMonitorLGCtx ctx;
217:     PetscInt       howoften = 1;

219:     PetscOptionsInt("-ts_monitor_lg_ksp_iterations","Monitor number nonlinear iterations for each timestep graphically","TSMonitorLGKSPIterations",howoften,&howoften,NULL);
220:     TSMonitorLGCtxCreate(PetscObjectComm((PetscObject)ts),NULL,NULL,PETSC_DECIDE,PETSC_DECIDE,400,300,howoften,&ctx);
221:     TSMonitorSet(ts,TSMonitorLGKSPIterations,ctx,(PetscErrorCode (*)(void**))TSMonitorLGCtxDestroy);
222:   }
223:   PetscOptionsName("-ts_monitor_sp_eig","Monitor eigenvalues of linearized operator graphically","TSMonitorSPEig",&opt);
224:   if (opt) {
225:     TSMonitorSPEigCtx ctx;
226:     PetscInt          howoften = 1;

228:     PetscOptionsInt("-ts_monitor_sp_eig","Monitor eigenvalues of linearized operator graphically","TSMonitorSPEig",howoften,&howoften,NULL);
229:     TSMonitorSPEigCtxCreate(PETSC_COMM_SELF,NULL,NULL,PETSC_DECIDE,PETSC_DECIDE,300,300,howoften,&ctx);
230:     TSMonitorSet(ts,TSMonitorSPEig,ctx,(PetscErrorCode (*)(void**))TSMonitorSPEigCtxDestroy);
231:   }
232:   PetscOptionsName("-ts_monitor_sp_swarm","Display particle phase from the DMSwarm","TSMonitorSPSwarm",&opt);
233:   if (opt) {
234:     TSMonitorSPCtx  ctx;
235:     PetscInt        howoften = 1;
236:     PetscOptionsInt("-ts_monitor_sp_swarm","Display particles phase from the DMSwarm","TSMonitorSPSwarm",howoften,&howoften,NULL);
237:     TSMonitorSPCtxCreate(PETSC_COMM_SELF, NULL, NULL, PETSC_DECIDE, PETSC_DECIDE, 300, 300, howoften, &ctx);
238:     TSMonitorSet(ts, TSMonitorSPSwarmSolution, ctx, (PetscErrorCode (*)(void**))TSMonitorSPCtxDestroy);
239:   }
240:   opt  = PETSC_FALSE;
241:   PetscOptionsName("-ts_monitor_draw_solution","Monitor solution graphically","TSMonitorDrawSolution",&opt);
242:   if (opt) {
243:     TSMonitorDrawCtx ctx;
244:     PetscInt         howoften = 1;

246:     PetscOptionsInt("-ts_monitor_draw_solution","Monitor solution graphically","TSMonitorDrawSolution",howoften,&howoften,NULL);
247:     TSMonitorDrawCtxCreate(PetscObjectComm((PetscObject)ts),NULL,"Computed Solution",PETSC_DECIDE,PETSC_DECIDE,300,300,howoften,&ctx);
248:     TSMonitorSet(ts,TSMonitorDrawSolution,ctx,(PetscErrorCode (*)(void**))TSMonitorDrawCtxDestroy);
249:   }
250:   opt  = PETSC_FALSE;
251:   PetscOptionsName("-ts_monitor_draw_solution_phase","Monitor solution graphically","TSMonitorDrawSolutionPhase",&opt);
252:   if (opt) {
253:     TSMonitorDrawCtx ctx;
254:     PetscReal        bounds[4];
255:     PetscInt         n = 4;
256:     PetscDraw        draw;
257:     PetscDrawAxis    axis;

259:     PetscOptionsRealArray("-ts_monitor_draw_solution_phase","Monitor solution graphically","TSMonitorDrawSolutionPhase",bounds,&n,NULL);
260:     if (n != 4) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_ARG_WRONG,"Must provide bounding box of phase field");
261:     TSMonitorDrawCtxCreate(PetscObjectComm((PetscObject)ts),NULL,NULL,PETSC_DECIDE,PETSC_DECIDE,300,300,1,&ctx);
262:     PetscViewerDrawGetDraw(ctx->viewer,0,&draw);
263:     PetscViewerDrawGetDrawAxis(ctx->viewer,0,&axis);
264:     PetscDrawAxisSetLimits(axis,bounds[0],bounds[2],bounds[1],bounds[3]);
265:     PetscDrawAxisSetLabels(axis,"Phase Diagram","Variable 1","Variable 2");
266:     TSMonitorSet(ts,TSMonitorDrawSolutionPhase,ctx,(PetscErrorCode (*)(void**))TSMonitorDrawCtxDestroy);
267:   }
268:   opt  = PETSC_FALSE;
269:   PetscOptionsName("-ts_monitor_draw_error","Monitor error graphically","TSMonitorDrawError",&opt);
270:   if (opt) {
271:     TSMonitorDrawCtx ctx;
272:     PetscInt         howoften = 1;

274:     PetscOptionsInt("-ts_monitor_draw_error","Monitor error graphically","TSMonitorDrawError",howoften,&howoften,NULL);
275:     TSMonitorDrawCtxCreate(PetscObjectComm((PetscObject)ts),NULL,"Error",PETSC_DECIDE,PETSC_DECIDE,300,300,howoften,&ctx);
276:     TSMonitorSet(ts,TSMonitorDrawError,ctx,(PetscErrorCode (*)(void**))TSMonitorDrawCtxDestroy);
277:   }
278:   opt  = PETSC_FALSE;
279:   PetscOptionsName("-ts_monitor_draw_solution_function","Monitor solution provided by TSMonitorSetSolutionFunction() graphically","TSMonitorDrawSolutionFunction",&opt);
280:   if (opt) {
281:     TSMonitorDrawCtx ctx;
282:     PetscInt         howoften = 1;

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

289:   opt  = PETSC_FALSE;
290:   PetscOptionsString("-ts_monitor_solution_vtk","Save each time step to a binary file, use filename-%%03D.vts","TSMonitorSolutionVTK",NULL,monfilename,sizeof(monfilename),&flg);
291:   if (flg) {
292:     const char *ptr,*ptr2;
293:     char       *filetemplate;
294:     if (!monfilename[0]) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_USER,"-ts_monitor_solution_vtk requires a file template, e.g. filename-%%03D.vts");
295:     /* Do some cursory validation of the input. */
296:     PetscStrstr(monfilename,"%",(char**)&ptr);
297:     if (!ptr) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_USER,"-ts_monitor_solution_vtk requires a file template, e.g. filename-%%03D.vts");
298:     for (ptr++; ptr && *ptr; ptr++) {
299:       PetscStrchr("DdiouxX",*ptr,(char**)&ptr2);
300:       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");
301:       if (ptr2) break;
302:     }
303:     PetscStrallocpy(monfilename,&filetemplate);
304:     TSMonitorSet(ts,TSMonitorSolutionVTK,filetemplate,(PetscErrorCode (*)(void**))TSMonitorSolutionVTKDestroy);
305:   }

307:   PetscOptionsString("-ts_monitor_dmda_ray","Display a ray of the solution","None","y=0",dir,sizeof(dir),&flg);
308:   if (flg) {
309:     TSMonitorDMDARayCtx *rayctx;
310:     int                  ray = 0;
311:     DMDirection          ddir;
312:     DM                   da;
313:     PetscMPIInt          rank;

315:     if (dir[1] != '=') SETERRQ1(PetscObjectComm((PetscObject)ts),PETSC_ERR_ARG_WRONG,"Unknown ray %s",dir);
316:     if (dir[0] == 'x') ddir = DM_X;
317:     else if (dir[0] == 'y') ddir = DM_Y;
318:     else SETERRQ1(PetscObjectComm((PetscObject)ts),PETSC_ERR_ARG_WRONG,"Unknown ray %s",dir);
319:     sscanf(dir+2,"%d",&ray);

321:     PetscInfo2(((PetscObject)ts),"Displaying DMDA ray %c = %d\n",dir[0],ray);
322:     PetscNew(&rayctx);
323:     TSGetDM(ts,&da);
324:     DMDAGetRay(da,ddir,ray,&rayctx->ray,&rayctx->scatter);
325:     MPI_Comm_rank(PetscObjectComm((PetscObject)ts),&rank);
326:     if (rank == 0) {
327:       PetscViewerDrawOpen(PETSC_COMM_SELF,NULL,NULL,0,0,600,300,&rayctx->viewer);
328:     }
329:     rayctx->lgctx = NULL;
330:     TSMonitorSet(ts,TSMonitorDMDARay,rayctx,TSMonitorDMDARayDestroy);
331:   }
332:   PetscOptionsString("-ts_monitor_lg_dmda_ray","Display a ray of the solution","None","x=0",dir,sizeof(dir),&flg);
333:   if (flg) {
334:     TSMonitorDMDARayCtx *rayctx;
335:     int                 ray = 0;
336:     DMDirection         ddir;
337:     DM                  da;
338:     PetscInt            howoften = 1;

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

346:     PetscInfo2(((PetscObject) ts),"Displaying LG DMDA ray %c = %d\n", dir[0], ray);
347:     PetscNew(&rayctx);
348:     TSGetDM(ts, &da);
349:     DMDAGetRay(da, ddir, ray, &rayctx->ray, &rayctx->scatter);
350:     TSMonitorLGCtxCreate(PETSC_COMM_SELF,NULL,NULL,PETSC_DECIDE,PETSC_DECIDE,600,400,howoften,&rayctx->lgctx);
351:     TSMonitorSet(ts, TSMonitorLGDMDARay, rayctx, TSMonitorDMDARayDestroy);
352:   }

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

358:     TSMonitorEnvelopeCtxCreate(ts,&ctx);
359:     TSMonitorSet(ts,TSMonitorEnvelope,ctx,(PetscErrorCode (*)(void**))TSMonitorEnvelopeCtxDestroy);
360:   }
361:   flg  = PETSC_FALSE;
362:   PetscOptionsBool("-ts_monitor_cancel","Remove all monitors","TSMonitorCancel",flg,&flg,&opt);
363:   if (opt && flg) {TSMonitorCancel(ts);}

365:   flg  = PETSC_FALSE;
366:   PetscOptionsBool("-ts_fd_color", "Use finite differences with coloring to compute IJacobian", "TSComputeJacobianDefaultColor", flg, &flg, NULL);
367:   if (flg) {
368:     DM   dm;
369:     DMTS tdm;

371:     TSGetDM(ts, &dm);
372:     DMGetDMTS(dm, &tdm);
373:     tdm->ijacobianctx = NULL;
374:     TSSetIJacobian(ts, NULL, NULL, TSComputeIJacobianDefaultColor, NULL);
375:     PetscInfo(ts, "Setting default finite difference coloring Jacobian matrix\n");
376:   }

378:   /* Handle specific TS options */
379:   if (ts->ops->setfromoptions) {
380:     (*ts->ops->setfromoptions)(PetscOptionsObject,ts);
381:   }

383:   /* Handle TSAdapt options */
384:   TSGetAdapt(ts,&ts->adapt);
385:   TSAdaptSetDefaultType(ts->adapt,ts->default_adapt_type);
386:   TSAdaptSetFromOptions(PetscOptionsObject,ts->adapt);

388:   /* TS trajectory must be set after TS, since it may use some TS options above */
389:   tflg = ts->trajectory ? PETSC_TRUE : PETSC_FALSE;
390:   PetscOptionsBool("-ts_save_trajectory","Save the solution at each timestep","TSSetSaveTrajectory",tflg,&tflg,NULL);
391:   if (tflg) {
392:     TSSetSaveTrajectory(ts);
393:   }

395:   TSAdjointSetFromOptions(PetscOptionsObject,ts);

397:   /* process any options handlers added with PetscObjectAddOptionsHandler() */
398:   PetscObjectProcessOptionsHandlers(PetscOptionsObject,(PetscObject)ts);
399:   PetscOptionsEnd();

401:   if (ts->trajectory) {
402:     TSTrajectorySetFromOptions(ts->trajectory,ts);
403:   }

405:   /* why do we have to do this here and not during TSSetUp? */
406:   TSGetSNES(ts,&ts->snes);
407:   if (ts->problem_type == TS_LINEAR) {
408:     PetscObjectTypeCompareAny((PetscObject)ts->snes,&flg,SNESKSPONLY,SNESKSPTRANSPOSEONLY,"");
409:     if (!flg) { SNESSetType(ts->snes,SNESKSPONLY); }
410:   }
411:   SNESSetFromOptions(ts->snes);
412:   return(0);
413: }

415: /*@
416:    TSGetTrajectory - Gets the trajectory from a TS if it exists

418:    Collective on TS

420:    Input Parameters:
421: .  ts - the TS context obtained from TSCreate()

423:    Output Parameters:
424: .  tr - the TSTrajectory object, if it exists

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

428:    Level: advanced

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

432: @*/
433: PetscErrorCode  TSGetTrajectory(TS ts,TSTrajectory *tr)
434: {
437:   *tr = ts->trajectory;
438:   return(0);
439: }

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

444:    Collective on TS

446:    Input Parameter:
447: .  ts - the TS context obtained from TSCreate()

449:    Options Database:
450: +  -ts_save_trajectory - saves the trajectory to a file
451: -  -ts_trajectory_type type

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

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

458:    Level: intermediate

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

462: @*/
463: PetscErrorCode  TSSetSaveTrajectory(TS ts)
464: {

469:   if (!ts->trajectory) {
470:     TSTrajectoryCreate(PetscObjectComm((PetscObject)ts),&ts->trajectory);
471:   }
472:   return(0);
473: }

475: /*@
476:    TSResetTrajectory - Destroys and recreates the internal TSTrajectory object

478:    Collective on TS

480:    Input Parameters:
481: .  ts - the TS context obtained from TSCreate()

483:    Level: intermediate

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

487: @*/
488: PetscErrorCode  TSResetTrajectory(TS ts)
489: {

494:   if (ts->trajectory) {
495:     TSTrajectoryDestroy(&ts->trajectory);
496:     TSTrajectoryCreate(PetscObjectComm((PetscObject)ts),&ts->trajectory);
497:   }
498:   return(0);
499: }

501: /*@
502:    TSComputeRHSJacobian - Computes the Jacobian matrix that has been
503:       set with TSSetRHSJacobian().

505:    Collective on TS

507:    Input Parameters:
508: +  ts - the TS context
509: .  t - current timestep
510: -  U - input vector

512:    Output Parameters:
513: +  A - Jacobian matrix
514: -  B - optional preconditioning matrix

516:    Notes:
517:    Most users should not need to explicitly call this routine, as it
518:    is used internally within the nonlinear solvers.

520:    Level: developer

522: .seealso:  TSSetRHSJacobian(), KSPSetOperators()
523: @*/
524: PetscErrorCode  TSComputeRHSJacobian(TS ts,PetscReal t,Vec U,Mat A,Mat B)
525: {
526:   PetscErrorCode   ierr;
527:   PetscObjectState Ustate;
528:   PetscObjectId    Uid;
529:   DM               dm;
530:   DMTS             tsdm;
531:   TSRHSJacobian    rhsjacobianfunc;
532:   void             *ctx;
533:   TSRHSFunction    rhsfunction;

539:   TSGetDM(ts,&dm);
540:   DMGetDMTS(dm,&tsdm);
541:   DMTSGetRHSFunction(dm,&rhsfunction,NULL);
542:   DMTSGetRHSJacobian(dm,&rhsjacobianfunc,&ctx);
543:   PetscObjectStateGet((PetscObject)U,&Ustate);
544:   PetscObjectGetId((PetscObject)U,&Uid);

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

548:   if (ts->rhsjacobian.shift && ts->rhsjacobian.reuse) SETERRQ1(PetscObjectComm((PetscObject)ts),PETSC_ERR_USER,"Should not call TSComputeRHSJacobian() on a shifted matrix (shift=%lf) when RHSJacobian is reusable.",ts->rhsjacobian.shift);
549:   if (rhsjacobianfunc) {
550:     PetscLogEventBegin(TS_JacobianEval,ts,U,A,B);
551:     PetscStackPush("TS user Jacobian function");
552:     (*rhsjacobianfunc)(ts,t,U,A,B,ctx);
553:     PetscStackPop;
554:     ts->rhsjacs++;
555:     PetscLogEventEnd(TS_JacobianEval,ts,U,A,B);
556:   } else {
557:     MatZeroEntries(A);
558:     if (B && A != B) {MatZeroEntries(B);}
559:   }
560:   ts->rhsjacobian.time  = t;
561:   ts->rhsjacobian.shift = 0;
562:   ts->rhsjacobian.scale = 1.;
563:   PetscObjectGetId((PetscObject)U,&ts->rhsjacobian.Xid);
564:   PetscObjectStateGet((PetscObject)U,&ts->rhsjacobian.Xstate);
565:   return(0);
566: }

568: /*@
569:    TSComputeRHSFunction - Evaluates the right-hand-side function.

571:    Collective on TS

573:    Input Parameters:
574: +  ts - the TS context
575: .  t - current time
576: -  U - state vector

578:    Output Parameter:
579: .  y - right hand side

581:    Note:
582:    Most users should not need to explicitly call this routine, as it
583:    is used internally within the nonlinear solvers.

585:    Level: developer

587: .seealso: TSSetRHSFunction(), TSComputeIFunction()
588: @*/
589: PetscErrorCode TSComputeRHSFunction(TS ts,PetscReal t,Vec U,Vec y)
590: {
592:   TSRHSFunction  rhsfunction;
593:   TSIFunction    ifunction;
594:   void           *ctx;
595:   DM             dm;

601:   TSGetDM(ts,&dm);
602:   DMTSGetRHSFunction(dm,&rhsfunction,&ctx);
603:   DMTSGetIFunction(dm,&ifunction,NULL);

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

607:   if (rhsfunction) {
608:     PetscLogEventBegin(TS_FunctionEval,ts,U,y,0);
609:     VecLockReadPush(U);
610:     PetscStackPush("TS user right-hand-side function");
611:     (*rhsfunction)(ts,t,U,y,ctx);
612:     PetscStackPop;
613:     VecLockReadPop(U);
614:     ts->rhsfuncs++;
615:     PetscLogEventEnd(TS_FunctionEval,ts,U,y,0);
616:   } else {
617:     VecZeroEntries(y);
618:   }
619:   return(0);
620: }

622: /*@
623:    TSComputeSolutionFunction - Evaluates the solution function.

625:    Collective on TS

627:    Input Parameters:
628: +  ts - the TS context
629: -  t - current time

631:    Output Parameter:
632: .  U - the solution

634:    Note:
635:    Most users should not need to explicitly call this routine, as it
636:    is used internally within the nonlinear solvers.

638:    Level: developer

640: .seealso: TSSetSolutionFunction(), TSSetRHSFunction(), TSComputeIFunction()
641: @*/
642: PetscErrorCode TSComputeSolutionFunction(TS ts,PetscReal t,Vec U)
643: {
644:   PetscErrorCode     ierr;
645:   TSSolutionFunction solutionfunction;
646:   void               *ctx;
647:   DM                 dm;

652:   TSGetDM(ts,&dm);
653:   DMTSGetSolutionFunction(dm,&solutionfunction,&ctx);

655:   if (solutionfunction) {
656:     PetscStackPush("TS user solution function");
657:     (*solutionfunction)(ts,t,U,ctx);
658:     PetscStackPop;
659:   }
660:   return(0);
661: }
662: /*@
663:    TSComputeForcingFunction - Evaluates the forcing function.

665:    Collective on TS

667:    Input Parameters:
668: +  ts - the TS context
669: -  t - current time

671:    Output Parameter:
672: .  U - the function value

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

678:    Level: developer

680: .seealso: TSSetSolutionFunction(), TSSetRHSFunction(), TSComputeIFunction()
681: @*/
682: PetscErrorCode TSComputeForcingFunction(TS ts,PetscReal t,Vec U)
683: {
684:   PetscErrorCode     ierr, (*forcing)(TS,PetscReal,Vec,void*);
685:   void               *ctx;
686:   DM                 dm;

691:   TSGetDM(ts,&dm);
692:   DMTSGetForcingFunction(dm,&forcing,&ctx);

694:   if (forcing) {
695:     PetscStackPush("TS user forcing function");
696:     (*forcing)(ts,t,U,ctx);
697:     PetscStackPop;
698:   }
699:   return(0);
700: }

702: static PetscErrorCode TSGetRHSVec_Private(TS ts,Vec *Frhs)
703: {
704:   Vec            F;

708:   *Frhs = NULL;
709:   TSGetIFunction(ts,&F,NULL,NULL);
710:   if (!ts->Frhs) {
711:     VecDuplicate(F,&ts->Frhs);
712:   }
713:   *Frhs = ts->Frhs;
714:   return(0);
715: }

717: PetscErrorCode TSGetRHSMats_Private(TS ts,Mat *Arhs,Mat *Brhs)
718: {
719:   Mat            A,B;
721:   TSIJacobian    ijacobian;

724:   if (Arhs) *Arhs = NULL;
725:   if (Brhs) *Brhs = NULL;
726:   TSGetIJacobian(ts,&A,&B,&ijacobian,NULL);
727:   if (Arhs) {
728:     if (!ts->Arhs) {
729:       if (ijacobian) {
730:         MatDuplicate(A,MAT_DO_NOT_COPY_VALUES,&ts->Arhs);
731:         TSSetMatStructure(ts,SAME_NONZERO_PATTERN);
732:       } else {
733:         ts->Arhs = A;
734:         PetscObjectReference((PetscObject)A);
735:       }
736:     } else {
737:       PetscBool flg;
738:       SNESGetUseMatrixFree(ts->snes,NULL,&flg);
739:       /* Handle case where user provided only RHSJacobian and used -snes_mf_operator */
740:       if (flg && !ijacobian && ts->Arhs == ts->Brhs) {
741:         PetscObjectDereference((PetscObject)ts->Arhs);
742:         ts->Arhs = A;
743:         PetscObjectReference((PetscObject)A);
744:       }
745:     }
746:     *Arhs = ts->Arhs;
747:   }
748:   if (Brhs) {
749:     if (!ts->Brhs) {
750:       if (A != B) {
751:         if (ijacobian) {
752:           MatDuplicate(B,MAT_DO_NOT_COPY_VALUES,&ts->Brhs);
753:         } else {
754:           ts->Brhs = B;
755:           PetscObjectReference((PetscObject)B);
756:         }
757:       } else {
758:         PetscObjectReference((PetscObject)ts->Arhs);
759:         ts->Brhs = ts->Arhs;
760:       }
761:     }
762:     *Brhs = ts->Brhs;
763:   }
764:   return(0);
765: }

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

770:    Collective on TS

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

779:    Output Parameter:
780: .  Y - right hand side

782:    Note:
783:    Most users should not need to explicitly call this routine, as it
784:    is used internally within the nonlinear solvers.

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

789:    Level: developer

791: .seealso: TSSetIFunction(), TSComputeRHSFunction()
792: @*/
793: PetscErrorCode TSComputeIFunction(TS ts,PetscReal t,Vec U,Vec Udot,Vec Y,PetscBool imex)
794: {
796:   TSIFunction    ifunction;
797:   TSRHSFunction  rhsfunction;
798:   void           *ctx;
799:   DM             dm;


807:   TSGetDM(ts,&dm);
808:   DMTSGetIFunction(dm,&ifunction,&ctx);
809:   DMTSGetRHSFunction(dm,&rhsfunction,NULL);

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

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

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

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

845: */
846: static PetscErrorCode TSRecoverRHSJacobian(TS ts,Mat A,Mat B)
847: {
848:   PetscErrorCode   ierr;

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

855:   if (ts->rhsjacobian.shift) {
856:     MatShift(A,-ts->rhsjacobian.shift);
857:   }
858:   if (ts->rhsjacobian.scale == -1.) {
859:     MatScale(A,-1);
860:   }
861:   if (B && B == ts->Brhs && A != B) {
862:     if (ts->rhsjacobian.shift) {
863:       MatShift(B,-ts->rhsjacobian.shift);
864:     }
865:     if (ts->rhsjacobian.scale == -1.) {
866:       MatScale(B,-1);
867:     }
868:   }
869:   ts->rhsjacobian.shift = 0;
870:   ts->rhsjacobian.scale = 1.;
871:   return(0);
872: }

874: /*@
875:    TSComputeIJacobian - Evaluates the Jacobian of the DAE

877:    Collective on TS

879:    Input
880:       Input Parameters:
881: +  ts - the TS context
882: .  t - current timestep
883: .  U - state vector
884: .  Udot - time derivative of state vector
885: .  shift - shift to apply, see note below
886: -  imex - flag indicates if the method is IMEX so that the RHSJacobian should be kept separate

888:    Output Parameters:
889: +  A - Jacobian matrix
890: -  B - matrix from which the preconditioner is constructed; often the same as A

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

895:    dF/dU + shift*dF/dUdot

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

900:    Level: developer

902: .seealso:  TSSetIJacobian()
903: @*/
904: PetscErrorCode TSComputeIJacobian(TS ts,PetscReal t,Vec U,Vec Udot,PetscReal shift,Mat A,Mat B,PetscBool imex)
905: {
907:   TSIJacobian    ijacobian;
908:   TSRHSJacobian  rhsjacobian;
909:   DM             dm;
910:   void           *ctx;


921:   TSGetDM(ts,&dm);
922:   DMTSGetIJacobian(dm,&ijacobian,&ctx);
923:   DMTSGetRHSJacobian(dm,&rhsjacobian,NULL);

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

927:   PetscLogEventBegin(TS_JacobianEval,ts,U,A,B);
928:   if (ijacobian) {
929:     PetscStackPush("TS user implicit Jacobian");
930:     (*ijacobian)(ts,t,U,Udot,shift,A,B,ctx);
931:     ts->ijacs++;
932:     PetscStackPop;
933:   }
934:   if (imex) {
935:     if (!ijacobian) {  /* system was written as Udot = G(t,U) */
936:       PetscBool assembled;
937:       if (rhsjacobian) {
938:         Mat Arhs = NULL;
939:         TSGetRHSMats_Private(ts,&Arhs,NULL);
940:         if (A == Arhs) {
941:           if (rhsjacobian == TSComputeRHSJacobianConstant) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"Unsupported operation! cannot use TSComputeRHSJacobianConstant"); /* there is no way to reconstruct shift*M-J since J cannot be reevaluated */
942:           ts->rhsjacobian.time = PETSC_MIN_REAL;
943:         }
944:       }
945:       MatZeroEntries(A);
946:       MatAssembled(A,&assembled);
947:       if (!assembled) {
948:         MatAssemblyBegin(A,MAT_FINAL_ASSEMBLY);
949:         MatAssemblyEnd(A,MAT_FINAL_ASSEMBLY);
950:       }
951:       MatShift(A,shift);
952:       if (A != B) {
953:         MatZeroEntries(B);
954:         MatAssembled(B,&assembled);
955:         if (!assembled) {
956:           MatAssemblyBegin(B,MAT_FINAL_ASSEMBLY);
957:           MatAssemblyEnd(B,MAT_FINAL_ASSEMBLY);
958:         }
959:         MatShift(B,shift);
960:       }
961:     }
962:   } else {
963:     Mat Arhs = NULL,Brhs = NULL;
964:     if (rhsjacobian) { /* RHSJacobian needs to be converted to part of IJacobian if exists */
965:       TSGetRHSMats_Private(ts,&Arhs,&Brhs);
966:     }
967:     if (Arhs == A) { /* No IJacobian matrix, so we only have the RHS matrix */
968:       PetscObjectState Ustate;
969:       PetscObjectId    Uid;
970:       TSRHSFunction    rhsfunction;

972:       DMTSGetRHSFunction(dm,&rhsfunction,NULL);
973:       PetscObjectStateGet((PetscObject)U,&Ustate);
974:       PetscObjectGetId((PetscObject)U,&Uid);
975:       if ((rhsjacobian == TSComputeRHSJacobianConstant || (ts->rhsjacobian.time == t && (ts->problem_type == TS_LINEAR || (ts->rhsjacobian.Xid == Uid && ts->rhsjacobian.Xstate == Ustate)) && rhsfunction != TSComputeRHSFunctionLinear)) && ts->rhsjacobian.scale == -1.) { /* No need to recompute RHSJacobian */
976:         MatShift(A,shift-ts->rhsjacobian.shift); /* revert the old shift and add the new shift with a single call to MatShift */
977:         if (A != B) {
978:           MatShift(B,shift-ts->rhsjacobian.shift);
979:         }
980:       } else {
981:         PetscBool flg;

983:         if (ts->rhsjacobian.reuse) { /* Undo the damage */
984:           /* MatScale has a short path for this case.
985:              However, this code path is taken the first time TSComputeRHSJacobian is called
986:              and the matrices have not been assembled yet */
987:           TSRecoverRHSJacobian(ts,A,B);
988:         }
989:         TSComputeRHSJacobian(ts,t,U,A,B);
990:         SNESGetUseMatrixFree(ts->snes,NULL,&flg);
991:         /* since -snes_mf_operator uses the full SNES function it does not need to be shifted or scaled here */
992:         if (!flg) {
993:           MatScale(A,-1);
994:           MatShift(A,shift);
995:         }
996:         if (A != B) {
997:           MatScale(B,-1);
998:           MatShift(B,shift);
999:         }
1000:       }
1001:       ts->rhsjacobian.scale = -1;
1002:       ts->rhsjacobian.shift = shift;
1003:     } else if (Arhs) {          /* Both IJacobian and RHSJacobian */
1004:       if (!ijacobian) {         /* No IJacobian provided, but we have a separate RHS matrix */
1005:         MatZeroEntries(A);
1006:         MatShift(A,shift);
1007:         if (A != B) {
1008:           MatZeroEntries(B);
1009:           MatShift(B,shift);
1010:         }
1011:       }
1012:       TSComputeRHSJacobian(ts,t,U,Arhs,Brhs);
1013:       MatAXPY(A,-1,Arhs,ts->axpy_pattern);
1014:       if (A != B) {
1015:         MatAXPY(B,-1,Brhs,ts->axpy_pattern);
1016:       }
1017:     }
1018:   }
1019:   PetscLogEventEnd(TS_JacobianEval,ts,U,A,B);
1020:   return(0);
1021: }

1023: /*@C
1024:     TSSetRHSFunction - Sets the routine for evaluating the function,
1025:     where U_t = G(t,u).

1027:     Logically Collective on TS

1029:     Input Parameters:
1030: +   ts - the TS context obtained from TSCreate()
1031: .   r - vector to put the computed right hand side (or NULL to have it created)
1032: .   f - routine for evaluating the right-hand-side function
1033: -   ctx - [optional] user-defined context for private data for the
1034:           function evaluation routine (may be NULL)

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

1039: +   ts - timestep context
1040: .   t - current timestep
1041: .   u - input vector
1042: .   F - function vector
1043: -   ctx - [optional] user-defined function context

1045:     Level: beginner

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

1050: .seealso: TSSetRHSJacobian(), TSSetIJacobian(), TSSetIFunction()
1051: @*/
1052: PetscErrorCode  TSSetRHSFunction(TS ts,Vec r,PetscErrorCode (*f)(TS,PetscReal,Vec,Vec,void*),void *ctx)
1053: {
1055:   SNES           snes;
1056:   Vec            ralloc = NULL;
1057:   DM             dm;


1063:   TSGetDM(ts,&dm);
1064:   DMTSSetRHSFunction(dm,f,ctx);
1065:   TSGetSNES(ts,&snes);
1066:   if (!r && !ts->dm && ts->vec_sol) {
1067:     VecDuplicate(ts->vec_sol,&ralloc);
1068:     r = ralloc;
1069:   }
1070:   SNESSetFunction(snes,r,SNESTSFormFunction,ts);
1071:   VecDestroy(&ralloc);
1072:   return(0);
1073: }

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

1078:     Logically Collective on TS

1080:     Input Parameters:
1081: +   ts - the TS context obtained from TSCreate()
1082: .   f - routine for evaluating the solution
1083: -   ctx - [optional] user-defined context for private data for the
1084:           function evaluation routine (may be NULL)

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

1089: +   t - current timestep
1090: .   u - output vector
1091: -   ctx - [optional] user-defined function context

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

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

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

1104:     Level: beginner

1106: .seealso: TSSetRHSJacobian(), TSSetIJacobian(), TSComputeSolutionFunction(), TSSetForcingFunction(), TSSetSolution(), TSGetSolution(), TSMonitorLGError(), TSMonitorDrawError()
1107: @*/
1108: PetscErrorCode  TSSetSolutionFunction(TS ts,PetscErrorCode (*f)(TS,PetscReal,Vec,void*),void *ctx)
1109: {
1111:   DM             dm;

1115:   TSGetDM(ts,&dm);
1116:   DMTSSetSolutionFunction(dm,f,ctx);
1117:   return(0);
1118: }

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

1123:     Logically Collective on TS

1125:     Input Parameters:
1126: +   ts - the TS context obtained from TSCreate()
1127: .   func - routine for evaluating the forcing function
1128: -   ctx - [optional] user-defined context for private data for the
1129:           function evaluation routine (may be NULL)

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

1134: +   t - current timestep
1135: .   f - output vector
1136: -   ctx - [optional] user-defined function context

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

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

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

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

1150:     Level: beginner

1152: .seealso: TSSetRHSJacobian(), TSSetIJacobian(), TSComputeSolutionFunction(), TSSetSolutionFunction()
1153: @*/
1154: PetscErrorCode  TSSetForcingFunction(TS ts,TSForcingFunction func,void *ctx)
1155: {
1157:   DM             dm;

1161:   TSGetDM(ts,&dm);
1162:   DMTSSetForcingFunction(dm,func,ctx);
1163:   return(0);
1164: }

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

1170:    Logically Collective on TS

1172:    Input Parameters:
1173: +  ts  - the TS context obtained from TSCreate()
1174: .  Amat - (approximate) Jacobian matrix
1175: .  Pmat - matrix from which preconditioner is to be constructed (usually the same as Amat)
1176: .  f   - the Jacobian evaluation routine
1177: -  ctx - [optional] user-defined context for private data for the
1178:          Jacobian evaluation routine (may be NULL)

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

1183: +  t - current timestep
1184: .  u - input vector
1185: .  Amat - (approximate) Jacobian matrix
1186: .  Pmat - matrix from which preconditioner is to be constructed (usually the same as Amat)
1187: -  ctx - [optional] user-defined context for matrix evaluation routine

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

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

1195:    Level: beginner

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

1199: @*/
1200: PetscErrorCode  TSSetRHSJacobian(TS ts,Mat Amat,Mat Pmat,TSRHSJacobian f,void *ctx)
1201: {
1203:   SNES           snes;
1204:   DM             dm;
1205:   TSIJacobian    ijacobian;


1214:   TSGetDM(ts,&dm);
1215:   DMTSSetRHSJacobian(dm,f,ctx);
1216:   DMTSGetIJacobian(dm,&ijacobian,NULL);
1217:   TSGetSNES(ts,&snes);
1218:   if (!ijacobian) {
1219:     SNESSetJacobian(snes,Amat,Pmat,SNESTSFormJacobian,ts);
1220:   }
1221:   if (Amat) {
1222:     PetscObjectReference((PetscObject)Amat);
1223:     MatDestroy(&ts->Arhs);
1224:     ts->Arhs = Amat;
1225:   }
1226:   if (Pmat) {
1227:     PetscObjectReference((PetscObject)Pmat);
1228:     MatDestroy(&ts->Brhs);
1229:     ts->Brhs = Pmat;
1230:   }
1231:   return(0);
1232: }

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

1237:    Logically Collective on TS

1239:    Input Parameters:
1240: +  ts  - the TS context obtained from TSCreate()
1241: .  r   - vector to hold the residual (or NULL to have it created internally)
1242: .  f   - the function evaluation routine
1243: -  ctx - user-defined context for private data for the function evaluation routine (may be NULL)

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

1248: +  t   - time at step/stage being solved
1249: .  u   - state vector
1250: .  u_t - time derivative of state vector
1251: .  F   - function vector
1252: -  ctx - [optional] user-defined context for matrix evaluation routine

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

1257:    Level: beginner

1259: .seealso: TSSetRHSJacobian(), TSSetRHSFunction(), TSSetIJacobian()
1260: @*/
1261: PetscErrorCode  TSSetIFunction(TS ts,Vec r,TSIFunction f,void *ctx)
1262: {
1264:   SNES           snes;
1265:   Vec            ralloc = NULL;
1266:   DM             dm;


1272:   TSGetDM(ts,&dm);
1273:   DMTSSetIFunction(dm,f,ctx);

1275:   TSGetSNES(ts,&snes);
1276:   if (!r && !ts->dm && ts->vec_sol) {
1277:     VecDuplicate(ts->vec_sol,&ralloc);
1278:     r  = ralloc;
1279:   }
1280:   SNESSetFunction(snes,r,SNESTSFormFunction,ts);
1281:   VecDestroy(&ralloc);
1282:   return(0);
1283: }

1285: /*@C
1286:    TSGetIFunction - Returns the vector where the implicit residual is stored and the function/context to compute it.

1288:    Not Collective

1290:    Input Parameter:
1291: .  ts - the TS context

1293:    Output Parameters:
1294: +  r - vector to hold residual (or NULL)
1295: .  func - the function to compute residual (or NULL)
1296: -  ctx - the function context (or NULL)

1298:    Level: advanced

1300: .seealso: TSSetIFunction(), SNESGetFunction()
1301: @*/
1302: PetscErrorCode TSGetIFunction(TS ts,Vec *r,TSIFunction *func,void **ctx)
1303: {
1305:   SNES           snes;
1306:   DM             dm;

1310:   TSGetSNES(ts,&snes);
1311:   SNESGetFunction(snes,r,NULL,NULL);
1312:   TSGetDM(ts,&dm);
1313:   DMTSGetIFunction(dm,func,ctx);
1314:   return(0);
1315: }

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

1320:    Not Collective

1322:    Input Parameter:
1323: .  ts - the TS context

1325:    Output Parameters:
1326: +  r - vector to hold computed right hand side (or NULL)
1327: .  func - the function to compute right hand side (or NULL)
1328: -  ctx - the function context (or NULL)

1330:    Level: advanced

1332: .seealso: TSSetRHSFunction(), SNESGetFunction()
1333: @*/
1334: PetscErrorCode TSGetRHSFunction(TS ts,Vec *r,TSRHSFunction *func,void **ctx)
1335: {
1337:   SNES           snes;
1338:   DM             dm;

1342:   TSGetSNES(ts,&snes);
1343:   SNESGetFunction(snes,r,NULL,NULL);
1344:   TSGetDM(ts,&dm);
1345:   DMTSGetRHSFunction(dm,func,ctx);
1346:   return(0);
1347: }

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

1353:    Logically Collective on TS

1355:    Input Parameters:
1356: +  ts  - the TS context obtained from TSCreate()
1357: .  Amat - (approximate) Jacobian matrix
1358: .  Pmat - matrix used to compute preconditioner (usually the same as Amat)
1359: .  f   - the Jacobian evaluation routine
1360: -  ctx - user-defined context for private data for the Jacobian evaluation routine (may be NULL)

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

1365: +  t    - time at step/stage being solved
1366: .  U    - state vector
1367: .  U_t  - time derivative of state vector
1368: .  a    - shift
1369: .  Amat - (approximate) Jacobian of F(t,U,W+a*U), equivalent to dF/dU + a*dF/dU_t
1370: .  Pmat - matrix used for constructing preconditioner, usually the same as Amat
1371: -  ctx  - [optional] user-defined context for matrix evaluation routine

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

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

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

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

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

1391:    Level: beginner

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

1395: @*/
1396: PetscErrorCode  TSSetIJacobian(TS ts,Mat Amat,Mat Pmat,TSIJacobian f,void *ctx)
1397: {
1399:   SNES           snes;
1400:   DM             dm;


1409:   TSGetDM(ts,&dm);
1410:   DMTSSetIJacobian(dm,f,ctx);

1412:   TSGetSNES(ts,&snes);
1413:   SNESSetJacobian(snes,Amat,Pmat,SNESTSFormJacobian,ts);
1414:   return(0);
1415: }

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

1423:    Logically Collective

1425:    Input Parameters:
1426: +  ts - TS context obtained from TSCreate()
1427: -  reuse - PETSC_TRUE if the RHS Jacobian

1429:    Level: intermediate

1431: .seealso: TSSetRHSJacobian(), TSComputeRHSJacobianConstant()
1432: @*/
1433: PetscErrorCode TSRHSJacobianSetReuse(TS ts,PetscBool reuse)
1434: {
1436:   ts->rhsjacobian.reuse = reuse;
1437:   return(0);
1438: }

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

1443:    Logically Collective on TS

1445:    Input Parameters:
1446: +  ts  - the TS context obtained from TSCreate()
1447: .  F   - vector to hold the residual (or NULL to have it created internally)
1448: .  fun - the function evaluation routine
1449: -  ctx - user-defined context for private data for the function evaluation routine (may be NULL)

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

1454: +  t    - time at step/stage being solved
1455: .  U    - state vector
1456: .  U_t  - time derivative of state vector
1457: .  U_tt - second time derivative of state vector
1458: .  F    - function vector
1459: -  ctx  - [optional] user-defined context for matrix evaluation routine (may be NULL)

1461:    Level: beginner

1463: .seealso: TSSetI2Jacobian(), TSSetIFunction(), TSCreate(), TSSetRHSFunction()
1464: @*/
1465: PetscErrorCode TSSetI2Function(TS ts,Vec F,TSI2Function fun,void *ctx)
1466: {
1467:   DM             dm;

1473:   TSSetIFunction(ts,F,NULL,NULL);
1474:   TSGetDM(ts,&dm);
1475:   DMTSSetI2Function(dm,fun,ctx);
1476:   return(0);
1477: }

1479: /*@C
1480:   TSGetI2Function - Returns the vector where the implicit residual is stored and the function/context to compute it.

1482:   Not Collective

1484:   Input Parameter:
1485: . ts - the TS context

1487:   Output Parameters:
1488: + r - vector to hold residual (or NULL)
1489: . fun - the function to compute residual (or NULL)
1490: - ctx - the function context (or NULL)

1492:   Level: advanced

1494: .seealso: TSSetIFunction(), SNESGetFunction(), TSCreate()
1495: @*/
1496: PetscErrorCode TSGetI2Function(TS ts,Vec *r,TSI2Function *fun,void **ctx)
1497: {
1499:   SNES           snes;
1500:   DM             dm;

1504:   TSGetSNES(ts,&snes);
1505:   SNESGetFunction(snes,r,NULL,NULL);
1506:   TSGetDM(ts,&dm);
1507:   DMTSGetI2Function(dm,fun,ctx);
1508:   return(0);
1509: }

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

1515:    Logically Collective on TS

1517:    Input Parameters:
1518: +  ts  - the TS context obtained from TSCreate()
1519: .  J   - Jacobian matrix
1520: .  P   - preconditioning matrix for J (may be same as J)
1521: .  jac - the Jacobian evaluation routine
1522: -  ctx - user-defined context for private data for the Jacobian evaluation routine (may be NULL)

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

1527: +  t    - time at step/stage being solved
1528: .  U    - state vector
1529: .  U_t  - time derivative of state vector
1530: .  U_tt - second time derivative of state vector
1531: .  v    - shift for U_t
1532: .  a    - shift for U_tt
1533: .  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
1534: .  P    - preconditioning matrix for J, may be same as J
1535: -  ctx  - [optional] user-defined context for matrix evaluation routine

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

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

1545:    Level: beginner

1547: .seealso: TSSetI2Function(), TSGetI2Jacobian()
1548: @*/
1549: PetscErrorCode TSSetI2Jacobian(TS ts,Mat J,Mat P,TSI2Jacobian jac,void *ctx)
1550: {
1551:   DM             dm;

1558:   TSSetIJacobian(ts,J,P,NULL,NULL);
1559:   TSGetDM(ts,&dm);
1560:   DMTSSetI2Jacobian(dm,jac,ctx);
1561:   return(0);
1562: }

1564: /*@C
1565:   TSGetI2Jacobian - Returns the implicit Jacobian at the present timestep.

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

1569:   Input Parameter:
1570: . ts  - The TS context obtained from TSCreate()

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

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

1581:   Level: advanced

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

1585: @*/
1586: PetscErrorCode  TSGetI2Jacobian(TS ts,Mat *J,Mat *P,TSI2Jacobian *jac,void **ctx)
1587: {
1589:   SNES           snes;
1590:   DM             dm;

1593:   TSGetSNES(ts,&snes);
1594:   SNESSetUpMatrices(snes);
1595:   SNESGetJacobian(snes,J,P,NULL,NULL);
1596:   TSGetDM(ts,&dm);
1597:   DMTSGetI2Jacobian(dm,jac,ctx);
1598:   return(0);
1599: }

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

1604:   Collective on TS

1606:   Input Parameters:
1607: + ts - the TS context
1608: . t - current time
1609: . U - state vector
1610: . V - time derivative of state vector (U_t)
1611: - A - second time derivative of state vector (U_tt)

1613:   Output Parameter:
1614: . F - the residual vector

1616:   Note:
1617:   Most users should not need to explicitly call this routine, as it
1618:   is used internally within the nonlinear solvers.

1620:   Level: developer

1622: .seealso: TSSetI2Function(), TSGetI2Function()
1623: @*/
1624: PetscErrorCode TSComputeI2Function(TS ts,PetscReal t,Vec U,Vec V,Vec A,Vec F)
1625: {
1626:   DM             dm;
1627:   TSI2Function   I2Function;
1628:   void           *ctx;
1629:   TSRHSFunction  rhsfunction;


1639:   TSGetDM(ts,&dm);
1640:   DMTSGetI2Function(dm,&I2Function,&ctx);
1641:   DMTSGetRHSFunction(dm,&rhsfunction,NULL);

1643:   if (!I2Function) {
1644:     TSComputeIFunction(ts,t,U,A,F,PETSC_FALSE);
1645:     return(0);
1646:   }

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

1650:   PetscStackPush("TS user implicit function");
1651:   I2Function(ts,t,U,V,A,F,ctx);
1652:   PetscStackPop;

1654:   if (rhsfunction) {
1655:     Vec Frhs;
1656:     TSGetRHSVec_Private(ts,&Frhs);
1657:     TSComputeRHSFunction(ts,t,U,Frhs);
1658:     VecAXPY(F,-1,Frhs);
1659:   }

1661:   PetscLogEventEnd(TS_FunctionEval,ts,U,V,F);
1662:   return(0);
1663: }

1665: /*@
1666:   TSComputeI2Jacobian - Evaluates the Jacobian of the DAE

1668:   Collective on TS

1670:   Input Parameters:
1671: + ts - the TS context
1672: . t - current timestep
1673: . U - state vector
1674: . V - time derivative of state vector
1675: . A - second time derivative of state vector
1676: . shiftV - shift to apply, see note below
1677: - shiftA - shift to apply, see note below

1679:   Output Parameters:
1680: + J - Jacobian matrix
1681: - P - optional preconditioning matrix

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

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

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

1691:   Level: developer

1693: .seealso:  TSSetI2Jacobian()
1694: @*/
1695: PetscErrorCode TSComputeI2Jacobian(TS ts,PetscReal t,Vec U,Vec V,Vec A,PetscReal shiftV,PetscReal shiftA,Mat J,Mat P)
1696: {
1697:   DM             dm;
1698:   TSI2Jacobian   I2Jacobian;
1699:   void           *ctx;
1700:   TSRHSJacobian  rhsjacobian;


1711:   TSGetDM(ts,&dm);
1712:   DMTSGetI2Jacobian(dm,&I2Jacobian,&ctx);
1713:   DMTSGetRHSJacobian(dm,&rhsjacobian,NULL);

1715:   if (!I2Jacobian) {
1716:     TSComputeIJacobian(ts,t,U,A,shiftA,J,P,PETSC_FALSE);
1717:     return(0);
1718:   }

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

1722:   PetscStackPush("TS user implicit Jacobian");
1723:   I2Jacobian(ts,t,U,V,A,shiftV,shiftA,J,P,ctx);
1724:   PetscStackPop;

1726:   if (rhsjacobian) {
1727:     Mat Jrhs,Prhs;
1728:     TSGetRHSMats_Private(ts,&Jrhs,&Prhs);
1729:     TSComputeRHSJacobian(ts,t,U,Jrhs,Prhs);
1730:     MatAXPY(J,-1,Jrhs,ts->axpy_pattern);
1731:     if (P != J) {MatAXPY(P,-1,Prhs,ts->axpy_pattern);}
1732:   }

1734:   PetscLogEventEnd(TS_JacobianEval,ts,U,J,P);
1735:   return(0);
1736: }

1738: /*@C
1739:    TSSetTransientVariable - sets function to transform from state to transient variables

1741:    Logically Collective

1743:    Input Parameters:
1744: +  ts - time stepping context on which to change the transient variable
1745: .  tvar - a function that transforms to transient variables
1746: -  ctx - a context for tvar

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

1751: +   ts - timestep context
1752: .   p - input vector (primative form)
1753: .   c - output vector, transient variables (conservative form)
1754: -   ctx - [optional] user-defined function context

1756:    Level: advanced

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

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

1767: .seealso: DMTSSetTransientVariable(), DMTSGetTransientVariable(), TSSetIFunction(), TSSetIJacobian()
1768: @*/
1769: PetscErrorCode TSSetTransientVariable(TS ts,TSTransientVariable tvar,void *ctx)
1770: {
1772:   DM             dm;

1776:   TSGetDM(ts,&dm);
1777:   DMTSSetTransientVariable(dm,tvar,ctx);
1778:   return(0);
1779: }

1781: /*@
1782:    TSComputeTransientVariable - transforms state (primitive) variables to transient (conservative) variables

1784:    Logically Collective

1786:    Input Parameters:
1787: +  ts - TS on which to compute
1788: -  U - state vector to be transformed to transient variables

1790:    Output Parameters:
1791: .  C - transient (conservative) variable

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

1798:    Level: developer

1800: .seealso: DMTSSetTransientVariable(), TSComputeIFunction(), TSComputeIJacobian()
1801: @*/
1802: PetscErrorCode TSComputeTransientVariable(TS ts,Vec U,Vec C)
1803: {
1805:   DM             dm;
1806:   DMTS           dmts;

1811:   TSGetDM(ts,&dm);
1812:   DMGetDMTS(dm,&dmts);
1813:   if (dmts->ops->transientvar) {
1815:     (*dmts->ops->transientvar)(ts,U,C,dmts->transientvarctx);
1816:   }
1817:   return(0);
1818: }

1820: /*@
1821:    TSHasTransientVariable - determine whether transient variables have been set

1823:    Logically Collective

1825:    Input Parameters:
1826: .  ts - TS on which to compute

1828:    Output Parameters:
1829: .  has - PETSC_TRUE if transient variables have been set

1831:    Level: developer

1833: .seealso: DMTSSetTransientVariable(), TSComputeTransientVariable()
1834: @*/
1835: PetscErrorCode TSHasTransientVariable(TS ts,PetscBool *has)
1836: {
1838:   DM             dm;
1839:   DMTS           dmts;

1843:   TSGetDM(ts,&dm);
1844:   DMGetDMTS(dm,&dmts);
1845:   *has = dmts->ops->transientvar ? PETSC_TRUE : PETSC_FALSE;
1846:   return(0);
1847: }

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

1853:    Logically Collective on TS

1855:    Input Parameters:
1856: +  ts - the TS context obtained from TSCreate()
1857: .  u - the solution vector
1858: -  v - the time derivative vector

1860:    Level: beginner

1862: @*/
1863: PetscErrorCode  TS2SetSolution(TS ts,Vec u,Vec v)
1864: {

1871:   TSSetSolution(ts,u);
1872:   PetscObjectReference((PetscObject)v);
1873:   VecDestroy(&ts->vec_dot);
1874:   ts->vec_dot = v;
1875:   return(0);
1876: }

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

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

1886:    Input Parameter:
1887: .  ts - the TS context obtained from TSCreate()

1889:    Output Parameters:
1890: +  u - the vector containing the solution
1891: -  v - the vector containing the time derivative

1893:    Level: intermediate

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

1897: @*/
1898: PetscErrorCode  TS2GetSolution(TS ts,Vec *u,Vec *v)
1899: {
1904:   if (u) *u = ts->vec_sol;
1905:   if (v) *v = ts->vec_dot;
1906:   return(0);
1907: }

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

1912:   Collective on PetscViewer

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

1919:    Level: intermediate

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

1924:   Notes for advanced users:
1925:   Most users should not need to know the details of the binary storage
1926:   format, since TSLoad() and TSView() completely hide these details.
1927:   But for anyone who's interested, the standard binary matrix storage
1928:   format is
1929: .vb
1930:      has not yet been determined
1931: .ve

1933: .seealso: PetscViewerBinaryOpen(), TSView(), MatLoad(), VecLoad()
1934: @*/
1935: PetscErrorCode  TSLoad(TS ts, PetscViewer viewer)
1936: {
1938:   PetscBool      isbinary;
1939:   PetscInt       classid;
1940:   char           type[256];
1941:   DMTS           sdm;
1942:   DM             dm;

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

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

1967: #include <petscdraw.h>
1968: #if defined(PETSC_HAVE_SAWS)
1969: #include <petscviewersaws.h>
1970: #endif

1972: /*@C
1973:    TSViewFromOptions - View from Options

1975:    Collective on TS

1977:    Input Parameters:
1978: +  A - the application ordering context
1979: .  obj - Optional object
1980: -  name - command line option

1982:    Level: intermediate
1983: .seealso:  TS, TSView, PetscObjectViewFromOptions(), TSCreate()
1984: @*/
1985: PetscErrorCode  TSViewFromOptions(TS A,PetscObject obj,const char name[])
1986: {

1991:   PetscObjectViewFromOptions((PetscObject)A,obj,name);
1992:   return(0);
1993: }

1995: /*@C
1996:     TSView - Prints the TS data structure.

1998:     Collective on TS

2000:     Input Parameters:
2001: +   ts - the TS context obtained from TSCreate()
2002: -   viewer - visualization context

2004:     Options Database Key:
2005: .   -ts_view - calls TSView() at end of TSStep()

2007:     Notes:
2008:     The available visualization contexts include
2009: +     PETSC_VIEWER_STDOUT_SELF - standard output (default)
2010: -     PETSC_VIEWER_STDOUT_WORLD - synchronized standard
2011:          output where only the first processor opens
2012:          the file.  All other processors send their
2013:          data to the first processor to print.

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

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

2020:     Level: beginner

2022: .seealso: PetscViewerASCIIOpen()
2023: @*/
2024: PetscErrorCode  TSView(TS ts,PetscViewer viewer)
2025: {
2027:   TSType         type;
2028:   PetscBool      iascii,isstring,isundials,isbinary,isdraw;
2029:   DMTS           sdm;
2030: #if defined(PETSC_HAVE_SAWS)
2031:   PetscBool      issaws;
2032: #endif

2036:   if (!viewer) {
2037:     PetscViewerASCIIGetStdout(PetscObjectComm((PetscObject)ts),&viewer);
2038:   }

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

2107:     PetscObjectGetComm((PetscObject)ts,&comm);
2108:     MPI_Comm_rank(comm,&rank);
2109:     if (rank == 0) {
2110:       PetscViewerBinaryWrite(viewer,&classid,1,PETSC_INT);
2111:       PetscStrncpy(type,((PetscObject)ts)->type_name,256);
2112:       PetscViewerBinaryWrite(viewer,type,256,PETSC_CHAR);
2113:     }
2114:     if (ts->ops->view) {
2115:       (*ts->ops->view)(ts,viewer);
2116:     }
2117:     if (ts->adapt) {TSAdaptView(ts->adapt,viewer);}
2118:     DMView(ts->dm,viewer);
2119:     VecView(ts->vec_sol,viewer);
2120:     DMGetDMTS(ts->dm,&sdm);
2121:     DMTSView(sdm,viewer);
2122:   } else if (isdraw) {
2123:     PetscDraw draw;
2124:     char      str[36];
2125:     PetscReal x,y,bottom,h;

2127:     PetscViewerDrawGetDraw(viewer,0,&draw);
2128:     PetscDrawGetCurrentPoint(draw,&x,&y);
2129:     PetscStrcpy(str,"TS: ");
2130:     PetscStrcat(str,((PetscObject)ts)->type_name);
2131:     PetscDrawStringBoxed(draw,x,y,PETSC_DRAW_BLACK,PETSC_DRAW_BLACK,str,NULL,&h);
2132:     bottom = y - h;
2133:     PetscDrawPushCurrentPoint(draw,x,bottom);
2134:     if (ts->ops->view) {
2135:       (*ts->ops->view)(ts,viewer);
2136:     }
2137:     if (ts->adapt) {TSAdaptView(ts->adapt,viewer);}
2138:     if (ts->snes)  {SNESView(ts->snes,viewer);}
2139:     PetscDrawPopCurrentPoint(draw);
2140: #if defined(PETSC_HAVE_SAWS)
2141:   } else if (issaws) {
2142:     PetscMPIInt rank;
2143:     const char  *name;

2145:     PetscObjectGetName((PetscObject)ts,&name);
2146:     MPI_Comm_rank(PETSC_COMM_WORLD,&rank);
2147:     if (!((PetscObject)ts)->amsmem && rank == 0) {
2148:       char       dir[1024];

2150:       PetscObjectViewSAWs((PetscObject)ts,viewer);
2151:       PetscSNPrintf(dir,1024,"/PETSc/Objects/%s/time_step",name);
2152:       PetscStackCallSAWs(SAWs_Register,(dir,&ts->steps,1,SAWs_READ,SAWs_INT));
2153:       PetscSNPrintf(dir,1024,"/PETSc/Objects/%s/time",name);
2154:       PetscStackCallSAWs(SAWs_Register,(dir,&ts->ptime,1,SAWs_READ,SAWs_DOUBLE));
2155:     }
2156:     if (ts->ops->view) {
2157:       (*ts->ops->view)(ts,viewer);
2158:     }
2159: #endif
2160:   }
2161:   if (ts->snes && ts->usessnes)  {
2162:     PetscViewerASCIIPushTab(viewer);
2163:     SNESView(ts->snes,viewer);
2164:     PetscViewerASCIIPopTab(viewer);
2165:   }
2166:   DMGetDMTS(ts->dm,&sdm);
2167:   DMTSView(sdm,viewer);

2169:   PetscViewerASCIIPushTab(viewer);
2170:   PetscObjectTypeCompare((PetscObject)ts,TSSUNDIALS,&isundials);
2171:   PetscViewerASCIIPopTab(viewer);
2172:   return(0);
2173: }

2175: /*@
2176:    TSSetApplicationContext - Sets an optional user-defined context for
2177:    the timesteppers.

2179:    Logically Collective on TS

2181:    Input Parameters:
2182: +  ts - the TS context obtained from TSCreate()
2183: -  usrP - optional user context

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

2189:    Level: intermediate

2191: .seealso: TSGetApplicationContext()
2192: @*/
2193: PetscErrorCode  TSSetApplicationContext(TS ts,void *usrP)
2194: {
2197:   ts->user = usrP;
2198:   return(0);
2199: }

2201: /*@
2202:     TSGetApplicationContext - Gets the user-defined context for the
2203:     timestepper.

2205:     Not Collective

2207:     Input Parameter:
2208: .   ts - the TS context obtained from TSCreate()

2210:     Output Parameter:
2211: .   usrP - user context

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

2217:     Level: intermediate

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

2229: /*@
2230:    TSGetStepNumber - Gets the number of steps completed.

2232:    Not Collective

2234:    Input Parameter:
2235: .  ts - the TS context obtained from TSCreate()

2237:    Output Parameter:
2238: .  steps - number of steps completed so far

2240:    Level: intermediate

2242: .seealso: TSGetTime(), TSGetTimeStep(), TSSetPreStep(), TSSetPreStage(), TSSetPostStage(), TSSetPostStep()
2243: @*/
2244: PetscErrorCode TSGetStepNumber(TS ts,PetscInt *steps)
2245: {
2249:   *steps = ts->steps;
2250:   return(0);
2251: }

2253: /*@
2254:    TSSetStepNumber - Sets the number of steps completed.

2256:    Logically Collective on TS

2258:    Input Parameters:
2259: +  ts - the TS context
2260: -  steps - number of steps completed so far

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

2272:    Level: advanced

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

2286: /*@
2287:    TSSetTimeStep - Allows one to reset the timestep at any time,
2288:    useful for simple pseudo-timestepping codes.

2290:    Logically Collective on TS

2292:    Input Parameters:
2293: +  ts - the TS context obtained from TSCreate()
2294: -  time_step - the size of the timestep

2296:    Level: intermediate

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

2300: @*/
2301: PetscErrorCode  TSSetTimeStep(TS ts,PetscReal time_step)
2302: {
2306:   ts->time_step = time_step;
2307:   return(0);
2308: }

2310: /*@
2311:    TSSetExactFinalTime - Determines whether to adapt the final time step to
2312:      match the exact final time, interpolate solution to the exact final time,
2313:      or just return at the final time TS computed.

2315:   Logically Collective on TS

2317:    Input Parameters:
2318: +   ts - the time-step context
2319: -   eftopt - exact final time option

2321: $  TS_EXACTFINALTIME_STEPOVER    - Don't do anything if final time is exceeded
2322: $  TS_EXACTFINALTIME_INTERPOLATE - Interpolate back to final time
2323: $  TS_EXACTFINALTIME_MATCHSTEP - Adapt final time step to match the final time

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

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

2331:    Level: beginner

2333: .seealso: TSExactFinalTimeOption, TSGetExactFinalTime()
2334: @*/
2335: PetscErrorCode TSSetExactFinalTime(TS ts,TSExactFinalTimeOption eftopt)
2336: {
2340:   ts->exact_final_time = eftopt;
2341:   return(0);
2342: }

2344: /*@
2345:    TSGetExactFinalTime - Gets the exact final time option.

2347:    Not Collective

2349:    Input Parameter:
2350: .  ts - the TS context

2352:    Output Parameter:
2353: .  eftopt - exact final time option

2355:    Level: beginner

2357: .seealso: TSExactFinalTimeOption, TSSetExactFinalTime()
2358: @*/
2359: PetscErrorCode TSGetExactFinalTime(TS ts,TSExactFinalTimeOption *eftopt)
2360: {
2364:   *eftopt = ts->exact_final_time;
2365:   return(0);
2366: }

2368: /*@
2369:    TSGetTimeStep - Gets the current timestep size.

2371:    Not Collective

2373:    Input Parameter:
2374: .  ts - the TS context obtained from TSCreate()

2376:    Output Parameter:
2377: .  dt - the current timestep size

2379:    Level: intermediate

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

2383: @*/
2384: PetscErrorCode  TSGetTimeStep(TS ts,PetscReal *dt)
2385: {
2389:   *dt = ts->time_step;
2390:   return(0);
2391: }

2393: /*@
2394:    TSGetSolution - Returns the solution at the present timestep. It
2395:    is valid to call this routine inside the function that you are evaluating
2396:    in order to move to the new timestep. This vector not changed until
2397:    the solution at the next timestep has been calculated.

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

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

2404:    Output Parameter:
2405: .  v - the vector containing the solution

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

2410:    Level: intermediate

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

2414: @*/
2415: PetscErrorCode  TSGetSolution(TS ts,Vec *v)
2416: {
2420:   *v = ts->vec_sol;
2421:   return(0);
2422: }

2424: /*@
2425:    TSGetSolutionComponents - Returns any solution components at the present
2426:    timestep, if available for the time integration method being used.
2427:    Solution components are quantities that share the same size and
2428:    structure as the solution vector.

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

2432:    Parameters :
2433: +  ts - the TS context obtained from TSCreate() (input parameter).
2434: .  n - If v is PETSC_NULL, then the number of solution components is
2435:        returned through n, else the n-th solution component is
2436:        returned in v.
2437: -  v - the vector containing the n-th solution component
2438:        (may be PETSC_NULL to use this function to find out
2439:         the number of solutions components).

2441:    Level: advanced

2443: .seealso: TSGetSolution()

2445: @*/
2446: PetscErrorCode  TSGetSolutionComponents(TS ts,PetscInt *n,Vec *v)
2447: {

2452:   if (!ts->ops->getsolutioncomponents) *n = 0;
2453:   else {
2454:     (*ts->ops->getsolutioncomponents)(ts,n,v);
2455:   }
2456:   return(0);
2457: }

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

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

2465:    Parameters :
2466: +  ts - the TS context obtained from TSCreate() (input parameter).
2467: -  v - the vector containing the auxiliary solution

2469:    Level: intermediate

2471: .seealso: TSGetSolution()

2473: @*/
2474: PetscErrorCode  TSGetAuxSolution(TS ts,Vec *v)
2475: {

2480:   if (ts->ops->getauxsolution) {
2481:     (*ts->ops->getauxsolution)(ts,v);
2482:   } else {
2483:     VecZeroEntries(*v);
2484:   }
2485:   return(0);
2486: }

2488: /*@
2489:    TSGetTimeError - Returns the estimated error vector, if the chosen
2490:    TSType has an error estimation functionality.

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

2494:    Note: MUST call after TSSetUp()

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

2501:    Level: intermediate

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

2505: @*/
2506: PetscErrorCode  TSGetTimeError(TS ts,PetscInt n,Vec *v)
2507: {

2512:   if (ts->ops->gettimeerror) {
2513:     (*ts->ops->gettimeerror)(ts,n,v);
2514:   } else {
2515:     VecZeroEntries(*v);
2516:   }
2517:   return(0);
2518: }

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

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

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

2531:    Level: intermediate

2533: .seealso: TSSetSolution(), TSGetTimeError)

2535: @*/
2536: PetscErrorCode  TSSetTimeError(TS ts,Vec v)
2537: {

2542:   if (!ts->setupcalled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Must call TSSetUp() first");
2543:   if (ts->ops->settimeerror) {
2544:     (*ts->ops->settimeerror)(ts,v);
2545:   }
2546:   return(0);
2547: }

2549: /* ----- Routines to initialize and destroy a timestepper ---- */
2550: /*@
2551:   TSSetProblemType - Sets the type of problem to be solved.

2553:   Not collective

2555:   Input Parameters:
2556: + ts   - The TS
2557: - type - One of TS_LINEAR, TS_NONLINEAR where these types refer to problems of the forms
2558: .vb
2559:          U_t - A U = 0      (linear)
2560:          U_t - A(t) U = 0   (linear)
2561:          F(t,U,U_t) = 0     (nonlinear)
2562: .ve

2564:    Level: beginner

2566: .seealso: TSSetUp(), TSProblemType, TS
2567: @*/
2568: PetscErrorCode  TSSetProblemType(TS ts, TSProblemType type)
2569: {

2574:   ts->problem_type = type;
2575:   if (type == TS_LINEAR) {
2576:     SNES snes;
2577:     TSGetSNES(ts,&snes);
2578:     SNESSetType(snes,SNESKSPONLY);
2579:   }
2580:   return(0);
2581: }

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

2586:   Not collective

2588:   Input Parameter:
2589: . ts   - The TS

2591:   Output Parameter:
2592: . type - One of TS_LINEAR, TS_NONLINEAR where these types refer to problems of the forms
2593: .vb
2594:          M U_t = A U
2595:          M(t) U_t = A(t) U
2596:          F(t,U,U_t)
2597: .ve

2599:    Level: beginner

2601: .seealso: TSSetUp(), TSProblemType, TS
2602: @*/
2603: PetscErrorCode  TSGetProblemType(TS ts, TSProblemType *type)
2604: {
2608:   *type = ts->problem_type;
2609:   return(0);
2610: }

2612: /*
2613:     Attempt to check/preset a default value for the exact final time option. This is needed at the beginning of TSSolve() and in TSSetUp()
2614: */
2615: static PetscErrorCode TSSetExactFinalTimeDefault(TS ts)
2616: {
2618:   PetscBool      isnone;

2621:   TSGetAdapt(ts,&ts->adapt);
2622:   TSAdaptSetDefaultType(ts->adapt,ts->default_adapt_type);

2624:   PetscObjectTypeCompare((PetscObject)ts->adapt,TSADAPTNONE,&isnone);
2625:   if (!isnone && ts->exact_final_time == TS_EXACTFINALTIME_UNSPECIFIED) {
2626:     ts->exact_final_time = TS_EXACTFINALTIME_MATCHSTEP;
2627:   } else if (ts->exact_final_time == TS_EXACTFINALTIME_UNSPECIFIED) {
2628:     ts->exact_final_time = TS_EXACTFINALTIME_INTERPOLATE;
2629:   }
2630:   return(0);
2631: }

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

2636:    Collective on TS

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

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

2648:    Level: advanced

2650: .seealso: TSCreate(), TSStep(), TSDestroy(), TSSolve()
2651: @*/
2652: PetscErrorCode  TSSetUp(TS ts)
2653: {
2655:   DM             dm;
2656:   PetscErrorCode (*func)(SNES,Vec,Vec,void*);
2657:   PetscErrorCode (*jac)(SNES,Vec,Mat,Mat,void*);
2658:   TSIFunction    ifun;
2659:   TSIJacobian    ijac;
2660:   TSI2Jacobian   i2jac;
2661:   TSRHSJacobian  rhsjac;

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

2667:   if (!((PetscObject)ts)->type_name) {
2668:     TSGetIFunction(ts,NULL,&ifun,NULL);
2669:     TSSetType(ts,ifun ? TSBEULER : TSEULER);
2670:   }

2672:   if (!ts->vec_sol) {
2673:     if (ts->dm) {
2674:       DMCreateGlobalVector(ts->dm,&ts->vec_sol);
2675:     } else SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Must call TSSetSolution() first");
2676:   }

2678:   if (!ts->Jacp && ts->Jacprhs) { /* IJacobianP shares the same matrix with RHSJacobianP if only RHSJacobianP is provided */
2679:     PetscObjectReference((PetscObject)ts->Jacprhs);
2680:     ts->Jacp = ts->Jacprhs;
2681:   }

2683:   if (ts->quadraturets) {
2684:     TSSetUp(ts->quadraturets);
2685:     VecDestroy(&ts->vec_costintegrand);
2686:     VecDuplicate(ts->quadraturets->vec_sol,&ts->vec_costintegrand);
2687:   }

2689:   TSGetRHSJacobian(ts,NULL,NULL,&rhsjac,NULL);
2690:   if (rhsjac == TSComputeRHSJacobianConstant) {
2691:     Mat Amat,Pmat;
2692:     SNES snes;
2693:     TSGetSNES(ts,&snes);
2694:     SNESGetJacobian(snes,&Amat,&Pmat,NULL,NULL);
2695:     /* Matching matrices implies that an IJacobian is NOT set, because if it had been set, the IJacobian's matrix would
2696:      * have displaced the RHS matrix */
2697:     if (Amat && Amat == ts->Arhs) {
2698:       /* 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 */
2699:       MatDuplicate(ts->Arhs,MAT_COPY_VALUES,&Amat);
2700:       SNESSetJacobian(snes,Amat,NULL,NULL,NULL);
2701:       MatDestroy(&Amat);
2702:     }
2703:     if (Pmat && Pmat == ts->Brhs) {
2704:       MatDuplicate(ts->Brhs,MAT_COPY_VALUES,&Pmat);
2705:       SNESSetJacobian(snes,NULL,Pmat,NULL,NULL);
2706:       MatDestroy(&Pmat);
2707:     }
2708:   }

2710:   TSGetAdapt(ts,&ts->adapt);
2711:   TSAdaptSetDefaultType(ts->adapt,ts->default_adapt_type);

2713:   if (ts->ops->setup) {
2714:     (*ts->ops->setup)(ts);
2715:   }

2717:   TSSetExactFinalTimeDefault(ts);

2719:   /* In the case where we've set a DMTSFunction or what have you, we need the default SNESFunction
2720:      to be set right but can't do it elsewhere due to the overreliance on ctx=ts.
2721:    */
2722:   TSGetDM(ts,&dm);
2723:   DMSNESGetFunction(dm,&func,NULL);
2724:   if (!func) {
2725:     DMSNESSetFunction(dm,SNESTSFormFunction,ts);
2726:   }
2727:   /* If the SNES doesn't have a jacobian set and the TS has an ijacobian or rhsjacobian set, set the SNES to use it.
2728:      Otherwise, the SNES will use coloring internally to form the Jacobian.
2729:    */
2730:   DMSNESGetJacobian(dm,&jac,NULL);
2731:   DMTSGetIJacobian(dm,&ijac,NULL);
2732:   DMTSGetI2Jacobian(dm,&i2jac,NULL);
2733:   DMTSGetRHSJacobian(dm,&rhsjac,NULL);
2734:   if (!jac && (ijac || i2jac || rhsjac)) {
2735:     DMSNESSetJacobian(dm,SNESTSFormJacobian,ts);
2736:   }

2738:   /* if time integration scheme has a starting method, call it */
2739:   if (ts->ops->startingmethod) {
2740:     (*ts->ops->startingmethod)(ts);
2741:   }

2743:   ts->setupcalled = PETSC_TRUE;
2744:   return(0);
2745: }

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

2750:    Collective on TS

2752:    Input Parameter:
2753: .  ts - the TS context obtained from TSCreate()

2755:    Level: beginner

2757: .seealso: TSCreate(), TSSetup(), TSDestroy()
2758: @*/
2759: PetscErrorCode  TSReset(TS ts)
2760: {
2761:   TS_RHSSplitLink ilink = ts->tsrhssplit,next;
2762:   PetscErrorCode  ierr;


2767:   if (ts->ops->reset) {
2768:     (*ts->ops->reset)(ts);
2769:   }
2770:   if (ts->snes) {SNESReset(ts->snes);}
2771:   if (ts->adapt) {TSAdaptReset(ts->adapt);}

2773:   MatDestroy(&ts->Arhs);
2774:   MatDestroy(&ts->Brhs);
2775:   VecDestroy(&ts->Frhs);
2776:   VecDestroy(&ts->vec_sol);
2777:   VecDestroy(&ts->vec_dot);
2778:   VecDestroy(&ts->vatol);
2779:   VecDestroy(&ts->vrtol);
2780:   VecDestroyVecs(ts->nwork,&ts->work);

2782:   MatDestroy(&ts->Jacprhs);
2783:   MatDestroy(&ts->Jacp);
2784:   if (ts->forward_solve) {
2785:     TSForwardReset(ts);
2786:   }
2787:   if (ts->quadraturets) {
2788:     TSReset(ts->quadraturets);
2789:     VecDestroy(&ts->vec_costintegrand);
2790:   }
2791:   while (ilink) {
2792:     next = ilink->next;
2793:     TSDestroy(&ilink->ts);
2794:     PetscFree(ilink->splitname);
2795:     ISDestroy(&ilink->is);
2796:     PetscFree(ilink);
2797:     ilink = next;
2798:   }
2799:   ts->num_rhs_splits = 0;
2800:   ts->setupcalled = PETSC_FALSE;
2801:   return(0);
2802: }

2804: /*@C
2805:    TSDestroy - Destroys the timestepper context that was created
2806:    with TSCreate().

2808:    Collective on TS

2810:    Input Parameter:
2811: .  ts - the TS context obtained from TSCreate()

2813:    Level: beginner

2815: .seealso: TSCreate(), TSSetUp(), TSSolve()
2816: @*/
2817: PetscErrorCode  TSDestroy(TS *ts)
2818: {

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

2826:   TSReset(*ts);
2827:   TSAdjointReset(*ts);
2828:   if ((*ts)->forward_solve) {
2829:     TSForwardReset(*ts);
2830:   }
2831:   /* if memory was published with SAWs then destroy it */
2832:   PetscObjectSAWsViewOff((PetscObject)*ts);
2833:   if ((*ts)->ops->destroy) {(*(*ts)->ops->destroy)((*ts));}

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

2837:   TSAdaptDestroy(&(*ts)->adapt);
2838:   TSEventDestroy(&(*ts)->event);

2840:   SNESDestroy(&(*ts)->snes);
2841:   DMDestroy(&(*ts)->dm);
2842:   TSMonitorCancel((*ts));
2843:   TSAdjointMonitorCancel((*ts));

2845:   TSDestroy(&(*ts)->quadraturets);
2846:   PetscHeaderDestroy(ts);
2847:   return(0);
2848: }

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

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

2856:    Input Parameter:
2857: .  ts - the TS context obtained from TSCreate()

2859:    Output Parameter:
2860: .  snes - the nonlinear solver context

2862:    Notes:
2863:    The user can then directly manipulate the SNES context to set various
2864:    options, etc.  Likewise, the user can then extract and manipulate the
2865:    KSP, KSP, and PC contexts as well.

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

2870:    Level: beginner

2872: @*/
2873: PetscErrorCode  TSGetSNES(TS ts,SNES *snes)
2874: {

2880:   if (!ts->snes) {
2881:     SNESCreate(PetscObjectComm((PetscObject)ts),&ts->snes);
2882:     PetscObjectSetOptions((PetscObject)ts->snes,((PetscObject)ts)->options);
2883:     SNESSetFunction(ts->snes,NULL,SNESTSFormFunction,ts);
2884:     PetscLogObjectParent((PetscObject)ts,(PetscObject)ts->snes);
2885:     PetscObjectIncrementTabLevel((PetscObject)ts->snes,(PetscObject)ts,1);
2886:     if (ts->dm) {SNESSetDM(ts->snes,ts->dm);}
2887:     if (ts->problem_type == TS_LINEAR) {
2888:       SNESSetType(ts->snes,SNESKSPONLY);
2889:     }
2890:   }
2891:   *snes = ts->snes;
2892:   return(0);
2893: }

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

2898:    Collective

2900:    Input Parameters:
2901: +  ts - the TS context obtained from TSCreate()
2902: -  snes - the nonlinear solver context

2904:    Notes:
2905:    Most users should have the TS created by calling TSGetSNES()

2907:    Level: developer

2909: @*/
2910: PetscErrorCode TSSetSNES(TS ts,SNES snes)
2911: {
2913:   PetscErrorCode (*func)(SNES,Vec,Mat,Mat,void*);

2918:   PetscObjectReference((PetscObject)snes);
2919:   SNESDestroy(&ts->snes);

2921:   ts->snes = snes;

2923:   SNESSetFunction(ts->snes,NULL,SNESTSFormFunction,ts);
2924:   SNESGetJacobian(ts->snes,NULL,NULL,&func,NULL);
2925:   if (func == SNESTSFormJacobian) {
2926:     SNESSetJacobian(ts->snes,NULL,NULL,SNESTSFormJacobian,ts);
2927:   }
2928:   return(0);
2929: }

2931: /*@
2932:    TSGetKSP - Returns the KSP (linear solver) associated with
2933:    a TS (timestepper) context.

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

2937:    Input Parameter:
2938: .  ts - the TS context obtained from TSCreate()

2940:    Output Parameter:
2941: .  ksp - the nonlinear solver context

2943:    Notes:
2944:    The user can then directly manipulate the KSP context to set various
2945:    options, etc.  Likewise, the user can then extract and manipulate the
2946:    KSP and PC contexts as well.

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

2951:    Level: beginner

2953: @*/
2954: PetscErrorCode  TSGetKSP(TS ts,KSP *ksp)
2955: {
2957:   SNES           snes;

2962:   if (!((PetscObject)ts)->type_name) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_NULL,"KSP is not created yet. Call TSSetType() first");
2963:   if (ts->problem_type != TS_LINEAR) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,"Linear only; use TSGetSNES()");
2964:   TSGetSNES(ts,&snes);
2965:   SNESGetKSP(snes,ksp);
2966:   return(0);
2967: }

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

2971: /*@
2972:    TSSetMaxSteps - Sets the maximum number of steps to use.

2974:    Logically Collective on TS

2976:    Input Parameters:
2977: +  ts - the TS context obtained from TSCreate()
2978: -  maxsteps - maximum number of steps to use

2980:    Options Database Keys:
2981: .  -ts_max_steps <maxsteps> - Sets maxsteps

2983:    Notes:
2984:    The default maximum number of steps is 5000

2986:    Level: intermediate

2988: .seealso: TSGetMaxSteps(), TSSetMaxTime(), TSSetExactFinalTime()
2989: @*/
2990: PetscErrorCode TSSetMaxSteps(TS ts,PetscInt maxsteps)
2991: {
2995:   if (maxsteps < 0) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_ARG_OUTOFRANGE,"Maximum number of steps must be non-negative");
2996:   ts->max_steps = maxsteps;
2997:   return(0);
2998: }

3000: /*@
3001:    TSGetMaxSteps - Gets the maximum number of steps to use.

3003:    Not Collective

3005:    Input Parameters:
3006: .  ts - the TS context obtained from TSCreate()

3008:    Output Parameter:
3009: .  maxsteps - maximum number of steps to use

3011:    Level: advanced

3013: .seealso: TSSetMaxSteps(), TSGetMaxTime(), TSSetMaxTime()
3014: @*/
3015: PetscErrorCode TSGetMaxSteps(TS ts,PetscInt *maxsteps)
3016: {
3020:   *maxsteps = ts->max_steps;
3021:   return(0);
3022: }

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

3027:    Logically Collective on TS

3029:    Input Parameters:
3030: +  ts - the TS context obtained from TSCreate()
3031: -  maxtime - final time to step to

3033:    Options Database Keys:
3034: .  -ts_max_time <maxtime> - Sets maxtime

3036:    Notes:
3037:    The default maximum time is 5.0

3039:    Level: intermediate

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

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

3055:    Not Collective

3057:    Input Parameters:
3058: .  ts - the TS context obtained from TSCreate()

3060:    Output Parameter:
3061: .  maxtime - final time to step to

3063:    Level: advanced

3065: .seealso: TSSetMaxTime(), TSGetMaxSteps(), TSSetMaxSteps()
3066: @*/
3067: PetscErrorCode TSGetMaxTime(TS ts,PetscReal *maxtime)
3068: {
3072:   *maxtime = ts->max_time;
3073:   return(0);
3074: }

3076: /*@
3077:    TSSetInitialTimeStep - Deprecated, use TSSetTime() and TSSetTimeStep().

3079:    Level: deprecated

3081: @*/
3082: PetscErrorCode  TSSetInitialTimeStep(TS ts,PetscReal initial_time,PetscReal time_step)
3083: {
3087:   TSSetTime(ts,initial_time);
3088:   TSSetTimeStep(ts,time_step);
3089:   return(0);
3090: }

3092: /*@
3093:    TSGetDuration - Deprecated, use TSGetMaxSteps() and TSGetMaxTime().

3095:    Level: deprecated

3097: @*/
3098: PetscErrorCode TSGetDuration(TS ts, PetscInt *maxsteps, PetscReal *maxtime)
3099: {
3102:   if (maxsteps) {
3104:     *maxsteps = ts->max_steps;
3105:   }
3106:   if (maxtime) {
3108:     *maxtime = ts->max_time;
3109:   }
3110:   return(0);
3111: }

3113: /*@
3114:    TSSetDuration - Deprecated, use TSSetMaxSteps() and TSSetMaxTime().

3116:    Level: deprecated

3118: @*/
3119: PetscErrorCode TSSetDuration(TS ts,PetscInt maxsteps,PetscReal maxtime)
3120: {
3125:   if (maxsteps >= 0) ts->max_steps = maxsteps;
3126:   if (maxtime != PETSC_DEFAULT) ts->max_time = maxtime;
3127:   return(0);
3128: }

3130: /*@
3131:    TSGetTimeStepNumber - Deprecated, use TSGetStepNumber().

3133:    Level: deprecated

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

3138: /*@
3139:    TSGetTotalSteps - Deprecated, use TSGetStepNumber().

3141:    Level: deprecated

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

3146: /*@
3147:    TSSetSolution - Sets the initial solution vector
3148:    for use by the TS routines.

3150:    Logically Collective on TS

3152:    Input Parameters:
3153: +  ts - the TS context obtained from TSCreate()
3154: -  u - the solution vector

3156:    Level: beginner

3158: .seealso: TSSetSolutionFunction(), TSGetSolution(), TSCreate()
3159: @*/
3160: PetscErrorCode  TSSetSolution(TS ts,Vec u)
3161: {
3163:   DM             dm;

3168:   PetscObjectReference((PetscObject)u);
3169:   VecDestroy(&ts->vec_sol);
3170:   ts->vec_sol = u;

3172:   TSGetDM(ts,&dm);
3173:   DMShellSetGlobalVector(dm,u);
3174:   return(0);
3175: }

3177: /*@C
3178:   TSSetPreStep - Sets the general-purpose function
3179:   called once at the beginning of each time step.

3181:   Logically Collective on TS

3183:   Input Parameters:
3184: + ts   - The TS context obtained from TSCreate()
3185: - func - The function

3187:   Calling sequence of func:
3188: .   PetscErrorCode func (TS ts);

3190:   Level: intermediate

3192: .seealso: TSSetPreStage(), TSSetPostStage(), TSSetPostStep(), TSStep(), TSRestartStep()
3193: @*/
3194: PetscErrorCode  TSSetPreStep(TS ts, PetscErrorCode (*func)(TS))
3195: {
3198:   ts->prestep = func;
3199:   return(0);
3200: }

3202: /*@
3203:   TSPreStep - Runs the user-defined pre-step function.

3205:   Collective on TS

3207:   Input Parameters:
3208: . ts   - The TS context obtained from TSCreate()

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

3214:   Level: developer

3216: .seealso: TSSetPreStep(), TSPreStage(), TSPostStage(), TSPostStep()
3217: @*/
3218: PetscErrorCode  TSPreStep(TS ts)
3219: {

3224:   if (ts->prestep) {
3225:     Vec              U;
3226:     PetscObjectState sprev,spost;

3228:     TSGetSolution(ts,&U);
3229:     PetscObjectStateGet((PetscObject)U,&sprev);
3230:     PetscStackCallStandard((*ts->prestep),(ts));
3231:     PetscObjectStateGet((PetscObject)U,&spost);
3232:     if (sprev != spost) {TSRestartStep(ts);}
3233:   }
3234:   return(0);
3235: }

3237: /*@C
3238:   TSSetPreStage - Sets the general-purpose function
3239:   called once at the beginning of each stage.

3241:   Logically Collective on TS

3243:   Input Parameters:
3244: + ts   - The TS context obtained from TSCreate()
3245: - func - The function

3247:   Calling sequence of func:
3248: .    PetscErrorCode func(TS ts, PetscReal stagetime);

3250:   Level: intermediate

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

3257: .seealso: TSSetPostStage(), TSSetPreStep(), TSSetPostStep(), TSGetApplicationContext()
3258: @*/
3259: PetscErrorCode  TSSetPreStage(TS ts, PetscErrorCode (*func)(TS,PetscReal))
3260: {
3263:   ts->prestage = func;
3264:   return(0);
3265: }

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

3271:   Logically Collective on TS

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

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

3280:   Level: intermediate

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

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

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

3301:   Logically Collective on TS

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

3307:   Calling sequence of func:
3308: . PetscErrorCode func(TS ts);

3310:   Level: intermediate

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

3319: .seealso: TSSetPreStage(), TSSetPreStep(), TSSetPostStep(), TSGetApplicationContext()
3320: @*/
3321: PetscErrorCode  TSSetPostEvaluate(TS ts, PetscErrorCode (*func)(TS))
3322: {
3325:   ts->postevaluate = func;
3326:   return(0);
3327: }

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

3332:   Collective on TS

3334:   Input Parameters:
3335: . ts          - The TS context obtained from TSCreate()
3336:   stagetime   - The absolute time of the current stage

3338:   Notes:
3339:   TSPreStage() is typically used within time stepping implementations,
3340:   most users would not generally call this routine themselves.

3342:   Level: developer

3344: .seealso: TSPostStage(), TSSetPreStep(), TSPreStep(), TSPostStep()
3345: @*/
3346: PetscErrorCode  TSPreStage(TS ts, PetscReal stagetime)
3347: {
3350:   if (ts->prestage) {
3351:     PetscStackCallStandard((*ts->prestage),(ts,stagetime));
3352:   }
3353:   return(0);
3354: }

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

3359:   Collective on TS

3361:   Input Parameters:
3362: . ts          - The TS context obtained from TSCreate()
3363:   stagetime   - The absolute time of the current stage
3364:   stageindex  - Stage number
3365:   Y           - Array of vectors (of size = total number
3366:                 of stages) with the stage solutions

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

3372:   Level: developer

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

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

3389:   Collective on TS

3391:   Input Parameters:
3392: . ts          - The TS context obtained from TSCreate()

3394:   Notes:
3395:   TSPostEvaluate() is typically used within time stepping implementations,
3396:   most users would not generally call this routine themselves.

3398:   Level: developer

3400: .seealso: TSSetPostEvaluate(), TSSetPreStep(), TSPreStep(), TSPostStep()
3401: @*/
3402: PetscErrorCode  TSPostEvaluate(TS ts)
3403: {

3408:   if (ts->postevaluate) {
3409:     Vec              U;
3410:     PetscObjectState sprev,spost;

3412:     TSGetSolution(ts,&U);
3413:     PetscObjectStateGet((PetscObject)U,&sprev);
3414:     PetscStackCallStandard((*ts->postevaluate),(ts));
3415:     PetscObjectStateGet((PetscObject)U,&spost);
3416:     if (sprev != spost) {TSRestartStep(ts);}
3417:   }
3418:   return(0);
3419: }

3421: /*@C
3422:   TSSetPostStep - Sets the general-purpose function
3423:   called once at the end of each time step.

3425:   Logically Collective on TS

3427:   Input Parameters:
3428: + ts   - The TS context obtained from TSCreate()
3429: - func - The function

3431:   Calling sequence of func:
3432: $ func (TS ts);

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

3439:   Level: intermediate

3441: .seealso: TSSetPreStep(), TSSetPreStage(), TSSetPostEvaluate(), TSGetTimeStep(), TSGetStepNumber(), TSGetTime(), TSRestartStep()
3442: @*/
3443: PetscErrorCode  TSSetPostStep(TS ts, PetscErrorCode (*func)(TS))
3444: {
3447:   ts->poststep = func;
3448:   return(0);
3449: }

3451: /*@
3452:   TSPostStep - Runs the user-defined post-step function.

3454:   Collective on TS

3456:   Input Parameters:
3457: . ts   - The TS context obtained from TSCreate()

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

3463:   Level: developer

3465: @*/
3466: PetscErrorCode  TSPostStep(TS ts)
3467: {

3472:   if (ts->poststep) {
3473:     Vec              U;
3474:     PetscObjectState sprev,spost;

3476:     TSGetSolution(ts,&U);
3477:     PetscObjectStateGet((PetscObject)U,&sprev);
3478:     PetscStackCallStandard((*ts->poststep),(ts));
3479:     PetscObjectStateGet((PetscObject)U,&spost);
3480:     if (sprev != spost) {TSRestartStep(ts);}
3481:   }
3482:   return(0);
3483: }

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

3488:    Collective on TS

3490:    Input Parameters:
3491: +  ts - time stepping context
3492: -  t - time to interpolate to

3494:    Output Parameter:
3495: .  U - state at given time

3497:    Level: intermediate

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

3502: .seealso: TSSetExactFinalTime(), TSSolve()
3503: @*/
3504: PetscErrorCode TSInterpolate(TS ts,PetscReal t,Vec U)
3505: {

3511:   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);
3512:   if (!ts->ops->interpolate) SETERRQ1(PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"%s does not provide interpolation",((PetscObject)ts)->type_name);
3513:   (*ts->ops->interpolate)(ts,t,U);
3514:   return(0);
3515: }

3517: /*@
3518:    TSStep - Steps one time step

3520:    Collective on TS

3522:    Input Parameter:
3523: .  ts - the TS context obtained from TSCreate()

3525:    Level: developer

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

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

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

3536: .seealso: TSCreate(), TSSetUp(), TSDestroy(), TSSolve(), TSSetPreStep(), TSSetPreStage(), TSSetPostStage(), TSInterpolate()
3537: @*/
3538: PetscErrorCode  TSStep(TS ts)
3539: {
3540:   PetscErrorCode   ierr;
3541:   static PetscBool cite = PETSC_FALSE;
3542:   PetscReal        ptime;

3546:   PetscCitationsRegister("@article{tspaper,\n"
3547:                                 "  title         = {{PETSc/TS}: A Modern Scalable {DAE/ODE} Solver Library},\n"
3548:                                 "  author        = {Abhyankar, Shrirang and Brown, Jed and Constantinescu, Emil and Ghosh, Debojyoti and Smith, Barry F. and Zhang, Hong},\n"
3549:                                 "  journal       = {arXiv e-preprints},\n"
3550:                                 "  eprint        = {1806.01437},\n"
3551:                                 "  archivePrefix = {arXiv},\n"
3552:                                 "  year          = {2018}\n}\n",&cite);

3554:   TSSetUp(ts);
3555:   TSTrajectorySetUp(ts->trajectory,ts);

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

3562:   if (!ts->steps) ts->ptime_prev = ts->ptime;
3563:   ptime = ts->ptime; ts->ptime_prev_rollback = ts->ptime_prev;
3564:   ts->reason = TS_CONVERGED_ITERATING;

3566:   PetscLogEventBegin(TS_Step,ts,0,0,0);
3567:   (*ts->ops->step)(ts);
3568:   PetscLogEventEnd(TS_Step,ts,0,0,0);

3570:   if (ts->reason >= 0) {
3571:     ts->ptime_prev = ptime;
3572:     ts->steps++;
3573:     ts->steprollback = PETSC_FALSE;
3574:     ts->steprestart  = PETSC_FALSE;
3575:   }

3577:   if (!ts->reason) {
3578:     if (ts->steps >= ts->max_steps) ts->reason = TS_CONVERGED_ITS;
3579:     else if (ts->ptime >= ts->max_time) ts->reason = TS_CONVERGED_TIME;
3580:   }

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

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

3591:    Collective on TS

3593:    Input Parameters:
3594: +  ts - time stepping context
3595: -  wnormtype - norm type, either NORM_2 or NORM_INFINITY

3597:    Input/Output Parameter:
3598: .  order - optional, desired order for the error evaluation or PETSC_DECIDE;
3599:            on output, the actual order of the error evaluation

3601:    Output Parameter:
3602: .  wlte - the weighted local truncation error norm

3604:    Level: advanced

3606:    Notes:
3607:    If the timestepper cannot evaluate the error in a particular step
3608:    (eg. in the first step or restart steps after event handling),
3609:    this routine returns wlte=-1.0 .

3611: .seealso: TSStep(), TSAdapt, TSErrorWeightedNorm()
3612: @*/
3613: PetscErrorCode TSEvaluateWLTE(TS ts,NormType wnormtype,PetscInt *order,PetscReal *wlte)
3614: {

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

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

3633:    Collective on TS

3635:    Input Parameters:
3636: +  ts - time stepping context
3637: .  order - desired order of accuracy
3638: -  done - whether the step was evaluated at this order (pass NULL to generate an error if not available)

3640:    Output Parameter:
3641: .  U - state at the end of the current step

3643:    Level: advanced

3645:    Notes:
3646:    This function cannot be called until all stages have been evaluated.
3647:    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.

3649: .seealso: TSStep(), TSAdapt
3650: @*/
3651: PetscErrorCode TSEvaluateStep(TS ts,PetscInt order,Vec U,PetscBool *done)
3652: {

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

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

3667:   Not collective

3669:   Input Parameter:
3670: . ts        - time stepping context

3672:   Output Parameter:
3673: . initConditions - The function which computes an initial condition

3675:    Level: advanced

3677:    Notes:
3678:    The calling sequence for the function is
3679: $ initCondition(TS ts, Vec u)
3680: $ ts - The timestepping context
3681: $ u  - The input vector in which the initial condition is stored

3683: .seealso: TSSetComputeInitialCondition(), TSComputeInitialCondition()
3684: @*/
3685: PetscErrorCode TSGetComputeInitialCondition(TS ts, PetscErrorCode (**initCondition)(TS, Vec))
3686: {
3690:   *initCondition = ts->ops->initcondition;
3691:   return(0);
3692: }

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

3697:   Logically collective on ts

3699:   Input Parameters:
3700: + ts        - time stepping context
3701: - initCondition - The function which computes an initial condition

3703:   Level: advanced

3705:   Calling sequence for initCondition:
3706: $ PetscErrorCode initCondition(TS ts, Vec u)

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

3711: .seealso: TSGetComputeInitialCondition(), TSComputeInitialCondition()
3712: @*/
3713: PetscErrorCode TSSetComputeInitialCondition(TS ts, PetscErrorCode (*initCondition)(TS, Vec))
3714: {
3718:   ts->ops->initcondition = initCondition;
3719:   return(0);
3720: }

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

3725:   Collective on ts

3727:   Input Parameters:
3728: + ts - time stepping context
3729: - u  - The Vec to store the condition in which will be used in TSSolve()

3731:   Level: advanced

3733: .seealso: TSGetComputeInitialCondition(), TSSetComputeInitialCondition(), TSSolve()
3734: @*/
3735: PetscErrorCode TSComputeInitialCondition(TS ts, Vec u)
3736: {

3742:   if (ts->ops->initcondition) {(*ts->ops->initcondition)(ts, u);}
3743:   return(0);
3744: }

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

3749:   Not collective

3751:   Input Parameter:
3752: . ts         - time stepping context

3754:   Output Parameter:
3755: . exactError - The function which computes the solution error

3757:   Level: advanced

3759:   Calling sequence for exactError:
3760: $ PetscErrorCode exactError(TS ts, Vec u)

3762: + ts - The timestepping context
3763: . u  - The approximate solution vector
3764: - e  - The input vector in which the error is stored

3766: .seealso: TSGetComputeExactError(), TSComputeExactError()
3767: @*/
3768: PetscErrorCode TSGetComputeExactError(TS ts, PetscErrorCode (**exactError)(TS, Vec, Vec))
3769: {
3773:   *exactError = ts->ops->exacterror;
3774:   return(0);
3775: }

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

3780:   Logically collective on ts

3782:   Input Parameters:
3783: + ts         - time stepping context
3784: - exactError - The function which computes the solution error

3786:   Level: advanced

3788:   Calling sequence for exactError:
3789: $ PetscErrorCode exactError(TS ts, Vec u)

3791: + ts - The timestepping context
3792: . u  - The approximate solution vector
3793: - e  - The input vector in which the error is stored

3795: .seealso: TSGetComputeExactError(), TSComputeExactError()
3796: @*/
3797: PetscErrorCode TSSetComputeExactError(TS ts, PetscErrorCode (*exactError)(TS, Vec, Vec))
3798: {
3802:   ts->ops->exacterror = exactError;
3803:   return(0);
3804: }

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

3809:   Collective on ts

3811:   Input Parameters:
3812: + ts - time stepping context
3813: . u  - The approximate solution
3814: - e  - The Vec used to store the error

3816:   Level: advanced

3818: .seealso: TSGetComputeInitialCondition(), TSSetComputeInitialCondition(), TSSolve()
3819: @*/
3820: PetscErrorCode TSComputeExactError(TS ts, Vec u, Vec e)
3821: {

3828:   if (ts->ops->exacterror) {(*ts->ops->exacterror)(ts, u, e);}
3829:   return(0);
3830: }

3832: /*@
3833:    TSSolve - Steps the requested number of timesteps.

3835:    Collective on TS

3837:    Input Parameters:
3838: +  ts - the TS context obtained from TSCreate()
3839: -  u - the solution vector  (can be null if TSSetSolution() was used and TSSetExactFinalTime(ts,TS_EXACTFINALTIME_MATCHSTEP) was not used,
3840:                              otherwise must contain the initial conditions and will contain the solution at the final requested time

3842:    Level: beginner

3844:    Notes:
3845:    The final time returned by this function may be different from the time of the internally
3846:    held state accessible by TSGetSolution() and TSGetTime() because the method may have
3847:    stepped over the final time.

3849: .seealso: TSCreate(), TSSetSolution(), TSStep(), TSGetTime(), TSGetSolveTime()
3850: @*/
3851: PetscErrorCode TSSolve(TS ts,Vec u)
3852: {
3853:   Vec               solution;
3854:   PetscErrorCode    ierr;


3860:   TSSetExactFinalTimeDefault(ts);
3861:   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 */
3862:     if (!ts->vec_sol || u == ts->vec_sol) {
3863:       VecDuplicate(u,&solution);
3864:       TSSetSolution(ts,solution);
3865:       VecDestroy(&solution); /* grant ownership */
3866:     }
3867:     VecCopy(u,ts->vec_sol);
3868:     if (ts->forward_solve) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"Sensitivity analysis does not support the mode TS_EXACTFINALTIME_INTERPOLATE");
3869:   } else if (u) {
3870:     TSSetSolution(ts,u);
3871:   }
3872:   TSSetUp(ts);
3873:   TSTrajectorySetUp(ts->trajectory,ts);

3875:   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>");
3876:   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()");
3877:   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");

3879:   if (ts->forward_solve) {
3880:     TSForwardSetUp(ts);
3881:   }

3883:   /* reset number of steps only when the step is not restarted. ARKIMEX
3884:      restarts the step after an event. Resetting these counters in such case causes
3885:      TSTrajectory to incorrectly save the output files
3886:   */
3887:   /* reset time step and iteration counters */
3888:   if (!ts->steps) {
3889:     ts->ksp_its           = 0;
3890:     ts->snes_its          = 0;
3891:     ts->num_snes_failures = 0;
3892:     ts->reject            = 0;
3893:     ts->steprestart       = PETSC_TRUE;
3894:     ts->steprollback      = PETSC_FALSE;
3895:     ts->rhsjacobian.time  = PETSC_MIN_REAL;
3896:   }

3898:   /* make sure initial time step does not overshoot final time */
3899:   if (ts->exact_final_time == TS_EXACTFINALTIME_MATCHSTEP) {
3900:     PetscReal maxdt = ts->max_time-ts->ptime;
3901:     PetscReal dt = ts->time_step;

3903:     ts->time_step = dt >= maxdt ? maxdt : (PetscIsCloseAtTol(dt,maxdt,10*PETSC_MACHINE_EPSILON,0) ? maxdt : dt);
3904:   }
3905:   ts->reason = TS_CONVERGED_ITERATING;

3907:   {
3908:     PetscViewer       viewer;
3909:     PetscViewerFormat format;
3910:     PetscBool         flg;
3911:     static PetscBool  incall = PETSC_FALSE;

3913:     if (!incall) {
3914:       /* Estimate the convergence rate of the time discretization */
3915:       PetscOptionsGetViewer(PetscObjectComm((PetscObject) ts),((PetscObject)ts)->options, ((PetscObject) ts)->prefix, "-ts_convergence_estimate", &viewer, &format, &flg);
3916:       if (flg) {
3917:         PetscConvEst conv;
3918:         DM           dm;
3919:         PetscReal   *alpha; /* Convergence rate of the solution error for each field in the L_2 norm */
3920:         PetscInt     Nf;
3921:         PetscBool    checkTemporal = PETSC_TRUE;

3923:         incall = PETSC_TRUE;
3924:         PetscOptionsGetBool(((PetscObject)ts)->options, ((PetscObject) ts)->prefix, "-ts_convergence_temporal", &checkTemporal, &flg);
3925:         TSGetDM(ts, &dm);
3926:         DMGetNumFields(dm, &Nf);
3927:         PetscCalloc1(PetscMax(Nf, 1), &alpha);
3928:         PetscConvEstCreate(PetscObjectComm((PetscObject) ts), &conv);
3929:         PetscConvEstUseTS(conv, checkTemporal);
3930:         PetscConvEstSetSolver(conv, (PetscObject) ts);
3931:         PetscConvEstSetFromOptions(conv);
3932:         PetscConvEstSetUp(conv);
3933:         PetscConvEstGetConvRate(conv, alpha);
3934:         PetscViewerPushFormat(viewer, format);
3935:         PetscConvEstRateView(conv, alpha, viewer);
3936:         PetscViewerPopFormat(viewer);
3937:         PetscViewerDestroy(&viewer);
3938:         PetscConvEstDestroy(&conv);
3939:         PetscFree(alpha);
3940:         incall = PETSC_FALSE;
3941:       }
3942:     }
3943:   }

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

3947:   if (ts->ops->solve) { /* This private interface is transitional and should be removed when all implementations are updated. */
3948:     (*ts->ops->solve)(ts);
3949:     if (u) {VecCopy(ts->vec_sol,u);}
3950:     ts->solvetime = ts->ptime;
3951:     solution = ts->vec_sol;
3952:   } else { /* Step the requested number of timesteps. */
3953:     if (ts->steps >= ts->max_steps) ts->reason = TS_CONVERGED_ITS;
3954:     else if (ts->ptime >= ts->max_time) ts->reason = TS_CONVERGED_TIME;

3956:     if (!ts->steps) {
3957:       TSTrajectorySet(ts->trajectory,ts,ts->steps,ts->ptime,ts->vec_sol);
3958:       TSEventInitialize(ts->event,ts,ts->ptime,ts->vec_sol);
3959:     }

3961:     while (!ts->reason) {
3962:       TSMonitor(ts,ts->steps,ts->ptime,ts->vec_sol);
3963:       if (!ts->steprollback) {
3964:         TSPreStep(ts);
3965:       }
3966:       TSStep(ts);
3967:       if (ts->testjacobian) {
3968:         TSRHSJacobianTest(ts,NULL);
3969:       }
3970:       if (ts->testjacobiantranspose) {
3971:         TSRHSJacobianTestTranspose(ts,NULL);
3972:       }
3973:       if (ts->quadraturets && ts->costintegralfwd) { /* Must evaluate the cost integral before event is handled. The cost integral value can also be rolled back. */
3974:         if (ts->reason >= 0) ts->steps--; /* Revert the step number changed by TSStep() */
3975:         TSForwardCostIntegral(ts);
3976:         if (ts->reason >= 0) ts->steps++;
3977:       }
3978:       if (ts->forward_solve) { /* compute forward sensitivities before event handling because postevent() may change RHS and jump conditions may have to be applied */
3979:         if (ts->reason >= 0) ts->steps--; /* Revert the step number changed by TSStep() */
3980:         TSForwardStep(ts);
3981:         if (ts->reason >= 0) ts->steps++;
3982:       }
3983:       TSPostEvaluate(ts);
3984:       TSEventHandler(ts); /* The right-hand side may be changed due to event. Be careful with Any computation using the RHS information after this point. */
3985:       if (ts->steprollback) {
3986:         TSPostEvaluate(ts);
3987:       }
3988:       if (!ts->steprollback) {
3989:         TSTrajectorySet(ts->trajectory,ts,ts->steps,ts->ptime,ts->vec_sol);
3990:         TSPostStep(ts);
3991:       }
3992:     }
3993:     TSMonitor(ts,ts->steps,ts->ptime,ts->vec_sol);

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

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

4016: /*@
4017:    TSGetTime - Gets the time of the most recently completed step.

4019:    Not Collective

4021:    Input Parameter:
4022: .  ts - the TS context obtained from TSCreate()

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

4027:    Level: beginner

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

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

4035: @*/
4036: PetscErrorCode  TSGetTime(TS ts,PetscReal *t)
4037: {
4041:   *t = ts->ptime;
4042:   return(0);
4043: }

4045: /*@
4046:    TSGetPrevTime - Gets the starting time of the previously completed step.

4048:    Not Collective

4050:    Input Parameter:
4051: .  ts - the TS context obtained from TSCreate()

4053:    Output Parameter:
4054: .  t  - the previous time

4056:    Level: beginner

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

4060: @*/
4061: PetscErrorCode  TSGetPrevTime(TS ts,PetscReal *t)
4062: {
4066:   *t = ts->ptime_prev;
4067:   return(0);
4068: }

4070: /*@
4071:    TSSetTime - Allows one to reset the time.

4073:    Logically Collective on TS

4075:    Input Parameters:
4076: +  ts - the TS context obtained from TSCreate()
4077: -  time - the time

4079:    Level: intermediate

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

4083: @*/
4084: PetscErrorCode  TSSetTime(TS ts, PetscReal t)
4085: {
4089:   ts->ptime = t;
4090:   return(0);
4091: }

4093: /*@C
4094:    TSSetOptionsPrefix - Sets the prefix used for searching for all
4095:    TS options in the database.

4097:    Logically Collective on TS

4099:    Input Parameters:
4100: +  ts     - The TS context
4101: -  prefix - The prefix to prepend to all option names

4103:    Notes:
4104:    A hyphen (-) must NOT be given at the beginning of the prefix name.
4105:    The first character of all runtime options is AUTOMATICALLY the
4106:    hyphen.

4108:    Level: advanced

4110: .seealso: TSSetFromOptions()

4112: @*/
4113: PetscErrorCode  TSSetOptionsPrefix(TS ts,const char prefix[])
4114: {
4116:   SNES           snes;

4120:   PetscObjectSetOptionsPrefix((PetscObject)ts,prefix);
4121:   TSGetSNES(ts,&snes);
4122:   SNESSetOptionsPrefix(snes,prefix);
4123:   return(0);
4124: }

4126: /*@C
4127:    TSAppendOptionsPrefix - Appends to the prefix used for searching for all
4128:    TS options in the database.

4130:    Logically Collective on TS

4132:    Input Parameters:
4133: +  ts     - The TS context
4134: -  prefix - The prefix to prepend to all option names

4136:    Notes:
4137:    A hyphen (-) must NOT be given at the beginning of the prefix name.
4138:    The first character of all runtime options is AUTOMATICALLY the
4139:    hyphen.

4141:    Level: advanced

4143: .seealso: TSGetOptionsPrefix()

4145: @*/
4146: PetscErrorCode  TSAppendOptionsPrefix(TS ts,const char prefix[])
4147: {
4149:   SNES           snes;

4153:   PetscObjectAppendOptionsPrefix((PetscObject)ts,prefix);
4154:   TSGetSNES(ts,&snes);
4155:   SNESAppendOptionsPrefix(snes,prefix);
4156:   return(0);
4157: }

4159: /*@C
4160:    TSGetOptionsPrefix - Sets the prefix used for searching for all
4161:    TS options in the database.

4163:    Not Collective

4165:    Input Parameter:
4166: .  ts - The TS context

4168:    Output Parameter:
4169: .  prefix - A pointer to the prefix string used

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

4175:    Level: intermediate

4177: .seealso: TSAppendOptionsPrefix()
4178: @*/
4179: PetscErrorCode  TSGetOptionsPrefix(TS ts,const char *prefix[])
4180: {

4186:   PetscObjectGetOptionsPrefix((PetscObject)ts,prefix);
4187:   return(0);
4188: }

4190: /*@C
4191:    TSGetRHSJacobian - Returns the Jacobian J at the present timestep.

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

4195:    Input Parameter:
4196: .  ts  - The TS context obtained from TSCreate()

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

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

4207:    Level: intermediate

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

4211: @*/
4212: PetscErrorCode  TSGetRHSJacobian(TS ts,Mat *Amat,Mat *Pmat,TSRHSJacobian *func,void **ctx)
4213: {
4215:   DM             dm;

4218:   if (Amat || Pmat) {
4219:     SNES snes;
4220:     TSGetSNES(ts,&snes);
4221:     SNESSetUpMatrices(snes);
4222:     SNESGetJacobian(snes,Amat,Pmat,NULL,NULL);
4223:   }
4224:   TSGetDM(ts,&dm);
4225:   DMTSGetRHSJacobian(dm,func,ctx);
4226:   return(0);
4227: }

4229: /*@C
4230:    TSGetIJacobian - Returns the implicit Jacobian at the present timestep.

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

4234:    Input Parameter:
4235: .  ts  - The TS context obtained from TSCreate()

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

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

4246:    Level: advanced

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

4250: @*/
4251: PetscErrorCode  TSGetIJacobian(TS ts,Mat *Amat,Mat *Pmat,TSIJacobian *f,void **ctx)
4252: {
4254:   DM             dm;

4257:   if (Amat || Pmat) {
4258:     SNES snes;
4259:     TSGetSNES(ts,&snes);
4260:     SNESSetUpMatrices(snes);
4261:     SNESGetJacobian(snes,Amat,Pmat,NULL,NULL);
4262:   }
4263:   TSGetDM(ts,&dm);
4264:   DMTSGetIJacobian(dm,f,ctx);
4265:   return(0);
4266: }

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

4272:    Logically Collective on ts

4274:    Input Parameters:
4275: +  ts - the ODE integrator object
4276: -  dm - the dm, cannot be NULL

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

4283:    Level: intermediate

4285: .seealso: TSGetDM(), SNESSetDM(), SNESGetDM()
4286: @*/
4287: PetscErrorCode  TSSetDM(TS ts,DM dm)
4288: {
4290:   SNES           snes;
4291:   DMTS           tsdm;

4296:   PetscObjectReference((PetscObject)dm);
4297:   if (ts->dm) {               /* Move the DMTS context over to the new DM unless the new DM already has one */
4298:     if (ts->dm->dmts && !dm->dmts) {
4299:       DMCopyDMTS(ts->dm,dm);
4300:       DMGetDMTS(ts->dm,&tsdm);
4301:       if (tsdm->originaldm == ts->dm) { /* Grant write privileges to the replacement DM */
4302:         tsdm->originaldm = dm;
4303:       }
4304:     }
4305:     DMDestroy(&ts->dm);
4306:   }
4307:   ts->dm = dm;

4309:   TSGetSNES(ts,&snes);
4310:   SNESSetDM(snes,dm);
4311:   return(0);
4312: }

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

4317:    Not Collective

4319:    Input Parameter:
4320: . ts - the preconditioner context

4322:    Output Parameter:
4323: .  dm - the dm

4325:    Level: intermediate

4327: .seealso: TSSetDM(), SNESSetDM(), SNESGetDM()
4328: @*/
4329: PetscErrorCode  TSGetDM(TS ts,DM *dm)
4330: {

4335:   if (!ts->dm) {
4336:     DMShellCreate(PetscObjectComm((PetscObject)ts),&ts->dm);
4337:     if (ts->snes) {SNESSetDM(ts->snes,ts->dm);}
4338:   }
4339:   *dm = ts->dm;
4340:   return(0);
4341: }

4343: /*@
4344:    SNESTSFormFunction - Function to evaluate nonlinear residual

4346:    Logically Collective on SNES

4348:    Input Parameters:
4349: + snes - nonlinear solver
4350: . U - the current state at which to evaluate the residual
4351: - ctx - user context, must be a TS

4353:    Output Parameter:
4354: . F - the nonlinear residual

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

4360:    Level: advanced

4362: .seealso: SNESSetFunction(), MatFDColoringSetFunction()
4363: @*/
4364: PetscErrorCode  SNESTSFormFunction(SNES snes,Vec U,Vec F,void *ctx)
4365: {
4366:   TS             ts = (TS)ctx;

4374:   (ts->ops->snesfunction)(snes,U,F,ts);
4375:   return(0);
4376: }

4378: /*@
4379:    SNESTSFormJacobian - Function to evaluate the Jacobian

4381:    Collective on SNES

4383:    Input Parameters:
4384: + snes - nonlinear solver
4385: . U - the current state at which to evaluate the residual
4386: - ctx - user context, must be a TS

4388:    Output Parameters:
4389: + A - the Jacobian
4390: - B - the preconditioning matrix (may be the same as A)

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

4395:    Level: developer

4397: .seealso: SNESSetJacobian()
4398: @*/
4399: PetscErrorCode  SNESTSFormJacobian(SNES snes,Vec U,Mat A,Mat B,void *ctx)
4400: {
4401:   TS             ts = (TS)ctx;

4412:   (ts->ops->snesjacobian)(snes,U,A,B,ts);
4413:   return(0);
4414: }

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

4419:    Collective on TS

4421:    Input Parameters:
4422: +  ts - time stepping context
4423: .  t - time at which to evaluate
4424: .  U - state at which to evaluate
4425: -  ctx - context

4427:    Output Parameter:
4428: .  F - right hand side

4430:    Level: intermediate

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

4436: .seealso: TSSetRHSFunction(), TSSetRHSJacobian(), TSComputeRHSJacobianConstant()
4437: @*/
4438: PetscErrorCode TSComputeRHSFunctionLinear(TS ts,PetscReal t,Vec U,Vec F,void *ctx)
4439: {
4441:   Mat            Arhs,Brhs;

4444:   TSGetRHSMats_Private(ts,&Arhs,&Brhs);
4445:   /* undo the damage caused by shifting */
4446:   TSRecoverRHSJacobian(ts,Arhs,Brhs);
4447:   TSComputeRHSJacobian(ts,t,U,Arhs,Brhs);
4448:   MatMult(Arhs,U,F);
4449:   return(0);
4450: }

4452: /*@C
4453:    TSComputeRHSJacobianConstant - Reuses a Jacobian that is time-independent.

4455:    Collective on TS

4457:    Input Parameters:
4458: +  ts - time stepping context
4459: .  t - time at which to evaluate
4460: .  U - state at which to evaluate
4461: -  ctx - context

4463:    Output Parameters:
4464: +  A - pointer to operator
4465: -  B - pointer to preconditioning matrix

4467:    Level: intermediate

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

4472: .seealso: TSSetRHSFunction(), TSSetRHSJacobian(), TSComputeRHSFunctionLinear()
4473: @*/
4474: PetscErrorCode TSComputeRHSJacobianConstant(TS ts,PetscReal t,Vec U,Mat A,Mat B,void *ctx)
4475: {
4477:   return(0);
4478: }

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

4483:    Collective on TS

4485:    Input Parameters:
4486: +  ts - time stepping context
4487: .  t - time at which to evaluate
4488: .  U - state at which to evaluate
4489: .  Udot - time derivative of state vector
4490: -  ctx - context

4492:    Output Parameter:
4493: .  F - left hand side

4495:    Level: intermediate

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

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

4505: .seealso: TSSetIFunction(), TSSetIJacobian(), TSComputeIJacobianConstant(), TSComputeRHSFunctionLinear()
4506: @*/
4507: PetscErrorCode TSComputeIFunctionLinear(TS ts,PetscReal t,Vec U,Vec Udot,Vec F,void *ctx)
4508: {
4510:   Mat            A,B;

4513:   TSGetIJacobian(ts,&A,&B,NULL,NULL);
4514:   TSComputeIJacobian(ts,t,U,Udot,1.0,A,B,PETSC_TRUE);
4515:   MatMult(A,Udot,F);
4516:   return(0);
4517: }

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

4522:    Collective on TS

4524:    Input Parameters:
4525: +  ts - time stepping context
4526: .  t - time at which to evaluate
4527: .  U - state at which to evaluate
4528: .  Udot - time derivative of state vector
4529: .  shift - shift to apply
4530: -  ctx - context

4532:    Output Parameters:
4533: +  A - pointer to operator
4534: -  B - pointer to preconditioning matrix

4536:    Level: advanced

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

4541:    It is only appropriate for problems of the form

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

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

4549: $    shift*M + J

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

4554: .seealso: TSSetIFunction(), TSSetIJacobian(), TSComputeIFunctionLinear()
4555: @*/
4556: PetscErrorCode TSComputeIJacobianConstant(TS ts,PetscReal t,Vec U,Vec Udot,PetscReal shift,Mat A,Mat B,void *ctx)
4557: {

4561:   MatScale(A, shift / ts->ijacobian.shift);
4562:   ts->ijacobian.shift = shift;
4563:   return(0);
4564: }

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

4569:    Not Collective

4571:    Input Parameter:
4572: .  ts - the TS context

4574:    Output Parameter:
4575: .  equation_type - see TSEquationType

4577:    Level: beginner

4579: .seealso: TSSetEquationType(), TSEquationType
4580: @*/
4581: PetscErrorCode  TSGetEquationType(TS ts,TSEquationType *equation_type)
4582: {
4586:   *equation_type = ts->equation_type;
4587:   return(0);
4588: }

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

4593:    Not Collective

4595:    Input Parameters:
4596: +  ts - the TS context
4597: -  equation_type - see TSEquationType

4599:    Level: advanced

4601: .seealso: TSGetEquationType(), TSEquationType
4602: @*/
4603: PetscErrorCode  TSSetEquationType(TS ts,TSEquationType equation_type)
4604: {
4607:   ts->equation_type = equation_type;
4608:   return(0);
4609: }

4611: /*@
4612:    TSGetConvergedReason - Gets the reason the TS iteration was stopped.

4614:    Not Collective

4616:    Input Parameter:
4617: .  ts - the TS context

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

4623:    Level: beginner

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

4628: .seealso: TSSetConvergenceTest(), TSConvergedReason
4629: @*/
4630: PetscErrorCode  TSGetConvergedReason(TS ts,TSConvergedReason *reason)
4631: {
4635:   *reason = ts->reason;
4636:   return(0);
4637: }

4639: /*@
4640:    TSSetConvergedReason - Sets the reason for handling the convergence of TSSolve.

4642:    Logically Collective; reason must contain common value

4644:    Input Parameters:
4645: +  ts - the TS context
4646: -  reason - negative value indicates diverged, positive value converged, see TSConvergedReason or the
4647:             manual pages for the individual convergence tests for complete lists

4649:    Level: advanced

4651:    Notes:
4652:    Can only be called while TSSolve() is active.

4654: .seealso: TSConvergedReason
4655: @*/
4656: PetscErrorCode  TSSetConvergedReason(TS ts,TSConvergedReason reason)
4657: {
4660:   ts->reason = reason;
4661:   return(0);
4662: }

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

4667:    Not Collective

4669:    Input Parameter:
4670: .  ts - the TS context

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

4675:    Level: beginner

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

4680: .seealso: TSSetConvergenceTest(), TSConvergedReason
4681: @*/
4682: PetscErrorCode  TSGetSolveTime(TS ts,PetscReal *ftime)
4683: {
4687:   *ftime = ts->solvetime;
4688:   return(0);
4689: }

4691: /*@
4692:    TSGetSNESIterations - Gets the total number of nonlinear iterations
4693:    used by the time integrator.

4695:    Not Collective

4697:    Input Parameter:
4698: .  ts - TS context

4700:    Output Parameter:
4701: .  nits - number of nonlinear iterations

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

4706:    Level: intermediate

4708: .seealso:  TSGetKSPIterations()
4709: @*/
4710: PetscErrorCode TSGetSNESIterations(TS ts,PetscInt *nits)
4711: {
4715:   *nits = ts->snes_its;
4716:   return(0);
4717: }

4719: /*@
4720:    TSGetKSPIterations - Gets the total number of linear iterations
4721:    used by the time integrator.

4723:    Not Collective

4725:    Input Parameter:
4726: .  ts - TS context

4728:    Output Parameter:
4729: .  lits - number of linear iterations

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

4734:    Level: intermediate

4736: .seealso:  TSGetSNESIterations(), SNESGetKSPIterations()
4737: @*/
4738: PetscErrorCode TSGetKSPIterations(TS ts,PetscInt *lits)
4739: {
4743:   *lits = ts->ksp_its;
4744:   return(0);
4745: }

4747: /*@
4748:    TSGetStepRejections - Gets the total number of rejected steps.

4750:    Not Collective

4752:    Input Parameter:
4753: .  ts - TS context

4755:    Output Parameter:
4756: .  rejects - number of steps rejected

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

4761:    Level: intermediate

4763: .seealso:  TSGetSNESIterations(), TSGetKSPIterations(), TSSetMaxStepRejections(), TSGetSNESFailures(), TSSetMaxSNESFailures(), TSSetErrorIfStepFails()
4764: @*/
4765: PetscErrorCode TSGetStepRejections(TS ts,PetscInt *rejects)
4766: {
4770:   *rejects = ts->reject;
4771:   return(0);
4772: }

4774: /*@
4775:    TSGetSNESFailures - Gets the total number of failed SNES solves

4777:    Not Collective

4779:    Input Parameter:
4780: .  ts - TS context

4782:    Output Parameter:
4783: .  fails - number of failed nonlinear solves

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

4788:    Level: intermediate

4790: .seealso:  TSGetSNESIterations(), TSGetKSPIterations(), TSSetMaxStepRejections(), TSGetStepRejections(), TSSetMaxSNESFailures()
4791: @*/
4792: PetscErrorCode TSGetSNESFailures(TS ts,PetscInt *fails)
4793: {
4797:   *fails = ts->num_snes_failures;
4798:   return(0);
4799: }

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

4804:    Not Collective

4806:    Input Parameters:
4807: +  ts - TS context
4808: -  rejects - maximum number of rejected steps, pass -1 for unlimited

4810:    Notes:
4811:    The counter is reset to zero for each step

4813:    Options Database Key:
4814:  .  -ts_max_reject - Maximum number of step rejections before a step fails

4816:    Level: intermediate

4818: .seealso:  TSGetSNESIterations(), TSGetKSPIterations(), TSSetMaxSNESFailures(), TSGetStepRejections(), TSGetSNESFailures(), TSSetErrorIfStepFails(), TSGetConvergedReason()
4819: @*/
4820: PetscErrorCode TSSetMaxStepRejections(TS ts,PetscInt rejects)
4821: {
4824:   ts->max_reject = rejects;
4825:   return(0);
4826: }

4828: /*@
4829:    TSSetMaxSNESFailures - Sets the maximum number of failed SNES solves

4831:    Not Collective

4833:    Input Parameters:
4834: +  ts - TS context
4835: -  fails - maximum number of failed nonlinear solves, pass -1 for unlimited

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

4840:    Options Database Key:
4841:  .  -ts_max_snes_failures - Maximum number of nonlinear solve failures

4843:    Level: intermediate

4845: .seealso:  TSGetSNESIterations(), TSGetKSPIterations(), TSSetMaxStepRejections(), TSGetStepRejections(), TSGetSNESFailures(), SNESGetConvergedReason(), TSGetConvergedReason()
4846: @*/
4847: PetscErrorCode TSSetMaxSNESFailures(TS ts,PetscInt fails)
4848: {
4851:   ts->max_snes_failures = fails;
4852:   return(0);
4853: }

4855: /*@
4856:    TSSetErrorIfStepFails - Error if no step succeeds

4858:    Not Collective

4860:    Input Parameters:
4861: +  ts - TS context
4862: -  err - PETSC_TRUE to error if no step succeeds, PETSC_FALSE to return without failure

4864:    Options Database Key:
4865:  .  -ts_error_if_step_fails - Error if no step succeeds

4867:    Level: intermediate

4869: .seealso:  TSGetSNESIterations(), TSGetKSPIterations(), TSSetMaxStepRejections(), TSGetStepRejections(), TSGetSNESFailures(), TSSetErrorIfStepFails(), TSGetConvergedReason()
4870: @*/
4871: PetscErrorCode TSSetErrorIfStepFails(TS ts,PetscBool err)
4872: {
4875:   ts->errorifstepfailed = err;
4876:   return(0);
4877: }

4879: /*@
4880:    TSGetAdapt - Get the adaptive controller context for the current method

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

4884:    Input Parameter:
4885: .  ts - time stepping context

4887:    Output Parameter:
4888: .  adapt - adaptive controller

4890:    Level: intermediate

4892: .seealso: TSAdapt, TSAdaptSetType(), TSAdaptChoose()
4893: @*/
4894: PetscErrorCode TSGetAdapt(TS ts,TSAdapt *adapt)
4895: {

4901:   if (!ts->adapt) {
4902:     TSAdaptCreate(PetscObjectComm((PetscObject)ts),&ts->adapt);
4903:     PetscLogObjectParent((PetscObject)ts,(PetscObject)ts->adapt);
4904:     PetscObjectIncrementTabLevel((PetscObject)ts->adapt,(PetscObject)ts,1);
4905:   }
4906:   *adapt = ts->adapt;
4907:   return(0);
4908: }

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

4913:    Logically Collective

4915:    Input Parameters:
4916: +  ts - time integration context
4917: .  atol - scalar absolute tolerances, PETSC_DECIDE to leave current value
4918: .  vatol - vector of absolute tolerances or NULL, used in preference to atol if present
4919: .  rtol - scalar relative tolerances, PETSC_DECIDE to leave current value
4920: -  vrtol - vector of relative tolerances or NULL, used in preference to atol if present

4922:    Options Database keys:
4923: +  -ts_rtol <rtol> - relative tolerance for local truncation error
4924: -  -ts_atol <atol> Absolute tolerance for local truncation error

4926:    Notes:
4927:    With PETSc's implicit schemes for DAE problems, the calculation of the local truncation error
4928:    (LTE) includes both the differential and the algebraic variables. If one wants the LTE to be
4929:    computed only for the differential or the algebraic part then this can be done using the vector of
4930:    tolerances vatol. For example, by setting the tolerance vector with the desired tolerance for the
4931:    differential part and infinity for the algebraic part, the LTE calculation will include only the
4932:    differential variables.

4934:    Level: beginner

4936: .seealso: TS, TSAdapt, TSErrorWeightedNorm(), TSGetTolerances()
4937: @*/
4938: PetscErrorCode TSSetTolerances(TS ts,PetscReal atol,Vec vatol,PetscReal rtol,Vec vrtol)
4939: {

4943:   if (atol != PETSC_DECIDE && atol != PETSC_DEFAULT) ts->atol = atol;
4944:   if (vatol) {
4945:     PetscObjectReference((PetscObject)vatol);
4946:     VecDestroy(&ts->vatol);
4947:     ts->vatol = vatol;
4948:   }
4949:   if (rtol != PETSC_DECIDE && rtol != PETSC_DEFAULT) ts->rtol = rtol;
4950:   if (vrtol) {
4951:     PetscObjectReference((PetscObject)vrtol);
4952:     VecDestroy(&ts->vrtol);
4953:     ts->vrtol = vrtol;
4954:   }
4955:   return(0);
4956: }

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

4961:    Logically Collective

4963:    Input Parameter:
4964: .  ts - time integration context

4966:    Output Parameters:
4967: +  atol - scalar absolute tolerances, NULL to ignore
4968: .  vatol - vector of absolute tolerances, NULL to ignore
4969: .  rtol - scalar relative tolerances, NULL to ignore
4970: -  vrtol - vector of relative tolerances, NULL to ignore

4972:    Level: beginner

4974: .seealso: TS, TSAdapt, TSErrorWeightedNorm(), TSSetTolerances()
4975: @*/
4976: PetscErrorCode TSGetTolerances(TS ts,PetscReal *atol,Vec *vatol,PetscReal *rtol,Vec *vrtol)
4977: {
4979:   if (atol)  *atol  = ts->atol;
4980:   if (vatol) *vatol = ts->vatol;
4981:   if (rtol)  *rtol  = ts->rtol;
4982:   if (vrtol) *vrtol = ts->vrtol;
4983:   return(0);
4984: }

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

4989:    Collective on TS

4991:    Input Parameters:
4992: +  ts - time stepping context
4993: .  U - state vector, usually ts->vec_sol
4994: -  Y - state vector to be compared to U

4996:    Output Parameters:
4997: +  norm - weighted norm, a value of 1.0 means that the error matches the tolerances
4998: .  norma - weighted norm based on the absolute tolerance, a value of 1.0 means that the error matches the tolerances
4999: -  normr - weighted norm based on the relative tolerance, a value of 1.0 means that the error matches the tolerances

5001:    Level: developer

5003: .seealso: TSErrorWeightedNorm(), TSErrorWeightedNormInfinity()
5004: @*/
5005: PetscErrorCode TSErrorWeightedNorm2(TS ts,Vec U,Vec Y,PetscReal *norm,PetscReal *norma,PetscReal *normr)
5006: {
5007:   PetscErrorCode    ierr;
5008:   PetscInt          i,n,N,rstart;
5009:   PetscInt          n_loc,na_loc,nr_loc;
5010:   PetscReal         n_glb,na_glb,nr_glb;
5011:   const PetscScalar *u,*y;
5012:   PetscReal         sum,suma,sumr,gsum,gsuma,gsumr,diff;
5013:   PetscReal         tol,tola,tolr;
5014:   PetscReal         err_loc[6],err_glb[6];

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

5028:   VecGetSize(U,&N);
5029:   VecGetLocalSize(U,&n);
5030:   VecGetOwnershipRange(U,&rstart,NULL);
5031:   VecGetArrayRead(U,&u);
5032:   VecGetArrayRead(Y,&y);
5033:   sum  = 0.; n_loc  = 0;
5034:   suma = 0.; na_loc = 0;
5035:   sumr = 0.; nr_loc = 0;
5036:   if (ts->vatol && ts->vrtol) {
5037:     const PetscScalar *atol,*rtol;
5038:     VecGetArrayRead(ts->vatol,&atol);
5039:     VecGetArrayRead(ts->vrtol,&rtol);
5040:     for (i=0; i<n; i++) {
5041:       SkipSmallValue(y[i],u[i],ts->adapt->ignore_max);
5042:       diff = PetscAbsScalar(y[i] - u[i]);
5043:       tola = PetscRealPart(atol[i]);
5044:       if (tola>0.) {
5045:         suma  += PetscSqr(diff/tola);
5046:         na_loc++;
5047:       }
5048:       tolr = PetscRealPart(rtol[i]) * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
5049:       if (tolr>0.) {
5050:         sumr  += PetscSqr(diff/tolr);
5051:         nr_loc++;
5052:       }
5053:       tol=tola+tolr;
5054:       if (tol>0.) {
5055:         sum  += PetscSqr(diff/tol);
5056:         n_loc++;
5057:       }
5058:     }
5059:     VecRestoreArrayRead(ts->vatol,&atol);
5060:     VecRestoreArrayRead(ts->vrtol,&rtol);
5061:   } else if (ts->vatol) {       /* vector atol, scalar rtol */
5062:     const PetscScalar *atol;
5063:     VecGetArrayRead(ts->vatol,&atol);
5064:     for (i=0; i<n; i++) {
5065:       SkipSmallValue(y[i],u[i],ts->adapt->ignore_max);
5066:       diff = PetscAbsScalar(y[i] - u[i]);
5067:       tola = PetscRealPart(atol[i]);
5068:       if (tola>0.) {
5069:         suma  += PetscSqr(diff/tola);
5070:         na_loc++;
5071:       }
5072:       tolr = ts->rtol * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
5073:       if (tolr>0.) {
5074:         sumr  += PetscSqr(diff/tolr);
5075:         nr_loc++;
5076:       }
5077:       tol=tola+tolr;
5078:       if (tol>0.) {
5079:         sum  += PetscSqr(diff/tol);
5080:         n_loc++;
5081:       }
5082:     }
5083:     VecRestoreArrayRead(ts->vatol,&atol);
5084:   } else if (ts->vrtol) {       /* scalar atol, vector rtol */
5085:     const PetscScalar *rtol;
5086:     VecGetArrayRead(ts->vrtol,&rtol);
5087:     for (i=0; i<n; i++) {
5088:       SkipSmallValue(y[i],u[i],ts->adapt->ignore_max);
5089:       diff = PetscAbsScalar(y[i] - u[i]);
5090:       tola = ts->atol;
5091:       if (tola>0.) {
5092:         suma  += PetscSqr(diff/tola);
5093:         na_loc++;
5094:       }
5095:       tolr = PetscRealPart(rtol[i]) * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
5096:       if (tolr>0.) {
5097:         sumr  += PetscSqr(diff/tolr);
5098:         nr_loc++;
5099:       }
5100:       tol=tola+tolr;
5101:       if (tol>0.) {
5102:         sum  += PetscSqr(diff/tol);
5103:         n_loc++;
5104:       }
5105:     }
5106:     VecRestoreArrayRead(ts->vrtol,&rtol);
5107:   } else {                      /* scalar atol, scalar rtol */
5108:     for (i=0; i<n; i++) {
5109:       SkipSmallValue(y[i],u[i],ts->adapt->ignore_max);
5110:       diff = PetscAbsScalar(y[i] - u[i]);
5111:       tola = ts->atol;
5112:       if (tola>0.) {
5113:         suma  += PetscSqr(diff/tola);
5114:         na_loc++;
5115:       }
5116:       tolr = ts->rtol * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
5117:       if (tolr>0.) {
5118:         sumr  += PetscSqr(diff/tolr);
5119:         nr_loc++;
5120:       }
5121:       tol=tola+tolr;
5122:       if (tol>0.) {
5123:         sum  += PetscSqr(diff/tol);
5124:         n_loc++;
5125:       }
5126:     }
5127:   }
5128:   VecRestoreArrayRead(U,&u);
5129:   VecRestoreArrayRead(Y,&y);

5131:   err_loc[0] = sum;
5132:   err_loc[1] = suma;
5133:   err_loc[2] = sumr;
5134:   err_loc[3] = (PetscReal)n_loc;
5135:   err_loc[4] = (PetscReal)na_loc;
5136:   err_loc[5] = (PetscReal)nr_loc;

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

5140:   gsum   = err_glb[0];
5141:   gsuma  = err_glb[1];
5142:   gsumr  = err_glb[2];
5143:   n_glb  = err_glb[3];
5144:   na_glb = err_glb[4];
5145:   nr_glb = err_glb[5];

5147:   *norm  = 0.;
5148:   if (n_glb>0.) {*norm  = PetscSqrtReal(gsum  / n_glb);}
5149:   *norma = 0.;
5150:   if (na_glb>0.) {*norma = PetscSqrtReal(gsuma / na_glb);}
5151:   *normr = 0.;
5152:   if (nr_glb>0.) {*normr = PetscSqrtReal(gsumr / nr_glb);}

5154:   if (PetscIsInfOrNanScalar(*norm)) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_FP,"Infinite or not-a-number generated in norm");
5155:   if (PetscIsInfOrNanScalar(*norma)) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_FP,"Infinite or not-a-number generated in norma");
5156:   if (PetscIsInfOrNanScalar(*normr)) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_FP,"Infinite or not-a-number generated in normr");
5157:   return(0);
5158: }

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

5163:    Collective on TS

5165:    Input Parameters:
5166: +  ts - time stepping context
5167: .  U - state vector, usually ts->vec_sol
5168: -  Y - state vector to be compared to U

5170:    Output Parameters:
5171: +  norm - weighted norm, a value of 1.0 means that the error matches the tolerances
5172: .  norma - weighted norm based on the absolute tolerance, a value of 1.0 means that the error matches the tolerances
5173: -  normr - weighted norm based on the relative tolerance, a value of 1.0 means that the error matches the tolerances

5175:    Level: developer

5177: .seealso: TSErrorWeightedNorm(), TSErrorWeightedNorm2()
5178: @*/
5179: PetscErrorCode TSErrorWeightedNormInfinity(TS ts,Vec U,Vec Y,PetscReal *norm,PetscReal *norma,PetscReal *normr)
5180: {
5181:   PetscErrorCode    ierr;
5182:   PetscInt          i,n,N,rstart;
5183:   const PetscScalar *u,*y;
5184:   PetscReal         max,gmax,maxa,gmaxa,maxr,gmaxr;
5185:   PetscReal         tol,tola,tolr,diff;
5186:   PetscReal         err_loc[3],err_glb[3];

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

5200:   VecGetSize(U,&N);
5201:   VecGetLocalSize(U,&n);
5202:   VecGetOwnershipRange(U,&rstart,NULL);
5203:   VecGetArrayRead(U,&u);
5204:   VecGetArrayRead(Y,&y);

5206:   max=0.;
5207:   maxa=0.;
5208:   maxr=0.;

5210:   if (ts->vatol && ts->vrtol) {     /* vector atol, vector rtol */
5211:     const PetscScalar *atol,*rtol;
5212:     VecGetArrayRead(ts->vatol,&atol);
5213:     VecGetArrayRead(ts->vrtol,&rtol);

5215:     for (i=0; i<n; i++) {
5216:       SkipSmallValue(y[i],u[i],ts->adapt->ignore_max);
5217:       diff = PetscAbsScalar(y[i] - u[i]);
5218:       tola = PetscRealPart(atol[i]);
5219:       tolr = PetscRealPart(rtol[i]) * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
5220:       tol  = tola+tolr;
5221:       if (tola>0.) {
5222:         maxa = PetscMax(maxa,diff / tola);
5223:       }
5224:       if (tolr>0.) {
5225:         maxr = PetscMax(maxr,diff / tolr);
5226:       }
5227:       if (tol>0.) {
5228:         max = PetscMax(max,diff / tol);
5229:       }
5230:     }
5231:     VecRestoreArrayRead(ts->vatol,&atol);
5232:     VecRestoreArrayRead(ts->vrtol,&rtol);
5233:   } else if (ts->vatol) {       /* vector atol, scalar rtol */
5234:     const PetscScalar *atol;
5235:     VecGetArrayRead(ts->vatol,&atol);
5236:     for (i=0; i<n; i++) {
5237:       SkipSmallValue(y[i],u[i],ts->adapt->ignore_max);
5238:       diff = PetscAbsScalar(y[i] - u[i]);
5239:       tola = PetscRealPart(atol[i]);
5240:       tolr = ts->rtol  * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
5241:       tol  = tola+tolr;
5242:       if (tola>0.) {
5243:         maxa = PetscMax(maxa,diff / tola);
5244:       }
5245:       if (tolr>0.) {
5246:         maxr = PetscMax(maxr,diff / tolr);
5247:       }
5248:       if (tol>0.) {
5249:         max = PetscMax(max,diff / tol);
5250:       }
5251:     }
5252:     VecRestoreArrayRead(ts->vatol,&atol);
5253:   } else if (ts->vrtol) {       /* scalar atol, vector rtol */
5254:     const PetscScalar *rtol;
5255:     VecGetArrayRead(ts->vrtol,&rtol);

5257:     for (i=0; i<n; i++) {
5258:       SkipSmallValue(y[i],u[i],ts->adapt->ignore_max);
5259:       diff = PetscAbsScalar(y[i] - u[i]);
5260:       tola = ts->atol;
5261:       tolr = PetscRealPart(rtol[i]) * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
5262:       tol  = tola+tolr;
5263:       if (tola>0.) {
5264:         maxa = PetscMax(maxa,diff / tola);
5265:       }
5266:       if (tolr>0.) {
5267:         maxr = PetscMax(maxr,diff / tolr);
5268:       }
5269:       if (tol>0.) {
5270:         max = PetscMax(max,diff / tol);
5271:       }
5272:     }
5273:     VecRestoreArrayRead(ts->vrtol,&rtol);
5274:   } else {                      /* scalar atol, scalar rtol */

5276:     for (i=0; i<n; i++) {
5277:       SkipSmallValue(y[i],u[i],ts->adapt->ignore_max);
5278:       diff = PetscAbsScalar(y[i] - u[i]);
5279:       tola = ts->atol;
5280:       tolr = ts->rtol * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
5281:       tol  = tola+tolr;
5282:       if (tola>0.) {
5283:         maxa = PetscMax(maxa,diff / tola);
5284:       }
5285:       if (tolr>0.) {
5286:         maxr = PetscMax(maxr,diff / tolr);
5287:       }
5288:       if (tol>0.) {
5289:         max = PetscMax(max,diff / tol);
5290:       }
5291:     }
5292:   }
5293:   VecRestoreArrayRead(U,&u);
5294:   VecRestoreArrayRead(Y,&y);
5295:   err_loc[0] = max;
5296:   err_loc[1] = maxa;
5297:   err_loc[2] = maxr;
5298:   MPIU_Allreduce(err_loc,err_glb,3,MPIU_REAL,MPIU_MAX,PetscObjectComm((PetscObject)ts));
5299:   gmax   = err_glb[0];
5300:   gmaxa  = err_glb[1];
5301:   gmaxr  = err_glb[2];

5303:   *norm = gmax;
5304:   *norma = gmaxa;
5305:   *normr = gmaxr;
5306:   if (PetscIsInfOrNanScalar(*norm)) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_FP,"Infinite or not-a-number generated in norm");
5307:     if (PetscIsInfOrNanScalar(*norma)) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_FP,"Infinite or not-a-number generated in norma");
5308:     if (PetscIsInfOrNanScalar(*normr)) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_FP,"Infinite or not-a-number generated in normr");
5309:   return(0);
5310: }

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

5315:    Collective on TS

5317:    Input Parameters:
5318: +  ts - time stepping context
5319: .  U - state vector, usually ts->vec_sol
5320: .  Y - state vector to be compared to U
5321: -  wnormtype - norm type, either NORM_2 or NORM_INFINITY

5323:    Output Parameters:
5324: +  norm  - weighted norm, a value of 1.0 achieves a balance between absolute and relative tolerances
5325: .  norma - weighted norm, a value of 1.0 means that the error meets the absolute tolerance set by the user
5326: -  normr - weighted norm, a value of 1.0 means that the error meets the relative tolerance set by the user

5328:    Options Database Keys:
5329: .  -ts_adapt_wnormtype <wnormtype> - 2, INFINITY

5331:    Level: developer

5333: .seealso: TSErrorWeightedNormInfinity(), TSErrorWeightedNorm2(), TSErrorWeightedENorm
5334: @*/
5335: PetscErrorCode TSErrorWeightedNorm(TS ts,Vec U,Vec Y,NormType wnormtype,PetscReal *norm,PetscReal *norma,PetscReal *normr)
5336: {

5340:   if (wnormtype == NORM_2) {
5341:     TSErrorWeightedNorm2(ts,U,Y,norm,norma,normr);
5342:   } else if (wnormtype == NORM_INFINITY) {
5343:     TSErrorWeightedNormInfinity(ts,U,Y,norm,norma,normr);
5344:   } else SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"No support for norm type %s",NormTypes[wnormtype]);
5345:   return(0);
5346: }

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

5351:    Collective on TS

5353:    Input Parameters:
5354: +  ts - time stepping context
5355: .  E - error vector
5356: .  U - state vector, usually ts->vec_sol
5357: -  Y - state vector, previous time step

5359:    Output Parameters:
5360: +  norm - weighted norm, a value of 1.0 means that the error matches the tolerances
5361: .  norma - weighted norm based on the absolute tolerance, a value of 1.0 means that the error matches the tolerances
5362: -  normr - weighted norm based on the relative tolerance, a value of 1.0 means that the error matches the tolerances

5364:    Level: developer

5366: .seealso: TSErrorWeightedENorm(), TSErrorWeightedENormInfinity()
5367: @*/
5368: PetscErrorCode TSErrorWeightedENorm2(TS ts,Vec E,Vec U,Vec Y,PetscReal *norm,PetscReal *norma,PetscReal *normr)
5369: {
5370:   PetscErrorCode    ierr;
5371:   PetscInt          i,n,N,rstart;
5372:   PetscInt          n_loc,na_loc,nr_loc;
5373:   PetscReal         n_glb,na_glb,nr_glb;
5374:   const PetscScalar *e,*u,*y;
5375:   PetscReal         err,sum,suma,sumr,gsum,gsuma,gsumr;
5376:   PetscReal         tol,tola,tolr;
5377:   PetscReal         err_loc[6],err_glb[6];


5393:   VecGetSize(E,&N);
5394:   VecGetLocalSize(E,&n);
5395:   VecGetOwnershipRange(E,&rstart,NULL);
5396:   VecGetArrayRead(E,&e);
5397:   VecGetArrayRead(U,&u);
5398:   VecGetArrayRead(Y,&y);
5399:   sum  = 0.; n_loc  = 0;
5400:   suma = 0.; na_loc = 0;
5401:   sumr = 0.; nr_loc = 0;
5402:   if (ts->vatol && ts->vrtol) {
5403:     const PetscScalar *atol,*rtol;
5404:     VecGetArrayRead(ts->vatol,&atol);
5405:     VecGetArrayRead(ts->vrtol,&rtol);
5406:     for (i=0; i<n; i++) {
5407:       SkipSmallValue(y[i],u[i],ts->adapt->ignore_max);
5408:       err = PetscAbsScalar(e[i]);
5409:       tola = PetscRealPart(atol[i]);
5410:       if (tola>0.) {
5411:         suma  += PetscSqr(err/tola);
5412:         na_loc++;
5413:       }
5414:       tolr = PetscRealPart(rtol[i]) * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
5415:       if (tolr>0.) {
5416:         sumr  += PetscSqr(err/tolr);
5417:         nr_loc++;
5418:       }
5419:       tol=tola+tolr;
5420:       if (tol>0.) {
5421:         sum  += PetscSqr(err/tol);
5422:         n_loc++;
5423:       }
5424:     }
5425:     VecRestoreArrayRead(ts->vatol,&atol);
5426:     VecRestoreArrayRead(ts->vrtol,&rtol);
5427:   } else if (ts->vatol) {       /* vector atol, scalar rtol */
5428:     const PetscScalar *atol;
5429:     VecGetArrayRead(ts->vatol,&atol);
5430:     for (i=0; i<n; i++) {
5431:       SkipSmallValue(y[i],u[i],ts->adapt->ignore_max);
5432:       err = PetscAbsScalar(e[i]);
5433:       tola = PetscRealPart(atol[i]);
5434:       if (tola>0.) {
5435:         suma  += PetscSqr(err/tola);
5436:         na_loc++;
5437:       }
5438:       tolr = ts->rtol * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
5439:       if (tolr>0.) {
5440:         sumr  += PetscSqr(err/tolr);
5441:         nr_loc++;
5442:       }
5443:       tol=tola+tolr;
5444:       if (tol>0.) {
5445:         sum  += PetscSqr(err/tol);
5446:         n_loc++;
5447:       }
5448:     }
5449:     VecRestoreArrayRead(ts->vatol,&atol);
5450:   } else if (ts->vrtol) {       /* scalar atol, vector rtol */
5451:     const PetscScalar *rtol;
5452:     VecGetArrayRead(ts->vrtol,&rtol);
5453:     for (i=0; i<n; i++) {
5454:       SkipSmallValue(y[i],u[i],ts->adapt->ignore_max);
5455:       err = PetscAbsScalar(e[i]);
5456:       tola = ts->atol;
5457:       if (tola>0.) {
5458:         suma  += PetscSqr(err/tola);
5459:         na_loc++;
5460:       }
5461:       tolr = PetscRealPart(rtol[i]) * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
5462:       if (tolr>0.) {
5463:         sumr  += PetscSqr(err/tolr);
5464:         nr_loc++;
5465:       }
5466:       tol=tola+tolr;
5467:       if (tol>0.) {
5468:         sum  += PetscSqr(err/tol);
5469:         n_loc++;
5470:       }
5471:     }
5472:     VecRestoreArrayRead(ts->vrtol,&rtol);
5473:   } else {                      /* scalar atol, scalar rtol */
5474:     for (i=0; i<n; i++) {
5475:       SkipSmallValue(y[i],u[i],ts->adapt->ignore_max);
5476:       err = PetscAbsScalar(e[i]);
5477:       tola = ts->atol;
5478:       if (tola>0.) {
5479:         suma  += PetscSqr(err/tola);
5480:         na_loc++;
5481:       }
5482:       tolr = ts->rtol * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
5483:       if (tolr>0.) {
5484:         sumr  += PetscSqr(err/tolr);
5485:         nr_loc++;
5486:       }
5487:       tol=tola+tolr;
5488:       if (tol>0.) {
5489:         sum  += PetscSqr(err/tol);
5490:         n_loc++;
5491:       }
5492:     }
5493:   }
5494:   VecRestoreArrayRead(E,&e);
5495:   VecRestoreArrayRead(U,&u);
5496:   VecRestoreArrayRead(Y,&y);

5498:   err_loc[0] = sum;
5499:   err_loc[1] = suma;
5500:   err_loc[2] = sumr;
5501:   err_loc[3] = (PetscReal)n_loc;
5502:   err_loc[4] = (PetscReal)na_loc;
5503:   err_loc[5] = (PetscReal)nr_loc;

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

5507:   gsum   = err_glb[0];
5508:   gsuma  = err_glb[1];
5509:   gsumr  = err_glb[2];
5510:   n_glb  = err_glb[3];
5511:   na_glb = err_glb[4];
5512:   nr_glb = err_glb[5];

5514:   *norm  = 0.;
5515:   if (n_glb>0.) {*norm  = PetscSqrtReal(gsum  / n_glb);}
5516:   *norma = 0.;
5517:   if (na_glb>0.) {*norma = PetscSqrtReal(gsuma / na_glb);}
5518:   *normr = 0.;
5519:   if (nr_glb>0.) {*normr = PetscSqrtReal(gsumr / nr_glb);}

5521:   if (PetscIsInfOrNanScalar(*norm)) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_FP,"Infinite or not-a-number generated in norm");
5522:   if (PetscIsInfOrNanScalar(*norma)) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_FP,"Infinite or not-a-number generated in norma");
5523:   if (PetscIsInfOrNanScalar(*normr)) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_FP,"Infinite or not-a-number generated in normr");
5524:   return(0);
5525: }

5527: /*@
5528:    TSErrorWeightedENormInfinity - compute a weighted infinity error norm based on supplied absolute and relative tolerances
5529:    Collective on TS

5531:    Input Parameters:
5532: +  ts - time stepping context
5533: .  E - error vector
5534: .  U - state vector, usually ts->vec_sol
5535: -  Y - state vector, previous time step

5537:    Output Parameters:
5538: +  norm - weighted norm, a value of 1.0 means that the error matches the tolerances
5539: .  norma - weighted norm based on the absolute tolerance, a value of 1.0 means that the error matches the tolerances
5540: -  normr - weighted norm based on the relative tolerance, a value of 1.0 means that the error matches the tolerances

5542:    Level: developer

5544: .seealso: TSErrorWeightedENorm(), TSErrorWeightedENorm2()
5545: @*/
5546: PetscErrorCode TSErrorWeightedENormInfinity(TS ts,Vec E,Vec U,Vec Y,PetscReal *norm,PetscReal *norma,PetscReal *normr)
5547: {
5548:   PetscErrorCode    ierr;
5549:   PetscInt          i,n,N,rstart;
5550:   const PetscScalar *e,*u,*y;
5551:   PetscReal         err,max,gmax,maxa,gmaxa,maxr,gmaxr;
5552:   PetscReal         tol,tola,tolr;
5553:   PetscReal         err_loc[3],err_glb[3];


5569:   VecGetSize(E,&N);
5570:   VecGetLocalSize(E,&n);
5571:   VecGetOwnershipRange(E,&rstart,NULL);
5572:   VecGetArrayRead(E,&e);
5573:   VecGetArrayRead(U,&u);
5574:   VecGetArrayRead(Y,&y);

5576:   max=0.;
5577:   maxa=0.;
5578:   maxr=0.;

5580:   if (ts->vatol && ts->vrtol) {     /* vector atol, vector rtol */
5581:     const PetscScalar *atol,*rtol;
5582:     VecGetArrayRead(ts->vatol,&atol);
5583:     VecGetArrayRead(ts->vrtol,&rtol);

5585:     for (i=0; i<n; i++) {
5586:       SkipSmallValue(y[i],u[i],ts->adapt->ignore_max);
5587:       err = PetscAbsScalar(e[i]);
5588:       tola = PetscRealPart(atol[i]);
5589:       tolr = PetscRealPart(rtol[i]) * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
5590:       tol  = tola+tolr;
5591:       if (tola>0.) {
5592:         maxa = PetscMax(maxa,err / tola);
5593:       }
5594:       if (tolr>0.) {
5595:         maxr = PetscMax(maxr,err / tolr);
5596:       }
5597:       if (tol>0.) {
5598:         max = PetscMax(max,err / tol);
5599:       }
5600:     }
5601:     VecRestoreArrayRead(ts->vatol,&atol);
5602:     VecRestoreArrayRead(ts->vrtol,&rtol);
5603:   } else if (ts->vatol) {       /* vector atol, scalar rtol */
5604:     const PetscScalar *atol;
5605:     VecGetArrayRead(ts->vatol,&atol);
5606:     for (i=0; i<n; i++) {
5607:       SkipSmallValue(y[i],u[i],ts->adapt->ignore_max);
5608:       err = PetscAbsScalar(e[i]);
5609:       tola = PetscRealPart(atol[i]);
5610:       tolr = ts->rtol  * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
5611:       tol  = tola+tolr;
5612:       if (tola>0.) {
5613:         maxa = PetscMax(maxa,err / tola);
5614:       }
5615:       if (tolr>0.) {
5616:         maxr = PetscMax(maxr,err / tolr);
5617:       }
5618:       if (tol>0.) {
5619:         max = PetscMax(max,err / tol);
5620:       }
5621:     }
5622:     VecRestoreArrayRead(ts->vatol,&atol);
5623:   } else if (ts->vrtol) {       /* scalar atol, vector rtol */
5624:     const PetscScalar *rtol;
5625:     VecGetArrayRead(ts->vrtol,&rtol);

5627:     for (i=0; i<n; i++) {
5628:       SkipSmallValue(y[i],u[i],ts->adapt->ignore_max);
5629:       err = PetscAbsScalar(e[i]);
5630:       tola = ts->atol;
5631:       tolr = PetscRealPart(rtol[i]) * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
5632:       tol  = tola+tolr;
5633:       if (tola>0.) {
5634:         maxa = PetscMax(maxa,err / tola);
5635:       }
5636:       if (tolr>0.) {
5637:         maxr = PetscMax(maxr,err / tolr);
5638:       }
5639:       if (tol>0.) {
5640:         max = PetscMax(max,err / tol);
5641:       }
5642:     }
5643:     VecRestoreArrayRead(ts->vrtol,&rtol);
5644:   } else {                      /* scalar atol, scalar rtol */

5646:     for (i=0; i<n; i++) {
5647:       SkipSmallValue(y[i],u[i],ts->adapt->ignore_max);
5648:       err = PetscAbsScalar(e[i]);
5649:       tola = ts->atol;
5650:       tolr = ts->rtol * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
5651:       tol  = tola+tolr;
5652:       if (tola>0.) {
5653:         maxa = PetscMax(maxa,err / tola);
5654:       }
5655:       if (tolr>0.) {
5656:         maxr = PetscMax(maxr,err / tolr);
5657:       }
5658:       if (tol>0.) {
5659:         max = PetscMax(max,err / tol);
5660:       }
5661:     }
5662:   }
5663:   VecRestoreArrayRead(E,&e);
5664:   VecRestoreArrayRead(U,&u);
5665:   VecRestoreArrayRead(Y,&y);
5666:   err_loc[0] = max;
5667:   err_loc[1] = maxa;
5668:   err_loc[2] = maxr;
5669:   MPIU_Allreduce(err_loc,err_glb,3,MPIU_REAL,MPIU_MAX,PetscObjectComm((PetscObject)ts));
5670:   gmax   = err_glb[0];
5671:   gmaxa  = err_glb[1];
5672:   gmaxr  = err_glb[2];

5674:   *norm = gmax;
5675:   *norma = gmaxa;
5676:   *normr = gmaxr;
5677:   if (PetscIsInfOrNanScalar(*norm)) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_FP,"Infinite or not-a-number generated in norm");
5678:     if (PetscIsInfOrNanScalar(*norma)) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_FP,"Infinite or not-a-number generated in norma");
5679:     if (PetscIsInfOrNanScalar(*normr)) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_FP,"Infinite or not-a-number generated in normr");
5680:   return(0);
5681: }

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

5686:    Collective on TS

5688:    Input Parameters:
5689: +  ts - time stepping context
5690: .  E - error vector
5691: .  U - state vector, usually ts->vec_sol
5692: .  Y - state vector, previous time step
5693: -  wnormtype - norm type, either NORM_2 or NORM_INFINITY

5695:    Output Parameters:
5696: +  norm  - weighted norm, a value of 1.0 achieves a balance between absolute and relative tolerances
5697: .  norma - weighted norm, a value of 1.0 means that the error meets the absolute tolerance set by the user
5698: -  normr - weighted norm, a value of 1.0 means that the error meets the relative tolerance set by the user

5700:    Options Database Keys:
5701: .  -ts_adapt_wnormtype <wnormtype> - 2, INFINITY

5703:    Level: developer

5705: .seealso: TSErrorWeightedENormInfinity(), TSErrorWeightedENorm2(), TSErrorWeightedNormInfinity(), TSErrorWeightedNorm2()
5706: @*/
5707: PetscErrorCode TSErrorWeightedENorm(TS ts,Vec E,Vec U,Vec Y,NormType wnormtype,PetscReal *norm,PetscReal *norma,PetscReal *normr)
5708: {

5712:   if (wnormtype == NORM_2) {
5713:     TSErrorWeightedENorm2(ts,E,U,Y,norm,norma,normr);
5714:   } else if (wnormtype == NORM_INFINITY) {
5715:     TSErrorWeightedENormInfinity(ts,E,U,Y,norm,norma,normr);
5716:   } else SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"No support for norm type %s",NormTypes[wnormtype]);
5717:   return(0);
5718: }

5720: /*@
5721:    TSSetCFLTimeLocal - Set the local CFL constraint relative to forward Euler

5723:    Logically Collective on TS

5725:    Input Parameters:
5726: +  ts - time stepping context
5727: -  cfltime - maximum stable time step if using forward Euler (value can be different on each process)

5729:    Note:
5730:    After calling this function, the global CFL time can be obtained by calling TSGetCFLTime()

5732:    Level: intermediate

5734: .seealso: TSGetCFLTime(), TSADAPTCFL
5735: @*/
5736: PetscErrorCode TSSetCFLTimeLocal(TS ts,PetscReal cfltime)
5737: {
5740:   ts->cfltime_local = cfltime;
5741:   ts->cfltime       = -1.;
5742:   return(0);
5743: }

5745: /*@
5746:    TSGetCFLTime - Get the maximum stable time step according to CFL criteria applied to forward Euler

5748:    Collective on TS

5750:    Input Parameter:
5751: .  ts - time stepping context

5753:    Output Parameter:
5754: .  cfltime - maximum stable time step for forward Euler

5756:    Level: advanced

5758: .seealso: TSSetCFLTimeLocal()
5759: @*/
5760: PetscErrorCode TSGetCFLTime(TS ts,PetscReal *cfltime)
5761: {

5765:   if (ts->cfltime < 0) {
5766:     MPIU_Allreduce(&ts->cfltime_local,&ts->cfltime,1,MPIU_REAL,MPIU_MIN,PetscObjectComm((PetscObject)ts));
5767:   }
5768:   *cfltime = ts->cfltime;
5769:   return(0);
5770: }

5772: /*@
5773:    TSVISetVariableBounds - Sets the lower and upper bounds for the solution vector. xl <= x <= xu

5775:    Input Parameters:
5776: +  ts   - the TS context.
5777: .  xl   - lower bound.
5778: -  xu   - upper bound.

5780:    Notes:
5781:    If this routine is not called then the lower and upper bounds are set to
5782:    PETSC_NINFINITY and PETSC_INFINITY respectively during SNESSetUp().

5784:    Level: advanced

5786: @*/
5787: PetscErrorCode TSVISetVariableBounds(TS ts, Vec xl, Vec xu)
5788: {
5790:   SNES           snes;

5793:   TSGetSNES(ts,&snes);
5794:   SNESVISetVariableBounds(snes,xl,xu);
5795:   return(0);
5796: }

5798: /*@
5799:    TSComputeLinearStability - computes the linear stability function at a point

5801:    Collective on TS

5803:    Input Parameters:
5804: +  ts - the TS context
5805: -  xr,xi - real and imaginary part of input arguments

5807:    Output Parameters:
5808: .  yr,yi - real and imaginary part of function value

5810:    Level: developer

5812: .seealso: TSSetRHSFunction(), TSComputeIFunction()
5813: @*/
5814: PetscErrorCode TSComputeLinearStability(TS ts,PetscReal xr,PetscReal xi,PetscReal *yr,PetscReal *yi)
5815: {

5820:   if (!ts->ops->linearstability) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"Linearized stability function not provided for this method");
5821:   (*ts->ops->linearstability)(ts,xr,xi,yr,yi);
5822:   return(0);
5823: }

5825: /*@
5826:    TSRestartStep - Flags the solver to restart the next step

5828:    Collective on TS

5830:    Input Parameter:
5831: .  ts - the TS context obtained from TSCreate()

5833:    Level: advanced

5835:    Notes:
5836:    Multistep methods like BDF or Runge-Kutta methods with FSAL property require restarting the solver in the event of
5837:    discontinuities. These discontinuities may be introduced as a consequence of explicitly modifications to the solution
5838:    vector (which PETSc attempts to detect and handle) or problem coefficients (which PETSc is not able to detect). For
5839:    the sake of correctness and maximum safety, users are expected to call TSRestart() whenever they introduce
5840:    discontinuities in callback routines (e.g. prestep and poststep routines, or implicit/rhs function routines with
5841:    discontinuous source terms).

5843: .seealso: TSSolve(), TSSetPreStep(), TSSetPostStep()
5844: @*/
5845: PetscErrorCode TSRestartStep(TS ts)
5846: {
5849:   ts->steprestart = PETSC_TRUE;
5850:   return(0);
5851: }

5853: /*@
5854:    TSRollBack - Rolls back one time step

5856:    Collective on TS

5858:    Input Parameter:
5859: .  ts - the TS context obtained from TSCreate()

5861:    Level: advanced

5863: .seealso: TSCreate(), TSSetUp(), TSDestroy(), TSSolve(), TSSetPreStep(), TSSetPreStage(), TSInterpolate()
5864: @*/
5865: PetscErrorCode  TSRollBack(TS ts)
5866: {

5871:   if (ts->steprollback) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_ARG_WRONGSTATE,"TSRollBack already called");
5872:   if (!ts->ops->rollback) SETERRQ1(PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"TSRollBack not implemented for type '%s'",((PetscObject)ts)->type_name);
5873:   (*ts->ops->rollback)(ts);
5874:   ts->time_step = ts->ptime - ts->ptime_prev;
5875:   ts->ptime = ts->ptime_prev;
5876:   ts->ptime_prev = ts->ptime_prev_rollback;
5877:   ts->steps--;
5878:   ts->steprollback = PETSC_TRUE;
5879:   return(0);
5880: }

5882: /*@
5883:    TSGetStages - Get the number of stages and stage values

5885:    Input Parameter:
5886: .  ts - the TS context obtained from TSCreate()

5888:    Output Parameters:
5889: +  ns - the number of stages
5890: -  Y - the current stage vectors

5892:    Level: advanced

5894:    Notes: Both ns and Y can be NULL.

5896: .seealso: TSCreate()
5897: @*/
5898: PetscErrorCode  TSGetStages(TS ts,PetscInt *ns,Vec **Y)
5899: {

5906:   if (!ts->ops->getstages) {
5907:     if (ns) *ns = 0;
5908:     if (Y) *Y = NULL;
5909:   } else {
5910:     (*ts->ops->getstages)(ts,ns,Y);
5911:   }
5912:   return(0);
5913: }

5915: /*@C
5916:   TSComputeIJacobianDefaultColor - Computes the Jacobian using finite differences and coloring to exploit matrix sparsity.

5918:   Collective on SNES

5920:   Input Parameters:
5921: + ts - the TS context
5922: . t - current timestep
5923: . U - state vector
5924: . Udot - time derivative of state vector
5925: . shift - shift to apply, see note below
5926: - ctx - an optional user context

5928:   Output Parameters:
5929: + J - Jacobian matrix (not altered in this routine)
5930: - B - newly computed Jacobian matrix to use with preconditioner (generally the same as J)

5932:   Level: intermediate

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

5937:   dF/dU + shift*dF/dUdot

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

5942:   This will first try to get the coloring from the DM.  If the DM type has no coloring
5943:   routine, then it will try to get the coloring from the matrix.  This requires that the
5944:   matrix have nonzero entries precomputed.

5946: .seealso: TSSetIJacobian(), MatFDColoringCreate(), MatFDColoringSetFunction()
5947: @*/
5948: PetscErrorCode TSComputeIJacobianDefaultColor(TS ts,PetscReal t,Vec U,Vec Udot,PetscReal shift,Mat J,Mat B,void *ctx)
5949: {
5950:   SNES           snes;
5951:   MatFDColoring  color;
5952:   PetscBool      hascolor, matcolor = PETSC_FALSE;

5956:   PetscOptionsGetBool(((PetscObject)ts)->options,((PetscObject) ts)->prefix, "-ts_fd_color_use_mat", &matcolor, NULL);
5957:   PetscObjectQuery((PetscObject) B, "TSMatFDColoring", (PetscObject *) &color);
5958:   if (!color) {
5959:     DM         dm;
5960:     ISColoring iscoloring;

5962:     TSGetDM(ts, &dm);
5963:     DMHasColoring(dm, &hascolor);
5964:     if (hascolor && !matcolor) {
5965:       DMCreateColoring(dm, IS_COLORING_GLOBAL, &iscoloring);
5966:       MatFDColoringCreate(B, iscoloring, &color);
5967:       MatFDColoringSetFunction(color, (PetscErrorCode (*)(void)) SNESTSFormFunction, (void *) ts);
5968:       MatFDColoringSetFromOptions(color);
5969:       MatFDColoringSetUp(B, iscoloring, color);
5970:       ISColoringDestroy(&iscoloring);
5971:     } else {
5972:       MatColoring mc;

5974:       MatColoringCreate(B, &mc);
5975:       MatColoringSetDistance(mc, 2);
5976:       MatColoringSetType(mc, MATCOLORINGSL);
5977:       MatColoringSetFromOptions(mc);
5978:       MatColoringApply(mc, &iscoloring);
5979:       MatColoringDestroy(&mc);
5980:       MatFDColoringCreate(B, iscoloring, &color);
5981:       MatFDColoringSetFunction(color, (PetscErrorCode (*)(void)) SNESTSFormFunction, (void *) ts);
5982:       MatFDColoringSetFromOptions(color);
5983:       MatFDColoringSetUp(B, iscoloring, color);
5984:       ISColoringDestroy(&iscoloring);
5985:     }
5986:     PetscObjectCompose((PetscObject) B, "TSMatFDColoring", (PetscObject) color);
5987:     PetscObjectDereference((PetscObject) color);
5988:   }
5989:   TSGetSNES(ts, &snes);
5990:   MatFDColoringApply(B, color, U, snes);
5991:   if (J != B) {
5992:     MatAssemblyBegin(J, MAT_FINAL_ASSEMBLY);
5993:     MatAssemblyEnd(J, MAT_FINAL_ASSEMBLY);
5994:   }
5995:   return(0);
5996: }

5998: /*@
5999:     TSSetFunctionDomainError - Set a function that tests if the current state vector is valid

6001:     Input Parameters:
6002: +    ts - the TS context
6003: -    func - function called within TSFunctionDomainError

6005:     Calling sequence of func:
6006: $     PetscErrorCode func(TS ts,PetscReal time,Vec state,PetscBool reject)

6008: +   ts - the TS context
6009: .   time - the current time (of the stage)
6010: .   state - the state to check if it is valid
6011: -   reject - (output parameter) PETSC_FALSE if the state is acceptable, PETSC_TRUE if not acceptable

6013:     Level: intermediate

6015:     Notes:
6016:       If an implicit ODE solver is being used then, in addition to providing this routine, the
6017:       user's code should call SNESSetFunctionDomainError() when domain errors occur during
6018:       function evaluations where the functions are provided by TSSetIFunction() or TSSetRHSFunction().
6019:       Use TSGetSNES() to obtain the SNES object

6021:     Developer Notes:
6022:       The naming of this function is inconsistent with the SNESSetFunctionDomainError()
6023:       since one takes a function pointer and the other does not.

6025: .seealso: TSAdaptCheckStage(), TSFunctionDomainError(), SNESSetFunctionDomainError(), TSGetSNES()
6026: @*/

6028: PetscErrorCode TSSetFunctionDomainError(TS ts, PetscErrorCode (*func)(TS,PetscReal,Vec,PetscBool*))
6029: {
6032:   ts->functiondomainerror = func;
6033:   return(0);
6034: }

6036: /*@
6037:     TSFunctionDomainError - Checks if the current state is valid

6039:     Input Parameters:
6040: +    ts - the TS context
6041: .    stagetime - time of the simulation
6042: -    Y - state vector to check.

6044:     Output Parameter:
6045: .    accept - Set to PETSC_FALSE if the current state vector is valid.

6047:     Note:
6048:     This function is called by the TS integration routines and calls the user provided function (set with TSSetFunctionDomainError())
6049:     to check if the current state is valid.

6051:     Level: developer

6053: .seealso: TSSetFunctionDomainError()
6054: @*/
6055: PetscErrorCode TSFunctionDomainError(TS ts,PetscReal stagetime,Vec Y,PetscBool* accept)
6056: {
6059:   *accept = PETSC_TRUE;
6060:   if (ts->functiondomainerror) {
6061:     PetscStackCallStandard((*ts->functiondomainerror),(ts,stagetime,Y,accept));
6062:   }
6063:   return(0);
6064: }

6066: /*@C
6067:   TSClone - This function clones a time step object.

6069:   Collective

6071:   Input Parameter:
6072: . tsin    - The input TS

6074:   Output Parameter:
6075: . tsout   - The output TS (cloned)

6077:   Notes:
6078:   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.

6080:   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);

6082:   Level: developer

6084: .seealso: TSCreate(), TSSetType(), TSSetUp(), TSDestroy(), TSSetProblemType()
6085: @*/
6086: PetscErrorCode  TSClone(TS tsin, TS *tsout)
6087: {
6088:   TS             t;
6090:   SNES           snes_start;
6091:   DM             dm;
6092:   TSType         type;

6096:   *tsout = NULL;

6098:   PetscHeaderCreate(t, TS_CLASSID, "TS", "Time stepping", "TS", PetscObjectComm((PetscObject)tsin), TSDestroy, TSView);

6100:   /* General TS description */
6101:   t->numbermonitors    = 0;
6102:   t->monitorFrequency  = 1;
6103:   t->setupcalled       = 0;
6104:   t->ksp_its           = 0;
6105:   t->snes_its          = 0;
6106:   t->nwork             = 0;
6107:   t->rhsjacobian.time  = PETSC_MIN_REAL;
6108:   t->rhsjacobian.scale = 1.;
6109:   t->ijacobian.shift   = 1.;

6111:   TSGetSNES(tsin,&snes_start);
6112:   TSSetSNES(t,snes_start);

6114:   TSGetDM(tsin,&dm);
6115:   TSSetDM(t,dm);

6117:   t->adapt = tsin->adapt;
6118:   PetscObjectReference((PetscObject)t->adapt);

6120:   t->trajectory = tsin->trajectory;
6121:   PetscObjectReference((PetscObject)t->trajectory);

6123:   t->event = tsin->event;
6124:   if (t->event) t->event->refct++;

6126:   t->problem_type      = tsin->problem_type;
6127:   t->ptime             = tsin->ptime;
6128:   t->ptime_prev        = tsin->ptime_prev;
6129:   t->time_step         = tsin->time_step;
6130:   t->max_time          = tsin->max_time;
6131:   t->steps             = tsin->steps;
6132:   t->max_steps         = tsin->max_steps;
6133:   t->equation_type     = tsin->equation_type;
6134:   t->atol              = tsin->atol;
6135:   t->rtol              = tsin->rtol;
6136:   t->max_snes_failures = tsin->max_snes_failures;
6137:   t->max_reject        = tsin->max_reject;
6138:   t->errorifstepfailed = tsin->errorifstepfailed;

6140:   TSGetType(tsin,&type);
6141:   TSSetType(t,type);

6143:   t->vec_sol           = NULL;

6145:   t->cfltime          = tsin->cfltime;
6146:   t->cfltime_local    = tsin->cfltime_local;
6147:   t->exact_final_time = tsin->exact_final_time;

6149:   PetscMemcpy(t->ops,tsin->ops,sizeof(struct _TSOps));

6151:   if (((PetscObject)tsin)->fortran_func_pointers) {
6152:     PetscInt i;
6153:     PetscMalloc((10)*sizeof(void(*)(void)),&((PetscObject)t)->fortran_func_pointers);
6154:     for (i=0; i<10; i++) {
6155:       ((PetscObject)t)->fortran_func_pointers[i] = ((PetscObject)tsin)->fortran_func_pointers[i];
6156:     }
6157:   }
6158:   *tsout = t;
6159:   return(0);
6160: }

6162: static PetscErrorCode RHSWrapperFunction_TSRHSJacobianTest(void* ctx,Vec x,Vec y)
6163: {
6165:   TS             ts = (TS) ctx;

6168:   TSComputeRHSFunction(ts,0,x,y);
6169:   return(0);
6170: }

6172: /*@
6173:     TSRHSJacobianTest - Compares the multiply routine provided to the MATSHELL with differencing on the TS given RHS function.

6175:    Logically Collective on TS

6177:     Input Parameters:
6178:     TS - the time stepping routine

6180:    Output Parameter:
6181: .   flg - PETSC_TRUE if the multiply is likely correct

6183:    Options Database:
6184:  .   -ts_rhs_jacobian_test_mult -mat_shell_test_mult_view - run the test at each timestep of the integrator

6186:    Level: advanced

6188:    Notes:
6189:     This only works for problems defined only the RHS function and Jacobian NOT IFunction and IJacobian

6191: .seealso: MatCreateShell(), MatShellGetContext(), MatShellGetOperation(), MatShellTestMultTranspose(), TSRHSJacobianTestTranspose()
6192: @*/
6193: PetscErrorCode  TSRHSJacobianTest(TS ts,PetscBool *flg)
6194: {
6195:   Mat            J,B;
6197:   TSRHSJacobian  func;
6198:   void*          ctx;

6201:   TSGetRHSJacobian(ts,&J,&B,&func,&ctx);
6202:   (*func)(ts,0.0,ts->vec_sol,J,B,ctx);
6203:   MatShellTestMult(J,RHSWrapperFunction_TSRHSJacobianTest,ts->vec_sol,ts,flg);
6204:   return(0);
6205: }

6207: /*@C
6208:     TSRHSJacobianTestTranspose - Compares the multiply transpose routine provided to the MATSHELL with differencing on the TS given RHS function.

6210:    Logically Collective on TS

6212:     Input Parameters:
6213:     TS - the time stepping routine

6215:    Output Parameter:
6216: .   flg - PETSC_TRUE if the multiply is likely correct

6218:    Options Database:
6219: .   -ts_rhs_jacobian_test_mult_transpose -mat_shell_test_mult_transpose_view - run the test at each timestep of the integrator

6221:    Notes:
6222:     This only works for problems defined only the RHS function and Jacobian NOT IFunction and IJacobian

6224:    Level: advanced

6226: .seealso: MatCreateShell(), MatShellGetContext(), MatShellGetOperation(), MatShellTestMultTranspose(), TSRHSJacobianTest()
6227: @*/
6228: PetscErrorCode  TSRHSJacobianTestTranspose(TS ts,PetscBool *flg)
6229: {
6230:   Mat            J,B;
6232:   void           *ctx;
6233:   TSRHSJacobian  func;

6236:   TSGetRHSJacobian(ts,&J,&B,&func,&ctx);
6237:   (*func)(ts,0.0,ts->vec_sol,J,B,ctx);
6238:   MatShellTestMultTranspose(J,RHSWrapperFunction_TSRHSJacobianTest,ts->vec_sol,ts,flg);
6239:   return(0);
6240: }

6242: /*@
6243:   TSSetUseSplitRHSFunction - Use the split RHSFunction when a multirate method is used.

6245:   Logically collective

6247:   Input Parameters:
6248: +  ts - timestepping context
6249: -  use_splitrhsfunction - PETSC_TRUE indicates that the split RHSFunction will be used

6251:   Options Database:
6252: .   -ts_use_splitrhsfunction - <true,false>

6254:   Notes:
6255:     This is only useful for multirate methods

6257:   Level: intermediate

6259: .seealso: TSGetUseSplitRHSFunction()
6260: @*/
6261: PetscErrorCode TSSetUseSplitRHSFunction(TS ts, PetscBool use_splitrhsfunction)
6262: {
6265:   ts->use_splitrhsfunction = use_splitrhsfunction;
6266:   return(0);
6267: }

6269: /*@
6270:   TSGetUseSplitRHSFunction - Gets whether to use the split RHSFunction when a multirate method is used.

6272:   Not collective

6274:   Input Parameter:
6275: .  ts - timestepping context

6277:   Output Parameter:
6278: .  use_splitrhsfunction - PETSC_TRUE indicates that the split RHSFunction will be used

6280:   Level: intermediate

6282: .seealso: TSSetUseSplitRHSFunction()
6283: @*/
6284: PetscErrorCode TSGetUseSplitRHSFunction(TS ts, PetscBool *use_splitrhsfunction)
6285: {
6288:   *use_splitrhsfunction = ts->use_splitrhsfunction;
6289:   return(0);
6290: }

6292: /*@
6293:     TSSetMatStructure - sets the relationship between the nonzero structure of the RHS Jacobian matrix to the IJacobian matrix.

6295:    Logically  Collective on ts

6297:    Input Parameters:
6298: +  ts - the time-stepper
6299: -  str - the structure (the default is UNKNOWN_NONZERO_PATTERN)

6301:    Level: intermediate

6303:    Notes:
6304:      When the relationship between the nonzero structures is known and supplied the solution process can be much faster

6306: .seealso: MatAXPY(), MatStructure
6307:  @*/
6308: PetscErrorCode TSSetMatStructure(TS ts,MatStructure str)
6309: {
6312:   ts->axpy_pattern = str;
6313:   return(0);
6314: }