Actual source code: ts.c
1: #include <petsc/private/tsimpl.h>
2: #include <petscdmda.h>
3: #include <petscdmshell.h>
4: #include <petscdmplex.h>
5: #include <petscdmswarm.h>
6: #include <petscdraw.h>
7: #include <petscconvest.h>
9: /* Logging support */
10: PetscClassId TS_CLASSID, DMTS_CLASSID;
11: PetscLogEvent TS_Step, TS_PseudoComputeTimeStep, TS_FunctionEval, TS_JacobianEval;
13: const char *const TSExactFinalTimeOptions[] = {"UNSPECIFIED", "STEPOVER", "INTERPOLATE", "MATCHSTEP", "TSExactFinalTimeOption", "TS_EXACTFINALTIME_", NULL};
15: static PetscErrorCode TSAdaptSetDefaultType(TSAdapt adapt, TSAdaptType default_type)
16: {
17: PetscFunctionBegin;
19: PetscAssertPointer(default_type, 2);
20: if (!((PetscObject)adapt)->type_name) PetscCall(TSAdaptSetType(adapt, default_type));
21: PetscFunctionReturn(PETSC_SUCCESS);
22: }
24: /*@
25: TSSetFromOptions - Sets various `TS` parameters from the options database
27: Collective
29: Input Parameter:
30: . ts - the `TS` context obtained from `TSCreate()`
32: Options Database Keys:
33: + -ts_type type - see `TSType`
34: . -ts_save_trajectory (true|false) - checkpoint the solution at each time-step
35: . -ts_max_time time - maximum time to compute to
36: . -ts_time_span t0,...,tf - sets the time span, solutions are computed and stored for each indicated time, init_time and max_time are set
37: . -ts_eval_times t0,...,tn - time points where solutions are computed and stored for each indicated time
38: . -ts_max_steps steps - maximum time-step number to execute until (possibly with nonzero starting value)
39: . -ts_run_steps steps - maximum number of time steps for `TSSolve()` to take on each call
40: . -ts_init_time time - initial time to start computation
41: . -ts_final_time time - final time to compute to (deprecated: use `-ts_max_time`)
42: . -ts_time_step dt - initial time step (only a suggestion, the actual initial time step used differ)
43: . -ts_exact_final_time (stepover,interpolate,matchstep) - whether to stop at the exact given final time and how to compute the solution at that time
44: . -ts_max_snes_failures maxfailures - Maximum number of nonlinear solve failures allowed
45: . -ts_max_step_rejections maxrejects - Maximum number of step rejections before step fails
46: . -ts_error_if_step_fails (true|false) - Error if no step succeeds
47: . -ts_rtol rtol - relative tolerance for local truncation error
48: . -ts_atol atol - Absolute tolerance for local truncation error
49: . -ts_rhs_jacobian_test_mult -mat_shell_test_mult_view - test the Jacobian at each iteration against finite difference with RHS function
50: . -ts_rhs_jacobian_test_mult_transpose (true|false) - test the Jacobian at each iteration against finite difference with RHS function
51: . -ts_adjoint_solve (true|false) - After solving the ODE/DAE solve the adjoint problem (requires `-ts_save_trajectory`)
52: . -ts_fd_color (true|false) - Use finite differences with coloring to compute IJacobian
53: . -ts_monitor - print information at each timestep
54: . -ts_monitor_cancel (true|false) - Cancel all monitors
55: . -ts_monitor_wall_clock_time - Monitor wall-clock time, `KSP` iterations, and `SNES` iterations per step
56: . -ts_monitor_lg_solution - Monitor solution graphically
57: . -ts_monitor_lg_error - Monitor error graphically
58: . -ts_monitor_error - Monitors norm of error
59: . -ts_monitor_lg_timestep - Monitor timestep size graphically
60: . -ts_monitor_lg_timestep_log - Monitor log timestep size graphically
61: . -ts_monitor_lg_snes_iterations - Monitor number nonlinear iterations for each timestep graphically
62: . -ts_monitor_lg_ksp_iterations - Monitor number nonlinear iterations for each timestep graphically
63: . -ts_monitor_sp_eig - Monitor eigenvalues of linearized operator graphically
64: . -ts_monitor_draw_solution - Monitor solution graphically
65: . -ts_monitor_draw_solution_phase xleft,yleft,xright,yright - Monitor solution graphically with phase diagram, requires problem with exactly 2 degrees of freedom
66: . -ts_monitor_draw_error - Monitor error graphically, requires use to have provided TSSetSolutionFunction()
67: . -ts_monitor_solution [ascii binary draw][:filename][:viewerformat] - monitors the solution at each timestep
68: . -ts_monitor_solution_interval interval - output once every interval (default=1) time steps. Use -1 to only output at the end of the simulation
69: . -ts_monitor_solution_skip_initial (true|false) - skip writing of initial condition
70: . -ts_monitor_solution_vtk filename.vts,filename.vtu - Save each time step to a binary file, use filename-%%03" PetscInt_FMT ".vts (filename-%%03" PetscInt_FMT ".vtu)
71: . -ts_monitor_solution_vtk_interval interval - output once every interval (default=1) time steps. Use -1 to only output at the end of the simulation
72: - -ts_monitor_envelope - determine maximum and minimum value of each component of the solution over the solution time
74: Level: beginner
76: Notes:
77: See `SNESSetFromOptions()` and `KSPSetFromOptions()` for how to control the nonlinear and linear solves used by the time-stepper.
79: Certain `SNES` options get reset for each new nonlinear solver, for example `-snes_lag_jacobian its` and `-snes_lag_preconditioner its`, in order
80: to retain them over the multiple nonlinear solves that `TS` uses you must also provide `-snes_lag_jacobian_persists true` and
81: `-snes_lag_preconditioner_persists true`
83: Developer Notes:
84: We should unify all the -ts_monitor options in the way that -xxx_view has been unified
86: .seealso: [](ch_ts), `TS`, `TSGetType()`
87: @*/
88: PetscErrorCode TSSetFromOptions(TS ts)
89: {
90: PetscBool opt, flg, tflg;
91: char monfilename[PETSC_MAX_PATH_LEN];
92: PetscReal time_step, eval_times[100] = {0};
93: PetscInt num_eval_times = PETSC_STATIC_ARRAY_LENGTH(eval_times);
94: TSExactFinalTimeOption eftopt;
95: char dir[16];
96: TSIFunctionFn *ifun;
97: const char *defaultType;
98: char typeName[256];
100: PetscFunctionBegin;
103: PetscCall(TSRegisterAll());
104: PetscCall(TSGetIFunction(ts, NULL, &ifun, NULL));
106: PetscObjectOptionsBegin((PetscObject)ts);
107: if (((PetscObject)ts)->type_name) defaultType = ((PetscObject)ts)->type_name;
108: else defaultType = ifun ? TSBEULER : TSEULER;
109: PetscCall(PetscOptionsFList("-ts_type", "TS method", "TSSetType", TSList, defaultType, typeName, sizeof(typeName), &opt));
110: if (opt) PetscCall(TSSetType(ts, typeName));
111: else PetscCall(TSSetType(ts, defaultType));
113: /* Handle generic TS options */
114: PetscCall(PetscOptionsDeprecated("-ts_final_time", "-ts_max_time", "3.10", NULL));
115: PetscCall(PetscOptionsReal("-ts_max_time", "Maximum time to run to", "TSSetMaxTime", ts->max_time, &ts->max_time, NULL));
116: PetscCall(PetscOptionsRealArray("-ts_time_span", "Time span", "TSSetTimeSpan", eval_times, &num_eval_times, &flg));
117: if (flg) PetscCall(TSSetTimeSpan(ts, num_eval_times, eval_times));
118: num_eval_times = PETSC_STATIC_ARRAY_LENGTH(eval_times);
119: PetscCall(PetscOptionsRealArray("-ts_eval_times", "Evaluation time points", "TSSetEvaluationTimes", eval_times, &num_eval_times, &opt));
120: PetscCheck(flg != opt || (!flg && !opt), PetscObjectComm((PetscObject)ts), PETSC_ERR_ARG_WRONG, "May not provide -ts_time_span and -ts_eval_times simultaneously");
121: if (opt) PetscCall(TSSetEvaluationTimes(ts, num_eval_times, eval_times));
122: PetscCall(PetscOptionsInt("-ts_max_steps", "Maximum time step number to execute to (possibly with non-zero starting value)", "TSSetMaxSteps", ts->max_steps, &ts->max_steps, NULL));
123: PetscCall(PetscOptionsInt("-ts_run_steps", "Maximum number of time steps to take on each call to TSSolve()", "TSSetRunSteps", ts->run_steps, &ts->run_steps, NULL));
124: PetscCall(PetscOptionsReal("-ts_init_time", "Initial time", "TSSetTime", ts->ptime, &ts->ptime, NULL));
125: PetscCall(PetscOptionsDeprecated("-ts_dt", "-ts_time_step", "3.25", NULL));
126: PetscCall(PetscOptionsReal("-ts_time_step", "Initial time step", "TSSetTimeStep", ts->time_step, &time_step, &flg));
127: if (flg) PetscCall(TSSetTimeStep(ts, time_step));
128: PetscCall(PetscOptionsEnum("-ts_exact_final_time", "Option for handling of final time step", "TSSetExactFinalTime", TSExactFinalTimeOptions, (PetscEnum)ts->exact_final_time, (PetscEnum *)&eftopt, &flg));
129: if (flg) PetscCall(TSSetExactFinalTime(ts, eftopt));
130: PetscCall(PetscOptionsInt("-ts_max_snes_failures", "Maximum number of nonlinear solve failures", "TSSetMaxSNESFailures", ts->max_snes_failures, &ts->max_snes_failures, &flg));
131: if (flg) PetscCall(TSSetMaxSNESFailures(ts, ts->max_snes_failures));
132: PetscCall(PetscOptionsDeprecated("-ts_max_reject", "-ts_max_step_rejections", "3.25", NULL));
133: PetscCall(PetscOptionsInt("-ts_max_step_rejections", "Maximum number of step rejections before step fails", "TSSetMaxStepRejections", ts->max_reject, &ts->max_reject, &flg));
134: if (flg) PetscCall(TSSetMaxStepRejections(ts, ts->max_reject));
135: PetscCall(PetscOptionsBool("-ts_error_if_step_fails", "Error if no step succeeds", "TSSetErrorIfStepFails", ts->errorifstepfailed, &ts->errorifstepfailed, NULL));
136: PetscCall(PetscOptionsBoundedReal("-ts_rtol", "Relative tolerance for local truncation error", "TSSetTolerances", ts->rtol, &ts->rtol, NULL, 0));
137: PetscCall(PetscOptionsBoundedReal("-ts_atol", "Absolute tolerance for local truncation error", "TSSetTolerances", ts->atol, &ts->atol, NULL, 0));
139: PetscCall(PetscOptionsBool("-ts_rhs_jacobian_test_mult", "Test the RHS Jacobian for consistency with RHS at each solve ", "None", ts->testjacobian, &ts->testjacobian, NULL));
140: PetscCall(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));
141: PetscCall(PetscOptionsBool("-ts_use_splitrhsfunction", "Use the split RHS function for multirate solvers ", "TSSetUseSplitRHSFunction", ts->use_splitrhsfunction, &ts->use_splitrhsfunction, NULL));
142: #if PetscDefined(HAVE_SAWS)
143: {
144: PetscBool set;
145: flg = PETSC_FALSE;
146: PetscCall(PetscOptionsBool("-ts_saws_block", "Block for SAWs memory snooper at end of TSSolve", "PetscObjectSAWsBlock", ((PetscObject)ts)->amspublishblock, &flg, &set));
147: if (set) PetscCall(PetscObjectSAWsSetBlock((PetscObject)ts, flg));
148: }
149: #endif
151: /* Monitor options */
152: PetscCall(PetscOptionsDeprecated("-ts_monitor_frequency", "-ts_dmswarm_monitor_moments_interval", "3.24", "Retired in favor of monitor-specific intervals (ts_dmswarm_monitor_moments was the only monitor to use ts_monitor_frequency)"));
153: PetscCall(TSMonitorSetFromOptions(ts, "-ts_monitor", "Monitor time and timestep size", "TSMonitorDefault", TSMonitorDefault, NULL));
154: PetscCall(TSMonitorSetFromOptions(ts, "-ts_monitor_wall_clock_time", "Monitor wall-clock time, KSP iterations, and SNES iterations per step", "TSMonitorWallClockTime", TSMonitorWallClockTime, TSMonitorWallClockTimeSetUp));
155: PetscCall(TSMonitorSetFromOptions(ts, "-ts_monitor_extreme", "Monitor extreme values of the solution", "TSMonitorExtreme", TSMonitorExtreme, NULL));
156: PetscCall(TSMonitorSetFromOptions(ts, "-ts_monitor_solution", "View the solution at each timestep", "TSMonitorSolution", TSMonitorSolution, TSMonitorSolutionSetup));
157: PetscCall(TSMonitorSetFromOptions(ts, "-ts_dmswarm_monitor_moments", "Monitor moments of particle distribution", "TSDMSwarmMonitorMoments", TSDMSwarmMonitorMoments, NULL));
158: PetscCall(PetscOptionsString("-ts_monitor_python", "Use Python function", "TSMonitorSet", NULL, monfilename, sizeof(monfilename), &flg));
159: if (flg) PetscCall(PetscPythonMonitorSet((PetscObject)ts, monfilename));
161: PetscCall(PetscOptionsName("-ts_monitor_lg_solution", "Monitor solution graphically", "TSMonitorLGSolution", &opt));
162: if (opt) {
163: PetscInt howoften = 1;
164: DM dm;
165: PetscBool net;
167: PetscCall(PetscOptionsInt("-ts_monitor_lg_solution", "Monitor solution graphically", "TSMonitorLGSolution", howoften, &howoften, NULL));
168: PetscCall(TSGetDM(ts, &dm));
169: PetscCall(PetscObjectTypeCompare((PetscObject)dm, DMNETWORK, &net));
170: if (net) {
171: TSMonitorLGCtxNetwork ctx;
172: PetscCall(TSMonitorLGCtxNetworkCreate(ts, NULL, NULL, PETSC_DECIDE, PETSC_DECIDE, 600, 400, howoften, &ctx));
173: PetscCall(TSMonitorSet(ts, TSMonitorLGCtxNetworkSolution, ctx, (PetscCtxDestroyFn *)TSMonitorLGCtxNetworkDestroy));
174: PetscCall(PetscOptionsBool("-ts_monitor_lg_solution_semilogy", "Plot the solution with a semi-log axis", "", ctx->semilogy, &ctx->semilogy, NULL));
175: } else {
176: TSMonitorLGCtx ctx;
177: PetscCall(TSMonitorLGCtxCreate(PETSC_COMM_SELF, NULL, NULL, PETSC_DECIDE, PETSC_DECIDE, 400, 300, howoften, &ctx));
178: PetscCall(TSMonitorSet(ts, TSMonitorLGSolution, ctx, (PetscCtxDestroyFn *)TSMonitorLGCtxDestroy));
179: }
180: }
182: PetscCall(PetscOptionsName("-ts_monitor_lg_error", "Monitor error graphically", "TSMonitorLGError", &opt));
183: if (opt) {
184: TSMonitorLGCtx ctx;
185: PetscInt howoften = 1;
187: PetscCall(PetscOptionsInt("-ts_monitor_lg_error", "Monitor error graphically", "TSMonitorLGError", howoften, &howoften, NULL));
188: PetscCall(TSMonitorLGCtxCreate(PETSC_COMM_SELF, NULL, NULL, PETSC_DECIDE, PETSC_DECIDE, 400, 300, howoften, &ctx));
189: PetscCall(TSMonitorSet(ts, TSMonitorLGError, ctx, (PetscCtxDestroyFn *)TSMonitorLGCtxDestroy));
190: }
191: PetscCall(TSMonitorSetFromOptions(ts, "-ts_monitor_error", "View the error at each timestep", "TSMonitorError", TSMonitorError, NULL));
193: PetscCall(PetscOptionsName("-ts_monitor_lg_timestep", "Monitor timestep size graphically", "TSMonitorLGTimeStep", &opt));
194: if (opt) {
195: TSMonitorLGCtx ctx;
196: PetscInt howoften = 1;
198: PetscCall(PetscOptionsInt("-ts_monitor_lg_timestep", "Monitor timestep size graphically", "TSMonitorLGTimeStep", howoften, &howoften, NULL));
199: PetscCall(TSMonitorLGCtxCreate(PetscObjectComm((PetscObject)ts), NULL, NULL, PETSC_DECIDE, PETSC_DECIDE, 400, 300, howoften, &ctx));
200: PetscCall(TSMonitorSet(ts, TSMonitorLGTimeStep, ctx, (PetscCtxDestroyFn *)TSMonitorLGCtxDestroy));
201: }
202: PetscCall(PetscOptionsName("-ts_monitor_lg_timestep_log", "Monitor log timestep size graphically", "TSMonitorLGTimeStep", &opt));
203: if (opt) {
204: TSMonitorLGCtx ctx;
205: PetscInt howoften = 1;
207: PetscCall(PetscOptionsInt("-ts_monitor_lg_timestep_log", "Monitor log timestep size graphically", "TSMonitorLGTimeStep", howoften, &howoften, NULL));
208: PetscCall(TSMonitorLGCtxCreate(PetscObjectComm((PetscObject)ts), NULL, NULL, PETSC_DECIDE, PETSC_DECIDE, 400, 300, howoften, &ctx));
209: PetscCall(TSMonitorSet(ts, TSMonitorLGTimeStep, ctx, (PetscCtxDestroyFn *)TSMonitorLGCtxDestroy));
210: ctx->semilogy = PETSC_TRUE;
211: }
213: PetscCall(PetscOptionsName("-ts_monitor_lg_snes_iterations", "Monitor number nonlinear iterations for each timestep graphically", "TSMonitorLGSNESIterations", &opt));
214: if (opt) {
215: TSMonitorLGCtx ctx;
216: PetscInt howoften = 1;
218: PetscCall(PetscOptionsInt("-ts_monitor_lg_snes_iterations", "Monitor number nonlinear iterations for each timestep graphically", "TSMonitorLGSNESIterations", howoften, &howoften, NULL));
219: PetscCall(TSMonitorLGCtxCreate(PetscObjectComm((PetscObject)ts), NULL, NULL, PETSC_DECIDE, PETSC_DECIDE, 400, 300, howoften, &ctx));
220: PetscCall(TSMonitorSet(ts, TSMonitorLGSNESIterations, ctx, (PetscCtxDestroyFn *)TSMonitorLGCtxDestroy));
221: }
222: PetscCall(PetscOptionsName("-ts_monitor_lg_ksp_iterations", "Monitor number nonlinear iterations for each timestep graphically", "TSMonitorLGKSPIterations", &opt));
223: if (opt) {
224: TSMonitorLGCtx ctx;
225: PetscInt howoften = 1;
227: PetscCall(PetscOptionsInt("-ts_monitor_lg_ksp_iterations", "Monitor number nonlinear iterations for each timestep graphically", "TSMonitorLGKSPIterations", howoften, &howoften, NULL));
228: PetscCall(TSMonitorLGCtxCreate(PetscObjectComm((PetscObject)ts), NULL, NULL, PETSC_DECIDE, PETSC_DECIDE, 400, 300, howoften, &ctx));
229: PetscCall(TSMonitorSet(ts, TSMonitorLGKSPIterations, ctx, (PetscCtxDestroyFn *)TSMonitorLGCtxDestroy));
230: }
231: PetscCall(PetscOptionsName("-ts_monitor_sp_eig", "Monitor eigenvalues of linearized operator graphically", "TSMonitorSPEig", &opt));
232: if (opt) {
233: TSMonitorSPEigCtx ctx;
234: PetscInt howoften = 1;
236: PetscCall(PetscOptionsInt("-ts_monitor_sp_eig", "Monitor eigenvalues of linearized operator graphically", "TSMonitorSPEig", howoften, &howoften, NULL));
237: PetscCall(TSMonitorSPEigCtxCreate(PETSC_COMM_SELF, NULL, NULL, PETSC_DECIDE, PETSC_DECIDE, 300, 300, howoften, &ctx));
238: PetscCall(TSMonitorSet(ts, TSMonitorSPEig, ctx, (PetscCtxDestroyFn *)TSMonitorSPEigCtxDestroy));
239: }
240: PetscCall(PetscOptionsName("-ts_monitor_sp_swarm", "Display particle phase space from the DMSwarm", "TSMonitorSPSwarm", &opt));
241: if (opt) {
242: TSMonitorSPCtx ctx;
243: PetscInt howoften = 1, retain = 0;
244: PetscBool phase = PETSC_TRUE, create = PETSC_TRUE, multispecies = PETSC_FALSE;
246: for (PetscInt i = 0; i < ts->numbermonitors; ++i)
247: if (ts->monitor[i] == TSMonitorSPSwarmSolution) {
248: create = PETSC_FALSE;
249: break;
250: }
251: if (create) {
252: PetscCall(PetscOptionsInt("-ts_monitor_sp_swarm", "Display particles phase space from the DMSwarm", "TSMonitorSPSwarm", howoften, &howoften, NULL));
253: PetscCall(PetscOptionsInt("-ts_monitor_sp_swarm_retain", "Retain n points plotted to show trajectory, -1 for all points", "TSMonitorSPSwarm", retain, &retain, NULL));
254: PetscCall(PetscOptionsBool("-ts_monitor_sp_swarm_phase", "Plot in phase space rather than coordinate space", "TSMonitorSPSwarm", phase, &phase, NULL));
255: PetscCall(PetscOptionsBool("-ts_monitor_sp_swarm_multi_species", "Color particles by particle species", "TSMonitorSPSwarm", multispecies, &multispecies, NULL));
256: PetscCall(TSMonitorSPCtxCreate(PetscObjectComm((PetscObject)ts), NULL, NULL, PETSC_DECIDE, PETSC_DECIDE, 300, 300, howoften, retain, phase, multispecies, &ctx));
257: PetscCall(TSMonitorSet(ts, TSMonitorSPSwarmSolution, ctx, (PetscCtxDestroyFn *)TSMonitorSPCtxDestroy));
258: }
259: }
260: PetscCall(PetscOptionsName("-ts_monitor_hg_swarm", "Display particle histogram from the DMSwarm", "TSMonitorHGSwarm", &opt));
261: if (opt) {
262: TSMonitorHGCtx ctx;
263: PetscInt howoften = 1, Ns = 1;
264: PetscBool velocity = PETSC_FALSE, create = PETSC_TRUE;
266: for (PetscInt i = 0; i < ts->numbermonitors; ++i)
267: if (ts->monitor[i] == TSMonitorHGSwarmSolution) {
268: create = PETSC_FALSE;
269: break;
270: }
271: if (create) {
272: DM sw, dm;
273: PetscInt Nc, Nb;
275: PetscCall(TSGetDM(ts, &sw));
276: PetscCall(DMSwarmGetCellDM(sw, &dm));
277: PetscCall(DMPlexGetHeightStratum(dm, 0, NULL, &Nc));
278: Nb = PetscMin(20, PetscMax(10, Nc));
279: PetscCall(PetscOptionsInt("-ts_monitor_hg_swarm", "Display particles histogram from the DMSwarm", "TSMonitorHGSwarm", howoften, &howoften, NULL));
280: PetscCall(PetscOptionsBool("-ts_monitor_hg_swarm_velocity", "Plot in velocity space rather than coordinate space", "TSMonitorHGSwarm", velocity, &velocity, NULL));
281: PetscCall(PetscOptionsInt("-ts_monitor_hg_swarm_species", "Number of species to histogram", "TSMonitorHGSwarm", Ns, &Ns, NULL));
282: PetscCall(PetscOptionsInt("-ts_monitor_hg_swarm_bins", "Number of histogram bins", "TSMonitorHGSwarm", Nb, &Nb, NULL));
283: PetscCall(TSMonitorHGCtxCreate(PetscObjectComm((PetscObject)ts), NULL, NULL, PETSC_DECIDE, PETSC_DECIDE, 300, 300, howoften, Ns, Nb, velocity, &ctx));
284: PetscCall(TSMonitorSet(ts, TSMonitorHGSwarmSolution, ctx, (PetscCtxDestroyFn *)TSMonitorHGCtxDestroy));
285: }
286: }
287: opt = PETSC_FALSE;
288: PetscCall(PetscOptionsName("-ts_monitor_draw_solution", "Monitor solution graphically", "TSMonitorDrawSolution", &opt));
289: if (opt) {
290: TSMonitorDrawCtx ctx;
291: PetscInt howoften = 1;
293: PetscCall(PetscOptionsInt("-ts_monitor_draw_solution", "Monitor solution graphically", "TSMonitorDrawSolution", howoften, &howoften, NULL));
294: PetscCall(TSMonitorDrawCtxCreate(PetscObjectComm((PetscObject)ts), NULL, "Computed Solution", PETSC_DECIDE, PETSC_DECIDE, 300, 300, howoften, &ctx));
295: PetscCall(TSMonitorSet(ts, TSMonitorDrawSolution, ctx, (PetscCtxDestroyFn *)TSMonitorDrawCtxDestroy));
296: }
297: opt = PETSC_FALSE;
298: PetscCall(PetscOptionsName("-ts_monitor_draw_solution_phase", "Monitor solution graphically", "TSMonitorDrawSolutionPhase", &opt));
299: if (opt) {
300: TSMonitorDrawCtx ctx;
301: PetscReal bounds[4];
302: PetscInt n = 4;
303: PetscDraw draw;
304: PetscDrawAxis axis;
306: PetscCall(PetscOptionsRealArray("-ts_monitor_draw_solution_phase", "Monitor solution graphically", "TSMonitorDrawSolutionPhase", bounds, &n, NULL));
307: PetscCheck(n == 4, PetscObjectComm((PetscObject)ts), PETSC_ERR_ARG_WRONG, "Must provide bounding box of phase field");
308: PetscCall(TSMonitorDrawCtxCreate(PetscObjectComm((PetscObject)ts), NULL, NULL, PETSC_DECIDE, PETSC_DECIDE, 300, 300, 1, &ctx));
309: PetscCall(PetscViewerDrawGetDraw(ctx->viewer, 0, &draw));
310: PetscCall(PetscViewerDrawGetDrawAxis(ctx->viewer, 0, &axis));
311: PetscCall(PetscDrawAxisSetLimits(axis, bounds[0], bounds[2], bounds[1], bounds[3]));
312: PetscCall(PetscDrawAxisSetLabels(axis, "Phase Diagram", "Variable 1", "Variable 2"));
313: PetscCall(TSMonitorSet(ts, TSMonitorDrawSolutionPhase, ctx, (PetscCtxDestroyFn *)TSMonitorDrawCtxDestroy));
314: }
315: opt = PETSC_FALSE;
316: PetscCall(PetscOptionsName("-ts_monitor_draw_error", "Monitor error graphically", "TSMonitorDrawError", &opt));
317: if (opt) {
318: TSMonitorDrawCtx ctx;
319: PetscInt howoften = 1;
321: PetscCall(PetscOptionsInt("-ts_monitor_draw_error", "Monitor error graphically", "TSMonitorDrawError", howoften, &howoften, NULL));
322: PetscCall(TSMonitorDrawCtxCreate(PetscObjectComm((PetscObject)ts), NULL, "Error", PETSC_DECIDE, PETSC_DECIDE, 300, 300, howoften, &ctx));
323: PetscCall(TSMonitorSet(ts, TSMonitorDrawError, ctx, (PetscCtxDestroyFn *)TSMonitorDrawCtxDestroy));
324: }
325: opt = PETSC_FALSE;
326: PetscCall(PetscOptionsName("-ts_monitor_draw_solution_function", "Monitor solution provided by TSMonitorSetSolutionFunction() graphically", "TSMonitorDrawSolutionFunction", &opt));
327: if (opt) {
328: TSMonitorDrawCtx ctx;
329: PetscInt howoften = 1;
331: PetscCall(PetscOptionsInt("-ts_monitor_draw_solution_function", "Monitor solution provided by TSMonitorSetSolutionFunction() graphically", "TSMonitorDrawSolutionFunction", howoften, &howoften, NULL));
332: PetscCall(TSMonitorDrawCtxCreate(PetscObjectComm((PetscObject)ts), NULL, "Solution provided by user function", PETSC_DECIDE, PETSC_DECIDE, 300, 300, howoften, &ctx));
333: PetscCall(TSMonitorSet(ts, TSMonitorDrawSolutionFunction, ctx, (PetscCtxDestroyFn *)TSMonitorDrawCtxDestroy));
334: }
336: opt = PETSC_FALSE;
337: PetscCall(PetscOptionsString("-ts_monitor_solution_vtk", "Save each time step to a binary file, use filename-%%03" PetscInt_FMT ".vts", "TSMonitorSolutionVTK", NULL, monfilename, sizeof(monfilename), &flg));
338: if (flg) {
339: TSMonitorVTKCtx ctx;
341: PetscCall(TSMonitorSolutionVTKCtxCreate(monfilename, &ctx));
342: PetscCall(PetscOptionsInt("-ts_monitor_solution_vtk_interval", "Save every interval time step (-1 for last step only)", NULL, ctx->interval, &ctx->interval, NULL));
343: PetscCall(TSMonitorSet(ts, (PetscErrorCode (*)(TS, PetscInt, PetscReal, Vec, PetscCtx))TSMonitorSolutionVTK, ctx, (PetscCtxDestroyFn *)TSMonitorSolutionVTKDestroy));
344: }
346: PetscCall(PetscOptionsString("-ts_monitor_dmda_ray", "Display a ray of the solution", "None", "y=0", dir, sizeof(dir), &flg));
347: if (flg) {
348: TSMonitorDMDARayCtx *rayctx;
349: int ray = 0;
350: DMDirection ddir;
351: DM da;
352: PetscMPIInt rank;
354: PetscCheck(dir[1] == '=', PetscObjectComm((PetscObject)ts), PETSC_ERR_ARG_WRONG, "Unknown ray %s", dir);
355: if (dir[0] == 'x') ddir = DM_X;
356: else if (dir[0] == 'y') ddir = DM_Y;
357: else SETERRQ(PetscObjectComm((PetscObject)ts), PETSC_ERR_ARG_WRONG, "Unknown ray %s", dir);
358: sscanf(dir + 2, "%d", &ray);
360: PetscCall(PetscInfo(ts, "Displaying DMDA ray %c = %d\n", dir[0], ray));
361: PetscCall(PetscNew(&rayctx));
362: PetscCall(TSGetDM(ts, &da));
363: PetscCall(DMDAGetRay(da, ddir, ray, &rayctx->ray, &rayctx->scatter));
364: PetscCallMPI(MPI_Comm_rank(PetscObjectComm((PetscObject)ts), &rank));
365: if (rank == 0) PetscCall(PetscViewerDrawOpen(PETSC_COMM_SELF, NULL, NULL, 0, 0, 600, 300, &rayctx->viewer));
366: rayctx->lgctx = NULL;
367: PetscCall(TSMonitorSet(ts, TSMonitorDMDARay, rayctx, TSMonitorDMDARayDestroy));
368: }
369: PetscCall(PetscOptionsString("-ts_monitor_lg_dmda_ray", "Display a ray of the solution", "None", "x=0", dir, sizeof(dir), &flg));
370: if (flg) {
371: TSMonitorDMDARayCtx *rayctx;
372: int ray = 0;
373: DMDirection ddir;
374: DM da;
375: PetscInt howoften = 1;
377: PetscCheck(dir[1] == '=', PetscObjectComm((PetscObject)ts), PETSC_ERR_ARG_WRONG, "Malformed ray %s", dir);
378: if (dir[0] == 'x') ddir = DM_X;
379: else if (dir[0] == 'y') ddir = DM_Y;
380: else SETERRQ(PetscObjectComm((PetscObject)ts), PETSC_ERR_ARG_WRONG, "Unknown ray direction %s", dir);
381: sscanf(dir + 2, "%d", &ray);
383: PetscCall(PetscInfo(ts, "Displaying LG DMDA ray %c = %d\n", dir[0], ray));
384: PetscCall(PetscNew(&rayctx));
385: PetscCall(TSGetDM(ts, &da));
386: PetscCall(DMDAGetRay(da, ddir, ray, &rayctx->ray, &rayctx->scatter));
387: PetscCall(TSMonitorLGCtxCreate(PETSC_COMM_SELF, NULL, NULL, PETSC_DECIDE, PETSC_DECIDE, 600, 400, howoften, &rayctx->lgctx));
388: PetscCall(TSMonitorSet(ts, TSMonitorLGDMDARay, rayctx, TSMonitorDMDARayDestroy));
389: }
391: PetscCall(PetscOptionsName("-ts_monitor_envelope", "Monitor maximum and minimum value of each component of the solution", "TSMonitorEnvelope", &opt));
392: if (opt) {
393: TSMonitorEnvelopeCtx ctx;
395: PetscCall(TSMonitorEnvelopeCtxCreate(ts, &ctx));
396: PetscCall(TSMonitorSet(ts, TSMonitorEnvelope, ctx, (PetscCtxDestroyFn *)TSMonitorEnvelopeCtxDestroy));
397: }
398: flg = PETSC_FALSE;
399: PetscCall(PetscOptionsBool("-ts_monitor_cancel", "Remove all monitors", "TSMonitorCancel", flg, &flg, &opt));
400: if (opt && flg) PetscCall(TSMonitorCancel(ts));
402: flg = PETSC_FALSE;
403: PetscCall(PetscOptionsBool("-ts_fd_color", "Use finite differences with coloring to compute IJacobian", "TSComputeIJacobianDefaultColor", flg, &flg, NULL));
404: if (flg) {
405: DM dm;
407: PetscCall(TSGetDM(ts, &dm));
408: PetscCall(DMTSUnsetIJacobianContext_Internal(dm));
409: PetscCall(TSSetIJacobian(ts, NULL, NULL, TSComputeIJacobianDefaultColor, NULL));
410: PetscCall(PetscInfo(ts, "Setting default finite difference coloring Jacobian matrix\n"));
411: }
413: /* Handle specific TS options */
414: PetscTryTypeMethod(ts, setfromoptions, PetscOptionsObject);
416: /* Handle TSAdapt options */
417: PetscCall(TSGetAdapt(ts, &ts->adapt));
418: PetscCall(TSAdaptSetDefaultType(ts->adapt, ts->default_adapt_type));
419: PetscCall(TSAdaptSetFromOptions(ts->adapt, PetscOptionsObject));
421: /* TS trajectory must be set after TS, since it may use some TS options above */
422: tflg = ts->trajectory ? PETSC_TRUE : PETSC_FALSE;
423: PetscCall(PetscOptionsBool("-ts_save_trajectory", "Save the solution at each timestep", "TSSetSaveTrajectory", tflg, &tflg, NULL));
424: if (tflg) PetscCall(TSSetSaveTrajectory(ts));
426: PetscCall(TSAdjointSetFromOptions(ts, PetscOptionsObject));
428: /* process any options handlers added with PetscObjectAddOptionsHandler() */
429: PetscCall(PetscObjectProcessOptionsHandlers((PetscObject)ts, PetscOptionsObject));
430: PetscOptionsEnd();
432: if (ts->trajectory) PetscCall(TSTrajectorySetFromOptions(ts->trajectory, ts));
434: /* why do we have to do this here and not during TSSetUp? */
435: PetscCall(TSGetSNES(ts, &ts->snes));
436: if (ts->problem_type == TS_LINEAR) {
437: PetscCall(PetscObjectTypeCompareAny((PetscObject)ts->snes, &flg, SNESKSPONLY, SNESKSPTRANSPOSEONLY, ""));
438: if (!flg) PetscCall(SNESSetType(ts->snes, SNESKSPONLY));
439: }
440: PetscCall(SNESSetFromOptions(ts->snes));
441: PetscFunctionReturn(PETSC_SUCCESS);
442: }
444: /*@
445: TSGetTrajectory - Gets the trajectory from a `TS` if it exists
447: Collective
449: Input Parameter:
450: . ts - the `TS` context obtained from `TSCreate()`
452: Output Parameter:
453: . tr - the `TSTrajectory` object, if it exists
455: Level: advanced
457: Note:
458: This routine should be called after all `TS` options have been set
460: .seealso: [](ch_ts), `TS`, `TSTrajectory`, `TSAdjointSolve()`, `TSTrajectoryCreate()`
461: @*/
462: PetscErrorCode TSGetTrajectory(TS ts, TSTrajectory *tr)
463: {
464: PetscFunctionBegin;
466: *tr = ts->trajectory;
467: PetscFunctionReturn(PETSC_SUCCESS);
468: }
470: /*@
471: TSSetSaveTrajectory - Causes the `TS` to save its solutions as it iterates forward in time in a `TSTrajectory` object
473: Collective
475: Input Parameter:
476: . ts - the `TS` context obtained from `TSCreate()`
478: Options Database Keys:
479: + -ts_save_trajectory (true|false) - saves the trajectory to a file
480: - -ts_trajectory_type (basic|singlefile|memory|visualization) - set trajectory type
482: Level: intermediate
484: Notes:
485: This routine should be called after all `TS` options have been set
487: The `TSTRAJECTORYVISUALIZATION` files can be loaded into Python with $PETSC_DIR/lib/petsc/bin/PetscBinaryIOTrajectory.py and
488: MATLAB with $PETSC_DIR/share/petsc/matlab/PetscReadBinaryTrajectory.m
490: .seealso: [](ch_ts), `TS`, `TSTrajectoryType`, `TSTrajectory`, `TSGetTrajectory()`, `TSAdjointSolve()`
491: @*/
492: PetscErrorCode TSSetSaveTrajectory(TS ts)
493: {
494: PetscFunctionBegin;
496: if (!ts->trajectory) PetscCall(TSTrajectoryCreate(PetscObjectComm((PetscObject)ts), &ts->trajectory));
497: PetscFunctionReturn(PETSC_SUCCESS);
498: }
500: /*@
501: TSResetTrajectory - Destroys and recreates the internal `TSTrajectory` object
503: Collective
505: Input Parameter:
506: . ts - the `TS` context obtained from `TSCreate()`
508: Level: intermediate
510: .seealso: [](ch_ts), `TSTrajectory`, `TSGetTrajectory()`, `TSAdjointSolve()`, `TSRemoveTrajectory()`
511: @*/
512: PetscErrorCode TSResetTrajectory(TS ts)
513: {
514: PetscFunctionBegin;
516: if (ts->trajectory) {
517: PetscCall(TSTrajectoryDestroy(&ts->trajectory));
518: PetscCall(TSTrajectoryCreate(PetscObjectComm((PetscObject)ts), &ts->trajectory));
519: }
520: PetscFunctionReturn(PETSC_SUCCESS);
521: }
523: /*@
524: TSRemoveTrajectory - Destroys and removes the internal `TSTrajectory` object from a `TS`
526: Collective
528: Input Parameter:
529: . ts - the `TS` context obtained from `TSCreate()`
531: Level: intermediate
533: .seealso: [](ch_ts), `TSTrajectory`, `TSResetTrajectory()`, `TSAdjointSolve()`
534: @*/
535: PetscErrorCode TSRemoveTrajectory(TS ts)
536: {
537: PetscFunctionBegin;
539: PetscCall(TSTrajectoryDestroy(&ts->trajectory));
540: PetscFunctionReturn(PETSC_SUCCESS);
541: }
543: /*@
544: TSComputeRHSJacobian - Computes the Jacobian matrix that has been
545: set with `TSSetRHSJacobian()`.
547: Collective
549: Input Parameters:
550: + ts - the `TS` context
551: . t - current timestep
552: - U - input vector
554: Output Parameters:
555: + A - Jacobian matrix
556: - B - optional matrix used to compute the preconditioner, often the same as `A`
558: Level: developer
560: Note:
561: Most users should not need to explicitly call this routine, as it
562: is used internally within the ODE integrators.
564: .seealso: [](ch_ts), `TS`, `TSSetRHSJacobian()`, `KSPSetOperators()`
565: @*/
566: PetscErrorCode TSComputeRHSJacobian(TS ts, PetscReal t, Vec U, Mat A, Mat B)
567: {
568: VecState Ustate;
569: PetscBool same;
570: DM dm;
571: DMTS tsdm;
572: TSRHSJacobianFn *rhsjacobianfunc;
573: void *ctx;
574: TSRHSFunctionFn *rhsfunction;
576: PetscFunctionBegin;
579: PetscCheckSameComm(ts, 1, U, 3);
580: PetscCall(TSGetDM(ts, &dm));
581: PetscCall(DMGetDMTS(dm, &tsdm));
582: PetscCall(DMTSGetRHSFunction(dm, &rhsfunction, NULL));
583: PetscCall(DMTSGetRHSJacobian(dm, &rhsjacobianfunc, &ctx));
584: PetscCall(VecGetState(U, &Ustate));
585: PetscCall(VecStateCompare(Ustate, ts->rhsjacobian.Xstate, &same));
587: if (ts->rhsjacobian.time == t && (ts->problem_type == TS_LINEAR || same) && (rhsfunction != TSComputeRHSFunctionLinear)) PetscFunctionReturn(PETSC_SUCCESS);
589: PetscCheck(ts->rhsjacobian.shift == 0.0 || !ts->rhsjacobian.reuse, PetscObjectComm((PetscObject)ts), PETSC_ERR_USER, "Should not call TSComputeRHSJacobian() on a shifted matrix (shift=%lf) when RHSJacobian is reusable.", (double)ts->rhsjacobian.shift);
590: if (rhsjacobianfunc) {
591: PetscCall(PetscLogEventBegin(TS_JacobianEval, U, ts, A, B));
592: PetscCallBack("TS callback Jacobian", (*rhsjacobianfunc)(ts, t, U, A, B, ctx));
593: ts->rhsjacs++;
594: PetscCall(PetscLogEventEnd(TS_JacobianEval, U, ts, A, B));
595: } else {
596: PetscCall(MatZeroEntries(A));
597: if (B && A != B) PetscCall(MatZeroEntries(B));
598: }
599: ts->rhsjacobian.time = t;
600: ts->rhsjacobian.shift = 0;
601: ts->rhsjacobian.scale = 1.;
602: PetscCall(VecGetState(U, &ts->rhsjacobian.Xstate));
603: PetscFunctionReturn(PETSC_SUCCESS);
604: }
606: /*@
607: TSComputeRHSFunction - Evaluates the right-hand-side function for a `TS`
609: Collective
611: Input Parameters:
612: + ts - the `TS` context
613: . t - current time
614: - U - state vector
616: Output Parameter:
617: . y - right-hand side
619: Level: developer
621: Note:
622: Most users should not need to explicitly call this routine, as it
623: is used internally within the nonlinear solvers.
625: .seealso: [](ch_ts), `TS`, `TSSetRHSFunction()`, `TSComputeIFunction()`
626: @*/
627: PetscErrorCode TSComputeRHSFunction(TS ts, PetscReal t, Vec U, Vec y)
628: {
629: TSRHSFunctionFn *rhsfunction;
630: TSIFunctionFn *ifunction;
631: void *ctx;
632: DM dm;
634: PetscFunctionBegin;
638: PetscCall(TSGetDM(ts, &dm));
639: PetscCall(DMTSGetRHSFunction(dm, &rhsfunction, &ctx));
640: PetscCall(DMTSGetIFunction(dm, &ifunction, NULL));
642: PetscCheck(rhsfunction || ifunction, PetscObjectComm((PetscObject)ts), PETSC_ERR_USER, "Must call TSSetRHSFunction() and / or TSSetIFunction()");
644: if (rhsfunction) {
645: PetscCall(PetscLogEventBegin(TS_FunctionEval, U, ts, y, 0));
646: PetscCall(VecLockReadPush(U));
647: PetscCallBack("TS callback right-hand-side", (*rhsfunction)(ts, t, U, y, ctx));
648: PetscCall(VecLockReadPop(U));
649: ts->rhsfuncs++;
650: PetscCall(PetscLogEventEnd(TS_FunctionEval, U, ts, y, 0));
651: } else PetscCall(VecZeroEntries(y));
652: PetscFunctionReturn(PETSC_SUCCESS);
653: }
655: /*@
656: TSComputeSolutionFunction - Evaluates the solution function.
658: Collective
660: Input Parameters:
661: + ts - the `TS` context
662: - t - current time
664: Output Parameter:
665: . U - the solution
667: Level: developer
669: .seealso: [](ch_ts), `TS`, `TSSetSolutionFunction()`, `TSSetRHSFunction()`, `TSComputeIFunction()`
670: @*/
671: PetscErrorCode TSComputeSolutionFunction(TS ts, PetscReal t, Vec U)
672: {
673: TSSolutionFn *solutionfunction;
674: void *ctx;
675: DM dm;
677: PetscFunctionBegin;
680: PetscCall(TSGetDM(ts, &dm));
681: PetscCall(DMTSGetSolutionFunction(dm, &solutionfunction, &ctx));
682: if (solutionfunction) PetscCallBack("TS callback solution", (*solutionfunction)(ts, t, U, ctx));
683: PetscFunctionReturn(PETSC_SUCCESS);
684: }
685: /*@
686: TSComputeForcingFunction - Evaluates the forcing function.
688: Collective
690: Input Parameters:
691: + ts - the `TS` context
692: - t - current time
694: Output Parameter:
695: . U - the function value
697: Level: developer
699: .seealso: [](ch_ts), `TS`, `TSSetSolutionFunction()`, `TSSetRHSFunction()`, `TSComputeIFunction()`
700: @*/
701: PetscErrorCode TSComputeForcingFunction(TS ts, PetscReal t, Vec U)
702: {
703: void *ctx;
704: DM dm;
705: TSForcingFn *forcing;
707: PetscFunctionBegin;
710: PetscCall(TSGetDM(ts, &dm));
711: PetscCall(DMTSGetForcingFunction(dm, &forcing, &ctx));
713: if (forcing) PetscCallBack("TS callback forcing function", (*forcing)(ts, t, U, ctx));
714: PetscFunctionReturn(PETSC_SUCCESS);
715: }
717: PetscErrorCode TSGetRHSMats_Private(TS ts, Mat *Arhs, Mat *Brhs)
718: {
719: Mat A, B;
720: TSIJacobianFn *ijacobian;
722: PetscFunctionBegin;
723: if (Arhs) *Arhs = NULL;
724: if (Brhs) *Brhs = NULL;
725: PetscCall(TSGetIJacobian(ts, &A, &B, &ijacobian, NULL));
726: if (Arhs) {
727: if (!ts->Arhs) {
728: if (ijacobian) {
729: PetscCall(MatDuplicate(A, MAT_DO_NOT_COPY_VALUES, &ts->Arhs));
730: PetscCall(TSSetMatStructure(ts, SAME_NONZERO_PATTERN));
731: } else {
732: ts->Arhs = A;
733: PetscCall(PetscObjectReference((PetscObject)A));
734: }
735: } else {
736: PetscBool flg;
737: PetscCall(SNESGetUseMatrixFree(ts->snes, NULL, &flg));
738: /* Handle case where user provided only RHSJacobian and used -snes_mf_operator */
739: if (flg && !ijacobian && ts->Arhs == ts->Brhs) {
740: PetscCall(PetscObjectDereference((PetscObject)ts->Arhs));
741: ts->Arhs = A;
742: PetscCall(PetscObjectReference((PetscObject)A));
743: }
744: }
745: *Arhs = ts->Arhs;
746: }
747: if (Brhs) {
748: if (!ts->Brhs) {
749: if (A != B) {
750: if (ijacobian) {
751: PetscCall(MatDuplicate(B, MAT_DO_NOT_COPY_VALUES, &ts->Brhs));
752: } else {
753: ts->Brhs = B;
754: PetscCall(PetscObjectReference((PetscObject)B));
755: }
756: } else {
757: PetscCall(PetscObjectReference((PetscObject)ts->Arhs));
758: ts->Brhs = ts->Arhs;
759: }
760: }
761: *Brhs = ts->Brhs;
762: }
763: PetscFunctionReturn(PETSC_SUCCESS);
764: }
766: /*@
767: TSComputeIFunction - Evaluates the DAE residual written in the implicit form F(t,U,Udot)=0
769: Collective
771: Input Parameters:
772: + ts - the `TS` context
773: . t - current time
774: . U - state vector
775: . Udot - time derivative of state vector
776: - imex - flag indicates if the method is `TSARKIMEX` so that the RHSFunction should be kept separate
778: Output Parameter:
779: . Y - right-hand side
781: Level: developer
783: Note:
784: Most users should not need to explicitly call this routine, as it
785: is used internally within the nonlinear solvers.
787: If the user did not write their equations in implicit form, this
788: function recasts them in implicit form.
790: .seealso: [](ch_ts), `TS`, `TSSetIFunction()`, `TSComputeRHSFunction()`
791: @*/
792: PetscErrorCode TSComputeIFunction(TS ts, PetscReal t, Vec U, Vec Udot, Vec Y, PetscBool imex)
793: {
794: TSIFunctionFn *ifunction;
795: TSRHSFunctionFn *rhsfunction;
796: void *ctx;
797: DM dm;
799: PetscFunctionBegin;
805: PetscCall(TSGetDM(ts, &dm));
806: PetscCall(DMTSGetIFunction(dm, &ifunction, &ctx));
807: PetscCall(DMTSGetRHSFunction(dm, &rhsfunction, NULL));
809: PetscCheck(rhsfunction || ifunction, PetscObjectComm((PetscObject)ts), PETSC_ERR_USER, "Must call TSSetRHSFunction() and / or TSSetIFunction()");
811: PetscCall(PetscLogEventBegin(TS_FunctionEval, U, ts, Udot, Y));
812: if (ifunction) {
813: PetscCallBack("TS callback implicit function", (*ifunction)(ts, t, U, Udot, Y, ctx));
814: ts->ifuncs++;
815: }
816: if (imex) {
817: if (!ifunction) PetscCall(VecCopy(Udot, Y));
818: } else if (rhsfunction) {
819: if (ifunction) {
820: Vec Frhs;
822: PetscCall(DMGetGlobalVector(dm, &Frhs));
823: PetscCall(TSComputeRHSFunction(ts, t, U, Frhs));
824: PetscCall(VecAXPY(Y, -1, Frhs));
825: PetscCall(DMRestoreGlobalVector(dm, &Frhs));
826: } else {
827: PetscCall(TSComputeRHSFunction(ts, t, U, Y));
828: PetscCall(VecAYPX(Y, -1, Udot));
829: }
830: }
831: PetscCall(PetscLogEventEnd(TS_FunctionEval, U, ts, Udot, Y));
832: PetscFunctionReturn(PETSC_SUCCESS);
833: }
835: /*
836: TSRecoverRHSJacobian - Recover the Jacobian matrix so that one can call `TSComputeRHSJacobian()` on it.
838: Note:
839: This routine is needed when one switches from `TSComputeIJacobian()` to `TSComputeRHSJacobian()` because the Jacobian matrix may be shifted or scaled in `TSComputeIJacobian()`.
841: */
842: static PetscErrorCode TSRecoverRHSJacobian(TS ts, Mat A, Mat B)
843: {
844: PetscFunctionBegin;
846: PetscCheck(A == ts->Arhs, PetscObjectComm((PetscObject)ts), PETSC_ERR_SUP, "Invalid Amat");
847: PetscCheck(B == ts->Brhs, PetscObjectComm((PetscObject)ts), PETSC_ERR_SUP, "Invalid Bmat");
849: if (ts->rhsjacobian.shift) PetscCall(MatShift(A, -ts->rhsjacobian.shift));
850: if (ts->rhsjacobian.scale == -1.) PetscCall(MatScale(A, -1));
851: if (B && B == ts->Brhs && A != B) {
852: if (ts->rhsjacobian.shift) PetscCall(MatShift(B, -ts->rhsjacobian.shift));
853: if (ts->rhsjacobian.scale == -1.) PetscCall(MatScale(B, -1));
854: }
855: ts->rhsjacobian.shift = 0;
856: ts->rhsjacobian.scale = 1.;
857: PetscFunctionReturn(PETSC_SUCCESS);
858: }
860: /*
861: TSComputeIJacobian_Internal - Evaluates the Jacobian of the DAE
863: Collective
865: Input Parameters:
866: + ts - the `TS` context
867: . ijacobian - function to compute LHS Jacobian
868: . rhsjacobian - function to compute RHS Jacobian
869: . ctx - user context for Jacobian functions
870: . t - current timestep
871: . U - state vector
872: . Udot - time derivative of state vector
873: . shift - shift to apply, see note below
874: - imex - flag indicates if the method is `TSARKIMEX` so that the RHSJacobian should be kept separate
876: Output Parameters:
877: + A - Jacobian matrix
878: - B - matrix from which the preconditioner is constructed; often the same as `A`
880: Level: developer
882: Notes:
883: This function exists so that a user can assemble the Jacobian pieces with functions not stores in the `DMTS`. This was necessary in `TSDISCGRAD` since two different representations of the formulation can be stored.
885: If $F(t,U,\dot{U})=0$ is the DAE, the required Jacobian is
886: .vb
887: dF/dU + shift*dF/dUdot
888: .ve
890: .seealso: [](ch_ts), `TS`, `TSSetIJacobian()`
891: */
892: PetscErrorCode TSComputeIJacobian_Internal(TS ts, TSIJacobianFn *ijacobian, TSRHSJacobianFn *rhsjacobian, void *ctx, PetscReal t, Vec U, Vec Udot, PetscReal shift, Mat A, Mat B, PetscBool imex)
893: {
894: PetscFunctionBegin;
895: PetscCheck(rhsjacobian || ijacobian, PetscObjectComm((PetscObject)ts), PETSC_ERR_USER, "Must call TSSetRHSJacobian() and / or TSSetIJacobian()");
897: PetscCall(PetscLogEventBegin(TS_JacobianEval, U, ts, A, B));
898: if (ijacobian) {
899: PetscCallBack("TS callback implicit Jacobian", (*ijacobian)(ts, t, U, Udot, shift, A, B, ctx));
900: ts->ijacs++;
901: }
902: if (imex) {
903: if (!ijacobian) { /* system was written as Udot = G(t,U) */
904: PetscBool assembled;
905: if (rhsjacobian) {
906: Mat Arhs = NULL;
907: PetscCall(TSGetRHSMats_Private(ts, &Arhs, NULL));
908: if (A == Arhs) {
909: PetscCheck(rhsjacobian != TSComputeRHSJacobianConstant, 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 */
910: ts->rhsjacobian.time = PETSC_MIN_REAL;
911: }
912: }
913: PetscCall(MatZeroEntries(A));
914: PetscCall(MatAssembled(A, &assembled));
915: if (!assembled) {
916: PetscCall(MatAssemblyBegin(A, MAT_FINAL_ASSEMBLY));
917: PetscCall(MatAssemblyEnd(A, MAT_FINAL_ASSEMBLY));
918: }
919: PetscCall(MatShift(A, shift));
920: if (A != B) {
921: PetscCall(MatZeroEntries(B));
922: PetscCall(MatAssembled(B, &assembled));
923: if (!assembled) {
924: PetscCall(MatAssemblyBegin(B, MAT_FINAL_ASSEMBLY));
925: PetscCall(MatAssemblyEnd(B, MAT_FINAL_ASSEMBLY));
926: }
927: PetscCall(MatShift(B, shift));
928: }
929: }
930: } else {
931: Mat Arhs = NULL, Brhs = NULL;
933: /* RHSJacobian needs to be converted to part of IJacobian if exists */
934: if (rhsjacobian) PetscCall(TSGetRHSMats_Private(ts, &Arhs, &Brhs));
935: if (Arhs == A) { /* No IJacobian matrix, so we only have the RHS matrix */
936: DM dm;
937: VecState Ustate;
938: PetscBool same;
939: TSRHSFunctionFn *rhsfunction;
941: PetscCall(TSGetDM(ts, &dm));
942: PetscCall(DMTSGetRHSFunction(dm, &rhsfunction, NULL));
943: PetscCall(VecGetState(U, &Ustate));
944: PetscCall(VecStateCompare(Ustate, ts->rhsjacobian.Xstate, &same));
945: if ((rhsjacobian == TSComputeRHSJacobianConstant || (ts->rhsjacobian.time == t && (ts->problem_type == TS_LINEAR || same) && rhsfunction != TSComputeRHSFunctionLinear)) && ts->rhsjacobian.scale == -1.) { /* No need to recompute RHSJacobian */
946: PetscCall(MatShift(A, shift - ts->rhsjacobian.shift)); /* revert the old shift and add the new shift with a single call to MatShift */
947: if (A != B) PetscCall(MatShift(B, shift - ts->rhsjacobian.shift));
948: } else {
949: PetscBool flg;
951: if (ts->rhsjacobian.reuse) { /* Undo the damage */
952: /* MatScale has a short path for this case.
953: However, this code path is taken the first time TSComputeRHSJacobian is called
954: and the matrices have not been assembled yet */
955: PetscCall(TSRecoverRHSJacobian(ts, A, B));
956: }
957: PetscCall(TSComputeRHSJacobian(ts, t, U, A, B));
958: PetscCall(SNESGetUseMatrixFree(ts->snes, NULL, &flg));
959: /* since -snes_mf_operator uses the full SNES function it does not need to be shifted or scaled here */
960: if (!flg) {
961: PetscCall(MatScale(A, -1));
962: PetscCall(MatShift(A, shift));
963: }
964: if (A != B) {
965: PetscCall(MatScale(B, -1));
966: PetscCall(MatShift(B, shift));
967: }
968: }
969: ts->rhsjacobian.scale = -1;
970: ts->rhsjacobian.shift = shift;
971: } else if (Arhs) { /* Both IJacobian and RHSJacobian */
972: if (!ijacobian) { /* No IJacobian provided, but we have a separate RHS matrix */
973: PetscCall(MatZeroEntries(A));
974: PetscCall(MatShift(A, shift));
975: if (A != B) {
976: PetscCall(MatZeroEntries(B));
977: PetscCall(MatShift(B, shift));
978: }
979: }
980: PetscCall(TSComputeRHSJacobian(ts, t, U, Arhs, Brhs));
981: PetscCall(MatAXPY(A, -1, Arhs, ts->axpy_pattern));
982: if (A != B) PetscCall(MatAXPY(B, -1, Brhs, ts->axpy_pattern));
983: }
984: }
985: PetscCall(PetscLogEventEnd(TS_JacobianEval, U, ts, A, B));
986: PetscFunctionReturn(PETSC_SUCCESS);
987: }
989: /*@
990: TSComputeIJacobian - Evaluates the Jacobian of the DAE
992: Collective
994: Input Parameters:
995: + ts - the `TS` context
996: . t - current timestep
997: . U - state vector
998: . Udot - time derivative of state vector
999: . shift - shift to apply, see note below
1000: - imex - flag indicates if the method is `TSARKIMEX` so that the RHSJacobian should be kept separate
1002: Output Parameters:
1003: + A - Jacobian matrix
1004: - B - matrix from which the preconditioner is constructed; often the same as `A`
1006: Level: developer
1008: Notes:
1009: If $F(t,U,\dot{U})=0$ is the DAE, the required Jacobian is
1010: .vb
1011: dF/dU + shift*dF/dUdot
1012: .ve
1013: Most users should not need to explicitly call this routine, as it
1014: is used internally within the nonlinear solvers.
1016: .seealso: [](ch_ts), `TS`, `TSSetIJacobian()`
1017: @*/
1018: PetscErrorCode TSComputeIJacobian(TS ts, PetscReal t, Vec U, Vec Udot, PetscReal shift, Mat A, Mat B, PetscBool imex)
1019: {
1020: TSIJacobianFn *ijacobian;
1021: TSRHSJacobianFn *rhsjacobian;
1022: DM dm;
1023: void *ctx;
1025: PetscFunctionBegin;
1032: PetscCall(TSGetDM(ts, &dm));
1033: PetscCall(DMTSGetIJacobian(dm, &ijacobian, &ctx));
1034: PetscCall(DMTSGetRHSJacobian(dm, &rhsjacobian, NULL));
1035: PetscCall(TSComputeIJacobian_Internal(ts, ijacobian, rhsjacobian, ctx, t, U, Udot, shift, A, B, imex));
1036: PetscFunctionReturn(PETSC_SUCCESS);
1037: }
1039: /*@
1040: TSSetRHSFunction - Sets the routine for evaluating the function,
1041: where U_t = G(t,u).
1043: Logically Collective
1045: Input Parameters:
1046: + ts - the `TS` context obtained from `TSCreate()`
1047: . r - vector to put the computed right-hand side (or `NULL` to have it created)
1048: . f - routine for evaluating the right-hand-side function
1049: - ctx - [optional] user-defined context for private data for the function evaluation routine (may be `NULL`)
1051: Level: beginner
1053: Note:
1054: You must call this function or `TSSetIFunction()` to define your ODE. You cannot use this function when solving a DAE.
1056: .seealso: [](ch_ts), `TS`, `TSRHSFunctionFn`, `TSSetRHSJacobian()`, `TSSetIJacobian()`, `TSSetIFunction()`
1057: @*/
1058: PetscErrorCode TSSetRHSFunction(TS ts, Vec r, TSRHSFunctionFn *f, PetscCtx ctx)
1059: {
1060: SNES snes;
1061: Vec ralloc = NULL;
1062: DM dm;
1064: PetscFunctionBegin;
1068: PetscCall(TSGetDM(ts, &dm));
1069: PetscCall(DMTSSetRHSFunction(dm, f, ctx));
1070: PetscCall(TSGetSNES(ts, &snes));
1071: if (!r && !ts->dm && ts->vec_sol) {
1072: PetscCall(VecDuplicate(ts->vec_sol, &ralloc));
1073: r = ralloc;
1074: }
1075: PetscCall(SNESSetFunction(snes, r, SNESTSFormFunction, ts));
1076: PetscCall(VecDestroy(&ralloc));
1077: PetscFunctionReturn(PETSC_SUCCESS);
1078: }
1080: /*@
1081: TSSetSolutionFunction - Provide a function that computes the solution of the ODE or DAE
1083: Logically Collective
1085: Input Parameters:
1086: + ts - the `TS` context obtained from `TSCreate()`
1087: . f - routine for evaluating the solution
1088: - ctx - [optional] user-defined context for private data for the
1089: function evaluation routine (may be `NULL`)
1091: Options Database Keys:
1092: + -ts_monitor_lg_error - create a graphical monitor of error history, requires user to have provided `TSSetSolutionFunction()`
1093: - -ts_monitor_draw_error - Monitor error graphically, requires user to have provided `TSSetSolutionFunction()`
1095: Level: intermediate
1097: Notes:
1098: This routine is used for testing accuracy of time integration schemes when you already know the solution.
1099: If analytic solutions are not known for your system, consider using the Method of Manufactured Solutions to
1100: create closed-form solutions with non-physical forcing terms.
1102: For low-dimensional problems solved in serial, such as small discrete systems, `TSMonitorLGError()` can be used to monitor the error history.
1104: .seealso: [](ch_ts), `TS`, `TSSolutionFn`, `TSSetRHSJacobian()`, `TSSetIJacobian()`, `TSComputeSolutionFunction()`, `TSSetForcingFunction()`, `TSSetSolution()`, `TSGetSolution()`, `TSMonitorLGError()`, `TSMonitorDrawError()`
1105: @*/
1106: PetscErrorCode TSSetSolutionFunction(TS ts, TSSolutionFn *f, PetscCtx ctx)
1107: {
1108: DM dm;
1110: PetscFunctionBegin;
1112: PetscCall(TSGetDM(ts, &dm));
1113: PetscCall(DMTSSetSolutionFunction(dm, f, ctx));
1114: PetscFunctionReturn(PETSC_SUCCESS);
1115: }
1117: /*@
1118: TSSetForcingFunction - Provide a function that computes a forcing term for a ODE or PDE
1120: Logically Collective
1122: Input Parameters:
1123: + ts - the `TS` context obtained from `TSCreate()`
1124: . func - routine for evaluating the forcing function
1125: - ctx - [optional] user-defined context for private data for the function evaluation routine
1126: (may be `NULL`)
1128: Level: intermediate
1130: Notes:
1131: This routine is useful for testing accuracy of time integration schemes when using the Method of Manufactured Solutions to
1132: create closed-form solutions with a non-physical forcing term. It allows you to use the Method of Manufactored Solution without directly editing the
1133: definition of the problem you are solving and hence possibly introducing bugs.
1135: This replaces the ODE F(u,u_t,t) = 0 the `TS` is solving with F(u,u_t,t) - func(t) = 0
1137: This forcing function does not depend on the solution to the equations, it can only depend on spatial location, time, and possibly parameters, the
1138: parameters can be passed in the ctx variable.
1140: For low-dimensional problems solved in serial, such as small discrete systems, `TSMonitorLGError()` can be used to monitor the error history.
1142: .seealso: [](ch_ts), `TS`, `TSForcingFn`, `TSSetRHSJacobian()`, `TSSetIJacobian()`,
1143: `TSComputeSolutionFunction()`, `TSSetSolutionFunction()`
1144: @*/
1145: PetscErrorCode TSSetForcingFunction(TS ts, TSForcingFn *func, PetscCtx ctx)
1146: {
1147: DM dm;
1149: PetscFunctionBegin;
1151: PetscCall(TSGetDM(ts, &dm));
1152: PetscCall(DMTSSetForcingFunction(dm, func, ctx));
1153: PetscFunctionReturn(PETSC_SUCCESS);
1154: }
1156: /*@
1157: TSSetRHSJacobian - Sets the function to compute the Jacobian of G,
1158: where U_t = G(U,t), as well as the location to store the matrix.
1160: Logically Collective
1162: Input Parameters:
1163: + ts - the `TS` context obtained from `TSCreate()`
1164: . Amat - (approximate) location to store Jacobian matrix entries computed by `f`
1165: . Pmat - matrix from which preconditioner is to be constructed (usually the same as `Amat`)
1166: . f - the Jacobian evaluation routine
1167: - ctx - [optional] user-defined context for private data for the Jacobian evaluation routine (may be `NULL`)
1169: Level: beginner
1171: Notes:
1172: You must set all the diagonal entries of the matrices, if they are zero you must still set them with a zero value
1174: The `TS` solver may modify the nonzero structure and the entries of the matrices `Amat` and `Pmat` between the calls to `f()`
1175: You should not assume the values are the same in the next call to f() as you set them in the previous call.
1177: .seealso: [](ch_ts), `TS`, `TSRHSJacobianFn`, `SNESComputeJacobianDefaultColor()`,
1178: `TSSetRHSFunction()`, `TSRHSJacobianSetReuse()`, `TSSetIJacobian()`, `TSRHSFunctionFn`, `TSIFunctionFn`
1179: @*/
1180: PetscErrorCode TSSetRHSJacobian(TS ts, Mat Amat, Mat Pmat, TSRHSJacobianFn *f, PetscCtx ctx)
1181: {
1182: SNES snes;
1183: DM dm;
1184: TSIJacobianFn *ijacobian;
1186: PetscFunctionBegin;
1190: if (Amat) PetscCheckSameComm(ts, 1, Amat, 2);
1191: if (Pmat) PetscCheckSameComm(ts, 1, Pmat, 3);
1193: PetscCall(TSGetDM(ts, &dm));
1194: PetscCall(DMTSSetRHSJacobian(dm, f, ctx));
1195: PetscCall(DMTSGetIJacobian(dm, &ijacobian, NULL));
1196: PetscCall(TSGetSNES(ts, &snes));
1197: if (!ijacobian) PetscCall(SNESSetJacobian(snes, Amat, Pmat, SNESTSFormJacobian, ts));
1198: if (Amat) {
1199: PetscCall(PetscObjectReference((PetscObject)Amat));
1200: PetscCall(MatDestroy(&ts->Arhs));
1201: ts->Arhs = Amat;
1202: }
1203: if (Pmat) {
1204: PetscCall(PetscObjectReference((PetscObject)Pmat));
1205: PetscCall(MatDestroy(&ts->Brhs));
1206: ts->Brhs = Pmat;
1207: }
1208: PetscFunctionReturn(PETSC_SUCCESS);
1209: }
1211: /*@
1212: TSSetIFunction - Set the function to compute F(t,U,U_t) where F() = 0 is the DAE to be solved.
1214: Logically Collective
1216: Input Parameters:
1217: + ts - the `TS` context obtained from `TSCreate()`
1218: . r - vector to hold the residual (or `NULL` to have it created internally)
1219: . f - the function evaluation routine
1220: - ctx - user-defined context for private data for the function evaluation routine (may be `NULL`)
1222: Level: beginner
1224: Note:
1225: The user MUST call either this routine or `TSSetRHSFunction()` to define the ODE. When solving DAEs you must use this function.
1227: .seealso: [](ch_ts), `TS`, `TSIFunctionFn`, `TSSetRHSJacobian()`, `TSSetRHSFunction()`,
1228: `TSSetIJacobian()`
1229: @*/
1230: PetscErrorCode TSSetIFunction(TS ts, Vec r, TSIFunctionFn *f, PetscCtx ctx)
1231: {
1232: SNES snes;
1233: Vec ralloc = NULL;
1234: DM dm;
1236: PetscFunctionBegin;
1240: PetscCall(TSGetDM(ts, &dm));
1241: PetscCall(DMTSSetIFunction(dm, f, ctx));
1243: PetscCall(TSGetSNES(ts, &snes));
1244: if (!r && !ts->dm && ts->vec_sol) {
1245: PetscCall(VecDuplicate(ts->vec_sol, &ralloc));
1246: r = ralloc;
1247: }
1248: PetscCall(SNESSetFunction(snes, r, SNESTSFormFunction, ts));
1249: PetscCall(VecDestroy(&ralloc));
1250: PetscFunctionReturn(PETSC_SUCCESS);
1251: }
1253: /*@
1254: TSGetIFunction - Returns the vector where the implicit residual is stored and the function/context to compute it.
1256: Not Collective
1258: Input Parameter:
1259: . ts - the `TS` context
1261: Output Parameters:
1262: + r - vector to hold residual (or `NULL`)
1263: . func - the function to compute residual (or `NULL`)
1264: - ctx - the function context (or `NULL`)
1266: Level: advanced
1268: .seealso: [](ch_ts), `TS`, `TSSetIFunction()`, `SNESGetFunction()`
1269: @*/
1270: PetscErrorCode TSGetIFunction(TS ts, Vec *r, TSIFunctionFn **func, PetscCtxRt ctx)
1271: {
1272: SNES snes;
1273: DM dm;
1275: PetscFunctionBegin;
1277: PetscCall(TSGetSNES(ts, &snes));
1278: PetscCall(SNESGetFunction(snes, r, NULL, NULL));
1279: PetscCall(TSGetDM(ts, &dm));
1280: PetscCall(DMTSGetIFunction(dm, func, ctx));
1281: PetscFunctionReturn(PETSC_SUCCESS);
1282: }
1284: /*@
1285: TSGetRHSFunction - Returns the vector where the right-hand side is stored and the function/context to compute it.
1287: Not Collective
1289: Input Parameter:
1290: . ts - the `TS` context
1292: Output Parameters:
1293: + r - vector to hold computed right-hand side (or `NULL`)
1294: . func - the function to compute right-hand side (or `NULL`)
1295: - ctx - the function context (or `NULL`)
1297: Level: advanced
1299: .seealso: [](ch_ts), `TS`, `TSSetRHSFunction()`, `SNESGetFunction()`
1300: @*/
1301: PetscErrorCode TSGetRHSFunction(TS ts, Vec *r, TSRHSFunctionFn **func, PetscCtxRt ctx)
1302: {
1303: SNES snes;
1304: DM dm;
1306: PetscFunctionBegin;
1308: PetscCall(TSGetSNES(ts, &snes));
1309: PetscCall(SNESGetFunction(snes, r, NULL, NULL));
1310: PetscCall(TSGetDM(ts, &dm));
1311: PetscCall(DMTSGetRHSFunction(dm, func, ctx));
1312: PetscFunctionReturn(PETSC_SUCCESS);
1313: }
1315: /*@
1316: TSSetIJacobian - Set the function to compute the matrix dF/dU + a*dF/dU_t where F(t,U,U_t) is the function
1317: provided with `TSSetIFunction()`.
1319: Logically Collective
1321: Input Parameters:
1322: + ts - the `TS` context obtained from `TSCreate()`
1323: . Amat - (approximate) matrix to store Jacobian entries computed by `f`
1324: . Pmat - matrix used to compute preconditioner (usually the same as `Amat`)
1325: . f - the Jacobian evaluation routine
1326: - ctx - user-defined context for private data for the Jacobian evaluation routine (may be `NULL`)
1328: Level: beginner
1330: Notes:
1331: The matrices `Amat` and `Pmat` are exactly the matrices that are used by `SNES` for the nonlinear solve.
1333: If you know the operator Amat has a null space you can use `MatSetNullSpace()` and `MatSetTransposeNullSpace()` to supply the null
1334: space to `Amat` and the `KSP` solvers will automatically use that null space as needed during the solution process.
1336: The matrix dF/dU + a*dF/dU_t you provide turns out to be
1337: the Jacobian of F(t,U,W+a*U) where F(t,U,U_t) = 0 is the DAE to be solved.
1338: The time integrator internally approximates U_t by W+a*U where the positive "shift"
1339: a and vector W depend on the integration method, step size, and past states. For example with
1340: the backward Euler method a = 1/dt and W = -a*U(previous timestep) so
1341: W + a*U = a*(U - U(previous timestep)) = (U - U(previous timestep))/dt
1343: You must set all the diagonal entries of the matrices, if they are zero you must still set them with a zero value
1345: The TS solver may modify the nonzero structure and the entries of the matrices `Amat` and `Pmat` between the calls to `f`
1346: You should not assume the values are the same in the next call to `f` as you set them in the previous call.
1348: In case `TSSetRHSJacobian()` is also used in conjunction with a fully-implicit solver,
1349: multilevel linear solvers, e.g. `PCMG`, will likely not work due to the way `TS` handles rhs matrices.
1351: .seealso: [](ch_ts), `TS`, `TSIJacobianFn`, `TSSetIFunction()`, `TSSetRHSJacobian()`,
1352: `SNESComputeJacobianDefaultColor()`, `SNESComputeJacobianDefault()`, `TSSetRHSFunction()`
1353: @*/
1354: PetscErrorCode TSSetIJacobian(TS ts, Mat Amat, Mat Pmat, TSIJacobianFn *f, PetscCtx ctx)
1355: {
1356: SNES snes;
1357: DM dm;
1359: PetscFunctionBegin;
1363: if (Amat) PetscCheckSameComm(ts, 1, Amat, 2);
1364: if (Pmat) PetscCheckSameComm(ts, 1, Pmat, 3);
1366: PetscCall(TSGetDM(ts, &dm));
1367: PetscCall(DMTSSetIJacobian(dm, f, ctx));
1369: PetscCall(TSGetSNES(ts, &snes));
1370: PetscCall(SNESSetJacobian(snes, Amat, Pmat, SNESTSFormJacobian, ts));
1371: PetscFunctionReturn(PETSC_SUCCESS);
1372: }
1374: /*@
1375: TSSetMassMatrix - Set the function to compute the mass matrix $M = \partial F/\partial \dot U$ of a DAE.
1377: Logically Collective
1379: Input Parameters:
1380: + ts - the `TS` context obtained from `TSCreate()`
1381: . func - the mass matrix evaluation routine, see `TSMassMatrixFn` for the calling sequence
1382: - ctx - application context for the mass matrix evaluation routine (may be `NULL`)
1384: Level: intermediate
1386: Notes:
1387: This is used by implicit integrators that solve DAEs $F(t, U, \dot U) = 0$ with a possibly singular mass matrix $M$.
1388: Only `TSIRK` currently consumes it; other integrators ignore it.
1390: You do not create the matrix $M$ yourself. The consuming integrator creates it with the correct layout and passes it to
1391: `func` (a `TSMassMatrixFn`), which only fills its entries. `TSIRK` creates $M$ by duplicating the Jacobian matrix set with
1392: `TSSetIJacobian()`, so $M$ shares the Jacobian's nonzero pattern; fill only the entries the mass matrix needs.
1394: The callback is stored on the `TS`'s `DM` and copied to coarser `DM`s by `DMTSCopy()`, so it is available at
1395: every level of a geometric multigrid hierarchy. `TSIRK` currently assembles the mass matrix only on the fine `DM`.
1397: .seealso: [](ch_ts), `TS`, `TSMassMatrixFn`, `TSGetMassMatrix()`, `TSComputeMassMatrix()`, `TSSetIJacobian()`, `TSIRK`
1398: @*/
1399: PetscErrorCode TSSetMassMatrix(TS ts, TSMassMatrixFn *func, PetscCtx ctx)
1400: {
1401: DM dm;
1403: PetscFunctionBegin;
1405: PetscCall(TSGetDM(ts, &dm));
1406: PetscCall(DMTSSetMassMatrix(dm, func, ctx));
1407: PetscFunctionReturn(PETSC_SUCCESS);
1408: }
1410: /*@
1411: TSGetMassMatrix - Get the mass matrix evaluation routine and context set with `TSSetMassMatrix()`.
1413: Not Collective
1415: Input Parameter:
1416: . ts - the `TS` context obtained from `TSCreate()`
1418: Output Parameters:
1419: + func - the mass matrix evaluation routine (or `NULL`), see `TSMassMatrixFn` for the calling sequence
1420: - ctx - the application context (or `NULL`)
1422: Level: intermediate
1424: .seealso: [](ch_ts), `TS`, `TSMassMatrixFn`, `TSSetMassMatrix()`
1425: @*/
1426: PetscErrorCode TSGetMassMatrix(TS ts, TSMassMatrixFn **func, PetscCtxRt ctx)
1427: {
1428: DM dm;
1430: PetscFunctionBegin;
1432: PetscCall(TSGetDM(ts, &dm));
1433: PetscCall(DMTSGetMassMatrix(dm, func, ctx));
1434: PetscFunctionReturn(PETSC_SUCCESS);
1435: }
1437: /*@
1438: TSSetMassMatrixContextDestroy - Set the function to destroy the context set with `TSSetMassMatrix()`.
1440: Logically Collective
1442: Input Parameters:
1443: + ts - the `TS` context obtained from `TSCreate()`
1444: - f - the context destroy function, see `PetscCtxDestroyFn` for its calling sequence
1446: Level: intermediate
1448: .seealso: [](ch_ts), `TS`, `TSSetMassMatrix()`, `TSMassMatrixFn`
1449: @*/
1450: PetscErrorCode TSSetMassMatrixContextDestroy(TS ts, PetscCtxDestroyFn *f)
1451: {
1452: DM dm;
1454: PetscFunctionBegin;
1456: PetscCall(TSGetDM(ts, &dm));
1457: PetscCall(DMTSSetMassMatrixContextDestroy(dm, f));
1458: PetscFunctionReturn(PETSC_SUCCESS);
1459: }
1461: /*@
1462: TSSetMassMatrixConstant - Declare whether the mass matrix set with `TSSetMassMatrix()` is constant.
1464: Logically Collective
1466: Input Parameters:
1467: + ts - the `TS` context obtained from `TSCreate()`
1468: - constant - `PETSC_TRUE` if the mass matrix depends on neither time nor the solution, so it may be assembled once and reused
1470: Level: intermediate
1472: Note:
1473: By default the mass matrix is treated as time- and state-dependent and integrators re-evaluate it (via the routine set
1474: with `TSSetMassMatrix()`) whenever the operator is rebuilt. Setting this flag lets an integrator assemble the mass
1475: matrix a single time and reuse it, avoiding repeated assembly for the common constant-mass case.
1477: .seealso: [](ch_ts), `TS`, `TSSetMassMatrix()`, `TSGetMassMatrixConstant()`, `TSMassMatrixFn`, `TSIRK`
1478: @*/
1479: PetscErrorCode TSSetMassMatrixConstant(TS ts, PetscBool constant)
1480: {
1481: PetscFunctionBegin;
1484: ts->massmatrixconstant = constant;
1485: PetscFunctionReturn(PETSC_SUCCESS);
1486: }
1488: /*@
1489: TSGetMassMatrixConstant - Return whether the mass matrix has been declared constant with `TSSetMassMatrixConstant()`.
1491: Not Collective
1493: Input Parameter:
1494: . ts - the `TS` context obtained from `TSCreate()`
1496: Output Parameter:
1497: . constant - `PETSC_TRUE` if the mass matrix is constant
1499: Level: intermediate
1501: .seealso: [](ch_ts), `TS`, `TSSetMassMatrixConstant()`, `TSSetMassMatrix()`
1502: @*/
1503: PetscErrorCode TSGetMassMatrixConstant(TS ts, PetscBool *constant)
1504: {
1505: PetscFunctionBegin;
1507: PetscAssertPointer(constant, 2);
1508: *constant = ts->massmatrixconstant;
1509: PetscFunctionReturn(PETSC_SUCCESS);
1510: }
1512: /*@
1513: TSHasMassMatrix - Determine whether a mass matrix evaluation routine has been set with `TSSetMassMatrix()`.
1515: Not Collective
1517: Input Parameter:
1518: . ts - the `TS` context obtained from `TSCreate()`
1520: Output Parameter:
1521: . has - `PETSC_TRUE` if a mass matrix callback is set
1523: Level: intermediate
1525: .seealso: [](ch_ts), `TS`, `TSSetMassMatrix()`, `TSComputeMassMatrix()`
1526: @*/
1527: PetscErrorCode TSHasMassMatrix(TS ts, PetscBool *has)
1528: {
1529: TSMassMatrixFn *func;
1531: PetscFunctionBegin;
1533: PetscAssertPointer(has, 2);
1534: PetscCall(TSGetMassMatrix(ts, &func, NULL));
1535: *has = func ? PETSC_TRUE : PETSC_FALSE;
1536: PetscFunctionReturn(PETSC_SUCCESS);
1537: }
1539: /*@
1540: TSComputeMassMatrix - Evaluate the mass matrix $M = \partial F/\partial \dot U$ using the routine set with `TSSetMassMatrix()`.
1542: Collective
1544: Input Parameters:
1545: + ts - the `TS` context obtained from `TSCreate()`
1546: . t - the time at which to evaluate the mass matrix
1547: - U - the state vector at which to evaluate the mass matrix
1549: Output Parameter:
1550: . M - the mass matrix to fill; the integrator supplies it with the correct layout
1552: Level: developer
1554: Note:
1555: The mass matrix is assembled on the `DM` returned by `TSGetDM()`, that is the fine `DM` or, within a multigrid
1556: traversal, the current level's `DM`. This matches `TSComputeIJacobian()`, which likewise takes no `DM` argument.
1558: .seealso: [](ch_ts), `TS`, `TSMassMatrixFn`, `TSSetMassMatrix()`, `TSHasMassMatrix()`
1559: @*/
1560: PetscErrorCode TSComputeMassMatrix(TS ts, PetscReal t, Vec U, Mat M)
1561: {
1562: DM dm;
1563: TSMassMatrixFn *func;
1564: void *ctx;
1566: PetscFunctionBegin;
1570: PetscCall(TSGetDM(ts, &dm));
1571: PetscCall(DMTSGetMassMatrix(dm, &func, &ctx));
1572: PetscCheck(func, PetscObjectComm((PetscObject)ts), PETSC_ERR_USER, "Must call TSSetMassMatrix() before TSComputeMassMatrix()");
1573: PetscCall(PetscLogEventBegin(TS_JacobianEval, U, ts, M, 0));
1574: PetscCallBack("TS callback mass matrix", (*func)(ts, t, U, M, ctx));
1575: PetscCall(PetscLogEventEnd(TS_JacobianEval, U, ts, M, 0));
1576: PetscFunctionReturn(PETSC_SUCCESS);
1577: }
1579: /*@
1580: TSRHSJacobianSetReuse - restore the RHS Jacobian before calling the user-provided `TSRHSJacobianFn` function again
1582: Logically Collective
1584: Input Parameters:
1585: + ts - `TS` context obtained from `TSCreate()`
1586: - reuse - `PETSC_TRUE` if the RHS Jacobian
1588: Level: intermediate
1590: Notes:
1591: Without this flag, `TS` will change the sign and shift the RHS Jacobian for a
1592: finite-time-step implicit solve, in which case the user function will need to recompute the
1593: entire Jacobian. The `reuse `flag must be set if the evaluation function assumes that the
1594: matrix entries have not been changed by the `TS`.
1596: .seealso: [](ch_ts), `TS`, `TSSetRHSJacobian()`, `TSComputeRHSJacobianConstant()`
1597: @*/
1598: PetscErrorCode TSRHSJacobianSetReuse(TS ts, PetscBool reuse)
1599: {
1600: PetscFunctionBegin;
1601: ts->rhsjacobian.reuse = reuse;
1602: PetscFunctionReturn(PETSC_SUCCESS);
1603: }
1605: /*@
1606: TSSetI2Function - Set the function to compute F(t,U,U_t,U_tt) where F = 0 is the DAE to be solved.
1608: Logically Collective
1610: Input Parameters:
1611: + ts - the `TS` context obtained from `TSCreate()`
1612: . F - vector to hold the residual (or `NULL` to have it created internally)
1613: . fun - the function evaluation routine
1614: - ctx - user-defined context for private data for the function evaluation routine (may be `NULL`)
1616: Level: beginner
1618: .seealso: [](ch_ts), `TS`, `TSI2FunctionFn`, `TSSetI2Jacobian()`, `TSSetIFunction()`,
1619: `TSCreate()`, `TSSetRHSFunction()`
1620: @*/
1621: PetscErrorCode TSSetI2Function(TS ts, Vec F, TSI2FunctionFn *fun, PetscCtx ctx)
1622: {
1623: DM dm;
1625: PetscFunctionBegin;
1628: PetscCall(TSSetIFunction(ts, F, NULL, NULL));
1629: PetscCall(TSGetDM(ts, &dm));
1630: PetscCall(DMTSSetI2Function(dm, fun, ctx));
1631: PetscFunctionReturn(PETSC_SUCCESS);
1632: }
1634: /*@
1635: TSGetI2Function - Returns the vector where the implicit residual is stored and the function/context to compute it.
1637: Not Collective
1639: Input Parameter:
1640: . ts - the `TS` context
1642: Output Parameters:
1643: + r - vector to hold residual (or `NULL`)
1644: . fun - the function to compute residual (or `NULL`)
1645: - ctx - the function context (or `NULL`)
1647: Level: advanced
1649: .seealso: [](ch_ts), `TS`, `TSSetIFunction()`, `SNESGetFunction()`, `TSCreate()`
1650: @*/
1651: PetscErrorCode TSGetI2Function(TS ts, Vec *r, TSI2FunctionFn **fun, PetscCtxRt ctx)
1652: {
1653: SNES snes;
1654: DM dm;
1656: PetscFunctionBegin;
1658: PetscCall(TSGetSNES(ts, &snes));
1659: PetscCall(SNESGetFunction(snes, r, NULL, NULL));
1660: PetscCall(TSGetDM(ts, &dm));
1661: PetscCall(DMTSGetI2Function(dm, fun, ctx));
1662: PetscFunctionReturn(PETSC_SUCCESS);
1663: }
1665: /*@
1666: TSSetI2Jacobian - Set the function to compute the matrix dF/dU + v*dF/dU_t + a*dF/dU_tt
1667: where F(t,U,U_t,U_tt) is the function you provided with `TSSetI2Function()`.
1669: Logically Collective
1671: Input Parameters:
1672: + ts - the `TS` context obtained from `TSCreate()`
1673: . J - matrix to hold the Jacobian values
1674: . P - matrix for constructing the preconditioner (may be same as `J`)
1675: . jac - the Jacobian evaluation routine, see `TSI2JacobianFn` for the calling sequence
1676: - ctx - user-defined context for private data for the Jacobian evaluation routine (may be `NULL`)
1678: Level: beginner
1680: Notes:
1681: The matrices `J` and `P` are exactly the matrices that are used by `SNES` for the nonlinear solve.
1683: The matrix dF/dU + v*dF/dU_t + a*dF/dU_tt you provide turns out to be
1684: 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.
1685: The time integrator internally approximates U_t by W+v*U and U_tt by W'+a*U where the positive "shift"
1686: parameters 'v' and 'a' and vectors W, W' depend on the integration method, step size, and past states.
1688: .seealso: [](ch_ts), `TS`, `TSI2JacobianFn`, `TSSetI2Function()`, `TSGetI2Jacobian()`
1689: @*/
1690: PetscErrorCode TSSetI2Jacobian(TS ts, Mat J, Mat P, TSI2JacobianFn *jac, PetscCtx ctx)
1691: {
1692: DM dm;
1694: PetscFunctionBegin;
1698: PetscCall(TSSetIJacobian(ts, J, P, NULL, NULL));
1699: PetscCall(TSGetDM(ts, &dm));
1700: PetscCall(DMTSSetI2Jacobian(dm, jac, ctx));
1701: PetscFunctionReturn(PETSC_SUCCESS);
1702: }
1704: /*@
1705: TSGetI2Jacobian - Returns the implicit Jacobian at the present timestep.
1707: Not Collective, but parallel objects are returned if `TS` is parallel
1709: Input Parameter:
1710: . ts - The `TS` context obtained from `TSCreate()`
1712: Output Parameters:
1713: + J - The (approximate) Jacobian of F(t,U,U_t,U_tt)
1714: . P - The matrix from which the preconditioner is constructed, often the same as `J`
1715: . jac - The function to compute the Jacobian matrices
1716: - ctx - User-defined context for Jacobian evaluation routine
1718: Level: advanced
1720: Note:
1721: You can pass in `NULL` for any return argument you do not need.
1723: .seealso: [](ch_ts), `TS`, `TSGetTimeStep()`, `TSGetMatrices()`, `TSGetTime()`, `TSGetStepNumber()`, `TSSetI2Jacobian()`, `TSGetI2Function()`, `TSCreate()`
1724: @*/
1725: PetscErrorCode TSGetI2Jacobian(TS ts, Mat *J, Mat *P, TSI2JacobianFn **jac, PetscCtxRt ctx)
1726: {
1727: SNES snes;
1728: DM dm;
1730: PetscFunctionBegin;
1731: PetscCall(TSGetSNES(ts, &snes));
1732: PetscCall(SNESSetUpMatrices(snes));
1733: PetscCall(SNESGetJacobian(snes, J, P, NULL, NULL));
1734: PetscCall(TSGetDM(ts, &dm));
1735: PetscCall(DMTSGetI2Jacobian(dm, jac, ctx));
1736: PetscFunctionReturn(PETSC_SUCCESS);
1737: }
1739: /*@
1740: TSComputeI2Function - Evaluates the DAE residual written in implicit form F(t,U,U_t,U_tt) = 0
1742: Collective
1744: Input Parameters:
1745: + ts - the `TS` context
1746: . t - current time
1747: . U - state vector
1748: . V - time derivative of state vector (U_t)
1749: - A - second time derivative of state vector (U_tt)
1751: Output Parameter:
1752: . F - the residual vector
1754: Level: developer
1756: Note:
1757: Most users should not need to explicitly call this routine, as it
1758: is used internally within the nonlinear solvers.
1760: .seealso: [](ch_ts), `TS`, `TSSetI2Function()`, `TSGetI2Function()`
1761: @*/
1762: PetscErrorCode TSComputeI2Function(TS ts, PetscReal t, Vec U, Vec V, Vec A, Vec F)
1763: {
1764: DM dm;
1765: TSI2FunctionFn *I2Function;
1766: void *ctx;
1767: TSRHSFunctionFn *rhsfunction;
1769: PetscFunctionBegin;
1776: PetscCall(TSGetDM(ts, &dm));
1777: PetscCall(DMTSGetI2Function(dm, &I2Function, &ctx));
1778: PetscCall(DMTSGetRHSFunction(dm, &rhsfunction, NULL));
1780: if (!I2Function) {
1781: PetscCall(TSComputeIFunction(ts, t, U, A, F, PETSC_FALSE));
1782: PetscFunctionReturn(PETSC_SUCCESS);
1783: }
1785: PetscCall(PetscLogEventBegin(TS_FunctionEval, U, ts, V, F));
1787: PetscCallBack("TS callback implicit function", I2Function(ts, t, U, V, A, F, ctx));
1789: if (rhsfunction) {
1790: Vec Frhs;
1792: PetscCall(DMGetGlobalVector(dm, &Frhs));
1793: PetscCall(TSComputeRHSFunction(ts, t, U, Frhs));
1794: PetscCall(VecAXPY(F, -1, Frhs));
1795: PetscCall(DMRestoreGlobalVector(dm, &Frhs));
1796: }
1798: PetscCall(PetscLogEventEnd(TS_FunctionEval, U, ts, V, F));
1799: PetscFunctionReturn(PETSC_SUCCESS);
1800: }
1802: /*@
1803: TSComputeI2Jacobian - Evaluates the Jacobian of the DAE
1805: Collective
1807: Input Parameters:
1808: + ts - the `TS` context
1809: . t - current timestep
1810: . U - state vector
1811: . V - time derivative of state vector
1812: . A - second time derivative of state vector
1813: . shiftV - shift to apply, see note below
1814: - shiftA - shift to apply, see note below
1816: Output Parameters:
1817: + J - Jacobian matrix
1818: - P - optional matrix used to construct the preconditioner
1820: Level: developer
1822: Notes:
1823: If $F(t,U,V,A) = 0$ is the DAE, the required Jacobian is
1825: $$
1826: dF/dU + shiftV dF/dV + shiftA dF/dA
1827: $$
1829: Most users should not need to explicitly call this routine, as it
1830: is used internally within the ODE integrators.
1832: .seealso: [](ch_ts), `TS`, `TSSetI2Jacobian()`
1833: @*/
1834: PetscErrorCode TSComputeI2Jacobian(TS ts, PetscReal t, Vec U, Vec V, Vec A, PetscReal shiftV, PetscReal shiftA, Mat J, Mat P)
1835: {
1836: DM dm;
1837: TSI2JacobianFn *I2Jacobian;
1838: void *ctx;
1839: TSRHSJacobianFn *rhsjacobian;
1841: PetscFunctionBegin;
1849: PetscCall(TSGetDM(ts, &dm));
1850: PetscCall(DMTSGetI2Jacobian(dm, &I2Jacobian, &ctx));
1851: PetscCall(DMTSGetRHSJacobian(dm, &rhsjacobian, NULL));
1853: if (!I2Jacobian) {
1854: PetscCall(TSComputeIJacobian(ts, t, U, A, shiftA, J, P, PETSC_FALSE));
1855: PetscFunctionReturn(PETSC_SUCCESS);
1856: }
1858: PetscCall(PetscLogEventBegin(TS_JacobianEval, U, ts, J, P));
1859: PetscCallBack("TS callback implicit Jacobian", I2Jacobian(ts, t, U, V, A, shiftV, shiftA, J, P, ctx));
1860: if (rhsjacobian) {
1861: Mat Jrhs, Prhs;
1862: PetscCall(TSGetRHSMats_Private(ts, &Jrhs, &Prhs));
1863: PetscCall(TSComputeRHSJacobian(ts, t, U, Jrhs, Prhs));
1864: PetscCall(MatAXPY(J, -1, Jrhs, ts->axpy_pattern));
1865: if (P != J) PetscCall(MatAXPY(P, -1, Prhs, ts->axpy_pattern));
1866: }
1868: PetscCall(PetscLogEventEnd(TS_JacobianEval, U, ts, J, P));
1869: PetscFunctionReturn(PETSC_SUCCESS);
1870: }
1872: /*@
1873: TSSetTransientVariable - sets function to transform from state to transient variables
1875: Logically Collective
1877: Input Parameters:
1878: + ts - time stepping context on which to change the transient variable
1879: . tvar - a function that transforms to transient variables, see `TSTransientVariableFn` for the calling sequence
1880: - ctx - a context for tvar
1882: Level: advanced
1884: Notes:
1885: This is typically used to transform from primitive to conservative variables so that a time integrator (e.g., `TSBDF`)
1886: can be conservative. In this context, primitive variables P are used to model the state (e.g., because they lead to
1887: well-conditioned formulations even in limiting cases such as low-Mach or zero porosity). The transient variable is
1888: C(P), specified by calling this function. An IFunction thus receives arguments (P, Cdot) and the IJacobian must be
1889: evaluated via the chain rule, as in
1890: .vb
1891: dF/dP + shift * dF/dCdot dC/dP.
1892: .ve
1894: .seealso: [](ch_ts), `TS`, `TSBDF`, `TSTransientVariableFn`, `DMTSSetTransientVariable()`, `DMTSGetTransientVariable()`, `TSSetIFunction()`, `TSSetIJacobian()`
1895: @*/
1896: PetscErrorCode TSSetTransientVariable(TS ts, TSTransientVariableFn *tvar, PetscCtx ctx)
1897: {
1898: DM dm;
1900: PetscFunctionBegin;
1902: PetscCall(TSGetDM(ts, &dm));
1903: PetscCall(DMTSSetTransientVariable(dm, tvar, ctx));
1904: PetscFunctionReturn(PETSC_SUCCESS);
1905: }
1907: /*@
1908: TSComputeTransientVariable - transforms state (primitive) variables to transient (conservative) variables
1910: Logically Collective
1912: Input Parameters:
1913: + ts - TS on which to compute
1914: - U - state vector to be transformed to transient variables
1916: Output Parameter:
1917: . C - transient (conservative) variable
1919: Level: developer
1921: Developer Notes:
1922: If `DMTSSetTransientVariable()` has not been called, then C is not modified in this routine and C = `NULL` is allowed.
1923: This makes it safe to call without a guard. One can use `TSHasTransientVariable()` to check if transient variables are
1924: being used.
1926: .seealso: [](ch_ts), `TS`, `TSBDF`, `DMTSSetTransientVariable()`, `TSComputeIFunction()`, `TSComputeIJacobian()`
1927: @*/
1928: PetscErrorCode TSComputeTransientVariable(TS ts, Vec U, Vec C)
1929: {
1930: DM dm;
1931: DMTS dmts;
1933: PetscFunctionBegin;
1936: PetscCall(TSGetDM(ts, &dm));
1937: PetscCall(DMGetDMTS(dm, &dmts));
1938: if (dmts->ops->transientvar) {
1940: PetscCall((*dmts->ops->transientvar)(ts, U, C, dmts->transientvarctx));
1941: }
1942: PetscFunctionReturn(PETSC_SUCCESS);
1943: }
1945: /*@
1946: TSHasTransientVariable - determine whether transient variables have been set
1948: Logically Collective
1950: Input Parameter:
1951: . ts - `TS` on which to compute
1953: Output Parameter:
1954: . has - `PETSC_TRUE` if transient variables have been set
1956: Level: developer
1958: .seealso: [](ch_ts), `TS`, `TSBDF`, `DMTSSetTransientVariable()`, `TSComputeTransientVariable()`
1959: @*/
1960: PetscErrorCode TSHasTransientVariable(TS ts, PetscBool *has)
1961: {
1962: DM dm;
1963: DMTS dmts;
1965: PetscFunctionBegin;
1967: PetscCall(TSGetDM(ts, &dm));
1968: PetscCall(DMGetDMTS(dm, &dmts));
1969: *has = dmts->ops->transientvar ? PETSC_TRUE : PETSC_FALSE;
1970: PetscFunctionReturn(PETSC_SUCCESS);
1971: }
1973: /*@
1974: TS2SetSolution - Sets the initial solution and time derivative vectors
1975: for use by the `TS` routines handling second order equations.
1977: Logically Collective
1979: Input Parameters:
1980: + ts - the `TS` context obtained from `TSCreate()`
1981: . u - the solution vector
1982: - v - the time derivative vector
1984: Level: beginner
1986: .seealso: [](ch_ts), `TS`
1987: @*/
1988: PetscErrorCode TS2SetSolution(TS ts, Vec u, Vec v)
1989: {
1990: PetscFunctionBegin;
1994: PetscCall(TSSetSolution(ts, u));
1995: PetscCall(PetscObjectReference((PetscObject)v));
1996: PetscCall(VecDestroy(&ts->vec_dot));
1997: ts->vec_dot = v;
1998: PetscFunctionReturn(PETSC_SUCCESS);
1999: }
2001: /*@
2002: TS2GetSolution - Returns the solution and time derivative at the present timestep
2003: for second order equations.
2005: Not Collective
2007: Input Parameter:
2008: . ts - the `TS` context obtained from `TSCreate()`
2010: Output Parameters:
2011: + u - the vector containing the solution
2012: - v - the vector containing the time derivative
2014: Level: intermediate
2016: Notes:
2017: It is valid to call this routine inside the function
2018: that you are evaluating in order to move to the new timestep. This vector not
2019: changed until the solution at the next timestep has been calculated.
2021: .seealso: [](ch_ts), `TS`, `TS2SetSolution()`, `TSGetTimeStep()`, `TSGetTime()`
2022: @*/
2023: PetscErrorCode TS2GetSolution(TS ts, Vec *u, Vec *v)
2024: {
2025: PetscFunctionBegin;
2027: if (u) PetscAssertPointer(u, 2);
2028: if (v) PetscAssertPointer(v, 3);
2029: if (u) *u = ts->vec_sol;
2030: if (v) *v = ts->vec_dot;
2031: PetscFunctionReturn(PETSC_SUCCESS);
2032: }
2034: /*@
2035: TSLoad - Loads a `TS` that has been stored in binary with `TSView()`.
2037: Collective
2039: Input Parameters:
2040: + ts - the newly loaded `TS`, this needs to have been created with `TSCreate()` or
2041: some related function before a call to `TSLoad()`.
2042: - viewer - binary file viewer, obtained from `PetscViewerBinaryOpen()`
2044: Level: intermediate
2046: Note:
2047: The type is determined by the data in the file, any type set into the `TS` before this call is ignored.
2049: .seealso: [](ch_ts), `TS`, `PetscViewer`, `PetscViewerBinaryOpen()`, `TSView()`, `MatLoad()`, `VecLoad()`
2050: @*/
2051: PetscErrorCode TSLoad(TS ts, PetscViewer viewer)
2052: {
2053: PetscBool isbinary;
2054: PetscInt classid;
2055: char type[256];
2056: DMTS sdm;
2057: DM dm;
2059: PetscFunctionBegin;
2062: PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERBINARY, &isbinary));
2063: PetscCheck(isbinary, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Invalid viewer; open viewer with PetscViewerBinaryOpen()");
2065: PetscCall(PetscViewerBinaryRead(viewer, &classid, 1, NULL, PETSC_INT));
2066: PetscCheck(classid == TS_FILE_CLASSID, PetscObjectComm((PetscObject)ts), PETSC_ERR_ARG_WRONG, "Not TS next in file");
2067: PetscCall(PetscViewerBinaryRead(viewer, type, 256, NULL, PETSC_CHAR));
2068: PetscCall(TSSetType(ts, type));
2069: PetscTryTypeMethod(ts, load, viewer);
2070: PetscCall(DMCreate(PetscObjectComm((PetscObject)ts), &dm));
2071: PetscCall(DMLoad(dm, viewer));
2072: PetscCall(TSSetDM(ts, dm));
2073: PetscCall(DMCreateGlobalVector(ts->dm, &ts->vec_sol));
2074: PetscCall(VecLoad(ts->vec_sol, viewer));
2075: PetscCall(DMGetDMTS(ts->dm, &sdm));
2076: PetscCall(DMTSLoad(sdm, viewer));
2077: PetscFunctionReturn(PETSC_SUCCESS);
2078: }
2080: #include <petscdraw.h>
2081: #if PetscDefined(HAVE_SAWS)
2082: #include <petscviewersaws.h>
2083: #endif
2085: /*@
2086: TSViewFromOptions - View a `TS` based on values in the options database
2088: Collective
2090: Input Parameters:
2091: + ts - the `TS` context
2092: . obj - optional object that provides the prefix for the options database keys, pass `NULL` to use the options prefix of `ts`
2093: - name - command line option string to be passed by user
2095: Options Database Key:
2096: . -name viewer_specification - See `PetscOptionsCreateViewer()` for the values of `viewer_specification`
2098: Level: intermediate
2100: Note:
2101: This checks the options database, creates the viewer on-the-fly, uses it and then destroys it. Hence it should not be called in heavily used routines,
2102: rather `PetscOptionsCreateViewer()` should be used to construct the viewer once which can then be utilized in the heavily used routine.
2104: .seealso: [](ch_ts), `TS`, `TSView()`, `PetscObjectViewFromOptions()`, `TSCreate()`, `PetscOptionsCreateViewer()`
2105: @*/
2106: PetscErrorCode TSViewFromOptions(TS ts, PetscObject obj, const char name[])
2107: {
2108: PetscFunctionBegin;
2110: PetscCall(PetscObjectViewFromOptions((PetscObject)ts, obj, name));
2111: PetscFunctionReturn(PETSC_SUCCESS);
2112: }
2114: /*@
2115: TSView - Displays the `TS` data structure.
2117: Collective
2119: Input Parameters:
2120: + ts - the `TS` context obtained from `TSCreate()`
2121: - viewer - visualization context
2123: Options Database Key:
2124: . -ts_view viewer_specification - calls `TSView()` at end of `TSStep()`. See `PetscOptionsCreateViewer()` for the format of `viewer_specification`
2126: Level: beginner
2128: Notes:
2129: The available visualization contexts include
2130: + `PETSC_VIEWER_STDOUT_SELF` - standard output (default)
2131: - `PETSC_VIEWER_STDOUT_WORLD` - synchronized standard
2132: output where only the first processor opens
2133: the file. All other processors send their
2134: data to the first processor to print.
2136: The user can open an alternative visualization context with
2137: `PetscViewerASCIIOpen()` - output to a specified file.
2139: In the debugger you can do call `TSView`(ts,0) to display the `TS` solver. (The same holds for any PETSc object viewer).
2141: The "initial time step" displayed is the default time step from `TSCreate()` or that set with `TSSetTimeStep()` or `-ts_time_step`
2143: .seealso: [](ch_ts), `TS`, `PetscViewer`, `PetscViewerASCIIOpen()`, `PetscOptionsCreateViewer()`, `TSViewFromOptions()`
2144: @*/
2145: PetscErrorCode TSView(TS ts, PetscViewer viewer)
2146: {
2147: TSType type;
2148: PetscBool isascii, isstring, issundials, isbinary, isdraw;
2149: DMTS sdm;
2150: #if PetscDefined(HAVE_SAWS)
2151: PetscBool issaws;
2152: #endif
2154: PetscFunctionBegin;
2156: if (!viewer) PetscCall(PetscViewerASCIIGetStdout(PetscObjectComm((PetscObject)ts), &viewer));
2158: PetscCheckSameComm(ts, 1, viewer, 2);
2160: PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERASCII, &isascii));
2161: PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERSTRING, &isstring));
2162: PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERBINARY, &isbinary));
2163: PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERDRAW, &isdraw));
2164: #if PetscDefined(HAVE_SAWS)
2165: PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERSAWS, &issaws));
2166: #endif
2167: if (isascii) {
2168: PetscCall(PetscObjectPrintClassNamePrefixType((PetscObject)ts, viewer));
2169: if (ts->ops->view) {
2170: PetscCall(PetscViewerASCIIPushTab(viewer));
2171: PetscUseTypeMethod(ts, view, viewer);
2172: PetscCall(PetscViewerASCIIPopTab(viewer));
2173: }
2174: PetscCall(PetscViewerASCIIPrintf(viewer, " initial time step=%g\n", (double)ts->initial_time_step));
2175: if (ts->max_steps < PETSC_INT_MAX) PetscCall(PetscViewerASCIIPrintf(viewer, " maximum steps=%" PetscInt_FMT "\n", ts->max_steps));
2176: if (ts->run_steps < PETSC_INT_MAX) PetscCall(PetscViewerASCIIPrintf(viewer, " run steps=%" PetscInt_FMT "\n", ts->run_steps));
2177: if (ts->max_time < PETSC_MAX_REAL) PetscCall(PetscViewerASCIIPrintf(viewer, " maximum time=%g\n", (double)ts->max_time));
2178: if (ts->max_reject != PETSC_UNLIMITED) PetscCall(PetscViewerASCIIPrintf(viewer, " maximum number of step rejections=%" PetscInt_FMT "\n", ts->max_reject));
2179: if (ts->max_snes_failures != PETSC_UNLIMITED) PetscCall(PetscViewerASCIIPrintf(viewer, " maximum number of SNES failures allowed=%" PetscInt_FMT "\n", ts->max_snes_failures));
2180: if (ts->ifuncs) PetscCall(PetscViewerASCIIPrintf(viewer, " total number of I function evaluations=%" PetscInt_FMT "\n", ts->ifuncs));
2181: if (ts->ijacs) PetscCall(PetscViewerASCIIPrintf(viewer, " total number of I Jacobian evaluations=%" PetscInt_FMT "\n", ts->ijacs));
2182: if (ts->rhsfuncs) PetscCall(PetscViewerASCIIPrintf(viewer, " total number of RHS function evaluations=%" PetscInt_FMT "\n", ts->rhsfuncs));
2183: if (ts->rhsjacs) PetscCall(PetscViewerASCIIPrintf(viewer, " total number of RHS Jacobian evaluations=%" PetscInt_FMT "\n", ts->rhsjacs));
2184: if (ts->usessnes) {
2185: PetscBool lin;
2186: if (ts->problem_type == TS_NONLINEAR) PetscCall(PetscViewerASCIIPrintf(viewer, " total number of nonlinear solver iterations=%" PetscInt_FMT "\n", ts->snes_its));
2187: PetscCall(PetscViewerASCIIPrintf(viewer, " total number of linear solver iterations=%" PetscInt_FMT "\n", ts->ksp_its));
2188: PetscCall(PetscObjectTypeCompareAny((PetscObject)ts->snes, &lin, SNESKSPONLY, SNESKSPTRANSPOSEONLY, ""));
2189: PetscCall(PetscViewerASCIIPrintf(viewer, " total number of %slinear solve failures=%" PetscInt_FMT "\n", lin ? "" : "non", ts->num_snes_failures));
2190: }
2191: PetscCall(PetscViewerASCIIPrintf(viewer, " total number of rejected steps=%" PetscInt_FMT "\n", ts->reject));
2192: if (ts->vrtol) PetscCall(PetscViewerASCIIPrintf(viewer, " using vector of relative error tolerances, "));
2193: else PetscCall(PetscViewerASCIIPrintf(viewer, " using relative error tolerance of %g, ", (double)ts->rtol));
2194: if (ts->vatol) PetscCall(PetscViewerASCIIPrintf(viewer, "using vector of absolute error tolerances\n"));
2195: else PetscCall(PetscViewerASCIIPrintf(viewer, "using absolute error tolerance of %g\n", (double)ts->atol));
2196: PetscCall(PetscViewerASCIIPushTab(viewer));
2197: PetscCall(TSAdaptView(ts->adapt, viewer));
2198: PetscCall(PetscViewerASCIIPopTab(viewer));
2199: } else if (isstring) {
2200: PetscCall(TSGetType(ts, &type));
2201: PetscCall(PetscViewerStringSPrintf(viewer, " TSType: %-7.7s", type));
2202: PetscTryTypeMethod(ts, view, viewer);
2203: } else if (isbinary) {
2204: PetscInt classid = TS_FILE_CLASSID;
2205: MPI_Comm comm;
2206: PetscMPIInt rank;
2207: char type[256];
2209: PetscCall(PetscObjectGetComm((PetscObject)ts, &comm));
2210: PetscCallMPI(MPI_Comm_rank(comm, &rank));
2211: if (rank == 0) {
2212: PetscCall(PetscViewerBinaryWrite(viewer, &classid, 1, PETSC_INT));
2213: PetscCall(PetscStrncpy(type, ((PetscObject)ts)->type_name, 256));
2214: PetscCall(PetscViewerBinaryWrite(viewer, type, 256, PETSC_CHAR));
2215: }
2216: PetscTryTypeMethod(ts, view, viewer);
2217: if (ts->adapt) PetscCall(TSAdaptView(ts->adapt, viewer));
2218: PetscCall(DMView(ts->dm, viewer));
2219: PetscCall(VecView(ts->vec_sol, viewer));
2220: PetscCall(DMGetDMTS(ts->dm, &sdm));
2221: PetscCall(DMTSView(sdm, viewer));
2222: } else if (isdraw) {
2223: PetscDraw draw;
2224: char str[36];
2225: PetscReal x, y, bottom, h;
2227: PetscCall(PetscViewerDrawGetDraw(viewer, 0, &draw));
2228: PetscCall(PetscDrawGetCurrentPoint(draw, &x, &y));
2229: PetscCall(PetscStrncpy(str, "TS: ", sizeof(str)));
2230: PetscCall(PetscStrlcat(str, ((PetscObject)ts)->type_name, sizeof(str)));
2231: PetscCall(PetscDrawStringBoxed(draw, x, y, PETSC_DRAW_BLACK, PETSC_DRAW_BLACK, str, NULL, &h));
2232: bottom = y - h;
2233: PetscCall(PetscDrawPushCurrentPoint(draw, x, bottom));
2234: PetscTryTypeMethod(ts, view, viewer);
2235: if (ts->adapt) PetscCall(TSAdaptView(ts->adapt, viewer));
2236: if (ts->snes) PetscCall(SNESView(ts->snes, viewer));
2237: PetscCall(PetscDrawPopCurrentPoint(draw));
2238: #if PetscDefined(HAVE_SAWS)
2239: } else if (issaws) {
2240: PetscMPIInt rank;
2241: const char *name;
2243: PetscCall(PetscObjectGetName((PetscObject)ts, &name));
2244: PetscCallMPI(MPI_Comm_rank(PETSC_COMM_WORLD, &rank));
2245: if (!((PetscObject)ts)->amsmem && rank == 0) {
2246: char dir[1024];
2248: PetscCall(PetscObjectViewSAWs((PetscObject)ts, viewer));
2249: PetscCall(PetscSNPrintf(dir, 1024, "/PETSc/Objects/%s/time_step", name));
2250: PetscCallSAWs(SAWs_Register, dir, &ts->steps, 1, SAWs_READ, SAWs_INT);
2251: PetscCall(PetscSNPrintf(dir, 1024, "/PETSc/Objects/%s/time", name));
2252: PetscCallSAWs(SAWs_Register, dir, &ts->ptime, 1, SAWs_READ, SAWs_DOUBLE);
2253: }
2254: PetscTryTypeMethod(ts, view, viewer);
2255: #endif
2256: }
2257: if (ts->snes && ts->usessnes) {
2258: PetscCall(PetscViewerASCIIPushTab(viewer));
2259: PetscCall(SNESView(ts->snes, viewer));
2260: PetscCall(PetscViewerASCIIPopTab(viewer));
2261: }
2262: PetscCall(DMGetDMTS(ts->dm, &sdm));
2263: PetscCall(DMTSView(sdm, viewer));
2265: PetscCall(PetscViewerASCIIPushTab(viewer));
2266: PetscCall(PetscObjectTypeCompare((PetscObject)ts, TSSUNDIALS, &issundials));
2267: PetscCall(PetscViewerASCIIPopTab(viewer));
2268: PetscFunctionReturn(PETSC_SUCCESS);
2269: }
2271: /*@
2272: TSSetApplicationContext - Sets an optional user-defined context for the timesteppers that may be accessed, for example inside the user provided
2273: `TS` callbacks with `TSGetApplicationContext()`
2275: Logically Collective
2277: Input Parameters:
2278: + ts - the `TS` context obtained from `TSCreate()`
2279: - ctx - application context
2281: Level: intermediate
2283: Fortran Note:
2284: This only works when `ctx` is a Fortran derived type (it cannot be a `PetscObject`), we recommend writing a Fortran interface definition for this
2285: function that tells the Fortran compiler the derived data type that is passed in as the `ctx` argument. See `TSGetApplicationContext()` for
2286: an example.
2288: .seealso: [](ch_ts), `TS`, `TSGetApplicationContext()`
2289: @*/
2290: PetscErrorCode TSSetApplicationContext(TS ts, PetscCtx ctx)
2291: {
2292: PetscFunctionBegin;
2294: ts->ctx = ctx;
2295: PetscFunctionReturn(PETSC_SUCCESS);
2296: }
2298: /*@
2299: TSGetApplicationContext - Gets the user-defined context for the
2300: timestepper that was set with `TSSetApplicationContext()`
2302: Not Collective
2304: Input Parameter:
2305: . ts - the `TS` context obtained from `TSCreate()`
2307: Output Parameter:
2308: . ctx - a pointer to the application context
2310: Level: intermediate
2312: Fortran Notes:
2313: This only works when the context is a Fortran derived type or a `PetscObject`. Declare `ctx` with
2314: .vb
2315: type(tUsertype), pointer :: ctx
2316: .ve
2318: .seealso: [](ch_ts), `TS`, `TSSetApplicationContext()`
2319: @*/
2320: PetscErrorCode TSGetApplicationContext(TS ts, PetscCtxRt ctx)
2321: {
2322: PetscFunctionBegin;
2324: *(void **)ctx = ts->ctx;
2325: PetscFunctionReturn(PETSC_SUCCESS);
2326: }
2328: /*@
2329: TSGetStepNumber - Gets the number of time steps completed.
2331: Not Collective
2333: Input Parameter:
2334: . ts - the `TS` context obtained from `TSCreate()`
2336: Output Parameter:
2337: . steps - number of steps completed so far
2339: Level: intermediate
2341: .seealso: [](ch_ts), `TS`, `TSGetTime()`, `TSGetTimeStep()`, `TSSetPreStep()`, `TSSetPreStage()`, `TSSetPostStage()`, `TSSetPostStep()`
2342: @*/
2343: PetscErrorCode TSGetStepNumber(TS ts, PetscInt *steps)
2344: {
2345: PetscFunctionBegin;
2347: PetscAssertPointer(steps, 2);
2348: *steps = ts->steps;
2349: PetscFunctionReturn(PETSC_SUCCESS);
2350: }
2352: /*@
2353: TSSetStepNumber - Sets the number of steps completed.
2355: Logically Collective
2357: Input Parameters:
2358: + ts - the `TS` context
2359: - steps - number of steps completed so far
2361: Level: developer
2363: Note:
2364: For most uses of the `TS` solvers the user need not explicitly call
2365: `TSSetStepNumber()`, as the step counter is appropriately updated in
2366: `TSSolve()`/`TSStep()`/`TSRollBack()`. Power users may call this routine to
2367: reinitialize timestepping by setting the step counter to zero (and time
2368: to the initial time) to solve a similar problem with different initial
2369: conditions or parameters. Other possible use case is to continue
2370: timestepping from a previously interrupted run in such a way that `TS`
2371: monitors will be called with a initial nonzero step counter.
2373: .seealso: [](ch_ts), `TS`, `TSGetStepNumber()`, `TSSetTime()`, `TSSetTimeStep()`, `TSSetSolution()`
2374: @*/
2375: PetscErrorCode TSSetStepNumber(TS ts, PetscInt steps)
2376: {
2377: PetscFunctionBegin;
2380: PetscCheck(steps >= 0, PetscObjectComm((PetscObject)ts), PETSC_ERR_ARG_OUTOFRANGE, "Step number must be non-negative");
2381: ts->steps = steps;
2382: PetscFunctionReturn(PETSC_SUCCESS);
2383: }
2385: /*@
2386: TSSetTimeStep - Allows one to reset the timestep at any time.
2388: Logically Collective
2390: Input Parameters:
2391: + ts - the `TS` context obtained from `TSCreate()`
2392: - time_step - the size of the timestep
2394: Options Database Key:
2395: . -ts_time_step dt - provide the initial time step
2397: Level: intermediate
2399: Notes:
2400: This is only a suggestion, the actual initial time step used may differ
2402: If this is called after `TSSetUp()`, it will not change the initial time step value printed by `TSView()`
2404: .seealso: [](ch_ts), `TS`, `TSPSEUDO`, `TSGetTimeStep()`, `TSSetTime()`
2405: @*/
2406: PetscErrorCode TSSetTimeStep(TS ts, PetscReal time_step)
2407: {
2408: PetscFunctionBegin;
2411: ts->time_step = time_step;
2412: if (ts->setupcalled == PETSC_FALSE) ts->initial_time_step = time_step;
2413: PetscFunctionReturn(PETSC_SUCCESS);
2414: }
2416: /*@
2417: TSSetExactFinalTime - Determines whether to adapt the final time step to
2418: match the exact final time, to interpolate the solution to the exact final time,
2419: or to just return at the final time `TS` computed (which may be slightly larger
2420: than the requested final time).
2422: Logically Collective
2424: Input Parameters:
2425: + ts - the time-step context
2426: - eftopt - exact final time option
2427: .vb
2428: TS_EXACTFINALTIME_STEPOVER - Don't do anything if final time is exceeded, just use it
2429: TS_EXACTFINALTIME_INTERPOLATE - Interpolate back to final time if the final time is exceeded
2430: TS_EXACTFINALTIME_MATCHSTEP - Adapt final time step to ensure the computed final time exactly equals the requested final time
2431: .ve
2433: Options Database Key:
2434: . -ts_exact_final_time stepover,interpolate,matchstep - select the final step approach at runtime
2436: Level: beginner
2438: Note:
2439: If you use the option `TS_EXACTFINALTIME_STEPOVER` the solution may be at a very different time
2440: then the final time you selected.
2442: .seealso: [](ch_ts), `TS`, `TSExactFinalTimeOption`, `TSGetExactFinalTime()`
2443: @*/
2444: PetscErrorCode TSSetExactFinalTime(TS ts, TSExactFinalTimeOption eftopt)
2445: {
2446: PetscFunctionBegin;
2449: ts->exact_final_time = eftopt;
2450: PetscFunctionReturn(PETSC_SUCCESS);
2451: }
2453: /*@
2454: TSGetExactFinalTime - Gets the exact final time option set with `TSSetExactFinalTime()`
2456: Not Collective
2458: Input Parameter:
2459: . ts - the `TS` context
2461: Output Parameter:
2462: . eftopt - exact final time option
2464: Level: beginner
2466: .seealso: [](ch_ts), `TS`, `TSExactFinalTimeOption`, `TSSetExactFinalTime()`
2467: @*/
2468: PetscErrorCode TSGetExactFinalTime(TS ts, TSExactFinalTimeOption *eftopt)
2469: {
2470: PetscFunctionBegin;
2472: PetscAssertPointer(eftopt, 2);
2473: *eftopt = ts->exact_final_time;
2474: PetscFunctionReturn(PETSC_SUCCESS);
2475: }
2477: /*@
2478: TSGetTimeStep - Gets the current timestep size.
2480: Not Collective
2482: Input Parameter:
2483: . ts - the `TS` context obtained from `TSCreate()`
2485: Output Parameter:
2486: . dt - the current timestep size
2488: Level: intermediate
2490: .seealso: [](ch_ts), `TS`, `TSSetTimeStep()`, `TSGetTime()`
2491: @*/
2492: PetscErrorCode TSGetTimeStep(TS ts, PetscReal *dt)
2493: {
2494: PetscFunctionBegin;
2496: PetscAssertPointer(dt, 2);
2497: *dt = ts->time_step;
2498: PetscFunctionReturn(PETSC_SUCCESS);
2499: }
2501: /*@
2502: TSGetSolution - Returns the solution at the present timestep. It
2503: is valid to call this routine inside the function that you are evaluating
2504: in order to move to the new timestep. This vector not changed until
2505: the solution at the next timestep has been calculated.
2507: Not Collective, but v returned is parallel if ts is parallel
2509: Input Parameter:
2510: . ts - the `TS` context obtained from `TSCreate()`
2512: Output Parameter:
2513: . v - the vector containing the solution
2515: Level: intermediate
2517: Note:
2518: If you used `TSSetExactFinalTime`(ts,`TS_EXACTFINALTIME_MATCHSTEP`); this does not return the solution at the requested
2519: final time. It returns the solution at the next timestep.
2521: .seealso: [](ch_ts), `TS`, `TSGetTimeStep()`, `TSGetTime()`, `TSGetSolveTime()`, `TSGetSolutionComponents()`, `TSSetSolutionFunction()`
2522: @*/
2523: PetscErrorCode TSGetSolution(TS ts, Vec *v)
2524: {
2525: PetscFunctionBegin;
2527: PetscAssertPointer(v, 2);
2528: *v = ts->vec_sol;
2529: PetscFunctionReturn(PETSC_SUCCESS);
2530: }
2532: /*@
2533: TSGetSolutionComponents - Returns any solution components at the present
2534: timestep, if available for the time integration method being used.
2535: Solution components are quantities that share the same size and
2536: structure as the solution vector.
2538: Not Collective, but v returned is parallel if ts is parallel
2540: Input Parameters:
2541: + ts - the `TS` context obtained from `TSCreate()` (input parameter).
2542: . n - If v is `NULL`, then the number of solution components is
2543: returned through n, else the n-th solution component is
2544: returned in v.
2545: - v - the vector containing the n-th solution component
2546: (may be `NULL` to use this function to find out
2547: the number of solutions components).
2549: Level: advanced
2551: .seealso: [](ch_ts), `TS`, `TSGetSolution()`
2552: @*/
2553: PetscErrorCode TSGetSolutionComponents(TS ts, PetscInt *n, Vec *v)
2554: {
2555: PetscFunctionBegin;
2557: if (!ts->ops->getsolutioncomponents) *n = 0;
2558: else PetscUseTypeMethod(ts, getsolutioncomponents, n, v);
2559: PetscFunctionReturn(PETSC_SUCCESS);
2560: }
2562: /*@
2563: TSGetAuxSolution - Returns an auxiliary solution at the present
2564: timestep, if available for the time integration method being used.
2566: Not Collective, but v returned is parallel if ts is parallel
2568: Input Parameters:
2569: + ts - the `TS` context obtained from `TSCreate()` (input parameter).
2570: - v - the vector containing the auxiliary solution
2572: Level: intermediate
2574: .seealso: [](ch_ts), `TS`, `TSGetSolution()`
2575: @*/
2576: PetscErrorCode TSGetAuxSolution(TS ts, Vec *v)
2577: {
2578: PetscFunctionBegin;
2580: if (ts->ops->getauxsolution) PetscUseTypeMethod(ts, getauxsolution, v);
2581: else PetscCall(VecZeroEntries(*v));
2582: PetscFunctionReturn(PETSC_SUCCESS);
2583: }
2585: /*@
2586: TSGetTimeError - Returns the estimated error vector, if the chosen
2587: `TSType` has an error estimation functionality and `TSSetTimeError()` was called
2589: Not Collective, but v returned is parallel if ts is parallel
2591: Input Parameters:
2592: + ts - the `TS` context obtained from `TSCreate()` (input parameter).
2593: . n - current estimate (n=0) or previous one (n=-1)
2594: - v - the vector containing the error (same size as the solution).
2596: Level: intermediate
2598: Note:
2599: MUST call after `TSSetUp()`
2601: .seealso: [](ch_ts), `TSGetSolution()`, `TSSetTimeError()`
2602: @*/
2603: PetscErrorCode TSGetTimeError(TS ts, PetscInt n, Vec *v)
2604: {
2605: PetscFunctionBegin;
2607: if (ts->ops->gettimeerror) PetscUseTypeMethod(ts, gettimeerror, n, v);
2608: else PetscCall(VecZeroEntries(*v));
2609: PetscFunctionReturn(PETSC_SUCCESS);
2610: }
2612: /*@
2613: TSSetTimeError - Sets the estimated error vector, if the chosen
2614: `TSType` has an error estimation functionality. This can be used
2615: to restart such a time integrator with a given error vector.
2617: Not Collective, but v returned is parallel if ts is parallel
2619: Input Parameters:
2620: + ts - the `TS` context obtained from `TSCreate()` (input parameter).
2621: - v - the vector containing the error (same size as the solution).
2623: Level: intermediate
2625: .seealso: [](ch_ts), `TS`, `TSSetSolution()`, `TSGetTimeError()`
2626: @*/
2627: PetscErrorCode TSSetTimeError(TS ts, Vec v)
2628: {
2629: PetscFunctionBegin;
2631: PetscCheck(ts->setupcalled, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Must call TSSetUp() first");
2632: PetscTryTypeMethod(ts, settimeerror, v);
2633: PetscFunctionReturn(PETSC_SUCCESS);
2634: }
2636: /* ----- Routines to initialize and destroy a timestepper ---- */
2637: /*@
2638: TSSetProblemType - Sets the type of problem to be solved.
2640: Not collective
2642: Input Parameters:
2643: + ts - The `TS`
2644: - type - One of `TS_LINEAR`, `TS_NONLINEAR` where these types refer to problems of the forms
2645: .vb
2646: U_t - A U = 0 (linear)
2647: U_t - A(t) U = 0 (linear)
2648: F(t,U,U_t) = 0 (nonlinear)
2649: .ve
2651: Level: beginner
2653: .seealso: [](ch_ts), `TSSetUp()`, `TSProblemType`, `TS`
2654: @*/
2655: PetscErrorCode TSSetProblemType(TS ts, TSProblemType type)
2656: {
2657: PetscFunctionBegin;
2659: ts->problem_type = type;
2660: if (type == TS_LINEAR) {
2661: SNES snes;
2662: PetscCall(TSGetSNES(ts, &snes));
2663: PetscCall(SNESSetType(snes, SNESKSPONLY));
2664: }
2665: PetscFunctionReturn(PETSC_SUCCESS);
2666: }
2668: /*@
2669: TSGetProblemType - Gets the type of problem to be solved.
2671: Not collective
2673: Input Parameter:
2674: . ts - The `TS`
2676: Output Parameter:
2677: . type - One of `TS_LINEAR`, `TS_NONLINEAR` where these types refer to problems of the forms
2678: .vb
2679: M U_t = A U
2680: M(t) U_t = A(t) U
2681: F(t,U,U_t)
2682: .ve
2684: Level: beginner
2686: .seealso: [](ch_ts), `TSSetUp()`, `TSProblemType`, `TS`
2687: @*/
2688: PetscErrorCode TSGetProblemType(TS ts, TSProblemType *type)
2689: {
2690: PetscFunctionBegin;
2692: PetscAssertPointer(type, 2);
2693: *type = ts->problem_type;
2694: PetscFunctionReturn(PETSC_SUCCESS);
2695: }
2697: /*
2698: Attempt to check/preset a default value for the exact final time option. This is needed at the beginning of TSSolve() and in TSSetUp()
2699: */
2700: static PetscErrorCode TSSetExactFinalTimeDefault(TS ts)
2701: {
2702: PetscBool isnone;
2704: PetscFunctionBegin;
2705: PetscCall(TSGetAdapt(ts, &ts->adapt));
2706: PetscCall(TSAdaptSetDefaultType(ts->adapt, ts->default_adapt_type));
2708: PetscCall(PetscObjectTypeCompare((PetscObject)ts->adapt, TSADAPTNONE, &isnone));
2709: if (!isnone && ts->exact_final_time == TS_EXACTFINALTIME_UNSPECIFIED) ts->exact_final_time = TS_EXACTFINALTIME_MATCHSTEP;
2710: else if (ts->exact_final_time == TS_EXACTFINALTIME_UNSPECIFIED) ts->exact_final_time = TS_EXACTFINALTIME_INTERPOLATE;
2711: PetscFunctionReturn(PETSC_SUCCESS);
2712: }
2714: /*@
2715: TSSetUp - Sets up the internal data structures for the later use of a timestepper.
2717: Collective
2719: Input Parameter:
2720: . ts - the `TS` context obtained from `TSCreate()`
2722: Level: advanced
2724: Note:
2725: For basic use of the `TS` solvers the user need not explicitly call
2726: `TSSetUp()`, since these actions will automatically occur during
2727: the call to `TSStep()` or `TSSolve()`. However, if one wishes to control this
2728: phase separately, `TSSetUp()` should be called after `TSCreate()`
2729: and optional routines of the form TSSetXXX(), but before `TSStep()` and `TSSolve()`.
2731: .seealso: [](ch_ts), `TSCreate()`, `TS`, `TSStep()`, `TSDestroy()`, `TSSolve()`
2732: @*/
2733: PetscErrorCode TSSetUp(TS ts)
2734: {
2735: DM dm;
2736: PetscErrorCode (*func)(SNES, Vec, Vec, void *);
2737: PetscErrorCode (*jac)(SNES, Vec, Mat, Mat, void *);
2738: TSIFunctionFn *ifun;
2739: TSIJacobianFn *ijac;
2740: TSI2JacobianFn *i2jac;
2741: TSRHSJacobianFn *rhsjac;
2743: PetscFunctionBegin;
2745: if (ts->setupcalled) PetscFunctionReturn(PETSC_SUCCESS);
2747: if (!((PetscObject)ts)->type_name) {
2748: PetscCall(TSGetIFunction(ts, NULL, &ifun, NULL));
2749: PetscCall(TSSetType(ts, ifun ? TSBEULER : TSEULER));
2750: }
2752: if (!ts->vec_sol) {
2753: PetscCheck(ts->dm, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Must call TSSetSolution() first");
2754: PetscCall(DMCreateGlobalVector(ts->dm, &ts->vec_sol));
2755: }
2757: if (!ts->Jacp && ts->Jacprhs) { /* IJacobianP shares the same matrix with RHSJacobianP if only RHSJacobianP is provided */
2758: PetscCall(PetscObjectReference((PetscObject)ts->Jacprhs));
2759: ts->Jacp = ts->Jacprhs;
2760: }
2762: if (ts->quadraturets) {
2763: PetscCall(TSSetUp(ts->quadraturets));
2764: PetscCall(VecDestroy(&ts->vec_costintegrand));
2765: PetscCall(VecDuplicate(ts->quadraturets->vec_sol, &ts->vec_costintegrand));
2766: }
2768: PetscCall(TSGetRHSJacobian(ts, NULL, NULL, &rhsjac, NULL));
2769: if (rhsjac == TSComputeRHSJacobianConstant) {
2770: Mat Amat, Pmat;
2771: SNES snes;
2772: PetscCall(TSGetSNES(ts, &snes));
2773: PetscCall(SNESGetJacobian(snes, &Amat, &Pmat, NULL, NULL));
2774: /* Matching matrices implies that an IJacobian is NOT set, because if it had been set, the IJacobian's matrix would
2775: * have displaced the RHS matrix */
2776: if (Amat && Amat == ts->Arhs) {
2777: /* 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 */
2778: PetscCall(MatDuplicate(ts->Arhs, MAT_COPY_VALUES, &Amat));
2779: PetscCall(SNESSetJacobian(snes, Amat, NULL, NULL, NULL));
2780: PetscCall(MatDestroy(&Amat));
2781: }
2782: if (Pmat && Pmat == ts->Brhs) {
2783: PetscCall(MatDuplicate(ts->Brhs, MAT_COPY_VALUES, &Pmat));
2784: PetscCall(SNESSetJacobian(snes, NULL, Pmat, NULL, NULL));
2785: PetscCall(MatDestroy(&Pmat));
2786: }
2787: }
2789: PetscCall(TSGetAdapt(ts, &ts->adapt));
2790: PetscCall(TSAdaptSetDefaultType(ts->adapt, ts->default_adapt_type));
2792: PetscTryTypeMethod(ts, setup);
2794: PetscCall(TSSetExactFinalTimeDefault(ts));
2796: /* In the case where we've set a DMTSFunction or what have you, we need the default SNESFunction
2797: to be set right but can't do it elsewhere due to the overreliance on ctx=ts.
2798: */
2799: PetscCall(TSGetDM(ts, &dm));
2800: PetscCall(DMSNESGetFunction(dm, &func, NULL));
2801: if (!func) PetscCall(DMSNESSetFunction(dm, SNESTSFormFunction, ts));
2803: /* If the SNES doesn't have a jacobian set and the TS has an ijacobian or rhsjacobian set, set the SNES to use it.
2804: Otherwise, the SNES will use coloring internally to form the Jacobian.
2805: */
2806: PetscCall(DMSNESGetJacobian(dm, &jac, NULL));
2807: PetscCall(DMTSGetIJacobian(dm, &ijac, NULL));
2808: PetscCall(DMTSGetI2Jacobian(dm, &i2jac, NULL));
2809: PetscCall(DMTSGetRHSJacobian(dm, &rhsjac, NULL));
2810: if (!jac && (ijac || i2jac || rhsjac)) PetscCall(DMSNESSetJacobian(dm, SNESTSFormJacobian, ts));
2812: /* if time integration scheme has a starting method, call it */
2813: PetscTryTypeMethod(ts, startingmethod);
2815: ts->setupcalled = PETSC_TRUE;
2816: PetscFunctionReturn(PETSC_SUCCESS);
2817: }
2819: /*@
2820: TSReset - Resets a `TS` context to the state it was in before `TSSetUp()` was called and removes any allocated `Vec` and `Mat` from its data structures
2822: Collective
2824: Input Parameter:
2825: . ts - the `TS` context obtained from `TSCreate()`
2827: Level: developer
2829: Notes:
2830: Any options set on the `TS` object, including those set with `TSSetFromOptions()` remain.
2832: See also `TSSetResize()` to change the size of the system being integrated (for example by adaptive mesh refinement) during the time integration.
2834: .seealso: [](ch_ts), `TS`, `TSCreate()`, `TSSetUp()`, `TSDestroy()`, `TSSetResize()`
2835: @*/
2836: PetscErrorCode TSReset(TS ts)
2837: {
2838: TS_RHSSplitLink ilink = ts->tsrhssplit, next;
2840: PetscFunctionBegin;
2843: PetscTryTypeMethod(ts, reset);
2844: if (ts->snes) PetscCall(SNESReset(ts->snes));
2845: if (ts->adapt) PetscCall(TSAdaptReset(ts->adapt));
2847: PetscCall(MatDestroy(&ts->Arhs));
2848: PetscCall(MatDestroy(&ts->Brhs));
2849: PetscCall(VecDestroy(&ts->Frhs));
2850: PetscCall(VecDestroy(&ts->vec_sol));
2851: PetscCall(VecDestroy(&ts->vec_sol0));
2852: PetscCall(VecDestroy(&ts->vec_dot));
2853: PetscCall(VecDestroy(&ts->vatol));
2854: PetscCall(VecDestroy(&ts->vrtol));
2855: PetscCall(VecDestroyVecs(ts->nwork, &ts->work));
2857: PetscCall(MatDestroy(&ts->Jacprhs));
2858: PetscCall(MatDestroy(&ts->Jacp));
2859: if (ts->forward_solve) PetscCall(TSForwardReset(ts));
2860: if (ts->quadraturets) {
2861: PetscCall(TSReset(ts->quadraturets));
2862: PetscCall(VecDestroy(&ts->vec_costintegrand));
2863: }
2864: while (ilink) {
2865: next = ilink->next;
2866: PetscCall(TSDestroy(&ilink->ts));
2867: PetscCall(PetscFree(ilink->splitname));
2868: PetscCall(ISDestroy(&ilink->is));
2869: PetscCall(PetscFree(ilink));
2870: ilink = next;
2871: }
2872: ts->tsrhssplit = NULL;
2873: ts->num_rhs_splits = 0;
2874: if (ts->eval_times) {
2875: PetscCall(PetscFree(ts->eval_times->time_points));
2876: PetscCall(PetscFree(ts->eval_times->sol_times));
2877: PetscCall(VecDestroyVecs(ts->eval_times->num_time_points, &ts->eval_times->sol_vecs));
2878: PetscCall(PetscFree(ts->eval_times));
2879: }
2880: ts->rhsjacobian.time = PETSC_MIN_REAL;
2881: ts->rhsjacobian.scale = 1.0;
2882: ts->ijacobian.shift = 1.0;
2883: ts->setupcalled = PETSC_FALSE;
2884: PetscFunctionReturn(PETSC_SUCCESS);
2885: }
2887: static PetscErrorCode TSResizeReset(TS);
2889: /*@
2890: TSDestroy - Destroys the timestepper context that was created
2891: with `TSCreate()`.
2893: Collective
2895: Input Parameter:
2896: . ts - the `TS` context obtained from `TSCreate()`
2898: Level: beginner
2900: .seealso: [](ch_ts), `TS`, `TSCreate()`, `TSSetUp()`, `TSSolve()`
2901: @*/
2902: PetscErrorCode TSDestroy(TS *ts)
2903: {
2904: PetscFunctionBegin;
2905: if (!*ts) PetscFunctionReturn(PETSC_SUCCESS);
2907: if (--((PetscObject)*ts)->refct > 0) {
2908: *ts = NULL;
2909: PetscFunctionReturn(PETSC_SUCCESS);
2910: }
2912: PetscCall(TSReset(*ts));
2913: PetscCall(TSAdjointReset(*ts));
2914: if ((*ts)->forward_solve) PetscCall(TSForwardReset(*ts));
2915: PetscCall(TSResizeReset(*ts));
2917: /* if memory was published with SAWs then destroy it */
2918: PetscCall(PetscObjectSAWsViewOff((PetscObject)*ts));
2919: PetscTryTypeMethod(*ts, destroy);
2921: PetscCall(TSTrajectoryDestroy(&(*ts)->trajectory));
2923: PetscCall(TSAdaptDestroy(&(*ts)->adapt));
2924: PetscCall(TSEventDestroy(&(*ts)->event));
2926: PetscCall(SNESDestroy(&(*ts)->snes));
2927: PetscCall(SNESDestroy(&(*ts)->snesrhssplit));
2928: PetscCall(DMDestroy(&(*ts)->dm));
2929: PetscCall(TSMonitorCancel(*ts));
2930: PetscCall(TSAdjointMonitorCancel(*ts));
2932: PetscCall(TSDestroy(&(*ts)->quadraturets));
2933: PetscCall(PetscHeaderDestroy(ts));
2934: PetscFunctionReturn(PETSC_SUCCESS);
2935: }
2937: /*@
2938: TSSetSNES - Set the `SNES` (nonlinear solver) to be used by the `TS` timestepping context
2940: Collective
2942: Input Parameters:
2943: + ts - the `TS` context obtained from `TSCreate()`
2944: - snes - the nonlinear solver context
2946: Level: developer
2948: Note:
2949: Most users should obtain the `SNES` by calling `TSGetSNES()` rather than setting it with this function.
2951: .seealso: [](ch_ts), `TS`, `SNES`, `TSCreate()`, `TSSetUp()`, `TSSolve()`, `TSGetKSP()`, `TSIsImplicit()`, `TSGetSNES()`
2952: @*/
2953: PetscErrorCode TSSetSNES(TS ts, SNES snes)
2954: {
2955: PetscErrorCode (*func)(SNES, Vec, Mat, Mat, void *);
2957: PetscFunctionBegin;
2960: PetscCall(PetscObjectReference((PetscObject)snes));
2961: PetscCall(SNESDestroy(&ts->snes));
2962: ts->snes = snes;
2963: PetscCall(SNESSetFunction(ts->snes, NULL, SNESTSFormFunction, ts));
2964: PetscCall(SNESGetJacobian(ts->snes, NULL, NULL, &func, NULL));
2965: if (func == SNESTSFormJacobian) PetscCall(SNESSetJacobian(ts->snes, NULL, NULL, SNESTSFormJacobian, ts));
2966: PetscFunctionReturn(PETSC_SUCCESS);
2967: }
2969: /*@
2970: TSGetSNES - Returns the `SNES` (nonlinear solver) associated with
2971: a `TS` (timestepper) context.
2973: Not Collective, but `snes` is parallel if `ts` is parallel
2975: Input Parameter:
2976: . ts - the `TS` context obtained from `TSCreate()`
2978: Output Parameter:
2979: . snes - the nonlinear solver context
2981: Level: beginner
2983: Notes:
2984: The user can then directly manipulate the `SNES` context to set various
2985: options, etc. Likewise, the user can then extract and manipulate the
2986: `KSP`, and `PC` contexts as well.
2988: For linear problems, use `TSGetKSP()`.
2990: For integrators that do not use `SNES` (that is, explicit methods),
2991: the `snes` exists but is not used. Use `TSIsImplicit()` to determine if the
2992: method is implicit and uses `snes`.
2994: Developer Note:
2995: `TS` manages the life-cycle of the `SNES` object for all `TSType` for the life-time of the `TS` object,
2996: even explicit methods that do not use `SNES`. This is so that `SNES` options are retained between changes to the `TSType` with `TSSetType()`.
2998: .seealso: [](ch_ts), `TS`, `SNES`, `TSCreate()`, `TSSetUp()`, `TSSolve()`, `TSGetKSP()`, `TSIsImplicit()`
2999: @*/
3000: PetscErrorCode TSGetSNES(TS ts, SNES *snes)
3001: {
3002: PetscFunctionBegin;
3004: PetscAssertPointer(snes, 2);
3005: if (!ts->snes) {
3006: PetscCall(SNESCreate(PetscObjectComm((PetscObject)ts), &ts->snes));
3007: PetscCall(PetscObjectSetOptions((PetscObject)ts->snes, ((PetscObject)ts)->options));
3008: PetscCall(SNESSetFunction(ts->snes, NULL, SNESTSFormFunction, ts));
3009: PetscCall(PetscObjectIncrementTabLevel((PetscObject)ts->snes, (PetscObject)ts, 1));
3010: if (ts->dm) PetscCall(SNESSetDM(ts->snes, ts->dm));
3011: if (ts->problem_type == TS_LINEAR) PetscCall(SNESSetType(ts->snes, SNESKSPONLY));
3012: }
3013: *snes = ts->snes;
3014: PetscFunctionReturn(PETSC_SUCCESS);
3015: }
3017: /*@
3018: TSIsImplicit - Indicates if a `TS` represents an implicit integrator that uses `SNES`
3020: Not Collective
3022: Input Parameter:
3023: . ts - the `TS` context obtained from `TSCreate()`
3025: Output Parameter:
3026: . isimplicit - if the integrator is implicit and uses either `SNES` or `KSP`
3028: Level: beginner
3030: Note:
3031: For integrators that do not use `SNES` (that is, explicit methods), `snes` exists but is not used.
3033: .seealso: [](ch_ts), `TS`, `SNES`, `TSCreate()`, `TSSetUp()`, `TSSolve()`, `TSGetKSP()`, `TSGetSNES()`
3034: @*/
3035: PetscErrorCode TSIsImplicit(TS ts, PetscBool *isimplicit)
3036: {
3037: PetscFunctionBegin;
3039: PetscAssertPointer(isimplicit, 2);
3040: *isimplicit = ts->usessnes;
3041: PetscFunctionReturn(PETSC_SUCCESS);
3042: }
3044: /*@
3045: TSGetKSP - Returns the `KSP` (linear solver) associated with
3046: a `TS` (timestepper) context.
3048: Not Collective, but `ksp` is parallel if `ts` is parallel
3050: Input Parameter:
3051: . ts - the `TS` context obtained from `TSCreate()`
3053: Output Parameter:
3054: . ksp - the nonlinear solver context
3056: Level: beginner
3058: Notes:
3059: The user can then directly manipulate the `KSP` context to set various
3060: options, etc. Likewise, the user can then extract and manipulate the
3061: `PC` context as well.
3063: For nonlinear problems (`TS_NONLINEAR`), use `TSGetSNES()` followed by `SNESGetKSP()`.
3065: For integrators that do not use `KSP` (that is, explicit methods),
3066: `TSGetKSP()` returns a `ksp` that is not used. Use `TSIsImplicit()` to determine if
3067: the `ksp` is actually used.
3069: .seealso: [](ch_ts), `TS`, `SNES`, `KSP`, `TSCreate()`, `TSSetUp()`, `TSSolve()`, `TSGetSNES()`, `TSIsImplicit()`
3070: @*/
3071: PetscErrorCode TSGetKSP(TS ts, KSP *ksp)
3072: {
3073: SNES snes;
3075: PetscFunctionBegin;
3077: PetscAssertPointer(ksp, 2);
3078: PetscCheck(((PetscObject)ts)->type_name, PETSC_COMM_SELF, PETSC_ERR_ARG_NULL, "KSP is not created yet. Call TSSetType() first");
3079: PetscCheck(ts->problem_type == TS_LINEAR, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "For linear problems only; use TSGetSNES() then SNESGetKSP()");
3080: PetscCall(TSGetSNES(ts, &snes));
3081: PetscCall(SNESGetKSP(snes, ksp));
3082: PetscFunctionReturn(PETSC_SUCCESS);
3083: }
3085: /* ----------- Routines to set solver parameters ---------- */
3087: /*@
3088: TSSetMaxSteps - Sets the maximum number of steps to use.
3090: Logically Collective
3092: Input Parameters:
3093: + ts - the `TS` context obtained from `TSCreate()`
3094: - maxsteps - maximum number of steps to use
3096: Options Database Key:
3097: . -ts_max_steps maxsteps - Sets maxsteps
3099: Level: intermediate
3101: Note:
3102: Use `PETSC_DETERMINE` to reset the maximum number of steps to the default from when the object's type was set
3104: The default maximum number of steps is 5,000
3106: Fortran Note:
3107: Use `PETSC_DETERMINE_INTEGER`
3109: .seealso: [](ch_ts), `TS`, `TSGetMaxSteps()`, `TSSetMaxTime()`, `TSSetExactFinalTime()`
3110: @*/
3111: PetscErrorCode TSSetMaxSteps(TS ts, PetscInt maxsteps)
3112: {
3113: PetscFunctionBegin;
3116: if (maxsteps == PETSC_DETERMINE) {
3117: ts->max_steps = ts->default_max_steps;
3118: } else {
3119: PetscCheck(maxsteps >= 0, PetscObjectComm((PetscObject)ts), PETSC_ERR_ARG_OUTOFRANGE, "Maximum number of steps must be non-negative");
3120: ts->max_steps = maxsteps;
3121: }
3122: PetscFunctionReturn(PETSC_SUCCESS);
3123: }
3125: /*@
3126: TSGetMaxSteps - Gets the maximum number of steps to use.
3128: Not Collective
3130: Input Parameter:
3131: . ts - the `TS` context obtained from `TSCreate()`
3133: Output Parameter:
3134: . maxsteps - maximum number of steps to use
3136: Level: advanced
3138: .seealso: [](ch_ts), `TS`, `TSSetMaxSteps()`, `TSGetMaxTime()`, `TSSetMaxTime()`
3139: @*/
3140: PetscErrorCode TSGetMaxSteps(TS ts, PetscInt *maxsteps)
3141: {
3142: PetscFunctionBegin;
3144: PetscAssertPointer(maxsteps, 2);
3145: *maxsteps = ts->max_steps;
3146: PetscFunctionReturn(PETSC_SUCCESS);
3147: }
3149: /*@
3150: TSSetRunSteps - Sets the maximum number of steps to take in each call to `TSSolve()`.
3152: If the step count when `TSSolve()` is `start_step`, this will stop the simulation once `current_step - start_step >= run_steps`.
3153: Comparatively, `TSSetMaxSteps()` will stop if `current_step >= max_steps`.
3154: The simulation will stop when either condition is reached.
3156: Logically Collective
3158: Input Parameters:
3159: + ts - the `TS` context obtained from `TSCreate()`
3160: - runsteps - maximum number of steps to take in each call to `TSSolve()`;
3162: Options Database Key:
3163: . -ts_run_steps runsteps - Sets runsteps
3165: Level: intermediate
3167: Note:
3168: The default is `PETSC_UNLIMITED`
3170: .seealso: [](ch_ts), `TS`, `TSGetRunSteps()`, `TSSetMaxTime()`, `TSSetExactFinalTime()`, `TSSetMaxSteps()`
3171: @*/
3172: PetscErrorCode TSSetRunSteps(TS ts, PetscInt runsteps)
3173: {
3174: PetscFunctionBegin;
3177: if (runsteps == PETSC_DETERMINE) {
3178: ts->run_steps = PETSC_UNLIMITED;
3179: } else {
3180: PetscCheck(runsteps >= 0, PetscObjectComm((PetscObject)ts), PETSC_ERR_ARG_OUTOFRANGE, "Max number of steps to take in each call to TSSolve must be non-negative");
3181: ts->run_steps = runsteps;
3182: }
3183: PetscFunctionReturn(PETSC_SUCCESS);
3184: }
3186: /*@
3187: TSGetRunSteps - Gets the maximum number of steps to take in each call to `TSSolve()`.
3189: Not Collective
3191: Input Parameter:
3192: . ts - the `TS` context obtained from `TSCreate()`
3194: Output Parameter:
3195: . runsteps - maximum number of steps to take in each call to `TSSolve`.
3197: Level: advanced
3199: .seealso: [](ch_ts), `TS`, `TSSetRunSteps()`, `TSGetMaxTime()`, `TSSetMaxTime()`, `TSGetMaxSteps()`
3200: @*/
3201: PetscErrorCode TSGetRunSteps(TS ts, PetscInt *runsteps)
3202: {
3203: PetscFunctionBegin;
3205: PetscAssertPointer(runsteps, 2);
3206: *runsteps = ts->run_steps;
3207: PetscFunctionReturn(PETSC_SUCCESS);
3208: }
3210: /*@
3211: TSSetMaxTime - Sets the maximum (or final) time for timestepping.
3213: Logically Collective
3215: Input Parameters:
3216: + ts - the `TS` context obtained from `TSCreate()`
3217: - maxtime - final time to step to
3219: Options Database Key:
3220: . -ts_max_time maxtime - Sets maxtime
3222: Level: intermediate
3224: Notes:
3225: Use `PETSC_DETERMINE` to reset the maximum time to the default from when the object's type was set
3227: The default maximum time is 5.0
3229: Fortran Note:
3230: Use `PETSC_DETERMINE_REAL`
3232: .seealso: [](ch_ts), `TS`, `TSGetMaxTime()`, `TSSetMaxSteps()`, `TSSetExactFinalTime()`
3233: @*/
3234: PetscErrorCode TSSetMaxTime(TS ts, PetscReal maxtime)
3235: {
3236: PetscFunctionBegin;
3239: if (maxtime == PETSC_DETERMINE) {
3240: ts->max_time = ts->default_max_time;
3241: } else {
3242: ts->max_time = maxtime;
3243: }
3244: PetscFunctionReturn(PETSC_SUCCESS);
3245: }
3247: /*@
3248: TSGetMaxTime - Gets the maximum (or final) time for timestepping.
3250: Not Collective
3252: Input Parameter:
3253: . ts - the `TS` context obtained from `TSCreate()`
3255: Output Parameter:
3256: . maxtime - final time to step to
3258: Level: advanced
3260: .seealso: [](ch_ts), `TS`, `TSSetMaxTime()`, `TSGetMaxSteps()`, `TSSetMaxSteps()`
3261: @*/
3262: PetscErrorCode TSGetMaxTime(TS ts, PetscReal *maxtime)
3263: {
3264: PetscFunctionBegin;
3266: PetscAssertPointer(maxtime, 2);
3267: *maxtime = ts->max_time;
3268: PetscFunctionReturn(PETSC_SUCCESS);
3269: }
3271: // PetscClangLinter pragma disable: -fdoc-*
3272: /*@
3273: TSSetInitialTimeStep - Deprecated, use `TSSetTime()` and `TSSetTimeStep()`.
3275: Level: deprecated
3277: @*/
3278: PetscErrorCode TSSetInitialTimeStep(TS ts, PetscReal initial_time, PetscReal time_step)
3279: {
3280: PetscFunctionBegin;
3282: PetscCall(TSSetTime(ts, initial_time));
3283: PetscCall(TSSetTimeStep(ts, time_step));
3284: PetscFunctionReturn(PETSC_SUCCESS);
3285: }
3287: // PetscClangLinter pragma disable: -fdoc-*
3288: /*@
3289: TSGetDuration - Deprecated, use `TSGetMaxSteps()` and `TSGetMaxTime()`.
3291: Level: deprecated
3293: @*/
3294: PetscErrorCode TSGetDuration(TS ts, PetscInt *maxsteps, PetscReal *maxtime)
3295: {
3296: PetscFunctionBegin;
3298: if (maxsteps) {
3299: PetscAssertPointer(maxsteps, 2);
3300: *maxsteps = ts->max_steps;
3301: }
3302: if (maxtime) {
3303: PetscAssertPointer(maxtime, 3);
3304: *maxtime = ts->max_time;
3305: }
3306: PetscFunctionReturn(PETSC_SUCCESS);
3307: }
3309: // PetscClangLinter pragma disable: -fdoc-*
3310: /*@
3311: TSSetDuration - Deprecated, use `TSSetMaxSteps()` and `TSSetMaxTime()`.
3313: Level: deprecated
3315: @*/
3316: PetscErrorCode TSSetDuration(TS ts, PetscInt maxsteps, PetscReal maxtime)
3317: {
3318: PetscFunctionBegin;
3319: if (maxsteps != PETSC_CURRENT) PetscCall(TSSetMaxSteps(ts, maxsteps));
3320: if (maxtime != (PetscReal)PETSC_CURRENT) PetscCall(TSSetMaxTime(ts, maxtime));
3321: PetscFunctionReturn(PETSC_SUCCESS);
3322: }
3324: // PetscClangLinter pragma disable: -fdoc-*
3325: /*@
3326: TSGetTimeStepNumber - Deprecated, use `TSGetStepNumber()`.
3328: Level: deprecated
3330: @*/
3331: PetscErrorCode TSGetTimeStepNumber(TS ts, PetscInt *steps)
3332: {
3333: return TSGetStepNumber(ts, steps);
3334: }
3336: // PetscClangLinter pragma disable: -fdoc-*
3337: /*@
3338: TSGetTotalSteps - Deprecated, use `TSGetStepNumber()`.
3340: Level: deprecated
3342: @*/
3343: PetscErrorCode TSGetTotalSteps(TS ts, PetscInt *steps)
3344: {
3345: return TSGetStepNumber(ts, steps);
3346: }
3348: /*@
3349: TSSetSolution - Sets the initial solution vector
3350: for use by the `TS` routines.
3352: Logically Collective
3354: Input Parameters:
3355: + ts - the `TS` context obtained from `TSCreate()`
3356: - u - the solution vector
3358: Level: beginner
3360: .seealso: [](ch_ts), `TS`, `TSSetSolutionFunction()`, `TSGetSolution()`, `TSCreate()`
3361: @*/
3362: PetscErrorCode TSSetSolution(TS ts, Vec u)
3363: {
3364: DM dm;
3366: PetscFunctionBegin;
3369: PetscCall(PetscObjectReference((PetscObject)u));
3370: PetscCall(VecDestroy(&ts->vec_sol));
3371: ts->vec_sol = u;
3373: PetscCall(TSGetDM(ts, &dm));
3374: PetscCall(DMShellSetGlobalVector(dm, u));
3375: PetscFunctionReturn(PETSC_SUCCESS);
3376: }
3378: /*@
3379: TSSetPreStep - Sets the general-purpose function
3380: called once at the beginning of each time step.
3382: Logically Collective
3384: Input Parameters:
3385: + ts - The `TS` context obtained from `TSCreate()`
3386: - func - The function
3388: Calling sequence of `func`:
3389: . ts - the `TS` context
3391: Level: intermediate
3393: .seealso: [](ch_ts), `TS`, `TSSetPreStage()`, `TSSetPostStage()`, `TSSetPostStep()`, `TSStep()`, `TSRestartStep()`
3394: @*/
3395: PetscErrorCode TSSetPreStep(TS ts, PetscErrorCode (*func)(TS ts))
3396: {
3397: PetscFunctionBegin;
3399: ts->prestep = func;
3400: PetscFunctionReturn(PETSC_SUCCESS);
3401: }
3403: /*@
3404: TSPreStep - Runs the user-defined pre-step function provided with `TSSetPreStep()`
3406: Collective
3408: Input Parameter:
3409: . ts - The `TS` context obtained from `TSCreate()`
3411: Level: developer
3413: Note:
3414: `TSPreStep()` is typically used within time stepping implementations,
3415: so most users would not generally call this routine themselves.
3417: .seealso: [](ch_ts), `TS`, `TSSetPreStep()`, `TSPreStage()`, `TSPostStage()`, `TSPostStep()`
3418: @*/
3419: PetscErrorCode TSPreStep(TS ts)
3420: {
3421: PetscFunctionBegin;
3423: if (ts->prestep) {
3424: Vec U;
3425: VecState Ustate;
3426: PetscBool same;
3428: PetscCall(TSGetSolution(ts, &U));
3429: PetscCall(VecGetState(U, &Ustate));
3430: PetscCallBack("TS callback preset", (*ts->prestep)(ts));
3431: PetscCall(TSGetSolution(ts, &U));
3432: PetscCall(VecStateCompareUpdate(U, &Ustate, &same));
3433: if (!same) PetscCall(TSRestartStep(ts));
3434: }
3435: PetscFunctionReturn(PETSC_SUCCESS);
3436: }
3438: /*@
3439: TSSetPreStage - Sets the general-purpose function
3440: called once at the beginning of each stage.
3442: Logically Collective
3444: Input Parameters:
3445: + ts - The `TS` context obtained from `TSCreate()`
3446: - func - The function
3448: Calling sequence of `func`:
3449: + ts - the `TS` context
3450: - stagetime - the stage time
3452: Level: intermediate
3454: Note:
3455: There may be several stages per time step. If the solve for a given stage fails, the step may be rejected and retried.
3456: The time step number being computed can be queried using `TSGetStepNumber()` and the total size of the step being
3457: attempted can be obtained using `TSGetTimeStep()`. The time at the start of the step is available via `TSGetTime()`.
3459: .seealso: [](ch_ts), `TS`, `TSSetPostStage()`, `TSSetPreStep()`, `TSSetPostStep()`, `TSGetApplicationContext()`
3460: @*/
3461: PetscErrorCode TSSetPreStage(TS ts, PetscErrorCode (*func)(TS ts, PetscReal stagetime))
3462: {
3463: PetscFunctionBegin;
3465: ts->prestage = func;
3466: PetscFunctionReturn(PETSC_SUCCESS);
3467: }
3469: /*@
3470: TSSetPostStage - Sets the general-purpose function
3471: called once at the end of each stage.
3473: Logically Collective
3475: Input Parameters:
3476: + ts - The `TS` context obtained from `TSCreate()`
3477: - func - The function
3479: Calling sequence of `func`:
3480: + ts - the `TS` context
3481: . stagetime - the stage time
3482: . stageindex - the stage index
3483: - Y - Array of vectors (of size = total number of stages) with the stage solutions
3485: Level: intermediate
3487: Note:
3488: There may be several stages per time step. If the solve for a given stage fails, the step may be rejected and retried.
3489: The time step number being computed can be queried using `TSGetStepNumber()` and the total size of the step being
3490: attempted can be obtained using `TSGetTimeStep()`. The time at the start of the step is available via `TSGetTime()`.
3492: .seealso: [](ch_ts), `TS`, `TSSetPreStage()`, `TSSetPreStep()`, `TSSetPostStep()`, `TSGetApplicationContext()`
3493: @*/
3494: PetscErrorCode TSSetPostStage(TS ts, PetscErrorCode (*func)(TS ts, PetscReal stagetime, PetscInt stageindex, Vec *Y))
3495: {
3496: PetscFunctionBegin;
3498: ts->poststage = func;
3499: PetscFunctionReturn(PETSC_SUCCESS);
3500: }
3502: /*@
3503: TSSetPostEvaluate - Sets the general-purpose function
3504: called at the end of each step evaluation.
3506: Logically Collective
3508: Input Parameters:
3509: + ts - The `TS` context obtained from `TSCreate()`
3510: - func - The function
3512: Calling sequence of `func`:
3513: . ts - the `TS` context
3515: Level: intermediate
3517: Note:
3518: The function set by `TSSetPostEvaluate()` is called after the solution is evaluated, or after the step rollback.
3519: Inside the `func` callback, the solution vector can be obtained with `TSGetSolution()`, and modified, if need be.
3520: The time step can be obtained with `TSGetTimeStep()`, and the time at the start of the step - via `TSGetTime()`.
3521: The potential changes to the solution vector introduced by event handling (`postevent()`) are not relevant for `TSSetPostEvaluate()`,
3522: but are relevant for `TSSetPostStep()`, according to the function call scheme in `TSSolve()`, as shown below
3523: .vb
3524: ...
3525: Step()
3526: PostEvaluate()
3527: EventHandling()
3528: step_rollback ? PostEvaluate() : PostStep()
3529: ...
3530: .ve
3531: where EventHandling() may result in one of the following three outcomes
3532: .vb
3533: (1) | successful step | solution intact
3534: (2) | successful step | solution modified by `postevent()`
3535: (3) | step_rollback | solution rolled back
3536: .ve
3538: .seealso: [](ch_ts), `TS`, `TSSetPreStage()`, `TSSetPreStep()`, `TSSetPostStep()`, `TSGetApplicationContext()`
3539: @*/
3540: PetscErrorCode TSSetPostEvaluate(TS ts, PetscErrorCode (*func)(TS ts))
3541: {
3542: PetscFunctionBegin;
3544: ts->postevaluate = func;
3545: PetscFunctionReturn(PETSC_SUCCESS);
3546: }
3548: /*@
3549: TSPreStage - Runs the user-defined pre-stage function set using `TSSetPreStage()`
3551: Collective
3553: Input Parameters:
3554: + ts - The `TS` context obtained from `TSCreate()`
3555: - stagetime - The absolute time of the current stage
3557: Level: developer
3559: Note:
3560: `TSPreStage()` is typically used within time stepping implementations,
3561: most users would not generally call this routine themselves.
3563: .seealso: [](ch_ts), `TS`, `TSPostStage()`, `TSSetPreStep()`, `TSPreStep()`, `TSPostStep()`
3564: @*/
3565: PetscErrorCode TSPreStage(TS ts, PetscReal stagetime)
3566: {
3567: PetscFunctionBegin;
3569: if (ts->prestage) PetscCallBack("TS callback prestage", (*ts->prestage)(ts, stagetime));
3570: PetscFunctionReturn(PETSC_SUCCESS);
3571: }
3573: /*@
3574: TSPostStage - Runs the user-defined post-stage function set using `TSSetPostStage()`
3576: Collective
3578: Input Parameters:
3579: + ts - The `TS` context obtained from `TSCreate()`
3580: . stagetime - The absolute time of the current stage
3581: . stageindex - Stage number
3582: - Y - Array of vectors (of size = total number of stages) with the stage solutions
3584: Level: developer
3586: Note:
3587: `TSPostStage()` is typically used within time stepping implementations,
3588: most users would not generally call this routine themselves.
3590: .seealso: [](ch_ts), `TS`, `TSPreStage()`, `TSSetPreStep()`, `TSPreStep()`, `TSPostStep()`
3591: @*/
3592: PetscErrorCode TSPostStage(TS ts, PetscReal stagetime, PetscInt stageindex, Vec Y[])
3593: {
3594: PetscFunctionBegin;
3596: if (ts->poststage) PetscCallBack("TS callback poststage", (*ts->poststage)(ts, stagetime, stageindex, Y));
3597: PetscFunctionReturn(PETSC_SUCCESS);
3598: }
3600: /*@
3601: TSPostEvaluate - Runs the user-defined post-evaluate function set using `TSSetPostEvaluate()`
3603: Collective
3605: Input Parameter:
3606: . ts - The `TS` context obtained from `TSCreate()`
3608: Level: developer
3610: Note:
3611: `TSPostEvaluate()` is typically used within time stepping implementations,
3612: most users would not generally call this routine themselves.
3614: .seealso: [](ch_ts), `TS`, `TSSetPostEvaluate()`, `TSSetPreStep()`, `TSPreStep()`, `TSPostStep()`
3615: @*/
3616: PetscErrorCode TSPostEvaluate(TS ts)
3617: {
3618: PetscFunctionBegin;
3620: if (ts->postevaluate) {
3621: Vec U;
3622: VecState Ustate;
3623: PetscBool same;
3625: PetscCall(TSGetSolution(ts, &U));
3626: PetscCall(VecGetState(U, &Ustate));
3627: PetscCallBack("TS callback postevaluate", (*ts->postevaluate)(ts));
3628: PetscCall(VecStateCompareUpdate(U, &Ustate, &same));
3629: if (!same) PetscCall(TSRestartStep(ts));
3630: }
3631: PetscFunctionReturn(PETSC_SUCCESS);
3632: }
3634: /*@
3635: TSSetPostStep - Sets the general-purpose function
3636: called once at the end of each successful time step.
3638: Logically Collective
3640: Input Parameters:
3641: + ts - The `TS` context obtained from `TSCreate()`
3642: - func - The function
3644: Calling sequence of `func`:
3645: . ts - the `TS` context
3647: Level: intermediate
3649: Note:
3650: The function set by `TSSetPostStep()` is called after each successful step. If the event handler locates an event at the
3651: given step, and `postevent()` modifies the solution vector, the solution vector obtained by `TSGetSolution()` inside `func` will
3652: contain the changes. To get the solution without these changes, use `TSSetPostEvaluate()` to set the appropriate callback.
3653: The scheme of the relevant function calls in `TSSolve()` is shown below
3654: .vb
3655: ...
3656: Step()
3657: PostEvaluate()
3658: EventHandling()
3659: step_rollback ? PostEvaluate() : PostStep()
3660: ...
3661: .ve
3662: where EventHandling() may result in one of the following three outcomes
3663: .vb
3664: (1) | successful step | solution intact
3665: (2) | successful step | solution modified by `postevent()`
3666: (3) | step_rollback | solution rolled back
3667: .ve
3669: .seealso: [](ch_ts), `TS`, `TSSetPreStep()`, `TSSetPreStage()`, `TSSetPostEvaluate()`, `TSGetTimeStep()`, `TSGetStepNumber()`, `TSGetTime()`, `TSRestartStep()`
3670: @*/
3671: PetscErrorCode TSSetPostStep(TS ts, PetscErrorCode (*func)(TS ts))
3672: {
3673: PetscFunctionBegin;
3675: ts->poststep = func;
3676: PetscFunctionReturn(PETSC_SUCCESS);
3677: }
3679: /*@
3680: TSPostStep - Runs the user-defined post-step function that was set with `TSSetPostStep()`
3682: Collective
3684: Input Parameter:
3685: . ts - The `TS` context obtained from `TSCreate()`
3687: Note:
3688: `TSPostStep()` is typically used within time stepping implementations,
3689: so most users would not generally call this routine themselves.
3691: Level: developer
3693: .seealso: [](ch_ts), `TS`, `TSSetPreStep()`, `TSSetPreStage()`, `TSSetPostEvaluate()`, `TSGetTimeStep()`, `TSGetStepNumber()`, `TSGetTime()`, `TSSetPostStep()`
3694: @*/
3695: PetscErrorCode TSPostStep(TS ts)
3696: {
3697: PetscFunctionBegin;
3699: if (ts->poststep) {
3700: Vec U;
3701: VecState Ustate;
3702: PetscBool same;
3704: PetscCall(TSGetSolution(ts, &U));
3705: PetscCall(VecGetState(U, &Ustate));
3706: PetscCallBack("TS callback poststep", (*ts->poststep)(ts));
3707: PetscCall(TSGetSolution(ts, &U));
3708: PetscCall(VecStateCompareUpdate(U, &Ustate, &same));
3709: if (!same) PetscCall(TSRestartStep(ts));
3710: }
3711: PetscFunctionReturn(PETSC_SUCCESS);
3712: }
3714: /*@
3715: TSInterpolate - Interpolate the solution computed during the previous step to an arbitrary location in the interval
3717: Collective
3719: Input Parameters:
3720: + ts - time stepping context
3721: - t - time to interpolate to
3723: Output Parameter:
3724: . U - state at given time
3726: Level: intermediate
3728: Developer Notes:
3729: `TSInterpolate()` and the storing of previous steps/stages should be generalized to support delay differential equations and continuous adjoints.
3731: .seealso: [](ch_ts), `TS`, `TSSetExactFinalTime()`, `TSSolve()`
3732: @*/
3733: PetscErrorCode TSInterpolate(TS ts, PetscReal t, Vec U)
3734: {
3735: PetscFunctionBegin;
3738: PetscCheck(t >= ts->ptime_prev && t <= ts->ptime, PetscObjectComm((PetscObject)ts), PETSC_ERR_ARG_OUTOFRANGE, "Requested time %g not in last time steps [%g,%g]", (double)t, (double)ts->ptime_prev, (double)ts->ptime);
3739: PetscUseTypeMethod(ts, interpolate, t, U);
3740: PetscFunctionReturn(PETSC_SUCCESS);
3741: }
3743: /*@
3744: TSStep - Steps one time step
3746: Collective
3748: Input Parameter:
3749: . ts - the `TS` context obtained from `TSCreate()`
3751: Level: developer
3753: Notes:
3754: The public interface for the ODE/DAE solvers is `TSSolve()`, you should almost for sure be using that routine and not this routine.
3756: The hook set using `TSSetPreStep()` is called before each attempt to take the step. In general, the time step size may
3757: be changed due to adaptive error controller or solve failures. Note that steps may contain multiple stages.
3759: This may over-step the final time provided in `TSSetMaxTime()` depending on the time-step used. `TSSolve()` interpolates to exactly the
3760: time provided in `TSSetMaxTime()`. One can use `TSInterpolate()` to determine an interpolated solution within the final timestep.
3762: .seealso: [](ch_ts), `TS`, `TSCreate()`, `TSSetUp()`, `TSDestroy()`, `TSSolve()`, `TSSetPreStep()`, `TSSetPreStage()`, `TSSetPostStage()`, `TSInterpolate()`
3763: @*/
3764: PetscErrorCode TSStep(TS ts)
3765: {
3766: static PetscBool cite = PETSC_FALSE;
3767: PetscReal ptime;
3769: PetscFunctionBegin;
3771: PetscCall(PetscCitationsRegister("@article{tspaper,\n"
3772: " title = {{PETSc/TS}: A Modern Scalable {DAE/ODE} Solver Library},\n"
3773: " author = {Abhyankar, Shrirang and Brown, Jed and Constantinescu, Emil and Ghosh, Debojyoti and Smith, Barry F. and Zhang, Hong},\n"
3774: " journal = {arXiv e-preprints},\n"
3775: " eprint = {1806.01437},\n"
3776: " archivePrefix = {arXiv},\n"
3777: " year = {2018}\n}\n",
3778: &cite));
3779: PetscCall(TSSetUp(ts));
3780: PetscCall(TSTrajectorySetUp(ts->trajectory, ts));
3781: if (ts->eval_times)
3782: ts->eval_times->worktol = 0; /* In each step of TSSolve() 'eval_times->worktol' will be meaningfully defined (later) only once:
3783: in TSAdaptChoose() or TSEvent_dt_cap(), and then reused till the end of the step */
3785: PetscCheck(ts->max_time < PETSC_MAX_REAL || ts->run_steps != PETSC_INT_MAX || ts->max_steps != PETSC_INT_MAX, PetscObjectComm((PetscObject)ts), PETSC_ERR_ARG_WRONGSTATE, "You must call TSSetMaxTime(), TSSetMaxSteps(), or TSSetRunSteps() or use -ts_max_time <time>, -ts_max_steps <steps>, -ts_run_steps <steps>");
3786: PetscCheck(ts->exact_final_time != TS_EXACTFINALTIME_UNSPECIFIED, PetscObjectComm((PetscObject)ts), PETSC_ERR_ARG_WRONGSTATE, "You must call TSSetExactFinalTime() or use -ts_exact_final_time <stepover,interpolate,matchstep> before calling TSStep()");
3787: PetscCheck(ts->exact_final_time != TS_EXACTFINALTIME_MATCHSTEP || ts->adapt, PetscObjectComm((PetscObject)ts), PETSC_ERR_SUP, "Since TS is not adaptive you cannot use TS_EXACTFINALTIME_MATCHSTEP, suggest TS_EXACTFINALTIME_INTERPOLATE");
3789: if (!ts->vec_sol0) PetscCall(VecDuplicate(ts->vec_sol, &ts->vec_sol0));
3790: PetscCall(VecCopy(ts->vec_sol, ts->vec_sol0));
3791: ts->time_step0 = ts->time_step;
3793: if (!ts->steps) ts->ptime_prev = ts->ptime;
3794: ptime = ts->ptime;
3796: ts->ptime_prev_rollback = ts->ptime_prev;
3797: ts->reason = TS_CONVERGED_ITERATING;
3799: PetscCall(PetscLogEventBegin(TS_Step, ts, 0, 0, 0));
3800: PetscUseTypeMethod(ts, step);
3801: PetscCall(PetscLogEventEnd(TS_Step, ts, 0, 0, 0));
3803: if (ts->reason >= 0) {
3804: ts->ptime_prev = ptime;
3805: ts->steps++;
3806: ts->steprollback = PETSC_FALSE;
3807: ts->steprestart = PETSC_FALSE;
3808: ts->stepresize = PETSC_FALSE;
3809: }
3811: if (ts->reason < 0 && ts->errorifstepfailed) {
3812: PetscCall(TSMonitorCancel(ts));
3813: if (ts->usessnes && ts->snes) PetscCall(SNESMonitorCancel(ts->snes));
3814: PetscCheck(ts->reason != TS_DIVERGED_NONLINEAR_SOLVE, PetscObjectComm((PetscObject)ts), PETSC_ERR_NOT_CONVERGED, "TSStep has failed due to %s, increase -ts_max_snes_failures or use unlimited to attempt recovery", TSConvergedReasons[ts->reason]);
3815: SETERRQ(PetscObjectComm((PetscObject)ts), PETSC_ERR_NOT_CONVERGED, "TSStep has failed due to %s", TSConvergedReasons[ts->reason]);
3816: }
3817: PetscFunctionReturn(PETSC_SUCCESS);
3818: }
3820: /*@
3821: TSEvaluateWLTE - Evaluate the weighted local truncation error norm
3822: at the end of a time step with a given order of accuracy.
3824: Collective
3826: Input Parameters:
3827: + ts - time stepping context
3828: - wnormtype - norm type, either `NORM_2` or `NORM_INFINITY`
3830: Input/Output Parameter:
3831: . order - optional, desired order for the error evaluation or `PETSC_DECIDE`;
3832: on output, the actual order of the error evaluation
3834: Output Parameter:
3835: . wlte - the weighted local truncation error norm
3837: Level: advanced
3839: Note:
3840: If the timestepper cannot evaluate the error in a particular step
3841: (eg. in the first step or restart steps after event handling),
3842: this routine returns wlte=-1.0 .
3844: .seealso: [](ch_ts), `TS`, `TSStep()`, `TSAdapt`, `TSErrorWeightedNorm()`
3845: @*/
3846: PetscErrorCode TSEvaluateWLTE(TS ts, NormType wnormtype, PetscInt *order, PetscReal *wlte)
3847: {
3848: PetscFunctionBegin;
3852: if (order) PetscAssertPointer(order, 3);
3854: PetscAssertPointer(wlte, 4);
3855: PetscCheck(wnormtype == NORM_2 || wnormtype == NORM_INFINITY, PetscObjectComm((PetscObject)ts), PETSC_ERR_SUP, "No support for norm type %s", NormTypes[wnormtype]);
3856: PetscUseTypeMethod(ts, evaluatewlte, wnormtype, order, wlte);
3857: PetscFunctionReturn(PETSC_SUCCESS);
3858: }
3860: /*@
3861: TSEvaluateStep - Evaluate the solution at the end of a time step with a given order of accuracy.
3863: Collective
3865: Input Parameters:
3866: + ts - time stepping context
3867: . order - desired order of accuracy
3868: - done - whether the step was evaluated at this order (pass `NULL` to generate an error if not available)
3870: Output Parameter:
3871: . U - state at the end of the current step
3873: Level: advanced
3875: Notes:
3876: This function cannot be called until all stages have been evaluated.
3878: 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.
3880: .seealso: [](ch_ts), `TS`, `TSStep()`, `TSAdapt`
3881: @*/
3882: PetscErrorCode TSEvaluateStep(TS ts, PetscInt order, Vec U, PetscBool *done)
3883: {
3884: PetscFunctionBegin;
3888: PetscUseTypeMethod(ts, evaluatestep, order, U, done);
3889: PetscFunctionReturn(PETSC_SUCCESS);
3890: }
3892: /*@
3893: TSGetComputeInitialCondition - Get the function used to automatically compute an initial condition for the timestepping.
3895: Not collective
3897: Input Parameter:
3898: . ts - time stepping context
3900: Output Parameter:
3901: . initCondition - The function which computes an initial condition
3903: Calling sequence of `initCondition`:
3904: + ts - The timestepping context
3905: - u - The input vector in which the initial condition is stored
3907: Level: advanced
3909: .seealso: [](ch_ts), `TS`, `TSSetComputeInitialCondition()`, `TSComputeInitialCondition()`
3910: @*/
3911: PetscErrorCode TSGetComputeInitialCondition(TS ts, PetscErrorCode (**initCondition)(TS ts, Vec u))
3912: {
3913: PetscFunctionBegin;
3915: PetscAssertPointer(initCondition, 2);
3916: *initCondition = ts->ops->initcondition;
3917: PetscFunctionReturn(PETSC_SUCCESS);
3918: }
3920: /*@
3921: TSSetComputeInitialCondition - Set the function used to automatically compute an initial condition for the timestepping.
3923: Logically collective
3925: Input Parameters:
3926: + ts - time stepping context
3927: - initCondition - The function which computes an initial condition
3929: Calling sequence of `initCondition`:
3930: + ts - The timestepping context
3931: - e - The input vector in which the initial condition is to be stored
3933: Level: advanced
3935: .seealso: [](ch_ts), `TS`, `TSGetComputeInitialCondition()`, `TSComputeInitialCondition()`
3936: @*/
3937: PetscErrorCode TSSetComputeInitialCondition(TS ts, PetscErrorCode (*initCondition)(TS ts, Vec e))
3938: {
3939: PetscFunctionBegin;
3942: ts->ops->initcondition = initCondition;
3943: PetscFunctionReturn(PETSC_SUCCESS);
3944: }
3946: /*@
3947: TSComputeInitialCondition - Compute an initial condition for the timestepping using the function previously set with `TSSetComputeInitialCondition()`
3949: Collective
3951: Input Parameters:
3952: + ts - time stepping context
3953: - u - The `Vec` to store the condition in which will be used in `TSSolve()`
3955: Level: advanced
3957: .seealso: [](ch_ts), `TS`, `TSGetComputeInitialCondition()`, `TSSetComputeInitialCondition()`, `TSSolve()`
3958: @*/
3959: PetscErrorCode TSComputeInitialCondition(TS ts, Vec u)
3960: {
3961: PetscFunctionBegin;
3964: PetscTryTypeMethod(ts, initcondition, u);
3965: PetscFunctionReturn(PETSC_SUCCESS);
3966: }
3968: /*@
3969: TSGetComputeExactError - Get the function used to automatically compute the exact error for the timestepping.
3971: Not collective
3973: Input Parameter:
3974: . ts - time stepping context
3976: Output Parameter:
3977: . exactError - The function which computes the solution error
3979: Calling sequence of `exactError`:
3980: + ts - The timestepping context
3981: . u - The approximate solution vector
3982: - e - The vector in which the error is stored
3984: Level: advanced
3986: .seealso: [](ch_ts), `TS`, `TSComputeExactError()`
3987: @*/
3988: PetscErrorCode TSGetComputeExactError(TS ts, PetscErrorCode (**exactError)(TS ts, Vec u, Vec e))
3989: {
3990: PetscFunctionBegin;
3992: PetscAssertPointer(exactError, 2);
3993: *exactError = ts->ops->exacterror;
3994: PetscFunctionReturn(PETSC_SUCCESS);
3995: }
3997: /*@
3998: TSSetComputeExactError - Set the function used to automatically compute the exact error for the timestepping.
4000: Logically collective
4002: Input Parameters:
4003: + ts - time stepping context
4004: - exactError - The function which computes the solution error
4006: Calling sequence of `exactError`:
4007: + ts - The timestepping context
4008: . u - The approximate solution vector
4009: - e - The vector in which the error is stored
4011: Level: advanced
4013: .seealso: [](ch_ts), `TS`, `TSGetComputeExactError()`, `TSComputeExactError()`
4014: @*/
4015: PetscErrorCode TSSetComputeExactError(TS ts, PetscErrorCode (*exactError)(TS ts, Vec u, Vec e))
4016: {
4017: PetscFunctionBegin;
4020: ts->ops->exacterror = exactError;
4021: PetscFunctionReturn(PETSC_SUCCESS);
4022: }
4024: /*@
4025: TSComputeExactError - Compute the solution error for the timestepping using the function previously set with `TSSetComputeExactError()`
4027: Collective
4029: Input Parameters:
4030: + ts - time stepping context
4031: . u - The approximate solution
4032: - e - The `Vec` used to store the error
4034: Level: advanced
4036: .seealso: [](ch_ts), `TS`, `TSGetComputeInitialCondition()`, `TSSetComputeInitialCondition()`, `TSSolve()`
4037: @*/
4038: PetscErrorCode TSComputeExactError(TS ts, Vec u, Vec e)
4039: {
4040: PetscFunctionBegin;
4044: PetscTryTypeMethod(ts, exacterror, u, e);
4045: PetscFunctionReturn(PETSC_SUCCESS);
4046: }
4048: /*@
4049: TSSetResize - Sets the resize callbacks.
4051: Logically Collective
4053: Input Parameters:
4054: + ts - The `TS` context obtained from `TSCreate()`
4055: . rollback - Whether a resize will restart the step
4056: . setup - The setup function
4057: . transfer - The transfer function
4058: - ctx - [optional] The user-defined context
4060: Calling sequence of `setup`:
4061: + ts - the `TS` context
4062: . step - the current step
4063: . time - the current time
4064: . state - the current vector of state
4065: . resize - (output parameter) `PETSC_TRUE` if need resizing, `PETSC_FALSE` otherwise
4066: - ctx - user defined context
4068: Calling sequence of `transfer`:
4069: + ts - the `TS` context
4070: . nv - the number of vectors to be transferred
4071: . vecsin - array of vectors to be transferred
4072: . vecsout - array of transferred vectors
4073: - ctx - user defined context
4075: Notes:
4076: The `setup` function is called inside `TSSolve()` after `TSEventHandler()` or after `TSPostStep()`
4077: depending on the `rollback` value: if `rollback` is true, then these callbacks behave as error indicators
4078: and will flag the need to remesh and restart the current step. Otherwise, they will simply flag the solver
4079: that the size of the discrete problem has changed.
4080: In both cases, the solver will collect the needed vectors that will be
4081: transferred from the old to the new sizes using the `transfer` callback. These vectors will include the
4082: current solution vector, and other vectors needed by the specific solver used.
4083: For example, `TSBDF` uses previous solutions vectors to solve for the next time step.
4084: Other application specific objects associated with the solver, i.e. Jacobian matrices and `DM`,
4085: will be automatically reset if the sizes are changed and they must be specified again by the user
4086: inside the `transfer` function.
4087: The input and output arrays passed to `transfer` are allocated by PETSc.
4088: Vectors in `vecsout` must be created by the user.
4089: Ownership of vectors in `vecsout` is transferred to PETSc.
4091: Level: advanced
4093: .seealso: [](ch_ts), `TS`, `TSSetDM()`, `TSSetIJacobian()`, `TSSetRHSJacobian()`
4094: @*/
4095: PetscErrorCode TSSetResize(TS ts, PetscBool rollback, PetscErrorCode (*setup)(TS ts, PetscInt step, PetscReal time, Vec state, PetscBool *resize, PetscCtx ctx), PetscErrorCode (*transfer)(TS ts, PetscInt nv, Vec vecsin[], Vec vecsout[], PetscCtx ctx), PetscCtx ctx)
4096: {
4097: PetscFunctionBegin;
4099: ts->resizerollback = rollback;
4100: ts->resizesetup = setup;
4101: ts->resizetransfer = transfer;
4102: ts->resizectx = ctx;
4103: PetscFunctionReturn(PETSC_SUCCESS);
4104: }
4106: /*
4107: TSResizeRegisterOrRetrieve - Register or import vectors transferred with `TSResize()`.
4109: Collective
4111: Input Parameters:
4112: + ts - The `TS` context obtained from `TSCreate()`
4113: - flg - If `PETSC_TRUE` each TS implementation (e.g. `TSBDF`) will register vectors to be transferred, if `PETSC_FALSE` vectors will be imported from transferred vectors.
4115: Level: developer
4117: Note:
4118: `TSResizeRegisterOrRetrieve()` is declared PETSC_INTERN since it is
4119: used within time stepping implementations,
4120: so most users would not generally call this routine themselves.
4122: .seealso: [](ch_ts), `TS`, `TSSetResize()`
4123: @*/
4124: static PetscErrorCode TSResizeRegisterOrRetrieve(TS ts, PetscBool flg)
4125: {
4126: PetscFunctionBegin;
4128: PetscTryTypeMethod(ts, resizeregister, flg);
4129: /* PetscTryTypeMethod(adapt, resizeregister, flg); */
4130: PetscFunctionReturn(PETSC_SUCCESS);
4131: }
4133: static PetscErrorCode TSResizeReset(TS ts)
4134: {
4135: PetscFunctionBegin;
4137: PetscCall(PetscObjectListDestroy(&ts->resizetransferobjs));
4138: PetscFunctionReturn(PETSC_SUCCESS);
4139: }
4141: static PetscErrorCode TSResizeTransferVecs(TS ts, PetscInt cnt, Vec vecsin[], Vec vecsout[])
4142: {
4143: PetscFunctionBegin;
4146: for (PetscInt i = 0; i < cnt; i++) PetscCall(VecLockReadPush(vecsin[i]));
4147: if (ts->resizetransfer) {
4148: PetscCall(PetscInfo(ts, "Transferring %" PetscInt_FMT " vectors\n", cnt));
4149: PetscCallBack("TS callback resize transfer", (*ts->resizetransfer)(ts, cnt, vecsin, vecsout, ts->resizectx));
4150: }
4151: for (PetscInt i = 0; i < cnt; i++) PetscCall(VecLockReadPop(vecsin[i]));
4152: PetscFunctionReturn(PETSC_SUCCESS);
4153: }
4155: /*@
4156: TSResizeRegisterVec - Register a vector to be transferred with `TSResize()`.
4158: Collective
4160: Input Parameters:
4161: + ts - The `TS` context obtained from `TSCreate()`
4162: . name - A string identifying the vector
4163: - vec - The vector
4165: Level: developer
4167: Note:
4168: `TSResizeRegisterVec()` is typically used within time stepping implementations,
4169: so most users would not generally call this routine themselves.
4171: .seealso: [](ch_ts), `TS`, `TSSetResize()`, `TSResize()`, `TSResizeRetrieveVec()`
4172: @*/
4173: PetscErrorCode TSResizeRegisterVec(TS ts, const char name[], Vec vec)
4174: {
4175: PetscFunctionBegin;
4177: PetscAssertPointer(name, 2);
4179: PetscCall(PetscObjectListAdd(&ts->resizetransferobjs, name, (PetscObject)vec));
4180: PetscFunctionReturn(PETSC_SUCCESS);
4181: }
4183: /*@
4184: TSResizeRetrieveVec - Retrieve a vector registered with `TSResizeRegisterVec()`.
4186: Collective
4188: Input Parameters:
4189: + ts - The `TS` context obtained from `TSCreate()`
4190: . name - A string identifying the vector
4191: - vec - The vector
4193: Level: developer
4195: Note:
4196: `TSResizeRetrieveVec()` is typically used within time stepping implementations,
4197: so most users would not generally call this routine themselves.
4199: .seealso: [](ch_ts), `TS`, `TSSetResize()`, `TSResize()`, `TSResizeRegisterVec()`
4200: @*/
4201: PetscErrorCode TSResizeRetrieveVec(TS ts, const char name[], Vec *vec)
4202: {
4203: PetscFunctionBegin;
4205: PetscAssertPointer(name, 2);
4206: PetscAssertPointer(vec, 3);
4207: PetscCall(PetscObjectListFind(ts->resizetransferobjs, name, (PetscObject *)vec));
4208: PetscFunctionReturn(PETSC_SUCCESS);
4209: }
4211: static PetscErrorCode TSResizeGetVecArray(TS ts, PetscInt *nv, const char **names[], Vec *vecs[])
4212: {
4213: PetscInt cnt;
4214: PetscObjectList tmp;
4215: Vec *vecsin = NULL;
4216: const char **namesin = NULL;
4218: PetscFunctionBegin;
4219: for (tmp = ts->resizetransferobjs, cnt = 0; tmp; tmp = tmp->next)
4220: if (tmp->obj && tmp->obj->classid == VEC_CLASSID) cnt++;
4221: if (names) PetscCall(PetscMalloc1(cnt, &namesin));
4222: if (vecs) PetscCall(PetscMalloc1(cnt, &vecsin));
4223: for (tmp = ts->resizetransferobjs, cnt = 0; tmp; tmp = tmp->next) {
4224: if (tmp->obj && tmp->obj->classid == VEC_CLASSID) {
4225: if (vecs) vecsin[cnt] = (Vec)tmp->obj;
4226: if (names) namesin[cnt] = tmp->name;
4227: cnt++;
4228: }
4229: }
4230: if (nv) *nv = cnt;
4231: if (names) *names = namesin;
4232: if (vecs) *vecs = vecsin;
4233: PetscFunctionReturn(PETSC_SUCCESS);
4234: }
4236: /*@
4237: TSResize - Runs the user-defined transfer functions provided with `TSSetResize()`
4239: Collective
4241: Input Parameter:
4242: . ts - The `TS` context obtained from `TSCreate()`
4244: Level: developer
4246: Note:
4247: `TSResize()` is typically used within time stepping implementations,
4248: so most users would not generally call this routine themselves.
4250: .seealso: [](ch_ts), `TS`, `TSSetResize()`
4251: @*/
4252: PetscErrorCode TSResize(TS ts)
4253: {
4254: PetscInt nv = 0;
4255: const char **names = NULL;
4256: Vec *vecsin = NULL;
4257: const char *solname = "ts:vec_sol";
4259: PetscFunctionBegin;
4261: if (!ts->resizesetup) PetscFunctionReturn(PETSC_SUCCESS);
4262: if (ts->resizesetup) {
4263: PetscCall(VecLockReadPush(ts->vec_sol));
4264: PetscCallBack("TS callback resize setup", (*ts->resizesetup)(ts, ts->steps, ts->ptime, ts->vec_sol, &ts->stepresize, ts->resizectx));
4265: PetscCall(VecLockReadPop(ts->vec_sol));
4266: if (ts->stepresize) {
4267: if (ts->resizerollback) {
4268: PetscCall(TSRollBack(ts));
4269: ts->time_step = ts->time_step0;
4270: }
4271: PetscCall(TSResizeRegisterVec(ts, solname, ts->vec_sol));
4272: PetscCall(TSResizeRegisterOrRetrieve(ts, PETSC_TRUE)); /* specific impls register their own objects */
4273: }
4274: }
4276: PetscCall(TSResizeGetVecArray(ts, &nv, &names, &vecsin));
4277: if (nv) {
4278: Vec *vecsout, vecsol;
4280: /* Reset internal objects */
4281: PetscCall(TSReset(ts));
4283: /* Transfer needed vectors (users can call SetJacobian, SetDM, etc. here) */
4284: PetscCall(PetscCalloc1(nv, &vecsout));
4285: PetscCall(TSResizeTransferVecs(ts, nv, vecsin, vecsout));
4286: for (PetscInt i = 0; i < nv; i++) {
4287: const char *name;
4288: char *oname;
4290: PetscCall(PetscObjectGetName((PetscObject)vecsin[i], &name));
4291: PetscCall(PetscStrallocpy(name, &oname));
4292: PetscCall(TSResizeRegisterVec(ts, names[i], vecsout[i]));
4293: if (vecsout[i]) PetscCall(PetscObjectSetName((PetscObject)vecsout[i], oname));
4294: PetscCall(PetscFree(oname));
4295: PetscCall(VecDestroy(&vecsout[i]));
4296: }
4297: PetscCall(PetscFree(vecsout));
4298: PetscCall(TSResizeRegisterOrRetrieve(ts, PETSC_FALSE)); /* specific impls import the transferred objects */
4300: PetscCall(TSResizeRetrieveVec(ts, solname, &vecsol));
4301: if (vecsol) PetscCall(TSSetSolution(ts, vecsol));
4302: PetscAssert(ts->vec_sol, PetscObjectComm((PetscObject)ts), PETSC_ERR_ARG_NULL, "Missing TS solution");
4303: }
4305: PetscCall(PetscFree(names));
4306: PetscCall(PetscFree(vecsin));
4307: PetscCall(TSResizeReset(ts));
4308: PetscFunctionReturn(PETSC_SUCCESS);
4309: }
4311: /*@
4312: TSSolve - Steps the requested number of timesteps.
4314: Collective
4316: Input Parameters:
4317: + ts - the `TS` context obtained from `TSCreate()`
4318: - u - the solution vector (can be `NULL` if `TSSetSolution()` was used and `TSSetExactFinalTime`(ts,`TS_EXACTFINALTIME_MATCHSTEP`) was not used,
4319: otherwise it must contain the initial conditions and will contain the solution at the final requested time
4321: Level: beginner
4323: Note:
4324: The final time returned by this function may be different from the time of the internally
4325: held state accessible by `TSGetSolution()` and `TSGetTime()` because the method may have
4326: stepped over the final time.
4328: .seealso: [](ch_ts), `TS`, `TSCreate()`, `TSSetSolution()`, `TSStep()`, `TSGetTime()`, `TSGetSolveTime()`
4329: @*/
4330: PetscErrorCode TSSolve(TS ts, Vec u)
4331: {
4332: Vec solution;
4334: PetscFunctionBegin;
4338: PetscCall(TSSetExactFinalTimeDefault(ts));
4339: 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 */
4340: if (!ts->vec_sol || u == ts->vec_sol) {
4341: PetscCall(VecDuplicate(u, &solution));
4342: PetscCall(TSSetSolution(ts, solution));
4343: PetscCall(VecDestroy(&solution)); /* grant ownership */
4344: }
4345: PetscCall(VecCopy(u, ts->vec_sol));
4346: PetscCheck(!ts->forward_solve, PetscObjectComm((PetscObject)ts), PETSC_ERR_SUP, "Sensitivity analysis does not support the mode TS_EXACTFINALTIME_INTERPOLATE");
4347: } else if (u) PetscCall(TSSetSolution(ts, u));
4348: PetscCall(TSSetUp(ts));
4349: PetscCall(TSTrajectorySetUp(ts->trajectory, ts));
4351: PetscCheck(ts->max_time < PETSC_MAX_REAL || ts->run_steps != PETSC_INT_MAX || ts->max_steps != PETSC_INT_MAX, PetscObjectComm((PetscObject)ts), PETSC_ERR_ARG_WRONGSTATE, "You must call TSSetMaxTime(), TSSetMaxSteps(), or TSSetRunSteps() or use -ts_max_time <time>, -ts_max_steps <steps>, -ts_run_steps <steps>");
4352: PetscCheck(ts->exact_final_time != TS_EXACTFINALTIME_UNSPECIFIED, PetscObjectComm((PetscObject)ts), PETSC_ERR_ARG_WRONGSTATE, "You must call TSSetExactFinalTime() or use -ts_exact_final_time <stepover,interpolate,matchstep> before calling TSSolve()");
4353: PetscCheck(ts->exact_final_time != TS_EXACTFINALTIME_MATCHSTEP || ts->adapt, PetscObjectComm((PetscObject)ts), PETSC_ERR_SUP, "Since TS is not adaptive you cannot use TS_EXACTFINALTIME_MATCHSTEP, suggest TS_EXACTFINALTIME_INTERPOLATE");
4354: PetscCheck(!(ts->eval_times && ts->exact_final_time != TS_EXACTFINALTIME_MATCHSTEP), PetscObjectComm((PetscObject)ts), PETSC_ERR_SUP, "You must use TS_EXACTFINALTIME_MATCHSTEP when using time span or evaluation times");
4356: if (ts->eval_times) {
4357: if (!ts->eval_times->sol_vecs) PetscCall(VecDuplicateVecs(ts->vec_sol, ts->eval_times->num_time_points, &ts->eval_times->sol_vecs));
4358: for (PetscInt i = 0; i < ts->eval_times->num_time_points; i++) {
4359: PetscBool is_close = PetscIsCloseAtTol(ts->ptime, ts->eval_times->time_points[i], ts->eval_times->reltol * ts->time_step + ts->eval_times->abstol, 0);
4360: if (ts->ptime <= ts->eval_times->time_points[i] || is_close) {
4361: ts->eval_times->time_point_idx = i;
4363: PetscBool is_ptime_in_sol_times = PETSC_FALSE; // If current solution has already been saved, we should not save it again
4364: if (ts->eval_times->sol_idx > 0) is_ptime_in_sol_times = PetscIsCloseAtTol(ts->ptime, ts->eval_times->sol_times[ts->eval_times->sol_idx - 1], ts->eval_times->reltol * ts->time_step + ts->eval_times->abstol, 0);
4365: if (is_close && !is_ptime_in_sol_times) {
4366: PetscCall(VecCopy(ts->vec_sol, ts->eval_times->sol_vecs[ts->eval_times->sol_idx]));
4367: ts->eval_times->sol_times[ts->eval_times->sol_idx] = ts->ptime;
4368: ts->eval_times->sol_idx++;
4369: ts->eval_times->time_point_idx++;
4370: }
4371: break;
4372: }
4373: }
4374: }
4376: if (ts->forward_solve) PetscCall(TSForwardSetUp(ts));
4378: /* reset number of steps only when the step is not restarted. ARKIMEX
4379: restarts the step after an event. Resetting these counters in such case causes
4380: TSTrajectory to incorrectly save the output files
4381: */
4382: /* reset time step and iteration counters */
4383: if (!ts->steps) {
4384: ts->ksp_its = 0;
4385: ts->snes_its = 0;
4386: ts->num_snes_failures = 0;
4387: ts->reject = 0;
4388: ts->steprestart = PETSC_TRUE;
4389: ts->steprollback = PETSC_FALSE;
4390: ts->stepresize = PETSC_FALSE;
4391: ts->rhsjacobian.time = PETSC_MIN_REAL;
4392: }
4394: /* make sure initial time step does not overshoot final time or the next point in evaluation times */
4395: if (ts->exact_final_time == TS_EXACTFINALTIME_MATCHSTEP) {
4396: PetscReal maxdt;
4397: PetscReal dt = ts->time_step;
4399: if (ts->eval_times) maxdt = ts->eval_times->time_points[ts->eval_times->time_point_idx] - ts->ptime;
4400: else maxdt = ts->max_time - ts->ptime;
4401: ts->time_step = dt >= maxdt ? maxdt : (PetscIsCloseAtTol(dt, maxdt, 10 * PETSC_MACHINE_EPSILON, 0) ? maxdt : dt);
4402: }
4403: ts->reason = TS_CONVERGED_ITERATING;
4405: {
4406: PetscViewer viewer;
4407: PetscViewerFormat format;
4408: PetscBool flg;
4409: static PetscBool incall = PETSC_FALSE;
4411: if (!incall) {
4412: /* Estimate the convergence rate of the time discretization */
4413: PetscCall(PetscOptionsCreateViewer(PetscObjectComm((PetscObject)ts), ((PetscObject)ts)->options, ((PetscObject)ts)->prefix, "-ts_convergence_estimate", &viewer, &format, &flg));
4414: if (flg) {
4415: PetscConvEst conv;
4416: DM dm;
4417: PetscReal *alpha; /* Convergence rate of the solution error for each field in the L_2 norm */
4418: PetscInt Nf;
4419: PetscBool checkTemporal = PETSC_TRUE;
4421: incall = PETSC_TRUE;
4422: PetscCall(PetscOptionsGetBool(((PetscObject)ts)->options, ((PetscObject)ts)->prefix, "-ts_convergence_temporal", &checkTemporal, &flg));
4423: PetscCall(TSGetDM(ts, &dm));
4424: PetscCall(DMGetNumFields(dm, &Nf));
4425: PetscCall(PetscCalloc1(PetscMax(Nf, 1), &alpha));
4426: PetscCall(PetscConvEstCreate(PetscObjectComm((PetscObject)ts), &conv));
4427: PetscCall(PetscConvEstUseTS(conv, checkTemporal));
4428: PetscCall(PetscConvEstSetSolver(conv, (PetscObject)ts));
4429: PetscCall(PetscConvEstSetFromOptions(conv));
4430: PetscCall(PetscConvEstSetUp(conv));
4431: PetscCall(PetscConvEstGetConvRate(conv, alpha));
4432: PetscCall(PetscViewerPushFormat(viewer, format));
4433: PetscCall(PetscConvEstRateView(conv, alpha, viewer));
4434: PetscCall(PetscViewerPopFormat(viewer));
4435: PetscCall(PetscViewerDestroy(&viewer));
4436: PetscCall(PetscConvEstDestroy(&conv));
4437: PetscCall(PetscFree(alpha));
4438: incall = PETSC_FALSE;
4439: }
4440: }
4441: }
4443: PetscCall(TSViewFromOptions(ts, NULL, "-ts_view_pre"));
4445: if (ts->ops->solve) { /* This private interface is transitional and should be removed when all implementations are updated. */
4446: PetscUseTypeMethod(ts, solve);
4447: if (u) PetscCall(VecCopy(ts->vec_sol, u));
4448: ts->solvetime = ts->ptime;
4449: solution = ts->vec_sol;
4450: } else { /* Step the requested number of timesteps. */
4451: if (ts->steps >= ts->max_steps) ts->reason = TS_CONVERGED_ITS;
4452: else if (ts->ptime >= ts->max_time) ts->reason = TS_CONVERGED_TIME;
4454: if (!ts->steps) {
4455: PetscCall(TSTrajectoryResetHistory_Private(ts->trajectory));
4456: PetscCall(TSTrajectorySet(ts->trajectory, ts, ts->steps, ts->ptime, ts->vec_sol));
4457: PetscCall(TSEventInitialize(ts->event, ts, ts->ptime, ts->vec_sol));
4458: }
4460: ts->start_step = ts->steps; // records starting step
4461: while (!ts->reason) {
4462: PetscCall(TSMonitor(ts, ts->steps, ts->ptime, ts->vec_sol));
4463: if (!ts->steprollback || (ts->stepresize && ts->resizerollback)) PetscCall(TSPreStep(ts));
4464: PetscCall(TSStep(ts));
4465: if (ts->testjacobian) PetscCall(TSRHSJacobianTest(ts, NULL));
4466: if (ts->testjacobiantranspose) PetscCall(TSRHSJacobianTestTranspose(ts, NULL));
4467: if (ts->quadraturets && ts->costintegralfwd) { /* Must evaluate the cost integral before event is handled. The cost integral value can also be rolled back. */
4468: if (ts->reason >= 0) ts->steps--; /* Revert the step number changed by TSStep() */
4469: PetscCall(TSForwardCostIntegral(ts));
4470: if (ts->reason >= 0) ts->steps++;
4471: }
4472: if (ts->forward_solve) { /* compute forward sensitivities before event handling because postevent() may change RHS and jump conditions may have to be applied */
4473: if (ts->reason >= 0) ts->steps--; /* Revert the step number changed by TSStep() */
4474: PetscCall(TSForwardStep(ts));
4475: if (ts->reason >= 0) ts->steps++;
4476: }
4477: PetscCall(TSPostEvaluate(ts));
4478: PetscCall(TSEventHandler(ts)); /* The right-hand side may be changed due to event. Be careful with Any computation using the RHS information after this point. */
4479: if (ts->steprollback) PetscCall(TSPostEvaluate(ts));
4480: if (!ts->steprollback && ts->resizerollback) PetscCall(TSResize(ts));
4481: /* check convergence */
4482: if (!ts->reason) {
4483: if ((ts->steps - ts->start_step) >= ts->run_steps) ts->reason = TS_CONVERGED_ITS;
4484: else if (ts->steps >= ts->max_steps) ts->reason = TS_CONVERGED_ITS;
4485: else if (ts->ptime >= ts->max_time) ts->reason = TS_CONVERGED_TIME;
4486: }
4487: if (!ts->steprollback) {
4488: PetscCall(TSTrajectorySet(ts->trajectory, ts, ts->steps, ts->ptime, ts->vec_sol));
4489: PetscCall(TSPostStep(ts));
4490: if (!ts->resizerollback) PetscCall(TSResize(ts));
4492: if (ts->eval_times && ts->eval_times->time_point_idx < ts->eval_times->num_time_points && ts->reason >= 0) {
4493: PetscCheck(ts->eval_times->worktol > 0, PetscObjectComm((PetscObject)ts), PETSC_ERR_PLIB, "Unexpected state !(eval_times->worktol > 0) in TSSolve()");
4494: if (PetscIsCloseAtTol(ts->ptime, ts->eval_times->time_points[ts->eval_times->time_point_idx], ts->eval_times->worktol, 0)) {
4495: ts->eval_times->sol_times[ts->eval_times->sol_idx] = ts->ptime;
4496: PetscCall(VecCopy(ts->vec_sol, ts->eval_times->sol_vecs[ts->eval_times->sol_idx]));
4497: ts->eval_times->sol_idx++;
4498: ts->eval_times->time_point_idx++;
4499: }
4500: }
4501: }
4502: }
4503: PetscCall(TSMonitor(ts, ts->steps, ts->ptime, ts->vec_sol));
4505: if (ts->exact_final_time == TS_EXACTFINALTIME_INTERPOLATE && ts->ptime > ts->max_time) {
4506: if (!u) u = ts->vec_sol;
4507: PetscCall(TSInterpolate(ts, ts->max_time, u));
4508: ts->solvetime = ts->max_time;
4509: solution = u;
4510: PetscCall(TSMonitor(ts, -1, ts->solvetime, solution));
4511: } else {
4512: if (u) PetscCall(VecCopy(ts->vec_sol, u));
4513: ts->solvetime = ts->ptime;
4514: solution = ts->vec_sol;
4515: }
4516: }
4518: PetscCall(TSViewFromOptions(ts, NULL, "-ts_view"));
4519: PetscCall(VecViewFromOptions(solution, (PetscObject)ts, "-ts_view_solution"));
4520: PetscCall(PetscObjectSAWsBlock((PetscObject)ts));
4521: if (ts->adjoint_solve) PetscCall(TSAdjointSolve(ts));
4522: PetscFunctionReturn(PETSC_SUCCESS);
4523: }
4525: /*@
4526: TSGetTime - Gets the time of the most recently completed step.
4528: Not Collective
4530: Input Parameter:
4531: . ts - the `TS` context obtained from `TSCreate()`
4533: Output Parameter:
4534: . t - the current time. This time may not corresponds to the final time set with `TSSetMaxTime()`, use `TSGetSolveTime()`.
4536: Level: beginner
4538: Note:
4539: When called during time step evaluation (e.g. during residual evaluation or via hooks set using `TSSetPreStep()`,
4540: `TSSetPreStage()`, `TSSetPostStage()`, or `TSSetPostStep()`), the time is the time at the start of the step being evaluated.
4542: .seealso: [](ch_ts), `TS`, `TSGetSolveTime()`, `TSSetTime()`, `TSGetTimeStep()`, `TSGetStepNumber()`
4543: @*/
4544: PetscErrorCode TSGetTime(TS ts, PetscReal *t)
4545: {
4546: PetscFunctionBegin;
4548: PetscAssertPointer(t, 2);
4549: *t = ts->ptime;
4550: PetscFunctionReturn(PETSC_SUCCESS);
4551: }
4553: /*@
4554: TSGetPrevTime - Gets the starting time of the previously completed step.
4556: Not Collective
4558: Input Parameter:
4559: . ts - the `TS` context obtained from `TSCreate()`
4561: Output Parameter:
4562: . t - the previous time
4564: Level: beginner
4566: .seealso: [](ch_ts), `TS`, `TSGetTime()`, `TSGetSolveTime()`, `TSGetTimeStep()`
4567: @*/
4568: PetscErrorCode TSGetPrevTime(TS ts, PetscReal *t)
4569: {
4570: PetscFunctionBegin;
4572: PetscAssertPointer(t, 2);
4573: *t = ts->ptime_prev;
4574: PetscFunctionReturn(PETSC_SUCCESS);
4575: }
4577: /*@
4578: TSSetTime - Allows one to reset the time.
4580: Logically Collective
4582: Input Parameters:
4583: + ts - the `TS` context obtained from `TSCreate()`
4584: - t - the time
4586: Level: intermediate
4588: .seealso: [](ch_ts), `TS`, `TSGetTime()`, `TSSetMaxSteps()`
4589: @*/
4590: PetscErrorCode TSSetTime(TS ts, PetscReal t)
4591: {
4592: PetscFunctionBegin;
4595: ts->ptime = t;
4596: PetscFunctionReturn(PETSC_SUCCESS);
4597: }
4599: /*@
4600: TSSetOptionsPrefix - Sets the prefix used for searching for all
4601: TS options in the database.
4603: Logically Collective
4605: Input Parameters:
4606: + ts - The `TS` context
4607: - prefix - The prefix to prepend to all option names
4609: Level: advanced
4611: Note:
4612: A hyphen (-) must NOT be given at the beginning of the prefix name.
4613: The first character of all runtime options is AUTOMATICALLY the
4614: hyphen.
4616: .seealso: [](ch_ts), `TS`, `TSSetFromOptions()`, `TSAppendOptionsPrefix()`
4617: @*/
4618: PetscErrorCode TSSetOptionsPrefix(TS ts, const char prefix[])
4619: {
4620: SNES snes;
4622: PetscFunctionBegin;
4624: PetscCall(PetscObjectSetOptionsPrefix((PetscObject)ts, prefix));
4625: PetscCall(TSGetSNES(ts, &snes));
4626: PetscCall(SNESSetOptionsPrefix(snes, prefix));
4627: PetscFunctionReturn(PETSC_SUCCESS);
4628: }
4630: /*@
4631: TSAppendOptionsPrefix - Appends to the prefix used for searching for all
4632: TS options in the database.
4634: Logically Collective
4636: Input Parameters:
4637: + ts - The `TS` context
4638: - prefix - The prefix to prepend to all option names
4640: Level: advanced
4642: Note:
4643: A hyphen (-) must NOT be given at the beginning of the prefix name.
4644: The first character of all runtime options is AUTOMATICALLY the
4645: hyphen.
4647: .seealso: [](ch_ts), `TS`, `TSGetOptionsPrefix()`, `TSSetOptionsPrefix()`, `TSSetFromOptions()`
4648: @*/
4649: PetscErrorCode TSAppendOptionsPrefix(TS ts, const char prefix[])
4650: {
4651: SNES snes;
4653: PetscFunctionBegin;
4655: PetscCall(PetscObjectAppendOptionsPrefix((PetscObject)ts, prefix));
4656: PetscCall(TSGetSNES(ts, &snes));
4657: PetscCall(SNESAppendOptionsPrefix(snes, prefix));
4658: PetscFunctionReturn(PETSC_SUCCESS);
4659: }
4661: /*@
4662: TSGetOptionsPrefix - Sets the prefix used for searching for all
4663: `TS` options in the database.
4665: Not Collective
4667: Input Parameter:
4668: . ts - The `TS` context
4670: Output Parameter:
4671: . prefix - A pointer to the prefix string used
4673: Level: intermediate
4675: .seealso: [](ch_ts), `TS`, `TSAppendOptionsPrefix()`, `TSSetFromOptions()`
4676: @*/
4677: PetscErrorCode TSGetOptionsPrefix(TS ts, const char *prefix[])
4678: {
4679: PetscFunctionBegin;
4681: PetscAssertPointer(prefix, 2);
4682: PetscCall(PetscObjectGetOptionsPrefix((PetscObject)ts, prefix));
4683: PetscFunctionReturn(PETSC_SUCCESS);
4684: }
4686: /*@
4687: TSGetRHSJacobian - Returns the Jacobian J at the present timestep.
4689: Not Collective, but parallel objects are returned if ts is parallel
4691: Input Parameter:
4692: . ts - The `TS` context obtained from `TSCreate()`
4694: Output Parameters:
4695: + Amat - The (approximate) Jacobian J of G, where U_t = G(U,t) (or `NULL`)
4696: . Pmat - The matrix from which the preconditioner is constructed, usually the same as `Amat` (or `NULL`)
4697: . func - Function to compute the Jacobian of the RHS (or `NULL`)
4698: - ctx - User-defined context for Jacobian evaluation routine (or `NULL`)
4700: Level: intermediate
4702: Note:
4703: You can pass in `NULL` for any return argument you do not need.
4705: .seealso: [](ch_ts), `TS`, `TSGetTimeStep()`, `TSGetMatrices()`, `TSGetTime()`, `TSGetStepNumber()`
4706: @*/
4707: PetscErrorCode TSGetRHSJacobian(TS ts, Mat *Amat, Mat *Pmat, TSRHSJacobianFn **func, PetscCtxRt ctx)
4708: {
4709: DM dm;
4711: PetscFunctionBegin;
4712: if (Amat || Pmat) {
4713: SNES snes;
4714: PetscCall(TSGetSNES(ts, &snes));
4715: PetscCall(SNESSetUpMatrices(snes));
4716: PetscCall(SNESGetJacobian(snes, Amat, Pmat, NULL, NULL));
4717: }
4718: PetscCall(TSGetDM(ts, &dm));
4719: PetscCall(DMTSGetRHSJacobian(dm, func, ctx));
4720: PetscFunctionReturn(PETSC_SUCCESS);
4721: }
4723: /*@
4724: TSGetIJacobian - Returns the implicit Jacobian at the present timestep.
4726: Not Collective, but parallel objects are returned if ts is parallel
4728: Input Parameter:
4729: . ts - The `TS` context obtained from `TSCreate()`
4731: Output Parameters:
4732: + Amat - The (approximate) Jacobian of F(t,U,U_t)
4733: . Pmat - The matrix from which the preconditioner is constructed, often the same as `Amat`
4734: . f - The function to compute the matrices
4735: - ctx - User-defined context for Jacobian evaluation routine
4737: Level: advanced
4739: Note:
4740: You can pass in `NULL` for any return argument you do not need.
4742: .seealso: [](ch_ts), `TS`, `TSGetTimeStep()`, `TSGetRHSJacobian()`, `TSGetMatrices()`, `TSGetTime()`, `TSGetStepNumber()`
4743: @*/
4744: PetscErrorCode TSGetIJacobian(TS ts, Mat *Amat, Mat *Pmat, TSIJacobianFn **f, PetscCtxRt ctx)
4745: {
4746: DM dm;
4748: PetscFunctionBegin;
4749: if (Amat || Pmat) {
4750: SNES snes;
4751: PetscCall(TSGetSNES(ts, &snes));
4752: PetscCall(SNESSetUpMatrices(snes));
4753: PetscCall(SNESGetJacobian(snes, Amat, Pmat, NULL, NULL));
4754: }
4755: PetscCall(TSGetDM(ts, &dm));
4756: PetscCall(DMTSGetIJacobian(dm, f, ctx));
4757: PetscFunctionReturn(PETSC_SUCCESS);
4758: }
4760: #include <petsc/private/dmimpl.h>
4761: /*@
4762: TSSetDM - Sets the `DM` that may be used by some nonlinear solvers or preconditioners under the `TS`
4764: Logically Collective
4766: Input Parameters:
4767: + ts - the `TS` integrator object
4768: - dm - the dm, cannot be `NULL`
4770: Level: intermediate
4772: Notes:
4773: A `DM` can only be used for solving one problem at a time because information about the problem is stored on the `DM`,
4774: even when not using interfaces like `DMTSSetIFunction()`. Use `DMClone()` to get a distinct `DM` when solving
4775: different problems using the same function space.
4777: .seealso: [](ch_ts), `TS`, `DM`, `TSGetDM()`, `SNESSetDM()`, `SNESGetDM()`
4778: @*/
4779: PetscErrorCode TSSetDM(TS ts, DM dm)
4780: {
4781: SNES snes;
4782: DMTS tsdm;
4784: PetscFunctionBegin;
4787: PetscCall(PetscObjectReference((PetscObject)dm));
4788: if (ts->dm) { /* Move the DMTS context over to the new DM unless the new DM already has one */
4789: if (ts->dm->dmts && !dm->dmts) {
4790: PetscCall(DMCopyDMTS(ts->dm, dm));
4791: PetscCall(DMGetDMTS(ts->dm, &tsdm));
4792: /* Grant write privileges to the replacement DM */
4793: if (tsdm->originaldm == ts->dm) tsdm->originaldm = dm;
4794: }
4795: PetscCall(DMDestroy(&ts->dm));
4796: }
4797: ts->dm = dm;
4799: PetscCall(TSGetSNES(ts, &snes));
4800: PetscCall(SNESSetDM(snes, dm));
4801: PetscFunctionReturn(PETSC_SUCCESS);
4802: }
4804: /*@
4805: TSGetDM - Gets the `DM` that may be used by some preconditioners
4807: Not Collective
4809: Input Parameter:
4810: . ts - the `TS`
4812: Output Parameter:
4813: . dm - the `DM`
4815: Level: intermediate
4817: .seealso: [](ch_ts), `TS`, `DM`, `TSSetDM()`, `SNESSetDM()`, `SNESGetDM()`
4818: @*/
4819: PetscErrorCode TSGetDM(TS ts, DM *dm)
4820: {
4821: PetscFunctionBegin;
4823: if (!ts->dm) {
4824: PetscCall(DMShellCreate(PetscObjectComm((PetscObject)ts), &ts->dm));
4825: if (ts->snes) PetscCall(SNESSetDM(ts->snes, ts->dm));
4826: }
4827: *dm = ts->dm;
4828: PetscFunctionReturn(PETSC_SUCCESS);
4829: }
4831: /*@
4832: SNESTSFormFunction - Function to evaluate nonlinear residual defined by an ODE solver algorithm implemented within `TS`
4834: Logically Collective
4836: Input Parameters:
4837: + snes - nonlinear solver
4838: . U - the current state at which to evaluate the residual
4839: - ctx - application context, must be a `TS`
4841: Output Parameter:
4842: . F - the nonlinear residual
4844: Level: developer
4846: Note:
4847: This function is not normally called by users and is automatically registered with the `SNES` used by `TS`.
4848: It is most frequently passed to `MatFDColoringSetFunction()`.
4850: .seealso: [](ch_ts), `SNESSetFunction()`, `MatFDColoringSetFunction()`
4851: @*/
4852: PetscErrorCode SNESTSFormFunction(SNES snes, Vec U, Vec F, PetscCtx ctx)
4853: {
4854: TS ts = (TS)ctx;
4856: PetscFunctionBegin;
4861: PetscCheck(ts->ops->snesfunction, PetscObjectComm((PetscObject)ts), PETSC_ERR_SUP, "No method snesfunction for TS of type %s", ((PetscObject)ts)->type_name);
4862: PetscCall((*ts->ops->snesfunction)(snes, U, F, ts));
4863: PetscFunctionReturn(PETSC_SUCCESS);
4864: }
4866: /*@
4867: SNESTSFormJacobian - Function to evaluate the Jacobian defined by an ODE solver algorithm implemented within `TS`
4869: Collective
4871: Input Parameters:
4872: + snes - nonlinear solver
4873: . U - the current state at which to evaluate the residual
4874: - ctx - application context, must be a `TS`
4876: Output Parameters:
4877: + A - the Jacobian
4878: - B - the matrix used to construct the preconditioner (often the same as `A`)
4880: Level: developer
4882: Note:
4883: This function is not normally called by users and is automatically registered with the `SNES` used by `TS`.
4885: .seealso: [](ch_ts), `SNESSetJacobian()`
4886: @*/
4887: PetscErrorCode SNESTSFormJacobian(SNES snes, Vec U, Mat A, Mat B, PetscCtx ctx)
4888: {
4889: TS ts = (TS)ctx;
4891: PetscFunctionBegin;
4897: PetscCheck(ts->ops->snesjacobian, PetscObjectComm((PetscObject)ts), PETSC_ERR_SUP, "No method snesjacobian for TS of type %s", ((PetscObject)ts)->type_name);
4898: PetscCall((*ts->ops->snesjacobian)(snes, U, A, B, ts));
4899: PetscFunctionReturn(PETSC_SUCCESS);
4900: }
4902: /*@
4903: TSComputeRHSFunctionLinear - Evaluate the right-hand side via the user-provided Jacobian, for linear problems Udot = A U only
4905: Collective
4907: Input Parameters:
4908: + ts - time stepping context
4909: . t - time at which to evaluate
4910: . U - state at which to evaluate
4911: - ctx - context
4913: Output Parameter:
4914: . F - right-hand side
4916: Level: intermediate
4918: Note:
4919: This function is intended to be passed to `TSSetRHSFunction()` to evaluate the right-hand side for linear problems.
4920: The matrix (and optionally the evaluation context) should be passed to `TSSetRHSJacobian()`.
4922: .seealso: [](ch_ts), `TS`, `TSSetRHSFunction()`, `TSSetRHSJacobian()`, `TSComputeRHSJacobianConstant()`
4923: @*/
4924: PetscErrorCode TSComputeRHSFunctionLinear(TS ts, PetscReal t, Vec U, Vec F, PetscCtx ctx)
4925: {
4926: Mat Arhs, Brhs;
4928: PetscFunctionBegin;
4929: PetscCall(TSGetRHSMats_Private(ts, &Arhs, &Brhs));
4930: /* undo the damage caused by shifting */
4931: PetscCall(TSRecoverRHSJacobian(ts, Arhs, Brhs));
4932: PetscCall(TSComputeRHSJacobian(ts, t, U, Arhs, Brhs));
4933: PetscCall(MatMult(Arhs, U, F));
4934: PetscFunctionReturn(PETSC_SUCCESS);
4935: }
4937: /*@
4938: TSComputeRHSJacobianConstant - Reuses a Jacobian that is time-independent.
4940: Collective
4942: Input Parameters:
4943: + ts - time stepping context
4944: . t - time at which to evaluate
4945: . U - state at which to evaluate
4946: - ctx - context
4948: Output Parameters:
4949: + A - Jacobian
4950: - B - matrix used to construct the preconditioner, often the same as `A`
4952: Level: intermediate
4954: Note:
4955: This function is intended to be passed to `TSSetRHSJacobian()` to evaluate the Jacobian for linear time-independent problems.
4957: .seealso: [](ch_ts), `TS`, `TSSetRHSFunction()`, `TSSetRHSJacobian()`, `TSComputeRHSFunctionLinear()`
4958: @*/
4959: PetscErrorCode TSComputeRHSJacobianConstant(TS ts, PetscReal t, Vec U, Mat A, Mat B, PetscCtx ctx)
4960: {
4961: PetscFunctionBegin;
4962: PetscFunctionReturn(PETSC_SUCCESS);
4963: }
4965: /*@
4966: TSComputeIFunctionLinear - Evaluate the left hand side via the user-provided Jacobian, for linear problems only
4968: Collective
4970: Input Parameters:
4971: + ts - time stepping context
4972: . t - time at which to evaluate
4973: . U - state at which to evaluate
4974: . Udot - time derivative of state vector
4975: - ctx - context
4977: Output Parameter:
4978: . F - left hand side
4980: Level: intermediate
4982: Notes:
4983: 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
4984: user is required to write their own `TSComputeIFunction()`.
4985: This function is intended to be passed to `TSSetIFunction()` to evaluate the left hand side for linear problems.
4986: The matrix (and optionally the evaluation context) should be passed to `TSSetIJacobian()`.
4988: Note that using this function is NOT equivalent to using `TSComputeRHSFunctionLinear()` since that solves Udot = A U
4990: .seealso: [](ch_ts), `TS`, `TSSetIFunction()`, `TSSetIJacobian()`, `TSComputeIJacobianConstant()`, `TSComputeRHSFunctionLinear()`
4991: @*/
4992: PetscErrorCode TSComputeIFunctionLinear(TS ts, PetscReal t, Vec U, Vec Udot, Vec F, PetscCtx ctx)
4993: {
4994: Mat A, B;
4996: PetscFunctionBegin;
4997: PetscCall(TSGetIJacobian(ts, &A, &B, NULL, NULL));
4998: PetscCall(TSComputeIJacobian(ts, t, U, Udot, 1.0, A, B, PETSC_TRUE));
4999: PetscCall(MatMult(A, Udot, F));
5000: PetscFunctionReturn(PETSC_SUCCESS);
5001: }
5003: /*@
5004: TSComputeIJacobianConstant - Reuses the matrix previously computed with the provided `TSIJacobianFn` for a semi-implicit DAE or ODE
5006: Collective
5008: Input Parameters:
5009: + ts - time stepping context
5010: . t - time at which to evaluate
5011: . U - state at which to evaluate
5012: . Udot - time derivative of state vector
5013: . shift - shift to apply
5014: - ctx - context
5016: Output Parameters:
5017: + A - pointer to operator
5018: - B - pointer to matrix from which the preconditioner is built (often `A`)
5020: Level: advanced
5022: Notes:
5023: This function is intended to be passed to `TSSetIJacobian()` to evaluate the Jacobian for linear time-independent problems.
5025: It is only appropriate for problems of the form
5027: $$
5028: M \dot{U} = F(U,t)
5029: $$
5031: where M is constant and F is non-stiff. The user must pass M to `TSSetIJacobian()`. The current implementation only
5032: works with IMEX time integration methods such as `TSROSW` and `TSARKIMEX`, since there is no support for de-constructing
5033: an implicit operator of the form
5035: $$
5036: shift M + J
5037: $$
5039: 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
5040: a copy of M or reassemble it when requested.
5042: .seealso: [](ch_ts), `TS`, `TSROSW`, `TSARKIMEX`, `TSSetIFunction()`, `TSSetIJacobian()`, `TSComputeIFunctionLinear()`
5043: @*/
5044: PetscErrorCode TSComputeIJacobianConstant(TS ts, PetscReal t, Vec U, Vec Udot, PetscReal shift, Mat A, Mat B, PetscCtx ctx)
5045: {
5046: PetscFunctionBegin;
5047: PetscCall(MatScale(A, shift / ts->ijacobian.shift));
5048: ts->ijacobian.shift = shift;
5049: PetscFunctionReturn(PETSC_SUCCESS);
5050: }
5052: /*@
5053: TSGetEquationType - Gets the type of the equation that `TS` is solving.
5055: Not Collective
5057: Input Parameter:
5058: . ts - the `TS` context
5060: Output Parameter:
5061: . equation_type - see `TSEquationType`
5063: Level: beginner
5065: .seealso: [](ch_ts), `TS`, `TSSetEquationType()`, `TSEquationType`
5066: @*/
5067: PetscErrorCode TSGetEquationType(TS ts, TSEquationType *equation_type)
5068: {
5069: PetscFunctionBegin;
5071: PetscAssertPointer(equation_type, 2);
5072: *equation_type = ts->equation_type;
5073: PetscFunctionReturn(PETSC_SUCCESS);
5074: }
5076: /*@
5077: TSSetEquationType - Sets the type of the equation that `TS` is solving.
5079: Not Collective
5081: Input Parameters:
5082: + ts - the `TS` context
5083: - equation_type - see `TSEquationType`
5085: Level: advanced
5087: .seealso: [](ch_ts), `TS`, `TSGetEquationType()`, `TSEquationType`
5088: @*/
5089: PetscErrorCode TSSetEquationType(TS ts, TSEquationType equation_type)
5090: {
5091: PetscFunctionBegin;
5093: ts->equation_type = equation_type;
5094: PetscFunctionReturn(PETSC_SUCCESS);
5095: }
5097: /*@
5098: TSGetConvergedReason - Gets the reason the `TS` iteration was stopped.
5100: Not Collective
5102: Input Parameter:
5103: . ts - the `TS` context
5105: Output Parameter:
5106: . reason - negative value indicates diverged, positive value converged, see `TSConvergedReason` or the
5107: manual pages for the individual convergence tests for complete lists
5109: Level: beginner
5111: Note:
5112: Can only be called after the call to `TSSolve()` is complete.
5114: .seealso: [](ch_ts), `TS`, `TSSolve()`, `TSConvergedReason`
5115: @*/
5116: PetscErrorCode TSGetConvergedReason(TS ts, TSConvergedReason *reason)
5117: {
5118: PetscFunctionBegin;
5120: PetscAssertPointer(reason, 2);
5121: *reason = ts->reason;
5122: PetscFunctionReturn(PETSC_SUCCESS);
5123: }
5125: /*@
5126: TSSetConvergedReason - Sets the reason for handling the convergence of `TSSolve()`.
5128: Logically Collective; reason must contain common value
5130: Input Parameters:
5131: + ts - the `TS` context
5132: - reason - negative value indicates diverged, positive value converged, see `TSConvergedReason` or the
5133: manual pages for the individual convergence tests for complete lists
5135: Level: advanced
5137: Note:
5138: Can only be called while `TSSolve()` is active.
5140: .seealso: [](ch_ts), `TS`, `TSSolve()`, `TSConvergedReason`
5141: @*/
5142: PetscErrorCode TSSetConvergedReason(TS ts, TSConvergedReason reason)
5143: {
5144: PetscFunctionBegin;
5146: ts->reason = reason;
5147: PetscFunctionReturn(PETSC_SUCCESS);
5148: }
5150: /*@
5151: TSGetSolveTime - Gets the time after a call to `TSSolve()`
5153: Not Collective
5155: Input Parameter:
5156: . ts - the `TS` context
5158: Output Parameter:
5159: . ftime - the final time. This time corresponds to the final time set with `TSSetMaxTime()`
5161: Level: beginner
5163: Note:
5164: Can only be called after the call to `TSSolve()` is complete.
5166: .seealso: [](ch_ts), `TS`, `TSSolve()`, `TSConvergedReason`
5167: @*/
5168: PetscErrorCode TSGetSolveTime(TS ts, PetscReal *ftime)
5169: {
5170: PetscFunctionBegin;
5172: PetscAssertPointer(ftime, 2);
5173: *ftime = ts->solvetime;
5174: PetscFunctionReturn(PETSC_SUCCESS);
5175: }
5177: /*@
5178: TSGetSNESIterations - Gets the total number of nonlinear `SNESSolve()` iterations
5179: used by the time integrator over all previous timesteps
5181: Not Collective
5183: Input Parameter:
5184: . ts - `TS` context
5186: Output Parameter:
5187: . nits - number of nonlinear iterations
5189: Level: intermediate
5191: Note:
5192: This counter is reset to zero when `TSSolve()` starts at step number zero and when `TSAdjointSolve()` starts.
5193: It accumulates over successive `TSSolve()` calls that continue a run, for example with `TSSetRunSteps()`.
5195: .seealso: [](ch_ts), `TS`, `TSSolve()`, `TSGetKSPIterations()`
5196: @*/
5197: PetscErrorCode TSGetSNESIterations(TS ts, PetscInt *nits)
5198: {
5199: PetscFunctionBegin;
5201: PetscAssertPointer(nits, 2);
5202: *nits = ts->snes_its;
5203: PetscFunctionReturn(PETSC_SUCCESS);
5204: }
5206: /*@
5207: TSGetKSPIterations - Gets the total number of linear `KSPSolve()` iterations
5208: used by the time integrator over all previous timesteps
5210: Not Collective
5212: Input Parameter:
5213: . ts - `TS` context
5215: Output Parameter:
5216: . lits - number of linear iterations
5218: Level: intermediate
5220: Note:
5221: This counter is reset to zero when `TSSolve()` starts at step number zero and when `TSAdjointSolve()` starts.
5222: It accumulates over successive `TSSolve()` calls that continue a run, for example with `TSSetRunSteps()`.
5224: .seealso: [](ch_ts), `TS`, `TSSolve()`, `TSGetSNESIterations()`
5225: @*/
5226: PetscErrorCode TSGetKSPIterations(TS ts, PetscInt *lits)
5227: {
5228: PetscFunctionBegin;
5230: PetscAssertPointer(lits, 2);
5231: *lits = ts->ksp_its;
5232: PetscFunctionReturn(PETSC_SUCCESS);
5233: }
5235: /*@
5236: TSGetStepRejections - Gets the total number of rejected steps over all previous timesteps
5238: Not Collective
5240: Input Parameter:
5241: . ts - `TS` context
5243: Output Parameter:
5244: . rejects - number of steps rejected
5246: Level: intermediate
5248: Note:
5249: This counter is reset to zero when `TSSolve()` starts at step number zero and when `TSAdjointSolve()` starts.
5250: It accumulates over successive `TSSolve()` calls that continue a run, for example with `TSSetRunSteps()`.
5252: .seealso: [](ch_ts), `TS`, `TSSolve()`, `TSGetSNESIterations()`, `TSGetKSPIterations()`, `TSSetMaxStepRejections()`, `TSGetSNESFailures()`, `TSSetMaxSNESFailures()`, `TSSetErrorIfStepFails()`
5253: @*/
5254: PetscErrorCode TSGetStepRejections(TS ts, PetscInt *rejects)
5255: {
5256: PetscFunctionBegin;
5258: PetscAssertPointer(rejects, 2);
5259: *rejects = ts->reject;
5260: PetscFunctionReturn(PETSC_SUCCESS);
5261: }
5263: /*@
5264: TSGetSNESFailures - Gets the total number of failed `SNESSolve()` calls over all previous timesteps
5266: Not Collective
5268: Input Parameter:
5269: . ts - `TS` context
5271: Output Parameter:
5272: . fails - number of failed nonlinear solves
5274: Level: intermediate
5276: Notes:
5277: This counter is reset to zero when `TSSolve()` starts at step number zero and when `TSAdjointSolve()` starts.
5278: It accumulates over successive `TSSolve()` calls that continue a run, for example with `TSSetRunSteps()`.
5280: Except with `TSGLLE`, it does not count `SNESSolve()` failures with reason `SNES_DIVERGED_FUNCTION_DOMAIN`.
5282: .seealso: [](ch_ts), `TS`, `TSSolve()`, `TSGetSNESIterations()`, `TSGetKSPIterations()`, `TSSetMaxStepRejections()`, `TSGetStepRejections()`, `TSSetMaxSNESFailures()`
5283: @*/
5284: PetscErrorCode TSGetSNESFailures(TS ts, PetscInt *fails)
5285: {
5286: PetscFunctionBegin;
5288: PetscAssertPointer(fails, 2);
5289: *fails = ts->num_snes_failures;
5290: PetscFunctionReturn(PETSC_SUCCESS);
5291: }
5293: /*@
5294: TSSetMaxStepRejections - Sets the maximum number of step rejections allowed in a single time-step attempt before a time step fails in `TSSolve()` with `TS_DIVERGED_STEP_REJECTED`
5296: Not Collective
5298: Input Parameters:
5299: + ts - `TS` context
5300: - maxrejects - maximum number of rejected steps, pass `PETSC_UNLIMITED` for unlimited
5302: Options Database Key:
5303: . -ts_max_step_rejections maxrejects - Maximum number of step rejections before a step fails
5305: Level: intermediate
5307: Note:
5308: The limit applies to each time step separately.
5310: .seealso: [](ch_ts), `TS`, `SNES`, `TSGetSNESIterations()`, `TSGetKSPIterations()`, `TSSetMaxSNESFailures()`, `TSGetStepRejections()`, `TSGetSNESFailures()`, `TSSetErrorIfStepFails()`,
5311: `TSGetConvergedReason()`, `TSSolve()`, `TS_DIVERGED_STEP_REJECTED`
5312: @*/
5313: PetscErrorCode TSSetMaxStepRejections(TS ts, PetscInt maxrejects)
5314: {
5315: PetscFunctionBegin;
5317: if (maxrejects == PETSC_UNLIMITED || maxrejects == -1) {
5318: ts->max_reject = PETSC_UNLIMITED;
5319: } else {
5320: PetscCheck(maxrejects >= 0, PetscObjectComm((PetscObject)ts), PETSC_ERR_ARG_OUTOFRANGE, "Cannot have a negative maximum number of rejections");
5321: ts->max_reject = maxrejects;
5322: }
5323: PetscFunctionReturn(PETSC_SUCCESS);
5324: }
5326: /*@
5327: TSSetMaxSNESFailures - Sets the maximum number of failed `SNES` solves allowed before `TSSolve()` is ended with a `TSConvergedReason` of `TS_DIVERGED_NONLINEAR_SOLVE`
5329: Not Collective
5331: Input Parameters:
5332: + ts - `TS` context
5333: - fails - maximum number of failed nonlinear solves, pass `PETSC_UNLIMITED` to allow any number of failures.
5335: Options Database Key:
5336: . -ts_max_snes_failures fails - Maximum number of nonlinear solve failures
5338: Level: intermediate
5340: Note:
5341: The failures are counted as in `TSGetSNESFailures()`, so successive `TSSolve()` calls that continue a run share one limit.
5343: .seealso: [](ch_ts), `TS`, `SNES`, `TSGetSNESIterations()`, `TSGetKSPIterations()`, `TSSetMaxStepRejections()`, `TSGetStepRejections()`, `TSGetSNESFailures()`, `SNESGetConvergedReason()`,
5344: `TSGetConvergedReason()`, `TS_DIVERGED_NONLINEAR_SOLVE`, `TSConvergedReason`
5345: @*/
5346: PetscErrorCode TSSetMaxSNESFailures(TS ts, PetscInt fails)
5347: {
5348: PetscFunctionBegin;
5350: if (fails == PETSC_UNLIMITED || fails == -1) {
5351: ts->max_snes_failures = PETSC_UNLIMITED;
5352: } else {
5353: PetscCheck(fails >= 0, PetscObjectComm((PetscObject)ts), PETSC_ERR_ARG_OUTOFRANGE, "Cannot have a negative maximum number of failures");
5354: ts->max_snes_failures = fails;
5355: }
5356: PetscFunctionReturn(PETSC_SUCCESS);
5357: }
5359: /*@
5360: TSSetErrorIfStepFails - Immediately error if no step succeeds during `TSSolve()`
5362: Not Collective
5364: Input Parameters:
5365: + ts - `TS` context
5366: - err - `PETSC_TRUE` to error if no step succeeds, `PETSC_FALSE` to return without failure
5368: Options Database Key:
5369: . -ts_error_if_step_fails (true|false) - Error if no step succeeds, otherwise `TSSolve()` returns an appropriate value obtainable with `TSGetConvergedReason()`
5371: Level: intermediate
5373: .seealso: [](ch_ts), `TS`, `TSGetSNESIterations()`, `TSGetKSPIterations()`, `TSSetMaxStepRejections()`, `TSGetStepRejections()`, `TSGetSNESFailures()`, `TSGetConvergedReason()`
5374: @*/
5375: PetscErrorCode TSSetErrorIfStepFails(TS ts, PetscBool err)
5376: {
5377: PetscFunctionBegin;
5379: ts->errorifstepfailed = err;
5380: PetscFunctionReturn(PETSC_SUCCESS);
5381: }
5383: /*@
5384: TSGetAdapt - Get the adaptive controller context for the current method
5386: Collective if controller has not yet been created
5388: Input Parameter:
5389: . ts - time stepping context
5391: Output Parameter:
5392: . adapt - adaptive controller
5394: Level: intermediate
5396: .seealso: [](ch_ts), `TS`, `TSAdapt`, `TSAdaptSetType()`, `TSAdaptChoose()`
5397: @*/
5398: PetscErrorCode TSGetAdapt(TS ts, TSAdapt *adapt)
5399: {
5400: PetscFunctionBegin;
5402: PetscAssertPointer(adapt, 2);
5403: if (!ts->adapt) {
5404: PetscCall(TSAdaptCreate(PetscObjectComm((PetscObject)ts), &ts->adapt));
5405: PetscCall(PetscObjectIncrementTabLevel((PetscObject)ts->adapt, (PetscObject)ts, 1));
5406: }
5407: *adapt = ts->adapt;
5408: PetscFunctionReturn(PETSC_SUCCESS);
5409: }
5411: /*@
5412: TSSetTolerances - Set tolerances for local truncation error when using an adaptive controller
5414: Logically Collective
5416: Input Parameters:
5417: + ts - time integration context
5418: . atol - scalar absolute tolerances
5419: . vatol - vector of absolute tolerances or `NULL`, used in preference to `atol` if present
5420: . rtol - scalar relative tolerances
5421: - vrtol - vector of relative tolerances or `NULL`, used in preference to `rtol` if present
5423: Options Database Keys:
5424: + -ts_rtol rtol - relative tolerance for local truncation error
5425: - -ts_atol atol - Absolute tolerance for local truncation error
5427: Level: beginner
5429: Notes:
5430: `PETSC_CURRENT` or `PETSC_DETERMINE` may be used for `atol` or `rtol` to indicate the current value
5431: or the default value from when the object's type was set.
5433: With PETSc's implicit schemes for DAE problems, the calculation of the local truncation error
5434: (LTE) includes both the differential and the algebraic variables. If one wants the LTE to be
5435: computed only for the differential or the algebraic part then this can be done using the vector of
5436: tolerances vatol. For example, by setting the tolerance vector with the desired tolerance for the
5437: differential part and infinity for the algebraic part, the LTE calculation will include only the
5438: differential variables.
5440: Fortran Note:
5441: Use `PETSC_CURRENT_INTEGER` or `PETSC_DETERMINE_INTEGER`.
5443: .seealso: [](ch_ts), `TS`, `TSAdapt`, `TSErrorWeightedNorm()`, `TSGetTolerances()`
5444: @*/
5445: PetscErrorCode TSSetTolerances(TS ts, PetscReal atol, Vec vatol, PetscReal rtol, Vec vrtol)
5446: {
5447: PetscFunctionBegin;
5448: if (atol == (PetscReal)PETSC_DETERMINE) {
5449: ts->atol = ts->default_atol;
5450: } else if (atol != (PetscReal)PETSC_CURRENT) {
5451: PetscCheck(atol >= 0.0, PetscObjectComm((PetscObject)ts), PETSC_ERR_ARG_OUTOFRANGE, "Absolute tolerance %g must be non-negative", (double)atol);
5452: ts->atol = atol;
5453: }
5455: if (vatol) {
5456: PetscCall(PetscObjectReference((PetscObject)vatol));
5457: PetscCall(VecDestroy(&ts->vatol));
5458: ts->vatol = vatol;
5459: }
5461: if (rtol == (PetscReal)PETSC_DETERMINE) {
5462: ts->rtol = ts->default_rtol;
5463: } else if (rtol != (PetscReal)PETSC_CURRENT) {
5464: PetscCheck(rtol >= 0.0, PetscObjectComm((PetscObject)ts), PETSC_ERR_ARG_OUTOFRANGE, "Relative tolerance %g must be non-negative", (double)rtol);
5465: ts->rtol = rtol;
5466: }
5468: if (vrtol) {
5469: PetscCall(PetscObjectReference((PetscObject)vrtol));
5470: PetscCall(VecDestroy(&ts->vrtol));
5471: ts->vrtol = vrtol;
5472: }
5473: PetscFunctionReturn(PETSC_SUCCESS);
5474: }
5476: /*@
5477: TSGetTolerances - Get tolerances for local truncation error when using adaptive controller
5479: Logically Collective
5481: Input Parameter:
5482: . ts - time integration context
5484: Output Parameters:
5485: + atol - scalar absolute tolerances, `NULL` to ignore
5486: . vatol - vector of absolute tolerances, `NULL` to ignore
5487: . rtol - scalar relative tolerances, `NULL` to ignore
5488: - vrtol - vector of relative tolerances, `NULL` to ignore
5490: Level: beginner
5492: .seealso: [](ch_ts), `TS`, `TSAdapt`, `TSErrorWeightedNorm()`, `TSSetTolerances()`
5493: @*/
5494: PetscErrorCode TSGetTolerances(TS ts, PetscReal *atol, Vec *vatol, PetscReal *rtol, Vec *vrtol)
5495: {
5496: PetscFunctionBegin;
5497: if (atol) *atol = ts->atol;
5498: if (vatol) *vatol = ts->vatol;
5499: if (rtol) *rtol = ts->rtol;
5500: if (vrtol) *vrtol = ts->vrtol;
5501: PetscFunctionReturn(PETSC_SUCCESS);
5502: }
5504: /*@
5505: TSErrorWeightedNorm - compute a weighted norm of the difference between two state vectors based on supplied absolute and relative tolerances
5507: Collective
5509: Input Parameters:
5510: + ts - time stepping context
5511: . U - state vector, usually ts->vec_sol
5512: . Y - state vector to be compared to U
5513: - wnormtype - norm type, either `NORM_2` or `NORM_INFINITY`
5515: Output Parameters:
5516: + norm - weighted norm, a value of 1.0 achieves a balance between absolute and relative tolerances
5517: . norma - weighted norm, a value of 1.0 means that the error meets the absolute tolerance set by the user
5518: - normr - weighted norm, a value of 1.0 means that the error meets the relative tolerance set by the user
5520: Options Database Key:
5521: . -ts_adapt_wnormtype wnormtype - 2, INFINITY
5523: Level: developer
5525: .seealso: [](ch_ts), `TS`, `VecErrorWeightedNorms()`, `TSErrorWeightedENorm()`
5526: @*/
5527: PetscErrorCode TSErrorWeightedNorm(TS ts, Vec U, Vec Y, NormType wnormtype, PetscReal *norm, PetscReal *norma, PetscReal *normr)
5528: {
5529: PetscInt norma_loc, norm_loc, normr_loc;
5531: PetscFunctionBegin;
5536: PetscAssertPointer(norm, 5);
5537: PetscAssertPointer(norma, 6);
5538: PetscAssertPointer(normr, 7);
5539: PetscCall(VecErrorWeightedNorms(U, Y, NULL, wnormtype, ts->atol, ts->vatol, ts->rtol, ts->vrtol, ts->adapt->ignore_max, norm, &norm_loc, norma, &norma_loc, normr, &normr_loc));
5540: if (wnormtype == NORM_2) {
5541: if (norm_loc) *norm = PetscSqrtReal(PetscSqr(*norm) / norm_loc);
5542: if (norma_loc) *norma = PetscSqrtReal(PetscSqr(*norma) / norma_loc);
5543: if (normr_loc) *normr = PetscSqrtReal(PetscSqr(*normr) / normr_loc);
5544: }
5545: PetscCheck(!PetscIsInfOrNanScalar(*norm), PetscObjectComm((PetscObject)ts), PETSC_ERR_FP, "Infinite or not-a-number generated in norm");
5546: PetscCheck(!PetscIsInfOrNanScalar(*norma), PetscObjectComm((PetscObject)ts), PETSC_ERR_FP, "Infinite or not-a-number generated in norma");
5547: PetscCheck(!PetscIsInfOrNanScalar(*normr), PetscObjectComm((PetscObject)ts), PETSC_ERR_FP, "Infinite or not-a-number generated in normr");
5548: PetscFunctionReturn(PETSC_SUCCESS);
5549: }
5551: /*@
5552: TSErrorWeightedENorm - compute a weighted error norm based on supplied absolute and relative tolerances
5554: Collective
5556: Input Parameters:
5557: + ts - time stepping context
5558: . E - error vector
5559: . U - state vector, usually ts->vec_sol
5560: . Y - state vector, previous time step
5561: - wnormtype - norm type, either `NORM_2` or `NORM_INFINITY`
5563: Output Parameters:
5564: + norm - weighted norm, a value of 1.0 achieves a balance between absolute and relative tolerances
5565: . norma - weighted norm, a value of 1.0 means that the error meets the absolute tolerance set by the user
5566: - normr - weighted norm, a value of 1.0 means that the error meets the relative tolerance set by the user
5568: Options Database Key:
5569: . -ts_adapt_wnormtype wnormtype - 2, INFINITY
5571: Level: developer
5573: .seealso: [](ch_ts), `TS`, `VecErrorWeightedNorms()`, `TSErrorWeightedNorm()`
5574: @*/
5575: PetscErrorCode TSErrorWeightedENorm(TS ts, Vec E, Vec U, Vec Y, NormType wnormtype, PetscReal *norm, PetscReal *norma, PetscReal *normr)
5576: {
5577: PetscInt norma_loc, norm_loc, normr_loc;
5579: PetscFunctionBegin;
5581: PetscCall(VecErrorWeightedNorms(U, Y, E, wnormtype, ts->atol, ts->vatol, ts->rtol, ts->vrtol, ts->adapt->ignore_max, norm, &norm_loc, norma, &norma_loc, normr, &normr_loc));
5582: if (wnormtype == NORM_2) {
5583: if (norm_loc) *norm = PetscSqrtReal(PetscSqr(*norm) / norm_loc);
5584: if (norma_loc) *norma = PetscSqrtReal(PetscSqr(*norma) / norma_loc);
5585: if (normr_loc) *normr = PetscSqrtReal(PetscSqr(*normr) / normr_loc);
5586: }
5587: PetscCheck(!PetscIsInfOrNanScalar(*norm), PetscObjectComm((PetscObject)ts), PETSC_ERR_FP, "Infinite or not-a-number generated in norm");
5588: PetscCheck(!PetscIsInfOrNanScalar(*norma), PetscObjectComm((PetscObject)ts), PETSC_ERR_FP, "Infinite or not-a-number generated in norma");
5589: PetscCheck(!PetscIsInfOrNanScalar(*normr), PetscObjectComm((PetscObject)ts), PETSC_ERR_FP, "Infinite or not-a-number generated in normr");
5590: PetscFunctionReturn(PETSC_SUCCESS);
5591: }
5593: /*@
5594: TSSetCFLTimeLocal - Set the local CFL constraint relative to forward Euler
5596: Logically Collective
5598: Input Parameters:
5599: + ts - time stepping context
5600: - cfltime - maximum stable time step if using forward Euler (value can be different on each process)
5602: Note:
5603: After calling this function, the global CFL time can be obtained by calling TSGetCFLTime()
5605: Level: intermediate
5607: .seealso: [](ch_ts), `TSGetCFLTime()`, `TSADAPTCFL`
5608: @*/
5609: PetscErrorCode TSSetCFLTimeLocal(TS ts, PetscReal cfltime)
5610: {
5611: PetscFunctionBegin;
5613: ts->cfltime_local = cfltime;
5614: ts->cfltime = -1.;
5615: PetscFunctionReturn(PETSC_SUCCESS);
5616: }
5618: /*@
5619: TSGetCFLTime - Get the maximum stable time step according to CFL criteria applied to forward Euler
5621: Collective
5623: Input Parameter:
5624: . ts - time stepping context
5626: Output Parameter:
5627: . cfltime - maximum stable time step for forward Euler
5629: Level: advanced
5631: .seealso: [](ch_ts), `TSSetCFLTimeLocal()`
5632: @*/
5633: PetscErrorCode TSGetCFLTime(TS ts, PetscReal *cfltime)
5634: {
5635: PetscFunctionBegin;
5636: if (ts->cfltime < 0) PetscCallMPI(MPIU_Allreduce(&ts->cfltime_local, &ts->cfltime, 1, MPIU_REAL, MPIU_MIN, PetscObjectComm((PetscObject)ts)));
5637: *cfltime = ts->cfltime;
5638: PetscFunctionReturn(PETSC_SUCCESS);
5639: }
5641: /*@
5642: TSVISetVariableBounds - Sets the lower and upper bounds for the solution vector. xl <= x <= xu
5644: Input Parameters:
5645: + ts - the `TS` context.
5646: . xl - lower bound.
5647: - xu - upper bound.
5649: Level: advanced
5651: Note:
5652: If this routine is not called then the lower and upper bounds are set to
5653: `PETSC_NINFINITY` and `PETSC_INFINITY` respectively during `SNESSetUp()`.
5655: .seealso: [](ch_ts), `TS`
5656: @*/
5657: PetscErrorCode TSVISetVariableBounds(TS ts, Vec xl, Vec xu)
5658: {
5659: SNES snes;
5661: PetscFunctionBegin;
5662: PetscCall(TSGetSNES(ts, &snes));
5663: PetscCall(SNESVISetVariableBounds(snes, xl, xu));
5664: PetscFunctionReturn(PETSC_SUCCESS);
5665: }
5667: /*@
5668: TSComputeLinearStability - computes the linear stability function at a point
5670: Collective
5672: Input Parameters:
5673: + ts - the `TS` context
5674: . xr - real part of input argument
5675: - xi - imaginary part of input argument
5677: Output Parameters:
5678: + yr - real part of function value
5679: - yi - imaginary part of function value
5681: Level: developer
5683: .seealso: [](ch_ts), `TS`, `TSSetRHSFunction()`, `TSComputeIFunction()`
5684: @*/
5685: PetscErrorCode TSComputeLinearStability(TS ts, PetscReal xr, PetscReal xi, PetscReal *yr, PetscReal *yi)
5686: {
5687: PetscFunctionBegin;
5689: PetscUseTypeMethod(ts, linearstability, xr, xi, yr, yi);
5690: PetscFunctionReturn(PETSC_SUCCESS);
5691: }
5693: /*@
5694: TSRestartStep - Flags the solver to restart the next step
5696: Collective
5698: Input Parameter:
5699: . ts - the `TS` context obtained from `TSCreate()`
5701: Level: advanced
5703: Notes:
5704: Multistep methods like `TSBDF` or Runge-Kutta methods with FSAL property require restarting the solver in the event of
5705: discontinuities. These discontinuities may be introduced as a consequence of explicitly modifications to the solution
5706: vector (which PETSc attempts to detect and handle) or problem coefficients (which PETSc is not able to detect). For
5707: the sake of correctness and maximum safety, users are expected to call `TSRestart()` whenever they introduce
5708: discontinuities in callback routines (e.g. prestep and poststep routines, or implicit/rhs function routines with
5709: discontinuous source terms).
5711: .seealso: [](ch_ts), `TS`, `TSBDF`, `TSSolve()`, `TSSetPreStep()`, `TSSetPostStep()`
5712: @*/
5713: PetscErrorCode TSRestartStep(TS ts)
5714: {
5715: PetscFunctionBegin;
5717: ts->steprestart = PETSC_TRUE;
5718: PetscFunctionReturn(PETSC_SUCCESS);
5719: }
5721: /*@
5722: TSRollBack - Rolls back one time step
5724: Collective
5726: Input Parameter:
5727: . ts - the `TS` context obtained from `TSCreate()`
5729: Level: advanced
5731: .seealso: [](ch_ts), `TS`, `TSGetStepRollBack()`, `TSCreate()`, `TSSetUp()`, `TSDestroy()`, `TSSolve()`, `TSSetPreStep()`, `TSSetPreStage()`, `TSInterpolate()`
5732: @*/
5733: PetscErrorCode TSRollBack(TS ts)
5734: {
5735: PetscFunctionBegin;
5737: PetscCheck(!ts->steprollback, PetscObjectComm((PetscObject)ts), PETSC_ERR_ARG_WRONGSTATE, "TSRollBack already called");
5738: PetscTryTypeMethod(ts, rollback);
5739: PetscCall(VecCopy(ts->vec_sol0, ts->vec_sol));
5740: ts->time_step = ts->ptime - ts->ptime_prev;
5741: ts->ptime = ts->ptime_prev;
5742: ts->ptime_prev = ts->ptime_prev_rollback;
5743: ts->steps--;
5744: ts->steprollback = PETSC_TRUE;
5745: PetscFunctionReturn(PETSC_SUCCESS);
5746: }
5748: /*@
5749: TSGetStepRollBack - Get the internal flag indicating if you are rolling back a step
5751: Not collective
5753: Input Parameter:
5754: . ts - the `TS` context obtained from `TSCreate()`
5756: Output Parameter:
5757: . flg - the rollback flag
5759: Level: advanced
5761: .seealso: [](ch_ts), `TS`, `TSCreate()`, `TSRollBack()`
5762: @*/
5763: PetscErrorCode TSGetStepRollBack(TS ts, PetscBool *flg)
5764: {
5765: PetscFunctionBegin;
5767: PetscAssertPointer(flg, 2);
5768: *flg = ts->steprollback;
5769: PetscFunctionReturn(PETSC_SUCCESS);
5770: }
5772: /*@
5773: TSGetStepResize - Get the internal flag indicating if the current step is after a resize.
5775: Not collective
5777: Input Parameter:
5778: . ts - the `TS` context obtained from `TSCreate()`
5780: Output Parameter:
5781: . flg - the resize flag
5783: Level: advanced
5785: .seealso: [](ch_ts), `TS`, `TSCreate()`, `TSSetResize()`
5786: @*/
5787: PetscErrorCode TSGetStepResize(TS ts, PetscBool *flg)
5788: {
5789: PetscFunctionBegin;
5791: PetscAssertPointer(flg, 2);
5792: *flg = ts->stepresize;
5793: PetscFunctionReturn(PETSC_SUCCESS);
5794: }
5796: /*@
5797: TSGetStages - Get the number of stages and stage values
5799: Input Parameter:
5800: . ts - the `TS` context obtained from `TSCreate()`
5802: Output Parameters:
5803: + ns - the number of stages
5804: - Y - the current stage vectors
5806: Level: advanced
5808: Note:
5809: Both `ns` and `Y` can be `NULL`.
5811: .seealso: [](ch_ts), `TS`, `TSCreate()`
5812: @*/
5813: PetscErrorCode TSGetStages(TS ts, PetscInt *ns, Vec **Y)
5814: {
5815: PetscFunctionBegin;
5817: if (ns) PetscAssertPointer(ns, 2);
5818: if (Y) PetscAssertPointer(Y, 3);
5819: if (!ts->ops->getstages) {
5820: if (ns) *ns = 0;
5821: if (Y) *Y = NULL;
5822: } else PetscUseTypeMethod(ts, getstages, ns, Y);
5823: PetscFunctionReturn(PETSC_SUCCESS);
5824: }
5826: /*@
5827: TSComputeIJacobianDefaultColor - Computes the Jacobian using finite differences and coloring to exploit matrix sparsity.
5829: Collective
5831: Input Parameters:
5832: + ts - the `TS` context
5833: . t - current timestep
5834: . U - state vector
5835: . Udot - time derivative of state vector
5836: . shift - shift to apply, see note below
5837: - ctx - an optional application context
5839: Output Parameters:
5840: + J - Jacobian matrix (not altered in this routine)
5841: - B - newly computed Jacobian matrix to use with preconditioner (generally the same as `J`)
5843: Level: intermediate
5845: Notes:
5846: If F(t,U,Udot)=0 is the DAE, the required Jacobian is
5848: dF/dU + shift*dF/dUdot
5850: Most users should not need to explicitly call this routine, as it
5851: is used internally within the nonlinear solvers.
5853: This will first try to get the coloring from the `DM`. If the `DM` type has no coloring
5854: routine, then it will try to get the coloring from the matrix. This requires that the
5855: matrix have nonzero entries precomputed.
5857: .seealso: [](ch_ts), `TS`, `TSSetIJacobian()`, `MatFDColoringCreate()`, `MatFDColoringSetFunction()`
5858: @*/
5859: PetscErrorCode TSComputeIJacobianDefaultColor(TS ts, PetscReal t, Vec U, Vec Udot, PetscReal shift, Mat J, Mat B, PetscCtx ctx)
5860: {
5861: SNES snes;
5862: MatFDColoring color;
5863: PetscBool hascolor, matcolor = PETSC_FALSE;
5865: PetscFunctionBegin;
5866: PetscCall(PetscOptionsGetBool(((PetscObject)ts)->options, ((PetscObject)ts)->prefix, "-ts_fd_color_use_mat", &matcolor, NULL));
5867: PetscCall(PetscObjectQuery((PetscObject)B, "TSMatFDColoring", (PetscObject *)&color));
5868: if (!color) {
5869: DM dm;
5870: ISColoring iscoloring;
5872: PetscCall(TSGetDM(ts, &dm));
5873: PetscCall(DMHasColoring(dm, &hascolor));
5874: if (hascolor && !matcolor) {
5875: PetscCall(DMCreateColoring(dm, IS_COLORING_GLOBAL, &iscoloring));
5876: PetscCall(MatFDColoringCreate(B, iscoloring, &color));
5877: PetscCall(MatFDColoringSetFunction(color, (MatFDColoringFn *)SNESTSFormFunction, (void *)ts));
5878: PetscCall(MatFDColoringSetFromOptions(color));
5879: PetscCall(MatFDColoringSetUp(B, iscoloring, color));
5880: PetscCall(ISColoringDestroy(&iscoloring));
5881: } else {
5882: MatColoring mc;
5884: PetscCall(MatColoringCreate(B, &mc));
5885: PetscCall(MatColoringSetDistance(mc, 2));
5886: PetscCall(MatColoringSetType(mc, MATCOLORINGSL));
5887: PetscCall(MatColoringSetFromOptions(mc));
5888: PetscCall(MatColoringApply(mc, &iscoloring));
5889: PetscCall(MatColoringDestroy(&mc));
5890: PetscCall(MatFDColoringCreate(B, iscoloring, &color));
5891: PetscCall(MatFDColoringSetFunction(color, (MatFDColoringFn *)SNESTSFormFunction, (void *)ts));
5892: PetscCall(MatFDColoringSetFromOptions(color));
5893: PetscCall(MatFDColoringSetUp(B, iscoloring, color));
5894: PetscCall(ISColoringDestroy(&iscoloring));
5895: }
5896: PetscCall(PetscObjectCompose((PetscObject)B, "TSMatFDColoring", (PetscObject)color));
5897: PetscCall(PetscObjectDereference((PetscObject)color));
5898: }
5899: PetscCall(TSGetSNES(ts, &snes));
5900: PetscCall(MatFDColoringApply(B, color, U, snes));
5901: if (J != B) {
5902: PetscCall(MatAssemblyBegin(J, MAT_FINAL_ASSEMBLY));
5903: PetscCall(MatAssemblyEnd(J, MAT_FINAL_ASSEMBLY));
5904: }
5905: PetscFunctionReturn(PETSC_SUCCESS);
5906: }
5908: /*@
5909: TSSetFunctionDomainError - Set a function that tests if the current state vector is valid
5911: Logically collective
5913: Input Parameters:
5914: + ts - the `TS` context
5915: - func - function called within `TSFunctionDomainError()`
5917: Calling sequence of `func`:
5918: + ts - the `TS` context
5919: . time - the current time (of the stage)
5920: . state - the state to check if it is valid
5921: - accept - (output parameter) `PETSC_FALSE` if the state is not acceptable, `PETSC_TRUE` if acceptable
5923: Level: intermediate
5925: Notes:
5926: `accept` must be collectively specified.
5927: If an implicit ODE solver is being used then, in addition to providing this routine, the
5928: user's code should call `SNESSetFunctionDomainError()` when domain errors occur during
5929: function evaluations where the functions are provided by `TSSetIFunction()` or `TSSetRHSFunction()`.
5930: Use `TSGetSNES()` to obtain the `SNES` object
5932: Developer Notes:
5933: The naming of this function is inconsistent with the `SNESSetFunctionDomainError()`
5934: since one takes a function pointer and the other does not.
5936: .seealso: [](ch_ts), `TSAdaptCheckStage()`, `TSFunctionDomainError()`, `SNESSetFunctionDomainError()`, `TSGetSNES()`
5937: @*/
5938: PetscErrorCode TSSetFunctionDomainError(TS ts, PetscErrorCode (*func)(TS ts, PetscReal time, Vec state, PetscBool *accept))
5939: {
5940: PetscFunctionBegin;
5942: ts->functiondomainerror = func;
5943: PetscFunctionReturn(PETSC_SUCCESS);
5944: }
5946: /*@
5947: TSFunctionDomainError - Checks if the current state is valid
5949: Collective
5951: Input Parameters:
5952: + ts - the `TS` context
5953: . stagetime - time of the simulation
5954: - Y - state vector to check.
5956: Output Parameter:
5957: . accept - Set to `PETSC_FALSE` if the current state vector is valid.
5959: Level: developer
5961: Note:
5962: This function is called by the `TS` integration routines and calls the user provided function (set with `TSSetFunctionDomainError()`)
5963: to check if the current state is valid.
5965: .seealso: [](ch_ts), `TS`, `TSSetFunctionDomainError()`
5966: @*/
5967: PetscErrorCode TSFunctionDomainError(TS ts, PetscReal stagetime, Vec Y, PetscBool *accept)
5968: {
5969: PetscFunctionBegin;
5973: PetscAssertPointer(accept, 4);
5974: *accept = PETSC_TRUE;
5975: if (ts->functiondomainerror) PetscCall((*ts->functiondomainerror)(ts, stagetime, Y, accept));
5976: PetscFunctionReturn(PETSC_SUCCESS);
5977: }
5979: /*@
5980: TSClone - This function clones a time step `TS` object.
5982: Collective
5984: Input Parameter:
5985: . tsin - The input `TS`
5987: Output Parameter:
5988: . tsout - The output `TS` (cloned)
5990: Level: developer
5992: Notes:
5993: This function is used to create a clone of a `TS` object. It is used in `TSARKIMEX` for initializing the slope for first stage explicit methods.
5994: It will likely be replaced in the future with a mechanism of switching methods on the fly.
5996: 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
5997: .vb
5998: SNES snes_dup = NULL;
5999: TSGetSNES(ts,&snes_dup);
6000: TSSetSNES(ts,snes_dup);
6001: .ve
6003: .seealso: [](ch_ts), `TS`, `SNES`, `TSCreate()`, `TSSetType()`, `TSSetUp()`, `TSDestroy()`, `TSSetProblemType()`
6004: @*/
6005: PetscErrorCode TSClone(TS tsin, TS *tsout)
6006: {
6007: TS t;
6008: SNES snes_start;
6009: DM dm;
6010: TSType type;
6012: PetscFunctionBegin;
6013: PetscAssertPointer(tsin, 1);
6014: *tsout = NULL;
6016: PetscCall(PetscHeaderCreate(t, TS_CLASSID, "TS", "Time stepping", "TS", PetscObjectComm((PetscObject)tsin), TSDestroy, TSView));
6018: /* General TS description */
6019: t->numbermonitors = 0;
6020: t->setupcalled = PETSC_FALSE;
6021: t->ksp_its = 0;
6022: t->snes_its = 0;
6023: t->nwork = 0;
6024: t->rhsjacobian.time = PETSC_MIN_REAL;
6025: t->rhsjacobian.scale = 1.;
6026: t->ijacobian.shift = 1.;
6028: PetscCall(TSGetSNES(tsin, &snes_start));
6029: PetscCall(TSSetSNES(t, snes_start));
6031: PetscCall(TSGetDM(tsin, &dm));
6032: PetscCall(TSSetDM(t, dm));
6034: t->adapt = tsin->adapt;
6035: PetscCall(PetscObjectReference((PetscObject)t->adapt));
6037: t->trajectory = tsin->trajectory;
6038: PetscCall(PetscObjectReference((PetscObject)t->trajectory));
6040: t->event = tsin->event;
6041: if (t->event) t->event->refct++;
6043: t->problem_type = tsin->problem_type;
6044: t->ptime = tsin->ptime;
6045: t->ptime_prev = tsin->ptime_prev;
6046: t->time_step = tsin->time_step;
6047: t->max_time = tsin->max_time;
6048: t->steps = tsin->steps;
6049: t->max_steps = tsin->max_steps;
6050: t->equation_type = tsin->equation_type;
6051: t->atol = tsin->atol;
6052: t->rtol = tsin->rtol;
6053: t->max_snes_failures = tsin->max_snes_failures;
6054: t->max_reject = tsin->max_reject;
6055: t->errorifstepfailed = tsin->errorifstepfailed;
6057: PetscCall(TSGetType(tsin, &type));
6058: PetscCall(TSSetType(t, type));
6060: t->vec_sol = NULL;
6062: t->cfltime = tsin->cfltime;
6063: t->cfltime_local = tsin->cfltime_local;
6064: t->exact_final_time = tsin->exact_final_time;
6066: t->ops[0] = tsin->ops[0];
6068: if (((PetscObject)tsin)->fortran_func_pointers) {
6069: PetscCall(PetscMalloc((10) * sizeof(PetscFortranCallbackFn *), &((PetscObject)t)->fortran_func_pointers));
6070: for (PetscInt i = 0; i < 10; i++) ((PetscObject)t)->fortran_func_pointers[i] = ((PetscObject)tsin)->fortran_func_pointers[i];
6071: }
6072: *tsout = t;
6073: PetscFunctionReturn(PETSC_SUCCESS);
6074: }
6076: static PetscErrorCode RHSWrapperFunction_TSRHSJacobianTest(PetscCtx ctx, Vec x, Vec y)
6077: {
6078: TS ts = (TS)ctx;
6080: PetscFunctionBegin;
6081: PetscCall(TSComputeRHSFunction(ts, 0, x, y));
6082: PetscFunctionReturn(PETSC_SUCCESS);
6083: }
6085: /*@
6086: TSRHSJacobianTest - Compares the multiply routine provided to the `MATSHELL` with differencing on the `TS` given RHS function.
6088: Logically Collective
6090: Input Parameter:
6091: . ts - the time stepping routine
6093: Output Parameter:
6094: . flg - `PETSC_TRUE` if the multiply is likely correct
6096: Options Database Key:
6097: . -ts_rhs_jacobian_test_mult -mat_shell_test_mult_view - run the test at each timestep of the integrator
6099: Level: advanced
6101: Note:
6102: This only works for problems defined using `TSSetRHSFunction()` and Jacobian NOT `TSSetIFunction()` and Jacobian
6104: .seealso: [](ch_ts), `TS`, `Mat`, `MATSHELL`, `MatCreateShell()`, `MatShellGetContext()`, `MatShellGetOperation()`, `MatShellTestMultTranspose()`, `TSRHSJacobianTestTranspose()`
6105: @*/
6106: PetscErrorCode TSRHSJacobianTest(TS ts, PetscBool *flg)
6107: {
6108: Mat J, B;
6109: TSRHSJacobianFn *func;
6110: void *ctx;
6112: PetscFunctionBegin;
6113: PetscCall(TSGetRHSJacobian(ts, &J, &B, &func, &ctx));
6114: PetscCall((*func)(ts, 0.0, ts->vec_sol, J, B, ctx));
6115: PetscCall(MatShellTestMult(J, RHSWrapperFunction_TSRHSJacobianTest, ts->vec_sol, ts, flg));
6116: PetscFunctionReturn(PETSC_SUCCESS);
6117: }
6119: /*@
6120: TSRHSJacobianTestTranspose - Compares the multiply transpose routine provided to the `MATSHELL` with differencing on the `TS` given RHS function.
6122: Logically Collective
6124: Input Parameter:
6125: . ts - the time stepping routine
6127: Output Parameter:
6128: . flg - `PETSC_TRUE` if the multiply is likely correct
6130: Options Database Key:
6131: . -ts_rhs_jacobian_test_mult_transpose -mat_shell_test_mult_transpose_view - run the test at each timestep of the integrator
6133: Level: advanced
6135: Notes:
6136: This only works for problems defined using `TSSetRHSFunction()` and Jacobian NOT `TSSetIFunction()` and Jacobian
6138: .seealso: [](ch_ts), `TS`, `Mat`, `MatCreateShell()`, `MatShellGetContext()`, `MatShellGetOperation()`, `MatShellTestMultTranspose()`, `TSRHSJacobianTest()`
6139: @*/
6140: PetscErrorCode TSRHSJacobianTestTranspose(TS ts, PetscBool *flg)
6141: {
6142: Mat J, B;
6143: void *ctx;
6144: TSRHSJacobianFn *func;
6146: PetscFunctionBegin;
6147: PetscCall(TSGetRHSJacobian(ts, &J, &B, &func, &ctx));
6148: PetscCall((*func)(ts, 0.0, ts->vec_sol, J, B, ctx));
6149: PetscCall(MatShellTestMultTranspose(J, RHSWrapperFunction_TSRHSJacobianTest, ts->vec_sol, ts, flg));
6150: PetscFunctionReturn(PETSC_SUCCESS);
6151: }
6153: /*@
6154: TSSetUseSplitRHSFunction - Use the split RHSFunction when a multirate method is used.
6156: Logically Collective
6158: Input Parameters:
6159: + ts - timestepping context
6160: - use_splitrhsfunction - `PETSC_TRUE` indicates that the split RHSFunction will be used
6162: Options Database Key:
6163: . -ts_use_splitrhsfunction (true|false) - use the split RHS function for multirate solvers
6165: Level: intermediate
6167: Note:
6168: This is only for multirate methods
6170: .seealso: [](ch_ts), `TS`, `TSGetUseSplitRHSFunction()`
6171: @*/
6172: PetscErrorCode TSSetUseSplitRHSFunction(TS ts, PetscBool use_splitrhsfunction)
6173: {
6174: PetscFunctionBegin;
6176: ts->use_splitrhsfunction = use_splitrhsfunction;
6177: PetscFunctionReturn(PETSC_SUCCESS);
6178: }
6180: /*@
6181: TSGetUseSplitRHSFunction - Gets whether to use the split RHSFunction when a multirate method is used.
6183: Not Collective
6185: Input Parameter:
6186: . ts - timestepping context
6188: Output Parameter:
6189: . use_splitrhsfunction - `PETSC_TRUE` indicates that the split RHSFunction will be used
6191: Level: intermediate
6193: .seealso: [](ch_ts), `TS`, `TSSetUseSplitRHSFunction()`
6194: @*/
6195: PetscErrorCode TSGetUseSplitRHSFunction(TS ts, PetscBool *use_splitrhsfunction)
6196: {
6197: PetscFunctionBegin;
6199: *use_splitrhsfunction = ts->use_splitrhsfunction;
6200: PetscFunctionReturn(PETSC_SUCCESS);
6201: }
6203: /*@
6204: TSSetMatStructure - sets the relationship between the nonzero structure of the RHS Jacobian matrix to the IJacobian matrix.
6206: Logically Collective
6208: Input Parameters:
6209: + ts - the time-stepper
6210: - str - the structure (the default is `UNKNOWN_NONZERO_PATTERN`)
6212: Level: intermediate
6214: Note:
6215: When the relationship between the nonzero structures is known and supplied the solution process can be much faster
6217: .seealso: [](ch_ts), `TS`, `MatAXPY()`, `MatStructure`
6218: @*/
6219: PetscErrorCode TSSetMatStructure(TS ts, MatStructure str)
6220: {
6221: PetscFunctionBegin;
6223: ts->axpy_pattern = str;
6224: PetscFunctionReturn(PETSC_SUCCESS);
6225: }
6227: /*@
6228: TSSetEvaluationTimes - sets the evaluation points. The solution will be computed and stored for each time requested
6230: Collective
6232: Input Parameters:
6233: + ts - the time-stepper
6234: . n - number of the time points
6235: - time_points - array of the time points, must be increasing
6237: Options Database Key:
6238: . -ts_eval_times t0,...,tn - Sets the evaluation times
6240: Level: intermediate
6242: Notes:
6243: The elements in `time_points` must be all increasing. They correspond to the intermediate points to be saved.
6245: `TS_EXACTFINALTIME_MATCHSTEP` must be used to make the last time step in each sub-interval match the intermediate points specified.
6247: The intermediate solutions are saved in a vector array that can be accessed with `TSGetEvaluationSolutions()`. Thus using evaluation times may
6248: pressure the memory system when using a large number of time points.
6250: .seealso: [](ch_ts), `TS`, `TSGetEvaluationTimes()`, `TSGetEvaluationSolutions()`, `TSSetTimeSpan()`
6251: @*/
6252: PetscErrorCode TSSetEvaluationTimes(TS ts, PetscInt n, PetscReal time_points[])
6253: {
6254: PetscBool is_sorted;
6256: PetscFunctionBegin;
6258: if (ts->eval_times) { // Reset eval_times
6259: ts->eval_times->sol_idx = 0;
6260: ts->eval_times->time_point_idx = 0;
6261: if (n != ts->eval_times->num_time_points) {
6262: PetscCall(PetscFree(ts->eval_times->time_points));
6263: PetscCall(PetscFree(ts->eval_times->sol_times));
6264: PetscCall(VecDestroyVecs(ts->eval_times->num_time_points, &ts->eval_times->sol_vecs));
6265: } else {
6266: PetscCall(PetscArrayzero(ts->eval_times->sol_times, n));
6267: for (PetscInt i = 0; i < n; i++) PetscCall(VecZeroEntries(ts->eval_times->sol_vecs[i]));
6268: }
6269: } else { // Create/initialize eval_times
6270: TSEvaluationTimes eval_times;
6271: PetscCall(PetscNew(&eval_times));
6272: PetscCall(PetscMalloc1(n, &eval_times->time_points));
6273: PetscCall(PetscMalloc1(n, &eval_times->sol_times));
6274: eval_times->reltol = 1e-6;
6275: eval_times->abstol = 10 * PETSC_MACHINE_EPSILON;
6276: eval_times->worktol = 0;
6277: ts->eval_times = eval_times;
6278: }
6279: ts->eval_times->num_time_points = n;
6280: PetscCall(PetscSortedReal(n, time_points, &is_sorted));
6281: PetscCheck(is_sorted, PetscObjectComm((PetscObject)ts), PETSC_ERR_ARG_WRONG, "time_points array must be sorted");
6282: PetscCall(PetscArraycpy(ts->eval_times->time_points, time_points, n));
6283: // Note: ts->vec_sol not guaranteed to exist, so ts->eval_times->sol_vecs allocated at TSSolve time
6284: PetscFunctionReturn(PETSC_SUCCESS);
6285: }
6287: /*@
6288: TSGetEvaluationTimes - gets the evaluation times set with `TSSetEvaluationTimes()`
6290: Not Collective
6292: Input Parameter:
6293: . ts - the time-stepper
6295: Output Parameters:
6296: + n - number of the time points
6297: - time_points - array of the time points
6299: Level: beginner
6301: Note:
6302: The values obtained are valid until the `TS` object is destroyed.
6304: Both `n` and `time_points` can be `NULL`.
6306: Also used to see time points set by `TSSetTimeSpan()`.
6308: .seealso: [](ch_ts), `TS`, `TSSetEvaluationTimes()`, `TSGetEvaluationSolutions()`
6309: @*/
6310: PetscErrorCode TSGetEvaluationTimes(TS ts, PetscInt *n, const PetscReal *time_points[])
6311: {
6312: PetscFunctionBegin;
6314: if (n) PetscAssertPointer(n, 2);
6315: if (time_points) PetscAssertPointer(time_points, 3);
6316: if (!ts->eval_times) {
6317: if (n) *n = 0;
6318: if (time_points) *time_points = NULL;
6319: } else {
6320: if (n) *n = ts->eval_times->num_time_points;
6321: if (time_points) *time_points = ts->eval_times->time_points;
6322: }
6323: PetscFunctionReturn(PETSC_SUCCESS);
6324: }
6326: /*@
6327: TSGetEvaluationSolutions - Get the number of solutions and the solutions at the evaluation time points specified
6329: Input Parameter:
6330: . ts - the `TS` context obtained from `TSCreate()`
6332: Output Parameters:
6333: + nsol - the number of solutions
6334: . sol_times - array of solution times corresponding to the solution vectors. See note below
6335: - Sols - the solution vectors
6337: Level: intermediate
6339: Notes:
6340: Both `nsol` and `Sols` can be `NULL`.
6342: Some time points in the evaluation points may be skipped by `TS` so that `nsol` is less than the number of points specified by `TSSetEvaluationTimes()`.
6343: For example, manipulating the step size, especially with a reduced precision, may cause `TS` to step over certain evaluation times.
6345: Also used to see view solutions requested by `TSSetTimeSpan()`.
6347: .seealso: [](ch_ts), `TS`, `TSSetEvaluationTimes()`, `TSGetEvaluationTimes()`
6348: @*/
6349: PetscErrorCode TSGetEvaluationSolutions(TS ts, PetscInt *nsol, const PetscReal *sol_times[], Vec *Sols[])
6350: {
6351: PetscFunctionBegin;
6353: if (nsol) PetscAssertPointer(nsol, 2);
6354: if (sol_times) PetscAssertPointer(sol_times, 3);
6355: if (Sols) PetscAssertPointer(Sols, 4);
6356: if (!ts->eval_times) {
6357: if (nsol) *nsol = 0;
6358: if (sol_times) *sol_times = NULL;
6359: if (Sols) *Sols = NULL;
6360: } else {
6361: if (nsol) *nsol = ts->eval_times->sol_idx;
6362: if (sol_times) *sol_times = ts->eval_times->sol_times;
6363: if (Sols) *Sols = ts->eval_times->sol_vecs;
6364: }
6365: PetscFunctionReturn(PETSC_SUCCESS);
6366: }
6368: /*@
6369: TSSetTimeSpan - sets the time span. The solution will be computed and stored for each time requested in the span
6371: Collective
6373: Input Parameters:
6374: + ts - the time-stepper
6375: . n - number of the time points (>=2)
6376: - span_times - array of the time points, must be increasing. The first element and the last element are the initial time and the final time respectively.
6378: Options Database Key:
6379: . -ts_time_span t0,...,tf - Sets the time span
6381: Level: intermediate
6383: Notes:
6384: This function is identical to `TSSetEvaluationTimes()`, except that it also sets the initial time and final time for the `ts` to the first and last `span_times` entries.
6386: The elements in `span_times` must be all increasing. They correspond to the intermediate points to be saved.
6388: `TS_EXACTFINALTIME_MATCHSTEP` must be used to make the last time step in each sub-interval match the intermediate points specified.
6390: The intermediate solutions are saved in a vector array that can be accessed with `TSGetEvaluationSolutions()`. Thus using time span may
6391: pressure the memory system when using a large number of span points.
6393: .seealso: [](ch_ts), `TS`, `TSSetEvaluationTimes()`, `TSGetEvaluationTimes()`, `TSGetEvaluationSolutions()`
6394: @*/
6395: PetscErrorCode TSSetTimeSpan(TS ts, PetscInt n, PetscReal span_times[])
6396: {
6397: PetscFunctionBegin;
6399: PetscCheck(n >= 2, PetscObjectComm((PetscObject)ts), PETSC_ERR_ARG_WRONG, "Minimum time span size is 2 but %" PetscInt_FMT " is provided", n);
6400: PetscCall(TSSetEvaluationTimes(ts, n, span_times));
6401: PetscCall(TSSetTime(ts, span_times[0]));
6402: PetscCall(TSSetMaxTime(ts, span_times[n - 1]));
6403: PetscFunctionReturn(PETSC_SUCCESS);
6404: }
6406: /*@
6407: TSPruneIJacobianColor - Remove nondiagonal zeros in the Jacobian matrix and update the `MatMFFD` coloring information.
6409: Collective
6411: Input Parameters:
6412: + ts - the `TS` context
6413: . J - Jacobian matrix (not altered in this routine)
6414: - B - newly computed Jacobian matrix to use with preconditioner
6416: Level: intermediate
6418: Notes:
6419: This function improves the `MatFDColoring` performance when the Jacobian matrix was over-allocated or contains
6420: many constant zeros entries, which is typically the case when the matrix is generated by a `DM`
6421: and multiple fields are involved.
6423: Users need to make sure that the Jacobian matrix is properly filled to reflect the sparsity
6424: structure. For `MatFDColoring`, the values of nonzero entries are not important. So one can
6425: usually call `TSComputeIJacobian()` with randomized input vectors to generate a dummy Jacobian.
6426: `TSComputeIJacobian()` should be called before `TSSolve()` but after `TSSetUp()`.
6428: .seealso: [](ch_ts), `TS`, `MatFDColoring`, `TSComputeIJacobianDefaultColor()`, `MatEliminateZeros()`, `MatFDColoringCreate()`, `MatFDColoringSetFunction()`
6429: @*/
6430: PetscErrorCode TSPruneIJacobianColor(TS ts, Mat J, Mat B)
6431: {
6432: MatColoring mc = NULL;
6433: ISColoring iscoloring = NULL;
6434: MatFDColoring matfdcoloring = NULL;
6436: PetscFunctionBegin;
6437: /* Generate new coloring after eliminating zeros in the matrix */
6438: PetscCall(MatEliminateZeros(B, PETSC_TRUE));
6439: PetscCall(MatColoringCreate(B, &mc));
6440: PetscCall(MatColoringSetDistance(mc, 2));
6441: PetscCall(MatColoringSetType(mc, MATCOLORINGSL));
6442: PetscCall(MatColoringSetFromOptions(mc));
6443: PetscCall(MatColoringApply(mc, &iscoloring));
6444: PetscCall(MatColoringDestroy(&mc));
6445: /* Replace the old coloring with the new one */
6446: PetscCall(MatFDColoringCreate(B, iscoloring, &matfdcoloring));
6447: PetscCall(MatFDColoringSetFunction(matfdcoloring, (MatFDColoringFn *)SNESTSFormFunction, (void *)ts));
6448: PetscCall(MatFDColoringSetFromOptions(matfdcoloring));
6449: PetscCall(MatFDColoringSetUp(B, iscoloring, matfdcoloring));
6450: PetscCall(PetscObjectCompose((PetscObject)B, "TSMatFDColoring", (PetscObject)matfdcoloring));
6451: PetscCall(PetscObjectDereference((PetscObject)matfdcoloring));
6452: PetscCall(ISColoringDestroy(&iscoloring));
6453: PetscFunctionReturn(PETSC_SUCCESS);
6454: }