xref: /petsc/src/ts/interface/ts.c (revision 340b794c6bb4bf4f05a91c896fd500c569804341)
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
56*340b794cSJed 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];
93136cf249SJames Wright   PetscReal              time_step, eval_times[100];
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));
153*340b794cSJed 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;
18952b0a91c0SBarry Smith   PetscBool iascii, isstring, isundials, 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 
19079566063dSJacob Faibussowitsch   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERASCII, &iascii));
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
191432077d6dSBarry Smith   if (iascii) {
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));
20109566063dSJacob Faibussowitsch   PetscCall(PetscObjectTypeCompare((PetscObject)ts, TSSUNDIALS, &isundials));
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 
2507136cf249SJames Wright   if (ts->eval_times) {
2508136cf249SJames Wright     if (!ts->eval_times->sol_vecs) PetscCall(VecDuplicateVecs(ts->vec_sol, ts->eval_times->num_time_points, &ts->eval_times->sol_vecs));
2509136cf249SJames Wright     if (!ts->eval_times->sol_times) PetscCall(PetscMalloc1(ts->eval_times->num_time_points, &ts->eval_times->sol_times));
25104a658b32SHong Zhang   }
2511298bade4SHong Zhang   if (!ts->Jacp && ts->Jacprhs) { /* IJacobianP shares the same matrix with RHSJacobianP if only RHSJacobianP is provided */
25129566063dSJacob Faibussowitsch     PetscCall(PetscObjectReference((PetscObject)ts->Jacprhs));
2513298bade4SHong Zhang     ts->Jacp = ts->Jacprhs;
2514298bade4SHong Zhang   }
2515298bade4SHong Zhang 
2516cd4cee2dSHong Zhang   if (ts->quadraturets) {
25179566063dSJacob Faibussowitsch     PetscCall(TSSetUp(ts->quadraturets));
25189566063dSJacob Faibussowitsch     PetscCall(VecDestroy(&ts->vec_costintegrand));
25199566063dSJacob Faibussowitsch     PetscCall(VecDuplicate(ts->quadraturets->vec_sol, &ts->vec_costintegrand));
2520cd4cee2dSHong Zhang   }
2521cd4cee2dSHong Zhang 
25229566063dSJacob Faibussowitsch   PetscCall(TSGetRHSJacobian(ts, NULL, NULL, &rhsjac, NULL));
2523f23ba4b3SHong Zhang   if (rhsjac == TSComputeRHSJacobianConstant) {
2524e1244c69SJed Brown     Mat  Amat, Pmat;
2525e1244c69SJed Brown     SNES snes;
25269566063dSJacob Faibussowitsch     PetscCall(TSGetSNES(ts, &snes));
25279566063dSJacob Faibussowitsch     PetscCall(SNESGetJacobian(snes, &Amat, &Pmat, NULL, NULL));
2528e1244c69SJed Brown     /* Matching matrices implies that an IJacobian is NOT set, because if it had been set, the IJacobian's matrix would
2529e1244c69SJed Brown      * have displaced the RHS matrix */
2530971015bcSStefano Zampini     if (Amat && Amat == ts->Arhs) {
2531abc0d4abSBarry 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 */
25329566063dSJacob Faibussowitsch       PetscCall(MatDuplicate(ts->Arhs, MAT_COPY_VALUES, &Amat));
25339566063dSJacob Faibussowitsch       PetscCall(SNESSetJacobian(snes, Amat, NULL, NULL, NULL));
25349566063dSJacob Faibussowitsch       PetscCall(MatDestroy(&Amat));
2535e1244c69SJed Brown     }
2536971015bcSStefano Zampini     if (Pmat && Pmat == ts->Brhs) {
25379566063dSJacob Faibussowitsch       PetscCall(MatDuplicate(ts->Brhs, MAT_COPY_VALUES, &Pmat));
25389566063dSJacob Faibussowitsch       PetscCall(SNESSetJacobian(snes, NULL, Pmat, NULL, NULL));
25399566063dSJacob Faibussowitsch       PetscCall(MatDestroy(&Pmat));
2540e1244c69SJed Brown     }
2541e1244c69SJed Brown   }
25422ffb9264SLisandro Dalcin 
25439566063dSJacob Faibussowitsch   PetscCall(TSGetAdapt(ts, &ts->adapt));
25449566063dSJacob Faibussowitsch   PetscCall(TSAdaptSetDefaultType(ts->adapt, ts->default_adapt_type));
25452ffb9264SLisandro Dalcin 
2546dbbe0bcdSBarry Smith   PetscTryTypeMethod(ts, setup);
2547277b19d0SLisandro Dalcin 
25489566063dSJacob Faibussowitsch   PetscCall(TSSetExactFinalTimeDefault(ts));
25492ffb9264SLisandro Dalcin 
2550a6772fa2SLisandro Dalcin   /* In the case where we've set a DMTSFunction or what have you, we need the default SNESFunction
25516c6b9e74SPeter Brune      to be set right but can't do it elsewhere due to the overreliance on ctx=ts.
25526c6b9e74SPeter Brune    */
25539566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
25549566063dSJacob Faibussowitsch   PetscCall(DMSNESGetFunction(dm, &func, NULL));
25551e66621cSBarry Smith   if (!func) PetscCall(DMSNESSetFunction(dm, SNESTSFormFunction, ts));
25561e66621cSBarry Smith 
2557a6772fa2SLisandro 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.
25586c6b9e74SPeter Brune      Otherwise, the SNES will use coloring internally to form the Jacobian.
25596c6b9e74SPeter Brune    */
25609566063dSJacob Faibussowitsch   PetscCall(DMSNESGetJacobian(dm, &jac, NULL));
25619566063dSJacob Faibussowitsch   PetscCall(DMTSGetIJacobian(dm, &ijac, NULL));
25629566063dSJacob Faibussowitsch   PetscCall(DMTSGetI2Jacobian(dm, &i2jac, NULL));
25639566063dSJacob Faibussowitsch   PetscCall(DMTSGetRHSJacobian(dm, &rhsjac, NULL));
25641e66621cSBarry Smith   if (!jac && (ijac || i2jac || rhsjac)) PetscCall(DMSNESSetJacobian(dm, SNESTSFormJacobian, ts));
2565c0517034SDebojyoti Ghosh 
2566c0517034SDebojyoti Ghosh   /* if time integration scheme has a starting method, call it */
2567dbbe0bcdSBarry Smith   PetscTryTypeMethod(ts, startingmethod);
2568c0517034SDebojyoti Ghosh 
2569277b19d0SLisandro Dalcin   ts->setupcalled = PETSC_TRUE;
25703ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2571277b19d0SLisandro Dalcin }
2572277b19d0SLisandro Dalcin 
2573f6a906c0SBarry Smith /*@
25740b4b7b1cSBarry 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
2575277b19d0SLisandro Dalcin 
2576c3339decSBarry Smith   Collective
2577277b19d0SLisandro Dalcin 
2578277b19d0SLisandro Dalcin   Input Parameter:
2579bcf0153eSBarry Smith . ts - the `TS` context obtained from `TSCreate()`
2580277b19d0SLisandro Dalcin 
25810b4b7b1cSBarry Smith   Level: developer
2582277b19d0SLisandro Dalcin 
25830b4b7b1cSBarry Smith   Notes:
25840b4b7b1cSBarry Smith   Any options set on the `TS` object, including those set with `TSSetFromOptions()` remain.
25850b4b7b1cSBarry Smith 
25860b4b7b1cSBarry Smith   See also `TSSetResize()` to change the size of the system being integrated (for example by adaptive mesh refinement) during the time integration.
25870b4b7b1cSBarry Smith 
2588bfe80ac4SPierre Jolivet .seealso: [](ch_ts), `TS`, `TSCreate()`, `TSSetUp()`, `TSDestroy()`, `TSSetResize()`
2589277b19d0SLisandro Dalcin @*/
2590d71ae5a4SJacob Faibussowitsch PetscErrorCode TSReset(TS ts)
2591d71ae5a4SJacob Faibussowitsch {
25921d06f6b3SHong Zhang   TS_RHSSplitLink ilink = ts->tsrhssplit, next;
2593277b19d0SLisandro Dalcin 
2594277b19d0SLisandro Dalcin   PetscFunctionBegin;
2595277b19d0SLisandro Dalcin   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
2596b18ea86cSHong Zhang 
2597dbbe0bcdSBarry Smith   PetscTryTypeMethod(ts, reset);
25989566063dSJacob Faibussowitsch   if (ts->snes) PetscCall(SNESReset(ts->snes));
25999566063dSJacob Faibussowitsch   if (ts->adapt) PetscCall(TSAdaptReset(ts->adapt));
2600bbd56ea5SKarl Rupp 
26019566063dSJacob Faibussowitsch   PetscCall(MatDestroy(&ts->Arhs));
26029566063dSJacob Faibussowitsch   PetscCall(MatDestroy(&ts->Brhs));
26039566063dSJacob Faibussowitsch   PetscCall(VecDestroy(&ts->Frhs));
26049566063dSJacob Faibussowitsch   PetscCall(VecDestroy(&ts->vec_sol));
2605c61711c8SStefano Zampini   PetscCall(VecDestroy(&ts->vec_sol0));
26069566063dSJacob Faibussowitsch   PetscCall(VecDestroy(&ts->vec_dot));
26079566063dSJacob Faibussowitsch   PetscCall(VecDestroy(&ts->vatol));
26089566063dSJacob Faibussowitsch   PetscCall(VecDestroy(&ts->vrtol));
26099566063dSJacob Faibussowitsch   PetscCall(VecDestroyVecs(ts->nwork, &ts->work));
2610bbd56ea5SKarl Rupp 
26119566063dSJacob Faibussowitsch   PetscCall(MatDestroy(&ts->Jacprhs));
26129566063dSJacob Faibussowitsch   PetscCall(MatDestroy(&ts->Jacp));
26131baa6e33SBarry Smith   if (ts->forward_solve) PetscCall(TSForwardReset(ts));
2614cd4cee2dSHong Zhang   if (ts->quadraturets) {
26159566063dSJacob Faibussowitsch     PetscCall(TSReset(ts->quadraturets));
26169566063dSJacob Faibussowitsch     PetscCall(VecDestroy(&ts->vec_costintegrand));
2617cd4cee2dSHong Zhang   }
26181d06f6b3SHong Zhang   while (ilink) {
26191d06f6b3SHong Zhang     next = ilink->next;
26209566063dSJacob Faibussowitsch     PetscCall(TSDestroy(&ilink->ts));
26219566063dSJacob Faibussowitsch     PetscCall(PetscFree(ilink->splitname));
26229566063dSJacob Faibussowitsch     PetscCall(ISDestroy(&ilink->is));
26239566063dSJacob Faibussowitsch     PetscCall(PetscFree(ilink));
26241d06f6b3SHong Zhang     ilink = next;
262587f4e208SHong Zhang   }
26266bf673ebSJoe Pusztay   ts->tsrhssplit     = NULL;
2627545aaa6fSHong Zhang   ts->num_rhs_splits = 0;
2628136cf249SJames Wright   if (ts->eval_times) {
2629136cf249SJames Wright     PetscCall(PetscFree(ts->eval_times->time_points));
2630136cf249SJames Wright     PetscCall(PetscFree(ts->eval_times->sol_times));
2631136cf249SJames Wright     PetscCall(VecDestroyVecs(ts->eval_times->num_time_points, &ts->eval_times->sol_vecs));
2632136cf249SJames Wright     PetscCall(PetscFree(ts->eval_times));
26334a658b32SHong Zhang   }
2634b3a72457SStefano Zampini   ts->rhsjacobian.time  = PETSC_MIN_REAL;
2635b3a72457SStefano Zampini   ts->rhsjacobian.scale = 1.0;
2636b3a72457SStefano Zampini   ts->ijacobian.shift   = 1.0;
2637277b19d0SLisandro Dalcin   ts->setupcalled       = PETSC_FALSE;
26383ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2639d763cef2SBarry Smith }
2640d763cef2SBarry Smith 
264114d0ab18SJacob Faibussowitsch static PetscErrorCode TSResizeReset(TS);
264214d0ab18SJacob Faibussowitsch 
26430764c050SBarry Smith /*@
2644d763cef2SBarry Smith   TSDestroy - Destroys the timestepper context that was created
2645bcf0153eSBarry Smith   with `TSCreate()`.
2646d763cef2SBarry Smith 
2647c3339decSBarry Smith   Collective
2648d763cef2SBarry Smith 
2649d763cef2SBarry Smith   Input Parameter:
2650bcf0153eSBarry Smith . ts - the `TS` context obtained from `TSCreate()`
2651d763cef2SBarry Smith 
2652d763cef2SBarry Smith   Level: beginner
2653d763cef2SBarry Smith 
26541cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSCreate()`, `TSSetUp()`, `TSSolve()`
2655d763cef2SBarry Smith @*/
2656d71ae5a4SJacob Faibussowitsch PetscErrorCode TSDestroy(TS *ts)
2657d71ae5a4SJacob Faibussowitsch {
2658d763cef2SBarry Smith   PetscFunctionBegin;
26593ba16761SJacob Faibussowitsch   if (!*ts) PetscFunctionReturn(PETSC_SUCCESS);
2660ecf68647SHong Zhang   PetscValidHeaderSpecific(*ts, TS_CLASSID, 1);
2661f4f49eeaSPierre Jolivet   if (--((PetscObject)*ts)->refct > 0) {
26629371c9d4SSatish Balay     *ts = NULL;
26633ba16761SJacob Faibussowitsch     PetscFunctionReturn(PETSC_SUCCESS);
26649371c9d4SSatish Balay   }
2665d763cef2SBarry Smith 
26669566063dSJacob Faibussowitsch   PetscCall(TSReset(*ts));
26679566063dSJacob Faibussowitsch   PetscCall(TSAdjointReset(*ts));
26681e66621cSBarry Smith   if ((*ts)->forward_solve) PetscCall(TSForwardReset(*ts));
26696bd3a4fdSStefano Zampini   PetscCall(TSResizeReset(*ts));
26701e66621cSBarry Smith 
2671e04113cfSBarry Smith   /* if memory was published with SAWs then destroy it */
26729566063dSJacob Faibussowitsch   PetscCall(PetscObjectSAWsViewOff((PetscObject)*ts));
2673f4f49eeaSPierre Jolivet   PetscTryTypeMethod(*ts, destroy);
26746d4c513bSLisandro Dalcin 
26759566063dSJacob Faibussowitsch   PetscCall(TSTrajectoryDestroy(&(*ts)->trajectory));
2676bc952696SBarry Smith 
26779566063dSJacob Faibussowitsch   PetscCall(TSAdaptDestroy(&(*ts)->adapt));
26789566063dSJacob Faibussowitsch   PetscCall(TSEventDestroy(&(*ts)->event));
26796427ac75SLisandro Dalcin 
26809566063dSJacob Faibussowitsch   PetscCall(SNESDestroy(&(*ts)->snes));
26814bd3aaa3SHong Zhang   PetscCall(SNESDestroy(&(*ts)->snesrhssplit));
26829566063dSJacob Faibussowitsch   PetscCall(DMDestroy(&(*ts)->dm));
2683f4f49eeaSPierre Jolivet   PetscCall(TSMonitorCancel(*ts));
2684f4f49eeaSPierre Jolivet   PetscCall(TSAdjointMonitorCancel(*ts));
26856d4c513bSLisandro Dalcin 
26869566063dSJacob Faibussowitsch   PetscCall(TSDestroy(&(*ts)->quadraturets));
26879566063dSJacob Faibussowitsch   PetscCall(PetscHeaderDestroy(ts));
26883ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2689d763cef2SBarry Smith }
2690d763cef2SBarry Smith 
2691d8e5e3e6SSatish Balay /*@
2692bcf0153eSBarry Smith   TSGetSNES - Returns the `SNES` (nonlinear solver) associated with
2693bcf0153eSBarry Smith   a `TS` (timestepper) context. Valid only for nonlinear problems.
2694d763cef2SBarry Smith 
2695bcf0153eSBarry Smith   Not Collective, but snes is parallel if ts is parallel
2696d763cef2SBarry Smith 
2697d763cef2SBarry Smith   Input Parameter:
2698bcf0153eSBarry Smith . ts - the `TS` context obtained from `TSCreate()`
2699d763cef2SBarry Smith 
2700d763cef2SBarry Smith   Output Parameter:
2701d763cef2SBarry Smith . snes - the nonlinear solver context
2702d763cef2SBarry Smith 
2703d763cef2SBarry Smith   Level: beginner
2704d763cef2SBarry Smith 
2705bcf0153eSBarry Smith   Notes:
2706bcf0153eSBarry Smith   The user can then directly manipulate the `SNES` context to set various
2707bcf0153eSBarry Smith   options, etc.  Likewise, the user can then extract and manipulate the
2708bcf0153eSBarry Smith   `KSP`, and `PC` contexts as well.
2709bcf0153eSBarry Smith 
2710bcf0153eSBarry Smith   `TSGetSNES()` does not work for integrators that do not use `SNES`; in
2711195e9b02SBarry Smith   this case `TSGetSNES()` returns `NULL` in `snes`.
2712bcf0153eSBarry Smith 
27131cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `SNES`, `TSCreate()`, `TSSetUp()`, `TSSolve()`
2714d763cef2SBarry Smith @*/
2715d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetSNES(TS ts, SNES *snes)
2716d71ae5a4SJacob Faibussowitsch {
2717d763cef2SBarry Smith   PetscFunctionBegin;
27180700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
27194f572ea9SToby Isaac   PetscAssertPointer(snes, 2);
2720d372ba47SLisandro Dalcin   if (!ts->snes) {
27219566063dSJacob Faibussowitsch     PetscCall(SNESCreate(PetscObjectComm((PetscObject)ts), &ts->snes));
27229566063dSJacob Faibussowitsch     PetscCall(PetscObjectSetOptions((PetscObject)ts->snes, ((PetscObject)ts)->options));
27239566063dSJacob Faibussowitsch     PetscCall(SNESSetFunction(ts->snes, NULL, SNESTSFormFunction, ts));
27249566063dSJacob Faibussowitsch     PetscCall(PetscObjectIncrementTabLevel((PetscObject)ts->snes, (PetscObject)ts, 1));
27254bd3aaa3SHong Zhang     if (ts->dm) PetscCall(SNESSetDM(ts->snes, ts->dm));
27261e66621cSBarry Smith     if (ts->problem_type == TS_LINEAR) PetscCall(SNESSetType(ts->snes, SNESKSPONLY));
2727d372ba47SLisandro Dalcin   }
2728d763cef2SBarry Smith   *snes = ts->snes;
27293ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2730d763cef2SBarry Smith }
2731d763cef2SBarry Smith 
2732deb2cd25SJed Brown /*@
27330b4b7b1cSBarry Smith   TSSetSNES - Set the `SNES` (nonlinear solver) to be used by the `TS` timestepping context
2734deb2cd25SJed Brown 
2735deb2cd25SJed Brown   Collective
2736deb2cd25SJed Brown 
2737d8d19677SJose E. Roman   Input Parameters:
2738bcf0153eSBarry Smith + ts   - the `TS` context obtained from `TSCreate()`
2739deb2cd25SJed Brown - snes - the nonlinear solver context
2740deb2cd25SJed Brown 
2741deb2cd25SJed Brown   Level: developer
2742deb2cd25SJed Brown 
2743bcf0153eSBarry Smith   Note:
2744bcf0153eSBarry Smith   Most users should have the `TS` created by calling `TSGetSNES()`
2745bcf0153eSBarry Smith 
27461cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `SNES`, `TSCreate()`, `TSSetUp()`, `TSSolve()`, `TSGetSNES()`
2747deb2cd25SJed Brown @*/
2748d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetSNES(TS ts, SNES snes)
2749d71ae5a4SJacob Faibussowitsch {
2750d1e9a80fSBarry Smith   PetscErrorCode (*func)(SNES, Vec, Mat, Mat, void *);
2751deb2cd25SJed Brown 
2752deb2cd25SJed Brown   PetscFunctionBegin;
2753deb2cd25SJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
2754deb2cd25SJed Brown   PetscValidHeaderSpecific(snes, SNES_CLASSID, 2);
27559566063dSJacob Faibussowitsch   PetscCall(PetscObjectReference((PetscObject)snes));
27569566063dSJacob Faibussowitsch   PetscCall(SNESDestroy(&ts->snes));
2757bbd56ea5SKarl Rupp 
2758deb2cd25SJed Brown   ts->snes = snes;
2759bbd56ea5SKarl Rupp 
27609566063dSJacob Faibussowitsch   PetscCall(SNESSetFunction(ts->snes, NULL, SNESTSFormFunction, ts));
27619566063dSJacob Faibussowitsch   PetscCall(SNESGetJacobian(ts->snes, NULL, NULL, &func, NULL));
27621e66621cSBarry Smith   if (func == SNESTSFormJacobian) PetscCall(SNESSetJacobian(ts->snes, NULL, NULL, SNESTSFormJacobian, ts));
27633ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2764deb2cd25SJed Brown }
2765deb2cd25SJed Brown 
2766d8e5e3e6SSatish Balay /*@
2767bcf0153eSBarry Smith   TSGetKSP - Returns the `KSP` (linear solver) associated with
2768bcf0153eSBarry Smith   a `TS` (timestepper) context.
2769d763cef2SBarry Smith 
2770195e9b02SBarry Smith   Not Collective, but `ksp` is parallel if `ts` is parallel
2771d763cef2SBarry Smith 
2772d763cef2SBarry Smith   Input Parameter:
2773bcf0153eSBarry Smith . ts - the `TS` context obtained from `TSCreate()`
2774d763cef2SBarry Smith 
2775d763cef2SBarry Smith   Output Parameter:
277694b7f48cSBarry Smith . ksp - the nonlinear solver context
2777d763cef2SBarry Smith 
2778d763cef2SBarry Smith   Level: beginner
2779d763cef2SBarry Smith 
2780bcf0153eSBarry Smith   Notes:
2781bcf0153eSBarry Smith   The user can then directly manipulate the `KSP` context to set various
2782bcf0153eSBarry Smith   options, etc.  Likewise, the user can then extract and manipulate the
2783bcf0153eSBarry Smith   `PC` context as well.
2784bcf0153eSBarry Smith 
2785bcf0153eSBarry Smith   `TSGetKSP()` does not work for integrators that do not use `KSP`;
2786195e9b02SBarry Smith   in this case `TSGetKSP()` returns `NULL` in `ksp`.
2787bcf0153eSBarry Smith 
27881cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `SNES`, `KSP`, `TSCreate()`, `TSSetUp()`, `TSSolve()`, `TSGetSNES()`
2789d763cef2SBarry Smith @*/
2790d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetKSP(TS ts, KSP *ksp)
2791d71ae5a4SJacob Faibussowitsch {
2792089b2837SJed Brown   SNES snes;
2793d372ba47SLisandro Dalcin 
2794d763cef2SBarry Smith   PetscFunctionBegin;
27950700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
27964f572ea9SToby Isaac   PetscAssertPointer(ksp, 2);
27973c633725SBarry Smith   PetscCheck(((PetscObject)ts)->type_name, PETSC_COMM_SELF, PETSC_ERR_ARG_NULL, "KSP is not created yet. Call TSSetType() first");
27983c633725SBarry Smith   PetscCheck(ts->problem_type == TS_LINEAR, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Linear only; use TSGetSNES()");
27999566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts, &snes));
28009566063dSJacob Faibussowitsch   PetscCall(SNESGetKSP(snes, ksp));
28013ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2802d763cef2SBarry Smith }
2803d763cef2SBarry Smith 
2804d763cef2SBarry Smith /* ----------- Routines to set solver parameters ---------- */
2805d763cef2SBarry Smith 
2806adb62b0dSMatthew Knepley /*@
2807618ce8baSLisandro Dalcin   TSSetMaxSteps - Sets the maximum number of steps to use.
2808618ce8baSLisandro Dalcin 
2809c3339decSBarry Smith   Logically Collective
2810618ce8baSLisandro Dalcin 
2811618ce8baSLisandro Dalcin   Input Parameters:
2812bcf0153eSBarry Smith + ts       - the `TS` context obtained from `TSCreate()`
2813618ce8baSLisandro Dalcin - maxsteps - maximum number of steps to use
2814618ce8baSLisandro Dalcin 
2815bcf0153eSBarry Smith   Options Database Key:
2816618ce8baSLisandro Dalcin . -ts_max_steps <maxsteps> - Sets maxsteps
2817618ce8baSLisandro Dalcin 
2818618ce8baSLisandro Dalcin   Level: intermediate
2819618ce8baSLisandro Dalcin 
2820bcf0153eSBarry Smith   Note:
282109cb0f53SBarry Smith   Use `PETSC_DETERMINE` to reset the maximum number of steps to the default from when the object's type was set
282209cb0f53SBarry Smith 
282309cb0f53SBarry Smith   The default maximum number of steps is 5,000
282409cb0f53SBarry Smith 
282509cb0f53SBarry Smith   Fortran Note:
282609cb0f53SBarry Smith   Use `PETSC_DETERMINE_INTEGER`
2827bcf0153eSBarry Smith 
28281cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSGetMaxSteps()`, `TSSetMaxTime()`, `TSSetExactFinalTime()`
2829618ce8baSLisandro Dalcin @*/
2830d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetMaxSteps(TS ts, PetscInt maxsteps)
2831d71ae5a4SJacob Faibussowitsch {
2832618ce8baSLisandro Dalcin   PetscFunctionBegin;
2833618ce8baSLisandro Dalcin   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
2834618ce8baSLisandro Dalcin   PetscValidLogicalCollectiveInt(ts, maxsteps, 2);
283509cb0f53SBarry Smith   if (maxsteps == PETSC_DETERMINE) {
283609cb0f53SBarry Smith     ts->max_steps = ts->default_max_steps;
283709cb0f53SBarry Smith   } else {
28383c633725SBarry Smith     PetscCheck(maxsteps >= 0, PetscObjectComm((PetscObject)ts), PETSC_ERR_ARG_OUTOFRANGE, "Maximum number of steps must be non-negative");
2839618ce8baSLisandro Dalcin     ts->max_steps = maxsteps;
284009cb0f53SBarry Smith   }
28413ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2842618ce8baSLisandro Dalcin }
2843618ce8baSLisandro Dalcin 
2844618ce8baSLisandro Dalcin /*@
2845618ce8baSLisandro Dalcin   TSGetMaxSteps - Gets the maximum number of steps to use.
2846618ce8baSLisandro Dalcin 
2847618ce8baSLisandro Dalcin   Not Collective
2848618ce8baSLisandro Dalcin 
28492fe279fdSBarry Smith   Input Parameter:
2850bcf0153eSBarry Smith . ts - the `TS` context obtained from `TSCreate()`
2851618ce8baSLisandro Dalcin 
2852618ce8baSLisandro Dalcin   Output Parameter:
2853618ce8baSLisandro Dalcin . maxsteps - maximum number of steps to use
2854618ce8baSLisandro Dalcin 
2855618ce8baSLisandro Dalcin   Level: advanced
2856618ce8baSLisandro Dalcin 
28571cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetMaxSteps()`, `TSGetMaxTime()`, `TSSetMaxTime()`
2858618ce8baSLisandro Dalcin @*/
2859d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetMaxSteps(TS ts, PetscInt *maxsteps)
2860d71ae5a4SJacob Faibussowitsch {
2861618ce8baSLisandro Dalcin   PetscFunctionBegin;
2862618ce8baSLisandro Dalcin   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
28634f572ea9SToby Isaac   PetscAssertPointer(maxsteps, 2);
2864618ce8baSLisandro Dalcin   *maxsteps = ts->max_steps;
28653ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2866618ce8baSLisandro Dalcin }
2867618ce8baSLisandro Dalcin 
2868618ce8baSLisandro Dalcin /*@
28698e562f8dSJames Wright   TSSetRunSteps - Sets the maximum number of steps to take in each call to `TSSolve()`.
28708e562f8dSJames Wright 
28718e562f8dSJames Wright   If the step count when `TSSolve()` is `start_step`, this will stop the simulation once `current_step - start_step >= run_steps`.
28728e562f8dSJames Wright   Comparatively, `TSSetMaxSteps()` will stop if `current_step >= max_steps`.
28738e562f8dSJames Wright   The simulation will stop when either condition is reached.
28748e562f8dSJames Wright 
28758e562f8dSJames Wright   Logically Collective
28768e562f8dSJames Wright 
28778e562f8dSJames Wright   Input Parameters:
28788e562f8dSJames Wright + ts       - the `TS` context obtained from `TSCreate()`
28798e562f8dSJames Wright - runsteps - maximum number of steps to take in each call to `TSSolve()`;
28808e562f8dSJames Wright 
28818e562f8dSJames Wright   Options Database Key:
28828e562f8dSJames Wright . -ts_run_steps <runsteps> - Sets runsteps
28838e562f8dSJames Wright 
28848e562f8dSJames Wright   Level: intermediate
28858e562f8dSJames Wright 
28868e562f8dSJames Wright   Note:
28878e562f8dSJames Wright   The default is `PETSC_UNLIMITED`
28888e562f8dSJames Wright 
28898e562f8dSJames Wright .seealso: [](ch_ts), `TS`, `TSGetRunSteps()`, `TSSetMaxTime()`, `TSSetExactFinalTime()`, `TSSetMaxSteps()`
28908e562f8dSJames Wright @*/
28918e562f8dSJames Wright PetscErrorCode TSSetRunSteps(TS ts, PetscInt runsteps)
28928e562f8dSJames Wright {
28938e562f8dSJames Wright   PetscFunctionBegin;
28948e562f8dSJames Wright   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
28958e562f8dSJames Wright   PetscValidLogicalCollectiveInt(ts, runsteps, 2);
28968e562f8dSJames Wright   if (runsteps == PETSC_DETERMINE) {
28978e562f8dSJames Wright     ts->run_steps = PETSC_UNLIMITED;
28988e562f8dSJames Wright   } else {
28998e562f8dSJames 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");
29008e562f8dSJames Wright     ts->run_steps = runsteps;
29018e562f8dSJames Wright   }
29028e562f8dSJames Wright   PetscFunctionReturn(PETSC_SUCCESS);
29038e562f8dSJames Wright }
29048e562f8dSJames Wright 
29058e562f8dSJames Wright /*@
29068e562f8dSJames Wright   TSGetRunSteps - Gets the maximum number of steps to take in each call to `TSSolve()`.
29078e562f8dSJames Wright 
29088e562f8dSJames Wright   Not Collective
29098e562f8dSJames Wright 
29108e562f8dSJames Wright   Input Parameter:
29118e562f8dSJames Wright . ts - the `TS` context obtained from `TSCreate()`
29128e562f8dSJames Wright 
29138e562f8dSJames Wright   Output Parameter:
29148e562f8dSJames Wright . runsteps - maximum number of steps to take in each call to `TSSolve`.
29158e562f8dSJames Wright 
29168e562f8dSJames Wright   Level: advanced
29178e562f8dSJames Wright 
29188e562f8dSJames Wright .seealso: [](ch_ts), `TS`, `TSSetRunSteps()`, `TSGetMaxTime()`, `TSSetMaxTime()`, `TSGetMaxSteps()`
29198e562f8dSJames Wright @*/
29208e562f8dSJames Wright PetscErrorCode TSGetRunSteps(TS ts, PetscInt *runsteps)
29218e562f8dSJames Wright {
29228e562f8dSJames Wright   PetscFunctionBegin;
29238e562f8dSJames Wright   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
29248e562f8dSJames Wright   PetscAssertPointer(runsteps, 2);
29258e562f8dSJames Wright   *runsteps = ts->run_steps;
29268e562f8dSJames Wright   PetscFunctionReturn(PETSC_SUCCESS);
29278e562f8dSJames Wright }
29288e562f8dSJames Wright 
29298e562f8dSJames Wright /*@
2930618ce8baSLisandro Dalcin   TSSetMaxTime - Sets the maximum (or final) time for timestepping.
2931618ce8baSLisandro Dalcin 
2932c3339decSBarry Smith   Logically Collective
2933618ce8baSLisandro Dalcin 
2934618ce8baSLisandro Dalcin   Input Parameters:
2935bcf0153eSBarry Smith + ts      - the `TS` context obtained from `TSCreate()`
2936618ce8baSLisandro Dalcin - maxtime - final time to step to
2937618ce8baSLisandro Dalcin 
2938bcf0153eSBarry Smith   Options Database Key:
2939ef85077eSLisandro Dalcin . -ts_max_time <maxtime> - Sets maxtime
2940618ce8baSLisandro Dalcin 
2941bcf0153eSBarry Smith   Level: intermediate
2942bcf0153eSBarry Smith 
2943618ce8baSLisandro Dalcin   Notes:
294409cb0f53SBarry Smith   Use `PETSC_DETERMINE` to reset the maximum time to the default from when the object's type was set
294509cb0f53SBarry Smith 
2946618ce8baSLisandro Dalcin   The default maximum time is 5.0
2947618ce8baSLisandro Dalcin 
294809cb0f53SBarry Smith   Fortran Note:
294909cb0f53SBarry Smith   Use `PETSC_DETERMINE_REAL`
295009cb0f53SBarry Smith 
29511cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSGetMaxTime()`, `TSSetMaxSteps()`, `TSSetExactFinalTime()`
2952618ce8baSLisandro Dalcin @*/
2953d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetMaxTime(TS ts, PetscReal maxtime)
2954d71ae5a4SJacob Faibussowitsch {
2955618ce8baSLisandro Dalcin   PetscFunctionBegin;
2956618ce8baSLisandro Dalcin   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
2957618ce8baSLisandro Dalcin   PetscValidLogicalCollectiveReal(ts, maxtime, 2);
295809cb0f53SBarry Smith   if (maxtime == PETSC_DETERMINE) {
295909cb0f53SBarry Smith     ts->max_time = ts->default_max_time;
296009cb0f53SBarry Smith   } else {
2961618ce8baSLisandro Dalcin     ts->max_time = maxtime;
296209cb0f53SBarry Smith   }
29633ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2964618ce8baSLisandro Dalcin }
2965618ce8baSLisandro Dalcin 
2966618ce8baSLisandro Dalcin /*@
2967618ce8baSLisandro Dalcin   TSGetMaxTime - Gets the maximum (or final) time for timestepping.
2968618ce8baSLisandro Dalcin 
2969618ce8baSLisandro Dalcin   Not Collective
2970618ce8baSLisandro Dalcin 
29712fe279fdSBarry Smith   Input Parameter:
2972bcf0153eSBarry Smith . ts - the `TS` context obtained from `TSCreate()`
2973618ce8baSLisandro Dalcin 
2974618ce8baSLisandro Dalcin   Output Parameter:
2975618ce8baSLisandro Dalcin . maxtime - final time to step to
2976618ce8baSLisandro Dalcin 
2977618ce8baSLisandro Dalcin   Level: advanced
2978618ce8baSLisandro Dalcin 
29791cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetMaxTime()`, `TSGetMaxSteps()`, `TSSetMaxSteps()`
2980618ce8baSLisandro Dalcin @*/
2981d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetMaxTime(TS ts, PetscReal *maxtime)
2982d71ae5a4SJacob Faibussowitsch {
2983618ce8baSLisandro Dalcin   PetscFunctionBegin;
2984618ce8baSLisandro Dalcin   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
29854f572ea9SToby Isaac   PetscAssertPointer(maxtime, 2);
2986618ce8baSLisandro Dalcin   *maxtime = ts->max_time;
29873ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2988618ce8baSLisandro Dalcin }
2989618ce8baSLisandro Dalcin 
299014d0ab18SJacob Faibussowitsch // PetscClangLinter pragma disable: -fdoc-*
2991618ce8baSLisandro Dalcin /*@
2992bcf0153eSBarry Smith   TSSetInitialTimeStep - Deprecated, use `TSSetTime()` and `TSSetTimeStep()`.
2993edc382c3SSatish Balay 
2994edc382c3SSatish Balay   Level: deprecated
2995edc382c3SSatish Balay 
2996aaa6c58dSLisandro Dalcin @*/
2997d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetInitialTimeStep(TS ts, PetscReal initial_time, PetscReal time_step)
2998d71ae5a4SJacob Faibussowitsch {
2999aaa6c58dSLisandro Dalcin   PetscFunctionBegin;
3000aaa6c58dSLisandro Dalcin   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
30019566063dSJacob Faibussowitsch   PetscCall(TSSetTime(ts, initial_time));
30029566063dSJacob Faibussowitsch   PetscCall(TSSetTimeStep(ts, time_step));
30033ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
3004aaa6c58dSLisandro Dalcin }
3005aaa6c58dSLisandro Dalcin 
300614d0ab18SJacob Faibussowitsch // PetscClangLinter pragma disable: -fdoc-*
3007aaa6c58dSLisandro Dalcin /*@
3008bcf0153eSBarry Smith   TSGetDuration - Deprecated, use `TSGetMaxSteps()` and `TSGetMaxTime()`.
3009edc382c3SSatish Balay 
3010edc382c3SSatish Balay   Level: deprecated
3011edc382c3SSatish Balay 
3012adb62b0dSMatthew Knepley @*/
3013d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetDuration(TS ts, PetscInt *maxsteps, PetscReal *maxtime)
3014d71ae5a4SJacob Faibussowitsch {
3015adb62b0dSMatthew Knepley   PetscFunctionBegin;
30160700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3017abc0a331SBarry Smith   if (maxsteps) {
30184f572ea9SToby Isaac     PetscAssertPointer(maxsteps, 2);
3019adb62b0dSMatthew Knepley     *maxsteps = ts->max_steps;
3020adb62b0dSMatthew Knepley   }
3021abc0a331SBarry Smith   if (maxtime) {
30224f572ea9SToby Isaac     PetscAssertPointer(maxtime, 3);
3023adb62b0dSMatthew Knepley     *maxtime = ts->max_time;
3024adb62b0dSMatthew Knepley   }
30253ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
3026adb62b0dSMatthew Knepley }
3027adb62b0dSMatthew Knepley 
302814d0ab18SJacob Faibussowitsch // PetscClangLinter pragma disable: -fdoc-*
3029d763cef2SBarry Smith /*@
3030bcf0153eSBarry Smith   TSSetDuration - Deprecated, use `TSSetMaxSteps()` and `TSSetMaxTime()`.
3031edc382c3SSatish Balay 
3032edc382c3SSatish Balay   Level: deprecated
3033edc382c3SSatish Balay 
3034d763cef2SBarry Smith @*/
3035d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetDuration(TS ts, PetscInt maxsteps, PetscReal maxtime)
3036d71ae5a4SJacob Faibussowitsch {
3037d763cef2SBarry Smith   PetscFunctionBegin;
3038835f2295SStefano Zampini   if (maxsteps != PETSC_CURRENT) PetscCall(TSSetMaxSteps(ts, maxsteps));
303909cb0f53SBarry Smith   if (maxtime != (PetscReal)PETSC_CURRENT) PetscCall(TSSetMaxTime(ts, maxtime));
30403ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
3041d763cef2SBarry Smith }
3042d763cef2SBarry Smith 
304314d0ab18SJacob Faibussowitsch // PetscClangLinter pragma disable: -fdoc-*
3044d763cef2SBarry Smith /*@
3045bcf0153eSBarry Smith   TSGetTimeStepNumber - Deprecated, use `TSGetStepNumber()`.
3046edc382c3SSatish Balay 
3047edc382c3SSatish Balay   Level: deprecated
3048edc382c3SSatish Balay 
30495c5f5948SLisandro Dalcin @*/
3050d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetTimeStepNumber(TS ts, PetscInt *steps)
3051d71ae5a4SJacob Faibussowitsch {
30529371c9d4SSatish Balay   return TSGetStepNumber(ts, steps);
30539371c9d4SSatish Balay }
30545c5f5948SLisandro Dalcin 
305514d0ab18SJacob Faibussowitsch // PetscClangLinter pragma disable: -fdoc-*
305619eac22cSLisandro Dalcin /*@
3057bcf0153eSBarry Smith   TSGetTotalSteps - Deprecated, use `TSGetStepNumber()`.
3058edc382c3SSatish Balay 
3059edc382c3SSatish Balay   Level: deprecated
3060edc382c3SSatish Balay 
30614f4e0956SLisandro Dalcin @*/
3062d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetTotalSteps(TS ts, PetscInt *steps)
3063d71ae5a4SJacob Faibussowitsch {
30649371c9d4SSatish Balay   return TSGetStepNumber(ts, steps);
30659371c9d4SSatish Balay }
30664f4e0956SLisandro Dalcin 
30674f4e0956SLisandro Dalcin /*@
3068d763cef2SBarry Smith   TSSetSolution - Sets the initial solution vector
3069bcf0153eSBarry Smith   for use by the `TS` routines.
3070d763cef2SBarry Smith 
3071c3339decSBarry Smith   Logically Collective
3072d763cef2SBarry Smith 
3073d763cef2SBarry Smith   Input Parameters:
3074bcf0153eSBarry Smith + ts - the `TS` context obtained from `TSCreate()`
30750910c330SBarry Smith - u  - the solution vector
3076d763cef2SBarry Smith 
3077d763cef2SBarry Smith   Level: beginner
3078d763cef2SBarry Smith 
30791cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetSolutionFunction()`, `TSGetSolution()`, `TSCreate()`
3080d763cef2SBarry Smith @*/
3081d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetSolution(TS ts, Vec u)
3082d71ae5a4SJacob Faibussowitsch {
3083496e6a7aSJed Brown   DM dm;
30848737fe31SLisandro Dalcin 
3085d763cef2SBarry Smith   PetscFunctionBegin;
30860700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
30870910c330SBarry Smith   PetscValidHeaderSpecific(u, VEC_CLASSID, 2);
30889566063dSJacob Faibussowitsch   PetscCall(PetscObjectReference((PetscObject)u));
30899566063dSJacob Faibussowitsch   PetscCall(VecDestroy(&ts->vec_sol));
30900910c330SBarry Smith   ts->vec_sol = u;
3091bbd56ea5SKarl Rupp 
30929566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
30939566063dSJacob Faibussowitsch   PetscCall(DMShellSetGlobalVector(dm, u));
30943ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
3095d763cef2SBarry Smith }
3096d763cef2SBarry Smith 
3097ac226902SBarry Smith /*@C
3098000e7ae3SMatthew Knepley   TSSetPreStep - Sets the general-purpose function
30993f2090d5SJed Brown   called once at the beginning of each time step.
3100000e7ae3SMatthew Knepley 
3101c3339decSBarry Smith   Logically Collective
3102000e7ae3SMatthew Knepley 
3103000e7ae3SMatthew Knepley   Input Parameters:
3104bcf0153eSBarry Smith + ts   - The `TS` context obtained from `TSCreate()`
3105000e7ae3SMatthew Knepley - func - The function
3106000e7ae3SMatthew Knepley 
310720f4b53cSBarry Smith   Calling sequence of `func`:
310814d0ab18SJacob Faibussowitsch . ts - the `TS` context
3109000e7ae3SMatthew Knepley 
3110000e7ae3SMatthew Knepley   Level: intermediate
3111000e7ae3SMatthew Knepley 
31121cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetPreStage()`, `TSSetPostStage()`, `TSSetPostStep()`, `TSStep()`, `TSRestartStep()`
3113000e7ae3SMatthew Knepley @*/
311414d0ab18SJacob Faibussowitsch PetscErrorCode TSSetPreStep(TS ts, PetscErrorCode (*func)(TS ts))
3115d71ae5a4SJacob Faibussowitsch {
3116000e7ae3SMatthew Knepley   PetscFunctionBegin;
31170700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3118ae60f76fSBarry Smith   ts->prestep = func;
31193ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
3120000e7ae3SMatthew Knepley }
3121000e7ae3SMatthew Knepley 
312209ee8438SJed Brown /*@
3123bcf0153eSBarry Smith   TSPreStep - Runs the user-defined pre-step function provided with `TSSetPreStep()`
31243f2090d5SJed Brown 
3125c3339decSBarry Smith   Collective
31263f2090d5SJed Brown 
31272fe279fdSBarry Smith   Input Parameter:
3128bcf0153eSBarry Smith . ts - The `TS` context obtained from `TSCreate()`
31293f2090d5SJed Brown 
31303f2090d5SJed Brown   Level: developer
31313f2090d5SJed Brown 
3132bcf0153eSBarry Smith   Note:
3133bcf0153eSBarry Smith   `TSPreStep()` is typically used within time stepping implementations,
3134bcf0153eSBarry Smith   so most users would not generally call this routine themselves.
3135bcf0153eSBarry Smith 
31361cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetPreStep()`, `TSPreStage()`, `TSPostStage()`, `TSPostStep()`
31373f2090d5SJed Brown @*/
3138d71ae5a4SJacob Faibussowitsch PetscErrorCode TSPreStep(TS ts)
3139d71ae5a4SJacob Faibussowitsch {
31403f2090d5SJed Brown   PetscFunctionBegin;
31410700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3142ae60f76fSBarry Smith   if (ts->prestep) {
31435efd42a4SStefano Zampini     Vec              U;
3144ef8d1ce0SJohann Rudi     PetscObjectId    idprev;
3145ef8d1ce0SJohann Rudi     PetscBool        sameObject;
31465efd42a4SStefano Zampini     PetscObjectState sprev, spost;
31475efd42a4SStefano Zampini 
31489566063dSJacob Faibussowitsch     PetscCall(TSGetSolution(ts, &U));
31499566063dSJacob Faibussowitsch     PetscCall(PetscObjectGetId((PetscObject)U, &idprev));
31509566063dSJacob Faibussowitsch     PetscCall(PetscObjectStateGet((PetscObject)U, &sprev));
315125e27a38SBarry Smith     PetscCallBack("TS callback preset", (*ts->prestep)(ts));
31529566063dSJacob Faibussowitsch     PetscCall(TSGetSolution(ts, &U));
31539566063dSJacob Faibussowitsch     PetscCall(PetscObjectCompareId((PetscObject)U, idprev, &sameObject));
31549566063dSJacob Faibussowitsch     PetscCall(PetscObjectStateGet((PetscObject)U, &spost));
31559566063dSJacob Faibussowitsch     if (!sameObject || sprev != spost) PetscCall(TSRestartStep(ts));
3156312ce896SJed Brown   }
31573ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
31583f2090d5SJed Brown }
31593f2090d5SJed Brown 
3160b8123daeSJed Brown /*@C
3161b8123daeSJed Brown   TSSetPreStage - Sets the general-purpose function
3162b8123daeSJed Brown   called once at the beginning of each stage.
3163b8123daeSJed Brown 
3164c3339decSBarry Smith   Logically Collective
3165b8123daeSJed Brown 
3166b8123daeSJed Brown   Input Parameters:
3167bcf0153eSBarry Smith + ts   - The `TS` context obtained from `TSCreate()`
3168b8123daeSJed Brown - func - The function
3169b8123daeSJed Brown 
317020f4b53cSBarry Smith   Calling sequence of `func`:
317114d0ab18SJacob Faibussowitsch + ts        - the `TS` context
317214d0ab18SJacob Faibussowitsch - stagetime - the stage time
3173b8123daeSJed Brown 
3174b8123daeSJed Brown   Level: intermediate
3175b8123daeSJed Brown 
3176b8123daeSJed Brown   Note:
3177b8123daeSJed Brown   There may be several stages per time step. If the solve for a given stage fails, the step may be rejected and retried.
3178bcf0153eSBarry Smith   The time step number being computed can be queried using `TSGetStepNumber()` and the total size of the step being
3179bcf0153eSBarry Smith   attempted can be obtained using `TSGetTimeStep()`. The time at the start of the step is available via `TSGetTime()`.
3180b8123daeSJed Brown 
31811cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetPostStage()`, `TSSetPreStep()`, `TSSetPostStep()`, `TSGetApplicationContext()`
3182b8123daeSJed Brown @*/
318314d0ab18SJacob Faibussowitsch PetscErrorCode TSSetPreStage(TS ts, PetscErrorCode (*func)(TS ts, PetscReal stagetime))
3184d71ae5a4SJacob Faibussowitsch {
3185b8123daeSJed Brown   PetscFunctionBegin;
3186b8123daeSJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3187ae60f76fSBarry Smith   ts->prestage = func;
31883ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
3189b8123daeSJed Brown }
3190b8123daeSJed Brown 
31919be3e283SDebojyoti Ghosh /*@C
31920d56bcf9SIlya Fursov   TSSetPostStage - Sets the general-purpose function
31939be3e283SDebojyoti Ghosh   called once at the end of each stage.
31949be3e283SDebojyoti Ghosh 
3195c3339decSBarry Smith   Logically Collective
31969be3e283SDebojyoti Ghosh 
31979be3e283SDebojyoti Ghosh   Input Parameters:
3198bcf0153eSBarry Smith + ts   - The `TS` context obtained from `TSCreate()`
31999be3e283SDebojyoti Ghosh - func - The function
32009be3e283SDebojyoti Ghosh 
320120f4b53cSBarry Smith   Calling sequence of `func`:
320214d0ab18SJacob Faibussowitsch + ts         - the `TS` context
320314d0ab18SJacob Faibussowitsch . stagetime  - the stage time
320414d0ab18SJacob Faibussowitsch . stageindex - the stage index
320514d0ab18SJacob Faibussowitsch - Y          - Array of vectors (of size = total number of stages) with the stage solutions
32069be3e283SDebojyoti Ghosh 
32079be3e283SDebojyoti Ghosh   Level: intermediate
32089be3e283SDebojyoti Ghosh 
32099be3e283SDebojyoti Ghosh   Note:
32109be3e283SDebojyoti Ghosh   There may be several stages per time step. If the solve for a given stage fails, the step may be rejected and retried.
3211bcf0153eSBarry Smith   The time step number being computed can be queried using `TSGetStepNumber()` and the total size of the step being
3212bcf0153eSBarry Smith   attempted can be obtained using `TSGetTimeStep()`. The time at the start of the step is available via `TSGetTime()`.
32139be3e283SDebojyoti Ghosh 
32141cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetPreStage()`, `TSSetPreStep()`, `TSSetPostStep()`, `TSGetApplicationContext()`
32159be3e283SDebojyoti Ghosh @*/
321614d0ab18SJacob Faibussowitsch PetscErrorCode TSSetPostStage(TS ts, PetscErrorCode (*func)(TS ts, PetscReal stagetime, PetscInt stageindex, Vec *Y))
3217d71ae5a4SJacob Faibussowitsch {
32189be3e283SDebojyoti Ghosh   PetscFunctionBegin;
32199be3e283SDebojyoti Ghosh   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
32209be3e283SDebojyoti Ghosh   ts->poststage = func;
32213ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
32229be3e283SDebojyoti Ghosh }
32239be3e283SDebojyoti Ghosh 
3224c688d042SShri Abhyankar /*@C
3225c688d042SShri Abhyankar   TSSetPostEvaluate - Sets the general-purpose function
32260d56bcf9SIlya Fursov   called at the end of each step evaluation.
3227c688d042SShri Abhyankar 
3228c3339decSBarry Smith   Logically Collective
3229c688d042SShri Abhyankar 
3230c688d042SShri Abhyankar   Input Parameters:
3231bcf0153eSBarry Smith + ts   - The `TS` context obtained from `TSCreate()`
3232c688d042SShri Abhyankar - func - The function
3233c688d042SShri Abhyankar 
323420f4b53cSBarry Smith   Calling sequence of `func`:
323514d0ab18SJacob Faibussowitsch . ts - the `TS` context
3236c688d042SShri Abhyankar 
3237c688d042SShri Abhyankar   Level: intermediate
3238c688d042SShri Abhyankar 
3239c688d042SShri Abhyankar   Note:
32400d56bcf9SIlya Fursov   The function set by `TSSetPostEvaluate()` is called after the solution is evaluated, or after the step rollback.
32410d56bcf9SIlya Fursov   Inside the `func` callback, the solution vector can be obtained with `TSGetSolution()`, and modified, if need be.
32420d56bcf9SIlya Fursov   The time step can be obtained with `TSGetTimeStep()`, and the time at the start of the step - via `TSGetTime()`.
32430d56bcf9SIlya Fursov   The potential changes to the solution vector introduced by event handling (`postevent()`) are not relevant for `TSSetPostEvaluate()`,
32440d56bcf9SIlya Fursov   but are relevant for `TSSetPostStep()`, according to the function call scheme in `TSSolve()`, as shown below
32450d56bcf9SIlya Fursov .vb
32460d56bcf9SIlya Fursov   ...
32470d56bcf9SIlya Fursov   Step()
32480d56bcf9SIlya Fursov   PostEvaluate()
32490d56bcf9SIlya Fursov   EventHandling()
32500d56bcf9SIlya Fursov   step_rollback ? PostEvaluate() : PostStep()
32510d56bcf9SIlya Fursov   ...
32520d56bcf9SIlya Fursov .ve
32530d56bcf9SIlya Fursov   where EventHandling() may result in one of the following three outcomes
32540d56bcf9SIlya Fursov .vb
32550d56bcf9SIlya Fursov   (1) | successful step | solution intact
32560d56bcf9SIlya Fursov   (2) | successful step | solution modified by `postevent()`
32570d56bcf9SIlya Fursov   (3) | step_rollback   | solution rolled back
32580d56bcf9SIlya Fursov .ve
3259c688d042SShri Abhyankar 
32601cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetPreStage()`, `TSSetPreStep()`, `TSSetPostStep()`, `TSGetApplicationContext()`
3261c688d042SShri Abhyankar @*/
326214d0ab18SJacob Faibussowitsch PetscErrorCode TSSetPostEvaluate(TS ts, PetscErrorCode (*func)(TS ts))
3263d71ae5a4SJacob Faibussowitsch {
3264c688d042SShri Abhyankar   PetscFunctionBegin;
3265c688d042SShri Abhyankar   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3266c688d042SShri Abhyankar   ts->postevaluate = func;
32673ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
3268c688d042SShri Abhyankar }
3269c688d042SShri Abhyankar 
3270b8123daeSJed Brown /*@
3271bcf0153eSBarry Smith   TSPreStage - Runs the user-defined pre-stage function set using `TSSetPreStage()`
3272b8123daeSJed Brown 
3273c3339decSBarry Smith   Collective
3274b8123daeSJed Brown 
3275b8123daeSJed Brown   Input Parameters:
327614d0ab18SJacob Faibussowitsch + ts        - The `TS` context obtained from `TSCreate()`
327714d0ab18SJacob Faibussowitsch - stagetime - The absolute time of the current stage
3278b8123daeSJed Brown 
3279b8123daeSJed Brown   Level: developer
3280b8123daeSJed Brown 
3281bcf0153eSBarry Smith   Note:
3282bcf0153eSBarry Smith   `TSPreStage()` is typically used within time stepping implementations,
3283bcf0153eSBarry Smith   most users would not generally call this routine themselves.
3284bcf0153eSBarry Smith 
32851cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSPostStage()`, `TSSetPreStep()`, `TSPreStep()`, `TSPostStep()`
3286b8123daeSJed Brown @*/
3287d71ae5a4SJacob Faibussowitsch PetscErrorCode TSPreStage(TS ts, PetscReal stagetime)
3288d71ae5a4SJacob Faibussowitsch {
3289b8123daeSJed Brown   PetscFunctionBegin;
3290b8123daeSJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
32911e66621cSBarry Smith   if (ts->prestage) PetscCallBack("TS callback prestage", (*ts->prestage)(ts, stagetime));
32923ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
3293b8123daeSJed Brown }
3294b8123daeSJed Brown 
32959be3e283SDebojyoti Ghosh /*@
3296bcf0153eSBarry Smith   TSPostStage - Runs the user-defined post-stage function set using `TSSetPostStage()`
32979be3e283SDebojyoti Ghosh 
3298c3339decSBarry Smith   Collective
32999be3e283SDebojyoti Ghosh 
33009be3e283SDebojyoti Ghosh   Input Parameters:
330114d0ab18SJacob Faibussowitsch + ts         - The `TS` context obtained from `TSCreate()`
330214d0ab18SJacob Faibussowitsch . stagetime  - The absolute time of the current stage
330314d0ab18SJacob Faibussowitsch . stageindex - Stage number
330414d0ab18SJacob Faibussowitsch - Y          - Array of vectors (of size = total number of stages) with the stage solutions
33059be3e283SDebojyoti Ghosh 
33069be3e283SDebojyoti Ghosh   Level: developer
33079be3e283SDebojyoti Ghosh 
3308bcf0153eSBarry Smith   Note:
3309bcf0153eSBarry Smith   `TSPostStage()` is typically used within time stepping implementations,
3310bcf0153eSBarry Smith   most users would not generally call this routine themselves.
3311bcf0153eSBarry Smith 
33121cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSPreStage()`, `TSSetPreStep()`, `TSPreStep()`, `TSPostStep()`
33139be3e283SDebojyoti Ghosh @*/
3314d71ae5a4SJacob Faibussowitsch PetscErrorCode TSPostStage(TS ts, PetscReal stagetime, PetscInt stageindex, Vec *Y)
3315d71ae5a4SJacob Faibussowitsch {
33169be3e283SDebojyoti Ghosh   PetscFunctionBegin;
33179be3e283SDebojyoti Ghosh   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
33181e66621cSBarry Smith   if (ts->poststage) PetscCallBack("TS callback poststage", (*ts->poststage)(ts, stagetime, stageindex, Y));
33193ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
33209be3e283SDebojyoti Ghosh }
33219be3e283SDebojyoti Ghosh 
3322c688d042SShri Abhyankar /*@
3323bcf0153eSBarry Smith   TSPostEvaluate - Runs the user-defined post-evaluate function set using `TSSetPostEvaluate()`
3324c688d042SShri Abhyankar 
3325c3339decSBarry Smith   Collective
3326c688d042SShri Abhyankar 
33272fe279fdSBarry Smith   Input Parameter:
3328bcf0153eSBarry Smith . ts - The `TS` context obtained from `TSCreate()`
3329c688d042SShri Abhyankar 
3330c688d042SShri Abhyankar   Level: developer
3331c688d042SShri Abhyankar 
3332bcf0153eSBarry Smith   Note:
3333bcf0153eSBarry Smith   `TSPostEvaluate()` is typically used within time stepping implementations,
3334bcf0153eSBarry Smith   most users would not generally call this routine themselves.
3335bcf0153eSBarry Smith 
33361cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetPostEvaluate()`, `TSSetPreStep()`, `TSPreStep()`, `TSPostStep()`
3337c688d042SShri Abhyankar @*/
3338d71ae5a4SJacob Faibussowitsch PetscErrorCode TSPostEvaluate(TS ts)
3339d71ae5a4SJacob Faibussowitsch {
3340c688d042SShri Abhyankar   PetscFunctionBegin;
3341c688d042SShri Abhyankar   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3342c688d042SShri Abhyankar   if (ts->postevaluate) {
3343dcb233daSLisandro Dalcin     Vec              U;
3344dcb233daSLisandro Dalcin     PetscObjectState sprev, spost;
3345dcb233daSLisandro Dalcin 
33469566063dSJacob Faibussowitsch     PetscCall(TSGetSolution(ts, &U));
33479566063dSJacob Faibussowitsch     PetscCall(PetscObjectStateGet((PetscObject)U, &sprev));
334825e27a38SBarry Smith     PetscCallBack("TS callback postevaluate", (*ts->postevaluate)(ts));
33499566063dSJacob Faibussowitsch     PetscCall(PetscObjectStateGet((PetscObject)U, &spost));
33509566063dSJacob Faibussowitsch     if (sprev != spost) PetscCall(TSRestartStep(ts));
3351c688d042SShri Abhyankar   }
33523ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
3353c688d042SShri Abhyankar }
3354c688d042SShri Abhyankar 
3355ac226902SBarry Smith /*@C
3356000e7ae3SMatthew Knepley   TSSetPostStep - Sets the general-purpose function
33570d56bcf9SIlya Fursov   called once at the end of each successful time step.
3358000e7ae3SMatthew Knepley 
3359c3339decSBarry Smith   Logically Collective
3360000e7ae3SMatthew Knepley 
3361000e7ae3SMatthew Knepley   Input Parameters:
3362bcf0153eSBarry Smith + ts   - The `TS` context obtained from `TSCreate()`
3363000e7ae3SMatthew Knepley - func - The function
3364000e7ae3SMatthew Knepley 
336520f4b53cSBarry Smith   Calling sequence of `func`:
336614d0ab18SJacob Faibussowitsch . ts - the `TS` context
3367000e7ae3SMatthew Knepley 
3368000e7ae3SMatthew Knepley   Level: intermediate
3369000e7ae3SMatthew Knepley 
3370bcf0153eSBarry Smith   Note:
33710d56bcf9SIlya Fursov   The function set by `TSSetPostStep()` is called after each successful step. If the event handler locates an event at the
33720d56bcf9SIlya Fursov   given step, and `postevent()` modifies the solution vector, the solution vector obtained by `TSGetSolution()` inside `func` will
33730d56bcf9SIlya Fursov   contain the changes. To get the solution without these changes, use `TSSetPostEvaluate()` to set the appropriate callback.
33740d56bcf9SIlya Fursov   The scheme of the relevant function calls in `TSSolve()` is shown below
33750d56bcf9SIlya Fursov .vb
33760d56bcf9SIlya Fursov   ...
33770d56bcf9SIlya Fursov   Step()
33780d56bcf9SIlya Fursov   PostEvaluate()
33790d56bcf9SIlya Fursov   EventHandling()
33800d56bcf9SIlya Fursov   step_rollback ? PostEvaluate() : PostStep()
33810d56bcf9SIlya Fursov   ...
33820d56bcf9SIlya Fursov .ve
33830d56bcf9SIlya Fursov   where EventHandling() may result in one of the following three outcomes
33840d56bcf9SIlya Fursov .vb
33850d56bcf9SIlya Fursov   (1) | successful step | solution intact
33860d56bcf9SIlya Fursov   (2) | successful step | solution modified by `postevent()`
33870d56bcf9SIlya Fursov   (3) | step_rollback   | solution rolled back
33880d56bcf9SIlya Fursov .ve
3389bcf0153eSBarry Smith 
33901cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetPreStep()`, `TSSetPreStage()`, `TSSetPostEvaluate()`, `TSGetTimeStep()`, `TSGetStepNumber()`, `TSGetTime()`, `TSRestartStep()`
3391000e7ae3SMatthew Knepley @*/
339214d0ab18SJacob Faibussowitsch PetscErrorCode TSSetPostStep(TS ts, PetscErrorCode (*func)(TS ts))
3393d71ae5a4SJacob Faibussowitsch {
3394000e7ae3SMatthew Knepley   PetscFunctionBegin;
33950700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3396ae60f76fSBarry Smith   ts->poststep = func;
33973ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
3398000e7ae3SMatthew Knepley }
3399000e7ae3SMatthew Knepley 
340009ee8438SJed Brown /*@
3401195e9b02SBarry Smith   TSPostStep - Runs the user-defined post-step function that was set with `TSSetPostStep()`
34023f2090d5SJed Brown 
3403c3339decSBarry Smith   Collective
34043f2090d5SJed Brown 
34052fe279fdSBarry Smith   Input Parameter:
3406bcf0153eSBarry Smith . ts - The `TS` context obtained from `TSCreate()`
34073f2090d5SJed Brown 
3408bcf0153eSBarry Smith   Note:
3409bcf0153eSBarry Smith   `TSPostStep()` is typically used within time stepping implementations,
34103f2090d5SJed Brown   so most users would not generally call this routine themselves.
34113f2090d5SJed Brown 
34123f2090d5SJed Brown   Level: developer
34133f2090d5SJed Brown 
3414bfe80ac4SPierre Jolivet .seealso: [](ch_ts), `TS`, `TSSetPreStep()`, `TSSetPreStage()`, `TSSetPostEvaluate()`, `TSGetTimeStep()`, `TSGetStepNumber()`, `TSGetTime()`, `TSSetPostStep()`
34153f2090d5SJed Brown @*/
3416d71ae5a4SJacob Faibussowitsch PetscErrorCode TSPostStep(TS ts)
3417d71ae5a4SJacob Faibussowitsch {
34183f2090d5SJed Brown   PetscFunctionBegin;
34190700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3420ae60f76fSBarry Smith   if (ts->poststep) {
34215efd42a4SStefano Zampini     Vec              U;
3422ef8d1ce0SJohann Rudi     PetscObjectId    idprev;
3423ef8d1ce0SJohann Rudi     PetscBool        sameObject;
34245efd42a4SStefano Zampini     PetscObjectState sprev, spost;
34255efd42a4SStefano Zampini 
34269566063dSJacob Faibussowitsch     PetscCall(TSGetSolution(ts, &U));
34279566063dSJacob Faibussowitsch     PetscCall(PetscObjectGetId((PetscObject)U, &idprev));
34289566063dSJacob Faibussowitsch     PetscCall(PetscObjectStateGet((PetscObject)U, &sprev));
342925e27a38SBarry Smith     PetscCallBack("TS callback poststep", (*ts->poststep)(ts));
34309566063dSJacob Faibussowitsch     PetscCall(TSGetSolution(ts, &U));
34319566063dSJacob Faibussowitsch     PetscCall(PetscObjectCompareId((PetscObject)U, idprev, &sameObject));
34329566063dSJacob Faibussowitsch     PetscCall(PetscObjectStateGet((PetscObject)U, &spost));
34339566063dSJacob Faibussowitsch     if (!sameObject || sprev != spost) PetscCall(TSRestartStep(ts));
343472ac3e02SJed Brown   }
34353ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
34363f2090d5SJed Brown }
34373f2090d5SJed Brown 
3438cd652676SJed Brown /*@
3439cd652676SJed Brown   TSInterpolate - Interpolate the solution computed during the previous step to an arbitrary location in the interval
3440cd652676SJed Brown 
3441c3339decSBarry Smith   Collective
3442cd652676SJed Brown 
34434165533cSJose E. Roman   Input Parameters:
3444cd652676SJed Brown + ts - time stepping context
3445cd652676SJed Brown - t  - time to interpolate to
3446cd652676SJed Brown 
34474165533cSJose E. Roman   Output Parameter:
34480910c330SBarry Smith . U - state at given time
3449cd652676SJed Brown 
3450cd652676SJed Brown   Level: intermediate
3451cd652676SJed Brown 
3452b43aa488SJacob Faibussowitsch   Developer Notes:
3453bcf0153eSBarry Smith   `TSInterpolate()` and the storing of previous steps/stages should be generalized to support delay differential equations and continuous adjoints.
3454cd652676SJed Brown 
34551cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetExactFinalTime()`, `TSSolve()`
3456cd652676SJed Brown @*/
3457d71ae5a4SJacob Faibussowitsch PetscErrorCode TSInterpolate(TS ts, PetscReal t, Vec U)
3458d71ae5a4SJacob Faibussowitsch {
3459cd652676SJed Brown   PetscFunctionBegin;
3460cd652676SJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3461b06615a5SLisandro Dalcin   PetscValidHeaderSpecific(U, VEC_CLASSID, 3);
346263a3b9bcSJacob 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);
3463dbbe0bcdSBarry Smith   PetscUseTypeMethod(ts, interpolate, t, U);
34643ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
3465cd652676SJed Brown }
3466cd652676SJed Brown 
3467d763cef2SBarry Smith /*@
34686d9e5789SSean Farley   TSStep - Steps one time step
3469d763cef2SBarry Smith 
3470c3339decSBarry Smith   Collective
3471d763cef2SBarry Smith 
3472d763cef2SBarry Smith   Input Parameter:
3473bcf0153eSBarry Smith . ts - the `TS` context obtained from `TSCreate()`
3474d763cef2SBarry Smith 
347527829d71SBarry Smith   Level: developer
3476d763cef2SBarry Smith 
3477b8123daeSJed Brown   Notes:
3478bcf0153eSBarry Smith   The public interface for the ODE/DAE solvers is `TSSolve()`, you should almost for sure be using that routine and not this routine.
347927829d71SBarry Smith 
3480bcf0153eSBarry Smith   The hook set using `TSSetPreStep()` is called before each attempt to take the step. In general, the time step size may
3481b8123daeSJed Brown   be changed due to adaptive error controller or solve failures. Note that steps may contain multiple stages.
3482b8123daeSJed Brown 
3483bcf0153eSBarry Smith   This may over-step the final time provided in `TSSetMaxTime()` depending on the time-step used. `TSSolve()` interpolates to exactly the
3484bcf0153eSBarry Smith   time provided in `TSSetMaxTime()`. One can use `TSInterpolate()` to determine an interpolated solution within the final timestep.
348525cb2221SBarry Smith 
34861cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSCreate()`, `TSSetUp()`, `TSDestroy()`, `TSSolve()`, `TSSetPreStep()`, `TSSetPreStage()`, `TSSetPostStage()`, `TSInterpolate()`
3487d763cef2SBarry Smith @*/
3488d71ae5a4SJacob Faibussowitsch PetscErrorCode TSStep(TS ts)
3489d71ae5a4SJacob Faibussowitsch {
3490fffbeea8SBarry Smith   static PetscBool cite = PETSC_FALSE;
3491be5899b3SLisandro Dalcin   PetscReal        ptime;
3492d763cef2SBarry Smith 
3493d763cef2SBarry Smith   PetscFunctionBegin;
34940700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3495d0609cedSBarry Smith   PetscCall(PetscCitationsRegister("@article{tspaper,\n"
3496fffbeea8SBarry Smith                                    "  title         = {{PETSc/TS}: A Modern Scalable {DAE/ODE} Solver Library},\n"
3497f1d62c27SHong Zhang                                    "  author        = {Abhyankar, Shrirang and Brown, Jed and Constantinescu, Emil and Ghosh, Debojyoti and Smith, Barry F. and Zhang, Hong},\n"
3498f1d62c27SHong Zhang                                    "  journal       = {arXiv e-preprints},\n"
3499f1d62c27SHong Zhang                                    "  eprint        = {1806.01437},\n"
3500f1d62c27SHong Zhang                                    "  archivePrefix = {arXiv},\n"
35019371c9d4SSatish Balay                                    "  year          = {2018}\n}\n",
35029371c9d4SSatish Balay                                    &cite));
35039566063dSJacob Faibussowitsch   PetscCall(TSSetUp(ts));
35049566063dSJacob Faibussowitsch   PetscCall(TSTrajectorySetUp(ts->trajectory, ts));
3505136cf249SJames Wright   if (ts->eval_times)
3506136cf249SJames Wright     ts->eval_times->worktol = 0; /* In each step of TSSolve() 'eval_times->worktol' will be meaningfully defined (later) only once:
3507ca4445c7SIlya Fursov                                                    in TSAdaptChoose() or TSEvent_dt_cap(), and then reused till the end of the step */
3508d405a339SMatthew Knepley 
35098e562f8dSJames 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>");
35103c633725SBarry 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()");
35113c633725SBarry 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");
3512a6772fa2SLisandro Dalcin 
3513c61711c8SStefano Zampini   if (!ts->vec_sol0) PetscCall(VecDuplicate(ts->vec_sol, &ts->vec_sol0));
3514c61711c8SStefano Zampini   PetscCall(VecCopy(ts->vec_sol, ts->vec_sol0));
3515c61711c8SStefano Zampini   ts->time_step0 = ts->time_step;
3516c61711c8SStefano Zampini 
3517be5899b3SLisandro Dalcin   if (!ts->steps) ts->ptime_prev = ts->ptime;
35189371c9d4SSatish Balay   ptime = ts->ptime;
3519c61711c8SStefano Zampini 
35209371c9d4SSatish Balay   ts->ptime_prev_rollback = ts->ptime_prev;
35212808aa04SLisandro Dalcin   ts->reason              = TS_CONVERGED_ITERATING;
3522fc8dbba5SLisandro Dalcin 
35239566063dSJacob Faibussowitsch   PetscCall(PetscLogEventBegin(TS_Step, ts, 0, 0, 0));
3524dbbe0bcdSBarry Smith   PetscUseTypeMethod(ts, step);
35259566063dSJacob Faibussowitsch   PetscCall(PetscLogEventEnd(TS_Step, ts, 0, 0, 0));
3526fc8dbba5SLisandro Dalcin 
3527fc8dbba5SLisandro Dalcin   if (ts->reason >= 0) {
3528be5899b3SLisandro Dalcin     ts->ptime_prev = ptime;
35292808aa04SLisandro Dalcin     ts->steps++;
3530be5899b3SLisandro Dalcin     ts->steprollback = PETSC_FALSE;
353128d5b5d6SLisandro Dalcin     ts->steprestart  = PETSC_FALSE;
3532c6bf8827SStefano Zampini     ts->stepresize   = PETSC_FALSE;
3533d2daff3dSHong Zhang   }
3534fc8dbba5SLisandro Dalcin 
35355c9bbc89SJed Brown   if (ts->reason < 0 && ts->errorifstepfailed) {
35365c9bbc89SJed Brown     PetscCall(TSMonitorCancel(ts));
353709cb0f53SBarry 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]);
35385c9bbc89SJed Brown     SETERRQ(PetscObjectComm((PetscObject)ts), PETSC_ERR_NOT_CONVERGED, "TSStep has failed due to %s", TSConvergedReasons[ts->reason]);
35395c9bbc89SJed Brown   }
35403ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
354108c7845fSBarry Smith }
354208c7845fSBarry Smith 
354308c7845fSBarry Smith /*@
35447cbde773SLisandro Dalcin   TSEvaluateWLTE - Evaluate the weighted local truncation error norm
35457cbde773SLisandro Dalcin   at the end of a time step with a given order of accuracy.
35467cbde773SLisandro Dalcin 
3547c3339decSBarry Smith   Collective
35487cbde773SLisandro Dalcin 
35494165533cSJose E. Roman   Input Parameters:
35507cbde773SLisandro Dalcin + ts        - time stepping context
3551bcf0153eSBarry Smith - wnormtype - norm type, either `NORM_2` or `NORM_INFINITY`
35527cbde773SLisandro Dalcin 
355397bb3fdcSJose E. Roman   Input/Output Parameter:
3554bcf0153eSBarry Smith . order - optional, desired order for the error evaluation or `PETSC_DECIDE`;
355597bb3fdcSJose E. Roman            on output, the actual order of the error evaluation
355697bb3fdcSJose E. Roman 
355797bb3fdcSJose E. Roman   Output Parameter:
355897bb3fdcSJose E. Roman . wlte - the weighted local truncation error norm
35597cbde773SLisandro Dalcin 
35607cbde773SLisandro Dalcin   Level: advanced
35617cbde773SLisandro Dalcin 
3562bcf0153eSBarry Smith   Note:
35637cbde773SLisandro Dalcin   If the timestepper cannot evaluate the error in a particular step
35647cbde773SLisandro Dalcin   (eg. in the first step or restart steps after event handling),
35657cbde773SLisandro Dalcin   this routine returns wlte=-1.0 .
35667cbde773SLisandro Dalcin 
35671cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSStep()`, `TSAdapt`, `TSErrorWeightedNorm()`
35687cbde773SLisandro Dalcin @*/
3569d71ae5a4SJacob Faibussowitsch PetscErrorCode TSEvaluateWLTE(TS ts, NormType wnormtype, PetscInt *order, PetscReal *wlte)
3570d71ae5a4SJacob Faibussowitsch {
35717cbde773SLisandro Dalcin   PetscFunctionBegin;
35727cbde773SLisandro Dalcin   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
35737cbde773SLisandro Dalcin   PetscValidType(ts, 1);
3574064a246eSJacob Faibussowitsch   PetscValidLogicalCollectiveEnum(ts, wnormtype, 2);
35754f572ea9SToby Isaac   if (order) PetscAssertPointer(order, 3);
35767cbde773SLisandro Dalcin   if (order) PetscValidLogicalCollectiveInt(ts, *order, 3);
35774f572ea9SToby Isaac   PetscAssertPointer(wlte, 4);
35783c633725SBarry Smith   PetscCheck(wnormtype == NORM_2 || wnormtype == NORM_INFINITY, PetscObjectComm((PetscObject)ts), PETSC_ERR_SUP, "No support for norm type %s", NormTypes[wnormtype]);
3579dbbe0bcdSBarry Smith   PetscUseTypeMethod(ts, evaluatewlte, wnormtype, order, wlte);
35803ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
35817cbde773SLisandro Dalcin }
35827cbde773SLisandro Dalcin 
358305175c85SJed Brown /*@
358405175c85SJed Brown   TSEvaluateStep - Evaluate the solution at the end of a time step with a given order of accuracy.
358505175c85SJed Brown 
3586c3339decSBarry Smith   Collective
358705175c85SJed Brown 
35884165533cSJose E. Roman   Input Parameters:
35891c3436cfSJed Brown + ts    - time stepping context
35901c3436cfSJed Brown . order - desired order of accuracy
3591195e9b02SBarry Smith - done  - whether the step was evaluated at this order (pass `NULL` to generate an error if not available)
359205175c85SJed Brown 
35934165533cSJose E. Roman   Output Parameter:
35940910c330SBarry Smith . U - state at the end of the current step
359505175c85SJed Brown 
359605175c85SJed Brown   Level: advanced
359705175c85SJed Brown 
3598108c343cSJed Brown   Notes:
3599108c343cSJed Brown   This function cannot be called until all stages have been evaluated.
3600108c343cSJed Brown 
3601bcf0153eSBarry 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.
3602bcf0153eSBarry Smith 
36031cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSStep()`, `TSAdapt`
360405175c85SJed Brown @*/
3605d71ae5a4SJacob Faibussowitsch PetscErrorCode TSEvaluateStep(TS ts, PetscInt order, Vec U, PetscBool *done)
3606d71ae5a4SJacob Faibussowitsch {
360705175c85SJed Brown   PetscFunctionBegin;
360805175c85SJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
360905175c85SJed Brown   PetscValidType(ts, 1);
36100910c330SBarry Smith   PetscValidHeaderSpecific(U, VEC_CLASSID, 3);
3611dbbe0bcdSBarry Smith   PetscUseTypeMethod(ts, evaluatestep, order, U, done);
36123ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
361305175c85SJed Brown }
361405175c85SJed Brown 
3615aad739acSMatthew G. Knepley /*@C
36162e61be88SMatthew G. Knepley   TSGetComputeInitialCondition - Get the function used to automatically compute an initial condition for the timestepping.
3617aad739acSMatthew G. Knepley 
3618aad739acSMatthew G. Knepley   Not collective
3619aad739acSMatthew G. Knepley 
36204165533cSJose E. Roman   Input Parameter:
3621aad739acSMatthew G. Knepley . ts - time stepping context
3622aad739acSMatthew G. Knepley 
36234165533cSJose E. Roman   Output Parameter:
3624b43aa488SJacob Faibussowitsch . initCondition - The function which computes an initial condition
3625aad739acSMatthew G. Knepley 
362620f4b53cSBarry Smith   Calling sequence of `initCondition`:
362720f4b53cSBarry Smith + ts - The timestepping context
362820f4b53cSBarry Smith - u  - The input vector in which the initial condition is stored
3629bcf0153eSBarry Smith 
3630aad739acSMatthew G. Knepley   Level: advanced
3631aad739acSMatthew G. Knepley 
36321cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetComputeInitialCondition()`, `TSComputeInitialCondition()`
3633aad739acSMatthew G. Knepley @*/
363414d0ab18SJacob Faibussowitsch PetscErrorCode TSGetComputeInitialCondition(TS ts, PetscErrorCode (**initCondition)(TS ts, Vec u))
3635d71ae5a4SJacob Faibussowitsch {
3636aad739acSMatthew G. Knepley   PetscFunctionBegin;
3637aad739acSMatthew G. Knepley   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
36384f572ea9SToby Isaac   PetscAssertPointer(initCondition, 2);
36392e61be88SMatthew G. Knepley   *initCondition = ts->ops->initcondition;
36403ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
3641aad739acSMatthew G. Knepley }
3642aad739acSMatthew G. Knepley 
3643aad739acSMatthew G. Knepley /*@C
36442e61be88SMatthew G. Knepley   TSSetComputeInitialCondition - Set the function used to automatically compute an initial condition for the timestepping.
3645aad739acSMatthew G. Knepley 
3646c3339decSBarry Smith   Logically collective
3647aad739acSMatthew G. Knepley 
36484165533cSJose E. Roman   Input Parameters:
3649aad739acSMatthew G. Knepley + ts            - time stepping context
36502e61be88SMatthew G. Knepley - initCondition - The function which computes an initial condition
3651aad739acSMatthew G. Knepley 
365220f4b53cSBarry Smith   Calling sequence of `initCondition`:
3653a96d6ef6SBarry Smith + ts - The timestepping context
365414d0ab18SJacob Faibussowitsch - e  - The input vector in which the initial condition is to be stored
3655aad739acSMatthew G. Knepley 
3656bcf0153eSBarry Smith   Level: advanced
3657bcf0153eSBarry Smith 
36581cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSGetComputeInitialCondition()`, `TSComputeInitialCondition()`
3659aad739acSMatthew G. Knepley @*/
366014d0ab18SJacob Faibussowitsch PetscErrorCode TSSetComputeInitialCondition(TS ts, PetscErrorCode (*initCondition)(TS ts, Vec e))
3661d71ae5a4SJacob Faibussowitsch {
3662aad739acSMatthew G. Knepley   PetscFunctionBegin;
3663aad739acSMatthew G. Knepley   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
36642e61be88SMatthew G. Knepley   PetscValidFunction(initCondition, 2);
36652e61be88SMatthew G. Knepley   ts->ops->initcondition = initCondition;
36663ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
3667aad739acSMatthew G. Knepley }
3668aad739acSMatthew G. Knepley 
3669aad739acSMatthew G. Knepley /*@
3670bcf0153eSBarry Smith   TSComputeInitialCondition - Compute an initial condition for the timestepping using the function previously set with `TSSetComputeInitialCondition()`
3671aad739acSMatthew G. Knepley 
3672c3339decSBarry Smith   Collective
3673aad739acSMatthew G. Knepley 
36744165533cSJose E. Roman   Input Parameters:
3675aad739acSMatthew G. Knepley + ts - time stepping context
3676bcf0153eSBarry Smith - u  - The `Vec` to store the condition in which will be used in `TSSolve()`
3677aad739acSMatthew G. Knepley 
3678aad739acSMatthew G. Knepley   Level: advanced
3679aad739acSMatthew G. Knepley 
36801cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSGetComputeInitialCondition()`, `TSSetComputeInitialCondition()`, `TSSolve()`
3681aad739acSMatthew G. Knepley @*/
3682d71ae5a4SJacob Faibussowitsch PetscErrorCode TSComputeInitialCondition(TS ts, Vec u)
3683d71ae5a4SJacob Faibussowitsch {
3684aad739acSMatthew G. Knepley   PetscFunctionBegin;
3685aad739acSMatthew G. Knepley   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3686aad739acSMatthew G. Knepley   PetscValidHeaderSpecific(u, VEC_CLASSID, 2);
3687dbbe0bcdSBarry Smith   PetscTryTypeMethod(ts, initcondition, u);
36883ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
3689aad739acSMatthew G. Knepley }
3690aad739acSMatthew G. Knepley 
3691aad739acSMatthew G. Knepley /*@C
3692aad739acSMatthew G. Knepley   TSGetComputeExactError - Get the function used to automatically compute the exact error for the timestepping.
3693aad739acSMatthew G. Knepley 
3694aad739acSMatthew G. Knepley   Not collective
3695aad739acSMatthew G. Knepley 
36964165533cSJose E. Roman   Input Parameter:
3697aad739acSMatthew G. Knepley . ts - time stepping context
3698aad739acSMatthew G. Knepley 
36994165533cSJose E. Roman   Output Parameter:
3700aad739acSMatthew G. Knepley . exactError - The function which computes the solution error
3701aad739acSMatthew G. Knepley 
370220f4b53cSBarry Smith   Calling sequence of `exactError`:
3703a96d6ef6SBarry Smith + ts - The timestepping context
3704a96d6ef6SBarry Smith . u  - The approximate solution vector
370520f4b53cSBarry Smith - e  - The vector in which the error is stored
3706aad739acSMatthew G. Knepley 
3707bcf0153eSBarry Smith   Level: advanced
3708bcf0153eSBarry Smith 
370942747ad1SJacob Faibussowitsch .seealso: [](ch_ts), `TS`, `TSComputeExactError()`
3710aad739acSMatthew G. Knepley @*/
371114d0ab18SJacob Faibussowitsch PetscErrorCode TSGetComputeExactError(TS ts, PetscErrorCode (**exactError)(TS ts, Vec u, Vec e))
3712d71ae5a4SJacob Faibussowitsch {
3713aad739acSMatthew G. Knepley   PetscFunctionBegin;
3714aad739acSMatthew G. Knepley   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
37154f572ea9SToby Isaac   PetscAssertPointer(exactError, 2);
3716aad739acSMatthew G. Knepley   *exactError = ts->ops->exacterror;
37173ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
3718aad739acSMatthew G. Knepley }
3719aad739acSMatthew G. Knepley 
3720aad739acSMatthew G. Knepley /*@C
3721aad739acSMatthew G. Knepley   TSSetComputeExactError - Set the function used to automatically compute the exact error for the timestepping.
3722aad739acSMatthew G. Knepley 
3723c3339decSBarry Smith   Logically collective
3724aad739acSMatthew G. Knepley 
37254165533cSJose E. Roman   Input Parameters:
3726aad739acSMatthew G. Knepley + ts         - time stepping context
3727aad739acSMatthew G. Knepley - exactError - The function which computes the solution error
3728aad739acSMatthew G. Knepley 
372920f4b53cSBarry Smith   Calling sequence of `exactError`:
3730a96d6ef6SBarry Smith + ts - The timestepping context
3731a96d6ef6SBarry Smith . u  - The approximate solution vector
373220f4b53cSBarry Smith - e  - The  vector in which the error is stored
3733aad739acSMatthew G. Knepley 
3734bcf0153eSBarry Smith   Level: advanced
3735bcf0153eSBarry Smith 
37361cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSGetComputeExactError()`, `TSComputeExactError()`
3737aad739acSMatthew G. Knepley @*/
373814d0ab18SJacob Faibussowitsch PetscErrorCode TSSetComputeExactError(TS ts, PetscErrorCode (*exactError)(TS ts, Vec u, Vec e))
3739d71ae5a4SJacob Faibussowitsch {
3740aad739acSMatthew G. Knepley   PetscFunctionBegin;
3741aad739acSMatthew G. Knepley   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3742f907fdbfSMatthew G. Knepley   PetscValidFunction(exactError, 2);
3743aad739acSMatthew G. Knepley   ts->ops->exacterror = exactError;
37443ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
3745aad739acSMatthew G. Knepley }
3746aad739acSMatthew G. Knepley 
3747aad739acSMatthew G. Knepley /*@
3748bcf0153eSBarry Smith   TSComputeExactError - Compute the solution error for the timestepping using the function previously set with `TSSetComputeExactError()`
3749aad739acSMatthew G. Knepley 
3750c3339decSBarry Smith   Collective
3751aad739acSMatthew G. Knepley 
37524165533cSJose E. Roman   Input Parameters:
3753aad739acSMatthew G. Knepley + ts - time stepping context
3754aad739acSMatthew G. Knepley . u  - The approximate solution
3755bcf0153eSBarry Smith - e  - The `Vec` used to store the error
3756aad739acSMatthew G. Knepley 
3757aad739acSMatthew G. Knepley   Level: advanced
3758aad739acSMatthew G. Knepley 
37591cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSGetComputeInitialCondition()`, `TSSetComputeInitialCondition()`, `TSSolve()`
3760aad739acSMatthew G. Knepley @*/
3761d71ae5a4SJacob Faibussowitsch PetscErrorCode TSComputeExactError(TS ts, Vec u, Vec e)
3762d71ae5a4SJacob Faibussowitsch {
3763aad739acSMatthew G. Knepley   PetscFunctionBegin;
3764aad739acSMatthew G. Knepley   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3765aad739acSMatthew G. Knepley   PetscValidHeaderSpecific(u, VEC_CLASSID, 2);
3766aad739acSMatthew G. Knepley   PetscValidHeaderSpecific(e, VEC_CLASSID, 3);
3767dbbe0bcdSBarry Smith   PetscTryTypeMethod(ts, exacterror, u, e);
37683ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
3769aad739acSMatthew G. Knepley }
3770aad739acSMatthew G. Knepley 
37716bd3a4fdSStefano Zampini /*@C
37726bd3a4fdSStefano Zampini   TSSetResize - Sets the resize callbacks.
37736bd3a4fdSStefano Zampini 
37746bd3a4fdSStefano Zampini   Logically Collective
37756bd3a4fdSStefano Zampini 
37766bd3a4fdSStefano Zampini   Input Parameters:
37776bd3a4fdSStefano Zampini + ts       - The `TS` context obtained from `TSCreate()`
3778ecc87898SStefano Zampini . rollback - Whether a resize will restart the step
37796bd3a4fdSStefano Zampini . setup    - The setup function
378014d0ab18SJacob Faibussowitsch . transfer - The transfer function
378114d0ab18SJacob Faibussowitsch - ctx      - [optional] The user-defined context
37826bd3a4fdSStefano Zampini 
37836bd3a4fdSStefano Zampini   Calling sequence of `setup`:
37848847d985SBarry Smith + ts     - the `TS` context
37856bd3a4fdSStefano Zampini . step   - the current step
37866bd3a4fdSStefano Zampini . time   - the current time
37876bd3a4fdSStefano Zampini . state  - the current vector of state
37886bd3a4fdSStefano Zampini . resize - (output parameter) `PETSC_TRUE` if need resizing, `PETSC_FALSE` otherwise
37896bd3a4fdSStefano Zampini - ctx    - user defined context
37906bd3a4fdSStefano Zampini 
37916bd3a4fdSStefano Zampini   Calling sequence of `transfer`:
37928847d985SBarry Smith + ts      - the `TS` context
37936bd3a4fdSStefano Zampini . nv      - the number of vectors to be transferred
37946bd3a4fdSStefano Zampini . vecsin  - array of vectors to be transferred
37956bd3a4fdSStefano Zampini . vecsout - array of transferred vectors
37966bd3a4fdSStefano Zampini - ctx     - user defined context
37976bd3a4fdSStefano Zampini 
37986bd3a4fdSStefano Zampini   Notes:
3799ecc87898SStefano Zampini   The `setup` function is called inside `TSSolve()` after `TSEventHandler()` or after `TSPostStep()`
3800ecc87898SStefano Zampini   depending on the `rollback` value: if `rollback` is true, then these callbacks behave as error indicators
3801ecc87898SStefano Zampini   and will flag the need to remesh and restart the current step. Otherwise, they will simply flag the solver
3802ecc87898SStefano Zampini   that the size of the discrete problem has changed.
3803ecc87898SStefano Zampini   In both cases, the solver will collect the needed vectors that will be
3804ecc87898SStefano Zampini   transferred from the old to the new sizes using the `transfer` callback. These vectors will include the
3805ecc87898SStefano Zampini   current solution vector, and other vectors needed by the specific solver used.
38066bd3a4fdSStefano Zampini   For example, `TSBDF` uses previous solutions vectors to solve for the next time step.
38076bd3a4fdSStefano Zampini   Other application specific objects associated with the solver, i.e. Jacobian matrices and `DM`,
38086bd3a4fdSStefano Zampini   will be automatically reset if the sizes are changed and they must be specified again by the user
38096bd3a4fdSStefano Zampini   inside the `transfer` function.
38106bd3a4fdSStefano Zampini   The input and output arrays passed to `transfer` are allocated by PETSc.
38116bd3a4fdSStefano Zampini   Vectors in `vecsout` must be created by the user.
38126bd3a4fdSStefano Zampini   Ownership of vectors in `vecsout` is transferred to PETSc.
38136bd3a4fdSStefano Zampini 
38146bd3a4fdSStefano Zampini   Level: advanced
38156bd3a4fdSStefano Zampini 
38166bd3a4fdSStefano Zampini .seealso: [](ch_ts), `TS`, `TSSetDM()`, `TSSetIJacobian()`, `TSSetRHSJacobian()`
38176bd3a4fdSStefano Zampini @*/
3818ecc87898SStefano 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)
38196bd3a4fdSStefano Zampini {
38206bd3a4fdSStefano Zampini   PetscFunctionBegin;
38216bd3a4fdSStefano Zampini   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3822ecc87898SStefano Zampini   ts->resizerollback = rollback;
38236bd3a4fdSStefano Zampini   ts->resizesetup    = setup;
38246bd3a4fdSStefano Zampini   ts->resizetransfer = transfer;
38256bd3a4fdSStefano Zampini   ts->resizectx      = ctx;
38266bd3a4fdSStefano Zampini   PetscFunctionReturn(PETSC_SUCCESS);
38276bd3a4fdSStefano Zampini }
38286bd3a4fdSStefano Zampini 
382914d0ab18SJacob Faibussowitsch /*
38306bd3a4fdSStefano Zampini   TSResizeRegisterOrRetrieve - Register or import vectors transferred with `TSResize()`.
38316bd3a4fdSStefano Zampini 
38326bd3a4fdSStefano Zampini   Collective
38336bd3a4fdSStefano Zampini 
38346bd3a4fdSStefano Zampini   Input Parameters:
38356bd3a4fdSStefano Zampini + ts   - The `TS` context obtained from `TSCreate()`
38366bd3a4fdSStefano 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.
38376bd3a4fdSStefano Zampini 
38386bd3a4fdSStefano Zampini   Level: developer
38396bd3a4fdSStefano Zampini 
38406bd3a4fdSStefano Zampini   Note:
38416bd3a4fdSStefano Zampini   `TSResizeRegisterOrRetrieve()` is declared PETSC_INTERN since it is
38426bd3a4fdSStefano Zampini    used within time stepping implementations,
38436bd3a4fdSStefano Zampini    so most users would not generally call this routine themselves.
38446bd3a4fdSStefano Zampini 
38456bd3a4fdSStefano Zampini .seealso: [](ch_ts), `TS`, `TSSetResize()`
38466bd3a4fdSStefano Zampini @*/
384714d0ab18SJacob Faibussowitsch static PetscErrorCode TSResizeRegisterOrRetrieve(TS ts, PetscBool flg)
38486bd3a4fdSStefano Zampini {
38496bd3a4fdSStefano Zampini   PetscFunctionBegin;
38506bd3a4fdSStefano Zampini   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
38516bd3a4fdSStefano Zampini   PetscTryTypeMethod(ts, resizeregister, flg);
38526bd3a4fdSStefano Zampini   /* PetscTryTypeMethod(adapt, resizeregister, flg); */
38536bd3a4fdSStefano Zampini   PetscFunctionReturn(PETSC_SUCCESS);
38546bd3a4fdSStefano Zampini }
38556bd3a4fdSStefano Zampini 
385614d0ab18SJacob Faibussowitsch static PetscErrorCode TSResizeReset(TS ts)
38576bd3a4fdSStefano Zampini {
38586bd3a4fdSStefano Zampini   PetscFunctionBegin;
38596bd3a4fdSStefano Zampini   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
38606bd3a4fdSStefano Zampini   PetscCall(PetscObjectListDestroy(&ts->resizetransferobjs));
38616bd3a4fdSStefano Zampini   PetscFunctionReturn(PETSC_SUCCESS);
38626bd3a4fdSStefano Zampini }
38636bd3a4fdSStefano Zampini 
38646bd3a4fdSStefano Zampini static PetscErrorCode TSResizeTransferVecs(TS ts, PetscInt cnt, Vec vecsin[], Vec vecsout[])
38656bd3a4fdSStefano Zampini {
38666bd3a4fdSStefano Zampini   PetscFunctionBegin;
38676bd3a4fdSStefano Zampini   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
38686bd3a4fdSStefano Zampini   PetscValidLogicalCollectiveInt(ts, cnt, 2);
38696bd3a4fdSStefano Zampini   for (PetscInt i = 0; i < cnt; i++) PetscCall(VecLockReadPush(vecsin[i]));
38706bd3a4fdSStefano Zampini   if (ts->resizetransfer) {
38716bd3a4fdSStefano Zampini     PetscCall(PetscInfo(ts, "Transferring %" PetscInt_FMT " vectors\n", cnt));
38726bd3a4fdSStefano Zampini     PetscCallBack("TS callback resize transfer", (*ts->resizetransfer)(ts, cnt, vecsin, vecsout, ts->resizectx));
38736bd3a4fdSStefano Zampini   }
38746bd3a4fdSStefano Zampini   for (PetscInt i = 0; i < cnt; i++) PetscCall(VecLockReadPop(vecsin[i]));
38756bd3a4fdSStefano Zampini   PetscFunctionReturn(PETSC_SUCCESS);
38766bd3a4fdSStefano Zampini }
38776bd3a4fdSStefano Zampini 
38786bd3a4fdSStefano Zampini /*@C
38796bd3a4fdSStefano Zampini   TSResizeRegisterVec - Register a vector to be transferred with `TSResize()`.
38806bd3a4fdSStefano Zampini 
38816bd3a4fdSStefano Zampini   Collective
38826bd3a4fdSStefano Zampini 
38836bd3a4fdSStefano Zampini   Input Parameters:
38846bd3a4fdSStefano Zampini + ts   - The `TS` context obtained from `TSCreate()`
3885baca6076SPierre Jolivet . name - A string identifying the vector
38866bd3a4fdSStefano Zampini - vec  - The vector
38876bd3a4fdSStefano Zampini 
38886bd3a4fdSStefano Zampini   Level: developer
38896bd3a4fdSStefano Zampini 
38906bd3a4fdSStefano Zampini   Note:
38916bd3a4fdSStefano Zampini   `TSResizeRegisterVec()` is typically used within time stepping implementations,
38926bd3a4fdSStefano Zampini   so most users would not generally call this routine themselves.
38936bd3a4fdSStefano Zampini 
38946bd3a4fdSStefano Zampini .seealso: [](ch_ts), `TS`, `TSSetResize()`, `TSResize()`, `TSResizeRetrieveVec()`
38956bd3a4fdSStefano Zampini @*/
3896cc4c1da9SBarry Smith PetscErrorCode TSResizeRegisterVec(TS ts, const char name[], Vec vec)
38976bd3a4fdSStefano Zampini {
38986bd3a4fdSStefano Zampini   PetscFunctionBegin;
38996bd3a4fdSStefano Zampini   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
39004f572ea9SToby Isaac   PetscAssertPointer(name, 2);
39016bd3a4fdSStefano Zampini   if (vec) PetscValidHeaderSpecific(vec, VEC_CLASSID, 3);
39026bd3a4fdSStefano Zampini   PetscCall(PetscObjectListAdd(&ts->resizetransferobjs, name, (PetscObject)vec));
39036bd3a4fdSStefano Zampini   PetscFunctionReturn(PETSC_SUCCESS);
39046bd3a4fdSStefano Zampini }
39056bd3a4fdSStefano Zampini 
39066bd3a4fdSStefano Zampini /*@C
39076bd3a4fdSStefano Zampini   TSResizeRetrieveVec - Retrieve a vector registered with `TSResizeRegisterVec()`.
39086bd3a4fdSStefano Zampini 
39096bd3a4fdSStefano Zampini   Collective
39106bd3a4fdSStefano Zampini 
39116bd3a4fdSStefano Zampini   Input Parameters:
39126bd3a4fdSStefano Zampini + ts   - The `TS` context obtained from `TSCreate()`
3913baca6076SPierre Jolivet . name - A string identifying the vector
39146bd3a4fdSStefano Zampini - vec  - The vector
39156bd3a4fdSStefano Zampini 
39166bd3a4fdSStefano Zampini   Level: developer
39176bd3a4fdSStefano Zampini 
39186bd3a4fdSStefano Zampini   Note:
39196bd3a4fdSStefano Zampini   `TSResizeRetrieveVec()` is typically used within time stepping implementations,
39206bd3a4fdSStefano Zampini   so most users would not generally call this routine themselves.
39216bd3a4fdSStefano Zampini 
39226bd3a4fdSStefano Zampini .seealso: [](ch_ts), `TS`, `TSSetResize()`, `TSResize()`, `TSResizeRegisterVec()`
39236bd3a4fdSStefano Zampini @*/
3924cc4c1da9SBarry Smith PetscErrorCode TSResizeRetrieveVec(TS ts, const char name[], Vec *vec)
39256bd3a4fdSStefano Zampini {
39266bd3a4fdSStefano Zampini   PetscFunctionBegin;
39276bd3a4fdSStefano Zampini   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
39284f572ea9SToby Isaac   PetscAssertPointer(name, 2);
39294f572ea9SToby Isaac   PetscAssertPointer(vec, 3);
39306bd3a4fdSStefano Zampini   PetscCall(PetscObjectListFind(ts->resizetransferobjs, name, (PetscObject *)vec));
39316bd3a4fdSStefano Zampini   PetscFunctionReturn(PETSC_SUCCESS);
39326bd3a4fdSStefano Zampini }
39336bd3a4fdSStefano Zampini 
39346bd3a4fdSStefano Zampini static PetscErrorCode TSResizeGetVecArray(TS ts, PetscInt *nv, const char **names[], Vec *vecs[])
39356bd3a4fdSStefano Zampini {
39366bd3a4fdSStefano Zampini   PetscInt        cnt;
39376bd3a4fdSStefano Zampini   PetscObjectList tmp;
39386bd3a4fdSStefano Zampini   Vec            *vecsin  = NULL;
39396bd3a4fdSStefano Zampini   const char    **namesin = NULL;
39406bd3a4fdSStefano Zampini 
39416bd3a4fdSStefano Zampini   PetscFunctionBegin;
39426bd3a4fdSStefano Zampini   for (tmp = ts->resizetransferobjs, cnt = 0; tmp; tmp = tmp->next)
39436bd3a4fdSStefano Zampini     if (tmp->obj && tmp->obj->classid == VEC_CLASSID) cnt++;
394403ba6ac9SBarry Smith   if (names) PetscCall(PetscMalloc1(cnt, &namesin));
394503ba6ac9SBarry Smith   if (vecs) PetscCall(PetscMalloc1(cnt, &vecsin));
39466bd3a4fdSStefano Zampini   for (tmp = ts->resizetransferobjs, cnt = 0; tmp; tmp = tmp->next) {
39476bd3a4fdSStefano Zampini     if (tmp->obj && tmp->obj->classid == VEC_CLASSID) {
39486bd3a4fdSStefano Zampini       if (vecs) vecsin[cnt] = (Vec)tmp->obj;
39496bd3a4fdSStefano Zampini       if (names) namesin[cnt] = tmp->name;
39506bd3a4fdSStefano Zampini       cnt++;
39516bd3a4fdSStefano Zampini     }
39526bd3a4fdSStefano Zampini   }
39536bd3a4fdSStefano Zampini   if (nv) *nv = cnt;
39546bd3a4fdSStefano Zampini   if (names) *names = namesin;
39556bd3a4fdSStefano Zampini   if (vecs) *vecs = vecsin;
39566bd3a4fdSStefano Zampini   PetscFunctionReturn(PETSC_SUCCESS);
39576bd3a4fdSStefano Zampini }
39586bd3a4fdSStefano Zampini 
39596bd3a4fdSStefano Zampini /*@
39606bd3a4fdSStefano Zampini   TSResize - Runs the user-defined transfer functions provided with `TSSetResize()`
39616bd3a4fdSStefano Zampini 
39626bd3a4fdSStefano Zampini   Collective
39636bd3a4fdSStefano Zampini 
39646bd3a4fdSStefano Zampini   Input Parameter:
39656bd3a4fdSStefano Zampini . ts - The `TS` context obtained from `TSCreate()`
39666bd3a4fdSStefano Zampini 
39676bd3a4fdSStefano Zampini   Level: developer
39686bd3a4fdSStefano Zampini 
39696bd3a4fdSStefano Zampini   Note:
39706bd3a4fdSStefano Zampini   `TSResize()` is typically used within time stepping implementations,
39716bd3a4fdSStefano Zampini   so most users would not generally call this routine themselves.
39726bd3a4fdSStefano Zampini 
39736bd3a4fdSStefano Zampini .seealso: [](ch_ts), `TS`, `TSSetResize()`
39746bd3a4fdSStefano Zampini @*/
39756bd3a4fdSStefano Zampini PetscErrorCode TSResize(TS ts)
39766bd3a4fdSStefano Zampini {
39776bd3a4fdSStefano Zampini   PetscInt     nv      = 0;
39786bd3a4fdSStefano Zampini   const char **names   = NULL;
39796bd3a4fdSStefano Zampini   Vec         *vecsin  = NULL;
39806bd3a4fdSStefano Zampini   const char  *solname = "ts:vec_sol";
39816bd3a4fdSStefano Zampini 
39826bd3a4fdSStefano Zampini   PetscFunctionBegin;
39836bd3a4fdSStefano Zampini   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3984ecc87898SStefano Zampini   if (!ts->resizesetup) PetscFunctionReturn(PETSC_SUCCESS);
39856bd3a4fdSStefano Zampini   if (ts->resizesetup) {
39866bd3a4fdSStefano Zampini     PetscCall(VecLockReadPush(ts->vec_sol));
3987c6bf8827SStefano Zampini     PetscCallBack("TS callback resize setup", (*ts->resizesetup)(ts, ts->steps, ts->ptime, ts->vec_sol, &ts->stepresize, ts->resizectx));
39886bd3a4fdSStefano Zampini     PetscCall(VecLockReadPop(ts->vec_sol));
3989c6bf8827SStefano Zampini     if (ts->stepresize) {
3990ecc87898SStefano Zampini       if (ts->resizerollback) {
3991ecc87898SStefano Zampini         PetscCall(TSRollBack(ts));
3992ecc87898SStefano Zampini         ts->time_step = ts->time_step0;
3993ecc87898SStefano Zampini       }
39946bd3a4fdSStefano Zampini       PetscCall(TSResizeRegisterVec(ts, solname, ts->vec_sol));
39956bd3a4fdSStefano Zampini       PetscCall(TSResizeRegisterOrRetrieve(ts, PETSC_TRUE)); /* specific impls register their own objects */
39966bd3a4fdSStefano Zampini     }
39976bd3a4fdSStefano Zampini   }
39986bd3a4fdSStefano Zampini 
39996bd3a4fdSStefano Zampini   PetscCall(TSResizeGetVecArray(ts, &nv, &names, &vecsin));
40006bd3a4fdSStefano Zampini   if (nv) {
40016bd3a4fdSStefano Zampini     Vec *vecsout, vecsol;
40026bd3a4fdSStefano Zampini 
40036bd3a4fdSStefano Zampini     /* Reset internal objects */
40046bd3a4fdSStefano Zampini     PetscCall(TSReset(ts));
40056bd3a4fdSStefano Zampini 
4006ecc87898SStefano Zampini     /* Transfer needed vectors (users can call SetJacobian, SetDM, etc. here) */
40076bd3a4fdSStefano Zampini     PetscCall(PetscCalloc1(nv, &vecsout));
40086bd3a4fdSStefano Zampini     PetscCall(TSResizeTransferVecs(ts, nv, vecsin, vecsout));
40096bd3a4fdSStefano Zampini     for (PetscInt i = 0; i < nv; i++) {
4010ecc87898SStefano Zampini       const char *name;
4011ecc87898SStefano Zampini       char       *oname;
4012ecc87898SStefano Zampini 
4013ecc87898SStefano Zampini       PetscCall(PetscObjectGetName((PetscObject)vecsin[i], &name));
4014ecc87898SStefano Zampini       PetscCall(PetscStrallocpy(name, &oname));
40156bd3a4fdSStefano Zampini       PetscCall(TSResizeRegisterVec(ts, names[i], vecsout[i]));
4016ecc87898SStefano Zampini       if (vecsout[i]) PetscCall(PetscObjectSetName((PetscObject)vecsout[i], oname));
4017ecc87898SStefano Zampini       PetscCall(PetscFree(oname));
40186bd3a4fdSStefano Zampini       PetscCall(VecDestroy(&vecsout[i]));
40196bd3a4fdSStefano Zampini     }
40206bd3a4fdSStefano Zampini     PetscCall(PetscFree(vecsout));
40216bd3a4fdSStefano Zampini     PetscCall(TSResizeRegisterOrRetrieve(ts, PETSC_FALSE)); /* specific impls import the transferred objects */
40226bd3a4fdSStefano Zampini 
40236bd3a4fdSStefano Zampini     PetscCall(TSResizeRetrieveVec(ts, solname, &vecsol));
40246bd3a4fdSStefano Zampini     if (vecsol) PetscCall(TSSetSolution(ts, vecsol));
40256bd3a4fdSStefano Zampini     PetscAssert(ts->vec_sol, PetscObjectComm((PetscObject)ts), PETSC_ERR_ARG_NULL, "Missing TS solution");
40266bd3a4fdSStefano Zampini   }
40276bd3a4fdSStefano Zampini 
40286bd3a4fdSStefano Zampini   PetscCall(PetscFree(names));
40296bd3a4fdSStefano Zampini   PetscCall(PetscFree(vecsin));
40306bd3a4fdSStefano Zampini   PetscCall(TSResizeReset(ts));
40316bd3a4fdSStefano Zampini   PetscFunctionReturn(PETSC_SUCCESS);
40326bd3a4fdSStefano Zampini }
40336bd3a4fdSStefano Zampini 
4034b1cb36f3SHong Zhang /*@
40356a4d4014SLisandro Dalcin   TSSolve - Steps the requested number of timesteps.
40366a4d4014SLisandro Dalcin 
4037c3339decSBarry Smith   Collective
40386a4d4014SLisandro Dalcin 
4039d8d19677SJose E. Roman   Input Parameters:
4040bcf0153eSBarry Smith + ts - the `TS` context obtained from `TSCreate()`
4041bcf0153eSBarry Smith - u  - the solution vector  (can be null if `TSSetSolution()` was used and `TSSetExactFinalTime`(ts,`TS_EXACTFINALTIME_MATCHSTEP`) was not used,
40420b4b7b1cSBarry Smith        otherwise it must contain the initial conditions and will contain the solution at the final requested time
40435a3a76d0SJed Brown 
40446a4d4014SLisandro Dalcin   Level: beginner
40456a4d4014SLisandro Dalcin 
40465a3a76d0SJed Brown   Notes:
40475a3a76d0SJed Brown   The final time returned by this function may be different from the time of the internally
4048bcf0153eSBarry Smith   held state accessible by `TSGetSolution()` and `TSGetTime()` because the method may have
40495a3a76d0SJed Brown   stepped over the final time.
40505a3a76d0SJed Brown 
40511cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSCreate()`, `TSSetSolution()`, `TSStep()`, `TSGetTime()`, `TSGetSolveTime()`
40526a4d4014SLisandro Dalcin @*/
4053d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSolve(TS ts, Vec u)
4054d71ae5a4SJacob Faibussowitsch {
4055b06615a5SLisandro Dalcin   Vec solution;
4056f22f69f0SBarry Smith 
40576a4d4014SLisandro Dalcin   PetscFunctionBegin;
40580700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
4059f2c2a1b9SBarry Smith   if (u) PetscValidHeaderSpecific(u, VEC_CLASSID, 2);
4060303a5415SBarry Smith 
40619566063dSJacob Faibussowitsch   PetscCall(TSSetExactFinalTimeDefault(ts));
4062ee41a567SStefano 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 */
40630910c330SBarry Smith     if (!ts->vec_sol || u == ts->vec_sol) {
40649566063dSJacob Faibussowitsch       PetscCall(VecDuplicate(u, &solution));
40659566063dSJacob Faibussowitsch       PetscCall(TSSetSolution(ts, solution));
40669566063dSJacob Faibussowitsch       PetscCall(VecDestroy(&solution)); /* grant ownership */
40675a3a76d0SJed Brown     }
40689566063dSJacob Faibussowitsch     PetscCall(VecCopy(u, ts->vec_sol));
40693c633725SBarry Smith     PetscCheck(!ts->forward_solve, PetscObjectComm((PetscObject)ts), PETSC_ERR_SUP, "Sensitivity analysis does not support the mode TS_EXACTFINALTIME_INTERPOLATE");
40701baa6e33SBarry Smith   } else if (u) PetscCall(TSSetSolution(ts, u));
40719566063dSJacob Faibussowitsch   PetscCall(TSSetUp(ts));
40729566063dSJacob Faibussowitsch   PetscCall(TSTrajectorySetUp(ts->trajectory, ts));
4073a6772fa2SLisandro Dalcin 
40748e562f8dSJames 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>");
40753c633725SBarry 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()");
40763c633725SBarry 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");
4077136cf249SJames 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");
40784a658b32SHong Zhang 
4079136cf249SJames Wright   if (ts->eval_times) {
4080136cf249SJames Wright     for (PetscInt i = 0; i < ts->eval_times->num_time_points; i++) {
4081136cf249SJames 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);
4082136cf249SJames Wright       if (ts->ptime <= ts->eval_times->time_points[i] || is_close) {
4083136cf249SJames Wright         ts->eval_times->time_point_idx = i;
4084136cf249SJames Wright         if (is_close) { /* starting point in evaluation times */
4085136cf249SJames Wright           PetscCall(VecCopy(ts->vec_sol, ts->eval_times->sol_vecs[ts->eval_times->sol_ctr]));
4086136cf249SJames Wright           ts->eval_times->sol_times[ts->eval_times->sol_ctr] = ts->ptime;
4087136cf249SJames Wright           ts->eval_times->sol_ctr++;
4088136cf249SJames Wright           ts->eval_times->time_point_idx++;
40898343f784SJames Wright         }
40908343f784SJames Wright         break;
40918343f784SJames Wright       }
40928343f784SJames Wright     }
40934a658b32SHong Zhang   }
4094a6772fa2SLisandro Dalcin 
40951baa6e33SBarry Smith   if (ts->forward_solve) PetscCall(TSForwardSetUp(ts));
4096715f1b00SHong Zhang 
4097e7069c78SShri   /* reset number of steps only when the step is not restarted. ARKIMEX
4098715f1b00SHong Zhang      restarts the step after an event. Resetting these counters in such case causes
4099e7069c78SShri      TSTrajectory to incorrectly save the output files
4100e7069c78SShri   */
4101715f1b00SHong Zhang   /* reset time step and iteration counters */
41022808aa04SLisandro Dalcin   if (!ts->steps) {
41035ef26d82SJed Brown     ts->ksp_its           = 0;
41045ef26d82SJed Brown     ts->snes_its          = 0;
4105c610991cSLisandro Dalcin     ts->num_snes_failures = 0;
4106c610991cSLisandro Dalcin     ts->reject            = 0;
41072808aa04SLisandro Dalcin     ts->steprestart       = PETSC_TRUE;
41082808aa04SLisandro Dalcin     ts->steprollback      = PETSC_FALSE;
4109c6bf8827SStefano Zampini     ts->stepresize        = PETSC_FALSE;
41107d51462cSStefano Zampini     ts->rhsjacobian.time  = PETSC_MIN_REAL;
41112808aa04SLisandro Dalcin   }
4112e97c63d7SStefano Zampini 
4113136cf249SJames Wright   /* make sure initial time step does not overshoot final time or the next point in evaluation times */
4114e97c63d7SStefano Zampini   if (ts->exact_final_time == TS_EXACTFINALTIME_MATCHSTEP) {
41154a658b32SHong Zhang     PetscReal maxdt;
4116e97c63d7SStefano Zampini     PetscReal dt = ts->time_step;
4117e97c63d7SStefano Zampini 
4118136cf249SJames Wright     if (ts->eval_times) maxdt = ts->eval_times->time_points[ts->eval_times->time_point_idx] - ts->ptime;
41194a658b32SHong Zhang     else maxdt = ts->max_time - ts->ptime;
4120e97c63d7SStefano Zampini     ts->time_step = dt >= maxdt ? maxdt : (PetscIsCloseAtTol(dt, maxdt, 10 * PETSC_MACHINE_EPSILON, 0) ? maxdt : dt);
4121e97c63d7SStefano Zampini   }
4122193ac0bcSJed Brown   ts->reason = TS_CONVERGED_ITERATING;
4123193ac0bcSJed Brown 
4124900f6b5bSMatthew G. Knepley   {
4125900f6b5bSMatthew G. Knepley     PetscViewer       viewer;
4126900f6b5bSMatthew G. Knepley     PetscViewerFormat format;
4127900f6b5bSMatthew G. Knepley     PetscBool         flg;
4128900f6b5bSMatthew G. Knepley     static PetscBool  incall = PETSC_FALSE;
4129900f6b5bSMatthew G. Knepley 
4130900f6b5bSMatthew G. Knepley     if (!incall) {
4131900f6b5bSMatthew G. Knepley       /* Estimate the convergence rate of the time discretization */
4132648c30bcSBarry Smith       PetscCall(PetscOptionsCreateViewer(PetscObjectComm((PetscObject)ts), ((PetscObject)ts)->options, ((PetscObject)ts)->prefix, "-ts_convergence_estimate", &viewer, &format, &flg));
4133900f6b5bSMatthew G. Knepley       if (flg) {
4134900f6b5bSMatthew G. Knepley         PetscConvEst conv;
4135900f6b5bSMatthew G. Knepley         DM           dm;
4136900f6b5bSMatthew G. Knepley         PetscReal   *alpha; /* Convergence rate of the solution error for each field in the L_2 norm */
4137900f6b5bSMatthew G. Knepley         PetscInt     Nf;
4138f2ed2dc7SMatthew G. Knepley         PetscBool    checkTemporal = PETSC_TRUE;
4139900f6b5bSMatthew G. Knepley 
4140900f6b5bSMatthew G. Knepley         incall = PETSC_TRUE;
41419566063dSJacob Faibussowitsch         PetscCall(PetscOptionsGetBool(((PetscObject)ts)->options, ((PetscObject)ts)->prefix, "-ts_convergence_temporal", &checkTemporal, &flg));
41429566063dSJacob Faibussowitsch         PetscCall(TSGetDM(ts, &dm));
41439566063dSJacob Faibussowitsch         PetscCall(DMGetNumFields(dm, &Nf));
41449566063dSJacob Faibussowitsch         PetscCall(PetscCalloc1(PetscMax(Nf, 1), &alpha));
41459566063dSJacob Faibussowitsch         PetscCall(PetscConvEstCreate(PetscObjectComm((PetscObject)ts), &conv));
41469566063dSJacob Faibussowitsch         PetscCall(PetscConvEstUseTS(conv, checkTemporal));
41479566063dSJacob Faibussowitsch         PetscCall(PetscConvEstSetSolver(conv, (PetscObject)ts));
41489566063dSJacob Faibussowitsch         PetscCall(PetscConvEstSetFromOptions(conv));
41499566063dSJacob Faibussowitsch         PetscCall(PetscConvEstSetUp(conv));
41509566063dSJacob Faibussowitsch         PetscCall(PetscConvEstGetConvRate(conv, alpha));
41519566063dSJacob Faibussowitsch         PetscCall(PetscViewerPushFormat(viewer, format));
41529566063dSJacob Faibussowitsch         PetscCall(PetscConvEstRateView(conv, alpha, viewer));
41539566063dSJacob Faibussowitsch         PetscCall(PetscViewerPopFormat(viewer));
4154648c30bcSBarry Smith         PetscCall(PetscViewerDestroy(&viewer));
41559566063dSJacob Faibussowitsch         PetscCall(PetscConvEstDestroy(&conv));
41569566063dSJacob Faibussowitsch         PetscCall(PetscFree(alpha));
4157900f6b5bSMatthew G. Knepley         incall = PETSC_FALSE;
4158900f6b5bSMatthew G. Knepley       }
4159900f6b5bSMatthew G. Knepley     }
4160900f6b5bSMatthew G. Knepley   }
4161900f6b5bSMatthew G. Knepley 
41629566063dSJacob Faibussowitsch   PetscCall(TSViewFromOptions(ts, NULL, "-ts_view_pre"));
4163f05ece33SBarry Smith 
4164193ac0bcSJed Brown   if (ts->ops->solve) { /* This private interface is transitional and should be removed when all implementations are updated. */
4165dbbe0bcdSBarry Smith     PetscUseTypeMethod(ts, solve);
41669566063dSJacob Faibussowitsch     if (u) PetscCall(VecCopy(ts->vec_sol, u));
4167cc708dedSBarry Smith     ts->solvetime = ts->ptime;
4168a6772fa2SLisandro Dalcin     solution      = ts->vec_sol;
4169be5899b3SLisandro Dalcin   } else { /* Step the requested number of timesteps. */
4170db4deed7SKarl Rupp     if (ts->steps >= ts->max_steps) ts->reason = TS_CONVERGED_ITS;
4171db4deed7SKarl Rupp     else if (ts->ptime >= ts->max_time) ts->reason = TS_CONVERGED_TIME;
4172e7069c78SShri 
41732808aa04SLisandro Dalcin     if (!ts->steps) {
41749566063dSJacob Faibussowitsch       PetscCall(TSTrajectorySet(ts->trajectory, ts, ts->steps, ts->ptime, ts->vec_sol));
41759566063dSJacob Faibussowitsch       PetscCall(TSEventInitialize(ts->event, ts, ts->ptime, ts->vec_sol));
41762808aa04SLisandro Dalcin     }
41776427ac75SLisandro Dalcin 
41788e562f8dSJames Wright     ts->start_step = ts->steps; // records starting step
4179e1a7a14fSJed Brown     while (!ts->reason) {
41809566063dSJacob Faibussowitsch       PetscCall(TSMonitor(ts, ts->steps, ts->ptime, ts->vec_sol));
4181c6bf8827SStefano Zampini       if (!ts->steprollback || (ts->stepresize && ts->resizerollback)) PetscCall(TSPreStep(ts));
41829566063dSJacob Faibussowitsch       PetscCall(TSStep(ts));
41831baa6e33SBarry Smith       if (ts->testjacobian) PetscCall(TSRHSJacobianTest(ts, NULL));
41841baa6e33SBarry Smith       if (ts->testjacobiantranspose) PetscCall(TSRHSJacobianTestTranspose(ts, NULL));
4185cd4cee2dSHong Zhang       if (ts->quadraturets && ts->costintegralfwd) { /* Must evaluate the cost integral before event is handled. The cost integral value can also be rolled back. */
41867b0e2f17SHong Zhang         if (ts->reason >= 0) ts->steps--;            /* Revert the step number changed by TSStep() */
41879566063dSJacob Faibussowitsch         PetscCall(TSForwardCostIntegral(ts));
41887b0e2f17SHong Zhang         if (ts->reason >= 0) ts->steps++;
4189b1cb36f3SHong Zhang       }
419058818c2dSLisandro Dalcin       if (ts->forward_solve) {            /* compute forward sensitivities before event handling because postevent() may change RHS and jump conditions may have to be applied */
41917b0e2f17SHong Zhang         if (ts->reason >= 0) ts->steps--; /* Revert the step number changed by TSStep() */
41929566063dSJacob Faibussowitsch         PetscCall(TSForwardStep(ts));
41937b0e2f17SHong Zhang         if (ts->reason >= 0) ts->steps++;
4194715f1b00SHong Zhang       }
41959566063dSJacob Faibussowitsch       PetscCall(TSPostEvaluate(ts));
41969566063dSJacob 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. */
41971baa6e33SBarry Smith       if (ts->steprollback) PetscCall(TSPostEvaluate(ts));
4198ecc87898SStefano Zampini       if (!ts->steprollback && ts->resizerollback) PetscCall(TSResize(ts));
419990d719a4SStefano Zampini       /* check convergence */
420090d719a4SStefano Zampini       if (!ts->reason) {
42018e562f8dSJames Wright         if ((ts->steps - ts->start_step) >= ts->run_steps) ts->reason = TS_CONVERGED_ITS;
42028e562f8dSJames Wright         else if (ts->steps >= ts->max_steps) ts->reason = TS_CONVERGED_ITS;
420390d719a4SStefano Zampini         else if (ts->ptime >= ts->max_time) ts->reason = TS_CONVERGED_TIME;
420490d719a4SStefano Zampini       }
4205e783b05fSHong Zhang       if (!ts->steprollback) {
42069566063dSJacob Faibussowitsch         PetscCall(TSTrajectorySet(ts->trajectory, ts, ts->steps, ts->ptime, ts->vec_sol));
42079566063dSJacob Faibussowitsch         PetscCall(TSPostStep(ts));
4208ecc87898SStefano Zampini         if (!ts->resizerollback) PetscCall(TSResize(ts));
4209ca4445c7SIlya Fursov 
421026077dccSJames Wright         if (ts->eval_times && ts->eval_times->time_point_idx < ts->eval_times->num_time_points && ts->reason >= 0) {
4211136cf249SJames Wright           PetscCheck(ts->eval_times->worktol > 0, PetscObjectComm((PetscObject)ts), PETSC_ERR_PLIB, "Unexpected state !(eval_times->worktol > 0) in TSSolve()");
4212136cf249SJames Wright           if (PetscIsCloseAtTol(ts->ptime, ts->eval_times->time_points[ts->eval_times->time_point_idx], ts->eval_times->worktol, 0)) {
4213136cf249SJames Wright             ts->eval_times->sol_times[ts->eval_times->sol_ctr] = ts->ptime;
4214136cf249SJames Wright             PetscCall(VecCopy(ts->vec_sol, ts->eval_times->sol_vecs[ts->eval_times->sol_ctr]));
4215136cf249SJames Wright             ts->eval_times->sol_ctr++;
4216136cf249SJames Wright             ts->eval_times->time_point_idx++;
42178343f784SJames Wright           }
4218ca4445c7SIlya Fursov         }
4219aeb4809dSShri Abhyankar       }
4220193ac0bcSJed Brown     }
42219566063dSJacob Faibussowitsch     PetscCall(TSMonitor(ts, ts->steps, ts->ptime, ts->vec_sol));
42226427ac75SLisandro Dalcin 
422349354f04SShri Abhyankar     if (ts->exact_final_time == TS_EXACTFINALTIME_INTERPOLATE && ts->ptime > ts->max_time) {
42245dbbf88eSStefano Zampini       if (!u) u = ts->vec_sol;
42259566063dSJacob Faibussowitsch       PetscCall(TSInterpolate(ts, ts->max_time, u));
4226cc708dedSBarry Smith       ts->solvetime = ts->max_time;
4227b06615a5SLisandro Dalcin       solution      = u;
42289566063dSJacob Faibussowitsch       PetscCall(TSMonitor(ts, -1, ts->solvetime, solution));
42290574a7fbSJed Brown     } else {
42309566063dSJacob Faibussowitsch       if (u) PetscCall(VecCopy(ts->vec_sol, u));
4231cc708dedSBarry Smith       ts->solvetime = ts->ptime;
4232b06615a5SLisandro Dalcin       solution      = ts->vec_sol;
42330574a7fbSJed Brown     }
4234193ac0bcSJed Brown   }
4235d2daff3dSHong Zhang 
42369566063dSJacob Faibussowitsch   PetscCall(TSViewFromOptions(ts, NULL, "-ts_view"));
42379566063dSJacob Faibussowitsch   PetscCall(VecViewFromOptions(solution, (PetscObject)ts, "-ts_view_solution"));
42389566063dSJacob Faibussowitsch   PetscCall(PetscObjectSAWsBlock((PetscObject)ts));
42391baa6e33SBarry Smith   if (ts->adjoint_solve) PetscCall(TSAdjointSolve(ts));
42403ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
42416a4d4014SLisandro Dalcin }
42426a4d4014SLisandro Dalcin 
4243d763cef2SBarry Smith /*@
4244b8123daeSJed Brown   TSGetTime - Gets the time of the most recently completed step.
4245d763cef2SBarry Smith 
4246d763cef2SBarry Smith   Not Collective
4247d763cef2SBarry Smith 
4248d763cef2SBarry Smith   Input Parameter:
4249bcf0153eSBarry Smith . ts - the `TS` context obtained from `TSCreate()`
4250d763cef2SBarry Smith 
4251d763cef2SBarry Smith   Output Parameter:
4252bcf0153eSBarry Smith . t - the current time. This time may not corresponds to the final time set with `TSSetMaxTime()`, use `TSGetSolveTime()`.
4253d763cef2SBarry Smith 
4254d763cef2SBarry Smith   Level: beginner
4255d763cef2SBarry Smith 
4256b8123daeSJed Brown   Note:
4257bcf0153eSBarry Smith   When called during time step evaluation (e.g. during residual evaluation or via hooks set using `TSSetPreStep()`,
4258bcf0153eSBarry Smith   `TSSetPreStage()`, `TSSetPostStage()`, or `TSSetPostStep()`), the time is the time at the start of the step being evaluated.
4259b8123daeSJed Brown 
4260a94f484eSPierre Jolivet .seealso: [](ch_ts), `TS`, `TSGetSolveTime()`, `TSSetTime()`, `TSGetTimeStep()`, `TSGetStepNumber()`
4261d763cef2SBarry Smith @*/
4262d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetTime(TS ts, PetscReal *t)
4263d71ae5a4SJacob Faibussowitsch {
4264d763cef2SBarry Smith   PetscFunctionBegin;
42650700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
42664f572ea9SToby Isaac   PetscAssertPointer(t, 2);
4267d763cef2SBarry Smith   *t = ts->ptime;
42683ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
4269d763cef2SBarry Smith }
4270d763cef2SBarry Smith 
4271e5e524a1SHong Zhang /*@
4272e5e524a1SHong Zhang   TSGetPrevTime - Gets the starting time of the previously completed step.
4273e5e524a1SHong Zhang 
4274e5e524a1SHong Zhang   Not Collective
4275e5e524a1SHong Zhang 
4276e5e524a1SHong Zhang   Input Parameter:
4277bcf0153eSBarry Smith . ts - the `TS` context obtained from `TSCreate()`
4278e5e524a1SHong Zhang 
4279e5e524a1SHong Zhang   Output Parameter:
4280e5e524a1SHong Zhang . t - the previous time
4281e5e524a1SHong Zhang 
4282e5e524a1SHong Zhang   Level: beginner
4283e5e524a1SHong Zhang 
4284a94f484eSPierre Jolivet .seealso: [](ch_ts), `TS`, `TSGetTime()`, `TSGetSolveTime()`, `TSGetTimeStep()`
4285e5e524a1SHong Zhang @*/
4286d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetPrevTime(TS ts, PetscReal *t)
4287d71ae5a4SJacob Faibussowitsch {
4288e5e524a1SHong Zhang   PetscFunctionBegin;
4289e5e524a1SHong Zhang   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
42904f572ea9SToby Isaac   PetscAssertPointer(t, 2);
4291e5e524a1SHong Zhang   *t = ts->ptime_prev;
42923ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
4293e5e524a1SHong Zhang }
4294e5e524a1SHong Zhang 
42956a4d4014SLisandro Dalcin /*@
42966a4d4014SLisandro Dalcin   TSSetTime - Allows one to reset the time.
42976a4d4014SLisandro Dalcin 
4298c3339decSBarry Smith   Logically Collective
42996a4d4014SLisandro Dalcin 
43006a4d4014SLisandro Dalcin   Input Parameters:
4301bcf0153eSBarry Smith + ts - the `TS` context obtained from `TSCreate()`
4302b43aa488SJacob Faibussowitsch - t  - the time
43036a4d4014SLisandro Dalcin 
43046a4d4014SLisandro Dalcin   Level: intermediate
43056a4d4014SLisandro Dalcin 
43061cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSGetTime()`, `TSSetMaxSteps()`
43076a4d4014SLisandro Dalcin @*/
4308d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetTime(TS ts, PetscReal t)
4309d71ae5a4SJacob Faibussowitsch {
43106a4d4014SLisandro Dalcin   PetscFunctionBegin;
43110700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
4312c5eb9154SBarry Smith   PetscValidLogicalCollectiveReal(ts, t, 2);
43136a4d4014SLisandro Dalcin   ts->ptime = t;
43143ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
43156a4d4014SLisandro Dalcin }
43166a4d4014SLisandro Dalcin 
4317cc4c1da9SBarry Smith /*@
4318d763cef2SBarry Smith   TSSetOptionsPrefix - Sets the prefix used for searching for all
4319d763cef2SBarry Smith   TS options in the database.
4320d763cef2SBarry Smith 
4321c3339decSBarry Smith   Logically Collective
4322d763cef2SBarry Smith 
4323d8d19677SJose E. Roman   Input Parameters:
4324bcf0153eSBarry Smith + ts     - The `TS` context
4325d763cef2SBarry Smith - prefix - The prefix to prepend to all option names
4326d763cef2SBarry Smith 
4327bcf0153eSBarry Smith   Level: advanced
4328bcf0153eSBarry Smith 
4329bcf0153eSBarry Smith   Note:
4330d763cef2SBarry Smith   A hyphen (-) must NOT be given at the beginning of the prefix name.
4331d763cef2SBarry Smith   The first character of all runtime options is AUTOMATICALLY the
4332d763cef2SBarry Smith   hyphen.
4333d763cef2SBarry Smith 
43341cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetFromOptions()`, `TSAppendOptionsPrefix()`
4335d763cef2SBarry Smith @*/
4336d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetOptionsPrefix(TS ts, const char prefix[])
4337d71ae5a4SJacob Faibussowitsch {
4338089b2837SJed Brown   SNES snes;
4339d763cef2SBarry Smith 
4340d763cef2SBarry Smith   PetscFunctionBegin;
43410700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
43429566063dSJacob Faibussowitsch   PetscCall(PetscObjectSetOptionsPrefix((PetscObject)ts, prefix));
43439566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts, &snes));
43449566063dSJacob Faibussowitsch   PetscCall(SNESSetOptionsPrefix(snes, prefix));
43453ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
4346d763cef2SBarry Smith }
4347d763cef2SBarry Smith 
4348cc4c1da9SBarry Smith /*@
4349d763cef2SBarry Smith   TSAppendOptionsPrefix - Appends to the prefix used for searching for all
4350d763cef2SBarry Smith   TS options in the database.
4351d763cef2SBarry Smith 
4352c3339decSBarry Smith   Logically Collective
4353d763cef2SBarry Smith 
4354d8d19677SJose E. Roman   Input Parameters:
4355bcf0153eSBarry Smith + ts     - The `TS` context
4356d763cef2SBarry Smith - prefix - The prefix to prepend to all option names
4357d763cef2SBarry Smith 
4358bcf0153eSBarry Smith   Level: advanced
4359bcf0153eSBarry Smith 
4360bcf0153eSBarry Smith   Note:
4361d763cef2SBarry Smith   A hyphen (-) must NOT be given at the beginning of the prefix name.
4362d763cef2SBarry Smith   The first character of all runtime options is AUTOMATICALLY the
4363d763cef2SBarry Smith   hyphen.
4364d763cef2SBarry Smith 
43651cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSGetOptionsPrefix()`, `TSSetOptionsPrefix()`, `TSSetFromOptions()`
4366d763cef2SBarry Smith @*/
4367d71ae5a4SJacob Faibussowitsch PetscErrorCode TSAppendOptionsPrefix(TS ts, const char prefix[])
4368d71ae5a4SJacob Faibussowitsch {
4369089b2837SJed Brown   SNES snes;
4370d763cef2SBarry Smith 
4371d763cef2SBarry Smith   PetscFunctionBegin;
43720700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
43739566063dSJacob Faibussowitsch   PetscCall(PetscObjectAppendOptionsPrefix((PetscObject)ts, prefix));
43749566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts, &snes));
43759566063dSJacob Faibussowitsch   PetscCall(SNESAppendOptionsPrefix(snes, prefix));
43763ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
4377d763cef2SBarry Smith }
4378d763cef2SBarry Smith 
4379cc4c1da9SBarry Smith /*@
4380d763cef2SBarry Smith   TSGetOptionsPrefix - Sets the prefix used for searching for all
4381bcf0153eSBarry Smith   `TS` options in the database.
4382d763cef2SBarry Smith 
4383d763cef2SBarry Smith   Not Collective
4384d763cef2SBarry Smith 
4385d763cef2SBarry Smith   Input Parameter:
4386bcf0153eSBarry Smith . ts - The `TS` context
4387d763cef2SBarry Smith 
4388d763cef2SBarry Smith   Output Parameter:
4389d763cef2SBarry Smith . prefix - A pointer to the prefix string used
4390d763cef2SBarry Smith 
4391d763cef2SBarry Smith   Level: intermediate
4392d763cef2SBarry Smith 
43931cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSAppendOptionsPrefix()`, `TSSetFromOptions()`
4394d763cef2SBarry Smith @*/
4395d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetOptionsPrefix(TS ts, const char *prefix[])
4396d71ae5a4SJacob Faibussowitsch {
4397d763cef2SBarry Smith   PetscFunctionBegin;
43980700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
43994f572ea9SToby Isaac   PetscAssertPointer(prefix, 2);
44009566063dSJacob Faibussowitsch   PetscCall(PetscObjectGetOptionsPrefix((PetscObject)ts, prefix));
44013ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
4402d763cef2SBarry Smith }
4403d763cef2SBarry Smith 
4404d763cef2SBarry Smith /*@C
4405d763cef2SBarry Smith   TSGetRHSJacobian - Returns the Jacobian J at the present timestep.
4406d763cef2SBarry Smith 
4407bcf0153eSBarry Smith   Not Collective, but parallel objects are returned if ts is parallel
4408d763cef2SBarry Smith 
4409d763cef2SBarry Smith   Input Parameter:
4410bcf0153eSBarry Smith . ts - The `TS` context obtained from `TSCreate()`
4411d763cef2SBarry Smith 
4412d763cef2SBarry Smith   Output Parameters:
4413195e9b02SBarry Smith + Amat - The (approximate) Jacobian J of G, where U_t = G(U,t)  (or `NULL`)
4414195e9b02SBarry Smith . Pmat - The matrix from which the preconditioner is constructed, usually the same as `Amat`  (or `NULL`)
4415195e9b02SBarry Smith . func - Function to compute the Jacobian of the RHS  (or `NULL`)
4416195e9b02SBarry Smith - ctx  - User-defined context for Jacobian evaluation routine  (or `NULL`)
4417d763cef2SBarry Smith 
4418d763cef2SBarry Smith   Level: intermediate
4419d763cef2SBarry Smith 
4420bcf0153eSBarry Smith   Note:
4421195e9b02SBarry Smith   You can pass in `NULL` for any return argument you do not need.
4422bcf0153eSBarry Smith 
44231cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSGetTimeStep()`, `TSGetMatrices()`, `TSGetTime()`, `TSGetStepNumber()`
4424d763cef2SBarry Smith 
4425d763cef2SBarry Smith @*/
44268434afd1SBarry Smith PetscErrorCode TSGetRHSJacobian(TS ts, Mat *Amat, Mat *Pmat, TSRHSJacobianFn **func, void **ctx)
4427d71ae5a4SJacob Faibussowitsch {
442824989b8cSPeter Brune   DM dm;
4429089b2837SJed Brown 
4430d763cef2SBarry Smith   PetscFunctionBegin;
443123a57915SBarry Smith   if (Amat || Pmat) {
443223a57915SBarry Smith     SNES snes;
44339566063dSJacob Faibussowitsch     PetscCall(TSGetSNES(ts, &snes));
44349566063dSJacob Faibussowitsch     PetscCall(SNESSetUpMatrices(snes));
44359566063dSJacob Faibussowitsch     PetscCall(SNESGetJacobian(snes, Amat, Pmat, NULL, NULL));
443623a57915SBarry Smith   }
44379566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
44389566063dSJacob Faibussowitsch   PetscCall(DMTSGetRHSJacobian(dm, func, ctx));
44393ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
4440d763cef2SBarry Smith }
4441d763cef2SBarry Smith 
44422eca1d9cSJed Brown /*@C
44432eca1d9cSJed Brown   TSGetIJacobian - Returns the implicit Jacobian at the present timestep.
44442eca1d9cSJed Brown 
4445bcf0153eSBarry Smith   Not Collective, but parallel objects are returned if ts is parallel
44462eca1d9cSJed Brown 
44472eca1d9cSJed Brown   Input Parameter:
4448bcf0153eSBarry Smith . ts - The `TS` context obtained from `TSCreate()`
44492eca1d9cSJed Brown 
44502eca1d9cSJed Brown   Output Parameters:
4451e4357dc4SBarry Smith + Amat - The (approximate) Jacobian of F(t,U,U_t)
4452195e9b02SBarry Smith . Pmat - The matrix from which the preconditioner is constructed, often the same as `Amat`
44532eca1d9cSJed Brown . f    - The function to compute the matrices
44542eca1d9cSJed Brown - ctx  - User-defined context for Jacobian evaluation routine
44552eca1d9cSJed Brown 
44562eca1d9cSJed Brown   Level: advanced
44572eca1d9cSJed Brown 
4458bcf0153eSBarry Smith   Note:
4459195e9b02SBarry Smith   You can pass in `NULL` for any return argument you do not need.
4460bcf0153eSBarry Smith 
44611cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSGetTimeStep()`, `TSGetRHSJacobian()`, `TSGetMatrices()`, `TSGetTime()`, `TSGetStepNumber()`
44622eca1d9cSJed Brown @*/
44638434afd1SBarry Smith PetscErrorCode TSGetIJacobian(TS ts, Mat *Amat, Mat *Pmat, TSIJacobianFn **f, void **ctx)
4464d71ae5a4SJacob Faibussowitsch {
446524989b8cSPeter Brune   DM dm;
44660910c330SBarry Smith 
44672eca1d9cSJed Brown   PetscFunctionBegin;
4468c0aab802Sstefano_zampini   if (Amat || Pmat) {
4469c0aab802Sstefano_zampini     SNES snes;
44709566063dSJacob Faibussowitsch     PetscCall(TSGetSNES(ts, &snes));
44719566063dSJacob Faibussowitsch     PetscCall(SNESSetUpMatrices(snes));
44729566063dSJacob Faibussowitsch     PetscCall(SNESGetJacobian(snes, Amat, Pmat, NULL, NULL));
4473c0aab802Sstefano_zampini   }
44749566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
44759566063dSJacob Faibussowitsch   PetscCall(DMTSGetIJacobian(dm, f, ctx));
44763ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
44772eca1d9cSJed Brown }
44782eca1d9cSJed Brown 
4479af0996ceSBarry Smith #include <petsc/private/dmimpl.h>
44806c699258SBarry Smith /*@
4481bcf0153eSBarry Smith   TSSetDM - Sets the `DM` that may be used by some nonlinear solvers or preconditioners under the `TS`
44826c699258SBarry Smith 
4483c3339decSBarry Smith   Logically Collective
44846c699258SBarry Smith 
44856c699258SBarry Smith   Input Parameters:
4486bcf0153eSBarry Smith + ts - the `TS` integrator object
4487195e9b02SBarry Smith - dm - the dm, cannot be `NULL`
44886c699258SBarry Smith 
44896c699258SBarry Smith   Level: intermediate
44906c699258SBarry Smith 
4491bcf0153eSBarry Smith   Notes:
4492bcf0153eSBarry Smith   A `DM` can only be used for solving one problem at a time because information about the problem is stored on the `DM`,
4493bcf0153eSBarry Smith   even when not using interfaces like `DMTSSetIFunction()`.  Use `DMClone()` to get a distinct `DM` when solving
4494bcf0153eSBarry Smith   different problems using the same function space.
4495bcf0153eSBarry Smith 
44961cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `DM`, `TSGetDM()`, `SNESSetDM()`, `SNESGetDM()`
44976c699258SBarry Smith @*/
4498d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetDM(TS ts, DM dm)
4499d71ae5a4SJacob Faibussowitsch {
4500089b2837SJed Brown   SNES snes;
4501942e3340SBarry Smith   DMTS tsdm;
45026c699258SBarry Smith 
45036c699258SBarry Smith   PetscFunctionBegin;
45040700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
45052a808120SBarry Smith   PetscValidHeaderSpecific(dm, DM_CLASSID, 2);
45069566063dSJacob Faibussowitsch   PetscCall(PetscObjectReference((PetscObject)dm));
4507942e3340SBarry Smith   if (ts->dm) { /* Move the DMTS context over to the new DM unless the new DM already has one */
45082a34c10cSBarry Smith     if (ts->dm->dmts && !dm->dmts) {
45099566063dSJacob Faibussowitsch       PetscCall(DMCopyDMTS(ts->dm, dm));
45109566063dSJacob Faibussowitsch       PetscCall(DMGetDMTS(ts->dm, &tsdm));
45111e66621cSBarry Smith       /* Grant write privileges to the replacement DM */
45121e66621cSBarry Smith       if (tsdm->originaldm == ts->dm) tsdm->originaldm = dm;
451324989b8cSPeter Brune     }
45149566063dSJacob Faibussowitsch     PetscCall(DMDestroy(&ts->dm));
451524989b8cSPeter Brune   }
45166c699258SBarry Smith   ts->dm = dm;
4517bbd56ea5SKarl Rupp 
45189566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts, &snes));
45199566063dSJacob Faibussowitsch   PetscCall(SNESSetDM(snes, dm));
45203ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
45216c699258SBarry Smith }
45226c699258SBarry Smith 
45236c699258SBarry Smith /*@
4524bcf0153eSBarry Smith   TSGetDM - Gets the `DM` that may be used by some preconditioners
45256c699258SBarry Smith 
45263f9fe445SBarry Smith   Not Collective
45276c699258SBarry Smith 
45286c699258SBarry Smith   Input Parameter:
4529bcf0153eSBarry Smith . ts - the `TS`
45306c699258SBarry Smith 
45316c699258SBarry Smith   Output Parameter:
4532195e9b02SBarry Smith . dm - the `DM`
45336c699258SBarry Smith 
45346c699258SBarry Smith   Level: intermediate
45356c699258SBarry Smith 
45361cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `DM`, `TSSetDM()`, `SNESSetDM()`, `SNESGetDM()`
45376c699258SBarry Smith @*/
4538d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetDM(TS ts, DM *dm)
4539d71ae5a4SJacob Faibussowitsch {
45406c699258SBarry Smith   PetscFunctionBegin;
45410700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
4542496e6a7aSJed Brown   if (!ts->dm) {
45439566063dSJacob Faibussowitsch     PetscCall(DMShellCreate(PetscObjectComm((PetscObject)ts), &ts->dm));
45444bd3aaa3SHong Zhang     if (ts->snes) PetscCall(SNESSetDM(ts->snes, ts->dm));
4545496e6a7aSJed Brown   }
45466c699258SBarry Smith   *dm = ts->dm;
45473ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
45486c699258SBarry Smith }
45491713a123SBarry Smith 
45500f5c6efeSJed Brown /*@
45512ba42892SBarry Smith   SNESTSFormFunction - Function to evaluate nonlinear residual defined by an ODE solver algorithm implemented within `TS`
45520f5c6efeSJed Brown 
4553c3339decSBarry Smith   Logically Collective
45540f5c6efeSJed Brown 
4555d8d19677SJose E. Roman   Input Parameters:
4556d42a1c89SJed Brown + snes - nonlinear solver
45570910c330SBarry Smith . U    - the current state at which to evaluate the residual
45582ba42892SBarry Smith - ctx  - user context, must be a `TS`
45590f5c6efeSJed Brown 
45600f5c6efeSJed Brown   Output Parameter:
45610f5c6efeSJed Brown . F - the nonlinear residual
45620f5c6efeSJed Brown 
45632ba42892SBarry Smith   Level: developer
45640f5c6efeSJed Brown 
4565bcf0153eSBarry Smith   Note:
4566bcf0153eSBarry Smith   This function is not normally called by users and is automatically registered with the `SNES` used by `TS`.
4567bcf0153eSBarry Smith   It is most frequently passed to `MatFDColoringSetFunction()`.
4568bcf0153eSBarry Smith 
45691cc06b55SBarry Smith .seealso: [](ch_ts), `SNESSetFunction()`, `MatFDColoringSetFunction()`
45700f5c6efeSJed Brown @*/
4571d71ae5a4SJacob Faibussowitsch PetscErrorCode SNESTSFormFunction(SNES snes, Vec U, Vec F, void *ctx)
4572d71ae5a4SJacob Faibussowitsch {
45730f5c6efeSJed Brown   TS ts = (TS)ctx;
45740f5c6efeSJed Brown 
45750f5c6efeSJed Brown   PetscFunctionBegin;
45760f5c6efeSJed Brown   PetscValidHeaderSpecific(snes, SNES_CLASSID, 1);
45770910c330SBarry Smith   PetscValidHeaderSpecific(U, VEC_CLASSID, 2);
45780f5c6efeSJed Brown   PetscValidHeaderSpecific(F, VEC_CLASSID, 3);
45790f5c6efeSJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 4);
4580346ce620SStefano Zampini   PetscCheck(ts->ops->snesfunction, PetscObjectComm((PetscObject)ts), PETSC_ERR_SUP, "No method snesfunction for TS of type %s", ((PetscObject)ts)->type_name);
4581346ce620SStefano Zampini   PetscCall((*ts->ops->snesfunction)(snes, U, F, ts));
45823ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
45830f5c6efeSJed Brown }
45840f5c6efeSJed Brown 
45850f5c6efeSJed Brown /*@
45862ba42892SBarry Smith   SNESTSFormJacobian - Function to evaluate the Jacobian defined by an ODE solver algorithm implemented within `TS`
45870f5c6efeSJed Brown 
4588c3339decSBarry Smith   Collective
45890f5c6efeSJed Brown 
4590d8d19677SJose E. Roman   Input Parameters:
45910f5c6efeSJed Brown + snes - nonlinear solver
45920910c330SBarry Smith . U    - the current state at which to evaluate the residual
4593bcf0153eSBarry Smith - ctx  - user context, must be a `TS`
45940f5c6efeSJed Brown 
4595d8d19677SJose E. Roman   Output Parameters:
45960f5c6efeSJed Brown + A - the Jacobian
45977addb90fSBarry Smith - B - the matrix used to construct the preconditioner (often the same as `A`)
45980f5c6efeSJed Brown 
45990f5c6efeSJed Brown   Level: developer
46000f5c6efeSJed Brown 
4601bcf0153eSBarry Smith   Note:
4602bcf0153eSBarry Smith   This function is not normally called by users and is automatically registered with the `SNES` used by `TS`.
4603bcf0153eSBarry Smith 
46041cc06b55SBarry Smith .seealso: [](ch_ts), `SNESSetJacobian()`
46050f5c6efeSJed Brown @*/
4606d71ae5a4SJacob Faibussowitsch PetscErrorCode SNESTSFormJacobian(SNES snes, Vec U, Mat A, Mat B, void *ctx)
4607d71ae5a4SJacob Faibussowitsch {
46080f5c6efeSJed Brown   TS ts = (TS)ctx;
46090f5c6efeSJed Brown 
46100f5c6efeSJed Brown   PetscFunctionBegin;
46110f5c6efeSJed Brown   PetscValidHeaderSpecific(snes, SNES_CLASSID, 1);
46120910c330SBarry Smith   PetscValidHeaderSpecific(U, VEC_CLASSID, 2);
461394ab13aaSBarry Smith   PetscValidHeaderSpecific(A, MAT_CLASSID, 3);
461494ab13aaSBarry Smith   PetscValidHeaderSpecific(B, MAT_CLASSID, 4);
4615064a246eSJacob Faibussowitsch   PetscValidHeaderSpecific(ts, TS_CLASSID, 5);
4616346ce620SStefano Zampini   PetscCheck(ts->ops->snesjacobian, PetscObjectComm((PetscObject)ts), PETSC_ERR_SUP, "No method snesjacobian for TS of type %s", ((PetscObject)ts)->type_name);
4617346ce620SStefano Zampini   PetscCall((*ts->ops->snesjacobian)(snes, U, A, B, ts));
46183ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
46190f5c6efeSJed Brown }
4620325fc9f4SBarry Smith 
46210e4ef248SJed Brown /*@C
4622dd8e379bSPierre Jolivet   TSComputeRHSFunctionLinear - Evaluate the right-hand side via the user-provided Jacobian, for linear problems Udot = A U only
46230e4ef248SJed Brown 
4624c3339decSBarry Smith   Collective
46250e4ef248SJed Brown 
46264165533cSJose E. Roman   Input Parameters:
46270e4ef248SJed Brown + ts  - time stepping context
46280e4ef248SJed Brown . t   - time at which to evaluate
46290910c330SBarry Smith . U   - state at which to evaluate
46300e4ef248SJed Brown - ctx - context
46310e4ef248SJed Brown 
46324165533cSJose E. Roman   Output Parameter:
4633dd8e379bSPierre Jolivet . F - right-hand side
46340e4ef248SJed Brown 
46350e4ef248SJed Brown   Level: intermediate
46360e4ef248SJed Brown 
4637bcf0153eSBarry Smith   Note:
4638dd8e379bSPierre Jolivet   This function is intended to be passed to `TSSetRHSFunction()` to evaluate the right-hand side for linear problems.
4639bcf0153eSBarry Smith   The matrix (and optionally the evaluation context) should be passed to `TSSetRHSJacobian()`.
46400e4ef248SJed Brown 
46411cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetRHSFunction()`, `TSSetRHSJacobian()`, `TSComputeRHSJacobianConstant()`
46420e4ef248SJed Brown @*/
4643d71ae5a4SJacob Faibussowitsch PetscErrorCode TSComputeRHSFunctionLinear(TS ts, PetscReal t, Vec U, Vec F, void *ctx)
4644d71ae5a4SJacob Faibussowitsch {
46450e4ef248SJed Brown   Mat Arhs, Brhs;
46460e4ef248SJed Brown 
46470e4ef248SJed Brown   PetscFunctionBegin;
46489566063dSJacob Faibussowitsch   PetscCall(TSGetRHSMats_Private(ts, &Arhs, &Brhs));
46492663174eSHong Zhang   /* undo the damage caused by shifting */
46509566063dSJacob Faibussowitsch   PetscCall(TSRecoverRHSJacobian(ts, Arhs, Brhs));
46519566063dSJacob Faibussowitsch   PetscCall(TSComputeRHSJacobian(ts, t, U, Arhs, Brhs));
46529566063dSJacob Faibussowitsch   PetscCall(MatMult(Arhs, U, F));
46533ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
46540e4ef248SJed Brown }
46550e4ef248SJed Brown 
46560e4ef248SJed Brown /*@C
46570e4ef248SJed Brown   TSComputeRHSJacobianConstant - Reuses a Jacobian that is time-independent.
46580e4ef248SJed Brown 
4659c3339decSBarry Smith   Collective
46600e4ef248SJed Brown 
46614165533cSJose E. Roman   Input Parameters:
46620e4ef248SJed Brown + ts  - time stepping context
46630e4ef248SJed Brown . t   - time at which to evaluate
46640910c330SBarry Smith . U   - state at which to evaluate
46650e4ef248SJed Brown - ctx - context
46660e4ef248SJed Brown 
46674165533cSJose E. Roman   Output Parameters:
46687addb90fSBarry Smith + A - Jacobian
46697addb90fSBarry Smith - B - matrix used to construct the preconditioner, often the same as `A`
46700e4ef248SJed Brown 
46710e4ef248SJed Brown   Level: intermediate
46720e4ef248SJed Brown 
4673bcf0153eSBarry Smith   Note:
4674bcf0153eSBarry Smith   This function is intended to be passed to `TSSetRHSJacobian()` to evaluate the Jacobian for linear time-independent problems.
46750e4ef248SJed Brown 
46761cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetRHSFunction()`, `TSSetRHSJacobian()`, `TSComputeRHSFunctionLinear()`
46770e4ef248SJed Brown @*/
4678d71ae5a4SJacob Faibussowitsch PetscErrorCode TSComputeRHSJacobianConstant(TS ts, PetscReal t, Vec U, Mat A, Mat B, void *ctx)
4679d71ae5a4SJacob Faibussowitsch {
46800e4ef248SJed Brown   PetscFunctionBegin;
46813ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
46820e4ef248SJed Brown }
46830e4ef248SJed Brown 
46840026cea9SSean Farley /*@C
46850026cea9SSean Farley   TSComputeIFunctionLinear - Evaluate the left hand side via the user-provided Jacobian, for linear problems only
46860026cea9SSean Farley 
4687c3339decSBarry Smith   Collective
46880026cea9SSean Farley 
46894165533cSJose E. Roman   Input Parameters:
46900026cea9SSean Farley + ts   - time stepping context
46910026cea9SSean Farley . t    - time at which to evaluate
46920910c330SBarry Smith . U    - state at which to evaluate
46930910c330SBarry Smith . Udot - time derivative of state vector
46940026cea9SSean Farley - ctx  - context
46950026cea9SSean Farley 
46964165533cSJose E. Roman   Output Parameter:
46970026cea9SSean Farley . F - left hand side
46980026cea9SSean Farley 
46990026cea9SSean Farley   Level: intermediate
47000026cea9SSean Farley 
47010026cea9SSean Farley   Notes:
47020910c330SBarry 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
4703bcf0153eSBarry Smith   user is required to write their own `TSComputeIFunction()`.
4704bcf0153eSBarry Smith   This function is intended to be passed to `TSSetIFunction()` to evaluate the left hand side for linear problems.
4705bcf0153eSBarry Smith   The matrix (and optionally the evaluation context) should be passed to `TSSetIJacobian()`.
47060026cea9SSean Farley 
4707bcf0153eSBarry Smith   Note that using this function is NOT equivalent to using `TSComputeRHSFunctionLinear()` since that solves Udot = A U
47089ae8fd06SBarry Smith 
47091cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetIFunction()`, `TSSetIJacobian()`, `TSComputeIJacobianConstant()`, `TSComputeRHSFunctionLinear()`
47100026cea9SSean Farley @*/
4711d71ae5a4SJacob Faibussowitsch PetscErrorCode TSComputeIFunctionLinear(TS ts, PetscReal t, Vec U, Vec Udot, Vec F, void *ctx)
4712d71ae5a4SJacob Faibussowitsch {
47130026cea9SSean Farley   Mat A, B;
47140026cea9SSean Farley 
47150026cea9SSean Farley   PetscFunctionBegin;
47169566063dSJacob Faibussowitsch   PetscCall(TSGetIJacobian(ts, &A, &B, NULL, NULL));
47179566063dSJacob Faibussowitsch   PetscCall(TSComputeIJacobian(ts, t, U, Udot, 1.0, A, B, PETSC_TRUE));
47189566063dSJacob Faibussowitsch   PetscCall(MatMult(A, Udot, F));
47193ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
47200026cea9SSean Farley }
47210026cea9SSean Farley 
47220026cea9SSean Farley /*@C
47238434afd1SBarry Smith   TSComputeIJacobianConstant - Reuses the matrix previously computed with the provided `TSIJacobianFn` for a semi-implicit DAE or ODE
47240026cea9SSean Farley 
4725c3339decSBarry Smith   Collective
47260026cea9SSean Farley 
47274165533cSJose E. Roman   Input Parameters:
47280026cea9SSean Farley + ts    - time stepping context
47290026cea9SSean Farley . t     - time at which to evaluate
47300910c330SBarry Smith . U     - state at which to evaluate
47310910c330SBarry Smith . Udot  - time derivative of state vector
47320026cea9SSean Farley . shift - shift to apply
47330026cea9SSean Farley - ctx   - context
47340026cea9SSean Farley 
47354165533cSJose E. Roman   Output Parameters:
47360026cea9SSean Farley + A - pointer to operator
4737d1c5d1fcSBarry Smith - B - pointer to matrix from which the preconditioner is built (often `A`)
47380026cea9SSean Farley 
4739b41af12eSJed Brown   Level: advanced
47400026cea9SSean Farley 
47410026cea9SSean Farley   Notes:
4742bcf0153eSBarry Smith   This function is intended to be passed to `TSSetIJacobian()` to evaluate the Jacobian for linear time-independent problems.
47430026cea9SSean Farley 
4744b41af12eSJed Brown   It is only appropriate for problems of the form
4745b41af12eSJed Brown 
4746d1c5d1fcSBarry Smith   $$
4747d1c5d1fcSBarry Smith   M \dot{U} = F(U,t)
4748d1c5d1fcSBarry Smith   $$
4749b41af12eSJed Brown 
4750bcf0153eSBarry Smith   where M is constant and F is non-stiff.  The user must pass M to `TSSetIJacobian()`.  The current implementation only
4751bcf0153eSBarry Smith   works with IMEX time integration methods such as `TSROSW` and `TSARKIMEX`, since there is no support for de-constructing
4752b41af12eSJed Brown   an implicit operator of the form
4753b41af12eSJed Brown 
4754d1c5d1fcSBarry Smith   $$
4755d1c5d1fcSBarry Smith   shift*M + J
4756d1c5d1fcSBarry Smith   $$
4757b41af12eSJed Brown 
4758b41af12eSJed 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
4759b41af12eSJed Brown   a copy of M or reassemble it when requested.
4760b41af12eSJed Brown 
47611cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSROSW`, `TSARKIMEX`, `TSSetIFunction()`, `TSSetIJacobian()`, `TSComputeIFunctionLinear()`
47620026cea9SSean Farley @*/
4763d71ae5a4SJacob Faibussowitsch PetscErrorCode TSComputeIJacobianConstant(TS ts, PetscReal t, Vec U, Vec Udot, PetscReal shift, Mat A, Mat B, void *ctx)
4764d71ae5a4SJacob Faibussowitsch {
47650026cea9SSean Farley   PetscFunctionBegin;
47669566063dSJacob Faibussowitsch   PetscCall(MatScale(A, shift / ts->ijacobian.shift));
4767b41af12eSJed Brown   ts->ijacobian.shift = shift;
47683ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
47690026cea9SSean Farley }
4770b41af12eSJed Brown 
4771e817cc15SEmil Constantinescu /*@
4772bcf0153eSBarry Smith   TSGetEquationType - Gets the type of the equation that `TS` is solving.
4773e817cc15SEmil Constantinescu 
4774e817cc15SEmil Constantinescu   Not Collective
4775e817cc15SEmil Constantinescu 
4776e817cc15SEmil Constantinescu   Input Parameter:
4777bcf0153eSBarry Smith . ts - the `TS` context
4778e817cc15SEmil Constantinescu 
4779e817cc15SEmil Constantinescu   Output Parameter:
4780bcf0153eSBarry Smith . equation_type - see `TSEquationType`
4781e817cc15SEmil Constantinescu 
4782e817cc15SEmil Constantinescu   Level: beginner
4783e817cc15SEmil Constantinescu 
47841cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetEquationType()`, `TSEquationType`
4785e817cc15SEmil Constantinescu @*/
4786d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetEquationType(TS ts, TSEquationType *equation_type)
4787d71ae5a4SJacob Faibussowitsch {
4788e817cc15SEmil Constantinescu   PetscFunctionBegin;
4789e817cc15SEmil Constantinescu   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
47904f572ea9SToby Isaac   PetscAssertPointer(equation_type, 2);
4791e817cc15SEmil Constantinescu   *equation_type = ts->equation_type;
47923ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
4793e817cc15SEmil Constantinescu }
4794e817cc15SEmil Constantinescu 
4795e817cc15SEmil Constantinescu /*@
4796bcf0153eSBarry Smith   TSSetEquationType - Sets the type of the equation that `TS` is solving.
4797e817cc15SEmil Constantinescu 
4798e817cc15SEmil Constantinescu   Not Collective
4799e817cc15SEmil Constantinescu 
4800d8d19677SJose E. Roman   Input Parameters:
4801bcf0153eSBarry Smith + ts            - the `TS` context
4802bcf0153eSBarry Smith - equation_type - see `TSEquationType`
4803e817cc15SEmil Constantinescu 
4804e817cc15SEmil Constantinescu   Level: advanced
4805e817cc15SEmil Constantinescu 
48061cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSGetEquationType()`, `TSEquationType`
4807e817cc15SEmil Constantinescu @*/
4808d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetEquationType(TS ts, TSEquationType equation_type)
4809d71ae5a4SJacob Faibussowitsch {
4810e817cc15SEmil Constantinescu   PetscFunctionBegin;
4811e817cc15SEmil Constantinescu   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
4812e817cc15SEmil Constantinescu   ts->equation_type = equation_type;
48133ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
4814e817cc15SEmil Constantinescu }
48150026cea9SSean Farley 
48164af1b03aSJed Brown /*@
4817bcf0153eSBarry Smith   TSGetConvergedReason - Gets the reason the `TS` iteration was stopped.
48184af1b03aSJed Brown 
48194af1b03aSJed Brown   Not Collective
48204af1b03aSJed Brown 
48214af1b03aSJed Brown   Input Parameter:
4822bcf0153eSBarry Smith . ts - the `TS` context
48234af1b03aSJed Brown 
48244af1b03aSJed Brown   Output Parameter:
4825bcf0153eSBarry Smith . reason - negative value indicates diverged, positive value converged, see `TSConvergedReason` or the
48264af1b03aSJed Brown             manual pages for the individual convergence tests for complete lists
48274af1b03aSJed Brown 
4828487e0bb9SJed Brown   Level: beginner
48294af1b03aSJed Brown 
4830bcf0153eSBarry Smith   Note:
4831bcf0153eSBarry Smith   Can only be called after the call to `TSSolve()` is complete.
48324af1b03aSJed Brown 
48337d66147cSPierre Jolivet .seealso: [](ch_ts), `TS`, `TSSolve()`, `TSConvergedReason`
48344af1b03aSJed Brown @*/
4835d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetConvergedReason(TS ts, TSConvergedReason *reason)
4836d71ae5a4SJacob Faibussowitsch {
48374af1b03aSJed Brown   PetscFunctionBegin;
48384af1b03aSJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
48394f572ea9SToby Isaac   PetscAssertPointer(reason, 2);
48404af1b03aSJed Brown   *reason = ts->reason;
48413ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
48424af1b03aSJed Brown }
48434af1b03aSJed Brown 
4844d6ad946cSShri Abhyankar /*@
4845bcf0153eSBarry Smith   TSSetConvergedReason - Sets the reason for handling the convergence of `TSSolve()`.
4846d6ad946cSShri Abhyankar 
48476b221cbeSPatrick Sanan   Logically Collective; reason must contain common value
4848d6ad946cSShri Abhyankar 
48496b221cbeSPatrick Sanan   Input Parameters:
4850bcf0153eSBarry Smith + ts     - the `TS` context
4851bcf0153eSBarry Smith - reason - negative value indicates diverged, positive value converged, see `TSConvergedReason` or the
4852d6ad946cSShri Abhyankar             manual pages for the individual convergence tests for complete lists
4853d6ad946cSShri Abhyankar 
4854f5abba47SShri Abhyankar   Level: advanced
4855d6ad946cSShri Abhyankar 
4856bcf0153eSBarry Smith   Note:
4857bcf0153eSBarry Smith   Can only be called while `TSSolve()` is active.
4858d6ad946cSShri Abhyankar 
48591cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSolve()`, `TSConvergedReason`
4860d6ad946cSShri Abhyankar @*/
4861d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetConvergedReason(TS ts, TSConvergedReason reason)
4862d71ae5a4SJacob Faibussowitsch {
4863d6ad946cSShri Abhyankar   PetscFunctionBegin;
4864d6ad946cSShri Abhyankar   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
4865d6ad946cSShri Abhyankar   ts->reason = reason;
48663ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
4867d6ad946cSShri Abhyankar }
4868d6ad946cSShri Abhyankar 
4869cc708dedSBarry Smith /*@
4870bcf0153eSBarry Smith   TSGetSolveTime - Gets the time after a call to `TSSolve()`
4871cc708dedSBarry Smith 
4872cc708dedSBarry Smith   Not Collective
4873cc708dedSBarry Smith 
4874cc708dedSBarry Smith   Input Parameter:
4875bcf0153eSBarry Smith . ts - the `TS` context
4876cc708dedSBarry Smith 
4877cc708dedSBarry Smith   Output Parameter:
4878bcf0153eSBarry Smith . ftime - the final time. This time corresponds to the final time set with `TSSetMaxTime()`
4879cc708dedSBarry Smith 
4880487e0bb9SJed Brown   Level: beginner
4881cc708dedSBarry Smith 
4882bcf0153eSBarry Smith   Note:
4883bcf0153eSBarry Smith   Can only be called after the call to `TSSolve()` is complete.
4884cc708dedSBarry Smith 
48857d66147cSPierre Jolivet .seealso: [](ch_ts), `TS`, `TSSolve()`, `TSConvergedReason`
4886cc708dedSBarry Smith @*/
4887d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetSolveTime(TS ts, PetscReal *ftime)
4888d71ae5a4SJacob Faibussowitsch {
4889cc708dedSBarry Smith   PetscFunctionBegin;
4890cc708dedSBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
48914f572ea9SToby Isaac   PetscAssertPointer(ftime, 2);
4892cc708dedSBarry Smith   *ftime = ts->solvetime;
48933ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
4894cc708dedSBarry Smith }
4895cc708dedSBarry Smith 
48962c18e0fdSBarry Smith /*@
48975ef26d82SJed Brown   TSGetSNESIterations - Gets the total number of nonlinear iterations
48989f67acb7SJed Brown   used by the time integrator.
48999f67acb7SJed Brown 
49009f67acb7SJed Brown   Not Collective
49019f67acb7SJed Brown 
49029f67acb7SJed Brown   Input Parameter:
4903bcf0153eSBarry Smith . ts - `TS` context
49049f67acb7SJed Brown 
49059f67acb7SJed Brown   Output Parameter:
49069f67acb7SJed Brown . nits - number of nonlinear iterations
49079f67acb7SJed Brown 
49089f67acb7SJed Brown   Level: intermediate
49099f67acb7SJed Brown 
4910195e9b02SBarry Smith   Note:
4911bcf0153eSBarry Smith   This counter is reset to zero for each successive call to `TSSolve()`.
4912bcf0153eSBarry Smith 
49131cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSolve()`, `TSGetKSPIterations()`
49149f67acb7SJed Brown @*/
4915d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetSNESIterations(TS ts, PetscInt *nits)
4916d71ae5a4SJacob Faibussowitsch {
49179f67acb7SJed Brown   PetscFunctionBegin;
49189f67acb7SJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
49194f572ea9SToby Isaac   PetscAssertPointer(nits, 2);
49205ef26d82SJed Brown   *nits = ts->snes_its;
49213ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
49229f67acb7SJed Brown }
49239f67acb7SJed Brown 
49249f67acb7SJed Brown /*@
49255ef26d82SJed Brown   TSGetKSPIterations - Gets the total number of linear iterations
49269f67acb7SJed Brown   used by the time integrator.
49279f67acb7SJed Brown 
49289f67acb7SJed Brown   Not Collective
49299f67acb7SJed Brown 
49309f67acb7SJed Brown   Input Parameter:
4931bcf0153eSBarry Smith . ts - `TS` context
49329f67acb7SJed Brown 
49339f67acb7SJed Brown   Output Parameter:
49349f67acb7SJed Brown . lits - number of linear iterations
49359f67acb7SJed Brown 
49369f67acb7SJed Brown   Level: intermediate
49379f67acb7SJed Brown 
4938bcf0153eSBarry Smith   Note:
4939bcf0153eSBarry Smith   This counter is reset to zero for each successive call to `TSSolve()`.
4940bcf0153eSBarry Smith 
4941bfe80ac4SPierre Jolivet .seealso: [](ch_ts), `TS`, `TSSolve()`, `TSGetSNESIterations()`
49429f67acb7SJed Brown @*/
4943d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetKSPIterations(TS ts, PetscInt *lits)
4944d71ae5a4SJacob Faibussowitsch {
49459f67acb7SJed Brown   PetscFunctionBegin;
49469f67acb7SJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
49474f572ea9SToby Isaac   PetscAssertPointer(lits, 2);
49485ef26d82SJed Brown   *lits = ts->ksp_its;
49493ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
49509f67acb7SJed Brown }
49519f67acb7SJed Brown 
4952cef5090cSJed Brown /*@
4953cef5090cSJed Brown   TSGetStepRejections - Gets the total number of rejected steps.
4954cef5090cSJed Brown 
4955cef5090cSJed Brown   Not Collective
4956cef5090cSJed Brown 
4957cef5090cSJed Brown   Input Parameter:
4958bcf0153eSBarry Smith . ts - `TS` context
4959cef5090cSJed Brown 
4960cef5090cSJed Brown   Output Parameter:
4961cef5090cSJed Brown . rejects - number of steps rejected
4962cef5090cSJed Brown 
4963cef5090cSJed Brown   Level: intermediate
4964cef5090cSJed Brown 
4965bcf0153eSBarry Smith   Note:
4966bcf0153eSBarry Smith   This counter is reset to zero for each successive call to `TSSolve()`.
4967bcf0153eSBarry Smith 
49681cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSolve()`, `TSGetSNESIterations()`, `TSGetKSPIterations()`, `TSSetMaxStepRejections()`, `TSGetSNESFailures()`, `TSSetMaxSNESFailures()`, `TSSetErrorIfStepFails()`
4969cef5090cSJed Brown @*/
4970d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetStepRejections(TS ts, PetscInt *rejects)
4971d71ae5a4SJacob Faibussowitsch {
4972cef5090cSJed Brown   PetscFunctionBegin;
4973cef5090cSJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
49744f572ea9SToby Isaac   PetscAssertPointer(rejects, 2);
4975cef5090cSJed Brown   *rejects = ts->reject;
49763ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
4977cef5090cSJed Brown }
4978cef5090cSJed Brown 
4979cef5090cSJed Brown /*@
4980bcf0153eSBarry Smith   TSGetSNESFailures - Gets the total number of failed `SNES` solves in a `TS`
4981cef5090cSJed Brown 
4982cef5090cSJed Brown   Not Collective
4983cef5090cSJed Brown 
4984cef5090cSJed Brown   Input Parameter:
4985bcf0153eSBarry Smith . ts - `TS` context
4986cef5090cSJed Brown 
4987cef5090cSJed Brown   Output Parameter:
4988cef5090cSJed Brown . fails - number of failed nonlinear solves
4989cef5090cSJed Brown 
4990cef5090cSJed Brown   Level: intermediate
4991cef5090cSJed Brown 
4992bcf0153eSBarry Smith   Note:
4993bcf0153eSBarry Smith   This counter is reset to zero for each successive call to `TSSolve()`.
4994bcf0153eSBarry Smith 
49951cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSolve()`, `TSGetSNESIterations()`, `TSGetKSPIterations()`, `TSSetMaxStepRejections()`, `TSGetStepRejections()`, `TSSetMaxSNESFailures()`
4996cef5090cSJed Brown @*/
4997d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetSNESFailures(TS ts, PetscInt *fails)
4998d71ae5a4SJacob Faibussowitsch {
4999cef5090cSJed Brown   PetscFunctionBegin;
5000cef5090cSJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
50014f572ea9SToby Isaac   PetscAssertPointer(fails, 2);
5002cef5090cSJed Brown   *fails = ts->num_snes_failures;
50033ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
5004cef5090cSJed Brown }
5005cef5090cSJed Brown 
5006cef5090cSJed Brown /*@
5007bcf0153eSBarry Smith   TSSetMaxStepRejections - Sets the maximum number of step rejections before a time step fails
5008cef5090cSJed Brown 
5009cef5090cSJed Brown   Not Collective
5010cef5090cSJed Brown 
5011d8d19677SJose E. Roman   Input Parameters:
5012bcf0153eSBarry Smith + ts      - `TS` context
501309cb0f53SBarry Smith - rejects - maximum number of rejected steps, pass `PETSC_UNLIMITED` for unlimited
5014cef5090cSJed Brown 
5015cef5090cSJed Brown   Options Database Key:
5016cef5090cSJed Brown . -ts_max_reject - Maximum number of step rejections before a step fails
5017cef5090cSJed Brown 
5018cef5090cSJed Brown   Level: intermediate
5019cef5090cSJed Brown 
502009cb0f53SBarry Smith   Developer Note:
502109cb0f53SBarry Smith   The options database name is incorrect.
502209cb0f53SBarry Smith 
50231cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `SNES`, `TSGetSNESIterations()`, `TSGetKSPIterations()`, `TSSetMaxSNESFailures()`, `TSGetStepRejections()`, `TSGetSNESFailures()`, `TSSetErrorIfStepFails()`, `TSGetConvergedReason()`
5024cef5090cSJed Brown @*/
5025d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetMaxStepRejections(TS ts, PetscInt rejects)
5026d71ae5a4SJacob Faibussowitsch {
5027cef5090cSJed Brown   PetscFunctionBegin;
5028cef5090cSJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
502909cb0f53SBarry Smith   if (rejects == PETSC_UNLIMITED || rejects == -1) {
503009cb0f53SBarry Smith     ts->max_reject = PETSC_UNLIMITED;
503109cb0f53SBarry Smith   } else {
503209cb0f53SBarry Smith     PetscCheck(rejects >= 0, PetscObjectComm((PetscObject)ts), PETSC_ERR_ARG_OUTOFRANGE, "Cannot have a negative maximum number of rejections");
5033cef5090cSJed Brown     ts->max_reject = rejects;
503409cb0f53SBarry Smith   }
50353ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
5036cef5090cSJed Brown }
5037cef5090cSJed Brown 
5038cef5090cSJed Brown /*@
5039bcf0153eSBarry Smith   TSSetMaxSNESFailures - Sets the maximum number of failed `SNES` solves
5040cef5090cSJed Brown 
5041cef5090cSJed Brown   Not Collective
5042cef5090cSJed Brown 
5043d8d19677SJose E. Roman   Input Parameters:
5044bcf0153eSBarry Smith + ts    - `TS` context
504509cb0f53SBarry Smith - fails - maximum number of failed nonlinear solves, pass `PETSC_UNLIMITED` to allow any number of failures.
5046cef5090cSJed Brown 
5047cef5090cSJed Brown   Options Database Key:
5048cef5090cSJed Brown . -ts_max_snes_failures - Maximum number of nonlinear solve failures
5049cef5090cSJed Brown 
5050cef5090cSJed Brown   Level: intermediate
5051cef5090cSJed Brown 
50521cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `SNES`, `TSGetSNESIterations()`, `TSGetKSPIterations()`, `TSSetMaxStepRejections()`, `TSGetStepRejections()`, `TSGetSNESFailures()`, `SNESGetConvergedReason()`, `TSGetConvergedReason()`
5053cef5090cSJed Brown @*/
5054d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetMaxSNESFailures(TS ts, PetscInt fails)
5055d71ae5a4SJacob Faibussowitsch {
5056cef5090cSJed Brown   PetscFunctionBegin;
5057cef5090cSJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
505809cb0f53SBarry Smith   if (fails == PETSC_UNLIMITED || fails == -1) {
505909cb0f53SBarry Smith     ts->max_snes_failures = PETSC_UNLIMITED;
506009cb0f53SBarry Smith   } else {
506109cb0f53SBarry Smith     PetscCheck(fails >= 0, PetscObjectComm((PetscObject)ts), PETSC_ERR_ARG_OUTOFRANGE, "Cannot have a negative maximum number of failures");
5062cef5090cSJed Brown     ts->max_snes_failures = fails;
506309cb0f53SBarry Smith   }
50643ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
5065cef5090cSJed Brown }
5066cef5090cSJed Brown 
5067cef5090cSJed Brown /*@
5068195e9b02SBarry Smith   TSSetErrorIfStepFails - Immediately error if no step succeeds during `TSSolve()`
5069cef5090cSJed Brown 
5070cef5090cSJed Brown   Not Collective
5071cef5090cSJed Brown 
5072d8d19677SJose E. Roman   Input Parameters:
5073bcf0153eSBarry Smith + ts  - `TS` context
5074bcf0153eSBarry Smith - err - `PETSC_TRUE` to error if no step succeeds, `PETSC_FALSE` to return without failure
5075cef5090cSJed Brown 
5076cef5090cSJed Brown   Options Database Key:
5077cef5090cSJed Brown . -ts_error_if_step_fails - Error if no step succeeds
5078cef5090cSJed Brown 
5079cef5090cSJed Brown   Level: intermediate
5080cef5090cSJed Brown 
508142747ad1SJacob Faibussowitsch .seealso: [](ch_ts), `TS`, `TSGetSNESIterations()`, `TSGetKSPIterations()`, `TSSetMaxStepRejections()`, `TSGetStepRejections()`, `TSGetSNESFailures()`, `TSGetConvergedReason()`
5082cef5090cSJed Brown @*/
5083d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetErrorIfStepFails(TS ts, PetscBool err)
5084d71ae5a4SJacob Faibussowitsch {
5085cef5090cSJed Brown   PetscFunctionBegin;
5086cef5090cSJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
5087cef5090cSJed Brown   ts->errorifstepfailed = err;
50883ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
5089cef5090cSJed Brown }
5090cef5090cSJed Brown 
509184df9cb4SJed Brown /*@
5092552698daSJed Brown   TSGetAdapt - Get the adaptive controller context for the current method
509384df9cb4SJed Brown 
50948f14a041SBarry Smith   Collective if controller has not yet been created
509584df9cb4SJed Brown 
50964165533cSJose E. Roman   Input Parameter:
5097ed81e22dSJed Brown . ts - time stepping context
509884df9cb4SJed Brown 
50994165533cSJose E. Roman   Output Parameter:
5100ed81e22dSJed Brown . adapt - adaptive controller
510184df9cb4SJed Brown 
510284df9cb4SJed Brown   Level: intermediate
510384df9cb4SJed Brown 
51041cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSAdapt`, `TSAdaptSetType()`, `TSAdaptChoose()`
510584df9cb4SJed Brown @*/
5106d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetAdapt(TS ts, TSAdapt *adapt)
5107d71ae5a4SJacob Faibussowitsch {
510884df9cb4SJed Brown   PetscFunctionBegin;
510984df9cb4SJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
51104f572ea9SToby Isaac   PetscAssertPointer(adapt, 2);
511184df9cb4SJed Brown   if (!ts->adapt) {
51129566063dSJacob Faibussowitsch     PetscCall(TSAdaptCreate(PetscObjectComm((PetscObject)ts), &ts->adapt));
51139566063dSJacob Faibussowitsch     PetscCall(PetscObjectIncrementTabLevel((PetscObject)ts->adapt, (PetscObject)ts, 1));
511484df9cb4SJed Brown   }
5115bec58848SLisandro Dalcin   *adapt = ts->adapt;
51163ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
511784df9cb4SJed Brown }
5118d6ebe24aSShri Abhyankar 
51191c3436cfSJed Brown /*@
5120195e9b02SBarry Smith   TSSetTolerances - Set tolerances for local truncation error when using an adaptive controller
51211c3436cfSJed Brown 
51221c3436cfSJed Brown   Logically Collective
51231c3436cfSJed Brown 
51244165533cSJose E. Roman   Input Parameters:
51251c3436cfSJed Brown + ts    - time integration context
512609cb0f53SBarry Smith . atol  - scalar absolute tolerances
512709cb0f53SBarry Smith . vatol - vector of absolute tolerances or `NULL`, used in preference to `atol` if present
512809cb0f53SBarry Smith . rtol  - scalar relative tolerances
512909cb0f53SBarry Smith - vrtol - vector of relative tolerances or `NULL`, used in preference to `rtol` if present
51301c3436cfSJed Brown 
5131195e9b02SBarry Smith   Options Database Keys:
5132a3cdaa26SBarry Smith + -ts_rtol <rtol> - relative tolerance for local truncation error
513367b8a455SSatish Balay - -ts_atol <atol> - Absolute tolerance for local truncation error
5134a3cdaa26SBarry Smith 
5135bcf0153eSBarry Smith   Level: beginner
5136bcf0153eSBarry Smith 
51373ff766beSShri Abhyankar   Notes:
513809cb0f53SBarry Smith   `PETSC_CURRENT` or `PETSC_DETERMINE` may be used for `atol` or `rtol` to indicate the current value
513909cb0f53SBarry Smith   or the default value from when the object's type was set.
514009cb0f53SBarry Smith 
51413ff766beSShri Abhyankar   With PETSc's implicit schemes for DAE problems, the calculation of the local truncation error
51423ff766beSShri Abhyankar   (LTE) includes both the differential and the algebraic variables. If one wants the LTE to be
51433ff766beSShri Abhyankar   computed only for the differential or the algebraic part then this can be done using the vector of
51443ff766beSShri Abhyankar   tolerances vatol. For example, by setting the tolerance vector with the desired tolerance for the
51453ff766beSShri Abhyankar   differential part and infinity for the algebraic part, the LTE calculation will include only the
51463ff766beSShri Abhyankar   differential variables.
51473ff766beSShri Abhyankar 
514809cb0f53SBarry Smith   Fortran Note:
514909cb0f53SBarry Smith   Use `PETSC_CURRENT_INTEGER` or `PETSC_DETERMINE_INTEGER`.
515009cb0f53SBarry Smith 
51511cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSAdapt`, `TSErrorWeightedNorm()`, `TSGetTolerances()`
51521c3436cfSJed Brown @*/
5153d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetTolerances(TS ts, PetscReal atol, Vec vatol, PetscReal rtol, Vec vrtol)
5154d71ae5a4SJacob Faibussowitsch {
51551c3436cfSJed Brown   PetscFunctionBegin;
515609cb0f53SBarry Smith   if (atol == (PetscReal)PETSC_DETERMINE) {
5157dd460d27SBarry Smith     ts->atol = ts->default_atol;
515809cb0f53SBarry Smith   } else if (atol != (PetscReal)PETSC_CURRENT) {
515909cb0f53SBarry Smith     PetscCheck(atol >= 0.0, PetscObjectComm((PetscObject)ts), PETSC_ERR_ARG_OUTOFRANGE, "Absolute tolerance %g must be non-negative", (double)atol);
516009cb0f53SBarry Smith     ts->atol = atol;
516109cb0f53SBarry Smith   }
516209cb0f53SBarry Smith 
51631c3436cfSJed Brown   if (vatol) {
51649566063dSJacob Faibussowitsch     PetscCall(PetscObjectReference((PetscObject)vatol));
51659566063dSJacob Faibussowitsch     PetscCall(VecDestroy(&ts->vatol));
51661c3436cfSJed Brown     ts->vatol = vatol;
51671c3436cfSJed Brown   }
516809cb0f53SBarry Smith 
516909cb0f53SBarry Smith   if (rtol == (PetscReal)PETSC_DETERMINE) {
5170dd460d27SBarry Smith     ts->rtol = ts->default_rtol;
517109cb0f53SBarry Smith   } else if (rtol != (PetscReal)PETSC_CURRENT) {
517209cb0f53SBarry Smith     PetscCheck(rtol >= 0.0, PetscObjectComm((PetscObject)ts), PETSC_ERR_ARG_OUTOFRANGE, "Relative tolerance %g must be non-negative", (double)rtol);
517309cb0f53SBarry Smith     ts->rtol = rtol;
517409cb0f53SBarry Smith   }
517509cb0f53SBarry Smith 
51761c3436cfSJed Brown   if (vrtol) {
51779566063dSJacob Faibussowitsch     PetscCall(PetscObjectReference((PetscObject)vrtol));
51789566063dSJacob Faibussowitsch     PetscCall(VecDestroy(&ts->vrtol));
51791c3436cfSJed Brown     ts->vrtol = vrtol;
51801c3436cfSJed Brown   }
51813ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
51821c3436cfSJed Brown }
51831c3436cfSJed Brown 
5184c5033834SJed Brown /*@
5185c5033834SJed Brown   TSGetTolerances - Get tolerances for local truncation error when using adaptive controller
5186c5033834SJed Brown 
5187c5033834SJed Brown   Logically Collective
5188c5033834SJed Brown 
51894165533cSJose E. Roman   Input Parameter:
5190c5033834SJed Brown . ts - time integration context
5191c5033834SJed Brown 
51924165533cSJose E. Roman   Output Parameters:
5193195e9b02SBarry Smith + atol  - scalar absolute tolerances, `NULL` to ignore
5194195e9b02SBarry Smith . vatol - vector of absolute tolerances, `NULL` to ignore
5195195e9b02SBarry Smith . rtol  - scalar relative tolerances, `NULL` to ignore
5196195e9b02SBarry Smith - vrtol - vector of relative tolerances, `NULL` to ignore
5197c5033834SJed Brown 
5198c5033834SJed Brown   Level: beginner
5199c5033834SJed Brown 
52001cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSAdapt`, `TSErrorWeightedNorm()`, `TSSetTolerances()`
5201c5033834SJed Brown @*/
5202d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetTolerances(TS ts, PetscReal *atol, Vec *vatol, PetscReal *rtol, Vec *vrtol)
5203d71ae5a4SJacob Faibussowitsch {
5204c5033834SJed Brown   PetscFunctionBegin;
5205c5033834SJed Brown   if (atol) *atol = ts->atol;
5206c5033834SJed Brown   if (vatol) *vatol = ts->vatol;
5207c5033834SJed Brown   if (rtol) *rtol = ts->rtol;
5208c5033834SJed Brown   if (vrtol) *vrtol = ts->vrtol;
52093ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
5210c5033834SJed Brown }
5211c5033834SJed Brown 
52129c6b16b5SShri Abhyankar /*@
52138a175baeSEmil Constantinescu   TSErrorWeightedNorm - compute a weighted norm of the difference between two state vectors based on supplied absolute and relative tolerances
52141c3436cfSJed Brown 
5215c3339decSBarry Smith   Collective
52161c3436cfSJed Brown 
52174165533cSJose E. Roman   Input Parameters:
52181c3436cfSJed Brown + ts        - time stepping context
5219a4868fbcSLisandro Dalcin . U         - state vector, usually ts->vec_sol
5220a4868fbcSLisandro Dalcin . Y         - state vector to be compared to U
5221bcf0153eSBarry Smith - wnormtype - norm type, either `NORM_2` or `NORM_INFINITY`
52227619abb3SShri 
52234165533cSJose E. Roman   Output Parameters:
5224a2b725a8SWilliam Gropp + norm  - weighted norm, a value of 1.0 achieves a balance between absolute and relative tolerances
52258a175baeSEmil Constantinescu . norma - weighted norm, a value of 1.0 means that the error meets the absolute tolerance set by the user
5226a2b725a8SWilliam Gropp - normr - weighted norm, a value of 1.0 means that the error meets the relative tolerance set by the user
5227a4868fbcSLisandro Dalcin 
5228bcf0153eSBarry Smith   Options Database Key:
5229a4868fbcSLisandro Dalcin . -ts_adapt_wnormtype <wnormtype> - 2, INFINITY
5230a4868fbcSLisandro Dalcin 
52311c3436cfSJed Brown   Level: developer
52321c3436cfSJed Brown 
52338c38e02aSSatish Balay .seealso: [](ch_ts), `TS`, `VecErrorWeightedNorms()`, `TSErrorWeightedENorm()`
52341c3436cfSJed Brown @*/
5235d71ae5a4SJacob Faibussowitsch PetscErrorCode TSErrorWeightedNorm(TS ts, Vec U, Vec Y, NormType wnormtype, PetscReal *norm, PetscReal *norma, PetscReal *normr)
5236d71ae5a4SJacob Faibussowitsch {
5237037d63e4SStefano Zampini   PetscInt norma_loc, norm_loc, normr_loc;
52388a175baeSEmil Constantinescu 
52398a175baeSEmil Constantinescu   PetscFunctionBegin;
52408a175baeSEmil Constantinescu   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
5241037d63e4SStefano 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));
5242037d63e4SStefano Zampini   if (wnormtype == NORM_2) {
5243037d63e4SStefano Zampini     if (norm_loc) *norm = PetscSqrtReal(PetscSqr(*norm) / norm_loc);
5244037d63e4SStefano Zampini     if (norma_loc) *norma = PetscSqrtReal(PetscSqr(*norma) / norma_loc);
5245037d63e4SStefano Zampini     if (normr_loc) *normr = PetscSqrtReal(PetscSqr(*normr) / normr_loc);
52468a175baeSEmil Constantinescu   }
52473c633725SBarry Smith   PetscCheck(!PetscIsInfOrNanScalar(*norm), PetscObjectComm((PetscObject)ts), PETSC_ERR_FP, "Infinite or not-a-number generated in norm");
52483c633725SBarry Smith   PetscCheck(!PetscIsInfOrNanScalar(*norma), PetscObjectComm((PetscObject)ts), PETSC_ERR_FP, "Infinite or not-a-number generated in norma");
52493c633725SBarry Smith   PetscCheck(!PetscIsInfOrNanScalar(*normr), PetscObjectComm((PetscObject)ts), PETSC_ERR_FP, "Infinite or not-a-number generated in normr");
52503ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
52518a175baeSEmil Constantinescu }
52528a175baeSEmil Constantinescu 
52538a175baeSEmil Constantinescu /*@
52548a175baeSEmil Constantinescu   TSErrorWeightedENorm - compute a weighted error norm based on supplied absolute and relative tolerances
52558a175baeSEmil Constantinescu 
5256c3339decSBarry Smith   Collective
52578a175baeSEmil Constantinescu 
52584165533cSJose E. Roman   Input Parameters:
52598a175baeSEmil Constantinescu + ts        - time stepping context
52608a175baeSEmil Constantinescu . E         - error vector
52618a175baeSEmil Constantinescu . U         - state vector, usually ts->vec_sol
52628a175baeSEmil Constantinescu . Y         - state vector, previous time step
5263bcf0153eSBarry Smith - wnormtype - norm type, either `NORM_2` or `NORM_INFINITY`
52648a175baeSEmil Constantinescu 
52654165533cSJose E. Roman   Output Parameters:
5266a2b725a8SWilliam Gropp + norm  - weighted norm, a value of 1.0 achieves a balance between absolute and relative tolerances
52678a175baeSEmil Constantinescu . norma - weighted norm, a value of 1.0 means that the error meets the absolute tolerance set by the user
5268a2b725a8SWilliam Gropp - normr - weighted norm, a value of 1.0 means that the error meets the relative tolerance set by the user
52698a175baeSEmil Constantinescu 
5270bcf0153eSBarry Smith   Options Database Key:
52718a175baeSEmil Constantinescu . -ts_adapt_wnormtype <wnormtype> - 2, INFINITY
52728a175baeSEmil Constantinescu 
52738a175baeSEmil Constantinescu   Level: developer
52748a175baeSEmil Constantinescu 
52758c38e02aSSatish Balay .seealso: [](ch_ts), `TS`, `VecErrorWeightedNorms()`, `TSErrorWeightedNorm()`
52768a175baeSEmil Constantinescu @*/
5277d71ae5a4SJacob Faibussowitsch PetscErrorCode TSErrorWeightedENorm(TS ts, Vec E, Vec U, Vec Y, NormType wnormtype, PetscReal *norm, PetscReal *norma, PetscReal *normr)
5278d71ae5a4SJacob Faibussowitsch {
5279037d63e4SStefano Zampini   PetscInt norma_loc, norm_loc, normr_loc;
5280037d63e4SStefano Zampini 
52818a175baeSEmil Constantinescu   PetscFunctionBegin;
5282037d63e4SStefano Zampini   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
5283037d63e4SStefano 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));
5284037d63e4SStefano Zampini   if (wnormtype == NORM_2) {
5285037d63e4SStefano Zampini     if (norm_loc) *norm = PetscSqrtReal(PetscSqr(*norm) / norm_loc);
5286037d63e4SStefano Zampini     if (norma_loc) *norma = PetscSqrtReal(PetscSqr(*norma) / norma_loc);
5287037d63e4SStefano Zampini     if (normr_loc) *normr = PetscSqrtReal(PetscSqr(*normr) / normr_loc);
5288037d63e4SStefano Zampini   }
5289037d63e4SStefano Zampini   PetscCheck(!PetscIsInfOrNanScalar(*norm), PetscObjectComm((PetscObject)ts), PETSC_ERR_FP, "Infinite or not-a-number generated in norm");
5290037d63e4SStefano Zampini   PetscCheck(!PetscIsInfOrNanScalar(*norma), PetscObjectComm((PetscObject)ts), PETSC_ERR_FP, "Infinite or not-a-number generated in norma");
5291037d63e4SStefano Zampini   PetscCheck(!PetscIsInfOrNanScalar(*normr), PetscObjectComm((PetscObject)ts), PETSC_ERR_FP, "Infinite or not-a-number generated in normr");
52923ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
52938a175baeSEmil Constantinescu }
52948a175baeSEmil Constantinescu 
52958d59e960SJed Brown /*@
52968d59e960SJed Brown   TSSetCFLTimeLocal - Set the local CFL constraint relative to forward Euler
52978d59e960SJed Brown 
5298c3339decSBarry Smith   Logically Collective
52998d59e960SJed Brown 
53004165533cSJose E. Roman   Input Parameters:
53018d59e960SJed Brown + ts      - time stepping context
53028d59e960SJed Brown - cfltime - maximum stable time step if using forward Euler (value can be different on each process)
53038d59e960SJed Brown 
53048d59e960SJed Brown   Note:
53058d59e960SJed Brown   After calling this function, the global CFL time can be obtained by calling TSGetCFLTime()
53068d59e960SJed Brown 
53078d59e960SJed Brown   Level: intermediate
53088d59e960SJed Brown 
53091cc06b55SBarry Smith .seealso: [](ch_ts), `TSGetCFLTime()`, `TSADAPTCFL`
53108d59e960SJed Brown @*/
5311d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetCFLTimeLocal(TS ts, PetscReal cfltime)
5312d71ae5a4SJacob Faibussowitsch {
53138d59e960SJed Brown   PetscFunctionBegin;
53148d59e960SJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
53158d59e960SJed Brown   ts->cfltime_local = cfltime;
53168d59e960SJed Brown   ts->cfltime       = -1.;
53173ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
53188d59e960SJed Brown }
53198d59e960SJed Brown 
53208d59e960SJed Brown /*@
53218d59e960SJed Brown   TSGetCFLTime - Get the maximum stable time step according to CFL criteria applied to forward Euler
53228d59e960SJed Brown 
5323c3339decSBarry Smith   Collective
53248d59e960SJed Brown 
53254165533cSJose E. Roman   Input Parameter:
53268d59e960SJed Brown . ts - time stepping context
53278d59e960SJed Brown 
53284165533cSJose E. Roman   Output Parameter:
53298d59e960SJed Brown . cfltime - maximum stable time step for forward Euler
53308d59e960SJed Brown 
53318d59e960SJed Brown   Level: advanced
53328d59e960SJed Brown 
53331cc06b55SBarry Smith .seealso: [](ch_ts), `TSSetCFLTimeLocal()`
53348d59e960SJed Brown @*/
5335d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetCFLTime(TS ts, PetscReal *cfltime)
5336d71ae5a4SJacob Faibussowitsch {
53378d59e960SJed Brown   PetscFunctionBegin;
5338462c564dSBarry Smith   if (ts->cfltime < 0) PetscCallMPI(MPIU_Allreduce(&ts->cfltime_local, &ts->cfltime, 1, MPIU_REAL, MPIU_MIN, PetscObjectComm((PetscObject)ts)));
53398d59e960SJed Brown   *cfltime = ts->cfltime;
53403ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
53418d59e960SJed Brown }
53428d59e960SJed Brown 
5343d6ebe24aSShri Abhyankar /*@
5344d6ebe24aSShri Abhyankar   TSVISetVariableBounds - Sets the lower and upper bounds for the solution vector. xl <= x <= xu
5345d6ebe24aSShri Abhyankar 
5346d6ebe24aSShri Abhyankar   Input Parameters:
5347bcf0153eSBarry Smith + ts - the `TS` context.
5348d6ebe24aSShri Abhyankar . xl - lower bound.
5349a2b725a8SWilliam Gropp - xu - upper bound.
5350d6ebe24aSShri Abhyankar 
53512bd2b0e6SSatish Balay   Level: advanced
53522bd2b0e6SSatish Balay 
5353bcf0153eSBarry Smith   Note:
5354bcf0153eSBarry Smith   If this routine is not called then the lower and upper bounds are set to
5355bcf0153eSBarry Smith   `PETSC_NINFINITY` and `PETSC_INFINITY` respectively during `SNESSetUp()`.
5356bcf0153eSBarry Smith 
53571cc06b55SBarry Smith .seealso: [](ch_ts), `TS`
5358d6ebe24aSShri Abhyankar @*/
5359d71ae5a4SJacob Faibussowitsch PetscErrorCode TSVISetVariableBounds(TS ts, Vec xl, Vec xu)
5360d71ae5a4SJacob Faibussowitsch {
5361d6ebe24aSShri Abhyankar   SNES snes;
5362d6ebe24aSShri Abhyankar 
5363d6ebe24aSShri Abhyankar   PetscFunctionBegin;
53649566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts, &snes));
53659566063dSJacob Faibussowitsch   PetscCall(SNESVISetVariableBounds(snes, xl, xu));
53663ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
5367d6ebe24aSShri Abhyankar }
5368d6ebe24aSShri Abhyankar 
5369f9c1d6abSBarry Smith /*@
5370f9c1d6abSBarry Smith   TSComputeLinearStability - computes the linear stability function at a point
5371f9c1d6abSBarry Smith 
5372c3339decSBarry Smith   Collective
5373f9c1d6abSBarry Smith 
5374f9c1d6abSBarry Smith   Input Parameters:
5375bcf0153eSBarry Smith + ts - the `TS` context
53762fe279fdSBarry Smith . xr - real part of input argument
53772fe279fdSBarry Smith - xi - imaginary part of input argument
5378f9c1d6abSBarry Smith 
5379f9c1d6abSBarry Smith   Output Parameters:
53802fe279fdSBarry Smith + yr - real part of function value
53812fe279fdSBarry Smith - yi - imaginary part of function value
5382f9c1d6abSBarry Smith 
5383f9c1d6abSBarry Smith   Level: developer
5384f9c1d6abSBarry Smith 
53851cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetRHSFunction()`, `TSComputeIFunction()`
5386f9c1d6abSBarry Smith @*/
5387d71ae5a4SJacob Faibussowitsch PetscErrorCode TSComputeLinearStability(TS ts, PetscReal xr, PetscReal xi, PetscReal *yr, PetscReal *yi)
5388d71ae5a4SJacob Faibussowitsch {
5389f9c1d6abSBarry Smith   PetscFunctionBegin;
5390f9c1d6abSBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
5391dbbe0bcdSBarry Smith   PetscUseTypeMethod(ts, linearstability, xr, xi, yr, yi);
53923ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
5393f9c1d6abSBarry Smith }
539424655328SShri 
539524655328SShri /*@
5396dcb233daSLisandro Dalcin   TSRestartStep - Flags the solver to restart the next step
5397dcb233daSLisandro Dalcin 
5398c3339decSBarry Smith   Collective
5399dcb233daSLisandro Dalcin 
5400dcb233daSLisandro Dalcin   Input Parameter:
5401bcf0153eSBarry Smith . ts - the `TS` context obtained from `TSCreate()`
5402dcb233daSLisandro Dalcin 
5403dcb233daSLisandro Dalcin   Level: advanced
5404dcb233daSLisandro Dalcin 
5405dcb233daSLisandro Dalcin   Notes:
5406bcf0153eSBarry Smith   Multistep methods like `TSBDF` or Runge-Kutta methods with FSAL property require restarting the solver in the event of
5407dcb233daSLisandro Dalcin   discontinuities. These discontinuities may be introduced as a consequence of explicitly modifications to the solution
5408dcb233daSLisandro Dalcin   vector (which PETSc attempts to detect and handle) or problem coefficients (which PETSc is not able to detect). For
5409bcf0153eSBarry Smith   the sake of correctness and maximum safety, users are expected to call `TSRestart()` whenever they introduce
5410dcb233daSLisandro Dalcin   discontinuities in callback routines (e.g. prestep and poststep routines, or implicit/rhs function routines with
5411dcb233daSLisandro Dalcin   discontinuous source terms).
5412dcb233daSLisandro Dalcin 
54131cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSBDF`, `TSSolve()`, `TSSetPreStep()`, `TSSetPostStep()`
5414dcb233daSLisandro Dalcin @*/
5415d71ae5a4SJacob Faibussowitsch PetscErrorCode TSRestartStep(TS ts)
5416d71ae5a4SJacob Faibussowitsch {
5417dcb233daSLisandro Dalcin   PetscFunctionBegin;
5418dcb233daSLisandro Dalcin   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
5419dcb233daSLisandro Dalcin   ts->steprestart = PETSC_TRUE;
54203ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
5421dcb233daSLisandro Dalcin }
5422dcb233daSLisandro Dalcin 
5423dcb233daSLisandro Dalcin /*@
542424655328SShri   TSRollBack - Rolls back one time step
542524655328SShri 
5426c3339decSBarry Smith   Collective
542724655328SShri 
542824655328SShri   Input Parameter:
5429bcf0153eSBarry Smith . ts - the `TS` context obtained from `TSCreate()`
543024655328SShri 
543124655328SShri   Level: advanced
543224655328SShri 
54339dc50cb5SStefano Zampini .seealso: [](ch_ts), `TS`, `TSGetStepRollBack()`, `TSCreate()`, `TSSetUp()`, `TSDestroy()`, `TSSolve()`, `TSSetPreStep()`, `TSSetPreStage()`, `TSInterpolate()`
543424655328SShri @*/
5435d71ae5a4SJacob Faibussowitsch PetscErrorCode TSRollBack(TS ts)
5436d71ae5a4SJacob Faibussowitsch {
543724655328SShri   PetscFunctionBegin;
543824655328SShri   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
54393c633725SBarry Smith   PetscCheck(!ts->steprollback, PetscObjectComm((PetscObject)ts), PETSC_ERR_ARG_WRONGSTATE, "TSRollBack already called");
5440c61711c8SStefano Zampini   PetscTryTypeMethod(ts, rollback);
5441c61711c8SStefano Zampini   PetscCall(VecCopy(ts->vec_sol0, ts->vec_sol));
544224655328SShri   ts->time_step  = ts->ptime - ts->ptime_prev;
544324655328SShri   ts->ptime      = ts->ptime_prev;
5444be5899b3SLisandro Dalcin   ts->ptime_prev = ts->ptime_prev_rollback;
54452808aa04SLisandro Dalcin   ts->steps--;
5446b3de5cdeSLisandro Dalcin   ts->steprollback = PETSC_TRUE;
54473ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
544824655328SShri }
5449aeb4809dSShri Abhyankar 
5450ff22ae23SHong Zhang /*@
54519dc50cb5SStefano Zampini   TSGetStepRollBack - Get the internal flag indicating if you are rolling back a step
54529dc50cb5SStefano Zampini 
54539dc50cb5SStefano Zampini   Not collective
54549dc50cb5SStefano Zampini 
54559dc50cb5SStefano Zampini   Input Parameter:
54569dc50cb5SStefano Zampini . ts - the `TS` context obtained from `TSCreate()`
54579dc50cb5SStefano Zampini 
54589dc50cb5SStefano Zampini   Output Parameter:
54599dc50cb5SStefano Zampini . flg - the rollback flag
54609dc50cb5SStefano Zampini 
54619dc50cb5SStefano Zampini   Level: advanced
54629dc50cb5SStefano Zampini 
54639dc50cb5SStefano Zampini .seealso: [](ch_ts), `TS`, `TSCreate()`, `TSRollBack()`
54649dc50cb5SStefano Zampini @*/
54659dc50cb5SStefano Zampini PetscErrorCode TSGetStepRollBack(TS ts, PetscBool *flg)
54669dc50cb5SStefano Zampini {
54679dc50cb5SStefano Zampini   PetscFunctionBegin;
54689dc50cb5SStefano Zampini   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
54699dc50cb5SStefano Zampini   PetscAssertPointer(flg, 2);
54709dc50cb5SStefano Zampini   *flg = ts->steprollback;
54719dc50cb5SStefano Zampini   PetscFunctionReturn(PETSC_SUCCESS);
54729dc50cb5SStefano Zampini }
54739dc50cb5SStefano Zampini 
54749dc50cb5SStefano Zampini /*@
5475c6bf8827SStefano Zampini   TSGetStepResize - Get the internal flag indicating if the current step is after a resize.
5476c6bf8827SStefano Zampini 
5477c6bf8827SStefano Zampini   Not collective
5478c6bf8827SStefano Zampini 
5479c6bf8827SStefano Zampini   Input Parameter:
5480c6bf8827SStefano Zampini . ts - the `TS` context obtained from `TSCreate()`
5481c6bf8827SStefano Zampini 
5482c6bf8827SStefano Zampini   Output Parameter:
5483c6bf8827SStefano Zampini . flg - the resize flag
5484c6bf8827SStefano Zampini 
5485c6bf8827SStefano Zampini   Level: advanced
5486c6bf8827SStefano Zampini 
5487c6bf8827SStefano Zampini .seealso: [](ch_ts), `TS`, `TSCreate()`, `TSSetResize()`
5488c6bf8827SStefano Zampini @*/
5489c6bf8827SStefano Zampini PetscErrorCode TSGetStepResize(TS ts, PetscBool *flg)
5490c6bf8827SStefano Zampini {
5491c6bf8827SStefano Zampini   PetscFunctionBegin;
5492c6bf8827SStefano Zampini   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
5493c6bf8827SStefano Zampini   PetscAssertPointer(flg, 2);
5494c6bf8827SStefano Zampini   *flg = ts->stepresize;
5495c6bf8827SStefano Zampini   PetscFunctionReturn(PETSC_SUCCESS);
5496c6bf8827SStefano Zampini }
5497c6bf8827SStefano Zampini 
5498c6bf8827SStefano Zampini /*@
5499ff22ae23SHong Zhang   TSGetStages - Get the number of stages and stage values
5500ff22ae23SHong Zhang 
5501ff22ae23SHong Zhang   Input Parameter:
5502bcf0153eSBarry Smith . ts - the `TS` context obtained from `TSCreate()`
5503ff22ae23SHong Zhang 
55040429704eSStefano Zampini   Output Parameters:
55050429704eSStefano Zampini + ns - the number of stages
55060429704eSStefano Zampini - Y  - the current stage vectors
55070429704eSStefano Zampini 
5508ff22ae23SHong Zhang   Level: advanced
5509ff22ae23SHong Zhang 
5510bcf0153eSBarry Smith   Note:
5511195e9b02SBarry Smith   Both `ns` and `Y` can be `NULL`.
55120429704eSStefano Zampini 
55131cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSCreate()`
5514ff22ae23SHong Zhang @*/
5515d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetStages(TS ts, PetscInt *ns, Vec **Y)
5516d71ae5a4SJacob Faibussowitsch {
5517ff22ae23SHong Zhang   PetscFunctionBegin;
5518ff22ae23SHong Zhang   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
55194f572ea9SToby Isaac   if (ns) PetscAssertPointer(ns, 2);
55204f572ea9SToby Isaac   if (Y) PetscAssertPointer(Y, 3);
55210429704eSStefano Zampini   if (!ts->ops->getstages) {
55220429704eSStefano Zampini     if (ns) *ns = 0;
55230429704eSStefano Zampini     if (Y) *Y = NULL;
5524dbbe0bcdSBarry Smith   } else PetscUseTypeMethod(ts, getstages, ns, Y);
55253ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
5526ff22ae23SHong Zhang }
5527ff22ae23SHong Zhang 
5528847ff0e1SMatthew G. Knepley /*@C
5529847ff0e1SMatthew G. Knepley   TSComputeIJacobianDefaultColor - Computes the Jacobian using finite differences and coloring to exploit matrix sparsity.
5530847ff0e1SMatthew G. Knepley 
5531c3339decSBarry Smith   Collective
5532847ff0e1SMatthew G. Knepley 
5533847ff0e1SMatthew G. Knepley   Input Parameters:
5534bcf0153eSBarry Smith + ts    - the `TS` context
5535847ff0e1SMatthew G. Knepley . t     - current timestep
5536847ff0e1SMatthew G. Knepley . U     - state vector
5537847ff0e1SMatthew G. Knepley . Udot  - time derivative of state vector
5538847ff0e1SMatthew G. Knepley . shift - shift to apply, see note below
5539847ff0e1SMatthew G. Knepley - ctx   - an optional user context
5540847ff0e1SMatthew G. Knepley 
5541847ff0e1SMatthew G. Knepley   Output Parameters:
5542847ff0e1SMatthew G. Knepley + J - Jacobian matrix (not altered in this routine)
5543195e9b02SBarry Smith - B - newly computed Jacobian matrix to use with preconditioner (generally the same as `J`)
5544847ff0e1SMatthew G. Knepley 
5545847ff0e1SMatthew G. Knepley   Level: intermediate
5546847ff0e1SMatthew G. Knepley 
5547847ff0e1SMatthew G. Knepley   Notes:
5548847ff0e1SMatthew G. Knepley   If F(t,U,Udot)=0 is the DAE, the required Jacobian is
5549847ff0e1SMatthew G. Knepley 
5550847ff0e1SMatthew G. Knepley   dF/dU + shift*dF/dUdot
5551847ff0e1SMatthew G. Knepley 
5552847ff0e1SMatthew G. Knepley   Most users should not need to explicitly call this routine, as it
5553847ff0e1SMatthew G. Knepley   is used internally within the nonlinear solvers.
5554847ff0e1SMatthew G. Knepley 
5555bcf0153eSBarry Smith   This will first try to get the coloring from the `DM`.  If the `DM` type has no coloring
5556847ff0e1SMatthew G. Knepley   routine, then it will try to get the coloring from the matrix.  This requires that the
5557847ff0e1SMatthew G. Knepley   matrix have nonzero entries precomputed.
5558847ff0e1SMatthew G. Knepley 
55591cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetIJacobian()`, `MatFDColoringCreate()`, `MatFDColoringSetFunction()`
5560847ff0e1SMatthew G. Knepley @*/
5561d71ae5a4SJacob Faibussowitsch PetscErrorCode TSComputeIJacobianDefaultColor(TS ts, PetscReal t, Vec U, Vec Udot, PetscReal shift, Mat J, Mat B, void *ctx)
5562d71ae5a4SJacob Faibussowitsch {
5563847ff0e1SMatthew G. Knepley   SNES          snes;
5564847ff0e1SMatthew G. Knepley   MatFDColoring color;
5565847ff0e1SMatthew G. Knepley   PetscBool     hascolor, matcolor = PETSC_FALSE;
5566847ff0e1SMatthew G. Knepley 
5567847ff0e1SMatthew G. Knepley   PetscFunctionBegin;
55689566063dSJacob Faibussowitsch   PetscCall(PetscOptionsGetBool(((PetscObject)ts)->options, ((PetscObject)ts)->prefix, "-ts_fd_color_use_mat", &matcolor, NULL));
55699566063dSJacob Faibussowitsch   PetscCall(PetscObjectQuery((PetscObject)B, "TSMatFDColoring", (PetscObject *)&color));
5570847ff0e1SMatthew G. Knepley   if (!color) {
5571847ff0e1SMatthew G. Knepley     DM         dm;
5572847ff0e1SMatthew G. Knepley     ISColoring iscoloring;
5573847ff0e1SMatthew G. Knepley 
55749566063dSJacob Faibussowitsch     PetscCall(TSGetDM(ts, &dm));
55759566063dSJacob Faibussowitsch     PetscCall(DMHasColoring(dm, &hascolor));
5576847ff0e1SMatthew G. Knepley     if (hascolor && !matcolor) {
55779566063dSJacob Faibussowitsch       PetscCall(DMCreateColoring(dm, IS_COLORING_GLOBAL, &iscoloring));
55789566063dSJacob Faibussowitsch       PetscCall(MatFDColoringCreate(B, iscoloring, &color));
55792ba42892SBarry Smith       PetscCall(MatFDColoringSetFunction(color, (MatFDColoringFn *)SNESTSFormFunction, (void *)ts));
55809566063dSJacob Faibussowitsch       PetscCall(MatFDColoringSetFromOptions(color));
55819566063dSJacob Faibussowitsch       PetscCall(MatFDColoringSetUp(B, iscoloring, color));
55829566063dSJacob Faibussowitsch       PetscCall(ISColoringDestroy(&iscoloring));
5583847ff0e1SMatthew G. Knepley     } else {
5584847ff0e1SMatthew G. Knepley       MatColoring mc;
5585847ff0e1SMatthew G. Knepley 
55869566063dSJacob Faibussowitsch       PetscCall(MatColoringCreate(B, &mc));
55879566063dSJacob Faibussowitsch       PetscCall(MatColoringSetDistance(mc, 2));
55889566063dSJacob Faibussowitsch       PetscCall(MatColoringSetType(mc, MATCOLORINGSL));
55899566063dSJacob Faibussowitsch       PetscCall(MatColoringSetFromOptions(mc));
55909566063dSJacob Faibussowitsch       PetscCall(MatColoringApply(mc, &iscoloring));
55919566063dSJacob Faibussowitsch       PetscCall(MatColoringDestroy(&mc));
55929566063dSJacob Faibussowitsch       PetscCall(MatFDColoringCreate(B, iscoloring, &color));
55932ba42892SBarry Smith       PetscCall(MatFDColoringSetFunction(color, (MatFDColoringFn *)SNESTSFormFunction, (void *)ts));
55949566063dSJacob Faibussowitsch       PetscCall(MatFDColoringSetFromOptions(color));
55959566063dSJacob Faibussowitsch       PetscCall(MatFDColoringSetUp(B, iscoloring, color));
55969566063dSJacob Faibussowitsch       PetscCall(ISColoringDestroy(&iscoloring));
5597847ff0e1SMatthew G. Knepley     }
55989566063dSJacob Faibussowitsch     PetscCall(PetscObjectCompose((PetscObject)B, "TSMatFDColoring", (PetscObject)color));
55999566063dSJacob Faibussowitsch     PetscCall(PetscObjectDereference((PetscObject)color));
5600847ff0e1SMatthew G. Knepley   }
56019566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts, &snes));
56029566063dSJacob Faibussowitsch   PetscCall(MatFDColoringApply(B, color, U, snes));
5603847ff0e1SMatthew G. Knepley   if (J != B) {
56049566063dSJacob Faibussowitsch     PetscCall(MatAssemblyBegin(J, MAT_FINAL_ASSEMBLY));
56059566063dSJacob Faibussowitsch     PetscCall(MatAssemblyEnd(J, MAT_FINAL_ASSEMBLY));
5606847ff0e1SMatthew G. Knepley   }
56073ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
5608847ff0e1SMatthew G. Knepley }
560993b34091SDebojyoti Ghosh 
5610b43aa488SJacob Faibussowitsch /*@C
56116bc98fa9SBarry Smith   TSSetFunctionDomainError - Set a function that tests if the current state vector is valid
5612cb9d8021SPierre Barbier de Reuille 
5613cb9d8021SPierre Barbier de Reuille   Input Parameters:
5614bcf0153eSBarry Smith + ts   - the `TS` context
5615bcf0153eSBarry Smith - func - function called within `TSFunctionDomainError()`
56166bc98fa9SBarry Smith 
561720f4b53cSBarry Smith   Calling sequence of `func`:
56188847d985SBarry Smith + ts     - the `TS` context
56196bc98fa9SBarry Smith . time   - the current time (of the stage)
56206bc98fa9SBarry Smith . state  - the state to check if it is valid
5621a144a63fSStefano Zampini - accept - (output parameter) `PETSC_FALSE` if the state is not acceptable, `PETSC_TRUE` if acceptable
5622cb9d8021SPierre Barbier de Reuille 
5623cb9d8021SPierre Barbier de Reuille   Level: intermediate
5624cb9d8021SPierre Barbier de Reuille 
56256bc98fa9SBarry Smith   Notes:
56266bc98fa9SBarry Smith   If an implicit ODE solver is being used then, in addition to providing this routine, the
5627bcf0153eSBarry Smith   user's code should call `SNESSetFunctionDomainError()` when domain errors occur during
5628bcf0153eSBarry Smith   function evaluations where the functions are provided by `TSSetIFunction()` or `TSSetRHSFunction()`.
5629bcf0153eSBarry Smith   Use `TSGetSNES()` to obtain the `SNES` object
56306bc98fa9SBarry Smith 
5631b43aa488SJacob Faibussowitsch   Developer Notes:
5632bcf0153eSBarry Smith   The naming of this function is inconsistent with the `SNESSetFunctionDomainError()`
56336bc98fa9SBarry Smith   since one takes a function pointer and the other does not.
56346bc98fa9SBarry Smith 
56351cc06b55SBarry Smith .seealso: [](ch_ts), `TSAdaptCheckStage()`, `TSFunctionDomainError()`, `SNESSetFunctionDomainError()`, `TSGetSNES()`
5636cb9d8021SPierre Barbier de Reuille @*/
5637a144a63fSStefano Zampini PetscErrorCode TSSetFunctionDomainError(TS ts, PetscErrorCode (*func)(TS ts, PetscReal time, Vec state, PetscBool *accept))
5638d71ae5a4SJacob Faibussowitsch {
5639cb9d8021SPierre Barbier de Reuille   PetscFunctionBegin;
5640cb9d8021SPierre Barbier de Reuille   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
5641cb9d8021SPierre Barbier de Reuille   ts->functiondomainerror = func;
56423ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
5643cb9d8021SPierre Barbier de Reuille }
5644cb9d8021SPierre Barbier de Reuille 
5645cb9d8021SPierre Barbier de Reuille /*@
56466bc98fa9SBarry Smith   TSFunctionDomainError - Checks if the current state is valid
5647cb9d8021SPierre Barbier de Reuille 
5648cb9d8021SPierre Barbier de Reuille   Input Parameters:
5649bcf0153eSBarry Smith + ts        - the `TS` context
56506bc98fa9SBarry Smith . stagetime - time of the simulation
56516bc98fa9SBarry Smith - Y         - state vector to check.
5652cb9d8021SPierre Barbier de Reuille 
5653cb9d8021SPierre Barbier de Reuille   Output Parameter:
5654bcf0153eSBarry Smith . accept - Set to `PETSC_FALSE` if the current state vector is valid.
565596a0c994SBarry Smith 
56566bc98fa9SBarry Smith   Level: developer
56576bc98fa9SBarry Smith 
5658bcf0153eSBarry Smith   Note:
5659bcf0153eSBarry Smith   This function is called by the `TS` integration routines and calls the user provided function (set with `TSSetFunctionDomainError()`)
5660bcf0153eSBarry Smith   to check if the current state is valid.
5661bcf0153eSBarry Smith 
56621cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetFunctionDomainError()`
5663cb9d8021SPierre Barbier de Reuille @*/
5664d71ae5a4SJacob Faibussowitsch PetscErrorCode TSFunctionDomainError(TS ts, PetscReal stagetime, Vec Y, PetscBool *accept)
5665d71ae5a4SJacob Faibussowitsch {
5666cb9d8021SPierre Barbier de Reuille   PetscFunctionBegin;
5667cb9d8021SPierre Barbier de Reuille   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
5668cb9d8021SPierre Barbier de Reuille   *accept = PETSC_TRUE;
56691e66621cSBarry Smith   if (ts->functiondomainerror) PetscCall((*ts->functiondomainerror)(ts, stagetime, Y, accept));
56703ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
5671cb9d8021SPierre Barbier de Reuille }
56721ceb14c0SBarry Smith 
5673cc4c1da9SBarry Smith /*@
5674195e9b02SBarry Smith   TSClone - This function clones a time step `TS` object.
567593b34091SDebojyoti Ghosh 
5676d083f849SBarry Smith   Collective
567793b34091SDebojyoti Ghosh 
567893b34091SDebojyoti Ghosh   Input Parameter:
5679bcf0153eSBarry Smith . tsin - The input `TS`
568093b34091SDebojyoti Ghosh 
568193b34091SDebojyoti Ghosh   Output Parameter:
5682bcf0153eSBarry Smith . tsout - The output `TS` (cloned)
56835eca1a21SEmil Constantinescu 
56845eca1a21SEmil Constantinescu   Level: developer
568593b34091SDebojyoti Ghosh 
5686bcf0153eSBarry Smith   Notes:
5687bcf0153eSBarry 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.
5688bcf0153eSBarry Smith   It will likely be replaced in the future with a mechanism of switching methods on the fly.
5689bcf0153eSBarry Smith 
5690195e9b02SBarry 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
5691195e9b02SBarry Smith .vb
5692195e9b02SBarry Smith  SNES snes_dup = NULL;
5693195e9b02SBarry Smith  TSGetSNES(ts,&snes_dup);
5694195e9b02SBarry Smith  TSSetSNES(ts,snes_dup);
5695195e9b02SBarry Smith .ve
5696bcf0153eSBarry Smith 
56971cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `SNES`, `TSCreate()`, `TSSetType()`, `TSSetUp()`, `TSDestroy()`, `TSSetProblemType()`
569893b34091SDebojyoti Ghosh @*/
5699d71ae5a4SJacob Faibussowitsch PetscErrorCode TSClone(TS tsin, TS *tsout)
5700d71ae5a4SJacob Faibussowitsch {
570193b34091SDebojyoti Ghosh   TS     t;
5702dc846ba4SSatish Balay   SNES   snes_start;
5703dc846ba4SSatish Balay   DM     dm;
5704dc846ba4SSatish Balay   TSType type;
570593b34091SDebojyoti Ghosh 
570693b34091SDebojyoti Ghosh   PetscFunctionBegin;
57074f572ea9SToby Isaac   PetscAssertPointer(tsin, 1);
570893b34091SDebojyoti Ghosh   *tsout = NULL;
570993b34091SDebojyoti Ghosh 
57109566063dSJacob Faibussowitsch   PetscCall(PetscHeaderCreate(t, TS_CLASSID, "TS", "Time stepping", "TS", PetscObjectComm((PetscObject)tsin), TSDestroy, TSView));
571193b34091SDebojyoti Ghosh 
571293b34091SDebojyoti Ghosh   /* General TS description */
571393b34091SDebojyoti Ghosh   t->numbermonitors    = 0;
571493b34091SDebojyoti Ghosh   t->setupcalled       = 0;
571593b34091SDebojyoti Ghosh   t->ksp_its           = 0;
571693b34091SDebojyoti Ghosh   t->snes_its          = 0;
571793b34091SDebojyoti Ghosh   t->nwork             = 0;
57187d51462cSStefano Zampini   t->rhsjacobian.time  = PETSC_MIN_REAL;
571993b34091SDebojyoti Ghosh   t->rhsjacobian.scale = 1.;
572093b34091SDebojyoti Ghosh   t->ijacobian.shift   = 1.;
572193b34091SDebojyoti Ghosh 
57229566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(tsin, &snes_start));
57239566063dSJacob Faibussowitsch   PetscCall(TSSetSNES(t, snes_start));
5724d15a3a53SEmil Constantinescu 
57259566063dSJacob Faibussowitsch   PetscCall(TSGetDM(tsin, &dm));
57269566063dSJacob Faibussowitsch   PetscCall(TSSetDM(t, dm));
572793b34091SDebojyoti Ghosh 
572893b34091SDebojyoti Ghosh   t->adapt = tsin->adapt;
57299566063dSJacob Faibussowitsch   PetscCall(PetscObjectReference((PetscObject)t->adapt));
573093b34091SDebojyoti Ghosh 
5731e7069c78SShri   t->trajectory = tsin->trajectory;
57329566063dSJacob Faibussowitsch   PetscCall(PetscObjectReference((PetscObject)t->trajectory));
5733e7069c78SShri 
5734e7069c78SShri   t->event = tsin->event;
57356b10a48eSSatish Balay   if (t->event) t->event->refct++;
5736e7069c78SShri 
573793b34091SDebojyoti Ghosh   t->problem_type      = tsin->problem_type;
573893b34091SDebojyoti Ghosh   t->ptime             = tsin->ptime;
5739e7069c78SShri   t->ptime_prev        = tsin->ptime_prev;
574093b34091SDebojyoti Ghosh   t->time_step         = tsin->time_step;
574193b34091SDebojyoti Ghosh   t->max_time          = tsin->max_time;
574293b34091SDebojyoti Ghosh   t->steps             = tsin->steps;
574393b34091SDebojyoti Ghosh   t->max_steps         = tsin->max_steps;
574493b34091SDebojyoti Ghosh   t->equation_type     = tsin->equation_type;
574593b34091SDebojyoti Ghosh   t->atol              = tsin->atol;
574693b34091SDebojyoti Ghosh   t->rtol              = tsin->rtol;
574793b34091SDebojyoti Ghosh   t->max_snes_failures = tsin->max_snes_failures;
574893b34091SDebojyoti Ghosh   t->max_reject        = tsin->max_reject;
574993b34091SDebojyoti Ghosh   t->errorifstepfailed = tsin->errorifstepfailed;
575093b34091SDebojyoti Ghosh 
57519566063dSJacob Faibussowitsch   PetscCall(TSGetType(tsin, &type));
57529566063dSJacob Faibussowitsch   PetscCall(TSSetType(t, type));
575393b34091SDebojyoti Ghosh 
575493b34091SDebojyoti Ghosh   t->vec_sol = NULL;
575593b34091SDebojyoti Ghosh 
575693b34091SDebojyoti Ghosh   t->cfltime          = tsin->cfltime;
575793b34091SDebojyoti Ghosh   t->cfltime_local    = tsin->cfltime_local;
575893b34091SDebojyoti Ghosh   t->exact_final_time = tsin->exact_final_time;
575993b34091SDebojyoti Ghosh 
5760aea10558SJacob Faibussowitsch   t->ops[0] = tsin->ops[0];
576193b34091SDebojyoti Ghosh 
57620d4fed19SBarry Smith   if (((PetscObject)tsin)->fortran_func_pointers) {
57630d4fed19SBarry Smith     PetscInt i;
57649566063dSJacob Faibussowitsch     PetscCall(PetscMalloc((10) * sizeof(void (*)(void)), &((PetscObject)t)->fortran_func_pointers));
5765ad540459SPierre Jolivet     for (i = 0; i < 10; i++) ((PetscObject)t)->fortran_func_pointers[i] = ((PetscObject)tsin)->fortran_func_pointers[i];
57660d4fed19SBarry Smith   }
576793b34091SDebojyoti Ghosh   *tsout = t;
57683ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
576993b34091SDebojyoti Ghosh }
5770f3b1f45cSBarry Smith 
5771d71ae5a4SJacob Faibussowitsch static PetscErrorCode RHSWrapperFunction_TSRHSJacobianTest(void *ctx, Vec x, Vec y)
5772d71ae5a4SJacob Faibussowitsch {
5773f3b1f45cSBarry Smith   TS ts = (TS)ctx;
5774f3b1f45cSBarry Smith 
5775f3b1f45cSBarry Smith   PetscFunctionBegin;
57769566063dSJacob Faibussowitsch   PetscCall(TSComputeRHSFunction(ts, 0, x, y));
57773ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
5778f3b1f45cSBarry Smith }
5779f3b1f45cSBarry Smith 
5780f3b1f45cSBarry Smith /*@
5781bcf0153eSBarry Smith   TSRHSJacobianTest - Compares the multiply routine provided to the `MATSHELL` with differencing on the `TS` given RHS function.
5782f3b1f45cSBarry Smith 
5783c3339decSBarry Smith   Logically Collective
5784f3b1f45cSBarry Smith 
57852fe279fdSBarry Smith   Input Parameter:
5786b43aa488SJacob Faibussowitsch . ts - the time stepping routine
5787f3b1f45cSBarry Smith 
5788f3b1f45cSBarry Smith   Output Parameter:
5789bcf0153eSBarry Smith . flg - `PETSC_TRUE` if the multiply is likely correct
5790f3b1f45cSBarry Smith 
5791bcf0153eSBarry Smith   Options Database Key:
5792f3b1f45cSBarry Smith . -ts_rhs_jacobian_test_mult -mat_shell_test_mult_view - run the test at each timestep of the integrator
5793f3b1f45cSBarry Smith 
5794f3b1f45cSBarry Smith   Level: advanced
5795f3b1f45cSBarry Smith 
5796bcf0153eSBarry Smith   Note:
5797195e9b02SBarry Smith   This only works for problems defined using `TSSetRHSFunction()` and Jacobian NOT `TSSetIFunction()` and Jacobian
5798f3b1f45cSBarry Smith 
57991cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `Mat`, `MATSHELL`, `MatCreateShell()`, `MatShellGetContext()`, `MatShellGetOperation()`, `MatShellTestMultTranspose()`, `TSRHSJacobianTestTranspose()`
5800f3b1f45cSBarry Smith @*/
5801d71ae5a4SJacob Faibussowitsch PetscErrorCode TSRHSJacobianTest(TS ts, PetscBool *flg)
5802d71ae5a4SJacob Faibussowitsch {
5803f3b1f45cSBarry Smith   Mat              J, B;
58048434afd1SBarry Smith   TSRHSJacobianFn *func;
5805f3b1f45cSBarry Smith   void            *ctx;
5806f3b1f45cSBarry Smith 
5807f3b1f45cSBarry Smith   PetscFunctionBegin;
58089566063dSJacob Faibussowitsch   PetscCall(TSGetRHSJacobian(ts, &J, &B, &func, &ctx));
58099566063dSJacob Faibussowitsch   PetscCall((*func)(ts, 0.0, ts->vec_sol, J, B, ctx));
58109566063dSJacob Faibussowitsch   PetscCall(MatShellTestMult(J, RHSWrapperFunction_TSRHSJacobianTest, ts->vec_sol, ts, flg));
58113ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
5812f3b1f45cSBarry Smith }
5813f3b1f45cSBarry Smith 
5814cc4c1da9SBarry Smith /*@
5815bcf0153eSBarry Smith   TSRHSJacobianTestTranspose - Compares the multiply transpose routine provided to the `MATSHELL` with differencing on the `TS` given RHS function.
5816f3b1f45cSBarry Smith 
5817c3339decSBarry Smith   Logically Collective
5818f3b1f45cSBarry Smith 
58192fe279fdSBarry Smith   Input Parameter:
5820b43aa488SJacob Faibussowitsch . ts - the time stepping routine
5821f3b1f45cSBarry Smith 
5822f3b1f45cSBarry Smith   Output Parameter:
5823bcf0153eSBarry Smith . flg - `PETSC_TRUE` if the multiply is likely correct
5824f3b1f45cSBarry Smith 
5825bcf0153eSBarry Smith   Options Database Key:
5826f3b1f45cSBarry Smith . -ts_rhs_jacobian_test_mult_transpose -mat_shell_test_mult_transpose_view - run the test at each timestep of the integrator
5827f3b1f45cSBarry Smith 
5828bcf0153eSBarry Smith   Level: advanced
5829bcf0153eSBarry Smith 
583095452b02SPatrick Sanan   Notes:
5831195e9b02SBarry Smith   This only works for problems defined using `TSSetRHSFunction()` and Jacobian NOT `TSSetIFunction()` and Jacobian
5832f3b1f45cSBarry Smith 
58331cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `Mat`, `MatCreateShell()`, `MatShellGetContext()`, `MatShellGetOperation()`, `MatShellTestMultTranspose()`, `TSRHSJacobianTest()`
5834f3b1f45cSBarry Smith @*/
5835d71ae5a4SJacob Faibussowitsch PetscErrorCode TSRHSJacobianTestTranspose(TS ts, PetscBool *flg)
5836d71ae5a4SJacob Faibussowitsch {
5837f3b1f45cSBarry Smith   Mat              J, B;
5838f3b1f45cSBarry Smith   void            *ctx;
58398434afd1SBarry Smith   TSRHSJacobianFn *func;
5840f3b1f45cSBarry Smith 
5841f3b1f45cSBarry Smith   PetscFunctionBegin;
58429566063dSJacob Faibussowitsch   PetscCall(TSGetRHSJacobian(ts, &J, &B, &func, &ctx));
58439566063dSJacob Faibussowitsch   PetscCall((*func)(ts, 0.0, ts->vec_sol, J, B, ctx));
58449566063dSJacob Faibussowitsch   PetscCall(MatShellTestMultTranspose(J, RHSWrapperFunction_TSRHSJacobianTest, ts->vec_sol, ts, flg));
58453ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
5846f3b1f45cSBarry Smith }
58470fe4d17eSHong Zhang 
58480fe4d17eSHong Zhang /*@
58490fe4d17eSHong Zhang   TSSetUseSplitRHSFunction - Use the split RHSFunction when a multirate method is used.
58500fe4d17eSHong Zhang 
585120f4b53cSBarry Smith   Logically Collective
58520fe4d17eSHong Zhang 
5853d8d19677SJose E. Roman   Input Parameters:
58540fe4d17eSHong Zhang + ts                   - timestepping context
5855bcf0153eSBarry Smith - use_splitrhsfunction - `PETSC_TRUE` indicates that the split RHSFunction will be used
58560fe4d17eSHong Zhang 
5857bcf0153eSBarry Smith   Options Database Key:
58580fe4d17eSHong Zhang . -ts_use_splitrhsfunction - <true,false>
58590fe4d17eSHong Zhang 
58600fe4d17eSHong Zhang   Level: intermediate
58610fe4d17eSHong Zhang 
5862bcf0153eSBarry Smith   Note:
5863195e9b02SBarry Smith   This is only for multirate methods
5864bcf0153eSBarry Smith 
58651cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSGetUseSplitRHSFunction()`
58660fe4d17eSHong Zhang @*/
5867d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetUseSplitRHSFunction(TS ts, PetscBool use_splitrhsfunction)
5868d71ae5a4SJacob Faibussowitsch {
58690fe4d17eSHong Zhang   PetscFunctionBegin;
58700fe4d17eSHong Zhang   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
58710fe4d17eSHong Zhang   ts->use_splitrhsfunction = use_splitrhsfunction;
58723ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
58730fe4d17eSHong Zhang }
58740fe4d17eSHong Zhang 
58750fe4d17eSHong Zhang /*@
58760fe4d17eSHong Zhang   TSGetUseSplitRHSFunction - Gets whether to use the split RHSFunction when a multirate method is used.
58770fe4d17eSHong Zhang 
587820f4b53cSBarry Smith   Not Collective
58790fe4d17eSHong Zhang 
58800fe4d17eSHong Zhang   Input Parameter:
58810fe4d17eSHong Zhang . ts - timestepping context
58820fe4d17eSHong Zhang 
58830fe4d17eSHong Zhang   Output Parameter:
5884bcf0153eSBarry Smith . use_splitrhsfunction - `PETSC_TRUE` indicates that the split RHSFunction will be used
58850fe4d17eSHong Zhang 
58860fe4d17eSHong Zhang   Level: intermediate
58870fe4d17eSHong Zhang 
58881cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetUseSplitRHSFunction()`
58890fe4d17eSHong Zhang @*/
5890d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetUseSplitRHSFunction(TS ts, PetscBool *use_splitrhsfunction)
5891d71ae5a4SJacob Faibussowitsch {
58920fe4d17eSHong Zhang   PetscFunctionBegin;
58930fe4d17eSHong Zhang   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
58940fe4d17eSHong Zhang   *use_splitrhsfunction = ts->use_splitrhsfunction;
58953ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
58960fe4d17eSHong Zhang }
5897d60b7d5cSBarry Smith 
5898d60b7d5cSBarry Smith /*@
5899d60b7d5cSBarry Smith   TSSetMatStructure - sets the relationship between the nonzero structure of the RHS Jacobian matrix to the IJacobian matrix.
5900d60b7d5cSBarry Smith 
5901c3339decSBarry Smith   Logically  Collective
5902d60b7d5cSBarry Smith 
5903d60b7d5cSBarry Smith   Input Parameters:
5904d60b7d5cSBarry Smith + ts  - the time-stepper
5905bcf0153eSBarry Smith - str - the structure (the default is `UNKNOWN_NONZERO_PATTERN`)
5906d60b7d5cSBarry Smith 
5907d60b7d5cSBarry Smith   Level: intermediate
5908d60b7d5cSBarry Smith 
5909bcf0153eSBarry Smith   Note:
5910d60b7d5cSBarry Smith   When the relationship between the nonzero structures is known and supplied the solution process can be much faster
5911d60b7d5cSBarry Smith 
59121cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `MatAXPY()`, `MatStructure`
5913d60b7d5cSBarry Smith  @*/
5914d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetMatStructure(TS ts, MatStructure str)
5915d71ae5a4SJacob Faibussowitsch {
5916d60b7d5cSBarry Smith   PetscFunctionBegin;
5917d60b7d5cSBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
5918d60b7d5cSBarry Smith   ts->axpy_pattern = str;
59193ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
5920d60b7d5cSBarry Smith }
59214a658b32SHong Zhang 
59224a658b32SHong Zhang /*@
59238343f784SJames Wright   TSSetEvaluationTimes - sets the evaluation points. The solution will be computed and stored for each time requested
59244a658b32SHong Zhang 
5925c3339decSBarry Smith   Collective
59264a658b32SHong Zhang 
59274a658b32SHong Zhang   Input Parameters:
59284a658b32SHong Zhang + ts          - the time-stepper
59298343f784SJames Wright . n           - number of the time points
59308343f784SJames Wright - time_points - array of the time points
59314a658b32SHong Zhang 
5932bcf0153eSBarry Smith   Options Database Key:
59338343f784SJames Wright . -ts_eval_times <t0,...tn> - Sets the evaluation times
59344a658b32SHong Zhang 
5935bcf0153eSBarry Smith   Level: intermediate
59364a658b32SHong Zhang 
59374a658b32SHong Zhang   Notes:
59388343f784SJames Wright   The elements in `time_points` must be all increasing. They correspond to the intermediate points for time integration.
59394a658b32SHong Zhang 
59408343f784SJames Wright   `TS_EXACTFINALTIME_MATCHSTEP` must be used to make the last time step in each sub-interval match the intermediate points specified.
59418343f784SJames Wright 
5942c80d56d9SJames Wright   The intermediate solutions are saved in a vector array that can be accessed with `TSGetEvaluationSolutions()`. Thus using evaluation times may
59438343f784SJames Wright   pressure the memory system when using a large number of time points.
59448343f784SJames Wright 
5945c80d56d9SJames Wright .seealso: [](ch_ts), `TS`, `TSGetEvaluationTimes()`, `TSGetEvaluationSolutions()`, `TSSetTimeSpan()`
59464a658b32SHong Zhang  @*/
59478343f784SJames Wright PetscErrorCode TSSetEvaluationTimes(TS ts, PetscInt n, PetscReal *time_points)
5948d71ae5a4SJacob Faibussowitsch {
59498343f784SJames Wright   PetscBool is_sorted;
59508343f784SJames Wright 
59514a658b32SHong Zhang   PetscFunctionBegin;
59524a658b32SHong Zhang   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
5953136cf249SJames Wright   if (ts->eval_times && n != ts->eval_times->num_time_points) {
5954136cf249SJames Wright     PetscCall(PetscFree(ts->eval_times->time_points));
5955136cf249SJames Wright     PetscCall(VecDestroyVecs(ts->eval_times->num_time_points, &ts->eval_times->sol_vecs));
5956136cf249SJames Wright     PetscCall(PetscMalloc1(n, &ts->eval_times->time_points));
59574a658b32SHong Zhang   }
5958136cf249SJames Wright   if (!ts->eval_times) {
5959136cf249SJames Wright     TSEvaluationTimes eval_times;
5960136cf249SJames Wright     PetscCall(PetscNew(&eval_times));
5961136cf249SJames Wright     PetscCall(PetscMalloc1(n, &eval_times->time_points));
5962136cf249SJames Wright     eval_times->reltol  = 1e-6;
5963136cf249SJames Wright     eval_times->abstol  = 10 * PETSC_MACHINE_EPSILON;
5964136cf249SJames Wright     eval_times->worktol = 0;
5965136cf249SJames Wright     ts->eval_times      = eval_times;
59664a658b32SHong Zhang   }
5967136cf249SJames Wright   ts->eval_times->num_time_points = n;
59688343f784SJames Wright   PetscCall(PetscSortedReal(n, time_points, &is_sorted));
59698343f784SJames Wright   PetscCheck(is_sorted, PetscObjectComm((PetscObject)ts), PETSC_ERR_ARG_WRONG, "time_points array must be sorted");
5970136cf249SJames Wright   PetscCall(PetscArraycpy(ts->eval_times->time_points, time_points, n));
59718343f784SJames Wright   PetscFunctionReturn(PETSC_SUCCESS);
59728343f784SJames Wright }
59738343f784SJames Wright 
59748343f784SJames Wright /*@C
59758343f784SJames Wright   TSGetEvaluationTimes - gets the evaluation times set with `TSSetEvaluationTimes()`
59768343f784SJames Wright 
59778343f784SJames Wright   Not Collective
59788343f784SJames Wright 
59798343f784SJames Wright   Input Parameter:
59808343f784SJames Wright . ts - the time-stepper
59818343f784SJames Wright 
59828343f784SJames Wright   Output Parameters:
59838343f784SJames Wright + n           - number of the time points
59848343f784SJames Wright - time_points - array of the time points
59858343f784SJames Wright 
59868343f784SJames Wright   Level: beginner
59878343f784SJames Wright 
59888343f784SJames Wright   Note:
59898343f784SJames Wright   The values obtained are valid until the `TS` object is destroyed.
59908343f784SJames Wright 
59918343f784SJames Wright   Both `n` and `time_points` can be `NULL`.
59928343f784SJames Wright 
59938343f784SJames Wright   Also used to see time points set by `TSSetTimeSpan()`.
59948343f784SJames Wright 
5995c80d56d9SJames Wright .seealso: [](ch_ts), `TS`, `TSSetEvaluationTimes()`, `TSGetEvaluationSolutions()`
59968343f784SJames Wright  @*/
59978343f784SJames Wright PetscErrorCode TSGetEvaluationTimes(TS ts, PetscInt *n, const PetscReal *time_points[])
59988343f784SJames Wright {
59998343f784SJames Wright   PetscFunctionBegin;
60008343f784SJames Wright   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
60018343f784SJames Wright   if (n) PetscAssertPointer(n, 2);
60028343f784SJames Wright   if (time_points) PetscAssertPointer(time_points, 3);
6003136cf249SJames Wright   if (!ts->eval_times) {
60048343f784SJames Wright     if (n) *n = 0;
60058343f784SJames Wright     if (time_points) *time_points = NULL;
60068343f784SJames Wright   } else {
6007136cf249SJames Wright     if (n) *n = ts->eval_times->num_time_points;
6008136cf249SJames Wright     if (time_points) *time_points = ts->eval_times->time_points;
60098343f784SJames Wright   }
60108343f784SJames Wright   PetscFunctionReturn(PETSC_SUCCESS);
60118343f784SJames Wright }
60128343f784SJames Wright 
60138343f784SJames Wright /*@C
6014c80d56d9SJames Wright   TSGetEvaluationSolutions - Get the number of solutions and the solutions at the evaluation time points specified
60158343f784SJames Wright 
60168343f784SJames Wright   Input Parameter:
60178343f784SJames Wright . ts - the `TS` context obtained from `TSCreate()`
60188343f784SJames Wright 
60198343f784SJames Wright   Output Parameters:
60208343f784SJames Wright + nsol      - the number of solutions
60218343f784SJames Wright . sol_times - array of solution times corresponding to the solution vectors. See note below
60228343f784SJames Wright - Sols      - the solution vectors
60238343f784SJames Wright 
60248343f784SJames Wright   Level: intermediate
60258343f784SJames Wright 
60268343f784SJames Wright   Notes:
60278343f784SJames Wright   Both `nsol` and `Sols` can be `NULL`.
60288343f784SJames Wright 
60298343f784SJames 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()`.
60308343f784SJames Wright   For example, manipulating the step size, especially with a reduced precision, may cause `TS` to step over certain evaluation times.
60318343f784SJames Wright 
60328343f784SJames Wright   Also used to see view solutions requested by `TSSetTimeSpan()`.
60338343f784SJames Wright 
60348343f784SJames Wright .seealso: [](ch_ts), `TS`, `TSSetEvaluationTimes()`, `TSGetEvaluationTimes()`
60358343f784SJames Wright @*/
6036c80d56d9SJames Wright PetscErrorCode TSGetEvaluationSolutions(TS ts, PetscInt *nsol, const PetscReal *sol_times[], Vec **Sols)
60378343f784SJames Wright {
60388343f784SJames Wright   PetscFunctionBegin;
60398343f784SJames Wright   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
60408343f784SJames Wright   if (nsol) PetscAssertPointer(nsol, 2);
60418343f784SJames Wright   if (sol_times) PetscAssertPointer(sol_times, 3);
60428343f784SJames Wright   if (Sols) PetscAssertPointer(Sols, 4);
6043136cf249SJames Wright   if (!ts->eval_times) {
60448343f784SJames Wright     if (nsol) *nsol = 0;
60458343f784SJames Wright     if (sol_times) *sol_times = NULL;
60468343f784SJames Wright     if (Sols) *Sols = NULL;
60478343f784SJames Wright   } else {
6048136cf249SJames Wright     if (nsol) *nsol = ts->eval_times->sol_ctr;
6049136cf249SJames Wright     if (sol_times) *sol_times = ts->eval_times->sol_times;
6050136cf249SJames Wright     if (Sols) *Sols = ts->eval_times->sol_vecs;
60518343f784SJames Wright   }
60528343f784SJames Wright   PetscFunctionReturn(PETSC_SUCCESS);
60538343f784SJames Wright }
60548343f784SJames Wright 
60558343f784SJames Wright /*@
60568343f784SJames Wright   TSSetTimeSpan - sets the time span. The solution will be computed and stored for each time requested in the span
60578343f784SJames Wright 
60588343f784SJames Wright   Collective
60598343f784SJames Wright 
60608343f784SJames Wright   Input Parameters:
60618343f784SJames Wright + ts         - the time-stepper
60628343f784SJames Wright . n          - number of the time points (>=2)
60638343f784SJames Wright - span_times - array of the time points. The first element and the last element are the initial time and the final time respectively.
60648343f784SJames Wright 
60658343f784SJames Wright   Options Database Key:
60668343f784SJames Wright . -ts_time_span <t0,...tf> - Sets the time span
60678343f784SJames Wright 
60688343f784SJames Wright   Level: intermediate
60698343f784SJames Wright 
60708343f784SJames Wright   Notes:
6071c80d56d9SJames 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.
60728343f784SJames Wright 
60738343f784SJames Wright   The elements in tspan must be all increasing. They correspond to the intermediate points for time integration.
60748343f784SJames Wright 
60758343f784SJames Wright   `TS_EXACTFINALTIME_MATCHSTEP` must be used to make the last time step in each sub-interval match the intermediate points specified.
60768343f784SJames Wright 
6077c80d56d9SJames Wright   The intermediate solutions are saved in a vector array that can be accessed with `TSGetEvaluationSolutions()`. Thus using time span may
60788343f784SJames Wright   pressure the memory system when using a large number of span points.
60798343f784SJames Wright 
6080c80d56d9SJames Wright .seealso: [](ch_ts), `TS`, `TSSetEvaluationTimes()`, `TSGetEvaluationTimes()`, `TSGetEvaluationSolutions()`
60818343f784SJames Wright  @*/
60828343f784SJames Wright PetscErrorCode TSSetTimeSpan(TS ts, PetscInt n, PetscReal *span_times)
60838343f784SJames Wright {
60848343f784SJames Wright   PetscFunctionBegin;
60858343f784SJames Wright   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
60868343f784SJames Wright   PetscCheck(n >= 2, PetscObjectComm((PetscObject)ts), PETSC_ERR_ARG_WRONG, "Minimum time span size is 2 but %" PetscInt_FMT " is provided", n);
60878343f784SJames Wright   PetscCall(TSSetEvaluationTimes(ts, n, span_times));
60888343f784SJames Wright   PetscCall(TSSetTime(ts, span_times[0]));
60898343f784SJames Wright   PetscCall(TSSetMaxTime(ts, span_times[n - 1]));
60903ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
60914a658b32SHong Zhang }
60924a658b32SHong Zhang 
6093cc4c1da9SBarry Smith /*@
60947b2dc123SHong Zhang   TSPruneIJacobianColor - Remove nondiagonal zeros in the Jacobian matrix and update the `MatMFFD` coloring information.
6095d7cfae9bSHong Zhang 
6096195e9b02SBarry Smith   Collective
6097d7cfae9bSHong Zhang 
6098d7cfae9bSHong Zhang   Input Parameters:
6099195e9b02SBarry Smith + ts - the `TS` context
6100d7cfae9bSHong Zhang . J  - Jacobian matrix (not altered in this routine)
6101195e9b02SBarry Smith - B  - newly computed Jacobian matrix to use with preconditioner
6102d7cfae9bSHong Zhang 
6103d7cfae9bSHong Zhang   Level: intermediate
6104d7cfae9bSHong Zhang 
6105d7cfae9bSHong Zhang   Notes:
6106195e9b02SBarry Smith   This function improves the `MatFDColoring` performance when the Jacobian matrix was over-allocated or contains
6107195e9b02SBarry Smith   many constant zeros entries, which is typically the case when the matrix is generated by a `DM`
6108d7cfae9bSHong Zhang   and multiple fields are involved.
6109d7cfae9bSHong Zhang 
6110d7cfae9bSHong Zhang   Users need to make sure that the Jacobian matrix is properly filled to reflect the sparsity
6111195e9b02SBarry Smith   structure. For `MatFDColoring`, the values of nonzero entries are not important. So one can
61127b2dc123SHong Zhang   usually call `TSComputeIJacobian()` with randomized input vectors to generate a dummy Jacobian.
61137b2dc123SHong Zhang   `TSComputeIJacobian()` should be called before `TSSolve()` but after `TSSetUp()`.
6114d7cfae9bSHong Zhang 
61151cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `MatFDColoring`, `TSComputeIJacobianDefaultColor()`, `MatEliminateZeros()`, `MatFDColoringCreate()`, `MatFDColoringSetFunction()`
6116d7cfae9bSHong Zhang @*/
6117d7cfae9bSHong Zhang PetscErrorCode TSPruneIJacobianColor(TS ts, Mat J, Mat B)
6118d7cfae9bSHong Zhang {
6119d7cfae9bSHong Zhang   MatColoring   mc            = NULL;
6120d7cfae9bSHong Zhang   ISColoring    iscoloring    = NULL;
6121d7cfae9bSHong Zhang   MatFDColoring matfdcoloring = NULL;
6122d7cfae9bSHong Zhang 
6123d7cfae9bSHong Zhang   PetscFunctionBegin;
6124d7cfae9bSHong Zhang   /* Generate new coloring after eliminating zeros in the matrix */
612558c11ad4SPierre Jolivet   PetscCall(MatEliminateZeros(B, PETSC_TRUE));
6126d7cfae9bSHong Zhang   PetscCall(MatColoringCreate(B, &mc));
6127d7cfae9bSHong Zhang   PetscCall(MatColoringSetDistance(mc, 2));
6128d7cfae9bSHong Zhang   PetscCall(MatColoringSetType(mc, MATCOLORINGSL));
6129d7cfae9bSHong Zhang   PetscCall(MatColoringSetFromOptions(mc));
6130d7cfae9bSHong Zhang   PetscCall(MatColoringApply(mc, &iscoloring));
6131d7cfae9bSHong Zhang   PetscCall(MatColoringDestroy(&mc));
6132d7cfae9bSHong Zhang   /* Replace the old coloring with the new one */
6133d7cfae9bSHong Zhang   PetscCall(MatFDColoringCreate(B, iscoloring, &matfdcoloring));
61342ba42892SBarry Smith   PetscCall(MatFDColoringSetFunction(matfdcoloring, (MatFDColoringFn *)SNESTSFormFunction, (void *)ts));
6135d7cfae9bSHong Zhang   PetscCall(MatFDColoringSetFromOptions(matfdcoloring));
6136d7cfae9bSHong Zhang   PetscCall(MatFDColoringSetUp(B, iscoloring, matfdcoloring));
6137d7cfae9bSHong Zhang   PetscCall(PetscObjectCompose((PetscObject)B, "TSMatFDColoring", (PetscObject)matfdcoloring));
6138d7cfae9bSHong Zhang   PetscCall(PetscObjectDereference((PetscObject)matfdcoloring));
6139d7cfae9bSHong Zhang   PetscCall(ISColoringDestroy(&iscoloring));
61403ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
6141d7cfae9bSHong Zhang }
6142