Actual source code: ts.c
petsc-3.7.2 2016-06-05
2: #include <petsc/private/tsimpl.h> /*I "petscts.h" I*/
3: #include <petscdmshell.h>
4: #include <petscdmda.h>
5: #include <petscviewer.h>
6: #include <petscdraw.h>
8: /* Logging support */
9: PetscClassId TS_CLASSID, DMTS_CLASSID;
10: PetscLogEvent TS_AdjointStep, TS_Step, TS_PseudoComputeTimeStep, TS_FunctionEval, TS_JacobianEval;
12: const char *const TSExactFinalTimeOptions[] = {"UNSPECIFIED","STEPOVER","INTERPOLATE","MATCHSTEP","TSExactFinalTimeOption","TS_EXACTFINALTIME_",0};
14: struct _n_TSMonitorDrawCtx {
15: PetscViewer viewer;
16: Vec initialsolution;
17: PetscBool showinitial;
18: PetscInt howoften; /* when > 0 uses step % howoften, when negative only final solution plotted */
19: PetscBool showtimestepandtime;
20: };
24: /*@C
25: TSMonitorSetFromOptions - Sets a monitor function and viewer appropriate for the type indicated by the user
27: Collective on TS
29: Input Parameters:
30: + ts - TS object you wish to monitor
31: . name - the monitor type one is seeking
32: . help - message indicating what monitoring is done
33: . manual - manual page for the monitor
34: . monitor - the monitor function
35: - monitorsetup - a function that is called once ONLY if the user selected this monitor that may set additional features of the TS or PetscViewer objects
37: Level: developer
39: .seealso: PetscOptionsGetViewer(), PetscOptionsGetReal(), PetscOptionsHasName(), PetscOptionsGetString(),
40: PetscOptionsGetIntArray(), PetscOptionsGetRealArray(), PetscOptionsBool()
41: PetscOptionsInt(), PetscOptionsString(), PetscOptionsReal(), PetscOptionsBool(),
42: PetscOptionsName(), PetscOptionsBegin(), PetscOptionsEnd(), PetscOptionsHead(),
43: PetscOptionsStringArray(),PetscOptionsRealArray(), PetscOptionsScalar(),
44: PetscOptionsBoolGroupBegin(), PetscOptionsBoolGroup(), PetscOptionsBoolGroupEnd(),
45: PetscOptionsFList(), PetscOptionsEList()
46: @*/
47: PetscErrorCode TSMonitorSetFromOptions(TS ts,const char name[],const char help[], const char manual[],PetscErrorCode (*monitor)(TS,PetscInt,PetscReal,Vec,PetscViewerAndFormat*),PetscErrorCode (*monitorsetup)(TS,PetscViewerAndFormat*))
48: {
49: PetscErrorCode ierr;
50: PetscViewer viewer;
51: PetscViewerFormat format;
52: PetscBool flg;
55: PetscOptionsGetViewer(PetscObjectComm((PetscObject)ts),((PetscObject)ts)->prefix,name,&viewer,&format,&flg);
56: if (flg) {
57: PetscViewerAndFormat *vf;
58: PetscViewerAndFormatCreate(viewer,format,&vf);
59: PetscObjectDereference((PetscObject)viewer);
60: if (monitorsetup) {
61: (*monitorsetup)(ts,vf);
62: }
63: TSMonitorSet(ts,(PetscErrorCode (*)(TS,PetscInt,PetscReal,Vec,void*))monitor,vf,(PetscErrorCode (*)(void**))PetscViewerAndFormatDestroy);
64: }
65: return(0);
66: }
70: /*@C
71: TSAdjointMonitorSetFromOptions - Sets a monitor function and viewer appropriate for the type indicated by the user
73: Collective on TS
75: Input Parameters:
76: + ts - TS object you wish to monitor
77: . name - the monitor type one is seeking
78: . help - message indicating what monitoring is done
79: . manual - manual page for the monitor
80: . monitor - the monitor function
81: - monitorsetup - a function that is called once ONLY if the user selected this monitor that may set additional features of the TS or PetscViewer objects
83: Level: developer
85: .seealso: PetscOptionsGetViewer(), PetscOptionsGetReal(), PetscOptionsHasName(), PetscOptionsGetString(),
86: PetscOptionsGetIntArray(), PetscOptionsGetRealArray(), PetscOptionsBool()
87: PetscOptionsInt(), PetscOptionsString(), PetscOptionsReal(), PetscOptionsBool(),
88: PetscOptionsName(), PetscOptionsBegin(), PetscOptionsEnd(), PetscOptionsHead(),
89: PetscOptionsStringArray(),PetscOptionsRealArray(), PetscOptionsScalar(),
90: PetscOptionsBoolGroupBegin(), PetscOptionsBoolGroup(), PetscOptionsBoolGroupEnd(),
91: PetscOptionsFList(), PetscOptionsEList()
92: @*/
93: PetscErrorCode TSAdjointMonitorSetFromOptions(TS ts,const char name[],const char help[], const char manual[],PetscErrorCode (*monitor)(TS,PetscInt,PetscReal,Vec,PetscInt,Vec*,Vec*,PetscViewerAndFormat*),PetscErrorCode (*monitorsetup)(TS,PetscViewerAndFormat*))
94: {
95: PetscErrorCode ierr;
96: PetscViewer viewer;
97: PetscViewerFormat format;
98: PetscBool flg;
101: PetscOptionsGetViewer(PetscObjectComm((PetscObject)ts),((PetscObject)ts)->prefix,name,&viewer,&format,&flg);
102: if (flg) {
103: PetscViewerAndFormat *vf;
104: PetscViewerAndFormatCreate(viewer,format,&vf);
105: PetscObjectDereference((PetscObject)viewer);
106: if (monitorsetup) {
107: (*monitorsetup)(ts,vf);
108: }
109: TSAdjointMonitorSet(ts,(PetscErrorCode (*)(TS,PetscInt,PetscReal,Vec,PetscInt,Vec*,Vec*,void*))monitor,vf,(PetscErrorCode (*)(void**))PetscViewerAndFormatDestroy);
110: }
111: return(0);
112: }
116: /*@
117: TSSetFromOptions - Sets various TS parameters from user options.
119: Collective on TS
121: Input Parameter:
122: . ts - the TS context obtained from TSCreate()
124: Options Database Keys:
125: + -ts_type <type> - TSEULER, TSBEULER, TSSUNDIALS, TSPSEUDO, TSCN, TSRK, TSTHETA, TSALPHA, TSGL, TSSSP
126: . -ts_save_trajectory - checkpoint the solution at each time-step
127: . -ts_max_steps <maxsteps> - maximum number of time-steps to take
128: . -ts_final_time <time> - maximum time to compute to
129: . -ts_dt <dt> - initial time step
130: . -ts_exact_final_time <stepover,interpolate,matchstep> whether to stop at the exact given final time and how to compute the solution at that ti,e
131: . -ts_max_snes_failures <maxfailures> - Maximum number of nonlinear solve failures allowed
132: . -ts_max_reject <maxrejects> - Maximum number of step rejections before step fails
133: . -ts_error_if_step_fails <true,false> - Error if no step succeeds
134: . -ts_rtol <rtol> - relative tolerance for local truncation error
135: . -ts_atol <atol> Absolute tolerance for local truncation error
136: . -ts_adjoint_solve <yes,no> After solving the ODE/DAE solve the adjoint problem (requires -ts_save_trajectory)
137: . -ts_fd_color - Use finite differences with coloring to compute IJacobian
138: . -ts_monitor - print information at each timestep
139: . -ts_monitor_lg_solution - Monitor solution graphically
140: . -ts_monitor_lg_error - Monitor error graphically
141: . -ts_monitor_lg_timestep - Monitor timestep size graphically
142: . -ts_monitor_lg_snes_iterations - Monitor number nonlinear iterations for each timestep graphically
143: . -ts_monitor_lg_ksp_iterations - Monitor number nonlinear iterations for each timestep graphically
144: . -ts_monitor_sp_eig - Monitor eigenvalues of linearized operator graphically
145: . -ts_monitor_draw_solution - Monitor solution graphically
146: . -ts_monitor_draw_solution_phase <xleft,yleft,xright,yright> - Monitor solution graphically with phase diagram, requires problem with exactly 2 degrees of freedom
147: . -ts_monitor_draw_error - Monitor error graphically, requires use to have provided TSSetSolutionFunction()
148: . -ts_monitor_solution [ascii binary draw][:filename][:viewerformat] - monitors the solution at each timestep
149: . -ts_monitor_solution_vtk <filename.vts> - Save each time step to a binary file, use filename-%%03D.vts
150: . -ts_monitor_envelope - determine maximum and minimum value of each component of the solution over the solution time
151: . -ts_adjoint_monitor - print information at each adjoint time step
152: - -ts_adjoint_monitor_draw_sensi - monitor the sensitivity of the first cost function wrt initial conditions (lambda[0]) graphically
154: Developer Note: We should unify all the -ts_monitor options in the way that -xxx_view has been unified
156: Level: beginner
158: .keywords: TS, timestep, set, options, database
160: .seealso: TSGetType()
161: @*/
162: PetscErrorCode TSSetFromOptions(TS ts)
163: {
164: PetscBool opt,flg,tflg;
165: PetscErrorCode ierr;
166: char monfilename[PETSC_MAX_PATH_LEN];
167: PetscReal time_step;
168: TSExactFinalTimeOption eftopt;
169: char dir[16];
170: TSIFunction ifun;
171: const char *defaultType;
172: char typeName[256];
177: TSRegisterAll();
178: TSGetIFunction(ts,NULL,&ifun,NULL);
180: PetscObjectOptionsBegin((PetscObject)ts);
181: if (((PetscObject)ts)->type_name)
182: defaultType = ((PetscObject)ts)->type_name;
183: else
184: defaultType = ifun ? TSBEULER : TSEULER;
185: PetscOptionsFList("-ts_type","TS method","TSSetType",TSList,defaultType,typeName,256,&opt);
186: if (opt) {
187: TSSetType(ts,typeName);
188: } else {
189: TSSetType(ts,defaultType);
190: }
192: /* Handle generic TS options */
193: PetscOptionsInt("-ts_max_steps","Maximum number of time steps","TSSetDuration",ts->max_steps,&ts->max_steps,NULL);
194: PetscOptionsReal("-ts_final_time","Time to run to","TSSetDuration",ts->max_time,&ts->max_time,NULL);
195: PetscOptionsReal("-ts_init_time","Initial time","TSSetTime",ts->ptime,&ts->ptime,NULL);
196: PetscOptionsReal("-ts_dt","Initial time step","TSSetTimeStep",ts->time_step,&time_step,&flg);
197: if (flg) {TSSetTimeStep(ts,time_step);}
198: PetscOptionsEnum("-ts_exact_final_time","Option for handling of final time step","TSSetExactFinalTime",TSExactFinalTimeOptions,(PetscEnum)ts->exact_final_time,(PetscEnum*)&eftopt,&flg);
199: if (flg) {TSSetExactFinalTime(ts,eftopt);}
200: PetscOptionsInt("-ts_max_snes_failures","Maximum number of nonlinear solve failures","TSSetMaxSNESFailures",ts->max_snes_failures,&ts->max_snes_failures,NULL);
201: PetscOptionsInt("-ts_max_reject","Maximum number of step rejections before step fails","TSSetMaxStepRejections",ts->max_reject,&ts->max_reject,NULL);
202: PetscOptionsBool("-ts_error_if_step_fails","Error if no step succeeds","TSSetErrorIfStepFails",ts->errorifstepfailed,&ts->errorifstepfailed,NULL);
203: PetscOptionsReal("-ts_rtol","Relative tolerance for local truncation error","TSSetTolerances",ts->rtol,&ts->rtol,NULL);
204: PetscOptionsReal("-ts_atol","Absolute tolerance for local truncation error","TSSetTolerances",ts->atol,&ts->atol,NULL);
206: #if defined(PETSC_HAVE_SAWS)
207: {
208: PetscBool set;
209: flg = PETSC_FALSE;
210: PetscOptionsBool("-ts_saws_block","Block for SAWs memory snooper at end of TSSolve","PetscObjectSAWsBlock",((PetscObject)ts)->amspublishblock,&flg,&set);
211: if (set) {
212: PetscObjectSAWsSetBlock((PetscObject)ts,flg);
213: }
214: }
215: #endif
217: /* Monitor options */
218: TSMonitorSetFromOptions(ts,"-ts_monitor","Monitor time and timestep size","TSMonitorDefault",TSMonitorDefault,NULL);
219: TSMonitorSetFromOptions(ts,"-ts_monitor_solution","View the solution at each timestep","TSMonitorSolution",TSMonitorSolution,NULL);
220: TSAdjointMonitorSetFromOptions(ts,"-ts_adjoint_monitor","Monitor adjoint timestep size","TSAdjointMonitorDefault",TSAdjointMonitorDefault,NULL);
222: PetscOptionsString("-ts_monitor_python","Use Python function","TSMonitorSet",0,monfilename,PETSC_MAX_PATH_LEN,&flg);
223: if (flg) {PetscPythonMonitorSet((PetscObject)ts,monfilename);}
225: PetscOptionsName("-ts_monitor_lg_solution","Monitor solution graphically","TSMonitorLGSolution",&opt);
226: if (opt) {
227: TSMonitorLGCtx ctx;
228: PetscInt howoften = 1;
230: PetscOptionsInt("-ts_monitor_lg_solution","Monitor solution graphically","TSMonitorLGSolution",howoften,&howoften,NULL);
231: TSMonitorLGCtxCreate(PETSC_COMM_SELF,0,0,PETSC_DECIDE,PETSC_DECIDE,400,300,howoften,&ctx);
232: TSMonitorSet(ts,TSMonitorLGSolution,ctx,(PetscErrorCode (*)(void**))TSMonitorLGCtxDestroy);
233: }
235: PetscOptionsName("-ts_monitor_lg_error","Monitor error graphically","TSMonitorLGError",&opt);
236: if (opt) {
237: TSMonitorLGCtx ctx;
238: PetscInt howoften = 1;
240: PetscOptionsInt("-ts_monitor_lg_error","Monitor error graphically","TSMonitorLGError",howoften,&howoften,NULL);
241: TSMonitorLGCtxCreate(PETSC_COMM_SELF,0,0,PETSC_DECIDE,PETSC_DECIDE,400,300,howoften,&ctx);
242: TSMonitorSet(ts,TSMonitorLGError,ctx,(PetscErrorCode (*)(void**))TSMonitorLGCtxDestroy);
243: }
245: PetscOptionsName("-ts_monitor_lg_timestep","Monitor timestep size graphically","TSMonitorLGTimeStep",&opt);
246: if (opt) {
247: TSMonitorLGCtx ctx;
248: PetscInt howoften = 1;
250: PetscOptionsInt("-ts_monitor_lg_timestep","Monitor timestep size graphically","TSMonitorLGTimeStep",howoften,&howoften,NULL);
251: TSMonitorLGCtxCreate(PetscObjectComm((PetscObject)ts),NULL,NULL,PETSC_DECIDE,PETSC_DECIDE,400,300,howoften,&ctx);
252: TSMonitorSet(ts,TSMonitorLGTimeStep,ctx,(PetscErrorCode (*)(void**))TSMonitorLGCtxDestroy);
253: }
254: PetscOptionsName("-ts_monitor_lg_snes_iterations","Monitor number nonlinear iterations for each timestep graphically","TSMonitorLGSNESIterations",&opt);
255: if (opt) {
256: TSMonitorLGCtx ctx;
257: PetscInt howoften = 1;
259: PetscOptionsInt("-ts_monitor_lg_snes_iterations","Monitor number nonlinear iterations for each timestep graphically","TSMonitorLGSNESIterations",howoften,&howoften,NULL);
260: TSMonitorLGCtxCreate(PetscObjectComm((PetscObject)ts),NULL,NULL,PETSC_DECIDE,PETSC_DECIDE,400,300,howoften,&ctx);
261: TSMonitorSet(ts,TSMonitorLGSNESIterations,ctx,(PetscErrorCode (*)(void**))TSMonitorLGCtxDestroy);
262: }
263: PetscOptionsName("-ts_monitor_lg_ksp_iterations","Monitor number nonlinear iterations for each timestep graphically","TSMonitorLGKSPIterations",&opt);
264: if (opt) {
265: TSMonitorLGCtx ctx;
266: PetscInt howoften = 1;
268: PetscOptionsInt("-ts_monitor_lg_ksp_iterations","Monitor number nonlinear iterations for each timestep graphically","TSMonitorLGKSPIterations",howoften,&howoften,NULL);
269: TSMonitorLGCtxCreate(PetscObjectComm((PetscObject)ts),NULL,NULL,PETSC_DECIDE,PETSC_DECIDE,400,300,howoften,&ctx);
270: TSMonitorSet(ts,TSMonitorLGKSPIterations,ctx,(PetscErrorCode (*)(void**))TSMonitorLGCtxDestroy);
271: }
272: PetscOptionsName("-ts_monitor_sp_eig","Monitor eigenvalues of linearized operator graphically","TSMonitorSPEig",&opt);
273: if (opt) {
274: TSMonitorSPEigCtx ctx;
275: PetscInt howoften = 1;
277: PetscOptionsInt("-ts_monitor_sp_eig","Monitor eigenvalues of linearized operator graphically","TSMonitorSPEig",howoften,&howoften,NULL);
278: TSMonitorSPEigCtxCreate(PETSC_COMM_SELF,0,0,PETSC_DECIDE,PETSC_DECIDE,300,300,howoften,&ctx);
279: TSMonitorSet(ts,TSMonitorSPEig,ctx,(PetscErrorCode (*)(void**))TSMonitorSPEigCtxDestroy);
280: }
281: opt = PETSC_FALSE;
282: PetscOptionsName("-ts_monitor_draw_solution","Monitor solution graphically","TSMonitorDrawSolution",&opt);
283: if (opt) {
284: TSMonitorDrawCtx ctx;
285: PetscInt howoften = 1;
287: PetscOptionsInt("-ts_monitor_draw_solution","Monitor solution graphically","TSMonitorDrawSolution",howoften,&howoften,NULL);
288: TSMonitorDrawCtxCreate(PetscObjectComm((PetscObject)ts),0,0,PETSC_DECIDE,PETSC_DECIDE,300,300,howoften,&ctx);
289: TSMonitorSet(ts,TSMonitorDrawSolution,ctx,(PetscErrorCode (*)(void**))TSMonitorDrawCtxDestroy);
290: }
291: opt = PETSC_FALSE;
292: PetscOptionsName("-ts_adjoint_monitor_draw_sensi","Monitor adjoint sensitivities (lambda only) graphically","TSAdjointMonitorDrawSensi",&opt);
293: if (opt) {
294: TSMonitorDrawCtx ctx;
295: PetscInt howoften = 1;
297: PetscOptionsInt("-ts_adjoint_monitor_draw_sensi","Monitor adjoint sensitivities (lambda only) graphically","TSAdjointMonitorDrawSensi",howoften,&howoften,NULL);
298: TSMonitorDrawCtxCreate(PetscObjectComm((PetscObject)ts),0,0,PETSC_DECIDE,PETSC_DECIDE,300,300,howoften,&ctx);
299: TSAdjointMonitorSet(ts,TSAdjointMonitorDrawSensi,ctx,(PetscErrorCode (*)(void**))TSMonitorDrawCtxDestroy);
300: }
301: opt = PETSC_FALSE;
302: PetscOptionsName("-ts_monitor_draw_solution_phase","Monitor solution graphically","TSMonitorDrawSolutionPhase",&opt);
303: if (opt) {
304: TSMonitorDrawCtx ctx;
305: PetscReal bounds[4];
306: PetscInt n = 4;
307: PetscDraw draw;
308: PetscDrawAxis axis;
310: PetscOptionsRealArray("-ts_monitor_draw_solution_phase","Monitor solution graphically","TSMonitorDrawSolutionPhase",bounds,&n,NULL);
311: if (n != 4) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_ARG_WRONG,"Must provide bounding box of phase field");
312: TSMonitorDrawCtxCreate(PetscObjectComm((PetscObject)ts),0,0,PETSC_DECIDE,PETSC_DECIDE,300,300,1,&ctx);
313: PetscViewerDrawGetDraw(ctx->viewer,0,&draw);
314: PetscViewerDrawGetDrawAxis(ctx->viewer,0,&axis);
315: PetscDrawAxisSetLimits(axis,bounds[0],bounds[2],bounds[1],bounds[3]);
316: PetscDrawAxisSetLabels(axis,"Phase Diagram","Variable 1","Variable 2");
317: TSMonitorSet(ts,TSMonitorDrawSolutionPhase,ctx,(PetscErrorCode (*)(void**))TSMonitorDrawCtxDestroy);
318: }
319: opt = PETSC_FALSE;
320: PetscOptionsName("-ts_monitor_draw_error","Monitor error graphically","TSMonitorDrawError",&opt);
321: if (opt) {
322: TSMonitorDrawCtx ctx;
323: PetscInt howoften = 1;
325: PetscOptionsInt("-ts_monitor_draw_error","Monitor error graphically","TSMonitorDrawError",howoften,&howoften,NULL);
326: TSMonitorDrawCtxCreate(PetscObjectComm((PetscObject)ts),0,0,PETSC_DECIDE,PETSC_DECIDE,300,300,howoften,&ctx);
327: TSMonitorSet(ts,TSMonitorDrawError,ctx,(PetscErrorCode (*)(void**))TSMonitorDrawCtxDestroy);
328: }
330: opt = PETSC_FALSE;
331: PetscOptionsString("-ts_monitor_solution_vtk","Save each time step to a binary file, use filename-%%03D.vts","TSMonitorSolutionVTK",0,monfilename,PETSC_MAX_PATH_LEN,&flg);
332: if (flg) {
333: const char *ptr,*ptr2;
334: char *filetemplate;
335: if (!monfilename[0]) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_USER,"-ts_monitor_solution_vtk requires a file template, e.g. filename-%%03D.vts");
336: /* Do some cursory validation of the input. */
337: PetscStrstr(monfilename,"%",(char**)&ptr);
338: if (!ptr) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_USER,"-ts_monitor_solution_vtk requires a file template, e.g. filename-%%03D.vts");
339: for (ptr++; ptr && *ptr; ptr++) {
340: PetscStrchr("DdiouxX",*ptr,(char**)&ptr2);
341: if (!ptr2 && (*ptr < '0' || '9' < *ptr)) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_USER,"Invalid file template argument to -ts_monitor_solution_vtk, should look like filename-%%03D.vts");
342: if (ptr2) break;
343: }
344: PetscStrallocpy(monfilename,&filetemplate);
345: TSMonitorSet(ts,TSMonitorSolutionVTK,filetemplate,(PetscErrorCode (*)(void**))TSMonitorSolutionVTKDestroy);
346: }
348: PetscOptionsString("-ts_monitor_dmda_ray","Display a ray of the solution","None","y=0",dir,16,&flg);
349: if (flg) {
350: TSMonitorDMDARayCtx *rayctx;
351: int ray = 0;
352: DMDADirection ddir;
353: DM da;
354: PetscMPIInt rank;
356: if (dir[1] != '=') SETERRQ1(PetscObjectComm((PetscObject)ts),PETSC_ERR_ARG_WRONG,"Unknown ray %s",dir);
357: if (dir[0] == 'x') ddir = DMDA_X;
358: else if (dir[0] == 'y') ddir = DMDA_Y;
359: else SETERRQ1(PetscObjectComm((PetscObject)ts),PETSC_ERR_ARG_WRONG,"Unknown ray %s",dir);
360: sscanf(dir+2,"%d",&ray);
362: PetscInfo2(((PetscObject)ts),"Displaying DMDA ray %c = %D\n",dir[0],ray);
363: PetscNew(&rayctx);
364: TSGetDM(ts,&da);
365: DMDAGetRay(da,ddir,ray,&rayctx->ray,&rayctx->scatter);
366: MPI_Comm_rank(PetscObjectComm((PetscObject)ts),&rank);
367: if (!rank) {
368: PetscViewerDrawOpen(PETSC_COMM_SELF,0,0,0,0,600,300,&rayctx->viewer);
369: }
370: rayctx->lgctx = NULL;
371: TSMonitorSet(ts,TSMonitorDMDARay,rayctx,TSMonitorDMDARayDestroy);
372: }
373: PetscOptionsString("-ts_monitor_lg_dmda_ray","Display a ray of the solution","None","x=0",dir,16,&flg);
374: if (flg) {
375: TSMonitorDMDARayCtx *rayctx;
376: int ray = 0;
377: DMDADirection ddir;
378: DM da;
379: PetscInt howoften = 1;
381: if (dir[1] != '=') SETERRQ1(PetscObjectComm((PetscObject) ts), PETSC_ERR_ARG_WRONG, "Malformed ray %s", dir);
382: if (dir[0] == 'x') ddir = DMDA_X;
383: else if (dir[0] == 'y') ddir = DMDA_Y;
384: else SETERRQ1(PetscObjectComm((PetscObject) ts), PETSC_ERR_ARG_WRONG, "Unknown ray direction %s", dir);
385: sscanf(dir+2, "%d", &ray);
387: PetscInfo2(((PetscObject) ts),"Displaying LG DMDA ray %c = %D\n", dir[0], ray);
388: PetscNew(&rayctx);
389: TSGetDM(ts, &da);
390: DMDAGetRay(da, ddir, ray, &rayctx->ray, &rayctx->scatter);
391: TSMonitorLGCtxCreate(PETSC_COMM_SELF,0,0,PETSC_DECIDE,PETSC_DECIDE,600,400,howoften,&rayctx->lgctx);
392: TSMonitorSet(ts, TSMonitorLGDMDARay, rayctx, TSMonitorDMDARayDestroy);
393: }
395: PetscOptionsName("-ts_monitor_envelope","Monitor maximum and minimum value of each component of the solution","TSMonitorEnvelope",&opt);
396: if (opt) {
397: TSMonitorEnvelopeCtx ctx;
399: TSMonitorEnvelopeCtxCreate(ts,&ctx);
400: TSMonitorSet(ts,TSMonitorEnvelope,ctx,(PetscErrorCode (*)(void**))TSMonitorEnvelopeCtxDestroy);
401: }
403: flg = PETSC_FALSE;
404: PetscOptionsBool("-ts_fd_color", "Use finite differences with coloring to compute IJacobian", "TSComputeJacobianDefaultColor", flg, &flg, NULL);
405: if (flg) {
406: DM dm;
407: DMTS tdm;
409: TSGetDM(ts, &dm);
410: DMGetDMTS(dm, &tdm);
411: tdm->ijacobianctx = NULL;
412: TSSetIJacobian(ts, NULL, NULL, TSComputeIJacobianDefaultColor, 0);
413: PetscInfo(ts, "Setting default finite difference coloring Jacobian matrix\n");
414: }
416: if (ts->adapt) {
417: TSAdaptSetFromOptions(PetscOptionsObject,ts->adapt);
418: }
420: /* Handle specific TS options */
421: if (ts->ops->setfromoptions) {
422: (*ts->ops->setfromoptions)(PetscOptionsObject,ts);
423: }
425: /* TS trajectory must be set after TS, since it may use some TS options above */
426: tflg = ts->trajectory ? PETSC_TRUE : PETSC_FALSE;
427: PetscOptionsBool("-ts_save_trajectory","Save the solution at each timestep","TSSetSaveTrajectory",tflg,&tflg,NULL);
428: if (tflg) {
429: TSSetSaveTrajectory(ts);
430: }
431: tflg = ts->adjoint_solve ? PETSC_TRUE : PETSC_FALSE;
432: PetscOptionsBool("-ts_adjoint_solve","Solve the adjoint problem immediately after solving the forward problem","",tflg,&tflg,&flg);
433: if (flg) {
434: TSSetSaveTrajectory(ts);
435: ts->adjoint_solve = tflg;
436: }
438: /* process any options handlers added with PetscObjectAddOptionsHandler() */
439: PetscObjectProcessOptionsHandlers(PetscOptionsObject,(PetscObject)ts);
440: PetscOptionsEnd();
442: if (ts->trajectory) {
443: TSTrajectorySetFromOptions(ts->trajectory,ts);
444: }
446: TSGetSNES(ts,&ts->snes);
447: if (ts->problem_type == TS_LINEAR) {SNESSetType(ts->snes,SNESKSPONLY);}
448: SNESSetFromOptions(ts->snes);
449: return(0);
450: }
454: /*@
455: TSSetSaveTrajectory - Causes the TS to save its solutions as it iterates forward in time in a TSTrajectory object
457: Collective on TS
459: Input Parameters:
460: . ts - the TS context obtained from TSCreate()
462: Note: This routine should be called after all TS options have been set
464: Level: intermediate
466: .seealso: TSGetTrajectory(), TSAdjointSolve()
468: .keywords: TS, set, checkpoint,
469: @*/
470: PetscErrorCode TSSetSaveTrajectory(TS ts)
471: {
476: if (!ts->trajectory) {
477: TSTrajectoryCreate(PetscObjectComm((PetscObject)ts),&ts->trajectory);
478: TSTrajectorySetFromOptions(ts->trajectory,ts);
479: }
480: return(0);
481: }
485: /*@
486: TSComputeRHSJacobian - Computes the Jacobian matrix that has been
487: set with TSSetRHSJacobian().
489: Collective on TS and Vec
491: Input Parameters:
492: + ts - the TS context
493: . t - current timestep
494: - U - input vector
496: Output Parameters:
497: + A - Jacobian matrix
498: . B - optional preconditioning matrix
499: - flag - flag indicating matrix structure
501: Notes:
502: Most users should not need to explicitly call this routine, as it
503: is used internally within the nonlinear solvers.
505: See KSPSetOperators() for important information about setting the
506: flag parameter.
508: Level: developer
510: .keywords: SNES, compute, Jacobian, matrix
512: .seealso: TSSetRHSJacobian(), KSPSetOperators()
513: @*/
514: PetscErrorCode TSComputeRHSJacobian(TS ts,PetscReal t,Vec U,Mat A,Mat B)
515: {
517: PetscObjectState Ustate;
518: DM dm;
519: DMTS tsdm;
520: TSRHSJacobian rhsjacobianfunc;
521: void *ctx;
522: TSIJacobian ijacobianfunc;
523: TSRHSFunction rhsfunction;
529: TSGetDM(ts,&dm);
530: DMGetDMTS(dm,&tsdm);
531: DMTSGetRHSJacobian(dm,&rhsjacobianfunc,&ctx);
532: DMTSGetIJacobian(dm,&ijacobianfunc,NULL);
533: DMTSGetRHSFunction(dm,&rhsfunction,&ctx);
534: PetscObjectStateGet((PetscObject)U,&Ustate);
535: if (ts->rhsjacobian.time == t && (ts->problem_type == TS_LINEAR || (ts->rhsjacobian.X == U && ts->rhsjacobian.Xstate == Ustate)) && (rhsfunction != TSComputeRHSFunctionLinear)) {
536: return(0);
537: }
539: if (!rhsjacobianfunc && !ijacobianfunc) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_USER,"Must call TSSetRHSJacobian() and / or TSSetIJacobian()");
541: if (ts->rhsjacobian.reuse) {
542: MatShift(A,-ts->rhsjacobian.shift);
543: MatScale(A,1./ts->rhsjacobian.scale);
544: if (A != B) {
545: MatShift(B,-ts->rhsjacobian.shift);
546: MatScale(B,1./ts->rhsjacobian.scale);
547: }
548: ts->rhsjacobian.shift = 0;
549: ts->rhsjacobian.scale = 1.;
550: }
552: if (rhsjacobianfunc) {
553: PetscBool missing;
554: PetscLogEventBegin(TS_JacobianEval,ts,U,A,B);
555: PetscStackPush("TS user Jacobian function");
556: (*rhsjacobianfunc)(ts,t,U,A,B,ctx);
557: PetscStackPop;
558: PetscLogEventEnd(TS_JacobianEval,ts,U,A,B);
559: if (A) {
560: MatMissingDiagonal(A,&missing,NULL);
561: if (missing) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Amat passed to TSSetRHSJacobian() must have all diagonal entries set, if they are zero you must still set them with a zero value");
562: }
563: if (B && B != A) {
564: MatMissingDiagonal(B,&missing,NULL);
565: if (missing) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Bmat passed to TSSetRHSJacobian() must have all diagonal entries set, if they are zero you must still set them with a zero value");
566: }
567: } else {
568: MatZeroEntries(A);
569: if (A != B) {MatZeroEntries(B);}
570: }
571: ts->rhsjacobian.time = t;
572: ts->rhsjacobian.X = U;
573: PetscObjectStateGet((PetscObject)U,&ts->rhsjacobian.Xstate);
574: return(0);
575: }
579: /*@
580: TSComputeRHSFunction - Evaluates the right-hand-side function.
582: Collective on TS and Vec
584: Input Parameters:
585: + ts - the TS context
586: . t - current time
587: - U - state vector
589: Output Parameter:
590: . y - right hand side
592: Note:
593: Most users should not need to explicitly call this routine, as it
594: is used internally within the nonlinear solvers.
596: Level: developer
598: .keywords: TS, compute
600: .seealso: TSSetRHSFunction(), TSComputeIFunction()
601: @*/
602: PetscErrorCode TSComputeRHSFunction(TS ts,PetscReal t,Vec U,Vec y)
603: {
605: TSRHSFunction rhsfunction;
606: TSIFunction ifunction;
607: void *ctx;
608: DM dm;
614: TSGetDM(ts,&dm);
615: DMTSGetRHSFunction(dm,&rhsfunction,&ctx);
616: DMTSGetIFunction(dm,&ifunction,NULL);
618: if (!rhsfunction && !ifunction) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_USER,"Must call TSSetRHSFunction() and / or TSSetIFunction()");
620: PetscLogEventBegin(TS_FunctionEval,ts,U,y,0);
621: if (rhsfunction) {
622: PetscStackPush("TS user right-hand-side function");
623: (*rhsfunction)(ts,t,U,y,ctx);
624: PetscStackPop;
625: } else {
626: VecZeroEntries(y);
627: }
629: PetscLogEventEnd(TS_FunctionEval,ts,U,y,0);
630: return(0);
631: }
635: /*@
636: TSComputeSolutionFunction - Evaluates the solution function.
638: Collective on TS and Vec
640: Input Parameters:
641: + ts - the TS context
642: - t - current time
644: Output Parameter:
645: . U - the solution
647: Note:
648: Most users should not need to explicitly call this routine, as it
649: is used internally within the nonlinear solvers.
651: Level: developer
653: .keywords: TS, compute
655: .seealso: TSSetSolutionFunction(), TSSetRHSFunction(), TSComputeIFunction()
656: @*/
657: PetscErrorCode TSComputeSolutionFunction(TS ts,PetscReal t,Vec U)
658: {
659: PetscErrorCode ierr;
660: TSSolutionFunction solutionfunction;
661: void *ctx;
662: DM dm;
667: TSGetDM(ts,&dm);
668: DMTSGetSolutionFunction(dm,&solutionfunction,&ctx);
670: if (solutionfunction) {
671: PetscStackPush("TS user solution function");
672: (*solutionfunction)(ts,t,U,ctx);
673: PetscStackPop;
674: }
675: return(0);
676: }
679: /*@
680: TSComputeForcingFunction - Evaluates the forcing function.
682: Collective on TS and Vec
684: Input Parameters:
685: + ts - the TS context
686: - t - current time
688: Output Parameter:
689: . U - the function value
691: Note:
692: Most users should not need to explicitly call this routine, as it
693: is used internally within the nonlinear solvers.
695: Level: developer
697: .keywords: TS, compute
699: .seealso: TSSetSolutionFunction(), TSSetRHSFunction(), TSComputeIFunction()
700: @*/
701: PetscErrorCode TSComputeForcingFunction(TS ts,PetscReal t,Vec U)
702: {
703: PetscErrorCode ierr, (*forcing)(TS,PetscReal,Vec,void*);
704: void *ctx;
705: DM dm;
710: TSGetDM(ts,&dm);
711: DMTSGetForcingFunction(dm,&forcing,&ctx);
713: if (forcing) {
714: PetscStackPush("TS user forcing function");
715: (*forcing)(ts,t,U,ctx);
716: PetscStackPop;
717: }
718: return(0);
719: }
723: static PetscErrorCode TSGetRHSVec_Private(TS ts,Vec *Frhs)
724: {
725: Vec F;
729: *Frhs = NULL;
730: TSGetIFunction(ts,&F,NULL,NULL);
731: if (!ts->Frhs) {
732: VecDuplicate(F,&ts->Frhs);
733: }
734: *Frhs = ts->Frhs;
735: return(0);
736: }
740: static PetscErrorCode TSGetRHSMats_Private(TS ts,Mat *Arhs,Mat *Brhs)
741: {
742: Mat A,B;
746: if (Arhs) *Arhs = NULL;
747: if (Brhs) *Brhs = NULL;
748: TSGetIJacobian(ts,&A,&B,NULL,NULL);
749: if (Arhs) {
750: if (!ts->Arhs) {
751: MatDuplicate(A,MAT_DO_NOT_COPY_VALUES,&ts->Arhs);
752: }
753: *Arhs = ts->Arhs;
754: }
755: if (Brhs) {
756: if (!ts->Brhs) {
757: if (A != B) {
758: MatDuplicate(B,MAT_DO_NOT_COPY_VALUES,&ts->Brhs);
759: } else {
760: PetscObjectReference((PetscObject)ts->Arhs);
761: ts->Brhs = ts->Arhs;
762: }
763: }
764: *Brhs = ts->Brhs;
765: }
766: return(0);
767: }
771: /*@
772: TSComputeIFunction - Evaluates the DAE residual written in implicit form F(t,U,Udot)=0
774: Collective on TS and Vec
776: Input Parameters:
777: + ts - the TS context
778: . t - current time
779: . U - state vector
780: . Udot - time derivative of state vector
781: - imex - flag indicates if the method is IMEX so that the RHSFunction should be kept separate
783: Output Parameter:
784: . Y - right hand side
786: Note:
787: Most users should not need to explicitly call this routine, as it
788: is used internally within the nonlinear solvers.
790: If the user did did not write their equations in implicit form, this
791: function recasts them in implicit form.
793: Level: developer
795: .keywords: TS, compute
797: .seealso: TSSetIFunction(), TSComputeRHSFunction()
798: @*/
799: PetscErrorCode TSComputeIFunction(TS ts,PetscReal t,Vec U,Vec Udot,Vec Y,PetscBool imex)
800: {
802: TSIFunction ifunction;
803: TSRHSFunction rhsfunction;
804: void *ctx;
805: DM dm;
813: TSGetDM(ts,&dm);
814: DMTSGetIFunction(dm,&ifunction,&ctx);
815: DMTSGetRHSFunction(dm,&rhsfunction,NULL);
817: if (!rhsfunction && !ifunction) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_USER,"Must call TSSetRHSFunction() and / or TSSetIFunction()");
819: PetscLogEventBegin(TS_FunctionEval,ts,U,Udot,Y);
820: if (ifunction) {
821: PetscStackPush("TS user implicit function");
822: (*ifunction)(ts,t,U,Udot,Y,ctx);
823: PetscStackPop;
824: }
825: if (imex) {
826: if (!ifunction) {
827: VecCopy(Udot,Y);
828: }
829: } else if (rhsfunction) {
830: if (ifunction) {
831: Vec Frhs;
832: TSGetRHSVec_Private(ts,&Frhs);
833: TSComputeRHSFunction(ts,t,U,Frhs);
834: VecAXPY(Y,-1,Frhs);
835: } else {
836: TSComputeRHSFunction(ts,t,U,Y);
837: VecAYPX(Y,-1,Udot);
838: }
839: }
840: PetscLogEventEnd(TS_FunctionEval,ts,U,Udot,Y);
841: return(0);
842: }
846: /*@
847: TSComputeIJacobian - Evaluates the Jacobian of the DAE
849: Collective on TS and Vec
851: Input
852: Input Parameters:
853: + ts - the TS context
854: . t - current timestep
855: . U - state vector
856: . Udot - time derivative of state vector
857: . shift - shift to apply, see note below
858: - imex - flag indicates if the method is IMEX so that the RHSJacobian should be kept separate
860: Output Parameters:
861: + A - Jacobian matrix
862: . B - optional preconditioning matrix
863: - flag - flag indicating matrix structure
865: Notes:
866: If F(t,U,Udot)=0 is the DAE, the required Jacobian is
868: dF/dU + shift*dF/dUdot
870: Most users should not need to explicitly call this routine, as it
871: is used internally within the nonlinear solvers.
873: Level: developer
875: .keywords: TS, compute, Jacobian, matrix
877: .seealso: TSSetIJacobian()
878: @*/
879: PetscErrorCode TSComputeIJacobian(TS ts,PetscReal t,Vec U,Vec Udot,PetscReal shift,Mat A,Mat B,PetscBool imex)
880: {
882: TSIJacobian ijacobian;
883: TSRHSJacobian rhsjacobian;
884: DM dm;
885: void *ctx;
896: TSGetDM(ts,&dm);
897: DMTSGetIJacobian(dm,&ijacobian,&ctx);
898: DMTSGetRHSJacobian(dm,&rhsjacobian,NULL);
900: if (!rhsjacobian && !ijacobian) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_USER,"Must call TSSetRHSJacobian() and / or TSSetIJacobian()");
902: PetscLogEventBegin(TS_JacobianEval,ts,U,A,B);
903: if (ijacobian) {
904: PetscBool missing;
905: PetscStackPush("TS user implicit Jacobian");
906: (*ijacobian)(ts,t,U,Udot,shift,A,B,ctx);
907: PetscStackPop;
908: if (A) {
909: MatMissingDiagonal(A,&missing,NULL);
910: if (missing) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Amat passed to TSSetIJacobian() must have all diagonal entries set, if they are zero you must still set them with a zero value");
911: }
912: if (B && B != A) {
913: MatMissingDiagonal(B,&missing,NULL);
914: if (missing) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Bmat passed to TSSetIJacobian() must have all diagonal entries set, if they are zero you must still set them with a zero value");
915: }
916: }
917: if (imex) {
918: if (!ijacobian) { /* system was written as Udot = G(t,U) */
919: MatZeroEntries(A);
920: MatShift(A,shift);
921: if (A != B) {
922: MatZeroEntries(B);
923: MatShift(B,shift);
924: }
925: }
926: } else {
927: Mat Arhs = NULL,Brhs = NULL;
928: if (rhsjacobian) {
929: if (ijacobian) {
930: TSGetRHSMats_Private(ts,&Arhs,&Brhs);
931: } else {
932: TSGetIJacobian(ts,&Arhs,&Brhs,NULL,NULL);
933: }
934: TSComputeRHSJacobian(ts,t,U,Arhs,Brhs);
935: }
936: if (Arhs == A) { /* No IJacobian, so we only have the RHS matrix */
937: ts->rhsjacobian.scale = -1;
938: ts->rhsjacobian.shift = shift;
939: MatScale(A,-1);
940: MatShift(A,shift);
941: if (A != B) {
942: MatScale(B,-1);
943: MatShift(B,shift);
944: }
945: } else if (Arhs) { /* Both IJacobian and RHSJacobian */
946: MatStructure axpy = DIFFERENT_NONZERO_PATTERN;
947: if (!ijacobian) { /* No IJacobian provided, but we have a separate RHS matrix */
948: MatZeroEntries(A);
949: MatShift(A,shift);
950: if (A != B) {
951: MatZeroEntries(B);
952: MatShift(B,shift);
953: }
954: }
955: MatAXPY(A,-1,Arhs,axpy);
956: if (A != B) {
957: MatAXPY(B,-1,Brhs,axpy);
958: }
959: }
960: }
961: PetscLogEventEnd(TS_JacobianEval,ts,U,A,B);
962: return(0);
963: }
967: /*@C
968: TSSetRHSFunction - Sets the routine for evaluating the function,
969: where U_t = G(t,u).
971: Logically Collective on TS
973: Input Parameters:
974: + ts - the TS context obtained from TSCreate()
975: . r - vector to put the computed right hand side (or NULL to have it created)
976: . f - routine for evaluating the right-hand-side function
977: - ctx - [optional] user-defined context for private data for the
978: function evaluation routine (may be NULL)
980: Calling sequence of func:
981: $ func (TS ts,PetscReal t,Vec u,Vec F,void *ctx);
983: + t - current timestep
984: . u - input vector
985: . F - function vector
986: - ctx - [optional] user-defined function context
988: Level: beginner
990: Notes: You must call this function or TSSetIFunction() to define your ODE. You cannot use this function when solving a DAE.
992: .keywords: TS, timestep, set, right-hand-side, function
994: .seealso: TSSetRHSJacobian(), TSSetIJacobian(), TSSetIFunction()
995: @*/
996: PetscErrorCode TSSetRHSFunction(TS ts,Vec r,PetscErrorCode (*f)(TS,PetscReal,Vec,Vec,void*),void *ctx)
997: {
999: SNES snes;
1000: Vec ralloc = NULL;
1001: DM dm;
1007: TSGetDM(ts,&dm);
1008: DMTSSetRHSFunction(dm,f,ctx);
1009: TSGetSNES(ts,&snes);
1010: if (!r && !ts->dm && ts->vec_sol) {
1011: VecDuplicate(ts->vec_sol,&ralloc);
1012: r = ralloc;
1013: }
1014: SNESSetFunction(snes,r,SNESTSFormFunction,ts);
1015: VecDestroy(&ralloc);
1016: return(0);
1017: }
1021: /*@C
1022: TSSetSolutionFunction - Provide a function that computes the solution of the ODE or DAE
1024: Logically Collective on TS
1026: Input Parameters:
1027: + ts - the TS context obtained from TSCreate()
1028: . f - routine for evaluating the solution
1029: - ctx - [optional] user-defined context for private data for the
1030: function evaluation routine (may be NULL)
1032: Calling sequence of func:
1033: $ func (TS ts,PetscReal t,Vec u,void *ctx);
1035: + t - current timestep
1036: . u - output vector
1037: - ctx - [optional] user-defined function context
1039: Notes:
1040: This routine is used for testing accuracy of time integration schemes when you already know the solution.
1041: If analytic solutions are not known for your system, consider using the Method of Manufactured Solutions to
1042: create closed-form solutions with non-physical forcing terms.
1044: For low-dimensional problems solved in serial, such as small discrete systems, TSMonitorLGError() can be used to monitor the error history.
1046: Level: beginner
1048: .keywords: TS, timestep, set, right-hand-side, function
1050: .seealso: TSSetRHSJacobian(), TSSetIJacobian(), TSComputeSolutionFunction(), TSSetForcingFunction()
1051: @*/
1052: PetscErrorCode TSSetSolutionFunction(TS ts,PetscErrorCode (*f)(TS,PetscReal,Vec,void*),void *ctx)
1053: {
1055: DM dm;
1059: TSGetDM(ts,&dm);
1060: DMTSSetSolutionFunction(dm,f,ctx);
1061: return(0);
1062: }
1066: /*@C
1067: TSSetForcingFunction - Provide a function that computes a forcing term for a ODE or PDE
1069: Logically Collective on TS
1071: Input Parameters:
1072: + ts - the TS context obtained from TSCreate()
1073: . f - routine for evaluating the forcing function
1074: - ctx - [optional] user-defined context for private data for the
1075: function evaluation routine (may be NULL)
1077: Calling sequence of func:
1078: $ func (TS ts,PetscReal t,Vec u,void *ctx);
1080: + t - current timestep
1081: . u - output vector
1082: - ctx - [optional] user-defined function context
1084: Notes:
1085: This routine is useful for testing accuracy of time integration schemes when using the Method of Manufactured Solutions to
1086: create closed-form solutions with a non-physical forcing term.
1088: For low-dimensional problems solved in serial, such as small discrete systems, TSMonitorLGError() can be used to monitor the error history.
1090: Level: beginner
1092: .keywords: TS, timestep, set, right-hand-side, function
1094: .seealso: TSSetRHSJacobian(), TSSetIJacobian(), TSComputeSolutionFunction(), TSSetSolutionFunction()
1095: @*/
1096: PetscErrorCode TSSetForcingFunction(TS ts,TSForcingFunction f,void *ctx)
1097: {
1099: DM dm;
1103: TSGetDM(ts,&dm);
1104: DMTSSetForcingFunction(dm,f,ctx);
1105: return(0);
1106: }
1110: /*@C
1111: TSSetRHSJacobian - Sets the function to compute the Jacobian of G,
1112: where U_t = G(U,t), as well as the location to store the matrix.
1114: Logically Collective on TS
1116: Input Parameters:
1117: + ts - the TS context obtained from TSCreate()
1118: . Amat - (approximate) Jacobian matrix
1119: . Pmat - matrix from which preconditioner is to be constructed (usually the same as Amat)
1120: . f - the Jacobian evaluation routine
1121: - ctx - [optional] user-defined context for private data for the
1122: Jacobian evaluation routine (may be NULL)
1124: Calling sequence of f:
1125: $ func (TS ts,PetscReal t,Vec u,Mat A,Mat B,void *ctx);
1127: + t - current timestep
1128: . u - input vector
1129: . Amat - (approximate) Jacobian matrix
1130: . Pmat - matrix from which preconditioner is to be constructed (usually the same as Amat)
1131: - ctx - [optional] user-defined context for matrix evaluation routine
1133: Notes:
1134: You must set all the diagonal entries of the matrices, if they are zero you must still set them with a zero value
1136: The TS solver may modify the nonzero structure and the entries of the matrices Amat and Pmat between the calls to f()
1137: You should not assume the values are the same in the next call to f() as you set them in the previous call.
1139: Level: beginner
1141: .keywords: TS, timestep, set, right-hand-side, Jacobian
1143: .seealso: SNESComputeJacobianDefaultColor(), TSSetRHSFunction(), TSRHSJacobianSetReuse(), TSSetIJacobian()
1145: @*/
1146: PetscErrorCode TSSetRHSJacobian(TS ts,Mat Amat,Mat Pmat,TSRHSJacobian f,void *ctx)
1147: {
1149: SNES snes;
1150: DM dm;
1151: TSIJacobian ijacobian;
1160: TSGetDM(ts,&dm);
1161: DMTSSetRHSJacobian(dm,f,ctx);
1162: if (f == TSComputeRHSJacobianConstant) {
1163: /* Handle this case automatically for the user; otherwise user should call themselves. */
1164: TSRHSJacobianSetReuse(ts,PETSC_TRUE);
1165: }
1166: DMTSGetIJacobian(dm,&ijacobian,NULL);
1167: TSGetSNES(ts,&snes);
1168: if (!ijacobian) {
1169: SNESSetJacobian(snes,Amat,Pmat,SNESTSFormJacobian,ts);
1170: }
1171: if (Amat) {
1172: PetscObjectReference((PetscObject)Amat);
1173: MatDestroy(&ts->Arhs);
1174: ts->Arhs = Amat;
1175: }
1176: if (Pmat) {
1177: PetscObjectReference((PetscObject)Pmat);
1178: MatDestroy(&ts->Brhs);
1179: ts->Brhs = Pmat;
1180: }
1181: return(0);
1182: }
1187: /*@C
1188: TSSetIFunction - Set the function to compute F(t,U,U_t) where F() = 0 is the DAE to be solved.
1190: Logically Collective on TS
1192: Input Parameters:
1193: + ts - the TS context obtained from TSCreate()
1194: . r - vector to hold the residual (or NULL to have it created internally)
1195: . f - the function evaluation routine
1196: - ctx - user-defined context for private data for the function evaluation routine (may be NULL)
1198: Calling sequence of f:
1199: $ f(TS ts,PetscReal t,Vec u,Vec u_t,Vec F,ctx);
1201: + t - time at step/stage being solved
1202: . u - state vector
1203: . u_t - time derivative of state vector
1204: . F - function vector
1205: - ctx - [optional] user-defined context for matrix evaluation routine
1207: Important:
1208: The user MUST call either this routine or TSSetRHSFunction() to define the ODE. When solving DAEs you must use this function.
1210: Level: beginner
1212: .keywords: TS, timestep, set, DAE, Jacobian
1214: .seealso: TSSetRHSJacobian(), TSSetRHSFunction(), TSSetIJacobian()
1215: @*/
1216: PetscErrorCode TSSetIFunction(TS ts,Vec r,TSIFunction f,void *ctx)
1217: {
1219: SNES snes;
1220: Vec ralloc = NULL;
1221: DM dm;
1227: TSGetDM(ts,&dm);
1228: DMTSSetIFunction(dm,f,ctx);
1230: TSGetSNES(ts,&snes);
1231: if (!r && !ts->dm && ts->vec_sol) {
1232: VecDuplicate(ts->vec_sol,&ralloc);
1233: r = ralloc;
1234: }
1235: SNESSetFunction(snes,r,SNESTSFormFunction,ts);
1236: VecDestroy(&ralloc);
1237: return(0);
1238: }
1242: /*@C
1243: TSGetIFunction - Returns the vector where the implicit residual is stored and the function/contex to compute it.
1245: Not Collective
1247: Input Parameter:
1248: . ts - the TS context
1250: Output Parameter:
1251: + r - vector to hold residual (or NULL)
1252: . func - the function to compute residual (or NULL)
1253: - ctx - the function context (or NULL)
1255: Level: advanced
1257: .keywords: TS, nonlinear, get, function
1259: .seealso: TSSetIFunction(), SNESGetFunction()
1260: @*/
1261: PetscErrorCode TSGetIFunction(TS ts,Vec *r,TSIFunction *func,void **ctx)
1262: {
1264: SNES snes;
1265: DM dm;
1269: TSGetSNES(ts,&snes);
1270: SNESGetFunction(snes,r,NULL,NULL);
1271: TSGetDM(ts,&dm);
1272: DMTSGetIFunction(dm,func,ctx);
1273: return(0);
1274: }
1278: /*@C
1279: TSGetRHSFunction - Returns the vector where the right hand side is stored and the function/context to compute it.
1281: Not Collective
1283: Input Parameter:
1284: . ts - the TS context
1286: Output Parameter:
1287: + r - vector to hold computed right hand side (or NULL)
1288: . func - the function to compute right hand side (or NULL)
1289: - ctx - the function context (or NULL)
1291: Level: advanced
1293: .keywords: TS, nonlinear, get, function
1295: .seealso: TSSetRHSFunction(), SNESGetFunction()
1296: @*/
1297: PetscErrorCode TSGetRHSFunction(TS ts,Vec *r,TSRHSFunction *func,void **ctx)
1298: {
1300: SNES snes;
1301: DM dm;
1305: TSGetSNES(ts,&snes);
1306: SNESGetFunction(snes,r,NULL,NULL);
1307: TSGetDM(ts,&dm);
1308: DMTSGetRHSFunction(dm,func,ctx);
1309: return(0);
1310: }
1314: /*@C
1315: TSSetIJacobian - Set the function to compute the matrix dF/dU + a*dF/dU_t where F(t,U,U_t) is the function
1316: provided with TSSetIFunction().
1318: Logically Collective on TS
1320: Input Parameters:
1321: + ts - the TS context obtained from TSCreate()
1322: . Amat - (approximate) Jacobian matrix
1323: . Pmat - matrix used to compute preconditioner (usually the same as Amat)
1324: . f - the Jacobian evaluation routine
1325: - ctx - user-defined context for private data for the Jacobian evaluation routine (may be NULL)
1327: Calling sequence of f:
1328: $ f(TS ts,PetscReal t,Vec U,Vec U_t,PetscReal a,Mat Amat,Mat Pmat,void *ctx);
1330: + t - time at step/stage being solved
1331: . U - state vector
1332: . U_t - time derivative of state vector
1333: . a - shift
1334: . Amat - (approximate) Jacobian of F(t,U,W+a*U), equivalent to dF/dU + a*dF/dU_t
1335: . Pmat - matrix used for constructing preconditioner, usually the same as Amat
1336: - ctx - [optional] user-defined context for matrix evaluation routine
1338: Notes:
1339: The matrices Amat and Pmat are exactly the matrices that are used by SNES for the nonlinear solve.
1341: If you know the operator Amat has a null space you can use MatSetNullSpace() and MatSetTransposeNullSpace() to supply the null
1342: space to Amat and the KSP solvers will automatically use that null space as needed during the solution process.
1344: The matrix dF/dU + a*dF/dU_t you provide turns out to be
1345: the Jacobian of F(t,U,W+a*U) where F(t,U,U_t) = 0 is the DAE to be solved.
1346: The time integrator internally approximates U_t by W+a*U where the positive "shift"
1347: a and vector W depend on the integration method, step size, and past states. For example with
1348: the backward Euler method a = 1/dt and W = -a*U(previous timestep) so
1349: W + a*U = a*(U - U(previous timestep)) = (U - U(previous timestep))/dt
1351: You must set all the diagonal entries of the matrices, if they are zero you must still set them with a zero value
1353: The TS solver may modify the nonzero structure and the entries of the matrices Amat and Pmat between the calls to f()
1354: You should not assume the values are the same in the next call to f() as you set them in the previous call.
1356: Level: beginner
1358: .keywords: TS, timestep, DAE, Jacobian
1360: .seealso: TSSetIFunction(), TSSetRHSJacobian(), SNESComputeJacobianDefaultColor(), SNESComputeJacobianDefault(), TSSetRHSFunction()
1362: @*/
1363: PetscErrorCode TSSetIJacobian(TS ts,Mat Amat,Mat Pmat,TSIJacobian f,void *ctx)
1364: {
1366: SNES snes;
1367: DM dm;
1376: TSGetDM(ts,&dm);
1377: DMTSSetIJacobian(dm,f,ctx);
1379: TSGetSNES(ts,&snes);
1380: SNESSetJacobian(snes,Amat,Pmat,SNESTSFormJacobian,ts);
1381: return(0);
1382: }
1386: /*@
1387: TSRHSJacobianSetReuse - restore RHS Jacobian before re-evaluating. Without this flag, TS will change the sign and
1388: shift the RHS Jacobian for a finite-time-step implicit solve, in which case the user function will need to recompute
1389: the entire Jacobian. The reuse flag must be set if the evaluation function will assume that the matrix entries have
1390: not been changed by the TS.
1392: Logically Collective
1394: Input Arguments:
1395: + ts - TS context obtained from TSCreate()
1396: - reuse - PETSC_TRUE if the RHS Jacobian
1398: Level: intermediate
1400: .seealso: TSSetRHSJacobian(), TSComputeRHSJacobianConstant()
1401: @*/
1402: PetscErrorCode TSRHSJacobianSetReuse(TS ts,PetscBool reuse)
1403: {
1405: ts->rhsjacobian.reuse = reuse;
1406: return(0);
1407: }
1411: /*@C
1412: TSSetI2Function - Set the function to compute F(t,U,U_t,U_tt) where F = 0 is the DAE to be solved.
1414: Logically Collective on TS
1416: Input Parameters:
1417: + ts - the TS context obtained from TSCreate()
1418: . F - vector to hold the residual (or NULL to have it created internally)
1419: . fun - the function evaluation routine
1420: - ctx - user-defined context for private data for the function evaluation routine (may be NULL)
1422: Calling sequence of fun:
1423: $ fun(TS ts,PetscReal t,Vec U,Vec U_t,Vec U_tt,Vec F,ctx);
1425: + t - time at step/stage being solved
1426: . U - state vector
1427: . U_t - time derivative of state vector
1428: . U_tt - second time derivative of state vector
1429: . F - function vector
1430: - ctx - [optional] user-defined context for matrix evaluation routine (may be NULL)
1432: Level: beginner
1434: .keywords: TS, timestep, set, ODE, DAE, Function
1436: .seealso: TSSetI2Jacobian()
1437: @*/
1438: PetscErrorCode TSSetI2Function(TS ts,Vec F,TSI2Function fun,void *ctx)
1439: {
1440: DM dm;
1446: TSSetIFunction(ts,F,NULL,NULL);
1447: TSGetDM(ts,&dm);
1448: DMTSSetI2Function(dm,fun,ctx);
1449: return(0);
1450: }
1454: /*@C
1455: TSGetI2Function - Returns the vector where the implicit residual is stored and the function/contex to compute it.
1457: Not Collective
1459: Input Parameter:
1460: . ts - the TS context
1462: Output Parameter:
1463: + r - vector to hold residual (or NULL)
1464: . fun - the function to compute residual (or NULL)
1465: - ctx - the function context (or NULL)
1467: Level: advanced
1469: .keywords: TS, nonlinear, get, function
1471: .seealso: TSSetI2Function(), SNESGetFunction()
1472: @*/
1473: PetscErrorCode TSGetI2Function(TS ts,Vec *r,TSI2Function *fun,void **ctx)
1474: {
1476: SNES snes;
1477: DM dm;
1481: TSGetSNES(ts,&snes);
1482: SNESGetFunction(snes,r,NULL,NULL);
1483: TSGetDM(ts,&dm);
1484: DMTSGetI2Function(dm,fun,ctx);
1485: return(0);
1486: }
1490: /*@C
1491: TSSetI2Jacobian - Set the function to compute the matrix dF/dU + v*dF/dU_t + a*dF/dU_tt
1492: where F(t,U,U_t,U_tt) is the function you provided with TSSetI2Function().
1494: Logically Collective on TS
1496: Input Parameters:
1497: + ts - the TS context obtained from TSCreate()
1498: . J - Jacobian matrix
1499: . P - preconditioning matrix for J (may be same as J)
1500: . jac - the Jacobian evaluation routine
1501: - ctx - user-defined context for private data for the Jacobian evaluation routine (may be NULL)
1503: Calling sequence of jac:
1504: $ jac(TS ts,PetscReal t,Vec U,Vec U_t,Vec U_tt,PetscReal v,PetscReal a,Mat J,Mat P,void *ctx);
1506: + t - time at step/stage being solved
1507: . U - state vector
1508: . U_t - time derivative of state vector
1509: . U_tt - second time derivative of state vector
1510: . v - shift for U_t
1511: . a - shift for U_tt
1512: . 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
1513: . P - preconditioning matrix for J, may be same as J
1514: - ctx - [optional] user-defined context for matrix evaluation routine
1516: Notes:
1517: The matrices J and P are exactly the matrices that are used by SNES for the nonlinear solve.
1519: The matrix dF/dU + v*dF/dU_t + a*dF/dU_tt you provide turns out to be
1520: 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.
1521: The time integrator internally approximates U_t by W+v*U and U_tt by W'+a*U where the positive "shift"
1522: parameters 'v' and 'a' and vectors W, W' depend on the integration method, step size, and past states.
1524: Level: beginner
1526: .keywords: TS, timestep, set, ODE, DAE, Jacobian
1528: .seealso: TSSetI2Function()
1529: @*/
1530: PetscErrorCode TSSetI2Jacobian(TS ts,Mat J,Mat P,TSI2Jacobian jac,void *ctx)
1531: {
1532: DM dm;
1539: TSSetIJacobian(ts,J,P,NULL,NULL);
1540: TSGetDM(ts,&dm);
1541: DMTSSetI2Jacobian(dm,jac,ctx);
1542: return(0);
1543: }
1547: /*@C
1548: TSGetI2Jacobian - Returns the implicit Jacobian at the present timestep.
1550: Not Collective, but parallel objects are returned if TS is parallel
1552: Input Parameter:
1553: . ts - The TS context obtained from TSCreate()
1555: Output Parameters:
1556: + J - The (approximate) Jacobian of F(t,U,U_t,U_tt)
1557: . P - The matrix from which the preconditioner is constructed, often the same as J
1558: . jac - The function to compute the Jacobian matrices
1559: - ctx - User-defined context for Jacobian evaluation routine
1561: Notes: You can pass in NULL for any return argument you do not need.
1563: Level: advanced
1565: .seealso: TSGetTimeStep(), TSGetMatrices(), TSGetTime(), TSGetTimeStepNumber()
1567: .keywords: TS, timestep, get, matrix, Jacobian
1568: @*/
1569: PetscErrorCode TSGetI2Jacobian(TS ts,Mat *J,Mat *P,TSI2Jacobian *jac,void **ctx)
1570: {
1572: SNES snes;
1573: DM dm;
1576: TSGetSNES(ts,&snes);
1577: SNESSetUpMatrices(snes);
1578: SNESGetJacobian(snes,J,P,NULL,NULL);
1579: TSGetDM(ts,&dm);
1580: DMTSGetI2Jacobian(dm,jac,ctx);
1581: return(0);
1582: }
1586: /*@
1587: TSComputeI2Function - Evaluates the DAE residual written in implicit form F(t,U,U_t,U_tt) = 0
1589: Collective on TS and Vec
1591: Input Parameters:
1592: + ts - the TS context
1593: . t - current time
1594: . U - state vector
1595: . V - time derivative of state vector (U_t)
1596: - A - second time derivative of state vector (U_tt)
1598: Output Parameter:
1599: . F - the residual vector
1601: Note:
1602: Most users should not need to explicitly call this routine, as it
1603: is used internally within the nonlinear solvers.
1605: Level: developer
1607: .keywords: TS, compute, function, vector
1609: .seealso: TSSetI2Function()
1610: @*/
1611: PetscErrorCode TSComputeI2Function(TS ts,PetscReal t,Vec U,Vec V,Vec A,Vec F)
1612: {
1613: DM dm;
1614: TSI2Function I2Function;
1615: void *ctx;
1616: TSRHSFunction rhsfunction;
1626: TSGetDM(ts,&dm);
1627: DMTSGetI2Function(dm,&I2Function,&ctx);
1628: DMTSGetRHSFunction(dm,&rhsfunction,NULL);
1630: if (!I2Function) {
1631: TSComputeIFunction(ts,t,U,A,F,PETSC_FALSE);
1632: return(0);
1633: }
1635: PetscLogEventBegin(TS_FunctionEval,ts,U,V,F);
1637: PetscStackPush("TS user implicit function");
1638: I2Function(ts,t,U,V,A,F,ctx);
1639: PetscStackPop;
1641: if (rhsfunction) {
1642: Vec Frhs;
1643: TSGetRHSVec_Private(ts,&Frhs);
1644: TSComputeRHSFunction(ts,t,U,Frhs);
1645: VecAXPY(F,-1,Frhs);
1646: }
1648: PetscLogEventEnd(TS_FunctionEval,ts,U,V,F);
1649: return(0);
1650: }
1654: /*@
1655: TSComputeI2Jacobian - Evaluates the Jacobian of the DAE
1657: Collective on TS and Vec
1659: Input Parameters:
1660: + ts - the TS context
1661: . t - current timestep
1662: . U - state vector
1663: . V - time derivative of state vector
1664: . A - second time derivative of state vector
1665: . shiftV - shift to apply, see note below
1666: - shiftA - shift to apply, see note below
1668: Output Parameters:
1669: + J - Jacobian matrix
1670: - P - optional preconditioning matrix
1672: Notes:
1673: If F(t,U,V,A)=0 is the DAE, the required Jacobian is
1675: dF/dU + shiftV*dF/dV + shiftA*dF/dA
1677: Most users should not need to explicitly call this routine, as it
1678: is used internally within the nonlinear solvers.
1680: Level: developer
1682: .keywords: TS, compute, Jacobian, matrix
1684: .seealso: TSSetI2Jacobian()
1685: @*/
1686: PetscErrorCode TSComputeI2Jacobian(TS ts,PetscReal t,Vec U,Vec V,Vec A,PetscReal shiftV,PetscReal shiftA,Mat J,Mat P)
1687: {
1688: DM dm;
1689: TSI2Jacobian I2Jacobian;
1690: void *ctx;
1691: TSRHSJacobian rhsjacobian;
1702: TSGetDM(ts,&dm);
1703: DMTSGetI2Jacobian(dm,&I2Jacobian,&ctx);
1704: DMTSGetRHSJacobian(dm,&rhsjacobian,NULL);
1706: if (!I2Jacobian) {
1707: TSComputeIJacobian(ts,t,U,A,shiftA,J,P,PETSC_FALSE);
1708: return(0);
1709: }
1711: PetscLogEventBegin(TS_JacobianEval,ts,U,J,P);
1713: PetscStackPush("TS user implicit Jacobian");
1714: I2Jacobian(ts,t,U,V,A,shiftV,shiftA,J,P,ctx);
1715: PetscStackPop;
1717: if (rhsjacobian) {
1718: Mat Jrhs,Prhs; MatStructure axpy = DIFFERENT_NONZERO_PATTERN;
1719: TSGetRHSMats_Private(ts,&Jrhs,&Prhs);
1720: TSComputeRHSJacobian(ts,t,U,Jrhs,Prhs);
1721: MatAXPY(J,-1,Jrhs,axpy);
1722: if (P != J) {MatAXPY(P,-1,Prhs,axpy);}
1723: }
1725: PetscLogEventEnd(TS_JacobianEval,ts,U,J,P);
1726: return(0);
1727: }
1731: /*@
1732: TS2SetSolution - Sets the initial solution and time derivative vectors
1733: for use by the TS routines handling second order equations.
1735: Logically Collective on TS and Vec
1737: Input Parameters:
1738: + ts - the TS context obtained from TSCreate()
1739: . u - the solution vector
1740: - v - the time derivative vector
1742: Level: beginner
1744: .keywords: TS, timestep, set, solution, initial conditions
1745: @*/
1746: PetscErrorCode TS2SetSolution(TS ts,Vec u,Vec v)
1747: {
1754: TSSetSolution(ts,u);
1755: PetscObjectReference((PetscObject)v);
1756: VecDestroy(&ts->vec_dot);
1757: ts->vec_dot = v;
1758: return(0);
1759: }
1763: /*@
1764: TS2GetSolution - Returns the solution and time derivative at the present timestep
1765: for second order equations. It is valid to call this routine inside the function
1766: that you are evaluating in order to move to the new timestep. This vector not
1767: changed until the solution at the next timestep has been calculated.
1769: Not Collective, but Vec returned is parallel if TS is parallel
1771: Input Parameter:
1772: . ts - the TS context obtained from TSCreate()
1774: Output Parameter:
1775: + u - the vector containing the solution
1776: - v - the vector containing the time derivative
1778: Level: intermediate
1780: .seealso: TS2SetSolution(), TSGetTimeStep(), TSGetTime()
1782: .keywords: TS, timestep, get, solution
1783: @*/
1784: PetscErrorCode TS2GetSolution(TS ts,Vec *u,Vec *v)
1785: {
1790: if (u) *u = ts->vec_sol;
1791: if (v) *v = ts->vec_dot;
1792: return(0);
1793: }
1797: /*@C
1798: TSLoad - Loads a KSP that has been stored in binary with KSPView().
1800: Collective on PetscViewer
1802: Input Parameters:
1803: + newdm - the newly loaded TS, this needs to have been created with TSCreate() or
1804: some related function before a call to TSLoad().
1805: - viewer - binary file viewer, obtained from PetscViewerBinaryOpen()
1807: Level: intermediate
1809: Notes:
1810: The type is determined by the data in the file, any type set into the TS before this call is ignored.
1812: Notes for advanced users:
1813: Most users should not need to know the details of the binary storage
1814: format, since TSLoad() and TSView() completely hide these details.
1815: But for anyone who's interested, the standard binary matrix storage
1816: format is
1817: .vb
1818: has not yet been determined
1819: .ve
1821: .seealso: PetscViewerBinaryOpen(), TSView(), MatLoad(), VecLoad()
1822: @*/
1823: PetscErrorCode TSLoad(TS ts, PetscViewer viewer)
1824: {
1826: PetscBool isbinary;
1827: PetscInt classid;
1828: char type[256];
1829: DMTS sdm;
1830: DM dm;
1835: PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERBINARY,&isbinary);
1836: if (!isbinary) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,"Invalid viewer; open viewer with PetscViewerBinaryOpen()");
1838: PetscViewerBinaryRead(viewer,&classid,1,NULL,PETSC_INT);
1839: if (classid != TS_FILE_CLASSID) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_ARG_WRONG,"Not TS next in file");
1840: PetscViewerBinaryRead(viewer,type,256,NULL,PETSC_CHAR);
1841: TSSetType(ts, type);
1842: if (ts->ops->load) {
1843: (*ts->ops->load)(ts,viewer);
1844: }
1845: DMCreate(PetscObjectComm((PetscObject)ts),&dm);
1846: DMLoad(dm,viewer);
1847: TSSetDM(ts,dm);
1848: DMCreateGlobalVector(ts->dm,&ts->vec_sol);
1849: VecLoad(ts->vec_sol,viewer);
1850: DMGetDMTS(ts->dm,&sdm);
1851: DMTSLoad(sdm,viewer);
1852: return(0);
1853: }
1855: #include <petscdraw.h>
1856: #if defined(PETSC_HAVE_SAWS)
1857: #include <petscviewersaws.h>
1858: #endif
1861: /*@C
1862: TSView - Prints the TS data structure.
1864: Collective on TS
1866: Input Parameters:
1867: + ts - the TS context obtained from TSCreate()
1868: - viewer - visualization context
1870: Options Database Key:
1871: . -ts_view - calls TSView() at end of TSStep()
1873: Notes:
1874: The available visualization contexts include
1875: + PETSC_VIEWER_STDOUT_SELF - standard output (default)
1876: - PETSC_VIEWER_STDOUT_WORLD - synchronized standard
1877: output where only the first processor opens
1878: the file. All other processors send their
1879: data to the first processor to print.
1881: The user can open an alternative visualization context with
1882: PetscViewerASCIIOpen() - output to a specified file.
1884: Level: beginner
1886: .keywords: TS, timestep, view
1888: .seealso: PetscViewerASCIIOpen()
1889: @*/
1890: PetscErrorCode TSView(TS ts,PetscViewer viewer)
1891: {
1893: TSType type;
1894: PetscBool iascii,isstring,isundials,isbinary,isdraw;
1895: DMTS sdm;
1896: #if defined(PETSC_HAVE_SAWS)
1897: PetscBool issaws;
1898: #endif
1902: if (!viewer) {
1903: PetscViewerASCIIGetStdout(PetscObjectComm((PetscObject)ts),&viewer);
1904: }
1908: PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERASCII,&iascii);
1909: PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERSTRING,&isstring);
1910: PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERBINARY,&isbinary);
1911: PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERDRAW,&isdraw);
1912: #if defined(PETSC_HAVE_SAWS)
1913: PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERSAWS,&issaws);
1914: #endif
1915: if (iascii) {
1916: PetscObjectPrintClassNamePrefixType((PetscObject)ts,viewer);
1917: PetscViewerASCIIPrintf(viewer," maximum steps=%D\n",ts->max_steps);
1918: PetscViewerASCIIPrintf(viewer," maximum time=%g\n",(double)ts->max_time);
1919: if (ts->problem_type == TS_NONLINEAR) {
1920: PetscViewerASCIIPrintf(viewer," total number of nonlinear solver iterations=%D\n",ts->snes_its);
1921: PetscViewerASCIIPrintf(viewer," total number of nonlinear solve failures=%D\n",ts->num_snes_failures);
1922: }
1923: PetscViewerASCIIPrintf(viewer," total number of linear solver iterations=%D\n",ts->ksp_its);
1924: PetscViewerASCIIPrintf(viewer," total number of rejected steps=%D\n",ts->reject);
1925: DMGetDMTS(ts->dm,&sdm);
1926: DMTSView(sdm,viewer);
1927: if (ts->ops->view) {
1928: PetscViewerASCIIPushTab(viewer);
1929: (*ts->ops->view)(ts,viewer);
1930: PetscViewerASCIIPopTab(viewer);
1931: }
1932: } else if (isstring) {
1933: TSGetType(ts,&type);
1934: PetscViewerStringSPrintf(viewer," %-7.7s",type);
1935: } else if (isbinary) {
1936: PetscInt classid = TS_FILE_CLASSID;
1937: MPI_Comm comm;
1938: PetscMPIInt rank;
1939: char type[256];
1941: PetscObjectGetComm((PetscObject)ts,&comm);
1942: MPI_Comm_rank(comm,&rank);
1943: if (!rank) {
1944: PetscViewerBinaryWrite(viewer,&classid,1,PETSC_INT,PETSC_FALSE);
1945: PetscStrncpy(type,((PetscObject)ts)->type_name,256);
1946: PetscViewerBinaryWrite(viewer,type,256,PETSC_CHAR,PETSC_FALSE);
1947: }
1948: if (ts->ops->view) {
1949: (*ts->ops->view)(ts,viewer);
1950: }
1951: DMView(ts->dm,viewer);
1952: VecView(ts->vec_sol,viewer);
1953: DMGetDMTS(ts->dm,&sdm);
1954: DMTSView(sdm,viewer);
1955: } else if (isdraw) {
1956: PetscDraw draw;
1957: char str[36];
1958: PetscReal x,y,bottom,h;
1960: PetscViewerDrawGetDraw(viewer,0,&draw);
1961: PetscDrawGetCurrentPoint(draw,&x,&y);
1962: PetscStrcpy(str,"TS: ");
1963: PetscStrcat(str,((PetscObject)ts)->type_name);
1964: PetscDrawStringBoxed(draw,x,y,PETSC_DRAW_BLACK,PETSC_DRAW_BLACK,str,NULL,&h);
1965: bottom = y - h;
1966: PetscDrawPushCurrentPoint(draw,x,bottom);
1967: if (ts->ops->view) {
1968: (*ts->ops->view)(ts,viewer);
1969: }
1970: PetscDrawPopCurrentPoint(draw);
1971: #if defined(PETSC_HAVE_SAWS)
1972: } else if (issaws) {
1973: PetscMPIInt rank;
1974: const char *name;
1976: PetscObjectGetName((PetscObject)ts,&name);
1977: MPI_Comm_rank(PETSC_COMM_WORLD,&rank);
1978: if (!((PetscObject)ts)->amsmem && !rank) {
1979: char dir[1024];
1981: PetscObjectViewSAWs((PetscObject)ts,viewer);
1982: PetscSNPrintf(dir,1024,"/PETSc/Objects/%s/time_step",name);
1983: PetscStackCallSAWs(SAWs_Register,(dir,&ts->steps,1,SAWs_READ,SAWs_INT));
1984: PetscSNPrintf(dir,1024,"/PETSc/Objects/%s/time",name);
1985: PetscStackCallSAWs(SAWs_Register,(dir,&ts->ptime,1,SAWs_READ,SAWs_DOUBLE));
1986: }
1987: if (ts->ops->view) {
1988: (*ts->ops->view)(ts,viewer);
1989: }
1990: #endif
1991: }
1993: PetscViewerASCIIPushTab(viewer);
1994: PetscObjectTypeCompare((PetscObject)ts,TSSUNDIALS,&isundials);
1995: PetscViewerASCIIPopTab(viewer);
1996: return(0);
1997: }
2002: /*@
2003: TSSetApplicationContext - Sets an optional user-defined context for
2004: the timesteppers.
2006: Logically Collective on TS
2008: Input Parameters:
2009: + ts - the TS context obtained from TSCreate()
2010: - usrP - optional user context
2012: Fortran Notes: To use this from Fortran you must write a Fortran interface definition for this
2013: function that tells Fortran the Fortran derived data type that you are passing in as the ctx argument.
2015: Level: intermediate
2017: .keywords: TS, timestep, set, application, context
2019: .seealso: TSGetApplicationContext()
2020: @*/
2021: PetscErrorCode TSSetApplicationContext(TS ts,void *usrP)
2022: {
2025: ts->user = usrP;
2026: return(0);
2027: }
2031: /*@
2032: TSGetApplicationContext - Gets the user-defined context for the
2033: timestepper.
2035: Not Collective
2037: Input Parameter:
2038: . ts - the TS context obtained from TSCreate()
2040: Output Parameter:
2041: . usrP - user context
2043: Fortran Notes: To use this from Fortran you must write a Fortran interface definition for this
2044: function that tells Fortran the Fortran derived data type that you are passing in as the ctx argument.
2046: Level: intermediate
2048: .keywords: TS, timestep, get, application, context
2050: .seealso: TSSetApplicationContext()
2051: @*/
2052: PetscErrorCode TSGetApplicationContext(TS ts,void *usrP)
2053: {
2056: *(void**)usrP = ts->user;
2057: return(0);
2058: }
2062: /*@
2063: TSGetTimeStepNumber - Gets the number of time steps completed.
2065: Not Collective
2067: Input Parameter:
2068: . ts - the TS context obtained from TSCreate()
2070: Output Parameter:
2071: . iter - number of steps completed so far
2073: Level: intermediate
2075: .keywords: TS, timestep, get, iteration, number
2076: .seealso: TSGetTime(), TSGetTimeStep(), TSSetPreStep(), TSSetPreStage(), TSSetPostStage(), TSSetPostStep()
2077: @*/
2078: PetscErrorCode TSGetTimeStepNumber(TS ts,PetscInt *iter)
2079: {
2083: *iter = ts->steps;
2084: return(0);
2085: }
2089: /*@
2090: TSSetInitialTimeStep - Sets the initial timestep to be used,
2091: as well as the initial time.
2093: Logically Collective on TS
2095: Input Parameters:
2096: + ts - the TS context obtained from TSCreate()
2097: . initial_time - the initial time
2098: - time_step - the size of the timestep
2100: Level: intermediate
2102: .seealso: TSSetTimeStep(), TSGetTimeStep()
2104: .keywords: TS, set, initial, timestep
2105: @*/
2106: PetscErrorCode TSSetInitialTimeStep(TS ts,PetscReal initial_time,PetscReal time_step)
2107: {
2112: TSSetTimeStep(ts,time_step);
2113: TSSetTime(ts,initial_time);
2114: return(0);
2115: }
2119: /*@
2120: TSSetTimeStep - Allows one to reset the timestep at any time,
2121: useful for simple pseudo-timestepping codes.
2123: Logically Collective on TS
2125: Input Parameters:
2126: + ts - the TS context obtained from TSCreate()
2127: - time_step - the size of the timestep
2129: Level: intermediate
2131: .seealso: TSSetInitialTimeStep(), TSGetTimeStep()
2133: .keywords: TS, set, timestep
2134: @*/
2135: PetscErrorCode TSSetTimeStep(TS ts,PetscReal time_step)
2136: {
2140: ts->time_step = time_step;
2141: return(0);
2142: }
2146: /*@
2147: TSSetExactFinalTime - Determines whether to adapt the final time step to
2148: match the exact final time, interpolate solution to the exact final time,
2149: or just return at the final time TS computed.
2151: Logically Collective on TS
2153: Input Parameter:
2154: + ts - the time-step context
2155: - eftopt - exact final time option
2157: $ TS_EXACTFINALTIME_STEPOVER - Don't do anything if final time is exceeded
2158: $ TS_EXACTFINALTIME_INTERPOLATE - Interpolate back to final time
2159: $ TS_EXACTFINALTIME_MATCHSTEP - Adapt final time step to match the final time
2161: Options Database:
2162: . -ts_exact_final_time <stepover,interpolate,matchstep> - select the final step at runtime
2164: Warning: If you use the option TS_EXACTFINALTIME_STEPOVER the solution may be at a very different time
2165: then the final time you selected.
2167: Level: beginner
2169: .seealso: TSExactFinalTimeOption
2170: @*/
2171: PetscErrorCode TSSetExactFinalTime(TS ts,TSExactFinalTimeOption eftopt)
2172: {
2176: ts->exact_final_time = eftopt;
2177: return(0);
2178: }
2182: /*@
2183: TSGetTimeStep - Gets the current timestep size.
2185: Not Collective
2187: Input Parameter:
2188: . ts - the TS context obtained from TSCreate()
2190: Output Parameter:
2191: . dt - the current timestep size
2193: Level: intermediate
2195: .seealso: TSSetInitialTimeStep(), TSGetTimeStep()
2197: .keywords: TS, get, timestep
2198: @*/
2199: PetscErrorCode TSGetTimeStep(TS ts,PetscReal *dt)
2200: {
2204: *dt = ts->time_step;
2205: return(0);
2206: }
2210: /*@
2211: TSGetSolution - Returns the solution at the present timestep. It
2212: is valid to call this routine inside the function that you are evaluating
2213: in order to move to the new timestep. This vector not changed until
2214: the solution at the next timestep has been calculated.
2216: Not Collective, but Vec returned is parallel if TS is parallel
2218: Input Parameter:
2219: . ts - the TS context obtained from TSCreate()
2221: Output Parameter:
2222: . v - the vector containing the solution
2224: Note: If you used TSSetExactFinalTime(ts,TS_EXACTFINALTIME_MATCHSTEP); this does not return the solution at the requested
2225: final time. It returns the solution at the next timestep.
2227: Level: intermediate
2229: .seealso: TSGetTimeStep(), TSGetTime(), TSGetSolveTime()
2231: .keywords: TS, timestep, get, solution
2232: @*/
2233: PetscErrorCode TSGetSolution(TS ts,Vec *v)
2234: {
2238: *v = ts->vec_sol;
2239: return(0);
2240: }
2244: /*@
2245: TSGetCostGradients - Returns the gradients from the TSAdjointSolve()
2247: Not Collective, but Vec returned is parallel if TS is parallel
2249: Input Parameter:
2250: . ts - the TS context obtained from TSCreate()
2252: Output Parameter:
2253: + lambda - vectors containing the gradients of the cost functions with respect to the ODE/DAE solution variables
2254: - mu - vectors containing the gradients of the cost functions with respect to the problem parameters
2256: Level: intermediate
2258: .seealso: TSGetTimeStep()
2260: .keywords: TS, timestep, get, sensitivity
2261: @*/
2262: PetscErrorCode TSGetCostGradients(TS ts,PetscInt *numcost,Vec **lambda,Vec **mu)
2263: {
2266: if (numcost) *numcost = ts->numcost;
2267: if (lambda) *lambda = ts->vecs_sensi;
2268: if (mu) *mu = ts->vecs_sensip;
2269: return(0);
2270: }
2272: /* ----- Routines to initialize and destroy a timestepper ---- */
2275: /*@
2276: TSSetProblemType - Sets the type of problem to be solved.
2278: Not collective
2280: Input Parameters:
2281: + ts - The TS
2282: - type - One of TS_LINEAR, TS_NONLINEAR where these types refer to problems of the forms
2283: .vb
2284: U_t - A U = 0 (linear)
2285: U_t - A(t) U = 0 (linear)
2286: F(t,U,U_t) = 0 (nonlinear)
2287: .ve
2289: Level: beginner
2291: .keywords: TS, problem type
2292: .seealso: TSSetUp(), TSProblemType, TS
2293: @*/
2294: PetscErrorCode TSSetProblemType(TS ts, TSProblemType type)
2295: {
2300: ts->problem_type = type;
2301: if (type == TS_LINEAR) {
2302: SNES snes;
2303: TSGetSNES(ts,&snes);
2304: SNESSetType(snes,SNESKSPONLY);
2305: }
2306: return(0);
2307: }
2311: /*@C
2312: TSGetProblemType - Gets the type of problem to be solved.
2314: Not collective
2316: Input Parameter:
2317: . ts - The TS
2319: Output Parameter:
2320: . type - One of TS_LINEAR, TS_NONLINEAR where these types refer to problems of the forms
2321: .vb
2322: M U_t = A U
2323: M(t) U_t = A(t) U
2324: F(t,U,U_t)
2325: .ve
2327: Level: beginner
2329: .keywords: TS, problem type
2330: .seealso: TSSetUp(), TSProblemType, TS
2331: @*/
2332: PetscErrorCode TSGetProblemType(TS ts, TSProblemType *type)
2333: {
2337: *type = ts->problem_type;
2338: return(0);
2339: }
2343: /*@
2344: TSSetUp - Sets up the internal data structures for the later use
2345: of a timestepper.
2347: Collective on TS
2349: Input Parameter:
2350: . ts - the TS context obtained from TSCreate()
2352: Notes:
2353: For basic use of the TS solvers the user need not explicitly call
2354: TSSetUp(), since these actions will automatically occur during
2355: the call to TSStep(). However, if one wishes to control this
2356: phase separately, TSSetUp() should be called after TSCreate()
2357: and optional routines of the form TSSetXXX(), but before TSStep().
2359: Level: advanced
2361: .keywords: TS, timestep, setup
2363: .seealso: TSCreate(), TSStep(), TSDestroy()
2364: @*/
2365: PetscErrorCode TSSetUp(TS ts)
2366: {
2368: DM dm;
2369: PetscErrorCode (*func)(SNES,Vec,Vec,void*);
2370: PetscErrorCode (*jac)(SNES,Vec,Mat,Mat,void*);
2371: TSIFunction ifun;
2372: TSIJacobian ijac;
2373: TSI2Jacobian i2jac;
2374: TSRHSJacobian rhsjac;
2378: if (ts->setupcalled) return(0);
2380: ts->total_steps = 0;
2381: if (!((PetscObject)ts)->type_name) {
2382: TSGetIFunction(ts,NULL,&ifun,NULL);
2383: TSSetType(ts,ifun ? TSBEULER : TSEULER);
2384: }
2386: if (!ts->vec_sol) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Must call TSSetSolution() first");
2388: if (ts->rhsjacobian.reuse) {
2389: Mat Amat,Pmat;
2390: SNES snes;
2391: TSGetSNES(ts,&snes);
2392: SNESGetJacobian(snes,&Amat,&Pmat,NULL,NULL);
2393: /* Matching matrices implies that an IJacobian is NOT set, because if it had been set, the IJacobian's matrix would
2394: * have displaced the RHS matrix */
2395: if (Amat == ts->Arhs) {
2396: MatDuplicate(ts->Arhs,MAT_DO_NOT_COPY_VALUES,&Amat);
2397: SNESSetJacobian(snes,Amat,NULL,NULL,NULL);
2398: MatDestroy(&Amat);
2399: }
2400: if (Pmat == ts->Brhs) {
2401: MatDuplicate(ts->Brhs,MAT_DO_NOT_COPY_VALUES,&Pmat);
2402: SNESSetJacobian(snes,NULL,Pmat,NULL,NULL);
2403: MatDestroy(&Pmat);
2404: }
2405: }
2406: if (ts->ops->setup) {
2407: (*ts->ops->setup)(ts);
2408: }
2410: /* In the case where we've set a DMTSFunction or what have you, we need the default SNESFunction
2411: to be set right but can't do it elsewhere due to the overreliance on ctx=ts.
2412: */
2413: TSGetDM(ts,&dm);
2414: DMSNESGetFunction(dm,&func,NULL);
2415: if (!func) {
2416: DMSNESSetFunction(dm,SNESTSFormFunction,ts);
2417: }
2418: /* If the SNES doesn't have a jacobian set and the TS has an ijacobian or rhsjacobian set, set the SNES to use it.
2419: Otherwise, the SNES will use coloring internally to form the Jacobian.
2420: */
2421: DMSNESGetJacobian(dm,&jac,NULL);
2422: DMTSGetIJacobian(dm,&ijac,NULL);
2423: DMTSGetI2Jacobian(dm,&i2jac,NULL);
2424: DMTSGetRHSJacobian(dm,&rhsjac,NULL);
2425: if (!jac && (ijac || i2jac || rhsjac)) {
2426: DMSNESSetJacobian(dm,SNESTSFormJacobian,ts);
2427: }
2428: ts->setupcalled = PETSC_TRUE;
2429: return(0);
2430: }
2434: /*@
2435: TSAdjointSetUp - Sets up the internal data structures for the later use
2436: of an adjoint solver
2438: Collective on TS
2440: Input Parameter:
2441: . ts - the TS context obtained from TSCreate()
2443: Level: advanced
2445: .keywords: TS, timestep, setup
2447: .seealso: TSCreate(), TSAdjointStep(), TSSetCostGradients()
2448: @*/
2449: PetscErrorCode TSAdjointSetUp(TS ts)
2450: {
2455: if (ts->adjointsetupcalled) return(0);
2456: if (!ts->vecs_sensi) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Must call TSSetCostGradients() first");
2458: if (ts->vec_costintegral) { /* if there is integral in the cost function*/
2459: VecDuplicateVecs(ts->vecs_sensi[0],ts->numcost,&ts->vecs_drdy);
2460: if (ts->vecs_sensip){
2461: VecDuplicateVecs(ts->vecs_sensip[0],ts->numcost,&ts->vecs_drdp);
2462: }
2463: }
2465: if (ts->ops->adjointsetup) {
2466: (*ts->ops->adjointsetup)(ts);
2467: }
2468: ts->adjointsetupcalled = PETSC_TRUE;
2469: return(0);
2470: }
2474: /*@
2475: TSReset - Resets a TS context and removes any allocated Vecs and Mats.
2477: Collective on TS
2479: Input Parameter:
2480: . ts - the TS context obtained from TSCreate()
2482: Level: beginner
2484: .keywords: TS, timestep, reset
2486: .seealso: TSCreate(), TSSetup(), TSDestroy()
2487: @*/
2488: PetscErrorCode TSReset(TS ts)
2489: {
2495: if (ts->ops->reset) {
2496: (*ts->ops->reset)(ts);
2497: }
2498: if (ts->snes) {SNESReset(ts->snes);}
2499: if (ts->adapt) {TSAdaptReset(ts->adapt);}
2501: MatDestroy(&ts->Arhs);
2502: MatDestroy(&ts->Brhs);
2503: VecDestroy(&ts->Frhs);
2504: VecDestroy(&ts->vec_sol);
2505: VecDestroy(&ts->vec_dot);
2506: VecDestroy(&ts->vatol);
2507: VecDestroy(&ts->vrtol);
2508: VecDestroyVecs(ts->nwork,&ts->work);
2510: if (ts->vec_costintegral) {
2511: VecDestroyVecs(ts->numcost,&ts->vecs_drdy);
2512: if (ts->vecs_drdp){
2513: VecDestroyVecs(ts->numcost,&ts->vecs_drdp);
2514: }
2515: }
2516: ts->vecs_sensi = NULL;
2517: ts->vecs_sensip = NULL;
2518: MatDestroy(&ts->Jacp);
2519: VecDestroy(&ts->vec_costintegral);
2520: VecDestroy(&ts->vec_costintegrand);
2521: ts->setupcalled = PETSC_FALSE;
2522: return(0);
2523: }
2527: /*@
2528: TSDestroy - Destroys the timestepper context that was created
2529: with TSCreate().
2531: Collective on TS
2533: Input Parameter:
2534: . ts - the TS context obtained from TSCreate()
2536: Level: beginner
2538: .keywords: TS, timestepper, destroy
2540: .seealso: TSCreate(), TSSetUp(), TSSolve()
2541: @*/
2542: PetscErrorCode TSDestroy(TS *ts)
2543: {
2547: if (!*ts) return(0);
2549: if (--((PetscObject)(*ts))->refct > 0) {*ts = 0; return(0);}
2551: TSReset((*ts));
2553: /* if memory was published with SAWs then destroy it */
2554: PetscObjectSAWsViewOff((PetscObject)*ts);
2555: if ((*ts)->ops->destroy) {(*(*ts)->ops->destroy)((*ts));}
2557: TSTrajectoryDestroy(&(*ts)->trajectory);
2559: TSAdaptDestroy(&(*ts)->adapt);
2560: TSEventDestroy(&(*ts)->event);
2562: SNESDestroy(&(*ts)->snes);
2563: DMDestroy(&(*ts)->dm);
2564: TSMonitorCancel((*ts));
2565: TSAdjointMonitorCancel((*ts));
2567: PetscHeaderDestroy(ts);
2568: return(0);
2569: }
2573: /*@
2574: TSGetSNES - Returns the SNES (nonlinear solver) associated with
2575: a TS (timestepper) context. Valid only for nonlinear problems.
2577: Not Collective, but SNES is parallel if TS is parallel
2579: Input Parameter:
2580: . ts - the TS context obtained from TSCreate()
2582: Output Parameter:
2583: . snes - the nonlinear solver context
2585: Notes:
2586: The user can then directly manipulate the SNES context to set various
2587: options, etc. Likewise, the user can then extract and manipulate the
2588: KSP, KSP, and PC contexts as well.
2590: TSGetSNES() does not work for integrators that do not use SNES; in
2591: this case TSGetSNES() returns NULL in snes.
2593: Level: beginner
2595: .keywords: timestep, get, SNES
2596: @*/
2597: PetscErrorCode TSGetSNES(TS ts,SNES *snes)
2598: {
2604: if (!ts->snes) {
2605: SNESCreate(PetscObjectComm((PetscObject)ts),&ts->snes);
2606: SNESSetFunction(ts->snes,NULL,SNESTSFormFunction,ts);
2607: PetscLogObjectParent((PetscObject)ts,(PetscObject)ts->snes);
2608: PetscObjectIncrementTabLevel((PetscObject)ts->snes,(PetscObject)ts,1);
2609: if (ts->dm) {SNESSetDM(ts->snes,ts->dm);}
2610: if (ts->problem_type == TS_LINEAR) {
2611: SNESSetType(ts->snes,SNESKSPONLY);
2612: }
2613: }
2614: *snes = ts->snes;
2615: return(0);
2616: }
2620: /*@
2621: TSSetSNES - Set the SNES (nonlinear solver) to be used by the timestepping context
2623: Collective
2625: Input Parameter:
2626: + ts - the TS context obtained from TSCreate()
2627: - snes - the nonlinear solver context
2629: Notes:
2630: Most users should have the TS created by calling TSGetSNES()
2632: Level: developer
2634: .keywords: timestep, set, SNES
2635: @*/
2636: PetscErrorCode TSSetSNES(TS ts,SNES snes)
2637: {
2639: PetscErrorCode (*func)(SNES,Vec,Mat,Mat,void*);
2644: PetscObjectReference((PetscObject)snes);
2645: SNESDestroy(&ts->snes);
2647: ts->snes = snes;
2649: SNESSetFunction(ts->snes,NULL,SNESTSFormFunction,ts);
2650: SNESGetJacobian(ts->snes,NULL,NULL,&func,NULL);
2651: if (func == SNESTSFormJacobian) {
2652: SNESSetJacobian(ts->snes,NULL,NULL,SNESTSFormJacobian,ts);
2653: }
2654: return(0);
2655: }
2659: /*@
2660: TSGetKSP - Returns the KSP (linear solver) associated with
2661: a TS (timestepper) context.
2663: Not Collective, but KSP is parallel if TS is parallel
2665: Input Parameter:
2666: . ts - the TS context obtained from TSCreate()
2668: Output Parameter:
2669: . ksp - the nonlinear solver context
2671: Notes:
2672: The user can then directly manipulate the KSP context to set various
2673: options, etc. Likewise, the user can then extract and manipulate the
2674: KSP and PC contexts as well.
2676: TSGetKSP() does not work for integrators that do not use KSP;
2677: in this case TSGetKSP() returns NULL in ksp.
2679: Level: beginner
2681: .keywords: timestep, get, KSP
2682: @*/
2683: PetscErrorCode TSGetKSP(TS ts,KSP *ksp)
2684: {
2686: SNES snes;
2691: if (!((PetscObject)ts)->type_name) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_NULL,"KSP is not created yet. Call TSSetType() first");
2692: if (ts->problem_type != TS_LINEAR) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,"Linear only; use TSGetSNES()");
2693: TSGetSNES(ts,&snes);
2694: SNESGetKSP(snes,ksp);
2695: return(0);
2696: }
2698: /* ----------- Routines to set solver parameters ---------- */
2702: /*@
2703: TSGetDuration - Gets the maximum number of timesteps to use and
2704: maximum time for iteration.
2706: Not Collective
2708: Input Parameters:
2709: + ts - the TS context obtained from TSCreate()
2710: . maxsteps - maximum number of iterations to use, or NULL
2711: - maxtime - final time to iterate to, or NULL
2713: Level: intermediate
2715: .keywords: TS, timestep, get, maximum, iterations, time
2716: @*/
2717: PetscErrorCode TSGetDuration(TS ts, PetscInt *maxsteps, PetscReal *maxtime)
2718: {
2721: if (maxsteps) {
2723: *maxsteps = ts->max_steps;
2724: }
2725: if (maxtime) {
2727: *maxtime = ts->max_time;
2728: }
2729: return(0);
2730: }
2734: /*@
2735: TSSetDuration - Sets the maximum number of timesteps to use and
2736: maximum time for iteration.
2738: Logically Collective on TS
2740: Input Parameters:
2741: + ts - the TS context obtained from TSCreate()
2742: . maxsteps - maximum number of iterations to use
2743: - maxtime - final time to iterate to
2745: Options Database Keys:
2746: . -ts_max_steps <maxsteps> - Sets maxsteps
2747: . -ts_final_time <maxtime> - Sets maxtime
2749: Notes:
2750: The default maximum number of iterations is 5000. Default time is 5.0
2752: Level: intermediate
2754: .keywords: TS, timestep, set, maximum, iterations
2756: .seealso: TSSetExactFinalTime()
2757: @*/
2758: PetscErrorCode TSSetDuration(TS ts,PetscInt maxsteps,PetscReal maxtime)
2759: {
2764: if (maxsteps >= 0) ts->max_steps = maxsteps;
2765: if (maxtime != PETSC_DEFAULT) ts->max_time = maxtime;
2766: return(0);
2767: }
2771: /*@
2772: TSSetSolution - Sets the initial solution vector
2773: for use by the TS routines.
2775: Logically Collective on TS and Vec
2777: Input Parameters:
2778: + ts - the TS context obtained from TSCreate()
2779: - u - the solution vector
2781: Level: beginner
2783: .keywords: TS, timestep, set, solution, initial conditions
2784: @*/
2785: PetscErrorCode TSSetSolution(TS ts,Vec u)
2786: {
2788: DM dm;
2793: PetscObjectReference((PetscObject)u);
2794: VecDestroy(&ts->vec_sol);
2795: ts->vec_sol = u;
2797: TSGetDM(ts,&dm);
2798: DMShellSetGlobalVector(dm,u);
2799: return(0);
2800: }
2804: /*@
2805: TSAdjointSetSteps - Sets the number of steps the adjoint solver should take backward in time
2807: Logically Collective on TS
2809: Input Parameters:
2810: + ts - the TS context obtained from TSCreate()
2811: . steps - number of steps to use
2813: Level: intermediate
2815: Notes: Normally one does not call this and TSAdjointSolve() integrates back to the original timestep. One can call this
2816: so as to integrate back to less than the original timestep
2818: .keywords: TS, timestep, set, maximum, iterations
2820: .seealso: TSSetExactFinalTime()
2821: @*/
2822: PetscErrorCode TSAdjointSetSteps(TS ts,PetscInt steps)
2823: {
2827: if (steps < 0) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_ARG_OUTOFRANGE,"Cannot step back a negative number of steps");
2828: if (steps > ts->total_steps) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_ARG_OUTOFRANGE,"Cannot step back more than the total number of forward steps");
2829: ts->adjoint_max_steps = steps;
2830: return(0);
2831: }
2835: /*@
2836: TSSetCostGradients - Sets the initial value of the gradients of the cost function w.r.t. initial conditions and w.r.t. the problem parameters
2837: for use by the TSAdjoint routines.
2839: Logically Collective on TS and Vec
2841: Input Parameters:
2842: + ts - the TS context obtained from TSCreate()
2843: . lambda - gradients with respect to the initial condition variables, the dimension and parallel layout of these vectors is the same as the ODE solution vector
2844: - mu - gradients with respect to the parameters, the number of entries in these vectors is the same as the number of parameters
2846: Level: beginner
2848: Notes: the entries in these vectors must be correctly initialized with the values lamda_i = df/dy|finaltime mu_i = df/dp|finaltime
2850: .keywords: TS, timestep, set, sensitivity, initial conditions
2851: @*/
2852: PetscErrorCode TSSetCostGradients(TS ts,PetscInt numcost,Vec *lambda,Vec *mu)
2853: {
2857: ts->vecs_sensi = lambda;
2858: ts->vecs_sensip = mu;
2859: if (ts->numcost && ts->numcost!=numcost) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_USER,"The number of cost functions (2rd parameter of TSSetCostIntegrand()) is inconsistent with the one set by TSSetCostIntegrand");
2860: ts->numcost = numcost;
2861: return(0);
2862: }
2866: /*@C
2867: TSAdjointSetRHSJacobian - Sets the function that computes the Jacobian of G w.r.t. the parameters p where y_t = G(y,p,t), as well as the location to store the matrix.
2869: Logically Collective on TS
2871: Input Parameters:
2872: + ts - The TS context obtained from TSCreate()
2873: - func - The function
2875: Calling sequence of func:
2876: $ func (TS ts,PetscReal t,Vec y,Mat A,void *ctx);
2877: + t - current timestep
2878: . y - input vector (current ODE solution)
2879: . A - output matrix
2880: - ctx - [optional] user-defined function context
2882: Level: intermediate
2884: Notes: Amat has the same number of rows and the same row parallel layout as u, Amat has the same number of columns and parallel layout as p
2886: .keywords: TS, sensitivity
2887: .seealso:
2888: @*/
2889: PetscErrorCode TSAdjointSetRHSJacobian(TS ts,Mat Amat,PetscErrorCode (*func)(TS,PetscReal,Vec,Mat,void*),void *ctx)
2890: {
2897: ts->rhsjacobianp = func;
2898: ts->rhsjacobianpctx = ctx;
2899: if(Amat) {
2900: PetscObjectReference((PetscObject)Amat);
2901: MatDestroy(&ts->Jacp);
2902: ts->Jacp = Amat;
2903: }
2904: return(0);
2905: }
2909: /*@C
2910: TSAdjointComputeRHSJacobian - Runs the user-defined Jacobian function.
2912: Collective on TS
2914: Input Parameters:
2915: . ts - The TS context obtained from TSCreate()
2917: Level: developer
2919: .keywords: TS, sensitivity
2920: .seealso: TSAdjointSetRHSJacobian()
2921: @*/
2922: PetscErrorCode TSAdjointComputeRHSJacobian(TS ts,PetscReal t,Vec X,Mat Amat)
2923: {
2931: PetscStackPush("TS user JacobianP function for sensitivity analysis");
2932: (*ts->rhsjacobianp)(ts,t,X,Amat,ts->rhsjacobianpctx);
2933: PetscStackPop;
2934: return(0);
2935: }
2939: /*@C
2940: TSSetCostIntegrand - Sets the routine for evaluating the integral term in one or more cost functions
2942: Logically Collective on TS
2944: Input Parameters:
2945: + ts - the TS context obtained from TSCreate()
2946: . numcost - number of gradients to be computed, this is the number of cost functions
2947: . rf - routine for evaluating the integrand function
2948: . drdyf - function that computes the gradients of the r's with respect to y,NULL if not a function y
2949: . drdpf - function that computes the gradients of the r's with respect to p, NULL if not a function of p
2950: . fwd ï¼ flag indicating whether to evaluate cost integral in the forward run or the adjoint run
2951: - ctx - [optional] user-defined context for private data for the function evaluation routine (may be NULL)
2953: Calling sequence of rf:
2954: $ rf(TS ts,PetscReal t,Vec y,Vec f[],void *ctx);
2956: + t - current timestep
2957: . y - input vector
2958: . f - function result; one vector entry for each cost function
2959: - ctx - [optional] user-defined function context
2961: Calling sequence of drdyf:
2962: $ PetscErroCode drdyf(TS ts,PetscReal t,Vec y,Vec *drdy,void *ctx);
2964: Calling sequence of drdpf:
2965: $ PetscErroCode drdpf(TS ts,PetscReal t,Vec y,Vec *drdp,void *ctx);
2967: Level: intermediate
2969: Notes: For optimization there is generally a single cost function, numcost = 1. For sensitivities there may be multiple cost functions
2971: .keywords: TS, sensitivity analysis, timestep, set, quadrature, function
2973: .seealso: TSAdjointSetRHSJacobian(),TSGetCostGradients(), TSSetCostGradients()
2974: @*/
2975: PetscErrorCode TSSetCostIntegrand(TS ts,PetscInt numcost,PetscErrorCode (*rf)(TS,PetscReal,Vec,Vec,void*),
2976: PetscErrorCode (*drdyf)(TS,PetscReal,Vec,Vec*,void*),
2977: PetscErrorCode (*drdpf)(TS,PetscReal,Vec,Vec*,void*),
2978: PetscBool fwd,void *ctx)
2979: {
2984: if (ts->numcost && ts->numcost!=numcost) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_USER,"The number of cost functions (2rd parameter of TSSetCostIntegrand()) is inconsistent with the one set by TSSetCostGradients()");
2985: if (!ts->numcost) ts->numcost=numcost;
2987: ts->costintegralfwd = fwd; /* Evaluate the cost integral in forward run if fwd is true */
2988: VecCreateSeq(PETSC_COMM_SELF,numcost,&ts->vec_costintegral);
2989: VecDuplicate(ts->vec_costintegral,&ts->vec_costintegrand);
2990: ts->costintegrand = rf;
2991: ts->costintegrandctx = ctx;
2992: ts->drdyfunction = drdyf;
2993: ts->drdpfunction = drdpf;
2994: return(0);
2995: }
2999: /*@
3000: TSGetCostIntegral - Returns the values of the integral term in the cost functions.
3001: It is valid to call the routine after a backward run.
3003: Not Collective
3005: Input Parameter:
3006: . ts - the TS context obtained from TSCreate()
3008: Output Parameter:
3009: . v - the vector containing the integrals for each cost function
3011: Level: intermediate
3013: .seealso: TSSetCostIntegrand()
3015: .keywords: TS, sensitivity analysis
3016: @*/
3017: PetscErrorCode TSGetCostIntegral(TS ts,Vec *v)
3018: {
3022: *v = ts->vec_costintegral;
3023: return(0);
3024: }
3028: /*@
3029: TSAdjointComputeCostIntegrand - Evaluates the integral function in the cost functions.
3031: Input Parameters:
3032: + ts - the TS context
3033: . t - current time
3034: - y - state vector, i.e. current solution
3036: Output Parameter:
3037: . q - vector of size numcost to hold the outputs
3039: Note:
3040: Most users should not need to explicitly call this routine, as it
3041: is used internally within the sensitivity analysis context.
3043: Level: developer
3045: .keywords: TS, compute
3047: .seealso: TSSetCostIntegrand()
3048: @*/
3049: PetscErrorCode TSAdjointComputeCostIntegrand(TS ts,PetscReal t,Vec y,Vec q)
3050: {
3058: PetscLogEventBegin(TS_FunctionEval,ts,y,q,0);
3059: if (ts->costintegrand) {
3060: PetscStackPush("TS user integrand in the cost function");
3061: (*ts->costintegrand)(ts,t,y,q,ts->costintegrandctx);
3062: PetscStackPop;
3063: } else {
3064: VecZeroEntries(q);
3065: }
3067: PetscLogEventEnd(TS_FunctionEval,ts,y,q,0);
3068: return(0);
3069: }
3073: /*@
3074: TSAdjointComputeDRDYFunction - Runs the user-defined DRDY function.
3076: Collective on TS
3078: Input Parameters:
3079: . ts - The TS context obtained from TSCreate()
3081: Notes:
3082: TSAdjointComputeDRDYFunction() is typically used for sensitivity implementation,
3083: so most users would not generally call this routine themselves.
3085: Level: developer
3087: .keywords: TS, sensitivity
3088: .seealso: TSAdjointComputeDRDYFunction()
3089: @*/
3090: PetscErrorCode TSAdjointComputeDRDYFunction(TS ts,PetscReal t,Vec y,Vec *drdy)
3091: {
3098: PetscStackPush("TS user DRDY function for sensitivity analysis");
3099: (*ts->drdyfunction)(ts,t,y,drdy,ts->costintegrandctx);
3100: PetscStackPop;
3101: return(0);
3102: }
3106: /*@
3107: TSAdjointComputeDRDPFunction - Runs the user-defined DRDP function.
3109: Collective on TS
3111: Input Parameters:
3112: . ts - The TS context obtained from TSCreate()
3114: Notes:
3115: TSDRDPFunction() is typically used for sensitivity implementation,
3116: so most users would not generally call this routine themselves.
3118: Level: developer
3120: .keywords: TS, sensitivity
3121: .seealso: TSAdjointSetDRDPFunction()
3122: @*/
3123: PetscErrorCode TSAdjointComputeDRDPFunction(TS ts,PetscReal t,Vec y,Vec *drdp)
3124: {
3131: PetscStackPush("TS user DRDP function for sensitivity analysis");
3132: (*ts->drdpfunction)(ts,t,y,drdp,ts->costintegrandctx);
3133: PetscStackPop;
3134: return(0);
3135: }
3139: /*@C
3140: TSSetPreStep - Sets the general-purpose function
3141: called once at the beginning of each time step.
3143: Logically Collective on TS
3145: Input Parameters:
3146: + ts - The TS context obtained from TSCreate()
3147: - func - The function
3149: Calling sequence of func:
3150: . func (TS ts);
3152: Level: intermediate
3154: Note:
3155: If a step is rejected, TSStep() will call this routine again before each attempt.
3156: The last completed time step number can be queried using TSGetTimeStepNumber(), the
3157: size of the step being attempted can be obtained using TSGetTimeStep().
3159: .keywords: TS, timestep
3160: .seealso: TSSetPreStage(), TSSetPostStage(), TSSetPostStep(), TSStep()
3161: @*/
3162: PetscErrorCode TSSetPreStep(TS ts, PetscErrorCode (*func)(TS))
3163: {
3166: ts->prestep = func;
3167: return(0);
3168: }
3172: /*@
3173: TSPreStep - Runs the user-defined pre-step function.
3175: Collective on TS
3177: Input Parameters:
3178: . ts - The TS context obtained from TSCreate()
3180: Notes:
3181: TSPreStep() is typically used within time stepping implementations,
3182: so most users would not generally call this routine themselves.
3184: Level: developer
3186: .keywords: TS, timestep
3187: .seealso: TSSetPreStep(), TSPreStage(), TSPostStage(), TSPostStep()
3188: @*/
3189: PetscErrorCode TSPreStep(TS ts)
3190: {
3195: if (ts->prestep) {
3196: PetscStackCallStandard((*ts->prestep),(ts));
3197: }
3198: return(0);
3199: }
3203: /*@C
3204: TSSetPreStage - Sets the general-purpose function
3205: called once at the beginning of each stage.
3207: Logically Collective on TS
3209: Input Parameters:
3210: + ts - The TS context obtained from TSCreate()
3211: - func - The function
3213: Calling sequence of func:
3214: . PetscErrorCode func(TS ts, PetscReal stagetime);
3216: Level: intermediate
3218: Note:
3219: There may be several stages per time step. If the solve for a given stage fails, the step may be rejected and retried.
3220: The time step number being computed can be queried using TSGetTimeStepNumber() and the total size of the step being
3221: attempted can be obtained using TSGetTimeStep(). The time at the start of the step is available via TSGetTime().
3223: .keywords: TS, timestep
3224: .seealso: TSSetPostStage(), TSSetPreStep(), TSSetPostStep(), TSGetApplicationContext()
3225: @*/
3226: PetscErrorCode TSSetPreStage(TS ts, PetscErrorCode (*func)(TS,PetscReal))
3227: {
3230: ts->prestage = func;
3231: return(0);
3232: }
3236: /*@C
3237: TSSetPostStage - Sets the general-purpose function
3238: called once at the end of each stage.
3240: Logically Collective on TS
3242: Input Parameters:
3243: + ts - The TS context obtained from TSCreate()
3244: - func - The function
3246: Calling sequence of func:
3247: . PetscErrorCode func(TS ts, PetscReal stagetime, PetscInt stageindex, Vec* Y);
3249: Level: intermediate
3251: Note:
3252: There may be several stages per time step. If the solve for a given stage fails, the step may be rejected and retried.
3253: The time step number being computed can be queried using TSGetTimeStepNumber() and the total size of the step being
3254: attempted can be obtained using TSGetTimeStep(). The time at the start of the step is available via TSGetTime().
3256: .keywords: TS, timestep
3257: .seealso: TSSetPreStage(), TSSetPreStep(), TSSetPostStep(), TSGetApplicationContext()
3258: @*/
3259: PetscErrorCode TSSetPostStage(TS ts, PetscErrorCode (*func)(TS,PetscReal,PetscInt,Vec*))
3260: {
3263: ts->poststage = func;
3264: return(0);
3265: }
3269: /*@
3270: TSPreStage - Runs the user-defined pre-stage function set using TSSetPreStage()
3272: Collective on TS
3274: Input Parameters:
3275: . ts - The TS context obtained from TSCreate()
3276: stagetime - The absolute time of the current stage
3278: Notes:
3279: TSPreStage() is typically used within time stepping implementations,
3280: most users would not generally call this routine themselves.
3282: Level: developer
3284: .keywords: TS, timestep
3285: .seealso: TSPostStage(), TSSetPreStep(), TSPreStep(), TSPostStep()
3286: @*/
3287: PetscErrorCode TSPreStage(TS ts, PetscReal stagetime)
3288: {
3293: if (ts->prestage) {
3294: PetscStackCallStandard((*ts->prestage),(ts,stagetime));
3295: }
3296: return(0);
3297: }
3301: /*@
3302: TSPostStage - Runs the user-defined post-stage function set using TSSetPostStage()
3304: Collective on TS
3306: Input Parameters:
3307: . ts - The TS context obtained from TSCreate()
3308: stagetime - The absolute time of the current stage
3309: stageindex - Stage number
3310: Y - Array of vectors (of size = total number
3311: of stages) with the stage solutions
3313: Notes:
3314: TSPostStage() is typically used within time stepping implementations,
3315: most users would not generally call this routine themselves.
3317: Level: developer
3319: .keywords: TS, timestep
3320: .seealso: TSPreStage(), TSSetPreStep(), TSPreStep(), TSPostStep()
3321: @*/
3322: PetscErrorCode TSPostStage(TS ts, PetscReal stagetime, PetscInt stageindex, Vec *Y)
3323: {
3328: if (ts->poststage) {
3329: PetscStackCallStandard((*ts->poststage),(ts,stagetime,stageindex,Y));
3330: }
3331: return(0);
3332: }
3336: /*@C
3337: TSSetPostStep - Sets the general-purpose function
3338: called once at the end of each time step.
3340: Logically Collective on TS
3342: Input Parameters:
3343: + ts - The TS context obtained from TSCreate()
3344: - func - The function
3346: Calling sequence of func:
3347: $ func (TS ts);
3349: Level: intermediate
3351: .keywords: TS, timestep
3352: .seealso: TSSetPreStep(), TSSetPreStage(), TSGetTimeStep(), TSGetTimeStepNumber(), TSGetTime()
3353: @*/
3354: PetscErrorCode TSSetPostStep(TS ts, PetscErrorCode (*func)(TS))
3355: {
3358: ts->poststep = func;
3359: return(0);
3360: }
3364: /*@
3365: TSPostStep - Runs the user-defined post-step function.
3367: Collective on TS
3369: Input Parameters:
3370: . ts - The TS context obtained from TSCreate()
3372: Notes:
3373: TSPostStep() is typically used within time stepping implementations,
3374: so most users would not generally call this routine themselves.
3376: Level: developer
3378: .keywords: TS, timestep
3379: @*/
3380: PetscErrorCode TSPostStep(TS ts)
3381: {
3386: if (ts->poststep) {
3387: PetscStackCallStandard((*ts->poststep),(ts));
3388: }
3389: return(0);
3390: }
3392: /* ------------ Routines to set performance monitoring options ----------- */
3396: /*@C
3397: TSMonitorSet - Sets an ADDITIONAL function that is to be used at every
3398: timestep to display the iteration's progress.
3400: Logically Collective on TS
3402: Input Parameters:
3403: + ts - the TS context obtained from TSCreate()
3404: . monitor - monitoring routine
3405: . mctx - [optional] user-defined context for private data for the
3406: monitor routine (use NULL if no context is desired)
3407: - monitordestroy - [optional] routine that frees monitor context
3408: (may be NULL)
3410: Calling sequence of monitor:
3411: $ int monitor(TS ts,PetscInt steps,PetscReal time,Vec u,void *mctx)
3413: + ts - the TS context
3414: . steps - iteration number (after the final time step the monitor routine may be called with a step of -1, this indicates the solution has been interpolated to this time)
3415: . time - current time
3416: . u - current iterate
3417: - mctx - [optional] monitoring context
3419: Notes:
3420: This routine adds an additional monitor to the list of monitors that
3421: already has been loaded.
3423: Fortran notes: Only a single monitor function can be set for each TS object
3425: Level: intermediate
3427: .keywords: TS, timestep, set, monitor
3429: .seealso: TSMonitorDefault(), TSMonitorCancel()
3430: @*/
3431: PetscErrorCode TSMonitorSet(TS ts,PetscErrorCode (*monitor)(TS,PetscInt,PetscReal,Vec,void*),void *mctx,PetscErrorCode (*mdestroy)(void**))
3432: {
3435: if (ts->numbermonitors >= MAXTSMONITORS) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Too many monitors set");
3436: ts->monitor[ts->numbermonitors] = monitor;
3437: ts->monitordestroy[ts->numbermonitors] = mdestroy;
3438: ts->monitorcontext[ts->numbermonitors++] = (void*)mctx;
3439: return(0);
3440: }
3444: /*@C
3445: TSMonitorCancel - Clears all the monitors that have been set on a time-step object.
3447: Logically Collective on TS
3449: Input Parameters:
3450: . ts - the TS context obtained from TSCreate()
3452: Notes:
3453: There is no way to remove a single, specific monitor.
3455: Level: intermediate
3457: .keywords: TS, timestep, set, monitor
3459: .seealso: TSMonitorDefault(), TSMonitorSet()
3460: @*/
3461: PetscErrorCode TSMonitorCancel(TS ts)
3462: {
3464: PetscInt i;
3468: for (i=0; i<ts->numbermonitors; i++) {
3469: if (ts->monitordestroy[i]) {
3470: (*ts->monitordestroy[i])(&ts->monitorcontext[i]);
3471: }
3472: }
3473: ts->numbermonitors = 0;
3474: return(0);
3475: }
3479: /*@C
3480: TSMonitorDefault - The Default monitor, prints the timestep and time for each step
3482: Level: intermediate
3484: .keywords: TS, set, monitor
3486: .seealso: TSMonitorSet()
3487: @*/
3488: PetscErrorCode TSMonitorDefault(TS ts,PetscInt step,PetscReal ptime,Vec v,PetscViewerAndFormat *vf)
3489: {
3491: PetscViewer viewer = vf->viewer;
3492: PetscBool iascii,ibinary;
3496: PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERASCII,&iascii);
3497: PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERBINARY,&ibinary);
3498: PetscViewerPushFormat(viewer,vf->format);
3499: if (iascii) {
3500: PetscViewerASCIIAddTab(viewer,((PetscObject)ts)->tablevel);
3501: if (step == -1){ /* this indicates it is an interpolated solution */
3502: PetscViewerASCIIPrintf(viewer,"Interpolated solution at time %g between steps %D and %D\n",(double)ptime,ts->steps-1,ts->steps);
3503: } else {
3504: PetscViewerASCIIPrintf(viewer,"%D TS dt %g time %g%s",step,(double)ts->time_step,(double)ptime,ts->steprollback ? " (r)\n" : "\n");
3505: }
3506: PetscViewerASCIISubtractTab(viewer,((PetscObject)ts)->tablevel);
3507: } else if (ibinary) {
3508: PetscMPIInt rank;
3509: MPI_Comm_rank(PetscObjectComm((PetscObject)viewer),&rank);
3510: if (!rank) {
3511: PetscRealView(1,&ptime,viewer);
3512: } else {
3513: PetscRealView(0,&ptime,viewer);
3514: }
3515: }
3516: PetscViewerPopFormat(viewer);
3517: return(0);
3518: }
3522: /*@C
3523: TSAdjointMonitorSet - Sets an ADDITIONAL function that is to be used at every
3524: timestep to display the iteration's progress.
3526: Logically Collective on TS
3528: Input Parameters:
3529: + ts - the TS context obtained from TSCreate()
3530: . adjointmonitor - monitoring routine
3531: . adjointmctx - [optional] user-defined context for private data for the
3532: monitor routine (use NULL if no context is desired)
3533: - adjointmonitordestroy - [optional] routine that frees monitor context
3534: (may be NULL)
3536: Calling sequence of monitor:
3537: $ int adjointmonitor(TS ts,PetscInt steps,PetscReal time,Vec u,PetscInt numcost,Vec *lambda, Vec *mu,void *adjointmctx)
3539: + ts - the TS context
3540: . steps - iteration number (after the final time step the monitor routine is called with a step of -1, this is at the final time which may have
3541: been interpolated to)
3542: . time - current time
3543: . u - current iterate
3544: . numcost - number of cost functionos
3545: . lambda - sensitivities to initial conditions
3546: . mu - sensitivities to parameters
3547: - adjointmctx - [optional] adjoint monitoring context
3549: Notes:
3550: This routine adds an additional monitor to the list of monitors that
3551: already has been loaded.
3553: Fortran notes: Only a single monitor function can be set for each TS object
3555: Level: intermediate
3557: .keywords: TS, timestep, set, adjoint, monitor
3559: .seealso: TSAdjointMonitorCancel()
3560: @*/
3561: PetscErrorCode TSAdjointMonitorSet(TS ts,PetscErrorCode (*adjointmonitor)(TS,PetscInt,PetscReal,Vec,PetscInt,Vec*,Vec*,void*),void *adjointmctx,PetscErrorCode (*adjointmdestroy)(void**))
3562: {
3565: if (ts->numberadjointmonitors >= MAXTSMONITORS) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Too many adjoint monitors set");
3566: ts->adjointmonitor[ts->numberadjointmonitors] = adjointmonitor;
3567: ts->adjointmonitordestroy[ts->numberadjointmonitors] = adjointmdestroy;
3568: ts->adjointmonitorcontext[ts->numberadjointmonitors++] = (void*)adjointmctx;
3569: return(0);
3570: }
3574: /*@C
3575: TSAdjointMonitorCancel - Clears all the adjoint monitors that have been set on a time-step object.
3577: Logically Collective on TS
3579: Input Parameters:
3580: . ts - the TS context obtained from TSCreate()
3582: Notes:
3583: There is no way to remove a single, specific monitor.
3585: Level: intermediate
3587: .keywords: TS, timestep, set, adjoint, monitor
3589: .seealso: TSAdjointMonitorSet()
3590: @*/
3591: PetscErrorCode TSAdjointMonitorCancel(TS ts)
3592: {
3594: PetscInt i;
3598: for (i=0; i<ts->numberadjointmonitors; i++) {
3599: if (ts->adjointmonitordestroy[i]) {
3600: (*ts->adjointmonitordestroy[i])(&ts->adjointmonitorcontext[i]);
3601: }
3602: }
3603: ts->numberadjointmonitors = 0;
3604: return(0);
3605: }
3609: /*@C
3610: TSAdjointMonitorDefault - the default monitor of adjoint computations
3612: Level: intermediate
3614: .keywords: TS, set, monitor
3616: .seealso: TSAdjointMonitorSet()
3617: @*/
3618: PetscErrorCode TSAdjointMonitorDefault(TS ts,PetscInt step,PetscReal ptime,Vec v,PetscInt numcost,Vec *lambda,Vec *mu,PetscViewerAndFormat *vf)
3619: {
3621: PetscViewer viewer = vf->viewer;
3625: PetscViewerPushFormat(viewer,vf->format);
3626: PetscViewerASCIIAddTab(viewer,((PetscObject)ts)->tablevel);
3627: PetscViewerASCIIPrintf(viewer,"%D TS dt %g time %g%s",step,(double)ts->time_step,(double)ptime,ts->steprollback ? " (r)\n" : "\n");
3628: PetscViewerASCIISubtractTab(viewer,((PetscObject)ts)->tablevel);
3629: PetscViewerPopFormat(viewer);
3630: return(0);
3631: }
3635: /*@
3636: TSInterpolate - Interpolate the solution computed during the previous step to an arbitrary location in the interval
3638: Collective on TS
3640: Input Argument:
3641: + ts - time stepping context
3642: - t - time to interpolate to
3644: Output Argument:
3645: . U - state at given time
3647: Level: intermediate
3649: Developer Notes:
3650: TSInterpolate() and the storing of previous steps/stages should be generalized to support delay differential equations and continuous adjoints.
3652: .keywords: TS, set
3654: .seealso: TSSetExactFinalTime(), TSSolve()
3655: @*/
3656: PetscErrorCode TSInterpolate(TS ts,PetscReal t,Vec U)
3657: {
3663: if (t < ts->ptime_prev || t > ts->ptime) SETERRQ3(PetscObjectComm((PetscObject)ts),PETSC_ERR_ARG_OUTOFRANGE,"Requested time %g not in last time steps [%g,%g]",t,(double)ts->ptime_prev,(double)ts->ptime);
3664: if (!ts->ops->interpolate) SETERRQ1(PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"%s does not provide interpolation",((PetscObject)ts)->type_name);
3665: (*ts->ops->interpolate)(ts,t,U);
3666: return(0);
3667: }
3671: /*@
3672: TSStep - Steps one time step
3674: Collective on TS
3676: Input Parameter:
3677: . ts - the TS context obtained from TSCreate()
3679: Level: developer
3681: Notes:
3682: The public interface for the ODE/DAE solvers is TSSolve(), you should almost for sure be using that routine and not this routine.
3684: The hook set using TSSetPreStep() is called before each attempt to take the step. In general, the time step size may
3685: be changed due to adaptive error controller or solve failures. Note that steps may contain multiple stages.
3687: This may over-step the final time provided in TSSetDuration() depending on the time-step used. TSSolve() interpolates to exactly the
3688: time provided in TSSetDuration(). One can use TSInterpolate() to determine an interpolated solution within the final timestep.
3690: .keywords: TS, timestep, solve
3692: .seealso: TSCreate(), TSSetUp(), TSDestroy(), TSSolve(), TSSetPreStep(), TSSetPreStage(), TSSetPostStage(), TSInterpolate()
3693: @*/
3694: PetscErrorCode TSStep(TS ts)
3695: {
3696: PetscErrorCode ierr;
3697: static PetscBool cite = PETSC_FALSE;
3698: PetscReal ptime;
3702: PetscCitationsRegister("@techreport{tspaper,\n"
3703: " title = {{PETSc/TS}: A Modern Scalable {DAE/ODE} Solver Library},\n"
3704: " author = {Shrirang Abhyankar and Jed Brown and Emil Constantinescu and Debojyoti Ghosh and Barry F. Smith},\n"
3705: " type = {Preprint},\n"
3706: " number = {ANL/MCS-P5061-0114},\n"
3707: " institution = {Argonne National Laboratory},\n"
3708: " year = {2014}\n}\n",&cite);
3710: TSSetUp(ts);
3711: TSTrajectorySetUp(ts->trajectory,ts);
3713: if (ts->exact_final_time == TS_EXACTFINALTIME_UNSPECIFIED) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_ARG_WRONGSTATE,"You must call TSSetExactFinalTime() or use -ts_exact_final_time <stepover,interpolate,matchstep> before calling TSStep()");
3714: if (ts->exact_final_time == TS_EXACTFINALTIME_MATCHSTEP && !ts->adapt) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"Since TS is not adaptive you cannot use TS_EXACTFINALTIME_MATCHSTEP, suggest TS_EXACTFINALTIME_INTERPOLATE");
3716: if (!ts->steps) ts->ptime_prev = ts->ptime;
3717: ts->reason = TS_CONVERGED_ITERATING;
3718: ptime = ts->ptime; ts->ptime_prev_rollback = ts->ptime_prev;
3719: if (!ts->ops->step) SETERRQ1(PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"TSStep not implemented for type '%s'",((PetscObject)ts)->type_name);
3720: PetscLogEventBegin(TS_Step,ts,0,0,0);
3721: (*ts->ops->step)(ts);
3722: PetscLogEventEnd(TS_Step,ts,0,0,0);
3723: ts->ptime_prev = ptime;
3724: ts->steps++; ts->total_steps++;
3725: ts->steprollback = PETSC_FALSE;
3726: ts->steprestart = PETSC_FALSE;
3728: if (ts->reason < 0) {
3729: if (ts->errorifstepfailed) {
3730: if (ts->reason == TS_DIVERGED_NONLINEAR_SOLVE) SETERRQ1(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]);
3731: else SETERRQ1(PetscObjectComm((PetscObject)ts),PETSC_ERR_NOT_CONVERGED,"TSStep has failed due to %s",TSConvergedReasons[ts->reason]);
3732: }
3733: } else if (!ts->reason) {
3734: if (ts->steps >= ts->max_steps) ts->reason = TS_CONVERGED_ITS;
3735: else if (ts->ptime >= ts->max_time) ts->reason = TS_CONVERGED_TIME;
3736: }
3737: return(0);
3738: }
3742: /*@
3743: TSAdjointStep - Steps one time step backward in the adjoint run
3745: Collective on TS
3747: Input Parameter:
3748: . ts - the TS context obtained from TSCreate()
3750: Level: intermediate
3752: .keywords: TS, adjoint, step
3754: .seealso: TSAdjointSetUp(), TSAdjointSolve()
3755: @*/
3756: PetscErrorCode TSAdjointStep(TS ts)
3757: {
3758: DM dm;
3759: PetscErrorCode ierr;
3763: TSGetDM(ts,&dm);
3764: TSAdjointSetUp(ts);
3766: VecViewFromOptions(ts->vec_sol,(PetscObject)ts,"-ts_view_solution");
3768: ts->reason = TS_CONVERGED_ITERATING;
3769: ts->ptime_prev = ts->ptime;
3770: if (!ts->ops->adjointstep) SETERRQ1(PetscObjectComm((PetscObject)ts),PETSC_ERR_NOT_CONVERGED,"TSStep has failed because the adjoint of %s has not been implemented, try other time stepping methods for adjoint sensitivity analysis",((PetscObject)ts)->type_name);
3771: PetscLogEventBegin(TS_AdjointStep,ts,0,0,0);
3772: (*ts->ops->adjointstep)(ts);
3773: PetscLogEventEnd(TS_AdjointStep,ts,0,0,0);
3774: ts->steps++; ts->total_steps--;
3776: if (ts->reason < 0) {
3777: if (ts->errorifstepfailed) {
3778: if (ts->reason == TS_DIVERGED_NONLINEAR_SOLVE) SETERRQ1(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]);
3779: else if (ts->reason == TS_DIVERGED_STEP_REJECTED) SETERRQ1(PetscObjectComm((PetscObject)ts),PETSC_ERR_NOT_CONVERGED,"TSStep has failed due to %s, increase -ts_max_reject or make negative to attempt recovery",TSConvergedReasons[ts->reason]);
3780: else SETERRQ1(PetscObjectComm((PetscObject)ts),PETSC_ERR_NOT_CONVERGED,"TSStep has failed due to %s",TSConvergedReasons[ts->reason]);
3781: }
3782: } else if (!ts->reason) {
3783: if (ts->steps >= ts->adjoint_max_steps) ts->reason = TS_CONVERGED_ITS;
3784: }
3785: return(0);
3786: }
3790: /*@
3791: TSEvaluateWLTE - Evaluate the weighted local truncation error norm
3792: at the end of a time step with a given order of accuracy.
3794: Collective on TS
3796: Input Arguments:
3797: + ts - time stepping context
3798: . wnormtype - norm type, either NORM_2 or NORM_INFINITY
3799: - order - optional, desired order for the error evaluation or PETSC_DECIDE
3801: Output Arguments:
3802: + order - optional, the actual order of the error evaluation
3803: - wlte - the weighted local truncation error norm
3805: Level: advanced
3807: Notes:
3808: If the timestepper cannot evaluate the error in a particular step
3809: (eg. in the first step or restart steps after event handling),
3810: this routine returns wlte=-1.0 .
3812: .seealso: TSStep(), TSAdapt, TSErrorWeightedNorm()
3813: @*/
3814: PetscErrorCode TSEvaluateWLTE(TS ts,NormType wnormtype,PetscInt *order,PetscReal *wlte)
3815: {
3825: if (wnormtype != NORM_2 && wnormtype != NORM_INFINITY) SETERRQ1(PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"No support for norm type %s",NormTypes[wnormtype]);
3826: if (!ts->ops->evaluatewlte) SETERRQ1(PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"TSEvaluateWLTE not implemented for type '%s'",((PetscObject)ts)->type_name);
3827: (*ts->ops->evaluatewlte)(ts,wnormtype,order,wlte);
3828: return(0);
3829: }
3833: /*@
3834: TSEvaluateStep - Evaluate the solution at the end of a time step with a given order of accuracy.
3836: Collective on TS
3838: Input Arguments:
3839: + ts - time stepping context
3840: . order - desired order of accuracy
3841: - done - whether the step was evaluated at this order (pass NULL to generate an error if not available)
3843: Output Arguments:
3844: . U - state at the end of the current step
3846: Level: advanced
3848: Notes:
3849: This function cannot be called until all stages have been evaluated.
3850: 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.
3852: .seealso: TSStep(), TSAdapt
3853: @*/
3854: PetscErrorCode TSEvaluateStep(TS ts,PetscInt order,Vec U,PetscBool *done)
3855: {
3862: if (!ts->ops->evaluatestep) SETERRQ1(PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"TSEvaluateStep not implemented for type '%s'",((PetscObject)ts)->type_name);
3863: (*ts->ops->evaluatestep)(ts,order,U,done);
3864: return(0);
3865: }
3869: /*@
3870: TSForwardCostIntegral - Evaluate the cost integral in the forward run.
3871:
3872: Collective on TS
3873:
3874: Input Arguments:
3875: . ts - time stepping context
3876:
3877: Level: advanced
3878:
3879: Notes:
3880: This function cannot be called until TSStep() has been completed.
3881:
3882: .seealso: TSSolve(), TSAdjointCostIntegral()
3883: @*/
3884: PetscErrorCode TSForwardCostIntegral(TS ts)
3885: {
3888: if (!ts->ops->forwardintegral) SETERRQ1(PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"%s does not provide integral evaluation in the forward run",((PetscObject)ts)->type_name);
3889: (*ts->ops->forwardintegral)(ts);
3890: return(0);
3891: }
3895: /*@
3896: TSSolve - Steps the requested number of timesteps.
3898: Collective on TS
3900: Input Parameter:
3901: + ts - the TS context obtained from TSCreate()
3902: - u - the solution vector (can be null if TSSetSolution() was used and TSSetExactFinalTime(ts,TS_EXACTFINALTIME_MATCHSTEP) was not used,
3903: otherwise must contain the initial conditions and will contain the solution at the final requested time
3905: Level: beginner
3907: Notes:
3908: The final time returned by this function may be different from the time of the internally
3909: held state accessible by TSGetSolution() and TSGetTime() because the method may have
3910: stepped over the final time.
3912: .keywords: TS, timestep, solve
3914: .seealso: TSCreate(), TSSetSolution(), TSStep(), TSGetTime(), TSGetSolveTime()
3915: @*/
3916: PetscErrorCode TSSolve(TS ts,Vec u)
3917: {
3918: Vec solution;
3919: PetscErrorCode ierr;
3925: if (ts->exact_final_time == TS_EXACTFINALTIME_INTERPOLATE) { /* Need ts->vec_sol to be distinct so it is not overwritten when we interpolate at the end */
3927: if (!ts->vec_sol || u == ts->vec_sol) {
3928: VecDuplicate(u,&solution);
3929: TSSetSolution(ts,solution);
3930: VecDestroy(&solution); /* grant ownership */
3931: }
3932: VecCopy(u,ts->vec_sol);
3933: } else if (u) {
3934: TSSetSolution(ts,u);
3935: }
3936: TSSetUp(ts);
3937: TSTrajectorySetUp(ts->trajectory,ts);
3939: if (ts->exact_final_time == TS_EXACTFINALTIME_UNSPECIFIED) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_ARG_WRONGSTATE,"You must call TSSetExactFinalTime() or use -ts_exact_final_time <stepover,interpolate,matchstep> before calling TSSolve()");
3940: if (ts->exact_final_time == TS_EXACTFINALTIME_MATCHSTEP && !ts->adapt) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"Since TS is not adaptive you cannot use TS_EXACTFINALTIME_MATCHSTEP, suggest TS_EXACTFINALTIME_INTERPOLATE");
3942: /* reset time step and iteration counters */
3943: ts->steps = 0;
3944: ts->ksp_its = 0;
3945: ts->snes_its = 0;
3946: ts->num_snes_failures = 0;
3947: ts->reject = 0;
3948: ts->reason = TS_CONVERGED_ITERATING;
3950: TSViewFromOptions(ts,NULL,"-ts_view_pre");
3952: if (ts->ops->solve) { /* This private interface is transitional and should be removed when all implementations are updated. */
3953: (*ts->ops->solve)(ts);
3954: if (u) {VecCopy(ts->vec_sol,u);}
3955: ts->solvetime = ts->ptime;
3956: solution = ts->vec_sol;
3957: } else { /* Step the requested number of timesteps. */
3958: if (ts->steps >= ts->max_steps) ts->reason = TS_CONVERGED_ITS;
3959: else if (ts->ptime >= ts->max_time) ts->reason = TS_CONVERGED_TIME;
3960: TSTrajectorySet(ts->trajectory,ts,ts->steps,ts->ptime,ts->vec_sol);
3961: TSEventInitialize(ts->event,ts,ts->ptime,ts->vec_sol);
3962: ts->steprollback = PETSC_FALSE;
3963: ts->steprestart = PETSC_TRUE;
3965: while (!ts->reason) {
3966: TSMonitor(ts,ts->steps,ts->ptime,ts->vec_sol);
3967: if (!ts->steprollback) {
3968: TSPreStep(ts);
3969: }
3970: TSStep(ts);
3971: TSEventHandler(ts);
3972: if (!ts->steprollback) {
3973: if (ts->vec_costintegral && ts->costintegralfwd) {
3974: TSForwardCostIntegral(ts);
3975: }
3976: TSTrajectorySet(ts->trajectory,ts,ts->steps,ts->ptime,ts->vec_sol);
3977: TSPostStep(ts);
3978: }
3979: }
3980: TSMonitor(ts,ts->steps,ts->ptime,ts->vec_sol);
3982: if (ts->exact_final_time == TS_EXACTFINALTIME_INTERPOLATE && ts->ptime > ts->max_time) {
3983: TSInterpolate(ts,ts->max_time,u);
3984: ts->solvetime = ts->max_time;
3985: solution = u;
3986: TSMonitor(ts,-1,ts->solvetime,solution);
3987: } else {
3988: if (u) {VecCopy(ts->vec_sol,u);}
3989: ts->solvetime = ts->ptime;
3990: solution = ts->vec_sol;
3991: }
3992: }
3994: TSViewFromOptions(ts,NULL,"-ts_view");
3995: VecViewFromOptions(solution,NULL,"-ts_view_solution");
3996: PetscObjectSAWsBlock((PetscObject)ts);
3997: if (ts->adjoint_solve) {
3998: TSAdjointSolve(ts);
3999: }
4000: return(0);
4001: }
4005: /*@
4006: TSAdjointCostIntegral - Evaluate the cost integral in the adjoint run.
4007:
4008: Collective on TS
4009:
4010: Input Arguments:
4011: . ts - time stepping context
4012:
4013: Level: advanced
4014:
4015: Notes:
4016: This function cannot be called until TSAdjointStep() has been completed.
4017:
4018: .seealso: TSAdjointSolve(), TSAdjointStep
4019: @*/
4020: PetscErrorCode TSAdjointCostIntegral(TS ts)
4021: {
4024: if (!ts->ops->adjointintegral) SETERRQ1(PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"%s does not provide integral evaluation in the adjoint run",((PetscObject)ts)->type_name);
4025: (*ts->ops->adjointintegral)(ts);
4026: return(0);
4027: }
4031: /*@
4032: TSAdjointSolve - Solves the discrete ajoint problem for an ODE/DAE
4034: Collective on TS
4036: Input Parameter:
4037: . ts - the TS context obtained from TSCreate()
4039: Options Database:
4040: . -ts_adjoint_view_solution <viewerinfo> - views the first gradient with respect to the initial conditions
4042: Level: intermediate
4044: Notes:
4045: This must be called after a call to TSSolve() that solves the forward problem
4047: By default this will integrate back to the initial time, one can use TSAdjointSetSteps() to step back to a later time
4049: .keywords: TS, timestep, solve
4051: .seealso: TSCreate(), TSSetCostGradients(), TSSetSolution(), TSAdjointStep()
4052: @*/
4053: PetscErrorCode TSAdjointSolve(TS ts)
4054: {
4055: PetscErrorCode ierr;
4059: TSAdjointSetUp(ts);
4061: /* reset time step and iteration counters */
4062: ts->steps = 0;
4063: ts->ksp_its = 0;
4064: ts->snes_its = 0;
4065: ts->num_snes_failures = 0;
4066: ts->reject = 0;
4067: ts->reason = TS_CONVERGED_ITERATING;
4069: if (!ts->adjoint_max_steps) ts->adjoint_max_steps = ts->total_steps;
4071: if (ts->steps >= ts->adjoint_max_steps) ts->reason = TS_CONVERGED_ITS;
4072: while (!ts->reason) {
4073: TSTrajectoryGet(ts->trajectory,ts,ts->total_steps,&ts->ptime);
4074: TSAdjointMonitor(ts,ts->total_steps,ts->ptime,ts->vec_sol,ts->numcost,ts->vecs_sensi,ts->vecs_sensip);
4075: TSAdjointEventHandler(ts);
4076: TSAdjointStep(ts);
4077: if (ts->vec_costintegral && !ts->costintegralfwd) {
4078: TSAdjointCostIntegral(ts);
4079: }
4080: }
4081: TSTrajectoryGet(ts->trajectory,ts,ts->total_steps,&ts->ptime);
4082: TSAdjointMonitor(ts,ts->total_steps,ts->ptime,ts->vec_sol,ts->numcost,ts->vecs_sensi,ts->vecs_sensip);
4083: ts->solvetime = ts->ptime;
4084: TSTrajectoryViewFromOptions(ts->trajectory,NULL,"-ts_trajectory_view");
4085: VecViewFromOptions(ts->vecs_sensi[0],(PetscObject) ts, "-ts_adjoint_view_solution");
4086: return(0);
4087: }
4091: /*@C
4092: TSMonitor - Runs all user-provided monitor routines set using TSMonitorSet()
4094: Collective on TS
4096: Input Parameters:
4097: + ts - time stepping context obtained from TSCreate()
4098: . step - step number that has just completed
4099: . ptime - model time of the state
4100: - u - state at the current model time
4102: Notes:
4103: TSMonitor() is typically used automatically within the time stepping implementations.
4104: Users would almost never call this routine directly.
4106: A step of -1 indicates that the monitor is being called on a solution obtained by interpolating from computed solutions
4108: Level: developer
4110: .keywords: TS, timestep
4111: @*/
4112: PetscErrorCode TSMonitor(TS ts,PetscInt step,PetscReal ptime,Vec u)
4113: {
4114: DM dm;
4115: PetscInt i,n = ts->numbermonitors;
4122: TSGetDM(ts,&dm);
4123: DMSetOutputSequenceNumber(dm,step,ptime);
4125: VecLockPush(u);
4126: for (i=0; i<n; i++) {
4127: (*ts->monitor[i])(ts,step,ptime,u,ts->monitorcontext[i]);
4128: }
4129: VecLockPop(u);
4130: return(0);
4131: }
4135: /*@C
4136: TSAdjointMonitor - Runs all user-provided adjoint monitor routines set using TSAdjointMonitorSet()
4138: Collective on TS
4140: Input Parameters:
4141: + ts - time stepping context obtained from TSCreate()
4142: . step - step number that has just completed
4143: . ptime - model time of the state
4144: . u - state at the current model time
4145: . numcost - number of cost functions (dimension of lambda or mu)
4146: . lambda - vectors containing the gradients of the cost functions with respect to the ODE/DAE solution variables
4147: - mu - vectors containing the gradients of the cost functions with respect to the problem parameters
4149: Notes:
4150: TSAdjointMonitor() is typically used automatically within the time stepping implementations.
4151: Users would almost never call this routine directly.
4153: Level: developer
4155: .keywords: TS, timestep
4156: @*/
4157: PetscErrorCode TSAdjointMonitor(TS ts,PetscInt step,PetscReal ptime,Vec u,PetscInt numcost,Vec *lambda, Vec *mu)
4158: {
4160: PetscInt i,n = ts->numberadjointmonitors;
4165: VecLockPush(u);
4166: for (i=0; i<n; i++) {
4167: (*ts->adjointmonitor[i])(ts,step,ptime,u,numcost,lambda,mu,ts->adjointmonitorcontext[i]);
4168: }
4169: VecLockPop(u);
4170: return(0);
4171: }
4173: /* ------------------------------------------------------------------------*/
4176: /*@C
4177: TSMonitorLGCtxCreate - Creates a TSMonitorLGCtx context for use with
4178: TS to monitor the solution process graphically in various ways
4180: Collective on TS
4182: Input Parameters:
4183: + host - the X display to open, or null for the local machine
4184: . label - the title to put in the title bar
4185: . x, y - the screen coordinates of the upper left coordinate of the window
4186: . m, n - the screen width and height in pixels
4187: - howoften - if positive then determines the frequency of the plotting, if -1 then only at the final time
4189: Output Parameter:
4190: . ctx - the context
4192: Options Database Key:
4193: + -ts_monitor_lg_timestep - automatically sets line graph monitor
4194: . -ts_monitor_lg_solution - monitor the solution (or certain values of the solution by calling TSMonitorLGSetDisplayVariables() or TSMonitorLGCtxSetDisplayVariables())
4195: . -ts_monitor_lg_error - monitor the error
4196: . -ts_monitor_lg_ksp_iterations - monitor the number of KSP iterations needed for each timestep
4197: . -ts_monitor_lg_snes_iterations - monitor the number of SNES iterations needed for each timestep
4198: - -lg_use_markers <true,false> - mark the data points (at each time step) on the plot; default is true
4200: Notes:
4201: Use TSMonitorLGCtxDestroy() to destroy.
4203: One can provide a function that transforms the solution before plotting it with TSMonitorLGCtxSetTransform() or TSMonitorLGSetTransform()
4205: Many of the functions that control the monitoring have two forms: TSMonitorLGSet/GetXXXX() and TSMonitorLGCtxSet/GetXXXX() the first take a TS object as the
4206: first argument (if that TS object does not have a TSMonitorLGCtx associated with it the function call is ignored) and the second takes a TSMonitorLGCtx object
4207: as the first argument.
4209: One can control the names displayed for each solution or error variable with TSMonitorLGCtxSetVariableNames() or TSMonitorLGSetVariableNames()
4212: Level: intermediate
4214: .keywords: TS, monitor, line graph, residual
4216: .seealso: TSMonitorLGTimeStep(), TSMonitorSet(), TSMonitorLGSolution(), TSMonitorLGError(), TSMonitorDefault(), VecView(),
4217: TSMonitorLGCtxCreate(), TSMonitorLGCtxSetVariableNames(), TSMonitorLGCtxGetVariableNames(),
4218: TSMonitorLGSetVariableNames(), TSMonitorLGGetVariableNames(), TSMonitorLGSetDisplayVariables(), TSMonitorLGCtxSetDisplayVariables(),
4219: TSMonitorLGCtxSetTransform(), TSMonitorLGSetTransform(), TSMonitorLGError(), TSMonitorLGSNESIterations(), TSMonitorLGKSPIterations(),
4220: TSMonitorEnvelopeCtxCreate(), TSMonitorEnvelopeGetBounds(), TSMonitorEnvelopeCtxDestroy(), TSMonitorEnvelop()
4222: @*/
4223: PetscErrorCode TSMonitorLGCtxCreate(MPI_Comm comm,const char host[],const char label[],int x,int y,int m,int n,PetscInt howoften,TSMonitorLGCtx *ctx)
4224: {
4225: PetscDraw draw;
4229: PetscNew(ctx);
4230: PetscDrawCreate(comm,host,label,x,y,m,n,&draw);
4231: PetscDrawSetFromOptions(draw);
4232: PetscDrawLGCreate(draw,1,&(*ctx)->lg);
4233: PetscDrawLGSetFromOptions((*ctx)->lg);
4234: PetscDrawDestroy(&draw);
4235: (*ctx)->howoften = howoften;
4236: return(0);
4237: }
4241: PetscErrorCode TSMonitorLGTimeStep(TS ts,PetscInt step,PetscReal ptime,Vec v,void *monctx)
4242: {
4243: TSMonitorLGCtx ctx = (TSMonitorLGCtx) monctx;
4244: PetscReal x = ptime,y;
4248: if (step < 0) return(0); /* -1 indicates an interpolated solution */
4249: if (!step) {
4250: PetscDrawAxis axis;
4251: PetscDrawLGGetAxis(ctx->lg,&axis);
4252: PetscDrawAxisSetLabels(axis,"Timestep as function of time","Time","Time Step");
4253: PetscDrawLGReset(ctx->lg);
4254: }
4255: TSGetTimeStep(ts,&y);
4256: PetscDrawLGAddPoint(ctx->lg,&x,&y);
4257: if (((ctx->howoften > 0) && (!(step % ctx->howoften))) || ((ctx->howoften == -1) && ts->reason)) {
4258: PetscDrawLGDraw(ctx->lg);
4259: PetscDrawLGSave(ctx->lg);
4260: }
4261: return(0);
4262: }
4266: /*@C
4267: TSMonitorLGCtxDestroy - Destroys a line graph context that was created
4268: with TSMonitorLGCtxCreate().
4270: Collective on TSMonitorLGCtx
4272: Input Parameter:
4273: . ctx - the monitor context
4275: Level: intermediate
4277: .keywords: TS, monitor, line graph, destroy
4279: .seealso: TSMonitorLGCtxCreate(), TSMonitorSet(), TSMonitorLGTimeStep();
4280: @*/
4281: PetscErrorCode TSMonitorLGCtxDestroy(TSMonitorLGCtx *ctx)
4282: {
4286: if ((*ctx)->transformdestroy) {
4287: ((*ctx)->transformdestroy)((*ctx)->transformctx);
4288: }
4289: PetscDrawLGDestroy(&(*ctx)->lg);
4290: PetscStrArrayDestroy(&(*ctx)->names);
4291: PetscStrArrayDestroy(&(*ctx)->displaynames);
4292: PetscFree((*ctx)->displayvariables);
4293: PetscFree((*ctx)->displayvalues);
4294: PetscFree(*ctx);
4295: return(0);
4296: }
4300: /*@
4301: TSGetTime - Gets the time of the most recently completed step.
4303: Not Collective
4305: Input Parameter:
4306: . ts - the TS context obtained from TSCreate()
4308: Output Parameter:
4309: . t - the current time. This time may not corresponds to the final time set with TSSetDuration(), use TSGetSolveTime().
4311: Level: beginner
4313: Note:
4314: When called during time step evaluation (e.g. during residual evaluation or via hooks set using TSSetPreStep(),
4315: TSSetPreStage(), TSSetPostStage(), or TSSetPostStep()), the time is the time at the start of the step being evaluated.
4317: .seealso: TSSetInitialTimeStep(), TSGetTimeStep(), TSGetSolveTime()
4319: .keywords: TS, get, time
4320: @*/
4321: PetscErrorCode TSGetTime(TS ts,PetscReal *t)
4322: {
4326: *t = ts->ptime;
4327: return(0);
4328: }
4332: /*@
4333: TSGetPrevTime - Gets the starting time of the previously completed step.
4335: Not Collective
4337: Input Parameter:
4338: . ts - the TS context obtained from TSCreate()
4340: Output Parameter:
4341: . t - the previous time
4343: Level: beginner
4345: .seealso: TSSetInitialTimeStep(), TSGetTimeStep()
4347: .keywords: TS, get, time
4348: @*/
4349: PetscErrorCode TSGetPrevTime(TS ts,PetscReal *t)
4350: {
4354: *t = ts->ptime_prev;
4355: return(0);
4356: }
4360: /*@
4361: TSSetTime - Allows one to reset the time.
4363: Logically Collective on TS
4365: Input Parameters:
4366: + ts - the TS context obtained from TSCreate()
4367: - time - the time
4369: Level: intermediate
4371: .seealso: TSGetTime(), TSSetDuration()
4373: .keywords: TS, set, time
4374: @*/
4375: PetscErrorCode TSSetTime(TS ts, PetscReal t)
4376: {
4380: ts->ptime = t;
4381: return(0);
4382: }
4386: /*@C
4387: TSSetOptionsPrefix - Sets the prefix used for searching for all
4388: TS options in the database.
4390: Logically Collective on TS
4392: Input Parameter:
4393: + ts - The TS context
4394: - prefix - The prefix to prepend to all option names
4396: Notes:
4397: A hyphen (-) must NOT be given at the beginning of the prefix name.
4398: The first character of all runtime options is AUTOMATICALLY the
4399: hyphen.
4401: Level: advanced
4403: .keywords: TS, set, options, prefix, database
4405: .seealso: TSSetFromOptions()
4407: @*/
4408: PetscErrorCode TSSetOptionsPrefix(TS ts,const char prefix[])
4409: {
4411: SNES snes;
4415: PetscObjectSetOptionsPrefix((PetscObject)ts,prefix);
4416: TSGetSNES(ts,&snes);
4417: SNESSetOptionsPrefix(snes,prefix);
4418: return(0);
4419: }
4424: /*@C
4425: TSAppendOptionsPrefix - Appends to the prefix used for searching for all
4426: TS options in the database.
4428: Logically Collective on TS
4430: Input Parameter:
4431: + ts - The TS context
4432: - prefix - The prefix to prepend to all option names
4434: Notes:
4435: A hyphen (-) must NOT be given at the beginning of the prefix name.
4436: The first character of all runtime options is AUTOMATICALLY the
4437: hyphen.
4439: Level: advanced
4441: .keywords: TS, append, options, prefix, database
4443: .seealso: TSGetOptionsPrefix()
4445: @*/
4446: PetscErrorCode TSAppendOptionsPrefix(TS ts,const char prefix[])
4447: {
4449: SNES snes;
4453: PetscObjectAppendOptionsPrefix((PetscObject)ts,prefix);
4454: TSGetSNES(ts,&snes);
4455: SNESAppendOptionsPrefix(snes,prefix);
4456: return(0);
4457: }
4461: /*@C
4462: TSGetOptionsPrefix - Sets the prefix used for searching for all
4463: TS options in the database.
4465: Not Collective
4467: Input Parameter:
4468: . ts - The TS context
4470: Output Parameter:
4471: . prefix - A pointer to the prefix string used
4473: Notes: On the fortran side, the user should pass in a string 'prifix' of
4474: sufficient length to hold the prefix.
4476: Level: intermediate
4478: .keywords: TS, get, options, prefix, database
4480: .seealso: TSAppendOptionsPrefix()
4481: @*/
4482: PetscErrorCode TSGetOptionsPrefix(TS ts,const char *prefix[])
4483: {
4489: PetscObjectGetOptionsPrefix((PetscObject)ts,prefix);
4490: return(0);
4491: }
4495: /*@C
4496: TSGetRHSJacobian - Returns the Jacobian J at the present timestep.
4498: Not Collective, but parallel objects are returned if TS is parallel
4500: Input Parameter:
4501: . ts - The TS context obtained from TSCreate()
4503: Output Parameters:
4504: + Amat - The (approximate) Jacobian J of G, where U_t = G(U,t) (or NULL)
4505: . Pmat - The matrix from which the preconditioner is constructed, usually the same as Amat (or NULL)
4506: . func - Function to compute the Jacobian of the RHS (or NULL)
4507: - ctx - User-defined context for Jacobian evaluation routine (or NULL)
4509: Notes: You can pass in NULL for any return argument you do not need.
4511: Level: intermediate
4513: .seealso: TSGetTimeStep(), TSGetMatrices(), TSGetTime(), TSGetTimeStepNumber()
4515: .keywords: TS, timestep, get, matrix, Jacobian
4516: @*/
4517: PetscErrorCode TSGetRHSJacobian(TS ts,Mat *Amat,Mat *Pmat,TSRHSJacobian *func,void **ctx)
4518: {
4520: SNES snes;
4521: DM dm;
4524: TSGetSNES(ts,&snes);
4525: SNESGetJacobian(snes,Amat,Pmat,NULL,NULL);
4526: TSGetDM(ts,&dm);
4527: DMTSGetRHSJacobian(dm,func,ctx);
4528: return(0);
4529: }
4533: /*@C
4534: TSGetIJacobian - Returns the implicit Jacobian at the present timestep.
4536: Not Collective, but parallel objects are returned if TS is parallel
4538: Input Parameter:
4539: . ts - The TS context obtained from TSCreate()
4541: Output Parameters:
4542: + Amat - The (approximate) Jacobian of F(t,U,U_t)
4543: . Pmat - The matrix from which the preconditioner is constructed, often the same as Amat
4544: . f - The function to compute the matrices
4545: - ctx - User-defined context for Jacobian evaluation routine
4547: Notes: You can pass in NULL for any return argument you do not need.
4549: Level: advanced
4551: .seealso: TSGetTimeStep(), TSGetRHSJacobian(), TSGetMatrices(), TSGetTime(), TSGetTimeStepNumber()
4553: .keywords: TS, timestep, get, matrix, Jacobian
4554: @*/
4555: PetscErrorCode TSGetIJacobian(TS ts,Mat *Amat,Mat *Pmat,TSIJacobian *f,void **ctx)
4556: {
4558: SNES snes;
4559: DM dm;
4562: TSGetSNES(ts,&snes);
4563: SNESSetUpMatrices(snes);
4564: SNESGetJacobian(snes,Amat,Pmat,NULL,NULL);
4565: TSGetDM(ts,&dm);
4566: DMTSGetIJacobian(dm,f,ctx);
4567: return(0);
4568: }
4573: /*@C
4574: TSMonitorDrawSolution - Monitors progress of the TS solvers by calling
4575: VecView() for the solution at each timestep
4577: Collective on TS
4579: Input Parameters:
4580: + ts - the TS context
4581: . step - current time-step
4582: . ptime - current time
4583: - dummy - either a viewer or NULL
4585: Options Database:
4586: . -ts_monitor_draw_solution_initial - show initial solution as well as current solution
4588: Notes: the initial solution and current solution are not display with a common axis scaling so generally the option -ts_monitor_draw_solution_initial
4589: will look bad
4591: Level: intermediate
4593: .keywords: TS, vector, monitor, view
4595: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView()
4596: @*/
4597: PetscErrorCode TSMonitorDrawSolution(TS ts,PetscInt step,PetscReal ptime,Vec u,void *dummy)
4598: {
4599: PetscErrorCode ierr;
4600: TSMonitorDrawCtx ictx = (TSMonitorDrawCtx)dummy;
4601: PetscDraw draw;
4604: if (!step && ictx->showinitial) {
4605: if (!ictx->initialsolution) {
4606: VecDuplicate(u,&ictx->initialsolution);
4607: }
4608: VecCopy(u,ictx->initialsolution);
4609: }
4610: if (!(((ictx->howoften > 0) && (!(step % ictx->howoften))) || ((ictx->howoften == -1) && ts->reason))) return(0);
4612: if (ictx->showinitial) {
4613: PetscReal pause;
4614: PetscViewerDrawGetPause(ictx->viewer,&pause);
4615: PetscViewerDrawSetPause(ictx->viewer,0.0);
4616: VecView(ictx->initialsolution,ictx->viewer);
4617: PetscViewerDrawSetPause(ictx->viewer,pause);
4618: PetscViewerDrawSetHold(ictx->viewer,PETSC_TRUE);
4619: }
4620: VecView(u,ictx->viewer);
4621: if (ictx->showtimestepandtime) {
4622: PetscReal xl,yl,xr,yr,h;
4623: char time[32];
4625: PetscViewerDrawGetDraw(ictx->viewer,0,&draw);
4626: PetscSNPrintf(time,32,"Timestep %d Time %g",(int)step,(double)ptime);
4627: PetscDrawGetCoordinates(draw,&xl,&yl,&xr,&yr);
4628: h = yl + .95*(yr - yl);
4629: PetscDrawStringCentered(draw,.5*(xl+xr),h,PETSC_DRAW_BLACK,time);
4630: PetscDrawFlush(draw);
4631: }
4633: if (ictx->showinitial) {
4634: PetscViewerDrawSetHold(ictx->viewer,PETSC_FALSE);
4635: }
4636: return(0);
4637: }
4641: /*@C
4642: TSAdjointMonitorDrawSensi - Monitors progress of the adjoint TS solvers by calling
4643: VecView() for the sensitivities to initial states at each timestep
4645: Collective on TS
4647: Input Parameters:
4648: + ts - the TS context
4649: . step - current time-step
4650: . ptime - current time
4651: . u - current state
4652: . numcost - number of cost functions
4653: . lambda - sensitivities to initial conditions
4654: . mu - sensitivities to parameters
4655: - dummy - either a viewer or NULL
4657: Level: intermediate
4659: .keywords: TS, vector, adjoint, monitor, view
4661: .seealso: TSAdjointMonitorSet(), TSAdjointMonitorDefault(), VecView()
4662: @*/
4663: PetscErrorCode TSAdjointMonitorDrawSensi(TS ts,PetscInt step,PetscReal ptime,Vec u,PetscInt numcost,Vec *lambda,Vec *mu,void *dummy)
4664: {
4665: PetscErrorCode ierr;
4666: TSMonitorDrawCtx ictx = (TSMonitorDrawCtx)dummy;
4667: PetscDraw draw;
4668: PetscReal xl,yl,xr,yr,h;
4669: char time[32];
4672: if (!(((ictx->howoften > 0) && (!(step % ictx->howoften))) || ((ictx->howoften == -1) && ts->reason))) return(0);
4674: VecView(lambda[0],ictx->viewer);
4675: PetscViewerDrawGetDraw(ictx->viewer,0,&draw);
4676: PetscSNPrintf(time,32,"Timestep %d Time %g",(int)step,(double)ptime);
4677: PetscDrawGetCoordinates(draw,&xl,&yl,&xr,&yr);
4678: h = yl + .95*(yr - yl);
4679: PetscDrawStringCentered(draw,.5*(xl+xr),h,PETSC_DRAW_BLACK,time);
4680: PetscDrawFlush(draw);
4681: return(0);
4682: }
4686: /*@C
4687: TSMonitorDrawSolutionPhase - Monitors progress of the TS solvers by plotting the solution as a phase diagram
4689: Collective on TS
4691: Input Parameters:
4692: + ts - the TS context
4693: . step - current time-step
4694: . ptime - current time
4695: - dummy - either a viewer or NULL
4697: Level: intermediate
4699: .keywords: TS, vector, monitor, view
4701: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView()
4702: @*/
4703: PetscErrorCode TSMonitorDrawSolutionPhase(TS ts,PetscInt step,PetscReal ptime,Vec u,void *dummy)
4704: {
4705: PetscErrorCode ierr;
4706: TSMonitorDrawCtx ictx = (TSMonitorDrawCtx)dummy;
4707: PetscDraw draw;
4708: PetscDrawAxis axis;
4709: PetscInt n;
4710: PetscMPIInt size;
4711: PetscReal U0,U1,xl,yl,xr,yr,h;
4712: char time[32];
4713: const PetscScalar *U;
4716: MPI_Comm_size(PetscObjectComm((PetscObject)ts),&size);
4717: if (size != 1) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"Only allowed for sequential runs");
4718: VecGetSize(u,&n);
4719: if (n != 2) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"Only for ODEs with two unknowns");
4721: PetscViewerDrawGetDraw(ictx->viewer,0,&draw);
4722: PetscViewerDrawGetDrawAxis(ictx->viewer,0,&axis);
4723: PetscDrawAxisGetLimits(axis,&xl,&xr,&yl,&yr);
4724: if (!step) {
4725: PetscDrawClear(draw);
4726: PetscDrawAxisDraw(axis);
4727: }
4729: VecGetArrayRead(u,&U);
4730: U0 = PetscRealPart(U[0]);
4731: U1 = PetscRealPart(U[1]);
4732: VecRestoreArrayRead(u,&U);
4733: if ((U0 < xl) || (U1 < yl) || (U0 > xr) || (U1 > yr)) return(0);
4735: PetscDrawCollectiveBegin(draw);
4736: PetscDrawPoint(draw,U0,U1,PETSC_DRAW_BLACK);
4737: if (ictx->showtimestepandtime) {
4738: PetscDrawGetCoordinates(draw,&xl,&yl,&xr,&yr);
4739: PetscSNPrintf(time,32,"Timestep %d Time %g",(int)step,(double)ptime);
4740: h = yl + .95*(yr - yl);
4741: PetscDrawStringCentered(draw,.5*(xl+xr),h,PETSC_DRAW_BLACK,time);
4742: }
4743: PetscDrawCollectiveEnd(draw);
4744: PetscDrawFlush(draw);
4745: PetscDrawSave(draw);
4746: return(0);
4747: }
4752: /*@C
4753: TSMonitorDrawCtxDestroy - Destroys the monitor context for TSMonitorDrawSolution()
4755: Collective on TS
4757: Input Parameters:
4758: . ctx - the monitor context
4760: Level: intermediate
4762: .keywords: TS, vector, monitor, view
4764: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorDrawSolution(), TSMonitorDrawError()
4765: @*/
4766: PetscErrorCode TSMonitorDrawCtxDestroy(TSMonitorDrawCtx *ictx)
4767: {
4771: PetscViewerDestroy(&(*ictx)->viewer);
4772: VecDestroy(&(*ictx)->initialsolution);
4773: PetscFree(*ictx);
4774: return(0);
4775: }
4779: /*@C
4780: TSMonitorDrawCtxCreate - Creates the monitor context for TSMonitorDrawCtx
4782: Collective on TS
4784: Input Parameter:
4785: . ts - time-step context
4787: Output Patameter:
4788: . ctx - the monitor context
4790: Options Database:
4791: . -ts_monitor_draw_solution_initial - show initial solution as well as current solution
4793: Level: intermediate
4795: .keywords: TS, vector, monitor, view
4797: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorDrawCtx()
4798: @*/
4799: PetscErrorCode TSMonitorDrawCtxCreate(MPI_Comm comm,const char host[],const char label[],int x,int y,int m,int n,PetscInt howoften,TSMonitorDrawCtx *ctx)
4800: {
4801: PetscErrorCode ierr;
4804: PetscNew(ctx);
4805: PetscViewerDrawOpen(comm,host,label,x,y,m,n,&(*ctx)->viewer);
4806: PetscViewerSetFromOptions((*ctx)->viewer);
4808: (*ctx)->howoften = howoften;
4809: (*ctx)->showinitial = PETSC_FALSE;
4810: PetscOptionsGetBool(NULL,NULL,"-ts_monitor_draw_solution_initial",&(*ctx)->showinitial,NULL);
4812: (*ctx)->showtimestepandtime = PETSC_FALSE;
4813: PetscOptionsGetBool(NULL,NULL,"-ts_monitor_draw_solution_show_time",&(*ctx)->showtimestepandtime,NULL);
4814: return(0);
4815: }
4819: /*@C
4820: TSMonitorDrawError - Monitors progress of the TS solvers by calling
4821: VecView() for the error at each timestep
4823: Collective on TS
4825: Input Parameters:
4826: + ts - the TS context
4827: . step - current time-step
4828: . ptime - current time
4829: - dummy - either a viewer or NULL
4831: Level: intermediate
4833: .keywords: TS, vector, monitor, view
4835: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView()
4836: @*/
4837: PetscErrorCode TSMonitorDrawError(TS ts,PetscInt step,PetscReal ptime,Vec u,void *dummy)
4838: {
4839: PetscErrorCode ierr;
4840: TSMonitorDrawCtx ctx = (TSMonitorDrawCtx)dummy;
4841: PetscViewer viewer = ctx->viewer;
4842: Vec work;
4845: if (!(((ctx->howoften > 0) && (!(step % ctx->howoften))) || ((ctx->howoften == -1) && ts->reason))) return(0);
4846: VecDuplicate(u,&work);
4847: TSComputeSolutionFunction(ts,ptime,work);
4848: VecAXPY(work,-1.0,u);
4849: VecView(work,viewer);
4850: VecDestroy(&work);
4851: return(0);
4852: }
4854: #include <petsc/private/dmimpl.h>
4857: /*@
4858: TSSetDM - Sets the DM that may be used by some preconditioners
4860: Logically Collective on TS and DM
4862: Input Parameters:
4863: + ts - the preconditioner context
4864: - dm - the dm
4866: Level: intermediate
4869: .seealso: TSGetDM(), SNESSetDM(), SNESGetDM()
4870: @*/
4871: PetscErrorCode TSSetDM(TS ts,DM dm)
4872: {
4874: SNES snes;
4875: DMTS tsdm;
4879: PetscObjectReference((PetscObject)dm);
4880: if (ts->dm) { /* Move the DMTS context over to the new DM unless the new DM already has one */
4881: if (ts->dm->dmts && !dm->dmts) {
4882: DMCopyDMTS(ts->dm,dm);
4883: DMGetDMTS(ts->dm,&tsdm);
4884: if (tsdm->originaldm == ts->dm) { /* Grant write privileges to the replacement DM */
4885: tsdm->originaldm = dm;
4886: }
4887: }
4888: DMDestroy(&ts->dm);
4889: }
4890: ts->dm = dm;
4892: TSGetSNES(ts,&snes);
4893: SNESSetDM(snes,dm);
4894: return(0);
4895: }
4899: /*@
4900: TSGetDM - Gets the DM that may be used by some preconditioners
4902: Not Collective
4904: Input Parameter:
4905: . ts - the preconditioner context
4907: Output Parameter:
4908: . dm - the dm
4910: Level: intermediate
4913: .seealso: TSSetDM(), SNESSetDM(), SNESGetDM()
4914: @*/
4915: PetscErrorCode TSGetDM(TS ts,DM *dm)
4916: {
4921: if (!ts->dm) {
4922: DMShellCreate(PetscObjectComm((PetscObject)ts),&ts->dm);
4923: if (ts->snes) {SNESSetDM(ts->snes,ts->dm);}
4924: }
4925: *dm = ts->dm;
4926: return(0);
4927: }
4931: /*@
4932: SNESTSFormFunction - Function to evaluate nonlinear residual
4934: Logically Collective on SNES
4936: Input Parameter:
4937: + snes - nonlinear solver
4938: . U - the current state at which to evaluate the residual
4939: - ctx - user context, must be a TS
4941: Output Parameter:
4942: . F - the nonlinear residual
4944: Notes:
4945: This function is not normally called by users and is automatically registered with the SNES used by TS.
4946: It is most frequently passed to MatFDColoringSetFunction().
4948: Level: advanced
4950: .seealso: SNESSetFunction(), MatFDColoringSetFunction()
4951: @*/
4952: PetscErrorCode SNESTSFormFunction(SNES snes,Vec U,Vec F,void *ctx)
4953: {
4954: TS ts = (TS)ctx;
4962: (ts->ops->snesfunction)(snes,U,F,ts);
4963: return(0);
4964: }
4968: /*@
4969: SNESTSFormJacobian - Function to evaluate the Jacobian
4971: Collective on SNES
4973: Input Parameter:
4974: + snes - nonlinear solver
4975: . U - the current state at which to evaluate the residual
4976: - ctx - user context, must be a TS
4978: Output Parameter:
4979: + A - the Jacobian
4980: . B - the preconditioning matrix (may be the same as A)
4981: - flag - indicates any structure change in the matrix
4983: Notes:
4984: This function is not normally called by users and is automatically registered with the SNES used by TS.
4986: Level: developer
4988: .seealso: SNESSetJacobian()
4989: @*/
4990: PetscErrorCode SNESTSFormJacobian(SNES snes,Vec U,Mat A,Mat B,void *ctx)
4991: {
4992: TS ts = (TS)ctx;
5003: (ts->ops->snesjacobian)(snes,U,A,B,ts);
5004: return(0);
5005: }
5009: /*@C
5010: TSComputeRHSFunctionLinear - Evaluate the right hand side via the user-provided Jacobian, for linear problems Udot = A U only
5012: Collective on TS
5014: Input Arguments:
5015: + ts - time stepping context
5016: . t - time at which to evaluate
5017: . U - state at which to evaluate
5018: - ctx - context
5020: Output Arguments:
5021: . F - right hand side
5023: Level: intermediate
5025: Notes:
5026: This function is intended to be passed to TSSetRHSFunction() to evaluate the right hand side for linear problems.
5027: The matrix (and optionally the evaluation context) should be passed to TSSetRHSJacobian().
5029: .seealso: TSSetRHSFunction(), TSSetRHSJacobian(), TSComputeRHSJacobianConstant()
5030: @*/
5031: PetscErrorCode TSComputeRHSFunctionLinear(TS ts,PetscReal t,Vec U,Vec F,void *ctx)
5032: {
5034: Mat Arhs,Brhs;
5037: TSGetRHSMats_Private(ts,&Arhs,&Brhs);
5038: TSComputeRHSJacobian(ts,t,U,Arhs,Brhs);
5039: MatMult(Arhs,U,F);
5040: return(0);
5041: }
5045: /*@C
5046: TSComputeRHSJacobianConstant - Reuses a Jacobian that is time-independent.
5048: Collective on TS
5050: Input Arguments:
5051: + ts - time stepping context
5052: . t - time at which to evaluate
5053: . U - state at which to evaluate
5054: - ctx - context
5056: Output Arguments:
5057: + A - pointer to operator
5058: . B - pointer to preconditioning matrix
5059: - flg - matrix structure flag
5061: Level: intermediate
5063: Notes:
5064: This function is intended to be passed to TSSetRHSJacobian() to evaluate the Jacobian for linear time-independent problems.
5066: .seealso: TSSetRHSFunction(), TSSetRHSJacobian(), TSComputeRHSFunctionLinear()
5067: @*/
5068: PetscErrorCode TSComputeRHSJacobianConstant(TS ts,PetscReal t,Vec U,Mat A,Mat B,void *ctx)
5069: {
5071: return(0);
5072: }
5076: /*@C
5077: TSComputeIFunctionLinear - Evaluate the left hand side via the user-provided Jacobian, for linear problems only
5079: Collective on TS
5081: Input Arguments:
5082: + ts - time stepping context
5083: . t - time at which to evaluate
5084: . U - state at which to evaluate
5085: . Udot - time derivative of state vector
5086: - ctx - context
5088: Output Arguments:
5089: . F - left hand side
5091: Level: intermediate
5093: Notes:
5094: 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
5095: user is required to write their own TSComputeIFunction.
5096: This function is intended to be passed to TSSetIFunction() to evaluate the left hand side for linear problems.
5097: The matrix (and optionally the evaluation context) should be passed to TSSetIJacobian().
5099: Note that using this function is NOT equivalent to using TSComputeRHSFunctionLinear() since that solves Udot = A U
5101: .seealso: TSSetIFunction(), TSSetIJacobian(), TSComputeIJacobianConstant(), TSComputeRHSFunctionLinear()
5102: @*/
5103: PetscErrorCode TSComputeIFunctionLinear(TS ts,PetscReal t,Vec U,Vec Udot,Vec F,void *ctx)
5104: {
5106: Mat A,B;
5109: TSGetIJacobian(ts,&A,&B,NULL,NULL);
5110: TSComputeIJacobian(ts,t,U,Udot,1.0,A,B,PETSC_TRUE);
5111: MatMult(A,Udot,F);
5112: return(0);
5113: }
5117: /*@C
5118: TSComputeIJacobianConstant - Reuses a time-independent for a semi-implicit DAE or ODE
5120: Collective on TS
5122: Input Arguments:
5123: + ts - time stepping context
5124: . t - time at which to evaluate
5125: . U - state at which to evaluate
5126: . Udot - time derivative of state vector
5127: . shift - shift to apply
5128: - ctx - context
5130: Output Arguments:
5131: + A - pointer to operator
5132: . B - pointer to preconditioning matrix
5133: - flg - matrix structure flag
5135: Level: advanced
5137: Notes:
5138: This function is intended to be passed to TSSetIJacobian() to evaluate the Jacobian for linear time-independent problems.
5140: It is only appropriate for problems of the form
5142: $ M Udot = F(U,t)
5144: where M is constant and F is non-stiff. The user must pass M to TSSetIJacobian(). The current implementation only
5145: works with IMEX time integration methods such as TSROSW and TSARKIMEX, since there is no support for de-constructing
5146: an implicit operator of the form
5148: $ shift*M + J
5150: 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
5151: a copy of M or reassemble it when requested.
5153: .seealso: TSSetIFunction(), TSSetIJacobian(), TSComputeIFunctionLinear()
5154: @*/
5155: PetscErrorCode TSComputeIJacobianConstant(TS ts,PetscReal t,Vec U,Vec Udot,PetscReal shift,Mat A,Mat B,void *ctx)
5156: {
5160: MatScale(A, shift / ts->ijacobian.shift);
5161: ts->ijacobian.shift = shift;
5162: return(0);
5163: }
5167: /*@
5168: TSGetEquationType - Gets the type of the equation that TS is solving.
5170: Not Collective
5172: Input Parameter:
5173: . ts - the TS context
5175: Output Parameter:
5176: . equation_type - see TSEquationType
5178: Level: beginner
5180: .keywords: TS, equation type
5182: .seealso: TSSetEquationType(), TSEquationType
5183: @*/
5184: PetscErrorCode TSGetEquationType(TS ts,TSEquationType *equation_type)
5185: {
5189: *equation_type = ts->equation_type;
5190: return(0);
5191: }
5195: /*@
5196: TSSetEquationType - Sets the type of the equation that TS is solving.
5198: Not Collective
5200: Input Parameter:
5201: + ts - the TS context
5202: - equation_type - see TSEquationType
5204: Level: advanced
5206: .keywords: TS, equation type
5208: .seealso: TSGetEquationType(), TSEquationType
5209: @*/
5210: PetscErrorCode TSSetEquationType(TS ts,TSEquationType equation_type)
5211: {
5214: ts->equation_type = equation_type;
5215: return(0);
5216: }
5220: /*@
5221: TSGetConvergedReason - Gets the reason the TS iteration was stopped.
5223: Not Collective
5225: Input Parameter:
5226: . ts - the TS context
5228: Output Parameter:
5229: . reason - negative value indicates diverged, positive value converged, see TSConvergedReason or the
5230: manual pages for the individual convergence tests for complete lists
5232: Level: beginner
5234: Notes:
5235: Can only be called after the call to TSSolve() is complete.
5237: .keywords: TS, nonlinear, set, convergence, test
5239: .seealso: TSSetConvergenceTest(), TSConvergedReason
5240: @*/
5241: PetscErrorCode TSGetConvergedReason(TS ts,TSConvergedReason *reason)
5242: {
5246: *reason = ts->reason;
5247: return(0);
5248: }
5252: /*@
5253: TSSetConvergedReason - Sets the reason for handling the convergence of TSSolve.
5255: Not Collective
5257: Input Parameter:
5258: + ts - the TS context
5259: . reason - negative value indicates diverged, positive value converged, see TSConvergedReason or the
5260: manual pages for the individual convergence tests for complete lists
5262: Level: advanced
5264: Notes:
5265: Can only be called during TSSolve() is active.
5267: .keywords: TS, nonlinear, set, convergence, test
5269: .seealso: TSConvergedReason
5270: @*/
5271: PetscErrorCode TSSetConvergedReason(TS ts,TSConvergedReason reason)
5272: {
5275: ts->reason = reason;
5276: return(0);
5277: }
5281: /*@
5282: TSGetSolveTime - Gets the time after a call to TSSolve()
5284: Not Collective
5286: Input Parameter:
5287: . ts - the TS context
5289: Output Parameter:
5290: . ftime - the final time. This time corresponds to the final time set with TSSetDuration()
5292: Level: beginner
5294: Notes:
5295: Can only be called after the call to TSSolve() is complete.
5297: .keywords: TS, nonlinear, set, convergence, test
5299: .seealso: TSSetConvergenceTest(), TSConvergedReason
5300: @*/
5301: PetscErrorCode TSGetSolveTime(TS ts,PetscReal *ftime)
5302: {
5306: *ftime = ts->solvetime;
5307: return(0);
5308: }
5312: /*@
5313: TSGetTotalSteps - Gets the total number of steps done since the last call to TSSetUp() or TSCreate()
5315: Not Collective
5317: Input Parameter:
5318: . ts - the TS context
5320: Output Parameter:
5321: . steps - the number of steps
5323: Level: beginner
5325: Notes:
5326: Includes the number of steps for all calls to TSSolve() since TSSetUp() was called
5328: .keywords: TS, nonlinear, set, convergence, test
5330: .seealso: TSSetConvergenceTest(), TSConvergedReason
5331: @*/
5332: PetscErrorCode TSGetTotalSteps(TS ts,PetscInt *steps)
5333: {
5337: *steps = ts->total_steps;
5338: return(0);
5339: }
5343: /*@
5344: TSGetSNESIterations - Gets the total number of nonlinear iterations
5345: used by the time integrator.
5347: Not Collective
5349: Input Parameter:
5350: . ts - TS context
5352: Output Parameter:
5353: . nits - number of nonlinear iterations
5355: Notes:
5356: This counter is reset to zero for each successive call to TSSolve().
5358: Level: intermediate
5360: .keywords: TS, get, number, nonlinear, iterations
5362: .seealso: TSGetKSPIterations()
5363: @*/
5364: PetscErrorCode TSGetSNESIterations(TS ts,PetscInt *nits)
5365: {
5369: *nits = ts->snes_its;
5370: return(0);
5371: }
5375: /*@
5376: TSGetKSPIterations - Gets the total number of linear iterations
5377: used by the time integrator.
5379: Not Collective
5381: Input Parameter:
5382: . ts - TS context
5384: Output Parameter:
5385: . lits - number of linear iterations
5387: Notes:
5388: This counter is reset to zero for each successive call to TSSolve().
5390: Level: intermediate
5392: .keywords: TS, get, number, linear, iterations
5394: .seealso: TSGetSNESIterations(), SNESGetKSPIterations()
5395: @*/
5396: PetscErrorCode TSGetKSPIterations(TS ts,PetscInt *lits)
5397: {
5401: *lits = ts->ksp_its;
5402: return(0);
5403: }
5407: /*@
5408: TSGetStepRejections - Gets the total number of rejected steps.
5410: Not Collective
5412: Input Parameter:
5413: . ts - TS context
5415: Output Parameter:
5416: . rejects - number of steps rejected
5418: Notes:
5419: This counter is reset to zero for each successive call to TSSolve().
5421: Level: intermediate
5423: .keywords: TS, get, number
5425: .seealso: TSGetSNESIterations(), TSGetKSPIterations(), TSSetMaxStepRejections(), TSGetSNESFailures(), TSSetMaxSNESFailures(), TSSetErrorIfStepFails()
5426: @*/
5427: PetscErrorCode TSGetStepRejections(TS ts,PetscInt *rejects)
5428: {
5432: *rejects = ts->reject;
5433: return(0);
5434: }
5438: /*@
5439: TSGetSNESFailures - Gets the total number of failed SNES solves
5441: Not Collective
5443: Input Parameter:
5444: . ts - TS context
5446: Output Parameter:
5447: . fails - number of failed nonlinear solves
5449: Notes:
5450: This counter is reset to zero for each successive call to TSSolve().
5452: Level: intermediate
5454: .keywords: TS, get, number
5456: .seealso: TSGetSNESIterations(), TSGetKSPIterations(), TSSetMaxStepRejections(), TSGetStepRejections(), TSSetMaxSNESFailures()
5457: @*/
5458: PetscErrorCode TSGetSNESFailures(TS ts,PetscInt *fails)
5459: {
5463: *fails = ts->num_snes_failures;
5464: return(0);
5465: }
5469: /*@
5470: TSSetMaxStepRejections - Sets the maximum number of step rejections before a step fails
5472: Not Collective
5474: Input Parameter:
5475: + ts - TS context
5476: - rejects - maximum number of rejected steps, pass -1 for unlimited
5478: Notes:
5479: The counter is reset to zero for each step
5481: Options Database Key:
5482: . -ts_max_reject - Maximum number of step rejections before a step fails
5484: Level: intermediate
5486: .keywords: TS, set, maximum, number
5488: .seealso: TSGetSNESIterations(), TSGetKSPIterations(), TSSetMaxSNESFailures(), TSGetStepRejections(), TSGetSNESFailures(), TSSetErrorIfStepFails(), TSGetConvergedReason()
5489: @*/
5490: PetscErrorCode TSSetMaxStepRejections(TS ts,PetscInt rejects)
5491: {
5494: ts->max_reject = rejects;
5495: return(0);
5496: }
5500: /*@
5501: TSSetMaxSNESFailures - Sets the maximum number of failed SNES solves
5503: Not Collective
5505: Input Parameter:
5506: + ts - TS context
5507: - fails - maximum number of failed nonlinear solves, pass -1 for unlimited
5509: Notes:
5510: The counter is reset to zero for each successive call to TSSolve().
5512: Options Database Key:
5513: . -ts_max_snes_failures - Maximum number of nonlinear solve failures
5515: Level: intermediate
5517: .keywords: TS, set, maximum, number
5519: .seealso: TSGetSNESIterations(), TSGetKSPIterations(), TSSetMaxStepRejections(), TSGetStepRejections(), TSGetSNESFailures(), SNESGetConvergedReason(), TSGetConvergedReason()
5520: @*/
5521: PetscErrorCode TSSetMaxSNESFailures(TS ts,PetscInt fails)
5522: {
5525: ts->max_snes_failures = fails;
5526: return(0);
5527: }
5531: /*@
5532: TSSetErrorIfStepFails - Error if no step succeeds
5534: Not Collective
5536: Input Parameter:
5537: + ts - TS context
5538: - err - PETSC_TRUE to error if no step succeeds, PETSC_FALSE to return without failure
5540: Options Database Key:
5541: . -ts_error_if_step_fails - Error if no step succeeds
5543: Level: intermediate
5545: .keywords: TS, set, error
5547: .seealso: TSGetSNESIterations(), TSGetKSPIterations(), TSSetMaxStepRejections(), TSGetStepRejections(), TSGetSNESFailures(), TSSetErrorIfStepFails(), TSGetConvergedReason()
5548: @*/
5549: PetscErrorCode TSSetErrorIfStepFails(TS ts,PetscBool err)
5550: {
5553: ts->errorifstepfailed = err;
5554: return(0);
5555: }
5559: /*@C
5560: TSMonitorSolution - Monitors progress of the TS solvers by VecView() for the solution at each timestep. Normally the viewer is a binary file or a PetscDraw object
5562: Collective on TS
5564: Input Parameters:
5565: + ts - the TS context
5566: . step - current time-step
5567: . ptime - current time
5568: . u - current state
5569: - vf - viewer and its format
5571: Level: intermediate
5573: .keywords: TS, vector, monitor, view
5575: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView()
5576: @*/
5577: PetscErrorCode TSMonitorSolution(TS ts,PetscInt step,PetscReal ptime,Vec u,PetscViewerAndFormat *vf)
5578: {
5582: PetscViewerPushFormat(vf->viewer,vf->format);
5583: VecView(u,vf->viewer);
5584: PetscViewerPopFormat(vf->viewer);
5585: return(0);
5586: }
5590: /*@C
5591: TSMonitorSolutionVTK - Monitors progress of the TS solvers by VecView() for the solution at each timestep.
5593: Collective on TS
5595: Input Parameters:
5596: + ts - the TS context
5597: . step - current time-step
5598: . ptime - current time
5599: . u - current state
5600: - filenametemplate - string containing a format specifier for the integer time step (e.g. %03D)
5602: Level: intermediate
5604: Notes:
5605: The VTK format does not allow writing multiple time steps in the same file, therefore a different file will be written for each time step.
5606: These are named according to the file name template.
5608: This function is normally passed as an argument to TSMonitorSet() along with TSMonitorSolutionVTKDestroy().
5610: .keywords: TS, vector, monitor, view
5612: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView()
5613: @*/
5614: PetscErrorCode TSMonitorSolutionVTK(TS ts,PetscInt step,PetscReal ptime,Vec u,void *filenametemplate)
5615: {
5617: char filename[PETSC_MAX_PATH_LEN];
5618: PetscViewer viewer;
5621: if (step < 0) return(0); /* -1 indicates interpolated solution */
5622: PetscSNPrintf(filename,sizeof(filename),(const char*)filenametemplate,step);
5623: PetscViewerVTKOpen(PetscObjectComm((PetscObject)ts),filename,FILE_MODE_WRITE,&viewer);
5624: VecView(u,viewer);
5625: PetscViewerDestroy(&viewer);
5626: return(0);
5627: }
5631: /*@C
5632: TSMonitorSolutionVTKDestroy - Destroy context for monitoring
5634: Collective on TS
5636: Input Parameters:
5637: . filenametemplate - string containing a format specifier for the integer time step (e.g. %03D)
5639: Level: intermediate
5641: Note:
5642: This function is normally passed to TSMonitorSet() along with TSMonitorSolutionVTK().
5644: .keywords: TS, vector, monitor, view
5646: .seealso: TSMonitorSet(), TSMonitorSolutionVTK()
5647: @*/
5648: PetscErrorCode TSMonitorSolutionVTKDestroy(void *filenametemplate)
5649: {
5653: PetscFree(*(char**)filenametemplate);
5654: return(0);
5655: }
5659: /*@
5660: TSGetAdapt - Get the adaptive controller context for the current method
5662: Collective on TS if controller has not been created yet
5664: Input Arguments:
5665: . ts - time stepping context
5667: Output Arguments:
5668: . adapt - adaptive controller
5670: Level: intermediate
5672: .seealso: TSAdapt, TSAdaptSetType(), TSAdaptChoose()
5673: @*/
5674: PetscErrorCode TSGetAdapt(TS ts,TSAdapt *adapt)
5675: {
5681: if (!ts->adapt) {
5682: TSAdaptCreate(PetscObjectComm((PetscObject)ts),&ts->adapt);
5683: PetscLogObjectParent((PetscObject)ts,(PetscObject)ts->adapt);
5684: PetscObjectIncrementTabLevel((PetscObject)ts->adapt,(PetscObject)ts,1);
5685: }
5686: *adapt = ts->adapt;
5687: return(0);
5688: }
5692: /*@
5693: TSSetTolerances - Set tolerances for local truncation error when using adaptive controller
5695: Logically Collective
5697: Input Arguments:
5698: + ts - time integration context
5699: . atol - scalar absolute tolerances, PETSC_DECIDE to leave current value
5700: . vatol - vector of absolute tolerances or NULL, used in preference to atol if present
5701: . rtol - scalar relative tolerances, PETSC_DECIDE to leave current value
5702: - vrtol - vector of relative tolerances or NULL, used in preference to atol if present
5704: Options Database keys:
5705: + -ts_rtol <rtol> - relative tolerance for local truncation error
5706: - -ts_atol <atol> Absolute tolerance for local truncation error
5708: Notes:
5709: With PETSc's implicit schemes for DAE problems, the calculation of the local truncation error
5710: (LTE) includes both the differential and the algebraic variables. If one wants the LTE to be
5711: computed only for the differential or the algebraic part then this can be done using the vector of
5712: tolerances vatol. For example, by setting the tolerance vector with the desired tolerance for the
5713: differential part and infinity for the algebraic part, the LTE calculation will include only the
5714: differential variables.
5716: Level: beginner
5718: .seealso: TS, TSAdapt, TSVecNormWRMS(), TSGetTolerances()
5719: @*/
5720: PetscErrorCode TSSetTolerances(TS ts,PetscReal atol,Vec vatol,PetscReal rtol,Vec vrtol)
5721: {
5725: if (atol != PETSC_DECIDE && atol != PETSC_DEFAULT) ts->atol = atol;
5726: if (vatol) {
5727: PetscObjectReference((PetscObject)vatol);
5728: VecDestroy(&ts->vatol);
5729: ts->vatol = vatol;
5730: }
5731: if (rtol != PETSC_DECIDE && rtol != PETSC_DEFAULT) ts->rtol = rtol;
5732: if (vrtol) {
5733: PetscObjectReference((PetscObject)vrtol);
5734: VecDestroy(&ts->vrtol);
5735: ts->vrtol = vrtol;
5736: }
5737: return(0);
5738: }
5742: /*@
5743: TSGetTolerances - Get tolerances for local truncation error when using adaptive controller
5745: Logically Collective
5747: Input Arguments:
5748: . ts - time integration context
5750: Output Arguments:
5751: + atol - scalar absolute tolerances, NULL to ignore
5752: . vatol - vector of absolute tolerances, NULL to ignore
5753: . rtol - scalar relative tolerances, NULL to ignore
5754: - vrtol - vector of relative tolerances, NULL to ignore
5756: Level: beginner
5758: .seealso: TS, TSAdapt, TSVecNormWRMS(), TSSetTolerances()
5759: @*/
5760: PetscErrorCode TSGetTolerances(TS ts,PetscReal *atol,Vec *vatol,PetscReal *rtol,Vec *vrtol)
5761: {
5763: if (atol) *atol = ts->atol;
5764: if (vatol) *vatol = ts->vatol;
5765: if (rtol) *rtol = ts->rtol;
5766: if (vrtol) *vrtol = ts->vrtol;
5767: return(0);
5768: }
5772: /*@
5773: TSErrorWeightedNorm2 - compute a weighted 2-norm of the difference between two state vectors
5775: Collective on TS
5777: Input Arguments:
5778: + ts - time stepping context
5779: . U - state vector, usually ts->vec_sol
5780: - Y - state vector to be compared to U
5782: Output Arguments:
5783: . norm - weighted norm, a value of 1.0 is considered small
5785: Level: developer
5787: .seealso: TSErrorWeightedNorm(), TSErrorWeightedNormInfinity()
5788: @*/
5789: PetscErrorCode TSErrorWeightedNorm2(TS ts,Vec U,Vec Y,PetscReal *norm)
5790: {
5791: PetscErrorCode ierr;
5792: PetscInt i,n,N,rstart;
5793: const PetscScalar *u,*y;
5794: PetscReal sum,gsum;
5795: PetscReal tol;
5805: if (U == Y) SETERRQ(PetscObjectComm((PetscObject)U),PETSC_ERR_ARG_IDN,"U and Y cannot be the same vector");
5807: VecGetSize(U,&N);
5808: VecGetLocalSize(U,&n);
5809: VecGetOwnershipRange(U,&rstart,NULL);
5810: VecGetArrayRead(U,&u);
5811: VecGetArrayRead(Y,&y);
5812: sum = 0.;
5813: if (ts->vatol && ts->vrtol) {
5814: const PetscScalar *atol,*rtol;
5815: VecGetArrayRead(ts->vatol,&atol);
5816: VecGetArrayRead(ts->vrtol,&rtol);
5817: for (i=0; i<n; i++) {
5818: tol = PetscRealPart(atol[i]) + PetscRealPart(rtol[i]) * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
5819: sum += PetscSqr(PetscAbsScalar(y[i] - u[i]) / tol);
5820: }
5821: VecRestoreArrayRead(ts->vatol,&atol);
5822: VecRestoreArrayRead(ts->vrtol,&rtol);
5823: } else if (ts->vatol) { /* vector atol, scalar rtol */
5824: const PetscScalar *atol;
5825: VecGetArrayRead(ts->vatol,&atol);
5826: for (i=0; i<n; i++) {
5827: tol = PetscRealPart(atol[i]) + ts->rtol * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
5828: sum += PetscSqr(PetscAbsScalar(y[i] - u[i]) / tol);
5829: }
5830: VecRestoreArrayRead(ts->vatol,&atol);
5831: } else if (ts->vrtol) { /* scalar atol, vector rtol */
5832: const PetscScalar *rtol;
5833: VecGetArrayRead(ts->vrtol,&rtol);
5834: for (i=0; i<n; i++) {
5835: tol = ts->atol + PetscRealPart(rtol[i]) * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
5836: sum += PetscSqr(PetscAbsScalar(y[i] - u[i]) / tol);
5837: }
5838: VecRestoreArrayRead(ts->vrtol,&rtol);
5839: } else { /* scalar atol, scalar rtol */
5840: for (i=0; i<n; i++) {
5841: tol = ts->atol + ts->rtol * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
5842: sum += PetscSqr(PetscAbsScalar(y[i] - u[i]) / tol);
5843: }
5844: }
5845: VecRestoreArrayRead(U,&u);
5846: VecRestoreArrayRead(Y,&y);
5848: MPIU_Allreduce(&sum,&gsum,1,MPIU_REAL,MPIU_SUM,PetscObjectComm((PetscObject)ts));
5849: *norm = PetscSqrtReal(gsum / N);
5851: if (PetscIsInfOrNanScalar(*norm)) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_FP,"Infinite or not-a-number generated in norm");
5852: return(0);
5853: }
5857: /*@
5858: TSErrorWeightedNormInfinity - compute a weighted infinity-norm of the difference between two state vectors
5860: Collective on TS
5862: Input Arguments:
5863: + ts - time stepping context
5864: . U - state vector, usually ts->vec_sol
5865: - Y - state vector to be compared to U
5867: Output Arguments:
5868: . norm - weighted norm, a value of 1.0 is considered small
5870: Level: developer
5872: .seealso: TSErrorWeightedNorm(), TSErrorWeightedNorm2()
5873: @*/
5874: PetscErrorCode TSErrorWeightedNormInfinity(TS ts,Vec U,Vec Y,PetscReal *norm)
5875: {
5876: PetscErrorCode ierr;
5877: PetscInt i,n,N,rstart,k;
5878: const PetscScalar *u,*y;
5879: PetscReal max,gmax;
5880: PetscReal tol;
5890: if (U == Y) SETERRQ(PetscObjectComm((PetscObject)U),PETSC_ERR_ARG_IDN,"U and Y cannot be the same vector");
5892: VecGetSize(U,&N);
5893: VecGetLocalSize(U,&n);
5894: VecGetOwnershipRange(U,&rstart,NULL);
5895: VecGetArrayRead(U,&u);
5896: VecGetArrayRead(Y,&y);
5897: if (ts->vatol && ts->vrtol) {
5898: const PetscScalar *atol,*rtol;
5899: VecGetArrayRead(ts->vatol,&atol);
5900: VecGetArrayRead(ts->vrtol,&rtol);
5901: k = 0;
5902: tol = PetscRealPart(atol[k]) + PetscRealPart(rtol[k]) * PetscMax(PetscAbsScalar(u[k]),PetscAbsScalar(y[k]));
5903: max = PetscAbsScalar(y[k] - u[k]) / tol;
5904: for (i=1; i<n; i++) {
5905: tol = PetscRealPart(atol[i]) + PetscRealPart(rtol[i]) * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
5906: max = PetscMax(max,PetscAbsScalar(y[i] - u[i]) / tol);
5907: }
5908: VecRestoreArrayRead(ts->vatol,&atol);
5909: VecRestoreArrayRead(ts->vrtol,&rtol);
5910: } else if (ts->vatol) { /* vector atol, scalar rtol */
5911: const PetscScalar *atol;
5912: VecGetArrayRead(ts->vatol,&atol);
5913: k = 0;
5914: tol = PetscRealPart(atol[k]) + ts->rtol * PetscMax(PetscAbsScalar(u[k]),PetscAbsScalar(y[k]));
5915: max = PetscAbsScalar(y[k] - u[k]) / tol;
5916: for (i=1; i<n; i++) {
5917: tol = PetscRealPart(atol[i]) + ts->rtol * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
5918: max = PetscMax(max,PetscAbsScalar(y[i] - u[i]) / tol);
5919: }
5920: VecRestoreArrayRead(ts->vatol,&atol);
5921: } else if (ts->vrtol) { /* scalar atol, vector rtol */
5922: const PetscScalar *rtol;
5923: VecGetArrayRead(ts->vrtol,&rtol);
5924: k = 0;
5925: tol = ts->atol + PetscRealPart(rtol[k]) * PetscMax(PetscAbsScalar(u[k]),PetscAbsScalar(y[k]));
5926: max = PetscAbsScalar(y[k] - u[k]) / tol;
5927: for (i=1; i<n; i++) {
5928: tol = ts->atol + PetscRealPart(rtol[i]) * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
5929: max = PetscMax(max,PetscAbsScalar(y[i] - u[i]) / tol);
5930: }
5931: VecRestoreArrayRead(ts->vrtol,&rtol);
5932: } else { /* scalar atol, scalar rtol */
5933: k = 0;
5934: tol = ts->atol + ts->rtol * PetscMax(PetscAbsScalar(u[k]),PetscAbsScalar(y[k]));
5935: max = PetscAbsScalar(y[k] - u[k]) / tol;
5936: for (i=1; i<n; i++) {
5937: tol = ts->atol + ts->rtol * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
5938: max = PetscMax(max,PetscAbsScalar(y[i] - u[i]) / tol);
5939: }
5940: }
5941: VecRestoreArrayRead(U,&u);
5942: VecRestoreArrayRead(Y,&y);
5944: MPIU_Allreduce(&max,&gmax,1,MPIU_REAL,MPIU_MAX,PetscObjectComm((PetscObject)ts));
5945: *norm = gmax;
5947: if (PetscIsInfOrNanScalar(*norm)) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_FP,"Infinite or not-a-number generated in norm");
5948: return(0);
5949: }
5953: /*@
5954: TSErrorWeightedNorm - compute a weighted norm of the difference between two state vectors
5956: Collective on TS
5958: Input Arguments:
5959: + ts - time stepping context
5960: . U - state vector, usually ts->vec_sol
5961: . Y - state vector to be compared to U
5962: - wnormtype - norm type, either NORM_2 or NORM_INFINITY
5964: Output Arguments:
5965: . norm - weighted norm, a value of 1.0 is considered small
5968: Options Database Keys:
5969: . -ts_adapt_wnormtype <wnormtype> - 2, INFINITY
5971: Level: developer
5973: .seealso: TSErrorWeightedNormInfinity(), TSErrorWeightedNorm2()
5974: @*/
5975: PetscErrorCode TSErrorWeightedNorm(TS ts,Vec U,Vec Y,NormType wnormtype,PetscReal *norm)
5976: {
5980: if (wnormtype == NORM_2) {
5981: TSErrorWeightedNorm2(ts,U,Y,norm);
5982: } else if(wnormtype == NORM_INFINITY) {
5983: TSErrorWeightedNormInfinity(ts,U,Y,norm);
5984: } else SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"No support for norm type %s",NormTypes[wnormtype]);
5985: return(0);
5986: }
5990: /*@
5991: TSSetCFLTimeLocal - Set the local CFL constraint relative to forward Euler
5993: Logically Collective on TS
5995: Input Arguments:
5996: + ts - time stepping context
5997: - cfltime - maximum stable time step if using forward Euler (value can be different on each process)
5999: Note:
6000: After calling this function, the global CFL time can be obtained by calling TSGetCFLTime()
6002: Level: intermediate
6004: .seealso: TSGetCFLTime(), TSADAPTCFL
6005: @*/
6006: PetscErrorCode TSSetCFLTimeLocal(TS ts,PetscReal cfltime)
6007: {
6010: ts->cfltime_local = cfltime;
6011: ts->cfltime = -1.;
6012: return(0);
6013: }
6017: /*@
6018: TSGetCFLTime - Get the maximum stable time step according to CFL criteria applied to forward Euler
6020: Collective on TS
6022: Input Arguments:
6023: . ts - time stepping context
6025: Output Arguments:
6026: . cfltime - maximum stable time step for forward Euler
6028: Level: advanced
6030: .seealso: TSSetCFLTimeLocal()
6031: @*/
6032: PetscErrorCode TSGetCFLTime(TS ts,PetscReal *cfltime)
6033: {
6037: if (ts->cfltime < 0) {
6038: MPIU_Allreduce(&ts->cfltime_local,&ts->cfltime,1,MPIU_REAL,MPIU_MIN,PetscObjectComm((PetscObject)ts));
6039: }
6040: *cfltime = ts->cfltime;
6041: return(0);
6042: }
6046: /*@
6047: TSVISetVariableBounds - Sets the lower and upper bounds for the solution vector. xl <= x <= xu
6049: Input Parameters:
6050: . ts - the TS context.
6051: . xl - lower bound.
6052: . xu - upper bound.
6054: Notes:
6055: If this routine is not called then the lower and upper bounds are set to
6056: PETSC_NINFINITY and PETSC_INFINITY respectively during SNESSetUp().
6058: Level: advanced
6060: @*/
6061: PetscErrorCode TSVISetVariableBounds(TS ts, Vec xl, Vec xu)
6062: {
6064: SNES snes;
6067: TSGetSNES(ts,&snes);
6068: SNESVISetVariableBounds(snes,xl,xu);
6069: return(0);
6070: }
6072: #if defined(PETSC_HAVE_MATLAB_ENGINE)
6073: #include <mex.h>
6075: typedef struct {char *funcname; mxArray *ctx;} TSMatlabContext;
6079: /*
6080: TSComputeFunction_Matlab - Calls the function that has been set with
6081: TSSetFunctionMatlab().
6083: Collective on TS
6085: Input Parameters:
6086: + snes - the TS context
6087: - u - input vector
6089: Output Parameter:
6090: . y - function vector, as set by TSSetFunction()
6092: Notes:
6093: TSComputeFunction() is typically used within nonlinear solvers
6094: implementations, so most users would not generally call this routine
6095: themselves.
6097: Level: developer
6099: .keywords: TS, nonlinear, compute, function
6101: .seealso: TSSetFunction(), TSGetFunction()
6102: */
6103: PetscErrorCode TSComputeFunction_Matlab(TS snes,PetscReal time,Vec u,Vec udot,Vec y, void *ctx)
6104: {
6105: PetscErrorCode ierr;
6106: TSMatlabContext *sctx = (TSMatlabContext*)ctx;
6107: int nlhs = 1,nrhs = 7;
6108: mxArray *plhs[1],*prhs[7];
6109: long long int lx = 0,lxdot = 0,ly = 0,ls = 0;
6119: PetscMemcpy(&ls,&snes,sizeof(snes));
6120: PetscMemcpy(&lx,&u,sizeof(u));
6121: PetscMemcpy(&lxdot,&udot,sizeof(udot));
6122: PetscMemcpy(&ly,&y,sizeof(u));
6124: prhs[0] = mxCreateDoubleScalar((double)ls);
6125: prhs[1] = mxCreateDoubleScalar(time);
6126: prhs[2] = mxCreateDoubleScalar((double)lx);
6127: prhs[3] = mxCreateDoubleScalar((double)lxdot);
6128: prhs[4] = mxCreateDoubleScalar((double)ly);
6129: prhs[5] = mxCreateString(sctx->funcname);
6130: prhs[6] = sctx->ctx;
6131: mexCallMATLAB(nlhs,plhs,nrhs,prhs,"PetscTSComputeFunctionInternal");
6132: mxGetScalar(plhs[0]);
6133: mxDestroyArray(prhs[0]);
6134: mxDestroyArray(prhs[1]);
6135: mxDestroyArray(prhs[2]);
6136: mxDestroyArray(prhs[3]);
6137: mxDestroyArray(prhs[4]);
6138: mxDestroyArray(prhs[5]);
6139: mxDestroyArray(plhs[0]);
6140: return(0);
6141: }
6146: /*
6147: TSSetFunctionMatlab - Sets the function evaluation routine and function
6148: vector for use by the TS routines in solving ODEs
6149: equations from MATLAB. Here the function is a string containing the name of a MATLAB function
6151: Logically Collective on TS
6153: Input Parameters:
6154: + ts - the TS context
6155: - func - function evaluation routine
6157: Calling sequence of func:
6158: $ func (TS ts,PetscReal time,Vec u,Vec udot,Vec f,void *ctx);
6160: Level: beginner
6162: .keywords: TS, nonlinear, set, function
6164: .seealso: TSGetFunction(), TSComputeFunction(), TSSetJacobian(), TSSetFunction()
6165: */
6166: PetscErrorCode TSSetFunctionMatlab(TS ts,const char *func,mxArray *ctx)
6167: {
6168: PetscErrorCode ierr;
6169: TSMatlabContext *sctx;
6172: /* currently sctx is memory bleed */
6173: PetscMalloc(sizeof(TSMatlabContext),&sctx);
6174: PetscStrallocpy(func,&sctx->funcname);
6175: /*
6176: This should work, but it doesn't
6177: sctx->ctx = ctx;
6178: mexMakeArrayPersistent(sctx->ctx);
6179: */
6180: sctx->ctx = mxDuplicateArray(ctx);
6182: TSSetIFunction(ts,NULL,TSComputeFunction_Matlab,sctx);
6183: return(0);
6184: }
6188: /*
6189: TSComputeJacobian_Matlab - Calls the function that has been set with
6190: TSSetJacobianMatlab().
6192: Collective on TS
6194: Input Parameters:
6195: + ts - the TS context
6196: . u - input vector
6197: . A, B - the matrices
6198: - ctx - user context
6200: Level: developer
6202: .keywords: TS, nonlinear, compute, function
6204: .seealso: TSSetFunction(), TSGetFunction()
6205: @*/
6206: PetscErrorCode TSComputeJacobian_Matlab(TS ts,PetscReal time,Vec u,Vec udot,PetscReal shift,Mat A,Mat B,void *ctx)
6207: {
6208: PetscErrorCode ierr;
6209: TSMatlabContext *sctx = (TSMatlabContext*)ctx;
6210: int nlhs = 2,nrhs = 9;
6211: mxArray *plhs[2],*prhs[9];
6212: long long int lx = 0,lxdot = 0,lA = 0,ls = 0, lB = 0;
6218: /* call Matlab function in ctx with arguments u and y */
6220: PetscMemcpy(&ls,&ts,sizeof(ts));
6221: PetscMemcpy(&lx,&u,sizeof(u));
6222: PetscMemcpy(&lxdot,&udot,sizeof(u));
6223: PetscMemcpy(&lA,A,sizeof(u));
6224: PetscMemcpy(&lB,B,sizeof(u));
6226: prhs[0] = mxCreateDoubleScalar((double)ls);
6227: prhs[1] = mxCreateDoubleScalar((double)time);
6228: prhs[2] = mxCreateDoubleScalar((double)lx);
6229: prhs[3] = mxCreateDoubleScalar((double)lxdot);
6230: prhs[4] = mxCreateDoubleScalar((double)shift);
6231: prhs[5] = mxCreateDoubleScalar((double)lA);
6232: prhs[6] = mxCreateDoubleScalar((double)lB);
6233: prhs[7] = mxCreateString(sctx->funcname);
6234: prhs[8] = sctx->ctx;
6235: mexCallMATLAB(nlhs,plhs,nrhs,prhs,"PetscTSComputeJacobianInternal");
6236: mxGetScalar(plhs[0]);
6237: mxDestroyArray(prhs[0]);
6238: mxDestroyArray(prhs[1]);
6239: mxDestroyArray(prhs[2]);
6240: mxDestroyArray(prhs[3]);
6241: mxDestroyArray(prhs[4]);
6242: mxDestroyArray(prhs[5]);
6243: mxDestroyArray(prhs[6]);
6244: mxDestroyArray(prhs[7]);
6245: mxDestroyArray(plhs[0]);
6246: mxDestroyArray(plhs[1]);
6247: return(0);
6248: }
6253: /*
6254: TSSetJacobianMatlab - Sets the Jacobian function evaluation routine and two empty Jacobian matrices
6255: vector for use by the TS routines in solving ODEs from MATLAB. Here the function is a string containing the name of a MATLAB function
6257: Logically Collective on TS
6259: Input Parameters:
6260: + ts - the TS context
6261: . A,B - Jacobian matrices
6262: . func - function evaluation routine
6263: - ctx - user context
6265: Calling sequence of func:
6266: $ flag = func (TS ts,PetscReal time,Vec u,Vec udot,Mat A,Mat B,void *ctx);
6269: Level: developer
6271: .keywords: TS, nonlinear, set, function
6273: .seealso: TSGetFunction(), TSComputeFunction(), TSSetJacobian(), TSSetFunction()
6274: */
6275: PetscErrorCode TSSetJacobianMatlab(TS ts,Mat A,Mat B,const char *func,mxArray *ctx)
6276: {
6277: PetscErrorCode ierr;
6278: TSMatlabContext *sctx;
6281: /* currently sctx is memory bleed */
6282: PetscMalloc(sizeof(TSMatlabContext),&sctx);
6283: PetscStrallocpy(func,&sctx->funcname);
6284: /*
6285: This should work, but it doesn't
6286: sctx->ctx = ctx;
6287: mexMakeArrayPersistent(sctx->ctx);
6288: */
6289: sctx->ctx = mxDuplicateArray(ctx);
6291: TSSetIJacobian(ts,A,B,TSComputeJacobian_Matlab,sctx);
6292: return(0);
6293: }
6297: /*
6298: TSMonitor_Matlab - Calls the function that has been set with TSMonitorSetMatlab().
6300: Collective on TS
6302: .seealso: TSSetFunction(), TSGetFunction()
6303: @*/
6304: PetscErrorCode TSMonitor_Matlab(TS ts,PetscInt it, PetscReal time,Vec u, void *ctx)
6305: {
6306: PetscErrorCode ierr;
6307: TSMatlabContext *sctx = (TSMatlabContext*)ctx;
6308: int nlhs = 1,nrhs = 6;
6309: mxArray *plhs[1],*prhs[6];
6310: long long int lx = 0,ls = 0;
6316: PetscMemcpy(&ls,&ts,sizeof(ts));
6317: PetscMemcpy(&lx,&u,sizeof(u));
6319: prhs[0] = mxCreateDoubleScalar((double)ls);
6320: prhs[1] = mxCreateDoubleScalar((double)it);
6321: prhs[2] = mxCreateDoubleScalar((double)time);
6322: prhs[3] = mxCreateDoubleScalar((double)lx);
6323: prhs[4] = mxCreateString(sctx->funcname);
6324: prhs[5] = sctx->ctx;
6325: mexCallMATLAB(nlhs,plhs,nrhs,prhs,"PetscTSMonitorInternal");
6326: mxGetScalar(plhs[0]);
6327: mxDestroyArray(prhs[0]);
6328: mxDestroyArray(prhs[1]);
6329: mxDestroyArray(prhs[2]);
6330: mxDestroyArray(prhs[3]);
6331: mxDestroyArray(prhs[4]);
6332: mxDestroyArray(plhs[0]);
6333: return(0);
6334: }
6339: /*
6340: TSMonitorSetMatlab - Sets the monitor function from Matlab
6342: Level: developer
6344: .keywords: TS, nonlinear, set, function
6346: .seealso: TSGetFunction(), TSComputeFunction(), TSSetJacobian(), TSSetFunction()
6347: */
6348: PetscErrorCode TSMonitorSetMatlab(TS ts,const char *func,mxArray *ctx)
6349: {
6350: PetscErrorCode ierr;
6351: TSMatlabContext *sctx;
6354: /* currently sctx is memory bleed */
6355: PetscMalloc(sizeof(TSMatlabContext),&sctx);
6356: PetscStrallocpy(func,&sctx->funcname);
6357: /*
6358: This should work, but it doesn't
6359: sctx->ctx = ctx;
6360: mexMakeArrayPersistent(sctx->ctx);
6361: */
6362: sctx->ctx = mxDuplicateArray(ctx);
6364: TSMonitorSet(ts,TSMonitor_Matlab,sctx,NULL);
6365: return(0);
6366: }
6367: #endif
6371: /*@C
6372: TSMonitorLGSolution - Monitors progress of the TS solvers by plotting each component of the solution vector
6373: in a time based line graph
6375: Collective on TS
6377: Input Parameters:
6378: + ts - the TS context
6379: . step - current time-step
6380: . ptime - current time
6381: . u - current solution
6382: - dctx - the TSMonitorLGCtx object that contains all the options for the monitoring, this is created with TSMonitorLGCtxCreate()
6384: Options Database:
6385: . -ts_monitor_lg_solution_variables
6387: Level: intermediate
6389: Notes: Each process in a parallel run displays its component solutions in a separate window
6391: .keywords: TS, vector, monitor, view
6393: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorLGCtxCreate(), TSMonitorLGCtxSetVariableNames(), TSMonitorLGCtxGetVariableNames(),
6394: TSMonitorLGSetVariableNames(), TSMonitorLGGetVariableNames(), TSMonitorLGSetDisplayVariables(), TSMonitorLGCtxSetDisplayVariables(),
6395: TSMonitorLGCtxSetTransform(), TSMonitorLGSetTransform(), TSMonitorLGError(), TSMonitorLGSNESIterations(), TSMonitorLGKSPIterations(),
6396: TSMonitorEnvelopeCtxCreate(), TSMonitorEnvelopeGetBounds(), TSMonitorEnvelopeCtxDestroy(), TSMonitorEnvelop()
6397: @*/
6398: PetscErrorCode TSMonitorLGSolution(TS ts,PetscInt step,PetscReal ptime,Vec u,void *dctx)
6399: {
6400: PetscErrorCode ierr;
6401: TSMonitorLGCtx ctx = (TSMonitorLGCtx)dctx;
6402: const PetscScalar *yy;
6403: Vec v;
6406: if (step < 0) return(0); /* -1 indicates interpolated solution */
6407: if (!step) {
6408: PetscDrawAxis axis;
6409: PetscInt dim;
6410: PetscDrawLGGetAxis(ctx->lg,&axis);
6411: PetscDrawAxisSetLabels(axis,"Solution as function of time","Time","Solution");
6412: if (ctx->names && !ctx->displaynames) {
6413: char **displaynames;
6414: PetscBool flg;
6415: VecGetLocalSize(u,&dim);
6416: PetscMalloc((dim+1)*sizeof(char*),&displaynames);
6417: PetscMemzero(displaynames,(dim+1)*sizeof(char*));
6418: PetscOptionsGetStringArray(((PetscObject)ts)->options,((PetscObject)ts)->prefix,"-ts_monitor_lg_solution_variables",displaynames,&dim,&flg);
6419: if (flg) {
6420: TSMonitorLGCtxSetDisplayVariables(ctx,(const char *const *)displaynames);
6421: }
6422: PetscStrArrayDestroy(&displaynames);
6423: }
6424: if (ctx->displaynames) {
6425: PetscDrawLGSetDimension(ctx->lg,ctx->ndisplayvariables);
6426: PetscDrawLGSetLegend(ctx->lg,(const char *const *)ctx->displaynames);
6427: } else if (ctx->names) {
6428: VecGetLocalSize(u,&dim);
6429: PetscDrawLGSetDimension(ctx->lg,dim);
6430: PetscDrawLGSetLegend(ctx->lg,(const char *const *)ctx->names);
6431: } else {
6432: VecGetLocalSize(u,&dim);
6433: PetscDrawLGSetDimension(ctx->lg,dim);
6434: }
6435: PetscDrawLGReset(ctx->lg);
6436: }
6438: if (!ctx->transform) v = u;
6439: else {(*ctx->transform)(ctx->transformctx,u,&v);}
6440: VecGetArrayRead(v,&yy);
6441: if (ctx->displaynames) {
6442: PetscInt i;
6443: for (i=0; i<ctx->ndisplayvariables; i++)
6444: ctx->displayvalues[i] = PetscRealPart(yy[ctx->displayvariables[i]]);
6445: PetscDrawLGAddCommonPoint(ctx->lg,ptime,ctx->displayvalues);
6446: } else {
6447: #if defined(PETSC_USE_COMPLEX)
6448: PetscInt i,n;
6449: PetscReal *yreal;
6450: VecGetLocalSize(v,&n);
6451: PetscMalloc1(n,&yreal);
6452: for (i=0; i<n; i++) yreal[i] = PetscRealPart(yy[i]);
6453: PetscDrawLGAddCommonPoint(ctx->lg,ptime,yreal);
6454: PetscFree(yreal);
6455: #else
6456: PetscDrawLGAddCommonPoint(ctx->lg,ptime,yy);
6457: #endif
6458: }
6459: VecRestoreArrayRead(v,&yy);
6460: if (ctx->transform) {VecDestroy(&v);}
6462: if (((ctx->howoften > 0) && (!(step % ctx->howoften))) || ((ctx->howoften == -1) && ts->reason)) {
6463: PetscDrawLGDraw(ctx->lg);
6464: PetscDrawLGSave(ctx->lg);
6465: }
6466: return(0);
6467: }
6472: /*@C
6473: TSMonitorLGSetVariableNames - Sets the name of each component in the solution vector so that it may be displayed in the plot
6475: Collective on TS
6477: Input Parameters:
6478: + ts - the TS context
6479: - names - the names of the components, final string must be NULL
6481: Level: intermediate
6483: Notes: If the TS object does not have a TSMonitorLGCtx associated with it then this function is ignored
6485: .keywords: TS, vector, monitor, view
6487: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorLGSetDisplayVariables(), TSMonitorLGCtxSetVariableNames()
6488: @*/
6489: PetscErrorCode TSMonitorLGSetVariableNames(TS ts,const char * const *names)
6490: {
6491: PetscErrorCode ierr;
6492: PetscInt i;
6495: for (i=0; i<ts->numbermonitors; i++) {
6496: if (ts->monitor[i] == TSMonitorLGSolution) {
6497: TSMonitorLGCtxSetVariableNames((TSMonitorLGCtx)ts->monitorcontext[i],names);
6498: break;
6499: }
6500: }
6501: return(0);
6502: }
6506: /*@C
6507: TSMonitorLGCtxSetVariableNames - Sets the name of each component in the solution vector so that it may be displayed in the plot
6509: Collective on TS
6511: Input Parameters:
6512: + ts - the TS context
6513: - names - the names of the components, final string must be NULL
6515: Level: intermediate
6517: .keywords: TS, vector, monitor, view
6519: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorLGSetDisplayVariables(), TSMonitorLGSetVariableNames()
6520: @*/
6521: PetscErrorCode TSMonitorLGCtxSetVariableNames(TSMonitorLGCtx ctx,const char * const *names)
6522: {
6523: PetscErrorCode ierr;
6526: PetscStrArrayDestroy(&ctx->names);
6527: PetscStrArrayallocpy(names,&ctx->names);
6528: return(0);
6529: }
6533: /*@C
6534: TSMonitorLGGetVariableNames - Gets the name of each component in the solution vector so that it may be displayed in the plot
6536: Collective on TS
6538: Input Parameter:
6539: . ts - the TS context
6541: Output Parameter:
6542: . names - the names of the components, final string must be NULL
6544: Level: intermediate
6546: Notes: If the TS object does not have a TSMonitorLGCtx associated with it then this function is ignored
6548: .keywords: TS, vector, monitor, view
6550: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorLGSetDisplayVariables()
6551: @*/
6552: PetscErrorCode TSMonitorLGGetVariableNames(TS ts,const char *const **names)
6553: {
6554: PetscInt i;
6557: *names = NULL;
6558: for (i=0; i<ts->numbermonitors; i++) {
6559: if (ts->monitor[i] == TSMonitorLGSolution) {
6560: TSMonitorLGCtx ctx = (TSMonitorLGCtx) ts->monitorcontext[i];
6561: *names = (const char *const *)ctx->names;
6562: break;
6563: }
6564: }
6565: return(0);
6566: }
6570: /*@C
6571: TSMonitorLGCtxSetDisplayVariables - Sets the variables that are to be display in the monitor
6573: Collective on TS
6575: Input Parameters:
6576: + ctx - the TSMonitorLG context
6577: . displaynames - the names of the components, final string must be NULL
6579: Level: intermediate
6581: .keywords: TS, vector, monitor, view
6583: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorLGSetVariableNames()
6584: @*/
6585: PetscErrorCode TSMonitorLGCtxSetDisplayVariables(TSMonitorLGCtx ctx,const char * const *displaynames)
6586: {
6587: PetscInt j = 0,k;
6588: PetscErrorCode ierr;
6591: if (!ctx->names) return(0);
6592: PetscStrArrayDestroy(&ctx->displaynames);
6593: PetscStrArrayallocpy(displaynames,&ctx->displaynames);
6594: while (displaynames[j]) j++;
6595: ctx->ndisplayvariables = j;
6596: PetscMalloc1(ctx->ndisplayvariables,&ctx->displayvariables);
6597: PetscMalloc1(ctx->ndisplayvariables,&ctx->displayvalues);
6598: j = 0;
6599: while (displaynames[j]) {
6600: k = 0;
6601: while (ctx->names[k]) {
6602: PetscBool flg;
6603: PetscStrcmp(displaynames[j],ctx->names[k],&flg);
6604: if (flg) {
6605: ctx->displayvariables[j] = k;
6606: break;
6607: }
6608: k++;
6609: }
6610: j++;
6611: }
6612: return(0);
6613: }
6618: /*@C
6619: TSMonitorLGSetDisplayVariables - Sets the variables that are to be display in the monitor
6621: Collective on TS
6623: Input Parameters:
6624: + ts - the TS context
6625: . displaynames - the names of the components, final string must be NULL
6627: Notes: If the TS object does not have a TSMonitorLGCtx associated with it then this function is ignored
6629: Level: intermediate
6631: .keywords: TS, vector, monitor, view
6633: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorLGSetVariableNames()
6634: @*/
6635: PetscErrorCode TSMonitorLGSetDisplayVariables(TS ts,const char * const *displaynames)
6636: {
6637: PetscInt i;
6638: PetscErrorCode ierr;
6641: for (i=0; i<ts->numbermonitors; i++) {
6642: if (ts->monitor[i] == TSMonitorLGSolution) {
6643: TSMonitorLGCtxSetDisplayVariables((TSMonitorLGCtx)ts->monitorcontext[i],displaynames);
6644: break;
6645: }
6646: }
6647: return(0);
6648: }
6652: /*@C
6653: TSMonitorLGSetTransform - Solution vector will be transformed by provided function before being displayed
6655: Collective on TS
6657: Input Parameters:
6658: + ts - the TS context
6659: . transform - the transform function
6660: . destroy - function to destroy the optional context
6661: - ctx - optional context used by transform function
6663: Notes: If the TS object does not have a TSMonitorLGCtx associated with it then this function is ignored
6665: Level: intermediate
6667: .keywords: TS, vector, monitor, view
6669: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorLGSetVariableNames(), TSMonitorLGCtxSetTransform()
6670: @*/
6671: PetscErrorCode TSMonitorLGSetTransform(TS ts,PetscErrorCode (*transform)(void*,Vec,Vec*),PetscErrorCode (*destroy)(void*),void *tctx)
6672: {
6673: PetscInt i;
6674: PetscErrorCode ierr;
6677: for (i=0; i<ts->numbermonitors; i++) {
6678: if (ts->monitor[i] == TSMonitorLGSolution) {
6679: TSMonitorLGCtxSetTransform((TSMonitorLGCtx)ts->monitorcontext[i],transform,destroy,tctx);
6680: }
6681: }
6682: return(0);
6683: }
6687: /*@C
6688: TSMonitorLGCtxSetTransform - Solution vector will be transformed by provided function before being displayed
6690: Collective on TSLGCtx
6692: Input Parameters:
6693: + ts - the TS context
6694: . transform - the transform function
6695: . destroy - function to destroy the optional context
6696: - ctx - optional context used by transform function
6698: Level: intermediate
6700: .keywords: TS, vector, monitor, view
6702: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorLGSetVariableNames(), TSMonitorLGSetTransform()
6703: @*/
6704: PetscErrorCode TSMonitorLGCtxSetTransform(TSMonitorLGCtx ctx,PetscErrorCode (*transform)(void*,Vec,Vec*),PetscErrorCode (*destroy)(void*),void *tctx)
6705: {
6707: ctx->transform = transform;
6708: ctx->transformdestroy = destroy;
6709: ctx->transformctx = tctx;
6710: return(0);
6711: }
6715: /*@C
6716: TSMonitorLGError - Monitors progress of the TS solvers by plotting each component of the solution vector
6717: in a time based line graph
6719: Collective on TS
6721: Input Parameters:
6722: + ts - the TS context
6723: . step - current time-step
6724: . ptime - current time
6725: . u - current solution
6726: - dctx - TSMonitorLGCtx object created with TSMonitorLGCtxCreate()
6728: Level: intermediate
6730: Notes: Each process in a parallel run displays its component errors in a separate window
6732: The user must provide the solution using TSSetSolutionFunction() to use this monitor.
6734: Options Database Keys:
6735: . -ts_monitor_lg_error - create a graphical monitor of error history
6737: .keywords: TS, vector, monitor, view
6739: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSSetSolutionFunction()
6740: @*/
6741: PetscErrorCode TSMonitorLGError(TS ts,PetscInt step,PetscReal ptime,Vec u,void *dummy)
6742: {
6743: PetscErrorCode ierr;
6744: TSMonitorLGCtx ctx = (TSMonitorLGCtx)dummy;
6745: const PetscScalar *yy;
6746: Vec y;
6749: if (!step) {
6750: PetscDrawAxis axis;
6751: PetscInt dim;
6752: PetscDrawLGGetAxis(ctx->lg,&axis);
6753: PetscDrawAxisSetLabels(axis,"Error in solution as function of time","Time","Solution");
6754: VecGetLocalSize(u,&dim);
6755: PetscDrawLGSetDimension(ctx->lg,dim);
6756: PetscDrawLGReset(ctx->lg);
6757: }
6758: VecDuplicate(u,&y);
6759: TSComputeSolutionFunction(ts,ptime,y);
6760: VecAXPY(y,-1.0,u);
6761: VecGetArrayRead(y,&yy);
6762: #if defined(PETSC_USE_COMPLEX)
6763: {
6764: PetscReal *yreal;
6765: PetscInt i,n;
6766: VecGetLocalSize(y,&n);
6767: PetscMalloc1(n,&yreal);
6768: for (i=0; i<n; i++) yreal[i] = PetscRealPart(yy[i]);
6769: PetscDrawLGAddCommonPoint(ctx->lg,ptime,yreal);
6770: PetscFree(yreal);
6771: }
6772: #else
6773: PetscDrawLGAddCommonPoint(ctx->lg,ptime,yy);
6774: #endif
6775: VecRestoreArrayRead(y,&yy);
6776: VecDestroy(&y);
6777: if (((ctx->howoften > 0) && (!(step % ctx->howoften))) || ((ctx->howoften == -1) && ts->reason)) {
6778: PetscDrawLGDraw(ctx->lg);
6779: PetscDrawLGSave(ctx->lg);
6780: }
6781: return(0);
6782: }
6786: PetscErrorCode TSMonitorLGSNESIterations(TS ts,PetscInt n,PetscReal ptime,Vec v,void *monctx)
6787: {
6788: TSMonitorLGCtx ctx = (TSMonitorLGCtx) monctx;
6789: PetscReal x = ptime,y;
6791: PetscInt its;
6794: if (n < 0) return(0); /* -1 indicates interpolated solution */
6795: if (!n) {
6796: PetscDrawAxis axis;
6797: PetscDrawLGGetAxis(ctx->lg,&axis);
6798: PetscDrawAxisSetLabels(axis,"Nonlinear iterations as function of time","Time","SNES Iterations");
6799: PetscDrawLGReset(ctx->lg);
6800: ctx->snes_its = 0;
6801: }
6802: TSGetSNESIterations(ts,&its);
6803: y = its - ctx->snes_its;
6804: PetscDrawLGAddPoint(ctx->lg,&x,&y);
6805: if (((ctx->howoften > 0) && (!(n % ctx->howoften)) && (n > -1)) || ((ctx->howoften == -1) && (n == -1))) {
6806: PetscDrawLGDraw(ctx->lg);
6807: PetscDrawLGSave(ctx->lg);
6808: }
6809: ctx->snes_its = its;
6810: return(0);
6811: }
6815: PetscErrorCode TSMonitorLGKSPIterations(TS ts,PetscInt n,PetscReal ptime,Vec v,void *monctx)
6816: {
6817: TSMonitorLGCtx ctx = (TSMonitorLGCtx) monctx;
6818: PetscReal x = ptime,y;
6820: PetscInt its;
6823: if (n < 0) return(0); /* -1 indicates interpolated solution */
6824: if (!n) {
6825: PetscDrawAxis axis;
6826: PetscDrawLGGetAxis(ctx->lg,&axis);
6827: PetscDrawAxisSetLabels(axis,"Linear iterations as function of time","Time","KSP Iterations");
6828: PetscDrawLGReset(ctx->lg);
6829: ctx->ksp_its = 0;
6830: }
6831: TSGetKSPIterations(ts,&its);
6832: y = its - ctx->ksp_its;
6833: PetscDrawLGAddPoint(ctx->lg,&x,&y);
6834: if (((ctx->howoften > 0) && (!(n % ctx->howoften)) && (n > -1)) || ((ctx->howoften == -1) && (n == -1))) {
6835: PetscDrawLGDraw(ctx->lg);
6836: PetscDrawLGSave(ctx->lg);
6837: }
6838: ctx->ksp_its = its;
6839: return(0);
6840: }
6844: /*@
6845: TSComputeLinearStability - computes the linear stability function at a point
6847: Collective on TS and Vec
6849: Input Parameters:
6850: + ts - the TS context
6851: - xr,xi - real and imaginary part of input arguments
6853: Output Parameters:
6854: . yr,yi - real and imaginary part of function value
6856: Level: developer
6858: .keywords: TS, compute
6860: .seealso: TSSetRHSFunction(), TSComputeIFunction()
6861: @*/
6862: PetscErrorCode TSComputeLinearStability(TS ts,PetscReal xr,PetscReal xi,PetscReal *yr,PetscReal *yi)
6863: {
6868: if (!ts->ops->linearstability) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"Linearized stability function not provided for this method");
6869: (*ts->ops->linearstability)(ts,xr,xi,yr,yi);
6870: return(0);
6871: }
6873: /* ------------------------------------------------------------------------*/
6876: /*@C
6877: TSMonitorEnvelopeCtxCreate - Creates a context for use with TSMonitorEnvelope()
6879: Collective on TS
6881: Input Parameters:
6882: . ts - the ODE solver object
6884: Output Parameter:
6885: . ctx - the context
6887: Level: intermediate
6889: .keywords: TS, monitor, line graph, residual, seealso
6891: .seealso: TSMonitorLGTimeStep(), TSMonitorSet(), TSMonitorLGSolution(), TSMonitorLGError()
6893: @*/
6894: PetscErrorCode TSMonitorEnvelopeCtxCreate(TS ts,TSMonitorEnvelopeCtx *ctx)
6895: {
6899: PetscNew(ctx);
6900: return(0);
6901: }
6905: /*@C
6906: TSMonitorEnvelope - Monitors the maximum and minimum value of each component of the solution
6908: Collective on TS
6910: Input Parameters:
6911: + ts - the TS context
6912: . step - current time-step
6913: . ptime - current time
6914: . u - current solution
6915: - dctx - the envelope context
6917: Options Database:
6918: . -ts_monitor_envelope
6920: Level: intermediate
6922: Notes: after a solve you can use TSMonitorEnvelopeGetBounds() to access the envelope
6924: .keywords: TS, vector, monitor, view
6926: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorEnvelopeGetBounds(), TSMonitorEnvelopeCtxCreate()
6927: @*/
6928: PetscErrorCode TSMonitorEnvelope(TS ts,PetscInt step,PetscReal ptime,Vec u,void *dctx)
6929: {
6930: PetscErrorCode ierr;
6931: TSMonitorEnvelopeCtx ctx = (TSMonitorEnvelopeCtx)dctx;
6934: if (!ctx->max) {
6935: VecDuplicate(u,&ctx->max);
6936: VecDuplicate(u,&ctx->min);
6937: VecCopy(u,ctx->max);
6938: VecCopy(u,ctx->min);
6939: } else {
6940: VecPointwiseMax(ctx->max,u,ctx->max);
6941: VecPointwiseMin(ctx->min,u,ctx->min);
6942: }
6943: return(0);
6944: }
6949: /*@C
6950: TSMonitorEnvelopeGetBounds - Gets the bounds for the components of the solution
6952: Collective on TS
6954: Input Parameter:
6955: . ts - the TS context
6957: Output Parameter:
6958: + max - the maximum values
6959: - min - the minimum values
6961: Notes: If the TS does not have a TSMonitorEnvelopeCtx associated with it then this function is ignored
6963: Level: intermediate
6965: .keywords: TS, vector, monitor, view
6967: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorLGSetDisplayVariables()
6968: @*/
6969: PetscErrorCode TSMonitorEnvelopeGetBounds(TS ts,Vec *max,Vec *min)
6970: {
6971: PetscInt i;
6974: if (max) *max = NULL;
6975: if (min) *min = NULL;
6976: for (i=0; i<ts->numbermonitors; i++) {
6977: if (ts->monitor[i] == TSMonitorEnvelope) {
6978: TSMonitorEnvelopeCtx ctx = (TSMonitorEnvelopeCtx) ts->monitorcontext[i];
6979: if (max) *max = ctx->max;
6980: if (min) *min = ctx->min;
6981: break;
6982: }
6983: }
6984: return(0);
6985: }
6989: /*@C
6990: TSMonitorEnvelopeCtxDestroy - Destroys a context that was created with TSMonitorEnvelopeCtxCreate().
6992: Collective on TSMonitorEnvelopeCtx
6994: Input Parameter:
6995: . ctx - the monitor context
6997: Level: intermediate
6999: .keywords: TS, monitor, line graph, destroy
7001: .seealso: TSMonitorLGCtxCreate(), TSMonitorSet(), TSMonitorLGTimeStep()
7002: @*/
7003: PetscErrorCode TSMonitorEnvelopeCtxDestroy(TSMonitorEnvelopeCtx *ctx)
7004: {
7008: VecDestroy(&(*ctx)->min);
7009: VecDestroy(&(*ctx)->max);
7010: PetscFree(*ctx);
7011: return(0);
7012: }
7016: /*@
7017: TSRollBack - Rolls back one time step
7019: Collective on TS
7021: Input Parameter:
7022: . ts - the TS context obtained from TSCreate()
7024: Level: advanced
7026: .keywords: TS, timestep, rollback
7028: .seealso: TSCreate(), TSSetUp(), TSDestroy(), TSSolve(), TSSetPreStep(), TSSetPreStage(), TSInterpolate()
7029: @*/
7030: PetscErrorCode TSRollBack(TS ts)
7031: {
7036: if (ts->steprollback) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_ARG_WRONGSTATE,"TSRollBack already called");
7037: if (!ts->ops->rollback) SETERRQ1(PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"TSRollBack not implemented for type '%s'",((PetscObject)ts)->type_name);
7038: (*ts->ops->rollback)(ts);
7039: ts->time_step = ts->ptime - ts->ptime_prev;
7040: ts->ptime = ts->ptime_prev;
7041: ts->ptime_prev = ts->ptime_prev_rollback;
7042: ts->steps--; ts->total_steps--;
7043: ts->steprollback = PETSC_TRUE;
7044: return(0);
7045: }
7049: /*@
7050: TSGetStages - Get the number of stages and stage values
7052: Input Parameter:
7053: . ts - the TS context obtained from TSCreate()
7055: Level: advanced
7057: .keywords: TS, getstages
7059: .seealso: TSCreate()
7060: @*/
7061: PetscErrorCode TSGetStages(TS ts,PetscInt *ns,Vec **Y)
7062: {
7069: if (!ts->ops->getstages) *ns=0;
7070: else {
7071: (*ts->ops->getstages)(ts,ns,Y);
7072: }
7073: return(0);
7074: }
7078: /*@C
7079: TSComputeIJacobianDefaultColor - Computes the Jacobian using finite differences and coloring to exploit matrix sparsity.
7081: Collective on SNES
7083: Input Parameters:
7084: + ts - the TS context
7085: . t - current timestep
7086: . U - state vector
7087: . Udot - time derivative of state vector
7088: . shift - shift to apply, see note below
7089: - ctx - an optional user context
7091: Output Parameters:
7092: + J - Jacobian matrix (not altered in this routine)
7093: - B - newly computed Jacobian matrix to use with preconditioner (generally the same as J)
7095: Level: intermediate
7097: Notes:
7098: If F(t,U,Udot)=0 is the DAE, the required Jacobian is
7100: dF/dU + shift*dF/dUdot
7102: Most users should not need to explicitly call this routine, as it
7103: is used internally within the nonlinear solvers.
7105: This will first try to get the coloring from the DM. If the DM type has no coloring
7106: routine, then it will try to get the coloring from the matrix. This requires that the
7107: matrix have nonzero entries precomputed.
7109: .keywords: TS, finite differences, Jacobian, coloring, sparse
7110: .seealso: TSSetIJacobian(), MatFDColoringCreate(), MatFDColoringSetFunction()
7111: @*/
7112: PetscErrorCode TSComputeIJacobianDefaultColor(TS ts,PetscReal t,Vec U,Vec Udot,PetscReal shift,Mat J,Mat B,void *ctx)
7113: {
7114: SNES snes;
7115: MatFDColoring color;
7116: PetscBool hascolor, matcolor = PETSC_FALSE;
7120: PetscOptionsGetBool(((PetscObject)ts)->options,((PetscObject) ts)->prefix, "-ts_fd_color_use_mat", &matcolor, NULL);
7121: PetscObjectQuery((PetscObject) B, "TSMatFDColoring", (PetscObject *) &color);
7122: if (!color) {
7123: DM dm;
7124: ISColoring iscoloring;
7126: TSGetDM(ts, &dm);
7127: DMHasColoring(dm, &hascolor);
7128: if (hascolor && !matcolor) {
7129: DMCreateColoring(dm, IS_COLORING_GLOBAL, &iscoloring);
7130: MatFDColoringCreate(B, iscoloring, &color);
7131: MatFDColoringSetFunction(color, (PetscErrorCode (*)(void)) SNESTSFormFunction, (void *) ts);
7132: MatFDColoringSetFromOptions(color);
7133: MatFDColoringSetUp(B, iscoloring, color);
7134: ISColoringDestroy(&iscoloring);
7135: } else {
7136: MatColoring mc;
7138: MatColoringCreate(B, &mc);
7139: MatColoringSetDistance(mc, 2);
7140: MatColoringSetType(mc, MATCOLORINGSL);
7141: MatColoringSetFromOptions(mc);
7142: MatColoringApply(mc, &iscoloring);
7143: MatColoringDestroy(&mc);
7144: MatFDColoringCreate(B, iscoloring, &color);
7145: MatFDColoringSetFunction(color, (PetscErrorCode (*)(void)) SNESTSFormFunction, (void *) ts);
7146: MatFDColoringSetFromOptions(color);
7147: MatFDColoringSetUp(B, iscoloring, color);
7148: ISColoringDestroy(&iscoloring);
7149: }
7150: PetscObjectCompose((PetscObject) B, "TSMatFDColoring", (PetscObject) color);
7151: PetscObjectDereference((PetscObject) color);
7152: }
7153: TSGetSNES(ts, &snes);
7154: MatFDColoringApply(B, color, U, snes);
7155: if (J != B) {
7156: MatAssemblyBegin(J, MAT_FINAL_ASSEMBLY);
7157: MatAssemblyEnd(J, MAT_FINAL_ASSEMBLY);
7158: }
7159: return(0);
7160: }
7164: /*@
7165: TSSetFunctionDomainError - Set the function testing if the current state vector is valid
7167: Input Parameters:
7168: ts - the TS context
7169: func - function called within TSFunctionDomainError
7171: Level: intermediate
7173: .keywords: TS, state, domain
7174: .seealso: TSAdaptCheckStage(), TSFunctionDomainError()
7175: @*/
7177: PetscErrorCode TSSetFunctionDomainError(TS ts, PetscErrorCode (*func)(TS,PetscReal,Vec,PetscBool*))
7178: {
7181: ts->functiondomainerror = func;
7182: return(0);
7183: }
7187: /*@
7188: TSFunctionDomainError - Check if the current state is valid
7190: Input Parameters:
7191: ts - the TS context
7192: stagetime - time of the simulation
7193: Y - state vector to check.
7195: Output Parameter:
7196: accept - Set to PETSC_FALSE if the current state vector is valid.
7198: Note:
7199: This function should be used to ensure the state is in a valid part of the space.
7200: For example, one can ensure here all values are positive.
7202: Level: advanced
7203: @*/
7204: PetscErrorCode TSFunctionDomainError(TS ts,PetscReal stagetime,Vec Y,PetscBool* accept)
7205: {
7211: *accept = PETSC_TRUE;
7212: if (ts->functiondomainerror) {
7213: PetscStackCallStandard((*ts->functiondomainerror),(ts,stagetime,Y,accept));
7214: }
7215: return(0);
7216: }
7218: #undef __FUNCT__
7220: /*@C
7221: TSClone - This function clones a time step object.
7223: Collective on MPI_Comm
7225: Input Parameter:
7226: . tsin - The input TS
7228: Output Parameter:
7229: . tsout - The output TS (cloned)
7231: Notes:
7232: 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.
7234: 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);
7236: Level: developer
7238: .keywords: TS, clone
7239: .seealso: TSCreate(), TSSetType(), TSSetUp(), TSDestroy(), TSSetProblemType()
7240: @*/
7241: PetscErrorCode TSClone(TS tsin, TS *tsout)
7242: {
7243: TS t;
7245: SNES snes_start;
7246: DM dm;
7247: TSType type;
7251: *tsout = NULL;
7253: PetscHeaderCreate(t, TS_CLASSID, "TS", "Time stepping", "TS", PetscObjectComm((PetscObject)tsin), TSDestroy, TSView);
7255: /* General TS description */
7256: t->numbermonitors = 0;
7257: t->setupcalled = 0;
7258: t->ksp_its = 0;
7259: t->snes_its = 0;
7260: t->nwork = 0;
7261: t->rhsjacobian.time = -1e20;
7262: t->rhsjacobian.scale = 1.;
7263: t->ijacobian.shift = 1.;
7265: TSGetSNES(tsin,&snes_start);
7266: TSSetSNES(t,snes_start);
7268: TSGetDM(tsin,&dm);
7269: TSSetDM(t,dm);
7271: t->adapt = tsin->adapt;
7272: PetscObjectReference((PetscObject)t->adapt);
7274: t->problem_type = tsin->problem_type;
7275: t->ptime = tsin->ptime;
7276: t->time_step = tsin->time_step;
7277: t->max_time = tsin->max_time;
7278: t->steps = tsin->steps;
7279: t->max_steps = tsin->max_steps;
7280: t->equation_type = tsin->equation_type;
7281: t->atol = tsin->atol;
7282: t->rtol = tsin->rtol;
7283: t->max_snes_failures = tsin->max_snes_failures;
7284: t->max_reject = tsin->max_reject;
7285: t->errorifstepfailed = tsin->errorifstepfailed;
7287: TSGetType(tsin,&type);
7288: TSSetType(t,type);
7290: t->vec_sol = NULL;
7292: t->cfltime = tsin->cfltime;
7293: t->cfltime_local = tsin->cfltime_local;
7294: t->exact_final_time = tsin->exact_final_time;
7296: PetscMemcpy(t->ops,tsin->ops,sizeof(struct _TSOps));
7298: if (((PetscObject)tsin)->fortran_func_pointers) {
7299: PetscInt i;
7300: PetscMalloc((10)*sizeof(void(*)(void)),&((PetscObject)t)->fortran_func_pointers);
7301: for (i=0; i<10; i++) {
7302: ((PetscObject)t)->fortran_func_pointers[i] = ((PetscObject)tsin)->fortran_func_pointers[i];
7303: }
7304: }
7305: *tsout = t;
7306: return(0);
7307: }