Actual source code: ts.c
petsc-3.14.0 2020-09-29
1: #include <petsc/private/tsimpl.h>
2: #include <petscdmshell.h>
3: #include <petscdmda.h>
4: #include <petscviewer.h>
5: #include <petscdraw.h>
6: #include <petscconvest.h>
8: #define SkipSmallValue(a,b,tol) if (PetscAbsScalar(a)< tol || PetscAbsScalar(b)< tol) continue;
10: /* Logging support */
11: PetscClassId TS_CLASSID, DMTS_CLASSID;
12: PetscLogEvent TS_Step, TS_PseudoComputeTimeStep, TS_FunctionEval, TS_JacobianEval;
14: const char *const TSExactFinalTimeOptions[] = {"UNSPECIFIED","STEPOVER","INTERPOLATE","MATCHSTEP","TSExactFinalTimeOption","TS_EXACTFINALTIME_",NULL};
17: /*@C
18: TSMonitorSetFromOptions - Sets a monitor function and viewer appropriate for the type indicated by the user
20: Collective on TS
22: Input Parameters:
23: + ts - TS object you wish to monitor
24: . name - the monitor type one is seeking
25: . help - message indicating what monitoring is done
26: . manual - manual page for the monitor
27: . monitor - the monitor function
28: - monitorsetup - a function that is called once ONLY if the user selected this monitor that may set additional features of the TS or PetscViewer objects
30: Level: developer
32: .seealso: PetscOptionsGetViewer(), PetscOptionsGetReal(), PetscOptionsHasName(), PetscOptionsGetString(),
33: PetscOptionsGetIntArray(), PetscOptionsGetRealArray(), PetscOptionsBool()
34: PetscOptionsInt(), PetscOptionsString(), PetscOptionsReal(), PetscOptionsBool(),
35: PetscOptionsName(), PetscOptionsBegin(), PetscOptionsEnd(), PetscOptionsHead(),
36: PetscOptionsStringArray(),PetscOptionsRealArray(), PetscOptionsScalar(),
37: PetscOptionsBoolGroupBegin(), PetscOptionsBoolGroup(), PetscOptionsBoolGroupEnd(),
38: PetscOptionsFList(), PetscOptionsEList()
39: @*/
40: PetscErrorCode TSMonitorSetFromOptions(TS ts,const char name[],const char help[], const char manual[],PetscErrorCode (*monitor)(TS,PetscInt,PetscReal,Vec,PetscViewerAndFormat*),PetscErrorCode (*monitorsetup)(TS,PetscViewerAndFormat*))
41: {
42: PetscErrorCode ierr;
43: PetscViewer viewer;
44: PetscViewerFormat format;
45: PetscBool flg;
48: PetscOptionsGetViewer(PetscObjectComm((PetscObject)ts),((PetscObject) ts)->options,((PetscObject)ts)->prefix,name,&viewer,&format,&flg);
49: if (flg) {
50: PetscViewerAndFormat *vf;
51: PetscViewerAndFormatCreate(viewer,format,&vf);
52: PetscObjectDereference((PetscObject)viewer);
53: if (monitorsetup) {
54: (*monitorsetup)(ts,vf);
55: }
56: TSMonitorSet(ts,(PetscErrorCode (*)(TS,PetscInt,PetscReal,Vec,void*))monitor,vf,(PetscErrorCode (*)(void**))PetscViewerAndFormatDestroy);
57: }
58: return(0);
59: }
61: static PetscErrorCode TSAdaptSetDefaultType(TSAdapt adapt,TSAdaptType default_type)
62: {
68: if (!((PetscObject)adapt)->type_name) {
69: TSAdaptSetType(adapt,default_type);
70: }
71: return(0);
72: }
74: /*@
75: TSSetFromOptions - Sets various TS parameters from user options.
77: Collective on TS
79: Input Parameter:
80: . ts - the TS context obtained from TSCreate()
82: Options Database Keys:
83: + -ts_type <type> - TSEULER, TSBEULER, TSSUNDIALS, TSPSEUDO, TSCN, TSRK, TSTHETA, TSALPHA, TSGLLE, TSSSP, TSGLEE, TSBSYMP
84: . -ts_save_trajectory - checkpoint the solution at each time-step
85: . -ts_max_time <time> - maximum time to compute to
86: . -ts_max_steps <steps> - maximum number of time-steps to take
87: . -ts_init_time <time> - initial time to start computation
88: . -ts_final_time <time> - final time to compute to (deprecated: use -ts_max_time)
89: . -ts_dt <dt> - initial time step
90: . -ts_exact_final_time <stepover,interpolate,matchstep> - whether to stop at the exact given final time and how to compute the solution at that ti,e
91: . -ts_max_snes_failures <maxfailures> - Maximum number of nonlinear solve failures allowed
92: . -ts_max_reject <maxrejects> - Maximum number of step rejections before step fails
93: . -ts_error_if_step_fails <true,false> - Error if no step succeeds
94: . -ts_rtol <rtol> - relative tolerance for local truncation error
95: . -ts_atol <atol> Absolute tolerance for local truncation error
96: . -ts_rhs_jacobian_test_mult -mat_shell_test_mult_view - test the Jacobian at each iteration against finite difference with RHS function
97: . -ts_rhs_jacobian_test_mult_transpose -mat_shell_test_mult_transpose_view - test the Jacobian at each iteration against finite difference with RHS function
98: . -ts_adjoint_solve <yes,no> After solving the ODE/DAE solve the adjoint problem (requires -ts_save_trajectory)
99: . -ts_fd_color - Use finite differences with coloring to compute IJacobian
100: . -ts_monitor - print information at each timestep
101: . -ts_monitor_lg_solution - Monitor solution graphically
102: . -ts_monitor_lg_error - Monitor error graphically
103: . -ts_monitor_error - Monitors norm of error
104: . -ts_monitor_lg_timestep - Monitor timestep size graphically
105: . -ts_monitor_lg_timestep_log - Monitor log timestep size graphically
106: . -ts_monitor_lg_snes_iterations - Monitor number nonlinear iterations for each timestep graphically
107: . -ts_monitor_lg_ksp_iterations - Monitor number nonlinear iterations for each timestep graphically
108: . -ts_monitor_sp_eig - Monitor eigenvalues of linearized operator graphically
109: . -ts_monitor_draw_solution - Monitor solution graphically
110: . -ts_monitor_draw_solution_phase <xleft,yleft,xright,yright> - Monitor solution graphically with phase diagram, requires problem with exactly 2 degrees of freedom
111: . -ts_monitor_draw_error - Monitor error graphically, requires use to have provided TSSetSolutionFunction()
112: . -ts_monitor_solution [ascii binary draw][:filename][:viewerformat] - monitors the solution at each timestep
113: . -ts_monitor_solution_vtk <filename.vts,filename.vtu> - Save each time step to a binary file, use filename-%%03D.vts (filename-%%03D.vtu)
114: - -ts_monitor_envelope - determine maximum and minimum value of each component of the solution over the solution time
116: Notes:
117: See SNESSetFromOptions() and KSPSetFromOptions() for how to control the nonlinear and linear solves used by the time-stepper.
119: Certain SNES options get reset for each new nonlinear solver, for example -snes_lag_jacobian <its> and -snes_lag_preconditioner <its>, in order
120: to retain them over the multiple nonlinear solves that TS uses you mush also provide -snes_lag_jacobian_persists true and
121: -snes_lag_preconditioner_persists true
123: Developer Note:
124: We should unify all the -ts_monitor options in the way that -xxx_view has been unified
126: Level: beginner
128: .seealso: TSGetType()
129: @*/
130: PetscErrorCode TSSetFromOptions(TS ts)
131: {
132: PetscBool opt,flg,tflg;
133: PetscErrorCode ierr;
134: char monfilename[PETSC_MAX_PATH_LEN];
135: PetscReal time_step;
136: TSExactFinalTimeOption eftopt;
137: char dir[16];
138: TSIFunction ifun;
139: const char *defaultType;
140: char typeName[256];
145: TSRegisterAll();
146: TSGetIFunction(ts,NULL,&ifun,NULL);
148: PetscObjectOptionsBegin((PetscObject)ts);
149: if (((PetscObject)ts)->type_name) defaultType = ((PetscObject)ts)->type_name;
150: else defaultType = ifun ? TSBEULER : TSEULER;
151: PetscOptionsFList("-ts_type","TS method","TSSetType",TSList,defaultType,typeName,256,&opt);
152: if (opt) {
153: TSSetType(ts,typeName);
154: } else {
155: TSSetType(ts,defaultType);
156: }
158: /* Handle generic TS options */
159: PetscOptionsDeprecated("-ts_final_time","-ts_max_time","3.10",NULL);
160: PetscOptionsReal("-ts_max_time","Maximum time to run to","TSSetMaxTime",ts->max_time,&ts->max_time,NULL);
161: PetscOptionsInt("-ts_max_steps","Maximum number of time steps","TSSetMaxSteps",ts->max_steps,&ts->max_steps,NULL);
162: PetscOptionsReal("-ts_init_time","Initial time","TSSetTime",ts->ptime,&ts->ptime,NULL);
163: PetscOptionsReal("-ts_dt","Initial time step","TSSetTimeStep",ts->time_step,&time_step,&flg);
164: if (flg) {TSSetTimeStep(ts,time_step);}
165: PetscOptionsEnum("-ts_exact_final_time","Option for handling of final time step","TSSetExactFinalTime",TSExactFinalTimeOptions,(PetscEnum)ts->exact_final_time,(PetscEnum*)&eftopt,&flg);
166: if (flg) {TSSetExactFinalTime(ts,eftopt);}
167: PetscOptionsInt("-ts_max_snes_failures","Maximum number of nonlinear solve failures","TSSetMaxSNESFailures",ts->max_snes_failures,&ts->max_snes_failures,NULL);
168: PetscOptionsInt("-ts_max_reject","Maximum number of step rejections before step fails","TSSetMaxStepRejections",ts->max_reject,&ts->max_reject,NULL);
169: PetscOptionsBool("-ts_error_if_step_fails","Error if no step succeeds","TSSetErrorIfStepFails",ts->errorifstepfailed,&ts->errorifstepfailed,NULL);
170: PetscOptionsReal("-ts_rtol","Relative tolerance for local truncation error","TSSetTolerances",ts->rtol,&ts->rtol,NULL);
171: PetscOptionsReal("-ts_atol","Absolute tolerance for local truncation error","TSSetTolerances",ts->atol,&ts->atol,NULL);
173: PetscOptionsBool("-ts_rhs_jacobian_test_mult","Test the RHS Jacobian for consistency with RHS at each solve ","None",ts->testjacobian,&ts->testjacobian,NULL);
174: PetscOptionsBool("-ts_rhs_jacobian_test_mult_transpose","Test the RHS Jacobian transpose for consistency with RHS at each solve ","None",ts->testjacobiantranspose,&ts->testjacobiantranspose,NULL);
175: PetscOptionsBool("-ts_use_splitrhsfunction","Use the split RHS function for multirate solvers ","TSSetUseSplitRHSFunction",ts->use_splitrhsfunction,&ts->use_splitrhsfunction,NULL);
176: #if defined(PETSC_HAVE_SAWS)
177: {
178: PetscBool set;
179: flg = PETSC_FALSE;
180: PetscOptionsBool("-ts_saws_block","Block for SAWs memory snooper at end of TSSolve","PetscObjectSAWsBlock",((PetscObject)ts)->amspublishblock,&flg,&set);
181: if (set) {
182: PetscObjectSAWsSetBlock((PetscObject)ts,flg);
183: }
184: }
185: #endif
187: /* Monitor options */
188: TSMonitorSetFromOptions(ts,"-ts_monitor","Monitor time and timestep size","TSMonitorDefault",TSMonitorDefault,NULL);
189: TSMonitorSetFromOptions(ts,"-ts_monitor_extreme","Monitor extreme values of the solution","TSMonitorExtreme",TSMonitorExtreme,NULL);
190: TSMonitorSetFromOptions(ts,"-ts_monitor_solution","View the solution at each timestep","TSMonitorSolution",TSMonitorSolution,NULL);
192: PetscOptionsString("-ts_monitor_python","Use Python function","TSMonitorSet",NULL,monfilename,sizeof(monfilename),&flg);
193: if (flg) {PetscPythonMonitorSet((PetscObject)ts,monfilename);}
195: PetscOptionsName("-ts_monitor_lg_solution","Monitor solution graphically","TSMonitorLGSolution",&opt);
196: if (opt) {
197: PetscInt howoften = 1;
198: DM dm;
199: PetscBool net;
201: PetscOptionsInt("-ts_monitor_lg_solution","Monitor solution graphically","TSMonitorLGSolution",howoften,&howoften,NULL);
202: TSGetDM(ts,&dm);
203: PetscObjectTypeCompare((PetscObject)dm,DMNETWORK,&net);
204: if (net) {
205: TSMonitorLGCtxNetwork ctx;
206: TSMonitorLGCtxNetworkCreate(ts,NULL,NULL,PETSC_DECIDE,PETSC_DECIDE,600,400,howoften,&ctx);
207: TSMonitorSet(ts,TSMonitorLGCtxNetworkSolution,ctx,(PetscErrorCode (*)(void**))TSMonitorLGCtxNetworkDestroy);
208: PetscOptionsBool("-ts_monitor_lg_solution_semilogy","Plot the solution with a semi-log axis","",ctx->semilogy,&ctx->semilogy,NULL);
209: } else {
210: TSMonitorLGCtx ctx;
211: TSMonitorLGCtxCreate(PETSC_COMM_SELF,NULL,NULL,PETSC_DECIDE,PETSC_DECIDE,400,300,howoften,&ctx);
212: TSMonitorSet(ts,TSMonitorLGSolution,ctx,(PetscErrorCode (*)(void**))TSMonitorLGCtxDestroy);
213: }
214: }
216: PetscOptionsName("-ts_monitor_lg_error","Monitor error graphically","TSMonitorLGError",&opt);
217: if (opt) {
218: TSMonitorLGCtx ctx;
219: PetscInt howoften = 1;
221: PetscOptionsInt("-ts_monitor_lg_error","Monitor error graphically","TSMonitorLGError",howoften,&howoften,NULL);
222: TSMonitorLGCtxCreate(PETSC_COMM_SELF,NULL,NULL,PETSC_DECIDE,PETSC_DECIDE,400,300,howoften,&ctx);
223: TSMonitorSet(ts,TSMonitorLGError,ctx,(PetscErrorCode (*)(void**))TSMonitorLGCtxDestroy);
224: }
225: TSMonitorSetFromOptions(ts,"-ts_monitor_error","View the error at each timestep","TSMonitorError",TSMonitorError,NULL);
227: PetscOptionsName("-ts_monitor_lg_timestep","Monitor timestep size graphically","TSMonitorLGTimeStep",&opt);
228: if (opt) {
229: TSMonitorLGCtx ctx;
230: PetscInt howoften = 1;
232: PetscOptionsInt("-ts_monitor_lg_timestep","Monitor timestep size graphically","TSMonitorLGTimeStep",howoften,&howoften,NULL);
233: TSMonitorLGCtxCreate(PetscObjectComm((PetscObject)ts),NULL,NULL,PETSC_DECIDE,PETSC_DECIDE,400,300,howoften,&ctx);
234: TSMonitorSet(ts,TSMonitorLGTimeStep,ctx,(PetscErrorCode (*)(void**))TSMonitorLGCtxDestroy);
235: }
236: PetscOptionsName("-ts_monitor_lg_timestep_log","Monitor log timestep size graphically","TSMonitorLGTimeStep",&opt);
237: if (opt) {
238: TSMonitorLGCtx ctx;
239: PetscInt howoften = 1;
241: PetscOptionsInt("-ts_monitor_lg_timestep_log","Monitor log timestep size graphically","TSMonitorLGTimeStep",howoften,&howoften,NULL);
242: TSMonitorLGCtxCreate(PetscObjectComm((PetscObject)ts),NULL,NULL,PETSC_DECIDE,PETSC_DECIDE,400,300,howoften,&ctx);
243: TSMonitorSet(ts,TSMonitorLGTimeStep,ctx,(PetscErrorCode (*)(void**))TSMonitorLGCtxDestroy);
244: ctx->semilogy = PETSC_TRUE;
245: }
247: PetscOptionsName("-ts_monitor_lg_snes_iterations","Monitor number nonlinear iterations for each timestep graphically","TSMonitorLGSNESIterations",&opt);
248: if (opt) {
249: TSMonitorLGCtx ctx;
250: PetscInt howoften = 1;
252: PetscOptionsInt("-ts_monitor_lg_snes_iterations","Monitor number nonlinear iterations for each timestep graphically","TSMonitorLGSNESIterations",howoften,&howoften,NULL);
253: TSMonitorLGCtxCreate(PetscObjectComm((PetscObject)ts),NULL,NULL,PETSC_DECIDE,PETSC_DECIDE,400,300,howoften,&ctx);
254: TSMonitorSet(ts,TSMonitorLGSNESIterations,ctx,(PetscErrorCode (*)(void**))TSMonitorLGCtxDestroy);
255: }
256: PetscOptionsName("-ts_monitor_lg_ksp_iterations","Monitor number nonlinear iterations for each timestep graphically","TSMonitorLGKSPIterations",&opt);
257: if (opt) {
258: TSMonitorLGCtx ctx;
259: PetscInt howoften = 1;
261: PetscOptionsInt("-ts_monitor_lg_ksp_iterations","Monitor number nonlinear iterations for each timestep graphically","TSMonitorLGKSPIterations",howoften,&howoften,NULL);
262: TSMonitorLGCtxCreate(PetscObjectComm((PetscObject)ts),NULL,NULL,PETSC_DECIDE,PETSC_DECIDE,400,300,howoften,&ctx);
263: TSMonitorSet(ts,TSMonitorLGKSPIterations,ctx,(PetscErrorCode (*)(void**))TSMonitorLGCtxDestroy);
264: }
265: PetscOptionsName("-ts_monitor_sp_eig","Monitor eigenvalues of linearized operator graphically","TSMonitorSPEig",&opt);
266: if (opt) {
267: TSMonitorSPEigCtx ctx;
268: PetscInt howoften = 1;
270: PetscOptionsInt("-ts_monitor_sp_eig","Monitor eigenvalues of linearized operator graphically","TSMonitorSPEig",howoften,&howoften,NULL);
271: TSMonitorSPEigCtxCreate(PETSC_COMM_SELF,NULL,NULL,PETSC_DECIDE,PETSC_DECIDE,300,300,howoften,&ctx);
272: TSMonitorSet(ts,TSMonitorSPEig,ctx,(PetscErrorCode (*)(void**))TSMonitorSPEigCtxDestroy);
273: }
274: PetscOptionsName("-ts_monitor_sp_swarm","Display particle phase from the DMSwarm","TSMonitorSPSwarm",&opt);
275: if (opt) {
276: TSMonitorSPCtx ctx;
277: PetscInt howoften = 1;
278: PetscOptionsInt("-ts_monitor_sp_swarm","Display particles phase from the DMSwarm","TSMonitorSPSwarm",howoften,&howoften,NULL);
279: TSMonitorSPCtxCreate(PETSC_COMM_SELF, NULL, NULL, PETSC_DECIDE, PETSC_DECIDE, 300, 300, howoften, &ctx);
280: TSMonitorSet(ts, TSMonitorSPSwarmSolution, ctx, (PetscErrorCode (*)(void**))TSMonitorSPCtxDestroy);
281: }
282: opt = PETSC_FALSE;
283: PetscOptionsName("-ts_monitor_draw_solution","Monitor solution graphically","TSMonitorDrawSolution",&opt);
284: if (opt) {
285: TSMonitorDrawCtx ctx;
286: PetscInt howoften = 1;
288: PetscOptionsInt("-ts_monitor_draw_solution","Monitor solution graphically","TSMonitorDrawSolution",howoften,&howoften,NULL);
289: TSMonitorDrawCtxCreate(PetscObjectComm((PetscObject)ts),NULL,"Computed Solution",PETSC_DECIDE,PETSC_DECIDE,300,300,howoften,&ctx);
290: TSMonitorSet(ts,TSMonitorDrawSolution,ctx,(PetscErrorCode (*)(void**))TSMonitorDrawCtxDestroy);
291: }
292: opt = PETSC_FALSE;
293: PetscOptionsName("-ts_monitor_draw_solution_phase","Monitor solution graphically","TSMonitorDrawSolutionPhase",&opt);
294: if (opt) {
295: TSMonitorDrawCtx ctx;
296: PetscReal bounds[4];
297: PetscInt n = 4;
298: PetscDraw draw;
299: PetscDrawAxis axis;
301: PetscOptionsRealArray("-ts_monitor_draw_solution_phase","Monitor solution graphically","TSMonitorDrawSolutionPhase",bounds,&n,NULL);
302: if (n != 4) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_ARG_WRONG,"Must provide bounding box of phase field");
303: TSMonitorDrawCtxCreate(PetscObjectComm((PetscObject)ts),NULL,NULL,PETSC_DECIDE,PETSC_DECIDE,300,300,1,&ctx);
304: PetscViewerDrawGetDraw(ctx->viewer,0,&draw);
305: PetscViewerDrawGetDrawAxis(ctx->viewer,0,&axis);
306: PetscDrawAxisSetLimits(axis,bounds[0],bounds[2],bounds[1],bounds[3]);
307: PetscDrawAxisSetLabels(axis,"Phase Diagram","Variable 1","Variable 2");
308: TSMonitorSet(ts,TSMonitorDrawSolutionPhase,ctx,(PetscErrorCode (*)(void**))TSMonitorDrawCtxDestroy);
309: }
310: opt = PETSC_FALSE;
311: PetscOptionsName("-ts_monitor_draw_error","Monitor error graphically","TSMonitorDrawError",&opt);
312: if (opt) {
313: TSMonitorDrawCtx ctx;
314: PetscInt howoften = 1;
316: PetscOptionsInt("-ts_monitor_draw_error","Monitor error graphically","TSMonitorDrawError",howoften,&howoften,NULL);
317: TSMonitorDrawCtxCreate(PetscObjectComm((PetscObject)ts),NULL,"Error",PETSC_DECIDE,PETSC_DECIDE,300,300,howoften,&ctx);
318: TSMonitorSet(ts,TSMonitorDrawError,ctx,(PetscErrorCode (*)(void**))TSMonitorDrawCtxDestroy);
319: }
320: opt = PETSC_FALSE;
321: PetscOptionsName("-ts_monitor_draw_solution_function","Monitor solution provided by TSMonitorSetSolutionFunction() graphically","TSMonitorDrawSolutionFunction",&opt);
322: if (opt) {
323: TSMonitorDrawCtx ctx;
324: PetscInt howoften = 1;
326: PetscOptionsInt("-ts_monitor_draw_solution_function","Monitor solution provided by TSMonitorSetSolutionFunction() graphically","TSMonitorDrawSolutionFunction",howoften,&howoften,NULL);
327: TSMonitorDrawCtxCreate(PetscObjectComm((PetscObject)ts),NULL,"Solution provided by user function",PETSC_DECIDE,PETSC_DECIDE,300,300,howoften,&ctx);
328: TSMonitorSet(ts,TSMonitorDrawSolutionFunction,ctx,(PetscErrorCode (*)(void**))TSMonitorDrawCtxDestroy);
329: }
331: opt = PETSC_FALSE;
332: PetscOptionsString("-ts_monitor_solution_vtk","Save each time step to a binary file, use filename-%%03D.vts","TSMonitorSolutionVTK",NULL,monfilename,sizeof(monfilename),&flg);
333: if (flg) {
334: const char *ptr,*ptr2;
335: char *filetemplate;
336: if (!monfilename[0]) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_USER,"-ts_monitor_solution_vtk requires a file template, e.g. filename-%%03D.vts");
337: /* Do some cursory validation of the input. */
338: PetscStrstr(monfilename,"%",(char**)&ptr);
339: if (!ptr) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_USER,"-ts_monitor_solution_vtk requires a file template, e.g. filename-%%03D.vts");
340: for (ptr++; ptr && *ptr; ptr++) {
341: PetscStrchr("DdiouxX",*ptr,(char**)&ptr2);
342: if (!ptr2 && (*ptr < '0' || '9' < *ptr)) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_USER,"Invalid file template argument to -ts_monitor_solution_vtk, should look like filename-%%03D.vts");
343: if (ptr2) break;
344: }
345: PetscStrallocpy(monfilename,&filetemplate);
346: TSMonitorSet(ts,TSMonitorSolutionVTK,filetemplate,(PetscErrorCode (*)(void**))TSMonitorSolutionVTKDestroy);
347: }
349: PetscOptionsString("-ts_monitor_dmda_ray","Display a ray of the solution","None","y=0",dir,sizeof(dir),&flg);
350: if (flg) {
351: TSMonitorDMDARayCtx *rayctx;
352: int ray = 0;
353: DMDirection ddir;
354: DM da;
355: PetscMPIInt rank;
357: if (dir[1] != '=') SETERRQ1(PetscObjectComm((PetscObject)ts),PETSC_ERR_ARG_WRONG,"Unknown ray %s",dir);
358: if (dir[0] == 'x') ddir = DM_X;
359: else if (dir[0] == 'y') ddir = DM_Y;
360: else SETERRQ1(PetscObjectComm((PetscObject)ts),PETSC_ERR_ARG_WRONG,"Unknown ray %s",dir);
361: sscanf(dir+2,"%d",&ray);
363: PetscInfo2(((PetscObject)ts),"Displaying DMDA ray %c = %d\n",dir[0],ray);
364: PetscNew(&rayctx);
365: TSGetDM(ts,&da);
366: DMDAGetRay(da,ddir,ray,&rayctx->ray,&rayctx->scatter);
367: MPI_Comm_rank(PetscObjectComm((PetscObject)ts),&rank);
368: if (!rank) {
369: PetscViewerDrawOpen(PETSC_COMM_SELF,NULL,NULL,0,0,600,300,&rayctx->viewer);
370: }
371: rayctx->lgctx = NULL;
372: TSMonitorSet(ts,TSMonitorDMDARay,rayctx,TSMonitorDMDARayDestroy);
373: }
374: PetscOptionsString("-ts_monitor_lg_dmda_ray","Display a ray of the solution","None","x=0",dir,sizeof(dir),&flg);
375: if (flg) {
376: TSMonitorDMDARayCtx *rayctx;
377: int ray = 0;
378: DMDirection ddir;
379: DM da;
380: PetscInt howoften = 1;
382: if (dir[1] != '=') SETERRQ1(PetscObjectComm((PetscObject) ts), PETSC_ERR_ARG_WRONG, "Malformed ray %s", dir);
383: if (dir[0] == 'x') ddir = DM_X;
384: else if (dir[0] == 'y') ddir = DM_Y;
385: else SETERRQ1(PetscObjectComm((PetscObject) ts), PETSC_ERR_ARG_WRONG, "Unknown ray direction %s", dir);
386: sscanf(dir+2, "%d", &ray);
388: PetscInfo2(((PetscObject) ts),"Displaying LG DMDA ray %c = %d\n", dir[0], ray);
389: PetscNew(&rayctx);
390: TSGetDM(ts, &da);
391: DMDAGetRay(da, ddir, ray, &rayctx->ray, &rayctx->scatter);
392: TSMonitorLGCtxCreate(PETSC_COMM_SELF,NULL,NULL,PETSC_DECIDE,PETSC_DECIDE,600,400,howoften,&rayctx->lgctx);
393: TSMonitorSet(ts, TSMonitorLGDMDARay, rayctx, TSMonitorDMDARayDestroy);
394: }
396: PetscOptionsName("-ts_monitor_envelope","Monitor maximum and minimum value of each component of the solution","TSMonitorEnvelope",&opt);
397: if (opt) {
398: TSMonitorEnvelopeCtx ctx;
400: TSMonitorEnvelopeCtxCreate(ts,&ctx);
401: TSMonitorSet(ts,TSMonitorEnvelope,ctx,(PetscErrorCode (*)(void**))TSMonitorEnvelopeCtxDestroy);
402: }
404: flg = PETSC_FALSE;
405: PetscOptionsBool("-ts_fd_color", "Use finite differences with coloring to compute IJacobian", "TSComputeJacobianDefaultColor", flg, &flg, NULL);
406: if (flg) {
407: DM dm;
408: DMTS tdm;
410: TSGetDM(ts, &dm);
411: DMGetDMTS(dm, &tdm);
412: tdm->ijacobianctx = NULL;
413: TSSetIJacobian(ts, NULL, NULL, TSComputeIJacobianDefaultColor, NULL);
414: PetscInfo(ts, "Setting default finite difference coloring Jacobian matrix\n");
415: }
417: /* Handle specific TS options */
418: if (ts->ops->setfromoptions) {
419: (*ts->ops->setfromoptions)(PetscOptionsObject,ts);
420: }
422: /* Handle TSAdapt options */
423: TSGetAdapt(ts,&ts->adapt);
424: TSAdaptSetDefaultType(ts->adapt,ts->default_adapt_type);
425: TSAdaptSetFromOptions(PetscOptionsObject,ts->adapt);
427: /* TS trajectory must be set after TS, since it may use some TS options above */
428: tflg = ts->trajectory ? PETSC_TRUE : PETSC_FALSE;
429: PetscOptionsBool("-ts_save_trajectory","Save the solution at each timestep","TSSetSaveTrajectory",tflg,&tflg,NULL);
430: if (tflg) {
431: TSSetSaveTrajectory(ts);
432: }
434: TSAdjointSetFromOptions(PetscOptionsObject,ts);
436: /* process any options handlers added with PetscObjectAddOptionsHandler() */
437: PetscObjectProcessOptionsHandlers(PetscOptionsObject,(PetscObject)ts);
438: PetscOptionsEnd();
440: if (ts->trajectory) {
441: TSTrajectorySetFromOptions(ts->trajectory,ts);
442: }
444: /* why do we have to do this here and not during TSSetUp? */
445: TSGetSNES(ts,&ts->snes);
446: if (ts->problem_type == TS_LINEAR) {
447: PetscObjectTypeCompareAny((PetscObject)ts->snes,&flg,SNESKSPONLY,SNESKSPTRANSPOSEONLY,"");
448: if (!flg) { SNESSetType(ts->snes,SNESKSPONLY); }
449: }
450: SNESSetFromOptions(ts->snes);
451: return(0);
452: }
454: /*@
455: TSGetTrajectory - Gets the trajectory from a TS if it exists
457: Collective on TS
459: Input Parameters:
460: . ts - the TS context obtained from TSCreate()
462: Output Parameters:
463: . tr - the TSTrajectory object, if it exists
465: Note: This routine should be called after all TS options have been set
467: Level: advanced
469: .seealso: TSGetTrajectory(), TSAdjointSolve(), TSTrajectory, TSTrajectoryCreate()
471: @*/
472: PetscErrorCode TSGetTrajectory(TS ts,TSTrajectory *tr)
473: {
476: *tr = ts->trajectory;
477: return(0);
478: }
480: /*@
481: TSSetSaveTrajectory - Causes the TS to save its solutions as it iterates forward in time in a TSTrajectory object
483: Collective on TS
485: Input Parameters:
486: . ts - the TS context obtained from TSCreate()
488: Options Database:
489: + -ts_save_trajectory - saves the trajectory to a file
490: - -ts_trajectory_type type
492: Note: This routine should be called after all TS options have been set
494: The TSTRAJECTORYVISUALIZATION files can be loaded into Python with $PETSC_DIR/lib/petsc/bin/PetscBinaryIOTrajectory.py and
495: MATLAB with $PETSC_DIR/share/petsc/matlab/PetscReadBinaryTrajectory.m
497: Level: intermediate
499: .seealso: TSGetTrajectory(), TSAdjointSolve()
501: @*/
502: PetscErrorCode TSSetSaveTrajectory(TS ts)
503: {
508: if (!ts->trajectory) {
509: TSTrajectoryCreate(PetscObjectComm((PetscObject)ts),&ts->trajectory);
510: }
511: return(0);
512: }
514: /*@
515: TSResetTrajectory - Destroys and recreates the internal TSTrajectory object
517: Collective on TS
519: Input Parameters:
520: . ts - the TS context obtained from TSCreate()
522: Level: intermediate
524: .seealso: TSGetTrajectory(), TSAdjointSolve()
526: @*/
527: PetscErrorCode TSResetTrajectory(TS ts)
528: {
533: if (ts->trajectory) {
534: TSTrajectoryDestroy(&ts->trajectory);
535: TSTrajectoryCreate(PetscObjectComm((PetscObject)ts),&ts->trajectory);
536: }
537: return(0);
538: }
540: /*@
541: TSComputeRHSJacobian - Computes the Jacobian matrix that has been
542: set with TSSetRHSJacobian().
544: Collective on TS
546: Input Parameters:
547: + ts - the TS context
548: . t - current timestep
549: - U - input vector
551: Output Parameters:
552: + A - Jacobian matrix
553: . B - optional preconditioning matrix
554: - flag - flag indicating matrix structure
556: Notes:
557: Most users should not need to explicitly call this routine, as it
558: is used internally within the nonlinear solvers.
560: See KSPSetOperators() for important information about setting the
561: flag parameter.
563: Level: developer
565: .seealso: TSSetRHSJacobian(), KSPSetOperators()
566: @*/
567: PetscErrorCode TSComputeRHSJacobian(TS ts,PetscReal t,Vec U,Mat A,Mat B)
568: {
569: PetscErrorCode ierr;
570: PetscObjectState Ustate;
571: PetscObjectId Uid;
572: DM dm;
573: DMTS tsdm;
574: TSRHSJacobian rhsjacobianfunc;
575: void *ctx;
576: TSRHSFunction rhsfunction;
582: TSGetDM(ts,&dm);
583: DMGetDMTS(dm,&tsdm);
584: DMTSGetRHSFunction(dm,&rhsfunction,NULL);
585: DMTSGetRHSJacobian(dm,&rhsjacobianfunc,&ctx);
586: PetscObjectStateGet((PetscObject)U,&Ustate);
587: PetscObjectGetId((PetscObject)U,&Uid);
589: if (ts->rhsjacobian.time == t && (ts->problem_type == TS_LINEAR || (ts->rhsjacobian.Xid == Uid && ts->rhsjacobian.Xstate == Ustate)) && (rhsfunction != TSComputeRHSFunctionLinear)) return(0);
591: if (ts->rhsjacobian.shift && ts->rhsjacobian.reuse) SETERRQ1(PetscObjectComm((PetscObject)ts),PETSC_ERR_USER,"Should not call TSComputeRHSJacobian() on a shifted matrix (shift=%lf) when RHSJacobian is reusable.",ts->rhsjacobian.shift);
592: if (rhsjacobianfunc) {
593: PetscLogEventBegin(TS_JacobianEval,ts,U,A,B);
594: PetscStackPush("TS user Jacobian function");
595: (*rhsjacobianfunc)(ts,t,U,A,B,ctx);
596: PetscStackPop;
597: PetscLogEventEnd(TS_JacobianEval,ts,U,A,B);
598: } else {
599: MatZeroEntries(A);
600: if (B && A != B) {MatZeroEntries(B);}
601: }
602: ts->rhsjacobian.time = t;
603: ts->rhsjacobian.shift = 0;
604: ts->rhsjacobian.scale = 1.;
605: PetscObjectGetId((PetscObject)U,&ts->rhsjacobian.Xid);
606: PetscObjectStateGet((PetscObject)U,&ts->rhsjacobian.Xstate);
607: return(0);
608: }
610: /*@
611: TSComputeRHSFunction - Evaluates the right-hand-side function.
613: Collective on TS
615: Input Parameters:
616: + ts - the TS context
617: . t - current time
618: - U - state vector
620: Output Parameter:
621: . y - right hand side
623: Note:
624: Most users should not need to explicitly call this routine, as it
625: is used internally within the nonlinear solvers.
627: Level: developer
629: .seealso: TSSetRHSFunction(), TSComputeIFunction()
630: @*/
631: PetscErrorCode TSComputeRHSFunction(TS ts,PetscReal t,Vec U,Vec y)
632: {
634: TSRHSFunction rhsfunction;
635: TSIFunction ifunction;
636: void *ctx;
637: DM dm;
643: TSGetDM(ts,&dm);
644: DMTSGetRHSFunction(dm,&rhsfunction,&ctx);
645: DMTSGetIFunction(dm,&ifunction,NULL);
647: if (!rhsfunction && !ifunction) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_USER,"Must call TSSetRHSFunction() and / or TSSetIFunction()");
649: PetscLogEventBegin(TS_FunctionEval,ts,U,y,0);
650: if (rhsfunction) {
651: VecLockReadPush(U);
652: PetscStackPush("TS user right-hand-side function");
653: (*rhsfunction)(ts,t,U,y,ctx);
654: PetscStackPop;
655: VecLockReadPop(U);
656: } else {
657: VecZeroEntries(y);
658: }
660: PetscLogEventEnd(TS_FunctionEval,ts,U,y,0);
661: return(0);
662: }
664: /*@
665: TSComputeSolutionFunction - Evaluates the solution function.
667: Collective on TS
669: Input Parameters:
670: + ts - the TS context
671: - t - current time
673: Output Parameter:
674: . U - the solution
676: Note:
677: Most users should not need to explicitly call this routine, as it
678: is used internally within the nonlinear solvers.
680: Level: developer
682: .seealso: TSSetSolutionFunction(), TSSetRHSFunction(), TSComputeIFunction()
683: @*/
684: PetscErrorCode TSComputeSolutionFunction(TS ts,PetscReal t,Vec U)
685: {
686: PetscErrorCode ierr;
687: TSSolutionFunction solutionfunction;
688: void *ctx;
689: DM dm;
694: TSGetDM(ts,&dm);
695: DMTSGetSolutionFunction(dm,&solutionfunction,&ctx);
697: if (solutionfunction) {
698: PetscStackPush("TS user solution function");
699: (*solutionfunction)(ts,t,U,ctx);
700: PetscStackPop;
701: }
702: return(0);
703: }
704: /*@
705: TSComputeForcingFunction - Evaluates the forcing function.
707: Collective on TS
709: Input Parameters:
710: + ts - the TS context
711: - t - current time
713: Output Parameter:
714: . U - the function value
716: Note:
717: Most users should not need to explicitly call this routine, as it
718: is used internally within the nonlinear solvers.
720: Level: developer
722: .seealso: TSSetSolutionFunction(), TSSetRHSFunction(), TSComputeIFunction()
723: @*/
724: PetscErrorCode TSComputeForcingFunction(TS ts,PetscReal t,Vec U)
725: {
726: PetscErrorCode ierr, (*forcing)(TS,PetscReal,Vec,void*);
727: void *ctx;
728: DM dm;
733: TSGetDM(ts,&dm);
734: DMTSGetForcingFunction(dm,&forcing,&ctx);
736: if (forcing) {
737: PetscStackPush("TS user forcing function");
738: (*forcing)(ts,t,U,ctx);
739: PetscStackPop;
740: }
741: return(0);
742: }
744: static PetscErrorCode TSGetRHSVec_Private(TS ts,Vec *Frhs)
745: {
746: Vec F;
750: *Frhs = NULL;
751: TSGetIFunction(ts,&F,NULL,NULL);
752: if (!ts->Frhs) {
753: VecDuplicate(F,&ts->Frhs);
754: }
755: *Frhs = ts->Frhs;
756: return(0);
757: }
759: PetscErrorCode TSGetRHSMats_Private(TS ts,Mat *Arhs,Mat *Brhs)
760: {
761: Mat A,B;
763: TSIJacobian ijacobian;
766: if (Arhs) *Arhs = NULL;
767: if (Brhs) *Brhs = NULL;
768: TSGetIJacobian(ts,&A,&B,&ijacobian,NULL);
769: if (Arhs) {
770: if (!ts->Arhs) {
771: if (ijacobian) {
772: MatDuplicate(A,MAT_DO_NOT_COPY_VALUES,&ts->Arhs);
773: } else {
774: ts->Arhs = A;
775: PetscObjectReference((PetscObject)A);
776: }
777: } else {
778: PetscBool flg;
779: SNESGetUseMatrixFree(ts->snes,NULL,&flg);
780: /* Handle case where user provided only RHSJacobian and used -snes_mf_operator */
781: if (flg && !ijacobian && ts->Arhs == ts->Brhs){
782: PetscObjectDereference((PetscObject)ts->Arhs);
783: ts->Arhs = A;
784: PetscObjectReference((PetscObject)A);
785: }
786: }
787: *Arhs = ts->Arhs;
788: }
789: if (Brhs) {
790: if (!ts->Brhs) {
791: if (A != B) {
792: if (ijacobian) {
793: MatDuplicate(B,MAT_DO_NOT_COPY_VALUES,&ts->Brhs);
794: } else {
795: ts->Brhs = B;
796: PetscObjectReference((PetscObject)B);
797: }
798: } else {
799: PetscObjectReference((PetscObject)ts->Arhs);
800: ts->Brhs = ts->Arhs;
801: }
802: }
803: *Brhs = ts->Brhs;
804: }
805: return(0);
806: }
808: /*@
809: TSComputeIFunction - Evaluates the DAE residual written in implicit form F(t,U,Udot)=0
811: Collective on TS
813: Input Parameters:
814: + ts - the TS context
815: . t - current time
816: . U - state vector
817: . Udot - time derivative of state vector
818: - imex - flag indicates if the method is IMEX so that the RHSFunction should be kept separate
820: Output Parameter:
821: . Y - right hand side
823: Note:
824: Most users should not need to explicitly call this routine, as it
825: is used internally within the nonlinear solvers.
827: If the user did did not write their equations in implicit form, this
828: function recasts them in implicit form.
830: Level: developer
832: .seealso: TSSetIFunction(), TSComputeRHSFunction()
833: @*/
834: PetscErrorCode TSComputeIFunction(TS ts,PetscReal t,Vec U,Vec Udot,Vec Y,PetscBool imex)
835: {
837: TSIFunction ifunction;
838: TSRHSFunction rhsfunction;
839: void *ctx;
840: DM dm;
848: TSGetDM(ts,&dm);
849: DMTSGetIFunction(dm,&ifunction,&ctx);
850: DMTSGetRHSFunction(dm,&rhsfunction,NULL);
852: if (!rhsfunction && !ifunction) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_USER,"Must call TSSetRHSFunction() and / or TSSetIFunction()");
854: PetscLogEventBegin(TS_FunctionEval,ts,U,Udot,Y);
855: if (ifunction) {
856: PetscStackPush("TS user implicit function");
857: (*ifunction)(ts,t,U,Udot,Y,ctx);
858: PetscStackPop;
859: }
860: if (imex) {
861: if (!ifunction) {
862: VecCopy(Udot,Y);
863: }
864: } else if (rhsfunction) {
865: if (ifunction) {
866: Vec Frhs;
867: TSGetRHSVec_Private(ts,&Frhs);
868: TSComputeRHSFunction(ts,t,U,Frhs);
869: VecAXPY(Y,-1,Frhs);
870: } else {
871: TSComputeRHSFunction(ts,t,U,Y);
872: VecAYPX(Y,-1,Udot);
873: }
874: }
875: PetscLogEventEnd(TS_FunctionEval,ts,U,Udot,Y);
876: return(0);
877: }
879: /*
880: TSRecoverRHSJacobian - Recover the Jacobian matrix so that one can call TSComputeRHSJacobian() on it.
882: Note:
883: This routine is needed when one switches from TSComputeIJacobian() to TSComputeRHSJacobian() because the Jacobian matrix may be shifted or scaled in TSComputeIJacobian().
885: */
886: static PetscErrorCode TSRecoverRHSJacobian(TS ts,Mat A,Mat B)
887: {
888: PetscErrorCode ierr;
892: if (A != ts->Arhs) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"Invalid Amat");
893: if (B != ts->Brhs) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"Invalid Bmat");
895: if (ts->rhsjacobian.shift) {
896: MatShift(A,-ts->rhsjacobian.shift);
897: }
898: if (ts->rhsjacobian.scale == -1.) {
899: MatScale(A,-1);
900: }
901: if (B && B == ts->Brhs && A != B) {
902: if (ts->rhsjacobian.shift) {
903: MatShift(B,-ts->rhsjacobian.shift);
904: }
905: if (ts->rhsjacobian.scale == -1.) {
906: MatScale(B,-1);
907: }
908: }
909: ts->rhsjacobian.shift = 0;
910: ts->rhsjacobian.scale = 1.;
911: return(0);
912: }
914: /*@
915: TSComputeIJacobian - Evaluates the Jacobian of the DAE
917: Collective on TS
919: Input
920: Input Parameters:
921: + ts - the TS context
922: . t - current timestep
923: . U - state vector
924: . Udot - time derivative of state vector
925: . shift - shift to apply, see note below
926: - imex - flag indicates if the method is IMEX so that the RHSJacobian should be kept separate
928: Output Parameters:
929: + A - Jacobian matrix
930: - B - matrix from which the preconditioner is constructed; often the same as A
932: Notes:
933: If F(t,U,Udot)=0 is the DAE, the required Jacobian is
935: dF/dU + shift*dF/dUdot
937: Most users should not need to explicitly call this routine, as it
938: is used internally within the nonlinear solvers.
940: Level: developer
942: .seealso: TSSetIJacobian()
943: @*/
944: PetscErrorCode TSComputeIJacobian(TS ts,PetscReal t,Vec U,Vec Udot,PetscReal shift,Mat A,Mat B,PetscBool imex)
945: {
947: TSIJacobian ijacobian;
948: TSRHSJacobian rhsjacobian;
949: DM dm;
950: void *ctx;
961: TSGetDM(ts,&dm);
962: DMTSGetIJacobian(dm,&ijacobian,&ctx);
963: DMTSGetRHSJacobian(dm,&rhsjacobian,NULL);
965: if (!rhsjacobian && !ijacobian) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_USER,"Must call TSSetRHSJacobian() and / or TSSetIJacobian()");
967: PetscLogEventBegin(TS_JacobianEval,ts,U,A,B);
968: if (ijacobian) {
969: PetscStackPush("TS user implicit Jacobian");
970: (*ijacobian)(ts,t,U,Udot,shift,A,B,ctx);
971: PetscStackPop;
972: }
973: if (imex) {
974: if (!ijacobian) { /* system was written as Udot = G(t,U) */
975: PetscBool assembled;
976: if (rhsjacobian) {
977: Mat Arhs = NULL;
978: TSGetRHSMats_Private(ts,&Arhs,NULL);
979: if (A == Arhs) {
980: if (rhsjacobian == TSComputeRHSJacobianConstant) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"Unsupported operation! cannot use TSComputeRHSJacobianConstant"); /* there is no way to reconstruct shift*M-J since J cannot be reevaluated */
981: ts->rhsjacobian.time = PETSC_MIN_REAL;
982: }
983: }
984: MatZeroEntries(A);
985: MatAssembled(A,&assembled);
986: if (!assembled) {
987: MatAssemblyBegin(A,MAT_FINAL_ASSEMBLY);
988: MatAssemblyEnd(A,MAT_FINAL_ASSEMBLY);
989: }
990: MatShift(A,shift);
991: if (A != B) {
992: MatZeroEntries(B);
993: MatAssembled(B,&assembled);
994: if (!assembled) {
995: MatAssemblyBegin(B,MAT_FINAL_ASSEMBLY);
996: MatAssemblyEnd(B,MAT_FINAL_ASSEMBLY);
997: }
998: MatShift(B,shift);
999: }
1000: }
1001: } else {
1002: Mat Arhs = NULL,Brhs = NULL;
1003: if (rhsjacobian) { /* RHSJacobian needs to be converted to part of IJacobian if exists */
1004: TSGetRHSMats_Private(ts,&Arhs,&Brhs);
1005: }
1006: if (Arhs == A) { /* No IJacobian matrix, so we only have the RHS matrix */
1007: PetscObjectState Ustate;
1008: PetscObjectId Uid;
1009: TSRHSFunction rhsfunction;
1011: DMTSGetRHSFunction(dm,&rhsfunction,NULL);
1012: PetscObjectStateGet((PetscObject)U,&Ustate);
1013: PetscObjectGetId((PetscObject)U,&Uid);
1014: if ((rhsjacobian == TSComputeRHSJacobianConstant || (ts->rhsjacobian.time == t && (ts->problem_type == TS_LINEAR || (ts->rhsjacobian.Xid == Uid && ts->rhsjacobian.Xstate == Ustate)) && rhsfunction != TSComputeRHSFunctionLinear)) && ts->rhsjacobian.scale == -1.) { /* No need to recompute RHSJacobian */
1015: MatShift(A,shift-ts->rhsjacobian.shift); /* revert the old shift and add the new shift with a single call to MatShift */
1016: if (A != B) {
1017: MatShift(B,shift-ts->rhsjacobian.shift);
1018: }
1019: } else {
1020: PetscBool flg;
1022: if (ts->rhsjacobian.reuse) { /* Undo the damage */
1023: /* MatScale has a short path for this case.
1024: However, this code path is taken the first time TSComputeRHSJacobian is called
1025: and the matrices have not been assembled yet */
1026: TSRecoverRHSJacobian(ts,A,B);
1027: }
1028: TSComputeRHSJacobian(ts,t,U,A,B);
1029: SNESGetUseMatrixFree(ts->snes,NULL,&flg);
1030: /* since -snes_mf_operator uses the full SNES function it does not need to be shifted or scaled here */
1031: if (!flg) {
1032: MatScale(A,-1);
1033: MatShift(A,shift);
1034: }
1035: if (A != B) {
1036: MatScale(B,-1);
1037: MatShift(B,shift);
1038: }
1039: }
1040: ts->rhsjacobian.scale = -1;
1041: ts->rhsjacobian.shift = shift;
1042: } else if (Arhs) { /* Both IJacobian and RHSJacobian exist or the RHS matrix provided (A) is different from the internal RHS matrix (Arhs) */
1043: MatStructure axpy = DIFFERENT_NONZERO_PATTERN;
1045: if (!ijacobian) { /* No IJacobian provided, but we have a separate RHS matrix */
1046: MatZeroEntries(A);
1047: MatShift(A,shift);
1048: if (A != B) {
1049: MatZeroEntries(B);
1050: MatShift(B,shift);
1051: }
1052: }
1053: TSComputeRHSJacobian(ts,t,U,Arhs,Brhs);
1054: MatAXPY(A,-1,Arhs,axpy);
1055: if (A != B) {
1056: MatAXPY(B,-1,Brhs,axpy);
1057: }
1058: }
1059: }
1060: PetscLogEventEnd(TS_JacobianEval,ts,U,A,B);
1061: return(0);
1062: }
1064: /*@C
1065: TSSetRHSFunction - Sets the routine for evaluating the function,
1066: where U_t = G(t,u).
1068: Logically Collective on TS
1070: Input Parameters:
1071: + ts - the TS context obtained from TSCreate()
1072: . r - vector to put the computed right hand side (or NULL to have it created)
1073: . f - routine for evaluating the right-hand-side function
1074: - ctx - [optional] user-defined context for private data for the
1075: function evaluation routine (may be NULL)
1077: Calling sequence of f:
1078: $ PetscErrorCode f(TS ts,PetscReal t,Vec u,Vec F,void *ctx);
1080: + ts - timestep context
1081: . t - current timestep
1082: . u - input vector
1083: . F - function vector
1084: - ctx - [optional] user-defined function context
1086: Level: beginner
1088: Notes:
1089: You must call this function or TSSetIFunction() to define your ODE. You cannot use this function when solving a DAE.
1091: .seealso: TSSetRHSJacobian(), TSSetIJacobian(), TSSetIFunction()
1092: @*/
1093: PetscErrorCode TSSetRHSFunction(TS ts,Vec r,PetscErrorCode (*f)(TS,PetscReal,Vec,Vec,void*),void *ctx)
1094: {
1096: SNES snes;
1097: Vec ralloc = NULL;
1098: DM dm;
1104: TSGetDM(ts,&dm);
1105: DMTSSetRHSFunction(dm,f,ctx);
1106: TSGetSNES(ts,&snes);
1107: if (!r && !ts->dm && ts->vec_sol) {
1108: VecDuplicate(ts->vec_sol,&ralloc);
1109: r = ralloc;
1110: }
1111: SNESSetFunction(snes,r,SNESTSFormFunction,ts);
1112: VecDestroy(&ralloc);
1113: return(0);
1114: }
1116: /*@C
1117: TSSetSolutionFunction - Provide a function that computes the solution of the ODE or DAE
1119: Logically Collective on TS
1121: Input Parameters:
1122: + ts - the TS context obtained from TSCreate()
1123: . f - routine for evaluating the solution
1124: - ctx - [optional] user-defined context for private data for the
1125: function evaluation routine (may be NULL)
1127: Calling sequence of f:
1128: $ PetscErrorCode f(TS ts,PetscReal t,Vec u,void *ctx);
1130: + t - current timestep
1131: . u - output vector
1132: - ctx - [optional] user-defined function context
1134: Options Database:
1135: + -ts_monitor_lg_error - create a graphical monitor of error history, requires user to have provided TSSetSolutionFunction()
1136: - -ts_monitor_draw_error - Monitor error graphically, requires user to have provided TSSetSolutionFunction()
1138: Notes:
1139: This routine is used for testing accuracy of time integration schemes when you already know the solution.
1140: If analytic solutions are not known for your system, consider using the Method of Manufactured Solutions to
1141: create closed-form solutions with non-physical forcing terms.
1143: For low-dimensional problems solved in serial, such as small discrete systems, TSMonitorLGError() can be used to monitor the error history.
1145: Level: beginner
1147: .seealso: TSSetRHSJacobian(), TSSetIJacobian(), TSComputeSolutionFunction(), TSSetForcingFunction(), TSSetSolution(), TSGetSolution(), TSMonitorLGError(), TSMonitorDrawError()
1148: @*/
1149: PetscErrorCode TSSetSolutionFunction(TS ts,PetscErrorCode (*f)(TS,PetscReal,Vec,void*),void *ctx)
1150: {
1152: DM dm;
1156: TSGetDM(ts,&dm);
1157: DMTSSetSolutionFunction(dm,f,ctx);
1158: return(0);
1159: }
1161: /*@C
1162: TSSetForcingFunction - Provide a function that computes a forcing term for a ODE or PDE
1164: Logically Collective on TS
1166: Input Parameters:
1167: + ts - the TS context obtained from TSCreate()
1168: . func - routine for evaluating the forcing function
1169: - ctx - [optional] user-defined context for private data for the
1170: function evaluation routine (may be NULL)
1172: Calling sequence of func:
1173: $ PetscErrorCode func (TS ts,PetscReal t,Vec f,void *ctx);
1175: + t - current timestep
1176: . f - output vector
1177: - ctx - [optional] user-defined function context
1179: Notes:
1180: This routine is useful for testing accuracy of time integration schemes when using the Method of Manufactured Solutions to
1181: create closed-form solutions with a non-physical forcing term. It allows you to use the Method of Manufactored Solution without directly editing the
1182: definition of the problem you are solving and hence possibly introducing bugs.
1184: This replaces the ODE F(u,u_t,t) = 0 the TS is solving with F(u,u_t,t) - func(t) = 0
1186: This forcing function does not depend on the solution to the equations, it can only depend on spatial location, time, and possibly parameters, the
1187: parameters can be passed in the ctx variable.
1189: For low-dimensional problems solved in serial, such as small discrete systems, TSMonitorLGError() can be used to monitor the error history.
1191: Level: beginner
1193: .seealso: TSSetRHSJacobian(), TSSetIJacobian(), TSComputeSolutionFunction(), TSSetSolutionFunction()
1194: @*/
1195: PetscErrorCode TSSetForcingFunction(TS ts,TSForcingFunction func,void *ctx)
1196: {
1198: DM dm;
1202: TSGetDM(ts,&dm);
1203: DMTSSetForcingFunction(dm,func,ctx);
1204: return(0);
1205: }
1207: /*@C
1208: TSSetRHSJacobian - Sets the function to compute the Jacobian of G,
1209: where U_t = G(U,t), as well as the location to store the matrix.
1211: Logically Collective on TS
1213: Input Parameters:
1214: + ts - the TS context obtained from TSCreate()
1215: . Amat - (approximate) Jacobian matrix
1216: . Pmat - matrix from which preconditioner is to be constructed (usually the same as Amat)
1217: . f - the Jacobian evaluation routine
1218: - ctx - [optional] user-defined context for private data for the
1219: Jacobian evaluation routine (may be NULL)
1221: Calling sequence of f:
1222: $ PetscErrorCode f(TS ts,PetscReal t,Vec u,Mat A,Mat B,void *ctx);
1224: + t - current timestep
1225: . u - input vector
1226: . Amat - (approximate) Jacobian matrix
1227: . Pmat - matrix from which preconditioner is to be constructed (usually the same as Amat)
1228: - ctx - [optional] user-defined context for matrix evaluation routine
1230: Notes:
1231: You must set all the diagonal entries of the matrices, if they are zero you must still set them with a zero value
1233: The TS solver may modify the nonzero structure and the entries of the matrices Amat and Pmat between the calls to f()
1234: You should not assume the values are the same in the next call to f() as you set them in the previous call.
1236: Level: beginner
1238: .seealso: SNESComputeJacobianDefaultColor(), TSSetRHSFunction(), TSRHSJacobianSetReuse(), TSSetIJacobian()
1240: @*/
1241: PetscErrorCode TSSetRHSJacobian(TS ts,Mat Amat,Mat Pmat,TSRHSJacobian f,void *ctx)
1242: {
1244: SNES snes;
1245: DM dm;
1246: TSIJacobian ijacobian;
1255: TSGetDM(ts,&dm);
1256: DMTSSetRHSJacobian(dm,f,ctx);
1257: DMTSGetIJacobian(dm,&ijacobian,NULL);
1258: TSGetSNES(ts,&snes);
1259: if (!ijacobian) {
1260: SNESSetJacobian(snes,Amat,Pmat,SNESTSFormJacobian,ts);
1261: }
1262: if (Amat) {
1263: PetscObjectReference((PetscObject)Amat);
1264: MatDestroy(&ts->Arhs);
1265: ts->Arhs = Amat;
1266: }
1267: if (Pmat) {
1268: PetscObjectReference((PetscObject)Pmat);
1269: MatDestroy(&ts->Brhs);
1270: ts->Brhs = Pmat;
1271: }
1272: return(0);
1273: }
1275: /*@C
1276: TSSetIFunction - Set the function to compute F(t,U,U_t) where F() = 0 is the DAE to be solved.
1278: Logically Collective on TS
1280: Input Parameters:
1281: + ts - the TS context obtained from TSCreate()
1282: . r - vector to hold the residual (or NULL to have it created internally)
1283: . f - the function evaluation routine
1284: - ctx - user-defined context for private data for the function evaluation routine (may be NULL)
1286: Calling sequence of f:
1287: $ PetscErrorCode f(TS ts,PetscReal t,Vec u,Vec u_t,Vec F,ctx);
1289: + t - time at step/stage being solved
1290: . u - state vector
1291: . u_t - time derivative of state vector
1292: . F - function vector
1293: - ctx - [optional] user-defined context for matrix evaluation routine
1295: Important:
1296: The user MUST call either this routine or TSSetRHSFunction() to define the ODE. When solving DAEs you must use this function.
1298: Level: beginner
1300: .seealso: TSSetRHSJacobian(), TSSetRHSFunction(), TSSetIJacobian()
1301: @*/
1302: PetscErrorCode TSSetIFunction(TS ts,Vec r,TSIFunction f,void *ctx)
1303: {
1305: SNES snes;
1306: Vec ralloc = NULL;
1307: DM dm;
1313: TSGetDM(ts,&dm);
1314: DMTSSetIFunction(dm,f,ctx);
1316: TSGetSNES(ts,&snes);
1317: if (!r && !ts->dm && ts->vec_sol) {
1318: VecDuplicate(ts->vec_sol,&ralloc);
1319: r = ralloc;
1320: }
1321: SNESSetFunction(snes,r,SNESTSFormFunction,ts);
1322: VecDestroy(&ralloc);
1323: return(0);
1324: }
1326: /*@C
1327: TSGetIFunction - Returns the vector where the implicit residual is stored and the function/contex to compute it.
1329: Not Collective
1331: Input Parameter:
1332: . ts - the TS context
1334: Output Parameter:
1335: + r - vector to hold residual (or NULL)
1336: . func - the function to compute residual (or NULL)
1337: - ctx - the function context (or NULL)
1339: Level: advanced
1341: .seealso: TSSetIFunction(), SNESGetFunction()
1342: @*/
1343: PetscErrorCode TSGetIFunction(TS ts,Vec *r,TSIFunction *func,void **ctx)
1344: {
1346: SNES snes;
1347: DM dm;
1351: TSGetSNES(ts,&snes);
1352: SNESGetFunction(snes,r,NULL,NULL);
1353: TSGetDM(ts,&dm);
1354: DMTSGetIFunction(dm,func,ctx);
1355: return(0);
1356: }
1358: /*@C
1359: TSGetRHSFunction - Returns the vector where the right hand side is stored and the function/context to compute it.
1361: Not Collective
1363: Input Parameter:
1364: . ts - the TS context
1366: Output Parameter:
1367: + r - vector to hold computed right hand side (or NULL)
1368: . func - the function to compute right hand side (or NULL)
1369: - ctx - the function context (or NULL)
1371: Level: advanced
1373: .seealso: TSSetRHSFunction(), SNESGetFunction()
1374: @*/
1375: PetscErrorCode TSGetRHSFunction(TS ts,Vec *r,TSRHSFunction *func,void **ctx)
1376: {
1378: SNES snes;
1379: DM dm;
1383: TSGetSNES(ts,&snes);
1384: SNESGetFunction(snes,r,NULL,NULL);
1385: TSGetDM(ts,&dm);
1386: DMTSGetRHSFunction(dm,func,ctx);
1387: return(0);
1388: }
1390: /*@C
1391: TSSetIJacobian - Set the function to compute the matrix dF/dU + a*dF/dU_t where F(t,U,U_t) is the function
1392: provided with TSSetIFunction().
1394: Logically Collective on TS
1396: Input Parameters:
1397: + ts - the TS context obtained from TSCreate()
1398: . Amat - (approximate) Jacobian matrix
1399: . Pmat - matrix used to compute preconditioner (usually the same as Amat)
1400: . f - the Jacobian evaluation routine
1401: - ctx - user-defined context for private data for the Jacobian evaluation routine (may be NULL)
1403: Calling sequence of f:
1404: $ PetscErrorCode f(TS ts,PetscReal t,Vec U,Vec U_t,PetscReal a,Mat Amat,Mat Pmat,void *ctx);
1406: + t - time at step/stage being solved
1407: . U - state vector
1408: . U_t - time derivative of state vector
1409: . a - shift
1410: . Amat - (approximate) Jacobian of F(t,U,W+a*U), equivalent to dF/dU + a*dF/dU_t
1411: . Pmat - matrix used for constructing preconditioner, usually the same as Amat
1412: - ctx - [optional] user-defined context for matrix evaluation routine
1414: Notes:
1415: The matrices Amat and Pmat are exactly the matrices that are used by SNES for the nonlinear solve.
1417: If you know the operator Amat has a null space you can use MatSetNullSpace() and MatSetTransposeNullSpace() to supply the null
1418: space to Amat and the KSP solvers will automatically use that null space as needed during the solution process.
1420: The matrix dF/dU + a*dF/dU_t you provide turns out to be
1421: the Jacobian of F(t,U,W+a*U) where F(t,U,U_t) = 0 is the DAE to be solved.
1422: The time integrator internally approximates U_t by W+a*U where the positive "shift"
1423: a and vector W depend on the integration method, step size, and past states. For example with
1424: the backward Euler method a = 1/dt and W = -a*U(previous timestep) so
1425: W + a*U = a*(U - U(previous timestep)) = (U - U(previous timestep))/dt
1427: You must set all the diagonal entries of the matrices, if they are zero you must still set them with a zero value
1429: The TS solver may modify the nonzero structure and the entries of the matrices Amat and Pmat between the calls to f()
1430: You should not assume the values are the same in the next call to f() as you set them in the previous call.
1432: Level: beginner
1434: .seealso: TSSetIFunction(), TSSetRHSJacobian(), SNESComputeJacobianDefaultColor(), SNESComputeJacobianDefault(), TSSetRHSFunction()
1436: @*/
1437: PetscErrorCode TSSetIJacobian(TS ts,Mat Amat,Mat Pmat,TSIJacobian f,void *ctx)
1438: {
1440: SNES snes;
1441: DM dm;
1450: TSGetDM(ts,&dm);
1451: DMTSSetIJacobian(dm,f,ctx);
1453: TSGetSNES(ts,&snes);
1454: SNESSetJacobian(snes,Amat,Pmat,SNESTSFormJacobian,ts);
1455: return(0);
1456: }
1458: /*@
1459: TSRHSJacobianSetReuse - restore RHS Jacobian before re-evaluating. Without this flag, TS will change the sign and
1460: shift the RHS Jacobian for a finite-time-step implicit solve, in which case the user function will need to recompute
1461: the entire Jacobian. The reuse flag must be set if the evaluation function will assume that the matrix entries have
1462: not been changed by the TS.
1464: Logically Collective
1466: Input Arguments:
1467: + ts - TS context obtained from TSCreate()
1468: - reuse - PETSC_TRUE if the RHS Jacobian
1470: Level: intermediate
1472: .seealso: TSSetRHSJacobian(), TSComputeRHSJacobianConstant()
1473: @*/
1474: PetscErrorCode TSRHSJacobianSetReuse(TS ts,PetscBool reuse)
1475: {
1477: ts->rhsjacobian.reuse = reuse;
1478: return(0);
1479: }
1481: /*@C
1482: TSSetI2Function - Set the function to compute F(t,U,U_t,U_tt) where F = 0 is the DAE to be solved.
1484: Logically Collective on TS
1486: Input Parameters:
1487: + ts - the TS context obtained from TSCreate()
1488: . F - vector to hold the residual (or NULL to have it created internally)
1489: . fun - the function evaluation routine
1490: - ctx - user-defined context for private data for the function evaluation routine (may be NULL)
1492: Calling sequence of fun:
1493: $ PetscErrorCode fun(TS ts,PetscReal t,Vec U,Vec U_t,Vec U_tt,Vec F,ctx);
1495: + t - time at step/stage being solved
1496: . U - state vector
1497: . U_t - time derivative of state vector
1498: . U_tt - second time derivative of state vector
1499: . F - function vector
1500: - ctx - [optional] user-defined context for matrix evaluation routine (may be NULL)
1502: Level: beginner
1504: .seealso: TSSetI2Jacobian(), TSSetIFunction(), TSCreate(), TSSetRHSFunction()
1505: @*/
1506: PetscErrorCode TSSetI2Function(TS ts,Vec F,TSI2Function fun,void *ctx)
1507: {
1508: DM dm;
1514: TSSetIFunction(ts,F,NULL,NULL);
1515: TSGetDM(ts,&dm);
1516: DMTSSetI2Function(dm,fun,ctx);
1517: return(0);
1518: }
1520: /*@C
1521: TSGetI2Function - Returns the vector where the implicit residual is stored and the function/contex to compute it.
1523: Not Collective
1525: Input Parameter:
1526: . ts - the TS context
1528: Output Parameter:
1529: + r - vector to hold residual (or NULL)
1530: . fun - the function to compute residual (or NULL)
1531: - ctx - the function context (or NULL)
1533: Level: advanced
1535: .seealso: TSSetIFunction(), SNESGetFunction(), TSCreate()
1536: @*/
1537: PetscErrorCode TSGetI2Function(TS ts,Vec *r,TSI2Function *fun,void **ctx)
1538: {
1540: SNES snes;
1541: DM dm;
1545: TSGetSNES(ts,&snes);
1546: SNESGetFunction(snes,r,NULL,NULL);
1547: TSGetDM(ts,&dm);
1548: DMTSGetI2Function(dm,fun,ctx);
1549: return(0);
1550: }
1552: /*@C
1553: TSSetI2Jacobian - Set the function to compute the matrix dF/dU + v*dF/dU_t + a*dF/dU_tt
1554: where F(t,U,U_t,U_tt) is the function you provided with TSSetI2Function().
1556: Logically Collective on TS
1558: Input Parameters:
1559: + ts - the TS context obtained from TSCreate()
1560: . J - Jacobian matrix
1561: . P - preconditioning matrix for J (may be same as J)
1562: . jac - the Jacobian evaluation routine
1563: - ctx - user-defined context for private data for the Jacobian evaluation routine (may be NULL)
1565: Calling sequence of jac:
1566: $ PetscErrorCode jac(TS ts,PetscReal t,Vec U,Vec U_t,Vec U_tt,PetscReal v,PetscReal a,Mat J,Mat P,void *ctx);
1568: + t - time at step/stage being solved
1569: . U - state vector
1570: . U_t - time derivative of state vector
1571: . U_tt - second time derivative of state vector
1572: . v - shift for U_t
1573: . a - shift for U_tt
1574: . J - Jacobian of G(U) = F(t,U,W+v*U,W'+a*U), equivalent to dF/dU + v*dF/dU_t + a*dF/dU_tt
1575: . P - preconditioning matrix for J, may be same as J
1576: - ctx - [optional] user-defined context for matrix evaluation routine
1578: Notes:
1579: The matrices J and P are exactly the matrices that are used by SNES for the nonlinear solve.
1581: The matrix dF/dU + v*dF/dU_t + a*dF/dU_tt you provide turns out to be
1582: the Jacobian of G(U) = F(t,U,W+v*U,W'+a*U) where F(t,U,U_t,U_tt) = 0 is the DAE to be solved.
1583: The time integrator internally approximates U_t by W+v*U and U_tt by W'+a*U where the positive "shift"
1584: parameters 'v' and 'a' and vectors W, W' depend on the integration method, step size, and past states.
1586: Level: beginner
1588: .seealso: TSSetI2Function(), TSGetI2Jacobian()
1589: @*/
1590: PetscErrorCode TSSetI2Jacobian(TS ts,Mat J,Mat P,TSI2Jacobian jac,void *ctx)
1591: {
1592: DM dm;
1599: TSSetIJacobian(ts,J,P,NULL,NULL);
1600: TSGetDM(ts,&dm);
1601: DMTSSetI2Jacobian(dm,jac,ctx);
1602: return(0);
1603: }
1605: /*@C
1606: TSGetI2Jacobian - Returns the implicit Jacobian at the present timestep.
1608: Not Collective, but parallel objects are returned if TS is parallel
1610: Input Parameter:
1611: . ts - The TS context obtained from TSCreate()
1613: Output Parameters:
1614: + J - The (approximate) Jacobian of F(t,U,U_t,U_tt)
1615: . P - The matrix from which the preconditioner is constructed, often the same as J
1616: . jac - The function to compute the Jacobian matrices
1617: - ctx - User-defined context for Jacobian evaluation routine
1619: Notes:
1620: You can pass in NULL for any return argument you do not need.
1622: Level: advanced
1624: .seealso: TSGetTimeStep(), TSGetMatrices(), TSGetTime(), TSGetStepNumber(), TSSetI2Jacobian(), TSGetI2Function(), TSCreate()
1626: @*/
1627: PetscErrorCode TSGetI2Jacobian(TS ts,Mat *J,Mat *P,TSI2Jacobian *jac,void **ctx)
1628: {
1630: SNES snes;
1631: DM dm;
1634: TSGetSNES(ts,&snes);
1635: SNESSetUpMatrices(snes);
1636: SNESGetJacobian(snes,J,P,NULL,NULL);
1637: TSGetDM(ts,&dm);
1638: DMTSGetI2Jacobian(dm,jac,ctx);
1639: return(0);
1640: }
1642: /*@
1643: TSComputeI2Function - Evaluates the DAE residual written in implicit form F(t,U,U_t,U_tt) = 0
1645: Collective on TS
1647: Input Parameters:
1648: + ts - the TS context
1649: . t - current time
1650: . U - state vector
1651: . V - time derivative of state vector (U_t)
1652: - A - second time derivative of state vector (U_tt)
1654: Output Parameter:
1655: . F - the residual vector
1657: Note:
1658: Most users should not need to explicitly call this routine, as it
1659: is used internally within the nonlinear solvers.
1661: Level: developer
1663: .seealso: TSSetI2Function(), TSGetI2Function()
1664: @*/
1665: PetscErrorCode TSComputeI2Function(TS ts,PetscReal t,Vec U,Vec V,Vec A,Vec F)
1666: {
1667: DM dm;
1668: TSI2Function I2Function;
1669: void *ctx;
1670: TSRHSFunction rhsfunction;
1680: TSGetDM(ts,&dm);
1681: DMTSGetI2Function(dm,&I2Function,&ctx);
1682: DMTSGetRHSFunction(dm,&rhsfunction,NULL);
1684: if (!I2Function) {
1685: TSComputeIFunction(ts,t,U,A,F,PETSC_FALSE);
1686: return(0);
1687: }
1689: PetscLogEventBegin(TS_FunctionEval,ts,U,V,F);
1691: PetscStackPush("TS user implicit function");
1692: I2Function(ts,t,U,V,A,F,ctx);
1693: PetscStackPop;
1695: if (rhsfunction) {
1696: Vec Frhs;
1697: TSGetRHSVec_Private(ts,&Frhs);
1698: TSComputeRHSFunction(ts,t,U,Frhs);
1699: VecAXPY(F,-1,Frhs);
1700: }
1702: PetscLogEventEnd(TS_FunctionEval,ts,U,V,F);
1703: return(0);
1704: }
1706: /*@
1707: TSComputeI2Jacobian - Evaluates the Jacobian of the DAE
1709: Collective on TS
1711: Input Parameters:
1712: + ts - the TS context
1713: . t - current timestep
1714: . U - state vector
1715: . V - time derivative of state vector
1716: . A - second time derivative of state vector
1717: . shiftV - shift to apply, see note below
1718: - shiftA - shift to apply, see note below
1720: Output Parameters:
1721: + J - Jacobian matrix
1722: - P - optional preconditioning matrix
1724: Notes:
1725: If F(t,U,V,A)=0 is the DAE, the required Jacobian is
1727: dF/dU + shiftV*dF/dV + shiftA*dF/dA
1729: Most users should not need to explicitly call this routine, as it
1730: is used internally within the nonlinear solvers.
1732: Level: developer
1734: .seealso: TSSetI2Jacobian()
1735: @*/
1736: PetscErrorCode TSComputeI2Jacobian(TS ts,PetscReal t,Vec U,Vec V,Vec A,PetscReal shiftV,PetscReal shiftA,Mat J,Mat P)
1737: {
1738: DM dm;
1739: TSI2Jacobian I2Jacobian;
1740: void *ctx;
1741: TSRHSJacobian rhsjacobian;
1752: TSGetDM(ts,&dm);
1753: DMTSGetI2Jacobian(dm,&I2Jacobian,&ctx);
1754: DMTSGetRHSJacobian(dm,&rhsjacobian,NULL);
1756: if (!I2Jacobian) {
1757: TSComputeIJacobian(ts,t,U,A,shiftA,J,P,PETSC_FALSE);
1758: return(0);
1759: }
1761: PetscLogEventBegin(TS_JacobianEval,ts,U,J,P);
1763: PetscStackPush("TS user implicit Jacobian");
1764: I2Jacobian(ts,t,U,V,A,shiftV,shiftA,J,P,ctx);
1765: PetscStackPop;
1767: if (rhsjacobian) {
1768: Mat Jrhs,Prhs; MatStructure axpy = DIFFERENT_NONZERO_PATTERN;
1769: TSGetRHSMats_Private(ts,&Jrhs,&Prhs);
1770: TSComputeRHSJacobian(ts,t,U,Jrhs,Prhs);
1771: MatAXPY(J,-1,Jrhs,axpy);
1772: if (P != J) {MatAXPY(P,-1,Prhs,axpy);}
1773: }
1775: PetscLogEventEnd(TS_JacobianEval,ts,U,J,P);
1776: return(0);
1777: }
1779: /*@C
1780: TSSetTransientVariable - sets function to transform from state to transient variables
1782: Logically Collective
1784: Input Arguments:
1785: + ts - time stepping context on which to change the transient variable
1786: . tvar - a function that transforms to transient variables
1787: - ctx - a context for tvar
1789: Calling sequence of tvar:
1790: $ PetscErrorCode tvar(TS ts,Vec p,Vec c,void *ctx);
1792: + ts - timestep context
1793: . p - input vector (primative form)
1794: . c - output vector, transient variables (conservative form)
1795: - ctx - [optional] user-defined function context
1797: Level: advanced
1799: Notes:
1800: This is typically used to transform from primitive to conservative variables so that a time integrator (e.g., TSBDF)
1801: can be conservative. In this context, primitive variables P are used to model the state (e.g., because they lead to
1802: well-conditioned formulations even in limiting cases such as low-Mach or zero porosity). The transient variable is
1803: C(P), specified by calling this function. An IFunction thus receives arguments (P, Cdot) and the IJacobian must be
1804: evaluated via the chain rule, as in
1806: dF/dP + shift * dF/dCdot dC/dP.
1808: .seealso: DMTSSetTransientVariable(), DMTSGetTransientVariable(), TSSetIFunction(), TSSetIJacobian()
1809: @*/
1810: PetscErrorCode TSSetTransientVariable(TS ts,TSTransientVariable tvar,void *ctx)
1811: {
1813: DM dm;
1817: TSGetDM(ts,&dm);
1818: DMTSSetTransientVariable(dm,tvar,ctx);
1819: return(0);
1820: }
1822: /*@
1823: TSComputeTransientVariable - transforms state (primitive) variables to transient (conservative) variables
1825: Logically Collective
1827: Input Parameters:
1828: + ts - TS on which to compute
1829: - U - state vector to be transformed to transient variables
1831: Output Parameters:
1832: . C - transient (conservative) variable
1834: Developer Notes:
1835: If DMTSSetTransientVariable() has not been called, then C is not modified in this routine and C=NULL is allowed.
1836: This makes it safe to call without a guard. One can use TSHasTransientVariable() to check if transient variables are
1837: being used.
1839: Level: developer
1841: .seealso: DMTSSetTransientVariable(), TSComputeIFunction(), TSComputeIJacobian()
1842: @*/
1843: PetscErrorCode TSComputeTransientVariable(TS ts,Vec U,Vec C)
1844: {
1846: DM dm;
1847: DMTS dmts;
1852: TSGetDM(ts,&dm);
1853: DMGetDMTS(dm,&dmts);
1854: if (dmts->ops->transientvar) {
1856: (*dmts->ops->transientvar)(ts,U,C,dmts->transientvarctx);
1857: }
1858: return(0);
1859: }
1861: /*@
1862: TSHasTransientVariable - determine whether transient variables have been set
1864: Logically Collective
1866: Input Parameters:
1867: . ts - TS on which to compute
1869: Output Parameters:
1870: . has - PETSC_TRUE if transient variables have been set
1872: Level: developer
1874: .seealso: DMTSSetTransientVariable(), TSComputeTransientVariable()
1875: @*/
1876: PetscErrorCode TSHasTransientVariable(TS ts,PetscBool *has)
1877: {
1879: DM dm;
1880: DMTS dmts;
1884: TSGetDM(ts,&dm);
1885: DMGetDMTS(dm,&dmts);
1886: *has = dmts->ops->transientvar ? PETSC_TRUE : PETSC_FALSE;
1887: return(0);
1888: }
1890: /*@
1891: TS2SetSolution - Sets the initial solution and time derivative vectors
1892: for use by the TS routines handling second order equations.
1894: Logically Collective on TS
1896: Input Parameters:
1897: + ts - the TS context obtained from TSCreate()
1898: . u - the solution vector
1899: - v - the time derivative vector
1901: Level: beginner
1903: @*/
1904: PetscErrorCode TS2SetSolution(TS ts,Vec u,Vec v)
1905: {
1912: TSSetSolution(ts,u);
1913: PetscObjectReference((PetscObject)v);
1914: VecDestroy(&ts->vec_dot);
1915: ts->vec_dot = v;
1916: return(0);
1917: }
1919: /*@
1920: TS2GetSolution - Returns the solution and time derivative at the present timestep
1921: for second order equations. It is valid to call this routine inside the function
1922: that you are evaluating in order to move to the new timestep. This vector not
1923: changed until the solution at the next timestep has been calculated.
1925: Not Collective, but Vec returned is parallel if TS is parallel
1927: Input Parameter:
1928: . ts - the TS context obtained from TSCreate()
1930: Output Parameter:
1931: + u - the vector containing the solution
1932: - v - the vector containing the time derivative
1934: Level: intermediate
1936: .seealso: TS2SetSolution(), TSGetTimeStep(), TSGetTime()
1938: @*/
1939: PetscErrorCode TS2GetSolution(TS ts,Vec *u,Vec *v)
1940: {
1945: if (u) *u = ts->vec_sol;
1946: if (v) *v = ts->vec_dot;
1947: return(0);
1948: }
1950: /*@C
1951: TSLoad - Loads a KSP that has been stored in binary with KSPView().
1953: Collective on PetscViewer
1955: Input Parameters:
1956: + newdm - the newly loaded TS, this needs to have been created with TSCreate() or
1957: some related function before a call to TSLoad().
1958: - viewer - binary file viewer, obtained from PetscViewerBinaryOpen()
1960: Level: intermediate
1962: Notes:
1963: The type is determined by the data in the file, any type set into the TS before this call is ignored.
1965: Notes for advanced users:
1966: Most users should not need to know the details of the binary storage
1967: format, since TSLoad() and TSView() completely hide these details.
1968: But for anyone who's interested, the standard binary matrix storage
1969: format is
1970: .vb
1971: has not yet been determined
1972: .ve
1974: .seealso: PetscViewerBinaryOpen(), TSView(), MatLoad(), VecLoad()
1975: @*/
1976: PetscErrorCode TSLoad(TS ts, PetscViewer viewer)
1977: {
1979: PetscBool isbinary;
1980: PetscInt classid;
1981: char type[256];
1982: DMTS sdm;
1983: DM dm;
1988: PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERBINARY,&isbinary);
1989: if (!isbinary) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,"Invalid viewer; open viewer with PetscViewerBinaryOpen()");
1991: PetscViewerBinaryRead(viewer,&classid,1,NULL,PETSC_INT);
1992: if (classid != TS_FILE_CLASSID) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_ARG_WRONG,"Not TS next in file");
1993: PetscViewerBinaryRead(viewer,type,256,NULL,PETSC_CHAR);
1994: TSSetType(ts, type);
1995: if (ts->ops->load) {
1996: (*ts->ops->load)(ts,viewer);
1997: }
1998: DMCreate(PetscObjectComm((PetscObject)ts),&dm);
1999: DMLoad(dm,viewer);
2000: TSSetDM(ts,dm);
2001: DMCreateGlobalVector(ts->dm,&ts->vec_sol);
2002: VecLoad(ts->vec_sol,viewer);
2003: DMGetDMTS(ts->dm,&sdm);
2004: DMTSLoad(sdm,viewer);
2005: return(0);
2006: }
2008: #include <petscdraw.h>
2009: #if defined(PETSC_HAVE_SAWS)
2010: #include <petscviewersaws.h>
2011: #endif
2013: /*@C
2014: TSViewFromOptions - View from Options
2016: Collective on TS
2018: Input Parameters:
2019: + A - the application ordering context
2020: . obj - Optional object
2021: - name - command line option
2023: Level: intermediate
2024: .seealso: TS, TSView, PetscObjectViewFromOptions(), TSCreate()
2025: @*/
2026: PetscErrorCode TSViewFromOptions(TS A,PetscObject obj,const char name[])
2027: {
2032: PetscObjectViewFromOptions((PetscObject)A,obj,name);
2033: return(0);
2034: }
2036: /*@C
2037: TSView - Prints the TS data structure.
2039: Collective on TS
2041: Input Parameters:
2042: + ts - the TS context obtained from TSCreate()
2043: - viewer - visualization context
2045: Options Database Key:
2046: . -ts_view - calls TSView() at end of TSStep()
2048: Notes:
2049: The available visualization contexts include
2050: + PETSC_VIEWER_STDOUT_SELF - standard output (default)
2051: - PETSC_VIEWER_STDOUT_WORLD - synchronized standard
2052: output where only the first processor opens
2053: the file. All other processors send their
2054: data to the first processor to print.
2056: The user can open an alternative visualization context with
2057: PetscViewerASCIIOpen() - output to a specified file.
2059: Level: beginner
2061: .seealso: PetscViewerASCIIOpen()
2062: @*/
2063: PetscErrorCode TSView(TS ts,PetscViewer viewer)
2064: {
2066: TSType type;
2067: PetscBool iascii,isstring,isundials,isbinary,isdraw;
2068: DMTS sdm;
2069: #if defined(PETSC_HAVE_SAWS)
2070: PetscBool issaws;
2071: #endif
2075: if (!viewer) {
2076: PetscViewerASCIIGetStdout(PetscObjectComm((PetscObject)ts),&viewer);
2077: }
2081: PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERASCII,&iascii);
2082: PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERSTRING,&isstring);
2083: PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERBINARY,&isbinary);
2084: PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERDRAW,&isdraw);
2085: #if defined(PETSC_HAVE_SAWS)
2086: PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERSAWS,&issaws);
2087: #endif
2088: if (iascii) {
2089: PetscObjectPrintClassNamePrefixType((PetscObject)ts,viewer);
2090: if (ts->ops->view) {
2091: PetscViewerASCIIPushTab(viewer);
2092: (*ts->ops->view)(ts,viewer);
2093: PetscViewerASCIIPopTab(viewer);
2094: }
2095: if (ts->max_steps < PETSC_MAX_INT) {
2096: PetscViewerASCIIPrintf(viewer," maximum steps=%D\n",ts->max_steps);
2097: }
2098: if (ts->max_time < PETSC_MAX_REAL) {
2099: PetscViewerASCIIPrintf(viewer," maximum time=%g\n",(double)ts->max_time);
2100: }
2101: if (ts->usessnes) {
2102: PetscBool lin;
2103: if (ts->problem_type == TS_NONLINEAR) {
2104: PetscViewerASCIIPrintf(viewer," total number of nonlinear solver iterations=%D\n",ts->snes_its);
2105: }
2106: PetscViewerASCIIPrintf(viewer," total number of linear solver iterations=%D\n",ts->ksp_its);
2107: PetscObjectTypeCompareAny((PetscObject)ts->snes,&lin,SNESKSPONLY,SNESKSPTRANSPOSEONLY,"");
2108: PetscViewerASCIIPrintf(viewer," total number of %slinear solve failures=%D\n",lin ? "" : "non",ts->num_snes_failures);
2109: }
2110: PetscViewerASCIIPrintf(viewer," total number of rejected steps=%D\n",ts->reject);
2111: if (ts->vrtol) {
2112: PetscViewerASCIIPrintf(viewer," using vector of relative error tolerances, ");
2113: } else {
2114: PetscViewerASCIIPrintf(viewer," using relative error tolerance of %g, ",(double)ts->rtol);
2115: }
2116: if (ts->vatol) {
2117: PetscViewerASCIIPrintf(viewer," using vector of absolute error tolerances\n");
2118: } else {
2119: PetscViewerASCIIPrintf(viewer," using absolute error tolerance of %g\n",(double)ts->atol);
2120: }
2121: PetscViewerASCIIPushTab(viewer);
2122: TSAdaptView(ts->adapt,viewer);
2123: PetscViewerASCIIPopTab(viewer);
2124: } else if (isstring) {
2125: TSGetType(ts,&type);
2126: PetscViewerStringSPrintf(viewer," TSType: %-7.7s",type);
2127: if (ts->ops->view) {(*ts->ops->view)(ts,viewer);}
2128: } else if (isbinary) {
2129: PetscInt classid = TS_FILE_CLASSID;
2130: MPI_Comm comm;
2131: PetscMPIInt rank;
2132: char type[256];
2134: PetscObjectGetComm((PetscObject)ts,&comm);
2135: MPI_Comm_rank(comm,&rank);
2136: if (!rank) {
2137: PetscViewerBinaryWrite(viewer,&classid,1,PETSC_INT);
2138: PetscStrncpy(type,((PetscObject)ts)->type_name,256);
2139: PetscViewerBinaryWrite(viewer,type,256,PETSC_CHAR);
2140: }
2141: if (ts->ops->view) {
2142: (*ts->ops->view)(ts,viewer);
2143: }
2144: if (ts->adapt) {TSAdaptView(ts->adapt,viewer);}
2145: DMView(ts->dm,viewer);
2146: VecView(ts->vec_sol,viewer);
2147: DMGetDMTS(ts->dm,&sdm);
2148: DMTSView(sdm,viewer);
2149: } else if (isdraw) {
2150: PetscDraw draw;
2151: char str[36];
2152: PetscReal x,y,bottom,h;
2154: PetscViewerDrawGetDraw(viewer,0,&draw);
2155: PetscDrawGetCurrentPoint(draw,&x,&y);
2156: PetscStrcpy(str,"TS: ");
2157: PetscStrcat(str,((PetscObject)ts)->type_name);
2158: PetscDrawStringBoxed(draw,x,y,PETSC_DRAW_BLACK,PETSC_DRAW_BLACK,str,NULL,&h);
2159: bottom = y - h;
2160: PetscDrawPushCurrentPoint(draw,x,bottom);
2161: if (ts->ops->view) {
2162: (*ts->ops->view)(ts,viewer);
2163: }
2164: if (ts->adapt) {TSAdaptView(ts->adapt,viewer);}
2165: if (ts->snes) {SNESView(ts->snes,viewer);}
2166: PetscDrawPopCurrentPoint(draw);
2167: #if defined(PETSC_HAVE_SAWS)
2168: } else if (issaws) {
2169: PetscMPIInt rank;
2170: const char *name;
2172: PetscObjectGetName((PetscObject)ts,&name);
2173: MPI_Comm_rank(PETSC_COMM_WORLD,&rank);
2174: if (!((PetscObject)ts)->amsmem && !rank) {
2175: char dir[1024];
2177: PetscObjectViewSAWs((PetscObject)ts,viewer);
2178: PetscSNPrintf(dir,1024,"/PETSc/Objects/%s/time_step",name);
2179: PetscStackCallSAWs(SAWs_Register,(dir,&ts->steps,1,SAWs_READ,SAWs_INT));
2180: PetscSNPrintf(dir,1024,"/PETSc/Objects/%s/time",name);
2181: PetscStackCallSAWs(SAWs_Register,(dir,&ts->ptime,1,SAWs_READ,SAWs_DOUBLE));
2182: }
2183: if (ts->ops->view) {
2184: (*ts->ops->view)(ts,viewer);
2185: }
2186: #endif
2187: }
2188: if (ts->snes && ts->usessnes) {
2189: PetscViewerASCIIPushTab(viewer);
2190: SNESView(ts->snes,viewer);
2191: PetscViewerASCIIPopTab(viewer);
2192: }
2193: DMGetDMTS(ts->dm,&sdm);
2194: DMTSView(sdm,viewer);
2196: PetscViewerASCIIPushTab(viewer);
2197: PetscObjectTypeCompare((PetscObject)ts,TSSUNDIALS,&isundials);
2198: PetscViewerASCIIPopTab(viewer);
2199: return(0);
2200: }
2202: /*@
2203: TSSetApplicationContext - Sets an optional user-defined context for
2204: the timesteppers.
2206: Logically Collective on TS
2208: Input Parameters:
2209: + ts - the TS context obtained from TSCreate()
2210: - usrP - optional user context
2212: Fortran Notes:
2213: To use this from Fortran you must write a Fortran interface definition for this
2214: function that tells Fortran the Fortran derived data type that you are passing in as the ctx argument.
2216: Level: intermediate
2218: .seealso: TSGetApplicationContext()
2219: @*/
2220: PetscErrorCode TSSetApplicationContext(TS ts,void *usrP)
2221: {
2224: ts->user = usrP;
2225: return(0);
2226: }
2228: /*@
2229: TSGetApplicationContext - Gets the user-defined context for the
2230: timestepper.
2232: Not Collective
2234: Input Parameter:
2235: . ts - the TS context obtained from TSCreate()
2237: Output Parameter:
2238: . usrP - user context
2240: Fortran Notes:
2241: To use this from Fortran you must write a Fortran interface definition for this
2242: function that tells Fortran the Fortran derived data type that you are passing in as the ctx argument.
2244: Level: intermediate
2246: .seealso: TSSetApplicationContext()
2247: @*/
2248: PetscErrorCode TSGetApplicationContext(TS ts,void *usrP)
2249: {
2252: *(void**)usrP = ts->user;
2253: return(0);
2254: }
2256: /*@
2257: TSGetStepNumber - Gets the number of steps completed.
2259: Not Collective
2261: Input Parameter:
2262: . ts - the TS context obtained from TSCreate()
2264: Output Parameter:
2265: . steps - number of steps completed so far
2267: Level: intermediate
2269: .seealso: TSGetTime(), TSGetTimeStep(), TSSetPreStep(), TSSetPreStage(), TSSetPostStage(), TSSetPostStep()
2270: @*/
2271: PetscErrorCode TSGetStepNumber(TS ts,PetscInt *steps)
2272: {
2276: *steps = ts->steps;
2277: return(0);
2278: }
2280: /*@
2281: TSSetStepNumber - Sets the number of steps completed.
2283: Logically Collective on TS
2285: Input Parameters:
2286: + ts - the TS context
2287: - steps - number of steps completed so far
2289: Notes:
2290: For most uses of the TS solvers the user need not explicitly call
2291: TSSetStepNumber(), as the step counter is appropriately updated in
2292: TSSolve()/TSStep()/TSRollBack(). Power users may call this routine to
2293: reinitialize timestepping by setting the step counter to zero (and time
2294: to the initial time) to solve a similar problem with different initial
2295: conditions or parameters. Other possible use case is to continue
2296: timestepping from a previously interrupted run in such a way that TS
2297: monitors will be called with a initial nonzero step counter.
2299: Level: advanced
2301: .seealso: TSGetStepNumber(), TSSetTime(), TSSetTimeStep(), TSSetSolution()
2302: @*/
2303: PetscErrorCode TSSetStepNumber(TS ts,PetscInt steps)
2304: {
2308: if (steps < 0) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_ARG_OUTOFRANGE,"Step number must be non-negative");
2309: ts->steps = steps;
2310: return(0);
2311: }
2313: /*@
2314: TSSetTimeStep - Allows one to reset the timestep at any time,
2315: useful for simple pseudo-timestepping codes.
2317: Logically Collective on TS
2319: Input Parameters:
2320: + ts - the TS context obtained from TSCreate()
2321: - time_step - the size of the timestep
2323: Level: intermediate
2325: .seealso: TSGetTimeStep(), TSSetTime()
2327: @*/
2328: PetscErrorCode TSSetTimeStep(TS ts,PetscReal time_step)
2329: {
2333: ts->time_step = time_step;
2334: return(0);
2335: }
2337: /*@
2338: TSSetExactFinalTime - Determines whether to adapt the final time step to
2339: match the exact final time, interpolate solution to the exact final time,
2340: or just return at the final time TS computed.
2342: Logically Collective on TS
2344: Input Parameter:
2345: + ts - the time-step context
2346: - eftopt - exact final time option
2348: $ TS_EXACTFINALTIME_STEPOVER - Don't do anything if final time is exceeded
2349: $ TS_EXACTFINALTIME_INTERPOLATE - Interpolate back to final time
2350: $ TS_EXACTFINALTIME_MATCHSTEP - Adapt final time step to match the final time
2352: Options Database:
2353: . -ts_exact_final_time <stepover,interpolate,matchstep> - select the final step at runtime
2355: Warning: If you use the option TS_EXACTFINALTIME_STEPOVER the solution may be at a very different time
2356: then the final time you selected.
2358: Level: beginner
2360: .seealso: TSExactFinalTimeOption, TSGetExactFinalTime()
2361: @*/
2362: PetscErrorCode TSSetExactFinalTime(TS ts,TSExactFinalTimeOption eftopt)
2363: {
2367: ts->exact_final_time = eftopt;
2368: return(0);
2369: }
2371: /*@
2372: TSGetExactFinalTime - Gets the exact final time option.
2374: Not Collective
2376: Input Parameter:
2377: . ts - the TS context
2379: Output Parameter:
2380: . eftopt - exact final time option
2382: Level: beginner
2384: .seealso: TSExactFinalTimeOption, TSSetExactFinalTime()
2385: @*/
2386: PetscErrorCode TSGetExactFinalTime(TS ts,TSExactFinalTimeOption *eftopt)
2387: {
2391: *eftopt = ts->exact_final_time;
2392: return(0);
2393: }
2395: /*@
2396: TSGetTimeStep - Gets the current timestep size.
2398: Not Collective
2400: Input Parameter:
2401: . ts - the TS context obtained from TSCreate()
2403: Output Parameter:
2404: . dt - the current timestep size
2406: Level: intermediate
2408: .seealso: TSSetTimeStep(), TSGetTime()
2410: @*/
2411: PetscErrorCode TSGetTimeStep(TS ts,PetscReal *dt)
2412: {
2416: *dt = ts->time_step;
2417: return(0);
2418: }
2420: /*@
2421: TSGetSolution - Returns the solution at the present timestep. It
2422: is valid to call this routine inside the function that you are evaluating
2423: in order to move to the new timestep. This vector not changed until
2424: the solution at the next timestep has been calculated.
2426: Not Collective, but Vec returned is parallel if TS is parallel
2428: Input Parameter:
2429: . ts - the TS context obtained from TSCreate()
2431: Output Parameter:
2432: . v - the vector containing the solution
2434: Note: If you used TSSetExactFinalTime(ts,TS_EXACTFINALTIME_MATCHSTEP); this does not return the solution at the requested
2435: final time. It returns the solution at the next timestep.
2437: Level: intermediate
2439: .seealso: TSGetTimeStep(), TSGetTime(), TSGetSolveTime(), TSGetSolutionComponents(), TSSetSolutionFunction()
2441: @*/
2442: PetscErrorCode TSGetSolution(TS ts,Vec *v)
2443: {
2447: *v = ts->vec_sol;
2448: return(0);
2449: }
2451: /*@
2452: TSGetSolutionComponents - Returns any solution components at the present
2453: timestep, if available for the time integration method being used.
2454: Solution components are quantities that share the same size and
2455: structure as the solution vector.
2457: Not Collective, but Vec returned is parallel if TS is parallel
2459: Parameters :
2460: + ts - the TS context obtained from TSCreate() (input parameter).
2461: . n - If v is PETSC_NULL, then the number of solution components is
2462: returned through n, else the n-th solution component is
2463: returned in v.
2464: - v - the vector containing the n-th solution component
2465: (may be PETSC_NULL to use this function to find out
2466: the number of solutions components).
2468: Level: advanced
2470: .seealso: TSGetSolution()
2472: @*/
2473: PetscErrorCode TSGetSolutionComponents(TS ts,PetscInt *n,Vec *v)
2474: {
2479: if (!ts->ops->getsolutioncomponents) *n = 0;
2480: else {
2481: (*ts->ops->getsolutioncomponents)(ts,n,v);
2482: }
2483: return(0);
2484: }
2486: /*@
2487: TSGetAuxSolution - Returns an auxiliary solution at the present
2488: timestep, if available for the time integration method being used.
2490: Not Collective, but Vec returned is parallel if TS is parallel
2492: Parameters :
2493: + ts - the TS context obtained from TSCreate() (input parameter).
2494: - v - the vector containing the auxiliary solution
2496: Level: intermediate
2498: .seealso: TSGetSolution()
2500: @*/
2501: PetscErrorCode TSGetAuxSolution(TS ts,Vec *v)
2502: {
2507: if (ts->ops->getauxsolution) {
2508: (*ts->ops->getauxsolution)(ts,v);
2509: } else {
2510: VecZeroEntries(*v);
2511: }
2512: return(0);
2513: }
2515: /*@
2516: TSGetTimeError - Returns the estimated error vector, if the chosen
2517: TSType has an error estimation functionality.
2519: Not Collective, but Vec returned is parallel if TS is parallel
2521: Note: MUST call after TSSetUp()
2523: Parameters :
2524: + ts - the TS context obtained from TSCreate() (input parameter).
2525: . n - current estimate (n=0) or previous one (n=-1)
2526: - v - the vector containing the error (same size as the solution).
2528: Level: intermediate
2530: .seealso: TSGetSolution(), TSSetTimeError()
2532: @*/
2533: PetscErrorCode TSGetTimeError(TS ts,PetscInt n,Vec *v)
2534: {
2539: if (ts->ops->gettimeerror) {
2540: (*ts->ops->gettimeerror)(ts,n,v);
2541: } else {
2542: VecZeroEntries(*v);
2543: }
2544: return(0);
2545: }
2547: /*@
2548: TSSetTimeError - Sets the estimated error vector, if the chosen
2549: TSType has an error estimation functionality. This can be used
2550: to restart such a time integrator with a given error vector.
2552: Not Collective, but Vec returned is parallel if TS is parallel
2554: Parameters :
2555: + ts - the TS context obtained from TSCreate() (input parameter).
2556: - v - the vector containing the error (same size as the solution).
2558: Level: intermediate
2560: .seealso: TSSetSolution(), TSGetTimeError)
2562: @*/
2563: PetscErrorCode TSSetTimeError(TS ts,Vec v)
2564: {
2569: if (!ts->setupcalled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Must call TSSetUp() first");
2570: if (ts->ops->settimeerror) {
2571: (*ts->ops->settimeerror)(ts,v);
2572: }
2573: return(0);
2574: }
2576: /* ----- Routines to initialize and destroy a timestepper ---- */
2577: /*@
2578: TSSetProblemType - Sets the type of problem to be solved.
2580: Not collective
2582: Input Parameters:
2583: + ts - The TS
2584: - type - One of TS_LINEAR, TS_NONLINEAR where these types refer to problems of the forms
2585: .vb
2586: U_t - A U = 0 (linear)
2587: U_t - A(t) U = 0 (linear)
2588: F(t,U,U_t) = 0 (nonlinear)
2589: .ve
2591: Level: beginner
2593: .seealso: TSSetUp(), TSProblemType, TS
2594: @*/
2595: PetscErrorCode TSSetProblemType(TS ts, TSProblemType type)
2596: {
2601: ts->problem_type = type;
2602: if (type == TS_LINEAR) {
2603: SNES snes;
2604: TSGetSNES(ts,&snes);
2605: SNESSetType(snes,SNESKSPONLY);
2606: }
2607: return(0);
2608: }
2610: /*@C
2611: TSGetProblemType - Gets the type of problem to be solved.
2613: Not collective
2615: Input Parameter:
2616: . ts - The TS
2618: Output Parameter:
2619: . type - One of TS_LINEAR, TS_NONLINEAR where these types refer to problems of the forms
2620: .vb
2621: M U_t = A U
2622: M(t) U_t = A(t) U
2623: F(t,U,U_t)
2624: .ve
2626: Level: beginner
2628: .seealso: TSSetUp(), TSProblemType, TS
2629: @*/
2630: PetscErrorCode TSGetProblemType(TS ts, TSProblemType *type)
2631: {
2635: *type = ts->problem_type;
2636: return(0);
2637: }
2639: /*
2640: Attempt to check/preset a default value for the exact final time option. This is needed at the beginning of TSSolve() and in TSSetUp()
2641: */
2642: static PetscErrorCode TSSetExactFinalTimeDefault(TS ts)
2643: {
2645: PetscBool isnone;
2648: TSGetAdapt(ts,&ts->adapt);
2649: TSAdaptSetDefaultType(ts->adapt,ts->default_adapt_type);
2651: PetscObjectTypeCompare((PetscObject)ts->adapt,TSADAPTNONE,&isnone);
2652: if (!isnone && ts->exact_final_time == TS_EXACTFINALTIME_UNSPECIFIED) {
2653: ts->exact_final_time = TS_EXACTFINALTIME_MATCHSTEP;
2654: } else if (ts->exact_final_time == TS_EXACTFINALTIME_UNSPECIFIED) {
2655: ts->exact_final_time = TS_EXACTFINALTIME_INTERPOLATE;
2656: }
2657: return(0);
2658: }
2661: /*@
2662: TSSetUp - Sets up the internal data structures for the later use of a timestepper.
2664: Collective on TS
2666: Input Parameter:
2667: . ts - the TS context obtained from TSCreate()
2669: Notes:
2670: For basic use of the TS solvers the user need not explicitly call
2671: TSSetUp(), since these actions will automatically occur during
2672: the call to TSStep() or TSSolve(). However, if one wishes to control this
2673: phase separately, TSSetUp() should be called after TSCreate()
2674: and optional routines of the form TSSetXXX(), but before TSStep() and TSSolve().
2676: Level: advanced
2678: .seealso: TSCreate(), TSStep(), TSDestroy(), TSSolve()
2679: @*/
2680: PetscErrorCode TSSetUp(TS ts)
2681: {
2683: DM dm;
2684: PetscErrorCode (*func)(SNES,Vec,Vec,void*);
2685: PetscErrorCode (*jac)(SNES,Vec,Mat,Mat,void*);
2686: TSIFunction ifun;
2687: TSIJacobian ijac;
2688: TSI2Jacobian i2jac;
2689: TSRHSJacobian rhsjac;
2693: if (ts->setupcalled) return(0);
2695: if (!((PetscObject)ts)->type_name) {
2696: TSGetIFunction(ts,NULL,&ifun,NULL);
2697: TSSetType(ts,ifun ? TSBEULER : TSEULER);
2698: }
2700: if (!ts->vec_sol) {
2701: if (ts->dm) {
2702: DMCreateGlobalVector(ts->dm,&ts->vec_sol);
2703: } else SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Must call TSSetSolution() first");
2704: }
2706: if (!ts->Jacp && ts->Jacprhs) { /* IJacobianP shares the same matrix with RHSJacobianP if only RHSJacobianP is provided */
2707: PetscObjectReference((PetscObject)ts->Jacprhs);
2708: ts->Jacp = ts->Jacprhs;
2709: }
2711: if (ts->quadraturets) {
2712: TSSetUp(ts->quadraturets);
2713: VecDestroy(&ts->vec_costintegrand);
2714: VecDuplicate(ts->quadraturets->vec_sol,&ts->vec_costintegrand);
2715: }
2717: TSGetRHSJacobian(ts,NULL,NULL,&rhsjac,NULL);
2718: if (rhsjac == TSComputeRHSJacobianConstant) {
2719: Mat Amat,Pmat;
2720: SNES snes;
2721: TSGetSNES(ts,&snes);
2722: SNESGetJacobian(snes,&Amat,&Pmat,NULL,NULL);
2723: /* Matching matrices implies that an IJacobian is NOT set, because if it had been set, the IJacobian's matrix would
2724: * have displaced the RHS matrix */
2725: if (Amat && Amat == ts->Arhs) {
2726: /* 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 */
2727: MatDuplicate(ts->Arhs,MAT_COPY_VALUES,&Amat);
2728: SNESSetJacobian(snes,Amat,NULL,NULL,NULL);
2729: MatDestroy(&Amat);
2730: }
2731: if (Pmat && Pmat == ts->Brhs) {
2732: MatDuplicate(ts->Brhs,MAT_COPY_VALUES,&Pmat);
2733: SNESSetJacobian(snes,NULL,Pmat,NULL,NULL);
2734: MatDestroy(&Pmat);
2735: }
2736: }
2738: TSGetAdapt(ts,&ts->adapt);
2739: TSAdaptSetDefaultType(ts->adapt,ts->default_adapt_type);
2741: if (ts->ops->setup) {
2742: (*ts->ops->setup)(ts);
2743: }
2745: TSSetExactFinalTimeDefault(ts);
2747: /* In the case where we've set a DMTSFunction or what have you, we need the default SNESFunction
2748: to be set right but can't do it elsewhere due to the overreliance on ctx=ts.
2749: */
2750: TSGetDM(ts,&dm);
2751: DMSNESGetFunction(dm,&func,NULL);
2752: if (!func) {
2753: DMSNESSetFunction(dm,SNESTSFormFunction,ts);
2754: }
2755: /* If the SNES doesn't have a jacobian set and the TS has an ijacobian or rhsjacobian set, set the SNES to use it.
2756: Otherwise, the SNES will use coloring internally to form the Jacobian.
2757: */
2758: DMSNESGetJacobian(dm,&jac,NULL);
2759: DMTSGetIJacobian(dm,&ijac,NULL);
2760: DMTSGetI2Jacobian(dm,&i2jac,NULL);
2761: DMTSGetRHSJacobian(dm,&rhsjac,NULL);
2762: if (!jac && (ijac || i2jac || rhsjac)) {
2763: DMSNESSetJacobian(dm,SNESTSFormJacobian,ts);
2764: }
2766: /* if time integration scheme has a starting method, call it */
2767: if (ts->ops->startingmethod) {
2768: (*ts->ops->startingmethod)(ts);
2769: }
2771: ts->setupcalled = PETSC_TRUE;
2772: return(0);
2773: }
2775: /*@
2776: TSReset - Resets a TS context and removes any allocated Vecs and Mats.
2778: Collective on TS
2780: Input Parameter:
2781: . ts - the TS context obtained from TSCreate()
2783: Level: beginner
2785: .seealso: TSCreate(), TSSetup(), TSDestroy()
2786: @*/
2787: PetscErrorCode TSReset(TS ts)
2788: {
2789: TS_RHSSplitLink ilink = ts->tsrhssplit,next;
2790: PetscErrorCode ierr;
2795: if (ts->ops->reset) {
2796: (*ts->ops->reset)(ts);
2797: }
2798: if (ts->snes) {SNESReset(ts->snes);}
2799: if (ts->adapt) {TSAdaptReset(ts->adapt);}
2801: MatDestroy(&ts->Arhs);
2802: MatDestroy(&ts->Brhs);
2803: VecDestroy(&ts->Frhs);
2804: VecDestroy(&ts->vec_sol);
2805: VecDestroy(&ts->vec_dot);
2806: VecDestroy(&ts->vatol);
2807: VecDestroy(&ts->vrtol);
2808: VecDestroyVecs(ts->nwork,&ts->work);
2810: MatDestroy(&ts->Jacprhs);
2811: MatDestroy(&ts->Jacp);
2812: if (ts->forward_solve) {
2813: TSForwardReset(ts);
2814: }
2815: if (ts->quadraturets) {
2816: TSReset(ts->quadraturets);
2817: VecDestroy(&ts->vec_costintegrand);
2818: }
2819: while (ilink) {
2820: next = ilink->next;
2821: TSDestroy(&ilink->ts);
2822: PetscFree(ilink->splitname);
2823: ISDestroy(&ilink->is);
2824: PetscFree(ilink);
2825: ilink = next;
2826: }
2827: ts->num_rhs_splits = 0;
2828: ts->setupcalled = PETSC_FALSE;
2829: return(0);
2830: }
2832: /*@
2833: TSDestroy - Destroys the timestepper context that was created
2834: with TSCreate().
2836: Collective on TS
2838: Input Parameter:
2839: . ts - the TS context obtained from TSCreate()
2841: Level: beginner
2843: .seealso: TSCreate(), TSSetUp(), TSSolve()
2844: @*/
2845: PetscErrorCode TSDestroy(TS *ts)
2846: {
2850: if (!*ts) return(0);
2852: if (--((PetscObject)(*ts))->refct > 0) {*ts = NULL; return(0);}
2854: TSReset(*ts);
2855: TSAdjointReset(*ts);
2856: if ((*ts)->forward_solve) {
2857: TSForwardReset(*ts);
2858: }
2859: /* if memory was published with SAWs then destroy it */
2860: PetscObjectSAWsViewOff((PetscObject)*ts);
2861: if ((*ts)->ops->destroy) {(*(*ts)->ops->destroy)((*ts));}
2863: TSTrajectoryDestroy(&(*ts)->trajectory);
2865: TSAdaptDestroy(&(*ts)->adapt);
2866: TSEventDestroy(&(*ts)->event);
2868: SNESDestroy(&(*ts)->snes);
2869: DMDestroy(&(*ts)->dm);
2870: TSMonitorCancel((*ts));
2871: TSAdjointMonitorCancel((*ts));
2873: TSDestroy(&(*ts)->quadraturets);
2874: PetscHeaderDestroy(ts);
2875: return(0);
2876: }
2878: /*@
2879: TSGetSNES - Returns the SNES (nonlinear solver) associated with
2880: a TS (timestepper) context. Valid only for nonlinear problems.
2882: Not Collective, but SNES is parallel if TS is parallel
2884: Input Parameter:
2885: . ts - the TS context obtained from TSCreate()
2887: Output Parameter:
2888: . snes - the nonlinear solver context
2890: Notes:
2891: The user can then directly manipulate the SNES context to set various
2892: options, etc. Likewise, the user can then extract and manipulate the
2893: KSP, KSP, and PC contexts as well.
2895: TSGetSNES() does not work for integrators that do not use SNES; in
2896: this case TSGetSNES() returns NULL in snes.
2898: Level: beginner
2900: @*/
2901: PetscErrorCode TSGetSNES(TS ts,SNES *snes)
2902: {
2908: if (!ts->snes) {
2909: SNESCreate(PetscObjectComm((PetscObject)ts),&ts->snes);
2910: PetscObjectSetOptions((PetscObject)ts->snes,((PetscObject)ts)->options);
2911: SNESSetFunction(ts->snes,NULL,SNESTSFormFunction,ts);
2912: PetscLogObjectParent((PetscObject)ts,(PetscObject)ts->snes);
2913: PetscObjectIncrementTabLevel((PetscObject)ts->snes,(PetscObject)ts,1);
2914: if (ts->dm) {SNESSetDM(ts->snes,ts->dm);}
2915: if (ts->problem_type == TS_LINEAR) {
2916: SNESSetType(ts->snes,SNESKSPONLY);
2917: }
2918: }
2919: *snes = ts->snes;
2920: return(0);
2921: }
2923: /*@
2924: TSSetSNES - Set the SNES (nonlinear solver) to be used by the timestepping context
2926: Collective
2928: Input Parameter:
2929: + ts - the TS context obtained from TSCreate()
2930: - snes - the nonlinear solver context
2932: Notes:
2933: Most users should have the TS created by calling TSGetSNES()
2935: Level: developer
2937: @*/
2938: PetscErrorCode TSSetSNES(TS ts,SNES snes)
2939: {
2941: PetscErrorCode (*func)(SNES,Vec,Mat,Mat,void*);
2946: PetscObjectReference((PetscObject)snes);
2947: SNESDestroy(&ts->snes);
2949: ts->snes = snes;
2951: SNESSetFunction(ts->snes,NULL,SNESTSFormFunction,ts);
2952: SNESGetJacobian(ts->snes,NULL,NULL,&func,NULL);
2953: if (func == SNESTSFormJacobian) {
2954: SNESSetJacobian(ts->snes,NULL,NULL,SNESTSFormJacobian,ts);
2955: }
2956: return(0);
2957: }
2959: /*@
2960: TSGetKSP - Returns the KSP (linear solver) associated with
2961: a TS (timestepper) context.
2963: Not Collective, but KSP is parallel if TS is parallel
2965: Input Parameter:
2966: . ts - the TS context obtained from TSCreate()
2968: Output Parameter:
2969: . ksp - the nonlinear solver context
2971: Notes:
2972: The user can then directly manipulate the KSP context to set various
2973: options, etc. Likewise, the user can then extract and manipulate the
2974: KSP and PC contexts as well.
2976: TSGetKSP() does not work for integrators that do not use KSP;
2977: in this case TSGetKSP() returns NULL in ksp.
2979: Level: beginner
2981: @*/
2982: PetscErrorCode TSGetKSP(TS ts,KSP *ksp)
2983: {
2985: SNES snes;
2990: if (!((PetscObject)ts)->type_name) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_NULL,"KSP is not created yet. Call TSSetType() first");
2991: if (ts->problem_type != TS_LINEAR) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,"Linear only; use TSGetSNES()");
2992: TSGetSNES(ts,&snes);
2993: SNESGetKSP(snes,ksp);
2994: return(0);
2995: }
2997: /* ----------- Routines to set solver parameters ---------- */
2999: /*@
3000: TSSetMaxSteps - Sets the maximum number of steps to use.
3002: Logically Collective on TS
3004: Input Parameters:
3005: + ts - the TS context obtained from TSCreate()
3006: - maxsteps - maximum number of steps to use
3008: Options Database Keys:
3009: . -ts_max_steps <maxsteps> - Sets maxsteps
3011: Notes:
3012: The default maximum number of steps is 5000
3014: Level: intermediate
3016: .seealso: TSGetMaxSteps(), TSSetMaxTime(), TSSetExactFinalTime()
3017: @*/
3018: PetscErrorCode TSSetMaxSteps(TS ts,PetscInt maxsteps)
3019: {
3023: if (maxsteps < 0) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_ARG_OUTOFRANGE,"Maximum number of steps must be non-negative");
3024: ts->max_steps = maxsteps;
3025: return(0);
3026: }
3028: /*@
3029: TSGetMaxSteps - Gets the maximum number of steps to use.
3031: Not Collective
3033: Input Parameters:
3034: . ts - the TS context obtained from TSCreate()
3036: Output Parameter:
3037: . maxsteps - maximum number of steps to use
3039: Level: advanced
3041: .seealso: TSSetMaxSteps(), TSGetMaxTime(), TSSetMaxTime()
3042: @*/
3043: PetscErrorCode TSGetMaxSteps(TS ts,PetscInt *maxsteps)
3044: {
3048: *maxsteps = ts->max_steps;
3049: return(0);
3050: }
3052: /*@
3053: TSSetMaxTime - Sets the maximum (or final) time for timestepping.
3055: Logically Collective on TS
3057: Input Parameters:
3058: + ts - the TS context obtained from TSCreate()
3059: - maxtime - final time to step to
3061: Options Database Keys:
3062: . -ts_max_time <maxtime> - Sets maxtime
3064: Notes:
3065: The default maximum time is 5.0
3067: Level: intermediate
3069: .seealso: TSGetMaxTime(), TSSetMaxSteps(), TSSetExactFinalTime()
3070: @*/
3071: PetscErrorCode TSSetMaxTime(TS ts,PetscReal maxtime)
3072: {
3076: ts->max_time = maxtime;
3077: return(0);
3078: }
3080: /*@
3081: TSGetMaxTime - Gets the maximum (or final) time for timestepping.
3083: Not Collective
3085: Input Parameters:
3086: . ts - the TS context obtained from TSCreate()
3088: Output Parameter:
3089: . maxtime - final time to step to
3091: Level: advanced
3093: .seealso: TSSetMaxTime(), TSGetMaxSteps(), TSSetMaxSteps()
3094: @*/
3095: PetscErrorCode TSGetMaxTime(TS ts,PetscReal *maxtime)
3096: {
3100: *maxtime = ts->max_time;
3101: return(0);
3102: }
3104: /*@
3105: TSSetInitialTimeStep - Deprecated, use TSSetTime() and TSSetTimeStep().
3107: Level: deprecated
3109: @*/
3110: PetscErrorCode TSSetInitialTimeStep(TS ts,PetscReal initial_time,PetscReal time_step)
3111: {
3115: TSSetTime(ts,initial_time);
3116: TSSetTimeStep(ts,time_step);
3117: return(0);
3118: }
3120: /*@
3121: TSGetDuration - Deprecated, use TSGetMaxSteps() and TSGetMaxTime().
3123: Level: deprecated
3125: @*/
3126: PetscErrorCode TSGetDuration(TS ts, PetscInt *maxsteps, PetscReal *maxtime)
3127: {
3130: if (maxsteps) {
3132: *maxsteps = ts->max_steps;
3133: }
3134: if (maxtime) {
3136: *maxtime = ts->max_time;
3137: }
3138: return(0);
3139: }
3141: /*@
3142: TSSetDuration - Deprecated, use TSSetMaxSteps() and TSSetMaxTime().
3144: Level: deprecated
3146: @*/
3147: PetscErrorCode TSSetDuration(TS ts,PetscInt maxsteps,PetscReal maxtime)
3148: {
3153: if (maxsteps >= 0) ts->max_steps = maxsteps;
3154: if (maxtime != PETSC_DEFAULT) ts->max_time = maxtime;
3155: return(0);
3156: }
3158: /*@
3159: TSGetTimeStepNumber - Deprecated, use TSGetStepNumber().
3161: Level: deprecated
3163: @*/
3164: PetscErrorCode TSGetTimeStepNumber(TS ts,PetscInt *steps) { return TSGetStepNumber(ts,steps); }
3166: /*@
3167: TSGetTotalSteps - Deprecated, use TSGetStepNumber().
3169: Level: deprecated
3171: @*/
3172: PetscErrorCode TSGetTotalSteps(TS ts,PetscInt *steps) { return TSGetStepNumber(ts,steps); }
3174: /*@
3175: TSSetSolution - Sets the initial solution vector
3176: for use by the TS routines.
3178: Logically Collective on TS
3180: Input Parameters:
3181: + ts - the TS context obtained from TSCreate()
3182: - u - the solution vector
3184: Level: beginner
3186: .seealso: TSSetSolutionFunction(), TSGetSolution(), TSCreate()
3187: @*/
3188: PetscErrorCode TSSetSolution(TS ts,Vec u)
3189: {
3191: DM dm;
3196: PetscObjectReference((PetscObject)u);
3197: VecDestroy(&ts->vec_sol);
3198: ts->vec_sol = u;
3200: TSGetDM(ts,&dm);
3201: DMShellSetGlobalVector(dm,u);
3202: return(0);
3203: }
3205: /*@C
3206: TSSetPreStep - Sets the general-purpose function
3207: called once at the beginning of each time step.
3209: Logically Collective on TS
3211: Input Parameters:
3212: + ts - The TS context obtained from TSCreate()
3213: - func - The function
3215: Calling sequence of func:
3216: . PetscErrorCode func (TS ts);
3218: Level: intermediate
3220: .seealso: TSSetPreStage(), TSSetPostStage(), TSSetPostStep(), TSStep(), TSRestartStep()
3221: @*/
3222: PetscErrorCode TSSetPreStep(TS ts, PetscErrorCode (*func)(TS))
3223: {
3226: ts->prestep = func;
3227: return(0);
3228: }
3230: /*@
3231: TSPreStep - Runs the user-defined pre-step function.
3233: Collective on TS
3235: Input Parameters:
3236: . ts - The TS context obtained from TSCreate()
3238: Notes:
3239: TSPreStep() is typically used within time stepping implementations,
3240: so most users would not generally call this routine themselves.
3242: Level: developer
3244: .seealso: TSSetPreStep(), TSPreStage(), TSPostStage(), TSPostStep()
3245: @*/
3246: PetscErrorCode TSPreStep(TS ts)
3247: {
3252: if (ts->prestep) {
3253: Vec U;
3254: PetscObjectState sprev,spost;
3256: TSGetSolution(ts,&U);
3257: PetscObjectStateGet((PetscObject)U,&sprev);
3258: PetscStackCallStandard((*ts->prestep),(ts));
3259: PetscObjectStateGet((PetscObject)U,&spost);
3260: if (sprev != spost) {TSRestartStep(ts);}
3261: }
3262: return(0);
3263: }
3265: /*@C
3266: TSSetPreStage - Sets the general-purpose function
3267: called once at the beginning of each stage.
3269: Logically Collective on TS
3271: Input Parameters:
3272: + ts - The TS context obtained from TSCreate()
3273: - func - The function
3275: Calling sequence of func:
3276: . PetscErrorCode func(TS ts, PetscReal stagetime);
3278: Level: intermediate
3280: Note:
3281: There may be several stages per time step. If the solve for a given stage fails, the step may be rejected and retried.
3282: The time step number being computed can be queried using TSGetStepNumber() and the total size of the step being
3283: attempted can be obtained using TSGetTimeStep(). The time at the start of the step is available via TSGetTime().
3285: .seealso: TSSetPostStage(), TSSetPreStep(), TSSetPostStep(), TSGetApplicationContext()
3286: @*/
3287: PetscErrorCode TSSetPreStage(TS ts, PetscErrorCode (*func)(TS,PetscReal))
3288: {
3291: ts->prestage = func;
3292: return(0);
3293: }
3295: /*@C
3296: TSSetPostStage - Sets the general-purpose function
3297: called once at the end of each stage.
3299: Logically Collective on TS
3301: Input Parameters:
3302: + ts - The TS context obtained from TSCreate()
3303: - func - The function
3305: Calling sequence of func:
3306: . PetscErrorCode func(TS ts, PetscReal stagetime, PetscInt stageindex, Vec* Y);
3308: Level: intermediate
3310: Note:
3311: There may be several stages per time step. If the solve for a given stage fails, the step may be rejected and retried.
3312: The time step number being computed can be queried using TSGetStepNumber() and the total size of the step being
3313: attempted can be obtained using TSGetTimeStep(). The time at the start of the step is available via TSGetTime().
3315: .seealso: TSSetPreStage(), TSSetPreStep(), TSSetPostStep(), TSGetApplicationContext()
3316: @*/
3317: PetscErrorCode TSSetPostStage(TS ts, PetscErrorCode (*func)(TS,PetscReal,PetscInt,Vec*))
3318: {
3321: ts->poststage = func;
3322: return(0);
3323: }
3325: /*@C
3326: TSSetPostEvaluate - Sets the general-purpose function
3327: called once at the end of each step evaluation.
3329: Logically Collective on TS
3331: Input Parameters:
3332: + ts - The TS context obtained from TSCreate()
3333: - func - The function
3335: Calling sequence of func:
3336: . PetscErrorCode func(TS ts);
3338: Level: intermediate
3340: Note:
3341: Semantically, TSSetPostEvaluate() differs from TSSetPostStep() since the function it sets is called before event-handling
3342: thus guaranteeing the same solution (computed by the time-stepper) will be passed to it. On the other hand, TSPostStep()
3343: may be passed a different solution, possibly changed by the event handler. TSPostEvaluate() is called after the next step
3344: solution is evaluated allowing to modify it, if need be. The solution can be obtained with TSGetSolution(), the time step
3345: with TSGetTimeStep(), and the time at the start of the step is available via TSGetTime()
3347: .seealso: TSSetPreStage(), TSSetPreStep(), TSSetPostStep(), TSGetApplicationContext()
3348: @*/
3349: PetscErrorCode TSSetPostEvaluate(TS ts, PetscErrorCode (*func)(TS))
3350: {
3353: ts->postevaluate = func;
3354: return(0);
3355: }
3357: /*@
3358: TSPreStage - Runs the user-defined pre-stage function set using TSSetPreStage()
3360: Collective on TS
3362: Input Parameters:
3363: . ts - The TS context obtained from TSCreate()
3364: stagetime - The absolute time of the current stage
3366: Notes:
3367: TSPreStage() is typically used within time stepping implementations,
3368: most users would not generally call this routine themselves.
3370: Level: developer
3372: .seealso: TSPostStage(), TSSetPreStep(), TSPreStep(), TSPostStep()
3373: @*/
3374: PetscErrorCode TSPreStage(TS ts, PetscReal stagetime)
3375: {
3378: if (ts->prestage) {
3379: PetscStackCallStandard((*ts->prestage),(ts,stagetime));
3380: }
3381: return(0);
3382: }
3384: /*@
3385: TSPostStage - Runs the user-defined post-stage function set using TSSetPostStage()
3387: Collective on TS
3389: Input Parameters:
3390: . ts - The TS context obtained from TSCreate()
3391: stagetime - The absolute time of the current stage
3392: stageindex - Stage number
3393: Y - Array of vectors (of size = total number
3394: of stages) with the stage solutions
3396: Notes:
3397: TSPostStage() is typically used within time stepping implementations,
3398: most users would not generally call this routine themselves.
3400: Level: developer
3402: .seealso: TSPreStage(), TSSetPreStep(), TSPreStep(), TSPostStep()
3403: @*/
3404: PetscErrorCode TSPostStage(TS ts, PetscReal stagetime, PetscInt stageindex, Vec *Y)
3405: {
3408: if (ts->poststage) {
3409: PetscStackCallStandard((*ts->poststage),(ts,stagetime,stageindex,Y));
3410: }
3411: return(0);
3412: }
3414: /*@
3415: TSPostEvaluate - Runs the user-defined post-evaluate function set using TSSetPostEvaluate()
3417: Collective on TS
3419: Input Parameters:
3420: . ts - The TS context obtained from TSCreate()
3422: Notes:
3423: TSPostEvaluate() is typically used within time stepping implementations,
3424: most users would not generally call this routine themselves.
3426: Level: developer
3428: .seealso: TSSetPostEvaluate(), TSSetPreStep(), TSPreStep(), TSPostStep()
3429: @*/
3430: PetscErrorCode TSPostEvaluate(TS ts)
3431: {
3436: if (ts->postevaluate) {
3437: Vec U;
3438: PetscObjectState sprev,spost;
3440: TSGetSolution(ts,&U);
3441: PetscObjectStateGet((PetscObject)U,&sprev);
3442: PetscStackCallStandard((*ts->postevaluate),(ts));
3443: PetscObjectStateGet((PetscObject)U,&spost);
3444: if (sprev != spost) {TSRestartStep(ts);}
3445: }
3446: return(0);
3447: }
3449: /*@C
3450: TSSetPostStep - Sets the general-purpose function
3451: called once at the end of each time step.
3453: Logically Collective on TS
3455: Input Parameters:
3456: + ts - The TS context obtained from TSCreate()
3457: - func - The function
3459: Calling sequence of func:
3460: $ func (TS ts);
3462: Notes:
3463: The function set by TSSetPostStep() is called after each successful step. The solution vector X
3464: obtained by TSGetSolution() may be different than that computed at the step end if the event handler
3465: locates an event and TSPostEvent() modifies it. Use TSSetPostEvaluate() if an unmodified solution is needed instead.
3467: Level: intermediate
3469: .seealso: TSSetPreStep(), TSSetPreStage(), TSSetPostEvaluate(), TSGetTimeStep(), TSGetStepNumber(), TSGetTime(), TSRestartStep()
3470: @*/
3471: PetscErrorCode TSSetPostStep(TS ts, PetscErrorCode (*func)(TS))
3472: {
3475: ts->poststep = func;
3476: return(0);
3477: }
3479: /*@
3480: TSPostStep - Runs the user-defined post-step function.
3482: Collective on TS
3484: Input Parameters:
3485: . ts - The TS context obtained from TSCreate()
3487: Notes:
3488: TSPostStep() is typically used within time stepping implementations,
3489: so most users would not generally call this routine themselves.
3491: Level: developer
3493: @*/
3494: PetscErrorCode TSPostStep(TS ts)
3495: {
3500: if (ts->poststep) {
3501: Vec U;
3502: PetscObjectState sprev,spost;
3504: TSGetSolution(ts,&U);
3505: PetscObjectStateGet((PetscObject)U,&sprev);
3506: PetscStackCallStandard((*ts->poststep),(ts));
3507: PetscObjectStateGet((PetscObject)U,&spost);
3508: if (sprev != spost) {TSRestartStep(ts);}
3509: }
3510: return(0);
3511: }
3513: /* ------------ Routines to set performance monitoring options ----------- */
3515: /*@C
3516: TSMonitorSet - Sets an ADDITIONAL function that is to be used at every
3517: timestep to display the iteration's progress.
3519: Logically Collective on TS
3521: Input Parameters:
3522: + ts - the TS context obtained from TSCreate()
3523: . monitor - monitoring routine
3524: . mctx - [optional] user-defined context for private data for the
3525: monitor routine (use NULL if no context is desired)
3526: - monitordestroy - [optional] routine that frees monitor context
3527: (may be NULL)
3529: Calling sequence of monitor:
3530: $ PetscErrorCode monitor(TS ts,PetscInt steps,PetscReal time,Vec u,void *mctx)
3532: + ts - the TS context
3533: . steps - iteration number (after the final time step the monitor routine may be called with a step of -1, this indicates the solution has been interpolated to this time)
3534: . time - current time
3535: . u - current iterate
3536: - mctx - [optional] monitoring context
3538: Notes:
3539: This routine adds an additional monitor to the list of monitors that
3540: already has been loaded.
3542: Fortran Notes:
3543: Only a single monitor function can be set for each TS object
3545: Level: intermediate
3547: .seealso: TSMonitorDefault(), TSMonitorCancel()
3548: @*/
3549: PetscErrorCode TSMonitorSet(TS ts,PetscErrorCode (*monitor)(TS,PetscInt,PetscReal,Vec,void*),void *mctx,PetscErrorCode (*mdestroy)(void**))
3550: {
3552: PetscInt i;
3553: PetscBool identical;
3557: for (i=0; i<ts->numbermonitors;i++) {
3558: PetscMonitorCompare((PetscErrorCode (*)(void))monitor,mctx,mdestroy,(PetscErrorCode (*)(void))ts->monitor[i],ts->monitorcontext[i],ts->monitordestroy[i],&identical);
3559: if (identical) return(0);
3560: }
3561: if (ts->numbermonitors >= MAXTSMONITORS) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Too many monitors set");
3562: ts->monitor[ts->numbermonitors] = monitor;
3563: ts->monitordestroy[ts->numbermonitors] = mdestroy;
3564: ts->monitorcontext[ts->numbermonitors++] = (void*)mctx;
3565: return(0);
3566: }
3568: /*@C
3569: TSMonitorCancel - Clears all the monitors that have been set on a time-step object.
3571: Logically Collective on TS
3573: Input Parameters:
3574: . ts - the TS context obtained from TSCreate()
3576: Notes:
3577: There is no way to remove a single, specific monitor.
3579: Level: intermediate
3581: .seealso: TSMonitorDefault(), TSMonitorSet()
3582: @*/
3583: PetscErrorCode TSMonitorCancel(TS ts)
3584: {
3586: PetscInt i;
3590: for (i=0; i<ts->numbermonitors; i++) {
3591: if (ts->monitordestroy[i]) {
3592: (*ts->monitordestroy[i])(&ts->monitorcontext[i]);
3593: }
3594: }
3595: ts->numbermonitors = 0;
3596: return(0);
3597: }
3599: /*@C
3600: TSMonitorDefault - The Default monitor, prints the timestep and time for each step
3602: Level: intermediate
3604: .seealso: TSMonitorSet()
3605: @*/
3606: PetscErrorCode TSMonitorDefault(TS ts,PetscInt step,PetscReal ptime,Vec v,PetscViewerAndFormat *vf)
3607: {
3609: PetscViewer viewer = vf->viewer;
3610: PetscBool iascii,ibinary;
3614: PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERASCII,&iascii);
3615: PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERBINARY,&ibinary);
3616: PetscViewerPushFormat(viewer,vf->format);
3617: if (iascii) {
3618: PetscViewerASCIIAddTab(viewer,((PetscObject)ts)->tablevel);
3619: if (step == -1){ /* this indicates it is an interpolated solution */
3620: PetscViewerASCIIPrintf(viewer,"Interpolated solution at time %g between steps %D and %D\n",(double)ptime,ts->steps-1,ts->steps);
3621: } else {
3622: PetscViewerASCIIPrintf(viewer,"%D TS dt %g time %g%s",step,(double)ts->time_step,(double)ptime,ts->steprollback ? " (r)\n" : "\n");
3623: }
3624: PetscViewerASCIISubtractTab(viewer,((PetscObject)ts)->tablevel);
3625: } else if (ibinary) {
3626: PetscMPIInt rank;
3627: MPI_Comm_rank(PetscObjectComm((PetscObject)viewer),&rank);
3628: if (!rank) {
3629: PetscBool skipHeader;
3630: PetscInt classid = REAL_FILE_CLASSID;
3632: PetscViewerBinaryGetSkipHeader(viewer,&skipHeader);
3633: if (!skipHeader) {
3634: PetscViewerBinaryWrite(viewer,&classid,1,PETSC_INT);
3635: }
3636: PetscRealView(1,&ptime,viewer);
3637: } else {
3638: PetscRealView(0,&ptime,viewer);
3639: }
3640: }
3641: PetscViewerPopFormat(viewer);
3642: return(0);
3643: }
3645: /*@C
3646: TSMonitorExtreme - Prints the extreme values of the solution at each timestep
3648: Level: intermediate
3650: .seealso: TSMonitorSet()
3651: @*/
3652: PetscErrorCode TSMonitorExtreme(TS ts,PetscInt step,PetscReal ptime,Vec v,PetscViewerAndFormat *vf)
3653: {
3655: PetscViewer viewer = vf->viewer;
3656: PetscBool iascii;
3657: PetscReal max,min;
3662: PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERASCII,&iascii);
3663: PetscViewerPushFormat(viewer,vf->format);
3664: if (iascii) {
3665: VecMax(v,NULL,&max);
3666: VecMin(v,NULL,&min);
3667: PetscViewerASCIIAddTab(viewer,((PetscObject)ts)->tablevel);
3668: PetscViewerASCIIPrintf(viewer,"%D TS dt %g time %g%s max %g min %g\n",step,(double)ts->time_step,(double)ptime,ts->steprollback ? " (r)" : "",(double)max,(double)min);
3669: PetscViewerASCIISubtractTab(viewer,((PetscObject)ts)->tablevel);
3670: }
3671: PetscViewerPopFormat(viewer);
3672: return(0);
3673: }
3675: /*@
3676: TSInterpolate - Interpolate the solution computed during the previous step to an arbitrary location in the interval
3678: Collective on TS
3680: Input Argument:
3681: + ts - time stepping context
3682: - t - time to interpolate to
3684: Output Argument:
3685: . U - state at given time
3687: Level: intermediate
3689: Developer Notes:
3690: TSInterpolate() and the storing of previous steps/stages should be generalized to support delay differential equations and continuous adjoints.
3692: .seealso: TSSetExactFinalTime(), TSSolve()
3693: @*/
3694: PetscErrorCode TSInterpolate(TS ts,PetscReal t,Vec U)
3695: {
3701: 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);
3702: if (!ts->ops->interpolate) SETERRQ1(PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"%s does not provide interpolation",((PetscObject)ts)->type_name);
3703: (*ts->ops->interpolate)(ts,t,U);
3704: return(0);
3705: }
3707: /*@
3708: TSStep - Steps one time step
3710: Collective on TS
3712: Input Parameter:
3713: . ts - the TS context obtained from TSCreate()
3715: Level: developer
3717: Notes:
3718: The public interface for the ODE/DAE solvers is TSSolve(), you should almost for sure be using that routine and not this routine.
3720: The hook set using TSSetPreStep() is called before each attempt to take the step. In general, the time step size may
3721: be changed due to adaptive error controller or solve failures. Note that steps may contain multiple stages.
3723: This may over-step the final time provided in TSSetMaxTime() depending on the time-step used. TSSolve() interpolates to exactly the
3724: time provided in TSSetMaxTime(). One can use TSInterpolate() to determine an interpolated solution within the final timestep.
3726: .seealso: TSCreate(), TSSetUp(), TSDestroy(), TSSolve(), TSSetPreStep(), TSSetPreStage(), TSSetPostStage(), TSInterpolate()
3727: @*/
3728: PetscErrorCode TSStep(TS ts)
3729: {
3730: PetscErrorCode ierr;
3731: static PetscBool cite = PETSC_FALSE;
3732: PetscReal ptime;
3736: PetscCitationsRegister("@article{tspaper,\n"
3737: " title = {{PETSc/TS}: A Modern Scalable {DAE/ODE} Solver Library},\n"
3738: " author = {Abhyankar, Shrirang and Brown, Jed and Constantinescu, Emil and Ghosh, Debojyoti and Smith, Barry F. and Zhang, Hong},\n"
3739: " journal = {arXiv e-preprints},\n"
3740: " eprint = {1806.01437},\n"
3741: " archivePrefix = {arXiv},\n"
3742: " year = {2018}\n}\n",&cite);
3744: TSSetUp(ts);
3745: TSTrajectorySetUp(ts->trajectory,ts);
3747: if (!ts->ops->step) SETERRQ1(PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"TSStep not implemented for type '%s'",((PetscObject)ts)->type_name);
3748: 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>");
3749: 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()");
3750: 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");
3752: if (!ts->steps) ts->ptime_prev = ts->ptime;
3753: ptime = ts->ptime; ts->ptime_prev_rollback = ts->ptime_prev;
3754: ts->reason = TS_CONVERGED_ITERATING;
3756: PetscLogEventBegin(TS_Step,ts,0,0,0);
3757: (*ts->ops->step)(ts);
3758: PetscLogEventEnd(TS_Step,ts,0,0,0);
3760: if (ts->reason >= 0) {
3761: ts->ptime_prev = ptime;
3762: ts->steps++;
3763: ts->steprollback = PETSC_FALSE;
3764: ts->steprestart = PETSC_FALSE;
3765: }
3767: if (!ts->reason) {
3768: if (ts->steps >= ts->max_steps) ts->reason = TS_CONVERGED_ITS;
3769: else if (ts->ptime >= ts->max_time) ts->reason = TS_CONVERGED_TIME;
3770: }
3772: 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]);
3773: if (ts->reason < 0 && ts->errorifstepfailed) SETERRQ1(PetscObjectComm((PetscObject)ts),PETSC_ERR_NOT_CONVERGED,"TSStep has failed due to %s",TSConvergedReasons[ts->reason]);
3774: return(0);
3775: }
3777: /*@
3778: TSEvaluateWLTE - Evaluate the weighted local truncation error norm
3779: at the end of a time step with a given order of accuracy.
3781: Collective on TS
3783: Input Arguments:
3784: + ts - time stepping context
3785: . wnormtype - norm type, either NORM_2 or NORM_INFINITY
3786: - order - optional, desired order for the error evaluation or PETSC_DECIDE
3788: Output Arguments:
3789: + order - optional, the actual order of the error evaluation
3790: - wlte - the weighted local truncation error norm
3792: Level: advanced
3794: Notes:
3795: If the timestepper cannot evaluate the error in a particular step
3796: (eg. in the first step or restart steps after event handling),
3797: this routine returns wlte=-1.0 .
3799: .seealso: TSStep(), TSAdapt, TSErrorWeightedNorm()
3800: @*/
3801: PetscErrorCode TSEvaluateWLTE(TS ts,NormType wnormtype,PetscInt *order,PetscReal *wlte)
3802: {
3812: if (wnormtype != NORM_2 && wnormtype != NORM_INFINITY) SETERRQ1(PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"No support for norm type %s",NormTypes[wnormtype]);
3813: if (!ts->ops->evaluatewlte) SETERRQ1(PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"TSEvaluateWLTE not implemented for type '%s'",((PetscObject)ts)->type_name);
3814: (*ts->ops->evaluatewlte)(ts,wnormtype,order,wlte);
3815: return(0);
3816: }
3818: /*@
3819: TSEvaluateStep - Evaluate the solution at the end of a time step with a given order of accuracy.
3821: Collective on TS
3823: Input Arguments:
3824: + ts - time stepping context
3825: . order - desired order of accuracy
3826: - done - whether the step was evaluated at this order (pass NULL to generate an error if not available)
3828: Output Arguments:
3829: . U - state at the end of the current step
3831: Level: advanced
3833: Notes:
3834: This function cannot be called until all stages have been evaluated.
3835: 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.
3837: .seealso: TSStep(), TSAdapt
3838: @*/
3839: PetscErrorCode TSEvaluateStep(TS ts,PetscInt order,Vec U,PetscBool *done)
3840: {
3847: if (!ts->ops->evaluatestep) SETERRQ1(PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"TSEvaluateStep not implemented for type '%s'",((PetscObject)ts)->type_name);
3848: (*ts->ops->evaluatestep)(ts,order,U,done);
3849: return(0);
3850: }
3852: /*@C
3853: TSGetComputeInitialCondition - Get the function used to automatically compute an initial condition for the timestepping.
3855: Not collective
3857: Input Argument:
3858: . ts - time stepping context
3860: Output Argument:
3861: . initConditions - The function which computes an initial condition
3863: Level: advanced
3865: Notes:
3866: The calling sequence for the function is
3867: $ initCondition(TS ts, Vec u)
3868: $ ts - The timestepping context
3869: $ u - The input vector in which the initial condition is stored
3871: .seealso: TSSetComputeInitialCondition(), TSComputeInitialCondition()
3872: @*/
3873: PetscErrorCode TSGetComputeInitialCondition(TS ts, PetscErrorCode (**initCondition)(TS, Vec))
3874: {
3878: *initCondition = ts->ops->initcondition;
3879: return(0);
3880: }
3882: /*@C
3883: TSSetComputeInitialCondition - Set the function used to automatically compute an initial condition for the timestepping.
3885: Logically collective on ts
3887: Input Arguments:
3888: + ts - time stepping context
3889: - initCondition - The function which computes an initial condition
3891: Level: advanced
3893: Calling sequence for initCondition:
3894: $ PetscErrorCode initCondition(TS ts, Vec u)
3896: + ts - The timestepping context
3897: - u - The input vector in which the initial condition is to be stored
3899: .seealso: TSGetComputeInitialCondition(), TSComputeInitialCondition()
3900: @*/
3901: PetscErrorCode TSSetComputeInitialCondition(TS ts, PetscErrorCode (*initCondition)(TS, Vec))
3902: {
3906: ts->ops->initcondition = initCondition;
3907: return(0);
3908: }
3910: /*@
3911: TSComputeInitialCondition - Compute an initial condition for the timestepping using the function previously set.
3913: Collective on ts
3915: Input Arguments:
3916: + ts - time stepping context
3917: - u - The Vec to store the condition in which will be used in TSSolve()
3919: Level: advanced
3921: .seealso: TSGetComputeInitialCondition(), TSSetComputeInitialCondition(), TSSolve()
3922: @*/
3923: PetscErrorCode TSComputeInitialCondition(TS ts, Vec u)
3924: {
3930: if (ts->ops->initcondition) {(*ts->ops->initcondition)(ts, u);}
3931: return(0);
3932: }
3934: /*@C
3935: TSGetComputeExactError - Get the function used to automatically compute the exact error for the timestepping.
3937: Not collective
3939: Input Argument:
3940: . ts - time stepping context
3942: Output Argument:
3943: . exactError - The function which computes the solution error
3945: Level: advanced
3947: Calling sequence for exactError:
3948: $ PetscErrorCode exactError(TS ts, Vec u)
3950: + ts - The timestepping context
3951: . u - The approximate solution vector
3952: - e - The input vector in which the error is stored
3954: .seealso: TSGetComputeExactError(), TSComputeExactError()
3955: @*/
3956: PetscErrorCode TSGetComputeExactError(TS ts, PetscErrorCode (**exactError)(TS, Vec, Vec))
3957: {
3961: *exactError = ts->ops->exacterror;
3962: return(0);
3963: }
3965: /*@C
3966: TSSetComputeExactError - Set the function used to automatically compute the exact error for the timestepping.
3968: Logically collective on ts
3970: Input Arguments:
3971: + ts - time stepping context
3972: - exactError - The function which computes the solution error
3974: Level: advanced
3976: Calling sequence for exactError:
3977: $ PetscErrorCode exactError(TS ts, Vec u)
3979: + ts - The timestepping context
3980: . u - The approximate solution vector
3981: - e - The input vector in which the error is stored
3983: .seealso: TSGetComputeExactError(), TSComputeExactError()
3984: @*/
3985: PetscErrorCode TSSetComputeExactError(TS ts, PetscErrorCode (*exactError)(TS, Vec, Vec))
3986: {
3990: ts->ops->exacterror = exactError;
3991: return(0);
3992: }
3994: /*@
3995: TSComputeExactError - Compute the solution error for the timestepping using the function previously set.
3997: Collective on ts
3999: Input Arguments:
4000: + ts - time stepping context
4001: . u - The approximate solution
4002: - e - The Vec used to store the error
4004: Level: advanced
4006: .seealso: TSGetComputeInitialCondition(), TSSetComputeInitialCondition(), TSSolve()
4007: @*/
4008: PetscErrorCode TSComputeExactError(TS ts, Vec u, Vec e)
4009: {
4016: if (ts->ops->exacterror) {(*ts->ops->exacterror)(ts, u, e);}
4017: return(0);
4018: }
4020: /*@
4021: TSSolve - Steps the requested number of timesteps.
4023: Collective on TS
4025: Input Parameter:
4026: + ts - the TS context obtained from TSCreate()
4027: - u - the solution vector (can be null if TSSetSolution() was used and TSSetExactFinalTime(ts,TS_EXACTFINALTIME_MATCHSTEP) was not used,
4028: otherwise must contain the initial conditions and will contain the solution at the final requested time
4030: Level: beginner
4032: Notes:
4033: The final time returned by this function may be different from the time of the internally
4034: held state accessible by TSGetSolution() and TSGetTime() because the method may have
4035: stepped over the final time.
4037: .seealso: TSCreate(), TSSetSolution(), TSStep(), TSGetTime(), TSGetSolveTime()
4038: @*/
4039: PetscErrorCode TSSolve(TS ts,Vec u)
4040: {
4041: Vec solution;
4042: PetscErrorCode ierr;
4048: TSSetExactFinalTimeDefault(ts);
4049: 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 */
4050: if (!ts->vec_sol || u == ts->vec_sol) {
4051: VecDuplicate(u,&solution);
4052: TSSetSolution(ts,solution);
4053: VecDestroy(&solution); /* grant ownership */
4054: }
4055: VecCopy(u,ts->vec_sol);
4056: if (ts->forward_solve) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"Sensitivity analysis does not support the mode TS_EXACTFINALTIME_INTERPOLATE");
4057: } else if (u) {
4058: TSSetSolution(ts,u);
4059: }
4060: TSSetUp(ts);
4061: TSTrajectorySetUp(ts->trajectory,ts);
4063: 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>");
4064: 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()");
4065: 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");
4067: if (ts->forward_solve) {
4068: TSForwardSetUp(ts);
4069: }
4071: /* reset number of steps only when the step is not restarted. ARKIMEX
4072: restarts the step after an event. Resetting these counters in such case causes
4073: TSTrajectory to incorrectly save the output files
4074: */
4075: /* reset time step and iteration counters */
4076: if (!ts->steps) {
4077: ts->ksp_its = 0;
4078: ts->snes_its = 0;
4079: ts->num_snes_failures = 0;
4080: ts->reject = 0;
4081: ts->steprestart = PETSC_TRUE;
4082: ts->steprollback = PETSC_FALSE;
4083: ts->rhsjacobian.time = PETSC_MIN_REAL;
4084: }
4086: /* make sure initial time step does not overshoot final time */
4087: if (ts->exact_final_time == TS_EXACTFINALTIME_MATCHSTEP) {
4088: PetscReal maxdt = ts->max_time-ts->ptime;
4089: PetscReal dt = ts->time_step;
4091: ts->time_step = dt >= maxdt ? maxdt : (PetscIsCloseAtTol(dt,maxdt,10*PETSC_MACHINE_EPSILON,0) ? maxdt : dt);
4092: }
4093: ts->reason = TS_CONVERGED_ITERATING;
4095: {
4096: PetscViewer viewer;
4097: PetscViewerFormat format;
4098: PetscBool flg;
4099: static PetscBool incall = PETSC_FALSE;
4101: if (!incall) {
4102: /* Estimate the convergence rate of the time discretization */
4103: PetscOptionsGetViewer(PetscObjectComm((PetscObject) ts),((PetscObject)ts)->options, ((PetscObject) ts)->prefix, "-ts_convergence_estimate", &viewer, &format, &flg);
4104: if (flg) {
4105: PetscConvEst conv;
4106: DM dm;
4107: PetscReal *alpha; /* Convergence rate of the solution error for each field in the L_2 norm */
4108: PetscInt Nf;
4109: PetscBool checkTemporal = PETSC_TRUE;
4111: incall = PETSC_TRUE;
4112: PetscOptionsGetBool(((PetscObject)ts)->options, ((PetscObject) ts)->prefix, "-ts_convergence_temporal", &checkTemporal, &flg);
4113: TSGetDM(ts, &dm);
4114: DMGetNumFields(dm, &Nf);
4115: PetscCalloc1(PetscMax(Nf, 1), &alpha);
4116: PetscConvEstCreate(PetscObjectComm((PetscObject) ts), &conv);
4117: PetscConvEstUseTS(conv, checkTemporal);
4118: PetscConvEstSetSolver(conv, (PetscObject) ts);
4119: PetscConvEstSetFromOptions(conv);
4120: PetscConvEstSetUp(conv);
4121: PetscConvEstGetConvRate(conv, alpha);
4122: PetscViewerPushFormat(viewer, format);
4123: PetscConvEstRateView(conv, alpha, viewer);
4124: PetscViewerPopFormat(viewer);
4125: PetscViewerDestroy(&viewer);
4126: PetscConvEstDestroy(&conv);
4127: PetscFree(alpha);
4128: incall = PETSC_FALSE;
4129: }
4130: }
4131: }
4133: TSViewFromOptions(ts,NULL,"-ts_view_pre");
4135: if (ts->ops->solve) { /* This private interface is transitional and should be removed when all implementations are updated. */
4136: (*ts->ops->solve)(ts);
4137: if (u) {VecCopy(ts->vec_sol,u);}
4138: ts->solvetime = ts->ptime;
4139: solution = ts->vec_sol;
4140: } else { /* Step the requested number of timesteps. */
4141: if (ts->steps >= ts->max_steps) ts->reason = TS_CONVERGED_ITS;
4142: else if (ts->ptime >= ts->max_time) ts->reason = TS_CONVERGED_TIME;
4144: if (!ts->steps) {
4145: TSTrajectorySet(ts->trajectory,ts,ts->steps,ts->ptime,ts->vec_sol);
4146: TSEventInitialize(ts->event,ts,ts->ptime,ts->vec_sol);
4147: }
4149: while (!ts->reason) {
4150: TSMonitor(ts,ts->steps,ts->ptime,ts->vec_sol);
4151: if (!ts->steprollback) {
4152: TSPreStep(ts);
4153: }
4154: TSStep(ts);
4155: if (ts->testjacobian) {
4156: TSRHSJacobianTest(ts,NULL);
4157: }
4158: if (ts->testjacobiantranspose) {
4159: TSRHSJacobianTestTranspose(ts,NULL);
4160: }
4161: if (ts->quadraturets && ts->costintegralfwd) { /* Must evaluate the cost integral before event is handled. The cost integral value can also be rolled back. */
4162: if (ts->reason >= 0) ts->steps--; /* Revert the step number changed by TSStep() */
4163: TSForwardCostIntegral(ts);
4164: if (ts->reason >= 0) ts->steps++;
4165: }
4166: if (ts->forward_solve) { /* compute forward sensitivities before event handling because postevent() may change RHS and jump conditions may have to be applied */
4167: if (ts->reason >= 0) ts->steps--; /* Revert the step number changed by TSStep() */
4168: TSForwardStep(ts);
4169: if (ts->reason >= 0) ts->steps++;
4170: }
4171: TSPostEvaluate(ts);
4172: TSEventHandler(ts); /* The right-hand side may be changed due to event. Be careful with Any computation using the RHS information after this point. */
4173: if (ts->steprollback) {
4174: TSPostEvaluate(ts);
4175: }
4176: if (!ts->steprollback) {
4177: TSTrajectorySet(ts->trajectory,ts,ts->steps,ts->ptime,ts->vec_sol);
4178: TSPostStep(ts);
4179: }
4180: }
4181: TSMonitor(ts,ts->steps,ts->ptime,ts->vec_sol);
4183: if (ts->exact_final_time == TS_EXACTFINALTIME_INTERPOLATE && ts->ptime > ts->max_time) {
4184: TSInterpolate(ts,ts->max_time,u);
4185: ts->solvetime = ts->max_time;
4186: solution = u;
4187: TSMonitor(ts,-1,ts->solvetime,solution);
4188: } else {
4189: if (u) {VecCopy(ts->vec_sol,u);}
4190: ts->solvetime = ts->ptime;
4191: solution = ts->vec_sol;
4192: }
4193: }
4195: TSViewFromOptions(ts,NULL,"-ts_view");
4196: VecViewFromOptions(solution,NULL,"-ts_view_solution");
4197: PetscObjectSAWsBlock((PetscObject)ts);
4198: if (ts->adjoint_solve) {
4199: TSAdjointSolve(ts);
4200: }
4201: return(0);
4202: }
4204: /*@C
4205: TSMonitor - Runs all user-provided monitor routines set using TSMonitorSet()
4207: Collective on TS
4209: Input Parameters:
4210: + ts - time stepping context obtained from TSCreate()
4211: . step - step number that has just completed
4212: . ptime - model time of the state
4213: - u - state at the current model time
4215: Notes:
4216: TSMonitor() is typically used automatically within the time stepping implementations.
4217: Users would almost never call this routine directly.
4219: A step of -1 indicates that the monitor is being called on a solution obtained by interpolating from computed solutions
4221: Level: developer
4223: @*/
4224: PetscErrorCode TSMonitor(TS ts,PetscInt step,PetscReal ptime,Vec u)
4225: {
4226: DM dm;
4227: PetscInt i,n = ts->numbermonitors;
4234: TSGetDM(ts,&dm);
4235: DMSetOutputSequenceNumber(dm,step,ptime);
4237: VecLockReadPush(u);
4238: for (i=0; i<n; i++) {
4239: (*ts->monitor[i])(ts,step,ptime,u,ts->monitorcontext[i]);
4240: }
4241: VecLockReadPop(u);
4242: return(0);
4243: }
4245: /* ------------------------------------------------------------------------*/
4246: /*@C
4247: TSMonitorLGCtxCreate - Creates a TSMonitorLGCtx context for use with
4248: TS to monitor the solution process graphically in various ways
4250: Collective on TS
4252: Input Parameters:
4253: + host - the X display to open, or null for the local machine
4254: . label - the title to put in the title bar
4255: . x, y - the screen coordinates of the upper left coordinate of the window
4256: . m, n - the screen width and height in pixels
4257: - howoften - if positive then determines the frequency of the plotting, if -1 then only at the final time
4259: Output Parameter:
4260: . ctx - the context
4262: Options Database Key:
4263: + -ts_monitor_lg_timestep - automatically sets line graph monitor
4264: + -ts_monitor_lg_timestep_log - automatically sets line graph monitor
4265: . -ts_monitor_lg_solution - monitor the solution (or certain values of the solution by calling TSMonitorLGSetDisplayVariables() or TSMonitorLGCtxSetDisplayVariables())
4266: . -ts_monitor_lg_error - monitor the error
4267: . -ts_monitor_lg_ksp_iterations - monitor the number of KSP iterations needed for each timestep
4268: . -ts_monitor_lg_snes_iterations - monitor the number of SNES iterations needed for each timestep
4269: - -lg_use_markers <true,false> - mark the data points (at each time step) on the plot; default is true
4271: Notes:
4272: Use TSMonitorLGCtxDestroy() to destroy.
4274: One can provide a function that transforms the solution before plotting it with TSMonitorLGCtxSetTransform() or TSMonitorLGSetTransform()
4276: Many of the functions that control the monitoring have two forms: TSMonitorLGSet/GetXXXX() and TSMonitorLGCtxSet/GetXXXX() the first take a TS object as the
4277: first argument (if that TS object does not have a TSMonitorLGCtx associated with it the function call is ignored) and the second takes a TSMonitorLGCtx object
4278: as the first argument.
4280: One can control the names displayed for each solution or error variable with TSMonitorLGCtxSetVariableNames() or TSMonitorLGSetVariableNames()
4282: Level: intermediate
4284: .seealso: TSMonitorLGTimeStep(), TSMonitorSet(), TSMonitorLGSolution(), TSMonitorLGError(), TSMonitorDefault(), VecView(),
4285: TSMonitorLGCtxCreate(), TSMonitorLGCtxSetVariableNames(), TSMonitorLGCtxGetVariableNames(),
4286: TSMonitorLGSetVariableNames(), TSMonitorLGGetVariableNames(), TSMonitorLGSetDisplayVariables(), TSMonitorLGCtxSetDisplayVariables(),
4287: TSMonitorLGCtxSetTransform(), TSMonitorLGSetTransform(), TSMonitorLGError(), TSMonitorLGSNESIterations(), TSMonitorLGKSPIterations(),
4288: TSMonitorEnvelopeCtxCreate(), TSMonitorEnvelopeGetBounds(), TSMonitorEnvelopeCtxDestroy(), TSMonitorEnvelop()
4290: @*/
4291: PetscErrorCode TSMonitorLGCtxCreate(MPI_Comm comm,const char host[],const char label[],int x,int y,int m,int n,PetscInt howoften,TSMonitorLGCtx *ctx)
4292: {
4293: PetscDraw draw;
4297: PetscNew(ctx);
4298: PetscDrawCreate(comm,host,label,x,y,m,n,&draw);
4299: PetscDrawSetFromOptions(draw);
4300: PetscDrawLGCreate(draw,1,&(*ctx)->lg);
4301: PetscDrawLGSetFromOptions((*ctx)->lg);
4302: PetscDrawDestroy(&draw);
4303: (*ctx)->howoften = howoften;
4304: return(0);
4305: }
4307: PetscErrorCode TSMonitorLGTimeStep(TS ts,PetscInt step,PetscReal ptime,Vec v,void *monctx)
4308: {
4309: TSMonitorLGCtx ctx = (TSMonitorLGCtx) monctx;
4310: PetscReal x = ptime,y;
4314: if (step < 0) return(0); /* -1 indicates an interpolated solution */
4315: if (!step) {
4316: PetscDrawAxis axis;
4317: const char *ylabel = ctx->semilogy ? "Log Time Step" : "Time Step";
4318: PetscDrawLGGetAxis(ctx->lg,&axis);
4319: PetscDrawAxisSetLabels(axis,"Timestep as function of time","Time",ylabel);
4320: PetscDrawLGReset(ctx->lg);
4321: }
4322: TSGetTimeStep(ts,&y);
4323: if (ctx->semilogy) y = PetscLog10Real(y);
4324: PetscDrawLGAddPoint(ctx->lg,&x,&y);
4325: if (((ctx->howoften > 0) && (!(step % ctx->howoften))) || ((ctx->howoften == -1) && ts->reason)) {
4326: PetscDrawLGDraw(ctx->lg);
4327: PetscDrawLGSave(ctx->lg);
4328: }
4329: return(0);
4330: }
4332: /*@C
4333: TSMonitorLGCtxDestroy - Destroys a line graph context that was created
4334: with TSMonitorLGCtxCreate().
4336: Collective on TSMonitorLGCtx
4338: Input Parameter:
4339: . ctx - the monitor context
4341: Level: intermediate
4343: .seealso: TSMonitorLGCtxCreate(), TSMonitorSet(), TSMonitorLGTimeStep();
4344: @*/
4345: PetscErrorCode TSMonitorLGCtxDestroy(TSMonitorLGCtx *ctx)
4346: {
4350: if ((*ctx)->transformdestroy) {
4351: ((*ctx)->transformdestroy)((*ctx)->transformctx);
4352: }
4353: PetscDrawLGDestroy(&(*ctx)->lg);
4354: PetscStrArrayDestroy(&(*ctx)->names);
4355: PetscStrArrayDestroy(&(*ctx)->displaynames);
4356: PetscFree((*ctx)->displayvariables);
4357: PetscFree((*ctx)->displayvalues);
4358: PetscFree(*ctx);
4359: return(0);
4360: }
4362: /*
4364: Creates a TS Monitor SPCtx for use with DM Swarm particle visualizations
4366: */
4367: PetscErrorCode TSMonitorSPCtxCreate(MPI_Comm comm,const char host[],const char label[],int x,int y,int m,int n,PetscInt howoften,TSMonitorSPCtx *ctx)
4368: {
4369: PetscDraw draw;
4373: PetscNew(ctx);
4374: PetscDrawCreate(comm,host,label,x,y,m,n,&draw);
4375: PetscDrawSetFromOptions(draw);
4376: PetscDrawSPCreate(draw,1,&(*ctx)->sp);
4377: PetscDrawDestroy(&draw);
4378: (*ctx)->howoften = howoften;
4379: return(0);
4381: }
4383: /*
4384: Destroys a TSMonitorSPCtx that was created with TSMonitorSPCtxCreate
4385: */
4386: PetscErrorCode TSMonitorSPCtxDestroy(TSMonitorSPCtx *ctx)
4387: {
4392: PetscDrawSPDestroy(&(*ctx)->sp);
4393: PetscFree(*ctx);
4395: return(0);
4397: }
4399: /*@
4400: TSGetTime - Gets the time of the most recently completed step.
4402: Not Collective
4404: Input Parameter:
4405: . ts - the TS context obtained from TSCreate()
4407: Output Parameter:
4408: . t - the current time. This time may not corresponds to the final time set with TSSetMaxTime(), use TSGetSolveTime().
4410: Level: beginner
4412: Note:
4413: When called during time step evaluation (e.g. during residual evaluation or via hooks set using TSSetPreStep(),
4414: TSSetPreStage(), TSSetPostStage(), or TSSetPostStep()), the time is the time at the start of the step being evaluated.
4416: .seealso: TSGetSolveTime(), TSSetTime(), TSGetTimeStep(), TSGetStepNumber()
4418: @*/
4419: PetscErrorCode TSGetTime(TS ts,PetscReal *t)
4420: {
4424: *t = ts->ptime;
4425: return(0);
4426: }
4428: /*@
4429: TSGetPrevTime - Gets the starting time of the previously completed step.
4431: Not Collective
4433: Input Parameter:
4434: . ts - the TS context obtained from TSCreate()
4436: Output Parameter:
4437: . t - the previous time
4439: Level: beginner
4441: .seealso: TSGetTime(), TSGetSolveTime(), TSGetTimeStep()
4443: @*/
4444: PetscErrorCode TSGetPrevTime(TS ts,PetscReal *t)
4445: {
4449: *t = ts->ptime_prev;
4450: return(0);
4451: }
4453: /*@
4454: TSSetTime - Allows one to reset the time.
4456: Logically Collective on TS
4458: Input Parameters:
4459: + ts - the TS context obtained from TSCreate()
4460: - time - the time
4462: Level: intermediate
4464: .seealso: TSGetTime(), TSSetMaxSteps()
4466: @*/
4467: PetscErrorCode TSSetTime(TS ts, PetscReal t)
4468: {
4472: ts->ptime = t;
4473: return(0);
4474: }
4476: /*@C
4477: TSSetOptionsPrefix - Sets the prefix used for searching for all
4478: TS options in the database.
4480: Logically Collective on TS
4482: Input Parameter:
4483: + ts - The TS context
4484: - prefix - The prefix to prepend to all option names
4486: Notes:
4487: A hyphen (-) must NOT be given at the beginning of the prefix name.
4488: The first character of all runtime options is AUTOMATICALLY the
4489: hyphen.
4491: Level: advanced
4493: .seealso: TSSetFromOptions()
4495: @*/
4496: PetscErrorCode TSSetOptionsPrefix(TS ts,const char prefix[])
4497: {
4499: SNES snes;
4503: PetscObjectSetOptionsPrefix((PetscObject)ts,prefix);
4504: TSGetSNES(ts,&snes);
4505: SNESSetOptionsPrefix(snes,prefix);
4506: return(0);
4507: }
4509: /*@C
4510: TSAppendOptionsPrefix - Appends to the prefix used for searching for all
4511: TS options in the database.
4513: Logically Collective on TS
4515: Input Parameter:
4516: + ts - The TS context
4517: - prefix - The prefix to prepend to all option names
4519: Notes:
4520: A hyphen (-) must NOT be given at the beginning of the prefix name.
4521: The first character of all runtime options is AUTOMATICALLY the
4522: hyphen.
4524: Level: advanced
4526: .seealso: TSGetOptionsPrefix()
4528: @*/
4529: PetscErrorCode TSAppendOptionsPrefix(TS ts,const char prefix[])
4530: {
4532: SNES snes;
4536: PetscObjectAppendOptionsPrefix((PetscObject)ts,prefix);
4537: TSGetSNES(ts,&snes);
4538: SNESAppendOptionsPrefix(snes,prefix);
4539: return(0);
4540: }
4542: /*@C
4543: TSGetOptionsPrefix - Sets the prefix used for searching for all
4544: TS options in the database.
4546: Not Collective
4548: Input Parameter:
4549: . ts - The TS context
4551: Output Parameter:
4552: . prefix - A pointer to the prefix string used
4554: Notes:
4555: On the fortran side, the user should pass in a string 'prifix' of
4556: sufficient length to hold the prefix.
4558: Level: intermediate
4560: .seealso: TSAppendOptionsPrefix()
4561: @*/
4562: PetscErrorCode TSGetOptionsPrefix(TS ts,const char *prefix[])
4563: {
4569: PetscObjectGetOptionsPrefix((PetscObject)ts,prefix);
4570: return(0);
4571: }
4573: /*@C
4574: TSGetRHSJacobian - Returns the Jacobian J at the present timestep.
4576: Not Collective, but parallel objects are returned if TS is parallel
4578: Input Parameter:
4579: . ts - The TS context obtained from TSCreate()
4581: Output Parameters:
4582: + Amat - The (approximate) Jacobian J of G, where U_t = G(U,t) (or NULL)
4583: . Pmat - The matrix from which the preconditioner is constructed, usually the same as Amat (or NULL)
4584: . func - Function to compute the Jacobian of the RHS (or NULL)
4585: - ctx - User-defined context for Jacobian evaluation routine (or NULL)
4587: Notes:
4588: You can pass in NULL for any return argument you do not need.
4590: Level: intermediate
4592: .seealso: TSGetTimeStep(), TSGetMatrices(), TSGetTime(), TSGetStepNumber()
4594: @*/
4595: PetscErrorCode TSGetRHSJacobian(TS ts,Mat *Amat,Mat *Pmat,TSRHSJacobian *func,void **ctx)
4596: {
4598: DM dm;
4601: if (Amat || Pmat) {
4602: SNES snes;
4603: TSGetSNES(ts,&snes);
4604: SNESSetUpMatrices(snes);
4605: SNESGetJacobian(snes,Amat,Pmat,NULL,NULL);
4606: }
4607: TSGetDM(ts,&dm);
4608: DMTSGetRHSJacobian(dm,func,ctx);
4609: return(0);
4610: }
4612: /*@C
4613: TSGetIJacobian - Returns the implicit Jacobian at the present timestep.
4615: Not Collective, but parallel objects are returned if TS is parallel
4617: Input Parameter:
4618: . ts - The TS context obtained from TSCreate()
4620: Output Parameters:
4621: + Amat - The (approximate) Jacobian of F(t,U,U_t)
4622: . Pmat - The matrix from which the preconditioner is constructed, often the same as Amat
4623: . f - The function to compute the matrices
4624: - ctx - User-defined context for Jacobian evaluation routine
4626: Notes:
4627: You can pass in NULL for any return argument you do not need.
4629: Level: advanced
4631: .seealso: TSGetTimeStep(), TSGetRHSJacobian(), TSGetMatrices(), TSGetTime(), TSGetStepNumber()
4633: @*/
4634: PetscErrorCode TSGetIJacobian(TS ts,Mat *Amat,Mat *Pmat,TSIJacobian *f,void **ctx)
4635: {
4637: DM dm;
4640: if (Amat || Pmat) {
4641: SNES snes;
4642: TSGetSNES(ts,&snes);
4643: SNESSetUpMatrices(snes);
4644: SNESGetJacobian(snes,Amat,Pmat,NULL,NULL);
4645: }
4646: TSGetDM(ts,&dm);
4647: DMTSGetIJacobian(dm,f,ctx);
4648: return(0);
4649: }
4651: /*@C
4652: TSMonitorDrawSolution - Monitors progress of the TS solvers by calling
4653: VecView() for the solution at each timestep
4655: Collective on TS
4657: Input Parameters:
4658: + ts - the TS context
4659: . step - current time-step
4660: . ptime - current time
4661: - dummy - either a viewer or NULL
4663: Options Database:
4664: . -ts_monitor_draw_solution_initial - show initial solution as well as current solution
4666: Notes:
4667: the initial solution and current solution are not display with a common axis scaling so generally the option -ts_monitor_draw_solution_initial
4668: will look bad
4670: Level: intermediate
4672: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView()
4673: @*/
4674: PetscErrorCode TSMonitorDrawSolution(TS ts,PetscInt step,PetscReal ptime,Vec u,void *dummy)
4675: {
4676: PetscErrorCode ierr;
4677: TSMonitorDrawCtx ictx = (TSMonitorDrawCtx)dummy;
4678: PetscDraw draw;
4681: if (!step && ictx->showinitial) {
4682: if (!ictx->initialsolution) {
4683: VecDuplicate(u,&ictx->initialsolution);
4684: }
4685: VecCopy(u,ictx->initialsolution);
4686: }
4687: if (!(((ictx->howoften > 0) && (!(step % ictx->howoften))) || ((ictx->howoften == -1) && ts->reason))) return(0);
4689: if (ictx->showinitial) {
4690: PetscReal pause;
4691: PetscViewerDrawGetPause(ictx->viewer,&pause);
4692: PetscViewerDrawSetPause(ictx->viewer,0.0);
4693: VecView(ictx->initialsolution,ictx->viewer);
4694: PetscViewerDrawSetPause(ictx->viewer,pause);
4695: PetscViewerDrawSetHold(ictx->viewer,PETSC_TRUE);
4696: }
4697: VecView(u,ictx->viewer);
4698: if (ictx->showtimestepandtime) {
4699: PetscReal xl,yl,xr,yr,h;
4700: char time[32];
4702: PetscViewerDrawGetDraw(ictx->viewer,0,&draw);
4703: PetscSNPrintf(time,32,"Timestep %d Time %g",(int)step,(double)ptime);
4704: PetscDrawGetCoordinates(draw,&xl,&yl,&xr,&yr);
4705: h = yl + .95*(yr - yl);
4706: PetscDrawStringCentered(draw,.5*(xl+xr),h,PETSC_DRAW_BLACK,time);
4707: PetscDrawFlush(draw);
4708: }
4710: if (ictx->showinitial) {
4711: PetscViewerDrawSetHold(ictx->viewer,PETSC_FALSE);
4712: }
4713: return(0);
4714: }
4716: /*@C
4717: TSMonitorDrawSolutionPhase - Monitors progress of the TS solvers by plotting the solution as a phase diagram
4719: Collective on TS
4721: Input Parameters:
4722: + ts - the TS context
4723: . step - current time-step
4724: . ptime - current time
4725: - dummy - either a viewer or NULL
4727: Level: intermediate
4729: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView()
4730: @*/
4731: PetscErrorCode TSMonitorDrawSolutionPhase(TS ts,PetscInt step,PetscReal ptime,Vec u,void *dummy)
4732: {
4733: PetscErrorCode ierr;
4734: TSMonitorDrawCtx ictx = (TSMonitorDrawCtx)dummy;
4735: PetscDraw draw;
4736: PetscDrawAxis axis;
4737: PetscInt n;
4738: PetscMPIInt size;
4739: PetscReal U0,U1,xl,yl,xr,yr,h;
4740: char time[32];
4741: const PetscScalar *U;
4744: MPI_Comm_size(PetscObjectComm((PetscObject)ts),&size);
4745: if (size != 1) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"Only allowed for sequential runs");
4746: VecGetSize(u,&n);
4747: if (n != 2) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"Only for ODEs with two unknowns");
4749: PetscViewerDrawGetDraw(ictx->viewer,0,&draw);
4750: PetscViewerDrawGetDrawAxis(ictx->viewer,0,&axis);
4751: PetscDrawAxisGetLimits(axis,&xl,&xr,&yl,&yr);
4752: if (!step) {
4753: PetscDrawClear(draw);
4754: PetscDrawAxisDraw(axis);
4755: }
4757: VecGetArrayRead(u,&U);
4758: U0 = PetscRealPart(U[0]);
4759: U1 = PetscRealPart(U[1]);
4760: VecRestoreArrayRead(u,&U);
4761: if ((U0 < xl) || (U1 < yl) || (U0 > xr) || (U1 > yr)) return(0);
4763: PetscDrawCollectiveBegin(draw);
4764: PetscDrawPoint(draw,U0,U1,PETSC_DRAW_BLACK);
4765: if (ictx->showtimestepandtime) {
4766: PetscDrawGetCoordinates(draw,&xl,&yl,&xr,&yr);
4767: PetscSNPrintf(time,32,"Timestep %d Time %g",(int)step,(double)ptime);
4768: h = yl + .95*(yr - yl);
4769: PetscDrawStringCentered(draw,.5*(xl+xr),h,PETSC_DRAW_BLACK,time);
4770: }
4771: PetscDrawCollectiveEnd(draw);
4772: PetscDrawFlush(draw);
4773: PetscDrawPause(draw);
4774: PetscDrawSave(draw);
4775: return(0);
4776: }
4778: /*@C
4779: TSMonitorDrawCtxDestroy - Destroys the monitor context for TSMonitorDrawSolution()
4781: Collective on TS
4783: Input Parameters:
4784: . ctx - the monitor context
4786: Level: intermediate
4788: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorDrawSolution(), TSMonitorDrawError()
4789: @*/
4790: PetscErrorCode TSMonitorDrawCtxDestroy(TSMonitorDrawCtx *ictx)
4791: {
4795: PetscViewerDestroy(&(*ictx)->viewer);
4796: VecDestroy(&(*ictx)->initialsolution);
4797: PetscFree(*ictx);
4798: return(0);
4799: }
4801: /*@C
4802: TSMonitorDrawCtxCreate - Creates the monitor context for TSMonitorDrawCtx
4804: Collective on TS
4806: Input Parameter:
4807: . ts - time-step context
4809: Output Patameter:
4810: . ctx - the monitor context
4812: Options Database:
4813: . -ts_monitor_draw_solution_initial - show initial solution as well as current solution
4815: Level: intermediate
4817: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorDrawCtx()
4818: @*/
4819: PetscErrorCode TSMonitorDrawCtxCreate(MPI_Comm comm,const char host[],const char label[],int x,int y,int m,int n,PetscInt howoften,TSMonitorDrawCtx *ctx)
4820: {
4821: PetscErrorCode ierr;
4824: PetscNew(ctx);
4825: PetscViewerDrawOpen(comm,host,label,x,y,m,n,&(*ctx)->viewer);
4826: PetscViewerSetFromOptions((*ctx)->viewer);
4828: (*ctx)->howoften = howoften;
4829: (*ctx)->showinitial = PETSC_FALSE;
4830: PetscOptionsGetBool(NULL,NULL,"-ts_monitor_draw_solution_initial",&(*ctx)->showinitial,NULL);
4832: (*ctx)->showtimestepandtime = PETSC_FALSE;
4833: PetscOptionsGetBool(NULL,NULL,"-ts_monitor_draw_solution_show_time",&(*ctx)->showtimestepandtime,NULL);
4834: return(0);
4835: }
4837: /*@C
4838: TSMonitorDrawSolutionFunction - Monitors progress of the TS solvers by calling
4839: VecView() for the solution provided by TSSetSolutionFunction() at each timestep
4841: Collective on TS
4843: Input Parameters:
4844: + ts - the TS context
4845: . step - current time-step
4846: . ptime - current time
4847: - dummy - either a viewer or NULL
4849: Options Database:
4850: . -ts_monitor_draw_solution_function - Monitor error graphically, requires user to have provided TSSetSolutionFunction()
4852: Level: intermediate
4854: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSSetSolutionFunction()
4855: @*/
4856: PetscErrorCode TSMonitorDrawSolutionFunction(TS ts,PetscInt step,PetscReal ptime,Vec u,void *dummy)
4857: {
4858: PetscErrorCode ierr;
4859: TSMonitorDrawCtx ctx = (TSMonitorDrawCtx)dummy;
4860: PetscViewer viewer = ctx->viewer;
4861: Vec work;
4864: if (!(((ctx->howoften > 0) && (!(step % ctx->howoften))) || ((ctx->howoften == -1) && ts->reason))) return(0);
4865: VecDuplicate(u,&work);
4866: TSComputeSolutionFunction(ts,ptime,work);
4867: VecView(work,viewer);
4868: VecDestroy(&work);
4869: return(0);
4870: }
4872: /*@C
4873: TSMonitorDrawError - Monitors progress of the TS solvers by calling
4874: VecView() for the error at each timestep
4876: Collective on TS
4878: Input Parameters:
4879: + ts - the TS context
4880: . step - current time-step
4881: . ptime - current time
4882: - dummy - either a viewer or NULL
4884: Options Database:
4885: . -ts_monitor_draw_error - Monitor error graphically, requires user to have provided TSSetSolutionFunction()
4887: Level: intermediate
4889: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSSetSolutionFunction()
4890: @*/
4891: PetscErrorCode TSMonitorDrawError(TS ts,PetscInt step,PetscReal ptime,Vec u,void *dummy)
4892: {
4893: PetscErrorCode ierr;
4894: TSMonitorDrawCtx ctx = (TSMonitorDrawCtx)dummy;
4895: PetscViewer viewer = ctx->viewer;
4896: Vec work;
4899: if (!(((ctx->howoften > 0) && (!(step % ctx->howoften))) || ((ctx->howoften == -1) && ts->reason))) return(0);
4900: VecDuplicate(u,&work);
4901: TSComputeSolutionFunction(ts,ptime,work);
4902: VecAXPY(work,-1.0,u);
4903: VecView(work,viewer);
4904: VecDestroy(&work);
4905: return(0);
4906: }
4908: #include <petsc/private/dmimpl.h>
4909: /*@
4910: TSSetDM - Sets the DM that may be used by some nonlinear solvers or preconditioners under the TS
4912: Logically Collective on ts
4914: Input Parameters:
4915: + ts - the ODE integrator object
4916: - dm - the dm, cannot be NULL
4918: Notes:
4919: A DM can only be used for solving one problem at a time because information about the problem is stored on the DM,
4920: even when not using interfaces like DMTSSetIFunction(). Use DMClone() to get a distinct DM when solving
4921: different problems using the same function space.
4923: Level: intermediate
4925: .seealso: TSGetDM(), SNESSetDM(), SNESGetDM()
4926: @*/
4927: PetscErrorCode TSSetDM(TS ts,DM dm)
4928: {
4930: SNES snes;
4931: DMTS tsdm;
4936: PetscObjectReference((PetscObject)dm);
4937: if (ts->dm) { /* Move the DMTS context over to the new DM unless the new DM already has one */
4938: if (ts->dm->dmts && !dm->dmts) {
4939: DMCopyDMTS(ts->dm,dm);
4940: DMGetDMTS(ts->dm,&tsdm);
4941: if (tsdm->originaldm == ts->dm) { /* Grant write privileges to the replacement DM */
4942: tsdm->originaldm = dm;
4943: }
4944: }
4945: DMDestroy(&ts->dm);
4946: }
4947: ts->dm = dm;
4949: TSGetSNES(ts,&snes);
4950: SNESSetDM(snes,dm);
4951: return(0);
4952: }
4954: /*@
4955: TSGetDM - Gets the DM that may be used by some preconditioners
4957: Not Collective
4959: Input Parameter:
4960: . ts - the preconditioner context
4962: Output Parameter:
4963: . dm - the dm
4965: Level: intermediate
4967: .seealso: TSSetDM(), SNESSetDM(), SNESGetDM()
4968: @*/
4969: PetscErrorCode TSGetDM(TS ts,DM *dm)
4970: {
4975: if (!ts->dm) {
4976: DMShellCreate(PetscObjectComm((PetscObject)ts),&ts->dm);
4977: if (ts->snes) {SNESSetDM(ts->snes,ts->dm);}
4978: }
4979: *dm = ts->dm;
4980: return(0);
4981: }
4983: /*@
4984: SNESTSFormFunction - Function to evaluate nonlinear residual
4986: Logically Collective on SNES
4988: Input Parameter:
4989: + snes - nonlinear solver
4990: . U - the current state at which to evaluate the residual
4991: - ctx - user context, must be a TS
4993: Output Parameter:
4994: . F - the nonlinear residual
4996: Notes:
4997: This function is not normally called by users and is automatically registered with the SNES used by TS.
4998: It is most frequently passed to MatFDColoringSetFunction().
5000: Level: advanced
5002: .seealso: SNESSetFunction(), MatFDColoringSetFunction()
5003: @*/
5004: PetscErrorCode SNESTSFormFunction(SNES snes,Vec U,Vec F,void *ctx)
5005: {
5006: TS ts = (TS)ctx;
5014: (ts->ops->snesfunction)(snes,U,F,ts);
5015: return(0);
5016: }
5018: /*@
5019: SNESTSFormJacobian - Function to evaluate the Jacobian
5021: Collective on SNES
5023: Input Parameter:
5024: + snes - nonlinear solver
5025: . U - the current state at which to evaluate the residual
5026: - ctx - user context, must be a TS
5028: Output Parameter:
5029: + A - the Jacobian
5030: . B - the preconditioning matrix (may be the same as A)
5031: - flag - indicates any structure change in the matrix
5033: Notes:
5034: This function is not normally called by users and is automatically registered with the SNES used by TS.
5036: Level: developer
5038: .seealso: SNESSetJacobian()
5039: @*/
5040: PetscErrorCode SNESTSFormJacobian(SNES snes,Vec U,Mat A,Mat B,void *ctx)
5041: {
5042: TS ts = (TS)ctx;
5053: (ts->ops->snesjacobian)(snes,U,A,B,ts);
5054: return(0);
5055: }
5057: /*@C
5058: TSComputeRHSFunctionLinear - Evaluate the right hand side via the user-provided Jacobian, for linear problems Udot = A U only
5060: Collective on TS
5062: Input Arguments:
5063: + ts - time stepping context
5064: . t - time at which to evaluate
5065: . U - state at which to evaluate
5066: - ctx - context
5068: Output Arguments:
5069: . F - right hand side
5071: Level: intermediate
5073: Notes:
5074: This function is intended to be passed to TSSetRHSFunction() to evaluate the right hand side for linear problems.
5075: The matrix (and optionally the evaluation context) should be passed to TSSetRHSJacobian().
5077: .seealso: TSSetRHSFunction(), TSSetRHSJacobian(), TSComputeRHSJacobianConstant()
5078: @*/
5079: PetscErrorCode TSComputeRHSFunctionLinear(TS ts,PetscReal t,Vec U,Vec F,void *ctx)
5080: {
5082: Mat Arhs,Brhs;
5085: TSGetRHSMats_Private(ts,&Arhs,&Brhs);
5086: /* undo the damage caused by shifting */
5087: TSRecoverRHSJacobian(ts,Arhs,Brhs);
5088: TSComputeRHSJacobian(ts,t,U,Arhs,Brhs);
5089: MatMult(Arhs,U,F);
5090: return(0);
5091: }
5093: /*@C
5094: TSComputeRHSJacobianConstant - Reuses a Jacobian that is time-independent.
5096: Collective on TS
5098: Input Arguments:
5099: + ts - time stepping context
5100: . t - time at which to evaluate
5101: . U - state at which to evaluate
5102: - ctx - context
5104: Output Arguments:
5105: + A - pointer to operator
5106: . B - pointer to preconditioning matrix
5107: - flg - matrix structure flag
5109: Level: intermediate
5111: Notes:
5112: This function is intended to be passed to TSSetRHSJacobian() to evaluate the Jacobian for linear time-independent problems.
5114: .seealso: TSSetRHSFunction(), TSSetRHSJacobian(), TSComputeRHSFunctionLinear()
5115: @*/
5116: PetscErrorCode TSComputeRHSJacobianConstant(TS ts,PetscReal t,Vec U,Mat A,Mat B,void *ctx)
5117: {
5119: return(0);
5120: }
5122: /*@C
5123: TSComputeIFunctionLinear - Evaluate the left hand side via the user-provided Jacobian, for linear problems only
5125: Collective on TS
5127: Input Arguments:
5128: + ts - time stepping context
5129: . t - time at which to evaluate
5130: . U - state at which to evaluate
5131: . Udot - time derivative of state vector
5132: - ctx - context
5134: Output Arguments:
5135: . F - left hand side
5137: Level: intermediate
5139: Notes:
5140: 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
5141: user is required to write their own TSComputeIFunction.
5142: This function is intended to be passed to TSSetIFunction() to evaluate the left hand side for linear problems.
5143: The matrix (and optionally the evaluation context) should be passed to TSSetIJacobian().
5145: Note that using this function is NOT equivalent to using TSComputeRHSFunctionLinear() since that solves Udot = A U
5147: .seealso: TSSetIFunction(), TSSetIJacobian(), TSComputeIJacobianConstant(), TSComputeRHSFunctionLinear()
5148: @*/
5149: PetscErrorCode TSComputeIFunctionLinear(TS ts,PetscReal t,Vec U,Vec Udot,Vec F,void *ctx)
5150: {
5152: Mat A,B;
5155: TSGetIJacobian(ts,&A,&B,NULL,NULL);
5156: TSComputeIJacobian(ts,t,U,Udot,1.0,A,B,PETSC_TRUE);
5157: MatMult(A,Udot,F);
5158: return(0);
5159: }
5161: /*@C
5162: TSComputeIJacobianConstant - Reuses a time-independent for a semi-implicit DAE or ODE
5164: Collective on TS
5166: Input Arguments:
5167: + ts - time stepping context
5168: . t - time at which to evaluate
5169: . U - state at which to evaluate
5170: . Udot - time derivative of state vector
5171: . shift - shift to apply
5172: - ctx - context
5174: Output Arguments:
5175: + A - pointer to operator
5176: . B - pointer to preconditioning matrix
5177: - flg - matrix structure flag
5179: Level: advanced
5181: Notes:
5182: This function is intended to be passed to TSSetIJacobian() to evaluate the Jacobian for linear time-independent problems.
5184: It is only appropriate for problems of the form
5186: $ M Udot = F(U,t)
5188: where M is constant and F is non-stiff. The user must pass M to TSSetIJacobian(). The current implementation only
5189: works with IMEX time integration methods such as TSROSW and TSARKIMEX, since there is no support for de-constructing
5190: an implicit operator of the form
5192: $ shift*M + J
5194: 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
5195: a copy of M or reassemble it when requested.
5197: .seealso: TSSetIFunction(), TSSetIJacobian(), TSComputeIFunctionLinear()
5198: @*/
5199: PetscErrorCode TSComputeIJacobianConstant(TS ts,PetscReal t,Vec U,Vec Udot,PetscReal shift,Mat A,Mat B,void *ctx)
5200: {
5204: MatScale(A, shift / ts->ijacobian.shift);
5205: ts->ijacobian.shift = shift;
5206: return(0);
5207: }
5209: /*@
5210: TSGetEquationType - Gets the type of the equation that TS is solving.
5212: Not Collective
5214: Input Parameter:
5215: . ts - the TS context
5217: Output Parameter:
5218: . equation_type - see TSEquationType
5220: Level: beginner
5222: .seealso: TSSetEquationType(), TSEquationType
5223: @*/
5224: PetscErrorCode TSGetEquationType(TS ts,TSEquationType *equation_type)
5225: {
5229: *equation_type = ts->equation_type;
5230: return(0);
5231: }
5233: /*@
5234: TSSetEquationType - Sets the type of the equation that TS is solving.
5236: Not Collective
5238: Input Parameter:
5239: + ts - the TS context
5240: - equation_type - see TSEquationType
5242: Level: advanced
5244: .seealso: TSGetEquationType(), TSEquationType
5245: @*/
5246: PetscErrorCode TSSetEquationType(TS ts,TSEquationType equation_type)
5247: {
5250: ts->equation_type = equation_type;
5251: return(0);
5252: }
5254: /*@
5255: TSGetConvergedReason - Gets the reason the TS iteration was stopped.
5257: Not Collective
5259: Input Parameter:
5260: . ts - the TS context
5262: Output Parameter:
5263: . reason - negative value indicates diverged, positive value converged, see TSConvergedReason or the
5264: manual pages for the individual convergence tests for complete lists
5266: Level: beginner
5268: Notes:
5269: Can only be called after the call to TSSolve() is complete.
5271: .seealso: TSSetConvergenceTest(), TSConvergedReason
5272: @*/
5273: PetscErrorCode TSGetConvergedReason(TS ts,TSConvergedReason *reason)
5274: {
5278: *reason = ts->reason;
5279: return(0);
5280: }
5282: /*@
5283: TSSetConvergedReason - Sets the reason for handling the convergence of TSSolve.
5285: Logically Collective; reason must contain common value
5287: Input Parameters:
5288: + ts - the TS context
5289: - reason - negative value indicates diverged, positive value converged, see TSConvergedReason or the
5290: manual pages for the individual convergence tests for complete lists
5292: Level: advanced
5294: Notes:
5295: Can only be called while TSSolve() is active.
5297: .seealso: TSConvergedReason
5298: @*/
5299: PetscErrorCode TSSetConvergedReason(TS ts,TSConvergedReason reason)
5300: {
5303: ts->reason = reason;
5304: return(0);
5305: }
5307: /*@
5308: TSGetSolveTime - Gets the time after a call to TSSolve()
5310: Not Collective
5312: Input Parameter:
5313: . ts - the TS context
5315: Output Parameter:
5316: . ftime - the final time. This time corresponds to the final time set with TSSetMaxTime()
5318: Level: beginner
5320: Notes:
5321: Can only be called after the call to TSSolve() is complete.
5323: .seealso: TSSetConvergenceTest(), TSConvergedReason
5324: @*/
5325: PetscErrorCode TSGetSolveTime(TS ts,PetscReal *ftime)
5326: {
5330: *ftime = ts->solvetime;
5331: return(0);
5332: }
5334: /*@
5335: TSGetSNESIterations - Gets the total number of nonlinear iterations
5336: used by the time integrator.
5338: Not Collective
5340: Input Parameter:
5341: . ts - TS context
5343: Output Parameter:
5344: . nits - number of nonlinear iterations
5346: Notes:
5347: This counter is reset to zero for each successive call to TSSolve().
5349: Level: intermediate
5351: .seealso: TSGetKSPIterations()
5352: @*/
5353: PetscErrorCode TSGetSNESIterations(TS ts,PetscInt *nits)
5354: {
5358: *nits = ts->snes_its;
5359: return(0);
5360: }
5362: /*@
5363: TSGetKSPIterations - Gets the total number of linear iterations
5364: used by the time integrator.
5366: Not Collective
5368: Input Parameter:
5369: . ts - TS context
5371: Output Parameter:
5372: . lits - number of linear iterations
5374: Notes:
5375: This counter is reset to zero for each successive call to TSSolve().
5377: Level: intermediate
5379: .seealso: TSGetSNESIterations(), SNESGetKSPIterations()
5380: @*/
5381: PetscErrorCode TSGetKSPIterations(TS ts,PetscInt *lits)
5382: {
5386: *lits = ts->ksp_its;
5387: return(0);
5388: }
5390: /*@
5391: TSGetStepRejections - Gets the total number of rejected steps.
5393: Not Collective
5395: Input Parameter:
5396: . ts - TS context
5398: Output Parameter:
5399: . rejects - number of steps rejected
5401: Notes:
5402: This counter is reset to zero for each successive call to TSSolve().
5404: Level: intermediate
5406: .seealso: TSGetSNESIterations(), TSGetKSPIterations(), TSSetMaxStepRejections(), TSGetSNESFailures(), TSSetMaxSNESFailures(), TSSetErrorIfStepFails()
5407: @*/
5408: PetscErrorCode TSGetStepRejections(TS ts,PetscInt *rejects)
5409: {
5413: *rejects = ts->reject;
5414: return(0);
5415: }
5417: /*@
5418: TSGetSNESFailures - Gets the total number of failed SNES solves
5420: Not Collective
5422: Input Parameter:
5423: . ts - TS context
5425: Output Parameter:
5426: . fails - number of failed nonlinear solves
5428: Notes:
5429: This counter is reset to zero for each successive call to TSSolve().
5431: Level: intermediate
5433: .seealso: TSGetSNESIterations(), TSGetKSPIterations(), TSSetMaxStepRejections(), TSGetStepRejections(), TSSetMaxSNESFailures()
5434: @*/
5435: PetscErrorCode TSGetSNESFailures(TS ts,PetscInt *fails)
5436: {
5440: *fails = ts->num_snes_failures;
5441: return(0);
5442: }
5444: /*@
5445: TSSetMaxStepRejections - Sets the maximum number of step rejections before a step fails
5447: Not Collective
5449: Input Parameter:
5450: + ts - TS context
5451: - rejects - maximum number of rejected steps, pass -1 for unlimited
5453: Notes:
5454: The counter is reset to zero for each step
5456: Options Database Key:
5457: . -ts_max_reject - Maximum number of step rejections before a step fails
5459: Level: intermediate
5461: .seealso: TSGetSNESIterations(), TSGetKSPIterations(), TSSetMaxSNESFailures(), TSGetStepRejections(), TSGetSNESFailures(), TSSetErrorIfStepFails(), TSGetConvergedReason()
5462: @*/
5463: PetscErrorCode TSSetMaxStepRejections(TS ts,PetscInt rejects)
5464: {
5467: ts->max_reject = rejects;
5468: return(0);
5469: }
5471: /*@
5472: TSSetMaxSNESFailures - Sets the maximum number of failed SNES solves
5474: Not Collective
5476: Input Parameter:
5477: + ts - TS context
5478: - fails - maximum number of failed nonlinear solves, pass -1 for unlimited
5480: Notes:
5481: The counter is reset to zero for each successive call to TSSolve().
5483: Options Database Key:
5484: . -ts_max_snes_failures - Maximum number of nonlinear solve failures
5486: Level: intermediate
5488: .seealso: TSGetSNESIterations(), TSGetKSPIterations(), TSSetMaxStepRejections(), TSGetStepRejections(), TSGetSNESFailures(), SNESGetConvergedReason(), TSGetConvergedReason()
5489: @*/
5490: PetscErrorCode TSSetMaxSNESFailures(TS ts,PetscInt fails)
5491: {
5494: ts->max_snes_failures = fails;
5495: return(0);
5496: }
5498: /*@
5499: TSSetErrorIfStepFails - Error if no step succeeds
5501: Not Collective
5503: Input Parameter:
5504: + ts - TS context
5505: - err - PETSC_TRUE to error if no step succeeds, PETSC_FALSE to return without failure
5507: Options Database Key:
5508: . -ts_error_if_step_fails - Error if no step succeeds
5510: Level: intermediate
5512: .seealso: TSGetSNESIterations(), TSGetKSPIterations(), TSSetMaxStepRejections(), TSGetStepRejections(), TSGetSNESFailures(), TSSetErrorIfStepFails(), TSGetConvergedReason()
5513: @*/
5514: PetscErrorCode TSSetErrorIfStepFails(TS ts,PetscBool err)
5515: {
5518: ts->errorifstepfailed = err;
5519: return(0);
5520: }
5522: /*@C
5523: TSMonitorSolution - Monitors progress of the TS solvers by VecView() for the solution at each timestep. Normally the viewer is a binary file or a PetscDraw object
5525: Collective on TS
5527: Input Parameters:
5528: + ts - the TS context
5529: . step - current time-step
5530: . ptime - current time
5531: . u - current state
5532: - vf - viewer and its format
5534: Level: intermediate
5536: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView()
5537: @*/
5538: PetscErrorCode TSMonitorSolution(TS ts,PetscInt step,PetscReal ptime,Vec u,PetscViewerAndFormat *vf)
5539: {
5543: PetscViewerPushFormat(vf->viewer,vf->format);
5544: VecView(u,vf->viewer);
5545: PetscViewerPopFormat(vf->viewer);
5546: return(0);
5547: }
5549: /*@C
5550: TSMonitorSolutionVTK - Monitors progress of the TS solvers by VecView() for the solution at each timestep.
5552: Collective on TS
5554: Input Parameters:
5555: + ts - the TS context
5556: . step - current time-step
5557: . ptime - current time
5558: . u - current state
5559: - filenametemplate - string containing a format specifier for the integer time step (e.g. %03D)
5561: Level: intermediate
5563: Notes:
5564: The VTK format does not allow writing multiple time steps in the same file, therefore a different file will be written for each time step.
5565: These are named according to the file name template.
5567: This function is normally passed as an argument to TSMonitorSet() along with TSMonitorSolutionVTKDestroy().
5569: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView()
5570: @*/
5571: PetscErrorCode TSMonitorSolutionVTK(TS ts,PetscInt step,PetscReal ptime,Vec u,void *filenametemplate)
5572: {
5574: char filename[PETSC_MAX_PATH_LEN];
5575: PetscViewer viewer;
5578: if (step < 0) return(0); /* -1 indicates interpolated solution */
5579: PetscSNPrintf(filename,sizeof(filename),(const char*)filenametemplate,step);
5580: PetscViewerVTKOpen(PetscObjectComm((PetscObject)ts),filename,FILE_MODE_WRITE,&viewer);
5581: VecView(u,viewer);
5582: PetscViewerDestroy(&viewer);
5583: return(0);
5584: }
5586: /*@C
5587: TSMonitorSolutionVTKDestroy - Destroy context for monitoring
5589: Collective on TS
5591: Input Parameters:
5592: . filenametemplate - string containing a format specifier for the integer time step (e.g. %03D)
5594: Level: intermediate
5596: Note:
5597: This function is normally passed to TSMonitorSet() along with TSMonitorSolutionVTK().
5599: .seealso: TSMonitorSet(), TSMonitorSolutionVTK()
5600: @*/
5601: PetscErrorCode TSMonitorSolutionVTKDestroy(void *filenametemplate)
5602: {
5606: PetscFree(*(char**)filenametemplate);
5607: return(0);
5608: }
5610: /*@
5611: TSGetAdapt - Get the adaptive controller context for the current method
5613: Collective on TS if controller has not been created yet
5615: Input Arguments:
5616: . ts - time stepping context
5618: Output Arguments:
5619: . adapt - adaptive controller
5621: Level: intermediate
5623: .seealso: TSAdapt, TSAdaptSetType(), TSAdaptChoose()
5624: @*/
5625: PetscErrorCode TSGetAdapt(TS ts,TSAdapt *adapt)
5626: {
5632: if (!ts->adapt) {
5633: TSAdaptCreate(PetscObjectComm((PetscObject)ts),&ts->adapt);
5634: PetscLogObjectParent((PetscObject)ts,(PetscObject)ts->adapt);
5635: PetscObjectIncrementTabLevel((PetscObject)ts->adapt,(PetscObject)ts,1);
5636: }
5637: *adapt = ts->adapt;
5638: return(0);
5639: }
5641: /*@
5642: TSSetTolerances - Set tolerances for local truncation error when using adaptive controller
5644: Logically Collective
5646: Input Arguments:
5647: + ts - time integration context
5648: . atol - scalar absolute tolerances, PETSC_DECIDE to leave current value
5649: . vatol - vector of absolute tolerances or NULL, used in preference to atol if present
5650: . rtol - scalar relative tolerances, PETSC_DECIDE to leave current value
5651: - vrtol - vector of relative tolerances or NULL, used in preference to atol if present
5653: Options Database keys:
5654: + -ts_rtol <rtol> - relative tolerance for local truncation error
5655: - -ts_atol <atol> Absolute tolerance for local truncation error
5657: Notes:
5658: With PETSc's implicit schemes for DAE problems, the calculation of the local truncation error
5659: (LTE) includes both the differential and the algebraic variables. If one wants the LTE to be
5660: computed only for the differential or the algebraic part then this can be done using the vector of
5661: tolerances vatol. For example, by setting the tolerance vector with the desired tolerance for the
5662: differential part and infinity for the algebraic part, the LTE calculation will include only the
5663: differential variables.
5665: Level: beginner
5667: .seealso: TS, TSAdapt, TSErrorWeightedNorm(), TSGetTolerances()
5668: @*/
5669: PetscErrorCode TSSetTolerances(TS ts,PetscReal atol,Vec vatol,PetscReal rtol,Vec vrtol)
5670: {
5674: if (atol != PETSC_DECIDE && atol != PETSC_DEFAULT) ts->atol = atol;
5675: if (vatol) {
5676: PetscObjectReference((PetscObject)vatol);
5677: VecDestroy(&ts->vatol);
5678: ts->vatol = vatol;
5679: }
5680: if (rtol != PETSC_DECIDE && rtol != PETSC_DEFAULT) ts->rtol = rtol;
5681: if (vrtol) {
5682: PetscObjectReference((PetscObject)vrtol);
5683: VecDestroy(&ts->vrtol);
5684: ts->vrtol = vrtol;
5685: }
5686: return(0);
5687: }
5689: /*@
5690: TSGetTolerances - Get tolerances for local truncation error when using adaptive controller
5692: Logically Collective
5694: Input Arguments:
5695: . ts - time integration context
5697: Output Arguments:
5698: + atol - scalar absolute tolerances, NULL to ignore
5699: . vatol - vector of absolute tolerances, NULL to ignore
5700: . rtol - scalar relative tolerances, NULL to ignore
5701: - vrtol - vector of relative tolerances, NULL to ignore
5703: Level: beginner
5705: .seealso: TS, TSAdapt, TSErrorWeightedNorm(), TSSetTolerances()
5706: @*/
5707: PetscErrorCode TSGetTolerances(TS ts,PetscReal *atol,Vec *vatol,PetscReal *rtol,Vec *vrtol)
5708: {
5710: if (atol) *atol = ts->atol;
5711: if (vatol) *vatol = ts->vatol;
5712: if (rtol) *rtol = ts->rtol;
5713: if (vrtol) *vrtol = ts->vrtol;
5714: return(0);
5715: }
5717: /*@
5718: TSErrorWeightedNorm2 - compute a weighted 2-norm of the difference between two state vectors
5720: Collective on TS
5722: Input Arguments:
5723: + ts - time stepping context
5724: . U - state vector, usually ts->vec_sol
5725: - Y - state vector to be compared to U
5727: Output Arguments:
5728: + norm - weighted norm, a value of 1.0 means that the error matches the tolerances
5729: . norma - weighted norm based on the absolute tolerance, a value of 1.0 means that the error matches the tolerances
5730: - normr - weighted norm based on the relative tolerance, a value of 1.0 means that the error matches the tolerances
5732: Level: developer
5734: .seealso: TSErrorWeightedNorm(), TSErrorWeightedNormInfinity()
5735: @*/
5736: PetscErrorCode TSErrorWeightedNorm2(TS ts,Vec U,Vec Y,PetscReal *norm,PetscReal *norma,PetscReal *normr)
5737: {
5738: PetscErrorCode ierr;
5739: PetscInt i,n,N,rstart;
5740: PetscInt n_loc,na_loc,nr_loc;
5741: PetscReal n_glb,na_glb,nr_glb;
5742: const PetscScalar *u,*y;
5743: PetscReal sum,suma,sumr,gsum,gsuma,gsumr,diff;
5744: PetscReal tol,tola,tolr;
5745: PetscReal err_loc[6],err_glb[6];
5757: if (U == Y) SETERRQ(PetscObjectComm((PetscObject)U),PETSC_ERR_ARG_IDN,"U and Y cannot be the same vector");
5759: VecGetSize(U,&N);
5760: VecGetLocalSize(U,&n);
5761: VecGetOwnershipRange(U,&rstart,NULL);
5762: VecGetArrayRead(U,&u);
5763: VecGetArrayRead(Y,&y);
5764: sum = 0.; n_loc = 0;
5765: suma = 0.; na_loc = 0;
5766: sumr = 0.; nr_loc = 0;
5767: if (ts->vatol && ts->vrtol) {
5768: const PetscScalar *atol,*rtol;
5769: VecGetArrayRead(ts->vatol,&atol);
5770: VecGetArrayRead(ts->vrtol,&rtol);
5771: for (i=0; i<n; i++) {
5772: SkipSmallValue(y[i],u[i],ts->adapt->ignore_max);
5773: diff = PetscAbsScalar(y[i] - u[i]);
5774: tola = PetscRealPart(atol[i]);
5775: if (tola>0.){
5776: suma += PetscSqr(diff/tola);
5777: na_loc++;
5778: }
5779: tolr = PetscRealPart(rtol[i]) * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
5780: if (tolr>0.){
5781: sumr += PetscSqr(diff/tolr);
5782: nr_loc++;
5783: }
5784: tol=tola+tolr;
5785: if (tol>0.){
5786: sum += PetscSqr(diff/tol);
5787: n_loc++;
5788: }
5789: }
5790: VecRestoreArrayRead(ts->vatol,&atol);
5791: VecRestoreArrayRead(ts->vrtol,&rtol);
5792: } else if (ts->vatol) { /* vector atol, scalar rtol */
5793: const PetscScalar *atol;
5794: VecGetArrayRead(ts->vatol,&atol);
5795: for (i=0; i<n; i++) {
5796: SkipSmallValue(y[i],u[i],ts->adapt->ignore_max);
5797: diff = PetscAbsScalar(y[i] - u[i]);
5798: tola = PetscRealPart(atol[i]);
5799: if (tola>0.){
5800: suma += PetscSqr(diff/tola);
5801: na_loc++;
5802: }
5803: tolr = ts->rtol * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
5804: if (tolr>0.){
5805: sumr += PetscSqr(diff/tolr);
5806: nr_loc++;
5807: }
5808: tol=tola+tolr;
5809: if (tol>0.){
5810: sum += PetscSqr(diff/tol);
5811: n_loc++;
5812: }
5813: }
5814: VecRestoreArrayRead(ts->vatol,&atol);
5815: } else if (ts->vrtol) { /* scalar atol, vector rtol */
5816: const PetscScalar *rtol;
5817: VecGetArrayRead(ts->vrtol,&rtol);
5818: for (i=0; i<n; i++) {
5819: SkipSmallValue(y[i],u[i],ts->adapt->ignore_max);
5820: diff = PetscAbsScalar(y[i] - u[i]);
5821: tola = ts->atol;
5822: if (tola>0.){
5823: suma += PetscSqr(diff/tola);
5824: na_loc++;
5825: }
5826: tolr = PetscRealPart(rtol[i]) * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
5827: if (tolr>0.){
5828: sumr += PetscSqr(diff/tolr);
5829: nr_loc++;
5830: }
5831: tol=tola+tolr;
5832: if (tol>0.){
5833: sum += PetscSqr(diff/tol);
5834: n_loc++;
5835: }
5836: }
5837: VecRestoreArrayRead(ts->vrtol,&rtol);
5838: } else { /* scalar atol, scalar rtol */
5839: for (i=0; i<n; i++) {
5840: SkipSmallValue(y[i],u[i],ts->adapt->ignore_max);
5841: diff = PetscAbsScalar(y[i] - u[i]);
5842: tola = ts->atol;
5843: if (tola>0.){
5844: suma += PetscSqr(diff/tola);
5845: na_loc++;
5846: }
5847: tolr = ts->rtol * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
5848: if (tolr>0.){
5849: sumr += PetscSqr(diff/tolr);
5850: nr_loc++;
5851: }
5852: tol=tola+tolr;
5853: if (tol>0.){
5854: sum += PetscSqr(diff/tol);
5855: n_loc++;
5856: }
5857: }
5858: }
5859: VecRestoreArrayRead(U,&u);
5860: VecRestoreArrayRead(Y,&y);
5862: err_loc[0] = sum;
5863: err_loc[1] = suma;
5864: err_loc[2] = sumr;
5865: err_loc[3] = (PetscReal)n_loc;
5866: err_loc[4] = (PetscReal)na_loc;
5867: err_loc[5] = (PetscReal)nr_loc;
5869: MPIU_Allreduce(err_loc,err_glb,6,MPIU_REAL,MPIU_SUM,PetscObjectComm((PetscObject)ts));
5871: gsum = err_glb[0];
5872: gsuma = err_glb[1];
5873: gsumr = err_glb[2];
5874: n_glb = err_glb[3];
5875: na_glb = err_glb[4];
5876: nr_glb = err_glb[5];
5878: *norm = 0.;
5879: if (n_glb>0.){*norm = PetscSqrtReal(gsum / n_glb);}
5880: *norma = 0.;
5881: if (na_glb>0.){*norma = PetscSqrtReal(gsuma / na_glb);}
5882: *normr = 0.;
5883: if (nr_glb>0.){*normr = PetscSqrtReal(gsumr / nr_glb);}
5885: if (PetscIsInfOrNanScalar(*norm)) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_FP,"Infinite or not-a-number generated in norm");
5886: if (PetscIsInfOrNanScalar(*norma)) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_FP,"Infinite or not-a-number generated in norma");
5887: if (PetscIsInfOrNanScalar(*normr)) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_FP,"Infinite or not-a-number generated in normr");
5888: return(0);
5889: }
5891: /*@
5892: TSErrorWeightedNormInfinity - compute a weighted infinity-norm of the difference between two state vectors
5894: Collective on TS
5896: Input Arguments:
5897: + ts - time stepping context
5898: . U - state vector, usually ts->vec_sol
5899: - Y - state vector to be compared to U
5901: Output Arguments:
5902: + norm - weighted norm, a value of 1.0 means that the error matches the tolerances
5903: . norma - weighted norm based on the absolute tolerance, a value of 1.0 means that the error matches the tolerances
5904: - normr - weighted norm based on the relative tolerance, a value of 1.0 means that the error matches the tolerances
5906: Level: developer
5908: .seealso: TSErrorWeightedNorm(), TSErrorWeightedNorm2()
5909: @*/
5910: PetscErrorCode TSErrorWeightedNormInfinity(TS ts,Vec U,Vec Y,PetscReal *norm,PetscReal *norma,PetscReal *normr)
5911: {
5912: PetscErrorCode ierr;
5913: PetscInt i,n,N,rstart;
5914: const PetscScalar *u,*y;
5915: PetscReal max,gmax,maxa,gmaxa,maxr,gmaxr;
5916: PetscReal tol,tola,tolr,diff;
5917: PetscReal err_loc[3],err_glb[3];
5929: if (U == Y) SETERRQ(PetscObjectComm((PetscObject)U),PETSC_ERR_ARG_IDN,"U and Y cannot be the same vector");
5931: VecGetSize(U,&N);
5932: VecGetLocalSize(U,&n);
5933: VecGetOwnershipRange(U,&rstart,NULL);
5934: VecGetArrayRead(U,&u);
5935: VecGetArrayRead(Y,&y);
5937: max=0.;
5938: maxa=0.;
5939: maxr=0.;
5941: if (ts->vatol && ts->vrtol) { /* vector atol, vector rtol */
5942: const PetscScalar *atol,*rtol;
5943: VecGetArrayRead(ts->vatol,&atol);
5944: VecGetArrayRead(ts->vrtol,&rtol);
5946: for (i=0; i<n; i++) {
5947: SkipSmallValue(y[i],u[i],ts->adapt->ignore_max);
5948: diff = PetscAbsScalar(y[i] - u[i]);
5949: tola = PetscRealPart(atol[i]);
5950: tolr = PetscRealPart(rtol[i]) * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
5951: tol = tola+tolr;
5952: if (tola>0.){
5953: maxa = PetscMax(maxa,diff / tola);
5954: }
5955: if (tolr>0.){
5956: maxr = PetscMax(maxr,diff / tolr);
5957: }
5958: if (tol>0.){
5959: max = PetscMax(max,diff / tol);
5960: }
5961: }
5962: VecRestoreArrayRead(ts->vatol,&atol);
5963: VecRestoreArrayRead(ts->vrtol,&rtol);
5964: } else if (ts->vatol) { /* vector atol, scalar rtol */
5965: const PetscScalar *atol;
5966: VecGetArrayRead(ts->vatol,&atol);
5967: for (i=0; i<n; i++) {
5968: SkipSmallValue(y[i],u[i],ts->adapt->ignore_max);
5969: diff = PetscAbsScalar(y[i] - u[i]);
5970: tola = PetscRealPart(atol[i]);
5971: tolr = ts->rtol * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
5972: tol = tola+tolr;
5973: if (tola>0.){
5974: maxa = PetscMax(maxa,diff / tola);
5975: }
5976: if (tolr>0.){
5977: maxr = PetscMax(maxr,diff / tolr);
5978: }
5979: if (tol>0.){
5980: max = PetscMax(max,diff / tol);
5981: }
5982: }
5983: VecRestoreArrayRead(ts->vatol,&atol);
5984: } else if (ts->vrtol) { /* scalar atol, vector rtol */
5985: const PetscScalar *rtol;
5986: VecGetArrayRead(ts->vrtol,&rtol);
5988: for (i=0; i<n; i++) {
5989: SkipSmallValue(y[i],u[i],ts->adapt->ignore_max);
5990: diff = PetscAbsScalar(y[i] - u[i]);
5991: tola = ts->atol;
5992: tolr = PetscRealPart(rtol[i]) * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
5993: tol = tola+tolr;
5994: if (tola>0.){
5995: maxa = PetscMax(maxa,diff / tola);
5996: }
5997: if (tolr>0.){
5998: maxr = PetscMax(maxr,diff / tolr);
5999: }
6000: if (tol>0.){
6001: max = PetscMax(max,diff / tol);
6002: }
6003: }
6004: VecRestoreArrayRead(ts->vrtol,&rtol);
6005: } else { /* scalar atol, scalar rtol */
6007: for (i=0; i<n; i++) {
6008: SkipSmallValue(y[i],u[i],ts->adapt->ignore_max);
6009: diff = PetscAbsScalar(y[i] - u[i]);
6010: tola = ts->atol;
6011: tolr = ts->rtol * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
6012: tol = tola+tolr;
6013: if (tola>0.){
6014: maxa = PetscMax(maxa,diff / tola);
6015: }
6016: if (tolr>0.){
6017: maxr = PetscMax(maxr,diff / tolr);
6018: }
6019: if (tol>0.){
6020: max = PetscMax(max,diff / tol);
6021: }
6022: }
6023: }
6024: VecRestoreArrayRead(U,&u);
6025: VecRestoreArrayRead(Y,&y);
6026: err_loc[0] = max;
6027: err_loc[1] = maxa;
6028: err_loc[2] = maxr;
6029: MPIU_Allreduce(err_loc,err_glb,3,MPIU_REAL,MPIU_MAX,PetscObjectComm((PetscObject)ts));
6030: gmax = err_glb[0];
6031: gmaxa = err_glb[1];
6032: gmaxr = err_glb[2];
6034: *norm = gmax;
6035: *norma = gmaxa;
6036: *normr = gmaxr;
6037: if (PetscIsInfOrNanScalar(*norm)) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_FP,"Infinite or not-a-number generated in norm");
6038: if (PetscIsInfOrNanScalar(*norma)) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_FP,"Infinite or not-a-number generated in norma");
6039: if (PetscIsInfOrNanScalar(*normr)) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_FP,"Infinite or not-a-number generated in normr");
6040: return(0);
6041: }
6043: /*@
6044: TSErrorWeightedNorm - compute a weighted norm of the difference between two state vectors based on supplied absolute and relative tolerances
6046: Collective on TS
6048: Input Arguments:
6049: + ts - time stepping context
6050: . U - state vector, usually ts->vec_sol
6051: . Y - state vector to be compared to U
6052: - wnormtype - norm type, either NORM_2 or NORM_INFINITY
6054: Output Arguments:
6055: + norm - weighted norm, a value of 1.0 achieves a balance between absolute and relative tolerances
6056: . norma - weighted norm, a value of 1.0 means that the error meets the absolute tolerance set by the user
6057: - normr - weighted norm, a value of 1.0 means that the error meets the relative tolerance set by the user
6059: Options Database Keys:
6060: . -ts_adapt_wnormtype <wnormtype> - 2, INFINITY
6062: Level: developer
6064: .seealso: TSErrorWeightedNormInfinity(), TSErrorWeightedNorm2(), TSErrorWeightedENorm
6065: @*/
6066: PetscErrorCode TSErrorWeightedNorm(TS ts,Vec U,Vec Y,NormType wnormtype,PetscReal *norm,PetscReal *norma,PetscReal *normr)
6067: {
6071: if (wnormtype == NORM_2) {
6072: TSErrorWeightedNorm2(ts,U,Y,norm,norma,normr);
6073: } else if (wnormtype == NORM_INFINITY) {
6074: TSErrorWeightedNormInfinity(ts,U,Y,norm,norma,normr);
6075: } else SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"No support for norm type %s",NormTypes[wnormtype]);
6076: return(0);
6077: }
6080: /*@
6081: TSErrorWeightedENorm2 - compute a weighted 2 error norm based on supplied absolute and relative tolerances
6083: Collective on TS
6085: Input Arguments:
6086: + ts - time stepping context
6087: . E - error vector
6088: . U - state vector, usually ts->vec_sol
6089: - Y - state vector, previous time step
6091: Output Arguments:
6092: + norm - weighted norm, a value of 1.0 means that the error matches the tolerances
6093: . norma - weighted norm based on the absolute tolerance, a value of 1.0 means that the error matches the tolerances
6094: - normr - weighted norm based on the relative tolerance, a value of 1.0 means that the error matches the tolerances
6096: Level: developer
6098: .seealso: TSErrorWeightedENorm(), TSErrorWeightedENormInfinity()
6099: @*/
6100: PetscErrorCode TSErrorWeightedENorm2(TS ts,Vec E,Vec U,Vec Y,PetscReal *norm,PetscReal *norma,PetscReal *normr)
6101: {
6102: PetscErrorCode ierr;
6103: PetscInt i,n,N,rstart;
6104: PetscInt n_loc,na_loc,nr_loc;
6105: PetscReal n_glb,na_glb,nr_glb;
6106: const PetscScalar *e,*u,*y;
6107: PetscReal err,sum,suma,sumr,gsum,gsuma,gsumr;
6108: PetscReal tol,tola,tolr;
6109: PetscReal err_loc[6],err_glb[6];
6125: VecGetSize(E,&N);
6126: VecGetLocalSize(E,&n);
6127: VecGetOwnershipRange(E,&rstart,NULL);
6128: VecGetArrayRead(E,&e);
6129: VecGetArrayRead(U,&u);
6130: VecGetArrayRead(Y,&y);
6131: sum = 0.; n_loc = 0;
6132: suma = 0.; na_loc = 0;
6133: sumr = 0.; nr_loc = 0;
6134: if (ts->vatol && ts->vrtol) {
6135: const PetscScalar *atol,*rtol;
6136: VecGetArrayRead(ts->vatol,&atol);
6137: VecGetArrayRead(ts->vrtol,&rtol);
6138: for (i=0; i<n; i++) {
6139: SkipSmallValue(y[i],u[i],ts->adapt->ignore_max);
6140: err = PetscAbsScalar(e[i]);
6141: tola = PetscRealPart(atol[i]);
6142: if (tola>0.){
6143: suma += PetscSqr(err/tola);
6144: na_loc++;
6145: }
6146: tolr = PetscRealPart(rtol[i]) * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
6147: if (tolr>0.){
6148: sumr += PetscSqr(err/tolr);
6149: nr_loc++;
6150: }
6151: tol=tola+tolr;
6152: if (tol>0.){
6153: sum += PetscSqr(err/tol);
6154: n_loc++;
6155: }
6156: }
6157: VecRestoreArrayRead(ts->vatol,&atol);
6158: VecRestoreArrayRead(ts->vrtol,&rtol);
6159: } else if (ts->vatol) { /* vector atol, scalar rtol */
6160: const PetscScalar *atol;
6161: VecGetArrayRead(ts->vatol,&atol);
6162: for (i=0; i<n; i++) {
6163: SkipSmallValue(y[i],u[i],ts->adapt->ignore_max);
6164: err = PetscAbsScalar(e[i]);
6165: tola = PetscRealPart(atol[i]);
6166: if (tola>0.){
6167: suma += PetscSqr(err/tola);
6168: na_loc++;
6169: }
6170: tolr = ts->rtol * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
6171: if (tolr>0.){
6172: sumr += PetscSqr(err/tolr);
6173: nr_loc++;
6174: }
6175: tol=tola+tolr;
6176: if (tol>0.){
6177: sum += PetscSqr(err/tol);
6178: n_loc++;
6179: }
6180: }
6181: VecRestoreArrayRead(ts->vatol,&atol);
6182: } else if (ts->vrtol) { /* scalar atol, vector rtol */
6183: const PetscScalar *rtol;
6184: VecGetArrayRead(ts->vrtol,&rtol);
6185: for (i=0; i<n; i++) {
6186: SkipSmallValue(y[i],u[i],ts->adapt->ignore_max);
6187: err = PetscAbsScalar(e[i]);
6188: tola = ts->atol;
6189: if (tola>0.){
6190: suma += PetscSqr(err/tola);
6191: na_loc++;
6192: }
6193: tolr = PetscRealPart(rtol[i]) * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
6194: if (tolr>0.){
6195: sumr += PetscSqr(err/tolr);
6196: nr_loc++;
6197: }
6198: tol=tola+tolr;
6199: if (tol>0.){
6200: sum += PetscSqr(err/tol);
6201: n_loc++;
6202: }
6203: }
6204: VecRestoreArrayRead(ts->vrtol,&rtol);
6205: } else { /* scalar atol, scalar rtol */
6206: for (i=0; i<n; i++) {
6207: SkipSmallValue(y[i],u[i],ts->adapt->ignore_max);
6208: err = PetscAbsScalar(e[i]);
6209: tola = ts->atol;
6210: if (tola>0.){
6211: suma += PetscSqr(err/tola);
6212: na_loc++;
6213: }
6214: tolr = ts->rtol * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
6215: if (tolr>0.){
6216: sumr += PetscSqr(err/tolr);
6217: nr_loc++;
6218: }
6219: tol=tola+tolr;
6220: if (tol>0.){
6221: sum += PetscSqr(err/tol);
6222: n_loc++;
6223: }
6224: }
6225: }
6226: VecRestoreArrayRead(E,&e);
6227: VecRestoreArrayRead(U,&u);
6228: VecRestoreArrayRead(Y,&y);
6230: err_loc[0] = sum;
6231: err_loc[1] = suma;
6232: err_loc[2] = sumr;
6233: err_loc[3] = (PetscReal)n_loc;
6234: err_loc[4] = (PetscReal)na_loc;
6235: err_loc[5] = (PetscReal)nr_loc;
6237: MPIU_Allreduce(err_loc,err_glb,6,MPIU_REAL,MPIU_SUM,PetscObjectComm((PetscObject)ts));
6239: gsum = err_glb[0];
6240: gsuma = err_glb[1];
6241: gsumr = err_glb[2];
6242: n_glb = err_glb[3];
6243: na_glb = err_glb[4];
6244: nr_glb = err_glb[5];
6246: *norm = 0.;
6247: if (n_glb>0.){*norm = PetscSqrtReal(gsum / n_glb);}
6248: *norma = 0.;
6249: if (na_glb>0.){*norma = PetscSqrtReal(gsuma / na_glb);}
6250: *normr = 0.;
6251: if (nr_glb>0.){*normr = PetscSqrtReal(gsumr / nr_glb);}
6253: if (PetscIsInfOrNanScalar(*norm)) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_FP,"Infinite or not-a-number generated in norm");
6254: if (PetscIsInfOrNanScalar(*norma)) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_FP,"Infinite or not-a-number generated in norma");
6255: if (PetscIsInfOrNanScalar(*normr)) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_FP,"Infinite or not-a-number generated in normr");
6256: return(0);
6257: }
6259: /*@
6260: TSErrorWeightedENormInfinity - compute a weighted infinity error norm based on supplied absolute and relative tolerances
6261: Collective on TS
6263: Input Arguments:
6264: + ts - time stepping context
6265: . E - error vector
6266: . U - state vector, usually ts->vec_sol
6267: - Y - state vector, previous time step
6269: Output Arguments:
6270: + norm - weighted norm, a value of 1.0 means that the error matches the tolerances
6271: . norma - weighted norm based on the absolute tolerance, a value of 1.0 means that the error matches the tolerances
6272: - normr - weighted norm based on the relative tolerance, a value of 1.0 means that the error matches the tolerances
6274: Level: developer
6276: .seealso: TSErrorWeightedENorm(), TSErrorWeightedENorm2()
6277: @*/
6278: PetscErrorCode TSErrorWeightedENormInfinity(TS ts,Vec E,Vec U,Vec Y,PetscReal *norm,PetscReal *norma,PetscReal *normr)
6279: {
6280: PetscErrorCode ierr;
6281: PetscInt i,n,N,rstart;
6282: const PetscScalar *e,*u,*y;
6283: PetscReal err,max,gmax,maxa,gmaxa,maxr,gmaxr;
6284: PetscReal tol,tola,tolr;
6285: PetscReal err_loc[3],err_glb[3];
6301: VecGetSize(E,&N);
6302: VecGetLocalSize(E,&n);
6303: VecGetOwnershipRange(E,&rstart,NULL);
6304: VecGetArrayRead(E,&e);
6305: VecGetArrayRead(U,&u);
6306: VecGetArrayRead(Y,&y);
6308: max=0.;
6309: maxa=0.;
6310: maxr=0.;
6312: if (ts->vatol && ts->vrtol) { /* vector atol, vector rtol */
6313: const PetscScalar *atol,*rtol;
6314: VecGetArrayRead(ts->vatol,&atol);
6315: VecGetArrayRead(ts->vrtol,&rtol);
6317: for (i=0; i<n; i++) {
6318: SkipSmallValue(y[i],u[i],ts->adapt->ignore_max);
6319: err = PetscAbsScalar(e[i]);
6320: tola = PetscRealPart(atol[i]);
6321: tolr = PetscRealPart(rtol[i]) * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
6322: tol = tola+tolr;
6323: if (tola>0.){
6324: maxa = PetscMax(maxa,err / tola);
6325: }
6326: if (tolr>0.){
6327: maxr = PetscMax(maxr,err / tolr);
6328: }
6329: if (tol>0.){
6330: max = PetscMax(max,err / tol);
6331: }
6332: }
6333: VecRestoreArrayRead(ts->vatol,&atol);
6334: VecRestoreArrayRead(ts->vrtol,&rtol);
6335: } else if (ts->vatol) { /* vector atol, scalar rtol */
6336: const PetscScalar *atol;
6337: VecGetArrayRead(ts->vatol,&atol);
6338: for (i=0; i<n; i++) {
6339: SkipSmallValue(y[i],u[i],ts->adapt->ignore_max);
6340: err = PetscAbsScalar(e[i]);
6341: tola = PetscRealPart(atol[i]);
6342: tolr = ts->rtol * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
6343: tol = tola+tolr;
6344: if (tola>0.){
6345: maxa = PetscMax(maxa,err / tola);
6346: }
6347: if (tolr>0.){
6348: maxr = PetscMax(maxr,err / tolr);
6349: }
6350: if (tol>0.){
6351: max = PetscMax(max,err / tol);
6352: }
6353: }
6354: VecRestoreArrayRead(ts->vatol,&atol);
6355: } else if (ts->vrtol) { /* scalar atol, vector rtol */
6356: const PetscScalar *rtol;
6357: VecGetArrayRead(ts->vrtol,&rtol);
6359: for (i=0; i<n; i++) {
6360: SkipSmallValue(y[i],u[i],ts->adapt->ignore_max);
6361: err = PetscAbsScalar(e[i]);
6362: tola = ts->atol;
6363: tolr = PetscRealPart(rtol[i]) * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
6364: tol = tola+tolr;
6365: if (tola>0.){
6366: maxa = PetscMax(maxa,err / tola);
6367: }
6368: if (tolr>0.){
6369: maxr = PetscMax(maxr,err / tolr);
6370: }
6371: if (tol>0.){
6372: max = PetscMax(max,err / tol);
6373: }
6374: }
6375: VecRestoreArrayRead(ts->vrtol,&rtol);
6376: } else { /* scalar atol, scalar rtol */
6378: for (i=0; i<n; i++) {
6379: SkipSmallValue(y[i],u[i],ts->adapt->ignore_max);
6380: err = PetscAbsScalar(e[i]);
6381: tola = ts->atol;
6382: tolr = ts->rtol * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
6383: tol = tola+tolr;
6384: if (tola>0.){
6385: maxa = PetscMax(maxa,err / tola);
6386: }
6387: if (tolr>0.){
6388: maxr = PetscMax(maxr,err / tolr);
6389: }
6390: if (tol>0.){
6391: max = PetscMax(max,err / tol);
6392: }
6393: }
6394: }
6395: VecRestoreArrayRead(E,&e);
6396: VecRestoreArrayRead(U,&u);
6397: VecRestoreArrayRead(Y,&y);
6398: err_loc[0] = max;
6399: err_loc[1] = maxa;
6400: err_loc[2] = maxr;
6401: MPIU_Allreduce(err_loc,err_glb,3,MPIU_REAL,MPIU_MAX,PetscObjectComm((PetscObject)ts));
6402: gmax = err_glb[0];
6403: gmaxa = err_glb[1];
6404: gmaxr = err_glb[2];
6406: *norm = gmax;
6407: *norma = gmaxa;
6408: *normr = gmaxr;
6409: if (PetscIsInfOrNanScalar(*norm)) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_FP,"Infinite or not-a-number generated in norm");
6410: if (PetscIsInfOrNanScalar(*norma)) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_FP,"Infinite or not-a-number generated in norma");
6411: if (PetscIsInfOrNanScalar(*normr)) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_FP,"Infinite or not-a-number generated in normr");
6412: return(0);
6413: }
6415: /*@
6416: TSErrorWeightedENorm - compute a weighted error norm based on supplied absolute and relative tolerances
6418: Collective on TS
6420: Input Arguments:
6421: + ts - time stepping context
6422: . E - error vector
6423: . U - state vector, usually ts->vec_sol
6424: . Y - state vector, previous time step
6425: - wnormtype - norm type, either NORM_2 or NORM_INFINITY
6427: Output Arguments:
6428: + norm - weighted norm, a value of 1.0 achieves a balance between absolute and relative tolerances
6429: . norma - weighted norm, a value of 1.0 means that the error meets the absolute tolerance set by the user
6430: - normr - weighted norm, a value of 1.0 means that the error meets the relative tolerance set by the user
6432: Options Database Keys:
6433: . -ts_adapt_wnormtype <wnormtype> - 2, INFINITY
6435: Level: developer
6437: .seealso: TSErrorWeightedENormInfinity(), TSErrorWeightedENorm2(), TSErrorWeightedNormInfinity(), TSErrorWeightedNorm2()
6438: @*/
6439: PetscErrorCode TSErrorWeightedENorm(TS ts,Vec E,Vec U,Vec Y,NormType wnormtype,PetscReal *norm,PetscReal *norma,PetscReal *normr)
6440: {
6444: if (wnormtype == NORM_2) {
6445: TSErrorWeightedENorm2(ts,E,U,Y,norm,norma,normr);
6446: } else if (wnormtype == NORM_INFINITY) {
6447: TSErrorWeightedENormInfinity(ts,E,U,Y,norm,norma,normr);
6448: } else SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"No support for norm type %s",NormTypes[wnormtype]);
6449: return(0);
6450: }
6453: /*@
6454: TSSetCFLTimeLocal - Set the local CFL constraint relative to forward Euler
6456: Logically Collective on TS
6458: Input Arguments:
6459: + ts - time stepping context
6460: - cfltime - maximum stable time step if using forward Euler (value can be different on each process)
6462: Note:
6463: After calling this function, the global CFL time can be obtained by calling TSGetCFLTime()
6465: Level: intermediate
6467: .seealso: TSGetCFLTime(), TSADAPTCFL
6468: @*/
6469: PetscErrorCode TSSetCFLTimeLocal(TS ts,PetscReal cfltime)
6470: {
6473: ts->cfltime_local = cfltime;
6474: ts->cfltime = -1.;
6475: return(0);
6476: }
6478: /*@
6479: TSGetCFLTime - Get the maximum stable time step according to CFL criteria applied to forward Euler
6481: Collective on TS
6483: Input Arguments:
6484: . ts - time stepping context
6486: Output Arguments:
6487: . cfltime - maximum stable time step for forward Euler
6489: Level: advanced
6491: .seealso: TSSetCFLTimeLocal()
6492: @*/
6493: PetscErrorCode TSGetCFLTime(TS ts,PetscReal *cfltime)
6494: {
6498: if (ts->cfltime < 0) {
6499: MPIU_Allreduce(&ts->cfltime_local,&ts->cfltime,1,MPIU_REAL,MPIU_MIN,PetscObjectComm((PetscObject)ts));
6500: }
6501: *cfltime = ts->cfltime;
6502: return(0);
6503: }
6505: /*@
6506: TSVISetVariableBounds - Sets the lower and upper bounds for the solution vector. xl <= x <= xu
6508: Input Parameters:
6509: + ts - the TS context.
6510: . xl - lower bound.
6511: - xu - upper bound.
6513: Notes:
6514: If this routine is not called then the lower and upper bounds are set to
6515: PETSC_NINFINITY and PETSC_INFINITY respectively during SNESSetUp().
6517: Level: advanced
6519: @*/
6520: PetscErrorCode TSVISetVariableBounds(TS ts, Vec xl, Vec xu)
6521: {
6523: SNES snes;
6526: TSGetSNES(ts,&snes);
6527: SNESVISetVariableBounds(snes,xl,xu);
6528: return(0);
6529: }
6531: /*@C
6532: TSMonitorLGSolution - Monitors progress of the TS solvers by plotting each component of the solution vector
6533: in a time based line graph
6535: Collective on TS
6537: Input Parameters:
6538: + ts - the TS context
6539: . step - current time-step
6540: . ptime - current time
6541: . u - current solution
6542: - dctx - the TSMonitorLGCtx object that contains all the options for the monitoring, this is created with TSMonitorLGCtxCreate()
6544: Options Database:
6545: . -ts_monitor_lg_solution_variables
6547: Level: intermediate
6549: Notes:
6550: Each process in a parallel run displays its component solutions in a separate window
6552: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorLGCtxCreate(), TSMonitorLGCtxSetVariableNames(), TSMonitorLGCtxGetVariableNames(),
6553: TSMonitorLGSetVariableNames(), TSMonitorLGGetVariableNames(), TSMonitorLGSetDisplayVariables(), TSMonitorLGCtxSetDisplayVariables(),
6554: TSMonitorLGCtxSetTransform(), TSMonitorLGSetTransform(), TSMonitorLGError(), TSMonitorLGSNESIterations(), TSMonitorLGKSPIterations(),
6555: TSMonitorEnvelopeCtxCreate(), TSMonitorEnvelopeGetBounds(), TSMonitorEnvelopeCtxDestroy(), TSMonitorEnvelop()
6556: @*/
6557: PetscErrorCode TSMonitorLGSolution(TS ts,PetscInt step,PetscReal ptime,Vec u,void *dctx)
6558: {
6559: PetscErrorCode ierr;
6560: TSMonitorLGCtx ctx = (TSMonitorLGCtx)dctx;
6561: const PetscScalar *yy;
6562: Vec v;
6565: if (step < 0) return(0); /* -1 indicates interpolated solution */
6566: if (!step) {
6567: PetscDrawAxis axis;
6568: PetscInt dim;
6569: PetscDrawLGGetAxis(ctx->lg,&axis);
6570: PetscDrawAxisSetLabels(axis,"Solution as function of time","Time","Solution");
6571: if (!ctx->names) {
6572: PetscBool flg;
6573: /* user provides names of variables to plot but no names has been set so assume names are integer values */
6574: PetscOptionsHasName(((PetscObject)ts)->options,((PetscObject)ts)->prefix,"-ts_monitor_lg_solution_variables",&flg);
6575: if (flg) {
6576: PetscInt i,n;
6577: char **names;
6578: VecGetSize(u,&n);
6579: PetscMalloc1(n+1,&names);
6580: for (i=0; i<n; i++) {
6581: PetscMalloc1(5,&names[i]);
6582: PetscSNPrintf(names[i],5,"%D",i);
6583: }
6584: names[n] = NULL;
6585: ctx->names = names;
6586: }
6587: }
6588: if (ctx->names && !ctx->displaynames) {
6589: char **displaynames;
6590: PetscBool flg;
6591: VecGetLocalSize(u,&dim);
6592: PetscCalloc1(dim+1,&displaynames);
6593: PetscOptionsGetStringArray(((PetscObject)ts)->options,((PetscObject)ts)->prefix,"-ts_monitor_lg_solution_variables",displaynames,&dim,&flg);
6594: if (flg) {
6595: TSMonitorLGCtxSetDisplayVariables(ctx,(const char *const *)displaynames);
6596: }
6597: PetscStrArrayDestroy(&displaynames);
6598: }
6599: if (ctx->displaynames) {
6600: PetscDrawLGSetDimension(ctx->lg,ctx->ndisplayvariables);
6601: PetscDrawLGSetLegend(ctx->lg,(const char *const *)ctx->displaynames);
6602: } else if (ctx->names) {
6603: VecGetLocalSize(u,&dim);
6604: PetscDrawLGSetDimension(ctx->lg,dim);
6605: PetscDrawLGSetLegend(ctx->lg,(const char *const *)ctx->names);
6606: } else {
6607: VecGetLocalSize(u,&dim);
6608: PetscDrawLGSetDimension(ctx->lg,dim);
6609: }
6610: PetscDrawLGReset(ctx->lg);
6611: }
6613: if (!ctx->transform) v = u;
6614: else {(*ctx->transform)(ctx->transformctx,u,&v);}
6615: VecGetArrayRead(v,&yy);
6616: if (ctx->displaynames) {
6617: PetscInt i;
6618: for (i=0; i<ctx->ndisplayvariables; i++)
6619: ctx->displayvalues[i] = PetscRealPart(yy[ctx->displayvariables[i]]);
6620: PetscDrawLGAddCommonPoint(ctx->lg,ptime,ctx->displayvalues);
6621: } else {
6622: #if defined(PETSC_USE_COMPLEX)
6623: PetscInt i,n;
6624: PetscReal *yreal;
6625: VecGetLocalSize(v,&n);
6626: PetscMalloc1(n,&yreal);
6627: for (i=0; i<n; i++) yreal[i] = PetscRealPart(yy[i]);
6628: PetscDrawLGAddCommonPoint(ctx->lg,ptime,yreal);
6629: PetscFree(yreal);
6630: #else
6631: PetscDrawLGAddCommonPoint(ctx->lg,ptime,yy);
6632: #endif
6633: }
6634: VecRestoreArrayRead(v,&yy);
6635: if (ctx->transform) {VecDestroy(&v);}
6637: if (((ctx->howoften > 0) && (!(step % ctx->howoften))) || ((ctx->howoften == -1) && ts->reason)) {
6638: PetscDrawLGDraw(ctx->lg);
6639: PetscDrawLGSave(ctx->lg);
6640: }
6641: return(0);
6642: }
6644: /*@C
6645: TSMonitorLGSetVariableNames - Sets the name of each component in the solution vector so that it may be displayed in the plot
6647: Collective on TS
6649: Input Parameters:
6650: + ts - the TS context
6651: - names - the names of the components, final string must be NULL
6653: Level: intermediate
6655: Notes:
6656: If the TS object does not have a TSMonitorLGCtx associated with it then this function is ignored
6658: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorLGSetDisplayVariables(), TSMonitorLGCtxSetVariableNames()
6659: @*/
6660: PetscErrorCode TSMonitorLGSetVariableNames(TS ts,const char * const *names)
6661: {
6662: PetscErrorCode ierr;
6663: PetscInt i;
6666: for (i=0; i<ts->numbermonitors; i++) {
6667: if (ts->monitor[i] == TSMonitorLGSolution) {
6668: TSMonitorLGCtxSetVariableNames((TSMonitorLGCtx)ts->monitorcontext[i],names);
6669: break;
6670: }
6671: }
6672: return(0);
6673: }
6675: /*@C
6676: TSMonitorLGCtxSetVariableNames - Sets the name of each component in the solution vector so that it may be displayed in the plot
6678: Collective on TS
6680: Input Parameters:
6681: + ts - the TS context
6682: - names - the names of the components, final string must be NULL
6684: Level: intermediate
6686: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorLGSetDisplayVariables(), TSMonitorLGSetVariableNames()
6687: @*/
6688: PetscErrorCode TSMonitorLGCtxSetVariableNames(TSMonitorLGCtx ctx,const char * const *names)
6689: {
6690: PetscErrorCode ierr;
6693: PetscStrArrayDestroy(&ctx->names);
6694: PetscStrArrayallocpy(names,&ctx->names);
6695: return(0);
6696: }
6698: /*@C
6699: TSMonitorLGGetVariableNames - Gets the name of each component in the solution vector so that it may be displayed in the plot
6701: Collective on TS
6703: Input Parameter:
6704: . ts - the TS context
6706: Output Parameter:
6707: . names - the names of the components, final string must be NULL
6709: Level: intermediate
6711: Notes:
6712: If the TS object does not have a TSMonitorLGCtx associated with it then this function is ignored
6714: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorLGSetDisplayVariables()
6715: @*/
6716: PetscErrorCode TSMonitorLGGetVariableNames(TS ts,const char *const **names)
6717: {
6718: PetscInt i;
6721: *names = NULL;
6722: for (i=0; i<ts->numbermonitors; i++) {
6723: if (ts->monitor[i] == TSMonitorLGSolution) {
6724: TSMonitorLGCtx ctx = (TSMonitorLGCtx) ts->monitorcontext[i];
6725: *names = (const char *const *)ctx->names;
6726: break;
6727: }
6728: }
6729: return(0);
6730: }
6732: /*@C
6733: TSMonitorLGCtxSetDisplayVariables - Sets the variables that are to be display in the monitor
6735: Collective on TS
6737: Input Parameters:
6738: + ctx - the TSMonitorLG context
6739: - displaynames - the names of the components, final string must be NULL
6741: Level: intermediate
6743: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorLGSetVariableNames()
6744: @*/
6745: PetscErrorCode TSMonitorLGCtxSetDisplayVariables(TSMonitorLGCtx ctx,const char * const *displaynames)
6746: {
6747: PetscInt j = 0,k;
6748: PetscErrorCode ierr;
6751: if (!ctx->names) return(0);
6752: PetscStrArrayDestroy(&ctx->displaynames);
6753: PetscStrArrayallocpy(displaynames,&ctx->displaynames);
6754: while (displaynames[j]) j++;
6755: ctx->ndisplayvariables = j;
6756: PetscMalloc1(ctx->ndisplayvariables,&ctx->displayvariables);
6757: PetscMalloc1(ctx->ndisplayvariables,&ctx->displayvalues);
6758: j = 0;
6759: while (displaynames[j]) {
6760: k = 0;
6761: while (ctx->names[k]) {
6762: PetscBool flg;
6763: PetscStrcmp(displaynames[j],ctx->names[k],&flg);
6764: if (flg) {
6765: ctx->displayvariables[j] = k;
6766: break;
6767: }
6768: k++;
6769: }
6770: j++;
6771: }
6772: return(0);
6773: }
6775: /*@C
6776: TSMonitorLGSetDisplayVariables - Sets the variables that are to be display in the monitor
6778: Collective on TS
6780: Input Parameters:
6781: + ts - the TS context
6782: - displaynames - the names of the components, final string must be NULL
6784: Notes:
6785: If the TS object does not have a TSMonitorLGCtx associated with it then this function is ignored
6787: Level: intermediate
6789: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorLGSetVariableNames()
6790: @*/
6791: PetscErrorCode TSMonitorLGSetDisplayVariables(TS ts,const char * const *displaynames)
6792: {
6793: PetscInt i;
6794: PetscErrorCode ierr;
6797: for (i=0; i<ts->numbermonitors; i++) {
6798: if (ts->monitor[i] == TSMonitorLGSolution) {
6799: TSMonitorLGCtxSetDisplayVariables((TSMonitorLGCtx)ts->monitorcontext[i],displaynames);
6800: break;
6801: }
6802: }
6803: return(0);
6804: }
6806: /*@C
6807: TSMonitorLGSetTransform - Solution vector will be transformed by provided function before being displayed
6809: Collective on TS
6811: Input Parameters:
6812: + ts - the TS context
6813: . transform - the transform function
6814: . destroy - function to destroy the optional context
6815: - ctx - optional context used by transform function
6817: Notes:
6818: If the TS object does not have a TSMonitorLGCtx associated with it then this function is ignored
6820: Level: intermediate
6822: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorLGSetVariableNames(), TSMonitorLGCtxSetTransform()
6823: @*/
6824: PetscErrorCode TSMonitorLGSetTransform(TS ts,PetscErrorCode (*transform)(void*,Vec,Vec*),PetscErrorCode (*destroy)(void*),void *tctx)
6825: {
6826: PetscInt i;
6827: PetscErrorCode ierr;
6830: for (i=0; i<ts->numbermonitors; i++) {
6831: if (ts->monitor[i] == TSMonitorLGSolution) {
6832: TSMonitorLGCtxSetTransform((TSMonitorLGCtx)ts->monitorcontext[i],transform,destroy,tctx);
6833: }
6834: }
6835: return(0);
6836: }
6838: /*@C
6839: TSMonitorLGCtxSetTransform - Solution vector will be transformed by provided function before being displayed
6841: Collective on TSLGCtx
6843: Input Parameters:
6844: + ts - the TS context
6845: . transform - the transform function
6846: . destroy - function to destroy the optional context
6847: - ctx - optional context used by transform function
6849: Level: intermediate
6851: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorLGSetVariableNames(), TSMonitorLGSetTransform()
6852: @*/
6853: PetscErrorCode TSMonitorLGCtxSetTransform(TSMonitorLGCtx ctx,PetscErrorCode (*transform)(void*,Vec,Vec*),PetscErrorCode (*destroy)(void*),void *tctx)
6854: {
6856: ctx->transform = transform;
6857: ctx->transformdestroy = destroy;
6858: ctx->transformctx = tctx;
6859: return(0);
6860: }
6862: /*@C
6863: TSMonitorLGError - Monitors progress of the TS solvers by plotting each component of the error
6864: in a time based line graph
6866: Collective on TS
6868: Input Parameters:
6869: + ts - the TS context
6870: . step - current time-step
6871: . ptime - current time
6872: . u - current solution
6873: - dctx - TSMonitorLGCtx object created with TSMonitorLGCtxCreate()
6875: Level: intermediate
6877: Notes:
6878: Each process in a parallel run displays its component errors in a separate window
6880: The user must provide the solution using TSSetSolutionFunction() to use this monitor.
6882: Options Database Keys:
6883: . -ts_monitor_lg_error - create a graphical monitor of error history
6885: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSSetSolutionFunction()
6886: @*/
6887: PetscErrorCode TSMonitorLGError(TS ts,PetscInt step,PetscReal ptime,Vec u,void *dummy)
6888: {
6889: PetscErrorCode ierr;
6890: TSMonitorLGCtx ctx = (TSMonitorLGCtx)dummy;
6891: const PetscScalar *yy;
6892: Vec y;
6895: if (!step) {
6896: PetscDrawAxis axis;
6897: PetscInt dim;
6898: PetscDrawLGGetAxis(ctx->lg,&axis);
6899: PetscDrawAxisSetLabels(axis,"Error in solution as function of time","Time","Error");
6900: VecGetLocalSize(u,&dim);
6901: PetscDrawLGSetDimension(ctx->lg,dim);
6902: PetscDrawLGReset(ctx->lg);
6903: }
6904: VecDuplicate(u,&y);
6905: TSComputeSolutionFunction(ts,ptime,y);
6906: VecAXPY(y,-1.0,u);
6907: VecGetArrayRead(y,&yy);
6908: #if defined(PETSC_USE_COMPLEX)
6909: {
6910: PetscReal *yreal;
6911: PetscInt i,n;
6912: VecGetLocalSize(y,&n);
6913: PetscMalloc1(n,&yreal);
6914: for (i=0; i<n; i++) yreal[i] = PetscRealPart(yy[i]);
6915: PetscDrawLGAddCommonPoint(ctx->lg,ptime,yreal);
6916: PetscFree(yreal);
6917: }
6918: #else
6919: PetscDrawLGAddCommonPoint(ctx->lg,ptime,yy);
6920: #endif
6921: VecRestoreArrayRead(y,&yy);
6922: VecDestroy(&y);
6923: if (((ctx->howoften > 0) && (!(step % ctx->howoften))) || ((ctx->howoften == -1) && ts->reason)) {
6924: PetscDrawLGDraw(ctx->lg);
6925: PetscDrawLGSave(ctx->lg);
6926: }
6927: return(0);
6928: }
6930: /*@C
6931: TSMonitorSPSwarmSolution - Graphically displays phase plots of DMSwarm particles on a scatter plot
6933: Input Parameters:
6934: + ts - the TS context
6935: . step - current time-step
6936: . ptime - current time
6937: . u - current solution
6938: - dctx - the TSMonitorSPCtx object that contains all the options for the monitoring, this is created with TSMonitorSPCtxCreate()
6940: Options Database:
6941: . -ts_monitor_sp_swarm
6943: Level: intermediate
6945: @*/
6946: PetscErrorCode TSMonitorSPSwarmSolution(TS ts,PetscInt step,PetscReal ptime,Vec u,void *dctx)
6947: {
6948: PetscErrorCode ierr;
6949: TSMonitorSPCtx ctx = (TSMonitorSPCtx)dctx;
6950: const PetscScalar *yy;
6951: PetscReal *y,*x;
6952: PetscInt Np, p, dim=2;
6953: DM dm;
6957: if (step < 0) return(0); /* -1 indicates interpolated solution */
6958: if (!step) {
6959: PetscDrawAxis axis;
6960: PetscDrawSPGetAxis(ctx->sp,&axis);
6961: PetscDrawAxisSetLabels(axis,"Particles","X","Y");
6962: PetscDrawAxisSetLimits(axis, -5, 5, -5, 5);
6963: PetscDrawAxisSetHoldLimits(axis, PETSC_TRUE);
6964: TSGetDM(ts, &dm);
6965: DMGetDimension(dm, &dim);
6966: if (dim!=2) SETERRQ(PETSC_COMM_SELF, ierr, "Dimensions improper for monitor arguments! Current support: two dimensions.");
6967: VecGetLocalSize(u, &Np);
6968: Np /= 2*dim;
6969: PetscDrawSPSetDimension(ctx->sp, Np);
6970: PetscDrawSPReset(ctx->sp);
6971: }
6973: VecGetLocalSize(u, &Np);
6974: Np /= 2*dim;
6975: VecGetArrayRead(u,&yy);
6976: PetscMalloc2(Np, &x, Np, &y);
6977: /* get points from solution vector */
6978: for (p=0; p<Np; ++p){
6979: x[p] = PetscRealPart(yy[2*dim*p]);
6980: y[p] = PetscRealPart(yy[2*dim*p+1]);
6981: }
6982: VecRestoreArrayRead(u,&yy);
6984: if (((ctx->howoften > 0) && (!(step % ctx->howoften))) || ((ctx->howoften == -1) && ts->reason)) {
6985: PetscDrawSPAddPoint(ctx->sp,x,y);
6986: PetscDrawSPDraw(ctx->sp,PETSC_FALSE);
6987: PetscDrawSPSave(ctx->sp);
6988: }
6990: PetscFree2(x, y);
6992: return(0);
6993: }
6997: /*@C
6998: TSMonitorError - Monitors progress of the TS solvers by printing the 2 norm of the error at each timestep
7000: Collective on TS
7002: Input Parameters:
7003: + ts - the TS context
7004: . step - current time-step
7005: . ptime - current time
7006: . u - current solution
7007: - dctx - unused context
7009: Level: intermediate
7011: The user must provide the solution using TSSetSolutionFunction() to use this monitor.
7013: Options Database Keys:
7014: . -ts_monitor_error - create a graphical monitor of error history
7016: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSSetSolutionFunction()
7017: @*/
7018: PetscErrorCode TSMonitorError(TS ts,PetscInt step,PetscReal ptime,Vec u,PetscViewerAndFormat *vf)
7019: {
7020: PetscErrorCode ierr;
7021: Vec y;
7022: PetscReal nrm;
7023: PetscBool flg;
7026: VecDuplicate(u,&y);
7027: TSComputeSolutionFunction(ts,ptime,y);
7028: VecAXPY(y,-1.0,u);
7029: PetscObjectTypeCompare((PetscObject)vf->viewer,PETSCVIEWERASCII,&flg);
7030: if (flg) {
7031: VecNorm(y,NORM_2,&nrm);
7032: PetscViewerASCIIPrintf(vf->viewer,"2-norm of error %g\n",(double)nrm);
7033: }
7034: PetscObjectTypeCompare((PetscObject)vf->viewer,PETSCVIEWERDRAW,&flg);
7035: if (flg) {
7036: VecView(y,vf->viewer);
7037: }
7038: VecDestroy(&y);
7039: return(0);
7040: }
7042: PetscErrorCode TSMonitorLGSNESIterations(TS ts,PetscInt n,PetscReal ptime,Vec v,void *monctx)
7043: {
7044: TSMonitorLGCtx ctx = (TSMonitorLGCtx) monctx;
7045: PetscReal x = ptime,y;
7047: PetscInt its;
7050: if (n < 0) return(0); /* -1 indicates interpolated solution */
7051: if (!n) {
7052: PetscDrawAxis axis;
7053: PetscDrawLGGetAxis(ctx->lg,&axis);
7054: PetscDrawAxisSetLabels(axis,"Nonlinear iterations as function of time","Time","SNES Iterations");
7055: PetscDrawLGReset(ctx->lg);
7056: ctx->snes_its = 0;
7057: }
7058: TSGetSNESIterations(ts,&its);
7059: y = its - ctx->snes_its;
7060: PetscDrawLGAddPoint(ctx->lg,&x,&y);
7061: if (((ctx->howoften > 0) && (!(n % ctx->howoften)) && (n > -1)) || ((ctx->howoften == -1) && (n == -1))) {
7062: PetscDrawLGDraw(ctx->lg);
7063: PetscDrawLGSave(ctx->lg);
7064: }
7065: ctx->snes_its = its;
7066: return(0);
7067: }
7069: PetscErrorCode TSMonitorLGKSPIterations(TS ts,PetscInt n,PetscReal ptime,Vec v,void *monctx)
7070: {
7071: TSMonitorLGCtx ctx = (TSMonitorLGCtx) monctx;
7072: PetscReal x = ptime,y;
7074: PetscInt its;
7077: if (n < 0) return(0); /* -1 indicates interpolated solution */
7078: if (!n) {
7079: PetscDrawAxis axis;
7080: PetscDrawLGGetAxis(ctx->lg,&axis);
7081: PetscDrawAxisSetLabels(axis,"Linear iterations as function of time","Time","KSP Iterations");
7082: PetscDrawLGReset(ctx->lg);
7083: ctx->ksp_its = 0;
7084: }
7085: TSGetKSPIterations(ts,&its);
7086: y = its - ctx->ksp_its;
7087: PetscDrawLGAddPoint(ctx->lg,&x,&y);
7088: if (((ctx->howoften > 0) && (!(n % ctx->howoften)) && (n > -1)) || ((ctx->howoften == -1) && (n == -1))) {
7089: PetscDrawLGDraw(ctx->lg);
7090: PetscDrawLGSave(ctx->lg);
7091: }
7092: ctx->ksp_its = its;
7093: return(0);
7094: }
7096: /*@
7097: TSComputeLinearStability - computes the linear stability function at a point
7099: Collective on TS
7101: Input Parameters:
7102: + ts - the TS context
7103: - xr,xi - real and imaginary part of input arguments
7105: Output Parameters:
7106: . yr,yi - real and imaginary part of function value
7108: Level: developer
7110: .seealso: TSSetRHSFunction(), TSComputeIFunction()
7111: @*/
7112: PetscErrorCode TSComputeLinearStability(TS ts,PetscReal xr,PetscReal xi,PetscReal *yr,PetscReal *yi)
7113: {
7118: if (!ts->ops->linearstability) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"Linearized stability function not provided for this method");
7119: (*ts->ops->linearstability)(ts,xr,xi,yr,yi);
7120: return(0);
7121: }
7123: /* ------------------------------------------------------------------------*/
7124: /*@C
7125: TSMonitorEnvelopeCtxCreate - Creates a context for use with TSMonitorEnvelope()
7127: Collective on TS
7129: Input Parameters:
7130: . ts - the ODE solver object
7132: Output Parameter:
7133: . ctx - the context
7135: Level: intermediate
7137: .seealso: TSMonitorLGTimeStep(), TSMonitorSet(), TSMonitorLGSolution(), TSMonitorLGError()
7139: @*/
7140: PetscErrorCode TSMonitorEnvelopeCtxCreate(TS ts,TSMonitorEnvelopeCtx *ctx)
7141: {
7145: PetscNew(ctx);
7146: return(0);
7147: }
7149: /*@C
7150: TSMonitorEnvelope - Monitors the maximum and minimum value of each component of the solution
7152: Collective on TS
7154: Input Parameters:
7155: + ts - the TS context
7156: . step - current time-step
7157: . ptime - current time
7158: . u - current solution
7159: - dctx - the envelope context
7161: Options Database:
7162: . -ts_monitor_envelope
7164: Level: intermediate
7166: Notes:
7167: after a solve you can use TSMonitorEnvelopeGetBounds() to access the envelope
7169: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorEnvelopeGetBounds(), TSMonitorEnvelopeCtxCreate()
7170: @*/
7171: PetscErrorCode TSMonitorEnvelope(TS ts,PetscInt step,PetscReal ptime,Vec u,void *dctx)
7172: {
7173: PetscErrorCode ierr;
7174: TSMonitorEnvelopeCtx ctx = (TSMonitorEnvelopeCtx)dctx;
7177: if (!ctx->max) {
7178: VecDuplicate(u,&ctx->max);
7179: VecDuplicate(u,&ctx->min);
7180: VecCopy(u,ctx->max);
7181: VecCopy(u,ctx->min);
7182: } else {
7183: VecPointwiseMax(ctx->max,u,ctx->max);
7184: VecPointwiseMin(ctx->min,u,ctx->min);
7185: }
7186: return(0);
7187: }
7189: /*@C
7190: TSMonitorEnvelopeGetBounds - Gets the bounds for the components of the solution
7192: Collective on TS
7194: Input Parameter:
7195: . ts - the TS context
7197: Output Parameter:
7198: + max - the maximum values
7199: - min - the minimum values
7201: Notes:
7202: If the TS does not have a TSMonitorEnvelopeCtx associated with it then this function is ignored
7204: Level: intermediate
7206: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorLGSetDisplayVariables()
7207: @*/
7208: PetscErrorCode TSMonitorEnvelopeGetBounds(TS ts,Vec *max,Vec *min)
7209: {
7210: PetscInt i;
7213: if (max) *max = NULL;
7214: if (min) *min = NULL;
7215: for (i=0; i<ts->numbermonitors; i++) {
7216: if (ts->monitor[i] == TSMonitorEnvelope) {
7217: TSMonitorEnvelopeCtx ctx = (TSMonitorEnvelopeCtx) ts->monitorcontext[i];
7218: if (max) *max = ctx->max;
7219: if (min) *min = ctx->min;
7220: break;
7221: }
7222: }
7223: return(0);
7224: }
7226: /*@C
7227: TSMonitorEnvelopeCtxDestroy - Destroys a context that was created with TSMonitorEnvelopeCtxCreate().
7229: Collective on TSMonitorEnvelopeCtx
7231: Input Parameter:
7232: . ctx - the monitor context
7234: Level: intermediate
7236: .seealso: TSMonitorLGCtxCreate(), TSMonitorSet(), TSMonitorLGTimeStep()
7237: @*/
7238: PetscErrorCode TSMonitorEnvelopeCtxDestroy(TSMonitorEnvelopeCtx *ctx)
7239: {
7243: VecDestroy(&(*ctx)->min);
7244: VecDestroy(&(*ctx)->max);
7245: PetscFree(*ctx);
7246: return(0);
7247: }
7249: /*@
7250: TSRestartStep - Flags the solver to restart the next step
7252: Collective on TS
7254: Input Parameter:
7255: . ts - the TS context obtained from TSCreate()
7257: Level: advanced
7259: Notes:
7260: Multistep methods like BDF or Runge-Kutta methods with FSAL property require restarting the solver in the event of
7261: discontinuities. These discontinuities may be introduced as a consequence of explicitly modifications to the solution
7262: vector (which PETSc attempts to detect and handle) or problem coefficients (which PETSc is not able to detect). For
7263: the sake of correctness and maximum safety, users are expected to call TSRestart() whenever they introduce
7264: discontinuities in callback routines (e.g. prestep and poststep routines, or implicit/rhs function routines with
7265: discontinuous source terms).
7267: .seealso: TSSolve(), TSSetPreStep(), TSSetPostStep()
7268: @*/
7269: PetscErrorCode TSRestartStep(TS ts)
7270: {
7273: ts->steprestart = PETSC_TRUE;
7274: return(0);
7275: }
7277: /*@
7278: TSRollBack - Rolls back one time step
7280: Collective on TS
7282: Input Parameter:
7283: . ts - the TS context obtained from TSCreate()
7285: Level: advanced
7287: .seealso: TSCreate(), TSSetUp(), TSDestroy(), TSSolve(), TSSetPreStep(), TSSetPreStage(), TSInterpolate()
7288: @*/
7289: PetscErrorCode TSRollBack(TS ts)
7290: {
7295: if (ts->steprollback) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_ARG_WRONGSTATE,"TSRollBack already called");
7296: if (!ts->ops->rollback) SETERRQ1(PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"TSRollBack not implemented for type '%s'",((PetscObject)ts)->type_name);
7297: (*ts->ops->rollback)(ts);
7298: ts->time_step = ts->ptime - ts->ptime_prev;
7299: ts->ptime = ts->ptime_prev;
7300: ts->ptime_prev = ts->ptime_prev_rollback;
7301: ts->steps--;
7302: ts->steprollback = PETSC_TRUE;
7303: return(0);
7304: }
7306: /*@
7307: TSGetStages - Get the number of stages and stage values
7309: Input Parameter:
7310: . ts - the TS context obtained from TSCreate()
7312: Output Parameters:
7313: + ns - the number of stages
7314: - Y - the current stage vectors
7316: Level: advanced
7318: Notes: Both ns and Y can be NULL.
7320: .seealso: TSCreate()
7321: @*/
7322: PetscErrorCode TSGetStages(TS ts,PetscInt *ns,Vec **Y)
7323: {
7330: if (!ts->ops->getstages) {
7331: if (ns) *ns = 0;
7332: if (Y) *Y = NULL;
7333: } else {
7334: (*ts->ops->getstages)(ts,ns,Y);
7335: }
7336: return(0);
7337: }
7339: /*@C
7340: TSComputeIJacobianDefaultColor - Computes the Jacobian using finite differences and coloring to exploit matrix sparsity.
7342: Collective on SNES
7344: Input Parameters:
7345: + ts - the TS context
7346: . t - current timestep
7347: . U - state vector
7348: . Udot - time derivative of state vector
7349: . shift - shift to apply, see note below
7350: - ctx - an optional user context
7352: Output Parameters:
7353: + J - Jacobian matrix (not altered in this routine)
7354: - B - newly computed Jacobian matrix to use with preconditioner (generally the same as J)
7356: Level: intermediate
7358: Notes:
7359: If F(t,U,Udot)=0 is the DAE, the required Jacobian is
7361: dF/dU + shift*dF/dUdot
7363: Most users should not need to explicitly call this routine, as it
7364: is used internally within the nonlinear solvers.
7366: This will first try to get the coloring from the DM. If the DM type has no coloring
7367: routine, then it will try to get the coloring from the matrix. This requires that the
7368: matrix have nonzero entries precomputed.
7370: .seealso: TSSetIJacobian(), MatFDColoringCreate(), MatFDColoringSetFunction()
7371: @*/
7372: PetscErrorCode TSComputeIJacobianDefaultColor(TS ts,PetscReal t,Vec U,Vec Udot,PetscReal shift,Mat J,Mat B,void *ctx)
7373: {
7374: SNES snes;
7375: MatFDColoring color;
7376: PetscBool hascolor, matcolor = PETSC_FALSE;
7380: PetscOptionsGetBool(((PetscObject)ts)->options,((PetscObject) ts)->prefix, "-ts_fd_color_use_mat", &matcolor, NULL);
7381: PetscObjectQuery((PetscObject) B, "TSMatFDColoring", (PetscObject *) &color);
7382: if (!color) {
7383: DM dm;
7384: ISColoring iscoloring;
7386: TSGetDM(ts, &dm);
7387: DMHasColoring(dm, &hascolor);
7388: if (hascolor && !matcolor) {
7389: DMCreateColoring(dm, IS_COLORING_GLOBAL, &iscoloring);
7390: MatFDColoringCreate(B, iscoloring, &color);
7391: MatFDColoringSetFunction(color, (PetscErrorCode (*)(void)) SNESTSFormFunction, (void *) ts);
7392: MatFDColoringSetFromOptions(color);
7393: MatFDColoringSetUp(B, iscoloring, color);
7394: ISColoringDestroy(&iscoloring);
7395: } else {
7396: MatColoring mc;
7398: MatColoringCreate(B, &mc);
7399: MatColoringSetDistance(mc, 2);
7400: MatColoringSetType(mc, MATCOLORINGSL);
7401: MatColoringSetFromOptions(mc);
7402: MatColoringApply(mc, &iscoloring);
7403: MatColoringDestroy(&mc);
7404: MatFDColoringCreate(B, iscoloring, &color);
7405: MatFDColoringSetFunction(color, (PetscErrorCode (*)(void)) SNESTSFormFunction, (void *) ts);
7406: MatFDColoringSetFromOptions(color);
7407: MatFDColoringSetUp(B, iscoloring, color);
7408: ISColoringDestroy(&iscoloring);
7409: }
7410: PetscObjectCompose((PetscObject) B, "TSMatFDColoring", (PetscObject) color);
7411: PetscObjectDereference((PetscObject) color);
7412: }
7413: TSGetSNES(ts, &snes);
7414: MatFDColoringApply(B, color, U, snes);
7415: if (J != B) {
7416: MatAssemblyBegin(J, MAT_FINAL_ASSEMBLY);
7417: MatAssemblyEnd(J, MAT_FINAL_ASSEMBLY);
7418: }
7419: return(0);
7420: }
7422: /*@
7423: TSSetFunctionDomainError - Set a function that tests if the current state vector is valid
7425: Input Parameters:
7426: + ts - the TS context
7427: - func - function called within TSFunctionDomainError
7429: Calling sequence of func:
7430: $ PetscErrorCode func(TS ts,PetscReal time,Vec state,PetscBool reject)
7432: + ts - the TS context
7433: . time - the current time (of the stage)
7434: . state - the state to check if it is valid
7435: - reject - (output parameter) PETSC_FALSE if the state is acceptable, PETSC_TRUE if not acceptable
7437: Level: intermediate
7439: Notes:
7440: If an implicit ODE solver is being used then, in addition to providing this routine, the
7441: user's code should call SNESSetFunctionDomainError() when domain errors occur during
7442: function evaluations where the functions are provided by TSSetIFunction() or TSSetRHSFunction().
7443: Use TSGetSNES() to obtain the SNES object
7445: Developer Notes:
7446: The naming of this function is inconsistent with the SNESSetFunctionDomainError()
7447: since one takes a function pointer and the other does not.
7449: .seealso: TSAdaptCheckStage(), TSFunctionDomainError(), SNESSetFunctionDomainError(), TSGetSNES()
7450: @*/
7452: PetscErrorCode TSSetFunctionDomainError(TS ts, PetscErrorCode (*func)(TS,PetscReal,Vec,PetscBool*))
7453: {
7456: ts->functiondomainerror = func;
7457: return(0);
7458: }
7460: /*@
7461: TSFunctionDomainError - Checks if the current state is valid
7463: Input Parameters:
7464: + ts - the TS context
7465: . stagetime - time of the simulation
7466: - Y - state vector to check.
7468: Output Parameter:
7469: . accept - Set to PETSC_FALSE if the current state vector is valid.
7471: Note:
7472: This function is called by the TS integration routines and calls the user provided function (set with TSSetFunctionDomainError())
7473: to check if the current state is valid.
7475: Level: developer
7477: .seealso: TSSetFunctionDomainError()
7478: @*/
7479: PetscErrorCode TSFunctionDomainError(TS ts,PetscReal stagetime,Vec Y,PetscBool* accept)
7480: {
7483: *accept = PETSC_TRUE;
7484: if (ts->functiondomainerror) {
7485: PetscStackCallStandard((*ts->functiondomainerror),(ts,stagetime,Y,accept));
7486: }
7487: return(0);
7488: }
7490: /*@C
7491: TSClone - This function clones a time step object.
7493: Collective
7495: Input Parameter:
7496: . tsin - The input TS
7498: Output Parameter:
7499: . tsout - The output TS (cloned)
7501: Notes:
7502: 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.
7504: 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);
7506: Level: developer
7508: .seealso: TSCreate(), TSSetType(), TSSetUp(), TSDestroy(), TSSetProblemType()
7509: @*/
7510: PetscErrorCode TSClone(TS tsin, TS *tsout)
7511: {
7512: TS t;
7514: SNES snes_start;
7515: DM dm;
7516: TSType type;
7520: *tsout = NULL;
7522: PetscHeaderCreate(t, TS_CLASSID, "TS", "Time stepping", "TS", PetscObjectComm((PetscObject)tsin), TSDestroy, TSView);
7524: /* General TS description */
7525: t->numbermonitors = 0;
7526: t->setupcalled = 0;
7527: t->ksp_its = 0;
7528: t->snes_its = 0;
7529: t->nwork = 0;
7530: t->rhsjacobian.time = PETSC_MIN_REAL;
7531: t->rhsjacobian.scale = 1.;
7532: t->ijacobian.shift = 1.;
7534: TSGetSNES(tsin,&snes_start);
7535: TSSetSNES(t,snes_start);
7537: TSGetDM(tsin,&dm);
7538: TSSetDM(t,dm);
7540: t->adapt = tsin->adapt;
7541: PetscObjectReference((PetscObject)t->adapt);
7543: t->trajectory = tsin->trajectory;
7544: PetscObjectReference((PetscObject)t->trajectory);
7546: t->event = tsin->event;
7547: if (t->event) t->event->refct++;
7549: t->problem_type = tsin->problem_type;
7550: t->ptime = tsin->ptime;
7551: t->ptime_prev = tsin->ptime_prev;
7552: t->time_step = tsin->time_step;
7553: t->max_time = tsin->max_time;
7554: t->steps = tsin->steps;
7555: t->max_steps = tsin->max_steps;
7556: t->equation_type = tsin->equation_type;
7557: t->atol = tsin->atol;
7558: t->rtol = tsin->rtol;
7559: t->max_snes_failures = tsin->max_snes_failures;
7560: t->max_reject = tsin->max_reject;
7561: t->errorifstepfailed = tsin->errorifstepfailed;
7563: TSGetType(tsin,&type);
7564: TSSetType(t,type);
7566: t->vec_sol = NULL;
7568: t->cfltime = tsin->cfltime;
7569: t->cfltime_local = tsin->cfltime_local;
7570: t->exact_final_time = tsin->exact_final_time;
7572: PetscMemcpy(t->ops,tsin->ops,sizeof(struct _TSOps));
7574: if (((PetscObject)tsin)->fortran_func_pointers) {
7575: PetscInt i;
7576: PetscMalloc((10)*sizeof(void(*)(void)),&((PetscObject)t)->fortran_func_pointers);
7577: for (i=0; i<10; i++) {
7578: ((PetscObject)t)->fortran_func_pointers[i] = ((PetscObject)tsin)->fortran_func_pointers[i];
7579: }
7580: }
7581: *tsout = t;
7582: return(0);
7583: }
7585: static PetscErrorCode RHSWrapperFunction_TSRHSJacobianTest(void* ctx,Vec x,Vec y)
7586: {
7588: TS ts = (TS) ctx;
7591: TSComputeRHSFunction(ts,0,x,y);
7592: return(0);
7593: }
7595: /*@
7596: TSRHSJacobianTest - Compares the multiply routine provided to the MATSHELL with differencing on the TS given RHS function.
7598: Logically Collective on TS
7600: Input Parameters:
7601: TS - the time stepping routine
7603: Output Parameter:
7604: . flg - PETSC_TRUE if the multiply is likely correct
7606: Options Database:
7607: . -ts_rhs_jacobian_test_mult -mat_shell_test_mult_view - run the test at each timestep of the integrator
7609: Level: advanced
7611: Notes:
7612: This only works for problems defined only the RHS function and Jacobian NOT IFunction and IJacobian
7614: .seealso: MatCreateShell(), MatShellGetContext(), MatShellGetOperation(), MatShellTestMultTranspose(), TSRHSJacobianTestTranspose()
7615: @*/
7616: PetscErrorCode TSRHSJacobianTest(TS ts,PetscBool *flg)
7617: {
7618: Mat J,B;
7620: TSRHSJacobian func;
7621: void* ctx;
7624: TSGetRHSJacobian(ts,&J,&B,&func,&ctx);
7625: (*func)(ts,0.0,ts->vec_sol,J,B,ctx);
7626: MatShellTestMult(J,RHSWrapperFunction_TSRHSJacobianTest,ts->vec_sol,ts,flg);
7627: return(0);
7628: }
7630: /*@C
7631: TSRHSJacobianTestTranspose - Compares the multiply transpose routine provided to the MATSHELL with differencing on the TS given RHS function.
7633: Logically Collective on TS
7635: Input Parameters:
7636: TS - the time stepping routine
7638: Output Parameter:
7639: . flg - PETSC_TRUE if the multiply is likely correct
7641: Options Database:
7642: . -ts_rhs_jacobian_test_mult_transpose -mat_shell_test_mult_transpose_view - run the test at each timestep of the integrator
7644: Notes:
7645: This only works for problems defined only the RHS function and Jacobian NOT IFunction and IJacobian
7647: Level: advanced
7649: .seealso: MatCreateShell(), MatShellGetContext(), MatShellGetOperation(), MatShellTestMultTranspose(), TSRHSJacobianTest()
7650: @*/
7651: PetscErrorCode TSRHSJacobianTestTranspose(TS ts,PetscBool *flg)
7652: {
7653: Mat J,B;
7655: void *ctx;
7656: TSRHSJacobian func;
7659: TSGetRHSJacobian(ts,&J,&B,&func,&ctx);
7660: (*func)(ts,0.0,ts->vec_sol,J,B,ctx);
7661: MatShellTestMultTranspose(J,RHSWrapperFunction_TSRHSJacobianTest,ts->vec_sol,ts,flg);
7662: return(0);
7663: }
7665: /*@
7666: TSSetUseSplitRHSFunction - Use the split RHSFunction when a multirate method is used.
7668: Logically collective
7670: Input Parameter:
7671: + ts - timestepping context
7672: - use_splitrhsfunction - PETSC_TRUE indicates that the split RHSFunction will be used
7674: Options Database:
7675: . -ts_use_splitrhsfunction - <true,false>
7677: Notes:
7678: This is only useful for multirate methods
7680: Level: intermediate
7682: .seealso: TSGetUseSplitRHSFunction()
7683: @*/
7684: PetscErrorCode TSSetUseSplitRHSFunction(TS ts, PetscBool use_splitrhsfunction)
7685: {
7688: ts->use_splitrhsfunction = use_splitrhsfunction;
7689: return(0);
7690: }
7692: /*@
7693: TSGetUseSplitRHSFunction - Gets whether to use the split RHSFunction when a multirate method is used.
7695: Not collective
7697: Input Parameter:
7698: . ts - timestepping context
7700: Output Parameter:
7701: . use_splitrhsfunction - PETSC_TRUE indicates that the split RHSFunction will be used
7703: Level: intermediate
7705: .seealso: TSSetUseSplitRHSFunction()
7706: @*/
7707: PetscErrorCode TSGetUseSplitRHSFunction(TS ts, PetscBool *use_splitrhsfunction)
7708: {
7711: *use_splitrhsfunction = ts->use_splitrhsfunction;
7712: return(0);
7713: }