Actual source code: kaij.c
1: /*
2: Defines the basic matrix operations for the KAIJ matrix storage format.
3: This format is used to evaluate matrices of the form:
5: [B \otimes S + A \otimes T]
7: where
8: S is a dense (p \times q) matrix
9: T is a dense (p \times q) matrix
10: A is an AIJ (n \times n) matrix
11: B is an AIJ (n \times n) matrix, or the identity matrix by default
13: The resulting matrix is (np \times nq)
15: We provide:
16: MatMult()
17: MatMultAdd()
18: MatInvertBlockDiagonal()
19: and
20: MatCreateKAIJ(Mat,PetscInt,PetscInt,const PetscScalar[],const PetscScalar[],Mat*)
22: This single directory handles both the sequential and parallel codes
23: */
25: #include <../src/mat/impls/kaij/kaij.h>
26: #include <../src/mat/utils/freespace.h>
27: #include <petsc/private/vecimpl.h>
29: /*@
30: MatKAIJGetA - Get the `MATAIJ` matrix `A` describing the first Kronecker term $A \otimes T$ of the `MATKAIJ` matrix
32: Not Collective, but if the `MATKAIJ` matrix is parallel, the `MATAIJ` matrix is also parallel
34: Input Parameter:
35: . A - the `MATKAIJ` matrix
37: Output Parameter:
38: . a - the `MATAIJ` matrix `A`
40: Level: advanced
42: Note:
43: The reference count on the `MATAIJ` matrix is not increased so you should not destroy it.
45: .seealso: [](ch_matrices), `Mat`, `MatCreateKAIJ()`, `MatCreateKAIJAB()`, `MatKAIJGetB()`, `MATKAIJ`, `MATAIJ`
46: @*/
47: PetscErrorCode MatKAIJGetA(Mat A, Mat *a)
48: {
49: PetscBool ismpikaij, isseqkaij;
51: PetscFunctionBegin;
53: PetscAssertPointer(a, 2);
54: PetscCall(PetscObjectTypeCompare((PetscObject)A, MATMPIKAIJ, &ismpikaij));
55: PetscCall(PetscObjectTypeCompare((PetscObject)A, MATSEQKAIJ, &isseqkaij));
56: if (ismpikaij) {
57: Mat_MPIKAIJ *b = (Mat_MPIKAIJ *)A->data;
59: *a = b->A;
60: } else if (isseqkaij) {
61: Mat_SeqKAIJ *b = (Mat_SeqKAIJ *)A->data;
63: *a = b->AIJ;
64: } else SETERRQ(PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_WRONG, "Matrix passed in is not of type KAIJ");
65: PetscFunctionReturn(PETSC_SUCCESS);
66: }
68: /*@
69: MatKAIJGetS - Get the `S` matrix describing the shift action of the `MATKAIJ` matrix
71: Logically Collective; the entire `S` is stored and returned independently on all processes.
73: Input Parameter:
74: . A - the `MATKAIJ` matrix
76: Output Parameters:
77: + m - the number of rows in `S`
78: . n - the number of columns in `S`
79: - S - the S matrix, in form of a scalar array in column-major format
81: Level: advanced
83: Note:
84: All output parameters are optional (pass `NULL` if not desired)
86: .seealso: [](ch_matrices), `Mat`, `MATKAIJ`, `MatKAIJRestoreS()`, `MatKAIJGetSRead()`, `MatKAIJRestoreSRead()`, `MatCreateKAIJ()`, `MatGetBlockSizes()`
87: @*/
88: PetscErrorCode MatKAIJGetS(Mat A, PetscInt *m, PetscInt *n, PetscScalar *S[])
89: {
90: Mat_SeqKAIJ *b;
92: PetscFunctionBegin;
94: PetscCheckTypeNames(A, MATSEQKAIJ, MATMPIKAIJ);
95: b = (Mat_SeqKAIJ *)A->data;
96: if (m) *m = b->p;
97: if (n) *n = b->q;
98: if (S) *S = b->S;
99: PetscFunctionReturn(PETSC_SUCCESS);
100: }
102: /*@
103: MatKAIJGetSRead - Get a read-only pointer to the `S` matrix describing the shift action of the `MATKAIJ` matrix
105: Not Collective; the entire `S` is stored and returned independently on all processes.
107: Input Parameter:
108: . A - the `MATKAIJ` matrix
110: Output Parameters:
111: + m - the number of rows in `S`
112: . n - the number of columns in `S`
113: - S - the S matrix, in form of a scalar array in column-major format
115: Level: advanced
117: Note:
118: All output parameters are optional (pass `NULL` if not desired)
120: .seealso: [](ch_matrices), `Mat`, `MATKAIJ`, `MatKAIJGetS()`, `MatKAIJRestoreS()`, `MatKAIJRestoreSRead()`, `MatCreateKAIJ()`, `MatGetBlockSizes()`
121: @*/
122: PetscErrorCode MatKAIJGetSRead(Mat A, PetscInt *m, PetscInt *n, const PetscScalar *S[])
123: {
124: Mat_SeqKAIJ *b;
126: PetscFunctionBegin;
128: PetscCheckTypeNames(A, MATSEQKAIJ, MATMPIKAIJ);
129: b = (Mat_SeqKAIJ *)A->data;
130: if (m) *m = b->p;
131: if (n) *n = b->q;
132: if (S) *S = b->S;
133: PetscFunctionReturn(PETSC_SUCCESS);
134: }
136: /*@
137: MatKAIJRestoreS - Restore array obtained with `MatKAIJGetS()`
139: Logically Collective
141: Input Parameters:
142: + A - the `MATKAIJ` matrix
143: - S - location of pointer to array obtained with `MatKAIJGetS()`
145: Level: advanced
147: Notes:
148: This routine zeros the array pointer to prevent accidental reuse after it has been restored.
149: If `NULL` is passed, it will not attempt to zero the array pointer.
151: Every process must restore `S`, because doing so raises the state of the `MATKAIJ` matrix. Before its next use, a
152: `MATMPIKAIJ` then rebuilds its cached submatrices locally, and its next `MatMult()` checks, and possibly rebuilds, its
153: ghost scatter collectively. Use `MatKAIJGetSRead()`/`MatKAIJRestoreSRead()` to read `S` without raising the state.
155: .seealso: [](ch_matrices), `Mat`, `MATKAIJ`, `MatKAIJGetS()`, `MatKAIJGetSRead()`, `MatKAIJRestoreSRead()`
156: @*/
157: PetscErrorCode MatKAIJRestoreS(Mat A, PetscScalar *S[])
158: {
159: PetscFunctionBegin;
161: PetscCheckTypeNames(A, MATSEQKAIJ, MATMPIKAIJ);
162: if (S) *S = NULL;
163: PetscCall(PetscObjectStateIncrease((PetscObject)A));
164: PetscFunctionReturn(PETSC_SUCCESS);
165: }
167: /*@
168: MatKAIJRestoreSRead - Restore array obtained with `MatKAIJGetSRead()`
170: Not Collective
172: Input Parameters:
173: + A - the `MATKAIJ` matrix
174: - S - location of pointer to array obtained with `MatKAIJGetSRead()`
176: Level: advanced
178: Note:
179: This routine zeros the array pointer to prevent accidental reuse after it has been restored.
180: If `NULL` is passed, it will not attempt to zero the array pointer.
182: .seealso: [](ch_matrices), `Mat`, `MATKAIJ`, `MatKAIJGetS()`, `MatKAIJRestoreS()`, `MatKAIJGetSRead()`
183: @*/
184: PetscErrorCode MatKAIJRestoreSRead(Mat A, const PetscScalar *S[])
185: {
186: PetscFunctionBegin;
188: PetscCheckTypeNames(A, MATSEQKAIJ, MATMPIKAIJ);
189: if (S) *S = NULL;
190: PetscFunctionReturn(PETSC_SUCCESS);
191: }
193: /*@
194: MatKAIJGetT - Get the transformation matrix `T` associated with the `MATKAIJ` matrix
196: Logically Collective; the entire `T` is stored and returned independently on all processes
198: Input Parameter:
199: . A - the `MATKAIJ` matrix
201: Output Parameters:
202: + m - the number of rows in `T`
203: . n - the number of columns in `T`
204: - T - the T matrix, in form of a scalar array in column-major format
206: Level: advanced
208: Note:
209: All output parameters are optional (pass `NULL` if not desired)
211: .seealso: [](ch_matrices), `Mat`, `MATKAIJ`, `MatKAIJRestoreT()`, `MatKAIJGetTRead()`, `MatKAIJRestoreTRead()`, `MatCreateKAIJ()`, `MatGetBlockSizes()`
212: @*/
213: PetscErrorCode MatKAIJGetT(Mat A, PetscInt *m, PetscInt *n, PetscScalar *T[])
214: {
215: Mat_SeqKAIJ *b;
217: PetscFunctionBegin;
219: PetscCheckTypeNames(A, MATSEQKAIJ, MATMPIKAIJ);
220: b = (Mat_SeqKAIJ *)A->data;
221: if (m) *m = b->p;
222: if (n) *n = b->q;
223: if (T) *T = b->T;
224: PetscFunctionReturn(PETSC_SUCCESS);
225: }
227: /*@
228: MatKAIJGetTRead - Get a read-only pointer to the transformation matrix `T` associated with the `MATKAIJ` matrix
230: Not Collective; the entire `T` is stored and returned independently on all processes
232: Input Parameter:
233: . A - the `MATKAIJ` matrix
235: Output Parameters:
236: + m - the number of rows in `T`
237: . n - the number of columns in `T`
238: - T - the T matrix, in form of a scalar array in column-major format
240: Level: advanced
242: Note:
243: All output parameters are optional (pass `NULL` if not desired)
245: .seealso: [](ch_matrices), `Mat`, `MATKAIJ`, `MatKAIJGetT()`, `MatKAIJRestoreT()`, `MatKAIJRestoreTRead()`, `MatCreateKAIJ()`, `MatGetBlockSizes()`
246: @*/
247: PetscErrorCode MatKAIJGetTRead(Mat A, PetscInt *m, PetscInt *n, const PetscScalar *T[])
248: {
249: Mat_SeqKAIJ *b;
251: PetscFunctionBegin;
253: PetscCheckTypeNames(A, MATSEQKAIJ, MATMPIKAIJ);
254: b = (Mat_SeqKAIJ *)A->data;
255: if (m) *m = b->p;
256: if (n) *n = b->q;
257: if (T) *T = b->T;
258: PetscFunctionReturn(PETSC_SUCCESS);
259: }
261: /*@
262: MatKAIJRestoreT - Restore array obtained with `MatKAIJGetT()`
264: Logically Collective
266: Input Parameters:
267: + A - the `MATKAIJ` matrix
268: - T - location of pointer to array obtained with `MatKAIJGetT()`
270: Level: advanced
272: Notes:
273: This routine zeros the array pointer to prevent accidental reuse after it has been restored.
274: If `NULL` is passed, it will not attempt to zero the array pointer.
276: Every process must restore `T`, because doing so raises the state of the `MATKAIJ` matrix. Before its next use, a
277: `MATMPIKAIJ` then rebuilds its cached submatrices locally, and its next `MatMult()` checks, and possibly rebuilds, its
278: ghost scatter collectively. Use `MatKAIJGetTRead()`/`MatKAIJRestoreTRead()` to read `T` without raising the state.
280: .seealso: [](ch_matrices), `Mat`, `MATKAIJ`, `MatKAIJGetT()`, `MatKAIJGetTRead()`, `MatKAIJRestoreTRead()`
281: @*/
282: PetscErrorCode MatKAIJRestoreT(Mat A, PetscScalar *T[])
283: {
284: PetscFunctionBegin;
286: PetscCheckTypeNames(A, MATSEQKAIJ, MATMPIKAIJ);
287: if (T) *T = NULL;
288: PetscCall(PetscObjectStateIncrease((PetscObject)A));
289: PetscFunctionReturn(PETSC_SUCCESS);
290: }
292: /*@
293: MatKAIJRestoreTRead - Restore array obtained with `MatKAIJGetTRead()`
295: Not Collective
297: Input Parameters:
298: + A - the `MATKAIJ` matrix
299: - T - location of pointer to array obtained with `MatKAIJGetTRead()`
301: Level: advanced
303: Note:
304: This routine zeros the array pointer to prevent accidental reuse after it has been restored.
305: If `NULL` is passed, it will not attempt to zero the array pointer.
307: .seealso: [](ch_matrices), `Mat`, `MATKAIJ`, `MatKAIJGetT()`, `MatKAIJRestoreT()`, `MatKAIJGetTRead()`
308: @*/
309: PetscErrorCode MatKAIJRestoreTRead(Mat A, const PetscScalar *T[])
310: {
311: PetscFunctionBegin;
313: PetscCheckTypeNames(A, MATSEQKAIJ, MATMPIKAIJ);
314: if (T) *T = NULL;
315: PetscFunctionReturn(PETSC_SUCCESS);
316: }
318: // Record the operand nonzero states that MatAssemblyEnd_KAIJ() compares against
319: static PetscErrorCode MatKAIJResetOperandNnzState_Private(Mat A)
320: {
321: Mat_SeqKAIJ *kaij = (Mat_SeqKAIJ *)A->data;
322: Mat a, b;
324: PetscFunctionBegin;
325: PetscCall(MatKAIJGetA(A, &a));
326: PetscCall(MatKAIJGetB(A, &b));
327: kaij->aijnnzstate = 0;
328: kaij->bnnzstate = 0;
329: if (a) PetscCall(MatGetNonzeroState(a, &kaij->aijnnzstate));
330: if (b) PetscCall(MatGetNonzeroState(b, &kaij->bnnzstate));
331: PetscFunctionReturn(PETSC_SUCCESS);
332: }
334: // Check that B shares the layout of A, and that a replacement operand keeps the layout that MatSetUp() fixed
335: static PetscErrorCode MatKAIJCheckOperandLayout_Private(Mat A)
336: {
337: Mat_SeqKAIJ *kaij = (Mat_SeqKAIJ *)A->data;
338: Mat a, b;
339: PetscBool rcong, ccong;
341: PetscFunctionBegin;
342: PetscCall(MatKAIJGetA(A, &a));
343: PetscCall(MatKAIJGetB(A, &b));
344: if (a && b) {
345: PetscCall(PetscLayoutSetUp(a->rmap));
346: PetscCall(PetscLayoutSetUp(a->cmap));
347: PetscCall(PetscLayoutSetUp(b->rmap));
348: PetscCall(PetscLayoutSetUp(b->cmap));
349: // PetscLayoutCompare() checks the global size and the parallel range, so it returns the same result on every rank
350: PetscCall(PetscLayoutCompare(a->rmap, b->rmap, &rcong));
351: PetscCall(PetscLayoutCompare(a->cmap, b->cmap, &ccong));
352: PetscCheck(rcong && ccong, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_INCOMP, "The B matrix must share the row and column layout of the A matrix");
353: }
354: // B is compared against A above, so checking A alone covers both operands
355: PetscCheck(!a || !A->preallocated || (A->rmap->n == kaij->p * a->rmap->n && A->cmap->n == kaij->q * a->cmap->n && A->rmap->N == kaij->p * a->rmap->N && A->cmap->N == kaij->q * a->cmap->N), PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_INCOMP, "The operand must keep the layout the %" PetscInt_FMT " x %" PetscInt_FMT " MATKAIJ matrix was set up with; it gives %" PetscInt_FMT " x %" PetscInt_FMT " instead",
356: A->rmap->N, A->cmap->N, kaij->p * a->rmap->N, kaij->q * a->cmap->N);
357: PetscFunctionReturn(PETSC_SUCCESS);
358: }
360: // Check that an operand is MATSEQAIJ for a MATSEQKAIJ and MATMPIAIJ for a MATMPIKAIJ
361: static PetscErrorCode MatKAIJCheckOperandType_Private(Mat A, Mat a)
362: {
363: PetscMPIInt size;
364: PetscBool match;
366: PetscFunctionBegin;
367: PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)A), &size));
368: // The operand data is cast to Mat_SeqAIJ or Mat_MPIAIJ, so check the type also in optimized builds
369: PetscCall(PetscObjectTypeCompare((PetscObject)a, size == 1 ? MATSEQAIJ : MATMPIAIJ, &match));
370: PetscCheck(match, PetscObjectComm((PetscObject)a), PETSC_ERR_SUP, "MATKAIJ does not support %s as an operand, it requires %s", ((PetscObject)a)->type_name, size == 1 ? MATSEQAIJ : MATMPIAIJ);
371: PetscFunctionReturn(PETSC_SUCCESS);
372: }
374: /*@
375: MatKAIJSetA - Set the `MATAIJ` matrix `A` describing the first Kronecker term $A \otimes T$ of the `MATKAIJ` matrix
377: Logically Collective; if the `MATAIJ` matrix is parallel, the `MATKAIJ` matrix is also parallel
379: Input Parameters:
380: + A - the `MATKAIJ` matrix
381: - a - the `MATAIJ` matrix, of type `MATSEQAIJ` for a `MATSEQKAIJ` and `MATMPIAIJ` for a `MATMPIKAIJ`
383: Level: advanced
385: Notes:
386: This function increases the reference count on the `MATAIJ` matrix, so the user is free to destroy the matrix if it is not needed.
388: Changes to the entries of the `MATAIJ` matrix will immediately affect the `MATKAIJ` matrix.
390: A previously set `MATAIJ` matrix is released, so the operand may be replaced after the `MATKAIJ` matrix has been set
391: up. The replacement need not have the same nonzero structure as the matrix it replaces; a `MATMPIKAIJ` rebuilds its
392: ghost scatter whenever the off-diagonal ghost columns change. It must have the same row and column layout, however,
393: since the size of the `MATKAIJ` matrix was fixed when it was set up. If a `B` operand has been set with
394: `MatKAIJSetB()`, the two operands must still share their off-diagonal ghost columns.
396: .seealso: [](ch_matrices), `Mat`, `MATKAIJ`, `MatKAIJGetA()`, `MatKAIJSetB()`, `MatKAIJSetS()`, `MatKAIJSetT()`, `MatCreateKAIJAB()`
397: @*/
398: PetscErrorCode MatKAIJSetA(Mat A, Mat a)
399: {
400: PetscMPIInt size;
402: PetscFunctionBegin;
405: PetscCheckTypeNames(A, MATSEQKAIJ, MATMPIKAIJ);
406: PetscCall(MatKAIJCheckOperandType_Private(A, a));
407: PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)A), &size));
408: // Reference before releasing the previous operand, so that resetting the same matrix is safe
409: PetscCall(PetscObjectReference((PetscObject)a));
410: if (size == 1) {
411: Mat_SeqKAIJ *seq = (Mat_SeqKAIJ *)A->data;
413: PetscCall(MatDestroy(&seq->AIJ));
414: seq->AIJ = a;
415: } else {
416: Mat_MPIKAIJ *m = (Mat_MPIKAIJ *)A->data;
418: PetscCall(MatDestroy(&m->A));
419: m->A = a;
420: }
421: PetscCall(MatKAIJCheckOperandLayout_Private(A));
422: PetscCall(PetscObjectStateIncrease((PetscObject)A));
423: PetscCall(MatKAIJResetOperandNnzState_Private(A));
424: PetscFunctionReturn(PETSC_SUCCESS);
425: }
427: /*@
428: MatKAIJSetB - Set the `MATAIJ` matrix `B` describing the second Kronecker term $B \otimes S$ of the `MATKAIJ` matrix
430: Logically Collective
432: Input Parameters:
433: + A - the `MATKAIJ` matrix
434: - B - the `MATAIJ` matrix, or `NULL` to make the second term $I_n \otimes S$ (the default `MATKAIJ` behavior)
436: Level: advanced
438: Notes:
439: This function increases the reference count on the `MATAIJ` matrix, so the user is free to destroy the matrix if it is not needed.
441: `B` must share the row and column layout of the `MATAIJ` matrix set with `MatKAIJSetA()`, and in the `MATMPIKAIJ`
442: case it must also share its off-diagonal ghost columns, for example by being assembled from the same `DM`; both
443: requirements are enforced.
445: A common use for `B` is a mass matrix from a differential-algebraic equation; see `MatCreateKAIJAB()`.
447: .seealso: [](ch_matrices), `Mat`, `MATKAIJ`, `MatCreateKAIJAB()`, `MatKAIJGetB()`, `MatKAIJSetA()`, `MatKAIJSetS()`
448: @*/
449: PetscErrorCode MatKAIJSetB(Mat A, Mat B)
450: {
451: Mat_SeqKAIJ *a;
453: PetscFunctionBegin;
455: PetscCheckTypeNames(A, MATSEQKAIJ, MATMPIKAIJ);
456: a = (Mat_SeqKAIJ *)A->data;
457: if (B) {
459: PetscCall(MatKAIJCheckOperandType_Private(A, B));
460: PetscCall(PetscObjectReference((PetscObject)B));
461: }
462: PetscCall(MatDestroy(&a->B));
463: a->B = B;
464: PetscCall(MatKAIJCheckOperandLayout_Private(A));
465: // The second operand changed, so the submatrices must be rebuilt even when neither operand has been reassembled
466: PetscCall(PetscObjectStateIncrease((PetscObject)A));
467: PetscCall(MatKAIJResetOperandNnzState_Private(A));
468: PetscFunctionReturn(PETSC_SUCCESS);
469: }
471: /*@
472: MatKAIJGetB - Get the `MATAIJ` matrix `B` describing the second Kronecker term $B \otimes S$ of the `MATKAIJ` matrix
474: Not Collective, but if the `MATKAIJ` matrix is parallel, the `MATAIJ` matrix is also parallel
476: Input Parameter:
477: . A - the `MATKAIJ` matrix
479: Output Parameter:
480: . B - the `MATAIJ` matrix, or `NULL` if the second term is $I_n \otimes S$
482: Level: advanced
484: Note:
485: The reference count on the `MATAIJ` matrix is not increased so you should not destroy it.
487: .seealso: [](ch_matrices), `Mat`, `MATKAIJ`, `MatCreateKAIJAB()`, `MatKAIJSetB()`, `MatKAIJGetA()`
488: @*/
489: PetscErrorCode MatKAIJGetB(Mat A, Mat *B)
490: {
491: PetscFunctionBegin;
493: PetscAssertPointer(B, 2);
494: PetscCheckTypeNames(A, MATSEQKAIJ, MATMPIKAIJ);
495: *B = ((Mat_SeqKAIJ *)A->data)->B;
496: PetscFunctionReturn(PETSC_SUCCESS);
497: }
499: /*@
500: MatKAIJSetS - Set the `S` matrix describing the shift action of the `MATKAIJ` matrix
502: Logically Collective; the entire `S` is stored independently on all processes.
504: Input Parameters:
505: + A - the `MATKAIJ` matrix
506: . p - the number of rows in `S`
507: . q - the number of columns in `S`
508: - S - the S matrix, in form of a scalar array in column-major format
510: Level: advanced
512: Notes:
513: The dimensions `p` and `q` must match those of the transformation matrix `T` associated with the `MATKAIJ` matrix.
515: The `S` matrix is copied, so the user can destroy this array.
517: .seealso: [](ch_matrices), `Mat`, `MATKAIJ`, `MatKAIJGetS()`, `MatKAIJSetT()`, `MatKAIJSetA()`
518: @*/
519: PetscErrorCode MatKAIJSetS(Mat A, PetscInt p, PetscInt q, const PetscScalar S[])
520: {
521: Mat_SeqKAIJ *a;
523: PetscFunctionBegin;
525: PetscCheckTypeNames(A, MATSEQKAIJ, MATMPIKAIJ);
526: a = (Mat_SeqKAIJ *)A->data;
527: PetscCall(PetscFree(a->S));
528: if (S) {
529: PetscCall(PetscMalloc1(p * q, &a->S));
530: PetscCall(PetscArraycpy(a->S, S, p * q));
531: }
533: a->p = p;
534: a->q = q;
535: PetscCall(PetscObjectStateIncrease((PetscObject)A));
536: PetscFunctionReturn(PETSC_SUCCESS);
537: }
539: /*@
540: MatKAIJGetScaledIdentity - Check if both `S` and `T` are scaled identities and the second operand `B` is the identity.
542: Logically Collective.
544: Input Parameter:
545: . A - the `MATKAIJ` matrix
547: Output Parameter:
548: . identity - the Boolean value
550: Level: advanced
552: .seealso: [](ch_matrices), `Mat`, `MATKAIJ`, `MatKAIJGetS()`, `MatKAIJGetT()`
553: @*/
554: PetscErrorCode MatKAIJGetScaledIdentity(Mat A, PetscBool *identity)
555: {
556: Mat_SeqKAIJ *a;
557: PetscInt i, j;
559: PetscFunctionBegin;
561: PetscAssertPointer(identity, 2);
562: PetscCheckTypeNames(A, MATSEQKAIJ, MATMPIKAIJ);
563: a = (Mat_SeqKAIJ *)A->data;
564: if (a->B) { // a general second operand is not a scaled identity
565: *identity = PETSC_FALSE;
566: PetscFunctionReturn(PETSC_SUCCESS);
567: }
568: if (a->p != a->q) {
569: *identity = PETSC_FALSE;
570: PetscFunctionReturn(PETSC_SUCCESS);
571: } else *identity = PETSC_TRUE;
572: if (!a->isTI || a->S) {
573: for (i = 0; i < a->p && *identity; i++) {
574: for (j = 0; j < a->p && *identity; j++) {
575: if (i != j) {
576: if (a->S && PetscAbsScalar(a->S[i + j * a->p]) > PETSC_SMALL) *identity = PETSC_FALSE;
577: if (a->T && PetscAbsScalar(a->T[i + j * a->p]) > PETSC_SMALL) *identity = PETSC_FALSE;
578: } else {
579: if (a->S && PetscAbsScalar(a->S[i * (a->p + 1)] - a->S[0]) > PETSC_SMALL) *identity = PETSC_FALSE;
580: if (a->T && PetscAbsScalar(a->T[i * (a->p + 1)] - a->T[0]) > PETSC_SMALL) *identity = PETSC_FALSE;
581: }
582: }
583: }
584: }
585: PetscFunctionReturn(PETSC_SUCCESS);
586: }
588: /*@
589: MatKAIJSetT - Set the transformation matrix `T` associated with the `MATKAIJ` matrix
591: Logically Collective; the entire `T` is stored independently on all processes.
593: Input Parameters:
594: + A - the `MATKAIJ` matrix
595: . p - the number of rows in `S`
596: . q - the number of columns in `S`
597: - T - the `T` matrix, in form of a scalar array in column-major format
599: Level: advanced
601: Notes:
602: The dimensions `p` and `q` must match those of the shift matrix `S` associated with the `MATKAIJ` matrix.
604: The `T` matrix is copied, so the user can destroy this array.
606: .seealso: [](ch_matrices), `Mat`, `MATKAIJ`, `MatKAIJGetT()`, `MatKAIJSetS()`, `MatKAIJSetA()`
607: @*/
608: PetscErrorCode MatKAIJSetT(Mat A, PetscInt p, PetscInt q, const PetscScalar T[])
609: {
610: PetscInt i, j;
611: Mat_SeqKAIJ *a;
612: PetscBool isTI = PETSC_FALSE;
614: PetscFunctionBegin;
616: PetscCheckTypeNames(A, MATSEQKAIJ, MATMPIKAIJ);
617: a = (Mat_SeqKAIJ *)A->data;
618: /* check if T is an identity matrix */
619: if (T && (p == q)) {
620: isTI = PETSC_TRUE;
621: for (i = 0; i < p; i++) {
622: for (j = 0; j < q; j++) {
623: if (i == j) {
624: /* diagonal term must be 1 */
625: if (T[i + j * p] != 1.0) isTI = PETSC_FALSE;
626: } else {
627: /* off-diagonal term must be 0 */
628: if (T[i + j * p] != 0.0) isTI = PETSC_FALSE;
629: }
630: }
631: }
632: }
633: a->isTI = isTI;
635: PetscCall(PetscFree(a->T));
636: if (T && (!isTI)) {
637: PetscCall(PetscMalloc1(p * q, &a->T));
638: PetscCall(PetscArraycpy(a->T, T, p * q));
639: }
641: a->p = p;
642: a->q = q;
643: PetscCall(PetscObjectStateIncrease((PetscObject)A));
644: PetscFunctionReturn(PETSC_SUCCESS);
645: }
647: static PetscErrorCode MatDestroy_SeqKAIJ(Mat A)
648: {
649: Mat_SeqKAIJ *b = (Mat_SeqKAIJ *)A->data;
651: PetscFunctionBegin;
652: PetscCall(MatDestroy(&b->AIJ));
653: PetscCall(MatDestroy(&b->B));
654: PetscCall(PetscFree(b->S));
655: PetscCall(PetscFree(b->T));
656: PetscCall(PetscFree(b->ibdiag));
657: PetscCall(PetscFree5(b->sor.w, b->sor.y, b->sor.work, b->sor.t, b->sor.arr));
658: PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatConvert_seqkaij_seqaij_C", NULL));
659: PetscCall(PetscFree(A->data));
660: PetscFunctionReturn(PETSC_SUCCESS);
661: }
663: // Rebuild the ghost scatter of a MATMPIKAIJ only when the ghost columns of its A operand change
664: static PetscErrorCode MatKAIJ_build_scatter(Mat A)
665: {
666: Mat_MPIKAIJ *a = (Mat_MPIKAIJ *)A->data;
667: Mat_MPIAIJ *mpiaij = (Mat_MPIAIJ *)a->A->data;
668: IS from, to;
669: Vec gvec;
670: PetscInt n;
671: PetscBool reusable = PETSC_FALSE;
673: PetscFunctionBegin;
674: a->scatterstale = PETSC_FALSE;
675: PetscCall(VecGetSize(mpiaij->lvec, &n));
676: if (a->ctx && n == a->nghosts) PetscCall(PetscArraycmp(a->ghosts, mpiaij->garray, n, &reusable));
677: PetscCallMPI(MPIU_Allreduce(MPI_IN_PLACE, &reusable, 1, MPI_C_BOOL, MPI_LAND, PetscObjectComm((PetscObject)A)));
678: if (reusable) PetscFunctionReturn(PETSC_SUCCESS);
680: PetscCall(VecScatterDestroy(&a->ctx));
681: PetscCall(VecDestroy(&a->w));
682: PetscCall(PetscFree(a->ghosts));
683: PetscCall(PetscMalloc1(n, &a->ghosts));
684: PetscCall(PetscArraycpy(a->ghosts, mpiaij->garray, n));
685: a->nghosts = n;
687: PetscCall(VecCreate(PETSC_COMM_SELF, &a->w));
688: PetscCall(VecSetSizes(a->w, n * a->q, n * a->q));
689: PetscCall(VecSetBlockSize(a->w, a->q));
690: PetscCall(VecSetType(a->w, VECSEQ));
692: /* create two temporary Index sets for build scatter gather */
693: PetscCall(ISCreateBlock(PetscObjectComm((PetscObject)a->A), a->q, n, mpiaij->garray, PETSC_COPY_VALUES, &from));
694: PetscCall(ISCreateStride(PETSC_COMM_SELF, n * a->q, 0, 1, &to));
696: /* create temporary global vector to generate scatter context */
697: PetscCall(VecCreateMPIWithArray(PetscObjectComm((PetscObject)a->A), a->q, a->q * a->A->cmap->n, a->q * a->A->cmap->N, NULL, &gvec));
699: /* generate the scatter context */
700: PetscCall(VecScatterCreate(gvec, from, a->w, to, &a->ctx));
702: PetscCall(ISDestroy(&from));
703: PetscCall(ISDestroy(&to));
704: PetscCall(VecDestroy(&gvec));
705: PetscFunctionReturn(PETSC_SUCCESS);
706: }
708: static PetscErrorCode MatKAIJ_build_AIJ_OAIJ(Mat A)
709: {
710: Mat_MPIKAIJ *a;
711: Mat_MPIAIJ *mpiaij, *mpibij = NULL;
712: PetscScalar *T;
713: PetscInt i, j;
714: PetscObjectState state, bstate = 0, kstate;
716: PetscFunctionBegin;
717: a = (Mat_MPIKAIJ *)A->data;
718: mpiaij = (Mat_MPIAIJ *)a->A->data;
719: if (a->B) mpibij = (Mat_MPIAIJ *)a->B->data;
721: // The submatrices hold copies of S and T, and a change to S or T raises the state of the KAIJ matrix
722: PetscCall(PetscObjectStateGet((PetscObject)A, &kstate));
723: PetscCall(PetscObjectStateGet((PetscObject)a->A, &state));
724: if (a->B) PetscCall(PetscObjectStateGet((PetscObject)a->B, &bstate));
725: if (a->AIJ && state == a->state && kstate == a->kstate && (!a->B || bstate == a->bstate)) {
726: /* The existing AIJ and KAIJ members are up-to-date, so simply exit. */
727: PetscFunctionReturn(PETSC_SUCCESS);
728: } else {
729: PetscCall(MatDestroy(&a->AIJ));
730: PetscCall(MatDestroy(&a->OAIJ));
731: PetscCall(MatDestroy(&a->OB));
732: if (a->isTI) {
733: /* If the transformation matrix associated with the parallel matrix A is the identity matrix, then a->T will be NULL.
734: * In this case, if we pass a->T directly to the MatCreateKAIJ() calls to create the sequential submatrices, the routine will
735: * not be able to tell that transformation matrix should be set to the identity; thus we create a temporary identity matrix
736: * to pass in. */
737: PetscCall(PetscMalloc1(a->p * a->q, &T));
738: for (i = 0; i < a->p; i++) {
739: for (j = 0; j < a->q; j++) {
740: if (i == j) T[i + j * a->p] = 1.0;
741: else T[i + j * a->p] = 0.0;
742: }
743: }
744: } else T = a->T;
745: if (a->B) {
746: PetscInt an, bn;
748: // The ghost vectors compared below only exist once each operand has been assembled
749: PetscCheck(a->A->assembled && a->B->assembled, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_WRONGSTATE, "The A and B matrices must be assembled before the KAIJ matrix is used");
750: // B reuses A's ghost scatter, so re-verify the shared ghost columns: either operand may have been reassembled since the last build
751: PetscCall(VecGetSize(mpiaij->lvec, &an));
752: PetscCall(VecGetSize(mpibij->lvec, &bn));
753: PetscCheck(an == bn, PETSC_COMM_SELF, PETSC_ERR_ARG_INCOMP, "The B matrix must share the nonzero structure of the A matrix (differing ghost column counts %" PetscInt_FMT " != %" PetscInt_FMT ")", bn, an);
754: for (PetscInt g = 0; g < an; g++)
755: PetscCheck(mpiaij->garray[g] == mpibij->garray[g], PETSC_COMM_SELF, PETSC_ERR_ARG_INCOMP, "The B matrix must share the off-diagonal ghost columns of the A matrix; assemble B with the same nonzero pattern (e.g. from the same DM)");
756: // diagonal block action: (A_diag \otimes T) + (B_diag \otimes S)
757: PetscCall(MatCreateKAIJAB(mpiaij->A, mpibij->A, a->p, a->q, a->S, T, &a->AIJ));
758: // off-diagonal action of A: (A_offdiag \otimes T)
759: PetscCall(MatCreateKAIJ(mpiaij->B, a->p, a->q, NULL, T, &a->OAIJ));
760: // off-diagonal action of B: (B_offdiag \otimes S), expressed with S in the transformation slot
761: PetscCall(MatCreateKAIJ(mpibij->B, a->p, a->q, NULL, a->S, &a->OB));
762: } else {
763: PetscCall(MatCreateKAIJ(mpiaij->A, a->p, a->q, a->S, T, &a->AIJ));
764: PetscCall(MatCreateKAIJ(mpiaij->B, a->p, a->q, NULL, T, &a->OAIJ));
765: }
766: if (a->isTI) PetscCall(PetscFree(T));
767: // The ghost columns of A may have changed. MatMultAdd_MPIKAIJ() rebuilds the scatter collectively
768: a->scatterstale = PETSC_TRUE;
769: a->state = state;
770: a->bstate = bstate;
771: a->kstate = kstate;
772: }
773: PetscFunctionReturn(PETSC_SUCCESS);
774: }
776: static PetscErrorCode MatSetUp_KAIJ(Mat A)
777: {
778: PetscMPIInt size;
779: Mat_SeqKAIJ *seqkaij = (Mat_SeqKAIJ *)A->data;
781: PetscFunctionBegin;
782: PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)A), &size));
783: PetscCall(MatKAIJCheckOperandLayout_Private(A));
784: if (size == 1) {
785: PetscCall(MatSetSizes(A, seqkaij->p * seqkaij->AIJ->rmap->n, seqkaij->q * seqkaij->AIJ->cmap->n, seqkaij->p * seqkaij->AIJ->rmap->N, seqkaij->q * seqkaij->AIJ->cmap->N));
786: PetscCall(PetscLayoutSetBlockSize(A->rmap, seqkaij->p));
787: PetscCall(PetscLayoutSetBlockSize(A->cmap, seqkaij->q));
788: PetscCall(PetscLayoutSetUp(A->rmap));
789: PetscCall(PetscLayoutSetUp(A->cmap));
790: } else {
791: Mat_MPIKAIJ *a = (Mat_MPIKAIJ *)A->data;
793: // MatKAIJ_build_AIJ_OAIJ() below verifies that B shares the off-diagonal ghost columns of A, which the shared ghost scatter requires
794: PetscCall(MatSetSizes(A, a->p * a->A->rmap->n, a->q * a->A->cmap->n, a->p * a->A->rmap->N, a->q * a->A->cmap->N));
795: PetscCall(PetscLayoutSetBlockSize(A->rmap, seqkaij->p));
796: PetscCall(PetscLayoutSetBlockSize(A->cmap, seqkaij->q));
797: PetscCall(PetscLayoutSetUp(A->rmap));
798: PetscCall(PetscLayoutSetUp(A->cmap));
800: PetscCall(MatKAIJ_build_AIJ_OAIJ(A));
801: }
803: // Prime the operand nonzero states so MatAssemblyEnd_KAIJ() forwards only genuine post-setup pattern changes
804: PetscCall(MatKAIJResetOperandNnzState_Private(A));
806: A->assembled = PETSC_TRUE;
807: PetscFunctionReturn(PETSC_SUCCESS);
808: }
810: // Raise the nonzero state of the KAIJ matrix when the nonzero pattern of an operand has changed
811: static PetscErrorCode MatAssemblyEnd_KAIJ(Mat A, MatAssemblyType type)
812: {
813: Mat_SeqKAIJ *kaij = (Mat_SeqKAIJ *)A->data;
814: Mat a, b;
815: PetscObjectState aijnnz = 0, bnnz = 0;
817: PetscFunctionBegin;
818: if (type == MAT_FLUSH_ASSEMBLY) PetscFunctionReturn(PETSC_SUCCESS);
819: PetscCall(MatKAIJGetA(A, &a));
820: PetscCall(MatKAIJGetB(A, &b));
821: if (a) PetscCall(MatGetNonzeroState(a, &aijnnz));
822: if (b) PetscCall(MatGetNonzeroState(b, &bnnz));
823: if (aijnnz != kaij->aijnnzstate || bnnz != kaij->bnnzstate) A->nonzerostate++;
824: kaij->aijnnzstate = aijnnz;
825: kaij->bnnzstate = bnnz;
826: PetscFunctionReturn(PETSC_SUCCESS);
827: }
829: static PetscErrorCode MatView_KAIJ(Mat A, PetscViewer viewer)
830: {
831: PetscViewerFormat format;
832: Mat_SeqKAIJ *a = (Mat_SeqKAIJ *)A->data;
833: Mat B;
834: PetscInt i;
835: PetscBool ismpikaij;
837: PetscFunctionBegin;
838: PetscCall(PetscObjectTypeCompare((PetscObject)A, MATMPIKAIJ, &ismpikaij));
839: PetscCall(PetscViewerGetFormat(viewer, &format));
840: if (format == PETSC_VIEWER_ASCII_INFO || format == PETSC_VIEWER_ASCII_INFO_DETAIL || format == PETSC_VIEWER_ASCII_IMPL) {
841: PetscCall(PetscViewerASCIIPrintf(viewer, "S and T have %" PetscInt_FMT " rows and %" PetscInt_FMT " columns\n", a->p, a->q));
843: /* Print appropriate details for S. */
844: if (!a->S) {
845: PetscCall(PetscViewerASCIIPrintf(viewer, "S is NULL\n"));
846: } else if (format == PETSC_VIEWER_ASCII_IMPL) {
847: PetscCall(PetscViewerASCIIPrintf(viewer, "Entries of S are "));
848: for (i = 0; i < (a->p * a->q); i++) {
849: if (PetscDefined(USE_COMPLEX)) PetscCall(PetscViewerASCIIPrintf(viewer, "%18.16e %18.16e ", (double)PetscRealPart(a->S[i]), (double)PetscImaginaryPart(a->S[i])));
850: else PetscCall(PetscViewerASCIIPrintf(viewer, "%18.16e ", (double)PetscRealPart(a->S[i])));
851: }
852: PetscCall(PetscViewerASCIIPrintf(viewer, "\n"));
853: }
855: /* Print appropriate details for T. */
856: if (a->isTI) {
857: PetscCall(PetscViewerASCIIPrintf(viewer, "T is the identity matrix\n"));
858: } else if (!a->T) {
859: PetscCall(PetscViewerASCIIPrintf(viewer, "T is NULL\n"));
860: } else if (format == PETSC_VIEWER_ASCII_IMPL) {
861: PetscCall(PetscViewerASCIIPrintf(viewer, "Entries of T are "));
862: for (i = 0; i < (a->p * a->q); i++) {
863: if (PetscDefined(USE_COMPLEX)) PetscCall(PetscViewerASCIIPrintf(viewer, "%18.16e %18.16e ", (double)PetscRealPart(a->T[i]), (double)PetscImaginaryPart(a->T[i])));
864: else PetscCall(PetscViewerASCIIPrintf(viewer, "%18.16e ", (double)PetscRealPart(a->T[i])));
865: }
866: PetscCall(PetscViewerASCIIPrintf(viewer, "\n"));
867: }
869: /* Now print details for the A matrix, using its own viewer. */
870: PetscCall(PetscViewerASCIIPrintf(viewer, "Now viewing the associated A matrix:\n"));
871: if (ismpikaij) {
872: Mat_MPIKAIJ *b = (Mat_MPIKAIJ *)A->data;
873: PetscCall(MatView(b->A, viewer));
874: } else {
875: PetscCall(MatView(a->AIJ, viewer));
876: }
878: // Print appropriate details for the second operand B
879: if (!a->B) PetscCall(PetscViewerASCIIPrintf(viewer, "B is the identity matrix\n"));
880: else {
881: PetscCall(PetscViewerASCIIPrintf(viewer, "Now viewing the associated B matrix:\n"));
882: PetscCall(MatView(a->B, viewer));
883: }
885: } else {
886: /* For all other matrix viewer output formats, simply convert to an AIJ matrix and call MatView() on that. */
887: PetscCall(MatConvert(A, MATAIJ, MAT_INITIAL_MATRIX, &B));
888: PetscCall(MatView(B, viewer));
889: PetscCall(MatDestroy(&B));
890: }
891: PetscFunctionReturn(PETSC_SUCCESS);
892: }
894: static PetscErrorCode MatDestroy_MPIKAIJ(Mat A)
895: {
896: Mat_MPIKAIJ *b = (Mat_MPIKAIJ *)A->data;
898: PetscFunctionBegin;
899: PetscCall(MatDestroy(&b->AIJ));
900: PetscCall(MatDestroy(&b->OAIJ));
901: PetscCall(MatDestroy(&b->OB));
902: PetscCall(MatDestroy(&b->A));
903: PetscCall(MatDestroy(&b->B));
904: PetscCall(VecScatterDestroy(&b->ctx));
905: PetscCall(VecDestroy(&b->w));
906: PetscCall(PetscFree(b->ghosts));
907: PetscCall(PetscFree(b->S));
908: PetscCall(PetscFree(b->T));
909: PetscCall(PetscFree(b->ibdiag));
910: PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatConvert_mpikaij_mpiaij_C", NULL));
911: PetscCall(PetscFree(A->data));
912: PetscFunctionReturn(PETSC_SUCCESS);
913: }
915: /* zz = yy + Axx */
916: static PetscErrorCode MatMultAdd_SeqKAIJ(Mat A, Vec xx, Vec yy, Vec zz)
917: {
918: Mat_SeqKAIJ *b = (Mat_SeqKAIJ *)A->data;
919: Mat_SeqAIJ *a = (Mat_SeqAIJ *)b->AIJ->data;
920: Mat_SeqAIJ *bb = b->B ? (Mat_SeqAIJ *)b->B->data : NULL;
921: const PetscScalar *s = b->S, *t = b->T;
922: const PetscScalar *x, *v, *bx, *bv;
923: PetscScalar *y, *sums;
924: const PetscInt m = b->AIJ->rmap->n;
925: const PetscInt *idx, *ii, *bidx, *bii;
926: PetscInt n, i, jrow, j, l, p = b->p, q = b->q, k;
928: PetscFunctionBegin;
929: if (!yy) PetscCall(VecSet(zz, 0.0));
930: else PetscCall(VecCopy(yy, zz));
931: if ((!s) && (!t) && (!b->isTI)) PetscFunctionReturn(PETSC_SUCCESS);
933: PetscCall(VecGetArrayRead(xx, &x));
934: PetscCall(VecGetArray(zz, &y));
935: idx = a->j;
936: v = a->a;
937: ii = a->i;
939: if (b->isTI) {
940: for (i = 0; i < m; i++) {
941: jrow = ii[i];
942: n = ii[i + 1] - jrow;
943: sums = y + p * i;
944: for (j = 0; j < n; j++) {
945: for (k = 0; k < p; k++) sums[k] += v[jrow + j] * x[q * idx[jrow + j] + k];
946: }
947: }
948: PetscCall(PetscLogFlops(3.0 * (a->nz) * p));
949: } else if (t) {
950: for (i = 0; i < m; i++) {
951: jrow = ii[i];
952: n = ii[i + 1] - jrow;
953: sums = y + p * i;
954: for (j = 0; j < n; j++) {
955: for (k = 0; k < p; k++) {
956: for (l = 0; l < q; l++) sums[k] += v[jrow + j] * t[k + l * p] * x[q * idx[jrow + j] + l];
957: }
958: }
959: }
960: /* The flop count below assumes that v[jrow+j] is hoisted out (which an optimizing compiler is likely to do),
961: * and also that T part is hoisted outside this loop (in exchange for temporary storage) as (A \otimes I) (I \otimes T),
962: * so that this multiply doesn't have to be redone for each matrix entry, but just once per column. The latter
963: * transformation is much less likely to be applied, but we nonetheless count the minimum flops required. */
964: PetscCall(PetscLogFlops((2.0 * p * q - p) * m + 2.0 * p * a->nz));
965: }
966: if (s && !bb) { // (I \otimes S): S acts only on the diagonal block
967: for (i = 0; i < m; i++) {
968: sums = y + p * i;
969: bx = x + q * i;
970: if (i < b->AIJ->cmap->n) {
971: for (j = 0; j < q; j++) {
972: for (k = 0; k < p; k++) sums[k] += s[k + j * p] * bx[j];
973: }
974: }
975: }
976: PetscCall(PetscLogFlops(2.0 * m * p * q));
977: } else if (s) { // (B \otimes S): sparse matvec over the rows of B
978: bidx = bb->j;
979: bv = bb->a;
980: bii = bb->i;
981: for (i = 0; i < m; i++) {
982: jrow = bii[i];
983: n = bii[i + 1] - jrow;
984: sums = y + p * i;
985: for (j = 0; j < n; j++) {
986: for (k = 0; k < p; k++) {
987: for (l = 0; l < q; l++) sums[k] += bv[jrow + j] * s[k + l * p] * x[q * bidx[jrow + j] + l];
988: }
989: }
990: }
991: PetscCall(PetscLogFlops((2.0 * p * q - p) * m + 2.0 * p * bb->nz));
992: }
994: PetscCall(VecRestoreArrayRead(xx, &x));
995: PetscCall(VecRestoreArray(zz, &y));
996: PetscFunctionReturn(PETSC_SUCCESS);
997: }
999: static PetscErrorCode MatMult_SeqKAIJ(Mat A, Vec xx, Vec yy)
1000: {
1001: PetscFunctionBegin;
1002: PetscCall(MatMultAdd_SeqKAIJ(A, xx, NULL, yy));
1003: PetscFunctionReturn(PETSC_SUCCESS);
1004: }
1006: #include <petsc/private/kernels/blockinvert.h>
1008: static PetscErrorCode MatInvertBlockDiagonal_SeqKAIJ(Mat A, const PetscScalar **values)
1009: {
1010: Mat_SeqKAIJ *b = (Mat_SeqKAIJ *)A->data;
1011: Mat_SeqAIJ *a = (Mat_SeqAIJ *)b->AIJ->data;
1012: Mat_SeqAIJ *bb = b->B ? (Mat_SeqAIJ *)b->B->data : NULL;
1013: const PetscScalar *S = b->S;
1014: const PetscScalar *T = b->T;
1015: const PetscScalar *v = a->a, *bv = bb ? bb->a : NULL;
1016: const PetscInt p = b->p, q = b->q, m = b->AIJ->rmap->n, *idx = a->j, *ii = a->i;
1017: const PetscInt *bidx = bb ? bb->j : NULL, *bii = bb ? bb->i : NULL;
1018: PetscInt i, j, *v_pivots, dof, dof2;
1019: PetscObjectState astate, bstate = 0, kstate;
1020: PetscScalar aval, bval;
1021: PetscScalar *diag, *v_work;
1023: PetscFunctionBegin;
1024: PetscCheck(p == q, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "MATKAIJ: Block size must be square to calculate inverse.");
1025: PetscCheck(S || T || b->isTI, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "MATKAIJ: Cannot invert a zero matrix.");
1027: dof = p;
1028: dof2 = dof * dof;
1030: /* Invalidate the cached block-diagonal if the entries of A or B, or the dense blocks S or T, have changed.
1031: Changes to S and T are signaled by the state of the KAIJ matrix, which MatKAIJRestoreS() and MatKAIJRestoreT() increase. */
1032: PetscCall(PetscObjectStateGet((PetscObject)A, &kstate));
1033: PetscCall(PetscObjectStateGet((PetscObject)b->AIJ, &astate));
1034: if (b->B) PetscCall(PetscObjectStateGet((PetscObject)b->B, &bstate));
1035: if (astate != b->ibdiagstate || bstate != b->ibdiagbstate || kstate != b->ibdiagkstate) b->ibdiagvalid = PETSC_FALSE;
1037: if (b->ibdiagvalid) {
1038: if (values) *values = b->ibdiag;
1039: PetscFunctionReturn(PETSC_SUCCESS);
1040: }
1041: // the block size or the operand row count may have changed the size the buffer needs
1042: if (b->ibdiag && b->ibdiagcount != dof2 * m) PetscCall(PetscFree(b->ibdiag));
1043: if (!b->ibdiag) {
1044: PetscCall(PetscMalloc1(dof2 * m, &b->ibdiag));
1045: b->ibdiagcount = dof2 * m;
1046: }
1047: if (values) *values = b->ibdiag;
1048: diag = b->ibdiag;
1050: PetscCall(PetscMalloc2(dof, &v_work, dof, &v_pivots));
1051: for (i = 0; i < m; i++) {
1052: // block diagonal for dof i is A_ii * T + B_ii * S (with B_ii = 1 when B is the identity)
1053: PetscCall(PetscArrayzero(diag, dof2));
1054: if (S) {
1055: if (bb) {
1056: bval = 0;
1057: for (j = bii[i]; j < bii[i + 1]; j++)
1058: if (bidx[j] == i) bval = bv[j];
1059: for (j = 0; j < dof2; j++) diag[j] += bval * S[j];
1060: } else
1061: for (j = 0; j < dof2; j++) diag[j] += S[j];
1062: }
1063: if (b->isTI) {
1064: aval = 0;
1065: for (j = ii[i]; j < ii[i + 1]; j++)
1066: if (idx[j] == i) aval = v[j];
1067: for (j = 0; j < dof; j++) diag[j + dof * j] += aval;
1068: } else if (T) {
1069: aval = 0;
1070: for (j = ii[i]; j < ii[i + 1]; j++)
1071: if (idx[j] == i) aval = v[j];
1072: for (j = 0; j < dof2; j++) diag[j] += aval * T[j];
1073: }
1074: PetscCall(PetscKernel_A_gets_inverse_A(dof, diag, v_pivots, v_work, PETSC_FALSE, NULL));
1075: diag += dof2;
1076: }
1077: PetscCall(PetscFree2(v_work, v_pivots));
1079: b->ibdiagvalid = PETSC_TRUE;
1080: b->ibdiagstate = astate;
1081: b->ibdiagbstate = bstate;
1082: b->ibdiagkstate = kstate;
1083: PetscFunctionReturn(PETSC_SUCCESS);
1084: }
1086: static PetscErrorCode MatGetDiagonalBlock_MPIKAIJ(Mat A, Mat *B)
1087: {
1088: Mat_MPIKAIJ *kaij = (Mat_MPIKAIJ *)A->data;
1090: PetscFunctionBegin;
1091: PetscCall(MatKAIJ_build_AIJ_OAIJ(A)); // A rebuild replaces b->AIJ, so do it before b->AIJ is returned
1092: *B = kaij->AIJ;
1093: PetscFunctionReturn(PETSC_SUCCESS);
1094: }
1096: static PetscErrorCode MatConvert_KAIJ_AIJ(Mat A, MatType newtype, MatReuse reuse, Mat *newmat)
1097: {
1098: Mat_SeqKAIJ *a = (Mat_SeqKAIJ *)A->data;
1099: Mat AIJ, OAIJ, B;
1100: PetscInt *d_nnz, *o_nnz = NULL, nz, i, j, m, d;
1101: const PetscInt p = a->p, q = a->q;
1102: PetscBool ismpikaij, diagDense;
1103: const PetscInt *aijdiag;
1105: PetscFunctionBegin;
1106: PetscCheck(!a->B, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "MATKAIJ: MatConvert() is not implemented for a KAIJ matrix with a general second operand B");
1107: if (reuse != MAT_REUSE_MATRIX) {
1108: PetscCall(PetscObjectTypeCompare((PetscObject)A, MATMPIKAIJ, &ismpikaij));
1109: if (ismpikaij) {
1110: Mat_MPIKAIJ *b = (Mat_MPIKAIJ *)A->data;
1111: AIJ = ((Mat_SeqKAIJ *)b->AIJ->data)->AIJ;
1112: OAIJ = ((Mat_SeqKAIJ *)b->OAIJ->data)->AIJ;
1113: } else {
1114: AIJ = a->AIJ;
1115: OAIJ = NULL;
1116: }
1117: PetscCall(MatCreate(PetscObjectComm((PetscObject)A), &B));
1118: PetscCall(MatSetSizes(B, A->rmap->n, A->cmap->n, A->rmap->N, A->cmap->N));
1119: PetscCall(MatSetType(B, MATAIJ));
1120: PetscCall(MatGetSize(AIJ, &m, NULL));
1122: /*
1123: Determine the first row of A with missing diagonal and assume all successive rows also have a missing diagonal
1124: */
1125: PetscCall(MatGetDiagonalMarkers_SeqAIJ(AIJ, &aijdiag, &diagDense));
1126: if (diagDense || !a->S) d = m;
1127: else {
1128: Mat_SeqAIJ *aij = (Mat_SeqAIJ *)AIJ->data;
1130: for (d = 0; d < m; d++) {
1131: if (aijdiag[d] == aij->i[d + 1]) break;
1132: }
1133: }
1134: PetscCall(PetscMalloc1(m * p, &d_nnz));
1135: for (i = 0; i < m; ++i) {
1136: PetscCall(MatGetRow_SeqAIJ(AIJ, i, &nz, NULL, NULL));
1137: for (j = 0; j < p; ++j) d_nnz[i * p + j] = nz * q + (i >= d) * q;
1138: PetscCall(MatRestoreRow_SeqAIJ(AIJ, i, &nz, NULL, NULL));
1139: }
1140: if (OAIJ) {
1141: PetscCall(PetscMalloc1(m * p, &o_nnz));
1142: for (i = 0; i < m; ++i) {
1143: PetscCall(MatGetRow_SeqAIJ(OAIJ, i, &nz, NULL, NULL));
1144: for (j = 0; j < p; ++j) o_nnz[i * p + j] = nz * q;
1145: PetscCall(MatRestoreRow_SeqAIJ(OAIJ, i, &nz, NULL, NULL));
1146: }
1147: PetscCall(MatMPIAIJSetPreallocation(B, 0, d_nnz, 0, o_nnz));
1148: } else {
1149: PetscCall(MatSeqAIJSetPreallocation(B, 0, d_nnz));
1150: }
1151: PetscCall(PetscFree(d_nnz));
1152: PetscCall(PetscFree(o_nnz));
1153: } else B = *newmat;
1154: PetscCall(MatConvert_Basic(A, newtype, MAT_REUSE_MATRIX, &B));
1155: if (reuse == MAT_INPLACE_MATRIX) PetscCall(MatHeaderReplace(A, &B));
1156: else *newmat = B;
1157: PetscFunctionReturn(PETSC_SUCCESS);
1158: }
1160: static PetscErrorCode MatSOR_SeqKAIJ(Mat A, Vec bb, PetscReal omega, MatSORType flag, PetscReal fshift, PetscInt its, PetscInt lits, Vec xx)
1161: {
1162: Mat_SeqKAIJ *kaij = (Mat_SeqKAIJ *)A->data;
1163: Mat_SeqAIJ *a = (Mat_SeqAIJ *)kaij->AIJ->data;
1164: const PetscScalar *aa = a->a, *T = kaij->T, *v;
1165: const PetscInt m = kaij->AIJ->rmap->n, *ai = a->i, *aj = a->j, p = kaij->p, q = kaij->q, *diag, *vi;
1166: const PetscScalar *b, *xb, *idiag;
1167: PetscScalar *x, *work, *workt, *w, *y, *arr, *t, *arrt;
1168: PetscInt i, j, k, i2, bs, bs2, nz;
1170: PetscFunctionBegin;
1171: PetscCheck(!kaij->B, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "MATKAIJ: MatSOR() is not implemented for a KAIJ matrix with a general second operand B");
1172: its = its * lits;
1173: PetscCheck(!(flag & SOR_EISENSTAT), PETSC_COMM_SELF, PETSC_ERR_SUP, "No support yet for Eisenstat");
1174: PetscCheck(its > 0, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Relaxation requires global its %" PetscInt_FMT " and local its %" PetscInt_FMT " both positive", its, lits);
1175: PetscCheck(!fshift, PETSC_COMM_SELF, PETSC_ERR_SUP, "No support for diagonal shift");
1176: PetscCheck(!(flag & SOR_APPLY_UPPER) && !(flag & SOR_APPLY_LOWER), PETSC_COMM_SELF, PETSC_ERR_SUP, "No support for applying upper or lower triangular parts");
1177: PetscCheck(p == q, PETSC_COMM_SELF, PETSC_ERR_SUP, "MatSOR for KAIJ: No support for non-square dense blocks");
1178: bs = p;
1179: bs2 = bs * bs;
1181: if (!m) PetscFunctionReturn(PETSC_SUCCESS);
1183: // Call unconditionally: the routine returns the cached block diagonal when it is still valid and recomputes it when the operands have changed
1184: PetscCall(MatInvertBlockDiagonal_SeqKAIJ(A, NULL));
1185: idiag = kaij->ibdiag;
1186: PetscCall(MatGetDiagonalMarkers_SeqAIJ(kaij->AIJ, &diag, NULL));
1188: if (!kaij->sor.setup) {
1189: PetscCall(PetscMalloc5(bs, &kaij->sor.w, bs, &kaij->sor.y, m * bs, &kaij->sor.work, m * bs, &kaij->sor.t, m * bs2, &kaij->sor.arr));
1190: kaij->sor.setup = PETSC_TRUE;
1191: }
1192: y = kaij->sor.y;
1193: w = kaij->sor.w;
1194: work = kaij->sor.work;
1195: t = kaij->sor.t;
1196: arr = kaij->sor.arr;
1198: PetscCall(VecGetArray(xx, &x));
1199: PetscCall(VecGetArrayRead(bb, &b));
1201: if (flag & SOR_ZERO_INITIAL_GUESS) {
1202: if (flag & SOR_FORWARD_SWEEP || flag & SOR_LOCAL_FORWARD_SWEEP) {
1203: PetscKernel_w_gets_Ar_times_v(bs, bs, b, idiag, x); /* x[0:bs] <- D^{-1} b[0:bs] */
1204: PetscCall(PetscArraycpy(t, b, bs));
1205: i2 = bs;
1206: idiag += bs2;
1207: for (i = 1; i < m; i++) {
1208: v = aa + ai[i];
1209: vi = aj + ai[i];
1210: nz = diag[i] - ai[i];
1212: if (T) { /* b - T (Arow * x) */
1213: PetscCall(PetscArrayzero(w, bs));
1214: for (j = 0; j < nz; j++) {
1215: for (k = 0; k < bs; k++) w[k] -= v[j] * x[vi[j] * bs + k];
1216: }
1217: PetscKernel_w_gets_w_minus_Ar_times_v(bs, bs, w, T, &t[i2]);
1218: for (k = 0; k < bs; k++) t[i2 + k] += b[i2 + k];
1219: } else if (kaij->isTI) {
1220: PetscCall(PetscArraycpy(t + i2, b + i2, bs));
1221: for (j = 0; j < nz; j++) {
1222: for (k = 0; k < bs; k++) t[i2 + k] -= v[j] * x[vi[j] * bs + k];
1223: }
1224: } else {
1225: PetscCall(PetscArraycpy(t + i2, b + i2, bs));
1226: }
1228: PetscKernel_w_gets_Ar_times_v(bs, bs, t + i2, idiag, y);
1229: for (j = 0; j < bs; j++) x[i2 + j] = omega * y[j];
1231: idiag += bs2;
1232: i2 += bs;
1233: }
1234: /* for logging purposes assume number of nonzero in lower half is 1/2 of total */
1235: PetscCall(PetscLogFlops(1.0 * bs2 * a->nz));
1236: xb = t;
1237: } else xb = b;
1238: if (flag & SOR_BACKWARD_SWEEP || flag & SOR_LOCAL_BACKWARD_SWEEP) {
1239: idiag = kaij->ibdiag + bs2 * (m - 1);
1240: i2 = bs * (m - 1);
1241: PetscCall(PetscArraycpy(w, xb + i2, bs));
1242: PetscKernel_w_gets_Ar_times_v(bs, bs, w, idiag, x + i2);
1243: i2 -= bs;
1244: idiag -= bs2;
1245: for (i = m - 2; i >= 0; i--) {
1246: v = aa + diag[i] + 1;
1247: vi = aj + diag[i] + 1;
1248: nz = ai[i + 1] - diag[i] - 1;
1250: if (T) { /* FIXME: This branch untested */
1251: PetscCall(PetscArraycpy(w, xb + i2, bs));
1252: /* copy all rows of x that are needed into contiguous space */
1253: workt = work;
1254: for (j = 0; j < nz; j++) {
1255: PetscCall(PetscArraycpy(workt, x + bs * (*vi++), bs));
1256: workt += bs;
1257: }
1258: arrt = arr;
1259: for (j = 0; j < nz; j++) {
1260: PetscCall(PetscArraycpy(arrt, T, bs2));
1261: for (k = 0; k < bs2; k++) arrt[k] *= v[j];
1262: arrt += bs2;
1263: }
1264: PetscKernel_w_gets_w_minus_Ar_times_v(bs, bs * nz, w, arr, work);
1265: } else if (kaij->isTI) {
1266: PetscCall(PetscArraycpy(w, t + i2, bs));
1267: for (j = 0; j < nz; j++) {
1268: for (k = 0; k < bs; k++) w[k] -= v[j] * x[vi[j] * bs + k];
1269: }
1270: }
1272: PetscKernel_w_gets_Ar_times_v(bs, bs, w, idiag, y); /* RHS incorrect for omega != 1.0 */
1273: for (j = 0; j < bs; j++) x[i2 + j] = (1.0 - omega) * x[i2 + j] + omega * y[j];
1275: idiag -= bs2;
1276: i2 -= bs;
1277: }
1278: PetscCall(PetscLogFlops(1.0 * bs2 * (a->nz)));
1279: }
1280: its--;
1281: }
1282: while (its--) { /* FIXME: This branch not updated */
1283: if (flag & SOR_FORWARD_SWEEP || flag & SOR_LOCAL_FORWARD_SWEEP) {
1284: i2 = 0;
1285: idiag = kaij->ibdiag;
1286: for (i = 0; i < m; i++) {
1287: PetscCall(PetscArraycpy(w, b + i2, bs));
1289: v = aa + ai[i];
1290: vi = aj + ai[i];
1291: nz = diag[i] - ai[i];
1292: workt = work;
1293: for (j = 0; j < nz; j++) {
1294: PetscCall(PetscArraycpy(workt, x + bs * (*vi++), bs));
1295: workt += bs;
1296: }
1297: arrt = arr;
1298: if (T) {
1299: for (j = 0; j < nz; j++) {
1300: PetscCall(PetscArraycpy(arrt, T, bs2));
1301: for (k = 0; k < bs2; k++) arrt[k] *= v[j];
1302: arrt += bs2;
1303: }
1304: PetscKernel_w_gets_w_minus_Ar_times_v(bs, bs * nz, w, arr, work);
1305: } else if (kaij->isTI) {
1306: for (j = 0; j < nz; j++) {
1307: PetscCall(PetscArrayzero(arrt, bs2));
1308: for (k = 0; k < bs; k++) arrt[k + bs * k] = v[j];
1309: arrt += bs2;
1310: }
1311: PetscKernel_w_gets_w_minus_Ar_times_v(bs, bs * nz, w, arr, work);
1312: }
1313: PetscCall(PetscArraycpy(t + i2, w, bs));
1315: v = aa + diag[i] + 1;
1316: vi = aj + diag[i] + 1;
1317: nz = ai[i + 1] - diag[i] - 1;
1318: workt = work;
1319: for (j = 0; j < nz; j++) {
1320: PetscCall(PetscArraycpy(workt, x + bs * (*vi++), bs));
1321: workt += bs;
1322: }
1323: arrt = arr;
1324: if (T) {
1325: for (j = 0; j < nz; j++) {
1326: PetscCall(PetscArraycpy(arrt, T, bs2));
1327: for (k = 0; k < bs2; k++) arrt[k] *= v[j];
1328: arrt += bs2;
1329: }
1330: PetscKernel_w_gets_w_minus_Ar_times_v(bs, bs * nz, w, arr, work);
1331: } else if (kaij->isTI) {
1332: for (j = 0; j < nz; j++) {
1333: PetscCall(PetscArrayzero(arrt, bs2));
1334: for (k = 0; k < bs; k++) arrt[k + bs * k] = v[j];
1335: arrt += bs2;
1336: }
1337: PetscKernel_w_gets_w_minus_Ar_times_v(bs, bs * nz, w, arr, work);
1338: }
1340: PetscKernel_w_gets_Ar_times_v(bs, bs, w, idiag, y);
1341: for (j = 0; j < bs; j++) *(x + i2 + j) = (1.0 - omega) * *(x + i2 + j) + omega * *(y + j);
1343: idiag += bs2;
1344: i2 += bs;
1345: }
1346: xb = t;
1347: } else xb = b;
1348: if (flag & SOR_BACKWARD_SWEEP || flag & SOR_LOCAL_BACKWARD_SWEEP) {
1349: idiag = kaij->ibdiag + bs2 * (m - 1);
1350: i2 = bs * (m - 1);
1351: if (xb == b) {
1352: for (i = m - 1; i >= 0; i--) {
1353: PetscCall(PetscArraycpy(w, b + i2, bs));
1355: v = aa + ai[i];
1356: vi = aj + ai[i];
1357: nz = diag[i] - ai[i];
1358: workt = work;
1359: for (j = 0; j < nz; j++) {
1360: PetscCall(PetscArraycpy(workt, x + bs * (*vi++), bs));
1361: workt += bs;
1362: }
1363: arrt = arr;
1364: if (T) {
1365: for (j = 0; j < nz; j++) {
1366: PetscCall(PetscArraycpy(arrt, T, bs2));
1367: for (k = 0; k < bs2; k++) arrt[k] *= v[j];
1368: arrt += bs2;
1369: }
1370: PetscKernel_w_gets_w_minus_Ar_times_v(bs, bs * nz, w, arr, work);
1371: } else if (kaij->isTI) {
1372: for (j = 0; j < nz; j++) {
1373: PetscCall(PetscArrayzero(arrt, bs2));
1374: for (k = 0; k < bs; k++) arrt[k + bs * k] = v[j];
1375: arrt += bs2;
1376: }
1377: PetscKernel_w_gets_w_minus_Ar_times_v(bs, bs * nz, w, arr, work);
1378: }
1380: v = aa + diag[i] + 1;
1381: vi = aj + diag[i] + 1;
1382: nz = ai[i + 1] - diag[i] - 1;
1383: workt = work;
1384: for (j = 0; j < nz; j++) {
1385: PetscCall(PetscArraycpy(workt, x + bs * (*vi++), bs));
1386: workt += bs;
1387: }
1388: arrt = arr;
1389: if (T) {
1390: for (j = 0; j < nz; j++) {
1391: PetscCall(PetscArraycpy(arrt, T, bs2));
1392: for (k = 0; k < bs2; k++) arrt[k] *= v[j];
1393: arrt += bs2;
1394: }
1395: PetscKernel_w_gets_w_minus_Ar_times_v(bs, bs * nz, w, arr, work);
1396: } else if (kaij->isTI) {
1397: for (j = 0; j < nz; j++) {
1398: PetscCall(PetscArrayzero(arrt, bs2));
1399: for (k = 0; k < bs; k++) arrt[k + bs * k] = v[j];
1400: arrt += bs2;
1401: }
1402: PetscKernel_w_gets_w_minus_Ar_times_v(bs, bs * nz, w, arr, work);
1403: }
1405: PetscKernel_w_gets_Ar_times_v(bs, bs, w, idiag, y);
1406: for (j = 0; j < bs; j++) *(x + i2 + j) = (1.0 - omega) * *(x + i2 + j) + omega * *(y + j);
1407: }
1408: } else {
1409: for (i = m - 1; i >= 0; i--) {
1410: PetscCall(PetscArraycpy(w, xb + i2, bs));
1411: v = aa + diag[i] + 1;
1412: vi = aj + diag[i] + 1;
1413: nz = ai[i + 1] - diag[i] - 1;
1414: workt = work;
1415: for (j = 0; j < nz; j++) {
1416: PetscCall(PetscArraycpy(workt, x + bs * (*vi++), bs));
1417: workt += bs;
1418: }
1419: arrt = arr;
1420: if (T) {
1421: for (j = 0; j < nz; j++) {
1422: PetscCall(PetscArraycpy(arrt, T, bs2));
1423: for (k = 0; k < bs2; k++) arrt[k] *= v[j];
1424: arrt += bs2;
1425: }
1426: PetscKernel_w_gets_w_minus_Ar_times_v(bs, bs * nz, w, arr, work);
1427: } else if (kaij->isTI) {
1428: for (j = 0; j < nz; j++) {
1429: PetscCall(PetscArrayzero(arrt, bs2));
1430: for (k = 0; k < bs; k++) arrt[k + bs * k] = v[j];
1431: arrt += bs2;
1432: }
1433: PetscKernel_w_gets_w_minus_Ar_times_v(bs, bs * nz, w, arr, work);
1434: }
1435: PetscKernel_w_gets_Ar_times_v(bs, bs, w, idiag, y);
1436: for (j = 0; j < bs; j++) *(x + i2 + j) = (1.0 - omega) * *(x + i2 + j) + omega * *(y + j);
1437: }
1438: }
1439: PetscCall(PetscLogFlops(1.0 * bs2 * (a->nz)));
1440: }
1441: }
1443: PetscCall(VecRestoreArray(xx, &x));
1444: PetscCall(VecRestoreArrayRead(bb, &b));
1445: PetscFunctionReturn(PETSC_SUCCESS);
1446: }
1448: /*===================================================================================*/
1450: static PetscErrorCode MatMultAdd_MPIKAIJ(Mat A, Vec xx, Vec yy, Vec zz)
1451: {
1452: Mat_MPIKAIJ *b = (Mat_MPIKAIJ *)A->data;
1454: PetscFunctionBegin;
1455: if (!yy) PetscCall(VecSet(zz, 0.0));
1456: else PetscCall(VecCopy(yy, zz));
1457: PetscCall(MatKAIJ_build_AIJ_OAIJ(A)); /* Ensure b->AIJ, b->OAIJ and b->OB are up to date. */
1458: if (b->scatterstale) PetscCall(MatKAIJ_build_scatter(A));
1459: /* start the scatter */
1460: PetscCall(VecScatterBegin(b->ctx, xx, b->w, INSERT_VALUES, SCATTER_FORWARD));
1461: PetscUseTypeMethod(b->AIJ, multadd, xx, zz, zz);
1462: PetscCall(VecScatterEnd(b->ctx, xx, b->w, INSERT_VALUES, SCATTER_FORWARD));
1463: PetscUseTypeMethod(b->OAIJ, multadd, b->w, zz, zz);
1464: // B shares A's nonzero structure, so it reuses the same ghost values in b->w
1465: if (b->OB) PetscUseTypeMethod(b->OB, multadd, b->w, zz, zz);
1466: PetscFunctionReturn(PETSC_SUCCESS);
1467: }
1469: static PetscErrorCode MatMult_MPIKAIJ(Mat A, Vec xx, Vec yy)
1470: {
1471: PetscFunctionBegin;
1472: PetscCall(MatMultAdd_MPIKAIJ(A, xx, NULL, yy));
1473: PetscFunctionReturn(PETSC_SUCCESS);
1474: }
1476: // Return a copy owned by this matrix, because a rebuild of b->AIJ frees the buffer of the submatrix
1477: static PetscErrorCode MatInvertBlockDiagonal_MPIKAIJ(Mat A, const PetscScalar **values)
1478: {
1479: Mat_MPIKAIJ *b = (Mat_MPIKAIJ *)A->data;
1480: const PetscScalar *diag;
1481: PetscInt nb;
1483: PetscFunctionBegin;
1484: PetscCall(MatKAIJ_build_AIJ_OAIJ(A)); /* Ensure b->AIJ is up to date. */
1485: PetscUseTypeMethod(b->AIJ, invertblockdiagonal, &diag);
1486: nb = b->p * b->p * b->A->rmap->n; // MatInvertBlockDiagonal_SeqKAIJ() requires p == q
1487: // the block size or the operand row count may have changed the size the buffer needs
1488: if (b->ibdiag && b->ibdiagcount != nb) PetscCall(PetscFree(b->ibdiag));
1489: if (!b->ibdiag) {
1490: PetscCall(PetscMalloc1(nb, &b->ibdiag));
1491: b->ibdiagcount = nb;
1492: }
1493: PetscCall(PetscArraycpy(b->ibdiag, diag, nb));
1494: if (values) *values = b->ibdiag;
1495: PetscFunctionReturn(PETSC_SUCCESS);
1496: }
1498: static PetscErrorCode MatGetRow_SeqKAIJ(Mat A, PetscInt row, PetscInt *ncols, PetscInt **cols, PetscScalar **values)
1499: {
1500: Mat_SeqKAIJ *b = (Mat_SeqKAIJ *)A->data;
1501: PetscBool diag = PETSC_FALSE;
1502: PetscInt nzaij, nz, *colsaij, *idx, i, j, p = b->p, q = b->q, r = row / p, s = row % p, c;
1503: PetscScalar *vaij, *v, *S = b->S, *T = b->T;
1505: PetscFunctionBegin;
1506: PetscCheck(!b->B, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "MATKAIJ: MatGetRow() is not implemented for a KAIJ matrix with a general second operand B");
1507: PetscCheck(!b->getrowactive, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Already active");
1508: b->getrowactive = PETSC_TRUE;
1509: PetscCheck(row >= 0 && row < A->rmap->n, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Row %" PetscInt_FMT " out of range", row);
1511: if ((!S) && (!T) && (!b->isTI)) {
1512: if (ncols) *ncols = 0;
1513: if (cols) *cols = NULL;
1514: if (values) *values = NULL;
1515: PetscFunctionReturn(PETSC_SUCCESS);
1516: }
1518: if (T || b->isTI) {
1519: PetscCall(MatGetRow_SeqAIJ(b->AIJ, r, &nzaij, &colsaij, &vaij));
1520: c = nzaij;
1521: for (i = 0; i < nzaij; i++) {
1522: /* check if this row contains a diagonal entry */
1523: if (colsaij[i] == r) {
1524: diag = PETSC_TRUE;
1525: c = i;
1526: }
1527: }
1528: } else nzaij = c = 0;
1530: /* calculate size of row */
1531: nz = 0;
1532: if (S) nz += q;
1533: if (T || b->isTI) nz += (diag && S ? (nzaij - 1) * q : nzaij * q);
1535: if (cols || values) {
1536: PetscCall(PetscMalloc2(nz, &idx, nz, &v));
1537: for (i = 0; i < q; i++) {
1538: /* We need to initialize the v[i] to zero to handle the case in which T is NULL (not the identity matrix). */
1539: v[i] = 0.0;
1540: }
1541: if (b->isTI) {
1542: for (i = 0; i < nzaij; i++) {
1543: for (j = 0; j < q; j++) {
1544: idx[i * q + j] = colsaij[i] * q + j;
1545: v[i * q + j] = (j == s ? vaij[i] : 0);
1546: }
1547: }
1548: } else if (T) {
1549: for (i = 0; i < nzaij; i++) {
1550: for (j = 0; j < q; j++) {
1551: idx[i * q + j] = colsaij[i] * q + j;
1552: v[i * q + j] = vaij[i] * T[s + j * p];
1553: }
1554: }
1555: }
1556: if (S) {
1557: for (j = 0; j < q; j++) {
1558: idx[c * q + j] = r * q + j;
1559: v[c * q + j] += S[s + j * p];
1560: }
1561: }
1562: }
1564: if (ncols) *ncols = nz;
1565: if (cols) *cols = idx;
1566: if (values) *values = v;
1567: PetscFunctionReturn(PETSC_SUCCESS);
1568: }
1570: static PetscErrorCode MatRestoreRow_SeqKAIJ(Mat A, PetscInt row, PetscInt *nz, PetscInt **idx, PetscScalar **v)
1571: {
1572: PetscFunctionBegin;
1573: PetscCall(PetscFree2(*idx, *v));
1574: ((Mat_SeqKAIJ *)A->data)->getrowactive = PETSC_FALSE;
1575: PetscFunctionReturn(PETSC_SUCCESS);
1576: }
1578: static PetscErrorCode MatGetRow_MPIKAIJ(Mat A, PetscInt row, PetscInt *ncols, PetscInt **cols, PetscScalar **values)
1579: {
1580: Mat_MPIKAIJ *b = (Mat_MPIKAIJ *)A->data;
1581: Mat AIJ = b->A;
1582: PetscBool diag = PETSC_FALSE;
1583: Mat MatAIJ, MatOAIJ;
1584: const PetscInt rstart = A->rmap->rstart, rend = A->rmap->rend, p = b->p, q = b->q, *garray;
1585: PetscInt nz, *idx, ncolsaij = 0, ncolsoaij = 0, *colsaij, *colsoaij, r, s, c, i, j, lrow;
1586: PetscScalar *v, *vals, *ovals, *S = b->S, *T = b->T;
1588: PetscFunctionBegin;
1589: PetscCheck(!b->B, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "MATKAIJ: MatGetRow() is not implemented for a KAIJ matrix with a general second operand B");
1590: PetscCall(MatKAIJ_build_AIJ_OAIJ(A)); /* Ensure b->AIJ and b->OAIJ are up to date. */
1591: MatAIJ = ((Mat_SeqKAIJ *)b->AIJ->data)->AIJ;
1592: MatOAIJ = ((Mat_SeqKAIJ *)b->OAIJ->data)->AIJ;
1593: PetscCheck(!b->getrowactive, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Already active");
1594: b->getrowactive = PETSC_TRUE;
1595: PetscCheck(row >= rstart && row < rend, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Only local rows");
1596: lrow = row - rstart;
1598: if ((!S) && (!T) && (!b->isTI)) {
1599: if (ncols) *ncols = 0;
1600: if (cols) *cols = NULL;
1601: if (values) *values = NULL;
1602: PetscFunctionReturn(PETSC_SUCCESS);
1603: }
1605: r = lrow / p;
1606: s = lrow % p;
1608: if (T || b->isTI) {
1609: PetscCall(MatMPIAIJGetSeqAIJ(AIJ, NULL, NULL, &garray));
1610: PetscCall(MatGetRow_SeqAIJ(MatAIJ, lrow / p, &ncolsaij, &colsaij, &vals));
1611: PetscCall(MatGetRow_SeqAIJ(MatOAIJ, lrow / p, &ncolsoaij, &colsoaij, &ovals));
1613: c = ncolsaij + ncolsoaij;
1614: for (i = 0; i < ncolsaij; i++) {
1615: /* check if this row contains a diagonal entry */
1616: if (colsaij[i] == r) {
1617: diag = PETSC_TRUE;
1618: c = i;
1619: }
1620: }
1621: } else c = 0;
1623: /* calculate size of row */
1624: nz = 0;
1625: if (S) nz += q;
1626: if (T || b->isTI) nz += (diag && S ? (ncolsaij + ncolsoaij - 1) * q : (ncolsaij + ncolsoaij) * q);
1628: if (cols || values) {
1629: PetscCall(PetscMalloc2(nz, &idx, nz, &v));
1630: for (i = 0; i < q; i++) {
1631: /* We need to initialize the v[i] to zero to handle the case in which T is NULL (not the identity matrix). */
1632: v[i] = 0.0;
1633: }
1634: if (b->isTI) {
1635: for (i = 0; i < ncolsaij; i++) {
1636: for (j = 0; j < q; j++) {
1637: idx[i * q + j] = (colsaij[i] + rstart / p) * q + j;
1638: v[i * q + j] = (j == s ? vals[i] : 0.0);
1639: }
1640: }
1641: for (i = 0; i < ncolsoaij; i++) {
1642: for (j = 0; j < q; j++) {
1643: idx[(i + ncolsaij) * q + j] = garray[colsoaij[i]] * q + j;
1644: v[(i + ncolsaij) * q + j] = (j == s ? ovals[i] : 0.0);
1645: }
1646: }
1647: } else if (T) {
1648: for (i = 0; i < ncolsaij; i++) {
1649: for (j = 0; j < q; j++) {
1650: idx[i * q + j] = (colsaij[i] + rstart / p) * q + j;
1651: v[i * q + j] = vals[i] * T[s + j * p];
1652: }
1653: }
1654: for (i = 0; i < ncolsoaij; i++) {
1655: for (j = 0; j < q; j++) {
1656: idx[(i + ncolsaij) * q + j] = garray[colsoaij[i]] * q + j;
1657: v[(i + ncolsaij) * q + j] = ovals[i] * T[s + j * p];
1658: }
1659: }
1660: }
1661: if (S) {
1662: for (j = 0; j < q; j++) {
1663: idx[c * q + j] = (r + rstart / p) * q + j;
1664: v[c * q + j] += S[s + j * p];
1665: }
1666: }
1667: }
1669: if (ncols) *ncols = nz;
1670: if (cols) *cols = idx;
1671: if (values) *values = v;
1672: PetscFunctionReturn(PETSC_SUCCESS);
1673: }
1675: static PetscErrorCode MatRestoreRow_MPIKAIJ(Mat A, PetscInt row, PetscInt *nz, PetscInt **idx, PetscScalar **v)
1676: {
1677: PetscFunctionBegin;
1678: PetscCall(PetscFree2(*idx, *v));
1679: ((Mat_SeqKAIJ *)A->data)->getrowactive = PETSC_FALSE;
1680: PetscFunctionReturn(PETSC_SUCCESS);
1681: }
1683: static PetscErrorCode MatCreateSubMatrix_KAIJ(Mat mat, IS isrow, IS iscol, MatReuse cll, Mat *newmat)
1684: {
1685: Mat A;
1687: PetscFunctionBegin;
1688: PetscCall(MatConvert(mat, MATAIJ, MAT_INITIAL_MATRIX, &A));
1689: PetscCall(MatCreateSubMatrix(A, isrow, iscol, cll, newmat));
1690: PetscCall(MatDestroy(&A));
1691: PetscFunctionReturn(PETSC_SUCCESS);
1692: }
1694: /*@
1695: MatCreateKAIJ - Creates a matrix of type `MATKAIJ`.
1697: Collective
1699: Input Parameters:
1700: + A - the `MATAIJ` matrix
1701: . p - number of rows in `S` and `T`
1702: . q - number of columns in `S` and `T`
1703: . S - the `S` matrix (can be `NULL`), stored as a `PetscScalar` array (column-major)
1704: - T - the `T` matrix (can be `NULL`), stored as a `PetscScalar` array (column-major)
1706: Output Parameter:
1707: . kaij - the new `MATKAIJ` matrix
1709: Level: advanced
1711: Notes:
1712: The created matrix is of the following form\:
1713: .vb
1714: [I \otimes S + A \otimes T]
1715: .ve
1716: where
1717: .vb
1718: S is a dense (p \times q) matrix
1719: T is a dense (p \times q) matrix
1720: A is a `MATAIJ` (n \times n) matrix
1721: I is the identity matrix
1722: .ve
1723: The resulting matrix is (np \times nq)
1725: `S` and `T` are always stored independently on all processes as `PetscScalar` arrays in
1726: column-major format.
1728: This function increases the reference count on the `MATAIJ` matrix, so the user is free to destroy the matrix if it is not needed.
1730: Changes to the entries of the `MATAIJ` matrix will immediately affect the `MATKAIJ` matrix, so `MatMult()` and the other operations
1731: always use the current entries. Reassembling an operand does not, however, raise the object state of the `MATKAIJ` matrix itself, and
1732: a `PC` decides whether to rebuild from that state, so follow the reassembly with `MatAssemblyBegin()`/`MatAssemblyEnd()` on the
1733: `MATKAIJ` matrix, exactly as for any other matrix handed to a `KSP`; otherwise the preconditioner is reused unchanged. Assembling the
1734: `MATKAIJ` matrix forwards the operands' nonzero states to it, so a `PC` sees a changed nonzero pattern only when an operand's pattern
1735: actually changed. Changing `S` or `T` with `MatKAIJSetS()`, `MatKAIJSetT()`, or `MatKAIJRestoreS()`/`MatKAIJRestoreT()` raises the
1736: state on its own.
1738: Developer Notes:
1739: In the `MATMPIKAIJ` case, the internal 'AIJ' and 'OAIJ' sequential KAIJ matrices are kept up to date by tracking the object state
1740: of the A matrix that describes the blockwise action of the `MATMPIKAIJ` matrix and, if the object state has changed, lazily
1741: rebuilding 'AIJ' and 'OAIJ' just before executing operations with the `MATMPIKAIJ` matrix. If new types of operations are added,
1742: routines implementing those must also ensure these are rebuilt when needed (by calling the internal MatKAIJ_build_AIJ_OAIJ() routine).
1743: That rebuild is local. It only marks the ghost scatter stale, and the next `MatMult()` checks, and possibly rebuilds, the
1744: scatter collectively.
1746: .seealso: [](ch_matrices), `Mat`, `MatCreateKAIJAB()`, `MatKAIJSetA()`, `MatKAIJSetS()`, `MatKAIJSetT()`, `MatKAIJGetA()`, `MatKAIJGetS()`, `MatKAIJGetT()`, `MATKAIJ`
1747: @*/
1748: PetscErrorCode MatCreateKAIJ(Mat A, PetscInt p, PetscInt q, const PetscScalar S[], const PetscScalar T[], Mat *kaij)
1749: {
1750: PetscFunctionBegin;
1751: PetscCall(MatCreateKAIJAB(A, NULL, p, q, S, T, kaij));
1752: PetscFunctionReturn(PETSC_SUCCESS);
1753: }
1755: /*@
1756: MatCreateKAIJAB - Creates a matrix of type `MATKAIJ` with a general second Kronecker operand.
1758: Collective
1760: Input Parameters:
1761: + A - the `MATAIJ` matrix
1762: . B - the second `MATAIJ` matrix (can be `NULL`, in which case it is treated as the identity, and this is equivalent to `MatCreateKAIJ()`)
1763: . p - number of rows in `S` and `T`
1764: . q - number of columns in `S` and `T`
1765: . S - the `S` matrix (can be `NULL`), stored as a `PetscScalar` array (column-major)
1766: - T - the `T` matrix (can be `NULL`), stored as a `PetscScalar` array (column-major)
1768: Output Parameter:
1769: . kaij - the new `MATKAIJ` matrix
1771: Level: advanced
1773: Notes:
1774: The created matrix is of the following form\:
1775: .vb
1776: [B \otimes S + A \otimes T]
1777: .ve
1778: where
1779: .vb
1780: S is a dense (p \times q) matrix
1781: T is a dense (p \times q) matrix
1782: A is a `MATAIJ` (n \times n) matrix
1783: B is a `MATAIJ` (n \times n) matrix, or the identity if `NULL`
1784: .ve
1785: The resulting matrix is (np \times nq)
1787: A common source of a non-identity `B` is a differential-algebraic equation integrated with an implicit Runge-Kutta
1788: method. In that case the first operand `A` is the Jacobian $\partial F/\partial U$ and the second operand `B` is the
1789: (possibly singular) mass matrix $M = \partial F/\partial \dot{U}$; a `NULL` `B` recovers the identity mass matrix of an
1790: ODE with no algebraic constraints. See `TSIRK` and `TSSetMassMatrix()`.
1792: `B` must share the parallel row and column layout of `A`, and in the `MATMPIKAIJ` case it must share the nonzero
1793: structure of `A` (the same off-diagonal ghost columns), for example by assembling both from the same `DM`. In that
1794: case both operands must be assembled before the `MATKAIJ` matrix is created.
1796: This function increases the reference count on both `MATAIJ` matrices, so the user is free to destroy them if they are not needed.
1798: When `B` is not the identity, `MatMult()`, `MatMultAdd()`, `MatGetDiagonalBlock()`, and `MatInvertBlockDiagonal()`
1799: (hence `PCPBJACOBI`) are supported; the remaining operations raise an error in that case. These are `MatSOR()`,
1800: `MatGetRow()`, `MatConvert()`, and the operations built on `MatConvert()`\: `MatCreateSubMatrix()` and `MatView()` in
1801: any format other than `PETSC_VIEWER_ASCII_INFO`, `PETSC_VIEWER_ASCII_INFO_DETAIL`, or `PETSC_VIEWER_ASCII_IMPL`. In
1802: particular `-mat_view` and `-ksp_view_mat` will error on such a matrix.
1804: .seealso: [](ch_matrices), `Mat`, `MatCreateKAIJ()`, `MatKAIJSetA()`, `MatKAIJSetB()`, `MatKAIJSetS()`, `MatKAIJSetT()`, `MATKAIJ`
1805: @*/
1806: PetscErrorCode MatCreateKAIJAB(Mat A, Mat B, PetscInt p, PetscInt q, const PetscScalar S[], const PetscScalar T[], Mat *kaij)
1807: {
1808: PetscFunctionBegin;
1811: PetscAssertPointer(kaij, 7);
1812: PetscCall(MatCreate(PetscObjectComm((PetscObject)A), kaij));
1813: PetscCall(MatSetType(*kaij, MATKAIJ));
1814: PetscCall(MatKAIJSetA(*kaij, A));
1815: PetscCall(MatKAIJSetB(*kaij, B));
1816: PetscCall(MatKAIJSetS(*kaij, p, q, S));
1817: PetscCall(MatKAIJSetT(*kaij, p, q, T));
1818: PetscCall(MatSetUp(*kaij));
1819: PetscFunctionReturn(PETSC_SUCCESS);
1820: }
1822: /*MC
1823: MATKAIJ - MATKAIJ = "kaij" - A matrix type to be used to evaluate matrices of form
1824: [B \otimes S + A \otimes T],
1825: where
1826: .vb
1827: S is a dense (p \times q) matrix,
1828: T is a dense (p \times q) matrix,
1829: A is an AIJ (n \times n) matrix,
1830: and B is an AIJ (n \times n) matrix, or the identity matrix.
1831: .ve
1832: The resulting matrix is (np \times nq).
1834: S and T are always stored independently on all processes as `PetscScalar` arrays in column-major format.
1836: Level: advanced
1838: Notes:
1839: A linear system with multiple right-hand sides, AX = B, can be expressed in the KAIJ-friendly form of (A \otimes I) x = b,
1840: where x and b are column vectors containing the row-major representations of X and B.
1842: `MatCreateKAIJ()` leaves the second operand as the identity, giving the common (I \otimes S + A \otimes T) form; a general
1843: `B` is set with `MatCreateKAIJAB()` or `MatKAIJSetB()`, which supports fewer operations (see `MatCreateKAIJAB()`).
1845: A general `B` lets a `MATKAIJ` matrix carry a mass matrix, which is how `TSIRK` assembles the stage system of a
1846: differential-algebraic equation; see `MatCreateKAIJAB()` and `TSSetMassMatrix()`.
1848: .seealso: [](ch_matrices), `Mat`, `MatKAIJSetA()`, `MatKAIJSetB()`, `MatKAIJSetS()`, `MatKAIJSetT()`, `MatKAIJGetA()`, `MatKAIJGetB()`, `MatKAIJGetS()`, `MatKAIJGetT()`, `MatCreateKAIJ()`, `MatCreateKAIJAB()`
1849: M*/
1851: PETSC_EXTERN PetscErrorCode MatCreate_KAIJ(Mat A)
1852: {
1853: Mat_MPIKAIJ *b;
1854: PetscMPIInt size;
1856: PetscFunctionBegin;
1857: PetscCall(PetscNew(&b));
1858: A->data = (void *)b;
1860: PetscCall(PetscMemzero(A->ops, sizeof(struct _MatOps)));
1862: b->w = NULL;
1863: PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)A), &size));
1864: if (size == 1) {
1865: PetscCall(PetscObjectChangeTypeName((PetscObject)A, MATSEQKAIJ));
1866: A->ops->destroy = MatDestroy_SeqKAIJ;
1867: A->ops->mult = MatMult_SeqKAIJ;
1868: A->ops->multadd = MatMultAdd_SeqKAIJ;
1869: A->ops->invertblockdiagonal = MatInvertBlockDiagonal_SeqKAIJ;
1870: A->ops->getrow = MatGetRow_SeqKAIJ;
1871: A->ops->restorerow = MatRestoreRow_SeqKAIJ;
1872: A->ops->sor = MatSOR_SeqKAIJ;
1873: PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatConvert_seqkaij_seqaij_C", MatConvert_KAIJ_AIJ));
1874: } else {
1875: PetscCall(PetscObjectChangeTypeName((PetscObject)A, MATMPIKAIJ));
1876: A->ops->destroy = MatDestroy_MPIKAIJ;
1877: A->ops->mult = MatMult_MPIKAIJ;
1878: A->ops->multadd = MatMultAdd_MPIKAIJ;
1879: A->ops->invertblockdiagonal = MatInvertBlockDiagonal_MPIKAIJ;
1880: A->ops->getrow = MatGetRow_MPIKAIJ;
1881: A->ops->restorerow = MatRestoreRow_MPIKAIJ;
1882: A->ops->getdiagonalblock = MatGetDiagonalBlock_MPIKAIJ;
1883: PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatConvert_mpikaij_mpiaij_C", MatConvert_KAIJ_AIJ));
1884: }
1885: A->ops->setup = MatSetUp_KAIJ;
1886: A->ops->view = MatView_KAIJ;
1887: A->ops->assemblyend = MatAssemblyEnd_KAIJ;
1888: A->ops->createsubmatrix = MatCreateSubMatrix_KAIJ;
1889: PetscFunctionReturn(PETSC_SUCCESS);
1890: }