xref: /petsc/src/ts/interface/ts.c (revision 764c9dfdf0de18698088dfaf44fb3a5ee569d5f7)
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
378343f784SJames Wright . -ts_time_span <t0,...tf>                                           - sets the time span, solutions are computed and stored for each indicated time, init_time and max_time are set
388343f784SJames Wright . -ts_eval_times <t0,...tn>                                          - time points where solutions are computed and stored for each indicated time
398e562f8dSJames Wright . -ts_max_steps <steps>                                              - maximum time-step number to execute until (possibly with nonzero starting value)
408e562f8dSJames Wright . -ts_run_steps <steps>                                              - maximum number of time steps for TSSolve to take on each call
41ef85077eSLisandro Dalcin . -ts_init_time <time>                                               - initial time to start computation
42195e9b02SBarry Smith . -ts_final_time <time>                                              - final time to compute to (deprecated: use `-ts_max_time`)
433e4cdcaaSBarry Smith . -ts_dt <dt>                                                        - initial time step
441628793fSSatish 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
45a3cdaa26SBarry Smith . -ts_max_snes_failures <maxfailures>                                - Maximum number of nonlinear solve failures allowed
46a3cdaa26SBarry Smith . -ts_max_reject <maxrejects>                                        - Maximum number of step rejections before step fails
47a3cdaa26SBarry Smith . -ts_error_if_step_fails <true,false>                               - Error if no step succeeds
48a3cdaa26SBarry Smith . -ts_rtol <rtol>                                                    - relative tolerance for local truncation error
4967b8a455SSatish Balay . -ts_atol <atol>                                                    - Absolute tolerance for local truncation error
50f3b1f45cSBarry Smith . -ts_rhs_jacobian_test_mult -mat_shell_test_mult_view               - test the Jacobian at each iteration against finite difference with RHS function
51b43aa488SJacob Faibussowitsch . -ts_rhs_jacobian_test_mult_transpose                               - test the Jacobian at each iteration against finite difference with RHS function
52195e9b02SBarry Smith . -ts_adjoint_solve <yes,no>                                         - After solving the ODE/DAE solve the adjoint problem (requires `-ts_save_trajectory`)
53847ff0e1SMatthew G. Knepley . -ts_fd_color                                                       - Use finite differences with coloring to compute IJacobian
54bdad233fSMatthew Knepley . -ts_monitor                                                        - print information at each timestep
55aee7a9fbSMatthew G. Knepley . -ts_monitor_cancel                                                 - Cancel all monitors
56340b794cSJed Brown . -ts_monitor_wall_clock_time                                        - Monitor wall-clock time, KSP iterations, and SNES iterations per step
57de06c3feSJed Brown . -ts_monitor_lg_solution                                            - Monitor solution graphically
58de06c3feSJed Brown . -ts_monitor_lg_error                                               - Monitor error graphically
597cf37e64SBarry Smith . -ts_monitor_error                                                  - Monitors norm of error
606934998bSLisandro Dalcin . -ts_monitor_lg_timestep                                            - Monitor timestep size graphically
618b668821SLisandro Dalcin . -ts_monitor_lg_timestep_log                                        - Monitor log timestep size graphically
62de06c3feSJed Brown . -ts_monitor_lg_snes_iterations                                     - Monitor number nonlinear iterations for each timestep graphically
63de06c3feSJed Brown . -ts_monitor_lg_ksp_iterations                                      - Monitor number nonlinear iterations for each timestep graphically
64de06c3feSJed Brown . -ts_monitor_sp_eig                                                 - Monitor eigenvalues of linearized operator graphically
65de06c3feSJed Brown . -ts_monitor_draw_solution                                          - Monitor solution graphically
663e4cdcaaSBarry Smith . -ts_monitor_draw_solution_phase  <xleft,yleft,xright,yright>       - Monitor solution graphically with phase diagram, requires problem with exactly 2 degrees of freedom
673e4cdcaaSBarry Smith . -ts_monitor_draw_error                                             - Monitor error graphically, requires use to have provided TSSetSolutionFunction()
68fde5950dSBarry Smith . -ts_monitor_solution [ascii binary draw][:filename][:viewerformat] - monitors the solution at each timestep
69c17ba870SStefano Zampini . -ts_monitor_solution_interval <interval>                           - output once every interval (default=1) time steps. Use -1 to only output at the end of the simulation
708e562f8dSJames Wright . -ts_monitor_solution_skip_initial                                  - skip writing of initial condition
7163a3b9bcSJacob 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)
72c17ba870SStefano Zampini . -ts_monitor_solution_vtk_interval <interval>                       - output once every interval (default=1) time steps. Use -1 to only output at the end of the simulation
739e336e28SPatrick Sanan - -ts_monitor_envelope                                               - determine maximum and minimum value of each component of the solution over the solution time
7453ea634cSHong Zhang 
75bcf0153eSBarry Smith   Level: beginner
763d5a8a6aSBarry Smith 
77bcf0153eSBarry Smith   Notes:
78bcf0153eSBarry Smith   See `SNESSetFromOptions()` and `KSPSetFromOptions()` for how to control the nonlinear and linear solves used by the time-stepper.
79bcf0153eSBarry Smith 
80195e9b02SBarry Smith   Certain `SNES` options get reset for each new nonlinear solver, for example `-snes_lag_jacobian its` and `-snes_lag_preconditioner its`, in order
810d56bcf9SIlya Fursov   to retain them over the multiple nonlinear solves that `TS` uses you must also provide `-snes_lag_jacobian_persists true` and
82195e9b02SBarry Smith   `-snes_lag_preconditioner_persists true`
833d5a8a6aSBarry Smith 
84b43aa488SJacob Faibussowitsch   Developer Notes:
859e336e28SPatrick Sanan   We should unify all the -ts_monitor options in the way that -xxx_view has been unified
86bdad233fSMatthew Knepley 
871cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSGetType()`
88bdad233fSMatthew Knepley @*/
89d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetFromOptions(TS ts)
90d71ae5a4SJacob Faibussowitsch {
91bc952696SBarry Smith   PetscBool              opt, flg, tflg;
92eabae89aSBarry Smith   char                   monfilename[PETSC_MAX_PATH_LEN];
93acc0c1feSStefano Zampini   PetscReal              time_step, eval_times[100] = {0};
94136cf249SJames Wright   PetscInt               num_eval_times = PETSC_STATIC_ARRAY_LENGTH(eval_times);
9549354f04SShri Abhyankar   TSExactFinalTimeOption eftopt;
96d1212d36SBarry Smith   char                   dir[16];
978434afd1SBarry Smith   TSIFunctionFn         *ifun;
986991f827SBarry Smith   const char            *defaultType;
996991f827SBarry Smith   char                   typeName[256];
100bdad233fSMatthew Knepley 
101bdad233fSMatthew Knepley   PetscFunctionBegin;
1020700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
1036991f827SBarry Smith 
1049566063dSJacob Faibussowitsch   PetscCall(TSRegisterAll());
1059566063dSJacob Faibussowitsch   PetscCall(TSGetIFunction(ts, NULL, &ifun, NULL));
106cd11d68dSLisandro Dalcin 
107d0609cedSBarry Smith   PetscObjectOptionsBegin((PetscObject)ts);
1081ef27442SStefano Zampini   if (((PetscObject)ts)->type_name) defaultType = ((PetscObject)ts)->type_name;
1091ef27442SStefano Zampini   else defaultType = ifun ? TSBEULER : TSEULER;
1109566063dSJacob Faibussowitsch   PetscCall(PetscOptionsFList("-ts_type", "TS method", "TSSetType", TSList, defaultType, typeName, 256, &opt));
1111e66621cSBarry Smith   if (opt) PetscCall(TSSetType(ts, typeName));
1121e66621cSBarry Smith   else PetscCall(TSSetType(ts, defaultType));
113bdad233fSMatthew Knepley 
114bdad233fSMatthew Knepley   /* Handle generic TS options */
1159566063dSJacob Faibussowitsch   PetscCall(PetscOptionsDeprecated("-ts_final_time", "-ts_max_time", "3.10", NULL));
1169566063dSJacob Faibussowitsch   PetscCall(PetscOptionsReal("-ts_max_time", "Maximum time to run to", "TSSetMaxTime", ts->max_time, &ts->max_time, NULL));
117136cf249SJames Wright   PetscCall(PetscOptionsRealArray("-ts_time_span", "Time span", "TSSetTimeSpan", eval_times, &num_eval_times, &flg));
118136cf249SJames Wright   if (flg) PetscCall(TSSetTimeSpan(ts, num_eval_times, eval_times));
119136cf249SJames Wright   num_eval_times = PETSC_STATIC_ARRAY_LENGTH(eval_times);
120136cf249SJames Wright   PetscCall(PetscOptionsRealArray("-ts_eval_times", "Evaluation time points", "TSSetEvaluationTimes", eval_times, &num_eval_times, &opt));
1218343f784SJames Wright   PetscCheck(flg != opt || (!flg && !opt), PetscObjectComm((PetscObject)ts), PETSC_ERR_ARG_WRONG, "May not provide -ts_time_span and -ts_eval_times simultaneously");
122136cf249SJames Wright   if (opt) PetscCall(TSSetEvaluationTimes(ts, num_eval_times, eval_times));
1238e562f8dSJames Wright   PetscCall(PetscOptionsInt("-ts_max_steps", "Maximum time step number to execute to (possibly with non-zero starting value)", "TSSetMaxSteps", ts->max_steps, &ts->max_steps, NULL));
1248e562f8dSJames Wright   PetscCall(PetscOptionsInt("-ts_run_steps", "Maximum number of time steps to take on each call to TSSolve()", "TSSetRunSteps", ts->run_steps, &ts->run_steps, NULL));
1259566063dSJacob Faibussowitsch   PetscCall(PetscOptionsReal("-ts_init_time", "Initial time", "TSSetTime", ts->ptime, &ts->ptime, NULL));
1269566063dSJacob Faibussowitsch   PetscCall(PetscOptionsReal("-ts_dt", "Initial time step", "TSSetTimeStep", ts->time_step, &time_step, &flg));
1279566063dSJacob Faibussowitsch   if (flg) PetscCall(TSSetTimeStep(ts, time_step));
1289566063dSJacob Faibussowitsch   PetscCall(PetscOptionsEnum("-ts_exact_final_time", "Option for handling of final time step", "TSSetExactFinalTime", TSExactFinalTimeOptions, (PetscEnum)ts->exact_final_time, (PetscEnum *)&eftopt, &flg));
1299566063dSJacob Faibussowitsch   if (flg) PetscCall(TSSetExactFinalTime(ts, eftopt));
13009cb0f53SBarry Smith   PetscCall(PetscOptionsInt("-ts_max_snes_failures", "Maximum number of nonlinear solve failures", "TSSetMaxSNESFailures", ts->max_snes_failures, &ts->max_snes_failures, &flg));
13109cb0f53SBarry Smith   if (flg) PetscCall(TSSetMaxSNESFailures(ts, ts->max_snes_failures));
13209cb0f53SBarry Smith   PetscCall(PetscOptionsInt("-ts_max_reject", "Maximum number of step rejections before step fails", "TSSetMaxStepRejections", ts->max_reject, &ts->max_reject, &flg));
13309cb0f53SBarry Smith   if (flg) PetscCall(TSSetMaxStepRejections(ts, ts->max_reject));
1349566063dSJacob Faibussowitsch   PetscCall(PetscOptionsBool("-ts_error_if_step_fails", "Error if no step succeeds", "TSSetErrorIfStepFails", ts->errorifstepfailed, &ts->errorifstepfailed, NULL));
13509cb0f53SBarry Smith   PetscCall(PetscOptionsBoundedReal("-ts_rtol", "Relative tolerance for local truncation error", "TSSetTolerances", ts->rtol, &ts->rtol, NULL, 0));
13609cb0f53SBarry Smith   PetscCall(PetscOptionsBoundedReal("-ts_atol", "Absolute tolerance for local truncation error", "TSSetTolerances", ts->atol, &ts->atol, NULL, 0));
137bdad233fSMatthew Knepley 
1389566063dSJacob 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));
1399566063dSJacob 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));
1409566063dSJacob Faibussowitsch   PetscCall(PetscOptionsBool("-ts_use_splitrhsfunction", "Use the split RHS function for multirate solvers ", "TSSetUseSplitRHSFunction", ts->use_splitrhsfunction, &ts->use_splitrhsfunction, NULL));
14156f85f32SBarry Smith #if defined(PETSC_HAVE_SAWS)
14256f85f32SBarry Smith   {
14356f85f32SBarry Smith     PetscBool set;
14456f85f32SBarry Smith     flg = PETSC_FALSE;
1459566063dSJacob Faibussowitsch     PetscCall(PetscOptionsBool("-ts_saws_block", "Block for SAWs memory snooper at end of TSSolve", "PetscObjectSAWsBlock", ((PetscObject)ts)->amspublishblock, &flg, &set));
1461baa6e33SBarry Smith     if (set) PetscCall(PetscObjectSAWsSetBlock((PetscObject)ts, flg));
14756f85f32SBarry Smith   }
14856f85f32SBarry Smith #endif
14956f85f32SBarry Smith 
150bdad233fSMatthew Knepley   /* Monitor options */
15141d17464SJames Wright   PetscCall(PetscOptionsDeprecated("-ts_monitor_frequency", "-ts_dmswarm_monitor_moments_interval", "3.24", "Retired in favor of monitor-specific intervals (ts_dmswarm_monitor_moments was the only monitor to use ts_monitor_frequency)"));
1529566063dSJacob Faibussowitsch   PetscCall(TSMonitorSetFromOptions(ts, "-ts_monitor", "Monitor time and timestep size", "TSMonitorDefault", TSMonitorDefault, NULL));
153340b794cSJed Brown   PetscCall(TSMonitorSetFromOptions(ts, "-ts_monitor_wall_clock_time", "Monitor wall-clock time, KSP iterations, and SNES iterations per step", "TSMonitorWallClockTime", TSMonitorWallClockTime, TSMonitorWallClockTimeSetUp));
1549566063dSJacob Faibussowitsch   PetscCall(TSMonitorSetFromOptions(ts, "-ts_monitor_extreme", "Monitor extreme values of the solution", "TSMonitorExtreme", TSMonitorExtreme, NULL));
1558e562f8dSJames Wright   PetscCall(TSMonitorSetFromOptions(ts, "-ts_monitor_solution", "View the solution at each timestep", "TSMonitorSolution", TSMonitorSolution, TSMonitorSolutionSetup));
1569566063dSJacob Faibussowitsch   PetscCall(TSMonitorSetFromOptions(ts, "-ts_dmswarm_monitor_moments", "Monitor moments of particle distribution", "TSDMSwarmMonitorMoments", TSDMSwarmMonitorMoments, NULL));
1579566063dSJacob Faibussowitsch   PetscCall(PetscOptionsString("-ts_monitor_python", "Use Python function", "TSMonitorSet", NULL, monfilename, sizeof(monfilename), &flg));
1589566063dSJacob Faibussowitsch   if (flg) PetscCall(PetscPythonMonitorSet((PetscObject)ts, monfilename));
1595180491cSLisandro Dalcin 
1609566063dSJacob Faibussowitsch   PetscCall(PetscOptionsName("-ts_monitor_lg_solution", "Monitor solution graphically", "TSMonitorLGSolution", &opt));
161b3603a34SBarry Smith   if (opt) {
1623923b477SBarry Smith     PetscInt  howoften = 1;
163e669de00SBarry Smith     DM        dm;
164e669de00SBarry Smith     PetscBool net;
165b3603a34SBarry Smith 
1669566063dSJacob Faibussowitsch     PetscCall(PetscOptionsInt("-ts_monitor_lg_solution", "Monitor solution graphically", "TSMonitorLGSolution", howoften, &howoften, NULL));
1679566063dSJacob Faibussowitsch     PetscCall(TSGetDM(ts, &dm));
1689566063dSJacob Faibussowitsch     PetscCall(PetscObjectTypeCompare((PetscObject)dm, DMNETWORK, &net));
169e669de00SBarry Smith     if (net) {
170e669de00SBarry Smith       TSMonitorLGCtxNetwork ctx;
1719566063dSJacob Faibussowitsch       PetscCall(TSMonitorLGCtxNetworkCreate(ts, NULL, NULL, PETSC_DECIDE, PETSC_DECIDE, 600, 400, howoften, &ctx));
17249abdd8aSBarry Smith       PetscCall(TSMonitorSet(ts, TSMonitorLGCtxNetworkSolution, ctx, (PetscCtxDestroyFn *)TSMonitorLGCtxNetworkDestroy));
1739566063dSJacob Faibussowitsch       PetscCall(PetscOptionsBool("-ts_monitor_lg_solution_semilogy", "Plot the solution with a semi-log axis", "", ctx->semilogy, &ctx->semilogy, NULL));
174e669de00SBarry Smith     } else {
175e669de00SBarry Smith       TSMonitorLGCtx ctx;
1769566063dSJacob Faibussowitsch       PetscCall(TSMonitorLGCtxCreate(PETSC_COMM_SELF, NULL, NULL, PETSC_DECIDE, PETSC_DECIDE, 400, 300, howoften, &ctx));
17749abdd8aSBarry Smith       PetscCall(TSMonitorSet(ts, TSMonitorLGSolution, ctx, (PetscCtxDestroyFn *)TSMonitorLGCtxDestroy));
178bdad233fSMatthew Knepley     }
179e669de00SBarry Smith   }
1806ba87a44SLisandro Dalcin 
1819566063dSJacob Faibussowitsch   PetscCall(PetscOptionsName("-ts_monitor_lg_error", "Monitor error graphically", "TSMonitorLGError", &opt));
182ef20d060SBarry Smith   if (opt) {
1830b039ecaSBarry Smith     TSMonitorLGCtx ctx;
1843923b477SBarry Smith     PetscInt       howoften = 1;
185ef20d060SBarry Smith 
1869566063dSJacob Faibussowitsch     PetscCall(PetscOptionsInt("-ts_monitor_lg_error", "Monitor error graphically", "TSMonitorLGError", howoften, &howoften, NULL));
1879566063dSJacob Faibussowitsch     PetscCall(TSMonitorLGCtxCreate(PETSC_COMM_SELF, NULL, NULL, PETSC_DECIDE, PETSC_DECIDE, 400, 300, howoften, &ctx));
18849abdd8aSBarry Smith     PetscCall(TSMonitorSet(ts, TSMonitorLGError, ctx, (PetscCtxDestroyFn *)TSMonitorLGCtxDestroy));
189ef20d060SBarry Smith   }
1909566063dSJacob Faibussowitsch   PetscCall(TSMonitorSetFromOptions(ts, "-ts_monitor_error", "View the error at each timestep", "TSMonitorError", TSMonitorError, NULL));
1917cf37e64SBarry Smith 
1929566063dSJacob Faibussowitsch   PetscCall(PetscOptionsName("-ts_monitor_lg_timestep", "Monitor timestep size graphically", "TSMonitorLGTimeStep", &opt));
1936934998bSLisandro Dalcin   if (opt) {
1946934998bSLisandro Dalcin     TSMonitorLGCtx ctx;
1956934998bSLisandro Dalcin     PetscInt       howoften = 1;
1966934998bSLisandro Dalcin 
1979566063dSJacob Faibussowitsch     PetscCall(PetscOptionsInt("-ts_monitor_lg_timestep", "Monitor timestep size graphically", "TSMonitorLGTimeStep", howoften, &howoften, NULL));
1989566063dSJacob Faibussowitsch     PetscCall(TSMonitorLGCtxCreate(PetscObjectComm((PetscObject)ts), NULL, NULL, PETSC_DECIDE, PETSC_DECIDE, 400, 300, howoften, &ctx));
19949abdd8aSBarry Smith     PetscCall(TSMonitorSet(ts, TSMonitorLGTimeStep, ctx, (PetscCtxDestroyFn *)TSMonitorLGCtxDestroy));
2006934998bSLisandro Dalcin   }
2019566063dSJacob Faibussowitsch   PetscCall(PetscOptionsName("-ts_monitor_lg_timestep_log", "Monitor log timestep size graphically", "TSMonitorLGTimeStep", &opt));
2028b668821SLisandro Dalcin   if (opt) {
2038b668821SLisandro Dalcin     TSMonitorLGCtx ctx;
2048b668821SLisandro Dalcin     PetscInt       howoften = 1;
2058b668821SLisandro Dalcin 
2069566063dSJacob Faibussowitsch     PetscCall(PetscOptionsInt("-ts_monitor_lg_timestep_log", "Monitor log timestep size graphically", "TSMonitorLGTimeStep", howoften, &howoften, NULL));
2079566063dSJacob Faibussowitsch     PetscCall(TSMonitorLGCtxCreate(PetscObjectComm((PetscObject)ts), NULL, NULL, PETSC_DECIDE, PETSC_DECIDE, 400, 300, howoften, &ctx));
20849abdd8aSBarry Smith     PetscCall(TSMonitorSet(ts, TSMonitorLGTimeStep, ctx, (PetscCtxDestroyFn *)TSMonitorLGCtxDestroy));
2098b668821SLisandro Dalcin     ctx->semilogy = PETSC_TRUE;
2108b668821SLisandro Dalcin   }
2118b668821SLisandro Dalcin 
2129566063dSJacob Faibussowitsch   PetscCall(PetscOptionsName("-ts_monitor_lg_snes_iterations", "Monitor number nonlinear iterations for each timestep graphically", "TSMonitorLGSNESIterations", &opt));
213201da799SBarry Smith   if (opt) {
214201da799SBarry Smith     TSMonitorLGCtx ctx;
215201da799SBarry Smith     PetscInt       howoften = 1;
216201da799SBarry Smith 
2179566063dSJacob Faibussowitsch     PetscCall(PetscOptionsInt("-ts_monitor_lg_snes_iterations", "Monitor number nonlinear iterations for each timestep graphically", "TSMonitorLGSNESIterations", howoften, &howoften, NULL));
2189566063dSJacob Faibussowitsch     PetscCall(TSMonitorLGCtxCreate(PetscObjectComm((PetscObject)ts), NULL, NULL, PETSC_DECIDE, PETSC_DECIDE, 400, 300, howoften, &ctx));
21949abdd8aSBarry Smith     PetscCall(TSMonitorSet(ts, TSMonitorLGSNESIterations, ctx, (PetscCtxDestroyFn *)TSMonitorLGCtxDestroy));
220201da799SBarry Smith   }
2219566063dSJacob Faibussowitsch   PetscCall(PetscOptionsName("-ts_monitor_lg_ksp_iterations", "Monitor number nonlinear iterations for each timestep graphically", "TSMonitorLGKSPIterations", &opt));
222201da799SBarry Smith   if (opt) {
223201da799SBarry Smith     TSMonitorLGCtx ctx;
224201da799SBarry Smith     PetscInt       howoften = 1;
225201da799SBarry Smith 
2269566063dSJacob Faibussowitsch     PetscCall(PetscOptionsInt("-ts_monitor_lg_ksp_iterations", "Monitor number nonlinear iterations for each timestep graphically", "TSMonitorLGKSPIterations", howoften, &howoften, NULL));
2279566063dSJacob Faibussowitsch     PetscCall(TSMonitorLGCtxCreate(PetscObjectComm((PetscObject)ts), NULL, NULL, PETSC_DECIDE, PETSC_DECIDE, 400, 300, howoften, &ctx));
22849abdd8aSBarry Smith     PetscCall(TSMonitorSet(ts, TSMonitorLGKSPIterations, ctx, (PetscCtxDestroyFn *)TSMonitorLGCtxDestroy));
229201da799SBarry Smith   }
2309566063dSJacob Faibussowitsch   PetscCall(PetscOptionsName("-ts_monitor_sp_eig", "Monitor eigenvalues of linearized operator graphically", "TSMonitorSPEig", &opt));
2318189c53fSBarry Smith   if (opt) {
2328189c53fSBarry Smith     TSMonitorSPEigCtx ctx;
2338189c53fSBarry Smith     PetscInt          howoften = 1;
2348189c53fSBarry Smith 
2359566063dSJacob Faibussowitsch     PetscCall(PetscOptionsInt("-ts_monitor_sp_eig", "Monitor eigenvalues of linearized operator graphically", "TSMonitorSPEig", howoften, &howoften, NULL));
2369566063dSJacob Faibussowitsch     PetscCall(TSMonitorSPEigCtxCreate(PETSC_COMM_SELF, NULL, NULL, PETSC_DECIDE, PETSC_DECIDE, 300, 300, howoften, &ctx));
23749abdd8aSBarry Smith     PetscCall(TSMonitorSet(ts, TSMonitorSPEig, ctx, (PetscCtxDestroyFn *)TSMonitorSPEigCtxDestroy));
2388189c53fSBarry Smith   }
23960e16b1bSMatthew G. Knepley   PetscCall(PetscOptionsName("-ts_monitor_sp_swarm", "Display particle phase space from the DMSwarm", "TSMonitorSPSwarm", &opt));
2401b575b74SJoseph Pusztay   if (opt) {
2411b575b74SJoseph Pusztay     TSMonitorSPCtx ctx;
242d7462660SMatthew Knepley     PetscInt       howoften = 1, retain = 0;
24360e16b1bSMatthew G. Knepley     PetscBool      phase = PETSC_TRUE, create = PETSC_TRUE, multispecies = PETSC_FALSE;
244d7462660SMatthew Knepley 
2459371c9d4SSatish Balay     for (PetscInt i = 0; i < ts->numbermonitors; ++i)
2469371c9d4SSatish Balay       if (ts->monitor[i] == TSMonitorSPSwarmSolution) {
2479371c9d4SSatish Balay         create = PETSC_FALSE;
2489371c9d4SSatish Balay         break;
2499371c9d4SSatish Balay       }
2506a5217c0SMatthew G. Knepley     if (create) {
25160e16b1bSMatthew G. Knepley       PetscCall(PetscOptionsInt("-ts_monitor_sp_swarm", "Display particles phase space from the DMSwarm", "TSMonitorSPSwarm", howoften, &howoften, NULL));
2529566063dSJacob Faibussowitsch       PetscCall(PetscOptionsInt("-ts_monitor_sp_swarm_retain", "Retain n points plotted to show trajectory, -1 for all points", "TSMonitorSPSwarm", retain, &retain, NULL));
2539566063dSJacob Faibussowitsch       PetscCall(PetscOptionsBool("-ts_monitor_sp_swarm_phase", "Plot in phase space rather than coordinate space", "TSMonitorSPSwarm", phase, &phase, NULL));
25460e16b1bSMatthew G. Knepley       PetscCall(PetscOptionsBool("-ts_monitor_sp_swarm_multi_species", "Color particles by particle species", "TSMonitorSPSwarm", multispecies, &multispecies, NULL));
25560e16b1bSMatthew G. Knepley       PetscCall(TSMonitorSPCtxCreate(PetscObjectComm((PetscObject)ts), NULL, NULL, PETSC_DECIDE, PETSC_DECIDE, 300, 300, howoften, retain, phase, multispecies, &ctx));
25649abdd8aSBarry Smith       PetscCall(TSMonitorSet(ts, TSMonitorSPSwarmSolution, ctx, (PetscCtxDestroyFn *)TSMonitorSPCtxDestroy));
2571b575b74SJoseph Pusztay     }
2586a5217c0SMatthew G. Knepley   }
25960e16b1bSMatthew G. Knepley   PetscCall(PetscOptionsName("-ts_monitor_hg_swarm", "Display particle histogram from the DMSwarm", "TSMonitorHGSwarm", &opt));
26060e16b1bSMatthew G. Knepley   if (opt) {
26160e16b1bSMatthew G. Knepley     TSMonitorHGCtx ctx;
26260e16b1bSMatthew G. Knepley     PetscInt       howoften = 1, Ns = 1;
26360e16b1bSMatthew G. Knepley     PetscBool      velocity = PETSC_FALSE, create = PETSC_TRUE;
26460e16b1bSMatthew G. Knepley 
26560e16b1bSMatthew G. Knepley     for (PetscInt i = 0; i < ts->numbermonitors; ++i)
26660e16b1bSMatthew G. Knepley       if (ts->monitor[i] == TSMonitorHGSwarmSolution) {
26760e16b1bSMatthew G. Knepley         create = PETSC_FALSE;
26860e16b1bSMatthew G. Knepley         break;
26960e16b1bSMatthew G. Knepley       }
27060e16b1bSMatthew G. Knepley     if (create) {
27160e16b1bSMatthew G. Knepley       DM       sw, dm;
27260e16b1bSMatthew G. Knepley       PetscInt Nc, Nb;
27360e16b1bSMatthew G. Knepley 
27460e16b1bSMatthew G. Knepley       PetscCall(TSGetDM(ts, &sw));
27560e16b1bSMatthew G. Knepley       PetscCall(DMSwarmGetCellDM(sw, &dm));
27660e16b1bSMatthew G. Knepley       PetscCall(DMPlexGetHeightStratum(dm, 0, NULL, &Nc));
27760e16b1bSMatthew G. Knepley       Nb = PetscMin(20, PetscMax(10, Nc));
27860e16b1bSMatthew G. Knepley       PetscCall(PetscOptionsInt("-ts_monitor_hg_swarm", "Display particles histogram from the DMSwarm", "TSMonitorHGSwarm", howoften, &howoften, NULL));
27960e16b1bSMatthew G. Knepley       PetscCall(PetscOptionsBool("-ts_monitor_hg_swarm_velocity", "Plot in velocity space rather than coordinate space", "TSMonitorHGSwarm", velocity, &velocity, NULL));
28060e16b1bSMatthew G. Knepley       PetscCall(PetscOptionsInt("-ts_monitor_hg_swarm_species", "Number of species to histogram", "TSMonitorHGSwarm", Ns, &Ns, NULL));
28160e16b1bSMatthew G. Knepley       PetscCall(PetscOptionsInt("-ts_monitor_hg_swarm_bins", "Number of histogram bins", "TSMonitorHGSwarm", Nb, &Nb, NULL));
28260e16b1bSMatthew G. Knepley       PetscCall(TSMonitorHGCtxCreate(PetscObjectComm((PetscObject)ts), NULL, NULL, PETSC_DECIDE, PETSC_DECIDE, 300, 300, howoften, Ns, Nb, velocity, &ctx));
28349abdd8aSBarry Smith       PetscCall(TSMonitorSet(ts, TSMonitorHGSwarmSolution, ctx, (PetscCtxDestroyFn *)TSMonitorHGCtxDestroy));
28460e16b1bSMatthew G. Knepley     }
28560e16b1bSMatthew G. Knepley   }
286ef20d060SBarry Smith   opt = PETSC_FALSE;
2879566063dSJacob Faibussowitsch   PetscCall(PetscOptionsName("-ts_monitor_draw_solution", "Monitor solution graphically", "TSMonitorDrawSolution", &opt));
288a7cc72afSBarry Smith   if (opt) {
28983a4ac43SBarry Smith     TSMonitorDrawCtx ctx;
29083a4ac43SBarry Smith     PetscInt         howoften = 1;
291a80ad3e0SBarry Smith 
2929566063dSJacob Faibussowitsch     PetscCall(PetscOptionsInt("-ts_monitor_draw_solution", "Monitor solution graphically", "TSMonitorDrawSolution", howoften, &howoften, NULL));
2939566063dSJacob Faibussowitsch     PetscCall(TSMonitorDrawCtxCreate(PetscObjectComm((PetscObject)ts), NULL, "Computed Solution", PETSC_DECIDE, PETSC_DECIDE, 300, 300, howoften, &ctx));
29449abdd8aSBarry Smith     PetscCall(TSMonitorSet(ts, TSMonitorDrawSolution, ctx, (PetscCtxDestroyFn *)TSMonitorDrawCtxDestroy));
295bdad233fSMatthew Knepley   }
296fb1732b5SBarry Smith   opt = PETSC_FALSE;
2979566063dSJacob Faibussowitsch   PetscCall(PetscOptionsName("-ts_monitor_draw_solution_phase", "Monitor solution graphically", "TSMonitorDrawSolutionPhase", &opt));
2982d5ee99bSBarry Smith   if (opt) {
2992d5ee99bSBarry Smith     TSMonitorDrawCtx ctx;
3002d5ee99bSBarry Smith     PetscReal        bounds[4];
3012d5ee99bSBarry Smith     PetscInt         n = 4;
3022d5ee99bSBarry Smith     PetscDraw        draw;
3036934998bSLisandro Dalcin     PetscDrawAxis    axis;
3042d5ee99bSBarry Smith 
3059566063dSJacob Faibussowitsch     PetscCall(PetscOptionsRealArray("-ts_monitor_draw_solution_phase", "Monitor solution graphically", "TSMonitorDrawSolutionPhase", bounds, &n, NULL));
3063c633725SBarry Smith     PetscCheck(n == 4, PetscObjectComm((PetscObject)ts), PETSC_ERR_ARG_WRONG, "Must provide bounding box of phase field");
3079566063dSJacob Faibussowitsch     PetscCall(TSMonitorDrawCtxCreate(PetscObjectComm((PetscObject)ts), NULL, NULL, PETSC_DECIDE, PETSC_DECIDE, 300, 300, 1, &ctx));
3089566063dSJacob Faibussowitsch     PetscCall(PetscViewerDrawGetDraw(ctx->viewer, 0, &draw));
3099566063dSJacob Faibussowitsch     PetscCall(PetscViewerDrawGetDrawAxis(ctx->viewer, 0, &axis));
3109566063dSJacob Faibussowitsch     PetscCall(PetscDrawAxisSetLimits(axis, bounds[0], bounds[2], bounds[1], bounds[3]));
3119566063dSJacob Faibussowitsch     PetscCall(PetscDrawAxisSetLabels(axis, "Phase Diagram", "Variable 1", "Variable 2"));
31249abdd8aSBarry Smith     PetscCall(TSMonitorSet(ts, TSMonitorDrawSolutionPhase, ctx, (PetscCtxDestroyFn *)TSMonitorDrawCtxDestroy));
3132d5ee99bSBarry Smith   }
3142d5ee99bSBarry Smith   opt = PETSC_FALSE;
3159566063dSJacob Faibussowitsch   PetscCall(PetscOptionsName("-ts_monitor_draw_error", "Monitor error graphically", "TSMonitorDrawError", &opt));
3163a471f94SBarry Smith   if (opt) {
31783a4ac43SBarry Smith     TSMonitorDrawCtx ctx;
31883a4ac43SBarry Smith     PetscInt         howoften = 1;
3193a471f94SBarry Smith 
3209566063dSJacob Faibussowitsch     PetscCall(PetscOptionsInt("-ts_monitor_draw_error", "Monitor error graphically", "TSMonitorDrawError", howoften, &howoften, NULL));
3219566063dSJacob Faibussowitsch     PetscCall(TSMonitorDrawCtxCreate(PetscObjectComm((PetscObject)ts), NULL, "Error", PETSC_DECIDE, PETSC_DECIDE, 300, 300, howoften, &ctx));
32249abdd8aSBarry Smith     PetscCall(TSMonitorSet(ts, TSMonitorDrawError, ctx, (PetscCtxDestroyFn *)TSMonitorDrawCtxDestroy));
3233a471f94SBarry Smith   }
3240ed3bfb6SBarry Smith   opt = PETSC_FALSE;
3259566063dSJacob Faibussowitsch   PetscCall(PetscOptionsName("-ts_monitor_draw_solution_function", "Monitor solution provided by TSMonitorSetSolutionFunction() graphically", "TSMonitorDrawSolutionFunction", &opt));
3260ed3bfb6SBarry Smith   if (opt) {
3270ed3bfb6SBarry Smith     TSMonitorDrawCtx ctx;
3280ed3bfb6SBarry Smith     PetscInt         howoften = 1;
3290ed3bfb6SBarry Smith 
3309566063dSJacob Faibussowitsch     PetscCall(PetscOptionsInt("-ts_monitor_draw_solution_function", "Monitor solution provided by TSMonitorSetSolutionFunction() graphically", "TSMonitorDrawSolutionFunction", howoften, &howoften, NULL));
3319566063dSJacob Faibussowitsch     PetscCall(TSMonitorDrawCtxCreate(PetscObjectComm((PetscObject)ts), NULL, "Solution provided by user function", PETSC_DECIDE, PETSC_DECIDE, 300, 300, howoften, &ctx));
33249abdd8aSBarry Smith     PetscCall(TSMonitorSet(ts, TSMonitorDrawSolutionFunction, ctx, (PetscCtxDestroyFn *)TSMonitorDrawCtxDestroy));
3330ed3bfb6SBarry Smith   }
334fde5950dSBarry Smith 
335ed81e22dSJed Brown   opt = PETSC_FALSE;
33663a3b9bcSJacob 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));
337ed81e22dSJed Brown   if (flg) {
3387f27e910SStefano Zampini     TSMonitorVTKCtx ctx;
3397f27e910SStefano Zampini 
3407f27e910SStefano Zampini     PetscCall(TSMonitorSolutionVTKCtxCreate(monfilename, &ctx));
341c17ba870SStefano Zampini     PetscCall(PetscOptionsInt("-ts_monitor_solution_vtk_interval", "Save every interval time step (-1 for last step only)", NULL, ctx->interval, &ctx->interval, NULL));
34249abdd8aSBarry Smith     PetscCall(TSMonitorSet(ts, (PetscErrorCode (*)(TS, PetscInt, PetscReal, Vec, void *))TSMonitorSolutionVTK, ctx, (PetscCtxDestroyFn *)TSMonitorSolutionVTKDestroy));
343ed81e22dSJed Brown   }
344bdad233fSMatthew Knepley 
3459566063dSJacob Faibussowitsch   PetscCall(PetscOptionsString("-ts_monitor_dmda_ray", "Display a ray of the solution", "None", "y=0", dir, sizeof(dir), &flg));
346d1212d36SBarry Smith   if (flg) {
347d1212d36SBarry Smith     TSMonitorDMDARayCtx *rayctx;
348d1212d36SBarry Smith     int                  ray = 0;
3493ee9839eSMatthew G. Knepley     DMDirection          ddir;
350d1212d36SBarry Smith     DM                   da;
351d1212d36SBarry Smith     PetscMPIInt          rank;
352d1212d36SBarry Smith 
3533c633725SBarry Smith     PetscCheck(dir[1] == '=', PetscObjectComm((PetscObject)ts), PETSC_ERR_ARG_WRONG, "Unknown ray %s", dir);
3543ee9839eSMatthew G. Knepley     if (dir[0] == 'x') ddir = DM_X;
3553ee9839eSMatthew G. Knepley     else if (dir[0] == 'y') ddir = DM_Y;
35698921bdaSJacob Faibussowitsch     else SETERRQ(PetscObjectComm((PetscObject)ts), PETSC_ERR_ARG_WRONG, "Unknown ray %s", dir);
357d1212d36SBarry Smith     sscanf(dir + 2, "%d", &ray);
358d1212d36SBarry Smith 
359835f2295SStefano Zampini     PetscCall(PetscInfo(ts, "Displaying DMDA ray %c = %d\n", dir[0], ray));
3609566063dSJacob Faibussowitsch     PetscCall(PetscNew(&rayctx));
3619566063dSJacob Faibussowitsch     PetscCall(TSGetDM(ts, &da));
3629566063dSJacob Faibussowitsch     PetscCall(DMDAGetRay(da, ddir, ray, &rayctx->ray, &rayctx->scatter));
3639566063dSJacob Faibussowitsch     PetscCallMPI(MPI_Comm_rank(PetscObjectComm((PetscObject)ts), &rank));
3641e66621cSBarry Smith     if (rank == 0) PetscCall(PetscViewerDrawOpen(PETSC_COMM_SELF, NULL, NULL, 0, 0, 600, 300, &rayctx->viewer));
36551b4a12fSMatthew G. Knepley     rayctx->lgctx = NULL;
3669566063dSJacob Faibussowitsch     PetscCall(TSMonitorSet(ts, TSMonitorDMDARay, rayctx, TSMonitorDMDARayDestroy));
367d1212d36SBarry Smith   }
3689566063dSJacob Faibussowitsch   PetscCall(PetscOptionsString("-ts_monitor_lg_dmda_ray", "Display a ray of the solution", "None", "x=0", dir, sizeof(dir), &flg));
36951b4a12fSMatthew G. Knepley   if (flg) {
37051b4a12fSMatthew G. Knepley     TSMonitorDMDARayCtx *rayctx;
37151b4a12fSMatthew G. Knepley     int                  ray = 0;
3723ee9839eSMatthew G. Knepley     DMDirection          ddir;
37351b4a12fSMatthew G. Knepley     DM                   da;
37451b4a12fSMatthew G. Knepley     PetscInt             howoften = 1;
375d1212d36SBarry Smith 
3763c633725SBarry Smith     PetscCheck(dir[1] == '=', PetscObjectComm((PetscObject)ts), PETSC_ERR_ARG_WRONG, "Malformed ray %s", dir);
3773ee9839eSMatthew G. Knepley     if (dir[0] == 'x') ddir = DM_X;
3783ee9839eSMatthew G. Knepley     else if (dir[0] == 'y') ddir = DM_Y;
37998921bdaSJacob Faibussowitsch     else SETERRQ(PetscObjectComm((PetscObject)ts), PETSC_ERR_ARG_WRONG, "Unknown ray direction %s", dir);
38051b4a12fSMatthew G. Knepley     sscanf(dir + 2, "%d", &ray);
3811c3436cfSJed Brown 
382835f2295SStefano Zampini     PetscCall(PetscInfo(ts, "Displaying LG DMDA ray %c = %d\n", dir[0], ray));
3839566063dSJacob Faibussowitsch     PetscCall(PetscNew(&rayctx));
3849566063dSJacob Faibussowitsch     PetscCall(TSGetDM(ts, &da));
3859566063dSJacob Faibussowitsch     PetscCall(DMDAGetRay(da, ddir, ray, &rayctx->ray, &rayctx->scatter));
3869566063dSJacob Faibussowitsch     PetscCall(TSMonitorLGCtxCreate(PETSC_COMM_SELF, NULL, NULL, PETSC_DECIDE, PETSC_DECIDE, 600, 400, howoften, &rayctx->lgctx));
3879566063dSJacob Faibussowitsch     PetscCall(TSMonitorSet(ts, TSMonitorLGDMDARay, rayctx, TSMonitorDMDARayDestroy));
38851b4a12fSMatthew G. Knepley   }
389a7a1495cSBarry Smith 
3909566063dSJacob Faibussowitsch   PetscCall(PetscOptionsName("-ts_monitor_envelope", "Monitor maximum and minimum value of each component of the solution", "TSMonitorEnvelope", &opt));
391b3d3934dSBarry Smith   if (opt) {
392b3d3934dSBarry Smith     TSMonitorEnvelopeCtx ctx;
393b3d3934dSBarry Smith 
3949566063dSJacob Faibussowitsch     PetscCall(TSMonitorEnvelopeCtxCreate(ts, &ctx));
39549abdd8aSBarry Smith     PetscCall(TSMonitorSet(ts, TSMonitorEnvelope, ctx, (PetscCtxDestroyFn *)TSMonitorEnvelopeCtxDestroy));
396b3d3934dSBarry Smith   }
397aee7a9fbSMatthew G. Knepley   flg = PETSC_FALSE;
3989566063dSJacob Faibussowitsch   PetscCall(PetscOptionsBool("-ts_monitor_cancel", "Remove all monitors", "TSMonitorCancel", flg, &flg, &opt));
3999566063dSJacob Faibussowitsch   if (opt && flg) PetscCall(TSMonitorCancel(ts));
400b3d3934dSBarry Smith 
401847ff0e1SMatthew G. Knepley   flg = PETSC_FALSE;
402d7cfae9bSHong Zhang   PetscCall(PetscOptionsBool("-ts_fd_color", "Use finite differences with coloring to compute IJacobian", "TSComputeIJacobianDefaultColor", flg, &flg, NULL));
403847ff0e1SMatthew G. Knepley   if (flg) {
404847ff0e1SMatthew G. Knepley     DM dm;
405847ff0e1SMatthew G. Knepley 
4069371c9d4SSatish Balay     PetscCall(TSGetDM(ts, &dm));
4079371c9d4SSatish Balay     PetscCall(DMTSUnsetIJacobianContext_Internal(dm));
4089566063dSJacob Faibussowitsch     PetscCall(TSSetIJacobian(ts, NULL, NULL, TSComputeIJacobianDefaultColor, NULL));
4099566063dSJacob Faibussowitsch     PetscCall(PetscInfo(ts, "Setting default finite difference coloring Jacobian matrix\n"));
410847ff0e1SMatthew G. Knepley   }
411847ff0e1SMatthew G. Knepley 
412d763cef2SBarry Smith   /* Handle specific TS options */
413dbbe0bcdSBarry Smith   PetscTryTypeMethod(ts, setfromoptions, PetscOptionsObject);
414fbc52257SHong Zhang 
415a7bdc993SLisandro Dalcin   /* Handle TSAdapt options */
4169566063dSJacob Faibussowitsch   PetscCall(TSGetAdapt(ts, &ts->adapt));
4179566063dSJacob Faibussowitsch   PetscCall(TSAdaptSetDefaultType(ts->adapt, ts->default_adapt_type));
418dbbe0bcdSBarry Smith   PetscCall(TSAdaptSetFromOptions(ts->adapt, PetscOptionsObject));
419a7bdc993SLisandro Dalcin 
42068bece0bSHong Zhang   /* TS trajectory must be set after TS, since it may use some TS options above */
4214f122a70SLisandro Dalcin   tflg = ts->trajectory ? PETSC_TRUE : PETSC_FALSE;
4229566063dSJacob Faibussowitsch   PetscCall(PetscOptionsBool("-ts_save_trajectory", "Save the solution at each timestep", "TSSetSaveTrajectory", tflg, &tflg, NULL));
4231baa6e33SBarry Smith   if (tflg) PetscCall(TSSetSaveTrajectory(ts));
424a05bf03eSHong Zhang 
425dbbe0bcdSBarry Smith   PetscCall(TSAdjointSetFromOptions(ts, PetscOptionsObject));
426d763cef2SBarry Smith 
427d763cef2SBarry Smith   /* process any options handlers added with PetscObjectAddOptionsHandler() */
428dbbe0bcdSBarry Smith   PetscCall(PetscObjectProcessOptionsHandlers((PetscObject)ts, PetscOptionsObject));
429d0609cedSBarry Smith   PetscOptionsEnd();
430d763cef2SBarry Smith 
4311baa6e33SBarry Smith   if (ts->trajectory) PetscCall(TSTrajectorySetFromOptions(ts->trajectory, ts));
43268bece0bSHong Zhang 
4331ef27442SStefano Zampini   /* why do we have to do this here and not during TSSetUp? */
4349566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts, &ts->snes));
4351ef27442SStefano Zampini   if (ts->problem_type == TS_LINEAR) {
4369566063dSJacob Faibussowitsch     PetscCall(PetscObjectTypeCompareAny((PetscObject)ts->snes, &flg, SNESKSPONLY, SNESKSPTRANSPOSEONLY, ""));
4379566063dSJacob Faibussowitsch     if (!flg) PetscCall(SNESSetType(ts->snes, SNESKSPONLY));
4381ef27442SStefano Zampini   }
4399566063dSJacob Faibussowitsch   PetscCall(SNESSetFromOptions(ts->snes));
4403ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
441d763cef2SBarry Smith }
442d763cef2SBarry Smith 
443d2daff3dSHong Zhang /*@
444bcf0153eSBarry Smith   TSGetTrajectory - Gets the trajectory from a `TS` if it exists
44578fbdcc8SBarry Smith 
446c3339decSBarry Smith   Collective
44778fbdcc8SBarry Smith 
4482fe279fdSBarry Smith   Input Parameter:
449bcf0153eSBarry Smith . ts - the `TS` context obtained from `TSCreate()`
45078fbdcc8SBarry Smith 
4512fe279fdSBarry Smith   Output Parameter:
452bcf0153eSBarry Smith . tr - the `TSTrajectory` object, if it exists
45378fbdcc8SBarry Smith 
45478fbdcc8SBarry Smith   Level: advanced
45578fbdcc8SBarry Smith 
456bcf0153eSBarry Smith   Note:
457bcf0153eSBarry Smith   This routine should be called after all `TS` options have been set
45878fbdcc8SBarry Smith 
459b43aa488SJacob Faibussowitsch .seealso: [](ch_ts), `TS`, `TSTrajectory`, `TSAdjointSolve()`, `TSTrajectoryCreate()`
46078fbdcc8SBarry Smith @*/
461d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetTrajectory(TS ts, TSTrajectory *tr)
462d71ae5a4SJacob Faibussowitsch {
46378fbdcc8SBarry Smith   PetscFunctionBegin;
46478fbdcc8SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
46578fbdcc8SBarry Smith   *tr = ts->trajectory;
4663ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
46778fbdcc8SBarry Smith }
46878fbdcc8SBarry Smith 
46978fbdcc8SBarry Smith /*@
470bcf0153eSBarry Smith   TSSetSaveTrajectory - Causes the `TS` to save its solutions as it iterates forward in time in a `TSTrajectory` object
471d2daff3dSHong Zhang 
472c3339decSBarry Smith   Collective
473d2daff3dSHong Zhang 
474f899ff85SJose E. Roman   Input Parameter:
475bcf0153eSBarry Smith . ts - the `TS` context obtained from `TSCreate()`
476bc952696SBarry Smith 
477bcf0153eSBarry Smith   Options Database Keys:
47878fbdcc8SBarry Smith + -ts_save_trajectory      - saves the trajectory to a file
47967b8a455SSatish Balay - -ts_trajectory_type type - set trajectory type
48078fbdcc8SBarry Smith 
481d2daff3dSHong Zhang   Level: intermediate
482d2daff3dSHong Zhang 
483bcf0153eSBarry Smith   Notes:
484bcf0153eSBarry Smith   This routine should be called after all `TS` options have been set
485d2daff3dSHong Zhang 
486bcf0153eSBarry Smith   The `TSTRAJECTORYVISUALIZATION` files can be loaded into Python with $PETSC_DIR/lib/petsc/bin/PetscBinaryIOTrajectory.py and
487bcf0153eSBarry Smith   MATLAB with $PETSC_DIR/share/petsc/matlab/PetscReadBinaryTrajectory.m
488bcf0153eSBarry Smith 
4891cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSTrajectory`, `TSGetTrajectory()`, `TSAdjointSolve()`
490d2daff3dSHong Zhang @*/
491d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetSaveTrajectory(TS ts)
492d71ae5a4SJacob Faibussowitsch {
493d2daff3dSHong Zhang   PetscFunctionBegin;
494d2daff3dSHong Zhang   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
49563a3b9bcSJacob Faibussowitsch   if (!ts->trajectory) PetscCall(TSTrajectoryCreate(PetscObjectComm((PetscObject)ts), &ts->trajectory));
4963ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
497d2daff3dSHong Zhang }
498d2daff3dSHong Zhang 
499a7a1495cSBarry Smith /*@
500bcf0153eSBarry Smith   TSResetTrajectory - Destroys and recreates the internal `TSTrajectory` object
5012d29f1f2SStefano Zampini 
502c3339decSBarry Smith   Collective
5032d29f1f2SStefano Zampini 
5042fe279fdSBarry Smith   Input Parameter:
505bcf0153eSBarry Smith . ts - the `TS` context obtained from `TSCreate()`
5062d29f1f2SStefano Zampini 
5072d29f1f2SStefano Zampini   Level: intermediate
5082d29f1f2SStefano Zampini 
5091cc06b55SBarry Smith .seealso: [](ch_ts), `TSTrajectory`, `TSGetTrajectory()`, `TSAdjointSolve()`, `TSRemoveTrajectory()`
5102d29f1f2SStefano Zampini @*/
511d71ae5a4SJacob Faibussowitsch PetscErrorCode TSResetTrajectory(TS ts)
512d71ae5a4SJacob Faibussowitsch {
5132d29f1f2SStefano Zampini   PetscFunctionBegin;
5142d29f1f2SStefano Zampini   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
5152d29f1f2SStefano Zampini   if (ts->trajectory) {
5169566063dSJacob Faibussowitsch     PetscCall(TSTrajectoryDestroy(&ts->trajectory));
5179566063dSJacob Faibussowitsch     PetscCall(TSTrajectoryCreate(PetscObjectComm((PetscObject)ts), &ts->trajectory));
5182d29f1f2SStefano Zampini   }
5193ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
5202d29f1f2SStefano Zampini }
5212d29f1f2SStefano Zampini 
5222d29f1f2SStefano Zampini /*@
523195e9b02SBarry Smith   TSRemoveTrajectory - Destroys and removes the internal `TSTrajectory` object from a `TS`
52467a3cfb0SHong Zhang 
525c3339decSBarry Smith   Collective
52667a3cfb0SHong Zhang 
5272fe279fdSBarry Smith   Input Parameter:
528bcf0153eSBarry Smith . ts - the `TS` context obtained from `TSCreate()`
52967a3cfb0SHong Zhang 
53067a3cfb0SHong Zhang   Level: intermediate
53167a3cfb0SHong Zhang 
5321cc06b55SBarry Smith .seealso: [](ch_ts), `TSTrajectory`, `TSResetTrajectory()`, `TSAdjointSolve()`
53367a3cfb0SHong Zhang @*/
534d71ae5a4SJacob Faibussowitsch PetscErrorCode TSRemoveTrajectory(TS ts)
535d71ae5a4SJacob Faibussowitsch {
53667a3cfb0SHong Zhang   PetscFunctionBegin;
53767a3cfb0SHong Zhang   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
5381e66621cSBarry Smith   if (ts->trajectory) PetscCall(TSTrajectoryDestroy(&ts->trajectory));
5393ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
54067a3cfb0SHong Zhang }
54167a3cfb0SHong Zhang 
54267a3cfb0SHong Zhang /*@
543a7a1495cSBarry Smith   TSComputeRHSJacobian - Computes the Jacobian matrix that has been
544bcf0153eSBarry Smith   set with `TSSetRHSJacobian()`.
545a7a1495cSBarry Smith 
546c3339decSBarry Smith   Collective
547a7a1495cSBarry Smith 
548a7a1495cSBarry Smith   Input Parameters:
549bcf0153eSBarry Smith + ts - the `TS` context
550a7a1495cSBarry Smith . t  - current timestep
5510910c330SBarry Smith - U  - input vector
552a7a1495cSBarry Smith 
553a7a1495cSBarry Smith   Output Parameters:
554a7a1495cSBarry Smith + A - Jacobian matrix
5557addb90fSBarry Smith - B - optional matrix used to compute the preconditioner, often the same as `A`
556a7a1495cSBarry Smith 
557bcf0153eSBarry Smith   Level: developer
558bcf0153eSBarry Smith 
559bcf0153eSBarry Smith   Note:
560a7a1495cSBarry Smith   Most users should not need to explicitly call this routine, as it
5617addb90fSBarry Smith   is used internally within the ODE integrators.
562a7a1495cSBarry Smith 
5631cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetRHSJacobian()`, `KSPSetOperators()`
564a7a1495cSBarry Smith @*/
565d71ae5a4SJacob Faibussowitsch PetscErrorCode TSComputeRHSJacobian(TS ts, PetscReal t, Vec U, Mat A, Mat B)
566d71ae5a4SJacob Faibussowitsch {
567270bf2e7SJed Brown   PetscObjectState Ustate;
5686c1e1eecSBarry Smith   PetscObjectId    Uid;
56924989b8cSPeter Brune   DM               dm;
570942e3340SBarry Smith   DMTS             tsdm;
5718434afd1SBarry Smith   TSRHSJacobianFn *rhsjacobianfunc;
57224989b8cSPeter Brune   void            *ctx;
5738434afd1SBarry Smith   TSRHSFunctionFn *rhsfunction;
574a7a1495cSBarry Smith 
575a7a1495cSBarry Smith   PetscFunctionBegin;
5760700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
5770910c330SBarry Smith   PetscValidHeaderSpecific(U, VEC_CLASSID, 3);
5780910c330SBarry Smith   PetscCheckSameComm(ts, 1, U, 3);
5799566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
5809566063dSJacob Faibussowitsch   PetscCall(DMGetDMTS(dm, &tsdm));
5819566063dSJacob Faibussowitsch   PetscCall(DMTSGetRHSFunction(dm, &rhsfunction, NULL));
5829566063dSJacob Faibussowitsch   PetscCall(DMTSGetRHSJacobian(dm, &rhsjacobianfunc, &ctx));
5839566063dSJacob Faibussowitsch   PetscCall(PetscObjectStateGet((PetscObject)U, &Ustate));
5849566063dSJacob Faibussowitsch   PetscCall(PetscObjectGetId((PetscObject)U, &Uid));
585971015bcSStefano Zampini 
5863ba16761SJacob Faibussowitsch   if (ts->rhsjacobian.time == t && (ts->problem_type == TS_LINEAR || (ts->rhsjacobian.Xid == Uid && ts->rhsjacobian.Xstate == Ustate)) && (rhsfunction != TSComputeRHSFunctionLinear)) PetscFunctionReturn(PETSC_SUCCESS);
587d90be118SSean Farley 
58863a3b9bcSJacob 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);
58924989b8cSPeter Brune   if (rhsjacobianfunc) {
590da023ba9SStefano Zampini     PetscCall(PetscLogEventBegin(TS_JacobianEval, U, ts, A, B));
591792fecdfSBarry Smith     PetscCallBack("TS callback Jacobian", (*rhsjacobianfunc)(ts, t, U, A, B, ctx));
592a6ab3590SBarry Smith     ts->rhsjacs++;
593da023ba9SStefano Zampini     PetscCall(PetscLogEventEnd(TS_JacobianEval, U, ts, A, B));
594ef66eb69SBarry Smith   } else {
5959566063dSJacob Faibussowitsch     PetscCall(MatZeroEntries(A));
5969566063dSJacob Faibussowitsch     if (B && A != B) PetscCall(MatZeroEntries(B));
597ef66eb69SBarry Smith   }
5980e4ef248SJed Brown   ts->rhsjacobian.time  = t;
599971015bcSStefano Zampini   ts->rhsjacobian.shift = 0;
600971015bcSStefano Zampini   ts->rhsjacobian.scale = 1.;
6019566063dSJacob Faibussowitsch   PetscCall(PetscObjectGetId((PetscObject)U, &ts->rhsjacobian.Xid));
6029566063dSJacob Faibussowitsch   PetscCall(PetscObjectStateGet((PetscObject)U, &ts->rhsjacobian.Xstate));
6033ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
604a7a1495cSBarry Smith }
605a7a1495cSBarry Smith 
606316643e7SJed Brown /*@
607bcf0153eSBarry Smith   TSComputeRHSFunction - Evaluates the right-hand-side function for a `TS`
608d763cef2SBarry Smith 
609c3339decSBarry Smith   Collective
610316643e7SJed Brown 
611316643e7SJed Brown   Input Parameters:
612bcf0153eSBarry Smith + ts - the `TS` context
613316643e7SJed Brown . t  - current time
6140910c330SBarry Smith - U  - state vector
615316643e7SJed Brown 
616316643e7SJed Brown   Output Parameter:
617dd8e379bSPierre Jolivet . y - right-hand side
618316643e7SJed Brown 
619bcf0153eSBarry Smith   Level: developer
620bcf0153eSBarry Smith 
621316643e7SJed Brown   Note:
622316643e7SJed Brown   Most users should not need to explicitly call this routine, as it
623316643e7SJed Brown   is used internally within the nonlinear solvers.
624316643e7SJed Brown 
6251cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetRHSFunction()`, `TSComputeIFunction()`
626316643e7SJed Brown @*/
627d71ae5a4SJacob Faibussowitsch PetscErrorCode TSComputeRHSFunction(TS ts, PetscReal t, Vec U, Vec y)
628d71ae5a4SJacob Faibussowitsch {
6298434afd1SBarry Smith   TSRHSFunctionFn *rhsfunction;
6308434afd1SBarry Smith   TSIFunctionFn   *ifunction;
63124989b8cSPeter Brune   void            *ctx;
63224989b8cSPeter Brune   DM               dm;
63324989b8cSPeter Brune 
634d763cef2SBarry Smith   PetscFunctionBegin;
6350700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
6360910c330SBarry Smith   PetscValidHeaderSpecific(U, VEC_CLASSID, 3);
6370700a824SBarry Smith   PetscValidHeaderSpecific(y, VEC_CLASSID, 4);
6389566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
6399566063dSJacob Faibussowitsch   PetscCall(DMTSGetRHSFunction(dm, &rhsfunction, &ctx));
6409566063dSJacob Faibussowitsch   PetscCall(DMTSGetIFunction(dm, &ifunction, NULL));
641d763cef2SBarry Smith 
6423c633725SBarry Smith   PetscCheck(rhsfunction || ifunction, PetscObjectComm((PetscObject)ts), PETSC_ERR_USER, "Must call TSSetRHSFunction() and / or TSSetIFunction()");
643d763cef2SBarry Smith 
64424989b8cSPeter Brune   if (rhsfunction) {
645da023ba9SStefano Zampini     PetscCall(PetscLogEventBegin(TS_FunctionEval, U, ts, y, 0));
6469566063dSJacob Faibussowitsch     PetscCall(VecLockReadPush(U));
647792fecdfSBarry Smith     PetscCallBack("TS callback right-hand-side", (*rhsfunction)(ts, t, U, y, ctx));
6489566063dSJacob Faibussowitsch     PetscCall(VecLockReadPop(U));
649a6ab3590SBarry Smith     ts->rhsfuncs++;
650da023ba9SStefano Zampini     PetscCall(PetscLogEventEnd(TS_FunctionEval, U, ts, y, 0));
6511e66621cSBarry Smith   } else PetscCall(VecZeroEntries(y));
6523ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
653d763cef2SBarry Smith }
654d763cef2SBarry Smith 
655ef20d060SBarry Smith /*@
656ef20d060SBarry Smith   TSComputeSolutionFunction - Evaluates the solution function.
657ef20d060SBarry Smith 
658c3339decSBarry Smith   Collective
659ef20d060SBarry Smith 
660ef20d060SBarry Smith   Input Parameters:
661bcf0153eSBarry Smith + ts - the `TS` context
662ef20d060SBarry Smith - t  - current time
663ef20d060SBarry Smith 
664ef20d060SBarry Smith   Output Parameter:
6650910c330SBarry Smith . U - the solution
666ef20d060SBarry Smith 
667ef20d060SBarry Smith   Level: developer
668ef20d060SBarry Smith 
6691cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetSolutionFunction()`, `TSSetRHSFunction()`, `TSComputeIFunction()`
670ef20d060SBarry Smith @*/
671d71ae5a4SJacob Faibussowitsch PetscErrorCode TSComputeSolutionFunction(TS ts, PetscReal t, Vec U)
672d71ae5a4SJacob Faibussowitsch {
6738434afd1SBarry Smith   TSSolutionFn *solutionfunction;
674ef20d060SBarry Smith   void         *ctx;
675ef20d060SBarry Smith   DM            dm;
676ef20d060SBarry Smith 
677ef20d060SBarry Smith   PetscFunctionBegin;
678ef20d060SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
6790910c330SBarry Smith   PetscValidHeaderSpecific(U, VEC_CLASSID, 3);
6809566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
6819566063dSJacob Faibussowitsch   PetscCall(DMTSGetSolutionFunction(dm, &solutionfunction, &ctx));
682792fecdfSBarry Smith   if (solutionfunction) PetscCallBack("TS callback solution", (*solutionfunction)(ts, t, U, ctx));
6833ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
684ef20d060SBarry Smith }
6859b7cd975SBarry Smith /*@
6869b7cd975SBarry Smith   TSComputeForcingFunction - Evaluates the forcing function.
6879b7cd975SBarry Smith 
688c3339decSBarry Smith   Collective
6899b7cd975SBarry Smith 
6909b7cd975SBarry Smith   Input Parameters:
691bcf0153eSBarry Smith + ts - the `TS` context
6929b7cd975SBarry Smith - t  - current time
6939b7cd975SBarry Smith 
6949b7cd975SBarry Smith   Output Parameter:
6959b7cd975SBarry Smith . U - the function value
6969b7cd975SBarry Smith 
6979b7cd975SBarry Smith   Level: developer
6989b7cd975SBarry Smith 
6991cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetSolutionFunction()`, `TSSetRHSFunction()`, `TSComputeIFunction()`
7009b7cd975SBarry Smith @*/
701d71ae5a4SJacob Faibussowitsch PetscErrorCode TSComputeForcingFunction(TS ts, PetscReal t, Vec U)
702d71ae5a4SJacob Faibussowitsch {
7039b7cd975SBarry Smith   void        *ctx;
7049b7cd975SBarry Smith   DM           dm;
7058434afd1SBarry Smith   TSForcingFn *forcing;
7069b7cd975SBarry Smith 
7079b7cd975SBarry Smith   PetscFunctionBegin;
7089b7cd975SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
7099b7cd975SBarry Smith   PetscValidHeaderSpecific(U, VEC_CLASSID, 3);
7109566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
7119566063dSJacob Faibussowitsch   PetscCall(DMTSGetForcingFunction(dm, &forcing, &ctx));
7129b7cd975SBarry Smith 
713792fecdfSBarry Smith   if (forcing) PetscCallBack("TS callback forcing function", (*forcing)(ts, t, U, ctx));
7143ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
7159b7cd975SBarry Smith }
716ef20d060SBarry Smith 
717d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetRHSMats_Private(TS ts, Mat *Arhs, Mat *Brhs)
718d71ae5a4SJacob Faibussowitsch {
719214bc6a2SJed Brown   Mat            A, B;
7208434afd1SBarry Smith   TSIJacobianFn *ijacobian;
721214bc6a2SJed Brown 
722214bc6a2SJed Brown   PetscFunctionBegin;
723c0cd0301SJed Brown   if (Arhs) *Arhs = NULL;
724c0cd0301SJed Brown   if (Brhs) *Brhs = NULL;
7259566063dSJacob Faibussowitsch   PetscCall(TSGetIJacobian(ts, &A, &B, &ijacobian, NULL));
726214bc6a2SJed Brown   if (Arhs) {
727214bc6a2SJed Brown     if (!ts->Arhs) {
72841a1d4d2SBarry Smith       if (ijacobian) {
7299566063dSJacob Faibussowitsch         PetscCall(MatDuplicate(A, MAT_DO_NOT_COPY_VALUES, &ts->Arhs));
7309566063dSJacob Faibussowitsch         PetscCall(TSSetMatStructure(ts, SAME_NONZERO_PATTERN));
73141a1d4d2SBarry Smith       } else {
73241a1d4d2SBarry Smith         ts->Arhs = A;
7339566063dSJacob Faibussowitsch         PetscCall(PetscObjectReference((PetscObject)A));
73441a1d4d2SBarry Smith       }
7353565c898SBarry Smith     } else {
7363565c898SBarry Smith       PetscBool flg;
7379566063dSJacob Faibussowitsch       PetscCall(SNESGetUseMatrixFree(ts->snes, NULL, &flg));
7383565c898SBarry Smith       /* Handle case where user provided only RHSJacobian and used -snes_mf_operator */
7393565c898SBarry Smith       if (flg && !ijacobian && ts->Arhs == ts->Brhs) {
7409566063dSJacob Faibussowitsch         PetscCall(PetscObjectDereference((PetscObject)ts->Arhs));
7413565c898SBarry Smith         ts->Arhs = A;
7429566063dSJacob Faibussowitsch         PetscCall(PetscObjectReference((PetscObject)A));
7433565c898SBarry Smith       }
744214bc6a2SJed Brown     }
745214bc6a2SJed Brown     *Arhs = ts->Arhs;
746214bc6a2SJed Brown   }
747214bc6a2SJed Brown   if (Brhs) {
748214bc6a2SJed Brown     if (!ts->Brhs) {
749bdb70873SJed Brown       if (A != B) {
75041a1d4d2SBarry Smith         if (ijacobian) {
7519566063dSJacob Faibussowitsch           PetscCall(MatDuplicate(B, MAT_DO_NOT_COPY_VALUES, &ts->Brhs));
752bdb70873SJed Brown         } else {
75341a1d4d2SBarry Smith           ts->Brhs = B;
7549566063dSJacob Faibussowitsch           PetscCall(PetscObjectReference((PetscObject)B));
75541a1d4d2SBarry Smith         }
75641a1d4d2SBarry Smith       } else {
7579566063dSJacob Faibussowitsch         PetscCall(PetscObjectReference((PetscObject)ts->Arhs));
75851699248SLisandro Dalcin         ts->Brhs = ts->Arhs;
759bdb70873SJed Brown       }
760214bc6a2SJed Brown     }
761214bc6a2SJed Brown     *Brhs = ts->Brhs;
762214bc6a2SJed Brown   }
7633ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
764214bc6a2SJed Brown }
765214bc6a2SJed Brown 
766316643e7SJed Brown /*@
767195e9b02SBarry Smith   TSComputeIFunction - Evaluates the DAE residual written in the implicit form F(t,U,Udot)=0
768316643e7SJed Brown 
769c3339decSBarry Smith   Collective
770316643e7SJed Brown 
771316643e7SJed Brown   Input Parameters:
772bcf0153eSBarry Smith + ts   - the `TS` context
773316643e7SJed Brown . t    - current time
7740910c330SBarry Smith . U    - state vector
7750910c330SBarry Smith . Udot - time derivative of state vector
7763dddbd81SStefano Zampini - imex - flag indicates if the method is `TSARKIMEX` so that the RHSFunction should be kept separate
777316643e7SJed Brown 
778316643e7SJed Brown   Output Parameter:
779dd8e379bSPierre Jolivet . Y - right-hand side
780316643e7SJed Brown 
781bcf0153eSBarry Smith   Level: developer
782bcf0153eSBarry Smith 
783316643e7SJed Brown   Note:
784316643e7SJed Brown   Most users should not need to explicitly call this routine, as it
785316643e7SJed Brown   is used internally within the nonlinear solvers.
786316643e7SJed Brown 
78715229ffcSPierre Jolivet   If the user did not write their equations in implicit form, this
788316643e7SJed Brown   function recasts them in implicit form.
789316643e7SJed Brown 
7901cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetIFunction()`, `TSComputeRHSFunction()`
791316643e7SJed Brown @*/
792d71ae5a4SJacob Faibussowitsch PetscErrorCode TSComputeIFunction(TS ts, PetscReal t, Vec U, Vec Udot, Vec Y, PetscBool imex)
793d71ae5a4SJacob Faibussowitsch {
7948434afd1SBarry Smith   TSIFunctionFn   *ifunction;
7958434afd1SBarry Smith   TSRHSFunctionFn *rhsfunction;
79624989b8cSPeter Brune   void            *ctx;
79724989b8cSPeter Brune   DM               dm;
798316643e7SJed Brown 
799316643e7SJed Brown   PetscFunctionBegin;
8000700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
8010910c330SBarry Smith   PetscValidHeaderSpecific(U, VEC_CLASSID, 3);
8020910c330SBarry Smith   PetscValidHeaderSpecific(Udot, VEC_CLASSID, 4);
8030700a824SBarry Smith   PetscValidHeaderSpecific(Y, VEC_CLASSID, 5);
804316643e7SJed Brown 
8059566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
8069566063dSJacob Faibussowitsch   PetscCall(DMTSGetIFunction(dm, &ifunction, &ctx));
8079566063dSJacob Faibussowitsch   PetscCall(DMTSGetRHSFunction(dm, &rhsfunction, NULL));
80824989b8cSPeter Brune 
8093c633725SBarry Smith   PetscCheck(rhsfunction || ifunction, PetscObjectComm((PetscObject)ts), PETSC_ERR_USER, "Must call TSSetRHSFunction() and / or TSSetIFunction()");
810d90be118SSean Farley 
811da023ba9SStefano Zampini   PetscCall(PetscLogEventBegin(TS_FunctionEval, U, ts, Udot, Y));
81224989b8cSPeter Brune   if (ifunction) {
813792fecdfSBarry Smith     PetscCallBack("TS callback implicit function", (*ifunction)(ts, t, U, Udot, Y, ctx));
814a6ab3590SBarry Smith     ts->ifuncs++;
815214bc6a2SJed Brown   }
816214bc6a2SJed Brown   if (imex) {
8171e66621cSBarry Smith     if (!ifunction) PetscCall(VecCopy(Udot, Y));
81824989b8cSPeter Brune   } else if (rhsfunction) {
81924989b8cSPeter Brune     if (ifunction) {
820214bc6a2SJed Brown       Vec Frhs;
8218af0501fSStefano Zampini 
8228af0501fSStefano Zampini       PetscCall(DMGetGlobalVector(dm, &Frhs));
8239566063dSJacob Faibussowitsch       PetscCall(TSComputeRHSFunction(ts, t, U, Frhs));
8249566063dSJacob Faibussowitsch       PetscCall(VecAXPY(Y, -1, Frhs));
8258af0501fSStefano Zampini       PetscCall(DMRestoreGlobalVector(dm, &Frhs));
8262dd45cf8SJed Brown     } else {
8279566063dSJacob Faibussowitsch       PetscCall(TSComputeRHSFunction(ts, t, U, Y));
8289566063dSJacob Faibussowitsch       PetscCall(VecAYPX(Y, -1, Udot));
829316643e7SJed Brown     }
8304a6899ffSJed Brown   }
831da023ba9SStefano Zampini   PetscCall(PetscLogEventEnd(TS_FunctionEval, U, ts, Udot, Y));
8323ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
833316643e7SJed Brown }
834316643e7SJed Brown 
835cfa8a9a2SHong Zhang /*
836195e9b02SBarry Smith    TSRecoverRHSJacobian - Recover the Jacobian matrix so that one can call `TSComputeRHSJacobian()` on it.
837cfa8a9a2SHong Zhang 
838cfa8a9a2SHong Zhang    Note:
839195e9b02SBarry Smith    This routine is needed when one switches from `TSComputeIJacobian()` to `TSComputeRHSJacobian()` because the Jacobian matrix may be shifted or scaled in `TSComputeIJacobian()`.
840cfa8a9a2SHong Zhang 
841cfa8a9a2SHong Zhang */
842d71ae5a4SJacob Faibussowitsch static PetscErrorCode TSRecoverRHSJacobian(TS ts, Mat A, Mat B)
843d71ae5a4SJacob Faibussowitsch {
844cfa8a9a2SHong Zhang   PetscFunctionBegin;
845cfa8a9a2SHong Zhang   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
8463c633725SBarry Smith   PetscCheck(A == ts->Arhs, PetscObjectComm((PetscObject)ts), PETSC_ERR_SUP, "Invalid Amat");
8473c633725SBarry Smith   PetscCheck(B == ts->Brhs, PetscObjectComm((PetscObject)ts), PETSC_ERR_SUP, "Invalid Bmat");
848cfa8a9a2SHong Zhang 
8491baa6e33SBarry Smith   if (ts->rhsjacobian.shift) PetscCall(MatShift(A, -ts->rhsjacobian.shift));
85048a46eb9SPierre Jolivet   if (ts->rhsjacobian.scale == -1.) PetscCall(MatScale(A, -1));
851cfa8a9a2SHong Zhang   if (B && B == ts->Brhs && A != B) {
8521baa6e33SBarry Smith     if (ts->rhsjacobian.shift) PetscCall(MatShift(B, -ts->rhsjacobian.shift));
8531e66621cSBarry Smith     if (ts->rhsjacobian.scale == -1.) PetscCall(MatScale(B, -1));
854cfa8a9a2SHong Zhang   }
855cfa8a9a2SHong Zhang   ts->rhsjacobian.shift = 0;
856cfa8a9a2SHong Zhang   ts->rhsjacobian.scale = 1.;
8573ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
858cfa8a9a2SHong Zhang }
859cfa8a9a2SHong Zhang 
860316643e7SJed Brown /*@
861316643e7SJed Brown   TSComputeIJacobian - Evaluates the Jacobian of the DAE
862316643e7SJed Brown 
863c3339decSBarry Smith   Collective
864316643e7SJed Brown 
865316643e7SJed Brown   Input Parameters:
866bcf0153eSBarry Smith + ts    - the `TS` context
867316643e7SJed Brown . t     - current timestep
8680910c330SBarry Smith . U     - state vector
8690910c330SBarry Smith . Udot  - time derivative of state vector
870214bc6a2SJed Brown . shift - shift to apply, see note below
8713dddbd81SStefano Zampini - imex  - flag indicates if the method is `TSARKIMEX` so that the RHSJacobian should be kept separate
872316643e7SJed Brown 
873316643e7SJed Brown   Output Parameters:
874316643e7SJed Brown + A - Jacobian matrix
875195e9b02SBarry Smith - B - matrix from which the preconditioner is constructed; often the same as `A`
876316643e7SJed Brown 
877bcf0153eSBarry Smith   Level: developer
878bcf0153eSBarry Smith 
879316643e7SJed Brown   Notes:
8800910c330SBarry Smith   If F(t,U,Udot)=0 is the DAE, the required Jacobian is
881195e9b02SBarry Smith .vb
8820910c330SBarry Smith    dF/dU + shift*dF/dUdot
883195e9b02SBarry Smith .ve
884316643e7SJed Brown   Most users should not need to explicitly call this routine, as it
885316643e7SJed Brown   is used internally within the nonlinear solvers.
886316643e7SJed Brown 
8871cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetIJacobian()`
88863495f91SJed Brown @*/
889d71ae5a4SJacob Faibussowitsch PetscErrorCode TSComputeIJacobian(TS ts, PetscReal t, Vec U, Vec Udot, PetscReal shift, Mat A, Mat B, PetscBool imex)
890d71ae5a4SJacob Faibussowitsch {
8918434afd1SBarry Smith   TSIJacobianFn   *ijacobian;
8928434afd1SBarry Smith   TSRHSJacobianFn *rhsjacobian;
89324989b8cSPeter Brune   DM               dm;
89424989b8cSPeter Brune   void            *ctx;
895316643e7SJed Brown 
896316643e7SJed Brown   PetscFunctionBegin;
8970700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
8980910c330SBarry Smith   PetscValidHeaderSpecific(U, VEC_CLASSID, 3);
8990910c330SBarry Smith   PetscValidHeaderSpecific(Udot, VEC_CLASSID, 4);
90094ab13aaSBarry Smith   PetscValidHeaderSpecific(A, MAT_CLASSID, 6);
90194ab13aaSBarry Smith   PetscValidHeaderSpecific(B, MAT_CLASSID, 7);
90224989b8cSPeter Brune 
9039566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
9049566063dSJacob Faibussowitsch   PetscCall(DMTSGetIJacobian(dm, &ijacobian, &ctx));
9059566063dSJacob Faibussowitsch   PetscCall(DMTSGetRHSJacobian(dm, &rhsjacobian, NULL));
90624989b8cSPeter Brune 
9073c633725SBarry Smith   PetscCheck(rhsjacobian || ijacobian, PetscObjectComm((PetscObject)ts), PETSC_ERR_USER, "Must call TSSetRHSJacobian() and / or TSSetIJacobian()");
908316643e7SJed Brown 
909da023ba9SStefano Zampini   PetscCall(PetscLogEventBegin(TS_JacobianEval, U, ts, A, B));
91024989b8cSPeter Brune   if (ijacobian) {
911792fecdfSBarry Smith     PetscCallBack("TS callback implicit Jacobian", (*ijacobian)(ts, t, U, Udot, shift, A, B, ctx));
912a6ab3590SBarry Smith     ts->ijacs++;
9134a6899ffSJed Brown   }
914214bc6a2SJed Brown   if (imex) {
915b5abc632SBarry Smith     if (!ijacobian) { /* system was written as Udot = G(t,U) */
9164c26be97Sstefano_zampini       PetscBool assembled;
917971015bcSStefano Zampini       if (rhsjacobian) {
918971015bcSStefano Zampini         Mat Arhs = NULL;
9199566063dSJacob Faibussowitsch         PetscCall(TSGetRHSMats_Private(ts, &Arhs, NULL));
920971015bcSStefano Zampini         if (A == Arhs) {
9213c633725SBarry 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 */
922971015bcSStefano Zampini           ts->rhsjacobian.time = PETSC_MIN_REAL;
923971015bcSStefano Zampini         }
924971015bcSStefano Zampini       }
9259566063dSJacob Faibussowitsch       PetscCall(MatZeroEntries(A));
9269566063dSJacob Faibussowitsch       PetscCall(MatAssembled(A, &assembled));
9274c26be97Sstefano_zampini       if (!assembled) {
9289566063dSJacob Faibussowitsch         PetscCall(MatAssemblyBegin(A, MAT_FINAL_ASSEMBLY));
9299566063dSJacob Faibussowitsch         PetscCall(MatAssemblyEnd(A, MAT_FINAL_ASSEMBLY));
9304c26be97Sstefano_zampini       }
9319566063dSJacob Faibussowitsch       PetscCall(MatShift(A, shift));
93294ab13aaSBarry Smith       if (A != B) {
9339566063dSJacob Faibussowitsch         PetscCall(MatZeroEntries(B));
9349566063dSJacob Faibussowitsch         PetscCall(MatAssembled(B, &assembled));
9354c26be97Sstefano_zampini         if (!assembled) {
9369566063dSJacob Faibussowitsch           PetscCall(MatAssemblyBegin(B, MAT_FINAL_ASSEMBLY));
9379566063dSJacob Faibussowitsch           PetscCall(MatAssemblyEnd(B, MAT_FINAL_ASSEMBLY));
9384c26be97Sstefano_zampini         }
9399566063dSJacob Faibussowitsch         PetscCall(MatShift(B, shift));
940214bc6a2SJed Brown       }
941214bc6a2SJed Brown     }
942214bc6a2SJed Brown   } else {
943e1244c69SJed Brown     Mat Arhs = NULL, Brhs = NULL;
9441e66621cSBarry Smith 
9451e66621cSBarry Smith     /* RHSJacobian needs to be converted to part of IJacobian if exists */
9461e66621cSBarry Smith     if (rhsjacobian) PetscCall(TSGetRHSMats_Private(ts, &Arhs, &Brhs));
947e8b1e424SHong Zhang     if (Arhs == A) { /* No IJacobian matrix, so we only have the RHS matrix */
948e8b1e424SHong Zhang       PetscObjectState Ustate;
949e8b1e424SHong Zhang       PetscObjectId    Uid;
9508434afd1SBarry Smith       TSRHSFunctionFn *rhsfunction;
951e8b1e424SHong Zhang 
9529566063dSJacob Faibussowitsch       PetscCall(DMTSGetRHSFunction(dm, &rhsfunction, NULL));
9539566063dSJacob Faibussowitsch       PetscCall(PetscObjectStateGet((PetscObject)U, &Ustate));
9549566063dSJacob Faibussowitsch       PetscCall(PetscObjectGetId((PetscObject)U, &Uid));
9559371c9d4SSatish Balay       if ((rhsjacobian == TSComputeRHSJacobianConstant || (ts->rhsjacobian.time == t && (ts->problem_type == TS_LINEAR || (ts->rhsjacobian.Xid == Uid && ts->rhsjacobian.Xstate == Ustate)) && rhsfunction != TSComputeRHSFunctionLinear)) &&
9569371c9d4SSatish Balay           ts->rhsjacobian.scale == -1.) {                      /* No need to recompute RHSJacobian */
9579566063dSJacob Faibussowitsch         PetscCall(MatShift(A, shift - ts->rhsjacobian.shift)); /* revert the old shift and add the new shift with a single call to MatShift */
9581e66621cSBarry Smith         if (A != B) PetscCall(MatShift(B, shift - ts->rhsjacobian.shift));
959e8b1e424SHong Zhang       } else {
9603565c898SBarry Smith         PetscBool flg;
961e8b1e424SHong Zhang 
962e8b1e424SHong Zhang         if (ts->rhsjacobian.reuse) { /* Undo the damage */
963e8b1e424SHong Zhang           /* MatScale has a short path for this case.
964e8b1e424SHong Zhang              However, this code path is taken the first time TSComputeRHSJacobian is called
965e8b1e424SHong Zhang              and the matrices have not been assembled yet */
9669566063dSJacob Faibussowitsch           PetscCall(TSRecoverRHSJacobian(ts, A, B));
967e8b1e424SHong Zhang         }
9689566063dSJacob Faibussowitsch         PetscCall(TSComputeRHSJacobian(ts, t, U, A, B));
9699566063dSJacob Faibussowitsch         PetscCall(SNESGetUseMatrixFree(ts->snes, NULL, &flg));
9703565c898SBarry Smith         /* since -snes_mf_operator uses the full SNES function it does not need to be shifted or scaled here */
9713565c898SBarry Smith         if (!flg) {
9729566063dSJacob Faibussowitsch           PetscCall(MatScale(A, -1));
9739566063dSJacob Faibussowitsch           PetscCall(MatShift(A, shift));
9743565c898SBarry Smith         }
97594ab13aaSBarry Smith         if (A != B) {
9769566063dSJacob Faibussowitsch           PetscCall(MatScale(B, -1));
9779566063dSJacob Faibussowitsch           PetscCall(MatShift(B, shift));
978316643e7SJed Brown         }
979e8b1e424SHong Zhang       }
980e8b1e424SHong Zhang       ts->rhsjacobian.scale = -1;
981e8b1e424SHong Zhang       ts->rhsjacobian.shift = shift;
982d60b7d5cSBarry Smith     } else if (Arhs) {  /* Both IJacobian and RHSJacobian */
983e1244c69SJed Brown       if (!ijacobian) { /* No IJacobian provided, but we have a separate RHS matrix */
9849566063dSJacob Faibussowitsch         PetscCall(MatZeroEntries(A));
9859566063dSJacob Faibussowitsch         PetscCall(MatShift(A, shift));
98694ab13aaSBarry Smith         if (A != B) {
9879566063dSJacob Faibussowitsch           PetscCall(MatZeroEntries(B));
9889566063dSJacob Faibussowitsch           PetscCall(MatShift(B, shift));
989214bc6a2SJed Brown         }
990316643e7SJed Brown       }
9919566063dSJacob Faibussowitsch       PetscCall(TSComputeRHSJacobian(ts, t, U, Arhs, Brhs));
9929566063dSJacob Faibussowitsch       PetscCall(MatAXPY(A, -1, Arhs, ts->axpy_pattern));
9931e66621cSBarry Smith       if (A != B) PetscCall(MatAXPY(B, -1, Brhs, ts->axpy_pattern));
994316643e7SJed Brown     }
995316643e7SJed Brown   }
996da023ba9SStefano Zampini   PetscCall(PetscLogEventEnd(TS_JacobianEval, U, ts, A, B));
9973ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
998316643e7SJed Brown }
999316643e7SJed Brown 
1000d763cef2SBarry Smith /*@C
1001d763cef2SBarry Smith   TSSetRHSFunction - Sets the routine for evaluating the function,
1002b5abc632SBarry Smith   where U_t = G(t,u).
1003d763cef2SBarry Smith 
1004c3339decSBarry Smith   Logically Collective
1005d763cef2SBarry Smith 
1006d763cef2SBarry Smith   Input Parameters:
1007bcf0153eSBarry Smith + ts  - the `TS` context obtained from `TSCreate()`
1008dd8e379bSPierre Jolivet . r   - vector to put the computed right-hand side (or `NULL` to have it created)
1009d763cef2SBarry Smith . f   - routine for evaluating the right-hand-side function
1010195e9b02SBarry Smith - ctx - [optional] user-defined context for private data for the function evaluation routine (may be `NULL`)
1011d763cef2SBarry Smith 
1012d763cef2SBarry Smith   Level: beginner
1013d763cef2SBarry Smith 
1014bcf0153eSBarry Smith   Note:
1015bcf0153eSBarry Smith   You must call this function or `TSSetIFunction()` to define your ODE. You cannot use this function when solving a DAE.
10162bbac0d3SBarry Smith 
10178434afd1SBarry Smith .seealso: [](ch_ts), `TS`, `TSRHSFunctionFn`, `TSSetRHSJacobian()`, `TSSetIJacobian()`, `TSSetIFunction()`
1018d763cef2SBarry Smith @*/
10198434afd1SBarry Smith PetscErrorCode TSSetRHSFunction(TS ts, Vec r, TSRHSFunctionFn *f, void *ctx)
1020d71ae5a4SJacob Faibussowitsch {
1021089b2837SJed Brown   SNES snes;
10220298fd71SBarry Smith   Vec  ralloc = NULL;
102324989b8cSPeter Brune   DM   dm;
1024d763cef2SBarry Smith 
1025089b2837SJed Brown   PetscFunctionBegin;
10260700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
1027ca94891dSJed Brown   if (r) PetscValidHeaderSpecific(r, VEC_CLASSID, 2);
102824989b8cSPeter Brune 
10299566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
10309566063dSJacob Faibussowitsch   PetscCall(DMTSSetRHSFunction(dm, f, ctx));
10319566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts, &snes));
1032e856ceecSJed Brown   if (!r && !ts->dm && ts->vec_sol) {
10339566063dSJacob Faibussowitsch     PetscCall(VecDuplicate(ts->vec_sol, &ralloc));
1034e856ceecSJed Brown     r = ralloc;
1035e856ceecSJed Brown   }
10369566063dSJacob Faibussowitsch   PetscCall(SNESSetFunction(snes, r, SNESTSFormFunction, ts));
10379566063dSJacob Faibussowitsch   PetscCall(VecDestroy(&ralloc));
10383ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1039d763cef2SBarry Smith }
1040d763cef2SBarry Smith 
1041ef20d060SBarry Smith /*@C
1042abd5a294SJed Brown   TSSetSolutionFunction - Provide a function that computes the solution of the ODE or DAE
1043ef20d060SBarry Smith 
1044c3339decSBarry Smith   Logically Collective
1045ef20d060SBarry Smith 
1046ef20d060SBarry Smith   Input Parameters:
1047bcf0153eSBarry Smith + ts  - the `TS` context obtained from `TSCreate()`
1048ef20d060SBarry Smith . f   - routine for evaluating the solution
1049ef20d060SBarry Smith - ctx - [optional] user-defined context for private data for the
1050195e9b02SBarry Smith           function evaluation routine (may be `NULL`)
1051ef20d060SBarry Smith 
1052bcf0153eSBarry Smith   Options Database Keys:
1053bcf0153eSBarry Smith + -ts_monitor_lg_error   - create a graphical monitor of error history, requires user to have provided `TSSetSolutionFunction()`
1054bcf0153eSBarry Smith - -ts_monitor_draw_error - Monitor error graphically, requires user to have provided `TSSetSolutionFunction()`
1055bcf0153eSBarry Smith 
1056bcf0153eSBarry Smith   Level: intermediate
10570ed3bfb6SBarry Smith 
1058abd5a294SJed Brown   Notes:
1059abd5a294SJed Brown   This routine is used for testing accuracy of time integration schemes when you already know the solution.
1060abd5a294SJed Brown   If analytic solutions are not known for your system, consider using the Method of Manufactured Solutions to
1061abd5a294SJed Brown   create closed-form solutions with non-physical forcing terms.
1062abd5a294SJed Brown 
1063bcf0153eSBarry Smith   For low-dimensional problems solved in serial, such as small discrete systems, `TSMonitorLGError()` can be used to monitor the error history.
1064abd5a294SJed Brown 
10658434afd1SBarry Smith .seealso: [](ch_ts), `TS`, `TSSolutionFn`, `TSSetRHSJacobian()`, `TSSetIJacobian()`, `TSComputeSolutionFunction()`, `TSSetForcingFunction()`, `TSSetSolution()`, `TSGetSolution()`, `TSMonitorLGError()`, `TSMonitorDrawError()`
1066ef20d060SBarry Smith @*/
10678434afd1SBarry Smith PetscErrorCode TSSetSolutionFunction(TS ts, TSSolutionFn *f, void *ctx)
1068d71ae5a4SJacob Faibussowitsch {
1069ef20d060SBarry Smith   DM dm;
1070ef20d060SBarry Smith 
1071ef20d060SBarry Smith   PetscFunctionBegin;
1072ef20d060SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
10739566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
10749566063dSJacob Faibussowitsch   PetscCall(DMTSSetSolutionFunction(dm, f, ctx));
10753ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1076ef20d060SBarry Smith }
1077ef20d060SBarry Smith 
10789b7cd975SBarry Smith /*@C
10799b7cd975SBarry Smith   TSSetForcingFunction - Provide a function that computes a forcing term for a ODE or PDE
10809b7cd975SBarry Smith 
1081c3339decSBarry Smith   Logically Collective
10829b7cd975SBarry Smith 
10839b7cd975SBarry Smith   Input Parameters:
1084bcf0153eSBarry Smith + ts   - the `TS` context obtained from `TSCreate()`
1085e162b725SBarry Smith . func - routine for evaluating the forcing function
108614d0ab18SJacob Faibussowitsch - ctx  - [optional] user-defined context for private data for the function evaluation routine
108714d0ab18SJacob Faibussowitsch          (may be `NULL`)
10889b7cd975SBarry Smith 
1089bcf0153eSBarry Smith   Level: intermediate
1090bcf0153eSBarry Smith 
10919b7cd975SBarry Smith   Notes:
10929b7cd975SBarry Smith   This routine is useful for testing accuracy of time integration schemes when using the Method of Manufactured Solutions to
1093e162b725SBarry 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
1094e162b725SBarry Smith   definition of the problem you are solving and hence possibly introducing bugs.
1095e162b725SBarry Smith 
10968847d985SBarry Smith   This replaces the ODE F(u,u_t,t) = 0 the `TS` is solving with F(u,u_t,t) - func(t) = 0
1097e162b725SBarry Smith 
1098e162b725SBarry 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
1099e162b725SBarry Smith   parameters can be passed in the ctx variable.
11009b7cd975SBarry Smith 
1101bcf0153eSBarry Smith   For low-dimensional problems solved in serial, such as small discrete systems, `TSMonitorLGError()` can be used to monitor the error history.
11029b7cd975SBarry Smith 
11038434afd1SBarry Smith .seealso: [](ch_ts), `TS`, `TSForcingFn`, `TSSetRHSJacobian()`, `TSSetIJacobian()`,
110414d0ab18SJacob Faibussowitsch `TSComputeSolutionFunction()`, `TSSetSolutionFunction()`
11059b7cd975SBarry Smith @*/
11068434afd1SBarry Smith PetscErrorCode TSSetForcingFunction(TS ts, TSForcingFn *func, void *ctx)
1107d71ae5a4SJacob Faibussowitsch {
11089b7cd975SBarry Smith   DM dm;
11099b7cd975SBarry Smith 
11109b7cd975SBarry Smith   PetscFunctionBegin;
11119b7cd975SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
11129566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
11139566063dSJacob Faibussowitsch   PetscCall(DMTSSetForcingFunction(dm, func, ctx));
11143ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
11159b7cd975SBarry Smith }
11169b7cd975SBarry Smith 
1117d763cef2SBarry Smith /*@C
1118f7ab8db6SBarry Smith   TSSetRHSJacobian - Sets the function to compute the Jacobian of G,
1119b5abc632SBarry Smith   where U_t = G(U,t), as well as the location to store the matrix.
1120d763cef2SBarry Smith 
1121c3339decSBarry Smith   Logically Collective
1122d763cef2SBarry Smith 
1123d763cef2SBarry Smith   Input Parameters:
1124bcf0153eSBarry Smith + ts   - the `TS` context obtained from `TSCreate()`
1125195e9b02SBarry Smith . Amat - (approximate) location to store Jacobian matrix entries computed by `f`
1126195e9b02SBarry Smith . Pmat - matrix from which preconditioner is to be constructed (usually the same as `Amat`)
1127d763cef2SBarry Smith . f    - the Jacobian evaluation routine
1128195e9b02SBarry Smith - ctx  - [optional] user-defined context for private data for the Jacobian evaluation routine (may be `NULL`)
1129d763cef2SBarry Smith 
1130bcf0153eSBarry Smith   Level: beginner
1131bcf0153eSBarry Smith 
11326cd88445SBarry Smith   Notes:
11336cd88445SBarry Smith   You must set all the diagonal entries of the matrices, if they are zero you must still set them with a zero value
11346cd88445SBarry Smith 
113514d0ab18SJacob Faibussowitsch   The `TS` solver may modify the nonzero structure and the entries of the matrices `Amat` and `Pmat` between the calls to `f()`
1136ca5f011dSBarry Smith   You should not assume the values are the same in the next call to f() as you set them in the previous call.
1137d763cef2SBarry Smith 
11388434afd1SBarry Smith .seealso: [](ch_ts), `TS`, `TSRHSJacobianFn`, `SNESComputeJacobianDefaultColor()`,
11398434afd1SBarry Smith `TSSetRHSFunction()`, `TSRHSJacobianSetReuse()`, `TSSetIJacobian()`, `TSRHSFunctionFn`, `TSIFunctionFn`
1140d763cef2SBarry Smith @*/
11418434afd1SBarry Smith PetscErrorCode TSSetRHSJacobian(TS ts, Mat Amat, Mat Pmat, TSRHSJacobianFn *f, void *ctx)
1142d71ae5a4SJacob Faibussowitsch {
1143089b2837SJed Brown   SNES           snes;
114424989b8cSPeter Brune   DM             dm;
11458434afd1SBarry Smith   TSIJacobianFn *ijacobian;
1146277b19d0SLisandro Dalcin 
1147d763cef2SBarry Smith   PetscFunctionBegin;
11480700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
1149e5d3d808SBarry Smith   if (Amat) PetscValidHeaderSpecific(Amat, MAT_CLASSID, 2);
1150e5d3d808SBarry Smith   if (Pmat) PetscValidHeaderSpecific(Pmat, MAT_CLASSID, 3);
1151e5d3d808SBarry Smith   if (Amat) PetscCheckSameComm(ts, 1, Amat, 2);
1152e5d3d808SBarry Smith   if (Pmat) PetscCheckSameComm(ts, 1, Pmat, 3);
1153d763cef2SBarry Smith 
11549566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
11559566063dSJacob Faibussowitsch   PetscCall(DMTSSetRHSJacobian(dm, f, ctx));
11569566063dSJacob Faibussowitsch   PetscCall(DMTSGetIJacobian(dm, &ijacobian, NULL));
11579566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts, &snes));
11581e66621cSBarry Smith   if (!ijacobian) PetscCall(SNESSetJacobian(snes, Amat, Pmat, SNESTSFormJacobian, ts));
1159e5d3d808SBarry Smith   if (Amat) {
11609566063dSJacob Faibussowitsch     PetscCall(PetscObjectReference((PetscObject)Amat));
11619566063dSJacob Faibussowitsch     PetscCall(MatDestroy(&ts->Arhs));
1162e5d3d808SBarry Smith     ts->Arhs = Amat;
11630e4ef248SJed Brown   }
1164e5d3d808SBarry Smith   if (Pmat) {
11659566063dSJacob Faibussowitsch     PetscCall(PetscObjectReference((PetscObject)Pmat));
11669566063dSJacob Faibussowitsch     PetscCall(MatDestroy(&ts->Brhs));
1167e5d3d808SBarry Smith     ts->Brhs = Pmat;
11680e4ef248SJed Brown   }
11693ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1170d763cef2SBarry Smith }
1171d763cef2SBarry Smith 
1172316643e7SJed Brown /*@C
1173b5abc632SBarry Smith   TSSetIFunction - Set the function to compute F(t,U,U_t) where F() = 0 is the DAE to be solved.
1174316643e7SJed Brown 
1175c3339decSBarry Smith   Logically Collective
1176316643e7SJed Brown 
1177316643e7SJed Brown   Input Parameters:
1178bcf0153eSBarry Smith + ts  - the `TS` context obtained from `TSCreate()`
1179195e9b02SBarry Smith . r   - vector to hold the residual (or `NULL` to have it created internally)
1180316643e7SJed Brown . f   - the function evaluation routine
1181195e9b02SBarry Smith - ctx - user-defined context for private data for the function evaluation routine (may be `NULL`)
1182316643e7SJed Brown 
1183316643e7SJed Brown   Level: beginner
1184316643e7SJed Brown 
1185bcf0153eSBarry Smith   Note:
1186bcf0153eSBarry Smith   The user MUST call either this routine or `TSSetRHSFunction()` to define the ODE.  When solving DAEs you must use this function.
1187bcf0153eSBarry Smith 
11888434afd1SBarry Smith .seealso: [](ch_ts), `TS`, `TSIFunctionFn`, `TSSetRHSJacobian()`, `TSSetRHSFunction()`,
118914d0ab18SJacob Faibussowitsch `TSSetIJacobian()`
1190316643e7SJed Brown @*/
11918434afd1SBarry Smith PetscErrorCode TSSetIFunction(TS ts, Vec r, TSIFunctionFn *f, void *ctx)
1192d71ae5a4SJacob Faibussowitsch {
1193089b2837SJed Brown   SNES snes;
119451699248SLisandro Dalcin   Vec  ralloc = NULL;
119524989b8cSPeter Brune   DM   dm;
1196316643e7SJed Brown 
1197316643e7SJed Brown   PetscFunctionBegin;
11980700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
119951699248SLisandro Dalcin   if (r) PetscValidHeaderSpecific(r, VEC_CLASSID, 2);
120024989b8cSPeter Brune 
12019566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
12029566063dSJacob Faibussowitsch   PetscCall(DMTSSetIFunction(dm, f, ctx));
120324989b8cSPeter Brune 
12049566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts, &snes));
120551699248SLisandro Dalcin   if (!r && !ts->dm && ts->vec_sol) {
12069566063dSJacob Faibussowitsch     PetscCall(VecDuplicate(ts->vec_sol, &ralloc));
120751699248SLisandro Dalcin     r = ralloc;
1208e856ceecSJed Brown   }
12099566063dSJacob Faibussowitsch   PetscCall(SNESSetFunction(snes, r, SNESTSFormFunction, ts));
12109566063dSJacob Faibussowitsch   PetscCall(VecDestroy(&ralloc));
12113ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1212089b2837SJed Brown }
1213089b2837SJed Brown 
1214089b2837SJed Brown /*@C
1215a5b23f4aSJose E. Roman   TSGetIFunction - Returns the vector where the implicit residual is stored and the function/context to compute it.
1216089b2837SJed Brown 
1217089b2837SJed Brown   Not Collective
1218089b2837SJed Brown 
1219089b2837SJed Brown   Input Parameter:
1220bcf0153eSBarry Smith . ts - the `TS` context
1221089b2837SJed Brown 
1222d8d19677SJose E. Roman   Output Parameters:
1223195e9b02SBarry Smith + r    - vector to hold residual (or `NULL`)
1224195e9b02SBarry Smith . func - the function to compute residual (or `NULL`)
1225195e9b02SBarry Smith - ctx  - the function context (or `NULL`)
1226089b2837SJed Brown 
1227089b2837SJed Brown   Level: advanced
1228089b2837SJed Brown 
12291cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetIFunction()`, `SNESGetFunction()`
1230089b2837SJed Brown @*/
12318434afd1SBarry Smith PetscErrorCode TSGetIFunction(TS ts, Vec *r, TSIFunctionFn **func, void **ctx)
1232d71ae5a4SJacob Faibussowitsch {
1233089b2837SJed Brown   SNES snes;
123424989b8cSPeter Brune   DM   dm;
1235089b2837SJed Brown 
1236089b2837SJed Brown   PetscFunctionBegin;
1237089b2837SJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
12389566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts, &snes));
12399566063dSJacob Faibussowitsch   PetscCall(SNESGetFunction(snes, r, NULL, NULL));
12409566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
12419566063dSJacob Faibussowitsch   PetscCall(DMTSGetIFunction(dm, func, ctx));
12423ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1243089b2837SJed Brown }
1244089b2837SJed Brown 
1245089b2837SJed Brown /*@C
1246dd8e379bSPierre Jolivet   TSGetRHSFunction - Returns the vector where the right-hand side is stored and the function/context to compute it.
1247089b2837SJed Brown 
1248089b2837SJed Brown   Not Collective
1249089b2837SJed Brown 
1250089b2837SJed Brown   Input Parameter:
1251bcf0153eSBarry Smith . ts - the `TS` context
1252089b2837SJed Brown 
1253d8d19677SJose E. Roman   Output Parameters:
1254dd8e379bSPierre Jolivet + r    - vector to hold computed right-hand side (or `NULL`)
1255dd8e379bSPierre Jolivet . func - the function to compute right-hand side (or `NULL`)
1256195e9b02SBarry Smith - ctx  - the function context (or `NULL`)
1257089b2837SJed Brown 
1258089b2837SJed Brown   Level: advanced
1259089b2837SJed Brown 
12601cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetRHSFunction()`, `SNESGetFunction()`
1261089b2837SJed Brown @*/
12628434afd1SBarry Smith PetscErrorCode TSGetRHSFunction(TS ts, Vec *r, TSRHSFunctionFn **func, void **ctx)
1263d71ae5a4SJacob Faibussowitsch {
1264089b2837SJed Brown   SNES snes;
126524989b8cSPeter Brune   DM   dm;
1266089b2837SJed Brown 
1267089b2837SJed Brown   PetscFunctionBegin;
1268089b2837SJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
12699566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts, &snes));
12709566063dSJacob Faibussowitsch   PetscCall(SNESGetFunction(snes, r, NULL, NULL));
12719566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
12729566063dSJacob Faibussowitsch   PetscCall(DMTSGetRHSFunction(dm, func, ctx));
12733ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1274316643e7SJed Brown }
1275316643e7SJed Brown 
1276316643e7SJed Brown /*@C
1277a4f0a591SBarry Smith   TSSetIJacobian - Set the function to compute the matrix dF/dU + a*dF/dU_t where F(t,U,U_t) is the function
1278bcf0153eSBarry Smith   provided with `TSSetIFunction()`.
1279316643e7SJed Brown 
1280c3339decSBarry Smith   Logically Collective
1281316643e7SJed Brown 
1282316643e7SJed Brown   Input Parameters:
1283bcf0153eSBarry Smith + ts   - the `TS` context obtained from `TSCreate()`
1284aaa8cc7dSPierre Jolivet . Amat - (approximate) matrix to store Jacobian entries computed by `f`
1285195e9b02SBarry Smith . Pmat - matrix used to compute preconditioner (usually the same as `Amat`)
1286316643e7SJed Brown . f    - the Jacobian evaluation routine
1287195e9b02SBarry Smith - ctx  - user-defined context for private data for the Jacobian evaluation routine (may be `NULL`)
1288316643e7SJed Brown 
1289bcf0153eSBarry Smith   Level: beginner
1290316643e7SJed Brown 
1291bcf0153eSBarry Smith   Notes:
1292195e9b02SBarry Smith   The matrices `Amat` and `Pmat` are exactly the matrices that are used by `SNES` for the nonlinear solve.
1293bcf0153eSBarry Smith 
1294bcf0153eSBarry Smith   If you know the operator Amat has a null space you can use `MatSetNullSpace()` and `MatSetTransposeNullSpace()` to supply the null
1295195e9b02SBarry Smith   space to `Amat` and the `KSP` solvers will automatically use that null space as needed during the solution process.
1296895c21f2SBarry Smith 
1297a4f0a591SBarry Smith   The matrix dF/dU + a*dF/dU_t you provide turns out to be
1298b5abc632SBarry Smith   the Jacobian of F(t,U,W+a*U) where F(t,U,U_t) = 0 is the DAE to be solved.
1299a4f0a591SBarry Smith   The time integrator internally approximates U_t by W+a*U where the positive "shift"
1300a4f0a591SBarry Smith   a and vector W depend on the integration method, step size, and past states. For example with
1301a4f0a591SBarry Smith   the backward Euler method a = 1/dt and W = -a*U(previous timestep) so
1302a4f0a591SBarry Smith   W + a*U = a*(U - U(previous timestep)) = (U - U(previous timestep))/dt
1303a4f0a591SBarry Smith 
13046cd88445SBarry Smith   You must set all the diagonal entries of the matrices, if they are zero you must still set them with a zero value
13056cd88445SBarry Smith 
1306195e9b02SBarry Smith   The TS solver may modify the nonzero structure and the entries of the matrices `Amat` and `Pmat` between the calls to `f`
1307195e9b02SBarry Smith   You should not assume the values are the same in the next call to `f` as you set them in the previous call.
1308ca5f011dSBarry Smith 
1309bc7fdbb5SPierre Jolivet   In case `TSSetRHSJacobian()` is also used in conjunction with a fully-implicit solver,
1310d469ad21SStefano Zampini   multilevel linear solvers, e.g. `PCMG`, will likely not work due to the way `TS` handles rhs matrices.
1311d469ad21SStefano Zampini 
13128434afd1SBarry Smith .seealso: [](ch_ts), `TS`, `TSIJacobianFn`, `TSSetIFunction()`, `TSSetRHSJacobian()`,
131314d0ab18SJacob Faibussowitsch `SNESComputeJacobianDefaultColor()`, `SNESComputeJacobianDefault()`, `TSSetRHSFunction()`
1314316643e7SJed Brown @*/
13158434afd1SBarry Smith PetscErrorCode TSSetIJacobian(TS ts, Mat Amat, Mat Pmat, TSIJacobianFn *f, void *ctx)
1316d71ae5a4SJacob Faibussowitsch {
1317089b2837SJed Brown   SNES snes;
131824989b8cSPeter Brune   DM   dm;
1319316643e7SJed Brown 
1320316643e7SJed Brown   PetscFunctionBegin;
13210700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
1322e5d3d808SBarry Smith   if (Amat) PetscValidHeaderSpecific(Amat, MAT_CLASSID, 2);
1323e5d3d808SBarry Smith   if (Pmat) PetscValidHeaderSpecific(Pmat, MAT_CLASSID, 3);
1324e5d3d808SBarry Smith   if (Amat) PetscCheckSameComm(ts, 1, Amat, 2);
1325e5d3d808SBarry Smith   if (Pmat) PetscCheckSameComm(ts, 1, Pmat, 3);
132624989b8cSPeter Brune 
13279566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
13289566063dSJacob Faibussowitsch   PetscCall(DMTSSetIJacobian(dm, f, ctx));
132924989b8cSPeter Brune 
13309566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts, &snes));
13319566063dSJacob Faibussowitsch   PetscCall(SNESSetJacobian(snes, Amat, Pmat, SNESTSFormJacobian, ts));
13323ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1333316643e7SJed Brown }
1334316643e7SJed Brown 
1335e1244c69SJed Brown /*@
13368434afd1SBarry Smith   TSRHSJacobianSetReuse - restore the RHS Jacobian before calling the user-provided `TSRHSJacobianFn` function again
1337e1244c69SJed Brown 
1338e1244c69SJed Brown   Logically Collective
1339e1244c69SJed Brown 
13404165533cSJose E. Roman   Input Parameters:
1341bcf0153eSBarry Smith + ts    - `TS` context obtained from `TSCreate()`
1342bcf0153eSBarry Smith - reuse - `PETSC_TRUE` if the RHS Jacobian
1343e1244c69SJed Brown 
1344e1244c69SJed Brown   Level: intermediate
1345e1244c69SJed Brown 
134614d0ab18SJacob Faibussowitsch   Notes:
134714d0ab18SJacob Faibussowitsch   Without this flag, `TS` will change the sign and shift the RHS Jacobian for a
134814d0ab18SJacob Faibussowitsch   finite-time-step implicit solve, in which case the user function will need to recompute the
134914d0ab18SJacob Faibussowitsch   entire Jacobian.  The `reuse `flag must be set if the evaluation function assumes that the
135014d0ab18SJacob Faibussowitsch   matrix entries have not been changed by the `TS`.
135114d0ab18SJacob Faibussowitsch 
13521cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetRHSJacobian()`, `TSComputeRHSJacobianConstant()`
1353e1244c69SJed Brown @*/
1354d71ae5a4SJacob Faibussowitsch PetscErrorCode TSRHSJacobianSetReuse(TS ts, PetscBool reuse)
1355d71ae5a4SJacob Faibussowitsch {
1356e1244c69SJed Brown   PetscFunctionBegin;
1357e1244c69SJed Brown   ts->rhsjacobian.reuse = reuse;
13583ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1359e1244c69SJed Brown }
1360e1244c69SJed Brown 
1361efe9872eSLisandro Dalcin /*@C
1362efe9872eSLisandro Dalcin   TSSetI2Function - Set the function to compute F(t,U,U_t,U_tt) where F = 0 is the DAE to be solved.
1363efe9872eSLisandro Dalcin 
1364c3339decSBarry Smith   Logically Collective
1365efe9872eSLisandro Dalcin 
1366efe9872eSLisandro Dalcin   Input Parameters:
1367bcf0153eSBarry Smith + ts  - the `TS` context obtained from `TSCreate()`
1368195e9b02SBarry Smith . F   - vector to hold the residual (or `NULL` to have it created internally)
1369efe9872eSLisandro Dalcin . fun - the function evaluation routine
1370195e9b02SBarry Smith - ctx - user-defined context for private data for the function evaluation routine (may be `NULL`)
1371efe9872eSLisandro Dalcin 
1372efe9872eSLisandro Dalcin   Level: beginner
1373efe9872eSLisandro Dalcin 
13748434afd1SBarry Smith .seealso: [](ch_ts), `TS`, `TSI2FunctionFn`, `TSSetI2Jacobian()`, `TSSetIFunction()`,
137514d0ab18SJacob Faibussowitsch `TSCreate()`, `TSSetRHSFunction()`
1376efe9872eSLisandro Dalcin @*/
13778434afd1SBarry Smith PetscErrorCode TSSetI2Function(TS ts, Vec F, TSI2FunctionFn *fun, void *ctx)
1378d71ae5a4SJacob Faibussowitsch {
1379efe9872eSLisandro Dalcin   DM dm;
1380efe9872eSLisandro Dalcin 
1381efe9872eSLisandro Dalcin   PetscFunctionBegin;
1382efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
1383efe9872eSLisandro Dalcin   if (F) PetscValidHeaderSpecific(F, VEC_CLASSID, 2);
13849566063dSJacob Faibussowitsch   PetscCall(TSSetIFunction(ts, F, NULL, NULL));
13859566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
13869566063dSJacob Faibussowitsch   PetscCall(DMTSSetI2Function(dm, fun, ctx));
13873ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1388efe9872eSLisandro Dalcin }
1389efe9872eSLisandro Dalcin 
1390efe9872eSLisandro Dalcin /*@C
1391a5b23f4aSJose E. Roman   TSGetI2Function - Returns the vector where the implicit residual is stored and the function/context to compute it.
1392efe9872eSLisandro Dalcin 
1393efe9872eSLisandro Dalcin   Not Collective
1394efe9872eSLisandro Dalcin 
1395efe9872eSLisandro Dalcin   Input Parameter:
1396bcf0153eSBarry Smith . ts - the `TS` context
1397efe9872eSLisandro Dalcin 
1398d8d19677SJose E. Roman   Output Parameters:
1399195e9b02SBarry Smith + r   - vector to hold residual (or `NULL`)
1400195e9b02SBarry Smith . fun - the function to compute residual (or `NULL`)
1401195e9b02SBarry Smith - ctx - the function context (or `NULL`)
1402efe9872eSLisandro Dalcin 
1403efe9872eSLisandro Dalcin   Level: advanced
1404efe9872eSLisandro Dalcin 
14051cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetIFunction()`, `SNESGetFunction()`, `TSCreate()`
1406efe9872eSLisandro Dalcin @*/
14078434afd1SBarry Smith PetscErrorCode TSGetI2Function(TS ts, Vec *r, TSI2FunctionFn **fun, void **ctx)
1408d71ae5a4SJacob Faibussowitsch {
1409efe9872eSLisandro Dalcin   SNES snes;
1410efe9872eSLisandro Dalcin   DM   dm;
1411efe9872eSLisandro Dalcin 
1412efe9872eSLisandro Dalcin   PetscFunctionBegin;
1413efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
14149566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts, &snes));
14159566063dSJacob Faibussowitsch   PetscCall(SNESGetFunction(snes, r, NULL, NULL));
14169566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
14179566063dSJacob Faibussowitsch   PetscCall(DMTSGetI2Function(dm, fun, ctx));
14183ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1419efe9872eSLisandro Dalcin }
1420efe9872eSLisandro Dalcin 
1421efe9872eSLisandro Dalcin /*@C
1422bc77d74cSLisandro Dalcin   TSSetI2Jacobian - Set the function to compute the matrix dF/dU + v*dF/dU_t  + a*dF/dU_tt
1423bcf0153eSBarry Smith   where F(t,U,U_t,U_tt) is the function you provided with `TSSetI2Function()`.
1424efe9872eSLisandro Dalcin 
1425c3339decSBarry Smith   Logically Collective
1426efe9872eSLisandro Dalcin 
1427efe9872eSLisandro Dalcin   Input Parameters:
1428bcf0153eSBarry Smith + ts  - the `TS` context obtained from `TSCreate()`
1429195e9b02SBarry Smith . J   - matrix to hold the Jacobian values
1430195e9b02SBarry Smith . P   - matrix for constructing the preconditioner (may be same as `J`)
14318434afd1SBarry Smith . jac - the Jacobian evaluation routine, see `TSI2JacobianFn` for the calling sequence
1432195e9b02SBarry Smith - ctx - user-defined context for private data for the Jacobian evaluation routine (may be `NULL`)
1433efe9872eSLisandro Dalcin 
1434bcf0153eSBarry Smith   Level: beginner
1435bcf0153eSBarry Smith 
1436efe9872eSLisandro Dalcin   Notes:
1437195e9b02SBarry Smith   The matrices `J` and `P` are exactly the matrices that are used by `SNES` for the nonlinear solve.
1438efe9872eSLisandro Dalcin 
1439efe9872eSLisandro Dalcin   The matrix dF/dU + v*dF/dU_t + a*dF/dU_tt you provide turns out to be
1440efe9872eSLisandro 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.
1441efe9872eSLisandro Dalcin   The time integrator internally approximates U_t by W+v*U and U_tt by W'+a*U  where the positive "shift"
1442bc77d74cSLisandro Dalcin   parameters 'v' and 'a' and vectors W, W' depend on the integration method, step size, and past states.
1443efe9872eSLisandro Dalcin 
14448434afd1SBarry Smith .seealso: [](ch_ts), `TS`, `TSI2JacobianFn`, `TSSetI2Function()`, `TSGetI2Jacobian()`
1445efe9872eSLisandro Dalcin @*/
14468434afd1SBarry Smith PetscErrorCode TSSetI2Jacobian(TS ts, Mat J, Mat P, TSI2JacobianFn *jac, void *ctx)
1447d71ae5a4SJacob Faibussowitsch {
1448efe9872eSLisandro Dalcin   DM dm;
1449efe9872eSLisandro Dalcin 
1450efe9872eSLisandro Dalcin   PetscFunctionBegin;
1451efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
1452efe9872eSLisandro Dalcin   if (J) PetscValidHeaderSpecific(J, MAT_CLASSID, 2);
1453efe9872eSLisandro Dalcin   if (P) PetscValidHeaderSpecific(P, MAT_CLASSID, 3);
14549566063dSJacob Faibussowitsch   PetscCall(TSSetIJacobian(ts, J, P, NULL, NULL));
14559566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
14569566063dSJacob Faibussowitsch   PetscCall(DMTSSetI2Jacobian(dm, jac, ctx));
14573ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1458efe9872eSLisandro Dalcin }
1459efe9872eSLisandro Dalcin 
1460efe9872eSLisandro Dalcin /*@C
1461efe9872eSLisandro Dalcin   TSGetI2Jacobian - Returns the implicit Jacobian at the present timestep.
1462efe9872eSLisandro Dalcin 
1463bcf0153eSBarry Smith   Not Collective, but parallel objects are returned if `TS` is parallel
1464efe9872eSLisandro Dalcin 
1465efe9872eSLisandro Dalcin   Input Parameter:
1466bcf0153eSBarry Smith . ts - The `TS` context obtained from `TSCreate()`
1467efe9872eSLisandro Dalcin 
1468efe9872eSLisandro Dalcin   Output Parameters:
1469efe9872eSLisandro Dalcin + J   - The (approximate) Jacobian of F(t,U,U_t,U_tt)
1470195e9b02SBarry Smith . P   - The matrix from which the preconditioner is constructed, often the same as `J`
1471efe9872eSLisandro Dalcin . jac - The function to compute the Jacobian matrices
1472efe9872eSLisandro Dalcin - ctx - User-defined context for Jacobian evaluation routine
1473efe9872eSLisandro Dalcin 
1474bcf0153eSBarry Smith   Level: advanced
1475bcf0153eSBarry Smith 
1476195e9b02SBarry Smith   Note:
1477195e9b02SBarry Smith   You can pass in `NULL` for any return argument you do not need.
1478efe9872eSLisandro Dalcin 
14791cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSGetTimeStep()`, `TSGetMatrices()`, `TSGetTime()`, `TSGetStepNumber()`, `TSSetI2Jacobian()`, `TSGetI2Function()`, `TSCreate()`
1480efe9872eSLisandro Dalcin @*/
14818434afd1SBarry Smith PetscErrorCode TSGetI2Jacobian(TS ts, Mat *J, Mat *P, TSI2JacobianFn **jac, void **ctx)
1482d71ae5a4SJacob Faibussowitsch {
1483efe9872eSLisandro Dalcin   SNES snes;
1484efe9872eSLisandro Dalcin   DM   dm;
1485efe9872eSLisandro Dalcin 
1486efe9872eSLisandro Dalcin   PetscFunctionBegin;
14879566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts, &snes));
14889566063dSJacob Faibussowitsch   PetscCall(SNESSetUpMatrices(snes));
14899566063dSJacob Faibussowitsch   PetscCall(SNESGetJacobian(snes, J, P, NULL, NULL));
14909566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
14919566063dSJacob Faibussowitsch   PetscCall(DMTSGetI2Jacobian(dm, jac, ctx));
14923ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1493efe9872eSLisandro Dalcin }
1494efe9872eSLisandro Dalcin 
1495efe9872eSLisandro Dalcin /*@
1496efe9872eSLisandro Dalcin   TSComputeI2Function - Evaluates the DAE residual written in implicit form F(t,U,U_t,U_tt) = 0
1497efe9872eSLisandro Dalcin 
1498c3339decSBarry Smith   Collective
1499efe9872eSLisandro Dalcin 
1500efe9872eSLisandro Dalcin   Input Parameters:
1501bcf0153eSBarry Smith + ts - the `TS` context
1502efe9872eSLisandro Dalcin . t  - current time
1503efe9872eSLisandro Dalcin . U  - state vector
1504efe9872eSLisandro Dalcin . V  - time derivative of state vector (U_t)
1505efe9872eSLisandro Dalcin - A  - second time derivative of state vector (U_tt)
1506efe9872eSLisandro Dalcin 
1507efe9872eSLisandro Dalcin   Output Parameter:
1508efe9872eSLisandro Dalcin . F - the residual vector
1509efe9872eSLisandro Dalcin 
1510bcf0153eSBarry Smith   Level: developer
1511bcf0153eSBarry Smith 
1512efe9872eSLisandro Dalcin   Note:
1513efe9872eSLisandro Dalcin   Most users should not need to explicitly call this routine, as it
1514efe9872eSLisandro Dalcin   is used internally within the nonlinear solvers.
1515efe9872eSLisandro Dalcin 
15161cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetI2Function()`, `TSGetI2Function()`
1517efe9872eSLisandro Dalcin @*/
1518d71ae5a4SJacob Faibussowitsch PetscErrorCode TSComputeI2Function(TS ts, PetscReal t, Vec U, Vec V, Vec A, Vec F)
1519d71ae5a4SJacob Faibussowitsch {
1520efe9872eSLisandro Dalcin   DM               dm;
15218434afd1SBarry Smith   TSI2FunctionFn  *I2Function;
1522efe9872eSLisandro Dalcin   void            *ctx;
15238434afd1SBarry Smith   TSRHSFunctionFn *rhsfunction;
1524efe9872eSLisandro Dalcin 
1525efe9872eSLisandro Dalcin   PetscFunctionBegin;
1526efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
1527efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(U, VEC_CLASSID, 3);
1528efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(V, VEC_CLASSID, 4);
1529efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(A, VEC_CLASSID, 5);
1530efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(F, VEC_CLASSID, 6);
1531efe9872eSLisandro Dalcin 
15329566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
15339566063dSJacob Faibussowitsch   PetscCall(DMTSGetI2Function(dm, &I2Function, &ctx));
15349566063dSJacob Faibussowitsch   PetscCall(DMTSGetRHSFunction(dm, &rhsfunction, NULL));
1535efe9872eSLisandro Dalcin 
1536efe9872eSLisandro Dalcin   if (!I2Function) {
15379566063dSJacob Faibussowitsch     PetscCall(TSComputeIFunction(ts, t, U, A, F, PETSC_FALSE));
15383ba16761SJacob Faibussowitsch     PetscFunctionReturn(PETSC_SUCCESS);
1539efe9872eSLisandro Dalcin   }
1540efe9872eSLisandro Dalcin 
1541da023ba9SStefano Zampini   PetscCall(PetscLogEventBegin(TS_FunctionEval, U, ts, V, F));
1542efe9872eSLisandro Dalcin 
1543792fecdfSBarry Smith   PetscCallBack("TS callback implicit function", I2Function(ts, t, U, V, A, F, ctx));
1544efe9872eSLisandro Dalcin 
1545efe9872eSLisandro Dalcin   if (rhsfunction) {
1546efe9872eSLisandro Dalcin     Vec Frhs;
15478af0501fSStefano Zampini 
15488af0501fSStefano Zampini     PetscCall(DMGetGlobalVector(dm, &Frhs));
15499566063dSJacob Faibussowitsch     PetscCall(TSComputeRHSFunction(ts, t, U, Frhs));
15509566063dSJacob Faibussowitsch     PetscCall(VecAXPY(F, -1, Frhs));
15518af0501fSStefano Zampini     PetscCall(DMRestoreGlobalVector(dm, &Frhs));
1552efe9872eSLisandro Dalcin   }
1553efe9872eSLisandro Dalcin 
1554da023ba9SStefano Zampini   PetscCall(PetscLogEventEnd(TS_FunctionEval, U, ts, V, F));
15553ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1556efe9872eSLisandro Dalcin }
1557efe9872eSLisandro Dalcin 
1558efe9872eSLisandro Dalcin /*@
1559efe9872eSLisandro Dalcin   TSComputeI2Jacobian - Evaluates the Jacobian of the DAE
1560efe9872eSLisandro Dalcin 
1561c3339decSBarry Smith   Collective
1562efe9872eSLisandro Dalcin 
1563efe9872eSLisandro Dalcin   Input Parameters:
1564bcf0153eSBarry Smith + ts     - the `TS` context
1565efe9872eSLisandro Dalcin . t      - current timestep
1566efe9872eSLisandro Dalcin . U      - state vector
1567efe9872eSLisandro Dalcin . V      - time derivative of state vector
1568efe9872eSLisandro Dalcin . A      - second time derivative of state vector
1569efe9872eSLisandro Dalcin . shiftV - shift to apply, see note below
1570efe9872eSLisandro Dalcin - shiftA - shift to apply, see note below
1571efe9872eSLisandro Dalcin 
1572efe9872eSLisandro Dalcin   Output Parameters:
1573efe9872eSLisandro Dalcin + J - Jacobian matrix
15747addb90fSBarry Smith - P - optional matrix used to construct the preconditioner
1575efe9872eSLisandro Dalcin 
1576bcf0153eSBarry Smith   Level: developer
1577bcf0153eSBarry Smith 
1578efe9872eSLisandro Dalcin   Notes:
15797addb90fSBarry Smith   If $F(t,U,V,A) = 0$ is the DAE, the required Jacobian is
1580efe9872eSLisandro Dalcin 
15817addb90fSBarry Smith $$
1582efe9872eSLisandro Dalcin   dF/dU + shiftV*dF/dV + shiftA*dF/dA
15837addb90fSBarry Smith $$
1584efe9872eSLisandro Dalcin 
1585efe9872eSLisandro Dalcin   Most users should not need to explicitly call this routine, as it
15867addb90fSBarry Smith   is used internally within the ODE integrators.
1587efe9872eSLisandro Dalcin 
15881cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetI2Jacobian()`
1589efe9872eSLisandro Dalcin @*/
1590d71ae5a4SJacob Faibussowitsch PetscErrorCode TSComputeI2Jacobian(TS ts, PetscReal t, Vec U, Vec V, Vec A, PetscReal shiftV, PetscReal shiftA, Mat J, Mat P)
1591d71ae5a4SJacob Faibussowitsch {
1592efe9872eSLisandro Dalcin   DM               dm;
15938434afd1SBarry Smith   TSI2JacobianFn  *I2Jacobian;
1594efe9872eSLisandro Dalcin   void            *ctx;
15958434afd1SBarry Smith   TSRHSJacobianFn *rhsjacobian;
1596efe9872eSLisandro Dalcin 
1597efe9872eSLisandro Dalcin   PetscFunctionBegin;
1598efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
1599efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(U, VEC_CLASSID, 3);
1600efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(V, VEC_CLASSID, 4);
1601efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(A, VEC_CLASSID, 5);
1602efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(J, MAT_CLASSID, 8);
1603efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(P, MAT_CLASSID, 9);
1604efe9872eSLisandro Dalcin 
16059566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
16069566063dSJacob Faibussowitsch   PetscCall(DMTSGetI2Jacobian(dm, &I2Jacobian, &ctx));
16079566063dSJacob Faibussowitsch   PetscCall(DMTSGetRHSJacobian(dm, &rhsjacobian, NULL));
1608efe9872eSLisandro Dalcin 
1609efe9872eSLisandro Dalcin   if (!I2Jacobian) {
16109566063dSJacob Faibussowitsch     PetscCall(TSComputeIJacobian(ts, t, U, A, shiftA, J, P, PETSC_FALSE));
16113ba16761SJacob Faibussowitsch     PetscFunctionReturn(PETSC_SUCCESS);
1612efe9872eSLisandro Dalcin   }
1613efe9872eSLisandro Dalcin 
1614da023ba9SStefano Zampini   PetscCall(PetscLogEventBegin(TS_JacobianEval, U, ts, J, P));
1615792fecdfSBarry Smith   PetscCallBack("TS callback implicit Jacobian", I2Jacobian(ts, t, U, V, A, shiftV, shiftA, J, P, ctx));
1616efe9872eSLisandro Dalcin   if (rhsjacobian) {
1617d60b7d5cSBarry Smith     Mat Jrhs, Prhs;
16189566063dSJacob Faibussowitsch     PetscCall(TSGetRHSMats_Private(ts, &Jrhs, &Prhs));
16199566063dSJacob Faibussowitsch     PetscCall(TSComputeRHSJacobian(ts, t, U, Jrhs, Prhs));
16209566063dSJacob Faibussowitsch     PetscCall(MatAXPY(J, -1, Jrhs, ts->axpy_pattern));
16219566063dSJacob Faibussowitsch     if (P != J) PetscCall(MatAXPY(P, -1, Prhs, ts->axpy_pattern));
1622efe9872eSLisandro Dalcin   }
1623efe9872eSLisandro Dalcin 
1624da023ba9SStefano Zampini   PetscCall(PetscLogEventEnd(TS_JacobianEval, U, ts, J, P));
16253ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1626efe9872eSLisandro Dalcin }
1627efe9872eSLisandro Dalcin 
1628438f35afSJed Brown /*@C
1629438f35afSJed Brown   TSSetTransientVariable - sets function to transform from state to transient variables
1630438f35afSJed Brown 
1631438f35afSJed Brown   Logically Collective
1632438f35afSJed Brown 
16334165533cSJose E. Roman   Input Parameters:
1634438f35afSJed Brown + ts   - time stepping context on which to change the transient variable
16358434afd1SBarry Smith . tvar - a function that transforms to transient variables, see `TSTransientVariableFn` for the calling sequence
1636438f35afSJed Brown - ctx  - a context for tvar
1637438f35afSJed Brown 
1638438f35afSJed Brown   Level: advanced
1639438f35afSJed Brown 
1640438f35afSJed Brown   Notes:
1641bcf0153eSBarry Smith   This is typically used to transform from primitive to conservative variables so that a time integrator (e.g., `TSBDF`)
1642438f35afSJed Brown   can be conservative.  In this context, primitive variables P are used to model the state (e.g., because they lead to
1643438f35afSJed Brown   well-conditioned formulations even in limiting cases such as low-Mach or zero porosity).  The transient variable is
1644438f35afSJed Brown   C(P), specified by calling this function.  An IFunction thus receives arguments (P, Cdot) and the IJacobian must be
1645438f35afSJed Brown   evaluated via the chain rule, as in
1646195e9b02SBarry Smith .vb
1647438f35afSJed Brown      dF/dP + shift * dF/dCdot dC/dP.
1648195e9b02SBarry Smith .ve
1649438f35afSJed Brown 
16508434afd1SBarry Smith .seealso: [](ch_ts), `TS`, `TSBDF`, `TSTransientVariableFn`, `DMTSSetTransientVariable()`, `DMTSGetTransientVariable()`, `TSSetIFunction()`, `TSSetIJacobian()`
1651438f35afSJed Brown @*/
16528434afd1SBarry Smith PetscErrorCode TSSetTransientVariable(TS ts, TSTransientVariableFn *tvar, void *ctx)
1653d71ae5a4SJacob Faibussowitsch {
1654438f35afSJed Brown   DM dm;
1655438f35afSJed Brown 
1656438f35afSJed Brown   PetscFunctionBegin;
1657438f35afSJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
16589566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
16599566063dSJacob Faibussowitsch   PetscCall(DMTSSetTransientVariable(dm, tvar, ctx));
16603ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1661438f35afSJed Brown }
1662438f35afSJed Brown 
1663efe9872eSLisandro Dalcin /*@
1664e3c11fc1SJed Brown   TSComputeTransientVariable - transforms state (primitive) variables to transient (conservative) variables
1665e3c11fc1SJed Brown 
1666e3c11fc1SJed Brown   Logically Collective
1667e3c11fc1SJed Brown 
1668e3c11fc1SJed Brown   Input Parameters:
1669e3c11fc1SJed Brown + ts - TS on which to compute
1670e3c11fc1SJed Brown - U  - state vector to be transformed to transient variables
1671e3c11fc1SJed Brown 
16722fe279fdSBarry Smith   Output Parameter:
1673e3c11fc1SJed Brown . C - transient (conservative) variable
1674e3c11fc1SJed Brown 
1675e3c11fc1SJed Brown   Level: developer
1676e3c11fc1SJed Brown 
1677b43aa488SJacob Faibussowitsch   Developer Notes:
1678195e9b02SBarry Smith   If `DMTSSetTransientVariable()` has not been called, then C is not modified in this routine and C = `NULL` is allowed.
1679bcf0153eSBarry Smith   This makes it safe to call without a guard.  One can use `TSHasTransientVariable()` to check if transient variables are
1680bcf0153eSBarry Smith   being used.
1681bcf0153eSBarry Smith 
16821cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSBDF`, `DMTSSetTransientVariable()`, `TSComputeIFunction()`, `TSComputeIJacobian()`
1683e3c11fc1SJed Brown @*/
1684d71ae5a4SJacob Faibussowitsch PetscErrorCode TSComputeTransientVariable(TS ts, Vec U, Vec C)
1685d71ae5a4SJacob Faibussowitsch {
1686e3c11fc1SJed Brown   DM   dm;
1687e3c11fc1SJed Brown   DMTS dmts;
1688e3c11fc1SJed Brown 
1689e3c11fc1SJed Brown   PetscFunctionBegin;
1690e3c11fc1SJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
1691e3c11fc1SJed Brown   PetscValidHeaderSpecific(U, VEC_CLASSID, 2);
16929566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
16939566063dSJacob Faibussowitsch   PetscCall(DMGetDMTS(dm, &dmts));
1694e3c11fc1SJed Brown   if (dmts->ops->transientvar) {
1695e3c11fc1SJed Brown     PetscValidHeaderSpecific(C, VEC_CLASSID, 3);
16969566063dSJacob Faibussowitsch     PetscCall((*dmts->ops->transientvar)(ts, U, C, dmts->transientvarctx));
1697e3c11fc1SJed Brown   }
16983ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1699e3c11fc1SJed Brown }
1700e3c11fc1SJed Brown 
1701e3c11fc1SJed Brown /*@
1702e3c11fc1SJed Brown   TSHasTransientVariable - determine whether transient variables have been set
1703e3c11fc1SJed Brown 
1704e3c11fc1SJed Brown   Logically Collective
1705e3c11fc1SJed Brown 
17062fe279fdSBarry Smith   Input Parameter:
1707195e9b02SBarry Smith . ts - `TS` on which to compute
1708e3c11fc1SJed Brown 
17092fe279fdSBarry Smith   Output Parameter:
1710bcf0153eSBarry Smith . has - `PETSC_TRUE` if transient variables have been set
1711e3c11fc1SJed Brown 
1712e3c11fc1SJed Brown   Level: developer
1713e3c11fc1SJed Brown 
17141cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSBDF`, `DMTSSetTransientVariable()`, `TSComputeTransientVariable()`
1715e3c11fc1SJed Brown @*/
1716d71ae5a4SJacob Faibussowitsch PetscErrorCode TSHasTransientVariable(TS ts, PetscBool *has)
1717d71ae5a4SJacob Faibussowitsch {
1718e3c11fc1SJed Brown   DM   dm;
1719e3c11fc1SJed Brown   DMTS dmts;
1720e3c11fc1SJed Brown 
1721e3c11fc1SJed Brown   PetscFunctionBegin;
1722e3c11fc1SJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
17239566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
17249566063dSJacob Faibussowitsch   PetscCall(DMGetDMTS(dm, &dmts));
1725e3c11fc1SJed Brown   *has = dmts->ops->transientvar ? PETSC_TRUE : PETSC_FALSE;
17263ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1727e3c11fc1SJed Brown }
1728e3c11fc1SJed Brown 
1729e3c11fc1SJed Brown /*@
1730efe9872eSLisandro Dalcin   TS2SetSolution - Sets the initial solution and time derivative vectors
1731bcf0153eSBarry Smith   for use by the `TS` routines handling second order equations.
1732efe9872eSLisandro Dalcin 
1733c3339decSBarry Smith   Logically Collective
1734efe9872eSLisandro Dalcin 
1735efe9872eSLisandro Dalcin   Input Parameters:
1736bcf0153eSBarry Smith + ts - the `TS` context obtained from `TSCreate()`
1737efe9872eSLisandro Dalcin . u  - the solution vector
1738efe9872eSLisandro Dalcin - v  - the time derivative vector
1739efe9872eSLisandro Dalcin 
1740efe9872eSLisandro Dalcin   Level: beginner
1741efe9872eSLisandro Dalcin 
17421cc06b55SBarry Smith .seealso: [](ch_ts), `TS`
1743efe9872eSLisandro Dalcin @*/
1744d71ae5a4SJacob Faibussowitsch PetscErrorCode TS2SetSolution(TS ts, Vec u, Vec v)
1745d71ae5a4SJacob Faibussowitsch {
1746efe9872eSLisandro Dalcin   PetscFunctionBegin;
1747efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
1748efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(u, VEC_CLASSID, 2);
1749efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(v, VEC_CLASSID, 3);
17509566063dSJacob Faibussowitsch   PetscCall(TSSetSolution(ts, u));
17519566063dSJacob Faibussowitsch   PetscCall(PetscObjectReference((PetscObject)v));
17529566063dSJacob Faibussowitsch   PetscCall(VecDestroy(&ts->vec_dot));
1753efe9872eSLisandro Dalcin   ts->vec_dot = v;
17543ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1755efe9872eSLisandro Dalcin }
1756efe9872eSLisandro Dalcin 
1757efe9872eSLisandro Dalcin /*@
1758efe9872eSLisandro Dalcin   TS2GetSolution - Returns the solution and time derivative at the present timestep
175914d0ab18SJacob Faibussowitsch   for second order equations.
1760efe9872eSLisandro Dalcin 
176114d0ab18SJacob Faibussowitsch   Not Collective
1762efe9872eSLisandro Dalcin 
1763efe9872eSLisandro Dalcin   Input Parameter:
1764bcf0153eSBarry Smith . ts - the `TS` context obtained from `TSCreate()`
1765efe9872eSLisandro Dalcin 
1766d8d19677SJose E. Roman   Output Parameters:
1767efe9872eSLisandro Dalcin + u - the vector containing the solution
1768efe9872eSLisandro Dalcin - v - the vector containing the time derivative
1769efe9872eSLisandro Dalcin 
1770efe9872eSLisandro Dalcin   Level: intermediate
1771efe9872eSLisandro Dalcin 
177214d0ab18SJacob Faibussowitsch   Notes:
177314d0ab18SJacob Faibussowitsch   It is valid to call this routine inside the function
177414d0ab18SJacob Faibussowitsch   that you are evaluating in order to move to the new timestep. This vector not
177514d0ab18SJacob Faibussowitsch   changed until the solution at the next timestep has been calculated.
177614d0ab18SJacob Faibussowitsch 
17771cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TS2SetSolution()`, `TSGetTimeStep()`, `TSGetTime()`
1778efe9872eSLisandro Dalcin @*/
1779d71ae5a4SJacob Faibussowitsch PetscErrorCode TS2GetSolution(TS ts, Vec *u, Vec *v)
1780d71ae5a4SJacob Faibussowitsch {
1781efe9872eSLisandro Dalcin   PetscFunctionBegin;
1782efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
17834f572ea9SToby Isaac   if (u) PetscAssertPointer(u, 2);
17844f572ea9SToby Isaac   if (v) PetscAssertPointer(v, 3);
1785efe9872eSLisandro Dalcin   if (u) *u = ts->vec_sol;
1786efe9872eSLisandro Dalcin   if (v) *v = ts->vec_dot;
17873ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1788efe9872eSLisandro Dalcin }
1789efe9872eSLisandro Dalcin 
1790ffeef943SBarry Smith /*@
1791bcf0153eSBarry Smith   TSLoad - Loads a `TS` that has been stored in binary  with `TSView()`.
179255849f57SBarry Smith 
1793c3339decSBarry Smith   Collective
179455849f57SBarry Smith 
179555849f57SBarry Smith   Input Parameters:
1796b43aa488SJacob Faibussowitsch + ts     - the newly loaded `TS`, this needs to have been created with `TSCreate()` or
1797bcf0153eSBarry Smith            some related function before a call to `TSLoad()`.
1798bcf0153eSBarry Smith - viewer - binary file viewer, obtained from `PetscViewerBinaryOpen()`
179955849f57SBarry Smith 
180055849f57SBarry Smith   Level: intermediate
180155849f57SBarry Smith 
1802bcf0153eSBarry Smith   Note:
1803bcf0153eSBarry Smith   The type is determined by the data in the file, any type set into the `TS` before this call is ignored.
180455849f57SBarry Smith 
18051cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `PetscViewer`, `PetscViewerBinaryOpen()`, `TSView()`, `MatLoad()`, `VecLoad()`
180655849f57SBarry Smith @*/
1807d71ae5a4SJacob Faibussowitsch PetscErrorCode TSLoad(TS ts, PetscViewer viewer)
1808d71ae5a4SJacob Faibussowitsch {
180955849f57SBarry Smith   PetscBool isbinary;
181055849f57SBarry Smith   PetscInt  classid;
181155849f57SBarry Smith   char      type[256];
18122d53ad75SBarry Smith   DMTS      sdm;
1813ad6bc421SBarry Smith   DM        dm;
181455849f57SBarry Smith 
181555849f57SBarry Smith   PetscFunctionBegin;
1816f2c2a1b9SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
181755849f57SBarry Smith   PetscValidHeaderSpecific(viewer, PETSC_VIEWER_CLASSID, 2);
18189566063dSJacob Faibussowitsch   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERBINARY, &isbinary));
18193c633725SBarry Smith   PetscCheck(isbinary, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Invalid viewer; open viewer with PetscViewerBinaryOpen()");
182055849f57SBarry Smith 
18219566063dSJacob Faibussowitsch   PetscCall(PetscViewerBinaryRead(viewer, &classid, 1, NULL, PETSC_INT));
18223c633725SBarry Smith   PetscCheck(classid == TS_FILE_CLASSID, PetscObjectComm((PetscObject)ts), PETSC_ERR_ARG_WRONG, "Not TS next in file");
18239566063dSJacob Faibussowitsch   PetscCall(PetscViewerBinaryRead(viewer, type, 256, NULL, PETSC_CHAR));
18249566063dSJacob Faibussowitsch   PetscCall(TSSetType(ts, type));
1825dbbe0bcdSBarry Smith   PetscTryTypeMethod(ts, load, viewer);
18269566063dSJacob Faibussowitsch   PetscCall(DMCreate(PetscObjectComm((PetscObject)ts), &dm));
18279566063dSJacob Faibussowitsch   PetscCall(DMLoad(dm, viewer));
18289566063dSJacob Faibussowitsch   PetscCall(TSSetDM(ts, dm));
18299566063dSJacob Faibussowitsch   PetscCall(DMCreateGlobalVector(ts->dm, &ts->vec_sol));
18309566063dSJacob Faibussowitsch   PetscCall(VecLoad(ts->vec_sol, viewer));
18319566063dSJacob Faibussowitsch   PetscCall(DMGetDMTS(ts->dm, &sdm));
18329566063dSJacob Faibussowitsch   PetscCall(DMTSLoad(sdm, viewer));
18333ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
183455849f57SBarry Smith }
183555849f57SBarry Smith 
18369804daf3SBarry Smith #include <petscdraw.h>
1837e04113cfSBarry Smith #if defined(PETSC_HAVE_SAWS)
1838e04113cfSBarry Smith   #include <petscviewersaws.h>
1839f05ece33SBarry Smith #endif
1840fe2efc57SMark 
1841ffeef943SBarry Smith /*@
1842bcf0153eSBarry Smith   TSViewFromOptions - View a `TS` based on values in the options database
1843fe2efc57SMark 
1844c3339decSBarry Smith   Collective
1845fe2efc57SMark 
1846fe2efc57SMark   Input Parameters:
1847bcf0153eSBarry Smith + ts   - the `TS` context
1848bcf0153eSBarry Smith . obj  - Optional object that provides the prefix for the options database keys
1849bcf0153eSBarry Smith - name - command line option string to be passed by user
1850fe2efc57SMark 
1851fe2efc57SMark   Level: intermediate
1852bcf0153eSBarry Smith 
18531cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSView`, `PetscObjectViewFromOptions()`, `TSCreate()`
1854fe2efc57SMark @*/
1855bcf0153eSBarry Smith PetscErrorCode TSViewFromOptions(TS ts, PetscObject obj, const char name[])
1856d71ae5a4SJacob Faibussowitsch {
1857fe2efc57SMark   PetscFunctionBegin;
1858bcf0153eSBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
1859bcf0153eSBarry Smith   PetscCall(PetscObjectViewFromOptions((PetscObject)ts, obj, name));
18603ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1861fe2efc57SMark }
1862fe2efc57SMark 
1863ffeef943SBarry Smith /*@
1864bcf0153eSBarry Smith   TSView - Prints the `TS` data structure.
1865d763cef2SBarry Smith 
1866c3339decSBarry Smith   Collective
1867d763cef2SBarry Smith 
1868d763cef2SBarry Smith   Input Parameters:
1869bcf0153eSBarry Smith + ts     - the `TS` context obtained from `TSCreate()`
1870d763cef2SBarry Smith - viewer - visualization context
1871d763cef2SBarry Smith 
1872d763cef2SBarry Smith   Options Database Key:
1873bcf0153eSBarry Smith . -ts_view - calls `TSView()` at end of `TSStep()`
1874bcf0153eSBarry Smith 
1875bcf0153eSBarry Smith   Level: beginner
1876d763cef2SBarry Smith 
1877d763cef2SBarry Smith   Notes:
1878d763cef2SBarry Smith   The available visualization contexts include
1879bcf0153eSBarry Smith +     `PETSC_VIEWER_STDOUT_SELF` - standard output (default)
1880bcf0153eSBarry Smith -     `PETSC_VIEWER_STDOUT_WORLD` - synchronized standard
1881d763cef2SBarry Smith   output where only the first processor opens
1882d763cef2SBarry Smith   the file.  All other processors send their
1883d763cef2SBarry Smith   data to the first processor to print.
1884d763cef2SBarry Smith 
1885d763cef2SBarry Smith   The user can open an alternative visualization context with
1886bcf0153eSBarry Smith   `PetscViewerASCIIOpen()` - output to a specified file.
1887d763cef2SBarry Smith 
1888bcf0153eSBarry Smith   In the debugger you can do call `TSView`(ts,0) to display the `TS` solver. (The same holds for any PETSc object viewer).
1889595c91d4SBarry Smith 
18901cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `PetscViewer`, `PetscViewerASCIIOpen()`
1891d763cef2SBarry Smith @*/
1892d71ae5a4SJacob Faibussowitsch PetscErrorCode TSView(TS ts, PetscViewer viewer)
1893d71ae5a4SJacob Faibussowitsch {
189419fd82e9SBarry Smith   TSType    type;
18959f196a02SMartin Diehl   PetscBool isascii, isstring, issundials, isbinary, isdraw;
18962d53ad75SBarry Smith   DMTS      sdm;
1897e04113cfSBarry Smith #if defined(PETSC_HAVE_SAWS)
1898536b137fSBarry Smith   PetscBool issaws;
1899f05ece33SBarry Smith #endif
1900d763cef2SBarry Smith 
1901d763cef2SBarry Smith   PetscFunctionBegin;
19020700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
19031e66621cSBarry Smith   if (!viewer) PetscCall(PetscViewerASCIIGetStdout(PetscObjectComm((PetscObject)ts), &viewer));
19040700a824SBarry Smith   PetscValidHeaderSpecific(viewer, PETSC_VIEWER_CLASSID, 2);
1905c9780b6fSBarry Smith   PetscCheckSameComm(ts, 1, viewer, 2);
1906fd16b177SBarry Smith 
19079f196a02SMartin Diehl   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERASCII, &isascii));
19089566063dSJacob Faibussowitsch   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERSTRING, &isstring));
19099566063dSJacob Faibussowitsch   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERBINARY, &isbinary));
19109566063dSJacob Faibussowitsch   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERDRAW, &isdraw));
1911e04113cfSBarry Smith #if defined(PETSC_HAVE_SAWS)
19129566063dSJacob Faibussowitsch   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERSAWS, &issaws));
1913f05ece33SBarry Smith #endif
19149f196a02SMartin Diehl   if (isascii) {
19159566063dSJacob Faibussowitsch     PetscCall(PetscObjectPrintClassNamePrefixType((PetscObject)ts, viewer));
1916efd4aadfSBarry Smith     if (ts->ops->view) {
19179566063dSJacob Faibussowitsch       PetscCall(PetscViewerASCIIPushTab(viewer));
1918dbbe0bcdSBarry Smith       PetscUseTypeMethod(ts, view, viewer);
19199566063dSJacob Faibussowitsch       PetscCall(PetscViewerASCIIPopTab(viewer));
1920efd4aadfSBarry Smith     }
19211690c2aeSBarry Smith     if (ts->max_steps < PETSC_INT_MAX) PetscCall(PetscViewerASCIIPrintf(viewer, "  maximum steps=%" PetscInt_FMT "\n", ts->max_steps));
19228e562f8dSJames Wright     if (ts->run_steps < PETSC_INT_MAX) PetscCall(PetscViewerASCIIPrintf(viewer, "  run steps=%" PetscInt_FMT "\n", ts->run_steps));
19231e66621cSBarry Smith     if (ts->max_time < PETSC_MAX_REAL) PetscCall(PetscViewerASCIIPrintf(viewer, "  maximum time=%g\n", (double)ts->max_time));
19241e66621cSBarry Smith     if (ts->ifuncs) PetscCall(PetscViewerASCIIPrintf(viewer, "  total number of I function evaluations=%" PetscInt_FMT "\n", ts->ifuncs));
19251e66621cSBarry Smith     if (ts->ijacs) PetscCall(PetscViewerASCIIPrintf(viewer, "  total number of I Jacobian evaluations=%" PetscInt_FMT "\n", ts->ijacs));
19261e66621cSBarry Smith     if (ts->rhsfuncs) PetscCall(PetscViewerASCIIPrintf(viewer, "  total number of RHS function evaluations=%" PetscInt_FMT "\n", ts->rhsfuncs));
19271e66621cSBarry Smith     if (ts->rhsjacs) PetscCall(PetscViewerASCIIPrintf(viewer, "  total number of RHS Jacobian evaluations=%" PetscInt_FMT "\n", ts->rhsjacs));
1928efd4aadfSBarry Smith     if (ts->usessnes) {
1929efd4aadfSBarry Smith       PetscBool lin;
19301e66621cSBarry Smith       if (ts->problem_type == TS_NONLINEAR) PetscCall(PetscViewerASCIIPrintf(viewer, "  total number of nonlinear solver iterations=%" PetscInt_FMT "\n", ts->snes_its));
193163a3b9bcSJacob Faibussowitsch       PetscCall(PetscViewerASCIIPrintf(viewer, "  total number of linear solver iterations=%" PetscInt_FMT "\n", ts->ksp_its));
19329566063dSJacob Faibussowitsch       PetscCall(PetscObjectTypeCompareAny((PetscObject)ts->snes, &lin, SNESKSPONLY, SNESKSPTRANSPOSEONLY, ""));
193363a3b9bcSJacob Faibussowitsch       PetscCall(PetscViewerASCIIPrintf(viewer, "  total number of %slinear solve failures=%" PetscInt_FMT "\n", lin ? "" : "non", ts->num_snes_failures));
1934efd4aadfSBarry Smith     }
193563a3b9bcSJacob Faibussowitsch     PetscCall(PetscViewerASCIIPrintf(viewer, "  total number of rejected steps=%" PetscInt_FMT "\n", ts->reject));
19361e66621cSBarry Smith     if (ts->vrtol) PetscCall(PetscViewerASCIIPrintf(viewer, "  using vector of relative error tolerances, "));
19371e66621cSBarry Smith     else PetscCall(PetscViewerASCIIPrintf(viewer, "  using relative error tolerance of %g, ", (double)ts->rtol));
19381e66621cSBarry Smith     if (ts->vatol) PetscCall(PetscViewerASCIIPrintf(viewer, "  using vector of absolute error tolerances\n"));
19391e66621cSBarry Smith     else PetscCall(PetscViewerASCIIPrintf(viewer, "  using absolute error tolerance of %g\n", (double)ts->atol));
19409566063dSJacob Faibussowitsch     PetscCall(PetscViewerASCIIPushTab(viewer));
19419566063dSJacob Faibussowitsch     PetscCall(TSAdaptView(ts->adapt, viewer));
19429566063dSJacob Faibussowitsch     PetscCall(PetscViewerASCIIPopTab(viewer));
19430f5bd95cSBarry Smith   } else if (isstring) {
19449566063dSJacob Faibussowitsch     PetscCall(TSGetType(ts, &type));
19459566063dSJacob Faibussowitsch     PetscCall(PetscViewerStringSPrintf(viewer, " TSType: %-7.7s", type));
1946dbbe0bcdSBarry Smith     PetscTryTypeMethod(ts, view, viewer);
194755849f57SBarry Smith   } else if (isbinary) {
194855849f57SBarry Smith     PetscInt    classid = TS_FILE_CLASSID;
194955849f57SBarry Smith     MPI_Comm    comm;
195055849f57SBarry Smith     PetscMPIInt rank;
195155849f57SBarry Smith     char        type[256];
195255849f57SBarry Smith 
19539566063dSJacob Faibussowitsch     PetscCall(PetscObjectGetComm((PetscObject)ts, &comm));
19549566063dSJacob Faibussowitsch     PetscCallMPI(MPI_Comm_rank(comm, &rank));
1955dd400576SPatrick Sanan     if (rank == 0) {
19569566063dSJacob Faibussowitsch       PetscCall(PetscViewerBinaryWrite(viewer, &classid, 1, PETSC_INT));
19579566063dSJacob Faibussowitsch       PetscCall(PetscStrncpy(type, ((PetscObject)ts)->type_name, 256));
19589566063dSJacob Faibussowitsch       PetscCall(PetscViewerBinaryWrite(viewer, type, 256, PETSC_CHAR));
195955849f57SBarry Smith     }
1960dbbe0bcdSBarry Smith     PetscTryTypeMethod(ts, view, viewer);
19619566063dSJacob Faibussowitsch     if (ts->adapt) PetscCall(TSAdaptView(ts->adapt, viewer));
19629566063dSJacob Faibussowitsch     PetscCall(DMView(ts->dm, viewer));
19639566063dSJacob Faibussowitsch     PetscCall(VecView(ts->vec_sol, viewer));
19649566063dSJacob Faibussowitsch     PetscCall(DMGetDMTS(ts->dm, &sdm));
19659566063dSJacob Faibussowitsch     PetscCall(DMTSView(sdm, viewer));
19662b0a91c0SBarry Smith   } else if (isdraw) {
19672b0a91c0SBarry Smith     PetscDraw draw;
19682b0a91c0SBarry Smith     char      str[36];
196989fd9fafSBarry Smith     PetscReal x, y, bottom, h;
19702b0a91c0SBarry Smith 
19719566063dSJacob Faibussowitsch     PetscCall(PetscViewerDrawGetDraw(viewer, 0, &draw));
19729566063dSJacob Faibussowitsch     PetscCall(PetscDrawGetCurrentPoint(draw, &x, &y));
1973c6a7a370SJeremy L Thompson     PetscCall(PetscStrncpy(str, "TS: ", sizeof(str)));
1974c6a7a370SJeremy L Thompson     PetscCall(PetscStrlcat(str, ((PetscObject)ts)->type_name, sizeof(str)));
19759566063dSJacob Faibussowitsch     PetscCall(PetscDrawStringBoxed(draw, x, y, PETSC_DRAW_BLACK, PETSC_DRAW_BLACK, str, NULL, &h));
197689fd9fafSBarry Smith     bottom = y - h;
19779566063dSJacob Faibussowitsch     PetscCall(PetscDrawPushCurrentPoint(draw, x, bottom));
1978dbbe0bcdSBarry Smith     PetscTryTypeMethod(ts, view, viewer);
19799566063dSJacob Faibussowitsch     if (ts->adapt) PetscCall(TSAdaptView(ts->adapt, viewer));
19809566063dSJacob Faibussowitsch     if (ts->snes) PetscCall(SNESView(ts->snes, viewer));
19819566063dSJacob Faibussowitsch     PetscCall(PetscDrawPopCurrentPoint(draw));
1982e04113cfSBarry Smith #if defined(PETSC_HAVE_SAWS)
1983536b137fSBarry Smith   } else if (issaws) {
1984d45a07a7SBarry Smith     PetscMPIInt rank;
19852657e9d9SBarry Smith     const char *name;
19862657e9d9SBarry Smith 
19879566063dSJacob Faibussowitsch     PetscCall(PetscObjectGetName((PetscObject)ts, &name));
19889566063dSJacob Faibussowitsch     PetscCallMPI(MPI_Comm_rank(PETSC_COMM_WORLD, &rank));
1989dd400576SPatrick Sanan     if (!((PetscObject)ts)->amsmem && rank == 0) {
1990d45a07a7SBarry Smith       char dir[1024];
1991d45a07a7SBarry Smith 
19929566063dSJacob Faibussowitsch       PetscCall(PetscObjectViewSAWs((PetscObject)ts, viewer));
19939566063dSJacob Faibussowitsch       PetscCall(PetscSNPrintf(dir, 1024, "/PETSc/Objects/%s/time_step", name));
1994792fecdfSBarry Smith       PetscCallSAWs(SAWs_Register, (dir, &ts->steps, 1, SAWs_READ, SAWs_INT));
19959566063dSJacob Faibussowitsch       PetscCall(PetscSNPrintf(dir, 1024, "/PETSc/Objects/%s/time", name));
1996792fecdfSBarry Smith       PetscCallSAWs(SAWs_Register, (dir, &ts->ptime, 1, SAWs_READ, SAWs_DOUBLE));
1997d763cef2SBarry Smith     }
1998dbbe0bcdSBarry Smith     PetscTryTypeMethod(ts, view, viewer);
1999f05ece33SBarry Smith #endif
2000f05ece33SBarry Smith   }
200136a9e3b9SBarry Smith   if (ts->snes && ts->usessnes) {
20029566063dSJacob Faibussowitsch     PetscCall(PetscViewerASCIIPushTab(viewer));
20039566063dSJacob Faibussowitsch     PetscCall(SNESView(ts->snes, viewer));
20049566063dSJacob Faibussowitsch     PetscCall(PetscViewerASCIIPopTab(viewer));
200536a9e3b9SBarry Smith   }
20069566063dSJacob Faibussowitsch   PetscCall(DMGetDMTS(ts->dm, &sdm));
20079566063dSJacob Faibussowitsch   PetscCall(DMTSView(sdm, viewer));
2008f05ece33SBarry Smith 
20099566063dSJacob Faibussowitsch   PetscCall(PetscViewerASCIIPushTab(viewer));
20109f196a02SMartin Diehl   PetscCall(PetscObjectTypeCompare((PetscObject)ts, TSSUNDIALS, &issundials));
20119566063dSJacob Faibussowitsch   PetscCall(PetscViewerASCIIPopTab(viewer));
20123ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2013d763cef2SBarry Smith }
2014d763cef2SBarry Smith 
2015b07ff414SBarry Smith /*@
2016ce78bad3SBarry Smith   TSSetApplicationContext - Sets an optional user-defined context for the timesteppers that may be accessed, for example inside the user provided
2017ce78bad3SBarry Smith   `TS` callbacks with `TSGetApplicationContext()`
2018d763cef2SBarry Smith 
2019c3339decSBarry Smith   Logically Collective
2020d763cef2SBarry Smith 
2021d763cef2SBarry Smith   Input Parameters:
2022bcf0153eSBarry Smith + ts  - the `TS` context obtained from `TSCreate()`
202349abdd8aSBarry Smith - ctx - user context
2024daf670e6SBarry Smith 
2025d763cef2SBarry Smith   Level: intermediate
2026d763cef2SBarry Smith 
2027ce78bad3SBarry Smith   Fortran Note:
2028ce78bad3SBarry Smith   This only works when `ctx` is a Fortran derived type (it cannot be a `PetscObject`), we recommend writing a Fortran interface definition for this
2029ce78bad3SBarry Smith   function that tells the Fortran compiler the derived data type that is passed in as the `ctx` argument. See `TSGetApplicationContext()` for
2030ce78bad3SBarry Smith   an example.
2031bcf0153eSBarry Smith 
20321cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSGetApplicationContext()`
2033d763cef2SBarry Smith @*/
2034ce78bad3SBarry Smith PetscErrorCode TSSetApplicationContext(TS ts, PeCtx ctx)
2035d71ae5a4SJacob Faibussowitsch {
2036d763cef2SBarry Smith   PetscFunctionBegin;
20370700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
203849abdd8aSBarry Smith   ts->ctx = ctx;
20393ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2040d763cef2SBarry Smith }
2041d763cef2SBarry Smith 
2042b07ff414SBarry Smith /*@
2043d763cef2SBarry Smith   TSGetApplicationContext - Gets the user-defined context for the
2044bcf0153eSBarry Smith   timestepper that was set with `TSSetApplicationContext()`
2045d763cef2SBarry Smith 
2046d763cef2SBarry Smith   Not Collective
2047d763cef2SBarry Smith 
2048d763cef2SBarry Smith   Input Parameter:
2049bcf0153eSBarry Smith . ts - the `TS` context obtained from `TSCreate()`
2050d763cef2SBarry Smith 
2051d763cef2SBarry Smith   Output Parameter:
2052ce78bad3SBarry Smith . ctx - a pointer to the user context
2053d763cef2SBarry Smith 
2054bcf0153eSBarry Smith   Level: intermediate
2055bcf0153eSBarry Smith 
2056b43aa488SJacob Faibussowitsch   Fortran Notes:
2057ce78bad3SBarry Smith   This only works when the context is a Fortran derived type (it cannot be a `PetscObject`) and you **must** write a Fortran interface definition for this
2058ce78bad3SBarry Smith   function that tells the Fortran compiler the derived data type that is returned as the `ctx` argument. For example,
2059ce78bad3SBarry Smith .vb
2060ce78bad3SBarry Smith   Interface TSGetApplicationContext
2061ce78bad3SBarry Smith     Subroutine TSGetApplicationContext(ts,ctx,ierr)
2062ce78bad3SBarry Smith   #include <petsc/finclude/petscts.h>
2063ce78bad3SBarry Smith       use petscts
2064ce78bad3SBarry Smith       TS ts
2065ce78bad3SBarry Smith       type(tUsertype), pointer :: ctx
2066ce78bad3SBarry Smith       PetscErrorCode ierr
2067ce78bad3SBarry Smith     End Subroutine
2068ce78bad3SBarry Smith   End Interface TSGetApplicationContext
2069ce78bad3SBarry Smith .ve
2070ce78bad3SBarry Smith 
2071bfe80ac4SPierre Jolivet   The prototype for `ctx` must be
2072ce78bad3SBarry Smith .vb
2073ce78bad3SBarry Smith   type(tUsertype), pointer :: ctx
2074ce78bad3SBarry Smith .ve
2075daf670e6SBarry Smith 
20761cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetApplicationContext()`
2077d763cef2SBarry Smith @*/
207849abdd8aSBarry Smith PetscErrorCode TSGetApplicationContext(TS ts, void *ctx)
2079d71ae5a4SJacob Faibussowitsch {
2080d763cef2SBarry Smith   PetscFunctionBegin;
20810700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
208249abdd8aSBarry Smith   *(void **)ctx = ts->ctx;
20833ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2084d763cef2SBarry Smith }
2085d763cef2SBarry Smith 
2086d763cef2SBarry Smith /*@
2087bcf0153eSBarry Smith   TSGetStepNumber - Gets the number of time steps completed.
2088d763cef2SBarry Smith 
2089d763cef2SBarry Smith   Not Collective
2090d763cef2SBarry Smith 
2091d763cef2SBarry Smith   Input Parameter:
2092bcf0153eSBarry Smith . ts - the `TS` context obtained from `TSCreate()`
2093d763cef2SBarry Smith 
2094d763cef2SBarry Smith   Output Parameter:
209580275a0aSLisandro Dalcin . steps - number of steps completed so far
2096d763cef2SBarry Smith 
2097d763cef2SBarry Smith   Level: intermediate
2098d763cef2SBarry Smith 
20991cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSGetTime()`, `TSGetTimeStep()`, `TSSetPreStep()`, `TSSetPreStage()`, `TSSetPostStage()`, `TSSetPostStep()`
2100d763cef2SBarry Smith @*/
2101d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetStepNumber(TS ts, PetscInt *steps)
2102d71ae5a4SJacob Faibussowitsch {
2103d763cef2SBarry Smith   PetscFunctionBegin;
21040700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
21054f572ea9SToby Isaac   PetscAssertPointer(steps, 2);
210680275a0aSLisandro Dalcin   *steps = ts->steps;
21073ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
210880275a0aSLisandro Dalcin }
210980275a0aSLisandro Dalcin 
211080275a0aSLisandro Dalcin /*@
211180275a0aSLisandro Dalcin   TSSetStepNumber - Sets the number of steps completed.
211280275a0aSLisandro Dalcin 
2113c3339decSBarry Smith   Logically Collective
211480275a0aSLisandro Dalcin 
211580275a0aSLisandro Dalcin   Input Parameters:
2116bcf0153eSBarry Smith + ts    - the `TS` context
211780275a0aSLisandro Dalcin - steps - number of steps completed so far
211880275a0aSLisandro Dalcin 
2119bcf0153eSBarry Smith   Level: developer
2120bcf0153eSBarry Smith 
2121bcf0153eSBarry Smith   Note:
2122bcf0153eSBarry Smith   For most uses of the `TS` solvers the user need not explicitly call
2123bcf0153eSBarry Smith   `TSSetStepNumber()`, as the step counter is appropriately updated in
2124bcf0153eSBarry Smith   `TSSolve()`/`TSStep()`/`TSRollBack()`. Power users may call this routine to
212580275a0aSLisandro Dalcin   reinitialize timestepping by setting the step counter to zero (and time
212680275a0aSLisandro Dalcin   to the initial time) to solve a similar problem with different initial
212780275a0aSLisandro Dalcin   conditions or parameters. Other possible use case is to continue
2128195e9b02SBarry Smith   timestepping from a previously interrupted run in such a way that `TS`
212980275a0aSLisandro Dalcin   monitors will be called with a initial nonzero step counter.
213080275a0aSLisandro Dalcin 
21311cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSGetStepNumber()`, `TSSetTime()`, `TSSetTimeStep()`, `TSSetSolution()`
213280275a0aSLisandro Dalcin @*/
2133d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetStepNumber(TS ts, PetscInt steps)
2134d71ae5a4SJacob Faibussowitsch {
213580275a0aSLisandro Dalcin   PetscFunctionBegin;
213680275a0aSLisandro Dalcin   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
213780275a0aSLisandro Dalcin   PetscValidLogicalCollectiveInt(ts, steps, 2);
21383c633725SBarry Smith   PetscCheck(steps >= 0, PetscObjectComm((PetscObject)ts), PETSC_ERR_ARG_OUTOFRANGE, "Step number must be non-negative");
213980275a0aSLisandro Dalcin   ts->steps = steps;
21403ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2141d763cef2SBarry Smith }
2142d763cef2SBarry Smith 
2143d763cef2SBarry Smith /*@
2144d763cef2SBarry Smith   TSSetTimeStep - Allows one to reset the timestep at any time,
2145d763cef2SBarry Smith   useful for simple pseudo-timestepping codes.
2146d763cef2SBarry Smith 
2147c3339decSBarry Smith   Logically Collective
2148d763cef2SBarry Smith 
2149d763cef2SBarry Smith   Input Parameters:
2150bcf0153eSBarry Smith + ts        - the `TS` context obtained from `TSCreate()`
2151d763cef2SBarry Smith - time_step - the size of the timestep
2152d763cef2SBarry Smith 
2153d763cef2SBarry Smith   Level: intermediate
2154d763cef2SBarry Smith 
21551cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSPSEUDO`, `TSGetTimeStep()`, `TSSetTime()`
2156d763cef2SBarry Smith @*/
2157d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetTimeStep(TS ts, PetscReal time_step)
2158d71ae5a4SJacob Faibussowitsch {
2159d763cef2SBarry Smith   PetscFunctionBegin;
21600700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
2161c5eb9154SBarry Smith   PetscValidLogicalCollectiveReal(ts, time_step, 2);
2162d763cef2SBarry Smith   ts->time_step = time_step;
21633ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2164d763cef2SBarry Smith }
2165d763cef2SBarry Smith 
2166a43b19c4SJed Brown /*@
216749354f04SShri Abhyankar   TSSetExactFinalTime - Determines whether to adapt the final time step to
21680b4b7b1cSBarry Smith   match the exact final time, to interpolate the solution to the exact final time,
21690b4b7b1cSBarry Smith   or to just return at the final time `TS` computed (which may be slightly larger
21700b4b7b1cSBarry Smith   than the requested final time).
2171a43b19c4SJed Brown 
2172c3339decSBarry Smith   Logically Collective
2173a43b19c4SJed Brown 
2174d8d19677SJose E. Roman   Input Parameters:
2175a43b19c4SJed Brown + ts     - the time-step context
217649354f04SShri Abhyankar - eftopt - exact final time option
2177bcf0153eSBarry Smith .vb
21780b4b7b1cSBarry Smith   TS_EXACTFINALTIME_STEPOVER    - Don't do anything if final time is exceeded, just use it
21790b4b7b1cSBarry Smith   TS_EXACTFINALTIME_INTERPOLATE - Interpolate back to final time if the final time is exceeded
21800b4b7b1cSBarry Smith   TS_EXACTFINALTIME_MATCHSTEP   - Adapt final time step to ensure the computed final time exactly equals the requested final time
2181bcf0153eSBarry Smith .ve
2182a43b19c4SJed Brown 
2183bcf0153eSBarry Smith   Options Database Key:
21840b4b7b1cSBarry Smith . -ts_exact_final_time <stepover,interpolate,matchstep> - select the final step approach at runtime
2185feed9e9dSBarry Smith 
2186a43b19c4SJed Brown   Level: beginner
2187a43b19c4SJed Brown 
2188bcf0153eSBarry Smith   Note:
2189bcf0153eSBarry Smith   If you use the option `TS_EXACTFINALTIME_STEPOVER` the solution may be at a very different time
2190bcf0153eSBarry Smith   then the final time you selected.
2191bcf0153eSBarry Smith 
21921cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSExactFinalTimeOption`, `TSGetExactFinalTime()`
2193a43b19c4SJed Brown @*/
2194d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetExactFinalTime(TS ts, TSExactFinalTimeOption eftopt)
2195d71ae5a4SJacob Faibussowitsch {
2196a43b19c4SJed Brown   PetscFunctionBegin;
2197a43b19c4SJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
219849354f04SShri Abhyankar   PetscValidLogicalCollectiveEnum(ts, eftopt, 2);
219949354f04SShri Abhyankar   ts->exact_final_time = eftopt;
22003ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2201a43b19c4SJed Brown }
2202a43b19c4SJed Brown 
2203d763cef2SBarry Smith /*@
2204bcf0153eSBarry Smith   TSGetExactFinalTime - Gets the exact final time option set with `TSSetExactFinalTime()`
2205f6953c82SLisandro Dalcin 
2206f6953c82SLisandro Dalcin   Not Collective
2207f6953c82SLisandro Dalcin 
2208f6953c82SLisandro Dalcin   Input Parameter:
2209bcf0153eSBarry Smith . ts - the `TS` context
2210f6953c82SLisandro Dalcin 
2211f6953c82SLisandro Dalcin   Output Parameter:
2212f6953c82SLisandro Dalcin . eftopt - exact final time option
2213f6953c82SLisandro Dalcin 
2214f6953c82SLisandro Dalcin   Level: beginner
2215f6953c82SLisandro Dalcin 
22161cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSExactFinalTimeOption`, `TSSetExactFinalTime()`
2217f6953c82SLisandro Dalcin @*/
2218d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetExactFinalTime(TS ts, TSExactFinalTimeOption *eftopt)
2219d71ae5a4SJacob Faibussowitsch {
2220f6953c82SLisandro Dalcin   PetscFunctionBegin;
2221f6953c82SLisandro Dalcin   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
22224f572ea9SToby Isaac   PetscAssertPointer(eftopt, 2);
2223f6953c82SLisandro Dalcin   *eftopt = ts->exact_final_time;
22243ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2225f6953c82SLisandro Dalcin }
2226f6953c82SLisandro Dalcin 
2227f6953c82SLisandro Dalcin /*@
2228d763cef2SBarry Smith   TSGetTimeStep - Gets the current timestep size.
2229d763cef2SBarry Smith 
2230d763cef2SBarry Smith   Not Collective
2231d763cef2SBarry Smith 
2232d763cef2SBarry Smith   Input Parameter:
2233bcf0153eSBarry Smith . ts - the `TS` context obtained from `TSCreate()`
2234d763cef2SBarry Smith 
2235d763cef2SBarry Smith   Output Parameter:
2236d763cef2SBarry Smith . dt - the current timestep size
2237d763cef2SBarry Smith 
2238d763cef2SBarry Smith   Level: intermediate
2239d763cef2SBarry Smith 
22401cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetTimeStep()`, `TSGetTime()`
2241d763cef2SBarry Smith @*/
2242d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetTimeStep(TS ts, PetscReal *dt)
2243d71ae5a4SJacob Faibussowitsch {
2244d763cef2SBarry Smith   PetscFunctionBegin;
22450700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
22464f572ea9SToby Isaac   PetscAssertPointer(dt, 2);
2247d763cef2SBarry Smith   *dt = ts->time_step;
22483ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2249d763cef2SBarry Smith }
2250d763cef2SBarry Smith 
2251d8e5e3e6SSatish Balay /*@
2252d763cef2SBarry Smith   TSGetSolution - Returns the solution at the present timestep. It
2253d763cef2SBarry Smith   is valid to call this routine inside the function that you are evaluating
2254d763cef2SBarry Smith   in order to move to the new timestep. This vector not changed until
2255d763cef2SBarry Smith   the solution at the next timestep has been calculated.
2256d763cef2SBarry Smith 
2257bcf0153eSBarry Smith   Not Collective, but v returned is parallel if ts is parallel
2258d763cef2SBarry Smith 
2259d763cef2SBarry Smith   Input Parameter:
2260bcf0153eSBarry Smith . ts - the `TS` context obtained from `TSCreate()`
2261d763cef2SBarry Smith 
2262d763cef2SBarry Smith   Output Parameter:
2263d763cef2SBarry Smith . v - the vector containing the solution
2264d763cef2SBarry Smith 
2265d763cef2SBarry Smith   Level: intermediate
2266d763cef2SBarry Smith 
2267bcf0153eSBarry Smith   Note:
2268bcf0153eSBarry Smith   If you used `TSSetExactFinalTime`(ts,`TS_EXACTFINALTIME_MATCHSTEP`); this does not return the solution at the requested
2269bcf0153eSBarry Smith   final time. It returns the solution at the next timestep.
2270d763cef2SBarry Smith 
22711cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSGetTimeStep()`, `TSGetTime()`, `TSGetSolveTime()`, `TSGetSolutionComponents()`, `TSSetSolutionFunction()`
2272d763cef2SBarry Smith @*/
2273d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetSolution(TS ts, Vec *v)
2274d71ae5a4SJacob Faibussowitsch {
2275d763cef2SBarry Smith   PetscFunctionBegin;
22760700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
22774f572ea9SToby Isaac   PetscAssertPointer(v, 2);
22788737fe31SLisandro Dalcin   *v = ts->vec_sol;
22793ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2280d763cef2SBarry Smith }
2281d763cef2SBarry Smith 
228203fe5f5eSDebojyoti Ghosh /*@
2283b2bf4f3aSDebojyoti Ghosh   TSGetSolutionComponents - Returns any solution components at the present
228403fe5f5eSDebojyoti Ghosh   timestep, if available for the time integration method being used.
2285b2bf4f3aSDebojyoti Ghosh   Solution components are quantities that share the same size and
228603fe5f5eSDebojyoti Ghosh   structure as the solution vector.
228703fe5f5eSDebojyoti Ghosh 
2288bcf0153eSBarry Smith   Not Collective, but v returned is parallel if ts is parallel
228903fe5f5eSDebojyoti Ghosh 
2290b43aa488SJacob Faibussowitsch   Input Parameters:
2291bcf0153eSBarry Smith + ts - the `TS` context obtained from `TSCreate()` (input parameter).
2292195e9b02SBarry Smith . n  - If v is `NULL`, then the number of solution components is
2293b2bf4f3aSDebojyoti Ghosh        returned through n, else the n-th solution component is
229403fe5f5eSDebojyoti Ghosh        returned in v.
2295a2b725a8SWilliam Gropp - v  - the vector containing the n-th solution component
2296195e9b02SBarry Smith        (may be `NULL` to use this function to find out
2297b2bf4f3aSDebojyoti Ghosh         the number of solutions components).
229803fe5f5eSDebojyoti Ghosh 
22994cdd57e5SDebojyoti Ghosh   Level: advanced
230003fe5f5eSDebojyoti Ghosh 
23011cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSGetSolution()`
230203fe5f5eSDebojyoti Ghosh @*/
2303d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetSolutionComponents(TS ts, PetscInt *n, Vec *v)
2304d71ae5a4SJacob Faibussowitsch {
230503fe5f5eSDebojyoti Ghosh   PetscFunctionBegin;
230603fe5f5eSDebojyoti Ghosh   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
2307b2bf4f3aSDebojyoti Ghosh   if (!ts->ops->getsolutioncomponents) *n = 0;
2308dbbe0bcdSBarry Smith   else PetscUseTypeMethod(ts, getsolutioncomponents, n, v);
23093ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
231003fe5f5eSDebojyoti Ghosh }
231103fe5f5eSDebojyoti Ghosh 
23124cdd57e5SDebojyoti Ghosh /*@
23134cdd57e5SDebojyoti Ghosh   TSGetAuxSolution - Returns an auxiliary solution at the present
23144cdd57e5SDebojyoti Ghosh   timestep, if available for the time integration method being used.
23154cdd57e5SDebojyoti Ghosh 
2316bcf0153eSBarry Smith   Not Collective, but v returned is parallel if ts is parallel
23174cdd57e5SDebojyoti Ghosh 
2318b43aa488SJacob Faibussowitsch   Input Parameters:
2319bcf0153eSBarry Smith + ts - the `TS` context obtained from `TSCreate()` (input parameter).
2320a2b725a8SWilliam Gropp - v  - the vector containing the auxiliary solution
23214cdd57e5SDebojyoti Ghosh 
23224cdd57e5SDebojyoti Ghosh   Level: intermediate
23234cdd57e5SDebojyoti Ghosh 
23241cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSGetSolution()`
23254cdd57e5SDebojyoti Ghosh @*/
2326d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetAuxSolution(TS ts, Vec *v)
2327d71ae5a4SJacob Faibussowitsch {
23284cdd57e5SDebojyoti Ghosh   PetscFunctionBegin;
23294cdd57e5SDebojyoti Ghosh   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
2330dbbe0bcdSBarry Smith   if (ts->ops->getauxsolution) PetscUseTypeMethod(ts, getauxsolution, v);
23311e66621cSBarry Smith   else PetscCall(VecZeroEntries(*v));
23323ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
23334cdd57e5SDebojyoti Ghosh }
23344cdd57e5SDebojyoti Ghosh 
23354cdd57e5SDebojyoti Ghosh /*@
23364cdd57e5SDebojyoti Ghosh   TSGetTimeError - Returns the estimated error vector, if the chosen
2337bcf0153eSBarry Smith   `TSType` has an error estimation functionality and `TSSetTimeError()` was called
23384cdd57e5SDebojyoti Ghosh 
2339bcf0153eSBarry Smith   Not Collective, but v returned is parallel if ts is parallel
23409657682dSDebojyoti Ghosh 
2341b43aa488SJacob Faibussowitsch   Input Parameters:
2342bcf0153eSBarry Smith + ts - the `TS` context obtained from `TSCreate()` (input parameter).
2343657c1e31SEmil Constantinescu . n  - current estimate (n=0) or previous one (n=-1)
2344a2b725a8SWilliam Gropp - v  - the vector containing the error (same size as the solution).
23454cdd57e5SDebojyoti Ghosh 
23464cdd57e5SDebojyoti Ghosh   Level: intermediate
23474cdd57e5SDebojyoti Ghosh 
2348bcf0153eSBarry Smith   Note:
2349bcf0153eSBarry Smith   MUST call after `TSSetUp()`
23504cdd57e5SDebojyoti Ghosh 
23511cc06b55SBarry Smith .seealso: [](ch_ts), `TSGetSolution()`, `TSSetTimeError()`
23524cdd57e5SDebojyoti Ghosh @*/
2353d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetTimeError(TS ts, PetscInt n, Vec *v)
2354d71ae5a4SJacob Faibussowitsch {
23554cdd57e5SDebojyoti Ghosh   PetscFunctionBegin;
23564cdd57e5SDebojyoti Ghosh   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
2357dbbe0bcdSBarry Smith   if (ts->ops->gettimeerror) PetscUseTypeMethod(ts, gettimeerror, n, v);
23581e66621cSBarry Smith   else PetscCall(VecZeroEntries(*v));
23593ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
23604cdd57e5SDebojyoti Ghosh }
23614cdd57e5SDebojyoti Ghosh 
236257df6a1bSDebojyoti Ghosh /*@
236357df6a1bSDebojyoti Ghosh   TSSetTimeError - Sets the estimated error vector, if the chosen
2364bcf0153eSBarry Smith   `TSType` has an error estimation functionality. This can be used
236557df6a1bSDebojyoti Ghosh   to restart such a time integrator with a given error vector.
236657df6a1bSDebojyoti Ghosh 
2367bcf0153eSBarry Smith   Not Collective, but v returned is parallel if ts is parallel
236857df6a1bSDebojyoti Ghosh 
2369b43aa488SJacob Faibussowitsch   Input Parameters:
2370bcf0153eSBarry Smith + ts - the `TS` context obtained from `TSCreate()` (input parameter).
2371a2b725a8SWilliam Gropp - v  - the vector containing the error (same size as the solution).
237257df6a1bSDebojyoti Ghosh 
237357df6a1bSDebojyoti Ghosh   Level: intermediate
237457df6a1bSDebojyoti Ghosh 
2375b43aa488SJacob Faibussowitsch .seealso: [](ch_ts), `TS`, `TSSetSolution()`, `TSGetTimeError()`
237657df6a1bSDebojyoti Ghosh @*/
2377d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetTimeError(TS ts, Vec v)
2378d71ae5a4SJacob Faibussowitsch {
237957df6a1bSDebojyoti Ghosh   PetscFunctionBegin;
238057df6a1bSDebojyoti Ghosh   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
23813c633725SBarry Smith   PetscCheck(ts->setupcalled, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Must call TSSetUp() first");
2382dbbe0bcdSBarry Smith   PetscTryTypeMethod(ts, settimeerror, v);
23833ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
238457df6a1bSDebojyoti Ghosh }
238557df6a1bSDebojyoti Ghosh 
2386bdad233fSMatthew Knepley /* ----- Routines to initialize and destroy a timestepper ---- */
2387d8e5e3e6SSatish Balay /*@
2388bdad233fSMatthew Knepley   TSSetProblemType - Sets the type of problem to be solved.
2389d763cef2SBarry Smith 
2390bdad233fSMatthew Knepley   Not collective
2391d763cef2SBarry Smith 
2392bdad233fSMatthew Knepley   Input Parameters:
2393bcf0153eSBarry Smith + ts   - The `TS`
2394bcf0153eSBarry Smith - type - One of `TS_LINEAR`, `TS_NONLINEAR` where these types refer to problems of the forms
2395d763cef2SBarry Smith .vb
23960910c330SBarry Smith          U_t - A U = 0      (linear)
23970910c330SBarry Smith          U_t - A(t) U = 0   (linear)
23980910c330SBarry Smith          F(t,U,U_t) = 0     (nonlinear)
2399d763cef2SBarry Smith .ve
2400d763cef2SBarry Smith 
2401d763cef2SBarry Smith   Level: beginner
2402d763cef2SBarry Smith 
24031cc06b55SBarry Smith .seealso: [](ch_ts), `TSSetUp()`, `TSProblemType`, `TS`
2404d763cef2SBarry Smith @*/
2405d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetProblemType(TS ts, TSProblemType type)
2406d71ae5a4SJacob Faibussowitsch {
2407d763cef2SBarry Smith   PetscFunctionBegin;
24080700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
2409bdad233fSMatthew Knepley   ts->problem_type = type;
24109e2a6581SJed Brown   if (type == TS_LINEAR) {
24119e2a6581SJed Brown     SNES snes;
24129566063dSJacob Faibussowitsch     PetscCall(TSGetSNES(ts, &snes));
24139566063dSJacob Faibussowitsch     PetscCall(SNESSetType(snes, SNESKSPONLY));
24149e2a6581SJed Brown   }
24153ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2416d763cef2SBarry Smith }
2417d763cef2SBarry Smith 
2418cc4c1da9SBarry Smith /*@
2419bdad233fSMatthew Knepley   TSGetProblemType - Gets the type of problem to be solved.
2420bdad233fSMatthew Knepley 
2421bdad233fSMatthew Knepley   Not collective
2422bdad233fSMatthew Knepley 
2423bdad233fSMatthew Knepley   Input Parameter:
2424bcf0153eSBarry Smith . ts - The `TS`
2425bdad233fSMatthew Knepley 
2426bdad233fSMatthew Knepley   Output Parameter:
2427bcf0153eSBarry Smith . type - One of `TS_LINEAR`, `TS_NONLINEAR` where these types refer to problems of the forms
2428bdad233fSMatthew Knepley .vb
2429089b2837SJed Brown          M U_t = A U
2430089b2837SJed Brown          M(t) U_t = A(t) U
2431b5abc632SBarry Smith          F(t,U,U_t)
2432bdad233fSMatthew Knepley .ve
2433bdad233fSMatthew Knepley 
2434bdad233fSMatthew Knepley   Level: beginner
2435bdad233fSMatthew Knepley 
24361cc06b55SBarry Smith .seealso: [](ch_ts), `TSSetUp()`, `TSProblemType`, `TS`
2437bdad233fSMatthew Knepley @*/
2438d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetProblemType(TS ts, TSProblemType *type)
2439d71ae5a4SJacob Faibussowitsch {
2440bdad233fSMatthew Knepley   PetscFunctionBegin;
24410700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
24424f572ea9SToby Isaac   PetscAssertPointer(type, 2);
2443bdad233fSMatthew Knepley   *type = ts->problem_type;
24443ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2445bdad233fSMatthew Knepley }
2446d763cef2SBarry Smith 
2447303a5415SBarry Smith /*
2448303a5415SBarry 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()
2449303a5415SBarry Smith */
2450d71ae5a4SJacob Faibussowitsch static PetscErrorCode TSSetExactFinalTimeDefault(TS ts)
2451d71ae5a4SJacob Faibussowitsch {
2452303a5415SBarry Smith   PetscBool isnone;
2453303a5415SBarry Smith 
2454303a5415SBarry Smith   PetscFunctionBegin;
24559566063dSJacob Faibussowitsch   PetscCall(TSGetAdapt(ts, &ts->adapt));
24569566063dSJacob Faibussowitsch   PetscCall(TSAdaptSetDefaultType(ts->adapt, ts->default_adapt_type));
2457303a5415SBarry Smith 
24589566063dSJacob Faibussowitsch   PetscCall(PetscObjectTypeCompare((PetscObject)ts->adapt, TSADAPTNONE, &isnone));
24591e66621cSBarry Smith   if (!isnone && ts->exact_final_time == TS_EXACTFINALTIME_UNSPECIFIED) ts->exact_final_time = TS_EXACTFINALTIME_MATCHSTEP;
24601e66621cSBarry Smith   else if (ts->exact_final_time == TS_EXACTFINALTIME_UNSPECIFIED) ts->exact_final_time = TS_EXACTFINALTIME_INTERPOLATE;
24613ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2462303a5415SBarry Smith }
2463303a5415SBarry Smith 
2464d763cef2SBarry Smith /*@
2465303a5415SBarry Smith   TSSetUp - Sets up the internal data structures for the later use of a timestepper.
2466d763cef2SBarry Smith 
2467c3339decSBarry Smith   Collective
2468d763cef2SBarry Smith 
2469d763cef2SBarry Smith   Input Parameter:
2470bcf0153eSBarry Smith . ts - the `TS` context obtained from `TSCreate()`
2471d763cef2SBarry Smith 
2472d763cef2SBarry Smith   Level: advanced
2473d763cef2SBarry Smith 
2474bcf0153eSBarry Smith   Note:
2475bcf0153eSBarry Smith   For basic use of the `TS` solvers the user need not explicitly call
2476bcf0153eSBarry Smith   `TSSetUp()`, since these actions will automatically occur during
2477bcf0153eSBarry Smith   the call to `TSStep()` or `TSSolve()`.  However, if one wishes to control this
2478bcf0153eSBarry Smith   phase separately, `TSSetUp()` should be called after `TSCreate()`
2479bcf0153eSBarry Smith   and optional routines of the form TSSetXXX(), but before `TSStep()` and `TSSolve()`.
2480bcf0153eSBarry Smith 
24811cc06b55SBarry Smith .seealso: [](ch_ts), `TSCreate()`, `TS`, `TSStep()`, `TSDestroy()`, `TSSolve()`
2482d763cef2SBarry Smith @*/
2483d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetUp(TS ts)
2484d71ae5a4SJacob Faibussowitsch {
24856c6b9e74SPeter Brune   DM dm;
24866c6b9e74SPeter Brune   PetscErrorCode (*func)(SNES, Vec, Vec, void *);
2487d1e9a80fSBarry Smith   PetscErrorCode (*jac)(SNES, Vec, Mat, Mat, void *);
24888434afd1SBarry Smith   TSIFunctionFn   *ifun;
24898434afd1SBarry Smith   TSIJacobianFn   *ijac;
24908434afd1SBarry Smith   TSI2JacobianFn  *i2jac;
24918434afd1SBarry Smith   TSRHSJacobianFn *rhsjac;
2492d763cef2SBarry Smith 
2493d763cef2SBarry Smith   PetscFunctionBegin;
24940700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
24953ba16761SJacob Faibussowitsch   if (ts->setupcalled) PetscFunctionReturn(PETSC_SUCCESS);
2496277b19d0SLisandro Dalcin 
24977adad957SLisandro Dalcin   if (!((PetscObject)ts)->type_name) {
24989566063dSJacob Faibussowitsch     PetscCall(TSGetIFunction(ts, NULL, &ifun, NULL));
24999566063dSJacob Faibussowitsch     PetscCall(TSSetType(ts, ifun ? TSBEULER : TSEULER));
2500d763cef2SBarry Smith   }
2501277b19d0SLisandro Dalcin 
25021a638600SStefano Zampini   if (!ts->vec_sol) {
25031e66621cSBarry Smith     PetscCheck(ts->dm, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Must call TSSetSolution() first");
25049566063dSJacob Faibussowitsch     PetscCall(DMCreateGlobalVector(ts->dm, &ts->vec_sol));
25051a638600SStefano Zampini   }
2506277b19d0SLisandro Dalcin 
2507298bade4SHong Zhang   if (!ts->Jacp && ts->Jacprhs) { /* IJacobianP shares the same matrix with RHSJacobianP if only RHSJacobianP is provided */
25089566063dSJacob Faibussowitsch     PetscCall(PetscObjectReference((PetscObject)ts->Jacprhs));
2509298bade4SHong Zhang     ts->Jacp = ts->Jacprhs;
2510298bade4SHong Zhang   }
2511298bade4SHong Zhang 
2512cd4cee2dSHong Zhang   if (ts->quadraturets) {
25139566063dSJacob Faibussowitsch     PetscCall(TSSetUp(ts->quadraturets));
25149566063dSJacob Faibussowitsch     PetscCall(VecDestroy(&ts->vec_costintegrand));
25159566063dSJacob Faibussowitsch     PetscCall(VecDuplicate(ts->quadraturets->vec_sol, &ts->vec_costintegrand));
2516cd4cee2dSHong Zhang   }
2517cd4cee2dSHong Zhang 
25189566063dSJacob Faibussowitsch   PetscCall(TSGetRHSJacobian(ts, NULL, NULL, &rhsjac, NULL));
2519f23ba4b3SHong Zhang   if (rhsjac == TSComputeRHSJacobianConstant) {
2520e1244c69SJed Brown     Mat  Amat, Pmat;
2521e1244c69SJed Brown     SNES snes;
25229566063dSJacob Faibussowitsch     PetscCall(TSGetSNES(ts, &snes));
25239566063dSJacob Faibussowitsch     PetscCall(SNESGetJacobian(snes, &Amat, &Pmat, NULL, NULL));
2524e1244c69SJed Brown     /* Matching matrices implies that an IJacobian is NOT set, because if it had been set, the IJacobian's matrix would
2525e1244c69SJed Brown      * have displaced the RHS matrix */
2526971015bcSStefano Zampini     if (Amat && Amat == ts->Arhs) {
2527abc0d4abSBarry 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 */
25289566063dSJacob Faibussowitsch       PetscCall(MatDuplicate(ts->Arhs, MAT_COPY_VALUES, &Amat));
25299566063dSJacob Faibussowitsch       PetscCall(SNESSetJacobian(snes, Amat, NULL, NULL, NULL));
25309566063dSJacob Faibussowitsch       PetscCall(MatDestroy(&Amat));
2531e1244c69SJed Brown     }
2532971015bcSStefano Zampini     if (Pmat && Pmat == ts->Brhs) {
25339566063dSJacob Faibussowitsch       PetscCall(MatDuplicate(ts->Brhs, MAT_COPY_VALUES, &Pmat));
25349566063dSJacob Faibussowitsch       PetscCall(SNESSetJacobian(snes, NULL, Pmat, NULL, NULL));
25359566063dSJacob Faibussowitsch       PetscCall(MatDestroy(&Pmat));
2536e1244c69SJed Brown     }
2537e1244c69SJed Brown   }
25382ffb9264SLisandro Dalcin 
25399566063dSJacob Faibussowitsch   PetscCall(TSGetAdapt(ts, &ts->adapt));
25409566063dSJacob Faibussowitsch   PetscCall(TSAdaptSetDefaultType(ts->adapt, ts->default_adapt_type));
25412ffb9264SLisandro Dalcin 
2542dbbe0bcdSBarry Smith   PetscTryTypeMethod(ts, setup);
2543277b19d0SLisandro Dalcin 
25449566063dSJacob Faibussowitsch   PetscCall(TSSetExactFinalTimeDefault(ts));
25452ffb9264SLisandro Dalcin 
2546a6772fa2SLisandro Dalcin   /* In the case where we've set a DMTSFunction or what have you, we need the default SNESFunction
25476c6b9e74SPeter Brune      to be set right but can't do it elsewhere due to the overreliance on ctx=ts.
25486c6b9e74SPeter Brune    */
25499566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
25509566063dSJacob Faibussowitsch   PetscCall(DMSNESGetFunction(dm, &func, NULL));
25511e66621cSBarry Smith   if (!func) PetscCall(DMSNESSetFunction(dm, SNESTSFormFunction, ts));
25521e66621cSBarry Smith 
2553a6772fa2SLisandro 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.
25546c6b9e74SPeter Brune      Otherwise, the SNES will use coloring internally to form the Jacobian.
25556c6b9e74SPeter Brune    */
25569566063dSJacob Faibussowitsch   PetscCall(DMSNESGetJacobian(dm, &jac, NULL));
25579566063dSJacob Faibussowitsch   PetscCall(DMTSGetIJacobian(dm, &ijac, NULL));
25589566063dSJacob Faibussowitsch   PetscCall(DMTSGetI2Jacobian(dm, &i2jac, NULL));
25599566063dSJacob Faibussowitsch   PetscCall(DMTSGetRHSJacobian(dm, &rhsjac, NULL));
25601e66621cSBarry Smith   if (!jac && (ijac || i2jac || rhsjac)) PetscCall(DMSNESSetJacobian(dm, SNESTSFormJacobian, ts));
2561c0517034SDebojyoti Ghosh 
2562c0517034SDebojyoti Ghosh   /* if time integration scheme has a starting method, call it */
2563dbbe0bcdSBarry Smith   PetscTryTypeMethod(ts, startingmethod);
2564c0517034SDebojyoti Ghosh 
2565277b19d0SLisandro Dalcin   ts->setupcalled = PETSC_TRUE;
25663ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2567277b19d0SLisandro Dalcin }
2568277b19d0SLisandro Dalcin 
2569f6a906c0SBarry Smith /*@
25700b4b7b1cSBarry Smith   TSReset - Resets a `TS` context to the state it was in before `TSSetUp()` was called and removes any allocated `Vec` and `Mat` from its data structures
2571277b19d0SLisandro Dalcin 
2572c3339decSBarry Smith   Collective
2573277b19d0SLisandro Dalcin 
2574277b19d0SLisandro Dalcin   Input Parameter:
2575bcf0153eSBarry Smith . ts - the `TS` context obtained from `TSCreate()`
2576277b19d0SLisandro Dalcin 
25770b4b7b1cSBarry Smith   Level: developer
2578277b19d0SLisandro Dalcin 
25790b4b7b1cSBarry Smith   Notes:
25800b4b7b1cSBarry Smith   Any options set on the `TS` object, including those set with `TSSetFromOptions()` remain.
25810b4b7b1cSBarry Smith 
25820b4b7b1cSBarry Smith   See also `TSSetResize()` to change the size of the system being integrated (for example by adaptive mesh refinement) during the time integration.
25830b4b7b1cSBarry Smith 
2584bfe80ac4SPierre Jolivet .seealso: [](ch_ts), `TS`, `TSCreate()`, `TSSetUp()`, `TSDestroy()`, `TSSetResize()`
2585277b19d0SLisandro Dalcin @*/
2586d71ae5a4SJacob Faibussowitsch PetscErrorCode TSReset(TS ts)
2587d71ae5a4SJacob Faibussowitsch {
25881d06f6b3SHong Zhang   TS_RHSSplitLink ilink = ts->tsrhssplit, next;
2589277b19d0SLisandro Dalcin 
2590277b19d0SLisandro Dalcin   PetscFunctionBegin;
2591277b19d0SLisandro Dalcin   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
2592b18ea86cSHong Zhang 
2593dbbe0bcdSBarry Smith   PetscTryTypeMethod(ts, reset);
25949566063dSJacob Faibussowitsch   if (ts->snes) PetscCall(SNESReset(ts->snes));
25959566063dSJacob Faibussowitsch   if (ts->adapt) PetscCall(TSAdaptReset(ts->adapt));
2596bbd56ea5SKarl Rupp 
25979566063dSJacob Faibussowitsch   PetscCall(MatDestroy(&ts->Arhs));
25989566063dSJacob Faibussowitsch   PetscCall(MatDestroy(&ts->Brhs));
25999566063dSJacob Faibussowitsch   PetscCall(VecDestroy(&ts->Frhs));
26009566063dSJacob Faibussowitsch   PetscCall(VecDestroy(&ts->vec_sol));
2601c61711c8SStefano Zampini   PetscCall(VecDestroy(&ts->vec_sol0));
26029566063dSJacob Faibussowitsch   PetscCall(VecDestroy(&ts->vec_dot));
26039566063dSJacob Faibussowitsch   PetscCall(VecDestroy(&ts->vatol));
26049566063dSJacob Faibussowitsch   PetscCall(VecDestroy(&ts->vrtol));
26059566063dSJacob Faibussowitsch   PetscCall(VecDestroyVecs(ts->nwork, &ts->work));
2606bbd56ea5SKarl Rupp 
26079566063dSJacob Faibussowitsch   PetscCall(MatDestroy(&ts->Jacprhs));
26089566063dSJacob Faibussowitsch   PetscCall(MatDestroy(&ts->Jacp));
26091baa6e33SBarry Smith   if (ts->forward_solve) PetscCall(TSForwardReset(ts));
2610cd4cee2dSHong Zhang   if (ts->quadraturets) {
26119566063dSJacob Faibussowitsch     PetscCall(TSReset(ts->quadraturets));
26129566063dSJacob Faibussowitsch     PetscCall(VecDestroy(&ts->vec_costintegrand));
2613cd4cee2dSHong Zhang   }
26141d06f6b3SHong Zhang   while (ilink) {
26151d06f6b3SHong Zhang     next = ilink->next;
26169566063dSJacob Faibussowitsch     PetscCall(TSDestroy(&ilink->ts));
26179566063dSJacob Faibussowitsch     PetscCall(PetscFree(ilink->splitname));
26189566063dSJacob Faibussowitsch     PetscCall(ISDestroy(&ilink->is));
26199566063dSJacob Faibussowitsch     PetscCall(PetscFree(ilink));
26201d06f6b3SHong Zhang     ilink = next;
262187f4e208SHong Zhang   }
26226bf673ebSJoe Pusztay   ts->tsrhssplit     = NULL;
2623545aaa6fSHong Zhang   ts->num_rhs_splits = 0;
2624136cf249SJames Wright   if (ts->eval_times) {
2625136cf249SJames Wright     PetscCall(PetscFree(ts->eval_times->time_points));
2626136cf249SJames Wright     PetscCall(PetscFree(ts->eval_times->sol_times));
2627136cf249SJames Wright     PetscCall(VecDestroyVecs(ts->eval_times->num_time_points, &ts->eval_times->sol_vecs));
2628136cf249SJames Wright     PetscCall(PetscFree(ts->eval_times));
26294a658b32SHong Zhang   }
2630b3a72457SStefano Zampini   ts->rhsjacobian.time  = PETSC_MIN_REAL;
2631b3a72457SStefano Zampini   ts->rhsjacobian.scale = 1.0;
2632b3a72457SStefano Zampini   ts->ijacobian.shift   = 1.0;
2633277b19d0SLisandro Dalcin   ts->setupcalled       = PETSC_FALSE;
26343ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2635d763cef2SBarry Smith }
2636d763cef2SBarry Smith 
263714d0ab18SJacob Faibussowitsch static PetscErrorCode TSResizeReset(TS);
263814d0ab18SJacob Faibussowitsch 
26390764c050SBarry Smith /*@
2640d763cef2SBarry Smith   TSDestroy - Destroys the timestepper context that was created
2641bcf0153eSBarry Smith   with `TSCreate()`.
2642d763cef2SBarry Smith 
2643c3339decSBarry Smith   Collective
2644d763cef2SBarry Smith 
2645d763cef2SBarry Smith   Input Parameter:
2646bcf0153eSBarry Smith . ts - the `TS` context obtained from `TSCreate()`
2647d763cef2SBarry Smith 
2648d763cef2SBarry Smith   Level: beginner
2649d763cef2SBarry Smith 
26501cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSCreate()`, `TSSetUp()`, `TSSolve()`
2651d763cef2SBarry Smith @*/
2652d71ae5a4SJacob Faibussowitsch PetscErrorCode TSDestroy(TS *ts)
2653d71ae5a4SJacob Faibussowitsch {
2654d763cef2SBarry Smith   PetscFunctionBegin;
26553ba16761SJacob Faibussowitsch   if (!*ts) PetscFunctionReturn(PETSC_SUCCESS);
2656ecf68647SHong Zhang   PetscValidHeaderSpecific(*ts, TS_CLASSID, 1);
2657f4f49eeaSPierre Jolivet   if (--((PetscObject)*ts)->refct > 0) {
26589371c9d4SSatish Balay     *ts = NULL;
26593ba16761SJacob Faibussowitsch     PetscFunctionReturn(PETSC_SUCCESS);
26609371c9d4SSatish Balay   }
2661d763cef2SBarry Smith 
26629566063dSJacob Faibussowitsch   PetscCall(TSReset(*ts));
26639566063dSJacob Faibussowitsch   PetscCall(TSAdjointReset(*ts));
26641e66621cSBarry Smith   if ((*ts)->forward_solve) PetscCall(TSForwardReset(*ts));
26656bd3a4fdSStefano Zampini   PetscCall(TSResizeReset(*ts));
26661e66621cSBarry Smith 
2667e04113cfSBarry Smith   /* if memory was published with SAWs then destroy it */
26689566063dSJacob Faibussowitsch   PetscCall(PetscObjectSAWsViewOff((PetscObject)*ts));
2669f4f49eeaSPierre Jolivet   PetscTryTypeMethod(*ts, destroy);
26706d4c513bSLisandro Dalcin 
26719566063dSJacob Faibussowitsch   PetscCall(TSTrajectoryDestroy(&(*ts)->trajectory));
2672bc952696SBarry Smith 
26739566063dSJacob Faibussowitsch   PetscCall(TSAdaptDestroy(&(*ts)->adapt));
26749566063dSJacob Faibussowitsch   PetscCall(TSEventDestroy(&(*ts)->event));
26756427ac75SLisandro Dalcin 
26769566063dSJacob Faibussowitsch   PetscCall(SNESDestroy(&(*ts)->snes));
26774bd3aaa3SHong Zhang   PetscCall(SNESDestroy(&(*ts)->snesrhssplit));
26789566063dSJacob Faibussowitsch   PetscCall(DMDestroy(&(*ts)->dm));
2679f4f49eeaSPierre Jolivet   PetscCall(TSMonitorCancel(*ts));
2680f4f49eeaSPierre Jolivet   PetscCall(TSAdjointMonitorCancel(*ts));
26816d4c513bSLisandro Dalcin 
26829566063dSJacob Faibussowitsch   PetscCall(TSDestroy(&(*ts)->quadraturets));
26839566063dSJacob Faibussowitsch   PetscCall(PetscHeaderDestroy(ts));
26843ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2685d763cef2SBarry Smith }
2686d763cef2SBarry Smith 
2687d8e5e3e6SSatish Balay /*@
2688bcf0153eSBarry Smith   TSGetSNES - Returns the `SNES` (nonlinear solver) associated with
2689bcf0153eSBarry Smith   a `TS` (timestepper) context. Valid only for nonlinear problems.
2690d763cef2SBarry Smith 
2691bcf0153eSBarry Smith   Not Collective, but snes is parallel if ts is parallel
2692d763cef2SBarry Smith 
2693d763cef2SBarry Smith   Input Parameter:
2694bcf0153eSBarry Smith . ts - the `TS` context obtained from `TSCreate()`
2695d763cef2SBarry Smith 
2696d763cef2SBarry Smith   Output Parameter:
2697d763cef2SBarry Smith . snes - the nonlinear solver context
2698d763cef2SBarry Smith 
2699d763cef2SBarry Smith   Level: beginner
2700d763cef2SBarry Smith 
2701bcf0153eSBarry Smith   Notes:
2702bcf0153eSBarry Smith   The user can then directly manipulate the `SNES` context to set various
2703bcf0153eSBarry Smith   options, etc.  Likewise, the user can then extract and manipulate the
2704bcf0153eSBarry Smith   `KSP`, and `PC` contexts as well.
2705bcf0153eSBarry Smith 
2706bcf0153eSBarry Smith   `TSGetSNES()` does not work for integrators that do not use `SNES`; in
2707195e9b02SBarry Smith   this case `TSGetSNES()` returns `NULL` in `snes`.
2708bcf0153eSBarry Smith 
27091cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `SNES`, `TSCreate()`, `TSSetUp()`, `TSSolve()`
2710d763cef2SBarry Smith @*/
2711d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetSNES(TS ts, SNES *snes)
2712d71ae5a4SJacob Faibussowitsch {
2713d763cef2SBarry Smith   PetscFunctionBegin;
27140700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
27154f572ea9SToby Isaac   PetscAssertPointer(snes, 2);
2716d372ba47SLisandro Dalcin   if (!ts->snes) {
27179566063dSJacob Faibussowitsch     PetscCall(SNESCreate(PetscObjectComm((PetscObject)ts), &ts->snes));
27189566063dSJacob Faibussowitsch     PetscCall(PetscObjectSetOptions((PetscObject)ts->snes, ((PetscObject)ts)->options));
27199566063dSJacob Faibussowitsch     PetscCall(SNESSetFunction(ts->snes, NULL, SNESTSFormFunction, ts));
27209566063dSJacob Faibussowitsch     PetscCall(PetscObjectIncrementTabLevel((PetscObject)ts->snes, (PetscObject)ts, 1));
27214bd3aaa3SHong Zhang     if (ts->dm) PetscCall(SNESSetDM(ts->snes, ts->dm));
27221e66621cSBarry Smith     if (ts->problem_type == TS_LINEAR) PetscCall(SNESSetType(ts->snes, SNESKSPONLY));
2723d372ba47SLisandro Dalcin   }
2724d763cef2SBarry Smith   *snes = ts->snes;
27253ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2726d763cef2SBarry Smith }
2727d763cef2SBarry Smith 
2728deb2cd25SJed Brown /*@
27290b4b7b1cSBarry Smith   TSSetSNES - Set the `SNES` (nonlinear solver) to be used by the `TS` timestepping context
2730deb2cd25SJed Brown 
2731deb2cd25SJed Brown   Collective
2732deb2cd25SJed Brown 
2733d8d19677SJose E. Roman   Input Parameters:
2734bcf0153eSBarry Smith + ts   - the `TS` context obtained from `TSCreate()`
2735deb2cd25SJed Brown - snes - the nonlinear solver context
2736deb2cd25SJed Brown 
2737deb2cd25SJed Brown   Level: developer
2738deb2cd25SJed Brown 
2739bcf0153eSBarry Smith   Note:
2740bcf0153eSBarry Smith   Most users should have the `TS` created by calling `TSGetSNES()`
2741bcf0153eSBarry Smith 
27421cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `SNES`, `TSCreate()`, `TSSetUp()`, `TSSolve()`, `TSGetSNES()`
2743deb2cd25SJed Brown @*/
2744d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetSNES(TS ts, SNES snes)
2745d71ae5a4SJacob Faibussowitsch {
2746d1e9a80fSBarry Smith   PetscErrorCode (*func)(SNES, Vec, Mat, Mat, void *);
2747deb2cd25SJed Brown 
2748deb2cd25SJed Brown   PetscFunctionBegin;
2749deb2cd25SJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
2750deb2cd25SJed Brown   PetscValidHeaderSpecific(snes, SNES_CLASSID, 2);
27519566063dSJacob Faibussowitsch   PetscCall(PetscObjectReference((PetscObject)snes));
27529566063dSJacob Faibussowitsch   PetscCall(SNESDestroy(&ts->snes));
2753bbd56ea5SKarl Rupp 
2754deb2cd25SJed Brown   ts->snes = snes;
2755bbd56ea5SKarl Rupp 
27569566063dSJacob Faibussowitsch   PetscCall(SNESSetFunction(ts->snes, NULL, SNESTSFormFunction, ts));
27579566063dSJacob Faibussowitsch   PetscCall(SNESGetJacobian(ts->snes, NULL, NULL, &func, NULL));
27581e66621cSBarry Smith   if (func == SNESTSFormJacobian) PetscCall(SNESSetJacobian(ts->snes, NULL, NULL, SNESTSFormJacobian, ts));
27593ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2760deb2cd25SJed Brown }
2761deb2cd25SJed Brown 
2762d8e5e3e6SSatish Balay /*@
2763bcf0153eSBarry Smith   TSGetKSP - Returns the `KSP` (linear solver) associated with
2764bcf0153eSBarry Smith   a `TS` (timestepper) context.
2765d763cef2SBarry Smith 
2766195e9b02SBarry Smith   Not Collective, but `ksp` is parallel if `ts` is parallel
2767d763cef2SBarry Smith 
2768d763cef2SBarry Smith   Input Parameter:
2769bcf0153eSBarry Smith . ts - the `TS` context obtained from `TSCreate()`
2770d763cef2SBarry Smith 
2771d763cef2SBarry Smith   Output Parameter:
277294b7f48cSBarry Smith . ksp - the nonlinear solver context
2773d763cef2SBarry Smith 
2774d763cef2SBarry Smith   Level: beginner
2775d763cef2SBarry Smith 
2776bcf0153eSBarry Smith   Notes:
2777bcf0153eSBarry Smith   The user can then directly manipulate the `KSP` context to set various
2778bcf0153eSBarry Smith   options, etc.  Likewise, the user can then extract and manipulate the
2779bcf0153eSBarry Smith   `PC` context as well.
2780bcf0153eSBarry Smith 
2781bcf0153eSBarry Smith   `TSGetKSP()` does not work for integrators that do not use `KSP`;
2782195e9b02SBarry Smith   in this case `TSGetKSP()` returns `NULL` in `ksp`.
2783bcf0153eSBarry Smith 
27841cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `SNES`, `KSP`, `TSCreate()`, `TSSetUp()`, `TSSolve()`, `TSGetSNES()`
2785d763cef2SBarry Smith @*/
2786d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetKSP(TS ts, KSP *ksp)
2787d71ae5a4SJacob Faibussowitsch {
2788089b2837SJed Brown   SNES snes;
2789d372ba47SLisandro Dalcin 
2790d763cef2SBarry Smith   PetscFunctionBegin;
27910700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
27924f572ea9SToby Isaac   PetscAssertPointer(ksp, 2);
27933c633725SBarry Smith   PetscCheck(((PetscObject)ts)->type_name, PETSC_COMM_SELF, PETSC_ERR_ARG_NULL, "KSP is not created yet. Call TSSetType() first");
27943c633725SBarry Smith   PetscCheck(ts->problem_type == TS_LINEAR, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Linear only; use TSGetSNES()");
27959566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts, &snes));
27969566063dSJacob Faibussowitsch   PetscCall(SNESGetKSP(snes, ksp));
27973ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2798d763cef2SBarry Smith }
2799d763cef2SBarry Smith 
2800d763cef2SBarry Smith /* ----------- Routines to set solver parameters ---------- */
2801d763cef2SBarry Smith 
2802adb62b0dSMatthew Knepley /*@
2803618ce8baSLisandro Dalcin   TSSetMaxSteps - Sets the maximum number of steps to use.
2804618ce8baSLisandro Dalcin 
2805c3339decSBarry Smith   Logically Collective
2806618ce8baSLisandro Dalcin 
2807618ce8baSLisandro Dalcin   Input Parameters:
2808bcf0153eSBarry Smith + ts       - the `TS` context obtained from `TSCreate()`
2809618ce8baSLisandro Dalcin - maxsteps - maximum number of steps to use
2810618ce8baSLisandro Dalcin 
2811bcf0153eSBarry Smith   Options Database Key:
2812618ce8baSLisandro Dalcin . -ts_max_steps <maxsteps> - Sets maxsteps
2813618ce8baSLisandro Dalcin 
2814618ce8baSLisandro Dalcin   Level: intermediate
2815618ce8baSLisandro Dalcin 
2816bcf0153eSBarry Smith   Note:
281709cb0f53SBarry Smith   Use `PETSC_DETERMINE` to reset the maximum number of steps to the default from when the object's type was set
281809cb0f53SBarry Smith 
281909cb0f53SBarry Smith   The default maximum number of steps is 5,000
282009cb0f53SBarry Smith 
282109cb0f53SBarry Smith   Fortran Note:
282209cb0f53SBarry Smith   Use `PETSC_DETERMINE_INTEGER`
2823bcf0153eSBarry Smith 
28241cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSGetMaxSteps()`, `TSSetMaxTime()`, `TSSetExactFinalTime()`
2825618ce8baSLisandro Dalcin @*/
2826d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetMaxSteps(TS ts, PetscInt maxsteps)
2827d71ae5a4SJacob Faibussowitsch {
2828618ce8baSLisandro Dalcin   PetscFunctionBegin;
2829618ce8baSLisandro Dalcin   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
2830618ce8baSLisandro Dalcin   PetscValidLogicalCollectiveInt(ts, maxsteps, 2);
283109cb0f53SBarry Smith   if (maxsteps == PETSC_DETERMINE) {
283209cb0f53SBarry Smith     ts->max_steps = ts->default_max_steps;
283309cb0f53SBarry Smith   } else {
28343c633725SBarry Smith     PetscCheck(maxsteps >= 0, PetscObjectComm((PetscObject)ts), PETSC_ERR_ARG_OUTOFRANGE, "Maximum number of steps must be non-negative");
2835618ce8baSLisandro Dalcin     ts->max_steps = maxsteps;
283609cb0f53SBarry Smith   }
28373ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2838618ce8baSLisandro Dalcin }
2839618ce8baSLisandro Dalcin 
2840618ce8baSLisandro Dalcin /*@
2841618ce8baSLisandro Dalcin   TSGetMaxSteps - Gets the maximum number of steps to use.
2842618ce8baSLisandro Dalcin 
2843618ce8baSLisandro Dalcin   Not Collective
2844618ce8baSLisandro Dalcin 
28452fe279fdSBarry Smith   Input Parameter:
2846bcf0153eSBarry Smith . ts - the `TS` context obtained from `TSCreate()`
2847618ce8baSLisandro Dalcin 
2848618ce8baSLisandro Dalcin   Output Parameter:
2849618ce8baSLisandro Dalcin . maxsteps - maximum number of steps to use
2850618ce8baSLisandro Dalcin 
2851618ce8baSLisandro Dalcin   Level: advanced
2852618ce8baSLisandro Dalcin 
28531cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetMaxSteps()`, `TSGetMaxTime()`, `TSSetMaxTime()`
2854618ce8baSLisandro Dalcin @*/
2855d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetMaxSteps(TS ts, PetscInt *maxsteps)
2856d71ae5a4SJacob Faibussowitsch {
2857618ce8baSLisandro Dalcin   PetscFunctionBegin;
2858618ce8baSLisandro Dalcin   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
28594f572ea9SToby Isaac   PetscAssertPointer(maxsteps, 2);
2860618ce8baSLisandro Dalcin   *maxsteps = ts->max_steps;
28613ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2862618ce8baSLisandro Dalcin }
2863618ce8baSLisandro Dalcin 
2864618ce8baSLisandro Dalcin /*@
28658e562f8dSJames Wright   TSSetRunSteps - Sets the maximum number of steps to take in each call to `TSSolve()`.
28668e562f8dSJames Wright 
28678e562f8dSJames Wright   If the step count when `TSSolve()` is `start_step`, this will stop the simulation once `current_step - start_step >= run_steps`.
28688e562f8dSJames Wright   Comparatively, `TSSetMaxSteps()` will stop if `current_step >= max_steps`.
28698e562f8dSJames Wright   The simulation will stop when either condition is reached.
28708e562f8dSJames Wright 
28718e562f8dSJames Wright   Logically Collective
28728e562f8dSJames Wright 
28738e562f8dSJames Wright   Input Parameters:
28748e562f8dSJames Wright + ts       - the `TS` context obtained from `TSCreate()`
28758e562f8dSJames Wright - runsteps - maximum number of steps to take in each call to `TSSolve()`;
28768e562f8dSJames Wright 
28778e562f8dSJames Wright   Options Database Key:
28788e562f8dSJames Wright . -ts_run_steps <runsteps> - Sets runsteps
28798e562f8dSJames Wright 
28808e562f8dSJames Wright   Level: intermediate
28818e562f8dSJames Wright 
28828e562f8dSJames Wright   Note:
28838e562f8dSJames Wright   The default is `PETSC_UNLIMITED`
28848e562f8dSJames Wright 
28858e562f8dSJames Wright .seealso: [](ch_ts), `TS`, `TSGetRunSteps()`, `TSSetMaxTime()`, `TSSetExactFinalTime()`, `TSSetMaxSteps()`
28868e562f8dSJames Wright @*/
28878e562f8dSJames Wright PetscErrorCode TSSetRunSteps(TS ts, PetscInt runsteps)
28888e562f8dSJames Wright {
28898e562f8dSJames Wright   PetscFunctionBegin;
28908e562f8dSJames Wright   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
28918e562f8dSJames Wright   PetscValidLogicalCollectiveInt(ts, runsteps, 2);
28928e562f8dSJames Wright   if (runsteps == PETSC_DETERMINE) {
28938e562f8dSJames Wright     ts->run_steps = PETSC_UNLIMITED;
28948e562f8dSJames Wright   } else {
28958e562f8dSJames Wright     PetscCheck(runsteps >= 0, PetscObjectComm((PetscObject)ts), PETSC_ERR_ARG_OUTOFRANGE, "Max number of steps to take in each call to TSSolve must be non-negative");
28968e562f8dSJames Wright     ts->run_steps = runsteps;
28978e562f8dSJames Wright   }
28988e562f8dSJames Wright   PetscFunctionReturn(PETSC_SUCCESS);
28998e562f8dSJames Wright }
29008e562f8dSJames Wright 
29018e562f8dSJames Wright /*@
29028e562f8dSJames Wright   TSGetRunSteps - Gets the maximum number of steps to take in each call to `TSSolve()`.
29038e562f8dSJames Wright 
29048e562f8dSJames Wright   Not Collective
29058e562f8dSJames Wright 
29068e562f8dSJames Wright   Input Parameter:
29078e562f8dSJames Wright . ts - the `TS` context obtained from `TSCreate()`
29088e562f8dSJames Wright 
29098e562f8dSJames Wright   Output Parameter:
29108e562f8dSJames Wright . runsteps - maximum number of steps to take in each call to `TSSolve`.
29118e562f8dSJames Wright 
29128e562f8dSJames Wright   Level: advanced
29138e562f8dSJames Wright 
29148e562f8dSJames Wright .seealso: [](ch_ts), `TS`, `TSSetRunSteps()`, `TSGetMaxTime()`, `TSSetMaxTime()`, `TSGetMaxSteps()`
29158e562f8dSJames Wright @*/
29168e562f8dSJames Wright PetscErrorCode TSGetRunSteps(TS ts, PetscInt *runsteps)
29178e562f8dSJames Wright {
29188e562f8dSJames Wright   PetscFunctionBegin;
29198e562f8dSJames Wright   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
29208e562f8dSJames Wright   PetscAssertPointer(runsteps, 2);
29218e562f8dSJames Wright   *runsteps = ts->run_steps;
29228e562f8dSJames Wright   PetscFunctionReturn(PETSC_SUCCESS);
29238e562f8dSJames Wright }
29248e562f8dSJames Wright 
29258e562f8dSJames Wright /*@
2926618ce8baSLisandro Dalcin   TSSetMaxTime - Sets the maximum (or final) time for timestepping.
2927618ce8baSLisandro Dalcin 
2928c3339decSBarry Smith   Logically Collective
2929618ce8baSLisandro Dalcin 
2930618ce8baSLisandro Dalcin   Input Parameters:
2931bcf0153eSBarry Smith + ts      - the `TS` context obtained from `TSCreate()`
2932618ce8baSLisandro Dalcin - maxtime - final time to step to
2933618ce8baSLisandro Dalcin 
2934bcf0153eSBarry Smith   Options Database Key:
2935ef85077eSLisandro Dalcin . -ts_max_time <maxtime> - Sets maxtime
2936618ce8baSLisandro Dalcin 
2937bcf0153eSBarry Smith   Level: intermediate
2938bcf0153eSBarry Smith 
2939618ce8baSLisandro Dalcin   Notes:
294009cb0f53SBarry Smith   Use `PETSC_DETERMINE` to reset the maximum time to the default from when the object's type was set
294109cb0f53SBarry Smith 
2942618ce8baSLisandro Dalcin   The default maximum time is 5.0
2943618ce8baSLisandro Dalcin 
294409cb0f53SBarry Smith   Fortran Note:
294509cb0f53SBarry Smith   Use `PETSC_DETERMINE_REAL`
294609cb0f53SBarry Smith 
29471cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSGetMaxTime()`, `TSSetMaxSteps()`, `TSSetExactFinalTime()`
2948618ce8baSLisandro Dalcin @*/
2949d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetMaxTime(TS ts, PetscReal maxtime)
2950d71ae5a4SJacob Faibussowitsch {
2951618ce8baSLisandro Dalcin   PetscFunctionBegin;
2952618ce8baSLisandro Dalcin   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
2953618ce8baSLisandro Dalcin   PetscValidLogicalCollectiveReal(ts, maxtime, 2);
295409cb0f53SBarry Smith   if (maxtime == PETSC_DETERMINE) {
295509cb0f53SBarry Smith     ts->max_time = ts->default_max_time;
295609cb0f53SBarry Smith   } else {
2957618ce8baSLisandro Dalcin     ts->max_time = maxtime;
295809cb0f53SBarry Smith   }
29593ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2960618ce8baSLisandro Dalcin }
2961618ce8baSLisandro Dalcin 
2962618ce8baSLisandro Dalcin /*@
2963618ce8baSLisandro Dalcin   TSGetMaxTime - Gets the maximum (or final) time for timestepping.
2964618ce8baSLisandro Dalcin 
2965618ce8baSLisandro Dalcin   Not Collective
2966618ce8baSLisandro Dalcin 
29672fe279fdSBarry Smith   Input Parameter:
2968bcf0153eSBarry Smith . ts - the `TS` context obtained from `TSCreate()`
2969618ce8baSLisandro Dalcin 
2970618ce8baSLisandro Dalcin   Output Parameter:
2971618ce8baSLisandro Dalcin . maxtime - final time to step to
2972618ce8baSLisandro Dalcin 
2973618ce8baSLisandro Dalcin   Level: advanced
2974618ce8baSLisandro Dalcin 
29751cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetMaxTime()`, `TSGetMaxSteps()`, `TSSetMaxSteps()`
2976618ce8baSLisandro Dalcin @*/
2977d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetMaxTime(TS ts, PetscReal *maxtime)
2978d71ae5a4SJacob Faibussowitsch {
2979618ce8baSLisandro Dalcin   PetscFunctionBegin;
2980618ce8baSLisandro Dalcin   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
29814f572ea9SToby Isaac   PetscAssertPointer(maxtime, 2);
2982618ce8baSLisandro Dalcin   *maxtime = ts->max_time;
29833ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2984618ce8baSLisandro Dalcin }
2985618ce8baSLisandro Dalcin 
298614d0ab18SJacob Faibussowitsch // PetscClangLinter pragma disable: -fdoc-*
2987618ce8baSLisandro Dalcin /*@
2988bcf0153eSBarry Smith   TSSetInitialTimeStep - Deprecated, use `TSSetTime()` and `TSSetTimeStep()`.
2989edc382c3SSatish Balay 
2990edc382c3SSatish Balay   Level: deprecated
2991edc382c3SSatish Balay 
2992aaa6c58dSLisandro Dalcin @*/
2993d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetInitialTimeStep(TS ts, PetscReal initial_time, PetscReal time_step)
2994d71ae5a4SJacob Faibussowitsch {
2995aaa6c58dSLisandro Dalcin   PetscFunctionBegin;
2996aaa6c58dSLisandro Dalcin   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
29979566063dSJacob Faibussowitsch   PetscCall(TSSetTime(ts, initial_time));
29989566063dSJacob Faibussowitsch   PetscCall(TSSetTimeStep(ts, time_step));
29993ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
3000aaa6c58dSLisandro Dalcin }
3001aaa6c58dSLisandro Dalcin 
300214d0ab18SJacob Faibussowitsch // PetscClangLinter pragma disable: -fdoc-*
3003aaa6c58dSLisandro Dalcin /*@
3004bcf0153eSBarry Smith   TSGetDuration - Deprecated, use `TSGetMaxSteps()` and `TSGetMaxTime()`.
3005edc382c3SSatish Balay 
3006edc382c3SSatish Balay   Level: deprecated
3007edc382c3SSatish Balay 
3008adb62b0dSMatthew Knepley @*/
3009d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetDuration(TS ts, PetscInt *maxsteps, PetscReal *maxtime)
3010d71ae5a4SJacob Faibussowitsch {
3011adb62b0dSMatthew Knepley   PetscFunctionBegin;
30120700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3013abc0a331SBarry Smith   if (maxsteps) {
30144f572ea9SToby Isaac     PetscAssertPointer(maxsteps, 2);
3015adb62b0dSMatthew Knepley     *maxsteps = ts->max_steps;
3016adb62b0dSMatthew Knepley   }
3017abc0a331SBarry Smith   if (maxtime) {
30184f572ea9SToby Isaac     PetscAssertPointer(maxtime, 3);
3019adb62b0dSMatthew Knepley     *maxtime = ts->max_time;
3020adb62b0dSMatthew Knepley   }
30213ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
3022adb62b0dSMatthew Knepley }
3023adb62b0dSMatthew Knepley 
302414d0ab18SJacob Faibussowitsch // PetscClangLinter pragma disable: -fdoc-*
3025d763cef2SBarry Smith /*@
3026bcf0153eSBarry Smith   TSSetDuration - Deprecated, use `TSSetMaxSteps()` and `TSSetMaxTime()`.
3027edc382c3SSatish Balay 
3028edc382c3SSatish Balay   Level: deprecated
3029edc382c3SSatish Balay 
3030d763cef2SBarry Smith @*/
3031d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetDuration(TS ts, PetscInt maxsteps, PetscReal maxtime)
3032d71ae5a4SJacob Faibussowitsch {
3033d763cef2SBarry Smith   PetscFunctionBegin;
3034835f2295SStefano Zampini   if (maxsteps != PETSC_CURRENT) PetscCall(TSSetMaxSteps(ts, maxsteps));
303509cb0f53SBarry Smith   if (maxtime != (PetscReal)PETSC_CURRENT) PetscCall(TSSetMaxTime(ts, maxtime));
30363ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
3037d763cef2SBarry Smith }
3038d763cef2SBarry Smith 
303914d0ab18SJacob Faibussowitsch // PetscClangLinter pragma disable: -fdoc-*
3040d763cef2SBarry Smith /*@
3041bcf0153eSBarry Smith   TSGetTimeStepNumber - Deprecated, use `TSGetStepNumber()`.
3042edc382c3SSatish Balay 
3043edc382c3SSatish Balay   Level: deprecated
3044edc382c3SSatish Balay 
30455c5f5948SLisandro Dalcin @*/
3046d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetTimeStepNumber(TS ts, PetscInt *steps)
3047d71ae5a4SJacob Faibussowitsch {
30489371c9d4SSatish Balay   return TSGetStepNumber(ts, steps);
30499371c9d4SSatish Balay }
30505c5f5948SLisandro Dalcin 
305114d0ab18SJacob Faibussowitsch // PetscClangLinter pragma disable: -fdoc-*
305219eac22cSLisandro Dalcin /*@
3053bcf0153eSBarry Smith   TSGetTotalSteps - Deprecated, use `TSGetStepNumber()`.
3054edc382c3SSatish Balay 
3055edc382c3SSatish Balay   Level: deprecated
3056edc382c3SSatish Balay 
30574f4e0956SLisandro Dalcin @*/
3058d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetTotalSteps(TS ts, PetscInt *steps)
3059d71ae5a4SJacob Faibussowitsch {
30609371c9d4SSatish Balay   return TSGetStepNumber(ts, steps);
30619371c9d4SSatish Balay }
30624f4e0956SLisandro Dalcin 
30634f4e0956SLisandro Dalcin /*@
3064d763cef2SBarry Smith   TSSetSolution - Sets the initial solution vector
3065bcf0153eSBarry Smith   for use by the `TS` routines.
3066d763cef2SBarry Smith 
3067c3339decSBarry Smith   Logically Collective
3068d763cef2SBarry Smith 
3069d763cef2SBarry Smith   Input Parameters:
3070bcf0153eSBarry Smith + ts - the `TS` context obtained from `TSCreate()`
30710910c330SBarry Smith - u  - the solution vector
3072d763cef2SBarry Smith 
3073d763cef2SBarry Smith   Level: beginner
3074d763cef2SBarry Smith 
30751cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetSolutionFunction()`, `TSGetSolution()`, `TSCreate()`
3076d763cef2SBarry Smith @*/
3077d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetSolution(TS ts, Vec u)
3078d71ae5a4SJacob Faibussowitsch {
3079496e6a7aSJed Brown   DM dm;
30808737fe31SLisandro Dalcin 
3081d763cef2SBarry Smith   PetscFunctionBegin;
30820700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
30830910c330SBarry Smith   PetscValidHeaderSpecific(u, VEC_CLASSID, 2);
30849566063dSJacob Faibussowitsch   PetscCall(PetscObjectReference((PetscObject)u));
30859566063dSJacob Faibussowitsch   PetscCall(VecDestroy(&ts->vec_sol));
30860910c330SBarry Smith   ts->vec_sol = u;
3087bbd56ea5SKarl Rupp 
30889566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
30899566063dSJacob Faibussowitsch   PetscCall(DMShellSetGlobalVector(dm, u));
30903ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
3091d763cef2SBarry Smith }
3092d763cef2SBarry Smith 
3093ac226902SBarry Smith /*@C
3094000e7ae3SMatthew Knepley   TSSetPreStep - Sets the general-purpose function
30953f2090d5SJed Brown   called once at the beginning of each time step.
3096000e7ae3SMatthew Knepley 
3097c3339decSBarry Smith   Logically Collective
3098000e7ae3SMatthew Knepley 
3099000e7ae3SMatthew Knepley   Input Parameters:
3100bcf0153eSBarry Smith + ts   - The `TS` context obtained from `TSCreate()`
3101000e7ae3SMatthew Knepley - func - The function
3102000e7ae3SMatthew Knepley 
310320f4b53cSBarry Smith   Calling sequence of `func`:
310414d0ab18SJacob Faibussowitsch . ts - the `TS` context
3105000e7ae3SMatthew Knepley 
3106000e7ae3SMatthew Knepley   Level: intermediate
3107000e7ae3SMatthew Knepley 
31081cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetPreStage()`, `TSSetPostStage()`, `TSSetPostStep()`, `TSStep()`, `TSRestartStep()`
3109000e7ae3SMatthew Knepley @*/
311014d0ab18SJacob Faibussowitsch PetscErrorCode TSSetPreStep(TS ts, PetscErrorCode (*func)(TS ts))
3111d71ae5a4SJacob Faibussowitsch {
3112000e7ae3SMatthew Knepley   PetscFunctionBegin;
31130700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3114ae60f76fSBarry Smith   ts->prestep = func;
31153ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
3116000e7ae3SMatthew Knepley }
3117000e7ae3SMatthew Knepley 
311809ee8438SJed Brown /*@
3119bcf0153eSBarry Smith   TSPreStep - Runs the user-defined pre-step function provided with `TSSetPreStep()`
31203f2090d5SJed Brown 
3121c3339decSBarry Smith   Collective
31223f2090d5SJed Brown 
31232fe279fdSBarry Smith   Input Parameter:
3124bcf0153eSBarry Smith . ts - The `TS` context obtained from `TSCreate()`
31253f2090d5SJed Brown 
31263f2090d5SJed Brown   Level: developer
31273f2090d5SJed Brown 
3128bcf0153eSBarry Smith   Note:
3129bcf0153eSBarry Smith   `TSPreStep()` is typically used within time stepping implementations,
3130bcf0153eSBarry Smith   so most users would not generally call this routine themselves.
3131bcf0153eSBarry Smith 
31321cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetPreStep()`, `TSPreStage()`, `TSPostStage()`, `TSPostStep()`
31333f2090d5SJed Brown @*/
3134d71ae5a4SJacob Faibussowitsch PetscErrorCode TSPreStep(TS ts)
3135d71ae5a4SJacob Faibussowitsch {
31363f2090d5SJed Brown   PetscFunctionBegin;
31370700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3138ae60f76fSBarry Smith   if (ts->prestep) {
31395efd42a4SStefano Zampini     Vec              U;
3140ef8d1ce0SJohann Rudi     PetscObjectId    idprev;
3141ef8d1ce0SJohann Rudi     PetscBool        sameObject;
31425efd42a4SStefano Zampini     PetscObjectState sprev, spost;
31435efd42a4SStefano Zampini 
31449566063dSJacob Faibussowitsch     PetscCall(TSGetSolution(ts, &U));
31459566063dSJacob Faibussowitsch     PetscCall(PetscObjectGetId((PetscObject)U, &idprev));
31469566063dSJacob Faibussowitsch     PetscCall(PetscObjectStateGet((PetscObject)U, &sprev));
314725e27a38SBarry Smith     PetscCallBack("TS callback preset", (*ts->prestep)(ts));
31489566063dSJacob Faibussowitsch     PetscCall(TSGetSolution(ts, &U));
31499566063dSJacob Faibussowitsch     PetscCall(PetscObjectCompareId((PetscObject)U, idprev, &sameObject));
31509566063dSJacob Faibussowitsch     PetscCall(PetscObjectStateGet((PetscObject)U, &spost));
31519566063dSJacob Faibussowitsch     if (!sameObject || sprev != spost) PetscCall(TSRestartStep(ts));
3152312ce896SJed Brown   }
31533ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
31543f2090d5SJed Brown }
31553f2090d5SJed Brown 
3156b8123daeSJed Brown /*@C
3157b8123daeSJed Brown   TSSetPreStage - Sets the general-purpose function
3158b8123daeSJed Brown   called once at the beginning of each stage.
3159b8123daeSJed Brown 
3160c3339decSBarry Smith   Logically Collective
3161b8123daeSJed Brown 
3162b8123daeSJed Brown   Input Parameters:
3163bcf0153eSBarry Smith + ts   - The `TS` context obtained from `TSCreate()`
3164b8123daeSJed Brown - func - The function
3165b8123daeSJed Brown 
316620f4b53cSBarry Smith   Calling sequence of `func`:
316714d0ab18SJacob Faibussowitsch + ts        - the `TS` context
316814d0ab18SJacob Faibussowitsch - stagetime - the stage time
3169b8123daeSJed Brown 
3170b8123daeSJed Brown   Level: intermediate
3171b8123daeSJed Brown 
3172b8123daeSJed Brown   Note:
3173b8123daeSJed Brown   There may be several stages per time step. If the solve for a given stage fails, the step may be rejected and retried.
3174bcf0153eSBarry Smith   The time step number being computed can be queried using `TSGetStepNumber()` and the total size of the step being
3175bcf0153eSBarry Smith   attempted can be obtained using `TSGetTimeStep()`. The time at the start of the step is available via `TSGetTime()`.
3176b8123daeSJed Brown 
31771cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetPostStage()`, `TSSetPreStep()`, `TSSetPostStep()`, `TSGetApplicationContext()`
3178b8123daeSJed Brown @*/
317914d0ab18SJacob Faibussowitsch PetscErrorCode TSSetPreStage(TS ts, PetscErrorCode (*func)(TS ts, PetscReal stagetime))
3180d71ae5a4SJacob Faibussowitsch {
3181b8123daeSJed Brown   PetscFunctionBegin;
3182b8123daeSJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3183ae60f76fSBarry Smith   ts->prestage = func;
31843ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
3185b8123daeSJed Brown }
3186b8123daeSJed Brown 
31879be3e283SDebojyoti Ghosh /*@C
31880d56bcf9SIlya Fursov   TSSetPostStage - Sets the general-purpose function
31899be3e283SDebojyoti Ghosh   called once at the end of each stage.
31909be3e283SDebojyoti Ghosh 
3191c3339decSBarry Smith   Logically Collective
31929be3e283SDebojyoti Ghosh 
31939be3e283SDebojyoti Ghosh   Input Parameters:
3194bcf0153eSBarry Smith + ts   - The `TS` context obtained from `TSCreate()`
31959be3e283SDebojyoti Ghosh - func - The function
31969be3e283SDebojyoti Ghosh 
319720f4b53cSBarry Smith   Calling sequence of `func`:
319814d0ab18SJacob Faibussowitsch + ts         - the `TS` context
319914d0ab18SJacob Faibussowitsch . stagetime  - the stage time
320014d0ab18SJacob Faibussowitsch . stageindex - the stage index
320114d0ab18SJacob Faibussowitsch - Y          - Array of vectors (of size = total number of stages) with the stage solutions
32029be3e283SDebojyoti Ghosh 
32039be3e283SDebojyoti Ghosh   Level: intermediate
32049be3e283SDebojyoti Ghosh 
32059be3e283SDebojyoti Ghosh   Note:
32069be3e283SDebojyoti Ghosh   There may be several stages per time step. If the solve for a given stage fails, the step may be rejected and retried.
3207bcf0153eSBarry Smith   The time step number being computed can be queried using `TSGetStepNumber()` and the total size of the step being
3208bcf0153eSBarry Smith   attempted can be obtained using `TSGetTimeStep()`. The time at the start of the step is available via `TSGetTime()`.
32099be3e283SDebojyoti Ghosh 
32101cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetPreStage()`, `TSSetPreStep()`, `TSSetPostStep()`, `TSGetApplicationContext()`
32119be3e283SDebojyoti Ghosh @*/
321214d0ab18SJacob Faibussowitsch PetscErrorCode TSSetPostStage(TS ts, PetscErrorCode (*func)(TS ts, PetscReal stagetime, PetscInt stageindex, Vec *Y))
3213d71ae5a4SJacob Faibussowitsch {
32149be3e283SDebojyoti Ghosh   PetscFunctionBegin;
32159be3e283SDebojyoti Ghosh   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
32169be3e283SDebojyoti Ghosh   ts->poststage = func;
32173ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
32189be3e283SDebojyoti Ghosh }
32199be3e283SDebojyoti Ghosh 
3220c688d042SShri Abhyankar /*@C
3221c688d042SShri Abhyankar   TSSetPostEvaluate - Sets the general-purpose function
32220d56bcf9SIlya Fursov   called at the end of each step evaluation.
3223c688d042SShri Abhyankar 
3224c3339decSBarry Smith   Logically Collective
3225c688d042SShri Abhyankar 
3226c688d042SShri Abhyankar   Input Parameters:
3227bcf0153eSBarry Smith + ts   - The `TS` context obtained from `TSCreate()`
3228c688d042SShri Abhyankar - func - The function
3229c688d042SShri Abhyankar 
323020f4b53cSBarry Smith   Calling sequence of `func`:
323114d0ab18SJacob Faibussowitsch . ts - the `TS` context
3232c688d042SShri Abhyankar 
3233c688d042SShri Abhyankar   Level: intermediate
3234c688d042SShri Abhyankar 
3235c688d042SShri Abhyankar   Note:
32360d56bcf9SIlya Fursov   The function set by `TSSetPostEvaluate()` is called after the solution is evaluated, or after the step rollback.
32370d56bcf9SIlya Fursov   Inside the `func` callback, the solution vector can be obtained with `TSGetSolution()`, and modified, if need be.
32380d56bcf9SIlya Fursov   The time step can be obtained with `TSGetTimeStep()`, and the time at the start of the step - via `TSGetTime()`.
32390d56bcf9SIlya Fursov   The potential changes to the solution vector introduced by event handling (`postevent()`) are not relevant for `TSSetPostEvaluate()`,
32400d56bcf9SIlya Fursov   but are relevant for `TSSetPostStep()`, according to the function call scheme in `TSSolve()`, as shown below
32410d56bcf9SIlya Fursov .vb
32420d56bcf9SIlya Fursov   ...
32430d56bcf9SIlya Fursov   Step()
32440d56bcf9SIlya Fursov   PostEvaluate()
32450d56bcf9SIlya Fursov   EventHandling()
32460d56bcf9SIlya Fursov   step_rollback ? PostEvaluate() : PostStep()
32470d56bcf9SIlya Fursov   ...
32480d56bcf9SIlya Fursov .ve
32490d56bcf9SIlya Fursov   where EventHandling() may result in one of the following three outcomes
32500d56bcf9SIlya Fursov .vb
32510d56bcf9SIlya Fursov   (1) | successful step | solution intact
32520d56bcf9SIlya Fursov   (2) | successful step | solution modified by `postevent()`
32530d56bcf9SIlya Fursov   (3) | step_rollback   | solution rolled back
32540d56bcf9SIlya Fursov .ve
3255c688d042SShri Abhyankar 
32561cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetPreStage()`, `TSSetPreStep()`, `TSSetPostStep()`, `TSGetApplicationContext()`
3257c688d042SShri Abhyankar @*/
325814d0ab18SJacob Faibussowitsch PetscErrorCode TSSetPostEvaluate(TS ts, PetscErrorCode (*func)(TS ts))
3259d71ae5a4SJacob Faibussowitsch {
3260c688d042SShri Abhyankar   PetscFunctionBegin;
3261c688d042SShri Abhyankar   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3262c688d042SShri Abhyankar   ts->postevaluate = func;
32633ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
3264c688d042SShri Abhyankar }
3265c688d042SShri Abhyankar 
3266b8123daeSJed Brown /*@
3267bcf0153eSBarry Smith   TSPreStage - Runs the user-defined pre-stage function set using `TSSetPreStage()`
3268b8123daeSJed Brown 
3269c3339decSBarry Smith   Collective
3270b8123daeSJed Brown 
3271b8123daeSJed Brown   Input Parameters:
327214d0ab18SJacob Faibussowitsch + ts        - The `TS` context obtained from `TSCreate()`
327314d0ab18SJacob Faibussowitsch - stagetime - The absolute time of the current stage
3274b8123daeSJed Brown 
3275b8123daeSJed Brown   Level: developer
3276b8123daeSJed Brown 
3277bcf0153eSBarry Smith   Note:
3278bcf0153eSBarry Smith   `TSPreStage()` is typically used within time stepping implementations,
3279bcf0153eSBarry Smith   most users would not generally call this routine themselves.
3280bcf0153eSBarry Smith 
32811cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSPostStage()`, `TSSetPreStep()`, `TSPreStep()`, `TSPostStep()`
3282b8123daeSJed Brown @*/
3283d71ae5a4SJacob Faibussowitsch PetscErrorCode TSPreStage(TS ts, PetscReal stagetime)
3284d71ae5a4SJacob Faibussowitsch {
3285b8123daeSJed Brown   PetscFunctionBegin;
3286b8123daeSJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
32871e66621cSBarry Smith   if (ts->prestage) PetscCallBack("TS callback prestage", (*ts->prestage)(ts, stagetime));
32883ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
3289b8123daeSJed Brown }
3290b8123daeSJed Brown 
32919be3e283SDebojyoti Ghosh /*@
3292bcf0153eSBarry Smith   TSPostStage - Runs the user-defined post-stage function set using `TSSetPostStage()`
32939be3e283SDebojyoti Ghosh 
3294c3339decSBarry Smith   Collective
32959be3e283SDebojyoti Ghosh 
32969be3e283SDebojyoti Ghosh   Input Parameters:
329714d0ab18SJacob Faibussowitsch + ts         - The `TS` context obtained from `TSCreate()`
329814d0ab18SJacob Faibussowitsch . stagetime  - The absolute time of the current stage
329914d0ab18SJacob Faibussowitsch . stageindex - Stage number
330014d0ab18SJacob Faibussowitsch - Y          - Array of vectors (of size = total number of stages) with the stage solutions
33019be3e283SDebojyoti Ghosh 
33029be3e283SDebojyoti Ghosh   Level: developer
33039be3e283SDebojyoti Ghosh 
3304bcf0153eSBarry Smith   Note:
3305bcf0153eSBarry Smith   `TSPostStage()` is typically used within time stepping implementations,
3306bcf0153eSBarry Smith   most users would not generally call this routine themselves.
3307bcf0153eSBarry Smith 
33081cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSPreStage()`, `TSSetPreStep()`, `TSPreStep()`, `TSPostStep()`
33099be3e283SDebojyoti Ghosh @*/
33100fc7ecceSBarry Smith PetscErrorCode TSPostStage(TS ts, PetscReal stagetime, PetscInt stageindex, Vec Y[])
3311d71ae5a4SJacob Faibussowitsch {
33129be3e283SDebojyoti Ghosh   PetscFunctionBegin;
33139be3e283SDebojyoti Ghosh   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
33141e66621cSBarry Smith   if (ts->poststage) PetscCallBack("TS callback poststage", (*ts->poststage)(ts, stagetime, stageindex, Y));
33153ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
33169be3e283SDebojyoti Ghosh }
33179be3e283SDebojyoti Ghosh 
3318c688d042SShri Abhyankar /*@
3319bcf0153eSBarry Smith   TSPostEvaluate - Runs the user-defined post-evaluate function set using `TSSetPostEvaluate()`
3320c688d042SShri Abhyankar 
3321c3339decSBarry Smith   Collective
3322c688d042SShri Abhyankar 
33232fe279fdSBarry Smith   Input Parameter:
3324bcf0153eSBarry Smith . ts - The `TS` context obtained from `TSCreate()`
3325c688d042SShri Abhyankar 
3326c688d042SShri Abhyankar   Level: developer
3327c688d042SShri Abhyankar 
3328bcf0153eSBarry Smith   Note:
3329bcf0153eSBarry Smith   `TSPostEvaluate()` is typically used within time stepping implementations,
3330bcf0153eSBarry Smith   most users would not generally call this routine themselves.
3331bcf0153eSBarry Smith 
33321cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetPostEvaluate()`, `TSSetPreStep()`, `TSPreStep()`, `TSPostStep()`
3333c688d042SShri Abhyankar @*/
3334d71ae5a4SJacob Faibussowitsch PetscErrorCode TSPostEvaluate(TS ts)
3335d71ae5a4SJacob Faibussowitsch {
3336c688d042SShri Abhyankar   PetscFunctionBegin;
3337c688d042SShri Abhyankar   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3338c688d042SShri Abhyankar   if (ts->postevaluate) {
3339dcb233daSLisandro Dalcin     Vec              U;
3340dcb233daSLisandro Dalcin     PetscObjectState sprev, spost;
3341dcb233daSLisandro Dalcin 
33429566063dSJacob Faibussowitsch     PetscCall(TSGetSolution(ts, &U));
33439566063dSJacob Faibussowitsch     PetscCall(PetscObjectStateGet((PetscObject)U, &sprev));
334425e27a38SBarry Smith     PetscCallBack("TS callback postevaluate", (*ts->postevaluate)(ts));
33459566063dSJacob Faibussowitsch     PetscCall(PetscObjectStateGet((PetscObject)U, &spost));
33469566063dSJacob Faibussowitsch     if (sprev != spost) PetscCall(TSRestartStep(ts));
3347c688d042SShri Abhyankar   }
33483ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
3349c688d042SShri Abhyankar }
3350c688d042SShri Abhyankar 
3351ac226902SBarry Smith /*@C
3352000e7ae3SMatthew Knepley   TSSetPostStep - Sets the general-purpose function
33530d56bcf9SIlya Fursov   called once at the end of each successful time step.
3354000e7ae3SMatthew Knepley 
3355c3339decSBarry Smith   Logically Collective
3356000e7ae3SMatthew Knepley 
3357000e7ae3SMatthew Knepley   Input Parameters:
3358bcf0153eSBarry Smith + ts   - The `TS` context obtained from `TSCreate()`
3359000e7ae3SMatthew Knepley - func - The function
3360000e7ae3SMatthew Knepley 
336120f4b53cSBarry Smith   Calling sequence of `func`:
336214d0ab18SJacob Faibussowitsch . ts - the `TS` context
3363000e7ae3SMatthew Knepley 
3364000e7ae3SMatthew Knepley   Level: intermediate
3365000e7ae3SMatthew Knepley 
3366bcf0153eSBarry Smith   Note:
33670d56bcf9SIlya Fursov   The function set by `TSSetPostStep()` is called after each successful step. If the event handler locates an event at the
33680d56bcf9SIlya Fursov   given step, and `postevent()` modifies the solution vector, the solution vector obtained by `TSGetSolution()` inside `func` will
33690d56bcf9SIlya Fursov   contain the changes. To get the solution without these changes, use `TSSetPostEvaluate()` to set the appropriate callback.
33700d56bcf9SIlya Fursov   The scheme of the relevant function calls in `TSSolve()` is shown below
33710d56bcf9SIlya Fursov .vb
33720d56bcf9SIlya Fursov   ...
33730d56bcf9SIlya Fursov   Step()
33740d56bcf9SIlya Fursov   PostEvaluate()
33750d56bcf9SIlya Fursov   EventHandling()
33760d56bcf9SIlya Fursov   step_rollback ? PostEvaluate() : PostStep()
33770d56bcf9SIlya Fursov   ...
33780d56bcf9SIlya Fursov .ve
33790d56bcf9SIlya Fursov   where EventHandling() may result in one of the following three outcomes
33800d56bcf9SIlya Fursov .vb
33810d56bcf9SIlya Fursov   (1) | successful step | solution intact
33820d56bcf9SIlya Fursov   (2) | successful step | solution modified by `postevent()`
33830d56bcf9SIlya Fursov   (3) | step_rollback   | solution rolled back
33840d56bcf9SIlya Fursov .ve
3385bcf0153eSBarry Smith 
33861cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetPreStep()`, `TSSetPreStage()`, `TSSetPostEvaluate()`, `TSGetTimeStep()`, `TSGetStepNumber()`, `TSGetTime()`, `TSRestartStep()`
3387000e7ae3SMatthew Knepley @*/
338814d0ab18SJacob Faibussowitsch PetscErrorCode TSSetPostStep(TS ts, PetscErrorCode (*func)(TS ts))
3389d71ae5a4SJacob Faibussowitsch {
3390000e7ae3SMatthew Knepley   PetscFunctionBegin;
33910700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3392ae60f76fSBarry Smith   ts->poststep = func;
33933ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
3394000e7ae3SMatthew Knepley }
3395000e7ae3SMatthew Knepley 
339609ee8438SJed Brown /*@
3397195e9b02SBarry Smith   TSPostStep - Runs the user-defined post-step function that was set with `TSSetPostStep()`
33983f2090d5SJed Brown 
3399c3339decSBarry Smith   Collective
34003f2090d5SJed Brown 
34012fe279fdSBarry Smith   Input Parameter:
3402bcf0153eSBarry Smith . ts - The `TS` context obtained from `TSCreate()`
34033f2090d5SJed Brown 
3404bcf0153eSBarry Smith   Note:
3405bcf0153eSBarry Smith   `TSPostStep()` is typically used within time stepping implementations,
34063f2090d5SJed Brown   so most users would not generally call this routine themselves.
34073f2090d5SJed Brown 
34083f2090d5SJed Brown   Level: developer
34093f2090d5SJed Brown 
3410bfe80ac4SPierre Jolivet .seealso: [](ch_ts), `TS`, `TSSetPreStep()`, `TSSetPreStage()`, `TSSetPostEvaluate()`, `TSGetTimeStep()`, `TSGetStepNumber()`, `TSGetTime()`, `TSSetPostStep()`
34113f2090d5SJed Brown @*/
3412d71ae5a4SJacob Faibussowitsch PetscErrorCode TSPostStep(TS ts)
3413d71ae5a4SJacob Faibussowitsch {
34143f2090d5SJed Brown   PetscFunctionBegin;
34150700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3416ae60f76fSBarry Smith   if (ts->poststep) {
34175efd42a4SStefano Zampini     Vec              U;
3418ef8d1ce0SJohann Rudi     PetscObjectId    idprev;
3419ef8d1ce0SJohann Rudi     PetscBool        sameObject;
34205efd42a4SStefano Zampini     PetscObjectState sprev, spost;
34215efd42a4SStefano Zampini 
34229566063dSJacob Faibussowitsch     PetscCall(TSGetSolution(ts, &U));
34239566063dSJacob Faibussowitsch     PetscCall(PetscObjectGetId((PetscObject)U, &idprev));
34249566063dSJacob Faibussowitsch     PetscCall(PetscObjectStateGet((PetscObject)U, &sprev));
342525e27a38SBarry Smith     PetscCallBack("TS callback poststep", (*ts->poststep)(ts));
34269566063dSJacob Faibussowitsch     PetscCall(TSGetSolution(ts, &U));
34279566063dSJacob Faibussowitsch     PetscCall(PetscObjectCompareId((PetscObject)U, idprev, &sameObject));
34289566063dSJacob Faibussowitsch     PetscCall(PetscObjectStateGet((PetscObject)U, &spost));
34299566063dSJacob Faibussowitsch     if (!sameObject || sprev != spost) PetscCall(TSRestartStep(ts));
343072ac3e02SJed Brown   }
34313ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
34323f2090d5SJed Brown }
34333f2090d5SJed Brown 
3434cd652676SJed Brown /*@
3435cd652676SJed Brown   TSInterpolate - Interpolate the solution computed during the previous step to an arbitrary location in the interval
3436cd652676SJed Brown 
3437c3339decSBarry Smith   Collective
3438cd652676SJed Brown 
34394165533cSJose E. Roman   Input Parameters:
3440cd652676SJed Brown + ts - time stepping context
3441cd652676SJed Brown - t  - time to interpolate to
3442cd652676SJed Brown 
34434165533cSJose E. Roman   Output Parameter:
34440910c330SBarry Smith . U - state at given time
3445cd652676SJed Brown 
3446cd652676SJed Brown   Level: intermediate
3447cd652676SJed Brown 
3448b43aa488SJacob Faibussowitsch   Developer Notes:
3449bcf0153eSBarry Smith   `TSInterpolate()` and the storing of previous steps/stages should be generalized to support delay differential equations and continuous adjoints.
3450cd652676SJed Brown 
34511cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetExactFinalTime()`, `TSSolve()`
3452cd652676SJed Brown @*/
3453d71ae5a4SJacob Faibussowitsch PetscErrorCode TSInterpolate(TS ts, PetscReal t, Vec U)
3454d71ae5a4SJacob Faibussowitsch {
3455cd652676SJed Brown   PetscFunctionBegin;
3456cd652676SJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3457b06615a5SLisandro Dalcin   PetscValidHeaderSpecific(U, VEC_CLASSID, 3);
345863a3b9bcSJacob 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);
3459dbbe0bcdSBarry Smith   PetscUseTypeMethod(ts, interpolate, t, U);
34603ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
3461cd652676SJed Brown }
3462cd652676SJed Brown 
3463d763cef2SBarry Smith /*@
34646d9e5789SSean Farley   TSStep - Steps one time step
3465d763cef2SBarry Smith 
3466c3339decSBarry Smith   Collective
3467d763cef2SBarry Smith 
3468d763cef2SBarry Smith   Input Parameter:
3469bcf0153eSBarry Smith . ts - the `TS` context obtained from `TSCreate()`
3470d763cef2SBarry Smith 
347127829d71SBarry Smith   Level: developer
3472d763cef2SBarry Smith 
3473b8123daeSJed Brown   Notes:
3474bcf0153eSBarry Smith   The public interface for the ODE/DAE solvers is `TSSolve()`, you should almost for sure be using that routine and not this routine.
347527829d71SBarry Smith 
3476bcf0153eSBarry Smith   The hook set using `TSSetPreStep()` is called before each attempt to take the step. In general, the time step size may
3477b8123daeSJed Brown   be changed due to adaptive error controller or solve failures. Note that steps may contain multiple stages.
3478b8123daeSJed Brown 
3479bcf0153eSBarry Smith   This may over-step the final time provided in `TSSetMaxTime()` depending on the time-step used. `TSSolve()` interpolates to exactly the
3480bcf0153eSBarry Smith   time provided in `TSSetMaxTime()`. One can use `TSInterpolate()` to determine an interpolated solution within the final timestep.
348125cb2221SBarry Smith 
34821cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSCreate()`, `TSSetUp()`, `TSDestroy()`, `TSSolve()`, `TSSetPreStep()`, `TSSetPreStage()`, `TSSetPostStage()`, `TSInterpolate()`
3483d763cef2SBarry Smith @*/
3484d71ae5a4SJacob Faibussowitsch PetscErrorCode TSStep(TS ts)
3485d71ae5a4SJacob Faibussowitsch {
3486fffbeea8SBarry Smith   static PetscBool cite = PETSC_FALSE;
3487be5899b3SLisandro Dalcin   PetscReal        ptime;
3488d763cef2SBarry Smith 
3489d763cef2SBarry Smith   PetscFunctionBegin;
34900700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3491d0609cedSBarry Smith   PetscCall(PetscCitationsRegister("@article{tspaper,\n"
3492fffbeea8SBarry Smith                                    "  title         = {{PETSc/TS}: A Modern Scalable {DAE/ODE} Solver Library},\n"
3493f1d62c27SHong Zhang                                    "  author        = {Abhyankar, Shrirang and Brown, Jed and Constantinescu, Emil and Ghosh, Debojyoti and Smith, Barry F. and Zhang, Hong},\n"
3494f1d62c27SHong Zhang                                    "  journal       = {arXiv e-preprints},\n"
3495f1d62c27SHong Zhang                                    "  eprint        = {1806.01437},\n"
3496f1d62c27SHong Zhang                                    "  archivePrefix = {arXiv},\n"
34979371c9d4SSatish Balay                                    "  year          = {2018}\n}\n",
34989371c9d4SSatish Balay                                    &cite));
34999566063dSJacob Faibussowitsch   PetscCall(TSSetUp(ts));
35009566063dSJacob Faibussowitsch   PetscCall(TSTrajectorySetUp(ts->trajectory, ts));
3501136cf249SJames Wright   if (ts->eval_times)
3502136cf249SJames Wright     ts->eval_times->worktol = 0; /* In each step of TSSolve() 'eval_times->worktol' will be meaningfully defined (later) only once:
3503ca4445c7SIlya Fursov                                                    in TSAdaptChoose() or TSEvent_dt_cap(), and then reused till the end of the step */
3504d405a339SMatthew Knepley 
35058e562f8dSJames Wright   PetscCheck(ts->max_time < PETSC_MAX_REAL || ts->run_steps != PETSC_INT_MAX || ts->max_steps != PETSC_INT_MAX, PetscObjectComm((PetscObject)ts), PETSC_ERR_ARG_WRONGSTATE, "You must call TSSetMaxTime(), TSSetMaxSteps(), or TSSetRunSteps() or use -ts_max_time <time>, -ts_max_steps <steps>, -ts_run_steps <steps>");
35063c633725SBarry 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()");
35073c633725SBarry 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");
3508a6772fa2SLisandro Dalcin 
3509c61711c8SStefano Zampini   if (!ts->vec_sol0) PetscCall(VecDuplicate(ts->vec_sol, &ts->vec_sol0));
3510c61711c8SStefano Zampini   PetscCall(VecCopy(ts->vec_sol, ts->vec_sol0));
3511c61711c8SStefano Zampini   ts->time_step0 = ts->time_step;
3512c61711c8SStefano Zampini 
3513be5899b3SLisandro Dalcin   if (!ts->steps) ts->ptime_prev = ts->ptime;
35149371c9d4SSatish Balay   ptime = ts->ptime;
3515c61711c8SStefano Zampini 
35169371c9d4SSatish Balay   ts->ptime_prev_rollback = ts->ptime_prev;
35172808aa04SLisandro Dalcin   ts->reason              = TS_CONVERGED_ITERATING;
3518fc8dbba5SLisandro Dalcin 
35199566063dSJacob Faibussowitsch   PetscCall(PetscLogEventBegin(TS_Step, ts, 0, 0, 0));
3520dbbe0bcdSBarry Smith   PetscUseTypeMethod(ts, step);
35219566063dSJacob Faibussowitsch   PetscCall(PetscLogEventEnd(TS_Step, ts, 0, 0, 0));
3522fc8dbba5SLisandro Dalcin 
3523fc8dbba5SLisandro Dalcin   if (ts->reason >= 0) {
3524be5899b3SLisandro Dalcin     ts->ptime_prev = ptime;
35252808aa04SLisandro Dalcin     ts->steps++;
3526be5899b3SLisandro Dalcin     ts->steprollback = PETSC_FALSE;
352728d5b5d6SLisandro Dalcin     ts->steprestart  = PETSC_FALSE;
3528c6bf8827SStefano Zampini     ts->stepresize   = PETSC_FALSE;
3529d2daff3dSHong Zhang   }
3530fc8dbba5SLisandro Dalcin 
35315c9bbc89SJed Brown   if (ts->reason < 0 && ts->errorifstepfailed) {
35325c9bbc89SJed Brown     PetscCall(TSMonitorCancel(ts));
3533*764c9dfdSStefano Zampini     if (ts->usessnes && ts->snes) PetscCall(SNESMonitorCancel(ts->snes));
353409cb0f53SBarry Smith     PetscCheck(ts->reason != TS_DIVERGED_NONLINEAR_SOLVE, PetscObjectComm((PetscObject)ts), PETSC_ERR_NOT_CONVERGED, "TSStep has failed due to %s, increase -ts_max_snes_failures or use unlimited to attempt recovery", TSConvergedReasons[ts->reason]);
35355c9bbc89SJed Brown     SETERRQ(PetscObjectComm((PetscObject)ts), PETSC_ERR_NOT_CONVERGED, "TSStep has failed due to %s", TSConvergedReasons[ts->reason]);
35365c9bbc89SJed Brown   }
35373ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
353808c7845fSBarry Smith }
353908c7845fSBarry Smith 
354008c7845fSBarry Smith /*@
35417cbde773SLisandro Dalcin   TSEvaluateWLTE - Evaluate the weighted local truncation error norm
35427cbde773SLisandro Dalcin   at the end of a time step with a given order of accuracy.
35437cbde773SLisandro Dalcin 
3544c3339decSBarry Smith   Collective
35457cbde773SLisandro Dalcin 
35464165533cSJose E. Roman   Input Parameters:
35477cbde773SLisandro Dalcin + ts        - time stepping context
3548bcf0153eSBarry Smith - wnormtype - norm type, either `NORM_2` or `NORM_INFINITY`
35497cbde773SLisandro Dalcin 
355097bb3fdcSJose E. Roman   Input/Output Parameter:
3551bcf0153eSBarry Smith . order - optional, desired order for the error evaluation or `PETSC_DECIDE`;
355297bb3fdcSJose E. Roman            on output, the actual order of the error evaluation
355397bb3fdcSJose E. Roman 
355497bb3fdcSJose E. Roman   Output Parameter:
355597bb3fdcSJose E. Roman . wlte - the weighted local truncation error norm
35567cbde773SLisandro Dalcin 
35577cbde773SLisandro Dalcin   Level: advanced
35587cbde773SLisandro Dalcin 
3559bcf0153eSBarry Smith   Note:
35607cbde773SLisandro Dalcin   If the timestepper cannot evaluate the error in a particular step
35617cbde773SLisandro Dalcin   (eg. in the first step or restart steps after event handling),
35627cbde773SLisandro Dalcin   this routine returns wlte=-1.0 .
35637cbde773SLisandro Dalcin 
35641cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSStep()`, `TSAdapt`, `TSErrorWeightedNorm()`
35657cbde773SLisandro Dalcin @*/
3566d71ae5a4SJacob Faibussowitsch PetscErrorCode TSEvaluateWLTE(TS ts, NormType wnormtype, PetscInt *order, PetscReal *wlte)
3567d71ae5a4SJacob Faibussowitsch {
35687cbde773SLisandro Dalcin   PetscFunctionBegin;
35697cbde773SLisandro Dalcin   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
35707cbde773SLisandro Dalcin   PetscValidType(ts, 1);
3571064a246eSJacob Faibussowitsch   PetscValidLogicalCollectiveEnum(ts, wnormtype, 2);
35724f572ea9SToby Isaac   if (order) PetscAssertPointer(order, 3);
35737cbde773SLisandro Dalcin   if (order) PetscValidLogicalCollectiveInt(ts, *order, 3);
35744f572ea9SToby Isaac   PetscAssertPointer(wlte, 4);
35753c633725SBarry Smith   PetscCheck(wnormtype == NORM_2 || wnormtype == NORM_INFINITY, PetscObjectComm((PetscObject)ts), PETSC_ERR_SUP, "No support for norm type %s", NormTypes[wnormtype]);
3576dbbe0bcdSBarry Smith   PetscUseTypeMethod(ts, evaluatewlte, wnormtype, order, wlte);
35773ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
35787cbde773SLisandro Dalcin }
35797cbde773SLisandro Dalcin 
358005175c85SJed Brown /*@
358105175c85SJed Brown   TSEvaluateStep - Evaluate the solution at the end of a time step with a given order of accuracy.
358205175c85SJed Brown 
3583c3339decSBarry Smith   Collective
358405175c85SJed Brown 
35854165533cSJose E. Roman   Input Parameters:
35861c3436cfSJed Brown + ts    - time stepping context
35871c3436cfSJed Brown . order - desired order of accuracy
3588195e9b02SBarry Smith - done  - whether the step was evaluated at this order (pass `NULL` to generate an error if not available)
358905175c85SJed Brown 
35904165533cSJose E. Roman   Output Parameter:
35910910c330SBarry Smith . U - state at the end of the current step
359205175c85SJed Brown 
359305175c85SJed Brown   Level: advanced
359405175c85SJed Brown 
3595108c343cSJed Brown   Notes:
3596108c343cSJed Brown   This function cannot be called until all stages have been evaluated.
3597108c343cSJed Brown 
3598bcf0153eSBarry 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.
3599bcf0153eSBarry Smith 
36001cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSStep()`, `TSAdapt`
360105175c85SJed Brown @*/
3602d71ae5a4SJacob Faibussowitsch PetscErrorCode TSEvaluateStep(TS ts, PetscInt order, Vec U, PetscBool *done)
3603d71ae5a4SJacob Faibussowitsch {
360405175c85SJed Brown   PetscFunctionBegin;
360505175c85SJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
360605175c85SJed Brown   PetscValidType(ts, 1);
36070910c330SBarry Smith   PetscValidHeaderSpecific(U, VEC_CLASSID, 3);
3608dbbe0bcdSBarry Smith   PetscUseTypeMethod(ts, evaluatestep, order, U, done);
36093ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
361005175c85SJed Brown }
361105175c85SJed Brown 
3612aad739acSMatthew G. Knepley /*@C
36132e61be88SMatthew G. Knepley   TSGetComputeInitialCondition - Get the function used to automatically compute an initial condition for the timestepping.
3614aad739acSMatthew G. Knepley 
3615aad739acSMatthew G. Knepley   Not collective
3616aad739acSMatthew G. Knepley 
36174165533cSJose E. Roman   Input Parameter:
3618aad739acSMatthew G. Knepley . ts - time stepping context
3619aad739acSMatthew G. Knepley 
36204165533cSJose E. Roman   Output Parameter:
3621b43aa488SJacob Faibussowitsch . initCondition - The function which computes an initial condition
3622aad739acSMatthew G. Knepley 
362320f4b53cSBarry Smith   Calling sequence of `initCondition`:
362420f4b53cSBarry Smith + ts - The timestepping context
362520f4b53cSBarry Smith - u  - The input vector in which the initial condition is stored
3626bcf0153eSBarry Smith 
3627aad739acSMatthew G. Knepley   Level: advanced
3628aad739acSMatthew G. Knepley 
36291cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetComputeInitialCondition()`, `TSComputeInitialCondition()`
3630aad739acSMatthew G. Knepley @*/
363114d0ab18SJacob Faibussowitsch PetscErrorCode TSGetComputeInitialCondition(TS ts, PetscErrorCode (**initCondition)(TS ts, Vec u))
3632d71ae5a4SJacob Faibussowitsch {
3633aad739acSMatthew G. Knepley   PetscFunctionBegin;
3634aad739acSMatthew G. Knepley   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
36354f572ea9SToby Isaac   PetscAssertPointer(initCondition, 2);
36362e61be88SMatthew G. Knepley   *initCondition = ts->ops->initcondition;
36373ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
3638aad739acSMatthew G. Knepley }
3639aad739acSMatthew G. Knepley 
3640aad739acSMatthew G. Knepley /*@C
36412e61be88SMatthew G. Knepley   TSSetComputeInitialCondition - Set the function used to automatically compute an initial condition for the timestepping.
3642aad739acSMatthew G. Knepley 
3643c3339decSBarry Smith   Logically collective
3644aad739acSMatthew G. Knepley 
36454165533cSJose E. Roman   Input Parameters:
3646aad739acSMatthew G. Knepley + ts            - time stepping context
36472e61be88SMatthew G. Knepley - initCondition - The function which computes an initial condition
3648aad739acSMatthew G. Knepley 
364920f4b53cSBarry Smith   Calling sequence of `initCondition`:
3650a96d6ef6SBarry Smith + ts - The timestepping context
365114d0ab18SJacob Faibussowitsch - e  - The input vector in which the initial condition is to be stored
3652aad739acSMatthew G. Knepley 
3653bcf0153eSBarry Smith   Level: advanced
3654bcf0153eSBarry Smith 
36551cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSGetComputeInitialCondition()`, `TSComputeInitialCondition()`
3656aad739acSMatthew G. Knepley @*/
365714d0ab18SJacob Faibussowitsch PetscErrorCode TSSetComputeInitialCondition(TS ts, PetscErrorCode (*initCondition)(TS ts, Vec e))
3658d71ae5a4SJacob Faibussowitsch {
3659aad739acSMatthew G. Knepley   PetscFunctionBegin;
3660aad739acSMatthew G. Knepley   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
36612e61be88SMatthew G. Knepley   PetscValidFunction(initCondition, 2);
36622e61be88SMatthew G. Knepley   ts->ops->initcondition = initCondition;
36633ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
3664aad739acSMatthew G. Knepley }
3665aad739acSMatthew G. Knepley 
3666aad739acSMatthew G. Knepley /*@
3667bcf0153eSBarry Smith   TSComputeInitialCondition - Compute an initial condition for the timestepping using the function previously set with `TSSetComputeInitialCondition()`
3668aad739acSMatthew G. Knepley 
3669c3339decSBarry Smith   Collective
3670aad739acSMatthew G. Knepley 
36714165533cSJose E. Roman   Input Parameters:
3672aad739acSMatthew G. Knepley + ts - time stepping context
3673bcf0153eSBarry Smith - u  - The `Vec` to store the condition in which will be used in `TSSolve()`
3674aad739acSMatthew G. Knepley 
3675aad739acSMatthew G. Knepley   Level: advanced
3676aad739acSMatthew G. Knepley 
36771cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSGetComputeInitialCondition()`, `TSSetComputeInitialCondition()`, `TSSolve()`
3678aad739acSMatthew G. Knepley @*/
3679d71ae5a4SJacob Faibussowitsch PetscErrorCode TSComputeInitialCondition(TS ts, Vec u)
3680d71ae5a4SJacob Faibussowitsch {
3681aad739acSMatthew G. Knepley   PetscFunctionBegin;
3682aad739acSMatthew G. Knepley   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3683aad739acSMatthew G. Knepley   PetscValidHeaderSpecific(u, VEC_CLASSID, 2);
3684dbbe0bcdSBarry Smith   PetscTryTypeMethod(ts, initcondition, u);
36853ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
3686aad739acSMatthew G. Knepley }
3687aad739acSMatthew G. Knepley 
3688aad739acSMatthew G. Knepley /*@C
3689aad739acSMatthew G. Knepley   TSGetComputeExactError - Get the function used to automatically compute the exact error for the timestepping.
3690aad739acSMatthew G. Knepley 
3691aad739acSMatthew G. Knepley   Not collective
3692aad739acSMatthew G. Knepley 
36934165533cSJose E. Roman   Input Parameter:
3694aad739acSMatthew G. Knepley . ts - time stepping context
3695aad739acSMatthew G. Knepley 
36964165533cSJose E. Roman   Output Parameter:
3697aad739acSMatthew G. Knepley . exactError - The function which computes the solution error
3698aad739acSMatthew G. Knepley 
369920f4b53cSBarry Smith   Calling sequence of `exactError`:
3700a96d6ef6SBarry Smith + ts - The timestepping context
3701a96d6ef6SBarry Smith . u  - The approximate solution vector
370220f4b53cSBarry Smith - e  - The vector in which the error is stored
3703aad739acSMatthew G. Knepley 
3704bcf0153eSBarry Smith   Level: advanced
3705bcf0153eSBarry Smith 
370642747ad1SJacob Faibussowitsch .seealso: [](ch_ts), `TS`, `TSComputeExactError()`
3707aad739acSMatthew G. Knepley @*/
370814d0ab18SJacob Faibussowitsch PetscErrorCode TSGetComputeExactError(TS ts, PetscErrorCode (**exactError)(TS ts, Vec u, Vec e))
3709d71ae5a4SJacob Faibussowitsch {
3710aad739acSMatthew G. Knepley   PetscFunctionBegin;
3711aad739acSMatthew G. Knepley   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
37124f572ea9SToby Isaac   PetscAssertPointer(exactError, 2);
3713aad739acSMatthew G. Knepley   *exactError = ts->ops->exacterror;
37143ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
3715aad739acSMatthew G. Knepley }
3716aad739acSMatthew G. Knepley 
3717aad739acSMatthew G. Knepley /*@C
3718aad739acSMatthew G. Knepley   TSSetComputeExactError - Set the function used to automatically compute the exact error for the timestepping.
3719aad739acSMatthew G. Knepley 
3720c3339decSBarry Smith   Logically collective
3721aad739acSMatthew G. Knepley 
37224165533cSJose E. Roman   Input Parameters:
3723aad739acSMatthew G. Knepley + ts         - time stepping context
3724aad739acSMatthew G. Knepley - exactError - The function which computes the solution error
3725aad739acSMatthew G. Knepley 
372620f4b53cSBarry Smith   Calling sequence of `exactError`:
3727a96d6ef6SBarry Smith + ts - The timestepping context
3728a96d6ef6SBarry Smith . u  - The approximate solution vector
372920f4b53cSBarry Smith - e  - The  vector in which the error is stored
3730aad739acSMatthew G. Knepley 
3731bcf0153eSBarry Smith   Level: advanced
3732bcf0153eSBarry Smith 
37331cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSGetComputeExactError()`, `TSComputeExactError()`
3734aad739acSMatthew G. Knepley @*/
373514d0ab18SJacob Faibussowitsch PetscErrorCode TSSetComputeExactError(TS ts, PetscErrorCode (*exactError)(TS ts, Vec u, Vec e))
3736d71ae5a4SJacob Faibussowitsch {
3737aad739acSMatthew G. Knepley   PetscFunctionBegin;
3738aad739acSMatthew G. Knepley   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3739f907fdbfSMatthew G. Knepley   PetscValidFunction(exactError, 2);
3740aad739acSMatthew G. Knepley   ts->ops->exacterror = exactError;
37413ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
3742aad739acSMatthew G. Knepley }
3743aad739acSMatthew G. Knepley 
3744aad739acSMatthew G. Knepley /*@
3745bcf0153eSBarry Smith   TSComputeExactError - Compute the solution error for the timestepping using the function previously set with `TSSetComputeExactError()`
3746aad739acSMatthew G. Knepley 
3747c3339decSBarry Smith   Collective
3748aad739acSMatthew G. Knepley 
37494165533cSJose E. Roman   Input Parameters:
3750aad739acSMatthew G. Knepley + ts - time stepping context
3751aad739acSMatthew G. Knepley . u  - The approximate solution
3752bcf0153eSBarry Smith - e  - The `Vec` used to store the error
3753aad739acSMatthew G. Knepley 
3754aad739acSMatthew G. Knepley   Level: advanced
3755aad739acSMatthew G. Knepley 
37561cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSGetComputeInitialCondition()`, `TSSetComputeInitialCondition()`, `TSSolve()`
3757aad739acSMatthew G. Knepley @*/
3758d71ae5a4SJacob Faibussowitsch PetscErrorCode TSComputeExactError(TS ts, Vec u, Vec e)
3759d71ae5a4SJacob Faibussowitsch {
3760aad739acSMatthew G. Knepley   PetscFunctionBegin;
3761aad739acSMatthew G. Knepley   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3762aad739acSMatthew G. Knepley   PetscValidHeaderSpecific(u, VEC_CLASSID, 2);
3763aad739acSMatthew G. Knepley   PetscValidHeaderSpecific(e, VEC_CLASSID, 3);
3764dbbe0bcdSBarry Smith   PetscTryTypeMethod(ts, exacterror, u, e);
37653ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
3766aad739acSMatthew G. Knepley }
3767aad739acSMatthew G. Knepley 
37686bd3a4fdSStefano Zampini /*@C
37696bd3a4fdSStefano Zampini   TSSetResize - Sets the resize callbacks.
37706bd3a4fdSStefano Zampini 
37716bd3a4fdSStefano Zampini   Logically Collective
37726bd3a4fdSStefano Zampini 
37736bd3a4fdSStefano Zampini   Input Parameters:
37746bd3a4fdSStefano Zampini + ts       - The `TS` context obtained from `TSCreate()`
3775ecc87898SStefano Zampini . rollback - Whether a resize will restart the step
37766bd3a4fdSStefano Zampini . setup    - The setup function
377714d0ab18SJacob Faibussowitsch . transfer - The transfer function
377814d0ab18SJacob Faibussowitsch - ctx      - [optional] The user-defined context
37796bd3a4fdSStefano Zampini 
37806bd3a4fdSStefano Zampini   Calling sequence of `setup`:
37818847d985SBarry Smith + ts     - the `TS` context
37826bd3a4fdSStefano Zampini . step   - the current step
37836bd3a4fdSStefano Zampini . time   - the current time
37846bd3a4fdSStefano Zampini . state  - the current vector of state
37856bd3a4fdSStefano Zampini . resize - (output parameter) `PETSC_TRUE` if need resizing, `PETSC_FALSE` otherwise
37866bd3a4fdSStefano Zampini - ctx    - user defined context
37876bd3a4fdSStefano Zampini 
37886bd3a4fdSStefano Zampini   Calling sequence of `transfer`:
37898847d985SBarry Smith + ts      - the `TS` context
37906bd3a4fdSStefano Zampini . nv      - the number of vectors to be transferred
37916bd3a4fdSStefano Zampini . vecsin  - array of vectors to be transferred
37926bd3a4fdSStefano Zampini . vecsout - array of transferred vectors
37936bd3a4fdSStefano Zampini - ctx     - user defined context
37946bd3a4fdSStefano Zampini 
37956bd3a4fdSStefano Zampini   Notes:
3796ecc87898SStefano Zampini   The `setup` function is called inside `TSSolve()` after `TSEventHandler()` or after `TSPostStep()`
3797ecc87898SStefano Zampini   depending on the `rollback` value: if `rollback` is true, then these callbacks behave as error indicators
3798ecc87898SStefano Zampini   and will flag the need to remesh and restart the current step. Otherwise, they will simply flag the solver
3799ecc87898SStefano Zampini   that the size of the discrete problem has changed.
3800ecc87898SStefano Zampini   In both cases, the solver will collect the needed vectors that will be
3801ecc87898SStefano Zampini   transferred from the old to the new sizes using the `transfer` callback. These vectors will include the
3802ecc87898SStefano Zampini   current solution vector, and other vectors needed by the specific solver used.
38036bd3a4fdSStefano Zampini   For example, `TSBDF` uses previous solutions vectors to solve for the next time step.
38046bd3a4fdSStefano Zampini   Other application specific objects associated with the solver, i.e. Jacobian matrices and `DM`,
38056bd3a4fdSStefano Zampini   will be automatically reset if the sizes are changed and they must be specified again by the user
38066bd3a4fdSStefano Zampini   inside the `transfer` function.
38076bd3a4fdSStefano Zampini   The input and output arrays passed to `transfer` are allocated by PETSc.
38086bd3a4fdSStefano Zampini   Vectors in `vecsout` must be created by the user.
38096bd3a4fdSStefano Zampini   Ownership of vectors in `vecsout` is transferred to PETSc.
38106bd3a4fdSStefano Zampini 
38116bd3a4fdSStefano Zampini   Level: advanced
38126bd3a4fdSStefano Zampini 
38136bd3a4fdSStefano Zampini .seealso: [](ch_ts), `TS`, `TSSetDM()`, `TSSetIJacobian()`, `TSSetRHSJacobian()`
38146bd3a4fdSStefano Zampini @*/
3815ecc87898SStefano Zampini PetscErrorCode TSSetResize(TS ts, PetscBool rollback, 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)
38166bd3a4fdSStefano Zampini {
38176bd3a4fdSStefano Zampini   PetscFunctionBegin;
38186bd3a4fdSStefano Zampini   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3819ecc87898SStefano Zampini   ts->resizerollback = rollback;
38206bd3a4fdSStefano Zampini   ts->resizesetup    = setup;
38216bd3a4fdSStefano Zampini   ts->resizetransfer = transfer;
38226bd3a4fdSStefano Zampini   ts->resizectx      = ctx;
38236bd3a4fdSStefano Zampini   PetscFunctionReturn(PETSC_SUCCESS);
38246bd3a4fdSStefano Zampini }
38256bd3a4fdSStefano Zampini 
382614d0ab18SJacob Faibussowitsch /*
38276bd3a4fdSStefano Zampini   TSResizeRegisterOrRetrieve - Register or import vectors transferred with `TSResize()`.
38286bd3a4fdSStefano Zampini 
38296bd3a4fdSStefano Zampini   Collective
38306bd3a4fdSStefano Zampini 
38316bd3a4fdSStefano Zampini   Input Parameters:
38326bd3a4fdSStefano Zampini + ts   - The `TS` context obtained from `TSCreate()`
38336bd3a4fdSStefano 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.
38346bd3a4fdSStefano Zampini 
38356bd3a4fdSStefano Zampini   Level: developer
38366bd3a4fdSStefano Zampini 
38376bd3a4fdSStefano Zampini   Note:
38386bd3a4fdSStefano Zampini   `TSResizeRegisterOrRetrieve()` is declared PETSC_INTERN since it is
38396bd3a4fdSStefano Zampini    used within time stepping implementations,
38406bd3a4fdSStefano Zampini    so most users would not generally call this routine themselves.
38416bd3a4fdSStefano Zampini 
38426bd3a4fdSStefano Zampini .seealso: [](ch_ts), `TS`, `TSSetResize()`
38436bd3a4fdSStefano Zampini @*/
384414d0ab18SJacob Faibussowitsch static PetscErrorCode TSResizeRegisterOrRetrieve(TS ts, PetscBool flg)
38456bd3a4fdSStefano Zampini {
38466bd3a4fdSStefano Zampini   PetscFunctionBegin;
38476bd3a4fdSStefano Zampini   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
38486bd3a4fdSStefano Zampini   PetscTryTypeMethod(ts, resizeregister, flg);
38496bd3a4fdSStefano Zampini   /* PetscTryTypeMethod(adapt, resizeregister, flg); */
38506bd3a4fdSStefano Zampini   PetscFunctionReturn(PETSC_SUCCESS);
38516bd3a4fdSStefano Zampini }
38526bd3a4fdSStefano Zampini 
385314d0ab18SJacob Faibussowitsch static PetscErrorCode TSResizeReset(TS ts)
38546bd3a4fdSStefano Zampini {
38556bd3a4fdSStefano Zampini   PetscFunctionBegin;
38566bd3a4fdSStefano Zampini   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
38576bd3a4fdSStefano Zampini   PetscCall(PetscObjectListDestroy(&ts->resizetransferobjs));
38586bd3a4fdSStefano Zampini   PetscFunctionReturn(PETSC_SUCCESS);
38596bd3a4fdSStefano Zampini }
38606bd3a4fdSStefano Zampini 
38616bd3a4fdSStefano Zampini static PetscErrorCode TSResizeTransferVecs(TS ts, PetscInt cnt, Vec vecsin[], Vec vecsout[])
38626bd3a4fdSStefano Zampini {
38636bd3a4fdSStefano Zampini   PetscFunctionBegin;
38646bd3a4fdSStefano Zampini   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
38656bd3a4fdSStefano Zampini   PetscValidLogicalCollectiveInt(ts, cnt, 2);
38666bd3a4fdSStefano Zampini   for (PetscInt i = 0; i < cnt; i++) PetscCall(VecLockReadPush(vecsin[i]));
38676bd3a4fdSStefano Zampini   if (ts->resizetransfer) {
38686bd3a4fdSStefano Zampini     PetscCall(PetscInfo(ts, "Transferring %" PetscInt_FMT " vectors\n", cnt));
38696bd3a4fdSStefano Zampini     PetscCallBack("TS callback resize transfer", (*ts->resizetransfer)(ts, cnt, vecsin, vecsout, ts->resizectx));
38706bd3a4fdSStefano Zampini   }
38716bd3a4fdSStefano Zampini   for (PetscInt i = 0; i < cnt; i++) PetscCall(VecLockReadPop(vecsin[i]));
38726bd3a4fdSStefano Zampini   PetscFunctionReturn(PETSC_SUCCESS);
38736bd3a4fdSStefano Zampini }
38746bd3a4fdSStefano Zampini 
38756bd3a4fdSStefano Zampini /*@C
38766bd3a4fdSStefano Zampini   TSResizeRegisterVec - Register a vector to be transferred with `TSResize()`.
38776bd3a4fdSStefano Zampini 
38786bd3a4fdSStefano Zampini   Collective
38796bd3a4fdSStefano Zampini 
38806bd3a4fdSStefano Zampini   Input Parameters:
38816bd3a4fdSStefano Zampini + ts   - The `TS` context obtained from `TSCreate()`
3882baca6076SPierre Jolivet . name - A string identifying the vector
38836bd3a4fdSStefano Zampini - vec  - The vector
38846bd3a4fdSStefano Zampini 
38856bd3a4fdSStefano Zampini   Level: developer
38866bd3a4fdSStefano Zampini 
38876bd3a4fdSStefano Zampini   Note:
38886bd3a4fdSStefano Zampini   `TSResizeRegisterVec()` is typically used within time stepping implementations,
38896bd3a4fdSStefano Zampini   so most users would not generally call this routine themselves.
38906bd3a4fdSStefano Zampini 
38916bd3a4fdSStefano Zampini .seealso: [](ch_ts), `TS`, `TSSetResize()`, `TSResize()`, `TSResizeRetrieveVec()`
38926bd3a4fdSStefano Zampini @*/
3893cc4c1da9SBarry Smith PetscErrorCode TSResizeRegisterVec(TS ts, const char name[], Vec vec)
38946bd3a4fdSStefano Zampini {
38956bd3a4fdSStefano Zampini   PetscFunctionBegin;
38966bd3a4fdSStefano Zampini   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
38974f572ea9SToby Isaac   PetscAssertPointer(name, 2);
38986bd3a4fdSStefano Zampini   if (vec) PetscValidHeaderSpecific(vec, VEC_CLASSID, 3);
38996bd3a4fdSStefano Zampini   PetscCall(PetscObjectListAdd(&ts->resizetransferobjs, name, (PetscObject)vec));
39006bd3a4fdSStefano Zampini   PetscFunctionReturn(PETSC_SUCCESS);
39016bd3a4fdSStefano Zampini }
39026bd3a4fdSStefano Zampini 
39036bd3a4fdSStefano Zampini /*@C
39046bd3a4fdSStefano Zampini   TSResizeRetrieveVec - Retrieve a vector registered with `TSResizeRegisterVec()`.
39056bd3a4fdSStefano Zampini 
39066bd3a4fdSStefano Zampini   Collective
39076bd3a4fdSStefano Zampini 
39086bd3a4fdSStefano Zampini   Input Parameters:
39096bd3a4fdSStefano Zampini + ts   - The `TS` context obtained from `TSCreate()`
3910baca6076SPierre Jolivet . name - A string identifying the vector
39116bd3a4fdSStefano Zampini - vec  - The vector
39126bd3a4fdSStefano Zampini 
39136bd3a4fdSStefano Zampini   Level: developer
39146bd3a4fdSStefano Zampini 
39156bd3a4fdSStefano Zampini   Note:
39166bd3a4fdSStefano Zampini   `TSResizeRetrieveVec()` is typically used within time stepping implementations,
39176bd3a4fdSStefano Zampini   so most users would not generally call this routine themselves.
39186bd3a4fdSStefano Zampini 
39196bd3a4fdSStefano Zampini .seealso: [](ch_ts), `TS`, `TSSetResize()`, `TSResize()`, `TSResizeRegisterVec()`
39206bd3a4fdSStefano Zampini @*/
3921cc4c1da9SBarry Smith PetscErrorCode TSResizeRetrieveVec(TS ts, const char name[], Vec *vec)
39226bd3a4fdSStefano Zampini {
39236bd3a4fdSStefano Zampini   PetscFunctionBegin;
39246bd3a4fdSStefano Zampini   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
39254f572ea9SToby Isaac   PetscAssertPointer(name, 2);
39264f572ea9SToby Isaac   PetscAssertPointer(vec, 3);
39276bd3a4fdSStefano Zampini   PetscCall(PetscObjectListFind(ts->resizetransferobjs, name, (PetscObject *)vec));
39286bd3a4fdSStefano Zampini   PetscFunctionReturn(PETSC_SUCCESS);
39296bd3a4fdSStefano Zampini }
39306bd3a4fdSStefano Zampini 
39316bd3a4fdSStefano Zampini static PetscErrorCode TSResizeGetVecArray(TS ts, PetscInt *nv, const char **names[], Vec *vecs[])
39326bd3a4fdSStefano Zampini {
39336bd3a4fdSStefano Zampini   PetscInt        cnt;
39346bd3a4fdSStefano Zampini   PetscObjectList tmp;
39356bd3a4fdSStefano Zampini   Vec            *vecsin  = NULL;
39366bd3a4fdSStefano Zampini   const char    **namesin = NULL;
39376bd3a4fdSStefano Zampini 
39386bd3a4fdSStefano Zampini   PetscFunctionBegin;
39396bd3a4fdSStefano Zampini   for (tmp = ts->resizetransferobjs, cnt = 0; tmp; tmp = tmp->next)
39406bd3a4fdSStefano Zampini     if (tmp->obj && tmp->obj->classid == VEC_CLASSID) cnt++;
394103ba6ac9SBarry Smith   if (names) PetscCall(PetscMalloc1(cnt, &namesin));
394203ba6ac9SBarry Smith   if (vecs) PetscCall(PetscMalloc1(cnt, &vecsin));
39436bd3a4fdSStefano Zampini   for (tmp = ts->resizetransferobjs, cnt = 0; tmp; tmp = tmp->next) {
39446bd3a4fdSStefano Zampini     if (tmp->obj && tmp->obj->classid == VEC_CLASSID) {
39456bd3a4fdSStefano Zampini       if (vecs) vecsin[cnt] = (Vec)tmp->obj;
39466bd3a4fdSStefano Zampini       if (names) namesin[cnt] = tmp->name;
39476bd3a4fdSStefano Zampini       cnt++;
39486bd3a4fdSStefano Zampini     }
39496bd3a4fdSStefano Zampini   }
39506bd3a4fdSStefano Zampini   if (nv) *nv = cnt;
39516bd3a4fdSStefano Zampini   if (names) *names = namesin;
39526bd3a4fdSStefano Zampini   if (vecs) *vecs = vecsin;
39536bd3a4fdSStefano Zampini   PetscFunctionReturn(PETSC_SUCCESS);
39546bd3a4fdSStefano Zampini }
39556bd3a4fdSStefano Zampini 
39566bd3a4fdSStefano Zampini /*@
39576bd3a4fdSStefano Zampini   TSResize - Runs the user-defined transfer functions provided with `TSSetResize()`
39586bd3a4fdSStefano Zampini 
39596bd3a4fdSStefano Zampini   Collective
39606bd3a4fdSStefano Zampini 
39616bd3a4fdSStefano Zampini   Input Parameter:
39626bd3a4fdSStefano Zampini . ts - The `TS` context obtained from `TSCreate()`
39636bd3a4fdSStefano Zampini 
39646bd3a4fdSStefano Zampini   Level: developer
39656bd3a4fdSStefano Zampini 
39666bd3a4fdSStefano Zampini   Note:
39676bd3a4fdSStefano Zampini   `TSResize()` is typically used within time stepping implementations,
39686bd3a4fdSStefano Zampini   so most users would not generally call this routine themselves.
39696bd3a4fdSStefano Zampini 
39706bd3a4fdSStefano Zampini .seealso: [](ch_ts), `TS`, `TSSetResize()`
39716bd3a4fdSStefano Zampini @*/
39726bd3a4fdSStefano Zampini PetscErrorCode TSResize(TS ts)
39736bd3a4fdSStefano Zampini {
39746bd3a4fdSStefano Zampini   PetscInt     nv      = 0;
39756bd3a4fdSStefano Zampini   const char **names   = NULL;
39766bd3a4fdSStefano Zampini   Vec         *vecsin  = NULL;
39776bd3a4fdSStefano Zampini   const char  *solname = "ts:vec_sol";
39786bd3a4fdSStefano Zampini 
39796bd3a4fdSStefano Zampini   PetscFunctionBegin;
39806bd3a4fdSStefano Zampini   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3981ecc87898SStefano Zampini   if (!ts->resizesetup) PetscFunctionReturn(PETSC_SUCCESS);
39826bd3a4fdSStefano Zampini   if (ts->resizesetup) {
39836bd3a4fdSStefano Zampini     PetscCall(VecLockReadPush(ts->vec_sol));
3984c6bf8827SStefano Zampini     PetscCallBack("TS callback resize setup", (*ts->resizesetup)(ts, ts->steps, ts->ptime, ts->vec_sol, &ts->stepresize, ts->resizectx));
39856bd3a4fdSStefano Zampini     PetscCall(VecLockReadPop(ts->vec_sol));
3986c6bf8827SStefano Zampini     if (ts->stepresize) {
3987ecc87898SStefano Zampini       if (ts->resizerollback) {
3988ecc87898SStefano Zampini         PetscCall(TSRollBack(ts));
3989ecc87898SStefano Zampini         ts->time_step = ts->time_step0;
3990ecc87898SStefano Zampini       }
39916bd3a4fdSStefano Zampini       PetscCall(TSResizeRegisterVec(ts, solname, ts->vec_sol));
39926bd3a4fdSStefano Zampini       PetscCall(TSResizeRegisterOrRetrieve(ts, PETSC_TRUE)); /* specific impls register their own objects */
39936bd3a4fdSStefano Zampini     }
39946bd3a4fdSStefano Zampini   }
39956bd3a4fdSStefano Zampini 
39966bd3a4fdSStefano Zampini   PetscCall(TSResizeGetVecArray(ts, &nv, &names, &vecsin));
39976bd3a4fdSStefano Zampini   if (nv) {
39986bd3a4fdSStefano Zampini     Vec *vecsout, vecsol;
39996bd3a4fdSStefano Zampini 
40006bd3a4fdSStefano Zampini     /* Reset internal objects */
40016bd3a4fdSStefano Zampini     PetscCall(TSReset(ts));
40026bd3a4fdSStefano Zampini 
4003ecc87898SStefano Zampini     /* Transfer needed vectors (users can call SetJacobian, SetDM, etc. here) */
40046bd3a4fdSStefano Zampini     PetscCall(PetscCalloc1(nv, &vecsout));
40056bd3a4fdSStefano Zampini     PetscCall(TSResizeTransferVecs(ts, nv, vecsin, vecsout));
40066bd3a4fdSStefano Zampini     for (PetscInt i = 0; i < nv; i++) {
4007ecc87898SStefano Zampini       const char *name;
4008ecc87898SStefano Zampini       char       *oname;
4009ecc87898SStefano Zampini 
4010ecc87898SStefano Zampini       PetscCall(PetscObjectGetName((PetscObject)vecsin[i], &name));
4011ecc87898SStefano Zampini       PetscCall(PetscStrallocpy(name, &oname));
40126bd3a4fdSStefano Zampini       PetscCall(TSResizeRegisterVec(ts, names[i], vecsout[i]));
4013ecc87898SStefano Zampini       if (vecsout[i]) PetscCall(PetscObjectSetName((PetscObject)vecsout[i], oname));
4014ecc87898SStefano Zampini       PetscCall(PetscFree(oname));
40156bd3a4fdSStefano Zampini       PetscCall(VecDestroy(&vecsout[i]));
40166bd3a4fdSStefano Zampini     }
40176bd3a4fdSStefano Zampini     PetscCall(PetscFree(vecsout));
40186bd3a4fdSStefano Zampini     PetscCall(TSResizeRegisterOrRetrieve(ts, PETSC_FALSE)); /* specific impls import the transferred objects */
40196bd3a4fdSStefano Zampini 
40206bd3a4fdSStefano Zampini     PetscCall(TSResizeRetrieveVec(ts, solname, &vecsol));
40216bd3a4fdSStefano Zampini     if (vecsol) PetscCall(TSSetSolution(ts, vecsol));
40226bd3a4fdSStefano Zampini     PetscAssert(ts->vec_sol, PetscObjectComm((PetscObject)ts), PETSC_ERR_ARG_NULL, "Missing TS solution");
40236bd3a4fdSStefano Zampini   }
40246bd3a4fdSStefano Zampini 
40256bd3a4fdSStefano Zampini   PetscCall(PetscFree(names));
40266bd3a4fdSStefano Zampini   PetscCall(PetscFree(vecsin));
40276bd3a4fdSStefano Zampini   PetscCall(TSResizeReset(ts));
40286bd3a4fdSStefano Zampini   PetscFunctionReturn(PETSC_SUCCESS);
40296bd3a4fdSStefano Zampini }
40306bd3a4fdSStefano Zampini 
4031b1cb36f3SHong Zhang /*@
40326a4d4014SLisandro Dalcin   TSSolve - Steps the requested number of timesteps.
40336a4d4014SLisandro Dalcin 
4034c3339decSBarry Smith   Collective
40356a4d4014SLisandro Dalcin 
4036d8d19677SJose E. Roman   Input Parameters:
4037bcf0153eSBarry Smith + ts - the `TS` context obtained from `TSCreate()`
4038bcf0153eSBarry Smith - u  - the solution vector  (can be null if `TSSetSolution()` was used and `TSSetExactFinalTime`(ts,`TS_EXACTFINALTIME_MATCHSTEP`) was not used,
40390b4b7b1cSBarry Smith        otherwise it must contain the initial conditions and will contain the solution at the final requested time
40405a3a76d0SJed Brown 
40416a4d4014SLisandro Dalcin   Level: beginner
40426a4d4014SLisandro Dalcin 
40435a3a76d0SJed Brown   Notes:
40445a3a76d0SJed Brown   The final time returned by this function may be different from the time of the internally
4045bcf0153eSBarry Smith   held state accessible by `TSGetSolution()` and `TSGetTime()` because the method may have
40465a3a76d0SJed Brown   stepped over the final time.
40475a3a76d0SJed Brown 
40481cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSCreate()`, `TSSetSolution()`, `TSStep()`, `TSGetTime()`, `TSGetSolveTime()`
40496a4d4014SLisandro Dalcin @*/
4050d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSolve(TS ts, Vec u)
4051d71ae5a4SJacob Faibussowitsch {
4052b06615a5SLisandro Dalcin   Vec solution;
4053f22f69f0SBarry Smith 
40546a4d4014SLisandro Dalcin   PetscFunctionBegin;
40550700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
4056f2c2a1b9SBarry Smith   if (u) PetscValidHeaderSpecific(u, VEC_CLASSID, 2);
4057303a5415SBarry Smith 
40589566063dSJacob Faibussowitsch   PetscCall(TSSetExactFinalTimeDefault(ts));
4059ee41a567SStefano 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 */
40600910c330SBarry Smith     if (!ts->vec_sol || u == ts->vec_sol) {
40619566063dSJacob Faibussowitsch       PetscCall(VecDuplicate(u, &solution));
40629566063dSJacob Faibussowitsch       PetscCall(TSSetSolution(ts, solution));
40639566063dSJacob Faibussowitsch       PetscCall(VecDestroy(&solution)); /* grant ownership */
40645a3a76d0SJed Brown     }
40659566063dSJacob Faibussowitsch     PetscCall(VecCopy(u, ts->vec_sol));
40663c633725SBarry Smith     PetscCheck(!ts->forward_solve, PetscObjectComm((PetscObject)ts), PETSC_ERR_SUP, "Sensitivity analysis does not support the mode TS_EXACTFINALTIME_INTERPOLATE");
40671baa6e33SBarry Smith   } else if (u) PetscCall(TSSetSolution(ts, u));
40689566063dSJacob Faibussowitsch   PetscCall(TSSetUp(ts));
40699566063dSJacob Faibussowitsch   PetscCall(TSTrajectorySetUp(ts->trajectory, ts));
4070a6772fa2SLisandro Dalcin 
40718e562f8dSJames Wright   PetscCheck(ts->max_time < PETSC_MAX_REAL || ts->run_steps != PETSC_INT_MAX || ts->max_steps != PETSC_INT_MAX, PetscObjectComm((PetscObject)ts), PETSC_ERR_ARG_WRONGSTATE, "You must call TSSetMaxTime(), TSSetMaxSteps(), or TSSetRunSteps() or use -ts_max_time <time>, -ts_max_steps <steps>, -ts_run_steps <steps>");
40723c633725SBarry 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()");
40733c633725SBarry 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");
4074136cf249SJames Wright   PetscCheck(!(ts->eval_times && ts->exact_final_time != TS_EXACTFINALTIME_MATCHSTEP), PetscObjectComm((PetscObject)ts), PETSC_ERR_SUP, "You must use TS_EXACTFINALTIME_MATCHSTEP when using time span or evaluation times");
40754a658b32SHong Zhang 
4076136cf249SJames Wright   if (ts->eval_times) {
4077264c38b7SJames Wright     if (!ts->eval_times->sol_vecs) PetscCall(VecDuplicateVecs(ts->vec_sol, ts->eval_times->num_time_points, &ts->eval_times->sol_vecs));
4078136cf249SJames Wright     for (PetscInt i = 0; i < ts->eval_times->num_time_points; i++) {
4079136cf249SJames Wright       PetscBool is_close = PetscIsCloseAtTol(ts->ptime, ts->eval_times->time_points[i], ts->eval_times->reltol * ts->time_step + ts->eval_times->abstol, 0);
4080136cf249SJames Wright       if (ts->ptime <= ts->eval_times->time_points[i] || is_close) {
4081136cf249SJames Wright         ts->eval_times->time_point_idx = i;
4082264c38b7SJames Wright 
4083264c38b7SJames Wright         PetscBool is_ptime_in_sol_times = PETSC_FALSE; // If current solution has already been saved, we should not save it again
4084264c38b7SJames Wright         if (ts->eval_times->sol_idx > 0) is_ptime_in_sol_times = PetscIsCloseAtTol(ts->ptime, ts->eval_times->sol_times[ts->eval_times->sol_idx - 1], ts->eval_times->reltol * ts->time_step + ts->eval_times->abstol, 0);
4085264c38b7SJames Wright         if (is_close && !is_ptime_in_sol_times) {
4086264c38b7SJames Wright           PetscCall(VecCopy(ts->vec_sol, ts->eval_times->sol_vecs[ts->eval_times->sol_idx]));
4087264c38b7SJames Wright           ts->eval_times->sol_times[ts->eval_times->sol_idx] = ts->ptime;
4088264c38b7SJames Wright           ts->eval_times->sol_idx++;
4089136cf249SJames Wright           ts->eval_times->time_point_idx++;
40908343f784SJames Wright         }
40918343f784SJames Wright         break;
40928343f784SJames Wright       }
40938343f784SJames Wright     }
40944a658b32SHong Zhang   }
4095a6772fa2SLisandro Dalcin 
40961baa6e33SBarry Smith   if (ts->forward_solve) PetscCall(TSForwardSetUp(ts));
4097715f1b00SHong Zhang 
4098e7069c78SShri   /* reset number of steps only when the step is not restarted. ARKIMEX
4099715f1b00SHong Zhang      restarts the step after an event. Resetting these counters in such case causes
4100e7069c78SShri      TSTrajectory to incorrectly save the output files
4101e7069c78SShri   */
4102715f1b00SHong Zhang   /* reset time step and iteration counters */
41032808aa04SLisandro Dalcin   if (!ts->steps) {
41045ef26d82SJed Brown     ts->ksp_its           = 0;
41055ef26d82SJed Brown     ts->snes_its          = 0;
4106c610991cSLisandro Dalcin     ts->num_snes_failures = 0;
4107c610991cSLisandro Dalcin     ts->reject            = 0;
41082808aa04SLisandro Dalcin     ts->steprestart       = PETSC_TRUE;
41092808aa04SLisandro Dalcin     ts->steprollback      = PETSC_FALSE;
4110c6bf8827SStefano Zampini     ts->stepresize        = PETSC_FALSE;
41117d51462cSStefano Zampini     ts->rhsjacobian.time  = PETSC_MIN_REAL;
41122808aa04SLisandro Dalcin   }
4113e97c63d7SStefano Zampini 
4114136cf249SJames Wright   /* make sure initial time step does not overshoot final time or the next point in evaluation times */
4115e97c63d7SStefano Zampini   if (ts->exact_final_time == TS_EXACTFINALTIME_MATCHSTEP) {
41164a658b32SHong Zhang     PetscReal maxdt;
4117e97c63d7SStefano Zampini     PetscReal dt = ts->time_step;
4118e97c63d7SStefano Zampini 
4119136cf249SJames Wright     if (ts->eval_times) maxdt = ts->eval_times->time_points[ts->eval_times->time_point_idx] - ts->ptime;
41204a658b32SHong Zhang     else maxdt = ts->max_time - ts->ptime;
4121e97c63d7SStefano Zampini     ts->time_step = dt >= maxdt ? maxdt : (PetscIsCloseAtTol(dt, maxdt, 10 * PETSC_MACHINE_EPSILON, 0) ? maxdt : dt);
4122e97c63d7SStefano Zampini   }
4123193ac0bcSJed Brown   ts->reason = TS_CONVERGED_ITERATING;
4124193ac0bcSJed Brown 
4125900f6b5bSMatthew G. Knepley   {
4126900f6b5bSMatthew G. Knepley     PetscViewer       viewer;
4127900f6b5bSMatthew G. Knepley     PetscViewerFormat format;
4128900f6b5bSMatthew G. Knepley     PetscBool         flg;
4129900f6b5bSMatthew G. Knepley     static PetscBool  incall = PETSC_FALSE;
4130900f6b5bSMatthew G. Knepley 
4131900f6b5bSMatthew G. Knepley     if (!incall) {
4132900f6b5bSMatthew G. Knepley       /* Estimate the convergence rate of the time discretization */
4133648c30bcSBarry Smith       PetscCall(PetscOptionsCreateViewer(PetscObjectComm((PetscObject)ts), ((PetscObject)ts)->options, ((PetscObject)ts)->prefix, "-ts_convergence_estimate", &viewer, &format, &flg));
4134900f6b5bSMatthew G. Knepley       if (flg) {
4135900f6b5bSMatthew G. Knepley         PetscConvEst conv;
4136900f6b5bSMatthew G. Knepley         DM           dm;
4137900f6b5bSMatthew G. Knepley         PetscReal   *alpha; /* Convergence rate of the solution error for each field in the L_2 norm */
4138900f6b5bSMatthew G. Knepley         PetscInt     Nf;
4139f2ed2dc7SMatthew G. Knepley         PetscBool    checkTemporal = PETSC_TRUE;
4140900f6b5bSMatthew G. Knepley 
4141900f6b5bSMatthew G. Knepley         incall = PETSC_TRUE;
41429566063dSJacob Faibussowitsch         PetscCall(PetscOptionsGetBool(((PetscObject)ts)->options, ((PetscObject)ts)->prefix, "-ts_convergence_temporal", &checkTemporal, &flg));
41439566063dSJacob Faibussowitsch         PetscCall(TSGetDM(ts, &dm));
41449566063dSJacob Faibussowitsch         PetscCall(DMGetNumFields(dm, &Nf));
41459566063dSJacob Faibussowitsch         PetscCall(PetscCalloc1(PetscMax(Nf, 1), &alpha));
41469566063dSJacob Faibussowitsch         PetscCall(PetscConvEstCreate(PetscObjectComm((PetscObject)ts), &conv));
41479566063dSJacob Faibussowitsch         PetscCall(PetscConvEstUseTS(conv, checkTemporal));
41489566063dSJacob Faibussowitsch         PetscCall(PetscConvEstSetSolver(conv, (PetscObject)ts));
41499566063dSJacob Faibussowitsch         PetscCall(PetscConvEstSetFromOptions(conv));
41509566063dSJacob Faibussowitsch         PetscCall(PetscConvEstSetUp(conv));
41519566063dSJacob Faibussowitsch         PetscCall(PetscConvEstGetConvRate(conv, alpha));
41529566063dSJacob Faibussowitsch         PetscCall(PetscViewerPushFormat(viewer, format));
41539566063dSJacob Faibussowitsch         PetscCall(PetscConvEstRateView(conv, alpha, viewer));
41549566063dSJacob Faibussowitsch         PetscCall(PetscViewerPopFormat(viewer));
4155648c30bcSBarry Smith         PetscCall(PetscViewerDestroy(&viewer));
41569566063dSJacob Faibussowitsch         PetscCall(PetscConvEstDestroy(&conv));
41579566063dSJacob Faibussowitsch         PetscCall(PetscFree(alpha));
4158900f6b5bSMatthew G. Knepley         incall = PETSC_FALSE;
4159900f6b5bSMatthew G. Knepley       }
4160900f6b5bSMatthew G. Knepley     }
4161900f6b5bSMatthew G. Knepley   }
4162900f6b5bSMatthew G. Knepley 
41639566063dSJacob Faibussowitsch   PetscCall(TSViewFromOptions(ts, NULL, "-ts_view_pre"));
4164f05ece33SBarry Smith 
4165193ac0bcSJed Brown   if (ts->ops->solve) { /* This private interface is transitional and should be removed when all implementations are updated. */
4166dbbe0bcdSBarry Smith     PetscUseTypeMethod(ts, solve);
41679566063dSJacob Faibussowitsch     if (u) PetscCall(VecCopy(ts->vec_sol, u));
4168cc708dedSBarry Smith     ts->solvetime = ts->ptime;
4169a6772fa2SLisandro Dalcin     solution      = ts->vec_sol;
4170be5899b3SLisandro Dalcin   } else { /* Step the requested number of timesteps. */
4171db4deed7SKarl Rupp     if (ts->steps >= ts->max_steps) ts->reason = TS_CONVERGED_ITS;
4172db4deed7SKarl Rupp     else if (ts->ptime >= ts->max_time) ts->reason = TS_CONVERGED_TIME;
4173e7069c78SShri 
41742808aa04SLisandro Dalcin     if (!ts->steps) {
41759566063dSJacob Faibussowitsch       PetscCall(TSTrajectorySet(ts->trajectory, ts, ts->steps, ts->ptime, ts->vec_sol));
41769566063dSJacob Faibussowitsch       PetscCall(TSEventInitialize(ts->event, ts, ts->ptime, ts->vec_sol));
41772808aa04SLisandro Dalcin     }
41786427ac75SLisandro Dalcin 
41798e562f8dSJames Wright     ts->start_step = ts->steps; // records starting step
4180e1a7a14fSJed Brown     while (!ts->reason) {
41819566063dSJacob Faibussowitsch       PetscCall(TSMonitor(ts, ts->steps, ts->ptime, ts->vec_sol));
4182c6bf8827SStefano Zampini       if (!ts->steprollback || (ts->stepresize && ts->resizerollback)) PetscCall(TSPreStep(ts));
41839566063dSJacob Faibussowitsch       PetscCall(TSStep(ts));
41841baa6e33SBarry Smith       if (ts->testjacobian) PetscCall(TSRHSJacobianTest(ts, NULL));
41851baa6e33SBarry Smith       if (ts->testjacobiantranspose) PetscCall(TSRHSJacobianTestTranspose(ts, NULL));
4186cd4cee2dSHong Zhang       if (ts->quadraturets && ts->costintegralfwd) { /* Must evaluate the cost integral before event is handled. The cost integral value can also be rolled back. */
41877b0e2f17SHong Zhang         if (ts->reason >= 0) ts->steps--;            /* Revert the step number changed by TSStep() */
41889566063dSJacob Faibussowitsch         PetscCall(TSForwardCostIntegral(ts));
41897b0e2f17SHong Zhang         if (ts->reason >= 0) ts->steps++;
4190b1cb36f3SHong Zhang       }
419158818c2dSLisandro Dalcin       if (ts->forward_solve) {            /* compute forward sensitivities before event handling because postevent() may change RHS and jump conditions may have to be applied */
41927b0e2f17SHong Zhang         if (ts->reason >= 0) ts->steps--; /* Revert the step number changed by TSStep() */
41939566063dSJacob Faibussowitsch         PetscCall(TSForwardStep(ts));
41947b0e2f17SHong Zhang         if (ts->reason >= 0) ts->steps++;
4195715f1b00SHong Zhang       }
41969566063dSJacob Faibussowitsch       PetscCall(TSPostEvaluate(ts));
41979566063dSJacob 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. */
41981baa6e33SBarry Smith       if (ts->steprollback) PetscCall(TSPostEvaluate(ts));
4199ecc87898SStefano Zampini       if (!ts->steprollback && ts->resizerollback) PetscCall(TSResize(ts));
420090d719a4SStefano Zampini       /* check convergence */
420190d719a4SStefano Zampini       if (!ts->reason) {
42028e562f8dSJames Wright         if ((ts->steps - ts->start_step) >= ts->run_steps) ts->reason = TS_CONVERGED_ITS;
42038e562f8dSJames Wright         else if (ts->steps >= ts->max_steps) ts->reason = TS_CONVERGED_ITS;
420490d719a4SStefano Zampini         else if (ts->ptime >= ts->max_time) ts->reason = TS_CONVERGED_TIME;
420590d719a4SStefano Zampini       }
4206e783b05fSHong Zhang       if (!ts->steprollback) {
42079566063dSJacob Faibussowitsch         PetscCall(TSTrajectorySet(ts->trajectory, ts, ts->steps, ts->ptime, ts->vec_sol));
42089566063dSJacob Faibussowitsch         PetscCall(TSPostStep(ts));
4209ecc87898SStefano Zampini         if (!ts->resizerollback) PetscCall(TSResize(ts));
4210ca4445c7SIlya Fursov 
421126077dccSJames Wright         if (ts->eval_times && ts->eval_times->time_point_idx < ts->eval_times->num_time_points && ts->reason >= 0) {
4212136cf249SJames Wright           PetscCheck(ts->eval_times->worktol > 0, PetscObjectComm((PetscObject)ts), PETSC_ERR_PLIB, "Unexpected state !(eval_times->worktol > 0) in TSSolve()");
4213136cf249SJames Wright           if (PetscIsCloseAtTol(ts->ptime, ts->eval_times->time_points[ts->eval_times->time_point_idx], ts->eval_times->worktol, 0)) {
4214264c38b7SJames Wright             ts->eval_times->sol_times[ts->eval_times->sol_idx] = ts->ptime;
4215264c38b7SJames Wright             PetscCall(VecCopy(ts->vec_sol, ts->eval_times->sol_vecs[ts->eval_times->sol_idx]));
4216264c38b7SJames Wright             ts->eval_times->sol_idx++;
4217136cf249SJames Wright             ts->eval_times->time_point_idx++;
42188343f784SJames Wright           }
4219ca4445c7SIlya Fursov         }
4220aeb4809dSShri Abhyankar       }
4221193ac0bcSJed Brown     }
42229566063dSJacob Faibussowitsch     PetscCall(TSMonitor(ts, ts->steps, ts->ptime, ts->vec_sol));
42236427ac75SLisandro Dalcin 
422449354f04SShri Abhyankar     if (ts->exact_final_time == TS_EXACTFINALTIME_INTERPOLATE && ts->ptime > ts->max_time) {
42255dbbf88eSStefano Zampini       if (!u) u = ts->vec_sol;
42269566063dSJacob Faibussowitsch       PetscCall(TSInterpolate(ts, ts->max_time, u));
4227cc708dedSBarry Smith       ts->solvetime = ts->max_time;
4228b06615a5SLisandro Dalcin       solution      = u;
42299566063dSJacob Faibussowitsch       PetscCall(TSMonitor(ts, -1, ts->solvetime, solution));
42300574a7fbSJed Brown     } else {
42319566063dSJacob Faibussowitsch       if (u) PetscCall(VecCopy(ts->vec_sol, u));
4232cc708dedSBarry Smith       ts->solvetime = ts->ptime;
4233b06615a5SLisandro Dalcin       solution      = ts->vec_sol;
42340574a7fbSJed Brown     }
4235193ac0bcSJed Brown   }
4236d2daff3dSHong Zhang 
42379566063dSJacob Faibussowitsch   PetscCall(TSViewFromOptions(ts, NULL, "-ts_view"));
42389566063dSJacob Faibussowitsch   PetscCall(VecViewFromOptions(solution, (PetscObject)ts, "-ts_view_solution"));
42399566063dSJacob Faibussowitsch   PetscCall(PetscObjectSAWsBlock((PetscObject)ts));
42401baa6e33SBarry Smith   if (ts->adjoint_solve) PetscCall(TSAdjointSolve(ts));
42413ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
42426a4d4014SLisandro Dalcin }
42436a4d4014SLisandro Dalcin 
4244d763cef2SBarry Smith /*@
4245b8123daeSJed Brown   TSGetTime - Gets the time of the most recently completed step.
4246d763cef2SBarry Smith 
4247d763cef2SBarry Smith   Not Collective
4248d763cef2SBarry Smith 
4249d763cef2SBarry Smith   Input Parameter:
4250bcf0153eSBarry Smith . ts - the `TS` context obtained from `TSCreate()`
4251d763cef2SBarry Smith 
4252d763cef2SBarry Smith   Output Parameter:
4253bcf0153eSBarry Smith . t - the current time. This time may not corresponds to the final time set with `TSSetMaxTime()`, use `TSGetSolveTime()`.
4254d763cef2SBarry Smith 
4255d763cef2SBarry Smith   Level: beginner
4256d763cef2SBarry Smith 
4257b8123daeSJed Brown   Note:
4258bcf0153eSBarry Smith   When called during time step evaluation (e.g. during residual evaluation or via hooks set using `TSSetPreStep()`,
4259bcf0153eSBarry Smith   `TSSetPreStage()`, `TSSetPostStage()`, or `TSSetPostStep()`), the time is the time at the start of the step being evaluated.
4260b8123daeSJed Brown 
4261a94f484eSPierre Jolivet .seealso: [](ch_ts), `TS`, `TSGetSolveTime()`, `TSSetTime()`, `TSGetTimeStep()`, `TSGetStepNumber()`
4262d763cef2SBarry Smith @*/
4263d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetTime(TS ts, PetscReal *t)
4264d71ae5a4SJacob Faibussowitsch {
4265d763cef2SBarry Smith   PetscFunctionBegin;
42660700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
42674f572ea9SToby Isaac   PetscAssertPointer(t, 2);
4268d763cef2SBarry Smith   *t = ts->ptime;
42693ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
4270d763cef2SBarry Smith }
4271d763cef2SBarry Smith 
4272e5e524a1SHong Zhang /*@
4273e5e524a1SHong Zhang   TSGetPrevTime - Gets the starting time of the previously completed step.
4274e5e524a1SHong Zhang 
4275e5e524a1SHong Zhang   Not Collective
4276e5e524a1SHong Zhang 
4277e5e524a1SHong Zhang   Input Parameter:
4278bcf0153eSBarry Smith . ts - the `TS` context obtained from `TSCreate()`
4279e5e524a1SHong Zhang 
4280e5e524a1SHong Zhang   Output Parameter:
4281e5e524a1SHong Zhang . t - the previous time
4282e5e524a1SHong Zhang 
4283e5e524a1SHong Zhang   Level: beginner
4284e5e524a1SHong Zhang 
4285a94f484eSPierre Jolivet .seealso: [](ch_ts), `TS`, `TSGetTime()`, `TSGetSolveTime()`, `TSGetTimeStep()`
4286e5e524a1SHong Zhang @*/
4287d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetPrevTime(TS ts, PetscReal *t)
4288d71ae5a4SJacob Faibussowitsch {
4289e5e524a1SHong Zhang   PetscFunctionBegin;
4290e5e524a1SHong Zhang   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
42914f572ea9SToby Isaac   PetscAssertPointer(t, 2);
4292e5e524a1SHong Zhang   *t = ts->ptime_prev;
42933ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
4294e5e524a1SHong Zhang }
4295e5e524a1SHong Zhang 
42966a4d4014SLisandro Dalcin /*@
42976a4d4014SLisandro Dalcin   TSSetTime - Allows one to reset the time.
42986a4d4014SLisandro Dalcin 
4299c3339decSBarry Smith   Logically Collective
43006a4d4014SLisandro Dalcin 
43016a4d4014SLisandro Dalcin   Input Parameters:
4302bcf0153eSBarry Smith + ts - the `TS` context obtained from `TSCreate()`
4303b43aa488SJacob Faibussowitsch - t  - the time
43046a4d4014SLisandro Dalcin 
43056a4d4014SLisandro Dalcin   Level: intermediate
43066a4d4014SLisandro Dalcin 
43071cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSGetTime()`, `TSSetMaxSteps()`
43086a4d4014SLisandro Dalcin @*/
4309d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetTime(TS ts, PetscReal t)
4310d71ae5a4SJacob Faibussowitsch {
43116a4d4014SLisandro Dalcin   PetscFunctionBegin;
43120700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
4313c5eb9154SBarry Smith   PetscValidLogicalCollectiveReal(ts, t, 2);
43146a4d4014SLisandro Dalcin   ts->ptime = t;
43153ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
43166a4d4014SLisandro Dalcin }
43176a4d4014SLisandro Dalcin 
4318cc4c1da9SBarry Smith /*@
4319d763cef2SBarry Smith   TSSetOptionsPrefix - Sets the prefix used for searching for all
4320d763cef2SBarry Smith   TS options in the database.
4321d763cef2SBarry Smith 
4322c3339decSBarry Smith   Logically Collective
4323d763cef2SBarry Smith 
4324d8d19677SJose E. Roman   Input Parameters:
4325bcf0153eSBarry Smith + ts     - The `TS` context
4326d763cef2SBarry Smith - prefix - The prefix to prepend to all option names
4327d763cef2SBarry Smith 
4328bcf0153eSBarry Smith   Level: advanced
4329bcf0153eSBarry Smith 
4330bcf0153eSBarry Smith   Note:
4331d763cef2SBarry Smith   A hyphen (-) must NOT be given at the beginning of the prefix name.
4332d763cef2SBarry Smith   The first character of all runtime options is AUTOMATICALLY the
4333d763cef2SBarry Smith   hyphen.
4334d763cef2SBarry Smith 
43351cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetFromOptions()`, `TSAppendOptionsPrefix()`
4336d763cef2SBarry Smith @*/
4337d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetOptionsPrefix(TS ts, const char prefix[])
4338d71ae5a4SJacob Faibussowitsch {
4339089b2837SJed Brown   SNES snes;
4340d763cef2SBarry Smith 
4341d763cef2SBarry Smith   PetscFunctionBegin;
43420700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
43439566063dSJacob Faibussowitsch   PetscCall(PetscObjectSetOptionsPrefix((PetscObject)ts, prefix));
43449566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts, &snes));
43459566063dSJacob Faibussowitsch   PetscCall(SNESSetOptionsPrefix(snes, prefix));
43463ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
4347d763cef2SBarry Smith }
4348d763cef2SBarry Smith 
4349cc4c1da9SBarry Smith /*@
4350d763cef2SBarry Smith   TSAppendOptionsPrefix - Appends to the prefix used for searching for all
4351d763cef2SBarry Smith   TS options in the database.
4352d763cef2SBarry Smith 
4353c3339decSBarry Smith   Logically Collective
4354d763cef2SBarry Smith 
4355d8d19677SJose E. Roman   Input Parameters:
4356bcf0153eSBarry Smith + ts     - The `TS` context
4357d763cef2SBarry Smith - prefix - The prefix to prepend to all option names
4358d763cef2SBarry Smith 
4359bcf0153eSBarry Smith   Level: advanced
4360bcf0153eSBarry Smith 
4361bcf0153eSBarry Smith   Note:
4362d763cef2SBarry Smith   A hyphen (-) must NOT be given at the beginning of the prefix name.
4363d763cef2SBarry Smith   The first character of all runtime options is AUTOMATICALLY the
4364d763cef2SBarry Smith   hyphen.
4365d763cef2SBarry Smith 
43661cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSGetOptionsPrefix()`, `TSSetOptionsPrefix()`, `TSSetFromOptions()`
4367d763cef2SBarry Smith @*/
4368d71ae5a4SJacob Faibussowitsch PetscErrorCode TSAppendOptionsPrefix(TS ts, const char prefix[])
4369d71ae5a4SJacob Faibussowitsch {
4370089b2837SJed Brown   SNES snes;
4371d763cef2SBarry Smith 
4372d763cef2SBarry Smith   PetscFunctionBegin;
43730700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
43749566063dSJacob Faibussowitsch   PetscCall(PetscObjectAppendOptionsPrefix((PetscObject)ts, prefix));
43759566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts, &snes));
43769566063dSJacob Faibussowitsch   PetscCall(SNESAppendOptionsPrefix(snes, prefix));
43773ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
4378d763cef2SBarry Smith }
4379d763cef2SBarry Smith 
4380cc4c1da9SBarry Smith /*@
4381d763cef2SBarry Smith   TSGetOptionsPrefix - Sets the prefix used for searching for all
4382bcf0153eSBarry Smith   `TS` options in the database.
4383d763cef2SBarry Smith 
4384d763cef2SBarry Smith   Not Collective
4385d763cef2SBarry Smith 
4386d763cef2SBarry Smith   Input Parameter:
4387bcf0153eSBarry Smith . ts - The `TS` context
4388d763cef2SBarry Smith 
4389d763cef2SBarry Smith   Output Parameter:
4390d763cef2SBarry Smith . prefix - A pointer to the prefix string used
4391d763cef2SBarry Smith 
4392d763cef2SBarry Smith   Level: intermediate
4393d763cef2SBarry Smith 
43941cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSAppendOptionsPrefix()`, `TSSetFromOptions()`
4395d763cef2SBarry Smith @*/
4396d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetOptionsPrefix(TS ts, const char *prefix[])
4397d71ae5a4SJacob Faibussowitsch {
4398d763cef2SBarry Smith   PetscFunctionBegin;
43990700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
44004f572ea9SToby Isaac   PetscAssertPointer(prefix, 2);
44019566063dSJacob Faibussowitsch   PetscCall(PetscObjectGetOptionsPrefix((PetscObject)ts, prefix));
44023ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
4403d763cef2SBarry Smith }
4404d763cef2SBarry Smith 
4405d763cef2SBarry Smith /*@C
4406d763cef2SBarry Smith   TSGetRHSJacobian - Returns the Jacobian J at the present timestep.
4407d763cef2SBarry Smith 
4408bcf0153eSBarry Smith   Not Collective, but parallel objects are returned if ts is parallel
4409d763cef2SBarry Smith 
4410d763cef2SBarry Smith   Input Parameter:
4411bcf0153eSBarry Smith . ts - The `TS` context obtained from `TSCreate()`
4412d763cef2SBarry Smith 
4413d763cef2SBarry Smith   Output Parameters:
4414195e9b02SBarry Smith + Amat - The (approximate) Jacobian J of G, where U_t = G(U,t)  (or `NULL`)
4415195e9b02SBarry Smith . Pmat - The matrix from which the preconditioner is constructed, usually the same as `Amat`  (or `NULL`)
4416195e9b02SBarry Smith . func - Function to compute the Jacobian of the RHS  (or `NULL`)
4417195e9b02SBarry Smith - ctx  - User-defined context for Jacobian evaluation routine  (or `NULL`)
4418d763cef2SBarry Smith 
4419d763cef2SBarry Smith   Level: intermediate
4420d763cef2SBarry Smith 
4421bcf0153eSBarry Smith   Note:
4422195e9b02SBarry Smith   You can pass in `NULL` for any return argument you do not need.
4423bcf0153eSBarry Smith 
44241cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSGetTimeStep()`, `TSGetMatrices()`, `TSGetTime()`, `TSGetStepNumber()`
4425d763cef2SBarry Smith 
4426d763cef2SBarry Smith @*/
44278434afd1SBarry Smith PetscErrorCode TSGetRHSJacobian(TS ts, Mat *Amat, Mat *Pmat, TSRHSJacobianFn **func, void **ctx)
4428d71ae5a4SJacob Faibussowitsch {
442924989b8cSPeter Brune   DM dm;
4430089b2837SJed Brown 
4431d763cef2SBarry Smith   PetscFunctionBegin;
443223a57915SBarry Smith   if (Amat || Pmat) {
443323a57915SBarry Smith     SNES snes;
44349566063dSJacob Faibussowitsch     PetscCall(TSGetSNES(ts, &snes));
44359566063dSJacob Faibussowitsch     PetscCall(SNESSetUpMatrices(snes));
44369566063dSJacob Faibussowitsch     PetscCall(SNESGetJacobian(snes, Amat, Pmat, NULL, NULL));
443723a57915SBarry Smith   }
44389566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
44399566063dSJacob Faibussowitsch   PetscCall(DMTSGetRHSJacobian(dm, func, ctx));
44403ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
4441d763cef2SBarry Smith }
4442d763cef2SBarry Smith 
44432eca1d9cSJed Brown /*@C
44442eca1d9cSJed Brown   TSGetIJacobian - Returns the implicit Jacobian at the present timestep.
44452eca1d9cSJed Brown 
4446bcf0153eSBarry Smith   Not Collective, but parallel objects are returned if ts is parallel
44472eca1d9cSJed Brown 
44482eca1d9cSJed Brown   Input Parameter:
4449bcf0153eSBarry Smith . ts - The `TS` context obtained from `TSCreate()`
44502eca1d9cSJed Brown 
44512eca1d9cSJed Brown   Output Parameters:
4452e4357dc4SBarry Smith + Amat - The (approximate) Jacobian of F(t,U,U_t)
4453195e9b02SBarry Smith . Pmat - The matrix from which the preconditioner is constructed, often the same as `Amat`
44542eca1d9cSJed Brown . f    - The function to compute the matrices
44552eca1d9cSJed Brown - ctx  - User-defined context for Jacobian evaluation routine
44562eca1d9cSJed Brown 
44572eca1d9cSJed Brown   Level: advanced
44582eca1d9cSJed Brown 
4459bcf0153eSBarry Smith   Note:
4460195e9b02SBarry Smith   You can pass in `NULL` for any return argument you do not need.
4461bcf0153eSBarry Smith 
44621cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSGetTimeStep()`, `TSGetRHSJacobian()`, `TSGetMatrices()`, `TSGetTime()`, `TSGetStepNumber()`
44632eca1d9cSJed Brown @*/
44648434afd1SBarry Smith PetscErrorCode TSGetIJacobian(TS ts, Mat *Amat, Mat *Pmat, TSIJacobianFn **f, void **ctx)
4465d71ae5a4SJacob Faibussowitsch {
446624989b8cSPeter Brune   DM dm;
44670910c330SBarry Smith 
44682eca1d9cSJed Brown   PetscFunctionBegin;
4469c0aab802Sstefano_zampini   if (Amat || Pmat) {
4470c0aab802Sstefano_zampini     SNES snes;
44719566063dSJacob Faibussowitsch     PetscCall(TSGetSNES(ts, &snes));
44729566063dSJacob Faibussowitsch     PetscCall(SNESSetUpMatrices(snes));
44739566063dSJacob Faibussowitsch     PetscCall(SNESGetJacobian(snes, Amat, Pmat, NULL, NULL));
4474c0aab802Sstefano_zampini   }
44759566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
44769566063dSJacob Faibussowitsch   PetscCall(DMTSGetIJacobian(dm, f, ctx));
44773ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
44782eca1d9cSJed Brown }
44792eca1d9cSJed Brown 
4480af0996ceSBarry Smith #include <petsc/private/dmimpl.h>
44816c699258SBarry Smith /*@
4482bcf0153eSBarry Smith   TSSetDM - Sets the `DM` that may be used by some nonlinear solvers or preconditioners under the `TS`
44836c699258SBarry Smith 
4484c3339decSBarry Smith   Logically Collective
44856c699258SBarry Smith 
44866c699258SBarry Smith   Input Parameters:
4487bcf0153eSBarry Smith + ts - the `TS` integrator object
4488195e9b02SBarry Smith - dm - the dm, cannot be `NULL`
44896c699258SBarry Smith 
44906c699258SBarry Smith   Level: intermediate
44916c699258SBarry Smith 
4492bcf0153eSBarry Smith   Notes:
4493bcf0153eSBarry Smith   A `DM` can only be used for solving one problem at a time because information about the problem is stored on the `DM`,
4494bcf0153eSBarry Smith   even when not using interfaces like `DMTSSetIFunction()`.  Use `DMClone()` to get a distinct `DM` when solving
4495bcf0153eSBarry Smith   different problems using the same function space.
4496bcf0153eSBarry Smith 
44971cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `DM`, `TSGetDM()`, `SNESSetDM()`, `SNESGetDM()`
44986c699258SBarry Smith @*/
4499d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetDM(TS ts, DM dm)
4500d71ae5a4SJacob Faibussowitsch {
4501089b2837SJed Brown   SNES snes;
4502942e3340SBarry Smith   DMTS tsdm;
45036c699258SBarry Smith 
45046c699258SBarry Smith   PetscFunctionBegin;
45050700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
45062a808120SBarry Smith   PetscValidHeaderSpecific(dm, DM_CLASSID, 2);
45079566063dSJacob Faibussowitsch   PetscCall(PetscObjectReference((PetscObject)dm));
4508942e3340SBarry Smith   if (ts->dm) { /* Move the DMTS context over to the new DM unless the new DM already has one */
45092a34c10cSBarry Smith     if (ts->dm->dmts && !dm->dmts) {
45109566063dSJacob Faibussowitsch       PetscCall(DMCopyDMTS(ts->dm, dm));
45119566063dSJacob Faibussowitsch       PetscCall(DMGetDMTS(ts->dm, &tsdm));
45121e66621cSBarry Smith       /* Grant write privileges to the replacement DM */
45131e66621cSBarry Smith       if (tsdm->originaldm == ts->dm) tsdm->originaldm = dm;
451424989b8cSPeter Brune     }
45159566063dSJacob Faibussowitsch     PetscCall(DMDestroy(&ts->dm));
451624989b8cSPeter Brune   }
45176c699258SBarry Smith   ts->dm = dm;
4518bbd56ea5SKarl Rupp 
45199566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts, &snes));
45209566063dSJacob Faibussowitsch   PetscCall(SNESSetDM(snes, dm));
45213ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
45226c699258SBarry Smith }
45236c699258SBarry Smith 
45246c699258SBarry Smith /*@
4525bcf0153eSBarry Smith   TSGetDM - Gets the `DM` that may be used by some preconditioners
45266c699258SBarry Smith 
45273f9fe445SBarry Smith   Not Collective
45286c699258SBarry Smith 
45296c699258SBarry Smith   Input Parameter:
4530bcf0153eSBarry Smith . ts - the `TS`
45316c699258SBarry Smith 
45326c699258SBarry Smith   Output Parameter:
4533195e9b02SBarry Smith . dm - the `DM`
45346c699258SBarry Smith 
45356c699258SBarry Smith   Level: intermediate
45366c699258SBarry Smith 
45371cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `DM`, `TSSetDM()`, `SNESSetDM()`, `SNESGetDM()`
45386c699258SBarry Smith @*/
4539d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetDM(TS ts, DM *dm)
4540d71ae5a4SJacob Faibussowitsch {
45416c699258SBarry Smith   PetscFunctionBegin;
45420700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
4543496e6a7aSJed Brown   if (!ts->dm) {
45449566063dSJacob Faibussowitsch     PetscCall(DMShellCreate(PetscObjectComm((PetscObject)ts), &ts->dm));
45454bd3aaa3SHong Zhang     if (ts->snes) PetscCall(SNESSetDM(ts->snes, ts->dm));
4546496e6a7aSJed Brown   }
45476c699258SBarry Smith   *dm = ts->dm;
45483ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
45496c699258SBarry Smith }
45501713a123SBarry Smith 
45510f5c6efeSJed Brown /*@
45522ba42892SBarry Smith   SNESTSFormFunction - Function to evaluate nonlinear residual defined by an ODE solver algorithm implemented within `TS`
45530f5c6efeSJed Brown 
4554c3339decSBarry Smith   Logically Collective
45550f5c6efeSJed Brown 
4556d8d19677SJose E. Roman   Input Parameters:
4557d42a1c89SJed Brown + snes - nonlinear solver
45580910c330SBarry Smith . U    - the current state at which to evaluate the residual
45592ba42892SBarry Smith - ctx  - user context, must be a `TS`
45600f5c6efeSJed Brown 
45610f5c6efeSJed Brown   Output Parameter:
45620f5c6efeSJed Brown . F - the nonlinear residual
45630f5c6efeSJed Brown 
45642ba42892SBarry Smith   Level: developer
45650f5c6efeSJed Brown 
4566bcf0153eSBarry Smith   Note:
4567bcf0153eSBarry Smith   This function is not normally called by users and is automatically registered with the `SNES` used by `TS`.
4568bcf0153eSBarry Smith   It is most frequently passed to `MatFDColoringSetFunction()`.
4569bcf0153eSBarry Smith 
45701cc06b55SBarry Smith .seealso: [](ch_ts), `SNESSetFunction()`, `MatFDColoringSetFunction()`
45710f5c6efeSJed Brown @*/
4572d71ae5a4SJacob Faibussowitsch PetscErrorCode SNESTSFormFunction(SNES snes, Vec U, Vec F, void *ctx)
4573d71ae5a4SJacob Faibussowitsch {
45740f5c6efeSJed Brown   TS ts = (TS)ctx;
45750f5c6efeSJed Brown 
45760f5c6efeSJed Brown   PetscFunctionBegin;
45770f5c6efeSJed Brown   PetscValidHeaderSpecific(snes, SNES_CLASSID, 1);
45780910c330SBarry Smith   PetscValidHeaderSpecific(U, VEC_CLASSID, 2);
45790f5c6efeSJed Brown   PetscValidHeaderSpecific(F, VEC_CLASSID, 3);
45800f5c6efeSJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 4);
4581346ce620SStefano Zampini   PetscCheck(ts->ops->snesfunction, PetscObjectComm((PetscObject)ts), PETSC_ERR_SUP, "No method snesfunction for TS of type %s", ((PetscObject)ts)->type_name);
4582346ce620SStefano Zampini   PetscCall((*ts->ops->snesfunction)(snes, U, F, ts));
45833ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
45840f5c6efeSJed Brown }
45850f5c6efeSJed Brown 
45860f5c6efeSJed Brown /*@
45872ba42892SBarry Smith   SNESTSFormJacobian - Function to evaluate the Jacobian defined by an ODE solver algorithm implemented within `TS`
45880f5c6efeSJed Brown 
4589c3339decSBarry Smith   Collective
45900f5c6efeSJed Brown 
4591d8d19677SJose E. Roman   Input Parameters:
45920f5c6efeSJed Brown + snes - nonlinear solver
45930910c330SBarry Smith . U    - the current state at which to evaluate the residual
4594bcf0153eSBarry Smith - ctx  - user context, must be a `TS`
45950f5c6efeSJed Brown 
4596d8d19677SJose E. Roman   Output Parameters:
45970f5c6efeSJed Brown + A - the Jacobian
45987addb90fSBarry Smith - B - the matrix used to construct the preconditioner (often the same as `A`)
45990f5c6efeSJed Brown 
46000f5c6efeSJed Brown   Level: developer
46010f5c6efeSJed Brown 
4602bcf0153eSBarry Smith   Note:
4603bcf0153eSBarry Smith   This function is not normally called by users and is automatically registered with the `SNES` used by `TS`.
4604bcf0153eSBarry Smith 
46051cc06b55SBarry Smith .seealso: [](ch_ts), `SNESSetJacobian()`
46060f5c6efeSJed Brown @*/
4607d71ae5a4SJacob Faibussowitsch PetscErrorCode SNESTSFormJacobian(SNES snes, Vec U, Mat A, Mat B, void *ctx)
4608d71ae5a4SJacob Faibussowitsch {
46090f5c6efeSJed Brown   TS ts = (TS)ctx;
46100f5c6efeSJed Brown 
46110f5c6efeSJed Brown   PetscFunctionBegin;
46120f5c6efeSJed Brown   PetscValidHeaderSpecific(snes, SNES_CLASSID, 1);
46130910c330SBarry Smith   PetscValidHeaderSpecific(U, VEC_CLASSID, 2);
461494ab13aaSBarry Smith   PetscValidHeaderSpecific(A, MAT_CLASSID, 3);
461594ab13aaSBarry Smith   PetscValidHeaderSpecific(B, MAT_CLASSID, 4);
4616064a246eSJacob Faibussowitsch   PetscValidHeaderSpecific(ts, TS_CLASSID, 5);
4617346ce620SStefano Zampini   PetscCheck(ts->ops->snesjacobian, PetscObjectComm((PetscObject)ts), PETSC_ERR_SUP, "No method snesjacobian for TS of type %s", ((PetscObject)ts)->type_name);
4618346ce620SStefano Zampini   PetscCall((*ts->ops->snesjacobian)(snes, U, A, B, ts));
46193ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
46200f5c6efeSJed Brown }
4621325fc9f4SBarry Smith 
46220e4ef248SJed Brown /*@C
4623dd8e379bSPierre Jolivet   TSComputeRHSFunctionLinear - Evaluate the right-hand side via the user-provided Jacobian, for linear problems Udot = A U only
46240e4ef248SJed Brown 
4625c3339decSBarry Smith   Collective
46260e4ef248SJed Brown 
46274165533cSJose E. Roman   Input Parameters:
46280e4ef248SJed Brown + ts  - time stepping context
46290e4ef248SJed Brown . t   - time at which to evaluate
46300910c330SBarry Smith . U   - state at which to evaluate
46310e4ef248SJed Brown - ctx - context
46320e4ef248SJed Brown 
46334165533cSJose E. Roman   Output Parameter:
4634dd8e379bSPierre Jolivet . F - right-hand side
46350e4ef248SJed Brown 
46360e4ef248SJed Brown   Level: intermediate
46370e4ef248SJed Brown 
4638bcf0153eSBarry Smith   Note:
4639dd8e379bSPierre Jolivet   This function is intended to be passed to `TSSetRHSFunction()` to evaluate the right-hand side for linear problems.
4640bcf0153eSBarry Smith   The matrix (and optionally the evaluation context) should be passed to `TSSetRHSJacobian()`.
46410e4ef248SJed Brown 
46421cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetRHSFunction()`, `TSSetRHSJacobian()`, `TSComputeRHSJacobianConstant()`
46430e4ef248SJed Brown @*/
4644d71ae5a4SJacob Faibussowitsch PetscErrorCode TSComputeRHSFunctionLinear(TS ts, PetscReal t, Vec U, Vec F, void *ctx)
4645d71ae5a4SJacob Faibussowitsch {
46460e4ef248SJed Brown   Mat Arhs, Brhs;
46470e4ef248SJed Brown 
46480e4ef248SJed Brown   PetscFunctionBegin;
46499566063dSJacob Faibussowitsch   PetscCall(TSGetRHSMats_Private(ts, &Arhs, &Brhs));
46502663174eSHong Zhang   /* undo the damage caused by shifting */
46519566063dSJacob Faibussowitsch   PetscCall(TSRecoverRHSJacobian(ts, Arhs, Brhs));
46529566063dSJacob Faibussowitsch   PetscCall(TSComputeRHSJacobian(ts, t, U, Arhs, Brhs));
46539566063dSJacob Faibussowitsch   PetscCall(MatMult(Arhs, U, F));
46543ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
46550e4ef248SJed Brown }
46560e4ef248SJed Brown 
46570e4ef248SJed Brown /*@C
46580e4ef248SJed Brown   TSComputeRHSJacobianConstant - Reuses a Jacobian that is time-independent.
46590e4ef248SJed Brown 
4660c3339decSBarry Smith   Collective
46610e4ef248SJed Brown 
46624165533cSJose E. Roman   Input Parameters:
46630e4ef248SJed Brown + ts  - time stepping context
46640e4ef248SJed Brown . t   - time at which to evaluate
46650910c330SBarry Smith . U   - state at which to evaluate
46660e4ef248SJed Brown - ctx - context
46670e4ef248SJed Brown 
46684165533cSJose E. Roman   Output Parameters:
46697addb90fSBarry Smith + A - Jacobian
46707addb90fSBarry Smith - B - matrix used to construct the preconditioner, often the same as `A`
46710e4ef248SJed Brown 
46720e4ef248SJed Brown   Level: intermediate
46730e4ef248SJed Brown 
4674bcf0153eSBarry Smith   Note:
4675bcf0153eSBarry Smith   This function is intended to be passed to `TSSetRHSJacobian()` to evaluate the Jacobian for linear time-independent problems.
46760e4ef248SJed Brown 
46771cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetRHSFunction()`, `TSSetRHSJacobian()`, `TSComputeRHSFunctionLinear()`
46780e4ef248SJed Brown @*/
4679d71ae5a4SJacob Faibussowitsch PetscErrorCode TSComputeRHSJacobianConstant(TS ts, PetscReal t, Vec U, Mat A, Mat B, void *ctx)
4680d71ae5a4SJacob Faibussowitsch {
46810e4ef248SJed Brown   PetscFunctionBegin;
46823ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
46830e4ef248SJed Brown }
46840e4ef248SJed Brown 
46850026cea9SSean Farley /*@C
46860026cea9SSean Farley   TSComputeIFunctionLinear - Evaluate the left hand side via the user-provided Jacobian, for linear problems only
46870026cea9SSean Farley 
4688c3339decSBarry Smith   Collective
46890026cea9SSean Farley 
46904165533cSJose E. Roman   Input Parameters:
46910026cea9SSean Farley + ts   - time stepping context
46920026cea9SSean Farley . t    - time at which to evaluate
46930910c330SBarry Smith . U    - state at which to evaluate
46940910c330SBarry Smith . Udot - time derivative of state vector
46950026cea9SSean Farley - ctx  - context
46960026cea9SSean Farley 
46974165533cSJose E. Roman   Output Parameter:
46980026cea9SSean Farley . F - left hand side
46990026cea9SSean Farley 
47000026cea9SSean Farley   Level: intermediate
47010026cea9SSean Farley 
47020026cea9SSean Farley   Notes:
47030910c330SBarry 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
4704bcf0153eSBarry Smith   user is required to write their own `TSComputeIFunction()`.
4705bcf0153eSBarry Smith   This function is intended to be passed to `TSSetIFunction()` to evaluate the left hand side for linear problems.
4706bcf0153eSBarry Smith   The matrix (and optionally the evaluation context) should be passed to `TSSetIJacobian()`.
47070026cea9SSean Farley 
4708bcf0153eSBarry Smith   Note that using this function is NOT equivalent to using `TSComputeRHSFunctionLinear()` since that solves Udot = A U
47099ae8fd06SBarry Smith 
47101cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetIFunction()`, `TSSetIJacobian()`, `TSComputeIJacobianConstant()`, `TSComputeRHSFunctionLinear()`
47110026cea9SSean Farley @*/
4712d71ae5a4SJacob Faibussowitsch PetscErrorCode TSComputeIFunctionLinear(TS ts, PetscReal t, Vec U, Vec Udot, Vec F, void *ctx)
4713d71ae5a4SJacob Faibussowitsch {
47140026cea9SSean Farley   Mat A, B;
47150026cea9SSean Farley 
47160026cea9SSean Farley   PetscFunctionBegin;
47179566063dSJacob Faibussowitsch   PetscCall(TSGetIJacobian(ts, &A, &B, NULL, NULL));
47189566063dSJacob Faibussowitsch   PetscCall(TSComputeIJacobian(ts, t, U, Udot, 1.0, A, B, PETSC_TRUE));
47199566063dSJacob Faibussowitsch   PetscCall(MatMult(A, Udot, F));
47203ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
47210026cea9SSean Farley }
47220026cea9SSean Farley 
47230026cea9SSean Farley /*@C
47248434afd1SBarry Smith   TSComputeIJacobianConstant - Reuses the matrix previously computed with the provided `TSIJacobianFn` for a semi-implicit DAE or ODE
47250026cea9SSean Farley 
4726c3339decSBarry Smith   Collective
47270026cea9SSean Farley 
47284165533cSJose E. Roman   Input Parameters:
47290026cea9SSean Farley + ts    - time stepping context
47300026cea9SSean Farley . t     - time at which to evaluate
47310910c330SBarry Smith . U     - state at which to evaluate
47320910c330SBarry Smith . Udot  - time derivative of state vector
47330026cea9SSean Farley . shift - shift to apply
47340026cea9SSean Farley - ctx   - context
47350026cea9SSean Farley 
47364165533cSJose E. Roman   Output Parameters:
47370026cea9SSean Farley + A - pointer to operator
4738d1c5d1fcSBarry Smith - B - pointer to matrix from which the preconditioner is built (often `A`)
47390026cea9SSean Farley 
4740b41af12eSJed Brown   Level: advanced
47410026cea9SSean Farley 
47420026cea9SSean Farley   Notes:
4743bcf0153eSBarry Smith   This function is intended to be passed to `TSSetIJacobian()` to evaluate the Jacobian for linear time-independent problems.
47440026cea9SSean Farley 
4745b41af12eSJed Brown   It is only appropriate for problems of the form
4746b41af12eSJed Brown 
4747d1c5d1fcSBarry Smith   $$
4748d1c5d1fcSBarry Smith   M \dot{U} = F(U,t)
4749d1c5d1fcSBarry Smith   $$
4750b41af12eSJed Brown 
4751bcf0153eSBarry Smith   where M is constant and F is non-stiff.  The user must pass M to `TSSetIJacobian()`.  The current implementation only
4752bcf0153eSBarry Smith   works with IMEX time integration methods such as `TSROSW` and `TSARKIMEX`, since there is no support for de-constructing
4753b41af12eSJed Brown   an implicit operator of the form
4754b41af12eSJed Brown 
4755d1c5d1fcSBarry Smith   $$
4756d1c5d1fcSBarry Smith   shift*M + J
4757d1c5d1fcSBarry Smith   $$
4758b41af12eSJed Brown 
4759b41af12eSJed 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
4760b41af12eSJed Brown   a copy of M or reassemble it when requested.
4761b41af12eSJed Brown 
47621cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSROSW`, `TSARKIMEX`, `TSSetIFunction()`, `TSSetIJacobian()`, `TSComputeIFunctionLinear()`
47630026cea9SSean Farley @*/
4764d71ae5a4SJacob Faibussowitsch PetscErrorCode TSComputeIJacobianConstant(TS ts, PetscReal t, Vec U, Vec Udot, PetscReal shift, Mat A, Mat B, void *ctx)
4765d71ae5a4SJacob Faibussowitsch {
47660026cea9SSean Farley   PetscFunctionBegin;
47679566063dSJacob Faibussowitsch   PetscCall(MatScale(A, shift / ts->ijacobian.shift));
4768b41af12eSJed Brown   ts->ijacobian.shift = shift;
47693ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
47700026cea9SSean Farley }
4771b41af12eSJed Brown 
4772e817cc15SEmil Constantinescu /*@
4773bcf0153eSBarry Smith   TSGetEquationType - Gets the type of the equation that `TS` is solving.
4774e817cc15SEmil Constantinescu 
4775e817cc15SEmil Constantinescu   Not Collective
4776e817cc15SEmil Constantinescu 
4777e817cc15SEmil Constantinescu   Input Parameter:
4778bcf0153eSBarry Smith . ts - the `TS` context
4779e817cc15SEmil Constantinescu 
4780e817cc15SEmil Constantinescu   Output Parameter:
4781bcf0153eSBarry Smith . equation_type - see `TSEquationType`
4782e817cc15SEmil Constantinescu 
4783e817cc15SEmil Constantinescu   Level: beginner
4784e817cc15SEmil Constantinescu 
47851cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetEquationType()`, `TSEquationType`
4786e817cc15SEmil Constantinescu @*/
4787d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetEquationType(TS ts, TSEquationType *equation_type)
4788d71ae5a4SJacob Faibussowitsch {
4789e817cc15SEmil Constantinescu   PetscFunctionBegin;
4790e817cc15SEmil Constantinescu   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
47914f572ea9SToby Isaac   PetscAssertPointer(equation_type, 2);
4792e817cc15SEmil Constantinescu   *equation_type = ts->equation_type;
47933ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
4794e817cc15SEmil Constantinescu }
4795e817cc15SEmil Constantinescu 
4796e817cc15SEmil Constantinescu /*@
4797bcf0153eSBarry Smith   TSSetEquationType - Sets the type of the equation that `TS` is solving.
4798e817cc15SEmil Constantinescu 
4799e817cc15SEmil Constantinescu   Not Collective
4800e817cc15SEmil Constantinescu 
4801d8d19677SJose E. Roman   Input Parameters:
4802bcf0153eSBarry Smith + ts            - the `TS` context
4803bcf0153eSBarry Smith - equation_type - see `TSEquationType`
4804e817cc15SEmil Constantinescu 
4805e817cc15SEmil Constantinescu   Level: advanced
4806e817cc15SEmil Constantinescu 
48071cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSGetEquationType()`, `TSEquationType`
4808e817cc15SEmil Constantinescu @*/
4809d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetEquationType(TS ts, TSEquationType equation_type)
4810d71ae5a4SJacob Faibussowitsch {
4811e817cc15SEmil Constantinescu   PetscFunctionBegin;
4812e817cc15SEmil Constantinescu   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
4813e817cc15SEmil Constantinescu   ts->equation_type = equation_type;
48143ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
4815e817cc15SEmil Constantinescu }
48160026cea9SSean Farley 
48174af1b03aSJed Brown /*@
4818bcf0153eSBarry Smith   TSGetConvergedReason - Gets the reason the `TS` iteration was stopped.
48194af1b03aSJed Brown 
48204af1b03aSJed Brown   Not Collective
48214af1b03aSJed Brown 
48224af1b03aSJed Brown   Input Parameter:
4823bcf0153eSBarry Smith . ts - the `TS` context
48244af1b03aSJed Brown 
48254af1b03aSJed Brown   Output Parameter:
4826bcf0153eSBarry Smith . reason - negative value indicates diverged, positive value converged, see `TSConvergedReason` or the
48274af1b03aSJed Brown             manual pages for the individual convergence tests for complete lists
48284af1b03aSJed Brown 
4829487e0bb9SJed Brown   Level: beginner
48304af1b03aSJed Brown 
4831bcf0153eSBarry Smith   Note:
4832bcf0153eSBarry Smith   Can only be called after the call to `TSSolve()` is complete.
48334af1b03aSJed Brown 
48347d66147cSPierre Jolivet .seealso: [](ch_ts), `TS`, `TSSolve()`, `TSConvergedReason`
48354af1b03aSJed Brown @*/
4836d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetConvergedReason(TS ts, TSConvergedReason *reason)
4837d71ae5a4SJacob Faibussowitsch {
48384af1b03aSJed Brown   PetscFunctionBegin;
48394af1b03aSJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
48404f572ea9SToby Isaac   PetscAssertPointer(reason, 2);
48414af1b03aSJed Brown   *reason = ts->reason;
48423ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
48434af1b03aSJed Brown }
48444af1b03aSJed Brown 
4845d6ad946cSShri Abhyankar /*@
4846bcf0153eSBarry Smith   TSSetConvergedReason - Sets the reason for handling the convergence of `TSSolve()`.
4847d6ad946cSShri Abhyankar 
48486b221cbeSPatrick Sanan   Logically Collective; reason must contain common value
4849d6ad946cSShri Abhyankar 
48506b221cbeSPatrick Sanan   Input Parameters:
4851bcf0153eSBarry Smith + ts     - the `TS` context
4852bcf0153eSBarry Smith - reason - negative value indicates diverged, positive value converged, see `TSConvergedReason` or the
4853d6ad946cSShri Abhyankar             manual pages for the individual convergence tests for complete lists
4854d6ad946cSShri Abhyankar 
4855f5abba47SShri Abhyankar   Level: advanced
4856d6ad946cSShri Abhyankar 
4857bcf0153eSBarry Smith   Note:
4858bcf0153eSBarry Smith   Can only be called while `TSSolve()` is active.
4859d6ad946cSShri Abhyankar 
48601cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSolve()`, `TSConvergedReason`
4861d6ad946cSShri Abhyankar @*/
4862d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetConvergedReason(TS ts, TSConvergedReason reason)
4863d71ae5a4SJacob Faibussowitsch {
4864d6ad946cSShri Abhyankar   PetscFunctionBegin;
4865d6ad946cSShri Abhyankar   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
4866d6ad946cSShri Abhyankar   ts->reason = reason;
48673ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
4868d6ad946cSShri Abhyankar }
4869d6ad946cSShri Abhyankar 
4870cc708dedSBarry Smith /*@
4871bcf0153eSBarry Smith   TSGetSolveTime - Gets the time after a call to `TSSolve()`
4872cc708dedSBarry Smith 
4873cc708dedSBarry Smith   Not Collective
4874cc708dedSBarry Smith 
4875cc708dedSBarry Smith   Input Parameter:
4876bcf0153eSBarry Smith . ts - the `TS` context
4877cc708dedSBarry Smith 
4878cc708dedSBarry Smith   Output Parameter:
4879bcf0153eSBarry Smith . ftime - the final time. This time corresponds to the final time set with `TSSetMaxTime()`
4880cc708dedSBarry Smith 
4881487e0bb9SJed Brown   Level: beginner
4882cc708dedSBarry Smith 
4883bcf0153eSBarry Smith   Note:
4884bcf0153eSBarry Smith   Can only be called after the call to `TSSolve()` is complete.
4885cc708dedSBarry Smith 
48867d66147cSPierre Jolivet .seealso: [](ch_ts), `TS`, `TSSolve()`, `TSConvergedReason`
4887cc708dedSBarry Smith @*/
4888d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetSolveTime(TS ts, PetscReal *ftime)
4889d71ae5a4SJacob Faibussowitsch {
4890cc708dedSBarry Smith   PetscFunctionBegin;
4891cc708dedSBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
48924f572ea9SToby Isaac   PetscAssertPointer(ftime, 2);
4893cc708dedSBarry Smith   *ftime = ts->solvetime;
48943ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
4895cc708dedSBarry Smith }
4896cc708dedSBarry Smith 
48972c18e0fdSBarry Smith /*@
48985ef26d82SJed Brown   TSGetSNESIterations - Gets the total number of nonlinear iterations
48999f67acb7SJed Brown   used by the time integrator.
49009f67acb7SJed Brown 
49019f67acb7SJed Brown   Not Collective
49029f67acb7SJed Brown 
49039f67acb7SJed Brown   Input Parameter:
4904bcf0153eSBarry Smith . ts - `TS` context
49059f67acb7SJed Brown 
49069f67acb7SJed Brown   Output Parameter:
49079f67acb7SJed Brown . nits - number of nonlinear iterations
49089f67acb7SJed Brown 
49099f67acb7SJed Brown   Level: intermediate
49109f67acb7SJed Brown 
4911195e9b02SBarry Smith   Note:
4912bcf0153eSBarry Smith   This counter is reset to zero for each successive call to `TSSolve()`.
4913bcf0153eSBarry Smith 
49141cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSolve()`, `TSGetKSPIterations()`
49159f67acb7SJed Brown @*/
4916d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetSNESIterations(TS ts, PetscInt *nits)
4917d71ae5a4SJacob Faibussowitsch {
49189f67acb7SJed Brown   PetscFunctionBegin;
49199f67acb7SJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
49204f572ea9SToby Isaac   PetscAssertPointer(nits, 2);
49215ef26d82SJed Brown   *nits = ts->snes_its;
49223ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
49239f67acb7SJed Brown }
49249f67acb7SJed Brown 
49259f67acb7SJed Brown /*@
49265ef26d82SJed Brown   TSGetKSPIterations - Gets the total number of linear iterations
49279f67acb7SJed Brown   used by the time integrator.
49289f67acb7SJed Brown 
49299f67acb7SJed Brown   Not Collective
49309f67acb7SJed Brown 
49319f67acb7SJed Brown   Input Parameter:
4932bcf0153eSBarry Smith . ts - `TS` context
49339f67acb7SJed Brown 
49349f67acb7SJed Brown   Output Parameter:
49359f67acb7SJed Brown . lits - number of linear iterations
49369f67acb7SJed Brown 
49379f67acb7SJed Brown   Level: intermediate
49389f67acb7SJed Brown 
4939bcf0153eSBarry Smith   Note:
4940bcf0153eSBarry Smith   This counter is reset to zero for each successive call to `TSSolve()`.
4941bcf0153eSBarry Smith 
4942bfe80ac4SPierre Jolivet .seealso: [](ch_ts), `TS`, `TSSolve()`, `TSGetSNESIterations()`
49439f67acb7SJed Brown @*/
4944d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetKSPIterations(TS ts, PetscInt *lits)
4945d71ae5a4SJacob Faibussowitsch {
49469f67acb7SJed Brown   PetscFunctionBegin;
49479f67acb7SJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
49484f572ea9SToby Isaac   PetscAssertPointer(lits, 2);
49495ef26d82SJed Brown   *lits = ts->ksp_its;
49503ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
49519f67acb7SJed Brown }
49529f67acb7SJed Brown 
4953cef5090cSJed Brown /*@
4954cef5090cSJed Brown   TSGetStepRejections - Gets the total number of rejected steps.
4955cef5090cSJed Brown 
4956cef5090cSJed Brown   Not Collective
4957cef5090cSJed Brown 
4958cef5090cSJed Brown   Input Parameter:
4959bcf0153eSBarry Smith . ts - `TS` context
4960cef5090cSJed Brown 
4961cef5090cSJed Brown   Output Parameter:
4962cef5090cSJed Brown . rejects - number of steps rejected
4963cef5090cSJed Brown 
4964cef5090cSJed Brown   Level: intermediate
4965cef5090cSJed Brown 
4966bcf0153eSBarry Smith   Note:
4967bcf0153eSBarry Smith   This counter is reset to zero for each successive call to `TSSolve()`.
4968bcf0153eSBarry Smith 
49691cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSolve()`, `TSGetSNESIterations()`, `TSGetKSPIterations()`, `TSSetMaxStepRejections()`, `TSGetSNESFailures()`, `TSSetMaxSNESFailures()`, `TSSetErrorIfStepFails()`
4970cef5090cSJed Brown @*/
4971d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetStepRejections(TS ts, PetscInt *rejects)
4972d71ae5a4SJacob Faibussowitsch {
4973cef5090cSJed Brown   PetscFunctionBegin;
4974cef5090cSJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
49754f572ea9SToby Isaac   PetscAssertPointer(rejects, 2);
4976cef5090cSJed Brown   *rejects = ts->reject;
49773ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
4978cef5090cSJed Brown }
4979cef5090cSJed Brown 
4980cef5090cSJed Brown /*@
4981bcf0153eSBarry Smith   TSGetSNESFailures - Gets the total number of failed `SNES` solves in a `TS`
4982cef5090cSJed Brown 
4983cef5090cSJed Brown   Not Collective
4984cef5090cSJed Brown 
4985cef5090cSJed Brown   Input Parameter:
4986bcf0153eSBarry Smith . ts - `TS` context
4987cef5090cSJed Brown 
4988cef5090cSJed Brown   Output Parameter:
4989cef5090cSJed Brown . fails - number of failed nonlinear solves
4990cef5090cSJed Brown 
4991cef5090cSJed Brown   Level: intermediate
4992cef5090cSJed Brown 
4993bcf0153eSBarry Smith   Note:
4994bcf0153eSBarry Smith   This counter is reset to zero for each successive call to `TSSolve()`.
4995bcf0153eSBarry Smith 
49961cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSolve()`, `TSGetSNESIterations()`, `TSGetKSPIterations()`, `TSSetMaxStepRejections()`, `TSGetStepRejections()`, `TSSetMaxSNESFailures()`
4997cef5090cSJed Brown @*/
4998d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetSNESFailures(TS ts, PetscInt *fails)
4999d71ae5a4SJacob Faibussowitsch {
5000cef5090cSJed Brown   PetscFunctionBegin;
5001cef5090cSJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
50024f572ea9SToby Isaac   PetscAssertPointer(fails, 2);
5003cef5090cSJed Brown   *fails = ts->num_snes_failures;
50043ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
5005cef5090cSJed Brown }
5006cef5090cSJed Brown 
5007cef5090cSJed Brown /*@
5008bcf0153eSBarry Smith   TSSetMaxStepRejections - Sets the maximum number of step rejections before a time step fails
5009cef5090cSJed Brown 
5010cef5090cSJed Brown   Not Collective
5011cef5090cSJed Brown 
5012d8d19677SJose E. Roman   Input Parameters:
5013bcf0153eSBarry Smith + ts      - `TS` context
501409cb0f53SBarry Smith - rejects - maximum number of rejected steps, pass `PETSC_UNLIMITED` for unlimited
5015cef5090cSJed Brown 
5016cef5090cSJed Brown   Options Database Key:
5017cef5090cSJed Brown . -ts_max_reject - Maximum number of step rejections before a step fails
5018cef5090cSJed Brown 
5019cef5090cSJed Brown   Level: intermediate
5020cef5090cSJed Brown 
502109cb0f53SBarry Smith   Developer Note:
502209cb0f53SBarry Smith   The options database name is incorrect.
502309cb0f53SBarry Smith 
50241cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `SNES`, `TSGetSNESIterations()`, `TSGetKSPIterations()`, `TSSetMaxSNESFailures()`, `TSGetStepRejections()`, `TSGetSNESFailures()`, `TSSetErrorIfStepFails()`, `TSGetConvergedReason()`
5025cef5090cSJed Brown @*/
5026d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetMaxStepRejections(TS ts, PetscInt rejects)
5027d71ae5a4SJacob Faibussowitsch {
5028cef5090cSJed Brown   PetscFunctionBegin;
5029cef5090cSJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
503009cb0f53SBarry Smith   if (rejects == PETSC_UNLIMITED || rejects == -1) {
503109cb0f53SBarry Smith     ts->max_reject = PETSC_UNLIMITED;
503209cb0f53SBarry Smith   } else {
503309cb0f53SBarry Smith     PetscCheck(rejects >= 0, PetscObjectComm((PetscObject)ts), PETSC_ERR_ARG_OUTOFRANGE, "Cannot have a negative maximum number of rejections");
5034cef5090cSJed Brown     ts->max_reject = rejects;
503509cb0f53SBarry Smith   }
50363ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
5037cef5090cSJed Brown }
5038cef5090cSJed Brown 
5039cef5090cSJed Brown /*@
5040bcf0153eSBarry Smith   TSSetMaxSNESFailures - Sets the maximum number of failed `SNES` solves
5041cef5090cSJed Brown 
5042cef5090cSJed Brown   Not Collective
5043cef5090cSJed Brown 
5044d8d19677SJose E. Roman   Input Parameters:
5045bcf0153eSBarry Smith + ts    - `TS` context
504609cb0f53SBarry Smith - fails - maximum number of failed nonlinear solves, pass `PETSC_UNLIMITED` to allow any number of failures.
5047cef5090cSJed Brown 
5048cef5090cSJed Brown   Options Database Key:
5049cef5090cSJed Brown . -ts_max_snes_failures - Maximum number of nonlinear solve failures
5050cef5090cSJed Brown 
5051cef5090cSJed Brown   Level: intermediate
5052cef5090cSJed Brown 
50531cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `SNES`, `TSGetSNESIterations()`, `TSGetKSPIterations()`, `TSSetMaxStepRejections()`, `TSGetStepRejections()`, `TSGetSNESFailures()`, `SNESGetConvergedReason()`, `TSGetConvergedReason()`
5054cef5090cSJed Brown @*/
5055d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetMaxSNESFailures(TS ts, PetscInt fails)
5056d71ae5a4SJacob Faibussowitsch {
5057cef5090cSJed Brown   PetscFunctionBegin;
5058cef5090cSJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
505909cb0f53SBarry Smith   if (fails == PETSC_UNLIMITED || fails == -1) {
506009cb0f53SBarry Smith     ts->max_snes_failures = PETSC_UNLIMITED;
506109cb0f53SBarry Smith   } else {
506209cb0f53SBarry Smith     PetscCheck(fails >= 0, PetscObjectComm((PetscObject)ts), PETSC_ERR_ARG_OUTOFRANGE, "Cannot have a negative maximum number of failures");
5063cef5090cSJed Brown     ts->max_snes_failures = fails;
506409cb0f53SBarry Smith   }
50653ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
5066cef5090cSJed Brown }
5067cef5090cSJed Brown 
5068cef5090cSJed Brown /*@
5069195e9b02SBarry Smith   TSSetErrorIfStepFails - Immediately error if no step succeeds during `TSSolve()`
5070cef5090cSJed Brown 
5071cef5090cSJed Brown   Not Collective
5072cef5090cSJed Brown 
5073d8d19677SJose E. Roman   Input Parameters:
5074bcf0153eSBarry Smith + ts  - `TS` context
5075bcf0153eSBarry Smith - err - `PETSC_TRUE` to error if no step succeeds, `PETSC_FALSE` to return without failure
5076cef5090cSJed Brown 
5077cef5090cSJed Brown   Options Database Key:
5078cef5090cSJed Brown . -ts_error_if_step_fails - Error if no step succeeds
5079cef5090cSJed Brown 
5080cef5090cSJed Brown   Level: intermediate
5081cef5090cSJed Brown 
508242747ad1SJacob Faibussowitsch .seealso: [](ch_ts), `TS`, `TSGetSNESIterations()`, `TSGetKSPIterations()`, `TSSetMaxStepRejections()`, `TSGetStepRejections()`, `TSGetSNESFailures()`, `TSGetConvergedReason()`
5083cef5090cSJed Brown @*/
5084d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetErrorIfStepFails(TS ts, PetscBool err)
5085d71ae5a4SJacob Faibussowitsch {
5086cef5090cSJed Brown   PetscFunctionBegin;
5087cef5090cSJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
5088cef5090cSJed Brown   ts->errorifstepfailed = err;
50893ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
5090cef5090cSJed Brown }
5091cef5090cSJed Brown 
509284df9cb4SJed Brown /*@
5093552698daSJed Brown   TSGetAdapt - Get the adaptive controller context for the current method
509484df9cb4SJed Brown 
50958f14a041SBarry Smith   Collective if controller has not yet been created
509684df9cb4SJed Brown 
50974165533cSJose E. Roman   Input Parameter:
5098ed81e22dSJed Brown . ts - time stepping context
509984df9cb4SJed Brown 
51004165533cSJose E. Roman   Output Parameter:
5101ed81e22dSJed Brown . adapt - adaptive controller
510284df9cb4SJed Brown 
510384df9cb4SJed Brown   Level: intermediate
510484df9cb4SJed Brown 
51051cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSAdapt`, `TSAdaptSetType()`, `TSAdaptChoose()`
510684df9cb4SJed Brown @*/
5107d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetAdapt(TS ts, TSAdapt *adapt)
5108d71ae5a4SJacob Faibussowitsch {
510984df9cb4SJed Brown   PetscFunctionBegin;
511084df9cb4SJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
51114f572ea9SToby Isaac   PetscAssertPointer(adapt, 2);
511284df9cb4SJed Brown   if (!ts->adapt) {
51139566063dSJacob Faibussowitsch     PetscCall(TSAdaptCreate(PetscObjectComm((PetscObject)ts), &ts->adapt));
51149566063dSJacob Faibussowitsch     PetscCall(PetscObjectIncrementTabLevel((PetscObject)ts->adapt, (PetscObject)ts, 1));
511584df9cb4SJed Brown   }
5116bec58848SLisandro Dalcin   *adapt = ts->adapt;
51173ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
511884df9cb4SJed Brown }
5119d6ebe24aSShri Abhyankar 
51201c3436cfSJed Brown /*@
5121195e9b02SBarry Smith   TSSetTolerances - Set tolerances for local truncation error when using an adaptive controller
51221c3436cfSJed Brown 
51231c3436cfSJed Brown   Logically Collective
51241c3436cfSJed Brown 
51254165533cSJose E. Roman   Input Parameters:
51261c3436cfSJed Brown + ts    - time integration context
512709cb0f53SBarry Smith . atol  - scalar absolute tolerances
512809cb0f53SBarry Smith . vatol - vector of absolute tolerances or `NULL`, used in preference to `atol` if present
512909cb0f53SBarry Smith . rtol  - scalar relative tolerances
513009cb0f53SBarry Smith - vrtol - vector of relative tolerances or `NULL`, used in preference to `rtol` if present
51311c3436cfSJed Brown 
5132195e9b02SBarry Smith   Options Database Keys:
5133a3cdaa26SBarry Smith + -ts_rtol <rtol> - relative tolerance for local truncation error
513467b8a455SSatish Balay - -ts_atol <atol> - Absolute tolerance for local truncation error
5135a3cdaa26SBarry Smith 
5136bcf0153eSBarry Smith   Level: beginner
5137bcf0153eSBarry Smith 
51383ff766beSShri Abhyankar   Notes:
513909cb0f53SBarry Smith   `PETSC_CURRENT` or `PETSC_DETERMINE` may be used for `atol` or `rtol` to indicate the current value
514009cb0f53SBarry Smith   or the default value from when the object's type was set.
514109cb0f53SBarry Smith 
51423ff766beSShri Abhyankar   With PETSc's implicit schemes for DAE problems, the calculation of the local truncation error
51433ff766beSShri Abhyankar   (LTE) includes both the differential and the algebraic variables. If one wants the LTE to be
51443ff766beSShri Abhyankar   computed only for the differential or the algebraic part then this can be done using the vector of
51453ff766beSShri Abhyankar   tolerances vatol. For example, by setting the tolerance vector with the desired tolerance for the
51463ff766beSShri Abhyankar   differential part and infinity for the algebraic part, the LTE calculation will include only the
51473ff766beSShri Abhyankar   differential variables.
51483ff766beSShri Abhyankar 
514909cb0f53SBarry Smith   Fortran Note:
515009cb0f53SBarry Smith   Use `PETSC_CURRENT_INTEGER` or `PETSC_DETERMINE_INTEGER`.
515109cb0f53SBarry Smith 
51521cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSAdapt`, `TSErrorWeightedNorm()`, `TSGetTolerances()`
51531c3436cfSJed Brown @*/
5154d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetTolerances(TS ts, PetscReal atol, Vec vatol, PetscReal rtol, Vec vrtol)
5155d71ae5a4SJacob Faibussowitsch {
51561c3436cfSJed Brown   PetscFunctionBegin;
515709cb0f53SBarry Smith   if (atol == (PetscReal)PETSC_DETERMINE) {
5158dd460d27SBarry Smith     ts->atol = ts->default_atol;
515909cb0f53SBarry Smith   } else if (atol != (PetscReal)PETSC_CURRENT) {
516009cb0f53SBarry Smith     PetscCheck(atol >= 0.0, PetscObjectComm((PetscObject)ts), PETSC_ERR_ARG_OUTOFRANGE, "Absolute tolerance %g must be non-negative", (double)atol);
516109cb0f53SBarry Smith     ts->atol = atol;
516209cb0f53SBarry Smith   }
516309cb0f53SBarry Smith 
51641c3436cfSJed Brown   if (vatol) {
51659566063dSJacob Faibussowitsch     PetscCall(PetscObjectReference((PetscObject)vatol));
51669566063dSJacob Faibussowitsch     PetscCall(VecDestroy(&ts->vatol));
51671c3436cfSJed Brown     ts->vatol = vatol;
51681c3436cfSJed Brown   }
516909cb0f53SBarry Smith 
517009cb0f53SBarry Smith   if (rtol == (PetscReal)PETSC_DETERMINE) {
5171dd460d27SBarry Smith     ts->rtol = ts->default_rtol;
517209cb0f53SBarry Smith   } else if (rtol != (PetscReal)PETSC_CURRENT) {
517309cb0f53SBarry Smith     PetscCheck(rtol >= 0.0, PetscObjectComm((PetscObject)ts), PETSC_ERR_ARG_OUTOFRANGE, "Relative tolerance %g must be non-negative", (double)rtol);
517409cb0f53SBarry Smith     ts->rtol = rtol;
517509cb0f53SBarry Smith   }
517609cb0f53SBarry Smith 
51771c3436cfSJed Brown   if (vrtol) {
51789566063dSJacob Faibussowitsch     PetscCall(PetscObjectReference((PetscObject)vrtol));
51799566063dSJacob Faibussowitsch     PetscCall(VecDestroy(&ts->vrtol));
51801c3436cfSJed Brown     ts->vrtol = vrtol;
51811c3436cfSJed Brown   }
51823ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
51831c3436cfSJed Brown }
51841c3436cfSJed Brown 
5185c5033834SJed Brown /*@
5186c5033834SJed Brown   TSGetTolerances - Get tolerances for local truncation error when using adaptive controller
5187c5033834SJed Brown 
5188c5033834SJed Brown   Logically Collective
5189c5033834SJed Brown 
51904165533cSJose E. Roman   Input Parameter:
5191c5033834SJed Brown . ts - time integration context
5192c5033834SJed Brown 
51934165533cSJose E. Roman   Output Parameters:
5194195e9b02SBarry Smith + atol  - scalar absolute tolerances, `NULL` to ignore
5195195e9b02SBarry Smith . vatol - vector of absolute tolerances, `NULL` to ignore
5196195e9b02SBarry Smith . rtol  - scalar relative tolerances, `NULL` to ignore
5197195e9b02SBarry Smith - vrtol - vector of relative tolerances, `NULL` to ignore
5198c5033834SJed Brown 
5199c5033834SJed Brown   Level: beginner
5200c5033834SJed Brown 
52011cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSAdapt`, `TSErrorWeightedNorm()`, `TSSetTolerances()`
5202c5033834SJed Brown @*/
5203d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetTolerances(TS ts, PetscReal *atol, Vec *vatol, PetscReal *rtol, Vec *vrtol)
5204d71ae5a4SJacob Faibussowitsch {
5205c5033834SJed Brown   PetscFunctionBegin;
5206c5033834SJed Brown   if (atol) *atol = ts->atol;
5207c5033834SJed Brown   if (vatol) *vatol = ts->vatol;
5208c5033834SJed Brown   if (rtol) *rtol = ts->rtol;
5209c5033834SJed Brown   if (vrtol) *vrtol = ts->vrtol;
52103ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
5211c5033834SJed Brown }
5212c5033834SJed Brown 
52139c6b16b5SShri Abhyankar /*@
52148a175baeSEmil Constantinescu   TSErrorWeightedNorm - compute a weighted norm of the difference between two state vectors based on supplied absolute and relative tolerances
52151c3436cfSJed Brown 
5216c3339decSBarry Smith   Collective
52171c3436cfSJed Brown 
52184165533cSJose E. Roman   Input Parameters:
52191c3436cfSJed Brown + ts        - time stepping context
5220a4868fbcSLisandro Dalcin . U         - state vector, usually ts->vec_sol
5221a4868fbcSLisandro Dalcin . Y         - state vector to be compared to U
5222bcf0153eSBarry Smith - wnormtype - norm type, either `NORM_2` or `NORM_INFINITY`
52237619abb3SShri 
52244165533cSJose E. Roman   Output Parameters:
5225a2b725a8SWilliam Gropp + norm  - weighted norm, a value of 1.0 achieves a balance between absolute and relative tolerances
52268a175baeSEmil Constantinescu . norma - weighted norm, a value of 1.0 means that the error meets the absolute tolerance set by the user
5227a2b725a8SWilliam Gropp - normr - weighted norm, a value of 1.0 means that the error meets the relative tolerance set by the user
5228a4868fbcSLisandro Dalcin 
5229bcf0153eSBarry Smith   Options Database Key:
5230a4868fbcSLisandro Dalcin . -ts_adapt_wnormtype <wnormtype> - 2, INFINITY
5231a4868fbcSLisandro Dalcin 
52321c3436cfSJed Brown   Level: developer
52331c3436cfSJed Brown 
52348c38e02aSSatish Balay .seealso: [](ch_ts), `TS`, `VecErrorWeightedNorms()`, `TSErrorWeightedENorm()`
52351c3436cfSJed Brown @*/
5236d71ae5a4SJacob Faibussowitsch PetscErrorCode TSErrorWeightedNorm(TS ts, Vec U, Vec Y, NormType wnormtype, PetscReal *norm, PetscReal *norma, PetscReal *normr)
5237d71ae5a4SJacob Faibussowitsch {
5238037d63e4SStefano Zampini   PetscInt norma_loc, norm_loc, normr_loc;
52398a175baeSEmil Constantinescu 
52408a175baeSEmil Constantinescu   PetscFunctionBegin;
52418a175baeSEmil Constantinescu   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
5242dabfcb17SStefano Zampini   PetscValidHeaderSpecific(U, VEC_CLASSID, 2);
5243dabfcb17SStefano Zampini   PetscValidHeaderSpecific(Y, VEC_CLASSID, 3);
5244dabfcb17SStefano Zampini   PetscValidLogicalCollectiveEnum(ts, wnormtype, 4);
5245dabfcb17SStefano Zampini   PetscAssertPointer(norm, 5);
5246dabfcb17SStefano Zampini   PetscAssertPointer(norma, 6);
5247dabfcb17SStefano Zampini   PetscAssertPointer(normr, 7);
5248037d63e4SStefano 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));
5249037d63e4SStefano Zampini   if (wnormtype == NORM_2) {
5250037d63e4SStefano Zampini     if (norm_loc) *norm = PetscSqrtReal(PetscSqr(*norm) / norm_loc);
5251037d63e4SStefano Zampini     if (norma_loc) *norma = PetscSqrtReal(PetscSqr(*norma) / norma_loc);
5252037d63e4SStefano Zampini     if (normr_loc) *normr = PetscSqrtReal(PetscSqr(*normr) / normr_loc);
52538a175baeSEmil Constantinescu   }
52543c633725SBarry Smith   PetscCheck(!PetscIsInfOrNanScalar(*norm), PetscObjectComm((PetscObject)ts), PETSC_ERR_FP, "Infinite or not-a-number generated in norm");
52553c633725SBarry Smith   PetscCheck(!PetscIsInfOrNanScalar(*norma), PetscObjectComm((PetscObject)ts), PETSC_ERR_FP, "Infinite or not-a-number generated in norma");
52563c633725SBarry Smith   PetscCheck(!PetscIsInfOrNanScalar(*normr), PetscObjectComm((PetscObject)ts), PETSC_ERR_FP, "Infinite or not-a-number generated in normr");
52573ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
52588a175baeSEmil Constantinescu }
52598a175baeSEmil Constantinescu 
52608a175baeSEmil Constantinescu /*@
52618a175baeSEmil Constantinescu   TSErrorWeightedENorm - compute a weighted error norm based on supplied absolute and relative tolerances
52628a175baeSEmil Constantinescu 
5263c3339decSBarry Smith   Collective
52648a175baeSEmil Constantinescu 
52654165533cSJose E. Roman   Input Parameters:
52668a175baeSEmil Constantinescu + ts        - time stepping context
52678a175baeSEmil Constantinescu . E         - error vector
52688a175baeSEmil Constantinescu . U         - state vector, usually ts->vec_sol
52698a175baeSEmil Constantinescu . Y         - state vector, previous time step
5270bcf0153eSBarry Smith - wnormtype - norm type, either `NORM_2` or `NORM_INFINITY`
52718a175baeSEmil Constantinescu 
52724165533cSJose E. Roman   Output Parameters:
5273a2b725a8SWilliam Gropp + norm  - weighted norm, a value of 1.0 achieves a balance between absolute and relative tolerances
52748a175baeSEmil Constantinescu . norma - weighted norm, a value of 1.0 means that the error meets the absolute tolerance set by the user
5275a2b725a8SWilliam Gropp - normr - weighted norm, a value of 1.0 means that the error meets the relative tolerance set by the user
52768a175baeSEmil Constantinescu 
5277bcf0153eSBarry Smith   Options Database Key:
52788a175baeSEmil Constantinescu . -ts_adapt_wnormtype <wnormtype> - 2, INFINITY
52798a175baeSEmil Constantinescu 
52808a175baeSEmil Constantinescu   Level: developer
52818a175baeSEmil Constantinescu 
52828c38e02aSSatish Balay .seealso: [](ch_ts), `TS`, `VecErrorWeightedNorms()`, `TSErrorWeightedNorm()`
52838a175baeSEmil Constantinescu @*/
5284d71ae5a4SJacob Faibussowitsch PetscErrorCode TSErrorWeightedENorm(TS ts, Vec E, Vec U, Vec Y, NormType wnormtype, PetscReal *norm, PetscReal *norma, PetscReal *normr)
5285d71ae5a4SJacob Faibussowitsch {
5286037d63e4SStefano Zampini   PetscInt norma_loc, norm_loc, normr_loc;
5287037d63e4SStefano Zampini 
52888a175baeSEmil Constantinescu   PetscFunctionBegin;
5289037d63e4SStefano Zampini   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
5290037d63e4SStefano 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));
5291037d63e4SStefano Zampini   if (wnormtype == NORM_2) {
5292037d63e4SStefano Zampini     if (norm_loc) *norm = PetscSqrtReal(PetscSqr(*norm) / norm_loc);
5293037d63e4SStefano Zampini     if (norma_loc) *norma = PetscSqrtReal(PetscSqr(*norma) / norma_loc);
5294037d63e4SStefano Zampini     if (normr_loc) *normr = PetscSqrtReal(PetscSqr(*normr) / normr_loc);
5295037d63e4SStefano Zampini   }
5296037d63e4SStefano Zampini   PetscCheck(!PetscIsInfOrNanScalar(*norm), PetscObjectComm((PetscObject)ts), PETSC_ERR_FP, "Infinite or not-a-number generated in norm");
5297037d63e4SStefano Zampini   PetscCheck(!PetscIsInfOrNanScalar(*norma), PetscObjectComm((PetscObject)ts), PETSC_ERR_FP, "Infinite or not-a-number generated in norma");
5298037d63e4SStefano Zampini   PetscCheck(!PetscIsInfOrNanScalar(*normr), PetscObjectComm((PetscObject)ts), PETSC_ERR_FP, "Infinite or not-a-number generated in normr");
52993ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
53008a175baeSEmil Constantinescu }
53018a175baeSEmil Constantinescu 
53028d59e960SJed Brown /*@
53038d59e960SJed Brown   TSSetCFLTimeLocal - Set the local CFL constraint relative to forward Euler
53048d59e960SJed Brown 
5305c3339decSBarry Smith   Logically Collective
53068d59e960SJed Brown 
53074165533cSJose E. Roman   Input Parameters:
53088d59e960SJed Brown + ts      - time stepping context
53098d59e960SJed Brown - cfltime - maximum stable time step if using forward Euler (value can be different on each process)
53108d59e960SJed Brown 
53118d59e960SJed Brown   Note:
53128d59e960SJed Brown   After calling this function, the global CFL time can be obtained by calling TSGetCFLTime()
53138d59e960SJed Brown 
53148d59e960SJed Brown   Level: intermediate
53158d59e960SJed Brown 
53161cc06b55SBarry Smith .seealso: [](ch_ts), `TSGetCFLTime()`, `TSADAPTCFL`
53178d59e960SJed Brown @*/
5318d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetCFLTimeLocal(TS ts, PetscReal cfltime)
5319d71ae5a4SJacob Faibussowitsch {
53208d59e960SJed Brown   PetscFunctionBegin;
53218d59e960SJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
53228d59e960SJed Brown   ts->cfltime_local = cfltime;
53238d59e960SJed Brown   ts->cfltime       = -1.;
53243ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
53258d59e960SJed Brown }
53268d59e960SJed Brown 
53278d59e960SJed Brown /*@
53288d59e960SJed Brown   TSGetCFLTime - Get the maximum stable time step according to CFL criteria applied to forward Euler
53298d59e960SJed Brown 
5330c3339decSBarry Smith   Collective
53318d59e960SJed Brown 
53324165533cSJose E. Roman   Input Parameter:
53338d59e960SJed Brown . ts - time stepping context
53348d59e960SJed Brown 
53354165533cSJose E. Roman   Output Parameter:
53368d59e960SJed Brown . cfltime - maximum stable time step for forward Euler
53378d59e960SJed Brown 
53388d59e960SJed Brown   Level: advanced
53398d59e960SJed Brown 
53401cc06b55SBarry Smith .seealso: [](ch_ts), `TSSetCFLTimeLocal()`
53418d59e960SJed Brown @*/
5342d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetCFLTime(TS ts, PetscReal *cfltime)
5343d71ae5a4SJacob Faibussowitsch {
53448d59e960SJed Brown   PetscFunctionBegin;
5345462c564dSBarry Smith   if (ts->cfltime < 0) PetscCallMPI(MPIU_Allreduce(&ts->cfltime_local, &ts->cfltime, 1, MPIU_REAL, MPIU_MIN, PetscObjectComm((PetscObject)ts)));
53468d59e960SJed Brown   *cfltime = ts->cfltime;
53473ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
53488d59e960SJed Brown }
53498d59e960SJed Brown 
5350d6ebe24aSShri Abhyankar /*@
5351d6ebe24aSShri Abhyankar   TSVISetVariableBounds - Sets the lower and upper bounds for the solution vector. xl <= x <= xu
5352d6ebe24aSShri Abhyankar 
5353d6ebe24aSShri Abhyankar   Input Parameters:
5354bcf0153eSBarry Smith + ts - the `TS` context.
5355d6ebe24aSShri Abhyankar . xl - lower bound.
5356a2b725a8SWilliam Gropp - xu - upper bound.
5357d6ebe24aSShri Abhyankar 
53582bd2b0e6SSatish Balay   Level: advanced
53592bd2b0e6SSatish Balay 
5360bcf0153eSBarry Smith   Note:
5361bcf0153eSBarry Smith   If this routine is not called then the lower and upper bounds are set to
5362bcf0153eSBarry Smith   `PETSC_NINFINITY` and `PETSC_INFINITY` respectively during `SNESSetUp()`.
5363bcf0153eSBarry Smith 
53641cc06b55SBarry Smith .seealso: [](ch_ts), `TS`
5365d6ebe24aSShri Abhyankar @*/
5366d71ae5a4SJacob Faibussowitsch PetscErrorCode TSVISetVariableBounds(TS ts, Vec xl, Vec xu)
5367d71ae5a4SJacob Faibussowitsch {
5368d6ebe24aSShri Abhyankar   SNES snes;
5369d6ebe24aSShri Abhyankar 
5370d6ebe24aSShri Abhyankar   PetscFunctionBegin;
53719566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts, &snes));
53729566063dSJacob Faibussowitsch   PetscCall(SNESVISetVariableBounds(snes, xl, xu));
53733ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
5374d6ebe24aSShri Abhyankar }
5375d6ebe24aSShri Abhyankar 
5376f9c1d6abSBarry Smith /*@
5377f9c1d6abSBarry Smith   TSComputeLinearStability - computes the linear stability function at a point
5378f9c1d6abSBarry Smith 
5379c3339decSBarry Smith   Collective
5380f9c1d6abSBarry Smith 
5381f9c1d6abSBarry Smith   Input Parameters:
5382bcf0153eSBarry Smith + ts - the `TS` context
53832fe279fdSBarry Smith . xr - real part of input argument
53842fe279fdSBarry Smith - xi - imaginary part of input argument
5385f9c1d6abSBarry Smith 
5386f9c1d6abSBarry Smith   Output Parameters:
53872fe279fdSBarry Smith + yr - real part of function value
53882fe279fdSBarry Smith - yi - imaginary part of function value
5389f9c1d6abSBarry Smith 
5390f9c1d6abSBarry Smith   Level: developer
5391f9c1d6abSBarry Smith 
53921cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetRHSFunction()`, `TSComputeIFunction()`
5393f9c1d6abSBarry Smith @*/
5394d71ae5a4SJacob Faibussowitsch PetscErrorCode TSComputeLinearStability(TS ts, PetscReal xr, PetscReal xi, PetscReal *yr, PetscReal *yi)
5395d71ae5a4SJacob Faibussowitsch {
5396f9c1d6abSBarry Smith   PetscFunctionBegin;
5397f9c1d6abSBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
5398dbbe0bcdSBarry Smith   PetscUseTypeMethod(ts, linearstability, xr, xi, yr, yi);
53993ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
5400f9c1d6abSBarry Smith }
540124655328SShri 
540224655328SShri /*@
5403dcb233daSLisandro Dalcin   TSRestartStep - Flags the solver to restart the next step
5404dcb233daSLisandro Dalcin 
5405c3339decSBarry Smith   Collective
5406dcb233daSLisandro Dalcin 
5407dcb233daSLisandro Dalcin   Input Parameter:
5408bcf0153eSBarry Smith . ts - the `TS` context obtained from `TSCreate()`
5409dcb233daSLisandro Dalcin 
5410dcb233daSLisandro Dalcin   Level: advanced
5411dcb233daSLisandro Dalcin 
5412dcb233daSLisandro Dalcin   Notes:
5413bcf0153eSBarry Smith   Multistep methods like `TSBDF` or Runge-Kutta methods with FSAL property require restarting the solver in the event of
5414dcb233daSLisandro Dalcin   discontinuities. These discontinuities may be introduced as a consequence of explicitly modifications to the solution
5415dcb233daSLisandro Dalcin   vector (which PETSc attempts to detect and handle) or problem coefficients (which PETSc is not able to detect). For
5416bcf0153eSBarry Smith   the sake of correctness and maximum safety, users are expected to call `TSRestart()` whenever they introduce
5417dcb233daSLisandro Dalcin   discontinuities in callback routines (e.g. prestep and poststep routines, or implicit/rhs function routines with
5418dcb233daSLisandro Dalcin   discontinuous source terms).
5419dcb233daSLisandro Dalcin 
54201cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSBDF`, `TSSolve()`, `TSSetPreStep()`, `TSSetPostStep()`
5421dcb233daSLisandro Dalcin @*/
5422d71ae5a4SJacob Faibussowitsch PetscErrorCode TSRestartStep(TS ts)
5423d71ae5a4SJacob Faibussowitsch {
5424dcb233daSLisandro Dalcin   PetscFunctionBegin;
5425dcb233daSLisandro Dalcin   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
5426dcb233daSLisandro Dalcin   ts->steprestart = PETSC_TRUE;
54273ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
5428dcb233daSLisandro Dalcin }
5429dcb233daSLisandro Dalcin 
5430dcb233daSLisandro Dalcin /*@
543124655328SShri   TSRollBack - Rolls back one time step
543224655328SShri 
5433c3339decSBarry Smith   Collective
543424655328SShri 
543524655328SShri   Input Parameter:
5436bcf0153eSBarry Smith . ts - the `TS` context obtained from `TSCreate()`
543724655328SShri 
543824655328SShri   Level: advanced
543924655328SShri 
54409dc50cb5SStefano Zampini .seealso: [](ch_ts), `TS`, `TSGetStepRollBack()`, `TSCreate()`, `TSSetUp()`, `TSDestroy()`, `TSSolve()`, `TSSetPreStep()`, `TSSetPreStage()`, `TSInterpolate()`
544124655328SShri @*/
5442d71ae5a4SJacob Faibussowitsch PetscErrorCode TSRollBack(TS ts)
5443d71ae5a4SJacob Faibussowitsch {
544424655328SShri   PetscFunctionBegin;
544524655328SShri   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
54463c633725SBarry Smith   PetscCheck(!ts->steprollback, PetscObjectComm((PetscObject)ts), PETSC_ERR_ARG_WRONGSTATE, "TSRollBack already called");
5447c61711c8SStefano Zampini   PetscTryTypeMethod(ts, rollback);
5448c61711c8SStefano Zampini   PetscCall(VecCopy(ts->vec_sol0, ts->vec_sol));
544924655328SShri   ts->time_step  = ts->ptime - ts->ptime_prev;
545024655328SShri   ts->ptime      = ts->ptime_prev;
5451be5899b3SLisandro Dalcin   ts->ptime_prev = ts->ptime_prev_rollback;
54522808aa04SLisandro Dalcin   ts->steps--;
5453b3de5cdeSLisandro Dalcin   ts->steprollback = PETSC_TRUE;
54543ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
545524655328SShri }
5456aeb4809dSShri Abhyankar 
5457ff22ae23SHong Zhang /*@
54589dc50cb5SStefano Zampini   TSGetStepRollBack - Get the internal flag indicating if you are rolling back a step
54599dc50cb5SStefano Zampini 
54609dc50cb5SStefano Zampini   Not collective
54619dc50cb5SStefano Zampini 
54629dc50cb5SStefano Zampini   Input Parameter:
54639dc50cb5SStefano Zampini . ts - the `TS` context obtained from `TSCreate()`
54649dc50cb5SStefano Zampini 
54659dc50cb5SStefano Zampini   Output Parameter:
54669dc50cb5SStefano Zampini . flg - the rollback flag
54679dc50cb5SStefano Zampini 
54689dc50cb5SStefano Zampini   Level: advanced
54699dc50cb5SStefano Zampini 
54709dc50cb5SStefano Zampini .seealso: [](ch_ts), `TS`, `TSCreate()`, `TSRollBack()`
54719dc50cb5SStefano Zampini @*/
54729dc50cb5SStefano Zampini PetscErrorCode TSGetStepRollBack(TS ts, PetscBool *flg)
54739dc50cb5SStefano Zampini {
54749dc50cb5SStefano Zampini   PetscFunctionBegin;
54759dc50cb5SStefano Zampini   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
54769dc50cb5SStefano Zampini   PetscAssertPointer(flg, 2);
54779dc50cb5SStefano Zampini   *flg = ts->steprollback;
54789dc50cb5SStefano Zampini   PetscFunctionReturn(PETSC_SUCCESS);
54799dc50cb5SStefano Zampini }
54809dc50cb5SStefano Zampini 
54819dc50cb5SStefano Zampini /*@
5482c6bf8827SStefano Zampini   TSGetStepResize - Get the internal flag indicating if the current step is after a resize.
5483c6bf8827SStefano Zampini 
5484c6bf8827SStefano Zampini   Not collective
5485c6bf8827SStefano Zampini 
5486c6bf8827SStefano Zampini   Input Parameter:
5487c6bf8827SStefano Zampini . ts - the `TS` context obtained from `TSCreate()`
5488c6bf8827SStefano Zampini 
5489c6bf8827SStefano Zampini   Output Parameter:
5490c6bf8827SStefano Zampini . flg - the resize flag
5491c6bf8827SStefano Zampini 
5492c6bf8827SStefano Zampini   Level: advanced
5493c6bf8827SStefano Zampini 
5494c6bf8827SStefano Zampini .seealso: [](ch_ts), `TS`, `TSCreate()`, `TSSetResize()`
5495c6bf8827SStefano Zampini @*/
5496c6bf8827SStefano Zampini PetscErrorCode TSGetStepResize(TS ts, PetscBool *flg)
5497c6bf8827SStefano Zampini {
5498c6bf8827SStefano Zampini   PetscFunctionBegin;
5499c6bf8827SStefano Zampini   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
5500c6bf8827SStefano Zampini   PetscAssertPointer(flg, 2);
5501c6bf8827SStefano Zampini   *flg = ts->stepresize;
5502c6bf8827SStefano Zampini   PetscFunctionReturn(PETSC_SUCCESS);
5503c6bf8827SStefano Zampini }
5504c6bf8827SStefano Zampini 
5505c6bf8827SStefano Zampini /*@
5506ff22ae23SHong Zhang   TSGetStages - Get the number of stages and stage values
5507ff22ae23SHong Zhang 
5508ff22ae23SHong Zhang   Input Parameter:
5509bcf0153eSBarry Smith . ts - the `TS` context obtained from `TSCreate()`
5510ff22ae23SHong Zhang 
55110429704eSStefano Zampini   Output Parameters:
55120429704eSStefano Zampini + ns - the number of stages
55130429704eSStefano Zampini - Y  - the current stage vectors
55140429704eSStefano Zampini 
5515ff22ae23SHong Zhang   Level: advanced
5516ff22ae23SHong Zhang 
5517bcf0153eSBarry Smith   Note:
5518195e9b02SBarry Smith   Both `ns` and `Y` can be `NULL`.
55190429704eSStefano Zampini 
55201cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSCreate()`
5521ff22ae23SHong Zhang @*/
5522d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetStages(TS ts, PetscInt *ns, Vec **Y)
5523d71ae5a4SJacob Faibussowitsch {
5524ff22ae23SHong Zhang   PetscFunctionBegin;
5525ff22ae23SHong Zhang   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
55264f572ea9SToby Isaac   if (ns) PetscAssertPointer(ns, 2);
55274f572ea9SToby Isaac   if (Y) PetscAssertPointer(Y, 3);
55280429704eSStefano Zampini   if (!ts->ops->getstages) {
55290429704eSStefano Zampini     if (ns) *ns = 0;
55300429704eSStefano Zampini     if (Y) *Y = NULL;
5531dbbe0bcdSBarry Smith   } else PetscUseTypeMethod(ts, getstages, ns, Y);
55323ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
5533ff22ae23SHong Zhang }
5534ff22ae23SHong Zhang 
5535847ff0e1SMatthew G. Knepley /*@C
5536847ff0e1SMatthew G. Knepley   TSComputeIJacobianDefaultColor - Computes the Jacobian using finite differences and coloring to exploit matrix sparsity.
5537847ff0e1SMatthew G. Knepley 
5538c3339decSBarry Smith   Collective
5539847ff0e1SMatthew G. Knepley 
5540847ff0e1SMatthew G. Knepley   Input Parameters:
5541bcf0153eSBarry Smith + ts    - the `TS` context
5542847ff0e1SMatthew G. Knepley . t     - current timestep
5543847ff0e1SMatthew G. Knepley . U     - state vector
5544847ff0e1SMatthew G. Knepley . Udot  - time derivative of state vector
5545847ff0e1SMatthew G. Knepley . shift - shift to apply, see note below
5546847ff0e1SMatthew G. Knepley - ctx   - an optional user context
5547847ff0e1SMatthew G. Knepley 
5548847ff0e1SMatthew G. Knepley   Output Parameters:
5549847ff0e1SMatthew G. Knepley + J - Jacobian matrix (not altered in this routine)
5550195e9b02SBarry Smith - B - newly computed Jacobian matrix to use with preconditioner (generally the same as `J`)
5551847ff0e1SMatthew G. Knepley 
5552847ff0e1SMatthew G. Knepley   Level: intermediate
5553847ff0e1SMatthew G. Knepley 
5554847ff0e1SMatthew G. Knepley   Notes:
5555847ff0e1SMatthew G. Knepley   If F(t,U,Udot)=0 is the DAE, the required Jacobian is
5556847ff0e1SMatthew G. Knepley 
5557847ff0e1SMatthew G. Knepley   dF/dU + shift*dF/dUdot
5558847ff0e1SMatthew G. Knepley 
5559847ff0e1SMatthew G. Knepley   Most users should not need to explicitly call this routine, as it
5560847ff0e1SMatthew G. Knepley   is used internally within the nonlinear solvers.
5561847ff0e1SMatthew G. Knepley 
5562bcf0153eSBarry Smith   This will first try to get the coloring from the `DM`.  If the `DM` type has no coloring
5563847ff0e1SMatthew G. Knepley   routine, then it will try to get the coloring from the matrix.  This requires that the
5564847ff0e1SMatthew G. Knepley   matrix have nonzero entries precomputed.
5565847ff0e1SMatthew G. Knepley 
55661cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetIJacobian()`, `MatFDColoringCreate()`, `MatFDColoringSetFunction()`
5567847ff0e1SMatthew G. Knepley @*/
5568d71ae5a4SJacob Faibussowitsch PetscErrorCode TSComputeIJacobianDefaultColor(TS ts, PetscReal t, Vec U, Vec Udot, PetscReal shift, Mat J, Mat B, void *ctx)
5569d71ae5a4SJacob Faibussowitsch {
5570847ff0e1SMatthew G. Knepley   SNES          snes;
5571847ff0e1SMatthew G. Knepley   MatFDColoring color;
5572847ff0e1SMatthew G. Knepley   PetscBool     hascolor, matcolor = PETSC_FALSE;
5573847ff0e1SMatthew G. Knepley 
5574847ff0e1SMatthew G. Knepley   PetscFunctionBegin;
55759566063dSJacob Faibussowitsch   PetscCall(PetscOptionsGetBool(((PetscObject)ts)->options, ((PetscObject)ts)->prefix, "-ts_fd_color_use_mat", &matcolor, NULL));
55769566063dSJacob Faibussowitsch   PetscCall(PetscObjectQuery((PetscObject)B, "TSMatFDColoring", (PetscObject *)&color));
5577847ff0e1SMatthew G. Knepley   if (!color) {
5578847ff0e1SMatthew G. Knepley     DM         dm;
5579847ff0e1SMatthew G. Knepley     ISColoring iscoloring;
5580847ff0e1SMatthew G. Knepley 
55819566063dSJacob Faibussowitsch     PetscCall(TSGetDM(ts, &dm));
55829566063dSJacob Faibussowitsch     PetscCall(DMHasColoring(dm, &hascolor));
5583847ff0e1SMatthew G. Knepley     if (hascolor && !matcolor) {
55849566063dSJacob Faibussowitsch       PetscCall(DMCreateColoring(dm, IS_COLORING_GLOBAL, &iscoloring));
55859566063dSJacob Faibussowitsch       PetscCall(MatFDColoringCreate(B, iscoloring, &color));
55862ba42892SBarry Smith       PetscCall(MatFDColoringSetFunction(color, (MatFDColoringFn *)SNESTSFormFunction, (void *)ts));
55879566063dSJacob Faibussowitsch       PetscCall(MatFDColoringSetFromOptions(color));
55889566063dSJacob Faibussowitsch       PetscCall(MatFDColoringSetUp(B, iscoloring, color));
55899566063dSJacob Faibussowitsch       PetscCall(ISColoringDestroy(&iscoloring));
5590847ff0e1SMatthew G. Knepley     } else {
5591847ff0e1SMatthew G. Knepley       MatColoring mc;
5592847ff0e1SMatthew G. Knepley 
55939566063dSJacob Faibussowitsch       PetscCall(MatColoringCreate(B, &mc));
55949566063dSJacob Faibussowitsch       PetscCall(MatColoringSetDistance(mc, 2));
55959566063dSJacob Faibussowitsch       PetscCall(MatColoringSetType(mc, MATCOLORINGSL));
55969566063dSJacob Faibussowitsch       PetscCall(MatColoringSetFromOptions(mc));
55979566063dSJacob Faibussowitsch       PetscCall(MatColoringApply(mc, &iscoloring));
55989566063dSJacob Faibussowitsch       PetscCall(MatColoringDestroy(&mc));
55999566063dSJacob Faibussowitsch       PetscCall(MatFDColoringCreate(B, iscoloring, &color));
56002ba42892SBarry Smith       PetscCall(MatFDColoringSetFunction(color, (MatFDColoringFn *)SNESTSFormFunction, (void *)ts));
56019566063dSJacob Faibussowitsch       PetscCall(MatFDColoringSetFromOptions(color));
56029566063dSJacob Faibussowitsch       PetscCall(MatFDColoringSetUp(B, iscoloring, color));
56039566063dSJacob Faibussowitsch       PetscCall(ISColoringDestroy(&iscoloring));
5604847ff0e1SMatthew G. Knepley     }
56059566063dSJacob Faibussowitsch     PetscCall(PetscObjectCompose((PetscObject)B, "TSMatFDColoring", (PetscObject)color));
56069566063dSJacob Faibussowitsch     PetscCall(PetscObjectDereference((PetscObject)color));
5607847ff0e1SMatthew G. Knepley   }
56089566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts, &snes));
56099566063dSJacob Faibussowitsch   PetscCall(MatFDColoringApply(B, color, U, snes));
5610847ff0e1SMatthew G. Knepley   if (J != B) {
56119566063dSJacob Faibussowitsch     PetscCall(MatAssemblyBegin(J, MAT_FINAL_ASSEMBLY));
56129566063dSJacob Faibussowitsch     PetscCall(MatAssemblyEnd(J, MAT_FINAL_ASSEMBLY));
5613847ff0e1SMatthew G. Knepley   }
56143ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
5615847ff0e1SMatthew G. Knepley }
561693b34091SDebojyoti Ghosh 
5617b43aa488SJacob Faibussowitsch /*@C
56186bc98fa9SBarry Smith   TSSetFunctionDomainError - Set a function that tests if the current state vector is valid
5619cb9d8021SPierre Barbier de Reuille 
562052f13ae7SStefano Zampini   Logically collective
562152f13ae7SStefano Zampini 
5622cb9d8021SPierre Barbier de Reuille   Input Parameters:
5623bcf0153eSBarry Smith + ts   - the `TS` context
5624bcf0153eSBarry Smith - func - function called within `TSFunctionDomainError()`
56256bc98fa9SBarry Smith 
562620f4b53cSBarry Smith   Calling sequence of `func`:
56278847d985SBarry Smith + ts     - the `TS` context
56286bc98fa9SBarry Smith . time   - the current time (of the stage)
56296bc98fa9SBarry Smith . state  - the state to check if it is valid
5630a144a63fSStefano Zampini - accept - (output parameter) `PETSC_FALSE` if the state is not acceptable, `PETSC_TRUE` if acceptable
5631cb9d8021SPierre Barbier de Reuille 
5632cb9d8021SPierre Barbier de Reuille   Level: intermediate
5633cb9d8021SPierre Barbier de Reuille 
56346bc98fa9SBarry Smith   Notes:
563552f13ae7SStefano Zampini   `accept` must be collectively specified.
56366bc98fa9SBarry Smith   If an implicit ODE solver is being used then, in addition to providing this routine, the
5637bcf0153eSBarry Smith   user's code should call `SNESSetFunctionDomainError()` when domain errors occur during
5638bcf0153eSBarry Smith   function evaluations where the functions are provided by `TSSetIFunction()` or `TSSetRHSFunction()`.
5639bcf0153eSBarry Smith   Use `TSGetSNES()` to obtain the `SNES` object
56406bc98fa9SBarry Smith 
5641b43aa488SJacob Faibussowitsch   Developer Notes:
5642bcf0153eSBarry Smith   The naming of this function is inconsistent with the `SNESSetFunctionDomainError()`
56436bc98fa9SBarry Smith   since one takes a function pointer and the other does not.
56446bc98fa9SBarry Smith 
56451cc06b55SBarry Smith .seealso: [](ch_ts), `TSAdaptCheckStage()`, `TSFunctionDomainError()`, `SNESSetFunctionDomainError()`, `TSGetSNES()`
5646cb9d8021SPierre Barbier de Reuille @*/
5647a144a63fSStefano Zampini PetscErrorCode TSSetFunctionDomainError(TS ts, PetscErrorCode (*func)(TS ts, PetscReal time, Vec state, PetscBool *accept))
5648d71ae5a4SJacob Faibussowitsch {
5649cb9d8021SPierre Barbier de Reuille   PetscFunctionBegin;
5650cb9d8021SPierre Barbier de Reuille   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
5651cb9d8021SPierre Barbier de Reuille   ts->functiondomainerror = func;
56523ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
5653cb9d8021SPierre Barbier de Reuille }
5654cb9d8021SPierre Barbier de Reuille 
5655cb9d8021SPierre Barbier de Reuille /*@
56566bc98fa9SBarry Smith   TSFunctionDomainError - Checks if the current state is valid
5657cb9d8021SPierre Barbier de Reuille 
565852f13ae7SStefano Zampini   Collective
565952f13ae7SStefano Zampini 
5660cb9d8021SPierre Barbier de Reuille   Input Parameters:
5661bcf0153eSBarry Smith + ts        - the `TS` context
56626bc98fa9SBarry Smith . stagetime - time of the simulation
56636bc98fa9SBarry Smith - Y         - state vector to check.
5664cb9d8021SPierre Barbier de Reuille 
5665cb9d8021SPierre Barbier de Reuille   Output Parameter:
5666bcf0153eSBarry Smith . accept - Set to `PETSC_FALSE` if the current state vector is valid.
566796a0c994SBarry Smith 
56686bc98fa9SBarry Smith   Level: developer
56696bc98fa9SBarry Smith 
5670bcf0153eSBarry Smith   Note:
5671bcf0153eSBarry Smith   This function is called by the `TS` integration routines and calls the user provided function (set with `TSSetFunctionDomainError()`)
5672bcf0153eSBarry Smith   to check if the current state is valid.
5673bcf0153eSBarry Smith 
56741cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetFunctionDomainError()`
5675cb9d8021SPierre Barbier de Reuille @*/
5676d71ae5a4SJacob Faibussowitsch PetscErrorCode TSFunctionDomainError(TS ts, PetscReal stagetime, Vec Y, PetscBool *accept)
5677d71ae5a4SJacob Faibussowitsch {
5678cb9d8021SPierre Barbier de Reuille   PetscFunctionBegin;
5679cb9d8021SPierre Barbier de Reuille   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
568052f13ae7SStefano Zampini   PetscValidLogicalCollectiveReal(ts, stagetime, 2);
568152f13ae7SStefano Zampini   PetscValidHeaderSpecific(Y, VEC_CLASSID, 3);
568252f13ae7SStefano Zampini   PetscAssertPointer(accept, 4);
5683cb9d8021SPierre Barbier de Reuille   *accept = PETSC_TRUE;
56841e66621cSBarry Smith   if (ts->functiondomainerror) PetscCall((*ts->functiondomainerror)(ts, stagetime, Y, accept));
56853ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
5686cb9d8021SPierre Barbier de Reuille }
56871ceb14c0SBarry Smith 
5688cc4c1da9SBarry Smith /*@
5689195e9b02SBarry Smith   TSClone - This function clones a time step `TS` object.
569093b34091SDebojyoti Ghosh 
5691d083f849SBarry Smith   Collective
569293b34091SDebojyoti Ghosh 
569393b34091SDebojyoti Ghosh   Input Parameter:
5694bcf0153eSBarry Smith . tsin - The input `TS`
569593b34091SDebojyoti Ghosh 
569693b34091SDebojyoti Ghosh   Output Parameter:
5697bcf0153eSBarry Smith . tsout - The output `TS` (cloned)
56985eca1a21SEmil Constantinescu 
56995eca1a21SEmil Constantinescu   Level: developer
570093b34091SDebojyoti Ghosh 
5701bcf0153eSBarry Smith   Notes:
5702bcf0153eSBarry 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.
5703bcf0153eSBarry Smith   It will likely be replaced in the future with a mechanism of switching methods on the fly.
5704bcf0153eSBarry Smith 
5705195e9b02SBarry 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
5706195e9b02SBarry Smith .vb
5707195e9b02SBarry Smith  SNES snes_dup = NULL;
5708195e9b02SBarry Smith  TSGetSNES(ts,&snes_dup);
5709195e9b02SBarry Smith  TSSetSNES(ts,snes_dup);
5710195e9b02SBarry Smith .ve
5711bcf0153eSBarry Smith 
57121cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `SNES`, `TSCreate()`, `TSSetType()`, `TSSetUp()`, `TSDestroy()`, `TSSetProblemType()`
571393b34091SDebojyoti Ghosh @*/
5714d71ae5a4SJacob Faibussowitsch PetscErrorCode TSClone(TS tsin, TS *tsout)
5715d71ae5a4SJacob Faibussowitsch {
571693b34091SDebojyoti Ghosh   TS     t;
5717dc846ba4SSatish Balay   SNES   snes_start;
5718dc846ba4SSatish Balay   DM     dm;
5719dc846ba4SSatish Balay   TSType type;
572093b34091SDebojyoti Ghosh 
572193b34091SDebojyoti Ghosh   PetscFunctionBegin;
57224f572ea9SToby Isaac   PetscAssertPointer(tsin, 1);
572393b34091SDebojyoti Ghosh   *tsout = NULL;
572493b34091SDebojyoti Ghosh 
57259566063dSJacob Faibussowitsch   PetscCall(PetscHeaderCreate(t, TS_CLASSID, "TS", "Time stepping", "TS", PetscObjectComm((PetscObject)tsin), TSDestroy, TSView));
572693b34091SDebojyoti Ghosh 
572793b34091SDebojyoti Ghosh   /* General TS description */
572893b34091SDebojyoti Ghosh   t->numbermonitors    = 0;
5729371d2eb7SMartin Diehl   t->setupcalled       = PETSC_FALSE;
573093b34091SDebojyoti Ghosh   t->ksp_its           = 0;
573193b34091SDebojyoti Ghosh   t->snes_its          = 0;
573293b34091SDebojyoti Ghosh   t->nwork             = 0;
57337d51462cSStefano Zampini   t->rhsjacobian.time  = PETSC_MIN_REAL;
573493b34091SDebojyoti Ghosh   t->rhsjacobian.scale = 1.;
573593b34091SDebojyoti Ghosh   t->ijacobian.shift   = 1.;
573693b34091SDebojyoti Ghosh 
57379566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(tsin, &snes_start));
57389566063dSJacob Faibussowitsch   PetscCall(TSSetSNES(t, snes_start));
5739d15a3a53SEmil Constantinescu 
57409566063dSJacob Faibussowitsch   PetscCall(TSGetDM(tsin, &dm));
57419566063dSJacob Faibussowitsch   PetscCall(TSSetDM(t, dm));
574293b34091SDebojyoti Ghosh 
574393b34091SDebojyoti Ghosh   t->adapt = tsin->adapt;
57449566063dSJacob Faibussowitsch   PetscCall(PetscObjectReference((PetscObject)t->adapt));
574593b34091SDebojyoti Ghosh 
5746e7069c78SShri   t->trajectory = tsin->trajectory;
57479566063dSJacob Faibussowitsch   PetscCall(PetscObjectReference((PetscObject)t->trajectory));
5748e7069c78SShri 
5749e7069c78SShri   t->event = tsin->event;
57506b10a48eSSatish Balay   if (t->event) t->event->refct++;
5751e7069c78SShri 
575293b34091SDebojyoti Ghosh   t->problem_type      = tsin->problem_type;
575393b34091SDebojyoti Ghosh   t->ptime             = tsin->ptime;
5754e7069c78SShri   t->ptime_prev        = tsin->ptime_prev;
575593b34091SDebojyoti Ghosh   t->time_step         = tsin->time_step;
575693b34091SDebojyoti Ghosh   t->max_time          = tsin->max_time;
575793b34091SDebojyoti Ghosh   t->steps             = tsin->steps;
575893b34091SDebojyoti Ghosh   t->max_steps         = tsin->max_steps;
575993b34091SDebojyoti Ghosh   t->equation_type     = tsin->equation_type;
576093b34091SDebojyoti Ghosh   t->atol              = tsin->atol;
576193b34091SDebojyoti Ghosh   t->rtol              = tsin->rtol;
576293b34091SDebojyoti Ghosh   t->max_snes_failures = tsin->max_snes_failures;
576393b34091SDebojyoti Ghosh   t->max_reject        = tsin->max_reject;
576493b34091SDebojyoti Ghosh   t->errorifstepfailed = tsin->errorifstepfailed;
576593b34091SDebojyoti Ghosh 
57669566063dSJacob Faibussowitsch   PetscCall(TSGetType(tsin, &type));
57679566063dSJacob Faibussowitsch   PetscCall(TSSetType(t, type));
576893b34091SDebojyoti Ghosh 
576993b34091SDebojyoti Ghosh   t->vec_sol = NULL;
577093b34091SDebojyoti Ghosh 
577193b34091SDebojyoti Ghosh   t->cfltime          = tsin->cfltime;
577293b34091SDebojyoti Ghosh   t->cfltime_local    = tsin->cfltime_local;
577393b34091SDebojyoti Ghosh   t->exact_final_time = tsin->exact_final_time;
577493b34091SDebojyoti Ghosh 
5775aea10558SJacob Faibussowitsch   t->ops[0] = tsin->ops[0];
577693b34091SDebojyoti Ghosh 
57770d4fed19SBarry Smith   if (((PetscObject)tsin)->fortran_func_pointers) {
57780d4fed19SBarry Smith     PetscInt i;
57795ebfa9e9SBarry Smith     PetscCall(PetscMalloc((10) * sizeof(PetscFortranCallbackFn *), &((PetscObject)t)->fortran_func_pointers));
5780ad540459SPierre Jolivet     for (i = 0; i < 10; i++) ((PetscObject)t)->fortran_func_pointers[i] = ((PetscObject)tsin)->fortran_func_pointers[i];
57810d4fed19SBarry Smith   }
578293b34091SDebojyoti Ghosh   *tsout = t;
57833ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
578493b34091SDebojyoti Ghosh }
5785f3b1f45cSBarry Smith 
5786d71ae5a4SJacob Faibussowitsch static PetscErrorCode RHSWrapperFunction_TSRHSJacobianTest(void *ctx, Vec x, Vec y)
5787d71ae5a4SJacob Faibussowitsch {
5788f3b1f45cSBarry Smith   TS ts = (TS)ctx;
5789f3b1f45cSBarry Smith 
5790f3b1f45cSBarry Smith   PetscFunctionBegin;
57919566063dSJacob Faibussowitsch   PetscCall(TSComputeRHSFunction(ts, 0, x, y));
57923ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
5793f3b1f45cSBarry Smith }
5794f3b1f45cSBarry Smith 
5795f3b1f45cSBarry Smith /*@
5796bcf0153eSBarry Smith   TSRHSJacobianTest - Compares the multiply routine provided to the `MATSHELL` with differencing on the `TS` given RHS function.
5797f3b1f45cSBarry Smith 
5798c3339decSBarry Smith   Logically Collective
5799f3b1f45cSBarry Smith 
58002fe279fdSBarry Smith   Input Parameter:
5801b43aa488SJacob Faibussowitsch . ts - the time stepping routine
5802f3b1f45cSBarry Smith 
5803f3b1f45cSBarry Smith   Output Parameter:
5804bcf0153eSBarry Smith . flg - `PETSC_TRUE` if the multiply is likely correct
5805f3b1f45cSBarry Smith 
5806bcf0153eSBarry Smith   Options Database Key:
5807f3b1f45cSBarry Smith . -ts_rhs_jacobian_test_mult -mat_shell_test_mult_view - run the test at each timestep of the integrator
5808f3b1f45cSBarry Smith 
5809f3b1f45cSBarry Smith   Level: advanced
5810f3b1f45cSBarry Smith 
5811bcf0153eSBarry Smith   Note:
5812195e9b02SBarry Smith   This only works for problems defined using `TSSetRHSFunction()` and Jacobian NOT `TSSetIFunction()` and Jacobian
5813f3b1f45cSBarry Smith 
58141cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `Mat`, `MATSHELL`, `MatCreateShell()`, `MatShellGetContext()`, `MatShellGetOperation()`, `MatShellTestMultTranspose()`, `TSRHSJacobianTestTranspose()`
5815f3b1f45cSBarry Smith @*/
5816d71ae5a4SJacob Faibussowitsch PetscErrorCode TSRHSJacobianTest(TS ts, PetscBool *flg)
5817d71ae5a4SJacob Faibussowitsch {
5818f3b1f45cSBarry Smith   Mat              J, B;
58198434afd1SBarry Smith   TSRHSJacobianFn *func;
5820f3b1f45cSBarry Smith   void            *ctx;
5821f3b1f45cSBarry Smith 
5822f3b1f45cSBarry Smith   PetscFunctionBegin;
58239566063dSJacob Faibussowitsch   PetscCall(TSGetRHSJacobian(ts, &J, &B, &func, &ctx));
58249566063dSJacob Faibussowitsch   PetscCall((*func)(ts, 0.0, ts->vec_sol, J, B, ctx));
58259566063dSJacob Faibussowitsch   PetscCall(MatShellTestMult(J, RHSWrapperFunction_TSRHSJacobianTest, ts->vec_sol, ts, flg));
58263ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
5827f3b1f45cSBarry Smith }
5828f3b1f45cSBarry Smith 
5829cc4c1da9SBarry Smith /*@
5830bcf0153eSBarry Smith   TSRHSJacobianTestTranspose - Compares the multiply transpose routine provided to the `MATSHELL` with differencing on the `TS` given RHS function.
5831f3b1f45cSBarry Smith 
5832c3339decSBarry Smith   Logically Collective
5833f3b1f45cSBarry Smith 
58342fe279fdSBarry Smith   Input Parameter:
5835b43aa488SJacob Faibussowitsch . ts - the time stepping routine
5836f3b1f45cSBarry Smith 
5837f3b1f45cSBarry Smith   Output Parameter:
5838bcf0153eSBarry Smith . flg - `PETSC_TRUE` if the multiply is likely correct
5839f3b1f45cSBarry Smith 
5840bcf0153eSBarry Smith   Options Database Key:
5841f3b1f45cSBarry Smith . -ts_rhs_jacobian_test_mult_transpose -mat_shell_test_mult_transpose_view - run the test at each timestep of the integrator
5842f3b1f45cSBarry Smith 
5843bcf0153eSBarry Smith   Level: advanced
5844bcf0153eSBarry Smith 
584595452b02SPatrick Sanan   Notes:
5846195e9b02SBarry Smith   This only works for problems defined using `TSSetRHSFunction()` and Jacobian NOT `TSSetIFunction()` and Jacobian
5847f3b1f45cSBarry Smith 
58481cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `Mat`, `MatCreateShell()`, `MatShellGetContext()`, `MatShellGetOperation()`, `MatShellTestMultTranspose()`, `TSRHSJacobianTest()`
5849f3b1f45cSBarry Smith @*/
5850d71ae5a4SJacob Faibussowitsch PetscErrorCode TSRHSJacobianTestTranspose(TS ts, PetscBool *flg)
5851d71ae5a4SJacob Faibussowitsch {
5852f3b1f45cSBarry Smith   Mat              J, B;
5853f3b1f45cSBarry Smith   void            *ctx;
58548434afd1SBarry Smith   TSRHSJacobianFn *func;
5855f3b1f45cSBarry Smith 
5856f3b1f45cSBarry Smith   PetscFunctionBegin;
58579566063dSJacob Faibussowitsch   PetscCall(TSGetRHSJacobian(ts, &J, &B, &func, &ctx));
58589566063dSJacob Faibussowitsch   PetscCall((*func)(ts, 0.0, ts->vec_sol, J, B, ctx));
58599566063dSJacob Faibussowitsch   PetscCall(MatShellTestMultTranspose(J, RHSWrapperFunction_TSRHSJacobianTest, ts->vec_sol, ts, flg));
58603ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
5861f3b1f45cSBarry Smith }
58620fe4d17eSHong Zhang 
58630fe4d17eSHong Zhang /*@
58640fe4d17eSHong Zhang   TSSetUseSplitRHSFunction - Use the split RHSFunction when a multirate method is used.
58650fe4d17eSHong Zhang 
586620f4b53cSBarry Smith   Logically Collective
58670fe4d17eSHong Zhang 
5868d8d19677SJose E. Roman   Input Parameters:
58690fe4d17eSHong Zhang + ts                   - timestepping context
5870bcf0153eSBarry Smith - use_splitrhsfunction - `PETSC_TRUE` indicates that the split RHSFunction will be used
58710fe4d17eSHong Zhang 
5872bcf0153eSBarry Smith   Options Database Key:
58730fe4d17eSHong Zhang . -ts_use_splitrhsfunction - <true,false>
58740fe4d17eSHong Zhang 
58750fe4d17eSHong Zhang   Level: intermediate
58760fe4d17eSHong Zhang 
5877bcf0153eSBarry Smith   Note:
5878195e9b02SBarry Smith   This is only for multirate methods
5879bcf0153eSBarry Smith 
58801cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSGetUseSplitRHSFunction()`
58810fe4d17eSHong Zhang @*/
5882d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetUseSplitRHSFunction(TS ts, PetscBool use_splitrhsfunction)
5883d71ae5a4SJacob Faibussowitsch {
58840fe4d17eSHong Zhang   PetscFunctionBegin;
58850fe4d17eSHong Zhang   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
58860fe4d17eSHong Zhang   ts->use_splitrhsfunction = use_splitrhsfunction;
58873ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
58880fe4d17eSHong Zhang }
58890fe4d17eSHong Zhang 
58900fe4d17eSHong Zhang /*@
58910fe4d17eSHong Zhang   TSGetUseSplitRHSFunction - Gets whether to use the split RHSFunction when a multirate method is used.
58920fe4d17eSHong Zhang 
589320f4b53cSBarry Smith   Not Collective
58940fe4d17eSHong Zhang 
58950fe4d17eSHong Zhang   Input Parameter:
58960fe4d17eSHong Zhang . ts - timestepping context
58970fe4d17eSHong Zhang 
58980fe4d17eSHong Zhang   Output Parameter:
5899bcf0153eSBarry Smith . use_splitrhsfunction - `PETSC_TRUE` indicates that the split RHSFunction will be used
59000fe4d17eSHong Zhang 
59010fe4d17eSHong Zhang   Level: intermediate
59020fe4d17eSHong Zhang 
59031cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetUseSplitRHSFunction()`
59040fe4d17eSHong Zhang @*/
5905d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetUseSplitRHSFunction(TS ts, PetscBool *use_splitrhsfunction)
5906d71ae5a4SJacob Faibussowitsch {
59070fe4d17eSHong Zhang   PetscFunctionBegin;
59080fe4d17eSHong Zhang   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
59090fe4d17eSHong Zhang   *use_splitrhsfunction = ts->use_splitrhsfunction;
59103ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
59110fe4d17eSHong Zhang }
5912d60b7d5cSBarry Smith 
5913d60b7d5cSBarry Smith /*@
5914d60b7d5cSBarry Smith   TSSetMatStructure - sets the relationship between the nonzero structure of the RHS Jacobian matrix to the IJacobian matrix.
5915d60b7d5cSBarry Smith 
5916c3339decSBarry Smith   Logically  Collective
5917d60b7d5cSBarry Smith 
5918d60b7d5cSBarry Smith   Input Parameters:
5919d60b7d5cSBarry Smith + ts  - the time-stepper
5920bcf0153eSBarry Smith - str - the structure (the default is `UNKNOWN_NONZERO_PATTERN`)
5921d60b7d5cSBarry Smith 
5922d60b7d5cSBarry Smith   Level: intermediate
5923d60b7d5cSBarry Smith 
5924bcf0153eSBarry Smith   Note:
5925d60b7d5cSBarry Smith   When the relationship between the nonzero structures is known and supplied the solution process can be much faster
5926d60b7d5cSBarry Smith 
59271cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `MatAXPY()`, `MatStructure`
5928d60b7d5cSBarry Smith  @*/
5929d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetMatStructure(TS ts, MatStructure str)
5930d71ae5a4SJacob Faibussowitsch {
5931d60b7d5cSBarry Smith   PetscFunctionBegin;
5932d60b7d5cSBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
5933d60b7d5cSBarry Smith   ts->axpy_pattern = str;
59343ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
5935d60b7d5cSBarry Smith }
59364a658b32SHong Zhang 
59374a658b32SHong Zhang /*@
59388343f784SJames Wright   TSSetEvaluationTimes - sets the evaluation points. The solution will be computed and stored for each time requested
59394a658b32SHong Zhang 
5940c3339decSBarry Smith   Collective
59414a658b32SHong Zhang 
59424a658b32SHong Zhang   Input Parameters:
59434a658b32SHong Zhang + ts          - the time-stepper
59448343f784SJames Wright . n           - number of the time points
5945264c38b7SJames Wright - time_points - array of the time points, must be increasing
59464a658b32SHong Zhang 
5947bcf0153eSBarry Smith   Options Database Key:
59488343f784SJames Wright . -ts_eval_times <t0,...tn> - Sets the evaluation times
59494a658b32SHong Zhang 
5950bcf0153eSBarry Smith   Level: intermediate
59514a658b32SHong Zhang 
59524a658b32SHong Zhang   Notes:
5953264c38b7SJames Wright   The elements in `time_points` must be all increasing. They correspond to the intermediate points to be saved.
59544a658b32SHong Zhang 
59558343f784SJames Wright   `TS_EXACTFINALTIME_MATCHSTEP` must be used to make the last time step in each sub-interval match the intermediate points specified.
59568343f784SJames Wright 
5957c80d56d9SJames Wright   The intermediate solutions are saved in a vector array that can be accessed with `TSGetEvaluationSolutions()`. Thus using evaluation times may
59588343f784SJames Wright   pressure the memory system when using a large number of time points.
59598343f784SJames Wright 
5960c80d56d9SJames Wright .seealso: [](ch_ts), `TS`, `TSGetEvaluationTimes()`, `TSGetEvaluationSolutions()`, `TSSetTimeSpan()`
59614a658b32SHong Zhang  @*/
59620fc7ecceSBarry Smith PetscErrorCode TSSetEvaluationTimes(TS ts, PetscInt n, PetscReal time_points[])
5963d71ae5a4SJacob Faibussowitsch {
59648343f784SJames Wright   PetscBool is_sorted;
59658343f784SJames Wright 
59664a658b32SHong Zhang   PetscFunctionBegin;
59674a658b32SHong Zhang   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
5968264c38b7SJames Wright   if (ts->eval_times) { // Reset eval_times
5969264c38b7SJames Wright     ts->eval_times->sol_idx        = 0;
5970264c38b7SJames Wright     ts->eval_times->time_point_idx = 0;
5971264c38b7SJames Wright     if (n != ts->eval_times->num_time_points) {
5972136cf249SJames Wright       PetscCall(PetscFree(ts->eval_times->time_points));
5973264c38b7SJames Wright       PetscCall(PetscFree(ts->eval_times->sol_times));
5974136cf249SJames Wright       PetscCall(VecDestroyVecs(ts->eval_times->num_time_points, &ts->eval_times->sol_vecs));
5975264c38b7SJames Wright     } else {
5976264c38b7SJames Wright       PetscCall(PetscArrayzero(ts->eval_times->sol_times, n));
5977264c38b7SJames Wright       for (PetscInt i = 0; i < n; i++) PetscCall(VecZeroEntries(ts->eval_times->sol_vecs[i]));
59784a658b32SHong Zhang     }
5979264c38b7SJames Wright   } else { // Create/initialize eval_times
5980136cf249SJames Wright     TSEvaluationTimes eval_times;
5981136cf249SJames Wright     PetscCall(PetscNew(&eval_times));
5982136cf249SJames Wright     PetscCall(PetscMalloc1(n, &eval_times->time_points));
5983264c38b7SJames Wright     PetscCall(PetscMalloc1(n, &eval_times->sol_times));
5984136cf249SJames Wright     eval_times->reltol  = 1e-6;
5985136cf249SJames Wright     eval_times->abstol  = 10 * PETSC_MACHINE_EPSILON;
5986136cf249SJames Wright     eval_times->worktol = 0;
5987136cf249SJames Wright     ts->eval_times      = eval_times;
59884a658b32SHong Zhang   }
5989136cf249SJames Wright   ts->eval_times->num_time_points = n;
59908343f784SJames Wright   PetscCall(PetscSortedReal(n, time_points, &is_sorted));
59918343f784SJames Wright   PetscCheck(is_sorted, PetscObjectComm((PetscObject)ts), PETSC_ERR_ARG_WRONG, "time_points array must be sorted");
5992136cf249SJames Wright   PetscCall(PetscArraycpy(ts->eval_times->time_points, time_points, n));
5993264c38b7SJames Wright   // Note: ts->vec_sol not guaranteed to exist, so ts->eval_times->sol_vecs allocated at TSSolve time
59948343f784SJames Wright   PetscFunctionReturn(PETSC_SUCCESS);
59958343f784SJames Wright }
59968343f784SJames Wright 
59978343f784SJames Wright /*@C
59988343f784SJames Wright   TSGetEvaluationTimes - gets the evaluation times set with `TSSetEvaluationTimes()`
59998343f784SJames Wright 
60008343f784SJames Wright   Not Collective
60018343f784SJames Wright 
60028343f784SJames Wright   Input Parameter:
60038343f784SJames Wright . ts - the time-stepper
60048343f784SJames Wright 
60058343f784SJames Wright   Output Parameters:
60068343f784SJames Wright + n           - number of the time points
60078343f784SJames Wright - time_points - array of the time points
60088343f784SJames Wright 
60098343f784SJames Wright   Level: beginner
60108343f784SJames Wright 
60118343f784SJames Wright   Note:
60128343f784SJames Wright   The values obtained are valid until the `TS` object is destroyed.
60138343f784SJames Wright 
60148343f784SJames Wright   Both `n` and `time_points` can be `NULL`.
60158343f784SJames Wright 
60168343f784SJames Wright   Also used to see time points set by `TSSetTimeSpan()`.
60178343f784SJames Wright 
6018c80d56d9SJames Wright .seealso: [](ch_ts), `TS`, `TSSetEvaluationTimes()`, `TSGetEvaluationSolutions()`
60198343f784SJames Wright  @*/
60208343f784SJames Wright PetscErrorCode TSGetEvaluationTimes(TS ts, PetscInt *n, const PetscReal *time_points[])
60218343f784SJames Wright {
60228343f784SJames Wright   PetscFunctionBegin;
60238343f784SJames Wright   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
60248343f784SJames Wright   if (n) PetscAssertPointer(n, 2);
60258343f784SJames Wright   if (time_points) PetscAssertPointer(time_points, 3);
6026136cf249SJames Wright   if (!ts->eval_times) {
60278343f784SJames Wright     if (n) *n = 0;
60288343f784SJames Wright     if (time_points) *time_points = NULL;
60298343f784SJames Wright   } else {
6030136cf249SJames Wright     if (n) *n = ts->eval_times->num_time_points;
6031136cf249SJames Wright     if (time_points) *time_points = ts->eval_times->time_points;
60328343f784SJames Wright   }
60338343f784SJames Wright   PetscFunctionReturn(PETSC_SUCCESS);
60348343f784SJames Wright }
60358343f784SJames Wright 
60368343f784SJames Wright /*@C
6037c80d56d9SJames Wright   TSGetEvaluationSolutions - Get the number of solutions and the solutions at the evaluation time points specified
60388343f784SJames Wright 
60398343f784SJames Wright   Input Parameter:
60408343f784SJames Wright . ts - the `TS` context obtained from `TSCreate()`
60418343f784SJames Wright 
60428343f784SJames Wright   Output Parameters:
60438343f784SJames Wright + nsol      - the number of solutions
60448343f784SJames Wright . sol_times - array of solution times corresponding to the solution vectors. See note below
60458343f784SJames Wright - Sols      - the solution vectors
60468343f784SJames Wright 
60478343f784SJames Wright   Level: intermediate
60488343f784SJames Wright 
60498343f784SJames Wright   Notes:
60508343f784SJames Wright   Both `nsol` and `Sols` can be `NULL`.
60518343f784SJames Wright 
60528343f784SJames Wright   Some time points in the evaluation points may be skipped by `TS` so that `nsol` is less than the number of points specified by `TSSetEvaluationTimes()`.
60538343f784SJames Wright   For example, manipulating the step size, especially with a reduced precision, may cause `TS` to step over certain evaluation times.
60548343f784SJames Wright 
60558343f784SJames Wright   Also used to see view solutions requested by `TSSetTimeSpan()`.
60568343f784SJames Wright 
60578343f784SJames Wright .seealso: [](ch_ts), `TS`, `TSSetEvaluationTimes()`, `TSGetEvaluationTimes()`
60588343f784SJames Wright @*/
60590fc7ecceSBarry Smith PetscErrorCode TSGetEvaluationSolutions(TS ts, PetscInt *nsol, const PetscReal *sol_times[], Vec *Sols[])
60608343f784SJames Wright {
60618343f784SJames Wright   PetscFunctionBegin;
60628343f784SJames Wright   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
60638343f784SJames Wright   if (nsol) PetscAssertPointer(nsol, 2);
60648343f784SJames Wright   if (sol_times) PetscAssertPointer(sol_times, 3);
60658343f784SJames Wright   if (Sols) PetscAssertPointer(Sols, 4);
6066136cf249SJames Wright   if (!ts->eval_times) {
60678343f784SJames Wright     if (nsol) *nsol = 0;
60688343f784SJames Wright     if (sol_times) *sol_times = NULL;
60698343f784SJames Wright     if (Sols) *Sols = NULL;
60708343f784SJames Wright   } else {
6071264c38b7SJames Wright     if (nsol) *nsol = ts->eval_times->sol_idx;
6072136cf249SJames Wright     if (sol_times) *sol_times = ts->eval_times->sol_times;
6073136cf249SJames Wright     if (Sols) *Sols = ts->eval_times->sol_vecs;
60748343f784SJames Wright   }
60758343f784SJames Wright   PetscFunctionReturn(PETSC_SUCCESS);
60768343f784SJames Wright }
60778343f784SJames Wright 
60788343f784SJames Wright /*@
60798343f784SJames Wright   TSSetTimeSpan - sets the time span. The solution will be computed and stored for each time requested in the span
60808343f784SJames Wright 
60818343f784SJames Wright   Collective
60828343f784SJames Wright 
60838343f784SJames Wright   Input Parameters:
60848343f784SJames Wright + ts         - the time-stepper
60858343f784SJames Wright . n          - number of the time points (>=2)
6086264c38b7SJames Wright - span_times - array of the time points, must be increasing. The first element and the last element are the initial time and the final time respectively.
60878343f784SJames Wright 
60888343f784SJames Wright   Options Database Key:
60898343f784SJames Wright . -ts_time_span <t0,...tf> - Sets the time span
60908343f784SJames Wright 
60918343f784SJames Wright   Level: intermediate
60928343f784SJames Wright 
60938343f784SJames Wright   Notes:
6094c80d56d9SJames Wright   This function is identical to `TSSetEvaluationTimes()`, except that it also sets the initial time and final time for the `ts` to the first and last `span_times` entries.
60958343f784SJames Wright 
6096264c38b7SJames Wright   The elements in `span_times` must be all increasing. They correspond to the intermediate points to be saved.
60978343f784SJames Wright 
60988343f784SJames Wright   `TS_EXACTFINALTIME_MATCHSTEP` must be used to make the last time step in each sub-interval match the intermediate points specified.
60998343f784SJames Wright 
6100c80d56d9SJames Wright   The intermediate solutions are saved in a vector array that can be accessed with `TSGetEvaluationSolutions()`. Thus using time span may
61018343f784SJames Wright   pressure the memory system when using a large number of span points.
61028343f784SJames Wright 
6103c80d56d9SJames Wright .seealso: [](ch_ts), `TS`, `TSSetEvaluationTimes()`, `TSGetEvaluationTimes()`, `TSGetEvaluationSolutions()`
61048343f784SJames Wright  @*/
61050fc7ecceSBarry Smith PetscErrorCode TSSetTimeSpan(TS ts, PetscInt n, PetscReal span_times[])
61068343f784SJames Wright {
61078343f784SJames Wright   PetscFunctionBegin;
61088343f784SJames Wright   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
61098343f784SJames Wright   PetscCheck(n >= 2, PetscObjectComm((PetscObject)ts), PETSC_ERR_ARG_WRONG, "Minimum time span size is 2 but %" PetscInt_FMT " is provided", n);
61108343f784SJames Wright   PetscCall(TSSetEvaluationTimes(ts, n, span_times));
61118343f784SJames Wright   PetscCall(TSSetTime(ts, span_times[0]));
61128343f784SJames Wright   PetscCall(TSSetMaxTime(ts, span_times[n - 1]));
61133ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
61144a658b32SHong Zhang }
61154a658b32SHong Zhang 
6116cc4c1da9SBarry Smith /*@
61177b2dc123SHong Zhang   TSPruneIJacobianColor - Remove nondiagonal zeros in the Jacobian matrix and update the `MatMFFD` coloring information.
6118d7cfae9bSHong Zhang 
6119195e9b02SBarry Smith   Collective
6120d7cfae9bSHong Zhang 
6121d7cfae9bSHong Zhang   Input Parameters:
6122195e9b02SBarry Smith + ts - the `TS` context
6123d7cfae9bSHong Zhang . J  - Jacobian matrix (not altered in this routine)
6124195e9b02SBarry Smith - B  - newly computed Jacobian matrix to use with preconditioner
6125d7cfae9bSHong Zhang 
6126d7cfae9bSHong Zhang   Level: intermediate
6127d7cfae9bSHong Zhang 
6128d7cfae9bSHong Zhang   Notes:
6129195e9b02SBarry Smith   This function improves the `MatFDColoring` performance when the Jacobian matrix was over-allocated or contains
6130195e9b02SBarry Smith   many constant zeros entries, which is typically the case when the matrix is generated by a `DM`
6131d7cfae9bSHong Zhang   and multiple fields are involved.
6132d7cfae9bSHong Zhang 
6133d7cfae9bSHong Zhang   Users need to make sure that the Jacobian matrix is properly filled to reflect the sparsity
6134195e9b02SBarry Smith   structure. For `MatFDColoring`, the values of nonzero entries are not important. So one can
61357b2dc123SHong Zhang   usually call `TSComputeIJacobian()` with randomized input vectors to generate a dummy Jacobian.
61367b2dc123SHong Zhang   `TSComputeIJacobian()` should be called before `TSSolve()` but after `TSSetUp()`.
6137d7cfae9bSHong Zhang 
61381cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `MatFDColoring`, `TSComputeIJacobianDefaultColor()`, `MatEliminateZeros()`, `MatFDColoringCreate()`, `MatFDColoringSetFunction()`
6139d7cfae9bSHong Zhang @*/
6140d7cfae9bSHong Zhang PetscErrorCode TSPruneIJacobianColor(TS ts, Mat J, Mat B)
6141d7cfae9bSHong Zhang {
6142d7cfae9bSHong Zhang   MatColoring   mc            = NULL;
6143d7cfae9bSHong Zhang   ISColoring    iscoloring    = NULL;
6144d7cfae9bSHong Zhang   MatFDColoring matfdcoloring = NULL;
6145d7cfae9bSHong Zhang 
6146d7cfae9bSHong Zhang   PetscFunctionBegin;
6147d7cfae9bSHong Zhang   /* Generate new coloring after eliminating zeros in the matrix */
614858c11ad4SPierre Jolivet   PetscCall(MatEliminateZeros(B, PETSC_TRUE));
6149d7cfae9bSHong Zhang   PetscCall(MatColoringCreate(B, &mc));
6150d7cfae9bSHong Zhang   PetscCall(MatColoringSetDistance(mc, 2));
6151d7cfae9bSHong Zhang   PetscCall(MatColoringSetType(mc, MATCOLORINGSL));
6152d7cfae9bSHong Zhang   PetscCall(MatColoringSetFromOptions(mc));
6153d7cfae9bSHong Zhang   PetscCall(MatColoringApply(mc, &iscoloring));
6154d7cfae9bSHong Zhang   PetscCall(MatColoringDestroy(&mc));
6155d7cfae9bSHong Zhang   /* Replace the old coloring with the new one */
6156d7cfae9bSHong Zhang   PetscCall(MatFDColoringCreate(B, iscoloring, &matfdcoloring));
61572ba42892SBarry Smith   PetscCall(MatFDColoringSetFunction(matfdcoloring, (MatFDColoringFn *)SNESTSFormFunction, (void *)ts));
6158d7cfae9bSHong Zhang   PetscCall(MatFDColoringSetFromOptions(matfdcoloring));
6159d7cfae9bSHong Zhang   PetscCall(MatFDColoringSetUp(B, iscoloring, matfdcoloring));
6160d7cfae9bSHong Zhang   PetscCall(PetscObjectCompose((PetscObject)B, "TSMatFDColoring", (PetscObject)matfdcoloring));
6161d7cfae9bSHong Zhang   PetscCall(PetscObjectDereference((PetscObject)matfdcoloring));
6162d7cfae9bSHong Zhang   PetscCall(ISColoringDestroy(&iscoloring));
61633ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
6164d7cfae9bSHong Zhang }
6165