xref: /petsc/src/ts/interface/ts.c (revision aaa8cc7d2a5c3913edcbb923e20f154fe9c4aa65)
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 
4472fe279fdSBarry Smith    Input Parameter:
448bcf0153eSBarry Smith .  ts - the `TS` context obtained from `TSCreate()`
44978fbdcc8SBarry Smith 
4502fe279fdSBarry Smith    Output Parameter:
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 
5032fe279fdSBarry Smith    Input Parameter:
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 
5262fe279fdSBarry Smith    Input Parameter:
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 
102420f4b53cSBarry Smith     Calling sequence of `f`:
102520f4b53cSBarry Smith $     PetscErrorCode f(TS ts, PetscReal t, Vec u, Vec F, void *ctx)
1026a96d6ef6SBarry Smith +   ts - timestep context
1027a96d6ef6SBarry Smith .   t - current timestep
1028d763cef2SBarry Smith .   u - input vector
1029d763cef2SBarry Smith .   F - function vector
1030d763cef2SBarry Smith -   ctx - [optional] user-defined function context
1031d763cef2SBarry Smith 
1032d763cef2SBarry Smith     Level: beginner
1033d763cef2SBarry Smith 
1034bcf0153eSBarry Smith     Note:
1035bcf0153eSBarry Smith     You must call this function or `TSSetIFunction()` to define your ODE. You cannot use this function when solving a DAE.
10362bbac0d3SBarry Smith 
1037bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSSetRHSJacobian()`, `TSSetIJacobian()`, `TSSetIFunction()`
1038d763cef2SBarry Smith @*/
1039d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetRHSFunction(TS ts, Vec r, PetscErrorCode (*f)(TS, PetscReal, Vec, Vec, void *), void *ctx)
1040d71ae5a4SJacob Faibussowitsch {
1041089b2837SJed Brown   SNES snes;
10420298fd71SBarry Smith   Vec  ralloc = NULL;
104324989b8cSPeter Brune   DM   dm;
1044d763cef2SBarry Smith 
1045089b2837SJed Brown   PetscFunctionBegin;
10460700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
1047ca94891dSJed Brown   if (r) PetscValidHeaderSpecific(r, VEC_CLASSID, 2);
104824989b8cSPeter Brune 
10499566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
10509566063dSJacob Faibussowitsch   PetscCall(DMTSSetRHSFunction(dm, f, ctx));
10519566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts, &snes));
1052e856ceecSJed Brown   if (!r && !ts->dm && ts->vec_sol) {
10539566063dSJacob Faibussowitsch     PetscCall(VecDuplicate(ts->vec_sol, &ralloc));
1054e856ceecSJed Brown     r = ralloc;
1055e856ceecSJed Brown   }
10569566063dSJacob Faibussowitsch   PetscCall(SNESSetFunction(snes, r, SNESTSFormFunction, ts));
10579566063dSJacob Faibussowitsch   PetscCall(VecDestroy(&ralloc));
10583ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1059d763cef2SBarry Smith }
1060d763cef2SBarry Smith 
1061ef20d060SBarry Smith /*@C
1062abd5a294SJed Brown     TSSetSolutionFunction - Provide a function that computes the solution of the ODE or DAE
1063ef20d060SBarry Smith 
1064c3339decSBarry Smith     Logically Collective
1065ef20d060SBarry Smith 
1066ef20d060SBarry Smith     Input Parameters:
1067bcf0153eSBarry Smith +   ts - the `TS` context obtained from `TSCreate()`
1068ef20d060SBarry Smith .   f - routine for evaluating the solution
1069ef20d060SBarry Smith -   ctx - [optional] user-defined context for private data for the
1070195e9b02SBarry Smith           function evaluation routine (may be `NULL`)
1071ef20d060SBarry Smith 
107220f4b53cSBarry Smith     Calling sequence of `f`:
107320f4b53cSBarry Smith $   PetscErrorCode f(TS ts, PetscReal t, Vec u, void *ctx)
107420f4b53cSBarry Smith +   ts - the integrator context
107520f4b53cSBarry Smith .   t - current timestep
1076ef20d060SBarry Smith .   u - output vector
1077ef20d060SBarry Smith -   ctx - [optional] user-defined function context
1078ef20d060SBarry Smith 
1079bcf0153eSBarry Smith     Options Database Keys:
1080bcf0153eSBarry Smith +  -ts_monitor_lg_error - create a graphical monitor of error history, requires user to have provided `TSSetSolutionFunction()`
1081bcf0153eSBarry Smith -  -ts_monitor_draw_error - Monitor error graphically, requires user to have provided `TSSetSolutionFunction()`
1082bcf0153eSBarry Smith 
1083bcf0153eSBarry Smith     Level: intermediate
10840ed3bfb6SBarry Smith 
1085abd5a294SJed Brown     Notes:
1086abd5a294SJed Brown     This routine is used for testing accuracy of time integration schemes when you already know the solution.
1087abd5a294SJed Brown     If analytic solutions are not known for your system, consider using the Method of Manufactured Solutions to
1088abd5a294SJed Brown     create closed-form solutions with non-physical forcing terms.
1089abd5a294SJed Brown 
1090bcf0153eSBarry Smith     For low-dimensional problems solved in serial, such as small discrete systems, `TSMonitorLGError()` can be used to monitor the error history.
1091abd5a294SJed Brown 
1092bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSSetRHSJacobian()`, `TSSetIJacobian()`, `TSComputeSolutionFunction()`, `TSSetForcingFunction()`, `TSSetSolution()`, `TSGetSolution()`, `TSMonitorLGError()`, `TSMonitorDrawError()`
1093ef20d060SBarry Smith @*/
1094d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetSolutionFunction(TS ts, PetscErrorCode (*f)(TS, PetscReal, Vec, void *), void *ctx)
1095d71ae5a4SJacob Faibussowitsch {
1096ef20d060SBarry Smith   DM dm;
1097ef20d060SBarry Smith 
1098ef20d060SBarry Smith   PetscFunctionBegin;
1099ef20d060SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
11009566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
11019566063dSJacob Faibussowitsch   PetscCall(DMTSSetSolutionFunction(dm, f, ctx));
11023ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1103ef20d060SBarry Smith }
1104ef20d060SBarry Smith 
11059b7cd975SBarry Smith /*@C
11069b7cd975SBarry Smith     TSSetForcingFunction - Provide a function that computes a forcing term for a ODE or PDE
11079b7cd975SBarry Smith 
1108c3339decSBarry Smith     Logically Collective
11099b7cd975SBarry Smith 
11109b7cd975SBarry Smith     Input Parameters:
1111bcf0153eSBarry Smith +   ts - the `TS` context obtained from `TSCreate()`
1112e162b725SBarry Smith .   func - routine for evaluating the forcing function
11139b7cd975SBarry Smith -   ctx - [optional] user-defined context for private data for the
1114195e9b02SBarry Smith           function evaluation routine (may be `NULL`)
11159b7cd975SBarry Smith 
11169b7cd975SBarry Smith     Calling sequence of func:
111720f4b53cSBarry Smith $   PetscErrorCode func(TS ts, PetscReal t, Vec f, void *ctx)
111820f4b53cSBarry Smith +   ts - the integrator context
111920f4b53cSBarry Smith .   t - current timestep
1120e162b725SBarry Smith .   f - output vector
11219b7cd975SBarry Smith -   ctx - [optional] user-defined function context
11229b7cd975SBarry Smith 
1123bcf0153eSBarry Smith     Level: intermediate
1124bcf0153eSBarry Smith 
11259b7cd975SBarry Smith     Notes:
11269b7cd975SBarry Smith     This routine is useful for testing accuracy of time integration schemes when using the Method of Manufactured Solutions to
1127e162b725SBarry 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
1128e162b725SBarry Smith     definition of the problem you are solving and hence possibly introducing bugs.
1129e162b725SBarry Smith 
1130e162b725SBarry Smith     This replaces the ODE F(u,u_t,t) = 0 the TS is solving with F(u,u_t,t) - func(t) = 0
1131e162b725SBarry Smith 
1132e162b725SBarry 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
1133e162b725SBarry Smith     parameters can be passed in the ctx variable.
11349b7cd975SBarry Smith 
1135bcf0153eSBarry Smith     For low-dimensional problems solved in serial, such as small discrete systems, `TSMonitorLGError()` can be used to monitor the error history.
11369b7cd975SBarry Smith 
1137bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSSetRHSJacobian()`, `TSSetIJacobian()`, `TSComputeSolutionFunction()`, `TSSetSolutionFunction()`
11389b7cd975SBarry Smith @*/
1139d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetForcingFunction(TS ts, TSForcingFunction func, void *ctx)
1140d71ae5a4SJacob Faibussowitsch {
11419b7cd975SBarry Smith   DM dm;
11429b7cd975SBarry Smith 
11439b7cd975SBarry Smith   PetscFunctionBegin;
11449b7cd975SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
11459566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
11469566063dSJacob Faibussowitsch   PetscCall(DMTSSetForcingFunction(dm, func, ctx));
11473ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
11489b7cd975SBarry Smith }
11499b7cd975SBarry Smith 
1150d763cef2SBarry Smith /*@C
1151f7ab8db6SBarry Smith    TSSetRHSJacobian - Sets the function to compute the Jacobian of G,
1152b5abc632SBarry Smith    where U_t = G(U,t), as well as the location to store the matrix.
1153d763cef2SBarry Smith 
1154c3339decSBarry Smith    Logically Collective
1155d763cef2SBarry Smith 
1156d763cef2SBarry Smith    Input Parameters:
1157bcf0153eSBarry Smith +  ts  - the `TS` context obtained from `TSCreate()`
1158195e9b02SBarry Smith .  Amat - (approximate) location to store Jacobian matrix entries computed by `f`
1159195e9b02SBarry Smith .  Pmat - matrix from which preconditioner is to be constructed (usually the same as `Amat`)
1160d763cef2SBarry Smith .  f   - the Jacobian evaluation routine
1161195e9b02SBarry Smith -  ctx - [optional] user-defined context for private data for the Jacobian evaluation routine (may be `NULL`)
1162d763cef2SBarry Smith 
116320f4b53cSBarry Smith    Calling sequence of `f`:
116420f4b53cSBarry Smith $  PetscErrorCode f(TS ts, PetscReal t, Vec u, Mat A, Mat B, void *ctx)
116520f4b53cSBarry Smith +  ts  - the `TS` context obtained from `TSCreate()`
116620f4b53cSBarry Smith .  t - current timestep
1167d763cef2SBarry Smith .  u - input vector
1168e5d3d808SBarry Smith .  Amat - (approximate) Jacobian matrix
1169195e9b02SBarry Smith .  Pmat - matrix from which preconditioner is to be constructed (usually the same as `Amat`)
1170d763cef2SBarry Smith -  ctx - [optional] user-defined context for matrix evaluation routine
1171d763cef2SBarry Smith 
1172bcf0153eSBarry Smith    Level: beginner
1173bcf0153eSBarry Smith 
11746cd88445SBarry Smith    Notes:
11756cd88445SBarry Smith    You must set all the diagonal entries of the matrices, if they are zero you must still set them with a zero value
11766cd88445SBarry Smith 
1177bcf0153eSBarry Smith    The `TS` solver may modify the nonzero structure and the entries of the matrices Amat and Pmat between the calls to f()
1178ca5f011dSBarry Smith    You should not assume the values are the same in the next call to f() as you set them in the previous call.
1179d763cef2SBarry Smith 
1180bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `SNESComputeJacobianDefaultColor()`, `TSSetRHSFunction()`, `TSRHSJacobianSetReuse()`, `TSSetIJacobian()`
1181d763cef2SBarry Smith @*/
1182d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetRHSJacobian(TS ts, Mat Amat, Mat Pmat, TSRHSJacobian f, void *ctx)
1183d71ae5a4SJacob Faibussowitsch {
1184089b2837SJed Brown   SNES        snes;
118524989b8cSPeter Brune   DM          dm;
118624989b8cSPeter Brune   TSIJacobian ijacobian;
1187277b19d0SLisandro Dalcin 
1188d763cef2SBarry Smith   PetscFunctionBegin;
11890700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
1190e5d3d808SBarry Smith   if (Amat) PetscValidHeaderSpecific(Amat, MAT_CLASSID, 2);
1191e5d3d808SBarry Smith   if (Pmat) PetscValidHeaderSpecific(Pmat, MAT_CLASSID, 3);
1192e5d3d808SBarry Smith   if (Amat) PetscCheckSameComm(ts, 1, Amat, 2);
1193e5d3d808SBarry Smith   if (Pmat) PetscCheckSameComm(ts, 1, Pmat, 3);
1194d763cef2SBarry Smith 
11959566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
11969566063dSJacob Faibussowitsch   PetscCall(DMTSSetRHSJacobian(dm, f, ctx));
11979566063dSJacob Faibussowitsch   PetscCall(DMTSGetIJacobian(dm, &ijacobian, NULL));
11989566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts, &snes));
11991e66621cSBarry Smith   if (!ijacobian) PetscCall(SNESSetJacobian(snes, Amat, Pmat, SNESTSFormJacobian, ts));
1200e5d3d808SBarry Smith   if (Amat) {
12019566063dSJacob Faibussowitsch     PetscCall(PetscObjectReference((PetscObject)Amat));
12029566063dSJacob Faibussowitsch     PetscCall(MatDestroy(&ts->Arhs));
1203e5d3d808SBarry Smith     ts->Arhs = Amat;
12040e4ef248SJed Brown   }
1205e5d3d808SBarry Smith   if (Pmat) {
12069566063dSJacob Faibussowitsch     PetscCall(PetscObjectReference((PetscObject)Pmat));
12079566063dSJacob Faibussowitsch     PetscCall(MatDestroy(&ts->Brhs));
1208e5d3d808SBarry Smith     ts->Brhs = Pmat;
12090e4ef248SJed Brown   }
12103ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1211d763cef2SBarry Smith }
1212d763cef2SBarry Smith 
1213316643e7SJed Brown /*@C
1214b5abc632SBarry Smith    TSSetIFunction - Set the function to compute F(t,U,U_t) where F() = 0 is the DAE to be solved.
1215316643e7SJed Brown 
1216c3339decSBarry Smith    Logically Collective
1217316643e7SJed Brown 
1218316643e7SJed Brown    Input Parameters:
1219bcf0153eSBarry Smith +  ts  - the `TS` context obtained from `TSCreate()`
1220195e9b02SBarry Smith .  r   - vector to hold the residual (or `NULL` to have it created internally)
1221316643e7SJed Brown .  f   - the function evaluation routine
1222195e9b02SBarry Smith -  ctx - user-defined context for private data for the function evaluation routine (may be `NULL`)
1223316643e7SJed Brown 
122420f4b53cSBarry Smith    Calling sequence of `f`:
122520f4b53cSBarry Smith $   PetscErrorCode f(TS ts, PetscReal t, Vec u, Vec u_t, Vec F, void *ctx)
122620f4b53cSBarry Smith +  ts  - the `TS` context obtained from `TSCreate()`
122720f4b53cSBarry Smith .  t   - time at step/stage being solved
1228316643e7SJed Brown .  u   - state vector
1229316643e7SJed Brown .  u_t - time derivative of state vector
1230316643e7SJed Brown .  F   - function vector
1231316643e7SJed Brown -  ctx - [optional] user-defined context for matrix evaluation routine
1232316643e7SJed Brown 
1233316643e7SJed Brown    Level: beginner
1234316643e7SJed Brown 
1235bcf0153eSBarry Smith    Note:
1236bcf0153eSBarry Smith    The user MUST call either this routine or `TSSetRHSFunction()` to define the ODE.  When solving DAEs you must use this function.
1237bcf0153eSBarry Smith 
1238bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSSetRHSJacobian()`, `TSSetRHSFunction()`, `TSSetIJacobian()`
1239316643e7SJed Brown @*/
1240d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetIFunction(TS ts, Vec r, TSIFunction f, void *ctx)
1241d71ae5a4SJacob Faibussowitsch {
1242089b2837SJed Brown   SNES snes;
124351699248SLisandro Dalcin   Vec  ralloc = NULL;
124424989b8cSPeter Brune   DM   dm;
1245316643e7SJed Brown 
1246316643e7SJed Brown   PetscFunctionBegin;
12470700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
124851699248SLisandro Dalcin   if (r) PetscValidHeaderSpecific(r, VEC_CLASSID, 2);
124924989b8cSPeter Brune 
12509566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
12519566063dSJacob Faibussowitsch   PetscCall(DMTSSetIFunction(dm, f, ctx));
125224989b8cSPeter Brune 
12539566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts, &snes));
125451699248SLisandro Dalcin   if (!r && !ts->dm && ts->vec_sol) {
12559566063dSJacob Faibussowitsch     PetscCall(VecDuplicate(ts->vec_sol, &ralloc));
125651699248SLisandro Dalcin     r = ralloc;
1257e856ceecSJed Brown   }
12589566063dSJacob Faibussowitsch   PetscCall(SNESSetFunction(snes, r, SNESTSFormFunction, ts));
12599566063dSJacob Faibussowitsch   PetscCall(VecDestroy(&ralloc));
12603ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1261089b2837SJed Brown }
1262089b2837SJed Brown 
1263089b2837SJed Brown /*@C
1264a5b23f4aSJose E. Roman    TSGetIFunction - Returns the vector where the implicit residual is stored and the function/context to compute it.
1265089b2837SJed Brown 
1266089b2837SJed Brown    Not Collective
1267089b2837SJed Brown 
1268089b2837SJed Brown    Input Parameter:
1269bcf0153eSBarry Smith .  ts - the `TS` context
1270089b2837SJed Brown 
1271d8d19677SJose E. Roman    Output Parameters:
1272195e9b02SBarry Smith +  r - vector to hold residual (or `NULL`)
1273195e9b02SBarry Smith .  func - the function to compute residual (or `NULL`)
1274195e9b02SBarry Smith -  ctx - the function context (or `NULL`)
1275089b2837SJed Brown 
1276089b2837SJed Brown    Level: advanced
1277089b2837SJed Brown 
1278bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSSetIFunction()`, `SNESGetFunction()`
1279089b2837SJed Brown @*/
1280d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetIFunction(TS ts, Vec *r, TSIFunction *func, void **ctx)
1281d71ae5a4SJacob Faibussowitsch {
1282089b2837SJed Brown   SNES snes;
128324989b8cSPeter Brune   DM   dm;
1284089b2837SJed Brown 
1285089b2837SJed Brown   PetscFunctionBegin;
1286089b2837SJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
12879566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts, &snes));
12889566063dSJacob Faibussowitsch   PetscCall(SNESGetFunction(snes, r, NULL, NULL));
12899566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
12909566063dSJacob Faibussowitsch   PetscCall(DMTSGetIFunction(dm, func, ctx));
12913ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1292089b2837SJed Brown }
1293089b2837SJed Brown 
1294089b2837SJed Brown /*@C
1295089b2837SJed Brown    TSGetRHSFunction - Returns the vector where the right hand side is stored and the function/context to compute it.
1296089b2837SJed Brown 
1297089b2837SJed Brown    Not Collective
1298089b2837SJed Brown 
1299089b2837SJed Brown    Input Parameter:
1300bcf0153eSBarry Smith .  ts - the `TS` context
1301089b2837SJed Brown 
1302d8d19677SJose E. Roman    Output Parameters:
1303195e9b02SBarry Smith +  r - vector to hold computed right hand side (or `NULL`)
1304195e9b02SBarry Smith .  func - the function to compute right hand side (or `NULL`)
1305195e9b02SBarry Smith -  ctx - the function context (or `NULL`)
1306089b2837SJed Brown 
1307089b2837SJed Brown    Level: advanced
1308089b2837SJed Brown 
1309bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSSetRHSFunction()`, `SNESGetFunction()`
1310089b2837SJed Brown @*/
1311d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetRHSFunction(TS ts, Vec *r, TSRHSFunction *func, void **ctx)
1312d71ae5a4SJacob Faibussowitsch {
1313089b2837SJed Brown   SNES snes;
131424989b8cSPeter Brune   DM   dm;
1315089b2837SJed Brown 
1316089b2837SJed Brown   PetscFunctionBegin;
1317089b2837SJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
13189566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts, &snes));
13199566063dSJacob Faibussowitsch   PetscCall(SNESGetFunction(snes, r, NULL, NULL));
13209566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
13219566063dSJacob Faibussowitsch   PetscCall(DMTSGetRHSFunction(dm, func, ctx));
13223ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1323316643e7SJed Brown }
1324316643e7SJed Brown 
1325316643e7SJed Brown /*@C
1326a4f0a591SBarry Smith    TSSetIJacobian - Set the function to compute the matrix dF/dU + a*dF/dU_t where F(t,U,U_t) is the function
1327bcf0153eSBarry Smith         provided with `TSSetIFunction()`.
1328316643e7SJed Brown 
1329c3339decSBarry Smith    Logically Collective
1330316643e7SJed Brown 
1331316643e7SJed Brown    Input Parameters:
1332bcf0153eSBarry Smith +  ts  - the `TS` context obtained from `TSCreate()`
1333*aaa8cc7dSPierre Jolivet .  Amat - (approximate) matrix to store Jacobian entries computed by `f`
1334195e9b02SBarry Smith .  Pmat - matrix used to compute preconditioner (usually the same as `Amat`)
1335316643e7SJed Brown .  f   - the Jacobian evaluation routine
1336195e9b02SBarry Smith -  ctx - user-defined context for private data for the Jacobian evaluation routine (may be `NULL`)
1337316643e7SJed Brown 
133820f4b53cSBarry Smith    Calling sequence of `f`:
133920f4b53cSBarry Smith $    PetscErrorCode f(TS ts, PetscReal t, Vec U, Vec U_t, PetscReal a, Mat Amat, Mat Pmat, void *ctx)
134020f4b53cSBarry Smith +  ts  - the `TS` context obtained from `TSCreate()`
134120f4b53cSBarry Smith .  t    - time at step/stage being solved
13421b4a444bSJed Brown .  U    - state vector
13431b4a444bSJed Brown .  U_t  - time derivative of state vector
1344316643e7SJed Brown .  a    - shift
1345e5d3d808SBarry Smith .  Amat - (approximate) Jacobian of F(t,U,W+a*U), equivalent to dF/dU + a*dF/dU_t
1346195e9b02SBarry Smith .  Pmat - matrix used for constructing preconditioner, usually the same as `Amat`
1347316643e7SJed Brown -  ctx  - [optional] user-defined context for matrix evaluation routine
1348316643e7SJed Brown 
1349bcf0153eSBarry Smith    Level: beginner
1350316643e7SJed Brown 
1351bcf0153eSBarry Smith    Notes:
1352195e9b02SBarry Smith    The matrices `Amat` and `Pmat` are exactly the matrices that are used by `SNES` for the nonlinear solve.
1353bcf0153eSBarry Smith 
1354bcf0153eSBarry Smith    If you know the operator Amat has a null space you can use `MatSetNullSpace()` and `MatSetTransposeNullSpace()` to supply the null
1355195e9b02SBarry Smith    space to `Amat` and the `KSP` solvers will automatically use that null space as needed during the solution process.
1356895c21f2SBarry Smith 
1357a4f0a591SBarry Smith    The matrix dF/dU + a*dF/dU_t you provide turns out to be
1358b5abc632SBarry Smith    the Jacobian of F(t,U,W+a*U) where F(t,U,U_t) = 0 is the DAE to be solved.
1359a4f0a591SBarry Smith    The time integrator internally approximates U_t by W+a*U where the positive "shift"
1360a4f0a591SBarry Smith    a and vector W depend on the integration method, step size, and past states. For example with
1361a4f0a591SBarry Smith    the backward Euler method a = 1/dt and W = -a*U(previous timestep) so
1362a4f0a591SBarry Smith    W + a*U = a*(U - U(previous timestep)) = (U - U(previous timestep))/dt
1363a4f0a591SBarry Smith 
13646cd88445SBarry Smith    You must set all the diagonal entries of the matrices, if they are zero you must still set them with a zero value
13656cd88445SBarry Smith 
1366195e9b02SBarry Smith    The TS solver may modify the nonzero structure and the entries of the matrices `Amat` and `Pmat` between the calls to `f`
1367195e9b02SBarry Smith    You should not assume the values are the same in the next call to `f` as you set them in the previous call.
1368ca5f011dSBarry Smith 
1369bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSSetIFunction()`, `TSSetRHSJacobian()`, `SNESComputeJacobianDefaultColor()`, `SNESComputeJacobianDefault()`, `TSSetRHSFunction()`
1370316643e7SJed Brown @*/
1371d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetIJacobian(TS ts, Mat Amat, Mat Pmat, TSIJacobian f, void *ctx)
1372d71ae5a4SJacob Faibussowitsch {
1373089b2837SJed Brown   SNES snes;
137424989b8cSPeter Brune   DM   dm;
1375316643e7SJed Brown 
1376316643e7SJed Brown   PetscFunctionBegin;
13770700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
1378e5d3d808SBarry Smith   if (Amat) PetscValidHeaderSpecific(Amat, MAT_CLASSID, 2);
1379e5d3d808SBarry Smith   if (Pmat) PetscValidHeaderSpecific(Pmat, MAT_CLASSID, 3);
1380e5d3d808SBarry Smith   if (Amat) PetscCheckSameComm(ts, 1, Amat, 2);
1381e5d3d808SBarry Smith   if (Pmat) PetscCheckSameComm(ts, 1, Pmat, 3);
138224989b8cSPeter Brune 
13839566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
13849566063dSJacob Faibussowitsch   PetscCall(DMTSSetIJacobian(dm, f, ctx));
138524989b8cSPeter Brune 
13869566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts, &snes));
13879566063dSJacob Faibussowitsch   PetscCall(SNESSetJacobian(snes, Amat, Pmat, SNESTSFormJacobian, ts));
13883ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1389316643e7SJed Brown }
1390316643e7SJed Brown 
1391e1244c69SJed Brown /*@
1392bcf0153eSBarry Smith    TSRHSJacobianSetReuse - restore RHS Jacobian before re-evaluating.  Without this flag, `TS` will change the sign and
1393e1244c69SJed Brown    shift the RHS Jacobian for a finite-time-step implicit solve, in which case the user function will need to recompute
1394e1244c69SJed Brown    the entire Jacobian.  The reuse flag must be set if the evaluation function will assume that the matrix entries have
1395195e9b02SBarry Smith    not been changed by the `TS`.
1396e1244c69SJed Brown 
1397e1244c69SJed Brown    Logically Collective
1398e1244c69SJed Brown 
13994165533cSJose E. Roman    Input Parameters:
1400bcf0153eSBarry Smith +  ts - `TS` context obtained from `TSCreate()`
1401bcf0153eSBarry Smith -  reuse - `PETSC_TRUE` if the RHS Jacobian
1402e1244c69SJed Brown 
1403e1244c69SJed Brown    Level: intermediate
1404e1244c69SJed Brown 
1405bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSSetRHSJacobian()`, `TSComputeRHSJacobianConstant()`
1406e1244c69SJed Brown @*/
1407d71ae5a4SJacob Faibussowitsch PetscErrorCode TSRHSJacobianSetReuse(TS ts, PetscBool reuse)
1408d71ae5a4SJacob Faibussowitsch {
1409e1244c69SJed Brown   PetscFunctionBegin;
1410e1244c69SJed Brown   ts->rhsjacobian.reuse = reuse;
14113ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1412e1244c69SJed Brown }
1413e1244c69SJed Brown 
1414efe9872eSLisandro Dalcin /*@C
1415efe9872eSLisandro Dalcin    TSSetI2Function - Set the function to compute F(t,U,U_t,U_tt) where F = 0 is the DAE to be solved.
1416efe9872eSLisandro Dalcin 
1417c3339decSBarry Smith    Logically Collective
1418efe9872eSLisandro Dalcin 
1419efe9872eSLisandro Dalcin    Input Parameters:
1420bcf0153eSBarry Smith +  ts  - the `TS` context obtained from `TSCreate()`
1421195e9b02SBarry Smith .  F   - vector to hold the residual (or `NULL` to have it created internally)
1422efe9872eSLisandro Dalcin .  fun - the function evaluation routine
1423195e9b02SBarry Smith -  ctx - user-defined context for private data for the function evaluation routine (may be `NULL`)
1424efe9872eSLisandro Dalcin 
142520f4b53cSBarry Smith    Calling sequence of `fun`:
142620f4b53cSBarry Smith $   PetscErrorCode fun(TS ts, PetscReal t, Vec U, Vec U_t, Vec U_tt, Vec F,void *ctx);
142720f4b53cSBarry Smith +  ts  - the `TS` context obtained from `TSCreate()`
142820f4b53cSBarry Smith .  t    - time at step/stage being solved
1429efe9872eSLisandro Dalcin .  U    - state vector
1430efe9872eSLisandro Dalcin .  U_t  - time derivative of state vector
1431efe9872eSLisandro Dalcin .  U_tt - second time derivative of state vector
1432efe9872eSLisandro Dalcin .  F    - function vector
1433195e9b02SBarry Smith -  ctx  - [optional] user-defined context for matrix evaluation routine (may be `NULL`)
1434efe9872eSLisandro Dalcin 
1435efe9872eSLisandro Dalcin    Level: beginner
1436efe9872eSLisandro Dalcin 
1437bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSSetI2Jacobian()`, `TSSetIFunction()`, `TSCreate()`, `TSSetRHSFunction()`
1438efe9872eSLisandro Dalcin @*/
1439d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetI2Function(TS ts, Vec F, TSI2Function fun, void *ctx)
1440d71ae5a4SJacob Faibussowitsch {
1441efe9872eSLisandro Dalcin   DM dm;
1442efe9872eSLisandro Dalcin 
1443efe9872eSLisandro Dalcin   PetscFunctionBegin;
1444efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
1445efe9872eSLisandro Dalcin   if (F) PetscValidHeaderSpecific(F, VEC_CLASSID, 2);
14469566063dSJacob Faibussowitsch   PetscCall(TSSetIFunction(ts, F, NULL, NULL));
14479566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
14489566063dSJacob Faibussowitsch   PetscCall(DMTSSetI2Function(dm, fun, ctx));
14493ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1450efe9872eSLisandro Dalcin }
1451efe9872eSLisandro Dalcin 
1452efe9872eSLisandro Dalcin /*@C
1453a5b23f4aSJose E. Roman   TSGetI2Function - Returns the vector where the implicit residual is stored and the function/context to compute it.
1454efe9872eSLisandro Dalcin 
1455efe9872eSLisandro Dalcin   Not Collective
1456efe9872eSLisandro Dalcin 
1457efe9872eSLisandro Dalcin   Input Parameter:
1458bcf0153eSBarry Smith . ts - the `TS` context
1459efe9872eSLisandro Dalcin 
1460d8d19677SJose E. Roman   Output Parameters:
1461195e9b02SBarry Smith + r - vector to hold residual (or `NULL`)
1462195e9b02SBarry Smith . fun - the function to compute residual (or `NULL`)
1463195e9b02SBarry Smith - ctx - the function context (or `NULL`)
1464efe9872eSLisandro Dalcin 
1465efe9872eSLisandro Dalcin   Level: advanced
1466efe9872eSLisandro Dalcin 
1467bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSSetIFunction()`, `SNESGetFunction()`, `TSCreate()`
1468efe9872eSLisandro Dalcin @*/
1469d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetI2Function(TS ts, Vec *r, TSI2Function *fun, void **ctx)
1470d71ae5a4SJacob Faibussowitsch {
1471efe9872eSLisandro Dalcin   SNES snes;
1472efe9872eSLisandro Dalcin   DM   dm;
1473efe9872eSLisandro Dalcin 
1474efe9872eSLisandro Dalcin   PetscFunctionBegin;
1475efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
14769566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts, &snes));
14779566063dSJacob Faibussowitsch   PetscCall(SNESGetFunction(snes, r, NULL, NULL));
14789566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
14799566063dSJacob Faibussowitsch   PetscCall(DMTSGetI2Function(dm, fun, ctx));
14803ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1481efe9872eSLisandro Dalcin }
1482efe9872eSLisandro Dalcin 
1483efe9872eSLisandro Dalcin /*@C
1484bc77d74cSLisandro Dalcin    TSSetI2Jacobian - Set the function to compute the matrix dF/dU + v*dF/dU_t  + a*dF/dU_tt
1485bcf0153eSBarry Smith         where F(t,U,U_t,U_tt) is the function you provided with `TSSetI2Function()`.
1486efe9872eSLisandro Dalcin 
1487c3339decSBarry Smith    Logically Collective
1488efe9872eSLisandro Dalcin 
1489efe9872eSLisandro Dalcin    Input Parameters:
1490bcf0153eSBarry Smith +  ts  - the `TS` context obtained from `TSCreate()`
1491195e9b02SBarry Smith .  J   - matrix to hold the Jacobian values
1492195e9b02SBarry Smith .  P   - matrix for constructing the preconditioner (may be same as `J`)
1493efe9872eSLisandro Dalcin .  jac - the Jacobian evaluation routine
1494195e9b02SBarry Smith -  ctx - user-defined context for private data for the Jacobian evaluation routine (may be `NULL`)
1495efe9872eSLisandro Dalcin 
149620f4b53cSBarry Smith    Calling sequence of `jac`:
149720f4b53cSBarry 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)
149820f4b53cSBarry Smith +  ts  - the `TS` context obtained from `TSCreate()`
149920f4b53cSBarry Smith .  t    - time at step/stage being solved
1500efe9872eSLisandro Dalcin .  U    - state vector
1501efe9872eSLisandro Dalcin .  U_t  - time derivative of state vector
1502efe9872eSLisandro Dalcin .  U_tt - second time derivative of state vector
1503efe9872eSLisandro Dalcin .  v    - shift for U_t
1504efe9872eSLisandro Dalcin .  a    - shift for U_tt
1505efe9872eSLisandro 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
1506efe9872eSLisandro Dalcin .  P    - preconditioning matrix for J, may be same as J
1507efe9872eSLisandro Dalcin -  ctx  - [optional] user-defined context for matrix evaluation routine
1508efe9872eSLisandro Dalcin 
1509bcf0153eSBarry Smith    Level: beginner
1510bcf0153eSBarry Smith 
1511efe9872eSLisandro Dalcin    Notes:
1512195e9b02SBarry Smith    The matrices `J` and `P` are exactly the matrices that are used by `SNES` for the nonlinear solve.
1513efe9872eSLisandro Dalcin 
1514efe9872eSLisandro Dalcin    The matrix dF/dU + v*dF/dU_t + a*dF/dU_tt you provide turns out to be
1515efe9872eSLisandro 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.
1516efe9872eSLisandro Dalcin    The time integrator internally approximates U_t by W+v*U and U_tt by W'+a*U  where the positive "shift"
1517bc77d74cSLisandro Dalcin    parameters 'v' and 'a' and vectors W, W' depend on the integration method, step size, and past states.
1518efe9872eSLisandro Dalcin 
1519bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSSetI2Function()`, `TSGetI2Jacobian()`
1520efe9872eSLisandro Dalcin @*/
1521d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetI2Jacobian(TS ts, Mat J, Mat P, TSI2Jacobian jac, void *ctx)
1522d71ae5a4SJacob Faibussowitsch {
1523efe9872eSLisandro Dalcin   DM dm;
1524efe9872eSLisandro Dalcin 
1525efe9872eSLisandro Dalcin   PetscFunctionBegin;
1526efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
1527efe9872eSLisandro Dalcin   if (J) PetscValidHeaderSpecific(J, MAT_CLASSID, 2);
1528efe9872eSLisandro Dalcin   if (P) PetscValidHeaderSpecific(P, MAT_CLASSID, 3);
15299566063dSJacob Faibussowitsch   PetscCall(TSSetIJacobian(ts, J, P, NULL, NULL));
15309566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
15319566063dSJacob Faibussowitsch   PetscCall(DMTSSetI2Jacobian(dm, jac, ctx));
15323ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1533efe9872eSLisandro Dalcin }
1534efe9872eSLisandro Dalcin 
1535efe9872eSLisandro Dalcin /*@C
1536efe9872eSLisandro Dalcin   TSGetI2Jacobian - Returns the implicit Jacobian at the present timestep.
1537efe9872eSLisandro Dalcin 
1538bcf0153eSBarry Smith   Not Collective, but parallel objects are returned if `TS` is parallel
1539efe9872eSLisandro Dalcin 
1540efe9872eSLisandro Dalcin   Input Parameter:
1541bcf0153eSBarry Smith . ts  - The `TS` context obtained from `TSCreate()`
1542efe9872eSLisandro Dalcin 
1543efe9872eSLisandro Dalcin   Output Parameters:
1544efe9872eSLisandro Dalcin + J  - The (approximate) Jacobian of F(t,U,U_t,U_tt)
1545195e9b02SBarry Smith . P - The matrix from which the preconditioner is constructed, often the same as `J`
1546efe9872eSLisandro Dalcin . jac - The function to compute the Jacobian matrices
1547efe9872eSLisandro Dalcin - ctx - User-defined context for Jacobian evaluation routine
1548efe9872eSLisandro Dalcin 
1549bcf0153eSBarry Smith   Level: advanced
1550bcf0153eSBarry Smith 
1551195e9b02SBarry Smith   Note:
1552195e9b02SBarry Smith     You can pass in `NULL` for any return argument you do not need.
1553efe9872eSLisandro Dalcin 
1554bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSGetTimeStep()`, `TSGetMatrices()`, `TSGetTime()`, `TSGetStepNumber()`, `TSSetI2Jacobian()`, `TSGetI2Function()`, `TSCreate()`
1555efe9872eSLisandro Dalcin @*/
1556d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetI2Jacobian(TS ts, Mat *J, Mat *P, TSI2Jacobian *jac, void **ctx)
1557d71ae5a4SJacob Faibussowitsch {
1558efe9872eSLisandro Dalcin   SNES snes;
1559efe9872eSLisandro Dalcin   DM   dm;
1560efe9872eSLisandro Dalcin 
1561efe9872eSLisandro Dalcin   PetscFunctionBegin;
15629566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts, &snes));
15639566063dSJacob Faibussowitsch   PetscCall(SNESSetUpMatrices(snes));
15649566063dSJacob Faibussowitsch   PetscCall(SNESGetJacobian(snes, J, P, NULL, NULL));
15659566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
15669566063dSJacob Faibussowitsch   PetscCall(DMTSGetI2Jacobian(dm, jac, ctx));
15673ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1568efe9872eSLisandro Dalcin }
1569efe9872eSLisandro Dalcin 
1570efe9872eSLisandro Dalcin /*@
1571efe9872eSLisandro Dalcin   TSComputeI2Function - Evaluates the DAE residual written in implicit form F(t,U,U_t,U_tt) = 0
1572efe9872eSLisandro Dalcin 
1573c3339decSBarry Smith   Collective
1574efe9872eSLisandro Dalcin 
1575efe9872eSLisandro Dalcin   Input Parameters:
1576bcf0153eSBarry Smith + ts - the `TS` context
1577efe9872eSLisandro Dalcin . t - current time
1578efe9872eSLisandro Dalcin . U - state vector
1579efe9872eSLisandro Dalcin . V - time derivative of state vector (U_t)
1580efe9872eSLisandro Dalcin - A - second time derivative of state vector (U_tt)
1581efe9872eSLisandro Dalcin 
1582efe9872eSLisandro Dalcin   Output Parameter:
1583efe9872eSLisandro Dalcin . F - the residual vector
1584efe9872eSLisandro Dalcin 
1585bcf0153eSBarry Smith   Level: developer
1586bcf0153eSBarry Smith 
1587efe9872eSLisandro Dalcin   Note:
1588efe9872eSLisandro Dalcin   Most users should not need to explicitly call this routine, as it
1589efe9872eSLisandro Dalcin   is used internally within the nonlinear solvers.
1590efe9872eSLisandro Dalcin 
1591bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSSetI2Function()`, `TSGetI2Function()`
1592efe9872eSLisandro Dalcin @*/
1593d71ae5a4SJacob Faibussowitsch PetscErrorCode TSComputeI2Function(TS ts, PetscReal t, Vec U, Vec V, Vec A, Vec F)
1594d71ae5a4SJacob Faibussowitsch {
1595efe9872eSLisandro Dalcin   DM            dm;
1596efe9872eSLisandro Dalcin   TSI2Function  I2Function;
1597efe9872eSLisandro Dalcin   void         *ctx;
1598efe9872eSLisandro Dalcin   TSRHSFunction rhsfunction;
1599efe9872eSLisandro Dalcin 
1600efe9872eSLisandro Dalcin   PetscFunctionBegin;
1601efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
1602efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(U, VEC_CLASSID, 3);
1603efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(V, VEC_CLASSID, 4);
1604efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(A, VEC_CLASSID, 5);
1605efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(F, VEC_CLASSID, 6);
1606efe9872eSLisandro Dalcin 
16079566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
16089566063dSJacob Faibussowitsch   PetscCall(DMTSGetI2Function(dm, &I2Function, &ctx));
16099566063dSJacob Faibussowitsch   PetscCall(DMTSGetRHSFunction(dm, &rhsfunction, NULL));
1610efe9872eSLisandro Dalcin 
1611efe9872eSLisandro Dalcin   if (!I2Function) {
16129566063dSJacob Faibussowitsch     PetscCall(TSComputeIFunction(ts, t, U, A, F, PETSC_FALSE));
16133ba16761SJacob Faibussowitsch     PetscFunctionReturn(PETSC_SUCCESS);
1614efe9872eSLisandro Dalcin   }
1615efe9872eSLisandro Dalcin 
16169566063dSJacob Faibussowitsch   PetscCall(PetscLogEventBegin(TS_FunctionEval, ts, U, V, F));
1617efe9872eSLisandro Dalcin 
1618792fecdfSBarry Smith   PetscCallBack("TS callback implicit function", I2Function(ts, t, U, V, A, F, ctx));
1619efe9872eSLisandro Dalcin 
1620efe9872eSLisandro Dalcin   if (rhsfunction) {
1621efe9872eSLisandro Dalcin     Vec Frhs;
16229566063dSJacob Faibussowitsch     PetscCall(TSGetRHSVec_Private(ts, &Frhs));
16239566063dSJacob Faibussowitsch     PetscCall(TSComputeRHSFunction(ts, t, U, Frhs));
16249566063dSJacob Faibussowitsch     PetscCall(VecAXPY(F, -1, Frhs));
1625efe9872eSLisandro Dalcin   }
1626efe9872eSLisandro Dalcin 
16279566063dSJacob Faibussowitsch   PetscCall(PetscLogEventEnd(TS_FunctionEval, ts, U, V, F));
16283ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1629efe9872eSLisandro Dalcin }
1630efe9872eSLisandro Dalcin 
1631efe9872eSLisandro Dalcin /*@
1632efe9872eSLisandro Dalcin   TSComputeI2Jacobian - Evaluates the Jacobian of the DAE
1633efe9872eSLisandro Dalcin 
1634c3339decSBarry Smith   Collective
1635efe9872eSLisandro Dalcin 
1636efe9872eSLisandro Dalcin   Input Parameters:
1637bcf0153eSBarry Smith + ts - the `TS` context
1638efe9872eSLisandro Dalcin . t - current timestep
1639efe9872eSLisandro Dalcin . U - state vector
1640efe9872eSLisandro Dalcin . V - time derivative of state vector
1641efe9872eSLisandro Dalcin . A - second time derivative of state vector
1642efe9872eSLisandro Dalcin . shiftV - shift to apply, see note below
1643efe9872eSLisandro Dalcin - shiftA - shift to apply, see note below
1644efe9872eSLisandro Dalcin 
1645efe9872eSLisandro Dalcin   Output Parameters:
1646efe9872eSLisandro Dalcin + J - Jacobian matrix
1647efe9872eSLisandro Dalcin - P - optional preconditioning matrix
1648efe9872eSLisandro Dalcin 
1649bcf0153eSBarry Smith   Level: developer
1650bcf0153eSBarry Smith 
1651efe9872eSLisandro Dalcin   Notes:
1652efe9872eSLisandro Dalcin   If F(t,U,V,A)=0 is the DAE, the required Jacobian is
1653efe9872eSLisandro Dalcin 
1654efe9872eSLisandro Dalcin   dF/dU + shiftV*dF/dV + shiftA*dF/dA
1655efe9872eSLisandro Dalcin 
1656efe9872eSLisandro Dalcin   Most users should not need to explicitly call this routine, as it
1657efe9872eSLisandro Dalcin   is used internally within the nonlinear solvers.
1658efe9872eSLisandro Dalcin 
1659bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSSetI2Jacobian()`
1660efe9872eSLisandro Dalcin @*/
1661d71ae5a4SJacob Faibussowitsch PetscErrorCode TSComputeI2Jacobian(TS ts, PetscReal t, Vec U, Vec V, Vec A, PetscReal shiftV, PetscReal shiftA, Mat J, Mat P)
1662d71ae5a4SJacob Faibussowitsch {
1663efe9872eSLisandro Dalcin   DM            dm;
1664efe9872eSLisandro Dalcin   TSI2Jacobian  I2Jacobian;
1665efe9872eSLisandro Dalcin   void         *ctx;
1666efe9872eSLisandro Dalcin   TSRHSJacobian rhsjacobian;
1667efe9872eSLisandro Dalcin 
1668efe9872eSLisandro Dalcin   PetscFunctionBegin;
1669efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
1670efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(U, VEC_CLASSID, 3);
1671efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(V, VEC_CLASSID, 4);
1672efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(A, VEC_CLASSID, 5);
1673efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(J, MAT_CLASSID, 8);
1674efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(P, MAT_CLASSID, 9);
1675efe9872eSLisandro Dalcin 
16769566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
16779566063dSJacob Faibussowitsch   PetscCall(DMTSGetI2Jacobian(dm, &I2Jacobian, &ctx));
16789566063dSJacob Faibussowitsch   PetscCall(DMTSGetRHSJacobian(dm, &rhsjacobian, NULL));
1679efe9872eSLisandro Dalcin 
1680efe9872eSLisandro Dalcin   if (!I2Jacobian) {
16819566063dSJacob Faibussowitsch     PetscCall(TSComputeIJacobian(ts, t, U, A, shiftA, J, P, PETSC_FALSE));
16823ba16761SJacob Faibussowitsch     PetscFunctionReturn(PETSC_SUCCESS);
1683efe9872eSLisandro Dalcin   }
1684efe9872eSLisandro Dalcin 
16859566063dSJacob Faibussowitsch   PetscCall(PetscLogEventBegin(TS_JacobianEval, ts, U, J, P));
1686792fecdfSBarry Smith   PetscCallBack("TS callback implicit Jacobian", I2Jacobian(ts, t, U, V, A, shiftV, shiftA, J, P, ctx));
1687efe9872eSLisandro Dalcin   if (rhsjacobian) {
1688d60b7d5cSBarry Smith     Mat Jrhs, Prhs;
16899566063dSJacob Faibussowitsch     PetscCall(TSGetRHSMats_Private(ts, &Jrhs, &Prhs));
16909566063dSJacob Faibussowitsch     PetscCall(TSComputeRHSJacobian(ts, t, U, Jrhs, Prhs));
16919566063dSJacob Faibussowitsch     PetscCall(MatAXPY(J, -1, Jrhs, ts->axpy_pattern));
16929566063dSJacob Faibussowitsch     if (P != J) PetscCall(MatAXPY(P, -1, Prhs, ts->axpy_pattern));
1693efe9872eSLisandro Dalcin   }
1694efe9872eSLisandro Dalcin 
16959566063dSJacob Faibussowitsch   PetscCall(PetscLogEventEnd(TS_JacobianEval, ts, U, J, P));
16963ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1697efe9872eSLisandro Dalcin }
1698efe9872eSLisandro Dalcin 
1699438f35afSJed Brown /*@C
1700438f35afSJed Brown    TSSetTransientVariable - sets function to transform from state to transient variables
1701438f35afSJed Brown 
1702438f35afSJed Brown    Logically Collective
1703438f35afSJed Brown 
17044165533cSJose E. Roman    Input Parameters:
1705438f35afSJed Brown +  ts - time stepping context on which to change the transient variable
1706a96d6ef6SBarry Smith .  tvar - a function that transforms to transient variables
1707438f35afSJed Brown -  ctx - a context for tvar
1708438f35afSJed Brown 
170920f4b53cSBarry Smith     Calling sequence of `tvar`:
171020f4b53cSBarry Smith $   PetscErrorCode tvar(TS ts, Vec p, Vec c, void *ctx)
1711a96d6ef6SBarry Smith +   ts - timestep context
17126aad120cSJose E. Roman .   p - input vector (primitive form)
1713a96d6ef6SBarry Smith .   c - output vector, transient variables (conservative form)
1714a96d6ef6SBarry Smith -   ctx - [optional] user-defined function context
1715a96d6ef6SBarry Smith 
1716438f35afSJed Brown    Level: advanced
1717438f35afSJed Brown 
1718438f35afSJed Brown    Notes:
1719bcf0153eSBarry Smith    This is typically used to transform from primitive to conservative variables so that a time integrator (e.g., `TSBDF`)
1720438f35afSJed Brown    can be conservative.  In this context, primitive variables P are used to model the state (e.g., because they lead to
1721438f35afSJed Brown    well-conditioned formulations even in limiting cases such as low-Mach or zero porosity).  The transient variable is
1722438f35afSJed Brown    C(P), specified by calling this function.  An IFunction thus receives arguments (P, Cdot) and the IJacobian must be
1723438f35afSJed Brown    evaluated via the chain rule, as in
1724195e9b02SBarry Smith .vb
1725438f35afSJed Brown      dF/dP + shift * dF/dCdot dC/dP.
1726195e9b02SBarry Smith .ve
1727438f35afSJed Brown 
1728bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSBDF`, `DMTSSetTransientVariable()`, `DMTSGetTransientVariable()`, `TSSetIFunction()`, `TSSetIJacobian()`
1729438f35afSJed Brown @*/
1730d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetTransientVariable(TS ts, TSTransientVariable tvar, void *ctx)
1731d71ae5a4SJacob Faibussowitsch {
1732438f35afSJed Brown   DM dm;
1733438f35afSJed Brown 
1734438f35afSJed Brown   PetscFunctionBegin;
1735438f35afSJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
17369566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
17379566063dSJacob Faibussowitsch   PetscCall(DMTSSetTransientVariable(dm, tvar, ctx));
17383ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1739438f35afSJed Brown }
1740438f35afSJed Brown 
1741efe9872eSLisandro Dalcin /*@
1742e3c11fc1SJed Brown    TSComputeTransientVariable - transforms state (primitive) variables to transient (conservative) variables
1743e3c11fc1SJed Brown 
1744e3c11fc1SJed Brown    Logically Collective
1745e3c11fc1SJed Brown 
1746e3c11fc1SJed Brown    Input Parameters:
1747e3c11fc1SJed Brown +  ts - TS on which to compute
1748e3c11fc1SJed Brown -  U - state vector to be transformed to transient variables
1749e3c11fc1SJed Brown 
17502fe279fdSBarry Smith    Output Parameter:
1751e3c11fc1SJed Brown .  C - transient (conservative) variable
1752e3c11fc1SJed Brown 
1753e3c11fc1SJed Brown    Level: developer
1754e3c11fc1SJed Brown 
1755bcf0153eSBarry Smith    Developer Note:
1756195e9b02SBarry Smith    If `DMTSSetTransientVariable()` has not been called, then C is not modified in this routine and C = `NULL` is allowed.
1757bcf0153eSBarry Smith    This makes it safe to call without a guard.  One can use `TSHasTransientVariable()` to check if transient variables are
1758bcf0153eSBarry Smith    being used.
1759bcf0153eSBarry Smith 
1760bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSBDF`, `DMTSSetTransientVariable()`, `TSComputeIFunction()`, `TSComputeIJacobian()`
1761e3c11fc1SJed Brown @*/
1762d71ae5a4SJacob Faibussowitsch PetscErrorCode TSComputeTransientVariable(TS ts, Vec U, Vec C)
1763d71ae5a4SJacob Faibussowitsch {
1764e3c11fc1SJed Brown   DM   dm;
1765e3c11fc1SJed Brown   DMTS dmts;
1766e3c11fc1SJed Brown 
1767e3c11fc1SJed Brown   PetscFunctionBegin;
1768e3c11fc1SJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
1769e3c11fc1SJed Brown   PetscValidHeaderSpecific(U, VEC_CLASSID, 2);
17709566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
17719566063dSJacob Faibussowitsch   PetscCall(DMGetDMTS(dm, &dmts));
1772e3c11fc1SJed Brown   if (dmts->ops->transientvar) {
1773e3c11fc1SJed Brown     PetscValidHeaderSpecific(C, VEC_CLASSID, 3);
17749566063dSJacob Faibussowitsch     PetscCall((*dmts->ops->transientvar)(ts, U, C, dmts->transientvarctx));
1775e3c11fc1SJed Brown   }
17763ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1777e3c11fc1SJed Brown }
1778e3c11fc1SJed Brown 
1779e3c11fc1SJed Brown /*@
1780e3c11fc1SJed Brown    TSHasTransientVariable - determine whether transient variables have been set
1781e3c11fc1SJed Brown 
1782e3c11fc1SJed Brown    Logically Collective
1783e3c11fc1SJed Brown 
17842fe279fdSBarry Smith    Input Parameter:
1785195e9b02SBarry Smith .  ts - `TS` on which to compute
1786e3c11fc1SJed Brown 
17872fe279fdSBarry Smith    Output Parameter:
1788bcf0153eSBarry Smith .  has - `PETSC_TRUE` if transient variables have been set
1789e3c11fc1SJed Brown 
1790e3c11fc1SJed Brown    Level: developer
1791e3c11fc1SJed Brown 
1792bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSBDF`, `DMTSSetTransientVariable()`, `TSComputeTransientVariable()`
1793e3c11fc1SJed Brown @*/
1794d71ae5a4SJacob Faibussowitsch PetscErrorCode TSHasTransientVariable(TS ts, PetscBool *has)
1795d71ae5a4SJacob Faibussowitsch {
1796e3c11fc1SJed Brown   DM   dm;
1797e3c11fc1SJed Brown   DMTS dmts;
1798e3c11fc1SJed Brown 
1799e3c11fc1SJed Brown   PetscFunctionBegin;
1800e3c11fc1SJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
18019566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
18029566063dSJacob Faibussowitsch   PetscCall(DMGetDMTS(dm, &dmts));
1803e3c11fc1SJed Brown   *has = dmts->ops->transientvar ? PETSC_TRUE : PETSC_FALSE;
18043ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1805e3c11fc1SJed Brown }
1806e3c11fc1SJed Brown 
1807e3c11fc1SJed Brown /*@
1808efe9872eSLisandro Dalcin    TS2SetSolution - Sets the initial solution and time derivative vectors
1809bcf0153eSBarry Smith    for use by the `TS` routines handling second order equations.
1810efe9872eSLisandro Dalcin 
1811c3339decSBarry Smith    Logically Collective
1812efe9872eSLisandro Dalcin 
1813efe9872eSLisandro Dalcin    Input Parameters:
1814bcf0153eSBarry Smith +  ts - the `TS` context obtained from `TSCreate()`
1815efe9872eSLisandro Dalcin .  u - the solution vector
1816efe9872eSLisandro Dalcin -  v - the time derivative vector
1817efe9872eSLisandro Dalcin 
1818efe9872eSLisandro Dalcin    Level: beginner
1819efe9872eSLisandro Dalcin 
1820bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`
1821efe9872eSLisandro Dalcin @*/
1822d71ae5a4SJacob Faibussowitsch PetscErrorCode TS2SetSolution(TS ts, Vec u, Vec v)
1823d71ae5a4SJacob Faibussowitsch {
1824efe9872eSLisandro Dalcin   PetscFunctionBegin;
1825efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
1826efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(u, VEC_CLASSID, 2);
1827efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(v, VEC_CLASSID, 3);
18289566063dSJacob Faibussowitsch   PetscCall(TSSetSolution(ts, u));
18299566063dSJacob Faibussowitsch   PetscCall(PetscObjectReference((PetscObject)v));
18309566063dSJacob Faibussowitsch   PetscCall(VecDestroy(&ts->vec_dot));
1831efe9872eSLisandro Dalcin   ts->vec_dot = v;
18323ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1833efe9872eSLisandro Dalcin }
1834efe9872eSLisandro Dalcin 
1835efe9872eSLisandro Dalcin /*@
1836efe9872eSLisandro Dalcin    TS2GetSolution - Returns the solution and time derivative at the present timestep
1837efe9872eSLisandro Dalcin    for second order equations. It is valid to call this routine inside the function
1838efe9872eSLisandro Dalcin    that you are evaluating in order to move to the new timestep. This vector not
1839efe9872eSLisandro Dalcin    changed until the solution at the next timestep has been calculated.
1840efe9872eSLisandro Dalcin 
1841195e9b02SBarry Smith    Not Collective, but `u` returned is parallel if `TS` is parallel
1842efe9872eSLisandro Dalcin 
1843efe9872eSLisandro Dalcin    Input Parameter:
1844bcf0153eSBarry Smith .  ts - the `TS` context obtained from `TSCreate()`
1845efe9872eSLisandro Dalcin 
1846d8d19677SJose E. Roman    Output Parameters:
1847efe9872eSLisandro Dalcin +  u - the vector containing the solution
1848efe9872eSLisandro Dalcin -  v - the vector containing the time derivative
1849efe9872eSLisandro Dalcin 
1850efe9872eSLisandro Dalcin    Level: intermediate
1851efe9872eSLisandro Dalcin 
1852bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TS2SetSolution()`, `TSGetTimeStep()`, `TSGetTime()`
1853efe9872eSLisandro Dalcin @*/
1854d71ae5a4SJacob Faibussowitsch PetscErrorCode TS2GetSolution(TS ts, Vec *u, Vec *v)
1855d71ae5a4SJacob Faibussowitsch {
1856efe9872eSLisandro Dalcin   PetscFunctionBegin;
1857efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
1858efe9872eSLisandro Dalcin   if (u) PetscValidPointer(u, 2);
1859efe9872eSLisandro Dalcin   if (v) PetscValidPointer(v, 3);
1860efe9872eSLisandro Dalcin   if (u) *u = ts->vec_sol;
1861efe9872eSLisandro Dalcin   if (v) *v = ts->vec_dot;
18623ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1863efe9872eSLisandro Dalcin }
1864efe9872eSLisandro Dalcin 
186555849f57SBarry Smith /*@C
1866bcf0153eSBarry Smith   TSLoad - Loads a `TS` that has been stored in binary  with `TSView()`.
186755849f57SBarry Smith 
1868c3339decSBarry Smith   Collective
186955849f57SBarry Smith 
187055849f57SBarry Smith   Input Parameters:
1871bcf0153eSBarry Smith + newdm - the newly loaded `TS`, this needs to have been created with `TSCreate()` or
1872bcf0153eSBarry Smith            some related function before a call to `TSLoad()`.
1873bcf0153eSBarry Smith - viewer - binary file viewer, obtained from `PetscViewerBinaryOpen()`
187455849f57SBarry Smith 
187555849f57SBarry Smith    Level: intermediate
187655849f57SBarry Smith 
1877bcf0153eSBarry Smith   Note:
1878bcf0153eSBarry Smith  The type is determined by the data in the file, any type set into the `TS` before this call is ignored.
187955849f57SBarry Smith 
1880bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `PetscViewer`, `PetscViewerBinaryOpen()`, `TSView()`, `MatLoad()`, `VecLoad()`
188155849f57SBarry Smith @*/
1882d71ae5a4SJacob Faibussowitsch PetscErrorCode TSLoad(TS ts, PetscViewer viewer)
1883d71ae5a4SJacob Faibussowitsch {
188455849f57SBarry Smith   PetscBool isbinary;
188555849f57SBarry Smith   PetscInt  classid;
188655849f57SBarry Smith   char      type[256];
18872d53ad75SBarry Smith   DMTS      sdm;
1888ad6bc421SBarry Smith   DM        dm;
188955849f57SBarry Smith 
189055849f57SBarry Smith   PetscFunctionBegin;
1891f2c2a1b9SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
189255849f57SBarry Smith   PetscValidHeaderSpecific(viewer, PETSC_VIEWER_CLASSID, 2);
18939566063dSJacob Faibussowitsch   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERBINARY, &isbinary));
18943c633725SBarry Smith   PetscCheck(isbinary, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Invalid viewer; open viewer with PetscViewerBinaryOpen()");
189555849f57SBarry Smith 
18969566063dSJacob Faibussowitsch   PetscCall(PetscViewerBinaryRead(viewer, &classid, 1, NULL, PETSC_INT));
18973c633725SBarry Smith   PetscCheck(classid == TS_FILE_CLASSID, PetscObjectComm((PetscObject)ts), PETSC_ERR_ARG_WRONG, "Not TS next in file");
18989566063dSJacob Faibussowitsch   PetscCall(PetscViewerBinaryRead(viewer, type, 256, NULL, PETSC_CHAR));
18999566063dSJacob Faibussowitsch   PetscCall(TSSetType(ts, type));
1900dbbe0bcdSBarry Smith   PetscTryTypeMethod(ts, load, viewer);
19019566063dSJacob Faibussowitsch   PetscCall(DMCreate(PetscObjectComm((PetscObject)ts), &dm));
19029566063dSJacob Faibussowitsch   PetscCall(DMLoad(dm, viewer));
19039566063dSJacob Faibussowitsch   PetscCall(TSSetDM(ts, dm));
19049566063dSJacob Faibussowitsch   PetscCall(DMCreateGlobalVector(ts->dm, &ts->vec_sol));
19059566063dSJacob Faibussowitsch   PetscCall(VecLoad(ts->vec_sol, viewer));
19069566063dSJacob Faibussowitsch   PetscCall(DMGetDMTS(ts->dm, &sdm));
19079566063dSJacob Faibussowitsch   PetscCall(DMTSLoad(sdm, viewer));
19083ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
190955849f57SBarry Smith }
191055849f57SBarry Smith 
19119804daf3SBarry Smith #include <petscdraw.h>
1912e04113cfSBarry Smith #if defined(PETSC_HAVE_SAWS)
1913e04113cfSBarry Smith   #include <petscviewersaws.h>
1914f05ece33SBarry Smith #endif
1915fe2efc57SMark 
1916fe2efc57SMark /*@C
1917bcf0153eSBarry Smith    TSViewFromOptions - View a `TS` based on values in the options database
1918fe2efc57SMark 
1919c3339decSBarry Smith    Collective
1920fe2efc57SMark 
1921fe2efc57SMark    Input Parameters:
1922bcf0153eSBarry Smith +  ts - the `TS` context
1923bcf0153eSBarry Smith .  obj - Optional object that provides the prefix for the options database keys
1924bcf0153eSBarry Smith -  name - command line option string to be passed by user
1925fe2efc57SMark 
1926fe2efc57SMark    Level: intermediate
1927bcf0153eSBarry Smith 
1928bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSView`, `PetscObjectViewFromOptions()`, `TSCreate()`
1929fe2efc57SMark @*/
1930bcf0153eSBarry Smith PetscErrorCode TSViewFromOptions(TS ts, PetscObject obj, const char name[])
1931d71ae5a4SJacob Faibussowitsch {
1932fe2efc57SMark   PetscFunctionBegin;
1933bcf0153eSBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
1934bcf0153eSBarry Smith   PetscCall(PetscObjectViewFromOptions((PetscObject)ts, obj, name));
19353ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1936fe2efc57SMark }
1937fe2efc57SMark 
19387e2c5f70SBarry Smith /*@C
1939bcf0153eSBarry Smith     TSView - Prints the `TS` data structure.
1940d763cef2SBarry Smith 
1941c3339decSBarry Smith     Collective
1942d763cef2SBarry Smith 
1943d763cef2SBarry Smith     Input Parameters:
1944bcf0153eSBarry Smith +   ts - the `TS` context obtained from `TSCreate()`
1945d763cef2SBarry Smith -   viewer - visualization context
1946d763cef2SBarry Smith 
1947d763cef2SBarry Smith     Options Database Key:
1948bcf0153eSBarry Smith .   -ts_view - calls `TSView()` at end of `TSStep()`
1949bcf0153eSBarry Smith 
1950bcf0153eSBarry Smith     Level: beginner
1951d763cef2SBarry Smith 
1952d763cef2SBarry Smith     Notes:
1953d763cef2SBarry Smith     The available visualization contexts include
1954bcf0153eSBarry Smith +     `PETSC_VIEWER_STDOUT_SELF` - standard output (default)
1955bcf0153eSBarry Smith -     `PETSC_VIEWER_STDOUT_WORLD` - synchronized standard
1956d763cef2SBarry Smith          output where only the first processor opens
1957d763cef2SBarry Smith          the file.  All other processors send their
1958d763cef2SBarry Smith          data to the first processor to print.
1959d763cef2SBarry Smith 
1960d763cef2SBarry Smith     The user can open an alternative visualization context with
1961bcf0153eSBarry Smith     `PetscViewerASCIIOpen()` - output to a specified file.
1962d763cef2SBarry Smith 
1963bcf0153eSBarry Smith     In the debugger you can do call `TSView`(ts,0) to display the `TS` solver. (The same holds for any PETSc object viewer).
1964595c91d4SBarry Smith 
1965bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `PetscViewer`, `PetscViewerASCIIOpen()`
1966d763cef2SBarry Smith @*/
1967d71ae5a4SJacob Faibussowitsch PetscErrorCode TSView(TS ts, PetscViewer viewer)
1968d71ae5a4SJacob Faibussowitsch {
196919fd82e9SBarry Smith   TSType    type;
19702b0a91c0SBarry Smith   PetscBool iascii, isstring, isundials, isbinary, isdraw;
19712d53ad75SBarry Smith   DMTS      sdm;
1972e04113cfSBarry Smith #if defined(PETSC_HAVE_SAWS)
1973536b137fSBarry Smith   PetscBool issaws;
1974f05ece33SBarry Smith #endif
1975d763cef2SBarry Smith 
1976d763cef2SBarry Smith   PetscFunctionBegin;
19770700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
19781e66621cSBarry Smith   if (!viewer) PetscCall(PetscViewerASCIIGetStdout(PetscObjectComm((PetscObject)ts), &viewer));
19790700a824SBarry Smith   PetscValidHeaderSpecific(viewer, PETSC_VIEWER_CLASSID, 2);
1980c9780b6fSBarry Smith   PetscCheckSameComm(ts, 1, viewer, 2);
1981fd16b177SBarry Smith 
19829566063dSJacob Faibussowitsch   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERASCII, &iascii));
19839566063dSJacob Faibussowitsch   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERSTRING, &isstring));
19849566063dSJacob Faibussowitsch   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERBINARY, &isbinary));
19859566063dSJacob Faibussowitsch   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERDRAW, &isdraw));
1986e04113cfSBarry Smith #if defined(PETSC_HAVE_SAWS)
19879566063dSJacob Faibussowitsch   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERSAWS, &issaws));
1988f05ece33SBarry Smith #endif
198932077d6dSBarry Smith   if (iascii) {
19909566063dSJacob Faibussowitsch     PetscCall(PetscObjectPrintClassNamePrefixType((PetscObject)ts, viewer));
1991efd4aadfSBarry Smith     if (ts->ops->view) {
19929566063dSJacob Faibussowitsch       PetscCall(PetscViewerASCIIPushTab(viewer));
1993dbbe0bcdSBarry Smith       PetscUseTypeMethod(ts, view, viewer);
19949566063dSJacob Faibussowitsch       PetscCall(PetscViewerASCIIPopTab(viewer));
1995efd4aadfSBarry Smith     }
19961e66621cSBarry Smith     if (ts->max_steps < PETSC_MAX_INT) PetscCall(PetscViewerASCIIPrintf(viewer, "  maximum steps=%" PetscInt_FMT "\n", ts->max_steps));
19971e66621cSBarry Smith     if (ts->max_time < PETSC_MAX_REAL) PetscCall(PetscViewerASCIIPrintf(viewer, "  maximum time=%g\n", (double)ts->max_time));
19981e66621cSBarry Smith     if (ts->ifuncs) PetscCall(PetscViewerASCIIPrintf(viewer, "  total number of I function evaluations=%" PetscInt_FMT "\n", ts->ifuncs));
19991e66621cSBarry Smith     if (ts->ijacs) PetscCall(PetscViewerASCIIPrintf(viewer, "  total number of I Jacobian evaluations=%" PetscInt_FMT "\n", ts->ijacs));
20001e66621cSBarry Smith     if (ts->rhsfuncs) PetscCall(PetscViewerASCIIPrintf(viewer, "  total number of RHS function evaluations=%" PetscInt_FMT "\n", ts->rhsfuncs));
20011e66621cSBarry Smith     if (ts->rhsjacs) PetscCall(PetscViewerASCIIPrintf(viewer, "  total number of RHS Jacobian evaluations=%" PetscInt_FMT "\n", ts->rhsjacs));
2002efd4aadfSBarry Smith     if (ts->usessnes) {
2003efd4aadfSBarry Smith       PetscBool lin;
20041e66621cSBarry Smith       if (ts->problem_type == TS_NONLINEAR) PetscCall(PetscViewerASCIIPrintf(viewer, "  total number of nonlinear solver iterations=%" PetscInt_FMT "\n", ts->snes_its));
200563a3b9bcSJacob Faibussowitsch       PetscCall(PetscViewerASCIIPrintf(viewer, "  total number of linear solver iterations=%" PetscInt_FMT "\n", ts->ksp_its));
20069566063dSJacob Faibussowitsch       PetscCall(PetscObjectTypeCompareAny((PetscObject)ts->snes, &lin, SNESKSPONLY, SNESKSPTRANSPOSEONLY, ""));
200763a3b9bcSJacob Faibussowitsch       PetscCall(PetscViewerASCIIPrintf(viewer, "  total number of %slinear solve failures=%" PetscInt_FMT "\n", lin ? "" : "non", ts->num_snes_failures));
2008efd4aadfSBarry Smith     }
200963a3b9bcSJacob Faibussowitsch     PetscCall(PetscViewerASCIIPrintf(viewer, "  total number of rejected steps=%" PetscInt_FMT "\n", ts->reject));
20101e66621cSBarry Smith     if (ts->vrtol) PetscCall(PetscViewerASCIIPrintf(viewer, "  using vector of relative error tolerances, "));
20111e66621cSBarry Smith     else PetscCall(PetscViewerASCIIPrintf(viewer, "  using relative error tolerance of %g, ", (double)ts->rtol));
20121e66621cSBarry Smith     if (ts->vatol) PetscCall(PetscViewerASCIIPrintf(viewer, "  using vector of absolute error tolerances\n"));
20131e66621cSBarry Smith     else PetscCall(PetscViewerASCIIPrintf(viewer, "  using absolute error tolerance of %g\n", (double)ts->atol));
20149566063dSJacob Faibussowitsch     PetscCall(PetscViewerASCIIPushTab(viewer));
20159566063dSJacob Faibussowitsch     PetscCall(TSAdaptView(ts->adapt, viewer));
20169566063dSJacob Faibussowitsch     PetscCall(PetscViewerASCIIPopTab(viewer));
20170f5bd95cSBarry Smith   } else if (isstring) {
20189566063dSJacob Faibussowitsch     PetscCall(TSGetType(ts, &type));
20199566063dSJacob Faibussowitsch     PetscCall(PetscViewerStringSPrintf(viewer, " TSType: %-7.7s", type));
2020dbbe0bcdSBarry Smith     PetscTryTypeMethod(ts, view, viewer);
202155849f57SBarry Smith   } else if (isbinary) {
202255849f57SBarry Smith     PetscInt    classid = TS_FILE_CLASSID;
202355849f57SBarry Smith     MPI_Comm    comm;
202455849f57SBarry Smith     PetscMPIInt rank;
202555849f57SBarry Smith     char        type[256];
202655849f57SBarry Smith 
20279566063dSJacob Faibussowitsch     PetscCall(PetscObjectGetComm((PetscObject)ts, &comm));
20289566063dSJacob Faibussowitsch     PetscCallMPI(MPI_Comm_rank(comm, &rank));
2029dd400576SPatrick Sanan     if (rank == 0) {
20309566063dSJacob Faibussowitsch       PetscCall(PetscViewerBinaryWrite(viewer, &classid, 1, PETSC_INT));
20319566063dSJacob Faibussowitsch       PetscCall(PetscStrncpy(type, ((PetscObject)ts)->type_name, 256));
20329566063dSJacob Faibussowitsch       PetscCall(PetscViewerBinaryWrite(viewer, type, 256, PETSC_CHAR));
203355849f57SBarry Smith     }
2034dbbe0bcdSBarry Smith     PetscTryTypeMethod(ts, view, viewer);
20359566063dSJacob Faibussowitsch     if (ts->adapt) PetscCall(TSAdaptView(ts->adapt, viewer));
20369566063dSJacob Faibussowitsch     PetscCall(DMView(ts->dm, viewer));
20379566063dSJacob Faibussowitsch     PetscCall(VecView(ts->vec_sol, viewer));
20389566063dSJacob Faibussowitsch     PetscCall(DMGetDMTS(ts->dm, &sdm));
20399566063dSJacob Faibussowitsch     PetscCall(DMTSView(sdm, viewer));
20402b0a91c0SBarry Smith   } else if (isdraw) {
20412b0a91c0SBarry Smith     PetscDraw draw;
20422b0a91c0SBarry Smith     char      str[36];
204389fd9fafSBarry Smith     PetscReal x, y, bottom, h;
20442b0a91c0SBarry Smith 
20459566063dSJacob Faibussowitsch     PetscCall(PetscViewerDrawGetDraw(viewer, 0, &draw));
20469566063dSJacob Faibussowitsch     PetscCall(PetscDrawGetCurrentPoint(draw, &x, &y));
2047c6a7a370SJeremy L Thompson     PetscCall(PetscStrncpy(str, "TS: ", sizeof(str)));
2048c6a7a370SJeremy L Thompson     PetscCall(PetscStrlcat(str, ((PetscObject)ts)->type_name, sizeof(str)));
20499566063dSJacob Faibussowitsch     PetscCall(PetscDrawStringBoxed(draw, x, y, PETSC_DRAW_BLACK, PETSC_DRAW_BLACK, str, NULL, &h));
205089fd9fafSBarry Smith     bottom = y - h;
20519566063dSJacob Faibussowitsch     PetscCall(PetscDrawPushCurrentPoint(draw, x, bottom));
2052dbbe0bcdSBarry Smith     PetscTryTypeMethod(ts, view, viewer);
20539566063dSJacob Faibussowitsch     if (ts->adapt) PetscCall(TSAdaptView(ts->adapt, viewer));
20549566063dSJacob Faibussowitsch     if (ts->snes) PetscCall(SNESView(ts->snes, viewer));
20559566063dSJacob Faibussowitsch     PetscCall(PetscDrawPopCurrentPoint(draw));
2056e04113cfSBarry Smith #if defined(PETSC_HAVE_SAWS)
2057536b137fSBarry Smith   } else if (issaws) {
2058d45a07a7SBarry Smith     PetscMPIInt rank;
20592657e9d9SBarry Smith     const char *name;
20602657e9d9SBarry Smith 
20619566063dSJacob Faibussowitsch     PetscCall(PetscObjectGetName((PetscObject)ts, &name));
20629566063dSJacob Faibussowitsch     PetscCallMPI(MPI_Comm_rank(PETSC_COMM_WORLD, &rank));
2063dd400576SPatrick Sanan     if (!((PetscObject)ts)->amsmem && rank == 0) {
2064d45a07a7SBarry Smith       char dir[1024];
2065d45a07a7SBarry Smith 
20669566063dSJacob Faibussowitsch       PetscCall(PetscObjectViewSAWs((PetscObject)ts, viewer));
20679566063dSJacob Faibussowitsch       PetscCall(PetscSNPrintf(dir, 1024, "/PETSc/Objects/%s/time_step", name));
2068792fecdfSBarry Smith       PetscCallSAWs(SAWs_Register, (dir, &ts->steps, 1, SAWs_READ, SAWs_INT));
20699566063dSJacob Faibussowitsch       PetscCall(PetscSNPrintf(dir, 1024, "/PETSc/Objects/%s/time", name));
2070792fecdfSBarry Smith       PetscCallSAWs(SAWs_Register, (dir, &ts->ptime, 1, SAWs_READ, SAWs_DOUBLE));
2071d763cef2SBarry Smith     }
2072dbbe0bcdSBarry Smith     PetscTryTypeMethod(ts, view, viewer);
2073f05ece33SBarry Smith #endif
2074f05ece33SBarry Smith   }
207536a9e3b9SBarry Smith   if (ts->snes && ts->usessnes) {
20769566063dSJacob Faibussowitsch     PetscCall(PetscViewerASCIIPushTab(viewer));
20779566063dSJacob Faibussowitsch     PetscCall(SNESView(ts->snes, viewer));
20789566063dSJacob Faibussowitsch     PetscCall(PetscViewerASCIIPopTab(viewer));
207936a9e3b9SBarry Smith   }
20809566063dSJacob Faibussowitsch   PetscCall(DMGetDMTS(ts->dm, &sdm));
20819566063dSJacob Faibussowitsch   PetscCall(DMTSView(sdm, viewer));
2082f05ece33SBarry Smith 
20839566063dSJacob Faibussowitsch   PetscCall(PetscViewerASCIIPushTab(viewer));
20849566063dSJacob Faibussowitsch   PetscCall(PetscObjectTypeCompare((PetscObject)ts, TSSUNDIALS, &isundials));
20859566063dSJacob Faibussowitsch   PetscCall(PetscViewerASCIIPopTab(viewer));
20863ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2087d763cef2SBarry Smith }
2088d763cef2SBarry Smith 
2089b07ff414SBarry Smith /*@
2090d763cef2SBarry Smith    TSSetApplicationContext - Sets an optional user-defined context for
2091d763cef2SBarry Smith    the timesteppers.
2092d763cef2SBarry Smith 
2093c3339decSBarry Smith    Logically Collective
2094d763cef2SBarry Smith 
2095d763cef2SBarry Smith    Input Parameters:
2096bcf0153eSBarry Smith +  ts - the `TS` context obtained from `TSCreate()`
2097bcf0153eSBarry Smith -  usrP -  user context
2098daf670e6SBarry Smith 
2099d763cef2SBarry Smith    Level: intermediate
2100d763cef2SBarry Smith 
2101bcf0153eSBarry Smith    Fortran Note:
2102195e9b02SBarry Smith     You must write a Fortran interface definition for this
2103195e9b02SBarry Smith     function that tells Fortran the Fortran derived data type that you are passing in as the `ctx` argument.
2104bcf0153eSBarry Smith 
2105bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSGetApplicationContext()`
2106d763cef2SBarry Smith @*/
2107d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetApplicationContext(TS ts, void *usrP)
2108d71ae5a4SJacob Faibussowitsch {
2109d763cef2SBarry Smith   PetscFunctionBegin;
21100700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
2111d763cef2SBarry Smith   ts->user = usrP;
21123ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2113d763cef2SBarry Smith }
2114d763cef2SBarry Smith 
2115b07ff414SBarry Smith /*@
2116d763cef2SBarry Smith     TSGetApplicationContext - Gets the user-defined context for the
2117bcf0153eSBarry Smith     timestepper that was set with `TSSetApplicationContext()`
2118d763cef2SBarry Smith 
2119d763cef2SBarry Smith     Not Collective
2120d763cef2SBarry Smith 
2121d763cef2SBarry Smith     Input Parameter:
2122bcf0153eSBarry Smith .   ts - the `TS` context obtained from `TSCreate()`
2123d763cef2SBarry Smith 
2124d763cef2SBarry Smith     Output Parameter:
2125d763cef2SBarry Smith .   usrP - user context
2126d763cef2SBarry Smith 
2127bcf0153eSBarry Smith     Level: intermediate
2128bcf0153eSBarry Smith 
2129bcf0153eSBarry Smith     Fortran Note:
2130195e9b02SBarry Smith     You must write a Fortran interface definition for this
2131195e9b02SBarry Smith     function that tells Fortran the Fortran derived data type that you are passing in as the `ctx` argument.
2132daf670e6SBarry Smith 
2133bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSSetApplicationContext()`
2134d763cef2SBarry Smith @*/
2135d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetApplicationContext(TS ts, void *usrP)
2136d71ae5a4SJacob Faibussowitsch {
2137d763cef2SBarry Smith   PetscFunctionBegin;
21380700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
2139e71120c6SJed Brown   *(void **)usrP = ts->user;
21403ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2141d763cef2SBarry Smith }
2142d763cef2SBarry Smith 
2143d763cef2SBarry Smith /*@
2144bcf0153eSBarry Smith    TSGetStepNumber - Gets the number of time steps completed.
2145d763cef2SBarry Smith 
2146d763cef2SBarry Smith    Not Collective
2147d763cef2SBarry Smith 
2148d763cef2SBarry Smith    Input Parameter:
2149bcf0153eSBarry Smith .  ts - the `TS` context obtained from `TSCreate()`
2150d763cef2SBarry Smith 
2151d763cef2SBarry Smith    Output Parameter:
215280275a0aSLisandro Dalcin .  steps - number of steps completed so far
2153d763cef2SBarry Smith 
2154d763cef2SBarry Smith    Level: intermediate
2155d763cef2SBarry Smith 
2156bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSGetTime()`, `TSGetTimeStep()`, `TSSetPreStep()`, `TSSetPreStage()`, `TSSetPostStage()`, `TSSetPostStep()`
2157d763cef2SBarry Smith @*/
2158d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetStepNumber(TS ts, PetscInt *steps)
2159d71ae5a4SJacob Faibussowitsch {
2160d763cef2SBarry Smith   PetscFunctionBegin;
21610700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
216280275a0aSLisandro Dalcin   PetscValidIntPointer(steps, 2);
216380275a0aSLisandro Dalcin   *steps = ts->steps;
21643ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
216580275a0aSLisandro Dalcin }
216680275a0aSLisandro Dalcin 
216780275a0aSLisandro Dalcin /*@
216880275a0aSLisandro Dalcin    TSSetStepNumber - Sets the number of steps completed.
216980275a0aSLisandro Dalcin 
2170c3339decSBarry Smith    Logically Collective
217180275a0aSLisandro Dalcin 
217280275a0aSLisandro Dalcin    Input Parameters:
2173bcf0153eSBarry Smith +  ts - the `TS` context
217480275a0aSLisandro Dalcin -  steps - number of steps completed so far
217580275a0aSLisandro Dalcin 
2176bcf0153eSBarry Smith    Level: developer
2177bcf0153eSBarry Smith 
2178bcf0153eSBarry Smith    Note:
2179bcf0153eSBarry Smith    For most uses of the `TS` solvers the user need not explicitly call
2180bcf0153eSBarry Smith    `TSSetStepNumber()`, as the step counter is appropriately updated in
2181bcf0153eSBarry Smith    `TSSolve()`/`TSStep()`/`TSRollBack()`. Power users may call this routine to
218280275a0aSLisandro Dalcin    reinitialize timestepping by setting the step counter to zero (and time
218380275a0aSLisandro Dalcin    to the initial time) to solve a similar problem with different initial
218480275a0aSLisandro Dalcin    conditions or parameters. Other possible use case is to continue
2185195e9b02SBarry Smith    timestepping from a previously interrupted run in such a way that `TS`
218680275a0aSLisandro Dalcin    monitors will be called with a initial nonzero step counter.
218780275a0aSLisandro Dalcin 
2188bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSGetStepNumber()`, `TSSetTime()`, `TSSetTimeStep()`, `TSSetSolution()`
218980275a0aSLisandro Dalcin @*/
2190d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetStepNumber(TS ts, PetscInt steps)
2191d71ae5a4SJacob Faibussowitsch {
219280275a0aSLisandro Dalcin   PetscFunctionBegin;
219380275a0aSLisandro Dalcin   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
219480275a0aSLisandro Dalcin   PetscValidLogicalCollectiveInt(ts, steps, 2);
21953c633725SBarry Smith   PetscCheck(steps >= 0, PetscObjectComm((PetscObject)ts), PETSC_ERR_ARG_OUTOFRANGE, "Step number must be non-negative");
219680275a0aSLisandro Dalcin   ts->steps = steps;
21973ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2198d763cef2SBarry Smith }
2199d763cef2SBarry Smith 
2200d763cef2SBarry Smith /*@
2201d763cef2SBarry Smith    TSSetTimeStep - Allows one to reset the timestep at any time,
2202d763cef2SBarry Smith    useful for simple pseudo-timestepping codes.
2203d763cef2SBarry Smith 
2204c3339decSBarry Smith    Logically Collective
2205d763cef2SBarry Smith 
2206d763cef2SBarry Smith    Input Parameters:
2207bcf0153eSBarry Smith +  ts - the `TS` context obtained from `TSCreate()`
2208d763cef2SBarry Smith -  time_step - the size of the timestep
2209d763cef2SBarry Smith 
2210d763cef2SBarry Smith    Level: intermediate
2211d763cef2SBarry Smith 
2212bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSPSEUDO`, `TSGetTimeStep()`, `TSSetTime()`
2213d763cef2SBarry Smith @*/
2214d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetTimeStep(TS ts, PetscReal time_step)
2215d71ae5a4SJacob Faibussowitsch {
2216d763cef2SBarry Smith   PetscFunctionBegin;
22170700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
2218c5eb9154SBarry Smith   PetscValidLogicalCollectiveReal(ts, time_step, 2);
2219d763cef2SBarry Smith   ts->time_step = time_step;
22203ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2221d763cef2SBarry Smith }
2222d763cef2SBarry Smith 
2223a43b19c4SJed Brown /*@
222449354f04SShri Abhyankar    TSSetExactFinalTime - Determines whether to adapt the final time step to
222549354f04SShri Abhyankar      match the exact final time, interpolate solution to the exact final time,
2226bcf0153eSBarry Smith      or just return at the final time `TS` computed.
2227a43b19c4SJed Brown 
2228c3339decSBarry Smith   Logically Collective
2229a43b19c4SJed Brown 
2230d8d19677SJose E. Roman    Input Parameters:
2231a43b19c4SJed Brown +   ts - the time-step context
223249354f04SShri Abhyankar -   eftopt - exact final time option
2233bcf0153eSBarry Smith .vb
2234bcf0153eSBarry Smith   TS_EXACTFINALTIME_STEPOVER    - Don't do anything if final time is exceeded
2235bcf0153eSBarry Smith   TS_EXACTFINALTIME_INTERPOLATE - Interpolate back to final time
2236bcf0153eSBarry Smith   TS_EXACTFINALTIME_MATCHSTEP - Adapt final time step to match the final time
2237bcf0153eSBarry Smith .ve
2238a43b19c4SJed Brown 
2239bcf0153eSBarry Smith    Options Database Key:
2240feed9e9dSBarry Smith .   -ts_exact_final_time <stepover,interpolate,matchstep> - select the final step at runtime
2241feed9e9dSBarry Smith 
2242a43b19c4SJed Brown    Level: beginner
2243a43b19c4SJed Brown 
2244bcf0153eSBarry Smith    Note:
2245bcf0153eSBarry Smith    If you use the option `TS_EXACTFINALTIME_STEPOVER` the solution may be at a very different time
2246bcf0153eSBarry Smith    then the final time you selected.
2247bcf0153eSBarry Smith 
2248bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSExactFinalTimeOption`, `TSGetExactFinalTime()`
2249a43b19c4SJed Brown @*/
2250d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetExactFinalTime(TS ts, TSExactFinalTimeOption eftopt)
2251d71ae5a4SJacob Faibussowitsch {
2252a43b19c4SJed Brown   PetscFunctionBegin;
2253a43b19c4SJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
225449354f04SShri Abhyankar   PetscValidLogicalCollectiveEnum(ts, eftopt, 2);
225549354f04SShri Abhyankar   ts->exact_final_time = eftopt;
22563ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2257a43b19c4SJed Brown }
2258a43b19c4SJed Brown 
2259d763cef2SBarry Smith /*@
2260bcf0153eSBarry Smith    TSGetExactFinalTime - Gets the exact final time option set with `TSSetExactFinalTime()`
2261f6953c82SLisandro Dalcin 
2262f6953c82SLisandro Dalcin    Not Collective
2263f6953c82SLisandro Dalcin 
2264f6953c82SLisandro Dalcin    Input Parameter:
2265bcf0153eSBarry Smith .  ts - the `TS` context
2266f6953c82SLisandro Dalcin 
2267f6953c82SLisandro Dalcin    Output Parameter:
2268f6953c82SLisandro Dalcin .  eftopt - exact final time option
2269f6953c82SLisandro Dalcin 
2270f6953c82SLisandro Dalcin    Level: beginner
2271f6953c82SLisandro Dalcin 
2272bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSExactFinalTimeOption`, `TSSetExactFinalTime()`
2273f6953c82SLisandro Dalcin @*/
2274d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetExactFinalTime(TS ts, TSExactFinalTimeOption *eftopt)
2275d71ae5a4SJacob Faibussowitsch {
2276f6953c82SLisandro Dalcin   PetscFunctionBegin;
2277f6953c82SLisandro Dalcin   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
2278f6953c82SLisandro Dalcin   PetscValidPointer(eftopt, 2);
2279f6953c82SLisandro Dalcin   *eftopt = ts->exact_final_time;
22803ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2281f6953c82SLisandro Dalcin }
2282f6953c82SLisandro Dalcin 
2283f6953c82SLisandro Dalcin /*@
2284d763cef2SBarry Smith    TSGetTimeStep - Gets the current timestep size.
2285d763cef2SBarry Smith 
2286d763cef2SBarry Smith    Not Collective
2287d763cef2SBarry Smith 
2288d763cef2SBarry Smith    Input Parameter:
2289bcf0153eSBarry Smith .  ts - the `TS` context obtained from `TSCreate()`
2290d763cef2SBarry Smith 
2291d763cef2SBarry Smith    Output Parameter:
2292d763cef2SBarry Smith .  dt - the current timestep size
2293d763cef2SBarry Smith 
2294d763cef2SBarry Smith    Level: intermediate
2295d763cef2SBarry Smith 
2296bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSSetTimeStep()`, `TSGetTime()`
2297d763cef2SBarry Smith @*/
2298d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetTimeStep(TS ts, PetscReal *dt)
2299d71ae5a4SJacob Faibussowitsch {
2300d763cef2SBarry Smith   PetscFunctionBegin;
23010700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
2302f7cf8827SBarry Smith   PetscValidRealPointer(dt, 2);
2303d763cef2SBarry Smith   *dt = ts->time_step;
23043ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2305d763cef2SBarry Smith }
2306d763cef2SBarry Smith 
2307d8e5e3e6SSatish Balay /*@
2308d763cef2SBarry Smith    TSGetSolution - Returns the solution at the present timestep. It
2309d763cef2SBarry Smith    is valid to call this routine inside the function that you are evaluating
2310d763cef2SBarry Smith    in order to move to the new timestep. This vector not changed until
2311d763cef2SBarry Smith    the solution at the next timestep has been calculated.
2312d763cef2SBarry Smith 
2313bcf0153eSBarry Smith    Not Collective, but v returned is parallel if ts is parallel
2314d763cef2SBarry Smith 
2315d763cef2SBarry Smith    Input Parameter:
2316bcf0153eSBarry Smith .  ts - the `TS` context obtained from `TSCreate()`
2317d763cef2SBarry Smith 
2318d763cef2SBarry Smith    Output Parameter:
2319d763cef2SBarry Smith .  v - the vector containing the solution
2320d763cef2SBarry Smith 
2321d763cef2SBarry Smith    Level: intermediate
2322d763cef2SBarry Smith 
2323bcf0153eSBarry Smith    Note:
2324bcf0153eSBarry Smith    If you used `TSSetExactFinalTime`(ts,`TS_EXACTFINALTIME_MATCHSTEP`); this does not return the solution at the requested
2325bcf0153eSBarry Smith    final time. It returns the solution at the next timestep.
2326d763cef2SBarry Smith 
2327bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSGetTimeStep()`, `TSGetTime()`, `TSGetSolveTime()`, `TSGetSolutionComponents()`, `TSSetSolutionFunction()`
2328d763cef2SBarry Smith @*/
2329d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetSolution(TS ts, Vec *v)
2330d71ae5a4SJacob Faibussowitsch {
2331d763cef2SBarry Smith   PetscFunctionBegin;
23320700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
23334482741eSBarry Smith   PetscValidPointer(v, 2);
23348737fe31SLisandro Dalcin   *v = ts->vec_sol;
23353ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2336d763cef2SBarry Smith }
2337d763cef2SBarry Smith 
233803fe5f5eSDebojyoti Ghosh /*@
2339b2bf4f3aSDebojyoti Ghosh    TSGetSolutionComponents - Returns any solution components at the present
234003fe5f5eSDebojyoti Ghosh    timestep, if available for the time integration method being used.
2341b2bf4f3aSDebojyoti Ghosh    Solution components are quantities that share the same size and
234203fe5f5eSDebojyoti Ghosh    structure as the solution vector.
234303fe5f5eSDebojyoti Ghosh 
2344bcf0153eSBarry Smith    Not Collective, but v returned is parallel if ts is parallel
234503fe5f5eSDebojyoti Ghosh 
234603fe5f5eSDebojyoti Ghosh    Parameters :
2347bcf0153eSBarry Smith +  ts - the `TS` context obtained from `TSCreate()` (input parameter).
2348195e9b02SBarry Smith .  n - If v is `NULL`, then the number of solution components is
2349b2bf4f3aSDebojyoti Ghosh        returned through n, else the n-th solution component is
235003fe5f5eSDebojyoti Ghosh        returned in v.
2351a2b725a8SWilliam Gropp -  v - the vector containing the n-th solution component
2352195e9b02SBarry Smith        (may be `NULL` to use this function to find out
2353b2bf4f3aSDebojyoti Ghosh         the number of solutions components).
235403fe5f5eSDebojyoti Ghosh 
23554cdd57e5SDebojyoti Ghosh    Level: advanced
235603fe5f5eSDebojyoti Ghosh 
2357bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSGetSolution()`
235803fe5f5eSDebojyoti Ghosh @*/
2359d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetSolutionComponents(TS ts, PetscInt *n, Vec *v)
2360d71ae5a4SJacob Faibussowitsch {
236103fe5f5eSDebojyoti Ghosh   PetscFunctionBegin;
236203fe5f5eSDebojyoti Ghosh   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
2363b2bf4f3aSDebojyoti Ghosh   if (!ts->ops->getsolutioncomponents) *n = 0;
2364dbbe0bcdSBarry Smith   else PetscUseTypeMethod(ts, getsolutioncomponents, n, v);
23653ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
236603fe5f5eSDebojyoti Ghosh }
236703fe5f5eSDebojyoti Ghosh 
23684cdd57e5SDebojyoti Ghosh /*@
23694cdd57e5SDebojyoti Ghosh    TSGetAuxSolution - Returns an auxiliary solution at the present
23704cdd57e5SDebojyoti Ghosh    timestep, if available for the time integration method being used.
23714cdd57e5SDebojyoti Ghosh 
2372bcf0153eSBarry Smith    Not Collective, but v returned is parallel if ts is parallel
23734cdd57e5SDebojyoti Ghosh 
23744cdd57e5SDebojyoti Ghosh    Parameters :
2375bcf0153eSBarry Smith +  ts - the `TS` context obtained from `TSCreate()` (input parameter).
2376a2b725a8SWilliam Gropp -  v - the vector containing the auxiliary solution
23774cdd57e5SDebojyoti Ghosh 
23784cdd57e5SDebojyoti Ghosh    Level: intermediate
23794cdd57e5SDebojyoti Ghosh 
2380bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSGetSolution()`
23814cdd57e5SDebojyoti Ghosh @*/
2382d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetAuxSolution(TS ts, Vec *v)
2383d71ae5a4SJacob Faibussowitsch {
23844cdd57e5SDebojyoti Ghosh   PetscFunctionBegin;
23854cdd57e5SDebojyoti Ghosh   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
2386dbbe0bcdSBarry Smith   if (ts->ops->getauxsolution) PetscUseTypeMethod(ts, getauxsolution, v);
23871e66621cSBarry Smith   else PetscCall(VecZeroEntries(*v));
23883ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
23894cdd57e5SDebojyoti Ghosh }
23904cdd57e5SDebojyoti Ghosh 
23914cdd57e5SDebojyoti Ghosh /*@
23924cdd57e5SDebojyoti Ghosh    TSGetTimeError - Returns the estimated error vector, if the chosen
2393bcf0153eSBarry Smith    `TSType` has an error estimation functionality and `TSSetTimeError()` was called
23944cdd57e5SDebojyoti Ghosh 
2395bcf0153eSBarry Smith    Not Collective, but v returned is parallel if ts is parallel
23969657682dSDebojyoti Ghosh 
23974cdd57e5SDebojyoti Ghosh    Parameters :
2398bcf0153eSBarry Smith +  ts - the `TS` context obtained from `TSCreate()` (input parameter).
2399657c1e31SEmil Constantinescu .  n - current estimate (n=0) or previous one (n=-1)
2400a2b725a8SWilliam Gropp -  v - the vector containing the error (same size as the solution).
24014cdd57e5SDebojyoti Ghosh 
24024cdd57e5SDebojyoti Ghosh    Level: intermediate
24034cdd57e5SDebojyoti Ghosh 
2404bcf0153eSBarry Smith    Note:
2405bcf0153eSBarry Smith    MUST call after `TSSetUp()`
24064cdd57e5SDebojyoti Ghosh 
2407bcf0153eSBarry Smith .seealso: [](chapter_ts), `TSGetSolution()`, `TSSetTimeError()`
24084cdd57e5SDebojyoti Ghosh @*/
2409d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetTimeError(TS ts, PetscInt n, Vec *v)
2410d71ae5a4SJacob Faibussowitsch {
24114cdd57e5SDebojyoti Ghosh   PetscFunctionBegin;
24124cdd57e5SDebojyoti Ghosh   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
2413dbbe0bcdSBarry Smith   if (ts->ops->gettimeerror) PetscUseTypeMethod(ts, gettimeerror, n, v);
24141e66621cSBarry Smith   else PetscCall(VecZeroEntries(*v));
24153ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
24164cdd57e5SDebojyoti Ghosh }
24174cdd57e5SDebojyoti Ghosh 
241857df6a1bSDebojyoti Ghosh /*@
241957df6a1bSDebojyoti Ghosh    TSSetTimeError - Sets the estimated error vector, if the chosen
2420bcf0153eSBarry Smith    `TSType` has an error estimation functionality. This can be used
242157df6a1bSDebojyoti Ghosh    to restart such a time integrator with a given error vector.
242257df6a1bSDebojyoti Ghosh 
2423bcf0153eSBarry Smith    Not Collective, but v returned is parallel if ts is parallel
242457df6a1bSDebojyoti Ghosh 
242557df6a1bSDebojyoti Ghosh    Parameters :
2426bcf0153eSBarry Smith +  ts - the `TS` context obtained from `TSCreate()` (input parameter).
2427a2b725a8SWilliam Gropp -  v - the vector containing the error (same size as the solution).
242857df6a1bSDebojyoti Ghosh 
242957df6a1bSDebojyoti Ghosh    Level: intermediate
243057df6a1bSDebojyoti Ghosh 
2431bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSSetSolution()`, `TSGetTimeError)`
243257df6a1bSDebojyoti Ghosh @*/
2433d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetTimeError(TS ts, Vec v)
2434d71ae5a4SJacob Faibussowitsch {
243557df6a1bSDebojyoti Ghosh   PetscFunctionBegin;
243657df6a1bSDebojyoti Ghosh   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
24373c633725SBarry Smith   PetscCheck(ts->setupcalled, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Must call TSSetUp() first");
2438dbbe0bcdSBarry Smith   PetscTryTypeMethod(ts, settimeerror, v);
24393ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
244057df6a1bSDebojyoti Ghosh }
244157df6a1bSDebojyoti Ghosh 
2442bdad233fSMatthew Knepley /* ----- Routines to initialize and destroy a timestepper ---- */
2443d8e5e3e6SSatish Balay /*@
2444bdad233fSMatthew Knepley   TSSetProblemType - Sets the type of problem to be solved.
2445d763cef2SBarry Smith 
2446bdad233fSMatthew Knepley   Not collective
2447d763cef2SBarry Smith 
2448bdad233fSMatthew Knepley   Input Parameters:
2449bcf0153eSBarry Smith + ts   - The `TS`
2450bcf0153eSBarry Smith - type - One of `TS_LINEAR`, `TS_NONLINEAR` where these types refer to problems of the forms
2451d763cef2SBarry Smith .vb
24520910c330SBarry Smith          U_t - A U = 0      (linear)
24530910c330SBarry Smith          U_t - A(t) U = 0   (linear)
24540910c330SBarry Smith          F(t,U,U_t) = 0     (nonlinear)
2455d763cef2SBarry Smith .ve
2456d763cef2SBarry Smith 
2457d763cef2SBarry Smith    Level: beginner
2458d763cef2SBarry Smith 
2459bcf0153eSBarry Smith .seealso: [](chapter_ts), `TSSetUp()`, `TSProblemType`, `TS`
2460d763cef2SBarry Smith @*/
2461d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetProblemType(TS ts, TSProblemType type)
2462d71ae5a4SJacob Faibussowitsch {
2463d763cef2SBarry Smith   PetscFunctionBegin;
24640700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
2465bdad233fSMatthew Knepley   ts->problem_type = type;
24669e2a6581SJed Brown   if (type == TS_LINEAR) {
24679e2a6581SJed Brown     SNES snes;
24689566063dSJacob Faibussowitsch     PetscCall(TSGetSNES(ts, &snes));
24699566063dSJacob Faibussowitsch     PetscCall(SNESSetType(snes, SNESKSPONLY));
24709e2a6581SJed Brown   }
24713ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2472d763cef2SBarry Smith }
2473d763cef2SBarry Smith 
2474bdad233fSMatthew Knepley /*@C
2475bdad233fSMatthew Knepley   TSGetProblemType - Gets the type of problem to be solved.
2476bdad233fSMatthew Knepley 
2477bdad233fSMatthew Knepley   Not collective
2478bdad233fSMatthew Knepley 
2479bdad233fSMatthew Knepley   Input Parameter:
2480bcf0153eSBarry Smith . ts   - The `TS`
2481bdad233fSMatthew Knepley 
2482bdad233fSMatthew Knepley   Output Parameter:
2483bcf0153eSBarry Smith . type - One of `TS_LINEAR`, `TS_NONLINEAR` where these types refer to problems of the forms
2484bdad233fSMatthew Knepley .vb
2485089b2837SJed Brown          M U_t = A U
2486089b2837SJed Brown          M(t) U_t = A(t) U
2487b5abc632SBarry Smith          F(t,U,U_t)
2488bdad233fSMatthew Knepley .ve
2489bdad233fSMatthew Knepley 
2490bdad233fSMatthew Knepley    Level: beginner
2491bdad233fSMatthew Knepley 
2492bcf0153eSBarry Smith .seealso: [](chapter_ts), `TSSetUp()`, `TSProblemType`, `TS`
2493bdad233fSMatthew Knepley @*/
2494d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetProblemType(TS ts, TSProblemType *type)
2495d71ae5a4SJacob Faibussowitsch {
2496bdad233fSMatthew Knepley   PetscFunctionBegin;
24970700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
24984482741eSBarry Smith   PetscValidIntPointer(type, 2);
2499bdad233fSMatthew Knepley   *type = ts->problem_type;
25003ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2501bdad233fSMatthew Knepley }
2502d763cef2SBarry Smith 
2503303a5415SBarry Smith /*
2504303a5415SBarry 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()
2505303a5415SBarry Smith */
2506d71ae5a4SJacob Faibussowitsch static PetscErrorCode TSSetExactFinalTimeDefault(TS ts)
2507d71ae5a4SJacob Faibussowitsch {
2508303a5415SBarry Smith   PetscBool isnone;
2509303a5415SBarry Smith 
2510303a5415SBarry Smith   PetscFunctionBegin;
25119566063dSJacob Faibussowitsch   PetscCall(TSGetAdapt(ts, &ts->adapt));
25129566063dSJacob Faibussowitsch   PetscCall(TSAdaptSetDefaultType(ts->adapt, ts->default_adapt_type));
2513303a5415SBarry Smith 
25149566063dSJacob Faibussowitsch   PetscCall(PetscObjectTypeCompare((PetscObject)ts->adapt, TSADAPTNONE, &isnone));
25151e66621cSBarry Smith   if (!isnone && ts->exact_final_time == TS_EXACTFINALTIME_UNSPECIFIED) ts->exact_final_time = TS_EXACTFINALTIME_MATCHSTEP;
25161e66621cSBarry Smith   else if (ts->exact_final_time == TS_EXACTFINALTIME_UNSPECIFIED) ts->exact_final_time = TS_EXACTFINALTIME_INTERPOLATE;
25173ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2518303a5415SBarry Smith }
2519303a5415SBarry Smith 
2520d763cef2SBarry Smith /*@
2521303a5415SBarry Smith    TSSetUp - Sets up the internal data structures for the later use of a timestepper.
2522d763cef2SBarry Smith 
2523c3339decSBarry Smith    Collective
2524d763cef2SBarry Smith 
2525d763cef2SBarry Smith    Input Parameter:
2526bcf0153eSBarry Smith .  ts - the `TS` context obtained from `TSCreate()`
2527d763cef2SBarry Smith 
2528d763cef2SBarry Smith    Level: advanced
2529d763cef2SBarry Smith 
2530bcf0153eSBarry Smith    Note:
2531bcf0153eSBarry Smith    For basic use of the `TS` solvers the user need not explicitly call
2532bcf0153eSBarry Smith    `TSSetUp()`, since these actions will automatically occur during
2533bcf0153eSBarry Smith    the call to `TSStep()` or `TSSolve()`.  However, if one wishes to control this
2534bcf0153eSBarry Smith    phase separately, `TSSetUp()` should be called after `TSCreate()`
2535bcf0153eSBarry Smith    and optional routines of the form TSSetXXX(), but before `TSStep()` and `TSSolve()`.
2536bcf0153eSBarry Smith 
2537bcf0153eSBarry Smith .seealso: [](chapter_ts), `TSCreate()`, `TS`, `TSStep()`, `TSDestroy()`, `TSSolve()`
2538d763cef2SBarry Smith @*/
2539d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetUp(TS ts)
2540d71ae5a4SJacob Faibussowitsch {
25416c6b9e74SPeter Brune   DM dm;
25426c6b9e74SPeter Brune   PetscErrorCode (*func)(SNES, Vec, Vec, void *);
2543d1e9a80fSBarry Smith   PetscErrorCode (*jac)(SNES, Vec, Mat, Mat, void *);
2544cd11d68dSLisandro Dalcin   TSIFunction   ifun;
25456c6b9e74SPeter Brune   TSIJacobian   ijac;
2546efe9872eSLisandro Dalcin   TSI2Jacobian  i2jac;
25476c6b9e74SPeter Brune   TSRHSJacobian rhsjac;
2548d763cef2SBarry Smith 
2549d763cef2SBarry Smith   PetscFunctionBegin;
25500700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
25513ba16761SJacob Faibussowitsch   if (ts->setupcalled) PetscFunctionReturn(PETSC_SUCCESS);
2552277b19d0SLisandro Dalcin 
25537adad957SLisandro Dalcin   if (!((PetscObject)ts)->type_name) {
25549566063dSJacob Faibussowitsch     PetscCall(TSGetIFunction(ts, NULL, &ifun, NULL));
25559566063dSJacob Faibussowitsch     PetscCall(TSSetType(ts, ifun ? TSBEULER : TSEULER));
2556d763cef2SBarry Smith   }
2557277b19d0SLisandro Dalcin 
25581a638600SStefano Zampini   if (!ts->vec_sol) {
25591e66621cSBarry Smith     PetscCheck(ts->dm, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Must call TSSetSolution() first");
25609566063dSJacob Faibussowitsch     PetscCall(DMCreateGlobalVector(ts->dm, &ts->vec_sol));
25611a638600SStefano Zampini   }
2562277b19d0SLisandro Dalcin 
25634a658b32SHong Zhang   if (ts->tspan) {
25641e66621cSBarry Smith     if (!ts->tspan->vecs_sol) PetscCall(VecDuplicateVecs(ts->vec_sol, ts->tspan->num_span_times, &ts->tspan->vecs_sol));
25654a658b32SHong Zhang   }
2566298bade4SHong Zhang   if (!ts->Jacp && ts->Jacprhs) { /* IJacobianP shares the same matrix with RHSJacobianP if only RHSJacobianP is provided */
25679566063dSJacob Faibussowitsch     PetscCall(PetscObjectReference((PetscObject)ts->Jacprhs));
2568298bade4SHong Zhang     ts->Jacp = ts->Jacprhs;
2569298bade4SHong Zhang   }
2570298bade4SHong Zhang 
2571cd4cee2dSHong Zhang   if (ts->quadraturets) {
25729566063dSJacob Faibussowitsch     PetscCall(TSSetUp(ts->quadraturets));
25739566063dSJacob Faibussowitsch     PetscCall(VecDestroy(&ts->vec_costintegrand));
25749566063dSJacob Faibussowitsch     PetscCall(VecDuplicate(ts->quadraturets->vec_sol, &ts->vec_costintegrand));
2575cd4cee2dSHong Zhang   }
2576cd4cee2dSHong Zhang 
25779566063dSJacob Faibussowitsch   PetscCall(TSGetRHSJacobian(ts, NULL, NULL, &rhsjac, NULL));
2578f23ba4b3SHong Zhang   if (rhsjac == TSComputeRHSJacobianConstant) {
2579e1244c69SJed Brown     Mat  Amat, Pmat;
2580e1244c69SJed Brown     SNES snes;
25819566063dSJacob Faibussowitsch     PetscCall(TSGetSNES(ts, &snes));
25829566063dSJacob Faibussowitsch     PetscCall(SNESGetJacobian(snes, &Amat, &Pmat, NULL, NULL));
2583e1244c69SJed Brown     /* Matching matrices implies that an IJacobian is NOT set, because if it had been set, the IJacobian's matrix would
2584e1244c69SJed Brown      * have displaced the RHS matrix */
2585971015bcSStefano Zampini     if (Amat && Amat == ts->Arhs) {
2586abc0d4abSBarry 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 */
25879566063dSJacob Faibussowitsch       PetscCall(MatDuplicate(ts->Arhs, MAT_COPY_VALUES, &Amat));
25889566063dSJacob Faibussowitsch       PetscCall(SNESSetJacobian(snes, Amat, NULL, NULL, NULL));
25899566063dSJacob Faibussowitsch       PetscCall(MatDestroy(&Amat));
2590e1244c69SJed Brown     }
2591971015bcSStefano Zampini     if (Pmat && Pmat == ts->Brhs) {
25929566063dSJacob Faibussowitsch       PetscCall(MatDuplicate(ts->Brhs, MAT_COPY_VALUES, &Pmat));
25939566063dSJacob Faibussowitsch       PetscCall(SNESSetJacobian(snes, NULL, Pmat, NULL, NULL));
25949566063dSJacob Faibussowitsch       PetscCall(MatDestroy(&Pmat));
2595e1244c69SJed Brown     }
2596e1244c69SJed Brown   }
25972ffb9264SLisandro Dalcin 
25989566063dSJacob Faibussowitsch   PetscCall(TSGetAdapt(ts, &ts->adapt));
25999566063dSJacob Faibussowitsch   PetscCall(TSAdaptSetDefaultType(ts->adapt, ts->default_adapt_type));
26002ffb9264SLisandro Dalcin 
2601dbbe0bcdSBarry Smith   PetscTryTypeMethod(ts, setup);
2602277b19d0SLisandro Dalcin 
26039566063dSJacob Faibussowitsch   PetscCall(TSSetExactFinalTimeDefault(ts));
26042ffb9264SLisandro Dalcin 
2605a6772fa2SLisandro Dalcin   /* In the case where we've set a DMTSFunction or what have you, we need the default SNESFunction
26066c6b9e74SPeter Brune      to be set right but can't do it elsewhere due to the overreliance on ctx=ts.
26076c6b9e74SPeter Brune    */
26089566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
26099566063dSJacob Faibussowitsch   PetscCall(DMSNESGetFunction(dm, &func, NULL));
26101e66621cSBarry Smith   if (!func) PetscCall(DMSNESSetFunction(dm, SNESTSFormFunction, ts));
26111e66621cSBarry Smith 
2612a6772fa2SLisandro 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.
26136c6b9e74SPeter Brune      Otherwise, the SNES will use coloring internally to form the Jacobian.
26146c6b9e74SPeter Brune    */
26159566063dSJacob Faibussowitsch   PetscCall(DMSNESGetJacobian(dm, &jac, NULL));
26169566063dSJacob Faibussowitsch   PetscCall(DMTSGetIJacobian(dm, &ijac, NULL));
26179566063dSJacob Faibussowitsch   PetscCall(DMTSGetI2Jacobian(dm, &i2jac, NULL));
26189566063dSJacob Faibussowitsch   PetscCall(DMTSGetRHSJacobian(dm, &rhsjac, NULL));
26191e66621cSBarry Smith   if (!jac && (ijac || i2jac || rhsjac)) PetscCall(DMSNESSetJacobian(dm, SNESTSFormJacobian, ts));
2620c0517034SDebojyoti Ghosh 
2621c0517034SDebojyoti Ghosh   /* if time integration scheme has a starting method, call it */
2622dbbe0bcdSBarry Smith   PetscTryTypeMethod(ts, startingmethod);
2623c0517034SDebojyoti Ghosh 
2624277b19d0SLisandro Dalcin   ts->setupcalled = PETSC_TRUE;
26253ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2626277b19d0SLisandro Dalcin }
2627277b19d0SLisandro Dalcin 
2628f6a906c0SBarry Smith /*@
2629bcf0153eSBarry Smith    TSReset - Resets a `TS` context and removes any allocated `Vec`s and `Mat`s.
2630277b19d0SLisandro Dalcin 
2631c3339decSBarry Smith    Collective
2632277b19d0SLisandro Dalcin 
2633277b19d0SLisandro Dalcin    Input Parameter:
2634bcf0153eSBarry Smith .  ts - the `TS` context obtained from `TSCreate()`
2635277b19d0SLisandro Dalcin 
2636277b19d0SLisandro Dalcin    Level: beginner
2637277b19d0SLisandro Dalcin 
2638bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSCreate()`, `TSSetup()`, `TSDestroy()`
2639277b19d0SLisandro Dalcin @*/
2640d71ae5a4SJacob Faibussowitsch PetscErrorCode TSReset(TS ts)
2641d71ae5a4SJacob Faibussowitsch {
26421d06f6b3SHong Zhang   TS_RHSSplitLink ilink = ts->tsrhssplit, next;
2643277b19d0SLisandro Dalcin 
2644277b19d0SLisandro Dalcin   PetscFunctionBegin;
2645277b19d0SLisandro Dalcin   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
2646b18ea86cSHong Zhang 
2647dbbe0bcdSBarry Smith   PetscTryTypeMethod(ts, reset);
26489566063dSJacob Faibussowitsch   if (ts->snes) PetscCall(SNESReset(ts->snes));
26499566063dSJacob Faibussowitsch   if (ts->adapt) PetscCall(TSAdaptReset(ts->adapt));
2650bbd56ea5SKarl Rupp 
26519566063dSJacob Faibussowitsch   PetscCall(MatDestroy(&ts->Arhs));
26529566063dSJacob Faibussowitsch   PetscCall(MatDestroy(&ts->Brhs));
26539566063dSJacob Faibussowitsch   PetscCall(VecDestroy(&ts->Frhs));
26549566063dSJacob Faibussowitsch   PetscCall(VecDestroy(&ts->vec_sol));
26559566063dSJacob Faibussowitsch   PetscCall(VecDestroy(&ts->vec_dot));
26569566063dSJacob Faibussowitsch   PetscCall(VecDestroy(&ts->vatol));
26579566063dSJacob Faibussowitsch   PetscCall(VecDestroy(&ts->vrtol));
26589566063dSJacob Faibussowitsch   PetscCall(VecDestroyVecs(ts->nwork, &ts->work));
2659bbd56ea5SKarl Rupp 
26609566063dSJacob Faibussowitsch   PetscCall(MatDestroy(&ts->Jacprhs));
26619566063dSJacob Faibussowitsch   PetscCall(MatDestroy(&ts->Jacp));
26621baa6e33SBarry Smith   if (ts->forward_solve) PetscCall(TSForwardReset(ts));
2663cd4cee2dSHong Zhang   if (ts->quadraturets) {
26649566063dSJacob Faibussowitsch     PetscCall(TSReset(ts->quadraturets));
26659566063dSJacob Faibussowitsch     PetscCall(VecDestroy(&ts->vec_costintegrand));
2666cd4cee2dSHong Zhang   }
26671d06f6b3SHong Zhang   while (ilink) {
26681d06f6b3SHong Zhang     next = ilink->next;
26699566063dSJacob Faibussowitsch     PetscCall(TSDestroy(&ilink->ts));
26709566063dSJacob Faibussowitsch     PetscCall(PetscFree(ilink->splitname));
26719566063dSJacob Faibussowitsch     PetscCall(ISDestroy(&ilink->is));
26729566063dSJacob Faibussowitsch     PetscCall(PetscFree(ilink));
26731d06f6b3SHong Zhang     ilink = next;
267487f4e208SHong Zhang   }
26756bf673ebSJoe Pusztay   ts->tsrhssplit     = NULL;
2676545aaa6fSHong Zhang   ts->num_rhs_splits = 0;
26774a658b32SHong Zhang   if (ts->tspan) {
26784a658b32SHong Zhang     PetscCall(PetscFree(ts->tspan->span_times));
26794a658b32SHong Zhang     PetscCall(VecDestroyVecs(ts->tspan->num_span_times, &ts->tspan->vecs_sol));
26804a658b32SHong Zhang     PetscCall(PetscFree(ts->tspan));
26814a658b32SHong Zhang   }
2682277b19d0SLisandro Dalcin   ts->setupcalled = PETSC_FALSE;
26833ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2684d763cef2SBarry Smith }
2685d763cef2SBarry Smith 
26861fb7b255SJunchao Zhang /*@C
2687d763cef2SBarry Smith    TSDestroy - Destroys the timestepper context that was created
2688bcf0153eSBarry Smith    with `TSCreate()`.
2689d763cef2SBarry Smith 
2690c3339decSBarry Smith    Collective
2691d763cef2SBarry Smith 
2692d763cef2SBarry Smith    Input Parameter:
2693bcf0153eSBarry Smith .  ts - the `TS` context obtained from `TSCreate()`
2694d763cef2SBarry Smith 
2695d763cef2SBarry Smith    Level: beginner
2696d763cef2SBarry Smith 
2697bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSCreate()`, `TSSetUp()`, `TSSolve()`
2698d763cef2SBarry Smith @*/
2699d71ae5a4SJacob Faibussowitsch PetscErrorCode TSDestroy(TS *ts)
2700d71ae5a4SJacob Faibussowitsch {
2701d763cef2SBarry Smith   PetscFunctionBegin;
27023ba16761SJacob Faibussowitsch   if (!*ts) PetscFunctionReturn(PETSC_SUCCESS);
2703ecf68647SHong Zhang   PetscValidHeaderSpecific(*ts, TS_CLASSID, 1);
27049371c9d4SSatish Balay   if (--((PetscObject)(*ts))->refct > 0) {
27059371c9d4SSatish Balay     *ts = NULL;
27063ba16761SJacob Faibussowitsch     PetscFunctionReturn(PETSC_SUCCESS);
27079371c9d4SSatish Balay   }
2708d763cef2SBarry Smith 
27099566063dSJacob Faibussowitsch   PetscCall(TSReset(*ts));
27109566063dSJacob Faibussowitsch   PetscCall(TSAdjointReset(*ts));
27111e66621cSBarry Smith   if ((*ts)->forward_solve) PetscCall(TSForwardReset(*ts));
27121e66621cSBarry Smith 
2713e04113cfSBarry Smith   /* if memory was published with SAWs then destroy it */
27149566063dSJacob Faibussowitsch   PetscCall(PetscObjectSAWsViewOff((PetscObject)*ts));
2715dbbe0bcdSBarry Smith   PetscTryTypeMethod((*ts), destroy);
27166d4c513bSLisandro Dalcin 
27179566063dSJacob Faibussowitsch   PetscCall(TSTrajectoryDestroy(&(*ts)->trajectory));
2718bc952696SBarry Smith 
27199566063dSJacob Faibussowitsch   PetscCall(TSAdaptDestroy(&(*ts)->adapt));
27209566063dSJacob Faibussowitsch   PetscCall(TSEventDestroy(&(*ts)->event));
27216427ac75SLisandro Dalcin 
27229566063dSJacob Faibussowitsch   PetscCall(SNESDestroy(&(*ts)->snes));
27239566063dSJacob Faibussowitsch   PetscCall(DMDestroy(&(*ts)->dm));
27249566063dSJacob Faibussowitsch   PetscCall(TSMonitorCancel((*ts)));
27259566063dSJacob Faibussowitsch   PetscCall(TSAdjointMonitorCancel((*ts)));
27266d4c513bSLisandro Dalcin 
27279566063dSJacob Faibussowitsch   PetscCall(TSDestroy(&(*ts)->quadraturets));
27289566063dSJacob Faibussowitsch   PetscCall(PetscHeaderDestroy(ts));
27293ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2730d763cef2SBarry Smith }
2731d763cef2SBarry Smith 
2732d8e5e3e6SSatish Balay /*@
2733bcf0153eSBarry Smith    TSGetSNES - Returns the `SNES` (nonlinear solver) associated with
2734bcf0153eSBarry Smith    a `TS` (timestepper) context. Valid only for nonlinear problems.
2735d763cef2SBarry Smith 
2736bcf0153eSBarry Smith    Not Collective, but snes is parallel if ts is parallel
2737d763cef2SBarry Smith 
2738d763cef2SBarry Smith    Input Parameter:
2739bcf0153eSBarry Smith .  ts - the `TS` context obtained from `TSCreate()`
2740d763cef2SBarry Smith 
2741d763cef2SBarry Smith    Output Parameter:
2742d763cef2SBarry Smith .  snes - the nonlinear solver context
2743d763cef2SBarry Smith 
2744d763cef2SBarry Smith    Level: beginner
2745d763cef2SBarry Smith 
2746bcf0153eSBarry Smith    Notes:
2747bcf0153eSBarry Smith    The user can then directly manipulate the `SNES` context to set various
2748bcf0153eSBarry Smith    options, etc.  Likewise, the user can then extract and manipulate the
2749bcf0153eSBarry Smith    `KSP`, and `PC` contexts as well.
2750bcf0153eSBarry Smith 
2751bcf0153eSBarry Smith    `TSGetSNES()` does not work for integrators that do not use `SNES`; in
2752195e9b02SBarry Smith    this case `TSGetSNES()` returns `NULL` in `snes`.
2753bcf0153eSBarry Smith 
2754bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `SNES`, `TSCreate()`, `TSSetUp()`, `TSSolve()`
2755d763cef2SBarry Smith @*/
2756d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetSNES(TS ts, SNES *snes)
2757d71ae5a4SJacob Faibussowitsch {
2758d763cef2SBarry Smith   PetscFunctionBegin;
27590700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
27604482741eSBarry Smith   PetscValidPointer(snes, 2);
2761d372ba47SLisandro Dalcin   if (!ts->snes) {
27629566063dSJacob Faibussowitsch     PetscCall(SNESCreate(PetscObjectComm((PetscObject)ts), &ts->snes));
27639566063dSJacob Faibussowitsch     PetscCall(PetscObjectSetOptions((PetscObject)ts->snes, ((PetscObject)ts)->options));
27649566063dSJacob Faibussowitsch     PetscCall(SNESSetFunction(ts->snes, NULL, SNESTSFormFunction, ts));
27659566063dSJacob Faibussowitsch     PetscCall(PetscObjectIncrementTabLevel((PetscObject)ts->snes, (PetscObject)ts, 1));
27669566063dSJacob Faibussowitsch     if (ts->dm) PetscCall(SNESSetDM(ts->snes, ts->dm));
27671e66621cSBarry Smith     if (ts->problem_type == TS_LINEAR) PetscCall(SNESSetType(ts->snes, SNESKSPONLY));
2768d372ba47SLisandro Dalcin   }
2769d763cef2SBarry Smith   *snes = ts->snes;
27703ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2771d763cef2SBarry Smith }
2772d763cef2SBarry Smith 
2773deb2cd25SJed Brown /*@
2774bcf0153eSBarry Smith    TSSetSNES - Set the `SNES` (nonlinear solver) to be used by the timestepping context
2775deb2cd25SJed Brown 
2776deb2cd25SJed Brown    Collective
2777deb2cd25SJed Brown 
2778d8d19677SJose E. Roman    Input Parameters:
2779bcf0153eSBarry Smith +  ts - the `TS` context obtained from `TSCreate()`
2780deb2cd25SJed Brown -  snes - the nonlinear solver context
2781deb2cd25SJed Brown 
2782deb2cd25SJed Brown    Level: developer
2783deb2cd25SJed Brown 
2784bcf0153eSBarry Smith    Note:
2785bcf0153eSBarry Smith    Most users should have the `TS` created by calling `TSGetSNES()`
2786bcf0153eSBarry Smith 
2787bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `SNES`, `TSCreate()`, `TSSetUp()`, `TSSolve()`, `TSGetSNES()`
2788deb2cd25SJed Brown @*/
2789d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetSNES(TS ts, SNES snes)
2790d71ae5a4SJacob Faibussowitsch {
2791d1e9a80fSBarry Smith   PetscErrorCode (*func)(SNES, Vec, Mat, Mat, void *);
2792deb2cd25SJed Brown 
2793deb2cd25SJed Brown   PetscFunctionBegin;
2794deb2cd25SJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
2795deb2cd25SJed Brown   PetscValidHeaderSpecific(snes, SNES_CLASSID, 2);
27969566063dSJacob Faibussowitsch   PetscCall(PetscObjectReference((PetscObject)snes));
27979566063dSJacob Faibussowitsch   PetscCall(SNESDestroy(&ts->snes));
2798bbd56ea5SKarl Rupp 
2799deb2cd25SJed Brown   ts->snes = snes;
2800bbd56ea5SKarl Rupp 
28019566063dSJacob Faibussowitsch   PetscCall(SNESSetFunction(ts->snes, NULL, SNESTSFormFunction, ts));
28029566063dSJacob Faibussowitsch   PetscCall(SNESGetJacobian(ts->snes, NULL, NULL, &func, NULL));
28031e66621cSBarry Smith   if (func == SNESTSFormJacobian) PetscCall(SNESSetJacobian(ts->snes, NULL, NULL, SNESTSFormJacobian, ts));
28043ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2805deb2cd25SJed Brown }
2806deb2cd25SJed Brown 
2807d8e5e3e6SSatish Balay /*@
2808bcf0153eSBarry Smith    TSGetKSP - Returns the `KSP` (linear solver) associated with
2809bcf0153eSBarry Smith    a `TS` (timestepper) context.
2810d763cef2SBarry Smith 
2811195e9b02SBarry Smith    Not Collective, but `ksp` is parallel if `ts` is parallel
2812d763cef2SBarry Smith 
2813d763cef2SBarry Smith    Input Parameter:
2814bcf0153eSBarry Smith .  ts - the `TS` context obtained from `TSCreate()`
2815d763cef2SBarry Smith 
2816d763cef2SBarry Smith    Output Parameter:
281794b7f48cSBarry Smith .  ksp - the nonlinear solver context
2818d763cef2SBarry Smith 
2819d763cef2SBarry Smith    Level: beginner
2820d763cef2SBarry Smith 
2821bcf0153eSBarry Smith    Notes:
2822bcf0153eSBarry Smith    The user can then directly manipulate the `KSP` context to set various
2823bcf0153eSBarry Smith    options, etc.  Likewise, the user can then extract and manipulate the
2824bcf0153eSBarry Smith    `PC` context as well.
2825bcf0153eSBarry Smith 
2826bcf0153eSBarry Smith    `TSGetKSP()` does not work for integrators that do not use `KSP`;
2827195e9b02SBarry Smith    in this case `TSGetKSP()` returns `NULL` in `ksp`.
2828bcf0153eSBarry Smith 
2829bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `SNES`, `KSP`, `TSCreate()`, `TSSetUp()`, `TSSolve()`, `TSGetSNES()`
2830d763cef2SBarry Smith @*/
2831d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetKSP(TS ts, KSP *ksp)
2832d71ae5a4SJacob Faibussowitsch {
2833089b2837SJed Brown   SNES snes;
2834d372ba47SLisandro Dalcin 
2835d763cef2SBarry Smith   PetscFunctionBegin;
28360700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
28374482741eSBarry Smith   PetscValidPointer(ksp, 2);
28383c633725SBarry Smith   PetscCheck(((PetscObject)ts)->type_name, PETSC_COMM_SELF, PETSC_ERR_ARG_NULL, "KSP is not created yet. Call TSSetType() first");
28393c633725SBarry Smith   PetscCheck(ts->problem_type == TS_LINEAR, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Linear only; use TSGetSNES()");
28409566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts, &snes));
28419566063dSJacob Faibussowitsch   PetscCall(SNESGetKSP(snes, ksp));
28423ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2843d763cef2SBarry Smith }
2844d763cef2SBarry Smith 
2845d763cef2SBarry Smith /* ----------- Routines to set solver parameters ---------- */
2846d763cef2SBarry Smith 
2847adb62b0dSMatthew Knepley /*@
2848618ce8baSLisandro Dalcin    TSSetMaxSteps - Sets the maximum number of steps to use.
2849618ce8baSLisandro Dalcin 
2850c3339decSBarry Smith    Logically Collective
2851618ce8baSLisandro Dalcin 
2852618ce8baSLisandro Dalcin    Input Parameters:
2853bcf0153eSBarry Smith +  ts - the `TS` context obtained from `TSCreate()`
2854618ce8baSLisandro Dalcin -  maxsteps - maximum number of steps to use
2855618ce8baSLisandro Dalcin 
2856bcf0153eSBarry Smith    Options Database Key:
2857618ce8baSLisandro Dalcin .  -ts_max_steps <maxsteps> - Sets maxsteps
2858618ce8baSLisandro Dalcin 
2859618ce8baSLisandro Dalcin    Level: intermediate
2860618ce8baSLisandro Dalcin 
2861bcf0153eSBarry Smith    Note:
2862bcf0153eSBarry Smith    The default maximum number of steps is 5000
2863bcf0153eSBarry Smith 
2864bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSGetMaxSteps()`, `TSSetMaxTime()`, `TSSetExactFinalTime()`
2865618ce8baSLisandro Dalcin @*/
2866d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetMaxSteps(TS ts, PetscInt maxsteps)
2867d71ae5a4SJacob Faibussowitsch {
2868618ce8baSLisandro Dalcin   PetscFunctionBegin;
2869618ce8baSLisandro Dalcin   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
2870618ce8baSLisandro Dalcin   PetscValidLogicalCollectiveInt(ts, maxsteps, 2);
28713c633725SBarry Smith   PetscCheck(maxsteps >= 0, PetscObjectComm((PetscObject)ts), PETSC_ERR_ARG_OUTOFRANGE, "Maximum number of steps must be non-negative");
2872618ce8baSLisandro Dalcin   ts->max_steps = maxsteps;
28733ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2874618ce8baSLisandro Dalcin }
2875618ce8baSLisandro Dalcin 
2876618ce8baSLisandro Dalcin /*@
2877618ce8baSLisandro Dalcin    TSGetMaxSteps - Gets the maximum number of steps to use.
2878618ce8baSLisandro Dalcin 
2879618ce8baSLisandro Dalcin    Not Collective
2880618ce8baSLisandro Dalcin 
28812fe279fdSBarry Smith    Input Parameter:
2882bcf0153eSBarry Smith .  ts - the `TS` context obtained from `TSCreate()`
2883618ce8baSLisandro Dalcin 
2884618ce8baSLisandro Dalcin    Output Parameter:
2885618ce8baSLisandro Dalcin .  maxsteps - maximum number of steps to use
2886618ce8baSLisandro Dalcin 
2887618ce8baSLisandro Dalcin    Level: advanced
2888618ce8baSLisandro Dalcin 
2889bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSSetMaxSteps()`, `TSGetMaxTime()`, `TSSetMaxTime()`
2890618ce8baSLisandro Dalcin @*/
2891d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetMaxSteps(TS ts, PetscInt *maxsteps)
2892d71ae5a4SJacob Faibussowitsch {
2893618ce8baSLisandro Dalcin   PetscFunctionBegin;
2894618ce8baSLisandro Dalcin   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
2895618ce8baSLisandro Dalcin   PetscValidIntPointer(maxsteps, 2);
2896618ce8baSLisandro Dalcin   *maxsteps = ts->max_steps;
28973ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2898618ce8baSLisandro Dalcin }
2899618ce8baSLisandro Dalcin 
2900618ce8baSLisandro Dalcin /*@
2901618ce8baSLisandro Dalcin    TSSetMaxTime - Sets the maximum (or final) time for timestepping.
2902618ce8baSLisandro Dalcin 
2903c3339decSBarry Smith    Logically Collective
2904618ce8baSLisandro Dalcin 
2905618ce8baSLisandro Dalcin    Input Parameters:
2906bcf0153eSBarry Smith +  ts - the `TS` context obtained from `TSCreate()`
2907618ce8baSLisandro Dalcin -  maxtime - final time to step to
2908618ce8baSLisandro Dalcin 
2909bcf0153eSBarry Smith    Options Database Key:
2910ef85077eSLisandro Dalcin .  -ts_max_time <maxtime> - Sets maxtime
2911618ce8baSLisandro Dalcin 
2912bcf0153eSBarry Smith    Level: intermediate
2913bcf0153eSBarry Smith 
2914618ce8baSLisandro Dalcin    Notes:
2915618ce8baSLisandro Dalcin    The default maximum time is 5.0
2916618ce8baSLisandro Dalcin 
2917bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSGetMaxTime()`, `TSSetMaxSteps()`, `TSSetExactFinalTime()`
2918618ce8baSLisandro Dalcin @*/
2919d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetMaxTime(TS ts, PetscReal maxtime)
2920d71ae5a4SJacob Faibussowitsch {
2921618ce8baSLisandro Dalcin   PetscFunctionBegin;
2922618ce8baSLisandro Dalcin   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
2923618ce8baSLisandro Dalcin   PetscValidLogicalCollectiveReal(ts, maxtime, 2);
2924618ce8baSLisandro Dalcin   ts->max_time = maxtime;
29253ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2926618ce8baSLisandro Dalcin }
2927618ce8baSLisandro Dalcin 
2928618ce8baSLisandro Dalcin /*@
2929618ce8baSLisandro Dalcin    TSGetMaxTime - Gets the maximum (or final) time for timestepping.
2930618ce8baSLisandro Dalcin 
2931618ce8baSLisandro Dalcin    Not Collective
2932618ce8baSLisandro Dalcin 
29332fe279fdSBarry Smith    Input Parameter:
2934bcf0153eSBarry Smith .  ts - the `TS` context obtained from `TSCreate()`
2935618ce8baSLisandro Dalcin 
2936618ce8baSLisandro Dalcin    Output Parameter:
2937618ce8baSLisandro Dalcin .  maxtime - final time to step to
2938618ce8baSLisandro Dalcin 
2939618ce8baSLisandro Dalcin    Level: advanced
2940618ce8baSLisandro Dalcin 
2941bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSSetMaxTime()`, `TSGetMaxSteps()`, `TSSetMaxSteps()`
2942618ce8baSLisandro Dalcin @*/
2943d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetMaxTime(TS ts, PetscReal *maxtime)
2944d71ae5a4SJacob Faibussowitsch {
2945618ce8baSLisandro Dalcin   PetscFunctionBegin;
2946618ce8baSLisandro Dalcin   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
2947618ce8baSLisandro Dalcin   PetscValidRealPointer(maxtime, 2);
2948618ce8baSLisandro Dalcin   *maxtime = ts->max_time;
29493ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2950618ce8baSLisandro Dalcin }
2951618ce8baSLisandro Dalcin 
2952618ce8baSLisandro Dalcin /*@
2953bcf0153eSBarry Smith    TSSetInitialTimeStep - Deprecated, use `TSSetTime()` and `TSSetTimeStep()`.
2954edc382c3SSatish Balay 
2955edc382c3SSatish Balay    Level: deprecated
2956edc382c3SSatish Balay 
2957aaa6c58dSLisandro Dalcin @*/
2958d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetInitialTimeStep(TS ts, PetscReal initial_time, PetscReal time_step)
2959d71ae5a4SJacob Faibussowitsch {
2960aaa6c58dSLisandro Dalcin   PetscFunctionBegin;
2961aaa6c58dSLisandro Dalcin   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
29629566063dSJacob Faibussowitsch   PetscCall(TSSetTime(ts, initial_time));
29639566063dSJacob Faibussowitsch   PetscCall(TSSetTimeStep(ts, time_step));
29643ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2965aaa6c58dSLisandro Dalcin }
2966aaa6c58dSLisandro Dalcin 
2967aaa6c58dSLisandro Dalcin /*@
2968bcf0153eSBarry Smith    TSGetDuration - Deprecated, use `TSGetMaxSteps()` and `TSGetMaxTime()`.
2969edc382c3SSatish Balay 
2970edc382c3SSatish Balay    Level: deprecated
2971edc382c3SSatish Balay 
2972adb62b0dSMatthew Knepley @*/
2973d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetDuration(TS ts, PetscInt *maxsteps, PetscReal *maxtime)
2974d71ae5a4SJacob Faibussowitsch {
2975adb62b0dSMatthew Knepley   PetscFunctionBegin;
29760700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
2977abc0a331SBarry Smith   if (maxsteps) {
29784482741eSBarry Smith     PetscValidIntPointer(maxsteps, 2);
2979adb62b0dSMatthew Knepley     *maxsteps = ts->max_steps;
2980adb62b0dSMatthew Knepley   }
2981abc0a331SBarry Smith   if (maxtime) {
2982064a246eSJacob Faibussowitsch     PetscValidRealPointer(maxtime, 3);
2983adb62b0dSMatthew Knepley     *maxtime = ts->max_time;
2984adb62b0dSMatthew Knepley   }
29853ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2986adb62b0dSMatthew Knepley }
2987adb62b0dSMatthew Knepley 
2988d763cef2SBarry Smith /*@
2989bcf0153eSBarry Smith    TSSetDuration - Deprecated, use `TSSetMaxSteps()` and `TSSetMaxTime()`.
2990edc382c3SSatish Balay 
2991edc382c3SSatish Balay    Level: deprecated
2992edc382c3SSatish Balay 
2993d763cef2SBarry Smith @*/
2994d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetDuration(TS ts, PetscInt maxsteps, PetscReal maxtime)
2995d71ae5a4SJacob Faibussowitsch {
2996d763cef2SBarry Smith   PetscFunctionBegin;
29970700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
2998c5eb9154SBarry Smith   PetscValidLogicalCollectiveInt(ts, maxsteps, 2);
2999064a246eSJacob Faibussowitsch   PetscValidLogicalCollectiveReal(ts, maxtime, 3);
300039b7ec4bSSean Farley   if (maxsteps >= 0) ts->max_steps = maxsteps;
300113bcc0bdSJacob Faibussowitsch   if (maxtime != (PetscReal)PETSC_DEFAULT) ts->max_time = maxtime;
30023ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
3003d763cef2SBarry Smith }
3004d763cef2SBarry Smith 
3005d763cef2SBarry Smith /*@
3006bcf0153eSBarry Smith    TSGetTimeStepNumber - Deprecated, use `TSGetStepNumber()`.
3007edc382c3SSatish Balay 
3008edc382c3SSatish Balay    Level: deprecated
3009edc382c3SSatish Balay 
30105c5f5948SLisandro Dalcin @*/
3011d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetTimeStepNumber(TS ts, PetscInt *steps)
3012d71ae5a4SJacob Faibussowitsch {
30139371c9d4SSatish Balay   return TSGetStepNumber(ts, steps);
30149371c9d4SSatish Balay }
30155c5f5948SLisandro Dalcin 
301619eac22cSLisandro Dalcin /*@
3017bcf0153eSBarry Smith    TSGetTotalSteps - Deprecated, use `TSGetStepNumber()`.
3018edc382c3SSatish Balay 
3019edc382c3SSatish Balay    Level: deprecated
3020edc382c3SSatish Balay 
30214f4e0956SLisandro Dalcin @*/
3022d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetTotalSteps(TS ts, PetscInt *steps)
3023d71ae5a4SJacob Faibussowitsch {
30249371c9d4SSatish Balay   return TSGetStepNumber(ts, steps);
30259371c9d4SSatish Balay }
30264f4e0956SLisandro Dalcin 
30274f4e0956SLisandro Dalcin /*@
3028d763cef2SBarry Smith    TSSetSolution - Sets the initial solution vector
3029bcf0153eSBarry Smith    for use by the `TS` routines.
3030d763cef2SBarry Smith 
3031c3339decSBarry Smith    Logically Collective
3032d763cef2SBarry Smith 
3033d763cef2SBarry Smith    Input Parameters:
3034bcf0153eSBarry Smith +  ts - the `TS` context obtained from `TSCreate()`
30350910c330SBarry Smith -  u - the solution vector
3036d763cef2SBarry Smith 
3037d763cef2SBarry Smith    Level: beginner
3038d763cef2SBarry Smith 
3039bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSSetSolutionFunction()`, `TSGetSolution()`, `TSCreate()`
3040d763cef2SBarry Smith @*/
3041d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetSolution(TS ts, Vec u)
3042d71ae5a4SJacob Faibussowitsch {
3043496e6a7aSJed Brown   DM dm;
30448737fe31SLisandro Dalcin 
3045d763cef2SBarry Smith   PetscFunctionBegin;
30460700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
30470910c330SBarry Smith   PetscValidHeaderSpecific(u, VEC_CLASSID, 2);
30489566063dSJacob Faibussowitsch   PetscCall(PetscObjectReference((PetscObject)u));
30499566063dSJacob Faibussowitsch   PetscCall(VecDestroy(&ts->vec_sol));
30500910c330SBarry Smith   ts->vec_sol = u;
3051bbd56ea5SKarl Rupp 
30529566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
30539566063dSJacob Faibussowitsch   PetscCall(DMShellSetGlobalVector(dm, u));
30543ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
3055d763cef2SBarry Smith }
3056d763cef2SBarry Smith 
3057ac226902SBarry Smith /*@C
3058000e7ae3SMatthew Knepley   TSSetPreStep - Sets the general-purpose function
30593f2090d5SJed Brown   called once at the beginning of each time step.
3060000e7ae3SMatthew Knepley 
3061c3339decSBarry Smith   Logically Collective
3062000e7ae3SMatthew Knepley 
3063000e7ae3SMatthew Knepley   Input Parameters:
3064bcf0153eSBarry Smith + ts   - The `TS` context obtained from `TSCreate()`
3065000e7ae3SMatthew Knepley - func - The function
3066000e7ae3SMatthew Knepley 
306720f4b53cSBarry Smith   Calling sequence of `func`:
306867b8a455SSatish Balay .vb
306920f4b53cSBarry Smith   PetscErrorCode func (TS ts)
307067b8a455SSatish Balay .ve
3071000e7ae3SMatthew Knepley 
3072000e7ae3SMatthew Knepley   Level: intermediate
3073000e7ae3SMatthew Knepley 
3074bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSSetPreStage()`, `TSSetPostStage()`, `TSSetPostStep()`, `TSStep()`, `TSRestartStep()`
3075000e7ae3SMatthew Knepley @*/
3076d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetPreStep(TS ts, PetscErrorCode (*func)(TS))
3077d71ae5a4SJacob Faibussowitsch {
3078000e7ae3SMatthew Knepley   PetscFunctionBegin;
30790700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3080ae60f76fSBarry Smith   ts->prestep = func;
30813ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
3082000e7ae3SMatthew Knepley }
3083000e7ae3SMatthew Knepley 
308409ee8438SJed Brown /*@
3085bcf0153eSBarry Smith   TSPreStep - Runs the user-defined pre-step function provided with `TSSetPreStep()`
30863f2090d5SJed Brown 
3087c3339decSBarry Smith   Collective
30883f2090d5SJed Brown 
30892fe279fdSBarry Smith   Input Parameter:
3090bcf0153eSBarry Smith . ts   - The `TS` context obtained from `TSCreate()`
30913f2090d5SJed Brown 
30923f2090d5SJed Brown   Level: developer
30933f2090d5SJed Brown 
3094bcf0153eSBarry Smith   Note:
3095bcf0153eSBarry Smith   `TSPreStep()` is typically used within time stepping implementations,
3096bcf0153eSBarry Smith   so most users would not generally call this routine themselves.
3097bcf0153eSBarry Smith 
3098bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSSetPreStep()`, `TSPreStage()`, `TSPostStage()`, `TSPostStep()`
30993f2090d5SJed Brown @*/
3100d71ae5a4SJacob Faibussowitsch PetscErrorCode TSPreStep(TS ts)
3101d71ae5a4SJacob Faibussowitsch {
31023f2090d5SJed Brown   PetscFunctionBegin;
31030700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3104ae60f76fSBarry Smith   if (ts->prestep) {
31055efd42a4SStefano Zampini     Vec              U;
3106ef8d1ce0SJohann Rudi     PetscObjectId    idprev;
3107ef8d1ce0SJohann Rudi     PetscBool        sameObject;
31085efd42a4SStefano Zampini     PetscObjectState sprev, spost;
31095efd42a4SStefano Zampini 
31109566063dSJacob Faibussowitsch     PetscCall(TSGetSolution(ts, &U));
31119566063dSJacob Faibussowitsch     PetscCall(PetscObjectGetId((PetscObject)U, &idprev));
31129566063dSJacob Faibussowitsch     PetscCall(PetscObjectStateGet((PetscObject)U, &sprev));
311325e27a38SBarry Smith     PetscCallBack("TS callback preset", (*ts->prestep)(ts));
31149566063dSJacob Faibussowitsch     PetscCall(TSGetSolution(ts, &U));
31159566063dSJacob Faibussowitsch     PetscCall(PetscObjectCompareId((PetscObject)U, idprev, &sameObject));
31169566063dSJacob Faibussowitsch     PetscCall(PetscObjectStateGet((PetscObject)U, &spost));
31179566063dSJacob Faibussowitsch     if (!sameObject || sprev != spost) PetscCall(TSRestartStep(ts));
3118312ce896SJed Brown   }
31193ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
31203f2090d5SJed Brown }
31213f2090d5SJed Brown 
3122b8123daeSJed Brown /*@C
3123b8123daeSJed Brown   TSSetPreStage - Sets the general-purpose function
3124b8123daeSJed Brown   called once at the beginning of each stage.
3125b8123daeSJed Brown 
3126c3339decSBarry Smith   Logically Collective
3127b8123daeSJed Brown 
3128b8123daeSJed Brown   Input Parameters:
3129bcf0153eSBarry Smith + ts   - The `TS` context obtained from `TSCreate()`
3130b8123daeSJed Brown - func - The function
3131b8123daeSJed Brown 
313220f4b53cSBarry Smith   Calling sequence of `func`:
313367b8a455SSatish Balay .vb
313420f4b53cSBarry Smith   PetscErrorCode func(TS ts, PetscReal stagetime)
313567b8a455SSatish Balay .ve
3136b8123daeSJed Brown 
3137b8123daeSJed Brown   Level: intermediate
3138b8123daeSJed Brown 
3139b8123daeSJed Brown   Note:
3140b8123daeSJed Brown   There may be several stages per time step. If the solve for a given stage fails, the step may be rejected and retried.
3141bcf0153eSBarry Smith   The time step number being computed can be queried using `TSGetStepNumber()` and the total size of the step being
3142bcf0153eSBarry Smith   attempted can be obtained using `TSGetTimeStep()`. The time at the start of the step is available via `TSGetTime()`.
3143b8123daeSJed Brown 
3144bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSSetPostStage()`, `TSSetPreStep()`, `TSSetPostStep()`, `TSGetApplicationContext()`
3145b8123daeSJed Brown @*/
3146d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetPreStage(TS ts, PetscErrorCode (*func)(TS, PetscReal))
3147d71ae5a4SJacob Faibussowitsch {
3148b8123daeSJed Brown   PetscFunctionBegin;
3149b8123daeSJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3150ae60f76fSBarry Smith   ts->prestage = func;
31513ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
3152b8123daeSJed Brown }
3153b8123daeSJed Brown 
31549be3e283SDebojyoti Ghosh /*@C
3155bcf0153eSBarry Smith   TSSetPostStage - Sets the general-purpose function, provided with `TSSetPostStep()`,
31569be3e283SDebojyoti Ghosh   called once at the end of each stage.
31579be3e283SDebojyoti Ghosh 
3158c3339decSBarry Smith   Logically Collective
31599be3e283SDebojyoti Ghosh 
31609be3e283SDebojyoti Ghosh   Input Parameters:
3161bcf0153eSBarry Smith + ts   - The `TS` context obtained from `TSCreate()`
31629be3e283SDebojyoti Ghosh - func - The function
31639be3e283SDebojyoti Ghosh 
316420f4b53cSBarry Smith   Calling sequence of `func`:
316567b8a455SSatish Balay .vb
316620f4b53cSBarry Smith   PetscErrorCode func(TS ts, PetscReal stagetime, PetscInt stageindex, Vec* Y)
316767b8a455SSatish Balay .ve
31689be3e283SDebojyoti Ghosh 
31699be3e283SDebojyoti Ghosh   Level: intermediate
31709be3e283SDebojyoti Ghosh 
31719be3e283SDebojyoti Ghosh   Note:
31729be3e283SDebojyoti Ghosh   There may be several stages per time step. If the solve for a given stage fails, the step may be rejected and retried.
3173bcf0153eSBarry Smith   The time step number being computed can be queried using `TSGetStepNumber()` and the total size of the step being
3174bcf0153eSBarry Smith   attempted can be obtained using `TSGetTimeStep()`. The time at the start of the step is available via `TSGetTime()`.
31759be3e283SDebojyoti Ghosh 
3176bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSSetPreStage()`, `TSSetPreStep()`, `TSSetPostStep()`, `TSGetApplicationContext()`
31779be3e283SDebojyoti Ghosh @*/
3178d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetPostStage(TS ts, PetscErrorCode (*func)(TS, PetscReal, PetscInt, Vec *))
3179d71ae5a4SJacob Faibussowitsch {
31809be3e283SDebojyoti Ghosh   PetscFunctionBegin;
31819be3e283SDebojyoti Ghosh   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
31829be3e283SDebojyoti Ghosh   ts->poststage = func;
31833ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
31849be3e283SDebojyoti Ghosh }
31859be3e283SDebojyoti Ghosh 
3186c688d042SShri Abhyankar /*@C
3187c688d042SShri Abhyankar   TSSetPostEvaluate - Sets the general-purpose function
3188c688d042SShri Abhyankar   called once at the end of each step evaluation.
3189c688d042SShri Abhyankar 
3190c3339decSBarry Smith   Logically Collective
3191c688d042SShri Abhyankar 
3192c688d042SShri Abhyankar   Input Parameters:
3193bcf0153eSBarry Smith + ts   - The `TS` context obtained from `TSCreate()`
3194c688d042SShri Abhyankar - func - The function
3195c688d042SShri Abhyankar 
319620f4b53cSBarry Smith   Calling sequence of `func`:
319767b8a455SSatish Balay .vb
319820f4b53cSBarry Smith   PetscErrorCode func(TS ts)
319967b8a455SSatish Balay .ve
3200c688d042SShri Abhyankar 
3201c688d042SShri Abhyankar   Level: intermediate
3202c688d042SShri Abhyankar 
3203c688d042SShri Abhyankar   Note:
3204bcf0153eSBarry Smith   Semantically, `TSSetPostEvaluate()` differs from `TSSetPostStep()` since the function it sets is called before event-handling
3205bcf0153eSBarry Smith   thus guaranteeing the same solution (computed by the time-stepper) will be passed to it. On the other hand, `TSPostStep()`
3206bcf0153eSBarry Smith   may be passed a different solution, possibly changed by the event handler. `TSPostEvaluate()` is called after the next step
3207bcf0153eSBarry Smith   solution is evaluated allowing to modify it, if need be. The solution can be obtained with `TSGetSolution()`, the time step
3208bcf0153eSBarry Smith   with `TSGetTimeStep()`, and the time at the start of the step is available via `TSGetTime()`
3209c688d042SShri Abhyankar 
3210bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSSetPreStage()`, `TSSetPreStep()`, `TSSetPostStep()`, `TSGetApplicationContext()`
3211c688d042SShri Abhyankar @*/
3212d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetPostEvaluate(TS ts, PetscErrorCode (*func)(TS))
3213d71ae5a4SJacob Faibussowitsch {
3214c688d042SShri Abhyankar   PetscFunctionBegin;
3215c688d042SShri Abhyankar   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3216c688d042SShri Abhyankar   ts->postevaluate = func;
32173ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
3218c688d042SShri Abhyankar }
3219c688d042SShri Abhyankar 
3220b8123daeSJed Brown /*@
3221bcf0153eSBarry Smith   TSPreStage - Runs the user-defined pre-stage function set using `TSSetPreStage()`
3222b8123daeSJed Brown 
3223c3339decSBarry Smith   Collective
3224b8123daeSJed Brown 
3225b8123daeSJed Brown   Input Parameters:
3226bcf0153eSBarry Smith . ts          - The `TS` context obtained from `TSCreate()`
32279be3e283SDebojyoti Ghosh   stagetime   - The absolute time of the current stage
3228b8123daeSJed Brown 
3229b8123daeSJed Brown   Level: developer
3230b8123daeSJed Brown 
3231bcf0153eSBarry Smith   Note:
3232bcf0153eSBarry Smith   `TSPreStage()` is typically used within time stepping implementations,
3233bcf0153eSBarry Smith   most users would not generally call this routine themselves.
3234bcf0153eSBarry Smith 
3235bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSPostStage()`, `TSSetPreStep()`, `TSPreStep()`, `TSPostStep()`
3236b8123daeSJed Brown @*/
3237d71ae5a4SJacob Faibussowitsch PetscErrorCode TSPreStage(TS ts, PetscReal stagetime)
3238d71ae5a4SJacob Faibussowitsch {
3239b8123daeSJed Brown   PetscFunctionBegin;
3240b8123daeSJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
32411e66621cSBarry Smith   if (ts->prestage) PetscCallBack("TS callback prestage", (*ts->prestage)(ts, stagetime));
32423ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
3243b8123daeSJed Brown }
3244b8123daeSJed Brown 
32459be3e283SDebojyoti Ghosh /*@
3246bcf0153eSBarry Smith   TSPostStage - Runs the user-defined post-stage function set using `TSSetPostStage()`
32479be3e283SDebojyoti Ghosh 
3248c3339decSBarry Smith   Collective
32499be3e283SDebojyoti Ghosh 
32509be3e283SDebojyoti Ghosh   Input Parameters:
3251bcf0153eSBarry Smith . ts          - The `TS` context obtained from `TSCreate()`
32529be3e283SDebojyoti Ghosh   stagetime   - The absolute time of the current stage
32539be3e283SDebojyoti Ghosh   stageindex  - Stage number
32549be3e283SDebojyoti Ghosh   Y           - Array of vectors (of size = total number
32559be3e283SDebojyoti Ghosh                 of stages) with the stage solutions
32569be3e283SDebojyoti Ghosh 
32579be3e283SDebojyoti Ghosh   Level: developer
32589be3e283SDebojyoti Ghosh 
3259bcf0153eSBarry Smith   Note:
3260bcf0153eSBarry Smith   `TSPostStage()` is typically used within time stepping implementations,
3261bcf0153eSBarry Smith   most users would not generally call this routine themselves.
3262bcf0153eSBarry Smith 
3263bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSPreStage()`, `TSSetPreStep()`, `TSPreStep()`, `TSPostStep()`
32649be3e283SDebojyoti Ghosh @*/
3265d71ae5a4SJacob Faibussowitsch PetscErrorCode TSPostStage(TS ts, PetscReal stagetime, PetscInt stageindex, Vec *Y)
3266d71ae5a4SJacob Faibussowitsch {
32679be3e283SDebojyoti Ghosh   PetscFunctionBegin;
32689be3e283SDebojyoti Ghosh   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
32691e66621cSBarry Smith   if (ts->poststage) PetscCallBack("TS callback poststage", (*ts->poststage)(ts, stagetime, stageindex, Y));
32703ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
32719be3e283SDebojyoti Ghosh }
32729be3e283SDebojyoti Ghosh 
3273c688d042SShri Abhyankar /*@
3274bcf0153eSBarry Smith   TSPostEvaluate - Runs the user-defined post-evaluate function set using `TSSetPostEvaluate()`
3275c688d042SShri Abhyankar 
3276c3339decSBarry Smith   Collective
3277c688d042SShri Abhyankar 
32782fe279fdSBarry Smith   Input Parameter:
3279bcf0153eSBarry Smith . ts - The `TS` context obtained from `TSCreate()`
3280c688d042SShri Abhyankar 
3281c688d042SShri Abhyankar   Level: developer
3282c688d042SShri Abhyankar 
3283bcf0153eSBarry Smith   Note:
3284bcf0153eSBarry Smith   `TSPostEvaluate()` is typically used within time stepping implementations,
3285bcf0153eSBarry Smith   most users would not generally call this routine themselves.
3286bcf0153eSBarry Smith 
3287bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSSetPostEvaluate()`, `TSSetPreStep()`, `TSPreStep()`, `TSPostStep()`
3288c688d042SShri Abhyankar @*/
3289d71ae5a4SJacob Faibussowitsch PetscErrorCode TSPostEvaluate(TS ts)
3290d71ae5a4SJacob Faibussowitsch {
3291c688d042SShri Abhyankar   PetscFunctionBegin;
3292c688d042SShri Abhyankar   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3293c688d042SShri Abhyankar   if (ts->postevaluate) {
3294dcb233daSLisandro Dalcin     Vec              U;
3295dcb233daSLisandro Dalcin     PetscObjectState sprev, spost;
3296dcb233daSLisandro Dalcin 
32979566063dSJacob Faibussowitsch     PetscCall(TSGetSolution(ts, &U));
32989566063dSJacob Faibussowitsch     PetscCall(PetscObjectStateGet((PetscObject)U, &sprev));
329925e27a38SBarry Smith     PetscCallBack("TS callback postevaluate", (*ts->postevaluate)(ts));
33009566063dSJacob Faibussowitsch     PetscCall(PetscObjectStateGet((PetscObject)U, &spost));
33019566063dSJacob Faibussowitsch     if (sprev != spost) PetscCall(TSRestartStep(ts));
3302c688d042SShri Abhyankar   }
33033ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
3304c688d042SShri Abhyankar }
3305c688d042SShri Abhyankar 
3306ac226902SBarry Smith /*@C
3307000e7ae3SMatthew Knepley   TSSetPostStep - Sets the general-purpose function
33083f2090d5SJed Brown   called once at the end of each time step.
3309000e7ae3SMatthew Knepley 
3310c3339decSBarry Smith   Logically Collective
3311000e7ae3SMatthew Knepley 
3312000e7ae3SMatthew Knepley   Input Parameters:
3313bcf0153eSBarry Smith + ts   - The `TS` context obtained from `TSCreate()`
3314000e7ae3SMatthew Knepley - func - The function
3315000e7ae3SMatthew Knepley 
331620f4b53cSBarry Smith   Calling sequence of `func`:
331720f4b53cSBarry Smith $ PetscErrorCode func(TS ts)
3318000e7ae3SMatthew Knepley 
3319000e7ae3SMatthew Knepley   Level: intermediate
3320000e7ae3SMatthew Knepley 
3321bcf0153eSBarry Smith   Note:
3322195e9b02SBarry Smith   The function set by `TSSetPostStep()` is called after each successful step. The solution vector
3323bcf0153eSBarry Smith   obtained by `TSGetSolution()` may be different than that computed at the step end if the event handler
3324bcf0153eSBarry Smith   locates an event and `TSPostEvent()` modifies it. Use `TSSetPostEvaluate()` if an unmodified solution is needed instead.
3325bcf0153eSBarry Smith 
3326bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSSetPreStep()`, `TSSetPreStage()`, `TSSetPostEvaluate()`, `TSGetTimeStep()`, `TSGetStepNumber()`, `TSGetTime()`, `TSRestartStep()`
3327000e7ae3SMatthew Knepley @*/
3328d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetPostStep(TS ts, PetscErrorCode (*func)(TS))
3329d71ae5a4SJacob Faibussowitsch {
3330000e7ae3SMatthew Knepley   PetscFunctionBegin;
33310700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3332ae60f76fSBarry Smith   ts->poststep = func;
33333ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
3334000e7ae3SMatthew Knepley }
3335000e7ae3SMatthew Knepley 
333609ee8438SJed Brown /*@
3337195e9b02SBarry Smith   TSPostStep - Runs the user-defined post-step function that was set with `TSSetPostStep()`
33383f2090d5SJed Brown 
3339c3339decSBarry Smith   Collective
33403f2090d5SJed Brown 
33412fe279fdSBarry Smith   Input Parameter:
3342bcf0153eSBarry Smith . ts   - The `TS` context obtained from `TSCreate()`
33433f2090d5SJed Brown 
3344bcf0153eSBarry Smith   Note:
3345bcf0153eSBarry Smith   `TSPostStep()` is typically used within time stepping implementations,
33463f2090d5SJed Brown   so most users would not generally call this routine themselves.
33473f2090d5SJed Brown 
33483f2090d5SJed Brown   Level: developer
33493f2090d5SJed Brown 
3350bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSSetPreStep()`, `TSSetPreStage()`, `TSSetPostEvaluate()`, `TSGetTimeStep()`, `TSGetStepNumber()`, `TSGetTime()`, `TSSetPotsStep()`
33513f2090d5SJed Brown @*/
3352d71ae5a4SJacob Faibussowitsch PetscErrorCode TSPostStep(TS ts)
3353d71ae5a4SJacob Faibussowitsch {
33543f2090d5SJed Brown   PetscFunctionBegin;
33550700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3356ae60f76fSBarry Smith   if (ts->poststep) {
33575efd42a4SStefano Zampini     Vec              U;
3358ef8d1ce0SJohann Rudi     PetscObjectId    idprev;
3359ef8d1ce0SJohann Rudi     PetscBool        sameObject;
33605efd42a4SStefano Zampini     PetscObjectState sprev, spost;
33615efd42a4SStefano Zampini 
33629566063dSJacob Faibussowitsch     PetscCall(TSGetSolution(ts, &U));
33639566063dSJacob Faibussowitsch     PetscCall(PetscObjectGetId((PetscObject)U, &idprev));
33649566063dSJacob Faibussowitsch     PetscCall(PetscObjectStateGet((PetscObject)U, &sprev));
336525e27a38SBarry Smith     PetscCallBack("TS callback poststep", (*ts->poststep)(ts));
33669566063dSJacob Faibussowitsch     PetscCall(TSGetSolution(ts, &U));
33679566063dSJacob Faibussowitsch     PetscCall(PetscObjectCompareId((PetscObject)U, idprev, &sameObject));
33689566063dSJacob Faibussowitsch     PetscCall(PetscObjectStateGet((PetscObject)U, &spost));
33699566063dSJacob Faibussowitsch     if (!sameObject || sprev != spost) PetscCall(TSRestartStep(ts));
337072ac3e02SJed Brown   }
33713ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
33723f2090d5SJed Brown }
33733f2090d5SJed Brown 
3374cd652676SJed Brown /*@
3375cd652676SJed Brown    TSInterpolate - Interpolate the solution computed during the previous step to an arbitrary location in the interval
3376cd652676SJed Brown 
3377c3339decSBarry Smith    Collective
3378cd652676SJed Brown 
33794165533cSJose E. Roman    Input Parameters:
3380cd652676SJed Brown +  ts - time stepping context
3381cd652676SJed Brown -  t - time to interpolate to
3382cd652676SJed Brown 
33834165533cSJose E. Roman    Output Parameter:
33840910c330SBarry Smith .  U - state at given time
3385cd652676SJed Brown 
3386cd652676SJed Brown    Level: intermediate
3387cd652676SJed Brown 
3388bcf0153eSBarry Smith    Developer Note:
3389bcf0153eSBarry Smith    `TSInterpolate()` and the storing of previous steps/stages should be generalized to support delay differential equations and continuous adjoints.
3390cd652676SJed Brown 
3391bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSSetExactFinalTime()`, `TSSolve()`
3392cd652676SJed Brown @*/
3393d71ae5a4SJacob Faibussowitsch PetscErrorCode TSInterpolate(TS ts, PetscReal t, Vec U)
3394d71ae5a4SJacob Faibussowitsch {
3395cd652676SJed Brown   PetscFunctionBegin;
3396cd652676SJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3397b06615a5SLisandro Dalcin   PetscValidHeaderSpecific(U, VEC_CLASSID, 3);
339863a3b9bcSJacob 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);
3399dbbe0bcdSBarry Smith   PetscUseTypeMethod(ts, interpolate, t, U);
34003ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
3401cd652676SJed Brown }
3402cd652676SJed Brown 
3403d763cef2SBarry Smith /*@
34046d9e5789SSean Farley    TSStep - Steps one time step
3405d763cef2SBarry Smith 
3406c3339decSBarry Smith    Collective
3407d763cef2SBarry Smith 
3408d763cef2SBarry Smith    Input Parameter:
3409bcf0153eSBarry Smith .  ts - the `TS` context obtained from `TSCreate()`
3410d763cef2SBarry Smith 
341127829d71SBarry Smith    Level: developer
3412d763cef2SBarry Smith 
3413b8123daeSJed Brown    Notes:
3414bcf0153eSBarry Smith    The public interface for the ODE/DAE solvers is `TSSolve()`, you should almost for sure be using that routine and not this routine.
341527829d71SBarry Smith 
3416bcf0153eSBarry Smith    The hook set using `TSSetPreStep()` is called before each attempt to take the step. In general, the time step size may
3417b8123daeSJed Brown    be changed due to adaptive error controller or solve failures. Note that steps may contain multiple stages.
3418b8123daeSJed Brown 
3419bcf0153eSBarry Smith    This may over-step the final time provided in `TSSetMaxTime()` depending on the time-step used. `TSSolve()` interpolates to exactly the
3420bcf0153eSBarry Smith    time provided in `TSSetMaxTime()`. One can use `TSInterpolate()` to determine an interpolated solution within the final timestep.
342125cb2221SBarry Smith 
3422bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSCreate()`, `TSSetUp()`, `TSDestroy()`, `TSSolve()`, `TSSetPreStep()`, `TSSetPreStage()`, `TSSetPostStage()`, `TSInterpolate()`
3423d763cef2SBarry Smith @*/
3424d71ae5a4SJacob Faibussowitsch PetscErrorCode TSStep(TS ts)
3425d71ae5a4SJacob Faibussowitsch {
3426fffbeea8SBarry Smith   static PetscBool cite = PETSC_FALSE;
3427be5899b3SLisandro Dalcin   PetscReal        ptime;
3428d763cef2SBarry Smith 
3429d763cef2SBarry Smith   PetscFunctionBegin;
34300700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3431d0609cedSBarry Smith   PetscCall(PetscCitationsRegister("@article{tspaper,\n"
3432fffbeea8SBarry Smith                                    "  title         = {{PETSc/TS}: A Modern Scalable {DAE/ODE} Solver Library},\n"
3433f1d62c27SHong Zhang                                    "  author        = {Abhyankar, Shrirang and Brown, Jed and Constantinescu, Emil and Ghosh, Debojyoti and Smith, Barry F. and Zhang, Hong},\n"
3434f1d62c27SHong Zhang                                    "  journal       = {arXiv e-preprints},\n"
3435f1d62c27SHong Zhang                                    "  eprint        = {1806.01437},\n"
3436f1d62c27SHong Zhang                                    "  archivePrefix = {arXiv},\n"
34379371c9d4SSatish Balay                                    "  year          = {2018}\n}\n",
34389371c9d4SSatish Balay                                    &cite));
34399566063dSJacob Faibussowitsch   PetscCall(TSSetUp(ts));
34409566063dSJacob Faibussowitsch   PetscCall(TSTrajectorySetUp(ts->trajectory, ts));
3441d405a339SMatthew Knepley 
34423c633725SBarry 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>");
34433c633725SBarry 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()");
34443c633725SBarry 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");
3445a6772fa2SLisandro Dalcin 
3446be5899b3SLisandro Dalcin   if (!ts->steps) ts->ptime_prev = ts->ptime;
34479371c9d4SSatish Balay   ptime                   = ts->ptime;
34489371c9d4SSatish Balay   ts->ptime_prev_rollback = ts->ptime_prev;
34492808aa04SLisandro Dalcin   ts->reason              = TS_CONVERGED_ITERATING;
3450fc8dbba5SLisandro Dalcin 
34519566063dSJacob Faibussowitsch   PetscCall(PetscLogEventBegin(TS_Step, ts, 0, 0, 0));
3452dbbe0bcdSBarry Smith   PetscUseTypeMethod(ts, step);
34539566063dSJacob Faibussowitsch   PetscCall(PetscLogEventEnd(TS_Step, ts, 0, 0, 0));
3454fc8dbba5SLisandro Dalcin 
34559371c9d4SSatish 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)
34569371c9d4SSatish Balay     PetscCall(VecCopy(ts->vec_sol, ts->tspan->vecs_sol[ts->tspan->spanctr++]));
3457fc8dbba5SLisandro Dalcin   if (ts->reason >= 0) {
3458be5899b3SLisandro Dalcin     ts->ptime_prev = ptime;
34592808aa04SLisandro Dalcin     ts->steps++;
3460be5899b3SLisandro Dalcin     ts->steprollback = PETSC_FALSE;
346128d5b5d6SLisandro Dalcin     ts->steprestart  = PETSC_FALSE;
3462d2daff3dSHong Zhang   }
3463fc8dbba5SLisandro Dalcin   if (!ts->reason) {
346408c7845fSBarry Smith     if (ts->steps >= ts->max_steps) ts->reason = TS_CONVERGED_ITS;
346508c7845fSBarry Smith     else if (ts->ptime >= ts->max_time) ts->reason = TS_CONVERGED_TIME;
346608c7845fSBarry Smith   }
3467fc8dbba5SLisandro Dalcin 
34685c9bbc89SJed Brown   if (ts->reason < 0 && ts->errorifstepfailed) {
34695c9bbc89SJed Brown     PetscCall(TSMonitorCancel(ts));
34705c9bbc89SJed 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]);
34715c9bbc89SJed Brown     SETERRQ(PetscObjectComm((PetscObject)ts), PETSC_ERR_NOT_CONVERGED, "TSStep has failed due to %s", TSConvergedReasons[ts->reason]);
34725c9bbc89SJed Brown   }
34733ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
347408c7845fSBarry Smith }
347508c7845fSBarry Smith 
347608c7845fSBarry Smith /*@
34777cbde773SLisandro Dalcin    TSEvaluateWLTE - Evaluate the weighted local truncation error norm
34787cbde773SLisandro Dalcin    at the end of a time step with a given order of accuracy.
34797cbde773SLisandro Dalcin 
3480c3339decSBarry Smith    Collective
34817cbde773SLisandro Dalcin 
34824165533cSJose E. Roman    Input Parameters:
34837cbde773SLisandro Dalcin +  ts - time stepping context
3484bcf0153eSBarry Smith -  wnormtype - norm type, either `NORM_2` or `NORM_INFINITY`
34857cbde773SLisandro Dalcin 
348697bb3fdcSJose E. Roman    Input/Output Parameter:
3487bcf0153eSBarry Smith .  order - optional, desired order for the error evaluation or `PETSC_DECIDE`;
348897bb3fdcSJose E. Roman            on output, the actual order of the error evaluation
348997bb3fdcSJose E. Roman 
349097bb3fdcSJose E. Roman    Output Parameter:
349197bb3fdcSJose E. Roman .  wlte - the weighted local truncation error norm
34927cbde773SLisandro Dalcin 
34937cbde773SLisandro Dalcin    Level: advanced
34947cbde773SLisandro Dalcin 
3495bcf0153eSBarry Smith    Note:
34967cbde773SLisandro Dalcin    If the timestepper cannot evaluate the error in a particular step
34977cbde773SLisandro Dalcin    (eg. in the first step or restart steps after event handling),
34987cbde773SLisandro Dalcin    this routine returns wlte=-1.0 .
34997cbde773SLisandro Dalcin 
3500bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSStep()`, `TSAdapt`, `TSErrorWeightedNorm()`
35017cbde773SLisandro Dalcin @*/
3502d71ae5a4SJacob Faibussowitsch PetscErrorCode TSEvaluateWLTE(TS ts, NormType wnormtype, PetscInt *order, PetscReal *wlte)
3503d71ae5a4SJacob Faibussowitsch {
35047cbde773SLisandro Dalcin   PetscFunctionBegin;
35057cbde773SLisandro Dalcin   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
35067cbde773SLisandro Dalcin   PetscValidType(ts, 1);
3507064a246eSJacob Faibussowitsch   PetscValidLogicalCollectiveEnum(ts, wnormtype, 2);
35087cbde773SLisandro Dalcin   if (order) PetscValidIntPointer(order, 3);
35097cbde773SLisandro Dalcin   if (order) PetscValidLogicalCollectiveInt(ts, *order, 3);
35107cbde773SLisandro Dalcin   PetscValidRealPointer(wlte, 4);
35113c633725SBarry Smith   PetscCheck(wnormtype == NORM_2 || wnormtype == NORM_INFINITY, PetscObjectComm((PetscObject)ts), PETSC_ERR_SUP, "No support for norm type %s", NormTypes[wnormtype]);
3512dbbe0bcdSBarry Smith   PetscUseTypeMethod(ts, evaluatewlte, wnormtype, order, wlte);
35133ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
35147cbde773SLisandro Dalcin }
35157cbde773SLisandro Dalcin 
351605175c85SJed Brown /*@
351705175c85SJed Brown    TSEvaluateStep - Evaluate the solution at the end of a time step with a given order of accuracy.
351805175c85SJed Brown 
3519c3339decSBarry Smith    Collective
352005175c85SJed Brown 
35214165533cSJose E. Roman    Input Parameters:
35221c3436cfSJed Brown +  ts - time stepping context
35231c3436cfSJed Brown .  order - desired order of accuracy
3524195e9b02SBarry Smith -  done - whether the step was evaluated at this order (pass `NULL` to generate an error if not available)
352505175c85SJed Brown 
35264165533cSJose E. Roman    Output Parameter:
35270910c330SBarry Smith .  U - state at the end of the current step
352805175c85SJed Brown 
352905175c85SJed Brown    Level: advanced
353005175c85SJed Brown 
3531108c343cSJed Brown    Notes:
3532108c343cSJed Brown    This function cannot be called until all stages have been evaluated.
3533108c343cSJed Brown 
3534bcf0153eSBarry 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.
3535bcf0153eSBarry Smith 
3536bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSStep()`, `TSAdapt`
353705175c85SJed Brown @*/
3538d71ae5a4SJacob Faibussowitsch PetscErrorCode TSEvaluateStep(TS ts, PetscInt order, Vec U, PetscBool *done)
3539d71ae5a4SJacob Faibussowitsch {
354005175c85SJed Brown   PetscFunctionBegin;
354105175c85SJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
354205175c85SJed Brown   PetscValidType(ts, 1);
35430910c330SBarry Smith   PetscValidHeaderSpecific(U, VEC_CLASSID, 3);
3544dbbe0bcdSBarry Smith   PetscUseTypeMethod(ts, evaluatestep, order, U, done);
35453ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
354605175c85SJed Brown }
354705175c85SJed Brown 
3548aad739acSMatthew G. Knepley /*@C
35492e61be88SMatthew G. Knepley   TSGetComputeInitialCondition - Get the function used to automatically compute an initial condition for the timestepping.
3550aad739acSMatthew G. Knepley 
3551aad739acSMatthew G. Knepley   Not collective
3552aad739acSMatthew G. Knepley 
35534165533cSJose E. Roman   Input Parameter:
3554aad739acSMatthew G. Knepley . ts - time stepping context
3555aad739acSMatthew G. Knepley 
35564165533cSJose E. Roman   Output Parameter:
35572e61be88SMatthew G. Knepley . initConditions - The function which computes an initial condition
3558aad739acSMatthew G. Knepley 
355920f4b53cSBarry Smith   Calling sequence of `initCondition`:
3560bcf0153eSBarry Smith .vb
356120f4b53cSBarry Smith   PetscErrorCode initCondition(TS ts, Vec u)
3562bcf0153eSBarry Smith .ve
356320f4b53cSBarry Smith + ts - The timestepping context
356420f4b53cSBarry Smith - u  - The input vector in which the initial condition is stored
3565bcf0153eSBarry Smith 
3566aad739acSMatthew G. Knepley    Level: advanced
3567aad739acSMatthew G. Knepley 
3568bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSSetComputeInitialCondition()`, `TSComputeInitialCondition()`
3569aad739acSMatthew G. Knepley @*/
3570d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetComputeInitialCondition(TS ts, PetscErrorCode (**initCondition)(TS, Vec))
3571d71ae5a4SJacob Faibussowitsch {
3572aad739acSMatthew G. Knepley   PetscFunctionBegin;
3573aad739acSMatthew G. Knepley   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
35742e61be88SMatthew G. Knepley   PetscValidPointer(initCondition, 2);
35752e61be88SMatthew G. Knepley   *initCondition = ts->ops->initcondition;
35763ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
3577aad739acSMatthew G. Knepley }
3578aad739acSMatthew G. Knepley 
3579aad739acSMatthew G. Knepley /*@C
35802e61be88SMatthew G. Knepley   TSSetComputeInitialCondition - Set the function used to automatically compute an initial condition for the timestepping.
3581aad739acSMatthew G. Knepley 
3582c3339decSBarry Smith   Logically collective
3583aad739acSMatthew G. Knepley 
35844165533cSJose E. Roman   Input Parameters:
3585aad739acSMatthew G. Knepley + ts  - time stepping context
35862e61be88SMatthew G. Knepley - initCondition - The function which computes an initial condition
3587aad739acSMatthew G. Knepley 
358820f4b53cSBarry Smith   Calling sequence of `initCondition`:
3589a96d6ef6SBarry Smith $ PetscErrorCode initCondition(TS ts, Vec u)
3590a96d6ef6SBarry Smith + ts - The timestepping context
3591a96d6ef6SBarry Smith - u  - The input vector in which the initial condition is to be stored
3592aad739acSMatthew G. Knepley 
3593bcf0153eSBarry Smith   Level: advanced
3594bcf0153eSBarry Smith 
3595bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSGetComputeInitialCondition()`, `TSComputeInitialCondition()`
3596aad739acSMatthew G. Knepley @*/
3597d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetComputeInitialCondition(TS ts, PetscErrorCode (*initCondition)(TS, Vec))
3598d71ae5a4SJacob Faibussowitsch {
3599aad739acSMatthew G. Knepley   PetscFunctionBegin;
3600aad739acSMatthew G. Knepley   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
36012e61be88SMatthew G. Knepley   PetscValidFunction(initCondition, 2);
36022e61be88SMatthew G. Knepley   ts->ops->initcondition = initCondition;
36033ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
3604aad739acSMatthew G. Knepley }
3605aad739acSMatthew G. Knepley 
3606aad739acSMatthew G. Knepley /*@
3607bcf0153eSBarry Smith   TSComputeInitialCondition - Compute an initial condition for the timestepping using the function previously set with `TSSetComputeInitialCondition()`
3608aad739acSMatthew G. Knepley 
3609c3339decSBarry Smith   Collective
3610aad739acSMatthew G. Knepley 
36114165533cSJose E. Roman   Input Parameters:
3612aad739acSMatthew G. Knepley + ts - time stepping context
3613bcf0153eSBarry Smith - u  - The `Vec` to store the condition in which will be used in `TSSolve()`
3614aad739acSMatthew G. Knepley 
3615aad739acSMatthew G. Knepley   Level: advanced
3616aad739acSMatthew G. Knepley 
3617bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSGetComputeInitialCondition()`, `TSSetComputeInitialCondition()`, `TSSolve()`
3618aad739acSMatthew G. Knepley @*/
3619d71ae5a4SJacob Faibussowitsch PetscErrorCode TSComputeInitialCondition(TS ts, Vec u)
3620d71ae5a4SJacob Faibussowitsch {
3621aad739acSMatthew G. Knepley   PetscFunctionBegin;
3622aad739acSMatthew G. Knepley   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3623aad739acSMatthew G. Knepley   PetscValidHeaderSpecific(u, VEC_CLASSID, 2);
3624dbbe0bcdSBarry Smith   PetscTryTypeMethod(ts, initcondition, u);
36253ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
3626aad739acSMatthew G. Knepley }
3627aad739acSMatthew G. Knepley 
3628aad739acSMatthew G. Knepley /*@C
3629aad739acSMatthew G. Knepley   TSGetComputeExactError - Get the function used to automatically compute the exact error for the timestepping.
3630aad739acSMatthew G. Knepley 
3631aad739acSMatthew G. Knepley   Not collective
3632aad739acSMatthew G. Knepley 
36334165533cSJose E. Roman   Input Parameter:
3634aad739acSMatthew G. Knepley . ts - time stepping context
3635aad739acSMatthew G. Knepley 
36364165533cSJose E. Roman   Output Parameter:
3637aad739acSMatthew G. Knepley . exactError - The function which computes the solution error
3638aad739acSMatthew G. Knepley 
363920f4b53cSBarry Smith   Calling sequence of `exactError`:
364020f4b53cSBarry Smith $ PetscErrorCode exactError(TS ts, Vec u, Vec e)
3641a96d6ef6SBarry Smith + ts - The timestepping context
3642a96d6ef6SBarry Smith . u  - The approximate solution vector
364320f4b53cSBarry Smith - e  - The vector in which the error is stored
3644aad739acSMatthew G. Knepley 
3645bcf0153eSBarry Smith   Level: advanced
3646bcf0153eSBarry Smith 
3647bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSGetComputeExactError()`, `TSComputeExactError()`
3648aad739acSMatthew G. Knepley @*/
3649d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetComputeExactError(TS ts, PetscErrorCode (**exactError)(TS, Vec, Vec))
3650d71ae5a4SJacob Faibussowitsch {
3651aad739acSMatthew G. Knepley   PetscFunctionBegin;
3652aad739acSMatthew G. Knepley   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3653aad739acSMatthew G. Knepley   PetscValidPointer(exactError, 2);
3654aad739acSMatthew G. Knepley   *exactError = ts->ops->exacterror;
36553ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
3656aad739acSMatthew G. Knepley }
3657aad739acSMatthew G. Knepley 
3658aad739acSMatthew G. Knepley /*@C
3659aad739acSMatthew G. Knepley   TSSetComputeExactError - Set the function used to automatically compute the exact error for the timestepping.
3660aad739acSMatthew G. Knepley 
3661c3339decSBarry Smith   Logically collective
3662aad739acSMatthew G. Knepley 
36634165533cSJose E. Roman   Input Parameters:
3664aad739acSMatthew G. Knepley + ts - time stepping context
3665aad739acSMatthew G. Knepley - exactError - The function which computes the solution error
3666aad739acSMatthew G. Knepley 
366720f4b53cSBarry Smith   Calling sequence of `exactError`:
3668a96d6ef6SBarry Smith $ PetscErrorCode exactError(TS ts, Vec u)
3669a96d6ef6SBarry Smith + ts - The timestepping context
3670a96d6ef6SBarry Smith . u  - The approximate solution vector
367120f4b53cSBarry Smith - e  - The  vector in which the error is stored
3672aad739acSMatthew G. Knepley 
3673bcf0153eSBarry Smith   Level: advanced
3674bcf0153eSBarry Smith 
3675bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSGetComputeExactError()`, `TSComputeExactError()`
3676aad739acSMatthew G. Knepley @*/
3677d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetComputeExactError(TS ts, PetscErrorCode (*exactError)(TS, Vec, Vec))
3678d71ae5a4SJacob Faibussowitsch {
3679aad739acSMatthew G. Knepley   PetscFunctionBegin;
3680aad739acSMatthew G. Knepley   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3681f907fdbfSMatthew G. Knepley   PetscValidFunction(exactError, 2);
3682aad739acSMatthew G. Knepley   ts->ops->exacterror = exactError;
36833ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
3684aad739acSMatthew G. Knepley }
3685aad739acSMatthew G. Knepley 
3686aad739acSMatthew G. Knepley /*@
3687bcf0153eSBarry Smith   TSComputeExactError - Compute the solution error for the timestepping using the function previously set with `TSSetComputeExactError()`
3688aad739acSMatthew G. Knepley 
3689c3339decSBarry Smith   Collective
3690aad739acSMatthew G. Knepley 
36914165533cSJose E. Roman   Input Parameters:
3692aad739acSMatthew G. Knepley + ts - time stepping context
3693aad739acSMatthew G. Knepley . u  - The approximate solution
3694bcf0153eSBarry Smith - e  - The `Vec` used to store the error
3695aad739acSMatthew G. Knepley 
3696aad739acSMatthew G. Knepley   Level: advanced
3697aad739acSMatthew G. Knepley 
3698bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSGetComputeInitialCondition()`, `TSSetComputeInitialCondition()`, `TSSolve()`
3699aad739acSMatthew G. Knepley @*/
3700d71ae5a4SJacob Faibussowitsch PetscErrorCode TSComputeExactError(TS ts, Vec u, Vec e)
3701d71ae5a4SJacob Faibussowitsch {
3702aad739acSMatthew G. Knepley   PetscFunctionBegin;
3703aad739acSMatthew G. Knepley   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3704aad739acSMatthew G. Knepley   PetscValidHeaderSpecific(u, VEC_CLASSID, 2);
3705aad739acSMatthew G. Knepley   PetscValidHeaderSpecific(e, VEC_CLASSID, 3);
3706dbbe0bcdSBarry Smith   PetscTryTypeMethod(ts, exacterror, u, e);
37073ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
3708aad739acSMatthew G. Knepley }
3709aad739acSMatthew G. Knepley 
3710b1cb36f3SHong Zhang /*@
37116a4d4014SLisandro Dalcin    TSSolve - Steps the requested number of timesteps.
37126a4d4014SLisandro Dalcin 
3713c3339decSBarry Smith    Collective
37146a4d4014SLisandro Dalcin 
3715d8d19677SJose E. Roman    Input Parameters:
3716bcf0153eSBarry Smith +  ts - the `TS` context obtained from `TSCreate()`
3717bcf0153eSBarry Smith -  u - the solution vector  (can be null if `TSSetSolution()` was used and `TSSetExactFinalTime`(ts,`TS_EXACTFINALTIME_MATCHSTEP`) was not used,
371863e21af5SBarry Smith                              otherwise must contain the initial conditions and will contain the solution at the final requested time
37195a3a76d0SJed Brown 
37206a4d4014SLisandro Dalcin    Level: beginner
37216a4d4014SLisandro Dalcin 
37225a3a76d0SJed Brown    Notes:
37235a3a76d0SJed Brown    The final time returned by this function may be different from the time of the internally
3724bcf0153eSBarry Smith    held state accessible by `TSGetSolution()` and `TSGetTime()` because the method may have
37255a3a76d0SJed Brown    stepped over the final time.
37265a3a76d0SJed Brown 
3727bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSCreate()`, `TSSetSolution()`, `TSStep()`, `TSGetTime()`, `TSGetSolveTime()`
37286a4d4014SLisandro Dalcin @*/
3729d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSolve(TS ts, Vec u)
3730d71ae5a4SJacob Faibussowitsch {
3731b06615a5SLisandro Dalcin   Vec solution;
3732f22f69f0SBarry Smith 
37336a4d4014SLisandro Dalcin   PetscFunctionBegin;
37340700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3735f2c2a1b9SBarry Smith   if (u) PetscValidHeaderSpecific(u, VEC_CLASSID, 2);
3736303a5415SBarry Smith 
37379566063dSJacob Faibussowitsch   PetscCall(TSSetExactFinalTimeDefault(ts));
3738ee41a567SStefano 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 */
37390910c330SBarry Smith     if (!ts->vec_sol || u == ts->vec_sol) {
37409566063dSJacob Faibussowitsch       PetscCall(VecDuplicate(u, &solution));
37419566063dSJacob Faibussowitsch       PetscCall(TSSetSolution(ts, solution));
37429566063dSJacob Faibussowitsch       PetscCall(VecDestroy(&solution)); /* grant ownership */
37435a3a76d0SJed Brown     }
37449566063dSJacob Faibussowitsch     PetscCall(VecCopy(u, ts->vec_sol));
37453c633725SBarry Smith     PetscCheck(!ts->forward_solve, PetscObjectComm((PetscObject)ts), PETSC_ERR_SUP, "Sensitivity analysis does not support the mode TS_EXACTFINALTIME_INTERPOLATE");
37461baa6e33SBarry Smith   } else if (u) PetscCall(TSSetSolution(ts, u));
37479566063dSJacob Faibussowitsch   PetscCall(TSSetUp(ts));
37489566063dSJacob Faibussowitsch   PetscCall(TSTrajectorySetUp(ts->trajectory, ts));
3749a6772fa2SLisandro Dalcin 
37503c633725SBarry 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>");
37513c633725SBarry 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()");
37523c633725SBarry 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");
37534a658b32SHong 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");
37544a658b32SHong Zhang 
3755e1db57b0SHong 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 */
37564a658b32SHong Zhang     PetscCall(VecCopy(ts->vec_sol, ts->tspan->vecs_sol[0]));
37574a658b32SHong Zhang     ts->tspan->spanctr = 1;
37584a658b32SHong Zhang   }
3759a6772fa2SLisandro Dalcin 
37601baa6e33SBarry Smith   if (ts->forward_solve) PetscCall(TSForwardSetUp(ts));
3761715f1b00SHong Zhang 
3762e7069c78SShri   /* reset number of steps only when the step is not restarted. ARKIMEX
3763715f1b00SHong Zhang      restarts the step after an event. Resetting these counters in such case causes
3764e7069c78SShri      TSTrajectory to incorrectly save the output files
3765e7069c78SShri   */
3766715f1b00SHong Zhang   /* reset time step and iteration counters */
37672808aa04SLisandro Dalcin   if (!ts->steps) {
37685ef26d82SJed Brown     ts->ksp_its           = 0;
37695ef26d82SJed Brown     ts->snes_its          = 0;
3770c610991cSLisandro Dalcin     ts->num_snes_failures = 0;
3771c610991cSLisandro Dalcin     ts->reject            = 0;
37722808aa04SLisandro Dalcin     ts->steprestart       = PETSC_TRUE;
37732808aa04SLisandro Dalcin     ts->steprollback      = PETSC_FALSE;
37747d51462cSStefano Zampini     ts->rhsjacobian.time  = PETSC_MIN_REAL;
37752808aa04SLisandro Dalcin   }
3776e97c63d7SStefano Zampini 
37774a658b32SHong Zhang   /* make sure initial time step does not overshoot final time or the next point in tspan */
3778e97c63d7SStefano Zampini   if (ts->exact_final_time == TS_EXACTFINALTIME_MATCHSTEP) {
37794a658b32SHong Zhang     PetscReal maxdt;
3780e97c63d7SStefano Zampini     PetscReal dt = ts->time_step;
3781e97c63d7SStefano Zampini 
37824a658b32SHong Zhang     if (ts->tspan) maxdt = ts->tspan->span_times[ts->tspan->spanctr] - ts->ptime;
37834a658b32SHong Zhang     else maxdt = ts->max_time - ts->ptime;
3784e97c63d7SStefano Zampini     ts->time_step = dt >= maxdt ? maxdt : (PetscIsCloseAtTol(dt, maxdt, 10 * PETSC_MACHINE_EPSILON, 0) ? maxdt : dt);
3785e97c63d7SStefano Zampini   }
3786193ac0bcSJed Brown   ts->reason = TS_CONVERGED_ITERATING;
3787193ac0bcSJed Brown 
3788900f6b5bSMatthew G. Knepley   {
3789900f6b5bSMatthew G. Knepley     PetscViewer       viewer;
3790900f6b5bSMatthew G. Knepley     PetscViewerFormat format;
3791900f6b5bSMatthew G. Knepley     PetscBool         flg;
3792900f6b5bSMatthew G. Knepley     static PetscBool  incall = PETSC_FALSE;
3793900f6b5bSMatthew G. Knepley 
3794900f6b5bSMatthew G. Knepley     if (!incall) {
3795900f6b5bSMatthew G. Knepley       /* Estimate the convergence rate of the time discretization */
37969566063dSJacob Faibussowitsch       PetscCall(PetscOptionsGetViewer(PetscObjectComm((PetscObject)ts), ((PetscObject)ts)->options, ((PetscObject)ts)->prefix, "-ts_convergence_estimate", &viewer, &format, &flg));
3797900f6b5bSMatthew G. Knepley       if (flg) {
3798900f6b5bSMatthew G. Knepley         PetscConvEst conv;
3799900f6b5bSMatthew G. Knepley         DM           dm;
3800900f6b5bSMatthew G. Knepley         PetscReal   *alpha; /* Convergence rate of the solution error for each field in the L_2 norm */
3801900f6b5bSMatthew G. Knepley         PetscInt     Nf;
3802f2ed2dc7SMatthew G. Knepley         PetscBool    checkTemporal = PETSC_TRUE;
3803900f6b5bSMatthew G. Knepley 
3804900f6b5bSMatthew G. Knepley         incall = PETSC_TRUE;
38059566063dSJacob Faibussowitsch         PetscCall(PetscOptionsGetBool(((PetscObject)ts)->options, ((PetscObject)ts)->prefix, "-ts_convergence_temporal", &checkTemporal, &flg));
38069566063dSJacob Faibussowitsch         PetscCall(TSGetDM(ts, &dm));
38079566063dSJacob Faibussowitsch         PetscCall(DMGetNumFields(dm, &Nf));
38089566063dSJacob Faibussowitsch         PetscCall(PetscCalloc1(PetscMax(Nf, 1), &alpha));
38099566063dSJacob Faibussowitsch         PetscCall(PetscConvEstCreate(PetscObjectComm((PetscObject)ts), &conv));
38109566063dSJacob Faibussowitsch         PetscCall(PetscConvEstUseTS(conv, checkTemporal));
38119566063dSJacob Faibussowitsch         PetscCall(PetscConvEstSetSolver(conv, (PetscObject)ts));
38129566063dSJacob Faibussowitsch         PetscCall(PetscConvEstSetFromOptions(conv));
38139566063dSJacob Faibussowitsch         PetscCall(PetscConvEstSetUp(conv));
38149566063dSJacob Faibussowitsch         PetscCall(PetscConvEstGetConvRate(conv, alpha));
38159566063dSJacob Faibussowitsch         PetscCall(PetscViewerPushFormat(viewer, format));
38169566063dSJacob Faibussowitsch         PetscCall(PetscConvEstRateView(conv, alpha, viewer));
38179566063dSJacob Faibussowitsch         PetscCall(PetscViewerPopFormat(viewer));
38189566063dSJacob Faibussowitsch         PetscCall(PetscViewerDestroy(&viewer));
38199566063dSJacob Faibussowitsch         PetscCall(PetscConvEstDestroy(&conv));
38209566063dSJacob Faibussowitsch         PetscCall(PetscFree(alpha));
3821900f6b5bSMatthew G. Knepley         incall = PETSC_FALSE;
3822900f6b5bSMatthew G. Knepley       }
3823900f6b5bSMatthew G. Knepley     }
3824900f6b5bSMatthew G. Knepley   }
3825900f6b5bSMatthew G. Knepley 
38269566063dSJacob Faibussowitsch   PetscCall(TSViewFromOptions(ts, NULL, "-ts_view_pre"));
3827f05ece33SBarry Smith 
3828193ac0bcSJed Brown   if (ts->ops->solve) { /* This private interface is transitional and should be removed when all implementations are updated. */
3829dbbe0bcdSBarry Smith     PetscUseTypeMethod(ts, solve);
38309566063dSJacob Faibussowitsch     if (u) PetscCall(VecCopy(ts->vec_sol, u));
3831cc708dedSBarry Smith     ts->solvetime = ts->ptime;
3832a6772fa2SLisandro Dalcin     solution      = ts->vec_sol;
3833be5899b3SLisandro Dalcin   } else { /* Step the requested number of timesteps. */
3834db4deed7SKarl Rupp     if (ts->steps >= ts->max_steps) ts->reason = TS_CONVERGED_ITS;
3835db4deed7SKarl Rupp     else if (ts->ptime >= ts->max_time) ts->reason = TS_CONVERGED_TIME;
3836e7069c78SShri 
38372808aa04SLisandro Dalcin     if (!ts->steps) {
38389566063dSJacob Faibussowitsch       PetscCall(TSTrajectorySet(ts->trajectory, ts, ts->steps, ts->ptime, ts->vec_sol));
38399566063dSJacob Faibussowitsch       PetscCall(TSEventInitialize(ts->event, ts, ts->ptime, ts->vec_sol));
38402808aa04SLisandro Dalcin     }
38416427ac75SLisandro Dalcin 
3842e1a7a14fSJed Brown     while (!ts->reason) {
38439566063dSJacob Faibussowitsch       PetscCall(TSMonitor(ts, ts->steps, ts->ptime, ts->vec_sol));
38441e66621cSBarry Smith       if (!ts->steprollback) PetscCall(TSPreStep(ts));
38459566063dSJacob Faibussowitsch       PetscCall(TSStep(ts));
38461baa6e33SBarry Smith       if (ts->testjacobian) PetscCall(TSRHSJacobianTest(ts, NULL));
38471baa6e33SBarry Smith       if (ts->testjacobiantranspose) PetscCall(TSRHSJacobianTestTranspose(ts, NULL));
3848cd4cee2dSHong Zhang       if (ts->quadraturets && ts->costintegralfwd) { /* Must evaluate the cost integral before event is handled. The cost integral value can also be rolled back. */
38497b0e2f17SHong Zhang         if (ts->reason >= 0) ts->steps--;            /* Revert the step number changed by TSStep() */
38509566063dSJacob Faibussowitsch         PetscCall(TSForwardCostIntegral(ts));
38517b0e2f17SHong Zhang         if (ts->reason >= 0) ts->steps++;
3852b1cb36f3SHong Zhang       }
385358818c2dSLisandro Dalcin       if (ts->forward_solve) {            /* compute forward sensitivities before event handling because postevent() may change RHS and jump conditions may have to be applied */
38547b0e2f17SHong Zhang         if (ts->reason >= 0) ts->steps--; /* Revert the step number changed by TSStep() */
38559566063dSJacob Faibussowitsch         PetscCall(TSForwardStep(ts));
38567b0e2f17SHong Zhang         if (ts->reason >= 0) ts->steps++;
3857715f1b00SHong Zhang       }
38589566063dSJacob Faibussowitsch       PetscCall(TSPostEvaluate(ts));
38599566063dSJacob 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. */
38601baa6e33SBarry Smith       if (ts->steprollback) PetscCall(TSPostEvaluate(ts));
3861e783b05fSHong Zhang       if (!ts->steprollback) {
38629566063dSJacob Faibussowitsch         PetscCall(TSTrajectorySet(ts->trajectory, ts, ts->steps, ts->ptime, ts->vec_sol));
38639566063dSJacob Faibussowitsch         PetscCall(TSPostStep(ts));
3864aeb4809dSShri Abhyankar       }
3865193ac0bcSJed Brown     }
38669566063dSJacob Faibussowitsch     PetscCall(TSMonitor(ts, ts->steps, ts->ptime, ts->vec_sol));
38676427ac75SLisandro Dalcin 
386849354f04SShri Abhyankar     if (ts->exact_final_time == TS_EXACTFINALTIME_INTERPOLATE && ts->ptime > ts->max_time) {
38699566063dSJacob Faibussowitsch       PetscCall(TSInterpolate(ts, ts->max_time, u));
3870cc708dedSBarry Smith       ts->solvetime = ts->max_time;
3871b06615a5SLisandro Dalcin       solution      = u;
38729566063dSJacob Faibussowitsch       PetscCall(TSMonitor(ts, -1, ts->solvetime, solution));
38730574a7fbSJed Brown     } else {
38749566063dSJacob Faibussowitsch       if (u) PetscCall(VecCopy(ts->vec_sol, u));
3875cc708dedSBarry Smith       ts->solvetime = ts->ptime;
3876b06615a5SLisandro Dalcin       solution      = ts->vec_sol;
38770574a7fbSJed Brown     }
3878193ac0bcSJed Brown   }
3879d2daff3dSHong Zhang 
38809566063dSJacob Faibussowitsch   PetscCall(TSViewFromOptions(ts, NULL, "-ts_view"));
38819566063dSJacob Faibussowitsch   PetscCall(VecViewFromOptions(solution, (PetscObject)ts, "-ts_view_solution"));
38829566063dSJacob Faibussowitsch   PetscCall(PetscObjectSAWsBlock((PetscObject)ts));
38831baa6e33SBarry Smith   if (ts->adjoint_solve) PetscCall(TSAdjointSolve(ts));
38843ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
38856a4d4014SLisandro Dalcin }
38866a4d4014SLisandro Dalcin 
3887d763cef2SBarry Smith /*@
3888b8123daeSJed Brown    TSGetTime - Gets the time of the most recently completed step.
3889d763cef2SBarry Smith 
3890d763cef2SBarry Smith    Not Collective
3891d763cef2SBarry Smith 
3892d763cef2SBarry Smith    Input Parameter:
3893bcf0153eSBarry Smith .  ts - the `TS` context obtained from `TSCreate()`
3894d763cef2SBarry Smith 
3895d763cef2SBarry Smith    Output Parameter:
3896bcf0153eSBarry Smith .  t  - the current time. This time may not corresponds to the final time set with `TSSetMaxTime()`, use `TSGetSolveTime()`.
3897d763cef2SBarry Smith 
3898d763cef2SBarry Smith    Level: beginner
3899d763cef2SBarry Smith 
3900b8123daeSJed Brown    Note:
3901bcf0153eSBarry Smith    When called during time step evaluation (e.g. during residual evaluation or via hooks set using `TSSetPreStep()`,
3902bcf0153eSBarry Smith    `TSSetPreStage()`, `TSSetPostStage()`, or `TSSetPostStep()`), the time is the time at the start of the step being evaluated.
3903b8123daeSJed Brown 
3904bcf0153eSBarry Smith .seealso: [](chapter_ts), TS`, ``TSGetSolveTime()`, `TSSetTime()`, `TSGetTimeStep()`, `TSGetStepNumber()`
3905d763cef2SBarry Smith @*/
3906d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetTime(TS ts, PetscReal *t)
3907d71ae5a4SJacob Faibussowitsch {
3908d763cef2SBarry Smith   PetscFunctionBegin;
39090700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3910f7cf8827SBarry Smith   PetscValidRealPointer(t, 2);
3911d763cef2SBarry Smith   *t = ts->ptime;
39123ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
3913d763cef2SBarry Smith }
3914d763cef2SBarry Smith 
3915e5e524a1SHong Zhang /*@
3916e5e524a1SHong Zhang    TSGetPrevTime - Gets the starting time of the previously completed step.
3917e5e524a1SHong Zhang 
3918e5e524a1SHong Zhang    Not Collective
3919e5e524a1SHong Zhang 
3920e5e524a1SHong Zhang    Input Parameter:
3921bcf0153eSBarry Smith .  ts - the `TS` context obtained from `TSCreate()`
3922e5e524a1SHong Zhang 
3923e5e524a1SHong Zhang    Output Parameter:
3924e5e524a1SHong Zhang .  t  - the previous time
3925e5e524a1SHong Zhang 
3926e5e524a1SHong Zhang    Level: beginner
3927e5e524a1SHong Zhang 
3928bcf0153eSBarry Smith .seealso: [](chapter_ts), TS`, ``TSGetTime()`, `TSGetSolveTime()`, `TSGetTimeStep()`
3929e5e524a1SHong Zhang @*/
3930d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetPrevTime(TS ts, PetscReal *t)
3931d71ae5a4SJacob Faibussowitsch {
3932e5e524a1SHong Zhang   PetscFunctionBegin;
3933e5e524a1SHong Zhang   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3934e5e524a1SHong Zhang   PetscValidRealPointer(t, 2);
3935e5e524a1SHong Zhang   *t = ts->ptime_prev;
39363ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
3937e5e524a1SHong Zhang }
3938e5e524a1SHong Zhang 
39396a4d4014SLisandro Dalcin /*@
39406a4d4014SLisandro Dalcin    TSSetTime - Allows one to reset the time.
39416a4d4014SLisandro Dalcin 
3942c3339decSBarry Smith    Logically Collective
39436a4d4014SLisandro Dalcin 
39446a4d4014SLisandro Dalcin    Input Parameters:
3945bcf0153eSBarry Smith +  ts - the `TS` context obtained from `TSCreate()`
39466a4d4014SLisandro Dalcin -  time - the time
39476a4d4014SLisandro Dalcin 
39486a4d4014SLisandro Dalcin    Level: intermediate
39496a4d4014SLisandro Dalcin 
3950bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSGetTime()`, `TSSetMaxSteps()`
39516a4d4014SLisandro Dalcin @*/
3952d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetTime(TS ts, PetscReal t)
3953d71ae5a4SJacob Faibussowitsch {
39546a4d4014SLisandro Dalcin   PetscFunctionBegin;
39550700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3956c5eb9154SBarry Smith   PetscValidLogicalCollectiveReal(ts, t, 2);
39576a4d4014SLisandro Dalcin   ts->ptime = t;
39583ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
39596a4d4014SLisandro Dalcin }
39606a4d4014SLisandro Dalcin 
3961d763cef2SBarry Smith /*@C
3962d763cef2SBarry Smith    TSSetOptionsPrefix - Sets the prefix used for searching for all
3963d763cef2SBarry Smith    TS options in the database.
3964d763cef2SBarry Smith 
3965c3339decSBarry Smith    Logically Collective
3966d763cef2SBarry Smith 
3967d8d19677SJose E. Roman    Input Parameters:
3968bcf0153eSBarry Smith +  ts     - The `TS` context
3969d763cef2SBarry Smith -  prefix - The prefix to prepend to all option names
3970d763cef2SBarry Smith 
3971bcf0153eSBarry Smith    Level: advanced
3972bcf0153eSBarry Smith 
3973bcf0153eSBarry Smith    Note:
3974d763cef2SBarry Smith    A hyphen (-) must NOT be given at the beginning of the prefix name.
3975d763cef2SBarry Smith    The first character of all runtime options is AUTOMATICALLY the
3976d763cef2SBarry Smith    hyphen.
3977d763cef2SBarry Smith 
3978bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSSetFromOptions()`, `TSAppendOptionsPrefix()`
3979d763cef2SBarry Smith @*/
3980d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetOptionsPrefix(TS ts, const char prefix[])
3981d71ae5a4SJacob Faibussowitsch {
3982089b2837SJed Brown   SNES snes;
3983d763cef2SBarry Smith 
3984d763cef2SBarry Smith   PetscFunctionBegin;
39850700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
39869566063dSJacob Faibussowitsch   PetscCall(PetscObjectSetOptionsPrefix((PetscObject)ts, prefix));
39879566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts, &snes));
39889566063dSJacob Faibussowitsch   PetscCall(SNESSetOptionsPrefix(snes, prefix));
39893ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
3990d763cef2SBarry Smith }
3991d763cef2SBarry Smith 
3992d763cef2SBarry Smith /*@C
3993d763cef2SBarry Smith    TSAppendOptionsPrefix - Appends to the prefix used for searching for all
3994d763cef2SBarry Smith    TS options in the database.
3995d763cef2SBarry Smith 
3996c3339decSBarry Smith    Logically Collective
3997d763cef2SBarry Smith 
3998d8d19677SJose E. Roman    Input Parameters:
3999bcf0153eSBarry Smith +  ts     - The `TS` context
4000d763cef2SBarry Smith -  prefix - The prefix to prepend to all option names
4001d763cef2SBarry Smith 
4002bcf0153eSBarry Smith    Level: advanced
4003bcf0153eSBarry Smith 
4004bcf0153eSBarry Smith    Note:
4005d763cef2SBarry Smith    A hyphen (-) must NOT be given at the beginning of the prefix name.
4006d763cef2SBarry Smith    The first character of all runtime options is AUTOMATICALLY the
4007d763cef2SBarry Smith    hyphen.
4008d763cef2SBarry Smith 
4009bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSGetOptionsPrefix()`, `TSSetOptionsPrefix()`, `TSSetFromOptions()`
4010d763cef2SBarry Smith @*/
4011d71ae5a4SJacob Faibussowitsch PetscErrorCode TSAppendOptionsPrefix(TS ts, const char prefix[])
4012d71ae5a4SJacob Faibussowitsch {
4013089b2837SJed Brown   SNES snes;
4014d763cef2SBarry Smith 
4015d763cef2SBarry Smith   PetscFunctionBegin;
40160700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
40179566063dSJacob Faibussowitsch   PetscCall(PetscObjectAppendOptionsPrefix((PetscObject)ts, prefix));
40189566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts, &snes));
40199566063dSJacob Faibussowitsch   PetscCall(SNESAppendOptionsPrefix(snes, prefix));
40203ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
4021d763cef2SBarry Smith }
4022d763cef2SBarry Smith 
4023d763cef2SBarry Smith /*@C
4024d763cef2SBarry Smith    TSGetOptionsPrefix - Sets the prefix used for searching for all
4025bcf0153eSBarry Smith    `TS` options in the database.
4026d763cef2SBarry Smith 
4027d763cef2SBarry Smith    Not Collective
4028d763cef2SBarry Smith 
4029d763cef2SBarry Smith    Input Parameter:
4030bcf0153eSBarry Smith .  ts - The `TS` context
4031d763cef2SBarry Smith 
4032d763cef2SBarry Smith    Output Parameter:
4033d763cef2SBarry Smith .  prefix - A pointer to the prefix string used
4034d763cef2SBarry Smith 
4035d763cef2SBarry Smith    Level: intermediate
4036d763cef2SBarry Smith 
4037bcf0153eSBarry Smith    Fortran Note:
4038195e9b02SBarry Smith    The user should pass in a string 'prefix' of
4039bcf0153eSBarry Smith    sufficient length to hold the prefix.
4040bcf0153eSBarry Smith 
4041bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSAppendOptionsPrefix()`, `TSSetFromOptions()`
4042d763cef2SBarry Smith @*/
4043d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetOptionsPrefix(TS ts, const char *prefix[])
4044d71ae5a4SJacob Faibussowitsch {
4045d763cef2SBarry Smith   PetscFunctionBegin;
40460700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
40474482741eSBarry Smith   PetscValidPointer(prefix, 2);
40489566063dSJacob Faibussowitsch   PetscCall(PetscObjectGetOptionsPrefix((PetscObject)ts, prefix));
40493ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
4050d763cef2SBarry Smith }
4051d763cef2SBarry Smith 
4052d763cef2SBarry Smith /*@C
4053d763cef2SBarry Smith    TSGetRHSJacobian - Returns the Jacobian J at the present timestep.
4054d763cef2SBarry Smith 
4055bcf0153eSBarry Smith    Not Collective, but parallel objects are returned if ts is parallel
4056d763cef2SBarry Smith 
4057d763cef2SBarry Smith    Input Parameter:
4058bcf0153eSBarry Smith .  ts  - The `TS` context obtained from `TSCreate()`
4059d763cef2SBarry Smith 
4060d763cef2SBarry Smith    Output Parameters:
4061195e9b02SBarry Smith +  Amat - The (approximate) Jacobian J of G, where U_t = G(U,t)  (or `NULL`)
4062195e9b02SBarry Smith .  Pmat - The matrix from which the preconditioner is constructed, usually the same as `Amat`  (or `NULL`)
4063195e9b02SBarry Smith .  func - Function to compute the Jacobian of the RHS  (or `NULL`)
4064195e9b02SBarry Smith -  ctx - User-defined context for Jacobian evaluation routine  (or `NULL`)
4065d763cef2SBarry Smith 
4066d763cef2SBarry Smith    Level: intermediate
4067d763cef2SBarry Smith 
4068bcf0153eSBarry Smith    Note:
4069195e9b02SBarry Smith     You can pass in `NULL` for any return argument you do not need.
4070bcf0153eSBarry Smith 
4071bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSGetTimeStep()`, `TSGetMatrices()`, `TSGetTime()`, `TSGetStepNumber()`
4072d763cef2SBarry Smith 
4073d763cef2SBarry Smith @*/
4074d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetRHSJacobian(TS ts, Mat *Amat, Mat *Pmat, TSRHSJacobian *func, void **ctx)
4075d71ae5a4SJacob Faibussowitsch {
407624989b8cSPeter Brune   DM dm;
4077089b2837SJed Brown 
4078d763cef2SBarry Smith   PetscFunctionBegin;
407923a57915SBarry Smith   if (Amat || Pmat) {
408023a57915SBarry Smith     SNES snes;
40819566063dSJacob Faibussowitsch     PetscCall(TSGetSNES(ts, &snes));
40829566063dSJacob Faibussowitsch     PetscCall(SNESSetUpMatrices(snes));
40839566063dSJacob Faibussowitsch     PetscCall(SNESGetJacobian(snes, Amat, Pmat, NULL, NULL));
408423a57915SBarry Smith   }
40859566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
40869566063dSJacob Faibussowitsch   PetscCall(DMTSGetRHSJacobian(dm, func, ctx));
40873ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
4088d763cef2SBarry Smith }
4089d763cef2SBarry Smith 
40902eca1d9cSJed Brown /*@C
40912eca1d9cSJed Brown    TSGetIJacobian - Returns the implicit Jacobian at the present timestep.
40922eca1d9cSJed Brown 
4093bcf0153eSBarry Smith    Not Collective, but parallel objects are returned if ts is parallel
40942eca1d9cSJed Brown 
40952eca1d9cSJed Brown    Input Parameter:
4096bcf0153eSBarry Smith .  ts  - The `TS` context obtained from `TSCreate()`
40972eca1d9cSJed Brown 
40982eca1d9cSJed Brown    Output Parameters:
4099e4357dc4SBarry Smith +  Amat  - The (approximate) Jacobian of F(t,U,U_t)
4100195e9b02SBarry Smith .  Pmat - The matrix from which the preconditioner is constructed, often the same as `Amat`
41012eca1d9cSJed Brown .  f   - The function to compute the matrices
41022eca1d9cSJed Brown - ctx - User-defined context for Jacobian evaluation routine
41032eca1d9cSJed Brown 
41042eca1d9cSJed Brown    Level: advanced
41052eca1d9cSJed Brown 
4106bcf0153eSBarry Smith    Note:
4107195e9b02SBarry Smith     You can pass in `NULL` for any return argument you do not need.
4108bcf0153eSBarry Smith 
4109bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSGetTimeStep()`, `TSGetRHSJacobian()`, `TSGetMatrices()`, `TSGetTime()`, `TSGetStepNumber()`
41102eca1d9cSJed Brown @*/
4111d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetIJacobian(TS ts, Mat *Amat, Mat *Pmat, TSIJacobian *f, void **ctx)
4112d71ae5a4SJacob Faibussowitsch {
411324989b8cSPeter Brune   DM dm;
41140910c330SBarry Smith 
41152eca1d9cSJed Brown   PetscFunctionBegin;
4116c0aab802Sstefano_zampini   if (Amat || Pmat) {
4117c0aab802Sstefano_zampini     SNES snes;
41189566063dSJacob Faibussowitsch     PetscCall(TSGetSNES(ts, &snes));
41199566063dSJacob Faibussowitsch     PetscCall(SNESSetUpMatrices(snes));
41209566063dSJacob Faibussowitsch     PetscCall(SNESGetJacobian(snes, Amat, Pmat, NULL, NULL));
4121c0aab802Sstefano_zampini   }
41229566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
41239566063dSJacob Faibussowitsch   PetscCall(DMTSGetIJacobian(dm, f, ctx));
41243ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
41252eca1d9cSJed Brown }
41262eca1d9cSJed Brown 
4127af0996ceSBarry Smith #include <petsc/private/dmimpl.h>
41286c699258SBarry Smith /*@
4129bcf0153eSBarry Smith    TSSetDM - Sets the `DM` that may be used by some nonlinear solvers or preconditioners under the `TS`
41306c699258SBarry Smith 
4131c3339decSBarry Smith    Logically Collective
41326c699258SBarry Smith 
41336c699258SBarry Smith    Input Parameters:
4134bcf0153eSBarry Smith +  ts - the `TS` integrator object
4135195e9b02SBarry Smith -  dm - the dm, cannot be `NULL`
41366c699258SBarry Smith 
41376c699258SBarry Smith    Level: intermediate
41386c699258SBarry Smith 
4139bcf0153eSBarry Smith    Notes:
4140bcf0153eSBarry Smith    A `DM` can only be used for solving one problem at a time because information about the problem is stored on the `DM`,
4141bcf0153eSBarry Smith    even when not using interfaces like `DMTSSetIFunction()`.  Use `DMClone()` to get a distinct `DM` when solving
4142bcf0153eSBarry Smith    different problems using the same function space.
4143bcf0153eSBarry Smith 
4144bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `DM`, `TSGetDM()`, `SNESSetDM()`, `SNESGetDM()`
41456c699258SBarry Smith @*/
4146d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetDM(TS ts, DM dm)
4147d71ae5a4SJacob Faibussowitsch {
4148089b2837SJed Brown   SNES snes;
4149942e3340SBarry Smith   DMTS tsdm;
41506c699258SBarry Smith 
41516c699258SBarry Smith   PetscFunctionBegin;
41520700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
41532a808120SBarry Smith   PetscValidHeaderSpecific(dm, DM_CLASSID, 2);
41549566063dSJacob Faibussowitsch   PetscCall(PetscObjectReference((PetscObject)dm));
4155942e3340SBarry Smith   if (ts->dm) { /* Move the DMTS context over to the new DM unless the new DM already has one */
41562a34c10cSBarry Smith     if (ts->dm->dmts && !dm->dmts) {
41579566063dSJacob Faibussowitsch       PetscCall(DMCopyDMTS(ts->dm, dm));
41589566063dSJacob Faibussowitsch       PetscCall(DMGetDMTS(ts->dm, &tsdm));
41591e66621cSBarry Smith       /* Grant write privileges to the replacement DM */
41601e66621cSBarry Smith       if (tsdm->originaldm == ts->dm) tsdm->originaldm = dm;
416124989b8cSPeter Brune     }
41629566063dSJacob Faibussowitsch     PetscCall(DMDestroy(&ts->dm));
416324989b8cSPeter Brune   }
41646c699258SBarry Smith   ts->dm = dm;
4165bbd56ea5SKarl Rupp 
41669566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts, &snes));
41679566063dSJacob Faibussowitsch   PetscCall(SNESSetDM(snes, dm));
41683ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
41696c699258SBarry Smith }
41706c699258SBarry Smith 
41716c699258SBarry Smith /*@
4172bcf0153eSBarry Smith    TSGetDM - Gets the `DM` that may be used by some preconditioners
41736c699258SBarry Smith 
41743f9fe445SBarry Smith    Not Collective
41756c699258SBarry Smith 
41766c699258SBarry Smith    Input Parameter:
4177bcf0153eSBarry Smith . ts - the `TS`
41786c699258SBarry Smith 
41796c699258SBarry Smith    Output Parameter:
4180195e9b02SBarry Smith .  dm - the `DM`
41816c699258SBarry Smith 
41826c699258SBarry Smith    Level: intermediate
41836c699258SBarry Smith 
4184bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `DM`, `TSSetDM()`, `SNESSetDM()`, `SNESGetDM()`
41856c699258SBarry Smith @*/
4186d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetDM(TS ts, DM *dm)
4187d71ae5a4SJacob Faibussowitsch {
41886c699258SBarry Smith   PetscFunctionBegin;
41890700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
4190496e6a7aSJed Brown   if (!ts->dm) {
41919566063dSJacob Faibussowitsch     PetscCall(DMShellCreate(PetscObjectComm((PetscObject)ts), &ts->dm));
41929566063dSJacob Faibussowitsch     if (ts->snes) PetscCall(SNESSetDM(ts->snes, ts->dm));
4193496e6a7aSJed Brown   }
41946c699258SBarry Smith   *dm = ts->dm;
41953ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
41966c699258SBarry Smith }
41971713a123SBarry Smith 
41980f5c6efeSJed Brown /*@
41990f5c6efeSJed Brown    SNESTSFormFunction - Function to evaluate nonlinear residual
42000f5c6efeSJed Brown 
4201c3339decSBarry Smith    Logically Collective
42020f5c6efeSJed Brown 
4203d8d19677SJose E. Roman    Input Parameters:
4204d42a1c89SJed Brown + snes - nonlinear solver
42050910c330SBarry Smith . U - the current state at which to evaluate the residual
4206d42a1c89SJed Brown - ctx - user context, must be a TS
42070f5c6efeSJed Brown 
42080f5c6efeSJed Brown    Output Parameter:
42090f5c6efeSJed Brown . F - the nonlinear residual
42100f5c6efeSJed Brown 
42110f5c6efeSJed Brown    Level: advanced
42120f5c6efeSJed Brown 
4213bcf0153eSBarry Smith    Note:
4214bcf0153eSBarry Smith    This function is not normally called by users and is automatically registered with the `SNES` used by `TS`.
4215bcf0153eSBarry Smith    It is most frequently passed to `MatFDColoringSetFunction()`.
4216bcf0153eSBarry Smith 
4217bcf0153eSBarry Smith .seealso: [](chapter_ts), `SNESSetFunction()`, `MatFDColoringSetFunction()`
42180f5c6efeSJed Brown @*/
4219d71ae5a4SJacob Faibussowitsch PetscErrorCode SNESTSFormFunction(SNES snes, Vec U, Vec F, void *ctx)
4220d71ae5a4SJacob Faibussowitsch {
42210f5c6efeSJed Brown   TS ts = (TS)ctx;
42220f5c6efeSJed Brown 
42230f5c6efeSJed Brown   PetscFunctionBegin;
42240f5c6efeSJed Brown   PetscValidHeaderSpecific(snes, SNES_CLASSID, 1);
42250910c330SBarry Smith   PetscValidHeaderSpecific(U, VEC_CLASSID, 2);
42260f5c6efeSJed Brown   PetscValidHeaderSpecific(F, VEC_CLASSID, 3);
42270f5c6efeSJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 4);
42289566063dSJacob Faibussowitsch   PetscCall((ts->ops->snesfunction)(snes, U, F, ts));
42293ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
42300f5c6efeSJed Brown }
42310f5c6efeSJed Brown 
42320f5c6efeSJed Brown /*@
42330f5c6efeSJed Brown    SNESTSFormJacobian - Function to evaluate the Jacobian
42340f5c6efeSJed Brown 
4235c3339decSBarry Smith    Collective
42360f5c6efeSJed Brown 
4237d8d19677SJose E. Roman    Input Parameters:
42380f5c6efeSJed Brown + snes - nonlinear solver
42390910c330SBarry Smith . U - the current state at which to evaluate the residual
4240bcf0153eSBarry Smith - ctx - user context, must be a `TS`
42410f5c6efeSJed Brown 
4242d8d19677SJose E. Roman    Output Parameters:
42430f5c6efeSJed Brown + A - the Jacobian
42446b867d5aSJose E. Roman - B - the preconditioning matrix (may be the same as A)
42450f5c6efeSJed Brown 
42460f5c6efeSJed Brown    Level: developer
42470f5c6efeSJed Brown 
4248bcf0153eSBarry Smith    Note:
4249bcf0153eSBarry Smith    This function is not normally called by users and is automatically registered with the `SNES` used by `TS`.
4250bcf0153eSBarry Smith 
4251bcf0153eSBarry Smith .seealso: [](chapter_ts), `SNESSetJacobian()`
42520f5c6efeSJed Brown @*/
4253d71ae5a4SJacob Faibussowitsch PetscErrorCode SNESTSFormJacobian(SNES snes, Vec U, Mat A, Mat B, void *ctx)
4254d71ae5a4SJacob Faibussowitsch {
42550f5c6efeSJed Brown   TS ts = (TS)ctx;
42560f5c6efeSJed Brown 
42570f5c6efeSJed Brown   PetscFunctionBegin;
42580f5c6efeSJed Brown   PetscValidHeaderSpecific(snes, SNES_CLASSID, 1);
42590910c330SBarry Smith   PetscValidHeaderSpecific(U, VEC_CLASSID, 2);
42600f5c6efeSJed Brown   PetscValidPointer(A, 3);
426194ab13aaSBarry Smith   PetscValidHeaderSpecific(A, MAT_CLASSID, 3);
42620f5c6efeSJed Brown   PetscValidPointer(B, 4);
426394ab13aaSBarry Smith   PetscValidHeaderSpecific(B, MAT_CLASSID, 4);
4264064a246eSJacob Faibussowitsch   PetscValidHeaderSpecific(ts, TS_CLASSID, 5);
42659566063dSJacob Faibussowitsch   PetscCall((ts->ops->snesjacobian)(snes, U, A, B, ts));
42663ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
42670f5c6efeSJed Brown }
4268325fc9f4SBarry Smith 
42690e4ef248SJed Brown /*@C
42709ae8fd06SBarry Smith    TSComputeRHSFunctionLinear - Evaluate the right hand side via the user-provided Jacobian, for linear problems Udot = A U only
42710e4ef248SJed Brown 
4272c3339decSBarry Smith    Collective
42730e4ef248SJed Brown 
42744165533cSJose E. Roman    Input Parameters:
42750e4ef248SJed Brown +  ts - time stepping context
42760e4ef248SJed Brown .  t - time at which to evaluate
42770910c330SBarry Smith .  U - state at which to evaluate
42780e4ef248SJed Brown -  ctx - context
42790e4ef248SJed Brown 
42804165533cSJose E. Roman    Output Parameter:
42810e4ef248SJed Brown .  F - right hand side
42820e4ef248SJed Brown 
42830e4ef248SJed Brown    Level: intermediate
42840e4ef248SJed Brown 
4285bcf0153eSBarry Smith    Note:
4286bcf0153eSBarry Smith    This function is intended to be passed to `TSSetRHSFunction()` to evaluate the right hand side for linear problems.
4287bcf0153eSBarry Smith    The matrix (and optionally the evaluation context) should be passed to `TSSetRHSJacobian()`.
42880e4ef248SJed Brown 
4289bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSSetRHSFunction()`, `TSSetRHSJacobian()`, `TSComputeRHSJacobianConstant()`
42900e4ef248SJed Brown @*/
4291d71ae5a4SJacob Faibussowitsch PetscErrorCode TSComputeRHSFunctionLinear(TS ts, PetscReal t, Vec U, Vec F, void *ctx)
4292d71ae5a4SJacob Faibussowitsch {
42930e4ef248SJed Brown   Mat Arhs, Brhs;
42940e4ef248SJed Brown 
42950e4ef248SJed Brown   PetscFunctionBegin;
42969566063dSJacob Faibussowitsch   PetscCall(TSGetRHSMats_Private(ts, &Arhs, &Brhs));
42972663174eSHong Zhang   /* undo the damage caused by shifting */
42989566063dSJacob Faibussowitsch   PetscCall(TSRecoverRHSJacobian(ts, Arhs, Brhs));
42999566063dSJacob Faibussowitsch   PetscCall(TSComputeRHSJacobian(ts, t, U, Arhs, Brhs));
43009566063dSJacob Faibussowitsch   PetscCall(MatMult(Arhs, U, F));
43013ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
43020e4ef248SJed Brown }
43030e4ef248SJed Brown 
43040e4ef248SJed Brown /*@C
43050e4ef248SJed Brown    TSComputeRHSJacobianConstant - Reuses a Jacobian that is time-independent.
43060e4ef248SJed Brown 
4307c3339decSBarry Smith    Collective
43080e4ef248SJed Brown 
43094165533cSJose E. Roman    Input Parameters:
43100e4ef248SJed Brown +  ts - time stepping context
43110e4ef248SJed Brown .  t - time at which to evaluate
43120910c330SBarry Smith .  U - state at which to evaluate
43130e4ef248SJed Brown -  ctx - context
43140e4ef248SJed Brown 
43154165533cSJose E. Roman    Output Parameters:
43160e4ef248SJed Brown +  A - pointer to operator
431797bb3fdcSJose E. Roman -  B - pointer to preconditioning matrix
43180e4ef248SJed Brown 
43190e4ef248SJed Brown    Level: intermediate
43200e4ef248SJed Brown 
4321bcf0153eSBarry Smith    Note:
4322bcf0153eSBarry Smith    This function is intended to be passed to `TSSetRHSJacobian()` to evaluate the Jacobian for linear time-independent problems.
43230e4ef248SJed Brown 
4324bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSSetRHSFunction()`, `TSSetRHSJacobian()`, `TSComputeRHSFunctionLinear()`
43250e4ef248SJed Brown @*/
4326d71ae5a4SJacob Faibussowitsch PetscErrorCode TSComputeRHSJacobianConstant(TS ts, PetscReal t, Vec U, Mat A, Mat B, void *ctx)
4327d71ae5a4SJacob Faibussowitsch {
43280e4ef248SJed Brown   PetscFunctionBegin;
43293ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
43300e4ef248SJed Brown }
43310e4ef248SJed Brown 
43320026cea9SSean Farley /*@C
43330026cea9SSean Farley    TSComputeIFunctionLinear - Evaluate the left hand side via the user-provided Jacobian, for linear problems only
43340026cea9SSean Farley 
4335c3339decSBarry Smith    Collective
43360026cea9SSean Farley 
43374165533cSJose E. Roman    Input Parameters:
43380026cea9SSean Farley +  ts - time stepping context
43390026cea9SSean Farley .  t - time at which to evaluate
43400910c330SBarry Smith .  U - state at which to evaluate
43410910c330SBarry Smith .  Udot - time derivative of state vector
43420026cea9SSean Farley -  ctx - context
43430026cea9SSean Farley 
43444165533cSJose E. Roman    Output Parameter:
43450026cea9SSean Farley .  F - left hand side
43460026cea9SSean Farley 
43470026cea9SSean Farley    Level: intermediate
43480026cea9SSean Farley 
43490026cea9SSean Farley    Notes:
43500910c330SBarry 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
4351bcf0153eSBarry Smith    user is required to write their own `TSComputeIFunction()`.
4352bcf0153eSBarry Smith    This function is intended to be passed to `TSSetIFunction()` to evaluate the left hand side for linear problems.
4353bcf0153eSBarry Smith    The matrix (and optionally the evaluation context) should be passed to `TSSetIJacobian()`.
43540026cea9SSean Farley 
4355bcf0153eSBarry Smith    Note that using this function is NOT equivalent to using `TSComputeRHSFunctionLinear()` since that solves Udot = A U
43569ae8fd06SBarry Smith 
4357bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSSetIFunction()`, `TSSetIJacobian()`, `TSComputeIJacobianConstant()`, `TSComputeRHSFunctionLinear()`
43580026cea9SSean Farley @*/
4359d71ae5a4SJacob Faibussowitsch PetscErrorCode TSComputeIFunctionLinear(TS ts, PetscReal t, Vec U, Vec Udot, Vec F, void *ctx)
4360d71ae5a4SJacob Faibussowitsch {
43610026cea9SSean Farley   Mat A, B;
43620026cea9SSean Farley 
43630026cea9SSean Farley   PetscFunctionBegin;
43649566063dSJacob Faibussowitsch   PetscCall(TSGetIJacobian(ts, &A, &B, NULL, NULL));
43659566063dSJacob Faibussowitsch   PetscCall(TSComputeIJacobian(ts, t, U, Udot, 1.0, A, B, PETSC_TRUE));
43669566063dSJacob Faibussowitsch   PetscCall(MatMult(A, Udot, F));
43673ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
43680026cea9SSean Farley }
43690026cea9SSean Farley 
43700026cea9SSean Farley /*@C
4371b41af12eSJed Brown    TSComputeIJacobianConstant - Reuses a time-independent for a semi-implicit DAE or ODE
43720026cea9SSean Farley 
4373c3339decSBarry Smith    Collective
43740026cea9SSean Farley 
43754165533cSJose E. Roman    Input Parameters:
43760026cea9SSean Farley +  ts - time stepping context
43770026cea9SSean Farley .  t - time at which to evaluate
43780910c330SBarry Smith .  U - state at which to evaluate
43790910c330SBarry Smith .  Udot - time derivative of state vector
43800026cea9SSean Farley .  shift - shift to apply
43810026cea9SSean Farley -  ctx - context
43820026cea9SSean Farley 
43834165533cSJose E. Roman    Output Parameters:
43840026cea9SSean Farley +  A - pointer to operator
438597bb3fdcSJose E. Roman -  B - pointer to preconditioning matrix
43860026cea9SSean Farley 
4387b41af12eSJed Brown    Level: advanced
43880026cea9SSean Farley 
43890026cea9SSean Farley    Notes:
4390bcf0153eSBarry Smith    This function is intended to be passed to `TSSetIJacobian()` to evaluate the Jacobian for linear time-independent problems.
43910026cea9SSean Farley 
4392b41af12eSJed Brown    It is only appropriate for problems of the form
4393b41af12eSJed Brown 
4394b41af12eSJed Brown $     M Udot = F(U,t)
4395b41af12eSJed Brown 
4396bcf0153eSBarry Smith   where M is constant and F is non-stiff.  The user must pass M to `TSSetIJacobian()`.  The current implementation only
4397bcf0153eSBarry Smith   works with IMEX time integration methods such as `TSROSW` and `TSARKIMEX`, since there is no support for de-constructing
4398b41af12eSJed Brown   an implicit operator of the form
4399b41af12eSJed Brown 
4400b41af12eSJed Brown $    shift*M + J
4401b41af12eSJed Brown 
4402b41af12eSJed 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
4403b41af12eSJed Brown   a copy of M or reassemble it when requested.
4404b41af12eSJed Brown 
4405bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSROSW`, `TSARKIMEX`, `TSSetIFunction()`, `TSSetIJacobian()`, `TSComputeIFunctionLinear()`
44060026cea9SSean Farley @*/
4407d71ae5a4SJacob Faibussowitsch PetscErrorCode TSComputeIJacobianConstant(TS ts, PetscReal t, Vec U, Vec Udot, PetscReal shift, Mat A, Mat B, void *ctx)
4408d71ae5a4SJacob Faibussowitsch {
44090026cea9SSean Farley   PetscFunctionBegin;
44109566063dSJacob Faibussowitsch   PetscCall(MatScale(A, shift / ts->ijacobian.shift));
4411b41af12eSJed Brown   ts->ijacobian.shift = shift;
44123ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
44130026cea9SSean Farley }
4414b41af12eSJed Brown 
4415e817cc15SEmil Constantinescu /*@
4416bcf0153eSBarry Smith    TSGetEquationType - Gets the type of the equation that `TS` is solving.
4417e817cc15SEmil Constantinescu 
4418e817cc15SEmil Constantinescu    Not Collective
4419e817cc15SEmil Constantinescu 
4420e817cc15SEmil Constantinescu    Input Parameter:
4421bcf0153eSBarry Smith .  ts - the `TS` context
4422e817cc15SEmil Constantinescu 
4423e817cc15SEmil Constantinescu    Output Parameter:
4424bcf0153eSBarry Smith .  equation_type - see `TSEquationType`
4425e817cc15SEmil Constantinescu 
4426e817cc15SEmil Constantinescu    Level: beginner
4427e817cc15SEmil Constantinescu 
4428bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSSetEquationType()`, `TSEquationType`
4429e817cc15SEmil Constantinescu @*/
4430d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetEquationType(TS ts, TSEquationType *equation_type)
4431d71ae5a4SJacob Faibussowitsch {
4432e817cc15SEmil Constantinescu   PetscFunctionBegin;
4433e817cc15SEmil Constantinescu   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
4434e817cc15SEmil Constantinescu   PetscValidPointer(equation_type, 2);
4435e817cc15SEmil Constantinescu   *equation_type = ts->equation_type;
44363ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
4437e817cc15SEmil Constantinescu }
4438e817cc15SEmil Constantinescu 
4439e817cc15SEmil Constantinescu /*@
4440bcf0153eSBarry Smith    TSSetEquationType - Sets the type of the equation that `TS` is solving.
4441e817cc15SEmil Constantinescu 
4442e817cc15SEmil Constantinescu    Not Collective
4443e817cc15SEmil Constantinescu 
4444d8d19677SJose E. Roman    Input Parameters:
4445bcf0153eSBarry Smith +  ts - the `TS` context
4446bcf0153eSBarry Smith -  equation_type - see `TSEquationType`
4447e817cc15SEmil Constantinescu 
4448e817cc15SEmil Constantinescu    Level: advanced
4449e817cc15SEmil Constantinescu 
4450bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSGetEquationType()`, `TSEquationType`
4451e817cc15SEmil Constantinescu @*/
4452d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetEquationType(TS ts, TSEquationType equation_type)
4453d71ae5a4SJacob Faibussowitsch {
4454e817cc15SEmil Constantinescu   PetscFunctionBegin;
4455e817cc15SEmil Constantinescu   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
4456e817cc15SEmil Constantinescu   ts->equation_type = equation_type;
44573ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
4458e817cc15SEmil Constantinescu }
44590026cea9SSean Farley 
44604af1b03aSJed Brown /*@
4461bcf0153eSBarry Smith    TSGetConvergedReason - Gets the reason the `TS` iteration was stopped.
44624af1b03aSJed Brown 
44634af1b03aSJed Brown    Not Collective
44644af1b03aSJed Brown 
44654af1b03aSJed Brown    Input Parameter:
4466bcf0153eSBarry Smith .  ts - the `TS` context
44674af1b03aSJed Brown 
44684af1b03aSJed Brown    Output Parameter:
4469bcf0153eSBarry Smith .  reason - negative value indicates diverged, positive value converged, see `TSConvergedReason` or the
44704af1b03aSJed Brown             manual pages for the individual convergence tests for complete lists
44714af1b03aSJed Brown 
4472487e0bb9SJed Brown    Level: beginner
44734af1b03aSJed Brown 
4474bcf0153eSBarry Smith    Note:
4475bcf0153eSBarry Smith    Can only be called after the call to `TSSolve()` is complete.
44764af1b03aSJed Brown 
4477bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSSolve()`, `TSSetConvergenceTest()`, `TSConvergedReason`
44784af1b03aSJed Brown @*/
4479d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetConvergedReason(TS ts, TSConvergedReason *reason)
4480d71ae5a4SJacob Faibussowitsch {
44814af1b03aSJed Brown   PetscFunctionBegin;
44824af1b03aSJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
44834af1b03aSJed Brown   PetscValidPointer(reason, 2);
44844af1b03aSJed Brown   *reason = ts->reason;
44853ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
44864af1b03aSJed Brown }
44874af1b03aSJed Brown 
4488d6ad946cSShri Abhyankar /*@
4489bcf0153eSBarry Smith    TSSetConvergedReason - Sets the reason for handling the convergence of `TSSolve()`.
4490d6ad946cSShri Abhyankar 
44916b221cbeSPatrick Sanan    Logically Collective; reason must contain common value
4492d6ad946cSShri Abhyankar 
44936b221cbeSPatrick Sanan    Input Parameters:
4494bcf0153eSBarry Smith +  ts - the `TS` context
4495bcf0153eSBarry Smith -  reason - negative value indicates diverged, positive value converged, see `TSConvergedReason` or the
4496d6ad946cSShri Abhyankar             manual pages for the individual convergence tests for complete lists
4497d6ad946cSShri Abhyankar 
4498f5abba47SShri Abhyankar    Level: advanced
4499d6ad946cSShri Abhyankar 
4500bcf0153eSBarry Smith    Note:
4501bcf0153eSBarry Smith    Can only be called while `TSSolve()` is active.
4502d6ad946cSShri Abhyankar 
4503bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSSolve()`, `TSConvergedReason`
4504d6ad946cSShri Abhyankar @*/
4505d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetConvergedReason(TS ts, TSConvergedReason reason)
4506d71ae5a4SJacob Faibussowitsch {
4507d6ad946cSShri Abhyankar   PetscFunctionBegin;
4508d6ad946cSShri Abhyankar   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
4509d6ad946cSShri Abhyankar   ts->reason = reason;
45103ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
4511d6ad946cSShri Abhyankar }
4512d6ad946cSShri Abhyankar 
4513cc708dedSBarry Smith /*@
4514bcf0153eSBarry Smith    TSGetSolveTime - Gets the time after a call to `TSSolve()`
4515cc708dedSBarry Smith 
4516cc708dedSBarry Smith    Not Collective
4517cc708dedSBarry Smith 
4518cc708dedSBarry Smith    Input Parameter:
4519bcf0153eSBarry Smith .  ts - the `TS` context
4520cc708dedSBarry Smith 
4521cc708dedSBarry Smith    Output Parameter:
4522bcf0153eSBarry Smith .  ftime - the final time. This time corresponds to the final time set with `TSSetMaxTime()`
4523cc708dedSBarry Smith 
4524487e0bb9SJed Brown    Level: beginner
4525cc708dedSBarry Smith 
4526bcf0153eSBarry Smith    Note:
4527bcf0153eSBarry Smith    Can only be called after the call to `TSSolve()` is complete.
4528cc708dedSBarry Smith 
4529bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSSolve()`, `TSSetConvergenceTest()`, `TSConvergedReason`
4530cc708dedSBarry Smith @*/
4531d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetSolveTime(TS ts, PetscReal *ftime)
4532d71ae5a4SJacob Faibussowitsch {
4533cc708dedSBarry Smith   PetscFunctionBegin;
4534cc708dedSBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
4535dadcf809SJacob Faibussowitsch   PetscValidRealPointer(ftime, 2);
4536cc708dedSBarry Smith   *ftime = ts->solvetime;
45373ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
4538cc708dedSBarry Smith }
4539cc708dedSBarry Smith 
45402c18e0fdSBarry Smith /*@
45415ef26d82SJed Brown    TSGetSNESIterations - Gets the total number of nonlinear iterations
45429f67acb7SJed Brown    used by the time integrator.
45439f67acb7SJed Brown 
45449f67acb7SJed Brown    Not Collective
45459f67acb7SJed Brown 
45469f67acb7SJed Brown    Input Parameter:
4547bcf0153eSBarry Smith .  ts - `TS` context
45489f67acb7SJed Brown 
45499f67acb7SJed Brown    Output Parameter:
45509f67acb7SJed Brown .  nits - number of nonlinear iterations
45519f67acb7SJed Brown 
45529f67acb7SJed Brown    Level: intermediate
45539f67acb7SJed Brown 
4554195e9b02SBarry Smith    Note:
4555bcf0153eSBarry Smith    This counter is reset to zero for each successive call to `TSSolve()`.
4556bcf0153eSBarry Smith 
4557bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSSolve()`, `TSGetKSPIterations()`
45589f67acb7SJed Brown @*/
4559d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetSNESIterations(TS ts, PetscInt *nits)
4560d71ae5a4SJacob Faibussowitsch {
45619f67acb7SJed Brown   PetscFunctionBegin;
45629f67acb7SJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
45639f67acb7SJed Brown   PetscValidIntPointer(nits, 2);
45645ef26d82SJed Brown   *nits = ts->snes_its;
45653ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
45669f67acb7SJed Brown }
45679f67acb7SJed Brown 
45689f67acb7SJed Brown /*@
45695ef26d82SJed Brown    TSGetKSPIterations - Gets the total number of linear iterations
45709f67acb7SJed Brown    used by the time integrator.
45719f67acb7SJed Brown 
45729f67acb7SJed Brown    Not Collective
45739f67acb7SJed Brown 
45749f67acb7SJed Brown    Input Parameter:
4575bcf0153eSBarry Smith .  ts - `TS` context
45769f67acb7SJed Brown 
45779f67acb7SJed Brown    Output Parameter:
45789f67acb7SJed Brown .  lits - number of linear iterations
45799f67acb7SJed Brown 
45809f67acb7SJed Brown    Level: intermediate
45819f67acb7SJed Brown 
4582bcf0153eSBarry Smith    Note:
4583bcf0153eSBarry Smith    This counter is reset to zero for each successive call to `TSSolve()`.
4584bcf0153eSBarry Smith 
4585bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSSolve()`, `TSGetSNESIterations()`, `SNESGetKSPIterations()`
45869f67acb7SJed Brown @*/
4587d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetKSPIterations(TS ts, PetscInt *lits)
4588d71ae5a4SJacob Faibussowitsch {
45899f67acb7SJed Brown   PetscFunctionBegin;
45909f67acb7SJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
45919f67acb7SJed Brown   PetscValidIntPointer(lits, 2);
45925ef26d82SJed Brown   *lits = ts->ksp_its;
45933ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
45949f67acb7SJed Brown }
45959f67acb7SJed Brown 
4596cef5090cSJed Brown /*@
4597cef5090cSJed Brown    TSGetStepRejections - Gets the total number of rejected steps.
4598cef5090cSJed Brown 
4599cef5090cSJed Brown    Not Collective
4600cef5090cSJed Brown 
4601cef5090cSJed Brown    Input Parameter:
4602bcf0153eSBarry Smith .  ts - `TS` context
4603cef5090cSJed Brown 
4604cef5090cSJed Brown    Output Parameter:
4605cef5090cSJed Brown .  rejects - number of steps rejected
4606cef5090cSJed Brown 
4607cef5090cSJed Brown    Level: intermediate
4608cef5090cSJed Brown 
4609bcf0153eSBarry Smith    Note:
4610bcf0153eSBarry Smith    This counter is reset to zero for each successive call to `TSSolve()`.
4611bcf0153eSBarry Smith 
4612bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSSolve()`, `TSGetSNESIterations()`, `TSGetKSPIterations()`, `TSSetMaxStepRejections()`, `TSGetSNESFailures()`, `TSSetMaxSNESFailures()`, `TSSetErrorIfStepFails()`
4613cef5090cSJed Brown @*/
4614d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetStepRejections(TS ts, PetscInt *rejects)
4615d71ae5a4SJacob Faibussowitsch {
4616cef5090cSJed Brown   PetscFunctionBegin;
4617cef5090cSJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
4618cef5090cSJed Brown   PetscValidIntPointer(rejects, 2);
4619cef5090cSJed Brown   *rejects = ts->reject;
46203ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
4621cef5090cSJed Brown }
4622cef5090cSJed Brown 
4623cef5090cSJed Brown /*@
4624bcf0153eSBarry Smith    TSGetSNESFailures - Gets the total number of failed `SNES` solves in a `TS`
4625cef5090cSJed Brown 
4626cef5090cSJed Brown    Not Collective
4627cef5090cSJed Brown 
4628cef5090cSJed Brown    Input Parameter:
4629bcf0153eSBarry Smith .  ts - `TS` context
4630cef5090cSJed Brown 
4631cef5090cSJed Brown    Output Parameter:
4632cef5090cSJed Brown .  fails - number of failed nonlinear solves
4633cef5090cSJed Brown 
4634cef5090cSJed Brown    Level: intermediate
4635cef5090cSJed Brown 
4636bcf0153eSBarry Smith    Note:
4637bcf0153eSBarry Smith    This counter is reset to zero for each successive call to `TSSolve()`.
4638bcf0153eSBarry Smith 
4639bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSSolve()`, `TSGetSNESIterations()`, `TSGetKSPIterations()`, `TSSetMaxStepRejections()`, `TSGetStepRejections()`, `TSSetMaxSNESFailures()`
4640cef5090cSJed Brown @*/
4641d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetSNESFailures(TS ts, PetscInt *fails)
4642d71ae5a4SJacob Faibussowitsch {
4643cef5090cSJed Brown   PetscFunctionBegin;
4644cef5090cSJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
4645cef5090cSJed Brown   PetscValidIntPointer(fails, 2);
4646cef5090cSJed Brown   *fails = ts->num_snes_failures;
46473ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
4648cef5090cSJed Brown }
4649cef5090cSJed Brown 
4650cef5090cSJed Brown /*@
4651bcf0153eSBarry Smith    TSSetMaxStepRejections - Sets the maximum number of step rejections before a time step fails
4652cef5090cSJed Brown 
4653cef5090cSJed Brown    Not Collective
4654cef5090cSJed Brown 
4655d8d19677SJose E. Roman    Input Parameters:
4656bcf0153eSBarry Smith +  ts - `TS` context
4657cef5090cSJed Brown -  rejects - maximum number of rejected steps, pass -1 for unlimited
4658cef5090cSJed Brown 
4659cef5090cSJed Brown    Options Database Key:
4660cef5090cSJed Brown .  -ts_max_reject - Maximum number of step rejections before a step fails
4661cef5090cSJed Brown 
4662cef5090cSJed Brown    Level: intermediate
4663cef5090cSJed Brown 
4664bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `SNES`, `TSGetSNESIterations()`, `TSGetKSPIterations()`, `TSSetMaxSNESFailures()`, `TSGetStepRejections()`, `TSGetSNESFailures()`, `TSSetErrorIfStepFails()`, `TSGetConvergedReason()`
4665cef5090cSJed Brown @*/
4666d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetMaxStepRejections(TS ts, PetscInt rejects)
4667d71ae5a4SJacob Faibussowitsch {
4668cef5090cSJed Brown   PetscFunctionBegin;
4669cef5090cSJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
4670cef5090cSJed Brown   ts->max_reject = rejects;
46713ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
4672cef5090cSJed Brown }
4673cef5090cSJed Brown 
4674cef5090cSJed Brown /*@
4675bcf0153eSBarry Smith    TSSetMaxSNESFailures - Sets the maximum number of failed `SNES` solves
4676cef5090cSJed Brown 
4677cef5090cSJed Brown    Not Collective
4678cef5090cSJed Brown 
4679d8d19677SJose E. Roman    Input Parameters:
4680bcf0153eSBarry Smith +  ts - `TS` context
4681cef5090cSJed Brown -  fails - maximum number of failed nonlinear solves, pass -1 for unlimited
4682cef5090cSJed Brown 
4683cef5090cSJed Brown    Options Database Key:
4684cef5090cSJed Brown .  -ts_max_snes_failures - Maximum number of nonlinear solve failures
4685cef5090cSJed Brown 
4686cef5090cSJed Brown    Level: intermediate
4687cef5090cSJed Brown 
4688bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `SNES`, `TSGetSNESIterations()`, `TSGetKSPIterations()`, `TSSetMaxStepRejections()`, `TSGetStepRejections()`, `TSGetSNESFailures()`, `SNESGetConvergedReason()`, `TSGetConvergedReason()`
4689cef5090cSJed Brown @*/
4690d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetMaxSNESFailures(TS ts, PetscInt fails)
4691d71ae5a4SJacob Faibussowitsch {
4692cef5090cSJed Brown   PetscFunctionBegin;
4693cef5090cSJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
4694cef5090cSJed Brown   ts->max_snes_failures = fails;
46953ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
4696cef5090cSJed Brown }
4697cef5090cSJed Brown 
4698cef5090cSJed Brown /*@
4699195e9b02SBarry Smith    TSSetErrorIfStepFails - Immediately error if no step succeeds during `TSSolve()`
4700cef5090cSJed Brown 
4701cef5090cSJed Brown    Not Collective
4702cef5090cSJed Brown 
4703d8d19677SJose E. Roman    Input Parameters:
4704bcf0153eSBarry Smith +  ts - `TS` context
4705bcf0153eSBarry Smith -  err - `PETSC_TRUE` to error if no step succeeds, `PETSC_FALSE` to return without failure
4706cef5090cSJed Brown 
4707cef5090cSJed Brown    Options Database Key:
4708cef5090cSJed Brown .  -ts_error_if_step_fails - Error if no step succeeds
4709cef5090cSJed Brown 
4710cef5090cSJed Brown    Level: intermediate
4711cef5090cSJed Brown 
4712bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSGetSNESIterations()`, `TSGetKSPIterations()`, `TSSetMaxStepRejections()`, `TSGetStepRejections()`, `TSGetSNESFailures()`, `TSSetErrorIfStepFails()`, `TSGetConvergedReason()`
4713cef5090cSJed Brown @*/
4714d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetErrorIfStepFails(TS ts, PetscBool err)
4715d71ae5a4SJacob Faibussowitsch {
4716cef5090cSJed Brown   PetscFunctionBegin;
4717cef5090cSJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
4718cef5090cSJed Brown   ts->errorifstepfailed = err;
47193ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
4720cef5090cSJed Brown }
4721cef5090cSJed Brown 
472284df9cb4SJed Brown /*@
4723552698daSJed Brown    TSGetAdapt - Get the adaptive controller context for the current method
472484df9cb4SJed Brown 
4725195e9b02SBarry Smith    Collective on `ts` if controller has not been created yet
472684df9cb4SJed Brown 
47274165533cSJose E. Roman    Input Parameter:
4728ed81e22dSJed Brown .  ts - time stepping context
472984df9cb4SJed Brown 
47304165533cSJose E. Roman    Output Parameter:
4731ed81e22dSJed Brown .  adapt - adaptive controller
473284df9cb4SJed Brown 
473384df9cb4SJed Brown    Level: intermediate
473484df9cb4SJed Brown 
4735bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSAdapt`, `TSAdaptSetType()`, `TSAdaptChoose()`
473684df9cb4SJed Brown @*/
4737d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetAdapt(TS ts, TSAdapt *adapt)
4738d71ae5a4SJacob Faibussowitsch {
473984df9cb4SJed Brown   PetscFunctionBegin;
474084df9cb4SJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
4741bec58848SLisandro Dalcin   PetscValidPointer(adapt, 2);
474284df9cb4SJed Brown   if (!ts->adapt) {
47439566063dSJacob Faibussowitsch     PetscCall(TSAdaptCreate(PetscObjectComm((PetscObject)ts), &ts->adapt));
47449566063dSJacob Faibussowitsch     PetscCall(PetscObjectIncrementTabLevel((PetscObject)ts->adapt, (PetscObject)ts, 1));
474584df9cb4SJed Brown   }
4746bec58848SLisandro Dalcin   *adapt = ts->adapt;
47473ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
474884df9cb4SJed Brown }
4749d6ebe24aSShri Abhyankar 
47501c3436cfSJed Brown /*@
4751195e9b02SBarry Smith    TSSetTolerances - Set tolerances for local truncation error when using an adaptive controller
47521c3436cfSJed Brown 
47531c3436cfSJed Brown    Logically Collective
47541c3436cfSJed Brown 
47554165533cSJose E. Roman    Input Parameters:
47561c3436cfSJed Brown +  ts - time integration context
4757bcf0153eSBarry Smith .  atol - scalar absolute tolerances, `PETSC_DECIDE` to leave current value
4758195e9b02SBarry Smith .  vatol - vector of absolute tolerances or `NULL`, used in preference to atol if present
4759bcf0153eSBarry Smith .  rtol - scalar relative tolerances, `PETSC_DECIDE` to leave current value
4760195e9b02SBarry Smith -  vrtol - vector of relative tolerances or `NULL`, used in preference to atol if present
47611c3436cfSJed Brown 
4762195e9b02SBarry Smith    Options Database Keys:
4763a3cdaa26SBarry Smith +  -ts_rtol <rtol> - relative tolerance for local truncation error
476467b8a455SSatish Balay -  -ts_atol <atol> - Absolute tolerance for local truncation error
4765a3cdaa26SBarry Smith 
4766bcf0153eSBarry Smith    Level: beginner
4767bcf0153eSBarry Smith 
47683ff766beSShri Abhyankar    Notes:
47693ff766beSShri Abhyankar    With PETSc's implicit schemes for DAE problems, the calculation of the local truncation error
47703ff766beSShri Abhyankar    (LTE) includes both the differential and the algebraic variables. If one wants the LTE to be
47713ff766beSShri Abhyankar    computed only for the differential or the algebraic part then this can be done using the vector of
47723ff766beSShri Abhyankar    tolerances vatol. For example, by setting the tolerance vector with the desired tolerance for the
47733ff766beSShri Abhyankar    differential part and infinity for the algebraic part, the LTE calculation will include only the
47743ff766beSShri Abhyankar    differential variables.
47753ff766beSShri Abhyankar 
4776bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSAdapt`, `TSErrorWeightedNorm()`, `TSGetTolerances()`
47771c3436cfSJed Brown @*/
4778d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetTolerances(TS ts, PetscReal atol, Vec vatol, PetscReal rtol, Vec vrtol)
4779d71ae5a4SJacob Faibussowitsch {
47801c3436cfSJed Brown   PetscFunctionBegin;
478113bcc0bdSJacob Faibussowitsch   if (atol != (PetscReal)PETSC_DECIDE && atol != (PetscReal)PETSC_DEFAULT) ts->atol = atol;
47821c3436cfSJed Brown   if (vatol) {
47839566063dSJacob Faibussowitsch     PetscCall(PetscObjectReference((PetscObject)vatol));
47849566063dSJacob Faibussowitsch     PetscCall(VecDestroy(&ts->vatol));
47851c3436cfSJed Brown     ts->vatol = vatol;
47861c3436cfSJed Brown   }
478713bcc0bdSJacob Faibussowitsch   if (rtol != (PetscReal)PETSC_DECIDE && rtol != (PetscReal)PETSC_DEFAULT) ts->rtol = rtol;
47881c3436cfSJed Brown   if (vrtol) {
47899566063dSJacob Faibussowitsch     PetscCall(PetscObjectReference((PetscObject)vrtol));
47909566063dSJacob Faibussowitsch     PetscCall(VecDestroy(&ts->vrtol));
47911c3436cfSJed Brown     ts->vrtol = vrtol;
47921c3436cfSJed Brown   }
47933ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
47941c3436cfSJed Brown }
47951c3436cfSJed Brown 
4796c5033834SJed Brown /*@
4797c5033834SJed Brown    TSGetTolerances - Get tolerances for local truncation error when using adaptive controller
4798c5033834SJed Brown 
4799c5033834SJed Brown    Logically Collective
4800c5033834SJed Brown 
48014165533cSJose E. Roman    Input Parameter:
4802c5033834SJed Brown .  ts - time integration context
4803c5033834SJed Brown 
48044165533cSJose E. Roman    Output Parameters:
4805195e9b02SBarry Smith +  atol - scalar absolute tolerances, `NULL` to ignore
4806195e9b02SBarry Smith .  vatol - vector of absolute tolerances, `NULL` to ignore
4807195e9b02SBarry Smith .  rtol - scalar relative tolerances, `NULL` to ignore
4808195e9b02SBarry Smith -  vrtol - vector of relative tolerances, `NULL` to ignore
4809c5033834SJed Brown 
4810c5033834SJed Brown    Level: beginner
4811c5033834SJed Brown 
4812bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSAdapt`, `TSErrorWeightedNorm()`, `TSSetTolerances()`
4813c5033834SJed Brown @*/
4814d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetTolerances(TS ts, PetscReal *atol, Vec *vatol, PetscReal *rtol, Vec *vrtol)
4815d71ae5a4SJacob Faibussowitsch {
4816c5033834SJed Brown   PetscFunctionBegin;
4817c5033834SJed Brown   if (atol) *atol = ts->atol;
4818c5033834SJed Brown   if (vatol) *vatol = ts->vatol;
4819c5033834SJed Brown   if (rtol) *rtol = ts->rtol;
4820c5033834SJed Brown   if (vrtol) *vrtol = ts->vrtol;
48213ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
4822c5033834SJed Brown }
4823c5033834SJed Brown 
48249c6b16b5SShri Abhyankar /*@
4825a4868fbcSLisandro Dalcin    TSErrorWeightedNorm2 - compute a weighted 2-norm of the difference between two state vectors
48269c6b16b5SShri Abhyankar 
4827c3339decSBarry Smith    Collective
48289c6b16b5SShri Abhyankar 
48294165533cSJose E. Roman    Input Parameters:
48309c6b16b5SShri Abhyankar +  ts - time stepping context
4831a4868fbcSLisandro Dalcin .  U - state vector, usually ts->vec_sol
4832a4868fbcSLisandro Dalcin -  Y - state vector to be compared to U
48339c6b16b5SShri Abhyankar 
48344165533cSJose E. Roman    Output Parameters:
4835a2b725a8SWilliam Gropp +  norm - weighted norm, a value of 1.0 means that the error matches the tolerances
48367453f775SEmil Constantinescu .  norma - weighted norm based on the absolute tolerance, a value of 1.0 means that the error matches the tolerances
4837a2b725a8SWilliam Gropp -  normr - weighted norm based on the relative tolerance, a value of 1.0 means that the error matches the tolerances
48389c6b16b5SShri Abhyankar 
48399c6b16b5SShri Abhyankar    Level: developer
48409c6b16b5SShri Abhyankar 
4841bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSErrorWeightedNorm()`, `TSErrorWeightedNormInfinity()`
48429c6b16b5SShri Abhyankar @*/
4843d71ae5a4SJacob Faibussowitsch PetscErrorCode TSErrorWeightedNorm2(TS ts, Vec U, Vec Y, PetscReal *norm, PetscReal *norma, PetscReal *normr)
4844d71ae5a4SJacob Faibussowitsch {
48459c6b16b5SShri Abhyankar   PetscInt           i, n, N, rstart;
48467453f775SEmil Constantinescu   PetscInt           n_loc, na_loc, nr_loc;
48477453f775SEmil Constantinescu   PetscReal          n_glb, na_glb, nr_glb;
48489c6b16b5SShri Abhyankar   const PetscScalar *u, *y;
48497453f775SEmil Constantinescu   PetscReal          sum, suma, sumr, gsum, gsuma, gsumr, diff;
48507453f775SEmil Constantinescu   PetscReal          tol, tola, tolr;
48517453f775SEmil Constantinescu   PetscReal          err_loc[6], err_glb[6];
48529c6b16b5SShri Abhyankar 
48539c6b16b5SShri Abhyankar   PetscFunctionBegin;
48549c6b16b5SShri Abhyankar   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
4855a4868fbcSLisandro Dalcin   PetscValidHeaderSpecific(U, VEC_CLASSID, 2);
4856a4868fbcSLisandro Dalcin   PetscValidHeaderSpecific(Y, VEC_CLASSID, 3);
4857a4868fbcSLisandro Dalcin   PetscValidType(U, 2);
4858a4868fbcSLisandro Dalcin   PetscValidType(Y, 3);
4859a4868fbcSLisandro Dalcin   PetscCheckSameComm(U, 2, Y, 3);
4860dadcf809SJacob Faibussowitsch   PetscValidRealPointer(norm, 4);
4861dadcf809SJacob Faibussowitsch   PetscValidRealPointer(norma, 5);
4862dadcf809SJacob Faibussowitsch   PetscValidRealPointer(normr, 6);
48633c633725SBarry Smith   PetscCheck(U != Y, PetscObjectComm((PetscObject)U), PETSC_ERR_ARG_IDN, "U and Y cannot be the same vector");
48649c6b16b5SShri Abhyankar 
48659566063dSJacob Faibussowitsch   PetscCall(VecGetSize(U, &N));
48669566063dSJacob Faibussowitsch   PetscCall(VecGetLocalSize(U, &n));
48679566063dSJacob Faibussowitsch   PetscCall(VecGetOwnershipRange(U, &rstart, NULL));
48689566063dSJacob Faibussowitsch   PetscCall(VecGetArrayRead(U, &u));
48699566063dSJacob Faibussowitsch   PetscCall(VecGetArrayRead(Y, &y));
48709371c9d4SSatish Balay   sum    = 0.;
48719371c9d4SSatish Balay   n_loc  = 0;
48729371c9d4SSatish Balay   suma   = 0.;
48739371c9d4SSatish Balay   na_loc = 0;
48749371c9d4SSatish Balay   sumr   = 0.;
48759371c9d4SSatish Balay   nr_loc = 0;
48769c6b16b5SShri Abhyankar   if (ts->vatol && ts->vrtol) {
48779c6b16b5SShri Abhyankar     const PetscScalar *atol, *rtol;
48789566063dSJacob Faibussowitsch     PetscCall(VecGetArrayRead(ts->vatol, &atol));
48799566063dSJacob Faibussowitsch     PetscCall(VecGetArrayRead(ts->vrtol, &rtol));
48809c6b16b5SShri Abhyankar     for (i = 0; i < n; i++) {
488176cddca1SEmil Constantinescu       SkipSmallValue(y[i], u[i], ts->adapt->ignore_max);
48827453f775SEmil Constantinescu       diff = PetscAbsScalar(y[i] - u[i]);
48837453f775SEmil Constantinescu       tola = PetscRealPart(atol[i]);
48847453f775SEmil Constantinescu       if (tola > 0.) {
48857453f775SEmil Constantinescu         suma += PetscSqr(diff / tola);
48867453f775SEmil Constantinescu         na_loc++;
48877453f775SEmil Constantinescu       }
48887453f775SEmil Constantinescu       tolr = PetscRealPart(rtol[i]) * PetscMax(PetscAbsScalar(u[i]), PetscAbsScalar(y[i]));
48897453f775SEmil Constantinescu       if (tolr > 0.) {
48907453f775SEmil Constantinescu         sumr += PetscSqr(diff / tolr);
48917453f775SEmil Constantinescu         nr_loc++;
48927453f775SEmil Constantinescu       }
48937453f775SEmil Constantinescu       tol = tola + tolr;
48947453f775SEmil Constantinescu       if (tol > 0.) {
48957453f775SEmil Constantinescu         sum += PetscSqr(diff / tol);
48967453f775SEmil Constantinescu         n_loc++;
48977453f775SEmil Constantinescu       }
48989c6b16b5SShri Abhyankar     }
48999566063dSJacob Faibussowitsch     PetscCall(VecRestoreArrayRead(ts->vatol, &atol));
49009566063dSJacob Faibussowitsch     PetscCall(VecRestoreArrayRead(ts->vrtol, &rtol));
49019c6b16b5SShri Abhyankar   } else if (ts->vatol) { /* vector atol, scalar rtol */
49029c6b16b5SShri Abhyankar     const PetscScalar *atol;
49039566063dSJacob Faibussowitsch     PetscCall(VecGetArrayRead(ts->vatol, &atol));
49049c6b16b5SShri Abhyankar     for (i = 0; i < n; i++) {
490576cddca1SEmil Constantinescu       SkipSmallValue(y[i], u[i], ts->adapt->ignore_max);
49067453f775SEmil Constantinescu       diff = PetscAbsScalar(y[i] - u[i]);
49077453f775SEmil Constantinescu       tola = PetscRealPart(atol[i]);
49087453f775SEmil Constantinescu       if (tola > 0.) {
49097453f775SEmil Constantinescu         suma += PetscSqr(diff / tola);
49107453f775SEmil Constantinescu         na_loc++;
49117453f775SEmil Constantinescu       }
49127453f775SEmil Constantinescu       tolr = ts->rtol * PetscMax(PetscAbsScalar(u[i]), PetscAbsScalar(y[i]));
49137453f775SEmil Constantinescu       if (tolr > 0.) {
49147453f775SEmil Constantinescu         sumr += PetscSqr(diff / tolr);
49157453f775SEmil Constantinescu         nr_loc++;
49167453f775SEmil Constantinescu       }
49177453f775SEmil Constantinescu       tol = tola + tolr;
49187453f775SEmil Constantinescu       if (tol > 0.) {
49197453f775SEmil Constantinescu         sum += PetscSqr(diff / tol);
49207453f775SEmil Constantinescu         n_loc++;
49217453f775SEmil Constantinescu       }
49229c6b16b5SShri Abhyankar     }
49239566063dSJacob Faibussowitsch     PetscCall(VecRestoreArrayRead(ts->vatol, &atol));
49249c6b16b5SShri Abhyankar   } else if (ts->vrtol) { /* scalar atol, vector rtol */
49259c6b16b5SShri Abhyankar     const PetscScalar *rtol;
49269566063dSJacob Faibussowitsch     PetscCall(VecGetArrayRead(ts->vrtol, &rtol));
49279c6b16b5SShri Abhyankar     for (i = 0; i < n; i++) {
492876cddca1SEmil Constantinescu       SkipSmallValue(y[i], u[i], ts->adapt->ignore_max);
49297453f775SEmil Constantinescu       diff = PetscAbsScalar(y[i] - u[i]);
49307453f775SEmil Constantinescu       tola = ts->atol;
49317453f775SEmil Constantinescu       if (tola > 0.) {
49327453f775SEmil Constantinescu         suma += PetscSqr(diff / tola);
49337453f775SEmil Constantinescu         na_loc++;
49347453f775SEmil Constantinescu       }
49357453f775SEmil Constantinescu       tolr = PetscRealPart(rtol[i]) * PetscMax(PetscAbsScalar(u[i]), PetscAbsScalar(y[i]));
49367453f775SEmil Constantinescu       if (tolr > 0.) {
49377453f775SEmil Constantinescu         sumr += PetscSqr(diff / tolr);
49387453f775SEmil Constantinescu         nr_loc++;
49397453f775SEmil Constantinescu       }
49407453f775SEmil Constantinescu       tol = tola + tolr;
49417453f775SEmil Constantinescu       if (tol > 0.) {
49427453f775SEmil Constantinescu         sum += PetscSqr(diff / tol);
49437453f775SEmil Constantinescu         n_loc++;
49447453f775SEmil Constantinescu       }
49459c6b16b5SShri Abhyankar     }
49469566063dSJacob Faibussowitsch     PetscCall(VecRestoreArrayRead(ts->vrtol, &rtol));
49479c6b16b5SShri Abhyankar   } else { /* scalar atol, scalar rtol */
49489c6b16b5SShri Abhyankar     for (i = 0; i < n; i++) {
494976cddca1SEmil Constantinescu       SkipSmallValue(y[i], u[i], ts->adapt->ignore_max);
49507453f775SEmil Constantinescu       diff = PetscAbsScalar(y[i] - u[i]);
49517453f775SEmil Constantinescu       tola = ts->atol;
49527453f775SEmil Constantinescu       if (tola > 0.) {
49537453f775SEmil Constantinescu         suma += PetscSqr(diff / tola);
49547453f775SEmil Constantinescu         na_loc++;
49557453f775SEmil Constantinescu       }
49567453f775SEmil Constantinescu       tolr = ts->rtol * PetscMax(PetscAbsScalar(u[i]), PetscAbsScalar(y[i]));
49577453f775SEmil Constantinescu       if (tolr > 0.) {
49587453f775SEmil Constantinescu         sumr += PetscSqr(diff / tolr);
49597453f775SEmil Constantinescu         nr_loc++;
49607453f775SEmil Constantinescu       }
49617453f775SEmil Constantinescu       tol = tola + tolr;
49627453f775SEmil Constantinescu       if (tol > 0.) {
49637453f775SEmil Constantinescu         sum += PetscSqr(diff / tol);
49647453f775SEmil Constantinescu         n_loc++;
49657453f775SEmil Constantinescu       }
49669c6b16b5SShri Abhyankar     }
49679c6b16b5SShri Abhyankar   }
49689566063dSJacob Faibussowitsch   PetscCall(VecRestoreArrayRead(U, &u));
49699566063dSJacob Faibussowitsch   PetscCall(VecRestoreArrayRead(Y, &y));
49709c6b16b5SShri Abhyankar 
49717453f775SEmil Constantinescu   err_loc[0] = sum;
49727453f775SEmil Constantinescu   err_loc[1] = suma;
49737453f775SEmil Constantinescu   err_loc[2] = sumr;
49747453f775SEmil Constantinescu   err_loc[3] = (PetscReal)n_loc;
49757453f775SEmil Constantinescu   err_loc[4] = (PetscReal)na_loc;
49767453f775SEmil Constantinescu   err_loc[5] = (PetscReal)nr_loc;
49777453f775SEmil Constantinescu 
49781c2dc1cbSBarry Smith   PetscCall(MPIU_Allreduce(err_loc, err_glb, 6, MPIU_REAL, MPIU_SUM, PetscObjectComm((PetscObject)ts)));
49797453f775SEmil Constantinescu 
49807453f775SEmil Constantinescu   gsum   = err_glb[0];
49817453f775SEmil Constantinescu   gsuma  = err_glb[1];
49827453f775SEmil Constantinescu   gsumr  = err_glb[2];
49837453f775SEmil Constantinescu   n_glb  = err_glb[3];
49847453f775SEmil Constantinescu   na_glb = err_glb[4];
49857453f775SEmil Constantinescu   nr_glb = err_glb[5];
49867453f775SEmil Constantinescu 
4987b1316ef9SEmil Constantinescu   *norm = 0.;
49881e66621cSBarry Smith   if (n_glb > 0.) *norm = PetscSqrtReal(gsum / n_glb);
4989b1316ef9SEmil Constantinescu   *norma = 0.;
49901e66621cSBarry Smith   if (na_glb > 0.) *norma = PetscSqrtReal(gsuma / na_glb);
4991b1316ef9SEmil Constantinescu   *normr = 0.;
49921e66621cSBarry Smith   if (nr_glb > 0.) *normr = PetscSqrtReal(gsumr / nr_glb);
49939c6b16b5SShri Abhyankar 
49943c633725SBarry Smith   PetscCheck(!PetscIsInfOrNanScalar(*norm), PetscObjectComm((PetscObject)ts), PETSC_ERR_FP, "Infinite or not-a-number generated in norm");
49953c633725SBarry Smith   PetscCheck(!PetscIsInfOrNanScalar(*norma), PetscObjectComm((PetscObject)ts), PETSC_ERR_FP, "Infinite or not-a-number generated in norma");
49963c633725SBarry Smith   PetscCheck(!PetscIsInfOrNanScalar(*normr), PetscObjectComm((PetscObject)ts), PETSC_ERR_FP, "Infinite or not-a-number generated in normr");
49973ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
49989c6b16b5SShri Abhyankar }
49999c6b16b5SShri Abhyankar 
50009c6b16b5SShri Abhyankar /*@
5001a4868fbcSLisandro Dalcin    TSErrorWeightedNormInfinity - compute a weighted infinity-norm of the difference between two state vectors
50029c6b16b5SShri Abhyankar 
5003c3339decSBarry Smith    Collective
50049c6b16b5SShri Abhyankar 
50054165533cSJose E. Roman    Input Parameters:
50069c6b16b5SShri Abhyankar +  ts - time stepping context
5007a4868fbcSLisandro Dalcin .  U - state vector, usually ts->vec_sol
5008a4868fbcSLisandro Dalcin -  Y - state vector to be compared to U
50099c6b16b5SShri Abhyankar 
50104165533cSJose E. Roman    Output Parameters:
5011a2b725a8SWilliam Gropp +  norm - weighted norm, a value of 1.0 means that the error matches the tolerances
50127453f775SEmil Constantinescu .  norma - weighted norm based on the absolute tolerance, a value of 1.0 means that the error matches the tolerances
5013a2b725a8SWilliam Gropp -  normr - weighted norm based on the relative tolerance, a value of 1.0 means that the error matches the tolerances
50149c6b16b5SShri Abhyankar 
50159c6b16b5SShri Abhyankar    Level: developer
50169c6b16b5SShri Abhyankar 
5017bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSErrorWeightedNorm()`, `TSErrorWeightedNorm2()`
50189c6b16b5SShri Abhyankar @*/
5019d71ae5a4SJacob Faibussowitsch PetscErrorCode TSErrorWeightedNormInfinity(TS ts, Vec U, Vec Y, PetscReal *norm, PetscReal *norma, PetscReal *normr)
5020d71ae5a4SJacob Faibussowitsch {
50217453f775SEmil Constantinescu   PetscInt           i, n, N, rstart;
50229c6b16b5SShri Abhyankar   const PetscScalar *u, *y;
50237453f775SEmil Constantinescu   PetscReal          max, gmax, maxa, gmaxa, maxr, gmaxr;
50247453f775SEmil Constantinescu   PetscReal          tol, tola, tolr, diff;
50257453f775SEmil Constantinescu   PetscReal          err_loc[3], err_glb[3];
50269c6b16b5SShri Abhyankar 
50279c6b16b5SShri Abhyankar   PetscFunctionBegin;
50289c6b16b5SShri Abhyankar   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
5029a4868fbcSLisandro Dalcin   PetscValidHeaderSpecific(U, VEC_CLASSID, 2);
5030a4868fbcSLisandro Dalcin   PetscValidHeaderSpecific(Y, VEC_CLASSID, 3);
5031a4868fbcSLisandro Dalcin   PetscValidType(U, 2);
5032a4868fbcSLisandro Dalcin   PetscValidType(Y, 3);
5033a4868fbcSLisandro Dalcin   PetscCheckSameComm(U, 2, Y, 3);
5034dadcf809SJacob Faibussowitsch   PetscValidRealPointer(norm, 4);
5035dadcf809SJacob Faibussowitsch   PetscValidRealPointer(norma, 5);
5036dadcf809SJacob Faibussowitsch   PetscValidRealPointer(normr, 6);
50373c633725SBarry Smith   PetscCheck(U != Y, PetscObjectComm((PetscObject)U), PETSC_ERR_ARG_IDN, "U and Y cannot be the same vector");
50389c6b16b5SShri Abhyankar 
50399566063dSJacob Faibussowitsch   PetscCall(VecGetSize(U, &N));
50409566063dSJacob Faibussowitsch   PetscCall(VecGetLocalSize(U, &n));
50419566063dSJacob Faibussowitsch   PetscCall(VecGetOwnershipRange(U, &rstart, NULL));
50429566063dSJacob Faibussowitsch   PetscCall(VecGetArrayRead(U, &u));
50439566063dSJacob Faibussowitsch   PetscCall(VecGetArrayRead(Y, &y));
50447453f775SEmil Constantinescu 
50457453f775SEmil Constantinescu   max  = 0.;
50467453f775SEmil Constantinescu   maxa = 0.;
50477453f775SEmil Constantinescu   maxr = 0.;
50487453f775SEmil Constantinescu 
50497453f775SEmil Constantinescu   if (ts->vatol && ts->vrtol) { /* vector atol, vector rtol */
50509c6b16b5SShri Abhyankar     const PetscScalar *atol, *rtol;
50519566063dSJacob Faibussowitsch     PetscCall(VecGetArrayRead(ts->vatol, &atol));
50529566063dSJacob Faibussowitsch     PetscCall(VecGetArrayRead(ts->vrtol, &rtol));
50537453f775SEmil Constantinescu 
50547453f775SEmil Constantinescu     for (i = 0; i < n; i++) {
505576cddca1SEmil Constantinescu       SkipSmallValue(y[i], u[i], ts->adapt->ignore_max);
50567453f775SEmil Constantinescu       diff = PetscAbsScalar(y[i] - u[i]);
50577453f775SEmil Constantinescu       tola = PetscRealPart(atol[i]);
50587453f775SEmil Constantinescu       tolr = PetscRealPart(rtol[i]) * PetscMax(PetscAbsScalar(u[i]), PetscAbsScalar(y[i]));
50597453f775SEmil Constantinescu       tol  = tola + tolr;
50601e66621cSBarry Smith       if (tola > 0.) maxa = PetscMax(maxa, diff / tola);
50611e66621cSBarry Smith       if (tolr > 0.) maxr = PetscMax(maxr, diff / tolr);
50621e66621cSBarry Smith       if (tol > 0.) max = PetscMax(max, diff / tol);
50639c6b16b5SShri Abhyankar     }
50649566063dSJacob Faibussowitsch     PetscCall(VecRestoreArrayRead(ts->vatol, &atol));
50659566063dSJacob Faibussowitsch     PetscCall(VecRestoreArrayRead(ts->vrtol, &rtol));
50669c6b16b5SShri Abhyankar   } else if (ts->vatol) { /* vector atol, scalar rtol */
50679c6b16b5SShri Abhyankar     const PetscScalar *atol;
50689566063dSJacob Faibussowitsch     PetscCall(VecGetArrayRead(ts->vatol, &atol));
50697453f775SEmil Constantinescu     for (i = 0; i < n; i++) {
507076cddca1SEmil Constantinescu       SkipSmallValue(y[i], u[i], ts->adapt->ignore_max);
50717453f775SEmil Constantinescu       diff = PetscAbsScalar(y[i] - u[i]);
50727453f775SEmil Constantinescu       tola = PetscRealPart(atol[i]);
50737453f775SEmil Constantinescu       tolr = ts->rtol * PetscMax(PetscAbsScalar(u[i]), PetscAbsScalar(y[i]));
50747453f775SEmil Constantinescu       tol  = tola + tolr;
50751e66621cSBarry Smith       if (tola > 0.) maxa = PetscMax(maxa, diff / tola);
50761e66621cSBarry Smith       if (tolr > 0.) maxr = PetscMax(maxr, diff / tolr);
50771e66621cSBarry Smith       if (tol > 0.) max = PetscMax(max, diff / tol);
50789c6b16b5SShri Abhyankar     }
50799566063dSJacob Faibussowitsch     PetscCall(VecRestoreArrayRead(ts->vatol, &atol));
50809c6b16b5SShri Abhyankar   } else if (ts->vrtol) { /* scalar atol, vector rtol */
50819c6b16b5SShri Abhyankar     const PetscScalar *rtol;
50829566063dSJacob Faibussowitsch     PetscCall(VecGetArrayRead(ts->vrtol, &rtol));
50837453f775SEmil Constantinescu 
50847453f775SEmil Constantinescu     for (i = 0; i < n; i++) {
508576cddca1SEmil Constantinescu       SkipSmallValue(y[i], u[i], ts->adapt->ignore_max);
50867453f775SEmil Constantinescu       diff = PetscAbsScalar(y[i] - u[i]);
50877453f775SEmil Constantinescu       tola = ts->atol;
50887453f775SEmil Constantinescu       tolr = PetscRealPart(rtol[i]) * PetscMax(PetscAbsScalar(u[i]), PetscAbsScalar(y[i]));
50897453f775SEmil Constantinescu       tol  = tola + tolr;
50901e66621cSBarry Smith       if (tola > 0.) maxa = PetscMax(maxa, diff / tola);
50911e66621cSBarry Smith       if (tolr > 0.) maxr = PetscMax(maxr, diff / tolr);
50921e66621cSBarry Smith       if (tol > 0.) max = PetscMax(max, diff / tol);
50939c6b16b5SShri Abhyankar     }
50949566063dSJacob Faibussowitsch     PetscCall(VecRestoreArrayRead(ts->vrtol, &rtol));
50959c6b16b5SShri Abhyankar   } else { /* scalar atol, scalar rtol */
50967453f775SEmil Constantinescu 
50977453f775SEmil Constantinescu     for (i = 0; i < n; i++) {
509876cddca1SEmil Constantinescu       SkipSmallValue(y[i], u[i], ts->adapt->ignore_max);
50997453f775SEmil Constantinescu       diff = PetscAbsScalar(y[i] - u[i]);
51007453f775SEmil Constantinescu       tola = ts->atol;
51017453f775SEmil Constantinescu       tolr = ts->rtol * PetscMax(PetscAbsScalar(u[i]), PetscAbsScalar(y[i]));
51027453f775SEmil Constantinescu       tol  = tola + tolr;
51031e66621cSBarry Smith       if (tola > 0.) maxa = PetscMax(maxa, diff / tola);
51041e66621cSBarry Smith       if (tolr > 0.) maxr = PetscMax(maxr, diff / tolr);
51051e66621cSBarry Smith       if (tol > 0.) max = PetscMax(max, diff / tol);
51069c6b16b5SShri Abhyankar     }
51079c6b16b5SShri Abhyankar   }
51089566063dSJacob Faibussowitsch   PetscCall(VecRestoreArrayRead(U, &u));
51099566063dSJacob Faibussowitsch   PetscCall(VecRestoreArrayRead(Y, &y));
51107453f775SEmil Constantinescu   err_loc[0] = max;
51117453f775SEmil Constantinescu   err_loc[1] = maxa;
51127453f775SEmil Constantinescu   err_loc[2] = maxr;
51131c2dc1cbSBarry Smith   PetscCall(MPIU_Allreduce(err_loc, err_glb, 3, MPIU_REAL, MPIU_MAX, PetscObjectComm((PetscObject)ts)));
51147453f775SEmil Constantinescu   gmax  = err_glb[0];
51157453f775SEmil Constantinescu   gmaxa = err_glb[1];
51167453f775SEmil Constantinescu   gmaxr = err_glb[2];
51179c6b16b5SShri Abhyankar 
51189c6b16b5SShri Abhyankar   *norm  = gmax;
51197453f775SEmil Constantinescu   *norma = gmaxa;
51207453f775SEmil Constantinescu   *normr = gmaxr;
51213c633725SBarry Smith   PetscCheck(!PetscIsInfOrNanScalar(*norm), PetscObjectComm((PetscObject)ts), PETSC_ERR_FP, "Infinite or not-a-number generated in norm");
51223c633725SBarry Smith   PetscCheck(!PetscIsInfOrNanScalar(*norma), PetscObjectComm((PetscObject)ts), PETSC_ERR_FP, "Infinite or not-a-number generated in norma");
51233c633725SBarry Smith   PetscCheck(!PetscIsInfOrNanScalar(*normr), PetscObjectComm((PetscObject)ts), PETSC_ERR_FP, "Infinite or not-a-number generated in normr");
51243ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
51259c6b16b5SShri Abhyankar }
51269c6b16b5SShri Abhyankar 
51271c3436cfSJed Brown /*@
51288a175baeSEmil Constantinescu    TSErrorWeightedNorm - compute a weighted norm of the difference between two state vectors based on supplied absolute and relative tolerances
51291c3436cfSJed Brown 
5130c3339decSBarry Smith    Collective
51311c3436cfSJed Brown 
51324165533cSJose E. Roman    Input Parameters:
51331c3436cfSJed Brown +  ts - time stepping context
5134a4868fbcSLisandro Dalcin .  U - state vector, usually ts->vec_sol
5135a4868fbcSLisandro Dalcin .  Y - state vector to be compared to U
5136bcf0153eSBarry Smith -  wnormtype - norm type, either `NORM_2` or `NORM_INFINITY`
51377619abb3SShri 
51384165533cSJose E. Roman    Output Parameters:
5139a2b725a8SWilliam Gropp +  norm  - weighted norm, a value of 1.0 achieves a balance between absolute and relative tolerances
51408a175baeSEmil Constantinescu .  norma - weighted norm, a value of 1.0 means that the error meets the absolute tolerance set by the user
5141a2b725a8SWilliam Gropp -  normr - weighted norm, a value of 1.0 means that the error meets the relative tolerance set by the user
5142a4868fbcSLisandro Dalcin 
5143bcf0153eSBarry Smith    Options Database Key:
5144a4868fbcSLisandro Dalcin .  -ts_adapt_wnormtype <wnormtype> - 2, INFINITY
5145a4868fbcSLisandro Dalcin 
51461c3436cfSJed Brown    Level: developer
51471c3436cfSJed Brown 
5148bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSErrorWeightedNormInfinity()`, `TSErrorWeightedNorm2()`, `TSErrorWeightedENorm`
51491c3436cfSJed Brown @*/
5150d71ae5a4SJacob Faibussowitsch PetscErrorCode TSErrorWeightedNorm(TS ts, Vec U, Vec Y, NormType wnormtype, PetscReal *norm, PetscReal *norma, PetscReal *normr)
5151d71ae5a4SJacob Faibussowitsch {
51521c3436cfSJed Brown   PetscFunctionBegin;
51531e66621cSBarry Smith   if (wnormtype == NORM_2) PetscCall(TSErrorWeightedNorm2(ts, U, Y, norm, norma, normr));
51541e66621cSBarry Smith   else if (wnormtype == NORM_INFINITY) PetscCall(TSErrorWeightedNormInfinity(ts, U, Y, norm, norma, normr));
51551e66621cSBarry Smith   else SETERRQ(PETSC_COMM_SELF, PETSC_ERR_SUP, "No support for norm type %s", NormTypes[wnormtype]);
51563ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
51571c3436cfSJed Brown }
51581c3436cfSJed Brown 
51598a175baeSEmil Constantinescu /*@
51608a175baeSEmil Constantinescu    TSErrorWeightedENorm2 - compute a weighted 2 error norm based on supplied absolute and relative tolerances
51618a175baeSEmil Constantinescu 
5162c3339decSBarry Smith    Collective
51638a175baeSEmil Constantinescu 
51644165533cSJose E. Roman    Input Parameters:
51658a175baeSEmil Constantinescu +  ts - time stepping context
51668a175baeSEmil Constantinescu .  E - error vector
51678a175baeSEmil Constantinescu .  U - state vector, usually ts->vec_sol
51688a175baeSEmil Constantinescu -  Y - state vector, previous time step
51698a175baeSEmil Constantinescu 
51704165533cSJose E. Roman    Output Parameters:
5171a2b725a8SWilliam Gropp +  norm - weighted norm, a value of 1.0 means that the error matches the tolerances
51728a175baeSEmil Constantinescu .  norma - weighted norm based on the absolute tolerance, a value of 1.0 means that the error matches the tolerances
5173a2b725a8SWilliam Gropp -  normr - weighted norm based on the relative tolerance, a value of 1.0 means that the error matches the tolerances
51748a175baeSEmil Constantinescu 
51758a175baeSEmil Constantinescu    Level: developer
51768a175baeSEmil Constantinescu 
5177bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSErrorWeightedENorm()`, `TSErrorWeightedENormInfinity()`
51788a175baeSEmil Constantinescu @*/
5179d71ae5a4SJacob Faibussowitsch PetscErrorCode TSErrorWeightedENorm2(TS ts, Vec E, Vec U, Vec Y, PetscReal *norm, PetscReal *norma, PetscReal *normr)
5180d71ae5a4SJacob Faibussowitsch {
51818a175baeSEmil Constantinescu   PetscInt           i, n, N, rstart;
51828a175baeSEmil Constantinescu   PetscInt           n_loc, na_loc, nr_loc;
51838a175baeSEmil Constantinescu   PetscReal          n_glb, na_glb, nr_glb;
51848a175baeSEmil Constantinescu   const PetscScalar *e, *u, *y;
51858a175baeSEmil Constantinescu   PetscReal          err, sum, suma, sumr, gsum, gsuma, gsumr;
51868a175baeSEmil Constantinescu   PetscReal          tol, tola, tolr;
51878a175baeSEmil Constantinescu   PetscReal          err_loc[6], err_glb[6];
51888a175baeSEmil Constantinescu 
51898a175baeSEmil Constantinescu   PetscFunctionBegin;
51908a175baeSEmil Constantinescu   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
51918a175baeSEmil Constantinescu   PetscValidHeaderSpecific(E, VEC_CLASSID, 2);
51928a175baeSEmil Constantinescu   PetscValidHeaderSpecific(U, VEC_CLASSID, 3);
51938a175baeSEmil Constantinescu   PetscValidHeaderSpecific(Y, VEC_CLASSID, 4);
51948a175baeSEmil Constantinescu   PetscValidType(E, 2);
51958a175baeSEmil Constantinescu   PetscValidType(U, 3);
51968a175baeSEmil Constantinescu   PetscValidType(Y, 4);
51978a175baeSEmil Constantinescu   PetscCheckSameComm(E, 2, U, 3);
5198064a246eSJacob Faibussowitsch   PetscCheckSameComm(U, 3, Y, 4);
5199dadcf809SJacob Faibussowitsch   PetscValidRealPointer(norm, 5);
5200dadcf809SJacob Faibussowitsch   PetscValidRealPointer(norma, 6);
5201dadcf809SJacob Faibussowitsch   PetscValidRealPointer(normr, 7);
52028a175baeSEmil Constantinescu 
52039566063dSJacob Faibussowitsch   PetscCall(VecGetSize(E, &N));
52049566063dSJacob Faibussowitsch   PetscCall(VecGetLocalSize(E, &n));
52059566063dSJacob Faibussowitsch   PetscCall(VecGetOwnershipRange(E, &rstart, NULL));
52069566063dSJacob Faibussowitsch   PetscCall(VecGetArrayRead(E, &e));
52079566063dSJacob Faibussowitsch   PetscCall(VecGetArrayRead(U, &u));
52089566063dSJacob Faibussowitsch   PetscCall(VecGetArrayRead(Y, &y));
52099371c9d4SSatish Balay   sum    = 0.;
52109371c9d4SSatish Balay   n_loc  = 0;
52119371c9d4SSatish Balay   suma   = 0.;
52129371c9d4SSatish Balay   na_loc = 0;
52139371c9d4SSatish Balay   sumr   = 0.;
52149371c9d4SSatish Balay   nr_loc = 0;
52158a175baeSEmil Constantinescu   if (ts->vatol && ts->vrtol) {
52168a175baeSEmil Constantinescu     const PetscScalar *atol, *rtol;
52179566063dSJacob Faibussowitsch     PetscCall(VecGetArrayRead(ts->vatol, &atol));
52189566063dSJacob Faibussowitsch     PetscCall(VecGetArrayRead(ts->vrtol, &rtol));
52198a175baeSEmil Constantinescu     for (i = 0; i < n; i++) {
522076cddca1SEmil Constantinescu       SkipSmallValue(y[i], u[i], ts->adapt->ignore_max);
52218a175baeSEmil Constantinescu       err  = PetscAbsScalar(e[i]);
52228a175baeSEmil Constantinescu       tola = PetscRealPart(atol[i]);
52238a175baeSEmil Constantinescu       if (tola > 0.) {
52248a175baeSEmil Constantinescu         suma += PetscSqr(err / tola);
52258a175baeSEmil Constantinescu         na_loc++;
52268a175baeSEmil Constantinescu       }
52278a175baeSEmil Constantinescu       tolr = PetscRealPart(rtol[i]) * PetscMax(PetscAbsScalar(u[i]), PetscAbsScalar(y[i]));
52288a175baeSEmil Constantinescu       if (tolr > 0.) {
52298a175baeSEmil Constantinescu         sumr += PetscSqr(err / tolr);
52308a175baeSEmil Constantinescu         nr_loc++;
52318a175baeSEmil Constantinescu       }
52328a175baeSEmil Constantinescu       tol = tola + tolr;
52338a175baeSEmil Constantinescu       if (tol > 0.) {
52348a175baeSEmil Constantinescu         sum += PetscSqr(err / tol);
52358a175baeSEmil Constantinescu         n_loc++;
52368a175baeSEmil Constantinescu       }
52378a175baeSEmil Constantinescu     }
52389566063dSJacob Faibussowitsch     PetscCall(VecRestoreArrayRead(ts->vatol, &atol));
52399566063dSJacob Faibussowitsch     PetscCall(VecRestoreArrayRead(ts->vrtol, &rtol));
52408a175baeSEmil Constantinescu   } else if (ts->vatol) { /* vector atol, scalar rtol */
52418a175baeSEmil Constantinescu     const PetscScalar *atol;
52429566063dSJacob Faibussowitsch     PetscCall(VecGetArrayRead(ts->vatol, &atol));
52438a175baeSEmil Constantinescu     for (i = 0; i < n; i++) {
524476cddca1SEmil Constantinescu       SkipSmallValue(y[i], u[i], ts->adapt->ignore_max);
52458a175baeSEmil Constantinescu       err  = PetscAbsScalar(e[i]);
52468a175baeSEmil Constantinescu       tola = PetscRealPart(atol[i]);
52478a175baeSEmil Constantinescu       if (tola > 0.) {
52488a175baeSEmil Constantinescu         suma += PetscSqr(err / tola);
52498a175baeSEmil Constantinescu         na_loc++;
52508a175baeSEmil Constantinescu       }
52518a175baeSEmil Constantinescu       tolr = ts->rtol * PetscMax(PetscAbsScalar(u[i]), PetscAbsScalar(y[i]));
52528a175baeSEmil Constantinescu       if (tolr > 0.) {
52538a175baeSEmil Constantinescu         sumr += PetscSqr(err / tolr);
52548a175baeSEmil Constantinescu         nr_loc++;
52558a175baeSEmil Constantinescu       }
52568a175baeSEmil Constantinescu       tol = tola + tolr;
52578a175baeSEmil Constantinescu       if (tol > 0.) {
52588a175baeSEmil Constantinescu         sum += PetscSqr(err / tol);
52598a175baeSEmil Constantinescu         n_loc++;
52608a175baeSEmil Constantinescu       }
52618a175baeSEmil Constantinescu     }
52629566063dSJacob Faibussowitsch     PetscCall(VecRestoreArrayRead(ts->vatol, &atol));
52638a175baeSEmil Constantinescu   } else if (ts->vrtol) { /* scalar atol, vector rtol */
52648a175baeSEmil Constantinescu     const PetscScalar *rtol;
52659566063dSJacob Faibussowitsch     PetscCall(VecGetArrayRead(ts->vrtol, &rtol));
52668a175baeSEmil Constantinescu     for (i = 0; i < n; i++) {
526776cddca1SEmil Constantinescu       SkipSmallValue(y[i], u[i], ts->adapt->ignore_max);
52688a175baeSEmil Constantinescu       err  = PetscAbsScalar(e[i]);
52698a175baeSEmil Constantinescu       tola = ts->atol;
52708a175baeSEmil Constantinescu       if (tola > 0.) {
52718a175baeSEmil Constantinescu         suma += PetscSqr(err / tola);
52728a175baeSEmil Constantinescu         na_loc++;
52738a175baeSEmil Constantinescu       }
52748a175baeSEmil Constantinescu       tolr = PetscRealPart(rtol[i]) * PetscMax(PetscAbsScalar(u[i]), PetscAbsScalar(y[i]));
52758a175baeSEmil Constantinescu       if (tolr > 0.) {
52768a175baeSEmil Constantinescu         sumr += PetscSqr(err / tolr);
52778a175baeSEmil Constantinescu         nr_loc++;
52788a175baeSEmil Constantinescu       }
52798a175baeSEmil Constantinescu       tol = tola + tolr;
52808a175baeSEmil Constantinescu       if (tol > 0.) {
52818a175baeSEmil Constantinescu         sum += PetscSqr(err / tol);
52828a175baeSEmil Constantinescu         n_loc++;
52838a175baeSEmil Constantinescu       }
52848a175baeSEmil Constantinescu     }
52859566063dSJacob Faibussowitsch     PetscCall(VecRestoreArrayRead(ts->vrtol, &rtol));
52868a175baeSEmil Constantinescu   } else { /* scalar atol, scalar rtol */
52878a175baeSEmil Constantinescu     for (i = 0; i < n; i++) {
528876cddca1SEmil Constantinescu       SkipSmallValue(y[i], u[i], ts->adapt->ignore_max);
52898a175baeSEmil Constantinescu       err  = PetscAbsScalar(e[i]);
52908a175baeSEmil Constantinescu       tola = ts->atol;
52918a175baeSEmil Constantinescu       if (tola > 0.) {
52928a175baeSEmil Constantinescu         suma += PetscSqr(err / tola);
52938a175baeSEmil Constantinescu         na_loc++;
52948a175baeSEmil Constantinescu       }
52958a175baeSEmil Constantinescu       tolr = ts->rtol * PetscMax(PetscAbsScalar(u[i]), PetscAbsScalar(y[i]));
52968a175baeSEmil Constantinescu       if (tolr > 0.) {
52978a175baeSEmil Constantinescu         sumr += PetscSqr(err / tolr);
52988a175baeSEmil Constantinescu         nr_loc++;
52998a175baeSEmil Constantinescu       }
53008a175baeSEmil Constantinescu       tol = tola + tolr;
53018a175baeSEmil Constantinescu       if (tol > 0.) {
53028a175baeSEmil Constantinescu         sum += PetscSqr(err / tol);
53038a175baeSEmil Constantinescu         n_loc++;
53048a175baeSEmil Constantinescu       }
53058a175baeSEmil Constantinescu     }
53068a175baeSEmil Constantinescu   }
53079566063dSJacob Faibussowitsch   PetscCall(VecRestoreArrayRead(E, &e));
53089566063dSJacob Faibussowitsch   PetscCall(VecRestoreArrayRead(U, &u));
53099566063dSJacob Faibussowitsch   PetscCall(VecRestoreArrayRead(Y, &y));
53108a175baeSEmil Constantinescu 
53118a175baeSEmil Constantinescu   err_loc[0] = sum;
53128a175baeSEmil Constantinescu   err_loc[1] = suma;
53138a175baeSEmil Constantinescu   err_loc[2] = sumr;
53148a175baeSEmil Constantinescu   err_loc[3] = (PetscReal)n_loc;
53158a175baeSEmil Constantinescu   err_loc[4] = (PetscReal)na_loc;
53168a175baeSEmil Constantinescu   err_loc[5] = (PetscReal)nr_loc;
53178a175baeSEmil Constantinescu 
53181c2dc1cbSBarry Smith   PetscCall(MPIU_Allreduce(err_loc, err_glb, 6, MPIU_REAL, MPIU_SUM, PetscObjectComm((PetscObject)ts)));
53198a175baeSEmil Constantinescu 
53208a175baeSEmil Constantinescu   gsum   = err_glb[0];
53218a175baeSEmil Constantinescu   gsuma  = err_glb[1];
53228a175baeSEmil Constantinescu   gsumr  = err_glb[2];
53238a175baeSEmil Constantinescu   n_glb  = err_glb[3];
53248a175baeSEmil Constantinescu   na_glb = err_glb[4];
53258a175baeSEmil Constantinescu   nr_glb = err_glb[5];
53268a175baeSEmil Constantinescu 
53278a175baeSEmil Constantinescu   *norm = 0.;
53281e66621cSBarry Smith   if (n_glb > 0.) *norm = PetscSqrtReal(gsum / n_glb);
53298a175baeSEmil Constantinescu   *norma = 0.;
53301e66621cSBarry Smith   if (na_glb > 0.) *norma = PetscSqrtReal(gsuma / na_glb);
53318a175baeSEmil Constantinescu   *normr = 0.;
53321e66621cSBarry Smith   if (nr_glb > 0.) *normr = PetscSqrtReal(gsumr / nr_glb);
53338a175baeSEmil Constantinescu 
53343c633725SBarry Smith   PetscCheck(!PetscIsInfOrNanScalar(*norm), PetscObjectComm((PetscObject)ts), PETSC_ERR_FP, "Infinite or not-a-number generated in norm");
53353c633725SBarry Smith   PetscCheck(!PetscIsInfOrNanScalar(*norma), PetscObjectComm((PetscObject)ts), PETSC_ERR_FP, "Infinite or not-a-number generated in norma");
53363c633725SBarry Smith   PetscCheck(!PetscIsInfOrNanScalar(*normr), PetscObjectComm((PetscObject)ts), PETSC_ERR_FP, "Infinite or not-a-number generated in normr");
53373ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
53388a175baeSEmil Constantinescu }
53398a175baeSEmil Constantinescu 
53408a175baeSEmil Constantinescu /*@
53418a175baeSEmil Constantinescu    TSErrorWeightedENormInfinity - compute a weighted infinity error norm based on supplied absolute and relative tolerances
5342bcf0153eSBarry Smith 
5343c3339decSBarry Smith    Collective
53448a175baeSEmil Constantinescu 
53454165533cSJose E. Roman    Input Parameters:
53468a175baeSEmil Constantinescu +  ts - time stepping context
53478a175baeSEmil Constantinescu .  E - error vector
53488a175baeSEmil Constantinescu .  U - state vector, usually ts->vec_sol
53498a175baeSEmil Constantinescu -  Y - state vector, previous time step
53508a175baeSEmil Constantinescu 
53514165533cSJose E. Roman    Output Parameters:
5352a2b725a8SWilliam Gropp +  norm - weighted norm, a value of 1.0 means that the error matches the tolerances
53538a175baeSEmil Constantinescu .  norma - weighted norm based on the absolute tolerance, a value of 1.0 means that the error matches the tolerances
5354a2b725a8SWilliam Gropp -  normr - weighted norm based on the relative tolerance, a value of 1.0 means that the error matches the tolerances
53558a175baeSEmil Constantinescu 
53568a175baeSEmil Constantinescu    Level: developer
53578a175baeSEmil Constantinescu 
5358bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSErrorWeightedENorm()`, `TSErrorWeightedENorm2()`
53598a175baeSEmil Constantinescu @*/
5360d71ae5a4SJacob Faibussowitsch PetscErrorCode TSErrorWeightedENormInfinity(TS ts, Vec E, Vec U, Vec Y, PetscReal *norm, PetscReal *norma, PetscReal *normr)
5361d71ae5a4SJacob Faibussowitsch {
53628a175baeSEmil Constantinescu   PetscInt           i, n, N, rstart;
53638a175baeSEmil Constantinescu   const PetscScalar *e, *u, *y;
53648a175baeSEmil Constantinescu   PetscReal          err, max, gmax, maxa, gmaxa, maxr, gmaxr;
53658a175baeSEmil Constantinescu   PetscReal          tol, tola, tolr;
53668a175baeSEmil Constantinescu   PetscReal          err_loc[3], err_glb[3];
53678a175baeSEmil Constantinescu 
53688a175baeSEmil Constantinescu   PetscFunctionBegin;
53698a175baeSEmil Constantinescu   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
53708a175baeSEmil Constantinescu   PetscValidHeaderSpecific(E, VEC_CLASSID, 2);
53718a175baeSEmil Constantinescu   PetscValidHeaderSpecific(U, VEC_CLASSID, 3);
53728a175baeSEmil Constantinescu   PetscValidHeaderSpecific(Y, VEC_CLASSID, 4);
53738a175baeSEmil Constantinescu   PetscValidType(E, 2);
53748a175baeSEmil Constantinescu   PetscValidType(U, 3);
53758a175baeSEmil Constantinescu   PetscValidType(Y, 4);
53768a175baeSEmil Constantinescu   PetscCheckSameComm(E, 2, U, 3);
5377064a246eSJacob Faibussowitsch   PetscCheckSameComm(U, 3, Y, 4);
5378dadcf809SJacob Faibussowitsch   PetscValidRealPointer(norm, 5);
5379dadcf809SJacob Faibussowitsch   PetscValidRealPointer(norma, 6);
5380dadcf809SJacob Faibussowitsch   PetscValidRealPointer(normr, 7);
53818a175baeSEmil Constantinescu 
53829566063dSJacob Faibussowitsch   PetscCall(VecGetSize(E, &N));
53839566063dSJacob Faibussowitsch   PetscCall(VecGetLocalSize(E, &n));
53849566063dSJacob Faibussowitsch   PetscCall(VecGetOwnershipRange(E, &rstart, NULL));
53859566063dSJacob Faibussowitsch   PetscCall(VecGetArrayRead(E, &e));
53869566063dSJacob Faibussowitsch   PetscCall(VecGetArrayRead(U, &u));
53879566063dSJacob Faibussowitsch   PetscCall(VecGetArrayRead(Y, &y));
53888a175baeSEmil Constantinescu 
53898a175baeSEmil Constantinescu   max  = 0.;
53908a175baeSEmil Constantinescu   maxa = 0.;
53918a175baeSEmil Constantinescu   maxr = 0.;
53928a175baeSEmil Constantinescu 
53938a175baeSEmil Constantinescu   if (ts->vatol && ts->vrtol) { /* vector atol, vector rtol */
53948a175baeSEmil Constantinescu     const PetscScalar *atol, *rtol;
53959566063dSJacob Faibussowitsch     PetscCall(VecGetArrayRead(ts->vatol, &atol));
53969566063dSJacob Faibussowitsch     PetscCall(VecGetArrayRead(ts->vrtol, &rtol));
53978a175baeSEmil Constantinescu 
53988a175baeSEmil Constantinescu     for (i = 0; i < n; i++) {
539976cddca1SEmil Constantinescu       SkipSmallValue(y[i], u[i], ts->adapt->ignore_max);
54008a175baeSEmil Constantinescu       err  = PetscAbsScalar(e[i]);
54018a175baeSEmil Constantinescu       tola = PetscRealPart(atol[i]);
54028a175baeSEmil Constantinescu       tolr = PetscRealPart(rtol[i]) * PetscMax(PetscAbsScalar(u[i]), PetscAbsScalar(y[i]));
54038a175baeSEmil Constantinescu       tol  = tola + tolr;
54041e66621cSBarry Smith       if (tola > 0.) maxa = PetscMax(maxa, err / tola);
54051e66621cSBarry Smith       if (tolr > 0.) maxr = PetscMax(maxr, err / tolr);
54061e66621cSBarry Smith       if (tol > 0.) max = PetscMax(max, err / tol);
54078a175baeSEmil Constantinescu     }
54089566063dSJacob Faibussowitsch     PetscCall(VecRestoreArrayRead(ts->vatol, &atol));
54099566063dSJacob Faibussowitsch     PetscCall(VecRestoreArrayRead(ts->vrtol, &rtol));
54108a175baeSEmil Constantinescu   } else if (ts->vatol) { /* vector atol, scalar rtol */
54118a175baeSEmil Constantinescu     const PetscScalar *atol;
54129566063dSJacob Faibussowitsch     PetscCall(VecGetArrayRead(ts->vatol, &atol));
54138a175baeSEmil Constantinescu     for (i = 0; i < n; i++) {
541476cddca1SEmil Constantinescu       SkipSmallValue(y[i], u[i], ts->adapt->ignore_max);
54158a175baeSEmil Constantinescu       err  = PetscAbsScalar(e[i]);
54168a175baeSEmil Constantinescu       tola = PetscRealPart(atol[i]);
54178a175baeSEmil Constantinescu       tolr = ts->rtol * PetscMax(PetscAbsScalar(u[i]), PetscAbsScalar(y[i]));
54188a175baeSEmil Constantinescu       tol  = tola + tolr;
54191e66621cSBarry Smith       if (tola > 0.) maxa = PetscMax(maxa, err / tola);
54201e66621cSBarry Smith       if (tolr > 0.) maxr = PetscMax(maxr, err / tolr);
54211e66621cSBarry Smith       if (tol > 0.) max = PetscMax(max, err / tol);
54228a175baeSEmil Constantinescu     }
54239566063dSJacob Faibussowitsch     PetscCall(VecRestoreArrayRead(ts->vatol, &atol));
54248a175baeSEmil Constantinescu   } else if (ts->vrtol) { /* scalar atol, vector rtol */
54258a175baeSEmil Constantinescu     const PetscScalar *rtol;
54269566063dSJacob Faibussowitsch     PetscCall(VecGetArrayRead(ts->vrtol, &rtol));
54278a175baeSEmil Constantinescu 
54288a175baeSEmil Constantinescu     for (i = 0; i < n; i++) {
542976cddca1SEmil Constantinescu       SkipSmallValue(y[i], u[i], ts->adapt->ignore_max);
54308a175baeSEmil Constantinescu       err  = PetscAbsScalar(e[i]);
54318a175baeSEmil Constantinescu       tola = ts->atol;
54328a175baeSEmil Constantinescu       tolr = PetscRealPart(rtol[i]) * PetscMax(PetscAbsScalar(u[i]), PetscAbsScalar(y[i]));
54338a175baeSEmil Constantinescu       tol  = tola + tolr;
54341e66621cSBarry Smith       if (tola > 0.) maxa = PetscMax(maxa, err / tola);
54351e66621cSBarry Smith       if (tolr > 0.) maxr = PetscMax(maxr, err / tolr);
54361e66621cSBarry Smith       if (tol > 0.) max = PetscMax(max, err / tol);
54378a175baeSEmil Constantinescu     }
54389566063dSJacob Faibussowitsch     PetscCall(VecRestoreArrayRead(ts->vrtol, &rtol));
54398a175baeSEmil Constantinescu   } else { /* scalar atol, scalar rtol */
54408a175baeSEmil Constantinescu 
54418a175baeSEmil Constantinescu     for (i = 0; i < n; i++) {
544276cddca1SEmil Constantinescu       SkipSmallValue(y[i], u[i], ts->adapt->ignore_max);
54438a175baeSEmil Constantinescu       err  = PetscAbsScalar(e[i]);
54448a175baeSEmil Constantinescu       tola = ts->atol;
54458a175baeSEmil Constantinescu       tolr = ts->rtol * PetscMax(PetscAbsScalar(u[i]), PetscAbsScalar(y[i]));
54468a175baeSEmil Constantinescu       tol  = tola + tolr;
54471e66621cSBarry Smith       if (tola > 0.) maxa = PetscMax(maxa, err / tola);
54481e66621cSBarry Smith       if (tolr > 0.) maxr = PetscMax(maxr, err / tolr);
54491e66621cSBarry Smith       if (tol > 0.) max = PetscMax(max, err / tol);
54508a175baeSEmil Constantinescu     }
54518a175baeSEmil Constantinescu   }
54529566063dSJacob Faibussowitsch   PetscCall(VecRestoreArrayRead(E, &e));
54539566063dSJacob Faibussowitsch   PetscCall(VecRestoreArrayRead(U, &u));
54549566063dSJacob Faibussowitsch   PetscCall(VecRestoreArrayRead(Y, &y));
54558a175baeSEmil Constantinescu   err_loc[0] = max;
54568a175baeSEmil Constantinescu   err_loc[1] = maxa;
54578a175baeSEmil Constantinescu   err_loc[2] = maxr;
54581c2dc1cbSBarry Smith   PetscCall(MPIU_Allreduce(err_loc, err_glb, 3, MPIU_REAL, MPIU_MAX, PetscObjectComm((PetscObject)ts)));
54598a175baeSEmil Constantinescu   gmax  = err_glb[0];
54608a175baeSEmil Constantinescu   gmaxa = err_glb[1];
54618a175baeSEmil Constantinescu   gmaxr = err_glb[2];
54628a175baeSEmil Constantinescu 
54638a175baeSEmil Constantinescu   *norm  = gmax;
54648a175baeSEmil Constantinescu   *norma = gmaxa;
54658a175baeSEmil Constantinescu   *normr = gmaxr;
54663c633725SBarry Smith   PetscCheck(!PetscIsInfOrNanScalar(*norm), PetscObjectComm((PetscObject)ts), PETSC_ERR_FP, "Infinite or not-a-number generated in norm");
54673c633725SBarry Smith   PetscCheck(!PetscIsInfOrNanScalar(*norma), PetscObjectComm((PetscObject)ts), PETSC_ERR_FP, "Infinite or not-a-number generated in norma");
54683c633725SBarry Smith   PetscCheck(!PetscIsInfOrNanScalar(*normr), PetscObjectComm((PetscObject)ts), PETSC_ERR_FP, "Infinite or not-a-number generated in normr");
54693ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
54708a175baeSEmil Constantinescu }
54718a175baeSEmil Constantinescu 
54728a175baeSEmil Constantinescu /*@
54738a175baeSEmil Constantinescu    TSErrorWeightedENorm - compute a weighted error norm based on supplied absolute and relative tolerances
54748a175baeSEmil Constantinescu 
5475c3339decSBarry Smith    Collective
54768a175baeSEmil Constantinescu 
54774165533cSJose E. Roman    Input Parameters:
54788a175baeSEmil Constantinescu +  ts - time stepping context
54798a175baeSEmil Constantinescu .  E - error vector
54808a175baeSEmil Constantinescu .  U - state vector, usually ts->vec_sol
54818a175baeSEmil Constantinescu .  Y - state vector, previous time step
5482bcf0153eSBarry Smith -  wnormtype - norm type, either `NORM_2` or `NORM_INFINITY`
54838a175baeSEmil Constantinescu 
54844165533cSJose E. Roman    Output Parameters:
5485a2b725a8SWilliam Gropp +  norm  - weighted norm, a value of 1.0 achieves a balance between absolute and relative tolerances
54868a175baeSEmil Constantinescu .  norma - weighted norm, a value of 1.0 means that the error meets the absolute tolerance set by the user
5487a2b725a8SWilliam Gropp -  normr - weighted norm, a value of 1.0 means that the error meets the relative tolerance set by the user
54888a175baeSEmil Constantinescu 
5489bcf0153eSBarry Smith    Options Database Key:
54908a175baeSEmil Constantinescu .  -ts_adapt_wnormtype <wnormtype> - 2, INFINITY
54918a175baeSEmil Constantinescu 
54928a175baeSEmil Constantinescu    Level: developer
54938a175baeSEmil Constantinescu 
5494bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSErrorWeightedENormInfinity()`, `TSErrorWeightedENorm2()`, `TSErrorWeightedNormInfinity()`, `TSErrorWeightedNorm2()`
54958a175baeSEmil Constantinescu @*/
5496d71ae5a4SJacob Faibussowitsch PetscErrorCode TSErrorWeightedENorm(TS ts, Vec E, Vec U, Vec Y, NormType wnormtype, PetscReal *norm, PetscReal *norma, PetscReal *normr)
5497d71ae5a4SJacob Faibussowitsch {
54988a175baeSEmil Constantinescu   PetscFunctionBegin;
54991e66621cSBarry Smith   if (wnormtype == NORM_2) PetscCall(TSErrorWeightedENorm2(ts, E, U, Y, norm, norma, normr));
55001e66621cSBarry Smith   else if (wnormtype == NORM_INFINITY) PetscCall(TSErrorWeightedENormInfinity(ts, E, U, Y, norm, norma, normr));
55011e66621cSBarry Smith   else SETERRQ(PETSC_COMM_SELF, PETSC_ERR_SUP, "No support for norm type %s", NormTypes[wnormtype]);
55023ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
55038a175baeSEmil Constantinescu }
55048a175baeSEmil Constantinescu 
55058d59e960SJed Brown /*@
55068d59e960SJed Brown    TSSetCFLTimeLocal - Set the local CFL constraint relative to forward Euler
55078d59e960SJed Brown 
5508c3339decSBarry Smith    Logically Collective
55098d59e960SJed Brown 
55104165533cSJose E. Roman    Input Parameters:
55118d59e960SJed Brown +  ts - time stepping context
55128d59e960SJed Brown -  cfltime - maximum stable time step if using forward Euler (value can be different on each process)
55138d59e960SJed Brown 
55148d59e960SJed Brown    Note:
55158d59e960SJed Brown    After calling this function, the global CFL time can be obtained by calling TSGetCFLTime()
55168d59e960SJed Brown 
55178d59e960SJed Brown    Level: intermediate
55188d59e960SJed Brown 
5519bcf0153eSBarry Smith .seealso: [](chapter_ts), `TSGetCFLTime()`, `TSADAPTCFL`
55208d59e960SJed Brown @*/
5521d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetCFLTimeLocal(TS ts, PetscReal cfltime)
5522d71ae5a4SJacob Faibussowitsch {
55238d59e960SJed Brown   PetscFunctionBegin;
55248d59e960SJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
55258d59e960SJed Brown   ts->cfltime_local = cfltime;
55268d59e960SJed Brown   ts->cfltime       = -1.;
55273ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
55288d59e960SJed Brown }
55298d59e960SJed Brown 
55308d59e960SJed Brown /*@
55318d59e960SJed Brown    TSGetCFLTime - Get the maximum stable time step according to CFL criteria applied to forward Euler
55328d59e960SJed Brown 
5533c3339decSBarry Smith    Collective
55348d59e960SJed Brown 
55354165533cSJose E. Roman    Input Parameter:
55368d59e960SJed Brown .  ts - time stepping context
55378d59e960SJed Brown 
55384165533cSJose E. Roman    Output Parameter:
55398d59e960SJed Brown .  cfltime - maximum stable time step for forward Euler
55408d59e960SJed Brown 
55418d59e960SJed Brown    Level: advanced
55428d59e960SJed Brown 
5543bcf0153eSBarry Smith .seealso: [](chapter_ts), `TSSetCFLTimeLocal()`
55448d59e960SJed Brown @*/
5545d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetCFLTime(TS ts, PetscReal *cfltime)
5546d71ae5a4SJacob Faibussowitsch {
55478d59e960SJed Brown   PetscFunctionBegin;
55481e66621cSBarry Smith   if (ts->cfltime < 0) PetscCall(MPIU_Allreduce(&ts->cfltime_local, &ts->cfltime, 1, MPIU_REAL, MPIU_MIN, PetscObjectComm((PetscObject)ts)));
55498d59e960SJed Brown   *cfltime = ts->cfltime;
55503ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
55518d59e960SJed Brown }
55528d59e960SJed Brown 
5553d6ebe24aSShri Abhyankar /*@
5554d6ebe24aSShri Abhyankar    TSVISetVariableBounds - Sets the lower and upper bounds for the solution vector. xl <= x <= xu
5555d6ebe24aSShri Abhyankar 
5556d6ebe24aSShri Abhyankar    Input Parameters:
5557bcf0153eSBarry Smith +  ts   - the `TS` context.
5558d6ebe24aSShri Abhyankar .  xl   - lower bound.
5559a2b725a8SWilliam Gropp -  xu   - upper bound.
5560d6ebe24aSShri Abhyankar 
55612bd2b0e6SSatish Balay    Level: advanced
55622bd2b0e6SSatish Balay 
5563bcf0153eSBarry Smith    Note:
5564bcf0153eSBarry Smith    If this routine is not called then the lower and upper bounds are set to
5565bcf0153eSBarry Smith    `PETSC_NINFINITY` and `PETSC_INFINITY` respectively during `SNESSetUp()`.
5566bcf0153eSBarry Smith 
5567bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`
5568d6ebe24aSShri Abhyankar @*/
5569d71ae5a4SJacob Faibussowitsch PetscErrorCode TSVISetVariableBounds(TS ts, Vec xl, Vec xu)
5570d71ae5a4SJacob Faibussowitsch {
5571d6ebe24aSShri Abhyankar   SNES snes;
5572d6ebe24aSShri Abhyankar 
5573d6ebe24aSShri Abhyankar   PetscFunctionBegin;
55749566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts, &snes));
55759566063dSJacob Faibussowitsch   PetscCall(SNESVISetVariableBounds(snes, xl, xu));
55763ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
5577d6ebe24aSShri Abhyankar }
5578d6ebe24aSShri Abhyankar 
5579f9c1d6abSBarry Smith /*@
5580f9c1d6abSBarry Smith    TSComputeLinearStability - computes the linear stability function at a point
5581f9c1d6abSBarry Smith 
5582c3339decSBarry Smith    Collective
5583f9c1d6abSBarry Smith 
5584f9c1d6abSBarry Smith    Input Parameters:
5585bcf0153eSBarry Smith +  ts - the `TS` context
55862fe279fdSBarry Smith .  xr - real part of input argument
55872fe279fdSBarry Smith -  xi - imaginary part of input argument
5588f9c1d6abSBarry Smith 
5589f9c1d6abSBarry Smith    Output Parameters:
55902fe279fdSBarry Smith +  yr - real part of function value
55912fe279fdSBarry Smith -  yi - 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 
577820f4b53cSBarry Smith     Calling sequence of `func`:
57796bc98fa9SBarry Smith $   PetscErrorCode func(TS ts, PetscReal time, Vec state, PetscBool reject)
57806bc98fa9SBarry Smith +   ts - the TS context
57816bc98fa9SBarry Smith .   time - the current time (of the stage)
57826bc98fa9SBarry Smith .   state - the state to check if it is valid
578320f4b53cSBarry Smith -   reject - (output parameter) `PETSC_FALSE` if the state is acceptable, `PETSC_TRUE` if not acceptable
5784cb9d8021SPierre Barbier de Reuille 
5785cb9d8021SPierre Barbier de Reuille     Level: intermediate
5786cb9d8021SPierre Barbier de Reuille 
57876bc98fa9SBarry Smith     Notes:
57886bc98fa9SBarry Smith       If an implicit ODE solver is being used then, in addition to providing this routine, the
5789bcf0153eSBarry Smith       user's code should call `SNESSetFunctionDomainError()` when domain errors occur during
5790bcf0153eSBarry Smith       function evaluations where the functions are provided by `TSSetIFunction()` or `TSSetRHSFunction()`.
5791bcf0153eSBarry Smith       Use `TSGetSNES()` to obtain the `SNES` object
57926bc98fa9SBarry Smith 
5793bcf0153eSBarry Smith     Developer Note:
5794bcf0153eSBarry Smith       The naming of this function is inconsistent with the `SNESSetFunctionDomainError()`
57956bc98fa9SBarry Smith       since one takes a function pointer and the other does not.
57966bc98fa9SBarry Smith 
5797bcf0153eSBarry Smith .seealso: [](chapter_ts), `TSAdaptCheckStage()`, `TSFunctionDomainError()`, `SNESSetFunctionDomainError()`, `TSGetSNES()`
5798cb9d8021SPierre Barbier de Reuille @*/
5799cb9d8021SPierre Barbier de Reuille 
5800d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetFunctionDomainError(TS ts, PetscErrorCode (*func)(TS, PetscReal, Vec, PetscBool *))
5801d71ae5a4SJacob Faibussowitsch {
5802cb9d8021SPierre Barbier de Reuille   PetscFunctionBegin;
5803cb9d8021SPierre Barbier de Reuille   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
5804cb9d8021SPierre Barbier de Reuille   ts->functiondomainerror = func;
58053ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
5806cb9d8021SPierre Barbier de Reuille }
5807cb9d8021SPierre Barbier de Reuille 
5808cb9d8021SPierre Barbier de Reuille /*@
58096bc98fa9SBarry Smith     TSFunctionDomainError - Checks if the current state is valid
5810cb9d8021SPierre Barbier de Reuille 
5811cb9d8021SPierre Barbier de Reuille     Input Parameters:
5812bcf0153eSBarry Smith +    ts - the `TS` context
58136bc98fa9SBarry Smith .    stagetime - time of the simulation
58146bc98fa9SBarry Smith -    Y - state vector to check.
5815cb9d8021SPierre Barbier de Reuille 
5816cb9d8021SPierre Barbier de Reuille     Output Parameter:
5817bcf0153eSBarry Smith .    accept - Set to `PETSC_FALSE` if the current state vector is valid.
581896a0c994SBarry Smith 
58196bc98fa9SBarry Smith     Level: developer
58206bc98fa9SBarry Smith 
5821bcf0153eSBarry Smith     Note:
5822bcf0153eSBarry Smith     This function is called by the `TS` integration routines and calls the user provided function (set with `TSSetFunctionDomainError()`)
5823bcf0153eSBarry Smith     to check if the current state is valid.
5824bcf0153eSBarry Smith 
5825bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSSetFunctionDomainError()`
5826cb9d8021SPierre Barbier de Reuille @*/
5827d71ae5a4SJacob Faibussowitsch PetscErrorCode TSFunctionDomainError(TS ts, PetscReal stagetime, Vec Y, PetscBool *accept)
5828d71ae5a4SJacob Faibussowitsch {
5829cb9d8021SPierre Barbier de Reuille   PetscFunctionBegin;
5830cb9d8021SPierre Barbier de Reuille   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
5831cb9d8021SPierre Barbier de Reuille   *accept = PETSC_TRUE;
58321e66621cSBarry Smith   if (ts->functiondomainerror) PetscCall((*ts->functiondomainerror)(ts, stagetime, Y, accept));
58333ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
5834cb9d8021SPierre Barbier de Reuille }
58351ceb14c0SBarry Smith 
583693b34091SDebojyoti Ghosh /*@C
5837195e9b02SBarry Smith   TSClone - This function clones a time step `TS` object.
583893b34091SDebojyoti Ghosh 
5839d083f849SBarry Smith   Collective
584093b34091SDebojyoti Ghosh 
584193b34091SDebojyoti Ghosh   Input Parameter:
5842bcf0153eSBarry Smith . tsin    - The input `TS`
584393b34091SDebojyoti Ghosh 
584493b34091SDebojyoti Ghosh   Output Parameter:
5845bcf0153eSBarry Smith . tsout   - The output `TS` (cloned)
58465eca1a21SEmil Constantinescu 
58475eca1a21SEmil Constantinescu   Level: developer
584893b34091SDebojyoti Ghosh 
5849bcf0153eSBarry Smith   Notes:
5850bcf0153eSBarry 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.
5851bcf0153eSBarry Smith   It will likely be replaced in the future with a mechanism of switching methods on the fly.
5852bcf0153eSBarry Smith 
5853195e9b02SBarry 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
5854195e9b02SBarry Smith .vb
5855195e9b02SBarry Smith  SNES snes_dup = NULL;
5856195e9b02SBarry Smith  TSGetSNES(ts,&snes_dup);
5857195e9b02SBarry Smith  TSSetSNES(ts,snes_dup);
5858195e9b02SBarry Smith .ve
5859bcf0153eSBarry Smith 
5860bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `SNES`, `TSCreate()`, `TSSetType()`, `TSSetUp()`, `TSDestroy()`, `TSSetProblemType()`
586193b34091SDebojyoti Ghosh @*/
5862d71ae5a4SJacob Faibussowitsch PetscErrorCode TSClone(TS tsin, TS *tsout)
5863d71ae5a4SJacob Faibussowitsch {
586493b34091SDebojyoti Ghosh   TS     t;
5865dc846ba4SSatish Balay   SNES   snes_start;
5866dc846ba4SSatish Balay   DM     dm;
5867dc846ba4SSatish Balay   TSType type;
586893b34091SDebojyoti Ghosh 
586993b34091SDebojyoti Ghosh   PetscFunctionBegin;
587093b34091SDebojyoti Ghosh   PetscValidPointer(tsin, 1);
587193b34091SDebojyoti Ghosh   *tsout = NULL;
587293b34091SDebojyoti Ghosh 
58739566063dSJacob Faibussowitsch   PetscCall(PetscHeaderCreate(t, TS_CLASSID, "TS", "Time stepping", "TS", PetscObjectComm((PetscObject)tsin), TSDestroy, TSView));
587493b34091SDebojyoti Ghosh 
587593b34091SDebojyoti Ghosh   /* General TS description */
587693b34091SDebojyoti Ghosh   t->numbermonitors    = 0;
5877d0c080abSJoseph Pusztay   t->monitorFrequency  = 1;
587893b34091SDebojyoti Ghosh   t->setupcalled       = 0;
587993b34091SDebojyoti Ghosh   t->ksp_its           = 0;
588093b34091SDebojyoti Ghosh   t->snes_its          = 0;
588193b34091SDebojyoti Ghosh   t->nwork             = 0;
58827d51462cSStefano Zampini   t->rhsjacobian.time  = PETSC_MIN_REAL;
588393b34091SDebojyoti Ghosh   t->rhsjacobian.scale = 1.;
588493b34091SDebojyoti Ghosh   t->ijacobian.shift   = 1.;
588593b34091SDebojyoti Ghosh 
58869566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(tsin, &snes_start));
58879566063dSJacob Faibussowitsch   PetscCall(TSSetSNES(t, snes_start));
5888d15a3a53SEmil Constantinescu 
58899566063dSJacob Faibussowitsch   PetscCall(TSGetDM(tsin, &dm));
58909566063dSJacob Faibussowitsch   PetscCall(TSSetDM(t, dm));
589193b34091SDebojyoti Ghosh 
589293b34091SDebojyoti Ghosh   t->adapt = tsin->adapt;
58939566063dSJacob Faibussowitsch   PetscCall(PetscObjectReference((PetscObject)t->adapt));
589493b34091SDebojyoti Ghosh 
5895e7069c78SShri   t->trajectory = tsin->trajectory;
58969566063dSJacob Faibussowitsch   PetscCall(PetscObjectReference((PetscObject)t->trajectory));
5897e7069c78SShri 
5898e7069c78SShri   t->event = tsin->event;
58996b10a48eSSatish Balay   if (t->event) t->event->refct++;
5900e7069c78SShri 
590193b34091SDebojyoti Ghosh   t->problem_type      = tsin->problem_type;
590293b34091SDebojyoti Ghosh   t->ptime             = tsin->ptime;
5903e7069c78SShri   t->ptime_prev        = tsin->ptime_prev;
590493b34091SDebojyoti Ghosh   t->time_step         = tsin->time_step;
590593b34091SDebojyoti Ghosh   t->max_time          = tsin->max_time;
590693b34091SDebojyoti Ghosh   t->steps             = tsin->steps;
590793b34091SDebojyoti Ghosh   t->max_steps         = tsin->max_steps;
590893b34091SDebojyoti Ghosh   t->equation_type     = tsin->equation_type;
590993b34091SDebojyoti Ghosh   t->atol              = tsin->atol;
591093b34091SDebojyoti Ghosh   t->rtol              = tsin->rtol;
591193b34091SDebojyoti Ghosh   t->max_snes_failures = tsin->max_snes_failures;
591293b34091SDebojyoti Ghosh   t->max_reject        = tsin->max_reject;
591393b34091SDebojyoti Ghosh   t->errorifstepfailed = tsin->errorifstepfailed;
591493b34091SDebojyoti Ghosh 
59159566063dSJacob Faibussowitsch   PetscCall(TSGetType(tsin, &type));
59169566063dSJacob Faibussowitsch   PetscCall(TSSetType(t, type));
591793b34091SDebojyoti Ghosh 
591893b34091SDebojyoti Ghosh   t->vec_sol = NULL;
591993b34091SDebojyoti Ghosh 
592093b34091SDebojyoti Ghosh   t->cfltime          = tsin->cfltime;
592193b34091SDebojyoti Ghosh   t->cfltime_local    = tsin->cfltime_local;
592293b34091SDebojyoti Ghosh   t->exact_final_time = tsin->exact_final_time;
592393b34091SDebojyoti Ghosh 
59249566063dSJacob Faibussowitsch   PetscCall(PetscMemcpy(t->ops, tsin->ops, sizeof(struct _TSOps)));
592593b34091SDebojyoti Ghosh 
59260d4fed19SBarry Smith   if (((PetscObject)tsin)->fortran_func_pointers) {
59270d4fed19SBarry Smith     PetscInt i;
59289566063dSJacob Faibussowitsch     PetscCall(PetscMalloc((10) * sizeof(void (*)(void)), &((PetscObject)t)->fortran_func_pointers));
5929ad540459SPierre Jolivet     for (i = 0; i < 10; i++) ((PetscObject)t)->fortran_func_pointers[i] = ((PetscObject)tsin)->fortran_func_pointers[i];
59300d4fed19SBarry Smith   }
593193b34091SDebojyoti Ghosh   *tsout = t;
59323ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
593393b34091SDebojyoti Ghosh }
5934f3b1f45cSBarry Smith 
5935d71ae5a4SJacob Faibussowitsch static PetscErrorCode RHSWrapperFunction_TSRHSJacobianTest(void *ctx, Vec x, Vec y)
5936d71ae5a4SJacob Faibussowitsch {
5937f3b1f45cSBarry Smith   TS ts = (TS)ctx;
5938f3b1f45cSBarry Smith 
5939f3b1f45cSBarry Smith   PetscFunctionBegin;
59409566063dSJacob Faibussowitsch   PetscCall(TSComputeRHSFunction(ts, 0, x, y));
59413ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
5942f3b1f45cSBarry Smith }
5943f3b1f45cSBarry Smith 
5944f3b1f45cSBarry Smith /*@
5945bcf0153eSBarry Smith     TSRHSJacobianTest - Compares the multiply routine provided to the `MATSHELL` with differencing on the `TS` given RHS function.
5946f3b1f45cSBarry Smith 
5947c3339decSBarry Smith    Logically Collective
5948f3b1f45cSBarry Smith 
59492fe279fdSBarry Smith     Input Parameter:
59502fe279fdSBarry Smith .    TS - the time stepping routine
5951f3b1f45cSBarry Smith 
5952f3b1f45cSBarry Smith    Output Parameter:
5953bcf0153eSBarry Smith .   flg - `PETSC_TRUE` if the multiply is likely correct
5954f3b1f45cSBarry Smith 
5955bcf0153eSBarry Smith    Options Database Key:
5956f3b1f45cSBarry Smith  .   -ts_rhs_jacobian_test_mult -mat_shell_test_mult_view - run the test at each timestep of the integrator
5957f3b1f45cSBarry Smith 
5958f3b1f45cSBarry Smith    Level: advanced
5959f3b1f45cSBarry Smith 
5960bcf0153eSBarry Smith    Note:
5961195e9b02SBarry Smith     This only works for problems defined using `TSSetRHSFunction()` and Jacobian NOT `TSSetIFunction()` and Jacobian
5962f3b1f45cSBarry Smith 
5963bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `Mat`, `MATSHELL`, `MatCreateShell()`, `MatShellGetContext()`, `MatShellGetOperation()`, `MatShellTestMultTranspose()`, `TSRHSJacobianTestTranspose()`
5964f3b1f45cSBarry Smith @*/
5965d71ae5a4SJacob Faibussowitsch PetscErrorCode TSRHSJacobianTest(TS ts, PetscBool *flg)
5966d71ae5a4SJacob Faibussowitsch {
5967f3b1f45cSBarry Smith   Mat           J, B;
5968f3b1f45cSBarry Smith   TSRHSJacobian func;
5969f3b1f45cSBarry Smith   void         *ctx;
5970f3b1f45cSBarry Smith 
5971f3b1f45cSBarry Smith   PetscFunctionBegin;
59729566063dSJacob Faibussowitsch   PetscCall(TSGetRHSJacobian(ts, &J, &B, &func, &ctx));
59739566063dSJacob Faibussowitsch   PetscCall((*func)(ts, 0.0, ts->vec_sol, J, B, ctx));
59749566063dSJacob Faibussowitsch   PetscCall(MatShellTestMult(J, RHSWrapperFunction_TSRHSJacobianTest, ts->vec_sol, ts, flg));
59753ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
5976f3b1f45cSBarry Smith }
5977f3b1f45cSBarry Smith 
5978f3b1f45cSBarry Smith /*@C
5979bcf0153eSBarry Smith     TSRHSJacobianTestTranspose - Compares the multiply transpose routine provided to the `MATSHELL` with differencing on the `TS` given RHS function.
5980f3b1f45cSBarry Smith 
5981c3339decSBarry Smith    Logically Collective
5982f3b1f45cSBarry Smith 
59832fe279fdSBarry Smith     Input Parameter:
59842fe279fdSBarry Smith .    TS - the time stepping routine
5985f3b1f45cSBarry Smith 
5986f3b1f45cSBarry Smith    Output Parameter:
5987bcf0153eSBarry Smith .   flg - `PETSC_TRUE` if the multiply is likely correct
5988f3b1f45cSBarry Smith 
5989bcf0153eSBarry Smith    Options Database Key:
5990f3b1f45cSBarry Smith .   -ts_rhs_jacobian_test_mult_transpose -mat_shell_test_mult_transpose_view - run the test at each timestep of the integrator
5991f3b1f45cSBarry Smith 
5992bcf0153eSBarry Smith    Level: advanced
5993bcf0153eSBarry Smith 
599495452b02SPatrick Sanan    Notes:
5995195e9b02SBarry Smith     This only works for problems defined using `TSSetRHSFunction()` and Jacobian NOT `TSSetIFunction()` and Jacobian
5996f3b1f45cSBarry Smith 
5997bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `Mat`, `MatCreateShell()`, `MatShellGetContext()`, `MatShellGetOperation()`, `MatShellTestMultTranspose()`, `TSRHSJacobianTest()`
5998f3b1f45cSBarry Smith @*/
5999d71ae5a4SJacob Faibussowitsch PetscErrorCode TSRHSJacobianTestTranspose(TS ts, PetscBool *flg)
6000d71ae5a4SJacob Faibussowitsch {
6001f3b1f45cSBarry Smith   Mat           J, B;
6002f3b1f45cSBarry Smith   void         *ctx;
6003f3b1f45cSBarry Smith   TSRHSJacobian func;
6004f3b1f45cSBarry Smith 
6005f3b1f45cSBarry Smith   PetscFunctionBegin;
60069566063dSJacob Faibussowitsch   PetscCall(TSGetRHSJacobian(ts, &J, &B, &func, &ctx));
60079566063dSJacob Faibussowitsch   PetscCall((*func)(ts, 0.0, ts->vec_sol, J, B, ctx));
60089566063dSJacob Faibussowitsch   PetscCall(MatShellTestMultTranspose(J, RHSWrapperFunction_TSRHSJacobianTest, ts->vec_sol, ts, flg));
60093ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
6010f3b1f45cSBarry Smith }
60110fe4d17eSHong Zhang 
60120fe4d17eSHong Zhang /*@
60130fe4d17eSHong Zhang   TSSetUseSplitRHSFunction - Use the split RHSFunction when a multirate method is used.
60140fe4d17eSHong Zhang 
601520f4b53cSBarry Smith   Logically Collective
60160fe4d17eSHong Zhang 
6017d8d19677SJose E. Roman   Input Parameters:
60180fe4d17eSHong Zhang +  ts - timestepping context
6019bcf0153eSBarry Smith -  use_splitrhsfunction - `PETSC_TRUE` indicates that the split RHSFunction will be used
60200fe4d17eSHong Zhang 
6021bcf0153eSBarry Smith   Options Database Key:
60220fe4d17eSHong Zhang .   -ts_use_splitrhsfunction - <true,false>
60230fe4d17eSHong Zhang 
60240fe4d17eSHong Zhang   Level: intermediate
60250fe4d17eSHong Zhang 
6026bcf0153eSBarry Smith   Note:
6027195e9b02SBarry Smith   This is only for multirate methods
6028bcf0153eSBarry Smith 
6029bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSGetUseSplitRHSFunction()`
60300fe4d17eSHong Zhang @*/
6031d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetUseSplitRHSFunction(TS ts, PetscBool use_splitrhsfunction)
6032d71ae5a4SJacob Faibussowitsch {
60330fe4d17eSHong Zhang   PetscFunctionBegin;
60340fe4d17eSHong Zhang   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
60350fe4d17eSHong Zhang   ts->use_splitrhsfunction = use_splitrhsfunction;
60363ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
60370fe4d17eSHong Zhang }
60380fe4d17eSHong Zhang 
60390fe4d17eSHong Zhang /*@
60400fe4d17eSHong Zhang   TSGetUseSplitRHSFunction - Gets whether to use the split RHSFunction when a multirate method is used.
60410fe4d17eSHong Zhang 
604220f4b53cSBarry Smith   Not Collective
60430fe4d17eSHong Zhang 
60440fe4d17eSHong Zhang   Input Parameter:
60450fe4d17eSHong Zhang .  ts - timestepping context
60460fe4d17eSHong Zhang 
60470fe4d17eSHong Zhang   Output Parameter:
6048bcf0153eSBarry Smith .  use_splitrhsfunction - `PETSC_TRUE` indicates that the split RHSFunction will be used
60490fe4d17eSHong Zhang 
60500fe4d17eSHong Zhang   Level: intermediate
60510fe4d17eSHong Zhang 
6052bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSSetUseSplitRHSFunction()`
60530fe4d17eSHong Zhang @*/
6054d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetUseSplitRHSFunction(TS ts, PetscBool *use_splitrhsfunction)
6055d71ae5a4SJacob Faibussowitsch {
60560fe4d17eSHong Zhang   PetscFunctionBegin;
60570fe4d17eSHong Zhang   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
60580fe4d17eSHong Zhang   *use_splitrhsfunction = ts->use_splitrhsfunction;
60593ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
60600fe4d17eSHong Zhang }
6061d60b7d5cSBarry Smith 
6062d60b7d5cSBarry Smith /*@
6063d60b7d5cSBarry Smith     TSSetMatStructure - sets the relationship between the nonzero structure of the RHS Jacobian matrix to the IJacobian matrix.
6064d60b7d5cSBarry Smith 
6065c3339decSBarry Smith    Logically  Collective
6066d60b7d5cSBarry Smith 
6067d60b7d5cSBarry Smith    Input Parameters:
6068d60b7d5cSBarry Smith +  ts - the time-stepper
6069bcf0153eSBarry Smith -  str - the structure (the default is `UNKNOWN_NONZERO_PATTERN`)
6070d60b7d5cSBarry Smith 
6071d60b7d5cSBarry Smith    Level: intermediate
6072d60b7d5cSBarry Smith 
6073bcf0153eSBarry Smith    Note:
6074d60b7d5cSBarry Smith      When the relationship between the nonzero structures is known and supplied the solution process can be much faster
6075d60b7d5cSBarry Smith 
6076bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `MatAXPY()`, `MatStructure`
6077d60b7d5cSBarry Smith  @*/
6078d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetMatStructure(TS ts, MatStructure str)
6079d71ae5a4SJacob Faibussowitsch {
6080d60b7d5cSBarry Smith   PetscFunctionBegin;
6081d60b7d5cSBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
6082d60b7d5cSBarry Smith   ts->axpy_pattern = str;
60833ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
6084d60b7d5cSBarry Smith }
60854a658b32SHong Zhang 
60864a658b32SHong Zhang /*@
6087bcf0153eSBarry Smith   TSSetTimeSpan - sets the time span. The solution will be computed and stored for each time requested in the span
60884a658b32SHong Zhang 
6089c3339decSBarry Smith   Collective
60904a658b32SHong Zhang 
60914a658b32SHong Zhang   Input Parameters:
60924a658b32SHong Zhang + ts - the time-stepper
60934a658b32SHong Zhang . n - number of the time points (>=2)
60944a658b32SHong Zhang - span_times - array of the time points. The first element and the last element are the initial time and the final time respectively.
60954a658b32SHong Zhang 
6096bcf0153eSBarry Smith   Options Database Key:
60974a658b32SHong Zhang . -ts_time_span <t0,...tf> - Sets the time span
60984a658b32SHong Zhang 
6099bcf0153eSBarry Smith   Level: intermediate
61004a658b32SHong Zhang 
61014a658b32SHong Zhang   Notes:
61024a658b32SHong Zhang   The elements in tspan must be all increasing. They correspond to the intermediate points for time integration.
6103bcf0153eSBarry Smith   `TS_EXACTFINALTIME_MATCHSTEP` must be used to make the last time step in each sub-interval match the intermediate points specified.
6104bcf0153eSBarry Smith   The intermediate solutions are saved in a vector array that can be accessed with `TSGetTimeSpanSolutions()`. Thus using time span may
61054a658b32SHong Zhang   pressure the memory system when using a large number of span points.
61064a658b32SHong Zhang 
6107bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSGetTimeSpan()`, `TSGetTimeSpanSolutions()`
61084a658b32SHong Zhang  @*/
6109d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetTimeSpan(TS ts, PetscInt n, PetscReal *span_times)
6110d71ae5a4SJacob Faibussowitsch {
61114a658b32SHong Zhang   PetscFunctionBegin;
61124a658b32SHong Zhang   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
611363a3b9bcSJacob Faibussowitsch   PetscCheck(n >= 2, PetscObjectComm((PetscObject)ts), PETSC_ERR_ARG_WRONG, "Minimum time span size is 2 but %" PetscInt_FMT " is provided", n);
61144a658b32SHong Zhang   if (ts->tspan && n != ts->tspan->num_span_times) {
61154a658b32SHong Zhang     PetscCall(PetscFree(ts->tspan->span_times));
61164a658b32SHong Zhang     PetscCall(VecDestroyVecs(ts->tspan->num_span_times, &ts->tspan->vecs_sol));
61174a658b32SHong Zhang     PetscCall(PetscMalloc1(n, &ts->tspan->span_times));
61184a658b32SHong Zhang   }
61194a658b32SHong Zhang   if (!ts->tspan) {
61204a658b32SHong Zhang     TSTimeSpan tspan;
61214a658b32SHong Zhang     PetscCall(PetscNew(&tspan));
61224a658b32SHong Zhang     PetscCall(PetscMalloc1(n, &tspan->span_times));
6123e1db57b0SHong Zhang     tspan->reltol = 1e-6;
6124e1db57b0SHong Zhang     tspan->abstol = 10 * PETSC_MACHINE_EPSILON;
61254a658b32SHong Zhang     ts->tspan     = tspan;
61264a658b32SHong Zhang   }
61274a658b32SHong Zhang   ts->tspan->num_span_times = n;
61284a658b32SHong Zhang   PetscCall(PetscArraycpy(ts->tspan->span_times, span_times, n));
61294a658b32SHong Zhang   PetscCall(TSSetTime(ts, ts->tspan->span_times[0]));
61304a658b32SHong Zhang   PetscCall(TSSetMaxTime(ts, ts->tspan->span_times[n - 1]));
61313ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
61324a658b32SHong Zhang }
61334a658b32SHong Zhang 
61344a658b32SHong Zhang /*@C
6135195e9b02SBarry Smith   TSGetTimeSpan - gets the time span set with `TSSetTimeSpan()`
61364a658b32SHong Zhang 
61374a658b32SHong Zhang   Not Collective
61384a658b32SHong Zhang 
61394a658b32SHong Zhang   Input Parameter:
61404a658b32SHong Zhang . ts - the time-stepper
61414a658b32SHong Zhang 
61424a658b32SHong Zhang   Output Parameters:
61434a658b32SHong Zhang + n - number of the time points (>=2)
6144bcf0153eSBarry Smith - span_times - array of the time points. The first element and the last element are the initial time and the final time respectively.
61454a658b32SHong Zhang 
61464a658b32SHong Zhang   Level: beginner
61474a658b32SHong Zhang 
6148bcf0153eSBarry Smith   Note:
6149195e9b02SBarry Smith   The values obtained are valid until the `TS` object is destroyed.
6150195e9b02SBarry Smith 
6151195e9b02SBarry Smith   Both `n` and `span_times` can be `NULL`.
6152bcf0153eSBarry Smith 
6153bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSSetTimeSpan()`, `TSGetTimeSpanSolutions()`
61544a658b32SHong Zhang  @*/
6155d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetTimeSpan(TS ts, PetscInt *n, const PetscReal **span_times)
6156d71ae5a4SJacob Faibussowitsch {
61574a658b32SHong Zhang   PetscFunctionBegin;
61584a658b32SHong Zhang   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
61594a658b32SHong Zhang   if (n) PetscValidIntPointer(n, 2);
61604a658b32SHong Zhang   if (span_times) PetscValidPointer(span_times, 3);
61614a658b32SHong Zhang   if (!ts->tspan) {
61624a658b32SHong Zhang     if (n) *n = 0;
61634a658b32SHong Zhang     if (span_times) *span_times = NULL;
61644a658b32SHong Zhang   } else {
61654a658b32SHong Zhang     if (n) *n = ts->tspan->num_span_times;
61664a658b32SHong Zhang     if (span_times) *span_times = ts->tspan->span_times;
61674a658b32SHong Zhang   }
61683ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
61694a658b32SHong Zhang }
61704a658b32SHong Zhang 
61714a658b32SHong Zhang /*@
61724a658b32SHong Zhang    TSGetTimeSpanSolutions - Get the number of solutions and the solutions at the time points specified by the time span.
61734a658b32SHong Zhang 
61744a658b32SHong Zhang    Input Parameter:
6175bcf0153eSBarry Smith .  ts - the `TS` context obtained from `TSCreate()`
61764a658b32SHong Zhang 
61774a658b32SHong Zhang    Output Parameters:
61784a658b32SHong Zhang +  nsol - the number of solutions
61794a658b32SHong Zhang -  Sols - the solution vectors
61804a658b32SHong Zhang 
6181bcf0153eSBarry Smith    Level: intermediate
61824a658b32SHong Zhang 
618340bd4cedSHong Zhang    Notes:
6184195e9b02SBarry Smith     Both `nsol` and `Sols` can be `NULL`.
61854a658b32SHong Zhang 
6186195e9b02SBarry 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()`.
6187bcf0153eSBarry Smith     For example, manipulating the step size, especially with a reduced precision, may cause `TS` to step over certain points in the span.
6188bcf0153eSBarry Smith 
6189bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSSetTimeSpan()`
61904a658b32SHong Zhang @*/
6191d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetTimeSpanSolutions(TS ts, PetscInt *nsol, Vec **Sols)
6192d71ae5a4SJacob Faibussowitsch {
61934a658b32SHong Zhang   PetscFunctionBegin;
61944a658b32SHong Zhang   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
61954a658b32SHong Zhang   if (nsol) PetscValidIntPointer(nsol, 2);
61964a658b32SHong Zhang   if (Sols) PetscValidPointer(Sols, 3);
61974a658b32SHong Zhang   if (!ts->tspan) {
61984a658b32SHong Zhang     if (nsol) *nsol = 0;
61994a658b32SHong Zhang     if (Sols) *Sols = NULL;
62004a658b32SHong Zhang   } else {
620140bd4cedSHong Zhang     if (nsol) *nsol = ts->tspan->spanctr;
62024a658b32SHong Zhang     if (Sols) *Sols = ts->tspan->vecs_sol;
62034a658b32SHong Zhang   }
62043ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
62054a658b32SHong Zhang }
6206d7cfae9bSHong Zhang 
6207d7cfae9bSHong Zhang /*@C
62087b2dc123SHong Zhang   TSPruneIJacobianColor - Remove nondiagonal zeros in the Jacobian matrix and update the `MatMFFD` coloring information.
6209d7cfae9bSHong Zhang 
6210195e9b02SBarry Smith   Collective
6211d7cfae9bSHong Zhang 
6212d7cfae9bSHong Zhang   Input Parameters:
6213195e9b02SBarry Smith + ts - the `TS` context
6214d7cfae9bSHong Zhang . J - Jacobian matrix (not altered in this routine)
6215195e9b02SBarry Smith - B - newly computed Jacobian matrix to use with preconditioner
6216d7cfae9bSHong Zhang 
6217d7cfae9bSHong Zhang   Level: intermediate
6218d7cfae9bSHong Zhang 
6219d7cfae9bSHong Zhang   Notes:
6220195e9b02SBarry Smith   This function improves the `MatFDColoring` performance when the Jacobian matrix was over-allocated or contains
6221195e9b02SBarry Smith   many constant zeros entries, which is typically the case when the matrix is generated by a `DM`
6222d7cfae9bSHong Zhang   and multiple fields are involved.
6223d7cfae9bSHong Zhang 
6224d7cfae9bSHong Zhang   Users need to make sure that the Jacobian matrix is properly filled to reflect the sparsity
6225195e9b02SBarry Smith   structure. For `MatFDColoring`, the values of nonzero entries are not important. So one can
62267b2dc123SHong Zhang   usually call `TSComputeIJacobian()` with randomized input vectors to generate a dummy Jacobian.
62277b2dc123SHong Zhang   `TSComputeIJacobian()` should be called before `TSSolve()` but after `TSSetUp()`.
6228d7cfae9bSHong Zhang 
6229195e9b02SBarry Smith .seealso: [](chapter_ts), `TS`, `MatFDColoring`, `TSComputeIJacobianDefaultColor()`, `MatEliminateZeros()`, `MatFDColoringCreate()`, `MatFDColoringSetFunction()`
6230d7cfae9bSHong Zhang @*/
6231d7cfae9bSHong Zhang PetscErrorCode TSPruneIJacobianColor(TS ts, Mat J, Mat B)
6232d7cfae9bSHong Zhang {
6233d7cfae9bSHong Zhang   MatColoring   mc            = NULL;
6234d7cfae9bSHong Zhang   ISColoring    iscoloring    = NULL;
6235d7cfae9bSHong Zhang   MatFDColoring matfdcoloring = NULL;
6236d7cfae9bSHong Zhang 
6237d7cfae9bSHong Zhang   PetscFunctionBegin;
6238d7cfae9bSHong Zhang   /* Generate new coloring after eliminating zeros in the matrix */
6239d7cfae9bSHong Zhang   PetscCall(MatEliminateZeros(B));
6240d7cfae9bSHong Zhang   PetscCall(MatColoringCreate(B, &mc));
6241d7cfae9bSHong Zhang   PetscCall(MatColoringSetDistance(mc, 2));
6242d7cfae9bSHong Zhang   PetscCall(MatColoringSetType(mc, MATCOLORINGSL));
6243d7cfae9bSHong Zhang   PetscCall(MatColoringSetFromOptions(mc));
6244d7cfae9bSHong Zhang   PetscCall(MatColoringApply(mc, &iscoloring));
6245d7cfae9bSHong Zhang   PetscCall(MatColoringDestroy(&mc));
6246d7cfae9bSHong Zhang   /* Replace the old coloring with the new one */
6247d7cfae9bSHong Zhang   PetscCall(MatFDColoringCreate(B, iscoloring, &matfdcoloring));
6248d7cfae9bSHong Zhang   PetscCall(MatFDColoringSetFunction(matfdcoloring, (PetscErrorCode(*)(void))SNESTSFormFunction, (void *)ts));
6249d7cfae9bSHong Zhang   PetscCall(MatFDColoringSetFromOptions(matfdcoloring));
6250d7cfae9bSHong Zhang   PetscCall(MatFDColoringSetUp(B, iscoloring, matfdcoloring));
6251d7cfae9bSHong Zhang   PetscCall(PetscObjectCompose((PetscObject)B, "TSMatFDColoring", (PetscObject)matfdcoloring));
6252d7cfae9bSHong Zhang   PetscCall(PetscObjectDereference((PetscObject)matfdcoloring));
6253d7cfae9bSHong Zhang   PetscCall(ISColoringDestroy(&iscoloring));
62543ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
6255d7cfae9bSHong Zhang }
6256