xref: /petsc/src/ts/interface/ts.c (revision c6a7a37075f8bf8d34d92c4910d42445b7a3482d)
1af0996ceSBarry Smith #include <petsc/private/tsimpl.h> /*I "petscts.h"  I*/
21e25c274SJed Brown #include <petscdmda.h>
360e16b1bSMatthew G. Knepley #include <petscdmshell.h>
460e16b1bSMatthew G. Knepley #include <petscdmplex.h>  // For TSSetFromOptions()
560e16b1bSMatthew G. Knepley #include <petscdmswarm.h> // For TSSetFromOptions()
62d5ee99bSBarry Smith #include <petscviewer.h>
72d5ee99bSBarry Smith #include <petscdraw.h>
8900f6b5bSMatthew G. Knepley #include <petscconvest.h>
9d763cef2SBarry Smith 
109371c9d4SSatish Balay #define SkipSmallValue(a, b, tol) \
119371c9d4SSatish Balay   if (PetscAbsScalar(a) < tol || PetscAbsScalar(b) < tol) continue;
121c167fc2SEmil Constantinescu 
13d5ba7fb7SMatthew Knepley /* Logging support */
14d74926cbSBarry Smith PetscClassId  TS_CLASSID, DMTS_CLASSID;
15a05bf03eSHong Zhang PetscLogEvent TS_Step, TS_PseudoComputeTimeStep, TS_FunctionEval, TS_JacobianEval;
16d405a339SMatthew Knepley 
17c793f718SLisandro Dalcin const char *const TSExactFinalTimeOptions[] = {"UNSPECIFIED", "STEPOVER", "INTERPOLATE", "MATCHSTEP", "TSExactFinalTimeOption", "TS_EXACTFINALTIME_", NULL};
1849354f04SShri Abhyankar 
19d71ae5a4SJacob Faibussowitsch static PetscErrorCode TSAdaptSetDefaultType(TSAdapt adapt, TSAdaptType default_type)
20d71ae5a4SJacob Faibussowitsch {
212ffb9264SLisandro Dalcin   PetscFunctionBegin;
22b92453a8SLisandro Dalcin   PetscValidHeaderSpecific(adapt, TSADAPT_CLASSID, 1);
23b92453a8SLisandro Dalcin   PetscValidCharPointer(default_type, 2);
241e66621cSBarry Smith   if (!((PetscObject)adapt)->type_name) PetscCall(TSAdaptSetType(adapt, default_type));
253ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
262ffb9264SLisandro Dalcin }
272ffb9264SLisandro Dalcin 
28bdad233fSMatthew Knepley /*@
29195e9b02SBarry Smith    TSSetFromOptions - Sets various `TS` parameters from the options database
30bdad233fSMatthew Knepley 
31c3339decSBarry Smith    Collective
32bdad233fSMatthew Knepley 
33bdad233fSMatthew Knepley    Input Parameter:
34bcf0153eSBarry Smith .  ts - the `TS` context obtained from `TSCreate()`
35bdad233fSMatthew Knepley 
36bdad233fSMatthew Knepley    Options Database Keys:
37195e9b02SBarry Smith +  -ts_type <type> - EULER, BEULER, SUNDIALS, PSEUDO, CN, RK, THETA, ALPHA, GLLE,  SSP, GLEE, BSYMP, IRK, see `TSType`
38ef222394SBarry Smith .  -ts_save_trajectory - checkpoint the solution at each time-step
39ef85077eSLisandro Dalcin .  -ts_max_time <time> - maximum time to compute to
404a658b32SHong Zhang .  -ts_time_span <t0,...tf> - sets the time span, solutions are computed and stored for each indicated time
41ef85077eSLisandro Dalcin .  -ts_max_steps <steps> - maximum number of time-steps to take
42ef85077eSLisandro Dalcin .  -ts_init_time <time> - initial time to start computation
43195e9b02SBarry Smith .  -ts_final_time <time> - final time to compute to (deprecated: use `-ts_max_time`)
443e4cdcaaSBarry Smith .  -ts_dt <dt> - initial time step
451628793fSSatish Balay .  -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
46a3cdaa26SBarry Smith .  -ts_max_snes_failures <maxfailures> - Maximum number of nonlinear solve failures allowed
47a3cdaa26SBarry Smith .  -ts_max_reject <maxrejects> - Maximum number of step rejections before step fails
48a3cdaa26SBarry Smith .  -ts_error_if_step_fails <true,false> - Error if no step succeeds
49a3cdaa26SBarry Smith .  -ts_rtol <rtol> - relative tolerance for local truncation error
5067b8a455SSatish Balay .  -ts_atol <atol> - Absolute tolerance for local truncation error
51f3b1f45cSBarry Smith .  -ts_rhs_jacobian_test_mult -mat_shell_test_mult_view - test the Jacobian at each iteration against finite difference with RHS function
52f3b1f45cSBarry Smith .  -ts_rhs_jacobian_test_mult_transpose -mat_shell_test_mult_transpose_view - test the Jacobian at each iteration against finite difference with RHS function
53195e9b02SBarry Smith .  -ts_adjoint_solve <yes,no> - After solving the ODE/DAE solve the adjoint problem (requires `-ts_save_trajectory`)
54847ff0e1SMatthew G. Knepley .  -ts_fd_color - Use finite differences with coloring to compute IJacobian
55bdad233fSMatthew Knepley .  -ts_monitor - print information at each timestep
56aee7a9fbSMatthew G. Knepley .  -ts_monitor_cancel - Cancel all monitors
57de06c3feSJed Brown .  -ts_monitor_lg_solution - Monitor solution graphically
58de06c3feSJed Brown .  -ts_monitor_lg_error - Monitor error graphically
597cf37e64SBarry Smith .  -ts_monitor_error - Monitors norm of error
606934998bSLisandro Dalcin .  -ts_monitor_lg_timestep - Monitor timestep size graphically
618b668821SLisandro Dalcin .  -ts_monitor_lg_timestep_log - Monitor log timestep size graphically
62de06c3feSJed Brown .  -ts_monitor_lg_snes_iterations - Monitor number nonlinear iterations for each timestep graphically
63de06c3feSJed Brown .  -ts_monitor_lg_ksp_iterations - Monitor number nonlinear iterations for each timestep graphically
64de06c3feSJed Brown .  -ts_monitor_sp_eig - Monitor eigenvalues of linearized operator graphically
65de06c3feSJed Brown .  -ts_monitor_draw_solution - Monitor solution graphically
663e4cdcaaSBarry Smith .  -ts_monitor_draw_solution_phase  <xleft,yleft,xright,yright> - Monitor solution graphically with phase diagram, requires problem with exactly 2 degrees of freedom
673e4cdcaaSBarry Smith .  -ts_monitor_draw_error - Monitor error graphically, requires use to have provided TSSetSolutionFunction()
68fde5950dSBarry Smith .  -ts_monitor_solution [ascii binary draw][:filename][:viewerformat] - monitors the solution at each timestep
699812b6beSJed Brown    -ts_monitor_solution_interval <interval> - output once every interval (default=1) time steps; used with -ts_monitor_solution
7063a3b9bcSJacob Faibussowitsch .  -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)
719e336e28SPatrick Sanan -  -ts_monitor_envelope - determine maximum and minimum value of each component of the solution over the solution time
7253ea634cSHong Zhang 
73bcf0153eSBarry Smith    Level: beginner
743d5a8a6aSBarry Smith 
75bcf0153eSBarry Smith    Notes:
76bcf0153eSBarry Smith      See `SNESSetFromOptions()` and `KSPSetFromOptions()` for how to control the nonlinear and linear solves used by the time-stepper.
77bcf0153eSBarry Smith 
78195e9b02SBarry Smith      Certain `SNES` options get reset for each new nonlinear solver, for example `-snes_lag_jacobian its` and `-snes_lag_preconditioner its`, in order
79195e9b02SBarry Smith      to retain them over the multiple nonlinear solves that `TS` uses you mush also provide `-snes_lag_jacobian_persists true` and
80195e9b02SBarry Smith      `-snes_lag_preconditioner_persists true`
813d5a8a6aSBarry Smith 
829e336e28SPatrick Sanan    Developer Note:
839e336e28SPatrick Sanan      We should unify all the -ts_monitor options in the way that -xxx_view has been unified
84bdad233fSMatthew Knepley 
85bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSGetType()`
86bdad233fSMatthew Knepley @*/
87d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetFromOptions(TS ts)
88d71ae5a4SJacob Faibussowitsch {
89bc952696SBarry Smith   PetscBool              opt, flg, tflg;
90eabae89aSBarry Smith   char                   monfilename[PETSC_MAX_PATH_LEN];
914a658b32SHong Zhang   PetscReal              time_step, tspan[100];
924a658b32SHong Zhang   PetscInt               nt = PETSC_STATIC_ARRAY_LENGTH(tspan);
9349354f04SShri Abhyankar   TSExactFinalTimeOption eftopt;
94d1212d36SBarry Smith   char                   dir[16];
95cd11d68dSLisandro Dalcin   TSIFunction            ifun;
966991f827SBarry Smith   const char            *defaultType;
976991f827SBarry Smith   char                   typeName[256];
98bdad233fSMatthew Knepley 
99bdad233fSMatthew Knepley   PetscFunctionBegin;
1000700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
1016991f827SBarry Smith 
1029566063dSJacob Faibussowitsch   PetscCall(TSRegisterAll());
1039566063dSJacob Faibussowitsch   PetscCall(TSGetIFunction(ts, NULL, &ifun, NULL));
104cd11d68dSLisandro Dalcin 
105d0609cedSBarry Smith   PetscObjectOptionsBegin((PetscObject)ts);
1061ef27442SStefano Zampini   if (((PetscObject)ts)->type_name) defaultType = ((PetscObject)ts)->type_name;
1071ef27442SStefano Zampini   else defaultType = ifun ? TSBEULER : TSEULER;
1089566063dSJacob Faibussowitsch   PetscCall(PetscOptionsFList("-ts_type", "TS method", "TSSetType", TSList, defaultType, typeName, 256, &opt));
1091e66621cSBarry Smith   if (opt) PetscCall(TSSetType(ts, typeName));
1101e66621cSBarry Smith   else PetscCall(TSSetType(ts, defaultType));
111bdad233fSMatthew Knepley 
112bdad233fSMatthew Knepley   /* Handle generic TS options */
1139566063dSJacob Faibussowitsch   PetscCall(PetscOptionsDeprecated("-ts_final_time", "-ts_max_time", "3.10", NULL));
1149566063dSJacob Faibussowitsch   PetscCall(PetscOptionsReal("-ts_max_time", "Maximum time to run to", "TSSetMaxTime", ts->max_time, &ts->max_time, NULL));
1154a658b32SHong Zhang   PetscCall(PetscOptionsRealArray("-ts_time_span", "Time span", "TSSetTimeSpan", tspan, &nt, &flg));
1164a658b32SHong Zhang   if (flg) PetscCall(TSSetTimeSpan(ts, nt, tspan));
1179566063dSJacob Faibussowitsch   PetscCall(PetscOptionsInt("-ts_max_steps", "Maximum number of time steps", "TSSetMaxSteps", ts->max_steps, &ts->max_steps, NULL));
1189566063dSJacob Faibussowitsch   PetscCall(PetscOptionsReal("-ts_init_time", "Initial time", "TSSetTime", ts->ptime, &ts->ptime, NULL));
1199566063dSJacob Faibussowitsch   PetscCall(PetscOptionsReal("-ts_dt", "Initial time step", "TSSetTimeStep", ts->time_step, &time_step, &flg));
1209566063dSJacob Faibussowitsch   if (flg) PetscCall(TSSetTimeStep(ts, time_step));
1219566063dSJacob Faibussowitsch   PetscCall(PetscOptionsEnum("-ts_exact_final_time", "Option for handling of final time step", "TSSetExactFinalTime", TSExactFinalTimeOptions, (PetscEnum)ts->exact_final_time, (PetscEnum *)&eftopt, &flg));
1229566063dSJacob Faibussowitsch   if (flg) PetscCall(TSSetExactFinalTime(ts, eftopt));
1239566063dSJacob Faibussowitsch   PetscCall(PetscOptionsInt("-ts_max_snes_failures", "Maximum number of nonlinear solve failures", "TSSetMaxSNESFailures", ts->max_snes_failures, &ts->max_snes_failures, NULL));
1249566063dSJacob Faibussowitsch   PetscCall(PetscOptionsInt("-ts_max_reject", "Maximum number of step rejections before step fails", "TSSetMaxStepRejections", ts->max_reject, &ts->max_reject, NULL));
1259566063dSJacob Faibussowitsch   PetscCall(PetscOptionsBool("-ts_error_if_step_fails", "Error if no step succeeds", "TSSetErrorIfStepFails", ts->errorifstepfailed, &ts->errorifstepfailed, NULL));
1269566063dSJacob Faibussowitsch   PetscCall(PetscOptionsReal("-ts_rtol", "Relative tolerance for local truncation error", "TSSetTolerances", ts->rtol, &ts->rtol, NULL));
1279566063dSJacob Faibussowitsch   PetscCall(PetscOptionsReal("-ts_atol", "Absolute tolerance for local truncation error", "TSSetTolerances", ts->atol, &ts->atol, NULL));
128bdad233fSMatthew Knepley 
1299566063dSJacob Faibussowitsch   PetscCall(PetscOptionsBool("-ts_rhs_jacobian_test_mult", "Test the RHS Jacobian for consistency with RHS at each solve ", "None", ts->testjacobian, &ts->testjacobian, NULL));
1309566063dSJacob Faibussowitsch   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));
1319566063dSJacob Faibussowitsch   PetscCall(PetscOptionsBool("-ts_use_splitrhsfunction", "Use the split RHS function for multirate solvers ", "TSSetUseSplitRHSFunction", ts->use_splitrhsfunction, &ts->use_splitrhsfunction, NULL));
13256f85f32SBarry Smith #if defined(PETSC_HAVE_SAWS)
13356f85f32SBarry Smith   {
13456f85f32SBarry Smith     PetscBool set;
13556f85f32SBarry Smith     flg = PETSC_FALSE;
1369566063dSJacob Faibussowitsch     PetscCall(PetscOptionsBool("-ts_saws_block", "Block for SAWs memory snooper at end of TSSolve", "PetscObjectSAWsBlock", ((PetscObject)ts)->amspublishblock, &flg, &set));
1371baa6e33SBarry Smith     if (set) PetscCall(PetscObjectSAWsSetBlock((PetscObject)ts, flg));
13856f85f32SBarry Smith   }
13956f85f32SBarry Smith #endif
14056f85f32SBarry Smith 
141bdad233fSMatthew Knepley   /* Monitor options */
1429566063dSJacob Faibussowitsch   PetscCall(PetscOptionsInt("-ts_monitor_frequency", "Number of time steps between monitor output", "TSMonitorSetFrequency", ts->monitorFrequency, &ts->monitorFrequency, NULL));
1439566063dSJacob Faibussowitsch   PetscCall(TSMonitorSetFromOptions(ts, "-ts_monitor", "Monitor time and timestep size", "TSMonitorDefault", TSMonitorDefault, NULL));
1449566063dSJacob Faibussowitsch   PetscCall(TSMonitorSetFromOptions(ts, "-ts_monitor_extreme", "Monitor extreme values of the solution", "TSMonitorExtreme", TSMonitorExtreme, NULL));
1459566063dSJacob Faibussowitsch   PetscCall(TSMonitorSetFromOptions(ts, "-ts_monitor_solution", "View the solution at each timestep", "TSMonitorSolution", TSMonitorSolution, NULL));
1469566063dSJacob Faibussowitsch   PetscCall(TSMonitorSetFromOptions(ts, "-ts_dmswarm_monitor_moments", "Monitor moments of particle distribution", "TSDMSwarmMonitorMoments", TSDMSwarmMonitorMoments, NULL));
147fde5950dSBarry Smith 
1489566063dSJacob Faibussowitsch   PetscCall(PetscOptionsString("-ts_monitor_python", "Use Python function", "TSMonitorSet", NULL, monfilename, sizeof(monfilename), &flg));
1499566063dSJacob Faibussowitsch   if (flg) PetscCall(PetscPythonMonitorSet((PetscObject)ts, monfilename));
1505180491cSLisandro Dalcin 
1519566063dSJacob Faibussowitsch   PetscCall(PetscOptionsName("-ts_monitor_lg_solution", "Monitor solution graphically", "TSMonitorLGSolution", &opt));
152b3603a34SBarry Smith   if (opt) {
1533923b477SBarry Smith     PetscInt  howoften = 1;
154e669de00SBarry Smith     DM        dm;
155e669de00SBarry Smith     PetscBool net;
156b3603a34SBarry Smith 
1579566063dSJacob Faibussowitsch     PetscCall(PetscOptionsInt("-ts_monitor_lg_solution", "Monitor solution graphically", "TSMonitorLGSolution", howoften, &howoften, NULL));
1589566063dSJacob Faibussowitsch     PetscCall(TSGetDM(ts, &dm));
1599566063dSJacob Faibussowitsch     PetscCall(PetscObjectTypeCompare((PetscObject)dm, DMNETWORK, &net));
160e669de00SBarry Smith     if (net) {
161e669de00SBarry Smith       TSMonitorLGCtxNetwork ctx;
1629566063dSJacob Faibussowitsch       PetscCall(TSMonitorLGCtxNetworkCreate(ts, NULL, NULL, PETSC_DECIDE, PETSC_DECIDE, 600, 400, howoften, &ctx));
1639566063dSJacob Faibussowitsch       PetscCall(TSMonitorSet(ts, TSMonitorLGCtxNetworkSolution, ctx, (PetscErrorCode(*)(void **))TSMonitorLGCtxNetworkDestroy));
1649566063dSJacob Faibussowitsch       PetscCall(PetscOptionsBool("-ts_monitor_lg_solution_semilogy", "Plot the solution with a semi-log axis", "", ctx->semilogy, &ctx->semilogy, NULL));
165e669de00SBarry Smith     } else {
166e669de00SBarry Smith       TSMonitorLGCtx ctx;
1679566063dSJacob Faibussowitsch       PetscCall(TSMonitorLGCtxCreate(PETSC_COMM_SELF, NULL, NULL, PETSC_DECIDE, PETSC_DECIDE, 400, 300, howoften, &ctx));
1689566063dSJacob Faibussowitsch       PetscCall(TSMonitorSet(ts, TSMonitorLGSolution, ctx, (PetscErrorCode(*)(void **))TSMonitorLGCtxDestroy));
169bdad233fSMatthew Knepley     }
170e669de00SBarry Smith   }
1716ba87a44SLisandro Dalcin 
1729566063dSJacob Faibussowitsch   PetscCall(PetscOptionsName("-ts_monitor_lg_error", "Monitor error graphically", "TSMonitorLGError", &opt));
173ef20d060SBarry Smith   if (opt) {
1740b039ecaSBarry Smith     TSMonitorLGCtx ctx;
1753923b477SBarry Smith     PetscInt       howoften = 1;
176ef20d060SBarry Smith 
1779566063dSJacob Faibussowitsch     PetscCall(PetscOptionsInt("-ts_monitor_lg_error", "Monitor error graphically", "TSMonitorLGError", howoften, &howoften, NULL));
1789566063dSJacob Faibussowitsch     PetscCall(TSMonitorLGCtxCreate(PETSC_COMM_SELF, NULL, NULL, PETSC_DECIDE, PETSC_DECIDE, 400, 300, howoften, &ctx));
1799566063dSJacob Faibussowitsch     PetscCall(TSMonitorSet(ts, TSMonitorLGError, ctx, (PetscErrorCode(*)(void **))TSMonitorLGCtxDestroy));
180ef20d060SBarry Smith   }
1819566063dSJacob Faibussowitsch   PetscCall(TSMonitorSetFromOptions(ts, "-ts_monitor_error", "View the error at each timestep", "TSMonitorError", TSMonitorError, NULL));
1827cf37e64SBarry Smith 
1839566063dSJacob Faibussowitsch   PetscCall(PetscOptionsName("-ts_monitor_lg_timestep", "Monitor timestep size graphically", "TSMonitorLGTimeStep", &opt));
1846934998bSLisandro Dalcin   if (opt) {
1856934998bSLisandro Dalcin     TSMonitorLGCtx ctx;
1866934998bSLisandro Dalcin     PetscInt       howoften = 1;
1876934998bSLisandro Dalcin 
1889566063dSJacob Faibussowitsch     PetscCall(PetscOptionsInt("-ts_monitor_lg_timestep", "Monitor timestep size graphically", "TSMonitorLGTimeStep", howoften, &howoften, NULL));
1899566063dSJacob Faibussowitsch     PetscCall(TSMonitorLGCtxCreate(PetscObjectComm((PetscObject)ts), NULL, NULL, PETSC_DECIDE, PETSC_DECIDE, 400, 300, howoften, &ctx));
1909566063dSJacob Faibussowitsch     PetscCall(TSMonitorSet(ts, TSMonitorLGTimeStep, ctx, (PetscErrorCode(*)(void **))TSMonitorLGCtxDestroy));
1916934998bSLisandro Dalcin   }
1929566063dSJacob Faibussowitsch   PetscCall(PetscOptionsName("-ts_monitor_lg_timestep_log", "Monitor log timestep size graphically", "TSMonitorLGTimeStep", &opt));
1938b668821SLisandro Dalcin   if (opt) {
1948b668821SLisandro Dalcin     TSMonitorLGCtx ctx;
1958b668821SLisandro Dalcin     PetscInt       howoften = 1;
1968b668821SLisandro Dalcin 
1979566063dSJacob Faibussowitsch     PetscCall(PetscOptionsInt("-ts_monitor_lg_timestep_log", "Monitor log timestep size graphically", "TSMonitorLGTimeStep", howoften, &howoften, NULL));
1989566063dSJacob Faibussowitsch     PetscCall(TSMonitorLGCtxCreate(PetscObjectComm((PetscObject)ts), NULL, NULL, PETSC_DECIDE, PETSC_DECIDE, 400, 300, howoften, &ctx));
1999566063dSJacob Faibussowitsch     PetscCall(TSMonitorSet(ts, TSMonitorLGTimeStep, ctx, (PetscErrorCode(*)(void **))TSMonitorLGCtxDestroy));
2008b668821SLisandro Dalcin     ctx->semilogy = PETSC_TRUE;
2018b668821SLisandro Dalcin   }
2028b668821SLisandro Dalcin 
2039566063dSJacob Faibussowitsch   PetscCall(PetscOptionsName("-ts_monitor_lg_snes_iterations", "Monitor number nonlinear iterations for each timestep graphically", "TSMonitorLGSNESIterations", &opt));
204201da799SBarry Smith   if (opt) {
205201da799SBarry Smith     TSMonitorLGCtx ctx;
206201da799SBarry Smith     PetscInt       howoften = 1;
207201da799SBarry Smith 
2089566063dSJacob Faibussowitsch     PetscCall(PetscOptionsInt("-ts_monitor_lg_snes_iterations", "Monitor number nonlinear iterations for each timestep graphically", "TSMonitorLGSNESIterations", howoften, &howoften, NULL));
2099566063dSJacob Faibussowitsch     PetscCall(TSMonitorLGCtxCreate(PetscObjectComm((PetscObject)ts), NULL, NULL, PETSC_DECIDE, PETSC_DECIDE, 400, 300, howoften, &ctx));
2109566063dSJacob Faibussowitsch     PetscCall(TSMonitorSet(ts, TSMonitorLGSNESIterations, ctx, (PetscErrorCode(*)(void **))TSMonitorLGCtxDestroy));
211201da799SBarry Smith   }
2129566063dSJacob Faibussowitsch   PetscCall(PetscOptionsName("-ts_monitor_lg_ksp_iterations", "Monitor number nonlinear iterations for each timestep graphically", "TSMonitorLGKSPIterations", &opt));
213201da799SBarry Smith   if (opt) {
214201da799SBarry Smith     TSMonitorLGCtx ctx;
215201da799SBarry Smith     PetscInt       howoften = 1;
216201da799SBarry Smith 
2179566063dSJacob Faibussowitsch     PetscCall(PetscOptionsInt("-ts_monitor_lg_ksp_iterations", "Monitor number nonlinear iterations for each timestep graphically", "TSMonitorLGKSPIterations", howoften, &howoften, NULL));
2189566063dSJacob Faibussowitsch     PetscCall(TSMonitorLGCtxCreate(PetscObjectComm((PetscObject)ts), NULL, NULL, PETSC_DECIDE, PETSC_DECIDE, 400, 300, howoften, &ctx));
2199566063dSJacob Faibussowitsch     PetscCall(TSMonitorSet(ts, TSMonitorLGKSPIterations, ctx, (PetscErrorCode(*)(void **))TSMonitorLGCtxDestroy));
220201da799SBarry Smith   }
2219566063dSJacob Faibussowitsch   PetscCall(PetscOptionsName("-ts_monitor_sp_eig", "Monitor eigenvalues of linearized operator graphically", "TSMonitorSPEig", &opt));
2228189c53fSBarry Smith   if (opt) {
2238189c53fSBarry Smith     TSMonitorSPEigCtx ctx;
2248189c53fSBarry Smith     PetscInt          howoften = 1;
2258189c53fSBarry Smith 
2269566063dSJacob Faibussowitsch     PetscCall(PetscOptionsInt("-ts_monitor_sp_eig", "Monitor eigenvalues of linearized operator graphically", "TSMonitorSPEig", howoften, &howoften, NULL));
2279566063dSJacob Faibussowitsch     PetscCall(TSMonitorSPEigCtxCreate(PETSC_COMM_SELF, NULL, NULL, PETSC_DECIDE, PETSC_DECIDE, 300, 300, howoften, &ctx));
2289566063dSJacob Faibussowitsch     PetscCall(TSMonitorSet(ts, TSMonitorSPEig, ctx, (PetscErrorCode(*)(void **))TSMonitorSPEigCtxDestroy));
2298189c53fSBarry Smith   }
23060e16b1bSMatthew G. Knepley   PetscCall(PetscOptionsName("-ts_monitor_sp_swarm", "Display particle phase space from the DMSwarm", "TSMonitorSPSwarm", &opt));
2311b575b74SJoseph Pusztay   if (opt) {
2321b575b74SJoseph Pusztay     TSMonitorSPCtx ctx;
233d7462660SMatthew Knepley     PetscInt       howoften = 1, retain = 0;
23460e16b1bSMatthew G. Knepley     PetscBool      phase = PETSC_TRUE, create = PETSC_TRUE, multispecies = PETSC_FALSE;
235d7462660SMatthew Knepley 
2369371c9d4SSatish Balay     for (PetscInt i = 0; i < ts->numbermonitors; ++i)
2379371c9d4SSatish Balay       if (ts->monitor[i] == TSMonitorSPSwarmSolution) {
2389371c9d4SSatish Balay         create = PETSC_FALSE;
2399371c9d4SSatish Balay         break;
2409371c9d4SSatish Balay       }
2416a5217c0SMatthew G. Knepley     if (create) {
24260e16b1bSMatthew G. Knepley       PetscCall(PetscOptionsInt("-ts_monitor_sp_swarm", "Display particles phase space from the DMSwarm", "TSMonitorSPSwarm", howoften, &howoften, NULL));
2439566063dSJacob Faibussowitsch       PetscCall(PetscOptionsInt("-ts_monitor_sp_swarm_retain", "Retain n points plotted to show trajectory, -1 for all points", "TSMonitorSPSwarm", retain, &retain, NULL));
2449566063dSJacob Faibussowitsch       PetscCall(PetscOptionsBool("-ts_monitor_sp_swarm_phase", "Plot in phase space rather than coordinate space", "TSMonitorSPSwarm", phase, &phase, NULL));
24560e16b1bSMatthew G. Knepley       PetscCall(PetscOptionsBool("-ts_monitor_sp_swarm_multi_species", "Color particles by particle species", "TSMonitorSPSwarm", multispecies, &multispecies, NULL));
24660e16b1bSMatthew G. Knepley       PetscCall(TSMonitorSPCtxCreate(PetscObjectComm((PetscObject)ts), NULL, NULL, PETSC_DECIDE, PETSC_DECIDE, 300, 300, howoften, retain, phase, multispecies, &ctx));
2479566063dSJacob Faibussowitsch       PetscCall(TSMonitorSet(ts, TSMonitorSPSwarmSolution, ctx, (PetscErrorCode(*)(void **))TSMonitorSPCtxDestroy));
2481b575b74SJoseph Pusztay     }
2496a5217c0SMatthew G. Knepley   }
25060e16b1bSMatthew G. Knepley   PetscCall(PetscOptionsName("-ts_monitor_hg_swarm", "Display particle histogram from the DMSwarm", "TSMonitorHGSwarm", &opt));
25160e16b1bSMatthew G. Knepley   if (opt) {
25260e16b1bSMatthew G. Knepley     TSMonitorHGCtx ctx;
25360e16b1bSMatthew G. Knepley     PetscInt       howoften = 1, Ns = 1;
25460e16b1bSMatthew G. Knepley     PetscBool      velocity = PETSC_FALSE, create = PETSC_TRUE;
25560e16b1bSMatthew G. Knepley 
25660e16b1bSMatthew G. Knepley     for (PetscInt i = 0; i < ts->numbermonitors; ++i)
25760e16b1bSMatthew G. Knepley       if (ts->monitor[i] == TSMonitorHGSwarmSolution) {
25860e16b1bSMatthew G. Knepley         create = PETSC_FALSE;
25960e16b1bSMatthew G. Knepley         break;
26060e16b1bSMatthew G. Knepley       }
26160e16b1bSMatthew G. Knepley     if (create) {
26260e16b1bSMatthew G. Knepley       DM       sw, dm;
26360e16b1bSMatthew G. Knepley       PetscInt Nc, Nb;
26460e16b1bSMatthew G. Knepley 
26560e16b1bSMatthew G. Knepley       PetscCall(TSGetDM(ts, &sw));
26660e16b1bSMatthew G. Knepley       PetscCall(DMSwarmGetCellDM(sw, &dm));
26760e16b1bSMatthew G. Knepley       PetscCall(DMPlexGetHeightStratum(dm, 0, NULL, &Nc));
26860e16b1bSMatthew G. Knepley       Nb = PetscMin(20, PetscMax(10, Nc));
26960e16b1bSMatthew G. Knepley       PetscCall(PetscOptionsInt("-ts_monitor_hg_swarm", "Display particles histogram from the DMSwarm", "TSMonitorHGSwarm", howoften, &howoften, NULL));
27060e16b1bSMatthew G. Knepley       PetscCall(PetscOptionsBool("-ts_monitor_hg_swarm_velocity", "Plot in velocity space rather than coordinate space", "TSMonitorHGSwarm", velocity, &velocity, NULL));
27160e16b1bSMatthew G. Knepley       PetscCall(PetscOptionsInt("-ts_monitor_hg_swarm_species", "Number of species to histogram", "TSMonitorHGSwarm", Ns, &Ns, NULL));
27260e16b1bSMatthew G. Knepley       PetscCall(PetscOptionsInt("-ts_monitor_hg_swarm_bins", "Number of histogram bins", "TSMonitorHGSwarm", Nb, &Nb, NULL));
27360e16b1bSMatthew G. Knepley       PetscCall(TSMonitorHGCtxCreate(PetscObjectComm((PetscObject)ts), NULL, NULL, PETSC_DECIDE, PETSC_DECIDE, 300, 300, howoften, Ns, Nb, velocity, &ctx));
27460e16b1bSMatthew G. Knepley       PetscCall(TSMonitorSet(ts, TSMonitorHGSwarmSolution, ctx, (PetscErrorCode(*)(void **))TSMonitorHGCtxDestroy));
27560e16b1bSMatthew G. Knepley     }
27660e16b1bSMatthew G. Knepley   }
277ef20d060SBarry Smith   opt = PETSC_FALSE;
2789566063dSJacob Faibussowitsch   PetscCall(PetscOptionsName("-ts_monitor_draw_solution", "Monitor solution graphically", "TSMonitorDrawSolution", &opt));
279a7cc72afSBarry Smith   if (opt) {
28083a4ac43SBarry Smith     TSMonitorDrawCtx ctx;
28183a4ac43SBarry Smith     PetscInt         howoften = 1;
282a80ad3e0SBarry Smith 
2839566063dSJacob Faibussowitsch     PetscCall(PetscOptionsInt("-ts_monitor_draw_solution", "Monitor solution graphically", "TSMonitorDrawSolution", howoften, &howoften, NULL));
2849566063dSJacob Faibussowitsch     PetscCall(TSMonitorDrawCtxCreate(PetscObjectComm((PetscObject)ts), NULL, "Computed Solution", PETSC_DECIDE, PETSC_DECIDE, 300, 300, howoften, &ctx));
2859566063dSJacob Faibussowitsch     PetscCall(TSMonitorSet(ts, TSMonitorDrawSolution, ctx, (PetscErrorCode(*)(void **))TSMonitorDrawCtxDestroy));
286bdad233fSMatthew Knepley   }
287fb1732b5SBarry Smith   opt = PETSC_FALSE;
2889566063dSJacob Faibussowitsch   PetscCall(PetscOptionsName("-ts_monitor_draw_solution_phase", "Monitor solution graphically", "TSMonitorDrawSolutionPhase", &opt));
2892d5ee99bSBarry Smith   if (opt) {
2902d5ee99bSBarry Smith     TSMonitorDrawCtx ctx;
2912d5ee99bSBarry Smith     PetscReal        bounds[4];
2922d5ee99bSBarry Smith     PetscInt         n = 4;
2932d5ee99bSBarry Smith     PetscDraw        draw;
2946934998bSLisandro Dalcin     PetscDrawAxis    axis;
2952d5ee99bSBarry Smith 
2969566063dSJacob Faibussowitsch     PetscCall(PetscOptionsRealArray("-ts_monitor_draw_solution_phase", "Monitor solution graphically", "TSMonitorDrawSolutionPhase", bounds, &n, NULL));
2973c633725SBarry Smith     PetscCheck(n == 4, PetscObjectComm((PetscObject)ts), PETSC_ERR_ARG_WRONG, "Must provide bounding box of phase field");
2989566063dSJacob Faibussowitsch     PetscCall(TSMonitorDrawCtxCreate(PetscObjectComm((PetscObject)ts), NULL, NULL, PETSC_DECIDE, PETSC_DECIDE, 300, 300, 1, &ctx));
2999566063dSJacob Faibussowitsch     PetscCall(PetscViewerDrawGetDraw(ctx->viewer, 0, &draw));
3009566063dSJacob Faibussowitsch     PetscCall(PetscViewerDrawGetDrawAxis(ctx->viewer, 0, &axis));
3019566063dSJacob Faibussowitsch     PetscCall(PetscDrawAxisSetLimits(axis, bounds[0], bounds[2], bounds[1], bounds[3]));
3029566063dSJacob Faibussowitsch     PetscCall(PetscDrawAxisSetLabels(axis, "Phase Diagram", "Variable 1", "Variable 2"));
3039566063dSJacob Faibussowitsch     PetscCall(TSMonitorSet(ts, TSMonitorDrawSolutionPhase, ctx, (PetscErrorCode(*)(void **))TSMonitorDrawCtxDestroy));
3042d5ee99bSBarry Smith   }
3052d5ee99bSBarry Smith   opt = PETSC_FALSE;
3069566063dSJacob Faibussowitsch   PetscCall(PetscOptionsName("-ts_monitor_draw_error", "Monitor error graphically", "TSMonitorDrawError", &opt));
3073a471f94SBarry Smith   if (opt) {
30883a4ac43SBarry Smith     TSMonitorDrawCtx ctx;
30983a4ac43SBarry Smith     PetscInt         howoften = 1;
3103a471f94SBarry Smith 
3119566063dSJacob Faibussowitsch     PetscCall(PetscOptionsInt("-ts_monitor_draw_error", "Monitor error graphically", "TSMonitorDrawError", howoften, &howoften, NULL));
3129566063dSJacob Faibussowitsch     PetscCall(TSMonitorDrawCtxCreate(PetscObjectComm((PetscObject)ts), NULL, "Error", PETSC_DECIDE, PETSC_DECIDE, 300, 300, howoften, &ctx));
3139566063dSJacob Faibussowitsch     PetscCall(TSMonitorSet(ts, TSMonitorDrawError, ctx, (PetscErrorCode(*)(void **))TSMonitorDrawCtxDestroy));
3143a471f94SBarry Smith   }
3150ed3bfb6SBarry Smith   opt = PETSC_FALSE;
3169566063dSJacob Faibussowitsch   PetscCall(PetscOptionsName("-ts_monitor_draw_solution_function", "Monitor solution provided by TSMonitorSetSolutionFunction() graphically", "TSMonitorDrawSolutionFunction", &opt));
3170ed3bfb6SBarry Smith   if (opt) {
3180ed3bfb6SBarry Smith     TSMonitorDrawCtx ctx;
3190ed3bfb6SBarry Smith     PetscInt         howoften = 1;
3200ed3bfb6SBarry Smith 
3219566063dSJacob Faibussowitsch     PetscCall(PetscOptionsInt("-ts_monitor_draw_solution_function", "Monitor solution provided by TSMonitorSetSolutionFunction() graphically", "TSMonitorDrawSolutionFunction", howoften, &howoften, NULL));
3229566063dSJacob Faibussowitsch     PetscCall(TSMonitorDrawCtxCreate(PetscObjectComm((PetscObject)ts), NULL, "Solution provided by user function", PETSC_DECIDE, PETSC_DECIDE, 300, 300, howoften, &ctx));
3239566063dSJacob Faibussowitsch     PetscCall(TSMonitorSet(ts, TSMonitorDrawSolutionFunction, ctx, (PetscErrorCode(*)(void **))TSMonitorDrawCtxDestroy));
3240ed3bfb6SBarry Smith   }
325fde5950dSBarry Smith 
326ed81e22dSJed Brown   opt = PETSC_FALSE;
32763a3b9bcSJacob Faibussowitsch   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));
328ed81e22dSJed Brown   if (flg) {
329bbcf679cSJacob Faibussowitsch     const char *ptr = NULL, *ptr2 = NULL;
330ed81e22dSJed Brown     char       *filetemplate;
33163a3b9bcSJacob Faibussowitsch     PetscCheck(monfilename[0], PetscObjectComm((PetscObject)ts), PETSC_ERR_USER, "-ts_monitor_solution_vtk requires a file template, e.g. filename-%%03" PetscInt_FMT ".vts");
332ed81e22dSJed Brown     /* Do some cursory validation of the input. */
3339566063dSJacob Faibussowitsch     PetscCall(PetscStrstr(monfilename, "%", (char **)&ptr));
33463a3b9bcSJacob Faibussowitsch     PetscCheck(ptr, PetscObjectComm((PetscObject)ts), PETSC_ERR_USER, "-ts_monitor_solution_vtk requires a file template, e.g. filename-%%03" PetscInt_FMT ".vts");
335ed81e22dSJed Brown     for (ptr++; ptr && *ptr; ptr++) {
3369566063dSJacob Faibussowitsch       PetscCall(PetscStrchr("DdiouxX", *ptr, (char **)&ptr2));
33763a3b9bcSJacob Faibussowitsch       PetscCheck(ptr2 || (*ptr >= '0' && *ptr <= '9'), PetscObjectComm((PetscObject)ts), PETSC_ERR_USER, "Invalid file template argument to -ts_monitor_solution_vtk, should look like filename-%%03" PetscInt_FMT ".vts");
338ed81e22dSJed Brown       if (ptr2) break;
339ed81e22dSJed Brown     }
3409566063dSJacob Faibussowitsch     PetscCall(PetscStrallocpy(monfilename, &filetemplate));
3419566063dSJacob Faibussowitsch     PetscCall(TSMonitorSet(ts, TSMonitorSolutionVTK, filetemplate, (PetscErrorCode(*)(void **))TSMonitorSolutionVTKDestroy));
342ed81e22dSJed Brown   }
343bdad233fSMatthew Knepley 
3449566063dSJacob Faibussowitsch   PetscCall(PetscOptionsString("-ts_monitor_dmda_ray", "Display a ray of the solution", "None", "y=0", dir, sizeof(dir), &flg));
345d1212d36SBarry Smith   if (flg) {
346d1212d36SBarry Smith     TSMonitorDMDARayCtx *rayctx;
347d1212d36SBarry Smith     int                  ray = 0;
3483ee9839eSMatthew G. Knepley     DMDirection          ddir;
349d1212d36SBarry Smith     DM                   da;
350d1212d36SBarry Smith     PetscMPIInt          rank;
351d1212d36SBarry Smith 
3523c633725SBarry Smith     PetscCheck(dir[1] == '=', PetscObjectComm((PetscObject)ts), PETSC_ERR_ARG_WRONG, "Unknown ray %s", dir);
3533ee9839eSMatthew G. Knepley     if (dir[0] == 'x') ddir = DM_X;
3543ee9839eSMatthew G. Knepley     else if (dir[0] == 'y') ddir = DM_Y;
35598921bdaSJacob Faibussowitsch     else SETERRQ(PetscObjectComm((PetscObject)ts), PETSC_ERR_ARG_WRONG, "Unknown ray %s", dir);
356d1212d36SBarry Smith     sscanf(dir + 2, "%d", &ray);
357d1212d36SBarry Smith 
3589566063dSJacob Faibussowitsch     PetscCall(PetscInfo(((PetscObject)ts), "Displaying DMDA ray %c = %d\n", dir[0], ray));
3599566063dSJacob Faibussowitsch     PetscCall(PetscNew(&rayctx));
3609566063dSJacob Faibussowitsch     PetscCall(TSGetDM(ts, &da));
3619566063dSJacob Faibussowitsch     PetscCall(DMDAGetRay(da, ddir, ray, &rayctx->ray, &rayctx->scatter));
3629566063dSJacob Faibussowitsch     PetscCallMPI(MPI_Comm_rank(PetscObjectComm((PetscObject)ts), &rank));
3631e66621cSBarry Smith     if (rank == 0) PetscCall(PetscViewerDrawOpen(PETSC_COMM_SELF, NULL, NULL, 0, 0, 600, 300, &rayctx->viewer));
36451b4a12fSMatthew G. Knepley     rayctx->lgctx = NULL;
3659566063dSJacob Faibussowitsch     PetscCall(TSMonitorSet(ts, TSMonitorDMDARay, rayctx, TSMonitorDMDARayDestroy));
366d1212d36SBarry Smith   }
3679566063dSJacob Faibussowitsch   PetscCall(PetscOptionsString("-ts_monitor_lg_dmda_ray", "Display a ray of the solution", "None", "x=0", dir, sizeof(dir), &flg));
36851b4a12fSMatthew G. Knepley   if (flg) {
36951b4a12fSMatthew G. Knepley     TSMonitorDMDARayCtx *rayctx;
37051b4a12fSMatthew G. Knepley     int                  ray = 0;
3713ee9839eSMatthew G. Knepley     DMDirection          ddir;
37251b4a12fSMatthew G. Knepley     DM                   da;
37351b4a12fSMatthew G. Knepley     PetscInt             howoften = 1;
374d1212d36SBarry Smith 
3753c633725SBarry Smith     PetscCheck(dir[1] == '=', PetscObjectComm((PetscObject)ts), PETSC_ERR_ARG_WRONG, "Malformed ray %s", dir);
3763ee9839eSMatthew G. Knepley     if (dir[0] == 'x') ddir = DM_X;
3773ee9839eSMatthew G. Knepley     else if (dir[0] == 'y') ddir = DM_Y;
37898921bdaSJacob Faibussowitsch     else SETERRQ(PetscObjectComm((PetscObject)ts), PETSC_ERR_ARG_WRONG, "Unknown ray direction %s", dir);
37951b4a12fSMatthew G. Knepley     sscanf(dir + 2, "%d", &ray);
3801c3436cfSJed Brown 
3819566063dSJacob Faibussowitsch     PetscCall(PetscInfo(((PetscObject)ts), "Displaying LG DMDA ray %c = %d\n", dir[0], ray));
3829566063dSJacob Faibussowitsch     PetscCall(PetscNew(&rayctx));
3839566063dSJacob Faibussowitsch     PetscCall(TSGetDM(ts, &da));
3849566063dSJacob Faibussowitsch     PetscCall(DMDAGetRay(da, ddir, ray, &rayctx->ray, &rayctx->scatter));
3859566063dSJacob Faibussowitsch     PetscCall(TSMonitorLGCtxCreate(PETSC_COMM_SELF, NULL, NULL, PETSC_DECIDE, PETSC_DECIDE, 600, 400, howoften, &rayctx->lgctx));
3869566063dSJacob Faibussowitsch     PetscCall(TSMonitorSet(ts, TSMonitorLGDMDARay, rayctx, TSMonitorDMDARayDestroy));
38751b4a12fSMatthew G. Knepley   }
388a7a1495cSBarry Smith 
3899566063dSJacob Faibussowitsch   PetscCall(PetscOptionsName("-ts_monitor_envelope", "Monitor maximum and minimum value of each component of the solution", "TSMonitorEnvelope", &opt));
390b3d3934dSBarry Smith   if (opt) {
391b3d3934dSBarry Smith     TSMonitorEnvelopeCtx ctx;
392b3d3934dSBarry Smith 
3939566063dSJacob Faibussowitsch     PetscCall(TSMonitorEnvelopeCtxCreate(ts, &ctx));
3949566063dSJacob Faibussowitsch     PetscCall(TSMonitorSet(ts, TSMonitorEnvelope, ctx, (PetscErrorCode(*)(void **))TSMonitorEnvelopeCtxDestroy));
395b3d3934dSBarry Smith   }
396aee7a9fbSMatthew G. Knepley   flg = PETSC_FALSE;
3979566063dSJacob Faibussowitsch   PetscCall(PetscOptionsBool("-ts_monitor_cancel", "Remove all monitors", "TSMonitorCancel", flg, &flg, &opt));
3989566063dSJacob Faibussowitsch   if (opt && flg) PetscCall(TSMonitorCancel(ts));
399b3d3934dSBarry Smith 
400847ff0e1SMatthew G. Knepley   flg = PETSC_FALSE;
401d7cfae9bSHong Zhang   PetscCall(PetscOptionsBool("-ts_fd_color", "Use finite differences with coloring to compute IJacobian", "TSComputeIJacobianDefaultColor", flg, &flg, NULL));
402847ff0e1SMatthew G. Knepley   if (flg) {
403847ff0e1SMatthew G. Knepley     DM dm;
404847ff0e1SMatthew G. Knepley 
4059371c9d4SSatish Balay     PetscCall(TSGetDM(ts, &dm));
4069371c9d4SSatish Balay     PetscCall(DMTSUnsetIJacobianContext_Internal(dm));
4079566063dSJacob Faibussowitsch     PetscCall(TSSetIJacobian(ts, NULL, NULL, TSComputeIJacobianDefaultColor, NULL));
4089566063dSJacob Faibussowitsch     PetscCall(PetscInfo(ts, "Setting default finite difference coloring Jacobian matrix\n"));
409847ff0e1SMatthew G. Knepley   }
410847ff0e1SMatthew G. Knepley 
411d763cef2SBarry Smith   /* Handle specific TS options */
412dbbe0bcdSBarry Smith   PetscTryTypeMethod(ts, setfromoptions, PetscOptionsObject);
413fbc52257SHong Zhang 
414a7bdc993SLisandro Dalcin   /* Handle TSAdapt options */
4159566063dSJacob Faibussowitsch   PetscCall(TSGetAdapt(ts, &ts->adapt));
4169566063dSJacob Faibussowitsch   PetscCall(TSAdaptSetDefaultType(ts->adapt, ts->default_adapt_type));
417dbbe0bcdSBarry Smith   PetscCall(TSAdaptSetFromOptions(ts->adapt, PetscOptionsObject));
418a7bdc993SLisandro Dalcin 
41968bece0bSHong Zhang   /* TS trajectory must be set after TS, since it may use some TS options above */
4204f122a70SLisandro Dalcin   tflg = ts->trajectory ? PETSC_TRUE : PETSC_FALSE;
4219566063dSJacob Faibussowitsch   PetscCall(PetscOptionsBool("-ts_save_trajectory", "Save the solution at each timestep", "TSSetSaveTrajectory", tflg, &tflg, NULL));
4221baa6e33SBarry Smith   if (tflg) PetscCall(TSSetSaveTrajectory(ts));
423a05bf03eSHong Zhang 
424dbbe0bcdSBarry Smith   PetscCall(TSAdjointSetFromOptions(ts, PetscOptionsObject));
425d763cef2SBarry Smith 
426d763cef2SBarry Smith   /* process any options handlers added with PetscObjectAddOptionsHandler() */
427dbbe0bcdSBarry Smith   PetscCall(PetscObjectProcessOptionsHandlers((PetscObject)ts, PetscOptionsObject));
428d0609cedSBarry Smith   PetscOptionsEnd();
429d763cef2SBarry Smith 
4301baa6e33SBarry Smith   if (ts->trajectory) PetscCall(TSTrajectorySetFromOptions(ts->trajectory, ts));
43168bece0bSHong Zhang 
4321ef27442SStefano Zampini   /* why do we have to do this here and not during TSSetUp? */
4339566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts, &ts->snes));
4341ef27442SStefano Zampini   if (ts->problem_type == TS_LINEAR) {
4359566063dSJacob Faibussowitsch     PetscCall(PetscObjectTypeCompareAny((PetscObject)ts->snes, &flg, SNESKSPONLY, SNESKSPTRANSPOSEONLY, ""));
4369566063dSJacob Faibussowitsch     if (!flg) PetscCall(SNESSetType(ts->snes, SNESKSPONLY));
4371ef27442SStefano Zampini   }
4389566063dSJacob Faibussowitsch   PetscCall(SNESSetFromOptions(ts->snes));
4393ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
440d763cef2SBarry Smith }
441d763cef2SBarry Smith 
442d2daff3dSHong Zhang /*@
443bcf0153eSBarry Smith    TSGetTrajectory - Gets the trajectory from a `TS` if it exists
44478fbdcc8SBarry Smith 
445c3339decSBarry Smith    Collective
44678fbdcc8SBarry Smith 
44778fbdcc8SBarry Smith    Input Parameters:
448bcf0153eSBarry Smith .  ts - the `TS` context obtained from `TSCreate()`
44978fbdcc8SBarry Smith 
4507a7aea1fSJed Brown    Output Parameters:
451bcf0153eSBarry Smith .  tr - the `TSTrajectory` object, if it exists
45278fbdcc8SBarry Smith 
45378fbdcc8SBarry Smith    Level: advanced
45478fbdcc8SBarry Smith 
455bcf0153eSBarry Smith    Note:
456bcf0153eSBarry Smith    This routine should be called after all `TS` options have been set
45778fbdcc8SBarry Smith 
458195e9b02SBarry Smith .seealso: [](chapter_ts), `TS`, `TSTrajectory`, `TSAdjointSolve()`, `TSTrajectory`, `TSTrajectoryCreate()`
45978fbdcc8SBarry Smith @*/
460d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetTrajectory(TS ts, TSTrajectory *tr)
461d71ae5a4SJacob Faibussowitsch {
46278fbdcc8SBarry Smith   PetscFunctionBegin;
46378fbdcc8SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
46478fbdcc8SBarry Smith   *tr = ts->trajectory;
4653ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
46678fbdcc8SBarry Smith }
46778fbdcc8SBarry Smith 
46878fbdcc8SBarry Smith /*@
469bcf0153eSBarry Smith    TSSetSaveTrajectory - Causes the `TS` to save its solutions as it iterates forward in time in a `TSTrajectory` object
470d2daff3dSHong Zhang 
471c3339decSBarry Smith    Collective
472d2daff3dSHong Zhang 
473f899ff85SJose E. Roman    Input Parameter:
474bcf0153eSBarry Smith .  ts - the `TS` context obtained from `TSCreate()`
475bc952696SBarry Smith 
476bcf0153eSBarry Smith    Options Database Keys:
47778fbdcc8SBarry Smith +  -ts_save_trajectory - saves the trajectory to a file
47867b8a455SSatish Balay -  -ts_trajectory_type type - set trajectory type
47978fbdcc8SBarry Smith 
480d2daff3dSHong Zhang    Level: intermediate
481d2daff3dSHong Zhang 
482bcf0153eSBarry Smith    Notes:
483bcf0153eSBarry Smith    This routine should be called after all `TS` options have been set
484d2daff3dSHong Zhang 
485bcf0153eSBarry Smith    The `TSTRAJECTORYVISUALIZATION` files can be loaded into Python with $PETSC_DIR/lib/petsc/bin/PetscBinaryIOTrajectory.py and
486bcf0153eSBarry Smith    MATLAB with $PETSC_DIR/share/petsc/matlab/PetscReadBinaryTrajectory.m
487bcf0153eSBarry Smith 
488195e9b02SBarry Smith .seealso: [](chapter_ts), `TS`, `TSTrajectory`, `TSGetTrajectory()`, `TSAdjointSolve()`
489d2daff3dSHong Zhang @*/
490d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetSaveTrajectory(TS ts)
491d71ae5a4SJacob Faibussowitsch {
492d2daff3dSHong Zhang   PetscFunctionBegin;
493d2daff3dSHong Zhang   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
49463a3b9bcSJacob Faibussowitsch   if (!ts->trajectory) PetscCall(TSTrajectoryCreate(PetscObjectComm((PetscObject)ts), &ts->trajectory));
4953ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
496d2daff3dSHong Zhang }
497d2daff3dSHong Zhang 
498a7a1495cSBarry Smith /*@
499bcf0153eSBarry Smith    TSResetTrajectory - Destroys and recreates the internal `TSTrajectory` object
5002d29f1f2SStefano Zampini 
501c3339decSBarry Smith    Collective
5022d29f1f2SStefano Zampini 
5032d29f1f2SStefano Zampini    Input Parameters:
504bcf0153eSBarry Smith .  ts - the `TS` context obtained from `TSCreate()`
5052d29f1f2SStefano Zampini 
5062d29f1f2SStefano Zampini    Level: intermediate
5072d29f1f2SStefano Zampini 
508bcf0153eSBarry Smith .seealso: [](chapter_ts), `TSTrajectory`, `TSGetTrajectory()`, `TSAdjointSolve()`, `TSRemoveTrajectory()`
5092d29f1f2SStefano Zampini @*/
510d71ae5a4SJacob Faibussowitsch PetscErrorCode TSResetTrajectory(TS ts)
511d71ae5a4SJacob Faibussowitsch {
5122d29f1f2SStefano Zampini   PetscFunctionBegin;
5132d29f1f2SStefano Zampini   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
5142d29f1f2SStefano Zampini   if (ts->trajectory) {
5159566063dSJacob Faibussowitsch     PetscCall(TSTrajectoryDestroy(&ts->trajectory));
5169566063dSJacob Faibussowitsch     PetscCall(TSTrajectoryCreate(PetscObjectComm((PetscObject)ts), &ts->trajectory));
5172d29f1f2SStefano Zampini   }
5183ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
5192d29f1f2SStefano Zampini }
5202d29f1f2SStefano Zampini 
5212d29f1f2SStefano Zampini /*@
522195e9b02SBarry Smith    TSRemoveTrajectory - Destroys and removes the internal `TSTrajectory` object from a `TS`
52367a3cfb0SHong Zhang 
524c3339decSBarry Smith    Collective
52567a3cfb0SHong Zhang 
52667a3cfb0SHong Zhang    Input Parameters:
527bcf0153eSBarry Smith .  ts - the `TS` context obtained from `TSCreate()`
52867a3cfb0SHong Zhang 
52967a3cfb0SHong Zhang    Level: intermediate
53067a3cfb0SHong Zhang 
531bcf0153eSBarry Smith .seealso: [](chapter_ts), `TSTrajectory`, `TSResetTrajectory()`, `TSAdjointSolve()`
53267a3cfb0SHong Zhang @*/
533d71ae5a4SJacob Faibussowitsch PetscErrorCode TSRemoveTrajectory(TS ts)
534d71ae5a4SJacob Faibussowitsch {
53567a3cfb0SHong Zhang   PetscFunctionBegin;
53667a3cfb0SHong Zhang   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
5371e66621cSBarry Smith   if (ts->trajectory) PetscCall(TSTrajectoryDestroy(&ts->trajectory));
5383ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
53967a3cfb0SHong Zhang }
54067a3cfb0SHong Zhang 
54167a3cfb0SHong Zhang /*@
542a7a1495cSBarry Smith    TSComputeRHSJacobian - Computes the Jacobian matrix that has been
543bcf0153eSBarry Smith       set with `TSSetRHSJacobian()`.
544a7a1495cSBarry Smith 
545c3339decSBarry Smith    Collective
546a7a1495cSBarry Smith 
547a7a1495cSBarry Smith    Input Parameters:
548bcf0153eSBarry Smith +  ts - the `TS` context
549a7a1495cSBarry Smith .  t - current timestep
5500910c330SBarry Smith -  U - input vector
551a7a1495cSBarry Smith 
552a7a1495cSBarry Smith    Output Parameters:
553a7a1495cSBarry Smith +  A - Jacobian matrix
5546b867d5aSJose E. Roman -  B - optional preconditioning matrix
555a7a1495cSBarry Smith 
556bcf0153eSBarry Smith    Level: developer
557bcf0153eSBarry Smith 
558bcf0153eSBarry Smith    Note:
559a7a1495cSBarry Smith    Most users should not need to explicitly call this routine, as it
560a7a1495cSBarry Smith    is used internally within the nonlinear solvers.
561a7a1495cSBarry Smith 
562bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSSetRHSJacobian()`, `KSPSetOperators()`
563a7a1495cSBarry Smith @*/
564d71ae5a4SJacob Faibussowitsch PetscErrorCode TSComputeRHSJacobian(TS ts, PetscReal t, Vec U, Mat A, Mat B)
565d71ae5a4SJacob Faibussowitsch {
566270bf2e7SJed Brown   PetscObjectState Ustate;
5676c1e1eecSBarry Smith   PetscObjectId    Uid;
56824989b8cSPeter Brune   DM               dm;
569942e3340SBarry Smith   DMTS             tsdm;
57024989b8cSPeter Brune   TSRHSJacobian    rhsjacobianfunc;
57124989b8cSPeter Brune   void            *ctx;
572b2df71adSDebojyoti Ghosh   TSRHSFunction    rhsfunction;
573a7a1495cSBarry Smith 
574a7a1495cSBarry Smith   PetscFunctionBegin;
5750700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
5760910c330SBarry Smith   PetscValidHeaderSpecific(U, VEC_CLASSID, 3);
5770910c330SBarry Smith   PetscCheckSameComm(ts, 1, U, 3);
5789566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
5799566063dSJacob Faibussowitsch   PetscCall(DMGetDMTS(dm, &tsdm));
5809566063dSJacob Faibussowitsch   PetscCall(DMTSGetRHSFunction(dm, &rhsfunction, NULL));
5819566063dSJacob Faibussowitsch   PetscCall(DMTSGetRHSJacobian(dm, &rhsjacobianfunc, &ctx));
5829566063dSJacob Faibussowitsch   PetscCall(PetscObjectStateGet((PetscObject)U, &Ustate));
5839566063dSJacob Faibussowitsch   PetscCall(PetscObjectGetId((PetscObject)U, &Uid));
584971015bcSStefano Zampini 
5853ba16761SJacob Faibussowitsch   if (ts->rhsjacobian.time == t && (ts->problem_type == TS_LINEAR || (ts->rhsjacobian.Xid == Uid && ts->rhsjacobian.Xstate == Ustate)) && (rhsfunction != TSComputeRHSFunctionLinear)) PetscFunctionReturn(PETSC_SUCCESS);
586d90be118SSean Farley 
58763a3b9bcSJacob Faibussowitsch   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);
58824989b8cSPeter Brune   if (rhsjacobianfunc) {
5899566063dSJacob Faibussowitsch     PetscCall(PetscLogEventBegin(TS_JacobianEval, ts, U, A, B));
590792fecdfSBarry Smith     PetscCallBack("TS callback Jacobian", (*rhsjacobianfunc)(ts, t, U, A, B, ctx));
591a6ab3590SBarry Smith     ts->rhsjacs++;
5929566063dSJacob Faibussowitsch     PetscCall(PetscLogEventEnd(TS_JacobianEval, ts, U, A, B));
593ef66eb69SBarry Smith   } else {
5949566063dSJacob Faibussowitsch     PetscCall(MatZeroEntries(A));
5959566063dSJacob Faibussowitsch     if (B && A != B) PetscCall(MatZeroEntries(B));
596ef66eb69SBarry Smith   }
5970e4ef248SJed Brown   ts->rhsjacobian.time  = t;
598971015bcSStefano Zampini   ts->rhsjacobian.shift = 0;
599971015bcSStefano Zampini   ts->rhsjacobian.scale = 1.;
6009566063dSJacob Faibussowitsch   PetscCall(PetscObjectGetId((PetscObject)U, &ts->rhsjacobian.Xid));
6019566063dSJacob Faibussowitsch   PetscCall(PetscObjectStateGet((PetscObject)U, &ts->rhsjacobian.Xstate));
6023ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
603a7a1495cSBarry Smith }
604a7a1495cSBarry Smith 
605316643e7SJed Brown /*@
606bcf0153eSBarry Smith    TSComputeRHSFunction - Evaluates the right-hand-side function for a `TS`
607d763cef2SBarry Smith 
608c3339decSBarry Smith    Collective
609316643e7SJed Brown 
610316643e7SJed Brown    Input Parameters:
611bcf0153eSBarry Smith +  ts - the `TS` context
612316643e7SJed Brown .  t - current time
6130910c330SBarry Smith -  U - state vector
614316643e7SJed Brown 
615316643e7SJed Brown    Output Parameter:
616316643e7SJed Brown .  y - right hand side
617316643e7SJed Brown 
618bcf0153eSBarry Smith    Level: developer
619bcf0153eSBarry Smith 
620316643e7SJed Brown    Note:
621316643e7SJed Brown    Most users should not need to explicitly call this routine, as it
622316643e7SJed Brown    is used internally within the nonlinear solvers.
623316643e7SJed Brown 
624bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSSetRHSFunction()`, `TSComputeIFunction()`
625316643e7SJed Brown @*/
626d71ae5a4SJacob Faibussowitsch PetscErrorCode TSComputeRHSFunction(TS ts, PetscReal t, Vec U, Vec y)
627d71ae5a4SJacob Faibussowitsch {
62824989b8cSPeter Brune   TSRHSFunction rhsfunction;
62924989b8cSPeter Brune   TSIFunction   ifunction;
63024989b8cSPeter Brune   void         *ctx;
63124989b8cSPeter Brune   DM            dm;
63224989b8cSPeter Brune 
633d763cef2SBarry Smith   PetscFunctionBegin;
6340700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
6350910c330SBarry Smith   PetscValidHeaderSpecific(U, VEC_CLASSID, 3);
6360700a824SBarry Smith   PetscValidHeaderSpecific(y, VEC_CLASSID, 4);
6379566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
6389566063dSJacob Faibussowitsch   PetscCall(DMTSGetRHSFunction(dm, &rhsfunction, &ctx));
6399566063dSJacob Faibussowitsch   PetscCall(DMTSGetIFunction(dm, &ifunction, NULL));
640d763cef2SBarry Smith 
6413c633725SBarry Smith   PetscCheck(rhsfunction || ifunction, PetscObjectComm((PetscObject)ts), PETSC_ERR_USER, "Must call TSSetRHSFunction() and / or TSSetIFunction()");
642d763cef2SBarry Smith 
64324989b8cSPeter Brune   if (rhsfunction) {
6449566063dSJacob Faibussowitsch     PetscCall(PetscLogEventBegin(TS_FunctionEval, ts, U, y, 0));
6459566063dSJacob Faibussowitsch     PetscCall(VecLockReadPush(U));
646792fecdfSBarry Smith     PetscCallBack("TS callback right-hand-side", (*rhsfunction)(ts, t, U, y, ctx));
6479566063dSJacob Faibussowitsch     PetscCall(VecLockReadPop(U));
648a6ab3590SBarry Smith     ts->rhsfuncs++;
6499566063dSJacob Faibussowitsch     PetscCall(PetscLogEventEnd(TS_FunctionEval, ts, U, y, 0));
6501e66621cSBarry Smith   } else PetscCall(VecZeroEntries(y));
6513ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
652d763cef2SBarry Smith }
653d763cef2SBarry Smith 
654ef20d060SBarry Smith /*@
655ef20d060SBarry Smith    TSComputeSolutionFunction - Evaluates the solution function.
656ef20d060SBarry Smith 
657c3339decSBarry Smith    Collective
658ef20d060SBarry Smith 
659ef20d060SBarry Smith    Input Parameters:
660bcf0153eSBarry Smith +  ts - the `TS` context
661ef20d060SBarry Smith -  t - current time
662ef20d060SBarry Smith 
663ef20d060SBarry Smith    Output Parameter:
6640910c330SBarry Smith .  U - the solution
665ef20d060SBarry Smith 
666ef20d060SBarry Smith    Level: developer
667ef20d060SBarry Smith 
668bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSSetSolutionFunction()`, `TSSetRHSFunction()`, `TSComputeIFunction()`
669ef20d060SBarry Smith @*/
670d71ae5a4SJacob Faibussowitsch PetscErrorCode TSComputeSolutionFunction(TS ts, PetscReal t, Vec U)
671d71ae5a4SJacob Faibussowitsch {
672ef20d060SBarry Smith   TSSolutionFunction solutionfunction;
673ef20d060SBarry Smith   void              *ctx;
674ef20d060SBarry Smith   DM                 dm;
675ef20d060SBarry Smith 
676ef20d060SBarry Smith   PetscFunctionBegin;
677ef20d060SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
6780910c330SBarry Smith   PetscValidHeaderSpecific(U, VEC_CLASSID, 3);
6799566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
6809566063dSJacob Faibussowitsch   PetscCall(DMTSGetSolutionFunction(dm, &solutionfunction, &ctx));
681792fecdfSBarry Smith   if (solutionfunction) PetscCallBack("TS callback solution", (*solutionfunction)(ts, t, U, ctx));
6823ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
683ef20d060SBarry Smith }
6849b7cd975SBarry Smith /*@
6859b7cd975SBarry Smith    TSComputeForcingFunction - Evaluates the forcing function.
6869b7cd975SBarry Smith 
687c3339decSBarry Smith    Collective
6889b7cd975SBarry Smith 
6899b7cd975SBarry Smith    Input Parameters:
690bcf0153eSBarry Smith +  ts - the `TS` context
6919b7cd975SBarry Smith -  t - current time
6929b7cd975SBarry Smith 
6939b7cd975SBarry Smith    Output Parameter:
6949b7cd975SBarry Smith .  U - the function value
6959b7cd975SBarry Smith 
6969b7cd975SBarry Smith    Level: developer
6979b7cd975SBarry Smith 
698bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSSetSolutionFunction()`, `TSSetRHSFunction()`, `TSComputeIFunction()`
6999b7cd975SBarry Smith @*/
700d71ae5a4SJacob Faibussowitsch PetscErrorCode TSComputeForcingFunction(TS ts, PetscReal t, Vec U)
701d71ae5a4SJacob Faibussowitsch {
7029b7cd975SBarry Smith   void             *ctx;
7039b7cd975SBarry Smith   DM                dm;
7045f80ce2aSJacob Faibussowitsch   TSForcingFunction forcing;
7059b7cd975SBarry Smith 
7069b7cd975SBarry Smith   PetscFunctionBegin;
7079b7cd975SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
7089b7cd975SBarry Smith   PetscValidHeaderSpecific(U, VEC_CLASSID, 3);
7099566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
7109566063dSJacob Faibussowitsch   PetscCall(DMTSGetForcingFunction(dm, &forcing, &ctx));
7119b7cd975SBarry Smith 
712792fecdfSBarry Smith   if (forcing) PetscCallBack("TS callback forcing function", (*forcing)(ts, t, U, ctx));
7133ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
7149b7cd975SBarry Smith }
715ef20d060SBarry Smith 
716d71ae5a4SJacob Faibussowitsch static PetscErrorCode TSGetRHSVec_Private(TS ts, Vec *Frhs)
717d71ae5a4SJacob Faibussowitsch {
7182dd45cf8SJed Brown   Vec F;
719214bc6a2SJed Brown 
720214bc6a2SJed Brown   PetscFunctionBegin;
7210298fd71SBarry Smith   *Frhs = NULL;
7229566063dSJacob Faibussowitsch   PetscCall(TSGetIFunction(ts, &F, NULL, NULL));
7231e66621cSBarry Smith   if (!ts->Frhs) PetscCall(VecDuplicate(F, &ts->Frhs));
724214bc6a2SJed Brown   *Frhs = ts->Frhs;
7253ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
726214bc6a2SJed Brown }
727214bc6a2SJed Brown 
728d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetRHSMats_Private(TS ts, Mat *Arhs, Mat *Brhs)
729d71ae5a4SJacob Faibussowitsch {
730214bc6a2SJed Brown   Mat         A, B;
73141a1d4d2SBarry Smith   TSIJacobian ijacobian;
732214bc6a2SJed Brown 
733214bc6a2SJed Brown   PetscFunctionBegin;
734c0cd0301SJed Brown   if (Arhs) *Arhs = NULL;
735c0cd0301SJed Brown   if (Brhs) *Brhs = NULL;
7369566063dSJacob Faibussowitsch   PetscCall(TSGetIJacobian(ts, &A, &B, &ijacobian, NULL));
737214bc6a2SJed Brown   if (Arhs) {
738214bc6a2SJed Brown     if (!ts->Arhs) {
73941a1d4d2SBarry Smith       if (ijacobian) {
7409566063dSJacob Faibussowitsch         PetscCall(MatDuplicate(A, MAT_DO_NOT_COPY_VALUES, &ts->Arhs));
7419566063dSJacob Faibussowitsch         PetscCall(TSSetMatStructure(ts, SAME_NONZERO_PATTERN));
74241a1d4d2SBarry Smith       } else {
74341a1d4d2SBarry Smith         ts->Arhs = A;
7449566063dSJacob Faibussowitsch         PetscCall(PetscObjectReference((PetscObject)A));
74541a1d4d2SBarry Smith       }
7463565c898SBarry Smith     } else {
7473565c898SBarry Smith       PetscBool flg;
7489566063dSJacob Faibussowitsch       PetscCall(SNESGetUseMatrixFree(ts->snes, NULL, &flg));
7493565c898SBarry Smith       /* Handle case where user provided only RHSJacobian and used -snes_mf_operator */
7503565c898SBarry Smith       if (flg && !ijacobian && ts->Arhs == ts->Brhs) {
7519566063dSJacob Faibussowitsch         PetscCall(PetscObjectDereference((PetscObject)ts->Arhs));
7523565c898SBarry Smith         ts->Arhs = A;
7539566063dSJacob Faibussowitsch         PetscCall(PetscObjectReference((PetscObject)A));
7543565c898SBarry Smith       }
755214bc6a2SJed Brown     }
756214bc6a2SJed Brown     *Arhs = ts->Arhs;
757214bc6a2SJed Brown   }
758214bc6a2SJed Brown   if (Brhs) {
759214bc6a2SJed Brown     if (!ts->Brhs) {
760bdb70873SJed Brown       if (A != B) {
76141a1d4d2SBarry Smith         if (ijacobian) {
7629566063dSJacob Faibussowitsch           PetscCall(MatDuplicate(B, MAT_DO_NOT_COPY_VALUES, &ts->Brhs));
763bdb70873SJed Brown         } else {
76441a1d4d2SBarry Smith           ts->Brhs = B;
7659566063dSJacob Faibussowitsch           PetscCall(PetscObjectReference((PetscObject)B));
76641a1d4d2SBarry Smith         }
76741a1d4d2SBarry Smith       } else {
7689566063dSJacob Faibussowitsch         PetscCall(PetscObjectReference((PetscObject)ts->Arhs));
76951699248SLisandro Dalcin         ts->Brhs = ts->Arhs;
770bdb70873SJed Brown       }
771214bc6a2SJed Brown     }
772214bc6a2SJed Brown     *Brhs = ts->Brhs;
773214bc6a2SJed Brown   }
7743ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
775214bc6a2SJed Brown }
776214bc6a2SJed Brown 
777316643e7SJed Brown /*@
778195e9b02SBarry Smith    TSComputeIFunction - Evaluates the DAE residual written in the implicit form F(t,U,Udot)=0
779316643e7SJed Brown 
780c3339decSBarry Smith    Collective
781316643e7SJed Brown 
782316643e7SJed Brown    Input Parameters:
783bcf0153eSBarry Smith +  ts - the `TS` context
784316643e7SJed Brown .  t - current time
7850910c330SBarry Smith .  U - state vector
7860910c330SBarry Smith .  Udot - time derivative of state vector
787bcf0153eSBarry Smith -  imex - flag indicates if the method is `TSIMEX` so that the RHSFunction should be kept separate
788316643e7SJed Brown 
789316643e7SJed Brown    Output Parameter:
790316643e7SJed Brown .  Y - right hand side
791316643e7SJed Brown 
792bcf0153eSBarry Smith    Level: developer
793bcf0153eSBarry Smith 
794316643e7SJed Brown    Note:
795316643e7SJed Brown    Most users should not need to explicitly call this routine, as it
796316643e7SJed Brown    is used internally within the nonlinear solvers.
797316643e7SJed Brown 
798316643e7SJed Brown    If the user did did not write their equations in implicit form, this
799316643e7SJed Brown    function recasts them in implicit form.
800316643e7SJed Brown 
801bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSSetIFunction()`, `TSComputeRHSFunction()`
802316643e7SJed Brown @*/
803d71ae5a4SJacob Faibussowitsch PetscErrorCode TSComputeIFunction(TS ts, PetscReal t, Vec U, Vec Udot, Vec Y, PetscBool imex)
804d71ae5a4SJacob Faibussowitsch {
80524989b8cSPeter Brune   TSIFunction   ifunction;
80624989b8cSPeter Brune   TSRHSFunction rhsfunction;
80724989b8cSPeter Brune   void         *ctx;
80824989b8cSPeter Brune   DM            dm;
809316643e7SJed Brown 
810316643e7SJed Brown   PetscFunctionBegin;
8110700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
8120910c330SBarry Smith   PetscValidHeaderSpecific(U, VEC_CLASSID, 3);
8130910c330SBarry Smith   PetscValidHeaderSpecific(Udot, VEC_CLASSID, 4);
8140700a824SBarry Smith   PetscValidHeaderSpecific(Y, VEC_CLASSID, 5);
815316643e7SJed Brown 
8169566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
8179566063dSJacob Faibussowitsch   PetscCall(DMTSGetIFunction(dm, &ifunction, &ctx));
8189566063dSJacob Faibussowitsch   PetscCall(DMTSGetRHSFunction(dm, &rhsfunction, NULL));
81924989b8cSPeter Brune 
8203c633725SBarry Smith   PetscCheck(rhsfunction || ifunction, PetscObjectComm((PetscObject)ts), PETSC_ERR_USER, "Must call TSSetRHSFunction() and / or TSSetIFunction()");
821d90be118SSean Farley 
8229566063dSJacob Faibussowitsch   PetscCall(PetscLogEventBegin(TS_FunctionEval, ts, U, Udot, Y));
82324989b8cSPeter Brune   if (ifunction) {
824792fecdfSBarry Smith     PetscCallBack("TS callback implicit function", (*ifunction)(ts, t, U, Udot, Y, ctx));
825a6ab3590SBarry Smith     ts->ifuncs++;
826214bc6a2SJed Brown   }
827214bc6a2SJed Brown   if (imex) {
8281e66621cSBarry Smith     if (!ifunction) PetscCall(VecCopy(Udot, Y));
82924989b8cSPeter Brune   } else if (rhsfunction) {
83024989b8cSPeter Brune     if (ifunction) {
831214bc6a2SJed Brown       Vec Frhs;
8329566063dSJacob Faibussowitsch       PetscCall(TSGetRHSVec_Private(ts, &Frhs));
8339566063dSJacob Faibussowitsch       PetscCall(TSComputeRHSFunction(ts, t, U, Frhs));
8349566063dSJacob Faibussowitsch       PetscCall(VecAXPY(Y, -1, Frhs));
8352dd45cf8SJed Brown     } else {
8369566063dSJacob Faibussowitsch       PetscCall(TSComputeRHSFunction(ts, t, U, Y));
8379566063dSJacob Faibussowitsch       PetscCall(VecAYPX(Y, -1, Udot));
838316643e7SJed Brown     }
8394a6899ffSJed Brown   }
8409566063dSJacob Faibussowitsch   PetscCall(PetscLogEventEnd(TS_FunctionEval, ts, U, Udot, Y));
8413ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
842316643e7SJed Brown }
843316643e7SJed Brown 
844cfa8a9a2SHong Zhang /*
845195e9b02SBarry Smith    TSRecoverRHSJacobian - Recover the Jacobian matrix so that one can call `TSComputeRHSJacobian()` on it.
846cfa8a9a2SHong Zhang 
847cfa8a9a2SHong Zhang    Note:
848195e9b02SBarry Smith    This routine is needed when one switches from `TSComputeIJacobian()` to `TSComputeRHSJacobian()` because the Jacobian matrix may be shifted or scaled in `TSComputeIJacobian()`.
849cfa8a9a2SHong Zhang 
850cfa8a9a2SHong Zhang */
851d71ae5a4SJacob Faibussowitsch static PetscErrorCode TSRecoverRHSJacobian(TS ts, Mat A, Mat B)
852d71ae5a4SJacob Faibussowitsch {
853cfa8a9a2SHong Zhang   PetscFunctionBegin;
854cfa8a9a2SHong Zhang   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
8553c633725SBarry Smith   PetscCheck(A == ts->Arhs, PetscObjectComm((PetscObject)ts), PETSC_ERR_SUP, "Invalid Amat");
8563c633725SBarry Smith   PetscCheck(B == ts->Brhs, PetscObjectComm((PetscObject)ts), PETSC_ERR_SUP, "Invalid Bmat");
857cfa8a9a2SHong Zhang 
8581baa6e33SBarry Smith   if (ts->rhsjacobian.shift) PetscCall(MatShift(A, -ts->rhsjacobian.shift));
85948a46eb9SPierre Jolivet   if (ts->rhsjacobian.scale == -1.) PetscCall(MatScale(A, -1));
860cfa8a9a2SHong Zhang   if (B && B == ts->Brhs && A != B) {
8611baa6e33SBarry Smith     if (ts->rhsjacobian.shift) PetscCall(MatShift(B, -ts->rhsjacobian.shift));
8621e66621cSBarry Smith     if (ts->rhsjacobian.scale == -1.) PetscCall(MatScale(B, -1));
863cfa8a9a2SHong Zhang   }
864cfa8a9a2SHong Zhang   ts->rhsjacobian.shift = 0;
865cfa8a9a2SHong Zhang   ts->rhsjacobian.scale = 1.;
8663ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
867cfa8a9a2SHong Zhang }
868cfa8a9a2SHong Zhang 
869316643e7SJed Brown /*@
870316643e7SJed Brown    TSComputeIJacobian - Evaluates the Jacobian of the DAE
871316643e7SJed Brown 
872c3339decSBarry Smith    Collective
873316643e7SJed Brown 
874316643e7SJed Brown    Input
875316643e7SJed Brown       Input Parameters:
876bcf0153eSBarry Smith +  ts - the `TS` context
877316643e7SJed Brown .  t - current timestep
8780910c330SBarry Smith .  U - state vector
8790910c330SBarry Smith .  Udot - time derivative of state vector
880214bc6a2SJed Brown .  shift - shift to apply, see note below
881bcf0153eSBarry Smith -  imex - flag indicates if the method is `TSIMEX` so that the RHSJacobian should be kept separate
882316643e7SJed Brown 
883316643e7SJed Brown    Output Parameters:
884316643e7SJed Brown +  A - Jacobian matrix
885195e9b02SBarry Smith -  B - matrix from which the preconditioner is constructed; often the same as `A`
886316643e7SJed Brown 
887bcf0153eSBarry Smith    Level: developer
888bcf0153eSBarry Smith 
889316643e7SJed Brown    Notes:
8900910c330SBarry Smith    If F(t,U,Udot)=0 is the DAE, the required Jacobian is
891195e9b02SBarry Smith .vb
8920910c330SBarry Smith    dF/dU + shift*dF/dUdot
893195e9b02SBarry Smith .ve
894316643e7SJed Brown    Most users should not need to explicitly call this routine, as it
895316643e7SJed Brown    is used internally within the nonlinear solvers.
896316643e7SJed Brown 
897bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSSetIJacobian()`
89863495f91SJed Brown @*/
899d71ae5a4SJacob Faibussowitsch PetscErrorCode TSComputeIJacobian(TS ts, PetscReal t, Vec U, Vec Udot, PetscReal shift, Mat A, Mat B, PetscBool imex)
900d71ae5a4SJacob Faibussowitsch {
90124989b8cSPeter Brune   TSIJacobian   ijacobian;
90224989b8cSPeter Brune   TSRHSJacobian rhsjacobian;
90324989b8cSPeter Brune   DM            dm;
90424989b8cSPeter Brune   void         *ctx;
905316643e7SJed Brown 
906316643e7SJed Brown   PetscFunctionBegin;
9070700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
9080910c330SBarry Smith   PetscValidHeaderSpecific(U, VEC_CLASSID, 3);
9090910c330SBarry Smith   PetscValidHeaderSpecific(Udot, VEC_CLASSID, 4);
910316643e7SJed Brown   PetscValidPointer(A, 6);
91194ab13aaSBarry Smith   PetscValidHeaderSpecific(A, MAT_CLASSID, 6);
912316643e7SJed Brown   PetscValidPointer(B, 7);
91394ab13aaSBarry Smith   PetscValidHeaderSpecific(B, MAT_CLASSID, 7);
91424989b8cSPeter Brune 
9159566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
9169566063dSJacob Faibussowitsch   PetscCall(DMTSGetIJacobian(dm, &ijacobian, &ctx));
9179566063dSJacob Faibussowitsch   PetscCall(DMTSGetRHSJacobian(dm, &rhsjacobian, NULL));
91824989b8cSPeter Brune 
9193c633725SBarry Smith   PetscCheck(rhsjacobian || ijacobian, PetscObjectComm((PetscObject)ts), PETSC_ERR_USER, "Must call TSSetRHSJacobian() and / or TSSetIJacobian()");
920316643e7SJed Brown 
9219566063dSJacob Faibussowitsch   PetscCall(PetscLogEventBegin(TS_JacobianEval, ts, U, A, B));
92224989b8cSPeter Brune   if (ijacobian) {
923792fecdfSBarry Smith     PetscCallBack("TS callback implicit Jacobian", (*ijacobian)(ts, t, U, Udot, shift, A, B, ctx));
924a6ab3590SBarry Smith     ts->ijacs++;
9254a6899ffSJed Brown   }
926214bc6a2SJed Brown   if (imex) {
927b5abc632SBarry Smith     if (!ijacobian) { /* system was written as Udot = G(t,U) */
9284c26be97Sstefano_zampini       PetscBool assembled;
929971015bcSStefano Zampini       if (rhsjacobian) {
930971015bcSStefano Zampini         Mat Arhs = NULL;
9319566063dSJacob Faibussowitsch         PetscCall(TSGetRHSMats_Private(ts, &Arhs, NULL));
932971015bcSStefano Zampini         if (A == Arhs) {
9333c633725SBarry Smith           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 */
934971015bcSStefano Zampini           ts->rhsjacobian.time = PETSC_MIN_REAL;
935971015bcSStefano Zampini         }
936971015bcSStefano Zampini       }
9379566063dSJacob Faibussowitsch       PetscCall(MatZeroEntries(A));
9389566063dSJacob Faibussowitsch       PetscCall(MatAssembled(A, &assembled));
9394c26be97Sstefano_zampini       if (!assembled) {
9409566063dSJacob Faibussowitsch         PetscCall(MatAssemblyBegin(A, MAT_FINAL_ASSEMBLY));
9419566063dSJacob Faibussowitsch         PetscCall(MatAssemblyEnd(A, MAT_FINAL_ASSEMBLY));
9424c26be97Sstefano_zampini       }
9439566063dSJacob Faibussowitsch       PetscCall(MatShift(A, shift));
94494ab13aaSBarry Smith       if (A != B) {
9459566063dSJacob Faibussowitsch         PetscCall(MatZeroEntries(B));
9469566063dSJacob Faibussowitsch         PetscCall(MatAssembled(B, &assembled));
9474c26be97Sstefano_zampini         if (!assembled) {
9489566063dSJacob Faibussowitsch           PetscCall(MatAssemblyBegin(B, MAT_FINAL_ASSEMBLY));
9499566063dSJacob Faibussowitsch           PetscCall(MatAssemblyEnd(B, MAT_FINAL_ASSEMBLY));
9504c26be97Sstefano_zampini         }
9519566063dSJacob Faibussowitsch         PetscCall(MatShift(B, shift));
952214bc6a2SJed Brown       }
953214bc6a2SJed Brown     }
954214bc6a2SJed Brown   } else {
955e1244c69SJed Brown     Mat Arhs = NULL, Brhs = NULL;
9561e66621cSBarry Smith 
9571e66621cSBarry Smith     /* RHSJacobian needs to be converted to part of IJacobian if exists */
9581e66621cSBarry Smith     if (rhsjacobian) PetscCall(TSGetRHSMats_Private(ts, &Arhs, &Brhs));
959e8b1e424SHong Zhang     if (Arhs == A) { /* No IJacobian matrix, so we only have the RHS matrix */
960e8b1e424SHong Zhang       PetscObjectState Ustate;
961e8b1e424SHong Zhang       PetscObjectId    Uid;
962e8b1e424SHong Zhang       TSRHSFunction    rhsfunction;
963e8b1e424SHong Zhang 
9649566063dSJacob Faibussowitsch       PetscCall(DMTSGetRHSFunction(dm, &rhsfunction, NULL));
9659566063dSJacob Faibussowitsch       PetscCall(PetscObjectStateGet((PetscObject)U, &Ustate));
9669566063dSJacob Faibussowitsch       PetscCall(PetscObjectGetId((PetscObject)U, &Uid));
9679371c9d4SSatish Balay       if ((rhsjacobian == TSComputeRHSJacobianConstant || (ts->rhsjacobian.time == t && (ts->problem_type == TS_LINEAR || (ts->rhsjacobian.Xid == Uid && ts->rhsjacobian.Xstate == Ustate)) && rhsfunction != TSComputeRHSFunctionLinear)) &&
9689371c9d4SSatish Balay           ts->rhsjacobian.scale == -1.) {                      /* No need to recompute RHSJacobian */
9699566063dSJacob Faibussowitsch         PetscCall(MatShift(A, shift - ts->rhsjacobian.shift)); /* revert the old shift and add the new shift with a single call to MatShift */
9701e66621cSBarry Smith         if (A != B) PetscCall(MatShift(B, shift - ts->rhsjacobian.shift));
971e8b1e424SHong Zhang       } else {
9723565c898SBarry Smith         PetscBool flg;
973e8b1e424SHong Zhang 
974e8b1e424SHong Zhang         if (ts->rhsjacobian.reuse) { /* Undo the damage */
975e8b1e424SHong Zhang           /* MatScale has a short path for this case.
976e8b1e424SHong Zhang              However, this code path is taken the first time TSComputeRHSJacobian is called
977e8b1e424SHong Zhang              and the matrices have not been assembled yet */
9789566063dSJacob Faibussowitsch           PetscCall(TSRecoverRHSJacobian(ts, A, B));
979e8b1e424SHong Zhang         }
9809566063dSJacob Faibussowitsch         PetscCall(TSComputeRHSJacobian(ts, t, U, A, B));
9819566063dSJacob Faibussowitsch         PetscCall(SNESGetUseMatrixFree(ts->snes, NULL, &flg));
9823565c898SBarry Smith         /* since -snes_mf_operator uses the full SNES function it does not need to be shifted or scaled here */
9833565c898SBarry Smith         if (!flg) {
9849566063dSJacob Faibussowitsch           PetscCall(MatScale(A, -1));
9859566063dSJacob Faibussowitsch           PetscCall(MatShift(A, shift));
9863565c898SBarry Smith         }
98794ab13aaSBarry Smith         if (A != B) {
9889566063dSJacob Faibussowitsch           PetscCall(MatScale(B, -1));
9899566063dSJacob Faibussowitsch           PetscCall(MatShift(B, shift));
990316643e7SJed Brown         }
991e8b1e424SHong Zhang       }
992e8b1e424SHong Zhang       ts->rhsjacobian.scale = -1;
993e8b1e424SHong Zhang       ts->rhsjacobian.shift = shift;
994d60b7d5cSBarry Smith     } else if (Arhs) {  /* Both IJacobian and RHSJacobian */
995e1244c69SJed Brown       if (!ijacobian) { /* No IJacobian provided, but we have a separate RHS matrix */
9969566063dSJacob Faibussowitsch         PetscCall(MatZeroEntries(A));
9979566063dSJacob Faibussowitsch         PetscCall(MatShift(A, shift));
99894ab13aaSBarry Smith         if (A != B) {
9999566063dSJacob Faibussowitsch           PetscCall(MatZeroEntries(B));
10009566063dSJacob Faibussowitsch           PetscCall(MatShift(B, shift));
1001214bc6a2SJed Brown         }
1002316643e7SJed Brown       }
10039566063dSJacob Faibussowitsch       PetscCall(TSComputeRHSJacobian(ts, t, U, Arhs, Brhs));
10049566063dSJacob Faibussowitsch       PetscCall(MatAXPY(A, -1, Arhs, ts->axpy_pattern));
10051e66621cSBarry Smith       if (A != B) PetscCall(MatAXPY(B, -1, Brhs, ts->axpy_pattern));
1006316643e7SJed Brown     }
1007316643e7SJed Brown   }
10089566063dSJacob Faibussowitsch   PetscCall(PetscLogEventEnd(TS_JacobianEval, ts, U, A, B));
10093ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1010316643e7SJed Brown }
1011316643e7SJed Brown 
1012d763cef2SBarry Smith /*@C
1013d763cef2SBarry Smith     TSSetRHSFunction - Sets the routine for evaluating the function,
1014b5abc632SBarry Smith     where U_t = G(t,u).
1015d763cef2SBarry Smith 
1016c3339decSBarry Smith     Logically Collective
1017d763cef2SBarry Smith 
1018d763cef2SBarry Smith     Input Parameters:
1019bcf0153eSBarry Smith +   ts - the `TS` context obtained from `TSCreate()`
1020195e9b02SBarry Smith .   r - vector to put the computed right hand side (or `NULL` to have it created)
1021d763cef2SBarry Smith .   f - routine for evaluating the right-hand-side function
1022195e9b02SBarry Smith -   ctx - [optional] user-defined context for private data for the function evaluation routine (may be `NULL`)
1023d763cef2SBarry Smith 
1024a96d6ef6SBarry Smith     Calling sequence of f:
1025a96d6ef6SBarry Smith $     PetscErrorCode f(TS ts,PetscReal t,Vec u,Vec F,void *ctx);
1026d763cef2SBarry Smith 
1027a96d6ef6SBarry Smith +   ts - timestep context
1028a96d6ef6SBarry Smith .   t - current timestep
1029d763cef2SBarry Smith .   u - input vector
1030d763cef2SBarry Smith .   F - function vector
1031d763cef2SBarry Smith -   ctx - [optional] user-defined function context
1032d763cef2SBarry Smith 
1033d763cef2SBarry Smith     Level: beginner
1034d763cef2SBarry Smith 
1035bcf0153eSBarry Smith     Note:
1036bcf0153eSBarry Smith     You must call this function or `TSSetIFunction()` to define your ODE. You cannot use this function when solving a DAE.
10372bbac0d3SBarry Smith 
1038bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSSetRHSJacobian()`, `TSSetIJacobian()`, `TSSetIFunction()`
1039d763cef2SBarry Smith @*/
1040d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetRHSFunction(TS ts, Vec r, PetscErrorCode (*f)(TS, PetscReal, Vec, Vec, void *), void *ctx)
1041d71ae5a4SJacob Faibussowitsch {
1042089b2837SJed Brown   SNES snes;
10430298fd71SBarry Smith   Vec  ralloc = NULL;
104424989b8cSPeter Brune   DM   dm;
1045d763cef2SBarry Smith 
1046089b2837SJed Brown   PetscFunctionBegin;
10470700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
1048ca94891dSJed Brown   if (r) PetscValidHeaderSpecific(r, VEC_CLASSID, 2);
104924989b8cSPeter Brune 
10509566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
10519566063dSJacob Faibussowitsch   PetscCall(DMTSSetRHSFunction(dm, f, ctx));
10529566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts, &snes));
1053e856ceecSJed Brown   if (!r && !ts->dm && ts->vec_sol) {
10549566063dSJacob Faibussowitsch     PetscCall(VecDuplicate(ts->vec_sol, &ralloc));
1055e856ceecSJed Brown     r = ralloc;
1056e856ceecSJed Brown   }
10579566063dSJacob Faibussowitsch   PetscCall(SNESSetFunction(snes, r, SNESTSFormFunction, ts));
10589566063dSJacob Faibussowitsch   PetscCall(VecDestroy(&ralloc));
10593ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1060d763cef2SBarry Smith }
1061d763cef2SBarry Smith 
1062ef20d060SBarry Smith /*@C
1063abd5a294SJed Brown     TSSetSolutionFunction - Provide a function that computes the solution of the ODE or DAE
1064ef20d060SBarry Smith 
1065c3339decSBarry Smith     Logically Collective
1066ef20d060SBarry Smith 
1067ef20d060SBarry Smith     Input Parameters:
1068bcf0153eSBarry Smith +   ts - the `TS` context obtained from `TSCreate()`
1069ef20d060SBarry Smith .   f - routine for evaluating the solution
1070ef20d060SBarry Smith -   ctx - [optional] user-defined context for private data for the
1071195e9b02SBarry Smith           function evaluation routine (may be `NULL`)
1072ef20d060SBarry Smith 
1073a96d6ef6SBarry Smith     Calling sequence of f:
1074a96d6ef6SBarry Smith $     PetscErrorCode f(TS ts,PetscReal t,Vec u,void *ctx);
1075ef20d060SBarry Smith 
1076ef20d060SBarry Smith +   t - current timestep
1077ef20d060SBarry Smith .   u - output vector
1078ef20d060SBarry Smith -   ctx - [optional] user-defined function context
1079ef20d060SBarry Smith 
1080bcf0153eSBarry Smith     Options Database Keys:
1081bcf0153eSBarry Smith +  -ts_monitor_lg_error - create a graphical monitor of error history, requires user to have provided `TSSetSolutionFunction()`
1082bcf0153eSBarry Smith -  -ts_monitor_draw_error - Monitor error graphically, requires user to have provided `TSSetSolutionFunction()`
1083bcf0153eSBarry Smith 
1084bcf0153eSBarry Smith     Level: intermediate
10850ed3bfb6SBarry Smith 
1086abd5a294SJed Brown     Notes:
1087abd5a294SJed Brown     This routine is used for testing accuracy of time integration schemes when you already know the solution.
1088abd5a294SJed Brown     If analytic solutions are not known for your system, consider using the Method of Manufactured Solutions to
1089abd5a294SJed Brown     create closed-form solutions with non-physical forcing terms.
1090abd5a294SJed Brown 
1091bcf0153eSBarry Smith     For low-dimensional problems solved in serial, such as small discrete systems, `TSMonitorLGError()` can be used to monitor the error history.
1092abd5a294SJed Brown 
1093bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSSetRHSJacobian()`, `TSSetIJacobian()`, `TSComputeSolutionFunction()`, `TSSetForcingFunction()`, `TSSetSolution()`, `TSGetSolution()`, `TSMonitorLGError()`, `TSMonitorDrawError()`
1094ef20d060SBarry Smith @*/
1095d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetSolutionFunction(TS ts, PetscErrorCode (*f)(TS, PetscReal, Vec, void *), void *ctx)
1096d71ae5a4SJacob Faibussowitsch {
1097ef20d060SBarry Smith   DM dm;
1098ef20d060SBarry Smith 
1099ef20d060SBarry Smith   PetscFunctionBegin;
1100ef20d060SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
11019566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
11029566063dSJacob Faibussowitsch   PetscCall(DMTSSetSolutionFunction(dm, f, ctx));
11033ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1104ef20d060SBarry Smith }
1105ef20d060SBarry Smith 
11069b7cd975SBarry Smith /*@C
11079b7cd975SBarry Smith     TSSetForcingFunction - Provide a function that computes a forcing term for a ODE or PDE
11089b7cd975SBarry Smith 
1109c3339decSBarry Smith     Logically Collective
11109b7cd975SBarry Smith 
11119b7cd975SBarry Smith     Input Parameters:
1112bcf0153eSBarry Smith +   ts - the `TS` context obtained from `TSCreate()`
1113e162b725SBarry Smith .   func - routine for evaluating the forcing function
11149b7cd975SBarry Smith -   ctx - [optional] user-defined context for private data for the
1115195e9b02SBarry Smith           function evaluation routine (may be `NULL`)
11169b7cd975SBarry Smith 
11179b7cd975SBarry Smith     Calling sequence of func:
11186bc98fa9SBarry Smith $     PetscErrorCode func (TS ts,PetscReal t,Vec f,void *ctx);
11199b7cd975SBarry Smith 
11209b7cd975SBarry Smith +   t - current timestep
1121e162b725SBarry Smith .   f - output vector
11229b7cd975SBarry Smith -   ctx - [optional] user-defined function context
11239b7cd975SBarry Smith 
1124bcf0153eSBarry Smith     Level: intermediate
1125bcf0153eSBarry Smith 
11269b7cd975SBarry Smith     Notes:
11279b7cd975SBarry Smith     This routine is useful for testing accuracy of time integration schemes when using the Method of Manufactured Solutions to
1128e162b725SBarry Smith     create closed-form solutions with a non-physical forcing term. It allows you to use the Method of Manufactored Solution without directly editing the
1129e162b725SBarry Smith     definition of the problem you are solving and hence possibly introducing bugs.
1130e162b725SBarry Smith 
1131e162b725SBarry Smith     This replaces the ODE F(u,u_t,t) = 0 the TS is solving with F(u,u_t,t) - func(t) = 0
1132e162b725SBarry Smith 
1133e162b725SBarry Smith     This forcing function does not depend on the solution to the equations, it can only depend on spatial location, time, and possibly parameters, the
1134e162b725SBarry Smith     parameters can be passed in the ctx variable.
11359b7cd975SBarry Smith 
1136bcf0153eSBarry Smith     For low-dimensional problems solved in serial, such as small discrete systems, `TSMonitorLGError()` can be used to monitor the error history.
11379b7cd975SBarry Smith 
1138bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSSetRHSJacobian()`, `TSSetIJacobian()`, `TSComputeSolutionFunction()`, `TSSetSolutionFunction()`
11399b7cd975SBarry Smith @*/
1140d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetForcingFunction(TS ts, TSForcingFunction func, void *ctx)
1141d71ae5a4SJacob Faibussowitsch {
11429b7cd975SBarry Smith   DM dm;
11439b7cd975SBarry Smith 
11449b7cd975SBarry Smith   PetscFunctionBegin;
11459b7cd975SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
11469566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
11479566063dSJacob Faibussowitsch   PetscCall(DMTSSetForcingFunction(dm, func, ctx));
11483ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
11499b7cd975SBarry Smith }
11509b7cd975SBarry Smith 
1151d763cef2SBarry Smith /*@C
1152f7ab8db6SBarry Smith    TSSetRHSJacobian - Sets the function to compute the Jacobian of G,
1153b5abc632SBarry Smith    where U_t = G(U,t), as well as the location to store the matrix.
1154d763cef2SBarry Smith 
1155c3339decSBarry Smith    Logically Collective
1156d763cef2SBarry Smith 
1157d763cef2SBarry Smith    Input Parameters:
1158bcf0153eSBarry Smith +  ts  - the `TS` context obtained from `TSCreate()`
1159195e9b02SBarry Smith .  Amat - (approximate) location to store Jacobian matrix entries computed by `f`
1160195e9b02SBarry Smith .  Pmat - matrix from which preconditioner is to be constructed (usually the same as `Amat`)
1161d763cef2SBarry Smith .  f   - the Jacobian evaluation routine
1162195e9b02SBarry Smith -  ctx - [optional] user-defined context for private data for the Jacobian evaluation routine (may be `NULL`)
1163d763cef2SBarry Smith 
1164f7ab8db6SBarry Smith    Calling sequence of f:
1165a96d6ef6SBarry Smith $     PetscErrorCode f(TS ts,PetscReal t,Vec u,Mat A,Mat B,void *ctx);
1166d763cef2SBarry Smith 
1167d763cef2SBarry Smith +  t - current timestep
1168d763cef2SBarry Smith .  u - input vector
1169e5d3d808SBarry Smith .  Amat - (approximate) Jacobian matrix
1170195e9b02SBarry Smith .  Pmat - matrix from which preconditioner is to be constructed (usually the same as `Amat`)
1171d763cef2SBarry Smith -  ctx - [optional] user-defined context for matrix evaluation routine
1172d763cef2SBarry Smith 
1173bcf0153eSBarry Smith    Level: beginner
1174bcf0153eSBarry Smith 
11756cd88445SBarry Smith    Notes:
11766cd88445SBarry Smith    You must set all the diagonal entries of the matrices, if they are zero you must still set them with a zero value
11776cd88445SBarry Smith 
1178bcf0153eSBarry Smith    The `TS` solver may modify the nonzero structure and the entries of the matrices Amat and Pmat between the calls to f()
1179ca5f011dSBarry Smith    You should not assume the values are the same in the next call to f() as you set them in the previous call.
1180d763cef2SBarry Smith 
1181bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `SNESComputeJacobianDefaultColor()`, `TSSetRHSFunction()`, `TSRHSJacobianSetReuse()`, `TSSetIJacobian()`
1182d763cef2SBarry Smith @*/
1183d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetRHSJacobian(TS ts, Mat Amat, Mat Pmat, TSRHSJacobian f, void *ctx)
1184d71ae5a4SJacob Faibussowitsch {
1185089b2837SJed Brown   SNES        snes;
118624989b8cSPeter Brune   DM          dm;
118724989b8cSPeter Brune   TSIJacobian ijacobian;
1188277b19d0SLisandro Dalcin 
1189d763cef2SBarry Smith   PetscFunctionBegin;
11900700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
1191e5d3d808SBarry Smith   if (Amat) PetscValidHeaderSpecific(Amat, MAT_CLASSID, 2);
1192e5d3d808SBarry Smith   if (Pmat) PetscValidHeaderSpecific(Pmat, MAT_CLASSID, 3);
1193e5d3d808SBarry Smith   if (Amat) PetscCheckSameComm(ts, 1, Amat, 2);
1194e5d3d808SBarry Smith   if (Pmat) PetscCheckSameComm(ts, 1, Pmat, 3);
1195d763cef2SBarry Smith 
11969566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
11979566063dSJacob Faibussowitsch   PetscCall(DMTSSetRHSJacobian(dm, f, ctx));
11989566063dSJacob Faibussowitsch   PetscCall(DMTSGetIJacobian(dm, &ijacobian, NULL));
11999566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts, &snes));
12001e66621cSBarry Smith   if (!ijacobian) PetscCall(SNESSetJacobian(snes, Amat, Pmat, SNESTSFormJacobian, ts));
1201e5d3d808SBarry Smith   if (Amat) {
12029566063dSJacob Faibussowitsch     PetscCall(PetscObjectReference((PetscObject)Amat));
12039566063dSJacob Faibussowitsch     PetscCall(MatDestroy(&ts->Arhs));
1204e5d3d808SBarry Smith     ts->Arhs = Amat;
12050e4ef248SJed Brown   }
1206e5d3d808SBarry Smith   if (Pmat) {
12079566063dSJacob Faibussowitsch     PetscCall(PetscObjectReference((PetscObject)Pmat));
12089566063dSJacob Faibussowitsch     PetscCall(MatDestroy(&ts->Brhs));
1209e5d3d808SBarry Smith     ts->Brhs = Pmat;
12100e4ef248SJed Brown   }
12113ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1212d763cef2SBarry Smith }
1213d763cef2SBarry Smith 
1214316643e7SJed Brown /*@C
1215b5abc632SBarry Smith    TSSetIFunction - Set the function to compute F(t,U,U_t) where F() = 0 is the DAE to be solved.
1216316643e7SJed Brown 
1217c3339decSBarry Smith    Logically Collective
1218316643e7SJed Brown 
1219316643e7SJed Brown    Input Parameters:
1220bcf0153eSBarry Smith +  ts  - the `TS` context obtained from `TSCreate()`
1221195e9b02SBarry Smith .  r   - vector to hold the residual (or `NULL` to have it created internally)
1222316643e7SJed Brown .  f   - the function evaluation routine
1223195e9b02SBarry Smith -  ctx - user-defined context for private data for the function evaluation routine (may be `NULL`)
1224316643e7SJed Brown 
1225316643e7SJed Brown    Calling sequence of f:
12266bc98fa9SBarry Smith $     PetscErrorCode f(TS ts,PetscReal t,Vec u,Vec u_t,Vec F,ctx);
1227316643e7SJed Brown 
1228316643e7SJed Brown +  t   - time at step/stage being solved
1229316643e7SJed Brown .  u   - state vector
1230316643e7SJed Brown .  u_t - time derivative of state vector
1231316643e7SJed Brown .  F   - function vector
1232316643e7SJed Brown -  ctx - [optional] user-defined context for matrix evaluation routine
1233316643e7SJed Brown 
1234316643e7SJed Brown    Level: beginner
1235316643e7SJed Brown 
1236bcf0153eSBarry Smith    Note:
1237bcf0153eSBarry Smith    The user MUST call either this routine or `TSSetRHSFunction()` to define the ODE.  When solving DAEs you must use this function.
1238bcf0153eSBarry Smith 
1239bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSSetRHSJacobian()`, `TSSetRHSFunction()`, `TSSetIJacobian()`
1240316643e7SJed Brown @*/
1241d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetIFunction(TS ts, Vec r, TSIFunction f, void *ctx)
1242d71ae5a4SJacob Faibussowitsch {
1243089b2837SJed Brown   SNES snes;
124451699248SLisandro Dalcin   Vec  ralloc = NULL;
124524989b8cSPeter Brune   DM   dm;
1246316643e7SJed Brown 
1247316643e7SJed Brown   PetscFunctionBegin;
12480700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
124951699248SLisandro Dalcin   if (r) PetscValidHeaderSpecific(r, VEC_CLASSID, 2);
125024989b8cSPeter Brune 
12519566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
12529566063dSJacob Faibussowitsch   PetscCall(DMTSSetIFunction(dm, f, ctx));
125324989b8cSPeter Brune 
12549566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts, &snes));
125551699248SLisandro Dalcin   if (!r && !ts->dm && ts->vec_sol) {
12569566063dSJacob Faibussowitsch     PetscCall(VecDuplicate(ts->vec_sol, &ralloc));
125751699248SLisandro Dalcin     r = ralloc;
1258e856ceecSJed Brown   }
12599566063dSJacob Faibussowitsch   PetscCall(SNESSetFunction(snes, r, SNESTSFormFunction, ts));
12609566063dSJacob Faibussowitsch   PetscCall(VecDestroy(&ralloc));
12613ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1262089b2837SJed Brown }
1263089b2837SJed Brown 
1264089b2837SJed Brown /*@C
1265a5b23f4aSJose E. Roman    TSGetIFunction - Returns the vector where the implicit residual is stored and the function/context to compute it.
1266089b2837SJed Brown 
1267089b2837SJed Brown    Not Collective
1268089b2837SJed Brown 
1269089b2837SJed Brown    Input Parameter:
1270bcf0153eSBarry Smith .  ts - the `TS` context
1271089b2837SJed Brown 
1272d8d19677SJose E. Roman    Output Parameters:
1273195e9b02SBarry Smith +  r - vector to hold residual (or `NULL`)
1274195e9b02SBarry Smith .  func - the function to compute residual (or `NULL`)
1275195e9b02SBarry Smith -  ctx - the function context (or `NULL`)
1276089b2837SJed Brown 
1277089b2837SJed Brown    Level: advanced
1278089b2837SJed Brown 
1279bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSSetIFunction()`, `SNESGetFunction()`
1280089b2837SJed Brown @*/
1281d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetIFunction(TS ts, Vec *r, TSIFunction *func, void **ctx)
1282d71ae5a4SJacob Faibussowitsch {
1283089b2837SJed Brown   SNES snes;
128424989b8cSPeter Brune   DM   dm;
1285089b2837SJed Brown 
1286089b2837SJed Brown   PetscFunctionBegin;
1287089b2837SJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
12889566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts, &snes));
12899566063dSJacob Faibussowitsch   PetscCall(SNESGetFunction(snes, r, NULL, NULL));
12909566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
12919566063dSJacob Faibussowitsch   PetscCall(DMTSGetIFunction(dm, func, ctx));
12923ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1293089b2837SJed Brown }
1294089b2837SJed Brown 
1295089b2837SJed Brown /*@C
1296089b2837SJed Brown    TSGetRHSFunction - Returns the vector where the right hand side is stored and the function/context to compute it.
1297089b2837SJed Brown 
1298089b2837SJed Brown    Not Collective
1299089b2837SJed Brown 
1300089b2837SJed Brown    Input Parameter:
1301bcf0153eSBarry Smith .  ts - the `TS` context
1302089b2837SJed Brown 
1303d8d19677SJose E. Roman    Output Parameters:
1304195e9b02SBarry Smith +  r - vector to hold computed right hand side (or `NULL`)
1305195e9b02SBarry Smith .  func - the function to compute right hand side (or `NULL`)
1306195e9b02SBarry Smith -  ctx - the function context (or `NULL`)
1307089b2837SJed Brown 
1308089b2837SJed Brown    Level: advanced
1309089b2837SJed Brown 
1310bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSSetRHSFunction()`, `SNESGetFunction()`
1311089b2837SJed Brown @*/
1312d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetRHSFunction(TS ts, Vec *r, TSRHSFunction *func, void **ctx)
1313d71ae5a4SJacob Faibussowitsch {
1314089b2837SJed Brown   SNES snes;
131524989b8cSPeter Brune   DM   dm;
1316089b2837SJed Brown 
1317089b2837SJed Brown   PetscFunctionBegin;
1318089b2837SJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
13199566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts, &snes));
13209566063dSJacob Faibussowitsch   PetscCall(SNESGetFunction(snes, r, NULL, NULL));
13219566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
13229566063dSJacob Faibussowitsch   PetscCall(DMTSGetRHSFunction(dm, func, ctx));
13233ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1324316643e7SJed Brown }
1325316643e7SJed Brown 
1326316643e7SJed Brown /*@C
1327a4f0a591SBarry Smith    TSSetIJacobian - Set the function to compute the matrix dF/dU + a*dF/dU_t where F(t,U,U_t) is the function
1328bcf0153eSBarry Smith         provided with `TSSetIFunction()`.
1329316643e7SJed Brown 
1330c3339decSBarry Smith    Logically Collective
1331316643e7SJed Brown 
1332316643e7SJed Brown    Input Parameters:
1333bcf0153eSBarry Smith +  ts  - the `TS` context obtained from `TSCreate()`
1334195e9b02SBarry Smith .  Amat - (approximate) matrix to store Jacobian entires computed by `f`
1335195e9b02SBarry Smith .  Pmat - matrix used to compute preconditioner (usually the same as `Amat`)
1336316643e7SJed Brown .  f   - the Jacobian evaluation routine
1337195e9b02SBarry Smith -  ctx - user-defined context for private data for the Jacobian evaluation routine (may be `NULL`)
1338316643e7SJed Brown 
1339316643e7SJed Brown    Calling sequence of f:
13406bc98fa9SBarry Smith $    PetscErrorCode f(TS ts,PetscReal t,Vec U,Vec U_t,PetscReal a,Mat Amat,Mat Pmat,void *ctx);
1341316643e7SJed Brown 
1342316643e7SJed Brown +  t    - time at step/stage being solved
13431b4a444bSJed Brown .  U    - state vector
13441b4a444bSJed Brown .  U_t  - time derivative of state vector
1345316643e7SJed Brown .  a    - shift
1346e5d3d808SBarry Smith .  Amat - (approximate) Jacobian of F(t,U,W+a*U), equivalent to dF/dU + a*dF/dU_t
1347195e9b02SBarry Smith .  Pmat - matrix used for constructing preconditioner, usually the same as `Amat`
1348316643e7SJed Brown -  ctx  - [optional] user-defined context for matrix evaluation routine
1349316643e7SJed Brown 
1350bcf0153eSBarry Smith    Level: beginner
1351316643e7SJed Brown 
1352bcf0153eSBarry Smith    Notes:
1353195e9b02SBarry Smith    The matrices `Amat` and `Pmat` are exactly the matrices that are used by `SNES` for the nonlinear solve.
1354bcf0153eSBarry Smith 
1355bcf0153eSBarry Smith    If you know the operator Amat has a null space you can use `MatSetNullSpace()` and `MatSetTransposeNullSpace()` to supply the null
1356195e9b02SBarry Smith    space to `Amat` and the `KSP` solvers will automatically use that null space as needed during the solution process.
1357895c21f2SBarry Smith 
1358a4f0a591SBarry Smith    The matrix dF/dU + a*dF/dU_t you provide turns out to be
1359b5abc632SBarry Smith    the Jacobian of F(t,U,W+a*U) where F(t,U,U_t) = 0 is the DAE to be solved.
1360a4f0a591SBarry Smith    The time integrator internally approximates U_t by W+a*U where the positive "shift"
1361a4f0a591SBarry Smith    a and vector W depend on the integration method, step size, and past states. For example with
1362a4f0a591SBarry Smith    the backward Euler method a = 1/dt and W = -a*U(previous timestep) so
1363a4f0a591SBarry Smith    W + a*U = a*(U - U(previous timestep)) = (U - U(previous timestep))/dt
1364a4f0a591SBarry Smith 
13656cd88445SBarry Smith    You must set all the diagonal entries of the matrices, if they are zero you must still set them with a zero value
13666cd88445SBarry Smith 
1367195e9b02SBarry Smith    The TS solver may modify the nonzero structure and the entries of the matrices `Amat` and `Pmat` between the calls to `f`
1368195e9b02SBarry Smith    You should not assume the values are the same in the next call to `f` as you set them in the previous call.
1369ca5f011dSBarry Smith 
1370bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSSetIFunction()`, `TSSetRHSJacobian()`, `SNESComputeJacobianDefaultColor()`, `SNESComputeJacobianDefault()`, `TSSetRHSFunction()`
1371316643e7SJed Brown @*/
1372d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetIJacobian(TS ts, Mat Amat, Mat Pmat, TSIJacobian f, void *ctx)
1373d71ae5a4SJacob Faibussowitsch {
1374089b2837SJed Brown   SNES snes;
137524989b8cSPeter Brune   DM   dm;
1376316643e7SJed Brown 
1377316643e7SJed Brown   PetscFunctionBegin;
13780700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
1379e5d3d808SBarry Smith   if (Amat) PetscValidHeaderSpecific(Amat, MAT_CLASSID, 2);
1380e5d3d808SBarry Smith   if (Pmat) PetscValidHeaderSpecific(Pmat, MAT_CLASSID, 3);
1381e5d3d808SBarry Smith   if (Amat) PetscCheckSameComm(ts, 1, Amat, 2);
1382e5d3d808SBarry Smith   if (Pmat) PetscCheckSameComm(ts, 1, Pmat, 3);
138324989b8cSPeter Brune 
13849566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
13859566063dSJacob Faibussowitsch   PetscCall(DMTSSetIJacobian(dm, f, ctx));
138624989b8cSPeter Brune 
13879566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts, &snes));
13889566063dSJacob Faibussowitsch   PetscCall(SNESSetJacobian(snes, Amat, Pmat, SNESTSFormJacobian, ts));
13893ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1390316643e7SJed Brown }
1391316643e7SJed Brown 
1392e1244c69SJed Brown /*@
1393bcf0153eSBarry Smith    TSRHSJacobianSetReuse - restore RHS Jacobian before re-evaluating.  Without this flag, `TS` will change the sign and
1394e1244c69SJed Brown    shift the RHS Jacobian for a finite-time-step implicit solve, in which case the user function will need to recompute
1395e1244c69SJed Brown    the entire Jacobian.  The reuse flag must be set if the evaluation function will assume that the matrix entries have
1396195e9b02SBarry Smith    not been changed by the `TS`.
1397e1244c69SJed Brown 
1398e1244c69SJed Brown    Logically Collective
1399e1244c69SJed Brown 
14004165533cSJose E. Roman    Input Parameters:
1401bcf0153eSBarry Smith +  ts - `TS` context obtained from `TSCreate()`
1402bcf0153eSBarry Smith -  reuse - `PETSC_TRUE` if the RHS Jacobian
1403e1244c69SJed Brown 
1404e1244c69SJed Brown    Level: intermediate
1405e1244c69SJed Brown 
1406bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSSetRHSJacobian()`, `TSComputeRHSJacobianConstant()`
1407e1244c69SJed Brown @*/
1408d71ae5a4SJacob Faibussowitsch PetscErrorCode TSRHSJacobianSetReuse(TS ts, PetscBool reuse)
1409d71ae5a4SJacob Faibussowitsch {
1410e1244c69SJed Brown   PetscFunctionBegin;
1411e1244c69SJed Brown   ts->rhsjacobian.reuse = reuse;
14123ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1413e1244c69SJed Brown }
1414e1244c69SJed Brown 
1415efe9872eSLisandro Dalcin /*@C
1416efe9872eSLisandro Dalcin    TSSetI2Function - Set the function to compute F(t,U,U_t,U_tt) where F = 0 is the DAE to be solved.
1417efe9872eSLisandro Dalcin 
1418c3339decSBarry Smith    Logically Collective
1419efe9872eSLisandro Dalcin 
1420efe9872eSLisandro Dalcin    Input Parameters:
1421bcf0153eSBarry Smith +  ts  - the `TS` context obtained from `TSCreate()`
1422195e9b02SBarry Smith .  F   - vector to hold the residual (or `NULL` to have it created internally)
1423efe9872eSLisandro Dalcin .  fun - the function evaluation routine
1424195e9b02SBarry Smith -  ctx - user-defined context for private data for the function evaluation routine (may be `NULL`)
1425efe9872eSLisandro Dalcin 
1426efe9872eSLisandro Dalcin    Calling sequence of fun:
14276bc98fa9SBarry Smith $     PetscErrorCode fun(TS ts,PetscReal t,Vec U,Vec U_t,Vec U_tt,Vec F,ctx);
1428efe9872eSLisandro Dalcin 
1429efe9872eSLisandro Dalcin +  t    - time at step/stage being solved
1430efe9872eSLisandro Dalcin .  U    - state vector
1431efe9872eSLisandro Dalcin .  U_t  - time derivative of state vector
1432efe9872eSLisandro Dalcin .  U_tt - second time derivative of state vector
1433efe9872eSLisandro Dalcin .  F    - function vector
1434195e9b02SBarry Smith -  ctx  - [optional] user-defined context for matrix evaluation routine (may be `NULL`)
1435efe9872eSLisandro Dalcin 
1436efe9872eSLisandro Dalcin    Level: beginner
1437efe9872eSLisandro Dalcin 
1438bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSSetI2Jacobian()`, `TSSetIFunction()`, `TSCreate()`, `TSSetRHSFunction()`
1439efe9872eSLisandro Dalcin @*/
1440d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetI2Function(TS ts, Vec F, TSI2Function fun, void *ctx)
1441d71ae5a4SJacob Faibussowitsch {
1442efe9872eSLisandro Dalcin   DM dm;
1443efe9872eSLisandro Dalcin 
1444efe9872eSLisandro Dalcin   PetscFunctionBegin;
1445efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
1446efe9872eSLisandro Dalcin   if (F) PetscValidHeaderSpecific(F, VEC_CLASSID, 2);
14479566063dSJacob Faibussowitsch   PetscCall(TSSetIFunction(ts, F, NULL, NULL));
14489566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
14499566063dSJacob Faibussowitsch   PetscCall(DMTSSetI2Function(dm, fun, ctx));
14503ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1451efe9872eSLisandro Dalcin }
1452efe9872eSLisandro Dalcin 
1453efe9872eSLisandro Dalcin /*@C
1454a5b23f4aSJose E. Roman   TSGetI2Function - Returns the vector where the implicit residual is stored and the function/context to compute it.
1455efe9872eSLisandro Dalcin 
1456efe9872eSLisandro Dalcin   Not Collective
1457efe9872eSLisandro Dalcin 
1458efe9872eSLisandro Dalcin   Input Parameter:
1459bcf0153eSBarry Smith . ts - the `TS` context
1460efe9872eSLisandro Dalcin 
1461d8d19677SJose E. Roman   Output Parameters:
1462195e9b02SBarry Smith + r - vector to hold residual (or `NULL`)
1463195e9b02SBarry Smith . fun - the function to compute residual (or `NULL`)
1464195e9b02SBarry Smith - ctx - the function context (or `NULL`)
1465efe9872eSLisandro Dalcin 
1466efe9872eSLisandro Dalcin   Level: advanced
1467efe9872eSLisandro Dalcin 
1468bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSSetIFunction()`, `SNESGetFunction()`, `TSCreate()`
1469efe9872eSLisandro Dalcin @*/
1470d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetI2Function(TS ts, Vec *r, TSI2Function *fun, void **ctx)
1471d71ae5a4SJacob Faibussowitsch {
1472efe9872eSLisandro Dalcin   SNES snes;
1473efe9872eSLisandro Dalcin   DM   dm;
1474efe9872eSLisandro Dalcin 
1475efe9872eSLisandro Dalcin   PetscFunctionBegin;
1476efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
14779566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts, &snes));
14789566063dSJacob Faibussowitsch   PetscCall(SNESGetFunction(snes, r, NULL, NULL));
14799566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
14809566063dSJacob Faibussowitsch   PetscCall(DMTSGetI2Function(dm, fun, ctx));
14813ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1482efe9872eSLisandro Dalcin }
1483efe9872eSLisandro Dalcin 
1484efe9872eSLisandro Dalcin /*@C
1485bc77d74cSLisandro Dalcin    TSSetI2Jacobian - Set the function to compute the matrix dF/dU + v*dF/dU_t  + a*dF/dU_tt
1486bcf0153eSBarry Smith         where F(t,U,U_t,U_tt) is the function you provided with `TSSetI2Function()`.
1487efe9872eSLisandro Dalcin 
1488c3339decSBarry Smith    Logically Collective
1489efe9872eSLisandro Dalcin 
1490efe9872eSLisandro Dalcin    Input Parameters:
1491bcf0153eSBarry Smith +  ts  - the `TS` context obtained from `TSCreate()`
1492195e9b02SBarry Smith .  J   - matrix to hold the Jacobian values
1493195e9b02SBarry Smith .  P   - matrix for constructing the preconditioner (may be same as `J`)
1494efe9872eSLisandro Dalcin .  jac - the Jacobian evaluation routine
1495195e9b02SBarry Smith -  ctx - user-defined context for private data for the Jacobian evaluation routine (may be `NULL`)
1496efe9872eSLisandro Dalcin 
1497efe9872eSLisandro Dalcin    Calling sequence of jac:
14986bc98fa9SBarry Smith $    PetscErrorCode jac(TS ts,PetscReal t,Vec U,Vec U_t,Vec U_tt,PetscReal v,PetscReal a,Mat J,Mat P,void *ctx);
1499efe9872eSLisandro Dalcin 
1500efe9872eSLisandro Dalcin +  t    - time at step/stage being solved
1501efe9872eSLisandro Dalcin .  U    - state vector
1502efe9872eSLisandro Dalcin .  U_t  - time derivative of state vector
1503efe9872eSLisandro Dalcin .  U_tt - second time derivative of state vector
1504efe9872eSLisandro Dalcin .  v    - shift for U_t
1505efe9872eSLisandro Dalcin .  a    - shift for U_tt
1506efe9872eSLisandro Dalcin .  J    - Jacobian of G(U) = F(t,U,W+v*U,W'+a*U), equivalent to dF/dU + v*dF/dU_t  + a*dF/dU_tt
1507efe9872eSLisandro Dalcin .  P    - preconditioning matrix for J, may be same as J
1508efe9872eSLisandro Dalcin -  ctx  - [optional] user-defined context for matrix evaluation routine
1509efe9872eSLisandro Dalcin 
1510bcf0153eSBarry Smith    Level: beginner
1511bcf0153eSBarry Smith 
1512efe9872eSLisandro Dalcin    Notes:
1513195e9b02SBarry Smith    The matrices `J` and `P` are exactly the matrices that are used by `SNES` for the nonlinear solve.
1514efe9872eSLisandro Dalcin 
1515efe9872eSLisandro Dalcin    The matrix dF/dU + v*dF/dU_t + a*dF/dU_tt you provide turns out to be
1516efe9872eSLisandro Dalcin    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.
1517efe9872eSLisandro Dalcin    The time integrator internally approximates U_t by W+v*U and U_tt by W'+a*U  where the positive "shift"
1518bc77d74cSLisandro Dalcin    parameters 'v' and 'a' and vectors W, W' depend on the integration method, step size, and past states.
1519efe9872eSLisandro Dalcin 
1520bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSSetI2Function()`, `TSGetI2Jacobian()`
1521efe9872eSLisandro Dalcin @*/
1522d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetI2Jacobian(TS ts, Mat J, Mat P, TSI2Jacobian jac, void *ctx)
1523d71ae5a4SJacob Faibussowitsch {
1524efe9872eSLisandro Dalcin   DM dm;
1525efe9872eSLisandro Dalcin 
1526efe9872eSLisandro Dalcin   PetscFunctionBegin;
1527efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
1528efe9872eSLisandro Dalcin   if (J) PetscValidHeaderSpecific(J, MAT_CLASSID, 2);
1529efe9872eSLisandro Dalcin   if (P) PetscValidHeaderSpecific(P, MAT_CLASSID, 3);
15309566063dSJacob Faibussowitsch   PetscCall(TSSetIJacobian(ts, J, P, NULL, NULL));
15319566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
15329566063dSJacob Faibussowitsch   PetscCall(DMTSSetI2Jacobian(dm, jac, ctx));
15333ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1534efe9872eSLisandro Dalcin }
1535efe9872eSLisandro Dalcin 
1536efe9872eSLisandro Dalcin /*@C
1537efe9872eSLisandro Dalcin   TSGetI2Jacobian - Returns the implicit Jacobian at the present timestep.
1538efe9872eSLisandro Dalcin 
1539bcf0153eSBarry Smith   Not Collective, but parallel objects are returned if `TS` is parallel
1540efe9872eSLisandro Dalcin 
1541efe9872eSLisandro Dalcin   Input Parameter:
1542bcf0153eSBarry Smith . ts  - The `TS` context obtained from `TSCreate()`
1543efe9872eSLisandro Dalcin 
1544efe9872eSLisandro Dalcin   Output Parameters:
1545efe9872eSLisandro Dalcin + J  - The (approximate) Jacobian of F(t,U,U_t,U_tt)
1546195e9b02SBarry Smith . P - The matrix from which the preconditioner is constructed, often the same as `J`
1547efe9872eSLisandro Dalcin . jac - The function to compute the Jacobian matrices
1548efe9872eSLisandro Dalcin - ctx - User-defined context for Jacobian evaluation routine
1549efe9872eSLisandro Dalcin 
1550bcf0153eSBarry Smith   Level: advanced
1551bcf0153eSBarry Smith 
1552195e9b02SBarry Smith   Note:
1553195e9b02SBarry Smith     You can pass in `NULL` for any return argument you do not need.
1554efe9872eSLisandro Dalcin 
1555bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSGetTimeStep()`, `TSGetMatrices()`, `TSGetTime()`, `TSGetStepNumber()`, `TSSetI2Jacobian()`, `TSGetI2Function()`, `TSCreate()`
1556efe9872eSLisandro Dalcin @*/
1557d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetI2Jacobian(TS ts, Mat *J, Mat *P, TSI2Jacobian *jac, void **ctx)
1558d71ae5a4SJacob Faibussowitsch {
1559efe9872eSLisandro Dalcin   SNES snes;
1560efe9872eSLisandro Dalcin   DM   dm;
1561efe9872eSLisandro Dalcin 
1562efe9872eSLisandro Dalcin   PetscFunctionBegin;
15639566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts, &snes));
15649566063dSJacob Faibussowitsch   PetscCall(SNESSetUpMatrices(snes));
15659566063dSJacob Faibussowitsch   PetscCall(SNESGetJacobian(snes, J, P, NULL, NULL));
15669566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
15679566063dSJacob Faibussowitsch   PetscCall(DMTSGetI2Jacobian(dm, jac, ctx));
15683ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1569efe9872eSLisandro Dalcin }
1570efe9872eSLisandro Dalcin 
1571efe9872eSLisandro Dalcin /*@
1572efe9872eSLisandro Dalcin   TSComputeI2Function - Evaluates the DAE residual written in implicit form F(t,U,U_t,U_tt) = 0
1573efe9872eSLisandro Dalcin 
1574c3339decSBarry Smith   Collective
1575efe9872eSLisandro Dalcin 
1576efe9872eSLisandro Dalcin   Input Parameters:
1577bcf0153eSBarry Smith + ts - the `TS` context
1578efe9872eSLisandro Dalcin . t - current time
1579efe9872eSLisandro Dalcin . U - state vector
1580efe9872eSLisandro Dalcin . V - time derivative of state vector (U_t)
1581efe9872eSLisandro Dalcin - A - second time derivative of state vector (U_tt)
1582efe9872eSLisandro Dalcin 
1583efe9872eSLisandro Dalcin   Output Parameter:
1584efe9872eSLisandro Dalcin . F - the residual vector
1585efe9872eSLisandro Dalcin 
1586bcf0153eSBarry Smith   Level: developer
1587bcf0153eSBarry Smith 
1588efe9872eSLisandro Dalcin   Note:
1589efe9872eSLisandro Dalcin   Most users should not need to explicitly call this routine, as it
1590efe9872eSLisandro Dalcin   is used internally within the nonlinear solvers.
1591efe9872eSLisandro Dalcin 
1592bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSSetI2Function()`, `TSGetI2Function()`
1593efe9872eSLisandro Dalcin @*/
1594d71ae5a4SJacob Faibussowitsch PetscErrorCode TSComputeI2Function(TS ts, PetscReal t, Vec U, Vec V, Vec A, Vec F)
1595d71ae5a4SJacob Faibussowitsch {
1596efe9872eSLisandro Dalcin   DM            dm;
1597efe9872eSLisandro Dalcin   TSI2Function  I2Function;
1598efe9872eSLisandro Dalcin   void         *ctx;
1599efe9872eSLisandro Dalcin   TSRHSFunction rhsfunction;
1600efe9872eSLisandro Dalcin 
1601efe9872eSLisandro Dalcin   PetscFunctionBegin;
1602efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
1603efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(U, VEC_CLASSID, 3);
1604efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(V, VEC_CLASSID, 4);
1605efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(A, VEC_CLASSID, 5);
1606efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(F, VEC_CLASSID, 6);
1607efe9872eSLisandro Dalcin 
16089566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
16099566063dSJacob Faibussowitsch   PetscCall(DMTSGetI2Function(dm, &I2Function, &ctx));
16109566063dSJacob Faibussowitsch   PetscCall(DMTSGetRHSFunction(dm, &rhsfunction, NULL));
1611efe9872eSLisandro Dalcin 
1612efe9872eSLisandro Dalcin   if (!I2Function) {
16139566063dSJacob Faibussowitsch     PetscCall(TSComputeIFunction(ts, t, U, A, F, PETSC_FALSE));
16143ba16761SJacob Faibussowitsch     PetscFunctionReturn(PETSC_SUCCESS);
1615efe9872eSLisandro Dalcin   }
1616efe9872eSLisandro Dalcin 
16179566063dSJacob Faibussowitsch   PetscCall(PetscLogEventBegin(TS_FunctionEval, ts, U, V, F));
1618efe9872eSLisandro Dalcin 
1619792fecdfSBarry Smith   PetscCallBack("TS callback implicit function", I2Function(ts, t, U, V, A, F, ctx));
1620efe9872eSLisandro Dalcin 
1621efe9872eSLisandro Dalcin   if (rhsfunction) {
1622efe9872eSLisandro Dalcin     Vec Frhs;
16239566063dSJacob Faibussowitsch     PetscCall(TSGetRHSVec_Private(ts, &Frhs));
16249566063dSJacob Faibussowitsch     PetscCall(TSComputeRHSFunction(ts, t, U, Frhs));
16259566063dSJacob Faibussowitsch     PetscCall(VecAXPY(F, -1, Frhs));
1626efe9872eSLisandro Dalcin   }
1627efe9872eSLisandro Dalcin 
16289566063dSJacob Faibussowitsch   PetscCall(PetscLogEventEnd(TS_FunctionEval, ts, U, V, F));
16293ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1630efe9872eSLisandro Dalcin }
1631efe9872eSLisandro Dalcin 
1632efe9872eSLisandro Dalcin /*@
1633efe9872eSLisandro Dalcin   TSComputeI2Jacobian - Evaluates the Jacobian of the DAE
1634efe9872eSLisandro Dalcin 
1635c3339decSBarry Smith   Collective
1636efe9872eSLisandro Dalcin 
1637efe9872eSLisandro Dalcin   Input Parameters:
1638bcf0153eSBarry Smith + ts - the `TS` context
1639efe9872eSLisandro Dalcin . t - current timestep
1640efe9872eSLisandro Dalcin . U - state vector
1641efe9872eSLisandro Dalcin . V - time derivative of state vector
1642efe9872eSLisandro Dalcin . A - second time derivative of state vector
1643efe9872eSLisandro Dalcin . shiftV - shift to apply, see note below
1644efe9872eSLisandro Dalcin - shiftA - shift to apply, see note below
1645efe9872eSLisandro Dalcin 
1646efe9872eSLisandro Dalcin   Output Parameters:
1647efe9872eSLisandro Dalcin + J - Jacobian matrix
1648efe9872eSLisandro Dalcin - P - optional preconditioning matrix
1649efe9872eSLisandro Dalcin 
1650bcf0153eSBarry Smith   Level: developer
1651bcf0153eSBarry Smith 
1652efe9872eSLisandro Dalcin   Notes:
1653efe9872eSLisandro Dalcin   If F(t,U,V,A)=0 is the DAE, the required Jacobian is
1654efe9872eSLisandro Dalcin 
1655efe9872eSLisandro Dalcin   dF/dU + shiftV*dF/dV + shiftA*dF/dA
1656efe9872eSLisandro Dalcin 
1657efe9872eSLisandro Dalcin   Most users should not need to explicitly call this routine, as it
1658efe9872eSLisandro Dalcin   is used internally within the nonlinear solvers.
1659efe9872eSLisandro Dalcin 
1660bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSSetI2Jacobian()`
1661efe9872eSLisandro Dalcin @*/
1662d71ae5a4SJacob Faibussowitsch PetscErrorCode TSComputeI2Jacobian(TS ts, PetscReal t, Vec U, Vec V, Vec A, PetscReal shiftV, PetscReal shiftA, Mat J, Mat P)
1663d71ae5a4SJacob Faibussowitsch {
1664efe9872eSLisandro Dalcin   DM            dm;
1665efe9872eSLisandro Dalcin   TSI2Jacobian  I2Jacobian;
1666efe9872eSLisandro Dalcin   void         *ctx;
1667efe9872eSLisandro Dalcin   TSRHSJacobian rhsjacobian;
1668efe9872eSLisandro Dalcin 
1669efe9872eSLisandro Dalcin   PetscFunctionBegin;
1670efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
1671efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(U, VEC_CLASSID, 3);
1672efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(V, VEC_CLASSID, 4);
1673efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(A, VEC_CLASSID, 5);
1674efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(J, MAT_CLASSID, 8);
1675efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(P, MAT_CLASSID, 9);
1676efe9872eSLisandro Dalcin 
16779566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
16789566063dSJacob Faibussowitsch   PetscCall(DMTSGetI2Jacobian(dm, &I2Jacobian, &ctx));
16799566063dSJacob Faibussowitsch   PetscCall(DMTSGetRHSJacobian(dm, &rhsjacobian, NULL));
1680efe9872eSLisandro Dalcin 
1681efe9872eSLisandro Dalcin   if (!I2Jacobian) {
16829566063dSJacob Faibussowitsch     PetscCall(TSComputeIJacobian(ts, t, U, A, shiftA, J, P, PETSC_FALSE));
16833ba16761SJacob Faibussowitsch     PetscFunctionReturn(PETSC_SUCCESS);
1684efe9872eSLisandro Dalcin   }
1685efe9872eSLisandro Dalcin 
16869566063dSJacob Faibussowitsch   PetscCall(PetscLogEventBegin(TS_JacobianEval, ts, U, J, P));
1687792fecdfSBarry Smith   PetscCallBack("TS callback implicit Jacobian", I2Jacobian(ts, t, U, V, A, shiftV, shiftA, J, P, ctx));
1688efe9872eSLisandro Dalcin   if (rhsjacobian) {
1689d60b7d5cSBarry Smith     Mat Jrhs, Prhs;
16909566063dSJacob Faibussowitsch     PetscCall(TSGetRHSMats_Private(ts, &Jrhs, &Prhs));
16919566063dSJacob Faibussowitsch     PetscCall(TSComputeRHSJacobian(ts, t, U, Jrhs, Prhs));
16929566063dSJacob Faibussowitsch     PetscCall(MatAXPY(J, -1, Jrhs, ts->axpy_pattern));
16939566063dSJacob Faibussowitsch     if (P != J) PetscCall(MatAXPY(P, -1, Prhs, ts->axpy_pattern));
1694efe9872eSLisandro Dalcin   }
1695efe9872eSLisandro Dalcin 
16969566063dSJacob Faibussowitsch   PetscCall(PetscLogEventEnd(TS_JacobianEval, ts, U, J, P));
16973ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1698efe9872eSLisandro Dalcin }
1699efe9872eSLisandro Dalcin 
1700438f35afSJed Brown /*@C
1701438f35afSJed Brown    TSSetTransientVariable - sets function to transform from state to transient variables
1702438f35afSJed Brown 
1703438f35afSJed Brown    Logically Collective
1704438f35afSJed Brown 
17054165533cSJose E. Roman    Input Parameters:
1706438f35afSJed Brown +  ts - time stepping context on which to change the transient variable
1707a96d6ef6SBarry Smith .  tvar - a function that transforms to transient variables
1708438f35afSJed Brown -  ctx - a context for tvar
1709438f35afSJed Brown 
1710a96d6ef6SBarry Smith     Calling sequence of tvar:
1711a96d6ef6SBarry Smith $     PetscErrorCode tvar(TS ts,Vec p,Vec c,void *ctx);
1712a96d6ef6SBarry Smith 
1713a96d6ef6SBarry Smith +   ts - timestep context
17146aad120cSJose E. Roman .   p - input vector (primitive form)
1715a96d6ef6SBarry Smith .   c - output vector, transient variables (conservative form)
1716a96d6ef6SBarry Smith -   ctx - [optional] user-defined function context
1717a96d6ef6SBarry Smith 
1718438f35afSJed Brown    Level: advanced
1719438f35afSJed Brown 
1720438f35afSJed Brown    Notes:
1721bcf0153eSBarry Smith    This is typically used to transform from primitive to conservative variables so that a time integrator (e.g., `TSBDF`)
1722438f35afSJed Brown    can be conservative.  In this context, primitive variables P are used to model the state (e.g., because they lead to
1723438f35afSJed Brown    well-conditioned formulations even in limiting cases such as low-Mach or zero porosity).  The transient variable is
1724438f35afSJed Brown    C(P), specified by calling this function.  An IFunction thus receives arguments (P, Cdot) and the IJacobian must be
1725438f35afSJed Brown    evaluated via the chain rule, as in
1726195e9b02SBarry Smith .vb
1727438f35afSJed Brown      dF/dP + shift * dF/dCdot dC/dP.
1728195e9b02SBarry Smith .ve
1729438f35afSJed Brown 
1730bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSBDF`, `DMTSSetTransientVariable()`, `DMTSGetTransientVariable()`, `TSSetIFunction()`, `TSSetIJacobian()`
1731438f35afSJed Brown @*/
1732d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetTransientVariable(TS ts, TSTransientVariable tvar, void *ctx)
1733d71ae5a4SJacob Faibussowitsch {
1734438f35afSJed Brown   DM dm;
1735438f35afSJed Brown 
1736438f35afSJed Brown   PetscFunctionBegin;
1737438f35afSJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
17389566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
17399566063dSJacob Faibussowitsch   PetscCall(DMTSSetTransientVariable(dm, tvar, ctx));
17403ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1741438f35afSJed Brown }
1742438f35afSJed Brown 
1743efe9872eSLisandro Dalcin /*@
1744e3c11fc1SJed Brown    TSComputeTransientVariable - transforms state (primitive) variables to transient (conservative) variables
1745e3c11fc1SJed Brown 
1746e3c11fc1SJed Brown    Logically Collective
1747e3c11fc1SJed Brown 
1748e3c11fc1SJed Brown    Input Parameters:
1749e3c11fc1SJed Brown +  ts - TS on which to compute
1750e3c11fc1SJed Brown -  U - state vector to be transformed to transient variables
1751e3c11fc1SJed Brown 
1752e3c11fc1SJed Brown    Output Parameters:
1753e3c11fc1SJed Brown .  C - transient (conservative) variable
1754e3c11fc1SJed Brown 
1755e3c11fc1SJed Brown    Level: developer
1756e3c11fc1SJed Brown 
1757bcf0153eSBarry Smith    Developer Note:
1758195e9b02SBarry Smith    If `DMTSSetTransientVariable()` has not been called, then C is not modified in this routine and C = `NULL` is allowed.
1759bcf0153eSBarry Smith    This makes it safe to call without a guard.  One can use `TSHasTransientVariable()` to check if transient variables are
1760bcf0153eSBarry Smith    being used.
1761bcf0153eSBarry Smith 
1762bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSBDF`, `DMTSSetTransientVariable()`, `TSComputeIFunction()`, `TSComputeIJacobian()`
1763e3c11fc1SJed Brown @*/
1764d71ae5a4SJacob Faibussowitsch PetscErrorCode TSComputeTransientVariable(TS ts, Vec U, Vec C)
1765d71ae5a4SJacob Faibussowitsch {
1766e3c11fc1SJed Brown   DM   dm;
1767e3c11fc1SJed Brown   DMTS dmts;
1768e3c11fc1SJed Brown 
1769e3c11fc1SJed Brown   PetscFunctionBegin;
1770e3c11fc1SJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
1771e3c11fc1SJed Brown   PetscValidHeaderSpecific(U, VEC_CLASSID, 2);
17729566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
17739566063dSJacob Faibussowitsch   PetscCall(DMGetDMTS(dm, &dmts));
1774e3c11fc1SJed Brown   if (dmts->ops->transientvar) {
1775e3c11fc1SJed Brown     PetscValidHeaderSpecific(C, VEC_CLASSID, 3);
17769566063dSJacob Faibussowitsch     PetscCall((*dmts->ops->transientvar)(ts, U, C, dmts->transientvarctx));
1777e3c11fc1SJed Brown   }
17783ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1779e3c11fc1SJed Brown }
1780e3c11fc1SJed Brown 
1781e3c11fc1SJed Brown /*@
1782e3c11fc1SJed Brown    TSHasTransientVariable - determine whether transient variables have been set
1783e3c11fc1SJed Brown 
1784e3c11fc1SJed Brown    Logically Collective
1785e3c11fc1SJed Brown 
1786e3c11fc1SJed Brown    Input Parameters:
1787195e9b02SBarry Smith .  ts - `TS` on which to compute
1788e3c11fc1SJed Brown 
1789e3c11fc1SJed Brown    Output Parameters:
1790bcf0153eSBarry Smith .  has - `PETSC_TRUE` if transient variables have been set
1791e3c11fc1SJed Brown 
1792e3c11fc1SJed Brown    Level: developer
1793e3c11fc1SJed Brown 
1794bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSBDF`, `DMTSSetTransientVariable()`, `TSComputeTransientVariable()`
1795e3c11fc1SJed Brown @*/
1796d71ae5a4SJacob Faibussowitsch PetscErrorCode TSHasTransientVariable(TS ts, PetscBool *has)
1797d71ae5a4SJacob Faibussowitsch {
1798e3c11fc1SJed Brown   DM   dm;
1799e3c11fc1SJed Brown   DMTS dmts;
1800e3c11fc1SJed Brown 
1801e3c11fc1SJed Brown   PetscFunctionBegin;
1802e3c11fc1SJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
18039566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
18049566063dSJacob Faibussowitsch   PetscCall(DMGetDMTS(dm, &dmts));
1805e3c11fc1SJed Brown   *has = dmts->ops->transientvar ? PETSC_TRUE : PETSC_FALSE;
18063ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1807e3c11fc1SJed Brown }
1808e3c11fc1SJed Brown 
1809e3c11fc1SJed Brown /*@
1810efe9872eSLisandro Dalcin    TS2SetSolution - Sets the initial solution and time derivative vectors
1811bcf0153eSBarry Smith    for use by the `TS` routines handling second order equations.
1812efe9872eSLisandro Dalcin 
1813c3339decSBarry Smith    Logically Collective
1814efe9872eSLisandro Dalcin 
1815efe9872eSLisandro Dalcin    Input Parameters:
1816bcf0153eSBarry Smith +  ts - the `TS` context obtained from `TSCreate()`
1817efe9872eSLisandro Dalcin .  u - the solution vector
1818efe9872eSLisandro Dalcin -  v - the time derivative vector
1819efe9872eSLisandro Dalcin 
1820efe9872eSLisandro Dalcin    Level: beginner
1821efe9872eSLisandro Dalcin 
1822bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`
1823efe9872eSLisandro Dalcin @*/
1824d71ae5a4SJacob Faibussowitsch PetscErrorCode TS2SetSolution(TS ts, Vec u, Vec v)
1825d71ae5a4SJacob Faibussowitsch {
1826efe9872eSLisandro Dalcin   PetscFunctionBegin;
1827efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
1828efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(u, VEC_CLASSID, 2);
1829efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(v, VEC_CLASSID, 3);
18309566063dSJacob Faibussowitsch   PetscCall(TSSetSolution(ts, u));
18319566063dSJacob Faibussowitsch   PetscCall(PetscObjectReference((PetscObject)v));
18329566063dSJacob Faibussowitsch   PetscCall(VecDestroy(&ts->vec_dot));
1833efe9872eSLisandro Dalcin   ts->vec_dot = v;
18343ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1835efe9872eSLisandro Dalcin }
1836efe9872eSLisandro Dalcin 
1837efe9872eSLisandro Dalcin /*@
1838efe9872eSLisandro Dalcin    TS2GetSolution - Returns the solution and time derivative at the present timestep
1839efe9872eSLisandro Dalcin    for second order equations. It is valid to call this routine inside the function
1840efe9872eSLisandro Dalcin    that you are evaluating in order to move to the new timestep. This vector not
1841efe9872eSLisandro Dalcin    changed until the solution at the next timestep has been calculated.
1842efe9872eSLisandro Dalcin 
1843195e9b02SBarry Smith    Not Collective, but `u` returned is parallel if `TS` is parallel
1844efe9872eSLisandro Dalcin 
1845efe9872eSLisandro Dalcin    Input Parameter:
1846bcf0153eSBarry Smith .  ts - the `TS` context obtained from `TSCreate()`
1847efe9872eSLisandro Dalcin 
1848d8d19677SJose E. Roman    Output Parameters:
1849efe9872eSLisandro Dalcin +  u - the vector containing the solution
1850efe9872eSLisandro Dalcin -  v - the vector containing the time derivative
1851efe9872eSLisandro Dalcin 
1852efe9872eSLisandro Dalcin    Level: intermediate
1853efe9872eSLisandro Dalcin 
1854bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TS2SetSolution()`, `TSGetTimeStep()`, `TSGetTime()`
1855efe9872eSLisandro Dalcin @*/
1856d71ae5a4SJacob Faibussowitsch PetscErrorCode TS2GetSolution(TS ts, Vec *u, Vec *v)
1857d71ae5a4SJacob Faibussowitsch {
1858efe9872eSLisandro Dalcin   PetscFunctionBegin;
1859efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
1860efe9872eSLisandro Dalcin   if (u) PetscValidPointer(u, 2);
1861efe9872eSLisandro Dalcin   if (v) PetscValidPointer(v, 3);
1862efe9872eSLisandro Dalcin   if (u) *u = ts->vec_sol;
1863efe9872eSLisandro Dalcin   if (v) *v = ts->vec_dot;
18643ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1865efe9872eSLisandro Dalcin }
1866efe9872eSLisandro Dalcin 
186755849f57SBarry Smith /*@C
1868bcf0153eSBarry Smith   TSLoad - Loads a `TS` that has been stored in binary  with `TSView()`.
186955849f57SBarry Smith 
1870c3339decSBarry Smith   Collective
187155849f57SBarry Smith 
187255849f57SBarry Smith   Input Parameters:
1873bcf0153eSBarry Smith + newdm - the newly loaded `TS`, this needs to have been created with `TSCreate()` or
1874bcf0153eSBarry Smith            some related function before a call to `TSLoad()`.
1875bcf0153eSBarry Smith - viewer - binary file viewer, obtained from `PetscViewerBinaryOpen()`
187655849f57SBarry Smith 
187755849f57SBarry Smith    Level: intermediate
187855849f57SBarry Smith 
1879bcf0153eSBarry Smith   Note:
1880bcf0153eSBarry Smith  The type is determined by the data in the file, any type set into the `TS` before this call is ignored.
188155849f57SBarry Smith 
1882bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `PetscViewer`, `PetscViewerBinaryOpen()`, `TSView()`, `MatLoad()`, `VecLoad()`
188355849f57SBarry Smith @*/
1884d71ae5a4SJacob Faibussowitsch PetscErrorCode TSLoad(TS ts, PetscViewer viewer)
1885d71ae5a4SJacob Faibussowitsch {
188655849f57SBarry Smith   PetscBool isbinary;
188755849f57SBarry Smith   PetscInt  classid;
188855849f57SBarry Smith   char      type[256];
18892d53ad75SBarry Smith   DMTS      sdm;
1890ad6bc421SBarry Smith   DM        dm;
189155849f57SBarry Smith 
189255849f57SBarry Smith   PetscFunctionBegin;
1893f2c2a1b9SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
189455849f57SBarry Smith   PetscValidHeaderSpecific(viewer, PETSC_VIEWER_CLASSID, 2);
18959566063dSJacob Faibussowitsch   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERBINARY, &isbinary));
18963c633725SBarry Smith   PetscCheck(isbinary, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Invalid viewer; open viewer with PetscViewerBinaryOpen()");
189755849f57SBarry Smith 
18989566063dSJacob Faibussowitsch   PetscCall(PetscViewerBinaryRead(viewer, &classid, 1, NULL, PETSC_INT));
18993c633725SBarry Smith   PetscCheck(classid == TS_FILE_CLASSID, PetscObjectComm((PetscObject)ts), PETSC_ERR_ARG_WRONG, "Not TS next in file");
19009566063dSJacob Faibussowitsch   PetscCall(PetscViewerBinaryRead(viewer, type, 256, NULL, PETSC_CHAR));
19019566063dSJacob Faibussowitsch   PetscCall(TSSetType(ts, type));
1902dbbe0bcdSBarry Smith   PetscTryTypeMethod(ts, load, viewer);
19039566063dSJacob Faibussowitsch   PetscCall(DMCreate(PetscObjectComm((PetscObject)ts), &dm));
19049566063dSJacob Faibussowitsch   PetscCall(DMLoad(dm, viewer));
19059566063dSJacob Faibussowitsch   PetscCall(TSSetDM(ts, dm));
19069566063dSJacob Faibussowitsch   PetscCall(DMCreateGlobalVector(ts->dm, &ts->vec_sol));
19079566063dSJacob Faibussowitsch   PetscCall(VecLoad(ts->vec_sol, viewer));
19089566063dSJacob Faibussowitsch   PetscCall(DMGetDMTS(ts->dm, &sdm));
19099566063dSJacob Faibussowitsch   PetscCall(DMTSLoad(sdm, viewer));
19103ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
191155849f57SBarry Smith }
191255849f57SBarry Smith 
19139804daf3SBarry Smith #include <petscdraw.h>
1914e04113cfSBarry Smith #if defined(PETSC_HAVE_SAWS)
1915e04113cfSBarry Smith   #include <petscviewersaws.h>
1916f05ece33SBarry Smith #endif
1917fe2efc57SMark 
1918fe2efc57SMark /*@C
1919bcf0153eSBarry Smith    TSViewFromOptions - View a `TS` based on values in the options database
1920fe2efc57SMark 
1921c3339decSBarry Smith    Collective
1922fe2efc57SMark 
1923fe2efc57SMark    Input Parameters:
1924bcf0153eSBarry Smith +  ts - the `TS` context
1925bcf0153eSBarry Smith .  obj - Optional object that provides the prefix for the options database keys
1926bcf0153eSBarry Smith -  name - command line option string to be passed by user
1927fe2efc57SMark 
1928fe2efc57SMark    Level: intermediate
1929bcf0153eSBarry Smith 
1930bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSView`, `PetscObjectViewFromOptions()`, `TSCreate()`
1931fe2efc57SMark @*/
1932bcf0153eSBarry Smith PetscErrorCode TSViewFromOptions(TS ts, PetscObject obj, const char name[])
1933d71ae5a4SJacob Faibussowitsch {
1934fe2efc57SMark   PetscFunctionBegin;
1935bcf0153eSBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
1936bcf0153eSBarry Smith   PetscCall(PetscObjectViewFromOptions((PetscObject)ts, obj, name));
19373ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1938fe2efc57SMark }
1939fe2efc57SMark 
19407e2c5f70SBarry Smith /*@C
1941bcf0153eSBarry Smith     TSView - Prints the `TS` data structure.
1942d763cef2SBarry Smith 
1943c3339decSBarry Smith     Collective
1944d763cef2SBarry Smith 
1945d763cef2SBarry Smith     Input Parameters:
1946bcf0153eSBarry Smith +   ts - the `TS` context obtained from `TSCreate()`
1947d763cef2SBarry Smith -   viewer - visualization context
1948d763cef2SBarry Smith 
1949d763cef2SBarry Smith     Options Database Key:
1950bcf0153eSBarry Smith .   -ts_view - calls `TSView()` at end of `TSStep()`
1951bcf0153eSBarry Smith 
1952bcf0153eSBarry Smith     Level: beginner
1953d763cef2SBarry Smith 
1954d763cef2SBarry Smith     Notes:
1955d763cef2SBarry Smith     The available visualization contexts include
1956bcf0153eSBarry Smith +     `PETSC_VIEWER_STDOUT_SELF` - standard output (default)
1957bcf0153eSBarry Smith -     `PETSC_VIEWER_STDOUT_WORLD` - synchronized standard
1958d763cef2SBarry Smith          output where only the first processor opens
1959d763cef2SBarry Smith          the file.  All other processors send their
1960d763cef2SBarry Smith          data to the first processor to print.
1961d763cef2SBarry Smith 
1962d763cef2SBarry Smith     The user can open an alternative visualization context with
1963bcf0153eSBarry Smith     `PetscViewerASCIIOpen()` - output to a specified file.
1964d763cef2SBarry Smith 
1965bcf0153eSBarry Smith     In the debugger you can do call `TSView`(ts,0) to display the `TS` solver. (The same holds for any PETSc object viewer).
1966595c91d4SBarry Smith 
1967bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `PetscViewer`, `PetscViewerASCIIOpen()`
1968d763cef2SBarry Smith @*/
1969d71ae5a4SJacob Faibussowitsch PetscErrorCode TSView(TS ts, PetscViewer viewer)
1970d71ae5a4SJacob Faibussowitsch {
197119fd82e9SBarry Smith   TSType    type;
19722b0a91c0SBarry Smith   PetscBool iascii, isstring, isundials, isbinary, isdraw;
19732d53ad75SBarry Smith   DMTS      sdm;
1974e04113cfSBarry Smith #if defined(PETSC_HAVE_SAWS)
1975536b137fSBarry Smith   PetscBool issaws;
1976f05ece33SBarry Smith #endif
1977d763cef2SBarry Smith 
1978d763cef2SBarry Smith   PetscFunctionBegin;
19790700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
19801e66621cSBarry Smith   if (!viewer) PetscCall(PetscViewerASCIIGetStdout(PetscObjectComm((PetscObject)ts), &viewer));
19810700a824SBarry Smith   PetscValidHeaderSpecific(viewer, PETSC_VIEWER_CLASSID, 2);
1982c9780b6fSBarry Smith   PetscCheckSameComm(ts, 1, viewer, 2);
1983fd16b177SBarry Smith 
19849566063dSJacob Faibussowitsch   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERASCII, &iascii));
19859566063dSJacob Faibussowitsch   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERSTRING, &isstring));
19869566063dSJacob Faibussowitsch   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERBINARY, &isbinary));
19879566063dSJacob Faibussowitsch   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERDRAW, &isdraw));
1988e04113cfSBarry Smith #if defined(PETSC_HAVE_SAWS)
19899566063dSJacob Faibussowitsch   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERSAWS, &issaws));
1990f05ece33SBarry Smith #endif
199132077d6dSBarry Smith   if (iascii) {
19929566063dSJacob Faibussowitsch     PetscCall(PetscObjectPrintClassNamePrefixType((PetscObject)ts, viewer));
1993efd4aadfSBarry Smith     if (ts->ops->view) {
19949566063dSJacob Faibussowitsch       PetscCall(PetscViewerASCIIPushTab(viewer));
1995dbbe0bcdSBarry Smith       PetscUseTypeMethod(ts, view, viewer);
19969566063dSJacob Faibussowitsch       PetscCall(PetscViewerASCIIPopTab(viewer));
1997efd4aadfSBarry Smith     }
19981e66621cSBarry Smith     if (ts->max_steps < PETSC_MAX_INT) PetscCall(PetscViewerASCIIPrintf(viewer, "  maximum steps=%" PetscInt_FMT "\n", ts->max_steps));
19991e66621cSBarry Smith     if (ts->max_time < PETSC_MAX_REAL) PetscCall(PetscViewerASCIIPrintf(viewer, "  maximum time=%g\n", (double)ts->max_time));
20001e66621cSBarry Smith     if (ts->ifuncs) PetscCall(PetscViewerASCIIPrintf(viewer, "  total number of I function evaluations=%" PetscInt_FMT "\n", ts->ifuncs));
20011e66621cSBarry Smith     if (ts->ijacs) PetscCall(PetscViewerASCIIPrintf(viewer, "  total number of I Jacobian evaluations=%" PetscInt_FMT "\n", ts->ijacs));
20021e66621cSBarry Smith     if (ts->rhsfuncs) PetscCall(PetscViewerASCIIPrintf(viewer, "  total number of RHS function evaluations=%" PetscInt_FMT "\n", ts->rhsfuncs));
20031e66621cSBarry Smith     if (ts->rhsjacs) PetscCall(PetscViewerASCIIPrintf(viewer, "  total number of RHS Jacobian evaluations=%" PetscInt_FMT "\n", ts->rhsjacs));
2004efd4aadfSBarry Smith     if (ts->usessnes) {
2005efd4aadfSBarry Smith       PetscBool lin;
20061e66621cSBarry Smith       if (ts->problem_type == TS_NONLINEAR) PetscCall(PetscViewerASCIIPrintf(viewer, "  total number of nonlinear solver iterations=%" PetscInt_FMT "\n", ts->snes_its));
200763a3b9bcSJacob Faibussowitsch       PetscCall(PetscViewerASCIIPrintf(viewer, "  total number of linear solver iterations=%" PetscInt_FMT "\n", ts->ksp_its));
20089566063dSJacob Faibussowitsch       PetscCall(PetscObjectTypeCompareAny((PetscObject)ts->snes, &lin, SNESKSPONLY, SNESKSPTRANSPOSEONLY, ""));
200963a3b9bcSJacob Faibussowitsch       PetscCall(PetscViewerASCIIPrintf(viewer, "  total number of %slinear solve failures=%" PetscInt_FMT "\n", lin ? "" : "non", ts->num_snes_failures));
2010efd4aadfSBarry Smith     }
201163a3b9bcSJacob Faibussowitsch     PetscCall(PetscViewerASCIIPrintf(viewer, "  total number of rejected steps=%" PetscInt_FMT "\n", ts->reject));
20121e66621cSBarry Smith     if (ts->vrtol) PetscCall(PetscViewerASCIIPrintf(viewer, "  using vector of relative error tolerances, "));
20131e66621cSBarry Smith     else PetscCall(PetscViewerASCIIPrintf(viewer, "  using relative error tolerance of %g, ", (double)ts->rtol));
20141e66621cSBarry Smith     if (ts->vatol) PetscCall(PetscViewerASCIIPrintf(viewer, "  using vector of absolute error tolerances\n"));
20151e66621cSBarry Smith     else PetscCall(PetscViewerASCIIPrintf(viewer, "  using absolute error tolerance of %g\n", (double)ts->atol));
20169566063dSJacob Faibussowitsch     PetscCall(PetscViewerASCIIPushTab(viewer));
20179566063dSJacob Faibussowitsch     PetscCall(TSAdaptView(ts->adapt, viewer));
20189566063dSJacob Faibussowitsch     PetscCall(PetscViewerASCIIPopTab(viewer));
20190f5bd95cSBarry Smith   } else if (isstring) {
20209566063dSJacob Faibussowitsch     PetscCall(TSGetType(ts, &type));
20219566063dSJacob Faibussowitsch     PetscCall(PetscViewerStringSPrintf(viewer, " TSType: %-7.7s", type));
2022dbbe0bcdSBarry Smith     PetscTryTypeMethod(ts, view, viewer);
202355849f57SBarry Smith   } else if (isbinary) {
202455849f57SBarry Smith     PetscInt    classid = TS_FILE_CLASSID;
202555849f57SBarry Smith     MPI_Comm    comm;
202655849f57SBarry Smith     PetscMPIInt rank;
202755849f57SBarry Smith     char        type[256];
202855849f57SBarry Smith 
20299566063dSJacob Faibussowitsch     PetscCall(PetscObjectGetComm((PetscObject)ts, &comm));
20309566063dSJacob Faibussowitsch     PetscCallMPI(MPI_Comm_rank(comm, &rank));
2031dd400576SPatrick Sanan     if (rank == 0) {
20329566063dSJacob Faibussowitsch       PetscCall(PetscViewerBinaryWrite(viewer, &classid, 1, PETSC_INT));
20339566063dSJacob Faibussowitsch       PetscCall(PetscStrncpy(type, ((PetscObject)ts)->type_name, 256));
20349566063dSJacob Faibussowitsch       PetscCall(PetscViewerBinaryWrite(viewer, type, 256, PETSC_CHAR));
203555849f57SBarry Smith     }
2036dbbe0bcdSBarry Smith     PetscTryTypeMethod(ts, view, viewer);
20379566063dSJacob Faibussowitsch     if (ts->adapt) PetscCall(TSAdaptView(ts->adapt, viewer));
20389566063dSJacob Faibussowitsch     PetscCall(DMView(ts->dm, viewer));
20399566063dSJacob Faibussowitsch     PetscCall(VecView(ts->vec_sol, viewer));
20409566063dSJacob Faibussowitsch     PetscCall(DMGetDMTS(ts->dm, &sdm));
20419566063dSJacob Faibussowitsch     PetscCall(DMTSView(sdm, viewer));
20422b0a91c0SBarry Smith   } else if (isdraw) {
20432b0a91c0SBarry Smith     PetscDraw draw;
20442b0a91c0SBarry Smith     char      str[36];
204589fd9fafSBarry Smith     PetscReal x, y, bottom, h;
20462b0a91c0SBarry Smith 
20479566063dSJacob Faibussowitsch     PetscCall(PetscViewerDrawGetDraw(viewer, 0, &draw));
20489566063dSJacob Faibussowitsch     PetscCall(PetscDrawGetCurrentPoint(draw, &x, &y));
2049*c6a7a370SJeremy L Thompson     PetscCall(PetscStrncpy(str, "TS: ", sizeof(str)));
2050*c6a7a370SJeremy L Thompson     PetscCall(PetscStrlcat(str, ((PetscObject)ts)->type_name, sizeof(str)));
20519566063dSJacob Faibussowitsch     PetscCall(PetscDrawStringBoxed(draw, x, y, PETSC_DRAW_BLACK, PETSC_DRAW_BLACK, str, NULL, &h));
205289fd9fafSBarry Smith     bottom = y - h;
20539566063dSJacob Faibussowitsch     PetscCall(PetscDrawPushCurrentPoint(draw, x, bottom));
2054dbbe0bcdSBarry Smith     PetscTryTypeMethod(ts, view, viewer);
20559566063dSJacob Faibussowitsch     if (ts->adapt) PetscCall(TSAdaptView(ts->adapt, viewer));
20569566063dSJacob Faibussowitsch     if (ts->snes) PetscCall(SNESView(ts->snes, viewer));
20579566063dSJacob Faibussowitsch     PetscCall(PetscDrawPopCurrentPoint(draw));
2058e04113cfSBarry Smith #if defined(PETSC_HAVE_SAWS)
2059536b137fSBarry Smith   } else if (issaws) {
2060d45a07a7SBarry Smith     PetscMPIInt rank;
20612657e9d9SBarry Smith     const char *name;
20622657e9d9SBarry Smith 
20639566063dSJacob Faibussowitsch     PetscCall(PetscObjectGetName((PetscObject)ts, &name));
20649566063dSJacob Faibussowitsch     PetscCallMPI(MPI_Comm_rank(PETSC_COMM_WORLD, &rank));
2065dd400576SPatrick Sanan     if (!((PetscObject)ts)->amsmem && rank == 0) {
2066d45a07a7SBarry Smith       char dir[1024];
2067d45a07a7SBarry Smith 
20689566063dSJacob Faibussowitsch       PetscCall(PetscObjectViewSAWs((PetscObject)ts, viewer));
20699566063dSJacob Faibussowitsch       PetscCall(PetscSNPrintf(dir, 1024, "/PETSc/Objects/%s/time_step", name));
2070792fecdfSBarry Smith       PetscCallSAWs(SAWs_Register, (dir, &ts->steps, 1, SAWs_READ, SAWs_INT));
20719566063dSJacob Faibussowitsch       PetscCall(PetscSNPrintf(dir, 1024, "/PETSc/Objects/%s/time", name));
2072792fecdfSBarry Smith       PetscCallSAWs(SAWs_Register, (dir, &ts->ptime, 1, SAWs_READ, SAWs_DOUBLE));
2073d763cef2SBarry Smith     }
2074dbbe0bcdSBarry Smith     PetscTryTypeMethod(ts, view, viewer);
2075f05ece33SBarry Smith #endif
2076f05ece33SBarry Smith   }
207736a9e3b9SBarry Smith   if (ts->snes && ts->usessnes) {
20789566063dSJacob Faibussowitsch     PetscCall(PetscViewerASCIIPushTab(viewer));
20799566063dSJacob Faibussowitsch     PetscCall(SNESView(ts->snes, viewer));
20809566063dSJacob Faibussowitsch     PetscCall(PetscViewerASCIIPopTab(viewer));
208136a9e3b9SBarry Smith   }
20829566063dSJacob Faibussowitsch   PetscCall(DMGetDMTS(ts->dm, &sdm));
20839566063dSJacob Faibussowitsch   PetscCall(DMTSView(sdm, viewer));
2084f05ece33SBarry Smith 
20859566063dSJacob Faibussowitsch   PetscCall(PetscViewerASCIIPushTab(viewer));
20869566063dSJacob Faibussowitsch   PetscCall(PetscObjectTypeCompare((PetscObject)ts, TSSUNDIALS, &isundials));
20879566063dSJacob Faibussowitsch   PetscCall(PetscViewerASCIIPopTab(viewer));
20883ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2089d763cef2SBarry Smith }
2090d763cef2SBarry Smith 
2091b07ff414SBarry Smith /*@
2092d763cef2SBarry Smith    TSSetApplicationContext - Sets an optional user-defined context for
2093d763cef2SBarry Smith    the timesteppers.
2094d763cef2SBarry Smith 
2095c3339decSBarry Smith    Logically Collective
2096d763cef2SBarry Smith 
2097d763cef2SBarry Smith    Input Parameters:
2098bcf0153eSBarry Smith +  ts - the `TS` context obtained from `TSCreate()`
2099bcf0153eSBarry Smith -  usrP -  user context
2100daf670e6SBarry Smith 
2101d763cef2SBarry Smith    Level: intermediate
2102d763cef2SBarry Smith 
2103bcf0153eSBarry Smith    Fortran Note:
2104195e9b02SBarry Smith     You must write a Fortran interface definition for this
2105195e9b02SBarry Smith     function that tells Fortran the Fortran derived data type that you are passing in as the `ctx` argument.
2106bcf0153eSBarry Smith 
2107bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSGetApplicationContext()`
2108d763cef2SBarry Smith @*/
2109d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetApplicationContext(TS ts, void *usrP)
2110d71ae5a4SJacob Faibussowitsch {
2111d763cef2SBarry Smith   PetscFunctionBegin;
21120700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
2113d763cef2SBarry Smith   ts->user = usrP;
21143ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2115d763cef2SBarry Smith }
2116d763cef2SBarry Smith 
2117b07ff414SBarry Smith /*@
2118d763cef2SBarry Smith     TSGetApplicationContext - Gets the user-defined context for the
2119bcf0153eSBarry Smith     timestepper that was set with `TSSetApplicationContext()`
2120d763cef2SBarry Smith 
2121d763cef2SBarry Smith     Not Collective
2122d763cef2SBarry Smith 
2123d763cef2SBarry Smith     Input Parameter:
2124bcf0153eSBarry Smith .   ts - the `TS` context obtained from `TSCreate()`
2125d763cef2SBarry Smith 
2126d763cef2SBarry Smith     Output Parameter:
2127d763cef2SBarry Smith .   usrP - user context
2128d763cef2SBarry Smith 
2129bcf0153eSBarry Smith     Level: intermediate
2130bcf0153eSBarry Smith 
2131bcf0153eSBarry Smith     Fortran Note:
2132195e9b02SBarry Smith     You must write a Fortran interface definition for this
2133195e9b02SBarry Smith     function that tells Fortran the Fortran derived data type that you are passing in as the `ctx` argument.
2134daf670e6SBarry Smith 
2135bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSSetApplicationContext()`
2136d763cef2SBarry Smith @*/
2137d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetApplicationContext(TS ts, void *usrP)
2138d71ae5a4SJacob Faibussowitsch {
2139d763cef2SBarry Smith   PetscFunctionBegin;
21400700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
2141e71120c6SJed Brown   *(void **)usrP = ts->user;
21423ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2143d763cef2SBarry Smith }
2144d763cef2SBarry Smith 
2145d763cef2SBarry Smith /*@
2146bcf0153eSBarry Smith    TSGetStepNumber - Gets the number of time steps completed.
2147d763cef2SBarry Smith 
2148d763cef2SBarry Smith    Not Collective
2149d763cef2SBarry Smith 
2150d763cef2SBarry Smith    Input Parameter:
2151bcf0153eSBarry Smith .  ts - the `TS` context obtained from `TSCreate()`
2152d763cef2SBarry Smith 
2153d763cef2SBarry Smith    Output Parameter:
215480275a0aSLisandro Dalcin .  steps - number of steps completed so far
2155d763cef2SBarry Smith 
2156d763cef2SBarry Smith    Level: intermediate
2157d763cef2SBarry Smith 
2158bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSGetTime()`, `TSGetTimeStep()`, `TSSetPreStep()`, `TSSetPreStage()`, `TSSetPostStage()`, `TSSetPostStep()`
2159d763cef2SBarry Smith @*/
2160d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetStepNumber(TS ts, PetscInt *steps)
2161d71ae5a4SJacob Faibussowitsch {
2162d763cef2SBarry Smith   PetscFunctionBegin;
21630700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
216480275a0aSLisandro Dalcin   PetscValidIntPointer(steps, 2);
216580275a0aSLisandro Dalcin   *steps = ts->steps;
21663ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
216780275a0aSLisandro Dalcin }
216880275a0aSLisandro Dalcin 
216980275a0aSLisandro Dalcin /*@
217080275a0aSLisandro Dalcin    TSSetStepNumber - Sets the number of steps completed.
217180275a0aSLisandro Dalcin 
2172c3339decSBarry Smith    Logically Collective
217380275a0aSLisandro Dalcin 
217480275a0aSLisandro Dalcin    Input Parameters:
2175bcf0153eSBarry Smith +  ts - the `TS` context
217680275a0aSLisandro Dalcin -  steps - number of steps completed so far
217780275a0aSLisandro Dalcin 
2178bcf0153eSBarry Smith    Level: developer
2179bcf0153eSBarry Smith 
2180bcf0153eSBarry Smith    Note:
2181bcf0153eSBarry Smith    For most uses of the `TS` solvers the user need not explicitly call
2182bcf0153eSBarry Smith    `TSSetStepNumber()`, as the step counter is appropriately updated in
2183bcf0153eSBarry Smith    `TSSolve()`/`TSStep()`/`TSRollBack()`. Power users may call this routine to
218480275a0aSLisandro Dalcin    reinitialize timestepping by setting the step counter to zero (and time
218580275a0aSLisandro Dalcin    to the initial time) to solve a similar problem with different initial
218680275a0aSLisandro Dalcin    conditions or parameters. Other possible use case is to continue
2187195e9b02SBarry Smith    timestepping from a previously interrupted run in such a way that `TS`
218880275a0aSLisandro Dalcin    monitors will be called with a initial nonzero step counter.
218980275a0aSLisandro Dalcin 
2190bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSGetStepNumber()`, `TSSetTime()`, `TSSetTimeStep()`, `TSSetSolution()`
219180275a0aSLisandro Dalcin @*/
2192d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetStepNumber(TS ts, PetscInt steps)
2193d71ae5a4SJacob Faibussowitsch {
219480275a0aSLisandro Dalcin   PetscFunctionBegin;
219580275a0aSLisandro Dalcin   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
219680275a0aSLisandro Dalcin   PetscValidLogicalCollectiveInt(ts, steps, 2);
21973c633725SBarry Smith   PetscCheck(steps >= 0, PetscObjectComm((PetscObject)ts), PETSC_ERR_ARG_OUTOFRANGE, "Step number must be non-negative");
219880275a0aSLisandro Dalcin   ts->steps = steps;
21993ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2200d763cef2SBarry Smith }
2201d763cef2SBarry Smith 
2202d763cef2SBarry Smith /*@
2203d763cef2SBarry Smith    TSSetTimeStep - Allows one to reset the timestep at any time,
2204d763cef2SBarry Smith    useful for simple pseudo-timestepping codes.
2205d763cef2SBarry Smith 
2206c3339decSBarry Smith    Logically Collective
2207d763cef2SBarry Smith 
2208d763cef2SBarry Smith    Input Parameters:
2209bcf0153eSBarry Smith +  ts - the `TS` context obtained from `TSCreate()`
2210d763cef2SBarry Smith -  time_step - the size of the timestep
2211d763cef2SBarry Smith 
2212d763cef2SBarry Smith    Level: intermediate
2213d763cef2SBarry Smith 
2214bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSPSEUDO`, `TSGetTimeStep()`, `TSSetTime()`
2215d763cef2SBarry Smith @*/
2216d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetTimeStep(TS ts, PetscReal time_step)
2217d71ae5a4SJacob Faibussowitsch {
2218d763cef2SBarry Smith   PetscFunctionBegin;
22190700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
2220c5eb9154SBarry Smith   PetscValidLogicalCollectiveReal(ts, time_step, 2);
2221d763cef2SBarry Smith   ts->time_step = time_step;
22223ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2223d763cef2SBarry Smith }
2224d763cef2SBarry Smith 
2225a43b19c4SJed Brown /*@
222649354f04SShri Abhyankar    TSSetExactFinalTime - Determines whether to adapt the final time step to
222749354f04SShri Abhyankar      match the exact final time, interpolate solution to the exact final time,
2228bcf0153eSBarry Smith      or just return at the final time `TS` computed.
2229a43b19c4SJed Brown 
2230c3339decSBarry Smith   Logically Collective
2231a43b19c4SJed Brown 
2232d8d19677SJose E. Roman    Input Parameters:
2233a43b19c4SJed Brown +   ts - the time-step context
223449354f04SShri Abhyankar -   eftopt - exact final time option
2235bcf0153eSBarry Smith .vb
2236bcf0153eSBarry Smith   TS_EXACTFINALTIME_STEPOVER    - Don't do anything if final time is exceeded
2237bcf0153eSBarry Smith   TS_EXACTFINALTIME_INTERPOLATE - Interpolate back to final time
2238bcf0153eSBarry Smith   TS_EXACTFINALTIME_MATCHSTEP - Adapt final time step to match the final time
2239bcf0153eSBarry Smith .ve
2240a43b19c4SJed Brown 
2241bcf0153eSBarry Smith    Options Database Key:
2242feed9e9dSBarry Smith .   -ts_exact_final_time <stepover,interpolate,matchstep> - select the final step at runtime
2243feed9e9dSBarry Smith 
2244a43b19c4SJed Brown    Level: beginner
2245a43b19c4SJed Brown 
2246bcf0153eSBarry Smith    Note:
2247bcf0153eSBarry Smith    If you use the option `TS_EXACTFINALTIME_STEPOVER` the solution may be at a very different time
2248bcf0153eSBarry Smith    then the final time you selected.
2249bcf0153eSBarry Smith 
2250bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSExactFinalTimeOption`, `TSGetExactFinalTime()`
2251a43b19c4SJed Brown @*/
2252d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetExactFinalTime(TS ts, TSExactFinalTimeOption eftopt)
2253d71ae5a4SJacob Faibussowitsch {
2254a43b19c4SJed Brown   PetscFunctionBegin;
2255a43b19c4SJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
225649354f04SShri Abhyankar   PetscValidLogicalCollectiveEnum(ts, eftopt, 2);
225749354f04SShri Abhyankar   ts->exact_final_time = eftopt;
22583ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2259a43b19c4SJed Brown }
2260a43b19c4SJed Brown 
2261d763cef2SBarry Smith /*@
2262bcf0153eSBarry Smith    TSGetExactFinalTime - Gets the exact final time option set with `TSSetExactFinalTime()`
2263f6953c82SLisandro Dalcin 
2264f6953c82SLisandro Dalcin    Not Collective
2265f6953c82SLisandro Dalcin 
2266f6953c82SLisandro Dalcin    Input Parameter:
2267bcf0153eSBarry Smith .  ts - the `TS` context
2268f6953c82SLisandro Dalcin 
2269f6953c82SLisandro Dalcin    Output Parameter:
2270f6953c82SLisandro Dalcin .  eftopt - exact final time option
2271f6953c82SLisandro Dalcin 
2272f6953c82SLisandro Dalcin    Level: beginner
2273f6953c82SLisandro Dalcin 
2274bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSExactFinalTimeOption`, `TSSetExactFinalTime()`
2275f6953c82SLisandro Dalcin @*/
2276d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetExactFinalTime(TS ts, TSExactFinalTimeOption *eftopt)
2277d71ae5a4SJacob Faibussowitsch {
2278f6953c82SLisandro Dalcin   PetscFunctionBegin;
2279f6953c82SLisandro Dalcin   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
2280f6953c82SLisandro Dalcin   PetscValidPointer(eftopt, 2);
2281f6953c82SLisandro Dalcin   *eftopt = ts->exact_final_time;
22823ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2283f6953c82SLisandro Dalcin }
2284f6953c82SLisandro Dalcin 
2285f6953c82SLisandro Dalcin /*@
2286d763cef2SBarry Smith    TSGetTimeStep - Gets the current timestep size.
2287d763cef2SBarry Smith 
2288d763cef2SBarry Smith    Not Collective
2289d763cef2SBarry Smith 
2290d763cef2SBarry Smith    Input Parameter:
2291bcf0153eSBarry Smith .  ts - the `TS` context obtained from `TSCreate()`
2292d763cef2SBarry Smith 
2293d763cef2SBarry Smith    Output Parameter:
2294d763cef2SBarry Smith .  dt - the current timestep size
2295d763cef2SBarry Smith 
2296d763cef2SBarry Smith    Level: intermediate
2297d763cef2SBarry Smith 
2298bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSSetTimeStep()`, `TSGetTime()`
2299d763cef2SBarry Smith @*/
2300d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetTimeStep(TS ts, PetscReal *dt)
2301d71ae5a4SJacob Faibussowitsch {
2302d763cef2SBarry Smith   PetscFunctionBegin;
23030700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
2304f7cf8827SBarry Smith   PetscValidRealPointer(dt, 2);
2305d763cef2SBarry Smith   *dt = ts->time_step;
23063ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2307d763cef2SBarry Smith }
2308d763cef2SBarry Smith 
2309d8e5e3e6SSatish Balay /*@
2310d763cef2SBarry Smith    TSGetSolution - Returns the solution at the present timestep. It
2311d763cef2SBarry Smith    is valid to call this routine inside the function that you are evaluating
2312d763cef2SBarry Smith    in order to move to the new timestep. This vector not changed until
2313d763cef2SBarry Smith    the solution at the next timestep has been calculated.
2314d763cef2SBarry Smith 
2315bcf0153eSBarry Smith    Not Collective, but v returned is parallel if ts is parallel
2316d763cef2SBarry Smith 
2317d763cef2SBarry Smith    Input Parameter:
2318bcf0153eSBarry Smith .  ts - the `TS` context obtained from `TSCreate()`
2319d763cef2SBarry Smith 
2320d763cef2SBarry Smith    Output Parameter:
2321d763cef2SBarry Smith .  v - the vector containing the solution
2322d763cef2SBarry Smith 
2323d763cef2SBarry Smith    Level: intermediate
2324d763cef2SBarry Smith 
2325bcf0153eSBarry Smith    Note:
2326bcf0153eSBarry Smith    If you used `TSSetExactFinalTime`(ts,`TS_EXACTFINALTIME_MATCHSTEP`); this does not return the solution at the requested
2327bcf0153eSBarry Smith    final time. It returns the solution at the next timestep.
2328d763cef2SBarry Smith 
2329bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSGetTimeStep()`, `TSGetTime()`, `TSGetSolveTime()`, `TSGetSolutionComponents()`, `TSSetSolutionFunction()`
2330d763cef2SBarry Smith @*/
2331d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetSolution(TS ts, Vec *v)
2332d71ae5a4SJacob Faibussowitsch {
2333d763cef2SBarry Smith   PetscFunctionBegin;
23340700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
23354482741eSBarry Smith   PetscValidPointer(v, 2);
23368737fe31SLisandro Dalcin   *v = ts->vec_sol;
23373ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2338d763cef2SBarry Smith }
2339d763cef2SBarry Smith 
234003fe5f5eSDebojyoti Ghosh /*@
2341b2bf4f3aSDebojyoti Ghosh    TSGetSolutionComponents - Returns any solution components at the present
234203fe5f5eSDebojyoti Ghosh    timestep, if available for the time integration method being used.
2343b2bf4f3aSDebojyoti Ghosh    Solution components are quantities that share the same size and
234403fe5f5eSDebojyoti Ghosh    structure as the solution vector.
234503fe5f5eSDebojyoti Ghosh 
2346bcf0153eSBarry Smith    Not Collective, but v returned is parallel if ts is parallel
234703fe5f5eSDebojyoti Ghosh 
234803fe5f5eSDebojyoti Ghosh    Parameters :
2349bcf0153eSBarry Smith +  ts - the `TS` context obtained from `TSCreate()` (input parameter).
2350195e9b02SBarry Smith .  n - If v is `NULL`, then the number of solution components is
2351b2bf4f3aSDebojyoti Ghosh        returned through n, else the n-th solution component is
235203fe5f5eSDebojyoti Ghosh        returned in v.
2353a2b725a8SWilliam Gropp -  v - the vector containing the n-th solution component
2354195e9b02SBarry Smith        (may be `NULL` to use this function to find out
2355b2bf4f3aSDebojyoti Ghosh         the number of solutions components).
235603fe5f5eSDebojyoti Ghosh 
23574cdd57e5SDebojyoti Ghosh    Level: advanced
235803fe5f5eSDebojyoti Ghosh 
2359bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSGetSolution()`
236003fe5f5eSDebojyoti Ghosh @*/
2361d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetSolutionComponents(TS ts, PetscInt *n, Vec *v)
2362d71ae5a4SJacob Faibussowitsch {
236303fe5f5eSDebojyoti Ghosh   PetscFunctionBegin;
236403fe5f5eSDebojyoti Ghosh   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
2365b2bf4f3aSDebojyoti Ghosh   if (!ts->ops->getsolutioncomponents) *n = 0;
2366dbbe0bcdSBarry Smith   else PetscUseTypeMethod(ts, getsolutioncomponents, n, v);
23673ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
236803fe5f5eSDebojyoti Ghosh }
236903fe5f5eSDebojyoti Ghosh 
23704cdd57e5SDebojyoti Ghosh /*@
23714cdd57e5SDebojyoti Ghosh    TSGetAuxSolution - Returns an auxiliary solution at the present
23724cdd57e5SDebojyoti Ghosh    timestep, if available for the time integration method being used.
23734cdd57e5SDebojyoti Ghosh 
2374bcf0153eSBarry Smith    Not Collective, but v returned is parallel if ts is parallel
23754cdd57e5SDebojyoti Ghosh 
23764cdd57e5SDebojyoti Ghosh    Parameters :
2377bcf0153eSBarry Smith +  ts - the `TS` context obtained from `TSCreate()` (input parameter).
2378a2b725a8SWilliam Gropp -  v - the vector containing the auxiliary solution
23794cdd57e5SDebojyoti Ghosh 
23804cdd57e5SDebojyoti Ghosh    Level: intermediate
23814cdd57e5SDebojyoti Ghosh 
2382bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSGetSolution()`
23834cdd57e5SDebojyoti Ghosh @*/
2384d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetAuxSolution(TS ts, Vec *v)
2385d71ae5a4SJacob Faibussowitsch {
23864cdd57e5SDebojyoti Ghosh   PetscFunctionBegin;
23874cdd57e5SDebojyoti Ghosh   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
2388dbbe0bcdSBarry Smith   if (ts->ops->getauxsolution) PetscUseTypeMethod(ts, getauxsolution, v);
23891e66621cSBarry Smith   else PetscCall(VecZeroEntries(*v));
23903ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
23914cdd57e5SDebojyoti Ghosh }
23924cdd57e5SDebojyoti Ghosh 
23934cdd57e5SDebojyoti Ghosh /*@
23944cdd57e5SDebojyoti Ghosh    TSGetTimeError - Returns the estimated error vector, if the chosen
2395bcf0153eSBarry Smith    `TSType` has an error estimation functionality and `TSSetTimeError()` was called
23964cdd57e5SDebojyoti Ghosh 
2397bcf0153eSBarry Smith    Not Collective, but v returned is parallel if ts is parallel
23989657682dSDebojyoti Ghosh 
23994cdd57e5SDebojyoti Ghosh    Parameters :
2400bcf0153eSBarry Smith +  ts - the `TS` context obtained from `TSCreate()` (input parameter).
2401657c1e31SEmil Constantinescu .  n - current estimate (n=0) or previous one (n=-1)
2402a2b725a8SWilliam Gropp -  v - the vector containing the error (same size as the solution).
24034cdd57e5SDebojyoti Ghosh 
24044cdd57e5SDebojyoti Ghosh    Level: intermediate
24054cdd57e5SDebojyoti Ghosh 
2406bcf0153eSBarry Smith    Note:
2407bcf0153eSBarry Smith    MUST call after `TSSetUp()`
24084cdd57e5SDebojyoti Ghosh 
2409bcf0153eSBarry Smith .seealso: [](chapter_ts), `TSGetSolution()`, `TSSetTimeError()`
24104cdd57e5SDebojyoti Ghosh @*/
2411d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetTimeError(TS ts, PetscInt n, Vec *v)
2412d71ae5a4SJacob Faibussowitsch {
24134cdd57e5SDebojyoti Ghosh   PetscFunctionBegin;
24144cdd57e5SDebojyoti Ghosh   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
2415dbbe0bcdSBarry Smith   if (ts->ops->gettimeerror) PetscUseTypeMethod(ts, gettimeerror, n, v);
24161e66621cSBarry Smith   else PetscCall(VecZeroEntries(*v));
24173ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
24184cdd57e5SDebojyoti Ghosh }
24194cdd57e5SDebojyoti Ghosh 
242057df6a1bSDebojyoti Ghosh /*@
242157df6a1bSDebojyoti Ghosh    TSSetTimeError - Sets the estimated error vector, if the chosen
2422bcf0153eSBarry Smith    `TSType` has an error estimation functionality. This can be used
242357df6a1bSDebojyoti Ghosh    to restart such a time integrator with a given error vector.
242457df6a1bSDebojyoti Ghosh 
2425bcf0153eSBarry Smith    Not Collective, but v returned is parallel if ts is parallel
242657df6a1bSDebojyoti Ghosh 
242757df6a1bSDebojyoti Ghosh    Parameters :
2428bcf0153eSBarry Smith +  ts - the `TS` context obtained from `TSCreate()` (input parameter).
2429a2b725a8SWilliam Gropp -  v - the vector containing the error (same size as the solution).
243057df6a1bSDebojyoti Ghosh 
243157df6a1bSDebojyoti Ghosh    Level: intermediate
243257df6a1bSDebojyoti Ghosh 
2433bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSSetSolution()`, `TSGetTimeError)`
243457df6a1bSDebojyoti Ghosh @*/
2435d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetTimeError(TS ts, Vec v)
2436d71ae5a4SJacob Faibussowitsch {
243757df6a1bSDebojyoti Ghosh   PetscFunctionBegin;
243857df6a1bSDebojyoti Ghosh   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
24393c633725SBarry Smith   PetscCheck(ts->setupcalled, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Must call TSSetUp() first");
2440dbbe0bcdSBarry Smith   PetscTryTypeMethod(ts, settimeerror, v);
24413ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
244257df6a1bSDebojyoti Ghosh }
244357df6a1bSDebojyoti Ghosh 
2444bdad233fSMatthew Knepley /* ----- Routines to initialize and destroy a timestepper ---- */
2445d8e5e3e6SSatish Balay /*@
2446bdad233fSMatthew Knepley   TSSetProblemType - Sets the type of problem to be solved.
2447d763cef2SBarry Smith 
2448bdad233fSMatthew Knepley   Not collective
2449d763cef2SBarry Smith 
2450bdad233fSMatthew Knepley   Input Parameters:
2451bcf0153eSBarry Smith + ts   - The `TS`
2452bcf0153eSBarry Smith - type - One of `TS_LINEAR`, `TS_NONLINEAR` where these types refer to problems of the forms
2453d763cef2SBarry Smith .vb
24540910c330SBarry Smith          U_t - A U = 0      (linear)
24550910c330SBarry Smith          U_t - A(t) U = 0   (linear)
24560910c330SBarry Smith          F(t,U,U_t) = 0     (nonlinear)
2457d763cef2SBarry Smith .ve
2458d763cef2SBarry Smith 
2459d763cef2SBarry Smith    Level: beginner
2460d763cef2SBarry Smith 
2461bcf0153eSBarry Smith .seealso: [](chapter_ts), `TSSetUp()`, `TSProblemType`, `TS`
2462d763cef2SBarry Smith @*/
2463d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetProblemType(TS ts, TSProblemType type)
2464d71ae5a4SJacob Faibussowitsch {
2465d763cef2SBarry Smith   PetscFunctionBegin;
24660700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
2467bdad233fSMatthew Knepley   ts->problem_type = type;
24689e2a6581SJed Brown   if (type == TS_LINEAR) {
24699e2a6581SJed Brown     SNES snes;
24709566063dSJacob Faibussowitsch     PetscCall(TSGetSNES(ts, &snes));
24719566063dSJacob Faibussowitsch     PetscCall(SNESSetType(snes, SNESKSPONLY));
24729e2a6581SJed Brown   }
24733ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2474d763cef2SBarry Smith }
2475d763cef2SBarry Smith 
2476bdad233fSMatthew Knepley /*@C
2477bdad233fSMatthew Knepley   TSGetProblemType - Gets the type of problem to be solved.
2478bdad233fSMatthew Knepley 
2479bdad233fSMatthew Knepley   Not collective
2480bdad233fSMatthew Knepley 
2481bdad233fSMatthew Knepley   Input Parameter:
2482bcf0153eSBarry Smith . ts   - The `TS`
2483bdad233fSMatthew Knepley 
2484bdad233fSMatthew Knepley   Output Parameter:
2485bcf0153eSBarry Smith . type - One of `TS_LINEAR`, `TS_NONLINEAR` where these types refer to problems of the forms
2486bdad233fSMatthew Knepley .vb
2487089b2837SJed Brown          M U_t = A U
2488089b2837SJed Brown          M(t) U_t = A(t) U
2489b5abc632SBarry Smith          F(t,U,U_t)
2490bdad233fSMatthew Knepley .ve
2491bdad233fSMatthew Knepley 
2492bdad233fSMatthew Knepley    Level: beginner
2493bdad233fSMatthew Knepley 
2494bcf0153eSBarry Smith .seealso: [](chapter_ts), `TSSetUp()`, `TSProblemType`, `TS`
2495bdad233fSMatthew Knepley @*/
2496d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetProblemType(TS ts, TSProblemType *type)
2497d71ae5a4SJacob Faibussowitsch {
2498bdad233fSMatthew Knepley   PetscFunctionBegin;
24990700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
25004482741eSBarry Smith   PetscValidIntPointer(type, 2);
2501bdad233fSMatthew Knepley   *type = ts->problem_type;
25023ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2503bdad233fSMatthew Knepley }
2504d763cef2SBarry Smith 
2505303a5415SBarry Smith /*
2506303a5415SBarry Smith     Attempt to check/preset a default value for the exact final time option. This is needed at the beginning of TSSolve() and in TSSetUp()
2507303a5415SBarry Smith */
2508d71ae5a4SJacob Faibussowitsch static PetscErrorCode TSSetExactFinalTimeDefault(TS ts)
2509d71ae5a4SJacob Faibussowitsch {
2510303a5415SBarry Smith   PetscBool isnone;
2511303a5415SBarry Smith 
2512303a5415SBarry Smith   PetscFunctionBegin;
25139566063dSJacob Faibussowitsch   PetscCall(TSGetAdapt(ts, &ts->adapt));
25149566063dSJacob Faibussowitsch   PetscCall(TSAdaptSetDefaultType(ts->adapt, ts->default_adapt_type));
2515303a5415SBarry Smith 
25169566063dSJacob Faibussowitsch   PetscCall(PetscObjectTypeCompare((PetscObject)ts->adapt, TSADAPTNONE, &isnone));
25171e66621cSBarry Smith   if (!isnone && ts->exact_final_time == TS_EXACTFINALTIME_UNSPECIFIED) ts->exact_final_time = TS_EXACTFINALTIME_MATCHSTEP;
25181e66621cSBarry Smith   else if (ts->exact_final_time == TS_EXACTFINALTIME_UNSPECIFIED) ts->exact_final_time = TS_EXACTFINALTIME_INTERPOLATE;
25193ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2520303a5415SBarry Smith }
2521303a5415SBarry Smith 
2522d763cef2SBarry Smith /*@
2523303a5415SBarry Smith    TSSetUp - Sets up the internal data structures for the later use of a timestepper.
2524d763cef2SBarry Smith 
2525c3339decSBarry Smith    Collective
2526d763cef2SBarry Smith 
2527d763cef2SBarry Smith    Input Parameter:
2528bcf0153eSBarry Smith .  ts - the `TS` context obtained from `TSCreate()`
2529d763cef2SBarry Smith 
2530d763cef2SBarry Smith    Level: advanced
2531d763cef2SBarry Smith 
2532bcf0153eSBarry Smith    Note:
2533bcf0153eSBarry Smith    For basic use of the `TS` solvers the user need not explicitly call
2534bcf0153eSBarry Smith    `TSSetUp()`, since these actions will automatically occur during
2535bcf0153eSBarry Smith    the call to `TSStep()` or `TSSolve()`.  However, if one wishes to control this
2536bcf0153eSBarry Smith    phase separately, `TSSetUp()` should be called after `TSCreate()`
2537bcf0153eSBarry Smith    and optional routines of the form TSSetXXX(), but before `TSStep()` and `TSSolve()`.
2538bcf0153eSBarry Smith 
2539bcf0153eSBarry Smith .seealso: [](chapter_ts), `TSCreate()`, `TS`, `TSStep()`, `TSDestroy()`, `TSSolve()`
2540d763cef2SBarry Smith @*/
2541d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetUp(TS ts)
2542d71ae5a4SJacob Faibussowitsch {
25436c6b9e74SPeter Brune   DM dm;
25446c6b9e74SPeter Brune   PetscErrorCode (*func)(SNES, Vec, Vec, void *);
2545d1e9a80fSBarry Smith   PetscErrorCode (*jac)(SNES, Vec, Mat, Mat, void *);
2546cd11d68dSLisandro Dalcin   TSIFunction   ifun;
25476c6b9e74SPeter Brune   TSIJacobian   ijac;
2548efe9872eSLisandro Dalcin   TSI2Jacobian  i2jac;
25496c6b9e74SPeter Brune   TSRHSJacobian rhsjac;
2550d763cef2SBarry Smith 
2551d763cef2SBarry Smith   PetscFunctionBegin;
25520700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
25533ba16761SJacob Faibussowitsch   if (ts->setupcalled) PetscFunctionReturn(PETSC_SUCCESS);
2554277b19d0SLisandro Dalcin 
25557adad957SLisandro Dalcin   if (!((PetscObject)ts)->type_name) {
25569566063dSJacob Faibussowitsch     PetscCall(TSGetIFunction(ts, NULL, &ifun, NULL));
25579566063dSJacob Faibussowitsch     PetscCall(TSSetType(ts, ifun ? TSBEULER : TSEULER));
2558d763cef2SBarry Smith   }
2559277b19d0SLisandro Dalcin 
25601a638600SStefano Zampini   if (!ts->vec_sol) {
25611e66621cSBarry Smith     PetscCheck(ts->dm, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Must call TSSetSolution() first");
25629566063dSJacob Faibussowitsch     PetscCall(DMCreateGlobalVector(ts->dm, &ts->vec_sol));
25631a638600SStefano Zampini   }
2564277b19d0SLisandro Dalcin 
25654a658b32SHong Zhang   if (ts->tspan) {
25661e66621cSBarry Smith     if (!ts->tspan->vecs_sol) PetscCall(VecDuplicateVecs(ts->vec_sol, ts->tspan->num_span_times, &ts->tspan->vecs_sol));
25674a658b32SHong Zhang   }
2568298bade4SHong Zhang   if (!ts->Jacp && ts->Jacprhs) { /* IJacobianP shares the same matrix with RHSJacobianP if only RHSJacobianP is provided */
25699566063dSJacob Faibussowitsch     PetscCall(PetscObjectReference((PetscObject)ts->Jacprhs));
2570298bade4SHong Zhang     ts->Jacp = ts->Jacprhs;
2571298bade4SHong Zhang   }
2572298bade4SHong Zhang 
2573cd4cee2dSHong Zhang   if (ts->quadraturets) {
25749566063dSJacob Faibussowitsch     PetscCall(TSSetUp(ts->quadraturets));
25759566063dSJacob Faibussowitsch     PetscCall(VecDestroy(&ts->vec_costintegrand));
25769566063dSJacob Faibussowitsch     PetscCall(VecDuplicate(ts->quadraturets->vec_sol, &ts->vec_costintegrand));
2577cd4cee2dSHong Zhang   }
2578cd4cee2dSHong Zhang 
25799566063dSJacob Faibussowitsch   PetscCall(TSGetRHSJacobian(ts, NULL, NULL, &rhsjac, NULL));
2580f23ba4b3SHong Zhang   if (rhsjac == TSComputeRHSJacobianConstant) {
2581e1244c69SJed Brown     Mat  Amat, Pmat;
2582e1244c69SJed Brown     SNES snes;
25839566063dSJacob Faibussowitsch     PetscCall(TSGetSNES(ts, &snes));
25849566063dSJacob Faibussowitsch     PetscCall(SNESGetJacobian(snes, &Amat, &Pmat, NULL, NULL));
2585e1244c69SJed Brown     /* Matching matrices implies that an IJacobian is NOT set, because if it had been set, the IJacobian's matrix would
2586e1244c69SJed Brown      * have displaced the RHS matrix */
2587971015bcSStefano Zampini     if (Amat && Amat == ts->Arhs) {
2588abc0d4abSBarry Smith       /* 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 */
25899566063dSJacob Faibussowitsch       PetscCall(MatDuplicate(ts->Arhs, MAT_COPY_VALUES, &Amat));
25909566063dSJacob Faibussowitsch       PetscCall(SNESSetJacobian(snes, Amat, NULL, NULL, NULL));
25919566063dSJacob Faibussowitsch       PetscCall(MatDestroy(&Amat));
2592e1244c69SJed Brown     }
2593971015bcSStefano Zampini     if (Pmat && Pmat == ts->Brhs) {
25949566063dSJacob Faibussowitsch       PetscCall(MatDuplicate(ts->Brhs, MAT_COPY_VALUES, &Pmat));
25959566063dSJacob Faibussowitsch       PetscCall(SNESSetJacobian(snes, NULL, Pmat, NULL, NULL));
25969566063dSJacob Faibussowitsch       PetscCall(MatDestroy(&Pmat));
2597e1244c69SJed Brown     }
2598e1244c69SJed Brown   }
25992ffb9264SLisandro Dalcin 
26009566063dSJacob Faibussowitsch   PetscCall(TSGetAdapt(ts, &ts->adapt));
26019566063dSJacob Faibussowitsch   PetscCall(TSAdaptSetDefaultType(ts->adapt, ts->default_adapt_type));
26022ffb9264SLisandro Dalcin 
2603dbbe0bcdSBarry Smith   PetscTryTypeMethod(ts, setup);
2604277b19d0SLisandro Dalcin 
26059566063dSJacob Faibussowitsch   PetscCall(TSSetExactFinalTimeDefault(ts));
26062ffb9264SLisandro Dalcin 
2607a6772fa2SLisandro Dalcin   /* In the case where we've set a DMTSFunction or what have you, we need the default SNESFunction
26086c6b9e74SPeter Brune      to be set right but can't do it elsewhere due to the overreliance on ctx=ts.
26096c6b9e74SPeter Brune    */
26109566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
26119566063dSJacob Faibussowitsch   PetscCall(DMSNESGetFunction(dm, &func, NULL));
26121e66621cSBarry Smith   if (!func) PetscCall(DMSNESSetFunction(dm, SNESTSFormFunction, ts));
26131e66621cSBarry Smith 
2614a6772fa2SLisandro Dalcin   /* If the SNES doesn't have a jacobian set and the TS has an ijacobian or rhsjacobian set, set the SNES to use it.
26156c6b9e74SPeter Brune      Otherwise, the SNES will use coloring internally to form the Jacobian.
26166c6b9e74SPeter Brune    */
26179566063dSJacob Faibussowitsch   PetscCall(DMSNESGetJacobian(dm, &jac, NULL));
26189566063dSJacob Faibussowitsch   PetscCall(DMTSGetIJacobian(dm, &ijac, NULL));
26199566063dSJacob Faibussowitsch   PetscCall(DMTSGetI2Jacobian(dm, &i2jac, NULL));
26209566063dSJacob Faibussowitsch   PetscCall(DMTSGetRHSJacobian(dm, &rhsjac, NULL));
26211e66621cSBarry Smith   if (!jac && (ijac || i2jac || rhsjac)) PetscCall(DMSNESSetJacobian(dm, SNESTSFormJacobian, ts));
2622c0517034SDebojyoti Ghosh 
2623c0517034SDebojyoti Ghosh   /* if time integration scheme has a starting method, call it */
2624dbbe0bcdSBarry Smith   PetscTryTypeMethod(ts, startingmethod);
2625c0517034SDebojyoti Ghosh 
2626277b19d0SLisandro Dalcin   ts->setupcalled = PETSC_TRUE;
26273ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2628277b19d0SLisandro Dalcin }
2629277b19d0SLisandro Dalcin 
2630f6a906c0SBarry Smith /*@
2631bcf0153eSBarry Smith    TSReset - Resets a `TS` context and removes any allocated `Vec`s and `Mat`s.
2632277b19d0SLisandro Dalcin 
2633c3339decSBarry Smith    Collective
2634277b19d0SLisandro Dalcin 
2635277b19d0SLisandro Dalcin    Input Parameter:
2636bcf0153eSBarry Smith .  ts - the `TS` context obtained from `TSCreate()`
2637277b19d0SLisandro Dalcin 
2638277b19d0SLisandro Dalcin    Level: beginner
2639277b19d0SLisandro Dalcin 
2640bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSCreate()`, `TSSetup()`, `TSDestroy()`
2641277b19d0SLisandro Dalcin @*/
2642d71ae5a4SJacob Faibussowitsch PetscErrorCode TSReset(TS ts)
2643d71ae5a4SJacob Faibussowitsch {
26441d06f6b3SHong Zhang   TS_RHSSplitLink ilink = ts->tsrhssplit, next;
2645277b19d0SLisandro Dalcin 
2646277b19d0SLisandro Dalcin   PetscFunctionBegin;
2647277b19d0SLisandro Dalcin   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
2648b18ea86cSHong Zhang 
2649dbbe0bcdSBarry Smith   PetscTryTypeMethod(ts, reset);
26509566063dSJacob Faibussowitsch   if (ts->snes) PetscCall(SNESReset(ts->snes));
26519566063dSJacob Faibussowitsch   if (ts->adapt) PetscCall(TSAdaptReset(ts->adapt));
2652bbd56ea5SKarl Rupp 
26539566063dSJacob Faibussowitsch   PetscCall(MatDestroy(&ts->Arhs));
26549566063dSJacob Faibussowitsch   PetscCall(MatDestroy(&ts->Brhs));
26559566063dSJacob Faibussowitsch   PetscCall(VecDestroy(&ts->Frhs));
26569566063dSJacob Faibussowitsch   PetscCall(VecDestroy(&ts->vec_sol));
26579566063dSJacob Faibussowitsch   PetscCall(VecDestroy(&ts->vec_dot));
26589566063dSJacob Faibussowitsch   PetscCall(VecDestroy(&ts->vatol));
26599566063dSJacob Faibussowitsch   PetscCall(VecDestroy(&ts->vrtol));
26609566063dSJacob Faibussowitsch   PetscCall(VecDestroyVecs(ts->nwork, &ts->work));
2661bbd56ea5SKarl Rupp 
26629566063dSJacob Faibussowitsch   PetscCall(MatDestroy(&ts->Jacprhs));
26639566063dSJacob Faibussowitsch   PetscCall(MatDestroy(&ts->Jacp));
26641baa6e33SBarry Smith   if (ts->forward_solve) PetscCall(TSForwardReset(ts));
2665cd4cee2dSHong Zhang   if (ts->quadraturets) {
26669566063dSJacob Faibussowitsch     PetscCall(TSReset(ts->quadraturets));
26679566063dSJacob Faibussowitsch     PetscCall(VecDestroy(&ts->vec_costintegrand));
2668cd4cee2dSHong Zhang   }
26691d06f6b3SHong Zhang   while (ilink) {
26701d06f6b3SHong Zhang     next = ilink->next;
26719566063dSJacob Faibussowitsch     PetscCall(TSDestroy(&ilink->ts));
26729566063dSJacob Faibussowitsch     PetscCall(PetscFree(ilink->splitname));
26739566063dSJacob Faibussowitsch     PetscCall(ISDestroy(&ilink->is));
26749566063dSJacob Faibussowitsch     PetscCall(PetscFree(ilink));
26751d06f6b3SHong Zhang     ilink = next;
267687f4e208SHong Zhang   }
26776bf673ebSJoe Pusztay   ts->tsrhssplit     = NULL;
2678545aaa6fSHong Zhang   ts->num_rhs_splits = 0;
26794a658b32SHong Zhang   if (ts->tspan) {
26804a658b32SHong Zhang     PetscCall(PetscFree(ts->tspan->span_times));
26814a658b32SHong Zhang     PetscCall(VecDestroyVecs(ts->tspan->num_span_times, &ts->tspan->vecs_sol));
26824a658b32SHong Zhang     PetscCall(PetscFree(ts->tspan));
26834a658b32SHong Zhang   }
2684277b19d0SLisandro Dalcin   ts->setupcalled = PETSC_FALSE;
26853ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2686d763cef2SBarry Smith }
2687d763cef2SBarry Smith 
26881fb7b255SJunchao Zhang /*@C
2689d763cef2SBarry Smith    TSDestroy - Destroys the timestepper context that was created
2690bcf0153eSBarry Smith    with `TSCreate()`.
2691d763cef2SBarry Smith 
2692c3339decSBarry Smith    Collective
2693d763cef2SBarry Smith 
2694d763cef2SBarry Smith    Input Parameter:
2695bcf0153eSBarry Smith .  ts - the `TS` context obtained from `TSCreate()`
2696d763cef2SBarry Smith 
2697d763cef2SBarry Smith    Level: beginner
2698d763cef2SBarry Smith 
2699bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSCreate()`, `TSSetUp()`, `TSSolve()`
2700d763cef2SBarry Smith @*/
2701d71ae5a4SJacob Faibussowitsch PetscErrorCode TSDestroy(TS *ts)
2702d71ae5a4SJacob Faibussowitsch {
2703d763cef2SBarry Smith   PetscFunctionBegin;
27043ba16761SJacob Faibussowitsch   if (!*ts) PetscFunctionReturn(PETSC_SUCCESS);
2705ecf68647SHong Zhang   PetscValidHeaderSpecific(*ts, TS_CLASSID, 1);
27069371c9d4SSatish Balay   if (--((PetscObject)(*ts))->refct > 0) {
27079371c9d4SSatish Balay     *ts = NULL;
27083ba16761SJacob Faibussowitsch     PetscFunctionReturn(PETSC_SUCCESS);
27099371c9d4SSatish Balay   }
2710d763cef2SBarry Smith 
27119566063dSJacob Faibussowitsch   PetscCall(TSReset(*ts));
27129566063dSJacob Faibussowitsch   PetscCall(TSAdjointReset(*ts));
27131e66621cSBarry Smith   if ((*ts)->forward_solve) PetscCall(TSForwardReset(*ts));
27141e66621cSBarry Smith 
2715e04113cfSBarry Smith   /* if memory was published with SAWs then destroy it */
27169566063dSJacob Faibussowitsch   PetscCall(PetscObjectSAWsViewOff((PetscObject)*ts));
2717dbbe0bcdSBarry Smith   PetscTryTypeMethod((*ts), destroy);
27186d4c513bSLisandro Dalcin 
27199566063dSJacob Faibussowitsch   PetscCall(TSTrajectoryDestroy(&(*ts)->trajectory));
2720bc952696SBarry Smith 
27219566063dSJacob Faibussowitsch   PetscCall(TSAdaptDestroy(&(*ts)->adapt));
27229566063dSJacob Faibussowitsch   PetscCall(TSEventDestroy(&(*ts)->event));
27236427ac75SLisandro Dalcin 
27249566063dSJacob Faibussowitsch   PetscCall(SNESDestroy(&(*ts)->snes));
27259566063dSJacob Faibussowitsch   PetscCall(DMDestroy(&(*ts)->dm));
27269566063dSJacob Faibussowitsch   PetscCall(TSMonitorCancel((*ts)));
27279566063dSJacob Faibussowitsch   PetscCall(TSAdjointMonitorCancel((*ts)));
27286d4c513bSLisandro Dalcin 
27299566063dSJacob Faibussowitsch   PetscCall(TSDestroy(&(*ts)->quadraturets));
27309566063dSJacob Faibussowitsch   PetscCall(PetscHeaderDestroy(ts));
27313ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2732d763cef2SBarry Smith }
2733d763cef2SBarry Smith 
2734d8e5e3e6SSatish Balay /*@
2735bcf0153eSBarry Smith    TSGetSNES - Returns the `SNES` (nonlinear solver) associated with
2736bcf0153eSBarry Smith    a `TS` (timestepper) context. Valid only for nonlinear problems.
2737d763cef2SBarry Smith 
2738bcf0153eSBarry Smith    Not Collective, but snes is parallel if ts is parallel
2739d763cef2SBarry Smith 
2740d763cef2SBarry Smith    Input Parameter:
2741bcf0153eSBarry Smith .  ts - the `TS` context obtained from `TSCreate()`
2742d763cef2SBarry Smith 
2743d763cef2SBarry Smith    Output Parameter:
2744d763cef2SBarry Smith .  snes - the nonlinear solver context
2745d763cef2SBarry Smith 
2746d763cef2SBarry Smith    Level: beginner
2747d763cef2SBarry Smith 
2748bcf0153eSBarry Smith    Notes:
2749bcf0153eSBarry Smith    The user can then directly manipulate the `SNES` context to set various
2750bcf0153eSBarry Smith    options, etc.  Likewise, the user can then extract and manipulate the
2751bcf0153eSBarry Smith    `KSP`, and `PC` contexts as well.
2752bcf0153eSBarry Smith 
2753bcf0153eSBarry Smith    `TSGetSNES()` does not work for integrators that do not use `SNES`; in
2754195e9b02SBarry Smith    this case `TSGetSNES()` returns `NULL` in `snes`.
2755bcf0153eSBarry Smith 
2756bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `SNES`, `TSCreate()`, `TSSetUp()`, `TSSolve()`
2757d763cef2SBarry Smith @*/
2758d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetSNES(TS ts, SNES *snes)
2759d71ae5a4SJacob Faibussowitsch {
2760d763cef2SBarry Smith   PetscFunctionBegin;
27610700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
27624482741eSBarry Smith   PetscValidPointer(snes, 2);
2763d372ba47SLisandro Dalcin   if (!ts->snes) {
27649566063dSJacob Faibussowitsch     PetscCall(SNESCreate(PetscObjectComm((PetscObject)ts), &ts->snes));
27659566063dSJacob Faibussowitsch     PetscCall(PetscObjectSetOptions((PetscObject)ts->snes, ((PetscObject)ts)->options));
27669566063dSJacob Faibussowitsch     PetscCall(SNESSetFunction(ts->snes, NULL, SNESTSFormFunction, ts));
27679566063dSJacob Faibussowitsch     PetscCall(PetscObjectIncrementTabLevel((PetscObject)ts->snes, (PetscObject)ts, 1));
27689566063dSJacob Faibussowitsch     if (ts->dm) PetscCall(SNESSetDM(ts->snes, ts->dm));
27691e66621cSBarry Smith     if (ts->problem_type == TS_LINEAR) PetscCall(SNESSetType(ts->snes, SNESKSPONLY));
2770d372ba47SLisandro Dalcin   }
2771d763cef2SBarry Smith   *snes = ts->snes;
27723ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2773d763cef2SBarry Smith }
2774d763cef2SBarry Smith 
2775deb2cd25SJed Brown /*@
2776bcf0153eSBarry Smith    TSSetSNES - Set the `SNES` (nonlinear solver) to be used by the timestepping context
2777deb2cd25SJed Brown 
2778deb2cd25SJed Brown    Collective
2779deb2cd25SJed Brown 
2780d8d19677SJose E. Roman    Input Parameters:
2781bcf0153eSBarry Smith +  ts - the `TS` context obtained from `TSCreate()`
2782deb2cd25SJed Brown -  snes - the nonlinear solver context
2783deb2cd25SJed Brown 
2784deb2cd25SJed Brown    Level: developer
2785deb2cd25SJed Brown 
2786bcf0153eSBarry Smith    Note:
2787bcf0153eSBarry Smith    Most users should have the `TS` created by calling `TSGetSNES()`
2788bcf0153eSBarry Smith 
2789bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `SNES`, `TSCreate()`, `TSSetUp()`, `TSSolve()`, `TSGetSNES()`
2790deb2cd25SJed Brown @*/
2791d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetSNES(TS ts, SNES snes)
2792d71ae5a4SJacob Faibussowitsch {
2793d1e9a80fSBarry Smith   PetscErrorCode (*func)(SNES, Vec, Mat, Mat, void *);
2794deb2cd25SJed Brown 
2795deb2cd25SJed Brown   PetscFunctionBegin;
2796deb2cd25SJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
2797deb2cd25SJed Brown   PetscValidHeaderSpecific(snes, SNES_CLASSID, 2);
27989566063dSJacob Faibussowitsch   PetscCall(PetscObjectReference((PetscObject)snes));
27999566063dSJacob Faibussowitsch   PetscCall(SNESDestroy(&ts->snes));
2800bbd56ea5SKarl Rupp 
2801deb2cd25SJed Brown   ts->snes = snes;
2802bbd56ea5SKarl Rupp 
28039566063dSJacob Faibussowitsch   PetscCall(SNESSetFunction(ts->snes, NULL, SNESTSFormFunction, ts));
28049566063dSJacob Faibussowitsch   PetscCall(SNESGetJacobian(ts->snes, NULL, NULL, &func, NULL));
28051e66621cSBarry Smith   if (func == SNESTSFormJacobian) PetscCall(SNESSetJacobian(ts->snes, NULL, NULL, SNESTSFormJacobian, ts));
28063ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2807deb2cd25SJed Brown }
2808deb2cd25SJed Brown 
2809d8e5e3e6SSatish Balay /*@
2810bcf0153eSBarry Smith    TSGetKSP - Returns the `KSP` (linear solver) associated with
2811bcf0153eSBarry Smith    a `TS` (timestepper) context.
2812d763cef2SBarry Smith 
2813195e9b02SBarry Smith    Not Collective, but `ksp` is parallel if `ts` is parallel
2814d763cef2SBarry Smith 
2815d763cef2SBarry Smith    Input Parameter:
2816bcf0153eSBarry Smith .  ts - the `TS` context obtained from `TSCreate()`
2817d763cef2SBarry Smith 
2818d763cef2SBarry Smith    Output Parameter:
281994b7f48cSBarry Smith .  ksp - the nonlinear solver context
2820d763cef2SBarry Smith 
2821d763cef2SBarry Smith    Level: beginner
2822d763cef2SBarry Smith 
2823bcf0153eSBarry Smith    Notes:
2824bcf0153eSBarry Smith    The user can then directly manipulate the `KSP` context to set various
2825bcf0153eSBarry Smith    options, etc.  Likewise, the user can then extract and manipulate the
2826bcf0153eSBarry Smith    `PC` context as well.
2827bcf0153eSBarry Smith 
2828bcf0153eSBarry Smith    `TSGetKSP()` does not work for integrators that do not use `KSP`;
2829195e9b02SBarry Smith    in this case `TSGetKSP()` returns `NULL` in `ksp`.
2830bcf0153eSBarry Smith 
2831bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `SNES`, `KSP`, `TSCreate()`, `TSSetUp()`, `TSSolve()`, `TSGetSNES()`
2832d763cef2SBarry Smith @*/
2833d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetKSP(TS ts, KSP *ksp)
2834d71ae5a4SJacob Faibussowitsch {
2835089b2837SJed Brown   SNES snes;
2836d372ba47SLisandro Dalcin 
2837d763cef2SBarry Smith   PetscFunctionBegin;
28380700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
28394482741eSBarry Smith   PetscValidPointer(ksp, 2);
28403c633725SBarry Smith   PetscCheck(((PetscObject)ts)->type_name, PETSC_COMM_SELF, PETSC_ERR_ARG_NULL, "KSP is not created yet. Call TSSetType() first");
28413c633725SBarry Smith   PetscCheck(ts->problem_type == TS_LINEAR, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Linear only; use TSGetSNES()");
28429566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts, &snes));
28439566063dSJacob Faibussowitsch   PetscCall(SNESGetKSP(snes, ksp));
28443ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2845d763cef2SBarry Smith }
2846d763cef2SBarry Smith 
2847d763cef2SBarry Smith /* ----------- Routines to set solver parameters ---------- */
2848d763cef2SBarry Smith 
2849adb62b0dSMatthew Knepley /*@
2850618ce8baSLisandro Dalcin    TSSetMaxSteps - Sets the maximum number of steps to use.
2851618ce8baSLisandro Dalcin 
2852c3339decSBarry Smith    Logically Collective
2853618ce8baSLisandro Dalcin 
2854618ce8baSLisandro Dalcin    Input Parameters:
2855bcf0153eSBarry Smith +  ts - the `TS` context obtained from `TSCreate()`
2856618ce8baSLisandro Dalcin -  maxsteps - maximum number of steps to use
2857618ce8baSLisandro Dalcin 
2858bcf0153eSBarry Smith    Options Database Key:
2859618ce8baSLisandro Dalcin .  -ts_max_steps <maxsteps> - Sets maxsteps
2860618ce8baSLisandro Dalcin 
2861618ce8baSLisandro Dalcin    Level: intermediate
2862618ce8baSLisandro Dalcin 
2863bcf0153eSBarry Smith    Note:
2864bcf0153eSBarry Smith    The default maximum number of steps is 5000
2865bcf0153eSBarry Smith 
2866bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSGetMaxSteps()`, `TSSetMaxTime()`, `TSSetExactFinalTime()`
2867618ce8baSLisandro Dalcin @*/
2868d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetMaxSteps(TS ts, PetscInt maxsteps)
2869d71ae5a4SJacob Faibussowitsch {
2870618ce8baSLisandro Dalcin   PetscFunctionBegin;
2871618ce8baSLisandro Dalcin   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
2872618ce8baSLisandro Dalcin   PetscValidLogicalCollectiveInt(ts, maxsteps, 2);
28733c633725SBarry Smith   PetscCheck(maxsteps >= 0, PetscObjectComm((PetscObject)ts), PETSC_ERR_ARG_OUTOFRANGE, "Maximum number of steps must be non-negative");
2874618ce8baSLisandro Dalcin   ts->max_steps = maxsteps;
28753ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2876618ce8baSLisandro Dalcin }
2877618ce8baSLisandro Dalcin 
2878618ce8baSLisandro Dalcin /*@
2879618ce8baSLisandro Dalcin    TSGetMaxSteps - Gets the maximum number of steps to use.
2880618ce8baSLisandro Dalcin 
2881618ce8baSLisandro Dalcin    Not Collective
2882618ce8baSLisandro Dalcin 
2883618ce8baSLisandro Dalcin    Input Parameters:
2884bcf0153eSBarry Smith .  ts - the `TS` context obtained from `TSCreate()`
2885618ce8baSLisandro Dalcin 
2886618ce8baSLisandro Dalcin    Output Parameter:
2887618ce8baSLisandro Dalcin .  maxsteps - maximum number of steps to use
2888618ce8baSLisandro Dalcin 
2889618ce8baSLisandro Dalcin    Level: advanced
2890618ce8baSLisandro Dalcin 
2891bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSSetMaxSteps()`, `TSGetMaxTime()`, `TSSetMaxTime()`
2892618ce8baSLisandro Dalcin @*/
2893d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetMaxSteps(TS ts, PetscInt *maxsteps)
2894d71ae5a4SJacob Faibussowitsch {
2895618ce8baSLisandro Dalcin   PetscFunctionBegin;
2896618ce8baSLisandro Dalcin   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
2897618ce8baSLisandro Dalcin   PetscValidIntPointer(maxsteps, 2);
2898618ce8baSLisandro Dalcin   *maxsteps = ts->max_steps;
28993ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2900618ce8baSLisandro Dalcin }
2901618ce8baSLisandro Dalcin 
2902618ce8baSLisandro Dalcin /*@
2903618ce8baSLisandro Dalcin    TSSetMaxTime - Sets the maximum (or final) time for timestepping.
2904618ce8baSLisandro Dalcin 
2905c3339decSBarry Smith    Logically Collective
2906618ce8baSLisandro Dalcin 
2907618ce8baSLisandro Dalcin    Input Parameters:
2908bcf0153eSBarry Smith +  ts - the `TS` context obtained from `TSCreate()`
2909618ce8baSLisandro Dalcin -  maxtime - final time to step to
2910618ce8baSLisandro Dalcin 
2911bcf0153eSBarry Smith    Options Database Key:
2912ef85077eSLisandro Dalcin .  -ts_max_time <maxtime> - Sets maxtime
2913618ce8baSLisandro Dalcin 
2914bcf0153eSBarry Smith    Level: intermediate
2915bcf0153eSBarry Smith 
2916618ce8baSLisandro Dalcin    Notes:
2917618ce8baSLisandro Dalcin    The default maximum time is 5.0
2918618ce8baSLisandro Dalcin 
2919bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSGetMaxTime()`, `TSSetMaxSteps()`, `TSSetExactFinalTime()`
2920618ce8baSLisandro Dalcin @*/
2921d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetMaxTime(TS ts, PetscReal maxtime)
2922d71ae5a4SJacob Faibussowitsch {
2923618ce8baSLisandro Dalcin   PetscFunctionBegin;
2924618ce8baSLisandro Dalcin   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
2925618ce8baSLisandro Dalcin   PetscValidLogicalCollectiveReal(ts, maxtime, 2);
2926618ce8baSLisandro Dalcin   ts->max_time = maxtime;
29273ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2928618ce8baSLisandro Dalcin }
2929618ce8baSLisandro Dalcin 
2930618ce8baSLisandro Dalcin /*@
2931618ce8baSLisandro Dalcin    TSGetMaxTime - Gets the maximum (or final) time for timestepping.
2932618ce8baSLisandro Dalcin 
2933618ce8baSLisandro Dalcin    Not Collective
2934618ce8baSLisandro Dalcin 
2935618ce8baSLisandro Dalcin    Input Parameters:
2936bcf0153eSBarry Smith .  ts - the `TS` context obtained from `TSCreate()`
2937618ce8baSLisandro Dalcin 
2938618ce8baSLisandro Dalcin    Output Parameter:
2939618ce8baSLisandro Dalcin .  maxtime - final time to step to
2940618ce8baSLisandro Dalcin 
2941618ce8baSLisandro Dalcin    Level: advanced
2942618ce8baSLisandro Dalcin 
2943bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSSetMaxTime()`, `TSGetMaxSteps()`, `TSSetMaxSteps()`
2944618ce8baSLisandro Dalcin @*/
2945d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetMaxTime(TS ts, PetscReal *maxtime)
2946d71ae5a4SJacob Faibussowitsch {
2947618ce8baSLisandro Dalcin   PetscFunctionBegin;
2948618ce8baSLisandro Dalcin   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
2949618ce8baSLisandro Dalcin   PetscValidRealPointer(maxtime, 2);
2950618ce8baSLisandro Dalcin   *maxtime = ts->max_time;
29513ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2952618ce8baSLisandro Dalcin }
2953618ce8baSLisandro Dalcin 
2954618ce8baSLisandro Dalcin /*@
2955bcf0153eSBarry Smith    TSSetInitialTimeStep - Deprecated, use `TSSetTime()` and `TSSetTimeStep()`.
2956edc382c3SSatish Balay 
2957edc382c3SSatish Balay    Level: deprecated
2958edc382c3SSatish Balay 
2959aaa6c58dSLisandro Dalcin @*/
2960d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetInitialTimeStep(TS ts, PetscReal initial_time, PetscReal time_step)
2961d71ae5a4SJacob Faibussowitsch {
2962aaa6c58dSLisandro Dalcin   PetscFunctionBegin;
2963aaa6c58dSLisandro Dalcin   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
29649566063dSJacob Faibussowitsch   PetscCall(TSSetTime(ts, initial_time));
29659566063dSJacob Faibussowitsch   PetscCall(TSSetTimeStep(ts, time_step));
29663ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2967aaa6c58dSLisandro Dalcin }
2968aaa6c58dSLisandro Dalcin 
2969aaa6c58dSLisandro Dalcin /*@
2970bcf0153eSBarry Smith    TSGetDuration - Deprecated, use `TSGetMaxSteps()` and `TSGetMaxTime()`.
2971edc382c3SSatish Balay 
2972edc382c3SSatish Balay    Level: deprecated
2973edc382c3SSatish Balay 
2974adb62b0dSMatthew Knepley @*/
2975d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetDuration(TS ts, PetscInt *maxsteps, PetscReal *maxtime)
2976d71ae5a4SJacob Faibussowitsch {
2977adb62b0dSMatthew Knepley   PetscFunctionBegin;
29780700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
2979abc0a331SBarry Smith   if (maxsteps) {
29804482741eSBarry Smith     PetscValidIntPointer(maxsteps, 2);
2981adb62b0dSMatthew Knepley     *maxsteps = ts->max_steps;
2982adb62b0dSMatthew Knepley   }
2983abc0a331SBarry Smith   if (maxtime) {
2984064a246eSJacob Faibussowitsch     PetscValidRealPointer(maxtime, 3);
2985adb62b0dSMatthew Knepley     *maxtime = ts->max_time;
2986adb62b0dSMatthew Knepley   }
29873ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2988adb62b0dSMatthew Knepley }
2989adb62b0dSMatthew Knepley 
2990d763cef2SBarry Smith /*@
2991bcf0153eSBarry Smith    TSSetDuration - Deprecated, use `TSSetMaxSteps()` and `TSSetMaxTime()`.
2992edc382c3SSatish Balay 
2993edc382c3SSatish Balay    Level: deprecated
2994edc382c3SSatish Balay 
2995d763cef2SBarry Smith @*/
2996d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetDuration(TS ts, PetscInt maxsteps, PetscReal maxtime)
2997d71ae5a4SJacob Faibussowitsch {
2998d763cef2SBarry Smith   PetscFunctionBegin;
29990700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3000c5eb9154SBarry Smith   PetscValidLogicalCollectiveInt(ts, maxsteps, 2);
3001064a246eSJacob Faibussowitsch   PetscValidLogicalCollectiveReal(ts, maxtime, 3);
300239b7ec4bSSean Farley   if (maxsteps >= 0) ts->max_steps = maxsteps;
300313bcc0bdSJacob Faibussowitsch   if (maxtime != (PetscReal)PETSC_DEFAULT) ts->max_time = maxtime;
30043ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
3005d763cef2SBarry Smith }
3006d763cef2SBarry Smith 
3007d763cef2SBarry Smith /*@
3008bcf0153eSBarry Smith    TSGetTimeStepNumber - Deprecated, use `TSGetStepNumber()`.
3009edc382c3SSatish Balay 
3010edc382c3SSatish Balay    Level: deprecated
3011edc382c3SSatish Balay 
30125c5f5948SLisandro Dalcin @*/
3013d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetTimeStepNumber(TS ts, PetscInt *steps)
3014d71ae5a4SJacob Faibussowitsch {
30159371c9d4SSatish Balay   return TSGetStepNumber(ts, steps);
30169371c9d4SSatish Balay }
30175c5f5948SLisandro Dalcin 
301819eac22cSLisandro Dalcin /*@
3019bcf0153eSBarry Smith    TSGetTotalSteps - Deprecated, use `TSGetStepNumber()`.
3020edc382c3SSatish Balay 
3021edc382c3SSatish Balay    Level: deprecated
3022edc382c3SSatish Balay 
30234f4e0956SLisandro Dalcin @*/
3024d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetTotalSteps(TS ts, PetscInt *steps)
3025d71ae5a4SJacob Faibussowitsch {
30269371c9d4SSatish Balay   return TSGetStepNumber(ts, steps);
30279371c9d4SSatish Balay }
30284f4e0956SLisandro Dalcin 
30294f4e0956SLisandro Dalcin /*@
3030d763cef2SBarry Smith    TSSetSolution - Sets the initial solution vector
3031bcf0153eSBarry Smith    for use by the `TS` routines.
3032d763cef2SBarry Smith 
3033c3339decSBarry Smith    Logically Collective
3034d763cef2SBarry Smith 
3035d763cef2SBarry Smith    Input Parameters:
3036bcf0153eSBarry Smith +  ts - the `TS` context obtained from `TSCreate()`
30370910c330SBarry Smith -  u - the solution vector
3038d763cef2SBarry Smith 
3039d763cef2SBarry Smith    Level: beginner
3040d763cef2SBarry Smith 
3041bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSSetSolutionFunction()`, `TSGetSolution()`, `TSCreate()`
3042d763cef2SBarry Smith @*/
3043d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetSolution(TS ts, Vec u)
3044d71ae5a4SJacob Faibussowitsch {
3045496e6a7aSJed Brown   DM dm;
30468737fe31SLisandro Dalcin 
3047d763cef2SBarry Smith   PetscFunctionBegin;
30480700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
30490910c330SBarry Smith   PetscValidHeaderSpecific(u, VEC_CLASSID, 2);
30509566063dSJacob Faibussowitsch   PetscCall(PetscObjectReference((PetscObject)u));
30519566063dSJacob Faibussowitsch   PetscCall(VecDestroy(&ts->vec_sol));
30520910c330SBarry Smith   ts->vec_sol = u;
3053bbd56ea5SKarl Rupp 
30549566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
30559566063dSJacob Faibussowitsch   PetscCall(DMShellSetGlobalVector(dm, u));
30563ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
3057d763cef2SBarry Smith }
3058d763cef2SBarry Smith 
3059ac226902SBarry Smith /*@C
3060000e7ae3SMatthew Knepley   TSSetPreStep - Sets the general-purpose function
30613f2090d5SJed Brown   called once at the beginning of each time step.
3062000e7ae3SMatthew Knepley 
3063c3339decSBarry Smith   Logically Collective
3064000e7ae3SMatthew Knepley 
3065000e7ae3SMatthew Knepley   Input Parameters:
3066bcf0153eSBarry Smith + ts   - The `TS` context obtained from `TSCreate()`
3067000e7ae3SMatthew Knepley - func - The function
3068000e7ae3SMatthew Knepley 
3069000e7ae3SMatthew Knepley   Calling sequence of func:
307067b8a455SSatish Balay .vb
307167b8a455SSatish Balay   PetscErrorCode func (TS ts);
307267b8a455SSatish Balay .ve
3073000e7ae3SMatthew Knepley 
3074000e7ae3SMatthew Knepley   Level: intermediate
3075000e7ae3SMatthew Knepley 
3076bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSSetPreStage()`, `TSSetPostStage()`, `TSSetPostStep()`, `TSStep()`, `TSRestartStep()`
3077000e7ae3SMatthew Knepley @*/
3078d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetPreStep(TS ts, PetscErrorCode (*func)(TS))
3079d71ae5a4SJacob Faibussowitsch {
3080000e7ae3SMatthew Knepley   PetscFunctionBegin;
30810700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3082ae60f76fSBarry Smith   ts->prestep = func;
30833ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
3084000e7ae3SMatthew Knepley }
3085000e7ae3SMatthew Knepley 
308609ee8438SJed Brown /*@
3087bcf0153eSBarry Smith   TSPreStep - Runs the user-defined pre-step function provided with `TSSetPreStep()`
30883f2090d5SJed Brown 
3089c3339decSBarry Smith   Collective
30903f2090d5SJed Brown 
30913f2090d5SJed Brown   Input Parameters:
3092bcf0153eSBarry Smith . ts   - The `TS` context obtained from `TSCreate()`
30933f2090d5SJed Brown 
30943f2090d5SJed Brown   Level: developer
30953f2090d5SJed Brown 
3096bcf0153eSBarry Smith   Note:
3097bcf0153eSBarry Smith   `TSPreStep()` is typically used within time stepping implementations,
3098bcf0153eSBarry Smith   so most users would not generally call this routine themselves.
3099bcf0153eSBarry Smith 
3100bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSSetPreStep()`, `TSPreStage()`, `TSPostStage()`, `TSPostStep()`
31013f2090d5SJed Brown @*/
3102d71ae5a4SJacob Faibussowitsch PetscErrorCode TSPreStep(TS ts)
3103d71ae5a4SJacob Faibussowitsch {
31043f2090d5SJed Brown   PetscFunctionBegin;
31050700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3106ae60f76fSBarry Smith   if (ts->prestep) {
31075efd42a4SStefano Zampini     Vec              U;
3108ef8d1ce0SJohann Rudi     PetscObjectId    idprev;
3109ef8d1ce0SJohann Rudi     PetscBool        sameObject;
31105efd42a4SStefano Zampini     PetscObjectState sprev, spost;
31115efd42a4SStefano Zampini 
31129566063dSJacob Faibussowitsch     PetscCall(TSGetSolution(ts, &U));
31139566063dSJacob Faibussowitsch     PetscCall(PetscObjectGetId((PetscObject)U, &idprev));
31149566063dSJacob Faibussowitsch     PetscCall(PetscObjectStateGet((PetscObject)U, &sprev));
311525e27a38SBarry Smith     PetscCallBack("TS callback preset", (*ts->prestep)(ts));
31169566063dSJacob Faibussowitsch     PetscCall(TSGetSolution(ts, &U));
31179566063dSJacob Faibussowitsch     PetscCall(PetscObjectCompareId((PetscObject)U, idprev, &sameObject));
31189566063dSJacob Faibussowitsch     PetscCall(PetscObjectStateGet((PetscObject)U, &spost));
31199566063dSJacob Faibussowitsch     if (!sameObject || sprev != spost) PetscCall(TSRestartStep(ts));
3120312ce896SJed Brown   }
31213ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
31223f2090d5SJed Brown }
31233f2090d5SJed Brown 
3124b8123daeSJed Brown /*@C
3125b8123daeSJed Brown   TSSetPreStage - Sets the general-purpose function
3126b8123daeSJed Brown   called once at the beginning of each stage.
3127b8123daeSJed Brown 
3128c3339decSBarry Smith   Logically Collective
3129b8123daeSJed Brown 
3130b8123daeSJed Brown   Input Parameters:
3131bcf0153eSBarry Smith + ts   - The `TS` context obtained from `TSCreate()`
3132b8123daeSJed Brown - func - The function
3133b8123daeSJed Brown 
3134b8123daeSJed Brown   Calling sequence of func:
313567b8a455SSatish Balay .vb
313667b8a455SSatish Balay   PetscErrorCode func(TS ts, PetscReal stagetime);
313767b8a455SSatish Balay .ve
3138b8123daeSJed Brown 
3139b8123daeSJed Brown   Level: intermediate
3140b8123daeSJed Brown 
3141b8123daeSJed Brown   Note:
3142b8123daeSJed Brown   There may be several stages per time step. If the solve for a given stage fails, the step may be rejected and retried.
3143bcf0153eSBarry Smith   The time step number being computed can be queried using `TSGetStepNumber()` and the total size of the step being
3144bcf0153eSBarry Smith   attempted can be obtained using `TSGetTimeStep()`. The time at the start of the step is available via `TSGetTime()`.
3145b8123daeSJed Brown 
3146bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSSetPostStage()`, `TSSetPreStep()`, `TSSetPostStep()`, `TSGetApplicationContext()`
3147b8123daeSJed Brown @*/
3148d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetPreStage(TS ts, PetscErrorCode (*func)(TS, PetscReal))
3149d71ae5a4SJacob Faibussowitsch {
3150b8123daeSJed Brown   PetscFunctionBegin;
3151b8123daeSJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3152ae60f76fSBarry Smith   ts->prestage = func;
31533ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
3154b8123daeSJed Brown }
3155b8123daeSJed Brown 
31569be3e283SDebojyoti Ghosh /*@C
3157bcf0153eSBarry Smith   TSSetPostStage - Sets the general-purpose function, provided with `TSSetPostStep()`,
31589be3e283SDebojyoti Ghosh   called once at the end of each stage.
31599be3e283SDebojyoti Ghosh 
3160c3339decSBarry Smith   Logically Collective
31619be3e283SDebojyoti Ghosh 
31629be3e283SDebojyoti Ghosh   Input Parameters:
3163bcf0153eSBarry Smith + ts   - The `TS` context obtained from `TSCreate()`
31649be3e283SDebojyoti Ghosh - func - The function
31659be3e283SDebojyoti Ghosh 
31669be3e283SDebojyoti Ghosh   Calling sequence of func:
316767b8a455SSatish Balay .vb
316867b8a455SSatish Balay   PetscErrorCode func(TS ts, PetscReal stagetime, PetscInt stageindex, Vec* Y);
316967b8a455SSatish Balay .ve
31709be3e283SDebojyoti Ghosh 
31719be3e283SDebojyoti Ghosh   Level: intermediate
31729be3e283SDebojyoti Ghosh 
31739be3e283SDebojyoti Ghosh   Note:
31749be3e283SDebojyoti Ghosh   There may be several stages per time step. If the solve for a given stage fails, the step may be rejected and retried.
3175bcf0153eSBarry Smith   The time step number being computed can be queried using `TSGetStepNumber()` and the total size of the step being
3176bcf0153eSBarry Smith   attempted can be obtained using `TSGetTimeStep()`. The time at the start of the step is available via `TSGetTime()`.
31779be3e283SDebojyoti Ghosh 
3178bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSSetPreStage()`, `TSSetPreStep()`, `TSSetPostStep()`, `TSGetApplicationContext()`
31799be3e283SDebojyoti Ghosh @*/
3180d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetPostStage(TS ts, PetscErrorCode (*func)(TS, PetscReal, PetscInt, Vec *))
3181d71ae5a4SJacob Faibussowitsch {
31829be3e283SDebojyoti Ghosh   PetscFunctionBegin;
31839be3e283SDebojyoti Ghosh   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
31849be3e283SDebojyoti Ghosh   ts->poststage = func;
31853ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
31869be3e283SDebojyoti Ghosh }
31879be3e283SDebojyoti Ghosh 
3188c688d042SShri Abhyankar /*@C
3189c688d042SShri Abhyankar   TSSetPostEvaluate - Sets the general-purpose function
3190c688d042SShri Abhyankar   called once at the end of each step evaluation.
3191c688d042SShri Abhyankar 
3192c3339decSBarry Smith   Logically Collective
3193c688d042SShri Abhyankar 
3194c688d042SShri Abhyankar   Input Parameters:
3195bcf0153eSBarry Smith + ts   - The `TS` context obtained from `TSCreate()`
3196c688d042SShri Abhyankar - func - The function
3197c688d042SShri Abhyankar 
3198c688d042SShri Abhyankar   Calling sequence of func:
319967b8a455SSatish Balay .vb
320067b8a455SSatish Balay   PetscErrorCode func(TS ts);
320167b8a455SSatish Balay .ve
3202c688d042SShri Abhyankar 
3203c688d042SShri Abhyankar   Level: intermediate
3204c688d042SShri Abhyankar 
3205c688d042SShri Abhyankar   Note:
3206bcf0153eSBarry Smith   Semantically, `TSSetPostEvaluate()` differs from `TSSetPostStep()` since the function it sets is called before event-handling
3207bcf0153eSBarry Smith   thus guaranteeing the same solution (computed by the time-stepper) will be passed to it. On the other hand, `TSPostStep()`
3208bcf0153eSBarry Smith   may be passed a different solution, possibly changed by the event handler. `TSPostEvaluate()` is called after the next step
3209bcf0153eSBarry Smith   solution is evaluated allowing to modify it, if need be. The solution can be obtained with `TSGetSolution()`, the time step
3210bcf0153eSBarry Smith   with `TSGetTimeStep()`, and the time at the start of the step is available via `TSGetTime()`
3211c688d042SShri Abhyankar 
3212bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSSetPreStage()`, `TSSetPreStep()`, `TSSetPostStep()`, `TSGetApplicationContext()`
3213c688d042SShri Abhyankar @*/
3214d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetPostEvaluate(TS ts, PetscErrorCode (*func)(TS))
3215d71ae5a4SJacob Faibussowitsch {
3216c688d042SShri Abhyankar   PetscFunctionBegin;
3217c688d042SShri Abhyankar   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3218c688d042SShri Abhyankar   ts->postevaluate = func;
32193ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
3220c688d042SShri Abhyankar }
3221c688d042SShri Abhyankar 
3222b8123daeSJed Brown /*@
3223bcf0153eSBarry Smith   TSPreStage - Runs the user-defined pre-stage function set using `TSSetPreStage()`
3224b8123daeSJed Brown 
3225c3339decSBarry Smith   Collective
3226b8123daeSJed Brown 
3227b8123daeSJed Brown   Input Parameters:
3228bcf0153eSBarry Smith . ts          - The `TS` context obtained from `TSCreate()`
32299be3e283SDebojyoti Ghosh   stagetime   - The absolute time of the current stage
3230b8123daeSJed Brown 
3231b8123daeSJed Brown   Level: developer
3232b8123daeSJed Brown 
3233bcf0153eSBarry Smith   Note:
3234bcf0153eSBarry Smith   `TSPreStage()` is typically used within time stepping implementations,
3235bcf0153eSBarry Smith   most users would not generally call this routine themselves.
3236bcf0153eSBarry Smith 
3237bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSPostStage()`, `TSSetPreStep()`, `TSPreStep()`, `TSPostStep()`
3238b8123daeSJed Brown @*/
3239d71ae5a4SJacob Faibussowitsch PetscErrorCode TSPreStage(TS ts, PetscReal stagetime)
3240d71ae5a4SJacob Faibussowitsch {
3241b8123daeSJed Brown   PetscFunctionBegin;
3242b8123daeSJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
32431e66621cSBarry Smith   if (ts->prestage) PetscCallBack("TS callback prestage", (*ts->prestage)(ts, stagetime));
32443ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
3245b8123daeSJed Brown }
3246b8123daeSJed Brown 
32479be3e283SDebojyoti Ghosh /*@
3248bcf0153eSBarry Smith   TSPostStage - Runs the user-defined post-stage function set using `TSSetPostStage()`
32499be3e283SDebojyoti Ghosh 
3250c3339decSBarry Smith   Collective
32519be3e283SDebojyoti Ghosh 
32529be3e283SDebojyoti Ghosh   Input Parameters:
3253bcf0153eSBarry Smith . ts          - The `TS` context obtained from `TSCreate()`
32549be3e283SDebojyoti Ghosh   stagetime   - The absolute time of the current stage
32559be3e283SDebojyoti Ghosh   stageindex  - Stage number
32569be3e283SDebojyoti Ghosh   Y           - Array of vectors (of size = total number
32579be3e283SDebojyoti Ghosh                 of stages) with the stage solutions
32589be3e283SDebojyoti Ghosh 
32599be3e283SDebojyoti Ghosh   Level: developer
32609be3e283SDebojyoti Ghosh 
3261bcf0153eSBarry Smith   Note:
3262bcf0153eSBarry Smith   `TSPostStage()` is typically used within time stepping implementations,
3263bcf0153eSBarry Smith   most users would not generally call this routine themselves.
3264bcf0153eSBarry Smith 
3265bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSPreStage()`, `TSSetPreStep()`, `TSPreStep()`, `TSPostStep()`
32669be3e283SDebojyoti Ghosh @*/
3267d71ae5a4SJacob Faibussowitsch PetscErrorCode TSPostStage(TS ts, PetscReal stagetime, PetscInt stageindex, Vec *Y)
3268d71ae5a4SJacob Faibussowitsch {
32699be3e283SDebojyoti Ghosh   PetscFunctionBegin;
32709be3e283SDebojyoti Ghosh   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
32711e66621cSBarry Smith   if (ts->poststage) PetscCallBack("TS callback poststage", (*ts->poststage)(ts, stagetime, stageindex, Y));
32723ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
32739be3e283SDebojyoti Ghosh }
32749be3e283SDebojyoti Ghosh 
3275c688d042SShri Abhyankar /*@
3276bcf0153eSBarry Smith   TSPostEvaluate - Runs the user-defined post-evaluate function set using `TSSetPostEvaluate()`
3277c688d042SShri Abhyankar 
3278c3339decSBarry Smith   Collective
3279c688d042SShri Abhyankar 
3280c688d042SShri Abhyankar   Input Parameters:
3281bcf0153eSBarry Smith . ts - The `TS` context obtained from `TSCreate()`
3282c688d042SShri Abhyankar 
3283c688d042SShri Abhyankar   Level: developer
3284c688d042SShri Abhyankar 
3285bcf0153eSBarry Smith   Note:
3286bcf0153eSBarry Smith   `TSPostEvaluate()` is typically used within time stepping implementations,
3287bcf0153eSBarry Smith   most users would not generally call this routine themselves.
3288bcf0153eSBarry Smith 
3289bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSSetPostEvaluate()`, `TSSetPreStep()`, `TSPreStep()`, `TSPostStep()`
3290c688d042SShri Abhyankar @*/
3291d71ae5a4SJacob Faibussowitsch PetscErrorCode TSPostEvaluate(TS ts)
3292d71ae5a4SJacob Faibussowitsch {
3293c688d042SShri Abhyankar   PetscFunctionBegin;
3294c688d042SShri Abhyankar   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3295c688d042SShri Abhyankar   if (ts->postevaluate) {
3296dcb233daSLisandro Dalcin     Vec              U;
3297dcb233daSLisandro Dalcin     PetscObjectState sprev, spost;
3298dcb233daSLisandro Dalcin 
32999566063dSJacob Faibussowitsch     PetscCall(TSGetSolution(ts, &U));
33009566063dSJacob Faibussowitsch     PetscCall(PetscObjectStateGet((PetscObject)U, &sprev));
330125e27a38SBarry Smith     PetscCallBack("TS callback postevaluate", (*ts->postevaluate)(ts));
33029566063dSJacob Faibussowitsch     PetscCall(PetscObjectStateGet((PetscObject)U, &spost));
33039566063dSJacob Faibussowitsch     if (sprev != spost) PetscCall(TSRestartStep(ts));
3304c688d042SShri Abhyankar   }
33053ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
3306c688d042SShri Abhyankar }
3307c688d042SShri Abhyankar 
3308ac226902SBarry Smith /*@C
3309000e7ae3SMatthew Knepley   TSSetPostStep - Sets the general-purpose function
33103f2090d5SJed Brown   called once at the end of each time step.
3311000e7ae3SMatthew Knepley 
3312c3339decSBarry Smith   Logically Collective
3313000e7ae3SMatthew Knepley 
3314000e7ae3SMatthew Knepley   Input Parameters:
3315bcf0153eSBarry Smith + ts   - The `TS` context obtained from `TSCreate()`
3316000e7ae3SMatthew Knepley - func - The function
3317000e7ae3SMatthew Knepley 
3318000e7ae3SMatthew Knepley   Calling sequence of func:
3319b8123daeSJed Brown $ func (TS ts);
3320000e7ae3SMatthew Knepley 
3321000e7ae3SMatthew Knepley   Level: intermediate
3322000e7ae3SMatthew Knepley 
3323bcf0153eSBarry Smith   Note:
3324195e9b02SBarry Smith   The function set by `TSSetPostStep()` is called after each successful step. The solution vector
3325bcf0153eSBarry Smith   obtained by `TSGetSolution()` may be different than that computed at the step end if the event handler
3326bcf0153eSBarry Smith   locates an event and `TSPostEvent()` modifies it. Use `TSSetPostEvaluate()` if an unmodified solution is needed instead.
3327bcf0153eSBarry Smith 
3328bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSSetPreStep()`, `TSSetPreStage()`, `TSSetPostEvaluate()`, `TSGetTimeStep()`, `TSGetStepNumber()`, `TSGetTime()`, `TSRestartStep()`
3329000e7ae3SMatthew Knepley @*/
3330d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetPostStep(TS ts, PetscErrorCode (*func)(TS))
3331d71ae5a4SJacob Faibussowitsch {
3332000e7ae3SMatthew Knepley   PetscFunctionBegin;
33330700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3334ae60f76fSBarry Smith   ts->poststep = func;
33353ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
3336000e7ae3SMatthew Knepley }
3337000e7ae3SMatthew Knepley 
333809ee8438SJed Brown /*@
3339195e9b02SBarry Smith   TSPostStep - Runs the user-defined post-step function that was set with `TSSetPostStep()`
33403f2090d5SJed Brown 
3341c3339decSBarry Smith   Collective
33423f2090d5SJed Brown 
33433f2090d5SJed Brown   Input Parameters:
3344bcf0153eSBarry Smith . ts   - The `TS` context obtained from `TSCreate()`
33453f2090d5SJed Brown 
3346bcf0153eSBarry Smith   Note:
3347bcf0153eSBarry Smith   `TSPostStep()` is typically used within time stepping implementations,
33483f2090d5SJed Brown   so most users would not generally call this routine themselves.
33493f2090d5SJed Brown 
33503f2090d5SJed Brown   Level: developer
33513f2090d5SJed Brown 
3352bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSSetPreStep()`, `TSSetPreStage()`, `TSSetPostEvaluate()`, `TSGetTimeStep()`, `TSGetStepNumber()`, `TSGetTime()`, `TSSetPotsStep()`
33533f2090d5SJed Brown @*/
3354d71ae5a4SJacob Faibussowitsch PetscErrorCode TSPostStep(TS ts)
3355d71ae5a4SJacob Faibussowitsch {
33563f2090d5SJed Brown   PetscFunctionBegin;
33570700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3358ae60f76fSBarry Smith   if (ts->poststep) {
33595efd42a4SStefano Zampini     Vec              U;
3360ef8d1ce0SJohann Rudi     PetscObjectId    idprev;
3361ef8d1ce0SJohann Rudi     PetscBool        sameObject;
33625efd42a4SStefano Zampini     PetscObjectState sprev, spost;
33635efd42a4SStefano Zampini 
33649566063dSJacob Faibussowitsch     PetscCall(TSGetSolution(ts, &U));
33659566063dSJacob Faibussowitsch     PetscCall(PetscObjectGetId((PetscObject)U, &idprev));
33669566063dSJacob Faibussowitsch     PetscCall(PetscObjectStateGet((PetscObject)U, &sprev));
336725e27a38SBarry Smith     PetscCallBack("TS callback poststep", (*ts->poststep)(ts));
33689566063dSJacob Faibussowitsch     PetscCall(TSGetSolution(ts, &U));
33699566063dSJacob Faibussowitsch     PetscCall(PetscObjectCompareId((PetscObject)U, idprev, &sameObject));
33709566063dSJacob Faibussowitsch     PetscCall(PetscObjectStateGet((PetscObject)U, &spost));
33719566063dSJacob Faibussowitsch     if (!sameObject || sprev != spost) PetscCall(TSRestartStep(ts));
337272ac3e02SJed Brown   }
33733ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
33743f2090d5SJed Brown }
33753f2090d5SJed Brown 
3376cd652676SJed Brown /*@
3377cd652676SJed Brown    TSInterpolate - Interpolate the solution computed during the previous step to an arbitrary location in the interval
3378cd652676SJed Brown 
3379c3339decSBarry Smith    Collective
3380cd652676SJed Brown 
33814165533cSJose E. Roman    Input Parameters:
3382cd652676SJed Brown +  ts - time stepping context
3383cd652676SJed Brown -  t - time to interpolate to
3384cd652676SJed Brown 
33854165533cSJose E. Roman    Output Parameter:
33860910c330SBarry Smith .  U - state at given time
3387cd652676SJed Brown 
3388cd652676SJed Brown    Level: intermediate
3389cd652676SJed Brown 
3390bcf0153eSBarry Smith    Developer Note:
3391bcf0153eSBarry Smith    `TSInterpolate()` and the storing of previous steps/stages should be generalized to support delay differential equations and continuous adjoints.
3392cd652676SJed Brown 
3393bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSSetExactFinalTime()`, `TSSolve()`
3394cd652676SJed Brown @*/
3395d71ae5a4SJacob Faibussowitsch PetscErrorCode TSInterpolate(TS ts, PetscReal t, Vec U)
3396d71ae5a4SJacob Faibussowitsch {
3397cd652676SJed Brown   PetscFunctionBegin;
3398cd652676SJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3399b06615a5SLisandro Dalcin   PetscValidHeaderSpecific(U, VEC_CLASSID, 3);
340063a3b9bcSJacob Faibussowitsch   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);
3401dbbe0bcdSBarry Smith   PetscUseTypeMethod(ts, interpolate, t, U);
34023ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
3403cd652676SJed Brown }
3404cd652676SJed Brown 
3405d763cef2SBarry Smith /*@
34066d9e5789SSean Farley    TSStep - Steps one time step
3407d763cef2SBarry Smith 
3408c3339decSBarry Smith    Collective
3409d763cef2SBarry Smith 
3410d763cef2SBarry Smith    Input Parameter:
3411bcf0153eSBarry Smith .  ts - the `TS` context obtained from `TSCreate()`
3412d763cef2SBarry Smith 
341327829d71SBarry Smith    Level: developer
3414d763cef2SBarry Smith 
3415b8123daeSJed Brown    Notes:
3416bcf0153eSBarry Smith    The public interface for the ODE/DAE solvers is `TSSolve()`, you should almost for sure be using that routine and not this routine.
341727829d71SBarry Smith 
3418bcf0153eSBarry Smith    The hook set using `TSSetPreStep()` is called before each attempt to take the step. In general, the time step size may
3419b8123daeSJed Brown    be changed due to adaptive error controller or solve failures. Note that steps may contain multiple stages.
3420b8123daeSJed Brown 
3421bcf0153eSBarry Smith    This may over-step the final time provided in `TSSetMaxTime()` depending on the time-step used. `TSSolve()` interpolates to exactly the
3422bcf0153eSBarry Smith    time provided in `TSSetMaxTime()`. One can use `TSInterpolate()` to determine an interpolated solution within the final timestep.
342325cb2221SBarry Smith 
3424bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSCreate()`, `TSSetUp()`, `TSDestroy()`, `TSSolve()`, `TSSetPreStep()`, `TSSetPreStage()`, `TSSetPostStage()`, `TSInterpolate()`
3425d763cef2SBarry Smith @*/
3426d71ae5a4SJacob Faibussowitsch PetscErrorCode TSStep(TS ts)
3427d71ae5a4SJacob Faibussowitsch {
3428fffbeea8SBarry Smith   static PetscBool cite = PETSC_FALSE;
3429be5899b3SLisandro Dalcin   PetscReal        ptime;
3430d763cef2SBarry Smith 
3431d763cef2SBarry Smith   PetscFunctionBegin;
34320700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3433d0609cedSBarry Smith   PetscCall(PetscCitationsRegister("@article{tspaper,\n"
3434fffbeea8SBarry Smith                                    "  title         = {{PETSc/TS}: A Modern Scalable {DAE/ODE} Solver Library},\n"
3435f1d62c27SHong Zhang                                    "  author        = {Abhyankar, Shrirang and Brown, Jed and Constantinescu, Emil and Ghosh, Debojyoti and Smith, Barry F. and Zhang, Hong},\n"
3436f1d62c27SHong Zhang                                    "  journal       = {arXiv e-preprints},\n"
3437f1d62c27SHong Zhang                                    "  eprint        = {1806.01437},\n"
3438f1d62c27SHong Zhang                                    "  archivePrefix = {arXiv},\n"
34399371c9d4SSatish Balay                                    "  year          = {2018}\n}\n",
34409371c9d4SSatish Balay                                    &cite));
34419566063dSJacob Faibussowitsch   PetscCall(TSSetUp(ts));
34429566063dSJacob Faibussowitsch   PetscCall(TSTrajectorySetUp(ts->trajectory, ts));
3443d405a339SMatthew Knepley 
34443c633725SBarry Smith   PetscCheck(ts->max_time < PETSC_MAX_REAL || ts->max_steps != PETSC_MAX_INT, PetscObjectComm((PetscObject)ts), PETSC_ERR_ARG_WRONGSTATE, "You must call TSSetMaxTime() or TSSetMaxSteps(), or use -ts_max_time <time> or -ts_max_steps <steps>");
34453c633725SBarry Smith   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()");
34463c633725SBarry Smith   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");
3447a6772fa2SLisandro Dalcin 
3448be5899b3SLisandro Dalcin   if (!ts->steps) ts->ptime_prev = ts->ptime;
34499371c9d4SSatish Balay   ptime                   = ts->ptime;
34509371c9d4SSatish Balay   ts->ptime_prev_rollback = ts->ptime_prev;
34512808aa04SLisandro Dalcin   ts->reason              = TS_CONVERGED_ITERATING;
3452fc8dbba5SLisandro Dalcin 
34539566063dSJacob Faibussowitsch   PetscCall(PetscLogEventBegin(TS_Step, ts, 0, 0, 0));
3454dbbe0bcdSBarry Smith   PetscUseTypeMethod(ts, step);
34559566063dSJacob Faibussowitsch   PetscCall(PetscLogEventEnd(TS_Step, ts, 0, 0, 0));
3456fc8dbba5SLisandro Dalcin 
34579371c9d4SSatish Balay   if (ts->tspan && PetscIsCloseAtTol(ts->ptime, ts->tspan->span_times[ts->tspan->spanctr], ts->tspan->reltol * ts->time_step + ts->tspan->abstol, 0) && ts->tspan->spanctr < ts->tspan->num_span_times)
34589371c9d4SSatish Balay     PetscCall(VecCopy(ts->vec_sol, ts->tspan->vecs_sol[ts->tspan->spanctr++]));
3459fc8dbba5SLisandro Dalcin   if (ts->reason >= 0) {
3460be5899b3SLisandro Dalcin     ts->ptime_prev = ptime;
34612808aa04SLisandro Dalcin     ts->steps++;
3462be5899b3SLisandro Dalcin     ts->steprollback = PETSC_FALSE;
346328d5b5d6SLisandro Dalcin     ts->steprestart  = PETSC_FALSE;
3464d2daff3dSHong Zhang   }
3465fc8dbba5SLisandro Dalcin   if (!ts->reason) {
346608c7845fSBarry Smith     if (ts->steps >= ts->max_steps) ts->reason = TS_CONVERGED_ITS;
346708c7845fSBarry Smith     else if (ts->ptime >= ts->max_time) ts->reason = TS_CONVERGED_TIME;
346808c7845fSBarry Smith   }
3469fc8dbba5SLisandro Dalcin 
34705c9bbc89SJed Brown   if (ts->reason < 0 && ts->errorifstepfailed) {
34715c9bbc89SJed Brown     PetscCall(TSMonitorCancel(ts));
34725c9bbc89SJed Brown     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 make negative to attempt recovery", TSConvergedReasons[ts->reason]);
34735c9bbc89SJed Brown     SETERRQ(PetscObjectComm((PetscObject)ts), PETSC_ERR_NOT_CONVERGED, "TSStep has failed due to %s", TSConvergedReasons[ts->reason]);
34745c9bbc89SJed Brown   }
34753ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
347608c7845fSBarry Smith }
347708c7845fSBarry Smith 
347808c7845fSBarry Smith /*@
34797cbde773SLisandro Dalcin    TSEvaluateWLTE - Evaluate the weighted local truncation error norm
34807cbde773SLisandro Dalcin    at the end of a time step with a given order of accuracy.
34817cbde773SLisandro Dalcin 
3482c3339decSBarry Smith    Collective
34837cbde773SLisandro Dalcin 
34844165533cSJose E. Roman    Input Parameters:
34857cbde773SLisandro Dalcin +  ts - time stepping context
3486bcf0153eSBarry Smith -  wnormtype - norm type, either `NORM_2` or `NORM_INFINITY`
34877cbde773SLisandro Dalcin 
348897bb3fdcSJose E. Roman    Input/Output Parameter:
3489bcf0153eSBarry Smith .  order - optional, desired order for the error evaluation or `PETSC_DECIDE`;
349097bb3fdcSJose E. Roman            on output, the actual order of the error evaluation
349197bb3fdcSJose E. Roman 
349297bb3fdcSJose E. Roman    Output Parameter:
349397bb3fdcSJose E. Roman .  wlte - the weighted local truncation error norm
34947cbde773SLisandro Dalcin 
34957cbde773SLisandro Dalcin    Level: advanced
34967cbde773SLisandro Dalcin 
3497bcf0153eSBarry Smith    Note:
34987cbde773SLisandro Dalcin    If the timestepper cannot evaluate the error in a particular step
34997cbde773SLisandro Dalcin    (eg. in the first step or restart steps after event handling),
35007cbde773SLisandro Dalcin    this routine returns wlte=-1.0 .
35017cbde773SLisandro Dalcin 
3502bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSStep()`, `TSAdapt`, `TSErrorWeightedNorm()`
35037cbde773SLisandro Dalcin @*/
3504d71ae5a4SJacob Faibussowitsch PetscErrorCode TSEvaluateWLTE(TS ts, NormType wnormtype, PetscInt *order, PetscReal *wlte)
3505d71ae5a4SJacob Faibussowitsch {
35067cbde773SLisandro Dalcin   PetscFunctionBegin;
35077cbde773SLisandro Dalcin   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
35087cbde773SLisandro Dalcin   PetscValidType(ts, 1);
3509064a246eSJacob Faibussowitsch   PetscValidLogicalCollectiveEnum(ts, wnormtype, 2);
35107cbde773SLisandro Dalcin   if (order) PetscValidIntPointer(order, 3);
35117cbde773SLisandro Dalcin   if (order) PetscValidLogicalCollectiveInt(ts, *order, 3);
35127cbde773SLisandro Dalcin   PetscValidRealPointer(wlte, 4);
35133c633725SBarry Smith   PetscCheck(wnormtype == NORM_2 || wnormtype == NORM_INFINITY, PetscObjectComm((PetscObject)ts), PETSC_ERR_SUP, "No support for norm type %s", NormTypes[wnormtype]);
3514dbbe0bcdSBarry Smith   PetscUseTypeMethod(ts, evaluatewlte, wnormtype, order, wlte);
35153ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
35167cbde773SLisandro Dalcin }
35177cbde773SLisandro Dalcin 
351805175c85SJed Brown /*@
351905175c85SJed Brown    TSEvaluateStep - Evaluate the solution at the end of a time step with a given order of accuracy.
352005175c85SJed Brown 
3521c3339decSBarry Smith    Collective
352205175c85SJed Brown 
35234165533cSJose E. Roman    Input Parameters:
35241c3436cfSJed Brown +  ts - time stepping context
35251c3436cfSJed Brown .  order - desired order of accuracy
3526195e9b02SBarry Smith -  done - whether the step was evaluated at this order (pass `NULL` to generate an error if not available)
352705175c85SJed Brown 
35284165533cSJose E. Roman    Output Parameter:
35290910c330SBarry Smith .  U - state at the end of the current step
353005175c85SJed Brown 
353105175c85SJed Brown    Level: advanced
353205175c85SJed Brown 
3533108c343cSJed Brown    Notes:
3534108c343cSJed Brown    This function cannot be called until all stages have been evaluated.
3535108c343cSJed Brown 
3536bcf0153eSBarry Smith    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.
3537bcf0153eSBarry Smith 
3538bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSStep()`, `TSAdapt`
353905175c85SJed Brown @*/
3540d71ae5a4SJacob Faibussowitsch PetscErrorCode TSEvaluateStep(TS ts, PetscInt order, Vec U, PetscBool *done)
3541d71ae5a4SJacob Faibussowitsch {
354205175c85SJed Brown   PetscFunctionBegin;
354305175c85SJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
354405175c85SJed Brown   PetscValidType(ts, 1);
35450910c330SBarry Smith   PetscValidHeaderSpecific(U, VEC_CLASSID, 3);
3546dbbe0bcdSBarry Smith   PetscUseTypeMethod(ts, evaluatestep, order, U, done);
35473ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
354805175c85SJed Brown }
354905175c85SJed Brown 
3550aad739acSMatthew G. Knepley /*@C
35512e61be88SMatthew G. Knepley   TSGetComputeInitialCondition - Get the function used to automatically compute an initial condition for the timestepping.
3552aad739acSMatthew G. Knepley 
3553aad739acSMatthew G. Knepley   Not collective
3554aad739acSMatthew G. Knepley 
35554165533cSJose E. Roman   Input Parameter:
3556aad739acSMatthew G. Knepley . ts - time stepping context
3557aad739acSMatthew G. Knepley 
35584165533cSJose E. Roman   Output Parameter:
35592e61be88SMatthew G. Knepley . initConditions - The function which computes an initial condition
3560aad739acSMatthew G. Knepley 
3561bcf0153eSBarry Smith   The calling sequence for the function is
3562bcf0153eSBarry Smith .vb
3563bcf0153eSBarry Smith  initCondition(TS ts, Vec u)
3564bcf0153eSBarry Smith  ts - The timestepping context
3565bcf0153eSBarry Smith  u  - The input vector in which the initial condition is stored
3566bcf0153eSBarry Smith .ve
3567bcf0153eSBarry Smith 
3568aad739acSMatthew G. Knepley    Level: advanced
3569aad739acSMatthew G. Knepley 
3570bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSSetComputeInitialCondition()`, `TSComputeInitialCondition()`
3571aad739acSMatthew G. Knepley @*/
3572d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetComputeInitialCondition(TS ts, PetscErrorCode (**initCondition)(TS, Vec))
3573d71ae5a4SJacob Faibussowitsch {
3574aad739acSMatthew G. Knepley   PetscFunctionBegin;
3575aad739acSMatthew G. Knepley   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
35762e61be88SMatthew G. Knepley   PetscValidPointer(initCondition, 2);
35772e61be88SMatthew G. Knepley   *initCondition = ts->ops->initcondition;
35783ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
3579aad739acSMatthew G. Knepley }
3580aad739acSMatthew G. Knepley 
3581aad739acSMatthew G. Knepley /*@C
35822e61be88SMatthew G. Knepley   TSSetComputeInitialCondition - Set the function used to automatically compute an initial condition for the timestepping.
3583aad739acSMatthew G. Knepley 
3584c3339decSBarry Smith   Logically collective
3585aad739acSMatthew G. Knepley 
35864165533cSJose E. Roman   Input Parameters:
3587aad739acSMatthew G. Knepley + ts  - time stepping context
35882e61be88SMatthew G. Knepley - initCondition - The function which computes an initial condition
3589aad739acSMatthew G. Knepley 
3590a96d6ef6SBarry Smith   Calling sequence for initCondition:
3591a96d6ef6SBarry Smith $ PetscErrorCode initCondition(TS ts, Vec u)
3592a96d6ef6SBarry Smith + ts - The timestepping context
3593a96d6ef6SBarry Smith - u  - The input vector in which the initial condition is to be stored
3594aad739acSMatthew G. Knepley 
3595bcf0153eSBarry Smith   Level: advanced
3596bcf0153eSBarry Smith 
3597bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSGetComputeInitialCondition()`, `TSComputeInitialCondition()`
3598aad739acSMatthew G. Knepley @*/
3599d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetComputeInitialCondition(TS ts, PetscErrorCode (*initCondition)(TS, Vec))
3600d71ae5a4SJacob Faibussowitsch {
3601aad739acSMatthew G. Knepley   PetscFunctionBegin;
3602aad739acSMatthew G. Knepley   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
36032e61be88SMatthew G. Knepley   PetscValidFunction(initCondition, 2);
36042e61be88SMatthew G. Knepley   ts->ops->initcondition = initCondition;
36053ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
3606aad739acSMatthew G. Knepley }
3607aad739acSMatthew G. Knepley 
3608aad739acSMatthew G. Knepley /*@
3609bcf0153eSBarry Smith   TSComputeInitialCondition - Compute an initial condition for the timestepping using the function previously set with `TSSetComputeInitialCondition()`
3610aad739acSMatthew G. Knepley 
3611c3339decSBarry Smith   Collective
3612aad739acSMatthew G. Knepley 
36134165533cSJose E. Roman   Input Parameters:
3614aad739acSMatthew G. Knepley + ts - time stepping context
3615bcf0153eSBarry Smith - u  - The `Vec` to store the condition in which will be used in `TSSolve()`
3616aad739acSMatthew G. Knepley 
3617aad739acSMatthew G. Knepley   Level: advanced
3618aad739acSMatthew G. Knepley 
3619bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSGetComputeInitialCondition()`, `TSSetComputeInitialCondition()`, `TSSolve()`
3620aad739acSMatthew G. Knepley @*/
3621d71ae5a4SJacob Faibussowitsch PetscErrorCode TSComputeInitialCondition(TS ts, Vec u)
3622d71ae5a4SJacob Faibussowitsch {
3623aad739acSMatthew G. Knepley   PetscFunctionBegin;
3624aad739acSMatthew G. Knepley   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3625aad739acSMatthew G. Knepley   PetscValidHeaderSpecific(u, VEC_CLASSID, 2);
3626dbbe0bcdSBarry Smith   PetscTryTypeMethod(ts, initcondition, u);
36273ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
3628aad739acSMatthew G. Knepley }
3629aad739acSMatthew G. Knepley 
3630aad739acSMatthew G. Knepley /*@C
3631aad739acSMatthew G. Knepley   TSGetComputeExactError - Get the function used to automatically compute the exact error for the timestepping.
3632aad739acSMatthew G. Knepley 
3633aad739acSMatthew G. Knepley   Not collective
3634aad739acSMatthew G. Knepley 
36354165533cSJose E. Roman   Input Parameter:
3636aad739acSMatthew G. Knepley . ts - time stepping context
3637aad739acSMatthew G. Knepley 
36384165533cSJose E. Roman   Output Parameter:
3639aad739acSMatthew G. Knepley . exactError - The function which computes the solution error
3640aad739acSMatthew G. Knepley 
3641a96d6ef6SBarry Smith   Calling sequence for exactError:
3642a96d6ef6SBarry Smith $ PetscErrorCode exactError(TS ts, Vec u)
3643a96d6ef6SBarry Smith + ts - The timestepping context
3644a96d6ef6SBarry Smith . u  - The approximate solution vector
3645a96d6ef6SBarry Smith - e  - The input vector in which the error is stored
3646aad739acSMatthew G. Knepley 
3647bcf0153eSBarry Smith   Level: advanced
3648bcf0153eSBarry Smith 
3649bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSGetComputeExactError()`, `TSComputeExactError()`
3650aad739acSMatthew G. Knepley @*/
3651d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetComputeExactError(TS ts, PetscErrorCode (**exactError)(TS, Vec, Vec))
3652d71ae5a4SJacob Faibussowitsch {
3653aad739acSMatthew G. Knepley   PetscFunctionBegin;
3654aad739acSMatthew G. Knepley   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3655aad739acSMatthew G. Knepley   PetscValidPointer(exactError, 2);
3656aad739acSMatthew G. Knepley   *exactError = ts->ops->exacterror;
36573ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
3658aad739acSMatthew G. Knepley }
3659aad739acSMatthew G. Knepley 
3660aad739acSMatthew G. Knepley /*@C
3661aad739acSMatthew G. Knepley   TSSetComputeExactError - Set the function used to automatically compute the exact error for the timestepping.
3662aad739acSMatthew G. Knepley 
3663c3339decSBarry Smith   Logically collective
3664aad739acSMatthew G. Knepley 
36654165533cSJose E. Roman   Input Parameters:
3666aad739acSMatthew G. Knepley + ts - time stepping context
3667aad739acSMatthew G. Knepley - exactError - The function which computes the solution error
3668aad739acSMatthew G. Knepley 
3669a96d6ef6SBarry Smith   Calling sequence for exactError:
3670a96d6ef6SBarry Smith $ PetscErrorCode exactError(TS ts, Vec u)
3671a96d6ef6SBarry Smith + ts - The timestepping context
3672a96d6ef6SBarry Smith . u  - The approximate solution vector
3673a96d6ef6SBarry Smith - e  - The input vector in which the error is stored
3674aad739acSMatthew G. Knepley 
3675bcf0153eSBarry Smith   Level: advanced
3676bcf0153eSBarry Smith 
3677bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSGetComputeExactError()`, `TSComputeExactError()`
3678aad739acSMatthew G. Knepley @*/
3679d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetComputeExactError(TS ts, PetscErrorCode (*exactError)(TS, Vec, Vec))
3680d71ae5a4SJacob Faibussowitsch {
3681aad739acSMatthew G. Knepley   PetscFunctionBegin;
3682aad739acSMatthew G. Knepley   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3683f907fdbfSMatthew G. Knepley   PetscValidFunction(exactError, 2);
3684aad739acSMatthew G. Knepley   ts->ops->exacterror = exactError;
36853ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
3686aad739acSMatthew G. Knepley }
3687aad739acSMatthew G. Knepley 
3688aad739acSMatthew G. Knepley /*@
3689bcf0153eSBarry Smith   TSComputeExactError - Compute the solution error for the timestepping using the function previously set with `TSSetComputeExactError()`
3690aad739acSMatthew G. Knepley 
3691c3339decSBarry Smith   Collective
3692aad739acSMatthew G. Knepley 
36934165533cSJose E. Roman   Input Parameters:
3694aad739acSMatthew G. Knepley + ts - time stepping context
3695aad739acSMatthew G. Knepley . u  - The approximate solution
3696bcf0153eSBarry Smith - e  - The `Vec` used to store the error
3697aad739acSMatthew G. Knepley 
3698aad739acSMatthew G. Knepley   Level: advanced
3699aad739acSMatthew G. Knepley 
3700bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSGetComputeInitialCondition()`, `TSSetComputeInitialCondition()`, `TSSolve()`
3701aad739acSMatthew G. Knepley @*/
3702d71ae5a4SJacob Faibussowitsch PetscErrorCode TSComputeExactError(TS ts, Vec u, Vec e)
3703d71ae5a4SJacob Faibussowitsch {
3704aad739acSMatthew G. Knepley   PetscFunctionBegin;
3705aad739acSMatthew G. Knepley   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3706aad739acSMatthew G. Knepley   PetscValidHeaderSpecific(u, VEC_CLASSID, 2);
3707aad739acSMatthew G. Knepley   PetscValidHeaderSpecific(e, VEC_CLASSID, 3);
3708dbbe0bcdSBarry Smith   PetscTryTypeMethod(ts, exacterror, u, e);
37093ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
3710aad739acSMatthew G. Knepley }
3711aad739acSMatthew G. Knepley 
3712b1cb36f3SHong Zhang /*@
37136a4d4014SLisandro Dalcin    TSSolve - Steps the requested number of timesteps.
37146a4d4014SLisandro Dalcin 
3715c3339decSBarry Smith    Collective
37166a4d4014SLisandro Dalcin 
3717d8d19677SJose E. Roman    Input Parameters:
3718bcf0153eSBarry Smith +  ts - the `TS` context obtained from `TSCreate()`
3719bcf0153eSBarry Smith -  u - the solution vector  (can be null if `TSSetSolution()` was used and `TSSetExactFinalTime`(ts,`TS_EXACTFINALTIME_MATCHSTEP`) was not used,
372063e21af5SBarry Smith                              otherwise must contain the initial conditions and will contain the solution at the final requested time
37215a3a76d0SJed Brown 
37226a4d4014SLisandro Dalcin    Level: beginner
37236a4d4014SLisandro Dalcin 
37245a3a76d0SJed Brown    Notes:
37255a3a76d0SJed Brown    The final time returned by this function may be different from the time of the internally
3726bcf0153eSBarry Smith    held state accessible by `TSGetSolution()` and `TSGetTime()` because the method may have
37275a3a76d0SJed Brown    stepped over the final time.
37285a3a76d0SJed Brown 
3729bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSCreate()`, `TSSetSolution()`, `TSStep()`, `TSGetTime()`, `TSGetSolveTime()`
37306a4d4014SLisandro Dalcin @*/
3731d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSolve(TS ts, Vec u)
3732d71ae5a4SJacob Faibussowitsch {
3733b06615a5SLisandro Dalcin   Vec solution;
3734f22f69f0SBarry Smith 
37356a4d4014SLisandro Dalcin   PetscFunctionBegin;
37360700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3737f2c2a1b9SBarry Smith   if (u) PetscValidHeaderSpecific(u, VEC_CLASSID, 2);
3738303a5415SBarry Smith 
37399566063dSJacob Faibussowitsch   PetscCall(TSSetExactFinalTimeDefault(ts));
3740ee41a567SStefano Zampini   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 */
37410910c330SBarry Smith     if (!ts->vec_sol || u == ts->vec_sol) {
37429566063dSJacob Faibussowitsch       PetscCall(VecDuplicate(u, &solution));
37439566063dSJacob Faibussowitsch       PetscCall(TSSetSolution(ts, solution));
37449566063dSJacob Faibussowitsch       PetscCall(VecDestroy(&solution)); /* grant ownership */
37455a3a76d0SJed Brown     }
37469566063dSJacob Faibussowitsch     PetscCall(VecCopy(u, ts->vec_sol));
37473c633725SBarry Smith     PetscCheck(!ts->forward_solve, PetscObjectComm((PetscObject)ts), PETSC_ERR_SUP, "Sensitivity analysis does not support the mode TS_EXACTFINALTIME_INTERPOLATE");
37481baa6e33SBarry Smith   } else if (u) PetscCall(TSSetSolution(ts, u));
37499566063dSJacob Faibussowitsch   PetscCall(TSSetUp(ts));
37509566063dSJacob Faibussowitsch   PetscCall(TSTrajectorySetUp(ts->trajectory, ts));
3751a6772fa2SLisandro Dalcin 
37523c633725SBarry Smith   PetscCheck(ts->max_time < PETSC_MAX_REAL || ts->max_steps != PETSC_MAX_INT, PetscObjectComm((PetscObject)ts), PETSC_ERR_ARG_WRONGSTATE, "You must call TSSetMaxTime() or TSSetMaxSteps(), or use -ts_max_time <time> or -ts_max_steps <steps>");
37533c633725SBarry Smith   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()");
37543c633725SBarry Smith   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");
37554a658b32SHong Zhang   PetscCheck(!(ts->tspan && ts->exact_final_time != TS_EXACTFINALTIME_MATCHSTEP), PetscObjectComm((PetscObject)ts), PETSC_ERR_SUP, "You must use TS_EXACTFINALTIME_MATCHSTEP when using time span");
37564a658b32SHong Zhang 
3757e1db57b0SHong Zhang   if (ts->tspan && PetscIsCloseAtTol(ts->ptime, ts->tspan->span_times[0], ts->tspan->reltol * ts->time_step + ts->tspan->abstol, 0)) { /* starting point in time span */
37584a658b32SHong Zhang     PetscCall(VecCopy(ts->vec_sol, ts->tspan->vecs_sol[0]));
37594a658b32SHong Zhang     ts->tspan->spanctr = 1;
37604a658b32SHong Zhang   }
3761a6772fa2SLisandro Dalcin 
37621baa6e33SBarry Smith   if (ts->forward_solve) PetscCall(TSForwardSetUp(ts));
3763715f1b00SHong Zhang 
3764e7069c78SShri   /* reset number of steps only when the step is not restarted. ARKIMEX
3765715f1b00SHong Zhang      restarts the step after an event. Resetting these counters in such case causes
3766e7069c78SShri      TSTrajectory to incorrectly save the output files
3767e7069c78SShri   */
3768715f1b00SHong Zhang   /* reset time step and iteration counters */
37692808aa04SLisandro Dalcin   if (!ts->steps) {
37705ef26d82SJed Brown     ts->ksp_its           = 0;
37715ef26d82SJed Brown     ts->snes_its          = 0;
3772c610991cSLisandro Dalcin     ts->num_snes_failures = 0;
3773c610991cSLisandro Dalcin     ts->reject            = 0;
37742808aa04SLisandro Dalcin     ts->steprestart       = PETSC_TRUE;
37752808aa04SLisandro Dalcin     ts->steprollback      = PETSC_FALSE;
37767d51462cSStefano Zampini     ts->rhsjacobian.time  = PETSC_MIN_REAL;
37772808aa04SLisandro Dalcin   }
3778e97c63d7SStefano Zampini 
37794a658b32SHong Zhang   /* make sure initial time step does not overshoot final time or the next point in tspan */
3780e97c63d7SStefano Zampini   if (ts->exact_final_time == TS_EXACTFINALTIME_MATCHSTEP) {
37814a658b32SHong Zhang     PetscReal maxdt;
3782e97c63d7SStefano Zampini     PetscReal dt = ts->time_step;
3783e97c63d7SStefano Zampini 
37844a658b32SHong Zhang     if (ts->tspan) maxdt = ts->tspan->span_times[ts->tspan->spanctr] - ts->ptime;
37854a658b32SHong Zhang     else maxdt = ts->max_time - ts->ptime;
3786e97c63d7SStefano Zampini     ts->time_step = dt >= maxdt ? maxdt : (PetscIsCloseAtTol(dt, maxdt, 10 * PETSC_MACHINE_EPSILON, 0) ? maxdt : dt);
3787e97c63d7SStefano Zampini   }
3788193ac0bcSJed Brown   ts->reason = TS_CONVERGED_ITERATING;
3789193ac0bcSJed Brown 
3790900f6b5bSMatthew G. Knepley   {
3791900f6b5bSMatthew G. Knepley     PetscViewer       viewer;
3792900f6b5bSMatthew G. Knepley     PetscViewerFormat format;
3793900f6b5bSMatthew G. Knepley     PetscBool         flg;
3794900f6b5bSMatthew G. Knepley     static PetscBool  incall = PETSC_FALSE;
3795900f6b5bSMatthew G. Knepley 
3796900f6b5bSMatthew G. Knepley     if (!incall) {
3797900f6b5bSMatthew G. Knepley       /* Estimate the convergence rate of the time discretization */
37989566063dSJacob Faibussowitsch       PetscCall(PetscOptionsGetViewer(PetscObjectComm((PetscObject)ts), ((PetscObject)ts)->options, ((PetscObject)ts)->prefix, "-ts_convergence_estimate", &viewer, &format, &flg));
3799900f6b5bSMatthew G. Knepley       if (flg) {
3800900f6b5bSMatthew G. Knepley         PetscConvEst conv;
3801900f6b5bSMatthew G. Knepley         DM           dm;
3802900f6b5bSMatthew G. Knepley         PetscReal   *alpha; /* Convergence rate of the solution error for each field in the L_2 norm */
3803900f6b5bSMatthew G. Knepley         PetscInt     Nf;
3804f2ed2dc7SMatthew G. Knepley         PetscBool    checkTemporal = PETSC_TRUE;
3805900f6b5bSMatthew G. Knepley 
3806900f6b5bSMatthew G. Knepley         incall = PETSC_TRUE;
38079566063dSJacob Faibussowitsch         PetscCall(PetscOptionsGetBool(((PetscObject)ts)->options, ((PetscObject)ts)->prefix, "-ts_convergence_temporal", &checkTemporal, &flg));
38089566063dSJacob Faibussowitsch         PetscCall(TSGetDM(ts, &dm));
38099566063dSJacob Faibussowitsch         PetscCall(DMGetNumFields(dm, &Nf));
38109566063dSJacob Faibussowitsch         PetscCall(PetscCalloc1(PetscMax(Nf, 1), &alpha));
38119566063dSJacob Faibussowitsch         PetscCall(PetscConvEstCreate(PetscObjectComm((PetscObject)ts), &conv));
38129566063dSJacob Faibussowitsch         PetscCall(PetscConvEstUseTS(conv, checkTemporal));
38139566063dSJacob Faibussowitsch         PetscCall(PetscConvEstSetSolver(conv, (PetscObject)ts));
38149566063dSJacob Faibussowitsch         PetscCall(PetscConvEstSetFromOptions(conv));
38159566063dSJacob Faibussowitsch         PetscCall(PetscConvEstSetUp(conv));
38169566063dSJacob Faibussowitsch         PetscCall(PetscConvEstGetConvRate(conv, alpha));
38179566063dSJacob Faibussowitsch         PetscCall(PetscViewerPushFormat(viewer, format));
38189566063dSJacob Faibussowitsch         PetscCall(PetscConvEstRateView(conv, alpha, viewer));
38199566063dSJacob Faibussowitsch         PetscCall(PetscViewerPopFormat(viewer));
38209566063dSJacob Faibussowitsch         PetscCall(PetscViewerDestroy(&viewer));
38219566063dSJacob Faibussowitsch         PetscCall(PetscConvEstDestroy(&conv));
38229566063dSJacob Faibussowitsch         PetscCall(PetscFree(alpha));
3823900f6b5bSMatthew G. Knepley         incall = PETSC_FALSE;
3824900f6b5bSMatthew G. Knepley       }
3825900f6b5bSMatthew G. Knepley     }
3826900f6b5bSMatthew G. Knepley   }
3827900f6b5bSMatthew G. Knepley 
38289566063dSJacob Faibussowitsch   PetscCall(TSViewFromOptions(ts, NULL, "-ts_view_pre"));
3829f05ece33SBarry Smith 
3830193ac0bcSJed Brown   if (ts->ops->solve) { /* This private interface is transitional and should be removed when all implementations are updated. */
3831dbbe0bcdSBarry Smith     PetscUseTypeMethod(ts, solve);
38329566063dSJacob Faibussowitsch     if (u) PetscCall(VecCopy(ts->vec_sol, u));
3833cc708dedSBarry Smith     ts->solvetime = ts->ptime;
3834a6772fa2SLisandro Dalcin     solution      = ts->vec_sol;
3835be5899b3SLisandro Dalcin   } else { /* Step the requested number of timesteps. */
3836db4deed7SKarl Rupp     if (ts->steps >= ts->max_steps) ts->reason = TS_CONVERGED_ITS;
3837db4deed7SKarl Rupp     else if (ts->ptime >= ts->max_time) ts->reason = TS_CONVERGED_TIME;
3838e7069c78SShri 
38392808aa04SLisandro Dalcin     if (!ts->steps) {
38409566063dSJacob Faibussowitsch       PetscCall(TSTrajectorySet(ts->trajectory, ts, ts->steps, ts->ptime, ts->vec_sol));
38419566063dSJacob Faibussowitsch       PetscCall(TSEventInitialize(ts->event, ts, ts->ptime, ts->vec_sol));
38422808aa04SLisandro Dalcin     }
38436427ac75SLisandro Dalcin 
3844e1a7a14fSJed Brown     while (!ts->reason) {
38459566063dSJacob Faibussowitsch       PetscCall(TSMonitor(ts, ts->steps, ts->ptime, ts->vec_sol));
38461e66621cSBarry Smith       if (!ts->steprollback) PetscCall(TSPreStep(ts));
38479566063dSJacob Faibussowitsch       PetscCall(TSStep(ts));
38481baa6e33SBarry Smith       if (ts->testjacobian) PetscCall(TSRHSJacobianTest(ts, NULL));
38491baa6e33SBarry Smith       if (ts->testjacobiantranspose) PetscCall(TSRHSJacobianTestTranspose(ts, NULL));
3850cd4cee2dSHong Zhang       if (ts->quadraturets && ts->costintegralfwd) { /* Must evaluate the cost integral before event is handled. The cost integral value can also be rolled back. */
38517b0e2f17SHong Zhang         if (ts->reason >= 0) ts->steps--;            /* Revert the step number changed by TSStep() */
38529566063dSJacob Faibussowitsch         PetscCall(TSForwardCostIntegral(ts));
38537b0e2f17SHong Zhang         if (ts->reason >= 0) ts->steps++;
3854b1cb36f3SHong Zhang       }
385558818c2dSLisandro Dalcin       if (ts->forward_solve) {            /* compute forward sensitivities before event handling because postevent() may change RHS and jump conditions may have to be applied */
38567b0e2f17SHong Zhang         if (ts->reason >= 0) ts->steps--; /* Revert the step number changed by TSStep() */
38579566063dSJacob Faibussowitsch         PetscCall(TSForwardStep(ts));
38587b0e2f17SHong Zhang         if (ts->reason >= 0) ts->steps++;
3859715f1b00SHong Zhang       }
38609566063dSJacob Faibussowitsch       PetscCall(TSPostEvaluate(ts));
38619566063dSJacob Faibussowitsch       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. */
38621baa6e33SBarry Smith       if (ts->steprollback) PetscCall(TSPostEvaluate(ts));
3863e783b05fSHong Zhang       if (!ts->steprollback) {
38649566063dSJacob Faibussowitsch         PetscCall(TSTrajectorySet(ts->trajectory, ts, ts->steps, ts->ptime, ts->vec_sol));
38659566063dSJacob Faibussowitsch         PetscCall(TSPostStep(ts));
3866aeb4809dSShri Abhyankar       }
3867193ac0bcSJed Brown     }
38689566063dSJacob Faibussowitsch     PetscCall(TSMonitor(ts, ts->steps, ts->ptime, ts->vec_sol));
38696427ac75SLisandro Dalcin 
387049354f04SShri Abhyankar     if (ts->exact_final_time == TS_EXACTFINALTIME_INTERPOLATE && ts->ptime > ts->max_time) {
38719566063dSJacob Faibussowitsch       PetscCall(TSInterpolate(ts, ts->max_time, u));
3872cc708dedSBarry Smith       ts->solvetime = ts->max_time;
3873b06615a5SLisandro Dalcin       solution      = u;
38749566063dSJacob Faibussowitsch       PetscCall(TSMonitor(ts, -1, ts->solvetime, solution));
38750574a7fbSJed Brown     } else {
38769566063dSJacob Faibussowitsch       if (u) PetscCall(VecCopy(ts->vec_sol, u));
3877cc708dedSBarry Smith       ts->solvetime = ts->ptime;
3878b06615a5SLisandro Dalcin       solution      = ts->vec_sol;
38790574a7fbSJed Brown     }
3880193ac0bcSJed Brown   }
3881d2daff3dSHong Zhang 
38829566063dSJacob Faibussowitsch   PetscCall(TSViewFromOptions(ts, NULL, "-ts_view"));
38839566063dSJacob Faibussowitsch   PetscCall(VecViewFromOptions(solution, (PetscObject)ts, "-ts_view_solution"));
38849566063dSJacob Faibussowitsch   PetscCall(PetscObjectSAWsBlock((PetscObject)ts));
38851baa6e33SBarry Smith   if (ts->adjoint_solve) PetscCall(TSAdjointSolve(ts));
38863ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
38876a4d4014SLisandro Dalcin }
38886a4d4014SLisandro Dalcin 
3889d763cef2SBarry Smith /*@
3890b8123daeSJed Brown    TSGetTime - Gets the time of the most recently completed step.
3891d763cef2SBarry Smith 
3892d763cef2SBarry Smith    Not Collective
3893d763cef2SBarry Smith 
3894d763cef2SBarry Smith    Input Parameter:
3895bcf0153eSBarry Smith .  ts - the `TS` context obtained from `TSCreate()`
3896d763cef2SBarry Smith 
3897d763cef2SBarry Smith    Output Parameter:
3898bcf0153eSBarry Smith .  t  - the current time. This time may not corresponds to the final time set with `TSSetMaxTime()`, use `TSGetSolveTime()`.
3899d763cef2SBarry Smith 
3900d763cef2SBarry Smith    Level: beginner
3901d763cef2SBarry Smith 
3902b8123daeSJed Brown    Note:
3903bcf0153eSBarry Smith    When called during time step evaluation (e.g. during residual evaluation or via hooks set using `TSSetPreStep()`,
3904bcf0153eSBarry Smith    `TSSetPreStage()`, `TSSetPostStage()`, or `TSSetPostStep()`), the time is the time at the start of the step being evaluated.
3905b8123daeSJed Brown 
3906bcf0153eSBarry Smith .seealso: [](chapter_ts), TS`, ``TSGetSolveTime()`, `TSSetTime()`, `TSGetTimeStep()`, `TSGetStepNumber()`
3907d763cef2SBarry Smith @*/
3908d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetTime(TS ts, PetscReal *t)
3909d71ae5a4SJacob Faibussowitsch {
3910d763cef2SBarry Smith   PetscFunctionBegin;
39110700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3912f7cf8827SBarry Smith   PetscValidRealPointer(t, 2);
3913d763cef2SBarry Smith   *t = ts->ptime;
39143ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
3915d763cef2SBarry Smith }
3916d763cef2SBarry Smith 
3917e5e524a1SHong Zhang /*@
3918e5e524a1SHong Zhang    TSGetPrevTime - Gets the starting time of the previously completed step.
3919e5e524a1SHong Zhang 
3920e5e524a1SHong Zhang    Not Collective
3921e5e524a1SHong Zhang 
3922e5e524a1SHong Zhang    Input Parameter:
3923bcf0153eSBarry Smith .  ts - the `TS` context obtained from `TSCreate()`
3924e5e524a1SHong Zhang 
3925e5e524a1SHong Zhang    Output Parameter:
3926e5e524a1SHong Zhang .  t  - the previous time
3927e5e524a1SHong Zhang 
3928e5e524a1SHong Zhang    Level: beginner
3929e5e524a1SHong Zhang 
3930bcf0153eSBarry Smith .seealso: [](chapter_ts), TS`, ``TSGetTime()`, `TSGetSolveTime()`, `TSGetTimeStep()`
3931e5e524a1SHong Zhang @*/
3932d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetPrevTime(TS ts, PetscReal *t)
3933d71ae5a4SJacob Faibussowitsch {
3934e5e524a1SHong Zhang   PetscFunctionBegin;
3935e5e524a1SHong Zhang   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3936e5e524a1SHong Zhang   PetscValidRealPointer(t, 2);
3937e5e524a1SHong Zhang   *t = ts->ptime_prev;
39383ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
3939e5e524a1SHong Zhang }
3940e5e524a1SHong Zhang 
39416a4d4014SLisandro Dalcin /*@
39426a4d4014SLisandro Dalcin    TSSetTime - Allows one to reset the time.
39436a4d4014SLisandro Dalcin 
3944c3339decSBarry Smith    Logically Collective
39456a4d4014SLisandro Dalcin 
39466a4d4014SLisandro Dalcin    Input Parameters:
3947bcf0153eSBarry Smith +  ts - the `TS` context obtained from `TSCreate()`
39486a4d4014SLisandro Dalcin -  time - the time
39496a4d4014SLisandro Dalcin 
39506a4d4014SLisandro Dalcin    Level: intermediate
39516a4d4014SLisandro Dalcin 
3952bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSGetTime()`, `TSSetMaxSteps()`
39536a4d4014SLisandro Dalcin @*/
3954d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetTime(TS ts, PetscReal t)
3955d71ae5a4SJacob Faibussowitsch {
39566a4d4014SLisandro Dalcin   PetscFunctionBegin;
39570700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3958c5eb9154SBarry Smith   PetscValidLogicalCollectiveReal(ts, t, 2);
39596a4d4014SLisandro Dalcin   ts->ptime = t;
39603ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
39616a4d4014SLisandro Dalcin }
39626a4d4014SLisandro Dalcin 
3963d763cef2SBarry Smith /*@C
3964d763cef2SBarry Smith    TSSetOptionsPrefix - Sets the prefix used for searching for all
3965d763cef2SBarry Smith    TS options in the database.
3966d763cef2SBarry Smith 
3967c3339decSBarry Smith    Logically Collective
3968d763cef2SBarry Smith 
3969d8d19677SJose E. Roman    Input Parameters:
3970bcf0153eSBarry Smith +  ts     - The `TS` context
3971d763cef2SBarry Smith -  prefix - The prefix to prepend to all option names
3972d763cef2SBarry Smith 
3973bcf0153eSBarry Smith    Level: advanced
3974bcf0153eSBarry Smith 
3975bcf0153eSBarry Smith    Note:
3976d763cef2SBarry Smith    A hyphen (-) must NOT be given at the beginning of the prefix name.
3977d763cef2SBarry Smith    The first character of all runtime options is AUTOMATICALLY the
3978d763cef2SBarry Smith    hyphen.
3979d763cef2SBarry Smith 
3980bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSSetFromOptions()`, `TSAppendOptionsPrefix()`
3981d763cef2SBarry Smith @*/
3982d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetOptionsPrefix(TS ts, const char prefix[])
3983d71ae5a4SJacob Faibussowitsch {
3984089b2837SJed Brown   SNES snes;
3985d763cef2SBarry Smith 
3986d763cef2SBarry Smith   PetscFunctionBegin;
39870700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
39889566063dSJacob Faibussowitsch   PetscCall(PetscObjectSetOptionsPrefix((PetscObject)ts, prefix));
39899566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts, &snes));
39909566063dSJacob Faibussowitsch   PetscCall(SNESSetOptionsPrefix(snes, prefix));
39913ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
3992d763cef2SBarry Smith }
3993d763cef2SBarry Smith 
3994d763cef2SBarry Smith /*@C
3995d763cef2SBarry Smith    TSAppendOptionsPrefix - Appends to the prefix used for searching for all
3996d763cef2SBarry Smith    TS options in the database.
3997d763cef2SBarry Smith 
3998c3339decSBarry Smith    Logically Collective
3999d763cef2SBarry Smith 
4000d8d19677SJose E. Roman    Input Parameters:
4001bcf0153eSBarry Smith +  ts     - The `TS` context
4002d763cef2SBarry Smith -  prefix - The prefix to prepend to all option names
4003d763cef2SBarry Smith 
4004bcf0153eSBarry Smith    Level: advanced
4005bcf0153eSBarry Smith 
4006bcf0153eSBarry Smith    Note:
4007d763cef2SBarry Smith    A hyphen (-) must NOT be given at the beginning of the prefix name.
4008d763cef2SBarry Smith    The first character of all runtime options is AUTOMATICALLY the
4009d763cef2SBarry Smith    hyphen.
4010d763cef2SBarry Smith 
4011bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSGetOptionsPrefix()`, `TSSetOptionsPrefix()`, `TSSetFromOptions()`
4012d763cef2SBarry Smith @*/
4013d71ae5a4SJacob Faibussowitsch PetscErrorCode TSAppendOptionsPrefix(TS ts, const char prefix[])
4014d71ae5a4SJacob Faibussowitsch {
4015089b2837SJed Brown   SNES snes;
4016d763cef2SBarry Smith 
4017d763cef2SBarry Smith   PetscFunctionBegin;
40180700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
40199566063dSJacob Faibussowitsch   PetscCall(PetscObjectAppendOptionsPrefix((PetscObject)ts, prefix));
40209566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts, &snes));
40219566063dSJacob Faibussowitsch   PetscCall(SNESAppendOptionsPrefix(snes, prefix));
40223ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
4023d763cef2SBarry Smith }
4024d763cef2SBarry Smith 
4025d763cef2SBarry Smith /*@C
4026d763cef2SBarry Smith    TSGetOptionsPrefix - Sets the prefix used for searching for all
4027bcf0153eSBarry Smith    `TS` options in the database.
4028d763cef2SBarry Smith 
4029d763cef2SBarry Smith    Not Collective
4030d763cef2SBarry Smith 
4031d763cef2SBarry Smith    Input Parameter:
4032bcf0153eSBarry Smith .  ts - The `TS` context
4033d763cef2SBarry Smith 
4034d763cef2SBarry Smith    Output Parameter:
4035d763cef2SBarry Smith .  prefix - A pointer to the prefix string used
4036d763cef2SBarry Smith 
4037d763cef2SBarry Smith    Level: intermediate
4038d763cef2SBarry Smith 
4039bcf0153eSBarry Smith    Fortran Note:
4040195e9b02SBarry Smith    The user should pass in a string 'prefix' of
4041bcf0153eSBarry Smith    sufficient length to hold the prefix.
4042bcf0153eSBarry Smith 
4043bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSAppendOptionsPrefix()`, `TSSetFromOptions()`
4044d763cef2SBarry Smith @*/
4045d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetOptionsPrefix(TS ts, const char *prefix[])
4046d71ae5a4SJacob Faibussowitsch {
4047d763cef2SBarry Smith   PetscFunctionBegin;
40480700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
40494482741eSBarry Smith   PetscValidPointer(prefix, 2);
40509566063dSJacob Faibussowitsch   PetscCall(PetscObjectGetOptionsPrefix((PetscObject)ts, prefix));
40513ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
4052d763cef2SBarry Smith }
4053d763cef2SBarry Smith 
4054d763cef2SBarry Smith /*@C
4055d763cef2SBarry Smith    TSGetRHSJacobian - Returns the Jacobian J at the present timestep.
4056d763cef2SBarry Smith 
4057bcf0153eSBarry Smith    Not Collective, but parallel objects are returned if ts is parallel
4058d763cef2SBarry Smith 
4059d763cef2SBarry Smith    Input Parameter:
4060bcf0153eSBarry Smith .  ts  - The `TS` context obtained from `TSCreate()`
4061d763cef2SBarry Smith 
4062d763cef2SBarry Smith    Output Parameters:
4063195e9b02SBarry Smith +  Amat - The (approximate) Jacobian J of G, where U_t = G(U,t)  (or `NULL`)
4064195e9b02SBarry Smith .  Pmat - The matrix from which the preconditioner is constructed, usually the same as `Amat`  (or `NULL`)
4065195e9b02SBarry Smith .  func - Function to compute the Jacobian of the RHS  (or `NULL`)
4066195e9b02SBarry Smith -  ctx - User-defined context for Jacobian evaluation routine  (or `NULL`)
4067d763cef2SBarry Smith 
4068d763cef2SBarry Smith    Level: intermediate
4069d763cef2SBarry Smith 
4070bcf0153eSBarry Smith    Note:
4071195e9b02SBarry Smith     You can pass in `NULL` for any return argument you do not need.
4072bcf0153eSBarry Smith 
4073bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSGetTimeStep()`, `TSGetMatrices()`, `TSGetTime()`, `TSGetStepNumber()`
4074d763cef2SBarry Smith 
4075d763cef2SBarry Smith @*/
4076d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetRHSJacobian(TS ts, Mat *Amat, Mat *Pmat, TSRHSJacobian *func, void **ctx)
4077d71ae5a4SJacob Faibussowitsch {
407824989b8cSPeter Brune   DM dm;
4079089b2837SJed Brown 
4080d763cef2SBarry Smith   PetscFunctionBegin;
408123a57915SBarry Smith   if (Amat || Pmat) {
408223a57915SBarry Smith     SNES snes;
40839566063dSJacob Faibussowitsch     PetscCall(TSGetSNES(ts, &snes));
40849566063dSJacob Faibussowitsch     PetscCall(SNESSetUpMatrices(snes));
40859566063dSJacob Faibussowitsch     PetscCall(SNESGetJacobian(snes, Amat, Pmat, NULL, NULL));
408623a57915SBarry Smith   }
40879566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
40889566063dSJacob Faibussowitsch   PetscCall(DMTSGetRHSJacobian(dm, func, ctx));
40893ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
4090d763cef2SBarry Smith }
4091d763cef2SBarry Smith 
40922eca1d9cSJed Brown /*@C
40932eca1d9cSJed Brown    TSGetIJacobian - Returns the implicit Jacobian at the present timestep.
40942eca1d9cSJed Brown 
4095bcf0153eSBarry Smith    Not Collective, but parallel objects are returned if ts is parallel
40962eca1d9cSJed Brown 
40972eca1d9cSJed Brown    Input Parameter:
4098bcf0153eSBarry Smith .  ts  - The `TS` context obtained from `TSCreate()`
40992eca1d9cSJed Brown 
41002eca1d9cSJed Brown    Output Parameters:
4101e4357dc4SBarry Smith +  Amat  - The (approximate) Jacobian of F(t,U,U_t)
4102195e9b02SBarry Smith .  Pmat - The matrix from which the preconditioner is constructed, often the same as `Amat`
41032eca1d9cSJed Brown .  f   - The function to compute the matrices
41042eca1d9cSJed Brown - ctx - User-defined context for Jacobian evaluation routine
41052eca1d9cSJed Brown 
41062eca1d9cSJed Brown    Level: advanced
41072eca1d9cSJed Brown 
4108bcf0153eSBarry Smith    Note:
4109195e9b02SBarry Smith     You can pass in `NULL` for any return argument you do not need.
4110bcf0153eSBarry Smith 
4111bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSGetTimeStep()`, `TSGetRHSJacobian()`, `TSGetMatrices()`, `TSGetTime()`, `TSGetStepNumber()`
41122eca1d9cSJed Brown @*/
4113d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetIJacobian(TS ts, Mat *Amat, Mat *Pmat, TSIJacobian *f, void **ctx)
4114d71ae5a4SJacob Faibussowitsch {
411524989b8cSPeter Brune   DM dm;
41160910c330SBarry Smith 
41172eca1d9cSJed Brown   PetscFunctionBegin;
4118c0aab802Sstefano_zampini   if (Amat || Pmat) {
4119c0aab802Sstefano_zampini     SNES snes;
41209566063dSJacob Faibussowitsch     PetscCall(TSGetSNES(ts, &snes));
41219566063dSJacob Faibussowitsch     PetscCall(SNESSetUpMatrices(snes));
41229566063dSJacob Faibussowitsch     PetscCall(SNESGetJacobian(snes, Amat, Pmat, NULL, NULL));
4123c0aab802Sstefano_zampini   }
41249566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
41259566063dSJacob Faibussowitsch   PetscCall(DMTSGetIJacobian(dm, f, ctx));
41263ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
41272eca1d9cSJed Brown }
41282eca1d9cSJed Brown 
4129af0996ceSBarry Smith #include <petsc/private/dmimpl.h>
41306c699258SBarry Smith /*@
4131bcf0153eSBarry Smith    TSSetDM - Sets the `DM` that may be used by some nonlinear solvers or preconditioners under the `TS`
41326c699258SBarry Smith 
4133c3339decSBarry Smith    Logically Collective
41346c699258SBarry Smith 
41356c699258SBarry Smith    Input Parameters:
4136bcf0153eSBarry Smith +  ts - the `TS` integrator object
4137195e9b02SBarry Smith -  dm - the dm, cannot be `NULL`
41386c699258SBarry Smith 
41396c699258SBarry Smith    Level: intermediate
41406c699258SBarry Smith 
4141bcf0153eSBarry Smith    Notes:
4142bcf0153eSBarry Smith    A `DM` can only be used for solving one problem at a time because information about the problem is stored on the `DM`,
4143bcf0153eSBarry Smith    even when not using interfaces like `DMTSSetIFunction()`.  Use `DMClone()` to get a distinct `DM` when solving
4144bcf0153eSBarry Smith    different problems using the same function space.
4145bcf0153eSBarry Smith 
4146bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `DM`, `TSGetDM()`, `SNESSetDM()`, `SNESGetDM()`
41476c699258SBarry Smith @*/
4148d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetDM(TS ts, DM dm)
4149d71ae5a4SJacob Faibussowitsch {
4150089b2837SJed Brown   SNES snes;
4151942e3340SBarry Smith   DMTS tsdm;
41526c699258SBarry Smith 
41536c699258SBarry Smith   PetscFunctionBegin;
41540700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
41552a808120SBarry Smith   PetscValidHeaderSpecific(dm, DM_CLASSID, 2);
41569566063dSJacob Faibussowitsch   PetscCall(PetscObjectReference((PetscObject)dm));
4157942e3340SBarry Smith   if (ts->dm) { /* Move the DMTS context over to the new DM unless the new DM already has one */
41582a34c10cSBarry Smith     if (ts->dm->dmts && !dm->dmts) {
41599566063dSJacob Faibussowitsch       PetscCall(DMCopyDMTS(ts->dm, dm));
41609566063dSJacob Faibussowitsch       PetscCall(DMGetDMTS(ts->dm, &tsdm));
41611e66621cSBarry Smith       /* Grant write privileges to the replacement DM */
41621e66621cSBarry Smith       if (tsdm->originaldm == ts->dm) tsdm->originaldm = dm;
416324989b8cSPeter Brune     }
41649566063dSJacob Faibussowitsch     PetscCall(DMDestroy(&ts->dm));
416524989b8cSPeter Brune   }
41666c699258SBarry Smith   ts->dm = dm;
4167bbd56ea5SKarl Rupp 
41689566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts, &snes));
41699566063dSJacob Faibussowitsch   PetscCall(SNESSetDM(snes, dm));
41703ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
41716c699258SBarry Smith }
41726c699258SBarry Smith 
41736c699258SBarry Smith /*@
4174bcf0153eSBarry Smith    TSGetDM - Gets the `DM` that may be used by some preconditioners
41756c699258SBarry Smith 
41763f9fe445SBarry Smith    Not Collective
41776c699258SBarry Smith 
41786c699258SBarry Smith    Input Parameter:
4179bcf0153eSBarry Smith . ts - the `TS`
41806c699258SBarry Smith 
41816c699258SBarry Smith    Output Parameter:
4182195e9b02SBarry Smith .  dm - the `DM`
41836c699258SBarry Smith 
41846c699258SBarry Smith    Level: intermediate
41856c699258SBarry Smith 
4186bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `DM`, `TSSetDM()`, `SNESSetDM()`, `SNESGetDM()`
41876c699258SBarry Smith @*/
4188d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetDM(TS ts, DM *dm)
4189d71ae5a4SJacob Faibussowitsch {
41906c699258SBarry Smith   PetscFunctionBegin;
41910700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
4192496e6a7aSJed Brown   if (!ts->dm) {
41939566063dSJacob Faibussowitsch     PetscCall(DMShellCreate(PetscObjectComm((PetscObject)ts), &ts->dm));
41949566063dSJacob Faibussowitsch     if (ts->snes) PetscCall(SNESSetDM(ts->snes, ts->dm));
4195496e6a7aSJed Brown   }
41966c699258SBarry Smith   *dm = ts->dm;
41973ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
41986c699258SBarry Smith }
41991713a123SBarry Smith 
42000f5c6efeSJed Brown /*@
42010f5c6efeSJed Brown    SNESTSFormFunction - Function to evaluate nonlinear residual
42020f5c6efeSJed Brown 
4203c3339decSBarry Smith    Logically Collective
42040f5c6efeSJed Brown 
4205d8d19677SJose E. Roman    Input Parameters:
4206d42a1c89SJed Brown + snes - nonlinear solver
42070910c330SBarry Smith . U - the current state at which to evaluate the residual
4208d42a1c89SJed Brown - ctx - user context, must be a TS
42090f5c6efeSJed Brown 
42100f5c6efeSJed Brown    Output Parameter:
42110f5c6efeSJed Brown . F - the nonlinear residual
42120f5c6efeSJed Brown 
42130f5c6efeSJed Brown    Level: advanced
42140f5c6efeSJed Brown 
4215bcf0153eSBarry Smith    Note:
4216bcf0153eSBarry Smith    This function is not normally called by users and is automatically registered with the `SNES` used by `TS`.
4217bcf0153eSBarry Smith    It is most frequently passed to `MatFDColoringSetFunction()`.
4218bcf0153eSBarry Smith 
4219bcf0153eSBarry Smith .seealso: [](chapter_ts), `SNESSetFunction()`, `MatFDColoringSetFunction()`
42200f5c6efeSJed Brown @*/
4221d71ae5a4SJacob Faibussowitsch PetscErrorCode SNESTSFormFunction(SNES snes, Vec U, Vec F, void *ctx)
4222d71ae5a4SJacob Faibussowitsch {
42230f5c6efeSJed Brown   TS ts = (TS)ctx;
42240f5c6efeSJed Brown 
42250f5c6efeSJed Brown   PetscFunctionBegin;
42260f5c6efeSJed Brown   PetscValidHeaderSpecific(snes, SNES_CLASSID, 1);
42270910c330SBarry Smith   PetscValidHeaderSpecific(U, VEC_CLASSID, 2);
42280f5c6efeSJed Brown   PetscValidHeaderSpecific(F, VEC_CLASSID, 3);
42290f5c6efeSJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 4);
42309566063dSJacob Faibussowitsch   PetscCall((ts->ops->snesfunction)(snes, U, F, ts));
42313ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
42320f5c6efeSJed Brown }
42330f5c6efeSJed Brown 
42340f5c6efeSJed Brown /*@
42350f5c6efeSJed Brown    SNESTSFormJacobian - Function to evaluate the Jacobian
42360f5c6efeSJed Brown 
4237c3339decSBarry Smith    Collective
42380f5c6efeSJed Brown 
4239d8d19677SJose E. Roman    Input Parameters:
42400f5c6efeSJed Brown + snes - nonlinear solver
42410910c330SBarry Smith . U - the current state at which to evaluate the residual
4242bcf0153eSBarry Smith - ctx - user context, must be a `TS`
42430f5c6efeSJed Brown 
4244d8d19677SJose E. Roman    Output Parameters:
42450f5c6efeSJed Brown + A - the Jacobian
42466b867d5aSJose E. Roman - B - the preconditioning matrix (may be the same as A)
42470f5c6efeSJed Brown 
42480f5c6efeSJed Brown    Level: developer
42490f5c6efeSJed Brown 
4250bcf0153eSBarry Smith    Note:
4251bcf0153eSBarry Smith    This function is not normally called by users and is automatically registered with the `SNES` used by `TS`.
4252bcf0153eSBarry Smith 
4253bcf0153eSBarry Smith .seealso: [](chapter_ts), `SNESSetJacobian()`
42540f5c6efeSJed Brown @*/
4255d71ae5a4SJacob Faibussowitsch PetscErrorCode SNESTSFormJacobian(SNES snes, Vec U, Mat A, Mat B, void *ctx)
4256d71ae5a4SJacob Faibussowitsch {
42570f5c6efeSJed Brown   TS ts = (TS)ctx;
42580f5c6efeSJed Brown 
42590f5c6efeSJed Brown   PetscFunctionBegin;
42600f5c6efeSJed Brown   PetscValidHeaderSpecific(snes, SNES_CLASSID, 1);
42610910c330SBarry Smith   PetscValidHeaderSpecific(U, VEC_CLASSID, 2);
42620f5c6efeSJed Brown   PetscValidPointer(A, 3);
426394ab13aaSBarry Smith   PetscValidHeaderSpecific(A, MAT_CLASSID, 3);
42640f5c6efeSJed Brown   PetscValidPointer(B, 4);
426594ab13aaSBarry Smith   PetscValidHeaderSpecific(B, MAT_CLASSID, 4);
4266064a246eSJacob Faibussowitsch   PetscValidHeaderSpecific(ts, TS_CLASSID, 5);
42679566063dSJacob Faibussowitsch   PetscCall((ts->ops->snesjacobian)(snes, U, A, B, ts));
42683ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
42690f5c6efeSJed Brown }
4270325fc9f4SBarry Smith 
42710e4ef248SJed Brown /*@C
42729ae8fd06SBarry Smith    TSComputeRHSFunctionLinear - Evaluate the right hand side via the user-provided Jacobian, for linear problems Udot = A U only
42730e4ef248SJed Brown 
4274c3339decSBarry Smith    Collective
42750e4ef248SJed Brown 
42764165533cSJose E. Roman    Input Parameters:
42770e4ef248SJed Brown +  ts - time stepping context
42780e4ef248SJed Brown .  t - time at which to evaluate
42790910c330SBarry Smith .  U - state at which to evaluate
42800e4ef248SJed Brown -  ctx - context
42810e4ef248SJed Brown 
42824165533cSJose E. Roman    Output Parameter:
42830e4ef248SJed Brown .  F - right hand side
42840e4ef248SJed Brown 
42850e4ef248SJed Brown    Level: intermediate
42860e4ef248SJed Brown 
4287bcf0153eSBarry Smith    Note:
4288bcf0153eSBarry Smith    This function is intended to be passed to `TSSetRHSFunction()` to evaluate the right hand side for linear problems.
4289bcf0153eSBarry Smith    The matrix (and optionally the evaluation context) should be passed to `TSSetRHSJacobian()`.
42900e4ef248SJed Brown 
4291bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSSetRHSFunction()`, `TSSetRHSJacobian()`, `TSComputeRHSJacobianConstant()`
42920e4ef248SJed Brown @*/
4293d71ae5a4SJacob Faibussowitsch PetscErrorCode TSComputeRHSFunctionLinear(TS ts, PetscReal t, Vec U, Vec F, void *ctx)
4294d71ae5a4SJacob Faibussowitsch {
42950e4ef248SJed Brown   Mat Arhs, Brhs;
42960e4ef248SJed Brown 
42970e4ef248SJed Brown   PetscFunctionBegin;
42989566063dSJacob Faibussowitsch   PetscCall(TSGetRHSMats_Private(ts, &Arhs, &Brhs));
42992663174eSHong Zhang   /* undo the damage caused by shifting */
43009566063dSJacob Faibussowitsch   PetscCall(TSRecoverRHSJacobian(ts, Arhs, Brhs));
43019566063dSJacob Faibussowitsch   PetscCall(TSComputeRHSJacobian(ts, t, U, Arhs, Brhs));
43029566063dSJacob Faibussowitsch   PetscCall(MatMult(Arhs, U, F));
43033ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
43040e4ef248SJed Brown }
43050e4ef248SJed Brown 
43060e4ef248SJed Brown /*@C
43070e4ef248SJed Brown    TSComputeRHSJacobianConstant - Reuses a Jacobian that is time-independent.
43080e4ef248SJed Brown 
4309c3339decSBarry Smith    Collective
43100e4ef248SJed Brown 
43114165533cSJose E. Roman    Input Parameters:
43120e4ef248SJed Brown +  ts - time stepping context
43130e4ef248SJed Brown .  t - time at which to evaluate
43140910c330SBarry Smith .  U - state at which to evaluate
43150e4ef248SJed Brown -  ctx - context
43160e4ef248SJed Brown 
43174165533cSJose E. Roman    Output Parameters:
43180e4ef248SJed Brown +  A - pointer to operator
431997bb3fdcSJose E. Roman -  B - pointer to preconditioning matrix
43200e4ef248SJed Brown 
43210e4ef248SJed Brown    Level: intermediate
43220e4ef248SJed Brown 
4323bcf0153eSBarry Smith    Note:
4324bcf0153eSBarry Smith    This function is intended to be passed to `TSSetRHSJacobian()` to evaluate the Jacobian for linear time-independent problems.
43250e4ef248SJed Brown 
4326bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSSetRHSFunction()`, `TSSetRHSJacobian()`, `TSComputeRHSFunctionLinear()`
43270e4ef248SJed Brown @*/
4328d71ae5a4SJacob Faibussowitsch PetscErrorCode TSComputeRHSJacobianConstant(TS ts, PetscReal t, Vec U, Mat A, Mat B, void *ctx)
4329d71ae5a4SJacob Faibussowitsch {
43300e4ef248SJed Brown   PetscFunctionBegin;
43313ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
43320e4ef248SJed Brown }
43330e4ef248SJed Brown 
43340026cea9SSean Farley /*@C
43350026cea9SSean Farley    TSComputeIFunctionLinear - Evaluate the left hand side via the user-provided Jacobian, for linear problems only
43360026cea9SSean Farley 
4337c3339decSBarry Smith    Collective
43380026cea9SSean Farley 
43394165533cSJose E. Roman    Input Parameters:
43400026cea9SSean Farley +  ts - time stepping context
43410026cea9SSean Farley .  t - time at which to evaluate
43420910c330SBarry Smith .  U - state at which to evaluate
43430910c330SBarry Smith .  Udot - time derivative of state vector
43440026cea9SSean Farley -  ctx - context
43450026cea9SSean Farley 
43464165533cSJose E. Roman    Output Parameter:
43470026cea9SSean Farley .  F - left hand side
43480026cea9SSean Farley 
43490026cea9SSean Farley    Level: intermediate
43500026cea9SSean Farley 
43510026cea9SSean Farley    Notes:
43520910c330SBarry Smith    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
4353bcf0153eSBarry Smith    user is required to write their own `TSComputeIFunction()`.
4354bcf0153eSBarry Smith    This function is intended to be passed to `TSSetIFunction()` to evaluate the left hand side for linear problems.
4355bcf0153eSBarry Smith    The matrix (and optionally the evaluation context) should be passed to `TSSetIJacobian()`.
43560026cea9SSean Farley 
4357bcf0153eSBarry Smith    Note that using this function is NOT equivalent to using `TSComputeRHSFunctionLinear()` since that solves Udot = A U
43589ae8fd06SBarry Smith 
4359bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSSetIFunction()`, `TSSetIJacobian()`, `TSComputeIJacobianConstant()`, `TSComputeRHSFunctionLinear()`
43600026cea9SSean Farley @*/
4361d71ae5a4SJacob Faibussowitsch PetscErrorCode TSComputeIFunctionLinear(TS ts, PetscReal t, Vec U, Vec Udot, Vec F, void *ctx)
4362d71ae5a4SJacob Faibussowitsch {
43630026cea9SSean Farley   Mat A, B;
43640026cea9SSean Farley 
43650026cea9SSean Farley   PetscFunctionBegin;
43669566063dSJacob Faibussowitsch   PetscCall(TSGetIJacobian(ts, &A, &B, NULL, NULL));
43679566063dSJacob Faibussowitsch   PetscCall(TSComputeIJacobian(ts, t, U, Udot, 1.0, A, B, PETSC_TRUE));
43689566063dSJacob Faibussowitsch   PetscCall(MatMult(A, Udot, F));
43693ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
43700026cea9SSean Farley }
43710026cea9SSean Farley 
43720026cea9SSean Farley /*@C
4373b41af12eSJed Brown    TSComputeIJacobianConstant - Reuses a time-independent for a semi-implicit DAE or ODE
43740026cea9SSean Farley 
4375c3339decSBarry Smith    Collective
43760026cea9SSean Farley 
43774165533cSJose E. Roman    Input Parameters:
43780026cea9SSean Farley +  ts - time stepping context
43790026cea9SSean Farley .  t - time at which to evaluate
43800910c330SBarry Smith .  U - state at which to evaluate
43810910c330SBarry Smith .  Udot - time derivative of state vector
43820026cea9SSean Farley .  shift - shift to apply
43830026cea9SSean Farley -  ctx - context
43840026cea9SSean Farley 
43854165533cSJose E. Roman    Output Parameters:
43860026cea9SSean Farley +  A - pointer to operator
438797bb3fdcSJose E. Roman -  B - pointer to preconditioning matrix
43880026cea9SSean Farley 
4389b41af12eSJed Brown    Level: advanced
43900026cea9SSean Farley 
43910026cea9SSean Farley    Notes:
4392bcf0153eSBarry Smith    This function is intended to be passed to `TSSetIJacobian()` to evaluate the Jacobian for linear time-independent problems.
43930026cea9SSean Farley 
4394b41af12eSJed Brown    It is only appropriate for problems of the form
4395b41af12eSJed Brown 
4396b41af12eSJed Brown $     M Udot = F(U,t)
4397b41af12eSJed Brown 
4398bcf0153eSBarry Smith   where M is constant and F is non-stiff.  The user must pass M to `TSSetIJacobian()`.  The current implementation only
4399bcf0153eSBarry Smith   works with IMEX time integration methods such as `TSROSW` and `TSARKIMEX`, since there is no support for de-constructing
4400b41af12eSJed Brown   an implicit operator of the form
4401b41af12eSJed Brown 
4402b41af12eSJed Brown $    shift*M + J
4403b41af12eSJed Brown 
4404b41af12eSJed Brown   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
4405b41af12eSJed Brown   a copy of M or reassemble it when requested.
4406b41af12eSJed Brown 
4407bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSROSW`, `TSARKIMEX`, `TSSetIFunction()`, `TSSetIJacobian()`, `TSComputeIFunctionLinear()`
44080026cea9SSean Farley @*/
4409d71ae5a4SJacob Faibussowitsch PetscErrorCode TSComputeIJacobianConstant(TS ts, PetscReal t, Vec U, Vec Udot, PetscReal shift, Mat A, Mat B, void *ctx)
4410d71ae5a4SJacob Faibussowitsch {
44110026cea9SSean Farley   PetscFunctionBegin;
44129566063dSJacob Faibussowitsch   PetscCall(MatScale(A, shift / ts->ijacobian.shift));
4413b41af12eSJed Brown   ts->ijacobian.shift = shift;
44143ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
44150026cea9SSean Farley }
4416b41af12eSJed Brown 
4417e817cc15SEmil Constantinescu /*@
4418bcf0153eSBarry Smith    TSGetEquationType - Gets the type of the equation that `TS` is solving.
4419e817cc15SEmil Constantinescu 
4420e817cc15SEmil Constantinescu    Not Collective
4421e817cc15SEmil Constantinescu 
4422e817cc15SEmil Constantinescu    Input Parameter:
4423bcf0153eSBarry Smith .  ts - the `TS` context
4424e817cc15SEmil Constantinescu 
4425e817cc15SEmil Constantinescu    Output Parameter:
4426bcf0153eSBarry Smith .  equation_type - see `TSEquationType`
4427e817cc15SEmil Constantinescu 
4428e817cc15SEmil Constantinescu    Level: beginner
4429e817cc15SEmil Constantinescu 
4430bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSSetEquationType()`, `TSEquationType`
4431e817cc15SEmil Constantinescu @*/
4432d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetEquationType(TS ts, TSEquationType *equation_type)
4433d71ae5a4SJacob Faibussowitsch {
4434e817cc15SEmil Constantinescu   PetscFunctionBegin;
4435e817cc15SEmil Constantinescu   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
4436e817cc15SEmil Constantinescu   PetscValidPointer(equation_type, 2);
4437e817cc15SEmil Constantinescu   *equation_type = ts->equation_type;
44383ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
4439e817cc15SEmil Constantinescu }
4440e817cc15SEmil Constantinescu 
4441e817cc15SEmil Constantinescu /*@
4442bcf0153eSBarry Smith    TSSetEquationType - Sets the type of the equation that `TS` is solving.
4443e817cc15SEmil Constantinescu 
4444e817cc15SEmil Constantinescu    Not Collective
4445e817cc15SEmil Constantinescu 
4446d8d19677SJose E. Roman    Input Parameters:
4447bcf0153eSBarry Smith +  ts - the `TS` context
4448bcf0153eSBarry Smith -  equation_type - see `TSEquationType`
4449e817cc15SEmil Constantinescu 
4450e817cc15SEmil Constantinescu    Level: advanced
4451e817cc15SEmil Constantinescu 
4452bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSGetEquationType()`, `TSEquationType`
4453e817cc15SEmil Constantinescu @*/
4454d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetEquationType(TS ts, TSEquationType equation_type)
4455d71ae5a4SJacob Faibussowitsch {
4456e817cc15SEmil Constantinescu   PetscFunctionBegin;
4457e817cc15SEmil Constantinescu   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
4458e817cc15SEmil Constantinescu   ts->equation_type = equation_type;
44593ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
4460e817cc15SEmil Constantinescu }
44610026cea9SSean Farley 
44624af1b03aSJed Brown /*@
4463bcf0153eSBarry Smith    TSGetConvergedReason - Gets the reason the `TS` iteration was stopped.
44644af1b03aSJed Brown 
44654af1b03aSJed Brown    Not Collective
44664af1b03aSJed Brown 
44674af1b03aSJed Brown    Input Parameter:
4468bcf0153eSBarry Smith .  ts - the `TS` context
44694af1b03aSJed Brown 
44704af1b03aSJed Brown    Output Parameter:
4471bcf0153eSBarry Smith .  reason - negative value indicates diverged, positive value converged, see `TSConvergedReason` or the
44724af1b03aSJed Brown             manual pages for the individual convergence tests for complete lists
44734af1b03aSJed Brown 
4474487e0bb9SJed Brown    Level: beginner
44754af1b03aSJed Brown 
4476bcf0153eSBarry Smith    Note:
4477bcf0153eSBarry Smith    Can only be called after the call to `TSSolve()` is complete.
44784af1b03aSJed Brown 
4479bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSSolve()`, `TSSetConvergenceTest()`, `TSConvergedReason`
44804af1b03aSJed Brown @*/
4481d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetConvergedReason(TS ts, TSConvergedReason *reason)
4482d71ae5a4SJacob Faibussowitsch {
44834af1b03aSJed Brown   PetscFunctionBegin;
44844af1b03aSJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
44854af1b03aSJed Brown   PetscValidPointer(reason, 2);
44864af1b03aSJed Brown   *reason = ts->reason;
44873ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
44884af1b03aSJed Brown }
44894af1b03aSJed Brown 
4490d6ad946cSShri Abhyankar /*@
4491bcf0153eSBarry Smith    TSSetConvergedReason - Sets the reason for handling the convergence of `TSSolve()`.
4492d6ad946cSShri Abhyankar 
44936b221cbeSPatrick Sanan    Logically Collective; reason must contain common value
4494d6ad946cSShri Abhyankar 
44956b221cbeSPatrick Sanan    Input Parameters:
4496bcf0153eSBarry Smith +  ts - the `TS` context
4497bcf0153eSBarry Smith -  reason - negative value indicates diverged, positive value converged, see `TSConvergedReason` or the
4498d6ad946cSShri Abhyankar             manual pages for the individual convergence tests for complete lists
4499d6ad946cSShri Abhyankar 
4500f5abba47SShri Abhyankar    Level: advanced
4501d6ad946cSShri Abhyankar 
4502bcf0153eSBarry Smith    Note:
4503bcf0153eSBarry Smith    Can only be called while `TSSolve()` is active.
4504d6ad946cSShri Abhyankar 
4505bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSSolve()`, `TSConvergedReason`
4506d6ad946cSShri Abhyankar @*/
4507d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetConvergedReason(TS ts, TSConvergedReason reason)
4508d71ae5a4SJacob Faibussowitsch {
4509d6ad946cSShri Abhyankar   PetscFunctionBegin;
4510d6ad946cSShri Abhyankar   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
4511d6ad946cSShri Abhyankar   ts->reason = reason;
45123ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
4513d6ad946cSShri Abhyankar }
4514d6ad946cSShri Abhyankar 
4515cc708dedSBarry Smith /*@
4516bcf0153eSBarry Smith    TSGetSolveTime - Gets the time after a call to `TSSolve()`
4517cc708dedSBarry Smith 
4518cc708dedSBarry Smith    Not Collective
4519cc708dedSBarry Smith 
4520cc708dedSBarry Smith    Input Parameter:
4521bcf0153eSBarry Smith .  ts - the `TS` context
4522cc708dedSBarry Smith 
4523cc708dedSBarry Smith    Output Parameter:
4524bcf0153eSBarry Smith .  ftime - the final time. This time corresponds to the final time set with `TSSetMaxTime()`
4525cc708dedSBarry Smith 
4526487e0bb9SJed Brown    Level: beginner
4527cc708dedSBarry Smith 
4528bcf0153eSBarry Smith    Note:
4529bcf0153eSBarry Smith    Can only be called after the call to `TSSolve()` is complete.
4530cc708dedSBarry Smith 
4531bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSSolve()`, `TSSetConvergenceTest()`, `TSConvergedReason`
4532cc708dedSBarry Smith @*/
4533d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetSolveTime(TS ts, PetscReal *ftime)
4534d71ae5a4SJacob Faibussowitsch {
4535cc708dedSBarry Smith   PetscFunctionBegin;
4536cc708dedSBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
4537dadcf809SJacob Faibussowitsch   PetscValidRealPointer(ftime, 2);
4538cc708dedSBarry Smith   *ftime = ts->solvetime;
45393ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
4540cc708dedSBarry Smith }
4541cc708dedSBarry Smith 
45422c18e0fdSBarry Smith /*@
45435ef26d82SJed Brown    TSGetSNESIterations - Gets the total number of nonlinear iterations
45449f67acb7SJed Brown    used by the time integrator.
45459f67acb7SJed Brown 
45469f67acb7SJed Brown    Not Collective
45479f67acb7SJed Brown 
45489f67acb7SJed Brown    Input Parameter:
4549bcf0153eSBarry Smith .  ts - `TS` context
45509f67acb7SJed Brown 
45519f67acb7SJed Brown    Output Parameter:
45529f67acb7SJed Brown .  nits - number of nonlinear iterations
45539f67acb7SJed Brown 
45549f67acb7SJed Brown    Level: intermediate
45559f67acb7SJed Brown 
4556195e9b02SBarry Smith    Note:
4557bcf0153eSBarry Smith    This counter is reset to zero for each successive call to `TSSolve()`.
4558bcf0153eSBarry Smith 
4559bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSSolve()`, `TSGetKSPIterations()`
45609f67acb7SJed Brown @*/
4561d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetSNESIterations(TS ts, PetscInt *nits)
4562d71ae5a4SJacob Faibussowitsch {
45639f67acb7SJed Brown   PetscFunctionBegin;
45649f67acb7SJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
45659f67acb7SJed Brown   PetscValidIntPointer(nits, 2);
45665ef26d82SJed Brown   *nits = ts->snes_its;
45673ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
45689f67acb7SJed Brown }
45699f67acb7SJed Brown 
45709f67acb7SJed Brown /*@
45715ef26d82SJed Brown    TSGetKSPIterations - Gets the total number of linear iterations
45729f67acb7SJed Brown    used by the time integrator.
45739f67acb7SJed Brown 
45749f67acb7SJed Brown    Not Collective
45759f67acb7SJed Brown 
45769f67acb7SJed Brown    Input Parameter:
4577bcf0153eSBarry Smith .  ts - `TS` context
45789f67acb7SJed Brown 
45799f67acb7SJed Brown    Output Parameter:
45809f67acb7SJed Brown .  lits - number of linear iterations
45819f67acb7SJed Brown 
45829f67acb7SJed Brown    Level: intermediate
45839f67acb7SJed Brown 
4584bcf0153eSBarry Smith    Note:
4585bcf0153eSBarry Smith    This counter is reset to zero for each successive call to `TSSolve()`.
4586bcf0153eSBarry Smith 
4587bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSSolve()`, `TSGetSNESIterations()`, `SNESGetKSPIterations()`
45889f67acb7SJed Brown @*/
4589d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetKSPIterations(TS ts, PetscInt *lits)
4590d71ae5a4SJacob Faibussowitsch {
45919f67acb7SJed Brown   PetscFunctionBegin;
45929f67acb7SJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
45939f67acb7SJed Brown   PetscValidIntPointer(lits, 2);
45945ef26d82SJed Brown   *lits = ts->ksp_its;
45953ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
45969f67acb7SJed Brown }
45979f67acb7SJed Brown 
4598cef5090cSJed Brown /*@
4599cef5090cSJed Brown    TSGetStepRejections - Gets the total number of rejected steps.
4600cef5090cSJed Brown 
4601cef5090cSJed Brown    Not Collective
4602cef5090cSJed Brown 
4603cef5090cSJed Brown    Input Parameter:
4604bcf0153eSBarry Smith .  ts - `TS` context
4605cef5090cSJed Brown 
4606cef5090cSJed Brown    Output Parameter:
4607cef5090cSJed Brown .  rejects - number of steps rejected
4608cef5090cSJed Brown 
4609cef5090cSJed Brown    Level: intermediate
4610cef5090cSJed Brown 
4611bcf0153eSBarry Smith    Note:
4612bcf0153eSBarry Smith    This counter is reset to zero for each successive call to `TSSolve()`.
4613bcf0153eSBarry Smith 
4614bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSSolve()`, `TSGetSNESIterations()`, `TSGetKSPIterations()`, `TSSetMaxStepRejections()`, `TSGetSNESFailures()`, `TSSetMaxSNESFailures()`, `TSSetErrorIfStepFails()`
4615cef5090cSJed Brown @*/
4616d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetStepRejections(TS ts, PetscInt *rejects)
4617d71ae5a4SJacob Faibussowitsch {
4618cef5090cSJed Brown   PetscFunctionBegin;
4619cef5090cSJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
4620cef5090cSJed Brown   PetscValidIntPointer(rejects, 2);
4621cef5090cSJed Brown   *rejects = ts->reject;
46223ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
4623cef5090cSJed Brown }
4624cef5090cSJed Brown 
4625cef5090cSJed Brown /*@
4626bcf0153eSBarry Smith    TSGetSNESFailures - Gets the total number of failed `SNES` solves in a `TS`
4627cef5090cSJed Brown 
4628cef5090cSJed Brown    Not Collective
4629cef5090cSJed Brown 
4630cef5090cSJed Brown    Input Parameter:
4631bcf0153eSBarry Smith .  ts - `TS` context
4632cef5090cSJed Brown 
4633cef5090cSJed Brown    Output Parameter:
4634cef5090cSJed Brown .  fails - number of failed nonlinear solves
4635cef5090cSJed Brown 
4636cef5090cSJed Brown    Level: intermediate
4637cef5090cSJed Brown 
4638bcf0153eSBarry Smith    Note:
4639bcf0153eSBarry Smith    This counter is reset to zero for each successive call to `TSSolve()`.
4640bcf0153eSBarry Smith 
4641bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSSolve()`, `TSGetSNESIterations()`, `TSGetKSPIterations()`, `TSSetMaxStepRejections()`, `TSGetStepRejections()`, `TSSetMaxSNESFailures()`
4642cef5090cSJed Brown @*/
4643d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetSNESFailures(TS ts, PetscInt *fails)
4644d71ae5a4SJacob Faibussowitsch {
4645cef5090cSJed Brown   PetscFunctionBegin;
4646cef5090cSJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
4647cef5090cSJed Brown   PetscValidIntPointer(fails, 2);
4648cef5090cSJed Brown   *fails = ts->num_snes_failures;
46493ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
4650cef5090cSJed Brown }
4651cef5090cSJed Brown 
4652cef5090cSJed Brown /*@
4653bcf0153eSBarry Smith    TSSetMaxStepRejections - Sets the maximum number of step rejections before a time step fails
4654cef5090cSJed Brown 
4655cef5090cSJed Brown    Not Collective
4656cef5090cSJed Brown 
4657d8d19677SJose E. Roman    Input Parameters:
4658bcf0153eSBarry Smith +  ts - `TS` context
4659cef5090cSJed Brown -  rejects - maximum number of rejected steps, pass -1 for unlimited
4660cef5090cSJed Brown 
4661cef5090cSJed Brown    Options Database Key:
4662cef5090cSJed Brown .  -ts_max_reject - Maximum number of step rejections before a step fails
4663cef5090cSJed Brown 
4664cef5090cSJed Brown    Level: intermediate
4665cef5090cSJed Brown 
4666bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `SNES`, `TSGetSNESIterations()`, `TSGetKSPIterations()`, `TSSetMaxSNESFailures()`, `TSGetStepRejections()`, `TSGetSNESFailures()`, `TSSetErrorIfStepFails()`, `TSGetConvergedReason()`
4667cef5090cSJed Brown @*/
4668d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetMaxStepRejections(TS ts, PetscInt rejects)
4669d71ae5a4SJacob Faibussowitsch {
4670cef5090cSJed Brown   PetscFunctionBegin;
4671cef5090cSJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
4672cef5090cSJed Brown   ts->max_reject = rejects;
46733ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
4674cef5090cSJed Brown }
4675cef5090cSJed Brown 
4676cef5090cSJed Brown /*@
4677bcf0153eSBarry Smith    TSSetMaxSNESFailures - Sets the maximum number of failed `SNES` solves
4678cef5090cSJed Brown 
4679cef5090cSJed Brown    Not Collective
4680cef5090cSJed Brown 
4681d8d19677SJose E. Roman    Input Parameters:
4682bcf0153eSBarry Smith +  ts - `TS` context
4683cef5090cSJed Brown -  fails - maximum number of failed nonlinear solves, pass -1 for unlimited
4684cef5090cSJed Brown 
4685cef5090cSJed Brown    Options Database Key:
4686cef5090cSJed Brown .  -ts_max_snes_failures - Maximum number of nonlinear solve failures
4687cef5090cSJed Brown 
4688cef5090cSJed Brown    Level: intermediate
4689cef5090cSJed Brown 
4690bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `SNES`, `TSGetSNESIterations()`, `TSGetKSPIterations()`, `TSSetMaxStepRejections()`, `TSGetStepRejections()`, `TSGetSNESFailures()`, `SNESGetConvergedReason()`, `TSGetConvergedReason()`
4691cef5090cSJed Brown @*/
4692d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetMaxSNESFailures(TS ts, PetscInt fails)
4693d71ae5a4SJacob Faibussowitsch {
4694cef5090cSJed Brown   PetscFunctionBegin;
4695cef5090cSJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
4696cef5090cSJed Brown   ts->max_snes_failures = fails;
46973ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
4698cef5090cSJed Brown }
4699cef5090cSJed Brown 
4700cef5090cSJed Brown /*@
4701195e9b02SBarry Smith    TSSetErrorIfStepFails - Immediately error if no step succeeds during `TSSolve()`
4702cef5090cSJed Brown 
4703cef5090cSJed Brown    Not Collective
4704cef5090cSJed Brown 
4705d8d19677SJose E. Roman    Input Parameters:
4706bcf0153eSBarry Smith +  ts - `TS` context
4707bcf0153eSBarry Smith -  err - `PETSC_TRUE` to error if no step succeeds, `PETSC_FALSE` to return without failure
4708cef5090cSJed Brown 
4709cef5090cSJed Brown    Options Database Key:
4710cef5090cSJed Brown .  -ts_error_if_step_fails - Error if no step succeeds
4711cef5090cSJed Brown 
4712cef5090cSJed Brown    Level: intermediate
4713cef5090cSJed Brown 
4714bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSGetSNESIterations()`, `TSGetKSPIterations()`, `TSSetMaxStepRejections()`, `TSGetStepRejections()`, `TSGetSNESFailures()`, `TSSetErrorIfStepFails()`, `TSGetConvergedReason()`
4715cef5090cSJed Brown @*/
4716d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetErrorIfStepFails(TS ts, PetscBool err)
4717d71ae5a4SJacob Faibussowitsch {
4718cef5090cSJed Brown   PetscFunctionBegin;
4719cef5090cSJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
4720cef5090cSJed Brown   ts->errorifstepfailed = err;
47213ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
4722cef5090cSJed Brown }
4723cef5090cSJed Brown 
472484df9cb4SJed Brown /*@
4725552698daSJed Brown    TSGetAdapt - Get the adaptive controller context for the current method
472684df9cb4SJed Brown 
4727195e9b02SBarry Smith    Collective on `ts` if controller has not been created yet
472884df9cb4SJed Brown 
47294165533cSJose E. Roman    Input Parameter:
4730ed81e22dSJed Brown .  ts - time stepping context
473184df9cb4SJed Brown 
47324165533cSJose E. Roman    Output Parameter:
4733ed81e22dSJed Brown .  adapt - adaptive controller
473484df9cb4SJed Brown 
473584df9cb4SJed Brown    Level: intermediate
473684df9cb4SJed Brown 
4737bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSAdapt`, `TSAdaptSetType()`, `TSAdaptChoose()`
473884df9cb4SJed Brown @*/
4739d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetAdapt(TS ts, TSAdapt *adapt)
4740d71ae5a4SJacob Faibussowitsch {
474184df9cb4SJed Brown   PetscFunctionBegin;
474284df9cb4SJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
4743bec58848SLisandro Dalcin   PetscValidPointer(adapt, 2);
474484df9cb4SJed Brown   if (!ts->adapt) {
47459566063dSJacob Faibussowitsch     PetscCall(TSAdaptCreate(PetscObjectComm((PetscObject)ts), &ts->adapt));
47469566063dSJacob Faibussowitsch     PetscCall(PetscObjectIncrementTabLevel((PetscObject)ts->adapt, (PetscObject)ts, 1));
474784df9cb4SJed Brown   }
4748bec58848SLisandro Dalcin   *adapt = ts->adapt;
47493ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
475084df9cb4SJed Brown }
4751d6ebe24aSShri Abhyankar 
47521c3436cfSJed Brown /*@
4753195e9b02SBarry Smith    TSSetTolerances - Set tolerances for local truncation error when using an adaptive controller
47541c3436cfSJed Brown 
47551c3436cfSJed Brown    Logically Collective
47561c3436cfSJed Brown 
47574165533cSJose E. Roman    Input Parameters:
47581c3436cfSJed Brown +  ts - time integration context
4759bcf0153eSBarry Smith .  atol - scalar absolute tolerances, `PETSC_DECIDE` to leave current value
4760195e9b02SBarry Smith .  vatol - vector of absolute tolerances or `NULL`, used in preference to atol if present
4761bcf0153eSBarry Smith .  rtol - scalar relative tolerances, `PETSC_DECIDE` to leave current value
4762195e9b02SBarry Smith -  vrtol - vector of relative tolerances or `NULL`, used in preference to atol if present
47631c3436cfSJed Brown 
4764195e9b02SBarry Smith    Options Database Keys:
4765a3cdaa26SBarry Smith +  -ts_rtol <rtol> - relative tolerance for local truncation error
476667b8a455SSatish Balay -  -ts_atol <atol> - Absolute tolerance for local truncation error
4767a3cdaa26SBarry Smith 
4768bcf0153eSBarry Smith    Level: beginner
4769bcf0153eSBarry Smith 
47703ff766beSShri Abhyankar    Notes:
47713ff766beSShri Abhyankar    With PETSc's implicit schemes for DAE problems, the calculation of the local truncation error
47723ff766beSShri Abhyankar    (LTE) includes both the differential and the algebraic variables. If one wants the LTE to be
47733ff766beSShri Abhyankar    computed only for the differential or the algebraic part then this can be done using the vector of
47743ff766beSShri Abhyankar    tolerances vatol. For example, by setting the tolerance vector with the desired tolerance for the
47753ff766beSShri Abhyankar    differential part and infinity for the algebraic part, the LTE calculation will include only the
47763ff766beSShri Abhyankar    differential variables.
47773ff766beSShri Abhyankar 
4778bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSAdapt`, `TSErrorWeightedNorm()`, `TSGetTolerances()`
47791c3436cfSJed Brown @*/
4780d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetTolerances(TS ts, PetscReal atol, Vec vatol, PetscReal rtol, Vec vrtol)
4781d71ae5a4SJacob Faibussowitsch {
47821c3436cfSJed Brown   PetscFunctionBegin;
478313bcc0bdSJacob Faibussowitsch   if (atol != (PetscReal)PETSC_DECIDE && atol != (PetscReal)PETSC_DEFAULT) ts->atol = atol;
47841c3436cfSJed Brown   if (vatol) {
47859566063dSJacob Faibussowitsch     PetscCall(PetscObjectReference((PetscObject)vatol));
47869566063dSJacob Faibussowitsch     PetscCall(VecDestroy(&ts->vatol));
47871c3436cfSJed Brown     ts->vatol = vatol;
47881c3436cfSJed Brown   }
478913bcc0bdSJacob Faibussowitsch   if (rtol != (PetscReal)PETSC_DECIDE && rtol != (PetscReal)PETSC_DEFAULT) ts->rtol = rtol;
47901c3436cfSJed Brown   if (vrtol) {
47919566063dSJacob Faibussowitsch     PetscCall(PetscObjectReference((PetscObject)vrtol));
47929566063dSJacob Faibussowitsch     PetscCall(VecDestroy(&ts->vrtol));
47931c3436cfSJed Brown     ts->vrtol = vrtol;
47941c3436cfSJed Brown   }
47953ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
47961c3436cfSJed Brown }
47971c3436cfSJed Brown 
4798c5033834SJed Brown /*@
4799c5033834SJed Brown    TSGetTolerances - Get tolerances for local truncation error when using adaptive controller
4800c5033834SJed Brown 
4801c5033834SJed Brown    Logically Collective
4802c5033834SJed Brown 
48034165533cSJose E. Roman    Input Parameter:
4804c5033834SJed Brown .  ts - time integration context
4805c5033834SJed Brown 
48064165533cSJose E. Roman    Output Parameters:
4807195e9b02SBarry Smith +  atol - scalar absolute tolerances, `NULL` to ignore
4808195e9b02SBarry Smith .  vatol - vector of absolute tolerances, `NULL` to ignore
4809195e9b02SBarry Smith .  rtol - scalar relative tolerances, `NULL` to ignore
4810195e9b02SBarry Smith -  vrtol - vector of relative tolerances, `NULL` to ignore
4811c5033834SJed Brown 
4812c5033834SJed Brown    Level: beginner
4813c5033834SJed Brown 
4814bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSAdapt`, `TSErrorWeightedNorm()`, `TSSetTolerances()`
4815c5033834SJed Brown @*/
4816d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetTolerances(TS ts, PetscReal *atol, Vec *vatol, PetscReal *rtol, Vec *vrtol)
4817d71ae5a4SJacob Faibussowitsch {
4818c5033834SJed Brown   PetscFunctionBegin;
4819c5033834SJed Brown   if (atol) *atol = ts->atol;
4820c5033834SJed Brown   if (vatol) *vatol = ts->vatol;
4821c5033834SJed Brown   if (rtol) *rtol = ts->rtol;
4822c5033834SJed Brown   if (vrtol) *vrtol = ts->vrtol;
48233ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
4824c5033834SJed Brown }
4825c5033834SJed Brown 
48269c6b16b5SShri Abhyankar /*@
4827a4868fbcSLisandro Dalcin    TSErrorWeightedNorm2 - compute a weighted 2-norm of the difference between two state vectors
48289c6b16b5SShri Abhyankar 
4829c3339decSBarry Smith    Collective
48309c6b16b5SShri Abhyankar 
48314165533cSJose E. Roman    Input Parameters:
48329c6b16b5SShri Abhyankar +  ts - time stepping context
4833a4868fbcSLisandro Dalcin .  U - state vector, usually ts->vec_sol
4834a4868fbcSLisandro Dalcin -  Y - state vector to be compared to U
48359c6b16b5SShri Abhyankar 
48364165533cSJose E. Roman    Output Parameters:
4837a2b725a8SWilliam Gropp +  norm - weighted norm, a value of 1.0 means that the error matches the tolerances
48387453f775SEmil Constantinescu .  norma - weighted norm based on the absolute tolerance, a value of 1.0 means that the error matches the tolerances
4839a2b725a8SWilliam Gropp -  normr - weighted norm based on the relative tolerance, a value of 1.0 means that the error matches the tolerances
48409c6b16b5SShri Abhyankar 
48419c6b16b5SShri Abhyankar    Level: developer
48429c6b16b5SShri Abhyankar 
4843bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSErrorWeightedNorm()`, `TSErrorWeightedNormInfinity()`
48449c6b16b5SShri Abhyankar @*/
4845d71ae5a4SJacob Faibussowitsch PetscErrorCode TSErrorWeightedNorm2(TS ts, Vec U, Vec Y, PetscReal *norm, PetscReal *norma, PetscReal *normr)
4846d71ae5a4SJacob Faibussowitsch {
48479c6b16b5SShri Abhyankar   PetscInt           i, n, N, rstart;
48487453f775SEmil Constantinescu   PetscInt           n_loc, na_loc, nr_loc;
48497453f775SEmil Constantinescu   PetscReal          n_glb, na_glb, nr_glb;
48509c6b16b5SShri Abhyankar   const PetscScalar *u, *y;
48517453f775SEmil Constantinescu   PetscReal          sum, suma, sumr, gsum, gsuma, gsumr, diff;
48527453f775SEmil Constantinescu   PetscReal          tol, tola, tolr;
48537453f775SEmil Constantinescu   PetscReal          err_loc[6], err_glb[6];
48549c6b16b5SShri Abhyankar 
48559c6b16b5SShri Abhyankar   PetscFunctionBegin;
48569c6b16b5SShri Abhyankar   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
4857a4868fbcSLisandro Dalcin   PetscValidHeaderSpecific(U, VEC_CLASSID, 2);
4858a4868fbcSLisandro Dalcin   PetscValidHeaderSpecific(Y, VEC_CLASSID, 3);
4859a4868fbcSLisandro Dalcin   PetscValidType(U, 2);
4860a4868fbcSLisandro Dalcin   PetscValidType(Y, 3);
4861a4868fbcSLisandro Dalcin   PetscCheckSameComm(U, 2, Y, 3);
4862dadcf809SJacob Faibussowitsch   PetscValidRealPointer(norm, 4);
4863dadcf809SJacob Faibussowitsch   PetscValidRealPointer(norma, 5);
4864dadcf809SJacob Faibussowitsch   PetscValidRealPointer(normr, 6);
48653c633725SBarry Smith   PetscCheck(U != Y, PetscObjectComm((PetscObject)U), PETSC_ERR_ARG_IDN, "U and Y cannot be the same vector");
48669c6b16b5SShri Abhyankar 
48679566063dSJacob Faibussowitsch   PetscCall(VecGetSize(U, &N));
48689566063dSJacob Faibussowitsch   PetscCall(VecGetLocalSize(U, &n));
48699566063dSJacob Faibussowitsch   PetscCall(VecGetOwnershipRange(U, &rstart, NULL));
48709566063dSJacob Faibussowitsch   PetscCall(VecGetArrayRead(U, &u));
48719566063dSJacob Faibussowitsch   PetscCall(VecGetArrayRead(Y, &y));
48729371c9d4SSatish Balay   sum    = 0.;
48739371c9d4SSatish Balay   n_loc  = 0;
48749371c9d4SSatish Balay   suma   = 0.;
48759371c9d4SSatish Balay   na_loc = 0;
48769371c9d4SSatish Balay   sumr   = 0.;
48779371c9d4SSatish Balay   nr_loc = 0;
48789c6b16b5SShri Abhyankar   if (ts->vatol && ts->vrtol) {
48799c6b16b5SShri Abhyankar     const PetscScalar *atol, *rtol;
48809566063dSJacob Faibussowitsch     PetscCall(VecGetArrayRead(ts->vatol, &atol));
48819566063dSJacob Faibussowitsch     PetscCall(VecGetArrayRead(ts->vrtol, &rtol));
48829c6b16b5SShri Abhyankar     for (i = 0; i < n; i++) {
488376cddca1SEmil Constantinescu       SkipSmallValue(y[i], u[i], ts->adapt->ignore_max);
48847453f775SEmil Constantinescu       diff = PetscAbsScalar(y[i] - u[i]);
48857453f775SEmil Constantinescu       tola = PetscRealPart(atol[i]);
48867453f775SEmil Constantinescu       if (tola > 0.) {
48877453f775SEmil Constantinescu         suma += PetscSqr(diff / tola);
48887453f775SEmil Constantinescu         na_loc++;
48897453f775SEmil Constantinescu       }
48907453f775SEmil Constantinescu       tolr = PetscRealPart(rtol[i]) * PetscMax(PetscAbsScalar(u[i]), PetscAbsScalar(y[i]));
48917453f775SEmil Constantinescu       if (tolr > 0.) {
48927453f775SEmil Constantinescu         sumr += PetscSqr(diff / tolr);
48937453f775SEmil Constantinescu         nr_loc++;
48947453f775SEmil Constantinescu       }
48957453f775SEmil Constantinescu       tol = tola + tolr;
48967453f775SEmil Constantinescu       if (tol > 0.) {
48977453f775SEmil Constantinescu         sum += PetscSqr(diff / tol);
48987453f775SEmil Constantinescu         n_loc++;
48997453f775SEmil Constantinescu       }
49009c6b16b5SShri Abhyankar     }
49019566063dSJacob Faibussowitsch     PetscCall(VecRestoreArrayRead(ts->vatol, &atol));
49029566063dSJacob Faibussowitsch     PetscCall(VecRestoreArrayRead(ts->vrtol, &rtol));
49039c6b16b5SShri Abhyankar   } else if (ts->vatol) { /* vector atol, scalar rtol */
49049c6b16b5SShri Abhyankar     const PetscScalar *atol;
49059566063dSJacob Faibussowitsch     PetscCall(VecGetArrayRead(ts->vatol, &atol));
49069c6b16b5SShri Abhyankar     for (i = 0; i < n; i++) {
490776cddca1SEmil Constantinescu       SkipSmallValue(y[i], u[i], ts->adapt->ignore_max);
49087453f775SEmil Constantinescu       diff = PetscAbsScalar(y[i] - u[i]);
49097453f775SEmil Constantinescu       tola = PetscRealPart(atol[i]);
49107453f775SEmil Constantinescu       if (tola > 0.) {
49117453f775SEmil Constantinescu         suma += PetscSqr(diff / tola);
49127453f775SEmil Constantinescu         na_loc++;
49137453f775SEmil Constantinescu       }
49147453f775SEmil Constantinescu       tolr = ts->rtol * PetscMax(PetscAbsScalar(u[i]), PetscAbsScalar(y[i]));
49157453f775SEmil Constantinescu       if (tolr > 0.) {
49167453f775SEmil Constantinescu         sumr += PetscSqr(diff / tolr);
49177453f775SEmil Constantinescu         nr_loc++;
49187453f775SEmil Constantinescu       }
49197453f775SEmil Constantinescu       tol = tola + tolr;
49207453f775SEmil Constantinescu       if (tol > 0.) {
49217453f775SEmil Constantinescu         sum += PetscSqr(diff / tol);
49227453f775SEmil Constantinescu         n_loc++;
49237453f775SEmil Constantinescu       }
49249c6b16b5SShri Abhyankar     }
49259566063dSJacob Faibussowitsch     PetscCall(VecRestoreArrayRead(ts->vatol, &atol));
49269c6b16b5SShri Abhyankar   } else if (ts->vrtol) { /* scalar atol, vector rtol */
49279c6b16b5SShri Abhyankar     const PetscScalar *rtol;
49289566063dSJacob Faibussowitsch     PetscCall(VecGetArrayRead(ts->vrtol, &rtol));
49299c6b16b5SShri Abhyankar     for (i = 0; i < n; i++) {
493076cddca1SEmil Constantinescu       SkipSmallValue(y[i], u[i], ts->adapt->ignore_max);
49317453f775SEmil Constantinescu       diff = PetscAbsScalar(y[i] - u[i]);
49327453f775SEmil Constantinescu       tola = ts->atol;
49337453f775SEmil Constantinescu       if (tola > 0.) {
49347453f775SEmil Constantinescu         suma += PetscSqr(diff / tola);
49357453f775SEmil Constantinescu         na_loc++;
49367453f775SEmil Constantinescu       }
49377453f775SEmil Constantinescu       tolr = PetscRealPart(rtol[i]) * PetscMax(PetscAbsScalar(u[i]), PetscAbsScalar(y[i]));
49387453f775SEmil Constantinescu       if (tolr > 0.) {
49397453f775SEmil Constantinescu         sumr += PetscSqr(diff / tolr);
49407453f775SEmil Constantinescu         nr_loc++;
49417453f775SEmil Constantinescu       }
49427453f775SEmil Constantinescu       tol = tola + tolr;
49437453f775SEmil Constantinescu       if (tol > 0.) {
49447453f775SEmil Constantinescu         sum += PetscSqr(diff / tol);
49457453f775SEmil Constantinescu         n_loc++;
49467453f775SEmil Constantinescu       }
49479c6b16b5SShri Abhyankar     }
49489566063dSJacob Faibussowitsch     PetscCall(VecRestoreArrayRead(ts->vrtol, &rtol));
49499c6b16b5SShri Abhyankar   } else { /* scalar atol, scalar rtol */
49509c6b16b5SShri Abhyankar     for (i = 0; i < n; i++) {
495176cddca1SEmil Constantinescu       SkipSmallValue(y[i], u[i], ts->adapt->ignore_max);
49527453f775SEmil Constantinescu       diff = PetscAbsScalar(y[i] - u[i]);
49537453f775SEmil Constantinescu       tola = ts->atol;
49547453f775SEmil Constantinescu       if (tola > 0.) {
49557453f775SEmil Constantinescu         suma += PetscSqr(diff / tola);
49567453f775SEmil Constantinescu         na_loc++;
49577453f775SEmil Constantinescu       }
49587453f775SEmil Constantinescu       tolr = ts->rtol * PetscMax(PetscAbsScalar(u[i]), PetscAbsScalar(y[i]));
49597453f775SEmil Constantinescu       if (tolr > 0.) {
49607453f775SEmil Constantinescu         sumr += PetscSqr(diff / tolr);
49617453f775SEmil Constantinescu         nr_loc++;
49627453f775SEmil Constantinescu       }
49637453f775SEmil Constantinescu       tol = tola + tolr;
49647453f775SEmil Constantinescu       if (tol > 0.) {
49657453f775SEmil Constantinescu         sum += PetscSqr(diff / tol);
49667453f775SEmil Constantinescu         n_loc++;
49677453f775SEmil Constantinescu       }
49689c6b16b5SShri Abhyankar     }
49699c6b16b5SShri Abhyankar   }
49709566063dSJacob Faibussowitsch   PetscCall(VecRestoreArrayRead(U, &u));
49719566063dSJacob Faibussowitsch   PetscCall(VecRestoreArrayRead(Y, &y));
49729c6b16b5SShri Abhyankar 
49737453f775SEmil Constantinescu   err_loc[0] = sum;
49747453f775SEmil Constantinescu   err_loc[1] = suma;
49757453f775SEmil Constantinescu   err_loc[2] = sumr;
49767453f775SEmil Constantinescu   err_loc[3] = (PetscReal)n_loc;
49777453f775SEmil Constantinescu   err_loc[4] = (PetscReal)na_loc;
49787453f775SEmil Constantinescu   err_loc[5] = (PetscReal)nr_loc;
49797453f775SEmil Constantinescu 
49801c2dc1cbSBarry Smith   PetscCall(MPIU_Allreduce(err_loc, err_glb, 6, MPIU_REAL, MPIU_SUM, PetscObjectComm((PetscObject)ts)));
49817453f775SEmil Constantinescu 
49827453f775SEmil Constantinescu   gsum   = err_glb[0];
49837453f775SEmil Constantinescu   gsuma  = err_glb[1];
49847453f775SEmil Constantinescu   gsumr  = err_glb[2];
49857453f775SEmil Constantinescu   n_glb  = err_glb[3];
49867453f775SEmil Constantinescu   na_glb = err_glb[4];
49877453f775SEmil Constantinescu   nr_glb = err_glb[5];
49887453f775SEmil Constantinescu 
4989b1316ef9SEmil Constantinescu   *norm = 0.;
49901e66621cSBarry Smith   if (n_glb > 0.) *norm = PetscSqrtReal(gsum / n_glb);
4991b1316ef9SEmil Constantinescu   *norma = 0.;
49921e66621cSBarry Smith   if (na_glb > 0.) *norma = PetscSqrtReal(gsuma / na_glb);
4993b1316ef9SEmil Constantinescu   *normr = 0.;
49941e66621cSBarry Smith   if (nr_glb > 0.) *normr = PetscSqrtReal(gsumr / nr_glb);
49959c6b16b5SShri Abhyankar 
49963c633725SBarry Smith   PetscCheck(!PetscIsInfOrNanScalar(*norm), PetscObjectComm((PetscObject)ts), PETSC_ERR_FP, "Infinite or not-a-number generated in norm");
49973c633725SBarry Smith   PetscCheck(!PetscIsInfOrNanScalar(*norma), PetscObjectComm((PetscObject)ts), PETSC_ERR_FP, "Infinite or not-a-number generated in norma");
49983c633725SBarry Smith   PetscCheck(!PetscIsInfOrNanScalar(*normr), PetscObjectComm((PetscObject)ts), PETSC_ERR_FP, "Infinite or not-a-number generated in normr");
49993ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
50009c6b16b5SShri Abhyankar }
50019c6b16b5SShri Abhyankar 
50029c6b16b5SShri Abhyankar /*@
5003a4868fbcSLisandro Dalcin    TSErrorWeightedNormInfinity - compute a weighted infinity-norm of the difference between two state vectors
50049c6b16b5SShri Abhyankar 
5005c3339decSBarry Smith    Collective
50069c6b16b5SShri Abhyankar 
50074165533cSJose E. Roman    Input Parameters:
50089c6b16b5SShri Abhyankar +  ts - time stepping context
5009a4868fbcSLisandro Dalcin .  U - state vector, usually ts->vec_sol
5010a4868fbcSLisandro Dalcin -  Y - state vector to be compared to U
50119c6b16b5SShri Abhyankar 
50124165533cSJose E. Roman    Output Parameters:
5013a2b725a8SWilliam Gropp +  norm - weighted norm, a value of 1.0 means that the error matches the tolerances
50147453f775SEmil Constantinescu .  norma - weighted norm based on the absolute tolerance, a value of 1.0 means that the error matches the tolerances
5015a2b725a8SWilliam Gropp -  normr - weighted norm based on the relative tolerance, a value of 1.0 means that the error matches the tolerances
50169c6b16b5SShri Abhyankar 
50179c6b16b5SShri Abhyankar    Level: developer
50189c6b16b5SShri Abhyankar 
5019bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSErrorWeightedNorm()`, `TSErrorWeightedNorm2()`
50209c6b16b5SShri Abhyankar @*/
5021d71ae5a4SJacob Faibussowitsch PetscErrorCode TSErrorWeightedNormInfinity(TS ts, Vec U, Vec Y, PetscReal *norm, PetscReal *norma, PetscReal *normr)
5022d71ae5a4SJacob Faibussowitsch {
50237453f775SEmil Constantinescu   PetscInt           i, n, N, rstart;
50249c6b16b5SShri Abhyankar   const PetscScalar *u, *y;
50257453f775SEmil Constantinescu   PetscReal          max, gmax, maxa, gmaxa, maxr, gmaxr;
50267453f775SEmil Constantinescu   PetscReal          tol, tola, tolr, diff;
50277453f775SEmil Constantinescu   PetscReal          err_loc[3], err_glb[3];
50289c6b16b5SShri Abhyankar 
50299c6b16b5SShri Abhyankar   PetscFunctionBegin;
50309c6b16b5SShri Abhyankar   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
5031a4868fbcSLisandro Dalcin   PetscValidHeaderSpecific(U, VEC_CLASSID, 2);
5032a4868fbcSLisandro Dalcin   PetscValidHeaderSpecific(Y, VEC_CLASSID, 3);
5033a4868fbcSLisandro Dalcin   PetscValidType(U, 2);
5034a4868fbcSLisandro Dalcin   PetscValidType(Y, 3);
5035a4868fbcSLisandro Dalcin   PetscCheckSameComm(U, 2, Y, 3);
5036dadcf809SJacob Faibussowitsch   PetscValidRealPointer(norm, 4);
5037dadcf809SJacob Faibussowitsch   PetscValidRealPointer(norma, 5);
5038dadcf809SJacob Faibussowitsch   PetscValidRealPointer(normr, 6);
50393c633725SBarry Smith   PetscCheck(U != Y, PetscObjectComm((PetscObject)U), PETSC_ERR_ARG_IDN, "U and Y cannot be the same vector");
50409c6b16b5SShri Abhyankar 
50419566063dSJacob Faibussowitsch   PetscCall(VecGetSize(U, &N));
50429566063dSJacob Faibussowitsch   PetscCall(VecGetLocalSize(U, &n));
50439566063dSJacob Faibussowitsch   PetscCall(VecGetOwnershipRange(U, &rstart, NULL));
50449566063dSJacob Faibussowitsch   PetscCall(VecGetArrayRead(U, &u));
50459566063dSJacob Faibussowitsch   PetscCall(VecGetArrayRead(Y, &y));
50467453f775SEmil Constantinescu 
50477453f775SEmil Constantinescu   max  = 0.;
50487453f775SEmil Constantinescu   maxa = 0.;
50497453f775SEmil Constantinescu   maxr = 0.;
50507453f775SEmil Constantinescu 
50517453f775SEmil Constantinescu   if (ts->vatol && ts->vrtol) { /* vector atol, vector rtol */
50529c6b16b5SShri Abhyankar     const PetscScalar *atol, *rtol;
50539566063dSJacob Faibussowitsch     PetscCall(VecGetArrayRead(ts->vatol, &atol));
50549566063dSJacob Faibussowitsch     PetscCall(VecGetArrayRead(ts->vrtol, &rtol));
50557453f775SEmil Constantinescu 
50567453f775SEmil Constantinescu     for (i = 0; i < n; i++) {
505776cddca1SEmil Constantinescu       SkipSmallValue(y[i], u[i], ts->adapt->ignore_max);
50587453f775SEmil Constantinescu       diff = PetscAbsScalar(y[i] - u[i]);
50597453f775SEmil Constantinescu       tola = PetscRealPart(atol[i]);
50607453f775SEmil Constantinescu       tolr = PetscRealPart(rtol[i]) * PetscMax(PetscAbsScalar(u[i]), PetscAbsScalar(y[i]));
50617453f775SEmil Constantinescu       tol  = tola + tolr;
50621e66621cSBarry Smith       if (tola > 0.) maxa = PetscMax(maxa, diff / tola);
50631e66621cSBarry Smith       if (tolr > 0.) maxr = PetscMax(maxr, diff / tolr);
50641e66621cSBarry Smith       if (tol > 0.) max = PetscMax(max, diff / tol);
50659c6b16b5SShri Abhyankar     }
50669566063dSJacob Faibussowitsch     PetscCall(VecRestoreArrayRead(ts->vatol, &atol));
50679566063dSJacob Faibussowitsch     PetscCall(VecRestoreArrayRead(ts->vrtol, &rtol));
50689c6b16b5SShri Abhyankar   } else if (ts->vatol) { /* vector atol, scalar rtol */
50699c6b16b5SShri Abhyankar     const PetscScalar *atol;
50709566063dSJacob Faibussowitsch     PetscCall(VecGetArrayRead(ts->vatol, &atol));
50717453f775SEmil Constantinescu     for (i = 0; i < n; i++) {
507276cddca1SEmil Constantinescu       SkipSmallValue(y[i], u[i], ts->adapt->ignore_max);
50737453f775SEmil Constantinescu       diff = PetscAbsScalar(y[i] - u[i]);
50747453f775SEmil Constantinescu       tola = PetscRealPart(atol[i]);
50757453f775SEmil Constantinescu       tolr = ts->rtol * PetscMax(PetscAbsScalar(u[i]), PetscAbsScalar(y[i]));
50767453f775SEmil Constantinescu       tol  = tola + tolr;
50771e66621cSBarry Smith       if (tola > 0.) maxa = PetscMax(maxa, diff / tola);
50781e66621cSBarry Smith       if (tolr > 0.) maxr = PetscMax(maxr, diff / tolr);
50791e66621cSBarry Smith       if (tol > 0.) max = PetscMax(max, diff / tol);
50809c6b16b5SShri Abhyankar     }
50819566063dSJacob Faibussowitsch     PetscCall(VecRestoreArrayRead(ts->vatol, &atol));
50829c6b16b5SShri Abhyankar   } else if (ts->vrtol) { /* scalar atol, vector rtol */
50839c6b16b5SShri Abhyankar     const PetscScalar *rtol;
50849566063dSJacob Faibussowitsch     PetscCall(VecGetArrayRead(ts->vrtol, &rtol));
50857453f775SEmil Constantinescu 
50867453f775SEmil Constantinescu     for (i = 0; i < n; i++) {
508776cddca1SEmil Constantinescu       SkipSmallValue(y[i], u[i], ts->adapt->ignore_max);
50887453f775SEmil Constantinescu       diff = PetscAbsScalar(y[i] - u[i]);
50897453f775SEmil Constantinescu       tola = ts->atol;
50907453f775SEmil Constantinescu       tolr = PetscRealPart(rtol[i]) * PetscMax(PetscAbsScalar(u[i]), PetscAbsScalar(y[i]));
50917453f775SEmil Constantinescu       tol  = tola + tolr;
50921e66621cSBarry Smith       if (tola > 0.) maxa = PetscMax(maxa, diff / tola);
50931e66621cSBarry Smith       if (tolr > 0.) maxr = PetscMax(maxr, diff / tolr);
50941e66621cSBarry Smith       if (tol > 0.) max = PetscMax(max, diff / tol);
50959c6b16b5SShri Abhyankar     }
50969566063dSJacob Faibussowitsch     PetscCall(VecRestoreArrayRead(ts->vrtol, &rtol));
50979c6b16b5SShri Abhyankar   } else { /* scalar atol, scalar rtol */
50987453f775SEmil Constantinescu 
50997453f775SEmil Constantinescu     for (i = 0; i < n; i++) {
510076cddca1SEmil Constantinescu       SkipSmallValue(y[i], u[i], ts->adapt->ignore_max);
51017453f775SEmil Constantinescu       diff = PetscAbsScalar(y[i] - u[i]);
51027453f775SEmil Constantinescu       tola = ts->atol;
51037453f775SEmil Constantinescu       tolr = ts->rtol * PetscMax(PetscAbsScalar(u[i]), PetscAbsScalar(y[i]));
51047453f775SEmil Constantinescu       tol  = tola + tolr;
51051e66621cSBarry Smith       if (tola > 0.) maxa = PetscMax(maxa, diff / tola);
51061e66621cSBarry Smith       if (tolr > 0.) maxr = PetscMax(maxr, diff / tolr);
51071e66621cSBarry Smith       if (tol > 0.) max = PetscMax(max, diff / tol);
51089c6b16b5SShri Abhyankar     }
51099c6b16b5SShri Abhyankar   }
51109566063dSJacob Faibussowitsch   PetscCall(VecRestoreArrayRead(U, &u));
51119566063dSJacob Faibussowitsch   PetscCall(VecRestoreArrayRead(Y, &y));
51127453f775SEmil Constantinescu   err_loc[0] = max;
51137453f775SEmil Constantinescu   err_loc[1] = maxa;
51147453f775SEmil Constantinescu   err_loc[2] = maxr;
51151c2dc1cbSBarry Smith   PetscCall(MPIU_Allreduce(err_loc, err_glb, 3, MPIU_REAL, MPIU_MAX, PetscObjectComm((PetscObject)ts)));
51167453f775SEmil Constantinescu   gmax  = err_glb[0];
51177453f775SEmil Constantinescu   gmaxa = err_glb[1];
51187453f775SEmil Constantinescu   gmaxr = err_glb[2];
51199c6b16b5SShri Abhyankar 
51209c6b16b5SShri Abhyankar   *norm  = gmax;
51217453f775SEmil Constantinescu   *norma = gmaxa;
51227453f775SEmil Constantinescu   *normr = gmaxr;
51233c633725SBarry Smith   PetscCheck(!PetscIsInfOrNanScalar(*norm), PetscObjectComm((PetscObject)ts), PETSC_ERR_FP, "Infinite or not-a-number generated in norm");
51243c633725SBarry Smith   PetscCheck(!PetscIsInfOrNanScalar(*norma), PetscObjectComm((PetscObject)ts), PETSC_ERR_FP, "Infinite or not-a-number generated in norma");
51253c633725SBarry Smith   PetscCheck(!PetscIsInfOrNanScalar(*normr), PetscObjectComm((PetscObject)ts), PETSC_ERR_FP, "Infinite or not-a-number generated in normr");
51263ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
51279c6b16b5SShri Abhyankar }
51289c6b16b5SShri Abhyankar 
51291c3436cfSJed Brown /*@
51308a175baeSEmil Constantinescu    TSErrorWeightedNorm - compute a weighted norm of the difference between two state vectors based on supplied absolute and relative tolerances
51311c3436cfSJed Brown 
5132c3339decSBarry Smith    Collective
51331c3436cfSJed Brown 
51344165533cSJose E. Roman    Input Parameters:
51351c3436cfSJed Brown +  ts - time stepping context
5136a4868fbcSLisandro Dalcin .  U - state vector, usually ts->vec_sol
5137a4868fbcSLisandro Dalcin .  Y - state vector to be compared to U
5138bcf0153eSBarry Smith -  wnormtype - norm type, either `NORM_2` or `NORM_INFINITY`
51397619abb3SShri 
51404165533cSJose E. Roman    Output Parameters:
5141a2b725a8SWilliam Gropp +  norm  - weighted norm, a value of 1.0 achieves a balance between absolute and relative tolerances
51428a175baeSEmil Constantinescu .  norma - weighted norm, a value of 1.0 means that the error meets the absolute tolerance set by the user
5143a2b725a8SWilliam Gropp -  normr - weighted norm, a value of 1.0 means that the error meets the relative tolerance set by the user
5144a4868fbcSLisandro Dalcin 
5145bcf0153eSBarry Smith    Options Database Key:
5146a4868fbcSLisandro Dalcin .  -ts_adapt_wnormtype <wnormtype> - 2, INFINITY
5147a4868fbcSLisandro Dalcin 
51481c3436cfSJed Brown    Level: developer
51491c3436cfSJed Brown 
5150bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSErrorWeightedNormInfinity()`, `TSErrorWeightedNorm2()`, `TSErrorWeightedENorm`
51511c3436cfSJed Brown @*/
5152d71ae5a4SJacob Faibussowitsch PetscErrorCode TSErrorWeightedNorm(TS ts, Vec U, Vec Y, NormType wnormtype, PetscReal *norm, PetscReal *norma, PetscReal *normr)
5153d71ae5a4SJacob Faibussowitsch {
51541c3436cfSJed Brown   PetscFunctionBegin;
51551e66621cSBarry Smith   if (wnormtype == NORM_2) PetscCall(TSErrorWeightedNorm2(ts, U, Y, norm, norma, normr));
51561e66621cSBarry Smith   else if (wnormtype == NORM_INFINITY) PetscCall(TSErrorWeightedNormInfinity(ts, U, Y, norm, norma, normr));
51571e66621cSBarry Smith   else SETERRQ(PETSC_COMM_SELF, PETSC_ERR_SUP, "No support for norm type %s", NormTypes[wnormtype]);
51583ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
51591c3436cfSJed Brown }
51601c3436cfSJed Brown 
51618a175baeSEmil Constantinescu /*@
51628a175baeSEmil Constantinescu    TSErrorWeightedENorm2 - compute a weighted 2 error norm based on supplied absolute and relative tolerances
51638a175baeSEmil Constantinescu 
5164c3339decSBarry Smith    Collective
51658a175baeSEmil Constantinescu 
51664165533cSJose E. Roman    Input Parameters:
51678a175baeSEmil Constantinescu +  ts - time stepping context
51688a175baeSEmil Constantinescu .  E - error vector
51698a175baeSEmil Constantinescu .  U - state vector, usually ts->vec_sol
51708a175baeSEmil Constantinescu -  Y - state vector, previous time step
51718a175baeSEmil Constantinescu 
51724165533cSJose E. Roman    Output Parameters:
5173a2b725a8SWilliam Gropp +  norm - weighted norm, a value of 1.0 means that the error matches the tolerances
51748a175baeSEmil Constantinescu .  norma - weighted norm based on the absolute tolerance, a value of 1.0 means that the error matches the tolerances
5175a2b725a8SWilliam Gropp -  normr - weighted norm based on the relative tolerance, a value of 1.0 means that the error matches the tolerances
51768a175baeSEmil Constantinescu 
51778a175baeSEmil Constantinescu    Level: developer
51788a175baeSEmil Constantinescu 
5179bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSErrorWeightedENorm()`, `TSErrorWeightedENormInfinity()`
51808a175baeSEmil Constantinescu @*/
5181d71ae5a4SJacob Faibussowitsch PetscErrorCode TSErrorWeightedENorm2(TS ts, Vec E, Vec U, Vec Y, PetscReal *norm, PetscReal *norma, PetscReal *normr)
5182d71ae5a4SJacob Faibussowitsch {
51838a175baeSEmil Constantinescu   PetscInt           i, n, N, rstart;
51848a175baeSEmil Constantinescu   PetscInt           n_loc, na_loc, nr_loc;
51858a175baeSEmil Constantinescu   PetscReal          n_glb, na_glb, nr_glb;
51868a175baeSEmil Constantinescu   const PetscScalar *e, *u, *y;
51878a175baeSEmil Constantinescu   PetscReal          err, sum, suma, sumr, gsum, gsuma, gsumr;
51888a175baeSEmil Constantinescu   PetscReal          tol, tola, tolr;
51898a175baeSEmil Constantinescu   PetscReal          err_loc[6], err_glb[6];
51908a175baeSEmil Constantinescu 
51918a175baeSEmil Constantinescu   PetscFunctionBegin;
51928a175baeSEmil Constantinescu   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
51938a175baeSEmil Constantinescu   PetscValidHeaderSpecific(E, VEC_CLASSID, 2);
51948a175baeSEmil Constantinescu   PetscValidHeaderSpecific(U, VEC_CLASSID, 3);
51958a175baeSEmil Constantinescu   PetscValidHeaderSpecific(Y, VEC_CLASSID, 4);
51968a175baeSEmil Constantinescu   PetscValidType(E, 2);
51978a175baeSEmil Constantinescu   PetscValidType(U, 3);
51988a175baeSEmil Constantinescu   PetscValidType(Y, 4);
51998a175baeSEmil Constantinescu   PetscCheckSameComm(E, 2, U, 3);
5200064a246eSJacob Faibussowitsch   PetscCheckSameComm(U, 3, Y, 4);
5201dadcf809SJacob Faibussowitsch   PetscValidRealPointer(norm, 5);
5202dadcf809SJacob Faibussowitsch   PetscValidRealPointer(norma, 6);
5203dadcf809SJacob Faibussowitsch   PetscValidRealPointer(normr, 7);
52048a175baeSEmil Constantinescu 
52059566063dSJacob Faibussowitsch   PetscCall(VecGetSize(E, &N));
52069566063dSJacob Faibussowitsch   PetscCall(VecGetLocalSize(E, &n));
52079566063dSJacob Faibussowitsch   PetscCall(VecGetOwnershipRange(E, &rstart, NULL));
52089566063dSJacob Faibussowitsch   PetscCall(VecGetArrayRead(E, &e));
52099566063dSJacob Faibussowitsch   PetscCall(VecGetArrayRead(U, &u));
52109566063dSJacob Faibussowitsch   PetscCall(VecGetArrayRead(Y, &y));
52119371c9d4SSatish Balay   sum    = 0.;
52129371c9d4SSatish Balay   n_loc  = 0;
52139371c9d4SSatish Balay   suma   = 0.;
52149371c9d4SSatish Balay   na_loc = 0;
52159371c9d4SSatish Balay   sumr   = 0.;
52169371c9d4SSatish Balay   nr_loc = 0;
52178a175baeSEmil Constantinescu   if (ts->vatol && ts->vrtol) {
52188a175baeSEmil Constantinescu     const PetscScalar *atol, *rtol;
52199566063dSJacob Faibussowitsch     PetscCall(VecGetArrayRead(ts->vatol, &atol));
52209566063dSJacob Faibussowitsch     PetscCall(VecGetArrayRead(ts->vrtol, &rtol));
52218a175baeSEmil Constantinescu     for (i = 0; i < n; i++) {
522276cddca1SEmil Constantinescu       SkipSmallValue(y[i], u[i], ts->adapt->ignore_max);
52238a175baeSEmil Constantinescu       err  = PetscAbsScalar(e[i]);
52248a175baeSEmil Constantinescu       tola = PetscRealPart(atol[i]);
52258a175baeSEmil Constantinescu       if (tola > 0.) {
52268a175baeSEmil Constantinescu         suma += PetscSqr(err / tola);
52278a175baeSEmil Constantinescu         na_loc++;
52288a175baeSEmil Constantinescu       }
52298a175baeSEmil Constantinescu       tolr = PetscRealPart(rtol[i]) * PetscMax(PetscAbsScalar(u[i]), PetscAbsScalar(y[i]));
52308a175baeSEmil Constantinescu       if (tolr > 0.) {
52318a175baeSEmil Constantinescu         sumr += PetscSqr(err / tolr);
52328a175baeSEmil Constantinescu         nr_loc++;
52338a175baeSEmil Constantinescu       }
52348a175baeSEmil Constantinescu       tol = tola + tolr;
52358a175baeSEmil Constantinescu       if (tol > 0.) {
52368a175baeSEmil Constantinescu         sum += PetscSqr(err / tol);
52378a175baeSEmil Constantinescu         n_loc++;
52388a175baeSEmil Constantinescu       }
52398a175baeSEmil Constantinescu     }
52409566063dSJacob Faibussowitsch     PetscCall(VecRestoreArrayRead(ts->vatol, &atol));
52419566063dSJacob Faibussowitsch     PetscCall(VecRestoreArrayRead(ts->vrtol, &rtol));
52428a175baeSEmil Constantinescu   } else if (ts->vatol) { /* vector atol, scalar rtol */
52438a175baeSEmil Constantinescu     const PetscScalar *atol;
52449566063dSJacob Faibussowitsch     PetscCall(VecGetArrayRead(ts->vatol, &atol));
52458a175baeSEmil Constantinescu     for (i = 0; i < n; i++) {
524676cddca1SEmil Constantinescu       SkipSmallValue(y[i], u[i], ts->adapt->ignore_max);
52478a175baeSEmil Constantinescu       err  = PetscAbsScalar(e[i]);
52488a175baeSEmil Constantinescu       tola = PetscRealPart(atol[i]);
52498a175baeSEmil Constantinescu       if (tola > 0.) {
52508a175baeSEmil Constantinescu         suma += PetscSqr(err / tola);
52518a175baeSEmil Constantinescu         na_loc++;
52528a175baeSEmil Constantinescu       }
52538a175baeSEmil Constantinescu       tolr = ts->rtol * PetscMax(PetscAbsScalar(u[i]), PetscAbsScalar(y[i]));
52548a175baeSEmil Constantinescu       if (tolr > 0.) {
52558a175baeSEmil Constantinescu         sumr += PetscSqr(err / tolr);
52568a175baeSEmil Constantinescu         nr_loc++;
52578a175baeSEmil Constantinescu       }
52588a175baeSEmil Constantinescu       tol = tola + tolr;
52598a175baeSEmil Constantinescu       if (tol > 0.) {
52608a175baeSEmil Constantinescu         sum += PetscSqr(err / tol);
52618a175baeSEmil Constantinescu         n_loc++;
52628a175baeSEmil Constantinescu       }
52638a175baeSEmil Constantinescu     }
52649566063dSJacob Faibussowitsch     PetscCall(VecRestoreArrayRead(ts->vatol, &atol));
52658a175baeSEmil Constantinescu   } else if (ts->vrtol) { /* scalar atol, vector rtol */
52668a175baeSEmil Constantinescu     const PetscScalar *rtol;
52679566063dSJacob Faibussowitsch     PetscCall(VecGetArrayRead(ts->vrtol, &rtol));
52688a175baeSEmil Constantinescu     for (i = 0; i < n; i++) {
526976cddca1SEmil Constantinescu       SkipSmallValue(y[i], u[i], ts->adapt->ignore_max);
52708a175baeSEmil Constantinescu       err  = PetscAbsScalar(e[i]);
52718a175baeSEmil Constantinescu       tola = ts->atol;
52728a175baeSEmil Constantinescu       if (tola > 0.) {
52738a175baeSEmil Constantinescu         suma += PetscSqr(err / tola);
52748a175baeSEmil Constantinescu         na_loc++;
52758a175baeSEmil Constantinescu       }
52768a175baeSEmil Constantinescu       tolr = PetscRealPart(rtol[i]) * PetscMax(PetscAbsScalar(u[i]), PetscAbsScalar(y[i]));
52778a175baeSEmil Constantinescu       if (tolr > 0.) {
52788a175baeSEmil Constantinescu         sumr += PetscSqr(err / tolr);
52798a175baeSEmil Constantinescu         nr_loc++;
52808a175baeSEmil Constantinescu       }
52818a175baeSEmil Constantinescu       tol = tola + tolr;
52828a175baeSEmil Constantinescu       if (tol > 0.) {
52838a175baeSEmil Constantinescu         sum += PetscSqr(err / tol);
52848a175baeSEmil Constantinescu         n_loc++;
52858a175baeSEmil Constantinescu       }
52868a175baeSEmil Constantinescu     }
52879566063dSJacob Faibussowitsch     PetscCall(VecRestoreArrayRead(ts->vrtol, &rtol));
52888a175baeSEmil Constantinescu   } else { /* scalar atol, scalar rtol */
52898a175baeSEmil Constantinescu     for (i = 0; i < n; i++) {
529076cddca1SEmil Constantinescu       SkipSmallValue(y[i], u[i], ts->adapt->ignore_max);
52918a175baeSEmil Constantinescu       err  = PetscAbsScalar(e[i]);
52928a175baeSEmil Constantinescu       tola = ts->atol;
52938a175baeSEmil Constantinescu       if (tola > 0.) {
52948a175baeSEmil Constantinescu         suma += PetscSqr(err / tola);
52958a175baeSEmil Constantinescu         na_loc++;
52968a175baeSEmil Constantinescu       }
52978a175baeSEmil Constantinescu       tolr = ts->rtol * PetscMax(PetscAbsScalar(u[i]), PetscAbsScalar(y[i]));
52988a175baeSEmil Constantinescu       if (tolr > 0.) {
52998a175baeSEmil Constantinescu         sumr += PetscSqr(err / tolr);
53008a175baeSEmil Constantinescu         nr_loc++;
53018a175baeSEmil Constantinescu       }
53028a175baeSEmil Constantinescu       tol = tola + tolr;
53038a175baeSEmil Constantinescu       if (tol > 0.) {
53048a175baeSEmil Constantinescu         sum += PetscSqr(err / tol);
53058a175baeSEmil Constantinescu         n_loc++;
53068a175baeSEmil Constantinescu       }
53078a175baeSEmil Constantinescu     }
53088a175baeSEmil Constantinescu   }
53099566063dSJacob Faibussowitsch   PetscCall(VecRestoreArrayRead(E, &e));
53109566063dSJacob Faibussowitsch   PetscCall(VecRestoreArrayRead(U, &u));
53119566063dSJacob Faibussowitsch   PetscCall(VecRestoreArrayRead(Y, &y));
53128a175baeSEmil Constantinescu 
53138a175baeSEmil Constantinescu   err_loc[0] = sum;
53148a175baeSEmil Constantinescu   err_loc[1] = suma;
53158a175baeSEmil Constantinescu   err_loc[2] = sumr;
53168a175baeSEmil Constantinescu   err_loc[3] = (PetscReal)n_loc;
53178a175baeSEmil Constantinescu   err_loc[4] = (PetscReal)na_loc;
53188a175baeSEmil Constantinescu   err_loc[5] = (PetscReal)nr_loc;
53198a175baeSEmil Constantinescu 
53201c2dc1cbSBarry Smith   PetscCall(MPIU_Allreduce(err_loc, err_glb, 6, MPIU_REAL, MPIU_SUM, PetscObjectComm((PetscObject)ts)));
53218a175baeSEmil Constantinescu 
53228a175baeSEmil Constantinescu   gsum   = err_glb[0];
53238a175baeSEmil Constantinescu   gsuma  = err_glb[1];
53248a175baeSEmil Constantinescu   gsumr  = err_glb[2];
53258a175baeSEmil Constantinescu   n_glb  = err_glb[3];
53268a175baeSEmil Constantinescu   na_glb = err_glb[4];
53278a175baeSEmil Constantinescu   nr_glb = err_glb[5];
53288a175baeSEmil Constantinescu 
53298a175baeSEmil Constantinescu   *norm = 0.;
53301e66621cSBarry Smith   if (n_glb > 0.) *norm = PetscSqrtReal(gsum / n_glb);
53318a175baeSEmil Constantinescu   *norma = 0.;
53321e66621cSBarry Smith   if (na_glb > 0.) *norma = PetscSqrtReal(gsuma / na_glb);
53338a175baeSEmil Constantinescu   *normr = 0.;
53341e66621cSBarry Smith   if (nr_glb > 0.) *normr = PetscSqrtReal(gsumr / nr_glb);
53358a175baeSEmil Constantinescu 
53363c633725SBarry Smith   PetscCheck(!PetscIsInfOrNanScalar(*norm), PetscObjectComm((PetscObject)ts), PETSC_ERR_FP, "Infinite or not-a-number generated in norm");
53373c633725SBarry Smith   PetscCheck(!PetscIsInfOrNanScalar(*norma), PetscObjectComm((PetscObject)ts), PETSC_ERR_FP, "Infinite or not-a-number generated in norma");
53383c633725SBarry Smith   PetscCheck(!PetscIsInfOrNanScalar(*normr), PetscObjectComm((PetscObject)ts), PETSC_ERR_FP, "Infinite or not-a-number generated in normr");
53393ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
53408a175baeSEmil Constantinescu }
53418a175baeSEmil Constantinescu 
53428a175baeSEmil Constantinescu /*@
53438a175baeSEmil Constantinescu    TSErrorWeightedENormInfinity - compute a weighted infinity error norm based on supplied absolute and relative tolerances
5344bcf0153eSBarry Smith 
5345c3339decSBarry Smith    Collective
53468a175baeSEmil Constantinescu 
53474165533cSJose E. Roman    Input Parameters:
53488a175baeSEmil Constantinescu +  ts - time stepping context
53498a175baeSEmil Constantinescu .  E - error vector
53508a175baeSEmil Constantinescu .  U - state vector, usually ts->vec_sol
53518a175baeSEmil Constantinescu -  Y - state vector, previous time step
53528a175baeSEmil Constantinescu 
53534165533cSJose E. Roman    Output Parameters:
5354a2b725a8SWilliam Gropp +  norm - weighted norm, a value of 1.0 means that the error matches the tolerances
53558a175baeSEmil Constantinescu .  norma - weighted norm based on the absolute tolerance, a value of 1.0 means that the error matches the tolerances
5356a2b725a8SWilliam Gropp -  normr - weighted norm based on the relative tolerance, a value of 1.0 means that the error matches the tolerances
53578a175baeSEmil Constantinescu 
53588a175baeSEmil Constantinescu    Level: developer
53598a175baeSEmil Constantinescu 
5360bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSErrorWeightedENorm()`, `TSErrorWeightedENorm2()`
53618a175baeSEmil Constantinescu @*/
5362d71ae5a4SJacob Faibussowitsch PetscErrorCode TSErrorWeightedENormInfinity(TS ts, Vec E, Vec U, Vec Y, PetscReal *norm, PetscReal *norma, PetscReal *normr)
5363d71ae5a4SJacob Faibussowitsch {
53648a175baeSEmil Constantinescu   PetscInt           i, n, N, rstart;
53658a175baeSEmil Constantinescu   const PetscScalar *e, *u, *y;
53668a175baeSEmil Constantinescu   PetscReal          err, max, gmax, maxa, gmaxa, maxr, gmaxr;
53678a175baeSEmil Constantinescu   PetscReal          tol, tola, tolr;
53688a175baeSEmil Constantinescu   PetscReal          err_loc[3], err_glb[3];
53698a175baeSEmil Constantinescu 
53708a175baeSEmil Constantinescu   PetscFunctionBegin;
53718a175baeSEmil Constantinescu   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
53728a175baeSEmil Constantinescu   PetscValidHeaderSpecific(E, VEC_CLASSID, 2);
53738a175baeSEmil Constantinescu   PetscValidHeaderSpecific(U, VEC_CLASSID, 3);
53748a175baeSEmil Constantinescu   PetscValidHeaderSpecific(Y, VEC_CLASSID, 4);
53758a175baeSEmil Constantinescu   PetscValidType(E, 2);
53768a175baeSEmil Constantinescu   PetscValidType(U, 3);
53778a175baeSEmil Constantinescu   PetscValidType(Y, 4);
53788a175baeSEmil Constantinescu   PetscCheckSameComm(E, 2, U, 3);
5379064a246eSJacob Faibussowitsch   PetscCheckSameComm(U, 3, Y, 4);
5380dadcf809SJacob Faibussowitsch   PetscValidRealPointer(norm, 5);
5381dadcf809SJacob Faibussowitsch   PetscValidRealPointer(norma, 6);
5382dadcf809SJacob Faibussowitsch   PetscValidRealPointer(normr, 7);
53838a175baeSEmil Constantinescu 
53849566063dSJacob Faibussowitsch   PetscCall(VecGetSize(E, &N));
53859566063dSJacob Faibussowitsch   PetscCall(VecGetLocalSize(E, &n));
53869566063dSJacob Faibussowitsch   PetscCall(VecGetOwnershipRange(E, &rstart, NULL));
53879566063dSJacob Faibussowitsch   PetscCall(VecGetArrayRead(E, &e));
53889566063dSJacob Faibussowitsch   PetscCall(VecGetArrayRead(U, &u));
53899566063dSJacob Faibussowitsch   PetscCall(VecGetArrayRead(Y, &y));
53908a175baeSEmil Constantinescu 
53918a175baeSEmil Constantinescu   max  = 0.;
53928a175baeSEmil Constantinescu   maxa = 0.;
53938a175baeSEmil Constantinescu   maxr = 0.;
53948a175baeSEmil Constantinescu 
53958a175baeSEmil Constantinescu   if (ts->vatol && ts->vrtol) { /* vector atol, vector rtol */
53968a175baeSEmil Constantinescu     const PetscScalar *atol, *rtol;
53979566063dSJacob Faibussowitsch     PetscCall(VecGetArrayRead(ts->vatol, &atol));
53989566063dSJacob Faibussowitsch     PetscCall(VecGetArrayRead(ts->vrtol, &rtol));
53998a175baeSEmil Constantinescu 
54008a175baeSEmil Constantinescu     for (i = 0; i < n; i++) {
540176cddca1SEmil Constantinescu       SkipSmallValue(y[i], u[i], ts->adapt->ignore_max);
54028a175baeSEmil Constantinescu       err  = PetscAbsScalar(e[i]);
54038a175baeSEmil Constantinescu       tola = PetscRealPart(atol[i]);
54048a175baeSEmil Constantinescu       tolr = PetscRealPart(rtol[i]) * PetscMax(PetscAbsScalar(u[i]), PetscAbsScalar(y[i]));
54058a175baeSEmil Constantinescu       tol  = tola + tolr;
54061e66621cSBarry Smith       if (tola > 0.) maxa = PetscMax(maxa, err / tola);
54071e66621cSBarry Smith       if (tolr > 0.) maxr = PetscMax(maxr, err / tolr);
54081e66621cSBarry Smith       if (tol > 0.) max = PetscMax(max, err / tol);
54098a175baeSEmil Constantinescu     }
54109566063dSJacob Faibussowitsch     PetscCall(VecRestoreArrayRead(ts->vatol, &atol));
54119566063dSJacob Faibussowitsch     PetscCall(VecRestoreArrayRead(ts->vrtol, &rtol));
54128a175baeSEmil Constantinescu   } else if (ts->vatol) { /* vector atol, scalar rtol */
54138a175baeSEmil Constantinescu     const PetscScalar *atol;
54149566063dSJacob Faibussowitsch     PetscCall(VecGetArrayRead(ts->vatol, &atol));
54158a175baeSEmil Constantinescu     for (i = 0; i < n; i++) {
541676cddca1SEmil Constantinescu       SkipSmallValue(y[i], u[i], ts->adapt->ignore_max);
54178a175baeSEmil Constantinescu       err  = PetscAbsScalar(e[i]);
54188a175baeSEmil Constantinescu       tola = PetscRealPart(atol[i]);
54198a175baeSEmil Constantinescu       tolr = ts->rtol * PetscMax(PetscAbsScalar(u[i]), PetscAbsScalar(y[i]));
54208a175baeSEmil Constantinescu       tol  = tola + tolr;
54211e66621cSBarry Smith       if (tola > 0.) maxa = PetscMax(maxa, err / tola);
54221e66621cSBarry Smith       if (tolr > 0.) maxr = PetscMax(maxr, err / tolr);
54231e66621cSBarry Smith       if (tol > 0.) max = PetscMax(max, err / tol);
54248a175baeSEmil Constantinescu     }
54259566063dSJacob Faibussowitsch     PetscCall(VecRestoreArrayRead(ts->vatol, &atol));
54268a175baeSEmil Constantinescu   } else if (ts->vrtol) { /* scalar atol, vector rtol */
54278a175baeSEmil Constantinescu     const PetscScalar *rtol;
54289566063dSJacob Faibussowitsch     PetscCall(VecGetArrayRead(ts->vrtol, &rtol));
54298a175baeSEmil Constantinescu 
54308a175baeSEmil Constantinescu     for (i = 0; i < n; i++) {
543176cddca1SEmil Constantinescu       SkipSmallValue(y[i], u[i], ts->adapt->ignore_max);
54328a175baeSEmil Constantinescu       err  = PetscAbsScalar(e[i]);
54338a175baeSEmil Constantinescu       tola = ts->atol;
54348a175baeSEmil Constantinescu       tolr = PetscRealPart(rtol[i]) * PetscMax(PetscAbsScalar(u[i]), PetscAbsScalar(y[i]));
54358a175baeSEmil Constantinescu       tol  = tola + tolr;
54361e66621cSBarry Smith       if (tola > 0.) maxa = PetscMax(maxa, err / tola);
54371e66621cSBarry Smith       if (tolr > 0.) maxr = PetscMax(maxr, err / tolr);
54381e66621cSBarry Smith       if (tol > 0.) max = PetscMax(max, err / tol);
54398a175baeSEmil Constantinescu     }
54409566063dSJacob Faibussowitsch     PetscCall(VecRestoreArrayRead(ts->vrtol, &rtol));
54418a175baeSEmil Constantinescu   } else { /* scalar atol, scalar rtol */
54428a175baeSEmil Constantinescu 
54438a175baeSEmil Constantinescu     for (i = 0; i < n; i++) {
544476cddca1SEmil Constantinescu       SkipSmallValue(y[i], u[i], ts->adapt->ignore_max);
54458a175baeSEmil Constantinescu       err  = PetscAbsScalar(e[i]);
54468a175baeSEmil Constantinescu       tola = ts->atol;
54478a175baeSEmil Constantinescu       tolr = ts->rtol * PetscMax(PetscAbsScalar(u[i]), PetscAbsScalar(y[i]));
54488a175baeSEmil Constantinescu       tol  = tola + tolr;
54491e66621cSBarry Smith       if (tola > 0.) maxa = PetscMax(maxa, err / tola);
54501e66621cSBarry Smith       if (tolr > 0.) maxr = PetscMax(maxr, err / tolr);
54511e66621cSBarry Smith       if (tol > 0.) max = PetscMax(max, err / tol);
54528a175baeSEmil Constantinescu     }
54538a175baeSEmil Constantinescu   }
54549566063dSJacob Faibussowitsch   PetscCall(VecRestoreArrayRead(E, &e));
54559566063dSJacob Faibussowitsch   PetscCall(VecRestoreArrayRead(U, &u));
54569566063dSJacob Faibussowitsch   PetscCall(VecRestoreArrayRead(Y, &y));
54578a175baeSEmil Constantinescu   err_loc[0] = max;
54588a175baeSEmil Constantinescu   err_loc[1] = maxa;
54598a175baeSEmil Constantinescu   err_loc[2] = maxr;
54601c2dc1cbSBarry Smith   PetscCall(MPIU_Allreduce(err_loc, err_glb, 3, MPIU_REAL, MPIU_MAX, PetscObjectComm((PetscObject)ts)));
54618a175baeSEmil Constantinescu   gmax  = err_glb[0];
54628a175baeSEmil Constantinescu   gmaxa = err_glb[1];
54638a175baeSEmil Constantinescu   gmaxr = err_glb[2];
54648a175baeSEmil Constantinescu 
54658a175baeSEmil Constantinescu   *norm  = gmax;
54668a175baeSEmil Constantinescu   *norma = gmaxa;
54678a175baeSEmil Constantinescu   *normr = gmaxr;
54683c633725SBarry Smith   PetscCheck(!PetscIsInfOrNanScalar(*norm), PetscObjectComm((PetscObject)ts), PETSC_ERR_FP, "Infinite or not-a-number generated in norm");
54693c633725SBarry Smith   PetscCheck(!PetscIsInfOrNanScalar(*norma), PetscObjectComm((PetscObject)ts), PETSC_ERR_FP, "Infinite or not-a-number generated in norma");
54703c633725SBarry Smith   PetscCheck(!PetscIsInfOrNanScalar(*normr), PetscObjectComm((PetscObject)ts), PETSC_ERR_FP, "Infinite or not-a-number generated in normr");
54713ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
54728a175baeSEmil Constantinescu }
54738a175baeSEmil Constantinescu 
54748a175baeSEmil Constantinescu /*@
54758a175baeSEmil Constantinescu    TSErrorWeightedENorm - compute a weighted error norm based on supplied absolute and relative tolerances
54768a175baeSEmil Constantinescu 
5477c3339decSBarry Smith    Collective
54788a175baeSEmil Constantinescu 
54794165533cSJose E. Roman    Input Parameters:
54808a175baeSEmil Constantinescu +  ts - time stepping context
54818a175baeSEmil Constantinescu .  E - error vector
54828a175baeSEmil Constantinescu .  U - state vector, usually ts->vec_sol
54838a175baeSEmil Constantinescu .  Y - state vector, previous time step
5484bcf0153eSBarry Smith -  wnormtype - norm type, either `NORM_2` or `NORM_INFINITY`
54858a175baeSEmil Constantinescu 
54864165533cSJose E. Roman    Output Parameters:
5487a2b725a8SWilliam Gropp +  norm  - weighted norm, a value of 1.0 achieves a balance between absolute and relative tolerances
54888a175baeSEmil Constantinescu .  norma - weighted norm, a value of 1.0 means that the error meets the absolute tolerance set by the user
5489a2b725a8SWilliam Gropp -  normr - weighted norm, a value of 1.0 means that the error meets the relative tolerance set by the user
54908a175baeSEmil Constantinescu 
5491bcf0153eSBarry Smith    Options Database Key:
54928a175baeSEmil Constantinescu .  -ts_adapt_wnormtype <wnormtype> - 2, INFINITY
54938a175baeSEmil Constantinescu 
54948a175baeSEmil Constantinescu    Level: developer
54958a175baeSEmil Constantinescu 
5496bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSErrorWeightedENormInfinity()`, `TSErrorWeightedENorm2()`, `TSErrorWeightedNormInfinity()`, `TSErrorWeightedNorm2()`
54978a175baeSEmil Constantinescu @*/
5498d71ae5a4SJacob Faibussowitsch PetscErrorCode TSErrorWeightedENorm(TS ts, Vec E, Vec U, Vec Y, NormType wnormtype, PetscReal *norm, PetscReal *norma, PetscReal *normr)
5499d71ae5a4SJacob Faibussowitsch {
55008a175baeSEmil Constantinescu   PetscFunctionBegin;
55011e66621cSBarry Smith   if (wnormtype == NORM_2) PetscCall(TSErrorWeightedENorm2(ts, E, U, Y, norm, norma, normr));
55021e66621cSBarry Smith   else if (wnormtype == NORM_INFINITY) PetscCall(TSErrorWeightedENormInfinity(ts, E, U, Y, norm, norma, normr));
55031e66621cSBarry Smith   else SETERRQ(PETSC_COMM_SELF, PETSC_ERR_SUP, "No support for norm type %s", NormTypes[wnormtype]);
55043ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
55058a175baeSEmil Constantinescu }
55068a175baeSEmil Constantinescu 
55078d59e960SJed Brown /*@
55088d59e960SJed Brown    TSSetCFLTimeLocal - Set the local CFL constraint relative to forward Euler
55098d59e960SJed Brown 
5510c3339decSBarry Smith    Logically Collective
55118d59e960SJed Brown 
55124165533cSJose E. Roman    Input Parameters:
55138d59e960SJed Brown +  ts - time stepping context
55148d59e960SJed Brown -  cfltime - maximum stable time step if using forward Euler (value can be different on each process)
55158d59e960SJed Brown 
55168d59e960SJed Brown    Note:
55178d59e960SJed Brown    After calling this function, the global CFL time can be obtained by calling TSGetCFLTime()
55188d59e960SJed Brown 
55198d59e960SJed Brown    Level: intermediate
55208d59e960SJed Brown 
5521bcf0153eSBarry Smith .seealso: [](chapter_ts), `TSGetCFLTime()`, `TSADAPTCFL`
55228d59e960SJed Brown @*/
5523d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetCFLTimeLocal(TS ts, PetscReal cfltime)
5524d71ae5a4SJacob Faibussowitsch {
55258d59e960SJed Brown   PetscFunctionBegin;
55268d59e960SJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
55278d59e960SJed Brown   ts->cfltime_local = cfltime;
55288d59e960SJed Brown   ts->cfltime       = -1.;
55293ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
55308d59e960SJed Brown }
55318d59e960SJed Brown 
55328d59e960SJed Brown /*@
55338d59e960SJed Brown    TSGetCFLTime - Get the maximum stable time step according to CFL criteria applied to forward Euler
55348d59e960SJed Brown 
5535c3339decSBarry Smith    Collective
55368d59e960SJed Brown 
55374165533cSJose E. Roman    Input Parameter:
55388d59e960SJed Brown .  ts - time stepping context
55398d59e960SJed Brown 
55404165533cSJose E. Roman    Output Parameter:
55418d59e960SJed Brown .  cfltime - maximum stable time step for forward Euler
55428d59e960SJed Brown 
55438d59e960SJed Brown    Level: advanced
55448d59e960SJed Brown 
5545bcf0153eSBarry Smith .seealso: [](chapter_ts), `TSSetCFLTimeLocal()`
55468d59e960SJed Brown @*/
5547d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetCFLTime(TS ts, PetscReal *cfltime)
5548d71ae5a4SJacob Faibussowitsch {
55498d59e960SJed Brown   PetscFunctionBegin;
55501e66621cSBarry Smith   if (ts->cfltime < 0) PetscCall(MPIU_Allreduce(&ts->cfltime_local, &ts->cfltime, 1, MPIU_REAL, MPIU_MIN, PetscObjectComm((PetscObject)ts)));
55518d59e960SJed Brown   *cfltime = ts->cfltime;
55523ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
55538d59e960SJed Brown }
55548d59e960SJed Brown 
5555d6ebe24aSShri Abhyankar /*@
5556d6ebe24aSShri Abhyankar    TSVISetVariableBounds - Sets the lower and upper bounds for the solution vector. xl <= x <= xu
5557d6ebe24aSShri Abhyankar 
5558d6ebe24aSShri Abhyankar    Input Parameters:
5559bcf0153eSBarry Smith +  ts   - the `TS` context.
5560d6ebe24aSShri Abhyankar .  xl   - lower bound.
5561a2b725a8SWilliam Gropp -  xu   - upper bound.
5562d6ebe24aSShri Abhyankar 
55632bd2b0e6SSatish Balay    Level: advanced
55642bd2b0e6SSatish Balay 
5565bcf0153eSBarry Smith    Note:
5566bcf0153eSBarry Smith    If this routine is not called then the lower and upper bounds are set to
5567bcf0153eSBarry Smith    `PETSC_NINFINITY` and `PETSC_INFINITY` respectively during `SNESSetUp()`.
5568bcf0153eSBarry Smith 
5569bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`
5570d6ebe24aSShri Abhyankar @*/
5571d71ae5a4SJacob Faibussowitsch PetscErrorCode TSVISetVariableBounds(TS ts, Vec xl, Vec xu)
5572d71ae5a4SJacob Faibussowitsch {
5573d6ebe24aSShri Abhyankar   SNES snes;
5574d6ebe24aSShri Abhyankar 
5575d6ebe24aSShri Abhyankar   PetscFunctionBegin;
55769566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts, &snes));
55779566063dSJacob Faibussowitsch   PetscCall(SNESVISetVariableBounds(snes, xl, xu));
55783ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
5579d6ebe24aSShri Abhyankar }
5580d6ebe24aSShri Abhyankar 
5581f9c1d6abSBarry Smith /*@
5582f9c1d6abSBarry Smith    TSComputeLinearStability - computes the linear stability function at a point
5583f9c1d6abSBarry Smith 
5584c3339decSBarry Smith    Collective
5585f9c1d6abSBarry Smith 
5586f9c1d6abSBarry Smith    Input Parameters:
5587bcf0153eSBarry Smith +  ts - the `TS` context
5588f9c1d6abSBarry Smith -  xr,xi - real and imaginary part of input arguments
5589f9c1d6abSBarry Smith 
5590f9c1d6abSBarry Smith    Output Parameters:
5591f9c1d6abSBarry Smith .  yr,yi - real and imaginary part of function value
5592f9c1d6abSBarry Smith 
5593f9c1d6abSBarry Smith    Level: developer
5594f9c1d6abSBarry Smith 
5595bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSSetRHSFunction()`, `TSComputeIFunction()`
5596f9c1d6abSBarry Smith @*/
5597d71ae5a4SJacob Faibussowitsch PetscErrorCode TSComputeLinearStability(TS ts, PetscReal xr, PetscReal xi, PetscReal *yr, PetscReal *yi)
5598d71ae5a4SJacob Faibussowitsch {
5599f9c1d6abSBarry Smith   PetscFunctionBegin;
5600f9c1d6abSBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
5601dbbe0bcdSBarry Smith   PetscUseTypeMethod(ts, linearstability, xr, xi, yr, yi);
56023ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
5603f9c1d6abSBarry Smith }
560424655328SShri 
560524655328SShri /*@
5606dcb233daSLisandro Dalcin    TSRestartStep - Flags the solver to restart the next step
5607dcb233daSLisandro Dalcin 
5608c3339decSBarry Smith    Collective
5609dcb233daSLisandro Dalcin 
5610dcb233daSLisandro Dalcin    Input Parameter:
5611bcf0153eSBarry Smith .  ts - the `TS` context obtained from `TSCreate()`
5612dcb233daSLisandro Dalcin 
5613dcb233daSLisandro Dalcin    Level: advanced
5614dcb233daSLisandro Dalcin 
5615dcb233daSLisandro Dalcin    Notes:
5616bcf0153eSBarry Smith    Multistep methods like `TSBDF` or Runge-Kutta methods with FSAL property require restarting the solver in the event of
5617dcb233daSLisandro Dalcin    discontinuities. These discontinuities may be introduced as a consequence of explicitly modifications to the solution
5618dcb233daSLisandro Dalcin    vector (which PETSc attempts to detect and handle) or problem coefficients (which PETSc is not able to detect). For
5619bcf0153eSBarry Smith    the sake of correctness and maximum safety, users are expected to call `TSRestart()` whenever they introduce
5620dcb233daSLisandro Dalcin    discontinuities in callback routines (e.g. prestep and poststep routines, or implicit/rhs function routines with
5621dcb233daSLisandro Dalcin    discontinuous source terms).
5622dcb233daSLisandro Dalcin 
5623bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSBDF`, `TSSolve()`, `TSSetPreStep()`, `TSSetPostStep()`
5624dcb233daSLisandro Dalcin @*/
5625d71ae5a4SJacob Faibussowitsch PetscErrorCode TSRestartStep(TS ts)
5626d71ae5a4SJacob Faibussowitsch {
5627dcb233daSLisandro Dalcin   PetscFunctionBegin;
5628dcb233daSLisandro Dalcin   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
5629dcb233daSLisandro Dalcin   ts->steprestart = PETSC_TRUE;
56303ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
5631dcb233daSLisandro Dalcin }
5632dcb233daSLisandro Dalcin 
5633dcb233daSLisandro Dalcin /*@
563424655328SShri    TSRollBack - Rolls back one time step
563524655328SShri 
5636c3339decSBarry Smith    Collective
563724655328SShri 
563824655328SShri    Input Parameter:
5639bcf0153eSBarry Smith .  ts - the `TS` context obtained from `TSCreate()`
564024655328SShri 
564124655328SShri    Level: advanced
564224655328SShri 
5643bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSCreate()`, `TSSetUp()`, `TSDestroy()`, `TSSolve()`, `TSSetPreStep()`, `TSSetPreStage()`, `TSInterpolate()`
564424655328SShri @*/
5645d71ae5a4SJacob Faibussowitsch PetscErrorCode TSRollBack(TS ts)
5646d71ae5a4SJacob Faibussowitsch {
564724655328SShri   PetscFunctionBegin;
564824655328SShri   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
56493c633725SBarry Smith   PetscCheck(!ts->steprollback, PetscObjectComm((PetscObject)ts), PETSC_ERR_ARG_WRONGSTATE, "TSRollBack already called");
5650dbbe0bcdSBarry Smith   PetscUseTypeMethod(ts, rollback);
565124655328SShri   ts->time_step  = ts->ptime - ts->ptime_prev;
565224655328SShri   ts->ptime      = ts->ptime_prev;
5653be5899b3SLisandro Dalcin   ts->ptime_prev = ts->ptime_prev_rollback;
56542808aa04SLisandro Dalcin   ts->steps--;
5655b3de5cdeSLisandro Dalcin   ts->steprollback = PETSC_TRUE;
56563ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
565724655328SShri }
5658aeb4809dSShri Abhyankar 
5659ff22ae23SHong Zhang /*@
5660ff22ae23SHong Zhang    TSGetStages - Get the number of stages and stage values
5661ff22ae23SHong Zhang 
5662ff22ae23SHong Zhang    Input Parameter:
5663bcf0153eSBarry Smith .  ts - the `TS` context obtained from `TSCreate()`
5664ff22ae23SHong Zhang 
56650429704eSStefano Zampini    Output Parameters:
56660429704eSStefano Zampini +  ns - the number of stages
56670429704eSStefano Zampini -  Y - the current stage vectors
56680429704eSStefano Zampini 
5669ff22ae23SHong Zhang    Level: advanced
5670ff22ae23SHong Zhang 
5671bcf0153eSBarry Smith    Note:
5672195e9b02SBarry Smith    Both `ns` and `Y` can be `NULL`.
56730429704eSStefano Zampini 
5674bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSCreate()`
5675ff22ae23SHong Zhang @*/
5676d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetStages(TS ts, PetscInt *ns, Vec **Y)
5677d71ae5a4SJacob Faibussowitsch {
5678ff22ae23SHong Zhang   PetscFunctionBegin;
5679ff22ae23SHong Zhang   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
5680dadcf809SJacob Faibussowitsch   if (ns) PetscValidIntPointer(ns, 2);
56810429704eSStefano Zampini   if (Y) PetscValidPointer(Y, 3);
56820429704eSStefano Zampini   if (!ts->ops->getstages) {
56830429704eSStefano Zampini     if (ns) *ns = 0;
56840429704eSStefano Zampini     if (Y) *Y = NULL;
5685dbbe0bcdSBarry Smith   } else PetscUseTypeMethod(ts, getstages, ns, Y);
56863ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
5687ff22ae23SHong Zhang }
5688ff22ae23SHong Zhang 
5689847ff0e1SMatthew G. Knepley /*@C
5690847ff0e1SMatthew G. Knepley   TSComputeIJacobianDefaultColor - Computes the Jacobian using finite differences and coloring to exploit matrix sparsity.
5691847ff0e1SMatthew G. Knepley 
5692c3339decSBarry Smith   Collective
5693847ff0e1SMatthew G. Knepley 
5694847ff0e1SMatthew G. Knepley   Input Parameters:
5695bcf0153eSBarry Smith + ts - the `TS` context
5696847ff0e1SMatthew G. Knepley . t - current timestep
5697847ff0e1SMatthew G. Knepley . U - state vector
5698847ff0e1SMatthew G. Knepley . Udot - time derivative of state vector
5699847ff0e1SMatthew G. Knepley . shift - shift to apply, see note below
5700847ff0e1SMatthew G. Knepley - ctx - an optional user context
5701847ff0e1SMatthew G. Knepley 
5702847ff0e1SMatthew G. Knepley   Output Parameters:
5703847ff0e1SMatthew G. Knepley + J - Jacobian matrix (not altered in this routine)
5704195e9b02SBarry Smith - B - newly computed Jacobian matrix to use with preconditioner (generally the same as `J`)
5705847ff0e1SMatthew G. Knepley 
5706847ff0e1SMatthew G. Knepley   Level: intermediate
5707847ff0e1SMatthew G. Knepley 
5708847ff0e1SMatthew G. Knepley   Notes:
5709847ff0e1SMatthew G. Knepley   If F(t,U,Udot)=0 is the DAE, the required Jacobian is
5710847ff0e1SMatthew G. Knepley 
5711847ff0e1SMatthew G. Knepley   dF/dU + shift*dF/dUdot
5712847ff0e1SMatthew G. Knepley 
5713847ff0e1SMatthew G. Knepley   Most users should not need to explicitly call this routine, as it
5714847ff0e1SMatthew G. Knepley   is used internally within the nonlinear solvers.
5715847ff0e1SMatthew G. Knepley 
5716bcf0153eSBarry Smith   This will first try to get the coloring from the `DM`.  If the `DM` type has no coloring
5717847ff0e1SMatthew G. Knepley   routine, then it will try to get the coloring from the matrix.  This requires that the
5718847ff0e1SMatthew G. Knepley   matrix have nonzero entries precomputed.
5719847ff0e1SMatthew G. Knepley 
5720bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSSetIJacobian()`, `MatFDColoringCreate()`, `MatFDColoringSetFunction()`
5721847ff0e1SMatthew G. Knepley @*/
5722d71ae5a4SJacob Faibussowitsch PetscErrorCode TSComputeIJacobianDefaultColor(TS ts, PetscReal t, Vec U, Vec Udot, PetscReal shift, Mat J, Mat B, void *ctx)
5723d71ae5a4SJacob Faibussowitsch {
5724847ff0e1SMatthew G. Knepley   SNES          snes;
5725847ff0e1SMatthew G. Knepley   MatFDColoring color;
5726847ff0e1SMatthew G. Knepley   PetscBool     hascolor, matcolor = PETSC_FALSE;
5727847ff0e1SMatthew G. Knepley 
5728847ff0e1SMatthew G. Knepley   PetscFunctionBegin;
57299566063dSJacob Faibussowitsch   PetscCall(PetscOptionsGetBool(((PetscObject)ts)->options, ((PetscObject)ts)->prefix, "-ts_fd_color_use_mat", &matcolor, NULL));
57309566063dSJacob Faibussowitsch   PetscCall(PetscObjectQuery((PetscObject)B, "TSMatFDColoring", (PetscObject *)&color));
5731847ff0e1SMatthew G. Knepley   if (!color) {
5732847ff0e1SMatthew G. Knepley     DM         dm;
5733847ff0e1SMatthew G. Knepley     ISColoring iscoloring;
5734847ff0e1SMatthew G. Knepley 
57359566063dSJacob Faibussowitsch     PetscCall(TSGetDM(ts, &dm));
57369566063dSJacob Faibussowitsch     PetscCall(DMHasColoring(dm, &hascolor));
5737847ff0e1SMatthew G. Knepley     if (hascolor && !matcolor) {
57389566063dSJacob Faibussowitsch       PetscCall(DMCreateColoring(dm, IS_COLORING_GLOBAL, &iscoloring));
57399566063dSJacob Faibussowitsch       PetscCall(MatFDColoringCreate(B, iscoloring, &color));
57409566063dSJacob Faibussowitsch       PetscCall(MatFDColoringSetFunction(color, (PetscErrorCode(*)(void))SNESTSFormFunction, (void *)ts));
57419566063dSJacob Faibussowitsch       PetscCall(MatFDColoringSetFromOptions(color));
57429566063dSJacob Faibussowitsch       PetscCall(MatFDColoringSetUp(B, iscoloring, color));
57439566063dSJacob Faibussowitsch       PetscCall(ISColoringDestroy(&iscoloring));
5744847ff0e1SMatthew G. Knepley     } else {
5745847ff0e1SMatthew G. Knepley       MatColoring mc;
5746847ff0e1SMatthew G. Knepley 
57479566063dSJacob Faibussowitsch       PetscCall(MatColoringCreate(B, &mc));
57489566063dSJacob Faibussowitsch       PetscCall(MatColoringSetDistance(mc, 2));
57499566063dSJacob Faibussowitsch       PetscCall(MatColoringSetType(mc, MATCOLORINGSL));
57509566063dSJacob Faibussowitsch       PetscCall(MatColoringSetFromOptions(mc));
57519566063dSJacob Faibussowitsch       PetscCall(MatColoringApply(mc, &iscoloring));
57529566063dSJacob Faibussowitsch       PetscCall(MatColoringDestroy(&mc));
57539566063dSJacob Faibussowitsch       PetscCall(MatFDColoringCreate(B, iscoloring, &color));
57549566063dSJacob Faibussowitsch       PetscCall(MatFDColoringSetFunction(color, (PetscErrorCode(*)(void))SNESTSFormFunction, (void *)ts));
57559566063dSJacob Faibussowitsch       PetscCall(MatFDColoringSetFromOptions(color));
57569566063dSJacob Faibussowitsch       PetscCall(MatFDColoringSetUp(B, iscoloring, color));
57579566063dSJacob Faibussowitsch       PetscCall(ISColoringDestroy(&iscoloring));
5758847ff0e1SMatthew G. Knepley     }
57599566063dSJacob Faibussowitsch     PetscCall(PetscObjectCompose((PetscObject)B, "TSMatFDColoring", (PetscObject)color));
57609566063dSJacob Faibussowitsch     PetscCall(PetscObjectDereference((PetscObject)color));
5761847ff0e1SMatthew G. Knepley   }
57629566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts, &snes));
57639566063dSJacob Faibussowitsch   PetscCall(MatFDColoringApply(B, color, U, snes));
5764847ff0e1SMatthew G. Knepley   if (J != B) {
57659566063dSJacob Faibussowitsch     PetscCall(MatAssemblyBegin(J, MAT_FINAL_ASSEMBLY));
57669566063dSJacob Faibussowitsch     PetscCall(MatAssemblyEnd(J, MAT_FINAL_ASSEMBLY));
5767847ff0e1SMatthew G. Knepley   }
57683ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
5769847ff0e1SMatthew G. Knepley }
577093b34091SDebojyoti Ghosh 
5771cb9d8021SPierre Barbier de Reuille /*@
57726bc98fa9SBarry Smith     TSSetFunctionDomainError - Set a function that tests if the current state vector is valid
5773cb9d8021SPierre Barbier de Reuille 
5774cb9d8021SPierre Barbier de Reuille     Input Parameters:
5775bcf0153eSBarry Smith +    ts - the `TS` context
5776bcf0153eSBarry Smith -    func - function called within `TSFunctionDomainError()`
57776bc98fa9SBarry Smith 
57786bc98fa9SBarry Smith     Calling sequence of func:
57796bc98fa9SBarry Smith $     PetscErrorCode func(TS ts,PetscReal time,Vec state,PetscBool reject)
57806bc98fa9SBarry Smith 
57816bc98fa9SBarry Smith +   ts - the TS context
57826bc98fa9SBarry Smith .   time - the current time (of the stage)
57836bc98fa9SBarry Smith .   state - the state to check if it is valid
57846bc98fa9SBarry Smith -   reject - (output parameter) PETSC_FALSE if the state is acceptable, PETSC_TRUE if not acceptable
5785cb9d8021SPierre Barbier de Reuille 
5786cb9d8021SPierre Barbier de Reuille     Level: intermediate
5787cb9d8021SPierre Barbier de Reuille 
57886bc98fa9SBarry Smith     Notes:
57896bc98fa9SBarry Smith       If an implicit ODE solver is being used then, in addition to providing this routine, the
5790bcf0153eSBarry Smith       user's code should call `SNESSetFunctionDomainError()` when domain errors occur during
5791bcf0153eSBarry Smith       function evaluations where the functions are provided by `TSSetIFunction()` or `TSSetRHSFunction()`.
5792bcf0153eSBarry Smith       Use `TSGetSNES()` to obtain the `SNES` object
57936bc98fa9SBarry Smith 
5794bcf0153eSBarry Smith     Developer Note:
5795bcf0153eSBarry Smith       The naming of this function is inconsistent with the `SNESSetFunctionDomainError()`
57966bc98fa9SBarry Smith       since one takes a function pointer and the other does not.
57976bc98fa9SBarry Smith 
5798bcf0153eSBarry Smith .seealso: [](chapter_ts), `TSAdaptCheckStage()`, `TSFunctionDomainError()`, `SNESSetFunctionDomainError()`, `TSGetSNES()`
5799cb9d8021SPierre Barbier de Reuille @*/
5800cb9d8021SPierre Barbier de Reuille 
5801d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetFunctionDomainError(TS ts, PetscErrorCode (*func)(TS, PetscReal, Vec, PetscBool *))
5802d71ae5a4SJacob Faibussowitsch {
5803cb9d8021SPierre Barbier de Reuille   PetscFunctionBegin;
5804cb9d8021SPierre Barbier de Reuille   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
5805cb9d8021SPierre Barbier de Reuille   ts->functiondomainerror = func;
58063ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
5807cb9d8021SPierre Barbier de Reuille }
5808cb9d8021SPierre Barbier de Reuille 
5809cb9d8021SPierre Barbier de Reuille /*@
58106bc98fa9SBarry Smith     TSFunctionDomainError - Checks if the current state is valid
5811cb9d8021SPierre Barbier de Reuille 
5812cb9d8021SPierre Barbier de Reuille     Input Parameters:
5813bcf0153eSBarry Smith +    ts - the `TS` context
58146bc98fa9SBarry Smith .    stagetime - time of the simulation
58156bc98fa9SBarry Smith -    Y - state vector to check.
5816cb9d8021SPierre Barbier de Reuille 
5817cb9d8021SPierre Barbier de Reuille     Output Parameter:
5818bcf0153eSBarry Smith .    accept - Set to `PETSC_FALSE` if the current state vector is valid.
581996a0c994SBarry Smith 
58206bc98fa9SBarry Smith     Level: developer
58216bc98fa9SBarry Smith 
5822bcf0153eSBarry Smith     Note:
5823bcf0153eSBarry Smith     This function is called by the `TS` integration routines and calls the user provided function (set with `TSSetFunctionDomainError()`)
5824bcf0153eSBarry Smith     to check if the current state is valid.
5825bcf0153eSBarry Smith 
5826bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSSetFunctionDomainError()`
5827cb9d8021SPierre Barbier de Reuille @*/
5828d71ae5a4SJacob Faibussowitsch PetscErrorCode TSFunctionDomainError(TS ts, PetscReal stagetime, Vec Y, PetscBool *accept)
5829d71ae5a4SJacob Faibussowitsch {
5830cb9d8021SPierre Barbier de Reuille   PetscFunctionBegin;
5831cb9d8021SPierre Barbier de Reuille   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
5832cb9d8021SPierre Barbier de Reuille   *accept = PETSC_TRUE;
58331e66621cSBarry Smith   if (ts->functiondomainerror) PetscCall((*ts->functiondomainerror)(ts, stagetime, Y, accept));
58343ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
5835cb9d8021SPierre Barbier de Reuille }
58361ceb14c0SBarry Smith 
583793b34091SDebojyoti Ghosh /*@C
5838195e9b02SBarry Smith   TSClone - This function clones a time step `TS` object.
583993b34091SDebojyoti Ghosh 
5840d083f849SBarry Smith   Collective
584193b34091SDebojyoti Ghosh 
584293b34091SDebojyoti Ghosh   Input Parameter:
5843bcf0153eSBarry Smith . tsin    - The input `TS`
584493b34091SDebojyoti Ghosh 
584593b34091SDebojyoti Ghosh   Output Parameter:
5846bcf0153eSBarry Smith . tsout   - The output `TS` (cloned)
58475eca1a21SEmil Constantinescu 
58485eca1a21SEmil Constantinescu   Level: developer
584993b34091SDebojyoti Ghosh 
5850bcf0153eSBarry Smith   Notes:
5851bcf0153eSBarry Smith   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.
5852bcf0153eSBarry Smith   It will likely be replaced in the future with a mechanism of switching methods on the fly.
5853bcf0153eSBarry Smith 
5854195e9b02SBarry Smith   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
5855195e9b02SBarry Smith .vb
5856195e9b02SBarry Smith  SNES snes_dup = NULL;
5857195e9b02SBarry Smith  TSGetSNES(ts,&snes_dup);
5858195e9b02SBarry Smith  TSSetSNES(ts,snes_dup);
5859195e9b02SBarry Smith .ve
5860bcf0153eSBarry Smith 
5861bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `SNES`, `TSCreate()`, `TSSetType()`, `TSSetUp()`, `TSDestroy()`, `TSSetProblemType()`
586293b34091SDebojyoti Ghosh @*/
5863d71ae5a4SJacob Faibussowitsch PetscErrorCode TSClone(TS tsin, TS *tsout)
5864d71ae5a4SJacob Faibussowitsch {
586593b34091SDebojyoti Ghosh   TS     t;
5866dc846ba4SSatish Balay   SNES   snes_start;
5867dc846ba4SSatish Balay   DM     dm;
5868dc846ba4SSatish Balay   TSType type;
586993b34091SDebojyoti Ghosh 
587093b34091SDebojyoti Ghosh   PetscFunctionBegin;
587193b34091SDebojyoti Ghosh   PetscValidPointer(tsin, 1);
587293b34091SDebojyoti Ghosh   *tsout = NULL;
587393b34091SDebojyoti Ghosh 
58749566063dSJacob Faibussowitsch   PetscCall(PetscHeaderCreate(t, TS_CLASSID, "TS", "Time stepping", "TS", PetscObjectComm((PetscObject)tsin), TSDestroy, TSView));
587593b34091SDebojyoti Ghosh 
587693b34091SDebojyoti Ghosh   /* General TS description */
587793b34091SDebojyoti Ghosh   t->numbermonitors    = 0;
5878d0c080abSJoseph Pusztay   t->monitorFrequency  = 1;
587993b34091SDebojyoti Ghosh   t->setupcalled       = 0;
588093b34091SDebojyoti Ghosh   t->ksp_its           = 0;
588193b34091SDebojyoti Ghosh   t->snes_its          = 0;
588293b34091SDebojyoti Ghosh   t->nwork             = 0;
58837d51462cSStefano Zampini   t->rhsjacobian.time  = PETSC_MIN_REAL;
588493b34091SDebojyoti Ghosh   t->rhsjacobian.scale = 1.;
588593b34091SDebojyoti Ghosh   t->ijacobian.shift   = 1.;
588693b34091SDebojyoti Ghosh 
58879566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(tsin, &snes_start));
58889566063dSJacob Faibussowitsch   PetscCall(TSSetSNES(t, snes_start));
5889d15a3a53SEmil Constantinescu 
58909566063dSJacob Faibussowitsch   PetscCall(TSGetDM(tsin, &dm));
58919566063dSJacob Faibussowitsch   PetscCall(TSSetDM(t, dm));
589293b34091SDebojyoti Ghosh 
589393b34091SDebojyoti Ghosh   t->adapt = tsin->adapt;
58949566063dSJacob Faibussowitsch   PetscCall(PetscObjectReference((PetscObject)t->adapt));
589593b34091SDebojyoti Ghosh 
5896e7069c78SShri   t->trajectory = tsin->trajectory;
58979566063dSJacob Faibussowitsch   PetscCall(PetscObjectReference((PetscObject)t->trajectory));
5898e7069c78SShri 
5899e7069c78SShri   t->event = tsin->event;
59006b10a48eSSatish Balay   if (t->event) t->event->refct++;
5901e7069c78SShri 
590293b34091SDebojyoti Ghosh   t->problem_type      = tsin->problem_type;
590393b34091SDebojyoti Ghosh   t->ptime             = tsin->ptime;
5904e7069c78SShri   t->ptime_prev        = tsin->ptime_prev;
590593b34091SDebojyoti Ghosh   t->time_step         = tsin->time_step;
590693b34091SDebojyoti Ghosh   t->max_time          = tsin->max_time;
590793b34091SDebojyoti Ghosh   t->steps             = tsin->steps;
590893b34091SDebojyoti Ghosh   t->max_steps         = tsin->max_steps;
590993b34091SDebojyoti Ghosh   t->equation_type     = tsin->equation_type;
591093b34091SDebojyoti Ghosh   t->atol              = tsin->atol;
591193b34091SDebojyoti Ghosh   t->rtol              = tsin->rtol;
591293b34091SDebojyoti Ghosh   t->max_snes_failures = tsin->max_snes_failures;
591393b34091SDebojyoti Ghosh   t->max_reject        = tsin->max_reject;
591493b34091SDebojyoti Ghosh   t->errorifstepfailed = tsin->errorifstepfailed;
591593b34091SDebojyoti Ghosh 
59169566063dSJacob Faibussowitsch   PetscCall(TSGetType(tsin, &type));
59179566063dSJacob Faibussowitsch   PetscCall(TSSetType(t, type));
591893b34091SDebojyoti Ghosh 
591993b34091SDebojyoti Ghosh   t->vec_sol = NULL;
592093b34091SDebojyoti Ghosh 
592193b34091SDebojyoti Ghosh   t->cfltime          = tsin->cfltime;
592293b34091SDebojyoti Ghosh   t->cfltime_local    = tsin->cfltime_local;
592393b34091SDebojyoti Ghosh   t->exact_final_time = tsin->exact_final_time;
592493b34091SDebojyoti Ghosh 
59259566063dSJacob Faibussowitsch   PetscCall(PetscMemcpy(t->ops, tsin->ops, sizeof(struct _TSOps)));
592693b34091SDebojyoti Ghosh 
59270d4fed19SBarry Smith   if (((PetscObject)tsin)->fortran_func_pointers) {
59280d4fed19SBarry Smith     PetscInt i;
59299566063dSJacob Faibussowitsch     PetscCall(PetscMalloc((10) * sizeof(void (*)(void)), &((PetscObject)t)->fortran_func_pointers));
5930ad540459SPierre Jolivet     for (i = 0; i < 10; i++) ((PetscObject)t)->fortran_func_pointers[i] = ((PetscObject)tsin)->fortran_func_pointers[i];
59310d4fed19SBarry Smith   }
593293b34091SDebojyoti Ghosh   *tsout = t;
59333ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
593493b34091SDebojyoti Ghosh }
5935f3b1f45cSBarry Smith 
5936d71ae5a4SJacob Faibussowitsch static PetscErrorCode RHSWrapperFunction_TSRHSJacobianTest(void *ctx, Vec x, Vec y)
5937d71ae5a4SJacob Faibussowitsch {
5938f3b1f45cSBarry Smith   TS ts = (TS)ctx;
5939f3b1f45cSBarry Smith 
5940f3b1f45cSBarry Smith   PetscFunctionBegin;
59419566063dSJacob Faibussowitsch   PetscCall(TSComputeRHSFunction(ts, 0, x, y));
59423ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
5943f3b1f45cSBarry Smith }
5944f3b1f45cSBarry Smith 
5945f3b1f45cSBarry Smith /*@
5946bcf0153eSBarry Smith     TSRHSJacobianTest - Compares the multiply routine provided to the `MATSHELL` with differencing on the `TS` given RHS function.
5947f3b1f45cSBarry Smith 
5948c3339decSBarry Smith    Logically Collective
5949f3b1f45cSBarry Smith 
5950f3b1f45cSBarry Smith     Input Parameters:
5951f3b1f45cSBarry Smith     TS - the time stepping routine
5952f3b1f45cSBarry Smith 
5953f3b1f45cSBarry Smith    Output Parameter:
5954bcf0153eSBarry Smith .   flg - `PETSC_TRUE` if the multiply is likely correct
5955f3b1f45cSBarry Smith 
5956bcf0153eSBarry Smith    Options Database Key:
5957f3b1f45cSBarry Smith  .   -ts_rhs_jacobian_test_mult -mat_shell_test_mult_view - run the test at each timestep of the integrator
5958f3b1f45cSBarry Smith 
5959f3b1f45cSBarry Smith    Level: advanced
5960f3b1f45cSBarry Smith 
5961bcf0153eSBarry Smith    Note:
5962195e9b02SBarry Smith     This only works for problems defined using `TSSetRHSFunction()` and Jacobian NOT `TSSetIFunction()` and Jacobian
5963f3b1f45cSBarry Smith 
5964bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `Mat`, `MATSHELL`, `MatCreateShell()`, `MatShellGetContext()`, `MatShellGetOperation()`, `MatShellTestMultTranspose()`, `TSRHSJacobianTestTranspose()`
5965f3b1f45cSBarry Smith @*/
5966d71ae5a4SJacob Faibussowitsch PetscErrorCode TSRHSJacobianTest(TS ts, PetscBool *flg)
5967d71ae5a4SJacob Faibussowitsch {
5968f3b1f45cSBarry Smith   Mat           J, B;
5969f3b1f45cSBarry Smith   TSRHSJacobian func;
5970f3b1f45cSBarry Smith   void         *ctx;
5971f3b1f45cSBarry Smith 
5972f3b1f45cSBarry Smith   PetscFunctionBegin;
59739566063dSJacob Faibussowitsch   PetscCall(TSGetRHSJacobian(ts, &J, &B, &func, &ctx));
59749566063dSJacob Faibussowitsch   PetscCall((*func)(ts, 0.0, ts->vec_sol, J, B, ctx));
59759566063dSJacob Faibussowitsch   PetscCall(MatShellTestMult(J, RHSWrapperFunction_TSRHSJacobianTest, ts->vec_sol, ts, flg));
59763ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
5977f3b1f45cSBarry Smith }
5978f3b1f45cSBarry Smith 
5979f3b1f45cSBarry Smith /*@C
5980bcf0153eSBarry Smith     TSRHSJacobianTestTranspose - Compares the multiply transpose routine provided to the `MATSHELL` with differencing on the `TS` given RHS function.
5981f3b1f45cSBarry Smith 
5982c3339decSBarry Smith    Logically Collective
5983f3b1f45cSBarry Smith 
5984f3b1f45cSBarry Smith     Input Parameters:
5985f3b1f45cSBarry Smith     TS - the time stepping routine
5986f3b1f45cSBarry Smith 
5987f3b1f45cSBarry Smith    Output Parameter:
5988bcf0153eSBarry Smith .   flg - `PETSC_TRUE` if the multiply is likely correct
5989f3b1f45cSBarry Smith 
5990bcf0153eSBarry Smith    Options Database Key:
5991f3b1f45cSBarry Smith .   -ts_rhs_jacobian_test_mult_transpose -mat_shell_test_mult_transpose_view - run the test at each timestep of the integrator
5992f3b1f45cSBarry Smith 
5993bcf0153eSBarry Smith    Level: advanced
5994bcf0153eSBarry Smith 
599595452b02SPatrick Sanan    Notes:
5996195e9b02SBarry Smith     This only works for problems defined using `TSSetRHSFunction()` and Jacobian NOT `TSSetIFunction()` and Jacobian
5997f3b1f45cSBarry Smith 
5998bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `Mat`, `MatCreateShell()`, `MatShellGetContext()`, `MatShellGetOperation()`, `MatShellTestMultTranspose()`, `TSRHSJacobianTest()`
5999f3b1f45cSBarry Smith @*/
6000d71ae5a4SJacob Faibussowitsch PetscErrorCode TSRHSJacobianTestTranspose(TS ts, PetscBool *flg)
6001d71ae5a4SJacob Faibussowitsch {
6002f3b1f45cSBarry Smith   Mat           J, B;
6003f3b1f45cSBarry Smith   void         *ctx;
6004f3b1f45cSBarry Smith   TSRHSJacobian func;
6005f3b1f45cSBarry Smith 
6006f3b1f45cSBarry Smith   PetscFunctionBegin;
60079566063dSJacob Faibussowitsch   PetscCall(TSGetRHSJacobian(ts, &J, &B, &func, &ctx));
60089566063dSJacob Faibussowitsch   PetscCall((*func)(ts, 0.0, ts->vec_sol, J, B, ctx));
60099566063dSJacob Faibussowitsch   PetscCall(MatShellTestMultTranspose(J, RHSWrapperFunction_TSRHSJacobianTest, ts->vec_sol, ts, flg));
60103ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
6011f3b1f45cSBarry Smith }
60120fe4d17eSHong Zhang 
60130fe4d17eSHong Zhang /*@
60140fe4d17eSHong Zhang   TSSetUseSplitRHSFunction - Use the split RHSFunction when a multirate method is used.
60150fe4d17eSHong Zhang 
60160fe4d17eSHong Zhang   Logically collective
60170fe4d17eSHong Zhang 
6018d8d19677SJose E. Roman   Input Parameters:
60190fe4d17eSHong Zhang +  ts - timestepping context
6020bcf0153eSBarry Smith -  use_splitrhsfunction - `PETSC_TRUE` indicates that the split RHSFunction will be used
60210fe4d17eSHong Zhang 
6022bcf0153eSBarry Smith   Options Database Key:
60230fe4d17eSHong Zhang .   -ts_use_splitrhsfunction - <true,false>
60240fe4d17eSHong Zhang 
60250fe4d17eSHong Zhang   Level: intermediate
60260fe4d17eSHong Zhang 
6027bcf0153eSBarry Smith   Note:
6028195e9b02SBarry Smith   This is only for multirate methods
6029bcf0153eSBarry Smith 
6030bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSGetUseSplitRHSFunction()`
60310fe4d17eSHong Zhang @*/
6032d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetUseSplitRHSFunction(TS ts, PetscBool use_splitrhsfunction)
6033d71ae5a4SJacob Faibussowitsch {
60340fe4d17eSHong Zhang   PetscFunctionBegin;
60350fe4d17eSHong Zhang   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
60360fe4d17eSHong Zhang   ts->use_splitrhsfunction = use_splitrhsfunction;
60373ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
60380fe4d17eSHong Zhang }
60390fe4d17eSHong Zhang 
60400fe4d17eSHong Zhang /*@
60410fe4d17eSHong Zhang   TSGetUseSplitRHSFunction - Gets whether to use the split RHSFunction when a multirate method is used.
60420fe4d17eSHong Zhang 
60430fe4d17eSHong Zhang   Not collective
60440fe4d17eSHong Zhang 
60450fe4d17eSHong Zhang   Input Parameter:
60460fe4d17eSHong Zhang .  ts - timestepping context
60470fe4d17eSHong Zhang 
60480fe4d17eSHong Zhang   Output Parameter:
6049bcf0153eSBarry Smith .  use_splitrhsfunction - `PETSC_TRUE` indicates that the split RHSFunction will be used
60500fe4d17eSHong Zhang 
60510fe4d17eSHong Zhang   Level: intermediate
60520fe4d17eSHong Zhang 
6053bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSSetUseSplitRHSFunction()`
60540fe4d17eSHong Zhang @*/
6055d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetUseSplitRHSFunction(TS ts, PetscBool *use_splitrhsfunction)
6056d71ae5a4SJacob Faibussowitsch {
60570fe4d17eSHong Zhang   PetscFunctionBegin;
60580fe4d17eSHong Zhang   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
60590fe4d17eSHong Zhang   *use_splitrhsfunction = ts->use_splitrhsfunction;
60603ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
60610fe4d17eSHong Zhang }
6062d60b7d5cSBarry Smith 
6063d60b7d5cSBarry Smith /*@
6064d60b7d5cSBarry Smith     TSSetMatStructure - sets the relationship between the nonzero structure of the RHS Jacobian matrix to the IJacobian matrix.
6065d60b7d5cSBarry Smith 
6066c3339decSBarry Smith    Logically  Collective
6067d60b7d5cSBarry Smith 
6068d60b7d5cSBarry Smith    Input Parameters:
6069d60b7d5cSBarry Smith +  ts - the time-stepper
6070bcf0153eSBarry Smith -  str - the structure (the default is `UNKNOWN_NONZERO_PATTERN`)
6071d60b7d5cSBarry Smith 
6072d60b7d5cSBarry Smith    Level: intermediate
6073d60b7d5cSBarry Smith 
6074bcf0153eSBarry Smith    Note:
6075d60b7d5cSBarry Smith      When the relationship between the nonzero structures is known and supplied the solution process can be much faster
6076d60b7d5cSBarry Smith 
6077bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `MatAXPY()`, `MatStructure`
6078d60b7d5cSBarry Smith  @*/
6079d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetMatStructure(TS ts, MatStructure str)
6080d71ae5a4SJacob Faibussowitsch {
6081d60b7d5cSBarry Smith   PetscFunctionBegin;
6082d60b7d5cSBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
6083d60b7d5cSBarry Smith   ts->axpy_pattern = str;
60843ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
6085d60b7d5cSBarry Smith }
60864a658b32SHong Zhang 
60874a658b32SHong Zhang /*@
6088bcf0153eSBarry Smith   TSSetTimeSpan - sets the time span. The solution will be computed and stored for each time requested in the span
60894a658b32SHong Zhang 
6090c3339decSBarry Smith   Collective
60914a658b32SHong Zhang 
60924a658b32SHong Zhang   Input Parameters:
60934a658b32SHong Zhang + ts - the time-stepper
60944a658b32SHong Zhang . n - number of the time points (>=2)
60954a658b32SHong Zhang - span_times - array of the time points. The first element and the last element are the initial time and the final time respectively.
60964a658b32SHong Zhang 
6097bcf0153eSBarry Smith   Options Database Key:
60984a658b32SHong Zhang . -ts_time_span <t0,...tf> - Sets the time span
60994a658b32SHong Zhang 
6100bcf0153eSBarry Smith   Level: intermediate
61014a658b32SHong Zhang 
61024a658b32SHong Zhang   Notes:
61034a658b32SHong Zhang   The elements in tspan must be all increasing. They correspond to the intermediate points for time integration.
6104bcf0153eSBarry Smith   `TS_EXACTFINALTIME_MATCHSTEP` must be used to make the last time step in each sub-interval match the intermediate points specified.
6105bcf0153eSBarry Smith   The intermediate solutions are saved in a vector array that can be accessed with `TSGetTimeSpanSolutions()`. Thus using time span may
61064a658b32SHong Zhang   pressure the memory system when using a large number of span points.
61074a658b32SHong Zhang 
6108bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSGetTimeSpan()`, `TSGetTimeSpanSolutions()`
61094a658b32SHong Zhang  @*/
6110d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetTimeSpan(TS ts, PetscInt n, PetscReal *span_times)
6111d71ae5a4SJacob Faibussowitsch {
61124a658b32SHong Zhang   PetscFunctionBegin;
61134a658b32SHong Zhang   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
611463a3b9bcSJacob Faibussowitsch   PetscCheck(n >= 2, PetscObjectComm((PetscObject)ts), PETSC_ERR_ARG_WRONG, "Minimum time span size is 2 but %" PetscInt_FMT " is provided", n);
61154a658b32SHong Zhang   if (ts->tspan && n != ts->tspan->num_span_times) {
61164a658b32SHong Zhang     PetscCall(PetscFree(ts->tspan->span_times));
61174a658b32SHong Zhang     PetscCall(VecDestroyVecs(ts->tspan->num_span_times, &ts->tspan->vecs_sol));
61184a658b32SHong Zhang     PetscCall(PetscMalloc1(n, &ts->tspan->span_times));
61194a658b32SHong Zhang   }
61204a658b32SHong Zhang   if (!ts->tspan) {
61214a658b32SHong Zhang     TSTimeSpan tspan;
61224a658b32SHong Zhang     PetscCall(PetscNew(&tspan));
61234a658b32SHong Zhang     PetscCall(PetscMalloc1(n, &tspan->span_times));
6124e1db57b0SHong Zhang     tspan->reltol = 1e-6;
6125e1db57b0SHong Zhang     tspan->abstol = 10 * PETSC_MACHINE_EPSILON;
61264a658b32SHong Zhang     ts->tspan     = tspan;
61274a658b32SHong Zhang   }
61284a658b32SHong Zhang   ts->tspan->num_span_times = n;
61294a658b32SHong Zhang   PetscCall(PetscArraycpy(ts->tspan->span_times, span_times, n));
61304a658b32SHong Zhang   PetscCall(TSSetTime(ts, ts->tspan->span_times[0]));
61314a658b32SHong Zhang   PetscCall(TSSetMaxTime(ts, ts->tspan->span_times[n - 1]));
61323ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
61334a658b32SHong Zhang }
61344a658b32SHong Zhang 
61354a658b32SHong Zhang /*@C
6136195e9b02SBarry Smith   TSGetTimeSpan - gets the time span set with `TSSetTimeSpan()`
61374a658b32SHong Zhang 
61384a658b32SHong Zhang   Not Collective
61394a658b32SHong Zhang 
61404a658b32SHong Zhang   Input Parameter:
61414a658b32SHong Zhang . ts - the time-stepper
61424a658b32SHong Zhang 
61434a658b32SHong Zhang   Output Parameters:
61444a658b32SHong Zhang + n - number of the time points (>=2)
6145bcf0153eSBarry Smith - span_times - array of the time points. The first element and the last element are the initial time and the final time respectively.
61464a658b32SHong Zhang 
61474a658b32SHong Zhang   Level: beginner
61484a658b32SHong Zhang 
6149bcf0153eSBarry Smith   Note:
6150195e9b02SBarry Smith   The values obtained are valid until the `TS` object is destroyed.
6151195e9b02SBarry Smith 
6152195e9b02SBarry Smith   Both `n` and `span_times` can be `NULL`.
6153bcf0153eSBarry Smith 
6154bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSSetTimeSpan()`, `TSGetTimeSpanSolutions()`
61554a658b32SHong Zhang  @*/
6156d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetTimeSpan(TS ts, PetscInt *n, const PetscReal **span_times)
6157d71ae5a4SJacob Faibussowitsch {
61584a658b32SHong Zhang   PetscFunctionBegin;
61594a658b32SHong Zhang   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
61604a658b32SHong Zhang   if (n) PetscValidIntPointer(n, 2);
61614a658b32SHong Zhang   if (span_times) PetscValidPointer(span_times, 3);
61624a658b32SHong Zhang   if (!ts->tspan) {
61634a658b32SHong Zhang     if (n) *n = 0;
61644a658b32SHong Zhang     if (span_times) *span_times = NULL;
61654a658b32SHong Zhang   } else {
61664a658b32SHong Zhang     if (n) *n = ts->tspan->num_span_times;
61674a658b32SHong Zhang     if (span_times) *span_times = ts->tspan->span_times;
61684a658b32SHong Zhang   }
61693ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
61704a658b32SHong Zhang }
61714a658b32SHong Zhang 
61724a658b32SHong Zhang /*@
61734a658b32SHong Zhang    TSGetTimeSpanSolutions - Get the number of solutions and the solutions at the time points specified by the time span.
61744a658b32SHong Zhang 
61754a658b32SHong Zhang    Input Parameter:
6176bcf0153eSBarry Smith .  ts - the `TS` context obtained from `TSCreate()`
61774a658b32SHong Zhang 
61784a658b32SHong Zhang    Output Parameters:
61794a658b32SHong Zhang +  nsol - the number of solutions
61804a658b32SHong Zhang -  Sols - the solution vectors
61814a658b32SHong Zhang 
6182bcf0153eSBarry Smith    Level: intermediate
61834a658b32SHong Zhang 
618440bd4cedSHong Zhang    Notes:
6185195e9b02SBarry Smith     Both `nsol` and `Sols` can be `NULL`.
61864a658b32SHong Zhang 
6187195e9b02SBarry Smith     Some time points in the time span may be skipped by `TS` so that `nsol` is less than the number of points specified by `TSSetTimeSpan()`.
6188bcf0153eSBarry Smith     For example, manipulating the step size, especially with a reduced precision, may cause `TS` to step over certain points in the span.
6189bcf0153eSBarry Smith 
6190bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSSetTimeSpan()`
61914a658b32SHong Zhang @*/
6192d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetTimeSpanSolutions(TS ts, PetscInt *nsol, Vec **Sols)
6193d71ae5a4SJacob Faibussowitsch {
61944a658b32SHong Zhang   PetscFunctionBegin;
61954a658b32SHong Zhang   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
61964a658b32SHong Zhang   if (nsol) PetscValidIntPointer(nsol, 2);
61974a658b32SHong Zhang   if (Sols) PetscValidPointer(Sols, 3);
61984a658b32SHong Zhang   if (!ts->tspan) {
61994a658b32SHong Zhang     if (nsol) *nsol = 0;
62004a658b32SHong Zhang     if (Sols) *Sols = NULL;
62014a658b32SHong Zhang   } else {
620240bd4cedSHong Zhang     if (nsol) *nsol = ts->tspan->spanctr;
62034a658b32SHong Zhang     if (Sols) *Sols = ts->tspan->vecs_sol;
62044a658b32SHong Zhang   }
62053ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
62064a658b32SHong Zhang }
6207d7cfae9bSHong Zhang 
6208d7cfae9bSHong Zhang /*@C
62097b2dc123SHong Zhang   TSPruneIJacobianColor - Remove nondiagonal zeros in the Jacobian matrix and update the `MatMFFD` coloring information.
6210d7cfae9bSHong Zhang 
6211195e9b02SBarry Smith   Collective
6212d7cfae9bSHong Zhang 
6213d7cfae9bSHong Zhang   Input Parameters:
6214195e9b02SBarry Smith + ts - the `TS` context
6215d7cfae9bSHong Zhang . J - Jacobian matrix (not altered in this routine)
6216195e9b02SBarry Smith - B - newly computed Jacobian matrix to use with preconditioner
6217d7cfae9bSHong Zhang 
6218d7cfae9bSHong Zhang   Level: intermediate
6219d7cfae9bSHong Zhang 
6220d7cfae9bSHong Zhang   Notes:
6221195e9b02SBarry Smith   This function improves the `MatFDColoring` performance when the Jacobian matrix was over-allocated or contains
6222195e9b02SBarry Smith   many constant zeros entries, which is typically the case when the matrix is generated by a `DM`
6223d7cfae9bSHong Zhang   and multiple fields are involved.
6224d7cfae9bSHong Zhang 
6225d7cfae9bSHong Zhang   Users need to make sure that the Jacobian matrix is properly filled to reflect the sparsity
6226195e9b02SBarry Smith   structure. For `MatFDColoring`, the values of nonzero entries are not important. So one can
62277b2dc123SHong Zhang   usually call `TSComputeIJacobian()` with randomized input vectors to generate a dummy Jacobian.
62287b2dc123SHong Zhang   `TSComputeIJacobian()` should be called before `TSSolve()` but after `TSSetUp()`.
6229d7cfae9bSHong Zhang 
6230195e9b02SBarry Smith .seealso: [](chapter_ts), `TS`, `MatFDColoring`, `TSComputeIJacobianDefaultColor()`, `MatEliminateZeros()`, `MatFDColoringCreate()`, `MatFDColoringSetFunction()`
6231d7cfae9bSHong Zhang @*/
6232d7cfae9bSHong Zhang PetscErrorCode TSPruneIJacobianColor(TS ts, Mat J, Mat B)
6233d7cfae9bSHong Zhang {
6234d7cfae9bSHong Zhang   MatColoring   mc            = NULL;
6235d7cfae9bSHong Zhang   ISColoring    iscoloring    = NULL;
6236d7cfae9bSHong Zhang   MatFDColoring matfdcoloring = NULL;
6237d7cfae9bSHong Zhang 
6238d7cfae9bSHong Zhang   PetscFunctionBegin;
6239d7cfae9bSHong Zhang   /* Generate new coloring after eliminating zeros in the matrix */
6240d7cfae9bSHong Zhang   PetscCall(MatEliminateZeros(B));
6241d7cfae9bSHong Zhang   PetscCall(MatColoringCreate(B, &mc));
6242d7cfae9bSHong Zhang   PetscCall(MatColoringSetDistance(mc, 2));
6243d7cfae9bSHong Zhang   PetscCall(MatColoringSetType(mc, MATCOLORINGSL));
6244d7cfae9bSHong Zhang   PetscCall(MatColoringSetFromOptions(mc));
6245d7cfae9bSHong Zhang   PetscCall(MatColoringApply(mc, &iscoloring));
6246d7cfae9bSHong Zhang   PetscCall(MatColoringDestroy(&mc));
6247d7cfae9bSHong Zhang   /* Replace the old coloring with the new one */
6248d7cfae9bSHong Zhang   PetscCall(MatFDColoringCreate(B, iscoloring, &matfdcoloring));
6249d7cfae9bSHong Zhang   PetscCall(MatFDColoringSetFunction(matfdcoloring, (PetscErrorCode(*)(void))SNESTSFormFunction, (void *)ts));
6250d7cfae9bSHong Zhang   PetscCall(MatFDColoringSetFromOptions(matfdcoloring));
6251d7cfae9bSHong Zhang   PetscCall(MatFDColoringSetUp(B, iscoloring, matfdcoloring));
6252d7cfae9bSHong Zhang   PetscCall(PetscObjectCompose((PetscObject)B, "TSMatFDColoring", (PetscObject)matfdcoloring));
6253d7cfae9bSHong Zhang   PetscCall(PetscObjectDereference((PetscObject)matfdcoloring));
6254d7cfae9bSHong Zhang   PetscCall(ISColoringDestroy(&iscoloring));
62553ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
6256d7cfae9bSHong Zhang }
6257