xref: /petsc/src/ts/interface/ts.c (revision d71ae5a4db6382e7f06317b8d368875286fe9008)
1af0996ceSBarry Smith #include <petsc/private/tsimpl.h> /*I "petscts.h"  I*/
2496e6a7aSJed Brown #include <petscdmshell.h>
31e25c274SJed Brown #include <petscdmda.h>
42d5ee99bSBarry Smith #include <petscviewer.h>
52d5ee99bSBarry Smith #include <petscdraw.h>
6900f6b5bSMatthew G. Knepley #include <petscconvest.h>
7d763cef2SBarry Smith 
89371c9d4SSatish Balay #define SkipSmallValue(a, b, tol) \
99371c9d4SSatish Balay   if (PetscAbsScalar(a) < tol || PetscAbsScalar(b) < tol) continue;
101c167fc2SEmil Constantinescu 
11d5ba7fb7SMatthew Knepley /* Logging support */
12d74926cbSBarry Smith PetscClassId  TS_CLASSID, DMTS_CLASSID;
13a05bf03eSHong Zhang PetscLogEvent TS_Step, TS_PseudoComputeTimeStep, TS_FunctionEval, TS_JacobianEval;
14d405a339SMatthew Knepley 
15c793f718SLisandro Dalcin const char *const TSExactFinalTimeOptions[] = {"UNSPECIFIED", "STEPOVER", "INTERPOLATE", "MATCHSTEP", "TSExactFinalTimeOption", "TS_EXACTFINALTIME_", NULL};
1649354f04SShri Abhyankar 
17*d71ae5a4SJacob Faibussowitsch static PetscErrorCode TSAdaptSetDefaultType(TSAdapt adapt, TSAdaptType default_type)
18*d71ae5a4SJacob Faibussowitsch {
192ffb9264SLisandro Dalcin   PetscFunctionBegin;
20b92453a8SLisandro Dalcin   PetscValidHeaderSpecific(adapt, TSADAPT_CLASSID, 1);
21b92453a8SLisandro Dalcin   PetscValidCharPointer(default_type, 2);
221e66621cSBarry Smith   if (!((PetscObject)adapt)->type_name) PetscCall(TSAdaptSetType(adapt, default_type));
232ffb9264SLisandro Dalcin   PetscFunctionReturn(0);
242ffb9264SLisandro Dalcin }
252ffb9264SLisandro Dalcin 
26bdad233fSMatthew Knepley /*@
27bdad233fSMatthew Knepley    TSSetFromOptions - Sets various TS parameters from user options.
28bdad233fSMatthew Knepley 
29bdad233fSMatthew Knepley    Collective on TS
30bdad233fSMatthew Knepley 
31bdad233fSMatthew Knepley    Input Parameter:
32bdad233fSMatthew Knepley .  ts - the TS context obtained from TSCreate()
33bdad233fSMatthew Knepley 
34bdad233fSMatthew Knepley    Options Database Keys:
35d2567f34SHong Zhang +  -ts_type <type> - TSEULER, TSBEULER, TSSUNDIALS, TSPSEUDO, TSCN, TSRK, TSTHETA, TSALPHA, TSGLLE, TSSSP, TSGLEE, TSBSYMP, TSIRK
36ef222394SBarry Smith .  -ts_save_trajectory - checkpoint the solution at each time-step
37ef85077eSLisandro Dalcin .  -ts_max_time <time> - maximum time to compute to
384a658b32SHong Zhang .  -ts_time_span <t0,...tf> - sets the time span, solutions are computed and stored for each indicated time
39ef85077eSLisandro Dalcin .  -ts_max_steps <steps> - maximum number of time-steps to take
40ef85077eSLisandro Dalcin .  -ts_init_time <time> - initial time to start computation
414dc72f7fSBarry Smith .  -ts_final_time <time> - final time to compute to (deprecated: use -ts_max_time)
423e4cdcaaSBarry Smith .  -ts_dt <dt> - initial time step
431628793fSSatish 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
44a3cdaa26SBarry Smith .  -ts_max_snes_failures <maxfailures> - Maximum number of nonlinear solve failures allowed
45a3cdaa26SBarry Smith .  -ts_max_reject <maxrejects> - Maximum number of step rejections before step fails
46a3cdaa26SBarry Smith .  -ts_error_if_step_fails <true,false> - Error if no step succeeds
47a3cdaa26SBarry Smith .  -ts_rtol <rtol> - relative tolerance for local truncation error
4867b8a455SSatish Balay .  -ts_atol <atol> - Absolute tolerance for local truncation error
49f3b1f45cSBarry Smith .  -ts_rhs_jacobian_test_mult -mat_shell_test_mult_view - test the Jacobian at each iteration against finite difference with RHS function
50f3b1f45cSBarry Smith .  -ts_rhs_jacobian_test_mult_transpose -mat_shell_test_mult_transpose_view - test the Jacobian at each iteration against finite difference with RHS function
5167b8a455SSatish Balay .  -ts_adjoint_solve <yes,no> - After solving the ODE/DAE solve the adjoint problem (requires -ts_save_trajectory)
52847ff0e1SMatthew G. Knepley .  -ts_fd_color - Use finite differences with coloring to compute IJacobian
53bdad233fSMatthew Knepley .  -ts_monitor - print information at each timestep
54aee7a9fbSMatthew G. Knepley .  -ts_monitor_cancel - Cancel all monitors
55de06c3feSJed Brown .  -ts_monitor_lg_solution - Monitor solution graphically
56de06c3feSJed Brown .  -ts_monitor_lg_error - Monitor error graphically
577cf37e64SBarry Smith .  -ts_monitor_error - Monitors norm of error
586934998bSLisandro Dalcin .  -ts_monitor_lg_timestep - Monitor timestep size graphically
598b668821SLisandro Dalcin .  -ts_monitor_lg_timestep_log - Monitor log timestep size graphically
60de06c3feSJed Brown .  -ts_monitor_lg_snes_iterations - Monitor number nonlinear iterations for each timestep graphically
61de06c3feSJed Brown .  -ts_monitor_lg_ksp_iterations - Monitor number nonlinear iterations for each timestep graphically
62de06c3feSJed Brown .  -ts_monitor_sp_eig - Monitor eigenvalues of linearized operator graphically
63de06c3feSJed Brown .  -ts_monitor_draw_solution - Monitor solution graphically
643e4cdcaaSBarry Smith .  -ts_monitor_draw_solution_phase  <xleft,yleft,xright,yright> - Monitor solution graphically with phase diagram, requires problem with exactly 2 degrees of freedom
653e4cdcaaSBarry Smith .  -ts_monitor_draw_error - Monitor error graphically, requires use to have provided TSSetSolutionFunction()
66fde5950dSBarry Smith .  -ts_monitor_solution [ascii binary draw][:filename][:viewerformat] - monitors the solution at each timestep
6763a3b9bcSJacob Faibussowitsch .  -ts_monitor_solution_vtk <filename.vts,filename.vtu> - Save each time step to a binary file, use filename-%%03" PetscInt_FMT ".vts (filename-%%03" PetscInt_FMT ".vtu)
689e336e28SPatrick Sanan -  -ts_monitor_envelope - determine maximum and minimum value of each component of the solution over the solution time
6953ea634cSHong Zhang 
703d5a8a6aSBarry Smith    Notes:
713d5a8a6aSBarry Smith      See SNESSetFromOptions() and KSPSetFromOptions() for how to control the nonlinear and linear solves used by the time-stepper.
723d5a8a6aSBarry Smith 
733d5a8a6aSBarry Smith      Certain SNES options get reset for each new nonlinear solver, for example -snes_lag_jacobian <its> and -snes_lag_preconditioner <its>, in order
743d5a8a6aSBarry Smith      to retain them over the multiple nonlinear solves that TS uses you mush also provide -snes_lag_jacobian_persists true and
753d5a8a6aSBarry Smith      -snes_lag_preconditioner_persists true
763d5a8a6aSBarry Smith 
779e336e28SPatrick Sanan    Developer Note:
789e336e28SPatrick Sanan      We should unify all the -ts_monitor options in the way that -xxx_view has been unified
79bdad233fSMatthew Knepley 
80bdad233fSMatthew Knepley    Level: beginner
81bdad233fSMatthew Knepley 
82db781477SPatrick Sanan .seealso: `TSGetType()`
83bdad233fSMatthew Knepley @*/
84*d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetFromOptions(TS ts)
85*d71ae5a4SJacob Faibussowitsch {
86bc952696SBarry Smith   PetscBool              opt, flg, tflg;
87eabae89aSBarry Smith   char                   monfilename[PETSC_MAX_PATH_LEN];
884a658b32SHong Zhang   PetscReal              time_step, tspan[100];
894a658b32SHong Zhang   PetscInt               nt = PETSC_STATIC_ARRAY_LENGTH(tspan);
9049354f04SShri Abhyankar   TSExactFinalTimeOption eftopt;
91d1212d36SBarry Smith   char                   dir[16];
92cd11d68dSLisandro Dalcin   TSIFunction            ifun;
936991f827SBarry Smith   const char            *defaultType;
946991f827SBarry Smith   char                   typeName[256];
95bdad233fSMatthew Knepley 
96bdad233fSMatthew Knepley   PetscFunctionBegin;
970700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
986991f827SBarry Smith 
999566063dSJacob Faibussowitsch   PetscCall(TSRegisterAll());
1009566063dSJacob Faibussowitsch   PetscCall(TSGetIFunction(ts, NULL, &ifun, NULL));
101cd11d68dSLisandro Dalcin 
102d0609cedSBarry Smith   PetscObjectOptionsBegin((PetscObject)ts);
1031ef27442SStefano Zampini   if (((PetscObject)ts)->type_name) defaultType = ((PetscObject)ts)->type_name;
1041ef27442SStefano Zampini   else defaultType = ifun ? TSBEULER : TSEULER;
1059566063dSJacob Faibussowitsch   PetscCall(PetscOptionsFList("-ts_type", "TS method", "TSSetType", TSList, defaultType, typeName, 256, &opt));
1061e66621cSBarry Smith   if (opt) PetscCall(TSSetType(ts, typeName));
1071e66621cSBarry Smith   else PetscCall(TSSetType(ts, defaultType));
108bdad233fSMatthew Knepley 
109bdad233fSMatthew Knepley   /* Handle generic TS options */
1109566063dSJacob Faibussowitsch   PetscCall(PetscOptionsDeprecated("-ts_final_time", "-ts_max_time", "3.10", NULL));
1119566063dSJacob Faibussowitsch   PetscCall(PetscOptionsReal("-ts_max_time", "Maximum time to run to", "TSSetMaxTime", ts->max_time, &ts->max_time, NULL));
1124a658b32SHong Zhang   PetscCall(PetscOptionsRealArray("-ts_time_span", "Time span", "TSSetTimeSpan", tspan, &nt, &flg));
1134a658b32SHong Zhang   if (flg) PetscCall(TSSetTimeSpan(ts, nt, tspan));
1149566063dSJacob Faibussowitsch   PetscCall(PetscOptionsInt("-ts_max_steps", "Maximum number of time steps", "TSSetMaxSteps", ts->max_steps, &ts->max_steps, NULL));
1159566063dSJacob Faibussowitsch   PetscCall(PetscOptionsReal("-ts_init_time", "Initial time", "TSSetTime", ts->ptime, &ts->ptime, NULL));
1169566063dSJacob Faibussowitsch   PetscCall(PetscOptionsReal("-ts_dt", "Initial time step", "TSSetTimeStep", ts->time_step, &time_step, &flg));
1179566063dSJacob Faibussowitsch   if (flg) PetscCall(TSSetTimeStep(ts, time_step));
1189566063dSJacob Faibussowitsch   PetscCall(PetscOptionsEnum("-ts_exact_final_time", "Option for handling of final time step", "TSSetExactFinalTime", TSExactFinalTimeOptions, (PetscEnum)ts->exact_final_time, (PetscEnum *)&eftopt, &flg));
1199566063dSJacob Faibussowitsch   if (flg) PetscCall(TSSetExactFinalTime(ts, eftopt));
1209566063dSJacob Faibussowitsch   PetscCall(PetscOptionsInt("-ts_max_snes_failures", "Maximum number of nonlinear solve failures", "TSSetMaxSNESFailures", ts->max_snes_failures, &ts->max_snes_failures, NULL));
1219566063dSJacob Faibussowitsch   PetscCall(PetscOptionsInt("-ts_max_reject", "Maximum number of step rejections before step fails", "TSSetMaxStepRejections", ts->max_reject, &ts->max_reject, NULL));
1229566063dSJacob Faibussowitsch   PetscCall(PetscOptionsBool("-ts_error_if_step_fails", "Error if no step succeeds", "TSSetErrorIfStepFails", ts->errorifstepfailed, &ts->errorifstepfailed, NULL));
1239566063dSJacob Faibussowitsch   PetscCall(PetscOptionsReal("-ts_rtol", "Relative tolerance for local truncation error", "TSSetTolerances", ts->rtol, &ts->rtol, NULL));
1249566063dSJacob Faibussowitsch   PetscCall(PetscOptionsReal("-ts_atol", "Absolute tolerance for local truncation error", "TSSetTolerances", ts->atol, &ts->atol, NULL));
125bdad233fSMatthew Knepley 
1269566063dSJacob Faibussowitsch   PetscCall(PetscOptionsBool("-ts_rhs_jacobian_test_mult", "Test the RHS Jacobian for consistency with RHS at each solve ", "None", ts->testjacobian, &ts->testjacobian, NULL));
1279566063dSJacob Faibussowitsch   PetscCall(PetscOptionsBool("-ts_rhs_jacobian_test_mult_transpose", "Test the RHS Jacobian transpose for consistency with RHS at each solve ", "None", ts->testjacobiantranspose, &ts->testjacobiantranspose, NULL));
1289566063dSJacob Faibussowitsch   PetscCall(PetscOptionsBool("-ts_use_splitrhsfunction", "Use the split RHS function for multirate solvers ", "TSSetUseSplitRHSFunction", ts->use_splitrhsfunction, &ts->use_splitrhsfunction, NULL));
12956f85f32SBarry Smith #if defined(PETSC_HAVE_SAWS)
13056f85f32SBarry Smith   {
13156f85f32SBarry Smith     PetscBool set;
13256f85f32SBarry Smith     flg = PETSC_FALSE;
1339566063dSJacob Faibussowitsch     PetscCall(PetscOptionsBool("-ts_saws_block", "Block for SAWs memory snooper at end of TSSolve", "PetscObjectSAWsBlock", ((PetscObject)ts)->amspublishblock, &flg, &set));
1341baa6e33SBarry Smith     if (set) PetscCall(PetscObjectSAWsSetBlock((PetscObject)ts, flg));
13556f85f32SBarry Smith   }
13656f85f32SBarry Smith #endif
13756f85f32SBarry Smith 
138bdad233fSMatthew Knepley   /* Monitor options */
1399566063dSJacob Faibussowitsch   PetscCall(PetscOptionsInt("-ts_monitor_frequency", "Number of time steps between monitor output", "TSMonitorSetFrequency", ts->monitorFrequency, &ts->monitorFrequency, NULL));
1409566063dSJacob Faibussowitsch   PetscCall(TSMonitorSetFromOptions(ts, "-ts_monitor", "Monitor time and timestep size", "TSMonitorDefault", TSMonitorDefault, NULL));
1419566063dSJacob Faibussowitsch   PetscCall(TSMonitorSetFromOptions(ts, "-ts_monitor_extreme", "Monitor extreme values of the solution", "TSMonitorExtreme", TSMonitorExtreme, NULL));
1429566063dSJacob Faibussowitsch   PetscCall(TSMonitorSetFromOptions(ts, "-ts_monitor_solution", "View the solution at each timestep", "TSMonitorSolution", TSMonitorSolution, NULL));
1439566063dSJacob Faibussowitsch   PetscCall(TSMonitorSetFromOptions(ts, "-ts_dmswarm_monitor_moments", "Monitor moments of particle distribution", "TSDMSwarmMonitorMoments", TSDMSwarmMonitorMoments, NULL));
144fde5950dSBarry Smith 
1459566063dSJacob Faibussowitsch   PetscCall(PetscOptionsString("-ts_monitor_python", "Use Python function", "TSMonitorSet", NULL, monfilename, sizeof(monfilename), &flg));
1469566063dSJacob Faibussowitsch   if (flg) PetscCall(PetscPythonMonitorSet((PetscObject)ts, monfilename));
1475180491cSLisandro Dalcin 
1489566063dSJacob Faibussowitsch   PetscCall(PetscOptionsName("-ts_monitor_lg_solution", "Monitor solution graphically", "TSMonitorLGSolution", &opt));
149b3603a34SBarry Smith   if (opt) {
1503923b477SBarry Smith     PetscInt  howoften = 1;
151e669de00SBarry Smith     DM        dm;
152e669de00SBarry Smith     PetscBool net;
153b3603a34SBarry Smith 
1549566063dSJacob Faibussowitsch     PetscCall(PetscOptionsInt("-ts_monitor_lg_solution", "Monitor solution graphically", "TSMonitorLGSolution", howoften, &howoften, NULL));
1559566063dSJacob Faibussowitsch     PetscCall(TSGetDM(ts, &dm));
1569566063dSJacob Faibussowitsch     PetscCall(PetscObjectTypeCompare((PetscObject)dm, DMNETWORK, &net));
157e669de00SBarry Smith     if (net) {
158e669de00SBarry Smith       TSMonitorLGCtxNetwork ctx;
1599566063dSJacob Faibussowitsch       PetscCall(TSMonitorLGCtxNetworkCreate(ts, NULL, NULL, PETSC_DECIDE, PETSC_DECIDE, 600, 400, howoften, &ctx));
1609566063dSJacob Faibussowitsch       PetscCall(TSMonitorSet(ts, TSMonitorLGCtxNetworkSolution, ctx, (PetscErrorCode(*)(void **))TSMonitorLGCtxNetworkDestroy));
1619566063dSJacob Faibussowitsch       PetscCall(PetscOptionsBool("-ts_monitor_lg_solution_semilogy", "Plot the solution with a semi-log axis", "", ctx->semilogy, &ctx->semilogy, NULL));
162e669de00SBarry Smith     } else {
163e669de00SBarry Smith       TSMonitorLGCtx ctx;
1649566063dSJacob Faibussowitsch       PetscCall(TSMonitorLGCtxCreate(PETSC_COMM_SELF, NULL, NULL, PETSC_DECIDE, PETSC_DECIDE, 400, 300, howoften, &ctx));
1659566063dSJacob Faibussowitsch       PetscCall(TSMonitorSet(ts, TSMonitorLGSolution, ctx, (PetscErrorCode(*)(void **))TSMonitorLGCtxDestroy));
166bdad233fSMatthew Knepley     }
167e669de00SBarry Smith   }
1686ba87a44SLisandro Dalcin 
1699566063dSJacob Faibussowitsch   PetscCall(PetscOptionsName("-ts_monitor_lg_error", "Monitor error graphically", "TSMonitorLGError", &opt));
170ef20d060SBarry Smith   if (opt) {
1710b039ecaSBarry Smith     TSMonitorLGCtx ctx;
1723923b477SBarry Smith     PetscInt       howoften = 1;
173ef20d060SBarry Smith 
1749566063dSJacob Faibussowitsch     PetscCall(PetscOptionsInt("-ts_monitor_lg_error", "Monitor error graphically", "TSMonitorLGError", howoften, &howoften, NULL));
1759566063dSJacob Faibussowitsch     PetscCall(TSMonitorLGCtxCreate(PETSC_COMM_SELF, NULL, NULL, PETSC_DECIDE, PETSC_DECIDE, 400, 300, howoften, &ctx));
1769566063dSJacob Faibussowitsch     PetscCall(TSMonitorSet(ts, TSMonitorLGError, ctx, (PetscErrorCode(*)(void **))TSMonitorLGCtxDestroy));
177ef20d060SBarry Smith   }
1789566063dSJacob Faibussowitsch   PetscCall(TSMonitorSetFromOptions(ts, "-ts_monitor_error", "View the error at each timestep", "TSMonitorError", TSMonitorError, NULL));
1797cf37e64SBarry Smith 
1809566063dSJacob Faibussowitsch   PetscCall(PetscOptionsName("-ts_monitor_lg_timestep", "Monitor timestep size graphically", "TSMonitorLGTimeStep", &opt));
1816934998bSLisandro Dalcin   if (opt) {
1826934998bSLisandro Dalcin     TSMonitorLGCtx ctx;
1836934998bSLisandro Dalcin     PetscInt       howoften = 1;
1846934998bSLisandro Dalcin 
1859566063dSJacob Faibussowitsch     PetscCall(PetscOptionsInt("-ts_monitor_lg_timestep", "Monitor timestep size graphically", "TSMonitorLGTimeStep", howoften, &howoften, NULL));
1869566063dSJacob Faibussowitsch     PetscCall(TSMonitorLGCtxCreate(PetscObjectComm((PetscObject)ts), NULL, NULL, PETSC_DECIDE, PETSC_DECIDE, 400, 300, howoften, &ctx));
1879566063dSJacob Faibussowitsch     PetscCall(TSMonitorSet(ts, TSMonitorLGTimeStep, ctx, (PetscErrorCode(*)(void **))TSMonitorLGCtxDestroy));
1886934998bSLisandro Dalcin   }
1899566063dSJacob Faibussowitsch   PetscCall(PetscOptionsName("-ts_monitor_lg_timestep_log", "Monitor log timestep size graphically", "TSMonitorLGTimeStep", &opt));
1908b668821SLisandro Dalcin   if (opt) {
1918b668821SLisandro Dalcin     TSMonitorLGCtx ctx;
1928b668821SLisandro Dalcin     PetscInt       howoften = 1;
1938b668821SLisandro Dalcin 
1949566063dSJacob Faibussowitsch     PetscCall(PetscOptionsInt("-ts_monitor_lg_timestep_log", "Monitor log timestep size graphically", "TSMonitorLGTimeStep", howoften, &howoften, NULL));
1959566063dSJacob Faibussowitsch     PetscCall(TSMonitorLGCtxCreate(PetscObjectComm((PetscObject)ts), NULL, NULL, PETSC_DECIDE, PETSC_DECIDE, 400, 300, howoften, &ctx));
1969566063dSJacob Faibussowitsch     PetscCall(TSMonitorSet(ts, TSMonitorLGTimeStep, ctx, (PetscErrorCode(*)(void **))TSMonitorLGCtxDestroy));
1978b668821SLisandro Dalcin     ctx->semilogy = PETSC_TRUE;
1988b668821SLisandro Dalcin   }
1998b668821SLisandro Dalcin 
2009566063dSJacob Faibussowitsch   PetscCall(PetscOptionsName("-ts_monitor_lg_snes_iterations", "Monitor number nonlinear iterations for each timestep graphically", "TSMonitorLGSNESIterations", &opt));
201201da799SBarry Smith   if (opt) {
202201da799SBarry Smith     TSMonitorLGCtx ctx;
203201da799SBarry Smith     PetscInt       howoften = 1;
204201da799SBarry Smith 
2059566063dSJacob Faibussowitsch     PetscCall(PetscOptionsInt("-ts_monitor_lg_snes_iterations", "Monitor number nonlinear iterations for each timestep graphically", "TSMonitorLGSNESIterations", howoften, &howoften, NULL));
2069566063dSJacob Faibussowitsch     PetscCall(TSMonitorLGCtxCreate(PetscObjectComm((PetscObject)ts), NULL, NULL, PETSC_DECIDE, PETSC_DECIDE, 400, 300, howoften, &ctx));
2079566063dSJacob Faibussowitsch     PetscCall(TSMonitorSet(ts, TSMonitorLGSNESIterations, ctx, (PetscErrorCode(*)(void **))TSMonitorLGCtxDestroy));
208201da799SBarry Smith   }
2099566063dSJacob Faibussowitsch   PetscCall(PetscOptionsName("-ts_monitor_lg_ksp_iterations", "Monitor number nonlinear iterations for each timestep graphically", "TSMonitorLGKSPIterations", &opt));
210201da799SBarry Smith   if (opt) {
211201da799SBarry Smith     TSMonitorLGCtx ctx;
212201da799SBarry Smith     PetscInt       howoften = 1;
213201da799SBarry Smith 
2149566063dSJacob Faibussowitsch     PetscCall(PetscOptionsInt("-ts_monitor_lg_ksp_iterations", "Monitor number nonlinear iterations for each timestep graphically", "TSMonitorLGKSPIterations", howoften, &howoften, NULL));
2159566063dSJacob Faibussowitsch     PetscCall(TSMonitorLGCtxCreate(PetscObjectComm((PetscObject)ts), NULL, NULL, PETSC_DECIDE, PETSC_DECIDE, 400, 300, howoften, &ctx));
2169566063dSJacob Faibussowitsch     PetscCall(TSMonitorSet(ts, TSMonitorLGKSPIterations, ctx, (PetscErrorCode(*)(void **))TSMonitorLGCtxDestroy));
217201da799SBarry Smith   }
2189566063dSJacob Faibussowitsch   PetscCall(PetscOptionsName("-ts_monitor_sp_eig", "Monitor eigenvalues of linearized operator graphically", "TSMonitorSPEig", &opt));
2198189c53fSBarry Smith   if (opt) {
2208189c53fSBarry Smith     TSMonitorSPEigCtx ctx;
2218189c53fSBarry Smith     PetscInt          howoften = 1;
2228189c53fSBarry Smith 
2239566063dSJacob Faibussowitsch     PetscCall(PetscOptionsInt("-ts_monitor_sp_eig", "Monitor eigenvalues of linearized operator graphically", "TSMonitorSPEig", howoften, &howoften, NULL));
2249566063dSJacob Faibussowitsch     PetscCall(TSMonitorSPEigCtxCreate(PETSC_COMM_SELF, NULL, NULL, PETSC_DECIDE, PETSC_DECIDE, 300, 300, howoften, &ctx));
2259566063dSJacob Faibussowitsch     PetscCall(TSMonitorSet(ts, TSMonitorSPEig, ctx, (PetscErrorCode(*)(void **))TSMonitorSPEigCtxDestroy));
2268189c53fSBarry Smith   }
2279566063dSJacob Faibussowitsch   PetscCall(PetscOptionsName("-ts_monitor_sp_swarm", "Display particle phase from the DMSwarm", "TSMonitorSPSwarm", &opt));
2281b575b74SJoseph Pusztay   if (opt) {
2291b575b74SJoseph Pusztay     TSMonitorSPCtx ctx;
230d7462660SMatthew Knepley     PetscInt       howoften = 1, retain = 0;
2316a5217c0SMatthew G. Knepley     PetscBool      phase = PETSC_TRUE, create = PETSC_TRUE;
232d7462660SMatthew Knepley 
2339371c9d4SSatish Balay     for (PetscInt i = 0; i < ts->numbermonitors; ++i)
2349371c9d4SSatish Balay       if (ts->monitor[i] == TSMonitorSPSwarmSolution) {
2359371c9d4SSatish Balay         create = PETSC_FALSE;
2369371c9d4SSatish Balay         break;
2379371c9d4SSatish Balay       }
2386a5217c0SMatthew G. Knepley     if (create) {
2399566063dSJacob Faibussowitsch       PetscCall(PetscOptionsInt("-ts_monitor_sp_swarm", "Display particles phase from the DMSwarm", "TSMonitorSPSwarm", howoften, &howoften, NULL));
2409566063dSJacob Faibussowitsch       PetscCall(PetscOptionsInt("-ts_monitor_sp_swarm_retain", "Retain n points plotted to show trajectory, -1 for all points", "TSMonitorSPSwarm", retain, &retain, NULL));
2419566063dSJacob Faibussowitsch       PetscCall(PetscOptionsBool("-ts_monitor_sp_swarm_phase", "Plot in phase space rather than coordinate space", "TSMonitorSPSwarm", phase, &phase, NULL));
2429566063dSJacob Faibussowitsch       PetscCall(TSMonitorSPCtxCreate(PetscObjectComm((PetscObject)ts), NULL, NULL, PETSC_DECIDE, PETSC_DECIDE, 300, 300, howoften, retain, phase, &ctx));
2439566063dSJacob Faibussowitsch       PetscCall(TSMonitorSet(ts, TSMonitorSPSwarmSolution, ctx, (PetscErrorCode(*)(void **))TSMonitorSPCtxDestroy));
2441b575b74SJoseph Pusztay     }
2456a5217c0SMatthew G. Knepley   }
246ef20d060SBarry Smith   opt = PETSC_FALSE;
2479566063dSJacob Faibussowitsch   PetscCall(PetscOptionsName("-ts_monitor_draw_solution", "Monitor solution graphically", "TSMonitorDrawSolution", &opt));
248a7cc72afSBarry Smith   if (opt) {
24983a4ac43SBarry Smith     TSMonitorDrawCtx ctx;
25083a4ac43SBarry Smith     PetscInt         howoften = 1;
251a80ad3e0SBarry Smith 
2529566063dSJacob Faibussowitsch     PetscCall(PetscOptionsInt("-ts_monitor_draw_solution", "Monitor solution graphically", "TSMonitorDrawSolution", howoften, &howoften, NULL));
2539566063dSJacob Faibussowitsch     PetscCall(TSMonitorDrawCtxCreate(PetscObjectComm((PetscObject)ts), NULL, "Computed Solution", PETSC_DECIDE, PETSC_DECIDE, 300, 300, howoften, &ctx));
2549566063dSJacob Faibussowitsch     PetscCall(TSMonitorSet(ts, TSMonitorDrawSolution, ctx, (PetscErrorCode(*)(void **))TSMonitorDrawCtxDestroy));
255bdad233fSMatthew Knepley   }
256fb1732b5SBarry Smith   opt = PETSC_FALSE;
2579566063dSJacob Faibussowitsch   PetscCall(PetscOptionsName("-ts_monitor_draw_solution_phase", "Monitor solution graphically", "TSMonitorDrawSolutionPhase", &opt));
2582d5ee99bSBarry Smith   if (opt) {
2592d5ee99bSBarry Smith     TSMonitorDrawCtx ctx;
2602d5ee99bSBarry Smith     PetscReal        bounds[4];
2612d5ee99bSBarry Smith     PetscInt         n = 4;
2622d5ee99bSBarry Smith     PetscDraw        draw;
2636934998bSLisandro Dalcin     PetscDrawAxis    axis;
2642d5ee99bSBarry Smith 
2659566063dSJacob Faibussowitsch     PetscCall(PetscOptionsRealArray("-ts_monitor_draw_solution_phase", "Monitor solution graphically", "TSMonitorDrawSolutionPhase", bounds, &n, NULL));
2663c633725SBarry Smith     PetscCheck(n == 4, PetscObjectComm((PetscObject)ts), PETSC_ERR_ARG_WRONG, "Must provide bounding box of phase field");
2679566063dSJacob Faibussowitsch     PetscCall(TSMonitorDrawCtxCreate(PetscObjectComm((PetscObject)ts), NULL, NULL, PETSC_DECIDE, PETSC_DECIDE, 300, 300, 1, &ctx));
2689566063dSJacob Faibussowitsch     PetscCall(PetscViewerDrawGetDraw(ctx->viewer, 0, &draw));
2699566063dSJacob Faibussowitsch     PetscCall(PetscViewerDrawGetDrawAxis(ctx->viewer, 0, &axis));
2709566063dSJacob Faibussowitsch     PetscCall(PetscDrawAxisSetLimits(axis, bounds[0], bounds[2], bounds[1], bounds[3]));
2719566063dSJacob Faibussowitsch     PetscCall(PetscDrawAxisSetLabels(axis, "Phase Diagram", "Variable 1", "Variable 2"));
2729566063dSJacob Faibussowitsch     PetscCall(TSMonitorSet(ts, TSMonitorDrawSolutionPhase, ctx, (PetscErrorCode(*)(void **))TSMonitorDrawCtxDestroy));
2732d5ee99bSBarry Smith   }
2742d5ee99bSBarry Smith   opt = PETSC_FALSE;
2759566063dSJacob Faibussowitsch   PetscCall(PetscOptionsName("-ts_monitor_draw_error", "Monitor error graphically", "TSMonitorDrawError", &opt));
2763a471f94SBarry Smith   if (opt) {
27783a4ac43SBarry Smith     TSMonitorDrawCtx ctx;
27883a4ac43SBarry Smith     PetscInt         howoften = 1;
2793a471f94SBarry Smith 
2809566063dSJacob Faibussowitsch     PetscCall(PetscOptionsInt("-ts_monitor_draw_error", "Monitor error graphically", "TSMonitorDrawError", howoften, &howoften, NULL));
2819566063dSJacob Faibussowitsch     PetscCall(TSMonitorDrawCtxCreate(PetscObjectComm((PetscObject)ts), NULL, "Error", PETSC_DECIDE, PETSC_DECIDE, 300, 300, howoften, &ctx));
2829566063dSJacob Faibussowitsch     PetscCall(TSMonitorSet(ts, TSMonitorDrawError, ctx, (PetscErrorCode(*)(void **))TSMonitorDrawCtxDestroy));
2833a471f94SBarry Smith   }
2840ed3bfb6SBarry Smith   opt = PETSC_FALSE;
2859566063dSJacob Faibussowitsch   PetscCall(PetscOptionsName("-ts_monitor_draw_solution_function", "Monitor solution provided by TSMonitorSetSolutionFunction() graphically", "TSMonitorDrawSolutionFunction", &opt));
2860ed3bfb6SBarry Smith   if (opt) {
2870ed3bfb6SBarry Smith     TSMonitorDrawCtx ctx;
2880ed3bfb6SBarry Smith     PetscInt         howoften = 1;
2890ed3bfb6SBarry Smith 
2909566063dSJacob Faibussowitsch     PetscCall(PetscOptionsInt("-ts_monitor_draw_solution_function", "Monitor solution provided by TSMonitorSetSolutionFunction() graphically", "TSMonitorDrawSolutionFunction", howoften, &howoften, NULL));
2919566063dSJacob Faibussowitsch     PetscCall(TSMonitorDrawCtxCreate(PetscObjectComm((PetscObject)ts), NULL, "Solution provided by user function", PETSC_DECIDE, PETSC_DECIDE, 300, 300, howoften, &ctx));
2929566063dSJacob Faibussowitsch     PetscCall(TSMonitorSet(ts, TSMonitorDrawSolutionFunction, ctx, (PetscErrorCode(*)(void **))TSMonitorDrawCtxDestroy));
2930ed3bfb6SBarry Smith   }
294fde5950dSBarry Smith 
295ed81e22dSJed Brown   opt = PETSC_FALSE;
29663a3b9bcSJacob 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));
297ed81e22dSJed Brown   if (flg) {
298ed81e22dSJed Brown     const char *ptr, *ptr2;
299ed81e22dSJed Brown     char       *filetemplate;
30063a3b9bcSJacob Faibussowitsch     PetscCheck(monfilename[0], PetscObjectComm((PetscObject)ts), PETSC_ERR_USER, "-ts_monitor_solution_vtk requires a file template, e.g. filename-%%03" PetscInt_FMT ".vts");
301ed81e22dSJed Brown     /* Do some cursory validation of the input. */
3029566063dSJacob Faibussowitsch     PetscCall(PetscStrstr(monfilename, "%", (char **)&ptr));
30363a3b9bcSJacob Faibussowitsch     PetscCheck(ptr, PetscObjectComm((PetscObject)ts), PETSC_ERR_USER, "-ts_monitor_solution_vtk requires a file template, e.g. filename-%%03" PetscInt_FMT ".vts");
304ed81e22dSJed Brown     for (ptr++; ptr && *ptr; ptr++) {
3059566063dSJacob Faibussowitsch       PetscCall(PetscStrchr("DdiouxX", *ptr, (char **)&ptr2));
30663a3b9bcSJacob Faibussowitsch       PetscCheck(ptr2 || (*ptr >= '0' && *ptr <= '9'), PetscObjectComm((PetscObject)ts), PETSC_ERR_USER, "Invalid file template argument to -ts_monitor_solution_vtk, should look like filename-%%03" PetscInt_FMT ".vts");
307ed81e22dSJed Brown       if (ptr2) break;
308ed81e22dSJed Brown     }
3099566063dSJacob Faibussowitsch     PetscCall(PetscStrallocpy(monfilename, &filetemplate));
3109566063dSJacob Faibussowitsch     PetscCall(TSMonitorSet(ts, TSMonitorSolutionVTK, filetemplate, (PetscErrorCode(*)(void **))TSMonitorSolutionVTKDestroy));
311ed81e22dSJed Brown   }
312bdad233fSMatthew Knepley 
3139566063dSJacob Faibussowitsch   PetscCall(PetscOptionsString("-ts_monitor_dmda_ray", "Display a ray of the solution", "None", "y=0", dir, sizeof(dir), &flg));
314d1212d36SBarry Smith   if (flg) {
315d1212d36SBarry Smith     TSMonitorDMDARayCtx *rayctx;
316d1212d36SBarry Smith     int                  ray = 0;
3173ee9839eSMatthew G. Knepley     DMDirection          ddir;
318d1212d36SBarry Smith     DM                   da;
319d1212d36SBarry Smith     PetscMPIInt          rank;
320d1212d36SBarry Smith 
3213c633725SBarry Smith     PetscCheck(dir[1] == '=', PetscObjectComm((PetscObject)ts), PETSC_ERR_ARG_WRONG, "Unknown ray %s", dir);
3223ee9839eSMatthew G. Knepley     if (dir[0] == 'x') ddir = DM_X;
3233ee9839eSMatthew G. Knepley     else if (dir[0] == 'y') ddir = DM_Y;
32498921bdaSJacob Faibussowitsch     else SETERRQ(PetscObjectComm((PetscObject)ts), PETSC_ERR_ARG_WRONG, "Unknown ray %s", dir);
325d1212d36SBarry Smith     sscanf(dir + 2, "%d", &ray);
326d1212d36SBarry Smith 
3279566063dSJacob Faibussowitsch     PetscCall(PetscInfo(((PetscObject)ts), "Displaying DMDA ray %c = %d\n", dir[0], ray));
3289566063dSJacob Faibussowitsch     PetscCall(PetscNew(&rayctx));
3299566063dSJacob Faibussowitsch     PetscCall(TSGetDM(ts, &da));
3309566063dSJacob Faibussowitsch     PetscCall(DMDAGetRay(da, ddir, ray, &rayctx->ray, &rayctx->scatter));
3319566063dSJacob Faibussowitsch     PetscCallMPI(MPI_Comm_rank(PetscObjectComm((PetscObject)ts), &rank));
3321e66621cSBarry Smith     if (rank == 0) PetscCall(PetscViewerDrawOpen(PETSC_COMM_SELF, NULL, NULL, 0, 0, 600, 300, &rayctx->viewer));
33351b4a12fSMatthew G. Knepley     rayctx->lgctx = NULL;
3349566063dSJacob Faibussowitsch     PetscCall(TSMonitorSet(ts, TSMonitorDMDARay, rayctx, TSMonitorDMDARayDestroy));
335d1212d36SBarry Smith   }
3369566063dSJacob Faibussowitsch   PetscCall(PetscOptionsString("-ts_monitor_lg_dmda_ray", "Display a ray of the solution", "None", "x=0", dir, sizeof(dir), &flg));
33751b4a12fSMatthew G. Knepley   if (flg) {
33851b4a12fSMatthew G. Knepley     TSMonitorDMDARayCtx *rayctx;
33951b4a12fSMatthew G. Knepley     int                  ray = 0;
3403ee9839eSMatthew G. Knepley     DMDirection          ddir;
34151b4a12fSMatthew G. Knepley     DM                   da;
34251b4a12fSMatthew G. Knepley     PetscInt             howoften = 1;
343d1212d36SBarry Smith 
3443c633725SBarry Smith     PetscCheck(dir[1] == '=', PetscObjectComm((PetscObject)ts), PETSC_ERR_ARG_WRONG, "Malformed ray %s", dir);
3453ee9839eSMatthew G. Knepley     if (dir[0] == 'x') ddir = DM_X;
3463ee9839eSMatthew G. Knepley     else if (dir[0] == 'y') ddir = DM_Y;
34798921bdaSJacob Faibussowitsch     else SETERRQ(PetscObjectComm((PetscObject)ts), PETSC_ERR_ARG_WRONG, "Unknown ray direction %s", dir);
34851b4a12fSMatthew G. Knepley     sscanf(dir + 2, "%d", &ray);
3491c3436cfSJed Brown 
3509566063dSJacob Faibussowitsch     PetscCall(PetscInfo(((PetscObject)ts), "Displaying LG DMDA ray %c = %d\n", dir[0], ray));
3519566063dSJacob Faibussowitsch     PetscCall(PetscNew(&rayctx));
3529566063dSJacob Faibussowitsch     PetscCall(TSGetDM(ts, &da));
3539566063dSJacob Faibussowitsch     PetscCall(DMDAGetRay(da, ddir, ray, &rayctx->ray, &rayctx->scatter));
3549566063dSJacob Faibussowitsch     PetscCall(TSMonitorLGCtxCreate(PETSC_COMM_SELF, NULL, NULL, PETSC_DECIDE, PETSC_DECIDE, 600, 400, howoften, &rayctx->lgctx));
3559566063dSJacob Faibussowitsch     PetscCall(TSMonitorSet(ts, TSMonitorLGDMDARay, rayctx, TSMonitorDMDARayDestroy));
35651b4a12fSMatthew G. Knepley   }
357a7a1495cSBarry Smith 
3589566063dSJacob Faibussowitsch   PetscCall(PetscOptionsName("-ts_monitor_envelope", "Monitor maximum and minimum value of each component of the solution", "TSMonitorEnvelope", &opt));
359b3d3934dSBarry Smith   if (opt) {
360b3d3934dSBarry Smith     TSMonitorEnvelopeCtx ctx;
361b3d3934dSBarry Smith 
3629566063dSJacob Faibussowitsch     PetscCall(TSMonitorEnvelopeCtxCreate(ts, &ctx));
3639566063dSJacob Faibussowitsch     PetscCall(TSMonitorSet(ts, TSMonitorEnvelope, ctx, (PetscErrorCode(*)(void **))TSMonitorEnvelopeCtxDestroy));
364b3d3934dSBarry Smith   }
365aee7a9fbSMatthew G. Knepley   flg = PETSC_FALSE;
3669566063dSJacob Faibussowitsch   PetscCall(PetscOptionsBool("-ts_monitor_cancel", "Remove all monitors", "TSMonitorCancel", flg, &flg, &opt));
3679566063dSJacob Faibussowitsch   if (opt && flg) PetscCall(TSMonitorCancel(ts));
368b3d3934dSBarry Smith 
369847ff0e1SMatthew G. Knepley   flg = PETSC_FALSE;
3709566063dSJacob Faibussowitsch   PetscCall(PetscOptionsBool("-ts_fd_color", "Use finite differences with coloring to compute IJacobian", "TSComputeJacobianDefaultColor", flg, &flg, NULL));
371847ff0e1SMatthew G. Knepley   if (flg) {
372847ff0e1SMatthew G. Knepley     DM dm;
373847ff0e1SMatthew G. Knepley 
3749371c9d4SSatish Balay     PetscCall(TSGetDM(ts, &dm));
3759371c9d4SSatish Balay     PetscCall(DMTSUnsetIJacobianContext_Internal(dm));
3769566063dSJacob Faibussowitsch     PetscCall(TSSetIJacobian(ts, NULL, NULL, TSComputeIJacobianDefaultColor, NULL));
3779566063dSJacob Faibussowitsch     PetscCall(PetscInfo(ts, "Setting default finite difference coloring Jacobian matrix\n"));
378847ff0e1SMatthew G. Knepley   }
379847ff0e1SMatthew G. Knepley 
380d763cef2SBarry Smith   /* Handle specific TS options */
381dbbe0bcdSBarry Smith   PetscTryTypeMethod(ts, setfromoptions, PetscOptionsObject);
382fbc52257SHong Zhang 
383a7bdc993SLisandro Dalcin   /* Handle TSAdapt options */
3849566063dSJacob Faibussowitsch   PetscCall(TSGetAdapt(ts, &ts->adapt));
3859566063dSJacob Faibussowitsch   PetscCall(TSAdaptSetDefaultType(ts->adapt, ts->default_adapt_type));
386dbbe0bcdSBarry Smith   PetscCall(TSAdaptSetFromOptions(ts->adapt, PetscOptionsObject));
387a7bdc993SLisandro Dalcin 
38868bece0bSHong Zhang   /* TS trajectory must be set after TS, since it may use some TS options above */
3894f122a70SLisandro Dalcin   tflg = ts->trajectory ? PETSC_TRUE : PETSC_FALSE;
3909566063dSJacob Faibussowitsch   PetscCall(PetscOptionsBool("-ts_save_trajectory", "Save the solution at each timestep", "TSSetSaveTrajectory", tflg, &tflg, NULL));
3911baa6e33SBarry Smith   if (tflg) PetscCall(TSSetSaveTrajectory(ts));
392a05bf03eSHong Zhang 
393dbbe0bcdSBarry Smith   PetscCall(TSAdjointSetFromOptions(ts, PetscOptionsObject));
394d763cef2SBarry Smith 
395d763cef2SBarry Smith   /* process any options handlers added with PetscObjectAddOptionsHandler() */
396dbbe0bcdSBarry Smith   PetscCall(PetscObjectProcessOptionsHandlers((PetscObject)ts, PetscOptionsObject));
397d0609cedSBarry Smith   PetscOptionsEnd();
398d763cef2SBarry Smith 
3991baa6e33SBarry Smith   if (ts->trajectory) PetscCall(TSTrajectorySetFromOptions(ts->trajectory, ts));
40068bece0bSHong Zhang 
4011ef27442SStefano Zampini   /* why do we have to do this here and not during TSSetUp? */
4029566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts, &ts->snes));
4031ef27442SStefano Zampini   if (ts->problem_type == TS_LINEAR) {
4049566063dSJacob Faibussowitsch     PetscCall(PetscObjectTypeCompareAny((PetscObject)ts->snes, &flg, SNESKSPONLY, SNESKSPTRANSPOSEONLY, ""));
4059566063dSJacob Faibussowitsch     if (!flg) PetscCall(SNESSetType(ts->snes, SNESKSPONLY));
4061ef27442SStefano Zampini   }
4079566063dSJacob Faibussowitsch   PetscCall(SNESSetFromOptions(ts->snes));
408d763cef2SBarry Smith   PetscFunctionReturn(0);
409d763cef2SBarry Smith }
410d763cef2SBarry Smith 
411d2daff3dSHong Zhang /*@
41278fbdcc8SBarry Smith    TSGetTrajectory - Gets the trajectory from a TS if it exists
41378fbdcc8SBarry Smith 
41478fbdcc8SBarry Smith    Collective on TS
41578fbdcc8SBarry Smith 
41678fbdcc8SBarry Smith    Input Parameters:
41778fbdcc8SBarry Smith .  ts - the TS context obtained from TSCreate()
41878fbdcc8SBarry Smith 
4197a7aea1fSJed Brown    Output Parameters:
42078fbdcc8SBarry Smith .  tr - the TSTrajectory object, if it exists
42178fbdcc8SBarry Smith 
42278fbdcc8SBarry Smith    Note: This routine should be called after all TS options have been set
42378fbdcc8SBarry Smith 
42478fbdcc8SBarry Smith    Level: advanced
42578fbdcc8SBarry Smith 
426db781477SPatrick Sanan .seealso: `TSGetTrajectory()`, `TSAdjointSolve()`, `TSTrajectory`, `TSTrajectoryCreate()`
42778fbdcc8SBarry Smith 
42878fbdcc8SBarry Smith @*/
429*d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetTrajectory(TS ts, TSTrajectory *tr)
430*d71ae5a4SJacob Faibussowitsch {
43178fbdcc8SBarry Smith   PetscFunctionBegin;
43278fbdcc8SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
43378fbdcc8SBarry Smith   *tr = ts->trajectory;
43478fbdcc8SBarry Smith   PetscFunctionReturn(0);
43578fbdcc8SBarry Smith }
43678fbdcc8SBarry Smith 
43778fbdcc8SBarry Smith /*@
438bc952696SBarry Smith    TSSetSaveTrajectory - Causes the TS to save its solutions as it iterates forward in time in a TSTrajectory object
439d2daff3dSHong Zhang 
440d2daff3dSHong Zhang    Collective on TS
441d2daff3dSHong Zhang 
442f899ff85SJose E. Roman    Input Parameter:
443bc952696SBarry Smith .  ts - the TS context obtained from TSCreate()
444bc952696SBarry Smith 
44578fbdcc8SBarry Smith    Options Database:
44678fbdcc8SBarry Smith +  -ts_save_trajectory - saves the trajectory to a file
44767b8a455SSatish Balay -  -ts_trajectory_type type - set trajectory type
44878fbdcc8SBarry Smith 
44968bece0bSHong Zhang Note: This routine should be called after all TS options have been set
450d2daff3dSHong Zhang 
451c3a89c15SBarry Smith     The TSTRAJECTORYVISUALIZATION files can be loaded into Python with $PETSC_DIR/lib/petsc/bin/PetscBinaryIOTrajectory.py and
45278fbdcc8SBarry Smith    MATLAB with $PETSC_DIR/share/petsc/matlab/PetscReadBinaryTrajectory.m
45378fbdcc8SBarry Smith 
454d2daff3dSHong Zhang    Level: intermediate
455d2daff3dSHong Zhang 
456db781477SPatrick Sanan .seealso: `TSGetTrajectory()`, `TSAdjointSolve()`
457d2daff3dSHong Zhang 
458d2daff3dSHong Zhang @*/
459*d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetSaveTrajectory(TS ts)
460*d71ae5a4SJacob Faibussowitsch {
461d2daff3dSHong Zhang   PetscFunctionBegin;
462d2daff3dSHong Zhang   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
46363a3b9bcSJacob Faibussowitsch   if (!ts->trajectory) PetscCall(TSTrajectoryCreate(PetscObjectComm((PetscObject)ts), &ts->trajectory));
464d2daff3dSHong Zhang   PetscFunctionReturn(0);
465d2daff3dSHong Zhang }
466d2daff3dSHong Zhang 
467a7a1495cSBarry Smith /*@
4682d29f1f2SStefano Zampini    TSResetTrajectory - Destroys and recreates the internal TSTrajectory object
4692d29f1f2SStefano Zampini 
4702d29f1f2SStefano Zampini    Collective on TS
4712d29f1f2SStefano Zampini 
4722d29f1f2SStefano Zampini    Input Parameters:
4732d29f1f2SStefano Zampini .  ts - the TS context obtained from TSCreate()
4742d29f1f2SStefano Zampini 
4752d29f1f2SStefano Zampini    Level: intermediate
4762d29f1f2SStefano Zampini 
477db781477SPatrick Sanan .seealso: `TSGetTrajectory()`, `TSAdjointSolve()`, `TSRemoveTrajectory()`
4782d29f1f2SStefano Zampini 
4792d29f1f2SStefano Zampini @*/
480*d71ae5a4SJacob Faibussowitsch PetscErrorCode TSResetTrajectory(TS ts)
481*d71ae5a4SJacob Faibussowitsch {
4822d29f1f2SStefano Zampini   PetscFunctionBegin;
4832d29f1f2SStefano Zampini   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
4842d29f1f2SStefano Zampini   if (ts->trajectory) {
4859566063dSJacob Faibussowitsch     PetscCall(TSTrajectoryDestroy(&ts->trajectory));
4869566063dSJacob Faibussowitsch     PetscCall(TSTrajectoryCreate(PetscObjectComm((PetscObject)ts), &ts->trajectory));
4872d29f1f2SStefano Zampini   }
4882d29f1f2SStefano Zampini   PetscFunctionReturn(0);
4892d29f1f2SStefano Zampini }
4902d29f1f2SStefano Zampini 
4912d29f1f2SStefano Zampini /*@
49267a3cfb0SHong Zhang    TSRemoveTrajectory - Destroys and removes the internal TSTrajectory object from TS
49367a3cfb0SHong Zhang 
49467a3cfb0SHong Zhang    Collective on TS
49567a3cfb0SHong Zhang 
49667a3cfb0SHong Zhang    Input Parameters:
49767a3cfb0SHong Zhang .  ts - the TS context obtained from TSCreate()
49867a3cfb0SHong Zhang 
49967a3cfb0SHong Zhang    Level: intermediate
50067a3cfb0SHong Zhang 
501db781477SPatrick Sanan .seealso: `TSResetTrajectory()`, `TSAdjointSolve()`
50267a3cfb0SHong Zhang 
50367a3cfb0SHong Zhang @*/
504*d71ae5a4SJacob Faibussowitsch PetscErrorCode TSRemoveTrajectory(TS ts)
505*d71ae5a4SJacob Faibussowitsch {
50667a3cfb0SHong Zhang   PetscFunctionBegin;
50767a3cfb0SHong Zhang   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
5081e66621cSBarry Smith   if (ts->trajectory) PetscCall(TSTrajectoryDestroy(&ts->trajectory));
50967a3cfb0SHong Zhang   PetscFunctionReturn(0);
51067a3cfb0SHong Zhang }
51167a3cfb0SHong Zhang 
51267a3cfb0SHong Zhang /*@
513a7a1495cSBarry Smith    TSComputeRHSJacobian - Computes the Jacobian matrix that has been
514a7a1495cSBarry Smith       set with TSSetRHSJacobian().
515a7a1495cSBarry Smith 
516d083f849SBarry Smith    Collective on TS
517a7a1495cSBarry Smith 
518a7a1495cSBarry Smith    Input Parameters:
519316643e7SJed Brown +  ts - the TS context
520a7a1495cSBarry Smith .  t - current timestep
5210910c330SBarry Smith -  U - input vector
522a7a1495cSBarry Smith 
523a7a1495cSBarry Smith    Output Parameters:
524a7a1495cSBarry Smith +  A - Jacobian matrix
5256b867d5aSJose E. Roman -  B - optional preconditioning matrix
526a7a1495cSBarry Smith 
527a7a1495cSBarry Smith    Notes:
528a7a1495cSBarry Smith    Most users should not need to explicitly call this routine, as it
529a7a1495cSBarry Smith    is used internally within the nonlinear solvers.
530a7a1495cSBarry Smith 
531a7a1495cSBarry Smith    Level: developer
532a7a1495cSBarry Smith 
533db781477SPatrick Sanan .seealso: `TSSetRHSJacobian()`, `KSPSetOperators()`
534a7a1495cSBarry Smith @*/
535*d71ae5a4SJacob Faibussowitsch PetscErrorCode TSComputeRHSJacobian(TS ts, PetscReal t, Vec U, Mat A, Mat B)
536*d71ae5a4SJacob Faibussowitsch {
537270bf2e7SJed Brown   PetscObjectState Ustate;
5386c1e1eecSBarry Smith   PetscObjectId    Uid;
53924989b8cSPeter Brune   DM               dm;
540942e3340SBarry Smith   DMTS             tsdm;
54124989b8cSPeter Brune   TSRHSJacobian    rhsjacobianfunc;
54224989b8cSPeter Brune   void            *ctx;
543b2df71adSDebojyoti Ghosh   TSRHSFunction    rhsfunction;
544a7a1495cSBarry Smith 
545a7a1495cSBarry Smith   PetscFunctionBegin;
5460700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
5470910c330SBarry Smith   PetscValidHeaderSpecific(U, VEC_CLASSID, 3);
5480910c330SBarry Smith   PetscCheckSameComm(ts, 1, U, 3);
5499566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
5509566063dSJacob Faibussowitsch   PetscCall(DMGetDMTS(dm, &tsdm));
5519566063dSJacob Faibussowitsch   PetscCall(DMTSGetRHSFunction(dm, &rhsfunction, NULL));
5529566063dSJacob Faibussowitsch   PetscCall(DMTSGetRHSJacobian(dm, &rhsjacobianfunc, &ctx));
5539566063dSJacob Faibussowitsch   PetscCall(PetscObjectStateGet((PetscObject)U, &Ustate));
5549566063dSJacob Faibussowitsch   PetscCall(PetscObjectGetId((PetscObject)U, &Uid));
555971015bcSStefano Zampini 
5562663174eSHong Zhang   if (ts->rhsjacobian.time == t && (ts->problem_type == TS_LINEAR || (ts->rhsjacobian.Xid == Uid && ts->rhsjacobian.Xstate == Ustate)) && (rhsfunction != TSComputeRHSFunctionLinear)) PetscFunctionReturn(0);
557d90be118SSean Farley 
55863a3b9bcSJacob 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);
55924989b8cSPeter Brune   if (rhsjacobianfunc) {
5609566063dSJacob Faibussowitsch     PetscCall(PetscLogEventBegin(TS_JacobianEval, ts, U, A, B));
561792fecdfSBarry Smith     PetscCallBack("TS callback Jacobian", (*rhsjacobianfunc)(ts, t, U, A, B, ctx));
562a6ab3590SBarry Smith     ts->rhsjacs++;
5639566063dSJacob Faibussowitsch     PetscCall(PetscLogEventEnd(TS_JacobianEval, ts, U, A, B));
564ef66eb69SBarry Smith   } else {
5659566063dSJacob Faibussowitsch     PetscCall(MatZeroEntries(A));
5669566063dSJacob Faibussowitsch     if (B && A != B) PetscCall(MatZeroEntries(B));
567ef66eb69SBarry Smith   }
5680e4ef248SJed Brown   ts->rhsjacobian.time  = t;
569971015bcSStefano Zampini   ts->rhsjacobian.shift = 0;
570971015bcSStefano Zampini   ts->rhsjacobian.scale = 1.;
5719566063dSJacob Faibussowitsch   PetscCall(PetscObjectGetId((PetscObject)U, &ts->rhsjacobian.Xid));
5729566063dSJacob Faibussowitsch   PetscCall(PetscObjectStateGet((PetscObject)U, &ts->rhsjacobian.Xstate));
573a7a1495cSBarry Smith   PetscFunctionReturn(0);
574a7a1495cSBarry Smith }
575a7a1495cSBarry Smith 
576316643e7SJed Brown /*@
577d763cef2SBarry Smith    TSComputeRHSFunction - Evaluates the right-hand-side function.
578d763cef2SBarry Smith 
579d083f849SBarry Smith    Collective on TS
580316643e7SJed Brown 
581316643e7SJed Brown    Input Parameters:
582316643e7SJed Brown +  ts - the TS context
583316643e7SJed Brown .  t - current time
5840910c330SBarry Smith -  U - state vector
585316643e7SJed Brown 
586316643e7SJed Brown    Output Parameter:
587316643e7SJed Brown .  y - right hand side
588316643e7SJed Brown 
589316643e7SJed Brown    Note:
590316643e7SJed Brown    Most users should not need to explicitly call this routine, as it
591316643e7SJed Brown    is used internally within the nonlinear solvers.
592316643e7SJed Brown 
593316643e7SJed Brown    Level: developer
594316643e7SJed Brown 
595db781477SPatrick Sanan .seealso: `TSSetRHSFunction()`, `TSComputeIFunction()`
596316643e7SJed Brown @*/
597*d71ae5a4SJacob Faibussowitsch PetscErrorCode TSComputeRHSFunction(TS ts, PetscReal t, Vec U, Vec y)
598*d71ae5a4SJacob Faibussowitsch {
59924989b8cSPeter Brune   TSRHSFunction rhsfunction;
60024989b8cSPeter Brune   TSIFunction   ifunction;
60124989b8cSPeter Brune   void         *ctx;
60224989b8cSPeter Brune   DM            dm;
60324989b8cSPeter Brune 
604d763cef2SBarry Smith   PetscFunctionBegin;
6050700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
6060910c330SBarry Smith   PetscValidHeaderSpecific(U, VEC_CLASSID, 3);
6070700a824SBarry Smith   PetscValidHeaderSpecific(y, VEC_CLASSID, 4);
6089566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
6099566063dSJacob Faibussowitsch   PetscCall(DMTSGetRHSFunction(dm, &rhsfunction, &ctx));
6109566063dSJacob Faibussowitsch   PetscCall(DMTSGetIFunction(dm, &ifunction, NULL));
611d763cef2SBarry Smith 
6123c633725SBarry Smith   PetscCheck(rhsfunction || ifunction, PetscObjectComm((PetscObject)ts), PETSC_ERR_USER, "Must call TSSetRHSFunction() and / or TSSetIFunction()");
613d763cef2SBarry Smith 
61424989b8cSPeter Brune   if (rhsfunction) {
6159566063dSJacob Faibussowitsch     PetscCall(PetscLogEventBegin(TS_FunctionEval, ts, U, y, 0));
6169566063dSJacob Faibussowitsch     PetscCall(VecLockReadPush(U));
617792fecdfSBarry Smith     PetscCallBack("TS callback right-hand-side", (*rhsfunction)(ts, t, U, y, ctx));
6189566063dSJacob Faibussowitsch     PetscCall(VecLockReadPop(U));
619a6ab3590SBarry Smith     ts->rhsfuncs++;
6209566063dSJacob Faibussowitsch     PetscCall(PetscLogEventEnd(TS_FunctionEval, ts, U, y, 0));
6211e66621cSBarry Smith   } else PetscCall(VecZeroEntries(y));
622d763cef2SBarry Smith   PetscFunctionReturn(0);
623d763cef2SBarry Smith }
624d763cef2SBarry Smith 
625ef20d060SBarry Smith /*@
626ef20d060SBarry Smith    TSComputeSolutionFunction - Evaluates the solution function.
627ef20d060SBarry Smith 
628d083f849SBarry Smith    Collective on TS
629ef20d060SBarry Smith 
630ef20d060SBarry Smith    Input Parameters:
631ef20d060SBarry Smith +  ts - the TS context
632ef20d060SBarry Smith -  t - current time
633ef20d060SBarry Smith 
634ef20d060SBarry Smith    Output Parameter:
6350910c330SBarry Smith .  U - the solution
636ef20d060SBarry Smith 
637ef20d060SBarry Smith    Note:
638ef20d060SBarry Smith    Most users should not need to explicitly call this routine, as it
639ef20d060SBarry Smith    is used internally within the nonlinear solvers.
640ef20d060SBarry Smith 
641ef20d060SBarry Smith    Level: developer
642ef20d060SBarry Smith 
643db781477SPatrick Sanan .seealso: `TSSetSolutionFunction()`, `TSSetRHSFunction()`, `TSComputeIFunction()`
644ef20d060SBarry Smith @*/
645*d71ae5a4SJacob Faibussowitsch PetscErrorCode TSComputeSolutionFunction(TS ts, PetscReal t, Vec U)
646*d71ae5a4SJacob Faibussowitsch {
647ef20d060SBarry Smith   TSSolutionFunction solutionfunction;
648ef20d060SBarry Smith   void              *ctx;
649ef20d060SBarry Smith   DM                 dm;
650ef20d060SBarry Smith 
651ef20d060SBarry Smith   PetscFunctionBegin;
652ef20d060SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
6530910c330SBarry Smith   PetscValidHeaderSpecific(U, VEC_CLASSID, 3);
6549566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
6559566063dSJacob Faibussowitsch   PetscCall(DMTSGetSolutionFunction(dm, &solutionfunction, &ctx));
656ef20d060SBarry Smith 
657792fecdfSBarry Smith   if (solutionfunction) PetscCallBack("TS callback solution", (*solutionfunction)(ts, t, U, ctx));
658ef20d060SBarry Smith   PetscFunctionReturn(0);
659ef20d060SBarry Smith }
6609b7cd975SBarry Smith /*@
6619b7cd975SBarry Smith    TSComputeForcingFunction - Evaluates the forcing function.
6629b7cd975SBarry Smith 
663d083f849SBarry Smith    Collective on TS
6649b7cd975SBarry Smith 
6659b7cd975SBarry Smith    Input Parameters:
6669b7cd975SBarry Smith +  ts - the TS context
6679b7cd975SBarry Smith -  t - current time
6689b7cd975SBarry Smith 
6699b7cd975SBarry Smith    Output Parameter:
6709b7cd975SBarry Smith .  U - the function value
6719b7cd975SBarry Smith 
6729b7cd975SBarry Smith    Note:
6739b7cd975SBarry Smith    Most users should not need to explicitly call this routine, as it
6749b7cd975SBarry Smith    is used internally within the nonlinear solvers.
6759b7cd975SBarry Smith 
6769b7cd975SBarry Smith    Level: developer
6779b7cd975SBarry Smith 
678db781477SPatrick Sanan .seealso: `TSSetSolutionFunction()`, `TSSetRHSFunction()`, `TSComputeIFunction()`
6799b7cd975SBarry Smith @*/
680*d71ae5a4SJacob Faibussowitsch PetscErrorCode TSComputeForcingFunction(TS ts, PetscReal t, Vec U)
681*d71ae5a4SJacob Faibussowitsch {
6829b7cd975SBarry Smith   void             *ctx;
6839b7cd975SBarry Smith   DM                dm;
6845f80ce2aSJacob Faibussowitsch   TSForcingFunction forcing;
6859b7cd975SBarry Smith 
6869b7cd975SBarry Smith   PetscFunctionBegin;
6879b7cd975SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
6889b7cd975SBarry Smith   PetscValidHeaderSpecific(U, VEC_CLASSID, 3);
6899566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
6909566063dSJacob Faibussowitsch   PetscCall(DMTSGetForcingFunction(dm, &forcing, &ctx));
6919b7cd975SBarry Smith 
692792fecdfSBarry Smith   if (forcing) PetscCallBack("TS callback forcing function", (*forcing)(ts, t, U, ctx));
6939b7cd975SBarry Smith   PetscFunctionReturn(0);
6949b7cd975SBarry Smith }
695ef20d060SBarry Smith 
696*d71ae5a4SJacob Faibussowitsch static PetscErrorCode TSGetRHSVec_Private(TS ts, Vec *Frhs)
697*d71ae5a4SJacob Faibussowitsch {
6982dd45cf8SJed Brown   Vec F;
699214bc6a2SJed Brown 
700214bc6a2SJed Brown   PetscFunctionBegin;
7010298fd71SBarry Smith   *Frhs = NULL;
7029566063dSJacob Faibussowitsch   PetscCall(TSGetIFunction(ts, &F, NULL, NULL));
7031e66621cSBarry Smith   if (!ts->Frhs) PetscCall(VecDuplicate(F, &ts->Frhs));
704214bc6a2SJed Brown   *Frhs = ts->Frhs;
705214bc6a2SJed Brown   PetscFunctionReturn(0);
706214bc6a2SJed Brown }
707214bc6a2SJed Brown 
708*d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetRHSMats_Private(TS ts, Mat *Arhs, Mat *Brhs)
709*d71ae5a4SJacob Faibussowitsch {
710214bc6a2SJed Brown   Mat         A, B;
71141a1d4d2SBarry Smith   TSIJacobian ijacobian;
712214bc6a2SJed Brown 
713214bc6a2SJed Brown   PetscFunctionBegin;
714c0cd0301SJed Brown   if (Arhs) *Arhs = NULL;
715c0cd0301SJed Brown   if (Brhs) *Brhs = NULL;
7169566063dSJacob Faibussowitsch   PetscCall(TSGetIJacobian(ts, &A, &B, &ijacobian, NULL));
717214bc6a2SJed Brown   if (Arhs) {
718214bc6a2SJed Brown     if (!ts->Arhs) {
71941a1d4d2SBarry Smith       if (ijacobian) {
7209566063dSJacob Faibussowitsch         PetscCall(MatDuplicate(A, MAT_DO_NOT_COPY_VALUES, &ts->Arhs));
7219566063dSJacob Faibussowitsch         PetscCall(TSSetMatStructure(ts, SAME_NONZERO_PATTERN));
72241a1d4d2SBarry Smith       } else {
72341a1d4d2SBarry Smith         ts->Arhs = A;
7249566063dSJacob Faibussowitsch         PetscCall(PetscObjectReference((PetscObject)A));
72541a1d4d2SBarry Smith       }
7263565c898SBarry Smith     } else {
7273565c898SBarry Smith       PetscBool flg;
7289566063dSJacob Faibussowitsch       PetscCall(SNESGetUseMatrixFree(ts->snes, NULL, &flg));
7293565c898SBarry Smith       /* Handle case where user provided only RHSJacobian and used -snes_mf_operator */
7303565c898SBarry Smith       if (flg && !ijacobian && ts->Arhs == ts->Brhs) {
7319566063dSJacob Faibussowitsch         PetscCall(PetscObjectDereference((PetscObject)ts->Arhs));
7323565c898SBarry Smith         ts->Arhs = A;
7339566063dSJacob Faibussowitsch         PetscCall(PetscObjectReference((PetscObject)A));
7343565c898SBarry Smith       }
735214bc6a2SJed Brown     }
736214bc6a2SJed Brown     *Arhs = ts->Arhs;
737214bc6a2SJed Brown   }
738214bc6a2SJed Brown   if (Brhs) {
739214bc6a2SJed Brown     if (!ts->Brhs) {
740bdb70873SJed Brown       if (A != B) {
74141a1d4d2SBarry Smith         if (ijacobian) {
7429566063dSJacob Faibussowitsch           PetscCall(MatDuplicate(B, MAT_DO_NOT_COPY_VALUES, &ts->Brhs));
743bdb70873SJed Brown         } else {
74441a1d4d2SBarry Smith           ts->Brhs = B;
7459566063dSJacob Faibussowitsch           PetscCall(PetscObjectReference((PetscObject)B));
74641a1d4d2SBarry Smith         }
74741a1d4d2SBarry Smith       } else {
7489566063dSJacob Faibussowitsch         PetscCall(PetscObjectReference((PetscObject)ts->Arhs));
74951699248SLisandro Dalcin         ts->Brhs = ts->Arhs;
750bdb70873SJed Brown       }
751214bc6a2SJed Brown     }
752214bc6a2SJed Brown     *Brhs = ts->Brhs;
753214bc6a2SJed Brown   }
754214bc6a2SJed Brown   PetscFunctionReturn(0);
755214bc6a2SJed Brown }
756214bc6a2SJed Brown 
757316643e7SJed Brown /*@
7580910c330SBarry Smith    TSComputeIFunction - Evaluates the DAE residual written in implicit form F(t,U,Udot)=0
759316643e7SJed Brown 
760d083f849SBarry Smith    Collective on TS
761316643e7SJed Brown 
762316643e7SJed Brown    Input Parameters:
763316643e7SJed Brown +  ts - the TS context
764316643e7SJed Brown .  t - current time
7650910c330SBarry Smith .  U - state vector
7660910c330SBarry Smith .  Udot - time derivative of state vector
767214bc6a2SJed Brown -  imex - flag indicates if the method is IMEX so that the RHSFunction should be kept separate
768316643e7SJed Brown 
769316643e7SJed Brown    Output Parameter:
770316643e7SJed Brown .  Y - right hand side
771316643e7SJed Brown 
772316643e7SJed Brown    Note:
773316643e7SJed Brown    Most users should not need to explicitly call this routine, as it
774316643e7SJed Brown    is used internally within the nonlinear solvers.
775316643e7SJed Brown 
776316643e7SJed Brown    If the user did did not write their equations in implicit form, this
777316643e7SJed Brown    function recasts them in implicit form.
778316643e7SJed Brown 
779316643e7SJed Brown    Level: developer
780316643e7SJed Brown 
781db781477SPatrick Sanan .seealso: `TSSetIFunction()`, `TSComputeRHSFunction()`
782316643e7SJed Brown @*/
783*d71ae5a4SJacob Faibussowitsch PetscErrorCode TSComputeIFunction(TS ts, PetscReal t, Vec U, Vec Udot, Vec Y, PetscBool imex)
784*d71ae5a4SJacob Faibussowitsch {
78524989b8cSPeter Brune   TSIFunction   ifunction;
78624989b8cSPeter Brune   TSRHSFunction rhsfunction;
78724989b8cSPeter Brune   void         *ctx;
78824989b8cSPeter Brune   DM            dm;
789316643e7SJed Brown 
790316643e7SJed Brown   PetscFunctionBegin;
7910700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
7920910c330SBarry Smith   PetscValidHeaderSpecific(U, VEC_CLASSID, 3);
7930910c330SBarry Smith   PetscValidHeaderSpecific(Udot, VEC_CLASSID, 4);
7940700a824SBarry Smith   PetscValidHeaderSpecific(Y, VEC_CLASSID, 5);
795316643e7SJed Brown 
7969566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
7979566063dSJacob Faibussowitsch   PetscCall(DMTSGetIFunction(dm, &ifunction, &ctx));
7989566063dSJacob Faibussowitsch   PetscCall(DMTSGetRHSFunction(dm, &rhsfunction, NULL));
79924989b8cSPeter Brune 
8003c633725SBarry Smith   PetscCheck(rhsfunction || ifunction, PetscObjectComm((PetscObject)ts), PETSC_ERR_USER, "Must call TSSetRHSFunction() and / or TSSetIFunction()");
801d90be118SSean Farley 
8029566063dSJacob Faibussowitsch   PetscCall(PetscLogEventBegin(TS_FunctionEval, ts, U, Udot, Y));
80324989b8cSPeter Brune   if (ifunction) {
804792fecdfSBarry Smith     PetscCallBack("TS callback implicit function", (*ifunction)(ts, t, U, Udot, Y, ctx));
805a6ab3590SBarry Smith     ts->ifuncs++;
806214bc6a2SJed Brown   }
807214bc6a2SJed Brown   if (imex) {
8081e66621cSBarry Smith     if (!ifunction) PetscCall(VecCopy(Udot, Y));
80924989b8cSPeter Brune   } else if (rhsfunction) {
81024989b8cSPeter Brune     if (ifunction) {
811214bc6a2SJed Brown       Vec Frhs;
8129566063dSJacob Faibussowitsch       PetscCall(TSGetRHSVec_Private(ts, &Frhs));
8139566063dSJacob Faibussowitsch       PetscCall(TSComputeRHSFunction(ts, t, U, Frhs));
8149566063dSJacob Faibussowitsch       PetscCall(VecAXPY(Y, -1, Frhs));
8152dd45cf8SJed Brown     } else {
8169566063dSJacob Faibussowitsch       PetscCall(TSComputeRHSFunction(ts, t, U, Y));
8179566063dSJacob Faibussowitsch       PetscCall(VecAYPX(Y, -1, Udot));
818316643e7SJed Brown     }
8194a6899ffSJed Brown   }
8209566063dSJacob Faibussowitsch   PetscCall(PetscLogEventEnd(TS_FunctionEval, ts, U, Udot, Y));
821316643e7SJed Brown   PetscFunctionReturn(0);
822316643e7SJed Brown }
823316643e7SJed Brown 
824cfa8a9a2SHong Zhang /*
825cfa8a9a2SHong Zhang    TSRecoverRHSJacobian - Recover the Jacobian matrix so that one can call TSComputeRHSJacobian() on it.
826cfa8a9a2SHong Zhang 
827cfa8a9a2SHong Zhang    Note:
828cfa8a9a2SHong Zhang    This routine is needed when one switches from TSComputeIJacobian() to TSComputeRHSJacobian() because the Jacobian matrix may be shifted or scaled in TSComputeIJacobian().
829cfa8a9a2SHong Zhang 
830cfa8a9a2SHong Zhang */
831*d71ae5a4SJacob Faibussowitsch static PetscErrorCode TSRecoverRHSJacobian(TS ts, Mat A, Mat B)
832*d71ae5a4SJacob Faibussowitsch {
833cfa8a9a2SHong Zhang   PetscFunctionBegin;
834cfa8a9a2SHong Zhang   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
8353c633725SBarry Smith   PetscCheck(A == ts->Arhs, PetscObjectComm((PetscObject)ts), PETSC_ERR_SUP, "Invalid Amat");
8363c633725SBarry Smith   PetscCheck(B == ts->Brhs, PetscObjectComm((PetscObject)ts), PETSC_ERR_SUP, "Invalid Bmat");
837cfa8a9a2SHong Zhang 
8381baa6e33SBarry Smith   if (ts->rhsjacobian.shift) PetscCall(MatShift(A, -ts->rhsjacobian.shift));
83948a46eb9SPierre Jolivet   if (ts->rhsjacobian.scale == -1.) PetscCall(MatScale(A, -1));
840cfa8a9a2SHong Zhang   if (B && B == ts->Brhs && A != B) {
8411baa6e33SBarry Smith     if (ts->rhsjacobian.shift) PetscCall(MatShift(B, -ts->rhsjacobian.shift));
8421e66621cSBarry Smith     if (ts->rhsjacobian.scale == -1.) PetscCall(MatScale(B, -1));
843cfa8a9a2SHong Zhang   }
844cfa8a9a2SHong Zhang   ts->rhsjacobian.shift = 0;
845cfa8a9a2SHong Zhang   ts->rhsjacobian.scale = 1.;
846cfa8a9a2SHong Zhang   PetscFunctionReturn(0);
847cfa8a9a2SHong Zhang }
848cfa8a9a2SHong Zhang 
849316643e7SJed Brown /*@
850316643e7SJed Brown    TSComputeIJacobian - Evaluates the Jacobian of the DAE
851316643e7SJed Brown 
852d083f849SBarry Smith    Collective on TS
853316643e7SJed Brown 
854316643e7SJed Brown    Input
855316643e7SJed Brown       Input Parameters:
856316643e7SJed Brown +  ts - the TS context
857316643e7SJed Brown .  t - current timestep
8580910c330SBarry Smith .  U - state vector
8590910c330SBarry Smith .  Udot - time derivative of state vector
860214bc6a2SJed Brown .  shift - shift to apply, see note below
861214bc6a2SJed Brown -  imex - flag indicates if the method is IMEX so that the RHSJacobian should be kept separate
862316643e7SJed Brown 
863316643e7SJed Brown    Output Parameters:
864316643e7SJed Brown +  A - Jacobian matrix
8653565c898SBarry Smith -  B - matrix from which the preconditioner is constructed; often the same as A
866316643e7SJed Brown 
867316643e7SJed Brown    Notes:
8680910c330SBarry Smith    If F(t,U,Udot)=0 is the DAE, the required Jacobian is
869316643e7SJed Brown 
8700910c330SBarry Smith    dF/dU + shift*dF/dUdot
871316643e7SJed Brown 
872316643e7SJed Brown    Most users should not need to explicitly call this routine, as it
873316643e7SJed Brown    is used internally within the nonlinear solvers.
874316643e7SJed Brown 
875316643e7SJed Brown    Level: developer
876316643e7SJed Brown 
877db781477SPatrick Sanan .seealso: `TSSetIJacobian()`
87863495f91SJed Brown @*/
879*d71ae5a4SJacob Faibussowitsch PetscErrorCode TSComputeIJacobian(TS ts, PetscReal t, Vec U, Vec Udot, PetscReal shift, Mat A, Mat B, PetscBool imex)
880*d71ae5a4SJacob Faibussowitsch {
88124989b8cSPeter Brune   TSIJacobian   ijacobian;
88224989b8cSPeter Brune   TSRHSJacobian rhsjacobian;
88324989b8cSPeter Brune   DM            dm;
88424989b8cSPeter Brune   void         *ctx;
885316643e7SJed Brown 
886316643e7SJed Brown   PetscFunctionBegin;
8870700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
8880910c330SBarry Smith   PetscValidHeaderSpecific(U, VEC_CLASSID, 3);
8890910c330SBarry Smith   PetscValidHeaderSpecific(Udot, VEC_CLASSID, 4);
890316643e7SJed Brown   PetscValidPointer(A, 6);
89194ab13aaSBarry Smith   PetscValidHeaderSpecific(A, MAT_CLASSID, 6);
892316643e7SJed Brown   PetscValidPointer(B, 7);
89394ab13aaSBarry Smith   PetscValidHeaderSpecific(B, MAT_CLASSID, 7);
89424989b8cSPeter Brune 
8959566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
8969566063dSJacob Faibussowitsch   PetscCall(DMTSGetIJacobian(dm, &ijacobian, &ctx));
8979566063dSJacob Faibussowitsch   PetscCall(DMTSGetRHSJacobian(dm, &rhsjacobian, NULL));
89824989b8cSPeter Brune 
8993c633725SBarry Smith   PetscCheck(rhsjacobian || ijacobian, PetscObjectComm((PetscObject)ts), PETSC_ERR_USER, "Must call TSSetRHSJacobian() and / or TSSetIJacobian()");
900316643e7SJed Brown 
9019566063dSJacob Faibussowitsch   PetscCall(PetscLogEventBegin(TS_JacobianEval, ts, U, A, B));
90224989b8cSPeter Brune   if (ijacobian) {
903792fecdfSBarry Smith     PetscCallBack("TS callback implicit Jacobian", (*ijacobian)(ts, t, U, Udot, shift, A, B, ctx));
904a6ab3590SBarry Smith     ts->ijacs++;
9054a6899ffSJed Brown   }
906214bc6a2SJed Brown   if (imex) {
907b5abc632SBarry Smith     if (!ijacobian) { /* system was written as Udot = G(t,U) */
9084c26be97Sstefano_zampini       PetscBool assembled;
909971015bcSStefano Zampini       if (rhsjacobian) {
910971015bcSStefano Zampini         Mat Arhs = NULL;
9119566063dSJacob Faibussowitsch         PetscCall(TSGetRHSMats_Private(ts, &Arhs, NULL));
912971015bcSStefano Zampini         if (A == Arhs) {
9133c633725SBarry 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 */
914971015bcSStefano Zampini           ts->rhsjacobian.time = PETSC_MIN_REAL;
915971015bcSStefano Zampini         }
916971015bcSStefano Zampini       }
9179566063dSJacob Faibussowitsch       PetscCall(MatZeroEntries(A));
9189566063dSJacob Faibussowitsch       PetscCall(MatAssembled(A, &assembled));
9194c26be97Sstefano_zampini       if (!assembled) {
9209566063dSJacob Faibussowitsch         PetscCall(MatAssemblyBegin(A, MAT_FINAL_ASSEMBLY));
9219566063dSJacob Faibussowitsch         PetscCall(MatAssemblyEnd(A, MAT_FINAL_ASSEMBLY));
9224c26be97Sstefano_zampini       }
9239566063dSJacob Faibussowitsch       PetscCall(MatShift(A, shift));
92494ab13aaSBarry Smith       if (A != B) {
9259566063dSJacob Faibussowitsch         PetscCall(MatZeroEntries(B));
9269566063dSJacob Faibussowitsch         PetscCall(MatAssembled(B, &assembled));
9274c26be97Sstefano_zampini         if (!assembled) {
9289566063dSJacob Faibussowitsch           PetscCall(MatAssemblyBegin(B, MAT_FINAL_ASSEMBLY));
9299566063dSJacob Faibussowitsch           PetscCall(MatAssemblyEnd(B, MAT_FINAL_ASSEMBLY));
9304c26be97Sstefano_zampini         }
9319566063dSJacob Faibussowitsch         PetscCall(MatShift(B, shift));
932214bc6a2SJed Brown       }
933214bc6a2SJed Brown     }
934214bc6a2SJed Brown   } else {
935e1244c69SJed Brown     Mat Arhs = NULL, Brhs = NULL;
9361e66621cSBarry Smith 
9371e66621cSBarry Smith     /* RHSJacobian needs to be converted to part of IJacobian if exists */
9381e66621cSBarry Smith     if (rhsjacobian) PetscCall(TSGetRHSMats_Private(ts, &Arhs, &Brhs));
939e8b1e424SHong Zhang     if (Arhs == A) { /* No IJacobian matrix, so we only have the RHS matrix */
940e8b1e424SHong Zhang       PetscObjectState Ustate;
941e8b1e424SHong Zhang       PetscObjectId    Uid;
942e8b1e424SHong Zhang       TSRHSFunction    rhsfunction;
943e8b1e424SHong Zhang 
9449566063dSJacob Faibussowitsch       PetscCall(DMTSGetRHSFunction(dm, &rhsfunction, NULL));
9459566063dSJacob Faibussowitsch       PetscCall(PetscObjectStateGet((PetscObject)U, &Ustate));
9469566063dSJacob Faibussowitsch       PetscCall(PetscObjectGetId((PetscObject)U, &Uid));
9479371c9d4SSatish Balay       if ((rhsjacobian == TSComputeRHSJacobianConstant || (ts->rhsjacobian.time == t && (ts->problem_type == TS_LINEAR || (ts->rhsjacobian.Xid == Uid && ts->rhsjacobian.Xstate == Ustate)) && rhsfunction != TSComputeRHSFunctionLinear)) &&
9489371c9d4SSatish Balay           ts->rhsjacobian.scale == -1.) {                      /* No need to recompute RHSJacobian */
9499566063dSJacob Faibussowitsch         PetscCall(MatShift(A, shift - ts->rhsjacobian.shift)); /* revert the old shift and add the new shift with a single call to MatShift */
9501e66621cSBarry Smith         if (A != B) PetscCall(MatShift(B, shift - ts->rhsjacobian.shift));
951e8b1e424SHong Zhang       } else {
9523565c898SBarry Smith         PetscBool flg;
953e8b1e424SHong Zhang 
954e8b1e424SHong Zhang         if (ts->rhsjacobian.reuse) { /* Undo the damage */
955e8b1e424SHong Zhang           /* MatScale has a short path for this case.
956e8b1e424SHong Zhang              However, this code path is taken the first time TSComputeRHSJacobian is called
957e8b1e424SHong Zhang              and the matrices have not been assembled yet */
9589566063dSJacob Faibussowitsch           PetscCall(TSRecoverRHSJacobian(ts, A, B));
959e8b1e424SHong Zhang         }
9609566063dSJacob Faibussowitsch         PetscCall(TSComputeRHSJacobian(ts, t, U, A, B));
9619566063dSJacob Faibussowitsch         PetscCall(SNESGetUseMatrixFree(ts->snes, NULL, &flg));
9623565c898SBarry Smith         /* since -snes_mf_operator uses the full SNES function it does not need to be shifted or scaled here */
9633565c898SBarry Smith         if (!flg) {
9649566063dSJacob Faibussowitsch           PetscCall(MatScale(A, -1));
9659566063dSJacob Faibussowitsch           PetscCall(MatShift(A, shift));
9663565c898SBarry Smith         }
96794ab13aaSBarry Smith         if (A != B) {
9689566063dSJacob Faibussowitsch           PetscCall(MatScale(B, -1));
9699566063dSJacob Faibussowitsch           PetscCall(MatShift(B, shift));
970316643e7SJed Brown         }
971e8b1e424SHong Zhang       }
972e8b1e424SHong Zhang       ts->rhsjacobian.scale = -1;
973e8b1e424SHong Zhang       ts->rhsjacobian.shift = shift;
974d60b7d5cSBarry Smith     } else if (Arhs) {  /* Both IJacobian and RHSJacobian */
975e1244c69SJed Brown       if (!ijacobian) { /* No IJacobian provided, but we have a separate RHS matrix */
9769566063dSJacob Faibussowitsch         PetscCall(MatZeroEntries(A));
9779566063dSJacob Faibussowitsch         PetscCall(MatShift(A, shift));
97894ab13aaSBarry Smith         if (A != B) {
9799566063dSJacob Faibussowitsch           PetscCall(MatZeroEntries(B));
9809566063dSJacob Faibussowitsch           PetscCall(MatShift(B, shift));
981214bc6a2SJed Brown         }
982316643e7SJed Brown       }
9839566063dSJacob Faibussowitsch       PetscCall(TSComputeRHSJacobian(ts, t, U, Arhs, Brhs));
9849566063dSJacob Faibussowitsch       PetscCall(MatAXPY(A, -1, Arhs, ts->axpy_pattern));
9851e66621cSBarry Smith       if (A != B) PetscCall(MatAXPY(B, -1, Brhs, ts->axpy_pattern));
986316643e7SJed Brown     }
987316643e7SJed Brown   }
9889566063dSJacob Faibussowitsch   PetscCall(PetscLogEventEnd(TS_JacobianEval, ts, U, A, B));
989316643e7SJed Brown   PetscFunctionReturn(0);
990316643e7SJed Brown }
991316643e7SJed Brown 
992d763cef2SBarry Smith /*@C
993d763cef2SBarry Smith     TSSetRHSFunction - Sets the routine for evaluating the function,
994b5abc632SBarry Smith     where U_t = G(t,u).
995d763cef2SBarry Smith 
9963f9fe445SBarry Smith     Logically Collective on TS
997d763cef2SBarry Smith 
998d763cef2SBarry Smith     Input Parameters:
999d763cef2SBarry Smith +   ts - the TS context obtained from TSCreate()
10000298fd71SBarry Smith .   r - vector to put the computed right hand side (or NULL to have it created)
1001d763cef2SBarry Smith .   f - routine for evaluating the right-hand-side function
1002d763cef2SBarry Smith -   ctx - [optional] user-defined context for private data for the
10030298fd71SBarry Smith           function evaluation routine (may be NULL)
1004d763cef2SBarry Smith 
1005a96d6ef6SBarry Smith     Calling sequence of f:
1006a96d6ef6SBarry Smith $     PetscErrorCode f(TS ts,PetscReal t,Vec u,Vec F,void *ctx);
1007d763cef2SBarry Smith 
1008a96d6ef6SBarry Smith +   ts - timestep context
1009a96d6ef6SBarry Smith .   t - current timestep
1010d763cef2SBarry Smith .   u - input vector
1011d763cef2SBarry Smith .   F - function vector
1012d763cef2SBarry Smith -   ctx - [optional] user-defined function context
1013d763cef2SBarry Smith 
1014d763cef2SBarry Smith     Level: beginner
1015d763cef2SBarry Smith 
101695452b02SPatrick Sanan     Notes:
101795452b02SPatrick Sanan     You must call this function or TSSetIFunction() to define your ODE. You cannot use this function when solving a DAE.
10182bbac0d3SBarry Smith 
1019db781477SPatrick Sanan .seealso: `TSSetRHSJacobian()`, `TSSetIJacobian()`, `TSSetIFunction()`
1020d763cef2SBarry Smith @*/
1021*d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetRHSFunction(TS ts, Vec r, PetscErrorCode (*f)(TS, PetscReal, Vec, Vec, void *), void *ctx)
1022*d71ae5a4SJacob Faibussowitsch {
1023089b2837SJed Brown   SNES snes;
10240298fd71SBarry Smith   Vec  ralloc = NULL;
102524989b8cSPeter Brune   DM   dm;
1026d763cef2SBarry Smith 
1027089b2837SJed Brown   PetscFunctionBegin;
10280700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
1029ca94891dSJed Brown   if (r) PetscValidHeaderSpecific(r, VEC_CLASSID, 2);
103024989b8cSPeter Brune 
10319566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
10329566063dSJacob Faibussowitsch   PetscCall(DMTSSetRHSFunction(dm, f, ctx));
10339566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts, &snes));
1034e856ceecSJed Brown   if (!r && !ts->dm && ts->vec_sol) {
10359566063dSJacob Faibussowitsch     PetscCall(VecDuplicate(ts->vec_sol, &ralloc));
1036e856ceecSJed Brown     r = ralloc;
1037e856ceecSJed Brown   }
10389566063dSJacob Faibussowitsch   PetscCall(SNESSetFunction(snes, r, SNESTSFormFunction, ts));
10399566063dSJacob Faibussowitsch   PetscCall(VecDestroy(&ralloc));
1040d763cef2SBarry Smith   PetscFunctionReturn(0);
1041d763cef2SBarry Smith }
1042d763cef2SBarry Smith 
1043ef20d060SBarry Smith /*@C
1044abd5a294SJed Brown     TSSetSolutionFunction - Provide a function that computes the solution of the ODE or DAE
1045ef20d060SBarry Smith 
1046ef20d060SBarry Smith     Logically Collective on TS
1047ef20d060SBarry Smith 
1048ef20d060SBarry Smith     Input Parameters:
1049ef20d060SBarry Smith +   ts - the TS context obtained from TSCreate()
1050ef20d060SBarry Smith .   f - routine for evaluating the solution
1051ef20d060SBarry Smith -   ctx - [optional] user-defined context for private data for the
10520298fd71SBarry Smith           function evaluation routine (may be NULL)
1053ef20d060SBarry Smith 
1054a96d6ef6SBarry Smith     Calling sequence of f:
1055a96d6ef6SBarry Smith $     PetscErrorCode f(TS ts,PetscReal t,Vec u,void *ctx);
1056ef20d060SBarry Smith 
1057ef20d060SBarry Smith +   t - current timestep
1058ef20d060SBarry Smith .   u - output vector
1059ef20d060SBarry Smith -   ctx - [optional] user-defined function context
1060ef20d060SBarry Smith 
10610ed3bfb6SBarry Smith     Options Database:
10620ed3bfb6SBarry Smith +  -ts_monitor_lg_error - create a graphical monitor of error history, requires user to have provided TSSetSolutionFunction()
10630ed3bfb6SBarry Smith -  -ts_monitor_draw_error - Monitor error graphically, requires user to have provided TSSetSolutionFunction()
10640ed3bfb6SBarry Smith 
1065abd5a294SJed Brown     Notes:
1066abd5a294SJed Brown     This routine is used for testing accuracy of time integration schemes when you already know the solution.
1067abd5a294SJed Brown     If analytic solutions are not known for your system, consider using the Method of Manufactured Solutions to
1068abd5a294SJed Brown     create closed-form solutions with non-physical forcing terms.
1069abd5a294SJed Brown 
10704f09c107SBarry Smith     For low-dimensional problems solved in serial, such as small discrete systems, TSMonitorLGError() can be used to monitor the error history.
1071abd5a294SJed Brown 
1072ef20d060SBarry Smith     Level: beginner
1073ef20d060SBarry Smith 
1074db781477SPatrick Sanan .seealso: `TSSetRHSJacobian()`, `TSSetIJacobian()`, `TSComputeSolutionFunction()`, `TSSetForcingFunction()`, `TSSetSolution()`, `TSGetSolution()`, `TSMonitorLGError()`, `TSMonitorDrawError()`
1075ef20d060SBarry Smith @*/
1076*d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetSolutionFunction(TS ts, PetscErrorCode (*f)(TS, PetscReal, Vec, void *), void *ctx)
1077*d71ae5a4SJacob Faibussowitsch {
1078ef20d060SBarry Smith   DM dm;
1079ef20d060SBarry Smith 
1080ef20d060SBarry Smith   PetscFunctionBegin;
1081ef20d060SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
10829566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
10839566063dSJacob Faibussowitsch   PetscCall(DMTSSetSolutionFunction(dm, f, ctx));
1084ef20d060SBarry Smith   PetscFunctionReturn(0);
1085ef20d060SBarry Smith }
1086ef20d060SBarry Smith 
10879b7cd975SBarry Smith /*@C
10889b7cd975SBarry Smith     TSSetForcingFunction - Provide a function that computes a forcing term for a ODE or PDE
10899b7cd975SBarry Smith 
10909b7cd975SBarry Smith     Logically Collective on TS
10919b7cd975SBarry Smith 
10929b7cd975SBarry Smith     Input Parameters:
10939b7cd975SBarry Smith +   ts - the TS context obtained from TSCreate()
1094e162b725SBarry Smith .   func - routine for evaluating the forcing function
10959b7cd975SBarry Smith -   ctx - [optional] user-defined context for private data for the
10960298fd71SBarry Smith           function evaluation routine (may be NULL)
10979b7cd975SBarry Smith 
10989b7cd975SBarry Smith     Calling sequence of func:
10996bc98fa9SBarry Smith $     PetscErrorCode func (TS ts,PetscReal t,Vec f,void *ctx);
11009b7cd975SBarry Smith 
11019b7cd975SBarry Smith +   t - current timestep
1102e162b725SBarry Smith .   f - output vector
11039b7cd975SBarry Smith -   ctx - [optional] user-defined function context
11049b7cd975SBarry Smith 
11059b7cd975SBarry Smith     Notes:
11069b7cd975SBarry Smith     This routine is useful for testing accuracy of time integration schemes when using the Method of Manufactured Solutions to
1107e162b725SBarry 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
1108e162b725SBarry Smith     definition of the problem you are solving and hence possibly introducing bugs.
1109e162b725SBarry Smith 
1110e162b725SBarry Smith     This replaces the ODE F(u,u_t,t) = 0 the TS is solving with F(u,u_t,t) - func(t) = 0
1111e162b725SBarry Smith 
1112e162b725SBarry 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
1113e162b725SBarry Smith     parameters can be passed in the ctx variable.
11149b7cd975SBarry Smith 
11159b7cd975SBarry Smith     For low-dimensional problems solved in serial, such as small discrete systems, TSMonitorLGError() can be used to monitor the error history.
11169b7cd975SBarry Smith 
11179b7cd975SBarry Smith     Level: beginner
11189b7cd975SBarry Smith 
1119db781477SPatrick Sanan .seealso: `TSSetRHSJacobian()`, `TSSetIJacobian()`, `TSComputeSolutionFunction()`, `TSSetSolutionFunction()`
11209b7cd975SBarry Smith @*/
1121*d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetForcingFunction(TS ts, TSForcingFunction func, void *ctx)
1122*d71ae5a4SJacob Faibussowitsch {
11239b7cd975SBarry Smith   DM dm;
11249b7cd975SBarry Smith 
11259b7cd975SBarry Smith   PetscFunctionBegin;
11269b7cd975SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
11279566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
11289566063dSJacob Faibussowitsch   PetscCall(DMTSSetForcingFunction(dm, func, ctx));
11299b7cd975SBarry Smith   PetscFunctionReturn(0);
11309b7cd975SBarry Smith }
11319b7cd975SBarry Smith 
1132d763cef2SBarry Smith /*@C
1133f7ab8db6SBarry Smith    TSSetRHSJacobian - Sets the function to compute the Jacobian of G,
1134b5abc632SBarry Smith    where U_t = G(U,t), as well as the location to store the matrix.
1135d763cef2SBarry Smith 
11363f9fe445SBarry Smith    Logically Collective on TS
1137d763cef2SBarry Smith 
1138d763cef2SBarry Smith    Input Parameters:
1139d763cef2SBarry Smith +  ts  - the TS context obtained from TSCreate()
1140e5d3d808SBarry Smith .  Amat - (approximate) Jacobian matrix
1141e5d3d808SBarry Smith .  Pmat - matrix from which preconditioner is to be constructed (usually the same as Amat)
1142d763cef2SBarry Smith .  f   - the Jacobian evaluation routine
1143d763cef2SBarry Smith -  ctx - [optional] user-defined context for private data for the
11440298fd71SBarry Smith          Jacobian evaluation routine (may be NULL)
1145d763cef2SBarry Smith 
1146f7ab8db6SBarry Smith    Calling sequence of f:
1147a96d6ef6SBarry Smith $     PetscErrorCode f(TS ts,PetscReal t,Vec u,Mat A,Mat B,void *ctx);
1148d763cef2SBarry Smith 
1149d763cef2SBarry Smith +  t - current timestep
1150d763cef2SBarry Smith .  u - input vector
1151e5d3d808SBarry Smith .  Amat - (approximate) Jacobian matrix
1152e5d3d808SBarry Smith .  Pmat - matrix from which preconditioner is to be constructed (usually the same as Amat)
1153d763cef2SBarry Smith -  ctx - [optional] user-defined context for matrix evaluation routine
1154d763cef2SBarry Smith 
11556cd88445SBarry Smith    Notes:
11566cd88445SBarry Smith    You must set all the diagonal entries of the matrices, if they are zero you must still set them with a zero value
11576cd88445SBarry Smith 
11586cd88445SBarry Smith    The TS solver may modify the nonzero structure and the entries of the matrices Amat and Pmat between the calls to f()
1159ca5f011dSBarry Smith    You should not assume the values are the same in the next call to f() as you set them in the previous call.
1160d763cef2SBarry Smith 
1161d763cef2SBarry Smith    Level: beginner
1162d763cef2SBarry Smith 
1163db781477SPatrick Sanan .seealso: `SNESComputeJacobianDefaultColor()`, `TSSetRHSFunction()`, `TSRHSJacobianSetReuse()`, `TSSetIJacobian()`
1164d763cef2SBarry Smith 
1165d763cef2SBarry Smith @*/
1166*d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetRHSJacobian(TS ts, Mat Amat, Mat Pmat, TSRHSJacobian f, void *ctx)
1167*d71ae5a4SJacob Faibussowitsch {
1168089b2837SJed Brown   SNES        snes;
116924989b8cSPeter Brune   DM          dm;
117024989b8cSPeter Brune   TSIJacobian ijacobian;
1171277b19d0SLisandro Dalcin 
1172d763cef2SBarry Smith   PetscFunctionBegin;
11730700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
1174e5d3d808SBarry Smith   if (Amat) PetscValidHeaderSpecific(Amat, MAT_CLASSID, 2);
1175e5d3d808SBarry Smith   if (Pmat) PetscValidHeaderSpecific(Pmat, MAT_CLASSID, 3);
1176e5d3d808SBarry Smith   if (Amat) PetscCheckSameComm(ts, 1, Amat, 2);
1177e5d3d808SBarry Smith   if (Pmat) PetscCheckSameComm(ts, 1, Pmat, 3);
1178d763cef2SBarry Smith 
11799566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
11809566063dSJacob Faibussowitsch   PetscCall(DMTSSetRHSJacobian(dm, f, ctx));
11819566063dSJacob Faibussowitsch   PetscCall(DMTSGetIJacobian(dm, &ijacobian, NULL));
11829566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts, &snes));
11831e66621cSBarry Smith   if (!ijacobian) PetscCall(SNESSetJacobian(snes, Amat, Pmat, SNESTSFormJacobian, ts));
1184e5d3d808SBarry Smith   if (Amat) {
11859566063dSJacob Faibussowitsch     PetscCall(PetscObjectReference((PetscObject)Amat));
11869566063dSJacob Faibussowitsch     PetscCall(MatDestroy(&ts->Arhs));
1187e5d3d808SBarry Smith     ts->Arhs = Amat;
11880e4ef248SJed Brown   }
1189e5d3d808SBarry Smith   if (Pmat) {
11909566063dSJacob Faibussowitsch     PetscCall(PetscObjectReference((PetscObject)Pmat));
11919566063dSJacob Faibussowitsch     PetscCall(MatDestroy(&ts->Brhs));
1192e5d3d808SBarry Smith     ts->Brhs = Pmat;
11930e4ef248SJed Brown   }
1194d763cef2SBarry Smith   PetscFunctionReturn(0);
1195d763cef2SBarry Smith }
1196d763cef2SBarry Smith 
1197316643e7SJed Brown /*@C
1198b5abc632SBarry Smith    TSSetIFunction - Set the function to compute F(t,U,U_t) where F() = 0 is the DAE to be solved.
1199316643e7SJed Brown 
12003f9fe445SBarry Smith    Logically Collective on TS
1201316643e7SJed Brown 
1202316643e7SJed Brown    Input Parameters:
1203316643e7SJed Brown +  ts  - the TS context obtained from TSCreate()
12040298fd71SBarry Smith .  r   - vector to hold the residual (or NULL to have it created internally)
1205316643e7SJed Brown .  f   - the function evaluation routine
12060298fd71SBarry Smith -  ctx - user-defined context for private data for the function evaluation routine (may be NULL)
1207316643e7SJed Brown 
1208316643e7SJed Brown    Calling sequence of f:
12096bc98fa9SBarry Smith $     PetscErrorCode f(TS ts,PetscReal t,Vec u,Vec u_t,Vec F,ctx);
1210316643e7SJed Brown 
1211316643e7SJed Brown +  t   - time at step/stage being solved
1212316643e7SJed Brown .  u   - state vector
1213316643e7SJed Brown .  u_t - time derivative of state vector
1214316643e7SJed Brown .  F   - function vector
1215316643e7SJed Brown -  ctx - [optional] user-defined context for matrix evaluation routine
1216316643e7SJed Brown 
1217316643e7SJed Brown    Important:
12182bbac0d3SBarry Smith    The user MUST call either this routine or TSSetRHSFunction() to define the ODE.  When solving DAEs you must use this function.
1219316643e7SJed Brown 
1220316643e7SJed Brown    Level: beginner
1221316643e7SJed Brown 
1222db781477SPatrick Sanan .seealso: `TSSetRHSJacobian()`, `TSSetRHSFunction()`, `TSSetIJacobian()`
1223316643e7SJed Brown @*/
1224*d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetIFunction(TS ts, Vec r, TSIFunction f, void *ctx)
1225*d71ae5a4SJacob Faibussowitsch {
1226089b2837SJed Brown   SNES snes;
122751699248SLisandro Dalcin   Vec  ralloc = NULL;
122824989b8cSPeter Brune   DM   dm;
1229316643e7SJed Brown 
1230316643e7SJed Brown   PetscFunctionBegin;
12310700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
123251699248SLisandro Dalcin   if (r) PetscValidHeaderSpecific(r, VEC_CLASSID, 2);
123324989b8cSPeter Brune 
12349566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
12359566063dSJacob Faibussowitsch   PetscCall(DMTSSetIFunction(dm, f, ctx));
123624989b8cSPeter Brune 
12379566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts, &snes));
123851699248SLisandro Dalcin   if (!r && !ts->dm && ts->vec_sol) {
12399566063dSJacob Faibussowitsch     PetscCall(VecDuplicate(ts->vec_sol, &ralloc));
124051699248SLisandro Dalcin     r = ralloc;
1241e856ceecSJed Brown   }
12429566063dSJacob Faibussowitsch   PetscCall(SNESSetFunction(snes, r, SNESTSFormFunction, ts));
12439566063dSJacob Faibussowitsch   PetscCall(VecDestroy(&ralloc));
1244089b2837SJed Brown   PetscFunctionReturn(0);
1245089b2837SJed Brown }
1246089b2837SJed Brown 
1247089b2837SJed Brown /*@C
1248a5b23f4aSJose E. Roman    TSGetIFunction - Returns the vector where the implicit residual is stored and the function/context to compute it.
1249089b2837SJed Brown 
1250089b2837SJed Brown    Not Collective
1251089b2837SJed Brown 
1252089b2837SJed Brown    Input Parameter:
1253089b2837SJed Brown .  ts - the TS context
1254089b2837SJed Brown 
1255d8d19677SJose E. Roman    Output Parameters:
12560298fd71SBarry Smith +  r - vector to hold residual (or NULL)
12570298fd71SBarry Smith .  func - the function to compute residual (or NULL)
12580298fd71SBarry Smith -  ctx - the function context (or NULL)
1259089b2837SJed Brown 
1260089b2837SJed Brown    Level: advanced
1261089b2837SJed Brown 
1262db781477SPatrick Sanan .seealso: `TSSetIFunction()`, `SNESGetFunction()`
1263089b2837SJed Brown @*/
1264*d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetIFunction(TS ts, Vec *r, TSIFunction *func, void **ctx)
1265*d71ae5a4SJacob Faibussowitsch {
1266089b2837SJed Brown   SNES snes;
126724989b8cSPeter Brune   DM   dm;
1268089b2837SJed Brown 
1269089b2837SJed Brown   PetscFunctionBegin;
1270089b2837SJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
12719566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts, &snes));
12729566063dSJacob Faibussowitsch   PetscCall(SNESGetFunction(snes, r, NULL, NULL));
12739566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
12749566063dSJacob Faibussowitsch   PetscCall(DMTSGetIFunction(dm, func, ctx));
1275089b2837SJed Brown   PetscFunctionReturn(0);
1276089b2837SJed Brown }
1277089b2837SJed Brown 
1278089b2837SJed Brown /*@C
1279089b2837SJed Brown    TSGetRHSFunction - Returns the vector where the right hand side is stored and the function/context to compute it.
1280089b2837SJed Brown 
1281089b2837SJed Brown    Not Collective
1282089b2837SJed Brown 
1283089b2837SJed Brown    Input Parameter:
1284089b2837SJed Brown .  ts - the TS context
1285089b2837SJed Brown 
1286d8d19677SJose E. Roman    Output Parameters:
12870298fd71SBarry Smith +  r - vector to hold computed right hand side (or NULL)
12880298fd71SBarry Smith .  func - the function to compute right hand side (or NULL)
12890298fd71SBarry Smith -  ctx - the function context (or NULL)
1290089b2837SJed Brown 
1291089b2837SJed Brown    Level: advanced
1292089b2837SJed Brown 
1293db781477SPatrick Sanan .seealso: `TSSetRHSFunction()`, `SNESGetFunction()`
1294089b2837SJed Brown @*/
1295*d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetRHSFunction(TS ts, Vec *r, TSRHSFunction *func, void **ctx)
1296*d71ae5a4SJacob Faibussowitsch {
1297089b2837SJed Brown   SNES snes;
129824989b8cSPeter Brune   DM   dm;
1299089b2837SJed Brown 
1300089b2837SJed Brown   PetscFunctionBegin;
1301089b2837SJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
13029566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts, &snes));
13039566063dSJacob Faibussowitsch   PetscCall(SNESGetFunction(snes, r, NULL, NULL));
13049566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
13059566063dSJacob Faibussowitsch   PetscCall(DMTSGetRHSFunction(dm, func, ctx));
1306316643e7SJed Brown   PetscFunctionReturn(0);
1307316643e7SJed Brown }
1308316643e7SJed Brown 
1309316643e7SJed Brown /*@C
1310a4f0a591SBarry Smith    TSSetIJacobian - Set the function to compute the matrix dF/dU + a*dF/dU_t where F(t,U,U_t) is the function
1311ae8867d6SBarry Smith         provided with TSSetIFunction().
1312316643e7SJed Brown 
13133f9fe445SBarry Smith    Logically Collective on TS
1314316643e7SJed Brown 
1315316643e7SJed Brown    Input Parameters:
1316316643e7SJed Brown +  ts  - the TS context obtained from TSCreate()
1317e5d3d808SBarry Smith .  Amat - (approximate) Jacobian matrix
1318e5d3d808SBarry Smith .  Pmat - matrix used to compute preconditioner (usually the same as Amat)
1319316643e7SJed Brown .  f   - the Jacobian evaluation routine
13200298fd71SBarry Smith -  ctx - user-defined context for private data for the Jacobian evaluation routine (may be NULL)
1321316643e7SJed Brown 
1322316643e7SJed Brown    Calling sequence of f:
13236bc98fa9SBarry Smith $    PetscErrorCode f(TS ts,PetscReal t,Vec U,Vec U_t,PetscReal a,Mat Amat,Mat Pmat,void *ctx);
1324316643e7SJed Brown 
1325316643e7SJed Brown +  t    - time at step/stage being solved
13261b4a444bSJed Brown .  U    - state vector
13271b4a444bSJed Brown .  U_t  - time derivative of state vector
1328316643e7SJed Brown .  a    - shift
1329e5d3d808SBarry Smith .  Amat - (approximate) Jacobian of F(t,U,W+a*U), equivalent to dF/dU + a*dF/dU_t
1330e5d3d808SBarry Smith .  Pmat - matrix used for constructing preconditioner, usually the same as Amat
1331316643e7SJed Brown -  ctx  - [optional] user-defined context for matrix evaluation routine
1332316643e7SJed Brown 
1333316643e7SJed Brown    Notes:
1334e5d3d808SBarry Smith    The matrices Amat and Pmat are exactly the matrices that are used by SNES for the nonlinear solve.
1335316643e7SJed Brown 
1336895c21f2SBarry Smith    If you know the operator Amat has a null space you can use MatSetNullSpace() and MatSetTransposeNullSpace() to supply the null
1337895c21f2SBarry Smith    space to Amat and the KSP solvers will automatically use that null space as needed during the solution process.
1338895c21f2SBarry Smith 
1339a4f0a591SBarry Smith    The matrix dF/dU + a*dF/dU_t you provide turns out to be
1340b5abc632SBarry Smith    the Jacobian of F(t,U,W+a*U) where F(t,U,U_t) = 0 is the DAE to be solved.
1341a4f0a591SBarry Smith    The time integrator internally approximates U_t by W+a*U where the positive "shift"
1342a4f0a591SBarry Smith    a and vector W depend on the integration method, step size, and past states. For example with
1343a4f0a591SBarry Smith    the backward Euler method a = 1/dt and W = -a*U(previous timestep) so
1344a4f0a591SBarry Smith    W + a*U = a*(U - U(previous timestep)) = (U - U(previous timestep))/dt
1345a4f0a591SBarry Smith 
13466cd88445SBarry Smith    You must set all the diagonal entries of the matrices, if they are zero you must still set them with a zero value
13476cd88445SBarry Smith 
13486cd88445SBarry Smith    The TS solver may modify the nonzero structure and the entries of the matrices Amat and Pmat between the calls to f()
1349ca5f011dSBarry Smith    You should not assume the values are the same in the next call to f() as you set them in the previous call.
1350ca5f011dSBarry Smith 
1351316643e7SJed Brown    Level: beginner
1352316643e7SJed Brown 
1353db781477SPatrick Sanan .seealso: `TSSetIFunction()`, `TSSetRHSJacobian()`, `SNESComputeJacobianDefaultColor()`, `SNESComputeJacobianDefault()`, `TSSetRHSFunction()`
1354316643e7SJed Brown 
1355316643e7SJed Brown @*/
1356*d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetIJacobian(TS ts, Mat Amat, Mat Pmat, TSIJacobian f, void *ctx)
1357*d71ae5a4SJacob Faibussowitsch {
1358089b2837SJed Brown   SNES snes;
135924989b8cSPeter Brune   DM   dm;
1360316643e7SJed Brown 
1361316643e7SJed Brown   PetscFunctionBegin;
13620700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
1363e5d3d808SBarry Smith   if (Amat) PetscValidHeaderSpecific(Amat, MAT_CLASSID, 2);
1364e5d3d808SBarry Smith   if (Pmat) PetscValidHeaderSpecific(Pmat, MAT_CLASSID, 3);
1365e5d3d808SBarry Smith   if (Amat) PetscCheckSameComm(ts, 1, Amat, 2);
1366e5d3d808SBarry Smith   if (Pmat) PetscCheckSameComm(ts, 1, Pmat, 3);
136724989b8cSPeter Brune 
13689566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
13699566063dSJacob Faibussowitsch   PetscCall(DMTSSetIJacobian(dm, f, ctx));
137024989b8cSPeter Brune 
13719566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts, &snes));
13729566063dSJacob Faibussowitsch   PetscCall(SNESSetJacobian(snes, Amat, Pmat, SNESTSFormJacobian, ts));
1373316643e7SJed Brown   PetscFunctionReturn(0);
1374316643e7SJed Brown }
1375316643e7SJed Brown 
1376e1244c69SJed Brown /*@
1377e1244c69SJed Brown    TSRHSJacobianSetReuse - restore RHS Jacobian before re-evaluating.  Without this flag, TS will change the sign and
1378e1244c69SJed Brown    shift the RHS Jacobian for a finite-time-step implicit solve, in which case the user function will need to recompute
1379e1244c69SJed Brown    the entire Jacobian.  The reuse flag must be set if the evaluation function will assume that the matrix entries have
1380e1244c69SJed Brown    not been changed by the TS.
1381e1244c69SJed Brown 
1382e1244c69SJed Brown    Logically Collective
1383e1244c69SJed Brown 
13844165533cSJose E. Roman    Input Parameters:
1385e1244c69SJed Brown +  ts - TS context obtained from TSCreate()
1386e1244c69SJed Brown -  reuse - PETSC_TRUE if the RHS Jacobian
1387e1244c69SJed Brown 
1388e1244c69SJed Brown    Level: intermediate
1389e1244c69SJed Brown 
1390db781477SPatrick Sanan .seealso: `TSSetRHSJacobian()`, `TSComputeRHSJacobianConstant()`
1391e1244c69SJed Brown @*/
1392*d71ae5a4SJacob Faibussowitsch PetscErrorCode TSRHSJacobianSetReuse(TS ts, PetscBool reuse)
1393*d71ae5a4SJacob Faibussowitsch {
1394e1244c69SJed Brown   PetscFunctionBegin;
1395e1244c69SJed Brown   ts->rhsjacobian.reuse = reuse;
1396e1244c69SJed Brown   PetscFunctionReturn(0);
1397e1244c69SJed Brown }
1398e1244c69SJed Brown 
1399efe9872eSLisandro Dalcin /*@C
1400efe9872eSLisandro Dalcin    TSSetI2Function - Set the function to compute F(t,U,U_t,U_tt) where F = 0 is the DAE to be solved.
1401efe9872eSLisandro Dalcin 
1402efe9872eSLisandro Dalcin    Logically Collective on TS
1403efe9872eSLisandro Dalcin 
1404efe9872eSLisandro Dalcin    Input Parameters:
1405efe9872eSLisandro Dalcin +  ts  - the TS context obtained from TSCreate()
1406efe9872eSLisandro Dalcin .  F   - vector to hold the residual (or NULL to have it created internally)
1407efe9872eSLisandro Dalcin .  fun - the function evaluation routine
1408efe9872eSLisandro Dalcin -  ctx - user-defined context for private data for the function evaluation routine (may be NULL)
1409efe9872eSLisandro Dalcin 
1410efe9872eSLisandro Dalcin    Calling sequence of fun:
14116bc98fa9SBarry Smith $     PetscErrorCode fun(TS ts,PetscReal t,Vec U,Vec U_t,Vec U_tt,Vec F,ctx);
1412efe9872eSLisandro Dalcin 
1413efe9872eSLisandro Dalcin +  t    - time at step/stage being solved
1414efe9872eSLisandro Dalcin .  U    - state vector
1415efe9872eSLisandro Dalcin .  U_t  - time derivative of state vector
1416efe9872eSLisandro Dalcin .  U_tt - second time derivative of state vector
1417efe9872eSLisandro Dalcin .  F    - function vector
1418efe9872eSLisandro Dalcin -  ctx  - [optional] user-defined context for matrix evaluation routine (may be NULL)
1419efe9872eSLisandro Dalcin 
1420efe9872eSLisandro Dalcin    Level: beginner
1421efe9872eSLisandro Dalcin 
1422db781477SPatrick Sanan .seealso: `TSSetI2Jacobian()`, `TSSetIFunction()`, `TSCreate()`, `TSSetRHSFunction()`
1423efe9872eSLisandro Dalcin @*/
1424*d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetI2Function(TS ts, Vec F, TSI2Function fun, void *ctx)
1425*d71ae5a4SJacob Faibussowitsch {
1426efe9872eSLisandro Dalcin   DM dm;
1427efe9872eSLisandro Dalcin 
1428efe9872eSLisandro Dalcin   PetscFunctionBegin;
1429efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
1430efe9872eSLisandro Dalcin   if (F) PetscValidHeaderSpecific(F, VEC_CLASSID, 2);
14319566063dSJacob Faibussowitsch   PetscCall(TSSetIFunction(ts, F, NULL, NULL));
14329566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
14339566063dSJacob Faibussowitsch   PetscCall(DMTSSetI2Function(dm, fun, ctx));
1434efe9872eSLisandro Dalcin   PetscFunctionReturn(0);
1435efe9872eSLisandro Dalcin }
1436efe9872eSLisandro Dalcin 
1437efe9872eSLisandro Dalcin /*@C
1438a5b23f4aSJose E. Roman   TSGetI2Function - Returns the vector where the implicit residual is stored and the function/context to compute it.
1439efe9872eSLisandro Dalcin 
1440efe9872eSLisandro Dalcin   Not Collective
1441efe9872eSLisandro Dalcin 
1442efe9872eSLisandro Dalcin   Input Parameter:
1443efe9872eSLisandro Dalcin . ts - the TS context
1444efe9872eSLisandro Dalcin 
1445d8d19677SJose E. Roman   Output Parameters:
1446efe9872eSLisandro Dalcin + r - vector to hold residual (or NULL)
1447efe9872eSLisandro Dalcin . fun - the function to compute residual (or NULL)
1448efe9872eSLisandro Dalcin - ctx - the function context (or NULL)
1449efe9872eSLisandro Dalcin 
1450efe9872eSLisandro Dalcin   Level: advanced
1451efe9872eSLisandro Dalcin 
1452db781477SPatrick Sanan .seealso: `TSSetIFunction()`, `SNESGetFunction()`, `TSCreate()`
1453efe9872eSLisandro Dalcin @*/
1454*d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetI2Function(TS ts, Vec *r, TSI2Function *fun, void **ctx)
1455*d71ae5a4SJacob Faibussowitsch {
1456efe9872eSLisandro Dalcin   SNES snes;
1457efe9872eSLisandro Dalcin   DM   dm;
1458efe9872eSLisandro Dalcin 
1459efe9872eSLisandro Dalcin   PetscFunctionBegin;
1460efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
14619566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts, &snes));
14629566063dSJacob Faibussowitsch   PetscCall(SNESGetFunction(snes, r, NULL, NULL));
14639566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
14649566063dSJacob Faibussowitsch   PetscCall(DMTSGetI2Function(dm, fun, ctx));
1465efe9872eSLisandro Dalcin   PetscFunctionReturn(0);
1466efe9872eSLisandro Dalcin }
1467efe9872eSLisandro Dalcin 
1468efe9872eSLisandro Dalcin /*@C
1469bc77d74cSLisandro Dalcin    TSSetI2Jacobian - Set the function to compute the matrix dF/dU + v*dF/dU_t  + a*dF/dU_tt
1470efe9872eSLisandro Dalcin         where F(t,U,U_t,U_tt) is the function you provided with TSSetI2Function().
1471efe9872eSLisandro Dalcin 
1472efe9872eSLisandro Dalcin    Logically Collective on TS
1473efe9872eSLisandro Dalcin 
1474efe9872eSLisandro Dalcin    Input Parameters:
1475efe9872eSLisandro Dalcin +  ts  - the TS context obtained from TSCreate()
1476efe9872eSLisandro Dalcin .  J   - Jacobian matrix
1477efe9872eSLisandro Dalcin .  P   - preconditioning matrix for J (may be same as J)
1478efe9872eSLisandro Dalcin .  jac - the Jacobian evaluation routine
1479efe9872eSLisandro Dalcin -  ctx - user-defined context for private data for the Jacobian evaluation routine (may be NULL)
1480efe9872eSLisandro Dalcin 
1481efe9872eSLisandro Dalcin    Calling sequence of jac:
14826bc98fa9SBarry Smith $    PetscErrorCode jac(TS ts,PetscReal t,Vec U,Vec U_t,Vec U_tt,PetscReal v,PetscReal a,Mat J,Mat P,void *ctx);
1483efe9872eSLisandro Dalcin 
1484efe9872eSLisandro Dalcin +  t    - time at step/stage being solved
1485efe9872eSLisandro Dalcin .  U    - state vector
1486efe9872eSLisandro Dalcin .  U_t  - time derivative of state vector
1487efe9872eSLisandro Dalcin .  U_tt - second time derivative of state vector
1488efe9872eSLisandro Dalcin .  v    - shift for U_t
1489efe9872eSLisandro Dalcin .  a    - shift for U_tt
1490efe9872eSLisandro Dalcin .  J    - Jacobian of G(U) = F(t,U,W+v*U,W'+a*U), equivalent to dF/dU + v*dF/dU_t  + a*dF/dU_tt
1491efe9872eSLisandro Dalcin .  P    - preconditioning matrix for J, may be same as J
1492efe9872eSLisandro Dalcin -  ctx  - [optional] user-defined context for matrix evaluation routine
1493efe9872eSLisandro Dalcin 
1494efe9872eSLisandro Dalcin    Notes:
1495efe9872eSLisandro Dalcin    The matrices J and P are exactly the matrices that are used by SNES for the nonlinear solve.
1496efe9872eSLisandro Dalcin 
1497efe9872eSLisandro Dalcin    The matrix dF/dU + v*dF/dU_t + a*dF/dU_tt you provide turns out to be
1498efe9872eSLisandro 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.
1499efe9872eSLisandro Dalcin    The time integrator internally approximates U_t by W+v*U and U_tt by W'+a*U  where the positive "shift"
1500bc77d74cSLisandro Dalcin    parameters 'v' and 'a' and vectors W, W' depend on the integration method, step size, and past states.
1501efe9872eSLisandro Dalcin 
1502efe9872eSLisandro Dalcin    Level: beginner
1503efe9872eSLisandro Dalcin 
1504db781477SPatrick Sanan .seealso: `TSSetI2Function()`, `TSGetI2Jacobian()`
1505efe9872eSLisandro Dalcin @*/
1506*d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetI2Jacobian(TS ts, Mat J, Mat P, TSI2Jacobian jac, void *ctx)
1507*d71ae5a4SJacob Faibussowitsch {
1508efe9872eSLisandro Dalcin   DM dm;
1509efe9872eSLisandro Dalcin 
1510efe9872eSLisandro Dalcin   PetscFunctionBegin;
1511efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
1512efe9872eSLisandro Dalcin   if (J) PetscValidHeaderSpecific(J, MAT_CLASSID, 2);
1513efe9872eSLisandro Dalcin   if (P) PetscValidHeaderSpecific(P, MAT_CLASSID, 3);
15149566063dSJacob Faibussowitsch   PetscCall(TSSetIJacobian(ts, J, P, NULL, NULL));
15159566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
15169566063dSJacob Faibussowitsch   PetscCall(DMTSSetI2Jacobian(dm, jac, ctx));
1517efe9872eSLisandro Dalcin   PetscFunctionReturn(0);
1518efe9872eSLisandro Dalcin }
1519efe9872eSLisandro Dalcin 
1520efe9872eSLisandro Dalcin /*@C
1521efe9872eSLisandro Dalcin   TSGetI2Jacobian - Returns the implicit Jacobian at the present timestep.
1522efe9872eSLisandro Dalcin 
1523efe9872eSLisandro Dalcin   Not Collective, but parallel objects are returned if TS is parallel
1524efe9872eSLisandro Dalcin 
1525efe9872eSLisandro Dalcin   Input Parameter:
1526efe9872eSLisandro Dalcin . ts  - The TS context obtained from TSCreate()
1527efe9872eSLisandro Dalcin 
1528efe9872eSLisandro Dalcin   Output Parameters:
1529efe9872eSLisandro Dalcin + J  - The (approximate) Jacobian of F(t,U,U_t,U_tt)
1530efe9872eSLisandro Dalcin . P - The matrix from which the preconditioner is constructed, often the same as J
1531efe9872eSLisandro Dalcin . jac - The function to compute the Jacobian matrices
1532efe9872eSLisandro Dalcin - ctx - User-defined context for Jacobian evaluation routine
1533efe9872eSLisandro Dalcin 
153495452b02SPatrick Sanan   Notes:
153595452b02SPatrick Sanan     You can pass in NULL for any return argument you do not need.
1536efe9872eSLisandro Dalcin 
1537efe9872eSLisandro Dalcin   Level: advanced
1538efe9872eSLisandro Dalcin 
1539db781477SPatrick Sanan .seealso: `TSGetTimeStep()`, `TSGetMatrices()`, `TSGetTime()`, `TSGetStepNumber()`, `TSSetI2Jacobian()`, `TSGetI2Function()`, `TSCreate()`
1540efe9872eSLisandro Dalcin 
1541efe9872eSLisandro Dalcin @*/
1542*d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetI2Jacobian(TS ts, Mat *J, Mat *P, TSI2Jacobian *jac, void **ctx)
1543*d71ae5a4SJacob Faibussowitsch {
1544efe9872eSLisandro Dalcin   SNES snes;
1545efe9872eSLisandro Dalcin   DM   dm;
1546efe9872eSLisandro Dalcin 
1547efe9872eSLisandro Dalcin   PetscFunctionBegin;
15489566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts, &snes));
15499566063dSJacob Faibussowitsch   PetscCall(SNESSetUpMatrices(snes));
15509566063dSJacob Faibussowitsch   PetscCall(SNESGetJacobian(snes, J, P, NULL, NULL));
15519566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
15529566063dSJacob Faibussowitsch   PetscCall(DMTSGetI2Jacobian(dm, jac, ctx));
1553efe9872eSLisandro Dalcin   PetscFunctionReturn(0);
1554efe9872eSLisandro Dalcin }
1555efe9872eSLisandro Dalcin 
1556efe9872eSLisandro Dalcin /*@
1557efe9872eSLisandro Dalcin   TSComputeI2Function - Evaluates the DAE residual written in implicit form F(t,U,U_t,U_tt) = 0
1558efe9872eSLisandro Dalcin 
1559d083f849SBarry Smith   Collective on TS
1560efe9872eSLisandro Dalcin 
1561efe9872eSLisandro Dalcin   Input Parameters:
1562efe9872eSLisandro Dalcin + ts - the TS context
1563efe9872eSLisandro Dalcin . t - current time
1564efe9872eSLisandro Dalcin . U - state vector
1565efe9872eSLisandro Dalcin . V - time derivative of state vector (U_t)
1566efe9872eSLisandro Dalcin - A - second time derivative of state vector (U_tt)
1567efe9872eSLisandro Dalcin 
1568efe9872eSLisandro Dalcin   Output Parameter:
1569efe9872eSLisandro Dalcin . F - the residual vector
1570efe9872eSLisandro Dalcin 
1571efe9872eSLisandro Dalcin   Note:
1572efe9872eSLisandro Dalcin   Most users should not need to explicitly call this routine, as it
1573efe9872eSLisandro Dalcin   is used internally within the nonlinear solvers.
1574efe9872eSLisandro Dalcin 
1575efe9872eSLisandro Dalcin   Level: developer
1576efe9872eSLisandro Dalcin 
1577db781477SPatrick Sanan .seealso: `TSSetI2Function()`, `TSGetI2Function()`
1578efe9872eSLisandro Dalcin @*/
1579*d71ae5a4SJacob Faibussowitsch PetscErrorCode TSComputeI2Function(TS ts, PetscReal t, Vec U, Vec V, Vec A, Vec F)
1580*d71ae5a4SJacob Faibussowitsch {
1581efe9872eSLisandro Dalcin   DM            dm;
1582efe9872eSLisandro Dalcin   TSI2Function  I2Function;
1583efe9872eSLisandro Dalcin   void         *ctx;
1584efe9872eSLisandro Dalcin   TSRHSFunction rhsfunction;
1585efe9872eSLisandro Dalcin 
1586efe9872eSLisandro Dalcin   PetscFunctionBegin;
1587efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
1588efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(U, VEC_CLASSID, 3);
1589efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(V, VEC_CLASSID, 4);
1590efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(A, VEC_CLASSID, 5);
1591efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(F, VEC_CLASSID, 6);
1592efe9872eSLisandro Dalcin 
15939566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
15949566063dSJacob Faibussowitsch   PetscCall(DMTSGetI2Function(dm, &I2Function, &ctx));
15959566063dSJacob Faibussowitsch   PetscCall(DMTSGetRHSFunction(dm, &rhsfunction, NULL));
1596efe9872eSLisandro Dalcin 
1597efe9872eSLisandro Dalcin   if (!I2Function) {
15989566063dSJacob Faibussowitsch     PetscCall(TSComputeIFunction(ts, t, U, A, F, PETSC_FALSE));
1599efe9872eSLisandro Dalcin     PetscFunctionReturn(0);
1600efe9872eSLisandro Dalcin   }
1601efe9872eSLisandro Dalcin 
16029566063dSJacob Faibussowitsch   PetscCall(PetscLogEventBegin(TS_FunctionEval, ts, U, V, F));
1603efe9872eSLisandro Dalcin 
1604792fecdfSBarry Smith   PetscCallBack("TS callback implicit function", I2Function(ts, t, U, V, A, F, ctx));
1605efe9872eSLisandro Dalcin 
1606efe9872eSLisandro Dalcin   if (rhsfunction) {
1607efe9872eSLisandro Dalcin     Vec Frhs;
16089566063dSJacob Faibussowitsch     PetscCall(TSGetRHSVec_Private(ts, &Frhs));
16099566063dSJacob Faibussowitsch     PetscCall(TSComputeRHSFunction(ts, t, U, Frhs));
16109566063dSJacob Faibussowitsch     PetscCall(VecAXPY(F, -1, Frhs));
1611efe9872eSLisandro Dalcin   }
1612efe9872eSLisandro Dalcin 
16139566063dSJacob Faibussowitsch   PetscCall(PetscLogEventEnd(TS_FunctionEval, ts, U, V, F));
1614efe9872eSLisandro Dalcin   PetscFunctionReturn(0);
1615efe9872eSLisandro Dalcin }
1616efe9872eSLisandro Dalcin 
1617efe9872eSLisandro Dalcin /*@
1618efe9872eSLisandro Dalcin   TSComputeI2Jacobian - Evaluates the Jacobian of the DAE
1619efe9872eSLisandro Dalcin 
1620d083f849SBarry Smith   Collective on TS
1621efe9872eSLisandro Dalcin 
1622efe9872eSLisandro Dalcin   Input Parameters:
1623efe9872eSLisandro Dalcin + ts - the TS context
1624efe9872eSLisandro Dalcin . t - current timestep
1625efe9872eSLisandro Dalcin . U - state vector
1626efe9872eSLisandro Dalcin . V - time derivative of state vector
1627efe9872eSLisandro Dalcin . A - second time derivative of state vector
1628efe9872eSLisandro Dalcin . shiftV - shift to apply, see note below
1629efe9872eSLisandro Dalcin - shiftA - shift to apply, see note below
1630efe9872eSLisandro Dalcin 
1631efe9872eSLisandro Dalcin   Output Parameters:
1632efe9872eSLisandro Dalcin + J - Jacobian matrix
1633efe9872eSLisandro Dalcin - P - optional preconditioning matrix
1634efe9872eSLisandro Dalcin 
1635efe9872eSLisandro Dalcin   Notes:
1636efe9872eSLisandro Dalcin   If F(t,U,V,A)=0 is the DAE, the required Jacobian is
1637efe9872eSLisandro Dalcin 
1638efe9872eSLisandro Dalcin   dF/dU + shiftV*dF/dV + shiftA*dF/dA
1639efe9872eSLisandro Dalcin 
1640efe9872eSLisandro Dalcin   Most users should not need to explicitly call this routine, as it
1641efe9872eSLisandro Dalcin   is used internally within the nonlinear solvers.
1642efe9872eSLisandro Dalcin 
1643efe9872eSLisandro Dalcin   Level: developer
1644efe9872eSLisandro Dalcin 
1645db781477SPatrick Sanan .seealso: `TSSetI2Jacobian()`
1646efe9872eSLisandro Dalcin @*/
1647*d71ae5a4SJacob Faibussowitsch PetscErrorCode TSComputeI2Jacobian(TS ts, PetscReal t, Vec U, Vec V, Vec A, PetscReal shiftV, PetscReal shiftA, Mat J, Mat P)
1648*d71ae5a4SJacob Faibussowitsch {
1649efe9872eSLisandro Dalcin   DM            dm;
1650efe9872eSLisandro Dalcin   TSI2Jacobian  I2Jacobian;
1651efe9872eSLisandro Dalcin   void         *ctx;
1652efe9872eSLisandro Dalcin   TSRHSJacobian rhsjacobian;
1653efe9872eSLisandro Dalcin 
1654efe9872eSLisandro Dalcin   PetscFunctionBegin;
1655efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
1656efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(U, VEC_CLASSID, 3);
1657efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(V, VEC_CLASSID, 4);
1658efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(A, VEC_CLASSID, 5);
1659efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(J, MAT_CLASSID, 8);
1660efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(P, MAT_CLASSID, 9);
1661efe9872eSLisandro Dalcin 
16629566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
16639566063dSJacob Faibussowitsch   PetscCall(DMTSGetI2Jacobian(dm, &I2Jacobian, &ctx));
16649566063dSJacob Faibussowitsch   PetscCall(DMTSGetRHSJacobian(dm, &rhsjacobian, NULL));
1665efe9872eSLisandro Dalcin 
1666efe9872eSLisandro Dalcin   if (!I2Jacobian) {
16679566063dSJacob Faibussowitsch     PetscCall(TSComputeIJacobian(ts, t, U, A, shiftA, J, P, PETSC_FALSE));
1668efe9872eSLisandro Dalcin     PetscFunctionReturn(0);
1669efe9872eSLisandro Dalcin   }
1670efe9872eSLisandro Dalcin 
16719566063dSJacob Faibussowitsch   PetscCall(PetscLogEventBegin(TS_JacobianEval, ts, U, J, P));
1672792fecdfSBarry Smith   PetscCallBack("TS callback implicit Jacobian", I2Jacobian(ts, t, U, V, A, shiftV, shiftA, J, P, ctx));
1673efe9872eSLisandro Dalcin   if (rhsjacobian) {
1674d60b7d5cSBarry Smith     Mat Jrhs, Prhs;
16759566063dSJacob Faibussowitsch     PetscCall(TSGetRHSMats_Private(ts, &Jrhs, &Prhs));
16769566063dSJacob Faibussowitsch     PetscCall(TSComputeRHSJacobian(ts, t, U, Jrhs, Prhs));
16779566063dSJacob Faibussowitsch     PetscCall(MatAXPY(J, -1, Jrhs, ts->axpy_pattern));
16789566063dSJacob Faibussowitsch     if (P != J) PetscCall(MatAXPY(P, -1, Prhs, ts->axpy_pattern));
1679efe9872eSLisandro Dalcin   }
1680efe9872eSLisandro Dalcin 
16819566063dSJacob Faibussowitsch   PetscCall(PetscLogEventEnd(TS_JacobianEval, ts, U, J, P));
1682efe9872eSLisandro Dalcin   PetscFunctionReturn(0);
1683efe9872eSLisandro Dalcin }
1684efe9872eSLisandro Dalcin 
1685438f35afSJed Brown /*@C
1686438f35afSJed Brown    TSSetTransientVariable - sets function to transform from state to transient variables
1687438f35afSJed Brown 
1688438f35afSJed Brown    Logically Collective
1689438f35afSJed Brown 
16904165533cSJose E. Roman    Input Parameters:
1691438f35afSJed Brown +  ts - time stepping context on which to change the transient variable
1692a96d6ef6SBarry Smith .  tvar - a function that transforms to transient variables
1693438f35afSJed Brown -  ctx - a context for tvar
1694438f35afSJed Brown 
1695a96d6ef6SBarry Smith     Calling sequence of tvar:
1696a96d6ef6SBarry Smith $     PetscErrorCode tvar(TS ts,Vec p,Vec c,void *ctx);
1697a96d6ef6SBarry Smith 
1698a96d6ef6SBarry Smith +   ts - timestep context
16996aad120cSJose E. Roman .   p - input vector (primitive form)
1700a96d6ef6SBarry Smith .   c - output vector, transient variables (conservative form)
1701a96d6ef6SBarry Smith -   ctx - [optional] user-defined function context
1702a96d6ef6SBarry Smith 
1703438f35afSJed Brown    Level: advanced
1704438f35afSJed Brown 
1705438f35afSJed Brown    Notes:
1706438f35afSJed Brown    This is typically used to transform from primitive to conservative variables so that a time integrator (e.g., TSBDF)
1707438f35afSJed Brown    can be conservative.  In this context, primitive variables P are used to model the state (e.g., because they lead to
1708438f35afSJed Brown    well-conditioned formulations even in limiting cases such as low-Mach or zero porosity).  The transient variable is
1709438f35afSJed Brown    C(P), specified by calling this function.  An IFunction thus receives arguments (P, Cdot) and the IJacobian must be
1710438f35afSJed Brown    evaluated via the chain rule, as in
1711438f35afSJed Brown 
1712438f35afSJed Brown      dF/dP + shift * dF/dCdot dC/dP.
1713438f35afSJed Brown 
1714db781477SPatrick Sanan .seealso: `DMTSSetTransientVariable()`, `DMTSGetTransientVariable()`, `TSSetIFunction()`, `TSSetIJacobian()`
1715438f35afSJed Brown @*/
1716*d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetTransientVariable(TS ts, TSTransientVariable tvar, void *ctx)
1717*d71ae5a4SJacob Faibussowitsch {
1718438f35afSJed Brown   DM dm;
1719438f35afSJed Brown 
1720438f35afSJed Brown   PetscFunctionBegin;
1721438f35afSJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
17229566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
17239566063dSJacob Faibussowitsch   PetscCall(DMTSSetTransientVariable(dm, tvar, ctx));
1724438f35afSJed Brown   PetscFunctionReturn(0);
1725438f35afSJed Brown }
1726438f35afSJed Brown 
1727efe9872eSLisandro Dalcin /*@
1728e3c11fc1SJed Brown    TSComputeTransientVariable - transforms state (primitive) variables to transient (conservative) variables
1729e3c11fc1SJed Brown 
1730e3c11fc1SJed Brown    Logically Collective
1731e3c11fc1SJed Brown 
1732e3c11fc1SJed Brown    Input Parameters:
1733e3c11fc1SJed Brown +  ts - TS on which to compute
1734e3c11fc1SJed Brown -  U - state vector to be transformed to transient variables
1735e3c11fc1SJed Brown 
1736e3c11fc1SJed Brown    Output Parameters:
1737e3c11fc1SJed Brown .  C - transient (conservative) variable
1738e3c11fc1SJed Brown 
1739e3c11fc1SJed Brown    Developer Notes:
1740e3c11fc1SJed Brown    If DMTSSetTransientVariable() has not been called, then C is not modified in this routine and C=NULL is allowed.
1741e3c11fc1SJed Brown    This makes it safe to call without a guard.  One can use TSHasTransientVariable() to check if transient variables are
1742e3c11fc1SJed Brown    being used.
1743e3c11fc1SJed Brown 
1744e3c11fc1SJed Brown    Level: developer
1745e3c11fc1SJed Brown 
1746db781477SPatrick Sanan .seealso: `DMTSSetTransientVariable()`, `TSComputeIFunction()`, `TSComputeIJacobian()`
1747e3c11fc1SJed Brown @*/
1748*d71ae5a4SJacob Faibussowitsch PetscErrorCode TSComputeTransientVariable(TS ts, Vec U, Vec C)
1749*d71ae5a4SJacob Faibussowitsch {
1750e3c11fc1SJed Brown   DM   dm;
1751e3c11fc1SJed Brown   DMTS dmts;
1752e3c11fc1SJed Brown 
1753e3c11fc1SJed Brown   PetscFunctionBegin;
1754e3c11fc1SJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
1755e3c11fc1SJed Brown   PetscValidHeaderSpecific(U, VEC_CLASSID, 2);
17569566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
17579566063dSJacob Faibussowitsch   PetscCall(DMGetDMTS(dm, &dmts));
1758e3c11fc1SJed Brown   if (dmts->ops->transientvar) {
1759e3c11fc1SJed Brown     PetscValidHeaderSpecific(C, VEC_CLASSID, 3);
17609566063dSJacob Faibussowitsch     PetscCall((*dmts->ops->transientvar)(ts, U, C, dmts->transientvarctx));
1761e3c11fc1SJed Brown   }
1762e3c11fc1SJed Brown   PetscFunctionReturn(0);
1763e3c11fc1SJed Brown }
1764e3c11fc1SJed Brown 
1765e3c11fc1SJed Brown /*@
1766e3c11fc1SJed Brown    TSHasTransientVariable - determine whether transient variables have been set
1767e3c11fc1SJed Brown 
1768e3c11fc1SJed Brown    Logically Collective
1769e3c11fc1SJed Brown 
1770e3c11fc1SJed Brown    Input Parameters:
1771e3c11fc1SJed Brown .  ts - TS on which to compute
1772e3c11fc1SJed Brown 
1773e3c11fc1SJed Brown    Output Parameters:
1774e3c11fc1SJed Brown .  has - PETSC_TRUE if transient variables have been set
1775e3c11fc1SJed Brown 
1776e3c11fc1SJed Brown    Level: developer
1777e3c11fc1SJed Brown 
1778db781477SPatrick Sanan .seealso: `DMTSSetTransientVariable()`, `TSComputeTransientVariable()`
1779e3c11fc1SJed Brown @*/
1780*d71ae5a4SJacob Faibussowitsch PetscErrorCode TSHasTransientVariable(TS ts, PetscBool *has)
1781*d71ae5a4SJacob Faibussowitsch {
1782e3c11fc1SJed Brown   DM   dm;
1783e3c11fc1SJed Brown   DMTS dmts;
1784e3c11fc1SJed Brown 
1785e3c11fc1SJed Brown   PetscFunctionBegin;
1786e3c11fc1SJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
17879566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
17889566063dSJacob Faibussowitsch   PetscCall(DMGetDMTS(dm, &dmts));
1789e3c11fc1SJed Brown   *has = dmts->ops->transientvar ? PETSC_TRUE : PETSC_FALSE;
1790e3c11fc1SJed Brown   PetscFunctionReturn(0);
1791e3c11fc1SJed Brown }
1792e3c11fc1SJed Brown 
1793e3c11fc1SJed Brown /*@
1794efe9872eSLisandro Dalcin    TS2SetSolution - Sets the initial solution and time derivative vectors
1795efe9872eSLisandro Dalcin    for use by the TS routines handling second order equations.
1796efe9872eSLisandro Dalcin 
1797d083f849SBarry Smith    Logically Collective on TS
1798efe9872eSLisandro Dalcin 
1799efe9872eSLisandro Dalcin    Input Parameters:
1800efe9872eSLisandro Dalcin +  ts - the TS context obtained from TSCreate()
1801efe9872eSLisandro Dalcin .  u - the solution vector
1802efe9872eSLisandro Dalcin -  v - the time derivative vector
1803efe9872eSLisandro Dalcin 
1804efe9872eSLisandro Dalcin    Level: beginner
1805efe9872eSLisandro Dalcin 
1806efe9872eSLisandro Dalcin @*/
1807*d71ae5a4SJacob Faibussowitsch PetscErrorCode TS2SetSolution(TS ts, Vec u, Vec v)
1808*d71ae5a4SJacob Faibussowitsch {
1809efe9872eSLisandro Dalcin   PetscFunctionBegin;
1810efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
1811efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(u, VEC_CLASSID, 2);
1812efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(v, VEC_CLASSID, 3);
18139566063dSJacob Faibussowitsch   PetscCall(TSSetSolution(ts, u));
18149566063dSJacob Faibussowitsch   PetscCall(PetscObjectReference((PetscObject)v));
18159566063dSJacob Faibussowitsch   PetscCall(VecDestroy(&ts->vec_dot));
1816efe9872eSLisandro Dalcin   ts->vec_dot = v;
1817efe9872eSLisandro Dalcin   PetscFunctionReturn(0);
1818efe9872eSLisandro Dalcin }
1819efe9872eSLisandro Dalcin 
1820efe9872eSLisandro Dalcin /*@
1821efe9872eSLisandro Dalcin    TS2GetSolution - Returns the solution and time derivative at the present timestep
1822efe9872eSLisandro Dalcin    for second order equations. It is valid to call this routine inside the function
1823efe9872eSLisandro Dalcin    that you are evaluating in order to move to the new timestep. This vector not
1824efe9872eSLisandro Dalcin    changed until the solution at the next timestep has been calculated.
1825efe9872eSLisandro Dalcin 
1826efe9872eSLisandro Dalcin    Not Collective, but Vec returned is parallel if TS is parallel
1827efe9872eSLisandro Dalcin 
1828efe9872eSLisandro Dalcin    Input Parameter:
1829efe9872eSLisandro Dalcin .  ts - the TS context obtained from TSCreate()
1830efe9872eSLisandro Dalcin 
1831d8d19677SJose E. Roman    Output Parameters:
1832efe9872eSLisandro Dalcin +  u - the vector containing the solution
1833efe9872eSLisandro Dalcin -  v - the vector containing the time derivative
1834efe9872eSLisandro Dalcin 
1835efe9872eSLisandro Dalcin    Level: intermediate
1836efe9872eSLisandro Dalcin 
1837db781477SPatrick Sanan .seealso: `TS2SetSolution()`, `TSGetTimeStep()`, `TSGetTime()`
1838efe9872eSLisandro Dalcin 
1839efe9872eSLisandro Dalcin @*/
1840*d71ae5a4SJacob Faibussowitsch PetscErrorCode TS2GetSolution(TS ts, Vec *u, Vec *v)
1841*d71ae5a4SJacob Faibussowitsch {
1842efe9872eSLisandro Dalcin   PetscFunctionBegin;
1843efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
1844efe9872eSLisandro Dalcin   if (u) PetscValidPointer(u, 2);
1845efe9872eSLisandro Dalcin   if (v) PetscValidPointer(v, 3);
1846efe9872eSLisandro Dalcin   if (u) *u = ts->vec_sol;
1847efe9872eSLisandro Dalcin   if (v) *v = ts->vec_dot;
1848efe9872eSLisandro Dalcin   PetscFunctionReturn(0);
1849efe9872eSLisandro Dalcin }
1850efe9872eSLisandro Dalcin 
185155849f57SBarry Smith /*@C
185255849f57SBarry Smith   TSLoad - Loads a KSP that has been stored in binary  with KSPView().
185355849f57SBarry Smith 
185455849f57SBarry Smith   Collective on PetscViewer
185555849f57SBarry Smith 
185655849f57SBarry Smith   Input Parameters:
185755849f57SBarry Smith + newdm - the newly loaded TS, this needs to have been created with TSCreate() or
185855849f57SBarry Smith            some related function before a call to TSLoad().
185955849f57SBarry Smith - viewer - binary file viewer, obtained from PetscViewerBinaryOpen()
186055849f57SBarry Smith 
186155849f57SBarry Smith    Level: intermediate
186255849f57SBarry Smith 
186355849f57SBarry Smith   Notes:
186455849f57SBarry Smith    The type is determined by the data in the file, any type set into the TS before this call is ignored.
186555849f57SBarry Smith 
186655849f57SBarry Smith   Notes for advanced users:
186755849f57SBarry Smith   Most users should not need to know the details of the binary storage
186855849f57SBarry Smith   format, since TSLoad() and TSView() completely hide these details.
186955849f57SBarry Smith   But for anyone who's interested, the standard binary matrix storage
187055849f57SBarry Smith   format is
187155849f57SBarry Smith .vb
187255849f57SBarry Smith      has not yet been determined
187355849f57SBarry Smith .ve
187455849f57SBarry Smith 
1875db781477SPatrick Sanan .seealso: `PetscViewerBinaryOpen()`, `TSView()`, `MatLoad()`, `VecLoad()`
187655849f57SBarry Smith @*/
1877*d71ae5a4SJacob Faibussowitsch PetscErrorCode TSLoad(TS ts, PetscViewer viewer)
1878*d71ae5a4SJacob Faibussowitsch {
187955849f57SBarry Smith   PetscBool isbinary;
188055849f57SBarry Smith   PetscInt  classid;
188155849f57SBarry Smith   char      type[256];
18822d53ad75SBarry Smith   DMTS      sdm;
1883ad6bc421SBarry Smith   DM        dm;
188455849f57SBarry Smith 
188555849f57SBarry Smith   PetscFunctionBegin;
1886f2c2a1b9SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
188755849f57SBarry Smith   PetscValidHeaderSpecific(viewer, PETSC_VIEWER_CLASSID, 2);
18889566063dSJacob Faibussowitsch   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERBINARY, &isbinary));
18893c633725SBarry Smith   PetscCheck(isbinary, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Invalid viewer; open viewer with PetscViewerBinaryOpen()");
189055849f57SBarry Smith 
18919566063dSJacob Faibussowitsch   PetscCall(PetscViewerBinaryRead(viewer, &classid, 1, NULL, PETSC_INT));
18923c633725SBarry Smith   PetscCheck(classid == TS_FILE_CLASSID, PetscObjectComm((PetscObject)ts), PETSC_ERR_ARG_WRONG, "Not TS next in file");
18939566063dSJacob Faibussowitsch   PetscCall(PetscViewerBinaryRead(viewer, type, 256, NULL, PETSC_CHAR));
18949566063dSJacob Faibussowitsch   PetscCall(TSSetType(ts, type));
1895dbbe0bcdSBarry Smith   PetscTryTypeMethod(ts, load, viewer);
18969566063dSJacob Faibussowitsch   PetscCall(DMCreate(PetscObjectComm((PetscObject)ts), &dm));
18979566063dSJacob Faibussowitsch   PetscCall(DMLoad(dm, viewer));
18989566063dSJacob Faibussowitsch   PetscCall(TSSetDM(ts, dm));
18999566063dSJacob Faibussowitsch   PetscCall(DMCreateGlobalVector(ts->dm, &ts->vec_sol));
19009566063dSJacob Faibussowitsch   PetscCall(VecLoad(ts->vec_sol, viewer));
19019566063dSJacob Faibussowitsch   PetscCall(DMGetDMTS(ts->dm, &sdm));
19029566063dSJacob Faibussowitsch   PetscCall(DMTSLoad(sdm, viewer));
190355849f57SBarry Smith   PetscFunctionReturn(0);
190455849f57SBarry Smith }
190555849f57SBarry Smith 
19069804daf3SBarry Smith #include <petscdraw.h>
1907e04113cfSBarry Smith #if defined(PETSC_HAVE_SAWS)
1908e04113cfSBarry Smith   #include <petscviewersaws.h>
1909f05ece33SBarry Smith #endif
1910fe2efc57SMark 
1911fe2efc57SMark /*@C
1912fe2efc57SMark    TSViewFromOptions - View from Options
1913fe2efc57SMark 
1914fe2efc57SMark    Collective on TS
1915fe2efc57SMark 
1916fe2efc57SMark    Input Parameters:
1917fe2efc57SMark +  A - the application ordering context
1918736c3998SJose E. Roman .  obj - Optional object
1919736c3998SJose E. Roman -  name - command line option
1920fe2efc57SMark 
1921fe2efc57SMark    Level: intermediate
1922db781477SPatrick Sanan .seealso: `TS`, `TSView`, `PetscObjectViewFromOptions()`, `TSCreate()`
1923fe2efc57SMark @*/
1924*d71ae5a4SJacob Faibussowitsch PetscErrorCode TSViewFromOptions(TS A, PetscObject obj, const char name[])
1925*d71ae5a4SJacob Faibussowitsch {
1926fe2efc57SMark   PetscFunctionBegin;
1927fe2efc57SMark   PetscValidHeaderSpecific(A, TS_CLASSID, 1);
19289566063dSJacob Faibussowitsch   PetscCall(PetscObjectViewFromOptions((PetscObject)A, obj, name));
1929fe2efc57SMark   PetscFunctionReturn(0);
1930fe2efc57SMark }
1931fe2efc57SMark 
19327e2c5f70SBarry Smith /*@C
1933d763cef2SBarry Smith     TSView - Prints the TS data structure.
1934d763cef2SBarry Smith 
19354c49b128SBarry Smith     Collective on TS
1936d763cef2SBarry Smith 
1937d763cef2SBarry Smith     Input Parameters:
1938d763cef2SBarry Smith +   ts - the TS context obtained from TSCreate()
1939d763cef2SBarry Smith -   viewer - visualization context
1940d763cef2SBarry Smith 
1941d763cef2SBarry Smith     Options Database Key:
1942d763cef2SBarry Smith .   -ts_view - calls TSView() at end of TSStep()
1943d763cef2SBarry Smith 
1944d763cef2SBarry Smith     Notes:
1945d763cef2SBarry Smith     The available visualization contexts include
1946b0a32e0cSBarry Smith +     PETSC_VIEWER_STDOUT_SELF - standard output (default)
1947b0a32e0cSBarry Smith -     PETSC_VIEWER_STDOUT_WORLD - synchronized standard
1948d763cef2SBarry Smith          output where only the first processor opens
1949d763cef2SBarry Smith          the file.  All other processors send their
1950d763cef2SBarry Smith          data to the first processor to print.
1951d763cef2SBarry Smith 
1952d763cef2SBarry Smith     The user can open an alternative visualization context with
1953b0a32e0cSBarry Smith     PetscViewerASCIIOpen() - output to a specified file.
1954d763cef2SBarry Smith 
1955595c91d4SBarry Smith     In the debugger you can do "call TSView(ts,0)" to display the TS solver. (The same holds for any PETSc object viewer).
1956595c91d4SBarry Smith 
1957d763cef2SBarry Smith     Level: beginner
1958d763cef2SBarry Smith 
1959db781477SPatrick Sanan .seealso: `PetscViewerASCIIOpen()`
1960d763cef2SBarry Smith @*/
1961*d71ae5a4SJacob Faibussowitsch PetscErrorCode TSView(TS ts, PetscViewer viewer)
1962*d71ae5a4SJacob Faibussowitsch {
196319fd82e9SBarry Smith   TSType    type;
19642b0a91c0SBarry Smith   PetscBool iascii, isstring, isundials, isbinary, isdraw;
19652d53ad75SBarry Smith   DMTS      sdm;
1966e04113cfSBarry Smith #if defined(PETSC_HAVE_SAWS)
1967536b137fSBarry Smith   PetscBool issaws;
1968f05ece33SBarry Smith #endif
1969d763cef2SBarry Smith 
1970d763cef2SBarry Smith   PetscFunctionBegin;
19710700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
19721e66621cSBarry Smith   if (!viewer) PetscCall(PetscViewerASCIIGetStdout(PetscObjectComm((PetscObject)ts), &viewer));
19730700a824SBarry Smith   PetscValidHeaderSpecific(viewer, PETSC_VIEWER_CLASSID, 2);
1974c9780b6fSBarry Smith   PetscCheckSameComm(ts, 1, viewer, 2);
1975fd16b177SBarry Smith 
19769566063dSJacob Faibussowitsch   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERASCII, &iascii));
19779566063dSJacob Faibussowitsch   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERSTRING, &isstring));
19789566063dSJacob Faibussowitsch   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERBINARY, &isbinary));
19799566063dSJacob Faibussowitsch   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERDRAW, &isdraw));
1980e04113cfSBarry Smith #if defined(PETSC_HAVE_SAWS)
19819566063dSJacob Faibussowitsch   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERSAWS, &issaws));
1982f05ece33SBarry Smith #endif
198332077d6dSBarry Smith   if (iascii) {
19849566063dSJacob Faibussowitsch     PetscCall(PetscObjectPrintClassNamePrefixType((PetscObject)ts, viewer));
1985efd4aadfSBarry Smith     if (ts->ops->view) {
19869566063dSJacob Faibussowitsch       PetscCall(PetscViewerASCIIPushTab(viewer));
1987dbbe0bcdSBarry Smith       PetscUseTypeMethod(ts, view, viewer);
19889566063dSJacob Faibussowitsch       PetscCall(PetscViewerASCIIPopTab(viewer));
1989efd4aadfSBarry Smith     }
19901e66621cSBarry Smith     if (ts->max_steps < PETSC_MAX_INT) PetscCall(PetscViewerASCIIPrintf(viewer, "  maximum steps=%" PetscInt_FMT "\n", ts->max_steps));
19911e66621cSBarry Smith     if (ts->max_time < PETSC_MAX_REAL) PetscCall(PetscViewerASCIIPrintf(viewer, "  maximum time=%g\n", (double)ts->max_time));
19921e66621cSBarry Smith     if (ts->ifuncs) PetscCall(PetscViewerASCIIPrintf(viewer, "  total number of I function evaluations=%" PetscInt_FMT "\n", ts->ifuncs));
19931e66621cSBarry Smith     if (ts->ijacs) PetscCall(PetscViewerASCIIPrintf(viewer, "  total number of I Jacobian evaluations=%" PetscInt_FMT "\n", ts->ijacs));
19941e66621cSBarry Smith     if (ts->rhsfuncs) PetscCall(PetscViewerASCIIPrintf(viewer, "  total number of RHS function evaluations=%" PetscInt_FMT "\n", ts->rhsfuncs));
19951e66621cSBarry Smith     if (ts->rhsjacs) PetscCall(PetscViewerASCIIPrintf(viewer, "  total number of RHS Jacobian evaluations=%" PetscInt_FMT "\n", ts->rhsjacs));
1996efd4aadfSBarry Smith     if (ts->usessnes) {
1997efd4aadfSBarry Smith       PetscBool lin;
19981e66621cSBarry Smith       if (ts->problem_type == TS_NONLINEAR) PetscCall(PetscViewerASCIIPrintf(viewer, "  total number of nonlinear solver iterations=%" PetscInt_FMT "\n", ts->snes_its));
199963a3b9bcSJacob Faibussowitsch       PetscCall(PetscViewerASCIIPrintf(viewer, "  total number of linear solver iterations=%" PetscInt_FMT "\n", ts->ksp_its));
20009566063dSJacob Faibussowitsch       PetscCall(PetscObjectTypeCompareAny((PetscObject)ts->snes, &lin, SNESKSPONLY, SNESKSPTRANSPOSEONLY, ""));
200163a3b9bcSJacob Faibussowitsch       PetscCall(PetscViewerASCIIPrintf(viewer, "  total number of %slinear solve failures=%" PetscInt_FMT "\n", lin ? "" : "non", ts->num_snes_failures));
2002efd4aadfSBarry Smith     }
200363a3b9bcSJacob Faibussowitsch     PetscCall(PetscViewerASCIIPrintf(viewer, "  total number of rejected steps=%" PetscInt_FMT "\n", ts->reject));
20041e66621cSBarry Smith     if (ts->vrtol) PetscCall(PetscViewerASCIIPrintf(viewer, "  using vector of relative error tolerances, "));
20051e66621cSBarry Smith     else PetscCall(PetscViewerASCIIPrintf(viewer, "  using relative error tolerance of %g, ", (double)ts->rtol));
20061e66621cSBarry Smith     if (ts->vatol) PetscCall(PetscViewerASCIIPrintf(viewer, "  using vector of absolute error tolerances\n"));
20071e66621cSBarry Smith     else PetscCall(PetscViewerASCIIPrintf(viewer, "  using absolute error tolerance of %g\n", (double)ts->atol));
20089566063dSJacob Faibussowitsch     PetscCall(PetscViewerASCIIPushTab(viewer));
20099566063dSJacob Faibussowitsch     PetscCall(TSAdaptView(ts->adapt, viewer));
20109566063dSJacob Faibussowitsch     PetscCall(PetscViewerASCIIPopTab(viewer));
20110f5bd95cSBarry Smith   } else if (isstring) {
20129566063dSJacob Faibussowitsch     PetscCall(TSGetType(ts, &type));
20139566063dSJacob Faibussowitsch     PetscCall(PetscViewerStringSPrintf(viewer, " TSType: %-7.7s", type));
2014dbbe0bcdSBarry Smith     PetscTryTypeMethod(ts, view, viewer);
201555849f57SBarry Smith   } else if (isbinary) {
201655849f57SBarry Smith     PetscInt    classid = TS_FILE_CLASSID;
201755849f57SBarry Smith     MPI_Comm    comm;
201855849f57SBarry Smith     PetscMPIInt rank;
201955849f57SBarry Smith     char        type[256];
202055849f57SBarry Smith 
20219566063dSJacob Faibussowitsch     PetscCall(PetscObjectGetComm((PetscObject)ts, &comm));
20229566063dSJacob Faibussowitsch     PetscCallMPI(MPI_Comm_rank(comm, &rank));
2023dd400576SPatrick Sanan     if (rank == 0) {
20249566063dSJacob Faibussowitsch       PetscCall(PetscViewerBinaryWrite(viewer, &classid, 1, PETSC_INT));
20259566063dSJacob Faibussowitsch       PetscCall(PetscStrncpy(type, ((PetscObject)ts)->type_name, 256));
20269566063dSJacob Faibussowitsch       PetscCall(PetscViewerBinaryWrite(viewer, type, 256, PETSC_CHAR));
202755849f57SBarry Smith     }
2028dbbe0bcdSBarry Smith     PetscTryTypeMethod(ts, view, viewer);
20299566063dSJacob Faibussowitsch     if (ts->adapt) PetscCall(TSAdaptView(ts->adapt, viewer));
20309566063dSJacob Faibussowitsch     PetscCall(DMView(ts->dm, viewer));
20319566063dSJacob Faibussowitsch     PetscCall(VecView(ts->vec_sol, viewer));
20329566063dSJacob Faibussowitsch     PetscCall(DMGetDMTS(ts->dm, &sdm));
20339566063dSJacob Faibussowitsch     PetscCall(DMTSView(sdm, viewer));
20342b0a91c0SBarry Smith   } else if (isdraw) {
20352b0a91c0SBarry Smith     PetscDraw draw;
20362b0a91c0SBarry Smith     char      str[36];
203789fd9fafSBarry Smith     PetscReal x, y, bottom, h;
20382b0a91c0SBarry Smith 
20399566063dSJacob Faibussowitsch     PetscCall(PetscViewerDrawGetDraw(viewer, 0, &draw));
20409566063dSJacob Faibussowitsch     PetscCall(PetscDrawGetCurrentPoint(draw, &x, &y));
20419566063dSJacob Faibussowitsch     PetscCall(PetscStrcpy(str, "TS: "));
20429566063dSJacob Faibussowitsch     PetscCall(PetscStrcat(str, ((PetscObject)ts)->type_name));
20439566063dSJacob Faibussowitsch     PetscCall(PetscDrawStringBoxed(draw, x, y, PETSC_DRAW_BLACK, PETSC_DRAW_BLACK, str, NULL, &h));
204489fd9fafSBarry Smith     bottom = y - h;
20459566063dSJacob Faibussowitsch     PetscCall(PetscDrawPushCurrentPoint(draw, x, bottom));
2046dbbe0bcdSBarry Smith     PetscTryTypeMethod(ts, view, viewer);
20479566063dSJacob Faibussowitsch     if (ts->adapt) PetscCall(TSAdaptView(ts->adapt, viewer));
20489566063dSJacob Faibussowitsch     if (ts->snes) PetscCall(SNESView(ts->snes, viewer));
20499566063dSJacob Faibussowitsch     PetscCall(PetscDrawPopCurrentPoint(draw));
2050e04113cfSBarry Smith #if defined(PETSC_HAVE_SAWS)
2051536b137fSBarry Smith   } else if (issaws) {
2052d45a07a7SBarry Smith     PetscMPIInt rank;
20532657e9d9SBarry Smith     const char *name;
20542657e9d9SBarry Smith 
20559566063dSJacob Faibussowitsch     PetscCall(PetscObjectGetName((PetscObject)ts, &name));
20569566063dSJacob Faibussowitsch     PetscCallMPI(MPI_Comm_rank(PETSC_COMM_WORLD, &rank));
2057dd400576SPatrick Sanan     if (!((PetscObject)ts)->amsmem && rank == 0) {
2058d45a07a7SBarry Smith       char dir[1024];
2059d45a07a7SBarry Smith 
20609566063dSJacob Faibussowitsch       PetscCall(PetscObjectViewSAWs((PetscObject)ts, viewer));
20619566063dSJacob Faibussowitsch       PetscCall(PetscSNPrintf(dir, 1024, "/PETSc/Objects/%s/time_step", name));
2062792fecdfSBarry Smith       PetscCallSAWs(SAWs_Register, (dir, &ts->steps, 1, SAWs_READ, SAWs_INT));
20639566063dSJacob Faibussowitsch       PetscCall(PetscSNPrintf(dir, 1024, "/PETSc/Objects/%s/time", name));
2064792fecdfSBarry Smith       PetscCallSAWs(SAWs_Register, (dir, &ts->ptime, 1, SAWs_READ, SAWs_DOUBLE));
2065d763cef2SBarry Smith     }
2066dbbe0bcdSBarry Smith     PetscTryTypeMethod(ts, view, viewer);
2067f05ece33SBarry Smith #endif
2068f05ece33SBarry Smith   }
206936a9e3b9SBarry Smith   if (ts->snes && ts->usessnes) {
20709566063dSJacob Faibussowitsch     PetscCall(PetscViewerASCIIPushTab(viewer));
20719566063dSJacob Faibussowitsch     PetscCall(SNESView(ts->snes, viewer));
20729566063dSJacob Faibussowitsch     PetscCall(PetscViewerASCIIPopTab(viewer));
207336a9e3b9SBarry Smith   }
20749566063dSJacob Faibussowitsch   PetscCall(DMGetDMTS(ts->dm, &sdm));
20759566063dSJacob Faibussowitsch   PetscCall(DMTSView(sdm, viewer));
2076f05ece33SBarry Smith 
20779566063dSJacob Faibussowitsch   PetscCall(PetscViewerASCIIPushTab(viewer));
20789566063dSJacob Faibussowitsch   PetscCall(PetscObjectTypeCompare((PetscObject)ts, TSSUNDIALS, &isundials));
20799566063dSJacob Faibussowitsch   PetscCall(PetscViewerASCIIPopTab(viewer));
2080d763cef2SBarry Smith   PetscFunctionReturn(0);
2081d763cef2SBarry Smith }
2082d763cef2SBarry Smith 
2083b07ff414SBarry Smith /*@
2084d763cef2SBarry Smith    TSSetApplicationContext - Sets an optional user-defined context for
2085d763cef2SBarry Smith    the timesteppers.
2086d763cef2SBarry Smith 
20873f9fe445SBarry Smith    Logically Collective on TS
2088d763cef2SBarry Smith 
2089d763cef2SBarry Smith    Input Parameters:
2090d763cef2SBarry Smith +  ts - the TS context obtained from TSCreate()
2091d763cef2SBarry Smith -  usrP - optional user context
2092d763cef2SBarry Smith 
209395452b02SPatrick Sanan    Fortran Notes:
209495452b02SPatrick Sanan     To use this from Fortran you must write a Fortran interface definition for this
2095daf670e6SBarry Smith     function that tells Fortran the Fortran derived data type that you are passing in as the ctx argument.
2096daf670e6SBarry Smith 
2097d763cef2SBarry Smith    Level: intermediate
2098d763cef2SBarry Smith 
2099db781477SPatrick Sanan .seealso: `TSGetApplicationContext()`
2100d763cef2SBarry Smith @*/
2101*d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetApplicationContext(TS ts, void *usrP)
2102*d71ae5a4SJacob Faibussowitsch {
2103d763cef2SBarry Smith   PetscFunctionBegin;
21040700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
2105d763cef2SBarry Smith   ts->user = usrP;
2106d763cef2SBarry Smith   PetscFunctionReturn(0);
2107d763cef2SBarry Smith }
2108d763cef2SBarry Smith 
2109b07ff414SBarry Smith /*@
2110d763cef2SBarry Smith     TSGetApplicationContext - Gets the user-defined context for the
2111d763cef2SBarry Smith     timestepper.
2112d763cef2SBarry Smith 
2113d763cef2SBarry Smith     Not Collective
2114d763cef2SBarry Smith 
2115d763cef2SBarry Smith     Input Parameter:
2116d763cef2SBarry Smith .   ts - the TS context obtained from TSCreate()
2117d763cef2SBarry Smith 
2118d763cef2SBarry Smith     Output Parameter:
2119d763cef2SBarry Smith .   usrP - user context
2120d763cef2SBarry Smith 
212195452b02SPatrick Sanan    Fortran Notes:
212295452b02SPatrick Sanan     To use this from Fortran you must write a Fortran interface definition for this
2123daf670e6SBarry Smith     function that tells Fortran the Fortran derived data type that you are passing in as the ctx argument.
2124daf670e6SBarry Smith 
2125d763cef2SBarry Smith     Level: intermediate
2126d763cef2SBarry Smith 
2127db781477SPatrick Sanan .seealso: `TSSetApplicationContext()`
2128d763cef2SBarry Smith @*/
2129*d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetApplicationContext(TS ts, void *usrP)
2130*d71ae5a4SJacob Faibussowitsch {
2131d763cef2SBarry Smith   PetscFunctionBegin;
21320700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
2133e71120c6SJed Brown   *(void **)usrP = ts->user;
2134d763cef2SBarry Smith   PetscFunctionReturn(0);
2135d763cef2SBarry Smith }
2136d763cef2SBarry Smith 
2137d763cef2SBarry Smith /*@
213880275a0aSLisandro Dalcin    TSGetStepNumber - Gets the number of steps completed.
2139d763cef2SBarry Smith 
2140d763cef2SBarry Smith    Not Collective
2141d763cef2SBarry Smith 
2142d763cef2SBarry Smith    Input Parameter:
2143d763cef2SBarry Smith .  ts - the TS context obtained from TSCreate()
2144d763cef2SBarry Smith 
2145d763cef2SBarry Smith    Output Parameter:
214680275a0aSLisandro Dalcin .  steps - number of steps completed so far
2147d763cef2SBarry Smith 
2148d763cef2SBarry Smith    Level: intermediate
2149d763cef2SBarry Smith 
2150db781477SPatrick Sanan .seealso: `TSGetTime()`, `TSGetTimeStep()`, `TSSetPreStep()`, `TSSetPreStage()`, `TSSetPostStage()`, `TSSetPostStep()`
2151d763cef2SBarry Smith @*/
2152*d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetStepNumber(TS ts, PetscInt *steps)
2153*d71ae5a4SJacob Faibussowitsch {
2154d763cef2SBarry Smith   PetscFunctionBegin;
21550700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
215680275a0aSLisandro Dalcin   PetscValidIntPointer(steps, 2);
215780275a0aSLisandro Dalcin   *steps = ts->steps;
215880275a0aSLisandro Dalcin   PetscFunctionReturn(0);
215980275a0aSLisandro Dalcin }
216080275a0aSLisandro Dalcin 
216180275a0aSLisandro Dalcin /*@
216280275a0aSLisandro Dalcin    TSSetStepNumber - Sets the number of steps completed.
216380275a0aSLisandro Dalcin 
216480275a0aSLisandro Dalcin    Logically Collective on TS
216580275a0aSLisandro Dalcin 
216680275a0aSLisandro Dalcin    Input Parameters:
216780275a0aSLisandro Dalcin +  ts - the TS context
216880275a0aSLisandro Dalcin -  steps - number of steps completed so far
216980275a0aSLisandro Dalcin 
217080275a0aSLisandro Dalcin    Notes:
217180275a0aSLisandro Dalcin    For most uses of the TS solvers the user need not explicitly call
217280275a0aSLisandro Dalcin    TSSetStepNumber(), as the step counter is appropriately updated in
217380275a0aSLisandro Dalcin    TSSolve()/TSStep()/TSRollBack(). Power users may call this routine to
217480275a0aSLisandro Dalcin    reinitialize timestepping by setting the step counter to zero (and time
217580275a0aSLisandro Dalcin    to the initial time) to solve a similar problem with different initial
217680275a0aSLisandro Dalcin    conditions or parameters. Other possible use case is to continue
217780275a0aSLisandro Dalcin    timestepping from a previously interrupted run in such a way that TS
217880275a0aSLisandro Dalcin    monitors will be called with a initial nonzero step counter.
217980275a0aSLisandro Dalcin 
218080275a0aSLisandro Dalcin    Level: advanced
218180275a0aSLisandro Dalcin 
2182db781477SPatrick Sanan .seealso: `TSGetStepNumber()`, `TSSetTime()`, `TSSetTimeStep()`, `TSSetSolution()`
218380275a0aSLisandro Dalcin @*/
2184*d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetStepNumber(TS ts, PetscInt steps)
2185*d71ae5a4SJacob Faibussowitsch {
218680275a0aSLisandro Dalcin   PetscFunctionBegin;
218780275a0aSLisandro Dalcin   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
218880275a0aSLisandro Dalcin   PetscValidLogicalCollectiveInt(ts, steps, 2);
21893c633725SBarry Smith   PetscCheck(steps >= 0, PetscObjectComm((PetscObject)ts), PETSC_ERR_ARG_OUTOFRANGE, "Step number must be non-negative");
219080275a0aSLisandro Dalcin   ts->steps = steps;
2191d763cef2SBarry Smith   PetscFunctionReturn(0);
2192d763cef2SBarry Smith }
2193d763cef2SBarry Smith 
2194d763cef2SBarry Smith /*@
2195d763cef2SBarry Smith    TSSetTimeStep - Allows one to reset the timestep at any time,
2196d763cef2SBarry Smith    useful for simple pseudo-timestepping codes.
2197d763cef2SBarry Smith 
21983f9fe445SBarry Smith    Logically Collective on TS
2199d763cef2SBarry Smith 
2200d763cef2SBarry Smith    Input Parameters:
2201d763cef2SBarry Smith +  ts - the TS context obtained from TSCreate()
2202d763cef2SBarry Smith -  time_step - the size of the timestep
2203d763cef2SBarry Smith 
2204d763cef2SBarry Smith    Level: intermediate
2205d763cef2SBarry Smith 
2206db781477SPatrick Sanan .seealso: `TSGetTimeStep()`, `TSSetTime()`
2207d763cef2SBarry Smith 
2208d763cef2SBarry Smith @*/
2209*d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetTimeStep(TS ts, PetscReal time_step)
2210*d71ae5a4SJacob Faibussowitsch {
2211d763cef2SBarry Smith   PetscFunctionBegin;
22120700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
2213c5eb9154SBarry Smith   PetscValidLogicalCollectiveReal(ts, time_step, 2);
2214d763cef2SBarry Smith   ts->time_step = time_step;
2215d763cef2SBarry Smith   PetscFunctionReturn(0);
2216d763cef2SBarry Smith }
2217d763cef2SBarry Smith 
2218a43b19c4SJed Brown /*@
221949354f04SShri Abhyankar    TSSetExactFinalTime - Determines whether to adapt the final time step to
222049354f04SShri Abhyankar      match the exact final time, interpolate solution to the exact final time,
222149354f04SShri Abhyankar      or just return at the final time TS computed.
2222a43b19c4SJed Brown 
2223a43b19c4SJed Brown   Logically Collective on TS
2224a43b19c4SJed Brown 
2225d8d19677SJose E. Roman    Input Parameters:
2226a43b19c4SJed Brown +   ts - the time-step context
222749354f04SShri Abhyankar -   eftopt - exact final time option
2228a43b19c4SJed Brown 
2229feed9e9dSBarry Smith $  TS_EXACTFINALTIME_STEPOVER    - Don't do anything if final time is exceeded
2230feed9e9dSBarry Smith $  TS_EXACTFINALTIME_INTERPOLATE - Interpolate back to final time
2231feed9e9dSBarry Smith $  TS_EXACTFINALTIME_MATCHSTEP - Adapt final time step to match the final time
2232feed9e9dSBarry Smith 
2233feed9e9dSBarry Smith    Options Database:
2234feed9e9dSBarry Smith .   -ts_exact_final_time <stepover,interpolate,matchstep> - select the final step at runtime
2235feed9e9dSBarry Smith 
2236ee346746SBarry Smith    Warning: If you use the option TS_EXACTFINALTIME_STEPOVER the solution may be at a very different time
2237ee346746SBarry Smith     then the final time you selected.
2238ee346746SBarry Smith 
2239a43b19c4SJed Brown    Level: beginner
2240a43b19c4SJed Brown 
2241db781477SPatrick Sanan .seealso: `TSExactFinalTimeOption`, `TSGetExactFinalTime()`
2242a43b19c4SJed Brown @*/
2243*d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetExactFinalTime(TS ts, TSExactFinalTimeOption eftopt)
2244*d71ae5a4SJacob Faibussowitsch {
2245a43b19c4SJed Brown   PetscFunctionBegin;
2246a43b19c4SJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
224749354f04SShri Abhyankar   PetscValidLogicalCollectiveEnum(ts, eftopt, 2);
224849354f04SShri Abhyankar   ts->exact_final_time = eftopt;
2249a43b19c4SJed Brown   PetscFunctionReturn(0);
2250a43b19c4SJed Brown }
2251a43b19c4SJed Brown 
2252d763cef2SBarry Smith /*@
2253f6953c82SLisandro Dalcin    TSGetExactFinalTime - Gets the exact final time option.
2254f6953c82SLisandro Dalcin 
2255f6953c82SLisandro Dalcin    Not Collective
2256f6953c82SLisandro Dalcin 
2257f6953c82SLisandro Dalcin    Input Parameter:
2258f6953c82SLisandro Dalcin .  ts - the TS context
2259f6953c82SLisandro Dalcin 
2260f6953c82SLisandro Dalcin    Output Parameter:
2261f6953c82SLisandro Dalcin .  eftopt - exact final time option
2262f6953c82SLisandro Dalcin 
2263f6953c82SLisandro Dalcin    Level: beginner
2264f6953c82SLisandro Dalcin 
2265db781477SPatrick Sanan .seealso: `TSExactFinalTimeOption`, `TSSetExactFinalTime()`
2266f6953c82SLisandro Dalcin @*/
2267*d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetExactFinalTime(TS ts, TSExactFinalTimeOption *eftopt)
2268*d71ae5a4SJacob Faibussowitsch {
2269f6953c82SLisandro Dalcin   PetscFunctionBegin;
2270f6953c82SLisandro Dalcin   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
2271f6953c82SLisandro Dalcin   PetscValidPointer(eftopt, 2);
2272f6953c82SLisandro Dalcin   *eftopt = ts->exact_final_time;
2273f6953c82SLisandro Dalcin   PetscFunctionReturn(0);
2274f6953c82SLisandro Dalcin }
2275f6953c82SLisandro Dalcin 
2276f6953c82SLisandro Dalcin /*@
2277d763cef2SBarry Smith    TSGetTimeStep - Gets the current timestep size.
2278d763cef2SBarry Smith 
2279d763cef2SBarry Smith    Not Collective
2280d763cef2SBarry Smith 
2281d763cef2SBarry Smith    Input Parameter:
2282d763cef2SBarry Smith .  ts - the TS context obtained from TSCreate()
2283d763cef2SBarry Smith 
2284d763cef2SBarry Smith    Output Parameter:
2285d763cef2SBarry Smith .  dt - the current timestep size
2286d763cef2SBarry Smith 
2287d763cef2SBarry Smith    Level: intermediate
2288d763cef2SBarry Smith 
2289db781477SPatrick Sanan .seealso: `TSSetTimeStep()`, `TSGetTime()`
2290d763cef2SBarry Smith 
2291d763cef2SBarry Smith @*/
2292*d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetTimeStep(TS ts, PetscReal *dt)
2293*d71ae5a4SJacob Faibussowitsch {
2294d763cef2SBarry Smith   PetscFunctionBegin;
22950700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
2296f7cf8827SBarry Smith   PetscValidRealPointer(dt, 2);
2297d763cef2SBarry Smith   *dt = ts->time_step;
2298d763cef2SBarry Smith   PetscFunctionReturn(0);
2299d763cef2SBarry Smith }
2300d763cef2SBarry Smith 
2301d8e5e3e6SSatish Balay /*@
2302d763cef2SBarry Smith    TSGetSolution - Returns the solution at the present timestep. It
2303d763cef2SBarry Smith    is valid to call this routine inside the function that you are evaluating
2304d763cef2SBarry Smith    in order to move to the new timestep. This vector not changed until
2305d763cef2SBarry Smith    the solution at the next timestep has been calculated.
2306d763cef2SBarry Smith 
2307d763cef2SBarry Smith    Not Collective, but Vec returned is parallel if TS is parallel
2308d763cef2SBarry Smith 
2309d763cef2SBarry Smith    Input Parameter:
2310d763cef2SBarry Smith .  ts - the TS context obtained from TSCreate()
2311d763cef2SBarry Smith 
2312d763cef2SBarry Smith    Output Parameter:
2313d763cef2SBarry Smith .  v - the vector containing the solution
2314d763cef2SBarry Smith 
231563e21af5SBarry Smith    Note: If you used TSSetExactFinalTime(ts,TS_EXACTFINALTIME_MATCHSTEP); this does not return the solution at the requested
231663e21af5SBarry Smith    final time. It returns the solution at the next timestep.
231763e21af5SBarry Smith 
2318d763cef2SBarry Smith    Level: intermediate
2319d763cef2SBarry Smith 
2320db781477SPatrick Sanan .seealso: `TSGetTimeStep()`, `TSGetTime()`, `TSGetSolveTime()`, `TSGetSolutionComponents()`, `TSSetSolutionFunction()`
2321d763cef2SBarry Smith 
2322d763cef2SBarry Smith @*/
2323*d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetSolution(TS ts, Vec *v)
2324*d71ae5a4SJacob Faibussowitsch {
2325d763cef2SBarry Smith   PetscFunctionBegin;
23260700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
23274482741eSBarry Smith   PetscValidPointer(v, 2);
23288737fe31SLisandro Dalcin   *v = ts->vec_sol;
2329d763cef2SBarry Smith   PetscFunctionReturn(0);
2330d763cef2SBarry Smith }
2331d763cef2SBarry Smith 
233203fe5f5eSDebojyoti Ghosh /*@
2333b2bf4f3aSDebojyoti Ghosh    TSGetSolutionComponents - Returns any solution components at the present
233403fe5f5eSDebojyoti Ghosh    timestep, if available for the time integration method being used.
2335b2bf4f3aSDebojyoti Ghosh    Solution components are quantities that share the same size and
233603fe5f5eSDebojyoti Ghosh    structure as the solution vector.
233703fe5f5eSDebojyoti Ghosh 
233803fe5f5eSDebojyoti Ghosh    Not Collective, but Vec returned is parallel if TS is parallel
233903fe5f5eSDebojyoti Ghosh 
234003fe5f5eSDebojyoti Ghosh    Parameters :
2341a2b725a8SWilliam Gropp +  ts - the TS context obtained from TSCreate() (input parameter).
2342b2bf4f3aSDebojyoti Ghosh .  n - If v is PETSC_NULL, then the number of solution components is
2343b2bf4f3aSDebojyoti Ghosh        returned through n, else the n-th solution component is
234403fe5f5eSDebojyoti Ghosh        returned in v.
2345a2b725a8SWilliam Gropp -  v - the vector containing the n-th solution component
234603fe5f5eSDebojyoti Ghosh        (may be PETSC_NULL to use this function to find out
2347b2bf4f3aSDebojyoti Ghosh         the number of solutions components).
234803fe5f5eSDebojyoti Ghosh 
23494cdd57e5SDebojyoti Ghosh    Level: advanced
235003fe5f5eSDebojyoti Ghosh 
2351db781477SPatrick Sanan .seealso: `TSGetSolution()`
235203fe5f5eSDebojyoti Ghosh 
235303fe5f5eSDebojyoti Ghosh @*/
2354*d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetSolutionComponents(TS ts, PetscInt *n, Vec *v)
2355*d71ae5a4SJacob Faibussowitsch {
235603fe5f5eSDebojyoti Ghosh   PetscFunctionBegin;
235703fe5f5eSDebojyoti Ghosh   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
2358b2bf4f3aSDebojyoti Ghosh   if (!ts->ops->getsolutioncomponents) *n = 0;
2359dbbe0bcdSBarry Smith   else PetscUseTypeMethod(ts, getsolutioncomponents, n, v);
236003fe5f5eSDebojyoti Ghosh   PetscFunctionReturn(0);
236103fe5f5eSDebojyoti Ghosh }
236203fe5f5eSDebojyoti Ghosh 
23634cdd57e5SDebojyoti Ghosh /*@
23644cdd57e5SDebojyoti Ghosh    TSGetAuxSolution - Returns an auxiliary solution at the present
23654cdd57e5SDebojyoti Ghosh    timestep, if available for the time integration method being used.
23664cdd57e5SDebojyoti Ghosh 
23674cdd57e5SDebojyoti Ghosh    Not Collective, but Vec returned is parallel if TS is parallel
23684cdd57e5SDebojyoti Ghosh 
23694cdd57e5SDebojyoti Ghosh    Parameters :
2370a2b725a8SWilliam Gropp +  ts - the TS context obtained from TSCreate() (input parameter).
2371a2b725a8SWilliam Gropp -  v - the vector containing the auxiliary solution
23724cdd57e5SDebojyoti Ghosh 
23734cdd57e5SDebojyoti Ghosh    Level: intermediate
23744cdd57e5SDebojyoti Ghosh 
2375db781477SPatrick Sanan .seealso: `TSGetSolution()`
23764cdd57e5SDebojyoti Ghosh 
23774cdd57e5SDebojyoti Ghosh @*/
2378*d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetAuxSolution(TS ts, Vec *v)
2379*d71ae5a4SJacob Faibussowitsch {
23804cdd57e5SDebojyoti Ghosh   PetscFunctionBegin;
23814cdd57e5SDebojyoti Ghosh   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
2382dbbe0bcdSBarry Smith   if (ts->ops->getauxsolution) PetscUseTypeMethod(ts, getauxsolution, v);
23831e66621cSBarry Smith   else PetscCall(VecZeroEntries(*v));
23844cdd57e5SDebojyoti Ghosh   PetscFunctionReturn(0);
23854cdd57e5SDebojyoti Ghosh }
23864cdd57e5SDebojyoti Ghosh 
23874cdd57e5SDebojyoti Ghosh /*@
23884cdd57e5SDebojyoti Ghosh    TSGetTimeError - Returns the estimated error vector, if the chosen
23894cdd57e5SDebojyoti Ghosh    TSType has an error estimation functionality.
23904cdd57e5SDebojyoti Ghosh 
23914cdd57e5SDebojyoti Ghosh    Not Collective, but Vec returned is parallel if TS is parallel
23924cdd57e5SDebojyoti Ghosh 
23939657682dSDebojyoti Ghosh    Note: MUST call after TSSetUp()
23949657682dSDebojyoti Ghosh 
23954cdd57e5SDebojyoti Ghosh    Parameters :
2396a2b725a8SWilliam Gropp +  ts - the TS context obtained from TSCreate() (input parameter).
2397657c1e31SEmil Constantinescu .  n - current estimate (n=0) or previous one (n=-1)
2398a2b725a8SWilliam Gropp -  v - the vector containing the error (same size as the solution).
23994cdd57e5SDebojyoti Ghosh 
24004cdd57e5SDebojyoti Ghosh    Level: intermediate
24014cdd57e5SDebojyoti Ghosh 
2402db781477SPatrick Sanan .seealso: `TSGetSolution()`, `TSSetTimeError()`
24034cdd57e5SDebojyoti Ghosh 
24044cdd57e5SDebojyoti Ghosh @*/
2405*d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetTimeError(TS ts, PetscInt n, Vec *v)
2406*d71ae5a4SJacob Faibussowitsch {
24074cdd57e5SDebojyoti Ghosh   PetscFunctionBegin;
24084cdd57e5SDebojyoti Ghosh   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
2409dbbe0bcdSBarry Smith   if (ts->ops->gettimeerror) PetscUseTypeMethod(ts, gettimeerror, n, v);
24101e66621cSBarry Smith   else PetscCall(VecZeroEntries(*v));
24114cdd57e5SDebojyoti Ghosh   PetscFunctionReturn(0);
24124cdd57e5SDebojyoti Ghosh }
24134cdd57e5SDebojyoti Ghosh 
241457df6a1bSDebojyoti Ghosh /*@
241557df6a1bSDebojyoti Ghosh    TSSetTimeError - Sets the estimated error vector, if the chosen
241657df6a1bSDebojyoti Ghosh    TSType has an error estimation functionality. This can be used
241757df6a1bSDebojyoti Ghosh    to restart such a time integrator with a given error vector.
241857df6a1bSDebojyoti Ghosh 
241957df6a1bSDebojyoti Ghosh    Not Collective, but Vec returned is parallel if TS is parallel
242057df6a1bSDebojyoti Ghosh 
242157df6a1bSDebojyoti Ghosh    Parameters :
2422a2b725a8SWilliam Gropp +  ts - the TS context obtained from TSCreate() (input parameter).
2423a2b725a8SWilliam Gropp -  v - the vector containing the error (same size as the solution).
242457df6a1bSDebojyoti Ghosh 
242557df6a1bSDebojyoti Ghosh    Level: intermediate
242657df6a1bSDebojyoti Ghosh 
2427db781477SPatrick Sanan .seealso: `TSSetSolution()`, `TSGetTimeError)`
242857df6a1bSDebojyoti Ghosh 
242957df6a1bSDebojyoti Ghosh @*/
2430*d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetTimeError(TS ts, Vec v)
2431*d71ae5a4SJacob Faibussowitsch {
243257df6a1bSDebojyoti Ghosh   PetscFunctionBegin;
243357df6a1bSDebojyoti Ghosh   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
24343c633725SBarry Smith   PetscCheck(ts->setupcalled, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Must call TSSetUp() first");
2435dbbe0bcdSBarry Smith   PetscTryTypeMethod(ts, settimeerror, v);
243657df6a1bSDebojyoti Ghosh   PetscFunctionReturn(0);
243757df6a1bSDebojyoti Ghosh }
243857df6a1bSDebojyoti Ghosh 
2439bdad233fSMatthew Knepley /* ----- Routines to initialize and destroy a timestepper ---- */
2440d8e5e3e6SSatish Balay /*@
2441bdad233fSMatthew Knepley   TSSetProblemType - Sets the type of problem to be solved.
2442d763cef2SBarry Smith 
2443bdad233fSMatthew Knepley   Not collective
2444d763cef2SBarry Smith 
2445bdad233fSMatthew Knepley   Input Parameters:
2446bdad233fSMatthew Knepley + ts   - The TS
2447bdad233fSMatthew Knepley - type - One of TS_LINEAR, TS_NONLINEAR where these types refer to problems of the forms
2448d763cef2SBarry Smith .vb
24490910c330SBarry Smith          U_t - A U = 0      (linear)
24500910c330SBarry Smith          U_t - A(t) U = 0   (linear)
24510910c330SBarry Smith          F(t,U,U_t) = 0     (nonlinear)
2452d763cef2SBarry Smith .ve
2453d763cef2SBarry Smith 
2454d763cef2SBarry Smith    Level: beginner
2455d763cef2SBarry Smith 
2456db781477SPatrick Sanan .seealso: `TSSetUp()`, `TSProblemType`, `TS`
2457d763cef2SBarry Smith @*/
2458*d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetProblemType(TS ts, TSProblemType type)
2459*d71ae5a4SJacob Faibussowitsch {
2460d763cef2SBarry Smith   PetscFunctionBegin;
24610700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
2462bdad233fSMatthew Knepley   ts->problem_type = type;
24639e2a6581SJed Brown   if (type == TS_LINEAR) {
24649e2a6581SJed Brown     SNES snes;
24659566063dSJacob Faibussowitsch     PetscCall(TSGetSNES(ts, &snes));
24669566063dSJacob Faibussowitsch     PetscCall(SNESSetType(snes, SNESKSPONLY));
24679e2a6581SJed Brown   }
2468d763cef2SBarry Smith   PetscFunctionReturn(0);
2469d763cef2SBarry Smith }
2470d763cef2SBarry Smith 
2471bdad233fSMatthew Knepley /*@C
2472bdad233fSMatthew Knepley   TSGetProblemType - Gets the type of problem to be solved.
2473bdad233fSMatthew Knepley 
2474bdad233fSMatthew Knepley   Not collective
2475bdad233fSMatthew Knepley 
2476bdad233fSMatthew Knepley   Input Parameter:
2477bdad233fSMatthew Knepley . ts   - The TS
2478bdad233fSMatthew Knepley 
2479bdad233fSMatthew Knepley   Output Parameter:
2480bdad233fSMatthew Knepley . type - One of TS_LINEAR, TS_NONLINEAR where these types refer to problems of the forms
2481bdad233fSMatthew Knepley .vb
2482089b2837SJed Brown          M U_t = A U
2483089b2837SJed Brown          M(t) U_t = A(t) U
2484b5abc632SBarry Smith          F(t,U,U_t)
2485bdad233fSMatthew Knepley .ve
2486bdad233fSMatthew Knepley 
2487bdad233fSMatthew Knepley    Level: beginner
2488bdad233fSMatthew Knepley 
2489db781477SPatrick Sanan .seealso: `TSSetUp()`, `TSProblemType`, `TS`
2490bdad233fSMatthew Knepley @*/
2491*d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetProblemType(TS ts, TSProblemType *type)
2492*d71ae5a4SJacob Faibussowitsch {
2493bdad233fSMatthew Knepley   PetscFunctionBegin;
24940700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
24954482741eSBarry Smith   PetscValidIntPointer(type, 2);
2496bdad233fSMatthew Knepley   *type = ts->problem_type;
2497bdad233fSMatthew Knepley   PetscFunctionReturn(0);
2498bdad233fSMatthew Knepley }
2499d763cef2SBarry Smith 
2500303a5415SBarry Smith /*
2501303a5415SBarry 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()
2502303a5415SBarry Smith */
2503*d71ae5a4SJacob Faibussowitsch static PetscErrorCode TSSetExactFinalTimeDefault(TS ts)
2504*d71ae5a4SJacob Faibussowitsch {
2505303a5415SBarry Smith   PetscBool isnone;
2506303a5415SBarry Smith 
2507303a5415SBarry Smith   PetscFunctionBegin;
25089566063dSJacob Faibussowitsch   PetscCall(TSGetAdapt(ts, &ts->adapt));
25099566063dSJacob Faibussowitsch   PetscCall(TSAdaptSetDefaultType(ts->adapt, ts->default_adapt_type));
2510303a5415SBarry Smith 
25119566063dSJacob Faibussowitsch   PetscCall(PetscObjectTypeCompare((PetscObject)ts->adapt, TSADAPTNONE, &isnone));
25121e66621cSBarry Smith   if (!isnone && ts->exact_final_time == TS_EXACTFINALTIME_UNSPECIFIED) ts->exact_final_time = TS_EXACTFINALTIME_MATCHSTEP;
25131e66621cSBarry Smith   else if (ts->exact_final_time == TS_EXACTFINALTIME_UNSPECIFIED) ts->exact_final_time = TS_EXACTFINALTIME_INTERPOLATE;
2514303a5415SBarry Smith   PetscFunctionReturn(0);
2515303a5415SBarry Smith }
2516303a5415SBarry Smith 
2517d763cef2SBarry Smith /*@
2518303a5415SBarry Smith    TSSetUp - Sets up the internal data structures for the later use of a timestepper.
2519d763cef2SBarry Smith 
2520d763cef2SBarry Smith    Collective on TS
2521d763cef2SBarry Smith 
2522d763cef2SBarry Smith    Input Parameter:
2523d763cef2SBarry Smith .  ts - the TS context obtained from TSCreate()
2524d763cef2SBarry Smith 
2525d763cef2SBarry Smith    Notes:
2526d763cef2SBarry Smith    For basic use of the TS solvers the user need not explicitly call
2527d763cef2SBarry Smith    TSSetUp(), since these actions will automatically occur during
2528141bd67dSStefano Zampini    the call to TSStep() or TSSolve().  However, if one wishes to control this
2529d763cef2SBarry Smith    phase separately, TSSetUp() should be called after TSCreate()
2530141bd67dSStefano Zampini    and optional routines of the form TSSetXXX(), but before TSStep() and TSSolve().
2531d763cef2SBarry Smith 
2532d763cef2SBarry Smith    Level: advanced
2533d763cef2SBarry Smith 
2534db781477SPatrick Sanan .seealso: `TSCreate()`, `TSStep()`, `TSDestroy()`, `TSSolve()`
2535d763cef2SBarry Smith @*/
2536*d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetUp(TS ts)
2537*d71ae5a4SJacob Faibussowitsch {
25386c6b9e74SPeter Brune   DM dm;
25396c6b9e74SPeter Brune   PetscErrorCode (*func)(SNES, Vec, Vec, void *);
2540d1e9a80fSBarry Smith   PetscErrorCode (*jac)(SNES, Vec, Mat, Mat, void *);
2541cd11d68dSLisandro Dalcin   TSIFunction   ifun;
25426c6b9e74SPeter Brune   TSIJacobian   ijac;
2543efe9872eSLisandro Dalcin   TSI2Jacobian  i2jac;
25446c6b9e74SPeter Brune   TSRHSJacobian rhsjac;
2545d763cef2SBarry Smith 
2546d763cef2SBarry Smith   PetscFunctionBegin;
25470700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
2548277b19d0SLisandro Dalcin   if (ts->setupcalled) PetscFunctionReturn(0);
2549277b19d0SLisandro Dalcin 
25507adad957SLisandro Dalcin   if (!((PetscObject)ts)->type_name) {
25519566063dSJacob Faibussowitsch     PetscCall(TSGetIFunction(ts, NULL, &ifun, NULL));
25529566063dSJacob Faibussowitsch     PetscCall(TSSetType(ts, ifun ? TSBEULER : TSEULER));
2553d763cef2SBarry Smith   }
2554277b19d0SLisandro Dalcin 
25551a638600SStefano Zampini   if (!ts->vec_sol) {
25561e66621cSBarry Smith     PetscCheck(ts->dm, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Must call TSSetSolution() first");
25579566063dSJacob Faibussowitsch     PetscCall(DMCreateGlobalVector(ts->dm, &ts->vec_sol));
25581a638600SStefano Zampini   }
2559277b19d0SLisandro Dalcin 
25604a658b32SHong Zhang   if (ts->tspan) {
25611e66621cSBarry Smith     if (!ts->tspan->vecs_sol) PetscCall(VecDuplicateVecs(ts->vec_sol, ts->tspan->num_span_times, &ts->tspan->vecs_sol));
25624a658b32SHong Zhang   }
2563298bade4SHong Zhang   if (!ts->Jacp && ts->Jacprhs) { /* IJacobianP shares the same matrix with RHSJacobianP if only RHSJacobianP is provided */
25649566063dSJacob Faibussowitsch     PetscCall(PetscObjectReference((PetscObject)ts->Jacprhs));
2565298bade4SHong Zhang     ts->Jacp = ts->Jacprhs;
2566298bade4SHong Zhang   }
2567298bade4SHong Zhang 
2568cd4cee2dSHong Zhang   if (ts->quadraturets) {
25699566063dSJacob Faibussowitsch     PetscCall(TSSetUp(ts->quadraturets));
25709566063dSJacob Faibussowitsch     PetscCall(VecDestroy(&ts->vec_costintegrand));
25719566063dSJacob Faibussowitsch     PetscCall(VecDuplicate(ts->quadraturets->vec_sol, &ts->vec_costintegrand));
2572cd4cee2dSHong Zhang   }
2573cd4cee2dSHong Zhang 
25749566063dSJacob Faibussowitsch   PetscCall(TSGetRHSJacobian(ts, NULL, NULL, &rhsjac, NULL));
2575f23ba4b3SHong Zhang   if (rhsjac == TSComputeRHSJacobianConstant) {
2576e1244c69SJed Brown     Mat  Amat, Pmat;
2577e1244c69SJed Brown     SNES snes;
25789566063dSJacob Faibussowitsch     PetscCall(TSGetSNES(ts, &snes));
25799566063dSJacob Faibussowitsch     PetscCall(SNESGetJacobian(snes, &Amat, &Pmat, NULL, NULL));
2580e1244c69SJed Brown     /* Matching matrices implies that an IJacobian is NOT set, because if it had been set, the IJacobian's matrix would
2581e1244c69SJed Brown      * have displaced the RHS matrix */
2582971015bcSStefano Zampini     if (Amat && Amat == ts->Arhs) {
2583abc0d4abSBarry 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 */
25849566063dSJacob Faibussowitsch       PetscCall(MatDuplicate(ts->Arhs, MAT_COPY_VALUES, &Amat));
25859566063dSJacob Faibussowitsch       PetscCall(SNESSetJacobian(snes, Amat, NULL, NULL, NULL));
25869566063dSJacob Faibussowitsch       PetscCall(MatDestroy(&Amat));
2587e1244c69SJed Brown     }
2588971015bcSStefano Zampini     if (Pmat && Pmat == ts->Brhs) {
25899566063dSJacob Faibussowitsch       PetscCall(MatDuplicate(ts->Brhs, MAT_COPY_VALUES, &Pmat));
25909566063dSJacob Faibussowitsch       PetscCall(SNESSetJacobian(snes, NULL, Pmat, NULL, NULL));
25919566063dSJacob Faibussowitsch       PetscCall(MatDestroy(&Pmat));
2592e1244c69SJed Brown     }
2593e1244c69SJed Brown   }
25942ffb9264SLisandro Dalcin 
25959566063dSJacob Faibussowitsch   PetscCall(TSGetAdapt(ts, &ts->adapt));
25969566063dSJacob Faibussowitsch   PetscCall(TSAdaptSetDefaultType(ts->adapt, ts->default_adapt_type));
25972ffb9264SLisandro Dalcin 
2598dbbe0bcdSBarry Smith   PetscTryTypeMethod(ts, setup);
2599277b19d0SLisandro Dalcin 
26009566063dSJacob Faibussowitsch   PetscCall(TSSetExactFinalTimeDefault(ts));
26012ffb9264SLisandro Dalcin 
2602a6772fa2SLisandro Dalcin   /* In the case where we've set a DMTSFunction or what have you, we need the default SNESFunction
26036c6b9e74SPeter Brune      to be set right but can't do it elsewhere due to the overreliance on ctx=ts.
26046c6b9e74SPeter Brune    */
26059566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
26069566063dSJacob Faibussowitsch   PetscCall(DMSNESGetFunction(dm, &func, NULL));
26071e66621cSBarry Smith   if (!func) PetscCall(DMSNESSetFunction(dm, SNESTSFormFunction, ts));
26081e66621cSBarry Smith 
2609a6772fa2SLisandro 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.
26106c6b9e74SPeter Brune      Otherwise, the SNES will use coloring internally to form the Jacobian.
26116c6b9e74SPeter Brune    */
26129566063dSJacob Faibussowitsch   PetscCall(DMSNESGetJacobian(dm, &jac, NULL));
26139566063dSJacob Faibussowitsch   PetscCall(DMTSGetIJacobian(dm, &ijac, NULL));
26149566063dSJacob Faibussowitsch   PetscCall(DMTSGetI2Jacobian(dm, &i2jac, NULL));
26159566063dSJacob Faibussowitsch   PetscCall(DMTSGetRHSJacobian(dm, &rhsjac, NULL));
26161e66621cSBarry Smith   if (!jac && (ijac || i2jac || rhsjac)) PetscCall(DMSNESSetJacobian(dm, SNESTSFormJacobian, ts));
2617c0517034SDebojyoti Ghosh 
2618c0517034SDebojyoti Ghosh   /* if time integration scheme has a starting method, call it */
2619dbbe0bcdSBarry Smith   PetscTryTypeMethod(ts, startingmethod);
2620c0517034SDebojyoti Ghosh 
2621277b19d0SLisandro Dalcin   ts->setupcalled = PETSC_TRUE;
2622277b19d0SLisandro Dalcin   PetscFunctionReturn(0);
2623277b19d0SLisandro Dalcin }
2624277b19d0SLisandro Dalcin 
2625f6a906c0SBarry Smith /*@
2626277b19d0SLisandro Dalcin    TSReset - Resets a TS context and removes any allocated Vecs and Mats.
2627277b19d0SLisandro Dalcin 
2628277b19d0SLisandro Dalcin    Collective on TS
2629277b19d0SLisandro Dalcin 
2630277b19d0SLisandro Dalcin    Input Parameter:
2631277b19d0SLisandro Dalcin .  ts - the TS context obtained from TSCreate()
2632277b19d0SLisandro Dalcin 
2633277b19d0SLisandro Dalcin    Level: beginner
2634277b19d0SLisandro Dalcin 
2635db781477SPatrick Sanan .seealso: `TSCreate()`, `TSSetup()`, `TSDestroy()`
2636277b19d0SLisandro Dalcin @*/
2637*d71ae5a4SJacob Faibussowitsch PetscErrorCode TSReset(TS ts)
2638*d71ae5a4SJacob Faibussowitsch {
26391d06f6b3SHong Zhang   TS_RHSSplitLink ilink = ts->tsrhssplit, next;
2640277b19d0SLisandro Dalcin 
2641277b19d0SLisandro Dalcin   PetscFunctionBegin;
2642277b19d0SLisandro Dalcin   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
2643b18ea86cSHong Zhang 
2644dbbe0bcdSBarry Smith   PetscTryTypeMethod(ts, reset);
26459566063dSJacob Faibussowitsch   if (ts->snes) PetscCall(SNESReset(ts->snes));
26469566063dSJacob Faibussowitsch   if (ts->adapt) PetscCall(TSAdaptReset(ts->adapt));
2647bbd56ea5SKarl Rupp 
26489566063dSJacob Faibussowitsch   PetscCall(MatDestroy(&ts->Arhs));
26499566063dSJacob Faibussowitsch   PetscCall(MatDestroy(&ts->Brhs));
26509566063dSJacob Faibussowitsch   PetscCall(VecDestroy(&ts->Frhs));
26519566063dSJacob Faibussowitsch   PetscCall(VecDestroy(&ts->vec_sol));
26529566063dSJacob Faibussowitsch   PetscCall(VecDestroy(&ts->vec_dot));
26539566063dSJacob Faibussowitsch   PetscCall(VecDestroy(&ts->vatol));
26549566063dSJacob Faibussowitsch   PetscCall(VecDestroy(&ts->vrtol));
26559566063dSJacob Faibussowitsch   PetscCall(VecDestroyVecs(ts->nwork, &ts->work));
2656bbd56ea5SKarl Rupp 
26579566063dSJacob Faibussowitsch   PetscCall(MatDestroy(&ts->Jacprhs));
26589566063dSJacob Faibussowitsch   PetscCall(MatDestroy(&ts->Jacp));
26591baa6e33SBarry Smith   if (ts->forward_solve) PetscCall(TSForwardReset(ts));
2660cd4cee2dSHong Zhang   if (ts->quadraturets) {
26619566063dSJacob Faibussowitsch     PetscCall(TSReset(ts->quadraturets));
26629566063dSJacob Faibussowitsch     PetscCall(VecDestroy(&ts->vec_costintegrand));
2663cd4cee2dSHong Zhang   }
26641d06f6b3SHong Zhang   while (ilink) {
26651d06f6b3SHong Zhang     next = ilink->next;
26669566063dSJacob Faibussowitsch     PetscCall(TSDestroy(&ilink->ts));
26679566063dSJacob Faibussowitsch     PetscCall(PetscFree(ilink->splitname));
26689566063dSJacob Faibussowitsch     PetscCall(ISDestroy(&ilink->is));
26699566063dSJacob Faibussowitsch     PetscCall(PetscFree(ilink));
26701d06f6b3SHong Zhang     ilink = next;
267187f4e208SHong Zhang   }
26726bf673ebSJoe Pusztay   ts->tsrhssplit     = NULL;
2673545aaa6fSHong Zhang   ts->num_rhs_splits = 0;
26744a658b32SHong Zhang   if (ts->tspan) {
26754a658b32SHong Zhang     PetscCall(PetscFree(ts->tspan->span_times));
26764a658b32SHong Zhang     PetscCall(VecDestroyVecs(ts->tspan->num_span_times, &ts->tspan->vecs_sol));
26774a658b32SHong Zhang     PetscCall(PetscFree(ts->tspan));
26784a658b32SHong Zhang   }
2679277b19d0SLisandro Dalcin   ts->setupcalled = PETSC_FALSE;
2680d763cef2SBarry Smith   PetscFunctionReturn(0);
2681d763cef2SBarry Smith }
2682d763cef2SBarry Smith 
26831fb7b255SJunchao Zhang /*@C
2684d763cef2SBarry Smith    TSDestroy - Destroys the timestepper context that was created
2685d763cef2SBarry Smith    with TSCreate().
2686d763cef2SBarry Smith 
2687d763cef2SBarry Smith    Collective on TS
2688d763cef2SBarry Smith 
2689d763cef2SBarry Smith    Input Parameter:
2690d763cef2SBarry Smith .  ts - the TS context obtained from TSCreate()
2691d763cef2SBarry Smith 
2692d763cef2SBarry Smith    Level: beginner
2693d763cef2SBarry Smith 
2694db781477SPatrick Sanan .seealso: `TSCreate()`, `TSSetUp()`, `TSSolve()`
2695d763cef2SBarry Smith @*/
2696*d71ae5a4SJacob Faibussowitsch PetscErrorCode TSDestroy(TS *ts)
2697*d71ae5a4SJacob Faibussowitsch {
2698d763cef2SBarry Smith   PetscFunctionBegin;
26996bf464f9SBarry Smith   if (!*ts) PetscFunctionReturn(0);
2700ecf68647SHong Zhang   PetscValidHeaderSpecific(*ts, TS_CLASSID, 1);
27019371c9d4SSatish Balay   if (--((PetscObject)(*ts))->refct > 0) {
27029371c9d4SSatish Balay     *ts = NULL;
27039371c9d4SSatish Balay     PetscFunctionReturn(0);
27049371c9d4SSatish Balay   }
2705d763cef2SBarry Smith 
27069566063dSJacob Faibussowitsch   PetscCall(TSReset(*ts));
27079566063dSJacob Faibussowitsch   PetscCall(TSAdjointReset(*ts));
27081e66621cSBarry Smith   if ((*ts)->forward_solve) PetscCall(TSForwardReset(*ts));
27091e66621cSBarry Smith 
2710e04113cfSBarry Smith   /* if memory was published with SAWs then destroy it */
27119566063dSJacob Faibussowitsch   PetscCall(PetscObjectSAWsViewOff((PetscObject)*ts));
2712dbbe0bcdSBarry Smith   PetscTryTypeMethod((*ts), destroy);
27136d4c513bSLisandro Dalcin 
27149566063dSJacob Faibussowitsch   PetscCall(TSTrajectoryDestroy(&(*ts)->trajectory));
2715bc952696SBarry Smith 
27169566063dSJacob Faibussowitsch   PetscCall(TSAdaptDestroy(&(*ts)->adapt));
27179566063dSJacob Faibussowitsch   PetscCall(TSEventDestroy(&(*ts)->event));
27186427ac75SLisandro Dalcin 
27199566063dSJacob Faibussowitsch   PetscCall(SNESDestroy(&(*ts)->snes));
27209566063dSJacob Faibussowitsch   PetscCall(DMDestroy(&(*ts)->dm));
27219566063dSJacob Faibussowitsch   PetscCall(TSMonitorCancel((*ts)));
27229566063dSJacob Faibussowitsch   PetscCall(TSAdjointMonitorCancel((*ts)));
27236d4c513bSLisandro Dalcin 
27249566063dSJacob Faibussowitsch   PetscCall(TSDestroy(&(*ts)->quadraturets));
27259566063dSJacob Faibussowitsch   PetscCall(PetscHeaderDestroy(ts));
2726d763cef2SBarry Smith   PetscFunctionReturn(0);
2727d763cef2SBarry Smith }
2728d763cef2SBarry Smith 
2729d8e5e3e6SSatish Balay /*@
2730d763cef2SBarry Smith    TSGetSNES - Returns the SNES (nonlinear solver) associated with
2731d763cef2SBarry Smith    a TS (timestepper) context. Valid only for nonlinear problems.
2732d763cef2SBarry Smith 
2733d763cef2SBarry Smith    Not Collective, but SNES is parallel if TS is parallel
2734d763cef2SBarry Smith 
2735d763cef2SBarry Smith    Input Parameter:
2736d763cef2SBarry Smith .  ts - the TS context obtained from TSCreate()
2737d763cef2SBarry Smith 
2738d763cef2SBarry Smith    Output Parameter:
2739d763cef2SBarry Smith .  snes - the nonlinear solver context
2740d763cef2SBarry Smith 
2741d763cef2SBarry Smith    Notes:
2742d763cef2SBarry Smith    The user can then directly manipulate the SNES context to set various
2743d763cef2SBarry Smith    options, etc.  Likewise, the user can then extract and manipulate the
274494b7f48cSBarry Smith    KSP, KSP, and PC contexts as well.
2745d763cef2SBarry Smith 
2746d763cef2SBarry Smith    TSGetSNES() does not work for integrators that do not use SNES; in
27470298fd71SBarry Smith    this case TSGetSNES() returns NULL in snes.
2748d763cef2SBarry Smith 
2749d763cef2SBarry Smith    Level: beginner
2750d763cef2SBarry Smith 
2751d763cef2SBarry Smith @*/
2752*d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetSNES(TS ts, SNES *snes)
2753*d71ae5a4SJacob Faibussowitsch {
2754d763cef2SBarry Smith   PetscFunctionBegin;
27550700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
27564482741eSBarry Smith   PetscValidPointer(snes, 2);
2757d372ba47SLisandro Dalcin   if (!ts->snes) {
27589566063dSJacob Faibussowitsch     PetscCall(SNESCreate(PetscObjectComm((PetscObject)ts), &ts->snes));
27599566063dSJacob Faibussowitsch     PetscCall(PetscObjectSetOptions((PetscObject)ts->snes, ((PetscObject)ts)->options));
27609566063dSJacob Faibussowitsch     PetscCall(SNESSetFunction(ts->snes, NULL, SNESTSFormFunction, ts));
27619566063dSJacob Faibussowitsch     PetscCall(PetscObjectIncrementTabLevel((PetscObject)ts->snes, (PetscObject)ts, 1));
27629566063dSJacob Faibussowitsch     if (ts->dm) PetscCall(SNESSetDM(ts->snes, ts->dm));
27631e66621cSBarry Smith     if (ts->problem_type == TS_LINEAR) PetscCall(SNESSetType(ts->snes, SNESKSPONLY));
2764d372ba47SLisandro Dalcin   }
2765d763cef2SBarry Smith   *snes = ts->snes;
2766d763cef2SBarry Smith   PetscFunctionReturn(0);
2767d763cef2SBarry Smith }
2768d763cef2SBarry Smith 
2769deb2cd25SJed Brown /*@
2770deb2cd25SJed Brown    TSSetSNES - Set the SNES (nonlinear solver) to be used by the timestepping context
2771deb2cd25SJed Brown 
2772deb2cd25SJed Brown    Collective
2773deb2cd25SJed Brown 
2774d8d19677SJose E. Roman    Input Parameters:
2775deb2cd25SJed Brown +  ts - the TS context obtained from TSCreate()
2776deb2cd25SJed Brown -  snes - the nonlinear solver context
2777deb2cd25SJed Brown 
2778deb2cd25SJed Brown    Notes:
2779deb2cd25SJed Brown    Most users should have the TS created by calling TSGetSNES()
2780deb2cd25SJed Brown 
2781deb2cd25SJed Brown    Level: developer
2782deb2cd25SJed Brown 
2783deb2cd25SJed Brown @*/
2784*d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetSNES(TS ts, SNES snes)
2785*d71ae5a4SJacob Faibussowitsch {
2786d1e9a80fSBarry Smith   PetscErrorCode (*func)(SNES, Vec, Mat, Mat, void *);
2787deb2cd25SJed Brown 
2788deb2cd25SJed Brown   PetscFunctionBegin;
2789deb2cd25SJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
2790deb2cd25SJed Brown   PetscValidHeaderSpecific(snes, SNES_CLASSID, 2);
27919566063dSJacob Faibussowitsch   PetscCall(PetscObjectReference((PetscObject)snes));
27929566063dSJacob Faibussowitsch   PetscCall(SNESDestroy(&ts->snes));
2793bbd56ea5SKarl Rupp 
2794deb2cd25SJed Brown   ts->snes = snes;
2795bbd56ea5SKarl Rupp 
27969566063dSJacob Faibussowitsch   PetscCall(SNESSetFunction(ts->snes, NULL, SNESTSFormFunction, ts));
27979566063dSJacob Faibussowitsch   PetscCall(SNESGetJacobian(ts->snes, NULL, NULL, &func, NULL));
27981e66621cSBarry Smith   if (func == SNESTSFormJacobian) PetscCall(SNESSetJacobian(ts->snes, NULL, NULL, SNESTSFormJacobian, ts));
2799deb2cd25SJed Brown   PetscFunctionReturn(0);
2800deb2cd25SJed Brown }
2801deb2cd25SJed Brown 
2802d8e5e3e6SSatish Balay /*@
280394b7f48cSBarry Smith    TSGetKSP - Returns the KSP (linear solver) associated with
2804d763cef2SBarry Smith    a TS (timestepper) context.
2805d763cef2SBarry Smith 
280694b7f48cSBarry Smith    Not Collective, but KSP is parallel if TS is parallel
2807d763cef2SBarry Smith 
2808d763cef2SBarry Smith    Input Parameter:
2809d763cef2SBarry Smith .  ts - the TS context obtained from TSCreate()
2810d763cef2SBarry Smith 
2811d763cef2SBarry Smith    Output Parameter:
281294b7f48cSBarry Smith .  ksp - the nonlinear solver context
2813d763cef2SBarry Smith 
2814d763cef2SBarry Smith    Notes:
281594b7f48cSBarry Smith    The user can then directly manipulate the KSP context to set various
2816d763cef2SBarry Smith    options, etc.  Likewise, the user can then extract and manipulate the
2817d763cef2SBarry Smith    KSP and PC contexts as well.
2818d763cef2SBarry Smith 
281994b7f48cSBarry Smith    TSGetKSP() does not work for integrators that do not use KSP;
28200298fd71SBarry Smith    in this case TSGetKSP() returns NULL in ksp.
2821d763cef2SBarry Smith 
2822d763cef2SBarry Smith    Level: beginner
2823d763cef2SBarry Smith 
2824d763cef2SBarry Smith @*/
2825*d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetKSP(TS ts, KSP *ksp)
2826*d71ae5a4SJacob Faibussowitsch {
2827089b2837SJed Brown   SNES snes;
2828d372ba47SLisandro Dalcin 
2829d763cef2SBarry Smith   PetscFunctionBegin;
28300700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
28314482741eSBarry Smith   PetscValidPointer(ksp, 2);
28323c633725SBarry Smith   PetscCheck(((PetscObject)ts)->type_name, PETSC_COMM_SELF, PETSC_ERR_ARG_NULL, "KSP is not created yet. Call TSSetType() first");
28333c633725SBarry Smith   PetscCheck(ts->problem_type == TS_LINEAR, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Linear only; use TSGetSNES()");
28349566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts, &snes));
28359566063dSJacob Faibussowitsch   PetscCall(SNESGetKSP(snes, ksp));
2836d763cef2SBarry Smith   PetscFunctionReturn(0);
2837d763cef2SBarry Smith }
2838d763cef2SBarry Smith 
2839d763cef2SBarry Smith /* ----------- Routines to set solver parameters ---------- */
2840d763cef2SBarry Smith 
2841adb62b0dSMatthew Knepley /*@
2842618ce8baSLisandro Dalcin    TSSetMaxSteps - Sets the maximum number of steps to use.
2843618ce8baSLisandro Dalcin 
2844618ce8baSLisandro Dalcin    Logically Collective on TS
2845618ce8baSLisandro Dalcin 
2846618ce8baSLisandro Dalcin    Input Parameters:
2847618ce8baSLisandro Dalcin +  ts - the TS context obtained from TSCreate()
2848618ce8baSLisandro Dalcin -  maxsteps - maximum number of steps to use
2849618ce8baSLisandro Dalcin 
2850618ce8baSLisandro Dalcin    Options Database Keys:
2851618ce8baSLisandro Dalcin .  -ts_max_steps <maxsteps> - Sets maxsteps
2852618ce8baSLisandro Dalcin 
2853618ce8baSLisandro Dalcin    Notes:
2854618ce8baSLisandro Dalcin    The default maximum number of steps is 5000
2855618ce8baSLisandro Dalcin 
2856618ce8baSLisandro Dalcin    Level: intermediate
2857618ce8baSLisandro Dalcin 
2858db781477SPatrick Sanan .seealso: `TSGetMaxSteps()`, `TSSetMaxTime()`, `TSSetExactFinalTime()`
2859618ce8baSLisandro Dalcin @*/
2860*d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetMaxSteps(TS ts, PetscInt maxsteps)
2861*d71ae5a4SJacob Faibussowitsch {
2862618ce8baSLisandro Dalcin   PetscFunctionBegin;
2863618ce8baSLisandro Dalcin   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
2864618ce8baSLisandro Dalcin   PetscValidLogicalCollectiveInt(ts, maxsteps, 2);
28653c633725SBarry Smith   PetscCheck(maxsteps >= 0, PetscObjectComm((PetscObject)ts), PETSC_ERR_ARG_OUTOFRANGE, "Maximum number of steps must be non-negative");
2866618ce8baSLisandro Dalcin   ts->max_steps = maxsteps;
2867618ce8baSLisandro Dalcin   PetscFunctionReturn(0);
2868618ce8baSLisandro Dalcin }
2869618ce8baSLisandro Dalcin 
2870618ce8baSLisandro Dalcin /*@
2871618ce8baSLisandro Dalcin    TSGetMaxSteps - Gets the maximum number of steps to use.
2872618ce8baSLisandro Dalcin 
2873618ce8baSLisandro Dalcin    Not Collective
2874618ce8baSLisandro Dalcin 
2875618ce8baSLisandro Dalcin    Input Parameters:
2876618ce8baSLisandro Dalcin .  ts - the TS context obtained from TSCreate()
2877618ce8baSLisandro Dalcin 
2878618ce8baSLisandro Dalcin    Output Parameter:
2879618ce8baSLisandro Dalcin .  maxsteps - maximum number of steps to use
2880618ce8baSLisandro Dalcin 
2881618ce8baSLisandro Dalcin    Level: advanced
2882618ce8baSLisandro Dalcin 
2883db781477SPatrick Sanan .seealso: `TSSetMaxSteps()`, `TSGetMaxTime()`, `TSSetMaxTime()`
2884618ce8baSLisandro Dalcin @*/
2885*d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetMaxSteps(TS ts, PetscInt *maxsteps)
2886*d71ae5a4SJacob Faibussowitsch {
2887618ce8baSLisandro Dalcin   PetscFunctionBegin;
2888618ce8baSLisandro Dalcin   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
2889618ce8baSLisandro Dalcin   PetscValidIntPointer(maxsteps, 2);
2890618ce8baSLisandro Dalcin   *maxsteps = ts->max_steps;
2891618ce8baSLisandro Dalcin   PetscFunctionReturn(0);
2892618ce8baSLisandro Dalcin }
2893618ce8baSLisandro Dalcin 
2894618ce8baSLisandro Dalcin /*@
2895618ce8baSLisandro Dalcin    TSSetMaxTime - Sets the maximum (or final) time for timestepping.
2896618ce8baSLisandro Dalcin 
2897618ce8baSLisandro Dalcin    Logically Collective on TS
2898618ce8baSLisandro Dalcin 
2899618ce8baSLisandro Dalcin    Input Parameters:
2900618ce8baSLisandro Dalcin +  ts - the TS context obtained from TSCreate()
2901618ce8baSLisandro Dalcin -  maxtime - final time to step to
2902618ce8baSLisandro Dalcin 
2903618ce8baSLisandro Dalcin    Options Database Keys:
2904ef85077eSLisandro Dalcin .  -ts_max_time <maxtime> - Sets maxtime
2905618ce8baSLisandro Dalcin 
2906618ce8baSLisandro Dalcin    Notes:
2907618ce8baSLisandro Dalcin    The default maximum time is 5.0
2908618ce8baSLisandro Dalcin 
2909618ce8baSLisandro Dalcin    Level: intermediate
2910618ce8baSLisandro Dalcin 
2911db781477SPatrick Sanan .seealso: `TSGetMaxTime()`, `TSSetMaxSteps()`, `TSSetExactFinalTime()`
2912618ce8baSLisandro Dalcin @*/
2913*d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetMaxTime(TS ts, PetscReal maxtime)
2914*d71ae5a4SJacob Faibussowitsch {
2915618ce8baSLisandro Dalcin   PetscFunctionBegin;
2916618ce8baSLisandro Dalcin   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
2917618ce8baSLisandro Dalcin   PetscValidLogicalCollectiveReal(ts, maxtime, 2);
2918618ce8baSLisandro Dalcin   ts->max_time = maxtime;
2919618ce8baSLisandro Dalcin   PetscFunctionReturn(0);
2920618ce8baSLisandro Dalcin }
2921618ce8baSLisandro Dalcin 
2922618ce8baSLisandro Dalcin /*@
2923618ce8baSLisandro Dalcin    TSGetMaxTime - Gets the maximum (or final) time for timestepping.
2924618ce8baSLisandro Dalcin 
2925618ce8baSLisandro Dalcin    Not Collective
2926618ce8baSLisandro Dalcin 
2927618ce8baSLisandro Dalcin    Input Parameters:
2928618ce8baSLisandro Dalcin .  ts - the TS context obtained from TSCreate()
2929618ce8baSLisandro Dalcin 
2930618ce8baSLisandro Dalcin    Output Parameter:
2931618ce8baSLisandro Dalcin .  maxtime - final time to step to
2932618ce8baSLisandro Dalcin 
2933618ce8baSLisandro Dalcin    Level: advanced
2934618ce8baSLisandro Dalcin 
2935db781477SPatrick Sanan .seealso: `TSSetMaxTime()`, `TSGetMaxSteps()`, `TSSetMaxSteps()`
2936618ce8baSLisandro Dalcin @*/
2937*d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetMaxTime(TS ts, PetscReal *maxtime)
2938*d71ae5a4SJacob Faibussowitsch {
2939618ce8baSLisandro Dalcin   PetscFunctionBegin;
2940618ce8baSLisandro Dalcin   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
2941618ce8baSLisandro Dalcin   PetscValidRealPointer(maxtime, 2);
2942618ce8baSLisandro Dalcin   *maxtime = ts->max_time;
2943618ce8baSLisandro Dalcin   PetscFunctionReturn(0);
2944618ce8baSLisandro Dalcin }
2945618ce8baSLisandro Dalcin 
2946618ce8baSLisandro Dalcin /*@
2947aaa6c58dSLisandro Dalcin    TSSetInitialTimeStep - Deprecated, use TSSetTime() and TSSetTimeStep().
2948edc382c3SSatish Balay 
2949edc382c3SSatish Balay    Level: deprecated
2950edc382c3SSatish Balay 
2951aaa6c58dSLisandro Dalcin @*/
2952*d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetInitialTimeStep(TS ts, PetscReal initial_time, PetscReal time_step)
2953*d71ae5a4SJacob Faibussowitsch {
2954aaa6c58dSLisandro Dalcin   PetscFunctionBegin;
2955aaa6c58dSLisandro Dalcin   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
29569566063dSJacob Faibussowitsch   PetscCall(TSSetTime(ts, initial_time));
29579566063dSJacob Faibussowitsch   PetscCall(TSSetTimeStep(ts, time_step));
2958aaa6c58dSLisandro Dalcin   PetscFunctionReturn(0);
2959aaa6c58dSLisandro Dalcin }
2960aaa6c58dSLisandro Dalcin 
2961aaa6c58dSLisandro Dalcin /*@
296219eac22cSLisandro Dalcin    TSGetDuration - Deprecated, use TSGetMaxSteps() and TSGetMaxTime().
2963edc382c3SSatish Balay 
2964edc382c3SSatish Balay    Level: deprecated
2965edc382c3SSatish Balay 
2966adb62b0dSMatthew Knepley @*/
2967*d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetDuration(TS ts, PetscInt *maxsteps, PetscReal *maxtime)
2968*d71ae5a4SJacob Faibussowitsch {
2969adb62b0dSMatthew Knepley   PetscFunctionBegin;
29700700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
2971abc0a331SBarry Smith   if (maxsteps) {
29724482741eSBarry Smith     PetscValidIntPointer(maxsteps, 2);
2973adb62b0dSMatthew Knepley     *maxsteps = ts->max_steps;
2974adb62b0dSMatthew Knepley   }
2975abc0a331SBarry Smith   if (maxtime) {
2976064a246eSJacob Faibussowitsch     PetscValidRealPointer(maxtime, 3);
2977adb62b0dSMatthew Knepley     *maxtime = ts->max_time;
2978adb62b0dSMatthew Knepley   }
2979adb62b0dSMatthew Knepley   PetscFunctionReturn(0);
2980adb62b0dSMatthew Knepley }
2981adb62b0dSMatthew Knepley 
2982d763cef2SBarry Smith /*@
298319eac22cSLisandro Dalcin    TSSetDuration - Deprecated, use TSSetMaxSteps() and TSSetMaxTime().
2984edc382c3SSatish Balay 
2985edc382c3SSatish Balay    Level: deprecated
2986edc382c3SSatish Balay 
2987d763cef2SBarry Smith @*/
2988*d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetDuration(TS ts, PetscInt maxsteps, PetscReal maxtime)
2989*d71ae5a4SJacob Faibussowitsch {
2990d763cef2SBarry Smith   PetscFunctionBegin;
29910700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
2992c5eb9154SBarry Smith   PetscValidLogicalCollectiveInt(ts, maxsteps, 2);
2993064a246eSJacob Faibussowitsch   PetscValidLogicalCollectiveReal(ts, maxtime, 3);
299439b7ec4bSSean Farley   if (maxsteps >= 0) ts->max_steps = maxsteps;
299539b7ec4bSSean Farley   if (maxtime != PETSC_DEFAULT) ts->max_time = maxtime;
2996d763cef2SBarry Smith   PetscFunctionReturn(0);
2997d763cef2SBarry Smith }
2998d763cef2SBarry Smith 
2999d763cef2SBarry Smith /*@
30005c5f5948SLisandro Dalcin    TSGetTimeStepNumber - Deprecated, use TSGetStepNumber().
3001edc382c3SSatish Balay 
3002edc382c3SSatish Balay    Level: deprecated
3003edc382c3SSatish Balay 
30045c5f5948SLisandro Dalcin @*/
3005*d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetTimeStepNumber(TS ts, PetscInt *steps)
3006*d71ae5a4SJacob Faibussowitsch {
30079371c9d4SSatish Balay   return TSGetStepNumber(ts, steps);
30089371c9d4SSatish Balay }
30095c5f5948SLisandro Dalcin 
301019eac22cSLisandro Dalcin /*@
30114f4e0956SLisandro Dalcin    TSGetTotalSteps - Deprecated, use TSGetStepNumber().
3012edc382c3SSatish Balay 
3013edc382c3SSatish Balay    Level: deprecated
3014edc382c3SSatish Balay 
30154f4e0956SLisandro Dalcin @*/
3016*d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetTotalSteps(TS ts, PetscInt *steps)
3017*d71ae5a4SJacob Faibussowitsch {
30189371c9d4SSatish Balay   return TSGetStepNumber(ts, steps);
30199371c9d4SSatish Balay }
30204f4e0956SLisandro Dalcin 
30214f4e0956SLisandro Dalcin /*@
3022d763cef2SBarry Smith    TSSetSolution - Sets the initial solution vector
3023d763cef2SBarry Smith    for use by the TS routines.
3024d763cef2SBarry Smith 
3025d083f849SBarry Smith    Logically Collective on TS
3026d763cef2SBarry Smith 
3027d763cef2SBarry Smith    Input Parameters:
3028d763cef2SBarry Smith +  ts - the TS context obtained from TSCreate()
30290910c330SBarry Smith -  u - the solution vector
3030d763cef2SBarry Smith 
3031d763cef2SBarry Smith    Level: beginner
3032d763cef2SBarry Smith 
3033db781477SPatrick Sanan .seealso: `TSSetSolutionFunction()`, `TSGetSolution()`, `TSCreate()`
3034d763cef2SBarry Smith @*/
3035*d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetSolution(TS ts, Vec u)
3036*d71ae5a4SJacob Faibussowitsch {
3037496e6a7aSJed Brown   DM dm;
30388737fe31SLisandro Dalcin 
3039d763cef2SBarry Smith   PetscFunctionBegin;
30400700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
30410910c330SBarry Smith   PetscValidHeaderSpecific(u, VEC_CLASSID, 2);
30429566063dSJacob Faibussowitsch   PetscCall(PetscObjectReference((PetscObject)u));
30439566063dSJacob Faibussowitsch   PetscCall(VecDestroy(&ts->vec_sol));
30440910c330SBarry Smith   ts->vec_sol = u;
3045bbd56ea5SKarl Rupp 
30469566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
30479566063dSJacob Faibussowitsch   PetscCall(DMShellSetGlobalVector(dm, u));
3048d763cef2SBarry Smith   PetscFunctionReturn(0);
3049d763cef2SBarry Smith }
3050d763cef2SBarry Smith 
3051ac226902SBarry Smith /*@C
3052000e7ae3SMatthew Knepley   TSSetPreStep - Sets the general-purpose function
30533f2090d5SJed Brown   called once at the beginning of each time step.
3054000e7ae3SMatthew Knepley 
30553f9fe445SBarry Smith   Logically Collective on TS
3056000e7ae3SMatthew Knepley 
3057000e7ae3SMatthew Knepley   Input Parameters:
3058000e7ae3SMatthew Knepley + ts   - The TS context obtained from TSCreate()
3059000e7ae3SMatthew Knepley - func - The function
3060000e7ae3SMatthew Knepley 
3061000e7ae3SMatthew Knepley   Calling sequence of func:
306267b8a455SSatish Balay .vb
306367b8a455SSatish Balay   PetscErrorCode func (TS ts);
306467b8a455SSatish Balay .ve
3065000e7ae3SMatthew Knepley 
3066000e7ae3SMatthew Knepley   Level: intermediate
3067000e7ae3SMatthew Knepley 
3068db781477SPatrick Sanan .seealso: `TSSetPreStage()`, `TSSetPostStage()`, `TSSetPostStep()`, `TSStep()`, `TSRestartStep()`
3069000e7ae3SMatthew Knepley @*/
3070*d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetPreStep(TS ts, PetscErrorCode (*func)(TS))
3071*d71ae5a4SJacob Faibussowitsch {
3072000e7ae3SMatthew Knepley   PetscFunctionBegin;
30730700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3074ae60f76fSBarry Smith   ts->prestep = func;
3075000e7ae3SMatthew Knepley   PetscFunctionReturn(0);
3076000e7ae3SMatthew Knepley }
3077000e7ae3SMatthew Knepley 
307809ee8438SJed Brown /*@
30793f2090d5SJed Brown   TSPreStep - Runs the user-defined pre-step function.
30803f2090d5SJed Brown 
30813f2090d5SJed Brown   Collective on TS
30823f2090d5SJed Brown 
30833f2090d5SJed Brown   Input Parameters:
30843f2090d5SJed Brown . ts   - The TS context obtained from TSCreate()
30853f2090d5SJed Brown 
30863f2090d5SJed Brown   Notes:
30873f2090d5SJed Brown   TSPreStep() is typically used within time stepping implementations,
30883f2090d5SJed Brown   so most users would not generally call this routine themselves.
30893f2090d5SJed Brown 
30903f2090d5SJed Brown   Level: developer
30913f2090d5SJed Brown 
3092db781477SPatrick Sanan .seealso: `TSSetPreStep()`, `TSPreStage()`, `TSPostStage()`, `TSPostStep()`
30933f2090d5SJed Brown @*/
3094*d71ae5a4SJacob Faibussowitsch PetscErrorCode TSPreStep(TS ts)
3095*d71ae5a4SJacob Faibussowitsch {
30963f2090d5SJed Brown   PetscFunctionBegin;
30970700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3098ae60f76fSBarry Smith   if (ts->prestep) {
30995efd42a4SStefano Zampini     Vec              U;
3100ef8d1ce0SJohann Rudi     PetscObjectId    idprev;
3101ef8d1ce0SJohann Rudi     PetscBool        sameObject;
31025efd42a4SStefano Zampini     PetscObjectState sprev, spost;
31035efd42a4SStefano Zampini 
31049566063dSJacob Faibussowitsch     PetscCall(TSGetSolution(ts, &U));
31059566063dSJacob Faibussowitsch     PetscCall(PetscObjectGetId((PetscObject)U, &idprev));
31069566063dSJacob Faibussowitsch     PetscCall(PetscObjectStateGet((PetscObject)U, &sprev));
310725e27a38SBarry Smith     PetscCallBack("TS callback preset", (*ts->prestep)(ts));
31089566063dSJacob Faibussowitsch     PetscCall(TSGetSolution(ts, &U));
31099566063dSJacob Faibussowitsch     PetscCall(PetscObjectCompareId((PetscObject)U, idprev, &sameObject));
31109566063dSJacob Faibussowitsch     PetscCall(PetscObjectStateGet((PetscObject)U, &spost));
31119566063dSJacob Faibussowitsch     if (!sameObject || sprev != spost) PetscCall(TSRestartStep(ts));
3112312ce896SJed Brown   }
31133f2090d5SJed Brown   PetscFunctionReturn(0);
31143f2090d5SJed Brown }
31153f2090d5SJed Brown 
3116b8123daeSJed Brown /*@C
3117b8123daeSJed Brown   TSSetPreStage - Sets the general-purpose function
3118b8123daeSJed Brown   called once at the beginning of each stage.
3119b8123daeSJed Brown 
3120b8123daeSJed Brown   Logically Collective on TS
3121b8123daeSJed Brown 
3122b8123daeSJed Brown   Input Parameters:
3123b8123daeSJed Brown + ts   - The TS context obtained from TSCreate()
3124b8123daeSJed Brown - func - The function
3125b8123daeSJed Brown 
3126b8123daeSJed Brown   Calling sequence of func:
312767b8a455SSatish Balay .vb
312867b8a455SSatish Balay   PetscErrorCode func(TS ts, PetscReal stagetime);
312967b8a455SSatish Balay .ve
3130b8123daeSJed Brown 
3131b8123daeSJed Brown   Level: intermediate
3132b8123daeSJed Brown 
3133b8123daeSJed Brown   Note:
3134b8123daeSJed Brown   There may be several stages per time step. If the solve for a given stage fails, the step may be rejected and retried.
313580275a0aSLisandro Dalcin   The time step number being computed can be queried using TSGetStepNumber() and the total size of the step being
3136b8123daeSJed Brown   attempted can be obtained using TSGetTimeStep(). The time at the start of the step is available via TSGetTime().
3137b8123daeSJed Brown 
3138db781477SPatrick Sanan .seealso: `TSSetPostStage()`, `TSSetPreStep()`, `TSSetPostStep()`, `TSGetApplicationContext()`
3139b8123daeSJed Brown @*/
3140*d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetPreStage(TS ts, PetscErrorCode (*func)(TS, PetscReal))
3141*d71ae5a4SJacob Faibussowitsch {
3142b8123daeSJed Brown   PetscFunctionBegin;
3143b8123daeSJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3144ae60f76fSBarry Smith   ts->prestage = func;
3145b8123daeSJed Brown   PetscFunctionReturn(0);
3146b8123daeSJed Brown }
3147b8123daeSJed Brown 
31489be3e283SDebojyoti Ghosh /*@C
31499be3e283SDebojyoti Ghosh   TSSetPostStage - Sets the general-purpose function
31509be3e283SDebojyoti Ghosh   called once at the end of each stage.
31519be3e283SDebojyoti Ghosh 
31529be3e283SDebojyoti Ghosh   Logically Collective on TS
31539be3e283SDebojyoti Ghosh 
31549be3e283SDebojyoti Ghosh   Input Parameters:
31559be3e283SDebojyoti Ghosh + ts   - The TS context obtained from TSCreate()
31569be3e283SDebojyoti Ghosh - func - The function
31579be3e283SDebojyoti Ghosh 
31589be3e283SDebojyoti Ghosh   Calling sequence of func:
315967b8a455SSatish Balay .vb
316067b8a455SSatish Balay   PetscErrorCode func(TS ts, PetscReal stagetime, PetscInt stageindex, Vec* Y);
316167b8a455SSatish Balay .ve
31629be3e283SDebojyoti Ghosh 
31639be3e283SDebojyoti Ghosh   Level: intermediate
31649be3e283SDebojyoti Ghosh 
31659be3e283SDebojyoti Ghosh   Note:
31669be3e283SDebojyoti Ghosh   There may be several stages per time step. If the solve for a given stage fails, the step may be rejected and retried.
316780275a0aSLisandro Dalcin   The time step number being computed can be queried using TSGetStepNumber() and the total size of the step being
31689be3e283SDebojyoti Ghosh   attempted can be obtained using TSGetTimeStep(). The time at the start of the step is available via TSGetTime().
31699be3e283SDebojyoti Ghosh 
3170db781477SPatrick Sanan .seealso: `TSSetPreStage()`, `TSSetPreStep()`, `TSSetPostStep()`, `TSGetApplicationContext()`
31719be3e283SDebojyoti Ghosh @*/
3172*d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetPostStage(TS ts, PetscErrorCode (*func)(TS, PetscReal, PetscInt, Vec *))
3173*d71ae5a4SJacob Faibussowitsch {
31749be3e283SDebojyoti Ghosh   PetscFunctionBegin;
31759be3e283SDebojyoti Ghosh   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
31769be3e283SDebojyoti Ghosh   ts->poststage = func;
31779be3e283SDebojyoti Ghosh   PetscFunctionReturn(0);
31789be3e283SDebojyoti Ghosh }
31799be3e283SDebojyoti Ghosh 
3180c688d042SShri Abhyankar /*@C
3181c688d042SShri Abhyankar   TSSetPostEvaluate - Sets the general-purpose function
3182c688d042SShri Abhyankar   called once at the end of each step evaluation.
3183c688d042SShri Abhyankar 
3184c688d042SShri Abhyankar   Logically Collective on TS
3185c688d042SShri Abhyankar 
3186c688d042SShri Abhyankar   Input Parameters:
3187c688d042SShri Abhyankar + ts   - The TS context obtained from TSCreate()
3188c688d042SShri Abhyankar - func - The function
3189c688d042SShri Abhyankar 
3190c688d042SShri Abhyankar   Calling sequence of func:
319167b8a455SSatish Balay .vb
319267b8a455SSatish Balay   PetscErrorCode func(TS ts);
319367b8a455SSatish Balay .ve
3194c688d042SShri Abhyankar 
3195c688d042SShri Abhyankar   Level: intermediate
3196c688d042SShri Abhyankar 
3197c688d042SShri Abhyankar   Note:
31981785ff2aSShri Abhyankar   Semantically, TSSetPostEvaluate() differs from TSSetPostStep() since the function it sets is called before event-handling
31991785ff2aSShri Abhyankar   thus guaranteeing the same solution (computed by the time-stepper) will be passed to it. On the other hand, TSPostStep()
3200e7e94ed4SShri Abhyankar   may be passed a different solution, possibly changed by the event handler. TSPostEvaluate() is called after the next step
3201e7e94ed4SShri Abhyankar   solution is evaluated allowing to modify it, if need be. The solution can be obtained with TSGetSolution(), the time step
3202e7e94ed4SShri Abhyankar   with TSGetTimeStep(), and the time at the start of the step is available via TSGetTime()
3203c688d042SShri Abhyankar 
3204db781477SPatrick Sanan .seealso: `TSSetPreStage()`, `TSSetPreStep()`, `TSSetPostStep()`, `TSGetApplicationContext()`
3205c688d042SShri Abhyankar @*/
3206*d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetPostEvaluate(TS ts, PetscErrorCode (*func)(TS))
3207*d71ae5a4SJacob Faibussowitsch {
3208c688d042SShri Abhyankar   PetscFunctionBegin;
3209c688d042SShri Abhyankar   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3210c688d042SShri Abhyankar   ts->postevaluate = func;
3211c688d042SShri Abhyankar   PetscFunctionReturn(0);
3212c688d042SShri Abhyankar }
3213c688d042SShri Abhyankar 
3214b8123daeSJed Brown /*@
3215b8123daeSJed Brown   TSPreStage - Runs the user-defined pre-stage function set using TSSetPreStage()
3216b8123daeSJed Brown 
3217b8123daeSJed Brown   Collective on TS
3218b8123daeSJed Brown 
3219b8123daeSJed Brown   Input Parameters:
3220b8123daeSJed Brown . ts          - The TS context obtained from TSCreate()
32219be3e283SDebojyoti Ghosh   stagetime   - The absolute time of the current stage
3222b8123daeSJed Brown 
3223b8123daeSJed Brown   Notes:
3224b8123daeSJed Brown   TSPreStage() is typically used within time stepping implementations,
3225b8123daeSJed Brown   most users would not generally call this routine themselves.
3226b8123daeSJed Brown 
3227b8123daeSJed Brown   Level: developer
3228b8123daeSJed Brown 
3229db781477SPatrick Sanan .seealso: `TSPostStage()`, `TSSetPreStep()`, `TSPreStep()`, `TSPostStep()`
3230b8123daeSJed Brown @*/
3231*d71ae5a4SJacob Faibussowitsch PetscErrorCode TSPreStage(TS ts, PetscReal stagetime)
3232*d71ae5a4SJacob Faibussowitsch {
3233b8123daeSJed Brown   PetscFunctionBegin;
3234b8123daeSJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
32351e66621cSBarry Smith   if (ts->prestage) PetscCallBack("TS callback prestage", (*ts->prestage)(ts, stagetime));
3236b8123daeSJed Brown   PetscFunctionReturn(0);
3237b8123daeSJed Brown }
3238b8123daeSJed Brown 
32399be3e283SDebojyoti Ghosh /*@
32409be3e283SDebojyoti Ghosh   TSPostStage - Runs the user-defined post-stage function set using TSSetPostStage()
32419be3e283SDebojyoti Ghosh 
32429be3e283SDebojyoti Ghosh   Collective on TS
32439be3e283SDebojyoti Ghosh 
32449be3e283SDebojyoti Ghosh   Input Parameters:
32459be3e283SDebojyoti Ghosh . ts          - The TS context obtained from TSCreate()
32469be3e283SDebojyoti Ghosh   stagetime   - The absolute time of the current stage
32479be3e283SDebojyoti Ghosh   stageindex  - Stage number
32489be3e283SDebojyoti Ghosh   Y           - Array of vectors (of size = total number
32499be3e283SDebojyoti Ghosh                 of stages) with the stage solutions
32509be3e283SDebojyoti Ghosh 
32519be3e283SDebojyoti Ghosh   Notes:
32529be3e283SDebojyoti Ghosh   TSPostStage() is typically used within time stepping implementations,
32539be3e283SDebojyoti Ghosh   most users would not generally call this routine themselves.
32549be3e283SDebojyoti Ghosh 
32559be3e283SDebojyoti Ghosh   Level: developer
32569be3e283SDebojyoti Ghosh 
3257db781477SPatrick Sanan .seealso: `TSPreStage()`, `TSSetPreStep()`, `TSPreStep()`, `TSPostStep()`
32589be3e283SDebojyoti Ghosh @*/
3259*d71ae5a4SJacob Faibussowitsch PetscErrorCode TSPostStage(TS ts, PetscReal stagetime, PetscInt stageindex, Vec *Y)
3260*d71ae5a4SJacob Faibussowitsch {
32619be3e283SDebojyoti Ghosh   PetscFunctionBegin;
32629be3e283SDebojyoti Ghosh   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
32631e66621cSBarry Smith   if (ts->poststage) PetscCallBack("TS callback poststage", (*ts->poststage)(ts, stagetime, stageindex, Y));
32649be3e283SDebojyoti Ghosh   PetscFunctionReturn(0);
32659be3e283SDebojyoti Ghosh }
32669be3e283SDebojyoti Ghosh 
3267c688d042SShri Abhyankar /*@
3268c688d042SShri Abhyankar   TSPostEvaluate - Runs the user-defined post-evaluate function set using TSSetPostEvaluate()
3269c688d042SShri Abhyankar 
3270c688d042SShri Abhyankar   Collective on TS
3271c688d042SShri Abhyankar 
3272c688d042SShri Abhyankar   Input Parameters:
3273c688d042SShri Abhyankar . ts          - The TS context obtained from TSCreate()
3274c688d042SShri Abhyankar 
3275c688d042SShri Abhyankar   Notes:
3276c688d042SShri Abhyankar   TSPostEvaluate() is typically used within time stepping implementations,
3277c688d042SShri Abhyankar   most users would not generally call this routine themselves.
3278c688d042SShri Abhyankar 
3279c688d042SShri Abhyankar   Level: developer
3280c688d042SShri Abhyankar 
3281db781477SPatrick Sanan .seealso: `TSSetPostEvaluate()`, `TSSetPreStep()`, `TSPreStep()`, `TSPostStep()`
3282c688d042SShri Abhyankar @*/
3283*d71ae5a4SJacob Faibussowitsch PetscErrorCode TSPostEvaluate(TS ts)
3284*d71ae5a4SJacob Faibussowitsch {
3285c688d042SShri Abhyankar   PetscFunctionBegin;
3286c688d042SShri Abhyankar   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3287c688d042SShri Abhyankar   if (ts->postevaluate) {
3288dcb233daSLisandro Dalcin     Vec              U;
3289dcb233daSLisandro Dalcin     PetscObjectState sprev, spost;
3290dcb233daSLisandro Dalcin 
32919566063dSJacob Faibussowitsch     PetscCall(TSGetSolution(ts, &U));
32929566063dSJacob Faibussowitsch     PetscCall(PetscObjectStateGet((PetscObject)U, &sprev));
329325e27a38SBarry Smith     PetscCallBack("TS callback postevaluate", (*ts->postevaluate)(ts));
32949566063dSJacob Faibussowitsch     PetscCall(PetscObjectStateGet((PetscObject)U, &spost));
32959566063dSJacob Faibussowitsch     if (sprev != spost) PetscCall(TSRestartStep(ts));
3296c688d042SShri Abhyankar   }
3297c688d042SShri Abhyankar   PetscFunctionReturn(0);
3298c688d042SShri Abhyankar }
3299c688d042SShri Abhyankar 
3300ac226902SBarry Smith /*@C
3301000e7ae3SMatthew Knepley   TSSetPostStep - Sets the general-purpose function
33023f2090d5SJed Brown   called once at the end of each time step.
3303000e7ae3SMatthew Knepley 
33043f9fe445SBarry Smith   Logically Collective on TS
3305000e7ae3SMatthew Knepley 
3306000e7ae3SMatthew Knepley   Input Parameters:
3307000e7ae3SMatthew Knepley + ts   - The TS context obtained from TSCreate()
3308000e7ae3SMatthew Knepley - func - The function
3309000e7ae3SMatthew Knepley 
3310000e7ae3SMatthew Knepley   Calling sequence of func:
3311b8123daeSJed Brown $ func (TS ts);
3312000e7ae3SMatthew Knepley 
33131785ff2aSShri Abhyankar   Notes:
33141785ff2aSShri Abhyankar   The function set by TSSetPostStep() is called after each successful step. The solution vector X
33151785ff2aSShri Abhyankar   obtained by TSGetSolution() may be different than that computed at the step end if the event handler
33161785ff2aSShri Abhyankar   locates an event and TSPostEvent() modifies it. Use TSSetPostEvaluate() if an unmodified solution is needed instead.
33171785ff2aSShri Abhyankar 
3318000e7ae3SMatthew Knepley   Level: intermediate
3319000e7ae3SMatthew Knepley 
3320db781477SPatrick Sanan .seealso: `TSSetPreStep()`, `TSSetPreStage()`, `TSSetPostEvaluate()`, `TSGetTimeStep()`, `TSGetStepNumber()`, `TSGetTime()`, `TSRestartStep()`
3321000e7ae3SMatthew Knepley @*/
3322*d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetPostStep(TS ts, PetscErrorCode (*func)(TS))
3323*d71ae5a4SJacob Faibussowitsch {
3324000e7ae3SMatthew Knepley   PetscFunctionBegin;
33250700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3326ae60f76fSBarry Smith   ts->poststep = func;
3327000e7ae3SMatthew Knepley   PetscFunctionReturn(0);
3328000e7ae3SMatthew Knepley }
3329000e7ae3SMatthew Knepley 
333009ee8438SJed Brown /*@
33313f2090d5SJed Brown   TSPostStep - Runs the user-defined post-step function.
33323f2090d5SJed Brown 
33333f2090d5SJed Brown   Collective on TS
33343f2090d5SJed Brown 
33353f2090d5SJed Brown   Input Parameters:
33363f2090d5SJed Brown . ts   - The TS context obtained from TSCreate()
33373f2090d5SJed Brown 
33383f2090d5SJed Brown   Notes:
33393f2090d5SJed Brown   TSPostStep() is typically used within time stepping implementations,
33403f2090d5SJed Brown   so most users would not generally call this routine themselves.
33413f2090d5SJed Brown 
33423f2090d5SJed Brown   Level: developer
33433f2090d5SJed Brown 
33443f2090d5SJed Brown @*/
3345*d71ae5a4SJacob Faibussowitsch PetscErrorCode TSPostStep(TS ts)
3346*d71ae5a4SJacob Faibussowitsch {
33473f2090d5SJed Brown   PetscFunctionBegin;
33480700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3349ae60f76fSBarry Smith   if (ts->poststep) {
33505efd42a4SStefano Zampini     Vec              U;
3351ef8d1ce0SJohann Rudi     PetscObjectId    idprev;
3352ef8d1ce0SJohann Rudi     PetscBool        sameObject;
33535efd42a4SStefano Zampini     PetscObjectState sprev, spost;
33545efd42a4SStefano Zampini 
33559566063dSJacob Faibussowitsch     PetscCall(TSGetSolution(ts, &U));
33569566063dSJacob Faibussowitsch     PetscCall(PetscObjectGetId((PetscObject)U, &idprev));
33579566063dSJacob Faibussowitsch     PetscCall(PetscObjectStateGet((PetscObject)U, &sprev));
335825e27a38SBarry Smith     PetscCallBack("TS callback poststep", (*ts->poststep)(ts));
33599566063dSJacob Faibussowitsch     PetscCall(TSGetSolution(ts, &U));
33609566063dSJacob Faibussowitsch     PetscCall(PetscObjectCompareId((PetscObject)U, idprev, &sameObject));
33619566063dSJacob Faibussowitsch     PetscCall(PetscObjectStateGet((PetscObject)U, &spost));
33629566063dSJacob Faibussowitsch     if (!sameObject || sprev != spost) PetscCall(TSRestartStep(ts));
336372ac3e02SJed Brown   }
33643f2090d5SJed Brown   PetscFunctionReturn(0);
33653f2090d5SJed Brown }
33663f2090d5SJed Brown 
3367cd652676SJed Brown /*@
3368cd652676SJed Brown    TSInterpolate - Interpolate the solution computed during the previous step to an arbitrary location in the interval
3369cd652676SJed Brown 
3370cd652676SJed Brown    Collective on TS
3371cd652676SJed Brown 
33724165533cSJose E. Roman    Input Parameters:
3373cd652676SJed Brown +  ts - time stepping context
3374cd652676SJed Brown -  t - time to interpolate to
3375cd652676SJed Brown 
33764165533cSJose E. Roman    Output Parameter:
33770910c330SBarry Smith .  U - state at given time
3378cd652676SJed Brown 
3379cd652676SJed Brown    Level: intermediate
3380cd652676SJed Brown 
3381cd652676SJed Brown    Developer Notes:
3382cd652676SJed Brown    TSInterpolate() and the storing of previous steps/stages should be generalized to support delay differential equations and continuous adjoints.
3383cd652676SJed Brown 
3384db781477SPatrick Sanan .seealso: `TSSetExactFinalTime()`, `TSSolve()`
3385cd652676SJed Brown @*/
3386*d71ae5a4SJacob Faibussowitsch PetscErrorCode TSInterpolate(TS ts, PetscReal t, Vec U)
3387*d71ae5a4SJacob Faibussowitsch {
3388cd652676SJed Brown   PetscFunctionBegin;
3389cd652676SJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3390b06615a5SLisandro Dalcin   PetscValidHeaderSpecific(U, VEC_CLASSID, 3);
339163a3b9bcSJacob 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);
3392dbbe0bcdSBarry Smith   PetscUseTypeMethod(ts, interpolate, t, U);
3393cd652676SJed Brown   PetscFunctionReturn(0);
3394cd652676SJed Brown }
3395cd652676SJed Brown 
3396d763cef2SBarry Smith /*@
33976d9e5789SSean Farley    TSStep - Steps one time step
3398d763cef2SBarry Smith 
3399d763cef2SBarry Smith    Collective on TS
3400d763cef2SBarry Smith 
3401d763cef2SBarry Smith    Input Parameter:
3402d763cef2SBarry Smith .  ts - the TS context obtained from TSCreate()
3403d763cef2SBarry Smith 
340427829d71SBarry Smith    Level: developer
3405d763cef2SBarry Smith 
3406b8123daeSJed Brown    Notes:
340727829d71SBarry Smith    The public interface for the ODE/DAE solvers is TSSolve(), you should almost for sure be using that routine and not this routine.
340827829d71SBarry Smith 
3409b8123daeSJed Brown    The hook set using TSSetPreStep() is called before each attempt to take the step. In general, the time step size may
3410b8123daeSJed Brown    be changed due to adaptive error controller or solve failures. Note that steps may contain multiple stages.
3411b8123daeSJed Brown 
341219eac22cSLisandro Dalcin    This may over-step the final time provided in TSSetMaxTime() depending on the time-step used. TSSolve() interpolates to exactly the
341319eac22cSLisandro Dalcin    time provided in TSSetMaxTime(). One can use TSInterpolate() to determine an interpolated solution within the final timestep.
341425cb2221SBarry Smith 
3415db781477SPatrick Sanan .seealso: `TSCreate()`, `TSSetUp()`, `TSDestroy()`, `TSSolve()`, `TSSetPreStep()`, `TSSetPreStage()`, `TSSetPostStage()`, `TSInterpolate()`
3416d763cef2SBarry Smith @*/
3417*d71ae5a4SJacob Faibussowitsch PetscErrorCode TSStep(TS ts)
3418*d71ae5a4SJacob Faibussowitsch {
3419fffbeea8SBarry Smith   static PetscBool cite = PETSC_FALSE;
3420be5899b3SLisandro Dalcin   PetscReal        ptime;
3421d763cef2SBarry Smith 
3422d763cef2SBarry Smith   PetscFunctionBegin;
34230700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3424d0609cedSBarry Smith   PetscCall(PetscCitationsRegister("@article{tspaper,\n"
3425fffbeea8SBarry Smith                                    "  title         = {{PETSc/TS}: A Modern Scalable {DAE/ODE} Solver Library},\n"
3426f1d62c27SHong Zhang                                    "  author        = {Abhyankar, Shrirang and Brown, Jed and Constantinescu, Emil and Ghosh, Debojyoti and Smith, Barry F. and Zhang, Hong},\n"
3427f1d62c27SHong Zhang                                    "  journal       = {arXiv e-preprints},\n"
3428f1d62c27SHong Zhang                                    "  eprint        = {1806.01437},\n"
3429f1d62c27SHong Zhang                                    "  archivePrefix = {arXiv},\n"
34309371c9d4SSatish Balay                                    "  year          = {2018}\n}\n",
34319371c9d4SSatish Balay                                    &cite));
34329566063dSJacob Faibussowitsch   PetscCall(TSSetUp(ts));
34339566063dSJacob Faibussowitsch   PetscCall(TSTrajectorySetUp(ts->trajectory, ts));
3434d405a339SMatthew Knepley 
34353c633725SBarry Smith   PetscCheck(ts->max_time < PETSC_MAX_REAL || ts->max_steps != PETSC_MAX_INT, PetscObjectComm((PetscObject)ts), PETSC_ERR_ARG_WRONGSTATE, "You must call TSSetMaxTime() or TSSetMaxSteps(), or use -ts_max_time <time> or -ts_max_steps <steps>");
34363c633725SBarry 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()");
34373c633725SBarry 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");
3438a6772fa2SLisandro Dalcin 
3439be5899b3SLisandro Dalcin   if (!ts->steps) ts->ptime_prev = ts->ptime;
34409371c9d4SSatish Balay   ptime                   = ts->ptime;
34419371c9d4SSatish Balay   ts->ptime_prev_rollback = ts->ptime_prev;
34422808aa04SLisandro Dalcin   ts->reason              = TS_CONVERGED_ITERATING;
3443fc8dbba5SLisandro Dalcin 
34449566063dSJacob Faibussowitsch   PetscCall(PetscLogEventBegin(TS_Step, ts, 0, 0, 0));
3445dbbe0bcdSBarry Smith   PetscUseTypeMethod(ts, step);
34469566063dSJacob Faibussowitsch   PetscCall(PetscLogEventEnd(TS_Step, ts, 0, 0, 0));
3447fc8dbba5SLisandro Dalcin 
34489371c9d4SSatish Balay   if (ts->tspan && PetscIsCloseAtTol(ts->ptime, ts->tspan->span_times[ts->tspan->spanctr], ts->tspan->reltol * ts->time_step + ts->tspan->abstol, 0) && ts->tspan->spanctr < ts->tspan->num_span_times)
34499371c9d4SSatish Balay     PetscCall(VecCopy(ts->vec_sol, ts->tspan->vecs_sol[ts->tspan->spanctr++]));
3450fc8dbba5SLisandro Dalcin   if (ts->reason >= 0) {
3451be5899b3SLisandro Dalcin     ts->ptime_prev = ptime;
34522808aa04SLisandro Dalcin     ts->steps++;
3453be5899b3SLisandro Dalcin     ts->steprollback = PETSC_FALSE;
345428d5b5d6SLisandro Dalcin     ts->steprestart  = PETSC_FALSE;
3455d2daff3dSHong Zhang   }
3456fc8dbba5SLisandro Dalcin   if (!ts->reason) {
345708c7845fSBarry Smith     if (ts->steps >= ts->max_steps) ts->reason = TS_CONVERGED_ITS;
345808c7845fSBarry Smith     else if (ts->ptime >= ts->max_time) ts->reason = TS_CONVERGED_TIME;
345908c7845fSBarry Smith   }
3460fc8dbba5SLisandro Dalcin 
34613c633725SBarry Smith   PetscCheck(ts->reason >= 0 || !ts->errorifstepfailed || ts->reason != TS_DIVERGED_NONLINEAR_SOLVE, PetscObjectComm((PetscObject)ts), PETSC_ERR_NOT_CONVERGED, "TSStep has failed due to %s, increase -ts_max_snes_failures or make negative to attempt recovery", TSConvergedReasons[ts->reason]);
34623c633725SBarry Smith   PetscCheck(ts->reason >= 0 || !ts->errorifstepfailed, PetscObjectComm((PetscObject)ts), PETSC_ERR_NOT_CONVERGED, "TSStep has failed due to %s", TSConvergedReasons[ts->reason]);
346308c7845fSBarry Smith   PetscFunctionReturn(0);
346408c7845fSBarry Smith }
346508c7845fSBarry Smith 
346608c7845fSBarry Smith /*@
34677cbde773SLisandro Dalcin    TSEvaluateWLTE - Evaluate the weighted local truncation error norm
34687cbde773SLisandro Dalcin    at the end of a time step with a given order of accuracy.
34697cbde773SLisandro Dalcin 
34707cbde773SLisandro Dalcin    Collective on TS
34717cbde773SLisandro Dalcin 
34724165533cSJose E. Roman    Input Parameters:
34737cbde773SLisandro Dalcin +  ts - time stepping context
347497bb3fdcSJose E. Roman -  wnormtype - norm type, either NORM_2 or NORM_INFINITY
34757cbde773SLisandro Dalcin 
347697bb3fdcSJose E. Roman    Input/Output Parameter:
347797bb3fdcSJose E. Roman .  order - optional, desired order for the error evaluation or PETSC_DECIDE;
347897bb3fdcSJose E. Roman            on output, the actual order of the error evaluation
347997bb3fdcSJose E. Roman 
348097bb3fdcSJose E. Roman    Output Parameter:
348197bb3fdcSJose E. Roman .  wlte - the weighted local truncation error norm
34827cbde773SLisandro Dalcin 
34837cbde773SLisandro Dalcin    Level: advanced
34847cbde773SLisandro Dalcin 
34857cbde773SLisandro Dalcin    Notes:
34867cbde773SLisandro Dalcin    If the timestepper cannot evaluate the error in a particular step
34877cbde773SLisandro Dalcin    (eg. in the first step or restart steps after event handling),
34887cbde773SLisandro Dalcin    this routine returns wlte=-1.0 .
34897cbde773SLisandro Dalcin 
3490db781477SPatrick Sanan .seealso: `TSStep()`, `TSAdapt`, `TSErrorWeightedNorm()`
34917cbde773SLisandro Dalcin @*/
3492*d71ae5a4SJacob Faibussowitsch PetscErrorCode TSEvaluateWLTE(TS ts, NormType wnormtype, PetscInt *order, PetscReal *wlte)
3493*d71ae5a4SJacob Faibussowitsch {
34947cbde773SLisandro Dalcin   PetscFunctionBegin;
34957cbde773SLisandro Dalcin   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
34967cbde773SLisandro Dalcin   PetscValidType(ts, 1);
3497064a246eSJacob Faibussowitsch   PetscValidLogicalCollectiveEnum(ts, wnormtype, 2);
34987cbde773SLisandro Dalcin   if (order) PetscValidIntPointer(order, 3);
34997cbde773SLisandro Dalcin   if (order) PetscValidLogicalCollectiveInt(ts, *order, 3);
35007cbde773SLisandro Dalcin   PetscValidRealPointer(wlte, 4);
35013c633725SBarry Smith   PetscCheck(wnormtype == NORM_2 || wnormtype == NORM_INFINITY, PetscObjectComm((PetscObject)ts), PETSC_ERR_SUP, "No support for norm type %s", NormTypes[wnormtype]);
3502dbbe0bcdSBarry Smith   PetscUseTypeMethod(ts, evaluatewlte, wnormtype, order, wlte);
35037cbde773SLisandro Dalcin   PetscFunctionReturn(0);
35047cbde773SLisandro Dalcin }
35057cbde773SLisandro Dalcin 
350605175c85SJed Brown /*@
350705175c85SJed Brown    TSEvaluateStep - Evaluate the solution at the end of a time step with a given order of accuracy.
350805175c85SJed Brown 
35091c3436cfSJed Brown    Collective on TS
351005175c85SJed Brown 
35114165533cSJose E. Roman    Input Parameters:
35121c3436cfSJed Brown +  ts - time stepping context
35131c3436cfSJed Brown .  order - desired order of accuracy
35140298fd71SBarry Smith -  done - whether the step was evaluated at this order (pass NULL to generate an error if not available)
351505175c85SJed Brown 
35164165533cSJose E. Roman    Output Parameter:
35170910c330SBarry Smith .  U - state at the end of the current step
351805175c85SJed Brown 
351905175c85SJed Brown    Level: advanced
352005175c85SJed Brown 
3521108c343cSJed Brown    Notes:
3522108c343cSJed Brown    This function cannot be called until all stages have been evaluated.
3523108c343cSJed Brown    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.
3524108c343cSJed Brown 
3525db781477SPatrick Sanan .seealso: `TSStep()`, `TSAdapt`
352605175c85SJed Brown @*/
3527*d71ae5a4SJacob Faibussowitsch PetscErrorCode TSEvaluateStep(TS ts, PetscInt order, Vec U, PetscBool *done)
3528*d71ae5a4SJacob Faibussowitsch {
352905175c85SJed Brown   PetscFunctionBegin;
353005175c85SJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
353105175c85SJed Brown   PetscValidType(ts, 1);
35320910c330SBarry Smith   PetscValidHeaderSpecific(U, VEC_CLASSID, 3);
3533dbbe0bcdSBarry Smith   PetscUseTypeMethod(ts, evaluatestep, order, U, done);
353405175c85SJed Brown   PetscFunctionReturn(0);
353505175c85SJed Brown }
353605175c85SJed Brown 
3537aad739acSMatthew G. Knepley /*@C
35382e61be88SMatthew G. Knepley   TSGetComputeInitialCondition - Get the function used to automatically compute an initial condition for the timestepping.
3539aad739acSMatthew G. Knepley 
3540aad739acSMatthew G. Knepley   Not collective
3541aad739acSMatthew G. Knepley 
35424165533cSJose E. Roman   Input Parameter:
3543aad739acSMatthew G. Knepley . ts        - time stepping context
3544aad739acSMatthew G. Knepley 
35454165533cSJose E. Roman   Output Parameter:
35462e61be88SMatthew G. Knepley . initConditions - The function which computes an initial condition
3547aad739acSMatthew G. Knepley 
3548aad739acSMatthew G. Knepley    Level: advanced
3549aad739acSMatthew G. Knepley 
3550aad739acSMatthew G. Knepley    Notes:
3551aad739acSMatthew G. Knepley    The calling sequence for the function is
35522e61be88SMatthew G. Knepley $ initCondition(TS ts, Vec u)
3553aad739acSMatthew G. Knepley $ ts - The timestepping context
35542e61be88SMatthew G. Knepley $ u  - The input vector in which the initial condition is stored
3555aad739acSMatthew G. Knepley 
3556db781477SPatrick Sanan .seealso: `TSSetComputeInitialCondition()`, `TSComputeInitialCondition()`
3557aad739acSMatthew G. Knepley @*/
3558*d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetComputeInitialCondition(TS ts, PetscErrorCode (**initCondition)(TS, Vec))
3559*d71ae5a4SJacob Faibussowitsch {
3560aad739acSMatthew G. Knepley   PetscFunctionBegin;
3561aad739acSMatthew G. Knepley   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
35622e61be88SMatthew G. Knepley   PetscValidPointer(initCondition, 2);
35632e61be88SMatthew G. Knepley   *initCondition = ts->ops->initcondition;
3564aad739acSMatthew G. Knepley   PetscFunctionReturn(0);
3565aad739acSMatthew G. Knepley }
3566aad739acSMatthew G. Knepley 
3567aad739acSMatthew G. Knepley /*@C
35682e61be88SMatthew G. Knepley   TSSetComputeInitialCondition - Set the function used to automatically compute an initial condition for the timestepping.
3569aad739acSMatthew G. Knepley 
3570aad739acSMatthew G. Knepley   Logically collective on ts
3571aad739acSMatthew G. Knepley 
35724165533cSJose E. Roman   Input Parameters:
3573aad739acSMatthew G. Knepley + ts        - time stepping context
35742e61be88SMatthew G. Knepley - initCondition - The function which computes an initial condition
3575aad739acSMatthew G. Knepley 
3576aad739acSMatthew G. Knepley   Level: advanced
3577aad739acSMatthew G. Knepley 
3578a96d6ef6SBarry Smith   Calling sequence for initCondition:
3579a96d6ef6SBarry Smith $ PetscErrorCode initCondition(TS ts, Vec u)
3580a96d6ef6SBarry Smith 
3581a96d6ef6SBarry Smith + ts - The timestepping context
3582a96d6ef6SBarry Smith - u  - The input vector in which the initial condition is to be stored
3583aad739acSMatthew G. Knepley 
3584db781477SPatrick Sanan .seealso: `TSGetComputeInitialCondition()`, `TSComputeInitialCondition()`
3585aad739acSMatthew G. Knepley @*/
3586*d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetComputeInitialCondition(TS ts, PetscErrorCode (*initCondition)(TS, Vec))
3587*d71ae5a4SJacob Faibussowitsch {
3588aad739acSMatthew G. Knepley   PetscFunctionBegin;
3589aad739acSMatthew G. Knepley   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
35902e61be88SMatthew G. Knepley   PetscValidFunction(initCondition, 2);
35912e61be88SMatthew G. Knepley   ts->ops->initcondition = initCondition;
3592aad739acSMatthew G. Knepley   PetscFunctionReturn(0);
3593aad739acSMatthew G. Knepley }
3594aad739acSMatthew G. Knepley 
3595aad739acSMatthew G. Knepley /*@
35962e61be88SMatthew G. Knepley   TSComputeInitialCondition - Compute an initial condition for the timestepping using the function previously set.
3597aad739acSMatthew G. Knepley 
3598aad739acSMatthew G. Knepley   Collective on ts
3599aad739acSMatthew G. Knepley 
36004165533cSJose E. Roman   Input Parameters:
3601aad739acSMatthew G. Knepley + ts - time stepping context
36022e61be88SMatthew G. Knepley - u  - The Vec to store the condition in which will be used in TSSolve()
3603aad739acSMatthew G. Knepley 
3604aad739acSMatthew G. Knepley   Level: advanced
3605aad739acSMatthew G. Knepley 
3606db781477SPatrick Sanan .seealso: `TSGetComputeInitialCondition()`, `TSSetComputeInitialCondition()`, `TSSolve()`
3607aad739acSMatthew G. Knepley @*/
3608*d71ae5a4SJacob Faibussowitsch PetscErrorCode TSComputeInitialCondition(TS ts, Vec u)
3609*d71ae5a4SJacob Faibussowitsch {
3610aad739acSMatthew G. Knepley   PetscFunctionBegin;
3611aad739acSMatthew G. Knepley   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3612aad739acSMatthew G. Knepley   PetscValidHeaderSpecific(u, VEC_CLASSID, 2);
3613dbbe0bcdSBarry Smith   PetscTryTypeMethod(ts, initcondition, u);
3614aad739acSMatthew G. Knepley   PetscFunctionReturn(0);
3615aad739acSMatthew G. Knepley }
3616aad739acSMatthew G. Knepley 
3617aad739acSMatthew G. Knepley /*@C
3618aad739acSMatthew G. Knepley   TSGetComputeExactError - Get the function used to automatically compute the exact error for the timestepping.
3619aad739acSMatthew G. Knepley 
3620aad739acSMatthew G. Knepley   Not collective
3621aad739acSMatthew G. Knepley 
36224165533cSJose E. Roman   Input Parameter:
3623aad739acSMatthew G. Knepley . ts         - time stepping context
3624aad739acSMatthew G. Knepley 
36254165533cSJose E. Roman   Output Parameter:
3626aad739acSMatthew G. Knepley . exactError - The function which computes the solution error
3627aad739acSMatthew G. Knepley 
3628aad739acSMatthew G. Knepley   Level: advanced
3629aad739acSMatthew G. Knepley 
3630a96d6ef6SBarry Smith   Calling sequence for exactError:
3631a96d6ef6SBarry Smith $ PetscErrorCode exactError(TS ts, Vec u)
3632a96d6ef6SBarry Smith 
3633a96d6ef6SBarry Smith + ts - The timestepping context
3634a96d6ef6SBarry Smith . u  - The approximate solution vector
3635a96d6ef6SBarry Smith - e  - The input vector in which the error is stored
3636aad739acSMatthew G. Knepley 
3637db781477SPatrick Sanan .seealso: `TSGetComputeExactError()`, `TSComputeExactError()`
3638aad739acSMatthew G. Knepley @*/
3639*d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetComputeExactError(TS ts, PetscErrorCode (**exactError)(TS, Vec, Vec))
3640*d71ae5a4SJacob Faibussowitsch {
3641aad739acSMatthew G. Knepley   PetscFunctionBegin;
3642aad739acSMatthew G. Knepley   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3643aad739acSMatthew G. Knepley   PetscValidPointer(exactError, 2);
3644aad739acSMatthew G. Knepley   *exactError = ts->ops->exacterror;
3645aad739acSMatthew G. Knepley   PetscFunctionReturn(0);
3646aad739acSMatthew G. Knepley }
3647aad739acSMatthew G. Knepley 
3648aad739acSMatthew G. Knepley /*@C
3649aad739acSMatthew G. Knepley   TSSetComputeExactError - Set the function used to automatically compute the exact error for the timestepping.
3650aad739acSMatthew G. Knepley 
3651aad739acSMatthew G. Knepley   Logically collective on ts
3652aad739acSMatthew G. Knepley 
36534165533cSJose E. Roman   Input Parameters:
3654aad739acSMatthew G. Knepley + ts         - time stepping context
3655aad739acSMatthew G. Knepley - exactError - The function which computes the solution error
3656aad739acSMatthew G. Knepley 
3657aad739acSMatthew G. Knepley   Level: advanced
3658aad739acSMatthew G. Knepley 
3659a96d6ef6SBarry Smith   Calling sequence for exactError:
3660a96d6ef6SBarry Smith $ PetscErrorCode exactError(TS ts, Vec u)
3661a96d6ef6SBarry Smith 
3662a96d6ef6SBarry Smith + ts - The timestepping context
3663a96d6ef6SBarry Smith . u  - The approximate solution vector
3664a96d6ef6SBarry Smith - e  - The input vector in which the error is stored
3665aad739acSMatthew G. Knepley 
3666db781477SPatrick Sanan .seealso: `TSGetComputeExactError()`, `TSComputeExactError()`
3667aad739acSMatthew G. Knepley @*/
3668*d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetComputeExactError(TS ts, PetscErrorCode (*exactError)(TS, Vec, Vec))
3669*d71ae5a4SJacob Faibussowitsch {
3670aad739acSMatthew G. Knepley   PetscFunctionBegin;
3671aad739acSMatthew G. Knepley   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3672f907fdbfSMatthew G. Knepley   PetscValidFunction(exactError, 2);
3673aad739acSMatthew G. Knepley   ts->ops->exacterror = exactError;
3674aad739acSMatthew G. Knepley   PetscFunctionReturn(0);
3675aad739acSMatthew G. Knepley }
3676aad739acSMatthew G. Knepley 
3677aad739acSMatthew G. Knepley /*@
3678aad739acSMatthew G. Knepley   TSComputeExactError - Compute the solution error for the timestepping using the function previously set.
3679aad739acSMatthew G. Knepley 
3680aad739acSMatthew G. Knepley   Collective on ts
3681aad739acSMatthew G. Knepley 
36824165533cSJose E. Roman   Input Parameters:
3683aad739acSMatthew G. Knepley + ts - time stepping context
3684aad739acSMatthew G. Knepley . u  - The approximate solution
3685aad739acSMatthew G. Knepley - e  - The Vec used to store the error
3686aad739acSMatthew G. Knepley 
3687aad739acSMatthew G. Knepley   Level: advanced
3688aad739acSMatthew G. Knepley 
3689db781477SPatrick Sanan .seealso: `TSGetComputeInitialCondition()`, `TSSetComputeInitialCondition()`, `TSSolve()`
3690aad739acSMatthew G. Knepley @*/
3691*d71ae5a4SJacob Faibussowitsch PetscErrorCode TSComputeExactError(TS ts, Vec u, Vec e)
3692*d71ae5a4SJacob Faibussowitsch {
3693aad739acSMatthew G. Knepley   PetscFunctionBegin;
3694aad739acSMatthew G. Knepley   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3695aad739acSMatthew G. Knepley   PetscValidHeaderSpecific(u, VEC_CLASSID, 2);
3696aad739acSMatthew G. Knepley   PetscValidHeaderSpecific(e, VEC_CLASSID, 3);
3697dbbe0bcdSBarry Smith   PetscTryTypeMethod(ts, exacterror, u, e);
3698aad739acSMatthew G. Knepley   PetscFunctionReturn(0);
3699aad739acSMatthew G. Knepley }
3700aad739acSMatthew G. Knepley 
3701b1cb36f3SHong Zhang /*@
37026a4d4014SLisandro Dalcin    TSSolve - Steps the requested number of timesteps.
37036a4d4014SLisandro Dalcin 
37046a4d4014SLisandro Dalcin    Collective on TS
37056a4d4014SLisandro Dalcin 
3706d8d19677SJose E. Roman    Input Parameters:
37076a4d4014SLisandro Dalcin +  ts - the TS context obtained from TSCreate()
370863e21af5SBarry Smith -  u - the solution vector  (can be null if TSSetSolution() was used and TSSetExactFinalTime(ts,TS_EXACTFINALTIME_MATCHSTEP) was not used,
370963e21af5SBarry Smith                              otherwise must contain the initial conditions and will contain the solution at the final requested time
37105a3a76d0SJed Brown 
37116a4d4014SLisandro Dalcin    Level: beginner
37126a4d4014SLisandro Dalcin 
37135a3a76d0SJed Brown    Notes:
37145a3a76d0SJed Brown    The final time returned by this function may be different from the time of the internally
37155a3a76d0SJed Brown    held state accessible by TSGetSolution() and TSGetTime() because the method may have
37165a3a76d0SJed Brown    stepped over the final time.
37175a3a76d0SJed Brown 
3718db781477SPatrick Sanan .seealso: `TSCreate()`, `TSSetSolution()`, `TSStep()`, `TSGetTime()`, `TSGetSolveTime()`
37196a4d4014SLisandro Dalcin @*/
3720*d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSolve(TS ts, Vec u)
3721*d71ae5a4SJacob Faibussowitsch {
3722b06615a5SLisandro Dalcin   Vec solution;
3723f22f69f0SBarry Smith 
37246a4d4014SLisandro Dalcin   PetscFunctionBegin;
37250700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3726f2c2a1b9SBarry Smith   if (u) PetscValidHeaderSpecific(u, VEC_CLASSID, 2);
3727303a5415SBarry Smith 
37289566063dSJacob Faibussowitsch   PetscCall(TSSetExactFinalTimeDefault(ts));
3729ee41a567SStefano 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 */
37300910c330SBarry Smith     if (!ts->vec_sol || u == ts->vec_sol) {
37319566063dSJacob Faibussowitsch       PetscCall(VecDuplicate(u, &solution));
37329566063dSJacob Faibussowitsch       PetscCall(TSSetSolution(ts, solution));
37339566063dSJacob Faibussowitsch       PetscCall(VecDestroy(&solution)); /* grant ownership */
37345a3a76d0SJed Brown     }
37359566063dSJacob Faibussowitsch     PetscCall(VecCopy(u, ts->vec_sol));
37363c633725SBarry Smith     PetscCheck(!ts->forward_solve, PetscObjectComm((PetscObject)ts), PETSC_ERR_SUP, "Sensitivity analysis does not support the mode TS_EXACTFINALTIME_INTERPOLATE");
37371baa6e33SBarry Smith   } else if (u) PetscCall(TSSetSolution(ts, u));
37389566063dSJacob Faibussowitsch   PetscCall(TSSetUp(ts));
37399566063dSJacob Faibussowitsch   PetscCall(TSTrajectorySetUp(ts->trajectory, ts));
3740a6772fa2SLisandro Dalcin 
37413c633725SBarry Smith   PetscCheck(ts->max_time < PETSC_MAX_REAL || ts->max_steps != PETSC_MAX_INT, PetscObjectComm((PetscObject)ts), PETSC_ERR_ARG_WRONGSTATE, "You must call TSSetMaxTime() or TSSetMaxSteps(), or use -ts_max_time <time> or -ts_max_steps <steps>");
37423c633725SBarry 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()");
37433c633725SBarry 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");
37444a658b32SHong Zhang   PetscCheck(!(ts->tspan && ts->exact_final_time != TS_EXACTFINALTIME_MATCHSTEP), PetscObjectComm((PetscObject)ts), PETSC_ERR_SUP, "You must use TS_EXACTFINALTIME_MATCHSTEP when using time span");
37454a658b32SHong Zhang 
3746e1db57b0SHong Zhang   if (ts->tspan && PetscIsCloseAtTol(ts->ptime, ts->tspan->span_times[0], ts->tspan->reltol * ts->time_step + ts->tspan->abstol, 0)) { /* starting point in time span */
37474a658b32SHong Zhang     PetscCall(VecCopy(ts->vec_sol, ts->tspan->vecs_sol[0]));
37484a658b32SHong Zhang     ts->tspan->spanctr = 1;
37494a658b32SHong Zhang   }
3750a6772fa2SLisandro Dalcin 
37511baa6e33SBarry Smith   if (ts->forward_solve) PetscCall(TSForwardSetUp(ts));
3752715f1b00SHong Zhang 
3753e7069c78SShri   /* reset number of steps only when the step is not restarted. ARKIMEX
3754715f1b00SHong Zhang      restarts the step after an event. Resetting these counters in such case causes
3755e7069c78SShri      TSTrajectory to incorrectly save the output files
3756e7069c78SShri   */
3757715f1b00SHong Zhang   /* reset time step and iteration counters */
37582808aa04SLisandro Dalcin   if (!ts->steps) {
37595ef26d82SJed Brown     ts->ksp_its           = 0;
37605ef26d82SJed Brown     ts->snes_its          = 0;
3761c610991cSLisandro Dalcin     ts->num_snes_failures = 0;
3762c610991cSLisandro Dalcin     ts->reject            = 0;
37632808aa04SLisandro Dalcin     ts->steprestart       = PETSC_TRUE;
37642808aa04SLisandro Dalcin     ts->steprollback      = PETSC_FALSE;
37657d51462cSStefano Zampini     ts->rhsjacobian.time  = PETSC_MIN_REAL;
37662808aa04SLisandro Dalcin   }
3767e97c63d7SStefano Zampini 
37684a658b32SHong Zhang   /* make sure initial time step does not overshoot final time or the next point in tspan */
3769e97c63d7SStefano Zampini   if (ts->exact_final_time == TS_EXACTFINALTIME_MATCHSTEP) {
37704a658b32SHong Zhang     PetscReal maxdt;
3771e97c63d7SStefano Zampini     PetscReal dt = ts->time_step;
3772e97c63d7SStefano Zampini 
37734a658b32SHong Zhang     if (ts->tspan) maxdt = ts->tspan->span_times[ts->tspan->spanctr] - ts->ptime;
37744a658b32SHong Zhang     else maxdt = ts->max_time - ts->ptime;
3775e97c63d7SStefano Zampini     ts->time_step = dt >= maxdt ? maxdt : (PetscIsCloseAtTol(dt, maxdt, 10 * PETSC_MACHINE_EPSILON, 0) ? maxdt : dt);
3776e97c63d7SStefano Zampini   }
3777193ac0bcSJed Brown   ts->reason = TS_CONVERGED_ITERATING;
3778193ac0bcSJed Brown 
3779900f6b5bSMatthew G. Knepley   {
3780900f6b5bSMatthew G. Knepley     PetscViewer       viewer;
3781900f6b5bSMatthew G. Knepley     PetscViewerFormat format;
3782900f6b5bSMatthew G. Knepley     PetscBool         flg;
3783900f6b5bSMatthew G. Knepley     static PetscBool  incall = PETSC_FALSE;
3784900f6b5bSMatthew G. Knepley 
3785900f6b5bSMatthew G. Knepley     if (!incall) {
3786900f6b5bSMatthew G. Knepley       /* Estimate the convergence rate of the time discretization */
37879566063dSJacob Faibussowitsch       PetscCall(PetscOptionsGetViewer(PetscObjectComm((PetscObject)ts), ((PetscObject)ts)->options, ((PetscObject)ts)->prefix, "-ts_convergence_estimate", &viewer, &format, &flg));
3788900f6b5bSMatthew G. Knepley       if (flg) {
3789900f6b5bSMatthew G. Knepley         PetscConvEst conv;
3790900f6b5bSMatthew G. Knepley         DM           dm;
3791900f6b5bSMatthew G. Knepley         PetscReal   *alpha; /* Convergence rate of the solution error for each field in the L_2 norm */
3792900f6b5bSMatthew G. Knepley         PetscInt     Nf;
3793f2ed2dc7SMatthew G. Knepley         PetscBool    checkTemporal = PETSC_TRUE;
3794900f6b5bSMatthew G. Knepley 
3795900f6b5bSMatthew G. Knepley         incall = PETSC_TRUE;
37969566063dSJacob Faibussowitsch         PetscCall(PetscOptionsGetBool(((PetscObject)ts)->options, ((PetscObject)ts)->prefix, "-ts_convergence_temporal", &checkTemporal, &flg));
37979566063dSJacob Faibussowitsch         PetscCall(TSGetDM(ts, &dm));
37989566063dSJacob Faibussowitsch         PetscCall(DMGetNumFields(dm, &Nf));
37999566063dSJacob Faibussowitsch         PetscCall(PetscCalloc1(PetscMax(Nf, 1), &alpha));
38009566063dSJacob Faibussowitsch         PetscCall(PetscConvEstCreate(PetscObjectComm((PetscObject)ts), &conv));
38019566063dSJacob Faibussowitsch         PetscCall(PetscConvEstUseTS(conv, checkTemporal));
38029566063dSJacob Faibussowitsch         PetscCall(PetscConvEstSetSolver(conv, (PetscObject)ts));
38039566063dSJacob Faibussowitsch         PetscCall(PetscConvEstSetFromOptions(conv));
38049566063dSJacob Faibussowitsch         PetscCall(PetscConvEstSetUp(conv));
38059566063dSJacob Faibussowitsch         PetscCall(PetscConvEstGetConvRate(conv, alpha));
38069566063dSJacob Faibussowitsch         PetscCall(PetscViewerPushFormat(viewer, format));
38079566063dSJacob Faibussowitsch         PetscCall(PetscConvEstRateView(conv, alpha, viewer));
38089566063dSJacob Faibussowitsch         PetscCall(PetscViewerPopFormat(viewer));
38099566063dSJacob Faibussowitsch         PetscCall(PetscViewerDestroy(&viewer));
38109566063dSJacob Faibussowitsch         PetscCall(PetscConvEstDestroy(&conv));
38119566063dSJacob Faibussowitsch         PetscCall(PetscFree(alpha));
3812900f6b5bSMatthew G. Knepley         incall = PETSC_FALSE;
3813900f6b5bSMatthew G. Knepley       }
3814900f6b5bSMatthew G. Knepley     }
3815900f6b5bSMatthew G. Knepley   }
3816900f6b5bSMatthew G. Knepley 
38179566063dSJacob Faibussowitsch   PetscCall(TSViewFromOptions(ts, NULL, "-ts_view_pre"));
3818f05ece33SBarry Smith 
3819193ac0bcSJed Brown   if (ts->ops->solve) { /* This private interface is transitional and should be removed when all implementations are updated. */
3820dbbe0bcdSBarry Smith     PetscUseTypeMethod(ts, solve);
38219566063dSJacob Faibussowitsch     if (u) PetscCall(VecCopy(ts->vec_sol, u));
3822cc708dedSBarry Smith     ts->solvetime = ts->ptime;
3823a6772fa2SLisandro Dalcin     solution      = ts->vec_sol;
3824be5899b3SLisandro Dalcin   } else { /* Step the requested number of timesteps. */
3825db4deed7SKarl Rupp     if (ts->steps >= ts->max_steps) ts->reason = TS_CONVERGED_ITS;
3826db4deed7SKarl Rupp     else if (ts->ptime >= ts->max_time) ts->reason = TS_CONVERGED_TIME;
3827e7069c78SShri 
38282808aa04SLisandro Dalcin     if (!ts->steps) {
38299566063dSJacob Faibussowitsch       PetscCall(TSTrajectorySet(ts->trajectory, ts, ts->steps, ts->ptime, ts->vec_sol));
38309566063dSJacob Faibussowitsch       PetscCall(TSEventInitialize(ts->event, ts, ts->ptime, ts->vec_sol));
38312808aa04SLisandro Dalcin     }
38326427ac75SLisandro Dalcin 
3833e1a7a14fSJed Brown     while (!ts->reason) {
38349566063dSJacob Faibussowitsch       PetscCall(TSMonitor(ts, ts->steps, ts->ptime, ts->vec_sol));
38351e66621cSBarry Smith       if (!ts->steprollback) PetscCall(TSPreStep(ts));
38369566063dSJacob Faibussowitsch       PetscCall(TSStep(ts));
38371baa6e33SBarry Smith       if (ts->testjacobian) PetscCall(TSRHSJacobianTest(ts, NULL));
38381baa6e33SBarry Smith       if (ts->testjacobiantranspose) PetscCall(TSRHSJacobianTestTranspose(ts, NULL));
3839cd4cee2dSHong Zhang       if (ts->quadraturets && ts->costintegralfwd) { /* Must evaluate the cost integral before event is handled. The cost integral value can also be rolled back. */
38407b0e2f17SHong Zhang         if (ts->reason >= 0) ts->steps--;            /* Revert the step number changed by TSStep() */
38419566063dSJacob Faibussowitsch         PetscCall(TSForwardCostIntegral(ts));
38427b0e2f17SHong Zhang         if (ts->reason >= 0) ts->steps++;
3843b1cb36f3SHong Zhang       }
384458818c2dSLisandro Dalcin       if (ts->forward_solve) {            /* compute forward sensitivities before event handling because postevent() may change RHS and jump conditions may have to be applied */
38457b0e2f17SHong Zhang         if (ts->reason >= 0) ts->steps--; /* Revert the step number changed by TSStep() */
38469566063dSJacob Faibussowitsch         PetscCall(TSForwardStep(ts));
38477b0e2f17SHong Zhang         if (ts->reason >= 0) ts->steps++;
3848715f1b00SHong Zhang       }
38499566063dSJacob Faibussowitsch       PetscCall(TSPostEvaluate(ts));
38509566063dSJacob 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. */
38511baa6e33SBarry Smith       if (ts->steprollback) PetscCall(TSPostEvaluate(ts));
3852e783b05fSHong Zhang       if (!ts->steprollback) {
38539566063dSJacob Faibussowitsch         PetscCall(TSTrajectorySet(ts->trajectory, ts, ts->steps, ts->ptime, ts->vec_sol));
38549566063dSJacob Faibussowitsch         PetscCall(TSPostStep(ts));
3855aeb4809dSShri Abhyankar       }
3856193ac0bcSJed Brown     }
38579566063dSJacob Faibussowitsch     PetscCall(TSMonitor(ts, ts->steps, ts->ptime, ts->vec_sol));
38586427ac75SLisandro Dalcin 
385949354f04SShri Abhyankar     if (ts->exact_final_time == TS_EXACTFINALTIME_INTERPOLATE && ts->ptime > ts->max_time) {
38609566063dSJacob Faibussowitsch       PetscCall(TSInterpolate(ts, ts->max_time, u));
3861cc708dedSBarry Smith       ts->solvetime = ts->max_time;
3862b06615a5SLisandro Dalcin       solution      = u;
38639566063dSJacob Faibussowitsch       PetscCall(TSMonitor(ts, -1, ts->solvetime, solution));
38640574a7fbSJed Brown     } else {
38659566063dSJacob Faibussowitsch       if (u) PetscCall(VecCopy(ts->vec_sol, u));
3866cc708dedSBarry Smith       ts->solvetime = ts->ptime;
3867b06615a5SLisandro Dalcin       solution      = ts->vec_sol;
38680574a7fbSJed Brown     }
3869193ac0bcSJed Brown   }
3870d2daff3dSHong Zhang 
38719566063dSJacob Faibussowitsch   PetscCall(TSViewFromOptions(ts, NULL, "-ts_view"));
38729566063dSJacob Faibussowitsch   PetscCall(VecViewFromOptions(solution, (PetscObject)ts, "-ts_view_solution"));
38739566063dSJacob Faibussowitsch   PetscCall(PetscObjectSAWsBlock((PetscObject)ts));
38741baa6e33SBarry Smith   if (ts->adjoint_solve) PetscCall(TSAdjointSolve(ts));
38756a4d4014SLisandro Dalcin   PetscFunctionReturn(0);
38766a4d4014SLisandro Dalcin }
38776a4d4014SLisandro Dalcin 
3878d763cef2SBarry Smith /*@
3879b8123daeSJed Brown    TSGetTime - Gets the time of the most recently completed step.
3880d763cef2SBarry Smith 
3881d763cef2SBarry Smith    Not Collective
3882d763cef2SBarry Smith 
3883d763cef2SBarry Smith    Input Parameter:
3884d763cef2SBarry Smith .  ts - the TS context obtained from TSCreate()
3885d763cef2SBarry Smith 
3886d763cef2SBarry Smith    Output Parameter:
388719eac22cSLisandro Dalcin .  t  - the current time. This time may not corresponds to the final time set with TSSetMaxTime(), use TSGetSolveTime().
3888d763cef2SBarry Smith 
3889d763cef2SBarry Smith    Level: beginner
3890d763cef2SBarry Smith 
3891b8123daeSJed Brown    Note:
3892b8123daeSJed Brown    When called during time step evaluation (e.g. during residual evaluation or via hooks set using TSSetPreStep(),
38939be3e283SDebojyoti Ghosh    TSSetPreStage(), TSSetPostStage(), or TSSetPostStep()), the time is the time at the start of the step being evaluated.
3894b8123daeSJed Brown 
3895db781477SPatrick Sanan .seealso: `TSGetSolveTime()`, `TSSetTime()`, `TSGetTimeStep()`, `TSGetStepNumber()`
3896d763cef2SBarry Smith 
3897d763cef2SBarry Smith @*/
3898*d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetTime(TS ts, PetscReal *t)
3899*d71ae5a4SJacob Faibussowitsch {
3900d763cef2SBarry Smith   PetscFunctionBegin;
39010700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3902f7cf8827SBarry Smith   PetscValidRealPointer(t, 2);
3903d763cef2SBarry Smith   *t = ts->ptime;
3904d763cef2SBarry Smith   PetscFunctionReturn(0);
3905d763cef2SBarry Smith }
3906d763cef2SBarry Smith 
3907e5e524a1SHong Zhang /*@
3908e5e524a1SHong Zhang    TSGetPrevTime - Gets the starting time of the previously completed step.
3909e5e524a1SHong Zhang 
3910e5e524a1SHong Zhang    Not Collective
3911e5e524a1SHong Zhang 
3912e5e524a1SHong Zhang    Input Parameter:
3913e5e524a1SHong Zhang .  ts - the TS context obtained from TSCreate()
3914e5e524a1SHong Zhang 
3915e5e524a1SHong Zhang    Output Parameter:
3916e5e524a1SHong Zhang .  t  - the previous time
3917e5e524a1SHong Zhang 
3918e5e524a1SHong Zhang    Level: beginner
3919e5e524a1SHong Zhang 
3920db781477SPatrick Sanan .seealso: `TSGetTime()`, `TSGetSolveTime()`, `TSGetTimeStep()`
3921e5e524a1SHong Zhang 
3922e5e524a1SHong Zhang @*/
3923*d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetPrevTime(TS ts, PetscReal *t)
3924*d71ae5a4SJacob Faibussowitsch {
3925e5e524a1SHong Zhang   PetscFunctionBegin;
3926e5e524a1SHong Zhang   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3927e5e524a1SHong Zhang   PetscValidRealPointer(t, 2);
3928e5e524a1SHong Zhang   *t = ts->ptime_prev;
3929e5e524a1SHong Zhang   PetscFunctionReturn(0);
3930e5e524a1SHong Zhang }
3931e5e524a1SHong Zhang 
39326a4d4014SLisandro Dalcin /*@
39336a4d4014SLisandro Dalcin    TSSetTime - Allows one to reset the time.
39346a4d4014SLisandro Dalcin 
39353f9fe445SBarry Smith    Logically Collective on TS
39366a4d4014SLisandro Dalcin 
39376a4d4014SLisandro Dalcin    Input Parameters:
39386a4d4014SLisandro Dalcin +  ts - the TS context obtained from TSCreate()
39396a4d4014SLisandro Dalcin -  time - the time
39406a4d4014SLisandro Dalcin 
39416a4d4014SLisandro Dalcin    Level: intermediate
39426a4d4014SLisandro Dalcin 
3943db781477SPatrick Sanan .seealso: `TSGetTime()`, `TSSetMaxSteps()`
39446a4d4014SLisandro Dalcin 
39456a4d4014SLisandro Dalcin @*/
3946*d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetTime(TS ts, PetscReal t)
3947*d71ae5a4SJacob Faibussowitsch {
39486a4d4014SLisandro Dalcin   PetscFunctionBegin;
39490700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3950c5eb9154SBarry Smith   PetscValidLogicalCollectiveReal(ts, t, 2);
39516a4d4014SLisandro Dalcin   ts->ptime = t;
39526a4d4014SLisandro Dalcin   PetscFunctionReturn(0);
39536a4d4014SLisandro Dalcin }
39546a4d4014SLisandro Dalcin 
3955d763cef2SBarry Smith /*@C
3956d763cef2SBarry Smith    TSSetOptionsPrefix - Sets the prefix used for searching for all
3957d763cef2SBarry Smith    TS options in the database.
3958d763cef2SBarry Smith 
39593f9fe445SBarry Smith    Logically Collective on TS
3960d763cef2SBarry Smith 
3961d8d19677SJose E. Roman    Input Parameters:
3962d763cef2SBarry Smith +  ts     - The TS context
3963d763cef2SBarry Smith -  prefix - The prefix to prepend to all option names
3964d763cef2SBarry Smith 
3965d763cef2SBarry Smith    Notes:
3966d763cef2SBarry Smith    A hyphen (-) must NOT be given at the beginning of the prefix name.
3967d763cef2SBarry Smith    The first character of all runtime options is AUTOMATICALLY the
3968d763cef2SBarry Smith    hyphen.
3969d763cef2SBarry Smith 
3970d763cef2SBarry Smith    Level: advanced
3971d763cef2SBarry Smith 
3972db781477SPatrick Sanan .seealso: `TSSetFromOptions()`
3973d763cef2SBarry Smith 
3974d763cef2SBarry Smith @*/
3975*d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetOptionsPrefix(TS ts, const char prefix[])
3976*d71ae5a4SJacob Faibussowitsch {
3977089b2837SJed Brown   SNES snes;
3978d763cef2SBarry Smith 
3979d763cef2SBarry Smith   PetscFunctionBegin;
39800700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
39819566063dSJacob Faibussowitsch   PetscCall(PetscObjectSetOptionsPrefix((PetscObject)ts, prefix));
39829566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts, &snes));
39839566063dSJacob Faibussowitsch   PetscCall(SNESSetOptionsPrefix(snes, prefix));
3984d763cef2SBarry Smith   PetscFunctionReturn(0);
3985d763cef2SBarry Smith }
3986d763cef2SBarry Smith 
3987d763cef2SBarry Smith /*@C
3988d763cef2SBarry Smith    TSAppendOptionsPrefix - Appends to the prefix used for searching for all
3989d763cef2SBarry Smith    TS options in the database.
3990d763cef2SBarry Smith 
39913f9fe445SBarry Smith    Logically Collective on TS
3992d763cef2SBarry Smith 
3993d8d19677SJose E. Roman    Input Parameters:
3994d763cef2SBarry Smith +  ts     - The TS context
3995d763cef2SBarry Smith -  prefix - The prefix to prepend to all option names
3996d763cef2SBarry Smith 
3997d763cef2SBarry Smith    Notes:
3998d763cef2SBarry Smith    A hyphen (-) must NOT be given at the beginning of the prefix name.
3999d763cef2SBarry Smith    The first character of all runtime options is AUTOMATICALLY the
4000d763cef2SBarry Smith    hyphen.
4001d763cef2SBarry Smith 
4002d763cef2SBarry Smith    Level: advanced
4003d763cef2SBarry Smith 
4004db781477SPatrick Sanan .seealso: `TSGetOptionsPrefix()`
4005d763cef2SBarry Smith 
4006d763cef2SBarry Smith @*/
4007*d71ae5a4SJacob Faibussowitsch PetscErrorCode TSAppendOptionsPrefix(TS ts, const char prefix[])
4008*d71ae5a4SJacob Faibussowitsch {
4009089b2837SJed Brown   SNES snes;
4010d763cef2SBarry Smith 
4011d763cef2SBarry Smith   PetscFunctionBegin;
40120700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
40139566063dSJacob Faibussowitsch   PetscCall(PetscObjectAppendOptionsPrefix((PetscObject)ts, prefix));
40149566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts, &snes));
40159566063dSJacob Faibussowitsch   PetscCall(SNESAppendOptionsPrefix(snes, prefix));
4016d763cef2SBarry Smith   PetscFunctionReturn(0);
4017d763cef2SBarry Smith }
4018d763cef2SBarry Smith 
4019d763cef2SBarry Smith /*@C
4020d763cef2SBarry Smith    TSGetOptionsPrefix - Sets the prefix used for searching for all
4021d763cef2SBarry Smith    TS options in the database.
4022d763cef2SBarry Smith 
4023d763cef2SBarry Smith    Not Collective
4024d763cef2SBarry Smith 
4025d763cef2SBarry Smith    Input Parameter:
4026d763cef2SBarry Smith .  ts - The TS context
4027d763cef2SBarry Smith 
4028d763cef2SBarry Smith    Output Parameter:
4029d763cef2SBarry Smith .  prefix - A pointer to the prefix string used
4030d763cef2SBarry Smith 
403195452b02SPatrick Sanan    Notes:
403295452b02SPatrick Sanan     On the fortran side, the user should pass in a string 'prifix' of
4033d763cef2SBarry Smith    sufficient length to hold the prefix.
4034d763cef2SBarry Smith 
4035d763cef2SBarry Smith    Level: intermediate
4036d763cef2SBarry Smith 
4037db781477SPatrick Sanan .seealso: `TSAppendOptionsPrefix()`
4038d763cef2SBarry Smith @*/
4039*d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetOptionsPrefix(TS ts, const char *prefix[])
4040*d71ae5a4SJacob Faibussowitsch {
4041d763cef2SBarry Smith   PetscFunctionBegin;
40420700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
40434482741eSBarry Smith   PetscValidPointer(prefix, 2);
40449566063dSJacob Faibussowitsch   PetscCall(PetscObjectGetOptionsPrefix((PetscObject)ts, prefix));
4045d763cef2SBarry Smith   PetscFunctionReturn(0);
4046d763cef2SBarry Smith }
4047d763cef2SBarry Smith 
4048d763cef2SBarry Smith /*@C
4049d763cef2SBarry Smith    TSGetRHSJacobian - Returns the Jacobian J at the present timestep.
4050d763cef2SBarry Smith 
4051d763cef2SBarry Smith    Not Collective, but parallel objects are returned if TS is parallel
4052d763cef2SBarry Smith 
4053d763cef2SBarry Smith    Input Parameter:
4054d763cef2SBarry Smith .  ts  - The TS context obtained from TSCreate()
4055d763cef2SBarry Smith 
4056d763cef2SBarry Smith    Output Parameters:
4057e4357dc4SBarry Smith +  Amat - The (approximate) Jacobian J of G, where U_t = G(U,t)  (or NULL)
4058e4357dc4SBarry Smith .  Pmat - The matrix from which the preconditioner is constructed, usually the same as Amat  (or NULL)
4059e4357dc4SBarry Smith .  func - Function to compute the Jacobian of the RHS  (or NULL)
4060e4357dc4SBarry Smith -  ctx - User-defined context for Jacobian evaluation routine  (or NULL)
4061d763cef2SBarry Smith 
406295452b02SPatrick Sanan    Notes:
406395452b02SPatrick Sanan     You can pass in NULL for any return argument you do not need.
4064d763cef2SBarry Smith 
4065d763cef2SBarry Smith    Level: intermediate
4066d763cef2SBarry Smith 
4067db781477SPatrick Sanan .seealso: `TSGetTimeStep()`, `TSGetMatrices()`, `TSGetTime()`, `TSGetStepNumber()`
4068d763cef2SBarry Smith 
4069d763cef2SBarry Smith @*/
4070*d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetRHSJacobian(TS ts, Mat *Amat, Mat *Pmat, TSRHSJacobian *func, void **ctx)
4071*d71ae5a4SJacob Faibussowitsch {
407224989b8cSPeter Brune   DM dm;
4073089b2837SJed Brown 
4074d763cef2SBarry Smith   PetscFunctionBegin;
407523a57915SBarry Smith   if (Amat || Pmat) {
407623a57915SBarry Smith     SNES snes;
40779566063dSJacob Faibussowitsch     PetscCall(TSGetSNES(ts, &snes));
40789566063dSJacob Faibussowitsch     PetscCall(SNESSetUpMatrices(snes));
40799566063dSJacob Faibussowitsch     PetscCall(SNESGetJacobian(snes, Amat, Pmat, NULL, NULL));
408023a57915SBarry Smith   }
40819566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
40829566063dSJacob Faibussowitsch   PetscCall(DMTSGetRHSJacobian(dm, func, ctx));
4083d763cef2SBarry Smith   PetscFunctionReturn(0);
4084d763cef2SBarry Smith }
4085d763cef2SBarry Smith 
40862eca1d9cSJed Brown /*@C
40872eca1d9cSJed Brown    TSGetIJacobian - Returns the implicit Jacobian at the present timestep.
40882eca1d9cSJed Brown 
40892eca1d9cSJed Brown    Not Collective, but parallel objects are returned if TS is parallel
40902eca1d9cSJed Brown 
40912eca1d9cSJed Brown    Input Parameter:
40922eca1d9cSJed Brown .  ts  - The TS context obtained from TSCreate()
40932eca1d9cSJed Brown 
40942eca1d9cSJed Brown    Output Parameters:
4095e4357dc4SBarry Smith +  Amat  - The (approximate) Jacobian of F(t,U,U_t)
4096e4357dc4SBarry Smith .  Pmat - The matrix from which the preconditioner is constructed, often the same as Amat
40972eca1d9cSJed Brown .  f   - The function to compute the matrices
40982eca1d9cSJed Brown - ctx - User-defined context for Jacobian evaluation routine
40992eca1d9cSJed Brown 
410095452b02SPatrick Sanan    Notes:
410195452b02SPatrick Sanan     You can pass in NULL for any return argument you do not need.
41022eca1d9cSJed Brown 
41032eca1d9cSJed Brown    Level: advanced
41042eca1d9cSJed Brown 
4105db781477SPatrick Sanan .seealso: `TSGetTimeStep()`, `TSGetRHSJacobian()`, `TSGetMatrices()`, `TSGetTime()`, `TSGetStepNumber()`
41062eca1d9cSJed Brown 
41072eca1d9cSJed Brown @*/
4108*d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetIJacobian(TS ts, Mat *Amat, Mat *Pmat, TSIJacobian *f, void **ctx)
4109*d71ae5a4SJacob Faibussowitsch {
411024989b8cSPeter Brune   DM dm;
41110910c330SBarry Smith 
41122eca1d9cSJed Brown   PetscFunctionBegin;
4113c0aab802Sstefano_zampini   if (Amat || Pmat) {
4114c0aab802Sstefano_zampini     SNES snes;
41159566063dSJacob Faibussowitsch     PetscCall(TSGetSNES(ts, &snes));
41169566063dSJacob Faibussowitsch     PetscCall(SNESSetUpMatrices(snes));
41179566063dSJacob Faibussowitsch     PetscCall(SNESGetJacobian(snes, Amat, Pmat, NULL, NULL));
4118c0aab802Sstefano_zampini   }
41199566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
41209566063dSJacob Faibussowitsch   PetscCall(DMTSGetIJacobian(dm, f, ctx));
41212eca1d9cSJed Brown   PetscFunctionReturn(0);
41222eca1d9cSJed Brown }
41232eca1d9cSJed Brown 
4124af0996ceSBarry Smith #include <petsc/private/dmimpl.h>
41256c699258SBarry Smith /*@
41262a808120SBarry Smith    TSSetDM - Sets the DM that may be used by some nonlinear solvers or preconditioners under the TS
41276c699258SBarry Smith 
4128d083f849SBarry Smith    Logically Collective on ts
41296c699258SBarry Smith 
41306c699258SBarry Smith    Input Parameters:
41312a808120SBarry Smith +  ts - the ODE integrator object
41322a808120SBarry Smith -  dm - the dm, cannot be NULL
41336c699258SBarry Smith 
4134e03a659cSJed Brown    Notes:
4135e03a659cSJed Brown    A DM can only be used for solving one problem at a time because information about the problem is stored on the DM,
4136e03a659cSJed Brown    even when not using interfaces like DMTSSetIFunction().  Use DMClone() to get a distinct DM when solving
4137e03a659cSJed Brown    different problems using the same function space.
4138e03a659cSJed Brown 
41396c699258SBarry Smith    Level: intermediate
41406c699258SBarry Smith 
4141db781477SPatrick Sanan .seealso: `TSGetDM()`, `SNESSetDM()`, `SNESGetDM()`
41426c699258SBarry Smith @*/
4143*d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetDM(TS ts, DM dm)
4144*d71ae5a4SJacob Faibussowitsch {
4145089b2837SJed Brown   SNES snes;
4146942e3340SBarry Smith   DMTS tsdm;
41476c699258SBarry Smith 
41486c699258SBarry Smith   PetscFunctionBegin;
41490700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
41502a808120SBarry Smith   PetscValidHeaderSpecific(dm, DM_CLASSID, 2);
41519566063dSJacob Faibussowitsch   PetscCall(PetscObjectReference((PetscObject)dm));
4152942e3340SBarry Smith   if (ts->dm) { /* Move the DMTS context over to the new DM unless the new DM already has one */
41532a34c10cSBarry Smith     if (ts->dm->dmts && !dm->dmts) {
41549566063dSJacob Faibussowitsch       PetscCall(DMCopyDMTS(ts->dm, dm));
41559566063dSJacob Faibussowitsch       PetscCall(DMGetDMTS(ts->dm, &tsdm));
41561e66621cSBarry Smith       /* Grant write privileges to the replacement DM */
41571e66621cSBarry Smith       if (tsdm->originaldm == ts->dm) tsdm->originaldm = dm;
415824989b8cSPeter Brune     }
41599566063dSJacob Faibussowitsch     PetscCall(DMDestroy(&ts->dm));
416024989b8cSPeter Brune   }
41616c699258SBarry Smith   ts->dm = dm;
4162bbd56ea5SKarl Rupp 
41639566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts, &snes));
41649566063dSJacob Faibussowitsch   PetscCall(SNESSetDM(snes, dm));
41656c699258SBarry Smith   PetscFunctionReturn(0);
41666c699258SBarry Smith }
41676c699258SBarry Smith 
41686c699258SBarry Smith /*@
41696c699258SBarry Smith    TSGetDM - Gets the DM that may be used by some preconditioners
41706c699258SBarry Smith 
41713f9fe445SBarry Smith    Not Collective
41726c699258SBarry Smith 
41736c699258SBarry Smith    Input Parameter:
41746c699258SBarry Smith . ts - the preconditioner context
41756c699258SBarry Smith 
41766c699258SBarry Smith    Output Parameter:
41776c699258SBarry Smith .  dm - the dm
41786c699258SBarry Smith 
41796c699258SBarry Smith    Level: intermediate
41806c699258SBarry Smith 
4181db781477SPatrick Sanan .seealso: `TSSetDM()`, `SNESSetDM()`, `SNESGetDM()`
41826c699258SBarry Smith @*/
4183*d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetDM(TS ts, DM *dm)
4184*d71ae5a4SJacob Faibussowitsch {
41856c699258SBarry Smith   PetscFunctionBegin;
41860700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
4187496e6a7aSJed Brown   if (!ts->dm) {
41889566063dSJacob Faibussowitsch     PetscCall(DMShellCreate(PetscObjectComm((PetscObject)ts), &ts->dm));
41899566063dSJacob Faibussowitsch     if (ts->snes) PetscCall(SNESSetDM(ts->snes, ts->dm));
4190496e6a7aSJed Brown   }
41916c699258SBarry Smith   *dm = ts->dm;
41926c699258SBarry Smith   PetscFunctionReturn(0);
41936c699258SBarry Smith }
41941713a123SBarry Smith 
41950f5c6efeSJed Brown /*@
41960f5c6efeSJed Brown    SNESTSFormFunction - Function to evaluate nonlinear residual
41970f5c6efeSJed Brown 
41983f9fe445SBarry Smith    Logically Collective on SNES
41990f5c6efeSJed Brown 
4200d8d19677SJose E. Roman    Input Parameters:
4201d42a1c89SJed Brown + snes - nonlinear solver
42020910c330SBarry Smith . U - the current state at which to evaluate the residual
4203d42a1c89SJed Brown - ctx - user context, must be a TS
42040f5c6efeSJed Brown 
42050f5c6efeSJed Brown    Output Parameter:
42060f5c6efeSJed Brown . F - the nonlinear residual
42070f5c6efeSJed Brown 
42080f5c6efeSJed Brown    Notes:
42090f5c6efeSJed Brown    This function is not normally called by users and is automatically registered with the SNES used by TS.
42100f5c6efeSJed Brown    It is most frequently passed to MatFDColoringSetFunction().
42110f5c6efeSJed Brown 
42120f5c6efeSJed Brown    Level: advanced
42130f5c6efeSJed Brown 
4214db781477SPatrick Sanan .seealso: `SNESSetFunction()`, `MatFDColoringSetFunction()`
42150f5c6efeSJed Brown @*/
4216*d71ae5a4SJacob Faibussowitsch PetscErrorCode SNESTSFormFunction(SNES snes, Vec U, Vec F, void *ctx)
4217*d71ae5a4SJacob Faibussowitsch {
42180f5c6efeSJed Brown   TS ts = (TS)ctx;
42190f5c6efeSJed Brown 
42200f5c6efeSJed Brown   PetscFunctionBegin;
42210f5c6efeSJed Brown   PetscValidHeaderSpecific(snes, SNES_CLASSID, 1);
42220910c330SBarry Smith   PetscValidHeaderSpecific(U, VEC_CLASSID, 2);
42230f5c6efeSJed Brown   PetscValidHeaderSpecific(F, VEC_CLASSID, 3);
42240f5c6efeSJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 4);
42259566063dSJacob Faibussowitsch   PetscCall((ts->ops->snesfunction)(snes, U, F, ts));
42260f5c6efeSJed Brown   PetscFunctionReturn(0);
42270f5c6efeSJed Brown }
42280f5c6efeSJed Brown 
42290f5c6efeSJed Brown /*@
42300f5c6efeSJed Brown    SNESTSFormJacobian - Function to evaluate the Jacobian
42310f5c6efeSJed Brown 
42320f5c6efeSJed Brown    Collective on SNES
42330f5c6efeSJed Brown 
4234d8d19677SJose E. Roman    Input Parameters:
42350f5c6efeSJed Brown + snes - nonlinear solver
42360910c330SBarry Smith . U - the current state at which to evaluate the residual
42370f5c6efeSJed Brown - ctx - user context, must be a TS
42380f5c6efeSJed Brown 
4239d8d19677SJose E. Roman    Output Parameters:
42400f5c6efeSJed Brown + A - the Jacobian
42416b867d5aSJose E. Roman - B - the preconditioning matrix (may be the same as A)
42420f5c6efeSJed Brown 
42430f5c6efeSJed Brown    Notes:
42440f5c6efeSJed Brown    This function is not normally called by users and is automatically registered with the SNES used by TS.
42450f5c6efeSJed Brown 
42460f5c6efeSJed Brown    Level: developer
42470f5c6efeSJed Brown 
4248db781477SPatrick Sanan .seealso: `SNESSetJacobian()`
42490f5c6efeSJed Brown @*/
4250*d71ae5a4SJacob Faibussowitsch PetscErrorCode SNESTSFormJacobian(SNES snes, Vec U, Mat A, Mat B, void *ctx)
4251*d71ae5a4SJacob Faibussowitsch {
42520f5c6efeSJed Brown   TS ts = (TS)ctx;
42530f5c6efeSJed Brown 
42540f5c6efeSJed Brown   PetscFunctionBegin;
42550f5c6efeSJed Brown   PetscValidHeaderSpecific(snes, SNES_CLASSID, 1);
42560910c330SBarry Smith   PetscValidHeaderSpecific(U, VEC_CLASSID, 2);
42570f5c6efeSJed Brown   PetscValidPointer(A, 3);
425894ab13aaSBarry Smith   PetscValidHeaderSpecific(A, MAT_CLASSID, 3);
42590f5c6efeSJed Brown   PetscValidPointer(B, 4);
426094ab13aaSBarry Smith   PetscValidHeaderSpecific(B, MAT_CLASSID, 4);
4261064a246eSJacob Faibussowitsch   PetscValidHeaderSpecific(ts, TS_CLASSID, 5);
42629566063dSJacob Faibussowitsch   PetscCall((ts->ops->snesjacobian)(snes, U, A, B, ts));
42630f5c6efeSJed Brown   PetscFunctionReturn(0);
42640f5c6efeSJed Brown }
4265325fc9f4SBarry Smith 
42660e4ef248SJed Brown /*@C
42679ae8fd06SBarry Smith    TSComputeRHSFunctionLinear - Evaluate the right hand side via the user-provided Jacobian, for linear problems Udot = A U only
42680e4ef248SJed Brown 
42690e4ef248SJed Brown    Collective on TS
42700e4ef248SJed Brown 
42714165533cSJose E. Roman    Input Parameters:
42720e4ef248SJed Brown +  ts - time stepping context
42730e4ef248SJed Brown .  t - time at which to evaluate
42740910c330SBarry Smith .  U - state at which to evaluate
42750e4ef248SJed Brown -  ctx - context
42760e4ef248SJed Brown 
42774165533cSJose E. Roman    Output Parameter:
42780e4ef248SJed Brown .  F - right hand side
42790e4ef248SJed Brown 
42800e4ef248SJed Brown    Level: intermediate
42810e4ef248SJed Brown 
42820e4ef248SJed Brown    Notes:
42830e4ef248SJed Brown    This function is intended to be passed to TSSetRHSFunction() to evaluate the right hand side for linear problems.
42840e4ef248SJed Brown    The matrix (and optionally the evaluation context) should be passed to TSSetRHSJacobian().
42850e4ef248SJed Brown 
4286db781477SPatrick Sanan .seealso: `TSSetRHSFunction()`, `TSSetRHSJacobian()`, `TSComputeRHSJacobianConstant()`
42870e4ef248SJed Brown @*/
4288*d71ae5a4SJacob Faibussowitsch PetscErrorCode TSComputeRHSFunctionLinear(TS ts, PetscReal t, Vec U, Vec F, void *ctx)
4289*d71ae5a4SJacob Faibussowitsch {
42900e4ef248SJed Brown   Mat Arhs, Brhs;
42910e4ef248SJed Brown 
42920e4ef248SJed Brown   PetscFunctionBegin;
42939566063dSJacob Faibussowitsch   PetscCall(TSGetRHSMats_Private(ts, &Arhs, &Brhs));
42942663174eSHong Zhang   /* undo the damage caused by shifting */
42959566063dSJacob Faibussowitsch   PetscCall(TSRecoverRHSJacobian(ts, Arhs, Brhs));
42969566063dSJacob Faibussowitsch   PetscCall(TSComputeRHSJacobian(ts, t, U, Arhs, Brhs));
42979566063dSJacob Faibussowitsch   PetscCall(MatMult(Arhs, U, F));
42980e4ef248SJed Brown   PetscFunctionReturn(0);
42990e4ef248SJed Brown }
43000e4ef248SJed Brown 
43010e4ef248SJed Brown /*@C
43020e4ef248SJed Brown    TSComputeRHSJacobianConstant - Reuses a Jacobian that is time-independent.
43030e4ef248SJed Brown 
43040e4ef248SJed Brown    Collective on TS
43050e4ef248SJed Brown 
43064165533cSJose E. Roman    Input Parameters:
43070e4ef248SJed Brown +  ts - time stepping context
43080e4ef248SJed Brown .  t - time at which to evaluate
43090910c330SBarry Smith .  U - state at which to evaluate
43100e4ef248SJed Brown -  ctx - context
43110e4ef248SJed Brown 
43124165533cSJose E. Roman    Output Parameters:
43130e4ef248SJed Brown +  A - pointer to operator
431497bb3fdcSJose E. Roman -  B - pointer to preconditioning matrix
43150e4ef248SJed Brown 
43160e4ef248SJed Brown    Level: intermediate
43170e4ef248SJed Brown 
43180e4ef248SJed Brown    Notes:
43190e4ef248SJed Brown    This function is intended to be passed to TSSetRHSJacobian() to evaluate the Jacobian for linear time-independent problems.
43200e4ef248SJed Brown 
4321db781477SPatrick Sanan .seealso: `TSSetRHSFunction()`, `TSSetRHSJacobian()`, `TSComputeRHSFunctionLinear()`
43220e4ef248SJed Brown @*/
4323*d71ae5a4SJacob Faibussowitsch PetscErrorCode TSComputeRHSJacobianConstant(TS ts, PetscReal t, Vec U, Mat A, Mat B, void *ctx)
4324*d71ae5a4SJacob Faibussowitsch {
43250e4ef248SJed Brown   PetscFunctionBegin;
43260e4ef248SJed Brown   PetscFunctionReturn(0);
43270e4ef248SJed Brown }
43280e4ef248SJed Brown 
43290026cea9SSean Farley /*@C
43300026cea9SSean Farley    TSComputeIFunctionLinear - Evaluate the left hand side via the user-provided Jacobian, for linear problems only
43310026cea9SSean Farley 
43320026cea9SSean Farley    Collective on TS
43330026cea9SSean Farley 
43344165533cSJose E. Roman    Input Parameters:
43350026cea9SSean Farley +  ts - time stepping context
43360026cea9SSean Farley .  t - time at which to evaluate
43370910c330SBarry Smith .  U - state at which to evaluate
43380910c330SBarry Smith .  Udot - time derivative of state vector
43390026cea9SSean Farley -  ctx - context
43400026cea9SSean Farley 
43414165533cSJose E. Roman    Output Parameter:
43420026cea9SSean Farley .  F - left hand side
43430026cea9SSean Farley 
43440026cea9SSean Farley    Level: intermediate
43450026cea9SSean Farley 
43460026cea9SSean Farley    Notes:
43470910c330SBarry 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
43480026cea9SSean Farley    user is required to write their own TSComputeIFunction.
43490026cea9SSean Farley    This function is intended to be passed to TSSetIFunction() to evaluate the left hand side for linear problems.
43500026cea9SSean Farley    The matrix (and optionally the evaluation context) should be passed to TSSetIJacobian().
43510026cea9SSean Farley 
43529ae8fd06SBarry Smith    Note that using this function is NOT equivalent to using TSComputeRHSFunctionLinear() since that solves Udot = A U
43539ae8fd06SBarry Smith 
4354db781477SPatrick Sanan .seealso: `TSSetIFunction()`, `TSSetIJacobian()`, `TSComputeIJacobianConstant()`, `TSComputeRHSFunctionLinear()`
43550026cea9SSean Farley @*/
4356*d71ae5a4SJacob Faibussowitsch PetscErrorCode TSComputeIFunctionLinear(TS ts, PetscReal t, Vec U, Vec Udot, Vec F, void *ctx)
4357*d71ae5a4SJacob Faibussowitsch {
43580026cea9SSean Farley   Mat A, B;
43590026cea9SSean Farley 
43600026cea9SSean Farley   PetscFunctionBegin;
43619566063dSJacob Faibussowitsch   PetscCall(TSGetIJacobian(ts, &A, &B, NULL, NULL));
43629566063dSJacob Faibussowitsch   PetscCall(TSComputeIJacobian(ts, t, U, Udot, 1.0, A, B, PETSC_TRUE));
43639566063dSJacob Faibussowitsch   PetscCall(MatMult(A, Udot, F));
43640026cea9SSean Farley   PetscFunctionReturn(0);
43650026cea9SSean Farley }
43660026cea9SSean Farley 
43670026cea9SSean Farley /*@C
4368b41af12eSJed Brown    TSComputeIJacobianConstant - Reuses a time-independent for a semi-implicit DAE or ODE
43690026cea9SSean Farley 
43700026cea9SSean Farley    Collective on TS
43710026cea9SSean Farley 
43724165533cSJose E. Roman    Input Parameters:
43730026cea9SSean Farley +  ts - time stepping context
43740026cea9SSean Farley .  t - time at which to evaluate
43750910c330SBarry Smith .  U - state at which to evaluate
43760910c330SBarry Smith .  Udot - time derivative of state vector
43770026cea9SSean Farley .  shift - shift to apply
43780026cea9SSean Farley -  ctx - context
43790026cea9SSean Farley 
43804165533cSJose E. Roman    Output Parameters:
43810026cea9SSean Farley +  A - pointer to operator
438297bb3fdcSJose E. Roman -  B - pointer to preconditioning matrix
43830026cea9SSean Farley 
4384b41af12eSJed Brown    Level: advanced
43850026cea9SSean Farley 
43860026cea9SSean Farley    Notes:
43870026cea9SSean Farley    This function is intended to be passed to TSSetIJacobian() to evaluate the Jacobian for linear time-independent problems.
43880026cea9SSean Farley 
4389b41af12eSJed Brown    It is only appropriate for problems of the form
4390b41af12eSJed Brown 
4391b41af12eSJed Brown $     M Udot = F(U,t)
4392b41af12eSJed Brown 
4393b41af12eSJed Brown   where M is constant and F is non-stiff.  The user must pass M to TSSetIJacobian().  The current implementation only
4394b41af12eSJed Brown   works with IMEX time integration methods such as TSROSW and TSARKIMEX, since there is no support for de-constructing
4395b41af12eSJed Brown   an implicit operator of the form
4396b41af12eSJed Brown 
4397b41af12eSJed Brown $    shift*M + J
4398b41af12eSJed Brown 
4399b41af12eSJed 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
4400b41af12eSJed Brown   a copy of M or reassemble it when requested.
4401b41af12eSJed Brown 
4402db781477SPatrick Sanan .seealso: `TSSetIFunction()`, `TSSetIJacobian()`, `TSComputeIFunctionLinear()`
44030026cea9SSean Farley @*/
4404*d71ae5a4SJacob Faibussowitsch PetscErrorCode TSComputeIJacobianConstant(TS ts, PetscReal t, Vec U, Vec Udot, PetscReal shift, Mat A, Mat B, void *ctx)
4405*d71ae5a4SJacob Faibussowitsch {
44060026cea9SSean Farley   PetscFunctionBegin;
44079566063dSJacob Faibussowitsch   PetscCall(MatScale(A, shift / ts->ijacobian.shift));
4408b41af12eSJed Brown   ts->ijacobian.shift = shift;
44090026cea9SSean Farley   PetscFunctionReturn(0);
44100026cea9SSean Farley }
4411b41af12eSJed Brown 
4412e817cc15SEmil Constantinescu /*@
4413e817cc15SEmil Constantinescu    TSGetEquationType - Gets the type of the equation that TS is solving.
4414e817cc15SEmil Constantinescu 
4415e817cc15SEmil Constantinescu    Not Collective
4416e817cc15SEmil Constantinescu 
4417e817cc15SEmil Constantinescu    Input Parameter:
4418e817cc15SEmil Constantinescu .  ts - the TS context
4419e817cc15SEmil Constantinescu 
4420e817cc15SEmil Constantinescu    Output Parameter:
44214e6b9ce4SEmil Constantinescu .  equation_type - see TSEquationType
4422e817cc15SEmil Constantinescu 
4423e817cc15SEmil Constantinescu    Level: beginner
4424e817cc15SEmil Constantinescu 
4425db781477SPatrick Sanan .seealso: `TSSetEquationType()`, `TSEquationType`
4426e817cc15SEmil Constantinescu @*/
4427*d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetEquationType(TS ts, TSEquationType *equation_type)
4428*d71ae5a4SJacob Faibussowitsch {
4429e817cc15SEmil Constantinescu   PetscFunctionBegin;
4430e817cc15SEmil Constantinescu   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
4431e817cc15SEmil Constantinescu   PetscValidPointer(equation_type, 2);
4432e817cc15SEmil Constantinescu   *equation_type = ts->equation_type;
4433e817cc15SEmil Constantinescu   PetscFunctionReturn(0);
4434e817cc15SEmil Constantinescu }
4435e817cc15SEmil Constantinescu 
4436e817cc15SEmil Constantinescu /*@
4437e817cc15SEmil Constantinescu    TSSetEquationType - Sets the type of the equation that TS is solving.
4438e817cc15SEmil Constantinescu 
4439e817cc15SEmil Constantinescu    Not Collective
4440e817cc15SEmil Constantinescu 
4441d8d19677SJose E. Roman    Input Parameters:
4442e817cc15SEmil Constantinescu +  ts - the TS context
44431297b224SEmil Constantinescu -  equation_type - see TSEquationType
4444e817cc15SEmil Constantinescu 
4445e817cc15SEmil Constantinescu    Level: advanced
4446e817cc15SEmil Constantinescu 
4447db781477SPatrick Sanan .seealso: `TSGetEquationType()`, `TSEquationType`
4448e817cc15SEmil Constantinescu @*/
4449*d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetEquationType(TS ts, TSEquationType equation_type)
4450*d71ae5a4SJacob Faibussowitsch {
4451e817cc15SEmil Constantinescu   PetscFunctionBegin;
4452e817cc15SEmil Constantinescu   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
4453e817cc15SEmil Constantinescu   ts->equation_type = equation_type;
4454e817cc15SEmil Constantinescu   PetscFunctionReturn(0);
4455e817cc15SEmil Constantinescu }
44560026cea9SSean Farley 
44574af1b03aSJed Brown /*@
44584af1b03aSJed Brown    TSGetConvergedReason - Gets the reason the TS iteration was stopped.
44594af1b03aSJed Brown 
44604af1b03aSJed Brown    Not Collective
44614af1b03aSJed Brown 
44624af1b03aSJed Brown    Input Parameter:
44634af1b03aSJed Brown .  ts - the TS context
44644af1b03aSJed Brown 
44654af1b03aSJed Brown    Output Parameter:
44664af1b03aSJed Brown .  reason - negative value indicates diverged, positive value converged, see TSConvergedReason or the
44674af1b03aSJed Brown             manual pages for the individual convergence tests for complete lists
44684af1b03aSJed Brown 
4469487e0bb9SJed Brown    Level: beginner
44704af1b03aSJed Brown 
4471cd652676SJed Brown    Notes:
4472cd652676SJed Brown    Can only be called after the call to TSSolve() is complete.
44734af1b03aSJed Brown 
4474db781477SPatrick Sanan .seealso: `TSSetConvergenceTest()`, `TSConvergedReason`
44754af1b03aSJed Brown @*/
4476*d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetConvergedReason(TS ts, TSConvergedReason *reason)
4477*d71ae5a4SJacob Faibussowitsch {
44784af1b03aSJed Brown   PetscFunctionBegin;
44794af1b03aSJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
44804af1b03aSJed Brown   PetscValidPointer(reason, 2);
44814af1b03aSJed Brown   *reason = ts->reason;
44824af1b03aSJed Brown   PetscFunctionReturn(0);
44834af1b03aSJed Brown }
44844af1b03aSJed Brown 
4485d6ad946cSShri Abhyankar /*@
4486d6ad946cSShri Abhyankar    TSSetConvergedReason - Sets the reason for handling the convergence of TSSolve.
4487d6ad946cSShri Abhyankar 
44886b221cbeSPatrick Sanan    Logically Collective; reason must contain common value
4489d6ad946cSShri Abhyankar 
44906b221cbeSPatrick Sanan    Input Parameters:
4491d6ad946cSShri Abhyankar +  ts - the TS context
44926b221cbeSPatrick Sanan -  reason - negative value indicates diverged, positive value converged, see TSConvergedReason or the
4493d6ad946cSShri Abhyankar             manual pages for the individual convergence tests for complete lists
4494d6ad946cSShri Abhyankar 
4495f5abba47SShri Abhyankar    Level: advanced
4496d6ad946cSShri Abhyankar 
4497d6ad946cSShri Abhyankar    Notes:
44986b221cbeSPatrick Sanan    Can only be called while TSSolve() is active.
4499d6ad946cSShri Abhyankar 
4500db781477SPatrick Sanan .seealso: `TSConvergedReason`
4501d6ad946cSShri Abhyankar @*/
4502*d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetConvergedReason(TS ts, TSConvergedReason reason)
4503*d71ae5a4SJacob Faibussowitsch {
4504d6ad946cSShri Abhyankar   PetscFunctionBegin;
4505d6ad946cSShri Abhyankar   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
4506d6ad946cSShri Abhyankar   ts->reason = reason;
4507d6ad946cSShri Abhyankar   PetscFunctionReturn(0);
4508d6ad946cSShri Abhyankar }
4509d6ad946cSShri Abhyankar 
4510cc708dedSBarry Smith /*@
4511cc708dedSBarry Smith    TSGetSolveTime - Gets the time after a call to TSSolve()
4512cc708dedSBarry Smith 
4513cc708dedSBarry Smith    Not Collective
4514cc708dedSBarry Smith 
4515cc708dedSBarry Smith    Input Parameter:
4516cc708dedSBarry Smith .  ts - the TS context
4517cc708dedSBarry Smith 
4518cc708dedSBarry Smith    Output Parameter:
451919eac22cSLisandro Dalcin .  ftime - the final time. This time corresponds to the final time set with TSSetMaxTime()
4520cc708dedSBarry Smith 
4521487e0bb9SJed Brown    Level: beginner
4522cc708dedSBarry Smith 
4523cc708dedSBarry Smith    Notes:
4524cc708dedSBarry Smith    Can only be called after the call to TSSolve() is complete.
4525cc708dedSBarry Smith 
4526db781477SPatrick Sanan .seealso: `TSSetConvergenceTest()`, `TSConvergedReason`
4527cc708dedSBarry Smith @*/
4528*d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetSolveTime(TS ts, PetscReal *ftime)
4529*d71ae5a4SJacob Faibussowitsch {
4530cc708dedSBarry Smith   PetscFunctionBegin;
4531cc708dedSBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
4532dadcf809SJacob Faibussowitsch   PetscValidRealPointer(ftime, 2);
4533cc708dedSBarry Smith   *ftime = ts->solvetime;
4534cc708dedSBarry Smith   PetscFunctionReturn(0);
4535cc708dedSBarry Smith }
4536cc708dedSBarry Smith 
45372c18e0fdSBarry Smith /*@
45385ef26d82SJed Brown    TSGetSNESIterations - Gets the total number of nonlinear iterations
45399f67acb7SJed Brown    used by the time integrator.
45409f67acb7SJed Brown 
45419f67acb7SJed Brown    Not Collective
45429f67acb7SJed Brown 
45439f67acb7SJed Brown    Input Parameter:
45449f67acb7SJed Brown .  ts - TS context
45459f67acb7SJed Brown 
45469f67acb7SJed Brown    Output Parameter:
45479f67acb7SJed Brown .  nits - number of nonlinear iterations
45489f67acb7SJed Brown 
45499f67acb7SJed Brown    Notes:
45509f67acb7SJed Brown    This counter is reset to zero for each successive call to TSSolve().
45519f67acb7SJed Brown 
45529f67acb7SJed Brown    Level: intermediate
45539f67acb7SJed Brown 
4554db781477SPatrick Sanan .seealso: `TSGetKSPIterations()`
45559f67acb7SJed Brown @*/
4556*d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetSNESIterations(TS ts, PetscInt *nits)
4557*d71ae5a4SJacob Faibussowitsch {
45589f67acb7SJed Brown   PetscFunctionBegin;
45599f67acb7SJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
45609f67acb7SJed Brown   PetscValidIntPointer(nits, 2);
45615ef26d82SJed Brown   *nits = ts->snes_its;
45629f67acb7SJed Brown   PetscFunctionReturn(0);
45639f67acb7SJed Brown }
45649f67acb7SJed Brown 
45659f67acb7SJed Brown /*@
45665ef26d82SJed Brown    TSGetKSPIterations - Gets the total number of linear iterations
45679f67acb7SJed Brown    used by the time integrator.
45689f67acb7SJed Brown 
45699f67acb7SJed Brown    Not Collective
45709f67acb7SJed Brown 
45719f67acb7SJed Brown    Input Parameter:
45729f67acb7SJed Brown .  ts - TS context
45739f67acb7SJed Brown 
45749f67acb7SJed Brown    Output Parameter:
45759f67acb7SJed Brown .  lits - number of linear iterations
45769f67acb7SJed Brown 
45779f67acb7SJed Brown    Notes:
45789f67acb7SJed Brown    This counter is reset to zero for each successive call to TSSolve().
45799f67acb7SJed Brown 
45809f67acb7SJed Brown    Level: intermediate
45819f67acb7SJed Brown 
4582db781477SPatrick Sanan .seealso: `TSGetSNESIterations()`, `SNESGetKSPIterations()`
45839f67acb7SJed Brown @*/
4584*d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetKSPIterations(TS ts, PetscInt *lits)
4585*d71ae5a4SJacob Faibussowitsch {
45869f67acb7SJed Brown   PetscFunctionBegin;
45879f67acb7SJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
45889f67acb7SJed Brown   PetscValidIntPointer(lits, 2);
45895ef26d82SJed Brown   *lits = ts->ksp_its;
45909f67acb7SJed Brown   PetscFunctionReturn(0);
45919f67acb7SJed Brown }
45929f67acb7SJed Brown 
4593cef5090cSJed Brown /*@
4594cef5090cSJed Brown    TSGetStepRejections - Gets the total number of rejected steps.
4595cef5090cSJed Brown 
4596cef5090cSJed Brown    Not Collective
4597cef5090cSJed Brown 
4598cef5090cSJed Brown    Input Parameter:
4599cef5090cSJed Brown .  ts - TS context
4600cef5090cSJed Brown 
4601cef5090cSJed Brown    Output Parameter:
4602cef5090cSJed Brown .  rejects - number of steps rejected
4603cef5090cSJed Brown 
4604cef5090cSJed Brown    Notes:
4605cef5090cSJed Brown    This counter is reset to zero for each successive call to TSSolve().
4606cef5090cSJed Brown 
4607cef5090cSJed Brown    Level: intermediate
4608cef5090cSJed Brown 
4609db781477SPatrick Sanan .seealso: `TSGetSNESIterations()`, `TSGetKSPIterations()`, `TSSetMaxStepRejections()`, `TSGetSNESFailures()`, `TSSetMaxSNESFailures()`, `TSSetErrorIfStepFails()`
4610cef5090cSJed Brown @*/
4611*d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetStepRejections(TS ts, PetscInt *rejects)
4612*d71ae5a4SJacob Faibussowitsch {
4613cef5090cSJed Brown   PetscFunctionBegin;
4614cef5090cSJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
4615cef5090cSJed Brown   PetscValidIntPointer(rejects, 2);
4616cef5090cSJed Brown   *rejects = ts->reject;
4617cef5090cSJed Brown   PetscFunctionReturn(0);
4618cef5090cSJed Brown }
4619cef5090cSJed Brown 
4620cef5090cSJed Brown /*@
4621cef5090cSJed Brown    TSGetSNESFailures - Gets the total number of failed SNES solves
4622cef5090cSJed Brown 
4623cef5090cSJed Brown    Not Collective
4624cef5090cSJed Brown 
4625cef5090cSJed Brown    Input Parameter:
4626cef5090cSJed Brown .  ts - TS context
4627cef5090cSJed Brown 
4628cef5090cSJed Brown    Output Parameter:
4629cef5090cSJed Brown .  fails - number of failed nonlinear solves
4630cef5090cSJed Brown 
4631cef5090cSJed Brown    Notes:
4632cef5090cSJed Brown    This counter is reset to zero for each successive call to TSSolve().
4633cef5090cSJed Brown 
4634cef5090cSJed Brown    Level: intermediate
4635cef5090cSJed Brown 
4636db781477SPatrick Sanan .seealso: `TSGetSNESIterations()`, `TSGetKSPIterations()`, `TSSetMaxStepRejections()`, `TSGetStepRejections()`, `TSSetMaxSNESFailures()`
4637cef5090cSJed Brown @*/
4638*d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetSNESFailures(TS ts, PetscInt *fails)
4639*d71ae5a4SJacob Faibussowitsch {
4640cef5090cSJed Brown   PetscFunctionBegin;
4641cef5090cSJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
4642cef5090cSJed Brown   PetscValidIntPointer(fails, 2);
4643cef5090cSJed Brown   *fails = ts->num_snes_failures;
4644cef5090cSJed Brown   PetscFunctionReturn(0);
4645cef5090cSJed Brown }
4646cef5090cSJed Brown 
4647cef5090cSJed Brown /*@
4648cef5090cSJed Brown    TSSetMaxStepRejections - Sets the maximum number of step rejections before a step fails
4649cef5090cSJed Brown 
4650cef5090cSJed Brown    Not Collective
4651cef5090cSJed Brown 
4652d8d19677SJose E. Roman    Input Parameters:
4653cef5090cSJed Brown +  ts - TS context
4654cef5090cSJed Brown -  rejects - maximum number of rejected steps, pass -1 for unlimited
4655cef5090cSJed Brown 
4656cef5090cSJed Brown    Notes:
4657cef5090cSJed Brown    The counter is reset to zero for each step
4658cef5090cSJed Brown 
4659cef5090cSJed Brown    Options Database Key:
4660cef5090cSJed Brown .  -ts_max_reject - Maximum number of step rejections before a step fails
4661cef5090cSJed Brown 
4662cef5090cSJed Brown    Level: intermediate
4663cef5090cSJed Brown 
4664db781477SPatrick Sanan .seealso: `TSGetSNESIterations()`, `TSGetKSPIterations()`, `TSSetMaxSNESFailures()`, `TSGetStepRejections()`, `TSGetSNESFailures()`, `TSSetErrorIfStepFails()`, `TSGetConvergedReason()`
4665cef5090cSJed Brown @*/
4666*d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetMaxStepRejections(TS ts, PetscInt rejects)
4667*d71ae5a4SJacob Faibussowitsch {
4668cef5090cSJed Brown   PetscFunctionBegin;
4669cef5090cSJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
4670cef5090cSJed Brown   ts->max_reject = rejects;
4671cef5090cSJed Brown   PetscFunctionReturn(0);
4672cef5090cSJed Brown }
4673cef5090cSJed Brown 
4674cef5090cSJed Brown /*@
4675cef5090cSJed Brown    TSSetMaxSNESFailures - Sets the maximum number of failed SNES solves
4676cef5090cSJed Brown 
4677cef5090cSJed Brown    Not Collective
4678cef5090cSJed Brown 
4679d8d19677SJose E. Roman    Input Parameters:
4680cef5090cSJed Brown +  ts - TS context
4681cef5090cSJed Brown -  fails - maximum number of failed nonlinear solves, pass -1 for unlimited
4682cef5090cSJed Brown 
4683cef5090cSJed Brown    Notes:
4684cef5090cSJed Brown    The counter is reset to zero for each successive call to TSSolve().
4685cef5090cSJed Brown 
4686cef5090cSJed Brown    Options Database Key:
4687cef5090cSJed Brown .  -ts_max_snes_failures - Maximum number of nonlinear solve failures
4688cef5090cSJed Brown 
4689cef5090cSJed Brown    Level: intermediate
4690cef5090cSJed Brown 
4691db781477SPatrick Sanan .seealso: `TSGetSNESIterations()`, `TSGetKSPIterations()`, `TSSetMaxStepRejections()`, `TSGetStepRejections()`, `TSGetSNESFailures()`, `SNESGetConvergedReason()`, `TSGetConvergedReason()`
4692cef5090cSJed Brown @*/
4693*d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetMaxSNESFailures(TS ts, PetscInt fails)
4694*d71ae5a4SJacob Faibussowitsch {
4695cef5090cSJed Brown   PetscFunctionBegin;
4696cef5090cSJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
4697cef5090cSJed Brown   ts->max_snes_failures = fails;
4698cef5090cSJed Brown   PetscFunctionReturn(0);
4699cef5090cSJed Brown }
4700cef5090cSJed Brown 
4701cef5090cSJed Brown /*@
4702cef5090cSJed Brown    TSSetErrorIfStepFails - Error if no step succeeds
4703cef5090cSJed Brown 
4704cef5090cSJed Brown    Not Collective
4705cef5090cSJed Brown 
4706d8d19677SJose E. Roman    Input Parameters:
4707cef5090cSJed Brown +  ts - TS context
4708cef5090cSJed Brown -  err - PETSC_TRUE to error if no step succeeds, PETSC_FALSE to return without failure
4709cef5090cSJed Brown 
4710cef5090cSJed Brown    Options Database Key:
4711cef5090cSJed Brown .  -ts_error_if_step_fails - Error if no step succeeds
4712cef5090cSJed Brown 
4713cef5090cSJed Brown    Level: intermediate
4714cef5090cSJed Brown 
4715db781477SPatrick Sanan .seealso: `TSGetSNESIterations()`, `TSGetKSPIterations()`, `TSSetMaxStepRejections()`, `TSGetStepRejections()`, `TSGetSNESFailures()`, `TSSetErrorIfStepFails()`, `TSGetConvergedReason()`
4716cef5090cSJed Brown @*/
4717*d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetErrorIfStepFails(TS ts, PetscBool err)
4718*d71ae5a4SJacob Faibussowitsch {
4719cef5090cSJed Brown   PetscFunctionBegin;
4720cef5090cSJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
4721cef5090cSJed Brown   ts->errorifstepfailed = err;
4722cef5090cSJed Brown   PetscFunctionReturn(0);
4723cef5090cSJed Brown }
4724cef5090cSJed Brown 
472584df9cb4SJed Brown /*@
4726552698daSJed Brown    TSGetAdapt - Get the adaptive controller context for the current method
472784df9cb4SJed Brown 
4728ed81e22dSJed Brown    Collective on TS if controller has not been created yet
472984df9cb4SJed Brown 
47304165533cSJose E. Roman    Input Parameter:
4731ed81e22dSJed Brown .  ts - time stepping context
473284df9cb4SJed Brown 
47334165533cSJose E. Roman    Output Parameter:
4734ed81e22dSJed Brown .  adapt - adaptive controller
473584df9cb4SJed Brown 
473684df9cb4SJed Brown    Level: intermediate
473784df9cb4SJed Brown 
4738db781477SPatrick Sanan .seealso: `TSAdapt`, `TSAdaptSetType()`, `TSAdaptChoose()`
473984df9cb4SJed Brown @*/
4740*d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetAdapt(TS ts, TSAdapt *adapt)
4741*d71ae5a4SJacob Faibussowitsch {
474284df9cb4SJed Brown   PetscFunctionBegin;
474384df9cb4SJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
4744bec58848SLisandro Dalcin   PetscValidPointer(adapt, 2);
474584df9cb4SJed Brown   if (!ts->adapt) {
47469566063dSJacob Faibussowitsch     PetscCall(TSAdaptCreate(PetscObjectComm((PetscObject)ts), &ts->adapt));
47479566063dSJacob Faibussowitsch     PetscCall(PetscObjectIncrementTabLevel((PetscObject)ts->adapt, (PetscObject)ts, 1));
474884df9cb4SJed Brown   }
4749bec58848SLisandro Dalcin   *adapt = ts->adapt;
475084df9cb4SJed Brown   PetscFunctionReturn(0);
475184df9cb4SJed Brown }
4752d6ebe24aSShri Abhyankar 
47531c3436cfSJed Brown /*@
47541c3436cfSJed Brown    TSSetTolerances - Set tolerances for local truncation error when using adaptive controller
47551c3436cfSJed Brown 
47561c3436cfSJed Brown    Logically Collective
47571c3436cfSJed Brown 
47584165533cSJose E. Roman    Input Parameters:
47591c3436cfSJed Brown +  ts - time integration context
47601c3436cfSJed Brown .  atol - scalar absolute tolerances, PETSC_DECIDE to leave current value
47610298fd71SBarry Smith .  vatol - vector of absolute tolerances or NULL, used in preference to atol if present
47621c3436cfSJed Brown .  rtol - scalar relative tolerances, PETSC_DECIDE to leave current value
47630298fd71SBarry Smith -  vrtol - vector of relative tolerances or NULL, used in preference to atol if present
47641c3436cfSJed Brown 
4765a3cdaa26SBarry Smith    Options Database keys:
4766a3cdaa26SBarry Smith +  -ts_rtol <rtol> - relative tolerance for local truncation error
476767b8a455SSatish Balay -  -ts_atol <atol> - Absolute tolerance for local truncation error
4768a3cdaa26SBarry Smith 
47693ff766beSShri Abhyankar    Notes:
47703ff766beSShri Abhyankar    With PETSc's implicit schemes for DAE problems, the calculation of the local truncation error
47713ff766beSShri Abhyankar    (LTE) includes both the differential and the algebraic variables. If one wants the LTE to be
47723ff766beSShri Abhyankar    computed only for the differential or the algebraic part then this can be done using the vector of
47733ff766beSShri Abhyankar    tolerances vatol. For example, by setting the tolerance vector with the desired tolerance for the
47743ff766beSShri Abhyankar    differential part and infinity for the algebraic part, the LTE calculation will include only the
47753ff766beSShri Abhyankar    differential variables.
47763ff766beSShri Abhyankar 
47771c3436cfSJed Brown    Level: beginner
47781c3436cfSJed Brown 
4779db781477SPatrick Sanan .seealso: `TS`, `TSAdapt`, `TSErrorWeightedNorm()`, `TSGetTolerances()`
47801c3436cfSJed Brown @*/
4781*d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetTolerances(TS ts, PetscReal atol, Vec vatol, PetscReal rtol, Vec vrtol)
4782*d71ae5a4SJacob Faibussowitsch {
47831c3436cfSJed Brown   PetscFunctionBegin;
4784c5033834SJed Brown   if (atol != PETSC_DECIDE && atol != PETSC_DEFAULT) ts->atol = atol;
47851c3436cfSJed Brown   if (vatol) {
47869566063dSJacob Faibussowitsch     PetscCall(PetscObjectReference((PetscObject)vatol));
47879566063dSJacob Faibussowitsch     PetscCall(VecDestroy(&ts->vatol));
47881c3436cfSJed Brown     ts->vatol = vatol;
47891c3436cfSJed Brown   }
4790c5033834SJed Brown   if (rtol != PETSC_DECIDE && rtol != PETSC_DEFAULT) ts->rtol = rtol;
47911c3436cfSJed Brown   if (vrtol) {
47929566063dSJacob Faibussowitsch     PetscCall(PetscObjectReference((PetscObject)vrtol));
47939566063dSJacob Faibussowitsch     PetscCall(VecDestroy(&ts->vrtol));
47941c3436cfSJed Brown     ts->vrtol = vrtol;
47951c3436cfSJed Brown   }
47961c3436cfSJed Brown   PetscFunctionReturn(0);
47971c3436cfSJed Brown }
47981c3436cfSJed Brown 
4799c5033834SJed Brown /*@
4800c5033834SJed Brown    TSGetTolerances - Get tolerances for local truncation error when using adaptive controller
4801c5033834SJed Brown 
4802c5033834SJed Brown    Logically Collective
4803c5033834SJed Brown 
48044165533cSJose E. Roman    Input Parameter:
4805c5033834SJed Brown .  ts - time integration context
4806c5033834SJed Brown 
48074165533cSJose E. Roman    Output Parameters:
48080298fd71SBarry Smith +  atol - scalar absolute tolerances, NULL to ignore
48090298fd71SBarry Smith .  vatol - vector of absolute tolerances, NULL to ignore
48100298fd71SBarry Smith .  rtol - scalar relative tolerances, NULL to ignore
48110298fd71SBarry Smith -  vrtol - vector of relative tolerances, NULL to ignore
4812c5033834SJed Brown 
4813c5033834SJed Brown    Level: beginner
4814c5033834SJed Brown 
4815db781477SPatrick Sanan .seealso: `TS`, `TSAdapt`, `TSErrorWeightedNorm()`, `TSSetTolerances()`
4816c5033834SJed Brown @*/
4817*d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetTolerances(TS ts, PetscReal *atol, Vec *vatol, PetscReal *rtol, Vec *vrtol)
4818*d71ae5a4SJacob Faibussowitsch {
4819c5033834SJed Brown   PetscFunctionBegin;
4820c5033834SJed Brown   if (atol) *atol = ts->atol;
4821c5033834SJed Brown   if (vatol) *vatol = ts->vatol;
4822c5033834SJed Brown   if (rtol) *rtol = ts->rtol;
4823c5033834SJed Brown   if (vrtol) *vrtol = ts->vrtol;
4824c5033834SJed Brown   PetscFunctionReturn(0);
4825c5033834SJed Brown }
4826c5033834SJed Brown 
48279c6b16b5SShri Abhyankar /*@
4828a4868fbcSLisandro Dalcin    TSErrorWeightedNorm2 - compute a weighted 2-norm of the difference between two state vectors
48299c6b16b5SShri Abhyankar 
48309c6b16b5SShri Abhyankar    Collective on TS
48319c6b16b5SShri Abhyankar 
48324165533cSJose E. Roman    Input Parameters:
48339c6b16b5SShri Abhyankar +  ts - time stepping context
4834a4868fbcSLisandro Dalcin .  U - state vector, usually ts->vec_sol
4835a4868fbcSLisandro Dalcin -  Y - state vector to be compared to U
48369c6b16b5SShri Abhyankar 
48374165533cSJose E. Roman    Output Parameters:
4838a2b725a8SWilliam Gropp +  norm - weighted norm, a value of 1.0 means that the error matches the tolerances
48397453f775SEmil Constantinescu .  norma - weighted norm based on the absolute tolerance, a value of 1.0 means that the error matches the tolerances
4840a2b725a8SWilliam Gropp -  normr - weighted norm based on the relative tolerance, a value of 1.0 means that the error matches the tolerances
48419c6b16b5SShri Abhyankar 
48429c6b16b5SShri Abhyankar    Level: developer
48439c6b16b5SShri Abhyankar 
4844db781477SPatrick Sanan .seealso: `TSErrorWeightedNorm()`, `TSErrorWeightedNormInfinity()`
48459c6b16b5SShri Abhyankar @*/
4846*d71ae5a4SJacob Faibussowitsch PetscErrorCode TSErrorWeightedNorm2(TS ts, Vec U, Vec Y, PetscReal *norm, PetscReal *norma, PetscReal *normr)
4847*d71ae5a4SJacob Faibussowitsch {
48489c6b16b5SShri Abhyankar   PetscInt           i, n, N, rstart;
48497453f775SEmil Constantinescu   PetscInt           n_loc, na_loc, nr_loc;
48507453f775SEmil Constantinescu   PetscReal          n_glb, na_glb, nr_glb;
48519c6b16b5SShri Abhyankar   const PetscScalar *u, *y;
48527453f775SEmil Constantinescu   PetscReal          sum, suma, sumr, gsum, gsuma, gsumr, diff;
48537453f775SEmil Constantinescu   PetscReal          tol, tola, tolr;
48547453f775SEmil Constantinescu   PetscReal          err_loc[6], err_glb[6];
48559c6b16b5SShri Abhyankar 
48569c6b16b5SShri Abhyankar   PetscFunctionBegin;
48579c6b16b5SShri Abhyankar   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
4858a4868fbcSLisandro Dalcin   PetscValidHeaderSpecific(U, VEC_CLASSID, 2);
4859a4868fbcSLisandro Dalcin   PetscValidHeaderSpecific(Y, VEC_CLASSID, 3);
4860a4868fbcSLisandro Dalcin   PetscValidType(U, 2);
4861a4868fbcSLisandro Dalcin   PetscValidType(Y, 3);
4862a4868fbcSLisandro Dalcin   PetscCheckSameComm(U, 2, Y, 3);
4863dadcf809SJacob Faibussowitsch   PetscValidRealPointer(norm, 4);
4864dadcf809SJacob Faibussowitsch   PetscValidRealPointer(norma, 5);
4865dadcf809SJacob Faibussowitsch   PetscValidRealPointer(normr, 6);
48663c633725SBarry Smith   PetscCheck(U != Y, PetscObjectComm((PetscObject)U), PETSC_ERR_ARG_IDN, "U and Y cannot be the same vector");
48679c6b16b5SShri Abhyankar 
48689566063dSJacob Faibussowitsch   PetscCall(VecGetSize(U, &N));
48699566063dSJacob Faibussowitsch   PetscCall(VecGetLocalSize(U, &n));
48709566063dSJacob Faibussowitsch   PetscCall(VecGetOwnershipRange(U, &rstart, NULL));
48719566063dSJacob Faibussowitsch   PetscCall(VecGetArrayRead(U, &u));
48729566063dSJacob Faibussowitsch   PetscCall(VecGetArrayRead(Y, &y));
48739371c9d4SSatish Balay   sum    = 0.;
48749371c9d4SSatish Balay   n_loc  = 0;
48759371c9d4SSatish Balay   suma   = 0.;
48769371c9d4SSatish Balay   na_loc = 0;
48779371c9d4SSatish Balay   sumr   = 0.;
48789371c9d4SSatish Balay   nr_loc = 0;
48799c6b16b5SShri Abhyankar   if (ts->vatol && ts->vrtol) {
48809c6b16b5SShri Abhyankar     const PetscScalar *atol, *rtol;
48819566063dSJacob Faibussowitsch     PetscCall(VecGetArrayRead(ts->vatol, &atol));
48829566063dSJacob Faibussowitsch     PetscCall(VecGetArrayRead(ts->vrtol, &rtol));
48839c6b16b5SShri Abhyankar     for (i = 0; i < n; i++) {
488476cddca1SEmil Constantinescu       SkipSmallValue(y[i], u[i], ts->adapt->ignore_max);
48857453f775SEmil Constantinescu       diff = PetscAbsScalar(y[i] - u[i]);
48867453f775SEmil Constantinescu       tola = PetscRealPart(atol[i]);
48877453f775SEmil Constantinescu       if (tola > 0.) {
48887453f775SEmil Constantinescu         suma += PetscSqr(diff / tola);
48897453f775SEmil Constantinescu         na_loc++;
48907453f775SEmil Constantinescu       }
48917453f775SEmil Constantinescu       tolr = PetscRealPart(rtol[i]) * PetscMax(PetscAbsScalar(u[i]), PetscAbsScalar(y[i]));
48927453f775SEmil Constantinescu       if (tolr > 0.) {
48937453f775SEmil Constantinescu         sumr += PetscSqr(diff / tolr);
48947453f775SEmil Constantinescu         nr_loc++;
48957453f775SEmil Constantinescu       }
48967453f775SEmil Constantinescu       tol = tola + tolr;
48977453f775SEmil Constantinescu       if (tol > 0.) {
48987453f775SEmil Constantinescu         sum += PetscSqr(diff / tol);
48997453f775SEmil Constantinescu         n_loc++;
49007453f775SEmil Constantinescu       }
49019c6b16b5SShri Abhyankar     }
49029566063dSJacob Faibussowitsch     PetscCall(VecRestoreArrayRead(ts->vatol, &atol));
49039566063dSJacob Faibussowitsch     PetscCall(VecRestoreArrayRead(ts->vrtol, &rtol));
49049c6b16b5SShri Abhyankar   } else if (ts->vatol) { /* vector atol, scalar rtol */
49059c6b16b5SShri Abhyankar     const PetscScalar *atol;
49069566063dSJacob Faibussowitsch     PetscCall(VecGetArrayRead(ts->vatol, &atol));
49079c6b16b5SShri Abhyankar     for (i = 0; i < n; i++) {
490876cddca1SEmil Constantinescu       SkipSmallValue(y[i], u[i], ts->adapt->ignore_max);
49097453f775SEmil Constantinescu       diff = PetscAbsScalar(y[i] - u[i]);
49107453f775SEmil Constantinescu       tola = PetscRealPart(atol[i]);
49117453f775SEmil Constantinescu       if (tola > 0.) {
49127453f775SEmil Constantinescu         suma += PetscSqr(diff / tola);
49137453f775SEmil Constantinescu         na_loc++;
49147453f775SEmil Constantinescu       }
49157453f775SEmil Constantinescu       tolr = ts->rtol * PetscMax(PetscAbsScalar(u[i]), PetscAbsScalar(y[i]));
49167453f775SEmil Constantinescu       if (tolr > 0.) {
49177453f775SEmil Constantinescu         sumr += PetscSqr(diff / tolr);
49187453f775SEmil Constantinescu         nr_loc++;
49197453f775SEmil Constantinescu       }
49207453f775SEmil Constantinescu       tol = tola + tolr;
49217453f775SEmil Constantinescu       if (tol > 0.) {
49227453f775SEmil Constantinescu         sum += PetscSqr(diff / tol);
49237453f775SEmil Constantinescu         n_loc++;
49247453f775SEmil Constantinescu       }
49259c6b16b5SShri Abhyankar     }
49269566063dSJacob Faibussowitsch     PetscCall(VecRestoreArrayRead(ts->vatol, &atol));
49279c6b16b5SShri Abhyankar   } else if (ts->vrtol) { /* scalar atol, vector rtol */
49289c6b16b5SShri Abhyankar     const PetscScalar *rtol;
49299566063dSJacob Faibussowitsch     PetscCall(VecGetArrayRead(ts->vrtol, &rtol));
49309c6b16b5SShri Abhyankar     for (i = 0; i < n; i++) {
493176cddca1SEmil Constantinescu       SkipSmallValue(y[i], u[i], ts->adapt->ignore_max);
49327453f775SEmil Constantinescu       diff = PetscAbsScalar(y[i] - u[i]);
49337453f775SEmil Constantinescu       tola = ts->atol;
49347453f775SEmil Constantinescu       if (tola > 0.) {
49357453f775SEmil Constantinescu         suma += PetscSqr(diff / tola);
49367453f775SEmil Constantinescu         na_loc++;
49377453f775SEmil Constantinescu       }
49387453f775SEmil Constantinescu       tolr = PetscRealPart(rtol[i]) * PetscMax(PetscAbsScalar(u[i]), PetscAbsScalar(y[i]));
49397453f775SEmil Constantinescu       if (tolr > 0.) {
49407453f775SEmil Constantinescu         sumr += PetscSqr(diff / tolr);
49417453f775SEmil Constantinescu         nr_loc++;
49427453f775SEmil Constantinescu       }
49437453f775SEmil Constantinescu       tol = tola + tolr;
49447453f775SEmil Constantinescu       if (tol > 0.) {
49457453f775SEmil Constantinescu         sum += PetscSqr(diff / tol);
49467453f775SEmil Constantinescu         n_loc++;
49477453f775SEmil Constantinescu       }
49489c6b16b5SShri Abhyankar     }
49499566063dSJacob Faibussowitsch     PetscCall(VecRestoreArrayRead(ts->vrtol, &rtol));
49509c6b16b5SShri Abhyankar   } else { /* scalar atol, scalar rtol */
49519c6b16b5SShri Abhyankar     for (i = 0; i < n; i++) {
495276cddca1SEmil Constantinescu       SkipSmallValue(y[i], u[i], ts->adapt->ignore_max);
49537453f775SEmil Constantinescu       diff = PetscAbsScalar(y[i] - u[i]);
49547453f775SEmil Constantinescu       tola = ts->atol;
49557453f775SEmil Constantinescu       if (tola > 0.) {
49567453f775SEmil Constantinescu         suma += PetscSqr(diff / tola);
49577453f775SEmil Constantinescu         na_loc++;
49587453f775SEmil Constantinescu       }
49597453f775SEmil Constantinescu       tolr = ts->rtol * PetscMax(PetscAbsScalar(u[i]), PetscAbsScalar(y[i]));
49607453f775SEmil Constantinescu       if (tolr > 0.) {
49617453f775SEmil Constantinescu         sumr += PetscSqr(diff / tolr);
49627453f775SEmil Constantinescu         nr_loc++;
49637453f775SEmil Constantinescu       }
49647453f775SEmil Constantinescu       tol = tola + tolr;
49657453f775SEmil Constantinescu       if (tol > 0.) {
49667453f775SEmil Constantinescu         sum += PetscSqr(diff / tol);
49677453f775SEmil Constantinescu         n_loc++;
49687453f775SEmil Constantinescu       }
49699c6b16b5SShri Abhyankar     }
49709c6b16b5SShri Abhyankar   }
49719566063dSJacob Faibussowitsch   PetscCall(VecRestoreArrayRead(U, &u));
49729566063dSJacob Faibussowitsch   PetscCall(VecRestoreArrayRead(Y, &y));
49739c6b16b5SShri Abhyankar 
49747453f775SEmil Constantinescu   err_loc[0] = sum;
49757453f775SEmil Constantinescu   err_loc[1] = suma;
49767453f775SEmil Constantinescu   err_loc[2] = sumr;
49777453f775SEmil Constantinescu   err_loc[3] = (PetscReal)n_loc;
49787453f775SEmil Constantinescu   err_loc[4] = (PetscReal)na_loc;
49797453f775SEmil Constantinescu   err_loc[5] = (PetscReal)nr_loc;
49807453f775SEmil Constantinescu 
49811c2dc1cbSBarry Smith   PetscCall(MPIU_Allreduce(err_loc, err_glb, 6, MPIU_REAL, MPIU_SUM, PetscObjectComm((PetscObject)ts)));
49827453f775SEmil Constantinescu 
49837453f775SEmil Constantinescu   gsum   = err_glb[0];
49847453f775SEmil Constantinescu   gsuma  = err_glb[1];
49857453f775SEmil Constantinescu   gsumr  = err_glb[2];
49867453f775SEmil Constantinescu   n_glb  = err_glb[3];
49877453f775SEmil Constantinescu   na_glb = err_glb[4];
49887453f775SEmil Constantinescu   nr_glb = err_glb[5];
49897453f775SEmil Constantinescu 
4990b1316ef9SEmil Constantinescu   *norm = 0.;
49911e66621cSBarry Smith   if (n_glb > 0.) *norm = PetscSqrtReal(gsum / n_glb);
4992b1316ef9SEmil Constantinescu   *norma = 0.;
49931e66621cSBarry Smith   if (na_glb > 0.) *norma = PetscSqrtReal(gsuma / na_glb);
4994b1316ef9SEmil Constantinescu   *normr = 0.;
49951e66621cSBarry Smith   if (nr_glb > 0.) *normr = PetscSqrtReal(gsumr / nr_glb);
49969c6b16b5SShri Abhyankar 
49973c633725SBarry Smith   PetscCheck(!PetscIsInfOrNanScalar(*norm), PetscObjectComm((PetscObject)ts), PETSC_ERR_FP, "Infinite or not-a-number generated in norm");
49983c633725SBarry Smith   PetscCheck(!PetscIsInfOrNanScalar(*norma), PetscObjectComm((PetscObject)ts), PETSC_ERR_FP, "Infinite or not-a-number generated in norma");
49993c633725SBarry Smith   PetscCheck(!PetscIsInfOrNanScalar(*normr), PetscObjectComm((PetscObject)ts), PETSC_ERR_FP, "Infinite or not-a-number generated in normr");
50009c6b16b5SShri Abhyankar   PetscFunctionReturn(0);
50019c6b16b5SShri Abhyankar }
50029c6b16b5SShri Abhyankar 
50039c6b16b5SShri Abhyankar /*@
5004a4868fbcSLisandro Dalcin    TSErrorWeightedNormInfinity - compute a weighted infinity-norm of the difference between two state vectors
50059c6b16b5SShri Abhyankar 
50069c6b16b5SShri Abhyankar    Collective on TS
50079c6b16b5SShri Abhyankar 
50084165533cSJose E. Roman    Input Parameters:
50099c6b16b5SShri Abhyankar +  ts - time stepping context
5010a4868fbcSLisandro Dalcin .  U - state vector, usually ts->vec_sol
5011a4868fbcSLisandro Dalcin -  Y - state vector to be compared to U
50129c6b16b5SShri Abhyankar 
50134165533cSJose E. Roman    Output Parameters:
5014a2b725a8SWilliam Gropp +  norm - weighted norm, a value of 1.0 means that the error matches the tolerances
50157453f775SEmil Constantinescu .  norma - weighted norm based on the absolute tolerance, a value of 1.0 means that the error matches the tolerances
5016a2b725a8SWilliam Gropp -  normr - weighted norm based on the relative tolerance, a value of 1.0 means that the error matches the tolerances
50179c6b16b5SShri Abhyankar 
50189c6b16b5SShri Abhyankar    Level: developer
50199c6b16b5SShri Abhyankar 
5020db781477SPatrick Sanan .seealso: `TSErrorWeightedNorm()`, `TSErrorWeightedNorm2()`
50219c6b16b5SShri Abhyankar @*/
5022*d71ae5a4SJacob Faibussowitsch PetscErrorCode TSErrorWeightedNormInfinity(TS ts, Vec U, Vec Y, PetscReal *norm, PetscReal *norma, PetscReal *normr)
5023*d71ae5a4SJacob Faibussowitsch {
50247453f775SEmil Constantinescu   PetscInt           i, n, N, rstart;
50259c6b16b5SShri Abhyankar   const PetscScalar *u, *y;
50267453f775SEmil Constantinescu   PetscReal          max, gmax, maxa, gmaxa, maxr, gmaxr;
50277453f775SEmil Constantinescu   PetscReal          tol, tola, tolr, diff;
50287453f775SEmil Constantinescu   PetscReal          err_loc[3], err_glb[3];
50299c6b16b5SShri Abhyankar 
50309c6b16b5SShri Abhyankar   PetscFunctionBegin;
50319c6b16b5SShri Abhyankar   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
5032a4868fbcSLisandro Dalcin   PetscValidHeaderSpecific(U, VEC_CLASSID, 2);
5033a4868fbcSLisandro Dalcin   PetscValidHeaderSpecific(Y, VEC_CLASSID, 3);
5034a4868fbcSLisandro Dalcin   PetscValidType(U, 2);
5035a4868fbcSLisandro Dalcin   PetscValidType(Y, 3);
5036a4868fbcSLisandro Dalcin   PetscCheckSameComm(U, 2, Y, 3);
5037dadcf809SJacob Faibussowitsch   PetscValidRealPointer(norm, 4);
5038dadcf809SJacob Faibussowitsch   PetscValidRealPointer(norma, 5);
5039dadcf809SJacob Faibussowitsch   PetscValidRealPointer(normr, 6);
50403c633725SBarry Smith   PetscCheck(U != Y, PetscObjectComm((PetscObject)U), PETSC_ERR_ARG_IDN, "U and Y cannot be the same vector");
50419c6b16b5SShri Abhyankar 
50429566063dSJacob Faibussowitsch   PetscCall(VecGetSize(U, &N));
50439566063dSJacob Faibussowitsch   PetscCall(VecGetLocalSize(U, &n));
50449566063dSJacob Faibussowitsch   PetscCall(VecGetOwnershipRange(U, &rstart, NULL));
50459566063dSJacob Faibussowitsch   PetscCall(VecGetArrayRead(U, &u));
50469566063dSJacob Faibussowitsch   PetscCall(VecGetArrayRead(Y, &y));
50477453f775SEmil Constantinescu 
50487453f775SEmil Constantinescu   max  = 0.;
50497453f775SEmil Constantinescu   maxa = 0.;
50507453f775SEmil Constantinescu   maxr = 0.;
50517453f775SEmil Constantinescu 
50527453f775SEmil Constantinescu   if (ts->vatol && ts->vrtol) { /* vector atol, vector rtol */
50539c6b16b5SShri Abhyankar     const PetscScalar *atol, *rtol;
50549566063dSJacob Faibussowitsch     PetscCall(VecGetArrayRead(ts->vatol, &atol));
50559566063dSJacob Faibussowitsch     PetscCall(VecGetArrayRead(ts->vrtol, &rtol));
50567453f775SEmil Constantinescu 
50577453f775SEmil Constantinescu     for (i = 0; i < n; i++) {
505876cddca1SEmil Constantinescu       SkipSmallValue(y[i], u[i], ts->adapt->ignore_max);
50597453f775SEmil Constantinescu       diff = PetscAbsScalar(y[i] - u[i]);
50607453f775SEmil Constantinescu       tola = PetscRealPart(atol[i]);
50617453f775SEmil Constantinescu       tolr = PetscRealPart(rtol[i]) * PetscMax(PetscAbsScalar(u[i]), PetscAbsScalar(y[i]));
50627453f775SEmil Constantinescu       tol  = tola + tolr;
50631e66621cSBarry Smith       if (tola > 0.) maxa = PetscMax(maxa, diff / tola);
50641e66621cSBarry Smith       if (tolr > 0.) maxr = PetscMax(maxr, diff / tolr);
50651e66621cSBarry Smith       if (tol > 0.) max = PetscMax(max, diff / tol);
50669c6b16b5SShri Abhyankar     }
50679566063dSJacob Faibussowitsch     PetscCall(VecRestoreArrayRead(ts->vatol, &atol));
50689566063dSJacob Faibussowitsch     PetscCall(VecRestoreArrayRead(ts->vrtol, &rtol));
50699c6b16b5SShri Abhyankar   } else if (ts->vatol) { /* vector atol, scalar rtol */
50709c6b16b5SShri Abhyankar     const PetscScalar *atol;
50719566063dSJacob Faibussowitsch     PetscCall(VecGetArrayRead(ts->vatol, &atol));
50727453f775SEmil Constantinescu     for (i = 0; i < n; i++) {
507376cddca1SEmil Constantinescu       SkipSmallValue(y[i], u[i], ts->adapt->ignore_max);
50747453f775SEmil Constantinescu       diff = PetscAbsScalar(y[i] - u[i]);
50757453f775SEmil Constantinescu       tola = PetscRealPart(atol[i]);
50767453f775SEmil Constantinescu       tolr = ts->rtol * PetscMax(PetscAbsScalar(u[i]), PetscAbsScalar(y[i]));
50777453f775SEmil Constantinescu       tol  = tola + tolr;
50781e66621cSBarry Smith       if (tola > 0.) maxa = PetscMax(maxa, diff / tola);
50791e66621cSBarry Smith       if (tolr > 0.) maxr = PetscMax(maxr, diff / tolr);
50801e66621cSBarry Smith       if (tol > 0.) max = PetscMax(max, diff / tol);
50819c6b16b5SShri Abhyankar     }
50829566063dSJacob Faibussowitsch     PetscCall(VecRestoreArrayRead(ts->vatol, &atol));
50839c6b16b5SShri Abhyankar   } else if (ts->vrtol) { /* scalar atol, vector rtol */
50849c6b16b5SShri Abhyankar     const PetscScalar *rtol;
50859566063dSJacob Faibussowitsch     PetscCall(VecGetArrayRead(ts->vrtol, &rtol));
50867453f775SEmil Constantinescu 
50877453f775SEmil Constantinescu     for (i = 0; i < n; i++) {
508876cddca1SEmil Constantinescu       SkipSmallValue(y[i], u[i], ts->adapt->ignore_max);
50897453f775SEmil Constantinescu       diff = PetscAbsScalar(y[i] - u[i]);
50907453f775SEmil Constantinescu       tola = ts->atol;
50917453f775SEmil Constantinescu       tolr = PetscRealPart(rtol[i]) * PetscMax(PetscAbsScalar(u[i]), PetscAbsScalar(y[i]));
50927453f775SEmil Constantinescu       tol  = tola + tolr;
50931e66621cSBarry Smith       if (tola > 0.) maxa = PetscMax(maxa, diff / tola);
50941e66621cSBarry Smith       if (tolr > 0.) maxr = PetscMax(maxr, diff / tolr);
50951e66621cSBarry Smith       if (tol > 0.) max = PetscMax(max, diff / tol);
50969c6b16b5SShri Abhyankar     }
50979566063dSJacob Faibussowitsch     PetscCall(VecRestoreArrayRead(ts->vrtol, &rtol));
50989c6b16b5SShri Abhyankar   } else { /* scalar atol, scalar rtol */
50997453f775SEmil Constantinescu 
51007453f775SEmil Constantinescu     for (i = 0; i < n; i++) {
510176cddca1SEmil Constantinescu       SkipSmallValue(y[i], u[i], ts->adapt->ignore_max);
51027453f775SEmil Constantinescu       diff = PetscAbsScalar(y[i] - u[i]);
51037453f775SEmil Constantinescu       tola = ts->atol;
51047453f775SEmil Constantinescu       tolr = ts->rtol * PetscMax(PetscAbsScalar(u[i]), PetscAbsScalar(y[i]));
51057453f775SEmil Constantinescu       tol  = tola + tolr;
51061e66621cSBarry Smith       if (tola > 0.) maxa = PetscMax(maxa, diff / tola);
51071e66621cSBarry Smith       if (tolr > 0.) maxr = PetscMax(maxr, diff / tolr);
51081e66621cSBarry Smith       if (tol > 0.) max = PetscMax(max, diff / tol);
51099c6b16b5SShri Abhyankar     }
51109c6b16b5SShri Abhyankar   }
51119566063dSJacob Faibussowitsch   PetscCall(VecRestoreArrayRead(U, &u));
51129566063dSJacob Faibussowitsch   PetscCall(VecRestoreArrayRead(Y, &y));
51137453f775SEmil Constantinescu   err_loc[0] = max;
51147453f775SEmil Constantinescu   err_loc[1] = maxa;
51157453f775SEmil Constantinescu   err_loc[2] = maxr;
51161c2dc1cbSBarry Smith   PetscCall(MPIU_Allreduce(err_loc, err_glb, 3, MPIU_REAL, MPIU_MAX, PetscObjectComm((PetscObject)ts)));
51177453f775SEmil Constantinescu   gmax  = err_glb[0];
51187453f775SEmil Constantinescu   gmaxa = err_glb[1];
51197453f775SEmil Constantinescu   gmaxr = err_glb[2];
51209c6b16b5SShri Abhyankar 
51219c6b16b5SShri Abhyankar   *norm  = gmax;
51227453f775SEmil Constantinescu   *norma = gmaxa;
51237453f775SEmil Constantinescu   *normr = gmaxr;
51243c633725SBarry Smith   PetscCheck(!PetscIsInfOrNanScalar(*norm), PetscObjectComm((PetscObject)ts), PETSC_ERR_FP, "Infinite or not-a-number generated in norm");
51253c633725SBarry Smith   PetscCheck(!PetscIsInfOrNanScalar(*norma), PetscObjectComm((PetscObject)ts), PETSC_ERR_FP, "Infinite or not-a-number generated in norma");
51263c633725SBarry Smith   PetscCheck(!PetscIsInfOrNanScalar(*normr), PetscObjectComm((PetscObject)ts), PETSC_ERR_FP, "Infinite or not-a-number generated in normr");
51279c6b16b5SShri Abhyankar   PetscFunctionReturn(0);
51289c6b16b5SShri Abhyankar }
51299c6b16b5SShri Abhyankar 
51301c3436cfSJed Brown /*@
51318a175baeSEmil Constantinescu    TSErrorWeightedNorm - compute a weighted norm of the difference between two state vectors based on supplied absolute and relative tolerances
51321c3436cfSJed Brown 
51331c3436cfSJed Brown    Collective on TS
51341c3436cfSJed Brown 
51354165533cSJose E. Roman    Input Parameters:
51361c3436cfSJed Brown +  ts - time stepping context
5137a4868fbcSLisandro Dalcin .  U - state vector, usually ts->vec_sol
5138a4868fbcSLisandro Dalcin .  Y - state vector to be compared to U
5139a4868fbcSLisandro Dalcin -  wnormtype - norm type, either NORM_2 or NORM_INFINITY
51407619abb3SShri 
51414165533cSJose E. Roman    Output Parameters:
5142a2b725a8SWilliam Gropp +  norm  - weighted norm, a value of 1.0 achieves a balance between absolute and relative tolerances
51438a175baeSEmil Constantinescu .  norma - weighted norm, a value of 1.0 means that the error meets the absolute tolerance set by the user
5144a2b725a8SWilliam Gropp -  normr - weighted norm, a value of 1.0 means that the error meets the relative tolerance set by the user
5145a4868fbcSLisandro Dalcin 
5146a4868fbcSLisandro Dalcin    Options Database Keys:
5147a4868fbcSLisandro Dalcin .  -ts_adapt_wnormtype <wnormtype> - 2, INFINITY
5148a4868fbcSLisandro Dalcin 
51491c3436cfSJed Brown    Level: developer
51501c3436cfSJed Brown 
5151db781477SPatrick Sanan .seealso: `TSErrorWeightedNormInfinity()`, `TSErrorWeightedNorm2()`, `TSErrorWeightedENorm`
51521c3436cfSJed Brown @*/
5153*d71ae5a4SJacob Faibussowitsch PetscErrorCode TSErrorWeightedNorm(TS ts, Vec U, Vec Y, NormType wnormtype, PetscReal *norm, PetscReal *norma, PetscReal *normr)
5154*d71ae5a4SJacob Faibussowitsch {
51551c3436cfSJed Brown   PetscFunctionBegin;
51561e66621cSBarry Smith   if (wnormtype == NORM_2) PetscCall(TSErrorWeightedNorm2(ts, U, Y, norm, norma, normr));
51571e66621cSBarry Smith   else if (wnormtype == NORM_INFINITY) PetscCall(TSErrorWeightedNormInfinity(ts, U, Y, norm, norma, normr));
51581e66621cSBarry Smith   else SETERRQ(PETSC_COMM_SELF, PETSC_ERR_SUP, "No support for norm type %s", NormTypes[wnormtype]);
51591c3436cfSJed Brown   PetscFunctionReturn(0);
51601c3436cfSJed Brown }
51611c3436cfSJed Brown 
51628a175baeSEmil Constantinescu /*@
51638a175baeSEmil Constantinescu    TSErrorWeightedENorm2 - compute a weighted 2 error norm based on supplied absolute and relative tolerances
51648a175baeSEmil Constantinescu 
51658a175baeSEmil Constantinescu    Collective on TS
51668a175baeSEmil Constantinescu 
51674165533cSJose E. Roman    Input Parameters:
51688a175baeSEmil Constantinescu +  ts - time stepping context
51698a175baeSEmil Constantinescu .  E - error vector
51708a175baeSEmil Constantinescu .  U - state vector, usually ts->vec_sol
51718a175baeSEmil Constantinescu -  Y - state vector, previous time step
51728a175baeSEmil Constantinescu 
51734165533cSJose E. Roman    Output Parameters:
5174a2b725a8SWilliam Gropp +  norm - weighted norm, a value of 1.0 means that the error matches the tolerances
51758a175baeSEmil Constantinescu .  norma - weighted norm based on the absolute tolerance, a value of 1.0 means that the error matches the tolerances
5176a2b725a8SWilliam Gropp -  normr - weighted norm based on the relative tolerance, a value of 1.0 means that the error matches the tolerances
51778a175baeSEmil Constantinescu 
51788a175baeSEmil Constantinescu    Level: developer
51798a175baeSEmil Constantinescu 
5180db781477SPatrick Sanan .seealso: `TSErrorWeightedENorm()`, `TSErrorWeightedENormInfinity()`
51818a175baeSEmil Constantinescu @*/
5182*d71ae5a4SJacob Faibussowitsch PetscErrorCode TSErrorWeightedENorm2(TS ts, Vec E, Vec U, Vec Y, PetscReal *norm, PetscReal *norma, PetscReal *normr)
5183*d71ae5a4SJacob Faibussowitsch {
51848a175baeSEmil Constantinescu   PetscInt           i, n, N, rstart;
51858a175baeSEmil Constantinescu   PetscInt           n_loc, na_loc, nr_loc;
51868a175baeSEmil Constantinescu   PetscReal          n_glb, na_glb, nr_glb;
51878a175baeSEmil Constantinescu   const PetscScalar *e, *u, *y;
51888a175baeSEmil Constantinescu   PetscReal          err, sum, suma, sumr, gsum, gsuma, gsumr;
51898a175baeSEmil Constantinescu   PetscReal          tol, tola, tolr;
51908a175baeSEmil Constantinescu   PetscReal          err_loc[6], err_glb[6];
51918a175baeSEmil Constantinescu 
51928a175baeSEmil Constantinescu   PetscFunctionBegin;
51938a175baeSEmil Constantinescu   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
51948a175baeSEmil Constantinescu   PetscValidHeaderSpecific(E, VEC_CLASSID, 2);
51958a175baeSEmil Constantinescu   PetscValidHeaderSpecific(U, VEC_CLASSID, 3);
51968a175baeSEmil Constantinescu   PetscValidHeaderSpecific(Y, VEC_CLASSID, 4);
51978a175baeSEmil Constantinescu   PetscValidType(E, 2);
51988a175baeSEmil Constantinescu   PetscValidType(U, 3);
51998a175baeSEmil Constantinescu   PetscValidType(Y, 4);
52008a175baeSEmil Constantinescu   PetscCheckSameComm(E, 2, U, 3);
5201064a246eSJacob Faibussowitsch   PetscCheckSameComm(U, 3, Y, 4);
5202dadcf809SJacob Faibussowitsch   PetscValidRealPointer(norm, 5);
5203dadcf809SJacob Faibussowitsch   PetscValidRealPointer(norma, 6);
5204dadcf809SJacob Faibussowitsch   PetscValidRealPointer(normr, 7);
52058a175baeSEmil Constantinescu 
52069566063dSJacob Faibussowitsch   PetscCall(VecGetSize(E, &N));
52079566063dSJacob Faibussowitsch   PetscCall(VecGetLocalSize(E, &n));
52089566063dSJacob Faibussowitsch   PetscCall(VecGetOwnershipRange(E, &rstart, NULL));
52099566063dSJacob Faibussowitsch   PetscCall(VecGetArrayRead(E, &e));
52109566063dSJacob Faibussowitsch   PetscCall(VecGetArrayRead(U, &u));
52119566063dSJacob Faibussowitsch   PetscCall(VecGetArrayRead(Y, &y));
52129371c9d4SSatish Balay   sum    = 0.;
52139371c9d4SSatish Balay   n_loc  = 0;
52149371c9d4SSatish Balay   suma   = 0.;
52159371c9d4SSatish Balay   na_loc = 0;
52169371c9d4SSatish Balay   sumr   = 0.;
52179371c9d4SSatish Balay   nr_loc = 0;
52188a175baeSEmil Constantinescu   if (ts->vatol && ts->vrtol) {
52198a175baeSEmil Constantinescu     const PetscScalar *atol, *rtol;
52209566063dSJacob Faibussowitsch     PetscCall(VecGetArrayRead(ts->vatol, &atol));
52219566063dSJacob Faibussowitsch     PetscCall(VecGetArrayRead(ts->vrtol, &rtol));
52228a175baeSEmil Constantinescu     for (i = 0; i < n; i++) {
522376cddca1SEmil Constantinescu       SkipSmallValue(y[i], u[i], ts->adapt->ignore_max);
52248a175baeSEmil Constantinescu       err  = PetscAbsScalar(e[i]);
52258a175baeSEmil Constantinescu       tola = PetscRealPart(atol[i]);
52268a175baeSEmil Constantinescu       if (tola > 0.) {
52278a175baeSEmil Constantinescu         suma += PetscSqr(err / tola);
52288a175baeSEmil Constantinescu         na_loc++;
52298a175baeSEmil Constantinescu       }
52308a175baeSEmil Constantinescu       tolr = PetscRealPart(rtol[i]) * PetscMax(PetscAbsScalar(u[i]), PetscAbsScalar(y[i]));
52318a175baeSEmil Constantinescu       if (tolr > 0.) {
52328a175baeSEmil Constantinescu         sumr += PetscSqr(err / tolr);
52338a175baeSEmil Constantinescu         nr_loc++;
52348a175baeSEmil Constantinescu       }
52358a175baeSEmil Constantinescu       tol = tola + tolr;
52368a175baeSEmil Constantinescu       if (tol > 0.) {
52378a175baeSEmil Constantinescu         sum += PetscSqr(err / tol);
52388a175baeSEmil Constantinescu         n_loc++;
52398a175baeSEmil Constantinescu       }
52408a175baeSEmil Constantinescu     }
52419566063dSJacob Faibussowitsch     PetscCall(VecRestoreArrayRead(ts->vatol, &atol));
52429566063dSJacob Faibussowitsch     PetscCall(VecRestoreArrayRead(ts->vrtol, &rtol));
52438a175baeSEmil Constantinescu   } else if (ts->vatol) { /* vector atol, scalar rtol */
52448a175baeSEmil Constantinescu     const PetscScalar *atol;
52459566063dSJacob Faibussowitsch     PetscCall(VecGetArrayRead(ts->vatol, &atol));
52468a175baeSEmil Constantinescu     for (i = 0; i < n; i++) {
524776cddca1SEmil Constantinescu       SkipSmallValue(y[i], u[i], ts->adapt->ignore_max);
52488a175baeSEmil Constantinescu       err  = PetscAbsScalar(e[i]);
52498a175baeSEmil Constantinescu       tola = PetscRealPart(atol[i]);
52508a175baeSEmil Constantinescu       if (tola > 0.) {
52518a175baeSEmil Constantinescu         suma += PetscSqr(err / tola);
52528a175baeSEmil Constantinescu         na_loc++;
52538a175baeSEmil Constantinescu       }
52548a175baeSEmil Constantinescu       tolr = ts->rtol * PetscMax(PetscAbsScalar(u[i]), PetscAbsScalar(y[i]));
52558a175baeSEmil Constantinescu       if (tolr > 0.) {
52568a175baeSEmil Constantinescu         sumr += PetscSqr(err / tolr);
52578a175baeSEmil Constantinescu         nr_loc++;
52588a175baeSEmil Constantinescu       }
52598a175baeSEmil Constantinescu       tol = tola + tolr;
52608a175baeSEmil Constantinescu       if (tol > 0.) {
52618a175baeSEmil Constantinescu         sum += PetscSqr(err / tol);
52628a175baeSEmil Constantinescu         n_loc++;
52638a175baeSEmil Constantinescu       }
52648a175baeSEmil Constantinescu     }
52659566063dSJacob Faibussowitsch     PetscCall(VecRestoreArrayRead(ts->vatol, &atol));
52668a175baeSEmil Constantinescu   } else if (ts->vrtol) { /* scalar atol, vector rtol */
52678a175baeSEmil Constantinescu     const PetscScalar *rtol;
52689566063dSJacob Faibussowitsch     PetscCall(VecGetArrayRead(ts->vrtol, &rtol));
52698a175baeSEmil Constantinescu     for (i = 0; i < n; i++) {
527076cddca1SEmil Constantinescu       SkipSmallValue(y[i], u[i], ts->adapt->ignore_max);
52718a175baeSEmil Constantinescu       err  = PetscAbsScalar(e[i]);
52728a175baeSEmil Constantinescu       tola = ts->atol;
52738a175baeSEmil Constantinescu       if (tola > 0.) {
52748a175baeSEmil Constantinescu         suma += PetscSqr(err / tola);
52758a175baeSEmil Constantinescu         na_loc++;
52768a175baeSEmil Constantinescu       }
52778a175baeSEmil Constantinescu       tolr = PetscRealPart(rtol[i]) * PetscMax(PetscAbsScalar(u[i]), PetscAbsScalar(y[i]));
52788a175baeSEmil Constantinescu       if (tolr > 0.) {
52798a175baeSEmil Constantinescu         sumr += PetscSqr(err / tolr);
52808a175baeSEmil Constantinescu         nr_loc++;
52818a175baeSEmil Constantinescu       }
52828a175baeSEmil Constantinescu       tol = tola + tolr;
52838a175baeSEmil Constantinescu       if (tol > 0.) {
52848a175baeSEmil Constantinescu         sum += PetscSqr(err / tol);
52858a175baeSEmil Constantinescu         n_loc++;
52868a175baeSEmil Constantinescu       }
52878a175baeSEmil Constantinescu     }
52889566063dSJacob Faibussowitsch     PetscCall(VecRestoreArrayRead(ts->vrtol, &rtol));
52898a175baeSEmil Constantinescu   } else { /* scalar atol, scalar rtol */
52908a175baeSEmil Constantinescu     for (i = 0; i < n; i++) {
529176cddca1SEmil Constantinescu       SkipSmallValue(y[i], u[i], ts->adapt->ignore_max);
52928a175baeSEmil Constantinescu       err  = PetscAbsScalar(e[i]);
52938a175baeSEmil Constantinescu       tola = ts->atol;
52948a175baeSEmil Constantinescu       if (tola > 0.) {
52958a175baeSEmil Constantinescu         suma += PetscSqr(err / tola);
52968a175baeSEmil Constantinescu         na_loc++;
52978a175baeSEmil Constantinescu       }
52988a175baeSEmil Constantinescu       tolr = ts->rtol * PetscMax(PetscAbsScalar(u[i]), PetscAbsScalar(y[i]));
52998a175baeSEmil Constantinescu       if (tolr > 0.) {
53008a175baeSEmil Constantinescu         sumr += PetscSqr(err / tolr);
53018a175baeSEmil Constantinescu         nr_loc++;
53028a175baeSEmil Constantinescu       }
53038a175baeSEmil Constantinescu       tol = tola + tolr;
53048a175baeSEmil Constantinescu       if (tol > 0.) {
53058a175baeSEmil Constantinescu         sum += PetscSqr(err / tol);
53068a175baeSEmil Constantinescu         n_loc++;
53078a175baeSEmil Constantinescu       }
53088a175baeSEmil Constantinescu     }
53098a175baeSEmil Constantinescu   }
53109566063dSJacob Faibussowitsch   PetscCall(VecRestoreArrayRead(E, &e));
53119566063dSJacob Faibussowitsch   PetscCall(VecRestoreArrayRead(U, &u));
53129566063dSJacob Faibussowitsch   PetscCall(VecRestoreArrayRead(Y, &y));
53138a175baeSEmil Constantinescu 
53148a175baeSEmil Constantinescu   err_loc[0] = sum;
53158a175baeSEmil Constantinescu   err_loc[1] = suma;
53168a175baeSEmil Constantinescu   err_loc[2] = sumr;
53178a175baeSEmil Constantinescu   err_loc[3] = (PetscReal)n_loc;
53188a175baeSEmil Constantinescu   err_loc[4] = (PetscReal)na_loc;
53198a175baeSEmil Constantinescu   err_loc[5] = (PetscReal)nr_loc;
53208a175baeSEmil Constantinescu 
53211c2dc1cbSBarry Smith   PetscCall(MPIU_Allreduce(err_loc, err_glb, 6, MPIU_REAL, MPIU_SUM, PetscObjectComm((PetscObject)ts)));
53228a175baeSEmil Constantinescu 
53238a175baeSEmil Constantinescu   gsum   = err_glb[0];
53248a175baeSEmil Constantinescu   gsuma  = err_glb[1];
53258a175baeSEmil Constantinescu   gsumr  = err_glb[2];
53268a175baeSEmil Constantinescu   n_glb  = err_glb[3];
53278a175baeSEmil Constantinescu   na_glb = err_glb[4];
53288a175baeSEmil Constantinescu   nr_glb = err_glb[5];
53298a175baeSEmil Constantinescu 
53308a175baeSEmil Constantinescu   *norm = 0.;
53311e66621cSBarry Smith   if (n_glb > 0.) *norm = PetscSqrtReal(gsum / n_glb);
53328a175baeSEmil Constantinescu   *norma = 0.;
53331e66621cSBarry Smith   if (na_glb > 0.) *norma = PetscSqrtReal(gsuma / na_glb);
53348a175baeSEmil Constantinescu   *normr = 0.;
53351e66621cSBarry Smith   if (nr_glb > 0.) *normr = PetscSqrtReal(gsumr / nr_glb);
53368a175baeSEmil Constantinescu 
53373c633725SBarry Smith   PetscCheck(!PetscIsInfOrNanScalar(*norm), PetscObjectComm((PetscObject)ts), PETSC_ERR_FP, "Infinite or not-a-number generated in norm");
53383c633725SBarry Smith   PetscCheck(!PetscIsInfOrNanScalar(*norma), PetscObjectComm((PetscObject)ts), PETSC_ERR_FP, "Infinite or not-a-number generated in norma");
53393c633725SBarry Smith   PetscCheck(!PetscIsInfOrNanScalar(*normr), PetscObjectComm((PetscObject)ts), PETSC_ERR_FP, "Infinite or not-a-number generated in normr");
53408a175baeSEmil Constantinescu   PetscFunctionReturn(0);
53418a175baeSEmil Constantinescu }
53428a175baeSEmil Constantinescu 
53438a175baeSEmil Constantinescu /*@
53448a175baeSEmil Constantinescu    TSErrorWeightedENormInfinity - compute a weighted infinity error norm based on supplied absolute and relative tolerances
53458a175baeSEmil Constantinescu    Collective on TS
53468a175baeSEmil Constantinescu 
53474165533cSJose E. Roman    Input Parameters:
53488a175baeSEmil Constantinescu +  ts - time stepping context
53498a175baeSEmil Constantinescu .  E - error vector
53508a175baeSEmil Constantinescu .  U - state vector, usually ts->vec_sol
53518a175baeSEmil Constantinescu -  Y - state vector, previous time step
53528a175baeSEmil Constantinescu 
53534165533cSJose E. Roman    Output Parameters:
5354a2b725a8SWilliam Gropp +  norm - weighted norm, a value of 1.0 means that the error matches the tolerances
53558a175baeSEmil Constantinescu .  norma - weighted norm based on the absolute tolerance, a value of 1.0 means that the error matches the tolerances
5356a2b725a8SWilliam Gropp -  normr - weighted norm based on the relative tolerance, a value of 1.0 means that the error matches the tolerances
53578a175baeSEmil Constantinescu 
53588a175baeSEmil Constantinescu    Level: developer
53598a175baeSEmil Constantinescu 
5360db781477SPatrick Sanan .seealso: `TSErrorWeightedENorm()`, `TSErrorWeightedENorm2()`
53618a175baeSEmil Constantinescu @*/
5362*d71ae5a4SJacob Faibussowitsch PetscErrorCode TSErrorWeightedENormInfinity(TS ts, Vec E, Vec U, Vec Y, PetscReal *norm, PetscReal *norma, PetscReal *normr)
5363*d71ae5a4SJacob Faibussowitsch {
53648a175baeSEmil Constantinescu   PetscInt           i, n, N, rstart;
53658a175baeSEmil Constantinescu   const PetscScalar *e, *u, *y;
53668a175baeSEmil Constantinescu   PetscReal          err, max, gmax, maxa, gmaxa, maxr, gmaxr;
53678a175baeSEmil Constantinescu   PetscReal          tol, tola, tolr;
53688a175baeSEmil Constantinescu   PetscReal          err_loc[3], err_glb[3];
53698a175baeSEmil Constantinescu 
53708a175baeSEmil Constantinescu   PetscFunctionBegin;
53718a175baeSEmil Constantinescu   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
53728a175baeSEmil Constantinescu   PetscValidHeaderSpecific(E, VEC_CLASSID, 2);
53738a175baeSEmil Constantinescu   PetscValidHeaderSpecific(U, VEC_CLASSID, 3);
53748a175baeSEmil Constantinescu   PetscValidHeaderSpecific(Y, VEC_CLASSID, 4);
53758a175baeSEmil Constantinescu   PetscValidType(E, 2);
53768a175baeSEmil Constantinescu   PetscValidType(U, 3);
53778a175baeSEmil Constantinescu   PetscValidType(Y, 4);
53788a175baeSEmil Constantinescu   PetscCheckSameComm(E, 2, U, 3);
5379064a246eSJacob Faibussowitsch   PetscCheckSameComm(U, 3, Y, 4);
5380dadcf809SJacob Faibussowitsch   PetscValidRealPointer(norm, 5);
5381dadcf809SJacob Faibussowitsch   PetscValidRealPointer(norma, 6);
5382dadcf809SJacob Faibussowitsch   PetscValidRealPointer(normr, 7);
53838a175baeSEmil Constantinescu 
53849566063dSJacob Faibussowitsch   PetscCall(VecGetSize(E, &N));
53859566063dSJacob Faibussowitsch   PetscCall(VecGetLocalSize(E, &n));
53869566063dSJacob Faibussowitsch   PetscCall(VecGetOwnershipRange(E, &rstart, NULL));
53879566063dSJacob Faibussowitsch   PetscCall(VecGetArrayRead(E, &e));
53889566063dSJacob Faibussowitsch   PetscCall(VecGetArrayRead(U, &u));
53899566063dSJacob Faibussowitsch   PetscCall(VecGetArrayRead(Y, &y));
53908a175baeSEmil Constantinescu 
53918a175baeSEmil Constantinescu   max  = 0.;
53928a175baeSEmil Constantinescu   maxa = 0.;
53938a175baeSEmil Constantinescu   maxr = 0.;
53948a175baeSEmil Constantinescu 
53958a175baeSEmil Constantinescu   if (ts->vatol && ts->vrtol) { /* vector atol, vector rtol */
53968a175baeSEmil Constantinescu     const PetscScalar *atol, *rtol;
53979566063dSJacob Faibussowitsch     PetscCall(VecGetArrayRead(ts->vatol, &atol));
53989566063dSJacob Faibussowitsch     PetscCall(VecGetArrayRead(ts->vrtol, &rtol));
53998a175baeSEmil Constantinescu 
54008a175baeSEmil Constantinescu     for (i = 0; i < n; i++) {
540176cddca1SEmil Constantinescu       SkipSmallValue(y[i], u[i], ts->adapt->ignore_max);
54028a175baeSEmil Constantinescu       err  = PetscAbsScalar(e[i]);
54038a175baeSEmil Constantinescu       tola = PetscRealPart(atol[i]);
54048a175baeSEmil Constantinescu       tolr = PetscRealPart(rtol[i]) * PetscMax(PetscAbsScalar(u[i]), PetscAbsScalar(y[i]));
54058a175baeSEmil Constantinescu       tol  = tola + tolr;
54061e66621cSBarry Smith       if (tola > 0.) maxa = PetscMax(maxa, err / tola);
54071e66621cSBarry Smith       if (tolr > 0.) maxr = PetscMax(maxr, err / tolr);
54081e66621cSBarry Smith       if (tol > 0.) max = PetscMax(max, err / tol);
54098a175baeSEmil Constantinescu     }
54109566063dSJacob Faibussowitsch     PetscCall(VecRestoreArrayRead(ts->vatol, &atol));
54119566063dSJacob Faibussowitsch     PetscCall(VecRestoreArrayRead(ts->vrtol, &rtol));
54128a175baeSEmil Constantinescu   } else if (ts->vatol) { /* vector atol, scalar rtol */
54138a175baeSEmil Constantinescu     const PetscScalar *atol;
54149566063dSJacob Faibussowitsch     PetscCall(VecGetArrayRead(ts->vatol, &atol));
54158a175baeSEmil Constantinescu     for (i = 0; i < n; i++) {
541676cddca1SEmil Constantinescu       SkipSmallValue(y[i], u[i], ts->adapt->ignore_max);
54178a175baeSEmil Constantinescu       err  = PetscAbsScalar(e[i]);
54188a175baeSEmil Constantinescu       tola = PetscRealPart(atol[i]);
54198a175baeSEmil Constantinescu       tolr = ts->rtol * PetscMax(PetscAbsScalar(u[i]), PetscAbsScalar(y[i]));
54208a175baeSEmil Constantinescu       tol  = tola + tolr;
54211e66621cSBarry Smith       if (tola > 0.) maxa = PetscMax(maxa, err / tola);
54221e66621cSBarry Smith       if (tolr > 0.) maxr = PetscMax(maxr, err / tolr);
54231e66621cSBarry Smith       if (tol > 0.) max = PetscMax(max, err / tol);
54248a175baeSEmil Constantinescu     }
54259566063dSJacob Faibussowitsch     PetscCall(VecRestoreArrayRead(ts->vatol, &atol));
54268a175baeSEmil Constantinescu   } else if (ts->vrtol) { /* scalar atol, vector rtol */
54278a175baeSEmil Constantinescu     const PetscScalar *rtol;
54289566063dSJacob Faibussowitsch     PetscCall(VecGetArrayRead(ts->vrtol, &rtol));
54298a175baeSEmil Constantinescu 
54308a175baeSEmil Constantinescu     for (i = 0; i < n; i++) {
543176cddca1SEmil Constantinescu       SkipSmallValue(y[i], u[i], ts->adapt->ignore_max);
54328a175baeSEmil Constantinescu       err  = PetscAbsScalar(e[i]);
54338a175baeSEmil Constantinescu       tola = ts->atol;
54348a175baeSEmil Constantinescu       tolr = PetscRealPart(rtol[i]) * PetscMax(PetscAbsScalar(u[i]), PetscAbsScalar(y[i]));
54358a175baeSEmil Constantinescu       tol  = tola + tolr;
54361e66621cSBarry Smith       if (tola > 0.) maxa = PetscMax(maxa, err / tola);
54371e66621cSBarry Smith       if (tolr > 0.) maxr = PetscMax(maxr, err / tolr);
54381e66621cSBarry Smith       if (tol > 0.) max = PetscMax(max, err / tol);
54398a175baeSEmil Constantinescu     }
54409566063dSJacob Faibussowitsch     PetscCall(VecRestoreArrayRead(ts->vrtol, &rtol));
54418a175baeSEmil Constantinescu   } else { /* scalar atol, scalar rtol */
54428a175baeSEmil Constantinescu 
54438a175baeSEmil Constantinescu     for (i = 0; i < n; i++) {
544476cddca1SEmil Constantinescu       SkipSmallValue(y[i], u[i], ts->adapt->ignore_max);
54458a175baeSEmil Constantinescu       err  = PetscAbsScalar(e[i]);
54468a175baeSEmil Constantinescu       tola = ts->atol;
54478a175baeSEmil Constantinescu       tolr = ts->rtol * PetscMax(PetscAbsScalar(u[i]), PetscAbsScalar(y[i]));
54488a175baeSEmil Constantinescu       tol  = tola + tolr;
54491e66621cSBarry Smith       if (tola > 0.) maxa = PetscMax(maxa, err / tola);
54501e66621cSBarry Smith       if (tolr > 0.) maxr = PetscMax(maxr, err / tolr);
54511e66621cSBarry Smith       if (tol > 0.) max = PetscMax(max, err / tol);
54528a175baeSEmil Constantinescu     }
54538a175baeSEmil Constantinescu   }
54549566063dSJacob Faibussowitsch   PetscCall(VecRestoreArrayRead(E, &e));
54559566063dSJacob Faibussowitsch   PetscCall(VecRestoreArrayRead(U, &u));
54569566063dSJacob Faibussowitsch   PetscCall(VecRestoreArrayRead(Y, &y));
54578a175baeSEmil Constantinescu   err_loc[0] = max;
54588a175baeSEmil Constantinescu   err_loc[1] = maxa;
54598a175baeSEmil Constantinescu   err_loc[2] = maxr;
54601c2dc1cbSBarry Smith   PetscCall(MPIU_Allreduce(err_loc, err_glb, 3, MPIU_REAL, MPIU_MAX, PetscObjectComm((PetscObject)ts)));
54618a175baeSEmil Constantinescu   gmax  = err_glb[0];
54628a175baeSEmil Constantinescu   gmaxa = err_glb[1];
54638a175baeSEmil Constantinescu   gmaxr = err_glb[2];
54648a175baeSEmil Constantinescu 
54658a175baeSEmil Constantinescu   *norm  = gmax;
54668a175baeSEmil Constantinescu   *norma = gmaxa;
54678a175baeSEmil Constantinescu   *normr = gmaxr;
54683c633725SBarry Smith   PetscCheck(!PetscIsInfOrNanScalar(*norm), PetscObjectComm((PetscObject)ts), PETSC_ERR_FP, "Infinite or not-a-number generated in norm");
54693c633725SBarry Smith   PetscCheck(!PetscIsInfOrNanScalar(*norma), PetscObjectComm((PetscObject)ts), PETSC_ERR_FP, "Infinite or not-a-number generated in norma");
54703c633725SBarry Smith   PetscCheck(!PetscIsInfOrNanScalar(*normr), PetscObjectComm((PetscObject)ts), PETSC_ERR_FP, "Infinite or not-a-number generated in normr");
54718a175baeSEmil Constantinescu   PetscFunctionReturn(0);
54728a175baeSEmil Constantinescu }
54738a175baeSEmil Constantinescu 
54748a175baeSEmil Constantinescu /*@
54758a175baeSEmil Constantinescu    TSErrorWeightedENorm - compute a weighted error norm based on supplied absolute and relative tolerances
54768a175baeSEmil Constantinescu 
54778a175baeSEmil Constantinescu    Collective on TS
54788a175baeSEmil Constantinescu 
54794165533cSJose E. Roman    Input Parameters:
54808a175baeSEmil Constantinescu +  ts - time stepping context
54818a175baeSEmil Constantinescu .  E - error vector
54828a175baeSEmil Constantinescu .  U - state vector, usually ts->vec_sol
54838a175baeSEmil Constantinescu .  Y - state vector, previous time step
54848a175baeSEmil Constantinescu -  wnormtype - norm type, either NORM_2 or NORM_INFINITY
54858a175baeSEmil Constantinescu 
54864165533cSJose E. Roman    Output Parameters:
5487a2b725a8SWilliam Gropp +  norm  - weighted norm, a value of 1.0 achieves a balance between absolute and relative tolerances
54888a175baeSEmil Constantinescu .  norma - weighted norm, a value of 1.0 means that the error meets the absolute tolerance set by the user
5489a2b725a8SWilliam Gropp -  normr - weighted norm, a value of 1.0 means that the error meets the relative tolerance set by the user
54908a175baeSEmil Constantinescu 
54918a175baeSEmil Constantinescu    Options Database Keys:
54928a175baeSEmil Constantinescu .  -ts_adapt_wnormtype <wnormtype> - 2, INFINITY
54938a175baeSEmil Constantinescu 
54948a175baeSEmil Constantinescu    Level: developer
54958a175baeSEmil Constantinescu 
5496db781477SPatrick Sanan .seealso: `TSErrorWeightedENormInfinity()`, `TSErrorWeightedENorm2()`, `TSErrorWeightedNormInfinity()`, `TSErrorWeightedNorm2()`
54978a175baeSEmil Constantinescu @*/
5498*d71ae5a4SJacob Faibussowitsch PetscErrorCode TSErrorWeightedENorm(TS ts, Vec E, Vec U, Vec Y, NormType wnormtype, PetscReal *norm, PetscReal *norma, PetscReal *normr)
5499*d71ae5a4SJacob Faibussowitsch {
55008a175baeSEmil Constantinescu   PetscFunctionBegin;
55011e66621cSBarry Smith   if (wnormtype == NORM_2) PetscCall(TSErrorWeightedENorm2(ts, E, U, Y, norm, norma, normr));
55021e66621cSBarry Smith   else if (wnormtype == NORM_INFINITY) PetscCall(TSErrorWeightedENormInfinity(ts, E, U, Y, norm, norma, normr));
55031e66621cSBarry Smith   else SETERRQ(PETSC_COMM_SELF, PETSC_ERR_SUP, "No support for norm type %s", NormTypes[wnormtype]);
55048a175baeSEmil Constantinescu   PetscFunctionReturn(0);
55058a175baeSEmil Constantinescu }
55068a175baeSEmil Constantinescu 
55078d59e960SJed Brown /*@
55088d59e960SJed Brown    TSSetCFLTimeLocal - Set the local CFL constraint relative to forward Euler
55098d59e960SJed Brown 
55108d59e960SJed Brown    Logically Collective on TS
55118d59e960SJed Brown 
55124165533cSJose E. Roman    Input Parameters:
55138d59e960SJed Brown +  ts - time stepping context
55148d59e960SJed Brown -  cfltime - maximum stable time step if using forward Euler (value can be different on each process)
55158d59e960SJed Brown 
55168d59e960SJed Brown    Note:
55178d59e960SJed Brown    After calling this function, the global CFL time can be obtained by calling TSGetCFLTime()
55188d59e960SJed Brown 
55198d59e960SJed Brown    Level: intermediate
55208d59e960SJed Brown 
5521db781477SPatrick Sanan .seealso: `TSGetCFLTime()`, `TSADAPTCFL`
55228d59e960SJed Brown @*/
5523*d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetCFLTimeLocal(TS ts, PetscReal cfltime)
5524*d71ae5a4SJacob Faibussowitsch {
55258d59e960SJed Brown   PetscFunctionBegin;
55268d59e960SJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
55278d59e960SJed Brown   ts->cfltime_local = cfltime;
55288d59e960SJed Brown   ts->cfltime       = -1.;
55298d59e960SJed Brown   PetscFunctionReturn(0);
55308d59e960SJed Brown }
55318d59e960SJed Brown 
55328d59e960SJed Brown /*@
55338d59e960SJed Brown    TSGetCFLTime - Get the maximum stable time step according to CFL criteria applied to forward Euler
55348d59e960SJed Brown 
55358d59e960SJed Brown    Collective on TS
55368d59e960SJed Brown 
55374165533cSJose E. Roman    Input Parameter:
55388d59e960SJed Brown .  ts - time stepping context
55398d59e960SJed Brown 
55404165533cSJose E. Roman    Output Parameter:
55418d59e960SJed Brown .  cfltime - maximum stable time step for forward Euler
55428d59e960SJed Brown 
55438d59e960SJed Brown    Level: advanced
55448d59e960SJed Brown 
5545db781477SPatrick Sanan .seealso: `TSSetCFLTimeLocal()`
55468d59e960SJed Brown @*/
5547*d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetCFLTime(TS ts, PetscReal *cfltime)
5548*d71ae5a4SJacob Faibussowitsch {
55498d59e960SJed Brown   PetscFunctionBegin;
55501e66621cSBarry Smith   if (ts->cfltime < 0) PetscCall(MPIU_Allreduce(&ts->cfltime_local, &ts->cfltime, 1, MPIU_REAL, MPIU_MIN, PetscObjectComm((PetscObject)ts)));
55518d59e960SJed Brown   *cfltime = ts->cfltime;
55528d59e960SJed Brown   PetscFunctionReturn(0);
55538d59e960SJed Brown }
55548d59e960SJed Brown 
5555d6ebe24aSShri Abhyankar /*@
5556d6ebe24aSShri Abhyankar    TSVISetVariableBounds - Sets the lower and upper bounds for the solution vector. xl <= x <= xu
5557d6ebe24aSShri Abhyankar 
5558d6ebe24aSShri Abhyankar    Input Parameters:
5559a2b725a8SWilliam Gropp +  ts   - the TS context.
5560d6ebe24aSShri Abhyankar .  xl   - lower bound.
5561a2b725a8SWilliam Gropp -  xu   - upper bound.
5562d6ebe24aSShri Abhyankar 
5563d6ebe24aSShri Abhyankar    Notes:
5564d6ebe24aSShri Abhyankar    If this routine is not called then the lower and upper bounds are set to
5565e270355aSBarry Smith    PETSC_NINFINITY and PETSC_INFINITY respectively during SNESSetUp().
5566d6ebe24aSShri Abhyankar 
55672bd2b0e6SSatish Balay    Level: advanced
55682bd2b0e6SSatish Balay 
5569d6ebe24aSShri Abhyankar @*/
5570*d71ae5a4SJacob Faibussowitsch PetscErrorCode TSVISetVariableBounds(TS ts, Vec xl, Vec xu)
5571*d71ae5a4SJacob Faibussowitsch {
5572d6ebe24aSShri Abhyankar   SNES snes;
5573d6ebe24aSShri Abhyankar 
5574d6ebe24aSShri Abhyankar   PetscFunctionBegin;
55759566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts, &snes));
55769566063dSJacob Faibussowitsch   PetscCall(SNESVISetVariableBounds(snes, xl, xu));
5577d6ebe24aSShri Abhyankar   PetscFunctionReturn(0);
5578d6ebe24aSShri Abhyankar }
5579d6ebe24aSShri Abhyankar 
5580f9c1d6abSBarry Smith /*@
5581f9c1d6abSBarry Smith    TSComputeLinearStability - computes the linear stability function at a point
5582f9c1d6abSBarry Smith 
5583d083f849SBarry Smith    Collective on TS
5584f9c1d6abSBarry Smith 
5585f9c1d6abSBarry Smith    Input Parameters:
5586f9c1d6abSBarry Smith +  ts - the TS context
5587f9c1d6abSBarry Smith -  xr,xi - real and imaginary part of input arguments
5588f9c1d6abSBarry Smith 
5589f9c1d6abSBarry Smith    Output Parameters:
5590f9c1d6abSBarry Smith .  yr,yi - real and imaginary part of function value
5591f9c1d6abSBarry Smith 
5592f9c1d6abSBarry Smith    Level: developer
5593f9c1d6abSBarry Smith 
5594db781477SPatrick Sanan .seealso: `TSSetRHSFunction()`, `TSComputeIFunction()`
5595f9c1d6abSBarry Smith @*/
5596*d71ae5a4SJacob Faibussowitsch PetscErrorCode TSComputeLinearStability(TS ts, PetscReal xr, PetscReal xi, PetscReal *yr, PetscReal *yi)
5597*d71ae5a4SJacob Faibussowitsch {
5598f9c1d6abSBarry Smith   PetscFunctionBegin;
5599f9c1d6abSBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
5600dbbe0bcdSBarry Smith   PetscUseTypeMethod(ts, linearstability, xr, xi, yr, yi);
5601f9c1d6abSBarry Smith   PetscFunctionReturn(0);
5602f9c1d6abSBarry Smith }
560324655328SShri 
560424655328SShri /*@
5605dcb233daSLisandro Dalcin    TSRestartStep - Flags the solver to restart the next step
5606dcb233daSLisandro Dalcin 
5607dcb233daSLisandro Dalcin    Collective on TS
5608dcb233daSLisandro Dalcin 
5609dcb233daSLisandro Dalcin    Input Parameter:
5610dcb233daSLisandro Dalcin .  ts - the TS context obtained from TSCreate()
5611dcb233daSLisandro Dalcin 
5612dcb233daSLisandro Dalcin    Level: advanced
5613dcb233daSLisandro Dalcin 
5614dcb233daSLisandro Dalcin    Notes:
5615dcb233daSLisandro Dalcin    Multistep methods like BDF or Runge-Kutta methods with FSAL property require restarting the solver in the event of
5616dcb233daSLisandro Dalcin    discontinuities. These discontinuities may be introduced as a consequence of explicitly modifications to the solution
5617dcb233daSLisandro Dalcin    vector (which PETSc attempts to detect and handle) or problem coefficients (which PETSc is not able to detect). For
5618dcb233daSLisandro Dalcin    the sake of correctness and maximum safety, users are expected to call TSRestart() whenever they introduce
5619dcb233daSLisandro Dalcin    discontinuities in callback routines (e.g. prestep and poststep routines, or implicit/rhs function routines with
5620dcb233daSLisandro Dalcin    discontinuous source terms).
5621dcb233daSLisandro Dalcin 
5622db781477SPatrick Sanan .seealso: `TSSolve()`, `TSSetPreStep()`, `TSSetPostStep()`
5623dcb233daSLisandro Dalcin @*/
5624*d71ae5a4SJacob Faibussowitsch PetscErrorCode TSRestartStep(TS ts)
5625*d71ae5a4SJacob Faibussowitsch {
5626dcb233daSLisandro Dalcin   PetscFunctionBegin;
5627dcb233daSLisandro Dalcin   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
5628dcb233daSLisandro Dalcin   ts->steprestart = PETSC_TRUE;
5629dcb233daSLisandro Dalcin   PetscFunctionReturn(0);
5630dcb233daSLisandro Dalcin }
5631dcb233daSLisandro Dalcin 
5632dcb233daSLisandro Dalcin /*@
563324655328SShri    TSRollBack - Rolls back one time step
563424655328SShri 
563524655328SShri    Collective on TS
563624655328SShri 
563724655328SShri    Input Parameter:
563824655328SShri .  ts - the TS context obtained from TSCreate()
563924655328SShri 
564024655328SShri    Level: advanced
564124655328SShri 
5642db781477SPatrick Sanan .seealso: `TSCreate()`, `TSSetUp()`, `TSDestroy()`, `TSSolve()`, `TSSetPreStep()`, `TSSetPreStage()`, `TSInterpolate()`
564324655328SShri @*/
5644*d71ae5a4SJacob Faibussowitsch PetscErrorCode TSRollBack(TS ts)
5645*d71ae5a4SJacob Faibussowitsch {
564624655328SShri   PetscFunctionBegin;
564724655328SShri   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
56483c633725SBarry Smith   PetscCheck(!ts->steprollback, PetscObjectComm((PetscObject)ts), PETSC_ERR_ARG_WRONGSTATE, "TSRollBack already called");
5649dbbe0bcdSBarry Smith   PetscUseTypeMethod(ts, rollback);
565024655328SShri   ts->time_step  = ts->ptime - ts->ptime_prev;
565124655328SShri   ts->ptime      = ts->ptime_prev;
5652be5899b3SLisandro Dalcin   ts->ptime_prev = ts->ptime_prev_rollback;
56532808aa04SLisandro Dalcin   ts->steps--;
5654b3de5cdeSLisandro Dalcin   ts->steprollback = PETSC_TRUE;
565524655328SShri   PetscFunctionReturn(0);
565624655328SShri }
5657aeb4809dSShri Abhyankar 
5658ff22ae23SHong Zhang /*@
5659ff22ae23SHong Zhang    TSGetStages - Get the number of stages and stage values
5660ff22ae23SHong Zhang 
5661ff22ae23SHong Zhang    Input Parameter:
5662ff22ae23SHong Zhang .  ts - the TS context obtained from TSCreate()
5663ff22ae23SHong Zhang 
56640429704eSStefano Zampini    Output Parameters:
56650429704eSStefano Zampini +  ns - the number of stages
56660429704eSStefano Zampini -  Y - the current stage vectors
56670429704eSStefano Zampini 
5668ff22ae23SHong Zhang    Level: advanced
5669ff22ae23SHong Zhang 
56700429704eSStefano Zampini    Notes: Both ns and Y can be NULL.
56710429704eSStefano Zampini 
5672db781477SPatrick Sanan .seealso: `TSCreate()`
5673ff22ae23SHong Zhang @*/
5674*d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetStages(TS ts, PetscInt *ns, Vec **Y)
5675*d71ae5a4SJacob Faibussowitsch {
5676ff22ae23SHong Zhang   PetscFunctionBegin;
5677ff22ae23SHong Zhang   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
5678dadcf809SJacob Faibussowitsch   if (ns) PetscValidIntPointer(ns, 2);
56790429704eSStefano Zampini   if (Y) PetscValidPointer(Y, 3);
56800429704eSStefano Zampini   if (!ts->ops->getstages) {
56810429704eSStefano Zampini     if (ns) *ns = 0;
56820429704eSStefano Zampini     if (Y) *Y = NULL;
5683dbbe0bcdSBarry Smith   } else PetscUseTypeMethod(ts, getstages, ns, Y);
5684ff22ae23SHong Zhang   PetscFunctionReturn(0);
5685ff22ae23SHong Zhang }
5686ff22ae23SHong Zhang 
5687847ff0e1SMatthew G. Knepley /*@C
5688847ff0e1SMatthew G. Knepley   TSComputeIJacobianDefaultColor - Computes the Jacobian using finite differences and coloring to exploit matrix sparsity.
5689847ff0e1SMatthew G. Knepley 
5690847ff0e1SMatthew G. Knepley   Collective on SNES
5691847ff0e1SMatthew G. Knepley 
5692847ff0e1SMatthew G. Knepley   Input Parameters:
5693847ff0e1SMatthew G. Knepley + ts - the TS context
5694847ff0e1SMatthew G. Knepley . t - current timestep
5695847ff0e1SMatthew G. Knepley . U - state vector
5696847ff0e1SMatthew G. Knepley . Udot - time derivative of state vector
5697847ff0e1SMatthew G. Knepley . shift - shift to apply, see note below
5698847ff0e1SMatthew G. Knepley - ctx - an optional user context
5699847ff0e1SMatthew G. Knepley 
5700847ff0e1SMatthew G. Knepley   Output Parameters:
5701847ff0e1SMatthew G. Knepley + J - Jacobian matrix (not altered in this routine)
5702847ff0e1SMatthew G. Knepley - B - newly computed Jacobian matrix to use with preconditioner (generally the same as J)
5703847ff0e1SMatthew G. Knepley 
5704847ff0e1SMatthew G. Knepley   Level: intermediate
5705847ff0e1SMatthew G. Knepley 
5706847ff0e1SMatthew G. Knepley   Notes:
5707847ff0e1SMatthew G. Knepley   If F(t,U,Udot)=0 is the DAE, the required Jacobian is
5708847ff0e1SMatthew G. Knepley 
5709847ff0e1SMatthew G. Knepley   dF/dU + shift*dF/dUdot
5710847ff0e1SMatthew G. Knepley 
5711847ff0e1SMatthew G. Knepley   Most users should not need to explicitly call this routine, as it
5712847ff0e1SMatthew G. Knepley   is used internally within the nonlinear solvers.
5713847ff0e1SMatthew G. Knepley 
5714847ff0e1SMatthew G. Knepley   This will first try to get the coloring from the DM.  If the DM type has no coloring
5715847ff0e1SMatthew G. Knepley   routine, then it will try to get the coloring from the matrix.  This requires that the
5716847ff0e1SMatthew G. Knepley   matrix have nonzero entries precomputed.
5717847ff0e1SMatthew G. Knepley 
5718db781477SPatrick Sanan .seealso: `TSSetIJacobian()`, `MatFDColoringCreate()`, `MatFDColoringSetFunction()`
5719847ff0e1SMatthew G. Knepley @*/
5720*d71ae5a4SJacob Faibussowitsch PetscErrorCode TSComputeIJacobianDefaultColor(TS ts, PetscReal t, Vec U, Vec Udot, PetscReal shift, Mat J, Mat B, void *ctx)
5721*d71ae5a4SJacob Faibussowitsch {
5722847ff0e1SMatthew G. Knepley   SNES          snes;
5723847ff0e1SMatthew G. Knepley   MatFDColoring color;
5724847ff0e1SMatthew G. Knepley   PetscBool     hascolor, matcolor = PETSC_FALSE;
5725847ff0e1SMatthew G. Knepley 
5726847ff0e1SMatthew G. Knepley   PetscFunctionBegin;
57279566063dSJacob Faibussowitsch   PetscCall(PetscOptionsGetBool(((PetscObject)ts)->options, ((PetscObject)ts)->prefix, "-ts_fd_color_use_mat", &matcolor, NULL));
57289566063dSJacob Faibussowitsch   PetscCall(PetscObjectQuery((PetscObject)B, "TSMatFDColoring", (PetscObject *)&color));
5729847ff0e1SMatthew G. Knepley   if (!color) {
5730847ff0e1SMatthew G. Knepley     DM         dm;
5731847ff0e1SMatthew G. Knepley     ISColoring iscoloring;
5732847ff0e1SMatthew G. Knepley 
57339566063dSJacob Faibussowitsch     PetscCall(TSGetDM(ts, &dm));
57349566063dSJacob Faibussowitsch     PetscCall(DMHasColoring(dm, &hascolor));
5735847ff0e1SMatthew G. Knepley     if (hascolor && !matcolor) {
57369566063dSJacob Faibussowitsch       PetscCall(DMCreateColoring(dm, IS_COLORING_GLOBAL, &iscoloring));
57379566063dSJacob Faibussowitsch       PetscCall(MatFDColoringCreate(B, iscoloring, &color));
57389566063dSJacob Faibussowitsch       PetscCall(MatFDColoringSetFunction(color, (PetscErrorCode(*)(void))SNESTSFormFunction, (void *)ts));
57399566063dSJacob Faibussowitsch       PetscCall(MatFDColoringSetFromOptions(color));
57409566063dSJacob Faibussowitsch       PetscCall(MatFDColoringSetUp(B, iscoloring, color));
57419566063dSJacob Faibussowitsch       PetscCall(ISColoringDestroy(&iscoloring));
5742847ff0e1SMatthew G. Knepley     } else {
5743847ff0e1SMatthew G. Knepley       MatColoring mc;
5744847ff0e1SMatthew G. Knepley 
57459566063dSJacob Faibussowitsch       PetscCall(MatColoringCreate(B, &mc));
57469566063dSJacob Faibussowitsch       PetscCall(MatColoringSetDistance(mc, 2));
57479566063dSJacob Faibussowitsch       PetscCall(MatColoringSetType(mc, MATCOLORINGSL));
57489566063dSJacob Faibussowitsch       PetscCall(MatColoringSetFromOptions(mc));
57499566063dSJacob Faibussowitsch       PetscCall(MatColoringApply(mc, &iscoloring));
57509566063dSJacob Faibussowitsch       PetscCall(MatColoringDestroy(&mc));
57519566063dSJacob Faibussowitsch       PetscCall(MatFDColoringCreate(B, iscoloring, &color));
57529566063dSJacob Faibussowitsch       PetscCall(MatFDColoringSetFunction(color, (PetscErrorCode(*)(void))SNESTSFormFunction, (void *)ts));
57539566063dSJacob Faibussowitsch       PetscCall(MatFDColoringSetFromOptions(color));
57549566063dSJacob Faibussowitsch       PetscCall(MatFDColoringSetUp(B, iscoloring, color));
57559566063dSJacob Faibussowitsch       PetscCall(ISColoringDestroy(&iscoloring));
5756847ff0e1SMatthew G. Knepley     }
57579566063dSJacob Faibussowitsch     PetscCall(PetscObjectCompose((PetscObject)B, "TSMatFDColoring", (PetscObject)color));
57589566063dSJacob Faibussowitsch     PetscCall(PetscObjectDereference((PetscObject)color));
5759847ff0e1SMatthew G. Knepley   }
57609566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts, &snes));
57619566063dSJacob Faibussowitsch   PetscCall(MatFDColoringApply(B, color, U, snes));
5762847ff0e1SMatthew G. Knepley   if (J != B) {
57639566063dSJacob Faibussowitsch     PetscCall(MatAssemblyBegin(J, MAT_FINAL_ASSEMBLY));
57649566063dSJacob Faibussowitsch     PetscCall(MatAssemblyEnd(J, MAT_FINAL_ASSEMBLY));
5765847ff0e1SMatthew G. Knepley   }
5766847ff0e1SMatthew G. Knepley   PetscFunctionReturn(0);
5767847ff0e1SMatthew G. Knepley }
576893b34091SDebojyoti Ghosh 
5769cb9d8021SPierre Barbier de Reuille /*@
57706bc98fa9SBarry Smith     TSSetFunctionDomainError - Set a function that tests if the current state vector is valid
5771cb9d8021SPierre Barbier de Reuille 
5772cb9d8021SPierre Barbier de Reuille     Input Parameters:
57736bc98fa9SBarry Smith +    ts - the TS context
57746bc98fa9SBarry Smith -    func - function called within TSFunctionDomainError
57756bc98fa9SBarry Smith 
57766bc98fa9SBarry Smith     Calling sequence of func:
57776bc98fa9SBarry Smith $     PetscErrorCode func(TS ts,PetscReal time,Vec state,PetscBool reject)
57786bc98fa9SBarry Smith 
57796bc98fa9SBarry Smith +   ts - the TS context
57806bc98fa9SBarry Smith .   time - the current time (of the stage)
57816bc98fa9SBarry Smith .   state - the state to check if it is valid
57826bc98fa9SBarry Smith -   reject - (output parameter) PETSC_FALSE if the state is acceptable, PETSC_TRUE if not acceptable
5783cb9d8021SPierre Barbier de Reuille 
5784cb9d8021SPierre Barbier de Reuille     Level: intermediate
5785cb9d8021SPierre Barbier de Reuille 
57866bc98fa9SBarry Smith     Notes:
57876bc98fa9SBarry Smith       If an implicit ODE solver is being used then, in addition to providing this routine, the
57886bc98fa9SBarry Smith       user's code should call SNESSetFunctionDomainError() when domain errors occur during
57896bc98fa9SBarry Smith       function evaluations where the functions are provided by TSSetIFunction() or TSSetRHSFunction().
57906bc98fa9SBarry Smith       Use TSGetSNES() to obtain the SNES object
57916bc98fa9SBarry Smith 
57926bc98fa9SBarry Smith     Developer Notes:
57936bc98fa9SBarry Smith       The naming of this function is inconsistent with the SNESSetFunctionDomainError()
57946bc98fa9SBarry Smith       since one takes a function pointer and the other does not.
57956bc98fa9SBarry Smith 
5796db781477SPatrick Sanan .seealso: `TSAdaptCheckStage()`, `TSFunctionDomainError()`, `SNESSetFunctionDomainError()`, `TSGetSNES()`
5797cb9d8021SPierre Barbier de Reuille @*/
5798cb9d8021SPierre Barbier de Reuille 
5799*d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetFunctionDomainError(TS ts, PetscErrorCode (*func)(TS, PetscReal, Vec, PetscBool *))
5800*d71ae5a4SJacob Faibussowitsch {
5801cb9d8021SPierre Barbier de Reuille   PetscFunctionBegin;
5802cb9d8021SPierre Barbier de Reuille   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
5803cb9d8021SPierre Barbier de Reuille   ts->functiondomainerror = func;
5804cb9d8021SPierre Barbier de Reuille   PetscFunctionReturn(0);
5805cb9d8021SPierre Barbier de Reuille }
5806cb9d8021SPierre Barbier de Reuille 
5807cb9d8021SPierre Barbier de Reuille /*@
58086bc98fa9SBarry Smith     TSFunctionDomainError - Checks if the current state is valid
5809cb9d8021SPierre Barbier de Reuille 
5810cb9d8021SPierre Barbier de Reuille     Input Parameters:
58116bc98fa9SBarry Smith +    ts - the TS context
58126bc98fa9SBarry Smith .    stagetime - time of the simulation
58136bc98fa9SBarry Smith -    Y - state vector to check.
5814cb9d8021SPierre Barbier de Reuille 
5815cb9d8021SPierre Barbier de Reuille     Output Parameter:
58166bc98fa9SBarry Smith .    accept - Set to PETSC_FALSE if the current state vector is valid.
5817cb9d8021SPierre Barbier de Reuille 
5818cb9d8021SPierre Barbier de Reuille     Note:
58196bc98fa9SBarry Smith     This function is called by the TS integration routines and calls the user provided function (set with TSSetFunctionDomainError())
58206bc98fa9SBarry Smith     to check if the current state is valid.
582196a0c994SBarry Smith 
58226bc98fa9SBarry Smith     Level: developer
58236bc98fa9SBarry Smith 
5824db781477SPatrick Sanan .seealso: `TSSetFunctionDomainError()`
5825cb9d8021SPierre Barbier de Reuille @*/
5826*d71ae5a4SJacob Faibussowitsch PetscErrorCode TSFunctionDomainError(TS ts, PetscReal stagetime, Vec Y, PetscBool *accept)
5827*d71ae5a4SJacob Faibussowitsch {
5828cb9d8021SPierre Barbier de Reuille   PetscFunctionBegin;
5829cb9d8021SPierre Barbier de Reuille   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
5830cb9d8021SPierre Barbier de Reuille   *accept = PETSC_TRUE;
58311e66621cSBarry Smith   if (ts->functiondomainerror) PetscCall((*ts->functiondomainerror)(ts, stagetime, Y, accept));
5832cb9d8021SPierre Barbier de Reuille   PetscFunctionReturn(0);
5833cb9d8021SPierre Barbier de Reuille }
58341ceb14c0SBarry Smith 
583593b34091SDebojyoti Ghosh /*@C
5836e5168f73SEmil Constantinescu   TSClone - This function clones a time step object.
583793b34091SDebojyoti Ghosh 
5838d083f849SBarry Smith   Collective
583993b34091SDebojyoti Ghosh 
584093b34091SDebojyoti Ghosh   Input Parameter:
584193b34091SDebojyoti Ghosh . tsin    - The input TS
584293b34091SDebojyoti Ghosh 
584393b34091SDebojyoti Ghosh   Output Parameter:
5844e5168f73SEmil Constantinescu . tsout   - The output TS (cloned)
584593b34091SDebojyoti Ghosh 
58465eca1a21SEmil Constantinescu   Notes:
58475eca1a21SEmil Constantinescu   This function is used to create a clone of a TS object. It is used in ARKIMEX for initializing the slope for first stage explicit methods. It will likely be replaced in the future with a mechanism of switching methods on the fly.
58485eca1a21SEmil Constantinescu 
5849928bb9adSStefano Zampini   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 SNES snes_dup=NULL; TSGetSNES(ts,&snes_dup); TSSetSNES(ts,snes_dup);
58505eca1a21SEmil Constantinescu 
58515eca1a21SEmil Constantinescu   Level: developer
585293b34091SDebojyoti Ghosh 
5853db781477SPatrick Sanan .seealso: `TSCreate()`, `TSSetType()`, `TSSetUp()`, `TSDestroy()`, `TSSetProblemType()`
585493b34091SDebojyoti Ghosh @*/
5855*d71ae5a4SJacob Faibussowitsch PetscErrorCode TSClone(TS tsin, TS *tsout)
5856*d71ae5a4SJacob Faibussowitsch {
585793b34091SDebojyoti Ghosh   TS     t;
5858dc846ba4SSatish Balay   SNES   snes_start;
5859dc846ba4SSatish Balay   DM     dm;
5860dc846ba4SSatish Balay   TSType type;
586193b34091SDebojyoti Ghosh 
586293b34091SDebojyoti Ghosh   PetscFunctionBegin;
586393b34091SDebojyoti Ghosh   PetscValidPointer(tsin, 1);
586493b34091SDebojyoti Ghosh   *tsout = NULL;
586593b34091SDebojyoti Ghosh 
58669566063dSJacob Faibussowitsch   PetscCall(PetscHeaderCreate(t, TS_CLASSID, "TS", "Time stepping", "TS", PetscObjectComm((PetscObject)tsin), TSDestroy, TSView));
586793b34091SDebojyoti Ghosh 
586893b34091SDebojyoti Ghosh   /* General TS description */
586993b34091SDebojyoti Ghosh   t->numbermonitors    = 0;
5870d0c080abSJoseph Pusztay   t->monitorFrequency  = 1;
587193b34091SDebojyoti Ghosh   t->setupcalled       = 0;
587293b34091SDebojyoti Ghosh   t->ksp_its           = 0;
587393b34091SDebojyoti Ghosh   t->snes_its          = 0;
587493b34091SDebojyoti Ghosh   t->nwork             = 0;
58757d51462cSStefano Zampini   t->rhsjacobian.time  = PETSC_MIN_REAL;
587693b34091SDebojyoti Ghosh   t->rhsjacobian.scale = 1.;
587793b34091SDebojyoti Ghosh   t->ijacobian.shift   = 1.;
587893b34091SDebojyoti Ghosh 
58799566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(tsin, &snes_start));
58809566063dSJacob Faibussowitsch   PetscCall(TSSetSNES(t, snes_start));
5881d15a3a53SEmil Constantinescu 
58829566063dSJacob Faibussowitsch   PetscCall(TSGetDM(tsin, &dm));
58839566063dSJacob Faibussowitsch   PetscCall(TSSetDM(t, dm));
588493b34091SDebojyoti Ghosh 
588593b34091SDebojyoti Ghosh   t->adapt = tsin->adapt;
58869566063dSJacob Faibussowitsch   PetscCall(PetscObjectReference((PetscObject)t->adapt));
588793b34091SDebojyoti Ghosh 
5888e7069c78SShri   t->trajectory = tsin->trajectory;
58899566063dSJacob Faibussowitsch   PetscCall(PetscObjectReference((PetscObject)t->trajectory));
5890e7069c78SShri 
5891e7069c78SShri   t->event = tsin->event;
58926b10a48eSSatish Balay   if (t->event) t->event->refct++;
5893e7069c78SShri 
589493b34091SDebojyoti Ghosh   t->problem_type      = tsin->problem_type;
589593b34091SDebojyoti Ghosh   t->ptime             = tsin->ptime;
5896e7069c78SShri   t->ptime_prev        = tsin->ptime_prev;
589793b34091SDebojyoti Ghosh   t->time_step         = tsin->time_step;
589893b34091SDebojyoti Ghosh   t->max_time          = tsin->max_time;
589993b34091SDebojyoti Ghosh   t->steps             = tsin->steps;
590093b34091SDebojyoti Ghosh   t->max_steps         = tsin->max_steps;
590193b34091SDebojyoti Ghosh   t->equation_type     = tsin->equation_type;
590293b34091SDebojyoti Ghosh   t->atol              = tsin->atol;
590393b34091SDebojyoti Ghosh   t->rtol              = tsin->rtol;
590493b34091SDebojyoti Ghosh   t->max_snes_failures = tsin->max_snes_failures;
590593b34091SDebojyoti Ghosh   t->max_reject        = tsin->max_reject;
590693b34091SDebojyoti Ghosh   t->errorifstepfailed = tsin->errorifstepfailed;
590793b34091SDebojyoti Ghosh 
59089566063dSJacob Faibussowitsch   PetscCall(TSGetType(tsin, &type));
59099566063dSJacob Faibussowitsch   PetscCall(TSSetType(t, type));
591093b34091SDebojyoti Ghosh 
591193b34091SDebojyoti Ghosh   t->vec_sol = NULL;
591293b34091SDebojyoti Ghosh 
591393b34091SDebojyoti Ghosh   t->cfltime          = tsin->cfltime;
591493b34091SDebojyoti Ghosh   t->cfltime_local    = tsin->cfltime_local;
591593b34091SDebojyoti Ghosh   t->exact_final_time = tsin->exact_final_time;
591693b34091SDebojyoti Ghosh 
59179566063dSJacob Faibussowitsch   PetscCall(PetscMemcpy(t->ops, tsin->ops, sizeof(struct _TSOps)));
591893b34091SDebojyoti Ghosh 
59190d4fed19SBarry Smith   if (((PetscObject)tsin)->fortran_func_pointers) {
59200d4fed19SBarry Smith     PetscInt i;
59219566063dSJacob Faibussowitsch     PetscCall(PetscMalloc((10) * sizeof(void (*)(void)), &((PetscObject)t)->fortran_func_pointers));
5922ad540459SPierre Jolivet     for (i = 0; i < 10; i++) ((PetscObject)t)->fortran_func_pointers[i] = ((PetscObject)tsin)->fortran_func_pointers[i];
59230d4fed19SBarry Smith   }
592493b34091SDebojyoti Ghosh   *tsout = t;
592593b34091SDebojyoti Ghosh   PetscFunctionReturn(0);
592693b34091SDebojyoti Ghosh }
5927f3b1f45cSBarry Smith 
5928*d71ae5a4SJacob Faibussowitsch static PetscErrorCode RHSWrapperFunction_TSRHSJacobianTest(void *ctx, Vec x, Vec y)
5929*d71ae5a4SJacob Faibussowitsch {
5930f3b1f45cSBarry Smith   TS ts = (TS)ctx;
5931f3b1f45cSBarry Smith 
5932f3b1f45cSBarry Smith   PetscFunctionBegin;
59339566063dSJacob Faibussowitsch   PetscCall(TSComputeRHSFunction(ts, 0, x, y));
5934f3b1f45cSBarry Smith   PetscFunctionReturn(0);
5935f3b1f45cSBarry Smith }
5936f3b1f45cSBarry Smith 
5937f3b1f45cSBarry Smith /*@
5938f3b1f45cSBarry Smith     TSRHSJacobianTest - Compares the multiply routine provided to the MATSHELL with differencing on the TS given RHS function.
5939f3b1f45cSBarry Smith 
5940d083f849SBarry Smith    Logically Collective on TS
5941f3b1f45cSBarry Smith 
5942f3b1f45cSBarry Smith     Input Parameters:
5943f3b1f45cSBarry Smith     TS - the time stepping routine
5944f3b1f45cSBarry Smith 
5945f3b1f45cSBarry Smith    Output Parameter:
5946f3b1f45cSBarry Smith .   flg - PETSC_TRUE if the multiply is likely correct
5947f3b1f45cSBarry Smith 
5948f3b1f45cSBarry Smith    Options Database:
5949f3b1f45cSBarry Smith  .   -ts_rhs_jacobian_test_mult -mat_shell_test_mult_view - run the test at each timestep of the integrator
5950f3b1f45cSBarry Smith 
5951f3b1f45cSBarry Smith    Level: advanced
5952f3b1f45cSBarry Smith 
595395452b02SPatrick Sanan    Notes:
595495452b02SPatrick Sanan     This only works for problems defined only the RHS function and Jacobian NOT IFunction and IJacobian
5955f3b1f45cSBarry Smith 
5956db781477SPatrick Sanan .seealso: `MatCreateShell()`, `MatShellGetContext()`, `MatShellGetOperation()`, `MatShellTestMultTranspose()`, `TSRHSJacobianTestTranspose()`
5957f3b1f45cSBarry Smith @*/
5958*d71ae5a4SJacob Faibussowitsch PetscErrorCode TSRHSJacobianTest(TS ts, PetscBool *flg)
5959*d71ae5a4SJacob Faibussowitsch {
5960f3b1f45cSBarry Smith   Mat           J, B;
5961f3b1f45cSBarry Smith   TSRHSJacobian func;
5962f3b1f45cSBarry Smith   void         *ctx;
5963f3b1f45cSBarry Smith 
5964f3b1f45cSBarry Smith   PetscFunctionBegin;
59659566063dSJacob Faibussowitsch   PetscCall(TSGetRHSJacobian(ts, &J, &B, &func, &ctx));
59669566063dSJacob Faibussowitsch   PetscCall((*func)(ts, 0.0, ts->vec_sol, J, B, ctx));
59679566063dSJacob Faibussowitsch   PetscCall(MatShellTestMult(J, RHSWrapperFunction_TSRHSJacobianTest, ts->vec_sol, ts, flg));
5968f3b1f45cSBarry Smith   PetscFunctionReturn(0);
5969f3b1f45cSBarry Smith }
5970f3b1f45cSBarry Smith 
5971f3b1f45cSBarry Smith /*@C
5972f3b1f45cSBarry Smith     TSRHSJacobianTestTranspose - Compares the multiply transpose routine provided to the MATSHELL with differencing on the TS given RHS function.
5973f3b1f45cSBarry Smith 
5974d083f849SBarry Smith    Logically Collective on TS
5975f3b1f45cSBarry Smith 
5976f3b1f45cSBarry Smith     Input Parameters:
5977f3b1f45cSBarry Smith     TS - the time stepping routine
5978f3b1f45cSBarry Smith 
5979f3b1f45cSBarry Smith    Output Parameter:
5980f3b1f45cSBarry Smith .   flg - PETSC_TRUE if the multiply is likely correct
5981f3b1f45cSBarry Smith 
5982f3b1f45cSBarry Smith    Options Database:
5983f3b1f45cSBarry Smith .   -ts_rhs_jacobian_test_mult_transpose -mat_shell_test_mult_transpose_view - run the test at each timestep of the integrator
5984f3b1f45cSBarry Smith 
598595452b02SPatrick Sanan    Notes:
598695452b02SPatrick Sanan     This only works for problems defined only the RHS function and Jacobian NOT IFunction and IJacobian
5987f3b1f45cSBarry Smith 
5988f3b1f45cSBarry Smith    Level: advanced
5989f3b1f45cSBarry Smith 
5990db781477SPatrick Sanan .seealso: `MatCreateShell()`, `MatShellGetContext()`, `MatShellGetOperation()`, `MatShellTestMultTranspose()`, `TSRHSJacobianTest()`
5991f3b1f45cSBarry Smith @*/
5992*d71ae5a4SJacob Faibussowitsch PetscErrorCode TSRHSJacobianTestTranspose(TS ts, PetscBool *flg)
5993*d71ae5a4SJacob Faibussowitsch {
5994f3b1f45cSBarry Smith   Mat           J, B;
5995f3b1f45cSBarry Smith   void         *ctx;
5996f3b1f45cSBarry Smith   TSRHSJacobian func;
5997f3b1f45cSBarry Smith 
5998f3b1f45cSBarry Smith   PetscFunctionBegin;
59999566063dSJacob Faibussowitsch   PetscCall(TSGetRHSJacobian(ts, &J, &B, &func, &ctx));
60009566063dSJacob Faibussowitsch   PetscCall((*func)(ts, 0.0, ts->vec_sol, J, B, ctx));
60019566063dSJacob Faibussowitsch   PetscCall(MatShellTestMultTranspose(J, RHSWrapperFunction_TSRHSJacobianTest, ts->vec_sol, ts, flg));
6002f3b1f45cSBarry Smith   PetscFunctionReturn(0);
6003f3b1f45cSBarry Smith }
60040fe4d17eSHong Zhang 
60050fe4d17eSHong Zhang /*@
60060fe4d17eSHong Zhang   TSSetUseSplitRHSFunction - Use the split RHSFunction when a multirate method is used.
60070fe4d17eSHong Zhang 
60080fe4d17eSHong Zhang   Logically collective
60090fe4d17eSHong Zhang 
6010d8d19677SJose E. Roman   Input Parameters:
60110fe4d17eSHong Zhang +  ts - timestepping context
60120fe4d17eSHong Zhang -  use_splitrhsfunction - PETSC_TRUE indicates that the split RHSFunction will be used
60130fe4d17eSHong Zhang 
60140fe4d17eSHong Zhang   Options Database:
60150fe4d17eSHong Zhang .   -ts_use_splitrhsfunction - <true,false>
60160fe4d17eSHong Zhang 
60170fe4d17eSHong Zhang   Notes:
60180fe4d17eSHong Zhang     This is only useful for multirate methods
60190fe4d17eSHong Zhang 
60200fe4d17eSHong Zhang   Level: intermediate
60210fe4d17eSHong Zhang 
6022db781477SPatrick Sanan .seealso: `TSGetUseSplitRHSFunction()`
60230fe4d17eSHong Zhang @*/
6024*d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetUseSplitRHSFunction(TS ts, PetscBool use_splitrhsfunction)
6025*d71ae5a4SJacob Faibussowitsch {
60260fe4d17eSHong Zhang   PetscFunctionBegin;
60270fe4d17eSHong Zhang   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
60280fe4d17eSHong Zhang   ts->use_splitrhsfunction = use_splitrhsfunction;
60290fe4d17eSHong Zhang   PetscFunctionReturn(0);
60300fe4d17eSHong Zhang }
60310fe4d17eSHong Zhang 
60320fe4d17eSHong Zhang /*@
60330fe4d17eSHong Zhang   TSGetUseSplitRHSFunction - Gets whether to use the split RHSFunction when a multirate method is used.
60340fe4d17eSHong Zhang 
60350fe4d17eSHong Zhang   Not collective
60360fe4d17eSHong Zhang 
60370fe4d17eSHong Zhang   Input Parameter:
60380fe4d17eSHong Zhang .  ts - timestepping context
60390fe4d17eSHong Zhang 
60400fe4d17eSHong Zhang   Output Parameter:
60410fe4d17eSHong Zhang .  use_splitrhsfunction - PETSC_TRUE indicates that the split RHSFunction will be used
60420fe4d17eSHong Zhang 
60430fe4d17eSHong Zhang   Level: intermediate
60440fe4d17eSHong Zhang 
6045db781477SPatrick Sanan .seealso: `TSSetUseSplitRHSFunction()`
60460fe4d17eSHong Zhang @*/
6047*d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetUseSplitRHSFunction(TS ts, PetscBool *use_splitrhsfunction)
6048*d71ae5a4SJacob Faibussowitsch {
60490fe4d17eSHong Zhang   PetscFunctionBegin;
60500fe4d17eSHong Zhang   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
60510fe4d17eSHong Zhang   *use_splitrhsfunction = ts->use_splitrhsfunction;
60520fe4d17eSHong Zhang   PetscFunctionReturn(0);
60530fe4d17eSHong Zhang }
6054d60b7d5cSBarry Smith 
6055d60b7d5cSBarry Smith /*@
6056d60b7d5cSBarry Smith     TSSetMatStructure - sets the relationship between the nonzero structure of the RHS Jacobian matrix to the IJacobian matrix.
6057d60b7d5cSBarry Smith 
6058d60b7d5cSBarry Smith    Logically  Collective on ts
6059d60b7d5cSBarry Smith 
6060d60b7d5cSBarry Smith    Input Parameters:
6061d60b7d5cSBarry Smith +  ts - the time-stepper
6062d60b7d5cSBarry Smith -  str - the structure (the default is UNKNOWN_NONZERO_PATTERN)
6063d60b7d5cSBarry Smith 
6064d60b7d5cSBarry Smith    Level: intermediate
6065d60b7d5cSBarry Smith 
6066d60b7d5cSBarry Smith    Notes:
6067d60b7d5cSBarry Smith      When the relationship between the nonzero structures is known and supplied the solution process can be much faster
6068d60b7d5cSBarry Smith 
6069db781477SPatrick Sanan .seealso: `MatAXPY()`, `MatStructure`
6070d60b7d5cSBarry Smith  @*/
6071*d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetMatStructure(TS ts, MatStructure str)
6072*d71ae5a4SJacob Faibussowitsch {
6073d60b7d5cSBarry Smith   PetscFunctionBegin;
6074d60b7d5cSBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
6075d60b7d5cSBarry Smith   ts->axpy_pattern = str;
6076d60b7d5cSBarry Smith   PetscFunctionReturn(0);
6077d60b7d5cSBarry Smith }
60784a658b32SHong Zhang 
60794a658b32SHong Zhang /*@
60804a658b32SHong Zhang   TSSetTimeSpan - sets the time span. The solution will be computed and stored for each time requested.
60814a658b32SHong Zhang 
60824a658b32SHong Zhang   Collective on ts
60834a658b32SHong Zhang 
60844a658b32SHong Zhang   Input Parameters:
60854a658b32SHong Zhang + ts - the time-stepper
60864a658b32SHong Zhang . n - number of the time points (>=2)
60874a658b32SHong Zhang - span_times - array of the time points. The first element and the last element are the initial time and the final time respectively.
60884a658b32SHong Zhang 
60894a658b32SHong Zhang   Options Database Keys:
60904a658b32SHong Zhang . -ts_time_span <t0,...tf> - Sets the time span
60914a658b32SHong Zhang 
60924a658b32SHong Zhang   Level: beginner
60934a658b32SHong Zhang 
60944a658b32SHong Zhang   Notes:
60954a658b32SHong Zhang   The elements in tspan must be all increasing. They correspond to the intermediate points for time integration.
60964a658b32SHong Zhang   TS_EXACTFINALTIME_MATCHSTEP must be used to make the last time step in each sub-interval match the intermediate points specified.
60974a658b32SHong Zhang   The intermediate solutions are saved in a vector array that can be accessed with TSGetSolutions(). Thus using time span may
60984a658b32SHong Zhang   pressure the memory system when using a large number of span points.
60994a658b32SHong Zhang 
6100c2e3fba1SPatrick Sanan .seealso: `TSGetTimeSpan()`, `TSGetSolutions()`
61014a658b32SHong Zhang  @*/
6102*d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetTimeSpan(TS ts, PetscInt n, PetscReal *span_times)
6103*d71ae5a4SJacob Faibussowitsch {
61044a658b32SHong Zhang   PetscFunctionBegin;
61054a658b32SHong Zhang   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
610663a3b9bcSJacob Faibussowitsch   PetscCheck(n >= 2, PetscObjectComm((PetscObject)ts), PETSC_ERR_ARG_WRONG, "Minimum time span size is 2 but %" PetscInt_FMT " is provided", n);
61074a658b32SHong Zhang   if (ts->tspan && n != ts->tspan->num_span_times) {
61084a658b32SHong Zhang     PetscCall(PetscFree(ts->tspan->span_times));
61094a658b32SHong Zhang     PetscCall(VecDestroyVecs(ts->tspan->num_span_times, &ts->tspan->vecs_sol));
61104a658b32SHong Zhang     PetscCall(PetscMalloc1(n, &ts->tspan->span_times));
61114a658b32SHong Zhang   }
61124a658b32SHong Zhang   if (!ts->tspan) {
61134a658b32SHong Zhang     TSTimeSpan tspan;
61144a658b32SHong Zhang     PetscCall(PetscNew(&tspan));
61154a658b32SHong Zhang     PetscCall(PetscMalloc1(n, &tspan->span_times));
6116e1db57b0SHong Zhang     tspan->reltol = 1e-6;
6117e1db57b0SHong Zhang     tspan->abstol = 10 * PETSC_MACHINE_EPSILON;
61184a658b32SHong Zhang     ts->tspan     = tspan;
61194a658b32SHong Zhang   }
61204a658b32SHong Zhang   ts->tspan->num_span_times = n;
61214a658b32SHong Zhang   PetscCall(PetscArraycpy(ts->tspan->span_times, span_times, n));
61224a658b32SHong Zhang   PetscCall(TSSetTime(ts, ts->tspan->span_times[0]));
61234a658b32SHong Zhang   PetscCall(TSSetMaxTime(ts, ts->tspan->span_times[n - 1]));
61244a658b32SHong Zhang   PetscFunctionReturn(0);
61254a658b32SHong Zhang }
61264a658b32SHong Zhang 
61274a658b32SHong Zhang /*@C
61284a658b32SHong Zhang   TSGetTimeSpan - gets the time span.
61294a658b32SHong Zhang 
61304a658b32SHong Zhang   Not Collective
61314a658b32SHong Zhang 
61324a658b32SHong Zhang   Input Parameter:
61334a658b32SHong Zhang . ts - the time-stepper
61344a658b32SHong Zhang 
61354a658b32SHong Zhang   Output Parameters:
61364a658b32SHong Zhang + n - number of the time points (>=2)
61374a658b32SHong Zhang - span_times - array of the time points. The first element and the last element are the initial time and the final time respectively. The values are valid until the TS object is destroyed.
61384a658b32SHong Zhang 
61394a658b32SHong Zhang   Level: beginner
61404a658b32SHong Zhang   Notes: Both n and span_times can be NULL.
61414a658b32SHong Zhang 
6142c2e3fba1SPatrick Sanan .seealso: `TSSetTimeSpan()`, `TSGetSolutions()`
61434a658b32SHong Zhang  @*/
6144*d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetTimeSpan(TS ts, PetscInt *n, const PetscReal **span_times)
6145*d71ae5a4SJacob Faibussowitsch {
61464a658b32SHong Zhang   PetscFunctionBegin;
61474a658b32SHong Zhang   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
61484a658b32SHong Zhang   if (n) PetscValidIntPointer(n, 2);
61494a658b32SHong Zhang   if (span_times) PetscValidPointer(span_times, 3);
61504a658b32SHong Zhang   if (!ts->tspan) {
61514a658b32SHong Zhang     if (n) *n = 0;
61524a658b32SHong Zhang     if (span_times) *span_times = NULL;
61534a658b32SHong Zhang   } else {
61544a658b32SHong Zhang     if (n) *n = ts->tspan->num_span_times;
61554a658b32SHong Zhang     if (span_times) *span_times = ts->tspan->span_times;
61564a658b32SHong Zhang   }
61574a658b32SHong Zhang   PetscFunctionReturn(0);
61584a658b32SHong Zhang }
61594a658b32SHong Zhang 
61604a658b32SHong Zhang /*@
61614a658b32SHong Zhang    TSGetTimeSpanSolutions - Get the number of solutions and the solutions at the time points specified by the time span.
61624a658b32SHong Zhang 
61634a658b32SHong Zhang    Input Parameter:
61644a658b32SHong Zhang .  ts - the TS context obtained from TSCreate()
61654a658b32SHong Zhang 
61664a658b32SHong Zhang    Output Parameters:
61674a658b32SHong Zhang +  nsol - the number of solutions
61684a658b32SHong Zhang -  Sols - the solution vectors
61694a658b32SHong Zhang 
61704a658b32SHong Zhang    Level: beginner
61714a658b32SHong Zhang 
617240bd4cedSHong Zhang    Notes:
617340bd4cedSHong Zhang     Both nsol and Sols can be NULL.
617440bd4cedSHong Zhang     Some time points in the time span may be skipped by TS so that nsol is less than the number of points specified by TSSetTimeSpan(). For example, manipulating the step size, especially with a reduced precision, may cause TS to step over certain points in the span.
61754a658b32SHong Zhang 
6176db781477SPatrick Sanan .seealso: `TSSetTimeSpan()`
61774a658b32SHong Zhang @*/
6178*d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetTimeSpanSolutions(TS ts, PetscInt *nsol, Vec **Sols)
6179*d71ae5a4SJacob Faibussowitsch {
61804a658b32SHong Zhang   PetscFunctionBegin;
61814a658b32SHong Zhang   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
61824a658b32SHong Zhang   if (nsol) PetscValidIntPointer(nsol, 2);
61834a658b32SHong Zhang   if (Sols) PetscValidPointer(Sols, 3);
61844a658b32SHong Zhang   if (!ts->tspan) {
61854a658b32SHong Zhang     if (nsol) *nsol = 0;
61864a658b32SHong Zhang     if (Sols) *Sols = NULL;
61874a658b32SHong Zhang   } else {
618840bd4cedSHong Zhang     if (nsol) *nsol = ts->tspan->spanctr;
61894a658b32SHong Zhang     if (Sols) *Sols = ts->tspan->vecs_sol;
61904a658b32SHong Zhang   }
61914a658b32SHong Zhang   PetscFunctionReturn(0);
61924a658b32SHong Zhang }
6193