xref: /petsc/src/ts/interface/ts.c (revision a144a63f3d0bdf0a33e2b5ca97275684576fc3ca)
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 
10d5ba7fb7SMatthew Knepley /* Logging support */
11d74926cbSBarry Smith PetscClassId  TS_CLASSID, DMTS_CLASSID;
12a05bf03eSHong Zhang PetscLogEvent TS_Step, TS_PseudoComputeTimeStep, TS_FunctionEval, TS_JacobianEval;
13d405a339SMatthew Knepley 
14c793f718SLisandro Dalcin const char *const TSExactFinalTimeOptions[] = {"UNSPECIFIED", "STEPOVER", "INTERPOLATE", "MATCHSTEP", "TSExactFinalTimeOption", "TS_EXACTFINALTIME_", NULL};
1549354f04SShri Abhyankar 
16d71ae5a4SJacob Faibussowitsch static PetscErrorCode TSAdaptSetDefaultType(TSAdapt adapt, TSAdaptType default_type)
17d71ae5a4SJacob Faibussowitsch {
182ffb9264SLisandro Dalcin   PetscFunctionBegin;
19b92453a8SLisandro Dalcin   PetscValidHeaderSpecific(adapt, TSADAPT_CLASSID, 1);
204f572ea9SToby Isaac   PetscAssertPointer(default_type, 2);
211e66621cSBarry Smith   if (!((PetscObject)adapt)->type_name) PetscCall(TSAdaptSetType(adapt, default_type));
223ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
232ffb9264SLisandro Dalcin }
242ffb9264SLisandro Dalcin 
25bdad233fSMatthew Knepley /*@
26195e9b02SBarry Smith   TSSetFromOptions - Sets various `TS` parameters from the options database
27bdad233fSMatthew Knepley 
28c3339decSBarry Smith   Collective
29bdad233fSMatthew Knepley 
30bdad233fSMatthew Knepley   Input Parameter:
31bcf0153eSBarry Smith . ts - the `TS` context obtained from `TSCreate()`
32bdad233fSMatthew Knepley 
33bdad233fSMatthew Knepley   Options Database Keys:
34195e9b02SBarry Smith + -ts_type <type>                                                    - EULER, BEULER, SUNDIALS, PSEUDO, CN, RK, THETA, ALPHA, GLLE,  SSP, GLEE, BSYMP, IRK, see `TSType`
35ef222394SBarry Smith . -ts_save_trajectory                                                - checkpoint the solution at each time-step
36ef85077eSLisandro Dalcin . -ts_max_time <time>                                                - maximum time to compute to
374a658b32SHong Zhang . -ts_time_span <t0,...tf>                                           - sets the time span, solutions are computed and stored for each indicated time
38ef85077eSLisandro Dalcin . -ts_max_steps <steps>                                              - maximum number of time-steps to take
39ef85077eSLisandro Dalcin . -ts_init_time <time>                                               - initial time to start computation
40195e9b02SBarry Smith . -ts_final_time <time>                                              - final time to compute to (deprecated: use `-ts_max_time`)
413e4cdcaaSBarry Smith . -ts_dt <dt>                                                        - initial time step
421628793fSSatish 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
43a3cdaa26SBarry Smith . -ts_max_snes_failures <maxfailures>                                - Maximum number of nonlinear solve failures allowed
44a3cdaa26SBarry Smith . -ts_max_reject <maxrejects>                                        - Maximum number of step rejections before step fails
45a3cdaa26SBarry Smith . -ts_error_if_step_fails <true,false>                               - Error if no step succeeds
46a3cdaa26SBarry Smith . -ts_rtol <rtol>                                                    - relative tolerance for local truncation error
4767b8a455SSatish Balay . -ts_atol <atol>                                                    - Absolute tolerance for local truncation error
48f3b1f45cSBarry Smith . -ts_rhs_jacobian_test_mult -mat_shell_test_mult_view               - test the Jacobian at each iteration against finite difference with RHS function
49b43aa488SJacob Faibussowitsch . -ts_rhs_jacobian_test_mult_transpose                               - test the Jacobian at each iteration against finite difference with RHS function
50195e9b02SBarry Smith . -ts_adjoint_solve <yes,no>                                         - After solving the ODE/DAE solve the adjoint problem (requires `-ts_save_trajectory`)
51847ff0e1SMatthew G. Knepley . -ts_fd_color                                                       - Use finite differences with coloring to compute IJacobian
52bdad233fSMatthew Knepley . -ts_monitor                                                        - print information at each timestep
53aee7a9fbSMatthew G. Knepley . -ts_monitor_cancel                                                 - Cancel all monitors
54de06c3feSJed Brown . -ts_monitor_lg_solution                                            - Monitor solution graphically
55de06c3feSJed Brown . -ts_monitor_lg_error                                               - Monitor error graphically
567cf37e64SBarry Smith . -ts_monitor_error                                                  - Monitors norm of error
576934998bSLisandro Dalcin . -ts_monitor_lg_timestep                                            - Monitor timestep size graphically
588b668821SLisandro Dalcin . -ts_monitor_lg_timestep_log                                        - Monitor log timestep size graphically
59de06c3feSJed Brown . -ts_monitor_lg_snes_iterations                                     - Monitor number nonlinear iterations for each timestep graphically
60de06c3feSJed Brown . -ts_monitor_lg_ksp_iterations                                      - Monitor number nonlinear iterations for each timestep graphically
61de06c3feSJed Brown . -ts_monitor_sp_eig                                                 - Monitor eigenvalues of linearized operator graphically
62de06c3feSJed Brown . -ts_monitor_draw_solution                                          - Monitor solution graphically
633e4cdcaaSBarry Smith . -ts_monitor_draw_solution_phase  <xleft,yleft,xright,yright>       - Monitor solution graphically with phase diagram, requires problem with exactly 2 degrees of freedom
643e4cdcaaSBarry Smith . -ts_monitor_draw_error                                             - Monitor error graphically, requires use to have provided TSSetSolutionFunction()
65fde5950dSBarry Smith . -ts_monitor_solution [ascii binary draw][:filename][:viewerformat] - monitors the solution at each timestep
66b43aa488SJacob Faibussowitsch . -ts_monitor_solution_interval <interval>                           - output once every interval (default=1) time steps
6763a3b9bcSJacob 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)
689e336e28SPatrick Sanan - -ts_monitor_envelope                                               - determine maximum and minimum value of each component of the solution over the solution time
6953ea634cSHong Zhang 
70bcf0153eSBarry Smith   Level: beginner
713d5a8a6aSBarry Smith 
72bcf0153eSBarry Smith   Notes:
73bcf0153eSBarry Smith   See `SNESSetFromOptions()` and `KSPSetFromOptions()` for how to control the nonlinear and linear solves used by the time-stepper.
74bcf0153eSBarry Smith 
75195e9b02SBarry Smith   Certain `SNES` options get reset for each new nonlinear solver, for example `-snes_lag_jacobian its` and `-snes_lag_preconditioner its`, in order
76195e9b02SBarry Smith   to retain them over the multiple nonlinear solves that `TS` uses you mush also provide `-snes_lag_jacobian_persists true` and
77195e9b02SBarry Smith   `-snes_lag_preconditioner_persists true`
783d5a8a6aSBarry Smith 
79b43aa488SJacob Faibussowitsch   Developer Notes:
809e336e28SPatrick Sanan   We should unify all the -ts_monitor options in the way that -xxx_view has been unified
81bdad233fSMatthew Knepley 
821cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSGetType()`
83bdad233fSMatthew Knepley @*/
84d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetFromOptions(TS ts)
85d71ae5a4SJacob Faibussowitsch {
86bc952696SBarry Smith   PetscBool              opt, flg, tflg;
87eabae89aSBarry Smith   char                   monfilename[PETSC_MAX_PATH_LEN];
884a658b32SHong Zhang   PetscReal              time_step, tspan[100];
894a658b32SHong Zhang   PetscInt               nt = PETSC_STATIC_ARRAY_LENGTH(tspan);
9049354f04SShri Abhyankar   TSExactFinalTimeOption eftopt;
91d1212d36SBarry Smith   char                   dir[16];
92cd11d68dSLisandro Dalcin   TSIFunction            ifun;
936991f827SBarry Smith   const char            *defaultType;
946991f827SBarry Smith   char                   typeName[256];
95bdad233fSMatthew Knepley 
96bdad233fSMatthew Knepley   PetscFunctionBegin;
970700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
986991f827SBarry Smith 
999566063dSJacob Faibussowitsch   PetscCall(TSRegisterAll());
1009566063dSJacob Faibussowitsch   PetscCall(TSGetIFunction(ts, NULL, &ifun, NULL));
101cd11d68dSLisandro Dalcin 
102d0609cedSBarry Smith   PetscObjectOptionsBegin((PetscObject)ts);
1031ef27442SStefano Zampini   if (((PetscObject)ts)->type_name) defaultType = ((PetscObject)ts)->type_name;
1041ef27442SStefano Zampini   else defaultType = ifun ? TSBEULER : TSEULER;
1059566063dSJacob Faibussowitsch   PetscCall(PetscOptionsFList("-ts_type", "TS method", "TSSetType", TSList, defaultType, typeName, 256, &opt));
1061e66621cSBarry Smith   if (opt) PetscCall(TSSetType(ts, typeName));
1071e66621cSBarry Smith   else PetscCall(TSSetType(ts, defaultType));
108bdad233fSMatthew Knepley 
109bdad233fSMatthew Knepley   /* Handle generic TS options */
1109566063dSJacob Faibussowitsch   PetscCall(PetscOptionsDeprecated("-ts_final_time", "-ts_max_time", "3.10", NULL));
1119566063dSJacob Faibussowitsch   PetscCall(PetscOptionsReal("-ts_max_time", "Maximum time to run to", "TSSetMaxTime", ts->max_time, &ts->max_time, NULL));
1124a658b32SHong Zhang   PetscCall(PetscOptionsRealArray("-ts_time_span", "Time span", "TSSetTimeSpan", tspan, &nt, &flg));
1134a658b32SHong Zhang   if (flg) PetscCall(TSSetTimeSpan(ts, nt, tspan));
1149566063dSJacob Faibussowitsch   PetscCall(PetscOptionsInt("-ts_max_steps", "Maximum number of time steps", "TSSetMaxSteps", ts->max_steps, &ts->max_steps, NULL));
1159566063dSJacob Faibussowitsch   PetscCall(PetscOptionsReal("-ts_init_time", "Initial time", "TSSetTime", ts->ptime, &ts->ptime, NULL));
1169566063dSJacob Faibussowitsch   PetscCall(PetscOptionsReal("-ts_dt", "Initial time step", "TSSetTimeStep", ts->time_step, &time_step, &flg));
1179566063dSJacob Faibussowitsch   if (flg) PetscCall(TSSetTimeStep(ts, time_step));
1189566063dSJacob Faibussowitsch   PetscCall(PetscOptionsEnum("-ts_exact_final_time", "Option for handling of final time step", "TSSetExactFinalTime", TSExactFinalTimeOptions, (PetscEnum)ts->exact_final_time, (PetscEnum *)&eftopt, &flg));
1199566063dSJacob Faibussowitsch   if (flg) PetscCall(TSSetExactFinalTime(ts, eftopt));
1209566063dSJacob Faibussowitsch   PetscCall(PetscOptionsInt("-ts_max_snes_failures", "Maximum number of nonlinear solve failures", "TSSetMaxSNESFailures", ts->max_snes_failures, &ts->max_snes_failures, NULL));
1219566063dSJacob Faibussowitsch   PetscCall(PetscOptionsInt("-ts_max_reject", "Maximum number of step rejections before step fails", "TSSetMaxStepRejections", ts->max_reject, &ts->max_reject, NULL));
1229566063dSJacob Faibussowitsch   PetscCall(PetscOptionsBool("-ts_error_if_step_fails", "Error if no step succeeds", "TSSetErrorIfStepFails", ts->errorifstepfailed, &ts->errorifstepfailed, NULL));
1239566063dSJacob Faibussowitsch   PetscCall(PetscOptionsReal("-ts_rtol", "Relative tolerance for local truncation error", "TSSetTolerances", ts->rtol, &ts->rtol, NULL));
1249566063dSJacob Faibussowitsch   PetscCall(PetscOptionsReal("-ts_atol", "Absolute tolerance for local truncation error", "TSSetTolerances", ts->atol, &ts->atol, NULL));
125bdad233fSMatthew Knepley 
1269566063dSJacob 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));
1279566063dSJacob 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));
1289566063dSJacob Faibussowitsch   PetscCall(PetscOptionsBool("-ts_use_splitrhsfunction", "Use the split RHS function for multirate solvers ", "TSSetUseSplitRHSFunction", ts->use_splitrhsfunction, &ts->use_splitrhsfunction, NULL));
12956f85f32SBarry Smith #if defined(PETSC_HAVE_SAWS)
13056f85f32SBarry Smith   {
13156f85f32SBarry Smith     PetscBool set;
13256f85f32SBarry Smith     flg = PETSC_FALSE;
1339566063dSJacob Faibussowitsch     PetscCall(PetscOptionsBool("-ts_saws_block", "Block for SAWs memory snooper at end of TSSolve", "PetscObjectSAWsBlock", ((PetscObject)ts)->amspublishblock, &flg, &set));
1341baa6e33SBarry Smith     if (set) PetscCall(PetscObjectSAWsSetBlock((PetscObject)ts, flg));
13556f85f32SBarry Smith   }
13656f85f32SBarry Smith #endif
13756f85f32SBarry Smith 
138bdad233fSMatthew Knepley   /* Monitor options */
1399566063dSJacob Faibussowitsch   PetscCall(PetscOptionsInt("-ts_monitor_frequency", "Number of time steps between monitor output", "TSMonitorSetFrequency", ts->monitorFrequency, &ts->monitorFrequency, NULL));
1409566063dSJacob Faibussowitsch   PetscCall(TSMonitorSetFromOptions(ts, "-ts_monitor", "Monitor time and timestep size", "TSMonitorDefault", TSMonitorDefault, NULL));
1419566063dSJacob Faibussowitsch   PetscCall(TSMonitorSetFromOptions(ts, "-ts_monitor_extreme", "Monitor extreme values of the solution", "TSMonitorExtreme", TSMonitorExtreme, NULL));
1429566063dSJacob Faibussowitsch   PetscCall(TSMonitorSetFromOptions(ts, "-ts_monitor_solution", "View the solution at each timestep", "TSMonitorSolution", TSMonitorSolution, NULL));
1439566063dSJacob Faibussowitsch   PetscCall(TSMonitorSetFromOptions(ts, "-ts_dmswarm_monitor_moments", "Monitor moments of particle distribution", "TSDMSwarmMonitorMoments", TSDMSwarmMonitorMoments, NULL));
144fde5950dSBarry Smith 
1459566063dSJacob Faibussowitsch   PetscCall(PetscOptionsString("-ts_monitor_python", "Use Python function", "TSMonitorSet", NULL, monfilename, sizeof(monfilename), &flg));
1469566063dSJacob Faibussowitsch   if (flg) PetscCall(PetscPythonMonitorSet((PetscObject)ts, monfilename));
1475180491cSLisandro Dalcin 
1489566063dSJacob Faibussowitsch   PetscCall(PetscOptionsName("-ts_monitor_lg_solution", "Monitor solution graphically", "TSMonitorLGSolution", &opt));
149b3603a34SBarry Smith   if (opt) {
1503923b477SBarry Smith     PetscInt  howoften = 1;
151e669de00SBarry Smith     DM        dm;
152e669de00SBarry Smith     PetscBool net;
153b3603a34SBarry Smith 
1549566063dSJacob Faibussowitsch     PetscCall(PetscOptionsInt("-ts_monitor_lg_solution", "Monitor solution graphically", "TSMonitorLGSolution", howoften, &howoften, NULL));
1559566063dSJacob Faibussowitsch     PetscCall(TSGetDM(ts, &dm));
1569566063dSJacob Faibussowitsch     PetscCall(PetscObjectTypeCompare((PetscObject)dm, DMNETWORK, &net));
157e669de00SBarry Smith     if (net) {
158e669de00SBarry Smith       TSMonitorLGCtxNetwork ctx;
1599566063dSJacob Faibussowitsch       PetscCall(TSMonitorLGCtxNetworkCreate(ts, NULL, NULL, PETSC_DECIDE, PETSC_DECIDE, 600, 400, howoften, &ctx));
1609566063dSJacob Faibussowitsch       PetscCall(TSMonitorSet(ts, TSMonitorLGCtxNetworkSolution, ctx, (PetscErrorCode(*)(void **))TSMonitorLGCtxNetworkDestroy));
1619566063dSJacob Faibussowitsch       PetscCall(PetscOptionsBool("-ts_monitor_lg_solution_semilogy", "Plot the solution with a semi-log axis", "", ctx->semilogy, &ctx->semilogy, NULL));
162e669de00SBarry Smith     } else {
163e669de00SBarry Smith       TSMonitorLGCtx ctx;
1649566063dSJacob Faibussowitsch       PetscCall(TSMonitorLGCtxCreate(PETSC_COMM_SELF, NULL, NULL, PETSC_DECIDE, PETSC_DECIDE, 400, 300, howoften, &ctx));
1659566063dSJacob Faibussowitsch       PetscCall(TSMonitorSet(ts, TSMonitorLGSolution, ctx, (PetscErrorCode(*)(void **))TSMonitorLGCtxDestroy));
166bdad233fSMatthew Knepley     }
167e669de00SBarry Smith   }
1686ba87a44SLisandro Dalcin 
1699566063dSJacob Faibussowitsch   PetscCall(PetscOptionsName("-ts_monitor_lg_error", "Monitor error graphically", "TSMonitorLGError", &opt));
170ef20d060SBarry Smith   if (opt) {
1710b039ecaSBarry Smith     TSMonitorLGCtx ctx;
1723923b477SBarry Smith     PetscInt       howoften = 1;
173ef20d060SBarry Smith 
1749566063dSJacob Faibussowitsch     PetscCall(PetscOptionsInt("-ts_monitor_lg_error", "Monitor error graphically", "TSMonitorLGError", howoften, &howoften, NULL));
1759566063dSJacob Faibussowitsch     PetscCall(TSMonitorLGCtxCreate(PETSC_COMM_SELF, NULL, NULL, PETSC_DECIDE, PETSC_DECIDE, 400, 300, howoften, &ctx));
1769566063dSJacob Faibussowitsch     PetscCall(TSMonitorSet(ts, TSMonitorLGError, ctx, (PetscErrorCode(*)(void **))TSMonitorLGCtxDestroy));
177ef20d060SBarry Smith   }
1789566063dSJacob Faibussowitsch   PetscCall(TSMonitorSetFromOptions(ts, "-ts_monitor_error", "View the error at each timestep", "TSMonitorError", TSMonitorError, NULL));
1797cf37e64SBarry Smith 
1809566063dSJacob Faibussowitsch   PetscCall(PetscOptionsName("-ts_monitor_lg_timestep", "Monitor timestep size graphically", "TSMonitorLGTimeStep", &opt));
1816934998bSLisandro Dalcin   if (opt) {
1826934998bSLisandro Dalcin     TSMonitorLGCtx ctx;
1836934998bSLisandro Dalcin     PetscInt       howoften = 1;
1846934998bSLisandro Dalcin 
1859566063dSJacob Faibussowitsch     PetscCall(PetscOptionsInt("-ts_monitor_lg_timestep", "Monitor timestep size graphically", "TSMonitorLGTimeStep", howoften, &howoften, NULL));
1869566063dSJacob Faibussowitsch     PetscCall(TSMonitorLGCtxCreate(PetscObjectComm((PetscObject)ts), NULL, NULL, PETSC_DECIDE, PETSC_DECIDE, 400, 300, howoften, &ctx));
1879566063dSJacob Faibussowitsch     PetscCall(TSMonitorSet(ts, TSMonitorLGTimeStep, ctx, (PetscErrorCode(*)(void **))TSMonitorLGCtxDestroy));
1886934998bSLisandro Dalcin   }
1899566063dSJacob Faibussowitsch   PetscCall(PetscOptionsName("-ts_monitor_lg_timestep_log", "Monitor log timestep size graphically", "TSMonitorLGTimeStep", &opt));
1908b668821SLisandro Dalcin   if (opt) {
1918b668821SLisandro Dalcin     TSMonitorLGCtx ctx;
1928b668821SLisandro Dalcin     PetscInt       howoften = 1;
1938b668821SLisandro Dalcin 
1949566063dSJacob Faibussowitsch     PetscCall(PetscOptionsInt("-ts_monitor_lg_timestep_log", "Monitor log timestep size graphically", "TSMonitorLGTimeStep", howoften, &howoften, NULL));
1959566063dSJacob Faibussowitsch     PetscCall(TSMonitorLGCtxCreate(PetscObjectComm((PetscObject)ts), NULL, NULL, PETSC_DECIDE, PETSC_DECIDE, 400, 300, howoften, &ctx));
1969566063dSJacob Faibussowitsch     PetscCall(TSMonitorSet(ts, TSMonitorLGTimeStep, ctx, (PetscErrorCode(*)(void **))TSMonitorLGCtxDestroy));
1978b668821SLisandro Dalcin     ctx->semilogy = PETSC_TRUE;
1988b668821SLisandro Dalcin   }
1998b668821SLisandro Dalcin 
2009566063dSJacob Faibussowitsch   PetscCall(PetscOptionsName("-ts_monitor_lg_snes_iterations", "Monitor number nonlinear iterations for each timestep graphically", "TSMonitorLGSNESIterations", &opt));
201201da799SBarry Smith   if (opt) {
202201da799SBarry Smith     TSMonitorLGCtx ctx;
203201da799SBarry Smith     PetscInt       howoften = 1;
204201da799SBarry Smith 
2059566063dSJacob Faibussowitsch     PetscCall(PetscOptionsInt("-ts_monitor_lg_snes_iterations", "Monitor number nonlinear iterations for each timestep graphically", "TSMonitorLGSNESIterations", howoften, &howoften, NULL));
2069566063dSJacob Faibussowitsch     PetscCall(TSMonitorLGCtxCreate(PetscObjectComm((PetscObject)ts), NULL, NULL, PETSC_DECIDE, PETSC_DECIDE, 400, 300, howoften, &ctx));
2079566063dSJacob Faibussowitsch     PetscCall(TSMonitorSet(ts, TSMonitorLGSNESIterations, ctx, (PetscErrorCode(*)(void **))TSMonitorLGCtxDestroy));
208201da799SBarry Smith   }
2099566063dSJacob Faibussowitsch   PetscCall(PetscOptionsName("-ts_monitor_lg_ksp_iterations", "Monitor number nonlinear iterations for each timestep graphically", "TSMonitorLGKSPIterations", &opt));
210201da799SBarry Smith   if (opt) {
211201da799SBarry Smith     TSMonitorLGCtx ctx;
212201da799SBarry Smith     PetscInt       howoften = 1;
213201da799SBarry Smith 
2149566063dSJacob Faibussowitsch     PetscCall(PetscOptionsInt("-ts_monitor_lg_ksp_iterations", "Monitor number nonlinear iterations for each timestep graphically", "TSMonitorLGKSPIterations", howoften, &howoften, NULL));
2159566063dSJacob Faibussowitsch     PetscCall(TSMonitorLGCtxCreate(PetscObjectComm((PetscObject)ts), NULL, NULL, PETSC_DECIDE, PETSC_DECIDE, 400, 300, howoften, &ctx));
2169566063dSJacob Faibussowitsch     PetscCall(TSMonitorSet(ts, TSMonitorLGKSPIterations, ctx, (PetscErrorCode(*)(void **))TSMonitorLGCtxDestroy));
217201da799SBarry Smith   }
2189566063dSJacob Faibussowitsch   PetscCall(PetscOptionsName("-ts_monitor_sp_eig", "Monitor eigenvalues of linearized operator graphically", "TSMonitorSPEig", &opt));
2198189c53fSBarry Smith   if (opt) {
2208189c53fSBarry Smith     TSMonitorSPEigCtx ctx;
2218189c53fSBarry Smith     PetscInt          howoften = 1;
2228189c53fSBarry Smith 
2239566063dSJacob Faibussowitsch     PetscCall(PetscOptionsInt("-ts_monitor_sp_eig", "Monitor eigenvalues of linearized operator graphically", "TSMonitorSPEig", howoften, &howoften, NULL));
2249566063dSJacob Faibussowitsch     PetscCall(TSMonitorSPEigCtxCreate(PETSC_COMM_SELF, NULL, NULL, PETSC_DECIDE, PETSC_DECIDE, 300, 300, howoften, &ctx));
2259566063dSJacob Faibussowitsch     PetscCall(TSMonitorSet(ts, TSMonitorSPEig, ctx, (PetscErrorCode(*)(void **))TSMonitorSPEigCtxDestroy));
2268189c53fSBarry Smith   }
22760e16b1bSMatthew G. Knepley   PetscCall(PetscOptionsName("-ts_monitor_sp_swarm", "Display particle phase space from the DMSwarm", "TSMonitorSPSwarm", &opt));
2281b575b74SJoseph Pusztay   if (opt) {
2291b575b74SJoseph Pusztay     TSMonitorSPCtx ctx;
230d7462660SMatthew Knepley     PetscInt       howoften = 1, retain = 0;
23160e16b1bSMatthew G. Knepley     PetscBool      phase = PETSC_TRUE, create = PETSC_TRUE, multispecies = PETSC_FALSE;
232d7462660SMatthew Knepley 
2339371c9d4SSatish Balay     for (PetscInt i = 0; i < ts->numbermonitors; ++i)
2349371c9d4SSatish Balay       if (ts->monitor[i] == TSMonitorSPSwarmSolution) {
2359371c9d4SSatish Balay         create = PETSC_FALSE;
2369371c9d4SSatish Balay         break;
2379371c9d4SSatish Balay       }
2386a5217c0SMatthew G. Knepley     if (create) {
23960e16b1bSMatthew G. Knepley       PetscCall(PetscOptionsInt("-ts_monitor_sp_swarm", "Display particles phase space from the DMSwarm", "TSMonitorSPSwarm", howoften, &howoften, NULL));
2409566063dSJacob Faibussowitsch       PetscCall(PetscOptionsInt("-ts_monitor_sp_swarm_retain", "Retain n points plotted to show trajectory, -1 for all points", "TSMonitorSPSwarm", retain, &retain, NULL));
2419566063dSJacob Faibussowitsch       PetscCall(PetscOptionsBool("-ts_monitor_sp_swarm_phase", "Plot in phase space rather than coordinate space", "TSMonitorSPSwarm", phase, &phase, NULL));
24260e16b1bSMatthew G. Knepley       PetscCall(PetscOptionsBool("-ts_monitor_sp_swarm_multi_species", "Color particles by particle species", "TSMonitorSPSwarm", multispecies, &multispecies, NULL));
24360e16b1bSMatthew G. Knepley       PetscCall(TSMonitorSPCtxCreate(PetscObjectComm((PetscObject)ts), NULL, NULL, PETSC_DECIDE, PETSC_DECIDE, 300, 300, howoften, retain, phase, multispecies, &ctx));
2449566063dSJacob Faibussowitsch       PetscCall(TSMonitorSet(ts, TSMonitorSPSwarmSolution, ctx, (PetscErrorCode(*)(void **))TSMonitorSPCtxDestroy));
2451b575b74SJoseph Pusztay     }
2466a5217c0SMatthew G. Knepley   }
24760e16b1bSMatthew G. Knepley   PetscCall(PetscOptionsName("-ts_monitor_hg_swarm", "Display particle histogram from the DMSwarm", "TSMonitorHGSwarm", &opt));
24860e16b1bSMatthew G. Knepley   if (opt) {
24960e16b1bSMatthew G. Knepley     TSMonitorHGCtx ctx;
25060e16b1bSMatthew G. Knepley     PetscInt       howoften = 1, Ns = 1;
25160e16b1bSMatthew G. Knepley     PetscBool      velocity = PETSC_FALSE, create = PETSC_TRUE;
25260e16b1bSMatthew G. Knepley 
25360e16b1bSMatthew G. Knepley     for (PetscInt i = 0; i < ts->numbermonitors; ++i)
25460e16b1bSMatthew G. Knepley       if (ts->monitor[i] == TSMonitorHGSwarmSolution) {
25560e16b1bSMatthew G. Knepley         create = PETSC_FALSE;
25660e16b1bSMatthew G. Knepley         break;
25760e16b1bSMatthew G. Knepley       }
25860e16b1bSMatthew G. Knepley     if (create) {
25960e16b1bSMatthew G. Knepley       DM       sw, dm;
26060e16b1bSMatthew G. Knepley       PetscInt Nc, Nb;
26160e16b1bSMatthew G. Knepley 
26260e16b1bSMatthew G. Knepley       PetscCall(TSGetDM(ts, &sw));
26360e16b1bSMatthew G. Knepley       PetscCall(DMSwarmGetCellDM(sw, &dm));
26460e16b1bSMatthew G. Knepley       PetscCall(DMPlexGetHeightStratum(dm, 0, NULL, &Nc));
26560e16b1bSMatthew G. Knepley       Nb = PetscMin(20, PetscMax(10, Nc));
26660e16b1bSMatthew G. Knepley       PetscCall(PetscOptionsInt("-ts_monitor_hg_swarm", "Display particles histogram from the DMSwarm", "TSMonitorHGSwarm", howoften, &howoften, NULL));
26760e16b1bSMatthew G. Knepley       PetscCall(PetscOptionsBool("-ts_monitor_hg_swarm_velocity", "Plot in velocity space rather than coordinate space", "TSMonitorHGSwarm", velocity, &velocity, NULL));
26860e16b1bSMatthew G. Knepley       PetscCall(PetscOptionsInt("-ts_monitor_hg_swarm_species", "Number of species to histogram", "TSMonitorHGSwarm", Ns, &Ns, NULL));
26960e16b1bSMatthew G. Knepley       PetscCall(PetscOptionsInt("-ts_monitor_hg_swarm_bins", "Number of histogram bins", "TSMonitorHGSwarm", Nb, &Nb, NULL));
27060e16b1bSMatthew G. Knepley       PetscCall(TSMonitorHGCtxCreate(PetscObjectComm((PetscObject)ts), NULL, NULL, PETSC_DECIDE, PETSC_DECIDE, 300, 300, howoften, Ns, Nb, velocity, &ctx));
27160e16b1bSMatthew G. Knepley       PetscCall(TSMonitorSet(ts, TSMonitorHGSwarmSolution, ctx, (PetscErrorCode(*)(void **))TSMonitorHGCtxDestroy));
27260e16b1bSMatthew G. Knepley     }
27360e16b1bSMatthew G. Knepley   }
274ef20d060SBarry Smith   opt = PETSC_FALSE;
2759566063dSJacob Faibussowitsch   PetscCall(PetscOptionsName("-ts_monitor_draw_solution", "Monitor solution graphically", "TSMonitorDrawSolution", &opt));
276a7cc72afSBarry Smith   if (opt) {
27783a4ac43SBarry Smith     TSMonitorDrawCtx ctx;
27883a4ac43SBarry Smith     PetscInt         howoften = 1;
279a80ad3e0SBarry Smith 
2809566063dSJacob Faibussowitsch     PetscCall(PetscOptionsInt("-ts_monitor_draw_solution", "Monitor solution graphically", "TSMonitorDrawSolution", howoften, &howoften, NULL));
2819566063dSJacob Faibussowitsch     PetscCall(TSMonitorDrawCtxCreate(PetscObjectComm((PetscObject)ts), NULL, "Computed Solution", PETSC_DECIDE, PETSC_DECIDE, 300, 300, howoften, &ctx));
2829566063dSJacob Faibussowitsch     PetscCall(TSMonitorSet(ts, TSMonitorDrawSolution, ctx, (PetscErrorCode(*)(void **))TSMonitorDrawCtxDestroy));
283bdad233fSMatthew Knepley   }
284fb1732b5SBarry Smith   opt = PETSC_FALSE;
2859566063dSJacob Faibussowitsch   PetscCall(PetscOptionsName("-ts_monitor_draw_solution_phase", "Monitor solution graphically", "TSMonitorDrawSolutionPhase", &opt));
2862d5ee99bSBarry Smith   if (opt) {
2872d5ee99bSBarry Smith     TSMonitorDrawCtx ctx;
2882d5ee99bSBarry Smith     PetscReal        bounds[4];
2892d5ee99bSBarry Smith     PetscInt         n = 4;
2902d5ee99bSBarry Smith     PetscDraw        draw;
2916934998bSLisandro Dalcin     PetscDrawAxis    axis;
2922d5ee99bSBarry Smith 
2939566063dSJacob Faibussowitsch     PetscCall(PetscOptionsRealArray("-ts_monitor_draw_solution_phase", "Monitor solution graphically", "TSMonitorDrawSolutionPhase", bounds, &n, NULL));
2943c633725SBarry Smith     PetscCheck(n == 4, PetscObjectComm((PetscObject)ts), PETSC_ERR_ARG_WRONG, "Must provide bounding box of phase field");
2959566063dSJacob Faibussowitsch     PetscCall(TSMonitorDrawCtxCreate(PetscObjectComm((PetscObject)ts), NULL, NULL, PETSC_DECIDE, PETSC_DECIDE, 300, 300, 1, &ctx));
2969566063dSJacob Faibussowitsch     PetscCall(PetscViewerDrawGetDraw(ctx->viewer, 0, &draw));
2979566063dSJacob Faibussowitsch     PetscCall(PetscViewerDrawGetDrawAxis(ctx->viewer, 0, &axis));
2989566063dSJacob Faibussowitsch     PetscCall(PetscDrawAxisSetLimits(axis, bounds[0], bounds[2], bounds[1], bounds[3]));
2999566063dSJacob Faibussowitsch     PetscCall(PetscDrawAxisSetLabels(axis, "Phase Diagram", "Variable 1", "Variable 2"));
3009566063dSJacob Faibussowitsch     PetscCall(TSMonitorSet(ts, TSMonitorDrawSolutionPhase, ctx, (PetscErrorCode(*)(void **))TSMonitorDrawCtxDestroy));
3012d5ee99bSBarry Smith   }
3022d5ee99bSBarry Smith   opt = PETSC_FALSE;
3039566063dSJacob Faibussowitsch   PetscCall(PetscOptionsName("-ts_monitor_draw_error", "Monitor error graphically", "TSMonitorDrawError", &opt));
3043a471f94SBarry Smith   if (opt) {
30583a4ac43SBarry Smith     TSMonitorDrawCtx ctx;
30683a4ac43SBarry Smith     PetscInt         howoften = 1;
3073a471f94SBarry Smith 
3089566063dSJacob Faibussowitsch     PetscCall(PetscOptionsInt("-ts_monitor_draw_error", "Monitor error graphically", "TSMonitorDrawError", howoften, &howoften, NULL));
3099566063dSJacob Faibussowitsch     PetscCall(TSMonitorDrawCtxCreate(PetscObjectComm((PetscObject)ts), NULL, "Error", PETSC_DECIDE, PETSC_DECIDE, 300, 300, howoften, &ctx));
3109566063dSJacob Faibussowitsch     PetscCall(TSMonitorSet(ts, TSMonitorDrawError, ctx, (PetscErrorCode(*)(void **))TSMonitorDrawCtxDestroy));
3113a471f94SBarry Smith   }
3120ed3bfb6SBarry Smith   opt = PETSC_FALSE;
3139566063dSJacob Faibussowitsch   PetscCall(PetscOptionsName("-ts_monitor_draw_solution_function", "Monitor solution provided by TSMonitorSetSolutionFunction() graphically", "TSMonitorDrawSolutionFunction", &opt));
3140ed3bfb6SBarry Smith   if (opt) {
3150ed3bfb6SBarry Smith     TSMonitorDrawCtx ctx;
3160ed3bfb6SBarry Smith     PetscInt         howoften = 1;
3170ed3bfb6SBarry Smith 
3189566063dSJacob Faibussowitsch     PetscCall(PetscOptionsInt("-ts_monitor_draw_solution_function", "Monitor solution provided by TSMonitorSetSolutionFunction() graphically", "TSMonitorDrawSolutionFunction", howoften, &howoften, NULL));
3199566063dSJacob Faibussowitsch     PetscCall(TSMonitorDrawCtxCreate(PetscObjectComm((PetscObject)ts), NULL, "Solution provided by user function", PETSC_DECIDE, PETSC_DECIDE, 300, 300, howoften, &ctx));
3209566063dSJacob Faibussowitsch     PetscCall(TSMonitorSet(ts, TSMonitorDrawSolutionFunction, ctx, (PetscErrorCode(*)(void **))TSMonitorDrawCtxDestroy));
3210ed3bfb6SBarry Smith   }
322fde5950dSBarry Smith 
323ed81e22dSJed Brown   opt = PETSC_FALSE;
32463a3b9bcSJacob 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));
325ed81e22dSJed Brown   if (flg) {
326bbcf679cSJacob Faibussowitsch     const char *ptr = NULL, *ptr2 = NULL;
327ed81e22dSJed Brown     char       *filetemplate;
32863a3b9bcSJacob 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");
329ed81e22dSJed Brown     /* Do some cursory validation of the input. */
3309566063dSJacob Faibussowitsch     PetscCall(PetscStrstr(monfilename, "%", (char **)&ptr));
33163a3b9bcSJacob Faibussowitsch     PetscCheck(ptr, PetscObjectComm((PetscObject)ts), PETSC_ERR_USER, "-ts_monitor_solution_vtk requires a file template, e.g. filename-%%03" PetscInt_FMT ".vts");
332ed81e22dSJed Brown     for (ptr++; ptr && *ptr; ptr++) {
3339566063dSJacob Faibussowitsch       PetscCall(PetscStrchr("DdiouxX", *ptr, (char **)&ptr2));
33463a3b9bcSJacob 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");
335ed81e22dSJed Brown       if (ptr2) break;
336ed81e22dSJed Brown     }
3379566063dSJacob Faibussowitsch     PetscCall(PetscStrallocpy(monfilename, &filetemplate));
3389566063dSJacob Faibussowitsch     PetscCall(TSMonitorSet(ts, TSMonitorSolutionVTK, filetemplate, (PetscErrorCode(*)(void **))TSMonitorSolutionVTKDestroy));
339ed81e22dSJed Brown   }
340bdad233fSMatthew Knepley 
3419566063dSJacob Faibussowitsch   PetscCall(PetscOptionsString("-ts_monitor_dmda_ray", "Display a ray of the solution", "None", "y=0", dir, sizeof(dir), &flg));
342d1212d36SBarry Smith   if (flg) {
343d1212d36SBarry Smith     TSMonitorDMDARayCtx *rayctx;
344d1212d36SBarry Smith     int                  ray = 0;
3453ee9839eSMatthew G. Knepley     DMDirection          ddir;
346d1212d36SBarry Smith     DM                   da;
347d1212d36SBarry Smith     PetscMPIInt          rank;
348d1212d36SBarry Smith 
3493c633725SBarry Smith     PetscCheck(dir[1] == '=', PetscObjectComm((PetscObject)ts), PETSC_ERR_ARG_WRONG, "Unknown ray %s", dir);
3503ee9839eSMatthew G. Knepley     if (dir[0] == 'x') ddir = DM_X;
3513ee9839eSMatthew G. Knepley     else if (dir[0] == 'y') ddir = DM_Y;
35298921bdaSJacob Faibussowitsch     else SETERRQ(PetscObjectComm((PetscObject)ts), PETSC_ERR_ARG_WRONG, "Unknown ray %s", dir);
353d1212d36SBarry Smith     sscanf(dir + 2, "%d", &ray);
354d1212d36SBarry Smith 
3559566063dSJacob Faibussowitsch     PetscCall(PetscInfo(((PetscObject)ts), "Displaying DMDA ray %c = %d\n", dir[0], ray));
3569566063dSJacob Faibussowitsch     PetscCall(PetscNew(&rayctx));
3579566063dSJacob Faibussowitsch     PetscCall(TSGetDM(ts, &da));
3589566063dSJacob Faibussowitsch     PetscCall(DMDAGetRay(da, ddir, ray, &rayctx->ray, &rayctx->scatter));
3599566063dSJacob Faibussowitsch     PetscCallMPI(MPI_Comm_rank(PetscObjectComm((PetscObject)ts), &rank));
3601e66621cSBarry Smith     if (rank == 0) PetscCall(PetscViewerDrawOpen(PETSC_COMM_SELF, NULL, NULL, 0, 0, 600, 300, &rayctx->viewer));
36151b4a12fSMatthew G. Knepley     rayctx->lgctx = NULL;
3629566063dSJacob Faibussowitsch     PetscCall(TSMonitorSet(ts, TSMonitorDMDARay, rayctx, TSMonitorDMDARayDestroy));
363d1212d36SBarry Smith   }
3649566063dSJacob Faibussowitsch   PetscCall(PetscOptionsString("-ts_monitor_lg_dmda_ray", "Display a ray of the solution", "None", "x=0", dir, sizeof(dir), &flg));
36551b4a12fSMatthew G. Knepley   if (flg) {
36651b4a12fSMatthew G. Knepley     TSMonitorDMDARayCtx *rayctx;
36751b4a12fSMatthew G. Knepley     int                  ray = 0;
3683ee9839eSMatthew G. Knepley     DMDirection          ddir;
36951b4a12fSMatthew G. Knepley     DM                   da;
37051b4a12fSMatthew G. Knepley     PetscInt             howoften = 1;
371d1212d36SBarry Smith 
3723c633725SBarry Smith     PetscCheck(dir[1] == '=', PetscObjectComm((PetscObject)ts), PETSC_ERR_ARG_WRONG, "Malformed ray %s", dir);
3733ee9839eSMatthew G. Knepley     if (dir[0] == 'x') ddir = DM_X;
3743ee9839eSMatthew G. Knepley     else if (dir[0] == 'y') ddir = DM_Y;
37598921bdaSJacob Faibussowitsch     else SETERRQ(PetscObjectComm((PetscObject)ts), PETSC_ERR_ARG_WRONG, "Unknown ray direction %s", dir);
37651b4a12fSMatthew G. Knepley     sscanf(dir + 2, "%d", &ray);
3771c3436cfSJed Brown 
3789566063dSJacob Faibussowitsch     PetscCall(PetscInfo(((PetscObject)ts), "Displaying LG DMDA ray %c = %d\n", dir[0], ray));
3799566063dSJacob Faibussowitsch     PetscCall(PetscNew(&rayctx));
3809566063dSJacob Faibussowitsch     PetscCall(TSGetDM(ts, &da));
3819566063dSJacob Faibussowitsch     PetscCall(DMDAGetRay(da, ddir, ray, &rayctx->ray, &rayctx->scatter));
3829566063dSJacob Faibussowitsch     PetscCall(TSMonitorLGCtxCreate(PETSC_COMM_SELF, NULL, NULL, PETSC_DECIDE, PETSC_DECIDE, 600, 400, howoften, &rayctx->lgctx));
3839566063dSJacob Faibussowitsch     PetscCall(TSMonitorSet(ts, TSMonitorLGDMDARay, rayctx, TSMonitorDMDARayDestroy));
38451b4a12fSMatthew G. Knepley   }
385a7a1495cSBarry Smith 
3869566063dSJacob Faibussowitsch   PetscCall(PetscOptionsName("-ts_monitor_envelope", "Monitor maximum and minimum value of each component of the solution", "TSMonitorEnvelope", &opt));
387b3d3934dSBarry Smith   if (opt) {
388b3d3934dSBarry Smith     TSMonitorEnvelopeCtx ctx;
389b3d3934dSBarry Smith 
3909566063dSJacob Faibussowitsch     PetscCall(TSMonitorEnvelopeCtxCreate(ts, &ctx));
3919566063dSJacob Faibussowitsch     PetscCall(TSMonitorSet(ts, TSMonitorEnvelope, ctx, (PetscErrorCode(*)(void **))TSMonitorEnvelopeCtxDestroy));
392b3d3934dSBarry Smith   }
393aee7a9fbSMatthew G. Knepley   flg = PETSC_FALSE;
3949566063dSJacob Faibussowitsch   PetscCall(PetscOptionsBool("-ts_monitor_cancel", "Remove all monitors", "TSMonitorCancel", flg, &flg, &opt));
3959566063dSJacob Faibussowitsch   if (opt && flg) PetscCall(TSMonitorCancel(ts));
396b3d3934dSBarry Smith 
397847ff0e1SMatthew G. Knepley   flg = PETSC_FALSE;
398d7cfae9bSHong Zhang   PetscCall(PetscOptionsBool("-ts_fd_color", "Use finite differences with coloring to compute IJacobian", "TSComputeIJacobianDefaultColor", flg, &flg, NULL));
399847ff0e1SMatthew G. Knepley   if (flg) {
400847ff0e1SMatthew G. Knepley     DM dm;
401847ff0e1SMatthew G. Knepley 
4029371c9d4SSatish Balay     PetscCall(TSGetDM(ts, &dm));
4039371c9d4SSatish Balay     PetscCall(DMTSUnsetIJacobianContext_Internal(dm));
4049566063dSJacob Faibussowitsch     PetscCall(TSSetIJacobian(ts, NULL, NULL, TSComputeIJacobianDefaultColor, NULL));
4059566063dSJacob Faibussowitsch     PetscCall(PetscInfo(ts, "Setting default finite difference coloring Jacobian matrix\n"));
406847ff0e1SMatthew G. Knepley   }
407847ff0e1SMatthew G. Knepley 
408d763cef2SBarry Smith   /* Handle specific TS options */
409dbbe0bcdSBarry Smith   PetscTryTypeMethod(ts, setfromoptions, PetscOptionsObject);
410fbc52257SHong Zhang 
411a7bdc993SLisandro Dalcin   /* Handle TSAdapt options */
4129566063dSJacob Faibussowitsch   PetscCall(TSGetAdapt(ts, &ts->adapt));
4139566063dSJacob Faibussowitsch   PetscCall(TSAdaptSetDefaultType(ts->adapt, ts->default_adapt_type));
414dbbe0bcdSBarry Smith   PetscCall(TSAdaptSetFromOptions(ts->adapt, PetscOptionsObject));
415a7bdc993SLisandro Dalcin 
41668bece0bSHong Zhang   /* TS trajectory must be set after TS, since it may use some TS options above */
4174f122a70SLisandro Dalcin   tflg = ts->trajectory ? PETSC_TRUE : PETSC_FALSE;
4189566063dSJacob Faibussowitsch   PetscCall(PetscOptionsBool("-ts_save_trajectory", "Save the solution at each timestep", "TSSetSaveTrajectory", tflg, &tflg, NULL));
4191baa6e33SBarry Smith   if (tflg) PetscCall(TSSetSaveTrajectory(ts));
420a05bf03eSHong Zhang 
421dbbe0bcdSBarry Smith   PetscCall(TSAdjointSetFromOptions(ts, PetscOptionsObject));
422d763cef2SBarry Smith 
423d763cef2SBarry Smith   /* process any options handlers added with PetscObjectAddOptionsHandler() */
424dbbe0bcdSBarry Smith   PetscCall(PetscObjectProcessOptionsHandlers((PetscObject)ts, PetscOptionsObject));
425d0609cedSBarry Smith   PetscOptionsEnd();
426d763cef2SBarry Smith 
4271baa6e33SBarry Smith   if (ts->trajectory) PetscCall(TSTrajectorySetFromOptions(ts->trajectory, ts));
42868bece0bSHong Zhang 
4291ef27442SStefano Zampini   /* why do we have to do this here and not during TSSetUp? */
4309566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts, &ts->snes));
4311ef27442SStefano Zampini   if (ts->problem_type == TS_LINEAR) {
4329566063dSJacob Faibussowitsch     PetscCall(PetscObjectTypeCompareAny((PetscObject)ts->snes, &flg, SNESKSPONLY, SNESKSPTRANSPOSEONLY, ""));
4339566063dSJacob Faibussowitsch     if (!flg) PetscCall(SNESSetType(ts->snes, SNESKSPONLY));
4341ef27442SStefano Zampini   }
4359566063dSJacob Faibussowitsch   PetscCall(SNESSetFromOptions(ts->snes));
4363ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
437d763cef2SBarry Smith }
438d763cef2SBarry Smith 
439d2daff3dSHong Zhang /*@
440bcf0153eSBarry Smith   TSGetTrajectory - Gets the trajectory from a `TS` if it exists
44178fbdcc8SBarry Smith 
442c3339decSBarry Smith   Collective
44378fbdcc8SBarry Smith 
4442fe279fdSBarry Smith   Input Parameter:
445bcf0153eSBarry Smith . ts - the `TS` context obtained from `TSCreate()`
44678fbdcc8SBarry Smith 
4472fe279fdSBarry Smith   Output Parameter:
448bcf0153eSBarry Smith . tr - the `TSTrajectory` object, if it exists
44978fbdcc8SBarry Smith 
45078fbdcc8SBarry Smith   Level: advanced
45178fbdcc8SBarry Smith 
452bcf0153eSBarry Smith   Note:
453bcf0153eSBarry Smith   This routine should be called after all `TS` options have been set
45478fbdcc8SBarry Smith 
455b43aa488SJacob Faibussowitsch .seealso: [](ch_ts), `TS`, `TSTrajectory`, `TSAdjointSolve()`, `TSTrajectoryCreate()`
45678fbdcc8SBarry Smith @*/
457d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetTrajectory(TS ts, TSTrajectory *tr)
458d71ae5a4SJacob Faibussowitsch {
45978fbdcc8SBarry Smith   PetscFunctionBegin;
46078fbdcc8SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
46178fbdcc8SBarry Smith   *tr = ts->trajectory;
4623ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
46378fbdcc8SBarry Smith }
46478fbdcc8SBarry Smith 
46578fbdcc8SBarry Smith /*@
466bcf0153eSBarry Smith   TSSetSaveTrajectory - Causes the `TS` to save its solutions as it iterates forward in time in a `TSTrajectory` object
467d2daff3dSHong Zhang 
468c3339decSBarry Smith   Collective
469d2daff3dSHong Zhang 
470f899ff85SJose E. Roman   Input Parameter:
471bcf0153eSBarry Smith . ts - the `TS` context obtained from `TSCreate()`
472bc952696SBarry Smith 
473bcf0153eSBarry Smith   Options Database Keys:
47478fbdcc8SBarry Smith + -ts_save_trajectory      - saves the trajectory to a file
47567b8a455SSatish Balay - -ts_trajectory_type type - set trajectory type
47678fbdcc8SBarry Smith 
477d2daff3dSHong Zhang   Level: intermediate
478d2daff3dSHong Zhang 
479bcf0153eSBarry Smith   Notes:
480bcf0153eSBarry Smith   This routine should be called after all `TS` options have been set
481d2daff3dSHong Zhang 
482bcf0153eSBarry Smith   The `TSTRAJECTORYVISUALIZATION` files can be loaded into Python with $PETSC_DIR/lib/petsc/bin/PetscBinaryIOTrajectory.py and
483bcf0153eSBarry Smith   MATLAB with $PETSC_DIR/share/petsc/matlab/PetscReadBinaryTrajectory.m
484bcf0153eSBarry Smith 
4851cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSTrajectory`, `TSGetTrajectory()`, `TSAdjointSolve()`
486d2daff3dSHong Zhang @*/
487d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetSaveTrajectory(TS ts)
488d71ae5a4SJacob Faibussowitsch {
489d2daff3dSHong Zhang   PetscFunctionBegin;
490d2daff3dSHong Zhang   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
49163a3b9bcSJacob Faibussowitsch   if (!ts->trajectory) PetscCall(TSTrajectoryCreate(PetscObjectComm((PetscObject)ts), &ts->trajectory));
4923ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
493d2daff3dSHong Zhang }
494d2daff3dSHong Zhang 
495a7a1495cSBarry Smith /*@
496bcf0153eSBarry Smith   TSResetTrajectory - Destroys and recreates the internal `TSTrajectory` object
4972d29f1f2SStefano Zampini 
498c3339decSBarry Smith   Collective
4992d29f1f2SStefano Zampini 
5002fe279fdSBarry Smith   Input Parameter:
501bcf0153eSBarry Smith . ts - the `TS` context obtained from `TSCreate()`
5022d29f1f2SStefano Zampini 
5032d29f1f2SStefano Zampini   Level: intermediate
5042d29f1f2SStefano Zampini 
5051cc06b55SBarry Smith .seealso: [](ch_ts), `TSTrajectory`, `TSGetTrajectory()`, `TSAdjointSolve()`, `TSRemoveTrajectory()`
5062d29f1f2SStefano Zampini @*/
507d71ae5a4SJacob Faibussowitsch PetscErrorCode TSResetTrajectory(TS ts)
508d71ae5a4SJacob Faibussowitsch {
5092d29f1f2SStefano Zampini   PetscFunctionBegin;
5102d29f1f2SStefano Zampini   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
5112d29f1f2SStefano Zampini   if (ts->trajectory) {
5129566063dSJacob Faibussowitsch     PetscCall(TSTrajectoryDestroy(&ts->trajectory));
5139566063dSJacob Faibussowitsch     PetscCall(TSTrajectoryCreate(PetscObjectComm((PetscObject)ts), &ts->trajectory));
5142d29f1f2SStefano Zampini   }
5153ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
5162d29f1f2SStefano Zampini }
5172d29f1f2SStefano Zampini 
5182d29f1f2SStefano Zampini /*@
519195e9b02SBarry Smith   TSRemoveTrajectory - Destroys and removes the internal `TSTrajectory` object from a `TS`
52067a3cfb0SHong Zhang 
521c3339decSBarry Smith   Collective
52267a3cfb0SHong Zhang 
5232fe279fdSBarry Smith   Input Parameter:
524bcf0153eSBarry Smith . ts - the `TS` context obtained from `TSCreate()`
52567a3cfb0SHong Zhang 
52667a3cfb0SHong Zhang   Level: intermediate
52767a3cfb0SHong Zhang 
5281cc06b55SBarry Smith .seealso: [](ch_ts), `TSTrajectory`, `TSResetTrajectory()`, `TSAdjointSolve()`
52967a3cfb0SHong Zhang @*/
530d71ae5a4SJacob Faibussowitsch PetscErrorCode TSRemoveTrajectory(TS ts)
531d71ae5a4SJacob Faibussowitsch {
53267a3cfb0SHong Zhang   PetscFunctionBegin;
53367a3cfb0SHong Zhang   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
5341e66621cSBarry Smith   if (ts->trajectory) PetscCall(TSTrajectoryDestroy(&ts->trajectory));
5353ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
53667a3cfb0SHong Zhang }
53767a3cfb0SHong Zhang 
53867a3cfb0SHong Zhang /*@
539a7a1495cSBarry Smith   TSComputeRHSJacobian - Computes the Jacobian matrix that has been
540bcf0153eSBarry Smith   set with `TSSetRHSJacobian()`.
541a7a1495cSBarry Smith 
542c3339decSBarry Smith   Collective
543a7a1495cSBarry Smith 
544a7a1495cSBarry Smith   Input Parameters:
545bcf0153eSBarry Smith + ts - the `TS` context
546a7a1495cSBarry Smith . t  - current timestep
5470910c330SBarry Smith - U  - input vector
548a7a1495cSBarry Smith 
549a7a1495cSBarry Smith   Output Parameters:
550a7a1495cSBarry Smith + A - Jacobian matrix
5516b867d5aSJose E. Roman - B - optional preconditioning matrix
552a7a1495cSBarry Smith 
553bcf0153eSBarry Smith   Level: developer
554bcf0153eSBarry Smith 
555bcf0153eSBarry Smith   Note:
556a7a1495cSBarry Smith   Most users should not need to explicitly call this routine, as it
557a7a1495cSBarry Smith   is used internally within the nonlinear solvers.
558a7a1495cSBarry Smith 
5591cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetRHSJacobian()`, `KSPSetOperators()`
560a7a1495cSBarry Smith @*/
561d71ae5a4SJacob Faibussowitsch PetscErrorCode TSComputeRHSJacobian(TS ts, PetscReal t, Vec U, Mat A, Mat B)
562d71ae5a4SJacob Faibussowitsch {
563270bf2e7SJed Brown   PetscObjectState Ustate;
5646c1e1eecSBarry Smith   PetscObjectId    Uid;
56524989b8cSPeter Brune   DM               dm;
566942e3340SBarry Smith   DMTS             tsdm;
56724989b8cSPeter Brune   TSRHSJacobian    rhsjacobianfunc;
56824989b8cSPeter Brune   void            *ctx;
569b2df71adSDebojyoti Ghosh   TSRHSFunction    rhsfunction;
570a7a1495cSBarry Smith 
571a7a1495cSBarry Smith   PetscFunctionBegin;
5720700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
5730910c330SBarry Smith   PetscValidHeaderSpecific(U, VEC_CLASSID, 3);
5740910c330SBarry Smith   PetscCheckSameComm(ts, 1, U, 3);
5759566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
5769566063dSJacob Faibussowitsch   PetscCall(DMGetDMTS(dm, &tsdm));
5779566063dSJacob Faibussowitsch   PetscCall(DMTSGetRHSFunction(dm, &rhsfunction, NULL));
5789566063dSJacob Faibussowitsch   PetscCall(DMTSGetRHSJacobian(dm, &rhsjacobianfunc, &ctx));
5799566063dSJacob Faibussowitsch   PetscCall(PetscObjectStateGet((PetscObject)U, &Ustate));
5809566063dSJacob Faibussowitsch   PetscCall(PetscObjectGetId((PetscObject)U, &Uid));
581971015bcSStefano Zampini 
5823ba16761SJacob Faibussowitsch   if (ts->rhsjacobian.time == t && (ts->problem_type == TS_LINEAR || (ts->rhsjacobian.Xid == Uid && ts->rhsjacobian.Xstate == Ustate)) && (rhsfunction != TSComputeRHSFunctionLinear)) PetscFunctionReturn(PETSC_SUCCESS);
583d90be118SSean Farley 
58463a3b9bcSJacob 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);
58524989b8cSPeter Brune   if (rhsjacobianfunc) {
5869566063dSJacob Faibussowitsch     PetscCall(PetscLogEventBegin(TS_JacobianEval, ts, U, A, B));
587792fecdfSBarry Smith     PetscCallBack("TS callback Jacobian", (*rhsjacobianfunc)(ts, t, U, A, B, ctx));
588a6ab3590SBarry Smith     ts->rhsjacs++;
5899566063dSJacob Faibussowitsch     PetscCall(PetscLogEventEnd(TS_JacobianEval, ts, U, A, B));
590ef66eb69SBarry Smith   } else {
5919566063dSJacob Faibussowitsch     PetscCall(MatZeroEntries(A));
5929566063dSJacob Faibussowitsch     if (B && A != B) PetscCall(MatZeroEntries(B));
593ef66eb69SBarry Smith   }
5940e4ef248SJed Brown   ts->rhsjacobian.time  = t;
595971015bcSStefano Zampini   ts->rhsjacobian.shift = 0;
596971015bcSStefano Zampini   ts->rhsjacobian.scale = 1.;
5979566063dSJacob Faibussowitsch   PetscCall(PetscObjectGetId((PetscObject)U, &ts->rhsjacobian.Xid));
5989566063dSJacob Faibussowitsch   PetscCall(PetscObjectStateGet((PetscObject)U, &ts->rhsjacobian.Xstate));
5993ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
600a7a1495cSBarry Smith }
601a7a1495cSBarry Smith 
602316643e7SJed Brown /*@
603bcf0153eSBarry Smith   TSComputeRHSFunction - Evaluates the right-hand-side function for a `TS`
604d763cef2SBarry Smith 
605c3339decSBarry Smith   Collective
606316643e7SJed Brown 
607316643e7SJed Brown   Input Parameters:
608bcf0153eSBarry Smith + ts - the `TS` context
609316643e7SJed Brown . t  - current time
6100910c330SBarry Smith - U  - state vector
611316643e7SJed Brown 
612316643e7SJed Brown   Output Parameter:
613316643e7SJed Brown . y - right hand side
614316643e7SJed Brown 
615bcf0153eSBarry Smith   Level: developer
616bcf0153eSBarry Smith 
617316643e7SJed Brown   Note:
618316643e7SJed Brown   Most users should not need to explicitly call this routine, as it
619316643e7SJed Brown   is used internally within the nonlinear solvers.
620316643e7SJed Brown 
6211cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetRHSFunction()`, `TSComputeIFunction()`
622316643e7SJed Brown @*/
623d71ae5a4SJacob Faibussowitsch PetscErrorCode TSComputeRHSFunction(TS ts, PetscReal t, Vec U, Vec y)
624d71ae5a4SJacob Faibussowitsch {
62524989b8cSPeter Brune   TSRHSFunction rhsfunction;
62624989b8cSPeter Brune   TSIFunction   ifunction;
62724989b8cSPeter Brune   void         *ctx;
62824989b8cSPeter Brune   DM            dm;
62924989b8cSPeter Brune 
630d763cef2SBarry Smith   PetscFunctionBegin;
6310700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
6320910c330SBarry Smith   PetscValidHeaderSpecific(U, VEC_CLASSID, 3);
6330700a824SBarry Smith   PetscValidHeaderSpecific(y, VEC_CLASSID, 4);
6349566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
6359566063dSJacob Faibussowitsch   PetscCall(DMTSGetRHSFunction(dm, &rhsfunction, &ctx));
6369566063dSJacob Faibussowitsch   PetscCall(DMTSGetIFunction(dm, &ifunction, NULL));
637d763cef2SBarry Smith 
6383c633725SBarry Smith   PetscCheck(rhsfunction || ifunction, PetscObjectComm((PetscObject)ts), PETSC_ERR_USER, "Must call TSSetRHSFunction() and / or TSSetIFunction()");
639d763cef2SBarry Smith 
64024989b8cSPeter Brune   if (rhsfunction) {
6419566063dSJacob Faibussowitsch     PetscCall(PetscLogEventBegin(TS_FunctionEval, ts, U, y, 0));
6429566063dSJacob Faibussowitsch     PetscCall(VecLockReadPush(U));
643792fecdfSBarry Smith     PetscCallBack("TS callback right-hand-side", (*rhsfunction)(ts, t, U, y, ctx));
6449566063dSJacob Faibussowitsch     PetscCall(VecLockReadPop(U));
645a6ab3590SBarry Smith     ts->rhsfuncs++;
6469566063dSJacob Faibussowitsch     PetscCall(PetscLogEventEnd(TS_FunctionEval, ts, U, y, 0));
6471e66621cSBarry Smith   } else PetscCall(VecZeroEntries(y));
6483ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
649d763cef2SBarry Smith }
650d763cef2SBarry Smith 
651ef20d060SBarry Smith /*@
652ef20d060SBarry Smith   TSComputeSolutionFunction - Evaluates the solution function.
653ef20d060SBarry Smith 
654c3339decSBarry Smith   Collective
655ef20d060SBarry Smith 
656ef20d060SBarry Smith   Input Parameters:
657bcf0153eSBarry Smith + ts - the `TS` context
658ef20d060SBarry Smith - t  - current time
659ef20d060SBarry Smith 
660ef20d060SBarry Smith   Output Parameter:
6610910c330SBarry Smith . U - the solution
662ef20d060SBarry Smith 
663ef20d060SBarry Smith   Level: developer
664ef20d060SBarry Smith 
6651cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetSolutionFunction()`, `TSSetRHSFunction()`, `TSComputeIFunction()`
666ef20d060SBarry Smith @*/
667d71ae5a4SJacob Faibussowitsch PetscErrorCode TSComputeSolutionFunction(TS ts, PetscReal t, Vec U)
668d71ae5a4SJacob Faibussowitsch {
669ef20d060SBarry Smith   TSSolutionFunction solutionfunction;
670ef20d060SBarry Smith   void              *ctx;
671ef20d060SBarry Smith   DM                 dm;
672ef20d060SBarry Smith 
673ef20d060SBarry Smith   PetscFunctionBegin;
674ef20d060SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
6750910c330SBarry Smith   PetscValidHeaderSpecific(U, VEC_CLASSID, 3);
6769566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
6779566063dSJacob Faibussowitsch   PetscCall(DMTSGetSolutionFunction(dm, &solutionfunction, &ctx));
678792fecdfSBarry Smith   if (solutionfunction) PetscCallBack("TS callback solution", (*solutionfunction)(ts, t, U, ctx));
6793ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
680ef20d060SBarry Smith }
6819b7cd975SBarry Smith /*@
6829b7cd975SBarry Smith   TSComputeForcingFunction - Evaluates the forcing function.
6839b7cd975SBarry Smith 
684c3339decSBarry Smith   Collective
6859b7cd975SBarry Smith 
6869b7cd975SBarry Smith   Input Parameters:
687bcf0153eSBarry Smith + ts - the `TS` context
6889b7cd975SBarry Smith - t  - current time
6899b7cd975SBarry Smith 
6909b7cd975SBarry Smith   Output Parameter:
6919b7cd975SBarry Smith . U - the function value
6929b7cd975SBarry Smith 
6939b7cd975SBarry Smith   Level: developer
6949b7cd975SBarry Smith 
6951cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetSolutionFunction()`, `TSSetRHSFunction()`, `TSComputeIFunction()`
6969b7cd975SBarry Smith @*/
697d71ae5a4SJacob Faibussowitsch PetscErrorCode TSComputeForcingFunction(TS ts, PetscReal t, Vec U)
698d71ae5a4SJacob Faibussowitsch {
6999b7cd975SBarry Smith   void             *ctx;
7009b7cd975SBarry Smith   DM                dm;
7015f80ce2aSJacob Faibussowitsch   TSForcingFunction forcing;
7029b7cd975SBarry Smith 
7039b7cd975SBarry Smith   PetscFunctionBegin;
7049b7cd975SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
7059b7cd975SBarry Smith   PetscValidHeaderSpecific(U, VEC_CLASSID, 3);
7069566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
7079566063dSJacob Faibussowitsch   PetscCall(DMTSGetForcingFunction(dm, &forcing, &ctx));
7089b7cd975SBarry Smith 
709792fecdfSBarry Smith   if (forcing) PetscCallBack("TS callback forcing function", (*forcing)(ts, t, U, ctx));
7103ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
7119b7cd975SBarry Smith }
712ef20d060SBarry Smith 
713d71ae5a4SJacob Faibussowitsch static PetscErrorCode TSGetRHSVec_Private(TS ts, Vec *Frhs)
714d71ae5a4SJacob Faibussowitsch {
7152dd45cf8SJed Brown   Vec F;
716214bc6a2SJed Brown 
717214bc6a2SJed Brown   PetscFunctionBegin;
7180298fd71SBarry Smith   *Frhs = NULL;
7199566063dSJacob Faibussowitsch   PetscCall(TSGetIFunction(ts, &F, NULL, NULL));
7201e66621cSBarry Smith   if (!ts->Frhs) PetscCall(VecDuplicate(F, &ts->Frhs));
721214bc6a2SJed Brown   *Frhs = ts->Frhs;
7223ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
723214bc6a2SJed Brown }
724214bc6a2SJed Brown 
725d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetRHSMats_Private(TS ts, Mat *Arhs, Mat *Brhs)
726d71ae5a4SJacob Faibussowitsch {
727214bc6a2SJed Brown   Mat         A, B;
72841a1d4d2SBarry Smith   TSIJacobian ijacobian;
729214bc6a2SJed Brown 
730214bc6a2SJed Brown   PetscFunctionBegin;
731c0cd0301SJed Brown   if (Arhs) *Arhs = NULL;
732c0cd0301SJed Brown   if (Brhs) *Brhs = NULL;
7339566063dSJacob Faibussowitsch   PetscCall(TSGetIJacobian(ts, &A, &B, &ijacobian, NULL));
734214bc6a2SJed Brown   if (Arhs) {
735214bc6a2SJed Brown     if (!ts->Arhs) {
73641a1d4d2SBarry Smith       if (ijacobian) {
7379566063dSJacob Faibussowitsch         PetscCall(MatDuplicate(A, MAT_DO_NOT_COPY_VALUES, &ts->Arhs));
7389566063dSJacob Faibussowitsch         PetscCall(TSSetMatStructure(ts, SAME_NONZERO_PATTERN));
73941a1d4d2SBarry Smith       } else {
74041a1d4d2SBarry Smith         ts->Arhs = A;
7419566063dSJacob Faibussowitsch         PetscCall(PetscObjectReference((PetscObject)A));
74241a1d4d2SBarry Smith       }
7433565c898SBarry Smith     } else {
7443565c898SBarry Smith       PetscBool flg;
7459566063dSJacob Faibussowitsch       PetscCall(SNESGetUseMatrixFree(ts->snes, NULL, &flg));
7463565c898SBarry Smith       /* Handle case where user provided only RHSJacobian and used -snes_mf_operator */
7473565c898SBarry Smith       if (flg && !ijacobian && ts->Arhs == ts->Brhs) {
7489566063dSJacob Faibussowitsch         PetscCall(PetscObjectDereference((PetscObject)ts->Arhs));
7493565c898SBarry Smith         ts->Arhs = A;
7509566063dSJacob Faibussowitsch         PetscCall(PetscObjectReference((PetscObject)A));
7513565c898SBarry Smith       }
752214bc6a2SJed Brown     }
753214bc6a2SJed Brown     *Arhs = ts->Arhs;
754214bc6a2SJed Brown   }
755214bc6a2SJed Brown   if (Brhs) {
756214bc6a2SJed Brown     if (!ts->Brhs) {
757bdb70873SJed Brown       if (A != B) {
75841a1d4d2SBarry Smith         if (ijacobian) {
7599566063dSJacob Faibussowitsch           PetscCall(MatDuplicate(B, MAT_DO_NOT_COPY_VALUES, &ts->Brhs));
760bdb70873SJed Brown         } else {
76141a1d4d2SBarry Smith           ts->Brhs = B;
7629566063dSJacob Faibussowitsch           PetscCall(PetscObjectReference((PetscObject)B));
76341a1d4d2SBarry Smith         }
76441a1d4d2SBarry Smith       } else {
7659566063dSJacob Faibussowitsch         PetscCall(PetscObjectReference((PetscObject)ts->Arhs));
76651699248SLisandro Dalcin         ts->Brhs = ts->Arhs;
767bdb70873SJed Brown       }
768214bc6a2SJed Brown     }
769214bc6a2SJed Brown     *Brhs = ts->Brhs;
770214bc6a2SJed Brown   }
7713ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
772214bc6a2SJed Brown }
773214bc6a2SJed Brown 
774316643e7SJed Brown /*@
775195e9b02SBarry Smith   TSComputeIFunction - Evaluates the DAE residual written in the implicit form F(t,U,Udot)=0
776316643e7SJed Brown 
777c3339decSBarry Smith   Collective
778316643e7SJed Brown 
779316643e7SJed Brown   Input Parameters:
780bcf0153eSBarry Smith + ts   - the `TS` context
781316643e7SJed Brown . t    - current time
7820910c330SBarry Smith . U    - state vector
7830910c330SBarry Smith . Udot - time derivative of state vector
784bcf0153eSBarry Smith - imex - flag indicates if the method is `TSIMEX` so that the RHSFunction should be kept separate
785316643e7SJed Brown 
786316643e7SJed Brown   Output Parameter:
787316643e7SJed Brown . Y - right hand side
788316643e7SJed Brown 
789bcf0153eSBarry Smith   Level: developer
790bcf0153eSBarry Smith 
791316643e7SJed Brown   Note:
792316643e7SJed Brown   Most users should not need to explicitly call this routine, as it
793316643e7SJed Brown   is used internally within the nonlinear solvers.
794316643e7SJed Brown 
795316643e7SJed Brown   If the user did did not write their equations in implicit form, this
796316643e7SJed Brown   function recasts them in implicit form.
797316643e7SJed Brown 
7981cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetIFunction()`, `TSComputeRHSFunction()`
799316643e7SJed Brown @*/
800d71ae5a4SJacob Faibussowitsch PetscErrorCode TSComputeIFunction(TS ts, PetscReal t, Vec U, Vec Udot, Vec Y, PetscBool imex)
801d71ae5a4SJacob Faibussowitsch {
80224989b8cSPeter Brune   TSIFunction   ifunction;
80324989b8cSPeter Brune   TSRHSFunction rhsfunction;
80424989b8cSPeter Brune   void         *ctx;
80524989b8cSPeter Brune   DM            dm;
806316643e7SJed Brown 
807316643e7SJed Brown   PetscFunctionBegin;
8080700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
8090910c330SBarry Smith   PetscValidHeaderSpecific(U, VEC_CLASSID, 3);
8100910c330SBarry Smith   PetscValidHeaderSpecific(Udot, VEC_CLASSID, 4);
8110700a824SBarry Smith   PetscValidHeaderSpecific(Y, VEC_CLASSID, 5);
812316643e7SJed Brown 
8139566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
8149566063dSJacob Faibussowitsch   PetscCall(DMTSGetIFunction(dm, &ifunction, &ctx));
8159566063dSJacob Faibussowitsch   PetscCall(DMTSGetRHSFunction(dm, &rhsfunction, NULL));
81624989b8cSPeter Brune 
8173c633725SBarry Smith   PetscCheck(rhsfunction || ifunction, PetscObjectComm((PetscObject)ts), PETSC_ERR_USER, "Must call TSSetRHSFunction() and / or TSSetIFunction()");
818d90be118SSean Farley 
8199566063dSJacob Faibussowitsch   PetscCall(PetscLogEventBegin(TS_FunctionEval, ts, U, Udot, Y));
82024989b8cSPeter Brune   if (ifunction) {
821792fecdfSBarry Smith     PetscCallBack("TS callback implicit function", (*ifunction)(ts, t, U, Udot, Y, ctx));
822a6ab3590SBarry Smith     ts->ifuncs++;
823214bc6a2SJed Brown   }
824214bc6a2SJed Brown   if (imex) {
8251e66621cSBarry Smith     if (!ifunction) PetscCall(VecCopy(Udot, Y));
82624989b8cSPeter Brune   } else if (rhsfunction) {
82724989b8cSPeter Brune     if (ifunction) {
828214bc6a2SJed Brown       Vec Frhs;
8299566063dSJacob Faibussowitsch       PetscCall(TSGetRHSVec_Private(ts, &Frhs));
8309566063dSJacob Faibussowitsch       PetscCall(TSComputeRHSFunction(ts, t, U, Frhs));
8319566063dSJacob Faibussowitsch       PetscCall(VecAXPY(Y, -1, Frhs));
8322dd45cf8SJed Brown     } else {
8339566063dSJacob Faibussowitsch       PetscCall(TSComputeRHSFunction(ts, t, U, Y));
8349566063dSJacob Faibussowitsch       PetscCall(VecAYPX(Y, -1, Udot));
835316643e7SJed Brown     }
8364a6899ffSJed Brown   }
8379566063dSJacob Faibussowitsch   PetscCall(PetscLogEventEnd(TS_FunctionEval, ts, U, Udot, Y));
8383ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
839316643e7SJed Brown }
840316643e7SJed Brown 
841cfa8a9a2SHong Zhang /*
842195e9b02SBarry Smith    TSRecoverRHSJacobian - Recover the Jacobian matrix so that one can call `TSComputeRHSJacobian()` on it.
843cfa8a9a2SHong Zhang 
844cfa8a9a2SHong Zhang    Note:
845195e9b02SBarry Smith    This routine is needed when one switches from `TSComputeIJacobian()` to `TSComputeRHSJacobian()` because the Jacobian matrix may be shifted or scaled in `TSComputeIJacobian()`.
846cfa8a9a2SHong Zhang 
847cfa8a9a2SHong Zhang */
848d71ae5a4SJacob Faibussowitsch static PetscErrorCode TSRecoverRHSJacobian(TS ts, Mat A, Mat B)
849d71ae5a4SJacob Faibussowitsch {
850cfa8a9a2SHong Zhang   PetscFunctionBegin;
851cfa8a9a2SHong Zhang   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
8523c633725SBarry Smith   PetscCheck(A == ts->Arhs, PetscObjectComm((PetscObject)ts), PETSC_ERR_SUP, "Invalid Amat");
8533c633725SBarry Smith   PetscCheck(B == ts->Brhs, PetscObjectComm((PetscObject)ts), PETSC_ERR_SUP, "Invalid Bmat");
854cfa8a9a2SHong Zhang 
8551baa6e33SBarry Smith   if (ts->rhsjacobian.shift) PetscCall(MatShift(A, -ts->rhsjacobian.shift));
85648a46eb9SPierre Jolivet   if (ts->rhsjacobian.scale == -1.) PetscCall(MatScale(A, -1));
857cfa8a9a2SHong Zhang   if (B && B == ts->Brhs && A != B) {
8581baa6e33SBarry Smith     if (ts->rhsjacobian.shift) PetscCall(MatShift(B, -ts->rhsjacobian.shift));
8591e66621cSBarry Smith     if (ts->rhsjacobian.scale == -1.) PetscCall(MatScale(B, -1));
860cfa8a9a2SHong Zhang   }
861cfa8a9a2SHong Zhang   ts->rhsjacobian.shift = 0;
862cfa8a9a2SHong Zhang   ts->rhsjacobian.scale = 1.;
8633ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
864cfa8a9a2SHong Zhang }
865cfa8a9a2SHong Zhang 
866316643e7SJed Brown /*@
867316643e7SJed Brown   TSComputeIJacobian - Evaluates the Jacobian of the DAE
868316643e7SJed Brown 
869c3339decSBarry Smith   Collective
870316643e7SJed Brown 
871316643e7SJed Brown   Input Parameters:
872bcf0153eSBarry Smith + ts    - the `TS` context
873316643e7SJed Brown . t     - current timestep
8740910c330SBarry Smith . U     - state vector
8750910c330SBarry Smith . Udot  - time derivative of state vector
876214bc6a2SJed Brown . shift - shift to apply, see note below
877bcf0153eSBarry Smith - imex  - flag indicates if the method is `TSIMEX` so that the RHSJacobian should be kept separate
878316643e7SJed Brown 
879316643e7SJed Brown   Output Parameters:
880316643e7SJed Brown + A - Jacobian matrix
881195e9b02SBarry Smith - B - matrix from which the preconditioner is constructed; often the same as `A`
882316643e7SJed Brown 
883bcf0153eSBarry Smith   Level: developer
884bcf0153eSBarry Smith 
885316643e7SJed Brown   Notes:
8860910c330SBarry Smith   If F(t,U,Udot)=0 is the DAE, the required Jacobian is
887195e9b02SBarry Smith .vb
8880910c330SBarry Smith    dF/dU + shift*dF/dUdot
889195e9b02SBarry Smith .ve
890316643e7SJed Brown   Most users should not need to explicitly call this routine, as it
891316643e7SJed Brown   is used internally within the nonlinear solvers.
892316643e7SJed Brown 
8931cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetIJacobian()`
89463495f91SJed Brown @*/
895d71ae5a4SJacob Faibussowitsch PetscErrorCode TSComputeIJacobian(TS ts, PetscReal t, Vec U, Vec Udot, PetscReal shift, Mat A, Mat B, PetscBool imex)
896d71ae5a4SJacob Faibussowitsch {
89724989b8cSPeter Brune   TSIJacobian   ijacobian;
89824989b8cSPeter Brune   TSRHSJacobian rhsjacobian;
89924989b8cSPeter Brune   DM            dm;
90024989b8cSPeter Brune   void         *ctx;
901316643e7SJed Brown 
902316643e7SJed Brown   PetscFunctionBegin;
9030700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
9040910c330SBarry Smith   PetscValidHeaderSpecific(U, VEC_CLASSID, 3);
9050910c330SBarry Smith   PetscValidHeaderSpecific(Udot, VEC_CLASSID, 4);
90694ab13aaSBarry Smith   PetscValidHeaderSpecific(A, MAT_CLASSID, 6);
90794ab13aaSBarry Smith   PetscValidHeaderSpecific(B, MAT_CLASSID, 7);
90824989b8cSPeter Brune 
9099566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
9109566063dSJacob Faibussowitsch   PetscCall(DMTSGetIJacobian(dm, &ijacobian, &ctx));
9119566063dSJacob Faibussowitsch   PetscCall(DMTSGetRHSJacobian(dm, &rhsjacobian, NULL));
91224989b8cSPeter Brune 
9133c633725SBarry Smith   PetscCheck(rhsjacobian || ijacobian, PetscObjectComm((PetscObject)ts), PETSC_ERR_USER, "Must call TSSetRHSJacobian() and / or TSSetIJacobian()");
914316643e7SJed Brown 
9159566063dSJacob Faibussowitsch   PetscCall(PetscLogEventBegin(TS_JacobianEval, ts, U, A, B));
91624989b8cSPeter Brune   if (ijacobian) {
917792fecdfSBarry Smith     PetscCallBack("TS callback implicit Jacobian", (*ijacobian)(ts, t, U, Udot, shift, A, B, ctx));
918a6ab3590SBarry Smith     ts->ijacs++;
9194a6899ffSJed Brown   }
920214bc6a2SJed Brown   if (imex) {
921b5abc632SBarry Smith     if (!ijacobian) { /* system was written as Udot = G(t,U) */
9224c26be97Sstefano_zampini       PetscBool assembled;
923971015bcSStefano Zampini       if (rhsjacobian) {
924971015bcSStefano Zampini         Mat Arhs = NULL;
9259566063dSJacob Faibussowitsch         PetscCall(TSGetRHSMats_Private(ts, &Arhs, NULL));
926971015bcSStefano Zampini         if (A == Arhs) {
9273c633725SBarry 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 */
928971015bcSStefano Zampini           ts->rhsjacobian.time = PETSC_MIN_REAL;
929971015bcSStefano Zampini         }
930971015bcSStefano Zampini       }
9319566063dSJacob Faibussowitsch       PetscCall(MatZeroEntries(A));
9329566063dSJacob Faibussowitsch       PetscCall(MatAssembled(A, &assembled));
9334c26be97Sstefano_zampini       if (!assembled) {
9349566063dSJacob Faibussowitsch         PetscCall(MatAssemblyBegin(A, MAT_FINAL_ASSEMBLY));
9359566063dSJacob Faibussowitsch         PetscCall(MatAssemblyEnd(A, MAT_FINAL_ASSEMBLY));
9364c26be97Sstefano_zampini       }
9379566063dSJacob Faibussowitsch       PetscCall(MatShift(A, shift));
93894ab13aaSBarry Smith       if (A != B) {
9399566063dSJacob Faibussowitsch         PetscCall(MatZeroEntries(B));
9409566063dSJacob Faibussowitsch         PetscCall(MatAssembled(B, &assembled));
9414c26be97Sstefano_zampini         if (!assembled) {
9429566063dSJacob Faibussowitsch           PetscCall(MatAssemblyBegin(B, MAT_FINAL_ASSEMBLY));
9439566063dSJacob Faibussowitsch           PetscCall(MatAssemblyEnd(B, MAT_FINAL_ASSEMBLY));
9444c26be97Sstefano_zampini         }
9459566063dSJacob Faibussowitsch         PetscCall(MatShift(B, shift));
946214bc6a2SJed Brown       }
947214bc6a2SJed Brown     }
948214bc6a2SJed Brown   } else {
949e1244c69SJed Brown     Mat Arhs = NULL, Brhs = NULL;
9501e66621cSBarry Smith 
9511e66621cSBarry Smith     /* RHSJacobian needs to be converted to part of IJacobian if exists */
9521e66621cSBarry Smith     if (rhsjacobian) PetscCall(TSGetRHSMats_Private(ts, &Arhs, &Brhs));
953e8b1e424SHong Zhang     if (Arhs == A) { /* No IJacobian matrix, so we only have the RHS matrix */
954e8b1e424SHong Zhang       PetscObjectState Ustate;
955e8b1e424SHong Zhang       PetscObjectId    Uid;
956e8b1e424SHong Zhang       TSRHSFunction    rhsfunction;
957e8b1e424SHong Zhang 
9589566063dSJacob Faibussowitsch       PetscCall(DMTSGetRHSFunction(dm, &rhsfunction, NULL));
9599566063dSJacob Faibussowitsch       PetscCall(PetscObjectStateGet((PetscObject)U, &Ustate));
9609566063dSJacob Faibussowitsch       PetscCall(PetscObjectGetId((PetscObject)U, &Uid));
9619371c9d4SSatish Balay       if ((rhsjacobian == TSComputeRHSJacobianConstant || (ts->rhsjacobian.time == t && (ts->problem_type == TS_LINEAR || (ts->rhsjacobian.Xid == Uid && ts->rhsjacobian.Xstate == Ustate)) && rhsfunction != TSComputeRHSFunctionLinear)) &&
9629371c9d4SSatish Balay           ts->rhsjacobian.scale == -1.) {                      /* No need to recompute RHSJacobian */
9639566063dSJacob Faibussowitsch         PetscCall(MatShift(A, shift - ts->rhsjacobian.shift)); /* revert the old shift and add the new shift with a single call to MatShift */
9641e66621cSBarry Smith         if (A != B) PetscCall(MatShift(B, shift - ts->rhsjacobian.shift));
965e8b1e424SHong Zhang       } else {
9663565c898SBarry Smith         PetscBool flg;
967e8b1e424SHong Zhang 
968e8b1e424SHong Zhang         if (ts->rhsjacobian.reuse) { /* Undo the damage */
969e8b1e424SHong Zhang           /* MatScale has a short path for this case.
970e8b1e424SHong Zhang              However, this code path is taken the first time TSComputeRHSJacobian is called
971e8b1e424SHong Zhang              and the matrices have not been assembled yet */
9729566063dSJacob Faibussowitsch           PetscCall(TSRecoverRHSJacobian(ts, A, B));
973e8b1e424SHong Zhang         }
9749566063dSJacob Faibussowitsch         PetscCall(TSComputeRHSJacobian(ts, t, U, A, B));
9759566063dSJacob Faibussowitsch         PetscCall(SNESGetUseMatrixFree(ts->snes, NULL, &flg));
9763565c898SBarry Smith         /* since -snes_mf_operator uses the full SNES function it does not need to be shifted or scaled here */
9773565c898SBarry Smith         if (!flg) {
9789566063dSJacob Faibussowitsch           PetscCall(MatScale(A, -1));
9799566063dSJacob Faibussowitsch           PetscCall(MatShift(A, shift));
9803565c898SBarry Smith         }
98194ab13aaSBarry Smith         if (A != B) {
9829566063dSJacob Faibussowitsch           PetscCall(MatScale(B, -1));
9839566063dSJacob Faibussowitsch           PetscCall(MatShift(B, shift));
984316643e7SJed Brown         }
985e8b1e424SHong Zhang       }
986e8b1e424SHong Zhang       ts->rhsjacobian.scale = -1;
987e8b1e424SHong Zhang       ts->rhsjacobian.shift = shift;
988d60b7d5cSBarry Smith     } else if (Arhs) {  /* Both IJacobian and RHSJacobian */
989e1244c69SJed Brown       if (!ijacobian) { /* No IJacobian provided, but we have a separate RHS matrix */
9909566063dSJacob Faibussowitsch         PetscCall(MatZeroEntries(A));
9919566063dSJacob Faibussowitsch         PetscCall(MatShift(A, shift));
99294ab13aaSBarry Smith         if (A != B) {
9939566063dSJacob Faibussowitsch           PetscCall(MatZeroEntries(B));
9949566063dSJacob Faibussowitsch           PetscCall(MatShift(B, shift));
995214bc6a2SJed Brown         }
996316643e7SJed Brown       }
9979566063dSJacob Faibussowitsch       PetscCall(TSComputeRHSJacobian(ts, t, U, Arhs, Brhs));
9989566063dSJacob Faibussowitsch       PetscCall(MatAXPY(A, -1, Arhs, ts->axpy_pattern));
9991e66621cSBarry Smith       if (A != B) PetscCall(MatAXPY(B, -1, Brhs, ts->axpy_pattern));
1000316643e7SJed Brown     }
1001316643e7SJed Brown   }
10029566063dSJacob Faibussowitsch   PetscCall(PetscLogEventEnd(TS_JacobianEval, ts, U, A, B));
10033ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1004316643e7SJed Brown }
1005316643e7SJed Brown 
1006d763cef2SBarry Smith /*@C
1007d763cef2SBarry Smith   TSSetRHSFunction - Sets the routine for evaluating the function,
1008b5abc632SBarry Smith   where U_t = G(t,u).
1009d763cef2SBarry Smith 
1010c3339decSBarry Smith   Logically Collective
1011d763cef2SBarry Smith 
1012d763cef2SBarry Smith   Input Parameters:
1013bcf0153eSBarry Smith + ts  - the `TS` context obtained from `TSCreate()`
1014195e9b02SBarry Smith . r   - vector to put the computed right hand side (or `NULL` to have it created)
1015d763cef2SBarry Smith . f   - routine for evaluating the right-hand-side function
1016195e9b02SBarry Smith - ctx - [optional] user-defined context for private data for the function evaluation routine (may be `NULL`)
1017d763cef2SBarry Smith 
1018d763cef2SBarry Smith   Level: beginner
1019d763cef2SBarry Smith 
1020bcf0153eSBarry Smith   Note:
1021bcf0153eSBarry Smith   You must call this function or `TSSetIFunction()` to define your ODE. You cannot use this function when solving a DAE.
10222bbac0d3SBarry Smith 
102314d0ab18SJacob Faibussowitsch .seealso: [](ch_ts), `TS`, `TSRHSFunction`, `TSSetRHSJacobian()`, `TSSetIJacobian()`, `TSSetIFunction()`
1024d763cef2SBarry Smith @*/
102514d0ab18SJacob Faibussowitsch PetscErrorCode TSSetRHSFunction(TS ts, Vec r, TSRHSFunction f, void *ctx)
1026d71ae5a4SJacob Faibussowitsch {
1027089b2837SJed Brown   SNES snes;
10280298fd71SBarry Smith   Vec  ralloc = NULL;
102924989b8cSPeter Brune   DM   dm;
1030d763cef2SBarry Smith 
1031089b2837SJed Brown   PetscFunctionBegin;
10320700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
1033ca94891dSJed Brown   if (r) PetscValidHeaderSpecific(r, VEC_CLASSID, 2);
103424989b8cSPeter Brune 
10359566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
10369566063dSJacob Faibussowitsch   PetscCall(DMTSSetRHSFunction(dm, f, ctx));
10379566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts, &snes));
1038e856ceecSJed Brown   if (!r && !ts->dm && ts->vec_sol) {
10399566063dSJacob Faibussowitsch     PetscCall(VecDuplicate(ts->vec_sol, &ralloc));
1040e856ceecSJed Brown     r = ralloc;
1041e856ceecSJed Brown   }
10429566063dSJacob Faibussowitsch   PetscCall(SNESSetFunction(snes, r, SNESTSFormFunction, ts));
10439566063dSJacob Faibussowitsch   PetscCall(VecDestroy(&ralloc));
10443ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1045d763cef2SBarry Smith }
1046d763cef2SBarry Smith 
1047ef20d060SBarry Smith /*@C
1048abd5a294SJed Brown   TSSetSolutionFunction - Provide a function that computes the solution of the ODE or DAE
1049ef20d060SBarry Smith 
1050c3339decSBarry Smith   Logically Collective
1051ef20d060SBarry Smith 
1052ef20d060SBarry Smith   Input Parameters:
1053bcf0153eSBarry Smith + ts  - the `TS` context obtained from `TSCreate()`
1054ef20d060SBarry Smith . f   - routine for evaluating the solution
1055ef20d060SBarry Smith - ctx - [optional] user-defined context for private data for the
1056195e9b02SBarry Smith           function evaluation routine (may be `NULL`)
1057ef20d060SBarry Smith 
1058bcf0153eSBarry Smith   Options Database Keys:
1059bcf0153eSBarry Smith + -ts_monitor_lg_error   - create a graphical monitor of error history, requires user to have provided `TSSetSolutionFunction()`
1060bcf0153eSBarry Smith - -ts_monitor_draw_error - Monitor error graphically, requires user to have provided `TSSetSolutionFunction()`
1061bcf0153eSBarry Smith 
1062bcf0153eSBarry Smith   Level: intermediate
10630ed3bfb6SBarry Smith 
1064abd5a294SJed Brown   Notes:
1065abd5a294SJed Brown   This routine is used for testing accuracy of time integration schemes when you already know the solution.
1066abd5a294SJed Brown   If analytic solutions are not known for your system, consider using the Method of Manufactured Solutions to
1067abd5a294SJed Brown   create closed-form solutions with non-physical forcing terms.
1068abd5a294SJed Brown 
1069bcf0153eSBarry Smith   For low-dimensional problems solved in serial, such as small discrete systems, `TSMonitorLGError()` can be used to monitor the error history.
1070abd5a294SJed Brown 
107114d0ab18SJacob Faibussowitsch .seealso: [](ch_ts), `TS`, `TSSolutionFunction`, `TSSetRHSJacobian()`, `TSSetIJacobian()`, `TSComputeSolutionFunction()`, `TSSetForcingFunction()`, `TSSetSolution()`, `TSGetSolution()`, `TSMonitorLGError()`, `TSMonitorDrawError()`
1072ef20d060SBarry Smith @*/
107314d0ab18SJacob Faibussowitsch PetscErrorCode TSSetSolutionFunction(TS ts, TSSolutionFunction f, void *ctx)
1074d71ae5a4SJacob Faibussowitsch {
1075ef20d060SBarry Smith   DM dm;
1076ef20d060SBarry Smith 
1077ef20d060SBarry Smith   PetscFunctionBegin;
1078ef20d060SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
10799566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
10809566063dSJacob Faibussowitsch   PetscCall(DMTSSetSolutionFunction(dm, f, ctx));
10813ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1082ef20d060SBarry Smith }
1083ef20d060SBarry Smith 
10849b7cd975SBarry Smith /*@C
10859b7cd975SBarry Smith   TSSetForcingFunction - Provide a function that computes a forcing term for a ODE or PDE
10869b7cd975SBarry Smith 
1087c3339decSBarry Smith   Logically Collective
10889b7cd975SBarry Smith 
10899b7cd975SBarry Smith   Input Parameters:
1090bcf0153eSBarry Smith + ts   - the `TS` context obtained from `TSCreate()`
1091e162b725SBarry Smith . func - routine for evaluating the forcing function
109214d0ab18SJacob Faibussowitsch - ctx  - [optional] user-defined context for private data for the function evaluation routine
109314d0ab18SJacob Faibussowitsch          (may be `NULL`)
10949b7cd975SBarry Smith 
1095bcf0153eSBarry Smith   Level: intermediate
1096bcf0153eSBarry Smith 
10979b7cd975SBarry Smith   Notes:
10989b7cd975SBarry Smith   This routine is useful for testing accuracy of time integration schemes when using the Method of Manufactured Solutions to
1099e162b725SBarry 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
1100e162b725SBarry Smith   definition of the problem you are solving and hence possibly introducing bugs.
1101e162b725SBarry Smith 
11028847d985SBarry Smith   This replaces the ODE F(u,u_t,t) = 0 the `TS` is solving with F(u,u_t,t) - func(t) = 0
1103e162b725SBarry Smith 
1104e162b725SBarry 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
1105e162b725SBarry Smith   parameters can be passed in the ctx variable.
11069b7cd975SBarry Smith 
1107bcf0153eSBarry Smith   For low-dimensional problems solved in serial, such as small discrete systems, `TSMonitorLGError()` can be used to monitor the error history.
11089b7cd975SBarry Smith 
110914d0ab18SJacob Faibussowitsch .seealso: [](ch_ts), `TS`, `TSForcingFunction`, `TSSetRHSJacobian()`, `TSSetIJacobian()`,
111014d0ab18SJacob Faibussowitsch `TSComputeSolutionFunction()`, `TSSetSolutionFunction()`
11119b7cd975SBarry Smith @*/
1112d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetForcingFunction(TS ts, TSForcingFunction func, void *ctx)
1113d71ae5a4SJacob Faibussowitsch {
11149b7cd975SBarry Smith   DM dm;
11159b7cd975SBarry Smith 
11169b7cd975SBarry Smith   PetscFunctionBegin;
11179b7cd975SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
11189566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
11199566063dSJacob Faibussowitsch   PetscCall(DMTSSetForcingFunction(dm, func, ctx));
11203ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
11219b7cd975SBarry Smith }
11229b7cd975SBarry Smith 
1123d763cef2SBarry Smith /*@C
1124f7ab8db6SBarry Smith   TSSetRHSJacobian - Sets the function to compute the Jacobian of G,
1125b5abc632SBarry Smith   where U_t = G(U,t), as well as the location to store the matrix.
1126d763cef2SBarry Smith 
1127c3339decSBarry Smith   Logically Collective
1128d763cef2SBarry Smith 
1129d763cef2SBarry Smith   Input Parameters:
1130bcf0153eSBarry Smith + ts   - the `TS` context obtained from `TSCreate()`
1131195e9b02SBarry Smith . Amat - (approximate) location to store Jacobian matrix entries computed by `f`
1132195e9b02SBarry Smith . Pmat - matrix from which preconditioner is to be constructed (usually the same as `Amat`)
1133d763cef2SBarry Smith . f    - the Jacobian evaluation routine
1134195e9b02SBarry Smith - ctx  - [optional] user-defined context for private data for the Jacobian evaluation routine (may be `NULL`)
1135d763cef2SBarry Smith 
1136bcf0153eSBarry Smith   Level: beginner
1137bcf0153eSBarry Smith 
11386cd88445SBarry Smith   Notes:
11396cd88445SBarry Smith   You must set all the diagonal entries of the matrices, if they are zero you must still set them with a zero value
11406cd88445SBarry Smith 
114114d0ab18SJacob Faibussowitsch   The `TS` solver may modify the nonzero structure and the entries of the matrices `Amat` and `Pmat` between the calls to `f()`
1142ca5f011dSBarry Smith   You should not assume the values are the same in the next call to f() as you set them in the previous call.
1143d763cef2SBarry Smith 
114414d0ab18SJacob Faibussowitsch .seealso: [](ch_ts), `TS`, `TSRHSJacobian`, `SNESComputeJacobianDefaultColor()`,
114514d0ab18SJacob Faibussowitsch `TSSetRHSFunction()`, `TSRHSJacobianSetReuse()`, `TSSetIJacobian()`, `TSRHSFunction()`, `TSIFunction()`
1146d763cef2SBarry Smith @*/
1147d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetRHSJacobian(TS ts, Mat Amat, Mat Pmat, TSRHSJacobian f, void *ctx)
1148d71ae5a4SJacob Faibussowitsch {
1149089b2837SJed Brown   SNES        snes;
115024989b8cSPeter Brune   DM          dm;
115124989b8cSPeter Brune   TSIJacobian ijacobian;
1152277b19d0SLisandro Dalcin 
1153d763cef2SBarry Smith   PetscFunctionBegin;
11540700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
1155e5d3d808SBarry Smith   if (Amat) PetscValidHeaderSpecific(Amat, MAT_CLASSID, 2);
1156e5d3d808SBarry Smith   if (Pmat) PetscValidHeaderSpecific(Pmat, MAT_CLASSID, 3);
1157e5d3d808SBarry Smith   if (Amat) PetscCheckSameComm(ts, 1, Amat, 2);
1158e5d3d808SBarry Smith   if (Pmat) PetscCheckSameComm(ts, 1, Pmat, 3);
1159d763cef2SBarry Smith 
11609566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
11619566063dSJacob Faibussowitsch   PetscCall(DMTSSetRHSJacobian(dm, f, ctx));
11629566063dSJacob Faibussowitsch   PetscCall(DMTSGetIJacobian(dm, &ijacobian, NULL));
11639566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts, &snes));
11641e66621cSBarry Smith   if (!ijacobian) PetscCall(SNESSetJacobian(snes, Amat, Pmat, SNESTSFormJacobian, ts));
1165e5d3d808SBarry Smith   if (Amat) {
11669566063dSJacob Faibussowitsch     PetscCall(PetscObjectReference((PetscObject)Amat));
11679566063dSJacob Faibussowitsch     PetscCall(MatDestroy(&ts->Arhs));
1168e5d3d808SBarry Smith     ts->Arhs = Amat;
11690e4ef248SJed Brown   }
1170e5d3d808SBarry Smith   if (Pmat) {
11719566063dSJacob Faibussowitsch     PetscCall(PetscObjectReference((PetscObject)Pmat));
11729566063dSJacob Faibussowitsch     PetscCall(MatDestroy(&ts->Brhs));
1173e5d3d808SBarry Smith     ts->Brhs = Pmat;
11740e4ef248SJed Brown   }
11753ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1176d763cef2SBarry Smith }
1177d763cef2SBarry Smith 
1178316643e7SJed Brown /*@C
1179b5abc632SBarry Smith   TSSetIFunction - Set the function to compute F(t,U,U_t) where F() = 0 is the DAE to be solved.
1180316643e7SJed Brown 
1181c3339decSBarry Smith   Logically Collective
1182316643e7SJed Brown 
1183316643e7SJed Brown   Input Parameters:
1184bcf0153eSBarry Smith + ts  - the `TS` context obtained from `TSCreate()`
1185195e9b02SBarry Smith . r   - vector to hold the residual (or `NULL` to have it created internally)
1186316643e7SJed Brown . f   - the function evaluation routine
1187195e9b02SBarry Smith - ctx - user-defined context for private data for the function evaluation routine (may be `NULL`)
1188316643e7SJed Brown 
1189316643e7SJed Brown   Level: beginner
1190316643e7SJed Brown 
1191bcf0153eSBarry Smith   Note:
1192bcf0153eSBarry Smith   The user MUST call either this routine or `TSSetRHSFunction()` to define the ODE.  When solving DAEs you must use this function.
1193bcf0153eSBarry Smith 
119414d0ab18SJacob Faibussowitsch .seealso: [](ch_ts), `TS`, `TSIFunction`, `TSSetRHSJacobian()`, `TSSetRHSFunction()`,
119514d0ab18SJacob Faibussowitsch `TSSetIJacobian()`
1196316643e7SJed Brown @*/
1197d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetIFunction(TS ts, Vec r, TSIFunction f, void *ctx)
1198d71ae5a4SJacob Faibussowitsch {
1199089b2837SJed Brown   SNES snes;
120051699248SLisandro Dalcin   Vec  ralloc = NULL;
120124989b8cSPeter Brune   DM   dm;
1202316643e7SJed Brown 
1203316643e7SJed Brown   PetscFunctionBegin;
12040700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
120551699248SLisandro Dalcin   if (r) PetscValidHeaderSpecific(r, VEC_CLASSID, 2);
120624989b8cSPeter Brune 
12079566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
12089566063dSJacob Faibussowitsch   PetscCall(DMTSSetIFunction(dm, f, ctx));
120924989b8cSPeter Brune 
12109566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts, &snes));
121151699248SLisandro Dalcin   if (!r && !ts->dm && ts->vec_sol) {
12129566063dSJacob Faibussowitsch     PetscCall(VecDuplicate(ts->vec_sol, &ralloc));
121351699248SLisandro Dalcin     r = ralloc;
1214e856ceecSJed Brown   }
12159566063dSJacob Faibussowitsch   PetscCall(SNESSetFunction(snes, r, SNESTSFormFunction, ts));
12169566063dSJacob Faibussowitsch   PetscCall(VecDestroy(&ralloc));
12173ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1218089b2837SJed Brown }
1219089b2837SJed Brown 
1220089b2837SJed Brown /*@C
1221a5b23f4aSJose E. Roman   TSGetIFunction - Returns the vector where the implicit residual is stored and the function/context to compute it.
1222089b2837SJed Brown 
1223089b2837SJed Brown   Not Collective
1224089b2837SJed Brown 
1225089b2837SJed Brown   Input Parameter:
1226bcf0153eSBarry Smith . ts - the `TS` context
1227089b2837SJed Brown 
1228d8d19677SJose E. Roman   Output Parameters:
1229195e9b02SBarry Smith + r    - vector to hold residual (or `NULL`)
1230195e9b02SBarry Smith . func - the function to compute residual (or `NULL`)
1231195e9b02SBarry Smith - ctx  - the function context (or `NULL`)
1232089b2837SJed Brown 
1233089b2837SJed Brown   Level: advanced
1234089b2837SJed Brown 
12351cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetIFunction()`, `SNESGetFunction()`
1236089b2837SJed Brown @*/
1237d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetIFunction(TS ts, Vec *r, TSIFunction *func, void **ctx)
1238d71ae5a4SJacob Faibussowitsch {
1239089b2837SJed Brown   SNES snes;
124024989b8cSPeter Brune   DM   dm;
1241089b2837SJed Brown 
1242089b2837SJed Brown   PetscFunctionBegin;
1243089b2837SJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
12449566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts, &snes));
12459566063dSJacob Faibussowitsch   PetscCall(SNESGetFunction(snes, r, NULL, NULL));
12469566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
12479566063dSJacob Faibussowitsch   PetscCall(DMTSGetIFunction(dm, func, ctx));
12483ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1249089b2837SJed Brown }
1250089b2837SJed Brown 
1251089b2837SJed Brown /*@C
1252089b2837SJed Brown   TSGetRHSFunction - Returns the vector where the right hand side is stored and the function/context to compute it.
1253089b2837SJed Brown 
1254089b2837SJed Brown   Not Collective
1255089b2837SJed Brown 
1256089b2837SJed Brown   Input Parameter:
1257bcf0153eSBarry Smith . ts - the `TS` context
1258089b2837SJed Brown 
1259d8d19677SJose E. Roman   Output Parameters:
1260195e9b02SBarry Smith + r    - vector to hold computed right hand side (or `NULL`)
1261195e9b02SBarry Smith . func - the function to compute right hand side (or `NULL`)
1262195e9b02SBarry Smith - ctx  - the function context (or `NULL`)
1263089b2837SJed Brown 
1264089b2837SJed Brown   Level: advanced
1265089b2837SJed Brown 
12661cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetRHSFunction()`, `SNESGetFunction()`
1267089b2837SJed Brown @*/
1268d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetRHSFunction(TS ts, Vec *r, TSRHSFunction *func, void **ctx)
1269d71ae5a4SJacob Faibussowitsch {
1270089b2837SJed Brown   SNES snes;
127124989b8cSPeter Brune   DM   dm;
1272089b2837SJed Brown 
1273089b2837SJed Brown   PetscFunctionBegin;
1274089b2837SJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
12759566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts, &snes));
12769566063dSJacob Faibussowitsch   PetscCall(SNESGetFunction(snes, r, NULL, NULL));
12779566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
12789566063dSJacob Faibussowitsch   PetscCall(DMTSGetRHSFunction(dm, func, ctx));
12793ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1280316643e7SJed Brown }
1281316643e7SJed Brown 
1282316643e7SJed Brown /*@C
1283a4f0a591SBarry Smith   TSSetIJacobian - Set the function to compute the matrix dF/dU + a*dF/dU_t where F(t,U,U_t) is the function
1284bcf0153eSBarry Smith   provided with `TSSetIFunction()`.
1285316643e7SJed Brown 
1286c3339decSBarry Smith   Logically Collective
1287316643e7SJed Brown 
1288316643e7SJed Brown   Input Parameters:
1289bcf0153eSBarry Smith + ts   - the `TS` context obtained from `TSCreate()`
1290aaa8cc7dSPierre Jolivet . Amat - (approximate) matrix to store Jacobian entries computed by `f`
1291195e9b02SBarry Smith . Pmat - matrix used to compute preconditioner (usually the same as `Amat`)
1292316643e7SJed Brown . f    - the Jacobian evaluation routine
1293195e9b02SBarry Smith - ctx  - user-defined context for private data for the Jacobian evaluation routine (may be `NULL`)
1294316643e7SJed Brown 
1295bcf0153eSBarry Smith   Level: beginner
1296316643e7SJed Brown 
1297bcf0153eSBarry Smith   Notes:
1298195e9b02SBarry Smith   The matrices `Amat` and `Pmat` are exactly the matrices that are used by `SNES` for the nonlinear solve.
1299bcf0153eSBarry Smith 
1300bcf0153eSBarry Smith   If you know the operator Amat has a null space you can use `MatSetNullSpace()` and `MatSetTransposeNullSpace()` to supply the null
1301195e9b02SBarry Smith   space to `Amat` and the `KSP` solvers will automatically use that null space as needed during the solution process.
1302895c21f2SBarry Smith 
1303a4f0a591SBarry Smith   The matrix dF/dU + a*dF/dU_t you provide turns out to be
1304b5abc632SBarry Smith   the Jacobian of F(t,U,W+a*U) where F(t,U,U_t) = 0 is the DAE to be solved.
1305a4f0a591SBarry Smith   The time integrator internally approximates U_t by W+a*U where the positive "shift"
1306a4f0a591SBarry Smith   a and vector W depend on the integration method, step size, and past states. For example with
1307a4f0a591SBarry Smith   the backward Euler method a = 1/dt and W = -a*U(previous timestep) so
1308a4f0a591SBarry Smith   W + a*U = a*(U - U(previous timestep)) = (U - U(previous timestep))/dt
1309a4f0a591SBarry Smith 
13106cd88445SBarry Smith   You must set all the diagonal entries of the matrices, if they are zero you must still set them with a zero value
13116cd88445SBarry Smith 
1312195e9b02SBarry Smith   The TS solver may modify the nonzero structure and the entries of the matrices `Amat` and `Pmat` between the calls to `f`
1313195e9b02SBarry Smith   You should not assume the values are the same in the next call to `f` as you set them in the previous call.
1314ca5f011dSBarry Smith 
131514d0ab18SJacob Faibussowitsch .seealso: [](ch_ts), `TS`, `TSIJacobian`, `TSSetIFunction()`, `TSSetRHSJacobian()`,
131614d0ab18SJacob Faibussowitsch `SNESComputeJacobianDefaultColor()`, `SNESComputeJacobianDefault()`, `TSSetRHSFunction()`
1317316643e7SJed Brown @*/
1318d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetIJacobian(TS ts, Mat Amat, Mat Pmat, TSIJacobian f, void *ctx)
1319d71ae5a4SJacob Faibussowitsch {
1320089b2837SJed Brown   SNES snes;
132124989b8cSPeter Brune   DM   dm;
1322316643e7SJed Brown 
1323316643e7SJed Brown   PetscFunctionBegin;
13240700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
1325e5d3d808SBarry Smith   if (Amat) PetscValidHeaderSpecific(Amat, MAT_CLASSID, 2);
1326e5d3d808SBarry Smith   if (Pmat) PetscValidHeaderSpecific(Pmat, MAT_CLASSID, 3);
1327e5d3d808SBarry Smith   if (Amat) PetscCheckSameComm(ts, 1, Amat, 2);
1328e5d3d808SBarry Smith   if (Pmat) PetscCheckSameComm(ts, 1, Pmat, 3);
132924989b8cSPeter Brune 
13309566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
13319566063dSJacob Faibussowitsch   PetscCall(DMTSSetIJacobian(dm, f, ctx));
133224989b8cSPeter Brune 
13339566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts, &snes));
13349566063dSJacob Faibussowitsch   PetscCall(SNESSetJacobian(snes, Amat, Pmat, SNESTSFormJacobian, ts));
13353ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1336316643e7SJed Brown }
1337316643e7SJed Brown 
1338e1244c69SJed Brown /*@
133914d0ab18SJacob Faibussowitsch   TSRHSJacobianSetReuse - restore the RHS Jacobian before calling the user-provided `TSRHSJacobian()` function again
1340e1244c69SJed Brown 
1341e1244c69SJed Brown   Logically Collective
1342e1244c69SJed Brown 
13434165533cSJose E. Roman   Input Parameters:
1344bcf0153eSBarry Smith + ts    - `TS` context obtained from `TSCreate()`
1345bcf0153eSBarry Smith - reuse - `PETSC_TRUE` if the RHS Jacobian
1346e1244c69SJed Brown 
1347e1244c69SJed Brown   Level: intermediate
1348e1244c69SJed Brown 
134914d0ab18SJacob Faibussowitsch   Notes:
135014d0ab18SJacob Faibussowitsch   Without this flag, `TS` will change the sign and shift the RHS Jacobian for a
135114d0ab18SJacob Faibussowitsch   finite-time-step implicit solve, in which case the user function will need to recompute the
135214d0ab18SJacob Faibussowitsch   entire Jacobian.  The `reuse `flag must be set if the evaluation function assumes that the
135314d0ab18SJacob Faibussowitsch   matrix entries have not been changed by the `TS`.
135414d0ab18SJacob Faibussowitsch 
13551cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetRHSJacobian()`, `TSComputeRHSJacobianConstant()`
1356e1244c69SJed Brown @*/
1357d71ae5a4SJacob Faibussowitsch PetscErrorCode TSRHSJacobianSetReuse(TS ts, PetscBool reuse)
1358d71ae5a4SJacob Faibussowitsch {
1359e1244c69SJed Brown   PetscFunctionBegin;
1360e1244c69SJed Brown   ts->rhsjacobian.reuse = reuse;
13613ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1362e1244c69SJed Brown }
1363e1244c69SJed Brown 
1364efe9872eSLisandro Dalcin /*@C
1365efe9872eSLisandro Dalcin   TSSetI2Function - Set the function to compute F(t,U,U_t,U_tt) where F = 0 is the DAE to be solved.
1366efe9872eSLisandro Dalcin 
1367c3339decSBarry Smith   Logically Collective
1368efe9872eSLisandro Dalcin 
1369efe9872eSLisandro Dalcin   Input Parameters:
1370bcf0153eSBarry Smith + ts  - the `TS` context obtained from `TSCreate()`
1371195e9b02SBarry Smith . F   - vector to hold the residual (or `NULL` to have it created internally)
1372efe9872eSLisandro Dalcin . fun - the function evaluation routine
1373195e9b02SBarry Smith - ctx - user-defined context for private data for the function evaluation routine (may be `NULL`)
1374efe9872eSLisandro Dalcin 
1375efe9872eSLisandro Dalcin   Level: beginner
1376efe9872eSLisandro Dalcin 
137714d0ab18SJacob Faibussowitsch .seealso: [](ch_ts), `TS`, `TSI2Function`, `TSSetI2Jacobian()`, `TSSetIFunction()`,
137814d0ab18SJacob Faibussowitsch `TSCreate()`, `TSSetRHSFunction()`
1379efe9872eSLisandro Dalcin @*/
1380d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetI2Function(TS ts, Vec F, TSI2Function fun, void *ctx)
1381d71ae5a4SJacob Faibussowitsch {
1382efe9872eSLisandro Dalcin   DM dm;
1383efe9872eSLisandro Dalcin 
1384efe9872eSLisandro Dalcin   PetscFunctionBegin;
1385efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
1386efe9872eSLisandro Dalcin   if (F) PetscValidHeaderSpecific(F, VEC_CLASSID, 2);
13879566063dSJacob Faibussowitsch   PetscCall(TSSetIFunction(ts, F, NULL, NULL));
13889566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
13899566063dSJacob Faibussowitsch   PetscCall(DMTSSetI2Function(dm, fun, ctx));
13903ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1391efe9872eSLisandro Dalcin }
1392efe9872eSLisandro Dalcin 
1393efe9872eSLisandro Dalcin /*@C
1394a5b23f4aSJose E. Roman   TSGetI2Function - Returns the vector where the implicit residual is stored and the function/context to compute it.
1395efe9872eSLisandro Dalcin 
1396efe9872eSLisandro Dalcin   Not Collective
1397efe9872eSLisandro Dalcin 
1398efe9872eSLisandro Dalcin   Input Parameter:
1399bcf0153eSBarry Smith . ts - the `TS` context
1400efe9872eSLisandro Dalcin 
1401d8d19677SJose E. Roman   Output Parameters:
1402195e9b02SBarry Smith + r   - vector to hold residual (or `NULL`)
1403195e9b02SBarry Smith . fun - the function to compute residual (or `NULL`)
1404195e9b02SBarry Smith - ctx - the function context (or `NULL`)
1405efe9872eSLisandro Dalcin 
1406efe9872eSLisandro Dalcin   Level: advanced
1407efe9872eSLisandro Dalcin 
14081cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetIFunction()`, `SNESGetFunction()`, `TSCreate()`
1409efe9872eSLisandro Dalcin @*/
1410d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetI2Function(TS ts, Vec *r, TSI2Function *fun, void **ctx)
1411d71ae5a4SJacob Faibussowitsch {
1412efe9872eSLisandro Dalcin   SNES snes;
1413efe9872eSLisandro Dalcin   DM   dm;
1414efe9872eSLisandro Dalcin 
1415efe9872eSLisandro Dalcin   PetscFunctionBegin;
1416efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
14179566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts, &snes));
14189566063dSJacob Faibussowitsch   PetscCall(SNESGetFunction(snes, r, NULL, NULL));
14199566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
14209566063dSJacob Faibussowitsch   PetscCall(DMTSGetI2Function(dm, fun, ctx));
14213ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1422efe9872eSLisandro Dalcin }
1423efe9872eSLisandro Dalcin 
1424efe9872eSLisandro Dalcin /*@C
1425bc77d74cSLisandro Dalcin   TSSetI2Jacobian - Set the function to compute the matrix dF/dU + v*dF/dU_t  + a*dF/dU_tt
1426bcf0153eSBarry Smith   where F(t,U,U_t,U_tt) is the function you provided with `TSSetI2Function()`.
1427efe9872eSLisandro Dalcin 
1428c3339decSBarry Smith   Logically Collective
1429efe9872eSLisandro Dalcin 
1430efe9872eSLisandro Dalcin   Input Parameters:
1431bcf0153eSBarry Smith + ts  - the `TS` context obtained from `TSCreate()`
1432195e9b02SBarry Smith . J   - matrix to hold the Jacobian values
1433195e9b02SBarry Smith . P   - matrix for constructing the preconditioner (may be same as `J`)
1434efe9872eSLisandro Dalcin . jac - the Jacobian evaluation routine
1435195e9b02SBarry Smith - ctx - user-defined context for private data for the Jacobian evaluation routine (may be `NULL`)
1436efe9872eSLisandro Dalcin 
1437bcf0153eSBarry Smith   Level: beginner
1438bcf0153eSBarry Smith 
1439efe9872eSLisandro Dalcin   Notes:
1440195e9b02SBarry Smith   The matrices `J` and `P` are exactly the matrices that are used by `SNES` for the nonlinear solve.
1441efe9872eSLisandro Dalcin 
1442efe9872eSLisandro Dalcin   The matrix dF/dU + v*dF/dU_t + a*dF/dU_tt you provide turns out to be
1443efe9872eSLisandro 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.
1444efe9872eSLisandro Dalcin   The time integrator internally approximates U_t by W+v*U and U_tt by W'+a*U  where the positive "shift"
1445bc77d74cSLisandro Dalcin   parameters 'v' and 'a' and vectors W, W' depend on the integration method, step size, and past states.
1446efe9872eSLisandro Dalcin 
144714d0ab18SJacob Faibussowitsch .seealso: [](ch_ts), `TS`, `TSI2Jacobian`, `TSSetI2Function()`, `TSGetI2Jacobian()`
1448efe9872eSLisandro Dalcin @*/
1449d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetI2Jacobian(TS ts, Mat J, Mat P, TSI2Jacobian jac, void *ctx)
1450d71ae5a4SJacob Faibussowitsch {
1451efe9872eSLisandro Dalcin   DM dm;
1452efe9872eSLisandro Dalcin 
1453efe9872eSLisandro Dalcin   PetscFunctionBegin;
1454efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
1455efe9872eSLisandro Dalcin   if (J) PetscValidHeaderSpecific(J, MAT_CLASSID, 2);
1456efe9872eSLisandro Dalcin   if (P) PetscValidHeaderSpecific(P, MAT_CLASSID, 3);
14579566063dSJacob Faibussowitsch   PetscCall(TSSetIJacobian(ts, J, P, NULL, NULL));
14589566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
14599566063dSJacob Faibussowitsch   PetscCall(DMTSSetI2Jacobian(dm, jac, ctx));
14603ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1461efe9872eSLisandro Dalcin }
1462efe9872eSLisandro Dalcin 
1463efe9872eSLisandro Dalcin /*@C
1464efe9872eSLisandro Dalcin   TSGetI2Jacobian - Returns the implicit Jacobian at the present timestep.
1465efe9872eSLisandro Dalcin 
1466bcf0153eSBarry Smith   Not Collective, but parallel objects are returned if `TS` is parallel
1467efe9872eSLisandro Dalcin 
1468efe9872eSLisandro Dalcin   Input Parameter:
1469bcf0153eSBarry Smith . ts - The `TS` context obtained from `TSCreate()`
1470efe9872eSLisandro Dalcin 
1471efe9872eSLisandro Dalcin   Output Parameters:
1472efe9872eSLisandro Dalcin + J   - The (approximate) Jacobian of F(t,U,U_t,U_tt)
1473195e9b02SBarry Smith . P   - The matrix from which the preconditioner is constructed, often the same as `J`
1474efe9872eSLisandro Dalcin . jac - The function to compute the Jacobian matrices
1475efe9872eSLisandro Dalcin - ctx - User-defined context for Jacobian evaluation routine
1476efe9872eSLisandro Dalcin 
1477bcf0153eSBarry Smith   Level: advanced
1478bcf0153eSBarry Smith 
1479195e9b02SBarry Smith   Note:
1480195e9b02SBarry Smith   You can pass in `NULL` for any return argument you do not need.
1481efe9872eSLisandro Dalcin 
14821cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSGetTimeStep()`, `TSGetMatrices()`, `TSGetTime()`, `TSGetStepNumber()`, `TSSetI2Jacobian()`, `TSGetI2Function()`, `TSCreate()`
1483efe9872eSLisandro Dalcin @*/
1484d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetI2Jacobian(TS ts, Mat *J, Mat *P, TSI2Jacobian *jac, void **ctx)
1485d71ae5a4SJacob Faibussowitsch {
1486efe9872eSLisandro Dalcin   SNES snes;
1487efe9872eSLisandro Dalcin   DM   dm;
1488efe9872eSLisandro Dalcin 
1489efe9872eSLisandro Dalcin   PetscFunctionBegin;
14909566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts, &snes));
14919566063dSJacob Faibussowitsch   PetscCall(SNESSetUpMatrices(snes));
14929566063dSJacob Faibussowitsch   PetscCall(SNESGetJacobian(snes, J, P, NULL, NULL));
14939566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
14949566063dSJacob Faibussowitsch   PetscCall(DMTSGetI2Jacobian(dm, jac, ctx));
14953ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1496efe9872eSLisandro Dalcin }
1497efe9872eSLisandro Dalcin 
1498efe9872eSLisandro Dalcin /*@
1499efe9872eSLisandro Dalcin   TSComputeI2Function - Evaluates the DAE residual written in implicit form F(t,U,U_t,U_tt) = 0
1500efe9872eSLisandro Dalcin 
1501c3339decSBarry Smith   Collective
1502efe9872eSLisandro Dalcin 
1503efe9872eSLisandro Dalcin   Input Parameters:
1504bcf0153eSBarry Smith + ts - the `TS` context
1505efe9872eSLisandro Dalcin . t  - current time
1506efe9872eSLisandro Dalcin . U  - state vector
1507efe9872eSLisandro Dalcin . V  - time derivative of state vector (U_t)
1508efe9872eSLisandro Dalcin - A  - second time derivative of state vector (U_tt)
1509efe9872eSLisandro Dalcin 
1510efe9872eSLisandro Dalcin   Output Parameter:
1511efe9872eSLisandro Dalcin . F - the residual vector
1512efe9872eSLisandro Dalcin 
1513bcf0153eSBarry Smith   Level: developer
1514bcf0153eSBarry Smith 
1515efe9872eSLisandro Dalcin   Note:
1516efe9872eSLisandro Dalcin   Most users should not need to explicitly call this routine, as it
1517efe9872eSLisandro Dalcin   is used internally within the nonlinear solvers.
1518efe9872eSLisandro Dalcin 
15191cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetI2Function()`, `TSGetI2Function()`
1520efe9872eSLisandro Dalcin @*/
1521d71ae5a4SJacob Faibussowitsch PetscErrorCode TSComputeI2Function(TS ts, PetscReal t, Vec U, Vec V, Vec A, Vec F)
1522d71ae5a4SJacob Faibussowitsch {
1523efe9872eSLisandro Dalcin   DM            dm;
1524efe9872eSLisandro Dalcin   TSI2Function  I2Function;
1525efe9872eSLisandro Dalcin   void         *ctx;
1526efe9872eSLisandro Dalcin   TSRHSFunction rhsfunction;
1527efe9872eSLisandro Dalcin 
1528efe9872eSLisandro Dalcin   PetscFunctionBegin;
1529efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
1530efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(U, VEC_CLASSID, 3);
1531efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(V, VEC_CLASSID, 4);
1532efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(A, VEC_CLASSID, 5);
1533efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(F, VEC_CLASSID, 6);
1534efe9872eSLisandro Dalcin 
15359566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
15369566063dSJacob Faibussowitsch   PetscCall(DMTSGetI2Function(dm, &I2Function, &ctx));
15379566063dSJacob Faibussowitsch   PetscCall(DMTSGetRHSFunction(dm, &rhsfunction, NULL));
1538efe9872eSLisandro Dalcin 
1539efe9872eSLisandro Dalcin   if (!I2Function) {
15409566063dSJacob Faibussowitsch     PetscCall(TSComputeIFunction(ts, t, U, A, F, PETSC_FALSE));
15413ba16761SJacob Faibussowitsch     PetscFunctionReturn(PETSC_SUCCESS);
1542efe9872eSLisandro Dalcin   }
1543efe9872eSLisandro Dalcin 
15449566063dSJacob Faibussowitsch   PetscCall(PetscLogEventBegin(TS_FunctionEval, ts, U, V, F));
1545efe9872eSLisandro Dalcin 
1546792fecdfSBarry Smith   PetscCallBack("TS callback implicit function", I2Function(ts, t, U, V, A, F, ctx));
1547efe9872eSLisandro Dalcin 
1548efe9872eSLisandro Dalcin   if (rhsfunction) {
1549efe9872eSLisandro Dalcin     Vec Frhs;
15509566063dSJacob Faibussowitsch     PetscCall(TSGetRHSVec_Private(ts, &Frhs));
15519566063dSJacob Faibussowitsch     PetscCall(TSComputeRHSFunction(ts, t, U, Frhs));
15529566063dSJacob Faibussowitsch     PetscCall(VecAXPY(F, -1, Frhs));
1553efe9872eSLisandro Dalcin   }
1554efe9872eSLisandro Dalcin 
15559566063dSJacob Faibussowitsch   PetscCall(PetscLogEventEnd(TS_FunctionEval, ts, U, V, F));
15563ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1557efe9872eSLisandro Dalcin }
1558efe9872eSLisandro Dalcin 
1559efe9872eSLisandro Dalcin /*@
1560efe9872eSLisandro Dalcin   TSComputeI2Jacobian - Evaluates the Jacobian of the DAE
1561efe9872eSLisandro Dalcin 
1562c3339decSBarry Smith   Collective
1563efe9872eSLisandro Dalcin 
1564efe9872eSLisandro Dalcin   Input Parameters:
1565bcf0153eSBarry Smith + ts     - the `TS` context
1566efe9872eSLisandro Dalcin . t      - current timestep
1567efe9872eSLisandro Dalcin . U      - state vector
1568efe9872eSLisandro Dalcin . V      - time derivative of state vector
1569efe9872eSLisandro Dalcin . A      - second time derivative of state vector
1570efe9872eSLisandro Dalcin . shiftV - shift to apply, see note below
1571efe9872eSLisandro Dalcin - shiftA - shift to apply, see note below
1572efe9872eSLisandro Dalcin 
1573efe9872eSLisandro Dalcin   Output Parameters:
1574efe9872eSLisandro Dalcin + J - Jacobian matrix
1575efe9872eSLisandro Dalcin - P - optional preconditioning matrix
1576efe9872eSLisandro Dalcin 
1577bcf0153eSBarry Smith   Level: developer
1578bcf0153eSBarry Smith 
1579efe9872eSLisandro Dalcin   Notes:
1580efe9872eSLisandro Dalcin   If F(t,U,V,A)=0 is the DAE, the required Jacobian is
1581efe9872eSLisandro Dalcin 
1582efe9872eSLisandro Dalcin   dF/dU + shiftV*dF/dV + shiftA*dF/dA
1583efe9872eSLisandro Dalcin 
1584efe9872eSLisandro Dalcin   Most users should not need to explicitly call this routine, as it
1585efe9872eSLisandro Dalcin   is used internally within the nonlinear solvers.
1586efe9872eSLisandro Dalcin 
15871cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetI2Jacobian()`
1588efe9872eSLisandro Dalcin @*/
1589d71ae5a4SJacob Faibussowitsch PetscErrorCode TSComputeI2Jacobian(TS ts, PetscReal t, Vec U, Vec V, Vec A, PetscReal shiftV, PetscReal shiftA, Mat J, Mat P)
1590d71ae5a4SJacob Faibussowitsch {
1591efe9872eSLisandro Dalcin   DM            dm;
1592efe9872eSLisandro Dalcin   TSI2Jacobian  I2Jacobian;
1593efe9872eSLisandro Dalcin   void         *ctx;
1594efe9872eSLisandro Dalcin   TSRHSJacobian rhsjacobian;
1595efe9872eSLisandro Dalcin 
1596efe9872eSLisandro Dalcin   PetscFunctionBegin;
1597efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
1598efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(U, VEC_CLASSID, 3);
1599efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(V, VEC_CLASSID, 4);
1600efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(A, VEC_CLASSID, 5);
1601efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(J, MAT_CLASSID, 8);
1602efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(P, MAT_CLASSID, 9);
1603efe9872eSLisandro Dalcin 
16049566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
16059566063dSJacob Faibussowitsch   PetscCall(DMTSGetI2Jacobian(dm, &I2Jacobian, &ctx));
16069566063dSJacob Faibussowitsch   PetscCall(DMTSGetRHSJacobian(dm, &rhsjacobian, NULL));
1607efe9872eSLisandro Dalcin 
1608efe9872eSLisandro Dalcin   if (!I2Jacobian) {
16099566063dSJacob Faibussowitsch     PetscCall(TSComputeIJacobian(ts, t, U, A, shiftA, J, P, PETSC_FALSE));
16103ba16761SJacob Faibussowitsch     PetscFunctionReturn(PETSC_SUCCESS);
1611efe9872eSLisandro Dalcin   }
1612efe9872eSLisandro Dalcin 
16139566063dSJacob Faibussowitsch   PetscCall(PetscLogEventBegin(TS_JacobianEval, ts, U, J, P));
1614792fecdfSBarry Smith   PetscCallBack("TS callback implicit Jacobian", I2Jacobian(ts, t, U, V, A, shiftV, shiftA, J, P, ctx));
1615efe9872eSLisandro Dalcin   if (rhsjacobian) {
1616d60b7d5cSBarry Smith     Mat Jrhs, Prhs;
16179566063dSJacob Faibussowitsch     PetscCall(TSGetRHSMats_Private(ts, &Jrhs, &Prhs));
16189566063dSJacob Faibussowitsch     PetscCall(TSComputeRHSJacobian(ts, t, U, Jrhs, Prhs));
16199566063dSJacob Faibussowitsch     PetscCall(MatAXPY(J, -1, Jrhs, ts->axpy_pattern));
16209566063dSJacob Faibussowitsch     if (P != J) PetscCall(MatAXPY(P, -1, Prhs, ts->axpy_pattern));
1621efe9872eSLisandro Dalcin   }
1622efe9872eSLisandro Dalcin 
16239566063dSJacob Faibussowitsch   PetscCall(PetscLogEventEnd(TS_JacobianEval, ts, U, J, P));
16243ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1625efe9872eSLisandro Dalcin }
1626efe9872eSLisandro Dalcin 
1627438f35afSJed Brown /*@C
1628438f35afSJed Brown   TSSetTransientVariable - sets function to transform from state to transient variables
1629438f35afSJed Brown 
1630438f35afSJed Brown   Logically Collective
1631438f35afSJed Brown 
16324165533cSJose E. Roman   Input Parameters:
1633438f35afSJed Brown + ts   - time stepping context on which to change the transient variable
1634a96d6ef6SBarry Smith . tvar - a function that transforms to transient variables
1635438f35afSJed Brown - ctx  - a context for tvar
1636438f35afSJed Brown 
1637438f35afSJed Brown   Level: advanced
1638438f35afSJed Brown 
1639438f35afSJed Brown   Notes:
1640bcf0153eSBarry Smith   This is typically used to transform from primitive to conservative variables so that a time integrator (e.g., `TSBDF`)
1641438f35afSJed Brown   can be conservative.  In this context, primitive variables P are used to model the state (e.g., because they lead to
1642438f35afSJed Brown   well-conditioned formulations even in limiting cases such as low-Mach or zero porosity).  The transient variable is
1643438f35afSJed Brown   C(P), specified by calling this function.  An IFunction thus receives arguments (P, Cdot) and the IJacobian must be
1644438f35afSJed Brown   evaluated via the chain rule, as in
1645195e9b02SBarry Smith .vb
1646438f35afSJed Brown      dF/dP + shift * dF/dCdot dC/dP.
1647195e9b02SBarry Smith .ve
1648438f35afSJed Brown 
164914d0ab18SJacob Faibussowitsch .seealso: [](ch_ts), `TS`, `TSBDF`, `TSTransientVariable`, `DMTSSetTransientVariable()`, `DMTSGetTransientVariable()`, `TSSetIFunction()`, `TSSetIJacobian()`
1650438f35afSJed Brown @*/
1651d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetTransientVariable(TS ts, TSTransientVariable tvar, void *ctx)
1652d71ae5a4SJacob Faibussowitsch {
1653438f35afSJed Brown   DM dm;
1654438f35afSJed Brown 
1655438f35afSJed Brown   PetscFunctionBegin;
1656438f35afSJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
16579566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
16589566063dSJacob Faibussowitsch   PetscCall(DMTSSetTransientVariable(dm, tvar, ctx));
16593ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1660438f35afSJed Brown }
1661438f35afSJed Brown 
1662efe9872eSLisandro Dalcin /*@
1663e3c11fc1SJed Brown   TSComputeTransientVariable - transforms state (primitive) variables to transient (conservative) variables
1664e3c11fc1SJed Brown 
1665e3c11fc1SJed Brown   Logically Collective
1666e3c11fc1SJed Brown 
1667e3c11fc1SJed Brown   Input Parameters:
1668e3c11fc1SJed Brown + ts - TS on which to compute
1669e3c11fc1SJed Brown - U  - state vector to be transformed to transient variables
1670e3c11fc1SJed Brown 
16712fe279fdSBarry Smith   Output Parameter:
1672e3c11fc1SJed Brown . C - transient (conservative) variable
1673e3c11fc1SJed Brown 
1674e3c11fc1SJed Brown   Level: developer
1675e3c11fc1SJed Brown 
1676b43aa488SJacob Faibussowitsch   Developer Notes:
1677195e9b02SBarry Smith   If `DMTSSetTransientVariable()` has not been called, then C is not modified in this routine and C = `NULL` is allowed.
1678bcf0153eSBarry Smith   This makes it safe to call without a guard.  One can use `TSHasTransientVariable()` to check if transient variables are
1679bcf0153eSBarry Smith   being used.
1680bcf0153eSBarry Smith 
16811cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSBDF`, `DMTSSetTransientVariable()`, `TSComputeIFunction()`, `TSComputeIJacobian()`
1682e3c11fc1SJed Brown @*/
1683d71ae5a4SJacob Faibussowitsch PetscErrorCode TSComputeTransientVariable(TS ts, Vec U, Vec C)
1684d71ae5a4SJacob Faibussowitsch {
1685e3c11fc1SJed Brown   DM   dm;
1686e3c11fc1SJed Brown   DMTS dmts;
1687e3c11fc1SJed Brown 
1688e3c11fc1SJed Brown   PetscFunctionBegin;
1689e3c11fc1SJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
1690e3c11fc1SJed Brown   PetscValidHeaderSpecific(U, VEC_CLASSID, 2);
16919566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
16929566063dSJacob Faibussowitsch   PetscCall(DMGetDMTS(dm, &dmts));
1693e3c11fc1SJed Brown   if (dmts->ops->transientvar) {
1694e3c11fc1SJed Brown     PetscValidHeaderSpecific(C, VEC_CLASSID, 3);
16959566063dSJacob Faibussowitsch     PetscCall((*dmts->ops->transientvar)(ts, U, C, dmts->transientvarctx));
1696e3c11fc1SJed Brown   }
16973ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1698e3c11fc1SJed Brown }
1699e3c11fc1SJed Brown 
1700e3c11fc1SJed Brown /*@
1701e3c11fc1SJed Brown   TSHasTransientVariable - determine whether transient variables have been set
1702e3c11fc1SJed Brown 
1703e3c11fc1SJed Brown   Logically Collective
1704e3c11fc1SJed Brown 
17052fe279fdSBarry Smith   Input Parameter:
1706195e9b02SBarry Smith . ts - `TS` on which to compute
1707e3c11fc1SJed Brown 
17082fe279fdSBarry Smith   Output Parameter:
1709bcf0153eSBarry Smith . has - `PETSC_TRUE` if transient variables have been set
1710e3c11fc1SJed Brown 
1711e3c11fc1SJed Brown   Level: developer
1712e3c11fc1SJed Brown 
17131cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSBDF`, `DMTSSetTransientVariable()`, `TSComputeTransientVariable()`
1714e3c11fc1SJed Brown @*/
1715d71ae5a4SJacob Faibussowitsch PetscErrorCode TSHasTransientVariable(TS ts, PetscBool *has)
1716d71ae5a4SJacob Faibussowitsch {
1717e3c11fc1SJed Brown   DM   dm;
1718e3c11fc1SJed Brown   DMTS dmts;
1719e3c11fc1SJed Brown 
1720e3c11fc1SJed Brown   PetscFunctionBegin;
1721e3c11fc1SJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
17229566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
17239566063dSJacob Faibussowitsch   PetscCall(DMGetDMTS(dm, &dmts));
1724e3c11fc1SJed Brown   *has = dmts->ops->transientvar ? PETSC_TRUE : PETSC_FALSE;
17253ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1726e3c11fc1SJed Brown }
1727e3c11fc1SJed Brown 
1728e3c11fc1SJed Brown /*@
1729efe9872eSLisandro Dalcin   TS2SetSolution - Sets the initial solution and time derivative vectors
1730bcf0153eSBarry Smith   for use by the `TS` routines handling second order equations.
1731efe9872eSLisandro Dalcin 
1732c3339decSBarry Smith   Logically Collective
1733efe9872eSLisandro Dalcin 
1734efe9872eSLisandro Dalcin   Input Parameters:
1735bcf0153eSBarry Smith + ts - the `TS` context obtained from `TSCreate()`
1736efe9872eSLisandro Dalcin . u  - the solution vector
1737efe9872eSLisandro Dalcin - v  - the time derivative vector
1738efe9872eSLisandro Dalcin 
1739efe9872eSLisandro Dalcin   Level: beginner
1740efe9872eSLisandro Dalcin 
17411cc06b55SBarry Smith .seealso: [](ch_ts), `TS`
1742efe9872eSLisandro Dalcin @*/
1743d71ae5a4SJacob Faibussowitsch PetscErrorCode TS2SetSolution(TS ts, Vec u, Vec v)
1744d71ae5a4SJacob Faibussowitsch {
1745efe9872eSLisandro Dalcin   PetscFunctionBegin;
1746efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
1747efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(u, VEC_CLASSID, 2);
1748efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(v, VEC_CLASSID, 3);
17499566063dSJacob Faibussowitsch   PetscCall(TSSetSolution(ts, u));
17509566063dSJacob Faibussowitsch   PetscCall(PetscObjectReference((PetscObject)v));
17519566063dSJacob Faibussowitsch   PetscCall(VecDestroy(&ts->vec_dot));
1752efe9872eSLisandro Dalcin   ts->vec_dot = v;
17533ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1754efe9872eSLisandro Dalcin }
1755efe9872eSLisandro Dalcin 
1756efe9872eSLisandro Dalcin /*@
1757efe9872eSLisandro Dalcin   TS2GetSolution - Returns the solution and time derivative at the present timestep
175814d0ab18SJacob Faibussowitsch   for second order equations.
1759efe9872eSLisandro Dalcin 
176014d0ab18SJacob Faibussowitsch   Not Collective
1761efe9872eSLisandro Dalcin 
1762efe9872eSLisandro Dalcin   Input Parameter:
1763bcf0153eSBarry Smith . ts - the `TS` context obtained from `TSCreate()`
1764efe9872eSLisandro Dalcin 
1765d8d19677SJose E. Roman   Output Parameters:
1766efe9872eSLisandro Dalcin + u - the vector containing the solution
1767efe9872eSLisandro Dalcin - v - the vector containing the time derivative
1768efe9872eSLisandro Dalcin 
1769efe9872eSLisandro Dalcin   Level: intermediate
1770efe9872eSLisandro Dalcin 
177114d0ab18SJacob Faibussowitsch   Notes:
177214d0ab18SJacob Faibussowitsch   It is valid to call this routine inside the function
177314d0ab18SJacob Faibussowitsch   that you are evaluating in order to move to the new timestep. This vector not
177414d0ab18SJacob Faibussowitsch   changed until the solution at the next timestep has been calculated.
177514d0ab18SJacob Faibussowitsch 
17761cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TS2SetSolution()`, `TSGetTimeStep()`, `TSGetTime()`
1777efe9872eSLisandro Dalcin @*/
1778d71ae5a4SJacob Faibussowitsch PetscErrorCode TS2GetSolution(TS ts, Vec *u, Vec *v)
1779d71ae5a4SJacob Faibussowitsch {
1780efe9872eSLisandro Dalcin   PetscFunctionBegin;
1781efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
17824f572ea9SToby Isaac   if (u) PetscAssertPointer(u, 2);
17834f572ea9SToby Isaac   if (v) PetscAssertPointer(v, 3);
1784efe9872eSLisandro Dalcin   if (u) *u = ts->vec_sol;
1785efe9872eSLisandro Dalcin   if (v) *v = ts->vec_dot;
17863ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1787efe9872eSLisandro Dalcin }
1788efe9872eSLisandro Dalcin 
178955849f57SBarry Smith /*@C
1790bcf0153eSBarry Smith   TSLoad - Loads a `TS` that has been stored in binary  with `TSView()`.
179155849f57SBarry Smith 
1792c3339decSBarry Smith   Collective
179355849f57SBarry Smith 
179455849f57SBarry Smith   Input Parameters:
1795b43aa488SJacob Faibussowitsch + ts     - the newly loaded `TS`, this needs to have been created with `TSCreate()` or
1796bcf0153eSBarry Smith            some related function before a call to `TSLoad()`.
1797bcf0153eSBarry Smith - viewer - binary file viewer, obtained from `PetscViewerBinaryOpen()`
179855849f57SBarry Smith 
179955849f57SBarry Smith   Level: intermediate
180055849f57SBarry Smith 
1801bcf0153eSBarry Smith   Note:
1802bcf0153eSBarry Smith   The type is determined by the data in the file, any type set into the `TS` before this call is ignored.
180355849f57SBarry Smith 
18041cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `PetscViewer`, `PetscViewerBinaryOpen()`, `TSView()`, `MatLoad()`, `VecLoad()`
180555849f57SBarry Smith @*/
1806d71ae5a4SJacob Faibussowitsch PetscErrorCode TSLoad(TS ts, PetscViewer viewer)
1807d71ae5a4SJacob Faibussowitsch {
180855849f57SBarry Smith   PetscBool isbinary;
180955849f57SBarry Smith   PetscInt  classid;
181055849f57SBarry Smith   char      type[256];
18112d53ad75SBarry Smith   DMTS      sdm;
1812ad6bc421SBarry Smith   DM        dm;
181355849f57SBarry Smith 
181455849f57SBarry Smith   PetscFunctionBegin;
1815f2c2a1b9SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
181655849f57SBarry Smith   PetscValidHeaderSpecific(viewer, PETSC_VIEWER_CLASSID, 2);
18179566063dSJacob Faibussowitsch   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERBINARY, &isbinary));
18183c633725SBarry Smith   PetscCheck(isbinary, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Invalid viewer; open viewer with PetscViewerBinaryOpen()");
181955849f57SBarry Smith 
18209566063dSJacob Faibussowitsch   PetscCall(PetscViewerBinaryRead(viewer, &classid, 1, NULL, PETSC_INT));
18213c633725SBarry Smith   PetscCheck(classid == TS_FILE_CLASSID, PetscObjectComm((PetscObject)ts), PETSC_ERR_ARG_WRONG, "Not TS next in file");
18229566063dSJacob Faibussowitsch   PetscCall(PetscViewerBinaryRead(viewer, type, 256, NULL, PETSC_CHAR));
18239566063dSJacob Faibussowitsch   PetscCall(TSSetType(ts, type));
1824dbbe0bcdSBarry Smith   PetscTryTypeMethod(ts, load, viewer);
18259566063dSJacob Faibussowitsch   PetscCall(DMCreate(PetscObjectComm((PetscObject)ts), &dm));
18269566063dSJacob Faibussowitsch   PetscCall(DMLoad(dm, viewer));
18279566063dSJacob Faibussowitsch   PetscCall(TSSetDM(ts, dm));
18289566063dSJacob Faibussowitsch   PetscCall(DMCreateGlobalVector(ts->dm, &ts->vec_sol));
18299566063dSJacob Faibussowitsch   PetscCall(VecLoad(ts->vec_sol, viewer));
18309566063dSJacob Faibussowitsch   PetscCall(DMGetDMTS(ts->dm, &sdm));
18319566063dSJacob Faibussowitsch   PetscCall(DMTSLoad(sdm, viewer));
18323ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
183355849f57SBarry Smith }
183455849f57SBarry Smith 
18359804daf3SBarry Smith #include <petscdraw.h>
1836e04113cfSBarry Smith #if defined(PETSC_HAVE_SAWS)
1837e04113cfSBarry Smith   #include <petscviewersaws.h>
1838f05ece33SBarry Smith #endif
1839fe2efc57SMark 
1840fe2efc57SMark /*@C
1841bcf0153eSBarry Smith   TSViewFromOptions - View a `TS` based on values in the options database
1842fe2efc57SMark 
1843c3339decSBarry Smith   Collective
1844fe2efc57SMark 
1845fe2efc57SMark   Input Parameters:
1846bcf0153eSBarry Smith + ts   - the `TS` context
1847bcf0153eSBarry Smith . obj  - Optional object that provides the prefix for the options database keys
1848bcf0153eSBarry Smith - name - command line option string to be passed by user
1849fe2efc57SMark 
1850fe2efc57SMark   Level: intermediate
1851bcf0153eSBarry Smith 
18521cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSView`, `PetscObjectViewFromOptions()`, `TSCreate()`
1853fe2efc57SMark @*/
1854bcf0153eSBarry Smith PetscErrorCode TSViewFromOptions(TS ts, PetscObject obj, const char name[])
1855d71ae5a4SJacob Faibussowitsch {
1856fe2efc57SMark   PetscFunctionBegin;
1857bcf0153eSBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
1858bcf0153eSBarry Smith   PetscCall(PetscObjectViewFromOptions((PetscObject)ts, obj, name));
18593ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1860fe2efc57SMark }
1861fe2efc57SMark 
18627e2c5f70SBarry Smith /*@C
1863bcf0153eSBarry Smith   TSView - Prints the `TS` data structure.
1864d763cef2SBarry Smith 
1865c3339decSBarry Smith   Collective
1866d763cef2SBarry Smith 
1867d763cef2SBarry Smith   Input Parameters:
1868bcf0153eSBarry Smith + ts     - the `TS` context obtained from `TSCreate()`
1869d763cef2SBarry Smith - viewer - visualization context
1870d763cef2SBarry Smith 
1871d763cef2SBarry Smith   Options Database Key:
1872bcf0153eSBarry Smith . -ts_view - calls `TSView()` at end of `TSStep()`
1873bcf0153eSBarry Smith 
1874bcf0153eSBarry Smith   Level: beginner
1875d763cef2SBarry Smith 
1876d763cef2SBarry Smith   Notes:
1877d763cef2SBarry Smith   The available visualization contexts include
1878bcf0153eSBarry Smith +     `PETSC_VIEWER_STDOUT_SELF` - standard output (default)
1879bcf0153eSBarry Smith -     `PETSC_VIEWER_STDOUT_WORLD` - synchronized standard
1880d763cef2SBarry Smith   output where only the first processor opens
1881d763cef2SBarry Smith   the file.  All other processors send their
1882d763cef2SBarry Smith   data to the first processor to print.
1883d763cef2SBarry Smith 
1884d763cef2SBarry Smith   The user can open an alternative visualization context with
1885bcf0153eSBarry Smith   `PetscViewerASCIIOpen()` - output to a specified file.
1886d763cef2SBarry Smith 
1887bcf0153eSBarry Smith   In the debugger you can do call `TSView`(ts,0) to display the `TS` solver. (The same holds for any PETSc object viewer).
1888595c91d4SBarry Smith 
18891cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `PetscViewer`, `PetscViewerASCIIOpen()`
1890d763cef2SBarry Smith @*/
1891d71ae5a4SJacob Faibussowitsch PetscErrorCode TSView(TS ts, PetscViewer viewer)
1892d71ae5a4SJacob Faibussowitsch {
189319fd82e9SBarry Smith   TSType    type;
18942b0a91c0SBarry Smith   PetscBool iascii, isstring, isundials, isbinary, isdraw;
18952d53ad75SBarry Smith   DMTS      sdm;
1896e04113cfSBarry Smith #if defined(PETSC_HAVE_SAWS)
1897536b137fSBarry Smith   PetscBool issaws;
1898f05ece33SBarry Smith #endif
1899d763cef2SBarry Smith 
1900d763cef2SBarry Smith   PetscFunctionBegin;
19010700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
19021e66621cSBarry Smith   if (!viewer) PetscCall(PetscViewerASCIIGetStdout(PetscObjectComm((PetscObject)ts), &viewer));
19030700a824SBarry Smith   PetscValidHeaderSpecific(viewer, PETSC_VIEWER_CLASSID, 2);
1904c9780b6fSBarry Smith   PetscCheckSameComm(ts, 1, viewer, 2);
1905fd16b177SBarry Smith 
19069566063dSJacob Faibussowitsch   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERASCII, &iascii));
19079566063dSJacob Faibussowitsch   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERSTRING, &isstring));
19089566063dSJacob Faibussowitsch   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERBINARY, &isbinary));
19099566063dSJacob Faibussowitsch   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERDRAW, &isdraw));
1910e04113cfSBarry Smith #if defined(PETSC_HAVE_SAWS)
19119566063dSJacob Faibussowitsch   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERSAWS, &issaws));
1912f05ece33SBarry Smith #endif
191332077d6dSBarry Smith   if (iascii) {
19149566063dSJacob Faibussowitsch     PetscCall(PetscObjectPrintClassNamePrefixType((PetscObject)ts, viewer));
1915efd4aadfSBarry Smith     if (ts->ops->view) {
19169566063dSJacob Faibussowitsch       PetscCall(PetscViewerASCIIPushTab(viewer));
1917dbbe0bcdSBarry Smith       PetscUseTypeMethod(ts, view, viewer);
19189566063dSJacob Faibussowitsch       PetscCall(PetscViewerASCIIPopTab(viewer));
1919efd4aadfSBarry Smith     }
19201e66621cSBarry Smith     if (ts->max_steps < PETSC_MAX_INT) PetscCall(PetscViewerASCIIPrintf(viewer, "  maximum steps=%" PetscInt_FMT "\n", ts->max_steps));
19211e66621cSBarry Smith     if (ts->max_time < PETSC_MAX_REAL) PetscCall(PetscViewerASCIIPrintf(viewer, "  maximum time=%g\n", (double)ts->max_time));
19221e66621cSBarry Smith     if (ts->ifuncs) PetscCall(PetscViewerASCIIPrintf(viewer, "  total number of I function evaluations=%" PetscInt_FMT "\n", ts->ifuncs));
19231e66621cSBarry Smith     if (ts->ijacs) PetscCall(PetscViewerASCIIPrintf(viewer, "  total number of I Jacobian evaluations=%" PetscInt_FMT "\n", ts->ijacs));
19241e66621cSBarry Smith     if (ts->rhsfuncs) PetscCall(PetscViewerASCIIPrintf(viewer, "  total number of RHS function evaluations=%" PetscInt_FMT "\n", ts->rhsfuncs));
19251e66621cSBarry Smith     if (ts->rhsjacs) PetscCall(PetscViewerASCIIPrintf(viewer, "  total number of RHS Jacobian evaluations=%" PetscInt_FMT "\n", ts->rhsjacs));
1926efd4aadfSBarry Smith     if (ts->usessnes) {
1927efd4aadfSBarry Smith       PetscBool lin;
19281e66621cSBarry Smith       if (ts->problem_type == TS_NONLINEAR) PetscCall(PetscViewerASCIIPrintf(viewer, "  total number of nonlinear solver iterations=%" PetscInt_FMT "\n", ts->snes_its));
192963a3b9bcSJacob Faibussowitsch       PetscCall(PetscViewerASCIIPrintf(viewer, "  total number of linear solver iterations=%" PetscInt_FMT "\n", ts->ksp_its));
19309566063dSJacob Faibussowitsch       PetscCall(PetscObjectTypeCompareAny((PetscObject)ts->snes, &lin, SNESKSPONLY, SNESKSPTRANSPOSEONLY, ""));
193163a3b9bcSJacob Faibussowitsch       PetscCall(PetscViewerASCIIPrintf(viewer, "  total number of %slinear solve failures=%" PetscInt_FMT "\n", lin ? "" : "non", ts->num_snes_failures));
1932efd4aadfSBarry Smith     }
193363a3b9bcSJacob Faibussowitsch     PetscCall(PetscViewerASCIIPrintf(viewer, "  total number of rejected steps=%" PetscInt_FMT "\n", ts->reject));
19341e66621cSBarry Smith     if (ts->vrtol) PetscCall(PetscViewerASCIIPrintf(viewer, "  using vector of relative error tolerances, "));
19351e66621cSBarry Smith     else PetscCall(PetscViewerASCIIPrintf(viewer, "  using relative error tolerance of %g, ", (double)ts->rtol));
19361e66621cSBarry Smith     if (ts->vatol) PetscCall(PetscViewerASCIIPrintf(viewer, "  using vector of absolute error tolerances\n"));
19371e66621cSBarry Smith     else PetscCall(PetscViewerASCIIPrintf(viewer, "  using absolute error tolerance of %g\n", (double)ts->atol));
19389566063dSJacob Faibussowitsch     PetscCall(PetscViewerASCIIPushTab(viewer));
19399566063dSJacob Faibussowitsch     PetscCall(TSAdaptView(ts->adapt, viewer));
19409566063dSJacob Faibussowitsch     PetscCall(PetscViewerASCIIPopTab(viewer));
19410f5bd95cSBarry Smith   } else if (isstring) {
19429566063dSJacob Faibussowitsch     PetscCall(TSGetType(ts, &type));
19439566063dSJacob Faibussowitsch     PetscCall(PetscViewerStringSPrintf(viewer, " TSType: %-7.7s", type));
1944dbbe0bcdSBarry Smith     PetscTryTypeMethod(ts, view, viewer);
194555849f57SBarry Smith   } else if (isbinary) {
194655849f57SBarry Smith     PetscInt    classid = TS_FILE_CLASSID;
194755849f57SBarry Smith     MPI_Comm    comm;
194855849f57SBarry Smith     PetscMPIInt rank;
194955849f57SBarry Smith     char        type[256];
195055849f57SBarry Smith 
19519566063dSJacob Faibussowitsch     PetscCall(PetscObjectGetComm((PetscObject)ts, &comm));
19529566063dSJacob Faibussowitsch     PetscCallMPI(MPI_Comm_rank(comm, &rank));
1953dd400576SPatrick Sanan     if (rank == 0) {
19549566063dSJacob Faibussowitsch       PetscCall(PetscViewerBinaryWrite(viewer, &classid, 1, PETSC_INT));
19559566063dSJacob Faibussowitsch       PetscCall(PetscStrncpy(type, ((PetscObject)ts)->type_name, 256));
19569566063dSJacob Faibussowitsch       PetscCall(PetscViewerBinaryWrite(viewer, type, 256, PETSC_CHAR));
195755849f57SBarry Smith     }
1958dbbe0bcdSBarry Smith     PetscTryTypeMethod(ts, view, viewer);
19599566063dSJacob Faibussowitsch     if (ts->adapt) PetscCall(TSAdaptView(ts->adapt, viewer));
19609566063dSJacob Faibussowitsch     PetscCall(DMView(ts->dm, viewer));
19619566063dSJacob Faibussowitsch     PetscCall(VecView(ts->vec_sol, viewer));
19629566063dSJacob Faibussowitsch     PetscCall(DMGetDMTS(ts->dm, &sdm));
19639566063dSJacob Faibussowitsch     PetscCall(DMTSView(sdm, viewer));
19642b0a91c0SBarry Smith   } else if (isdraw) {
19652b0a91c0SBarry Smith     PetscDraw draw;
19662b0a91c0SBarry Smith     char      str[36];
196789fd9fafSBarry Smith     PetscReal x, y, bottom, h;
19682b0a91c0SBarry Smith 
19699566063dSJacob Faibussowitsch     PetscCall(PetscViewerDrawGetDraw(viewer, 0, &draw));
19709566063dSJacob Faibussowitsch     PetscCall(PetscDrawGetCurrentPoint(draw, &x, &y));
1971c6a7a370SJeremy L Thompson     PetscCall(PetscStrncpy(str, "TS: ", sizeof(str)));
1972c6a7a370SJeremy L Thompson     PetscCall(PetscStrlcat(str, ((PetscObject)ts)->type_name, sizeof(str)));
19739566063dSJacob Faibussowitsch     PetscCall(PetscDrawStringBoxed(draw, x, y, PETSC_DRAW_BLACK, PETSC_DRAW_BLACK, str, NULL, &h));
197489fd9fafSBarry Smith     bottom = y - h;
19759566063dSJacob Faibussowitsch     PetscCall(PetscDrawPushCurrentPoint(draw, x, bottom));
1976dbbe0bcdSBarry Smith     PetscTryTypeMethod(ts, view, viewer);
19779566063dSJacob Faibussowitsch     if (ts->adapt) PetscCall(TSAdaptView(ts->adapt, viewer));
19789566063dSJacob Faibussowitsch     if (ts->snes) PetscCall(SNESView(ts->snes, viewer));
19799566063dSJacob Faibussowitsch     PetscCall(PetscDrawPopCurrentPoint(draw));
1980e04113cfSBarry Smith #if defined(PETSC_HAVE_SAWS)
1981536b137fSBarry Smith   } else if (issaws) {
1982d45a07a7SBarry Smith     PetscMPIInt rank;
19832657e9d9SBarry Smith     const char *name;
19842657e9d9SBarry Smith 
19859566063dSJacob Faibussowitsch     PetscCall(PetscObjectGetName((PetscObject)ts, &name));
19869566063dSJacob Faibussowitsch     PetscCallMPI(MPI_Comm_rank(PETSC_COMM_WORLD, &rank));
1987dd400576SPatrick Sanan     if (!((PetscObject)ts)->amsmem && rank == 0) {
1988d45a07a7SBarry Smith       char dir[1024];
1989d45a07a7SBarry Smith 
19909566063dSJacob Faibussowitsch       PetscCall(PetscObjectViewSAWs((PetscObject)ts, viewer));
19919566063dSJacob Faibussowitsch       PetscCall(PetscSNPrintf(dir, 1024, "/PETSc/Objects/%s/time_step", name));
1992792fecdfSBarry Smith       PetscCallSAWs(SAWs_Register, (dir, &ts->steps, 1, SAWs_READ, SAWs_INT));
19939566063dSJacob Faibussowitsch       PetscCall(PetscSNPrintf(dir, 1024, "/PETSc/Objects/%s/time", name));
1994792fecdfSBarry Smith       PetscCallSAWs(SAWs_Register, (dir, &ts->ptime, 1, SAWs_READ, SAWs_DOUBLE));
1995d763cef2SBarry Smith     }
1996dbbe0bcdSBarry Smith     PetscTryTypeMethod(ts, view, viewer);
1997f05ece33SBarry Smith #endif
1998f05ece33SBarry Smith   }
199936a9e3b9SBarry Smith   if (ts->snes && ts->usessnes) {
20009566063dSJacob Faibussowitsch     PetscCall(PetscViewerASCIIPushTab(viewer));
20019566063dSJacob Faibussowitsch     PetscCall(SNESView(ts->snes, viewer));
20029566063dSJacob Faibussowitsch     PetscCall(PetscViewerASCIIPopTab(viewer));
200336a9e3b9SBarry Smith   }
20049566063dSJacob Faibussowitsch   PetscCall(DMGetDMTS(ts->dm, &sdm));
20059566063dSJacob Faibussowitsch   PetscCall(DMTSView(sdm, viewer));
2006f05ece33SBarry Smith 
20079566063dSJacob Faibussowitsch   PetscCall(PetscViewerASCIIPushTab(viewer));
20089566063dSJacob Faibussowitsch   PetscCall(PetscObjectTypeCompare((PetscObject)ts, TSSUNDIALS, &isundials));
20099566063dSJacob Faibussowitsch   PetscCall(PetscViewerASCIIPopTab(viewer));
20103ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2011d763cef2SBarry Smith }
2012d763cef2SBarry Smith 
2013b07ff414SBarry Smith /*@
2014d763cef2SBarry Smith   TSSetApplicationContext - Sets an optional user-defined context for
2015d763cef2SBarry Smith   the timesteppers.
2016d763cef2SBarry Smith 
2017c3339decSBarry Smith   Logically Collective
2018d763cef2SBarry Smith 
2019d763cef2SBarry Smith   Input Parameters:
2020bcf0153eSBarry Smith + ts   - the `TS` context obtained from `TSCreate()`
2021bcf0153eSBarry Smith - usrP - user context
2022daf670e6SBarry Smith 
2023d763cef2SBarry Smith   Level: intermediate
2024d763cef2SBarry Smith 
2025b43aa488SJacob Faibussowitsch   Fortran Notes:
2026195e9b02SBarry Smith   You must write a Fortran interface definition for this
2027195e9b02SBarry Smith   function that tells Fortran the Fortran derived data type that you are passing in as the `ctx` argument.
2028bcf0153eSBarry Smith 
20291cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSGetApplicationContext()`
2030d763cef2SBarry Smith @*/
2031d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetApplicationContext(TS ts, void *usrP)
2032d71ae5a4SJacob Faibussowitsch {
2033d763cef2SBarry Smith   PetscFunctionBegin;
20340700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
2035d763cef2SBarry Smith   ts->user = usrP;
20363ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2037d763cef2SBarry Smith }
2038d763cef2SBarry Smith 
2039b07ff414SBarry Smith /*@
2040d763cef2SBarry Smith   TSGetApplicationContext - Gets the user-defined context for the
2041bcf0153eSBarry Smith   timestepper that was set with `TSSetApplicationContext()`
2042d763cef2SBarry Smith 
2043d763cef2SBarry Smith   Not Collective
2044d763cef2SBarry Smith 
2045d763cef2SBarry Smith   Input Parameter:
2046bcf0153eSBarry Smith . ts - the `TS` context obtained from `TSCreate()`
2047d763cef2SBarry Smith 
2048d763cef2SBarry Smith   Output Parameter:
2049d763cef2SBarry Smith . usrP - user context
2050d763cef2SBarry Smith 
2051bcf0153eSBarry Smith   Level: intermediate
2052bcf0153eSBarry Smith 
2053b43aa488SJacob Faibussowitsch   Fortran Notes:
2054195e9b02SBarry Smith   You must write a Fortran interface definition for this
2055195e9b02SBarry Smith   function that tells Fortran the Fortran derived data type that you are passing in as the `ctx` argument.
2056daf670e6SBarry Smith 
20571cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetApplicationContext()`
2058d763cef2SBarry Smith @*/
2059d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetApplicationContext(TS ts, void *usrP)
2060d71ae5a4SJacob Faibussowitsch {
2061d763cef2SBarry Smith   PetscFunctionBegin;
20620700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
2063e71120c6SJed Brown   *(void **)usrP = ts->user;
20643ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2065d763cef2SBarry Smith }
2066d763cef2SBarry Smith 
2067d763cef2SBarry Smith /*@
2068bcf0153eSBarry Smith   TSGetStepNumber - Gets the number of time steps completed.
2069d763cef2SBarry Smith 
2070d763cef2SBarry Smith   Not Collective
2071d763cef2SBarry Smith 
2072d763cef2SBarry Smith   Input Parameter:
2073bcf0153eSBarry Smith . ts - the `TS` context obtained from `TSCreate()`
2074d763cef2SBarry Smith 
2075d763cef2SBarry Smith   Output Parameter:
207680275a0aSLisandro Dalcin . steps - number of steps completed so far
2077d763cef2SBarry Smith 
2078d763cef2SBarry Smith   Level: intermediate
2079d763cef2SBarry Smith 
20801cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSGetTime()`, `TSGetTimeStep()`, `TSSetPreStep()`, `TSSetPreStage()`, `TSSetPostStage()`, `TSSetPostStep()`
2081d763cef2SBarry Smith @*/
2082d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetStepNumber(TS ts, PetscInt *steps)
2083d71ae5a4SJacob Faibussowitsch {
2084d763cef2SBarry Smith   PetscFunctionBegin;
20850700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
20864f572ea9SToby Isaac   PetscAssertPointer(steps, 2);
208780275a0aSLisandro Dalcin   *steps = ts->steps;
20883ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
208980275a0aSLisandro Dalcin }
209080275a0aSLisandro Dalcin 
209180275a0aSLisandro Dalcin /*@
209280275a0aSLisandro Dalcin   TSSetStepNumber - Sets the number of steps completed.
209380275a0aSLisandro Dalcin 
2094c3339decSBarry Smith   Logically Collective
209580275a0aSLisandro Dalcin 
209680275a0aSLisandro Dalcin   Input Parameters:
2097bcf0153eSBarry Smith + ts    - the `TS` context
209880275a0aSLisandro Dalcin - steps - number of steps completed so far
209980275a0aSLisandro Dalcin 
2100bcf0153eSBarry Smith   Level: developer
2101bcf0153eSBarry Smith 
2102bcf0153eSBarry Smith   Note:
2103bcf0153eSBarry Smith   For most uses of the `TS` solvers the user need not explicitly call
2104bcf0153eSBarry Smith   `TSSetStepNumber()`, as the step counter is appropriately updated in
2105bcf0153eSBarry Smith   `TSSolve()`/`TSStep()`/`TSRollBack()`. Power users may call this routine to
210680275a0aSLisandro Dalcin   reinitialize timestepping by setting the step counter to zero (and time
210780275a0aSLisandro Dalcin   to the initial time) to solve a similar problem with different initial
210880275a0aSLisandro Dalcin   conditions or parameters. Other possible use case is to continue
2109195e9b02SBarry Smith   timestepping from a previously interrupted run in such a way that `TS`
211080275a0aSLisandro Dalcin   monitors will be called with a initial nonzero step counter.
211180275a0aSLisandro Dalcin 
21121cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSGetStepNumber()`, `TSSetTime()`, `TSSetTimeStep()`, `TSSetSolution()`
211380275a0aSLisandro Dalcin @*/
2114d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetStepNumber(TS ts, PetscInt steps)
2115d71ae5a4SJacob Faibussowitsch {
211680275a0aSLisandro Dalcin   PetscFunctionBegin;
211780275a0aSLisandro Dalcin   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
211880275a0aSLisandro Dalcin   PetscValidLogicalCollectiveInt(ts, steps, 2);
21193c633725SBarry Smith   PetscCheck(steps >= 0, PetscObjectComm((PetscObject)ts), PETSC_ERR_ARG_OUTOFRANGE, "Step number must be non-negative");
212080275a0aSLisandro Dalcin   ts->steps = steps;
21213ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2122d763cef2SBarry Smith }
2123d763cef2SBarry Smith 
2124d763cef2SBarry Smith /*@
2125d763cef2SBarry Smith   TSSetTimeStep - Allows one to reset the timestep at any time,
2126d763cef2SBarry Smith   useful for simple pseudo-timestepping codes.
2127d763cef2SBarry Smith 
2128c3339decSBarry Smith   Logically Collective
2129d763cef2SBarry Smith 
2130d763cef2SBarry Smith   Input Parameters:
2131bcf0153eSBarry Smith + ts        - the `TS` context obtained from `TSCreate()`
2132d763cef2SBarry Smith - time_step - the size of the timestep
2133d763cef2SBarry Smith 
2134d763cef2SBarry Smith   Level: intermediate
2135d763cef2SBarry Smith 
21361cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSPSEUDO`, `TSGetTimeStep()`, `TSSetTime()`
2137d763cef2SBarry Smith @*/
2138d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetTimeStep(TS ts, PetscReal time_step)
2139d71ae5a4SJacob Faibussowitsch {
2140d763cef2SBarry Smith   PetscFunctionBegin;
21410700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
2142c5eb9154SBarry Smith   PetscValidLogicalCollectiveReal(ts, time_step, 2);
2143d763cef2SBarry Smith   ts->time_step = time_step;
21443ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2145d763cef2SBarry Smith }
2146d763cef2SBarry Smith 
2147a43b19c4SJed Brown /*@
214849354f04SShri Abhyankar   TSSetExactFinalTime - Determines whether to adapt the final time step to
214949354f04SShri Abhyankar   match the exact final time, interpolate solution to the exact final time,
2150bcf0153eSBarry Smith   or just return at the final time `TS` computed.
2151a43b19c4SJed Brown 
2152c3339decSBarry Smith   Logically Collective
2153a43b19c4SJed Brown 
2154d8d19677SJose E. Roman   Input Parameters:
2155a43b19c4SJed Brown + ts     - the time-step context
215649354f04SShri Abhyankar - eftopt - exact final time option
2157bcf0153eSBarry Smith .vb
2158bcf0153eSBarry Smith   TS_EXACTFINALTIME_STEPOVER    - Don't do anything if final time is exceeded
2159bcf0153eSBarry Smith   TS_EXACTFINALTIME_INTERPOLATE - Interpolate back to final time
2160bcf0153eSBarry Smith   TS_EXACTFINALTIME_MATCHSTEP - Adapt final time step to match the final time
2161bcf0153eSBarry Smith .ve
2162a43b19c4SJed Brown 
2163bcf0153eSBarry Smith   Options Database Key:
2164feed9e9dSBarry Smith . -ts_exact_final_time <stepover,interpolate,matchstep> - select the final step at runtime
2165feed9e9dSBarry Smith 
2166a43b19c4SJed Brown   Level: beginner
2167a43b19c4SJed Brown 
2168bcf0153eSBarry Smith   Note:
2169bcf0153eSBarry Smith   If you use the option `TS_EXACTFINALTIME_STEPOVER` the solution may be at a very different time
2170bcf0153eSBarry Smith   then the final time you selected.
2171bcf0153eSBarry Smith 
21721cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSExactFinalTimeOption`, `TSGetExactFinalTime()`
2173a43b19c4SJed Brown @*/
2174d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetExactFinalTime(TS ts, TSExactFinalTimeOption eftopt)
2175d71ae5a4SJacob Faibussowitsch {
2176a43b19c4SJed Brown   PetscFunctionBegin;
2177a43b19c4SJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
217849354f04SShri Abhyankar   PetscValidLogicalCollectiveEnum(ts, eftopt, 2);
217949354f04SShri Abhyankar   ts->exact_final_time = eftopt;
21803ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2181a43b19c4SJed Brown }
2182a43b19c4SJed Brown 
2183d763cef2SBarry Smith /*@
2184bcf0153eSBarry Smith   TSGetExactFinalTime - Gets the exact final time option set with `TSSetExactFinalTime()`
2185f6953c82SLisandro Dalcin 
2186f6953c82SLisandro Dalcin   Not Collective
2187f6953c82SLisandro Dalcin 
2188f6953c82SLisandro Dalcin   Input Parameter:
2189bcf0153eSBarry Smith . ts - the `TS` context
2190f6953c82SLisandro Dalcin 
2191f6953c82SLisandro Dalcin   Output Parameter:
2192f6953c82SLisandro Dalcin . eftopt - exact final time option
2193f6953c82SLisandro Dalcin 
2194f6953c82SLisandro Dalcin   Level: beginner
2195f6953c82SLisandro Dalcin 
21961cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSExactFinalTimeOption`, `TSSetExactFinalTime()`
2197f6953c82SLisandro Dalcin @*/
2198d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetExactFinalTime(TS ts, TSExactFinalTimeOption *eftopt)
2199d71ae5a4SJacob Faibussowitsch {
2200f6953c82SLisandro Dalcin   PetscFunctionBegin;
2201f6953c82SLisandro Dalcin   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
22024f572ea9SToby Isaac   PetscAssertPointer(eftopt, 2);
2203f6953c82SLisandro Dalcin   *eftopt = ts->exact_final_time;
22043ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2205f6953c82SLisandro Dalcin }
2206f6953c82SLisandro Dalcin 
2207f6953c82SLisandro Dalcin /*@
2208d763cef2SBarry Smith   TSGetTimeStep - Gets the current timestep size.
2209d763cef2SBarry Smith 
2210d763cef2SBarry Smith   Not Collective
2211d763cef2SBarry Smith 
2212d763cef2SBarry Smith   Input Parameter:
2213bcf0153eSBarry Smith . ts - the `TS` context obtained from `TSCreate()`
2214d763cef2SBarry Smith 
2215d763cef2SBarry Smith   Output Parameter:
2216d763cef2SBarry Smith . dt - the current timestep size
2217d763cef2SBarry Smith 
2218d763cef2SBarry Smith   Level: intermediate
2219d763cef2SBarry Smith 
22201cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetTimeStep()`, `TSGetTime()`
2221d763cef2SBarry Smith @*/
2222d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetTimeStep(TS ts, PetscReal *dt)
2223d71ae5a4SJacob Faibussowitsch {
2224d763cef2SBarry Smith   PetscFunctionBegin;
22250700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
22264f572ea9SToby Isaac   PetscAssertPointer(dt, 2);
2227d763cef2SBarry Smith   *dt = ts->time_step;
22283ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2229d763cef2SBarry Smith }
2230d763cef2SBarry Smith 
2231d8e5e3e6SSatish Balay /*@
2232d763cef2SBarry Smith   TSGetSolution - Returns the solution at the present timestep. It
2233d763cef2SBarry Smith   is valid to call this routine inside the function that you are evaluating
2234d763cef2SBarry Smith   in order to move to the new timestep. This vector not changed until
2235d763cef2SBarry Smith   the solution at the next timestep has been calculated.
2236d763cef2SBarry Smith 
2237bcf0153eSBarry Smith   Not Collective, but v returned is parallel if ts is parallel
2238d763cef2SBarry Smith 
2239d763cef2SBarry Smith   Input Parameter:
2240bcf0153eSBarry Smith . ts - the `TS` context obtained from `TSCreate()`
2241d763cef2SBarry Smith 
2242d763cef2SBarry Smith   Output Parameter:
2243d763cef2SBarry Smith . v - the vector containing the solution
2244d763cef2SBarry Smith 
2245d763cef2SBarry Smith   Level: intermediate
2246d763cef2SBarry Smith 
2247bcf0153eSBarry Smith   Note:
2248bcf0153eSBarry Smith   If you used `TSSetExactFinalTime`(ts,`TS_EXACTFINALTIME_MATCHSTEP`); this does not return the solution at the requested
2249bcf0153eSBarry Smith   final time. It returns the solution at the next timestep.
2250d763cef2SBarry Smith 
22511cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSGetTimeStep()`, `TSGetTime()`, `TSGetSolveTime()`, `TSGetSolutionComponents()`, `TSSetSolutionFunction()`
2252d763cef2SBarry Smith @*/
2253d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetSolution(TS ts, Vec *v)
2254d71ae5a4SJacob Faibussowitsch {
2255d763cef2SBarry Smith   PetscFunctionBegin;
22560700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
22574f572ea9SToby Isaac   PetscAssertPointer(v, 2);
22588737fe31SLisandro Dalcin   *v = ts->vec_sol;
22593ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2260d763cef2SBarry Smith }
2261d763cef2SBarry Smith 
226203fe5f5eSDebojyoti Ghosh /*@
2263b2bf4f3aSDebojyoti Ghosh   TSGetSolutionComponents - Returns any solution components at the present
226403fe5f5eSDebojyoti Ghosh   timestep, if available for the time integration method being used.
2265b2bf4f3aSDebojyoti Ghosh   Solution components are quantities that share the same size and
226603fe5f5eSDebojyoti Ghosh   structure as the solution vector.
226703fe5f5eSDebojyoti Ghosh 
2268bcf0153eSBarry Smith   Not Collective, but v returned is parallel if ts is parallel
226903fe5f5eSDebojyoti Ghosh 
2270b43aa488SJacob Faibussowitsch   Input Parameters:
2271bcf0153eSBarry Smith + ts - the `TS` context obtained from `TSCreate()` (input parameter).
2272195e9b02SBarry Smith . n  - If v is `NULL`, then the number of solution components is
2273b2bf4f3aSDebojyoti Ghosh        returned through n, else the n-th solution component is
227403fe5f5eSDebojyoti Ghosh        returned in v.
2275a2b725a8SWilliam Gropp - v  - the vector containing the n-th solution component
2276195e9b02SBarry Smith        (may be `NULL` to use this function to find out
2277b2bf4f3aSDebojyoti Ghosh         the number of solutions components).
227803fe5f5eSDebojyoti Ghosh 
22794cdd57e5SDebojyoti Ghosh   Level: advanced
228003fe5f5eSDebojyoti Ghosh 
22811cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSGetSolution()`
228203fe5f5eSDebojyoti Ghosh @*/
2283d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetSolutionComponents(TS ts, PetscInt *n, Vec *v)
2284d71ae5a4SJacob Faibussowitsch {
228503fe5f5eSDebojyoti Ghosh   PetscFunctionBegin;
228603fe5f5eSDebojyoti Ghosh   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
2287b2bf4f3aSDebojyoti Ghosh   if (!ts->ops->getsolutioncomponents) *n = 0;
2288dbbe0bcdSBarry Smith   else PetscUseTypeMethod(ts, getsolutioncomponents, n, v);
22893ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
229003fe5f5eSDebojyoti Ghosh }
229103fe5f5eSDebojyoti Ghosh 
22924cdd57e5SDebojyoti Ghosh /*@
22934cdd57e5SDebojyoti Ghosh   TSGetAuxSolution - Returns an auxiliary solution at the present
22944cdd57e5SDebojyoti Ghosh   timestep, if available for the time integration method being used.
22954cdd57e5SDebojyoti Ghosh 
2296bcf0153eSBarry Smith   Not Collective, but v returned is parallel if ts is parallel
22974cdd57e5SDebojyoti Ghosh 
2298b43aa488SJacob Faibussowitsch   Input Parameters:
2299bcf0153eSBarry Smith + ts - the `TS` context obtained from `TSCreate()` (input parameter).
2300a2b725a8SWilliam Gropp - v  - the vector containing the auxiliary solution
23014cdd57e5SDebojyoti Ghosh 
23024cdd57e5SDebojyoti Ghosh   Level: intermediate
23034cdd57e5SDebojyoti Ghosh 
23041cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSGetSolution()`
23054cdd57e5SDebojyoti Ghosh @*/
2306d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetAuxSolution(TS ts, Vec *v)
2307d71ae5a4SJacob Faibussowitsch {
23084cdd57e5SDebojyoti Ghosh   PetscFunctionBegin;
23094cdd57e5SDebojyoti Ghosh   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
2310dbbe0bcdSBarry Smith   if (ts->ops->getauxsolution) PetscUseTypeMethod(ts, getauxsolution, v);
23111e66621cSBarry Smith   else PetscCall(VecZeroEntries(*v));
23123ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
23134cdd57e5SDebojyoti Ghosh }
23144cdd57e5SDebojyoti Ghosh 
23154cdd57e5SDebojyoti Ghosh /*@
23164cdd57e5SDebojyoti Ghosh   TSGetTimeError - Returns the estimated error vector, if the chosen
2317bcf0153eSBarry Smith   `TSType` has an error estimation functionality and `TSSetTimeError()` was called
23184cdd57e5SDebojyoti Ghosh 
2319bcf0153eSBarry Smith   Not Collective, but v returned is parallel if ts is parallel
23209657682dSDebojyoti Ghosh 
2321b43aa488SJacob Faibussowitsch   Input Parameters:
2322bcf0153eSBarry Smith + ts - the `TS` context obtained from `TSCreate()` (input parameter).
2323657c1e31SEmil Constantinescu . n  - current estimate (n=0) or previous one (n=-1)
2324a2b725a8SWilliam Gropp - v  - the vector containing the error (same size as the solution).
23254cdd57e5SDebojyoti Ghosh 
23264cdd57e5SDebojyoti Ghosh   Level: intermediate
23274cdd57e5SDebojyoti Ghosh 
2328bcf0153eSBarry Smith   Note:
2329bcf0153eSBarry Smith   MUST call after `TSSetUp()`
23304cdd57e5SDebojyoti Ghosh 
23311cc06b55SBarry Smith .seealso: [](ch_ts), `TSGetSolution()`, `TSSetTimeError()`
23324cdd57e5SDebojyoti Ghosh @*/
2333d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetTimeError(TS ts, PetscInt n, Vec *v)
2334d71ae5a4SJacob Faibussowitsch {
23354cdd57e5SDebojyoti Ghosh   PetscFunctionBegin;
23364cdd57e5SDebojyoti Ghosh   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
2337dbbe0bcdSBarry Smith   if (ts->ops->gettimeerror) PetscUseTypeMethod(ts, gettimeerror, n, v);
23381e66621cSBarry Smith   else PetscCall(VecZeroEntries(*v));
23393ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
23404cdd57e5SDebojyoti Ghosh }
23414cdd57e5SDebojyoti Ghosh 
234257df6a1bSDebojyoti Ghosh /*@
234357df6a1bSDebojyoti Ghosh   TSSetTimeError - Sets the estimated error vector, if the chosen
2344bcf0153eSBarry Smith   `TSType` has an error estimation functionality. This can be used
234557df6a1bSDebojyoti Ghosh   to restart such a time integrator with a given error vector.
234657df6a1bSDebojyoti Ghosh 
2347bcf0153eSBarry Smith   Not Collective, but v returned is parallel if ts is parallel
234857df6a1bSDebojyoti Ghosh 
2349b43aa488SJacob Faibussowitsch   Input Parameters:
2350bcf0153eSBarry Smith + ts - the `TS` context obtained from `TSCreate()` (input parameter).
2351a2b725a8SWilliam Gropp - v  - the vector containing the error (same size as the solution).
235257df6a1bSDebojyoti Ghosh 
235357df6a1bSDebojyoti Ghosh   Level: intermediate
235457df6a1bSDebojyoti Ghosh 
2355b43aa488SJacob Faibussowitsch .seealso: [](ch_ts), `TS`, `TSSetSolution()`, `TSGetTimeError()`
235657df6a1bSDebojyoti Ghosh @*/
2357d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetTimeError(TS ts, Vec v)
2358d71ae5a4SJacob Faibussowitsch {
235957df6a1bSDebojyoti Ghosh   PetscFunctionBegin;
236057df6a1bSDebojyoti Ghosh   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
23613c633725SBarry Smith   PetscCheck(ts->setupcalled, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Must call TSSetUp() first");
2362dbbe0bcdSBarry Smith   PetscTryTypeMethod(ts, settimeerror, v);
23633ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
236457df6a1bSDebojyoti Ghosh }
236557df6a1bSDebojyoti Ghosh 
2366bdad233fSMatthew Knepley /* ----- Routines to initialize and destroy a timestepper ---- */
2367d8e5e3e6SSatish Balay /*@
2368bdad233fSMatthew Knepley   TSSetProblemType - Sets the type of problem to be solved.
2369d763cef2SBarry Smith 
2370bdad233fSMatthew Knepley   Not collective
2371d763cef2SBarry Smith 
2372bdad233fSMatthew Knepley   Input Parameters:
2373bcf0153eSBarry Smith + ts   - The `TS`
2374bcf0153eSBarry Smith - type - One of `TS_LINEAR`, `TS_NONLINEAR` where these types refer to problems of the forms
2375d763cef2SBarry Smith .vb
23760910c330SBarry Smith          U_t - A U = 0      (linear)
23770910c330SBarry Smith          U_t - A(t) U = 0   (linear)
23780910c330SBarry Smith          F(t,U,U_t) = 0     (nonlinear)
2379d763cef2SBarry Smith .ve
2380d763cef2SBarry Smith 
2381d763cef2SBarry Smith   Level: beginner
2382d763cef2SBarry Smith 
23831cc06b55SBarry Smith .seealso: [](ch_ts), `TSSetUp()`, `TSProblemType`, `TS`
2384d763cef2SBarry Smith @*/
2385d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetProblemType(TS ts, TSProblemType type)
2386d71ae5a4SJacob Faibussowitsch {
2387d763cef2SBarry Smith   PetscFunctionBegin;
23880700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
2389bdad233fSMatthew Knepley   ts->problem_type = type;
23909e2a6581SJed Brown   if (type == TS_LINEAR) {
23919e2a6581SJed Brown     SNES snes;
23929566063dSJacob Faibussowitsch     PetscCall(TSGetSNES(ts, &snes));
23939566063dSJacob Faibussowitsch     PetscCall(SNESSetType(snes, SNESKSPONLY));
23949e2a6581SJed Brown   }
23953ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2396d763cef2SBarry Smith }
2397d763cef2SBarry Smith 
2398bdad233fSMatthew Knepley /*@C
2399bdad233fSMatthew Knepley   TSGetProblemType - Gets the type of problem to be solved.
2400bdad233fSMatthew Knepley 
2401bdad233fSMatthew Knepley   Not collective
2402bdad233fSMatthew Knepley 
2403bdad233fSMatthew Knepley   Input Parameter:
2404bcf0153eSBarry Smith . ts - The `TS`
2405bdad233fSMatthew Knepley 
2406bdad233fSMatthew Knepley   Output Parameter:
2407bcf0153eSBarry Smith . type - One of `TS_LINEAR`, `TS_NONLINEAR` where these types refer to problems of the forms
2408bdad233fSMatthew Knepley .vb
2409089b2837SJed Brown          M U_t = A U
2410089b2837SJed Brown          M(t) U_t = A(t) U
2411b5abc632SBarry Smith          F(t,U,U_t)
2412bdad233fSMatthew Knepley .ve
2413bdad233fSMatthew Knepley 
2414bdad233fSMatthew Knepley   Level: beginner
2415bdad233fSMatthew Knepley 
24161cc06b55SBarry Smith .seealso: [](ch_ts), `TSSetUp()`, `TSProblemType`, `TS`
2417bdad233fSMatthew Knepley @*/
2418d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetProblemType(TS ts, TSProblemType *type)
2419d71ae5a4SJacob Faibussowitsch {
2420bdad233fSMatthew Knepley   PetscFunctionBegin;
24210700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
24224f572ea9SToby Isaac   PetscAssertPointer(type, 2);
2423bdad233fSMatthew Knepley   *type = ts->problem_type;
24243ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2425bdad233fSMatthew Knepley }
2426d763cef2SBarry Smith 
2427303a5415SBarry Smith /*
2428303a5415SBarry 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()
2429303a5415SBarry Smith */
2430d71ae5a4SJacob Faibussowitsch static PetscErrorCode TSSetExactFinalTimeDefault(TS ts)
2431d71ae5a4SJacob Faibussowitsch {
2432303a5415SBarry Smith   PetscBool isnone;
2433303a5415SBarry Smith 
2434303a5415SBarry Smith   PetscFunctionBegin;
24359566063dSJacob Faibussowitsch   PetscCall(TSGetAdapt(ts, &ts->adapt));
24369566063dSJacob Faibussowitsch   PetscCall(TSAdaptSetDefaultType(ts->adapt, ts->default_adapt_type));
2437303a5415SBarry Smith 
24389566063dSJacob Faibussowitsch   PetscCall(PetscObjectTypeCompare((PetscObject)ts->adapt, TSADAPTNONE, &isnone));
24391e66621cSBarry Smith   if (!isnone && ts->exact_final_time == TS_EXACTFINALTIME_UNSPECIFIED) ts->exact_final_time = TS_EXACTFINALTIME_MATCHSTEP;
24401e66621cSBarry Smith   else if (ts->exact_final_time == TS_EXACTFINALTIME_UNSPECIFIED) ts->exact_final_time = TS_EXACTFINALTIME_INTERPOLATE;
24413ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2442303a5415SBarry Smith }
2443303a5415SBarry Smith 
2444d763cef2SBarry Smith /*@
2445303a5415SBarry Smith   TSSetUp - Sets up the internal data structures for the later use of a timestepper.
2446d763cef2SBarry Smith 
2447c3339decSBarry Smith   Collective
2448d763cef2SBarry Smith 
2449d763cef2SBarry Smith   Input Parameter:
2450bcf0153eSBarry Smith . ts - the `TS` context obtained from `TSCreate()`
2451d763cef2SBarry Smith 
2452d763cef2SBarry Smith   Level: advanced
2453d763cef2SBarry Smith 
2454bcf0153eSBarry Smith   Note:
2455bcf0153eSBarry Smith   For basic use of the `TS` solvers the user need not explicitly call
2456bcf0153eSBarry Smith   `TSSetUp()`, since these actions will automatically occur during
2457bcf0153eSBarry Smith   the call to `TSStep()` or `TSSolve()`.  However, if one wishes to control this
2458bcf0153eSBarry Smith   phase separately, `TSSetUp()` should be called after `TSCreate()`
2459bcf0153eSBarry Smith   and optional routines of the form TSSetXXX(), but before `TSStep()` and `TSSolve()`.
2460bcf0153eSBarry Smith 
24611cc06b55SBarry Smith .seealso: [](ch_ts), `TSCreate()`, `TS`, `TSStep()`, `TSDestroy()`, `TSSolve()`
2462d763cef2SBarry Smith @*/
2463d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetUp(TS ts)
2464d71ae5a4SJacob Faibussowitsch {
24656c6b9e74SPeter Brune   DM dm;
24666c6b9e74SPeter Brune   PetscErrorCode (*func)(SNES, Vec, Vec, void *);
2467d1e9a80fSBarry Smith   PetscErrorCode (*jac)(SNES, Vec, Mat, Mat, void *);
2468cd11d68dSLisandro Dalcin   TSIFunction   ifun;
24696c6b9e74SPeter Brune   TSIJacobian   ijac;
2470efe9872eSLisandro Dalcin   TSI2Jacobian  i2jac;
24716c6b9e74SPeter Brune   TSRHSJacobian rhsjac;
2472d763cef2SBarry Smith 
2473d763cef2SBarry Smith   PetscFunctionBegin;
24740700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
24753ba16761SJacob Faibussowitsch   if (ts->setupcalled) PetscFunctionReturn(PETSC_SUCCESS);
2476277b19d0SLisandro Dalcin 
24777adad957SLisandro Dalcin   if (!((PetscObject)ts)->type_name) {
24789566063dSJacob Faibussowitsch     PetscCall(TSGetIFunction(ts, NULL, &ifun, NULL));
24799566063dSJacob Faibussowitsch     PetscCall(TSSetType(ts, ifun ? TSBEULER : TSEULER));
2480d763cef2SBarry Smith   }
2481277b19d0SLisandro Dalcin 
24821a638600SStefano Zampini   if (!ts->vec_sol) {
24831e66621cSBarry Smith     PetscCheck(ts->dm, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Must call TSSetSolution() first");
24849566063dSJacob Faibussowitsch     PetscCall(DMCreateGlobalVector(ts->dm, &ts->vec_sol));
24851a638600SStefano Zampini   }
2486277b19d0SLisandro Dalcin 
24874a658b32SHong Zhang   if (ts->tspan) {
24881e66621cSBarry Smith     if (!ts->tspan->vecs_sol) PetscCall(VecDuplicateVecs(ts->vec_sol, ts->tspan->num_span_times, &ts->tspan->vecs_sol));
24894a658b32SHong Zhang   }
2490298bade4SHong Zhang   if (!ts->Jacp && ts->Jacprhs) { /* IJacobianP shares the same matrix with RHSJacobianP if only RHSJacobianP is provided */
24919566063dSJacob Faibussowitsch     PetscCall(PetscObjectReference((PetscObject)ts->Jacprhs));
2492298bade4SHong Zhang     ts->Jacp = ts->Jacprhs;
2493298bade4SHong Zhang   }
2494298bade4SHong Zhang 
2495cd4cee2dSHong Zhang   if (ts->quadraturets) {
24969566063dSJacob Faibussowitsch     PetscCall(TSSetUp(ts->quadraturets));
24979566063dSJacob Faibussowitsch     PetscCall(VecDestroy(&ts->vec_costintegrand));
24989566063dSJacob Faibussowitsch     PetscCall(VecDuplicate(ts->quadraturets->vec_sol, &ts->vec_costintegrand));
2499cd4cee2dSHong Zhang   }
2500cd4cee2dSHong Zhang 
25019566063dSJacob Faibussowitsch   PetscCall(TSGetRHSJacobian(ts, NULL, NULL, &rhsjac, NULL));
2502f23ba4b3SHong Zhang   if (rhsjac == TSComputeRHSJacobianConstant) {
2503e1244c69SJed Brown     Mat  Amat, Pmat;
2504e1244c69SJed Brown     SNES snes;
25059566063dSJacob Faibussowitsch     PetscCall(TSGetSNES(ts, &snes));
25069566063dSJacob Faibussowitsch     PetscCall(SNESGetJacobian(snes, &Amat, &Pmat, NULL, NULL));
2507e1244c69SJed Brown     /* Matching matrices implies that an IJacobian is NOT set, because if it had been set, the IJacobian's matrix would
2508e1244c69SJed Brown      * have displaced the RHS matrix */
2509971015bcSStefano Zampini     if (Amat && Amat == ts->Arhs) {
2510abc0d4abSBarry 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 */
25119566063dSJacob Faibussowitsch       PetscCall(MatDuplicate(ts->Arhs, MAT_COPY_VALUES, &Amat));
25129566063dSJacob Faibussowitsch       PetscCall(SNESSetJacobian(snes, Amat, NULL, NULL, NULL));
25139566063dSJacob Faibussowitsch       PetscCall(MatDestroy(&Amat));
2514e1244c69SJed Brown     }
2515971015bcSStefano Zampini     if (Pmat && Pmat == ts->Brhs) {
25169566063dSJacob Faibussowitsch       PetscCall(MatDuplicate(ts->Brhs, MAT_COPY_VALUES, &Pmat));
25179566063dSJacob Faibussowitsch       PetscCall(SNESSetJacobian(snes, NULL, Pmat, NULL, NULL));
25189566063dSJacob Faibussowitsch       PetscCall(MatDestroy(&Pmat));
2519e1244c69SJed Brown     }
2520e1244c69SJed Brown   }
25212ffb9264SLisandro Dalcin 
25229566063dSJacob Faibussowitsch   PetscCall(TSGetAdapt(ts, &ts->adapt));
25239566063dSJacob Faibussowitsch   PetscCall(TSAdaptSetDefaultType(ts->adapt, ts->default_adapt_type));
25242ffb9264SLisandro Dalcin 
2525dbbe0bcdSBarry Smith   PetscTryTypeMethod(ts, setup);
2526277b19d0SLisandro Dalcin 
25279566063dSJacob Faibussowitsch   PetscCall(TSSetExactFinalTimeDefault(ts));
25282ffb9264SLisandro Dalcin 
2529a6772fa2SLisandro Dalcin   /* In the case where we've set a DMTSFunction or what have you, we need the default SNESFunction
25306c6b9e74SPeter Brune      to be set right but can't do it elsewhere due to the overreliance on ctx=ts.
25316c6b9e74SPeter Brune    */
25329566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
25339566063dSJacob Faibussowitsch   PetscCall(DMSNESGetFunction(dm, &func, NULL));
25341e66621cSBarry Smith   if (!func) PetscCall(DMSNESSetFunction(dm, SNESTSFormFunction, ts));
25351e66621cSBarry Smith 
2536a6772fa2SLisandro 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.
25376c6b9e74SPeter Brune      Otherwise, the SNES will use coloring internally to form the Jacobian.
25386c6b9e74SPeter Brune    */
25399566063dSJacob Faibussowitsch   PetscCall(DMSNESGetJacobian(dm, &jac, NULL));
25409566063dSJacob Faibussowitsch   PetscCall(DMTSGetIJacobian(dm, &ijac, NULL));
25419566063dSJacob Faibussowitsch   PetscCall(DMTSGetI2Jacobian(dm, &i2jac, NULL));
25429566063dSJacob Faibussowitsch   PetscCall(DMTSGetRHSJacobian(dm, &rhsjac, NULL));
25431e66621cSBarry Smith   if (!jac && (ijac || i2jac || rhsjac)) PetscCall(DMSNESSetJacobian(dm, SNESTSFormJacobian, ts));
2544c0517034SDebojyoti Ghosh 
2545c0517034SDebojyoti Ghosh   /* if time integration scheme has a starting method, call it */
2546dbbe0bcdSBarry Smith   PetscTryTypeMethod(ts, startingmethod);
2547c0517034SDebojyoti Ghosh 
2548277b19d0SLisandro Dalcin   ts->setupcalled = PETSC_TRUE;
25493ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2550277b19d0SLisandro Dalcin }
2551277b19d0SLisandro Dalcin 
2552f6a906c0SBarry Smith /*@
2553bcf0153eSBarry Smith   TSReset - Resets a `TS` context and removes any allocated `Vec`s and `Mat`s.
2554277b19d0SLisandro Dalcin 
2555c3339decSBarry Smith   Collective
2556277b19d0SLisandro Dalcin 
2557277b19d0SLisandro Dalcin   Input Parameter:
2558bcf0153eSBarry Smith . ts - the `TS` context obtained from `TSCreate()`
2559277b19d0SLisandro Dalcin 
2560277b19d0SLisandro Dalcin   Level: beginner
2561277b19d0SLisandro Dalcin 
25621cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSCreate()`, `TSSetup()`, `TSDestroy()`
2563277b19d0SLisandro Dalcin @*/
2564d71ae5a4SJacob Faibussowitsch PetscErrorCode TSReset(TS ts)
2565d71ae5a4SJacob Faibussowitsch {
25661d06f6b3SHong Zhang   TS_RHSSplitLink ilink = ts->tsrhssplit, next;
2567277b19d0SLisandro Dalcin 
2568277b19d0SLisandro Dalcin   PetscFunctionBegin;
2569277b19d0SLisandro Dalcin   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
2570b18ea86cSHong Zhang 
2571dbbe0bcdSBarry Smith   PetscTryTypeMethod(ts, reset);
25729566063dSJacob Faibussowitsch   if (ts->snes) PetscCall(SNESReset(ts->snes));
25739566063dSJacob Faibussowitsch   if (ts->adapt) PetscCall(TSAdaptReset(ts->adapt));
2574bbd56ea5SKarl Rupp 
25759566063dSJacob Faibussowitsch   PetscCall(MatDestroy(&ts->Arhs));
25769566063dSJacob Faibussowitsch   PetscCall(MatDestroy(&ts->Brhs));
25779566063dSJacob Faibussowitsch   PetscCall(VecDestroy(&ts->Frhs));
25789566063dSJacob Faibussowitsch   PetscCall(VecDestroy(&ts->vec_sol));
25799566063dSJacob Faibussowitsch   PetscCall(VecDestroy(&ts->vec_dot));
25809566063dSJacob Faibussowitsch   PetscCall(VecDestroy(&ts->vatol));
25819566063dSJacob Faibussowitsch   PetscCall(VecDestroy(&ts->vrtol));
25829566063dSJacob Faibussowitsch   PetscCall(VecDestroyVecs(ts->nwork, &ts->work));
2583bbd56ea5SKarl Rupp 
25849566063dSJacob Faibussowitsch   PetscCall(MatDestroy(&ts->Jacprhs));
25859566063dSJacob Faibussowitsch   PetscCall(MatDestroy(&ts->Jacp));
25861baa6e33SBarry Smith   if (ts->forward_solve) PetscCall(TSForwardReset(ts));
2587cd4cee2dSHong Zhang   if (ts->quadraturets) {
25889566063dSJacob Faibussowitsch     PetscCall(TSReset(ts->quadraturets));
25899566063dSJacob Faibussowitsch     PetscCall(VecDestroy(&ts->vec_costintegrand));
2590cd4cee2dSHong Zhang   }
25911d06f6b3SHong Zhang   while (ilink) {
25921d06f6b3SHong Zhang     next = ilink->next;
25939566063dSJacob Faibussowitsch     PetscCall(TSDestroy(&ilink->ts));
25949566063dSJacob Faibussowitsch     PetscCall(PetscFree(ilink->splitname));
25959566063dSJacob Faibussowitsch     PetscCall(ISDestroy(&ilink->is));
25969566063dSJacob Faibussowitsch     PetscCall(PetscFree(ilink));
25971d06f6b3SHong Zhang     ilink = next;
259887f4e208SHong Zhang   }
25996bf673ebSJoe Pusztay   ts->tsrhssplit     = NULL;
2600545aaa6fSHong Zhang   ts->num_rhs_splits = 0;
26014a658b32SHong Zhang   if (ts->tspan) {
26024a658b32SHong Zhang     PetscCall(PetscFree(ts->tspan->span_times));
26034a658b32SHong Zhang     PetscCall(VecDestroyVecs(ts->tspan->num_span_times, &ts->tspan->vecs_sol));
26044a658b32SHong Zhang     PetscCall(PetscFree(ts->tspan));
26054a658b32SHong Zhang   }
2606277b19d0SLisandro Dalcin   ts->setupcalled = PETSC_FALSE;
26073ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2608d763cef2SBarry Smith }
2609d763cef2SBarry Smith 
261014d0ab18SJacob Faibussowitsch static PetscErrorCode TSResizeReset(TS);
261114d0ab18SJacob Faibussowitsch 
26121fb7b255SJunchao Zhang /*@C
2613d763cef2SBarry Smith   TSDestroy - Destroys the timestepper context that was created
2614bcf0153eSBarry Smith   with `TSCreate()`.
2615d763cef2SBarry Smith 
2616c3339decSBarry Smith   Collective
2617d763cef2SBarry Smith 
2618d763cef2SBarry Smith   Input Parameter:
2619bcf0153eSBarry Smith . ts - the `TS` context obtained from `TSCreate()`
2620d763cef2SBarry Smith 
2621d763cef2SBarry Smith   Level: beginner
2622d763cef2SBarry Smith 
26231cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSCreate()`, `TSSetUp()`, `TSSolve()`
2624d763cef2SBarry Smith @*/
2625d71ae5a4SJacob Faibussowitsch PetscErrorCode TSDestroy(TS *ts)
2626d71ae5a4SJacob Faibussowitsch {
2627d763cef2SBarry Smith   PetscFunctionBegin;
26283ba16761SJacob Faibussowitsch   if (!*ts) PetscFunctionReturn(PETSC_SUCCESS);
2629ecf68647SHong Zhang   PetscValidHeaderSpecific(*ts, TS_CLASSID, 1);
26309371c9d4SSatish Balay   if (--((PetscObject)(*ts))->refct > 0) {
26319371c9d4SSatish Balay     *ts = NULL;
26323ba16761SJacob Faibussowitsch     PetscFunctionReturn(PETSC_SUCCESS);
26339371c9d4SSatish Balay   }
2634d763cef2SBarry Smith 
26359566063dSJacob Faibussowitsch   PetscCall(TSReset(*ts));
26369566063dSJacob Faibussowitsch   PetscCall(TSAdjointReset(*ts));
26371e66621cSBarry Smith   if ((*ts)->forward_solve) PetscCall(TSForwardReset(*ts));
26386bd3a4fdSStefano Zampini   PetscCall(TSResizeReset(*ts));
26391e66621cSBarry Smith 
2640e04113cfSBarry Smith   /* if memory was published with SAWs then destroy it */
26419566063dSJacob Faibussowitsch   PetscCall(PetscObjectSAWsViewOff((PetscObject)*ts));
2642dbbe0bcdSBarry Smith   PetscTryTypeMethod((*ts), destroy);
26436d4c513bSLisandro Dalcin 
26449566063dSJacob Faibussowitsch   PetscCall(TSTrajectoryDestroy(&(*ts)->trajectory));
2645bc952696SBarry Smith 
26469566063dSJacob Faibussowitsch   PetscCall(TSAdaptDestroy(&(*ts)->adapt));
26479566063dSJacob Faibussowitsch   PetscCall(TSEventDestroy(&(*ts)->event));
26486427ac75SLisandro Dalcin 
26499566063dSJacob Faibussowitsch   PetscCall(SNESDestroy(&(*ts)->snes));
26509566063dSJacob Faibussowitsch   PetscCall(DMDestroy(&(*ts)->dm));
26519566063dSJacob Faibussowitsch   PetscCall(TSMonitorCancel((*ts)));
26529566063dSJacob Faibussowitsch   PetscCall(TSAdjointMonitorCancel((*ts)));
26536d4c513bSLisandro Dalcin 
26549566063dSJacob Faibussowitsch   PetscCall(TSDestroy(&(*ts)->quadraturets));
26559566063dSJacob Faibussowitsch   PetscCall(PetscHeaderDestroy(ts));
26563ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2657d763cef2SBarry Smith }
2658d763cef2SBarry Smith 
2659d8e5e3e6SSatish Balay /*@
2660bcf0153eSBarry Smith   TSGetSNES - Returns the `SNES` (nonlinear solver) associated with
2661bcf0153eSBarry Smith   a `TS` (timestepper) context. Valid only for nonlinear problems.
2662d763cef2SBarry Smith 
2663bcf0153eSBarry Smith   Not Collective, but snes is parallel if ts is parallel
2664d763cef2SBarry Smith 
2665d763cef2SBarry Smith   Input Parameter:
2666bcf0153eSBarry Smith . ts - the `TS` context obtained from `TSCreate()`
2667d763cef2SBarry Smith 
2668d763cef2SBarry Smith   Output Parameter:
2669d763cef2SBarry Smith . snes - the nonlinear solver context
2670d763cef2SBarry Smith 
2671d763cef2SBarry Smith   Level: beginner
2672d763cef2SBarry Smith 
2673bcf0153eSBarry Smith   Notes:
2674bcf0153eSBarry Smith   The user can then directly manipulate the `SNES` context to set various
2675bcf0153eSBarry Smith   options, etc.  Likewise, the user can then extract and manipulate the
2676bcf0153eSBarry Smith   `KSP`, and `PC` contexts as well.
2677bcf0153eSBarry Smith 
2678bcf0153eSBarry Smith   `TSGetSNES()` does not work for integrators that do not use `SNES`; in
2679195e9b02SBarry Smith   this case `TSGetSNES()` returns `NULL` in `snes`.
2680bcf0153eSBarry Smith 
26811cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `SNES`, `TSCreate()`, `TSSetUp()`, `TSSolve()`
2682d763cef2SBarry Smith @*/
2683d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetSNES(TS ts, SNES *snes)
2684d71ae5a4SJacob Faibussowitsch {
2685d763cef2SBarry Smith   PetscFunctionBegin;
26860700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
26874f572ea9SToby Isaac   PetscAssertPointer(snes, 2);
2688d372ba47SLisandro Dalcin   if (!ts->snes) {
26899566063dSJacob Faibussowitsch     PetscCall(SNESCreate(PetscObjectComm((PetscObject)ts), &ts->snes));
26909566063dSJacob Faibussowitsch     PetscCall(PetscObjectSetOptions((PetscObject)ts->snes, ((PetscObject)ts)->options));
26919566063dSJacob Faibussowitsch     PetscCall(SNESSetFunction(ts->snes, NULL, SNESTSFormFunction, ts));
26929566063dSJacob Faibussowitsch     PetscCall(PetscObjectIncrementTabLevel((PetscObject)ts->snes, (PetscObject)ts, 1));
26939566063dSJacob Faibussowitsch     if (ts->dm) PetscCall(SNESSetDM(ts->snes, ts->dm));
26941e66621cSBarry Smith     if (ts->problem_type == TS_LINEAR) PetscCall(SNESSetType(ts->snes, SNESKSPONLY));
2695d372ba47SLisandro Dalcin   }
2696d763cef2SBarry Smith   *snes = ts->snes;
26973ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2698d763cef2SBarry Smith }
2699d763cef2SBarry Smith 
2700deb2cd25SJed Brown /*@
2701bcf0153eSBarry Smith   TSSetSNES - Set the `SNES` (nonlinear solver) to be used by the timestepping context
2702deb2cd25SJed Brown 
2703deb2cd25SJed Brown   Collective
2704deb2cd25SJed Brown 
2705d8d19677SJose E. Roman   Input Parameters:
2706bcf0153eSBarry Smith + ts   - the `TS` context obtained from `TSCreate()`
2707deb2cd25SJed Brown - snes - the nonlinear solver context
2708deb2cd25SJed Brown 
2709deb2cd25SJed Brown   Level: developer
2710deb2cd25SJed Brown 
2711bcf0153eSBarry Smith   Note:
2712bcf0153eSBarry Smith   Most users should have the `TS` created by calling `TSGetSNES()`
2713bcf0153eSBarry Smith 
27141cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `SNES`, `TSCreate()`, `TSSetUp()`, `TSSolve()`, `TSGetSNES()`
2715deb2cd25SJed Brown @*/
2716d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetSNES(TS ts, SNES snes)
2717d71ae5a4SJacob Faibussowitsch {
2718d1e9a80fSBarry Smith   PetscErrorCode (*func)(SNES, Vec, Mat, Mat, void *);
2719deb2cd25SJed Brown 
2720deb2cd25SJed Brown   PetscFunctionBegin;
2721deb2cd25SJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
2722deb2cd25SJed Brown   PetscValidHeaderSpecific(snes, SNES_CLASSID, 2);
27239566063dSJacob Faibussowitsch   PetscCall(PetscObjectReference((PetscObject)snes));
27249566063dSJacob Faibussowitsch   PetscCall(SNESDestroy(&ts->snes));
2725bbd56ea5SKarl Rupp 
2726deb2cd25SJed Brown   ts->snes = snes;
2727bbd56ea5SKarl Rupp 
27289566063dSJacob Faibussowitsch   PetscCall(SNESSetFunction(ts->snes, NULL, SNESTSFormFunction, ts));
27299566063dSJacob Faibussowitsch   PetscCall(SNESGetJacobian(ts->snes, NULL, NULL, &func, NULL));
27301e66621cSBarry Smith   if (func == SNESTSFormJacobian) PetscCall(SNESSetJacobian(ts->snes, NULL, NULL, SNESTSFormJacobian, ts));
27313ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2732deb2cd25SJed Brown }
2733deb2cd25SJed Brown 
2734d8e5e3e6SSatish Balay /*@
2735bcf0153eSBarry Smith   TSGetKSP - Returns the `KSP` (linear solver) associated with
2736bcf0153eSBarry Smith   a `TS` (timestepper) context.
2737d763cef2SBarry Smith 
2738195e9b02SBarry Smith   Not Collective, but `ksp` is parallel if `ts` is parallel
2739d763cef2SBarry Smith 
2740d763cef2SBarry Smith   Input Parameter:
2741bcf0153eSBarry Smith . ts - the `TS` context obtained from `TSCreate()`
2742d763cef2SBarry Smith 
2743d763cef2SBarry Smith   Output Parameter:
274494b7f48cSBarry Smith . ksp - the nonlinear solver context
2745d763cef2SBarry Smith 
2746d763cef2SBarry Smith   Level: beginner
2747d763cef2SBarry Smith 
2748bcf0153eSBarry Smith   Notes:
2749bcf0153eSBarry Smith   The user can then directly manipulate the `KSP` context to set various
2750bcf0153eSBarry Smith   options, etc.  Likewise, the user can then extract and manipulate the
2751bcf0153eSBarry Smith   `PC` context as well.
2752bcf0153eSBarry Smith 
2753bcf0153eSBarry Smith   `TSGetKSP()` does not work for integrators that do not use `KSP`;
2754195e9b02SBarry Smith   in this case `TSGetKSP()` returns `NULL` in `ksp`.
2755bcf0153eSBarry Smith 
27561cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `SNES`, `KSP`, `TSCreate()`, `TSSetUp()`, `TSSolve()`, `TSGetSNES()`
2757d763cef2SBarry Smith @*/
2758d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetKSP(TS ts, KSP *ksp)
2759d71ae5a4SJacob Faibussowitsch {
2760089b2837SJed Brown   SNES snes;
2761d372ba47SLisandro Dalcin 
2762d763cef2SBarry Smith   PetscFunctionBegin;
27630700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
27644f572ea9SToby Isaac   PetscAssertPointer(ksp, 2);
27653c633725SBarry Smith   PetscCheck(((PetscObject)ts)->type_name, PETSC_COMM_SELF, PETSC_ERR_ARG_NULL, "KSP is not created yet. Call TSSetType() first");
27663c633725SBarry Smith   PetscCheck(ts->problem_type == TS_LINEAR, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Linear only; use TSGetSNES()");
27679566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts, &snes));
27689566063dSJacob Faibussowitsch   PetscCall(SNESGetKSP(snes, ksp));
27693ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2770d763cef2SBarry Smith }
2771d763cef2SBarry Smith 
2772d763cef2SBarry Smith /* ----------- Routines to set solver parameters ---------- */
2773d763cef2SBarry Smith 
2774adb62b0dSMatthew Knepley /*@
2775618ce8baSLisandro Dalcin   TSSetMaxSteps - Sets the maximum number of steps to use.
2776618ce8baSLisandro Dalcin 
2777c3339decSBarry Smith   Logically Collective
2778618ce8baSLisandro Dalcin 
2779618ce8baSLisandro Dalcin   Input Parameters:
2780bcf0153eSBarry Smith + ts       - the `TS` context obtained from `TSCreate()`
2781618ce8baSLisandro Dalcin - maxsteps - maximum number of steps to use
2782618ce8baSLisandro Dalcin 
2783bcf0153eSBarry Smith   Options Database Key:
2784618ce8baSLisandro Dalcin . -ts_max_steps <maxsteps> - Sets maxsteps
2785618ce8baSLisandro Dalcin 
2786618ce8baSLisandro Dalcin   Level: intermediate
2787618ce8baSLisandro Dalcin 
2788bcf0153eSBarry Smith   Note:
2789bcf0153eSBarry Smith   The default maximum number of steps is 5000
2790bcf0153eSBarry Smith 
27911cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSGetMaxSteps()`, `TSSetMaxTime()`, `TSSetExactFinalTime()`
2792618ce8baSLisandro Dalcin @*/
2793d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetMaxSteps(TS ts, PetscInt maxsteps)
2794d71ae5a4SJacob Faibussowitsch {
2795618ce8baSLisandro Dalcin   PetscFunctionBegin;
2796618ce8baSLisandro Dalcin   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
2797618ce8baSLisandro Dalcin   PetscValidLogicalCollectiveInt(ts, maxsteps, 2);
27983c633725SBarry Smith   PetscCheck(maxsteps >= 0, PetscObjectComm((PetscObject)ts), PETSC_ERR_ARG_OUTOFRANGE, "Maximum number of steps must be non-negative");
2799618ce8baSLisandro Dalcin   ts->max_steps = maxsteps;
28003ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2801618ce8baSLisandro Dalcin }
2802618ce8baSLisandro Dalcin 
2803618ce8baSLisandro Dalcin /*@
2804618ce8baSLisandro Dalcin   TSGetMaxSteps - Gets the maximum number of steps to use.
2805618ce8baSLisandro Dalcin 
2806618ce8baSLisandro Dalcin   Not Collective
2807618ce8baSLisandro Dalcin 
28082fe279fdSBarry Smith   Input Parameter:
2809bcf0153eSBarry Smith . ts - the `TS` context obtained from `TSCreate()`
2810618ce8baSLisandro Dalcin 
2811618ce8baSLisandro Dalcin   Output Parameter:
2812618ce8baSLisandro Dalcin . maxsteps - maximum number of steps to use
2813618ce8baSLisandro Dalcin 
2814618ce8baSLisandro Dalcin   Level: advanced
2815618ce8baSLisandro Dalcin 
28161cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetMaxSteps()`, `TSGetMaxTime()`, `TSSetMaxTime()`
2817618ce8baSLisandro Dalcin @*/
2818d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetMaxSteps(TS ts, PetscInt *maxsteps)
2819d71ae5a4SJacob Faibussowitsch {
2820618ce8baSLisandro Dalcin   PetscFunctionBegin;
2821618ce8baSLisandro Dalcin   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
28224f572ea9SToby Isaac   PetscAssertPointer(maxsteps, 2);
2823618ce8baSLisandro Dalcin   *maxsteps = ts->max_steps;
28243ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2825618ce8baSLisandro Dalcin }
2826618ce8baSLisandro Dalcin 
2827618ce8baSLisandro Dalcin /*@
2828618ce8baSLisandro Dalcin   TSSetMaxTime - Sets the maximum (or final) time for timestepping.
2829618ce8baSLisandro Dalcin 
2830c3339decSBarry Smith   Logically Collective
2831618ce8baSLisandro Dalcin 
2832618ce8baSLisandro Dalcin   Input Parameters:
2833bcf0153eSBarry Smith + ts      - the `TS` context obtained from `TSCreate()`
2834618ce8baSLisandro Dalcin - maxtime - final time to step to
2835618ce8baSLisandro Dalcin 
2836bcf0153eSBarry Smith   Options Database Key:
2837ef85077eSLisandro Dalcin . -ts_max_time <maxtime> - Sets maxtime
2838618ce8baSLisandro Dalcin 
2839bcf0153eSBarry Smith   Level: intermediate
2840bcf0153eSBarry Smith 
2841618ce8baSLisandro Dalcin   Notes:
2842618ce8baSLisandro Dalcin   The default maximum time is 5.0
2843618ce8baSLisandro Dalcin 
28441cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSGetMaxTime()`, `TSSetMaxSteps()`, `TSSetExactFinalTime()`
2845618ce8baSLisandro Dalcin @*/
2846d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetMaxTime(TS ts, PetscReal maxtime)
2847d71ae5a4SJacob Faibussowitsch {
2848618ce8baSLisandro Dalcin   PetscFunctionBegin;
2849618ce8baSLisandro Dalcin   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
2850618ce8baSLisandro Dalcin   PetscValidLogicalCollectiveReal(ts, maxtime, 2);
2851618ce8baSLisandro Dalcin   ts->max_time = maxtime;
28523ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2853618ce8baSLisandro Dalcin }
2854618ce8baSLisandro Dalcin 
2855618ce8baSLisandro Dalcin /*@
2856618ce8baSLisandro Dalcin   TSGetMaxTime - Gets the maximum (or final) time for timestepping.
2857618ce8baSLisandro Dalcin 
2858618ce8baSLisandro Dalcin   Not Collective
2859618ce8baSLisandro Dalcin 
28602fe279fdSBarry Smith   Input Parameter:
2861bcf0153eSBarry Smith . ts - the `TS` context obtained from `TSCreate()`
2862618ce8baSLisandro Dalcin 
2863618ce8baSLisandro Dalcin   Output Parameter:
2864618ce8baSLisandro Dalcin . maxtime - final time to step to
2865618ce8baSLisandro Dalcin 
2866618ce8baSLisandro Dalcin   Level: advanced
2867618ce8baSLisandro Dalcin 
28681cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetMaxTime()`, `TSGetMaxSteps()`, `TSSetMaxSteps()`
2869618ce8baSLisandro Dalcin @*/
2870d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetMaxTime(TS ts, PetscReal *maxtime)
2871d71ae5a4SJacob Faibussowitsch {
2872618ce8baSLisandro Dalcin   PetscFunctionBegin;
2873618ce8baSLisandro Dalcin   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
28744f572ea9SToby Isaac   PetscAssertPointer(maxtime, 2);
2875618ce8baSLisandro Dalcin   *maxtime = ts->max_time;
28763ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2877618ce8baSLisandro Dalcin }
2878618ce8baSLisandro Dalcin 
287914d0ab18SJacob Faibussowitsch // PetscClangLinter pragma disable: -fdoc-*
2880618ce8baSLisandro Dalcin /*@
2881bcf0153eSBarry Smith   TSSetInitialTimeStep - Deprecated, use `TSSetTime()` and `TSSetTimeStep()`.
2882edc382c3SSatish Balay 
2883edc382c3SSatish Balay   Level: deprecated
2884edc382c3SSatish Balay 
2885aaa6c58dSLisandro Dalcin @*/
2886d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetInitialTimeStep(TS ts, PetscReal initial_time, PetscReal time_step)
2887d71ae5a4SJacob Faibussowitsch {
2888aaa6c58dSLisandro Dalcin   PetscFunctionBegin;
2889aaa6c58dSLisandro Dalcin   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
28909566063dSJacob Faibussowitsch   PetscCall(TSSetTime(ts, initial_time));
28919566063dSJacob Faibussowitsch   PetscCall(TSSetTimeStep(ts, time_step));
28923ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2893aaa6c58dSLisandro Dalcin }
2894aaa6c58dSLisandro Dalcin 
289514d0ab18SJacob Faibussowitsch // PetscClangLinter pragma disable: -fdoc-*
2896aaa6c58dSLisandro Dalcin /*@
2897bcf0153eSBarry Smith   TSGetDuration - Deprecated, use `TSGetMaxSteps()` and `TSGetMaxTime()`.
2898edc382c3SSatish Balay 
2899edc382c3SSatish Balay   Level: deprecated
2900edc382c3SSatish Balay 
2901adb62b0dSMatthew Knepley @*/
2902d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetDuration(TS ts, PetscInt *maxsteps, PetscReal *maxtime)
2903d71ae5a4SJacob Faibussowitsch {
2904adb62b0dSMatthew Knepley   PetscFunctionBegin;
29050700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
2906abc0a331SBarry Smith   if (maxsteps) {
29074f572ea9SToby Isaac     PetscAssertPointer(maxsteps, 2);
2908adb62b0dSMatthew Knepley     *maxsteps = ts->max_steps;
2909adb62b0dSMatthew Knepley   }
2910abc0a331SBarry Smith   if (maxtime) {
29114f572ea9SToby Isaac     PetscAssertPointer(maxtime, 3);
2912adb62b0dSMatthew Knepley     *maxtime = ts->max_time;
2913adb62b0dSMatthew Knepley   }
29143ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2915adb62b0dSMatthew Knepley }
2916adb62b0dSMatthew Knepley 
291714d0ab18SJacob Faibussowitsch // PetscClangLinter pragma disable: -fdoc-*
2918d763cef2SBarry Smith /*@
2919bcf0153eSBarry Smith   TSSetDuration - Deprecated, use `TSSetMaxSteps()` and `TSSetMaxTime()`.
2920edc382c3SSatish Balay 
2921edc382c3SSatish Balay   Level: deprecated
2922edc382c3SSatish Balay 
2923d763cef2SBarry Smith @*/
2924d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetDuration(TS ts, PetscInt maxsteps, PetscReal maxtime)
2925d71ae5a4SJacob Faibussowitsch {
2926d763cef2SBarry Smith   PetscFunctionBegin;
29270700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
2928c5eb9154SBarry Smith   PetscValidLogicalCollectiveInt(ts, maxsteps, 2);
2929064a246eSJacob Faibussowitsch   PetscValidLogicalCollectiveReal(ts, maxtime, 3);
293039b7ec4bSSean Farley   if (maxsteps >= 0) ts->max_steps = maxsteps;
293113bcc0bdSJacob Faibussowitsch   if (maxtime != (PetscReal)PETSC_DEFAULT) ts->max_time = maxtime;
29323ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2933d763cef2SBarry Smith }
2934d763cef2SBarry Smith 
293514d0ab18SJacob Faibussowitsch // PetscClangLinter pragma disable: -fdoc-*
2936d763cef2SBarry Smith /*@
2937bcf0153eSBarry Smith   TSGetTimeStepNumber - Deprecated, use `TSGetStepNumber()`.
2938edc382c3SSatish Balay 
2939edc382c3SSatish Balay   Level: deprecated
2940edc382c3SSatish Balay 
29415c5f5948SLisandro Dalcin @*/
2942d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetTimeStepNumber(TS ts, PetscInt *steps)
2943d71ae5a4SJacob Faibussowitsch {
29449371c9d4SSatish Balay   return TSGetStepNumber(ts, steps);
29459371c9d4SSatish Balay }
29465c5f5948SLisandro Dalcin 
294714d0ab18SJacob Faibussowitsch // PetscClangLinter pragma disable: -fdoc-*
294819eac22cSLisandro Dalcin /*@
2949bcf0153eSBarry Smith   TSGetTotalSteps - Deprecated, use `TSGetStepNumber()`.
2950edc382c3SSatish Balay 
2951edc382c3SSatish Balay   Level: deprecated
2952edc382c3SSatish Balay 
29534f4e0956SLisandro Dalcin @*/
2954d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetTotalSteps(TS ts, PetscInt *steps)
2955d71ae5a4SJacob Faibussowitsch {
29569371c9d4SSatish Balay   return TSGetStepNumber(ts, steps);
29579371c9d4SSatish Balay }
29584f4e0956SLisandro Dalcin 
29594f4e0956SLisandro Dalcin /*@
2960d763cef2SBarry Smith   TSSetSolution - Sets the initial solution vector
2961bcf0153eSBarry Smith   for use by the `TS` routines.
2962d763cef2SBarry Smith 
2963c3339decSBarry Smith   Logically Collective
2964d763cef2SBarry Smith 
2965d763cef2SBarry Smith   Input Parameters:
2966bcf0153eSBarry Smith + ts - the `TS` context obtained from `TSCreate()`
29670910c330SBarry Smith - u  - the solution vector
2968d763cef2SBarry Smith 
2969d763cef2SBarry Smith   Level: beginner
2970d763cef2SBarry Smith 
29711cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetSolutionFunction()`, `TSGetSolution()`, `TSCreate()`
2972d763cef2SBarry Smith @*/
2973d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetSolution(TS ts, Vec u)
2974d71ae5a4SJacob Faibussowitsch {
2975496e6a7aSJed Brown   DM dm;
29768737fe31SLisandro Dalcin 
2977d763cef2SBarry Smith   PetscFunctionBegin;
29780700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
29790910c330SBarry Smith   PetscValidHeaderSpecific(u, VEC_CLASSID, 2);
29809566063dSJacob Faibussowitsch   PetscCall(PetscObjectReference((PetscObject)u));
29819566063dSJacob Faibussowitsch   PetscCall(VecDestroy(&ts->vec_sol));
29820910c330SBarry Smith   ts->vec_sol = u;
2983bbd56ea5SKarl Rupp 
29849566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
29859566063dSJacob Faibussowitsch   PetscCall(DMShellSetGlobalVector(dm, u));
29863ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2987d763cef2SBarry Smith }
2988d763cef2SBarry Smith 
2989ac226902SBarry Smith /*@C
2990000e7ae3SMatthew Knepley   TSSetPreStep - Sets the general-purpose function
29913f2090d5SJed Brown   called once at the beginning of each time step.
2992000e7ae3SMatthew Knepley 
2993c3339decSBarry Smith   Logically Collective
2994000e7ae3SMatthew Knepley 
2995000e7ae3SMatthew Knepley   Input Parameters:
2996bcf0153eSBarry Smith + ts   - The `TS` context obtained from `TSCreate()`
2997000e7ae3SMatthew Knepley - func - The function
2998000e7ae3SMatthew Knepley 
299920f4b53cSBarry Smith   Calling sequence of `func`:
300014d0ab18SJacob Faibussowitsch . ts - the `TS` context
3001000e7ae3SMatthew Knepley 
3002000e7ae3SMatthew Knepley   Level: intermediate
3003000e7ae3SMatthew Knepley 
30041cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetPreStage()`, `TSSetPostStage()`, `TSSetPostStep()`, `TSStep()`, `TSRestartStep()`
3005000e7ae3SMatthew Knepley @*/
300614d0ab18SJacob Faibussowitsch PetscErrorCode TSSetPreStep(TS ts, PetscErrorCode (*func)(TS ts))
3007d71ae5a4SJacob Faibussowitsch {
3008000e7ae3SMatthew Knepley   PetscFunctionBegin;
30090700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3010ae60f76fSBarry Smith   ts->prestep = func;
30113ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
3012000e7ae3SMatthew Knepley }
3013000e7ae3SMatthew Knepley 
301409ee8438SJed Brown /*@
3015bcf0153eSBarry Smith   TSPreStep - Runs the user-defined pre-step function provided with `TSSetPreStep()`
30163f2090d5SJed Brown 
3017c3339decSBarry Smith   Collective
30183f2090d5SJed Brown 
30192fe279fdSBarry Smith   Input Parameter:
3020bcf0153eSBarry Smith . ts - The `TS` context obtained from `TSCreate()`
30213f2090d5SJed Brown 
30223f2090d5SJed Brown   Level: developer
30233f2090d5SJed Brown 
3024bcf0153eSBarry Smith   Note:
3025bcf0153eSBarry Smith   `TSPreStep()` is typically used within time stepping implementations,
3026bcf0153eSBarry Smith   so most users would not generally call this routine themselves.
3027bcf0153eSBarry Smith 
30281cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetPreStep()`, `TSPreStage()`, `TSPostStage()`, `TSPostStep()`
30293f2090d5SJed Brown @*/
3030d71ae5a4SJacob Faibussowitsch PetscErrorCode TSPreStep(TS ts)
3031d71ae5a4SJacob Faibussowitsch {
30323f2090d5SJed Brown   PetscFunctionBegin;
30330700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3034ae60f76fSBarry Smith   if (ts->prestep) {
30355efd42a4SStefano Zampini     Vec              U;
3036ef8d1ce0SJohann Rudi     PetscObjectId    idprev;
3037ef8d1ce0SJohann Rudi     PetscBool        sameObject;
30385efd42a4SStefano Zampini     PetscObjectState sprev, spost;
30395efd42a4SStefano Zampini 
30409566063dSJacob Faibussowitsch     PetscCall(TSGetSolution(ts, &U));
30419566063dSJacob Faibussowitsch     PetscCall(PetscObjectGetId((PetscObject)U, &idprev));
30429566063dSJacob Faibussowitsch     PetscCall(PetscObjectStateGet((PetscObject)U, &sprev));
304325e27a38SBarry Smith     PetscCallBack("TS callback preset", (*ts->prestep)(ts));
30449566063dSJacob Faibussowitsch     PetscCall(TSGetSolution(ts, &U));
30459566063dSJacob Faibussowitsch     PetscCall(PetscObjectCompareId((PetscObject)U, idprev, &sameObject));
30469566063dSJacob Faibussowitsch     PetscCall(PetscObjectStateGet((PetscObject)U, &spost));
30479566063dSJacob Faibussowitsch     if (!sameObject || sprev != spost) PetscCall(TSRestartStep(ts));
3048312ce896SJed Brown   }
30493ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
30503f2090d5SJed Brown }
30513f2090d5SJed Brown 
3052b8123daeSJed Brown /*@C
3053b8123daeSJed Brown   TSSetPreStage - Sets the general-purpose function
3054b8123daeSJed Brown   called once at the beginning of each stage.
3055b8123daeSJed Brown 
3056c3339decSBarry Smith   Logically Collective
3057b8123daeSJed Brown 
3058b8123daeSJed Brown   Input Parameters:
3059bcf0153eSBarry Smith + ts   - The `TS` context obtained from `TSCreate()`
3060b8123daeSJed Brown - func - The function
3061b8123daeSJed Brown 
306220f4b53cSBarry Smith   Calling sequence of `func`:
306314d0ab18SJacob Faibussowitsch + ts        - the `TS` context
306414d0ab18SJacob Faibussowitsch - stagetime - the stage time
3065b8123daeSJed Brown 
3066b8123daeSJed Brown   Level: intermediate
3067b8123daeSJed Brown 
3068b8123daeSJed Brown   Note:
3069b8123daeSJed Brown   There may be several stages per time step. If the solve for a given stage fails, the step may be rejected and retried.
3070bcf0153eSBarry Smith   The time step number being computed can be queried using `TSGetStepNumber()` and the total size of the step being
3071bcf0153eSBarry Smith   attempted can be obtained using `TSGetTimeStep()`. The time at the start of the step is available via `TSGetTime()`.
3072b8123daeSJed Brown 
30731cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetPostStage()`, `TSSetPreStep()`, `TSSetPostStep()`, `TSGetApplicationContext()`
3074b8123daeSJed Brown @*/
307514d0ab18SJacob Faibussowitsch PetscErrorCode TSSetPreStage(TS ts, PetscErrorCode (*func)(TS ts, PetscReal stagetime))
3076d71ae5a4SJacob Faibussowitsch {
3077b8123daeSJed Brown   PetscFunctionBegin;
3078b8123daeSJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3079ae60f76fSBarry Smith   ts->prestage = func;
30803ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
3081b8123daeSJed Brown }
3082b8123daeSJed Brown 
30839be3e283SDebojyoti Ghosh /*@C
3084bcf0153eSBarry Smith   TSSetPostStage - Sets the general-purpose function, provided with `TSSetPostStep()`,
30859be3e283SDebojyoti Ghosh   called once at the end of each stage.
30869be3e283SDebojyoti Ghosh 
3087c3339decSBarry Smith   Logically Collective
30889be3e283SDebojyoti Ghosh 
30899be3e283SDebojyoti Ghosh   Input Parameters:
3090bcf0153eSBarry Smith + ts   - The `TS` context obtained from `TSCreate()`
30919be3e283SDebojyoti Ghosh - func - The function
30929be3e283SDebojyoti Ghosh 
309320f4b53cSBarry Smith   Calling sequence of `func`:
309414d0ab18SJacob Faibussowitsch + ts         - the `TS` context
309514d0ab18SJacob Faibussowitsch . stagetime  - the stage time
309614d0ab18SJacob Faibussowitsch . stageindex - the stage index
309714d0ab18SJacob Faibussowitsch - Y          - Array of vectors (of size = total number of stages) with the stage solutions
30989be3e283SDebojyoti Ghosh 
30999be3e283SDebojyoti Ghosh   Level: intermediate
31009be3e283SDebojyoti Ghosh 
31019be3e283SDebojyoti Ghosh   Note:
31029be3e283SDebojyoti Ghosh   There may be several stages per time step. If the solve for a given stage fails, the step may be rejected and retried.
3103bcf0153eSBarry Smith   The time step number being computed can be queried using `TSGetStepNumber()` and the total size of the step being
3104bcf0153eSBarry Smith   attempted can be obtained using `TSGetTimeStep()`. The time at the start of the step is available via `TSGetTime()`.
31059be3e283SDebojyoti Ghosh 
31061cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetPreStage()`, `TSSetPreStep()`, `TSSetPostStep()`, `TSGetApplicationContext()`
31079be3e283SDebojyoti Ghosh @*/
310814d0ab18SJacob Faibussowitsch PetscErrorCode TSSetPostStage(TS ts, PetscErrorCode (*func)(TS ts, PetscReal stagetime, PetscInt stageindex, Vec *Y))
3109d71ae5a4SJacob Faibussowitsch {
31109be3e283SDebojyoti Ghosh   PetscFunctionBegin;
31119be3e283SDebojyoti Ghosh   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
31129be3e283SDebojyoti Ghosh   ts->poststage = func;
31133ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
31149be3e283SDebojyoti Ghosh }
31159be3e283SDebojyoti Ghosh 
3116c688d042SShri Abhyankar /*@C
3117c688d042SShri Abhyankar   TSSetPostEvaluate - Sets the general-purpose function
3118c688d042SShri Abhyankar   called once at the end of each step evaluation.
3119c688d042SShri Abhyankar 
3120c3339decSBarry Smith   Logically Collective
3121c688d042SShri Abhyankar 
3122c688d042SShri Abhyankar   Input Parameters:
3123bcf0153eSBarry Smith + ts   - The `TS` context obtained from `TSCreate()`
3124c688d042SShri Abhyankar - func - The function
3125c688d042SShri Abhyankar 
312620f4b53cSBarry Smith   Calling sequence of `func`:
312714d0ab18SJacob Faibussowitsch . ts - the `TS` context
3128c688d042SShri Abhyankar 
3129c688d042SShri Abhyankar   Level: intermediate
3130c688d042SShri Abhyankar 
3131c688d042SShri Abhyankar   Note:
3132bcf0153eSBarry Smith   Semantically, `TSSetPostEvaluate()` differs from `TSSetPostStep()` since the function it sets is called before event-handling
3133bcf0153eSBarry Smith   thus guaranteeing the same solution (computed by the time-stepper) will be passed to it. On the other hand, `TSPostStep()`
3134bcf0153eSBarry Smith   may be passed a different solution, possibly changed by the event handler. `TSPostEvaluate()` is called after the next step
3135bcf0153eSBarry Smith   solution is evaluated allowing to modify it, if need be. The solution can be obtained with `TSGetSolution()`, the time step
3136bcf0153eSBarry Smith   with `TSGetTimeStep()`, and the time at the start of the step is available via `TSGetTime()`
3137c688d042SShri Abhyankar 
31381cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetPreStage()`, `TSSetPreStep()`, `TSSetPostStep()`, `TSGetApplicationContext()`
3139c688d042SShri Abhyankar @*/
314014d0ab18SJacob Faibussowitsch PetscErrorCode TSSetPostEvaluate(TS ts, PetscErrorCode (*func)(TS ts))
3141d71ae5a4SJacob Faibussowitsch {
3142c688d042SShri Abhyankar   PetscFunctionBegin;
3143c688d042SShri Abhyankar   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3144c688d042SShri Abhyankar   ts->postevaluate = func;
31453ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
3146c688d042SShri Abhyankar }
3147c688d042SShri Abhyankar 
3148b8123daeSJed Brown /*@
3149bcf0153eSBarry Smith   TSPreStage - Runs the user-defined pre-stage function set using `TSSetPreStage()`
3150b8123daeSJed Brown 
3151c3339decSBarry Smith   Collective
3152b8123daeSJed Brown 
3153b8123daeSJed Brown   Input Parameters:
315414d0ab18SJacob Faibussowitsch + ts        - The `TS` context obtained from `TSCreate()`
315514d0ab18SJacob Faibussowitsch - stagetime - The absolute time of the current stage
3156b8123daeSJed Brown 
3157b8123daeSJed Brown   Level: developer
3158b8123daeSJed Brown 
3159bcf0153eSBarry Smith   Note:
3160bcf0153eSBarry Smith   `TSPreStage()` is typically used within time stepping implementations,
3161bcf0153eSBarry Smith   most users would not generally call this routine themselves.
3162bcf0153eSBarry Smith 
31631cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSPostStage()`, `TSSetPreStep()`, `TSPreStep()`, `TSPostStep()`
3164b8123daeSJed Brown @*/
3165d71ae5a4SJacob Faibussowitsch PetscErrorCode TSPreStage(TS ts, PetscReal stagetime)
3166d71ae5a4SJacob Faibussowitsch {
3167b8123daeSJed Brown   PetscFunctionBegin;
3168b8123daeSJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
31691e66621cSBarry Smith   if (ts->prestage) PetscCallBack("TS callback prestage", (*ts->prestage)(ts, stagetime));
31703ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
3171b8123daeSJed Brown }
3172b8123daeSJed Brown 
31739be3e283SDebojyoti Ghosh /*@
3174bcf0153eSBarry Smith   TSPostStage - Runs the user-defined post-stage function set using `TSSetPostStage()`
31759be3e283SDebojyoti Ghosh 
3176c3339decSBarry Smith   Collective
31779be3e283SDebojyoti Ghosh 
31789be3e283SDebojyoti Ghosh   Input Parameters:
317914d0ab18SJacob Faibussowitsch + ts         - The `TS` context obtained from `TSCreate()`
318014d0ab18SJacob Faibussowitsch . stagetime  - The absolute time of the current stage
318114d0ab18SJacob Faibussowitsch . stageindex - Stage number
318214d0ab18SJacob Faibussowitsch - Y          - Array of vectors (of size = total number of stages) with the stage solutions
31839be3e283SDebojyoti Ghosh 
31849be3e283SDebojyoti Ghosh   Level: developer
31859be3e283SDebojyoti Ghosh 
3186bcf0153eSBarry Smith   Note:
3187bcf0153eSBarry Smith   `TSPostStage()` is typically used within time stepping implementations,
3188bcf0153eSBarry Smith   most users would not generally call this routine themselves.
3189bcf0153eSBarry Smith 
31901cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSPreStage()`, `TSSetPreStep()`, `TSPreStep()`, `TSPostStep()`
31919be3e283SDebojyoti Ghosh @*/
3192d71ae5a4SJacob Faibussowitsch PetscErrorCode TSPostStage(TS ts, PetscReal stagetime, PetscInt stageindex, Vec *Y)
3193d71ae5a4SJacob Faibussowitsch {
31949be3e283SDebojyoti Ghosh   PetscFunctionBegin;
31959be3e283SDebojyoti Ghosh   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
31961e66621cSBarry Smith   if (ts->poststage) PetscCallBack("TS callback poststage", (*ts->poststage)(ts, stagetime, stageindex, Y));
31973ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
31989be3e283SDebojyoti Ghosh }
31999be3e283SDebojyoti Ghosh 
3200c688d042SShri Abhyankar /*@
3201bcf0153eSBarry Smith   TSPostEvaluate - Runs the user-defined post-evaluate function set using `TSSetPostEvaluate()`
3202c688d042SShri Abhyankar 
3203c3339decSBarry Smith   Collective
3204c688d042SShri Abhyankar 
32052fe279fdSBarry Smith   Input Parameter:
3206bcf0153eSBarry Smith . ts - The `TS` context obtained from `TSCreate()`
3207c688d042SShri Abhyankar 
3208c688d042SShri Abhyankar   Level: developer
3209c688d042SShri Abhyankar 
3210bcf0153eSBarry Smith   Note:
3211bcf0153eSBarry Smith   `TSPostEvaluate()` is typically used within time stepping implementations,
3212bcf0153eSBarry Smith   most users would not generally call this routine themselves.
3213bcf0153eSBarry Smith 
32141cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetPostEvaluate()`, `TSSetPreStep()`, `TSPreStep()`, `TSPostStep()`
3215c688d042SShri Abhyankar @*/
3216d71ae5a4SJacob Faibussowitsch PetscErrorCode TSPostEvaluate(TS ts)
3217d71ae5a4SJacob Faibussowitsch {
3218c688d042SShri Abhyankar   PetscFunctionBegin;
3219c688d042SShri Abhyankar   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3220c688d042SShri Abhyankar   if (ts->postevaluate) {
3221dcb233daSLisandro Dalcin     Vec              U;
3222dcb233daSLisandro Dalcin     PetscObjectState sprev, spost;
3223dcb233daSLisandro Dalcin 
32249566063dSJacob Faibussowitsch     PetscCall(TSGetSolution(ts, &U));
32259566063dSJacob Faibussowitsch     PetscCall(PetscObjectStateGet((PetscObject)U, &sprev));
322625e27a38SBarry Smith     PetscCallBack("TS callback postevaluate", (*ts->postevaluate)(ts));
32279566063dSJacob Faibussowitsch     PetscCall(PetscObjectStateGet((PetscObject)U, &spost));
32289566063dSJacob Faibussowitsch     if (sprev != spost) PetscCall(TSRestartStep(ts));
3229c688d042SShri Abhyankar   }
32303ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
3231c688d042SShri Abhyankar }
3232c688d042SShri Abhyankar 
3233ac226902SBarry Smith /*@C
3234000e7ae3SMatthew Knepley   TSSetPostStep - Sets the general-purpose function
32353f2090d5SJed Brown   called once at the end of each time step.
3236000e7ae3SMatthew Knepley 
3237c3339decSBarry Smith   Logically Collective
3238000e7ae3SMatthew Knepley 
3239000e7ae3SMatthew Knepley   Input Parameters:
3240bcf0153eSBarry Smith + ts   - The `TS` context obtained from `TSCreate()`
3241000e7ae3SMatthew Knepley - func - The function
3242000e7ae3SMatthew Knepley 
324320f4b53cSBarry Smith   Calling sequence of `func`:
324414d0ab18SJacob Faibussowitsch . ts - the `TS` context
3245000e7ae3SMatthew Knepley 
3246000e7ae3SMatthew Knepley   Level: intermediate
3247000e7ae3SMatthew Knepley 
3248bcf0153eSBarry Smith   Note:
3249195e9b02SBarry Smith   The function set by `TSSetPostStep()` is called after each successful step. The solution vector
3250bcf0153eSBarry Smith   obtained by `TSGetSolution()` may be different than that computed at the step end if the event handler
3251bcf0153eSBarry Smith   locates an event and `TSPostEvent()` modifies it. Use `TSSetPostEvaluate()` if an unmodified solution is needed instead.
3252bcf0153eSBarry Smith 
32531cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetPreStep()`, `TSSetPreStage()`, `TSSetPostEvaluate()`, `TSGetTimeStep()`, `TSGetStepNumber()`, `TSGetTime()`, `TSRestartStep()`
3254000e7ae3SMatthew Knepley @*/
325514d0ab18SJacob Faibussowitsch PetscErrorCode TSSetPostStep(TS ts, PetscErrorCode (*func)(TS ts))
3256d71ae5a4SJacob Faibussowitsch {
3257000e7ae3SMatthew Knepley   PetscFunctionBegin;
32580700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3259ae60f76fSBarry Smith   ts->poststep = func;
32603ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
3261000e7ae3SMatthew Knepley }
3262000e7ae3SMatthew Knepley 
326309ee8438SJed Brown /*@
3264195e9b02SBarry Smith   TSPostStep - Runs the user-defined post-step function that was set with `TSSetPostStep()`
32653f2090d5SJed Brown 
3266c3339decSBarry Smith   Collective
32673f2090d5SJed Brown 
32682fe279fdSBarry Smith   Input Parameter:
3269bcf0153eSBarry Smith . ts - The `TS` context obtained from `TSCreate()`
32703f2090d5SJed Brown 
3271bcf0153eSBarry Smith   Note:
3272bcf0153eSBarry Smith   `TSPostStep()` is typically used within time stepping implementations,
32733f2090d5SJed Brown   so most users would not generally call this routine themselves.
32743f2090d5SJed Brown 
32753f2090d5SJed Brown   Level: developer
32763f2090d5SJed Brown 
32771cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetPreStep()`, `TSSetPreStage()`, `TSSetPostEvaluate()`, `TSGetTimeStep()`, `TSGetStepNumber()`, `TSGetTime()`, `TSSetPotsStep()`
32783f2090d5SJed Brown @*/
3279d71ae5a4SJacob Faibussowitsch PetscErrorCode TSPostStep(TS ts)
3280d71ae5a4SJacob Faibussowitsch {
32813f2090d5SJed Brown   PetscFunctionBegin;
32820700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3283ae60f76fSBarry Smith   if (ts->poststep) {
32845efd42a4SStefano Zampini     Vec              U;
3285ef8d1ce0SJohann Rudi     PetscObjectId    idprev;
3286ef8d1ce0SJohann Rudi     PetscBool        sameObject;
32875efd42a4SStefano Zampini     PetscObjectState sprev, spost;
32885efd42a4SStefano Zampini 
32899566063dSJacob Faibussowitsch     PetscCall(TSGetSolution(ts, &U));
32909566063dSJacob Faibussowitsch     PetscCall(PetscObjectGetId((PetscObject)U, &idprev));
32919566063dSJacob Faibussowitsch     PetscCall(PetscObjectStateGet((PetscObject)U, &sprev));
329225e27a38SBarry Smith     PetscCallBack("TS callback poststep", (*ts->poststep)(ts));
32939566063dSJacob Faibussowitsch     PetscCall(TSGetSolution(ts, &U));
32949566063dSJacob Faibussowitsch     PetscCall(PetscObjectCompareId((PetscObject)U, idprev, &sameObject));
32959566063dSJacob Faibussowitsch     PetscCall(PetscObjectStateGet((PetscObject)U, &spost));
32969566063dSJacob Faibussowitsch     if (!sameObject || sprev != spost) PetscCall(TSRestartStep(ts));
329772ac3e02SJed Brown   }
32983ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
32993f2090d5SJed Brown }
33003f2090d5SJed Brown 
3301cd652676SJed Brown /*@
3302cd652676SJed Brown   TSInterpolate - Interpolate the solution computed during the previous step to an arbitrary location in the interval
3303cd652676SJed Brown 
3304c3339decSBarry Smith   Collective
3305cd652676SJed Brown 
33064165533cSJose E. Roman   Input Parameters:
3307cd652676SJed Brown + ts - time stepping context
3308cd652676SJed Brown - t  - time to interpolate to
3309cd652676SJed Brown 
33104165533cSJose E. Roman   Output Parameter:
33110910c330SBarry Smith . U - state at given time
3312cd652676SJed Brown 
3313cd652676SJed Brown   Level: intermediate
3314cd652676SJed Brown 
3315b43aa488SJacob Faibussowitsch   Developer Notes:
3316bcf0153eSBarry Smith   `TSInterpolate()` and the storing of previous steps/stages should be generalized to support delay differential equations and continuous adjoints.
3317cd652676SJed Brown 
33181cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetExactFinalTime()`, `TSSolve()`
3319cd652676SJed Brown @*/
3320d71ae5a4SJacob Faibussowitsch PetscErrorCode TSInterpolate(TS ts, PetscReal t, Vec U)
3321d71ae5a4SJacob Faibussowitsch {
3322cd652676SJed Brown   PetscFunctionBegin;
3323cd652676SJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3324b06615a5SLisandro Dalcin   PetscValidHeaderSpecific(U, VEC_CLASSID, 3);
332563a3b9bcSJacob 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);
3326dbbe0bcdSBarry Smith   PetscUseTypeMethod(ts, interpolate, t, U);
33273ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
3328cd652676SJed Brown }
3329cd652676SJed Brown 
3330d763cef2SBarry Smith /*@
33316d9e5789SSean Farley   TSStep - Steps one time step
3332d763cef2SBarry Smith 
3333c3339decSBarry Smith   Collective
3334d763cef2SBarry Smith 
3335d763cef2SBarry Smith   Input Parameter:
3336bcf0153eSBarry Smith . ts - the `TS` context obtained from `TSCreate()`
3337d763cef2SBarry Smith 
333827829d71SBarry Smith   Level: developer
3339d763cef2SBarry Smith 
3340b8123daeSJed Brown   Notes:
3341bcf0153eSBarry Smith   The public interface for the ODE/DAE solvers is `TSSolve()`, you should almost for sure be using that routine and not this routine.
334227829d71SBarry Smith 
3343bcf0153eSBarry Smith   The hook set using `TSSetPreStep()` is called before each attempt to take the step. In general, the time step size may
3344b8123daeSJed Brown   be changed due to adaptive error controller or solve failures. Note that steps may contain multiple stages.
3345b8123daeSJed Brown 
3346bcf0153eSBarry Smith   This may over-step the final time provided in `TSSetMaxTime()` depending on the time-step used. `TSSolve()` interpolates to exactly the
3347bcf0153eSBarry Smith   time provided in `TSSetMaxTime()`. One can use `TSInterpolate()` to determine an interpolated solution within the final timestep.
334825cb2221SBarry Smith 
33491cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSCreate()`, `TSSetUp()`, `TSDestroy()`, `TSSolve()`, `TSSetPreStep()`, `TSSetPreStage()`, `TSSetPostStage()`, `TSInterpolate()`
3350d763cef2SBarry Smith @*/
3351d71ae5a4SJacob Faibussowitsch PetscErrorCode TSStep(TS ts)
3352d71ae5a4SJacob Faibussowitsch {
3353fffbeea8SBarry Smith   static PetscBool cite = PETSC_FALSE;
3354be5899b3SLisandro Dalcin   PetscReal        ptime;
3355d763cef2SBarry Smith 
3356d763cef2SBarry Smith   PetscFunctionBegin;
33570700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3358d0609cedSBarry Smith   PetscCall(PetscCitationsRegister("@article{tspaper,\n"
3359fffbeea8SBarry Smith                                    "  title         = {{PETSc/TS}: A Modern Scalable {DAE/ODE} Solver Library},\n"
3360f1d62c27SHong Zhang                                    "  author        = {Abhyankar, Shrirang and Brown, Jed and Constantinescu, Emil and Ghosh, Debojyoti and Smith, Barry F. and Zhang, Hong},\n"
3361f1d62c27SHong Zhang                                    "  journal       = {arXiv e-preprints},\n"
3362f1d62c27SHong Zhang                                    "  eprint        = {1806.01437},\n"
3363f1d62c27SHong Zhang                                    "  archivePrefix = {arXiv},\n"
33649371c9d4SSatish Balay                                    "  year          = {2018}\n}\n",
33659371c9d4SSatish Balay                                    &cite));
33669566063dSJacob Faibussowitsch   PetscCall(TSSetUp(ts));
33679566063dSJacob Faibussowitsch   PetscCall(TSTrajectorySetUp(ts->trajectory, ts));
3368d405a339SMatthew Knepley 
33693c633725SBarry 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>");
33703c633725SBarry 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()");
33713c633725SBarry 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");
3372a6772fa2SLisandro Dalcin 
3373be5899b3SLisandro Dalcin   if (!ts->steps) ts->ptime_prev = ts->ptime;
33749371c9d4SSatish Balay   ptime                   = ts->ptime;
33759371c9d4SSatish Balay   ts->ptime_prev_rollback = ts->ptime_prev;
33762808aa04SLisandro Dalcin   ts->reason              = TS_CONVERGED_ITERATING;
3377fc8dbba5SLisandro Dalcin 
33789566063dSJacob Faibussowitsch   PetscCall(PetscLogEventBegin(TS_Step, ts, 0, 0, 0));
3379dbbe0bcdSBarry Smith   PetscUseTypeMethod(ts, step);
33809566063dSJacob Faibussowitsch   PetscCall(PetscLogEventEnd(TS_Step, ts, 0, 0, 0));
3381fc8dbba5SLisandro Dalcin 
33829371c9d4SSatish 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)
33839371c9d4SSatish Balay     PetscCall(VecCopy(ts->vec_sol, ts->tspan->vecs_sol[ts->tspan->spanctr++]));
3384fc8dbba5SLisandro Dalcin   if (ts->reason >= 0) {
3385be5899b3SLisandro Dalcin     ts->ptime_prev = ptime;
33862808aa04SLisandro Dalcin     ts->steps++;
3387be5899b3SLisandro Dalcin     ts->steprollback = PETSC_FALSE;
338828d5b5d6SLisandro Dalcin     ts->steprestart  = PETSC_FALSE;
3389d2daff3dSHong Zhang   }
3390fc8dbba5SLisandro Dalcin   if (!ts->reason) {
339108c7845fSBarry Smith     if (ts->steps >= ts->max_steps) ts->reason = TS_CONVERGED_ITS;
339208c7845fSBarry Smith     else if (ts->ptime >= ts->max_time) ts->reason = TS_CONVERGED_TIME;
339308c7845fSBarry Smith   }
3394fc8dbba5SLisandro Dalcin 
33955c9bbc89SJed Brown   if (ts->reason < 0 && ts->errorifstepfailed) {
33965c9bbc89SJed Brown     PetscCall(TSMonitorCancel(ts));
33975c9bbc89SJed 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]);
33985c9bbc89SJed Brown     SETERRQ(PetscObjectComm((PetscObject)ts), PETSC_ERR_NOT_CONVERGED, "TSStep has failed due to %s", TSConvergedReasons[ts->reason]);
33995c9bbc89SJed Brown   }
34003ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
340108c7845fSBarry Smith }
340208c7845fSBarry Smith 
340308c7845fSBarry Smith /*@
34047cbde773SLisandro Dalcin   TSEvaluateWLTE - Evaluate the weighted local truncation error norm
34057cbde773SLisandro Dalcin   at the end of a time step with a given order of accuracy.
34067cbde773SLisandro Dalcin 
3407c3339decSBarry Smith   Collective
34087cbde773SLisandro Dalcin 
34094165533cSJose E. Roman   Input Parameters:
34107cbde773SLisandro Dalcin + ts        - time stepping context
3411bcf0153eSBarry Smith - wnormtype - norm type, either `NORM_2` or `NORM_INFINITY`
34127cbde773SLisandro Dalcin 
341397bb3fdcSJose E. Roman   Input/Output Parameter:
3414bcf0153eSBarry Smith . order - optional, desired order for the error evaluation or `PETSC_DECIDE`;
341597bb3fdcSJose E. Roman            on output, the actual order of the error evaluation
341697bb3fdcSJose E. Roman 
341797bb3fdcSJose E. Roman   Output Parameter:
341897bb3fdcSJose E. Roman . wlte - the weighted local truncation error norm
34197cbde773SLisandro Dalcin 
34207cbde773SLisandro Dalcin   Level: advanced
34217cbde773SLisandro Dalcin 
3422bcf0153eSBarry Smith   Note:
34237cbde773SLisandro Dalcin   If the timestepper cannot evaluate the error in a particular step
34247cbde773SLisandro Dalcin   (eg. in the first step or restart steps after event handling),
34257cbde773SLisandro Dalcin   this routine returns wlte=-1.0 .
34267cbde773SLisandro Dalcin 
34271cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSStep()`, `TSAdapt`, `TSErrorWeightedNorm()`
34287cbde773SLisandro Dalcin @*/
3429d71ae5a4SJacob Faibussowitsch PetscErrorCode TSEvaluateWLTE(TS ts, NormType wnormtype, PetscInt *order, PetscReal *wlte)
3430d71ae5a4SJacob Faibussowitsch {
34317cbde773SLisandro Dalcin   PetscFunctionBegin;
34327cbde773SLisandro Dalcin   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
34337cbde773SLisandro Dalcin   PetscValidType(ts, 1);
3434064a246eSJacob Faibussowitsch   PetscValidLogicalCollectiveEnum(ts, wnormtype, 2);
34354f572ea9SToby Isaac   if (order) PetscAssertPointer(order, 3);
34367cbde773SLisandro Dalcin   if (order) PetscValidLogicalCollectiveInt(ts, *order, 3);
34374f572ea9SToby Isaac   PetscAssertPointer(wlte, 4);
34383c633725SBarry Smith   PetscCheck(wnormtype == NORM_2 || wnormtype == NORM_INFINITY, PetscObjectComm((PetscObject)ts), PETSC_ERR_SUP, "No support for norm type %s", NormTypes[wnormtype]);
3439dbbe0bcdSBarry Smith   PetscUseTypeMethod(ts, evaluatewlte, wnormtype, order, wlte);
34403ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
34417cbde773SLisandro Dalcin }
34427cbde773SLisandro Dalcin 
344305175c85SJed Brown /*@
344405175c85SJed Brown   TSEvaluateStep - Evaluate the solution at the end of a time step with a given order of accuracy.
344505175c85SJed Brown 
3446c3339decSBarry Smith   Collective
344705175c85SJed Brown 
34484165533cSJose E. Roman   Input Parameters:
34491c3436cfSJed Brown + ts    - time stepping context
34501c3436cfSJed Brown . order - desired order of accuracy
3451195e9b02SBarry Smith - done  - whether the step was evaluated at this order (pass `NULL` to generate an error if not available)
345205175c85SJed Brown 
34534165533cSJose E. Roman   Output Parameter:
34540910c330SBarry Smith . U - state at the end of the current step
345505175c85SJed Brown 
345605175c85SJed Brown   Level: advanced
345705175c85SJed Brown 
3458108c343cSJed Brown   Notes:
3459108c343cSJed Brown   This function cannot be called until all stages have been evaluated.
3460108c343cSJed Brown 
3461bcf0153eSBarry 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.
3462bcf0153eSBarry Smith 
34631cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSStep()`, `TSAdapt`
346405175c85SJed Brown @*/
3465d71ae5a4SJacob Faibussowitsch PetscErrorCode TSEvaluateStep(TS ts, PetscInt order, Vec U, PetscBool *done)
3466d71ae5a4SJacob Faibussowitsch {
346705175c85SJed Brown   PetscFunctionBegin;
346805175c85SJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
346905175c85SJed Brown   PetscValidType(ts, 1);
34700910c330SBarry Smith   PetscValidHeaderSpecific(U, VEC_CLASSID, 3);
3471dbbe0bcdSBarry Smith   PetscUseTypeMethod(ts, evaluatestep, order, U, done);
34723ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
347305175c85SJed Brown }
347405175c85SJed Brown 
3475aad739acSMatthew G. Knepley /*@C
34762e61be88SMatthew G. Knepley   TSGetComputeInitialCondition - Get the function used to automatically compute an initial condition for the timestepping.
3477aad739acSMatthew G. Knepley 
3478aad739acSMatthew G. Knepley   Not collective
3479aad739acSMatthew G. Knepley 
34804165533cSJose E. Roman   Input Parameter:
3481aad739acSMatthew G. Knepley . ts - time stepping context
3482aad739acSMatthew G. Knepley 
34834165533cSJose E. Roman   Output Parameter:
3484b43aa488SJacob Faibussowitsch . initCondition - The function which computes an initial condition
3485aad739acSMatthew G. Knepley 
348620f4b53cSBarry Smith   Calling sequence of `initCondition`:
348720f4b53cSBarry Smith + ts - The timestepping context
348820f4b53cSBarry Smith - u  - The input vector in which the initial condition is stored
3489bcf0153eSBarry Smith 
3490aad739acSMatthew G. Knepley   Level: advanced
3491aad739acSMatthew G. Knepley 
34921cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetComputeInitialCondition()`, `TSComputeInitialCondition()`
3493aad739acSMatthew G. Knepley @*/
349414d0ab18SJacob Faibussowitsch PetscErrorCode TSGetComputeInitialCondition(TS ts, PetscErrorCode (**initCondition)(TS ts, Vec u))
3495d71ae5a4SJacob Faibussowitsch {
3496aad739acSMatthew G. Knepley   PetscFunctionBegin;
3497aad739acSMatthew G. Knepley   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
34984f572ea9SToby Isaac   PetscAssertPointer(initCondition, 2);
34992e61be88SMatthew G. Knepley   *initCondition = ts->ops->initcondition;
35003ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
3501aad739acSMatthew G. Knepley }
3502aad739acSMatthew G. Knepley 
3503aad739acSMatthew G. Knepley /*@C
35042e61be88SMatthew G. Knepley   TSSetComputeInitialCondition - Set the function used to automatically compute an initial condition for the timestepping.
3505aad739acSMatthew G. Knepley 
3506c3339decSBarry Smith   Logically collective
3507aad739acSMatthew G. Knepley 
35084165533cSJose E. Roman   Input Parameters:
3509aad739acSMatthew G. Knepley + ts            - time stepping context
35102e61be88SMatthew G. Knepley - initCondition - The function which computes an initial condition
3511aad739acSMatthew G. Knepley 
351220f4b53cSBarry Smith   Calling sequence of `initCondition`:
3513a96d6ef6SBarry Smith + ts - The timestepping context
351414d0ab18SJacob Faibussowitsch - e  - The input vector in which the initial condition is to be stored
3515aad739acSMatthew G. Knepley 
3516bcf0153eSBarry Smith   Level: advanced
3517bcf0153eSBarry Smith 
35181cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSGetComputeInitialCondition()`, `TSComputeInitialCondition()`
3519aad739acSMatthew G. Knepley @*/
352014d0ab18SJacob Faibussowitsch PetscErrorCode TSSetComputeInitialCondition(TS ts, PetscErrorCode (*initCondition)(TS ts, Vec e))
3521d71ae5a4SJacob Faibussowitsch {
3522aad739acSMatthew G. Knepley   PetscFunctionBegin;
3523aad739acSMatthew G. Knepley   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
35242e61be88SMatthew G. Knepley   PetscValidFunction(initCondition, 2);
35252e61be88SMatthew G. Knepley   ts->ops->initcondition = initCondition;
35263ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
3527aad739acSMatthew G. Knepley }
3528aad739acSMatthew G. Knepley 
3529aad739acSMatthew G. Knepley /*@
3530bcf0153eSBarry Smith   TSComputeInitialCondition - Compute an initial condition for the timestepping using the function previously set with `TSSetComputeInitialCondition()`
3531aad739acSMatthew G. Knepley 
3532c3339decSBarry Smith   Collective
3533aad739acSMatthew G. Knepley 
35344165533cSJose E. Roman   Input Parameters:
3535aad739acSMatthew G. Knepley + ts - time stepping context
3536bcf0153eSBarry Smith - u  - The `Vec` to store the condition in which will be used in `TSSolve()`
3537aad739acSMatthew G. Knepley 
3538aad739acSMatthew G. Knepley   Level: advanced
3539aad739acSMatthew G. Knepley 
35401cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSGetComputeInitialCondition()`, `TSSetComputeInitialCondition()`, `TSSolve()`
3541aad739acSMatthew G. Knepley @*/
3542d71ae5a4SJacob Faibussowitsch PetscErrorCode TSComputeInitialCondition(TS ts, Vec u)
3543d71ae5a4SJacob Faibussowitsch {
3544aad739acSMatthew G. Knepley   PetscFunctionBegin;
3545aad739acSMatthew G. Knepley   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3546aad739acSMatthew G. Knepley   PetscValidHeaderSpecific(u, VEC_CLASSID, 2);
3547dbbe0bcdSBarry Smith   PetscTryTypeMethod(ts, initcondition, u);
35483ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
3549aad739acSMatthew G. Knepley }
3550aad739acSMatthew G. Knepley 
3551aad739acSMatthew G. Knepley /*@C
3552aad739acSMatthew G. Knepley   TSGetComputeExactError - Get the function used to automatically compute the exact error for the timestepping.
3553aad739acSMatthew G. Knepley 
3554aad739acSMatthew G. Knepley   Not collective
3555aad739acSMatthew G. Knepley 
35564165533cSJose E. Roman   Input Parameter:
3557aad739acSMatthew G. Knepley . ts - time stepping context
3558aad739acSMatthew G. Knepley 
35594165533cSJose E. Roman   Output Parameter:
3560aad739acSMatthew G. Knepley . exactError - The function which computes the solution error
3561aad739acSMatthew G. Knepley 
356220f4b53cSBarry Smith   Calling sequence of `exactError`:
3563a96d6ef6SBarry Smith + ts - The timestepping context
3564a96d6ef6SBarry Smith . u  - The approximate solution vector
356520f4b53cSBarry Smith - e  - The vector in which the error is stored
3566aad739acSMatthew G. Knepley 
3567bcf0153eSBarry Smith   Level: advanced
3568bcf0153eSBarry Smith 
356942747ad1SJacob Faibussowitsch .seealso: [](ch_ts), `TS`, `TSComputeExactError()`
3570aad739acSMatthew G. Knepley @*/
357114d0ab18SJacob Faibussowitsch PetscErrorCode TSGetComputeExactError(TS ts, PetscErrorCode (**exactError)(TS ts, Vec u, Vec e))
3572d71ae5a4SJacob Faibussowitsch {
3573aad739acSMatthew G. Knepley   PetscFunctionBegin;
3574aad739acSMatthew G. Knepley   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
35754f572ea9SToby Isaac   PetscAssertPointer(exactError, 2);
3576aad739acSMatthew G. Knepley   *exactError = ts->ops->exacterror;
35773ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
3578aad739acSMatthew G. Knepley }
3579aad739acSMatthew G. Knepley 
3580aad739acSMatthew G. Knepley /*@C
3581aad739acSMatthew G. Knepley   TSSetComputeExactError - Set the function used to automatically compute the exact error for the timestepping.
3582aad739acSMatthew G. Knepley 
3583c3339decSBarry Smith   Logically collective
3584aad739acSMatthew G. Knepley 
35854165533cSJose E. Roman   Input Parameters:
3586aad739acSMatthew G. Knepley + ts         - time stepping context
3587aad739acSMatthew G. Knepley - exactError - The function which computes the solution error
3588aad739acSMatthew G. Knepley 
358920f4b53cSBarry Smith   Calling sequence of `exactError`:
3590a96d6ef6SBarry Smith + ts - The timestepping context
3591a96d6ef6SBarry Smith . u  - The approximate solution vector
359220f4b53cSBarry Smith - e  - The  vector in which the error is stored
3593aad739acSMatthew G. Knepley 
3594bcf0153eSBarry Smith   Level: advanced
3595bcf0153eSBarry Smith 
35961cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSGetComputeExactError()`, `TSComputeExactError()`
3597aad739acSMatthew G. Knepley @*/
359814d0ab18SJacob Faibussowitsch PetscErrorCode TSSetComputeExactError(TS ts, PetscErrorCode (*exactError)(TS ts, Vec u, Vec e))
3599d71ae5a4SJacob Faibussowitsch {
3600aad739acSMatthew G. Knepley   PetscFunctionBegin;
3601aad739acSMatthew G. Knepley   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3602f907fdbfSMatthew G. Knepley   PetscValidFunction(exactError, 2);
3603aad739acSMatthew G. Knepley   ts->ops->exacterror = exactError;
36043ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
3605aad739acSMatthew G. Knepley }
3606aad739acSMatthew G. Knepley 
3607aad739acSMatthew G. Knepley /*@
3608bcf0153eSBarry Smith   TSComputeExactError - Compute the solution error for the timestepping using the function previously set with `TSSetComputeExactError()`
3609aad739acSMatthew G. Knepley 
3610c3339decSBarry Smith   Collective
3611aad739acSMatthew G. Knepley 
36124165533cSJose E. Roman   Input Parameters:
3613aad739acSMatthew G. Knepley + ts - time stepping context
3614aad739acSMatthew G. Knepley . u  - The approximate solution
3615bcf0153eSBarry Smith - e  - The `Vec` used to store the error
3616aad739acSMatthew G. Knepley 
3617aad739acSMatthew G. Knepley   Level: advanced
3618aad739acSMatthew G. Knepley 
36191cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSGetComputeInitialCondition()`, `TSSetComputeInitialCondition()`, `TSSolve()`
3620aad739acSMatthew G. Knepley @*/
3621d71ae5a4SJacob Faibussowitsch PetscErrorCode TSComputeExactError(TS ts, Vec u, Vec e)
3622d71ae5a4SJacob Faibussowitsch {
3623aad739acSMatthew G. Knepley   PetscFunctionBegin;
3624aad739acSMatthew G. Knepley   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3625aad739acSMatthew G. Knepley   PetscValidHeaderSpecific(u, VEC_CLASSID, 2);
3626aad739acSMatthew G. Knepley   PetscValidHeaderSpecific(e, VEC_CLASSID, 3);
3627dbbe0bcdSBarry Smith   PetscTryTypeMethod(ts, exacterror, u, e);
36283ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
3629aad739acSMatthew G. Knepley }
3630aad739acSMatthew G. Knepley 
36316bd3a4fdSStefano Zampini /*@C
36326bd3a4fdSStefano Zampini   TSSetResize - Sets the resize callbacks.
36336bd3a4fdSStefano Zampini 
36346bd3a4fdSStefano Zampini   Logically Collective
36356bd3a4fdSStefano Zampini 
36366bd3a4fdSStefano Zampini   Input Parameters:
36376bd3a4fdSStefano Zampini + ts       - The `TS` context obtained from `TSCreate()`
36386bd3a4fdSStefano Zampini . setup    - The setup function
363914d0ab18SJacob Faibussowitsch . transfer - The transfer function
364014d0ab18SJacob Faibussowitsch - ctx      - [optional] The user-defined context
36416bd3a4fdSStefano Zampini 
36426bd3a4fdSStefano Zampini   Calling sequence of `setup`:
36438847d985SBarry Smith + ts     - the `TS` context
36446bd3a4fdSStefano Zampini . step   - the current step
36456bd3a4fdSStefano Zampini . time   - the current time
36466bd3a4fdSStefano Zampini . state  - the current vector of state
36476bd3a4fdSStefano Zampini . resize - (output parameter) `PETSC_TRUE` if need resizing, `PETSC_FALSE` otherwise
36486bd3a4fdSStefano Zampini - ctx    - user defined context
36496bd3a4fdSStefano Zampini 
36506bd3a4fdSStefano Zampini   Calling sequence of `transfer`:
36518847d985SBarry Smith + ts      - the `TS` context
36526bd3a4fdSStefano Zampini . nv      - the number of vectors to be transferred
36536bd3a4fdSStefano Zampini . vecsin  - array of vectors to be transferred
36546bd3a4fdSStefano Zampini . vecsout - array of transferred vectors
36556bd3a4fdSStefano Zampini - ctx     - user defined context
36566bd3a4fdSStefano Zampini 
36576bd3a4fdSStefano Zampini   Notes:
36586bd3a4fdSStefano Zampini   The `setup` function is called inside `TSSolve()` after `TSPostStep()` at the end of each time step
36596bd3a4fdSStefano Zampini   to determine if the problem size has changed.
36606bd3a4fdSStefano Zampini   If it is the case, the solver will collect the needed vectors that need to be
36616bd3a4fdSStefano Zampini   transferred from the old to the new sizes using `transfer`. These vectors will include the current
36626bd3a4fdSStefano Zampini   solution vector, and other vectors needed by the specific solver used.
36636bd3a4fdSStefano Zampini   For example, `TSBDF` uses previous solutions vectors to solve for the next time step.
36646bd3a4fdSStefano Zampini   Other application specific objects associated with the solver, i.e. Jacobian matrices and `DM`,
36656bd3a4fdSStefano Zampini   will be automatically reset if the sizes are changed and they must be specified again by the user
36666bd3a4fdSStefano Zampini   inside the `transfer` function.
36676bd3a4fdSStefano Zampini   The input and output arrays passed to `transfer` are allocated by PETSc.
36686bd3a4fdSStefano Zampini   Vectors in `vecsout` must be created by the user.
36696bd3a4fdSStefano Zampini   Ownership of vectors in `vecsout` is transferred to PETSc.
36706bd3a4fdSStefano Zampini 
36716bd3a4fdSStefano Zampini   Level: advanced
36726bd3a4fdSStefano Zampini 
36736bd3a4fdSStefano Zampini .seealso: [](ch_ts), `TS`, `TSSetDM()`, `TSSetIJacobian()`, `TSSetRHSJacobian()`
36746bd3a4fdSStefano Zampini @*/
367514d0ab18SJacob Faibussowitsch PetscErrorCode TSSetResize(TS ts, PetscErrorCode (*setup)(TS ts, PetscInt step, PetscReal time, Vec state, PetscBool *resize, void *ctx), PetscErrorCode (*transfer)(TS ts, PetscInt nv, Vec vecsin[], Vec vecsout[], void *ctx), void *ctx)
36766bd3a4fdSStefano Zampini {
36776bd3a4fdSStefano Zampini   PetscFunctionBegin;
36786bd3a4fdSStefano Zampini   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
36796bd3a4fdSStefano Zampini   ts->resizesetup    = setup;
36806bd3a4fdSStefano Zampini   ts->resizetransfer = transfer;
36816bd3a4fdSStefano Zampini   ts->resizectx      = ctx;
36826bd3a4fdSStefano Zampini   PetscFunctionReturn(PETSC_SUCCESS);
36836bd3a4fdSStefano Zampini }
36846bd3a4fdSStefano Zampini 
368514d0ab18SJacob Faibussowitsch /*
36866bd3a4fdSStefano Zampini   TSResizeRegisterOrRetrieve - Register or import vectors transferred with `TSResize()`.
36876bd3a4fdSStefano Zampini 
36886bd3a4fdSStefano Zampini   Collective
36896bd3a4fdSStefano Zampini 
36906bd3a4fdSStefano Zampini   Input Parameters:
36916bd3a4fdSStefano Zampini + ts   - The `TS` context obtained from `TSCreate()`
36926bd3a4fdSStefano Zampini - flg - If `PETSC_TRUE` each TS implementation (e.g. `TSBDF`) will register vectors to be transferred, if `PETSC_FALSE` vectors will be imported from transferred vectors.
36936bd3a4fdSStefano Zampini 
36946bd3a4fdSStefano Zampini   Level: developer
36956bd3a4fdSStefano Zampini 
36966bd3a4fdSStefano Zampini   Note:
36976bd3a4fdSStefano Zampini   `TSResizeRegisterOrRetrieve()` is declared PETSC_INTERN since it is
36986bd3a4fdSStefano Zampini    used within time stepping implementations,
36996bd3a4fdSStefano Zampini    so most users would not generally call this routine themselves.
37006bd3a4fdSStefano Zampini 
37016bd3a4fdSStefano Zampini .seealso: [](ch_ts), `TS`, `TSSetResize()`
37026bd3a4fdSStefano Zampini @*/
370314d0ab18SJacob Faibussowitsch static PetscErrorCode TSResizeRegisterOrRetrieve(TS ts, PetscBool flg)
37046bd3a4fdSStefano Zampini {
37056bd3a4fdSStefano Zampini   PetscFunctionBegin;
37066bd3a4fdSStefano Zampini   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
37076bd3a4fdSStefano Zampini   PetscTryTypeMethod(ts, resizeregister, flg);
37086bd3a4fdSStefano Zampini   /* PetscTryTypeMethod(adapt, resizeregister, flg); */
37096bd3a4fdSStefano Zampini   PetscFunctionReturn(PETSC_SUCCESS);
37106bd3a4fdSStefano Zampini }
37116bd3a4fdSStefano Zampini 
371214d0ab18SJacob Faibussowitsch static PetscErrorCode TSResizeReset(TS ts)
37136bd3a4fdSStefano Zampini {
37146bd3a4fdSStefano Zampini   PetscFunctionBegin;
37156bd3a4fdSStefano Zampini   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
37166bd3a4fdSStefano Zampini   PetscCall(PetscObjectListDestroy(&ts->resizetransferobjs));
37176bd3a4fdSStefano Zampini   PetscFunctionReturn(PETSC_SUCCESS);
37186bd3a4fdSStefano Zampini }
37196bd3a4fdSStefano Zampini 
37206bd3a4fdSStefano Zampini static PetscErrorCode TSResizeTransferVecs(TS ts, PetscInt cnt, Vec vecsin[], Vec vecsout[])
37216bd3a4fdSStefano Zampini {
37226bd3a4fdSStefano Zampini   PetscFunctionBegin;
37236bd3a4fdSStefano Zampini   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
37246bd3a4fdSStefano Zampini   PetscValidLogicalCollectiveInt(ts, cnt, 2);
37256bd3a4fdSStefano Zampini   for (PetscInt i = 0; i < cnt; i++) PetscCall(VecLockReadPush(vecsin[i]));
37266bd3a4fdSStefano Zampini   if (ts->resizetransfer) {
37276bd3a4fdSStefano Zampini     PetscCall(PetscInfo(ts, "Transferring %" PetscInt_FMT " vectors\n", cnt));
37286bd3a4fdSStefano Zampini     PetscCallBack("TS callback resize transfer", (*ts->resizetransfer)(ts, cnt, vecsin, vecsout, ts->resizectx));
37296bd3a4fdSStefano Zampini   }
37306bd3a4fdSStefano Zampini   for (PetscInt i = 0; i < cnt; i++) PetscCall(VecLockReadPop(vecsin[i]));
37316bd3a4fdSStefano Zampini   PetscFunctionReturn(PETSC_SUCCESS);
37326bd3a4fdSStefano Zampini }
37336bd3a4fdSStefano Zampini 
37346bd3a4fdSStefano Zampini /*@C
37356bd3a4fdSStefano Zampini   TSResizeRegisterVec - Register a vector to be transferred with `TSResize()`.
37366bd3a4fdSStefano Zampini 
37376bd3a4fdSStefano Zampini   Collective
37386bd3a4fdSStefano Zampini 
37396bd3a4fdSStefano Zampini   Input Parameters:
37406bd3a4fdSStefano Zampini + ts   - The `TS` context obtained from `TSCreate()`
3741baca6076SPierre Jolivet . name - A string identifying the vector
37426bd3a4fdSStefano Zampini - vec  - The vector
37436bd3a4fdSStefano Zampini 
37446bd3a4fdSStefano Zampini   Level: developer
37456bd3a4fdSStefano Zampini 
37466bd3a4fdSStefano Zampini   Note:
37476bd3a4fdSStefano Zampini   `TSResizeRegisterVec()` is typically used within time stepping implementations,
37486bd3a4fdSStefano Zampini   so most users would not generally call this routine themselves.
37496bd3a4fdSStefano Zampini 
37506bd3a4fdSStefano Zampini .seealso: [](ch_ts), `TS`, `TSSetResize()`, `TSResize()`, `TSResizeRetrieveVec()`
37516bd3a4fdSStefano Zampini @*/
37526bd3a4fdSStefano Zampini PetscErrorCode TSResizeRegisterVec(TS ts, const char *name, Vec vec)
37536bd3a4fdSStefano Zampini {
37546bd3a4fdSStefano Zampini   PetscFunctionBegin;
37556bd3a4fdSStefano Zampini   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
37564f572ea9SToby Isaac   PetscAssertPointer(name, 2);
37576bd3a4fdSStefano Zampini   if (vec) PetscValidHeaderSpecific(vec, VEC_CLASSID, 3);
37586bd3a4fdSStefano Zampini   PetscCall(PetscObjectListAdd(&ts->resizetransferobjs, name, (PetscObject)vec));
37596bd3a4fdSStefano Zampini   PetscFunctionReturn(PETSC_SUCCESS);
37606bd3a4fdSStefano Zampini }
37616bd3a4fdSStefano Zampini 
37626bd3a4fdSStefano Zampini /*@C
37636bd3a4fdSStefano Zampini   TSResizeRetrieveVec - Retrieve a vector registered with `TSResizeRegisterVec()`.
37646bd3a4fdSStefano Zampini 
37656bd3a4fdSStefano Zampini   Collective
37666bd3a4fdSStefano Zampini 
37676bd3a4fdSStefano Zampini   Input Parameters:
37686bd3a4fdSStefano Zampini + ts   - The `TS` context obtained from `TSCreate()`
3769baca6076SPierre Jolivet . name - A string identifying the vector
37706bd3a4fdSStefano Zampini - vec  - The vector
37716bd3a4fdSStefano Zampini 
37726bd3a4fdSStefano Zampini   Level: developer
37736bd3a4fdSStefano Zampini 
37746bd3a4fdSStefano Zampini   Note:
37756bd3a4fdSStefano Zampini   `TSResizeRetrieveVec()` is typically used within time stepping implementations,
37766bd3a4fdSStefano Zampini   so most users would not generally call this routine themselves.
37776bd3a4fdSStefano Zampini 
37786bd3a4fdSStefano Zampini .seealso: [](ch_ts), `TS`, `TSSetResize()`, `TSResize()`, `TSResizeRegisterVec()`
37796bd3a4fdSStefano Zampini @*/
37806bd3a4fdSStefano Zampini PetscErrorCode TSResizeRetrieveVec(TS ts, const char *name, Vec *vec)
37816bd3a4fdSStefano Zampini {
37826bd3a4fdSStefano Zampini   PetscFunctionBegin;
37836bd3a4fdSStefano Zampini   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
37844f572ea9SToby Isaac   PetscAssertPointer(name, 2);
37854f572ea9SToby Isaac   PetscAssertPointer(vec, 3);
37866bd3a4fdSStefano Zampini   PetscCall(PetscObjectListFind(ts->resizetransferobjs, name, (PetscObject *)vec));
37876bd3a4fdSStefano Zampini   PetscFunctionReturn(PETSC_SUCCESS);
37886bd3a4fdSStefano Zampini }
37896bd3a4fdSStefano Zampini 
37906bd3a4fdSStefano Zampini static PetscErrorCode TSResizeGetVecArray(TS ts, PetscInt *nv, const char **names[], Vec *vecs[])
37916bd3a4fdSStefano Zampini {
37926bd3a4fdSStefano Zampini   PetscInt        cnt;
37936bd3a4fdSStefano Zampini   PetscObjectList tmp;
37946bd3a4fdSStefano Zampini   Vec            *vecsin  = NULL;
37956bd3a4fdSStefano Zampini   const char    **namesin = NULL;
37966bd3a4fdSStefano Zampini 
37976bd3a4fdSStefano Zampini   PetscFunctionBegin;
37986bd3a4fdSStefano Zampini   for (tmp = ts->resizetransferobjs, cnt = 0; tmp; tmp = tmp->next)
37996bd3a4fdSStefano Zampini     if (tmp->obj && tmp->obj->classid == VEC_CLASSID) cnt++;
38006bd3a4fdSStefano Zampini   if (names) PetscCall(PetscMalloc1(cnt, &vecsin));
38016bd3a4fdSStefano Zampini   if (vecs) PetscCall(PetscMalloc1(cnt, &namesin));
38026bd3a4fdSStefano Zampini   for (tmp = ts->resizetransferobjs, cnt = 0; tmp; tmp = tmp->next) {
38036bd3a4fdSStefano Zampini     if (tmp->obj && tmp->obj->classid == VEC_CLASSID) {
38046bd3a4fdSStefano Zampini       if (vecs) vecsin[cnt] = (Vec)tmp->obj;
38056bd3a4fdSStefano Zampini       if (names) namesin[cnt] = tmp->name;
38066bd3a4fdSStefano Zampini       cnt++;
38076bd3a4fdSStefano Zampini     }
38086bd3a4fdSStefano Zampini   }
38096bd3a4fdSStefano Zampini   if (nv) *nv = cnt;
38106bd3a4fdSStefano Zampini   if (names) *names = namesin;
38116bd3a4fdSStefano Zampini   if (vecs) *vecs = vecsin;
38126bd3a4fdSStefano Zampini   PetscFunctionReturn(PETSC_SUCCESS);
38136bd3a4fdSStefano Zampini }
38146bd3a4fdSStefano Zampini 
38156bd3a4fdSStefano Zampini /*@
38166bd3a4fdSStefano Zampini   TSResize - Runs the user-defined transfer functions provided with `TSSetResize()`
38176bd3a4fdSStefano Zampini 
38186bd3a4fdSStefano Zampini   Collective
38196bd3a4fdSStefano Zampini 
38206bd3a4fdSStefano Zampini   Input Parameter:
38216bd3a4fdSStefano Zampini . ts - The `TS` context obtained from `TSCreate()`
38226bd3a4fdSStefano Zampini 
38236bd3a4fdSStefano Zampini   Level: developer
38246bd3a4fdSStefano Zampini 
38256bd3a4fdSStefano Zampini   Note:
38266bd3a4fdSStefano Zampini   `TSResize()` is typically used within time stepping implementations,
38276bd3a4fdSStefano Zampini   so most users would not generally call this routine themselves.
38286bd3a4fdSStefano Zampini 
38296bd3a4fdSStefano Zampini .seealso: [](ch_ts), `TS`, `TSSetResize()`
38306bd3a4fdSStefano Zampini @*/
38316bd3a4fdSStefano Zampini PetscErrorCode TSResize(TS ts)
38326bd3a4fdSStefano Zampini {
38336bd3a4fdSStefano Zampini   PetscInt     nv      = 0;
38346bd3a4fdSStefano Zampini   const char **names   = NULL;
38356bd3a4fdSStefano Zampini   Vec         *vecsin  = NULL;
38366bd3a4fdSStefano Zampini   const char  *solname = "ts:vec_sol";
38376bd3a4fdSStefano Zampini 
38386bd3a4fdSStefano Zampini   PetscFunctionBegin;
38396bd3a4fdSStefano Zampini   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
38406bd3a4fdSStefano Zampini   if (ts->resizesetup) {
38416bd3a4fdSStefano Zampini     PetscBool flg = PETSC_FALSE;
38426bd3a4fdSStefano Zampini 
38436bd3a4fdSStefano Zampini     PetscCall(VecLockReadPush(ts->vec_sol));
38446bd3a4fdSStefano Zampini     PetscCallBack("TS callback resize setup", (*ts->resizesetup)(ts, ts->steps, ts->ptime, ts->vec_sol, &flg, ts->resizectx));
38456bd3a4fdSStefano Zampini     PetscCall(VecLockReadPop(ts->vec_sol));
38466bd3a4fdSStefano Zampini     if (flg) {
38476bd3a4fdSStefano Zampini       PetscCall(TSResizeRegisterVec(ts, solname, ts->vec_sol));
38486bd3a4fdSStefano Zampini       PetscCall(TSResizeRegisterOrRetrieve(ts, PETSC_TRUE)); /* specific impls register their own objects */
38496bd3a4fdSStefano Zampini     }
38506bd3a4fdSStefano Zampini   }
38516bd3a4fdSStefano Zampini 
38526bd3a4fdSStefano Zampini   PetscCall(TSResizeGetVecArray(ts, &nv, &names, &vecsin));
38536bd3a4fdSStefano Zampini   if (nv) {
38546bd3a4fdSStefano Zampini     Vec *vecsout, vecsol;
38556bd3a4fdSStefano Zampini 
38566bd3a4fdSStefano Zampini     /* Reset internal objects */
38576bd3a4fdSStefano Zampini     PetscCall(TSReset(ts));
38586bd3a4fdSStefano Zampini 
38596bd3a4fdSStefano Zampini     /* Transfer needed vectors (users can call SetJacobian, SetDM here) */
38606bd3a4fdSStefano Zampini     PetscCall(PetscCalloc1(nv, &vecsout));
38616bd3a4fdSStefano Zampini     PetscCall(TSResizeTransferVecs(ts, nv, vecsin, vecsout));
38626bd3a4fdSStefano Zampini     for (PetscInt i = 0; i < nv; i++) {
38636bd3a4fdSStefano Zampini       PetscCall(TSResizeRegisterVec(ts, names[i], vecsout[i]));
38646bd3a4fdSStefano Zampini       PetscCall(VecDestroy(&vecsout[i]));
38656bd3a4fdSStefano Zampini     }
38666bd3a4fdSStefano Zampini     PetscCall(PetscFree(vecsout));
38676bd3a4fdSStefano Zampini     PetscCall(TSResizeRegisterOrRetrieve(ts, PETSC_FALSE)); /* specific impls import the transferred objects */
38686bd3a4fdSStefano Zampini 
38696bd3a4fdSStefano Zampini     PetscCall(TSResizeRetrieveVec(ts, solname, &vecsol));
38706bd3a4fdSStefano Zampini     if (vecsol) PetscCall(TSSetSolution(ts, vecsol));
38716bd3a4fdSStefano Zampini     PetscAssert(ts->vec_sol, PetscObjectComm((PetscObject)ts), PETSC_ERR_ARG_NULL, "Missing TS solution");
38726bd3a4fdSStefano Zampini   }
38736bd3a4fdSStefano Zampini 
38746bd3a4fdSStefano Zampini   PetscCall(PetscFree(names));
38756bd3a4fdSStefano Zampini   PetscCall(PetscFree(vecsin));
38766bd3a4fdSStefano Zampini   PetscCall(TSResizeReset(ts));
38776bd3a4fdSStefano Zampini   PetscFunctionReturn(PETSC_SUCCESS);
38786bd3a4fdSStefano Zampini }
38796bd3a4fdSStefano Zampini 
3880b1cb36f3SHong Zhang /*@
38816a4d4014SLisandro Dalcin   TSSolve - Steps the requested number of timesteps.
38826a4d4014SLisandro Dalcin 
3883c3339decSBarry Smith   Collective
38846a4d4014SLisandro Dalcin 
3885d8d19677SJose E. Roman   Input Parameters:
3886bcf0153eSBarry Smith + ts - the `TS` context obtained from `TSCreate()`
3887bcf0153eSBarry Smith - u  - the solution vector  (can be null if `TSSetSolution()` was used and `TSSetExactFinalTime`(ts,`TS_EXACTFINALTIME_MATCHSTEP`) was not used,
388863e21af5SBarry Smith                              otherwise must contain the initial conditions and will contain the solution at the final requested time
38895a3a76d0SJed Brown 
38906a4d4014SLisandro Dalcin   Level: beginner
38916a4d4014SLisandro Dalcin 
38925a3a76d0SJed Brown   Notes:
38935a3a76d0SJed Brown   The final time returned by this function may be different from the time of the internally
3894bcf0153eSBarry Smith   held state accessible by `TSGetSolution()` and `TSGetTime()` because the method may have
38955a3a76d0SJed Brown   stepped over the final time.
38965a3a76d0SJed Brown 
38971cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSCreate()`, `TSSetSolution()`, `TSStep()`, `TSGetTime()`, `TSGetSolveTime()`
38986a4d4014SLisandro Dalcin @*/
3899d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSolve(TS ts, Vec u)
3900d71ae5a4SJacob Faibussowitsch {
3901b06615a5SLisandro Dalcin   Vec solution;
3902f22f69f0SBarry Smith 
39036a4d4014SLisandro Dalcin   PetscFunctionBegin;
39040700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3905f2c2a1b9SBarry Smith   if (u) PetscValidHeaderSpecific(u, VEC_CLASSID, 2);
3906303a5415SBarry Smith 
39079566063dSJacob Faibussowitsch   PetscCall(TSSetExactFinalTimeDefault(ts));
3908ee41a567SStefano 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 */
39090910c330SBarry Smith     if (!ts->vec_sol || u == ts->vec_sol) {
39109566063dSJacob Faibussowitsch       PetscCall(VecDuplicate(u, &solution));
39119566063dSJacob Faibussowitsch       PetscCall(TSSetSolution(ts, solution));
39129566063dSJacob Faibussowitsch       PetscCall(VecDestroy(&solution)); /* grant ownership */
39135a3a76d0SJed Brown     }
39149566063dSJacob Faibussowitsch     PetscCall(VecCopy(u, ts->vec_sol));
39153c633725SBarry Smith     PetscCheck(!ts->forward_solve, PetscObjectComm((PetscObject)ts), PETSC_ERR_SUP, "Sensitivity analysis does not support the mode TS_EXACTFINALTIME_INTERPOLATE");
39161baa6e33SBarry Smith   } else if (u) PetscCall(TSSetSolution(ts, u));
39179566063dSJacob Faibussowitsch   PetscCall(TSSetUp(ts));
39189566063dSJacob Faibussowitsch   PetscCall(TSTrajectorySetUp(ts->trajectory, ts));
3919a6772fa2SLisandro Dalcin 
39203c633725SBarry 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>");
39213c633725SBarry 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()");
39223c633725SBarry 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");
39234a658b32SHong 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");
39244a658b32SHong Zhang 
3925e1db57b0SHong 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 */
39264a658b32SHong Zhang     PetscCall(VecCopy(ts->vec_sol, ts->tspan->vecs_sol[0]));
39274a658b32SHong Zhang     ts->tspan->spanctr = 1;
39284a658b32SHong Zhang   }
3929a6772fa2SLisandro Dalcin 
39301baa6e33SBarry Smith   if (ts->forward_solve) PetscCall(TSForwardSetUp(ts));
3931715f1b00SHong Zhang 
3932e7069c78SShri   /* reset number of steps only when the step is not restarted. ARKIMEX
3933715f1b00SHong Zhang      restarts the step after an event. Resetting these counters in such case causes
3934e7069c78SShri      TSTrajectory to incorrectly save the output files
3935e7069c78SShri   */
3936715f1b00SHong Zhang   /* reset time step and iteration counters */
39372808aa04SLisandro Dalcin   if (!ts->steps) {
39385ef26d82SJed Brown     ts->ksp_its           = 0;
39395ef26d82SJed Brown     ts->snes_its          = 0;
3940c610991cSLisandro Dalcin     ts->num_snes_failures = 0;
3941c610991cSLisandro Dalcin     ts->reject            = 0;
39422808aa04SLisandro Dalcin     ts->steprestart       = PETSC_TRUE;
39432808aa04SLisandro Dalcin     ts->steprollback      = PETSC_FALSE;
39447d51462cSStefano Zampini     ts->rhsjacobian.time  = PETSC_MIN_REAL;
39452808aa04SLisandro Dalcin   }
3946e97c63d7SStefano Zampini 
39474a658b32SHong Zhang   /* make sure initial time step does not overshoot final time or the next point in tspan */
3948e97c63d7SStefano Zampini   if (ts->exact_final_time == TS_EXACTFINALTIME_MATCHSTEP) {
39494a658b32SHong Zhang     PetscReal maxdt;
3950e97c63d7SStefano Zampini     PetscReal dt = ts->time_step;
3951e97c63d7SStefano Zampini 
39524a658b32SHong Zhang     if (ts->tspan) maxdt = ts->tspan->span_times[ts->tspan->spanctr] - ts->ptime;
39534a658b32SHong Zhang     else maxdt = ts->max_time - ts->ptime;
3954e97c63d7SStefano Zampini     ts->time_step = dt >= maxdt ? maxdt : (PetscIsCloseAtTol(dt, maxdt, 10 * PETSC_MACHINE_EPSILON, 0) ? maxdt : dt);
3955e97c63d7SStefano Zampini   }
3956193ac0bcSJed Brown   ts->reason = TS_CONVERGED_ITERATING;
3957193ac0bcSJed Brown 
3958900f6b5bSMatthew G. Knepley   {
3959900f6b5bSMatthew G. Knepley     PetscViewer       viewer;
3960900f6b5bSMatthew G. Knepley     PetscViewerFormat format;
3961900f6b5bSMatthew G. Knepley     PetscBool         flg;
3962900f6b5bSMatthew G. Knepley     static PetscBool  incall = PETSC_FALSE;
3963900f6b5bSMatthew G. Knepley 
3964900f6b5bSMatthew G. Knepley     if (!incall) {
3965900f6b5bSMatthew G. Knepley       /* Estimate the convergence rate of the time discretization */
39669566063dSJacob Faibussowitsch       PetscCall(PetscOptionsGetViewer(PetscObjectComm((PetscObject)ts), ((PetscObject)ts)->options, ((PetscObject)ts)->prefix, "-ts_convergence_estimate", &viewer, &format, &flg));
3967900f6b5bSMatthew G. Knepley       if (flg) {
3968900f6b5bSMatthew G. Knepley         PetscConvEst conv;
3969900f6b5bSMatthew G. Knepley         DM           dm;
3970900f6b5bSMatthew G. Knepley         PetscReal   *alpha; /* Convergence rate of the solution error for each field in the L_2 norm */
3971900f6b5bSMatthew G. Knepley         PetscInt     Nf;
3972f2ed2dc7SMatthew G. Knepley         PetscBool    checkTemporal = PETSC_TRUE;
3973900f6b5bSMatthew G. Knepley 
3974900f6b5bSMatthew G. Knepley         incall = PETSC_TRUE;
39759566063dSJacob Faibussowitsch         PetscCall(PetscOptionsGetBool(((PetscObject)ts)->options, ((PetscObject)ts)->prefix, "-ts_convergence_temporal", &checkTemporal, &flg));
39769566063dSJacob Faibussowitsch         PetscCall(TSGetDM(ts, &dm));
39779566063dSJacob Faibussowitsch         PetscCall(DMGetNumFields(dm, &Nf));
39789566063dSJacob Faibussowitsch         PetscCall(PetscCalloc1(PetscMax(Nf, 1), &alpha));
39799566063dSJacob Faibussowitsch         PetscCall(PetscConvEstCreate(PetscObjectComm((PetscObject)ts), &conv));
39809566063dSJacob Faibussowitsch         PetscCall(PetscConvEstUseTS(conv, checkTemporal));
39819566063dSJacob Faibussowitsch         PetscCall(PetscConvEstSetSolver(conv, (PetscObject)ts));
39829566063dSJacob Faibussowitsch         PetscCall(PetscConvEstSetFromOptions(conv));
39839566063dSJacob Faibussowitsch         PetscCall(PetscConvEstSetUp(conv));
39849566063dSJacob Faibussowitsch         PetscCall(PetscConvEstGetConvRate(conv, alpha));
39859566063dSJacob Faibussowitsch         PetscCall(PetscViewerPushFormat(viewer, format));
39869566063dSJacob Faibussowitsch         PetscCall(PetscConvEstRateView(conv, alpha, viewer));
39879566063dSJacob Faibussowitsch         PetscCall(PetscViewerPopFormat(viewer));
39889566063dSJacob Faibussowitsch         PetscCall(PetscViewerDestroy(&viewer));
39899566063dSJacob Faibussowitsch         PetscCall(PetscConvEstDestroy(&conv));
39909566063dSJacob Faibussowitsch         PetscCall(PetscFree(alpha));
3991900f6b5bSMatthew G. Knepley         incall = PETSC_FALSE;
3992900f6b5bSMatthew G. Knepley       }
3993900f6b5bSMatthew G. Knepley     }
3994900f6b5bSMatthew G. Knepley   }
3995900f6b5bSMatthew G. Knepley 
39969566063dSJacob Faibussowitsch   PetscCall(TSViewFromOptions(ts, NULL, "-ts_view_pre"));
3997f05ece33SBarry Smith 
3998193ac0bcSJed Brown   if (ts->ops->solve) { /* This private interface is transitional and should be removed when all implementations are updated. */
3999dbbe0bcdSBarry Smith     PetscUseTypeMethod(ts, solve);
40009566063dSJacob Faibussowitsch     if (u) PetscCall(VecCopy(ts->vec_sol, u));
4001cc708dedSBarry Smith     ts->solvetime = ts->ptime;
4002a6772fa2SLisandro Dalcin     solution      = ts->vec_sol;
4003be5899b3SLisandro Dalcin   } else { /* Step the requested number of timesteps. */
4004db4deed7SKarl Rupp     if (ts->steps >= ts->max_steps) ts->reason = TS_CONVERGED_ITS;
4005db4deed7SKarl Rupp     else if (ts->ptime >= ts->max_time) ts->reason = TS_CONVERGED_TIME;
4006e7069c78SShri 
40072808aa04SLisandro Dalcin     if (!ts->steps) {
40089566063dSJacob Faibussowitsch       PetscCall(TSTrajectorySet(ts->trajectory, ts, ts->steps, ts->ptime, ts->vec_sol));
40099566063dSJacob Faibussowitsch       PetscCall(TSEventInitialize(ts->event, ts, ts->ptime, ts->vec_sol));
40102808aa04SLisandro Dalcin     }
40116427ac75SLisandro Dalcin 
4012e1a7a14fSJed Brown     while (!ts->reason) {
40139566063dSJacob Faibussowitsch       PetscCall(TSMonitor(ts, ts->steps, ts->ptime, ts->vec_sol));
40141e66621cSBarry Smith       if (!ts->steprollback) PetscCall(TSPreStep(ts));
40159566063dSJacob Faibussowitsch       PetscCall(TSStep(ts));
40161baa6e33SBarry Smith       if (ts->testjacobian) PetscCall(TSRHSJacobianTest(ts, NULL));
40171baa6e33SBarry Smith       if (ts->testjacobiantranspose) PetscCall(TSRHSJacobianTestTranspose(ts, NULL));
4018cd4cee2dSHong Zhang       if (ts->quadraturets && ts->costintegralfwd) { /* Must evaluate the cost integral before event is handled. The cost integral value can also be rolled back. */
40197b0e2f17SHong Zhang         if (ts->reason >= 0) ts->steps--;            /* Revert the step number changed by TSStep() */
40209566063dSJacob Faibussowitsch         PetscCall(TSForwardCostIntegral(ts));
40217b0e2f17SHong Zhang         if (ts->reason >= 0) ts->steps++;
4022b1cb36f3SHong Zhang       }
402358818c2dSLisandro Dalcin       if (ts->forward_solve) {            /* compute forward sensitivities before event handling because postevent() may change RHS and jump conditions may have to be applied */
40247b0e2f17SHong Zhang         if (ts->reason >= 0) ts->steps--; /* Revert the step number changed by TSStep() */
40259566063dSJacob Faibussowitsch         PetscCall(TSForwardStep(ts));
40267b0e2f17SHong Zhang         if (ts->reason >= 0) ts->steps++;
4027715f1b00SHong Zhang       }
40289566063dSJacob Faibussowitsch       PetscCall(TSPostEvaluate(ts));
40299566063dSJacob 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. */
40301baa6e33SBarry Smith       if (ts->steprollback) PetscCall(TSPostEvaluate(ts));
4031e783b05fSHong Zhang       if (!ts->steprollback) {
40329566063dSJacob Faibussowitsch         PetscCall(TSTrajectorySet(ts->trajectory, ts, ts->steps, ts->ptime, ts->vec_sol));
40339566063dSJacob Faibussowitsch         PetscCall(TSPostStep(ts));
40346bd3a4fdSStefano Zampini         PetscCall(TSResize(ts));
4035aeb4809dSShri Abhyankar       }
4036193ac0bcSJed Brown     }
40379566063dSJacob Faibussowitsch     PetscCall(TSMonitor(ts, ts->steps, ts->ptime, ts->vec_sol));
40386427ac75SLisandro Dalcin 
403949354f04SShri Abhyankar     if (ts->exact_final_time == TS_EXACTFINALTIME_INTERPOLATE && ts->ptime > ts->max_time) {
40405dbbf88eSStefano Zampini       if (!u) u = ts->vec_sol;
40419566063dSJacob Faibussowitsch       PetscCall(TSInterpolate(ts, ts->max_time, u));
4042cc708dedSBarry Smith       ts->solvetime = ts->max_time;
4043b06615a5SLisandro Dalcin       solution      = u;
40449566063dSJacob Faibussowitsch       PetscCall(TSMonitor(ts, -1, ts->solvetime, solution));
40450574a7fbSJed Brown     } else {
40469566063dSJacob Faibussowitsch       if (u) PetscCall(VecCopy(ts->vec_sol, u));
4047cc708dedSBarry Smith       ts->solvetime = ts->ptime;
4048b06615a5SLisandro Dalcin       solution      = ts->vec_sol;
40490574a7fbSJed Brown     }
4050193ac0bcSJed Brown   }
4051d2daff3dSHong Zhang 
40529566063dSJacob Faibussowitsch   PetscCall(TSViewFromOptions(ts, NULL, "-ts_view"));
40539566063dSJacob Faibussowitsch   PetscCall(VecViewFromOptions(solution, (PetscObject)ts, "-ts_view_solution"));
40549566063dSJacob Faibussowitsch   PetscCall(PetscObjectSAWsBlock((PetscObject)ts));
40551baa6e33SBarry Smith   if (ts->adjoint_solve) PetscCall(TSAdjointSolve(ts));
40563ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
40576a4d4014SLisandro Dalcin }
40586a4d4014SLisandro Dalcin 
4059d763cef2SBarry Smith /*@
4060b8123daeSJed Brown   TSGetTime - Gets the time of the most recently completed step.
4061d763cef2SBarry Smith 
4062d763cef2SBarry Smith   Not Collective
4063d763cef2SBarry Smith 
4064d763cef2SBarry Smith   Input Parameter:
4065bcf0153eSBarry Smith . ts - the `TS` context obtained from `TSCreate()`
4066d763cef2SBarry Smith 
4067d763cef2SBarry Smith   Output Parameter:
4068bcf0153eSBarry Smith . t - the current time. This time may not corresponds to the final time set with `TSSetMaxTime()`, use `TSGetSolveTime()`.
4069d763cef2SBarry Smith 
4070d763cef2SBarry Smith   Level: beginner
4071d763cef2SBarry Smith 
4072b8123daeSJed Brown   Note:
4073bcf0153eSBarry Smith   When called during time step evaluation (e.g. during residual evaluation or via hooks set using `TSSetPreStep()`,
4074bcf0153eSBarry Smith   `TSSetPreStage()`, `TSSetPostStage()`, or `TSSetPostStep()`), the time is the time at the start of the step being evaluated.
4075b8123daeSJed Brown 
4076b43aa488SJacob Faibussowitsch .seealso: [](ch_ts), `TS`, ``TSGetSolveTime()`, `TSSetTime()`, `TSGetTimeStep()`, `TSGetStepNumber()`
4077d763cef2SBarry Smith @*/
4078d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetTime(TS ts, PetscReal *t)
4079d71ae5a4SJacob Faibussowitsch {
4080d763cef2SBarry Smith   PetscFunctionBegin;
40810700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
40824f572ea9SToby Isaac   PetscAssertPointer(t, 2);
4083d763cef2SBarry Smith   *t = ts->ptime;
40843ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
4085d763cef2SBarry Smith }
4086d763cef2SBarry Smith 
4087e5e524a1SHong Zhang /*@
4088e5e524a1SHong Zhang   TSGetPrevTime - Gets the starting time of the previously completed step.
4089e5e524a1SHong Zhang 
4090e5e524a1SHong Zhang   Not Collective
4091e5e524a1SHong Zhang 
4092e5e524a1SHong Zhang   Input Parameter:
4093bcf0153eSBarry Smith . ts - the `TS` context obtained from `TSCreate()`
4094e5e524a1SHong Zhang 
4095e5e524a1SHong Zhang   Output Parameter:
4096e5e524a1SHong Zhang . t - the previous time
4097e5e524a1SHong Zhang 
4098e5e524a1SHong Zhang   Level: beginner
4099e5e524a1SHong Zhang 
4100b43aa488SJacob Faibussowitsch .seealso: [](ch_ts), `TS`, ``TSGetTime()`, `TSGetSolveTime()`, `TSGetTimeStep()`
4101e5e524a1SHong Zhang @*/
4102d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetPrevTime(TS ts, PetscReal *t)
4103d71ae5a4SJacob Faibussowitsch {
4104e5e524a1SHong Zhang   PetscFunctionBegin;
4105e5e524a1SHong Zhang   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
41064f572ea9SToby Isaac   PetscAssertPointer(t, 2);
4107e5e524a1SHong Zhang   *t = ts->ptime_prev;
41083ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
4109e5e524a1SHong Zhang }
4110e5e524a1SHong Zhang 
41116a4d4014SLisandro Dalcin /*@
41126a4d4014SLisandro Dalcin   TSSetTime - Allows one to reset the time.
41136a4d4014SLisandro Dalcin 
4114c3339decSBarry Smith   Logically Collective
41156a4d4014SLisandro Dalcin 
41166a4d4014SLisandro Dalcin   Input Parameters:
4117bcf0153eSBarry Smith + ts - the `TS` context obtained from `TSCreate()`
4118b43aa488SJacob Faibussowitsch - t  - the time
41196a4d4014SLisandro Dalcin 
41206a4d4014SLisandro Dalcin   Level: intermediate
41216a4d4014SLisandro Dalcin 
41221cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSGetTime()`, `TSSetMaxSteps()`
41236a4d4014SLisandro Dalcin @*/
4124d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetTime(TS ts, PetscReal t)
4125d71ae5a4SJacob Faibussowitsch {
41266a4d4014SLisandro Dalcin   PetscFunctionBegin;
41270700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
4128c5eb9154SBarry Smith   PetscValidLogicalCollectiveReal(ts, t, 2);
41296a4d4014SLisandro Dalcin   ts->ptime = t;
41303ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
41316a4d4014SLisandro Dalcin }
41326a4d4014SLisandro Dalcin 
4133d763cef2SBarry Smith /*@C
4134d763cef2SBarry Smith   TSSetOptionsPrefix - Sets the prefix used for searching for all
4135d763cef2SBarry Smith   TS options in the database.
4136d763cef2SBarry Smith 
4137c3339decSBarry Smith   Logically Collective
4138d763cef2SBarry Smith 
4139d8d19677SJose E. Roman   Input Parameters:
4140bcf0153eSBarry Smith + ts     - The `TS` context
4141d763cef2SBarry Smith - prefix - The prefix to prepend to all option names
4142d763cef2SBarry Smith 
4143bcf0153eSBarry Smith   Level: advanced
4144bcf0153eSBarry Smith 
4145bcf0153eSBarry Smith   Note:
4146d763cef2SBarry Smith   A hyphen (-) must NOT be given at the beginning of the prefix name.
4147d763cef2SBarry Smith   The first character of all runtime options is AUTOMATICALLY the
4148d763cef2SBarry Smith   hyphen.
4149d763cef2SBarry Smith 
41501cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetFromOptions()`, `TSAppendOptionsPrefix()`
4151d763cef2SBarry Smith @*/
4152d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetOptionsPrefix(TS ts, const char prefix[])
4153d71ae5a4SJacob Faibussowitsch {
4154089b2837SJed Brown   SNES snes;
4155d763cef2SBarry Smith 
4156d763cef2SBarry Smith   PetscFunctionBegin;
41570700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
41589566063dSJacob Faibussowitsch   PetscCall(PetscObjectSetOptionsPrefix((PetscObject)ts, prefix));
41599566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts, &snes));
41609566063dSJacob Faibussowitsch   PetscCall(SNESSetOptionsPrefix(snes, prefix));
41613ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
4162d763cef2SBarry Smith }
4163d763cef2SBarry Smith 
4164d763cef2SBarry Smith /*@C
4165d763cef2SBarry Smith   TSAppendOptionsPrefix - Appends to the prefix used for searching for all
4166d763cef2SBarry Smith   TS options in the database.
4167d763cef2SBarry Smith 
4168c3339decSBarry Smith   Logically Collective
4169d763cef2SBarry Smith 
4170d8d19677SJose E. Roman   Input Parameters:
4171bcf0153eSBarry Smith + ts     - The `TS` context
4172d763cef2SBarry Smith - prefix - The prefix to prepend to all option names
4173d763cef2SBarry Smith 
4174bcf0153eSBarry Smith   Level: advanced
4175bcf0153eSBarry Smith 
4176bcf0153eSBarry Smith   Note:
4177d763cef2SBarry Smith   A hyphen (-) must NOT be given at the beginning of the prefix name.
4178d763cef2SBarry Smith   The first character of all runtime options is AUTOMATICALLY the
4179d763cef2SBarry Smith   hyphen.
4180d763cef2SBarry Smith 
41811cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSGetOptionsPrefix()`, `TSSetOptionsPrefix()`, `TSSetFromOptions()`
4182d763cef2SBarry Smith @*/
4183d71ae5a4SJacob Faibussowitsch PetscErrorCode TSAppendOptionsPrefix(TS ts, const char prefix[])
4184d71ae5a4SJacob Faibussowitsch {
4185089b2837SJed Brown   SNES snes;
4186d763cef2SBarry Smith 
4187d763cef2SBarry Smith   PetscFunctionBegin;
41880700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
41899566063dSJacob Faibussowitsch   PetscCall(PetscObjectAppendOptionsPrefix((PetscObject)ts, prefix));
41909566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts, &snes));
41919566063dSJacob Faibussowitsch   PetscCall(SNESAppendOptionsPrefix(snes, prefix));
41923ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
4193d763cef2SBarry Smith }
4194d763cef2SBarry Smith 
4195d763cef2SBarry Smith /*@C
4196d763cef2SBarry Smith   TSGetOptionsPrefix - Sets the prefix used for searching for all
4197bcf0153eSBarry Smith   `TS` options in the database.
4198d763cef2SBarry Smith 
4199d763cef2SBarry Smith   Not Collective
4200d763cef2SBarry Smith 
4201d763cef2SBarry Smith   Input Parameter:
4202bcf0153eSBarry Smith . ts - The `TS` context
4203d763cef2SBarry Smith 
4204d763cef2SBarry Smith   Output Parameter:
4205d763cef2SBarry Smith . prefix - A pointer to the prefix string used
4206d763cef2SBarry Smith 
4207d763cef2SBarry Smith   Level: intermediate
4208d763cef2SBarry Smith 
4209b43aa488SJacob Faibussowitsch   Fortran Notes:
4210195e9b02SBarry Smith   The user should pass in a string 'prefix' of
4211bcf0153eSBarry Smith   sufficient length to hold the prefix.
4212bcf0153eSBarry Smith 
42131cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSAppendOptionsPrefix()`, `TSSetFromOptions()`
4214d763cef2SBarry Smith @*/
4215d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetOptionsPrefix(TS ts, const char *prefix[])
4216d71ae5a4SJacob Faibussowitsch {
4217d763cef2SBarry Smith   PetscFunctionBegin;
42180700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
42194f572ea9SToby Isaac   PetscAssertPointer(prefix, 2);
42209566063dSJacob Faibussowitsch   PetscCall(PetscObjectGetOptionsPrefix((PetscObject)ts, prefix));
42213ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
4222d763cef2SBarry Smith }
4223d763cef2SBarry Smith 
4224d763cef2SBarry Smith /*@C
4225d763cef2SBarry Smith   TSGetRHSJacobian - Returns the Jacobian J at the present timestep.
4226d763cef2SBarry Smith 
4227bcf0153eSBarry Smith   Not Collective, but parallel objects are returned if ts is parallel
4228d763cef2SBarry Smith 
4229d763cef2SBarry Smith   Input Parameter:
4230bcf0153eSBarry Smith . ts - The `TS` context obtained from `TSCreate()`
4231d763cef2SBarry Smith 
4232d763cef2SBarry Smith   Output Parameters:
4233195e9b02SBarry Smith + Amat - The (approximate) Jacobian J of G, where U_t = G(U,t)  (or `NULL`)
4234195e9b02SBarry Smith . Pmat - The matrix from which the preconditioner is constructed, usually the same as `Amat`  (or `NULL`)
4235195e9b02SBarry Smith . func - Function to compute the Jacobian of the RHS  (or `NULL`)
4236195e9b02SBarry Smith - ctx  - User-defined context for Jacobian evaluation routine  (or `NULL`)
4237d763cef2SBarry Smith 
4238d763cef2SBarry Smith   Level: intermediate
4239d763cef2SBarry Smith 
4240bcf0153eSBarry Smith   Note:
4241195e9b02SBarry Smith   You can pass in `NULL` for any return argument you do not need.
4242bcf0153eSBarry Smith 
42431cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSGetTimeStep()`, `TSGetMatrices()`, `TSGetTime()`, `TSGetStepNumber()`
4244d763cef2SBarry Smith 
4245d763cef2SBarry Smith @*/
4246d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetRHSJacobian(TS ts, Mat *Amat, Mat *Pmat, TSRHSJacobian *func, void **ctx)
4247d71ae5a4SJacob Faibussowitsch {
424824989b8cSPeter Brune   DM dm;
4249089b2837SJed Brown 
4250d763cef2SBarry Smith   PetscFunctionBegin;
425123a57915SBarry Smith   if (Amat || Pmat) {
425223a57915SBarry Smith     SNES snes;
42539566063dSJacob Faibussowitsch     PetscCall(TSGetSNES(ts, &snes));
42549566063dSJacob Faibussowitsch     PetscCall(SNESSetUpMatrices(snes));
42559566063dSJacob Faibussowitsch     PetscCall(SNESGetJacobian(snes, Amat, Pmat, NULL, NULL));
425623a57915SBarry Smith   }
42579566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
42589566063dSJacob Faibussowitsch   PetscCall(DMTSGetRHSJacobian(dm, func, ctx));
42593ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
4260d763cef2SBarry Smith }
4261d763cef2SBarry Smith 
42622eca1d9cSJed Brown /*@C
42632eca1d9cSJed Brown   TSGetIJacobian - Returns the implicit Jacobian at the present timestep.
42642eca1d9cSJed Brown 
4265bcf0153eSBarry Smith   Not Collective, but parallel objects are returned if ts is parallel
42662eca1d9cSJed Brown 
42672eca1d9cSJed Brown   Input Parameter:
4268bcf0153eSBarry Smith . ts - The `TS` context obtained from `TSCreate()`
42692eca1d9cSJed Brown 
42702eca1d9cSJed Brown   Output Parameters:
4271e4357dc4SBarry Smith + Amat - The (approximate) Jacobian of F(t,U,U_t)
4272195e9b02SBarry Smith . Pmat - The matrix from which the preconditioner is constructed, often the same as `Amat`
42732eca1d9cSJed Brown . f    - The function to compute the matrices
42742eca1d9cSJed Brown - ctx  - User-defined context for Jacobian evaluation routine
42752eca1d9cSJed Brown 
42762eca1d9cSJed Brown   Level: advanced
42772eca1d9cSJed Brown 
4278bcf0153eSBarry Smith   Note:
4279195e9b02SBarry Smith   You can pass in `NULL` for any return argument you do not need.
4280bcf0153eSBarry Smith 
42811cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSGetTimeStep()`, `TSGetRHSJacobian()`, `TSGetMatrices()`, `TSGetTime()`, `TSGetStepNumber()`
42822eca1d9cSJed Brown @*/
4283d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetIJacobian(TS ts, Mat *Amat, Mat *Pmat, TSIJacobian *f, void **ctx)
4284d71ae5a4SJacob Faibussowitsch {
428524989b8cSPeter Brune   DM dm;
42860910c330SBarry Smith 
42872eca1d9cSJed Brown   PetscFunctionBegin;
4288c0aab802Sstefano_zampini   if (Amat || Pmat) {
4289c0aab802Sstefano_zampini     SNES snes;
42909566063dSJacob Faibussowitsch     PetscCall(TSGetSNES(ts, &snes));
42919566063dSJacob Faibussowitsch     PetscCall(SNESSetUpMatrices(snes));
42929566063dSJacob Faibussowitsch     PetscCall(SNESGetJacobian(snes, Amat, Pmat, NULL, NULL));
4293c0aab802Sstefano_zampini   }
42949566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
42959566063dSJacob Faibussowitsch   PetscCall(DMTSGetIJacobian(dm, f, ctx));
42963ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
42972eca1d9cSJed Brown }
42982eca1d9cSJed Brown 
4299af0996ceSBarry Smith #include <petsc/private/dmimpl.h>
43006c699258SBarry Smith /*@
4301bcf0153eSBarry Smith   TSSetDM - Sets the `DM` that may be used by some nonlinear solvers or preconditioners under the `TS`
43026c699258SBarry Smith 
4303c3339decSBarry Smith   Logically Collective
43046c699258SBarry Smith 
43056c699258SBarry Smith   Input Parameters:
4306bcf0153eSBarry Smith + ts - the `TS` integrator object
4307195e9b02SBarry Smith - dm - the dm, cannot be `NULL`
43086c699258SBarry Smith 
43096c699258SBarry Smith   Level: intermediate
43106c699258SBarry Smith 
4311bcf0153eSBarry Smith   Notes:
4312bcf0153eSBarry Smith   A `DM` can only be used for solving one problem at a time because information about the problem is stored on the `DM`,
4313bcf0153eSBarry Smith   even when not using interfaces like `DMTSSetIFunction()`.  Use `DMClone()` to get a distinct `DM` when solving
4314bcf0153eSBarry Smith   different problems using the same function space.
4315bcf0153eSBarry Smith 
43161cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `DM`, `TSGetDM()`, `SNESSetDM()`, `SNESGetDM()`
43176c699258SBarry Smith @*/
4318d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetDM(TS ts, DM dm)
4319d71ae5a4SJacob Faibussowitsch {
4320089b2837SJed Brown   SNES snes;
4321942e3340SBarry Smith   DMTS tsdm;
43226c699258SBarry Smith 
43236c699258SBarry Smith   PetscFunctionBegin;
43240700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
43252a808120SBarry Smith   PetscValidHeaderSpecific(dm, DM_CLASSID, 2);
43269566063dSJacob Faibussowitsch   PetscCall(PetscObjectReference((PetscObject)dm));
4327942e3340SBarry Smith   if (ts->dm) { /* Move the DMTS context over to the new DM unless the new DM already has one */
43282a34c10cSBarry Smith     if (ts->dm->dmts && !dm->dmts) {
43299566063dSJacob Faibussowitsch       PetscCall(DMCopyDMTS(ts->dm, dm));
43309566063dSJacob Faibussowitsch       PetscCall(DMGetDMTS(ts->dm, &tsdm));
43311e66621cSBarry Smith       /* Grant write privileges to the replacement DM */
43321e66621cSBarry Smith       if (tsdm->originaldm == ts->dm) tsdm->originaldm = dm;
433324989b8cSPeter Brune     }
43349566063dSJacob Faibussowitsch     PetscCall(DMDestroy(&ts->dm));
433524989b8cSPeter Brune   }
43366c699258SBarry Smith   ts->dm = dm;
4337bbd56ea5SKarl Rupp 
43389566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts, &snes));
43399566063dSJacob Faibussowitsch   PetscCall(SNESSetDM(snes, dm));
43403ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
43416c699258SBarry Smith }
43426c699258SBarry Smith 
43436c699258SBarry Smith /*@
4344bcf0153eSBarry Smith   TSGetDM - Gets the `DM` that may be used by some preconditioners
43456c699258SBarry Smith 
43463f9fe445SBarry Smith   Not Collective
43476c699258SBarry Smith 
43486c699258SBarry Smith   Input Parameter:
4349bcf0153eSBarry Smith . ts - the `TS`
43506c699258SBarry Smith 
43516c699258SBarry Smith   Output Parameter:
4352195e9b02SBarry Smith . dm - the `DM`
43536c699258SBarry Smith 
43546c699258SBarry Smith   Level: intermediate
43556c699258SBarry Smith 
43561cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `DM`, `TSSetDM()`, `SNESSetDM()`, `SNESGetDM()`
43576c699258SBarry Smith @*/
4358d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetDM(TS ts, DM *dm)
4359d71ae5a4SJacob Faibussowitsch {
43606c699258SBarry Smith   PetscFunctionBegin;
43610700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
4362496e6a7aSJed Brown   if (!ts->dm) {
43639566063dSJacob Faibussowitsch     PetscCall(DMShellCreate(PetscObjectComm((PetscObject)ts), &ts->dm));
43649566063dSJacob Faibussowitsch     if (ts->snes) PetscCall(SNESSetDM(ts->snes, ts->dm));
4365496e6a7aSJed Brown   }
43666c699258SBarry Smith   *dm = ts->dm;
43673ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
43686c699258SBarry Smith }
43691713a123SBarry Smith 
43700f5c6efeSJed Brown /*@
43710f5c6efeSJed Brown   SNESTSFormFunction - Function to evaluate nonlinear residual
43720f5c6efeSJed Brown 
4373c3339decSBarry Smith   Logically Collective
43740f5c6efeSJed Brown 
4375d8d19677SJose E. Roman   Input Parameters:
4376d42a1c89SJed Brown + snes - nonlinear solver
43770910c330SBarry Smith . U    - the current state at which to evaluate the residual
4378d42a1c89SJed Brown - ctx  - user context, must be a TS
43790f5c6efeSJed Brown 
43800f5c6efeSJed Brown   Output Parameter:
43810f5c6efeSJed Brown . F - the nonlinear residual
43820f5c6efeSJed Brown 
43830f5c6efeSJed Brown   Level: advanced
43840f5c6efeSJed Brown 
4385bcf0153eSBarry Smith   Note:
4386bcf0153eSBarry Smith   This function is not normally called by users and is automatically registered with the `SNES` used by `TS`.
4387bcf0153eSBarry Smith   It is most frequently passed to `MatFDColoringSetFunction()`.
4388bcf0153eSBarry Smith 
43891cc06b55SBarry Smith .seealso: [](ch_ts), `SNESSetFunction()`, `MatFDColoringSetFunction()`
43900f5c6efeSJed Brown @*/
4391d71ae5a4SJacob Faibussowitsch PetscErrorCode SNESTSFormFunction(SNES snes, Vec U, Vec F, void *ctx)
4392d71ae5a4SJacob Faibussowitsch {
43930f5c6efeSJed Brown   TS ts = (TS)ctx;
43940f5c6efeSJed Brown 
43950f5c6efeSJed Brown   PetscFunctionBegin;
43960f5c6efeSJed Brown   PetscValidHeaderSpecific(snes, SNES_CLASSID, 1);
43970910c330SBarry Smith   PetscValidHeaderSpecific(U, VEC_CLASSID, 2);
43980f5c6efeSJed Brown   PetscValidHeaderSpecific(F, VEC_CLASSID, 3);
43990f5c6efeSJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 4);
44009566063dSJacob Faibussowitsch   PetscCall((ts->ops->snesfunction)(snes, U, F, ts));
44013ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
44020f5c6efeSJed Brown }
44030f5c6efeSJed Brown 
44040f5c6efeSJed Brown /*@
44050f5c6efeSJed Brown   SNESTSFormJacobian - Function to evaluate the Jacobian
44060f5c6efeSJed Brown 
4407c3339decSBarry Smith   Collective
44080f5c6efeSJed Brown 
4409d8d19677SJose E. Roman   Input Parameters:
44100f5c6efeSJed Brown + snes - nonlinear solver
44110910c330SBarry Smith . U    - the current state at which to evaluate the residual
4412bcf0153eSBarry Smith - ctx  - user context, must be a `TS`
44130f5c6efeSJed Brown 
4414d8d19677SJose E. Roman   Output Parameters:
44150f5c6efeSJed Brown + A - the Jacobian
44166b867d5aSJose E. Roman - B - the preconditioning matrix (may be the same as A)
44170f5c6efeSJed Brown 
44180f5c6efeSJed Brown   Level: developer
44190f5c6efeSJed Brown 
4420bcf0153eSBarry Smith   Note:
4421bcf0153eSBarry Smith   This function is not normally called by users and is automatically registered with the `SNES` used by `TS`.
4422bcf0153eSBarry Smith 
44231cc06b55SBarry Smith .seealso: [](ch_ts), `SNESSetJacobian()`
44240f5c6efeSJed Brown @*/
4425d71ae5a4SJacob Faibussowitsch PetscErrorCode SNESTSFormJacobian(SNES snes, Vec U, Mat A, Mat B, void *ctx)
4426d71ae5a4SJacob Faibussowitsch {
44270f5c6efeSJed Brown   TS ts = (TS)ctx;
44280f5c6efeSJed Brown 
44290f5c6efeSJed Brown   PetscFunctionBegin;
44300f5c6efeSJed Brown   PetscValidHeaderSpecific(snes, SNES_CLASSID, 1);
44310910c330SBarry Smith   PetscValidHeaderSpecific(U, VEC_CLASSID, 2);
443294ab13aaSBarry Smith   PetscValidHeaderSpecific(A, MAT_CLASSID, 3);
443394ab13aaSBarry Smith   PetscValidHeaderSpecific(B, MAT_CLASSID, 4);
4434064a246eSJacob Faibussowitsch   PetscValidHeaderSpecific(ts, TS_CLASSID, 5);
44359566063dSJacob Faibussowitsch   PetscCall((ts->ops->snesjacobian)(snes, U, A, B, ts));
44363ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
44370f5c6efeSJed Brown }
4438325fc9f4SBarry Smith 
44390e4ef248SJed Brown /*@C
44409ae8fd06SBarry Smith   TSComputeRHSFunctionLinear - Evaluate the right hand side via the user-provided Jacobian, for linear problems Udot = A U only
44410e4ef248SJed Brown 
4442c3339decSBarry Smith   Collective
44430e4ef248SJed Brown 
44444165533cSJose E. Roman   Input Parameters:
44450e4ef248SJed Brown + ts  - time stepping context
44460e4ef248SJed Brown . t   - time at which to evaluate
44470910c330SBarry Smith . U   - state at which to evaluate
44480e4ef248SJed Brown - ctx - context
44490e4ef248SJed Brown 
44504165533cSJose E. Roman   Output Parameter:
44510e4ef248SJed Brown . F - right hand side
44520e4ef248SJed Brown 
44530e4ef248SJed Brown   Level: intermediate
44540e4ef248SJed Brown 
4455bcf0153eSBarry Smith   Note:
4456bcf0153eSBarry Smith   This function is intended to be passed to `TSSetRHSFunction()` to evaluate the right hand side for linear problems.
4457bcf0153eSBarry Smith   The matrix (and optionally the evaluation context) should be passed to `TSSetRHSJacobian()`.
44580e4ef248SJed Brown 
44591cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetRHSFunction()`, `TSSetRHSJacobian()`, `TSComputeRHSJacobianConstant()`
44600e4ef248SJed Brown @*/
4461d71ae5a4SJacob Faibussowitsch PetscErrorCode TSComputeRHSFunctionLinear(TS ts, PetscReal t, Vec U, Vec F, void *ctx)
4462d71ae5a4SJacob Faibussowitsch {
44630e4ef248SJed Brown   Mat Arhs, Brhs;
44640e4ef248SJed Brown 
44650e4ef248SJed Brown   PetscFunctionBegin;
44669566063dSJacob Faibussowitsch   PetscCall(TSGetRHSMats_Private(ts, &Arhs, &Brhs));
44672663174eSHong Zhang   /* undo the damage caused by shifting */
44689566063dSJacob Faibussowitsch   PetscCall(TSRecoverRHSJacobian(ts, Arhs, Brhs));
44699566063dSJacob Faibussowitsch   PetscCall(TSComputeRHSJacobian(ts, t, U, Arhs, Brhs));
44709566063dSJacob Faibussowitsch   PetscCall(MatMult(Arhs, U, F));
44713ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
44720e4ef248SJed Brown }
44730e4ef248SJed Brown 
44740e4ef248SJed Brown /*@C
44750e4ef248SJed Brown   TSComputeRHSJacobianConstant - Reuses a Jacobian that is time-independent.
44760e4ef248SJed Brown 
4477c3339decSBarry Smith   Collective
44780e4ef248SJed Brown 
44794165533cSJose E. Roman   Input Parameters:
44800e4ef248SJed Brown + ts  - time stepping context
44810e4ef248SJed Brown . t   - time at which to evaluate
44820910c330SBarry Smith . U   - state at which to evaluate
44830e4ef248SJed Brown - ctx - context
44840e4ef248SJed Brown 
44854165533cSJose E. Roman   Output Parameters:
44860e4ef248SJed Brown + A - pointer to operator
448797bb3fdcSJose E. Roman - B - pointer to preconditioning matrix
44880e4ef248SJed Brown 
44890e4ef248SJed Brown   Level: intermediate
44900e4ef248SJed Brown 
4491bcf0153eSBarry Smith   Note:
4492bcf0153eSBarry Smith   This function is intended to be passed to `TSSetRHSJacobian()` to evaluate the Jacobian for linear time-independent problems.
44930e4ef248SJed Brown 
44941cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetRHSFunction()`, `TSSetRHSJacobian()`, `TSComputeRHSFunctionLinear()`
44950e4ef248SJed Brown @*/
4496d71ae5a4SJacob Faibussowitsch PetscErrorCode TSComputeRHSJacobianConstant(TS ts, PetscReal t, Vec U, Mat A, Mat B, void *ctx)
4497d71ae5a4SJacob Faibussowitsch {
44980e4ef248SJed Brown   PetscFunctionBegin;
44993ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
45000e4ef248SJed Brown }
45010e4ef248SJed Brown 
45020026cea9SSean Farley /*@C
45030026cea9SSean Farley   TSComputeIFunctionLinear - Evaluate the left hand side via the user-provided Jacobian, for linear problems only
45040026cea9SSean Farley 
4505c3339decSBarry Smith   Collective
45060026cea9SSean Farley 
45074165533cSJose E. Roman   Input Parameters:
45080026cea9SSean Farley + ts   - time stepping context
45090026cea9SSean Farley . t    - time at which to evaluate
45100910c330SBarry Smith . U    - state at which to evaluate
45110910c330SBarry Smith . Udot - time derivative of state vector
45120026cea9SSean Farley - ctx  - context
45130026cea9SSean Farley 
45144165533cSJose E. Roman   Output Parameter:
45150026cea9SSean Farley . F - left hand side
45160026cea9SSean Farley 
45170026cea9SSean Farley   Level: intermediate
45180026cea9SSean Farley 
45190026cea9SSean Farley   Notes:
45200910c330SBarry 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
4521bcf0153eSBarry Smith   user is required to write their own `TSComputeIFunction()`.
4522bcf0153eSBarry Smith   This function is intended to be passed to `TSSetIFunction()` to evaluate the left hand side for linear problems.
4523bcf0153eSBarry Smith   The matrix (and optionally the evaluation context) should be passed to `TSSetIJacobian()`.
45240026cea9SSean Farley 
4525bcf0153eSBarry Smith   Note that using this function is NOT equivalent to using `TSComputeRHSFunctionLinear()` since that solves Udot = A U
45269ae8fd06SBarry Smith 
45271cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetIFunction()`, `TSSetIJacobian()`, `TSComputeIJacobianConstant()`, `TSComputeRHSFunctionLinear()`
45280026cea9SSean Farley @*/
4529d71ae5a4SJacob Faibussowitsch PetscErrorCode TSComputeIFunctionLinear(TS ts, PetscReal t, Vec U, Vec Udot, Vec F, void *ctx)
4530d71ae5a4SJacob Faibussowitsch {
45310026cea9SSean Farley   Mat A, B;
45320026cea9SSean Farley 
45330026cea9SSean Farley   PetscFunctionBegin;
45349566063dSJacob Faibussowitsch   PetscCall(TSGetIJacobian(ts, &A, &B, NULL, NULL));
45359566063dSJacob Faibussowitsch   PetscCall(TSComputeIJacobian(ts, t, U, Udot, 1.0, A, B, PETSC_TRUE));
45369566063dSJacob Faibussowitsch   PetscCall(MatMult(A, Udot, F));
45373ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
45380026cea9SSean Farley }
45390026cea9SSean Farley 
45400026cea9SSean Farley /*@C
454137c11d98SHong Zhang   TSComputeIJacobianConstant - Reuses the matrix previously computed with the provided `TSIJacobian()` for a semi-implicit DAE or ODE
45420026cea9SSean Farley 
4543c3339decSBarry Smith   Collective
45440026cea9SSean Farley 
45454165533cSJose E. Roman   Input Parameters:
45460026cea9SSean Farley + ts    - time stepping context
45470026cea9SSean Farley . t     - time at which to evaluate
45480910c330SBarry Smith . U     - state at which to evaluate
45490910c330SBarry Smith . Udot  - time derivative of state vector
45500026cea9SSean Farley . shift - shift to apply
45510026cea9SSean Farley - ctx   - context
45520026cea9SSean Farley 
45534165533cSJose E. Roman   Output Parameters:
45540026cea9SSean Farley + A - pointer to operator
455597bb3fdcSJose E. Roman - B - pointer to preconditioning matrix
45560026cea9SSean Farley 
4557b41af12eSJed Brown   Level: advanced
45580026cea9SSean Farley 
45590026cea9SSean Farley   Notes:
4560bcf0153eSBarry Smith   This function is intended to be passed to `TSSetIJacobian()` to evaluate the Jacobian for linear time-independent problems.
45610026cea9SSean Farley 
4562b41af12eSJed Brown   It is only appropriate for problems of the form
4563b41af12eSJed Brown 
4564b41af12eSJed Brown $     M Udot = F(U,t)
4565b41af12eSJed Brown 
4566bcf0153eSBarry Smith   where M is constant and F is non-stiff.  The user must pass M to `TSSetIJacobian()`.  The current implementation only
4567bcf0153eSBarry Smith   works with IMEX time integration methods such as `TSROSW` and `TSARKIMEX`, since there is no support for de-constructing
4568b41af12eSJed Brown   an implicit operator of the form
4569b41af12eSJed Brown 
4570b41af12eSJed Brown $    shift*M + J
4571b41af12eSJed Brown 
4572b41af12eSJed 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
4573b41af12eSJed Brown   a copy of M or reassemble it when requested.
4574b41af12eSJed Brown 
45751cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSROSW`, `TSARKIMEX`, `TSSetIFunction()`, `TSSetIJacobian()`, `TSComputeIFunctionLinear()`
45760026cea9SSean Farley @*/
4577d71ae5a4SJacob Faibussowitsch PetscErrorCode TSComputeIJacobianConstant(TS ts, PetscReal t, Vec U, Vec Udot, PetscReal shift, Mat A, Mat B, void *ctx)
4578d71ae5a4SJacob Faibussowitsch {
45790026cea9SSean Farley   PetscFunctionBegin;
45809566063dSJacob Faibussowitsch   PetscCall(MatScale(A, shift / ts->ijacobian.shift));
4581b41af12eSJed Brown   ts->ijacobian.shift = shift;
45823ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
45830026cea9SSean Farley }
4584b41af12eSJed Brown 
4585e817cc15SEmil Constantinescu /*@
4586bcf0153eSBarry Smith   TSGetEquationType - Gets the type of the equation that `TS` is solving.
4587e817cc15SEmil Constantinescu 
4588e817cc15SEmil Constantinescu   Not Collective
4589e817cc15SEmil Constantinescu 
4590e817cc15SEmil Constantinescu   Input Parameter:
4591bcf0153eSBarry Smith . ts - the `TS` context
4592e817cc15SEmil Constantinescu 
4593e817cc15SEmil Constantinescu   Output Parameter:
4594bcf0153eSBarry Smith . equation_type - see `TSEquationType`
4595e817cc15SEmil Constantinescu 
4596e817cc15SEmil Constantinescu   Level: beginner
4597e817cc15SEmil Constantinescu 
45981cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetEquationType()`, `TSEquationType`
4599e817cc15SEmil Constantinescu @*/
4600d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetEquationType(TS ts, TSEquationType *equation_type)
4601d71ae5a4SJacob Faibussowitsch {
4602e817cc15SEmil Constantinescu   PetscFunctionBegin;
4603e817cc15SEmil Constantinescu   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
46044f572ea9SToby Isaac   PetscAssertPointer(equation_type, 2);
4605e817cc15SEmil Constantinescu   *equation_type = ts->equation_type;
46063ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
4607e817cc15SEmil Constantinescu }
4608e817cc15SEmil Constantinescu 
4609e817cc15SEmil Constantinescu /*@
4610bcf0153eSBarry Smith   TSSetEquationType - Sets the type of the equation that `TS` is solving.
4611e817cc15SEmil Constantinescu 
4612e817cc15SEmil Constantinescu   Not Collective
4613e817cc15SEmil Constantinescu 
4614d8d19677SJose E. Roman   Input Parameters:
4615bcf0153eSBarry Smith + ts            - the `TS` context
4616bcf0153eSBarry Smith - equation_type - see `TSEquationType`
4617e817cc15SEmil Constantinescu 
4618e817cc15SEmil Constantinescu   Level: advanced
4619e817cc15SEmil Constantinescu 
46201cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSGetEquationType()`, `TSEquationType`
4621e817cc15SEmil Constantinescu @*/
4622d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetEquationType(TS ts, TSEquationType equation_type)
4623d71ae5a4SJacob Faibussowitsch {
4624e817cc15SEmil Constantinescu   PetscFunctionBegin;
4625e817cc15SEmil Constantinescu   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
4626e817cc15SEmil Constantinescu   ts->equation_type = equation_type;
46273ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
4628e817cc15SEmil Constantinescu }
46290026cea9SSean Farley 
46304af1b03aSJed Brown /*@
4631bcf0153eSBarry Smith   TSGetConvergedReason - Gets the reason the `TS` iteration was stopped.
46324af1b03aSJed Brown 
46334af1b03aSJed Brown   Not Collective
46344af1b03aSJed Brown 
46354af1b03aSJed Brown   Input Parameter:
4636bcf0153eSBarry Smith . ts - the `TS` context
46374af1b03aSJed Brown 
46384af1b03aSJed Brown   Output Parameter:
4639bcf0153eSBarry Smith . reason - negative value indicates diverged, positive value converged, see `TSConvergedReason` or the
46404af1b03aSJed Brown             manual pages for the individual convergence tests for complete lists
46414af1b03aSJed Brown 
4642487e0bb9SJed Brown   Level: beginner
46434af1b03aSJed Brown 
4644bcf0153eSBarry Smith   Note:
4645bcf0153eSBarry Smith   Can only be called after the call to `TSSolve()` is complete.
46464af1b03aSJed Brown 
46471cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSolve()`, `TSSetConvergenceTest()`, `TSConvergedReason`
46484af1b03aSJed Brown @*/
4649d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetConvergedReason(TS ts, TSConvergedReason *reason)
4650d71ae5a4SJacob Faibussowitsch {
46514af1b03aSJed Brown   PetscFunctionBegin;
46524af1b03aSJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
46534f572ea9SToby Isaac   PetscAssertPointer(reason, 2);
46544af1b03aSJed Brown   *reason = ts->reason;
46553ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
46564af1b03aSJed Brown }
46574af1b03aSJed Brown 
4658d6ad946cSShri Abhyankar /*@
4659bcf0153eSBarry Smith   TSSetConvergedReason - Sets the reason for handling the convergence of `TSSolve()`.
4660d6ad946cSShri Abhyankar 
46616b221cbeSPatrick Sanan   Logically Collective; reason must contain common value
4662d6ad946cSShri Abhyankar 
46636b221cbeSPatrick Sanan   Input Parameters:
4664bcf0153eSBarry Smith + ts     - the `TS` context
4665bcf0153eSBarry Smith - reason - negative value indicates diverged, positive value converged, see `TSConvergedReason` or the
4666d6ad946cSShri Abhyankar             manual pages for the individual convergence tests for complete lists
4667d6ad946cSShri Abhyankar 
4668f5abba47SShri Abhyankar   Level: advanced
4669d6ad946cSShri Abhyankar 
4670bcf0153eSBarry Smith   Note:
4671bcf0153eSBarry Smith   Can only be called while `TSSolve()` is active.
4672d6ad946cSShri Abhyankar 
46731cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSolve()`, `TSConvergedReason`
4674d6ad946cSShri Abhyankar @*/
4675d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetConvergedReason(TS ts, TSConvergedReason reason)
4676d71ae5a4SJacob Faibussowitsch {
4677d6ad946cSShri Abhyankar   PetscFunctionBegin;
4678d6ad946cSShri Abhyankar   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
4679d6ad946cSShri Abhyankar   ts->reason = reason;
46803ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
4681d6ad946cSShri Abhyankar }
4682d6ad946cSShri Abhyankar 
4683cc708dedSBarry Smith /*@
4684bcf0153eSBarry Smith   TSGetSolveTime - Gets the time after a call to `TSSolve()`
4685cc708dedSBarry Smith 
4686cc708dedSBarry Smith   Not Collective
4687cc708dedSBarry Smith 
4688cc708dedSBarry Smith   Input Parameter:
4689bcf0153eSBarry Smith . ts - the `TS` context
4690cc708dedSBarry Smith 
4691cc708dedSBarry Smith   Output Parameter:
4692bcf0153eSBarry Smith . ftime - the final time. This time corresponds to the final time set with `TSSetMaxTime()`
4693cc708dedSBarry Smith 
4694487e0bb9SJed Brown   Level: beginner
4695cc708dedSBarry Smith 
4696bcf0153eSBarry Smith   Note:
4697bcf0153eSBarry Smith   Can only be called after the call to `TSSolve()` is complete.
4698cc708dedSBarry Smith 
46991cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSolve()`, `TSSetConvergenceTest()`, `TSConvergedReason`
4700cc708dedSBarry Smith @*/
4701d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetSolveTime(TS ts, PetscReal *ftime)
4702d71ae5a4SJacob Faibussowitsch {
4703cc708dedSBarry Smith   PetscFunctionBegin;
4704cc708dedSBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
47054f572ea9SToby Isaac   PetscAssertPointer(ftime, 2);
4706cc708dedSBarry Smith   *ftime = ts->solvetime;
47073ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
4708cc708dedSBarry Smith }
4709cc708dedSBarry Smith 
47102c18e0fdSBarry Smith /*@
47115ef26d82SJed Brown   TSGetSNESIterations - Gets the total number of nonlinear iterations
47129f67acb7SJed Brown   used by the time integrator.
47139f67acb7SJed Brown 
47149f67acb7SJed Brown   Not Collective
47159f67acb7SJed Brown 
47169f67acb7SJed Brown   Input Parameter:
4717bcf0153eSBarry Smith . ts - `TS` context
47189f67acb7SJed Brown 
47199f67acb7SJed Brown   Output Parameter:
47209f67acb7SJed Brown . nits - number of nonlinear iterations
47219f67acb7SJed Brown 
47229f67acb7SJed Brown   Level: intermediate
47239f67acb7SJed Brown 
4724195e9b02SBarry Smith   Note:
4725bcf0153eSBarry Smith   This counter is reset to zero for each successive call to `TSSolve()`.
4726bcf0153eSBarry Smith 
47271cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSolve()`, `TSGetKSPIterations()`
47289f67acb7SJed Brown @*/
4729d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetSNESIterations(TS ts, PetscInt *nits)
4730d71ae5a4SJacob Faibussowitsch {
47319f67acb7SJed Brown   PetscFunctionBegin;
47329f67acb7SJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
47334f572ea9SToby Isaac   PetscAssertPointer(nits, 2);
47345ef26d82SJed Brown   *nits = ts->snes_its;
47353ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
47369f67acb7SJed Brown }
47379f67acb7SJed Brown 
47389f67acb7SJed Brown /*@
47395ef26d82SJed Brown   TSGetKSPIterations - Gets the total number of linear iterations
47409f67acb7SJed Brown   used by the time integrator.
47419f67acb7SJed Brown 
47429f67acb7SJed Brown   Not Collective
47439f67acb7SJed Brown 
47449f67acb7SJed Brown   Input Parameter:
4745bcf0153eSBarry Smith . ts - `TS` context
47469f67acb7SJed Brown 
47479f67acb7SJed Brown   Output Parameter:
47489f67acb7SJed Brown . lits - number of linear iterations
47499f67acb7SJed Brown 
47509f67acb7SJed Brown   Level: intermediate
47519f67acb7SJed Brown 
4752bcf0153eSBarry Smith   Note:
4753bcf0153eSBarry Smith   This counter is reset to zero for each successive call to `TSSolve()`.
4754bcf0153eSBarry Smith 
47551cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSolve()`, `TSGetSNESIterations()`, `SNESGetKSPIterations()`
47569f67acb7SJed Brown @*/
4757d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetKSPIterations(TS ts, PetscInt *lits)
4758d71ae5a4SJacob Faibussowitsch {
47599f67acb7SJed Brown   PetscFunctionBegin;
47609f67acb7SJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
47614f572ea9SToby Isaac   PetscAssertPointer(lits, 2);
47625ef26d82SJed Brown   *lits = ts->ksp_its;
47633ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
47649f67acb7SJed Brown }
47659f67acb7SJed Brown 
4766cef5090cSJed Brown /*@
4767cef5090cSJed Brown   TSGetStepRejections - Gets the total number of rejected steps.
4768cef5090cSJed Brown 
4769cef5090cSJed Brown   Not Collective
4770cef5090cSJed Brown 
4771cef5090cSJed Brown   Input Parameter:
4772bcf0153eSBarry Smith . ts - `TS` context
4773cef5090cSJed Brown 
4774cef5090cSJed Brown   Output Parameter:
4775cef5090cSJed Brown . rejects - number of steps rejected
4776cef5090cSJed Brown 
4777cef5090cSJed Brown   Level: intermediate
4778cef5090cSJed Brown 
4779bcf0153eSBarry Smith   Note:
4780bcf0153eSBarry Smith   This counter is reset to zero for each successive call to `TSSolve()`.
4781bcf0153eSBarry Smith 
47821cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSolve()`, `TSGetSNESIterations()`, `TSGetKSPIterations()`, `TSSetMaxStepRejections()`, `TSGetSNESFailures()`, `TSSetMaxSNESFailures()`, `TSSetErrorIfStepFails()`
4783cef5090cSJed Brown @*/
4784d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetStepRejections(TS ts, PetscInt *rejects)
4785d71ae5a4SJacob Faibussowitsch {
4786cef5090cSJed Brown   PetscFunctionBegin;
4787cef5090cSJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
47884f572ea9SToby Isaac   PetscAssertPointer(rejects, 2);
4789cef5090cSJed Brown   *rejects = ts->reject;
47903ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
4791cef5090cSJed Brown }
4792cef5090cSJed Brown 
4793cef5090cSJed Brown /*@
4794bcf0153eSBarry Smith   TSGetSNESFailures - Gets the total number of failed `SNES` solves in a `TS`
4795cef5090cSJed Brown 
4796cef5090cSJed Brown   Not Collective
4797cef5090cSJed Brown 
4798cef5090cSJed Brown   Input Parameter:
4799bcf0153eSBarry Smith . ts - `TS` context
4800cef5090cSJed Brown 
4801cef5090cSJed Brown   Output Parameter:
4802cef5090cSJed Brown . fails - number of failed nonlinear solves
4803cef5090cSJed Brown 
4804cef5090cSJed Brown   Level: intermediate
4805cef5090cSJed Brown 
4806bcf0153eSBarry Smith   Note:
4807bcf0153eSBarry Smith   This counter is reset to zero for each successive call to `TSSolve()`.
4808bcf0153eSBarry Smith 
48091cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSolve()`, `TSGetSNESIterations()`, `TSGetKSPIterations()`, `TSSetMaxStepRejections()`, `TSGetStepRejections()`, `TSSetMaxSNESFailures()`
4810cef5090cSJed Brown @*/
4811d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetSNESFailures(TS ts, PetscInt *fails)
4812d71ae5a4SJacob Faibussowitsch {
4813cef5090cSJed Brown   PetscFunctionBegin;
4814cef5090cSJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
48154f572ea9SToby Isaac   PetscAssertPointer(fails, 2);
4816cef5090cSJed Brown   *fails = ts->num_snes_failures;
48173ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
4818cef5090cSJed Brown }
4819cef5090cSJed Brown 
4820cef5090cSJed Brown /*@
4821bcf0153eSBarry Smith   TSSetMaxStepRejections - Sets the maximum number of step rejections before a time step fails
4822cef5090cSJed Brown 
4823cef5090cSJed Brown   Not Collective
4824cef5090cSJed Brown 
4825d8d19677SJose E. Roman   Input Parameters:
4826bcf0153eSBarry Smith + ts      - `TS` context
4827cef5090cSJed Brown - rejects - maximum number of rejected steps, pass -1 for unlimited
4828cef5090cSJed Brown 
4829cef5090cSJed Brown   Options Database Key:
4830cef5090cSJed Brown . -ts_max_reject - Maximum number of step rejections before a step fails
4831cef5090cSJed Brown 
4832cef5090cSJed Brown   Level: intermediate
4833cef5090cSJed Brown 
48341cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `SNES`, `TSGetSNESIterations()`, `TSGetKSPIterations()`, `TSSetMaxSNESFailures()`, `TSGetStepRejections()`, `TSGetSNESFailures()`, `TSSetErrorIfStepFails()`, `TSGetConvergedReason()`
4835cef5090cSJed Brown @*/
4836d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetMaxStepRejections(TS ts, PetscInt rejects)
4837d71ae5a4SJacob Faibussowitsch {
4838cef5090cSJed Brown   PetscFunctionBegin;
4839cef5090cSJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
4840cef5090cSJed Brown   ts->max_reject = rejects;
48413ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
4842cef5090cSJed Brown }
4843cef5090cSJed Brown 
4844cef5090cSJed Brown /*@
4845bcf0153eSBarry Smith   TSSetMaxSNESFailures - Sets the maximum number of failed `SNES` solves
4846cef5090cSJed Brown 
4847cef5090cSJed Brown   Not Collective
4848cef5090cSJed Brown 
4849d8d19677SJose E. Roman   Input Parameters:
4850bcf0153eSBarry Smith + ts    - `TS` context
4851cef5090cSJed Brown - fails - maximum number of failed nonlinear solves, pass -1 for unlimited
4852cef5090cSJed Brown 
4853cef5090cSJed Brown   Options Database Key:
4854cef5090cSJed Brown . -ts_max_snes_failures - Maximum number of nonlinear solve failures
4855cef5090cSJed Brown 
4856cef5090cSJed Brown   Level: intermediate
4857cef5090cSJed Brown 
48581cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `SNES`, `TSGetSNESIterations()`, `TSGetKSPIterations()`, `TSSetMaxStepRejections()`, `TSGetStepRejections()`, `TSGetSNESFailures()`, `SNESGetConvergedReason()`, `TSGetConvergedReason()`
4859cef5090cSJed Brown @*/
4860d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetMaxSNESFailures(TS ts, PetscInt fails)
4861d71ae5a4SJacob Faibussowitsch {
4862cef5090cSJed Brown   PetscFunctionBegin;
4863cef5090cSJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
4864cef5090cSJed Brown   ts->max_snes_failures = fails;
48653ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
4866cef5090cSJed Brown }
4867cef5090cSJed Brown 
4868cef5090cSJed Brown /*@
4869195e9b02SBarry Smith   TSSetErrorIfStepFails - Immediately error if no step succeeds during `TSSolve()`
4870cef5090cSJed Brown 
4871cef5090cSJed Brown   Not Collective
4872cef5090cSJed Brown 
4873d8d19677SJose E. Roman   Input Parameters:
4874bcf0153eSBarry Smith + ts  - `TS` context
4875bcf0153eSBarry Smith - err - `PETSC_TRUE` to error if no step succeeds, `PETSC_FALSE` to return without failure
4876cef5090cSJed Brown 
4877cef5090cSJed Brown   Options Database Key:
4878cef5090cSJed Brown . -ts_error_if_step_fails - Error if no step succeeds
4879cef5090cSJed Brown 
4880cef5090cSJed Brown   Level: intermediate
4881cef5090cSJed Brown 
488242747ad1SJacob Faibussowitsch .seealso: [](ch_ts), `TS`, `TSGetSNESIterations()`, `TSGetKSPIterations()`, `TSSetMaxStepRejections()`, `TSGetStepRejections()`, `TSGetSNESFailures()`, `TSGetConvergedReason()`
4883cef5090cSJed Brown @*/
4884d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetErrorIfStepFails(TS ts, PetscBool err)
4885d71ae5a4SJacob Faibussowitsch {
4886cef5090cSJed Brown   PetscFunctionBegin;
4887cef5090cSJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
4888cef5090cSJed Brown   ts->errorifstepfailed = err;
48893ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
4890cef5090cSJed Brown }
4891cef5090cSJed Brown 
489284df9cb4SJed Brown /*@
4893552698daSJed Brown   TSGetAdapt - Get the adaptive controller context for the current method
489484df9cb4SJed Brown 
48958f14a041SBarry Smith   Collective if controller has not yet been created
489684df9cb4SJed Brown 
48974165533cSJose E. Roman   Input Parameter:
4898ed81e22dSJed Brown . ts - time stepping context
489984df9cb4SJed Brown 
49004165533cSJose E. Roman   Output Parameter:
4901ed81e22dSJed Brown . adapt - adaptive controller
490284df9cb4SJed Brown 
490384df9cb4SJed Brown   Level: intermediate
490484df9cb4SJed Brown 
49051cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSAdapt`, `TSAdaptSetType()`, `TSAdaptChoose()`
490684df9cb4SJed Brown @*/
4907d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetAdapt(TS ts, TSAdapt *adapt)
4908d71ae5a4SJacob Faibussowitsch {
490984df9cb4SJed Brown   PetscFunctionBegin;
491084df9cb4SJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
49114f572ea9SToby Isaac   PetscAssertPointer(adapt, 2);
491284df9cb4SJed Brown   if (!ts->adapt) {
49139566063dSJacob Faibussowitsch     PetscCall(TSAdaptCreate(PetscObjectComm((PetscObject)ts), &ts->adapt));
49149566063dSJacob Faibussowitsch     PetscCall(PetscObjectIncrementTabLevel((PetscObject)ts->adapt, (PetscObject)ts, 1));
491584df9cb4SJed Brown   }
4916bec58848SLisandro Dalcin   *adapt = ts->adapt;
49173ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
491884df9cb4SJed Brown }
4919d6ebe24aSShri Abhyankar 
49201c3436cfSJed Brown /*@
4921195e9b02SBarry Smith   TSSetTolerances - Set tolerances for local truncation error when using an adaptive controller
49221c3436cfSJed Brown 
49231c3436cfSJed Brown   Logically Collective
49241c3436cfSJed Brown 
49254165533cSJose E. Roman   Input Parameters:
49261c3436cfSJed Brown + ts    - time integration context
4927bcf0153eSBarry Smith . atol  - scalar absolute tolerances, `PETSC_DECIDE` to leave current value
4928195e9b02SBarry Smith . vatol - vector of absolute tolerances or `NULL`, used in preference to atol if present
4929bcf0153eSBarry Smith . rtol  - scalar relative tolerances, `PETSC_DECIDE` to leave current value
4930195e9b02SBarry Smith - vrtol - vector of relative tolerances or `NULL`, used in preference to atol if present
49311c3436cfSJed Brown 
4932195e9b02SBarry Smith   Options Database Keys:
4933a3cdaa26SBarry Smith + -ts_rtol <rtol> - relative tolerance for local truncation error
493467b8a455SSatish Balay - -ts_atol <atol> - Absolute tolerance for local truncation error
4935a3cdaa26SBarry Smith 
4936bcf0153eSBarry Smith   Level: beginner
4937bcf0153eSBarry Smith 
49383ff766beSShri Abhyankar   Notes:
49393ff766beSShri Abhyankar   With PETSc's implicit schemes for DAE problems, the calculation of the local truncation error
49403ff766beSShri Abhyankar   (LTE) includes both the differential and the algebraic variables. If one wants the LTE to be
49413ff766beSShri Abhyankar   computed only for the differential or the algebraic part then this can be done using the vector of
49423ff766beSShri Abhyankar   tolerances vatol. For example, by setting the tolerance vector with the desired tolerance for the
49433ff766beSShri Abhyankar   differential part and infinity for the algebraic part, the LTE calculation will include only the
49443ff766beSShri Abhyankar   differential variables.
49453ff766beSShri Abhyankar 
49461cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSAdapt`, `TSErrorWeightedNorm()`, `TSGetTolerances()`
49471c3436cfSJed Brown @*/
4948d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetTolerances(TS ts, PetscReal atol, Vec vatol, PetscReal rtol, Vec vrtol)
4949d71ae5a4SJacob Faibussowitsch {
49501c3436cfSJed Brown   PetscFunctionBegin;
495113bcc0bdSJacob Faibussowitsch   if (atol != (PetscReal)PETSC_DECIDE && atol != (PetscReal)PETSC_DEFAULT) ts->atol = atol;
49521c3436cfSJed Brown   if (vatol) {
49539566063dSJacob Faibussowitsch     PetscCall(PetscObjectReference((PetscObject)vatol));
49549566063dSJacob Faibussowitsch     PetscCall(VecDestroy(&ts->vatol));
49551c3436cfSJed Brown     ts->vatol = vatol;
49561c3436cfSJed Brown   }
495713bcc0bdSJacob Faibussowitsch   if (rtol != (PetscReal)PETSC_DECIDE && rtol != (PetscReal)PETSC_DEFAULT) ts->rtol = rtol;
49581c3436cfSJed Brown   if (vrtol) {
49599566063dSJacob Faibussowitsch     PetscCall(PetscObjectReference((PetscObject)vrtol));
49609566063dSJacob Faibussowitsch     PetscCall(VecDestroy(&ts->vrtol));
49611c3436cfSJed Brown     ts->vrtol = vrtol;
49621c3436cfSJed Brown   }
49633ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
49641c3436cfSJed Brown }
49651c3436cfSJed Brown 
4966c5033834SJed Brown /*@
4967c5033834SJed Brown   TSGetTolerances - Get tolerances for local truncation error when using adaptive controller
4968c5033834SJed Brown 
4969c5033834SJed Brown   Logically Collective
4970c5033834SJed Brown 
49714165533cSJose E. Roman   Input Parameter:
4972c5033834SJed Brown . ts - time integration context
4973c5033834SJed Brown 
49744165533cSJose E. Roman   Output Parameters:
4975195e9b02SBarry Smith + atol  - scalar absolute tolerances, `NULL` to ignore
4976195e9b02SBarry Smith . vatol - vector of absolute tolerances, `NULL` to ignore
4977195e9b02SBarry Smith . rtol  - scalar relative tolerances, `NULL` to ignore
4978195e9b02SBarry Smith - vrtol - vector of relative tolerances, `NULL` to ignore
4979c5033834SJed Brown 
4980c5033834SJed Brown   Level: beginner
4981c5033834SJed Brown 
49821cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSAdapt`, `TSErrorWeightedNorm()`, `TSSetTolerances()`
4983c5033834SJed Brown @*/
4984d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetTolerances(TS ts, PetscReal *atol, Vec *vatol, PetscReal *rtol, Vec *vrtol)
4985d71ae5a4SJacob Faibussowitsch {
4986c5033834SJed Brown   PetscFunctionBegin;
4987c5033834SJed Brown   if (atol) *atol = ts->atol;
4988c5033834SJed Brown   if (vatol) *vatol = ts->vatol;
4989c5033834SJed Brown   if (rtol) *rtol = ts->rtol;
4990c5033834SJed Brown   if (vrtol) *vrtol = ts->vrtol;
49913ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
4992c5033834SJed Brown }
4993c5033834SJed Brown 
49949c6b16b5SShri Abhyankar /*@
49958a175baeSEmil Constantinescu   TSErrorWeightedNorm - compute a weighted norm of the difference between two state vectors based on supplied absolute and relative tolerances
49961c3436cfSJed Brown 
4997c3339decSBarry Smith   Collective
49981c3436cfSJed Brown 
49994165533cSJose E. Roman   Input Parameters:
50001c3436cfSJed Brown + ts        - time stepping context
5001a4868fbcSLisandro Dalcin . U         - state vector, usually ts->vec_sol
5002a4868fbcSLisandro Dalcin . Y         - state vector to be compared to U
5003bcf0153eSBarry Smith - wnormtype - norm type, either `NORM_2` or `NORM_INFINITY`
50047619abb3SShri 
50054165533cSJose E. Roman   Output Parameters:
5006a2b725a8SWilliam Gropp + norm  - weighted norm, a value of 1.0 achieves a balance between absolute and relative tolerances
50078a175baeSEmil Constantinescu . norma - weighted norm, a value of 1.0 means that the error meets the absolute tolerance set by the user
5008a2b725a8SWilliam Gropp - normr - weighted norm, a value of 1.0 means that the error meets the relative tolerance set by the user
5009a4868fbcSLisandro Dalcin 
5010bcf0153eSBarry Smith   Options Database Key:
5011a4868fbcSLisandro Dalcin . -ts_adapt_wnormtype <wnormtype> - 2, INFINITY
5012a4868fbcSLisandro Dalcin 
50131c3436cfSJed Brown   Level: developer
50141c3436cfSJed Brown 
50158c38e02aSSatish Balay .seealso: [](ch_ts), `TS`, `VecErrorWeightedNorms()`, `TSErrorWeightedENorm()`
50161c3436cfSJed Brown @*/
5017d71ae5a4SJacob Faibussowitsch PetscErrorCode TSErrorWeightedNorm(TS ts, Vec U, Vec Y, NormType wnormtype, PetscReal *norm, PetscReal *norma, PetscReal *normr)
5018d71ae5a4SJacob Faibussowitsch {
5019037d63e4SStefano Zampini   PetscInt norma_loc, norm_loc, normr_loc;
50208a175baeSEmil Constantinescu 
50218a175baeSEmil Constantinescu   PetscFunctionBegin;
50228a175baeSEmil Constantinescu   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
5023037d63e4SStefano Zampini   PetscCall(VecErrorWeightedNorms(U, Y, NULL, wnormtype, ts->atol, ts->vatol, ts->rtol, ts->vrtol, ts->adapt->ignore_max, norm, &norm_loc, norma, &norma_loc, normr, &normr_loc));
5024037d63e4SStefano Zampini   if (wnormtype == NORM_2) {
5025037d63e4SStefano Zampini     if (norm_loc) *norm = PetscSqrtReal(PetscSqr(*norm) / norm_loc);
5026037d63e4SStefano Zampini     if (norma_loc) *norma = PetscSqrtReal(PetscSqr(*norma) / norma_loc);
5027037d63e4SStefano Zampini     if (normr_loc) *normr = PetscSqrtReal(PetscSqr(*normr) / normr_loc);
50288a175baeSEmil Constantinescu   }
50293c633725SBarry Smith   PetscCheck(!PetscIsInfOrNanScalar(*norm), PetscObjectComm((PetscObject)ts), PETSC_ERR_FP, "Infinite or not-a-number generated in norm");
50303c633725SBarry Smith   PetscCheck(!PetscIsInfOrNanScalar(*norma), PetscObjectComm((PetscObject)ts), PETSC_ERR_FP, "Infinite or not-a-number generated in norma");
50313c633725SBarry Smith   PetscCheck(!PetscIsInfOrNanScalar(*normr), PetscObjectComm((PetscObject)ts), PETSC_ERR_FP, "Infinite or not-a-number generated in normr");
50323ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
50338a175baeSEmil Constantinescu }
50348a175baeSEmil Constantinescu 
50358a175baeSEmil Constantinescu /*@
50368a175baeSEmil Constantinescu   TSErrorWeightedENorm - compute a weighted error norm based on supplied absolute and relative tolerances
50378a175baeSEmil Constantinescu 
5038c3339decSBarry Smith   Collective
50398a175baeSEmil Constantinescu 
50404165533cSJose E. Roman   Input Parameters:
50418a175baeSEmil Constantinescu + ts        - time stepping context
50428a175baeSEmil Constantinescu . E         - error vector
50438a175baeSEmil Constantinescu . U         - state vector, usually ts->vec_sol
50448a175baeSEmil Constantinescu . Y         - state vector, previous time step
5045bcf0153eSBarry Smith - wnormtype - norm type, either `NORM_2` or `NORM_INFINITY`
50468a175baeSEmil Constantinescu 
50474165533cSJose E. Roman   Output Parameters:
5048a2b725a8SWilliam Gropp + norm  - weighted norm, a value of 1.0 achieves a balance between absolute and relative tolerances
50498a175baeSEmil Constantinescu . norma - weighted norm, a value of 1.0 means that the error meets the absolute tolerance set by the user
5050a2b725a8SWilliam Gropp - normr - weighted norm, a value of 1.0 means that the error meets the relative tolerance set by the user
50518a175baeSEmil Constantinescu 
5052bcf0153eSBarry Smith   Options Database Key:
50538a175baeSEmil Constantinescu . -ts_adapt_wnormtype <wnormtype> - 2, INFINITY
50548a175baeSEmil Constantinescu 
50558a175baeSEmil Constantinescu   Level: developer
50568a175baeSEmil Constantinescu 
50578c38e02aSSatish Balay .seealso: [](ch_ts), `TS`, `VecErrorWeightedNorms()`, `TSErrorWeightedNorm()`
50588a175baeSEmil Constantinescu @*/
5059d71ae5a4SJacob Faibussowitsch PetscErrorCode TSErrorWeightedENorm(TS ts, Vec E, Vec U, Vec Y, NormType wnormtype, PetscReal *norm, PetscReal *norma, PetscReal *normr)
5060d71ae5a4SJacob Faibussowitsch {
5061037d63e4SStefano Zampini   PetscInt norma_loc, norm_loc, normr_loc;
5062037d63e4SStefano Zampini 
50638a175baeSEmil Constantinescu   PetscFunctionBegin;
5064037d63e4SStefano Zampini   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
5065037d63e4SStefano Zampini   PetscCall(VecErrorWeightedNorms(U, Y, E, wnormtype, ts->atol, ts->vatol, ts->rtol, ts->vrtol, ts->adapt->ignore_max, norm, &norm_loc, norma, &norma_loc, normr, &normr_loc));
5066037d63e4SStefano Zampini   if (wnormtype == NORM_2) {
5067037d63e4SStefano Zampini     if (norm_loc) *norm = PetscSqrtReal(PetscSqr(*norm) / norm_loc);
5068037d63e4SStefano Zampini     if (norma_loc) *norma = PetscSqrtReal(PetscSqr(*norma) / norma_loc);
5069037d63e4SStefano Zampini     if (normr_loc) *normr = PetscSqrtReal(PetscSqr(*normr) / normr_loc);
5070037d63e4SStefano Zampini   }
5071037d63e4SStefano Zampini   PetscCheck(!PetscIsInfOrNanScalar(*norm), PetscObjectComm((PetscObject)ts), PETSC_ERR_FP, "Infinite or not-a-number generated in norm");
5072037d63e4SStefano Zampini   PetscCheck(!PetscIsInfOrNanScalar(*norma), PetscObjectComm((PetscObject)ts), PETSC_ERR_FP, "Infinite or not-a-number generated in norma");
5073037d63e4SStefano Zampini   PetscCheck(!PetscIsInfOrNanScalar(*normr), PetscObjectComm((PetscObject)ts), PETSC_ERR_FP, "Infinite or not-a-number generated in normr");
50743ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
50758a175baeSEmil Constantinescu }
50768a175baeSEmil Constantinescu 
50778d59e960SJed Brown /*@
50788d59e960SJed Brown   TSSetCFLTimeLocal - Set the local CFL constraint relative to forward Euler
50798d59e960SJed Brown 
5080c3339decSBarry Smith   Logically Collective
50818d59e960SJed Brown 
50824165533cSJose E. Roman   Input Parameters:
50838d59e960SJed Brown + ts      - time stepping context
50848d59e960SJed Brown - cfltime - maximum stable time step if using forward Euler (value can be different on each process)
50858d59e960SJed Brown 
50868d59e960SJed Brown   Note:
50878d59e960SJed Brown   After calling this function, the global CFL time can be obtained by calling TSGetCFLTime()
50888d59e960SJed Brown 
50898d59e960SJed Brown   Level: intermediate
50908d59e960SJed Brown 
50911cc06b55SBarry Smith .seealso: [](ch_ts), `TSGetCFLTime()`, `TSADAPTCFL`
50928d59e960SJed Brown @*/
5093d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetCFLTimeLocal(TS ts, PetscReal cfltime)
5094d71ae5a4SJacob Faibussowitsch {
50958d59e960SJed Brown   PetscFunctionBegin;
50968d59e960SJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
50978d59e960SJed Brown   ts->cfltime_local = cfltime;
50988d59e960SJed Brown   ts->cfltime       = -1.;
50993ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
51008d59e960SJed Brown }
51018d59e960SJed Brown 
51028d59e960SJed Brown /*@
51038d59e960SJed Brown   TSGetCFLTime - Get the maximum stable time step according to CFL criteria applied to forward Euler
51048d59e960SJed Brown 
5105c3339decSBarry Smith   Collective
51068d59e960SJed Brown 
51074165533cSJose E. Roman   Input Parameter:
51088d59e960SJed Brown . ts - time stepping context
51098d59e960SJed Brown 
51104165533cSJose E. Roman   Output Parameter:
51118d59e960SJed Brown . cfltime - maximum stable time step for forward Euler
51128d59e960SJed Brown 
51138d59e960SJed Brown   Level: advanced
51148d59e960SJed Brown 
51151cc06b55SBarry Smith .seealso: [](ch_ts), `TSSetCFLTimeLocal()`
51168d59e960SJed Brown @*/
5117d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetCFLTime(TS ts, PetscReal *cfltime)
5118d71ae5a4SJacob Faibussowitsch {
51198d59e960SJed Brown   PetscFunctionBegin;
51201e66621cSBarry Smith   if (ts->cfltime < 0) PetscCall(MPIU_Allreduce(&ts->cfltime_local, &ts->cfltime, 1, MPIU_REAL, MPIU_MIN, PetscObjectComm((PetscObject)ts)));
51218d59e960SJed Brown   *cfltime = ts->cfltime;
51223ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
51238d59e960SJed Brown }
51248d59e960SJed Brown 
5125d6ebe24aSShri Abhyankar /*@
5126d6ebe24aSShri Abhyankar   TSVISetVariableBounds - Sets the lower and upper bounds for the solution vector. xl <= x <= xu
5127d6ebe24aSShri Abhyankar 
5128d6ebe24aSShri Abhyankar   Input Parameters:
5129bcf0153eSBarry Smith + ts - the `TS` context.
5130d6ebe24aSShri Abhyankar . xl - lower bound.
5131a2b725a8SWilliam Gropp - xu - upper bound.
5132d6ebe24aSShri Abhyankar 
51332bd2b0e6SSatish Balay   Level: advanced
51342bd2b0e6SSatish Balay 
5135bcf0153eSBarry Smith   Note:
5136bcf0153eSBarry Smith   If this routine is not called then the lower and upper bounds are set to
5137bcf0153eSBarry Smith   `PETSC_NINFINITY` and `PETSC_INFINITY` respectively during `SNESSetUp()`.
5138bcf0153eSBarry Smith 
51391cc06b55SBarry Smith .seealso: [](ch_ts), `TS`
5140d6ebe24aSShri Abhyankar @*/
5141d71ae5a4SJacob Faibussowitsch PetscErrorCode TSVISetVariableBounds(TS ts, Vec xl, Vec xu)
5142d71ae5a4SJacob Faibussowitsch {
5143d6ebe24aSShri Abhyankar   SNES snes;
5144d6ebe24aSShri Abhyankar 
5145d6ebe24aSShri Abhyankar   PetscFunctionBegin;
51469566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts, &snes));
51479566063dSJacob Faibussowitsch   PetscCall(SNESVISetVariableBounds(snes, xl, xu));
51483ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
5149d6ebe24aSShri Abhyankar }
5150d6ebe24aSShri Abhyankar 
5151f9c1d6abSBarry Smith /*@
5152f9c1d6abSBarry Smith   TSComputeLinearStability - computes the linear stability function at a point
5153f9c1d6abSBarry Smith 
5154c3339decSBarry Smith   Collective
5155f9c1d6abSBarry Smith 
5156f9c1d6abSBarry Smith   Input Parameters:
5157bcf0153eSBarry Smith + ts - the `TS` context
51582fe279fdSBarry Smith . xr - real part of input argument
51592fe279fdSBarry Smith - xi - imaginary part of input argument
5160f9c1d6abSBarry Smith 
5161f9c1d6abSBarry Smith   Output Parameters:
51622fe279fdSBarry Smith + yr - real part of function value
51632fe279fdSBarry Smith - yi - imaginary part of function value
5164f9c1d6abSBarry Smith 
5165f9c1d6abSBarry Smith   Level: developer
5166f9c1d6abSBarry Smith 
51671cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetRHSFunction()`, `TSComputeIFunction()`
5168f9c1d6abSBarry Smith @*/
5169d71ae5a4SJacob Faibussowitsch PetscErrorCode TSComputeLinearStability(TS ts, PetscReal xr, PetscReal xi, PetscReal *yr, PetscReal *yi)
5170d71ae5a4SJacob Faibussowitsch {
5171f9c1d6abSBarry Smith   PetscFunctionBegin;
5172f9c1d6abSBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
5173dbbe0bcdSBarry Smith   PetscUseTypeMethod(ts, linearstability, xr, xi, yr, yi);
51743ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
5175f9c1d6abSBarry Smith }
517624655328SShri 
517724655328SShri /*@
5178dcb233daSLisandro Dalcin   TSRestartStep - Flags the solver to restart the next step
5179dcb233daSLisandro Dalcin 
5180c3339decSBarry Smith   Collective
5181dcb233daSLisandro Dalcin 
5182dcb233daSLisandro Dalcin   Input Parameter:
5183bcf0153eSBarry Smith . ts - the `TS` context obtained from `TSCreate()`
5184dcb233daSLisandro Dalcin 
5185dcb233daSLisandro Dalcin   Level: advanced
5186dcb233daSLisandro Dalcin 
5187dcb233daSLisandro Dalcin   Notes:
5188bcf0153eSBarry Smith   Multistep methods like `TSBDF` or Runge-Kutta methods with FSAL property require restarting the solver in the event of
5189dcb233daSLisandro Dalcin   discontinuities. These discontinuities may be introduced as a consequence of explicitly modifications to the solution
5190dcb233daSLisandro Dalcin   vector (which PETSc attempts to detect and handle) or problem coefficients (which PETSc is not able to detect). For
5191bcf0153eSBarry Smith   the sake of correctness and maximum safety, users are expected to call `TSRestart()` whenever they introduce
5192dcb233daSLisandro Dalcin   discontinuities in callback routines (e.g. prestep and poststep routines, or implicit/rhs function routines with
5193dcb233daSLisandro Dalcin   discontinuous source terms).
5194dcb233daSLisandro Dalcin 
51951cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSBDF`, `TSSolve()`, `TSSetPreStep()`, `TSSetPostStep()`
5196dcb233daSLisandro Dalcin @*/
5197d71ae5a4SJacob Faibussowitsch PetscErrorCode TSRestartStep(TS ts)
5198d71ae5a4SJacob Faibussowitsch {
5199dcb233daSLisandro Dalcin   PetscFunctionBegin;
5200dcb233daSLisandro Dalcin   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
5201dcb233daSLisandro Dalcin   ts->steprestart = PETSC_TRUE;
52023ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
5203dcb233daSLisandro Dalcin }
5204dcb233daSLisandro Dalcin 
5205dcb233daSLisandro Dalcin /*@
520624655328SShri   TSRollBack - Rolls back one time step
520724655328SShri 
5208c3339decSBarry Smith   Collective
520924655328SShri 
521024655328SShri   Input Parameter:
5211bcf0153eSBarry Smith . ts - the `TS` context obtained from `TSCreate()`
521224655328SShri 
521324655328SShri   Level: advanced
521424655328SShri 
52151cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSCreate()`, `TSSetUp()`, `TSDestroy()`, `TSSolve()`, `TSSetPreStep()`, `TSSetPreStage()`, `TSInterpolate()`
521624655328SShri @*/
5217d71ae5a4SJacob Faibussowitsch PetscErrorCode TSRollBack(TS ts)
5218d71ae5a4SJacob Faibussowitsch {
521924655328SShri   PetscFunctionBegin;
522024655328SShri   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
52213c633725SBarry Smith   PetscCheck(!ts->steprollback, PetscObjectComm((PetscObject)ts), PETSC_ERR_ARG_WRONGSTATE, "TSRollBack already called");
5222dbbe0bcdSBarry Smith   PetscUseTypeMethod(ts, rollback);
522324655328SShri   ts->time_step  = ts->ptime - ts->ptime_prev;
522424655328SShri   ts->ptime      = ts->ptime_prev;
5225be5899b3SLisandro Dalcin   ts->ptime_prev = ts->ptime_prev_rollback;
52262808aa04SLisandro Dalcin   ts->steps--;
5227b3de5cdeSLisandro Dalcin   ts->steprollback = PETSC_TRUE;
52283ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
522924655328SShri }
5230aeb4809dSShri Abhyankar 
5231ff22ae23SHong Zhang /*@
5232ff22ae23SHong Zhang   TSGetStages - Get the number of stages and stage values
5233ff22ae23SHong Zhang 
5234ff22ae23SHong Zhang   Input Parameter:
5235bcf0153eSBarry Smith . ts - the `TS` context obtained from `TSCreate()`
5236ff22ae23SHong Zhang 
52370429704eSStefano Zampini   Output Parameters:
52380429704eSStefano Zampini + ns - the number of stages
52390429704eSStefano Zampini - Y  - the current stage vectors
52400429704eSStefano Zampini 
5241ff22ae23SHong Zhang   Level: advanced
5242ff22ae23SHong Zhang 
5243bcf0153eSBarry Smith   Note:
5244195e9b02SBarry Smith   Both `ns` and `Y` can be `NULL`.
52450429704eSStefano Zampini 
52461cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSCreate()`
5247ff22ae23SHong Zhang @*/
5248d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetStages(TS ts, PetscInt *ns, Vec **Y)
5249d71ae5a4SJacob Faibussowitsch {
5250ff22ae23SHong Zhang   PetscFunctionBegin;
5251ff22ae23SHong Zhang   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
52524f572ea9SToby Isaac   if (ns) PetscAssertPointer(ns, 2);
52534f572ea9SToby Isaac   if (Y) PetscAssertPointer(Y, 3);
52540429704eSStefano Zampini   if (!ts->ops->getstages) {
52550429704eSStefano Zampini     if (ns) *ns = 0;
52560429704eSStefano Zampini     if (Y) *Y = NULL;
5257dbbe0bcdSBarry Smith   } else PetscUseTypeMethod(ts, getstages, ns, Y);
52583ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
5259ff22ae23SHong Zhang }
5260ff22ae23SHong Zhang 
5261847ff0e1SMatthew G. Knepley /*@C
5262847ff0e1SMatthew G. Knepley   TSComputeIJacobianDefaultColor - Computes the Jacobian using finite differences and coloring to exploit matrix sparsity.
5263847ff0e1SMatthew G. Knepley 
5264c3339decSBarry Smith   Collective
5265847ff0e1SMatthew G. Knepley 
5266847ff0e1SMatthew G. Knepley   Input Parameters:
5267bcf0153eSBarry Smith + ts    - the `TS` context
5268847ff0e1SMatthew G. Knepley . t     - current timestep
5269847ff0e1SMatthew G. Knepley . U     - state vector
5270847ff0e1SMatthew G. Knepley . Udot  - time derivative of state vector
5271847ff0e1SMatthew G. Knepley . shift - shift to apply, see note below
5272847ff0e1SMatthew G. Knepley - ctx   - an optional user context
5273847ff0e1SMatthew G. Knepley 
5274847ff0e1SMatthew G. Knepley   Output Parameters:
5275847ff0e1SMatthew G. Knepley + J - Jacobian matrix (not altered in this routine)
5276195e9b02SBarry Smith - B - newly computed Jacobian matrix to use with preconditioner (generally the same as `J`)
5277847ff0e1SMatthew G. Knepley 
5278847ff0e1SMatthew G. Knepley   Level: intermediate
5279847ff0e1SMatthew G. Knepley 
5280847ff0e1SMatthew G. Knepley   Notes:
5281847ff0e1SMatthew G. Knepley   If F(t,U,Udot)=0 is the DAE, the required Jacobian is
5282847ff0e1SMatthew G. Knepley 
5283847ff0e1SMatthew G. Knepley   dF/dU + shift*dF/dUdot
5284847ff0e1SMatthew G. Knepley 
5285847ff0e1SMatthew G. Knepley   Most users should not need to explicitly call this routine, as it
5286847ff0e1SMatthew G. Knepley   is used internally within the nonlinear solvers.
5287847ff0e1SMatthew G. Knepley 
5288bcf0153eSBarry Smith   This will first try to get the coloring from the `DM`.  If the `DM` type has no coloring
5289847ff0e1SMatthew G. Knepley   routine, then it will try to get the coloring from the matrix.  This requires that the
5290847ff0e1SMatthew G. Knepley   matrix have nonzero entries precomputed.
5291847ff0e1SMatthew G. Knepley 
52921cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetIJacobian()`, `MatFDColoringCreate()`, `MatFDColoringSetFunction()`
5293847ff0e1SMatthew G. Knepley @*/
5294d71ae5a4SJacob Faibussowitsch PetscErrorCode TSComputeIJacobianDefaultColor(TS ts, PetscReal t, Vec U, Vec Udot, PetscReal shift, Mat J, Mat B, void *ctx)
5295d71ae5a4SJacob Faibussowitsch {
5296847ff0e1SMatthew G. Knepley   SNES          snes;
5297847ff0e1SMatthew G. Knepley   MatFDColoring color;
5298847ff0e1SMatthew G. Knepley   PetscBool     hascolor, matcolor = PETSC_FALSE;
5299847ff0e1SMatthew G. Knepley 
5300847ff0e1SMatthew G. Knepley   PetscFunctionBegin;
53019566063dSJacob Faibussowitsch   PetscCall(PetscOptionsGetBool(((PetscObject)ts)->options, ((PetscObject)ts)->prefix, "-ts_fd_color_use_mat", &matcolor, NULL));
53029566063dSJacob Faibussowitsch   PetscCall(PetscObjectQuery((PetscObject)B, "TSMatFDColoring", (PetscObject *)&color));
5303847ff0e1SMatthew G. Knepley   if (!color) {
5304847ff0e1SMatthew G. Knepley     DM         dm;
5305847ff0e1SMatthew G. Knepley     ISColoring iscoloring;
5306847ff0e1SMatthew G. Knepley 
53079566063dSJacob Faibussowitsch     PetscCall(TSGetDM(ts, &dm));
53089566063dSJacob Faibussowitsch     PetscCall(DMHasColoring(dm, &hascolor));
5309847ff0e1SMatthew G. Knepley     if (hascolor && !matcolor) {
53109566063dSJacob Faibussowitsch       PetscCall(DMCreateColoring(dm, IS_COLORING_GLOBAL, &iscoloring));
53119566063dSJacob Faibussowitsch       PetscCall(MatFDColoringCreate(B, iscoloring, &color));
53129566063dSJacob Faibussowitsch       PetscCall(MatFDColoringSetFunction(color, (PetscErrorCode(*)(void))SNESTSFormFunction, (void *)ts));
53139566063dSJacob Faibussowitsch       PetscCall(MatFDColoringSetFromOptions(color));
53149566063dSJacob Faibussowitsch       PetscCall(MatFDColoringSetUp(B, iscoloring, color));
53159566063dSJacob Faibussowitsch       PetscCall(ISColoringDestroy(&iscoloring));
5316847ff0e1SMatthew G. Knepley     } else {
5317847ff0e1SMatthew G. Knepley       MatColoring mc;
5318847ff0e1SMatthew G. Knepley 
53199566063dSJacob Faibussowitsch       PetscCall(MatColoringCreate(B, &mc));
53209566063dSJacob Faibussowitsch       PetscCall(MatColoringSetDistance(mc, 2));
53219566063dSJacob Faibussowitsch       PetscCall(MatColoringSetType(mc, MATCOLORINGSL));
53229566063dSJacob Faibussowitsch       PetscCall(MatColoringSetFromOptions(mc));
53239566063dSJacob Faibussowitsch       PetscCall(MatColoringApply(mc, &iscoloring));
53249566063dSJacob Faibussowitsch       PetscCall(MatColoringDestroy(&mc));
53259566063dSJacob Faibussowitsch       PetscCall(MatFDColoringCreate(B, iscoloring, &color));
53269566063dSJacob Faibussowitsch       PetscCall(MatFDColoringSetFunction(color, (PetscErrorCode(*)(void))SNESTSFormFunction, (void *)ts));
53279566063dSJacob Faibussowitsch       PetscCall(MatFDColoringSetFromOptions(color));
53289566063dSJacob Faibussowitsch       PetscCall(MatFDColoringSetUp(B, iscoloring, color));
53299566063dSJacob Faibussowitsch       PetscCall(ISColoringDestroy(&iscoloring));
5330847ff0e1SMatthew G. Knepley     }
53319566063dSJacob Faibussowitsch     PetscCall(PetscObjectCompose((PetscObject)B, "TSMatFDColoring", (PetscObject)color));
53329566063dSJacob Faibussowitsch     PetscCall(PetscObjectDereference((PetscObject)color));
5333847ff0e1SMatthew G. Knepley   }
53349566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts, &snes));
53359566063dSJacob Faibussowitsch   PetscCall(MatFDColoringApply(B, color, U, snes));
5336847ff0e1SMatthew G. Knepley   if (J != B) {
53379566063dSJacob Faibussowitsch     PetscCall(MatAssemblyBegin(J, MAT_FINAL_ASSEMBLY));
53389566063dSJacob Faibussowitsch     PetscCall(MatAssemblyEnd(J, MAT_FINAL_ASSEMBLY));
5339847ff0e1SMatthew G. Knepley   }
53403ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
5341847ff0e1SMatthew G. Knepley }
534293b34091SDebojyoti Ghosh 
5343b43aa488SJacob Faibussowitsch /*@C
53446bc98fa9SBarry Smith   TSSetFunctionDomainError - Set a function that tests if the current state vector is valid
5345cb9d8021SPierre Barbier de Reuille 
5346cb9d8021SPierre Barbier de Reuille   Input Parameters:
5347bcf0153eSBarry Smith + ts   - the `TS` context
5348bcf0153eSBarry Smith - func - function called within `TSFunctionDomainError()`
53496bc98fa9SBarry Smith 
535020f4b53cSBarry Smith   Calling sequence of `func`:
53518847d985SBarry Smith + ts     - the `TS` context
53526bc98fa9SBarry Smith . time   - the current time (of the stage)
53536bc98fa9SBarry Smith . state  - the state to check if it is valid
5354*a144a63fSStefano Zampini - accept - (output parameter) `PETSC_FALSE` if the state is not acceptable, `PETSC_TRUE` if acceptable
5355cb9d8021SPierre Barbier de Reuille 
5356cb9d8021SPierre Barbier de Reuille   Level: intermediate
5357cb9d8021SPierre Barbier de Reuille 
53586bc98fa9SBarry Smith   Notes:
53596bc98fa9SBarry Smith   If an implicit ODE solver is being used then, in addition to providing this routine, the
5360bcf0153eSBarry Smith   user's code should call `SNESSetFunctionDomainError()` when domain errors occur during
5361bcf0153eSBarry Smith   function evaluations where the functions are provided by `TSSetIFunction()` or `TSSetRHSFunction()`.
5362bcf0153eSBarry Smith   Use `TSGetSNES()` to obtain the `SNES` object
53636bc98fa9SBarry Smith 
5364b43aa488SJacob Faibussowitsch   Developer Notes:
5365bcf0153eSBarry Smith   The naming of this function is inconsistent with the `SNESSetFunctionDomainError()`
53666bc98fa9SBarry Smith   since one takes a function pointer and the other does not.
53676bc98fa9SBarry Smith 
53681cc06b55SBarry Smith .seealso: [](ch_ts), `TSAdaptCheckStage()`, `TSFunctionDomainError()`, `SNESSetFunctionDomainError()`, `TSGetSNES()`
5369cb9d8021SPierre Barbier de Reuille @*/
5370*a144a63fSStefano Zampini PetscErrorCode TSSetFunctionDomainError(TS ts, PetscErrorCode (*func)(TS ts, PetscReal time, Vec state, PetscBool *accept))
5371d71ae5a4SJacob Faibussowitsch {
5372cb9d8021SPierre Barbier de Reuille   PetscFunctionBegin;
5373cb9d8021SPierre Barbier de Reuille   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
5374cb9d8021SPierre Barbier de Reuille   ts->functiondomainerror = func;
53753ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
5376cb9d8021SPierre Barbier de Reuille }
5377cb9d8021SPierre Barbier de Reuille 
5378cb9d8021SPierre Barbier de Reuille /*@
53796bc98fa9SBarry Smith   TSFunctionDomainError - Checks if the current state is valid
5380cb9d8021SPierre Barbier de Reuille 
5381cb9d8021SPierre Barbier de Reuille   Input Parameters:
5382bcf0153eSBarry Smith + ts        - the `TS` context
53836bc98fa9SBarry Smith . stagetime - time of the simulation
53846bc98fa9SBarry Smith - Y         - state vector to check.
5385cb9d8021SPierre Barbier de Reuille 
5386cb9d8021SPierre Barbier de Reuille   Output Parameter:
5387bcf0153eSBarry Smith . accept - Set to `PETSC_FALSE` if the current state vector is valid.
538896a0c994SBarry Smith 
53896bc98fa9SBarry Smith   Level: developer
53906bc98fa9SBarry Smith 
5391bcf0153eSBarry Smith   Note:
5392bcf0153eSBarry Smith   This function is called by the `TS` integration routines and calls the user provided function (set with `TSSetFunctionDomainError()`)
5393bcf0153eSBarry Smith   to check if the current state is valid.
5394bcf0153eSBarry Smith 
53951cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetFunctionDomainError()`
5396cb9d8021SPierre Barbier de Reuille @*/
5397d71ae5a4SJacob Faibussowitsch PetscErrorCode TSFunctionDomainError(TS ts, PetscReal stagetime, Vec Y, PetscBool *accept)
5398d71ae5a4SJacob Faibussowitsch {
5399cb9d8021SPierre Barbier de Reuille   PetscFunctionBegin;
5400cb9d8021SPierre Barbier de Reuille   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
5401cb9d8021SPierre Barbier de Reuille   *accept = PETSC_TRUE;
54021e66621cSBarry Smith   if (ts->functiondomainerror) PetscCall((*ts->functiondomainerror)(ts, stagetime, Y, accept));
54033ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
5404cb9d8021SPierre Barbier de Reuille }
54051ceb14c0SBarry Smith 
540693b34091SDebojyoti Ghosh /*@C
5407195e9b02SBarry Smith   TSClone - This function clones a time step `TS` object.
540893b34091SDebojyoti Ghosh 
5409d083f849SBarry Smith   Collective
541093b34091SDebojyoti Ghosh 
541193b34091SDebojyoti Ghosh   Input Parameter:
5412bcf0153eSBarry Smith . tsin - The input `TS`
541393b34091SDebojyoti Ghosh 
541493b34091SDebojyoti Ghosh   Output Parameter:
5415bcf0153eSBarry Smith . tsout - The output `TS` (cloned)
54165eca1a21SEmil Constantinescu 
54175eca1a21SEmil Constantinescu   Level: developer
541893b34091SDebojyoti Ghosh 
5419bcf0153eSBarry Smith   Notes:
5420bcf0153eSBarry 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.
5421bcf0153eSBarry Smith   It will likely be replaced in the future with a mechanism of switching methods on the fly.
5422bcf0153eSBarry Smith 
5423195e9b02SBarry 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
5424195e9b02SBarry Smith .vb
5425195e9b02SBarry Smith  SNES snes_dup = NULL;
5426195e9b02SBarry Smith  TSGetSNES(ts,&snes_dup);
5427195e9b02SBarry Smith  TSSetSNES(ts,snes_dup);
5428195e9b02SBarry Smith .ve
5429bcf0153eSBarry Smith 
54301cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `SNES`, `TSCreate()`, `TSSetType()`, `TSSetUp()`, `TSDestroy()`, `TSSetProblemType()`
543193b34091SDebojyoti Ghosh @*/
5432d71ae5a4SJacob Faibussowitsch PetscErrorCode TSClone(TS tsin, TS *tsout)
5433d71ae5a4SJacob Faibussowitsch {
543493b34091SDebojyoti Ghosh   TS     t;
5435dc846ba4SSatish Balay   SNES   snes_start;
5436dc846ba4SSatish Balay   DM     dm;
5437dc846ba4SSatish Balay   TSType type;
543893b34091SDebojyoti Ghosh 
543993b34091SDebojyoti Ghosh   PetscFunctionBegin;
54404f572ea9SToby Isaac   PetscAssertPointer(tsin, 1);
544193b34091SDebojyoti Ghosh   *tsout = NULL;
544293b34091SDebojyoti Ghosh 
54439566063dSJacob Faibussowitsch   PetscCall(PetscHeaderCreate(t, TS_CLASSID, "TS", "Time stepping", "TS", PetscObjectComm((PetscObject)tsin), TSDestroy, TSView));
544493b34091SDebojyoti Ghosh 
544593b34091SDebojyoti Ghosh   /* General TS description */
544693b34091SDebojyoti Ghosh   t->numbermonitors    = 0;
5447d0c080abSJoseph Pusztay   t->monitorFrequency  = 1;
544893b34091SDebojyoti Ghosh   t->setupcalled       = 0;
544993b34091SDebojyoti Ghosh   t->ksp_its           = 0;
545093b34091SDebojyoti Ghosh   t->snes_its          = 0;
545193b34091SDebojyoti Ghosh   t->nwork             = 0;
54527d51462cSStefano Zampini   t->rhsjacobian.time  = PETSC_MIN_REAL;
545393b34091SDebojyoti Ghosh   t->rhsjacobian.scale = 1.;
545493b34091SDebojyoti Ghosh   t->ijacobian.shift   = 1.;
545593b34091SDebojyoti Ghosh 
54569566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(tsin, &snes_start));
54579566063dSJacob Faibussowitsch   PetscCall(TSSetSNES(t, snes_start));
5458d15a3a53SEmil Constantinescu 
54599566063dSJacob Faibussowitsch   PetscCall(TSGetDM(tsin, &dm));
54609566063dSJacob Faibussowitsch   PetscCall(TSSetDM(t, dm));
546193b34091SDebojyoti Ghosh 
546293b34091SDebojyoti Ghosh   t->adapt = tsin->adapt;
54639566063dSJacob Faibussowitsch   PetscCall(PetscObjectReference((PetscObject)t->adapt));
546493b34091SDebojyoti Ghosh 
5465e7069c78SShri   t->trajectory = tsin->trajectory;
54669566063dSJacob Faibussowitsch   PetscCall(PetscObjectReference((PetscObject)t->trajectory));
5467e7069c78SShri 
5468e7069c78SShri   t->event = tsin->event;
54696b10a48eSSatish Balay   if (t->event) t->event->refct++;
5470e7069c78SShri 
547193b34091SDebojyoti Ghosh   t->problem_type      = tsin->problem_type;
547293b34091SDebojyoti Ghosh   t->ptime             = tsin->ptime;
5473e7069c78SShri   t->ptime_prev        = tsin->ptime_prev;
547493b34091SDebojyoti Ghosh   t->time_step         = tsin->time_step;
547593b34091SDebojyoti Ghosh   t->max_time          = tsin->max_time;
547693b34091SDebojyoti Ghosh   t->steps             = tsin->steps;
547793b34091SDebojyoti Ghosh   t->max_steps         = tsin->max_steps;
547893b34091SDebojyoti Ghosh   t->equation_type     = tsin->equation_type;
547993b34091SDebojyoti Ghosh   t->atol              = tsin->atol;
548093b34091SDebojyoti Ghosh   t->rtol              = tsin->rtol;
548193b34091SDebojyoti Ghosh   t->max_snes_failures = tsin->max_snes_failures;
548293b34091SDebojyoti Ghosh   t->max_reject        = tsin->max_reject;
548393b34091SDebojyoti Ghosh   t->errorifstepfailed = tsin->errorifstepfailed;
548493b34091SDebojyoti Ghosh 
54859566063dSJacob Faibussowitsch   PetscCall(TSGetType(tsin, &type));
54869566063dSJacob Faibussowitsch   PetscCall(TSSetType(t, type));
548793b34091SDebojyoti Ghosh 
548893b34091SDebojyoti Ghosh   t->vec_sol = NULL;
548993b34091SDebojyoti Ghosh 
549093b34091SDebojyoti Ghosh   t->cfltime          = tsin->cfltime;
549193b34091SDebojyoti Ghosh   t->cfltime_local    = tsin->cfltime_local;
549293b34091SDebojyoti Ghosh   t->exact_final_time = tsin->exact_final_time;
549393b34091SDebojyoti Ghosh 
5494aea10558SJacob Faibussowitsch   t->ops[0] = tsin->ops[0];
549593b34091SDebojyoti Ghosh 
54960d4fed19SBarry Smith   if (((PetscObject)tsin)->fortran_func_pointers) {
54970d4fed19SBarry Smith     PetscInt i;
54989566063dSJacob Faibussowitsch     PetscCall(PetscMalloc((10) * sizeof(void (*)(void)), &((PetscObject)t)->fortran_func_pointers));
5499ad540459SPierre Jolivet     for (i = 0; i < 10; i++) ((PetscObject)t)->fortran_func_pointers[i] = ((PetscObject)tsin)->fortran_func_pointers[i];
55000d4fed19SBarry Smith   }
550193b34091SDebojyoti Ghosh   *tsout = t;
55023ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
550393b34091SDebojyoti Ghosh }
5504f3b1f45cSBarry Smith 
5505d71ae5a4SJacob Faibussowitsch static PetscErrorCode RHSWrapperFunction_TSRHSJacobianTest(void *ctx, Vec x, Vec y)
5506d71ae5a4SJacob Faibussowitsch {
5507f3b1f45cSBarry Smith   TS ts = (TS)ctx;
5508f3b1f45cSBarry Smith 
5509f3b1f45cSBarry Smith   PetscFunctionBegin;
55109566063dSJacob Faibussowitsch   PetscCall(TSComputeRHSFunction(ts, 0, x, y));
55113ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
5512f3b1f45cSBarry Smith }
5513f3b1f45cSBarry Smith 
5514f3b1f45cSBarry Smith /*@
5515bcf0153eSBarry Smith   TSRHSJacobianTest - Compares the multiply routine provided to the `MATSHELL` with differencing on the `TS` given RHS function.
5516f3b1f45cSBarry Smith 
5517c3339decSBarry Smith   Logically Collective
5518f3b1f45cSBarry Smith 
55192fe279fdSBarry Smith   Input Parameter:
5520b43aa488SJacob Faibussowitsch . ts - the time stepping routine
5521f3b1f45cSBarry Smith 
5522f3b1f45cSBarry Smith   Output Parameter:
5523bcf0153eSBarry Smith . flg - `PETSC_TRUE` if the multiply is likely correct
5524f3b1f45cSBarry Smith 
5525bcf0153eSBarry Smith   Options Database Key:
5526f3b1f45cSBarry Smith . -ts_rhs_jacobian_test_mult -mat_shell_test_mult_view - run the test at each timestep of the integrator
5527f3b1f45cSBarry Smith 
5528f3b1f45cSBarry Smith   Level: advanced
5529f3b1f45cSBarry Smith 
5530bcf0153eSBarry Smith   Note:
5531195e9b02SBarry Smith   This only works for problems defined using `TSSetRHSFunction()` and Jacobian NOT `TSSetIFunction()` and Jacobian
5532f3b1f45cSBarry Smith 
55331cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `Mat`, `MATSHELL`, `MatCreateShell()`, `MatShellGetContext()`, `MatShellGetOperation()`, `MatShellTestMultTranspose()`, `TSRHSJacobianTestTranspose()`
5534f3b1f45cSBarry Smith @*/
5535d71ae5a4SJacob Faibussowitsch PetscErrorCode TSRHSJacobianTest(TS ts, PetscBool *flg)
5536d71ae5a4SJacob Faibussowitsch {
5537f3b1f45cSBarry Smith   Mat           J, B;
5538f3b1f45cSBarry Smith   TSRHSJacobian func;
5539f3b1f45cSBarry Smith   void         *ctx;
5540f3b1f45cSBarry Smith 
5541f3b1f45cSBarry Smith   PetscFunctionBegin;
55429566063dSJacob Faibussowitsch   PetscCall(TSGetRHSJacobian(ts, &J, &B, &func, &ctx));
55439566063dSJacob Faibussowitsch   PetscCall((*func)(ts, 0.0, ts->vec_sol, J, B, ctx));
55449566063dSJacob Faibussowitsch   PetscCall(MatShellTestMult(J, RHSWrapperFunction_TSRHSJacobianTest, ts->vec_sol, ts, flg));
55453ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
5546f3b1f45cSBarry Smith }
5547f3b1f45cSBarry Smith 
5548f3b1f45cSBarry Smith /*@C
5549bcf0153eSBarry Smith   TSRHSJacobianTestTranspose - Compares the multiply transpose routine provided to the `MATSHELL` with differencing on the `TS` given RHS function.
5550f3b1f45cSBarry Smith 
5551c3339decSBarry Smith   Logically Collective
5552f3b1f45cSBarry Smith 
55532fe279fdSBarry Smith   Input Parameter:
5554b43aa488SJacob Faibussowitsch . ts - the time stepping routine
5555f3b1f45cSBarry Smith 
5556f3b1f45cSBarry Smith   Output Parameter:
5557bcf0153eSBarry Smith . flg - `PETSC_TRUE` if the multiply is likely correct
5558f3b1f45cSBarry Smith 
5559bcf0153eSBarry Smith   Options Database Key:
5560f3b1f45cSBarry Smith . -ts_rhs_jacobian_test_mult_transpose -mat_shell_test_mult_transpose_view - run the test at each timestep of the integrator
5561f3b1f45cSBarry Smith 
5562bcf0153eSBarry Smith   Level: advanced
5563bcf0153eSBarry Smith 
556495452b02SPatrick Sanan   Notes:
5565195e9b02SBarry Smith   This only works for problems defined using `TSSetRHSFunction()` and Jacobian NOT `TSSetIFunction()` and Jacobian
5566f3b1f45cSBarry Smith 
55671cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `Mat`, `MatCreateShell()`, `MatShellGetContext()`, `MatShellGetOperation()`, `MatShellTestMultTranspose()`, `TSRHSJacobianTest()`
5568f3b1f45cSBarry Smith @*/
5569d71ae5a4SJacob Faibussowitsch PetscErrorCode TSRHSJacobianTestTranspose(TS ts, PetscBool *flg)
5570d71ae5a4SJacob Faibussowitsch {
5571f3b1f45cSBarry Smith   Mat           J, B;
5572f3b1f45cSBarry Smith   void         *ctx;
5573f3b1f45cSBarry Smith   TSRHSJacobian func;
5574f3b1f45cSBarry Smith 
5575f3b1f45cSBarry Smith   PetscFunctionBegin;
55769566063dSJacob Faibussowitsch   PetscCall(TSGetRHSJacobian(ts, &J, &B, &func, &ctx));
55779566063dSJacob Faibussowitsch   PetscCall((*func)(ts, 0.0, ts->vec_sol, J, B, ctx));
55789566063dSJacob Faibussowitsch   PetscCall(MatShellTestMultTranspose(J, RHSWrapperFunction_TSRHSJacobianTest, ts->vec_sol, ts, flg));
55793ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
5580f3b1f45cSBarry Smith }
55810fe4d17eSHong Zhang 
55820fe4d17eSHong Zhang /*@
55830fe4d17eSHong Zhang   TSSetUseSplitRHSFunction - Use the split RHSFunction when a multirate method is used.
55840fe4d17eSHong Zhang 
558520f4b53cSBarry Smith   Logically Collective
55860fe4d17eSHong Zhang 
5587d8d19677SJose E. Roman   Input Parameters:
55880fe4d17eSHong Zhang + ts                   - timestepping context
5589bcf0153eSBarry Smith - use_splitrhsfunction - `PETSC_TRUE` indicates that the split RHSFunction will be used
55900fe4d17eSHong Zhang 
5591bcf0153eSBarry Smith   Options Database Key:
55920fe4d17eSHong Zhang . -ts_use_splitrhsfunction - <true,false>
55930fe4d17eSHong Zhang 
55940fe4d17eSHong Zhang   Level: intermediate
55950fe4d17eSHong Zhang 
5596bcf0153eSBarry Smith   Note:
5597195e9b02SBarry Smith   This is only for multirate methods
5598bcf0153eSBarry Smith 
55991cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSGetUseSplitRHSFunction()`
56000fe4d17eSHong Zhang @*/
5601d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetUseSplitRHSFunction(TS ts, PetscBool use_splitrhsfunction)
5602d71ae5a4SJacob Faibussowitsch {
56030fe4d17eSHong Zhang   PetscFunctionBegin;
56040fe4d17eSHong Zhang   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
56050fe4d17eSHong Zhang   ts->use_splitrhsfunction = use_splitrhsfunction;
56063ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
56070fe4d17eSHong Zhang }
56080fe4d17eSHong Zhang 
56090fe4d17eSHong Zhang /*@
56100fe4d17eSHong Zhang   TSGetUseSplitRHSFunction - Gets whether to use the split RHSFunction when a multirate method is used.
56110fe4d17eSHong Zhang 
561220f4b53cSBarry Smith   Not Collective
56130fe4d17eSHong Zhang 
56140fe4d17eSHong Zhang   Input Parameter:
56150fe4d17eSHong Zhang . ts - timestepping context
56160fe4d17eSHong Zhang 
56170fe4d17eSHong Zhang   Output Parameter:
5618bcf0153eSBarry Smith . use_splitrhsfunction - `PETSC_TRUE` indicates that the split RHSFunction will be used
56190fe4d17eSHong Zhang 
56200fe4d17eSHong Zhang   Level: intermediate
56210fe4d17eSHong Zhang 
56221cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetUseSplitRHSFunction()`
56230fe4d17eSHong Zhang @*/
5624d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetUseSplitRHSFunction(TS ts, PetscBool *use_splitrhsfunction)
5625d71ae5a4SJacob Faibussowitsch {
56260fe4d17eSHong Zhang   PetscFunctionBegin;
56270fe4d17eSHong Zhang   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
56280fe4d17eSHong Zhang   *use_splitrhsfunction = ts->use_splitrhsfunction;
56293ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
56300fe4d17eSHong Zhang }
5631d60b7d5cSBarry Smith 
5632d60b7d5cSBarry Smith /*@
5633d60b7d5cSBarry Smith   TSSetMatStructure - sets the relationship between the nonzero structure of the RHS Jacobian matrix to the IJacobian matrix.
5634d60b7d5cSBarry Smith 
5635c3339decSBarry Smith   Logically  Collective
5636d60b7d5cSBarry Smith 
5637d60b7d5cSBarry Smith   Input Parameters:
5638d60b7d5cSBarry Smith + ts  - the time-stepper
5639bcf0153eSBarry Smith - str - the structure (the default is `UNKNOWN_NONZERO_PATTERN`)
5640d60b7d5cSBarry Smith 
5641d60b7d5cSBarry Smith   Level: intermediate
5642d60b7d5cSBarry Smith 
5643bcf0153eSBarry Smith   Note:
5644d60b7d5cSBarry Smith   When the relationship between the nonzero structures is known and supplied the solution process can be much faster
5645d60b7d5cSBarry Smith 
56461cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `MatAXPY()`, `MatStructure`
5647d60b7d5cSBarry Smith  @*/
5648d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetMatStructure(TS ts, MatStructure str)
5649d71ae5a4SJacob Faibussowitsch {
5650d60b7d5cSBarry Smith   PetscFunctionBegin;
5651d60b7d5cSBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
5652d60b7d5cSBarry Smith   ts->axpy_pattern = str;
56533ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
5654d60b7d5cSBarry Smith }
56554a658b32SHong Zhang 
56564a658b32SHong Zhang /*@
5657bcf0153eSBarry Smith   TSSetTimeSpan - sets the time span. The solution will be computed and stored for each time requested in the span
56584a658b32SHong Zhang 
5659c3339decSBarry Smith   Collective
56604a658b32SHong Zhang 
56614a658b32SHong Zhang   Input Parameters:
56624a658b32SHong Zhang + ts         - the time-stepper
56634a658b32SHong Zhang . n          - number of the time points (>=2)
56644a658b32SHong Zhang - span_times - array of the time points. The first element and the last element are the initial time and the final time respectively.
56654a658b32SHong Zhang 
5666bcf0153eSBarry Smith   Options Database Key:
56674a658b32SHong Zhang . -ts_time_span <t0,...tf> - Sets the time span
56684a658b32SHong Zhang 
5669bcf0153eSBarry Smith   Level: intermediate
56704a658b32SHong Zhang 
56714a658b32SHong Zhang   Notes:
56724a658b32SHong Zhang   The elements in tspan must be all increasing. They correspond to the intermediate points for time integration.
5673bcf0153eSBarry Smith   `TS_EXACTFINALTIME_MATCHSTEP` must be used to make the last time step in each sub-interval match the intermediate points specified.
5674bcf0153eSBarry Smith   The intermediate solutions are saved in a vector array that can be accessed with `TSGetTimeSpanSolutions()`. Thus using time span may
56754a658b32SHong Zhang   pressure the memory system when using a large number of span points.
56764a658b32SHong Zhang 
56771cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSGetTimeSpan()`, `TSGetTimeSpanSolutions()`
56784a658b32SHong Zhang  @*/
5679d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetTimeSpan(TS ts, PetscInt n, PetscReal *span_times)
5680d71ae5a4SJacob Faibussowitsch {
56814a658b32SHong Zhang   PetscFunctionBegin;
56824a658b32SHong Zhang   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
568363a3b9bcSJacob Faibussowitsch   PetscCheck(n >= 2, PetscObjectComm((PetscObject)ts), PETSC_ERR_ARG_WRONG, "Minimum time span size is 2 but %" PetscInt_FMT " is provided", n);
56844a658b32SHong Zhang   if (ts->tspan && n != ts->tspan->num_span_times) {
56854a658b32SHong Zhang     PetscCall(PetscFree(ts->tspan->span_times));
56864a658b32SHong Zhang     PetscCall(VecDestroyVecs(ts->tspan->num_span_times, &ts->tspan->vecs_sol));
56874a658b32SHong Zhang     PetscCall(PetscMalloc1(n, &ts->tspan->span_times));
56884a658b32SHong Zhang   }
56894a658b32SHong Zhang   if (!ts->tspan) {
56904a658b32SHong Zhang     TSTimeSpan tspan;
56914a658b32SHong Zhang     PetscCall(PetscNew(&tspan));
56924a658b32SHong Zhang     PetscCall(PetscMalloc1(n, &tspan->span_times));
5693e1db57b0SHong Zhang     tspan->reltol = 1e-6;
5694e1db57b0SHong Zhang     tspan->abstol = 10 * PETSC_MACHINE_EPSILON;
56954a658b32SHong Zhang     ts->tspan     = tspan;
56964a658b32SHong Zhang   }
56974a658b32SHong Zhang   ts->tspan->num_span_times = n;
56984a658b32SHong Zhang   PetscCall(PetscArraycpy(ts->tspan->span_times, span_times, n));
56994a658b32SHong Zhang   PetscCall(TSSetTime(ts, ts->tspan->span_times[0]));
57004a658b32SHong Zhang   PetscCall(TSSetMaxTime(ts, ts->tspan->span_times[n - 1]));
57013ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
57024a658b32SHong Zhang }
57034a658b32SHong Zhang 
57044a658b32SHong Zhang /*@C
5705195e9b02SBarry Smith   TSGetTimeSpan - gets the time span set with `TSSetTimeSpan()`
57064a658b32SHong Zhang 
57074a658b32SHong Zhang   Not Collective
57084a658b32SHong Zhang 
57094a658b32SHong Zhang   Input Parameter:
57104a658b32SHong Zhang . ts - the time-stepper
57114a658b32SHong Zhang 
57124a658b32SHong Zhang   Output Parameters:
57134a658b32SHong Zhang + n          - number of the time points (>=2)
5714bcf0153eSBarry Smith - span_times - array of the time points. The first element and the last element are the initial time and the final time respectively.
57154a658b32SHong Zhang 
57164a658b32SHong Zhang   Level: beginner
57174a658b32SHong Zhang 
5718bcf0153eSBarry Smith   Note:
5719195e9b02SBarry Smith   The values obtained are valid until the `TS` object is destroyed.
5720195e9b02SBarry Smith 
5721195e9b02SBarry Smith   Both `n` and `span_times` can be `NULL`.
5722bcf0153eSBarry Smith 
57231cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetTimeSpan()`, `TSGetTimeSpanSolutions()`
57244a658b32SHong Zhang  @*/
5725d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetTimeSpan(TS ts, PetscInt *n, const PetscReal **span_times)
5726d71ae5a4SJacob Faibussowitsch {
57274a658b32SHong Zhang   PetscFunctionBegin;
57284a658b32SHong Zhang   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
57294f572ea9SToby Isaac   if (n) PetscAssertPointer(n, 2);
57304f572ea9SToby Isaac   if (span_times) PetscAssertPointer(span_times, 3);
57314a658b32SHong Zhang   if (!ts->tspan) {
57324a658b32SHong Zhang     if (n) *n = 0;
57334a658b32SHong Zhang     if (span_times) *span_times = NULL;
57344a658b32SHong Zhang   } else {
57354a658b32SHong Zhang     if (n) *n = ts->tspan->num_span_times;
57364a658b32SHong Zhang     if (span_times) *span_times = ts->tspan->span_times;
57374a658b32SHong Zhang   }
57383ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
57394a658b32SHong Zhang }
57404a658b32SHong Zhang 
57414a658b32SHong Zhang /*@
57424a658b32SHong Zhang   TSGetTimeSpanSolutions - Get the number of solutions and the solutions at the time points specified by the time span.
57434a658b32SHong Zhang 
57444a658b32SHong Zhang   Input Parameter:
5745bcf0153eSBarry Smith . ts - the `TS` context obtained from `TSCreate()`
57464a658b32SHong Zhang 
57474a658b32SHong Zhang   Output Parameters:
57484a658b32SHong Zhang + nsol - the number of solutions
57494a658b32SHong Zhang - Sols - the solution vectors
57504a658b32SHong Zhang 
5751bcf0153eSBarry Smith   Level: intermediate
57524a658b32SHong Zhang 
575340bd4cedSHong Zhang   Notes:
5754195e9b02SBarry Smith   Both `nsol` and `Sols` can be `NULL`.
57554a658b32SHong Zhang 
5756195e9b02SBarry 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()`.
5757bcf0153eSBarry Smith   For example, manipulating the step size, especially with a reduced precision, may cause `TS` to step over certain points in the span.
5758bcf0153eSBarry Smith 
57591cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetTimeSpan()`
57604a658b32SHong Zhang @*/
5761d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetTimeSpanSolutions(TS ts, PetscInt *nsol, Vec **Sols)
5762d71ae5a4SJacob Faibussowitsch {
57634a658b32SHong Zhang   PetscFunctionBegin;
57644a658b32SHong Zhang   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
57654f572ea9SToby Isaac   if (nsol) PetscAssertPointer(nsol, 2);
57664f572ea9SToby Isaac   if (Sols) PetscAssertPointer(Sols, 3);
57674a658b32SHong Zhang   if (!ts->tspan) {
57684a658b32SHong Zhang     if (nsol) *nsol = 0;
57694a658b32SHong Zhang     if (Sols) *Sols = NULL;
57704a658b32SHong Zhang   } else {
577140bd4cedSHong Zhang     if (nsol) *nsol = ts->tspan->spanctr;
57724a658b32SHong Zhang     if (Sols) *Sols = ts->tspan->vecs_sol;
57734a658b32SHong Zhang   }
57743ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
57754a658b32SHong Zhang }
5776d7cfae9bSHong Zhang 
5777d7cfae9bSHong Zhang /*@C
57787b2dc123SHong Zhang   TSPruneIJacobianColor - Remove nondiagonal zeros in the Jacobian matrix and update the `MatMFFD` coloring information.
5779d7cfae9bSHong Zhang 
5780195e9b02SBarry Smith   Collective
5781d7cfae9bSHong Zhang 
5782d7cfae9bSHong Zhang   Input Parameters:
5783195e9b02SBarry Smith + ts - the `TS` context
5784d7cfae9bSHong Zhang . J  - Jacobian matrix (not altered in this routine)
5785195e9b02SBarry Smith - B  - newly computed Jacobian matrix to use with preconditioner
5786d7cfae9bSHong Zhang 
5787d7cfae9bSHong Zhang   Level: intermediate
5788d7cfae9bSHong Zhang 
5789d7cfae9bSHong Zhang   Notes:
5790195e9b02SBarry Smith   This function improves the `MatFDColoring` performance when the Jacobian matrix was over-allocated or contains
5791195e9b02SBarry Smith   many constant zeros entries, which is typically the case when the matrix is generated by a `DM`
5792d7cfae9bSHong Zhang   and multiple fields are involved.
5793d7cfae9bSHong Zhang 
5794d7cfae9bSHong Zhang   Users need to make sure that the Jacobian matrix is properly filled to reflect the sparsity
5795195e9b02SBarry Smith   structure. For `MatFDColoring`, the values of nonzero entries are not important. So one can
57967b2dc123SHong Zhang   usually call `TSComputeIJacobian()` with randomized input vectors to generate a dummy Jacobian.
57977b2dc123SHong Zhang   `TSComputeIJacobian()` should be called before `TSSolve()` but after `TSSetUp()`.
5798d7cfae9bSHong Zhang 
57991cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `MatFDColoring`, `TSComputeIJacobianDefaultColor()`, `MatEliminateZeros()`, `MatFDColoringCreate()`, `MatFDColoringSetFunction()`
5800d7cfae9bSHong Zhang @*/
5801d7cfae9bSHong Zhang PetscErrorCode TSPruneIJacobianColor(TS ts, Mat J, Mat B)
5802d7cfae9bSHong Zhang {
5803d7cfae9bSHong Zhang   MatColoring   mc            = NULL;
5804d7cfae9bSHong Zhang   ISColoring    iscoloring    = NULL;
5805d7cfae9bSHong Zhang   MatFDColoring matfdcoloring = NULL;
5806d7cfae9bSHong Zhang 
5807d7cfae9bSHong Zhang   PetscFunctionBegin;
5808d7cfae9bSHong Zhang   /* Generate new coloring after eliminating zeros in the matrix */
580958c11ad4SPierre Jolivet   PetscCall(MatEliminateZeros(B, PETSC_TRUE));
5810d7cfae9bSHong Zhang   PetscCall(MatColoringCreate(B, &mc));
5811d7cfae9bSHong Zhang   PetscCall(MatColoringSetDistance(mc, 2));
5812d7cfae9bSHong Zhang   PetscCall(MatColoringSetType(mc, MATCOLORINGSL));
5813d7cfae9bSHong Zhang   PetscCall(MatColoringSetFromOptions(mc));
5814d7cfae9bSHong Zhang   PetscCall(MatColoringApply(mc, &iscoloring));
5815d7cfae9bSHong Zhang   PetscCall(MatColoringDestroy(&mc));
5816d7cfae9bSHong Zhang   /* Replace the old coloring with the new one */
5817d7cfae9bSHong Zhang   PetscCall(MatFDColoringCreate(B, iscoloring, &matfdcoloring));
5818d7cfae9bSHong Zhang   PetscCall(MatFDColoringSetFunction(matfdcoloring, (PetscErrorCode(*)(void))SNESTSFormFunction, (void *)ts));
5819d7cfae9bSHong Zhang   PetscCall(MatFDColoringSetFromOptions(matfdcoloring));
5820d7cfae9bSHong Zhang   PetscCall(MatFDColoringSetUp(B, iscoloring, matfdcoloring));
5821d7cfae9bSHong Zhang   PetscCall(PetscObjectCompose((PetscObject)B, "TSMatFDColoring", (PetscObject)matfdcoloring));
5822d7cfae9bSHong Zhang   PetscCall(PetscObjectDereference((PetscObject)matfdcoloring));
5823d7cfae9bSHong Zhang   PetscCall(ISColoringDestroy(&iscoloring));
58243ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
5825d7cfae9bSHong Zhang }
5826