Actual source code: ts.c
petsc-3.7.7 2017-09-25
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: PetscBool assembled;
920: MatZeroEntries(A);
921: MatAssembled(A,&assembled);
922: if (!assembled) {
923: MatAssemblyBegin(A,MAT_FINAL_ASSEMBLY);
924: MatAssemblyEnd(A,MAT_FINAL_ASSEMBLY);
925: }
926: MatShift(A,shift);
927: if (A != B) {
928: MatZeroEntries(B);
929: MatAssembled(B,&assembled);
930: if (!assembled) {
931: MatAssemblyBegin(B,MAT_FINAL_ASSEMBLY);
932: MatAssemblyEnd(B,MAT_FINAL_ASSEMBLY);
933: }
934: MatShift(B,shift);
935: }
936: }
937: } else {
938: Mat Arhs = NULL,Brhs = NULL;
939: if (rhsjacobian) {
940: TSGetRHSMats_Private(ts,&Arhs,&Brhs);
941: TSComputeRHSJacobian(ts,t,U,Arhs,Brhs);
942: }
943: if (Arhs == A) { /* No IJacobian, so we only have the RHS matrix */
944: ts->rhsjacobian.scale = -1;
945: ts->rhsjacobian.shift = shift;
946: MatScale(A,-1);
947: MatShift(A,shift);
948: if (A != B) {
949: MatScale(B,-1);
950: MatShift(B,shift);
951: }
952: } else if (Arhs) { /* Both IJacobian and RHSJacobian */
953: MatStructure axpy = DIFFERENT_NONZERO_PATTERN;
954: if (!ijacobian) { /* No IJacobian provided, but we have a separate RHS matrix */
955: MatZeroEntries(A);
956: MatShift(A,shift);
957: if (A != B) {
958: MatZeroEntries(B);
959: MatShift(B,shift);
960: }
961: }
962: MatAXPY(A,-1,Arhs,axpy);
963: if (A != B) {
964: MatAXPY(B,-1,Brhs,axpy);
965: }
966: }
967: }
968: PetscLogEventEnd(TS_JacobianEval,ts,U,A,B);
969: return(0);
970: }
974: /*@C
975: TSSetRHSFunction - Sets the routine for evaluating the function,
976: where U_t = G(t,u).
978: Logically Collective on TS
980: Input Parameters:
981: + ts - the TS context obtained from TSCreate()
982: . r - vector to put the computed right hand side (or NULL to have it created)
983: . f - routine for evaluating the right-hand-side function
984: - ctx - [optional] user-defined context for private data for the
985: function evaluation routine (may be NULL)
987: Calling sequence of func:
988: $ func (TS ts,PetscReal t,Vec u,Vec F,void *ctx);
990: + t - current timestep
991: . u - input vector
992: . F - function vector
993: - ctx - [optional] user-defined function context
995: Level: beginner
997: Notes: You must call this function or TSSetIFunction() to define your ODE. You cannot use this function when solving a DAE.
999: .keywords: TS, timestep, set, right-hand-side, function
1001: .seealso: TSSetRHSJacobian(), TSSetIJacobian(), TSSetIFunction()
1002: @*/
1003: PetscErrorCode TSSetRHSFunction(TS ts,Vec r,PetscErrorCode (*f)(TS,PetscReal,Vec,Vec,void*),void *ctx)
1004: {
1006: SNES snes;
1007: Vec ralloc = NULL;
1008: DM dm;
1014: TSGetDM(ts,&dm);
1015: DMTSSetRHSFunction(dm,f,ctx);
1016: TSGetSNES(ts,&snes);
1017: if (!r && !ts->dm && ts->vec_sol) {
1018: VecDuplicate(ts->vec_sol,&ralloc);
1019: r = ralloc;
1020: }
1021: SNESSetFunction(snes,r,SNESTSFormFunction,ts);
1022: VecDestroy(&ralloc);
1023: return(0);
1024: }
1028: /*@C
1029: TSSetSolutionFunction - Provide a function that computes the solution of the ODE or DAE
1031: Logically Collective on TS
1033: Input Parameters:
1034: + ts - the TS context obtained from TSCreate()
1035: . f - routine for evaluating the solution
1036: - ctx - [optional] user-defined context for private data for the
1037: function evaluation routine (may be NULL)
1039: Calling sequence of func:
1040: $ func (TS ts,PetscReal t,Vec u,void *ctx);
1042: + t - current timestep
1043: . u - output vector
1044: - ctx - [optional] user-defined function context
1046: Notes:
1047: This routine is used for testing accuracy of time integration schemes when you already know the solution.
1048: If analytic solutions are not known for your system, consider using the Method of Manufactured Solutions to
1049: create closed-form solutions with non-physical forcing terms.
1051: For low-dimensional problems solved in serial, such as small discrete systems, TSMonitorLGError() can be used to monitor the error history.
1053: Level: beginner
1055: .keywords: TS, timestep, set, right-hand-side, function
1057: .seealso: TSSetRHSJacobian(), TSSetIJacobian(), TSComputeSolutionFunction(), TSSetForcingFunction()
1058: @*/
1059: PetscErrorCode TSSetSolutionFunction(TS ts,PetscErrorCode (*f)(TS,PetscReal,Vec,void*),void *ctx)
1060: {
1062: DM dm;
1066: TSGetDM(ts,&dm);
1067: DMTSSetSolutionFunction(dm,f,ctx);
1068: return(0);
1069: }
1073: /*@C
1074: TSSetForcingFunction - Provide a function that computes a forcing term for a ODE or PDE
1076: Logically Collective on TS
1078: Input Parameters:
1079: + ts - the TS context obtained from TSCreate()
1080: . f - routine for evaluating the forcing function
1081: - ctx - [optional] user-defined context for private data for the
1082: function evaluation routine (may be NULL)
1084: Calling sequence of func:
1085: $ func (TS ts,PetscReal t,Vec u,void *ctx);
1087: + t - current timestep
1088: . u - output vector
1089: - ctx - [optional] user-defined function context
1091: Notes:
1092: This routine is useful for testing accuracy of time integration schemes when using the Method of Manufactured Solutions to
1093: create closed-form solutions with a non-physical forcing term.
1095: For low-dimensional problems solved in serial, such as small discrete systems, TSMonitorLGError() can be used to monitor the error history.
1097: Level: beginner
1099: .keywords: TS, timestep, set, right-hand-side, function
1101: .seealso: TSSetRHSJacobian(), TSSetIJacobian(), TSComputeSolutionFunction(), TSSetSolutionFunction()
1102: @*/
1103: PetscErrorCode TSSetForcingFunction(TS ts,TSForcingFunction f,void *ctx)
1104: {
1106: DM dm;
1110: TSGetDM(ts,&dm);
1111: DMTSSetForcingFunction(dm,f,ctx);
1112: return(0);
1113: }
1117: /*@C
1118: TSSetRHSJacobian - Sets the function to compute the Jacobian of G,
1119: where U_t = G(U,t), as well as the location to store the matrix.
1121: Logically Collective on TS
1123: Input Parameters:
1124: + ts - the TS context obtained from TSCreate()
1125: . Amat - (approximate) Jacobian matrix
1126: . Pmat - matrix from which preconditioner is to be constructed (usually the same as Amat)
1127: . f - the Jacobian evaluation routine
1128: - ctx - [optional] user-defined context for private data for the
1129: Jacobian evaluation routine (may be NULL)
1131: Calling sequence of f:
1132: $ func (TS ts,PetscReal t,Vec u,Mat A,Mat B,void *ctx);
1134: + t - current timestep
1135: . u - input vector
1136: . Amat - (approximate) Jacobian matrix
1137: . Pmat - matrix from which preconditioner is to be constructed (usually the same as Amat)
1138: - ctx - [optional] user-defined context for matrix evaluation routine
1140: Notes:
1141: You must set all the diagonal entries of the matrices, if they are zero you must still set them with a zero value
1143: The TS solver may modify the nonzero structure and the entries of the matrices Amat and Pmat between the calls to f()
1144: You should not assume the values are the same in the next call to f() as you set them in the previous call.
1146: Level: beginner
1148: .keywords: TS, timestep, set, right-hand-side, Jacobian
1150: .seealso: SNESComputeJacobianDefaultColor(), TSSetRHSFunction(), TSRHSJacobianSetReuse(), TSSetIJacobian()
1152: @*/
1153: PetscErrorCode TSSetRHSJacobian(TS ts,Mat Amat,Mat Pmat,TSRHSJacobian f,void *ctx)
1154: {
1156: SNES snes;
1157: DM dm;
1158: TSIJacobian ijacobian;
1167: TSGetDM(ts,&dm);
1168: DMTSSetRHSJacobian(dm,f,ctx);
1169: if (f == TSComputeRHSJacobianConstant) {
1170: /* Handle this case automatically for the user; otherwise user should call themselves. */
1171: TSRHSJacobianSetReuse(ts,PETSC_TRUE);
1172: }
1173: DMTSGetIJacobian(dm,&ijacobian,NULL);
1174: TSGetSNES(ts,&snes);
1175: if (!ijacobian) {
1176: SNESSetJacobian(snes,Amat,Pmat,SNESTSFormJacobian,ts);
1177: }
1178: if (Amat) {
1179: PetscObjectReference((PetscObject)Amat);
1180: MatDestroy(&ts->Arhs);
1181: ts->Arhs = Amat;
1182: }
1183: if (Pmat) {
1184: PetscObjectReference((PetscObject)Pmat);
1185: MatDestroy(&ts->Brhs);
1186: ts->Brhs = Pmat;
1187: }
1188: return(0);
1189: }
1194: /*@C
1195: TSSetIFunction - Set the function to compute F(t,U,U_t) where F() = 0 is the DAE to be solved.
1197: Logically Collective on TS
1199: Input Parameters:
1200: + ts - the TS context obtained from TSCreate()
1201: . r - vector to hold the residual (or NULL to have it created internally)
1202: . f - the function evaluation routine
1203: - ctx - user-defined context for private data for the function evaluation routine (may be NULL)
1205: Calling sequence of f:
1206: $ f(TS ts,PetscReal t,Vec u,Vec u_t,Vec F,ctx);
1208: + t - time at step/stage being solved
1209: . u - state vector
1210: . u_t - time derivative of state vector
1211: . F - function vector
1212: - ctx - [optional] user-defined context for matrix evaluation routine
1214: Important:
1215: The user MUST call either this routine or TSSetRHSFunction() to define the ODE. When solving DAEs you must use this function.
1217: Level: beginner
1219: .keywords: TS, timestep, set, DAE, Jacobian
1221: .seealso: TSSetRHSJacobian(), TSSetRHSFunction(), TSSetIJacobian()
1222: @*/
1223: PetscErrorCode TSSetIFunction(TS ts,Vec r,TSIFunction f,void *ctx)
1224: {
1226: SNES snes;
1227: Vec ralloc = NULL;
1228: DM dm;
1234: TSGetDM(ts,&dm);
1235: DMTSSetIFunction(dm,f,ctx);
1237: TSGetSNES(ts,&snes);
1238: if (!r && !ts->dm && ts->vec_sol) {
1239: VecDuplicate(ts->vec_sol,&ralloc);
1240: r = ralloc;
1241: }
1242: SNESSetFunction(snes,r,SNESTSFormFunction,ts);
1243: VecDestroy(&ralloc);
1244: return(0);
1245: }
1249: /*@C
1250: TSGetIFunction - Returns the vector where the implicit residual is stored and the function/contex to compute it.
1252: Not Collective
1254: Input Parameter:
1255: . ts - the TS context
1257: Output Parameter:
1258: + r - vector to hold residual (or NULL)
1259: . func - the function to compute residual (or NULL)
1260: - ctx - the function context (or NULL)
1262: Level: advanced
1264: .keywords: TS, nonlinear, get, function
1266: .seealso: TSSetIFunction(), SNESGetFunction()
1267: @*/
1268: PetscErrorCode TSGetIFunction(TS ts,Vec *r,TSIFunction *func,void **ctx)
1269: {
1271: SNES snes;
1272: DM dm;
1276: TSGetSNES(ts,&snes);
1277: SNESGetFunction(snes,r,NULL,NULL);
1278: TSGetDM(ts,&dm);
1279: DMTSGetIFunction(dm,func,ctx);
1280: return(0);
1281: }
1285: /*@C
1286: TSGetRHSFunction - Returns the vector where the right hand side is stored and the function/context to compute it.
1288: Not Collective
1290: Input Parameter:
1291: . ts - the TS context
1293: Output Parameter:
1294: + r - vector to hold computed right hand side (or NULL)
1295: . func - the function to compute right hand side (or NULL)
1296: - ctx - the function context (or NULL)
1298: Level: advanced
1300: .keywords: TS, nonlinear, get, function
1302: .seealso: TSSetRHSFunction(), SNESGetFunction()
1303: @*/
1304: PetscErrorCode TSGetRHSFunction(TS ts,Vec *r,TSRHSFunction *func,void **ctx)
1305: {
1307: SNES snes;
1308: DM dm;
1312: TSGetSNES(ts,&snes);
1313: SNESGetFunction(snes,r,NULL,NULL);
1314: TSGetDM(ts,&dm);
1315: DMTSGetRHSFunction(dm,func,ctx);
1316: return(0);
1317: }
1321: /*@C
1322: TSSetIJacobian - Set the function to compute the matrix dF/dU + a*dF/dU_t where F(t,U,U_t) is the function
1323: provided with TSSetIFunction().
1325: Logically Collective on TS
1327: Input Parameters:
1328: + ts - the TS context obtained from TSCreate()
1329: . Amat - (approximate) Jacobian matrix
1330: . Pmat - matrix used to compute preconditioner (usually the same as Amat)
1331: . f - the Jacobian evaluation routine
1332: - ctx - user-defined context for private data for the Jacobian evaluation routine (may be NULL)
1334: Calling sequence of f:
1335: $ f(TS ts,PetscReal t,Vec U,Vec U_t,PetscReal a,Mat Amat,Mat Pmat,void *ctx);
1337: + t - time at step/stage being solved
1338: . U - state vector
1339: . U_t - time derivative of state vector
1340: . a - shift
1341: . Amat - (approximate) Jacobian of F(t,U,W+a*U), equivalent to dF/dU + a*dF/dU_t
1342: . Pmat - matrix used for constructing preconditioner, usually the same as Amat
1343: - ctx - [optional] user-defined context for matrix evaluation routine
1345: Notes:
1346: The matrices Amat and Pmat are exactly the matrices that are used by SNES for the nonlinear solve.
1348: If you know the operator Amat has a null space you can use MatSetNullSpace() and MatSetTransposeNullSpace() to supply the null
1349: space to Amat and the KSP solvers will automatically use that null space as needed during the solution process.
1351: The matrix dF/dU + a*dF/dU_t you provide turns out to be
1352: the Jacobian of F(t,U,W+a*U) where F(t,U,U_t) = 0 is the DAE to be solved.
1353: The time integrator internally approximates U_t by W+a*U where the positive "shift"
1354: a and vector W depend on the integration method, step size, and past states. For example with
1355: the backward Euler method a = 1/dt and W = -a*U(previous timestep) so
1356: W + a*U = a*(U - U(previous timestep)) = (U - U(previous timestep))/dt
1358: You must set all the diagonal entries of the matrices, if they are zero you must still set them with a zero value
1360: The TS solver may modify the nonzero structure and the entries of the matrices Amat and Pmat between the calls to f()
1361: You should not assume the values are the same in the next call to f() as you set them in the previous call.
1363: Level: beginner
1365: .keywords: TS, timestep, DAE, Jacobian
1367: .seealso: TSSetIFunction(), TSSetRHSJacobian(), SNESComputeJacobianDefaultColor(), SNESComputeJacobianDefault(), TSSetRHSFunction()
1369: @*/
1370: PetscErrorCode TSSetIJacobian(TS ts,Mat Amat,Mat Pmat,TSIJacobian f,void *ctx)
1371: {
1373: SNES snes;
1374: DM dm;
1383: TSGetDM(ts,&dm);
1384: DMTSSetIJacobian(dm,f,ctx);
1386: TSGetSNES(ts,&snes);
1387: SNESSetJacobian(snes,Amat,Pmat,SNESTSFormJacobian,ts);
1388: return(0);
1389: }
1393: /*@
1394: TSRHSJacobianSetReuse - restore RHS Jacobian before re-evaluating. Without this flag, TS will change the sign and
1395: shift the RHS Jacobian for a finite-time-step implicit solve, in which case the user function will need to recompute
1396: the entire Jacobian. The reuse flag must be set if the evaluation function will assume that the matrix entries have
1397: not been changed by the TS.
1399: Logically Collective
1401: Input Arguments:
1402: + ts - TS context obtained from TSCreate()
1403: - reuse - PETSC_TRUE if the RHS Jacobian
1405: Level: intermediate
1407: .seealso: TSSetRHSJacobian(), TSComputeRHSJacobianConstant()
1408: @*/
1409: PetscErrorCode TSRHSJacobianSetReuse(TS ts,PetscBool reuse)
1410: {
1412: ts->rhsjacobian.reuse = reuse;
1413: return(0);
1414: }
1418: /*@C
1419: TSSetI2Function - Set the function to compute F(t,U,U_t,U_tt) where F = 0 is the DAE to be solved.
1421: Logically Collective on TS
1423: Input Parameters:
1424: + ts - the TS context obtained from TSCreate()
1425: . F - vector to hold the residual (or NULL to have it created internally)
1426: . fun - the function evaluation routine
1427: - ctx - user-defined context for private data for the function evaluation routine (may be NULL)
1429: Calling sequence of fun:
1430: $ fun(TS ts,PetscReal t,Vec U,Vec U_t,Vec U_tt,Vec F,ctx);
1432: + t - time at step/stage being solved
1433: . U - state vector
1434: . U_t - time derivative of state vector
1435: . U_tt - second time derivative of state vector
1436: . F - function vector
1437: - ctx - [optional] user-defined context for matrix evaluation routine (may be NULL)
1439: Level: beginner
1441: .keywords: TS, timestep, set, ODE, DAE, Function
1443: .seealso: TSSetI2Jacobian()
1444: @*/
1445: PetscErrorCode TSSetI2Function(TS ts,Vec F,TSI2Function fun,void *ctx)
1446: {
1447: DM dm;
1453: TSSetIFunction(ts,F,NULL,NULL);
1454: TSGetDM(ts,&dm);
1455: DMTSSetI2Function(dm,fun,ctx);
1456: return(0);
1457: }
1461: /*@C
1462: TSGetI2Function - Returns the vector where the implicit residual is stored and the function/contex to compute it.
1464: Not Collective
1466: Input Parameter:
1467: . ts - the TS context
1469: Output Parameter:
1470: + r - vector to hold residual (or NULL)
1471: . fun - the function to compute residual (or NULL)
1472: - ctx - the function context (or NULL)
1474: Level: advanced
1476: .keywords: TS, nonlinear, get, function
1478: .seealso: TSSetI2Function(), SNESGetFunction()
1479: @*/
1480: PetscErrorCode TSGetI2Function(TS ts,Vec *r,TSI2Function *fun,void **ctx)
1481: {
1483: SNES snes;
1484: DM dm;
1488: TSGetSNES(ts,&snes);
1489: SNESGetFunction(snes,r,NULL,NULL);
1490: TSGetDM(ts,&dm);
1491: DMTSGetI2Function(dm,fun,ctx);
1492: return(0);
1493: }
1497: /*@C
1498: TSSetI2Jacobian - Set the function to compute the matrix dF/dU + v*dF/dU_t + a*dF/dU_tt
1499: where F(t,U,U_t,U_tt) is the function you provided with TSSetI2Function().
1501: Logically Collective on TS
1503: Input Parameters:
1504: + ts - the TS context obtained from TSCreate()
1505: . J - Jacobian matrix
1506: . P - preconditioning matrix for J (may be same as J)
1507: . jac - the Jacobian evaluation routine
1508: - ctx - user-defined context for private data for the Jacobian evaluation routine (may be NULL)
1510: Calling sequence of jac:
1511: $ jac(TS ts,PetscReal t,Vec U,Vec U_t,Vec U_tt,PetscReal v,PetscReal a,Mat J,Mat P,void *ctx);
1513: + t - time at step/stage being solved
1514: . U - state vector
1515: . U_t - time derivative of state vector
1516: . U_tt - second time derivative of state vector
1517: . v - shift for U_t
1518: . a - shift for U_tt
1519: . 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
1520: . P - preconditioning matrix for J, may be same as J
1521: - ctx - [optional] user-defined context for matrix evaluation routine
1523: Notes:
1524: The matrices J and P are exactly the matrices that are used by SNES for the nonlinear solve.
1526: The matrix dF/dU + v*dF/dU_t + a*dF/dU_tt you provide turns out to be
1527: 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.
1528: The time integrator internally approximates U_t by W+v*U and U_tt by W'+a*U where the positive "shift"
1529: parameters 'v' and 'a' and vectors W, W' depend on the integration method, step size, and past states.
1531: Level: beginner
1533: .keywords: TS, timestep, set, ODE, DAE, Jacobian
1535: .seealso: TSSetI2Function()
1536: @*/
1537: PetscErrorCode TSSetI2Jacobian(TS ts,Mat J,Mat P,TSI2Jacobian jac,void *ctx)
1538: {
1539: DM dm;
1546: TSSetIJacobian(ts,J,P,NULL,NULL);
1547: TSGetDM(ts,&dm);
1548: DMTSSetI2Jacobian(dm,jac,ctx);
1549: return(0);
1550: }
1554: /*@C
1555: TSGetI2Jacobian - Returns the implicit Jacobian at the present timestep.
1557: Not Collective, but parallel objects are returned if TS is parallel
1559: Input Parameter:
1560: . ts - The TS context obtained from TSCreate()
1562: Output Parameters:
1563: + J - The (approximate) Jacobian of F(t,U,U_t,U_tt)
1564: . P - The matrix from which the preconditioner is constructed, often the same as J
1565: . jac - The function to compute the Jacobian matrices
1566: - ctx - User-defined context for Jacobian evaluation routine
1568: Notes: You can pass in NULL for any return argument you do not need.
1570: Level: advanced
1572: .seealso: TSGetTimeStep(), TSGetMatrices(), TSGetTime(), TSGetTimeStepNumber()
1574: .keywords: TS, timestep, get, matrix, Jacobian
1575: @*/
1576: PetscErrorCode TSGetI2Jacobian(TS ts,Mat *J,Mat *P,TSI2Jacobian *jac,void **ctx)
1577: {
1579: SNES snes;
1580: DM dm;
1583: TSGetSNES(ts,&snes);
1584: SNESSetUpMatrices(snes);
1585: SNESGetJacobian(snes,J,P,NULL,NULL);
1586: TSGetDM(ts,&dm);
1587: DMTSGetI2Jacobian(dm,jac,ctx);
1588: return(0);
1589: }
1593: /*@
1594: TSComputeI2Function - Evaluates the DAE residual written in implicit form F(t,U,U_t,U_tt) = 0
1596: Collective on TS and Vec
1598: Input Parameters:
1599: + ts - the TS context
1600: . t - current time
1601: . U - state vector
1602: . V - time derivative of state vector (U_t)
1603: - A - second time derivative of state vector (U_tt)
1605: Output Parameter:
1606: . F - the residual vector
1608: Note:
1609: Most users should not need to explicitly call this routine, as it
1610: is used internally within the nonlinear solvers.
1612: Level: developer
1614: .keywords: TS, compute, function, vector
1616: .seealso: TSSetI2Function()
1617: @*/
1618: PetscErrorCode TSComputeI2Function(TS ts,PetscReal t,Vec U,Vec V,Vec A,Vec F)
1619: {
1620: DM dm;
1621: TSI2Function I2Function;
1622: void *ctx;
1623: TSRHSFunction rhsfunction;
1633: TSGetDM(ts,&dm);
1634: DMTSGetI2Function(dm,&I2Function,&ctx);
1635: DMTSGetRHSFunction(dm,&rhsfunction,NULL);
1637: if (!I2Function) {
1638: TSComputeIFunction(ts,t,U,A,F,PETSC_FALSE);
1639: return(0);
1640: }
1642: PetscLogEventBegin(TS_FunctionEval,ts,U,V,F);
1644: PetscStackPush("TS user implicit function");
1645: I2Function(ts,t,U,V,A,F,ctx);
1646: PetscStackPop;
1648: if (rhsfunction) {
1649: Vec Frhs;
1650: TSGetRHSVec_Private(ts,&Frhs);
1651: TSComputeRHSFunction(ts,t,U,Frhs);
1652: VecAXPY(F,-1,Frhs);
1653: }
1655: PetscLogEventEnd(TS_FunctionEval,ts,U,V,F);
1656: return(0);
1657: }
1661: /*@
1662: TSComputeI2Jacobian - Evaluates the Jacobian of the DAE
1664: Collective on TS and Vec
1666: Input Parameters:
1667: + ts - the TS context
1668: . t - current timestep
1669: . U - state vector
1670: . V - time derivative of state vector
1671: . A - second time derivative of state vector
1672: . shiftV - shift to apply, see note below
1673: - shiftA - shift to apply, see note below
1675: Output Parameters:
1676: + J - Jacobian matrix
1677: - P - optional preconditioning matrix
1679: Notes:
1680: If F(t,U,V,A)=0 is the DAE, the required Jacobian is
1682: dF/dU + shiftV*dF/dV + shiftA*dF/dA
1684: Most users should not need to explicitly call this routine, as it
1685: is used internally within the nonlinear solvers.
1687: Level: developer
1689: .keywords: TS, compute, Jacobian, matrix
1691: .seealso: TSSetI2Jacobian()
1692: @*/
1693: PetscErrorCode TSComputeI2Jacobian(TS ts,PetscReal t,Vec U,Vec V,Vec A,PetscReal shiftV,PetscReal shiftA,Mat J,Mat P)
1694: {
1695: DM dm;
1696: TSI2Jacobian I2Jacobian;
1697: void *ctx;
1698: TSRHSJacobian rhsjacobian;
1709: TSGetDM(ts,&dm);
1710: DMTSGetI2Jacobian(dm,&I2Jacobian,&ctx);
1711: DMTSGetRHSJacobian(dm,&rhsjacobian,NULL);
1713: if (!I2Jacobian) {
1714: TSComputeIJacobian(ts,t,U,A,shiftA,J,P,PETSC_FALSE);
1715: return(0);
1716: }
1718: PetscLogEventBegin(TS_JacobianEval,ts,U,J,P);
1720: PetscStackPush("TS user implicit Jacobian");
1721: I2Jacobian(ts,t,U,V,A,shiftV,shiftA,J,P,ctx);
1722: PetscStackPop;
1724: if (rhsjacobian) {
1725: Mat Jrhs,Prhs; MatStructure axpy = DIFFERENT_NONZERO_PATTERN;
1726: TSGetRHSMats_Private(ts,&Jrhs,&Prhs);
1727: TSComputeRHSJacobian(ts,t,U,Jrhs,Prhs);
1728: MatAXPY(J,-1,Jrhs,axpy);
1729: if (P != J) {MatAXPY(P,-1,Prhs,axpy);}
1730: }
1732: PetscLogEventEnd(TS_JacobianEval,ts,U,J,P);
1733: return(0);
1734: }
1738: /*@
1739: TS2SetSolution - Sets the initial solution and time derivative vectors
1740: for use by the TS routines handling second order equations.
1742: Logically Collective on TS and Vec
1744: Input Parameters:
1745: + ts - the TS context obtained from TSCreate()
1746: . u - the solution vector
1747: - v - the time derivative vector
1749: Level: beginner
1751: .keywords: TS, timestep, set, solution, initial conditions
1752: @*/
1753: PetscErrorCode TS2SetSolution(TS ts,Vec u,Vec v)
1754: {
1761: TSSetSolution(ts,u);
1762: PetscObjectReference((PetscObject)v);
1763: VecDestroy(&ts->vec_dot);
1764: ts->vec_dot = v;
1765: return(0);
1766: }
1770: /*@
1771: TS2GetSolution - Returns the solution and time derivative at the present timestep
1772: for second order equations. It is valid to call this routine inside the function
1773: that you are evaluating in order to move to the new timestep. This vector not
1774: changed until the solution at the next timestep has been calculated.
1776: Not Collective, but Vec returned is parallel if TS is parallel
1778: Input Parameter:
1779: . ts - the TS context obtained from TSCreate()
1781: Output Parameter:
1782: + u - the vector containing the solution
1783: - v - the vector containing the time derivative
1785: Level: intermediate
1787: .seealso: TS2SetSolution(), TSGetTimeStep(), TSGetTime()
1789: .keywords: TS, timestep, get, solution
1790: @*/
1791: PetscErrorCode TS2GetSolution(TS ts,Vec *u,Vec *v)
1792: {
1797: if (u) *u = ts->vec_sol;
1798: if (v) *v = ts->vec_dot;
1799: return(0);
1800: }
1804: /*@C
1805: TSLoad - Loads a KSP that has been stored in binary with KSPView().
1807: Collective on PetscViewer
1809: Input Parameters:
1810: + newdm - the newly loaded TS, this needs to have been created with TSCreate() or
1811: some related function before a call to TSLoad().
1812: - viewer - binary file viewer, obtained from PetscViewerBinaryOpen()
1814: Level: intermediate
1816: Notes:
1817: The type is determined by the data in the file, any type set into the TS before this call is ignored.
1819: Notes for advanced users:
1820: Most users should not need to know the details of the binary storage
1821: format, since TSLoad() and TSView() completely hide these details.
1822: But for anyone who's interested, the standard binary matrix storage
1823: format is
1824: .vb
1825: has not yet been determined
1826: .ve
1828: .seealso: PetscViewerBinaryOpen(), TSView(), MatLoad(), VecLoad()
1829: @*/
1830: PetscErrorCode TSLoad(TS ts, PetscViewer viewer)
1831: {
1833: PetscBool isbinary;
1834: PetscInt classid;
1835: char type[256];
1836: DMTS sdm;
1837: DM dm;
1842: PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERBINARY,&isbinary);
1843: if (!isbinary) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,"Invalid viewer; open viewer with PetscViewerBinaryOpen()");
1845: PetscViewerBinaryRead(viewer,&classid,1,NULL,PETSC_INT);
1846: if (classid != TS_FILE_CLASSID) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_ARG_WRONG,"Not TS next in file");
1847: PetscViewerBinaryRead(viewer,type,256,NULL,PETSC_CHAR);
1848: TSSetType(ts, type);
1849: if (ts->ops->load) {
1850: (*ts->ops->load)(ts,viewer);
1851: }
1852: DMCreate(PetscObjectComm((PetscObject)ts),&dm);
1853: DMLoad(dm,viewer);
1854: TSSetDM(ts,dm);
1855: DMCreateGlobalVector(ts->dm,&ts->vec_sol);
1856: VecLoad(ts->vec_sol,viewer);
1857: DMGetDMTS(ts->dm,&sdm);
1858: DMTSLoad(sdm,viewer);
1859: return(0);
1860: }
1862: #include <petscdraw.h>
1863: #if defined(PETSC_HAVE_SAWS)
1864: #include <petscviewersaws.h>
1865: #endif
1868: /*@C
1869: TSView - Prints the TS data structure.
1871: Collective on TS
1873: Input Parameters:
1874: + ts - the TS context obtained from TSCreate()
1875: - viewer - visualization context
1877: Options Database Key:
1878: . -ts_view - calls TSView() at end of TSStep()
1880: Notes:
1881: The available visualization contexts include
1882: + PETSC_VIEWER_STDOUT_SELF - standard output (default)
1883: - PETSC_VIEWER_STDOUT_WORLD - synchronized standard
1884: output where only the first processor opens
1885: the file. All other processors send their
1886: data to the first processor to print.
1888: The user can open an alternative visualization context with
1889: PetscViewerASCIIOpen() - output to a specified file.
1891: Level: beginner
1893: .keywords: TS, timestep, view
1895: .seealso: PetscViewerASCIIOpen()
1896: @*/
1897: PetscErrorCode TSView(TS ts,PetscViewer viewer)
1898: {
1900: TSType type;
1901: PetscBool iascii,isstring,isundials,isbinary,isdraw;
1902: DMTS sdm;
1903: #if defined(PETSC_HAVE_SAWS)
1904: PetscBool issaws;
1905: #endif
1909: if (!viewer) {
1910: PetscViewerASCIIGetStdout(PetscObjectComm((PetscObject)ts),&viewer);
1911: }
1915: PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERASCII,&iascii);
1916: PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERSTRING,&isstring);
1917: PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERBINARY,&isbinary);
1918: PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERDRAW,&isdraw);
1919: #if defined(PETSC_HAVE_SAWS)
1920: PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERSAWS,&issaws);
1921: #endif
1922: if (iascii) {
1923: PetscObjectPrintClassNamePrefixType((PetscObject)ts,viewer);
1924: PetscViewerASCIIPrintf(viewer," maximum steps=%D\n",ts->max_steps);
1925: PetscViewerASCIIPrintf(viewer," maximum time=%g\n",(double)ts->max_time);
1926: if (ts->problem_type == TS_NONLINEAR) {
1927: PetscViewerASCIIPrintf(viewer," total number of nonlinear solver iterations=%D\n",ts->snes_its);
1928: PetscViewerASCIIPrintf(viewer," total number of nonlinear solve failures=%D\n",ts->num_snes_failures);
1929: }
1930: PetscViewerASCIIPrintf(viewer," total number of linear solver iterations=%D\n",ts->ksp_its);
1931: PetscViewerASCIIPrintf(viewer," total number of rejected steps=%D\n",ts->reject);
1932: DMGetDMTS(ts->dm,&sdm);
1933: DMTSView(sdm,viewer);
1934: if (ts->ops->view) {
1935: PetscViewerASCIIPushTab(viewer);
1936: (*ts->ops->view)(ts,viewer);
1937: PetscViewerASCIIPopTab(viewer);
1938: }
1939: } else if (isstring) {
1940: TSGetType(ts,&type);
1941: PetscViewerStringSPrintf(viewer," %-7.7s",type);
1942: } else if (isbinary) {
1943: PetscInt classid = TS_FILE_CLASSID;
1944: MPI_Comm comm;
1945: PetscMPIInt rank;
1946: char type[256];
1948: PetscObjectGetComm((PetscObject)ts,&comm);
1949: MPI_Comm_rank(comm,&rank);
1950: if (!rank) {
1951: PetscViewerBinaryWrite(viewer,&classid,1,PETSC_INT,PETSC_FALSE);
1952: PetscStrncpy(type,((PetscObject)ts)->type_name,256);
1953: PetscViewerBinaryWrite(viewer,type,256,PETSC_CHAR,PETSC_FALSE);
1954: }
1955: if (ts->ops->view) {
1956: (*ts->ops->view)(ts,viewer);
1957: }
1958: DMView(ts->dm,viewer);
1959: VecView(ts->vec_sol,viewer);
1960: DMGetDMTS(ts->dm,&sdm);
1961: DMTSView(sdm,viewer);
1962: } else if (isdraw) {
1963: PetscDraw draw;
1964: char str[36];
1965: PetscReal x,y,bottom,h;
1967: PetscViewerDrawGetDraw(viewer,0,&draw);
1968: PetscDrawGetCurrentPoint(draw,&x,&y);
1969: PetscStrcpy(str,"TS: ");
1970: PetscStrcat(str,((PetscObject)ts)->type_name);
1971: PetscDrawStringBoxed(draw,x,y,PETSC_DRAW_BLACK,PETSC_DRAW_BLACK,str,NULL,&h);
1972: bottom = y - h;
1973: PetscDrawPushCurrentPoint(draw,x,bottom);
1974: if (ts->ops->view) {
1975: (*ts->ops->view)(ts,viewer);
1976: }
1977: PetscDrawPopCurrentPoint(draw);
1978: #if defined(PETSC_HAVE_SAWS)
1979: } else if (issaws) {
1980: PetscMPIInt rank;
1981: const char *name;
1983: PetscObjectGetName((PetscObject)ts,&name);
1984: MPI_Comm_rank(PETSC_COMM_WORLD,&rank);
1985: if (!((PetscObject)ts)->amsmem && !rank) {
1986: char dir[1024];
1988: PetscObjectViewSAWs((PetscObject)ts,viewer);
1989: PetscSNPrintf(dir,1024,"/PETSc/Objects/%s/time_step",name);
1990: PetscStackCallSAWs(SAWs_Register,(dir,&ts->steps,1,SAWs_READ,SAWs_INT));
1991: PetscSNPrintf(dir,1024,"/PETSc/Objects/%s/time",name);
1992: PetscStackCallSAWs(SAWs_Register,(dir,&ts->ptime,1,SAWs_READ,SAWs_DOUBLE));
1993: }
1994: if (ts->ops->view) {
1995: (*ts->ops->view)(ts,viewer);
1996: }
1997: #endif
1998: }
2000: PetscViewerASCIIPushTab(viewer);
2001: PetscObjectTypeCompare((PetscObject)ts,TSSUNDIALS,&isundials);
2002: PetscViewerASCIIPopTab(viewer);
2003: return(0);
2004: }
2009: /*@
2010: TSSetApplicationContext - Sets an optional user-defined context for
2011: the timesteppers.
2013: Logically Collective on TS
2015: Input Parameters:
2016: + ts - the TS context obtained from TSCreate()
2017: - usrP - optional user context
2019: Fortran Notes: To use this from Fortran you must write a Fortran interface definition for this
2020: function that tells Fortran the Fortran derived data type that you are passing in as the ctx argument.
2022: Level: intermediate
2024: .keywords: TS, timestep, set, application, context
2026: .seealso: TSGetApplicationContext()
2027: @*/
2028: PetscErrorCode TSSetApplicationContext(TS ts,void *usrP)
2029: {
2032: ts->user = usrP;
2033: return(0);
2034: }
2038: /*@
2039: TSGetApplicationContext - Gets the user-defined context for the
2040: timestepper.
2042: Not Collective
2044: Input Parameter:
2045: . ts - the TS context obtained from TSCreate()
2047: Output Parameter:
2048: . usrP - user context
2050: Fortran Notes: To use this from Fortran you must write a Fortran interface definition for this
2051: function that tells Fortran the Fortran derived data type that you are passing in as the ctx argument.
2053: Level: intermediate
2055: .keywords: TS, timestep, get, application, context
2057: .seealso: TSSetApplicationContext()
2058: @*/
2059: PetscErrorCode TSGetApplicationContext(TS ts,void *usrP)
2060: {
2063: *(void**)usrP = ts->user;
2064: return(0);
2065: }
2069: /*@
2070: TSGetTimeStepNumber - Gets the number of time steps completed.
2072: Not Collective
2074: Input Parameter:
2075: . ts - the TS context obtained from TSCreate()
2077: Output Parameter:
2078: . iter - number of steps completed so far
2080: Level: intermediate
2082: .keywords: TS, timestep, get, iteration, number
2083: .seealso: TSGetTime(), TSGetTimeStep(), TSSetPreStep(), TSSetPreStage(), TSSetPostStage(), TSSetPostStep()
2084: @*/
2085: PetscErrorCode TSGetTimeStepNumber(TS ts,PetscInt *iter)
2086: {
2090: *iter = ts->steps;
2091: return(0);
2092: }
2096: /*@
2097: TSSetInitialTimeStep - Sets the initial timestep to be used,
2098: as well as the initial time.
2100: Logically Collective on TS
2102: Input Parameters:
2103: + ts - the TS context obtained from TSCreate()
2104: . initial_time - the initial time
2105: - time_step - the size of the timestep
2107: Level: intermediate
2109: .seealso: TSSetTimeStep(), TSGetTimeStep()
2111: .keywords: TS, set, initial, timestep
2112: @*/
2113: PetscErrorCode TSSetInitialTimeStep(TS ts,PetscReal initial_time,PetscReal time_step)
2114: {
2119: TSSetTimeStep(ts,time_step);
2120: TSSetTime(ts,initial_time);
2121: return(0);
2122: }
2126: /*@
2127: TSSetTimeStep - Allows one to reset the timestep at any time,
2128: useful for simple pseudo-timestepping codes.
2130: Logically Collective on TS
2132: Input Parameters:
2133: + ts - the TS context obtained from TSCreate()
2134: - time_step - the size of the timestep
2136: Level: intermediate
2138: .seealso: TSSetInitialTimeStep(), TSGetTimeStep()
2140: .keywords: TS, set, timestep
2141: @*/
2142: PetscErrorCode TSSetTimeStep(TS ts,PetscReal time_step)
2143: {
2147: ts->time_step = time_step;
2148: return(0);
2149: }
2153: /*@
2154: TSSetExactFinalTime - Determines whether to adapt the final time step to
2155: match the exact final time, interpolate solution to the exact final time,
2156: or just return at the final time TS computed.
2158: Logically Collective on TS
2160: Input Parameter:
2161: + ts - the time-step context
2162: - eftopt - exact final time option
2164: $ TS_EXACTFINALTIME_STEPOVER - Don't do anything if final time is exceeded
2165: $ TS_EXACTFINALTIME_INTERPOLATE - Interpolate back to final time
2166: $ TS_EXACTFINALTIME_MATCHSTEP - Adapt final time step to match the final time
2168: Options Database:
2169: . -ts_exact_final_time <stepover,interpolate,matchstep> - select the final step at runtime
2171: Warning: If you use the option TS_EXACTFINALTIME_STEPOVER the solution may be at a very different time
2172: then the final time you selected.
2174: Level: beginner
2176: .seealso: TSExactFinalTimeOption
2177: @*/
2178: PetscErrorCode TSSetExactFinalTime(TS ts,TSExactFinalTimeOption eftopt)
2179: {
2183: ts->exact_final_time = eftopt;
2184: return(0);
2185: }
2189: /*@
2190: TSGetTimeStep - Gets the current timestep size.
2192: Not Collective
2194: Input Parameter:
2195: . ts - the TS context obtained from TSCreate()
2197: Output Parameter:
2198: . dt - the current timestep size
2200: Level: intermediate
2202: .seealso: TSSetInitialTimeStep(), TSGetTimeStep()
2204: .keywords: TS, get, timestep
2205: @*/
2206: PetscErrorCode TSGetTimeStep(TS ts,PetscReal *dt)
2207: {
2211: *dt = ts->time_step;
2212: return(0);
2213: }
2217: /*@
2218: TSGetSolution - Returns the solution at the present timestep. It
2219: is valid to call this routine inside the function that you are evaluating
2220: in order to move to the new timestep. This vector not changed until
2221: the solution at the next timestep has been calculated.
2223: Not Collective, but Vec returned is parallel if TS is parallel
2225: Input Parameter:
2226: . ts - the TS context obtained from TSCreate()
2228: Output Parameter:
2229: . v - the vector containing the solution
2231: Note: If you used TSSetExactFinalTime(ts,TS_EXACTFINALTIME_MATCHSTEP); this does not return the solution at the requested
2232: final time. It returns the solution at the next timestep.
2234: Level: intermediate
2236: .seealso: TSGetTimeStep(), TSGetTime(), TSGetSolveTime()
2238: .keywords: TS, timestep, get, solution
2239: @*/
2240: PetscErrorCode TSGetSolution(TS ts,Vec *v)
2241: {
2245: *v = ts->vec_sol;
2246: return(0);
2247: }
2251: /*@
2252: TSGetCostGradients - Returns the gradients from the TSAdjointSolve()
2254: Not Collective, but Vec returned is parallel if TS is parallel
2256: Input Parameter:
2257: . ts - the TS context obtained from TSCreate()
2259: Output Parameter:
2260: + lambda - vectors containing the gradients of the cost functions with respect to the ODE/DAE solution variables
2261: - mu - vectors containing the gradients of the cost functions with respect to the problem parameters
2263: Level: intermediate
2265: .seealso: TSGetTimeStep()
2267: .keywords: TS, timestep, get, sensitivity
2268: @*/
2269: PetscErrorCode TSGetCostGradients(TS ts,PetscInt *numcost,Vec **lambda,Vec **mu)
2270: {
2273: if (numcost) *numcost = ts->numcost;
2274: if (lambda) *lambda = ts->vecs_sensi;
2275: if (mu) *mu = ts->vecs_sensip;
2276: return(0);
2277: }
2279: /* ----- Routines to initialize and destroy a timestepper ---- */
2282: /*@
2283: TSSetProblemType - Sets the type of problem to be solved.
2285: Not collective
2287: Input Parameters:
2288: + ts - The TS
2289: - type - One of TS_LINEAR, TS_NONLINEAR where these types refer to problems of the forms
2290: .vb
2291: U_t - A U = 0 (linear)
2292: U_t - A(t) U = 0 (linear)
2293: F(t,U,U_t) = 0 (nonlinear)
2294: .ve
2296: Level: beginner
2298: .keywords: TS, problem type
2299: .seealso: TSSetUp(), TSProblemType, TS
2300: @*/
2301: PetscErrorCode TSSetProblemType(TS ts, TSProblemType type)
2302: {
2307: ts->problem_type = type;
2308: if (type == TS_LINEAR) {
2309: SNES snes;
2310: TSGetSNES(ts,&snes);
2311: SNESSetType(snes,SNESKSPONLY);
2312: }
2313: return(0);
2314: }
2318: /*@C
2319: TSGetProblemType - Gets the type of problem to be solved.
2321: Not collective
2323: Input Parameter:
2324: . ts - The TS
2326: Output Parameter:
2327: . type - One of TS_LINEAR, TS_NONLINEAR where these types refer to problems of the forms
2328: .vb
2329: M U_t = A U
2330: M(t) U_t = A(t) U
2331: F(t,U,U_t)
2332: .ve
2334: Level: beginner
2336: .keywords: TS, problem type
2337: .seealso: TSSetUp(), TSProblemType, TS
2338: @*/
2339: PetscErrorCode TSGetProblemType(TS ts, TSProblemType *type)
2340: {
2344: *type = ts->problem_type;
2345: return(0);
2346: }
2350: /*@
2351: TSSetUp - Sets up the internal data structures for the later use
2352: of a timestepper.
2354: Collective on TS
2356: Input Parameter:
2357: . ts - the TS context obtained from TSCreate()
2359: Notes:
2360: For basic use of the TS solvers the user need not explicitly call
2361: TSSetUp(), since these actions will automatically occur during
2362: the call to TSStep(). However, if one wishes to control this
2363: phase separately, TSSetUp() should be called after TSCreate()
2364: and optional routines of the form TSSetXXX(), but before TSStep().
2366: Level: advanced
2368: .keywords: TS, timestep, setup
2370: .seealso: TSCreate(), TSStep(), TSDestroy()
2371: @*/
2372: PetscErrorCode TSSetUp(TS ts)
2373: {
2375: DM dm;
2376: PetscErrorCode (*func)(SNES,Vec,Vec,void*);
2377: PetscErrorCode (*jac)(SNES,Vec,Mat,Mat,void*);
2378: TSIFunction ifun;
2379: TSIJacobian ijac;
2380: TSI2Jacobian i2jac;
2381: TSRHSJacobian rhsjac;
2385: if (ts->setupcalled) return(0);
2387: ts->total_steps = 0;
2388: if (!((PetscObject)ts)->type_name) {
2389: TSGetIFunction(ts,NULL,&ifun,NULL);
2390: TSSetType(ts,ifun ? TSBEULER : TSEULER);
2391: }
2393: if (!ts->vec_sol) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Must call TSSetSolution() first");
2395: if (ts->rhsjacobian.reuse) {
2396: Mat Amat,Pmat;
2397: SNES snes;
2398: TSGetSNES(ts,&snes);
2399: SNESGetJacobian(snes,&Amat,&Pmat,NULL,NULL);
2400: /* Matching matrices implies that an IJacobian is NOT set, because if it had been set, the IJacobian's matrix would
2401: * have displaced the RHS matrix */
2402: if (Amat == ts->Arhs) {
2403: MatDuplicate(ts->Arhs,MAT_DO_NOT_COPY_VALUES,&Amat);
2404: SNESSetJacobian(snes,Amat,NULL,NULL,NULL);
2405: MatDestroy(&Amat);
2406: }
2407: if (Pmat == ts->Brhs) {
2408: MatDuplicate(ts->Brhs,MAT_DO_NOT_COPY_VALUES,&Pmat);
2409: SNESSetJacobian(snes,NULL,Pmat,NULL,NULL);
2410: MatDestroy(&Pmat);
2411: }
2412: }
2413: if (ts->ops->setup) {
2414: (*ts->ops->setup)(ts);
2415: }
2417: /* In the case where we've set a DMTSFunction or what have you, we need the default SNESFunction
2418: to be set right but can't do it elsewhere due to the overreliance on ctx=ts.
2419: */
2420: TSGetDM(ts,&dm);
2421: DMSNESGetFunction(dm,&func,NULL);
2422: if (!func) {
2423: DMSNESSetFunction(dm,SNESTSFormFunction,ts);
2424: }
2425: /* If the SNES doesn't have a jacobian set and the TS has an ijacobian or rhsjacobian set, set the SNES to use it.
2426: Otherwise, the SNES will use coloring internally to form the Jacobian.
2427: */
2428: DMSNESGetJacobian(dm,&jac,NULL);
2429: DMTSGetIJacobian(dm,&ijac,NULL);
2430: DMTSGetI2Jacobian(dm,&i2jac,NULL);
2431: DMTSGetRHSJacobian(dm,&rhsjac,NULL);
2432: if (!jac && (ijac || i2jac || rhsjac)) {
2433: DMSNESSetJacobian(dm,SNESTSFormJacobian,ts);
2434: }
2435: ts->setupcalled = PETSC_TRUE;
2436: return(0);
2437: }
2441: /*@
2442: TSAdjointSetUp - Sets up the internal data structures for the later use
2443: of an adjoint solver
2445: Collective on TS
2447: Input Parameter:
2448: . ts - the TS context obtained from TSCreate()
2450: Level: advanced
2452: .keywords: TS, timestep, setup
2454: .seealso: TSCreate(), TSAdjointStep(), TSSetCostGradients()
2455: @*/
2456: PetscErrorCode TSAdjointSetUp(TS ts)
2457: {
2462: if (ts->adjointsetupcalled) return(0);
2463: if (!ts->vecs_sensi) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Must call TSSetCostGradients() first");
2465: if (ts->vec_costintegral) { /* if there is integral in the cost function*/
2466: VecDuplicateVecs(ts->vecs_sensi[0],ts->numcost,&ts->vecs_drdy);
2467: if (ts->vecs_sensip){
2468: VecDuplicateVecs(ts->vecs_sensip[0],ts->numcost,&ts->vecs_drdp);
2469: }
2470: }
2472: if (ts->ops->adjointsetup) {
2473: (*ts->ops->adjointsetup)(ts);
2474: }
2475: ts->adjointsetupcalled = PETSC_TRUE;
2476: return(0);
2477: }
2481: /*@
2482: TSReset - Resets a TS context and removes any allocated Vecs and Mats.
2484: Collective on TS
2486: Input Parameter:
2487: . ts - the TS context obtained from TSCreate()
2489: Level: beginner
2491: .keywords: TS, timestep, reset
2493: .seealso: TSCreate(), TSSetup(), TSDestroy()
2494: @*/
2495: PetscErrorCode TSReset(TS ts)
2496: {
2502: if (ts->ops->reset) {
2503: (*ts->ops->reset)(ts);
2504: }
2505: if (ts->snes) {SNESReset(ts->snes);}
2506: if (ts->adapt) {TSAdaptReset(ts->adapt);}
2508: MatDestroy(&ts->Arhs);
2509: MatDestroy(&ts->Brhs);
2510: VecDestroy(&ts->Frhs);
2511: VecDestroy(&ts->vec_sol);
2512: VecDestroy(&ts->vec_dot);
2513: VecDestroy(&ts->vatol);
2514: VecDestroy(&ts->vrtol);
2515: VecDestroyVecs(ts->nwork,&ts->work);
2517: if (ts->vec_costintegral) {
2518: VecDestroyVecs(ts->numcost,&ts->vecs_drdy);
2519: if (ts->vecs_drdp){
2520: VecDestroyVecs(ts->numcost,&ts->vecs_drdp);
2521: }
2522: }
2523: ts->vecs_sensi = NULL;
2524: ts->vecs_sensip = NULL;
2525: MatDestroy(&ts->Jacp);
2526: VecDestroy(&ts->vec_costintegral);
2527: VecDestroy(&ts->vec_costintegrand);
2528: ts->setupcalled = PETSC_FALSE;
2529: return(0);
2530: }
2534: /*@
2535: TSDestroy - Destroys the timestepper context that was created
2536: with TSCreate().
2538: Collective on TS
2540: Input Parameter:
2541: . ts - the TS context obtained from TSCreate()
2543: Level: beginner
2545: .keywords: TS, timestepper, destroy
2547: .seealso: TSCreate(), TSSetUp(), TSSolve()
2548: @*/
2549: PetscErrorCode TSDestroy(TS *ts)
2550: {
2554: if (!*ts) return(0);
2556: if (--((PetscObject)(*ts))->refct > 0) {*ts = 0; return(0);}
2558: TSReset((*ts));
2560: /* if memory was published with SAWs then destroy it */
2561: PetscObjectSAWsViewOff((PetscObject)*ts);
2562: if ((*ts)->ops->destroy) {(*(*ts)->ops->destroy)((*ts));}
2564: TSTrajectoryDestroy(&(*ts)->trajectory);
2566: TSAdaptDestroy(&(*ts)->adapt);
2567: TSEventDestroy(&(*ts)->event);
2569: SNESDestroy(&(*ts)->snes);
2570: DMDestroy(&(*ts)->dm);
2571: TSMonitorCancel((*ts));
2572: TSAdjointMonitorCancel((*ts));
2574: PetscHeaderDestroy(ts);
2575: return(0);
2576: }
2580: /*@
2581: TSGetSNES - Returns the SNES (nonlinear solver) associated with
2582: a TS (timestepper) context. Valid only for nonlinear problems.
2584: Not Collective, but SNES is parallel if TS is parallel
2586: Input Parameter:
2587: . ts - the TS context obtained from TSCreate()
2589: Output Parameter:
2590: . snes - the nonlinear solver context
2592: Notes:
2593: The user can then directly manipulate the SNES context to set various
2594: options, etc. Likewise, the user can then extract and manipulate the
2595: KSP, KSP, and PC contexts as well.
2597: TSGetSNES() does not work for integrators that do not use SNES; in
2598: this case TSGetSNES() returns NULL in snes.
2600: Level: beginner
2602: .keywords: timestep, get, SNES
2603: @*/
2604: PetscErrorCode TSGetSNES(TS ts,SNES *snes)
2605: {
2611: if (!ts->snes) {
2612: SNESCreate(PetscObjectComm((PetscObject)ts),&ts->snes);
2613: SNESSetFunction(ts->snes,NULL,SNESTSFormFunction,ts);
2614: PetscLogObjectParent((PetscObject)ts,(PetscObject)ts->snes);
2615: PetscObjectIncrementTabLevel((PetscObject)ts->snes,(PetscObject)ts,1);
2616: if (ts->dm) {SNESSetDM(ts->snes,ts->dm);}
2617: if (ts->problem_type == TS_LINEAR) {
2618: SNESSetType(ts->snes,SNESKSPONLY);
2619: }
2620: }
2621: *snes = ts->snes;
2622: return(0);
2623: }
2627: /*@
2628: TSSetSNES - Set the SNES (nonlinear solver) to be used by the timestepping context
2630: Collective
2632: Input Parameter:
2633: + ts - the TS context obtained from TSCreate()
2634: - snes - the nonlinear solver context
2636: Notes:
2637: Most users should have the TS created by calling TSGetSNES()
2639: Level: developer
2641: .keywords: timestep, set, SNES
2642: @*/
2643: PetscErrorCode TSSetSNES(TS ts,SNES snes)
2644: {
2646: PetscErrorCode (*func)(SNES,Vec,Mat,Mat,void*);
2651: PetscObjectReference((PetscObject)snes);
2652: SNESDestroy(&ts->snes);
2654: ts->snes = snes;
2656: SNESSetFunction(ts->snes,NULL,SNESTSFormFunction,ts);
2657: SNESGetJacobian(ts->snes,NULL,NULL,&func,NULL);
2658: if (func == SNESTSFormJacobian) {
2659: SNESSetJacobian(ts->snes,NULL,NULL,SNESTSFormJacobian,ts);
2660: }
2661: return(0);
2662: }
2666: /*@
2667: TSGetKSP - Returns the KSP (linear solver) associated with
2668: a TS (timestepper) context.
2670: Not Collective, but KSP is parallel if TS is parallel
2672: Input Parameter:
2673: . ts - the TS context obtained from TSCreate()
2675: Output Parameter:
2676: . ksp - the nonlinear solver context
2678: Notes:
2679: The user can then directly manipulate the KSP context to set various
2680: options, etc. Likewise, the user can then extract and manipulate the
2681: KSP and PC contexts as well.
2683: TSGetKSP() does not work for integrators that do not use KSP;
2684: in this case TSGetKSP() returns NULL in ksp.
2686: Level: beginner
2688: .keywords: timestep, get, KSP
2689: @*/
2690: PetscErrorCode TSGetKSP(TS ts,KSP *ksp)
2691: {
2693: SNES snes;
2698: if (!((PetscObject)ts)->type_name) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_NULL,"KSP is not created yet. Call TSSetType() first");
2699: if (ts->problem_type != TS_LINEAR) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,"Linear only; use TSGetSNES()");
2700: TSGetSNES(ts,&snes);
2701: SNESGetKSP(snes,ksp);
2702: return(0);
2703: }
2705: /* ----------- Routines to set solver parameters ---------- */
2709: /*@
2710: TSGetDuration - Gets the maximum number of timesteps to use and
2711: maximum time for iteration.
2713: Not Collective
2715: Input Parameters:
2716: + ts - the TS context obtained from TSCreate()
2717: . maxsteps - maximum number of iterations to use, or NULL
2718: - maxtime - final time to iterate to, or NULL
2720: Level: intermediate
2722: .keywords: TS, timestep, get, maximum, iterations, time
2723: @*/
2724: PetscErrorCode TSGetDuration(TS ts, PetscInt *maxsteps, PetscReal *maxtime)
2725: {
2728: if (maxsteps) {
2730: *maxsteps = ts->max_steps;
2731: }
2732: if (maxtime) {
2734: *maxtime = ts->max_time;
2735: }
2736: return(0);
2737: }
2741: /*@
2742: TSSetDuration - Sets the maximum number of timesteps to use and
2743: maximum time for iteration.
2745: Logically Collective on TS
2747: Input Parameters:
2748: + ts - the TS context obtained from TSCreate()
2749: . maxsteps - maximum number of iterations to use
2750: - maxtime - final time to iterate to
2752: Options Database Keys:
2753: . -ts_max_steps <maxsteps> - Sets maxsteps
2754: . -ts_final_time <maxtime> - Sets maxtime
2756: Notes:
2757: The default maximum number of iterations is 5000. Default time is 5.0
2759: Level: intermediate
2761: .keywords: TS, timestep, set, maximum, iterations
2763: .seealso: TSSetExactFinalTime()
2764: @*/
2765: PetscErrorCode TSSetDuration(TS ts,PetscInt maxsteps,PetscReal maxtime)
2766: {
2771: if (maxsteps >= 0) ts->max_steps = maxsteps;
2772: if (maxtime != PETSC_DEFAULT) ts->max_time = maxtime;
2773: return(0);
2774: }
2778: /*@
2779: TSSetSolution - Sets the initial solution vector
2780: for use by the TS routines.
2782: Logically Collective on TS and Vec
2784: Input Parameters:
2785: + ts - the TS context obtained from TSCreate()
2786: - u - the solution vector
2788: Level: beginner
2790: .keywords: TS, timestep, set, solution, initial conditions
2791: @*/
2792: PetscErrorCode TSSetSolution(TS ts,Vec u)
2793: {
2795: DM dm;
2800: PetscObjectReference((PetscObject)u);
2801: VecDestroy(&ts->vec_sol);
2802: ts->vec_sol = u;
2804: TSGetDM(ts,&dm);
2805: DMShellSetGlobalVector(dm,u);
2806: return(0);
2807: }
2811: /*@
2812: TSAdjointSetSteps - Sets the number of steps the adjoint solver should take backward in time
2814: Logically Collective on TS
2816: Input Parameters:
2817: + ts - the TS context obtained from TSCreate()
2818: . steps - number of steps to use
2820: Level: intermediate
2822: Notes: Normally one does not call this and TSAdjointSolve() integrates back to the original timestep. One can call this
2823: so as to integrate back to less than the original timestep
2825: .keywords: TS, timestep, set, maximum, iterations
2827: .seealso: TSSetExactFinalTime()
2828: @*/
2829: PetscErrorCode TSAdjointSetSteps(TS ts,PetscInt steps)
2830: {
2834: if (steps < 0) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_ARG_OUTOFRANGE,"Cannot step back a negative number of steps");
2835: if (steps > ts->total_steps) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_ARG_OUTOFRANGE,"Cannot step back more than the total number of forward steps");
2836: ts->adjoint_max_steps = steps;
2837: return(0);
2838: }
2842: /*@
2843: TSSetCostGradients - Sets the initial value of the gradients of the cost function w.r.t. initial conditions and w.r.t. the problem parameters
2844: for use by the TSAdjoint routines.
2846: Logically Collective on TS and Vec
2848: Input Parameters:
2849: + ts - the TS context obtained from TSCreate()
2850: . 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
2851: - mu - gradients with respect to the parameters, the number of entries in these vectors is the same as the number of parameters
2853: Level: beginner
2855: Notes: the entries in these vectors must be correctly initialized with the values lamda_i = df/dy|finaltime mu_i = df/dp|finaltime
2857: .keywords: TS, timestep, set, sensitivity, initial conditions
2858: @*/
2859: PetscErrorCode TSSetCostGradients(TS ts,PetscInt numcost,Vec *lambda,Vec *mu)
2860: {
2864: ts->vecs_sensi = lambda;
2865: ts->vecs_sensip = mu;
2866: 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");
2867: ts->numcost = numcost;
2868: return(0);
2869: }
2873: /*@C
2874: 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.
2876: Logically Collective on TS
2878: Input Parameters:
2879: + ts - The TS context obtained from TSCreate()
2880: - func - The function
2882: Calling sequence of func:
2883: $ func (TS ts,PetscReal t,Vec y,Mat A,void *ctx);
2884: + t - current timestep
2885: . y - input vector (current ODE solution)
2886: . A - output matrix
2887: - ctx - [optional] user-defined function context
2889: Level: intermediate
2891: 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
2893: .keywords: TS, sensitivity
2894: .seealso:
2895: @*/
2896: PetscErrorCode TSAdjointSetRHSJacobian(TS ts,Mat Amat,PetscErrorCode (*func)(TS,PetscReal,Vec,Mat,void*),void *ctx)
2897: {
2904: ts->rhsjacobianp = func;
2905: ts->rhsjacobianpctx = ctx;
2906: if(Amat) {
2907: PetscObjectReference((PetscObject)Amat);
2908: MatDestroy(&ts->Jacp);
2909: ts->Jacp = Amat;
2910: }
2911: return(0);
2912: }
2916: /*@C
2917: TSAdjointComputeRHSJacobian - Runs the user-defined Jacobian function.
2919: Collective on TS
2921: Input Parameters:
2922: . ts - The TS context obtained from TSCreate()
2924: Level: developer
2926: .keywords: TS, sensitivity
2927: .seealso: TSAdjointSetRHSJacobian()
2928: @*/
2929: PetscErrorCode TSAdjointComputeRHSJacobian(TS ts,PetscReal t,Vec X,Mat Amat)
2930: {
2938: PetscStackPush("TS user JacobianP function for sensitivity analysis");
2939: (*ts->rhsjacobianp)(ts,t,X,Amat,ts->rhsjacobianpctx);
2940: PetscStackPop;
2941: return(0);
2942: }
2946: /*@C
2947: TSSetCostIntegrand - Sets the routine for evaluating the integral term in one or more cost functions
2949: Logically Collective on TS
2951: Input Parameters:
2952: + ts - the TS context obtained from TSCreate()
2953: . numcost - number of gradients to be computed, this is the number of cost functions
2954: . rf - routine for evaluating the integrand function
2955: . drdyf - function that computes the gradients of the r's with respect to y,NULL if not a function y
2956: . drdpf - function that computes the gradients of the r's with respect to p, NULL if not a function of p
2957: . fwd � flag indicating whether to evaluate cost integral in the forward run or the adjoint run
2958: - ctx - [optional] user-defined context for private data for the function evaluation routine (may be NULL)
2960: Calling sequence of rf:
2961: $ rf(TS ts,PetscReal t,Vec y,Vec f[],void *ctx);
2963: + t - current timestep
2964: . y - input vector
2965: . f - function result; one vector entry for each cost function
2966: - ctx - [optional] user-defined function context
2968: Calling sequence of drdyf:
2969: $ PetscErroCode drdyf(TS ts,PetscReal t,Vec y,Vec *drdy,void *ctx);
2971: Calling sequence of drdpf:
2972: $ PetscErroCode drdpf(TS ts,PetscReal t,Vec y,Vec *drdp,void *ctx);
2974: Level: intermediate
2976: Notes: For optimization there is generally a single cost function, numcost = 1. For sensitivities there may be multiple cost functions
2978: .keywords: TS, sensitivity analysis, timestep, set, quadrature, function
2980: .seealso: TSAdjointSetRHSJacobian(),TSGetCostGradients(), TSSetCostGradients()
2981: @*/
2982: PetscErrorCode TSSetCostIntegrand(TS ts,PetscInt numcost,PetscErrorCode (*rf)(TS,PetscReal,Vec,Vec,void*),
2983: PetscErrorCode (*drdyf)(TS,PetscReal,Vec,Vec*,void*),
2984: PetscErrorCode (*drdpf)(TS,PetscReal,Vec,Vec*,void*),
2985: PetscBool fwd,void *ctx)
2986: {
2991: 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()");
2992: if (!ts->numcost) ts->numcost=numcost;
2994: ts->costintegralfwd = fwd; /* Evaluate the cost integral in forward run if fwd is true */
2995: VecCreateSeq(PETSC_COMM_SELF,numcost,&ts->vec_costintegral);
2996: VecDuplicate(ts->vec_costintegral,&ts->vec_costintegrand);
2997: ts->costintegrand = rf;
2998: ts->costintegrandctx = ctx;
2999: ts->drdyfunction = drdyf;
3000: ts->drdpfunction = drdpf;
3001: return(0);
3002: }
3006: /*@
3007: TSGetCostIntegral - Returns the values of the integral term in the cost functions.
3008: It is valid to call the routine after a backward run.
3010: Not Collective
3012: Input Parameter:
3013: . ts - the TS context obtained from TSCreate()
3015: Output Parameter:
3016: . v - the vector containing the integrals for each cost function
3018: Level: intermediate
3020: .seealso: TSSetCostIntegrand()
3022: .keywords: TS, sensitivity analysis
3023: @*/
3024: PetscErrorCode TSGetCostIntegral(TS ts,Vec *v)
3025: {
3029: *v = ts->vec_costintegral;
3030: return(0);
3031: }
3035: /*@
3036: TSAdjointComputeCostIntegrand - Evaluates the integral function in the cost functions.
3038: Input Parameters:
3039: + ts - the TS context
3040: . t - current time
3041: - y - state vector, i.e. current solution
3043: Output Parameter:
3044: . q - vector of size numcost to hold the outputs
3046: Note:
3047: Most users should not need to explicitly call this routine, as it
3048: is used internally within the sensitivity analysis context.
3050: Level: developer
3052: .keywords: TS, compute
3054: .seealso: TSSetCostIntegrand()
3055: @*/
3056: PetscErrorCode TSAdjointComputeCostIntegrand(TS ts,PetscReal t,Vec y,Vec q)
3057: {
3065: PetscLogEventBegin(TS_FunctionEval,ts,y,q,0);
3066: if (ts->costintegrand) {
3067: PetscStackPush("TS user integrand in the cost function");
3068: (*ts->costintegrand)(ts,t,y,q,ts->costintegrandctx);
3069: PetscStackPop;
3070: } else {
3071: VecZeroEntries(q);
3072: }
3074: PetscLogEventEnd(TS_FunctionEval,ts,y,q,0);
3075: return(0);
3076: }
3080: /*@
3081: TSAdjointComputeDRDYFunction - Runs the user-defined DRDY function.
3083: Collective on TS
3085: Input Parameters:
3086: . ts - The TS context obtained from TSCreate()
3088: Notes:
3089: TSAdjointComputeDRDYFunction() is typically used for sensitivity implementation,
3090: so most users would not generally call this routine themselves.
3092: Level: developer
3094: .keywords: TS, sensitivity
3095: .seealso: TSAdjointComputeDRDYFunction()
3096: @*/
3097: PetscErrorCode TSAdjointComputeDRDYFunction(TS ts,PetscReal t,Vec y,Vec *drdy)
3098: {
3105: PetscStackPush("TS user DRDY function for sensitivity analysis");
3106: (*ts->drdyfunction)(ts,t,y,drdy,ts->costintegrandctx);
3107: PetscStackPop;
3108: return(0);
3109: }
3113: /*@
3114: TSAdjointComputeDRDPFunction - Runs the user-defined DRDP function.
3116: Collective on TS
3118: Input Parameters:
3119: . ts - The TS context obtained from TSCreate()
3121: Notes:
3122: TSDRDPFunction() is typically used for sensitivity implementation,
3123: so most users would not generally call this routine themselves.
3125: Level: developer
3127: .keywords: TS, sensitivity
3128: .seealso: TSAdjointSetDRDPFunction()
3129: @*/
3130: PetscErrorCode TSAdjointComputeDRDPFunction(TS ts,PetscReal t,Vec y,Vec *drdp)
3131: {
3138: PetscStackPush("TS user DRDP function for sensitivity analysis");
3139: (*ts->drdpfunction)(ts,t,y,drdp,ts->costintegrandctx);
3140: PetscStackPop;
3141: return(0);
3142: }
3146: /*@C
3147: TSSetPreStep - Sets the general-purpose function
3148: called once at the beginning of each time step.
3150: Logically Collective on TS
3152: Input Parameters:
3153: + ts - The TS context obtained from TSCreate()
3154: - func - The function
3156: Calling sequence of func:
3157: . func (TS ts);
3159: Level: intermediate
3161: .keywords: TS, timestep
3162: .seealso: TSSetPreStage(), TSSetPostStage(), TSSetPostStep(), TSStep()
3163: @*/
3164: PetscErrorCode TSSetPreStep(TS ts, PetscErrorCode (*func)(TS))
3165: {
3168: ts->prestep = func;
3169: return(0);
3170: }
3174: /*@
3175: TSPreStep - Runs the user-defined pre-step function.
3177: Collective on TS
3179: Input Parameters:
3180: . ts - The TS context obtained from TSCreate()
3182: Notes:
3183: TSPreStep() is typically used within time stepping implementations,
3184: so most users would not generally call this routine themselves.
3186: Level: developer
3188: .keywords: TS, timestep
3189: .seealso: TSSetPreStep(), TSPreStage(), TSPostStage(), TSPostStep()
3190: @*/
3191: PetscErrorCode TSPreStep(TS ts)
3192: {
3197: if (ts->prestep) {
3198: Vec U;
3199: PetscObjectState sprev,spost;
3201: TSGetSolution(ts,&U);
3202: PetscObjectStateGet((PetscObject)U,&sprev);
3203: PetscStackCallStandard((*ts->prestep),(ts));
3204: PetscObjectStateGet((PetscObject)U,&spost);
3205: if (sprev != spost) ts->steprestart = PETSC_TRUE;
3206: }
3207: return(0);
3208: }
3212: /*@C
3213: TSSetPreStage - Sets the general-purpose function
3214: called once at the beginning of each stage.
3216: Logically Collective on TS
3218: Input Parameters:
3219: + ts - The TS context obtained from TSCreate()
3220: - func - The function
3222: Calling sequence of func:
3223: . PetscErrorCode func(TS ts, PetscReal stagetime);
3225: Level: intermediate
3227: Note:
3228: There may be several stages per time step. If the solve for a given stage fails, the step may be rejected and retried.
3229: The time step number being computed can be queried using TSGetTimeStepNumber() and the total size of the step being
3230: attempted can be obtained using TSGetTimeStep(). The time at the start of the step is available via TSGetTime().
3232: .keywords: TS, timestep
3233: .seealso: TSSetPostStage(), TSSetPreStep(), TSSetPostStep(), TSGetApplicationContext()
3234: @*/
3235: PetscErrorCode TSSetPreStage(TS ts, PetscErrorCode (*func)(TS,PetscReal))
3236: {
3239: ts->prestage = func;
3240: return(0);
3241: }
3245: /*@C
3246: TSSetPostStage - Sets the general-purpose function
3247: called once at the end of each stage.
3249: Logically Collective on TS
3251: Input Parameters:
3252: + ts - The TS context obtained from TSCreate()
3253: - func - The function
3255: Calling sequence of func:
3256: . PetscErrorCode func(TS ts, PetscReal stagetime, PetscInt stageindex, Vec* Y);
3258: Level: intermediate
3260: Note:
3261: There may be several stages per time step. If the solve for a given stage fails, the step may be rejected and retried.
3262: The time step number being computed can be queried using TSGetTimeStepNumber() and the total size of the step being
3263: attempted can be obtained using TSGetTimeStep(). The time at the start of the step is available via TSGetTime().
3265: .keywords: TS, timestep
3266: .seealso: TSSetPreStage(), TSSetPreStep(), TSSetPostStep(), TSGetApplicationContext()
3267: @*/
3268: PetscErrorCode TSSetPostStage(TS ts, PetscErrorCode (*func)(TS,PetscReal,PetscInt,Vec*))
3269: {
3272: ts->poststage = func;
3273: return(0);
3274: }
3278: /*@
3279: TSPreStage - Runs the user-defined pre-stage function set using TSSetPreStage()
3281: Collective on TS
3283: Input Parameters:
3284: . ts - The TS context obtained from TSCreate()
3285: stagetime - The absolute time of the current stage
3287: Notes:
3288: TSPreStage() is typically used within time stepping implementations,
3289: most users would not generally call this routine themselves.
3291: Level: developer
3293: .keywords: TS, timestep
3294: .seealso: TSPostStage(), TSSetPreStep(), TSPreStep(), TSPostStep()
3295: @*/
3296: PetscErrorCode TSPreStage(TS ts, PetscReal stagetime)
3297: {
3302: if (ts->prestage) {
3303: PetscStackCallStandard((*ts->prestage),(ts,stagetime));
3304: }
3305: return(0);
3306: }
3310: /*@
3311: TSPostStage - Runs the user-defined post-stage function set using TSSetPostStage()
3313: Collective on TS
3315: Input Parameters:
3316: . ts - The TS context obtained from TSCreate()
3317: stagetime - The absolute time of the current stage
3318: stageindex - Stage number
3319: Y - Array of vectors (of size = total number
3320: of stages) with the stage solutions
3322: Notes:
3323: TSPostStage() is typically used within time stepping implementations,
3324: most users would not generally call this routine themselves.
3326: Level: developer
3328: .keywords: TS, timestep
3329: .seealso: TSPreStage(), TSSetPreStep(), TSPreStep(), TSPostStep()
3330: @*/
3331: PetscErrorCode TSPostStage(TS ts, PetscReal stagetime, PetscInt stageindex, Vec *Y)
3332: {
3337: if (ts->poststage) {
3338: PetscStackCallStandard((*ts->poststage),(ts,stagetime,stageindex,Y));
3339: }
3340: return(0);
3341: }
3345: /*@C
3346: TSSetPostStep - Sets the general-purpose function
3347: called once at the end of each time step.
3349: Logically Collective on TS
3351: Input Parameters:
3352: + ts - The TS context obtained from TSCreate()
3353: - func - The function
3355: Calling sequence of func:
3356: $ func (TS ts);
3358: Level: intermediate
3360: .keywords: TS, timestep
3361: .seealso: TSSetPreStep(), TSSetPreStage(), TSGetTimeStep(), TSGetTimeStepNumber(), TSGetTime()
3362: @*/
3363: PetscErrorCode TSSetPostStep(TS ts, PetscErrorCode (*func)(TS))
3364: {
3367: ts->poststep = func;
3368: return(0);
3369: }
3373: /*@
3374: TSPostStep - Runs the user-defined post-step function.
3376: Collective on TS
3378: Input Parameters:
3379: . ts - The TS context obtained from TSCreate()
3381: Notes:
3382: TSPostStep() is typically used within time stepping implementations,
3383: so most users would not generally call this routine themselves.
3385: Level: developer
3387: .keywords: TS, timestep
3388: @*/
3389: PetscErrorCode TSPostStep(TS ts)
3390: {
3395: if (ts->poststep) {
3396: Vec U;
3397: PetscObjectState sprev,spost;
3399: TSGetSolution(ts,&U);
3400: PetscObjectStateGet((PetscObject)U,&sprev);
3401: PetscStackCallStandard((*ts->poststep),(ts));
3402: PetscObjectStateGet((PetscObject)U,&spost);
3403: if (sprev != spost) ts->steprestart = PETSC_TRUE;
3404: }
3405: return(0);
3406: }
3408: /* ------------ Routines to set performance monitoring options ----------- */
3412: /*@C
3413: TSMonitorSet - Sets an ADDITIONAL function that is to be used at every
3414: timestep to display the iteration's progress.
3416: Logically Collective on TS
3418: Input Parameters:
3419: + ts - the TS context obtained from TSCreate()
3420: . monitor - monitoring routine
3421: . mctx - [optional] user-defined context for private data for the
3422: monitor routine (use NULL if no context is desired)
3423: - monitordestroy - [optional] routine that frees monitor context
3424: (may be NULL)
3426: Calling sequence of monitor:
3427: $ int monitor(TS ts,PetscInt steps,PetscReal time,Vec u,void *mctx)
3429: + ts - the TS context
3430: . 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)
3431: . time - current time
3432: . u - current iterate
3433: - mctx - [optional] monitoring context
3435: Notes:
3436: This routine adds an additional monitor to the list of monitors that
3437: already has been loaded.
3439: Fortran notes: Only a single monitor function can be set for each TS object
3441: Level: intermediate
3443: .keywords: TS, timestep, set, monitor
3445: .seealso: TSMonitorDefault(), TSMonitorCancel()
3446: @*/
3447: PetscErrorCode TSMonitorSet(TS ts,PetscErrorCode (*monitor)(TS,PetscInt,PetscReal,Vec,void*),void *mctx,PetscErrorCode (*mdestroy)(void**))
3448: {
3450: PetscInt i;
3451: PetscBool identical;
3452:
3455: for (i=0; i<ts->numbermonitors;i++) {
3456: PetscMonitorCompare((PetscErrorCode (*)(void))monitor,mctx,mdestroy,(PetscErrorCode (*)(void))ts->monitor[i],ts->monitorcontext[i],ts->monitordestroy[i],&identical);
3457: if (identical) return(0);
3458: }
3459: if (ts->numbermonitors >= MAXTSMONITORS) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Too many monitors set");
3460: ts->monitor[ts->numbermonitors] = monitor;
3461: ts->monitordestroy[ts->numbermonitors] = mdestroy;
3462: ts->monitorcontext[ts->numbermonitors++] = (void*)mctx;
3463: return(0);
3464: }
3468: /*@C
3469: TSMonitorCancel - Clears all the monitors that have been set on a time-step object.
3471: Logically Collective on TS
3473: Input Parameters:
3474: . ts - the TS context obtained from TSCreate()
3476: Notes:
3477: There is no way to remove a single, specific monitor.
3479: Level: intermediate
3481: .keywords: TS, timestep, set, monitor
3483: .seealso: TSMonitorDefault(), TSMonitorSet()
3484: @*/
3485: PetscErrorCode TSMonitorCancel(TS ts)
3486: {
3488: PetscInt i;
3492: for (i=0; i<ts->numbermonitors; i++) {
3493: if (ts->monitordestroy[i]) {
3494: (*ts->monitordestroy[i])(&ts->monitorcontext[i]);
3495: }
3496: }
3497: ts->numbermonitors = 0;
3498: return(0);
3499: }
3503: /*@C
3504: TSMonitorDefault - The Default monitor, prints the timestep and time for each step
3506: Level: intermediate
3508: .keywords: TS, set, monitor
3510: .seealso: TSMonitorSet()
3511: @*/
3512: PetscErrorCode TSMonitorDefault(TS ts,PetscInt step,PetscReal ptime,Vec v,PetscViewerAndFormat *vf)
3513: {
3515: PetscViewer viewer = vf->viewer;
3516: PetscBool iascii,ibinary;
3520: PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERASCII,&iascii);
3521: PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERBINARY,&ibinary);
3522: PetscViewerPushFormat(viewer,vf->format);
3523: if (iascii) {
3524: PetscViewerASCIIAddTab(viewer,((PetscObject)ts)->tablevel);
3525: if (step == -1){ /* this indicates it is an interpolated solution */
3526: PetscViewerASCIIPrintf(viewer,"Interpolated solution at time %g between steps %D and %D\n",(double)ptime,ts->steps-1,ts->steps);
3527: } else {
3528: PetscViewerASCIIPrintf(viewer,"%D TS dt %g time %g%s",step,(double)ts->time_step,(double)ptime,ts->steprollback ? " (r)\n" : "\n");
3529: }
3530: PetscViewerASCIISubtractTab(viewer,((PetscObject)ts)->tablevel);
3531: } else if (ibinary) {
3532: PetscMPIInt rank;
3533: MPI_Comm_rank(PetscObjectComm((PetscObject)viewer),&rank);
3534: if (!rank) {
3535: PetscRealView(1,&ptime,viewer);
3536: } else {
3537: PetscRealView(0,&ptime,viewer);
3538: }
3539: }
3540: PetscViewerPopFormat(viewer);
3541: return(0);
3542: }
3546: /*@C
3547: TSAdjointMonitorSet - Sets an ADDITIONAL function that is to be used at every
3548: timestep to display the iteration's progress.
3550: Logically Collective on TS
3552: Input Parameters:
3553: + ts - the TS context obtained from TSCreate()
3554: . adjointmonitor - monitoring routine
3555: . adjointmctx - [optional] user-defined context for private data for the
3556: monitor routine (use NULL if no context is desired)
3557: - adjointmonitordestroy - [optional] routine that frees monitor context
3558: (may be NULL)
3560: Calling sequence of monitor:
3561: $ int adjointmonitor(TS ts,PetscInt steps,PetscReal time,Vec u,PetscInt numcost,Vec *lambda, Vec *mu,void *adjointmctx)
3563: + ts - the TS context
3564: . 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
3565: been interpolated to)
3566: . time - current time
3567: . u - current iterate
3568: . numcost - number of cost functionos
3569: . lambda - sensitivities to initial conditions
3570: . mu - sensitivities to parameters
3571: - adjointmctx - [optional] adjoint monitoring context
3573: Notes:
3574: This routine adds an additional monitor to the list of monitors that
3575: already has been loaded.
3577: Fortran notes: Only a single monitor function can be set for each TS object
3579: Level: intermediate
3581: .keywords: TS, timestep, set, adjoint, monitor
3583: .seealso: TSAdjointMonitorCancel()
3584: @*/
3585: PetscErrorCode TSAdjointMonitorSet(TS ts,PetscErrorCode (*adjointmonitor)(TS,PetscInt,PetscReal,Vec,PetscInt,Vec*,Vec*,void*),void *adjointmctx,PetscErrorCode (*adjointmdestroy)(void**))
3586: {
3588: PetscInt i;
3589: PetscBool identical;
3593: for (i=0; i<ts->numbermonitors;i++) {
3594: PetscMonitorCompare((PetscErrorCode (*)(void))adjointmonitor,adjointmctx,adjointmdestroy,(PetscErrorCode (*)(void))ts->adjointmonitor[i],ts->adjointmonitorcontext[i],ts->adjointmonitordestroy[i],&identical);
3595: if (identical) return(0);
3596: }
3597: if (ts->numberadjointmonitors >= MAXTSMONITORS) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Too many adjoint monitors set");
3598: ts->adjointmonitor[ts->numberadjointmonitors] = adjointmonitor;
3599: ts->adjointmonitordestroy[ts->numberadjointmonitors] = adjointmdestroy;
3600: ts->adjointmonitorcontext[ts->numberadjointmonitors++] = (void*)adjointmctx;
3601: return(0);
3602: }
3606: /*@C
3607: TSAdjointMonitorCancel - Clears all the adjoint monitors that have been set on a time-step object.
3609: Logically Collective on TS
3611: Input Parameters:
3612: . ts - the TS context obtained from TSCreate()
3614: Notes:
3615: There is no way to remove a single, specific monitor.
3617: Level: intermediate
3619: .keywords: TS, timestep, set, adjoint, monitor
3621: .seealso: TSAdjointMonitorSet()
3622: @*/
3623: PetscErrorCode TSAdjointMonitorCancel(TS ts)
3624: {
3626: PetscInt i;
3630: for (i=0; i<ts->numberadjointmonitors; i++) {
3631: if (ts->adjointmonitordestroy[i]) {
3632: (*ts->adjointmonitordestroy[i])(&ts->adjointmonitorcontext[i]);
3633: }
3634: }
3635: ts->numberadjointmonitors = 0;
3636: return(0);
3637: }
3641: /*@C
3642: TSAdjointMonitorDefault - the default monitor of adjoint computations
3644: Level: intermediate
3646: .keywords: TS, set, monitor
3648: .seealso: TSAdjointMonitorSet()
3649: @*/
3650: PetscErrorCode TSAdjointMonitorDefault(TS ts,PetscInt step,PetscReal ptime,Vec v,PetscInt numcost,Vec *lambda,Vec *mu,PetscViewerAndFormat *vf)
3651: {
3653: PetscViewer viewer = vf->viewer;
3657: PetscViewerPushFormat(viewer,vf->format);
3658: PetscViewerASCIIAddTab(viewer,((PetscObject)ts)->tablevel);
3659: PetscViewerASCIIPrintf(viewer,"%D TS dt %g time %g%s",step,(double)ts->time_step,(double)ptime,ts->steprollback ? " (r)\n" : "\n");
3660: PetscViewerASCIISubtractTab(viewer,((PetscObject)ts)->tablevel);
3661: PetscViewerPopFormat(viewer);
3662: return(0);
3663: }
3667: /*@
3668: TSInterpolate - Interpolate the solution computed during the previous step to an arbitrary location in the interval
3670: Collective on TS
3672: Input Argument:
3673: + ts - time stepping context
3674: - t - time to interpolate to
3676: Output Argument:
3677: . U - state at given time
3679: Level: intermediate
3681: Developer Notes:
3682: TSInterpolate() and the storing of previous steps/stages should be generalized to support delay differential equations and continuous adjoints.
3684: .keywords: TS, set
3686: .seealso: TSSetExactFinalTime(), TSSolve()
3687: @*/
3688: PetscErrorCode TSInterpolate(TS ts,PetscReal t,Vec U)
3689: {
3695: 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);
3696: if (!ts->ops->interpolate) SETERRQ1(PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"%s does not provide interpolation",((PetscObject)ts)->type_name);
3697: (*ts->ops->interpolate)(ts,t,U);
3698: return(0);
3699: }
3703: /*@
3704: TSStep - Steps one time step
3706: Collective on TS
3708: Input Parameter:
3709: . ts - the TS context obtained from TSCreate()
3711: Level: developer
3713: Notes:
3714: The public interface for the ODE/DAE solvers is TSSolve(), you should almost for sure be using that routine and not this routine.
3716: The hook set using TSSetPreStep() is called before each attempt to take the step. In general, the time step size may
3717: be changed due to adaptive error controller or solve failures. Note that steps may contain multiple stages.
3719: This may over-step the final time provided in TSSetDuration() depending on the time-step used. TSSolve() interpolates to exactly the
3720: time provided in TSSetDuration(). One can use TSInterpolate() to determine an interpolated solution within the final timestep.
3722: .keywords: TS, timestep, solve
3724: .seealso: TSCreate(), TSSetUp(), TSDestroy(), TSSolve(), TSSetPreStep(), TSSetPreStage(), TSSetPostStage(), TSInterpolate()
3725: @*/
3726: PetscErrorCode TSStep(TS ts)
3727: {
3728: PetscErrorCode ierr;
3729: static PetscBool cite = PETSC_FALSE;
3730: PetscReal ptime;
3734: PetscCitationsRegister("@techreport{tspaper,\n"
3735: " title = {{PETSc/TS}: A Modern Scalable {DAE/ODE} Solver Library},\n"
3736: " author = {Shrirang Abhyankar and Jed Brown and Emil Constantinescu and Debojyoti Ghosh and Barry F. Smith},\n"
3737: " type = {Preprint},\n"
3738: " number = {ANL/MCS-P5061-0114},\n"
3739: " institution = {Argonne National Laboratory},\n"
3740: " year = {2014}\n}\n",&cite);
3742: TSSetUp(ts);
3743: TSTrajectorySetUp(ts->trajectory,ts);
3745: 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()");
3746: 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");
3748: if (!ts->steps) ts->ptime_prev = ts->ptime;
3749: ts->reason = TS_CONVERGED_ITERATING;
3750: ptime = ts->ptime; ts->ptime_prev_rollback = ts->ptime_prev;
3751: if (!ts->ops->step) SETERRQ1(PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"TSStep not implemented for type '%s'",((PetscObject)ts)->type_name);
3752: PetscLogEventBegin(TS_Step,ts,0,0,0);
3753: (*ts->ops->step)(ts);
3754: PetscLogEventEnd(TS_Step,ts,0,0,0);
3755: ts->ptime_prev = ptime;
3756: ts->steps++; ts->total_steps++;
3757: ts->steprollback = PETSC_FALSE;
3758: ts->steprestart = PETSC_FALSE;
3760: if (ts->reason < 0) {
3761: if (ts->errorifstepfailed) {
3762: 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]);
3763: else SETERRQ1(PetscObjectComm((PetscObject)ts),PETSC_ERR_NOT_CONVERGED,"TSStep has failed due to %s",TSConvergedReasons[ts->reason]);
3764: }
3765: } else if (!ts->reason) {
3766: if (ts->steps >= ts->max_steps) ts->reason = TS_CONVERGED_ITS;
3767: else if (ts->ptime >= ts->max_time) ts->reason = TS_CONVERGED_TIME;
3768: }
3769: return(0);
3770: }
3774: /*@
3775: TSAdjointStep - Steps one time step backward in the adjoint run
3777: Collective on TS
3779: Input Parameter:
3780: . ts - the TS context obtained from TSCreate()
3782: Level: intermediate
3784: .keywords: TS, adjoint, step
3786: .seealso: TSAdjointSetUp(), TSAdjointSolve()
3787: @*/
3788: PetscErrorCode TSAdjointStep(TS ts)
3789: {
3790: DM dm;
3791: PetscErrorCode ierr;
3795: TSGetDM(ts,&dm);
3796: TSAdjointSetUp(ts);
3798: VecViewFromOptions(ts->vec_sol,(PetscObject)ts,"-ts_view_solution");
3800: ts->reason = TS_CONVERGED_ITERATING;
3801: ts->ptime_prev = ts->ptime;
3802: 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);
3803: PetscLogEventBegin(TS_AdjointStep,ts,0,0,0);
3804: (*ts->ops->adjointstep)(ts);
3805: PetscLogEventEnd(TS_AdjointStep,ts,0,0,0);
3806: ts->steps++; ts->total_steps--;
3808: if (ts->reason < 0) {
3809: if (ts->errorifstepfailed) {
3810: 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]);
3811: 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]);
3812: else SETERRQ1(PetscObjectComm((PetscObject)ts),PETSC_ERR_NOT_CONVERGED,"TSStep has failed due to %s",TSConvergedReasons[ts->reason]);
3813: }
3814: } else if (!ts->reason) {
3815: if (ts->steps >= ts->adjoint_max_steps) ts->reason = TS_CONVERGED_ITS;
3816: }
3817: return(0);
3818: }
3822: /*@
3823: TSEvaluateWLTE - Evaluate the weighted local truncation error norm
3824: at the end of a time step with a given order of accuracy.
3826: Collective on TS
3828: Input Arguments:
3829: + ts - time stepping context
3830: . wnormtype - norm type, either NORM_2 or NORM_INFINITY
3831: - order - optional, desired order for the error evaluation or PETSC_DECIDE
3833: Output Arguments:
3834: + order - optional, the actual order of the error evaluation
3835: - wlte - the weighted local truncation error norm
3837: Level: advanced
3839: Notes:
3840: If the timestepper cannot evaluate the error in a particular step
3841: (eg. in the first step or restart steps after event handling),
3842: this routine returns wlte=-1.0 .
3844: .seealso: TSStep(), TSAdapt, TSErrorWeightedNorm()
3845: @*/
3846: PetscErrorCode TSEvaluateWLTE(TS ts,NormType wnormtype,PetscInt *order,PetscReal *wlte)
3847: {
3857: if (wnormtype != NORM_2 && wnormtype != NORM_INFINITY) SETERRQ1(PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"No support for norm type %s",NormTypes[wnormtype]);
3858: if (!ts->ops->evaluatewlte) SETERRQ1(PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"TSEvaluateWLTE not implemented for type '%s'",((PetscObject)ts)->type_name);
3859: (*ts->ops->evaluatewlte)(ts,wnormtype,order,wlte);
3860: return(0);
3861: }
3865: /*@
3866: TSEvaluateStep - Evaluate the solution at the end of a time step with a given order of accuracy.
3868: Collective on TS
3870: Input Arguments:
3871: + ts - time stepping context
3872: . order - desired order of accuracy
3873: - done - whether the step was evaluated at this order (pass NULL to generate an error if not available)
3875: Output Arguments:
3876: . U - state at the end of the current step
3878: Level: advanced
3880: Notes:
3881: This function cannot be called until all stages have been evaluated.
3882: 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.
3884: .seealso: TSStep(), TSAdapt
3885: @*/
3886: PetscErrorCode TSEvaluateStep(TS ts,PetscInt order,Vec U,PetscBool *done)
3887: {
3894: if (!ts->ops->evaluatestep) SETERRQ1(PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"TSEvaluateStep not implemented for type '%s'",((PetscObject)ts)->type_name);
3895: (*ts->ops->evaluatestep)(ts,order,U,done);
3896: return(0);
3897: }
3901: /*@
3902: TSForwardCostIntegral - Evaluate the cost integral in the forward run.
3903:
3904: Collective on TS
3905:
3906: Input Arguments:
3907: . ts - time stepping context
3908:
3909: Level: advanced
3910:
3911: Notes:
3912: This function cannot be called until TSStep() has been completed.
3913:
3914: .seealso: TSSolve(), TSAdjointCostIntegral()
3915: @*/
3916: PetscErrorCode TSForwardCostIntegral(TS ts)
3917: {
3920: 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);
3921: (*ts->ops->forwardintegral)(ts);
3922: return(0);
3923: }
3927: /*@
3928: TSSolve - Steps the requested number of timesteps.
3930: Collective on TS
3932: Input Parameter:
3933: + ts - the TS context obtained from TSCreate()
3934: - u - the solution vector (can be null if TSSetSolution() was used and TSSetExactFinalTime(ts,TS_EXACTFINALTIME_MATCHSTEP) was not used,
3935: otherwise must contain the initial conditions and will contain the solution at the final requested time
3937: Level: beginner
3939: Notes:
3940: The final time returned by this function may be different from the time of the internally
3941: held state accessible by TSGetSolution() and TSGetTime() because the method may have
3942: stepped over the final time.
3944: .keywords: TS, timestep, solve
3946: .seealso: TSCreate(), TSSetSolution(), TSStep(), TSGetTime(), TSGetSolveTime()
3947: @*/
3948: PetscErrorCode TSSolve(TS ts,Vec u)
3949: {
3950: Vec solution;
3951: PetscErrorCode ierr;
3957: 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 */
3959: if (!ts->vec_sol || u == ts->vec_sol) {
3960: VecDuplicate(u,&solution);
3961: TSSetSolution(ts,solution);
3962: VecDestroy(&solution); /* grant ownership */
3963: }
3964: VecCopy(u,ts->vec_sol);
3965: } else if (u) {
3966: TSSetSolution(ts,u);
3967: }
3968: TSSetUp(ts);
3969: TSTrajectorySetUp(ts->trajectory,ts);
3971: 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()");
3972: 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");
3974: /* reset time step and iteration counters */
3975: ts->steps = 0;
3976: ts->ksp_its = 0;
3977: ts->snes_its = 0;
3978: ts->num_snes_failures = 0;
3979: ts->reject = 0;
3980: ts->reason = TS_CONVERGED_ITERATING;
3982: TSViewFromOptions(ts,NULL,"-ts_view_pre");
3984: if (ts->ops->solve) { /* This private interface is transitional and should be removed when all implementations are updated. */
3985: (*ts->ops->solve)(ts);
3986: if (u) {VecCopy(ts->vec_sol,u);}
3987: ts->solvetime = ts->ptime;
3988: solution = ts->vec_sol;
3989: } else { /* Step the requested number of timesteps. */
3990: if (ts->steps >= ts->max_steps) ts->reason = TS_CONVERGED_ITS;
3991: else if (ts->ptime >= ts->max_time) ts->reason = TS_CONVERGED_TIME;
3992: TSTrajectorySet(ts->trajectory,ts,ts->steps,ts->ptime,ts->vec_sol);
3993: TSEventInitialize(ts->event,ts,ts->ptime,ts->vec_sol);
3994: ts->steprollback = PETSC_FALSE;
3995: ts->steprestart = PETSC_TRUE;
3997: while (!ts->reason) {
3998: TSMonitor(ts,ts->steps,ts->ptime,ts->vec_sol);
3999: if (!ts->steprollback) {
4000: TSPreStep(ts);
4001: }
4002: TSStep(ts);
4003: if (ts->vec_costintegral && ts->costintegralfwd) { /* Must evaluate the cost integral before event is handled. The cost integral value can also be rolled back. */
4004: TSForwardCostIntegral(ts);
4005: }
4006: TSEventHandler(ts); /* The right-hand side may be changed due to event. Be careful with Any computation using the RHS information after this point. */
4007: if (!ts->steprollback) {
4008: TSTrajectorySet(ts->trajectory,ts,ts->steps,ts->ptime,ts->vec_sol);
4009: TSPostStep(ts);
4010: }
4011: }
4012: TSMonitor(ts,ts->steps,ts->ptime,ts->vec_sol);
4014: if (ts->exact_final_time == TS_EXACTFINALTIME_INTERPOLATE && ts->ptime > ts->max_time) {
4015: TSInterpolate(ts,ts->max_time,u);
4016: ts->solvetime = ts->max_time;
4017: solution = u;
4018: TSMonitor(ts,-1,ts->solvetime,solution);
4019: } else {
4020: if (u) {VecCopy(ts->vec_sol,u);}
4021: ts->solvetime = ts->ptime;
4022: solution = ts->vec_sol;
4023: }
4024: }
4026: TSViewFromOptions(ts,NULL,"-ts_view");
4027: VecViewFromOptions(solution,NULL,"-ts_view_solution");
4028: PetscObjectSAWsBlock((PetscObject)ts);
4029: if (ts->adjoint_solve) {
4030: TSAdjointSolve(ts);
4031: }
4032: return(0);
4033: }
4037: /*@
4038: TSAdjointCostIntegral - Evaluate the cost integral in the adjoint run.
4039:
4040: Collective on TS
4041:
4042: Input Arguments:
4043: . ts - time stepping context
4044:
4045: Level: advanced
4046:
4047: Notes:
4048: This function cannot be called until TSAdjointStep() has been completed.
4049:
4050: .seealso: TSAdjointSolve(), TSAdjointStep
4051: @*/
4052: PetscErrorCode TSAdjointCostIntegral(TS ts)
4053: {
4056: 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);
4057: (*ts->ops->adjointintegral)(ts);
4058: return(0);
4059: }
4063: /*@
4064: TSAdjointSolve - Solves the discrete ajoint problem for an ODE/DAE
4066: Collective on TS
4068: Input Parameter:
4069: . ts - the TS context obtained from TSCreate()
4071: Options Database:
4072: . -ts_adjoint_view_solution <viewerinfo> - views the first gradient with respect to the initial conditions
4074: Level: intermediate
4076: Notes:
4077: This must be called after a call to TSSolve() that solves the forward problem
4079: By default this will integrate back to the initial time, one can use TSAdjointSetSteps() to step back to a later time
4081: .keywords: TS, timestep, solve
4083: .seealso: TSCreate(), TSSetCostGradients(), TSSetSolution(), TSAdjointStep()
4084: @*/
4085: PetscErrorCode TSAdjointSolve(TS ts)
4086: {
4087: PetscErrorCode ierr;
4091: TSAdjointSetUp(ts);
4093: /* reset time step and iteration counters */
4094: ts->steps = 0;
4095: ts->ksp_its = 0;
4096: ts->snes_its = 0;
4097: ts->num_snes_failures = 0;
4098: ts->reject = 0;
4099: ts->reason = TS_CONVERGED_ITERATING;
4101: if (!ts->adjoint_max_steps) ts->adjoint_max_steps = ts->total_steps;
4103: if (ts->steps >= ts->adjoint_max_steps) ts->reason = TS_CONVERGED_ITS;
4104: while (!ts->reason) {
4105: TSTrajectoryGet(ts->trajectory,ts,ts->total_steps,&ts->ptime);
4106: TSAdjointMonitor(ts,ts->total_steps,ts->ptime,ts->vec_sol,ts->numcost,ts->vecs_sensi,ts->vecs_sensip);
4107: TSAdjointEventHandler(ts);
4108: TSAdjointStep(ts);
4109: if (ts->vec_costintegral && !ts->costintegralfwd) {
4110: TSAdjointCostIntegral(ts);
4111: }
4112: }
4113: TSTrajectoryGet(ts->trajectory,ts,ts->total_steps,&ts->ptime);
4114: TSAdjointMonitor(ts,ts->total_steps,ts->ptime,ts->vec_sol,ts->numcost,ts->vecs_sensi,ts->vecs_sensip);
4115: ts->solvetime = ts->ptime;
4116: TSTrajectoryViewFromOptions(ts->trajectory,NULL,"-ts_trajectory_view");
4117: VecViewFromOptions(ts->vecs_sensi[0],(PetscObject) ts, "-ts_adjoint_view_solution");
4118: return(0);
4119: }
4123: /*@C
4124: TSMonitor - Runs all user-provided monitor routines set using TSMonitorSet()
4126: Collective on TS
4128: Input Parameters:
4129: + ts - time stepping context obtained from TSCreate()
4130: . step - step number that has just completed
4131: . ptime - model time of the state
4132: - u - state at the current model time
4134: Notes:
4135: TSMonitor() is typically used automatically within the time stepping implementations.
4136: Users would almost never call this routine directly.
4138: A step of -1 indicates that the monitor is being called on a solution obtained by interpolating from computed solutions
4140: Level: developer
4142: .keywords: TS, timestep
4143: @*/
4144: PetscErrorCode TSMonitor(TS ts,PetscInt step,PetscReal ptime,Vec u)
4145: {
4146: DM dm;
4147: PetscInt i,n = ts->numbermonitors;
4154: TSGetDM(ts,&dm);
4155: DMSetOutputSequenceNumber(dm,step,ptime);
4157: VecLockPush(u);
4158: for (i=0; i<n; i++) {
4159: (*ts->monitor[i])(ts,step,ptime,u,ts->monitorcontext[i]);
4160: }
4161: VecLockPop(u);
4162: return(0);
4163: }
4167: /*@C
4168: TSAdjointMonitor - Runs all user-provided adjoint monitor routines set using TSAdjointMonitorSet()
4170: Collective on TS
4172: Input Parameters:
4173: + ts - time stepping context obtained from TSCreate()
4174: . step - step number that has just completed
4175: . ptime - model time of the state
4176: . u - state at the current model time
4177: . numcost - number of cost functions (dimension of lambda or mu)
4178: . lambda - vectors containing the gradients of the cost functions with respect to the ODE/DAE solution variables
4179: - mu - vectors containing the gradients of the cost functions with respect to the problem parameters
4181: Notes:
4182: TSAdjointMonitor() is typically used automatically within the time stepping implementations.
4183: Users would almost never call this routine directly.
4185: Level: developer
4187: .keywords: TS, timestep
4188: @*/
4189: PetscErrorCode TSAdjointMonitor(TS ts,PetscInt step,PetscReal ptime,Vec u,PetscInt numcost,Vec *lambda, Vec *mu)
4190: {
4192: PetscInt i,n = ts->numberadjointmonitors;
4197: VecLockPush(u);
4198: for (i=0; i<n; i++) {
4199: (*ts->adjointmonitor[i])(ts,step,ptime,u,numcost,lambda,mu,ts->adjointmonitorcontext[i]);
4200: }
4201: VecLockPop(u);
4202: return(0);
4203: }
4205: /* ------------------------------------------------------------------------*/
4208: /*@C
4209: TSMonitorLGCtxCreate - Creates a TSMonitorLGCtx context for use with
4210: TS to monitor the solution process graphically in various ways
4212: Collective on TS
4214: Input Parameters:
4215: + host - the X display to open, or null for the local machine
4216: . label - the title to put in the title bar
4217: . x, y - the screen coordinates of the upper left coordinate of the window
4218: . m, n - the screen width and height in pixels
4219: - howoften - if positive then determines the frequency of the plotting, if -1 then only at the final time
4221: Output Parameter:
4222: . ctx - the context
4224: Options Database Key:
4225: + -ts_monitor_lg_timestep - automatically sets line graph monitor
4226: . -ts_monitor_lg_solution - monitor the solution (or certain values of the solution by calling TSMonitorLGSetDisplayVariables() or TSMonitorLGCtxSetDisplayVariables())
4227: . -ts_monitor_lg_error - monitor the error
4228: . -ts_monitor_lg_ksp_iterations - monitor the number of KSP iterations needed for each timestep
4229: . -ts_monitor_lg_snes_iterations - monitor the number of SNES iterations needed for each timestep
4230: - -lg_use_markers <true,false> - mark the data points (at each time step) on the plot; default is true
4232: Notes:
4233: Use TSMonitorLGCtxDestroy() to destroy.
4235: One can provide a function that transforms the solution before plotting it with TSMonitorLGCtxSetTransform() or TSMonitorLGSetTransform()
4237: Many of the functions that control the monitoring have two forms: TSMonitorLGSet/GetXXXX() and TSMonitorLGCtxSet/GetXXXX() the first take a TS object as the
4238: 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
4239: as the first argument.
4241: One can control the names displayed for each solution or error variable with TSMonitorLGCtxSetVariableNames() or TSMonitorLGSetVariableNames()
4244: Level: intermediate
4246: .keywords: TS, monitor, line graph, residual
4248: .seealso: TSMonitorLGTimeStep(), TSMonitorSet(), TSMonitorLGSolution(), TSMonitorLGError(), TSMonitorDefault(), VecView(),
4249: TSMonitorLGCtxCreate(), TSMonitorLGCtxSetVariableNames(), TSMonitorLGCtxGetVariableNames(),
4250: TSMonitorLGSetVariableNames(), TSMonitorLGGetVariableNames(), TSMonitorLGSetDisplayVariables(), TSMonitorLGCtxSetDisplayVariables(),
4251: TSMonitorLGCtxSetTransform(), TSMonitorLGSetTransform(), TSMonitorLGError(), TSMonitorLGSNESIterations(), TSMonitorLGKSPIterations(),
4252: TSMonitorEnvelopeCtxCreate(), TSMonitorEnvelopeGetBounds(), TSMonitorEnvelopeCtxDestroy(), TSMonitorEnvelop()
4254: @*/
4255: PetscErrorCode TSMonitorLGCtxCreate(MPI_Comm comm,const char host[],const char label[],int x,int y,int m,int n,PetscInt howoften,TSMonitorLGCtx *ctx)
4256: {
4257: PetscDraw draw;
4261: PetscNew(ctx);
4262: PetscDrawCreate(comm,host,label,x,y,m,n,&draw);
4263: PetscDrawSetFromOptions(draw);
4264: PetscDrawLGCreate(draw,1,&(*ctx)->lg);
4265: PetscDrawLGSetFromOptions((*ctx)->lg);
4266: PetscDrawDestroy(&draw);
4267: (*ctx)->howoften = howoften;
4268: return(0);
4269: }
4273: PetscErrorCode TSMonitorLGTimeStep(TS ts,PetscInt step,PetscReal ptime,Vec v,void *monctx)
4274: {
4275: TSMonitorLGCtx ctx = (TSMonitorLGCtx) monctx;
4276: PetscReal x = ptime,y;
4280: if (step < 0) return(0); /* -1 indicates an interpolated solution */
4281: if (!step) {
4282: PetscDrawAxis axis;
4283: PetscDrawLGGetAxis(ctx->lg,&axis);
4284: PetscDrawAxisSetLabels(axis,"Timestep as function of time","Time","Time Step");
4285: PetscDrawLGReset(ctx->lg);
4286: }
4287: TSGetTimeStep(ts,&y);
4288: PetscDrawLGAddPoint(ctx->lg,&x,&y);
4289: if (((ctx->howoften > 0) && (!(step % ctx->howoften))) || ((ctx->howoften == -1) && ts->reason)) {
4290: PetscDrawLGDraw(ctx->lg);
4291: PetscDrawLGSave(ctx->lg);
4292: }
4293: return(0);
4294: }
4298: /*@C
4299: TSMonitorLGCtxDestroy - Destroys a line graph context that was created
4300: with TSMonitorLGCtxCreate().
4302: Collective on TSMonitorLGCtx
4304: Input Parameter:
4305: . ctx - the monitor context
4307: Level: intermediate
4309: .keywords: TS, monitor, line graph, destroy
4311: .seealso: TSMonitorLGCtxCreate(), TSMonitorSet(), TSMonitorLGTimeStep();
4312: @*/
4313: PetscErrorCode TSMonitorLGCtxDestroy(TSMonitorLGCtx *ctx)
4314: {
4318: if ((*ctx)->transformdestroy) {
4319: ((*ctx)->transformdestroy)((*ctx)->transformctx);
4320: }
4321: PetscDrawLGDestroy(&(*ctx)->lg);
4322: PetscStrArrayDestroy(&(*ctx)->names);
4323: PetscStrArrayDestroy(&(*ctx)->displaynames);
4324: PetscFree((*ctx)->displayvariables);
4325: PetscFree((*ctx)->displayvalues);
4326: PetscFree(*ctx);
4327: return(0);
4328: }
4332: /*@
4333: TSGetTime - Gets the time of the most recently completed step.
4335: Not Collective
4337: Input Parameter:
4338: . ts - the TS context obtained from TSCreate()
4340: Output Parameter:
4341: . t - the current time. This time may not corresponds to the final time set with TSSetDuration(), use TSGetSolveTime().
4343: Level: beginner
4345: Note:
4346: When called during time step evaluation (e.g. during residual evaluation or via hooks set using TSSetPreStep(),
4347: TSSetPreStage(), TSSetPostStage(), or TSSetPostStep()), the time is the time at the start of the step being evaluated.
4349: .seealso: TSSetInitialTimeStep(), TSGetTimeStep(), TSGetSolveTime()
4351: .keywords: TS, get, time
4352: @*/
4353: PetscErrorCode TSGetTime(TS ts,PetscReal *t)
4354: {
4358: *t = ts->ptime;
4359: return(0);
4360: }
4364: /*@
4365: TSGetPrevTime - Gets the starting time of the previously completed step.
4367: Not Collective
4369: Input Parameter:
4370: . ts - the TS context obtained from TSCreate()
4372: Output Parameter:
4373: . t - the previous time
4375: Level: beginner
4377: .seealso: TSSetInitialTimeStep(), TSGetTimeStep()
4379: .keywords: TS, get, time
4380: @*/
4381: PetscErrorCode TSGetPrevTime(TS ts,PetscReal *t)
4382: {
4386: *t = ts->ptime_prev;
4387: return(0);
4388: }
4392: /*@
4393: TSSetTime - Allows one to reset the time.
4395: Logically Collective on TS
4397: Input Parameters:
4398: + ts - the TS context obtained from TSCreate()
4399: - time - the time
4401: Level: intermediate
4403: .seealso: TSGetTime(), TSSetDuration()
4405: .keywords: TS, set, time
4406: @*/
4407: PetscErrorCode TSSetTime(TS ts, PetscReal t)
4408: {
4412: ts->ptime = t;
4413: return(0);
4414: }
4418: /*@C
4419: TSSetOptionsPrefix - Sets the prefix used for searching for all
4420: TS options in the database.
4422: Logically Collective on TS
4424: Input Parameter:
4425: + ts - The TS context
4426: - prefix - The prefix to prepend to all option names
4428: Notes:
4429: A hyphen (-) must NOT be given at the beginning of the prefix name.
4430: The first character of all runtime options is AUTOMATICALLY the
4431: hyphen.
4433: Level: advanced
4435: .keywords: TS, set, options, prefix, database
4437: .seealso: TSSetFromOptions()
4439: @*/
4440: PetscErrorCode TSSetOptionsPrefix(TS ts,const char prefix[])
4441: {
4443: SNES snes;
4447: PetscObjectSetOptionsPrefix((PetscObject)ts,prefix);
4448: TSGetSNES(ts,&snes);
4449: SNESSetOptionsPrefix(snes,prefix);
4450: return(0);
4451: }
4456: /*@C
4457: TSAppendOptionsPrefix - Appends to the prefix used for searching for all
4458: TS options in the database.
4460: Logically Collective on TS
4462: Input Parameter:
4463: + ts - The TS context
4464: - prefix - The prefix to prepend to all option names
4466: Notes:
4467: A hyphen (-) must NOT be given at the beginning of the prefix name.
4468: The first character of all runtime options is AUTOMATICALLY the
4469: hyphen.
4471: Level: advanced
4473: .keywords: TS, append, options, prefix, database
4475: .seealso: TSGetOptionsPrefix()
4477: @*/
4478: PetscErrorCode TSAppendOptionsPrefix(TS ts,const char prefix[])
4479: {
4481: SNES snes;
4485: PetscObjectAppendOptionsPrefix((PetscObject)ts,prefix);
4486: TSGetSNES(ts,&snes);
4487: SNESAppendOptionsPrefix(snes,prefix);
4488: return(0);
4489: }
4493: /*@C
4494: TSGetOptionsPrefix - Sets the prefix used for searching for all
4495: TS options in the database.
4497: Not Collective
4499: Input Parameter:
4500: . ts - The TS context
4502: Output Parameter:
4503: . prefix - A pointer to the prefix string used
4505: Notes: On the fortran side, the user should pass in a string 'prifix' of
4506: sufficient length to hold the prefix.
4508: Level: intermediate
4510: .keywords: TS, get, options, prefix, database
4512: .seealso: TSAppendOptionsPrefix()
4513: @*/
4514: PetscErrorCode TSGetOptionsPrefix(TS ts,const char *prefix[])
4515: {
4521: PetscObjectGetOptionsPrefix((PetscObject)ts,prefix);
4522: return(0);
4523: }
4527: /*@C
4528: TSGetRHSJacobian - Returns the Jacobian J at the present timestep.
4530: Not Collective, but parallel objects are returned if TS is parallel
4532: Input Parameter:
4533: . ts - The TS context obtained from TSCreate()
4535: Output Parameters:
4536: + Amat - The (approximate) Jacobian J of G, where U_t = G(U,t) (or NULL)
4537: . Pmat - The matrix from which the preconditioner is constructed, usually the same as Amat (or NULL)
4538: . func - Function to compute the Jacobian of the RHS (or NULL)
4539: - ctx - User-defined context for Jacobian evaluation routine (or NULL)
4541: Notes: You can pass in NULL for any return argument you do not need.
4543: Level: intermediate
4545: .seealso: TSGetTimeStep(), TSGetMatrices(), TSGetTime(), TSGetTimeStepNumber()
4547: .keywords: TS, timestep, get, matrix, Jacobian
4548: @*/
4549: PetscErrorCode TSGetRHSJacobian(TS ts,Mat *Amat,Mat *Pmat,TSRHSJacobian *func,void **ctx)
4550: {
4552: SNES snes;
4553: DM dm;
4556: TSGetSNES(ts,&snes);
4557: SNESGetJacobian(snes,Amat,Pmat,NULL,NULL);
4558: TSGetDM(ts,&dm);
4559: DMTSGetRHSJacobian(dm,func,ctx);
4560: return(0);
4561: }
4565: /*@C
4566: TSGetIJacobian - Returns the implicit Jacobian at the present timestep.
4568: Not Collective, but parallel objects are returned if TS is parallel
4570: Input Parameter:
4571: . ts - The TS context obtained from TSCreate()
4573: Output Parameters:
4574: + Amat - The (approximate) Jacobian of F(t,U,U_t)
4575: . Pmat - The matrix from which the preconditioner is constructed, often the same as Amat
4576: . f - The function to compute the matrices
4577: - ctx - User-defined context for Jacobian evaluation routine
4579: Notes: You can pass in NULL for any return argument you do not need.
4581: Level: advanced
4583: .seealso: TSGetTimeStep(), TSGetRHSJacobian(), TSGetMatrices(), TSGetTime(), TSGetTimeStepNumber()
4585: .keywords: TS, timestep, get, matrix, Jacobian
4586: @*/
4587: PetscErrorCode TSGetIJacobian(TS ts,Mat *Amat,Mat *Pmat,TSIJacobian *f,void **ctx)
4588: {
4590: DM dm;
4593: if (Amat || Pmat) {
4594: SNES snes;
4595: TSGetSNES(ts,&snes);
4596: SNESSetUpMatrices(snes);
4597: SNESGetJacobian(snes,Amat,Pmat,NULL,NULL);
4598: }
4599: TSGetDM(ts,&dm);
4600: DMTSGetIJacobian(dm,f,ctx);
4601: return(0);
4602: }
4607: /*@C
4608: TSMonitorDrawSolution - Monitors progress of the TS solvers by calling
4609: VecView() for the solution at each timestep
4611: Collective on TS
4613: Input Parameters:
4614: + ts - the TS context
4615: . step - current time-step
4616: . ptime - current time
4617: - dummy - either a viewer or NULL
4619: Options Database:
4620: . -ts_monitor_draw_solution_initial - show initial solution as well as current solution
4622: Notes: the initial solution and current solution are not display with a common axis scaling so generally the option -ts_monitor_draw_solution_initial
4623: will look bad
4625: Level: intermediate
4627: .keywords: TS, vector, monitor, view
4629: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView()
4630: @*/
4631: PetscErrorCode TSMonitorDrawSolution(TS ts,PetscInt step,PetscReal ptime,Vec u,void *dummy)
4632: {
4633: PetscErrorCode ierr;
4634: TSMonitorDrawCtx ictx = (TSMonitorDrawCtx)dummy;
4635: PetscDraw draw;
4638: if (!step && ictx->showinitial) {
4639: if (!ictx->initialsolution) {
4640: VecDuplicate(u,&ictx->initialsolution);
4641: }
4642: VecCopy(u,ictx->initialsolution);
4643: }
4644: if (!(((ictx->howoften > 0) && (!(step % ictx->howoften))) || ((ictx->howoften == -1) && ts->reason))) return(0);
4646: if (ictx->showinitial) {
4647: PetscReal pause;
4648: PetscViewerDrawGetPause(ictx->viewer,&pause);
4649: PetscViewerDrawSetPause(ictx->viewer,0.0);
4650: VecView(ictx->initialsolution,ictx->viewer);
4651: PetscViewerDrawSetPause(ictx->viewer,pause);
4652: PetscViewerDrawSetHold(ictx->viewer,PETSC_TRUE);
4653: }
4654: VecView(u,ictx->viewer);
4655: if (ictx->showtimestepandtime) {
4656: PetscReal xl,yl,xr,yr,h;
4657: char time[32];
4659: PetscViewerDrawGetDraw(ictx->viewer,0,&draw);
4660: PetscSNPrintf(time,32,"Timestep %d Time %g",(int)step,(double)ptime);
4661: PetscDrawGetCoordinates(draw,&xl,&yl,&xr,&yr);
4662: h = yl + .95*(yr - yl);
4663: PetscDrawStringCentered(draw,.5*(xl+xr),h,PETSC_DRAW_BLACK,time);
4664: PetscDrawFlush(draw);
4665: }
4667: if (ictx->showinitial) {
4668: PetscViewerDrawSetHold(ictx->viewer,PETSC_FALSE);
4669: }
4670: return(0);
4671: }
4675: /*@C
4676: TSAdjointMonitorDrawSensi - Monitors progress of the adjoint TS solvers by calling
4677: VecView() for the sensitivities to initial states at each timestep
4679: Collective on TS
4681: Input Parameters:
4682: + ts - the TS context
4683: . step - current time-step
4684: . ptime - current time
4685: . u - current state
4686: . numcost - number of cost functions
4687: . lambda - sensitivities to initial conditions
4688: . mu - sensitivities to parameters
4689: - dummy - either a viewer or NULL
4691: Level: intermediate
4693: .keywords: TS, vector, adjoint, monitor, view
4695: .seealso: TSAdjointMonitorSet(), TSAdjointMonitorDefault(), VecView()
4696: @*/
4697: PetscErrorCode TSAdjointMonitorDrawSensi(TS ts,PetscInt step,PetscReal ptime,Vec u,PetscInt numcost,Vec *lambda,Vec *mu,void *dummy)
4698: {
4699: PetscErrorCode ierr;
4700: TSMonitorDrawCtx ictx = (TSMonitorDrawCtx)dummy;
4701: PetscDraw draw;
4702: PetscReal xl,yl,xr,yr,h;
4703: char time[32];
4706: if (!(((ictx->howoften > 0) && (!(step % ictx->howoften))) || ((ictx->howoften == -1) && ts->reason))) return(0);
4708: VecView(lambda[0],ictx->viewer);
4709: PetscViewerDrawGetDraw(ictx->viewer,0,&draw);
4710: PetscSNPrintf(time,32,"Timestep %d Time %g",(int)step,(double)ptime);
4711: PetscDrawGetCoordinates(draw,&xl,&yl,&xr,&yr);
4712: h = yl + .95*(yr - yl);
4713: PetscDrawStringCentered(draw,.5*(xl+xr),h,PETSC_DRAW_BLACK,time);
4714: PetscDrawFlush(draw);
4715: return(0);
4716: }
4720: /*@C
4721: TSMonitorDrawSolutionPhase - Monitors progress of the TS solvers by plotting the solution as a phase diagram
4723: Collective on TS
4725: Input Parameters:
4726: + ts - the TS context
4727: . step - current time-step
4728: . ptime - current time
4729: - dummy - either a viewer or NULL
4731: Level: intermediate
4733: .keywords: TS, vector, monitor, view
4735: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView()
4736: @*/
4737: PetscErrorCode TSMonitorDrawSolutionPhase(TS ts,PetscInt step,PetscReal ptime,Vec u,void *dummy)
4738: {
4739: PetscErrorCode ierr;
4740: TSMonitorDrawCtx ictx = (TSMonitorDrawCtx)dummy;
4741: PetscDraw draw;
4742: PetscDrawAxis axis;
4743: PetscInt n;
4744: PetscMPIInt size;
4745: PetscReal U0,U1,xl,yl,xr,yr,h;
4746: char time[32];
4747: const PetscScalar *U;
4750: MPI_Comm_size(PetscObjectComm((PetscObject)ts),&size);
4751: if (size != 1) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"Only allowed for sequential runs");
4752: VecGetSize(u,&n);
4753: if (n != 2) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"Only for ODEs with two unknowns");
4755: PetscViewerDrawGetDraw(ictx->viewer,0,&draw);
4756: PetscViewerDrawGetDrawAxis(ictx->viewer,0,&axis);
4757: PetscDrawAxisGetLimits(axis,&xl,&xr,&yl,&yr);
4758: if (!step) {
4759: PetscDrawClear(draw);
4760: PetscDrawAxisDraw(axis);
4761: }
4763: VecGetArrayRead(u,&U);
4764: U0 = PetscRealPart(U[0]);
4765: U1 = PetscRealPart(U[1]);
4766: VecRestoreArrayRead(u,&U);
4767: if ((U0 < xl) || (U1 < yl) || (U0 > xr) || (U1 > yr)) return(0);
4769: PetscDrawCollectiveBegin(draw);
4770: PetscDrawPoint(draw,U0,U1,PETSC_DRAW_BLACK);
4771: if (ictx->showtimestepandtime) {
4772: PetscDrawGetCoordinates(draw,&xl,&yl,&xr,&yr);
4773: PetscSNPrintf(time,32,"Timestep %d Time %g",(int)step,(double)ptime);
4774: h = yl + .95*(yr - yl);
4775: PetscDrawStringCentered(draw,.5*(xl+xr),h,PETSC_DRAW_BLACK,time);
4776: }
4777: PetscDrawCollectiveEnd(draw);
4778: PetscDrawFlush(draw);
4779: PetscDrawSave(draw);
4780: return(0);
4781: }
4786: /*@C
4787: TSMonitorDrawCtxDestroy - Destroys the monitor context for TSMonitorDrawSolution()
4789: Collective on TS
4791: Input Parameters:
4792: . ctx - the monitor context
4794: Level: intermediate
4796: .keywords: TS, vector, monitor, view
4798: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorDrawSolution(), TSMonitorDrawError()
4799: @*/
4800: PetscErrorCode TSMonitorDrawCtxDestroy(TSMonitorDrawCtx *ictx)
4801: {
4805: PetscViewerDestroy(&(*ictx)->viewer);
4806: VecDestroy(&(*ictx)->initialsolution);
4807: PetscFree(*ictx);
4808: return(0);
4809: }
4813: /*@C
4814: TSMonitorDrawCtxCreate - Creates the monitor context for TSMonitorDrawCtx
4816: Collective on TS
4818: Input Parameter:
4819: . ts - time-step context
4821: Output Patameter:
4822: . ctx - the monitor context
4824: Options Database:
4825: . -ts_monitor_draw_solution_initial - show initial solution as well as current solution
4827: Level: intermediate
4829: .keywords: TS, vector, monitor, view
4831: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorDrawCtx()
4832: @*/
4833: PetscErrorCode TSMonitorDrawCtxCreate(MPI_Comm comm,const char host[],const char label[],int x,int y,int m,int n,PetscInt howoften,TSMonitorDrawCtx *ctx)
4834: {
4835: PetscErrorCode ierr;
4838: PetscNew(ctx);
4839: PetscViewerDrawOpen(comm,host,label,x,y,m,n,&(*ctx)->viewer);
4840: PetscViewerSetFromOptions((*ctx)->viewer);
4842: (*ctx)->howoften = howoften;
4843: (*ctx)->showinitial = PETSC_FALSE;
4844: PetscOptionsGetBool(NULL,NULL,"-ts_monitor_draw_solution_initial",&(*ctx)->showinitial,NULL);
4846: (*ctx)->showtimestepandtime = PETSC_FALSE;
4847: PetscOptionsGetBool(NULL,NULL,"-ts_monitor_draw_solution_show_time",&(*ctx)->showtimestepandtime,NULL);
4848: return(0);
4849: }
4853: /*@C
4854: TSMonitorDrawError - Monitors progress of the TS solvers by calling
4855: VecView() for the error at each timestep
4857: Collective on TS
4859: Input Parameters:
4860: + ts - the TS context
4861: . step - current time-step
4862: . ptime - current time
4863: - dummy - either a viewer or NULL
4865: Level: intermediate
4867: .keywords: TS, vector, monitor, view
4869: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView()
4870: @*/
4871: PetscErrorCode TSMonitorDrawError(TS ts,PetscInt step,PetscReal ptime,Vec u,void *dummy)
4872: {
4873: PetscErrorCode ierr;
4874: TSMonitorDrawCtx ctx = (TSMonitorDrawCtx)dummy;
4875: PetscViewer viewer = ctx->viewer;
4876: Vec work;
4879: if (!(((ctx->howoften > 0) && (!(step % ctx->howoften))) || ((ctx->howoften == -1) && ts->reason))) return(0);
4880: VecDuplicate(u,&work);
4881: TSComputeSolutionFunction(ts,ptime,work);
4882: VecAXPY(work,-1.0,u);
4883: VecView(work,viewer);
4884: VecDestroy(&work);
4885: return(0);
4886: }
4888: #include <petsc/private/dmimpl.h>
4891: /*@
4892: TSSetDM - Sets the DM that may be used by some preconditioners
4894: Logically Collective on TS and DM
4896: Input Parameters:
4897: + ts - the preconditioner context
4898: - dm - the dm
4900: Level: intermediate
4903: .seealso: TSGetDM(), SNESSetDM(), SNESGetDM()
4904: @*/
4905: PetscErrorCode TSSetDM(TS ts,DM dm)
4906: {
4908: SNES snes;
4909: DMTS tsdm;
4913: PetscObjectReference((PetscObject)dm);
4914: if (ts->dm) { /* Move the DMTS context over to the new DM unless the new DM already has one */
4915: if (ts->dm->dmts && !dm->dmts) {
4916: DMCopyDMTS(ts->dm,dm);
4917: DMGetDMTS(ts->dm,&tsdm);
4918: if (tsdm->originaldm == ts->dm) { /* Grant write privileges to the replacement DM */
4919: tsdm->originaldm = dm;
4920: }
4921: }
4922: DMDestroy(&ts->dm);
4923: }
4924: ts->dm = dm;
4926: TSGetSNES(ts,&snes);
4927: SNESSetDM(snes,dm);
4928: return(0);
4929: }
4933: /*@
4934: TSGetDM - Gets the DM that may be used by some preconditioners
4936: Not Collective
4938: Input Parameter:
4939: . ts - the preconditioner context
4941: Output Parameter:
4942: . dm - the dm
4944: Level: intermediate
4947: .seealso: TSSetDM(), SNESSetDM(), SNESGetDM()
4948: @*/
4949: PetscErrorCode TSGetDM(TS ts,DM *dm)
4950: {
4955: if (!ts->dm) {
4956: DMShellCreate(PetscObjectComm((PetscObject)ts),&ts->dm);
4957: if (ts->snes) {SNESSetDM(ts->snes,ts->dm);}
4958: }
4959: *dm = ts->dm;
4960: return(0);
4961: }
4965: /*@
4966: SNESTSFormFunction - Function to evaluate nonlinear residual
4968: Logically Collective on SNES
4970: Input Parameter:
4971: + snes - nonlinear solver
4972: . U - the current state at which to evaluate the residual
4973: - ctx - user context, must be a TS
4975: Output Parameter:
4976: . F - the nonlinear residual
4978: Notes:
4979: This function is not normally called by users and is automatically registered with the SNES used by TS.
4980: It is most frequently passed to MatFDColoringSetFunction().
4982: Level: advanced
4984: .seealso: SNESSetFunction(), MatFDColoringSetFunction()
4985: @*/
4986: PetscErrorCode SNESTSFormFunction(SNES snes,Vec U,Vec F,void *ctx)
4987: {
4988: TS ts = (TS)ctx;
4996: (ts->ops->snesfunction)(snes,U,F,ts);
4997: return(0);
4998: }
5002: /*@
5003: SNESTSFormJacobian - Function to evaluate the Jacobian
5005: Collective on SNES
5007: Input Parameter:
5008: + snes - nonlinear solver
5009: . U - the current state at which to evaluate the residual
5010: - ctx - user context, must be a TS
5012: Output Parameter:
5013: + A - the Jacobian
5014: . B - the preconditioning matrix (may be the same as A)
5015: - flag - indicates any structure change in the matrix
5017: Notes:
5018: This function is not normally called by users and is automatically registered with the SNES used by TS.
5020: Level: developer
5022: .seealso: SNESSetJacobian()
5023: @*/
5024: PetscErrorCode SNESTSFormJacobian(SNES snes,Vec U,Mat A,Mat B,void *ctx)
5025: {
5026: TS ts = (TS)ctx;
5037: (ts->ops->snesjacobian)(snes,U,A,B,ts);
5038: return(0);
5039: }
5043: /*@C
5044: TSComputeRHSFunctionLinear - Evaluate the right hand side via the user-provided Jacobian, for linear problems Udot = A U only
5046: Collective on TS
5048: Input Arguments:
5049: + ts - time stepping context
5050: . t - time at which to evaluate
5051: . U - state at which to evaluate
5052: - ctx - context
5054: Output Arguments:
5055: . F - right hand side
5057: Level: intermediate
5059: Notes:
5060: This function is intended to be passed to TSSetRHSFunction() to evaluate the right hand side for linear problems.
5061: The matrix (and optionally the evaluation context) should be passed to TSSetRHSJacobian().
5063: .seealso: TSSetRHSFunction(), TSSetRHSJacobian(), TSComputeRHSJacobianConstant()
5064: @*/
5065: PetscErrorCode TSComputeRHSFunctionLinear(TS ts,PetscReal t,Vec U,Vec F,void *ctx)
5066: {
5068: Mat Arhs,Brhs;
5071: TSGetRHSMats_Private(ts,&Arhs,&Brhs);
5072: TSComputeRHSJacobian(ts,t,U,Arhs,Brhs);
5073: MatMult(Arhs,U,F);
5074: return(0);
5075: }
5079: /*@C
5080: TSComputeRHSJacobianConstant - Reuses a Jacobian that is time-independent.
5082: Collective on TS
5084: Input Arguments:
5085: + ts - time stepping context
5086: . t - time at which to evaluate
5087: . U - state at which to evaluate
5088: - ctx - context
5090: Output Arguments:
5091: + A - pointer to operator
5092: . B - pointer to preconditioning matrix
5093: - flg - matrix structure flag
5095: Level: intermediate
5097: Notes:
5098: This function is intended to be passed to TSSetRHSJacobian() to evaluate the Jacobian for linear time-independent problems.
5100: .seealso: TSSetRHSFunction(), TSSetRHSJacobian(), TSComputeRHSFunctionLinear()
5101: @*/
5102: PetscErrorCode TSComputeRHSJacobianConstant(TS ts,PetscReal t,Vec U,Mat A,Mat B,void *ctx)
5103: {
5105: return(0);
5106: }
5110: /*@C
5111: TSComputeIFunctionLinear - Evaluate the left hand side via the user-provided Jacobian, for linear problems only
5113: Collective on TS
5115: Input Arguments:
5116: + ts - time stepping context
5117: . t - time at which to evaluate
5118: . U - state at which to evaluate
5119: . Udot - time derivative of state vector
5120: - ctx - context
5122: Output Arguments:
5123: . F - left hand side
5125: Level: intermediate
5127: Notes:
5128: 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
5129: user is required to write their own TSComputeIFunction.
5130: This function is intended to be passed to TSSetIFunction() to evaluate the left hand side for linear problems.
5131: The matrix (and optionally the evaluation context) should be passed to TSSetIJacobian().
5133: Note that using this function is NOT equivalent to using TSComputeRHSFunctionLinear() since that solves Udot = A U
5135: .seealso: TSSetIFunction(), TSSetIJacobian(), TSComputeIJacobianConstant(), TSComputeRHSFunctionLinear()
5136: @*/
5137: PetscErrorCode TSComputeIFunctionLinear(TS ts,PetscReal t,Vec U,Vec Udot,Vec F,void *ctx)
5138: {
5140: Mat A,B;
5143: TSGetIJacobian(ts,&A,&B,NULL,NULL);
5144: TSComputeIJacobian(ts,t,U,Udot,1.0,A,B,PETSC_TRUE);
5145: MatMult(A,Udot,F);
5146: return(0);
5147: }
5151: /*@C
5152: TSComputeIJacobianConstant - Reuses a time-independent for a semi-implicit DAE or ODE
5154: Collective on TS
5156: Input Arguments:
5157: + ts - time stepping context
5158: . t - time at which to evaluate
5159: . U - state at which to evaluate
5160: . Udot - time derivative of state vector
5161: . shift - shift to apply
5162: - ctx - context
5164: Output Arguments:
5165: + A - pointer to operator
5166: . B - pointer to preconditioning matrix
5167: - flg - matrix structure flag
5169: Level: advanced
5171: Notes:
5172: This function is intended to be passed to TSSetIJacobian() to evaluate the Jacobian for linear time-independent problems.
5174: It is only appropriate for problems of the form
5176: $ M Udot = F(U,t)
5178: where M is constant and F is non-stiff. The user must pass M to TSSetIJacobian(). The current implementation only
5179: works with IMEX time integration methods such as TSROSW and TSARKIMEX, since there is no support for de-constructing
5180: an implicit operator of the form
5182: $ shift*M + J
5184: 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
5185: a copy of M or reassemble it when requested.
5187: .seealso: TSSetIFunction(), TSSetIJacobian(), TSComputeIFunctionLinear()
5188: @*/
5189: PetscErrorCode TSComputeIJacobianConstant(TS ts,PetscReal t,Vec U,Vec Udot,PetscReal shift,Mat A,Mat B,void *ctx)
5190: {
5194: MatScale(A, shift / ts->ijacobian.shift);
5195: ts->ijacobian.shift = shift;
5196: return(0);
5197: }
5201: /*@
5202: TSGetEquationType - Gets the type of the equation that TS is solving.
5204: Not Collective
5206: Input Parameter:
5207: . ts - the TS context
5209: Output Parameter:
5210: . equation_type - see TSEquationType
5212: Level: beginner
5214: .keywords: TS, equation type
5216: .seealso: TSSetEquationType(), TSEquationType
5217: @*/
5218: PetscErrorCode TSGetEquationType(TS ts,TSEquationType *equation_type)
5219: {
5223: *equation_type = ts->equation_type;
5224: return(0);
5225: }
5229: /*@
5230: TSSetEquationType - Sets the type of the equation that TS is solving.
5232: Not Collective
5234: Input Parameter:
5235: + ts - the TS context
5236: - equation_type - see TSEquationType
5238: Level: advanced
5240: .keywords: TS, equation type
5242: .seealso: TSGetEquationType(), TSEquationType
5243: @*/
5244: PetscErrorCode TSSetEquationType(TS ts,TSEquationType equation_type)
5245: {
5248: ts->equation_type = equation_type;
5249: return(0);
5250: }
5254: /*@
5255: TSGetConvergedReason - Gets the reason the TS iteration was stopped.
5257: Not Collective
5259: Input Parameter:
5260: . ts - the TS context
5262: Output Parameter:
5263: . reason - negative value indicates diverged, positive value converged, see TSConvergedReason or the
5264: manual pages for the individual convergence tests for complete lists
5266: Level: beginner
5268: Notes:
5269: Can only be called after the call to TSSolve() is complete.
5271: .keywords: TS, nonlinear, set, convergence, test
5273: .seealso: TSSetConvergenceTest(), TSConvergedReason
5274: @*/
5275: PetscErrorCode TSGetConvergedReason(TS ts,TSConvergedReason *reason)
5276: {
5280: *reason = ts->reason;
5281: return(0);
5282: }
5286: /*@
5287: TSSetConvergedReason - Sets the reason for handling the convergence of TSSolve.
5289: Not Collective
5291: Input Parameter:
5292: + ts - the TS context
5293: . reason - negative value indicates diverged, positive value converged, see TSConvergedReason or the
5294: manual pages for the individual convergence tests for complete lists
5296: Level: advanced
5298: Notes:
5299: Can only be called during TSSolve() is active.
5301: .keywords: TS, nonlinear, set, convergence, test
5303: .seealso: TSConvergedReason
5304: @*/
5305: PetscErrorCode TSSetConvergedReason(TS ts,TSConvergedReason reason)
5306: {
5309: ts->reason = reason;
5310: return(0);
5311: }
5315: /*@
5316: TSGetSolveTime - Gets the time after a call to TSSolve()
5318: Not Collective
5320: Input Parameter:
5321: . ts - the TS context
5323: Output Parameter:
5324: . ftime - the final time. This time corresponds to the final time set with TSSetDuration()
5326: Level: beginner
5328: Notes:
5329: Can only be called after the call to TSSolve() is complete.
5331: .keywords: TS, nonlinear, set, convergence, test
5333: .seealso: TSSetConvergenceTest(), TSConvergedReason
5334: @*/
5335: PetscErrorCode TSGetSolveTime(TS ts,PetscReal *ftime)
5336: {
5340: *ftime = ts->solvetime;
5341: return(0);
5342: }
5346: /*@
5347: TSGetTotalSteps - Gets the total number of steps done since the last call to TSSetUp() or TSCreate()
5349: Not Collective
5351: Input Parameter:
5352: . ts - the TS context
5354: Output Parameter:
5355: . steps - the number of steps
5357: Level: beginner
5359: Notes:
5360: Includes the number of steps for all calls to TSSolve() since TSSetUp() was called
5362: .keywords: TS, nonlinear, set, convergence, test
5364: .seealso: TSSetConvergenceTest(), TSConvergedReason
5365: @*/
5366: PetscErrorCode TSGetTotalSteps(TS ts,PetscInt *steps)
5367: {
5371: *steps = ts->total_steps;
5372: return(0);
5373: }
5377: /*@
5378: TSGetSNESIterations - Gets the total number of nonlinear iterations
5379: used by the time integrator.
5381: Not Collective
5383: Input Parameter:
5384: . ts - TS context
5386: Output Parameter:
5387: . nits - number of nonlinear iterations
5389: Notes:
5390: This counter is reset to zero for each successive call to TSSolve().
5392: Level: intermediate
5394: .keywords: TS, get, number, nonlinear, iterations
5396: .seealso: TSGetKSPIterations()
5397: @*/
5398: PetscErrorCode TSGetSNESIterations(TS ts,PetscInt *nits)
5399: {
5403: *nits = ts->snes_its;
5404: return(0);
5405: }
5409: /*@
5410: TSGetKSPIterations - Gets the total number of linear iterations
5411: used by the time integrator.
5413: Not Collective
5415: Input Parameter:
5416: . ts - TS context
5418: Output Parameter:
5419: . lits - number of linear iterations
5421: Notes:
5422: This counter is reset to zero for each successive call to TSSolve().
5424: Level: intermediate
5426: .keywords: TS, get, number, linear, iterations
5428: .seealso: TSGetSNESIterations(), SNESGetKSPIterations()
5429: @*/
5430: PetscErrorCode TSGetKSPIterations(TS ts,PetscInt *lits)
5431: {
5435: *lits = ts->ksp_its;
5436: return(0);
5437: }
5441: /*@
5442: TSGetStepRejections - Gets the total number of rejected steps.
5444: Not Collective
5446: Input Parameter:
5447: . ts - TS context
5449: Output Parameter:
5450: . rejects - number of steps rejected
5452: Notes:
5453: This counter is reset to zero for each successive call to TSSolve().
5455: Level: intermediate
5457: .keywords: TS, get, number
5459: .seealso: TSGetSNESIterations(), TSGetKSPIterations(), TSSetMaxStepRejections(), TSGetSNESFailures(), TSSetMaxSNESFailures(), TSSetErrorIfStepFails()
5460: @*/
5461: PetscErrorCode TSGetStepRejections(TS ts,PetscInt *rejects)
5462: {
5466: *rejects = ts->reject;
5467: return(0);
5468: }
5472: /*@
5473: TSGetSNESFailures - Gets the total number of failed SNES solves
5475: Not Collective
5477: Input Parameter:
5478: . ts - TS context
5480: Output Parameter:
5481: . fails - number of failed nonlinear solves
5483: Notes:
5484: This counter is reset to zero for each successive call to TSSolve().
5486: Level: intermediate
5488: .keywords: TS, get, number
5490: .seealso: TSGetSNESIterations(), TSGetKSPIterations(), TSSetMaxStepRejections(), TSGetStepRejections(), TSSetMaxSNESFailures()
5491: @*/
5492: PetscErrorCode TSGetSNESFailures(TS ts,PetscInt *fails)
5493: {
5497: *fails = ts->num_snes_failures;
5498: return(0);
5499: }
5503: /*@
5504: TSSetMaxStepRejections - Sets the maximum number of step rejections before a step fails
5506: Not Collective
5508: Input Parameter:
5509: + ts - TS context
5510: - rejects - maximum number of rejected steps, pass -1 for unlimited
5512: Notes:
5513: The counter is reset to zero for each step
5515: Options Database Key:
5516: . -ts_max_reject - Maximum number of step rejections before a step fails
5518: Level: intermediate
5520: .keywords: TS, set, maximum, number
5522: .seealso: TSGetSNESIterations(), TSGetKSPIterations(), TSSetMaxSNESFailures(), TSGetStepRejections(), TSGetSNESFailures(), TSSetErrorIfStepFails(), TSGetConvergedReason()
5523: @*/
5524: PetscErrorCode TSSetMaxStepRejections(TS ts,PetscInt rejects)
5525: {
5528: ts->max_reject = rejects;
5529: return(0);
5530: }
5534: /*@
5535: TSSetMaxSNESFailures - Sets the maximum number of failed SNES solves
5537: Not Collective
5539: Input Parameter:
5540: + ts - TS context
5541: - fails - maximum number of failed nonlinear solves, pass -1 for unlimited
5543: Notes:
5544: The counter is reset to zero for each successive call to TSSolve().
5546: Options Database Key:
5547: . -ts_max_snes_failures - Maximum number of nonlinear solve failures
5549: Level: intermediate
5551: .keywords: TS, set, maximum, number
5553: .seealso: TSGetSNESIterations(), TSGetKSPIterations(), TSSetMaxStepRejections(), TSGetStepRejections(), TSGetSNESFailures(), SNESGetConvergedReason(), TSGetConvergedReason()
5554: @*/
5555: PetscErrorCode TSSetMaxSNESFailures(TS ts,PetscInt fails)
5556: {
5559: ts->max_snes_failures = fails;
5560: return(0);
5561: }
5565: /*@
5566: TSSetErrorIfStepFails - Error if no step succeeds
5568: Not Collective
5570: Input Parameter:
5571: + ts - TS context
5572: - err - PETSC_TRUE to error if no step succeeds, PETSC_FALSE to return without failure
5574: Options Database Key:
5575: . -ts_error_if_step_fails - Error if no step succeeds
5577: Level: intermediate
5579: .keywords: TS, set, error
5581: .seealso: TSGetSNESIterations(), TSGetKSPIterations(), TSSetMaxStepRejections(), TSGetStepRejections(), TSGetSNESFailures(), TSSetErrorIfStepFails(), TSGetConvergedReason()
5582: @*/
5583: PetscErrorCode TSSetErrorIfStepFails(TS ts,PetscBool err)
5584: {
5587: ts->errorifstepfailed = err;
5588: return(0);
5589: }
5593: /*@C
5594: 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
5596: Collective on TS
5598: Input Parameters:
5599: + ts - the TS context
5600: . step - current time-step
5601: . ptime - current time
5602: . u - current state
5603: - vf - viewer and its format
5605: Level: intermediate
5607: .keywords: TS, vector, monitor, view
5609: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView()
5610: @*/
5611: PetscErrorCode TSMonitorSolution(TS ts,PetscInt step,PetscReal ptime,Vec u,PetscViewerAndFormat *vf)
5612: {
5616: PetscViewerPushFormat(vf->viewer,vf->format);
5617: VecView(u,vf->viewer);
5618: PetscViewerPopFormat(vf->viewer);
5619: return(0);
5620: }
5624: /*@C
5625: TSMonitorSolutionVTK - Monitors progress of the TS solvers by VecView() for the solution at each timestep.
5627: Collective on TS
5629: Input Parameters:
5630: + ts - the TS context
5631: . step - current time-step
5632: . ptime - current time
5633: . u - current state
5634: - filenametemplate - string containing a format specifier for the integer time step (e.g. %03D)
5636: Level: intermediate
5638: Notes:
5639: 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.
5640: These are named according to the file name template.
5642: This function is normally passed as an argument to TSMonitorSet() along with TSMonitorSolutionVTKDestroy().
5644: .keywords: TS, vector, monitor, view
5646: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView()
5647: @*/
5648: PetscErrorCode TSMonitorSolutionVTK(TS ts,PetscInt step,PetscReal ptime,Vec u,void *filenametemplate)
5649: {
5651: char filename[PETSC_MAX_PATH_LEN];
5652: PetscViewer viewer;
5655: if (step < 0) return(0); /* -1 indicates interpolated solution */
5656: PetscSNPrintf(filename,sizeof(filename),(const char*)filenametemplate,step);
5657: PetscViewerVTKOpen(PetscObjectComm((PetscObject)ts),filename,FILE_MODE_WRITE,&viewer);
5658: VecView(u,viewer);
5659: PetscViewerDestroy(&viewer);
5660: return(0);
5661: }
5665: /*@C
5666: TSMonitorSolutionVTKDestroy - Destroy context for monitoring
5668: Collective on TS
5670: Input Parameters:
5671: . filenametemplate - string containing a format specifier for the integer time step (e.g. %03D)
5673: Level: intermediate
5675: Note:
5676: This function is normally passed to TSMonitorSet() along with TSMonitorSolutionVTK().
5678: .keywords: TS, vector, monitor, view
5680: .seealso: TSMonitorSet(), TSMonitorSolutionVTK()
5681: @*/
5682: PetscErrorCode TSMonitorSolutionVTKDestroy(void *filenametemplate)
5683: {
5687: PetscFree(*(char**)filenametemplate);
5688: return(0);
5689: }
5693: /*@
5694: TSGetAdapt - Get the adaptive controller context for the current method
5696: Collective on TS if controller has not been created yet
5698: Input Arguments:
5699: . ts - time stepping context
5701: Output Arguments:
5702: . adapt - adaptive controller
5704: Level: intermediate
5706: .seealso: TSAdapt, TSAdaptSetType(), TSAdaptChoose()
5707: @*/
5708: PetscErrorCode TSGetAdapt(TS ts,TSAdapt *adapt)
5709: {
5715: if (!ts->adapt) {
5716: TSAdaptCreate(PetscObjectComm((PetscObject)ts),&ts->adapt);
5717: PetscLogObjectParent((PetscObject)ts,(PetscObject)ts->adapt);
5718: PetscObjectIncrementTabLevel((PetscObject)ts->adapt,(PetscObject)ts,1);
5719: }
5720: *adapt = ts->adapt;
5721: return(0);
5722: }
5726: /*@
5727: TSSetTolerances - Set tolerances for local truncation error when using adaptive controller
5729: Logically Collective
5731: Input Arguments:
5732: + ts - time integration context
5733: . atol - scalar absolute tolerances, PETSC_DECIDE to leave current value
5734: . vatol - vector of absolute tolerances or NULL, used in preference to atol if present
5735: . rtol - scalar relative tolerances, PETSC_DECIDE to leave current value
5736: - vrtol - vector of relative tolerances or NULL, used in preference to atol if present
5738: Options Database keys:
5739: + -ts_rtol <rtol> - relative tolerance for local truncation error
5740: - -ts_atol <atol> Absolute tolerance for local truncation error
5742: Notes:
5743: With PETSc's implicit schemes for DAE problems, the calculation of the local truncation error
5744: (LTE) includes both the differential and the algebraic variables. If one wants the LTE to be
5745: computed only for the differential or the algebraic part then this can be done using the vector of
5746: tolerances vatol. For example, by setting the tolerance vector with the desired tolerance for the
5747: differential part and infinity for the algebraic part, the LTE calculation will include only the
5748: differential variables.
5750: Level: beginner
5752: .seealso: TS, TSAdapt, TSVecNormWRMS(), TSGetTolerances()
5753: @*/
5754: PetscErrorCode TSSetTolerances(TS ts,PetscReal atol,Vec vatol,PetscReal rtol,Vec vrtol)
5755: {
5759: if (atol != PETSC_DECIDE && atol != PETSC_DEFAULT) ts->atol = atol;
5760: if (vatol) {
5761: PetscObjectReference((PetscObject)vatol);
5762: VecDestroy(&ts->vatol);
5763: ts->vatol = vatol;
5764: }
5765: if (rtol != PETSC_DECIDE && rtol != PETSC_DEFAULT) ts->rtol = rtol;
5766: if (vrtol) {
5767: PetscObjectReference((PetscObject)vrtol);
5768: VecDestroy(&ts->vrtol);
5769: ts->vrtol = vrtol;
5770: }
5771: return(0);
5772: }
5776: /*@
5777: TSGetTolerances - Get tolerances for local truncation error when using adaptive controller
5779: Logically Collective
5781: Input Arguments:
5782: . ts - time integration context
5784: Output Arguments:
5785: + atol - scalar absolute tolerances, NULL to ignore
5786: . vatol - vector of absolute tolerances, NULL to ignore
5787: . rtol - scalar relative tolerances, NULL to ignore
5788: - vrtol - vector of relative tolerances, NULL to ignore
5790: Level: beginner
5792: .seealso: TS, TSAdapt, TSVecNormWRMS(), TSSetTolerances()
5793: @*/
5794: PetscErrorCode TSGetTolerances(TS ts,PetscReal *atol,Vec *vatol,PetscReal *rtol,Vec *vrtol)
5795: {
5797: if (atol) *atol = ts->atol;
5798: if (vatol) *vatol = ts->vatol;
5799: if (rtol) *rtol = ts->rtol;
5800: if (vrtol) *vrtol = ts->vrtol;
5801: return(0);
5802: }
5806: /*@
5807: TSErrorWeightedNorm2 - compute a weighted 2-norm of the difference between two state vectors
5809: Collective on TS
5811: Input Arguments:
5812: + ts - time stepping context
5813: . U - state vector, usually ts->vec_sol
5814: - Y - state vector to be compared to U
5816: Output Arguments:
5817: . norm - weighted norm, a value of 1.0 is considered small
5819: Level: developer
5821: .seealso: TSErrorWeightedNorm(), TSErrorWeightedNormInfinity()
5822: @*/
5823: PetscErrorCode TSErrorWeightedNorm2(TS ts,Vec U,Vec Y,PetscReal *norm)
5824: {
5825: PetscErrorCode ierr;
5826: PetscInt i,n,N,rstart;
5827: const PetscScalar *u,*y;
5828: PetscReal sum,gsum;
5829: PetscReal tol;
5839: if (U == Y) SETERRQ(PetscObjectComm((PetscObject)U),PETSC_ERR_ARG_IDN,"U and Y cannot be the same vector");
5841: VecGetSize(U,&N);
5842: VecGetLocalSize(U,&n);
5843: VecGetOwnershipRange(U,&rstart,NULL);
5844: VecGetArrayRead(U,&u);
5845: VecGetArrayRead(Y,&y);
5846: sum = 0.;
5847: if (ts->vatol && ts->vrtol) {
5848: const PetscScalar *atol,*rtol;
5849: VecGetArrayRead(ts->vatol,&atol);
5850: VecGetArrayRead(ts->vrtol,&rtol);
5851: for (i=0; i<n; i++) {
5852: tol = PetscRealPart(atol[i]) + PetscRealPart(rtol[i]) * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
5853: sum += PetscSqr(PetscAbsScalar(y[i] - u[i]) / tol);
5854: }
5855: VecRestoreArrayRead(ts->vatol,&atol);
5856: VecRestoreArrayRead(ts->vrtol,&rtol);
5857: } else if (ts->vatol) { /* vector atol, scalar rtol */
5858: const PetscScalar *atol;
5859: VecGetArrayRead(ts->vatol,&atol);
5860: for (i=0; i<n; i++) {
5861: tol = PetscRealPart(atol[i]) + ts->rtol * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
5862: sum += PetscSqr(PetscAbsScalar(y[i] - u[i]) / tol);
5863: }
5864: VecRestoreArrayRead(ts->vatol,&atol);
5865: } else if (ts->vrtol) { /* scalar atol, vector rtol */
5866: const PetscScalar *rtol;
5867: VecGetArrayRead(ts->vrtol,&rtol);
5868: for (i=0; i<n; i++) {
5869: tol = ts->atol + PetscRealPart(rtol[i]) * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
5870: sum += PetscSqr(PetscAbsScalar(y[i] - u[i]) / tol);
5871: }
5872: VecRestoreArrayRead(ts->vrtol,&rtol);
5873: } else { /* scalar atol, scalar rtol */
5874: for (i=0; i<n; i++) {
5875: tol = ts->atol + ts->rtol * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
5876: sum += PetscSqr(PetscAbsScalar(y[i] - u[i]) / tol);
5877: }
5878: }
5879: VecRestoreArrayRead(U,&u);
5880: VecRestoreArrayRead(Y,&y);
5882: MPIU_Allreduce(&sum,&gsum,1,MPIU_REAL,MPIU_SUM,PetscObjectComm((PetscObject)ts));
5883: *norm = PetscSqrtReal(gsum / N);
5885: if (PetscIsInfOrNanScalar(*norm)) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_FP,"Infinite or not-a-number generated in norm");
5886: return(0);
5887: }
5891: /*@
5892: TSErrorWeightedNormInfinity - compute a weighted infinity-norm of the difference between two state vectors
5894: Collective on TS
5896: Input Arguments:
5897: + ts - time stepping context
5898: . U - state vector, usually ts->vec_sol
5899: - Y - state vector to be compared to U
5901: Output Arguments:
5902: . norm - weighted norm, a value of 1.0 is considered small
5904: Level: developer
5906: .seealso: TSErrorWeightedNorm(), TSErrorWeightedNorm2()
5907: @*/
5908: PetscErrorCode TSErrorWeightedNormInfinity(TS ts,Vec U,Vec Y,PetscReal *norm)
5909: {
5910: PetscErrorCode ierr;
5911: PetscInt i,n,N,rstart,k;
5912: const PetscScalar *u,*y;
5913: PetscReal max,gmax;
5914: PetscReal tol;
5924: if (U == Y) SETERRQ(PetscObjectComm((PetscObject)U),PETSC_ERR_ARG_IDN,"U and Y cannot be the same vector");
5926: VecGetSize(U,&N);
5927: VecGetLocalSize(U,&n);
5928: VecGetOwnershipRange(U,&rstart,NULL);
5929: VecGetArrayRead(U,&u);
5930: VecGetArrayRead(Y,&y);
5931: if (ts->vatol && ts->vrtol) {
5932: const PetscScalar *atol,*rtol;
5933: VecGetArrayRead(ts->vatol,&atol);
5934: VecGetArrayRead(ts->vrtol,&rtol);
5935: k = 0;
5936: tol = PetscRealPart(atol[k]) + PetscRealPart(rtol[k]) * PetscMax(PetscAbsScalar(u[k]),PetscAbsScalar(y[k]));
5937: max = PetscAbsScalar(y[k] - u[k]) / tol;
5938: for (i=1; i<n; i++) {
5939: tol = PetscRealPart(atol[i]) + PetscRealPart(rtol[i]) * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
5940: max = PetscMax(max,PetscAbsScalar(y[i] - u[i]) / tol);
5941: }
5942: VecRestoreArrayRead(ts->vatol,&atol);
5943: VecRestoreArrayRead(ts->vrtol,&rtol);
5944: } else if (ts->vatol) { /* vector atol, scalar rtol */
5945: const PetscScalar *atol;
5946: VecGetArrayRead(ts->vatol,&atol);
5947: k = 0;
5948: tol = PetscRealPart(atol[k]) + ts->rtol * PetscMax(PetscAbsScalar(u[k]),PetscAbsScalar(y[k]));
5949: max = PetscAbsScalar(y[k] - u[k]) / tol;
5950: for (i=1; i<n; i++) {
5951: tol = PetscRealPart(atol[i]) + ts->rtol * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
5952: max = PetscMax(max,PetscAbsScalar(y[i] - u[i]) / tol);
5953: }
5954: VecRestoreArrayRead(ts->vatol,&atol);
5955: } else if (ts->vrtol) { /* scalar atol, vector rtol */
5956: const PetscScalar *rtol;
5957: VecGetArrayRead(ts->vrtol,&rtol);
5958: k = 0;
5959: tol = ts->atol + PetscRealPart(rtol[k]) * PetscMax(PetscAbsScalar(u[k]),PetscAbsScalar(y[k]));
5960: max = PetscAbsScalar(y[k] - u[k]) / tol;
5961: for (i=1; i<n; i++) {
5962: tol = ts->atol + PetscRealPart(rtol[i]) * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
5963: max = PetscMax(max,PetscAbsScalar(y[i] - u[i]) / tol);
5964: }
5965: VecRestoreArrayRead(ts->vrtol,&rtol);
5966: } else { /* scalar atol, scalar rtol */
5967: k = 0;
5968: tol = ts->atol + ts->rtol * PetscMax(PetscAbsScalar(u[k]),PetscAbsScalar(y[k]));
5969: max = PetscAbsScalar(y[k] - u[k]) / tol;
5970: for (i=1; i<n; i++) {
5971: tol = ts->atol + ts->rtol * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
5972: max = PetscMax(max,PetscAbsScalar(y[i] - u[i]) / tol);
5973: }
5974: }
5975: VecRestoreArrayRead(U,&u);
5976: VecRestoreArrayRead(Y,&y);
5978: MPIU_Allreduce(&max,&gmax,1,MPIU_REAL,MPIU_MAX,PetscObjectComm((PetscObject)ts));
5979: *norm = gmax;
5981: if (PetscIsInfOrNanScalar(*norm)) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_FP,"Infinite or not-a-number generated in norm");
5982: return(0);
5983: }
5987: /*@
5988: TSErrorWeightedNorm - compute a weighted norm of the difference between two state vectors
5990: Collective on TS
5992: Input Arguments:
5993: + ts - time stepping context
5994: . U - state vector, usually ts->vec_sol
5995: . Y - state vector to be compared to U
5996: - wnormtype - norm type, either NORM_2 or NORM_INFINITY
5998: Output Arguments:
5999: . norm - weighted norm, a value of 1.0 is considered small
6002: Options Database Keys:
6003: . -ts_adapt_wnormtype <wnormtype> - 2, INFINITY
6005: Level: developer
6007: .seealso: TSErrorWeightedNormInfinity(), TSErrorWeightedNorm2()
6008: @*/
6009: PetscErrorCode TSErrorWeightedNorm(TS ts,Vec U,Vec Y,NormType wnormtype,PetscReal *norm)
6010: {
6014: if (wnormtype == NORM_2) {
6015: TSErrorWeightedNorm2(ts,U,Y,norm);
6016: } else if(wnormtype == NORM_INFINITY) {
6017: TSErrorWeightedNormInfinity(ts,U,Y,norm);
6018: } else SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"No support for norm type %s",NormTypes[wnormtype]);
6019: return(0);
6020: }
6024: /*@
6025: TSSetCFLTimeLocal - Set the local CFL constraint relative to forward Euler
6027: Logically Collective on TS
6029: Input Arguments:
6030: + ts - time stepping context
6031: - cfltime - maximum stable time step if using forward Euler (value can be different on each process)
6033: Note:
6034: After calling this function, the global CFL time can be obtained by calling TSGetCFLTime()
6036: Level: intermediate
6038: .seealso: TSGetCFLTime(), TSADAPTCFL
6039: @*/
6040: PetscErrorCode TSSetCFLTimeLocal(TS ts,PetscReal cfltime)
6041: {
6044: ts->cfltime_local = cfltime;
6045: ts->cfltime = -1.;
6046: return(0);
6047: }
6051: /*@
6052: TSGetCFLTime - Get the maximum stable time step according to CFL criteria applied to forward Euler
6054: Collective on TS
6056: Input Arguments:
6057: . ts - time stepping context
6059: Output Arguments:
6060: . cfltime - maximum stable time step for forward Euler
6062: Level: advanced
6064: .seealso: TSSetCFLTimeLocal()
6065: @*/
6066: PetscErrorCode TSGetCFLTime(TS ts,PetscReal *cfltime)
6067: {
6071: if (ts->cfltime < 0) {
6072: MPIU_Allreduce(&ts->cfltime_local,&ts->cfltime,1,MPIU_REAL,MPIU_MIN,PetscObjectComm((PetscObject)ts));
6073: }
6074: *cfltime = ts->cfltime;
6075: return(0);
6076: }
6080: /*@
6081: TSVISetVariableBounds - Sets the lower and upper bounds for the solution vector. xl <= x <= xu
6083: Input Parameters:
6084: . ts - the TS context.
6085: . xl - lower bound.
6086: . xu - upper bound.
6088: Notes:
6089: If this routine is not called then the lower and upper bounds are set to
6090: PETSC_NINFINITY and PETSC_INFINITY respectively during SNESSetUp().
6092: Level: advanced
6094: @*/
6095: PetscErrorCode TSVISetVariableBounds(TS ts, Vec xl, Vec xu)
6096: {
6098: SNES snes;
6101: TSGetSNES(ts,&snes);
6102: SNESVISetVariableBounds(snes,xl,xu);
6103: return(0);
6104: }
6106: #if defined(PETSC_HAVE_MATLAB_ENGINE)
6107: #include <mex.h>
6109: typedef struct {char *funcname; mxArray *ctx;} TSMatlabContext;
6113: /*
6114: TSComputeFunction_Matlab - Calls the function that has been set with
6115: TSSetFunctionMatlab().
6117: Collective on TS
6119: Input Parameters:
6120: + snes - the TS context
6121: - u - input vector
6123: Output Parameter:
6124: . y - function vector, as set by TSSetFunction()
6126: Notes:
6127: TSComputeFunction() is typically used within nonlinear solvers
6128: implementations, so most users would not generally call this routine
6129: themselves.
6131: Level: developer
6133: .keywords: TS, nonlinear, compute, function
6135: .seealso: TSSetFunction(), TSGetFunction()
6136: */
6137: PetscErrorCode TSComputeFunction_Matlab(TS snes,PetscReal time,Vec u,Vec udot,Vec y, void *ctx)
6138: {
6139: PetscErrorCode ierr;
6140: TSMatlabContext *sctx = (TSMatlabContext*)ctx;
6141: int nlhs = 1,nrhs = 7;
6142: mxArray *plhs[1],*prhs[7];
6143: long long int lx = 0,lxdot = 0,ly = 0,ls = 0;
6153: PetscMemcpy(&ls,&snes,sizeof(snes));
6154: PetscMemcpy(&lx,&u,sizeof(u));
6155: PetscMemcpy(&lxdot,&udot,sizeof(udot));
6156: PetscMemcpy(&ly,&y,sizeof(u));
6158: prhs[0] = mxCreateDoubleScalar((double)ls);
6159: prhs[1] = mxCreateDoubleScalar(time);
6160: prhs[2] = mxCreateDoubleScalar((double)lx);
6161: prhs[3] = mxCreateDoubleScalar((double)lxdot);
6162: prhs[4] = mxCreateDoubleScalar((double)ly);
6163: prhs[5] = mxCreateString(sctx->funcname);
6164: prhs[6] = sctx->ctx;
6165: mexCallMATLAB(nlhs,plhs,nrhs,prhs,"PetscTSComputeFunctionInternal");
6166: mxGetScalar(plhs[0]);
6167: mxDestroyArray(prhs[0]);
6168: mxDestroyArray(prhs[1]);
6169: mxDestroyArray(prhs[2]);
6170: mxDestroyArray(prhs[3]);
6171: mxDestroyArray(prhs[4]);
6172: mxDestroyArray(prhs[5]);
6173: mxDestroyArray(plhs[0]);
6174: return(0);
6175: }
6180: /*
6181: TSSetFunctionMatlab - Sets the function evaluation routine and function
6182: vector for use by the TS routines in solving ODEs
6183: equations from MATLAB. Here the function is a string containing the name of a MATLAB function
6185: Logically Collective on TS
6187: Input Parameters:
6188: + ts - the TS context
6189: - func - function evaluation routine
6191: Calling sequence of func:
6192: $ func (TS ts,PetscReal time,Vec u,Vec udot,Vec f,void *ctx);
6194: Level: beginner
6196: .keywords: TS, nonlinear, set, function
6198: .seealso: TSGetFunction(), TSComputeFunction(), TSSetJacobian(), TSSetFunction()
6199: */
6200: PetscErrorCode TSSetFunctionMatlab(TS ts,const char *func,mxArray *ctx)
6201: {
6202: PetscErrorCode ierr;
6203: TSMatlabContext *sctx;
6206: /* currently sctx is memory bleed */
6207: PetscMalloc(sizeof(TSMatlabContext),&sctx);
6208: PetscStrallocpy(func,&sctx->funcname);
6209: /*
6210: This should work, but it doesn't
6211: sctx->ctx = ctx;
6212: mexMakeArrayPersistent(sctx->ctx);
6213: */
6214: sctx->ctx = mxDuplicateArray(ctx);
6216: TSSetIFunction(ts,NULL,TSComputeFunction_Matlab,sctx);
6217: return(0);
6218: }
6222: /*
6223: TSComputeJacobian_Matlab - Calls the function that has been set with
6224: TSSetJacobianMatlab().
6226: Collective on TS
6228: Input Parameters:
6229: + ts - the TS context
6230: . u - input vector
6231: . A, B - the matrices
6232: - ctx - user context
6234: Level: developer
6236: .keywords: TS, nonlinear, compute, function
6238: .seealso: TSSetFunction(), TSGetFunction()
6239: @*/
6240: PetscErrorCode TSComputeJacobian_Matlab(TS ts,PetscReal time,Vec u,Vec udot,PetscReal shift,Mat A,Mat B,void *ctx)
6241: {
6242: PetscErrorCode ierr;
6243: TSMatlabContext *sctx = (TSMatlabContext*)ctx;
6244: int nlhs = 2,nrhs = 9;
6245: mxArray *plhs[2],*prhs[9];
6246: long long int lx = 0,lxdot = 0,lA = 0,ls = 0, lB = 0;
6252: /* call Matlab function in ctx with arguments u and y */
6254: PetscMemcpy(&ls,&ts,sizeof(ts));
6255: PetscMemcpy(&lx,&u,sizeof(u));
6256: PetscMemcpy(&lxdot,&udot,sizeof(u));
6257: PetscMemcpy(&lA,A,sizeof(u));
6258: PetscMemcpy(&lB,B,sizeof(u));
6260: prhs[0] = mxCreateDoubleScalar((double)ls);
6261: prhs[1] = mxCreateDoubleScalar((double)time);
6262: prhs[2] = mxCreateDoubleScalar((double)lx);
6263: prhs[3] = mxCreateDoubleScalar((double)lxdot);
6264: prhs[4] = mxCreateDoubleScalar((double)shift);
6265: prhs[5] = mxCreateDoubleScalar((double)lA);
6266: prhs[6] = mxCreateDoubleScalar((double)lB);
6267: prhs[7] = mxCreateString(sctx->funcname);
6268: prhs[8] = sctx->ctx;
6269: mexCallMATLAB(nlhs,plhs,nrhs,prhs,"PetscTSComputeJacobianInternal");
6270: mxGetScalar(plhs[0]);
6271: mxDestroyArray(prhs[0]);
6272: mxDestroyArray(prhs[1]);
6273: mxDestroyArray(prhs[2]);
6274: mxDestroyArray(prhs[3]);
6275: mxDestroyArray(prhs[4]);
6276: mxDestroyArray(prhs[5]);
6277: mxDestroyArray(prhs[6]);
6278: mxDestroyArray(prhs[7]);
6279: mxDestroyArray(plhs[0]);
6280: mxDestroyArray(plhs[1]);
6281: return(0);
6282: }
6287: /*
6288: TSSetJacobianMatlab - Sets the Jacobian function evaluation routine and two empty Jacobian matrices
6289: 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
6291: Logically Collective on TS
6293: Input Parameters:
6294: + ts - the TS context
6295: . A,B - Jacobian matrices
6296: . func - function evaluation routine
6297: - ctx - user context
6299: Calling sequence of func:
6300: $ flag = func (TS ts,PetscReal time,Vec u,Vec udot,Mat A,Mat B,void *ctx);
6303: Level: developer
6305: .keywords: TS, nonlinear, set, function
6307: .seealso: TSGetFunction(), TSComputeFunction(), TSSetJacobian(), TSSetFunction()
6308: */
6309: PetscErrorCode TSSetJacobianMatlab(TS ts,Mat A,Mat B,const char *func,mxArray *ctx)
6310: {
6311: PetscErrorCode ierr;
6312: TSMatlabContext *sctx;
6315: /* currently sctx is memory bleed */
6316: PetscMalloc(sizeof(TSMatlabContext),&sctx);
6317: PetscStrallocpy(func,&sctx->funcname);
6318: /*
6319: This should work, but it doesn't
6320: sctx->ctx = ctx;
6321: mexMakeArrayPersistent(sctx->ctx);
6322: */
6323: sctx->ctx = mxDuplicateArray(ctx);
6325: TSSetIJacobian(ts,A,B,TSComputeJacobian_Matlab,sctx);
6326: return(0);
6327: }
6331: /*
6332: TSMonitor_Matlab - Calls the function that has been set with TSMonitorSetMatlab().
6334: Collective on TS
6336: .seealso: TSSetFunction(), TSGetFunction()
6337: @*/
6338: PetscErrorCode TSMonitor_Matlab(TS ts,PetscInt it, PetscReal time,Vec u, void *ctx)
6339: {
6340: PetscErrorCode ierr;
6341: TSMatlabContext *sctx = (TSMatlabContext*)ctx;
6342: int nlhs = 1,nrhs = 6;
6343: mxArray *plhs[1],*prhs[6];
6344: long long int lx = 0,ls = 0;
6350: PetscMemcpy(&ls,&ts,sizeof(ts));
6351: PetscMemcpy(&lx,&u,sizeof(u));
6353: prhs[0] = mxCreateDoubleScalar((double)ls);
6354: prhs[1] = mxCreateDoubleScalar((double)it);
6355: prhs[2] = mxCreateDoubleScalar((double)time);
6356: prhs[3] = mxCreateDoubleScalar((double)lx);
6357: prhs[4] = mxCreateString(sctx->funcname);
6358: prhs[5] = sctx->ctx;
6359: mexCallMATLAB(nlhs,plhs,nrhs,prhs,"PetscTSMonitorInternal");
6360: mxGetScalar(plhs[0]);
6361: mxDestroyArray(prhs[0]);
6362: mxDestroyArray(prhs[1]);
6363: mxDestroyArray(prhs[2]);
6364: mxDestroyArray(prhs[3]);
6365: mxDestroyArray(prhs[4]);
6366: mxDestroyArray(plhs[0]);
6367: return(0);
6368: }
6373: /*
6374: TSMonitorSetMatlab - Sets the monitor function from Matlab
6376: Level: developer
6378: .keywords: TS, nonlinear, set, function
6380: .seealso: TSGetFunction(), TSComputeFunction(), TSSetJacobian(), TSSetFunction()
6381: */
6382: PetscErrorCode TSMonitorSetMatlab(TS ts,const char *func,mxArray *ctx)
6383: {
6384: PetscErrorCode ierr;
6385: TSMatlabContext *sctx;
6388: /* currently sctx is memory bleed */
6389: PetscMalloc(sizeof(TSMatlabContext),&sctx);
6390: PetscStrallocpy(func,&sctx->funcname);
6391: /*
6392: This should work, but it doesn't
6393: sctx->ctx = ctx;
6394: mexMakeArrayPersistent(sctx->ctx);
6395: */
6396: sctx->ctx = mxDuplicateArray(ctx);
6398: TSMonitorSet(ts,TSMonitor_Matlab,sctx,NULL);
6399: return(0);
6400: }
6401: #endif
6405: /*@C
6406: TSMonitorLGSolution - Monitors progress of the TS solvers by plotting each component of the solution vector
6407: in a time based line graph
6409: Collective on TS
6411: Input Parameters:
6412: + ts - the TS context
6413: . step - current time-step
6414: . ptime - current time
6415: . u - current solution
6416: - dctx - the TSMonitorLGCtx object that contains all the options for the monitoring, this is created with TSMonitorLGCtxCreate()
6418: Options Database:
6419: . -ts_monitor_lg_solution_variables
6421: Level: intermediate
6423: Notes: Each process in a parallel run displays its component solutions in a separate window
6425: .keywords: TS, vector, monitor, view
6427: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorLGCtxCreate(), TSMonitorLGCtxSetVariableNames(), TSMonitorLGCtxGetVariableNames(),
6428: TSMonitorLGSetVariableNames(), TSMonitorLGGetVariableNames(), TSMonitorLGSetDisplayVariables(), TSMonitorLGCtxSetDisplayVariables(),
6429: TSMonitorLGCtxSetTransform(), TSMonitorLGSetTransform(), TSMonitorLGError(), TSMonitorLGSNESIterations(), TSMonitorLGKSPIterations(),
6430: TSMonitorEnvelopeCtxCreate(), TSMonitorEnvelopeGetBounds(), TSMonitorEnvelopeCtxDestroy(), TSMonitorEnvelop()
6431: @*/
6432: PetscErrorCode TSMonitorLGSolution(TS ts,PetscInt step,PetscReal ptime,Vec u,void *dctx)
6433: {
6434: PetscErrorCode ierr;
6435: TSMonitorLGCtx ctx = (TSMonitorLGCtx)dctx;
6436: const PetscScalar *yy;
6437: Vec v;
6440: if (step < 0) return(0); /* -1 indicates interpolated solution */
6441: if (!step) {
6442: PetscDrawAxis axis;
6443: PetscInt dim;
6444: PetscDrawLGGetAxis(ctx->lg,&axis);
6445: PetscDrawAxisSetLabels(axis,"Solution as function of time","Time","Solution");
6446: if (ctx->names && !ctx->displaynames) {
6447: char **displaynames;
6448: PetscBool flg;
6449: VecGetLocalSize(u,&dim);
6450: PetscMalloc((dim+1)*sizeof(char*),&displaynames);
6451: PetscMemzero(displaynames,(dim+1)*sizeof(char*));
6452: PetscOptionsGetStringArray(((PetscObject)ts)->options,((PetscObject)ts)->prefix,"-ts_monitor_lg_solution_variables",displaynames,&dim,&flg);
6453: if (flg) {
6454: TSMonitorLGCtxSetDisplayVariables(ctx,(const char *const *)displaynames);
6455: }
6456: PetscStrArrayDestroy(&displaynames);
6457: }
6458: if (ctx->displaynames) {
6459: PetscDrawLGSetDimension(ctx->lg,ctx->ndisplayvariables);
6460: PetscDrawLGSetLegend(ctx->lg,(const char *const *)ctx->displaynames);
6461: } else if (ctx->names) {
6462: VecGetLocalSize(u,&dim);
6463: PetscDrawLGSetDimension(ctx->lg,dim);
6464: PetscDrawLGSetLegend(ctx->lg,(const char *const *)ctx->names);
6465: } else {
6466: VecGetLocalSize(u,&dim);
6467: PetscDrawLGSetDimension(ctx->lg,dim);
6468: }
6469: PetscDrawLGReset(ctx->lg);
6470: }
6472: if (!ctx->transform) v = u;
6473: else {(*ctx->transform)(ctx->transformctx,u,&v);}
6474: VecGetArrayRead(v,&yy);
6475: if (ctx->displaynames) {
6476: PetscInt i;
6477: for (i=0; i<ctx->ndisplayvariables; i++)
6478: ctx->displayvalues[i] = PetscRealPart(yy[ctx->displayvariables[i]]);
6479: PetscDrawLGAddCommonPoint(ctx->lg,ptime,ctx->displayvalues);
6480: } else {
6481: #if defined(PETSC_USE_COMPLEX)
6482: PetscInt i,n;
6483: PetscReal *yreal;
6484: VecGetLocalSize(v,&n);
6485: PetscMalloc1(n,&yreal);
6486: for (i=0; i<n; i++) yreal[i] = PetscRealPart(yy[i]);
6487: PetscDrawLGAddCommonPoint(ctx->lg,ptime,yreal);
6488: PetscFree(yreal);
6489: #else
6490: PetscDrawLGAddCommonPoint(ctx->lg,ptime,yy);
6491: #endif
6492: }
6493: VecRestoreArrayRead(v,&yy);
6494: if (ctx->transform) {VecDestroy(&v);}
6496: if (((ctx->howoften > 0) && (!(step % ctx->howoften))) || ((ctx->howoften == -1) && ts->reason)) {
6497: PetscDrawLGDraw(ctx->lg);
6498: PetscDrawLGSave(ctx->lg);
6499: }
6500: return(0);
6501: }
6506: /*@C
6507: TSMonitorLGSetVariableNames - 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: Notes: If the TS object does not have a TSMonitorLGCtx associated with it then this function is ignored
6519: .keywords: TS, vector, monitor, view
6521: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorLGSetDisplayVariables(), TSMonitorLGCtxSetVariableNames()
6522: @*/
6523: PetscErrorCode TSMonitorLGSetVariableNames(TS ts,const char * const *names)
6524: {
6525: PetscErrorCode ierr;
6526: PetscInt i;
6529: for (i=0; i<ts->numbermonitors; i++) {
6530: if (ts->monitor[i] == TSMonitorLGSolution) {
6531: TSMonitorLGCtxSetVariableNames((TSMonitorLGCtx)ts->monitorcontext[i],names);
6532: break;
6533: }
6534: }
6535: return(0);
6536: }
6540: /*@C
6541: TSMonitorLGCtxSetVariableNames - Sets the name of each component in the solution vector so that it may be displayed in the plot
6543: Collective on TS
6545: Input Parameters:
6546: + ts - the TS context
6547: - names - the names of the components, final string must be NULL
6549: Level: intermediate
6551: .keywords: TS, vector, monitor, view
6553: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorLGSetDisplayVariables(), TSMonitorLGSetVariableNames()
6554: @*/
6555: PetscErrorCode TSMonitorLGCtxSetVariableNames(TSMonitorLGCtx ctx,const char * const *names)
6556: {
6557: PetscErrorCode ierr;
6560: PetscStrArrayDestroy(&ctx->names);
6561: PetscStrArrayallocpy(names,&ctx->names);
6562: return(0);
6563: }
6567: /*@C
6568: TSMonitorLGGetVariableNames - Gets the name of each component in the solution vector so that it may be displayed in the plot
6570: Collective on TS
6572: Input Parameter:
6573: . ts - the TS context
6575: Output Parameter:
6576: . names - the names of the components, final string must be NULL
6578: Level: intermediate
6580: Notes: If the TS object does not have a TSMonitorLGCtx associated with it then this function is ignored
6582: .keywords: TS, vector, monitor, view
6584: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorLGSetDisplayVariables()
6585: @*/
6586: PetscErrorCode TSMonitorLGGetVariableNames(TS ts,const char *const **names)
6587: {
6588: PetscInt i;
6591: *names = NULL;
6592: for (i=0; i<ts->numbermonitors; i++) {
6593: if (ts->monitor[i] == TSMonitorLGSolution) {
6594: TSMonitorLGCtx ctx = (TSMonitorLGCtx) ts->monitorcontext[i];
6595: *names = (const char *const *)ctx->names;
6596: break;
6597: }
6598: }
6599: return(0);
6600: }
6604: /*@C
6605: TSMonitorLGCtxSetDisplayVariables - Sets the variables that are to be display in the monitor
6607: Collective on TS
6609: Input Parameters:
6610: + ctx - the TSMonitorLG context
6611: . displaynames - the names of the components, final string must be NULL
6613: Level: intermediate
6615: .keywords: TS, vector, monitor, view
6617: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorLGSetVariableNames()
6618: @*/
6619: PetscErrorCode TSMonitorLGCtxSetDisplayVariables(TSMonitorLGCtx ctx,const char * const *displaynames)
6620: {
6621: PetscInt j = 0,k;
6622: PetscErrorCode ierr;
6625: if (!ctx->names) return(0);
6626: PetscStrArrayDestroy(&ctx->displaynames);
6627: PetscStrArrayallocpy(displaynames,&ctx->displaynames);
6628: while (displaynames[j]) j++;
6629: ctx->ndisplayvariables = j;
6630: PetscMalloc1(ctx->ndisplayvariables,&ctx->displayvariables);
6631: PetscMalloc1(ctx->ndisplayvariables,&ctx->displayvalues);
6632: j = 0;
6633: while (displaynames[j]) {
6634: k = 0;
6635: while (ctx->names[k]) {
6636: PetscBool flg;
6637: PetscStrcmp(displaynames[j],ctx->names[k],&flg);
6638: if (flg) {
6639: ctx->displayvariables[j] = k;
6640: break;
6641: }
6642: k++;
6643: }
6644: j++;
6645: }
6646: return(0);
6647: }
6652: /*@C
6653: TSMonitorLGSetDisplayVariables - Sets the variables that are to be display in the monitor
6655: Collective on TS
6657: Input Parameters:
6658: + ts - the TS context
6659: . displaynames - the names of the components, final string must be NULL
6661: Notes: If the TS object does not have a TSMonitorLGCtx associated with it then this function is ignored
6663: Level: intermediate
6665: .keywords: TS, vector, monitor, view
6667: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorLGSetVariableNames()
6668: @*/
6669: PetscErrorCode TSMonitorLGSetDisplayVariables(TS ts,const char * const *displaynames)
6670: {
6671: PetscInt i;
6672: PetscErrorCode ierr;
6675: for (i=0; i<ts->numbermonitors; i++) {
6676: if (ts->monitor[i] == TSMonitorLGSolution) {
6677: TSMonitorLGCtxSetDisplayVariables((TSMonitorLGCtx)ts->monitorcontext[i],displaynames);
6678: break;
6679: }
6680: }
6681: return(0);
6682: }
6686: /*@C
6687: TSMonitorLGSetTransform - Solution vector will be transformed by provided function before being displayed
6689: Collective on TS
6691: Input Parameters:
6692: + ts - the TS context
6693: . transform - the transform function
6694: . destroy - function to destroy the optional context
6695: - ctx - optional context used by transform function
6697: Notes: If the TS object does not have a TSMonitorLGCtx associated with it then this function is ignored
6699: Level: intermediate
6701: .keywords: TS, vector, monitor, view
6703: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorLGSetVariableNames(), TSMonitorLGCtxSetTransform()
6704: @*/
6705: PetscErrorCode TSMonitorLGSetTransform(TS ts,PetscErrorCode (*transform)(void*,Vec,Vec*),PetscErrorCode (*destroy)(void*),void *tctx)
6706: {
6707: PetscInt i;
6708: PetscErrorCode ierr;
6711: for (i=0; i<ts->numbermonitors; i++) {
6712: if (ts->monitor[i] == TSMonitorLGSolution) {
6713: TSMonitorLGCtxSetTransform((TSMonitorLGCtx)ts->monitorcontext[i],transform,destroy,tctx);
6714: }
6715: }
6716: return(0);
6717: }
6721: /*@C
6722: TSMonitorLGCtxSetTransform - Solution vector will be transformed by provided function before being displayed
6724: Collective on TSLGCtx
6726: Input Parameters:
6727: + ts - the TS context
6728: . transform - the transform function
6729: . destroy - function to destroy the optional context
6730: - ctx - optional context used by transform function
6732: Level: intermediate
6734: .keywords: TS, vector, monitor, view
6736: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorLGSetVariableNames(), TSMonitorLGSetTransform()
6737: @*/
6738: PetscErrorCode TSMonitorLGCtxSetTransform(TSMonitorLGCtx ctx,PetscErrorCode (*transform)(void*,Vec,Vec*),PetscErrorCode (*destroy)(void*),void *tctx)
6739: {
6741: ctx->transform = transform;
6742: ctx->transformdestroy = destroy;
6743: ctx->transformctx = tctx;
6744: return(0);
6745: }
6749: /*@C
6750: TSMonitorLGError - Monitors progress of the TS solvers by plotting each component of the solution vector
6751: in a time based line graph
6753: Collective on TS
6755: Input Parameters:
6756: + ts - the TS context
6757: . step - current time-step
6758: . ptime - current time
6759: . u - current solution
6760: - dctx - TSMonitorLGCtx object created with TSMonitorLGCtxCreate()
6762: Level: intermediate
6764: Notes: Each process in a parallel run displays its component errors in a separate window
6766: The user must provide the solution using TSSetSolutionFunction() to use this monitor.
6768: Options Database Keys:
6769: . -ts_monitor_lg_error - create a graphical monitor of error history
6771: .keywords: TS, vector, monitor, view
6773: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSSetSolutionFunction()
6774: @*/
6775: PetscErrorCode TSMonitorLGError(TS ts,PetscInt step,PetscReal ptime,Vec u,void *dummy)
6776: {
6777: PetscErrorCode ierr;
6778: TSMonitorLGCtx ctx = (TSMonitorLGCtx)dummy;
6779: const PetscScalar *yy;
6780: Vec y;
6783: if (!step) {
6784: PetscDrawAxis axis;
6785: PetscInt dim;
6786: PetscDrawLGGetAxis(ctx->lg,&axis);
6787: PetscDrawAxisSetLabels(axis,"Error in solution as function of time","Time","Solution");
6788: VecGetLocalSize(u,&dim);
6789: PetscDrawLGSetDimension(ctx->lg,dim);
6790: PetscDrawLGReset(ctx->lg);
6791: }
6792: VecDuplicate(u,&y);
6793: TSComputeSolutionFunction(ts,ptime,y);
6794: VecAXPY(y,-1.0,u);
6795: VecGetArrayRead(y,&yy);
6796: #if defined(PETSC_USE_COMPLEX)
6797: {
6798: PetscReal *yreal;
6799: PetscInt i,n;
6800: VecGetLocalSize(y,&n);
6801: PetscMalloc1(n,&yreal);
6802: for (i=0; i<n; i++) yreal[i] = PetscRealPart(yy[i]);
6803: PetscDrawLGAddCommonPoint(ctx->lg,ptime,yreal);
6804: PetscFree(yreal);
6805: }
6806: #else
6807: PetscDrawLGAddCommonPoint(ctx->lg,ptime,yy);
6808: #endif
6809: VecRestoreArrayRead(y,&yy);
6810: VecDestroy(&y);
6811: if (((ctx->howoften > 0) && (!(step % ctx->howoften))) || ((ctx->howoften == -1) && ts->reason)) {
6812: PetscDrawLGDraw(ctx->lg);
6813: PetscDrawLGSave(ctx->lg);
6814: }
6815: return(0);
6816: }
6820: PetscErrorCode TSMonitorLGSNESIterations(TS ts,PetscInt n,PetscReal ptime,Vec v,void *monctx)
6821: {
6822: TSMonitorLGCtx ctx = (TSMonitorLGCtx) monctx;
6823: PetscReal x = ptime,y;
6825: PetscInt its;
6828: if (n < 0) return(0); /* -1 indicates interpolated solution */
6829: if (!n) {
6830: PetscDrawAxis axis;
6831: PetscDrawLGGetAxis(ctx->lg,&axis);
6832: PetscDrawAxisSetLabels(axis,"Nonlinear iterations as function of time","Time","SNES Iterations");
6833: PetscDrawLGReset(ctx->lg);
6834: ctx->snes_its = 0;
6835: }
6836: TSGetSNESIterations(ts,&its);
6837: y = its - ctx->snes_its;
6838: PetscDrawLGAddPoint(ctx->lg,&x,&y);
6839: if (((ctx->howoften > 0) && (!(n % ctx->howoften)) && (n > -1)) || ((ctx->howoften == -1) && (n == -1))) {
6840: PetscDrawLGDraw(ctx->lg);
6841: PetscDrawLGSave(ctx->lg);
6842: }
6843: ctx->snes_its = its;
6844: return(0);
6845: }
6849: PetscErrorCode TSMonitorLGKSPIterations(TS ts,PetscInt n,PetscReal ptime,Vec v,void *monctx)
6850: {
6851: TSMonitorLGCtx ctx = (TSMonitorLGCtx) monctx;
6852: PetscReal x = ptime,y;
6854: PetscInt its;
6857: if (n < 0) return(0); /* -1 indicates interpolated solution */
6858: if (!n) {
6859: PetscDrawAxis axis;
6860: PetscDrawLGGetAxis(ctx->lg,&axis);
6861: PetscDrawAxisSetLabels(axis,"Linear iterations as function of time","Time","KSP Iterations");
6862: PetscDrawLGReset(ctx->lg);
6863: ctx->ksp_its = 0;
6864: }
6865: TSGetKSPIterations(ts,&its);
6866: y = its - ctx->ksp_its;
6867: PetscDrawLGAddPoint(ctx->lg,&x,&y);
6868: if (((ctx->howoften > 0) && (!(n % ctx->howoften)) && (n > -1)) || ((ctx->howoften == -1) && (n == -1))) {
6869: PetscDrawLGDraw(ctx->lg);
6870: PetscDrawLGSave(ctx->lg);
6871: }
6872: ctx->ksp_its = its;
6873: return(0);
6874: }
6878: /*@
6879: TSComputeLinearStability - computes the linear stability function at a point
6881: Collective on TS and Vec
6883: Input Parameters:
6884: + ts - the TS context
6885: - xr,xi - real and imaginary part of input arguments
6887: Output Parameters:
6888: . yr,yi - real and imaginary part of function value
6890: Level: developer
6892: .keywords: TS, compute
6894: .seealso: TSSetRHSFunction(), TSComputeIFunction()
6895: @*/
6896: PetscErrorCode TSComputeLinearStability(TS ts,PetscReal xr,PetscReal xi,PetscReal *yr,PetscReal *yi)
6897: {
6902: if (!ts->ops->linearstability) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"Linearized stability function not provided for this method");
6903: (*ts->ops->linearstability)(ts,xr,xi,yr,yi);
6904: return(0);
6905: }
6907: /* ------------------------------------------------------------------------*/
6910: /*@C
6911: TSMonitorEnvelopeCtxCreate - Creates a context for use with TSMonitorEnvelope()
6913: Collective on TS
6915: Input Parameters:
6916: . ts - the ODE solver object
6918: Output Parameter:
6919: . ctx - the context
6921: Level: intermediate
6923: .keywords: TS, monitor, line graph, residual, seealso
6925: .seealso: TSMonitorLGTimeStep(), TSMonitorSet(), TSMonitorLGSolution(), TSMonitorLGError()
6927: @*/
6928: PetscErrorCode TSMonitorEnvelopeCtxCreate(TS ts,TSMonitorEnvelopeCtx *ctx)
6929: {
6933: PetscNew(ctx);
6934: return(0);
6935: }
6939: /*@C
6940: TSMonitorEnvelope - Monitors the maximum and minimum value of each component of the solution
6942: Collective on TS
6944: Input Parameters:
6945: + ts - the TS context
6946: . step - current time-step
6947: . ptime - current time
6948: . u - current solution
6949: - dctx - the envelope context
6951: Options Database:
6952: . -ts_monitor_envelope
6954: Level: intermediate
6956: Notes: after a solve you can use TSMonitorEnvelopeGetBounds() to access the envelope
6958: .keywords: TS, vector, monitor, view
6960: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorEnvelopeGetBounds(), TSMonitorEnvelopeCtxCreate()
6961: @*/
6962: PetscErrorCode TSMonitorEnvelope(TS ts,PetscInt step,PetscReal ptime,Vec u,void *dctx)
6963: {
6964: PetscErrorCode ierr;
6965: TSMonitorEnvelopeCtx ctx = (TSMonitorEnvelopeCtx)dctx;
6968: if (!ctx->max) {
6969: VecDuplicate(u,&ctx->max);
6970: VecDuplicate(u,&ctx->min);
6971: VecCopy(u,ctx->max);
6972: VecCopy(u,ctx->min);
6973: } else {
6974: VecPointwiseMax(ctx->max,u,ctx->max);
6975: VecPointwiseMin(ctx->min,u,ctx->min);
6976: }
6977: return(0);
6978: }
6983: /*@C
6984: TSMonitorEnvelopeGetBounds - Gets the bounds for the components of the solution
6986: Collective on TS
6988: Input Parameter:
6989: . ts - the TS context
6991: Output Parameter:
6992: + max - the maximum values
6993: - min - the minimum values
6995: Notes: If the TS does not have a TSMonitorEnvelopeCtx associated with it then this function is ignored
6997: Level: intermediate
6999: .keywords: TS, vector, monitor, view
7001: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorLGSetDisplayVariables()
7002: @*/
7003: PetscErrorCode TSMonitorEnvelopeGetBounds(TS ts,Vec *max,Vec *min)
7004: {
7005: PetscInt i;
7008: if (max) *max = NULL;
7009: if (min) *min = NULL;
7010: for (i=0; i<ts->numbermonitors; i++) {
7011: if (ts->monitor[i] == TSMonitorEnvelope) {
7012: TSMonitorEnvelopeCtx ctx = (TSMonitorEnvelopeCtx) ts->monitorcontext[i];
7013: if (max) *max = ctx->max;
7014: if (min) *min = ctx->min;
7015: break;
7016: }
7017: }
7018: return(0);
7019: }
7023: /*@C
7024: TSMonitorEnvelopeCtxDestroy - Destroys a context that was created with TSMonitorEnvelopeCtxCreate().
7026: Collective on TSMonitorEnvelopeCtx
7028: Input Parameter:
7029: . ctx - the monitor context
7031: Level: intermediate
7033: .keywords: TS, monitor, line graph, destroy
7035: .seealso: TSMonitorLGCtxCreate(), TSMonitorSet(), TSMonitorLGTimeStep()
7036: @*/
7037: PetscErrorCode TSMonitorEnvelopeCtxDestroy(TSMonitorEnvelopeCtx *ctx)
7038: {
7042: VecDestroy(&(*ctx)->min);
7043: VecDestroy(&(*ctx)->max);
7044: PetscFree(*ctx);
7045: return(0);
7046: }
7050: /*@
7051: TSRollBack - Rolls back one time step
7053: Collective on TS
7055: Input Parameter:
7056: . ts - the TS context obtained from TSCreate()
7058: Level: advanced
7060: .keywords: TS, timestep, rollback
7062: .seealso: TSCreate(), TSSetUp(), TSDestroy(), TSSolve(), TSSetPreStep(), TSSetPreStage(), TSInterpolate()
7063: @*/
7064: PetscErrorCode TSRollBack(TS ts)
7065: {
7070: if (ts->steprollback) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_ARG_WRONGSTATE,"TSRollBack already called");
7071: if (!ts->ops->rollback) SETERRQ1(PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"TSRollBack not implemented for type '%s'",((PetscObject)ts)->type_name);
7072: (*ts->ops->rollback)(ts);
7073: ts->time_step = ts->ptime - ts->ptime_prev;
7074: ts->ptime = ts->ptime_prev;
7075: ts->ptime_prev = ts->ptime_prev_rollback;
7076: ts->steps--; ts->total_steps--;
7077: ts->steprollback = PETSC_TRUE;
7078: return(0);
7079: }
7083: /*@
7084: TSGetStages - Get the number of stages and stage values
7086: Input Parameter:
7087: . ts - the TS context obtained from TSCreate()
7089: Level: advanced
7091: .keywords: TS, getstages
7093: .seealso: TSCreate()
7094: @*/
7095: PetscErrorCode TSGetStages(TS ts,PetscInt *ns,Vec **Y)
7096: {
7103: if (!ts->ops->getstages) *ns=0;
7104: else {
7105: (*ts->ops->getstages)(ts,ns,Y);
7106: }
7107: return(0);
7108: }
7112: /*@C
7113: TSComputeIJacobianDefaultColor - Computes the Jacobian using finite differences and coloring to exploit matrix sparsity.
7115: Collective on SNES
7117: Input Parameters:
7118: + ts - the TS context
7119: . t - current timestep
7120: . U - state vector
7121: . Udot - time derivative of state vector
7122: . shift - shift to apply, see note below
7123: - ctx - an optional user context
7125: Output Parameters:
7126: + J - Jacobian matrix (not altered in this routine)
7127: - B - newly computed Jacobian matrix to use with preconditioner (generally the same as J)
7129: Level: intermediate
7131: Notes:
7132: If F(t,U,Udot)=0 is the DAE, the required Jacobian is
7134: dF/dU + shift*dF/dUdot
7136: Most users should not need to explicitly call this routine, as it
7137: is used internally within the nonlinear solvers.
7139: This will first try to get the coloring from the DM. If the DM type has no coloring
7140: routine, then it will try to get the coloring from the matrix. This requires that the
7141: matrix have nonzero entries precomputed.
7143: .keywords: TS, finite differences, Jacobian, coloring, sparse
7144: .seealso: TSSetIJacobian(), MatFDColoringCreate(), MatFDColoringSetFunction()
7145: @*/
7146: PetscErrorCode TSComputeIJacobianDefaultColor(TS ts,PetscReal t,Vec U,Vec Udot,PetscReal shift,Mat J,Mat B,void *ctx)
7147: {
7148: SNES snes;
7149: MatFDColoring color;
7150: PetscBool hascolor, matcolor = PETSC_FALSE;
7154: PetscOptionsGetBool(((PetscObject)ts)->options,((PetscObject) ts)->prefix, "-ts_fd_color_use_mat", &matcolor, NULL);
7155: PetscObjectQuery((PetscObject) B, "TSMatFDColoring", (PetscObject *) &color);
7156: if (!color) {
7157: DM dm;
7158: ISColoring iscoloring;
7160: TSGetDM(ts, &dm);
7161: DMHasColoring(dm, &hascolor);
7162: if (hascolor && !matcolor) {
7163: DMCreateColoring(dm, IS_COLORING_GLOBAL, &iscoloring);
7164: MatFDColoringCreate(B, iscoloring, &color);
7165: MatFDColoringSetFunction(color, (PetscErrorCode (*)(void)) SNESTSFormFunction, (void *) ts);
7166: MatFDColoringSetFromOptions(color);
7167: MatFDColoringSetUp(B, iscoloring, color);
7168: ISColoringDestroy(&iscoloring);
7169: } else {
7170: MatColoring mc;
7172: MatColoringCreate(B, &mc);
7173: MatColoringSetDistance(mc, 2);
7174: MatColoringSetType(mc, MATCOLORINGSL);
7175: MatColoringSetFromOptions(mc);
7176: MatColoringApply(mc, &iscoloring);
7177: MatColoringDestroy(&mc);
7178: MatFDColoringCreate(B, iscoloring, &color);
7179: MatFDColoringSetFunction(color, (PetscErrorCode (*)(void)) SNESTSFormFunction, (void *) ts);
7180: MatFDColoringSetFromOptions(color);
7181: MatFDColoringSetUp(B, iscoloring, color);
7182: ISColoringDestroy(&iscoloring);
7183: }
7184: PetscObjectCompose((PetscObject) B, "TSMatFDColoring", (PetscObject) color);
7185: PetscObjectDereference((PetscObject) color);
7186: }
7187: TSGetSNES(ts, &snes);
7188: MatFDColoringApply(B, color, U, snes);
7189: if (J != B) {
7190: MatAssemblyBegin(J, MAT_FINAL_ASSEMBLY);
7191: MatAssemblyEnd(J, MAT_FINAL_ASSEMBLY);
7192: }
7193: return(0);
7194: }
7198: /*@
7199: TSSetFunctionDomainError - Set the function testing if the current state vector is valid
7201: Input Parameters:
7202: ts - the TS context
7203: func - function called within TSFunctionDomainError
7205: Level: intermediate
7207: .keywords: TS, state, domain
7208: .seealso: TSAdaptCheckStage(), TSFunctionDomainError()
7209: @*/
7211: PetscErrorCode TSSetFunctionDomainError(TS ts, PetscErrorCode (*func)(TS,PetscReal,Vec,PetscBool*))
7212: {
7215: ts->functiondomainerror = func;
7216: return(0);
7217: }
7221: /*@
7222: TSFunctionDomainError - Check if the current state is valid
7224: Input Parameters:
7225: ts - the TS context
7226: stagetime - time of the simulation
7227: Y - state vector to check.
7229: Output Parameter:
7230: accept - Set to PETSC_FALSE if the current state vector is valid.
7232: Note:
7233: This function should be used to ensure the state is in a valid part of the space.
7234: For example, one can ensure here all values are positive.
7236: Level: advanced
7237: @*/
7238: PetscErrorCode TSFunctionDomainError(TS ts,PetscReal stagetime,Vec Y,PetscBool* accept)
7239: {
7245: *accept = PETSC_TRUE;
7246: if (ts->functiondomainerror) {
7247: PetscStackCallStandard((*ts->functiondomainerror),(ts,stagetime,Y,accept));
7248: }
7249: return(0);
7250: }
7252: #undef __FUNCT__
7254: /*@C
7255: TSClone - This function clones a time step object.
7257: Collective on MPI_Comm
7259: Input Parameter:
7260: . tsin - The input TS
7262: Output Parameter:
7263: . tsout - The output TS (cloned)
7265: Notes:
7266: 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.
7268: 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);
7270: Level: developer
7272: .keywords: TS, clone
7273: .seealso: TSCreate(), TSSetType(), TSSetUp(), TSDestroy(), TSSetProblemType()
7274: @*/
7275: PetscErrorCode TSClone(TS tsin, TS *tsout)
7276: {
7277: TS t;
7279: SNES snes_start;
7280: DM dm;
7281: TSType type;
7285: *tsout = NULL;
7287: PetscHeaderCreate(t, TS_CLASSID, "TS", "Time stepping", "TS", PetscObjectComm((PetscObject)tsin), TSDestroy, TSView);
7289: /* General TS description */
7290: t->numbermonitors = 0;
7291: t->setupcalled = 0;
7292: t->ksp_its = 0;
7293: t->snes_its = 0;
7294: t->nwork = 0;
7295: t->rhsjacobian.time = -1e20;
7296: t->rhsjacobian.scale = 1.;
7297: t->ijacobian.shift = 1.;
7299: TSGetSNES(tsin,&snes_start);
7300: TSSetSNES(t,snes_start);
7302: TSGetDM(tsin,&dm);
7303: TSSetDM(t,dm);
7305: t->adapt = tsin->adapt;
7306: PetscObjectReference((PetscObject)t->adapt);
7308: t->problem_type = tsin->problem_type;
7309: t->ptime = tsin->ptime;
7310: t->time_step = tsin->time_step;
7311: t->max_time = tsin->max_time;
7312: t->steps = tsin->steps;
7313: t->max_steps = tsin->max_steps;
7314: t->equation_type = tsin->equation_type;
7315: t->atol = tsin->atol;
7316: t->rtol = tsin->rtol;
7317: t->max_snes_failures = tsin->max_snes_failures;
7318: t->max_reject = tsin->max_reject;
7319: t->errorifstepfailed = tsin->errorifstepfailed;
7321: TSGetType(tsin,&type);
7322: TSSetType(t,type);
7324: t->vec_sol = NULL;
7326: t->cfltime = tsin->cfltime;
7327: t->cfltime_local = tsin->cfltime_local;
7328: t->exact_final_time = tsin->exact_final_time;
7330: PetscMemcpy(t->ops,tsin->ops,sizeof(struct _TSOps));
7332: if (((PetscObject)tsin)->fortran_func_pointers) {
7333: PetscInt i;
7334: PetscMalloc((10)*sizeof(void(*)(void)),&((PetscObject)t)->fortran_func_pointers);
7335: for (i=0; i<10; i++) {
7336: ((PetscObject)t)->fortran_func_pointers[i] = ((PetscObject)tsin)->fortran_func_pointers[i];
7337: }
7338: }
7339: *tsout = t;
7340: return(0);
7341: }