Actual source code: irk.c
1: /*
2: Code for timestepping with implicit Runge-Kutta method
4: Notes:
5: The general system is written as
7: F(t,U,Udot) = 0
9: */
10: #include <petsc/private/tsimpl.h>
11: #include <petscdm.h>
12: #include <petscdt.h>
14: static TSIRKType TSIRKDefault = TSIRKGAUSS;
15: static PetscBool TSIRKRegisterAllCalled;
16: static PetscBool TSIRKPackageInitialized;
17: static PetscFunctionList TSIRKList;
19: struct _IRKTableau {
20: PetscReal *A, *b, *c;
21: PetscScalar *A_inv, *A_inv_rowsum, *I_s;
22: PetscReal *binterp; /* Dense output formula */
23: };
25: typedef struct _IRKTableau *IRKTableau;
27: typedef struct {
28: char *method_name;
29: PetscInt order; /* Classical approximation order of the method */
30: PetscInt nstages; /* Number of stages */
31: PetscBool stiffly_accurate;
32: PetscInt pinterp; /* Interpolation order */
33: IRKTableau tableau;
34: Vec U0; /* Backup vector */
35: Vec Z; /* Combined stage vector */
36: Vec *Y; /* States computed during the step */
37: Vec Ydot; /* Work vector holding time derivatives during residual evaluation */
38: Vec U; /* U is used to compute Ydot = shift(Y-U) */
39: Vec *YdotI; /* Work vectors to hold the residual evaluation */
40: Mat TJ; /* KAIJ matrix for the Jacobian of the combined system */
41: Mat M; /* mass matrix dF/dUdot for a DAE, assembled from TSSetMassMatrix(), or NULL for an explicit ODE */
42: PetscScalar *work; /* Scalar work */
43: TSStepStatus status;
44: PetscBool rebuild_completion;
45: PetscReal ccfl;
46: } TS_IRK;
48: /*@
49: TSIRKTableauCreate - create the tableau for `TSIRK` and provide the entries
51: Not Collective
53: Input Parameters:
54: + ts - timestepping context
55: . nstages - number of stages, this is the dimension of the matrices below
56: . A - stage coefficients (dimension `nstages` * `nstages`, row-major)
57: . b - step completion table (dimension `nstages`)
58: . c - abscissa (dimension `nstages`)
59: . binterp - coefficients of the interpolation formula (dimension `nstages`), optional (use `NULL` to skip)
60: . A_inv - inverse of `A` (dimension `nstages` * `nstages`, row-major), optional (use `NULL` to skip)
61: . A_inv_rowsum - row sum of the inverse of `A` (dimension `nstages`), optional (use `NULL` to skip)
62: - I_s - identity matrix (dimension `nstages` * `nstages`), optional (use `NULL` to skip)
64: Level: advanced
66: .seealso: [](ch_ts), `TSIRK`, `TSIRKRegister()`
67: @*/
68: PetscErrorCode TSIRKTableauCreate(TS ts, PetscInt nstages, const PetscReal *A, const PetscReal *b, const PetscReal *c, const PetscReal *binterp, const PetscScalar *A_inv, const PetscScalar *A_inv_rowsum, const PetscScalar *I_s)
69: {
70: TS_IRK *irk = (TS_IRK *)ts->data;
71: IRKTableau tab = irk->tableau;
73: PetscFunctionBegin;
74: irk->order = nstages;
75: PetscCall(PetscMalloc3(PetscSqr(nstages), &tab->A, PetscSqr(nstages), &tab->A_inv, PetscSqr(nstages), &tab->I_s));
76: PetscCall(PetscMalloc4(nstages, &tab->b, nstages, &tab->c, nstages, &tab->binterp, nstages, &tab->A_inv_rowsum));
77: PetscCall(PetscArraycpy(tab->A, A, PetscSqr(nstages)));
78: PetscCall(PetscArraycpy(tab->b, b, nstages));
79: PetscCall(PetscArraycpy(tab->c, c, nstages));
80: /* optional coefficient arrays */
81: if (binterp) PetscCall(PetscArraycpy(tab->binterp, binterp, nstages));
82: if (A_inv) PetscCall(PetscArraycpy(tab->A_inv, A_inv, PetscSqr(nstages)));
83: if (A_inv_rowsum) PetscCall(PetscArraycpy(tab->A_inv_rowsum, A_inv_rowsum, nstages));
84: if (I_s) PetscCall(PetscArraycpy(tab->I_s, I_s, PetscSqr(nstages)));
85: PetscFunctionReturn(PETSC_SUCCESS);
86: }
88: /* Arrays should be freed with PetscFree3(A,b,c) */
89: static PetscErrorCode TSIRKCreate_Gauss(TS ts)
90: {
91: PetscInt nstages;
92: PetscReal *gauss_A_real, *gauss_b, *b, *gauss_c;
93: PetscScalar *gauss_A, *gauss_A_inv, *gauss_A_inv_rowsum, *I_s;
94: PetscScalar *G0, *G1;
95: PetscInt i, j;
96: Mat G0mat, G1mat, Amat;
98: PetscFunctionBegin;
99: PetscCall(TSIRKGetNumStages(ts, &nstages));
100: PetscCall(PetscMalloc3(PetscSqr(nstages), &gauss_A_real, nstages, &gauss_b, nstages, &gauss_c));
101: PetscCall(PetscMalloc4(PetscSqr(nstages), &gauss_A, PetscSqr(nstages), &gauss_A_inv, nstages, &gauss_A_inv_rowsum, PetscSqr(nstages), &I_s));
102: PetscCall(PetscMalloc3(nstages, &b, PetscSqr(nstages), &G0, PetscSqr(nstages), &G1));
103: PetscCall(PetscDTGaussQuadrature(nstages, 0., 1., gauss_c, b));
104: for (i = 0; i < nstages; i++) gauss_b[i] = b[i]; /* copy to possibly-complex array */
106: /* A^T = G0^{-1} G1 */
107: for (i = 0; i < nstages; i++) {
108: for (j = 0; j < nstages; j++) {
109: G0[i * nstages + j] = PetscPowRealInt(gauss_c[i], j);
110: G1[i * nstages + j] = PetscPowRealInt(gauss_c[i], j + 1) / (j + 1);
111: }
112: }
113: /* The arrays above are row-aligned, but we create dense matrices as the transpose */
114: PetscCall(MatCreateSeqDense(PETSC_COMM_SELF, nstages, nstages, G0, &G0mat));
115: PetscCall(MatCreateSeqDense(PETSC_COMM_SELF, nstages, nstages, G1, &G1mat));
116: PetscCall(MatCreateSeqDense(PETSC_COMM_SELF, nstages, nstages, gauss_A, &Amat));
117: PetscCall(MatLUFactor(G0mat, NULL, NULL, NULL));
118: PetscCall(MatMatSolve(G0mat, G1mat, Amat));
119: PetscCall(MatTranspose(Amat, MAT_INPLACE_MATRIX, &Amat));
120: for (i = 0; i < nstages; i++)
121: for (j = 0; j < nstages; j++) gauss_A_real[i * nstages + j] = PetscRealPart(gauss_A[i * nstages + j]);
123: PetscCall(MatDestroy(&G0mat));
124: PetscCall(MatDestroy(&G1mat));
125: PetscCall(MatDestroy(&Amat));
126: PetscCall(PetscFree3(b, G0, G1));
128: { /* Invert A */
129: /* PETSc does not provide a routine to calculate the inverse of a general matrix.
130: * To get the inverse of A, we form a sequential BAIJ matrix from it, consisting of a single block with block size
131: * equal to the dimension of A, and then use MatInvertBlockDiagonal(). */
132: Mat A_baij;
133: PetscInt idxm[1] = {0}, idxn[1] = {0};
134: const PetscScalar *A_inv;
136: PetscCall(MatCreateSeqBAIJ(PETSC_COMM_SELF, nstages, nstages, nstages, 1, NULL, &A_baij));
137: PetscCall(MatSetOption(A_baij, MAT_ROW_ORIENTED, PETSC_FALSE));
138: PetscCall(MatSetValuesBlocked(A_baij, 1, idxm, 1, idxn, gauss_A, INSERT_VALUES));
139: PetscCall(MatAssemblyBegin(A_baij, MAT_FINAL_ASSEMBLY));
140: PetscCall(MatAssemblyEnd(A_baij, MAT_FINAL_ASSEMBLY));
141: PetscCall(MatInvertBlockDiagonal(A_baij, &A_inv));
142: PetscCall(PetscArraycpy(gauss_A_inv, A_inv, nstages * nstages));
143: PetscCall(MatDestroy(&A_baij));
144: }
146: /* Compute row sums A_inv_rowsum and identity I_s */
147: for (i = 0; i < nstages; i++) {
148: gauss_A_inv_rowsum[i] = 0;
149: for (j = 0; j < nstages; j++) {
150: gauss_A_inv_rowsum[i] += gauss_A_inv[i + nstages * j];
151: I_s[i + nstages * j] = 1. * (i == j);
152: }
153: }
154: PetscCall(TSIRKTableauCreate(ts, nstages, gauss_A_real, gauss_b, gauss_c, NULL, gauss_A_inv, gauss_A_inv_rowsum, I_s));
155: PetscCall(PetscFree3(gauss_A_real, gauss_b, gauss_c));
156: PetscCall(PetscFree4(gauss_A, gauss_A_inv, gauss_A_inv_rowsum, I_s));
157: PetscFunctionReturn(PETSC_SUCCESS);
158: }
160: /*@
161: TSIRKRegister - adds a `TSIRK` implementation
163: Not Collective, No Fortran Support
165: Input Parameters:
166: + sname - name of user-defined IRK scheme
167: - function - function to create method context
169: Level: advanced
171: Note:
172: `TSIRKRegister()` may be called multiple times to add several user-defined families.
174: Example Usage:
175: .vb
176: TSIRKRegister("my_scheme", MySchemeCreate);
177: .ve
179: Then, your scheme can be chosen with the procedural interface via
180: .vb
181: TSIRKSetType(ts, "my_scheme")
182: .ve
183: or at runtime via the option
184: .vb
185: -ts_irk_type my_scheme
186: .ve
188: .seealso: [](ch_ts), `TSIRK`, `TSIRKRegisterAll()`
189: @*/
190: PetscErrorCode TSIRKRegister(const char sname[], PetscErrorCode (*function)(TS))
191: {
192: PetscFunctionBegin;
193: PetscCall(TSIRKInitializePackage());
194: PetscCall(PetscFunctionListAdd(&TSIRKList, sname, function));
195: PetscFunctionReturn(PETSC_SUCCESS);
196: }
198: /*@
199: TSIRKRegisterAll - Registers all of the implicit Runge-Kutta methods in `TSIRK`
201: Not Collective, but should be called by all processes which will need the schemes to be registered
203: Level: advanced
205: .seealso: [](ch_ts), `TSIRK`, `TSIRKRegisterDestroy()`
206: @*/
207: PetscErrorCode TSIRKRegisterAll(void)
208: {
209: PetscFunctionBegin;
210: if (TSIRKRegisterAllCalled) PetscFunctionReturn(PETSC_SUCCESS);
211: TSIRKRegisterAllCalled = PETSC_TRUE;
213: PetscCall(TSIRKRegister(TSIRKGAUSS, TSIRKCreate_Gauss));
214: PetscFunctionReturn(PETSC_SUCCESS);
215: }
217: /*@
218: TSIRKRegisterDestroy - Frees the list of schemes that were registered by `TSIRKRegister()`.
220: Not Collective
222: Level: advanced
224: .seealso: [](ch_ts), `TSIRK`, `TSIRKRegister()`, `TSIRKRegisterAll()`
225: @*/
226: PetscErrorCode TSIRKRegisterDestroy(void)
227: {
228: PetscFunctionBegin;
229: TSIRKRegisterAllCalled = PETSC_FALSE;
230: PetscFunctionReturn(PETSC_SUCCESS);
231: }
233: /*@
234: TSIRKInitializePackage - This function initializes everything in the `TSIRK` package. It is called
235: from `TSInitializePackage()`.
237: Level: developer
239: .seealso: [](ch_ts), `TSIRK`, `PetscInitialize()`, `TSIRKFinalizePackage()`, `TSInitializePackage()`
240: @*/
241: PetscErrorCode TSIRKInitializePackage(void)
242: {
243: PetscFunctionBegin;
244: if (TSIRKPackageInitialized) PetscFunctionReturn(PETSC_SUCCESS);
245: TSIRKPackageInitialized = PETSC_TRUE;
246: PetscCall(TSIRKRegisterAll());
247: PetscCall(PetscRegisterFinalize(TSIRKFinalizePackage));
248: PetscFunctionReturn(PETSC_SUCCESS);
249: }
251: /*@
252: TSIRKFinalizePackage - This function destroys everything in the `TSIRK` package. It is
253: called from `PetscFinalize()`.
255: Level: developer
257: .seealso: [](ch_ts), `TSIRK`, `PetscFinalize()`, `TSInitializePackage()`
258: @*/
259: PetscErrorCode TSIRKFinalizePackage(void)
260: {
261: PetscFunctionBegin;
262: PetscCall(PetscFunctionListDestroy(&TSIRKList));
263: TSIRKPackageInitialized = PETSC_FALSE;
264: PetscFunctionReturn(PETSC_SUCCESS);
265: }
267: /*
268: This function can be called before or after ts->vec_sol has been updated.
269: */
270: static PetscErrorCode TSEvaluateStep_IRK(TS ts, PetscInt order, Vec U, PetscBool *done)
271: {
272: TS_IRK *irk = (TS_IRK *)ts->data;
273: IRKTableau tab = irk->tableau;
274: Vec *YdotI = irk->YdotI;
275: PetscScalar *w = irk->work;
276: PetscReal h;
277: PetscInt j;
279: PetscFunctionBegin;
280: switch (irk->status) {
281: case TS_STEP_INCOMPLETE:
282: case TS_STEP_PENDING:
283: h = ts->time_step;
284: break;
285: case TS_STEP_COMPLETE:
286: h = ts->ptime - ts->ptime_prev;
287: break;
288: default:
289: SETERRQ(PetscObjectComm((PetscObject)ts), PETSC_ERR_PLIB, "Invalid TSStepStatus");
290: }
292: PetscCall(VecCopy(ts->vec_sol, U));
293: for (j = 0; j < irk->nstages; j++) w[j] = h * tab->b[j];
294: PetscCall(VecMAXPY(U, irk->nstages, w, YdotI));
295: PetscFunctionReturn(PETSC_SUCCESS);
296: }
298: static PetscErrorCode TSRollBack_IRK(TS ts)
299: {
300: TS_IRK *irk = (TS_IRK *)ts->data;
302: PetscFunctionBegin;
303: PetscCall(VecCopy(irk->U0, ts->vec_sol));
304: PetscFunctionReturn(PETSC_SUCCESS);
305: }
307: static PetscErrorCode TSStep_IRK(TS ts)
308: {
309: TS_IRK *irk = (TS_IRK *)ts->data;
310: IRKTableau tab = irk->tableau;
311: PetscScalar *A_inv = tab->A_inv, *A_inv_rowsum = tab->A_inv_rowsum;
312: const PetscInt nstages = irk->nstages;
313: SNES snes;
314: PetscInt i, j, its, lits;
315: TSAdapt adapt;
316: PetscInt rejections = 0;
317: PetscBool accept = PETSC_TRUE;
318: PetscReal next_time_step = ts->time_step;
320: PetscFunctionBegin;
321: if (!ts->steprollback) PetscCall(VecCopy(ts->vec_sol, irk->U0));
322: for (i = 0; i < nstages; i++) PetscCall(VecStrideScatter(ts->vec_sol, i, irk->Z, INSERT_VALUES));
324: irk->status = TS_STEP_INCOMPLETE;
325: while (!ts->reason && irk->status != TS_STEP_COMPLETE) {
326: PetscCall(VecCopy(ts->vec_sol, irk->U));
327: PetscCall(TSGetSNES(ts, &snes));
328: PetscCall(SNESSolve(snes, NULL, irk->Z));
329: PetscCall(SNESGetIterationNumber(snes, &its));
330: PetscCall(SNESGetLinearSolveIterations(snes, &lits));
331: ts->snes_its += its;
332: ts->ksp_its += lits;
333: for (i = 0; i < nstages; i++) PetscCall(VecStrideGather(irk->Z, i, irk->Y[i], INSERT_VALUES));
334: for (i = 0; i < nstages; i++) {
335: PetscCall(VecZeroEntries(irk->YdotI[i]));
336: for (j = 0; j < nstages; j++) PetscCall(VecAXPY(irk->YdotI[i], A_inv[i + j * nstages] / ts->time_step, irk->Y[j]));
337: PetscCall(VecAXPY(irk->YdotI[i], -A_inv_rowsum[i] / ts->time_step, irk->U));
338: }
339: irk->status = TS_STEP_INCOMPLETE;
340: PetscCall(TSEvaluateStep_IRK(ts, irk->order, ts->vec_sol, NULL));
341: irk->status = TS_STEP_PENDING;
342: PetscCall(TSGetAdapt(ts, &adapt));
343: PetscCall(TSAdaptChoose(adapt, ts, ts->time_step, NULL, &next_time_step, &accept));
344: irk->status = accept ? TS_STEP_COMPLETE : TS_STEP_INCOMPLETE;
345: if (!accept) {
346: PetscCall(TSRollBack_IRK(ts));
347: ts->time_step = next_time_step;
348: goto reject_step;
349: }
351: ts->ptime += ts->time_step;
352: ts->time_step = next_time_step;
353: break;
354: reject_step:
355: ts->reject++;
356: accept = PETSC_FALSE;
357: if (!ts->reason && ++rejections > ts->max_reject && ts->max_reject >= 0) {
358: ts->reason = TS_DIVERGED_STEP_REJECTED;
359: PetscCall(PetscInfo(ts, "Step=%" PetscInt_FMT ", step rejections %" PetscInt_FMT " greater than current TS allowed, stopping solve\n", ts->steps, rejections));
360: }
361: }
362: PetscFunctionReturn(PETSC_SUCCESS);
363: }
365: static PetscErrorCode TSInterpolate_IRK(TS ts, PetscReal itime, Vec U)
366: {
367: TS_IRK *irk = (TS_IRK *)ts->data;
368: PetscInt nstages = irk->nstages, pinterp = irk->pinterp, i, j;
369: PetscReal h;
370: PetscReal tt, t;
371: PetscScalar *bt;
372: const PetscReal *B = irk->tableau->binterp;
374: PetscFunctionBegin;
375: PetscCheck(B, PetscObjectComm((PetscObject)ts), PETSC_ERR_SUP, "TSIRK %s does not have an interpolation formula", irk->method_name);
376: switch (irk->status) {
377: case TS_STEP_INCOMPLETE:
378: case TS_STEP_PENDING:
379: h = ts->time_step;
380: t = (itime - ts->ptime) / h;
381: break;
382: case TS_STEP_COMPLETE:
383: h = ts->ptime - ts->ptime_prev;
384: t = (itime - ts->ptime) / h + 1; /* In the interval [0,1] */
385: break;
386: default:
387: SETERRQ(PetscObjectComm((PetscObject)ts), PETSC_ERR_PLIB, "Invalid TSStepStatus");
388: }
389: PetscCall(PetscMalloc1(nstages, &bt));
390: for (i = 0; i < nstages; i++) bt[i] = 0;
391: for (j = 0, tt = t; j < pinterp; j++, tt *= t) {
392: for (i = 0; i < nstages; i++) bt[i] += h * B[i * pinterp + j] * tt;
393: }
394: PetscCall(VecMAXPY(U, nstages, bt, irk->YdotI));
395: PetscFunctionReturn(PETSC_SUCCESS);
396: }
398: static PetscErrorCode TSIRKTableauReset(TS ts)
399: {
400: TS_IRK *irk = (TS_IRK *)ts->data;
401: IRKTableau tab = irk->tableau;
403: PetscFunctionBegin;
404: if (!tab) PetscFunctionReturn(PETSC_SUCCESS);
405: PetscCall(PetscFree3(tab->A, tab->A_inv, tab->I_s));
406: PetscCall(PetscFree4(tab->b, tab->c, tab->binterp, tab->A_inv_rowsum));
407: PetscFunctionReturn(PETSC_SUCCESS);
408: }
410: static PetscErrorCode TSReset_IRK(TS ts)
411: {
412: TS_IRK *irk = (TS_IRK *)ts->data;
414: PetscFunctionBegin;
415: PetscCall(TSIRKTableauReset(ts));
416: PetscCall(PetscFree(irk->tableau));
417: PetscCall(PetscFree(irk->method_name));
418: PetscCall(PetscFree(irk->work));
419: PetscCall(VecDestroyVecs(irk->nstages, &irk->Y));
420: PetscCall(VecDestroyVecs(irk->nstages, &irk->YdotI));
421: PetscCall(VecDestroy(&irk->Ydot));
422: PetscCall(VecDestroy(&irk->Z));
423: PetscCall(VecDestroy(&irk->U));
424: PetscCall(VecDestroy(&irk->U0));
425: PetscCall(MatDestroy(&irk->TJ));
426: PetscCall(MatDestroy(&irk->M));
427: PetscFunctionReturn(PETSC_SUCCESS);
428: }
430: static PetscErrorCode TSIRKGetVecs(TS ts, DM dm, Vec *U)
431: {
432: TS_IRK *irk = (TS_IRK *)ts->data;
434: PetscFunctionBegin;
435: if (U) {
436: if (dm && dm != ts->dm) PetscCall(DMGetNamedGlobalVector(dm, "TSIRK_U", U));
437: else *U = irk->U;
438: }
439: PetscFunctionReturn(PETSC_SUCCESS);
440: }
442: static PetscErrorCode TSIRKRestoreVecs(TS ts, DM dm, Vec *U)
443: {
444: PetscFunctionBegin;
445: if (U) {
446: if (dm && dm != ts->dm) PetscCall(DMRestoreNamedGlobalVector(dm, "TSIRK_U", U));
447: }
448: PetscFunctionReturn(PETSC_SUCCESS);
449: }
451: /*
452: This defines the nonlinear equations that is to be solved with SNES
453: G[e\otimes t + C*dt, Z, Zdot] = 0
454: Zdot = (In \otimes S)*Z - (In \otimes Se) U
455: where S = 1/(dt*A)
456: */
457: static PetscErrorCode SNESTSFormFunction_IRK(SNES snes, Vec ZC, Vec FC, TS ts)
458: {
459: TS_IRK *irk = (TS_IRK *)ts->data;
460: IRKTableau tab = irk->tableau;
461: const PetscInt nstages = irk->nstages;
462: const PetscReal *c = tab->c;
463: const PetscScalar *A_inv = tab->A_inv, *A_inv_rowsum = tab->A_inv_rowsum;
464: DM dm, dmsave;
465: Vec U, *YdotI = irk->YdotI, Ydot = irk->Ydot, *Y = irk->Y;
466: PetscReal h = ts->time_step;
467: PetscInt i, j;
469: PetscFunctionBegin;
470: PetscCall(SNESGetDM(snes, &dm));
471: PetscCall(TSIRKGetVecs(ts, dm, &U));
472: for (i = 0; i < nstages; i++) PetscCall(VecStrideGather(ZC, i, Y[i], INSERT_VALUES));
473: dmsave = ts->dm;
474: ts->dm = dm;
475: for (i = 0; i < nstages; i++) {
476: PetscCall(VecZeroEntries(Ydot));
477: for (j = 0; j < nstages; j++) PetscCall(VecAXPY(Ydot, A_inv[j * nstages + i] / h, Y[j]));
478: PetscCall(VecAXPY(Ydot, -A_inv_rowsum[i] / h, U)); /* Ydot = (S \otimes In)*Z - (Se \otimes In) U */
479: PetscCall(TSComputeIFunction(ts, ts->ptime + ts->time_step * c[i], Y[i], Ydot, YdotI[i], PETSC_FALSE));
480: }
481: for (i = 0; i < nstages; i++) PetscCall(VecStrideScatter(YdotI[i], i, FC, INSERT_VALUES));
482: ts->dm = dmsave;
483: PetscCall(TSIRKRestoreVecs(ts, dm, &U));
484: PetscFunctionReturn(PETSC_SUCCESS);
485: }
487: /*
488: J = dF/dU is obtained from TSComputeIJacobian() at zero shift, so the combined stage Jacobian is
489: JC = I_n \otimes S + J \otimes I_s for an explicit ODE
490: JC = M \otimes S + J \otimes I_s for a DAE
491: which is the form (A \otimes T) + (B \otimes S) evaluated by MATKAIJ.
492: */
493: static PetscErrorCode SNESTSFormJacobian_IRK(SNES snes, Vec ZC, Mat JC, Mat JCpre, TS ts)
494: {
495: TS_IRK *irk = (TS_IRK *)ts->data;
496: IRKTableau tab = irk->tableau;
497: const PetscInt nstages = irk->nstages;
498: const PetscReal *c = tab->c;
499: DM dm, dmsave;
500: Vec *Y = irk->Y, Ydot = irk->Ydot;
501: Mat J;
502: PetscScalar *S;
503: PetscReal stagetime = ts->ptime + ts->time_step * c[nstages - 1];
504: PetscBool hasmass, massconstant;
505: PetscInt i, j;
507: PetscFunctionBegin;
508: PetscCall(SNESGetDM(snes, &dm));
509: /* irk->Ydot has already been computed in SNESTSFormFunction_IRK (SNES guarantees this) */
510: dmsave = ts->dm;
511: ts->dm = dm;
512: // TSSetUp_IRK() consumes the mass matrix, so a mass matrix set after setup would be ignored
513: PetscCall(TSHasMassMatrix(ts, &hasmass));
514: PetscCheck(!hasmass || irk->M, PetscObjectComm((PetscObject)ts), PETSC_ERR_ARG_WRONGSTATE, "TSSetMassMatrix() was called after TSIRK was set up; call TSReset() before TSSolve() so that the mass matrix is used");
515: // Without a mass matrix, TSIRK supports only explicit ODEs
516: PetscCheck(irk->M || ts->equation_type <= TS_EQ_ODE_EXPLICIT, PetscObjectComm((PetscObject)ts), PETSC_ERR_SUP, "TSIRK %s does not support DAEs without a mass matrix; call TSSetMassMatrix()", irk->method_name);
517: PetscCall(VecStrideGather(ZC, nstages - 1, Y[nstages - 1], INSERT_VALUES));
518: // Re-evaluate a mass matrix that is not constant at the last stage
519: PetscCall(TSGetMassMatrixConstant(ts, &massconstant));
520: if (irk->M && !massconstant) PetscCall(TSComputeMassMatrix(ts, stagetime, Y[nstages - 1], irk->M));
521: PetscCall(MatKAIJGetA(JC, &J));
522: PetscCall(TSComputeIJacobian(ts, stagetime, Y[nstages - 1], Ydot, 0, J, J, PETSC_FALSE));
523: PetscCall(MatKAIJGetS(JC, NULL, NULL, &S));
524: for (i = 0; i < nstages; i++)
525: for (j = 0; j < nstages; j++) S[i + nstages * j] = tab->A_inv[i + nstages * j] / ts->time_step;
526: PetscCall(MatKAIJRestoreS(JC, &S));
527: ts->dm = dmsave;
528: PetscFunctionReturn(PETSC_SUCCESS);
529: }
531: // Nothing to coarsen, because TSIRK assembles the mass matrix only on the fine DM
532: static PetscErrorCode DMCoarsenHook_TSIRK(DM fine, DM coarse, PetscCtx ctx)
533: {
534: PetscFunctionBegin;
535: PetscFunctionReturn(PETSC_SUCCESS);
536: }
538: static PetscErrorCode DMRestrictHook_TSIRK(DM fine, Mat restrct, Vec rscale, Mat inject, DM coarse, PetscCtx ctx)
539: {
540: TS ts = (TS)ctx;
541: Vec U, U_c;
543: PetscFunctionBegin;
544: PetscCall(TSIRKGetVecs(ts, fine, &U));
545: PetscCall(TSIRKGetVecs(ts, coarse, &U_c));
546: PetscCall(MatRestrict(restrct, U, U_c));
547: PetscCall(VecPointwiseMult(U_c, rscale, U_c));
548: PetscCall(TSIRKRestoreVecs(ts, fine, &U));
549: PetscCall(TSIRKRestoreVecs(ts, coarse, &U_c));
550: PetscFunctionReturn(PETSC_SUCCESS);
551: }
553: static PetscErrorCode DMSubDomainHook_TSIRK(DM dm, DM subdm, PetscCtx ctx)
554: {
555: PetscFunctionBegin;
556: PetscFunctionReturn(PETSC_SUCCESS);
557: }
559: static PetscErrorCode DMSubDomainRestrictHook_TSIRK(DM dm, VecScatter gscat, VecScatter lscat, DM subdm, PetscCtx ctx)
560: {
561: TS ts = (TS)ctx;
562: Vec U, U_c;
564: PetscFunctionBegin;
565: PetscCall(TSIRKGetVecs(ts, dm, &U));
566: PetscCall(TSIRKGetVecs(ts, subdm, &U_c));
568: PetscCall(VecScatterBegin(gscat, U, U_c, INSERT_VALUES, SCATTER_FORWARD));
569: PetscCall(VecScatterEnd(gscat, U, U_c, INSERT_VALUES, SCATTER_FORWARD));
571: PetscCall(TSIRKRestoreVecs(ts, dm, &U));
572: PetscCall(TSIRKRestoreVecs(ts, subdm, &U_c));
573: PetscFunctionReturn(PETSC_SUCCESS);
574: }
576: static PetscErrorCode TSSetUp_IRK(TS ts)
577: {
578: TS_IRK *irk = (TS_IRK *)ts->data;
579: IRKTableau tab = irk->tableau;
580: DM dm;
581: Mat J;
582: Vec R;
583: VecType vtype;
584: const PetscInt nstages = irk->nstages;
585: PetscInt lsize;
586: PetscBool hasmass;
588: PetscFunctionBegin;
589: if (!irk->work) PetscCall(PetscMalloc1(irk->nstages, &irk->work));
590: if (!irk->Y) PetscCall(VecDuplicateVecs(ts->vec_sol, irk->nstages, &irk->Y));
591: if (!irk->YdotI) PetscCall(VecDuplicateVecs(ts->vec_sol, irk->nstages, &irk->YdotI));
592: if (!irk->Ydot) PetscCall(VecDuplicate(ts->vec_sol, &irk->Ydot));
593: if (!irk->U) PetscCall(VecDuplicate(ts->vec_sol, &irk->U));
594: if (!irk->U0) PetscCall(VecDuplicate(ts->vec_sol, &irk->U0));
595: if (!irk->Z) {
596: PetscCall(VecCreate(PetscObjectComm((PetscObject)ts->vec_sol), &irk->Z));
597: PetscCall(VecGetLocalSize(ts->vec_sol, &lsize));
598: PetscCall(VecSetSizes(irk->Z, lsize * irk->nstages, PETSC_DECIDE));
599: PetscCall(VecSetBlockSize(irk->Z, irk->nstages));
600: PetscCall(VecGetType(ts->vec_sol, &vtype));
601: PetscCall(VecSetType(irk->Z, vtype));
602: }
603: PetscCall(TSGetDM(ts, &dm));
604: PetscCall(DMCoarsenHookAdd(dm, DMCoarsenHook_TSIRK, DMRestrictHook_TSIRK, ts));
605: PetscCall(DMSubDomainHookAdd(dm, DMSubDomainHook_TSIRK, DMSubDomainRestrictHook_TSIRK, ts));
607: PetscCall(TSGetSNES(ts, &ts->snes));
608: PetscCall(VecDuplicate(irk->Z, &R));
609: PetscCall(SNESSetFunction(ts->snes, R, SNESTSFormFunction, ts));
610: PetscCall(TSGetIJacobian(ts, &J, NULL, NULL, NULL));
611: // Duplicate M from the Jacobian, because MatCreateKAIJAB() requires both operands to share a nonzero structure
612: PetscCall(TSHasMassMatrix(ts, &hasmass));
613: if (hasmass && !irk->M) {
614: PetscCall(MatDuplicate(J, MAT_DO_NOT_COPY_VALUES, &irk->M));
615: PetscCall(TSComputeMassMatrix(ts, ts->ptime, ts->vec_sol, irk->M));
616: }
617: if (!irk->TJ) {
618: /* Create the KAIJ matrix for solving the stages */
619: if (irk->M) PetscCall(MatCreateKAIJAB(J, irk->M, nstages, nstages, tab->A_inv, tab->I_s, &irk->TJ));
620: else PetscCall(MatCreateKAIJ(J, nstages, nstages, tab->A_inv, tab->I_s, &irk->TJ));
621: }
622: PetscCall(SNESSetJacobian(ts->snes, irk->TJ, irk->TJ, SNESTSFormJacobian, ts));
623: PetscCall(VecDestroy(&R));
624: PetscFunctionReturn(PETSC_SUCCESS);
625: }
627: static PetscErrorCode TSSetFromOptions_IRK(TS ts, PetscOptionItems PetscOptionsObject)
628: {
629: TS_IRK *irk = (TS_IRK *)ts->data;
630: char tname[256] = TSIRKGAUSS;
632: PetscFunctionBegin;
633: PetscOptionsHeadBegin(PetscOptionsObject, "IRK ODE solver options");
634: {
635: PetscBool flg1, flg2;
636: PetscCall(PetscOptionsInt("-ts_irk_nstages", "Stages of the IRK method", "TSIRKSetNumStages", irk->nstages, &irk->nstages, &flg1));
637: PetscCall(PetscOptionsFList("-ts_irk_type", "Type of IRK method", "TSIRKSetType", TSIRKList, irk->method_name[0] ? irk->method_name : tname, tname, sizeof(tname), &flg2));
638: if (flg1 || flg2 || !irk->method_name[0]) { /* Create the method tableau after nstages or method is set */
639: PetscCall(TSIRKSetType(ts, tname));
640: }
641: }
642: PetscOptionsHeadEnd();
643: PetscFunctionReturn(PETSC_SUCCESS);
644: }
646: static PetscErrorCode TSView_IRK(TS ts, PetscViewer viewer)
647: {
648: TS_IRK *irk = (TS_IRK *)ts->data;
649: PetscBool isascii;
651: PetscFunctionBegin;
652: PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERASCII, &isascii));
653: if (isascii) {
654: IRKTableau tab = irk->tableau;
655: TSIRKType irktype;
656: char buf[512];
658: PetscCall(TSIRKGetType(ts, &irktype));
659: PetscCall(PetscViewerASCIIPrintf(viewer, " IRK type %s\n", irktype));
660: PetscCall(PetscFormatRealArray(buf, sizeof(buf), "% 8.6f", irk->nstages, tab->c));
661: PetscCall(PetscViewerASCIIPrintf(viewer, " Abscissa c = %s\n", buf));
662: PetscCall(PetscViewerASCIIPrintf(viewer, "Stiffly accurate: %s\n", irk->stiffly_accurate ? "yes" : "no"));
663: PetscCall(PetscFormatRealArray(buf, sizeof(buf), "% 8.6f", PetscSqr(irk->nstages), tab->A));
664: PetscCall(PetscViewerASCIIPrintf(viewer, " A coefficients A = %s\n", buf));
665: }
666: PetscFunctionReturn(PETSC_SUCCESS);
667: }
669: static PetscErrorCode TSLoad_IRK(TS ts, PetscViewer viewer)
670: {
671: SNES snes;
672: TSAdapt adapt;
674: PetscFunctionBegin;
675: PetscCall(TSGetAdapt(ts, &adapt));
676: PetscCall(TSAdaptLoad(adapt, viewer));
677: PetscCall(TSGetSNES(ts, &snes));
678: PetscCall(SNESLoad(snes, viewer));
679: /* function and Jacobian context for SNES when used with TS is always ts object */
680: PetscCall(SNESSetFunction(snes, NULL, NULL, ts));
681: PetscCall(SNESSetJacobian(snes, NULL, NULL, NULL, ts));
682: PetscFunctionReturn(PETSC_SUCCESS);
683: }
685: /*@
686: TSIRKSetType - Set the type of `TSIRK` scheme to use
688: Logically Collective
690: Input Parameters:
691: + ts - timestepping context
692: - irktype - type of `TSIRK` scheme
694: Options Database Key:
695: . -ts_irk_type gauss - set irk type
697: Level: intermediate
699: .seealso: [](ch_ts), `TSIRKGetType()`, `TSIRK`, `TSIRKType`, `TSIRKGAUSS`
700: @*/
701: PetscErrorCode TSIRKSetType(TS ts, TSIRKType irktype)
702: {
703: PetscFunctionBegin;
705: PetscAssertPointer(irktype, 2);
706: PetscTryMethod(ts, "TSIRKSetType_C", (TS, TSIRKType), (ts, irktype));
707: PetscFunctionReturn(PETSC_SUCCESS);
708: }
710: /*@
711: TSIRKGetType - Get the type of `TSIRK` IMEX scheme being used
713: Logically Collective
715: Input Parameter:
716: . ts - timestepping context
718: Output Parameter:
719: . irktype - type of `TSIRK` IMEX scheme
721: Level: intermediate
723: .seealso: [](ch_ts), `TSIRK`, `TSIRKType`, `TSIRKGAUSS`
724: @*/
725: PetscErrorCode TSIRKGetType(TS ts, TSIRKType *irktype)
726: {
727: PetscFunctionBegin;
729: PetscUseMethod(ts, "TSIRKGetType_C", (TS, TSIRKType *), (ts, irktype));
730: PetscFunctionReturn(PETSC_SUCCESS);
731: }
733: /*@
734: TSIRKSetNumStages - Set the number of stages of `TSIRK` scheme to use
736: Logically Collective
738: Input Parameters:
739: + ts - timestepping context
740: - nstages - number of stages of `TSIRK` scheme
742: Options Database Key:
743: . -ts_irk_nstages int - set number of stages
745: Level: intermediate
747: .seealso: [](ch_ts), `TSIRKGetNumStages()`, `TSIRK`
748: @*/
749: PetscErrorCode TSIRKSetNumStages(TS ts, PetscInt nstages)
750: {
751: PetscFunctionBegin;
753: PetscTryMethod(ts, "TSIRKSetNumStages_C", (TS, PetscInt), (ts, nstages));
754: PetscFunctionReturn(PETSC_SUCCESS);
755: }
757: /*@
758: TSIRKGetNumStages - Get the number of stages of `TSIRK` scheme
760: Logically Collective
762: Input Parameters:
763: + ts - timestepping context
764: - nstages - number of stages of `TSIRK` scheme
766: Level: intermediate
768: .seealso: [](ch_ts), `TSIRKSetNumStages()`, `TSIRK`
769: @*/
770: PetscErrorCode TSIRKGetNumStages(TS ts, PetscInt *nstages)
771: {
772: PetscFunctionBegin;
774: PetscAssertPointer(nstages, 2);
775: PetscTryMethod(ts, "TSIRKGetNumStages_C", (TS, PetscInt *), (ts, nstages));
776: PetscFunctionReturn(PETSC_SUCCESS);
777: }
779: static PetscErrorCode TSIRKGetType_IRK(TS ts, TSIRKType *irktype)
780: {
781: TS_IRK *irk = (TS_IRK *)ts->data;
783: PetscFunctionBegin;
784: *irktype = irk->method_name;
785: PetscFunctionReturn(PETSC_SUCCESS);
786: }
788: static PetscErrorCode TSIRKSetType_IRK(TS ts, TSIRKType irktype)
789: {
790: TS_IRK *irk = (TS_IRK *)ts->data;
791: PetscErrorCode (*irkcreate)(TS);
793: PetscFunctionBegin;
794: if (irk->method_name) {
795: PetscCall(PetscFree(irk->method_name));
796: PetscCall(TSIRKTableauReset(ts));
797: }
798: PetscCall(PetscFunctionListFind(TSIRKList, irktype, &irkcreate));
799: PetscCheck(irkcreate, PetscObjectComm((PetscObject)ts), PETSC_ERR_ARG_UNKNOWN_TYPE, "Unknown TSIRK type \"%s\" given", irktype);
800: PetscCall((*irkcreate)(ts));
801: PetscCall(PetscStrallocpy(irktype, &irk->method_name));
802: PetscFunctionReturn(PETSC_SUCCESS);
803: }
805: static PetscErrorCode TSIRKSetNumStages_IRK(TS ts, PetscInt nstages)
806: {
807: TS_IRK *irk = (TS_IRK *)ts->data;
809: PetscFunctionBegin;
810: PetscCheck(nstages > 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "input argument, %" PetscInt_FMT ", out of range", nstages);
811: irk->nstages = nstages;
812: PetscFunctionReturn(PETSC_SUCCESS);
813: }
815: static PetscErrorCode TSIRKGetNumStages_IRK(TS ts, PetscInt *nstages)
816: {
817: TS_IRK *irk = (TS_IRK *)ts->data;
819: PetscFunctionBegin;
820: PetscAssertPointer(nstages, 2);
821: *nstages = irk->nstages;
822: PetscFunctionReturn(PETSC_SUCCESS);
823: }
825: static PetscErrorCode TSDestroy_IRK(TS ts)
826: {
827: PetscFunctionBegin;
828: PetscCall(TSReset_IRK(ts));
829: if (ts->dm) {
830: PetscCall(DMCoarsenHookRemove(ts->dm, DMCoarsenHook_TSIRK, DMRestrictHook_TSIRK, ts));
831: PetscCall(DMSubDomainHookRemove(ts->dm, DMSubDomainHook_TSIRK, DMSubDomainRestrictHook_TSIRK, ts));
832: }
833: PetscCall(PetscFree(ts->data));
834: PetscCall(PetscObjectComposeFunction((PetscObject)ts, "TSIRKSetType_C", NULL));
835: PetscCall(PetscObjectComposeFunction((PetscObject)ts, "TSIRKGetType_C", NULL));
836: PetscCall(PetscObjectComposeFunction((PetscObject)ts, "TSIRKSetNumStages_C", NULL));
837: PetscCall(PetscObjectComposeFunction((PetscObject)ts, "TSIRKGetNumStages_C", NULL));
838: PetscFunctionReturn(PETSC_SUCCESS);
839: }
841: /*MC
842: TSIRK - ODE and DAE solver using Implicit Runge-Kutta schemes
844: Level: beginner
846: Notes:
847: `TSIRK` uses the sparse Kronecker product matrix implementation of `MATKAIJ` to achieve good arithmetic intensity.
849: Gauss-Legrendre methods are currently supported. These are A-stable symplectic methods with an arbitrary number of stages. The order of accuracy is 2s
850: when using s stages. The default method uses three stages and thus has an order of six. The number of stages (thus order) can be set with
851: `-ts_irk_nstages` or `TSIRKSetNumStages()`.
853: .seealso: [](ch_ts), `TSCreate()`, `TS`, `TSSetType()`, `TSIRKSetType()`, `TSIRKGetType()`, `TSIRKGAUSS`, `TSIRKRegister()`, `TSIRKSetNumStages()`, `TSType`
854: M*/
855: PETSC_EXTERN PetscErrorCode TSCreate_IRK(TS ts)
856: {
857: TS_IRK *irk;
859: PetscFunctionBegin;
860: PetscCall(TSIRKInitializePackage());
862: ts->ops->reset = TSReset_IRK;
863: ts->ops->destroy = TSDestroy_IRK;
864: ts->ops->view = TSView_IRK;
865: ts->ops->load = TSLoad_IRK;
866: ts->ops->setup = TSSetUp_IRK;
867: ts->ops->step = TSStep_IRK;
868: ts->ops->interpolate = TSInterpolate_IRK;
869: ts->ops->evaluatestep = TSEvaluateStep_IRK;
870: ts->ops->rollback = TSRollBack_IRK;
871: ts->ops->setfromoptions = TSSetFromOptions_IRK;
872: ts->ops->snesfunction = SNESTSFormFunction_IRK;
873: ts->ops->snesjacobian = SNESTSFormJacobian_IRK;
875: ts->usessnes = PETSC_TRUE;
877: PetscCall(PetscNew(&irk));
878: ts->data = (void *)irk;
880: PetscCall(PetscObjectComposeFunction((PetscObject)ts, "TSIRKSetType_C", TSIRKSetType_IRK));
881: PetscCall(PetscObjectComposeFunction((PetscObject)ts, "TSIRKGetType_C", TSIRKGetType_IRK));
882: PetscCall(PetscObjectComposeFunction((PetscObject)ts, "TSIRKSetNumStages_C", TSIRKSetNumStages_IRK));
883: PetscCall(PetscObjectComposeFunction((PetscObject)ts, "TSIRKGetNumStages_C", TSIRKGetNumStages_IRK));
884: /* 3-stage IRK_Gauss is the default */
885: PetscCall(PetscNew(&irk->tableau));
886: irk->nstages = 3;
887: PetscCall(TSIRKSetType(ts, TSIRKDefault));
888: PetscFunctionReturn(PETSC_SUCCESS);
889: }