Actual source code: mpiaij.c
1: #include <../src/mat/impls/aij/mpi/mpiaij.h>
2: #include <petsc/private/vecimpl.h>
3: #include <petsc/private/sfimpl.h>
4: #include <petsc/private/isimpl.h>
5: #include <petscblaslapack.h>
6: #include <petscsf.h>
7: #include <petsc/private/hashmapi.h>
9: /* defines MatSetValues_MPI_Hash(), MatAssemblyBegin_MPI_Hash(), and MatAssemblyEnd_MPI_Hash() */
10: #define TYPE AIJ
11: #define TYPE_AIJ
12: #include "../src/mat/impls/aij/mpi/mpihashmat.h"
13: #undef TYPE
14: #undef TYPE_AIJ
16: static PetscErrorCode MatReset_MPIAIJ(Mat mat)
17: {
18: Mat_MPIAIJ *aij = (Mat_MPIAIJ *)mat->data;
20: PetscFunctionBegin;
21: PetscCall(PetscLogObjectState((PetscObject)mat, "Rows=%" PetscInt_FMT ", Cols=%" PetscInt_FMT, mat->rmap->N, mat->cmap->N));
22: PetscCall(MatStashDestroy_Private(&mat->stash));
23: PetscCall(VecDestroy(&aij->diag));
24: PetscCall(MatDestroy(&aij->A));
25: PetscCall(MatDestroy(&aij->B));
26: #if defined(PETSC_USE_CTABLE)
27: PetscCall(PetscHMapIDestroy(&aij->colmap));
28: #else
29: PetscCall(PetscFree(aij->colmap));
30: #endif
31: PetscCall(PetscFree(aij->garray));
32: PetscCall(VecDestroy(&aij->lvec));
33: PetscCall(VecScatterDestroy(&aij->Mvctx));
34: PetscCall(PetscFree2(aij->rowvalues, aij->rowindices));
35: PetscCall(PetscFree(aij->ld));
36: PetscFunctionReturn(PETSC_SUCCESS);
37: }
39: static PetscErrorCode MatResetHash_MPIAIJ(Mat mat)
40: {
41: Mat_MPIAIJ *aij = (Mat_MPIAIJ *)mat->data;
42: /* Save the nonzero states of the component matrices because those are what are used to determine
43: the nonzero state of mat */
44: PetscObjectState Astate = aij->A->nonzerostate, Bstate = aij->B->nonzerostate;
46: PetscFunctionBegin;
47: PetscCall(MatReset_MPIAIJ(mat));
48: PetscCall(MatSetUp_MPI_Hash(mat));
49: aij->A->nonzerostate = ++Astate, aij->B->nonzerostate = ++Bstate;
50: PetscFunctionReturn(PETSC_SUCCESS);
51: }
53: PetscErrorCode MatDestroy_MPIAIJ(Mat mat)
54: {
55: PetscFunctionBegin;
56: PetscCall(MatReset_MPIAIJ(mat));
58: PetscCall(PetscFree(mat->data));
60: /* may be created by MatCreateMPIAIJSumSeqAIJSymbolic */
61: PetscCall(PetscObjectCompose((PetscObject)mat, "MatMergeSeqsToMPI", NULL));
63: PetscCall(PetscObjectChangeTypeName((PetscObject)mat, NULL));
64: PetscCall(PetscObjectComposeFunction((PetscObject)mat, "MatStoreValues_C", NULL));
65: PetscCall(PetscObjectComposeFunction((PetscObject)mat, "MatRetrieveValues_C", NULL));
66: PetscCall(PetscObjectComposeFunction((PetscObject)mat, "MatIsTranspose_C", NULL));
67: PetscCall(PetscObjectComposeFunction((PetscObject)mat, "MatMPIAIJSetPreallocation_C", NULL));
68: PetscCall(PetscObjectComposeFunction((PetscObject)mat, "MatResetPreallocation_C", NULL));
69: PetscCall(PetscObjectComposeFunction((PetscObject)mat, "MatResetHash_C", NULL));
70: PetscCall(PetscObjectComposeFunction((PetscObject)mat, "MatMPIAIJSetPreallocationCSR_C", NULL));
71: PetscCall(PetscObjectComposeFunction((PetscObject)mat, "MatDiagonalScaleLocal_C", NULL));
72: PetscCall(PetscObjectComposeFunction((PetscObject)mat, "MatConvert_mpiaij_mpibaij_C", NULL));
73: PetscCall(PetscObjectComposeFunction((PetscObject)mat, "MatConvert_mpiaij_mpisbaij_C", NULL));
74: #if defined(PETSC_HAVE_CUDA)
75: PetscCall(PetscObjectComposeFunction((PetscObject)mat, "MatConvert_mpiaij_mpiaijcusparse_C", NULL));
76: #endif
77: #if defined(PETSC_HAVE_HIP)
78: PetscCall(PetscObjectComposeFunction((PetscObject)mat, "MatConvert_mpiaij_mpiaijhipsparse_C", NULL));
79: #endif
80: #if defined(PETSC_HAVE_KOKKOS_KERNELS)
81: PetscCall(PetscObjectComposeFunction((PetscObject)mat, "MatConvert_mpiaij_mpiaijkokkos_C", NULL));
82: #endif
83: PetscCall(PetscObjectComposeFunction((PetscObject)mat, "MatConvert_mpiaij_mpidense_C", NULL));
84: #if defined(PETSC_HAVE_ELEMENTAL)
85: PetscCall(PetscObjectComposeFunction((PetscObject)mat, "MatConvert_mpiaij_elemental_C", NULL));
86: #endif
87: #if defined(PETSC_HAVE_SCALAPACK) && (defined(PETSC_USE_REAL_SINGLE) || defined(PETSC_USE_REAL_DOUBLE))
88: PetscCall(PetscObjectComposeFunction((PetscObject)mat, "MatConvert_mpiaij_scalapack_C", NULL));
89: #endif
90: #if defined(PETSC_HAVE_HYPRE)
91: PetscCall(PetscObjectComposeFunction((PetscObject)mat, "MatConvert_mpiaij_hypre_C", NULL));
92: PetscCall(PetscObjectComposeFunction((PetscObject)mat, "MatProductSetFromOptions_transpose_mpiaij_mpiaij_C", NULL));
93: #endif
94: PetscCall(PetscObjectComposeFunction((PetscObject)mat, "MatConvert_mpiaij_is_C", NULL));
95: PetscCall(PetscObjectComposeFunction((PetscObject)mat, "MatProductSetFromOptions_is_mpiaij_C", NULL));
96: PetscCall(PetscObjectComposeFunction((PetscObject)mat, "MatProductSetFromOptions_mpiaij_mpiaij_C", NULL));
97: PetscCall(PetscObjectComposeFunction((PetscObject)mat, "MatMPIAIJSetUseScalableIncreaseOverlap_C", NULL));
98: PetscCall(PetscObjectComposeFunction((PetscObject)mat, "MatConvert_mpiaij_mpiaijperm_C", NULL));
99: PetscCall(PetscObjectComposeFunction((PetscObject)mat, "MatConvert_mpiaij_mpiaijsell_C", NULL));
100: #if defined(PETSC_HAVE_MKL_SPARSE)
101: PetscCall(PetscObjectComposeFunction((PetscObject)mat, "MatConvert_mpiaij_mpiaijmkl_C", NULL));
102: #endif
103: PetscCall(PetscObjectComposeFunction((PetscObject)mat, "MatConvert_mpiaij_mpiaijcrl_C", NULL));
104: PetscCall(PetscObjectComposeFunction((PetscObject)mat, "MatConvert_mpiaij_is_C", NULL));
105: PetscCall(PetscObjectComposeFunction((PetscObject)mat, "MatConvert_mpiaij_mpisell_C", NULL));
106: PetscCall(PetscObjectComposeFunction((PetscObject)mat, "MatSetPreallocationCOO_C", NULL));
107: PetscCall(PetscObjectComposeFunction((PetscObject)mat, "MatSetValuesCOO_C", NULL));
108: PetscFunctionReturn(PETSC_SUCCESS);
109: }
111: static PetscErrorCode MatGetRowIJ_MPIAIJ(Mat A, PetscInt oshift, PetscBool symmetric, PetscBool inodecompressed, PetscInt *m, const PetscInt *ia[], const PetscInt *ja[], PetscBool *done)
112: {
113: Mat B;
115: PetscFunctionBegin;
116: PetscCall(MatMPIAIJGetLocalMat(A, MAT_INITIAL_MATRIX, &B));
117: PetscCall(PetscObjectCompose((PetscObject)A, "MatGetRowIJ_MPIAIJ", (PetscObject)B));
118: PetscCall(MatGetRowIJ(B, oshift, symmetric, inodecompressed, m, ia, ja, done));
119: PetscCall(MatDestroy(&B));
120: PetscFunctionReturn(PETSC_SUCCESS);
121: }
123: static PetscErrorCode MatRestoreRowIJ_MPIAIJ(Mat A, PetscInt oshift, PetscBool symmetric, PetscBool inodecompressed, PetscInt *m, const PetscInt *ia[], const PetscInt *ja[], PetscBool *done)
124: {
125: Mat B;
127: PetscFunctionBegin;
128: PetscCall(PetscObjectQuery((PetscObject)A, "MatGetRowIJ_MPIAIJ", (PetscObject *)&B));
129: PetscCall(MatRestoreRowIJ(B, oshift, symmetric, inodecompressed, m, ia, ja, done));
130: PetscCall(PetscObjectCompose((PetscObject)A, "MatGetRowIJ_MPIAIJ", NULL));
131: PetscFunctionReturn(PETSC_SUCCESS);
132: }
134: /*MC
135: MATAIJ - MATAIJ = "aij" - A matrix type to be used for sparse matrices.
137: This matrix type is identical to` MATSEQAIJ` when constructed with a single process communicator,
138: and `MATMPIAIJ` otherwise. As a result, for single process communicators,
139: `MatSeqAIJSetPreallocation()` is supported, and similarly `MatMPIAIJSetPreallocation()` is supported
140: for communicators controlling multiple processes. It is recommended that you call both of
141: the above preallocation routines for simplicity.
143: Options Database Key:
144: . -mat_type aij - sets the matrix type to `MATAIJ` during a call to `MatSetFromOptions()`
146: Developer Note:
147: Level: beginner
149: Subclasses include `MATAIJCUSPARSE`, `MATAIJPERM`, `MATAIJSELL`, `MATAIJMKL`, `MATAIJCRL`, `MATAIJKOKKOS`,and also automatically switches over to use inodes when
150: enough exist.
152: .seealso: [](ch_matrices), `Mat`, `MATMPIAIJ`, `MATSEQAIJ`, `MatCreateAIJ()`, `MatCreateSeqAIJ()`, `MATBAIJ`
153: M*/
155: /*MC
156: MATAIJCRL - MATAIJCRL = "aijcrl" - A matrix type to be used for sparse matrices.
158: This matrix type is identical to `MATSEQAIJCRL` when constructed with a single process communicator,
159: and `MATMPIAIJCRL` otherwise. As a result, for single process communicators,
160: `MatSeqAIJSetPreallocation()` is supported, and similarly `MatMPIAIJSetPreallocation()` is supported
161: for communicators controlling multiple processes. It is recommended that you call both of
162: the above preallocation routines for simplicity.
164: Options Database Key:
165: . -mat_type aijcrl - sets the matrix type to `MATMPIAIJCRL` during a call to `MatSetFromOptions()`
167: Level: beginner
169: .seealso: [](ch_matrices), `Mat`, `MatCreateMPIAIJCRL`, `MATSEQAIJCRL`, `MATMPIAIJCRL`, `MATSEQAIJ`, `MATMPIAIJ`, `MATAIJ`
170: M*/
172: static PetscErrorCode MatBindToCPU_MPIAIJ(Mat A, PetscBool flg)
173: {
174: Mat_MPIAIJ *a = (Mat_MPIAIJ *)A->data;
176: PetscFunctionBegin;
177: #if defined(PETSC_HAVE_CUDA) || defined(PETSC_HAVE_HIP) || defined(PETSC_HAVE_VIENNACL)
178: A->boundtocpu = flg;
179: #endif
180: if (a->A) PetscCall(MatBindToCPU(a->A, flg));
181: if (a->B) PetscCall(MatBindToCPU(a->B, flg));
183: /* In addition to binding the diagonal and off-diagonal matrices, bind the local vectors used for matrix-vector products.
184: * This maybe seems a little odd for a MatBindToCPU() call to do, but it makes no sense for the binding of these vectors
185: * to differ from the parent matrix. */
186: if (a->lvec) PetscCall(VecBindToCPU(a->lvec, flg));
187: if (a->diag) PetscCall(VecBindToCPU(a->diag, flg));
188: PetscFunctionReturn(PETSC_SUCCESS);
189: }
191: static PetscErrorCode MatSetBlockSizes_MPIAIJ(Mat M, PetscInt rbs, PetscInt cbs)
192: {
193: Mat_MPIAIJ *mat = (Mat_MPIAIJ *)M->data;
195: PetscFunctionBegin;
196: if (mat->A) {
197: PetscCall(MatSetBlockSizes(mat->A, rbs, cbs));
198: PetscCall(MatSetBlockSizes(mat->B, rbs, 1));
199: }
200: PetscFunctionReturn(PETSC_SUCCESS);
201: }
203: static PetscErrorCode MatFindNonzeroRows_MPIAIJ(Mat M, IS *keptrows)
204: {
205: Mat_MPIAIJ *mat = (Mat_MPIAIJ *)M->data;
206: Mat_SeqAIJ *a = (Mat_SeqAIJ *)mat->A->data;
207: Mat_SeqAIJ *b = (Mat_SeqAIJ *)mat->B->data;
208: const PetscInt *ia, *ib;
209: const MatScalar *aa, *bb, *aav, *bav;
210: PetscInt na, nb, i, j, *rows, cnt = 0, n0rows;
211: PetscInt m = M->rmap->n, rstart = M->rmap->rstart;
213: PetscFunctionBegin;
214: *keptrows = NULL;
216: ia = a->i;
217: ib = b->i;
218: PetscCall(MatSeqAIJGetArrayRead(mat->A, &aav));
219: PetscCall(MatSeqAIJGetArrayRead(mat->B, &bav));
220: for (i = 0; i < m; i++) {
221: na = ia[i + 1] - ia[i];
222: nb = ib[i + 1] - ib[i];
223: if (!na && !nb) {
224: cnt++;
225: goto ok1;
226: }
227: aa = aav + ia[i];
228: for (j = 0; j < na; j++) {
229: if (aa[j] != 0.0) goto ok1;
230: }
231: bb = PetscSafePointerPlusOffset(bav, ib[i]);
232: for (j = 0; j < nb; j++) {
233: if (bb[j] != 0.0) goto ok1;
234: }
235: cnt++;
236: ok1:;
237: }
238: PetscCallMPI(MPIU_Allreduce(&cnt, &n0rows, 1, MPIU_INT, MPI_SUM, PetscObjectComm((PetscObject)M)));
239: if (!n0rows) {
240: PetscCall(MatSeqAIJRestoreArrayRead(mat->A, &aav));
241: PetscCall(MatSeqAIJRestoreArrayRead(mat->B, &bav));
242: PetscFunctionReturn(PETSC_SUCCESS);
243: }
244: PetscCall(PetscMalloc1(M->rmap->n - cnt, &rows));
245: cnt = 0;
246: for (i = 0; i < m; i++) {
247: na = ia[i + 1] - ia[i];
248: nb = ib[i + 1] - ib[i];
249: if (!na && !nb) continue;
250: aa = aav + ia[i];
251: for (j = 0; j < na; j++) {
252: if (aa[j] != 0.0) {
253: rows[cnt++] = rstart + i;
254: goto ok2;
255: }
256: }
257: bb = PetscSafePointerPlusOffset(bav, ib[i]);
258: for (j = 0; j < nb; j++) {
259: if (bb[j] != 0.0) {
260: rows[cnt++] = rstart + i;
261: goto ok2;
262: }
263: }
264: ok2:;
265: }
266: PetscCall(ISCreateGeneral(PetscObjectComm((PetscObject)M), cnt, rows, PETSC_OWN_POINTER, keptrows));
267: PetscCall(MatSeqAIJRestoreArrayRead(mat->A, &aav));
268: PetscCall(MatSeqAIJRestoreArrayRead(mat->B, &bav));
269: PetscFunctionReturn(PETSC_SUCCESS);
270: }
272: static PetscErrorCode MatDiagonalSet_MPIAIJ(Mat Y, Vec D, InsertMode is)
273: {
274: Mat_MPIAIJ *aij = (Mat_MPIAIJ *)Y->data;
275: PetscBool cong;
277: PetscFunctionBegin;
278: PetscCall(MatHasCongruentLayouts(Y, &cong));
279: if (Y->assembled && cong) PetscCall(MatDiagonalSet(aij->A, D, is));
280: else PetscCall(MatDiagonalSet_Default(Y, D, is));
281: PetscFunctionReturn(PETSC_SUCCESS);
282: }
284: static PetscErrorCode MatFindZeroDiagonals_MPIAIJ(Mat M, IS *zrows)
285: {
286: Mat_MPIAIJ *aij = (Mat_MPIAIJ *)M->data;
287: PetscInt i, rstart, nrows, *rows;
289: PetscFunctionBegin;
290: *zrows = NULL;
291: PetscCall(MatFindZeroDiagonals_SeqAIJ_Private(aij->A, &nrows, &rows));
292: PetscCall(MatGetOwnershipRange(M, &rstart, NULL));
293: for (i = 0; i < nrows; i++) rows[i] += rstart;
294: PetscCall(ISCreateGeneral(PetscObjectComm((PetscObject)M), nrows, rows, PETSC_OWN_POINTER, zrows));
295: PetscFunctionReturn(PETSC_SUCCESS);
296: }
298: static PetscErrorCode MatGetColumnReductions_MPIAIJ(Mat A, PetscInt type, PetscReal *reductions)
299: {
300: Mat_MPIAIJ *aij = (Mat_MPIAIJ *)A->data;
301: PetscInt i, m, n, *garray = aij->garray;
302: Mat_SeqAIJ *a_aij = (Mat_SeqAIJ *)aij->A->data;
303: Mat_SeqAIJ *b_aij = (Mat_SeqAIJ *)aij->B->data;
304: PetscReal *work;
305: const PetscScalar *dummy;
307: PetscFunctionBegin;
308: PetscCall(MatGetSize(A, &m, &n));
309: PetscCall(PetscCalloc1(n, &work));
310: PetscCall(MatSeqAIJGetArrayRead(aij->A, &dummy));
311: PetscCall(MatSeqAIJRestoreArrayRead(aij->A, &dummy));
312: PetscCall(MatSeqAIJGetArrayRead(aij->B, &dummy));
313: PetscCall(MatSeqAIJRestoreArrayRead(aij->B, &dummy));
314: if (type == NORM_2) {
315: for (i = 0; i < a_aij->i[aij->A->rmap->n]; i++) work[A->cmap->rstart + a_aij->j[i]] += PetscAbsScalar(a_aij->a[i] * a_aij->a[i]);
316: for (i = 0; i < b_aij->i[aij->B->rmap->n]; i++) work[garray[b_aij->j[i]]] += PetscAbsScalar(b_aij->a[i] * b_aij->a[i]);
317: } else if (type == NORM_1) {
318: for (i = 0; i < a_aij->i[aij->A->rmap->n]; i++) work[A->cmap->rstart + a_aij->j[i]] += PetscAbsScalar(a_aij->a[i]);
319: for (i = 0; i < b_aij->i[aij->B->rmap->n]; i++) work[garray[b_aij->j[i]]] += PetscAbsScalar(b_aij->a[i]);
320: } else if (type == NORM_INFINITY) {
321: for (i = 0; i < a_aij->i[aij->A->rmap->n]; i++) work[A->cmap->rstart + a_aij->j[i]] = PetscMax(PetscAbsScalar(a_aij->a[i]), work[A->cmap->rstart + a_aij->j[i]]);
322: for (i = 0; i < b_aij->i[aij->B->rmap->n]; i++) work[garray[b_aij->j[i]]] = PetscMax(PetscAbsScalar(b_aij->a[i]), work[garray[b_aij->j[i]]]);
323: } else if (type == REDUCTION_SUM_REALPART || type == REDUCTION_MEAN_REALPART) {
324: for (i = 0; i < a_aij->i[aij->A->rmap->n]; i++) work[A->cmap->rstart + a_aij->j[i]] += PetscRealPart(a_aij->a[i]);
325: for (i = 0; i < b_aij->i[aij->B->rmap->n]; i++) work[garray[b_aij->j[i]]] += PetscRealPart(b_aij->a[i]);
326: } else if (type == REDUCTION_SUM_IMAGINARYPART || type == REDUCTION_MEAN_IMAGINARYPART) {
327: for (i = 0; i < a_aij->i[aij->A->rmap->n]; i++) work[A->cmap->rstart + a_aij->j[i]] += PetscImaginaryPart(a_aij->a[i]);
328: for (i = 0; i < b_aij->i[aij->B->rmap->n]; i++) work[garray[b_aij->j[i]]] += PetscImaginaryPart(b_aij->a[i]);
329: } else SETERRQ(PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_WRONG, "Unknown reduction type");
330: if (type == NORM_INFINITY) {
331: PetscCallMPI(MPIU_Allreduce(work, reductions, n, MPIU_REAL, MPIU_MAX, PetscObjectComm((PetscObject)A)));
332: } else {
333: PetscCallMPI(MPIU_Allreduce(work, reductions, n, MPIU_REAL, MPIU_SUM, PetscObjectComm((PetscObject)A)));
334: }
335: PetscCall(PetscFree(work));
336: if (type == NORM_2) {
337: for (i = 0; i < n; i++) reductions[i] = PetscSqrtReal(reductions[i]);
338: } else if (type == REDUCTION_MEAN_REALPART || type == REDUCTION_MEAN_IMAGINARYPART) {
339: for (i = 0; i < n; i++) reductions[i] /= m;
340: }
341: PetscFunctionReturn(PETSC_SUCCESS);
342: }
344: static PetscErrorCode MatFindOffBlockDiagonalEntries_MPIAIJ(Mat A, IS *is)
345: {
346: Mat_MPIAIJ *a = (Mat_MPIAIJ *)A->data;
347: IS sis, gis;
348: const PetscInt *isis, *igis;
349: PetscInt n, *iis, nsis, ngis, rstart, i;
351: PetscFunctionBegin;
352: PetscCall(MatFindOffBlockDiagonalEntries(a->A, &sis));
353: PetscCall(MatFindNonzeroRows(a->B, &gis));
354: PetscCall(ISGetSize(gis, &ngis));
355: PetscCall(ISGetSize(sis, &nsis));
356: PetscCall(ISGetIndices(sis, &isis));
357: PetscCall(ISGetIndices(gis, &igis));
359: PetscCall(PetscMalloc1(ngis + nsis, &iis));
360: PetscCall(PetscArraycpy(iis, igis, ngis));
361: PetscCall(PetscArraycpy(iis + ngis, isis, nsis));
362: n = ngis + nsis;
363: PetscCall(PetscSortRemoveDupsInt(&n, iis));
364: PetscCall(MatGetOwnershipRange(A, &rstart, NULL));
365: for (i = 0; i < n; i++) iis[i] += rstart;
366: PetscCall(ISCreateGeneral(PetscObjectComm((PetscObject)A), n, iis, PETSC_OWN_POINTER, is));
368: PetscCall(ISRestoreIndices(sis, &isis));
369: PetscCall(ISRestoreIndices(gis, &igis));
370: PetscCall(ISDestroy(&sis));
371: PetscCall(ISDestroy(&gis));
372: PetscFunctionReturn(PETSC_SUCCESS);
373: }
375: /*
376: Local utility routine that creates a mapping from the global column
377: number to the local number in the off-diagonal part of the local
378: storage of the matrix. When PETSC_USE_CTABLE is used this is scalable at
379: a slightly higher hash table cost; without it it is not scalable (each processor
380: has an order N integer array but is fast to access.
381: */
382: PetscErrorCode MatCreateColmap_MPIAIJ_Private(Mat mat)
383: {
384: Mat_MPIAIJ *aij = (Mat_MPIAIJ *)mat->data;
385: PetscInt n = aij->B->cmap->n, i;
387: PetscFunctionBegin;
388: PetscCheck(!n || aij->garray, PETSC_COMM_SELF, PETSC_ERR_PLIB, "MPIAIJ Matrix was assembled but is missing garray");
389: #if defined(PETSC_USE_CTABLE)
390: PetscCall(PetscHMapICreateWithSize(n, &aij->colmap));
391: for (i = 0; i < n; i++) PetscCall(PetscHMapISet(aij->colmap, aij->garray[i] + 1, i + 1));
392: #else
393: PetscCall(PetscCalloc1(mat->cmap->N + 1, &aij->colmap));
394: for (i = 0; i < n; i++) aij->colmap[aij->garray[i]] = i + 1;
395: #endif
396: PetscFunctionReturn(PETSC_SUCCESS);
397: }
399: #define MatSetValues_SeqAIJ_A_Private(row, col, value, addv, orow, ocol) \
400: do { \
401: if (col <= lastcol1) low1 = 0; \
402: else high1 = nrow1; \
403: lastcol1 = col; \
404: while (high1 - low1 > 5) { \
405: t = (low1 + high1) / 2; \
406: if (rp1[t] > col) high1 = t; \
407: else low1 = t; \
408: } \
409: for (_i = low1; _i < high1; _i++) { \
410: if (rp1[_i] > col) break; \
411: if (rp1[_i] == col) { \
412: if (addv == ADD_VALUES) { \
413: ap1[_i] += value; \
414: /* Not sure LogFlops will slow down the code or not */ \
415: (void)PetscLogFlops(1.0); \
416: } else ap1[_i] = value; \
417: goto a_noinsert; \
418: } \
419: } \
420: if (value == 0.0 && ignorezeroentries && row != col) { \
421: low1 = 0; \
422: high1 = nrow1; \
423: goto a_noinsert; \
424: } \
425: if (nonew == 1) { \
426: low1 = 0; \
427: high1 = nrow1; \
428: goto a_noinsert; \
429: } \
430: PetscCheck(nonew != -1, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Inserting a new nonzero at global row/column (%" PetscInt_FMT ", %" PetscInt_FMT ") into matrix", orow, ocol); \
431: MatSeqXAIJReallocateAIJ(A, am, 1, nrow1, row, col, rmax1, aa, ai, aj, rp1, ap1, aimax, nonew, MatScalar); \
432: N = nrow1++ - 1; \
433: a->nz++; \
434: high1++; \
435: /* shift up all the later entries in this row */ \
436: PetscCall(PetscArraymove(rp1 + _i + 1, rp1 + _i, N - _i + 1)); \
437: PetscCall(PetscArraymove(ap1 + _i + 1, ap1 + _i, N - _i + 1)); \
438: rp1[_i] = col; \
439: ap1[_i] = value; \
440: a_noinsert:; \
441: ailen[row] = nrow1; \
442: } while (0)
444: #define MatSetValues_SeqAIJ_B_Private(row, col, value, addv, orow, ocol) \
445: do { \
446: if (col <= lastcol2) low2 = 0; \
447: else high2 = nrow2; \
448: lastcol2 = col; \
449: while (high2 - low2 > 5) { \
450: t = (low2 + high2) / 2; \
451: if (rp2[t] > col) high2 = t; \
452: else low2 = t; \
453: } \
454: for (_i = low2; _i < high2; _i++) { \
455: if (rp2[_i] > col) break; \
456: if (rp2[_i] == col) { \
457: if (addv == ADD_VALUES) { \
458: ap2[_i] += value; \
459: (void)PetscLogFlops(1.0); \
460: } else ap2[_i] = value; \
461: goto b_noinsert; \
462: } \
463: } \
464: if (value == 0.0 && ignorezeroentries) { \
465: low2 = 0; \
466: high2 = nrow2; \
467: goto b_noinsert; \
468: } \
469: if (nonew == 1) { \
470: low2 = 0; \
471: high2 = nrow2; \
472: goto b_noinsert; \
473: } \
474: PetscCheck(nonew != -1, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Inserting a new nonzero at global row/column (%" PetscInt_FMT ", %" PetscInt_FMT ") into matrix", orow, ocol); \
475: MatSeqXAIJReallocateAIJ(B, bm, 1, nrow2, row, col, rmax2, ba, bi, bj, rp2, ap2, bimax, nonew, MatScalar); \
476: N = nrow2++ - 1; \
477: b->nz++; \
478: high2++; \
479: /* shift up all the later entries in this row */ \
480: PetscCall(PetscArraymove(rp2 + _i + 1, rp2 + _i, N - _i + 1)); \
481: PetscCall(PetscArraymove(ap2 + _i + 1, ap2 + _i, N - _i + 1)); \
482: rp2[_i] = col; \
483: ap2[_i] = value; \
484: b_noinsert:; \
485: bilen[row] = nrow2; \
486: } while (0)
488: static PetscErrorCode MatSetValuesRow_MPIAIJ(Mat A, PetscInt row, const PetscScalar v[])
489: {
490: Mat_MPIAIJ *mat = (Mat_MPIAIJ *)A->data;
491: Mat_SeqAIJ *a = (Mat_SeqAIJ *)mat->A->data, *b = (Mat_SeqAIJ *)mat->B->data;
492: PetscInt l, *garray = mat->garray, diag;
493: PetscScalar *aa, *ba;
495: PetscFunctionBegin;
496: /* code only works for square matrices A */
498: /* find size of row to the left of the diagonal part */
499: PetscCall(MatGetOwnershipRange(A, &diag, NULL));
500: row = row - diag;
501: for (l = 0; l < b->i[row + 1] - b->i[row]; l++) {
502: if (garray[b->j[b->i[row] + l]] > diag) break;
503: }
504: if (l) {
505: PetscCall(MatSeqAIJGetArray(mat->B, &ba));
506: PetscCall(PetscArraycpy(ba + b->i[row], v, l));
507: PetscCall(MatSeqAIJRestoreArray(mat->B, &ba));
508: }
510: /* diagonal part */
511: if (a->i[row + 1] - a->i[row]) {
512: PetscCall(MatSeqAIJGetArray(mat->A, &aa));
513: PetscCall(PetscArraycpy(aa + a->i[row], v + l, a->i[row + 1] - a->i[row]));
514: PetscCall(MatSeqAIJRestoreArray(mat->A, &aa));
515: }
517: /* right of diagonal part */
518: if (b->i[row + 1] - b->i[row] - l) {
519: PetscCall(MatSeqAIJGetArray(mat->B, &ba));
520: PetscCall(PetscArraycpy(ba + b->i[row] + l, v + l + a->i[row + 1] - a->i[row], b->i[row + 1] - b->i[row] - l));
521: PetscCall(MatSeqAIJRestoreArray(mat->B, &ba));
522: }
523: PetscFunctionReturn(PETSC_SUCCESS);
524: }
526: PetscErrorCode MatSetValues_MPIAIJ(Mat mat, PetscInt m, const PetscInt im[], PetscInt n, const PetscInt in[], const PetscScalar v[], InsertMode addv)
527: {
528: Mat_MPIAIJ *aij = (Mat_MPIAIJ *)mat->data;
529: PetscScalar value = 0.0;
530: PetscInt i, j, rstart = mat->rmap->rstart, rend = mat->rmap->rend;
531: PetscInt cstart = mat->cmap->rstart, cend = mat->cmap->rend, row, col;
532: PetscBool roworiented = aij->roworiented;
534: /* Some Variables required in the macro */
535: Mat A = aij->A;
536: Mat_SeqAIJ *a = (Mat_SeqAIJ *)A->data;
537: PetscInt *aimax = a->imax, *ai = a->i, *ailen = a->ilen, *aj = a->j;
538: PetscBool ignorezeroentries = a->ignorezeroentries;
539: Mat B = aij->B;
540: Mat_SeqAIJ *b = (Mat_SeqAIJ *)B->data;
541: PetscInt *bimax = b->imax, *bi = b->i, *bilen = b->ilen, *bj = b->j, bm = aij->B->rmap->n, am = aij->A->rmap->n;
542: MatScalar *aa, *ba;
543: PetscInt *rp1, *rp2, ii, nrow1, nrow2, _i, rmax1, rmax2, N, low1, high1, low2, high2, t, lastcol1, lastcol2;
544: PetscInt nonew;
545: MatScalar *ap1, *ap2;
547: PetscFunctionBegin;
548: PetscCall(MatSeqAIJGetArray(A, &aa));
549: PetscCall(MatSeqAIJGetArray(B, &ba));
550: for (i = 0; i < m; i++) {
551: if (im[i] < 0) continue;
552: PetscCheck(im[i] < mat->rmap->N, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Row too large: row %" PetscInt_FMT " max %" PetscInt_FMT, im[i], mat->rmap->N - 1);
553: if (im[i] >= rstart && im[i] < rend) {
554: row = im[i] - rstart;
555: lastcol1 = -1;
556: rp1 = PetscSafePointerPlusOffset(aj, ai[row]);
557: ap1 = PetscSafePointerPlusOffset(aa, ai[row]);
558: rmax1 = aimax[row];
559: nrow1 = ailen[row];
560: low1 = 0;
561: high1 = nrow1;
562: lastcol2 = -1;
563: rp2 = PetscSafePointerPlusOffset(bj, bi[row]);
564: ap2 = PetscSafePointerPlusOffset(ba, bi[row]);
565: rmax2 = bimax[row];
566: nrow2 = bilen[row];
567: low2 = 0;
568: high2 = nrow2;
570: for (j = 0; j < n; j++) {
571: if (v) value = roworiented ? v[i * n + j] : v[i + j * m];
572: if (ignorezeroentries && value == 0.0 && (addv == ADD_VALUES) && im[i] != in[j]) continue;
573: if (in[j] >= cstart && in[j] < cend) {
574: col = in[j] - cstart;
575: nonew = a->nonew;
576: MatSetValues_SeqAIJ_A_Private(row, col, value, addv, im[i], in[j]);
577: } else if (in[j] < 0) {
578: continue;
579: } else {
580: PetscCheck(in[j] < mat->cmap->N, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Column too large: col %" PetscInt_FMT " max %" PetscInt_FMT, in[j], mat->cmap->N - 1);
581: if (mat->was_assembled) {
582: if (!aij->colmap) PetscCall(MatCreateColmap_MPIAIJ_Private(mat));
583: #if defined(PETSC_USE_CTABLE)
584: PetscCall(PetscHMapIGetWithDefault(aij->colmap, in[j] + 1, 0, &col)); /* map global col ids to local ones */
585: col--;
586: #else
587: col = aij->colmap[in[j]] - 1;
588: #endif
589: if (col < 0 && !((Mat_SeqAIJ *)aij->B->data)->nonew) { /* col < 0 means in[j] is a new col for B */
590: PetscCall(MatDisAssemble_MPIAIJ(mat, PETSC_FALSE)); /* Change aij->B from reduced/local format to expanded/global format */
591: col = in[j];
592: /* Reinitialize the variables required by MatSetValues_SeqAIJ_B_Private() */
593: B = aij->B;
594: b = (Mat_SeqAIJ *)B->data;
595: bimax = b->imax;
596: bi = b->i;
597: bilen = b->ilen;
598: bj = b->j;
599: ba = b->a;
600: rp2 = PetscSafePointerPlusOffset(bj, bi[row]);
601: ap2 = PetscSafePointerPlusOffset(ba, bi[row]);
602: rmax2 = bimax[row];
603: nrow2 = bilen[row];
604: low2 = 0;
605: high2 = nrow2;
606: bm = aij->B->rmap->n;
607: ba = b->a;
608: } else if (col < 0 && !(ignorezeroentries && value == 0.0)) {
609: PetscCheck(1 == ((Mat_SeqAIJ *)aij->B->data)->nonew, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Inserting a new nonzero at global row/column (%" PetscInt_FMT ", %" PetscInt_FMT ") into matrix", im[i], in[j]);
610: PetscCall(PetscInfo(mat, "Skipping of insertion of new nonzero location in off-diagonal portion of matrix %g(%" PetscInt_FMT ",%" PetscInt_FMT ")\n", (double)PetscRealPart(value), im[i], in[j]));
611: }
612: } else col = in[j];
613: nonew = b->nonew;
614: MatSetValues_SeqAIJ_B_Private(row, col, value, addv, im[i], in[j]);
615: }
616: }
617: } else {
618: PetscCheck(!mat->nooffprocentries, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Setting off process row %" PetscInt_FMT " even though MatSetOption(,MAT_NO_OFF_PROC_ENTRIES,PETSC_TRUE) was set", im[i]);
619: if (!aij->donotstash) {
620: mat->assembled = PETSC_FALSE;
621: if (roworiented) {
622: PetscCall(MatStashValuesRow_Private(&mat->stash, im[i], n, in, PetscSafePointerPlusOffset(v, i * n), (PetscBool)(ignorezeroentries && (addv == ADD_VALUES))));
623: } else {
624: PetscCall(MatStashValuesCol_Private(&mat->stash, im[i], n, in, PetscSafePointerPlusOffset(v, i), m, (PetscBool)(ignorezeroentries && (addv == ADD_VALUES))));
625: }
626: }
627: }
628: }
629: PetscCall(MatSeqAIJRestoreArray(A, &aa)); /* aa, bb might have been free'd due to reallocation above. But we don't access them here */
630: PetscCall(MatSeqAIJRestoreArray(B, &ba));
631: PetscFunctionReturn(PETSC_SUCCESS);
632: }
634: /*
635: This function sets the j and ilen arrays (of the diagonal and off-diagonal part) of an MPIAIJ-matrix.
636: The values in mat_i have to be sorted and the values in mat_j have to be sorted for each row (CSR-like).
637: No off-processor parts off the matrix are allowed here and mat->was_assembled has to be PETSC_FALSE.
638: */
639: PetscErrorCode MatSetValues_MPIAIJ_CopyFromCSRFormat_Symbolic(Mat mat, const PetscInt mat_j[], const PetscInt mat_i[])
640: {
641: Mat_MPIAIJ *aij = (Mat_MPIAIJ *)mat->data;
642: Mat A = aij->A; /* diagonal part of the matrix */
643: Mat B = aij->B; /* off-diagonal part of the matrix */
644: Mat_SeqAIJ *a = (Mat_SeqAIJ *)A->data;
645: Mat_SeqAIJ *b = (Mat_SeqAIJ *)B->data;
646: PetscInt cstart = mat->cmap->rstart, cend = mat->cmap->rend, col;
647: PetscInt *ailen = a->ilen, *aj = a->j;
648: PetscInt *bilen = b->ilen, *bj = b->j;
649: PetscInt am = aij->A->rmap->n, j;
650: PetscInt diag_so_far = 0, dnz;
651: PetscInt offd_so_far = 0, onz;
653: PetscFunctionBegin;
654: /* Iterate over all rows of the matrix */
655: for (j = 0; j < am; j++) {
656: dnz = onz = 0;
657: /* Iterate over all non-zero columns of the current row */
658: for (col = mat_i[j]; col < mat_i[j + 1]; col++) {
659: /* If column is in the diagonal */
660: if (mat_j[col] >= cstart && mat_j[col] < cend) {
661: aj[diag_so_far++] = mat_j[col] - cstart;
662: dnz++;
663: } else { /* off-diagonal entries */
664: bj[offd_so_far++] = mat_j[col];
665: onz++;
666: }
667: }
668: ailen[j] = dnz;
669: bilen[j] = onz;
670: }
671: PetscFunctionReturn(PETSC_SUCCESS);
672: }
674: /*
675: This function sets the local j, a and ilen arrays (of the diagonal and off-diagonal part) of an MPIAIJ-matrix.
676: The values in mat_i have to be sorted and the values in mat_j have to be sorted for each row (CSR-like).
677: No off-processor parts off the matrix are allowed here, they are set at a later point by MatSetValues_MPIAIJ.
678: Also, mat->was_assembled has to be false, otherwise the statement aj[rowstart_diag+dnz_row] = mat_j[col] - cstart;
679: would not be true and the more complex MatSetValues_MPIAIJ has to be used.
680: */
681: PetscErrorCode MatSetValues_MPIAIJ_CopyFromCSRFormat(Mat mat, const PetscInt mat_j[], const PetscInt mat_i[], const PetscScalar mat_a[])
682: {
683: Mat_MPIAIJ *aij = (Mat_MPIAIJ *)mat->data;
684: Mat A = aij->A; /* diagonal part of the matrix */
685: Mat B = aij->B; /* off-diagonal part of the matrix */
686: Mat_SeqAIJ *aijd = (Mat_SeqAIJ *)aij->A->data, *aijo = (Mat_SeqAIJ *)aij->B->data;
687: Mat_SeqAIJ *a = (Mat_SeqAIJ *)A->data;
688: Mat_SeqAIJ *b = (Mat_SeqAIJ *)B->data;
689: PetscInt cstart = mat->cmap->rstart, cend = mat->cmap->rend;
690: PetscInt *ailen = a->ilen, *aj = a->j;
691: PetscInt *bilen = b->ilen, *bj = b->j;
692: PetscInt am = aij->A->rmap->n, j;
693: PetscInt *full_diag_i = aijd->i, *full_offd_i = aijo->i; /* These variables can also include non-local elements, which are set at a later point. */
694: PetscInt col, dnz_row, onz_row, rowstart_diag, rowstart_offd;
695: PetscScalar *aa = a->a, *ba = b->a;
697: PetscFunctionBegin;
698: /* Iterate over all rows of the matrix */
699: for (j = 0; j < am; j++) {
700: dnz_row = onz_row = 0;
701: rowstart_offd = full_offd_i[j];
702: rowstart_diag = full_diag_i[j];
703: /* Iterate over all non-zero columns of the current row */
704: for (col = mat_i[j]; col < mat_i[j + 1]; col++) {
705: /* If column is in the diagonal */
706: if (mat_j[col] >= cstart && mat_j[col] < cend) {
707: aj[rowstart_diag + dnz_row] = mat_j[col] - cstart;
708: aa[rowstart_diag + dnz_row] = mat_a[col];
709: dnz_row++;
710: } else { /* off-diagonal entries */
711: bj[rowstart_offd + onz_row] = mat_j[col];
712: ba[rowstart_offd + onz_row] = mat_a[col];
713: onz_row++;
714: }
715: }
716: ailen[j] = dnz_row;
717: bilen[j] = onz_row;
718: }
719: PetscFunctionReturn(PETSC_SUCCESS);
720: }
722: static PetscErrorCode MatGetValues_MPIAIJ(Mat mat, PetscInt m, const PetscInt idxm[], PetscInt n, const PetscInt idxn[], PetscScalar v[])
723: {
724: Mat_MPIAIJ *aij = (Mat_MPIAIJ *)mat->data;
725: PetscInt i, j, rstart = mat->rmap->rstart, rend = mat->rmap->rend;
726: PetscInt cstart = mat->cmap->rstart, cend = mat->cmap->rend, row, col;
728: PetscFunctionBegin;
729: for (i = 0; i < m; i++) {
730: if (idxm[i] < 0) continue; /* negative row */
731: PetscCheck(idxm[i] < mat->rmap->N, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Row too large: row %" PetscInt_FMT " max %" PetscInt_FMT, idxm[i], mat->rmap->N - 1);
732: PetscCheck(idxm[i] >= rstart && idxm[i] < rend, PETSC_COMM_SELF, PETSC_ERR_SUP, "Only local values currently supported, row requested %" PetscInt_FMT " range [%" PetscInt_FMT " %" PetscInt_FMT ")", idxm[i], rstart, rend);
733: row = idxm[i] - rstart;
734: for (j = 0; j < n; j++) {
735: if (idxn[j] < 0) continue; /* negative column */
736: PetscCheck(idxn[j] < mat->cmap->N, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Column too large: col %" PetscInt_FMT " max %" PetscInt_FMT, idxn[j], mat->cmap->N - 1);
737: if (idxn[j] >= cstart && idxn[j] < cend) {
738: col = idxn[j] - cstart;
739: PetscCall(MatGetValues(aij->A, 1, &row, 1, &col, v + i * n + j));
740: } else {
741: if (!aij->colmap) PetscCall(MatCreateColmap_MPIAIJ_Private(mat));
742: #if defined(PETSC_USE_CTABLE)
743: PetscCall(PetscHMapIGetWithDefault(aij->colmap, idxn[j] + 1, 0, &col));
744: col--;
745: #else
746: col = aij->colmap[idxn[j]] - 1;
747: #endif
748: if ((col < 0) || (aij->garray[col] != idxn[j])) *(v + i * n + j) = 0.0;
749: else PetscCall(MatGetValues(aij->B, 1, &row, 1, &col, v + i * n + j));
750: }
751: }
752: }
753: PetscFunctionReturn(PETSC_SUCCESS);
754: }
756: static PetscErrorCode MatAssemblyBegin_MPIAIJ(Mat mat, MatAssemblyType mode)
757: {
758: Mat_MPIAIJ *aij = (Mat_MPIAIJ *)mat->data;
759: PetscInt nstash, reallocs;
761: PetscFunctionBegin;
762: if (aij->donotstash || mat->nooffprocentries) PetscFunctionReturn(PETSC_SUCCESS);
764: PetscCall(MatStashScatterBegin_Private(mat, &mat->stash, mat->rmap->range));
765: PetscCall(MatStashGetInfo_Private(&mat->stash, &nstash, &reallocs));
766: PetscCall(PetscInfo(mat, "Stash has %" PetscInt_FMT " entries, uses %" PetscInt_FMT " mallocs.\n", nstash, reallocs));
767: PetscFunctionReturn(PETSC_SUCCESS);
768: }
770: PetscErrorCode MatAssemblyEnd_MPIAIJ(Mat mat, MatAssemblyType mode)
771: {
772: Mat_MPIAIJ *aij = (Mat_MPIAIJ *)mat->data;
773: PetscMPIInt n;
774: PetscInt i, j, rstart, ncols, flg;
775: PetscInt *row, *col;
776: PetscBool all_assembled;
777: PetscScalar *val;
779: /* do not use 'b = (Mat_SeqAIJ*)aij->B->data' as B can be reset in disassembly */
781: PetscFunctionBegin;
782: if (!aij->donotstash && !mat->nooffprocentries) {
783: while (1) {
784: PetscCall(MatStashScatterGetMesg_Private(&mat->stash, &n, &row, &col, &val, &flg));
785: if (!flg) break;
787: for (i = 0; i < n;) {
788: /* Now identify the consecutive vals belonging to the same row */
789: for (j = i, rstart = row[j]; j < n; j++) {
790: if (row[j] != rstart) break;
791: }
792: if (j < n) ncols = j - i;
793: else ncols = n - i;
794: /* Now assemble all these values with a single function call */
795: PetscCall(MatSetValues_MPIAIJ(mat, 1, row + i, ncols, col + i, val + i, mat->insertmode));
796: i = j;
797: }
798: }
799: PetscCall(MatStashScatterEnd_Private(&mat->stash));
800: }
801: #if defined(PETSC_HAVE_DEVICE)
802: if (mat->offloadmask == PETSC_OFFLOAD_CPU) aij->A->offloadmask = PETSC_OFFLOAD_CPU;
803: /* We call MatBindToCPU() on aij->A and aij->B here, because if MatBindToCPU_MPIAIJ() is called before assembly, it cannot bind these. */
804: if (mat->boundtocpu) {
805: PetscCall(MatBindToCPU(aij->A, PETSC_TRUE));
806: PetscCall(MatBindToCPU(aij->B, PETSC_TRUE));
807: }
808: #endif
809: PetscCall(MatAssemblyBegin(aij->A, mode));
810: PetscCall(MatAssemblyEnd(aij->A, mode));
812: /* determine if any process has disassembled, if so we must
813: also disassemble ourself, in order that we may reassemble. */
814: /*
815: if nonzero structure of submatrix B cannot change then we know that
816: no process disassembled thus we can skip this stuff
817: */
818: if (!((Mat_SeqAIJ *)aij->B->data)->nonew) {
819: PetscCallMPI(MPIU_Allreduce(&mat->was_assembled, &all_assembled, 1, MPI_C_BOOL, MPI_LAND, PetscObjectComm((PetscObject)mat)));
820: if (mat->was_assembled && !all_assembled) { /* mat on this rank has reduced off-diag B with local col ids, but globally it does not */
821: PetscCall(MatDisAssemble_MPIAIJ(mat, PETSC_FALSE));
822: }
823: }
824: if (!mat->was_assembled && mode == MAT_FINAL_ASSEMBLY) PetscCall(MatSetUpMultiply_MPIAIJ(mat));
825: PetscCall(MatSetOption(aij->B, MAT_USE_INODES, PETSC_FALSE));
826: #if defined(PETSC_HAVE_DEVICE)
827: if (mat->offloadmask == PETSC_OFFLOAD_CPU && aij->B->offloadmask != PETSC_OFFLOAD_UNALLOCATED) aij->B->offloadmask = PETSC_OFFLOAD_CPU;
828: #endif
829: PetscCall(MatAssemblyBegin(aij->B, mode));
830: PetscCall(MatAssemblyEnd(aij->B, mode));
832: PetscCall(PetscFree2(aij->rowvalues, aij->rowindices));
834: aij->rowvalues = NULL;
836: PetscCall(VecDestroy(&aij->diag));
838: /* if no new nonzero locations are allowed in matrix then only set the matrix state the first time through */
839: if ((!mat->was_assembled && mode == MAT_FINAL_ASSEMBLY) || !((Mat_SeqAIJ *)aij->A->data)->nonew) {
840: PetscObjectState state = aij->A->nonzerostate + aij->B->nonzerostate;
841: PetscCallMPI(MPIU_Allreduce(&state, &mat->nonzerostate, 1, MPIU_INT64, MPI_SUM, PetscObjectComm((PetscObject)mat)));
842: }
843: #if defined(PETSC_HAVE_DEVICE)
844: mat->offloadmask = PETSC_OFFLOAD_BOTH;
845: #endif
846: PetscFunctionReturn(PETSC_SUCCESS);
847: }
849: static PetscErrorCode MatZeroEntries_MPIAIJ(Mat A)
850: {
851: Mat_MPIAIJ *l = (Mat_MPIAIJ *)A->data;
853: PetscFunctionBegin;
854: PetscCall(MatZeroEntries(l->A));
855: PetscCall(MatZeroEntries(l->B));
856: PetscFunctionReturn(PETSC_SUCCESS);
857: }
859: static PetscErrorCode MatZeroRows_MPIAIJ(Mat A, PetscInt N, const PetscInt rows[], PetscScalar diag, Vec x, Vec b)
860: {
861: Mat_MPIAIJ *mat = (Mat_MPIAIJ *)A->data;
862: PetscInt *lrows;
863: PetscInt r, len;
864: PetscBool cong;
866: PetscFunctionBegin;
867: /* get locally owned rows */
868: PetscCall(MatZeroRowsMapLocal_Private(A, N, rows, &len, &lrows));
869: PetscCall(MatHasCongruentLayouts(A, &cong));
870: /* fix right-hand side if needed */
871: if (x && b) {
872: const PetscScalar *xx;
873: PetscScalar *bb;
875: PetscCheck(cong, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "Need matching row/col layout");
876: PetscCall(VecGetArrayRead(x, &xx));
877: PetscCall(VecGetArray(b, &bb));
878: for (r = 0; r < len; ++r) bb[lrows[r]] = diag * xx[lrows[r]];
879: PetscCall(VecRestoreArrayRead(x, &xx));
880: PetscCall(VecRestoreArray(b, &bb));
881: }
883: if (diag != 0.0 && cong) {
884: PetscCall(MatZeroRows(mat->A, len, lrows, diag, NULL, NULL));
885: PetscCall(MatZeroRows(mat->B, len, lrows, 0.0, NULL, NULL));
886: } else if (diag != 0.0) { /* non-square or non congruent layouts -> if keepnonzeropattern is false, we allow for new insertion */
887: Mat_SeqAIJ *aijA = (Mat_SeqAIJ *)mat->A->data;
888: Mat_SeqAIJ *aijB = (Mat_SeqAIJ *)mat->B->data;
889: PetscInt nnwA, nnwB;
890: PetscBool nnzA, nnzB;
892: nnwA = aijA->nonew;
893: nnwB = aijB->nonew;
894: nnzA = aijA->keepnonzeropattern;
895: nnzB = aijB->keepnonzeropattern;
896: if (!nnzA) {
897: PetscCall(PetscInfo(mat->A, "Requested to not keep the pattern and add a nonzero diagonal; may encounter reallocations on diagonal block.\n"));
898: aijA->nonew = 0;
899: }
900: if (!nnzB) {
901: PetscCall(PetscInfo(mat->B, "Requested to not keep the pattern and add a nonzero diagonal; may encounter reallocations on off-diagonal block.\n"));
902: aijB->nonew = 0;
903: }
904: /* Must zero here before the next loop */
905: PetscCall(MatZeroRows(mat->A, len, lrows, 0.0, NULL, NULL));
906: PetscCall(MatZeroRows(mat->B, len, lrows, 0.0, NULL, NULL));
907: for (r = 0; r < len; ++r) {
908: const PetscInt row = lrows[r] + A->rmap->rstart;
909: if (row >= A->cmap->N) continue;
910: PetscCall(MatSetValues(A, 1, &row, 1, &row, &diag, INSERT_VALUES));
911: }
912: aijA->nonew = nnwA;
913: aijB->nonew = nnwB;
914: } else {
915: PetscCall(MatZeroRows(mat->A, len, lrows, 0.0, NULL, NULL));
916: PetscCall(MatZeroRows(mat->B, len, lrows, 0.0, NULL, NULL));
917: }
918: PetscCall(PetscFree(lrows));
919: PetscCall(MatAssemblyBegin(A, MAT_FINAL_ASSEMBLY));
920: PetscCall(MatAssemblyEnd(A, MAT_FINAL_ASSEMBLY));
922: /* only change matrix nonzero state if pattern was allowed to be changed */
923: if (!((Mat_SeqAIJ *)mat->A->data)->keepnonzeropattern || !((Mat_SeqAIJ *)mat->A->data)->nonew) {
924: PetscObjectState state = mat->A->nonzerostate + mat->B->nonzerostate;
925: PetscCallMPI(MPIU_Allreduce(&state, &A->nonzerostate, 1, MPIU_INT64, MPI_SUM, PetscObjectComm((PetscObject)A)));
926: }
927: PetscFunctionReturn(PETSC_SUCCESS);
928: }
930: static PetscErrorCode MatZeroRowsColumns_MPIAIJ(Mat A, PetscInt N, const PetscInt rows[], PetscScalar diag, Vec x, Vec b)
931: {
932: Mat_MPIAIJ *l = (Mat_MPIAIJ *)A->data;
933: PetscInt n = A->rmap->n;
934: PetscInt i, j, r, m, len = 0;
935: PetscInt *lrows, *owners = A->rmap->range;
936: PetscMPIInt p = 0;
937: PetscSFNode *rrows;
938: PetscSF sf;
939: const PetscScalar *xx;
940: PetscScalar *bb, *mask, *aij_a;
941: Vec xmask, lmask;
942: Mat_SeqAIJ *aij = (Mat_SeqAIJ *)l->B->data;
943: const PetscInt *aj, *ii, *ridx;
944: PetscScalar *aa;
946: PetscFunctionBegin;
947: /* Create SF where leaves are input rows and roots are owned rows */
948: PetscCall(PetscMalloc1(n, &lrows));
949: for (r = 0; r < n; ++r) lrows[r] = -1;
950: PetscCall(PetscMalloc1(N, &rrows));
951: for (r = 0; r < N; ++r) {
952: const PetscInt idx = rows[r];
953: PetscCheck(idx >= 0 && A->rmap->N > idx, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Row %" PetscInt_FMT " out of range [0,%" PetscInt_FMT ")", idx, A->rmap->N);
954: if (idx < owners[p] || owners[p + 1] <= idx) { /* short-circuit the search if the last p owns this row too */
955: PetscCall(PetscLayoutFindOwner(A->rmap, idx, &p));
956: }
957: rrows[r].rank = p;
958: rrows[r].index = rows[r] - owners[p];
959: }
960: PetscCall(PetscSFCreate(PetscObjectComm((PetscObject)A), &sf));
961: PetscCall(PetscSFSetGraph(sf, n, N, NULL, PETSC_OWN_POINTER, rrows, PETSC_OWN_POINTER));
962: /* Collect flags for rows to be zeroed */
963: PetscCall(PetscSFReduceBegin(sf, MPIU_INT, (PetscInt *)rows, lrows, MPI_LOR));
964: PetscCall(PetscSFReduceEnd(sf, MPIU_INT, (PetscInt *)rows, lrows, MPI_LOR));
965: PetscCall(PetscSFDestroy(&sf));
966: /* Compress and put in row numbers */
967: for (r = 0; r < n; ++r)
968: if (lrows[r] >= 0) lrows[len++] = r;
969: /* zero diagonal part of matrix */
970: PetscCall(MatZeroRowsColumns(l->A, len, lrows, diag, x, b));
971: /* handle off-diagonal part of matrix */
972: PetscCall(MatCreateVecs(A, &xmask, NULL));
973: PetscCall(VecDuplicate(l->lvec, &lmask));
974: PetscCall(VecGetArray(xmask, &bb));
975: for (i = 0; i < len; i++) bb[lrows[i]] = 1;
976: PetscCall(VecRestoreArray(xmask, &bb));
977: PetscCall(VecScatterBegin(l->Mvctx, xmask, lmask, ADD_VALUES, SCATTER_FORWARD));
978: PetscCall(VecScatterEnd(l->Mvctx, xmask, lmask, ADD_VALUES, SCATTER_FORWARD));
979: PetscCall(VecDestroy(&xmask));
980: if (x && b) { /* this code is buggy when the row and column layout don't match */
981: PetscBool cong;
983: PetscCall(MatHasCongruentLayouts(A, &cong));
984: PetscCheck(cong, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "Need matching row/col layout");
985: PetscCall(VecScatterBegin(l->Mvctx, x, l->lvec, INSERT_VALUES, SCATTER_FORWARD));
986: PetscCall(VecScatterEnd(l->Mvctx, x, l->lvec, INSERT_VALUES, SCATTER_FORWARD));
987: PetscCall(VecGetArrayRead(l->lvec, &xx));
988: PetscCall(VecGetArray(b, &bb));
989: }
990: PetscCall(VecGetArray(lmask, &mask));
991: /* remove zeroed rows of off-diagonal matrix */
992: PetscCall(MatSeqAIJGetArray(l->B, &aij_a));
993: ii = aij->i;
994: for (i = 0; i < len; i++) PetscCall(PetscArrayzero(PetscSafePointerPlusOffset(aij_a, ii[lrows[i]]), ii[lrows[i] + 1] - ii[lrows[i]]));
995: /* loop over all elements of off process part of matrix zeroing removed columns*/
996: if (aij->compressedrow.use) {
997: m = aij->compressedrow.nrows;
998: ii = aij->compressedrow.i;
999: ridx = aij->compressedrow.rindex;
1000: for (i = 0; i < m; i++) {
1001: n = ii[i + 1] - ii[i];
1002: aj = aij->j + ii[i];
1003: aa = aij_a + ii[i];
1005: for (j = 0; j < n; j++) {
1006: if (PetscAbsScalar(mask[*aj])) {
1007: if (b) bb[*ridx] -= *aa * xx[*aj];
1008: *aa = 0.0;
1009: }
1010: aa++;
1011: aj++;
1012: }
1013: ridx++;
1014: }
1015: } else { /* do not use compressed row format */
1016: m = l->B->rmap->n;
1017: for (i = 0; i < m; i++) {
1018: n = ii[i + 1] - ii[i];
1019: aj = aij->j + ii[i];
1020: aa = aij_a + ii[i];
1021: for (j = 0; j < n; j++) {
1022: if (PetscAbsScalar(mask[*aj])) {
1023: if (b) bb[i] -= *aa * xx[*aj];
1024: *aa = 0.0;
1025: }
1026: aa++;
1027: aj++;
1028: }
1029: }
1030: }
1031: if (x && b) {
1032: PetscCall(VecRestoreArray(b, &bb));
1033: PetscCall(VecRestoreArrayRead(l->lvec, &xx));
1034: }
1035: PetscCall(MatSeqAIJRestoreArray(l->B, &aij_a));
1036: PetscCall(VecRestoreArray(lmask, &mask));
1037: PetscCall(VecDestroy(&lmask));
1038: PetscCall(PetscFree(lrows));
1040: /* only change matrix nonzero state if pattern was allowed to be changed */
1041: if (!((Mat_SeqAIJ *)l->A->data)->nonew) {
1042: PetscObjectState state = l->A->nonzerostate + l->B->nonzerostate;
1043: PetscCallMPI(MPIU_Allreduce(&state, &A->nonzerostate, 1, MPIU_INT64, MPI_SUM, PetscObjectComm((PetscObject)A)));
1044: }
1045: PetscFunctionReturn(PETSC_SUCCESS);
1046: }
1048: static PetscErrorCode MatMult_MPIAIJ(Mat A, Vec xx, Vec yy)
1049: {
1050: Mat_MPIAIJ *a = (Mat_MPIAIJ *)A->data;
1051: PetscInt nt;
1052: VecScatter Mvctx = a->Mvctx;
1054: PetscFunctionBegin;
1055: PetscCall(VecGetLocalSize(xx, &nt));
1056: PetscCheck(nt == A->cmap->n, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Incompatible partition of A (%" PetscInt_FMT ") and xx (%" PetscInt_FMT ")", A->cmap->n, nt);
1057: PetscCall(VecScatterBegin(Mvctx, xx, a->lvec, INSERT_VALUES, SCATTER_FORWARD));
1058: PetscUseTypeMethod(a->A, mult, xx, yy);
1059: PetscCall(VecScatterEnd(Mvctx, xx, a->lvec, INSERT_VALUES, SCATTER_FORWARD));
1060: PetscUseTypeMethod(a->B, multadd, a->lvec, yy, yy);
1061: PetscFunctionReturn(PETSC_SUCCESS);
1062: }
1064: static PetscErrorCode MatMultDiagonalBlock_MPIAIJ(Mat A, Vec bb, Vec xx)
1065: {
1066: Mat_MPIAIJ *a = (Mat_MPIAIJ *)A->data;
1068: PetscFunctionBegin;
1069: PetscCall(MatMultDiagonalBlock(a->A, bb, xx));
1070: PetscFunctionReturn(PETSC_SUCCESS);
1071: }
1073: static PetscErrorCode MatMultAdd_MPIAIJ(Mat A, Vec xx, Vec yy, Vec zz)
1074: {
1075: Mat_MPIAIJ *a = (Mat_MPIAIJ *)A->data;
1076: VecScatter Mvctx = a->Mvctx;
1078: PetscFunctionBegin;
1079: PetscCall(VecScatterBegin(Mvctx, xx, a->lvec, INSERT_VALUES, SCATTER_FORWARD));
1080: PetscUseTypeMethod(a->A, multadd, xx, yy, zz);
1081: PetscCall(VecScatterEnd(Mvctx, xx, a->lvec, INSERT_VALUES, SCATTER_FORWARD));
1082: PetscUseTypeMethod(a->B, multadd, a->lvec, zz, zz);
1083: PetscFunctionReturn(PETSC_SUCCESS);
1084: }
1086: static PetscErrorCode MatMultTranspose_MPIAIJ(Mat A, Vec xx, Vec yy)
1087: {
1088: Mat_MPIAIJ *a = (Mat_MPIAIJ *)A->data;
1090: PetscFunctionBegin;
1091: /* do nondiagonal part */
1092: PetscUseTypeMethod(a->B, multtranspose, xx, a->lvec);
1093: /* do local part */
1094: PetscUseTypeMethod(a->A, multtranspose, xx, yy);
1095: /* add partial results together */
1096: PetscCall(VecScatterBegin(a->Mvctx, a->lvec, yy, ADD_VALUES, SCATTER_REVERSE));
1097: PetscCall(VecScatterEnd(a->Mvctx, a->lvec, yy, ADD_VALUES, SCATTER_REVERSE));
1098: PetscFunctionReturn(PETSC_SUCCESS);
1099: }
1101: static PetscErrorCode MatIsTranspose_MPIAIJ(Mat Amat, Mat Bmat, PetscReal tol, PetscBool *f)
1102: {
1103: MPI_Comm comm;
1104: Mat_MPIAIJ *Aij = (Mat_MPIAIJ *)Amat->data, *Bij = (Mat_MPIAIJ *)Bmat->data;
1105: Mat Adia = Aij->A, Bdia = Bij->A, Aoff, Boff, *Aoffs, *Boffs;
1106: IS Me, Notme;
1107: PetscInt M, N, first, last, *notme, i;
1108: PetscBool lf;
1109: PetscMPIInt size;
1111: PetscFunctionBegin;
1112: /* Easy test: symmetric diagonal block */
1113: PetscCall(MatIsTranspose(Adia, Bdia, tol, &lf));
1114: PetscCallMPI(MPIU_Allreduce(&lf, f, 1, MPI_C_BOOL, MPI_LAND, PetscObjectComm((PetscObject)Amat)));
1115: if (!*f) PetscFunctionReturn(PETSC_SUCCESS);
1116: PetscCall(PetscObjectGetComm((PetscObject)Amat, &comm));
1117: PetscCallMPI(MPI_Comm_size(comm, &size));
1118: if (size == 1) PetscFunctionReturn(PETSC_SUCCESS);
1120: /* Hard test: off-diagonal block. This takes a MatCreateSubMatrix. */
1121: PetscCall(MatGetSize(Amat, &M, &N));
1122: PetscCall(MatGetOwnershipRange(Amat, &first, &last));
1123: PetscCall(PetscMalloc1(N - last + first, ¬me));
1124: for (i = 0; i < first; i++) notme[i] = i;
1125: for (i = last; i < M; i++) notme[i - last + first] = i;
1126: PetscCall(ISCreateGeneral(MPI_COMM_SELF, N - last + first, notme, PETSC_COPY_VALUES, &Notme));
1127: PetscCall(ISCreateStride(MPI_COMM_SELF, last - first, first, 1, &Me));
1128: PetscCall(MatCreateSubMatrices(Amat, 1, &Me, &Notme, MAT_INITIAL_MATRIX, &Aoffs));
1129: Aoff = Aoffs[0];
1130: PetscCall(MatCreateSubMatrices(Bmat, 1, &Notme, &Me, MAT_INITIAL_MATRIX, &Boffs));
1131: Boff = Boffs[0];
1132: PetscCall(MatIsTranspose(Aoff, Boff, tol, f));
1133: PetscCall(MatDestroyMatrices(1, &Aoffs));
1134: PetscCall(MatDestroyMatrices(1, &Boffs));
1135: PetscCall(ISDestroy(&Me));
1136: PetscCall(ISDestroy(&Notme));
1137: PetscCall(PetscFree(notme));
1138: PetscFunctionReturn(PETSC_SUCCESS);
1139: }
1141: static PetscErrorCode MatMultTransposeAdd_MPIAIJ(Mat A, Vec xx, Vec yy, Vec zz)
1142: {
1143: Mat_MPIAIJ *a = (Mat_MPIAIJ *)A->data;
1145: PetscFunctionBegin;
1146: /* do nondiagonal part */
1147: PetscUseTypeMethod(a->B, multtranspose, xx, a->lvec);
1148: /* do local part */
1149: PetscUseTypeMethod(a->A, multtransposeadd, xx, yy, zz);
1150: /* add partial results together */
1151: PetscCall(VecScatterBegin(a->Mvctx, a->lvec, zz, ADD_VALUES, SCATTER_REVERSE));
1152: PetscCall(VecScatterEnd(a->Mvctx, a->lvec, zz, ADD_VALUES, SCATTER_REVERSE));
1153: PetscFunctionReturn(PETSC_SUCCESS);
1154: }
1156: /*
1157: This only works correctly for square matrices where the subblock A->A is the
1158: diagonal block
1159: */
1160: static PetscErrorCode MatGetDiagonal_MPIAIJ(Mat A, Vec v)
1161: {
1162: Mat_MPIAIJ *a = (Mat_MPIAIJ *)A->data;
1164: PetscFunctionBegin;
1165: PetscCheck(A->rmap->N == A->cmap->N, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "Supports only square matrix where A->A is diag block");
1166: PetscCheck(A->rmap->rstart == A->cmap->rstart && A->rmap->rend == A->cmap->rend, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "row partition must equal col partition");
1167: PetscCall(MatGetDiagonal(a->A, v));
1168: PetscFunctionReturn(PETSC_SUCCESS);
1169: }
1171: static PetscErrorCode MatScale_MPIAIJ(Mat A, PetscScalar aa)
1172: {
1173: Mat_MPIAIJ *a = (Mat_MPIAIJ *)A->data;
1175: PetscFunctionBegin;
1176: PetscCall(MatScale(a->A, aa));
1177: PetscCall(MatScale(a->B, aa));
1178: PetscFunctionReturn(PETSC_SUCCESS);
1179: }
1181: static PetscErrorCode MatView_MPIAIJ_Binary(Mat mat, PetscViewer viewer)
1182: {
1183: Mat_MPIAIJ *aij = (Mat_MPIAIJ *)mat->data;
1184: Mat_SeqAIJ *A = (Mat_SeqAIJ *)aij->A->data;
1185: Mat_SeqAIJ *B = (Mat_SeqAIJ *)aij->B->data;
1186: const PetscInt *garray = aij->garray;
1187: const PetscScalar *aa, *ba;
1188: PetscInt header[4], M, N, m, rs, cs, cnt, i, ja, jb;
1189: PetscInt64 nz, hnz;
1190: PetscInt *rowlens;
1191: PetscInt *colidxs;
1192: PetscScalar *matvals;
1193: PetscMPIInt rank;
1195: PetscFunctionBegin;
1196: PetscCall(PetscViewerSetUp(viewer));
1198: M = mat->rmap->N;
1199: N = mat->cmap->N;
1200: m = mat->rmap->n;
1201: rs = mat->rmap->rstart;
1202: cs = mat->cmap->rstart;
1203: nz = A->nz + B->nz;
1205: /* write matrix header */
1206: header[0] = MAT_FILE_CLASSID;
1207: header[1] = M;
1208: header[2] = N;
1209: PetscCallMPI(MPI_Reduce(&nz, &hnz, 1, MPIU_INT64, MPI_SUM, 0, PetscObjectComm((PetscObject)mat)));
1210: PetscCallMPI(MPI_Comm_rank(PetscObjectComm((PetscObject)mat), &rank));
1211: if (rank == 0) PetscCall(PetscIntCast(hnz, &header[3]));
1212: PetscCall(PetscViewerBinaryWrite(viewer, header, 4, PETSC_INT));
1214: /* fill in and store row lengths */
1215: PetscCall(PetscMalloc1(m, &rowlens));
1216: for (i = 0; i < m; i++) rowlens[i] = A->i[i + 1] - A->i[i] + B->i[i + 1] - B->i[i];
1217: PetscCall(PetscViewerBinaryWriteAll(viewer, rowlens, m, rs, M, PETSC_INT));
1218: PetscCall(PetscFree(rowlens));
1220: /* fill in and store column indices */
1221: PetscCall(PetscMalloc1(nz, &colidxs));
1222: for (cnt = 0, i = 0; i < m; i++) {
1223: for (jb = B->i[i]; jb < B->i[i + 1]; jb++) {
1224: if (garray[B->j[jb]] > cs) break;
1225: colidxs[cnt++] = garray[B->j[jb]];
1226: }
1227: for (ja = A->i[i]; ja < A->i[i + 1]; ja++) colidxs[cnt++] = A->j[ja] + cs;
1228: for (; jb < B->i[i + 1]; jb++) colidxs[cnt++] = garray[B->j[jb]];
1229: }
1230: PetscCheck(cnt == nz, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Internal PETSc error: cnt = %" PetscInt_FMT " nz = %" PetscInt64_FMT, cnt, nz);
1231: PetscCall(PetscViewerBinaryWriteAll(viewer, colidxs, nz, PETSC_DETERMINE, PETSC_DETERMINE, PETSC_INT));
1232: PetscCall(PetscFree(colidxs));
1234: /* fill in and store nonzero values */
1235: PetscCall(MatSeqAIJGetArrayRead(aij->A, &aa));
1236: PetscCall(MatSeqAIJGetArrayRead(aij->B, &ba));
1237: PetscCall(PetscMalloc1(nz, &matvals));
1238: for (cnt = 0, i = 0; i < m; i++) {
1239: for (jb = B->i[i]; jb < B->i[i + 1]; jb++) {
1240: if (garray[B->j[jb]] > cs) break;
1241: matvals[cnt++] = ba[jb];
1242: }
1243: for (ja = A->i[i]; ja < A->i[i + 1]; ja++) matvals[cnt++] = aa[ja];
1244: for (; jb < B->i[i + 1]; jb++) matvals[cnt++] = ba[jb];
1245: }
1246: PetscCall(MatSeqAIJRestoreArrayRead(aij->A, &aa));
1247: PetscCall(MatSeqAIJRestoreArrayRead(aij->B, &ba));
1248: PetscCheck(cnt == nz, PETSC_COMM_SELF, PETSC_ERR_LIB, "Internal PETSc error: cnt = %" PetscInt_FMT " nz = %" PetscInt64_FMT, cnt, nz);
1249: PetscCall(PetscViewerBinaryWriteAll(viewer, matvals, nz, PETSC_DETERMINE, PETSC_DETERMINE, PETSC_SCALAR));
1250: PetscCall(PetscFree(matvals));
1252: /* write block size option to the viewer's .info file */
1253: PetscCall(MatView_Binary_BlockSizes(mat, viewer));
1254: PetscFunctionReturn(PETSC_SUCCESS);
1255: }
1257: #include <petscdraw.h>
1258: static PetscErrorCode MatView_MPIAIJ_ASCIIorDraworSocket(Mat mat, PetscViewer viewer)
1259: {
1260: Mat_MPIAIJ *aij = (Mat_MPIAIJ *)mat->data;
1261: PetscMPIInt rank = aij->rank, size = aij->size;
1262: PetscBool isdraw, isascii, isbinary;
1263: PetscViewer sviewer;
1264: PetscViewerFormat format;
1266: PetscFunctionBegin;
1267: PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERDRAW, &isdraw));
1268: PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERASCII, &isascii));
1269: PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERBINARY, &isbinary));
1270: if (isascii) {
1271: PetscCall(PetscViewerGetFormat(viewer, &format));
1272: if (format == PETSC_VIEWER_LOAD_BALANCE) {
1273: PetscInt i, nmax = 0, nmin = PETSC_INT_MAX, navg = 0, *nz, nzlocal = ((Mat_SeqAIJ *)aij->A->data)->nz + ((Mat_SeqAIJ *)aij->B->data)->nz;
1274: PetscCall(PetscMalloc1(size, &nz));
1275: PetscCallMPI(MPI_Allgather(&nzlocal, 1, MPIU_INT, nz, 1, MPIU_INT, PetscObjectComm((PetscObject)mat)));
1276: for (i = 0; i < size; i++) {
1277: nmax = PetscMax(nmax, nz[i]);
1278: nmin = PetscMin(nmin, nz[i]);
1279: navg += nz[i];
1280: }
1281: PetscCall(PetscFree(nz));
1282: navg = navg / size;
1283: PetscCall(PetscViewerASCIIPrintf(viewer, "Load Balance - Nonzeros: Min %" PetscInt_FMT " avg %" PetscInt_FMT " max %" PetscInt_FMT "\n", nmin, navg, nmax));
1284: PetscFunctionReturn(PETSC_SUCCESS);
1285: }
1286: PetscCall(PetscViewerGetFormat(viewer, &format));
1287: if (format == PETSC_VIEWER_ASCII_INFO_DETAIL) {
1288: MatInfo info;
1289: PetscInt *inodes = NULL;
1291: PetscCallMPI(MPI_Comm_rank(PetscObjectComm((PetscObject)mat), &rank));
1292: PetscCall(MatGetInfo(mat, MAT_LOCAL, &info));
1293: PetscCall(MatInodeGetInodeSizes(aij->A, NULL, &inodes, NULL));
1294: PetscCall(PetscViewerASCIIPushSynchronized(viewer));
1295: if (!inodes) {
1296: PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, "[%d] Local rows %" PetscInt_FMT " nz %" PetscInt_FMT " nz alloced %" PetscInt_FMT " mem %g, not using I-node routines\n", rank, mat->rmap->n, (PetscInt)info.nz_used, (PetscInt)info.nz_allocated,
1297: info.memory));
1298: } else {
1299: PetscCall(
1300: PetscViewerASCIISynchronizedPrintf(viewer, "[%d] Local rows %" PetscInt_FMT " nz %" PetscInt_FMT " nz alloced %" PetscInt_FMT " mem %g, using I-node routines\n", rank, mat->rmap->n, (PetscInt)info.nz_used, (PetscInt)info.nz_allocated, info.memory));
1301: }
1302: PetscCall(MatGetInfo(aij->A, MAT_LOCAL, &info));
1303: PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, "[%d] on-diagonal part: nz %" PetscInt_FMT " \n", rank, (PetscInt)info.nz_used));
1304: PetscCall(MatGetInfo(aij->B, MAT_LOCAL, &info));
1305: PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, "[%d] off-diagonal part: nz %" PetscInt_FMT " \n", rank, (PetscInt)info.nz_used));
1306: PetscCall(PetscViewerFlush(viewer));
1307: PetscCall(PetscViewerASCIIPopSynchronized(viewer));
1308: PetscCall(PetscViewerASCIIPrintf(viewer, "Information on VecScatter used in matrix-vector product: \n"));
1309: PetscCall(VecScatterView(aij->Mvctx, viewer));
1310: PetscFunctionReturn(PETSC_SUCCESS);
1311: } else if (format == PETSC_VIEWER_ASCII_INFO) {
1312: PetscInt inodecount, inodelimit, *inodes;
1313: PetscCall(MatInodeGetInodeSizes(aij->A, &inodecount, &inodes, &inodelimit));
1314: if (inodes) {
1315: PetscCall(PetscViewerASCIIPrintf(viewer, "using I-node (on process 0) routines: found %" PetscInt_FMT " nodes, limit used is %" PetscInt_FMT "\n", inodecount, inodelimit));
1316: } else {
1317: PetscCall(PetscViewerASCIIPrintf(viewer, "not using I-node (on process 0) routines\n"));
1318: }
1319: PetscFunctionReturn(PETSC_SUCCESS);
1320: } else if (format == PETSC_VIEWER_ASCII_FACTOR_INFO) {
1321: PetscFunctionReturn(PETSC_SUCCESS);
1322: }
1323: } else if (isbinary) {
1324: if (size == 1) {
1325: PetscCall(PetscObjectSetName((PetscObject)aij->A, ((PetscObject)mat)->name));
1326: PetscCall(MatView(aij->A, viewer));
1327: } else {
1328: PetscCall(MatView_MPIAIJ_Binary(mat, viewer));
1329: }
1330: PetscFunctionReturn(PETSC_SUCCESS);
1331: } else if (isascii && size == 1) {
1332: PetscCall(PetscObjectSetName((PetscObject)aij->A, ((PetscObject)mat)->name));
1333: PetscCall(MatView(aij->A, viewer));
1334: PetscFunctionReturn(PETSC_SUCCESS);
1335: } else if (isdraw) {
1336: PetscDraw draw;
1337: PetscBool isnull;
1338: PetscCall(PetscViewerDrawGetDraw(viewer, 0, &draw));
1339: PetscCall(PetscDrawIsNull(draw, &isnull));
1340: if (isnull) PetscFunctionReturn(PETSC_SUCCESS);
1341: }
1343: { /* assemble the entire matrix onto first processor */
1344: Mat A = NULL, Av;
1345: IS isrow, iscol;
1347: PetscCall(ISCreateStride(PetscObjectComm((PetscObject)mat), rank == 0 ? mat->rmap->N : 0, 0, 1, &isrow));
1348: PetscCall(ISCreateStride(PetscObjectComm((PetscObject)mat), rank == 0 ? mat->cmap->N : 0, 0, 1, &iscol));
1349: PetscCall(MatCreateSubMatrix(mat, isrow, iscol, MAT_INITIAL_MATRIX, &A));
1350: PetscCall(MatMPIAIJGetSeqAIJ(A, &Av, NULL, NULL));
1351: /* The commented code uses MatCreateSubMatrices instead */
1352: /*
1353: Mat *AA, A = NULL, Av;
1354: IS isrow,iscol;
1356: PetscCall(ISCreateStride(PetscObjectComm((PetscObject)mat),rank == 0 ? mat->rmap->N : 0,0,1,&isrow));
1357: PetscCall(ISCreateStride(PetscObjectComm((PetscObject)mat),rank == 0 ? mat->cmap->N : 0,0,1,&iscol));
1358: PetscCall(MatCreateSubMatrices(mat,1,&isrow,&iscol,MAT_INITIAL_MATRIX,&AA));
1359: if (rank == 0) {
1360: PetscCall(PetscObjectReference((PetscObject)AA[0]));
1361: A = AA[0];
1362: Av = AA[0];
1363: }
1364: PetscCall(MatDestroySubMatrices(1,&AA));
1365: */
1366: PetscCall(ISDestroy(&iscol));
1367: PetscCall(ISDestroy(&isrow));
1368: /*
1369: Everyone has to call to draw the matrix since the graphics waits are
1370: synchronized across all processors that share the PetscDraw object
1371: */
1372: PetscCall(PetscViewerGetSubViewer(viewer, PETSC_COMM_SELF, &sviewer));
1373: if (rank == 0) {
1374: if (((PetscObject)mat)->name) PetscCall(PetscObjectSetName((PetscObject)Av, ((PetscObject)mat)->name));
1375: PetscCall(MatView_SeqAIJ(Av, sviewer));
1376: }
1377: PetscCall(PetscViewerRestoreSubViewer(viewer, PETSC_COMM_SELF, &sviewer));
1378: PetscCall(MatDestroy(&A));
1379: }
1380: PetscFunctionReturn(PETSC_SUCCESS);
1381: }
1383: PetscErrorCode MatView_MPIAIJ(Mat mat, PetscViewer viewer)
1384: {
1385: PetscBool isascii, isdraw, issocket, isbinary;
1387: PetscFunctionBegin;
1388: PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERASCII, &isascii));
1389: PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERDRAW, &isdraw));
1390: PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERBINARY, &isbinary));
1391: PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERSOCKET, &issocket));
1392: if (isascii || isdraw || isbinary || issocket) PetscCall(MatView_MPIAIJ_ASCIIorDraworSocket(mat, viewer));
1393: PetscFunctionReturn(PETSC_SUCCESS);
1394: }
1396: static PetscErrorCode MatSOR_MPIAIJ(Mat matin, Vec bb, PetscReal omega, MatSORType flag, PetscReal fshift, PetscInt its, PetscInt lits, Vec xx)
1397: {
1398: Mat_MPIAIJ *mat = (Mat_MPIAIJ *)matin->data;
1399: Vec bb1 = NULL;
1400: PetscBool hasop;
1402: PetscFunctionBegin;
1403: if (flag == SOR_APPLY_UPPER) {
1404: PetscUseTypeMethod(mat->A, sor, bb, omega, flag, fshift, lits, 1, xx);
1405: PetscFunctionReturn(PETSC_SUCCESS);
1406: }
1408: if (its > 1 || ~flag & SOR_ZERO_INITIAL_GUESS || flag & SOR_EISENSTAT) PetscCall(VecDuplicate(bb, &bb1));
1410: if ((flag & SOR_LOCAL_SYMMETRIC_SWEEP) == SOR_LOCAL_SYMMETRIC_SWEEP) {
1411: if (flag & SOR_ZERO_INITIAL_GUESS) {
1412: PetscUseTypeMethod(mat->A, sor, bb, omega, flag, fshift, lits, 1, xx);
1413: its--;
1414: }
1416: while (its--) {
1417: PetscCall(VecScatterBegin(mat->Mvctx, xx, mat->lvec, INSERT_VALUES, SCATTER_FORWARD));
1418: PetscCall(VecScatterEnd(mat->Mvctx, xx, mat->lvec, INSERT_VALUES, SCATTER_FORWARD));
1420: /* update rhs: bb1 = bb - B*x */
1421: PetscCall(VecScale(mat->lvec, -1.0));
1422: PetscUseTypeMethod(mat->B, multadd, mat->lvec, bb, bb1);
1424: /* local sweep */
1425: PetscUseTypeMethod(mat->A, sor, bb1, omega, SOR_SYMMETRIC_SWEEP, fshift, lits, 1, xx);
1426: }
1427: } else if (flag & SOR_LOCAL_FORWARD_SWEEP) {
1428: if (flag & SOR_ZERO_INITIAL_GUESS) {
1429: PetscUseTypeMethod(mat->A, sor, bb, omega, flag, fshift, lits, 1, xx);
1430: its--;
1431: }
1432: while (its--) {
1433: PetscCall(VecScatterBegin(mat->Mvctx, xx, mat->lvec, INSERT_VALUES, SCATTER_FORWARD));
1434: PetscCall(VecScatterEnd(mat->Mvctx, xx, mat->lvec, INSERT_VALUES, SCATTER_FORWARD));
1436: /* update rhs: bb1 = bb - B*x */
1437: PetscCall(VecScale(mat->lvec, -1.0));
1438: PetscUseTypeMethod(mat->B, multadd, mat->lvec, bb, bb1);
1440: /* local sweep */
1441: PetscUseTypeMethod(mat->A, sor, bb1, omega, SOR_FORWARD_SWEEP, fshift, lits, 1, xx);
1442: }
1443: } else if (flag & SOR_LOCAL_BACKWARD_SWEEP) {
1444: if (flag & SOR_ZERO_INITIAL_GUESS) {
1445: PetscUseTypeMethod(mat->A, sor, bb, omega, flag, fshift, lits, 1, xx);
1446: its--;
1447: }
1448: while (its--) {
1449: PetscCall(VecScatterBegin(mat->Mvctx, xx, mat->lvec, INSERT_VALUES, SCATTER_FORWARD));
1450: PetscCall(VecScatterEnd(mat->Mvctx, xx, mat->lvec, INSERT_VALUES, SCATTER_FORWARD));
1452: /* update rhs: bb1 = bb - B*x */
1453: PetscCall(VecScale(mat->lvec, -1.0));
1454: PetscUseTypeMethod(mat->B, multadd, mat->lvec, bb, bb1);
1456: /* local sweep */
1457: PetscUseTypeMethod(mat->A, sor, bb1, omega, SOR_BACKWARD_SWEEP, fshift, lits, 1, xx);
1458: }
1459: } else if (flag & SOR_EISENSTAT) {
1460: Vec xx1;
1462: PetscCall(VecDuplicate(bb, &xx1));
1463: PetscUseTypeMethod(mat->A, sor, bb, omega, (MatSORType)(SOR_ZERO_INITIAL_GUESS | SOR_LOCAL_BACKWARD_SWEEP), fshift, lits, 1, xx);
1465: PetscCall(VecScatterBegin(mat->Mvctx, xx, mat->lvec, INSERT_VALUES, SCATTER_FORWARD));
1466: PetscCall(VecScatterEnd(mat->Mvctx, xx, mat->lvec, INSERT_VALUES, SCATTER_FORWARD));
1467: if (!mat->diag) {
1468: PetscCall(MatCreateVecs(matin, &mat->diag, NULL));
1469: PetscCall(MatGetDiagonal(matin, mat->diag));
1470: }
1471: PetscCall(MatHasOperation(matin, MATOP_MULT_DIAGONAL_BLOCK, &hasop));
1472: if (hasop) PetscCall(MatMultDiagonalBlock(matin, xx, bb1));
1473: else PetscCall(VecPointwiseMult(bb1, mat->diag, xx));
1474: PetscCall(VecAYPX(bb1, (omega - 2.0) / omega, bb));
1476: PetscCall(MatMultAdd(mat->B, mat->lvec, bb1, bb1));
1478: /* local sweep */
1479: PetscUseTypeMethod(mat->A, sor, bb1, omega, (MatSORType)(SOR_ZERO_INITIAL_GUESS | SOR_LOCAL_FORWARD_SWEEP), fshift, lits, 1, xx1);
1480: PetscCall(VecAXPY(xx, 1.0, xx1));
1481: PetscCall(VecDestroy(&xx1));
1482: } else SETERRQ(PetscObjectComm((PetscObject)matin), PETSC_ERR_SUP, "Parallel SOR not supported");
1484: PetscCall(VecDestroy(&bb1));
1486: matin->factorerrortype = mat->A->factorerrortype;
1487: PetscFunctionReturn(PETSC_SUCCESS);
1488: }
1490: static PetscErrorCode MatPermute_MPIAIJ(Mat A, IS rowp, IS colp, Mat *B)
1491: {
1492: Mat aA, aB, Aperm;
1493: const PetscInt *rwant, *cwant, *gcols, *ai, *bi, *aj, *bj;
1494: PetscScalar *aa, *ba;
1495: PetscInt i, j, m, n, ng, anz, bnz, *dnnz, *onnz, *tdnnz, *tonnz, *rdest, *cdest, *work, *gcdest;
1496: PetscSF rowsf, sf;
1497: IS parcolp = NULL;
1498: PetscBool done;
1500: PetscFunctionBegin;
1501: PetscCall(MatGetLocalSize(A, &m, &n));
1502: PetscCall(ISGetIndices(rowp, &rwant));
1503: PetscCall(ISGetIndices(colp, &cwant));
1504: PetscCall(PetscMalloc3(PetscMax(m, n), &work, m, &rdest, n, &cdest));
1506: /* Invert row permutation to find out where my rows should go */
1507: PetscCall(PetscSFCreate(PetscObjectComm((PetscObject)A), &rowsf));
1508: PetscCall(PetscSFSetGraphLayout(rowsf, A->rmap, A->rmap->n, NULL, PETSC_OWN_POINTER, rwant));
1509: PetscCall(PetscSFSetFromOptions(rowsf));
1510: for (i = 0; i < m; i++) work[i] = A->rmap->rstart + i;
1511: PetscCall(PetscSFReduceBegin(rowsf, MPIU_INT, work, rdest, MPI_REPLACE));
1512: PetscCall(PetscSFReduceEnd(rowsf, MPIU_INT, work, rdest, MPI_REPLACE));
1514: /* Invert column permutation to find out where my columns should go */
1515: PetscCall(PetscSFCreate(PetscObjectComm((PetscObject)A), &sf));
1516: PetscCall(PetscSFSetGraphLayout(sf, A->cmap, A->cmap->n, NULL, PETSC_OWN_POINTER, cwant));
1517: PetscCall(PetscSFSetFromOptions(sf));
1518: for (i = 0; i < n; i++) work[i] = A->cmap->rstart + i;
1519: PetscCall(PetscSFReduceBegin(sf, MPIU_INT, work, cdest, MPI_REPLACE));
1520: PetscCall(PetscSFReduceEnd(sf, MPIU_INT, work, cdest, MPI_REPLACE));
1521: PetscCall(PetscSFDestroy(&sf));
1523: PetscCall(ISRestoreIndices(rowp, &rwant));
1524: PetscCall(ISRestoreIndices(colp, &cwant));
1525: PetscCall(MatMPIAIJGetSeqAIJ(A, &aA, &aB, &gcols));
1527: /* Find out where my gcols should go */
1528: PetscCall(MatGetSize(aB, NULL, &ng));
1529: PetscCall(PetscMalloc1(ng, &gcdest));
1530: PetscCall(PetscSFCreate(PetscObjectComm((PetscObject)A), &sf));
1531: PetscCall(PetscSFSetGraphLayout(sf, A->cmap, ng, NULL, PETSC_OWN_POINTER, gcols));
1532: PetscCall(PetscSFSetFromOptions(sf));
1533: PetscCall(PetscSFBcastBegin(sf, MPIU_INT, cdest, gcdest, MPI_REPLACE));
1534: PetscCall(PetscSFBcastEnd(sf, MPIU_INT, cdest, gcdest, MPI_REPLACE));
1535: PetscCall(PetscSFDestroy(&sf));
1537: PetscCall(PetscCalloc4(m, &dnnz, m, &onnz, m, &tdnnz, m, &tonnz));
1538: PetscCall(MatGetRowIJ(aA, 0, PETSC_FALSE, PETSC_FALSE, &anz, &ai, &aj, &done));
1539: PetscCall(MatGetRowIJ(aB, 0, PETSC_FALSE, PETSC_FALSE, &bnz, &bi, &bj, &done));
1540: for (i = 0; i < m; i++) {
1541: PetscInt row = rdest[i];
1542: PetscMPIInt rowner;
1543: PetscCall(PetscLayoutFindOwner(A->rmap, row, &rowner));
1544: for (j = ai[i]; j < ai[i + 1]; j++) {
1545: PetscInt col = cdest[aj[j]];
1546: PetscMPIInt cowner;
1547: PetscCall(PetscLayoutFindOwner(A->cmap, col, &cowner)); /* Could build an index for the columns to eliminate this search */
1548: if (rowner == cowner) dnnz[i]++;
1549: else onnz[i]++;
1550: }
1551: for (j = bi[i]; j < bi[i + 1]; j++) {
1552: PetscInt col = gcdest[bj[j]];
1553: PetscMPIInt cowner;
1554: PetscCall(PetscLayoutFindOwner(A->cmap, col, &cowner));
1555: if (rowner == cowner) dnnz[i]++;
1556: else onnz[i]++;
1557: }
1558: }
1559: PetscCall(PetscSFBcastBegin(rowsf, MPIU_INT, dnnz, tdnnz, MPI_REPLACE));
1560: PetscCall(PetscSFBcastEnd(rowsf, MPIU_INT, dnnz, tdnnz, MPI_REPLACE));
1561: PetscCall(PetscSFBcastBegin(rowsf, MPIU_INT, onnz, tonnz, MPI_REPLACE));
1562: PetscCall(PetscSFBcastEnd(rowsf, MPIU_INT, onnz, tonnz, MPI_REPLACE));
1563: PetscCall(PetscSFDestroy(&rowsf));
1565: PetscCall(MatCreateAIJ(PetscObjectComm((PetscObject)A), A->rmap->n, A->cmap->n, A->rmap->N, A->cmap->N, 0, tdnnz, 0, tonnz, &Aperm));
1566: PetscCall(MatSeqAIJGetArray(aA, &aa));
1567: PetscCall(MatSeqAIJGetArray(aB, &ba));
1568: for (i = 0; i < m; i++) {
1569: PetscInt *acols = dnnz, *bcols = onnz; /* Repurpose now-unneeded arrays */
1570: PetscInt rowlen;
1571: rowlen = ai[i + 1] - ai[i];
1572: for (PetscInt j0 = j = 0; j < rowlen; j0 = j) { /* rowlen could be larger than number of rows m, so sum in batches */
1573: for (; j < PetscMin(rowlen, j0 + m); j++) acols[j - j0] = cdest[aj[ai[i] + j]];
1574: PetscCall(MatSetValues(Aperm, 1, &rdest[i], j - j0, acols, aa + ai[i] + j0, INSERT_VALUES));
1575: }
1576: rowlen = bi[i + 1] - bi[i];
1577: for (PetscInt j0 = j = 0; j < rowlen; j0 = j) {
1578: for (; j < PetscMin(rowlen, j0 + m); j++) bcols[j - j0] = gcdest[bj[bi[i] + j]];
1579: PetscCall(MatSetValues(Aperm, 1, &rdest[i], j - j0, bcols, ba + bi[i] + j0, INSERT_VALUES));
1580: }
1581: }
1582: PetscCall(MatAssemblyBegin(Aperm, MAT_FINAL_ASSEMBLY));
1583: PetscCall(MatAssemblyEnd(Aperm, MAT_FINAL_ASSEMBLY));
1584: PetscCall(MatRestoreRowIJ(aA, 0, PETSC_FALSE, PETSC_FALSE, &anz, &ai, &aj, &done));
1585: PetscCall(MatRestoreRowIJ(aB, 0, PETSC_FALSE, PETSC_FALSE, &bnz, &bi, &bj, &done));
1586: PetscCall(MatSeqAIJRestoreArray(aA, &aa));
1587: PetscCall(MatSeqAIJRestoreArray(aB, &ba));
1588: PetscCall(PetscFree4(dnnz, onnz, tdnnz, tonnz));
1589: PetscCall(PetscFree3(work, rdest, cdest));
1590: PetscCall(PetscFree(gcdest));
1591: if (parcolp) PetscCall(ISDestroy(&colp));
1592: *B = Aperm;
1593: PetscFunctionReturn(PETSC_SUCCESS);
1594: }
1596: static PetscErrorCode MatGetGhosts_MPIAIJ(Mat mat, PetscInt *nghosts, const PetscInt *ghosts[])
1597: {
1598: Mat_MPIAIJ *aij = (Mat_MPIAIJ *)mat->data;
1600: PetscFunctionBegin;
1601: PetscCall(MatGetSize(aij->B, NULL, nghosts));
1602: if (ghosts) *ghosts = aij->garray;
1603: PetscFunctionReturn(PETSC_SUCCESS);
1604: }
1606: static PetscErrorCode MatGetInfo_MPIAIJ(Mat matin, MatInfoType flag, MatInfo *info)
1607: {
1608: Mat_MPIAIJ *mat = (Mat_MPIAIJ *)matin->data;
1609: Mat A = mat->A, B = mat->B;
1610: PetscLogDouble isend[5], irecv[5];
1612: PetscFunctionBegin;
1613: info->block_size = 1.0;
1614: PetscCall(MatGetInfo(A, MAT_LOCAL, info));
1616: isend[0] = info->nz_used;
1617: isend[1] = info->nz_allocated;
1618: isend[2] = info->nz_unneeded;
1619: isend[3] = info->memory;
1620: isend[4] = info->mallocs;
1622: PetscCall(MatGetInfo(B, MAT_LOCAL, info));
1624: isend[0] += info->nz_used;
1625: isend[1] += info->nz_allocated;
1626: isend[2] += info->nz_unneeded;
1627: isend[3] += info->memory;
1628: isend[4] += info->mallocs;
1629: if (flag == MAT_LOCAL) {
1630: info->nz_used = isend[0];
1631: info->nz_allocated = isend[1];
1632: info->nz_unneeded = isend[2];
1633: info->memory = isend[3];
1634: info->mallocs = isend[4];
1635: } else if (flag == MAT_GLOBAL_MAX) {
1636: PetscCallMPI(MPIU_Allreduce(isend, irecv, 5, MPIU_PETSCLOGDOUBLE, MPI_MAX, PetscObjectComm((PetscObject)matin)));
1638: info->nz_used = irecv[0];
1639: info->nz_allocated = irecv[1];
1640: info->nz_unneeded = irecv[2];
1641: info->memory = irecv[3];
1642: info->mallocs = irecv[4];
1643: } else if (flag == MAT_GLOBAL_SUM) {
1644: PetscCallMPI(MPIU_Allreduce(isend, irecv, 5, MPIU_PETSCLOGDOUBLE, MPI_SUM, PetscObjectComm((PetscObject)matin)));
1646: info->nz_used = irecv[0];
1647: info->nz_allocated = irecv[1];
1648: info->nz_unneeded = irecv[2];
1649: info->memory = irecv[3];
1650: info->mallocs = irecv[4];
1651: }
1652: info->fill_ratio_given = 0; /* no parallel LU/ILU/Cholesky */
1653: info->fill_ratio_needed = 0;
1654: info->factor_mallocs = 0;
1655: PetscFunctionReturn(PETSC_SUCCESS);
1656: }
1658: PetscErrorCode MatSetOption_MPIAIJ(Mat A, MatOption op, PetscBool flg)
1659: {
1660: Mat_MPIAIJ *a = (Mat_MPIAIJ *)A->data;
1662: PetscFunctionBegin;
1663: switch (op) {
1664: case MAT_NEW_NONZERO_LOCATIONS:
1665: case MAT_NEW_NONZERO_ALLOCATION_ERR:
1666: case MAT_UNUSED_NONZERO_LOCATION_ERR:
1667: case MAT_KEEP_NONZERO_PATTERN:
1668: case MAT_NEW_NONZERO_LOCATION_ERR:
1669: case MAT_USE_INODES:
1670: case MAT_IGNORE_ZERO_ENTRIES:
1671: case MAT_FORM_EXPLICIT_TRANSPOSE:
1672: MatCheckPreallocated(A, 1);
1673: PetscCall(MatSetOption(a->A, op, flg));
1674: PetscCall(MatSetOption(a->B, op, flg));
1675: break;
1676: case MAT_ROW_ORIENTED:
1677: MatCheckPreallocated(A, 1);
1678: a->roworiented = flg;
1680: PetscCall(MatSetOption(a->A, op, flg));
1681: PetscCall(MatSetOption(a->B, op, flg));
1682: break;
1683: case MAT_IGNORE_OFF_PROC_ENTRIES:
1684: a->donotstash = flg;
1685: break;
1686: /* Symmetry flags are handled directly by MatSetOption() and they don't affect preallocation */
1687: case MAT_SPD:
1688: case MAT_SYMMETRIC:
1689: case MAT_STRUCTURALLY_SYMMETRIC:
1690: case MAT_HERMITIAN:
1691: case MAT_SYMMETRY_ETERNAL:
1692: case MAT_STRUCTURAL_SYMMETRY_ETERNAL:
1693: case MAT_SPD_ETERNAL:
1694: /* if the diagonal matrix is square it inherits some of the properties above */
1695: if (a->A && A->rmap->n == A->cmap->n) PetscCall(MatSetOption(a->A, op, flg));
1696: break;
1697: case MAT_SUBMAT_SINGLEIS:
1698: A->submat_singleis = flg;
1699: break;
1700: default:
1701: break;
1702: }
1703: PetscFunctionReturn(PETSC_SUCCESS);
1704: }
1706: PetscErrorCode MatGetRow_MPIAIJ(Mat matin, PetscInt row, PetscInt *nz, PetscInt **idx, PetscScalar **v)
1707: {
1708: Mat_MPIAIJ *mat = (Mat_MPIAIJ *)matin->data;
1709: PetscScalar *vworkA, *vworkB, **pvA, **pvB, *v_p;
1710: PetscInt i, *cworkA, *cworkB, **pcA, **pcB, cstart = matin->cmap->rstart;
1711: PetscInt nztot, nzA, nzB, lrow, rstart = matin->rmap->rstart, rend = matin->rmap->rend;
1712: PetscInt *cmap, *idx_p;
1714: PetscFunctionBegin;
1715: PetscCheck(!mat->getrowactive, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Already active");
1716: mat->getrowactive = PETSC_TRUE;
1718: if (!mat->rowvalues && (idx || v)) {
1719: /*
1720: allocate enough space to hold information from the longest row.
1721: */
1722: Mat_SeqAIJ *Aa = (Mat_SeqAIJ *)mat->A->data, *Ba = (Mat_SeqAIJ *)mat->B->data;
1723: PetscInt max = 1, tmp;
1724: for (i = 0; i < matin->rmap->n; i++) {
1725: tmp = Aa->i[i + 1] - Aa->i[i] + Ba->i[i + 1] - Ba->i[i];
1726: if (max < tmp) max = tmp;
1727: }
1728: PetscCall(PetscMalloc2(max, &mat->rowvalues, max, &mat->rowindices));
1729: }
1731: PetscCheck(row >= rstart && row < rend, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Only local rows");
1732: lrow = row - rstart;
1734: pvA = &vworkA;
1735: pcA = &cworkA;
1736: pvB = &vworkB;
1737: pcB = &cworkB;
1738: if (!v) {
1739: pvA = NULL;
1740: pvB = NULL;
1741: }
1742: if (!idx) {
1743: pcA = NULL;
1744: if (!v) pcB = NULL;
1745: }
1746: PetscUseTypeMethod(mat->A, getrow, lrow, &nzA, pcA, pvA);
1747: PetscUseTypeMethod(mat->B, getrow, lrow, &nzB, pcB, pvB);
1748: nztot = nzA + nzB;
1750: cmap = mat->garray;
1751: if (v || idx) {
1752: if (nztot) {
1753: /* Sort by increasing column numbers, assuming A and B already sorted */
1754: PetscInt imark = -1;
1755: if (v) {
1756: *v = v_p = mat->rowvalues;
1757: for (i = 0; i < nzB; i++) {
1758: if (cmap[cworkB[i]] < cstart) v_p[i] = vworkB[i];
1759: else break;
1760: }
1761: imark = i;
1762: for (i = 0; i < nzA; i++) v_p[imark + i] = vworkA[i];
1763: for (i = imark; i < nzB; i++) v_p[nzA + i] = vworkB[i];
1764: }
1765: if (idx) {
1766: *idx = idx_p = mat->rowindices;
1767: if (imark > -1) {
1768: for (i = 0; i < imark; i++) idx_p[i] = cmap[cworkB[i]];
1769: } else {
1770: for (i = 0; i < nzB; i++) {
1771: if (cmap[cworkB[i]] < cstart) idx_p[i] = cmap[cworkB[i]];
1772: else break;
1773: }
1774: imark = i;
1775: }
1776: for (i = 0; i < nzA; i++) idx_p[imark + i] = cstart + cworkA[i];
1777: for (i = imark; i < nzB; i++) idx_p[nzA + i] = cmap[cworkB[i]];
1778: }
1779: } else {
1780: if (idx) *idx = NULL;
1781: if (v) *v = NULL;
1782: }
1783: }
1784: *nz = nztot;
1785: PetscUseTypeMethod(mat->A, restorerow, lrow, &nzA, pcA, pvA);
1786: PetscUseTypeMethod(mat->B, restorerow, lrow, &nzB, pcB, pvB);
1787: PetscFunctionReturn(PETSC_SUCCESS);
1788: }
1790: PetscErrorCode MatRestoreRow_MPIAIJ(Mat mat, PetscInt row, PetscInt *nz, PetscInt **idx, PetscScalar **v)
1791: {
1792: Mat_MPIAIJ *aij = (Mat_MPIAIJ *)mat->data;
1794: PetscFunctionBegin;
1795: PetscCheck(aij->getrowactive, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "MatGetRow() must be called first");
1796: aij->getrowactive = PETSC_FALSE;
1797: PetscFunctionReturn(PETSC_SUCCESS);
1798: }
1800: static PetscErrorCode MatNorm_MPIAIJ(Mat mat, NormType type, PetscReal *norm)
1801: {
1802: Mat_MPIAIJ *aij = (Mat_MPIAIJ *)mat->data;
1803: Mat_SeqAIJ *amat = (Mat_SeqAIJ *)aij->A->data, *bmat = (Mat_SeqAIJ *)aij->B->data;
1804: PetscInt i, j;
1805: PetscReal sum = 0.0;
1806: const MatScalar *v, *amata, *bmata;
1808: PetscFunctionBegin;
1809: if (aij->size == 1) {
1810: PetscCall(MatNorm(aij->A, type, norm));
1811: } else {
1812: PetscCall(MatSeqAIJGetArrayRead(aij->A, &amata));
1813: PetscCall(MatSeqAIJGetArrayRead(aij->B, &bmata));
1814: if (type == NORM_FROBENIUS) {
1815: v = amata;
1816: for (i = 0; i < amat->nz; i++) {
1817: sum += PetscRealPart(PetscConj(*v) * (*v));
1818: v++;
1819: }
1820: v = bmata;
1821: for (i = 0; i < bmat->nz; i++) {
1822: sum += PetscRealPart(PetscConj(*v) * (*v));
1823: v++;
1824: }
1825: PetscCallMPI(MPIU_Allreduce(&sum, norm, 1, MPIU_REAL, MPIU_SUM, PetscObjectComm((PetscObject)mat)));
1826: *norm = PetscSqrtReal(*norm);
1827: PetscCall(PetscLogFlops(2.0 * amat->nz + 2.0 * bmat->nz));
1828: } else if (type == NORM_1) { /* max column norm */
1829: Vec col, bcol;
1830: PetscScalar *array;
1831: PetscInt *jj, *garray = aij->garray;
1833: PetscCall(MatCreateVecs(mat, &col, NULL));
1834: PetscCall(VecGetArrayWrite(col, &array));
1835: v = amata;
1836: jj = amat->j;
1837: for (j = 0; j < amat->nz; j++) array[*jj++] += PetscAbsScalar(*v++);
1838: PetscCall(VecRestoreArrayWrite(col, &array));
1839: PetscCall(MatCreateVecs(aij->B, &bcol, NULL));
1840: PetscCall(VecGetArrayWrite(bcol, &array));
1841: v = bmata;
1842: jj = bmat->j;
1843: for (j = 0; j < bmat->nz; j++) array[*jj++] += PetscAbsScalar(*v++);
1844: PetscCall(VecSetValues(col, aij->B->cmap->n, garray, array, ADD_VALUES));
1845: PetscCall(VecRestoreArrayWrite(bcol, &array));
1846: PetscCall(VecDestroy(&bcol));
1847: PetscCall(VecAssemblyBegin(col));
1848: PetscCall(VecAssemblyEnd(col));
1849: PetscCall(VecNorm(col, NORM_INFINITY, norm));
1850: PetscCall(VecDestroy(&col));
1851: } else if (type == NORM_INFINITY) { /* max row norm */
1852: PetscReal ntemp = 0.0;
1853: for (j = 0; j < aij->A->rmap->n; j++) {
1854: v = PetscSafePointerPlusOffset(amata, amat->i[j]);
1855: sum = 0.0;
1856: for (i = 0; i < amat->i[j + 1] - amat->i[j]; i++) {
1857: sum += PetscAbsScalar(*v);
1858: v++;
1859: }
1860: v = PetscSafePointerPlusOffset(bmata, bmat->i[j]);
1861: for (i = 0; i < bmat->i[j + 1] - bmat->i[j]; i++) {
1862: sum += PetscAbsScalar(*v);
1863: v++;
1864: }
1865: if (sum > ntemp) ntemp = sum;
1866: }
1867: PetscCallMPI(MPIU_Allreduce(&ntemp, norm, 1, MPIU_REAL, MPIU_MAX, PetscObjectComm((PetscObject)mat)));
1868: PetscCall(PetscLogFlops(PetscMax(amat->nz + bmat->nz - 1, 0)));
1869: } else SETERRQ(PetscObjectComm((PetscObject)mat), PETSC_ERR_SUP, "No support for two norm");
1870: PetscCall(MatSeqAIJRestoreArrayRead(aij->A, &amata));
1871: PetscCall(MatSeqAIJRestoreArrayRead(aij->B, &bmata));
1872: }
1873: PetscFunctionReturn(PETSC_SUCCESS);
1874: }
1876: static PetscErrorCode MatTranspose_MPIAIJ(Mat A, MatReuse reuse, Mat *matout)
1877: {
1878: Mat_MPIAIJ *a = (Mat_MPIAIJ *)A->data, *b;
1879: Mat_SeqAIJ *Aloc = (Mat_SeqAIJ *)a->A->data, *Bloc = (Mat_SeqAIJ *)a->B->data, *sub_B_diag;
1880: PetscInt M = A->rmap->N, N = A->cmap->N, ma, na, mb, nb, row, *cols, *cols_tmp, *B_diag_ilen, i, ncol, A_diag_ncol;
1881: const PetscInt *ai, *aj, *bi, *bj, *B_diag_i;
1882: Mat B, A_diag, *B_diag;
1883: const MatScalar *pbv, *bv;
1885: PetscFunctionBegin;
1886: if (reuse == MAT_REUSE_MATRIX) PetscCall(MatTransposeCheckNonzeroState_Private(A, *matout));
1887: ma = A->rmap->n;
1888: na = A->cmap->n;
1889: mb = a->B->rmap->n;
1890: nb = a->B->cmap->n;
1891: ai = Aloc->i;
1892: aj = Aloc->j;
1893: bi = Bloc->i;
1894: bj = Bloc->j;
1895: if (reuse == MAT_INITIAL_MATRIX || *matout == A) {
1896: PetscInt *d_nnz, *g_nnz, *o_nnz;
1897: PetscSFNode *oloc;
1898: PETSC_UNUSED PetscSF sf;
1900: PetscCall(PetscMalloc4(na, &d_nnz, na, &o_nnz, nb, &g_nnz, nb, &oloc));
1901: /* compute d_nnz for preallocation */
1902: PetscCall(PetscArrayzero(d_nnz, na));
1903: for (i = 0; i < ai[ma]; i++) d_nnz[aj[i]]++;
1904: /* compute local off-diagonal contributions */
1905: PetscCall(PetscArrayzero(g_nnz, nb));
1906: for (i = 0; i < bi[ma]; i++) g_nnz[bj[i]]++;
1907: /* map those to global */
1908: PetscCall(PetscSFCreate(PetscObjectComm((PetscObject)A), &sf));
1909: PetscCall(PetscSFSetGraphLayout(sf, A->cmap, nb, NULL, PETSC_USE_POINTER, a->garray));
1910: PetscCall(PetscSFSetFromOptions(sf));
1911: PetscCall(PetscArrayzero(o_nnz, na));
1912: PetscCall(PetscSFReduceBegin(sf, MPIU_INT, g_nnz, o_nnz, MPI_SUM));
1913: PetscCall(PetscSFReduceEnd(sf, MPIU_INT, g_nnz, o_nnz, MPI_SUM));
1914: PetscCall(PetscSFDestroy(&sf));
1916: PetscCall(MatCreate(PetscObjectComm((PetscObject)A), &B));
1917: PetscCall(MatSetSizes(B, A->cmap->n, A->rmap->n, N, M));
1918: PetscCall(MatSetBlockSizes(B, A->cmap->bs, A->rmap->bs));
1919: PetscCall(MatSetType(B, ((PetscObject)A)->type_name));
1920: PetscCall(MatMPIAIJSetPreallocation(B, 0, d_nnz, 0, o_nnz));
1921: PetscCall(PetscFree4(d_nnz, o_nnz, g_nnz, oloc));
1922: } else {
1923: B = *matout;
1924: PetscCall(MatSetOption(B, MAT_NEW_NONZERO_ALLOCATION_ERR, PETSC_TRUE));
1925: }
1927: b = (Mat_MPIAIJ *)B->data;
1928: A_diag = a->A;
1929: B_diag = &b->A;
1930: sub_B_diag = (Mat_SeqAIJ *)(*B_diag)->data;
1931: A_diag_ncol = A_diag->cmap->N;
1932: B_diag_ilen = sub_B_diag->ilen;
1933: B_diag_i = sub_B_diag->i;
1935: /* Set ilen for diagonal of B */
1936: for (i = 0; i < A_diag_ncol; i++) B_diag_ilen[i] = B_diag_i[i + 1] - B_diag_i[i];
1938: /* Transpose the diagonal part of the matrix. In contrast to the off-diagonal part, this can be done
1939: very quickly (=without using MatSetValues), because all writes are local. */
1940: PetscCall(MatTransposeSetPrecursor(A_diag, *B_diag));
1941: PetscCall(MatTranspose(A_diag, MAT_REUSE_MATRIX, B_diag));
1943: /* copy over the B part */
1944: PetscCall(PetscMalloc1(bi[mb], &cols));
1945: PetscCall(MatSeqAIJGetArrayRead(a->B, &bv));
1946: pbv = bv;
1947: row = A->rmap->rstart;
1948: for (i = 0; i < bi[mb]; i++) cols[i] = a->garray[bj[i]];
1949: cols_tmp = cols;
1950: for (i = 0; i < mb; i++) {
1951: ncol = bi[i + 1] - bi[i];
1952: PetscCall(MatSetValues(B, ncol, cols_tmp, 1, &row, pbv, INSERT_VALUES));
1953: row++;
1954: if (pbv) pbv += ncol;
1955: if (cols_tmp) cols_tmp += ncol;
1956: }
1957: PetscCall(PetscFree(cols));
1958: PetscCall(MatSeqAIJRestoreArrayRead(a->B, &bv));
1960: PetscCall(MatAssemblyBegin(B, MAT_FINAL_ASSEMBLY));
1961: PetscCall(MatAssemblyEnd(B, MAT_FINAL_ASSEMBLY));
1962: if (reuse == MAT_INITIAL_MATRIX || reuse == MAT_REUSE_MATRIX) {
1963: *matout = B;
1964: } else {
1965: PetscCall(MatHeaderMerge(A, &B));
1966: }
1967: PetscFunctionReturn(PETSC_SUCCESS);
1968: }
1970: static PetscErrorCode MatDiagonalScale_MPIAIJ(Mat mat, Vec ll, Vec rr)
1971: {
1972: Mat_MPIAIJ *aij = (Mat_MPIAIJ *)mat->data;
1973: Mat a = aij->A, b = aij->B;
1974: PetscInt s1, s2, s3;
1976: PetscFunctionBegin;
1977: PetscCall(MatGetLocalSize(mat, &s2, &s3));
1978: if (rr) {
1979: PetscCall(VecGetLocalSize(rr, &s1));
1980: PetscCheck(s1 == s3, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "right vector non-conforming local size");
1981: /* Overlap communication with computation. */
1982: PetscCall(VecScatterBegin(aij->Mvctx, rr, aij->lvec, INSERT_VALUES, SCATTER_FORWARD));
1983: }
1984: if (ll) {
1985: PetscCall(VecGetLocalSize(ll, &s1));
1986: PetscCheck(s1 == s2, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "left vector non-conforming local size");
1987: PetscUseTypeMethod(b, diagonalscale, ll, NULL);
1988: }
1989: /* scale the diagonal block */
1990: PetscUseTypeMethod(a, diagonalscale, ll, rr);
1992: if (rr) {
1993: /* Do a scatter end and then right scale the off-diagonal block */
1994: PetscCall(VecScatterEnd(aij->Mvctx, rr, aij->lvec, INSERT_VALUES, SCATTER_FORWARD));
1995: PetscUseTypeMethod(b, diagonalscale, NULL, aij->lvec);
1996: }
1997: PetscFunctionReturn(PETSC_SUCCESS);
1998: }
2000: static PetscErrorCode MatSetUnfactored_MPIAIJ(Mat A)
2001: {
2002: Mat_MPIAIJ *a = (Mat_MPIAIJ *)A->data;
2004: PetscFunctionBegin;
2005: PetscCall(MatSetUnfactored(a->A));
2006: PetscFunctionReturn(PETSC_SUCCESS);
2007: }
2009: static PetscErrorCode MatEqual_MPIAIJ(Mat A, Mat B, PetscBool *flag)
2010: {
2011: Mat_MPIAIJ *matB = (Mat_MPIAIJ *)B->data, *matA = (Mat_MPIAIJ *)A->data;
2012: Mat a, b, c, d;
2013: PetscBool flg;
2015: PetscFunctionBegin;
2016: a = matA->A;
2017: b = matA->B;
2018: c = matB->A;
2019: d = matB->B;
2021: PetscCall(MatEqual(a, c, &flg));
2022: if (flg) PetscCall(MatEqual(b, d, &flg));
2023: PetscCallMPI(MPIU_Allreduce(&flg, flag, 1, MPI_C_BOOL, MPI_LAND, PetscObjectComm((PetscObject)A)));
2024: PetscFunctionReturn(PETSC_SUCCESS);
2025: }
2027: static PetscErrorCode MatCopy_MPIAIJ(Mat A, Mat B, MatStructure str)
2028: {
2029: Mat_MPIAIJ *a = (Mat_MPIAIJ *)A->data;
2030: Mat_MPIAIJ *b = (Mat_MPIAIJ *)B->data;
2032: PetscFunctionBegin;
2033: /* If the two matrices don't have the same copy implementation, they aren't compatible for fast copy. */
2034: if ((str != SAME_NONZERO_PATTERN) || (A->ops->copy != B->ops->copy)) {
2035: /* because of the column compression in the off-processor part of the matrix a->B,
2036: the number of columns in a->B and b->B may be different, hence we cannot call
2037: the MatCopy() directly on the two parts. If need be, we can provide a more
2038: efficient copy than the MatCopy_Basic() by first uncompressing the a->B matrices
2039: then copying the submatrices */
2040: PetscCall(MatCopy_Basic(A, B, str));
2041: } else {
2042: PetscCall(MatCopy(a->A, b->A, str));
2043: PetscCall(MatCopy(a->B, b->B, str));
2044: }
2045: PetscCall(PetscObjectStateIncrease((PetscObject)B));
2046: PetscFunctionReturn(PETSC_SUCCESS);
2047: }
2049: /*
2050: Computes the number of nonzeros per row needed for preallocation when X and Y
2051: have different nonzero structure.
2052: */
2053: PetscErrorCode MatAXPYGetPreallocation_MPIX_private(PetscInt m, const PetscInt *xi, const PetscInt *xj, const PetscInt *xltog, const PetscInt *yi, const PetscInt *yj, const PetscInt *yltog, PetscInt *nnz)
2054: {
2055: PetscInt i, j, k, nzx, nzy;
2057: PetscFunctionBegin;
2058: /* Set the number of nonzeros in the new matrix */
2059: for (i = 0; i < m; i++) {
2060: const PetscInt *xjj = PetscSafePointerPlusOffset(xj, xi[i]), *yjj = PetscSafePointerPlusOffset(yj, yi[i]);
2061: nzx = xi[i + 1] - xi[i];
2062: nzy = yi[i + 1] - yi[i];
2063: nnz[i] = 0;
2064: for (j = 0, k = 0; j < nzx; j++) { /* Point in X */
2065: for (; k < nzy && yltog[yjj[k]] < xltog[xjj[j]]; k++) nnz[i]++; /* Catch up to X */
2066: if (k < nzy && yltog[yjj[k]] == xltog[xjj[j]]) k++; /* Skip duplicate */
2067: nnz[i]++;
2068: }
2069: for (; k < nzy; k++) nnz[i]++;
2070: }
2071: PetscFunctionReturn(PETSC_SUCCESS);
2072: }
2074: /* This is the same as MatAXPYGetPreallocation_SeqAIJ, except that the local-to-global map is provided */
2075: static PetscErrorCode MatAXPYGetPreallocation_MPIAIJ(Mat Y, const PetscInt *yltog, Mat X, const PetscInt *xltog, PetscInt *nnz)
2076: {
2077: PetscInt m = Y->rmap->N;
2078: Mat_SeqAIJ *x = (Mat_SeqAIJ *)X->data;
2079: Mat_SeqAIJ *y = (Mat_SeqAIJ *)Y->data;
2081: PetscFunctionBegin;
2082: PetscCall(MatAXPYGetPreallocation_MPIX_private(m, x->i, x->j, xltog, y->i, y->j, yltog, nnz));
2083: PetscFunctionReturn(PETSC_SUCCESS);
2084: }
2086: static PetscErrorCode MatAXPY_MPIAIJ(Mat Y, PetscScalar a, Mat X, MatStructure str)
2087: {
2088: Mat_MPIAIJ *xx = (Mat_MPIAIJ *)X->data, *yy = (Mat_MPIAIJ *)Y->data;
2090: PetscFunctionBegin;
2091: if (str == SAME_NONZERO_PATTERN) {
2092: PetscCall(MatAXPY(yy->A, a, xx->A, str));
2093: PetscCall(MatAXPY(yy->B, a, xx->B, str));
2094: } else if (str == SUBSET_NONZERO_PATTERN) { /* nonzeros of X is a subset of Y's */
2095: PetscCall(MatAXPY_Basic(Y, a, X, str));
2096: } else {
2097: Mat B;
2098: PetscInt *nnz_d, *nnz_o;
2100: PetscCall(PetscMalloc1(yy->A->rmap->N, &nnz_d));
2101: PetscCall(PetscMalloc1(yy->B->rmap->N, &nnz_o));
2102: PetscCall(MatCreate(PetscObjectComm((PetscObject)Y), &B));
2103: PetscCall(PetscObjectSetName((PetscObject)B, ((PetscObject)Y)->name));
2104: PetscCall(MatSetLayouts(B, Y->rmap, Y->cmap));
2105: PetscCall(MatSetType(B, ((PetscObject)Y)->type_name));
2106: PetscCall(MatAXPYGetPreallocation_SeqAIJ(yy->A, xx->A, nnz_d));
2107: PetscCall(MatAXPYGetPreallocation_MPIAIJ(yy->B, yy->garray, xx->B, xx->garray, nnz_o));
2108: PetscCall(MatMPIAIJSetPreallocation(B, 0, nnz_d, 0, nnz_o));
2109: PetscCall(MatAXPY_BasicWithPreallocation(B, Y, a, X, str));
2110: PetscCall(MatHeaderMerge(Y, &B));
2111: PetscCall(PetscFree(nnz_d));
2112: PetscCall(PetscFree(nnz_o));
2113: }
2114: PetscFunctionReturn(PETSC_SUCCESS);
2115: }
2117: PETSC_INTERN PetscErrorCode MatConjugate_SeqAIJ(Mat);
2119: static PetscErrorCode MatConjugate_MPIAIJ(Mat mat)
2120: {
2121: Mat_MPIAIJ *aij = (Mat_MPIAIJ *)mat->data;
2123: PetscFunctionBegin;
2124: PetscCall(MatConjugate_SeqAIJ(aij->A));
2125: PetscCall(MatConjugate_SeqAIJ(aij->B));
2126: PetscFunctionReturn(PETSC_SUCCESS);
2127: }
2129: static PetscErrorCode MatRealPart_MPIAIJ(Mat A)
2130: {
2131: Mat_MPIAIJ *a = (Mat_MPIAIJ *)A->data;
2133: PetscFunctionBegin;
2134: PetscCall(MatRealPart(a->A));
2135: PetscCall(MatRealPart(a->B));
2136: PetscFunctionReturn(PETSC_SUCCESS);
2137: }
2139: static PetscErrorCode MatImaginaryPart_MPIAIJ(Mat A)
2140: {
2141: Mat_MPIAIJ *a = (Mat_MPIAIJ *)A->data;
2143: PetscFunctionBegin;
2144: PetscCall(MatImaginaryPart(a->A));
2145: PetscCall(MatImaginaryPart(a->B));
2146: PetscFunctionReturn(PETSC_SUCCESS);
2147: }
2149: static PetscErrorCode MatGetRowMaxAbs_MPIAIJ(Mat A, Vec v, PetscInt idx[])
2150: {
2151: Mat_MPIAIJ *a = (Mat_MPIAIJ *)A->data;
2152: PetscInt i, *idxb = NULL, m = A->rmap->n;
2153: PetscScalar *vv;
2154: Vec vB, vA;
2155: const PetscScalar *va, *vb;
2157: PetscFunctionBegin;
2158: PetscCall(MatCreateVecs(a->A, NULL, &vA));
2159: PetscCall(MatGetRowMaxAbs(a->A, vA, idx));
2161: PetscCall(VecGetArrayRead(vA, &va));
2162: if (idx) {
2163: for (i = 0; i < m; i++) {
2164: if (PetscAbsScalar(va[i])) idx[i] += A->cmap->rstart;
2165: }
2166: }
2168: PetscCall(MatCreateVecs(a->B, NULL, &vB));
2169: PetscCall(PetscMalloc1(m, &idxb));
2170: PetscCall(MatGetRowMaxAbs(a->B, vB, idxb));
2172: PetscCall(VecGetArrayWrite(v, &vv));
2173: PetscCall(VecGetArrayRead(vB, &vb));
2174: for (i = 0; i < m; i++) {
2175: if (PetscAbsScalar(va[i]) < PetscAbsScalar(vb[i])) {
2176: vv[i] = vb[i];
2177: if (idx) idx[i] = a->garray[idxb[i]];
2178: } else {
2179: vv[i] = va[i];
2180: if (idx && PetscAbsScalar(va[i]) == PetscAbsScalar(vb[i]) && idxb[i] != -1 && idx[i] > a->garray[idxb[i]]) idx[i] = a->garray[idxb[i]];
2181: }
2182: }
2183: PetscCall(VecRestoreArrayWrite(v, &vv));
2184: PetscCall(VecRestoreArrayRead(vA, &va));
2185: PetscCall(VecRestoreArrayRead(vB, &vb));
2186: PetscCall(PetscFree(idxb));
2187: PetscCall(VecDestroy(&vA));
2188: PetscCall(VecDestroy(&vB));
2189: PetscFunctionReturn(PETSC_SUCCESS);
2190: }
2192: static PetscErrorCode MatGetRowSumAbs_MPIAIJ(Mat A, Vec v)
2193: {
2194: Mat_MPIAIJ *a = (Mat_MPIAIJ *)A->data;
2195: Vec vB, vA;
2197: PetscFunctionBegin;
2198: PetscCall(MatCreateVecs(a->A, NULL, &vA));
2199: PetscCall(MatGetRowSumAbs(a->A, vA));
2200: PetscCall(MatCreateVecs(a->B, NULL, &vB));
2201: PetscCall(MatGetRowSumAbs(a->B, vB));
2202: PetscCall(VecAXPY(vA, 1.0, vB));
2203: PetscCall(VecDestroy(&vB));
2204: PetscCall(VecCopy(vA, v));
2205: PetscCall(VecDestroy(&vA));
2206: PetscFunctionReturn(PETSC_SUCCESS);
2207: }
2209: static PetscErrorCode MatGetRowMinAbs_MPIAIJ(Mat A, Vec v, PetscInt idx[])
2210: {
2211: Mat_MPIAIJ *mat = (Mat_MPIAIJ *)A->data;
2212: PetscInt m = A->rmap->n, n = A->cmap->n;
2213: PetscInt cstart = A->cmap->rstart, cend = A->cmap->rend;
2214: PetscInt *cmap = mat->garray;
2215: PetscInt *diagIdx, *offdiagIdx;
2216: Vec diagV, offdiagV;
2217: PetscScalar *a, *diagA, *offdiagA;
2218: const PetscScalar *ba, *bav;
2219: PetscInt r, j, col, ncols, *bi, *bj;
2220: Mat B = mat->B;
2221: Mat_SeqAIJ *b = (Mat_SeqAIJ *)B->data;
2223: PetscFunctionBegin;
2224: /* When a process holds entire A and other processes have no entry */
2225: if (A->cmap->N == n) {
2226: PetscCall(VecGetArrayWrite(v, &diagA));
2227: PetscCall(VecCreateSeqWithArray(PETSC_COMM_SELF, 1, m, diagA, &diagV));
2228: PetscCall(MatGetRowMinAbs(mat->A, diagV, idx));
2229: PetscCall(VecDestroy(&diagV));
2230: PetscCall(VecRestoreArrayWrite(v, &diagA));
2231: PetscFunctionReturn(PETSC_SUCCESS);
2232: } else if (n == 0) {
2233: if (m) {
2234: PetscCall(VecGetArrayWrite(v, &a));
2235: for (r = 0; r < m; r++) {
2236: a[r] = 0.0;
2237: if (idx) idx[r] = -1;
2238: }
2239: PetscCall(VecRestoreArrayWrite(v, &a));
2240: }
2241: PetscFunctionReturn(PETSC_SUCCESS);
2242: }
2244: PetscCall(PetscMalloc2(m, &diagIdx, m, &offdiagIdx));
2245: PetscCall(VecCreateSeq(PETSC_COMM_SELF, m, &diagV));
2246: PetscCall(VecCreateSeq(PETSC_COMM_SELF, m, &offdiagV));
2247: PetscCall(MatGetRowMinAbs(mat->A, diagV, diagIdx));
2249: /* Get offdiagIdx[] for implicit 0.0 */
2250: PetscCall(MatSeqAIJGetArrayRead(B, &bav));
2251: ba = bav;
2252: bi = b->i;
2253: bj = b->j;
2254: PetscCall(VecGetArrayWrite(offdiagV, &offdiagA));
2255: for (r = 0; r < m; r++) {
2256: ncols = bi[r + 1] - bi[r];
2257: if (ncols == A->cmap->N - n) { /* Brow is dense */
2258: offdiagA[r] = *ba;
2259: offdiagIdx[r] = cmap[0];
2260: } else { /* Brow is sparse so already KNOW maximum is 0.0 or higher */
2261: offdiagA[r] = 0.0;
2263: /* Find first hole in the cmap */
2264: for (j = 0; j < ncols; j++) {
2265: col = cmap[bj[j]]; /* global column number = cmap[B column number] */
2266: if (col > j && j < cstart) {
2267: offdiagIdx[r] = j; /* global column number of first implicit 0.0 */
2268: break;
2269: } else if (col > j + n && j >= cstart) {
2270: offdiagIdx[r] = j + n; /* global column number of first implicit 0.0 */
2271: break;
2272: }
2273: }
2274: if (j == ncols && ncols < A->cmap->N - n) {
2275: /* a hole is outside compressed Bcols */
2276: if (ncols == 0) {
2277: if (cstart) {
2278: offdiagIdx[r] = 0;
2279: } else offdiagIdx[r] = cend;
2280: } else { /* ncols > 0 */
2281: offdiagIdx[r] = cmap[ncols - 1] + 1;
2282: if (offdiagIdx[r] == cstart) offdiagIdx[r] += n;
2283: }
2284: }
2285: }
2287: for (j = 0; j < ncols; j++) {
2288: if (PetscAbsScalar(offdiagA[r]) > PetscAbsScalar(*ba)) {
2289: offdiagA[r] = *ba;
2290: offdiagIdx[r] = cmap[*bj];
2291: }
2292: ba++;
2293: bj++;
2294: }
2295: }
2297: PetscCall(VecGetArrayWrite(v, &a));
2298: PetscCall(VecGetArrayRead(diagV, (const PetscScalar **)&diagA));
2299: for (r = 0; r < m; ++r) {
2300: if (PetscAbsScalar(diagA[r]) < PetscAbsScalar(offdiagA[r])) {
2301: a[r] = diagA[r];
2302: if (idx) idx[r] = cstart + diagIdx[r];
2303: } else if (PetscAbsScalar(diagA[r]) == PetscAbsScalar(offdiagA[r])) {
2304: a[r] = diagA[r];
2305: if (idx) {
2306: if (cstart + diagIdx[r] <= offdiagIdx[r]) {
2307: idx[r] = cstart + diagIdx[r];
2308: } else idx[r] = offdiagIdx[r];
2309: }
2310: } else {
2311: a[r] = offdiagA[r];
2312: if (idx) idx[r] = offdiagIdx[r];
2313: }
2314: }
2315: PetscCall(MatSeqAIJRestoreArrayRead(B, &bav));
2316: PetscCall(VecRestoreArrayWrite(v, &a));
2317: PetscCall(VecRestoreArrayRead(diagV, (const PetscScalar **)&diagA));
2318: PetscCall(VecRestoreArrayWrite(offdiagV, &offdiagA));
2319: PetscCall(VecDestroy(&diagV));
2320: PetscCall(VecDestroy(&offdiagV));
2321: PetscCall(PetscFree2(diagIdx, offdiagIdx));
2322: PetscFunctionReturn(PETSC_SUCCESS);
2323: }
2325: static PetscErrorCode MatGetRowMin_MPIAIJ(Mat A, Vec v, PetscInt idx[])
2326: {
2327: Mat_MPIAIJ *mat = (Mat_MPIAIJ *)A->data;
2328: PetscInt m = A->rmap->n, n = A->cmap->n;
2329: PetscInt cstart = A->cmap->rstart, cend = A->cmap->rend;
2330: PetscInt *cmap = mat->garray;
2331: PetscInt *diagIdx, *offdiagIdx;
2332: Vec diagV, offdiagV;
2333: PetscScalar *a, *diagA, *offdiagA;
2334: const PetscScalar *ba, *bav;
2335: PetscInt r, j, col, ncols, *bi, *bj;
2336: Mat B = mat->B;
2337: Mat_SeqAIJ *b = (Mat_SeqAIJ *)B->data;
2339: PetscFunctionBegin;
2340: /* When a process holds entire A and other processes have no entry */
2341: if (A->cmap->N == n) {
2342: PetscCall(VecGetArrayWrite(v, &diagA));
2343: PetscCall(VecCreateSeqWithArray(PETSC_COMM_SELF, 1, m, diagA, &diagV));
2344: PetscCall(MatGetRowMin(mat->A, diagV, idx));
2345: PetscCall(VecDestroy(&diagV));
2346: PetscCall(VecRestoreArrayWrite(v, &diagA));
2347: PetscFunctionReturn(PETSC_SUCCESS);
2348: } else if (n == 0) {
2349: if (m) {
2350: PetscCall(VecGetArrayWrite(v, &a));
2351: for (r = 0; r < m; r++) {
2352: a[r] = PETSC_MAX_REAL;
2353: if (idx) idx[r] = -1;
2354: }
2355: PetscCall(VecRestoreArrayWrite(v, &a));
2356: }
2357: PetscFunctionReturn(PETSC_SUCCESS);
2358: }
2360: PetscCall(PetscCalloc2(m, &diagIdx, m, &offdiagIdx));
2361: PetscCall(VecCreateSeq(PETSC_COMM_SELF, m, &diagV));
2362: PetscCall(VecCreateSeq(PETSC_COMM_SELF, m, &offdiagV));
2363: PetscCall(MatGetRowMin(mat->A, diagV, diagIdx));
2365: /* Get offdiagIdx[] for implicit 0.0 */
2366: PetscCall(MatSeqAIJGetArrayRead(B, &bav));
2367: ba = bav;
2368: bi = b->i;
2369: bj = b->j;
2370: PetscCall(VecGetArrayWrite(offdiagV, &offdiagA));
2371: for (r = 0; r < m; r++) {
2372: ncols = bi[r + 1] - bi[r];
2373: if (ncols == A->cmap->N - n) { /* Brow is dense */
2374: offdiagA[r] = *ba;
2375: offdiagIdx[r] = cmap[0];
2376: } else { /* Brow is sparse so already KNOW maximum is 0.0 or higher */
2377: offdiagA[r] = 0.0;
2379: /* Find first hole in the cmap */
2380: for (j = 0; j < ncols; j++) {
2381: col = cmap[bj[j]]; /* global column number = cmap[B column number] */
2382: if (col > j && j < cstart) {
2383: offdiagIdx[r] = j; /* global column number of first implicit 0.0 */
2384: break;
2385: } else if (col > j + n && j >= cstart) {
2386: offdiagIdx[r] = j + n; /* global column number of first implicit 0.0 */
2387: break;
2388: }
2389: }
2390: if (j == ncols && ncols < A->cmap->N - n) {
2391: /* a hole is outside compressed Bcols */
2392: if (ncols == 0) {
2393: if (cstart) {
2394: offdiagIdx[r] = 0;
2395: } else offdiagIdx[r] = cend;
2396: } else { /* ncols > 0 */
2397: offdiagIdx[r] = cmap[ncols - 1] + 1;
2398: if (offdiagIdx[r] == cstart) offdiagIdx[r] += n;
2399: }
2400: }
2401: }
2403: for (j = 0; j < ncols; j++) {
2404: if (PetscRealPart(offdiagA[r]) > PetscRealPart(*ba)) {
2405: offdiagA[r] = *ba;
2406: offdiagIdx[r] = cmap[*bj];
2407: }
2408: ba++;
2409: bj++;
2410: }
2411: }
2413: PetscCall(VecGetArrayWrite(v, &a));
2414: PetscCall(VecGetArrayRead(diagV, (const PetscScalar **)&diagA));
2415: for (r = 0; r < m; ++r) {
2416: if (PetscRealPart(diagA[r]) < PetscRealPart(offdiagA[r])) {
2417: a[r] = diagA[r];
2418: if (idx) idx[r] = cstart + diagIdx[r];
2419: } else if (PetscRealPart(diagA[r]) == PetscRealPart(offdiagA[r])) {
2420: a[r] = diagA[r];
2421: if (idx) {
2422: if (cstart + diagIdx[r] <= offdiagIdx[r]) {
2423: idx[r] = cstart + diagIdx[r];
2424: } else idx[r] = offdiagIdx[r];
2425: }
2426: } else {
2427: a[r] = offdiagA[r];
2428: if (idx) idx[r] = offdiagIdx[r];
2429: }
2430: }
2431: PetscCall(MatSeqAIJRestoreArrayRead(B, &bav));
2432: PetscCall(VecRestoreArrayWrite(v, &a));
2433: PetscCall(VecRestoreArrayRead(diagV, (const PetscScalar **)&diagA));
2434: PetscCall(VecRestoreArrayWrite(offdiagV, &offdiagA));
2435: PetscCall(VecDestroy(&diagV));
2436: PetscCall(VecDestroy(&offdiagV));
2437: PetscCall(PetscFree2(diagIdx, offdiagIdx));
2438: PetscFunctionReturn(PETSC_SUCCESS);
2439: }
2441: static PetscErrorCode MatGetRowMax_MPIAIJ(Mat A, Vec v, PetscInt idx[])
2442: {
2443: Mat_MPIAIJ *mat = (Mat_MPIAIJ *)A->data;
2444: PetscInt m = A->rmap->n, n = A->cmap->n;
2445: PetscInt cstart = A->cmap->rstart, cend = A->cmap->rend;
2446: PetscInt *cmap = mat->garray;
2447: PetscInt *diagIdx, *offdiagIdx;
2448: Vec diagV, offdiagV;
2449: PetscScalar *a, *diagA, *offdiagA;
2450: const PetscScalar *ba, *bav;
2451: PetscInt r, j, col, ncols, *bi, *bj;
2452: Mat B = mat->B;
2453: Mat_SeqAIJ *b = (Mat_SeqAIJ *)B->data;
2455: PetscFunctionBegin;
2456: /* When a process holds entire A and other processes have no entry */
2457: if (A->cmap->N == n) {
2458: PetscCall(VecGetArrayWrite(v, &diagA));
2459: PetscCall(VecCreateSeqWithArray(PETSC_COMM_SELF, 1, m, diagA, &diagV));
2460: PetscCall(MatGetRowMax(mat->A, diagV, idx));
2461: PetscCall(VecDestroy(&diagV));
2462: PetscCall(VecRestoreArrayWrite(v, &diagA));
2463: PetscFunctionReturn(PETSC_SUCCESS);
2464: } else if (n == 0) {
2465: if (m) {
2466: PetscCall(VecGetArrayWrite(v, &a));
2467: for (r = 0; r < m; r++) {
2468: a[r] = PETSC_MIN_REAL;
2469: if (idx) idx[r] = -1;
2470: }
2471: PetscCall(VecRestoreArrayWrite(v, &a));
2472: }
2473: PetscFunctionReturn(PETSC_SUCCESS);
2474: }
2476: PetscCall(PetscMalloc2(m, &diagIdx, m, &offdiagIdx));
2477: PetscCall(VecCreateSeq(PETSC_COMM_SELF, m, &diagV));
2478: PetscCall(VecCreateSeq(PETSC_COMM_SELF, m, &offdiagV));
2479: PetscCall(MatGetRowMax(mat->A, diagV, diagIdx));
2481: /* Get offdiagIdx[] for implicit 0.0 */
2482: PetscCall(MatSeqAIJGetArrayRead(B, &bav));
2483: ba = bav;
2484: bi = b->i;
2485: bj = b->j;
2486: PetscCall(VecGetArrayWrite(offdiagV, &offdiagA));
2487: for (r = 0; r < m; r++) {
2488: ncols = bi[r + 1] - bi[r];
2489: if (ncols == A->cmap->N - n) { /* Brow is dense */
2490: offdiagA[r] = *ba;
2491: offdiagIdx[r] = cmap[0];
2492: } else { /* Brow is sparse so already KNOW maximum is 0.0 or higher */
2493: offdiagA[r] = 0.0;
2495: /* Find first hole in the cmap */
2496: for (j = 0; j < ncols; j++) {
2497: col = cmap[bj[j]]; /* global column number = cmap[B column number] */
2498: if (col > j && j < cstart) {
2499: offdiagIdx[r] = j; /* global column number of first implicit 0.0 */
2500: break;
2501: } else if (col > j + n && j >= cstart) {
2502: offdiagIdx[r] = j + n; /* global column number of first implicit 0.0 */
2503: break;
2504: }
2505: }
2506: if (j == ncols && ncols < A->cmap->N - n) {
2507: /* a hole is outside compressed Bcols */
2508: if (ncols == 0) {
2509: if (cstart) {
2510: offdiagIdx[r] = 0;
2511: } else offdiagIdx[r] = cend;
2512: } else { /* ncols > 0 */
2513: offdiagIdx[r] = cmap[ncols - 1] + 1;
2514: if (offdiagIdx[r] == cstart) offdiagIdx[r] += n;
2515: }
2516: }
2517: }
2519: for (j = 0; j < ncols; j++) {
2520: if (PetscRealPart(offdiagA[r]) < PetscRealPart(*ba)) {
2521: offdiagA[r] = *ba;
2522: offdiagIdx[r] = cmap[*bj];
2523: }
2524: ba++;
2525: bj++;
2526: }
2527: }
2529: PetscCall(VecGetArrayWrite(v, &a));
2530: PetscCall(VecGetArrayRead(diagV, (const PetscScalar **)&diagA));
2531: for (r = 0; r < m; ++r) {
2532: if (PetscRealPart(diagA[r]) > PetscRealPart(offdiagA[r])) {
2533: a[r] = diagA[r];
2534: if (idx) idx[r] = cstart + diagIdx[r];
2535: } else if (PetscRealPart(diagA[r]) == PetscRealPart(offdiagA[r])) {
2536: a[r] = diagA[r];
2537: if (idx) {
2538: if (cstart + diagIdx[r] <= offdiagIdx[r]) {
2539: idx[r] = cstart + diagIdx[r];
2540: } else idx[r] = offdiagIdx[r];
2541: }
2542: } else {
2543: a[r] = offdiagA[r];
2544: if (idx) idx[r] = offdiagIdx[r];
2545: }
2546: }
2547: PetscCall(MatSeqAIJRestoreArrayRead(B, &bav));
2548: PetscCall(VecRestoreArrayWrite(v, &a));
2549: PetscCall(VecRestoreArrayRead(diagV, (const PetscScalar **)&diagA));
2550: PetscCall(VecRestoreArrayWrite(offdiagV, &offdiagA));
2551: PetscCall(VecDestroy(&diagV));
2552: PetscCall(VecDestroy(&offdiagV));
2553: PetscCall(PetscFree2(diagIdx, offdiagIdx));
2554: PetscFunctionReturn(PETSC_SUCCESS);
2555: }
2557: PetscErrorCode MatGetSeqNonzeroStructure_MPIAIJ(Mat mat, Mat *newmat)
2558: {
2559: Mat *dummy;
2561: PetscFunctionBegin;
2562: PetscCall(MatCreateSubMatrix_MPIAIJ_All(mat, MAT_DO_NOT_GET_VALUES, MAT_INITIAL_MATRIX, &dummy));
2563: *newmat = *dummy;
2564: PetscCall(PetscFree(dummy));
2565: PetscFunctionReturn(PETSC_SUCCESS);
2566: }
2568: static PetscErrorCode MatInvertBlockDiagonal_MPIAIJ(Mat A, const PetscScalar **values)
2569: {
2570: Mat_MPIAIJ *a = (Mat_MPIAIJ *)A->data;
2572: PetscFunctionBegin;
2573: PetscCall(MatInvertBlockDiagonal(a->A, values));
2574: A->factorerrortype = a->A->factorerrortype;
2575: PetscFunctionReturn(PETSC_SUCCESS);
2576: }
2578: static PetscErrorCode MatSetRandom_MPIAIJ(Mat x, PetscRandom rctx)
2579: {
2580: Mat_MPIAIJ *aij = (Mat_MPIAIJ *)x->data;
2582: PetscFunctionBegin;
2583: PetscCheck(x->assembled || x->preallocated, PetscObjectComm((PetscObject)x), PETSC_ERR_ARG_WRONGSTATE, "MatSetRandom on an unassembled and unpreallocated MATMPIAIJ is not allowed");
2584: PetscCall(MatSetRandom(aij->A, rctx));
2585: if (x->assembled) {
2586: PetscCall(MatSetRandom(aij->B, rctx));
2587: } else {
2588: PetscCall(MatSetRandomSkipColumnRange_SeqAIJ_Private(aij->B, x->cmap->rstart, x->cmap->rend, rctx));
2589: }
2590: PetscCall(MatAssemblyBegin(x, MAT_FINAL_ASSEMBLY));
2591: PetscCall(MatAssemblyEnd(x, MAT_FINAL_ASSEMBLY));
2592: PetscFunctionReturn(PETSC_SUCCESS);
2593: }
2595: static PetscErrorCode MatMPIAIJSetUseScalableIncreaseOverlap_MPIAIJ(Mat A, PetscBool sc)
2596: {
2597: PetscFunctionBegin;
2598: if (sc) A->ops->increaseoverlap = MatIncreaseOverlap_MPIAIJ_Scalable;
2599: else A->ops->increaseoverlap = MatIncreaseOverlap_MPIAIJ;
2600: PetscFunctionReturn(PETSC_SUCCESS);
2601: }
2603: /*@
2604: MatMPIAIJGetNumberNonzeros - gets the number of nonzeros in the matrix on this MPI rank
2606: Not Collective
2608: Input Parameter:
2609: . A - the matrix
2611: Output Parameter:
2612: . nz - the number of nonzeros
2614: Level: advanced
2616: .seealso: [](ch_matrices), `Mat`, `MATMPIAIJ`
2617: @*/
2618: PetscErrorCode MatMPIAIJGetNumberNonzeros(Mat A, PetscCount *nz)
2619: {
2620: Mat_MPIAIJ *maij = (Mat_MPIAIJ *)A->data;
2621: Mat_SeqAIJ *aaij = (Mat_SeqAIJ *)maij->A->data, *baij = (Mat_SeqAIJ *)maij->B->data;
2622: PetscBool isaij;
2624: PetscFunctionBegin;
2625: PetscCall(PetscObjectBaseTypeCompare((PetscObject)A, MATMPIAIJ, &isaij));
2626: PetscCheck(isaij, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "Not for type %s", ((PetscObject)A)->type_name);
2627: *nz = aaij->i[A->rmap->n] + baij->i[A->rmap->n];
2628: PetscFunctionReturn(PETSC_SUCCESS);
2629: }
2631: /*@
2632: MatMPIAIJSetUseScalableIncreaseOverlap - Determine if the matrix uses a scalable algorithm to compute the overlap
2634: Collective
2636: Input Parameters:
2637: + A - the matrix
2638: - sc - `PETSC_TRUE` indicates use the scalable algorithm (default is not to use the scalable algorithm)
2640: Level: advanced
2642: .seealso: [](ch_matrices), `Mat`, `MATMPIAIJ`
2643: @*/
2644: PetscErrorCode MatMPIAIJSetUseScalableIncreaseOverlap(Mat A, PetscBool sc)
2645: {
2646: PetscFunctionBegin;
2647: PetscTryMethod(A, "MatMPIAIJSetUseScalableIncreaseOverlap_C", (Mat, PetscBool), (A, sc));
2648: PetscFunctionReturn(PETSC_SUCCESS);
2649: }
2651: PetscErrorCode MatSetFromOptions_MPIAIJ(Mat A, PetscOptionItems PetscOptionsObject)
2652: {
2653: PetscBool sc = PETSC_FALSE, flg;
2655: PetscFunctionBegin;
2656: PetscOptionsHeadBegin(PetscOptionsObject, "MPIAIJ options");
2657: if (A->ops->increaseoverlap == MatIncreaseOverlap_MPIAIJ_Scalable) sc = PETSC_TRUE;
2658: PetscCall(PetscOptionsBool("-mat_increase_overlap_scalable", "Use a scalable algorithm to compute the overlap", "MatIncreaseOverlap", sc, &sc, &flg));
2659: if (flg) PetscCall(MatMPIAIJSetUseScalableIncreaseOverlap(A, sc));
2660: PetscOptionsHeadEnd();
2661: PetscFunctionReturn(PETSC_SUCCESS);
2662: }
2664: static PetscErrorCode MatShift_MPIAIJ(Mat Y, PetscScalar a)
2665: {
2666: Mat_MPIAIJ *maij = (Mat_MPIAIJ *)Y->data;
2667: Mat_SeqAIJ *aij = (Mat_SeqAIJ *)maij->A->data;
2669: PetscFunctionBegin;
2670: if (!Y->preallocated) {
2671: PetscCall(MatMPIAIJSetPreallocation(Y, 1, NULL, 0, NULL));
2672: } else if (!aij->nz) { /* It does not matter if diagonals of Y only partially lie in maij->A. We just need an estimated preallocation. */
2673: PetscInt nonew = aij->nonew;
2674: PetscCall(MatSeqAIJSetPreallocation(maij->A, 1, NULL));
2675: aij->nonew = nonew;
2676: }
2677: PetscCall(MatShift_Basic(Y, a));
2678: PetscFunctionReturn(PETSC_SUCCESS);
2679: }
2681: static PetscErrorCode MatInvertVariableBlockDiagonal_MPIAIJ(Mat A, PetscInt nblocks, const PetscInt *bsizes, PetscScalar *diag)
2682: {
2683: Mat_MPIAIJ *a = (Mat_MPIAIJ *)A->data;
2685: PetscFunctionBegin;
2686: PetscCall(MatInvertVariableBlockDiagonal(a->A, nblocks, bsizes, diag));
2687: PetscFunctionReturn(PETSC_SUCCESS);
2688: }
2690: static PetscErrorCode MatEliminateZeros_MPIAIJ(Mat A, PetscBool keep)
2691: {
2692: Mat_MPIAIJ *a = (Mat_MPIAIJ *)A->data;
2694: PetscFunctionBegin;
2695: PetscCall(MatEliminateZeros_SeqAIJ(a->A, keep)); // possibly keep zero diagonal coefficients
2696: PetscCall(MatEliminateZeros_SeqAIJ(a->B, PETSC_FALSE)); // never keep zero diagonal coefficients
2697: PetscFunctionReturn(PETSC_SUCCESS);
2698: }
2700: static PetscErrorCode MatGetOrdering_MPIAIJ(Mat A, MatOrderingType type, IS *rperm, IS *cperm)
2701: {
2702: Mat_MPIAIJ *a = (Mat_MPIAIJ *)A->data;
2703: IS lrowperm, lcolperm;
2704: PetscInt i, rstart, rend, *idx;
2705: const PetscInt *lidx;
2707: PetscFunctionBegin;
2708: PetscCall(MatGetOrdering(a->A, type, &lrowperm, &lcolperm));
2709: PetscCall(MatGetOwnershipRange(A, &rstart, &rend));
2710: /* Remap row index set to global space */
2711: PetscCall(ISGetIndices(lrowperm, &lidx));
2712: PetscCall(PetscMalloc1(rend - rstart, &idx));
2713: for (i = 0; i + rstart < rend; i++) idx[i] = rstart + lidx[i];
2714: PetscCall(ISRestoreIndices(lrowperm, &lidx));
2715: PetscCall(ISDestroy(&lrowperm));
2716: PetscCall(ISCreateGeneral(PetscObjectComm((PetscObject)A), rend - rstart, idx, PETSC_OWN_POINTER, rperm));
2717: PetscCall(ISSetPermutation(*rperm));
2718: /* Remap column index set to global space */
2719: PetscCall(ISGetIndices(lcolperm, &lidx));
2720: PetscCall(PetscMalloc1(rend - rstart, &idx));
2721: for (i = 0; i + rstart < rend; i++) idx[i] = rstart + lidx[i];
2722: PetscCall(ISRestoreIndices(lcolperm, &lidx));
2723: PetscCall(ISDestroy(&lcolperm));
2724: PetscCall(ISCreateGeneral(PetscObjectComm((PetscObject)A), rend - rstart, idx, PETSC_OWN_POINTER, cperm));
2725: PetscCall(ISSetPermutation(*cperm));
2726: PetscFunctionReturn(PETSC_SUCCESS);
2727: }
2729: static struct _MatOps MatOps_Values = {MatSetValues_MPIAIJ,
2730: MatGetRow_MPIAIJ,
2731: MatRestoreRow_MPIAIJ,
2732: MatMult_MPIAIJ,
2733: /* 4*/ MatMultAdd_MPIAIJ,
2734: MatMultTranspose_MPIAIJ,
2735: MatMultTransposeAdd_MPIAIJ,
2736: NULL,
2737: NULL,
2738: NULL,
2739: /*10*/ NULL,
2740: NULL,
2741: NULL,
2742: MatSOR_MPIAIJ,
2743: MatTranspose_MPIAIJ,
2744: /*15*/ MatGetInfo_MPIAIJ,
2745: MatEqual_MPIAIJ,
2746: MatGetDiagonal_MPIAIJ,
2747: MatDiagonalScale_MPIAIJ,
2748: MatNorm_MPIAIJ,
2749: /*20*/ MatAssemblyBegin_MPIAIJ,
2750: MatAssemblyEnd_MPIAIJ,
2751: MatSetOption_MPIAIJ,
2752: MatZeroEntries_MPIAIJ,
2753: /*24*/ MatZeroRows_MPIAIJ,
2754: NULL,
2755: NULL,
2756: NULL,
2757: NULL,
2758: /*29*/ MatSetUp_MPI_Hash,
2759: NULL,
2760: NULL,
2761: MatGetDiagonalBlock_MPIAIJ,
2762: NULL,
2763: /*34*/ MatDuplicate_MPIAIJ,
2764: NULL,
2765: NULL,
2766: NULL,
2767: NULL,
2768: /*39*/ MatAXPY_MPIAIJ,
2769: MatCreateSubMatrices_MPIAIJ,
2770: MatIncreaseOverlap_MPIAIJ,
2771: MatGetValues_MPIAIJ,
2772: MatCopy_MPIAIJ,
2773: /*44*/ MatGetRowMax_MPIAIJ,
2774: MatScale_MPIAIJ,
2775: MatShift_MPIAIJ,
2776: MatDiagonalSet_MPIAIJ,
2777: MatZeroRowsColumns_MPIAIJ,
2778: /*49*/ MatSetRandom_MPIAIJ,
2779: MatGetRowIJ_MPIAIJ,
2780: MatRestoreRowIJ_MPIAIJ,
2781: NULL,
2782: NULL,
2783: /*54*/ MatFDColoringCreate_MPIXAIJ,
2784: NULL,
2785: MatSetUnfactored_MPIAIJ,
2786: MatPermute_MPIAIJ,
2787: NULL,
2788: /*59*/ MatCreateSubMatrix_MPIAIJ,
2789: MatDestroy_MPIAIJ,
2790: MatView_MPIAIJ,
2791: NULL,
2792: NULL,
2793: /*64*/ MatMatMatMultNumeric_MPIAIJ_MPIAIJ_MPIAIJ,
2794: NULL,
2795: NULL,
2796: NULL,
2797: MatGetRowMaxAbs_MPIAIJ,
2798: /*69*/ MatGetRowMinAbs_MPIAIJ,
2799: NULL,
2800: NULL,
2801: MatFDColoringApply_AIJ,
2802: MatSetFromOptions_MPIAIJ,
2803: MatFindZeroDiagonals_MPIAIJ,
2804: /*75*/ NULL,
2805: NULL,
2806: NULL,
2807: MatLoad_MPIAIJ,
2808: NULL,
2809: /*80*/ NULL,
2810: NULL,
2811: NULL,
2812: /*83*/ NULL,
2813: NULL,
2814: MatMatMultNumeric_MPIAIJ_MPIAIJ,
2815: MatPtAPNumeric_MPIAIJ_MPIAIJ,
2816: NULL,
2817: NULL,
2818: /*89*/ MatBindToCPU_MPIAIJ,
2819: MatProductSetFromOptions_MPIAIJ,
2820: NULL,
2821: NULL,
2822: MatConjugate_MPIAIJ,
2823: /*94*/ NULL,
2824: MatSetValuesRow_MPIAIJ,
2825: MatRealPart_MPIAIJ,
2826: MatImaginaryPart_MPIAIJ,
2827: NULL,
2828: /*99*/ NULL,
2829: NULL,
2830: NULL,
2831: MatGetRowMin_MPIAIJ,
2832: NULL,
2833: /*104*/ MatGetSeqNonzeroStructure_MPIAIJ,
2834: NULL,
2835: MatGetGhosts_MPIAIJ,
2836: NULL,
2837: NULL,
2838: /*109*/ MatMultDiagonalBlock_MPIAIJ,
2839: NULL,
2840: NULL,
2841: NULL,
2842: MatGetMultiProcBlock_MPIAIJ,
2843: /*114*/ MatFindNonzeroRows_MPIAIJ,
2844: MatGetColumnReductions_MPIAIJ,
2845: MatInvertBlockDiagonal_MPIAIJ,
2846: MatInvertVariableBlockDiagonal_MPIAIJ,
2847: MatCreateSubMatricesMPI_MPIAIJ,
2848: /*119*/ NULL,
2849: MatTransposeMatMultNumeric_MPIAIJ_MPIAIJ,
2850: NULL,
2851: NULL,
2852: NULL,
2853: /*124*/ NULL,
2854: MatSetBlockSizes_MPIAIJ,
2855: NULL,
2856: MatFDColoringSetUp_MPIXAIJ,
2857: MatFindOffBlockDiagonalEntries_MPIAIJ,
2858: /*129*/ MatCreateMPIMatConcatenateSeqMat_MPIAIJ,
2859: NULL,
2860: NULL,
2861: NULL,
2862: MatCreateGraph_Simple_AIJ,
2863: /*134*/ NULL,
2864: MatEliminateZeros_MPIAIJ,
2865: MatGetRowSumAbs_MPIAIJ,
2866: NULL,
2867: NULL,
2868: /*139*/ NULL,
2869: MatCopyHashToXAIJ_MPI_Hash,
2870: MatGetCurrentMemType_MPIAIJ,
2871: NULL,
2872: MatADot_Default,
2873: /*144*/ MatANorm_Default,
2874: NULL,
2875: NULL,
2876: MatGetOrdering_MPIAIJ};
2878: static PetscErrorCode MatStoreValues_MPIAIJ(Mat mat)
2879: {
2880: Mat_MPIAIJ *aij = (Mat_MPIAIJ *)mat->data;
2882: PetscFunctionBegin;
2883: PetscCall(MatStoreValues(aij->A));
2884: PetscCall(MatStoreValues(aij->B));
2885: PetscFunctionReturn(PETSC_SUCCESS);
2886: }
2888: static PetscErrorCode MatRetrieveValues_MPIAIJ(Mat mat)
2889: {
2890: Mat_MPIAIJ *aij = (Mat_MPIAIJ *)mat->data;
2892: PetscFunctionBegin;
2893: PetscCall(MatRetrieveValues(aij->A));
2894: PetscCall(MatRetrieveValues(aij->B));
2895: PetscFunctionReturn(PETSC_SUCCESS);
2896: }
2898: PetscErrorCode MatMPIAIJSetPreallocation_MPIAIJ(Mat B, PetscInt d_nz, const PetscInt d_nnz[], PetscInt o_nz, const PetscInt o_nnz[])
2899: {
2900: Mat_MPIAIJ *b = (Mat_MPIAIJ *)B->data;
2901: PetscMPIInt size;
2903: PetscFunctionBegin;
2904: if (B->hash_active) {
2905: B->ops[0] = b->cops;
2906: B->hash_active = PETSC_FALSE;
2907: }
2908: PetscCall(PetscLayoutSetUp(B->rmap));
2909: PetscCall(PetscLayoutSetUp(B->cmap));
2911: #if defined(PETSC_USE_CTABLE)
2912: PetscCall(PetscHMapIDestroy(&b->colmap));
2913: #else
2914: PetscCall(PetscFree(b->colmap));
2915: #endif
2916: PetscCall(PetscFree(b->garray));
2917: PetscCall(VecDestroy(&b->lvec));
2918: PetscCall(VecScatterDestroy(&b->Mvctx));
2920: PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)B), &size));
2922: MatSeqXAIJGetOptions_Private(b->B);
2923: PetscCall(MatDestroy(&b->B));
2924: PetscCall(MatCreate(PETSC_COMM_SELF, &b->B));
2925: PetscCall(MatSetSizes(b->B, B->rmap->n, size > 1 ? B->cmap->N : 0, B->rmap->n, size > 1 ? B->cmap->N : 0));
2926: PetscCall(MatSetBlockSizesFromMats(b->B, B, B));
2927: PetscCall(MatSetType(b->B, MATSEQAIJ));
2928: MatSeqXAIJRestoreOptions_Private(b->B);
2930: MatSeqXAIJGetOptions_Private(b->A);
2931: PetscCall(MatDestroy(&b->A));
2932: PetscCall(MatCreate(PETSC_COMM_SELF, &b->A));
2933: PetscCall(MatSetSizes(b->A, B->rmap->n, B->cmap->n, B->rmap->n, B->cmap->n));
2934: PetscCall(MatSetBlockSizesFromMats(b->A, B, B));
2935: PetscCall(MatSetType(b->A, MATSEQAIJ));
2936: MatSeqXAIJRestoreOptions_Private(b->A);
2938: PetscCall(MatSeqAIJSetPreallocation(b->A, d_nz, d_nnz));
2939: PetscCall(MatSeqAIJSetPreallocation(b->B, o_nz, o_nnz));
2940: B->preallocated = PETSC_TRUE;
2941: B->was_assembled = PETSC_FALSE;
2942: B->assembled = PETSC_FALSE;
2943: PetscFunctionReturn(PETSC_SUCCESS);
2944: }
2946: static PetscErrorCode MatResetPreallocation_MPIAIJ(Mat B)
2947: {
2948: Mat_MPIAIJ *b = (Mat_MPIAIJ *)B->data;
2949: PetscBool ondiagreset, offdiagreset, memoryreset;
2951: PetscFunctionBegin;
2953: PetscCheck(B->insertmode == NOT_SET_VALUES, PETSC_COMM_SELF, PETSC_ERR_SUP, "Cannot reset preallocation after setting some values but not yet calling MatAssemblyBegin()/MatAssemblyEnd()");
2954: if (B->num_ass == 0) PetscFunctionReturn(PETSC_SUCCESS);
2956: PetscCall(MatResetPreallocation_SeqAIJ_Private(b->A, &ondiagreset));
2957: PetscCall(MatResetPreallocation_SeqAIJ_Private(b->B, &offdiagreset));
2958: memoryreset = (PetscBool)(ondiagreset || offdiagreset);
2959: PetscCallMPI(MPIU_Allreduce(MPI_IN_PLACE, &memoryreset, 1, MPI_C_BOOL, MPI_LOR, PetscObjectComm((PetscObject)B)));
2960: if (!memoryreset) PetscFunctionReturn(PETSC_SUCCESS);
2962: PetscCall(PetscLayoutSetUp(B->rmap));
2963: PetscCall(PetscLayoutSetUp(B->cmap));
2964: PetscCheck(B->assembled || B->was_assembled, PetscObjectComm((PetscObject)B), PETSC_ERR_ARG_WRONGSTATE, "Should not need to reset preallocation if the matrix was never assembled");
2965: PetscCall(MatDisAssemble_MPIAIJ(B, PETSC_TRUE));
2966: PetscCall(VecScatterDestroy(&b->Mvctx));
2968: B->preallocated = PETSC_TRUE;
2969: B->was_assembled = PETSC_FALSE;
2970: B->assembled = PETSC_FALSE;
2971: /* Log that the state of this object has changed; this will help guarantee that preconditioners get re-setup */
2972: PetscCall(PetscObjectStateIncrease((PetscObject)B));
2973: PetscFunctionReturn(PETSC_SUCCESS);
2974: }
2976: PetscErrorCode MatDuplicate_MPIAIJ(Mat matin, MatDuplicateOption cpvalues, Mat *newmat)
2977: {
2978: Mat mat;
2979: Mat_MPIAIJ *a, *oldmat = (Mat_MPIAIJ *)matin->data;
2981: PetscFunctionBegin;
2982: *newmat = NULL;
2983: PetscCall(MatCreate(PetscObjectComm((PetscObject)matin), &mat));
2984: PetscCall(MatSetSizes(mat, matin->rmap->n, matin->cmap->n, matin->rmap->N, matin->cmap->N));
2985: PetscCall(MatSetBlockSizesFromMats(mat, matin, matin));
2986: PetscCall(MatSetType(mat, ((PetscObject)matin)->type_name));
2987: a = (Mat_MPIAIJ *)mat->data;
2989: mat->factortype = matin->factortype;
2990: mat->assembled = matin->assembled;
2991: mat->insertmode = NOT_SET_VALUES;
2993: a->size = oldmat->size;
2994: a->rank = oldmat->rank;
2995: a->donotstash = oldmat->donotstash;
2996: a->roworiented = oldmat->roworiented;
2997: a->rowindices = NULL;
2998: a->rowvalues = NULL;
2999: a->getrowactive = PETSC_FALSE;
3001: PetscCall(PetscLayoutReference(matin->rmap, &mat->rmap));
3002: PetscCall(PetscLayoutReference(matin->cmap, &mat->cmap));
3003: if (matin->hash_active) PetscCall(MatSetUp(mat));
3004: else {
3005: mat->preallocated = matin->preallocated;
3006: if (oldmat->colmap) {
3007: #if defined(PETSC_USE_CTABLE)
3008: PetscCall(PetscHMapIDuplicate(oldmat->colmap, &a->colmap));
3009: #else
3010: PetscCall(PetscMalloc1(mat->cmap->N, &a->colmap));
3011: PetscCall(PetscArraycpy(a->colmap, oldmat->colmap, mat->cmap->N));
3012: #endif
3013: } else a->colmap = NULL;
3014: if (oldmat->garray) {
3015: PetscInt len;
3016: len = oldmat->B->cmap->n;
3017: PetscCall(PetscMalloc1(len, &a->garray));
3018: if (len) PetscCall(PetscArraycpy(a->garray, oldmat->garray, len));
3019: } else a->garray = NULL;
3021: /* It may happen MatDuplicate is called with a non-assembled matrix
3022: In fact, MatDuplicate only requires the matrix to be preallocated
3023: This may happen inside a DMCreateMatrix_Shell */
3024: if (oldmat->lvec) PetscCall(VecDuplicate(oldmat->lvec, &a->lvec));
3025: if (oldmat->Mvctx) {
3026: a->Mvctx = oldmat->Mvctx;
3027: PetscCall(PetscObjectReference((PetscObject)oldmat->Mvctx));
3028: }
3029: PetscCall(MatDuplicate(oldmat->A, cpvalues, &a->A));
3030: PetscCall(MatDuplicate(oldmat->B, cpvalues, &a->B));
3031: }
3032: PetscCall(PetscFunctionListDuplicate(((PetscObject)matin)->qlist, &((PetscObject)mat)->qlist));
3033: *newmat = mat;
3034: PetscFunctionReturn(PETSC_SUCCESS);
3035: }
3037: PetscErrorCode MatLoad_MPIAIJ(Mat newMat, PetscViewer viewer)
3038: {
3039: PetscBool isbinary, ishdf5;
3041: PetscFunctionBegin;
3044: /* force binary viewer to load .info file if it has not yet done so */
3045: PetscCall(PetscViewerSetUp(viewer));
3046: PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERBINARY, &isbinary));
3047: PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERHDF5, &ishdf5));
3048: if (isbinary) {
3049: PetscCall(MatLoad_MPIAIJ_Binary(newMat, viewer));
3050: } else if (ishdf5) {
3051: #if defined(PETSC_HAVE_HDF5)
3052: PetscCall(MatLoad_AIJ_HDF5(newMat, viewer));
3053: #else
3054: SETERRQ(PetscObjectComm((PetscObject)newMat), PETSC_ERR_SUP, "HDF5 not supported in this build.\nPlease reconfigure using --download-hdf5");
3055: #endif
3056: } else {
3057: SETERRQ(PetscObjectComm((PetscObject)newMat), PETSC_ERR_SUP, "Viewer type %s not yet supported for reading %s matrices", ((PetscObject)viewer)->type_name, ((PetscObject)newMat)->type_name);
3058: }
3059: PetscFunctionReturn(PETSC_SUCCESS);
3060: }
3062: PetscErrorCode MatLoad_MPIAIJ_Binary(Mat mat, PetscViewer viewer)
3063: {
3064: PetscInt header[4], M, N, m, nz, rows, cols, sum, i;
3065: PetscInt *rowidxs, *colidxs;
3066: PetscScalar *matvals;
3068: PetscFunctionBegin;
3069: PetscCall(PetscViewerSetUp(viewer));
3071: /* read in matrix header */
3072: PetscCall(PetscViewerBinaryRead(viewer, header, 4, NULL, PETSC_INT));
3073: PetscCheck(header[0] == MAT_FILE_CLASSID, PetscObjectComm((PetscObject)viewer), PETSC_ERR_FILE_UNEXPECTED, "Not a matrix object in file");
3074: M = header[1];
3075: N = header[2];
3076: nz = header[3];
3077: PetscCheck(M >= 0, PetscObjectComm((PetscObject)viewer), PETSC_ERR_FILE_UNEXPECTED, "Matrix row size (%" PetscInt_FMT ") in file is negative", M);
3078: PetscCheck(N >= 0, PetscObjectComm((PetscObject)viewer), PETSC_ERR_FILE_UNEXPECTED, "Matrix column size (%" PetscInt_FMT ") in file is negative", N);
3079: PetscCheck(nz >= 0, PETSC_COMM_SELF, PETSC_ERR_FILE_UNEXPECTED, "Matrix stored in special format on disk, cannot load as MPIAIJ");
3081: /* set block sizes from the viewer's .info file */
3082: PetscCall(MatLoad_Binary_BlockSizes(mat, viewer));
3083: /* set global sizes if not set already */
3084: if (mat->rmap->N < 0) mat->rmap->N = M;
3085: if (mat->cmap->N < 0) mat->cmap->N = N;
3086: PetscCall(PetscLayoutSetUp(mat->rmap));
3087: PetscCall(PetscLayoutSetUp(mat->cmap));
3089: /* check if the matrix sizes are correct */
3090: PetscCall(MatGetSize(mat, &rows, &cols));
3091: PetscCheck(M == rows && N == cols, PETSC_COMM_SELF, PETSC_ERR_FILE_UNEXPECTED, "Matrix in file of different sizes (%" PetscInt_FMT ", %" PetscInt_FMT ") than the input matrix (%" PetscInt_FMT ", %" PetscInt_FMT ")", M, N, rows, cols);
3093: /* read in row lengths and build row indices */
3094: PetscCall(MatGetLocalSize(mat, &m, NULL));
3095: PetscCall(PetscMalloc1(m + 1, &rowidxs));
3096: PetscCall(PetscViewerBinaryReadAll(viewer, rowidxs + 1, m, PETSC_DECIDE, M, PETSC_INT));
3097: rowidxs[0] = 0;
3098: for (i = 0; i < m; i++) rowidxs[i + 1] += rowidxs[i];
3099: if (nz != PETSC_INT_MAX) {
3100: PetscCallMPI(MPIU_Allreduce(&rowidxs[m], &sum, 1, MPIU_INT, MPI_SUM, PetscObjectComm((PetscObject)viewer)));
3101: PetscCheck(sum == nz, PetscObjectComm((PetscObject)viewer), PETSC_ERR_FILE_UNEXPECTED, "Inconsistent matrix data in file: nonzeros = %" PetscInt_FMT ", sum-row-lengths = %" PetscInt_FMT, nz, sum);
3102: }
3104: /* read in column indices and matrix values */
3105: PetscCall(PetscMalloc2(rowidxs[m], &colidxs, rowidxs[m], &matvals));
3106: PetscCall(PetscViewerBinaryReadAll(viewer, colidxs, rowidxs[m], PETSC_DETERMINE, PETSC_DETERMINE, PETSC_INT));
3107: PetscCall(PetscViewerBinaryReadAll(viewer, matvals, rowidxs[m], PETSC_DETERMINE, PETSC_DETERMINE, PETSC_SCALAR));
3108: /* store matrix indices and values */
3109: PetscCall(MatMPIAIJSetPreallocationCSR(mat, rowidxs, colidxs, matvals));
3110: PetscCall(PetscFree(rowidxs));
3111: PetscCall(PetscFree2(colidxs, matvals));
3112: PetscFunctionReturn(PETSC_SUCCESS);
3113: }
3115: /* Not scalable because of ISAllGather() unless getting all columns. */
3116: static PetscErrorCode ISGetSeqIS_Private(Mat mat, IS iscol, IS *isseq)
3117: {
3118: IS iscol_local;
3119: PetscBool isstride;
3120: PetscMPIInt gisstride = 0;
3122: PetscFunctionBegin;
3123: /* check if we are grabbing all columns*/
3124: PetscCall(PetscObjectTypeCompare((PetscObject)iscol, ISSTRIDE, &isstride));
3126: if (isstride) {
3127: PetscInt start, len, mstart, mlen;
3128: PetscCall(ISStrideGetInfo(iscol, &start, NULL));
3129: PetscCall(ISGetLocalSize(iscol, &len));
3130: PetscCall(MatGetOwnershipRangeColumn(mat, &mstart, &mlen));
3131: if (mstart == start && mlen - mstart == len) gisstride = 1;
3132: }
3134: PetscCallMPI(MPIU_Allreduce(MPI_IN_PLACE, &gisstride, 1, MPI_INT, MPI_MIN, PetscObjectComm((PetscObject)mat)));
3135: if (gisstride) {
3136: PetscInt N;
3137: PetscCall(MatGetSize(mat, NULL, &N));
3138: PetscCall(ISCreateStride(PETSC_COMM_SELF, N, 0, 1, &iscol_local));
3139: PetscCall(ISSetIdentity(iscol_local));
3140: PetscCall(PetscInfo(mat, "Optimizing for obtaining all columns of the matrix; skipping ISAllGather()\n"));
3141: } else {
3142: PetscInt cbs;
3143: PetscCall(ISGetBlockSize(iscol, &cbs));
3144: PetscCall(ISAllGather(iscol, &iscol_local));
3145: PetscCall(ISSetBlockSize(iscol_local, cbs));
3146: }
3148: *isseq = iscol_local;
3149: PetscFunctionReturn(PETSC_SUCCESS);
3150: }
3152: /*
3153: Used by MatCreateSubMatrix_MPIAIJ_SameRowColDist() to avoid ISAllGather() and global size of iscol_local
3154: (see MatCreateSubMatrix_MPIAIJ_nonscalable)
3156: Input Parameters:
3157: + mat - matrix
3158: . isrow - parallel row index set; its local indices are a subset of local columns of `mat`,
3159: i.e., mat->rstart <= isrow[i] < mat->rend
3160: - iscol - parallel column index set; its local indices are a subset of local columns of `mat`,
3161: i.e., mat->cstart <= iscol[i] < mat->cend
3163: Output Parameters:
3164: + isrow_d - sequential row index set for retrieving mat->A
3165: . iscol_d - sequential column index set for retrieving mat->A
3166: . iscol_o - sequential column index set for retrieving mat->B
3167: - garray - column map; garray[i] indicates global location of iscol_o[i] in `iscol`
3168: */
3169: static PetscErrorCode ISGetSeqIS_SameColDist_Private(Mat mat, IS isrow, IS iscol, IS *isrow_d, IS *iscol_d, IS *iscol_o, PetscInt *garray[])
3170: {
3171: Vec x, cmap;
3172: const PetscInt *is_idx;
3173: PetscScalar *xarray, *cmaparray;
3174: PetscInt ncols, isstart, *idx, m, rstart, *cmap1, count;
3175: Mat_MPIAIJ *a = (Mat_MPIAIJ *)mat->data;
3176: Mat B = a->B;
3177: Vec lvec = a->lvec, lcmap;
3178: PetscInt i, cstart, cend, Bn = B->cmap->N;
3179: MPI_Comm comm;
3180: VecScatter Mvctx = a->Mvctx;
3182: PetscFunctionBegin;
3183: PetscCall(PetscObjectGetComm((PetscObject)mat, &comm));
3184: PetscCall(ISGetLocalSize(iscol, &ncols));
3186: /* (1) iscol is a sub-column vector of mat, pad it with '-1.' to form a full vector x */
3187: PetscCall(MatCreateVecs(mat, &x, NULL));
3188: PetscCall(VecSet(x, -1.0));
3189: PetscCall(VecDuplicate(x, &cmap));
3190: PetscCall(VecSet(cmap, -1.0));
3192: /* Get start indices */
3193: PetscCallMPI(MPI_Scan(&ncols, &isstart, 1, MPIU_INT, MPI_SUM, comm));
3194: isstart -= ncols;
3195: PetscCall(MatGetOwnershipRangeColumn(mat, &cstart, &cend));
3197: PetscCall(ISGetIndices(iscol, &is_idx));
3198: PetscCall(VecGetArray(x, &xarray));
3199: PetscCall(VecGetArray(cmap, &cmaparray));
3200: PetscCall(PetscMalloc1(ncols, &idx));
3201: for (i = 0; i < ncols; i++) {
3202: xarray[is_idx[i] - cstart] = (PetscScalar)is_idx[i];
3203: cmaparray[is_idx[i] - cstart] = i + isstart; /* global index of iscol[i] */
3204: idx[i] = is_idx[i] - cstart; /* local index of iscol[i] */
3205: }
3206: PetscCall(VecRestoreArray(x, &xarray));
3207: PetscCall(VecRestoreArray(cmap, &cmaparray));
3208: PetscCall(ISRestoreIndices(iscol, &is_idx));
3210: /* Get iscol_d */
3211: PetscCall(ISCreateGeneral(PETSC_COMM_SELF, ncols, idx, PETSC_OWN_POINTER, iscol_d));
3212: PetscCall(ISGetBlockSize(iscol, &i));
3213: PetscCall(ISSetBlockSize(*iscol_d, i));
3215: /* Get isrow_d */
3216: PetscCall(ISGetLocalSize(isrow, &m));
3217: rstart = mat->rmap->rstart;
3218: PetscCall(PetscMalloc1(m, &idx));
3219: PetscCall(ISGetIndices(isrow, &is_idx));
3220: for (i = 0; i < m; i++) idx[i] = is_idx[i] - rstart;
3221: PetscCall(ISRestoreIndices(isrow, &is_idx));
3223: PetscCall(ISCreateGeneral(PETSC_COMM_SELF, m, idx, PETSC_OWN_POINTER, isrow_d));
3224: PetscCall(ISGetBlockSize(isrow, &i));
3225: PetscCall(ISSetBlockSize(*isrow_d, i));
3227: /* (2) Scatter x and cmap using aij->Mvctx to get their off-process portions (see MatMult_MPIAIJ) */
3228: PetscCall(VecScatterBegin(Mvctx, x, lvec, INSERT_VALUES, SCATTER_FORWARD));
3229: PetscCall(VecScatterEnd(Mvctx, x, lvec, INSERT_VALUES, SCATTER_FORWARD));
3231: PetscCall(VecDuplicate(lvec, &lcmap));
3233: PetscCall(VecScatterBegin(Mvctx, cmap, lcmap, INSERT_VALUES, SCATTER_FORWARD));
3234: PetscCall(VecScatterEnd(Mvctx, cmap, lcmap, INSERT_VALUES, SCATTER_FORWARD));
3236: /* (3) create sequential iscol_o (a subset of iscol) and isgarray */
3237: /* off-process column indices */
3238: count = 0;
3239: PetscCall(PetscMalloc1(Bn, &idx));
3240: PetscCall(PetscMalloc1(Bn, &cmap1));
3242: PetscCall(VecGetArray(lvec, &xarray));
3243: PetscCall(VecGetArray(lcmap, &cmaparray));
3244: for (i = 0; i < Bn; i++) {
3245: if (PetscRealPart(xarray[i]) > -1.0) {
3246: idx[count] = i; /* local column index in off-diagonal part B */
3247: cmap1[count] = (PetscInt)PetscRealPart(cmaparray[i]); /* column index in submat */
3248: count++;
3249: }
3250: }
3251: PetscCall(VecRestoreArray(lvec, &xarray));
3252: PetscCall(VecRestoreArray(lcmap, &cmaparray));
3254: PetscCall(ISCreateGeneral(PETSC_COMM_SELF, count, idx, PETSC_COPY_VALUES, iscol_o));
3255: /* cannot ensure iscol_o has same blocksize as iscol! */
3257: PetscCall(PetscFree(idx));
3258: *garray = cmap1;
3260: PetscCall(VecDestroy(&x));
3261: PetscCall(VecDestroy(&cmap));
3262: PetscCall(VecDestroy(&lcmap));
3263: PetscFunctionReturn(PETSC_SUCCESS);
3264: }
3266: /* isrow and iscol have same processor distribution as mat, output *submat is a submatrix of local mat */
3267: PetscErrorCode MatCreateSubMatrix_MPIAIJ_SameRowColDist(Mat mat, IS isrow, IS iscol, MatReuse call, Mat *submat)
3268: {
3269: Mat_MPIAIJ *a = (Mat_MPIAIJ *)mat->data, *asub;
3270: Mat M = NULL;
3271: MPI_Comm comm;
3272: IS iscol_d, isrow_d, iscol_o;
3273: Mat Asub = NULL, Bsub = NULL;
3274: PetscInt n, count, M_size, N_size;
3276: PetscFunctionBegin;
3277: PetscCall(PetscObjectGetComm((PetscObject)mat, &comm));
3279: if (call == MAT_REUSE_MATRIX) {
3280: /* Retrieve isrow_d, iscol_d and iscol_o from submat */
3281: PetscCall(PetscObjectQuery((PetscObject)*submat, "isrow_d", (PetscObject *)&isrow_d));
3282: PetscCheck(isrow_d, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "isrow_d passed in was not used before, cannot reuse");
3284: PetscCall(PetscObjectQuery((PetscObject)*submat, "iscol_d", (PetscObject *)&iscol_d));
3285: PetscCheck(iscol_d, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "iscol_d passed in was not used before, cannot reuse");
3287: PetscCall(PetscObjectQuery((PetscObject)*submat, "iscol_o", (PetscObject *)&iscol_o));
3288: PetscCheck(iscol_o, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "iscol_o passed in was not used before, cannot reuse");
3290: /* Update diagonal and off-diagonal portions of submat */
3291: asub = (Mat_MPIAIJ *)(*submat)->data;
3292: PetscCall(MatCreateSubMatrix_SeqAIJ(a->A, isrow_d, iscol_d, PETSC_DECIDE, MAT_REUSE_MATRIX, &asub->A));
3293: PetscCall(ISGetLocalSize(iscol_o, &n));
3294: if (n) PetscCall(MatCreateSubMatrix_SeqAIJ(a->B, isrow_d, iscol_o, PETSC_DECIDE, MAT_REUSE_MATRIX, &asub->B));
3295: PetscCall(MatAssemblyBegin(*submat, MAT_FINAL_ASSEMBLY));
3296: PetscCall(MatAssemblyEnd(*submat, MAT_FINAL_ASSEMBLY));
3298: } else { /* call == MAT_INITIAL_MATRIX) */
3299: PetscInt *garray, *garray_compact;
3300: PetscInt BsubN;
3302: /* Create isrow_d, iscol_d, iscol_o and isgarray (replace isgarray with array?) */
3303: PetscCall(ISGetSeqIS_SameColDist_Private(mat, isrow, iscol, &isrow_d, &iscol_d, &iscol_o, &garray));
3305: /* Create local submatrices Asub and Bsub */
3306: PetscCall(MatCreateSubMatrix_SeqAIJ(a->A, isrow_d, iscol_d, PETSC_DECIDE, MAT_INITIAL_MATRIX, &Asub));
3307: PetscCall(MatCreateSubMatrix_SeqAIJ(a->B, isrow_d, iscol_o, PETSC_DECIDE, MAT_INITIAL_MATRIX, &Bsub));
3309: // Compact garray so its not of size Bn
3310: PetscCall(ISGetSize(iscol_o, &count));
3311: PetscCall(PetscMalloc1(count, &garray_compact));
3312: PetscCall(PetscArraycpy(garray_compact, garray, count));
3314: /* Create submatrix M */
3315: PetscCall(ISGetSize(isrow, &M_size));
3316: PetscCall(ISGetSize(iscol, &N_size));
3317: PetscCall(MatCreateMPIAIJWithSeqAIJ(comm, M_size, N_size, Asub, Bsub, garray_compact, &M));
3319: /* If Bsub has empty columns, compress iscol_o such that it will retrieve condensed Bsub from a->B during reuse */
3320: asub = (Mat_MPIAIJ *)M->data;
3322: PetscCall(ISGetLocalSize(iscol_o, &BsubN));
3323: n = asub->B->cmap->N;
3324: if (BsubN > n) {
3325: /* This case can be tested using ~petsc/src/tao/bound/tutorials/runplate2_3 */
3326: const PetscInt *idx;
3327: PetscInt i, j, *idx_new, *subgarray = asub->garray;
3328: PetscCall(PetscInfo(M, "submatrix Bn %" PetscInt_FMT " != BsubN %" PetscInt_FMT ", update iscol_o\n", n, BsubN));
3330: PetscCall(PetscMalloc1(n, &idx_new));
3331: j = 0;
3332: PetscCall(ISGetIndices(iscol_o, &idx));
3333: for (i = 0; i < n; i++) {
3334: if (j >= BsubN) break;
3335: while (subgarray[i] > garray[j]) j++;
3337: PetscCheck(subgarray[i] == garray[j], PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "subgarray[%" PetscInt_FMT "]=%" PetscInt_FMT " cannot < garray[%" PetscInt_FMT "]=%" PetscInt_FMT, i, subgarray[i], j, garray[j]);
3338: idx_new[i] = idx[j++];
3339: }
3340: PetscCall(ISRestoreIndices(iscol_o, &idx));
3342: PetscCall(ISDestroy(&iscol_o));
3343: PetscCall(ISCreateGeneral(PETSC_COMM_SELF, n, idx_new, PETSC_OWN_POINTER, &iscol_o));
3345: } else PetscCheck(BsubN >= n, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Columns of Bsub (%" PetscInt_FMT ") cannot be smaller than B's (%" PetscInt_FMT ")", BsubN, asub->B->cmap->N);
3347: PetscCall(PetscFree(garray));
3348: *submat = M;
3350: /* Save isrow_d, iscol_d and iscol_o used in processor for next request */
3351: PetscCall(PetscObjectCompose((PetscObject)M, "isrow_d", (PetscObject)isrow_d));
3352: PetscCall(ISDestroy(&isrow_d));
3354: PetscCall(PetscObjectCompose((PetscObject)M, "iscol_d", (PetscObject)iscol_d));
3355: PetscCall(ISDestroy(&iscol_d));
3357: PetscCall(PetscObjectCompose((PetscObject)M, "iscol_o", (PetscObject)iscol_o));
3358: PetscCall(ISDestroy(&iscol_o));
3359: }
3360: PetscFunctionReturn(PETSC_SUCCESS);
3361: }
3363: PetscErrorCode MatCreateSubMatrix_MPIAIJ(Mat mat, IS isrow, IS iscol, MatReuse call, Mat *newmat)
3364: {
3365: IS iscol_local = NULL, isrow_d;
3366: PetscInt csize;
3367: PetscInt n, i, j, start, end;
3368: PetscBool sameRowDist = PETSC_FALSE, sameDist[2], tsameDist[2];
3369: MPI_Comm comm;
3371: PetscFunctionBegin;
3372: /* If isrow has same processor distribution as mat,
3373: call MatCreateSubMatrix_MPIAIJ_SameRowDist() to avoid using a hash table with global size of iscol */
3374: if (call == MAT_REUSE_MATRIX) {
3375: PetscCall(PetscObjectQuery((PetscObject)*newmat, "isrow_d", (PetscObject *)&isrow_d));
3376: if (isrow_d) {
3377: sameRowDist = PETSC_TRUE;
3378: tsameDist[1] = PETSC_TRUE; /* sameColDist */
3379: } else {
3380: PetscCall(PetscObjectQuery((PetscObject)*newmat, "SubIScol", (PetscObject *)&iscol_local));
3381: if (iscol_local) {
3382: sameRowDist = PETSC_TRUE;
3383: tsameDist[1] = PETSC_FALSE; /* !sameColDist */
3384: }
3385: }
3386: } else {
3387: /* Check if isrow has same processor distribution as mat */
3388: sameDist[0] = PETSC_FALSE;
3389: PetscCall(ISGetLocalSize(isrow, &n));
3390: if (!n) {
3391: sameDist[0] = PETSC_TRUE;
3392: } else {
3393: PetscCall(ISGetMinMax(isrow, &i, &j));
3394: PetscCall(MatGetOwnershipRange(mat, &start, &end));
3395: if (i >= start && j < end) sameDist[0] = PETSC_TRUE;
3396: }
3398: /* Check if iscol has same processor distribution as mat */
3399: sameDist[1] = PETSC_FALSE;
3400: PetscCall(ISGetLocalSize(iscol, &n));
3401: if (!n) {
3402: sameDist[1] = PETSC_TRUE;
3403: } else {
3404: PetscCall(ISGetMinMax(iscol, &i, &j));
3405: PetscCall(MatGetOwnershipRangeColumn(mat, &start, &end));
3406: if (i >= start && j < end) sameDist[1] = PETSC_TRUE;
3407: }
3409: PetscCall(PetscObjectGetComm((PetscObject)mat, &comm));
3410: PetscCallMPI(MPIU_Allreduce(&sameDist, &tsameDist, 2, MPI_C_BOOL, MPI_LAND, comm));
3411: sameRowDist = tsameDist[0];
3412: }
3414: if (sameRowDist) {
3415: if (tsameDist[1]) { /* sameRowDist & sameColDist */
3416: /* isrow and iscol have same processor distribution as mat */
3417: PetscCall(MatCreateSubMatrix_MPIAIJ_SameRowColDist(mat, isrow, iscol, call, newmat));
3418: PetscFunctionReturn(PETSC_SUCCESS);
3419: } else { /* sameRowDist */
3420: /* isrow has same processor distribution as mat */
3421: if (call == MAT_INITIAL_MATRIX) {
3422: PetscBool sorted;
3423: PetscCall(ISGetSeqIS_Private(mat, iscol, &iscol_local));
3424: PetscCall(ISGetLocalSize(iscol_local, &n)); /* local size of iscol_local = global columns of newmat */
3425: PetscCall(ISGetSize(iscol, &i));
3426: PetscCheck(n == i, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "n %" PetscInt_FMT " != size of iscol %" PetscInt_FMT, n, i);
3428: PetscCall(ISSorted(iscol_local, &sorted));
3429: if (sorted) {
3430: /* MatCreateSubMatrix_MPIAIJ_SameRowDist() requires iscol_local be sorted; it can have duplicate indices */
3431: PetscCall(MatCreateSubMatrix_MPIAIJ_SameRowDist(mat, isrow, iscol, iscol_local, MAT_INITIAL_MATRIX, newmat));
3432: PetscFunctionReturn(PETSC_SUCCESS);
3433: }
3434: } else { /* call == MAT_REUSE_MATRIX */
3435: IS iscol_sub;
3436: PetscCall(PetscObjectQuery((PetscObject)*newmat, "SubIScol", (PetscObject *)&iscol_sub));
3437: if (iscol_sub) {
3438: PetscCall(MatCreateSubMatrix_MPIAIJ_SameRowDist(mat, isrow, iscol, NULL, call, newmat));
3439: PetscFunctionReturn(PETSC_SUCCESS);
3440: }
3441: }
3442: }
3443: }
3445: /* General case: iscol -> iscol_local which has global size of iscol */
3446: if (call == MAT_REUSE_MATRIX) {
3447: PetscCall(PetscObjectQuery((PetscObject)*newmat, "ISAllGather", (PetscObject *)&iscol_local));
3448: PetscCheck(iscol_local, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Submatrix passed in was not used before, cannot reuse");
3449: } else {
3450: if (!iscol_local) PetscCall(ISGetSeqIS_Private(mat, iscol, &iscol_local));
3451: }
3453: PetscCall(ISGetLocalSize(iscol, &csize));
3454: PetscCall(MatCreateSubMatrix_MPIAIJ_nonscalable(mat, isrow, iscol_local, csize, call, newmat));
3456: if (call == MAT_INITIAL_MATRIX) {
3457: PetscCall(PetscObjectCompose((PetscObject)*newmat, "ISAllGather", (PetscObject)iscol_local));
3458: PetscCall(ISDestroy(&iscol_local));
3459: }
3460: PetscFunctionReturn(PETSC_SUCCESS);
3461: }
3463: /*@C
3464: MatCreateMPIAIJWithSeqAIJ - creates a `MATMPIAIJ` matrix using `MATSEQAIJ` matrices that contain the "diagonal"
3465: and "off-diagonal" part of the matrix in CSR format.
3467: Collective
3469: Input Parameters:
3470: + comm - MPI communicator
3471: . M - the global row size
3472: . N - the global column size
3473: . A - "diagonal" portion of matrix
3474: . B - if garray is `NULL`, B should be the offdiag matrix using global col ids and of size N - if garray is not `NULL`, B should be the offdiag matrix using local col ids and of size garray
3475: - garray - either `NULL` or the global index of `B` columns. If not `NULL`, it should be allocated by `PetscMalloc1()` and will be owned by `mat` thereafter.
3477: Output Parameter:
3478: . mat - the matrix, with input `A` as its local diagonal matrix
3480: Level: advanced
3482: Notes:
3483: See `MatCreateAIJ()` for the definition of "diagonal" and "off-diagonal" portion of the matrix.
3485: `A` and `B` becomes part of output mat. The user cannot use `A` and `B` anymore.
3487: If `garray` is `NULL`, `B` will be compacted to use local indices. In this sense, `B`'s sparsity pattern (nonzerostate) will be changed. If `B` is a device matrix, we need to somehow also update
3488: `B`'s copy on device. We do so by increasing `B`'s nonzerostate. In use of `B` on device, device matrix types should detect this change (ref. internal routines `MatSeqAIJCUSPARSECopyToGPU()` or
3489: `MatAssemblyEnd_SeqAIJKokkos()`) and will just destroy and then recreate the device copy of `B`. It is not optimal, but is easy to implement and less hacky. To avoid this overhead, try to compute `garray`
3490: yourself, see algorithms in the private function `MatSetUpMultiply_MPIAIJ()`.
3492: The `NULL`-ness of `garray` doesn't need to be collective, in other words, `garray` can be `NULL` on some processes while not on others.
3494: .seealso: [](ch_matrices), `Mat`, `MATMPIAIJ`, `MATSEQAIJ`, `MatCreateMPIAIJWithSplitArrays()`
3495: @*/
3496: PetscErrorCode MatCreateMPIAIJWithSeqAIJ(MPI_Comm comm, PetscInt M, PetscInt N, Mat A, Mat B, PetscInt *garray, Mat *mat)
3497: {
3498: PetscInt m, n;
3499: MatType mpi_mat_type;
3500: Mat_MPIAIJ *mpiaij;
3501: Mat C;
3503: PetscFunctionBegin;
3504: PetscCall(MatCreate(comm, &C));
3505: PetscCall(MatGetSize(A, &m, &n));
3506: PetscCheck(m == B->rmap->N, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Am %" PetscInt_FMT " != Bm %" PetscInt_FMT, m, B->rmap->N);
3507: PetscCheck(A->rmap->bs == B->rmap->bs, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "A row bs %" PetscInt_FMT " != B row bs %" PetscInt_FMT, A->rmap->bs, B->rmap->bs);
3509: PetscCall(MatSetSizes(C, m, n, M, N));
3510: /* Determine the type of MPI matrix that should be created from the type of matrix A, which holds the "diagonal" portion. */
3511: PetscCall(MatGetMPIMatType_Private(A, &mpi_mat_type));
3512: PetscCall(MatSetType(C, mpi_mat_type));
3513: if (!garray) {
3514: const PetscScalar *ba;
3516: B->nonzerostate++;
3517: PetscCall(MatSeqAIJGetArrayRead(B, &ba)); /* Since we will destroy B's device copy, we need to make sure the host copy is up to date */
3518: PetscCall(MatSeqAIJRestoreArrayRead(B, &ba));
3519: }
3521: PetscCall(MatSetBlockSizes(C, A->rmap->bs, A->cmap->bs));
3522: PetscCall(PetscLayoutSetUp(C->rmap));
3523: PetscCall(PetscLayoutSetUp(C->cmap));
3525: mpiaij = (Mat_MPIAIJ *)C->data;
3526: mpiaij->A = A;
3527: mpiaij->B = B;
3528: mpiaij->garray = garray;
3529: C->preallocated = PETSC_TRUE;
3530: C->nooffprocentries = PETSC_TRUE; /* See MatAssemblyBegin_MPIAIJ. In effect, making MatAssemblyBegin a nop */
3532: PetscCall(MatSetOption(C, MAT_NO_OFF_PROC_ENTRIES, PETSC_TRUE));
3533: PetscCall(MatAssemblyBegin(C, MAT_FINAL_ASSEMBLY));
3534: /* MatAssemblyEnd is critical here. It sets mat->offloadmask according to A and B's, and
3535: also gets mpiaij->B compacted (if garray is NULL), with its col ids and size reduced
3536: */
3537: PetscCall(MatAssemblyEnd(C, MAT_FINAL_ASSEMBLY));
3538: PetscCall(MatSetOption(C, MAT_NO_OFF_PROC_ENTRIES, PETSC_FALSE));
3539: PetscCall(MatSetOption(C, MAT_NEW_NONZERO_LOCATION_ERR, PETSC_TRUE));
3540: *mat = C;
3541: PetscFunctionReturn(PETSC_SUCCESS);
3542: }
3544: extern PetscErrorCode MatCreateSubMatrices_MPIAIJ_SingleIS_Local(Mat, PetscInt, const IS[], const IS[], MatReuse, PetscBool, Mat *);
3546: PetscErrorCode MatCreateSubMatrix_MPIAIJ_SameRowDist(Mat mat, IS isrow, IS iscol, IS iscol_local, MatReuse call, Mat *newmat)
3547: {
3548: PetscInt i, m, n, rstart, row, rend, nz, j, bs, cbs;
3549: PetscInt *ii, *jj, nlocal, *dlens, *olens, dlen, olen, jend, mglobal;
3550: Mat_MPIAIJ *a = (Mat_MPIAIJ *)mat->data;
3551: Mat M, Msub, B = a->B;
3552: MatScalar *aa;
3553: Mat_SeqAIJ *aij;
3554: PetscInt *garray = a->garray, *colsub, Ncols;
3555: PetscInt count, Bn = B->cmap->N, cstart = mat->cmap->rstart, cend = mat->cmap->rend;
3556: IS iscol_sub, iscmap;
3557: const PetscInt *is_idx, *cmap;
3558: PetscBool allcolumns = PETSC_FALSE;
3559: MPI_Comm comm;
3561: PetscFunctionBegin;
3562: PetscCall(PetscObjectGetComm((PetscObject)mat, &comm));
3563: if (call == MAT_REUSE_MATRIX) {
3564: PetscCall(PetscObjectQuery((PetscObject)*newmat, "SubIScol", (PetscObject *)&iscol_sub));
3565: PetscCheck(iscol_sub, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "SubIScol passed in was not used before, cannot reuse");
3566: PetscCall(ISGetLocalSize(iscol_sub, &count));
3568: PetscCall(PetscObjectQuery((PetscObject)*newmat, "Subcmap", (PetscObject *)&iscmap));
3569: PetscCheck(iscmap, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Subcmap passed in was not used before, cannot reuse");
3571: PetscCall(PetscObjectQuery((PetscObject)*newmat, "SubMatrix", (PetscObject *)&Msub));
3572: PetscCheck(Msub, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Submatrix passed in was not used before, cannot reuse");
3574: PetscCall(MatCreateSubMatrices_MPIAIJ_SingleIS_Local(mat, 1, &isrow, &iscol_sub, MAT_REUSE_MATRIX, PETSC_FALSE, &Msub));
3576: } else { /* call == MAT_INITIAL_MATRIX) */
3577: PetscBool flg;
3579: PetscCall(ISGetLocalSize(iscol, &n));
3580: PetscCall(ISGetSize(iscol, &Ncols));
3582: /* (1) iscol -> nonscalable iscol_local */
3583: /* Check for special case: each processor gets entire matrix columns */
3584: PetscCall(ISIdentity(iscol_local, &flg));
3585: if (flg && n == mat->cmap->N) allcolumns = PETSC_TRUE;
3586: PetscCallMPI(MPIU_Allreduce(MPI_IN_PLACE, &allcolumns, 1, MPI_C_BOOL, MPI_LAND, PetscObjectComm((PetscObject)mat)));
3587: if (allcolumns) {
3588: iscol_sub = iscol_local;
3589: PetscCall(PetscObjectReference((PetscObject)iscol_local));
3590: PetscCall(ISCreateStride(PETSC_COMM_SELF, n, 0, 1, &iscmap));
3592: } else {
3593: /* (2) iscol_local -> iscol_sub and iscmap. Implementation below requires iscol_local be sorted, it can have duplicate indices */
3594: PetscInt *idx, *cmap1, k;
3595: PetscCall(PetscMalloc1(Ncols, &idx));
3596: PetscCall(PetscMalloc1(Ncols, &cmap1));
3597: PetscCall(ISGetIndices(iscol_local, &is_idx));
3598: count = 0;
3599: k = 0;
3600: for (i = 0; i < Ncols; i++) {
3601: j = is_idx[i];
3602: if (j >= cstart && j < cend) {
3603: /* diagonal part of mat */
3604: idx[count] = j;
3605: cmap1[count++] = i; /* column index in submat */
3606: } else if (Bn) {
3607: /* off-diagonal part of mat */
3608: if (j == garray[k]) {
3609: idx[count] = j;
3610: cmap1[count++] = i; /* column index in submat */
3611: } else if (j > garray[k]) {
3612: while (j > garray[k] && k < Bn - 1) k++;
3613: if (j == garray[k]) {
3614: idx[count] = j;
3615: cmap1[count++] = i; /* column index in submat */
3616: }
3617: }
3618: }
3619: }
3620: PetscCall(ISRestoreIndices(iscol_local, &is_idx));
3622: PetscCall(ISCreateGeneral(PETSC_COMM_SELF, count, idx, PETSC_OWN_POINTER, &iscol_sub));
3623: PetscCall(ISGetBlockSize(iscol, &cbs));
3624: PetscCall(ISSetBlockSize(iscol_sub, cbs));
3626: PetscCall(ISCreateGeneral(PetscObjectComm((PetscObject)iscol_local), count, cmap1, PETSC_OWN_POINTER, &iscmap));
3627: }
3629: /* (3) Create sequential Msub */
3630: PetscCall(MatCreateSubMatrices_MPIAIJ_SingleIS_Local(mat, 1, &isrow, &iscol_sub, MAT_INITIAL_MATRIX, allcolumns, &Msub));
3631: }
3633: PetscCall(ISGetLocalSize(iscol_sub, &count));
3634: aij = (Mat_SeqAIJ *)Msub->data;
3635: ii = aij->i;
3636: PetscCall(ISGetIndices(iscmap, &cmap));
3638: /*
3639: m - number of local rows
3640: Ncols - number of columns (same on all processors)
3641: rstart - first row in new global matrix generated
3642: */
3643: PetscCall(MatGetSize(Msub, &m, NULL));
3645: if (call == MAT_INITIAL_MATRIX) {
3646: /* (4) Create parallel newmat */
3647: PetscMPIInt rank, size;
3648: PetscInt csize;
3650: PetscCallMPI(MPI_Comm_size(comm, &size));
3651: PetscCallMPI(MPI_Comm_rank(comm, &rank));
3653: /*
3654: Determine the number of non-zeros in the diagonal and off-diagonal
3655: portions of the matrix in order to do correct preallocation
3656: */
3658: /* first get start and end of "diagonal" columns */
3659: PetscCall(ISGetLocalSize(iscol, &csize));
3660: if (csize == PETSC_DECIDE) {
3661: PetscCall(ISGetSize(isrow, &mglobal));
3662: if (mglobal == Ncols) { /* square matrix */
3663: nlocal = m;
3664: } else {
3665: nlocal = Ncols / size + ((Ncols % size) > rank);
3666: }
3667: } else {
3668: nlocal = csize;
3669: }
3670: PetscCallMPI(MPI_Scan(&nlocal, &rend, 1, MPIU_INT, MPI_SUM, comm));
3671: rstart = rend - nlocal;
3672: PetscCheck(rank != size - 1 || rend == Ncols, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Local column sizes %" PetscInt_FMT " do not add up to total number of columns %" PetscInt_FMT, rend, Ncols);
3674: /* next, compute all the lengths */
3675: jj = aij->j;
3676: PetscCall(PetscMalloc1(2 * m + 1, &dlens));
3677: olens = dlens + m;
3678: for (i = 0; i < m; i++) {
3679: jend = ii[i + 1] - ii[i];
3680: olen = 0;
3681: dlen = 0;
3682: for (j = 0; j < jend; j++) {
3683: if (cmap[*jj] < rstart || cmap[*jj] >= rend) olen++;
3684: else dlen++;
3685: jj++;
3686: }
3687: olens[i] = olen;
3688: dlens[i] = dlen;
3689: }
3691: PetscCall(ISGetBlockSize(isrow, &bs));
3692: PetscCall(ISGetBlockSize(iscol, &cbs));
3694: PetscCall(MatCreate(comm, &M));
3695: PetscCall(MatSetSizes(M, m, nlocal, PETSC_DECIDE, Ncols));
3696: PetscCall(MatSetBlockSizes(M, bs, cbs));
3697: PetscCall(MatSetType(M, ((PetscObject)mat)->type_name));
3698: PetscCall(MatMPIAIJSetPreallocation(M, 0, dlens, 0, olens));
3699: PetscCall(PetscFree(dlens));
3701: } else { /* call == MAT_REUSE_MATRIX */
3702: M = *newmat;
3703: PetscCall(MatGetLocalSize(M, &i, NULL));
3704: PetscCheck(i == m, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Previous matrix must be same size/layout as request");
3705: PetscCall(MatZeroEntries(M));
3706: /*
3707: The next two lines are needed so we may call MatSetValues_MPIAIJ() below directly,
3708: rather than the slower MatSetValues().
3709: */
3710: M->was_assembled = PETSC_TRUE;
3711: M->assembled = PETSC_FALSE;
3712: }
3714: /* (5) Set values of Msub to *newmat */
3715: PetscCall(PetscMalloc1(count, &colsub));
3716: PetscCall(MatGetOwnershipRange(M, &rstart, NULL));
3718: jj = aij->j;
3719: PetscCall(MatSeqAIJGetArrayRead(Msub, (const PetscScalar **)&aa));
3720: for (i = 0; i < m; i++) {
3721: row = rstart + i;
3722: nz = ii[i + 1] - ii[i];
3723: for (j = 0; j < nz; j++) colsub[j] = cmap[jj[j]];
3724: PetscCall(MatSetValues_MPIAIJ(M, 1, &row, nz, colsub, aa, INSERT_VALUES));
3725: jj += nz;
3726: aa += nz;
3727: }
3728: PetscCall(MatSeqAIJRestoreArrayRead(Msub, (const PetscScalar **)&aa));
3729: PetscCall(ISRestoreIndices(iscmap, &cmap));
3731: PetscCall(MatAssemblyBegin(M, MAT_FINAL_ASSEMBLY));
3732: PetscCall(MatAssemblyEnd(M, MAT_FINAL_ASSEMBLY));
3734: PetscCall(PetscFree(colsub));
3736: /* save Msub, iscol_sub and iscmap used in processor for next request */
3737: if (call == MAT_INITIAL_MATRIX) {
3738: *newmat = M;
3739: PetscCall(PetscObjectCompose((PetscObject)*newmat, "SubMatrix", (PetscObject)Msub));
3740: PetscCall(MatDestroy(&Msub));
3742: PetscCall(PetscObjectCompose((PetscObject)*newmat, "SubIScol", (PetscObject)iscol_sub));
3743: PetscCall(ISDestroy(&iscol_sub));
3745: PetscCall(PetscObjectCompose((PetscObject)*newmat, "Subcmap", (PetscObject)iscmap));
3746: PetscCall(ISDestroy(&iscmap));
3748: if (iscol_local) {
3749: PetscCall(PetscObjectCompose((PetscObject)*newmat, "ISAllGather", (PetscObject)iscol_local));
3750: PetscCall(ISDestroy(&iscol_local));
3751: }
3752: }
3753: PetscFunctionReturn(PETSC_SUCCESS);
3754: }
3756: /*
3757: Not great since it makes two copies of the submatrix, first an SeqAIJ
3758: in local and then by concatenating the local matrices the end result.
3759: Writing it directly would be much like MatCreateSubMatrices_MPIAIJ()
3761: This requires a sequential iscol with all indices.
3762: */
3763: PetscErrorCode MatCreateSubMatrix_MPIAIJ_nonscalable(Mat mat, IS isrow, IS iscol, PetscInt csize, MatReuse call, Mat *newmat)
3764: {
3765: PetscMPIInt rank, size;
3766: PetscInt i, m, n, rstart, row, rend, nz, *cwork, j, bs, cbs;
3767: PetscInt *ii, *jj, nlocal, *dlens, *olens, dlen, olen, jend, mglobal;
3768: Mat M, Mreuse;
3769: MatScalar *aa, *vwork;
3770: MPI_Comm comm;
3771: Mat_SeqAIJ *aij;
3772: PetscBool colflag, allcolumns = PETSC_FALSE;
3774: PetscFunctionBegin;
3775: PetscCall(PetscObjectGetComm((PetscObject)mat, &comm));
3776: PetscCallMPI(MPI_Comm_rank(comm, &rank));
3777: PetscCallMPI(MPI_Comm_size(comm, &size));
3779: /* Check for special case: each processor gets entire matrix columns */
3780: PetscCall(ISIdentity(iscol, &colflag));
3781: PetscCall(ISGetLocalSize(iscol, &n));
3782: if (colflag && n == mat->cmap->N) allcolumns = PETSC_TRUE;
3783: PetscCallMPI(MPIU_Allreduce(MPI_IN_PLACE, &allcolumns, 1, MPI_C_BOOL, MPI_LAND, PetscObjectComm((PetscObject)mat)));
3785: if (call == MAT_REUSE_MATRIX) {
3786: PetscCall(PetscObjectQuery((PetscObject)*newmat, "SubMatrix", (PetscObject *)&Mreuse));
3787: PetscCheck(Mreuse, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Submatrix passed in was not used before, cannot reuse");
3788: PetscCall(MatCreateSubMatrices_MPIAIJ_SingleIS_Local(mat, 1, &isrow, &iscol, MAT_REUSE_MATRIX, allcolumns, &Mreuse));
3789: } else {
3790: PetscCall(MatCreateSubMatrices_MPIAIJ_SingleIS_Local(mat, 1, &isrow, &iscol, MAT_INITIAL_MATRIX, allcolumns, &Mreuse));
3791: }
3793: /*
3794: m - number of local rows
3795: n - number of columns (same on all processors)
3796: rstart - first row in new global matrix generated
3797: */
3798: PetscCall(MatGetSize(Mreuse, &m, &n));
3799: PetscCall(MatGetBlockSizes(Mreuse, &bs, &cbs));
3800: if (call == MAT_INITIAL_MATRIX) {
3801: aij = (Mat_SeqAIJ *)Mreuse->data;
3802: ii = aij->i;
3803: jj = aij->j;
3805: /*
3806: Determine the number of non-zeros in the diagonal and off-diagonal
3807: portions of the matrix in order to do correct preallocation
3808: */
3810: /* first get start and end of "diagonal" columns */
3811: if (csize == PETSC_DECIDE) {
3812: PetscCall(ISGetSize(isrow, &mglobal));
3813: if (mglobal == n) { /* square matrix */
3814: nlocal = m;
3815: } else {
3816: nlocal = n / size + ((n % size) > rank);
3817: }
3818: } else {
3819: nlocal = csize;
3820: }
3821: PetscCallMPI(MPI_Scan(&nlocal, &rend, 1, MPIU_INT, MPI_SUM, comm));
3822: rstart = rend - nlocal;
3823: PetscCheck(rank != size - 1 || rend == n, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Local column sizes %" PetscInt_FMT " do not add up to total number of columns %" PetscInt_FMT, rend, n);
3825: /* next, compute all the lengths */
3826: PetscCall(PetscMalloc1(2 * m + 1, &dlens));
3827: olens = dlens + m;
3828: for (i = 0; i < m; i++) {
3829: jend = ii[i + 1] - ii[i];
3830: olen = 0;
3831: dlen = 0;
3832: for (j = 0; j < jend; j++) {
3833: if (*jj < rstart || *jj >= rend) olen++;
3834: else dlen++;
3835: jj++;
3836: }
3837: olens[i] = olen;
3838: dlens[i] = dlen;
3839: }
3840: PetscCall(MatCreate(comm, &M));
3841: PetscCall(MatSetSizes(M, m, nlocal, PETSC_DECIDE, n));
3842: PetscCall(MatSetBlockSizes(M, bs, cbs));
3843: PetscCall(MatSetType(M, ((PetscObject)mat)->type_name));
3844: PetscCall(MatMPIAIJSetPreallocation(M, 0, dlens, 0, olens));
3845: PetscCall(PetscFree(dlens));
3846: } else {
3847: PetscInt ml, nl;
3849: M = *newmat;
3850: PetscCall(MatGetLocalSize(M, &ml, &nl));
3851: PetscCheck(ml == m, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Previous matrix must be same size/layout as request");
3852: PetscCall(MatZeroEntries(M));
3853: /*
3854: The next two lines are needed so we may call MatSetValues_MPIAIJ() below directly,
3855: rather than the slower MatSetValues().
3856: */
3857: M->was_assembled = PETSC_TRUE;
3858: M->assembled = PETSC_FALSE;
3859: }
3860: PetscCall(MatGetOwnershipRange(M, &rstart, &rend));
3861: aij = (Mat_SeqAIJ *)Mreuse->data;
3862: ii = aij->i;
3863: jj = aij->j;
3865: /* trigger copy to CPU if needed */
3866: PetscCall(MatSeqAIJGetArrayRead(Mreuse, (const PetscScalar **)&aa));
3867: for (i = 0; i < m; i++) {
3868: row = rstart + i;
3869: nz = ii[i + 1] - ii[i];
3870: cwork = jj;
3871: jj = PetscSafePointerPlusOffset(jj, nz);
3872: vwork = aa;
3873: aa = PetscSafePointerPlusOffset(aa, nz);
3874: PetscCall(MatSetValues_MPIAIJ(M, 1, &row, nz, cwork, vwork, INSERT_VALUES));
3875: }
3876: PetscCall(MatSeqAIJRestoreArrayRead(Mreuse, (const PetscScalar **)&aa));
3878: PetscCall(MatAssemblyBegin(M, MAT_FINAL_ASSEMBLY));
3879: PetscCall(MatAssemblyEnd(M, MAT_FINAL_ASSEMBLY));
3880: *newmat = M;
3882: /* save submatrix used in processor for next request */
3883: if (call == MAT_INITIAL_MATRIX) {
3884: PetscCall(PetscObjectCompose((PetscObject)M, "SubMatrix", (PetscObject)Mreuse));
3885: PetscCall(MatDestroy(&Mreuse));
3886: }
3887: PetscFunctionReturn(PETSC_SUCCESS);
3888: }
3890: static PetscErrorCode MatMPIAIJSetPreallocationCSR_MPIAIJ(Mat B, const PetscInt Ii[], const PetscInt J[], const PetscScalar v[])
3891: {
3892: PetscInt m, cstart, cend, j, nnz, i, d, *ld;
3893: PetscInt *d_nnz, *o_nnz, nnz_max = 0, rstart, ii, irstart;
3894: const PetscInt *JJ;
3895: PetscBool nooffprocentries;
3896: Mat_MPIAIJ *Aij = (Mat_MPIAIJ *)B->data;
3898: PetscFunctionBegin;
3899: PetscCall(PetscLayoutSetUp(B->rmap));
3900: PetscCall(PetscLayoutSetUp(B->cmap));
3901: m = B->rmap->n;
3902: cstart = B->cmap->rstart;
3903: cend = B->cmap->rend;
3904: rstart = B->rmap->rstart;
3905: irstart = Ii[0];
3907: PetscCall(PetscCalloc2(m, &d_nnz, m, &o_nnz));
3909: if (PetscDefined(USE_DEBUG)) {
3910: for (i = 0; i < m; i++) {
3911: nnz = Ii[i + 1] - Ii[i];
3912: JJ = PetscSafePointerPlusOffset(J, Ii[i] - irstart);
3913: PetscCheck(nnz >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Local row %" PetscInt_FMT " has a negative %" PetscInt_FMT " number of columns", i, nnz);
3914: PetscCheck(!nnz || !(JJ[0] < 0), PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Row %" PetscInt_FMT " starts with negative column index %" PetscInt_FMT, i, JJ[0]);
3915: PetscCheck(!nnz || !(JJ[nnz - 1] >= B->cmap->N), PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Row %" PetscInt_FMT " ends with too large a column index %" PetscInt_FMT " (max allowed %" PetscInt_FMT ")", i, JJ[nnz - 1], B->cmap->N);
3916: }
3917: }
3919: for (i = 0; i < m; i++) {
3920: nnz = Ii[i + 1] - Ii[i];
3921: JJ = PetscSafePointerPlusOffset(J, Ii[i] - irstart);
3922: nnz_max = PetscMax(nnz_max, nnz);
3923: d = 0;
3924: for (j = 0; j < nnz; j++) {
3925: if (cstart <= JJ[j] && JJ[j] < cend) d++;
3926: }
3927: d_nnz[i] = d;
3928: o_nnz[i] = nnz - d;
3929: }
3930: PetscCall(MatMPIAIJSetPreallocation(B, 0, d_nnz, 0, o_nnz));
3931: PetscCall(PetscFree2(d_nnz, o_nnz));
3933: for (i = 0; i < m; i++) {
3934: ii = i + rstart;
3935: PetscCall(MatSetValues_MPIAIJ(B, 1, &ii, Ii[i + 1] - Ii[i], PetscSafePointerPlusOffset(J, Ii[i] - irstart), PetscSafePointerPlusOffset(v, Ii[i] - irstart), INSERT_VALUES));
3936: }
3937: nooffprocentries = B->nooffprocentries;
3938: B->nooffprocentries = PETSC_TRUE;
3939: PetscCall(MatAssemblyBegin(B, MAT_FINAL_ASSEMBLY));
3940: PetscCall(MatAssemblyEnd(B, MAT_FINAL_ASSEMBLY));
3941: B->nooffprocentries = nooffprocentries;
3943: /* count number of entries below block diagonal */
3944: PetscCall(PetscFree(Aij->ld));
3945: PetscCall(PetscCalloc1(m, &ld));
3946: Aij->ld = ld;
3947: for (i = 0; i < m; i++) {
3948: nnz = Ii[i + 1] - Ii[i];
3949: j = 0;
3950: while (j < nnz && J[j] < cstart) j++;
3951: ld[i] = j;
3952: if (J) J += nnz;
3953: }
3955: PetscCall(MatSetOption(B, MAT_NEW_NONZERO_LOCATION_ERR, PETSC_TRUE));
3956: PetscFunctionReturn(PETSC_SUCCESS);
3957: }
3959: /*@
3960: MatMPIAIJSetPreallocationCSR - Allocates memory for a sparse parallel matrix in `MATAIJ` format
3961: (the default parallel PETSc format).
3963: Collective
3965: Input Parameters:
3966: + B - the matrix
3967: . i - the indices into `j` for the start of each local row (indices start with zero)
3968: . j - the column indices for each local row (indices start with zero)
3969: - v - optional values in the matrix
3971: Level: developer
3973: Notes:
3974: The `i`, `j`, and `v` arrays ARE copied by this routine into the internal format used by PETSc;
3975: thus you CANNOT change the matrix entries by changing the values of `v` after you have
3976: called this routine. Use `MatCreateMPIAIJWithSplitArrays()` to avoid needing to copy the arrays.
3978: The `i` and `j` indices are 0 based, and `i` indices are indices corresponding to the local `j` array.
3980: A convenience routine for this functionality is `MatCreateMPIAIJWithArrays()`.
3982: You can update the matrix with new numerical values using `MatUpdateMPIAIJWithArrays()` after this call if the column indices in `j` are sorted.
3984: If you do **not** use `MatUpdateMPIAIJWithArrays()`, the column indices in `j` do not need to be sorted. If you will use
3985: `MatUpdateMPIAIJWithArrays()`, the column indices **must** be sorted.
3987: The format which is used for the sparse matrix input, is equivalent to a
3988: row-major ordering.. i.e for the following matrix, the input data expected is
3989: as shown
3990: .vb
3991: 1 0 0
3992: 2 0 3 P0
3993: -------
3994: 4 5 6 P1
3996: Process0 [P0] rows_owned=[0,1]
3997: i = {0,1,3} [size = nrow+1 = 2+1]
3998: j = {0,0,2} [size = 3]
3999: v = {1,2,3} [size = 3]
4001: Process1 [P1] rows_owned=[2]
4002: i = {0,3} [size = nrow+1 = 1+1]
4003: j = {0,1,2} [size = 3]
4004: v = {4,5,6} [size = 3]
4005: .ve
4007: .seealso: [](ch_matrices), `Mat`, `MATMPIAIJ`, `MatCreate()`, `MatCreateSeqAIJ()`, `MatSetValues()`, `MatMPIAIJSetPreallocation()`, `MatCreateAIJ()`,
4008: `MatCreateSeqAIJWithArrays()`, `MatCreateMPIAIJWithSplitArrays()`, `MatCreateMPIAIJWithArrays()`, `MatSetPreallocationCOO()`, `MatSetValuesCOO()`
4009: @*/
4010: PetscErrorCode MatMPIAIJSetPreallocationCSR(Mat B, const PetscInt i[], const PetscInt j[], const PetscScalar v[])
4011: {
4012: PetscFunctionBegin;
4013: PetscTryMethod(B, "MatMPIAIJSetPreallocationCSR_C", (Mat, const PetscInt[], const PetscInt[], const PetscScalar[]), (B, i, j, v));
4014: PetscFunctionReturn(PETSC_SUCCESS);
4015: }
4017: /*@
4018: MatMPIAIJSetPreallocation - Preallocates memory for a sparse parallel matrix in `MATMPIAIJ` format
4019: (the default parallel PETSc format). For good matrix assembly performance
4020: the user should preallocate the matrix storage by setting the parameters
4021: `d_nz` (or `d_nnz`) and `o_nz` (or `o_nnz`).
4023: Collective
4025: Input Parameters:
4026: + B - the matrix
4027: . d_nz - number of nonzeros per row in DIAGONAL portion of local submatrix
4028: (same value is used for all local rows)
4029: . d_nnz - array containing the number of nonzeros in the various rows of the
4030: DIAGONAL portion of the local submatrix (possibly different for each row)
4031: or `NULL` (`PETSC_NULL_INTEGER` in Fortran), if `d_nz` is used to specify the nonzero structure.
4032: The size of this array is equal to the number of local rows, i.e 'm'.
4033: For matrices that will be factored, you must leave room for (and set)
4034: the diagonal entry even if it is zero.
4035: . o_nz - number of nonzeros per row in the OFF-DIAGONAL portion of local
4036: submatrix (same value is used for all local rows).
4037: - o_nnz - array containing the number of nonzeros in the various rows of the
4038: OFF-DIAGONAL portion of the local submatrix (possibly different for
4039: each row) or `NULL` (`PETSC_NULL_INTEGER` in Fortran), if `o_nz` is used to specify the nonzero
4040: structure. The size of this array is equal to the number
4041: of local rows, i.e 'm'.
4043: Example Usage:
4044: Consider the following 8x8 matrix with 34 non-zero values, that is
4045: assembled across 3 processors. Lets assume that proc0 owns 3 rows,
4046: proc1 owns 3 rows, proc2 owns 2 rows. This division can be shown
4047: as follows
4049: .vb
4050: 1 2 0 | 0 3 0 | 0 4
4051: Proc0 0 5 6 | 7 0 0 | 8 0
4052: 9 0 10 | 11 0 0 | 12 0
4053: -------------------------------------
4054: 13 0 14 | 15 16 17 | 0 0
4055: Proc1 0 18 0 | 19 20 21 | 0 0
4056: 0 0 0 | 22 23 0 | 24 0
4057: -------------------------------------
4058: Proc2 25 26 27 | 0 0 28 | 29 0
4059: 30 0 0 | 31 32 33 | 0 34
4060: .ve
4062: This can be represented as a collection of submatrices as
4063: .vb
4064: A B C
4065: D E F
4066: G H I
4067: .ve
4069: Where the submatrices A,B,C are owned by proc0, D,E,F are
4070: owned by proc1, G,H,I are owned by proc2.
4072: The 'm' parameters for proc0,proc1,proc2 are 3,3,2 respectively.
4073: The 'n' parameters for proc0,proc1,proc2 are 3,3,2 respectively.
4074: The 'M','N' parameters are 8,8, and have the same values on all procs.
4076: The DIAGONAL submatrices corresponding to proc0,proc1,proc2 are
4077: submatrices [A], [E], [I] respectively. The OFF-DIAGONAL submatrices
4078: corresponding to proc0,proc1,proc2 are [BC], [DF], [GH] respectively.
4079: Internally, each processor stores the DIAGONAL part, and the OFF-DIAGONAL
4080: part as `MATSEQAIJ` matrices. For example, proc1 will store [E] as a `MATSEQAIJ`
4081: matrix, and [DF] as another `MATSEQAIJ` matrix.
4083: When `d_nz`, `o_nz` parameters are specified, `d_nz` storage elements are
4084: allocated for every row of the local DIAGONAL submatrix, and `o_nz`
4085: storage locations are allocated for every row of the OFF-DIAGONAL submatrix.
4086: One way to choose `d_nz` and `o_nz` is to use the maximum number of nonzeros over
4087: the local rows for each of the local DIAGONAL, and the OFF-DIAGONAL submatrices.
4088: In this case, the values of `d_nz`, `o_nz` are
4089: .vb
4090: proc0 dnz = 2, o_nz = 2
4091: proc1 dnz = 3, o_nz = 2
4092: proc2 dnz = 1, o_nz = 4
4093: .ve
4094: We are allocating `m`*(`d_nz`+`o_nz`) storage locations for every proc. This
4095: translates to 3*(2+2)=12 for proc0, 3*(3+2)=15 for proc1, 2*(1+4)=10
4096: for proc3. i.e we are using 12+15+10=37 storage locations to store
4097: 34 values.
4099: When `d_nnz`, `o_nnz` parameters are specified, the storage is specified
4100: for every row, corresponding to both DIAGONAL and OFF-DIAGONAL submatrices.
4101: In the above case the values for `d_nnz`, `o_nnz` are
4102: .vb
4103: proc0 d_nnz = [2,2,2] and o_nnz = [2,2,2]
4104: proc1 d_nnz = [3,3,2] and o_nnz = [2,1,1]
4105: proc2 d_nnz = [1,1] and o_nnz = [4,4]
4106: .ve
4107: Here the space allocated is sum of all the above values i.e 34, and
4108: hence pre-allocation is perfect.
4110: Level: intermediate
4112: Notes:
4113: If the *_nnz parameter is given then the *_nz parameter is ignored
4115: The `MATAIJ` format, also called compressed row storage (CSR), is compatible with standard Fortran
4116: storage. The stored row and column indices begin with zero.
4117: See [Sparse Matrices](sec_matsparse) for details.
4119: The parallel matrix is partitioned such that the first m0 rows belong to
4120: process 0, the next m1 rows belong to process 1, the next m2 rows belong
4121: to process 2 etc.. where m0,m1,m2... are the input parameter 'm'.
4123: The DIAGONAL portion of the local submatrix of a processor can be defined
4124: as the submatrix which is obtained by extraction the part corresponding to
4125: the rows r1-r2 and columns c1-c2 of the global matrix, where r1 is the
4126: first row that belongs to the processor, r2 is the last row belonging to
4127: the this processor, and c1-c2 is range of indices of the local part of a
4128: vector suitable for applying the matrix to. This is an mxn matrix. In the
4129: common case of a square matrix, the row and column ranges are the same and
4130: the DIAGONAL part is also square. The remaining portion of the local
4131: submatrix (mxN) constitute the OFF-DIAGONAL portion.
4133: If `o_nnz` and `d_nnz` are specified, then `o_nz` and `d_nz` are ignored.
4135: You can call `MatGetInfo()` to get information on how effective the preallocation was;
4136: for example the fields mallocs,nz_allocated,nz_used,nz_unneeded;
4137: You can also run with the option `-info` and look for messages with the string
4138: malloc in them to see if additional memory allocation was needed.
4140: .seealso: [](ch_matrices), `Mat`, [Sparse Matrices](sec_matsparse), `MATMPIAIJ`, `MATAIJ`, `MatCreate()`, `MatCreateSeqAIJ()`, `MatSetValues()`, `MatCreateAIJ()`, `MatMPIAIJSetPreallocationCSR()`,
4141: `MatGetInfo()`, `PetscSplitOwnership()`, `MatSetPreallocationCOO()`, `MatSetValuesCOO()`
4142: @*/
4143: PetscErrorCode MatMPIAIJSetPreallocation(Mat B, PetscInt d_nz, const PetscInt d_nnz[], PetscInt o_nz, const PetscInt o_nnz[])
4144: {
4145: PetscFunctionBegin;
4148: PetscTryMethod(B, "MatMPIAIJSetPreallocation_C", (Mat, PetscInt, const PetscInt[], PetscInt, const PetscInt[]), (B, d_nz, d_nnz, o_nz, o_nnz));
4149: PetscFunctionReturn(PETSC_SUCCESS);
4150: }
4152: /*@
4153: MatCreateMPIAIJWithArrays - creates a `MATMPIAIJ` matrix using arrays that contain in standard
4154: CSR format for the local rows.
4156: Collective
4158: Input Parameters:
4159: + comm - MPI communicator
4160: . m - number of local rows (Cannot be `PETSC_DECIDE`)
4161: . n - This value should be the same as the local size used in creating the
4162: x vector for the matrix-vector product $ y = Ax$. (or `PETSC_DECIDE` to have
4163: calculated if `N` is given) For square matrices n is almost always `m`.
4164: . M - number of global rows (or `PETSC_DETERMINE` to have calculated if `m` is given)
4165: . N - number of global columns (or `PETSC_DETERMINE` to have calculated if `n` is given)
4166: . i - row indices (of length m+1); that is i[0] = 0, i[row] = i[row-1] + number of elements in that row of the matrix
4167: . j - global column indices
4168: - a - optional matrix values
4170: Output Parameter:
4171: . mat - the matrix
4173: Level: intermediate
4175: Notes:
4176: The `i`, `j`, and `a` arrays ARE copied by this routine into the internal format used by PETSc;
4177: thus you CANNOT change the matrix entries by changing the values of `a[]` after you have
4178: called this routine. Use `MatCreateMPIAIJWithSplitArrays()` to avoid needing to copy the arrays.
4180: The `i` and `j` indices are 0 based, and `i` indices are indices corresponding to the local `j` array.
4182: Once you have created the matrix you can update it with new numerical values using `MatUpdateMPIAIJWithArray()`
4184: If you do **not** use `MatUpdateMPIAIJWithArray()`, the column indices in `j` do not need to be sorted. If you will use
4185: `MatUpdateMPIAIJWithArrays()`, the column indices **must** be sorted.
4187: The format which is used for the sparse matrix input, is equivalent to a
4188: row-major ordering, i.e., for the following matrix, the input data expected is
4189: as shown
4190: .vb
4191: 1 0 0
4192: 2 0 3 P0
4193: -------
4194: 4 5 6 P1
4196: Process0 [P0] rows_owned=[0,1]
4197: i = {0,1,3} [size = nrow+1 = 2+1]
4198: j = {0,0,2} [size = 3]
4199: v = {1,2,3} [size = 3]
4201: Process1 [P1] rows_owned=[2]
4202: i = {0,3} [size = nrow+1 = 1+1]
4203: j = {0,1,2} [size = 3]
4204: v = {4,5,6} [size = 3]
4205: .ve
4207: .seealso: [](ch_matrices), `Mat`, `MatCreate()`, `MatCreateSeqAIJ()`, `MatSetValues()`, `MatMPIAIJSetPreallocation()`, `MatMPIAIJSetPreallocationCSR()`,
4208: `MATMPIAIJ`, `MatCreateAIJ()`, `MatCreateMPIAIJWithSplitArrays()`, `MatUpdateMPIAIJWithArray()`, `MatSetPreallocationCOO()`, `MatSetValuesCOO()`
4209: @*/
4210: PetscErrorCode MatCreateMPIAIJWithArrays(MPI_Comm comm, PetscInt m, PetscInt n, PetscInt M, PetscInt N, const PetscInt i[], const PetscInt j[], const PetscScalar a[], Mat *mat)
4211: {
4212: PetscFunctionBegin;
4213: PetscCheck(!i || !i[0], PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "i (row indices) must start with 0");
4214: PetscCheck(m >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "local number of rows (m) cannot be PETSC_DECIDE, or negative");
4215: PetscCall(MatCreate(comm, mat));
4216: PetscCall(MatSetSizes(*mat, m, n, M, N));
4217: /* PetscCall(MatSetBlockSizes(M,bs,cbs)); */
4218: PetscCall(MatSetType(*mat, MATMPIAIJ));
4219: PetscCall(MatMPIAIJSetPreallocationCSR(*mat, i, j, a));
4220: PetscFunctionReturn(PETSC_SUCCESS);
4221: }
4223: /*@
4224: MatUpdateMPIAIJWithArrays - updates a `MATMPIAIJ` matrix using arrays that contain in standard
4225: CSR format for the local rows. Only the numerical values are updated the other arrays must be identical to what was passed
4226: from `MatCreateMPIAIJWithArrays()`
4228: Deprecated: Use `MatUpdateMPIAIJWithArray()`
4230: Collective
4232: Input Parameters:
4233: + mat - the matrix
4234: . m - number of local rows (Cannot be `PETSC_DECIDE`)
4235: . n - This value should be the same as the local size used in creating the
4236: x vector for the matrix-vector product y = Ax. (or `PETSC_DECIDE` to have
4237: calculated if N is given) For square matrices n is almost always m.
4238: . M - number of global rows (or `PETSC_DETERMINE` to have calculated if m is given)
4239: . N - number of global columns (or `PETSC_DETERMINE` to have calculated if n is given)
4240: . Ii - row indices; that is Ii[0] = 0, Ii[row] = Ii[row-1] + number of elements in that row of the matrix
4241: . J - column indices
4242: - v - matrix values
4244: Level: deprecated
4246: .seealso: [](ch_matrices), `Mat`, `MATMPIAIJ`, `MatCreate()`, `MatCreateSeqAIJ()`, `MatSetValues()`, `MatMPIAIJSetPreallocation()`, `MatMPIAIJSetPreallocationCSR()`,
4247: `MatCreateAIJ()`, `MatCreateMPIAIJWithSplitArrays()`, `MatUpdateMPIAIJWithArray()`, `MatSetPreallocationCOO()`, `MatSetValuesCOO()`
4248: @*/
4249: PetscErrorCode MatUpdateMPIAIJWithArrays(Mat mat, PetscInt m, PetscInt n, PetscInt M, PetscInt N, const PetscInt Ii[], const PetscInt J[], const PetscScalar v[])
4250: {
4251: PetscInt nnz, i;
4252: PetscBool nooffprocentries;
4253: Mat_MPIAIJ *Aij = (Mat_MPIAIJ *)mat->data;
4254: Mat_SeqAIJ *Ad = (Mat_SeqAIJ *)Aij->A->data;
4255: PetscScalar *ad, *ao;
4256: PetscInt ldi, Iii, md;
4257: const PetscInt *Adi = Ad->i;
4258: PetscInt *ld = Aij->ld;
4260: PetscFunctionBegin;
4261: PetscCheck(Ii[0] == 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "i (row indices) must start with 0");
4262: PetscCheck(m >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "local number of rows (m) cannot be PETSC_DECIDE, or negative");
4263: PetscCheck(m == mat->rmap->n, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Local number of rows cannot change from call to MatUpdateMPIAIJWithArrays()");
4264: PetscCheck(n == mat->cmap->n, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Local number of columns cannot change from call to MatUpdateMPIAIJWithArrays()");
4266: PetscCall(MatSeqAIJGetArrayWrite(Aij->A, &ad));
4267: PetscCall(MatSeqAIJGetArrayWrite(Aij->B, &ao));
4269: for (i = 0; i < m; i++) {
4270: if (PetscDefined(USE_DEBUG)) {
4271: for (PetscInt j = Ii[i] + 1; j < Ii[i + 1]; ++j) {
4272: PetscCheck(J[j] >= J[j - 1], PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Column entry number %" PetscInt_FMT " (actual column %" PetscInt_FMT ") in row %" PetscInt_FMT " is not sorted", j - Ii[i], J[j], i);
4273: PetscCheck(J[j] != J[j - 1], PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Column entry number %" PetscInt_FMT " (actual column %" PetscInt_FMT ") in row %" PetscInt_FMT " is identical to previous entry", j - Ii[i], J[j], i);
4274: }
4275: }
4276: nnz = Ii[i + 1] - Ii[i];
4277: Iii = Ii[i];
4278: ldi = ld[i];
4279: md = Adi[i + 1] - Adi[i];
4280: PetscCall(PetscArraycpy(ao, v + Iii, ldi));
4281: PetscCall(PetscArraycpy(ad, v + Iii + ldi, md));
4282: PetscCall(PetscArraycpy(ao + ldi, v + Iii + ldi + md, nnz - ldi - md));
4283: ad += md;
4284: ao += nnz - md;
4285: }
4286: nooffprocentries = mat->nooffprocentries;
4287: mat->nooffprocentries = PETSC_TRUE;
4288: PetscCall(MatSeqAIJRestoreArrayWrite(Aij->A, &ad));
4289: PetscCall(MatSeqAIJRestoreArrayWrite(Aij->B, &ao));
4290: PetscCall(PetscObjectStateIncrease((PetscObject)Aij->A));
4291: PetscCall(PetscObjectStateIncrease((PetscObject)Aij->B));
4292: PetscCall(PetscObjectStateIncrease((PetscObject)mat));
4293: PetscCall(MatAssemblyBegin(mat, MAT_FINAL_ASSEMBLY));
4294: PetscCall(MatAssemblyEnd(mat, MAT_FINAL_ASSEMBLY));
4295: mat->nooffprocentries = nooffprocentries;
4296: PetscFunctionReturn(PETSC_SUCCESS);
4297: }
4299: /*@
4300: MatUpdateMPIAIJWithArray - updates an `MATMPIAIJ` matrix using an array that contains the nonzero values
4302: Collective
4304: Input Parameters:
4305: + mat - the matrix
4306: - v - matrix values, stored by row
4308: Level: intermediate
4310: Notes:
4311: The matrix must have been obtained with `MatCreateMPIAIJWithArrays()` or `MatMPIAIJSetPreallocationCSR()`
4313: The column indices in the call to `MatCreateMPIAIJWithArrays()` or `MatMPIAIJSetPreallocationCSR()` must have been sorted for this call to work correctly
4315: .seealso: [](ch_matrices), `Mat`, `MatCreate()`, `MatCreateSeqAIJ()`, `MatSetValues()`, `MatMPIAIJSetPreallocation()`, `MatMPIAIJSetPreallocationCSR()`,
4316: `MATMPIAIJ`, `MatCreateAIJ()`, `MatCreateMPIAIJWithSplitArrays()`, `MatUpdateMPIAIJWithArrays()`, `MatSetPreallocationCOO()`, `MatSetValuesCOO()`
4317: @*/
4318: PetscErrorCode MatUpdateMPIAIJWithArray(Mat mat, const PetscScalar v[])
4319: {
4320: PetscInt nnz, i, m;
4321: PetscBool nooffprocentries;
4322: Mat_MPIAIJ *Aij = (Mat_MPIAIJ *)mat->data;
4323: Mat_SeqAIJ *Ad = (Mat_SeqAIJ *)Aij->A->data;
4324: Mat_SeqAIJ *Ao = (Mat_SeqAIJ *)Aij->B->data;
4325: PetscScalar *ad, *ao;
4326: const PetscInt *Adi = Ad->i, *Adj = Ao->i;
4327: PetscInt ldi, Iii, md;
4328: PetscInt *ld = Aij->ld;
4330: PetscFunctionBegin;
4331: m = mat->rmap->n;
4333: PetscCall(MatSeqAIJGetArrayWrite(Aij->A, &ad));
4334: PetscCall(MatSeqAIJGetArrayWrite(Aij->B, &ao));
4335: Iii = 0;
4336: for (i = 0; i < m; i++) {
4337: nnz = Adi[i + 1] - Adi[i] + Adj[i + 1] - Adj[i];
4338: ldi = ld[i];
4339: md = Adi[i + 1] - Adi[i];
4340: PetscCall(PetscArraycpy(ad, v + Iii + ldi, md));
4341: ad += md;
4342: if (ao) {
4343: PetscCall(PetscArraycpy(ao, v + Iii, ldi));
4344: PetscCall(PetscArraycpy(ao + ldi, v + Iii + ldi + md, nnz - ldi - md));
4345: ao += nnz - md;
4346: }
4347: Iii += nnz;
4348: }
4349: nooffprocentries = mat->nooffprocentries;
4350: mat->nooffprocentries = PETSC_TRUE;
4351: PetscCall(MatSeqAIJRestoreArrayWrite(Aij->A, &ad));
4352: PetscCall(MatSeqAIJRestoreArrayWrite(Aij->B, &ao));
4353: PetscCall(PetscObjectStateIncrease((PetscObject)Aij->A));
4354: PetscCall(PetscObjectStateIncrease((PetscObject)Aij->B));
4355: PetscCall(PetscObjectStateIncrease((PetscObject)mat));
4356: PetscCall(MatAssemblyBegin(mat, MAT_FINAL_ASSEMBLY));
4357: PetscCall(MatAssemblyEnd(mat, MAT_FINAL_ASSEMBLY));
4358: mat->nooffprocentries = nooffprocentries;
4359: PetscFunctionReturn(PETSC_SUCCESS);
4360: }
4362: /*@
4363: MatCreateAIJ - Creates a sparse parallel matrix in `MATAIJ` format
4364: (the default parallel PETSc format). For good matrix assembly performance
4365: the user should preallocate the matrix storage by setting the parameters
4366: `d_nz` (or `d_nnz`) and `o_nz` (or `o_nnz`).
4368: Collective
4370: Input Parameters:
4371: + comm - MPI communicator
4372: . m - number of local rows (or `PETSC_DECIDE` to have calculated if M is given)
4373: This value should be the same as the local size used in creating the
4374: y vector for the matrix-vector product y = Ax.
4375: . n - This value should be the same as the local size used in creating the
4376: x vector for the matrix-vector product y = Ax. (or `PETSC_DECIDE` to have
4377: calculated if N is given) For square matrices n is almost always m.
4378: . M - number of global rows (or `PETSC_DETERMINE` to have calculated if m is given)
4379: . N - number of global columns (or `PETSC_DETERMINE` to have calculated if n is given)
4380: . d_nz - number of nonzeros per row in DIAGONAL portion of local submatrix
4381: (same value is used for all local rows)
4382: . d_nnz - array containing the number of nonzeros in the various rows of the
4383: DIAGONAL portion of the local submatrix (possibly different for each row)
4384: or `NULL`, if `d_nz` is used to specify the nonzero structure.
4385: The size of this array is equal to the number of local rows, i.e 'm'.
4386: . o_nz - number of nonzeros per row in the OFF-DIAGONAL portion of local
4387: submatrix (same value is used for all local rows).
4388: - o_nnz - array containing the number of nonzeros in the various rows of the
4389: OFF-DIAGONAL portion of the local submatrix (possibly different for
4390: each row) or `NULL`, if `o_nz` is used to specify the nonzero
4391: structure. The size of this array is equal to the number
4392: of local rows, i.e 'm'.
4394: Output Parameter:
4395: . A - the matrix
4397: Options Database Keys:
4398: + -mat_no_inode - Do not use inodes
4399: . -mat_inode_limit limit - Sets inode limit (max limit=5)
4400: - -matmult_vecscatter_view viewer - View the vecscatter (i.e., communication pattern) used in `MatMult()` of sparse parallel matrices.
4401: See viewer types in manual of `MatView()`. Of them, ascii_matlab, draw or binary cause the `VecScatter`
4402: to be viewed as a matrix. Entry (i,j) is the size of message (in bytes) rank i sends to rank j in one `MatMult()` call.
4404: Level: intermediate
4406: Notes:
4407: It is recommended that one use `MatCreateFromOptions()` or the `MatCreate()`, `MatSetType()` and/or `MatSetFromOptions()`,
4408: MatXXXXSetPreallocation() paradigm instead of this routine directly.
4409: [MatXXXXSetPreallocation() is, for example, `MatSeqAIJSetPreallocation()`]
4411: If the *_nnz parameter is given then the *_nz parameter is ignored
4413: The `m`,`n`,`M`,`N` parameters specify the size of the matrix, and its partitioning across
4414: processors, while `d_nz`,`d_nnz`,`o_nz`,`o_nnz` parameters specify the approximate
4415: storage requirements for this matrix.
4417: If `PETSC_DECIDE` or `PETSC_DETERMINE` is used for a particular argument on one
4418: processor than it must be used on all processors that share the object for
4419: that argument.
4421: If `m` and `n` are not `PETSC_DECIDE`, then the values determine the `PetscLayout` of the matrix and the ranges returned by
4422: `MatGetOwnershipRange()`, `MatGetOwnershipRanges()`, `MatGetOwnershipRangeColumn()`, and `MatGetOwnershipRangesColumn()`.
4424: The user MUST specify either the local or global matrix dimensions
4425: (possibly both).
4427: The parallel matrix is partitioned across processors such that the
4428: first `m0` rows belong to process 0, the next `m1` rows belong to
4429: process 1, the next `m2` rows belong to process 2, etc., where
4430: `m0`, `m1`, `m2`... are the input parameter `m` on each MPI process. I.e., each MPI process stores
4431: values corresponding to [m x N] submatrix.
4433: The columns are logically partitioned with the n0 columns belonging
4434: to 0th partition, the next n1 columns belonging to the next
4435: partition etc.. where n0,n1,n2... are the input parameter 'n'.
4437: The DIAGONAL portion of the local submatrix on any given processor
4438: is the submatrix corresponding to the rows and columns m,n
4439: corresponding to the given processor. i.e diagonal matrix on
4440: process 0 is [m0 x n0], diagonal matrix on process 1 is [m1 x n1]
4441: etc. The remaining portion of the local submatrix [m x (N-n)]
4442: constitute the OFF-DIAGONAL portion. The example below better
4443: illustrates this concept. The two matrices, the DIAGONAL portion and
4444: the OFF-DIAGONAL portion are each stored as `MATSEQAIJ` matrices.
4446: For a square global matrix we define each processor's diagonal portion
4447: to be its local rows and the corresponding columns (a square submatrix);
4448: each processor's off-diagonal portion encompasses the remainder of the
4449: local matrix (a rectangular submatrix).
4451: If `o_nnz`, `d_nnz` are specified, then `o_nz`, and `d_nz` are ignored.
4453: When calling this routine with a single process communicator, a matrix of
4454: type `MATSEQAIJ` is returned. If a matrix of type `MATMPIAIJ` is desired for this
4455: type of communicator, use the construction mechanism
4456: .vb
4457: MatCreate(..., &A);
4458: MatSetType(A, MATMPIAIJ);
4459: MatSetSizes(A, m, n, M, N);
4460: MatMPIAIJSetPreallocation(A, ...);
4461: .ve
4463: By default, this format uses inodes (identical nodes) when possible.
4464: We search for consecutive rows with the same nonzero structure, thereby
4465: reusing matrix information to achieve increased efficiency.
4467: Example Usage:
4468: Consider the following 8x8 matrix with 34 non-zero values, that is
4469: assembled across 3 processors. Lets assume that proc0 owns 3 rows,
4470: proc1 owns 3 rows, proc2 owns 2 rows. This division can be shown
4471: as follows
4473: .vb
4474: 1 2 0 | 0 3 0 | 0 4
4475: Proc0 0 5 6 | 7 0 0 | 8 0
4476: 9 0 10 | 11 0 0 | 12 0
4477: -------------------------------------
4478: 13 0 14 | 15 16 17 | 0 0
4479: Proc1 0 18 0 | 19 20 21 | 0 0
4480: 0 0 0 | 22 23 0 | 24 0
4481: -------------------------------------
4482: Proc2 25 26 27 | 0 0 28 | 29 0
4483: 30 0 0 | 31 32 33 | 0 34
4484: .ve
4486: This can be represented as a collection of submatrices as
4488: .vb
4489: A B C
4490: D E F
4491: G H I
4492: .ve
4494: Where the submatrices A,B,C are owned by proc0, D,E,F are
4495: owned by proc1, G,H,I are owned by proc2.
4497: The 'm' parameters for proc0,proc1,proc2 are 3,3,2 respectively.
4498: The 'n' parameters for proc0,proc1,proc2 are 3,3,2 respectively.
4499: The 'M','N' parameters are 8,8, and have the same values on all procs.
4501: The DIAGONAL submatrices corresponding to proc0,proc1,proc2 are
4502: submatrices [A], [E], [I] respectively. The OFF-DIAGONAL submatrices
4503: corresponding to proc0,proc1,proc2 are [BC], [DF], [GH] respectively.
4504: Internally, each processor stores the DIAGONAL part, and the OFF-DIAGONAL
4505: part as `MATSEQAIJ` matrices. For example, proc1 will store [E] as a `MATSEQAIJ`
4506: matrix, and [DF] as another SeqAIJ matrix.
4508: When `d_nz`, `o_nz` parameters are specified, `d_nz` storage elements are
4509: allocated for every row of the local DIAGONAL submatrix, and `o_nz`
4510: storage locations are allocated for every row of the OFF-DIAGONAL submatrix.
4511: One way to choose `d_nz` and `o_nz` is to use the maximum number of nonzeros over
4512: the local rows for each of the local DIAGONAL, and the OFF-DIAGONAL submatrices.
4513: In this case, the values of `d_nz`,`o_nz` are
4514: .vb
4515: proc0 dnz = 2, o_nz = 2
4516: proc1 dnz = 3, o_nz = 2
4517: proc2 dnz = 1, o_nz = 4
4518: .ve
4519: We are allocating m*(`d_nz`+`o_nz`) storage locations for every proc. This
4520: translates to 3*(2+2)=12 for proc0, 3*(3+2)=15 for proc1, 2*(1+4)=10
4521: for proc3. i.e we are using 12+15+10=37 storage locations to store
4522: 34 values.
4524: When `d_nnz`, `o_nnz` parameters are specified, the storage is specified
4525: for every row, corresponding to both DIAGONAL and OFF-DIAGONAL submatrices.
4526: In the above case the values for d_nnz,o_nnz are
4527: .vb
4528: proc0 d_nnz = [2,2,2] and o_nnz = [2,2,2]
4529: proc1 d_nnz = [3,3,2] and o_nnz = [2,1,1]
4530: proc2 d_nnz = [1,1] and o_nnz = [4,4]
4531: .ve
4532: Here the space allocated is sum of all the above values i.e 34, and
4533: hence pre-allocation is perfect.
4535: .seealso: [](ch_matrices), `Mat`, [Sparse Matrix Creation](sec_matsparse), `MatCreate()`, `MatCreateSeqAIJ()`, `MatSetValues()`, `MatMPIAIJSetPreallocation()`, `MatMPIAIJSetPreallocationCSR()`,
4536: `MATMPIAIJ`, `MatCreateMPIAIJWithArrays()`, `MatGetOwnershipRange()`, `MatGetOwnershipRanges()`, `MatGetOwnershipRangeColumn()`,
4537: `MatGetOwnershipRangesColumn()`, `PetscLayout`
4538: @*/
4539: PetscErrorCode MatCreateAIJ(MPI_Comm comm, PetscInt m, PetscInt n, PetscInt M, PetscInt N, PetscInt d_nz, const PetscInt d_nnz[], PetscInt o_nz, const PetscInt o_nnz[], Mat *A)
4540: {
4541: PetscMPIInt size;
4543: PetscFunctionBegin;
4544: PetscCall(MatCreate(comm, A));
4545: PetscCall(MatSetSizes(*A, m, n, M, N));
4546: PetscCallMPI(MPI_Comm_size(comm, &size));
4547: if (size > 1) {
4548: PetscCall(MatSetType(*A, MATMPIAIJ));
4549: PetscCall(MatMPIAIJSetPreallocation(*A, d_nz, d_nnz, o_nz, o_nnz));
4550: } else {
4551: PetscCall(MatSetType(*A, MATSEQAIJ));
4552: PetscCall(MatSeqAIJSetPreallocation(*A, d_nz, d_nnz));
4553: }
4554: PetscFunctionReturn(PETSC_SUCCESS);
4555: }
4557: /*@C
4558: MatMPIAIJGetSeqAIJ - Returns the local pieces of this distributed matrix
4560: Not Collective
4562: Input Parameter:
4563: . A - The `MATMPIAIJ` matrix
4565: Output Parameters:
4566: + Ad - The local diagonal block as a `MATSEQAIJ` matrix
4567: . Ao - The local off-diagonal block as a `MATSEQAIJ` matrix
4568: - colmap - An array mapping local column numbers of `Ao` to global column numbers of the parallel matrix
4570: Level: intermediate
4572: Note:
4573: The rows in `Ad` and `Ao` are in [0, Nr), where Nr is the number of local rows on this process. The columns
4574: in `Ad` are in [0, Nc) where Nc is the number of local columns. The columns are `Ao` are in [0, Nco), where Nco is
4575: the number of nonzero columns in the local off-diagonal piece of the matrix `A`. The array colmap maps these
4576: local column numbers to global column numbers in the original matrix.
4578: .seealso: [](ch_matrices), `Mat`, `MATMPIAIJ`, `MatMPIAIJGetLocalMat()`, `MatMPIAIJGetLocalMatCondensed()`, `MatCreateAIJ()`, `MATSEQAIJ`
4579: @*/
4580: PetscErrorCode MatMPIAIJGetSeqAIJ(Mat A, Mat *Ad, Mat *Ao, const PetscInt *colmap[])
4581: {
4582: Mat_MPIAIJ *a = (Mat_MPIAIJ *)A->data;
4583: PetscBool flg;
4585: PetscFunctionBegin;
4586: PetscCall(PetscStrbeginswith(((PetscObject)A)->type_name, MATMPIAIJ, &flg));
4587: PetscCheck(flg, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "This function requires a MATMPIAIJ matrix as input");
4588: if (Ad) *Ad = a->A;
4589: if (Ao) *Ao = a->B;
4590: if (colmap) *colmap = a->garray;
4591: PetscFunctionReturn(PETSC_SUCCESS);
4592: }
4594: PetscErrorCode MatCreateMPIMatConcatenateSeqMat_MPIAIJ(MPI_Comm comm, Mat inmat, PetscInt n, MatReuse scall, Mat *outmat)
4595: {
4596: PetscInt m, N, i, rstart, nnz, Ii;
4597: PetscInt *indx;
4598: PetscScalar *values;
4599: MatType rootType;
4601: PetscFunctionBegin;
4602: PetscCall(MatGetSize(inmat, &m, &N));
4603: if (scall == MAT_INITIAL_MATRIX) { /* symbolic phase */
4604: PetscInt *dnz, *onz, sum, bs, cbs;
4606: if (n == PETSC_DECIDE) PetscCall(PetscSplitOwnership(comm, &n, &N));
4607: /* Check sum(n) = N */
4608: PetscCallMPI(MPIU_Allreduce(&n, &sum, 1, MPIU_INT, MPI_SUM, comm));
4609: PetscCheck(sum == N, PETSC_COMM_SELF, PETSC_ERR_ARG_INCOMP, "Sum of local columns %" PetscInt_FMT " != global columns %" PetscInt_FMT, sum, N);
4611: PetscCallMPI(MPI_Scan(&m, &rstart, 1, MPIU_INT, MPI_SUM, comm));
4612: rstart -= m;
4614: MatPreallocateBegin(comm, m, n, dnz, onz);
4615: for (i = 0; i < m; i++) {
4616: PetscCall(MatGetRow_SeqAIJ(inmat, i, &nnz, &indx, NULL));
4617: PetscCall(MatPreallocateSet(i + rstart, nnz, indx, dnz, onz));
4618: PetscCall(MatRestoreRow_SeqAIJ(inmat, i, &nnz, &indx, NULL));
4619: }
4621: PetscCall(MatCreate(comm, outmat));
4622: PetscCall(MatSetSizes(*outmat, m, n, PETSC_DETERMINE, PETSC_DETERMINE));
4623: PetscCall(MatGetBlockSizes(inmat, &bs, &cbs));
4624: PetscCall(MatSetBlockSizes(*outmat, bs, cbs));
4625: PetscCall(MatGetRootType_Private(inmat, &rootType));
4626: PetscCall(MatSetType(*outmat, rootType));
4627: PetscCall(MatSeqAIJSetPreallocation(*outmat, 0, dnz));
4628: PetscCall(MatMPIAIJSetPreallocation(*outmat, 0, dnz, 0, onz));
4629: MatPreallocateEnd(dnz, onz);
4630: PetscCall(MatSetOption(*outmat, MAT_NO_OFF_PROC_ENTRIES, PETSC_TRUE));
4631: }
4633: /* numeric phase */
4634: PetscCall(MatGetOwnershipRange(*outmat, &rstart, NULL));
4635: for (i = 0; i < m; i++) {
4636: PetscCall(MatGetRow_SeqAIJ(inmat, i, &nnz, &indx, &values));
4637: Ii = i + rstart;
4638: PetscCall(MatSetValues(*outmat, 1, &Ii, nnz, indx, values, INSERT_VALUES));
4639: PetscCall(MatRestoreRow_SeqAIJ(inmat, i, &nnz, &indx, &values));
4640: }
4641: PetscCall(MatAssemblyBegin(*outmat, MAT_FINAL_ASSEMBLY));
4642: PetscCall(MatAssemblyEnd(*outmat, MAT_FINAL_ASSEMBLY));
4643: PetscFunctionReturn(PETSC_SUCCESS);
4644: }
4646: static PetscErrorCode MatMergeSeqsToMPIDestroy(PetscCtxRt data)
4647: {
4648: MatMergeSeqsToMPI *merge = *(MatMergeSeqsToMPI **)data;
4650: PetscFunctionBegin;
4651: if (!merge) PetscFunctionReturn(PETSC_SUCCESS);
4652: PetscCall(PetscFree(merge->id_r));
4653: PetscCall(PetscFree(merge->len_s));
4654: PetscCall(PetscFree(merge->len_r));
4655: PetscCall(PetscFree(merge->bi));
4656: PetscCall(PetscFree(merge->bj));
4657: PetscCall(PetscFree(merge->buf_ri[0]));
4658: PetscCall(PetscFree(merge->buf_ri));
4659: PetscCall(PetscFree(merge->buf_rj[0]));
4660: PetscCall(PetscFree(merge->buf_rj));
4661: PetscCall(PetscFree(merge->coi));
4662: PetscCall(PetscFree(merge->coj));
4663: PetscCall(PetscFree(merge->owners_co));
4664: PetscCall(PetscLayoutDestroy(&merge->rowmap));
4665: PetscCall(PetscFree(merge));
4666: PetscFunctionReturn(PETSC_SUCCESS);
4667: }
4669: #include <../src/mat/utils/freespace.h>
4670: #include <petscbt.h>
4672: PetscErrorCode MatCreateMPIAIJSumSeqAIJNumeric(Mat seqmat, Mat mpimat)
4673: {
4674: MPI_Comm comm;
4675: Mat_SeqAIJ *a = (Mat_SeqAIJ *)seqmat->data;
4676: PetscMPIInt size, rank, taga, *len_s;
4677: PetscInt N = mpimat->cmap->N, i, j, *owners, *ai = a->i, *aj, m;
4678: PetscMPIInt proc, k;
4679: PetscInt **buf_ri, **buf_rj;
4680: PetscInt anzi, *bj_i, *bi, *bj, arow, bnzi, nextaj;
4681: PetscInt nrows, **buf_ri_k, **nextrow, **nextai;
4682: MPI_Request *s_waits, *r_waits;
4683: MPI_Status *status;
4684: const MatScalar *aa, *a_a;
4685: MatScalar **abuf_r, *ba_i;
4686: MatMergeSeqsToMPI *merge;
4687: PetscContainer container;
4689: PetscFunctionBegin;
4690: PetscCall(PetscObjectGetComm((PetscObject)mpimat, &comm));
4691: PetscCall(PetscLogEventBegin(MAT_Seqstompinum, seqmat, 0, 0, 0));
4693: PetscCallMPI(MPI_Comm_size(comm, &size));
4694: PetscCallMPI(MPI_Comm_rank(comm, &rank));
4696: PetscCall(PetscObjectQuery((PetscObject)mpimat, "MatMergeSeqsToMPI", (PetscObject *)&container));
4697: PetscCheck(container, PetscObjectComm((PetscObject)mpimat), PETSC_ERR_PLIB, "Mat not created from MatCreateMPIAIJSumSeqAIJSymbolic");
4698: PetscCall(PetscContainerGetPointer(container, &merge));
4699: PetscCall(MatSeqAIJGetArrayRead(seqmat, &a_a));
4700: aa = a_a;
4702: bi = merge->bi;
4703: bj = merge->bj;
4704: buf_ri = merge->buf_ri;
4705: buf_rj = merge->buf_rj;
4707: PetscCall(PetscMalloc1(size, &status));
4708: owners = merge->rowmap->range;
4709: len_s = merge->len_s;
4711: /* send and recv matrix values */
4712: PetscCall(PetscObjectGetNewTag((PetscObject)mpimat, &taga));
4713: PetscCall(PetscPostIrecvScalar(comm, taga, merge->nrecv, merge->id_r, merge->len_r, &abuf_r, &r_waits));
4715: PetscCall(PetscMalloc1(merge->nsend + 1, &s_waits));
4716: for (proc = 0, k = 0; proc < size; proc++) {
4717: if (!len_s[proc]) continue;
4718: i = owners[proc];
4719: PetscCallMPI(MPIU_Isend(aa + ai[i], len_s[proc], MPIU_MATSCALAR, proc, taga, comm, s_waits + k));
4720: k++;
4721: }
4723: if (merge->nrecv) PetscCallMPI(MPI_Waitall(merge->nrecv, r_waits, status));
4724: if (merge->nsend) PetscCallMPI(MPI_Waitall(merge->nsend, s_waits, status));
4725: PetscCall(PetscFree(status));
4727: PetscCall(PetscFree(s_waits));
4728: PetscCall(PetscFree(r_waits));
4730: /* insert mat values of mpimat */
4731: PetscCall(PetscMalloc1(N, &ba_i));
4732: PetscCall(PetscMalloc3(merge->nrecv, &buf_ri_k, merge->nrecv, &nextrow, merge->nrecv, &nextai));
4734: for (k = 0; k < merge->nrecv; k++) {
4735: buf_ri_k[k] = buf_ri[k]; /* beginning of k-th recved i-structure */
4736: nrows = *buf_ri_k[k];
4737: nextrow[k] = buf_ri_k[k] + 1; /* next row number of k-th recved i-structure */
4738: nextai[k] = buf_ri_k[k] + (nrows + 1); /* points to the next i-structure of k-th recved i-structure */
4739: }
4741: /* set values of ba */
4742: m = merge->rowmap->n;
4743: for (i = 0; i < m; i++) {
4744: arow = owners[rank] + i;
4745: bj_i = bj + bi[i]; /* col indices of the i-th row of mpimat */
4746: bnzi = bi[i + 1] - bi[i];
4747: PetscCall(PetscArrayzero(ba_i, bnzi));
4749: /* add local non-zero vals of this proc's seqmat into ba */
4750: anzi = ai[arow + 1] - ai[arow];
4751: aj = a->j + ai[arow];
4752: aa = a_a + ai[arow];
4753: nextaj = 0;
4754: for (j = 0; nextaj < anzi; j++) {
4755: if (*(bj_i + j) == aj[nextaj]) { /* bcol == acol */
4756: ba_i[j] += aa[nextaj++];
4757: }
4758: }
4760: /* add received vals into ba */
4761: for (k = 0; k < merge->nrecv; k++) { /* k-th received message */
4762: /* i-th row */
4763: if (i == *nextrow[k]) {
4764: anzi = *(nextai[k] + 1) - *nextai[k];
4765: aj = buf_rj[k] + *nextai[k];
4766: aa = abuf_r[k] + *nextai[k];
4767: nextaj = 0;
4768: for (j = 0; nextaj < anzi; j++) {
4769: if (*(bj_i + j) == aj[nextaj]) { /* bcol == acol */
4770: ba_i[j] += aa[nextaj++];
4771: }
4772: }
4773: nextrow[k]++;
4774: nextai[k]++;
4775: }
4776: }
4777: PetscCall(MatSetValues(mpimat, 1, &arow, bnzi, bj_i, ba_i, INSERT_VALUES));
4778: }
4779: PetscCall(MatSeqAIJRestoreArrayRead(seqmat, &a_a));
4780: PetscCall(MatAssemblyBegin(mpimat, MAT_FINAL_ASSEMBLY));
4781: PetscCall(MatAssemblyEnd(mpimat, MAT_FINAL_ASSEMBLY));
4783: PetscCall(PetscFree(abuf_r[0]));
4784: PetscCall(PetscFree(abuf_r));
4785: PetscCall(PetscFree(ba_i));
4786: PetscCall(PetscFree3(buf_ri_k, nextrow, nextai));
4787: PetscCall(PetscLogEventEnd(MAT_Seqstompinum, seqmat, 0, 0, 0));
4788: PetscFunctionReturn(PETSC_SUCCESS);
4789: }
4791: PetscErrorCode MatCreateMPIAIJSumSeqAIJSymbolic(MPI_Comm comm, Mat seqmat, PetscInt m, PetscInt n, Mat *mpimat)
4792: {
4793: Mat B_mpi;
4794: Mat_SeqAIJ *a = (Mat_SeqAIJ *)seqmat->data;
4795: PetscMPIInt size, rank, tagi, tagj, *len_s, *len_si, *len_ri;
4796: PetscInt **buf_rj, **buf_ri, **buf_ri_k;
4797: PetscInt M = seqmat->rmap->n, N = seqmat->cmap->n, i, *owners, *ai = a->i, *aj = a->j;
4798: PetscInt len, *dnz, *onz, bs, cbs;
4799: PetscInt k, anzi, *bi, *bj, *lnk, nlnk, arow, bnzi;
4800: PetscInt nrows, *buf_s, *buf_si, *buf_si_i, **nextrow, **nextai;
4801: MPI_Request *si_waits, *sj_waits, *ri_waits, *rj_waits;
4802: MPI_Status *status;
4803: PetscFreeSpaceList free_space = NULL, current_space = NULL;
4804: PetscBT lnkbt;
4805: MatMergeSeqsToMPI *merge;
4806: PetscContainer container;
4808: PetscFunctionBegin;
4809: PetscCall(PetscLogEventBegin(MAT_Seqstompisym, seqmat, 0, 0, 0));
4811: /* make sure it is a PETSc comm */
4812: PetscCall(PetscCommDuplicate(comm, &comm, NULL));
4813: PetscCallMPI(MPI_Comm_size(comm, &size));
4814: PetscCallMPI(MPI_Comm_rank(comm, &rank));
4816: PetscCall(PetscNew(&merge));
4817: PetscCall(PetscMalloc1(size, &status));
4819: /* determine row ownership */
4820: PetscCall(PetscLayoutCreate(comm, &merge->rowmap));
4821: PetscCall(PetscLayoutSetLocalSize(merge->rowmap, m));
4822: PetscCall(PetscLayoutSetSize(merge->rowmap, M));
4823: PetscCall(PetscLayoutSetBlockSize(merge->rowmap, 1));
4824: PetscCall(PetscLayoutSetUp(merge->rowmap));
4825: PetscCall(PetscMalloc1(size, &len_si));
4826: PetscCall(PetscMalloc1(size, &merge->len_s));
4828: m = merge->rowmap->n;
4829: owners = merge->rowmap->range;
4831: /* determine the number of messages to send, their lengths */
4832: len_s = merge->len_s;
4834: len = 0; /* length of buf_si[] */
4835: merge->nsend = 0;
4836: for (PetscMPIInt proc = 0; proc < size; proc++) {
4837: len_si[proc] = 0;
4838: if (proc == rank) {
4839: len_s[proc] = 0;
4840: } else {
4841: PetscCall(PetscMPIIntCast(owners[proc + 1] - owners[proc] + 1, &len_si[proc]));
4842: PetscCall(PetscMPIIntCast(ai[owners[proc + 1]] - ai[owners[proc]], &len_s[proc])); /* num of rows to be sent to [proc] */
4843: }
4844: if (len_s[proc]) {
4845: merge->nsend++;
4846: nrows = 0;
4847: for (i = owners[proc]; i < owners[proc + 1]; i++) {
4848: if (ai[i + 1] > ai[i]) nrows++;
4849: }
4850: PetscCall(PetscMPIIntCast(2 * (nrows + 1), &len_si[proc]));
4851: len += len_si[proc];
4852: }
4853: }
4855: /* determine the number and length of messages to receive for ij-structure */
4856: PetscCall(PetscGatherNumberOfMessages(comm, NULL, len_s, &merge->nrecv));
4857: PetscCall(PetscGatherMessageLengths2(comm, merge->nsend, merge->nrecv, len_s, len_si, &merge->id_r, &merge->len_r, &len_ri));
4859: /* post the Irecv of j-structure */
4860: PetscCall(PetscCommGetNewTag(comm, &tagj));
4861: PetscCall(PetscPostIrecvInt(comm, tagj, merge->nrecv, merge->id_r, merge->len_r, &buf_rj, &rj_waits));
4863: /* post the Isend of j-structure */
4864: PetscCall(PetscMalloc2(merge->nsend, &si_waits, merge->nsend, &sj_waits));
4866: for (PetscMPIInt proc = 0, k = 0; proc < size; proc++) {
4867: if (!len_s[proc]) continue;
4868: i = owners[proc];
4869: PetscCallMPI(MPIU_Isend(aj + ai[i], len_s[proc], MPIU_INT, proc, tagj, comm, sj_waits + k));
4870: k++;
4871: }
4873: /* receives and sends of j-structure are complete */
4874: if (merge->nrecv) PetscCallMPI(MPI_Waitall(merge->nrecv, rj_waits, status));
4875: if (merge->nsend) PetscCallMPI(MPI_Waitall(merge->nsend, sj_waits, status));
4877: /* send and recv i-structure */
4878: PetscCall(PetscCommGetNewTag(comm, &tagi));
4879: PetscCall(PetscPostIrecvInt(comm, tagi, merge->nrecv, merge->id_r, len_ri, &buf_ri, &ri_waits));
4881: PetscCall(PetscMalloc1(len + 1, &buf_s));
4882: buf_si = buf_s; /* points to the beginning of k-th msg to be sent */
4883: for (PetscMPIInt proc = 0, k = 0; proc < size; proc++) {
4884: if (!len_s[proc]) continue;
4885: /* form outgoing message for i-structure:
4886: buf_si[0]: nrows to be sent
4887: [1:nrows]: row index (global)
4888: [nrows+1:2*nrows+1]: i-structure index
4889: */
4890: nrows = len_si[proc] / 2 - 1;
4891: buf_si_i = buf_si + nrows + 1;
4892: buf_si[0] = nrows;
4893: buf_si_i[0] = 0;
4894: nrows = 0;
4895: for (i = owners[proc]; i < owners[proc + 1]; i++) {
4896: anzi = ai[i + 1] - ai[i];
4897: if (anzi) {
4898: buf_si_i[nrows + 1] = buf_si_i[nrows] + anzi; /* i-structure */
4899: buf_si[nrows + 1] = i - owners[proc]; /* local row index */
4900: nrows++;
4901: }
4902: }
4903: PetscCallMPI(MPIU_Isend(buf_si, len_si[proc], MPIU_INT, proc, tagi, comm, si_waits + k));
4904: k++;
4905: buf_si += len_si[proc];
4906: }
4908: if (merge->nrecv) PetscCallMPI(MPI_Waitall(merge->nrecv, ri_waits, status));
4909: if (merge->nsend) PetscCallMPI(MPI_Waitall(merge->nsend, si_waits, status));
4911: PetscCall(PetscInfo(seqmat, "nsend: %d, nrecv: %d\n", merge->nsend, merge->nrecv));
4912: for (i = 0; i < merge->nrecv; i++) PetscCall(PetscInfo(seqmat, "recv len_ri=%d, len_rj=%d from [%d]\n", len_ri[i], merge->len_r[i], merge->id_r[i]));
4914: PetscCall(PetscFree(len_si));
4915: PetscCall(PetscFree(len_ri));
4916: PetscCall(PetscFree(rj_waits));
4917: PetscCall(PetscFree2(si_waits, sj_waits));
4918: PetscCall(PetscFree(ri_waits));
4919: PetscCall(PetscFree(buf_s));
4920: PetscCall(PetscFree(status));
4922: /* compute a local seq matrix in each processor */
4923: /* allocate bi array and free space for accumulating nonzero column info */
4924: PetscCall(PetscMalloc1(m + 1, &bi));
4925: bi[0] = 0;
4927: /* create and initialize a linked list */
4928: nlnk = N + 1;
4929: PetscCall(PetscLLCreate(N, N, nlnk, lnk, lnkbt));
4931: /* initial FreeSpace size is 2*(num of local nnz(seqmat)) */
4932: len = ai[owners[rank + 1]] - ai[owners[rank]];
4933: PetscCall(PetscFreeSpaceGet(PetscIntMultTruncate(2, len) + 1, &free_space));
4935: current_space = free_space;
4937: /* determine symbolic info for each local row */
4938: PetscCall(PetscMalloc3(merge->nrecv, &buf_ri_k, merge->nrecv, &nextrow, merge->nrecv, &nextai));
4940: for (k = 0; k < merge->nrecv; k++) {
4941: buf_ri_k[k] = buf_ri[k]; /* beginning of k-th recved i-structure */
4942: nrows = *buf_ri_k[k];
4943: nextrow[k] = buf_ri_k[k] + 1; /* next row number of k-th recved i-structure */
4944: nextai[k] = buf_ri_k[k] + (nrows + 1); /* points to the next i-structure of k-th recved i-structure */
4945: }
4947: MatPreallocateBegin(comm, m, n, dnz, onz);
4948: len = 0;
4949: for (i = 0; i < m; i++) {
4950: bnzi = 0;
4951: /* add local non-zero cols of this proc's seqmat into lnk */
4952: arow = owners[rank] + i;
4953: anzi = ai[arow + 1] - ai[arow];
4954: aj = a->j + ai[arow];
4955: PetscCall(PetscLLAddSorted(anzi, aj, N, &nlnk, lnk, lnkbt));
4956: bnzi += nlnk;
4957: /* add received col data into lnk */
4958: for (k = 0; k < merge->nrecv; k++) { /* k-th received message */
4959: if (i == *nextrow[k]) { /* i-th row */
4960: anzi = *(nextai[k] + 1) - *nextai[k];
4961: aj = buf_rj[k] + *nextai[k];
4962: PetscCall(PetscLLAddSorted(anzi, aj, N, &nlnk, lnk, lnkbt));
4963: bnzi += nlnk;
4964: nextrow[k]++;
4965: nextai[k]++;
4966: }
4967: }
4968: if (len < bnzi) len = bnzi; /* =max(bnzi) */
4970: /* if free space is not available, make more free space */
4971: if (current_space->local_remaining < bnzi) PetscCall(PetscFreeSpaceGet(PetscIntSumTruncate(bnzi, current_space->total_array_size), ¤t_space));
4972: /* copy data into free space, then initialize lnk */
4973: PetscCall(PetscLLClean(N, N, bnzi, lnk, current_space->array, lnkbt));
4974: PetscCall(MatPreallocateSet(i + owners[rank], bnzi, current_space->array, dnz, onz));
4976: current_space->array += bnzi;
4977: current_space->local_used += bnzi;
4978: current_space->local_remaining -= bnzi;
4980: bi[i + 1] = bi[i] + bnzi;
4981: }
4983: PetscCall(PetscFree3(buf_ri_k, nextrow, nextai));
4985: PetscCall(PetscMalloc1(bi[m], &bj));
4986: PetscCall(PetscFreeSpaceContiguous(&free_space, bj));
4987: PetscCall(PetscLLDestroy(lnk, lnkbt));
4989: /* create symbolic parallel matrix B_mpi */
4990: PetscCall(MatGetBlockSizes(seqmat, &bs, &cbs));
4991: PetscCall(MatCreate(comm, &B_mpi));
4992: if (n == PETSC_DECIDE) PetscCall(MatSetSizes(B_mpi, m, n, PETSC_DETERMINE, N));
4993: else PetscCall(MatSetSizes(B_mpi, m, n, PETSC_DETERMINE, PETSC_DETERMINE));
4994: PetscCall(MatSetBlockSizes(B_mpi, bs, cbs));
4995: PetscCall(MatSetType(B_mpi, MATMPIAIJ));
4996: PetscCall(MatMPIAIJSetPreallocation(B_mpi, 0, dnz, 0, onz));
4997: MatPreallocateEnd(dnz, onz);
4998: PetscCall(MatSetOption(B_mpi, MAT_NEW_NONZERO_ALLOCATION_ERR, PETSC_FALSE));
5000: /* B_mpi is not ready for use - assembly will be done by MatCreateMPIAIJSumSeqAIJNumeric() */
5001: B_mpi->assembled = PETSC_FALSE;
5002: merge->bi = bi;
5003: merge->bj = bj;
5004: merge->buf_ri = buf_ri;
5005: merge->buf_rj = buf_rj;
5006: merge->coi = NULL;
5007: merge->coj = NULL;
5008: merge->owners_co = NULL;
5010: PetscCall(PetscCommDestroy(&comm));
5012: /* attach the supporting struct to B_mpi for reuse */
5013: PetscCall(PetscContainerCreate(PETSC_COMM_SELF, &container));
5014: PetscCall(PetscContainerSetPointer(container, merge));
5015: PetscCall(PetscContainerSetCtxDestroy(container, MatMergeSeqsToMPIDestroy));
5016: PetscCall(PetscObjectCompose((PetscObject)B_mpi, "MatMergeSeqsToMPI", (PetscObject)container));
5017: PetscCall(PetscContainerDestroy(&container));
5018: *mpimat = B_mpi;
5020: PetscCall(PetscLogEventEnd(MAT_Seqstompisym, seqmat, 0, 0, 0));
5021: PetscFunctionReturn(PETSC_SUCCESS);
5022: }
5024: /*@
5025: MatCreateMPIAIJSumSeqAIJ - Creates a `MATMPIAIJ` matrix by adding sequential
5026: matrices from each processor
5028: Collective
5030: Input Parameters:
5031: + comm - the communicators the parallel matrix will live on
5032: . seqmat - the input sequential matrices
5033: . m - number of local rows (or `PETSC_DECIDE`)
5034: . n - number of local columns (or `PETSC_DECIDE`)
5035: - scall - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`
5037: Output Parameter:
5038: . mpimat - the parallel matrix generated
5040: Level: advanced
5042: Note:
5043: The dimensions of the sequential matrix in each processor MUST be the same.
5044: The input seqmat is included into the container `MatMergeSeqsToMPIDestroy`, and will be
5045: destroyed when `mpimat` is destroyed. Call `PetscObjectQuery()` to access `seqmat`.
5047: .seealso: [](ch_matrices), `Mat`, `MatCreateAIJ()`
5048: @*/
5049: PetscErrorCode MatCreateMPIAIJSumSeqAIJ(MPI_Comm comm, Mat seqmat, PetscInt m, PetscInt n, MatReuse scall, Mat *mpimat)
5050: {
5051: PetscMPIInt size;
5053: PetscFunctionBegin;
5054: PetscCallMPI(MPI_Comm_size(comm, &size));
5055: if (size == 1) {
5056: PetscCall(PetscLogEventBegin(MAT_Seqstompi, seqmat, 0, 0, 0));
5057: if (scall == MAT_INITIAL_MATRIX) PetscCall(MatDuplicate(seqmat, MAT_COPY_VALUES, mpimat));
5058: else PetscCall(MatCopy(seqmat, *mpimat, SAME_NONZERO_PATTERN));
5059: PetscCall(PetscLogEventEnd(MAT_Seqstompi, seqmat, 0, 0, 0));
5060: PetscFunctionReturn(PETSC_SUCCESS);
5061: }
5062: PetscCall(PetscLogEventBegin(MAT_Seqstompi, seqmat, 0, 0, 0));
5063: if (scall == MAT_INITIAL_MATRIX) PetscCall(MatCreateMPIAIJSumSeqAIJSymbolic(comm, seqmat, m, n, mpimat));
5064: PetscCall(MatCreateMPIAIJSumSeqAIJNumeric(seqmat, *mpimat));
5065: PetscCall(PetscLogEventEnd(MAT_Seqstompi, seqmat, 0, 0, 0));
5066: PetscFunctionReturn(PETSC_SUCCESS);
5067: }
5069: /*@
5070: MatAIJGetLocalMat - Creates a `MATSEQAIJ` from a `MATAIJ` matrix.
5072: Not Collective
5074: Input Parameter:
5075: . A - the matrix
5077: Output Parameter:
5078: . A_loc - the local sequential matrix generated
5080: Level: developer
5082: Notes:
5083: The matrix is created by taking `A`'s local rows and putting them into a sequential matrix
5084: with `mlocal` rows and `n` columns. Where `mlocal` is obtained with `MatGetLocalSize()` and
5085: `n` is the global column count obtained with `MatGetSize()`
5087: In other words combines the two parts of a parallel `MATMPIAIJ` matrix on each process to a single matrix.
5089: For parallel matrices this creates an entirely new matrix. If the matrix is sequential it merely increases the reference count.
5091: Destroy the matrix with `MatDestroy()`
5093: .seealso: [](ch_matrices), `Mat`, `MatMPIAIJGetLocalMat()`
5094: @*/
5095: PetscErrorCode MatAIJGetLocalMat(Mat A, Mat *A_loc)
5096: {
5097: PetscBool mpi;
5099: PetscFunctionBegin;
5100: PetscCall(PetscObjectTypeCompare((PetscObject)A, MATMPIAIJ, &mpi));
5101: if (mpi) PetscCall(MatMPIAIJGetLocalMat(A, MAT_INITIAL_MATRIX, A_loc));
5102: else {
5103: *A_loc = A;
5104: PetscCall(PetscObjectReference((PetscObject)*A_loc));
5105: }
5106: PetscFunctionReturn(PETSC_SUCCESS);
5107: }
5109: /*@
5110: MatMPIAIJGetLocalMat - Creates a `MATSEQAIJ` from a `MATMPIAIJ` matrix.
5112: Not Collective
5114: Input Parameters:
5115: + A - the matrix
5116: - scall - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`
5118: Output Parameter:
5119: . A_loc - the local sequential matrix generated
5121: Level: developer
5123: Notes:
5124: The matrix is created by taking all `A`'s local rows and putting them into a sequential
5125: matrix with `mlocal` rows and `n` columns.`mlocal` is the row count obtained with
5126: `MatGetLocalSize()` and `n` is the global column count obtained with `MatGetSize()`.
5128: In other words combines the two parts of a parallel `MATMPIAIJ` matrix on each process to a single matrix.
5130: When `A` is sequential and `MAT_INITIAL_MATRIX` is requested, the matrix returned is the diagonal part of `A` (which contains the entire matrix),
5131: with its reference count increased by one. Hence changing values of `A_loc` changes `A`. If `MAT_REUSE_MATRIX` is requested on a sequential matrix
5132: then `MatCopy`(Adiag,*`A_loc`,`SAME_NONZERO_PATTERN`) is called to fill `A_loc`. Thus one can preallocate the appropriate sequential matrix `A_loc`
5133: and then call this routine with `MAT_REUSE_MATRIX`. In this case, one can modify the values of `A_loc` without affecting the original sequential matrix.
5135: .seealso: [](ch_matrices), `Mat`, `MATMPIAIJ`, `MatGetOwnershipRange()`, `MatMPIAIJGetLocalMatCondensed()`, `MatMPIAIJGetLocalMatMerge()`
5136: @*/
5137: PetscErrorCode MatMPIAIJGetLocalMat(Mat A, MatReuse scall, Mat *A_loc)
5138: {
5139: Mat_MPIAIJ *mpimat = (Mat_MPIAIJ *)A->data;
5140: Mat_SeqAIJ *mat, *a, *b;
5141: PetscInt *ai, *aj, *bi, *bj, *cmap = mpimat->garray;
5142: const PetscScalar *aa, *ba, *aav, *bav;
5143: PetscScalar *ca, *cam;
5144: PetscMPIInt size;
5145: PetscInt am = A->rmap->n, i, j, k, cstart = A->cmap->rstart;
5146: PetscInt *ci, *cj, col, ncols_d, ncols_o, jo;
5147: PetscBool match;
5149: PetscFunctionBegin;
5150: PetscCall(PetscStrbeginswith(((PetscObject)A)->type_name, MATMPIAIJ, &match));
5151: PetscCheck(match, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "Requires MATMPIAIJ matrix as input");
5152: PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)A), &size));
5153: if (size == 1) {
5154: if (scall == MAT_INITIAL_MATRIX) {
5155: PetscCall(PetscObjectReference((PetscObject)mpimat->A));
5156: *A_loc = mpimat->A;
5157: } else if (scall == MAT_REUSE_MATRIX) {
5158: PetscCall(MatCopy(mpimat->A, *A_loc, SAME_NONZERO_PATTERN));
5159: }
5160: PetscFunctionReturn(PETSC_SUCCESS);
5161: }
5163: PetscCall(PetscLogEventBegin(MAT_Getlocalmat, A, 0, 0, 0));
5164: a = (Mat_SeqAIJ *)mpimat->A->data;
5165: b = (Mat_SeqAIJ *)mpimat->B->data;
5166: ai = a->i;
5167: aj = a->j;
5168: bi = b->i;
5169: bj = b->j;
5170: PetscCall(MatSeqAIJGetArrayRead(mpimat->A, &aav));
5171: PetscCall(MatSeqAIJGetArrayRead(mpimat->B, &bav));
5172: aa = aav;
5173: ba = bav;
5174: if (scall == MAT_INITIAL_MATRIX) {
5175: PetscCall(PetscMalloc1(1 + am, &ci));
5176: ci[0] = 0;
5177: for (i = 0; i < am; i++) ci[i + 1] = ci[i] + (ai[i + 1] - ai[i]) + (bi[i + 1] - bi[i]);
5178: PetscCall(PetscMalloc1(1 + ci[am], &cj));
5179: PetscCall(PetscMalloc1(1 + ci[am], &ca));
5180: k = 0;
5181: for (i = 0; i < am; i++) {
5182: ncols_o = bi[i + 1] - bi[i];
5183: ncols_d = ai[i + 1] - ai[i];
5184: /* off-diagonal portion of A */
5185: for (jo = 0; jo < ncols_o; jo++) {
5186: col = cmap[*bj];
5187: if (col >= cstart) break;
5188: cj[k] = col;
5189: bj++;
5190: ca[k++] = *ba++;
5191: }
5192: /* diagonal portion of A */
5193: for (j = 0; j < ncols_d; j++) {
5194: cj[k] = cstart + *aj++;
5195: ca[k++] = *aa++;
5196: }
5197: /* off-diagonal portion of A */
5198: for (j = jo; j < ncols_o; j++) {
5199: cj[k] = cmap[*bj++];
5200: ca[k++] = *ba++;
5201: }
5202: }
5203: /* put together the new matrix */
5204: PetscCall(MatCreateSeqAIJWithArrays(PETSC_COMM_SELF, am, A->cmap->N, ci, cj, ca, A_loc));
5205: /* MatCreateSeqAIJWithArrays flags matrix so PETSc doesn't free the user's arrays. */
5206: /* Since these are PETSc arrays, change flags to free them as necessary. */
5207: mat = (Mat_SeqAIJ *)(*A_loc)->data;
5208: mat->free_a = PETSC_TRUE;
5209: mat->free_ij = PETSC_TRUE;
5210: mat->nonew = 0;
5211: } else if (scall == MAT_REUSE_MATRIX) {
5212: mat = (Mat_SeqAIJ *)(*A_loc)->data;
5213: ci = mat->i;
5214: cj = mat->j;
5215: PetscCall(MatSeqAIJGetArrayWrite(*A_loc, &cam));
5216: for (i = 0; i < am; i++) {
5217: /* off-diagonal portion of A */
5218: ncols_o = bi[i + 1] - bi[i];
5219: for (jo = 0; jo < ncols_o; jo++) {
5220: col = cmap[*bj];
5221: if (col >= cstart) break;
5222: *cam++ = *ba++;
5223: bj++;
5224: }
5225: /* diagonal portion of A */
5226: ncols_d = ai[i + 1] - ai[i];
5227: for (j = 0; j < ncols_d; j++) *cam++ = *aa++;
5228: /* off-diagonal portion of A */
5229: for (j = jo; j < ncols_o; j++) {
5230: *cam++ = *ba++;
5231: bj++;
5232: }
5233: }
5234: PetscCall(MatSeqAIJRestoreArrayWrite(*A_loc, &cam));
5235: } else SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Invalid MatReuse %d", (int)scall);
5236: PetscCall(MatSeqAIJRestoreArrayRead(mpimat->A, &aav));
5237: PetscCall(MatSeqAIJRestoreArrayRead(mpimat->B, &bav));
5238: PetscCall(PetscLogEventEnd(MAT_Getlocalmat, A, 0, 0, 0));
5239: PetscFunctionReturn(PETSC_SUCCESS);
5240: }
5242: /*@
5243: MatMPIAIJGetLocalMatMerge - Creates a `MATSEQAIJ` from a `MATMPIAIJ` matrix by taking all its local rows and putting them into a sequential matrix with
5244: mlocal rows and n columns. Where n is the sum of the number of columns of the diagonal and off-diagonal part
5246: Not Collective
5248: Input Parameters:
5249: + A - the matrix
5250: - scall - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`
5252: Output Parameters:
5253: + glob - sequential `IS` with global indices associated with the columns of the local sequential matrix generated (can be `NULL`)
5254: - A_loc - the local sequential matrix generated
5256: Level: developer
5258: Note:
5259: This is different from `MatMPIAIJGetLocalMat()` since the first columns in the returning matrix are those associated with the diagonal
5260: part, then those associated with the off-diagonal part (in its local ordering)
5262: .seealso: [](ch_matrices), `Mat`, `MATMPIAIJ`, `MatGetOwnershipRange()`, `MatMPIAIJGetLocalMat()`, `MatMPIAIJGetLocalMatCondensed()`
5263: @*/
5264: PetscErrorCode MatMPIAIJGetLocalMatMerge(Mat A, MatReuse scall, IS *glob, Mat *A_loc)
5265: {
5266: Mat Ao, Ad;
5267: const PetscInt *cmap;
5268: PetscMPIInt size;
5269: PetscErrorCode (*f)(Mat, MatReuse, IS *, Mat *);
5271: PetscFunctionBegin;
5272: PetscCall(MatMPIAIJGetSeqAIJ(A, &Ad, &Ao, &cmap));
5273: PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)A), &size));
5274: if (size == 1) {
5275: if (scall == MAT_INITIAL_MATRIX) {
5276: PetscCall(PetscObjectReference((PetscObject)Ad));
5277: *A_loc = Ad;
5278: } else if (scall == MAT_REUSE_MATRIX) {
5279: PetscCall(MatCopy(Ad, *A_loc, SAME_NONZERO_PATTERN));
5280: }
5281: if (glob) PetscCall(ISCreateStride(PetscObjectComm((PetscObject)Ad), Ad->cmap->n, Ad->cmap->rstart, 1, glob));
5282: PetscFunctionReturn(PETSC_SUCCESS);
5283: }
5284: PetscCall(PetscObjectQueryFunction((PetscObject)A, "MatMPIAIJGetLocalMatMerge_C", &f));
5285: PetscCall(PetscLogEventBegin(MAT_Getlocalmat, A, 0, 0, 0));
5286: if (f) PetscCall((*f)(A, scall, glob, A_loc));
5287: else {
5288: Mat_SeqAIJ *a = (Mat_SeqAIJ *)Ad->data;
5289: Mat_SeqAIJ *b = (Mat_SeqAIJ *)Ao->data;
5290: Mat_SeqAIJ *c;
5291: PetscInt *ai = a->i, *aj = a->j;
5292: PetscInt *bi = b->i, *bj = b->j;
5293: PetscInt *ci, *cj;
5294: const PetscScalar *aa, *ba;
5295: PetscScalar *ca;
5296: PetscInt i, j, am, dn, on;
5298: PetscCall(MatGetLocalSize(Ad, &am, &dn));
5299: PetscCall(MatGetLocalSize(Ao, NULL, &on));
5300: PetscCall(MatSeqAIJGetArrayRead(Ad, &aa));
5301: PetscCall(MatSeqAIJGetArrayRead(Ao, &ba));
5302: if (scall == MAT_INITIAL_MATRIX) {
5303: PetscInt k;
5304: PetscCall(PetscMalloc1(1 + am, &ci));
5305: PetscCall(PetscMalloc1(ai[am] + bi[am], &cj));
5306: PetscCall(PetscMalloc1(ai[am] + bi[am], &ca));
5307: ci[0] = 0;
5308: for (i = 0, k = 0; i < am; i++) {
5309: const PetscInt ncols_o = bi[i + 1] - bi[i];
5310: const PetscInt ncols_d = ai[i + 1] - ai[i];
5311: ci[i + 1] = ci[i] + ncols_o + ncols_d;
5312: /* diagonal portion of A */
5313: for (j = 0; j < ncols_d; j++, k++) {
5314: cj[k] = *aj++;
5315: ca[k] = *aa++;
5316: }
5317: /* off-diagonal portion of A */
5318: for (j = 0; j < ncols_o; j++, k++) {
5319: cj[k] = dn + *bj++;
5320: ca[k] = *ba++;
5321: }
5322: }
5323: /* put together the new matrix */
5324: PetscCall(MatCreateSeqAIJWithArrays(PETSC_COMM_SELF, am, dn + on, ci, cj, ca, A_loc));
5325: /* MatCreateSeqAIJWithArrays flags matrix so PETSc doesn't free the user's arrays. */
5326: /* Since these are PETSc arrays, change flags to free them as necessary. */
5327: c = (Mat_SeqAIJ *)(*A_loc)->data;
5328: c->free_a = PETSC_TRUE;
5329: c->free_ij = PETSC_TRUE;
5330: c->nonew = 0;
5331: PetscCall(MatSetType(*A_loc, ((PetscObject)Ad)->type_name));
5332: } else if (scall == MAT_REUSE_MATRIX) {
5333: PetscCall(MatSeqAIJGetArrayWrite(*A_loc, &ca));
5334: for (i = 0; i < am; i++) {
5335: const PetscInt ncols_d = ai[i + 1] - ai[i];
5336: const PetscInt ncols_o = bi[i + 1] - bi[i];
5337: /* diagonal portion of A */
5338: for (j = 0; j < ncols_d; j++) *ca++ = *aa++;
5339: /* off-diagonal portion of A */
5340: for (j = 0; j < ncols_o; j++) *ca++ = *ba++;
5341: }
5342: PetscCall(MatSeqAIJRestoreArrayWrite(*A_loc, &ca));
5343: } else SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Invalid MatReuse %d", (int)scall);
5344: PetscCall(MatSeqAIJRestoreArrayRead(Ad, &aa));
5345: PetscCall(MatSeqAIJRestoreArrayRead(Ao, &aa));
5346: if (glob) {
5347: PetscInt cst, *gidx;
5349: PetscCall(MatGetOwnershipRangeColumn(A, &cst, NULL));
5350: PetscCall(PetscMalloc1(dn + on, &gidx));
5351: for (i = 0; i < dn; i++) gidx[i] = cst + i;
5352: for (i = 0; i < on; i++) gidx[i + dn] = cmap[i];
5353: PetscCall(ISCreateGeneral(PetscObjectComm((PetscObject)Ad), dn + on, gidx, PETSC_OWN_POINTER, glob));
5354: }
5355: }
5356: PetscCall(PetscLogEventEnd(MAT_Getlocalmat, A, 0, 0, 0));
5357: PetscFunctionReturn(PETSC_SUCCESS);
5358: }
5360: /*@C
5361: MatMPIAIJGetLocalMatCondensed - Creates a `MATSEQAIJ` matrix from an `MATMPIAIJ` matrix by taking all its local rows and NON-ZERO columns
5363: Not Collective
5365: Input Parameters:
5366: + A - the matrix
5367: . scall - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`
5368: . row - index set of rows to extract (or `NULL`)
5369: - col - index set of columns to extract (or `NULL`)
5371: Output Parameter:
5372: . A_loc - the local sequential matrix generated
5374: Level: developer
5376: .seealso: [](ch_matrices), `Mat`, `MATMPIAIJ`, `MatGetOwnershipRange()`, `MatMPIAIJGetLocalMat()`
5377: @*/
5378: PetscErrorCode MatMPIAIJGetLocalMatCondensed(Mat A, MatReuse scall, IS *row, IS *col, Mat *A_loc)
5379: {
5380: Mat_MPIAIJ *a = (Mat_MPIAIJ *)A->data;
5381: PetscInt i, start, end, ncols, nzA, nzB, *cmap, imark, *idx;
5382: IS isrowa, iscola;
5383: Mat *aloc;
5384: PetscBool match;
5386: PetscFunctionBegin;
5387: PetscCall(PetscObjectTypeCompare((PetscObject)A, MATMPIAIJ, &match));
5388: PetscCheck(match, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "Requires MATMPIAIJ matrix as input");
5389: PetscCall(PetscLogEventBegin(MAT_Getlocalmatcondensed, A, 0, 0, 0));
5390: if (!row) {
5391: start = A->rmap->rstart;
5392: end = A->rmap->rend;
5393: PetscCall(ISCreateStride(PETSC_COMM_SELF, end - start, start, 1, &isrowa));
5394: } else {
5395: isrowa = *row;
5396: }
5397: if (!col) {
5398: start = A->cmap->rstart;
5399: cmap = a->garray;
5400: nzA = a->A->cmap->n;
5401: nzB = a->B->cmap->n;
5402: PetscCall(PetscMalloc1(nzA + nzB, &idx));
5403: ncols = 0;
5404: for (i = 0; i < nzB; i++) {
5405: if (cmap[i] < start) idx[ncols++] = cmap[i];
5406: else break;
5407: }
5408: imark = i;
5409: for (i = 0; i < nzA; i++) idx[ncols++] = start + i;
5410: for (i = imark; i < nzB; i++) idx[ncols++] = cmap[i];
5411: PetscCall(ISCreateGeneral(PETSC_COMM_SELF, ncols, idx, PETSC_OWN_POINTER, &iscola));
5412: } else {
5413: iscola = *col;
5414: }
5415: if (scall != MAT_INITIAL_MATRIX) {
5416: PetscCall(PetscMalloc1(1, &aloc));
5417: aloc[0] = *A_loc;
5418: }
5419: PetscCall(MatCreateSubMatrices(A, 1, &isrowa, &iscola, scall, &aloc));
5420: if (!col) { /* attach global id of condensed columns */
5421: PetscCall(PetscObjectCompose((PetscObject)aloc[0], "_petsc_GetLocalMatCondensed_iscol", (PetscObject)iscola));
5422: }
5423: *A_loc = aloc[0];
5424: PetscCall(PetscFree(aloc));
5425: if (!row) PetscCall(ISDestroy(&isrowa));
5426: if (!col) PetscCall(ISDestroy(&iscola));
5427: PetscCall(PetscLogEventEnd(MAT_Getlocalmatcondensed, A, 0, 0, 0));
5428: PetscFunctionReturn(PETSC_SUCCESS);
5429: }
5431: /*
5432: * Create a sequential AIJ matrix based on row indices. a whole column is extracted once a row is matched.
5433: * Row could be local or remote.The routine is designed to be scalable in memory so that nothing is based
5434: * on a global size.
5435: * */
5436: static PetscErrorCode MatCreateSeqSubMatrixWithRows_Private(Mat P, IS rows, Mat *P_oth)
5437: {
5438: Mat_MPIAIJ *p = (Mat_MPIAIJ *)P->data;
5439: Mat_SeqAIJ *pd = (Mat_SeqAIJ *)p->A->data, *po = (Mat_SeqAIJ *)p->B->data, *p_oth;
5440: PetscInt plocalsize, nrows, *ilocal, *oilocal, i, lidx, *nrcols, *nlcols, ncol;
5441: PetscMPIInt owner;
5442: PetscSFNode *iremote, *oiremote;
5443: const PetscInt *lrowindices;
5444: PetscSF sf, osf;
5445: PetscInt pcstart, *roffsets, *loffsets, *pnnz, j;
5446: PetscInt ontotalcols, dntotalcols, ntotalcols, nout;
5447: MPI_Comm comm;
5448: ISLocalToGlobalMapping mapping;
5449: const PetscScalar *pd_a, *po_a;
5451: PetscFunctionBegin;
5452: PetscCall(PetscObjectGetComm((PetscObject)P, &comm));
5453: /* plocalsize is the number of roots
5454: * nrows is the number of leaves
5455: * */
5456: PetscCall(MatGetLocalSize(P, &plocalsize, NULL));
5457: PetscCall(ISGetLocalSize(rows, &nrows));
5458: PetscCall(PetscCalloc1(nrows, &iremote));
5459: PetscCall(ISGetIndices(rows, &lrowindices));
5460: for (i = 0; i < nrows; i++) {
5461: /* Find a remote index and an owner for a row
5462: * The row could be local or remote
5463: * */
5464: owner = 0;
5465: lidx = 0;
5466: PetscCall(PetscLayoutFindOwnerIndex(P->rmap, lrowindices[i], &owner, &lidx));
5467: iremote[i].index = lidx;
5468: iremote[i].rank = owner;
5469: }
5470: /* Create SF to communicate how many nonzero columns for each row */
5471: PetscCall(PetscSFCreate(comm, &sf));
5472: /* SF will figure out the number of nonzero columns for each row, and their
5473: * offsets
5474: * */
5475: PetscCall(PetscSFSetGraph(sf, plocalsize, nrows, NULL, PETSC_OWN_POINTER, iremote, PETSC_OWN_POINTER));
5476: PetscCall(PetscSFSetFromOptions(sf));
5477: PetscCall(PetscSFSetUp(sf));
5479: PetscCall(PetscCalloc1(2 * (plocalsize + 1), &roffsets));
5480: PetscCall(PetscCalloc1(2 * plocalsize, &nrcols));
5481: PetscCall(PetscCalloc1(nrows, &pnnz));
5482: roffsets[0] = 0;
5483: roffsets[1] = 0;
5484: for (i = 0; i < plocalsize; i++) {
5485: /* diagonal */
5486: nrcols[i * 2 + 0] = pd->i[i + 1] - pd->i[i];
5487: /* off-diagonal */
5488: nrcols[i * 2 + 1] = po->i[i + 1] - po->i[i];
5489: /* compute offsets so that we relative location for each row */
5490: roffsets[(i + 1) * 2 + 0] = roffsets[i * 2 + 0] + nrcols[i * 2 + 0];
5491: roffsets[(i + 1) * 2 + 1] = roffsets[i * 2 + 1] + nrcols[i * 2 + 1];
5492: }
5493: PetscCall(PetscCalloc1(2 * nrows, &nlcols));
5494: PetscCall(PetscCalloc1(2 * nrows, &loffsets));
5495: /* 'r' means root, and 'l' means leaf */
5496: PetscCall(PetscSFBcastBegin(sf, MPIU_2INT, nrcols, nlcols, MPI_REPLACE));
5497: PetscCall(PetscSFBcastBegin(sf, MPIU_2INT, roffsets, loffsets, MPI_REPLACE));
5498: PetscCall(PetscSFBcastEnd(sf, MPIU_2INT, nrcols, nlcols, MPI_REPLACE));
5499: PetscCall(PetscSFBcastEnd(sf, MPIU_2INT, roffsets, loffsets, MPI_REPLACE));
5500: PetscCall(PetscSFDestroy(&sf));
5501: PetscCall(PetscFree(roffsets));
5502: PetscCall(PetscFree(nrcols));
5503: dntotalcols = 0;
5504: ontotalcols = 0;
5505: ncol = 0;
5506: for (i = 0; i < nrows; i++) {
5507: pnnz[i] = nlcols[i * 2 + 0] + nlcols[i * 2 + 1];
5508: ncol = PetscMax(pnnz[i], ncol);
5509: /* diagonal */
5510: dntotalcols += nlcols[i * 2 + 0];
5511: /* off-diagonal */
5512: ontotalcols += nlcols[i * 2 + 1];
5513: }
5514: /* We do not need to figure the right number of columns
5515: * since all the calculations will be done by going through the raw data
5516: * */
5517: PetscCall(MatCreateSeqAIJ(PETSC_COMM_SELF, nrows, ncol, 0, pnnz, P_oth));
5518: PetscCall(MatSetUp(*P_oth));
5519: PetscCall(PetscFree(pnnz));
5520: p_oth = (Mat_SeqAIJ *)(*P_oth)->data;
5521: /* diagonal */
5522: PetscCall(PetscCalloc1(dntotalcols, &iremote));
5523: /* off-diagonal */
5524: PetscCall(PetscCalloc1(ontotalcols, &oiremote));
5525: /* diagonal */
5526: PetscCall(PetscCalloc1(dntotalcols, &ilocal));
5527: /* off-diagonal */
5528: PetscCall(PetscCalloc1(ontotalcols, &oilocal));
5529: dntotalcols = 0;
5530: ontotalcols = 0;
5531: ntotalcols = 0;
5532: for (i = 0; i < nrows; i++) {
5533: owner = 0;
5534: PetscCall(PetscLayoutFindOwnerIndex(P->rmap, lrowindices[i], &owner, NULL));
5535: /* Set iremote for diag matrix */
5536: for (j = 0; j < nlcols[i * 2 + 0]; j++) {
5537: iremote[dntotalcols].index = loffsets[i * 2 + 0] + j;
5538: iremote[dntotalcols].rank = owner;
5539: /* P_oth is seqAIJ so that ilocal need to point to the first part of memory */
5540: ilocal[dntotalcols++] = ntotalcols++;
5541: }
5542: /* off-diagonal */
5543: for (j = 0; j < nlcols[i * 2 + 1]; j++) {
5544: oiremote[ontotalcols].index = loffsets[i * 2 + 1] + j;
5545: oiremote[ontotalcols].rank = owner;
5546: oilocal[ontotalcols++] = ntotalcols++;
5547: }
5548: }
5549: PetscCall(ISRestoreIndices(rows, &lrowindices));
5550: PetscCall(PetscFree(loffsets));
5551: PetscCall(PetscFree(nlcols));
5552: PetscCall(PetscSFCreate(comm, &sf));
5553: /* P serves as roots and P_oth is leaves
5554: * Diag matrix
5555: * */
5556: PetscCall(PetscSFSetGraph(sf, pd->i[plocalsize], dntotalcols, ilocal, PETSC_OWN_POINTER, iremote, PETSC_OWN_POINTER));
5557: PetscCall(PetscSFSetFromOptions(sf));
5558: PetscCall(PetscSFSetUp(sf));
5560: PetscCall(PetscSFCreate(comm, &osf));
5561: /* off-diagonal */
5562: PetscCall(PetscSFSetGraph(osf, po->i[plocalsize], ontotalcols, oilocal, PETSC_OWN_POINTER, oiremote, PETSC_OWN_POINTER));
5563: PetscCall(PetscSFSetFromOptions(osf));
5564: PetscCall(PetscSFSetUp(osf));
5565: PetscCall(MatSeqAIJGetArrayRead(p->A, &pd_a));
5566: PetscCall(MatSeqAIJGetArrayRead(p->B, &po_a));
5567: /* operate on the matrix internal data to save memory */
5568: PetscCall(PetscSFBcastBegin(sf, MPIU_SCALAR, pd_a, p_oth->a, MPI_REPLACE));
5569: PetscCall(PetscSFBcastBegin(osf, MPIU_SCALAR, po_a, p_oth->a, MPI_REPLACE));
5570: PetscCall(MatGetOwnershipRangeColumn(P, &pcstart, NULL));
5571: /* Convert to global indices for diag matrix */
5572: for (i = 0; i < pd->i[plocalsize]; i++) pd->j[i] += pcstart;
5573: PetscCall(PetscSFBcastBegin(sf, MPIU_INT, pd->j, p_oth->j, MPI_REPLACE));
5574: /* We want P_oth store global indices */
5575: PetscCall(ISLocalToGlobalMappingCreate(comm, 1, p->B->cmap->n, p->garray, PETSC_COPY_VALUES, &mapping));
5576: /* Use memory scalable approach */
5577: PetscCall(ISLocalToGlobalMappingSetType(mapping, ISLOCALTOGLOBALMAPPINGHASH));
5578: PetscCall(ISLocalToGlobalMappingApply(mapping, po->i[plocalsize], po->j, po->j));
5579: PetscCall(PetscSFBcastBegin(osf, MPIU_INT, po->j, p_oth->j, MPI_REPLACE));
5580: PetscCall(PetscSFBcastEnd(sf, MPIU_INT, pd->j, p_oth->j, MPI_REPLACE));
5581: /* Convert back to local indices */
5582: for (i = 0; i < pd->i[plocalsize]; i++) pd->j[i] -= pcstart;
5583: PetscCall(PetscSFBcastEnd(osf, MPIU_INT, po->j, p_oth->j, MPI_REPLACE));
5584: nout = 0;
5585: PetscCall(ISGlobalToLocalMappingApply(mapping, IS_GTOLM_DROP, po->i[plocalsize], po->j, &nout, po->j));
5586: PetscCheck(nout == po->i[plocalsize], comm, PETSC_ERR_ARG_INCOMP, "n %" PetscInt_FMT " does not equal to nout %" PetscInt_FMT " ", po->i[plocalsize], nout);
5587: PetscCall(ISLocalToGlobalMappingDestroy(&mapping));
5588: /* Exchange values */
5589: PetscCall(PetscSFBcastEnd(sf, MPIU_SCALAR, pd_a, p_oth->a, MPI_REPLACE));
5590: PetscCall(PetscSFBcastEnd(osf, MPIU_SCALAR, po_a, p_oth->a, MPI_REPLACE));
5591: PetscCall(MatSeqAIJRestoreArrayRead(p->A, &pd_a));
5592: PetscCall(MatSeqAIJRestoreArrayRead(p->B, &po_a));
5593: /* Stop PETSc from shrinking memory */
5594: for (i = 0; i < nrows; i++) p_oth->ilen[i] = p_oth->imax[i];
5595: PetscCall(MatAssemblyBegin(*P_oth, MAT_FINAL_ASSEMBLY));
5596: PetscCall(MatAssemblyEnd(*P_oth, MAT_FINAL_ASSEMBLY));
5597: /* Attach PetscSF objects to P_oth so that we can reuse it later */
5598: PetscCall(PetscObjectCompose((PetscObject)*P_oth, "diagsf", (PetscObject)sf));
5599: PetscCall(PetscObjectCompose((PetscObject)*P_oth, "offdiagsf", (PetscObject)osf));
5600: PetscCall(PetscSFDestroy(&sf));
5601: PetscCall(PetscSFDestroy(&osf));
5602: PetscFunctionReturn(PETSC_SUCCESS);
5603: }
5605: /*
5606: * Creates a SeqAIJ matrix by taking rows of B that equal to nonzero columns of local A
5607: * This supports MPIAIJ and MAIJ
5608: * */
5609: PetscErrorCode MatGetBrowsOfAcols_MPIXAIJ(Mat A, Mat P, PetscInt dof, MatReuse reuse, Mat *P_oth)
5610: {
5611: Mat_MPIAIJ *a = (Mat_MPIAIJ *)A->data, *p = (Mat_MPIAIJ *)P->data;
5612: Mat_SeqAIJ *p_oth;
5613: IS rows, map;
5614: PetscHMapI hamp;
5615: PetscInt i, htsize, *rowindices, off, *mapping, key, count;
5616: MPI_Comm comm;
5617: PetscSF sf, osf;
5618: PetscBool has;
5620: PetscFunctionBegin;
5621: PetscCall(PetscObjectGetComm((PetscObject)A, &comm));
5622: PetscCall(PetscLogEventBegin(MAT_GetBrowsOfAocols, A, P, 0, 0));
5623: /* If it is the first time, create an index set of off-diag nonzero columns of A,
5624: * and then create a submatrix (that often is an overlapping matrix)
5625: * */
5626: if (reuse == MAT_INITIAL_MATRIX) {
5627: /* Use a hash table to figure out unique keys */
5628: PetscCall(PetscHMapICreateWithSize(a->B->cmap->n, &hamp));
5629: PetscCall(PetscCalloc1(a->B->cmap->n, &mapping));
5630: count = 0;
5631: /* Assume that a->g is sorted, otherwise the following does not make sense */
5632: for (i = 0; i < a->B->cmap->n; i++) {
5633: key = a->garray[i] / dof;
5634: PetscCall(PetscHMapIHas(hamp, key, &has));
5635: if (!has) {
5636: mapping[i] = count;
5637: PetscCall(PetscHMapISet(hamp, key, count++));
5638: } else {
5639: /* Current 'i' has the same value the previous step */
5640: mapping[i] = count - 1;
5641: }
5642: }
5643: PetscCall(ISCreateGeneral(comm, a->B->cmap->n, mapping, PETSC_OWN_POINTER, &map));
5644: PetscCall(PetscHMapIGetSize(hamp, &htsize));
5645: PetscCheck(htsize == count, comm, PETSC_ERR_ARG_INCOMP, " Size of hash map %" PetscInt_FMT " is inconsistent with count %" PetscInt_FMT, htsize, count);
5646: PetscCall(PetscCalloc1(htsize, &rowindices));
5647: off = 0;
5648: PetscCall(PetscHMapIGetKeys(hamp, &off, rowindices));
5649: PetscCall(PetscHMapIDestroy(&hamp));
5650: PetscCall(PetscSortInt(htsize, rowindices));
5651: PetscCall(ISCreateGeneral(comm, htsize, rowindices, PETSC_OWN_POINTER, &rows));
5652: /* In case, the matrix was already created but users want to recreate the matrix */
5653: PetscCall(MatDestroy(P_oth));
5654: PetscCall(MatCreateSeqSubMatrixWithRows_Private(P, rows, P_oth));
5655: PetscCall(PetscObjectCompose((PetscObject)*P_oth, "aoffdiagtopothmapping", (PetscObject)map));
5656: PetscCall(ISDestroy(&map));
5657: PetscCall(ISDestroy(&rows));
5658: } else if (reuse == MAT_REUSE_MATRIX) {
5659: /* If matrix was already created, we simply update values using SF objects
5660: * that as attached to the matrix earlier.
5661: */
5662: const PetscScalar *pd_a, *po_a;
5664: PetscCall(PetscObjectQuery((PetscObject)*P_oth, "diagsf", (PetscObject *)&sf));
5665: PetscCall(PetscObjectQuery((PetscObject)*P_oth, "offdiagsf", (PetscObject *)&osf));
5666: PetscCheck(sf && osf, comm, PETSC_ERR_ARG_NULL, "Matrix is not initialized yet");
5667: p_oth = (Mat_SeqAIJ *)(*P_oth)->data;
5668: /* Update values in place */
5669: PetscCall(MatSeqAIJGetArrayRead(p->A, &pd_a));
5670: PetscCall(MatSeqAIJGetArrayRead(p->B, &po_a));
5671: PetscCall(PetscSFBcastBegin(sf, MPIU_SCALAR, pd_a, p_oth->a, MPI_REPLACE));
5672: PetscCall(PetscSFBcastBegin(osf, MPIU_SCALAR, po_a, p_oth->a, MPI_REPLACE));
5673: PetscCall(PetscSFBcastEnd(sf, MPIU_SCALAR, pd_a, p_oth->a, MPI_REPLACE));
5674: PetscCall(PetscSFBcastEnd(osf, MPIU_SCALAR, po_a, p_oth->a, MPI_REPLACE));
5675: PetscCall(MatSeqAIJRestoreArrayRead(p->A, &pd_a));
5676: PetscCall(MatSeqAIJRestoreArrayRead(p->B, &po_a));
5677: } else SETERRQ(comm, PETSC_ERR_ARG_UNKNOWN_TYPE, "Unknown reuse type");
5678: PetscCall(PetscLogEventEnd(MAT_GetBrowsOfAocols, A, P, 0, 0));
5679: PetscFunctionReturn(PETSC_SUCCESS);
5680: }
5682: /*@C
5683: MatGetBrowsOfAcols - Returns `IS` that contain rows of `B` that equal to nonzero columns of local `A`
5685: Collective
5687: Input Parameters:
5688: + A - the first matrix in `MATMPIAIJ` format
5689: . B - the second matrix in `MATMPIAIJ` format
5690: - scall - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`
5692: Output Parameters:
5693: + rowb - On input index sets of rows of B to extract (or `NULL`), modified on output
5694: . colb - On input index sets of columns of B to extract (or `NULL`), modified on output
5695: - B_seq - the sequential matrix generated
5697: Level: developer
5699: .seealso: `Mat`, `MATMPIAIJ`, `IS`, `MatReuse`
5700: @*/
5701: PetscErrorCode MatGetBrowsOfAcols(Mat A, Mat B, MatReuse scall, IS *rowb, IS *colb, Mat *B_seq)
5702: {
5703: Mat_MPIAIJ *a = (Mat_MPIAIJ *)A->data;
5704: PetscInt *idx, i, start, ncols, nzA, nzB, *cmap, imark;
5705: IS isrowb, iscolb;
5706: Mat *bseq = NULL;
5708: PetscFunctionBegin;
5709: PetscCheck(A->cmap->rstart == B->rmap->rstart && A->cmap->rend == B->rmap->rend, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Matrix local dimensions are incompatible, (%" PetscInt_FMT ", %" PetscInt_FMT ") != (%" PetscInt_FMT ",%" PetscInt_FMT ")",
5710: A->cmap->rstart, A->cmap->rend, B->rmap->rstart, B->rmap->rend);
5711: PetscCall(PetscLogEventBegin(MAT_GetBrowsOfAcols, A, B, 0, 0));
5713: if (scall == MAT_INITIAL_MATRIX) {
5714: start = A->cmap->rstart;
5715: cmap = a->garray;
5716: nzA = a->A->cmap->n;
5717: nzB = a->B->cmap->n;
5718: PetscCall(PetscMalloc1(nzA + nzB, &idx));
5719: ncols = 0;
5720: for (i = 0; i < nzB; i++) { /* row < local row index */
5721: if (cmap[i] < start) idx[ncols++] = cmap[i];
5722: else break;
5723: }
5724: imark = i;
5725: for (i = 0; i < nzA; i++) idx[ncols++] = start + i; /* local rows */
5726: for (i = imark; i < nzB; i++) idx[ncols++] = cmap[i]; /* row > local row index */
5727: PetscCall(ISCreateGeneral(PETSC_COMM_SELF, ncols, idx, PETSC_OWN_POINTER, &isrowb));
5728: PetscCall(ISCreateStride(PETSC_COMM_SELF, B->cmap->N, 0, 1, &iscolb));
5729: } else {
5730: PetscCheck(rowb && colb, PETSC_COMM_SELF, PETSC_ERR_SUP, "IS rowb and colb must be provided for MAT_REUSE_MATRIX");
5731: isrowb = *rowb;
5732: iscolb = *colb;
5733: PetscCall(PetscMalloc1(1, &bseq));
5734: bseq[0] = *B_seq;
5735: }
5736: PetscCall(MatCreateSubMatrices(B, 1, &isrowb, &iscolb, scall, &bseq));
5737: *B_seq = bseq[0];
5738: PetscCall(PetscFree(bseq));
5739: if (!rowb) {
5740: PetscCall(ISDestroy(&isrowb));
5741: } else {
5742: *rowb = isrowb;
5743: }
5744: if (!colb) {
5745: PetscCall(ISDestroy(&iscolb));
5746: } else {
5747: *colb = iscolb;
5748: }
5749: PetscCall(PetscLogEventEnd(MAT_GetBrowsOfAcols, A, B, 0, 0));
5750: PetscFunctionReturn(PETSC_SUCCESS);
5751: }
5753: // PetscClangLinter pragma disable: -fdoc-sowing-chars
5754: /*
5755: MatGetBrowsOfAoCols_MPIAIJ - Creates a `MATSEQAIJ` matrix by taking rows of B that equal to nonzero columns
5756: of the OFF-DIAGONAL portion of local A
5758: Collective
5760: Input Parameters:
5761: + A - the first matrix in `MATMPIAIJ` format
5762: . B - the second matrix in `MATMPIAIJ` format
5763: - scall - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`
5765: Output Parameters:
5766: + startsj_s - starting point in B's sending j-arrays, saved for MAT_REUSE (or NULL)
5767: . startsj_r - starting point in B's receiving j-arrays, saved for MAT_REUSE (or NULL)
5768: . bufa_ptr - array for sending matrix values, saved for MAT_REUSE (or NULL)
5769: - B_oth - the sequential matrix generated with size aBn=a->B->cmap->n by B->cmap->N
5771: Level: developer
5773: Developer Note:
5774: This directly accesses information inside the VecScatter associated with the matrix-vector product
5775: for this matrix. This is not desirable.
5777: .seealso: [](ch_mat), `Mat`, `MATMPIAIJ`
5778: */
5779: PetscErrorCode MatGetBrowsOfAoCols_MPIAIJ(Mat A, Mat B, MatReuse scall, PetscInt **startsj_s, PetscInt **startsj_r, MatScalar **bufa_ptr, Mat *B_oth)
5780: {
5781: Mat_MPIAIJ *a = (Mat_MPIAIJ *)A->data;
5782: VecScatter ctx;
5783: MPI_Comm comm;
5784: const PetscMPIInt *rprocs, *sprocs;
5785: PetscMPIInt nrecvs, nsends;
5786: const PetscInt *srow, *rstarts, *sstarts;
5787: PetscInt *rowlen, *bufj, *bufJ, ncols = 0, aBn = a->B->cmap->n, row, *b_othi, *b_othj, *rvalues = NULL, *svalues = NULL, *cols, sbs, rbs;
5788: PetscInt i, j, k = 0, l, ll, nrows, *rstartsj = NULL, *sstartsj, len;
5789: PetscScalar *b_otha, *bufa, *bufA, *vals = NULL;
5790: MPI_Request *reqs = NULL, *rwaits = NULL, *swaits = NULL;
5791: PetscMPIInt size, tag, rank, nreqs;
5793: PetscFunctionBegin;
5794: PetscCall(PetscObjectGetComm((PetscObject)A, &comm));
5795: PetscCallMPI(MPI_Comm_size(comm, &size));
5797: PetscCheck(A->cmap->rstart == B->rmap->rstart && A->cmap->rend == B->rmap->rend, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Matrix local dimensions are incompatible, (%" PetscInt_FMT ", %" PetscInt_FMT ") != (%" PetscInt_FMT ",%" PetscInt_FMT ")",
5798: A->cmap->rstart, A->cmap->rend, B->rmap->rstart, B->rmap->rend);
5799: PetscCall(PetscLogEventBegin(MAT_GetBrowsOfAocols, A, B, 0, 0));
5800: PetscCallMPI(MPI_Comm_rank(comm, &rank));
5802: if (size == 1) {
5803: startsj_s = NULL;
5804: bufa_ptr = NULL;
5805: *B_oth = NULL;
5806: PetscFunctionReturn(PETSC_SUCCESS);
5807: }
5809: ctx = a->Mvctx;
5810: tag = ((PetscObject)ctx)->tag;
5812: PetscCall(VecScatterGetRemote_Private(ctx, PETSC_TRUE /*send*/, &nsends, &sstarts, &srow, &sprocs, &sbs));
5813: /* rprocs[] must be ordered so that indices received from them are ordered in rvalues[], which is key to algorithms used in this subroutine */
5814: PetscCall(VecScatterGetRemoteOrdered_Private(ctx, PETSC_FALSE /*recv*/, &nrecvs, &rstarts, NULL /*indices not needed*/, &rprocs, &rbs));
5815: PetscCall(PetscMPIIntCast(nsends + nrecvs, &nreqs));
5816: PetscCall(PetscMalloc1(nreqs, &reqs));
5817: rwaits = reqs;
5818: swaits = PetscSafePointerPlusOffset(reqs, nrecvs);
5820: if (!startsj_s || !bufa_ptr) scall = MAT_INITIAL_MATRIX;
5821: if (scall == MAT_INITIAL_MATRIX) {
5822: /* i-array */
5823: /* post receives */
5824: if (nrecvs) PetscCall(PetscMalloc1(rbs * (rstarts[nrecvs] - rstarts[0]), &rvalues)); /* rstarts can be NULL when nrecvs=0 */
5825: for (i = 0; i < nrecvs; i++) {
5826: rowlen = rvalues + rstarts[i] * rbs;
5827: nrows = (rstarts[i + 1] - rstarts[i]) * rbs; /* num of indices to be received */
5828: PetscCallMPI(MPIU_Irecv(rowlen, nrows, MPIU_INT, rprocs[i], tag, comm, rwaits + i));
5829: }
5831: /* pack the outgoing message */
5832: PetscCall(PetscMalloc2(nsends + 1, &sstartsj, nrecvs + 1, &rstartsj));
5834: sstartsj[0] = 0;
5835: rstartsj[0] = 0;
5836: len = 0; /* total length of j or a array to be sent */
5837: if (nsends) {
5838: k = sstarts[0]; /* ATTENTION: sstarts[0] and rstarts[0] are not necessarily zero */
5839: PetscCall(PetscMalloc1(sbs * (sstarts[nsends] - sstarts[0]), &svalues));
5840: }
5841: for (i = 0; i < nsends; i++) {
5842: rowlen = svalues + (sstarts[i] - sstarts[0]) * sbs;
5843: nrows = sstarts[i + 1] - sstarts[i]; /* num of block rows */
5844: for (j = 0; j < nrows; j++) {
5845: row = srow[k] + B->rmap->range[rank]; /* global row idx */
5846: for (l = 0; l < sbs; l++) {
5847: PetscCall(MatGetRow_MPIAIJ(B, row + l, &ncols, NULL, NULL)); /* rowlength */
5849: rowlen[j * sbs + l] = ncols;
5851: len += ncols;
5852: PetscCall(MatRestoreRow_MPIAIJ(B, row + l, &ncols, NULL, NULL));
5853: }
5854: k++;
5855: }
5856: PetscCallMPI(MPIU_Isend(rowlen, nrows * sbs, MPIU_INT, sprocs[i], tag, comm, swaits + i));
5858: sstartsj[i + 1] = len; /* starting point of (i+1)-th outgoing msg in bufj and bufa */
5859: }
5860: /* recvs and sends of i-array are completed */
5861: if (nreqs) PetscCallMPI(MPI_Waitall(nreqs, reqs, MPI_STATUSES_IGNORE));
5862: PetscCall(PetscFree(svalues));
5864: /* allocate buffers for sending j and a arrays */
5865: PetscCall(PetscMalloc1(len, &bufj));
5866: PetscCall(PetscMalloc1(len, &bufa));
5868: /* create i-array of B_oth */
5869: PetscCall(PetscMalloc1(aBn + 1, &b_othi));
5871: b_othi[0] = 0;
5872: len = 0; /* total length of j or a array to be received */
5873: k = 0;
5874: for (i = 0; i < nrecvs; i++) {
5875: rowlen = rvalues + (rstarts[i] - rstarts[0]) * rbs;
5876: nrows = (rstarts[i + 1] - rstarts[i]) * rbs; /* num of rows to be received */
5877: for (j = 0; j < nrows; j++) {
5878: b_othi[k + 1] = b_othi[k] + rowlen[j];
5879: PetscCall(PetscIntSumError(rowlen[j], len, &len));
5880: k++;
5881: }
5882: rstartsj[i + 1] = len; /* starting point of (i+1)-th incoming msg in bufj and bufa */
5883: }
5884: PetscCall(PetscFree(rvalues));
5886: /* allocate space for j and a arrays of B_oth */
5887: PetscCall(PetscMalloc1(b_othi[aBn], &b_othj));
5888: PetscCall(PetscMalloc1(b_othi[aBn], &b_otha));
5890: /* j-array */
5891: /* post receives of j-array */
5892: for (i = 0; i < nrecvs; i++) {
5893: nrows = rstartsj[i + 1] - rstartsj[i]; /* length of the msg received */
5894: PetscCallMPI(MPIU_Irecv(PetscSafePointerPlusOffset(b_othj, rstartsj[i]), nrows, MPIU_INT, rprocs[i], tag, comm, rwaits + i));
5895: }
5897: /* pack the outgoing message j-array */
5898: if (nsends) k = sstarts[0];
5899: for (i = 0; i < nsends; i++) {
5900: nrows = sstarts[i + 1] - sstarts[i]; /* num of block rows */
5901: bufJ = PetscSafePointerPlusOffset(bufj, sstartsj[i]);
5902: for (j = 0; j < nrows; j++) {
5903: row = srow[k++] + B->rmap->range[rank]; /* global row idx */
5904: for (ll = 0; ll < sbs; ll++) {
5905: PetscCall(MatGetRow_MPIAIJ(B, row + ll, &ncols, &cols, NULL));
5906: for (l = 0; l < ncols; l++) *bufJ++ = cols[l];
5907: PetscCall(MatRestoreRow_MPIAIJ(B, row + ll, &ncols, &cols, NULL));
5908: }
5909: }
5910: PetscCallMPI(MPIU_Isend(PetscSafePointerPlusOffset(bufj, sstartsj[i]), sstartsj[i + 1] - sstartsj[i], MPIU_INT, sprocs[i], tag, comm, swaits + i));
5911: }
5913: /* recvs and sends of j-array are completed */
5914: if (nreqs) PetscCallMPI(MPI_Waitall(nreqs, reqs, MPI_STATUSES_IGNORE));
5915: } else if (scall == MAT_REUSE_MATRIX) {
5916: sstartsj = *startsj_s;
5917: rstartsj = *startsj_r;
5918: bufa = *bufa_ptr;
5919: PetscCall(MatSeqAIJGetArrayWrite(*B_oth, &b_otha));
5920: } else SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Matrix P does not possess an object container");
5922: /* a-array */
5923: /* post receives of a-array */
5924: for (i = 0; i < nrecvs; i++) {
5925: nrows = rstartsj[i + 1] - rstartsj[i]; /* length of the msg received */
5926: PetscCallMPI(MPIU_Irecv(PetscSafePointerPlusOffset(b_otha, rstartsj[i]), nrows, MPIU_SCALAR, rprocs[i], tag, comm, rwaits + i));
5927: }
5929: /* pack the outgoing message a-array */
5930: if (nsends) k = sstarts[0];
5931: for (i = 0; i < nsends; i++) {
5932: nrows = sstarts[i + 1] - sstarts[i]; /* num of block rows */
5933: bufA = PetscSafePointerPlusOffset(bufa, sstartsj[i]);
5934: for (j = 0; j < nrows; j++) {
5935: row = srow[k++] + B->rmap->range[rank]; /* global row idx */
5936: for (ll = 0; ll < sbs; ll++) {
5937: PetscCall(MatGetRow_MPIAIJ(B, row + ll, &ncols, NULL, &vals));
5938: for (l = 0; l < ncols; l++) *bufA++ = vals[l];
5939: PetscCall(MatRestoreRow_MPIAIJ(B, row + ll, &ncols, NULL, &vals));
5940: }
5941: }
5942: PetscCallMPI(MPIU_Isend(PetscSafePointerPlusOffset(bufa, sstartsj[i]), sstartsj[i + 1] - sstartsj[i], MPIU_SCALAR, sprocs[i], tag, comm, swaits + i));
5943: }
5944: /* recvs and sends of a-array are completed */
5945: if (nreqs) PetscCallMPI(MPI_Waitall(nreqs, reqs, MPI_STATUSES_IGNORE));
5946: PetscCall(PetscFree(reqs));
5948: if (scall == MAT_INITIAL_MATRIX) {
5949: Mat_SeqAIJ *b_oth;
5951: /* put together the new matrix */
5952: PetscCall(MatCreateSeqAIJWithArrays(PETSC_COMM_SELF, aBn, B->cmap->N, b_othi, b_othj, b_otha, B_oth));
5954: /* MatCreateSeqAIJWithArrays flags matrix so PETSc doesn't free the user's arrays. */
5955: /* Since these are PETSc arrays, change flags to free them as necessary. */
5956: b_oth = (Mat_SeqAIJ *)(*B_oth)->data;
5957: b_oth->free_a = PETSC_TRUE;
5958: b_oth->free_ij = PETSC_TRUE;
5959: b_oth->nonew = 0;
5961: PetscCall(PetscFree(bufj));
5962: if (!startsj_s || !bufa_ptr) {
5963: PetscCall(PetscFree2(sstartsj, rstartsj));
5964: PetscCall(PetscFree(bufa_ptr));
5965: } else {
5966: *startsj_s = sstartsj;
5967: *startsj_r = rstartsj;
5968: *bufa_ptr = bufa;
5969: }
5970: } else if (scall == MAT_REUSE_MATRIX) {
5971: PetscCall(MatSeqAIJRestoreArrayWrite(*B_oth, &b_otha));
5972: }
5974: PetscCall(VecScatterRestoreRemote_Private(ctx, PETSC_TRUE, &nsends, &sstarts, &srow, &sprocs, &sbs));
5975: PetscCall(VecScatterRestoreRemoteOrdered_Private(ctx, PETSC_FALSE, &nrecvs, &rstarts, NULL, &rprocs, &rbs));
5976: PetscCall(PetscLogEventEnd(MAT_GetBrowsOfAocols, A, B, 0, 0));
5977: PetscFunctionReturn(PETSC_SUCCESS);
5978: }
5980: PETSC_INTERN PetscErrorCode MatConvert_MPIAIJ_MPIAIJCRL(Mat, MatType, MatReuse, Mat *);
5981: PETSC_INTERN PetscErrorCode MatConvert_MPIAIJ_MPIAIJPERM(Mat, MatType, MatReuse, Mat *);
5982: PETSC_INTERN PetscErrorCode MatConvert_MPIAIJ_MPIAIJSELL(Mat, MatType, MatReuse, Mat *);
5983: #if defined(PETSC_HAVE_MKL_SPARSE)
5984: PETSC_INTERN PetscErrorCode MatConvert_MPIAIJ_MPIAIJMKL(Mat, MatType, MatReuse, Mat *);
5985: #endif
5986: PETSC_INTERN PetscErrorCode MatConvert_MPIAIJ_MPIBAIJ(Mat, MatType, MatReuse, Mat *);
5987: PETSC_INTERN PetscErrorCode MatConvert_MPIAIJ_MPISBAIJ(Mat, MatType, MatReuse, Mat *);
5988: #if defined(PETSC_HAVE_ELEMENTAL)
5989: PETSC_INTERN PetscErrorCode MatConvert_MPIAIJ_Elemental(Mat, MatType, MatReuse, Mat *);
5990: #endif
5991: #if defined(PETSC_HAVE_SCALAPACK) && (defined(PETSC_USE_REAL_SINGLE) || defined(PETSC_USE_REAL_DOUBLE))
5992: PETSC_INTERN PetscErrorCode MatConvert_AIJ_ScaLAPACK(Mat, MatType, MatReuse, Mat *);
5993: #endif
5994: #if defined(PETSC_HAVE_HYPRE)
5995: PETSC_INTERN PetscErrorCode MatConvert_AIJ_HYPRE(Mat, MatType, MatReuse, Mat *);
5996: #endif
5997: #if defined(PETSC_HAVE_CUDA)
5998: PETSC_INTERN PetscErrorCode MatConvert_MPIAIJ_MPIAIJCUSPARSE(Mat, MatType, MatReuse, Mat *);
5999: #endif
6000: #if defined(PETSC_HAVE_HIP)
6001: PETSC_INTERN PetscErrorCode MatConvert_MPIAIJ_MPIAIJHIPSPARSE(Mat, MatType, MatReuse, Mat *);
6002: #endif
6003: #if defined(PETSC_HAVE_KOKKOS_KERNELS)
6004: PETSC_INTERN PetscErrorCode MatConvert_MPIAIJ_MPIAIJKokkos(Mat, MatType, MatReuse, Mat *);
6005: #endif
6006: PETSC_INTERN PetscErrorCode MatConvert_MPIAIJ_MPISELL(Mat, MatType, MatReuse, Mat *);
6007: PETSC_INTERN PetscErrorCode MatConvert_XAIJ_IS(Mat, MatType, MatReuse, Mat *);
6008: PETSC_INTERN PetscErrorCode MatProductSetFromOptions_IS_XAIJ(Mat);
6010: /*
6011: Computes (B'*A')' since computing B*A directly is untenable
6013: n p p
6014: [ ] [ ] [ ]
6015: m [ A ] * n [ B ] = m [ C ]
6016: [ ] [ ] [ ]
6018: */
6019: static PetscErrorCode MatMatMultNumeric_MPIDense_MPIAIJ(Mat A, Mat B, Mat C)
6020: {
6021: Mat At, Bt, Ct;
6023: PetscFunctionBegin;
6024: PetscCall(MatTranspose(A, MAT_INITIAL_MATRIX, &At));
6025: PetscCall(MatTranspose(B, MAT_INITIAL_MATRIX, &Bt));
6026: PetscCall(MatMatMult(Bt, At, MAT_INITIAL_MATRIX, PETSC_CURRENT, &Ct));
6027: PetscCall(MatDestroy(&At));
6028: PetscCall(MatDestroy(&Bt));
6029: PetscCall(MatTransposeSetPrecursor(Ct, C));
6030: PetscCall(MatTranspose(Ct, MAT_REUSE_MATRIX, &C));
6031: PetscCall(MatDestroy(&Ct));
6032: PetscFunctionReturn(PETSC_SUCCESS);
6033: }
6035: static PetscErrorCode MatMatMultSymbolic_MPIDense_MPIAIJ(Mat A, Mat B, PetscReal fill, Mat C)
6036: {
6037: PetscBool cisdense;
6039: PetscFunctionBegin;
6040: PetscCheck(A->cmap->n == B->rmap->n, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "A->cmap->n %" PetscInt_FMT " != B->rmap->n %" PetscInt_FMT, A->cmap->n, B->rmap->n);
6041: PetscCall(MatSetSizes(C, A->rmap->n, B->cmap->n, A->rmap->N, B->cmap->N));
6042: PetscCall(MatSetBlockSizesFromMats(C, A, B));
6043: PetscCall(PetscObjectTypeCompareAny((PetscObject)C, &cisdense, MATMPIDENSE, MATMPIDENSECUDA, MATMPIDENSEHIP, ""));
6044: if (!cisdense) PetscCall(MatSetType(C, ((PetscObject)A)->type_name));
6045: PetscCall(MatSetUp(C));
6047: C->ops->matmultnumeric = MatMatMultNumeric_MPIDense_MPIAIJ;
6048: PetscFunctionReturn(PETSC_SUCCESS);
6049: }
6051: static PetscErrorCode MatProductSetFromOptions_MPIDense_MPIAIJ_AB(Mat C)
6052: {
6053: Mat_Product *product = C->product;
6054: Mat A = product->A, B = product->B;
6056: PetscFunctionBegin;
6057: PetscCheck(A->cmap->rstart == B->rmap->rstart && A->cmap->rend == B->rmap->rend, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Matrix local dimensions are incompatible, (%" PetscInt_FMT ", %" PetscInt_FMT ") != (%" PetscInt_FMT ",%" PetscInt_FMT ")",
6058: A->cmap->rstart, A->cmap->rend, B->rmap->rstart, B->rmap->rend);
6059: C->ops->matmultsymbolic = MatMatMultSymbolic_MPIDense_MPIAIJ;
6060: C->ops->productsymbolic = MatProductSymbolic_AB;
6061: PetscFunctionReturn(PETSC_SUCCESS);
6062: }
6064: PETSC_INTERN PetscErrorCode MatProductSetFromOptions_MPIDense_MPIAIJ(Mat C)
6065: {
6066: Mat_Product *product = C->product;
6068: PetscFunctionBegin;
6069: if (product->type == MATPRODUCT_AB) PetscCall(MatProductSetFromOptions_MPIDense_MPIAIJ_AB(C));
6070: PetscFunctionReturn(PETSC_SUCCESS);
6071: }
6073: /*
6074: Merge two sets of sorted nonzeros and return a CSR for the merged (sequential) matrix
6076: Input Parameters:
6078: j1,rowBegin1,rowEnd1,jmap1: describe the first set of nonzeros (Set1)
6079: j2,rowBegin2,rowEnd2,jmap2: describe the second set of nonzeros (Set2)
6081: mat: both sets' nonzeros are on m rows, where m is the number of local rows of the matrix mat
6083: For Set1, j1[] contains column indices of the nonzeros.
6084: For the k-th row (0<=k<m), [rowBegin1[k],rowEnd1[k]) index into j1[] and point to the begin/end nonzero in row k
6085: respectively (note rowEnd1[k] is not necessarily equal to rwoBegin1[k+1]). Indices in this range of j1[] are sorted,
6086: but might have repeats. jmap1[t+1] - jmap1[t] is the number of repeats for the t-th unique nonzero in Set1.
6088: Similar for Set2.
6090: This routine merges the two sets of nonzeros row by row and removes repeats.
6092: Output Parameters: (memory is allocated by the caller)
6094: i[],j[]: the CSR of the merged matrix, which has m rows.
6095: imap1[]: the k-th unique nonzero in Set1 (k=0,1,...) corresponds to imap1[k]-th unique nonzero in the merged matrix.
6096: imap2[]: similar to imap1[], but for Set2.
6097: Note we order nonzeros row-by-row and from left to right.
6098: */
6099: static PetscErrorCode MatMergeEntries_Internal(Mat mat, const PetscInt j1[], const PetscInt j2[], const PetscCount rowBegin1[], const PetscCount rowEnd1[], const PetscCount rowBegin2[], const PetscCount rowEnd2[], const PetscCount jmap1[], const PetscCount jmap2[], PetscCount imap1[], PetscCount imap2[], PetscInt i[], PetscInt j[])
6100: {
6101: PetscInt r, m; /* Row index of mat */
6102: PetscCount t, t1, t2, b1, e1, b2, e2;
6104: PetscFunctionBegin;
6105: PetscCall(MatGetLocalSize(mat, &m, NULL));
6106: t1 = t2 = t = 0; /* Count unique nonzeros of in Set1, Set1 and the merged respectively */
6107: i[0] = 0;
6108: for (r = 0; r < m; r++) { /* Do row by row merging */
6109: b1 = rowBegin1[r];
6110: e1 = rowEnd1[r];
6111: b2 = rowBegin2[r];
6112: e2 = rowEnd2[r];
6113: while (b1 < e1 && b2 < e2) {
6114: if (j1[b1] == j2[b2]) { /* Same column index and hence same nonzero */
6115: j[t] = j1[b1];
6116: imap1[t1] = t;
6117: imap2[t2] = t;
6118: b1 += jmap1[t1 + 1] - jmap1[t1]; /* Jump to next unique local nonzero */
6119: b2 += jmap2[t2 + 1] - jmap2[t2]; /* Jump to next unique remote nonzero */
6120: t1++;
6121: t2++;
6122: t++;
6123: } else if (j1[b1] < j2[b2]) {
6124: j[t] = j1[b1];
6125: imap1[t1] = t;
6126: b1 += jmap1[t1 + 1] - jmap1[t1];
6127: t1++;
6128: t++;
6129: } else {
6130: j[t] = j2[b2];
6131: imap2[t2] = t;
6132: b2 += jmap2[t2 + 1] - jmap2[t2];
6133: t2++;
6134: t++;
6135: }
6136: }
6137: /* Merge the remaining in either j1[] or j2[] */
6138: while (b1 < e1) {
6139: j[t] = j1[b1];
6140: imap1[t1] = t;
6141: b1 += jmap1[t1 + 1] - jmap1[t1];
6142: t1++;
6143: t++;
6144: }
6145: while (b2 < e2) {
6146: j[t] = j2[b2];
6147: imap2[t2] = t;
6148: b2 += jmap2[t2 + 1] - jmap2[t2];
6149: t2++;
6150: t++;
6151: }
6152: PetscCall(PetscIntCast(t, i + r + 1));
6153: }
6154: PetscFunctionReturn(PETSC_SUCCESS);
6155: }
6157: /*
6158: Split nonzeros in a block of local rows into two subsets: those in the diagonal block and those in the off-diagonal block
6160: Input Parameters:
6161: mat: an MPI matrix that provides row and column layout information for splitting. Let's say its number of local rows is m.
6162: n,i[],j[],perm[]: there are n input entries, belonging to m rows. Row/col indices of the entries are stored in i[] and j[]
6163: respectively, along with a permutation array perm[]. Length of the i[],j[],perm[] arrays is n.
6165: i[] is already sorted, but within a row, j[] is not sorted and might have repeats.
6166: i[] might contain negative indices at the beginning, which means the corresponding entries should be ignored in the splitting.
6168: Output Parameters:
6169: j[],perm[]: the routine needs to sort j[] within each row along with perm[].
6170: rowBegin[],rowMid[],rowEnd[]: of length m, and the memory is preallocated and zeroed by the caller.
6171: They contain indices pointing to j[]. For 0<=r<m, [rowBegin[r],rowMid[r]) point to begin/end entries of row r of the diagonal block,
6172: and [rowMid[r],rowEnd[r]) point to begin/end entries of row r of the off-diagonal block.
6174: Aperm[],Ajmap[],Atot,Annz: Arrays are allocated by this routine.
6175: Atot: number of entries belonging to the diagonal block.
6176: Annz: number of unique nonzeros belonging to the diagonal block.
6177: Aperm[Atot] stores values from perm[] for entries belonging to the diagonal block. Length of Aperm[] is Atot, though it may also count
6178: repeats (i.e., same 'i,j' pair).
6179: Ajmap[Annz+1] stores the number of repeats of each unique entry belonging to the diagonal block. More precisely, Ajmap[t+1] - Ajmap[t]
6180: is the number of repeats for the t-th unique entry in the diagonal block. Ajmap[0] is always 0.
6182: Atot: number of entries belonging to the diagonal block
6183: Annz: number of unique nonzeros belonging to the diagonal block.
6185: Bperm[], Bjmap[], Btot, Bnnz are similar but for the off-diagonal block.
6187: Aperm[],Bperm[],Ajmap[] and Bjmap[] are allocated separately by this routine with PetscMalloc1().
6188: */
6189: static PetscErrorCode MatSplitEntries_Internal(Mat mat, PetscCount n, const PetscInt i[], PetscInt j[], PetscCount perm[], PetscCount rowBegin[], PetscCount rowMid[], PetscCount rowEnd[], PetscCount *Atot_, PetscCount **Aperm_, PetscCount *Annz_, PetscCount **Ajmap_, PetscCount *Btot_, PetscCount **Bperm_, PetscCount *Bnnz_, PetscCount **Bjmap_)
6190: {
6191: PetscInt cstart, cend, rstart, rend, row, col;
6192: PetscCount Atot = 0, Btot = 0; /* Total number of nonzeros in the diagonal and off-diagonal blocks */
6193: PetscCount Annz = 0, Bnnz = 0; /* Number of unique nonzeros in the diagonal and off-diagonal blocks */
6194: PetscCount k, m, p, q, r, s, mid;
6195: PetscCount *Aperm, *Bperm, *Ajmap, *Bjmap;
6197: PetscFunctionBegin;
6198: PetscCall(PetscLayoutGetRange(mat->rmap, &rstart, &rend));
6199: PetscCall(PetscLayoutGetRange(mat->cmap, &cstart, &cend));
6200: m = rend - rstart;
6202: /* Skip negative rows */
6203: for (k = 0; k < n; k++)
6204: if (i[k] >= 0) break;
6206: /* Process [k,n): sort and partition each local row into diag and offdiag portions,
6207: fill rowBegin[], rowMid[], rowEnd[], and count Atot, Btot, Annz, Bnnz.
6208: */
6209: while (k < n) {
6210: row = i[k];
6211: /* Entries in [k,s) are in one row. Shift diagonal block col indices so that diag is ahead of offdiag after sorting the row */
6212: for (s = k; s < n; s++)
6213: if (i[s] != row) break;
6215: /* Shift diag columns to range of [-PETSC_INT_MAX, -1] */
6216: for (p = k; p < s; p++) {
6217: if (j[p] >= cstart && j[p] < cend) j[p] -= PETSC_INT_MAX;
6218: }
6219: PetscCall(PetscSortIntWithCountArray(s - k, j + k, perm + k));
6220: PetscCall(PetscSortedIntUpperBound(j, k, s, -1, &mid)); /* Separate [k,s) into [k,mid) for diag and [mid,s) for offdiag */
6221: rowBegin[row - rstart] = k;
6222: rowMid[row - rstart] = mid;
6223: rowEnd[row - rstart] = s;
6224: PetscCheck(k == s || j[s - 1] < mat->cmap->N, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Column index %" PetscInt_FMT " is >= matrix column size %" PetscInt_FMT, j[s - 1], mat->cmap->N);
6226: /* Count nonzeros of this diag/offdiag row, which might have repeats */
6227: Atot += mid - k;
6228: Btot += s - mid;
6230: /* Count unique nonzeros of this diag row */
6231: for (p = k; p < mid;) {
6232: col = j[p];
6233: do {
6234: j[p] += PETSC_INT_MAX; /* Revert the modified diagonal indices */
6235: p++;
6236: } while (p < mid && j[p] == col);
6237: Annz++;
6238: }
6240: /* Count unique nonzeros of this offdiag row */
6241: for (p = mid; p < s;) {
6242: col = j[p];
6243: do {
6244: p++;
6245: } while (p < s && j[p] == col);
6246: Bnnz++;
6247: }
6248: k = s;
6249: }
6251: /* Allocation according to Atot, Btot, Annz, Bnnz */
6252: PetscCall(PetscMalloc1(Atot, &Aperm));
6253: PetscCall(PetscMalloc1(Btot, &Bperm));
6254: PetscCall(PetscMalloc1(Annz + 1, &Ajmap));
6255: PetscCall(PetscMalloc1(Bnnz + 1, &Bjmap));
6257: /* Re-scan indices and copy diag/offdiag permutation indices to Aperm, Bperm and also fill Ajmap and Bjmap */
6258: Ajmap[0] = Bjmap[0] = Atot = Btot = Annz = Bnnz = 0;
6259: for (r = 0; r < m; r++) {
6260: k = rowBegin[r];
6261: mid = rowMid[r];
6262: s = rowEnd[r];
6263: PetscCall(PetscArraycpy(PetscSafePointerPlusOffset(Aperm, Atot), PetscSafePointerPlusOffset(perm, k), mid - k));
6264: PetscCall(PetscArraycpy(PetscSafePointerPlusOffset(Bperm, Btot), PetscSafePointerPlusOffset(perm, mid), s - mid));
6265: Atot += mid - k;
6266: Btot += s - mid;
6268: /* Scan column indices in this row and find out how many repeats each unique nonzero has */
6269: for (p = k; p < mid;) {
6270: col = j[p];
6271: q = p;
6272: do {
6273: p++;
6274: } while (p < mid && j[p] == col);
6275: Ajmap[Annz + 1] = Ajmap[Annz] + (p - q);
6276: Annz++;
6277: }
6279: for (p = mid; p < s;) {
6280: col = j[p];
6281: q = p;
6282: do {
6283: p++;
6284: } while (p < s && j[p] == col);
6285: Bjmap[Bnnz + 1] = Bjmap[Bnnz] + (p - q);
6286: Bnnz++;
6287: }
6288: }
6289: /* Output */
6290: *Aperm_ = Aperm;
6291: *Annz_ = Annz;
6292: *Atot_ = Atot;
6293: *Ajmap_ = Ajmap;
6294: *Bperm_ = Bperm;
6295: *Bnnz_ = Bnnz;
6296: *Btot_ = Btot;
6297: *Bjmap_ = Bjmap;
6298: PetscFunctionReturn(PETSC_SUCCESS);
6299: }
6301: /*
6302: Expand the jmap[] array to make a new one in view of nonzeros in the merged matrix
6304: Input Parameters:
6305: nnz1: number of unique nonzeros in a set that was used to produce imap[], jmap[]
6306: nnz: number of unique nonzeros in the merged matrix
6307: imap[nnz1]: i-th nonzero in the set is the imap[i]-th nonzero in the merged matrix
6308: jmap[nnz1+1]: i-th nonzero in the set has jmap[i+1] - jmap[i] repeats in the set
6310: Output Parameter: (memory is allocated by the caller)
6311: jmap_new[nnz+1]: i-th nonzero in the merged matrix has jmap_new[i+1] - jmap_new[i] repeats in the set
6313: Example:
6314: nnz1 = 4
6315: nnz = 6
6316: imap = [1,3,4,5]
6317: jmap = [0,3,5,6,7]
6318: then,
6319: jmap_new = [0,0,3,3,5,6,7]
6320: */
6321: static PetscErrorCode ExpandJmap_Internal(PetscCount nnz1, PetscCount nnz, const PetscCount imap[], const PetscCount jmap[], PetscCount jmap_new[])
6322: {
6323: PetscCount k, p;
6325: PetscFunctionBegin;
6326: jmap_new[0] = 0;
6327: p = nnz; /* p loops over jmap_new[] backwards */
6328: for (k = nnz1 - 1; k >= 0; k--) { /* k loops over imap[] */
6329: for (; p > imap[k]; p--) jmap_new[p] = jmap[k + 1];
6330: }
6331: for (; p >= 0; p--) jmap_new[p] = jmap[0];
6332: PetscFunctionReturn(PETSC_SUCCESS);
6333: }
6335: static PetscErrorCode MatCOOStructDestroy_MPIAIJ(PetscCtxRt data)
6336: {
6337: MatCOOStruct_MPIAIJ *coo = *(MatCOOStruct_MPIAIJ **)data;
6339: PetscFunctionBegin;
6340: PetscCall(PetscSFDestroy(&coo->sf));
6341: PetscCall(PetscFree(coo->Aperm1));
6342: PetscCall(PetscFree(coo->Bperm1));
6343: PetscCall(PetscFree(coo->Ajmap1));
6344: PetscCall(PetscFree(coo->Bjmap1));
6345: PetscCall(PetscFree(coo->Aimap2));
6346: PetscCall(PetscFree(coo->Bimap2));
6347: PetscCall(PetscFree(coo->Aperm2));
6348: PetscCall(PetscFree(coo->Bperm2));
6349: PetscCall(PetscFree(coo->Ajmap2));
6350: PetscCall(PetscFree(coo->Bjmap2));
6351: PetscCall(PetscFree(coo->Cperm1));
6352: PetscCall(PetscFree2(coo->sendbuf, coo->recvbuf));
6353: PetscCall(PetscFree(coo));
6354: PetscFunctionReturn(PETSC_SUCCESS);
6355: }
6357: PetscErrorCode MatSetPreallocationCOO_MPIAIJ(Mat mat, PetscCount coo_n, PetscInt coo_i[], PetscInt coo_j[])
6358: {
6359: MPI_Comm comm;
6360: PetscMPIInt rank, size;
6361: PetscInt m, n, M, N, rstart, rend, cstart, cend; /* Sizes, indices of row/col, therefore with type PetscInt */
6362: PetscCount k, p, q, rem; /* Loop variables over coo arrays */
6363: Mat_MPIAIJ *mpiaij = (Mat_MPIAIJ *)mat->data;
6364: PetscContainer container;
6365: MatCOOStruct_MPIAIJ *coo;
6367: PetscFunctionBegin;
6368: PetscCall(PetscFree(mpiaij->garray));
6369: PetscCall(VecDestroy(&mpiaij->lvec));
6370: #if defined(PETSC_USE_CTABLE)
6371: PetscCall(PetscHMapIDestroy(&mpiaij->colmap));
6372: #else
6373: PetscCall(PetscFree(mpiaij->colmap));
6374: #endif
6375: PetscCall(VecScatterDestroy(&mpiaij->Mvctx));
6376: mat->assembled = PETSC_FALSE;
6377: mat->was_assembled = PETSC_FALSE;
6379: PetscCall(PetscObjectGetComm((PetscObject)mat, &comm));
6380: PetscCallMPI(MPI_Comm_size(comm, &size));
6381: PetscCallMPI(MPI_Comm_rank(comm, &rank));
6382: PetscCall(PetscLayoutSetUp(mat->rmap));
6383: PetscCall(PetscLayoutSetUp(mat->cmap));
6384: PetscCall(PetscLayoutGetRange(mat->rmap, &rstart, &rend));
6385: PetscCall(PetscLayoutGetRange(mat->cmap, &cstart, &cend));
6386: PetscCall(MatGetLocalSize(mat, &m, &n));
6387: PetscCall(MatGetSize(mat, &M, &N));
6389: /* Sort (i,j) by row along with a permutation array, so that the to-be-ignored */
6390: /* entries come first, then local rows, then remote rows. */
6391: PetscCount n1 = coo_n, *perm1;
6392: PetscInt *i1 = coo_i, *j1 = coo_j;
6394: PetscCall(PetscMalloc1(n1, &perm1));
6395: for (k = 0; k < n1; k++) perm1[k] = k;
6397: /* Manipulate indices so that entries with negative row or col indices will have smallest
6398: row indices, local entries will have greater but negative row indices, and remote entries
6399: will have positive row indices.
6400: */
6401: for (k = 0; k < n1; k++) {
6402: if (i1[k] < 0 || j1[k] < 0) i1[k] = PETSC_INT_MIN; /* e.g., -2^31, minimal to move them ahead */
6403: else if (i1[k] >= rstart && i1[k] < rend) i1[k] -= PETSC_INT_MAX; /* e.g., minus 2^31-1 to shift local rows to range of [-PETSC_INT_MAX, -1] */
6404: else {
6405: PetscCheck(!mat->nooffprocentries, PETSC_COMM_SELF, PETSC_ERR_USER_INPUT, "MAT_NO_OFF_PROC_ENTRIES is set but insert to remote rows");
6406: if (mpiaij->donotstash) i1[k] = PETSC_INT_MIN; /* Ignore offproc entries as if they had negative indices */
6407: }
6408: }
6410: /* Sort by row; after that, [0,k) have ignored entries, [k,rem) have local rows and [rem,n1) have remote rows */
6411: PetscCall(PetscSortIntWithIntCountArrayPair(n1, i1, j1, perm1));
6413: /* Advance k to the first entry we need to take care of */
6414: for (k = 0; k < n1; k++)
6415: if (i1[k] > PETSC_INT_MIN) break;
6416: PetscCount i1start = k;
6418: PetscCall(PetscSortedIntUpperBound(i1, k, n1, rend - 1 - PETSC_INT_MAX, &rem)); /* rem is upper bound of the last local row */
6419: for (; k < rem; k++) i1[k] += PETSC_INT_MAX; /* Revert row indices of local rows*/
6421: PetscCheck(n1 == 0 || i1[n1 - 1] < M, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "COO row index %" PetscInt_FMT " is >= the matrix row size %" PetscInt_FMT, i1[n1 - 1], M);
6423: /* Send remote rows to their owner */
6424: /* Find which rows should be sent to which remote ranks*/
6425: PetscInt nsend = 0; /* Number of MPI ranks to send data to */
6426: PetscMPIInt *sendto; /* [nsend], storing remote ranks */
6427: PetscInt *nentries; /* [nsend], storing number of entries sent to remote ranks; Assume PetscInt is big enough for this count, and error if not */
6428: const PetscInt *ranges;
6429: PetscInt maxNsend = size >= 128 ? 128 : size; /* Assume max 128 neighbors; realloc when needed */
6431: PetscCall(PetscLayoutGetRanges(mat->rmap, &ranges));
6432: PetscCall(PetscMalloc2(maxNsend, &sendto, maxNsend, &nentries));
6433: for (k = rem; k < n1;) {
6434: PetscMPIInt owner;
6435: PetscInt firstRow, lastRow;
6437: /* Locate a row range */
6438: firstRow = i1[k]; /* first row of this owner */
6439: PetscCall(PetscLayoutFindOwner(mat->rmap, firstRow, &owner));
6440: lastRow = ranges[owner + 1] - 1; /* last row of this owner */
6442: /* Find the first index 'p' in [k,n) with i1[p] belonging to next owner */
6443: PetscCall(PetscSortedIntUpperBound(i1, k, n1, lastRow, &p));
6445: /* All entries in [k,p) belong to this remote owner */
6446: if (nsend >= maxNsend) { /* Double the remote ranks arrays if not long enough */
6447: PetscMPIInt *sendto2;
6448: PetscInt *nentries2;
6449: PetscInt maxNsend2 = (maxNsend <= size / 2) ? maxNsend * 2 : size;
6451: PetscCall(PetscMalloc2(maxNsend2, &sendto2, maxNsend2, &nentries2));
6452: PetscCall(PetscArraycpy(sendto2, sendto, maxNsend));
6453: PetscCall(PetscArraycpy(nentries2, nentries, maxNsend));
6454: PetscCall(PetscFree2(sendto, nentries));
6455: sendto = sendto2;
6456: nentries = nentries2;
6457: maxNsend = maxNsend2;
6458: }
6459: sendto[nsend] = owner;
6460: PetscCall(PetscIntCast(p - k, &nentries[nsend]));
6461: nsend++;
6462: k = p;
6463: }
6465: /* Build 1st SF to know offsets on remote to send data */
6466: PetscSF sf1;
6467: PetscInt nroots = 1, nroots2 = 0;
6468: PetscInt nleaves = nsend, nleaves2 = 0;
6469: PetscInt *offsets;
6470: PetscSFNode *iremote;
6472: PetscCall(PetscSFCreate(comm, &sf1));
6473: PetscCall(PetscMalloc1(nsend, &iremote));
6474: PetscCall(PetscMalloc1(nsend, &offsets));
6475: for (k = 0; k < nsend; k++) {
6476: iremote[k].rank = sendto[k];
6477: iremote[k].index = 0;
6478: nleaves2 += nentries[k];
6479: PetscCheck(nleaves2 >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Number of SF leaves is too large for PetscInt");
6480: }
6481: PetscCall(PetscSFSetGraph(sf1, nroots, nleaves, NULL, PETSC_OWN_POINTER, iremote, PETSC_OWN_POINTER));
6482: PetscCall(PetscSFFetchAndOpWithMemTypeBegin(sf1, MPIU_INT, PETSC_MEMTYPE_HOST, &nroots2 /*rootdata*/, PETSC_MEMTYPE_HOST, nentries /*leafdata*/, PETSC_MEMTYPE_HOST, offsets /*leafupdate*/, MPI_SUM));
6483: PetscCall(PetscSFFetchAndOpEnd(sf1, MPIU_INT, &nroots2, nentries, offsets, MPI_SUM)); /* Would nroots2 overflow, we check offsets[] below */
6484: PetscCall(PetscSFDestroy(&sf1));
6485: PetscAssert(nleaves2 == n1 - rem, PETSC_COMM_SELF, PETSC_ERR_PLIB, "nleaves2 %" PetscInt_FMT " != number of remote entries %" PetscCount_FMT, nleaves2, n1 - rem);
6487: /* Build 2nd SF to send remote COOs to their owner */
6488: PetscSF sf2;
6489: nroots = nroots2;
6490: nleaves = nleaves2;
6491: PetscCall(PetscSFCreate(comm, &sf2));
6492: PetscCall(PetscSFSetFromOptions(sf2));
6493: PetscCall(PetscMalloc1(nleaves, &iremote));
6494: p = 0;
6495: for (k = 0; k < nsend; k++) {
6496: PetscCheck(offsets[k] >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Number of SF roots is too large for PetscInt");
6497: for (q = 0; q < nentries[k]; q++, p++) {
6498: iremote[p].rank = sendto[k];
6499: PetscCall(PetscIntCast(offsets[k] + q, &iremote[p].index));
6500: }
6501: }
6502: PetscCall(PetscSFSetGraph(sf2, nroots, nleaves, NULL, PETSC_OWN_POINTER, iremote, PETSC_OWN_POINTER));
6504: /* Send the remote COOs to their owner */
6505: PetscInt n2 = nroots, *i2, *j2; /* Buffers for received COOs from other ranks, along with a permutation array */
6506: PetscCount *perm2; /* Though PetscInt is enough for remote entries, we use PetscCount here as we want to reuse MatSplitEntries_Internal() */
6507: PetscCall(PetscMalloc3(n2, &i2, n2, &j2, n2, &perm2));
6508: PetscAssert(rem == 0 || i1 != NULL, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Cannot add nonzero offset to null");
6509: PetscAssert(rem == 0 || j1 != NULL, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Cannot add nonzero offset to null");
6510: PetscInt *i1prem = PetscSafePointerPlusOffset(i1, rem);
6511: PetscInt *j1prem = PetscSafePointerPlusOffset(j1, rem);
6512: PetscCall(PetscSFReduceWithMemTypeBegin(sf2, MPIU_INT, PETSC_MEMTYPE_HOST, i1prem, PETSC_MEMTYPE_HOST, i2, MPI_REPLACE));
6513: PetscCall(PetscSFReduceEnd(sf2, MPIU_INT, i1prem, i2, MPI_REPLACE));
6514: PetscCall(PetscSFReduceWithMemTypeBegin(sf2, MPIU_INT, PETSC_MEMTYPE_HOST, j1prem, PETSC_MEMTYPE_HOST, j2, MPI_REPLACE));
6515: PetscCall(PetscSFReduceEnd(sf2, MPIU_INT, j1prem, j2, MPI_REPLACE));
6517: PetscCall(PetscFree(offsets));
6518: PetscCall(PetscFree2(sendto, nentries));
6520: /* Sort received COOs by row along with the permutation array */
6521: for (k = 0; k < n2; k++) perm2[k] = k;
6522: PetscCall(PetscSortIntWithIntCountArrayPair(n2, i2, j2, perm2));
6524: /* sf2 only sends contiguous leafdata to contiguous rootdata. We record the permutation which will be used to fill leafdata */
6525: PetscCount *Cperm1;
6526: PetscAssert(rem == 0 || perm1 != NULL, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Cannot add nonzero offset to null");
6527: PetscCount *perm1prem = PetscSafePointerPlusOffset(perm1, rem);
6528: PetscCall(PetscMalloc1(nleaves, &Cperm1));
6529: PetscCall(PetscArraycpy(Cperm1, perm1prem, nleaves));
6531: /* Support for HYPRE matrices, kind of a hack.
6532: Swap min column with diagonal so that diagonal values will go first */
6533: PetscBool hypre;
6534: PetscCall(PetscStrcmp("_internal_COO_mat_for_hypre", ((PetscObject)mat)->name, &hypre));
6535: if (hypre) {
6536: PetscInt *minj;
6537: PetscBT hasdiag;
6539: PetscCall(PetscBTCreate(m, &hasdiag));
6540: PetscCall(PetscMalloc1(m, &minj));
6541: for (k = 0; k < m; k++) minj[k] = PETSC_INT_MAX;
6542: for (k = i1start; k < rem; k++) {
6543: if (j1[k] < cstart || j1[k] >= cend) continue;
6544: const PetscInt rindex = i1[k] - rstart;
6545: if ((j1[k] - cstart) == rindex) PetscCall(PetscBTSet(hasdiag, rindex));
6546: minj[rindex] = PetscMin(minj[rindex], j1[k]);
6547: }
6548: for (k = 0; k < n2; k++) {
6549: if (j2[k] < cstart || j2[k] >= cend) continue;
6550: const PetscInt rindex = i2[k] - rstart;
6551: if ((j2[k] - cstart) == rindex) PetscCall(PetscBTSet(hasdiag, rindex));
6552: minj[rindex] = PetscMin(minj[rindex], j2[k]);
6553: }
6554: for (k = i1start; k < rem; k++) {
6555: const PetscInt rindex = i1[k] - rstart;
6556: if (j1[k] < cstart || j1[k] >= cend || !PetscBTLookup(hasdiag, rindex)) continue;
6557: if (j1[k] == minj[rindex]) j1[k] = i1[k] + (cstart - rstart);
6558: else if ((j1[k] - cstart) == rindex) j1[k] = minj[rindex];
6559: }
6560: for (k = 0; k < n2; k++) {
6561: const PetscInt rindex = i2[k] - rstart;
6562: if (j2[k] < cstart || j2[k] >= cend || !PetscBTLookup(hasdiag, rindex)) continue;
6563: if (j2[k] == minj[rindex]) j2[k] = i2[k] + (cstart - rstart);
6564: else if ((j2[k] - cstart) == rindex) j2[k] = minj[rindex];
6565: }
6566: PetscCall(PetscBTDestroy(&hasdiag));
6567: PetscCall(PetscFree(minj));
6568: }
6570: /* Split local COOs and received COOs into diag/offdiag portions */
6571: PetscCount *rowBegin1, *rowMid1, *rowEnd1;
6572: PetscCount *Ajmap1, *Aperm1, *Bjmap1, *Bperm1;
6573: PetscCount Annz1, Bnnz1, Atot1, Btot1;
6574: PetscCount *rowBegin2, *rowMid2, *rowEnd2;
6575: PetscCount *Ajmap2, *Aperm2, *Bjmap2, *Bperm2;
6576: PetscCount Annz2, Bnnz2, Atot2, Btot2;
6578: PetscCall(PetscCalloc3(m, &rowBegin1, m, &rowMid1, m, &rowEnd1));
6579: PetscCall(PetscCalloc3(m, &rowBegin2, m, &rowMid2, m, &rowEnd2));
6580: PetscCall(MatSplitEntries_Internal(mat, rem, i1, j1, perm1, rowBegin1, rowMid1, rowEnd1, &Atot1, &Aperm1, &Annz1, &Ajmap1, &Btot1, &Bperm1, &Bnnz1, &Bjmap1));
6581: PetscCall(MatSplitEntries_Internal(mat, n2, i2, j2, perm2, rowBegin2, rowMid2, rowEnd2, &Atot2, &Aperm2, &Annz2, &Ajmap2, &Btot2, &Bperm2, &Bnnz2, &Bjmap2));
6583: /* Merge local COOs with received COOs: diag with diag, offdiag with offdiag */
6584: PetscInt *Ai, *Bi;
6585: PetscInt *Aj, *Bj;
6587: PetscCall(PetscMalloc1(m + 1, &Ai));
6588: PetscCall(PetscMalloc1(m + 1, &Bi));
6589: PetscCall(PetscMalloc1(Annz1 + Annz2, &Aj)); /* Since local and remote entries might have dups, we might allocate excess memory */
6590: PetscCall(PetscMalloc1(Bnnz1 + Bnnz2, &Bj));
6592: PetscCount *Aimap1, *Bimap1, *Aimap2, *Bimap2;
6593: PetscCall(PetscMalloc1(Annz1, &Aimap1));
6594: PetscCall(PetscMalloc1(Bnnz1, &Bimap1));
6595: PetscCall(PetscMalloc1(Annz2, &Aimap2));
6596: PetscCall(PetscMalloc1(Bnnz2, &Bimap2));
6598: PetscCall(MatMergeEntries_Internal(mat, j1, j2, rowBegin1, rowMid1, rowBegin2, rowMid2, Ajmap1, Ajmap2, Aimap1, Aimap2, Ai, Aj));
6599: PetscCall(MatMergeEntries_Internal(mat, j1, j2, rowMid1, rowEnd1, rowMid2, rowEnd2, Bjmap1, Bjmap2, Bimap1, Bimap2, Bi, Bj));
6601: /* Expand Ajmap1/Bjmap1 to make them based off nonzeros in A/B, since we */
6602: /* expect nonzeros in A/B most likely have local contributing entries */
6603: PetscInt Annz = Ai[m];
6604: PetscInt Bnnz = Bi[m];
6605: PetscCount *Ajmap1_new, *Bjmap1_new;
6607: PetscCall(PetscMalloc1(Annz + 1, &Ajmap1_new));
6608: PetscCall(PetscMalloc1(Bnnz + 1, &Bjmap1_new));
6610: PetscCall(ExpandJmap_Internal(Annz1, Annz, Aimap1, Ajmap1, Ajmap1_new));
6611: PetscCall(ExpandJmap_Internal(Bnnz1, Bnnz, Bimap1, Bjmap1, Bjmap1_new));
6613: PetscCall(PetscFree(Aimap1));
6614: PetscCall(PetscFree(Ajmap1));
6615: PetscCall(PetscFree(Bimap1));
6616: PetscCall(PetscFree(Bjmap1));
6617: PetscCall(PetscFree3(rowBegin1, rowMid1, rowEnd1));
6618: PetscCall(PetscFree3(rowBegin2, rowMid2, rowEnd2));
6619: PetscCall(PetscFree(perm1));
6620: PetscCall(PetscFree3(i2, j2, perm2));
6622: Ajmap1 = Ajmap1_new;
6623: Bjmap1 = Bjmap1_new;
6625: /* Reallocate Aj, Bj once we know actual numbers of unique nonzeros in A and B */
6626: if (Annz < Annz1 + Annz2) {
6627: PetscInt *Aj_new;
6628: PetscCall(PetscMalloc1(Annz, &Aj_new));
6629: PetscCall(PetscArraycpy(Aj_new, Aj, Annz));
6630: PetscCall(PetscFree(Aj));
6631: Aj = Aj_new;
6632: }
6634: if (Bnnz < Bnnz1 + Bnnz2) {
6635: PetscInt *Bj_new;
6636: PetscCall(PetscMalloc1(Bnnz, &Bj_new));
6637: PetscCall(PetscArraycpy(Bj_new, Bj, Bnnz));
6638: PetscCall(PetscFree(Bj));
6639: Bj = Bj_new;
6640: }
6642: /* Create new submatrices for on-process and off-process coupling */
6643: PetscScalar *Aa, *Ba;
6644: MatType rtype;
6645: Mat_SeqAIJ *a, *b;
6646: PetscObjectState state;
6647: PetscCall(PetscCalloc1(Annz, &Aa)); /* Zero matrix on device */
6648: PetscCall(PetscCalloc1(Bnnz, &Ba));
6649: /* make Aj[] local, i.e, based off the start column of the diagonal portion */
6650: if (cstart) {
6651: for (k = 0; k < Annz; k++) Aj[k] -= cstart;
6652: }
6654: PetscCall(MatGetRootType_Private(mat, &rtype));
6656: MatSeqXAIJGetOptions_Private(mpiaij->A);
6657: PetscCall(MatDestroy(&mpiaij->A));
6658: PetscCall(MatCreateSeqAIJWithArrays(PETSC_COMM_SELF, m, n, Ai, Aj, Aa, &mpiaij->A));
6659: PetscCall(MatSetBlockSizesFromMats(mpiaij->A, mat, mat));
6660: MatSeqXAIJRestoreOptions_Private(mpiaij->A);
6662: MatSeqXAIJGetOptions_Private(mpiaij->B);
6663: PetscCall(MatDestroy(&mpiaij->B));
6664: PetscCall(MatCreateSeqAIJWithArrays(PETSC_COMM_SELF, m, mat->cmap->N, Bi, Bj, Ba, &mpiaij->B));
6665: PetscCall(MatSetBlockSizesFromMats(mpiaij->B, mat, mat));
6666: MatSeqXAIJRestoreOptions_Private(mpiaij->B);
6668: PetscCall(MatSetUpMultiply_MPIAIJ(mat));
6669: mat->was_assembled = PETSC_TRUE; // was_assembled in effect means the Mvctx is built; doing so avoids redundant MatSetUpMultiply_MPIAIJ
6670: state = mpiaij->A->nonzerostate + mpiaij->B->nonzerostate;
6671: PetscCallMPI(MPIU_Allreduce(&state, &mat->nonzerostate, 1, MPIU_INT64, MPI_SUM, PetscObjectComm((PetscObject)mat)));
6673: a = (Mat_SeqAIJ *)mpiaij->A->data;
6674: b = (Mat_SeqAIJ *)mpiaij->B->data;
6675: a->free_a = PETSC_TRUE;
6676: a->free_ij = PETSC_TRUE;
6677: b->free_a = PETSC_TRUE;
6678: b->free_ij = PETSC_TRUE;
6679: a->maxnz = a->nz;
6680: b->maxnz = b->nz;
6682: /* conversion must happen AFTER multiply setup */
6683: PetscCall(MatConvert(mpiaij->A, rtype, MAT_INPLACE_MATRIX, &mpiaij->A));
6684: PetscCall(MatConvert(mpiaij->B, rtype, MAT_INPLACE_MATRIX, &mpiaij->B));
6685: PetscCall(VecDestroy(&mpiaij->lvec));
6686: PetscCall(MatCreateVecs(mpiaij->B, &mpiaij->lvec, NULL));
6688: // Put the COO struct in a container and then attach that to the matrix
6689: PetscCall(PetscMalloc1(1, &coo));
6690: coo->n = coo_n;
6691: coo->sf = sf2;
6692: coo->sendlen = nleaves;
6693: coo->recvlen = nroots;
6694: coo->Annz = Annz;
6695: coo->Bnnz = Bnnz;
6696: coo->Annz2 = Annz2;
6697: coo->Bnnz2 = Bnnz2;
6698: coo->Atot1 = Atot1;
6699: coo->Atot2 = Atot2;
6700: coo->Btot1 = Btot1;
6701: coo->Btot2 = Btot2;
6702: coo->Ajmap1 = Ajmap1;
6703: coo->Aperm1 = Aperm1;
6704: coo->Bjmap1 = Bjmap1;
6705: coo->Bperm1 = Bperm1;
6706: coo->Aimap2 = Aimap2;
6707: coo->Ajmap2 = Ajmap2;
6708: coo->Aperm2 = Aperm2;
6709: coo->Bimap2 = Bimap2;
6710: coo->Bjmap2 = Bjmap2;
6711: coo->Bperm2 = Bperm2;
6712: coo->Cperm1 = Cperm1;
6713: // Allocate in preallocation. If not used, it has zero cost on host
6714: PetscCall(PetscMalloc2(coo->sendlen, &coo->sendbuf, coo->recvlen, &coo->recvbuf));
6715: PetscCall(PetscContainerCreate(PETSC_COMM_SELF, &container));
6716: PetscCall(PetscContainerSetPointer(container, coo));
6717: PetscCall(PetscContainerSetCtxDestroy(container, MatCOOStructDestroy_MPIAIJ));
6718: PetscCall(PetscObjectCompose((PetscObject)mat, "__PETSc_MatCOOStruct_Host", (PetscObject)container));
6719: PetscCall(PetscContainerDestroy(&container));
6720: PetscFunctionReturn(PETSC_SUCCESS);
6721: }
6723: static PetscErrorCode MatSetValuesCOO_MPIAIJ(Mat mat, const PetscScalar v[], InsertMode imode)
6724: {
6725: Mat_MPIAIJ *mpiaij = (Mat_MPIAIJ *)mat->data;
6726: Mat A = mpiaij->A, B = mpiaij->B;
6727: PetscScalar *Aa, *Ba;
6728: PetscScalar *sendbuf, *recvbuf;
6729: const PetscCount *Ajmap1, *Ajmap2, *Aimap2;
6730: const PetscCount *Bjmap1, *Bjmap2, *Bimap2;
6731: const PetscCount *Aperm1, *Aperm2, *Bperm1, *Bperm2;
6732: const PetscCount *Cperm1;
6733: PetscContainer container;
6734: MatCOOStruct_MPIAIJ *coo;
6736: PetscFunctionBegin;
6737: PetscCall(PetscObjectQuery((PetscObject)mat, "__PETSc_MatCOOStruct_Host", (PetscObject *)&container));
6738: PetscCheck(container, PetscObjectComm((PetscObject)mat), PETSC_ERR_PLIB, "Not found MatCOOStruct on this matrix");
6739: PetscCall(PetscContainerGetPointer(container, &coo));
6740: sendbuf = coo->sendbuf;
6741: recvbuf = coo->recvbuf;
6742: Ajmap1 = coo->Ajmap1;
6743: Ajmap2 = coo->Ajmap2;
6744: Aimap2 = coo->Aimap2;
6745: Bjmap1 = coo->Bjmap1;
6746: Bjmap2 = coo->Bjmap2;
6747: Bimap2 = coo->Bimap2;
6748: Aperm1 = coo->Aperm1;
6749: Aperm2 = coo->Aperm2;
6750: Bperm1 = coo->Bperm1;
6751: Bperm2 = coo->Bperm2;
6752: Cperm1 = coo->Cperm1;
6754: PetscCall(MatSeqAIJGetArray(A, &Aa)); /* Might read and write matrix values */
6755: PetscCall(MatSeqAIJGetArray(B, &Ba));
6757: /* Pack entries to be sent to remote */
6758: for (PetscCount i = 0; i < coo->sendlen; i++) sendbuf[i] = v[Cperm1[i]];
6760: /* Send remote entries to their owner and overlap the communication with local computation */
6761: PetscCall(PetscSFReduceWithMemTypeBegin(coo->sf, MPIU_SCALAR, PETSC_MEMTYPE_HOST, sendbuf, PETSC_MEMTYPE_HOST, recvbuf, MPI_REPLACE));
6762: /* Add local entries to A and B */
6763: for (PetscCount i = 0; i < coo->Annz; i++) { /* All nonzeros in A are either zero'ed or added with a value (i.e., initialized) */
6764: PetscScalar sum = 0.0; /* Do partial summation first to improve numerical stability */
6765: for (PetscCount k = Ajmap1[i]; k < Ajmap1[i + 1]; k++) sum += v[Aperm1[k]];
6766: Aa[i] = (imode == INSERT_VALUES ? 0.0 : Aa[i]) + sum;
6767: }
6768: for (PetscCount i = 0; i < coo->Bnnz; i++) {
6769: PetscScalar sum = 0.0;
6770: for (PetscCount k = Bjmap1[i]; k < Bjmap1[i + 1]; k++) sum += v[Bperm1[k]];
6771: Ba[i] = (imode == INSERT_VALUES ? 0.0 : Ba[i]) + sum;
6772: }
6773: PetscCall(PetscSFReduceEnd(coo->sf, MPIU_SCALAR, sendbuf, recvbuf, MPI_REPLACE));
6775: /* Add received remote entries to A and B */
6776: for (PetscCount i = 0; i < coo->Annz2; i++) {
6777: for (PetscCount k = Ajmap2[i]; k < Ajmap2[i + 1]; k++) Aa[Aimap2[i]] += recvbuf[Aperm2[k]];
6778: }
6779: for (PetscCount i = 0; i < coo->Bnnz2; i++) {
6780: for (PetscCount k = Bjmap2[i]; k < Bjmap2[i + 1]; k++) Ba[Bimap2[i]] += recvbuf[Bperm2[k]];
6781: }
6782: PetscCall(MatSeqAIJRestoreArray(A, &Aa));
6783: PetscCall(MatSeqAIJRestoreArray(B, &Ba));
6784: PetscFunctionReturn(PETSC_SUCCESS);
6785: }
6787: /*MC
6788: MATMPIAIJ - MATMPIAIJ = "mpiaij" - A matrix type to be used for parallel sparse matrices.
6790: Options Database Keys:
6791: . -mat_type mpiaij - sets the matrix type to `MATMPIAIJ` during a call to `MatSetFromOptions()`
6793: Level: beginner
6795: Notes:
6796: `MatSetValues()` may be called for this matrix type with a `NULL` argument for the numerical values,
6797: in this case the values associated with the rows and columns one passes in are set to zero
6798: in the matrix
6800: `MatSetOptions`(,`MAT_STRUCTURE_ONLY`,`PETSC_TRUE`) may be called for this matrix type. In this no
6801: space is allocated for the nonzero entries and any entries passed with `MatSetValues()` are ignored
6803: .seealso: [](ch_matrices), `Mat`, `MATSEQAIJ`, `MATAIJ`, `MatCreateAIJ()`
6804: M*/
6805: PETSC_EXTERN PetscErrorCode MatCreate_MPIAIJ(Mat B)
6806: {
6807: Mat_MPIAIJ *b;
6808: PetscMPIInt size;
6810: PetscFunctionBegin;
6811: PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)B), &size));
6813: PetscCall(PetscNew(&b));
6814: B->data = (void *)b;
6815: B->ops[0] = MatOps_Values;
6816: B->assembled = PETSC_FALSE;
6817: B->insertmode = NOT_SET_VALUES;
6818: b->size = size;
6820: PetscCallMPI(MPI_Comm_rank(PetscObjectComm((PetscObject)B), &b->rank));
6822: /* build cache for off array entries formed */
6823: PetscCall(MatStashCreate_Private(PetscObjectComm((PetscObject)B), 1, &B->stash));
6825: b->donotstash = PETSC_FALSE;
6826: b->colmap = NULL;
6827: b->garray = NULL;
6828: b->roworiented = PETSC_TRUE;
6830: /* stuff used for matrix vector multiply */
6831: b->lvec = NULL;
6832: b->Mvctx = NULL;
6834: /* stuff for MatGetRow() */
6835: b->rowindices = NULL;
6836: b->rowvalues = NULL;
6837: b->getrowactive = PETSC_FALSE;
6839: /* flexible pointer used in CUSPARSE classes */
6840: b->spptr = NULL;
6842: PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatMPIAIJSetUseScalableIncreaseOverlap_C", MatMPIAIJSetUseScalableIncreaseOverlap_MPIAIJ));
6843: PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatStoreValues_C", MatStoreValues_MPIAIJ));
6844: PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatRetrieveValues_C", MatRetrieveValues_MPIAIJ));
6845: PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatIsTranspose_C", MatIsTranspose_MPIAIJ));
6846: PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatMPIAIJSetPreallocation_C", MatMPIAIJSetPreallocation_MPIAIJ));
6847: PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatResetPreallocation_C", MatResetPreallocation_MPIAIJ));
6848: PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatResetHash_C", MatResetHash_MPIAIJ));
6849: PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatMPIAIJSetPreallocationCSR_C", MatMPIAIJSetPreallocationCSR_MPIAIJ));
6850: PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatDiagonalScaleLocal_C", MatDiagonalScaleLocal_MPIAIJ));
6851: PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatConvert_mpiaij_mpiaijperm_C", MatConvert_MPIAIJ_MPIAIJPERM));
6852: PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatConvert_mpiaij_mpiaijsell_C", MatConvert_MPIAIJ_MPIAIJSELL));
6853: #if defined(PETSC_HAVE_CUDA)
6854: PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatConvert_mpiaij_mpiaijcusparse_C", MatConvert_MPIAIJ_MPIAIJCUSPARSE));
6855: #endif
6856: #if defined(PETSC_HAVE_HIP)
6857: PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatConvert_mpiaij_mpiaijhipsparse_C", MatConvert_MPIAIJ_MPIAIJHIPSPARSE));
6858: #endif
6859: #if defined(PETSC_HAVE_KOKKOS_KERNELS)
6860: PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatConvert_mpiaij_mpiaijkokkos_C", MatConvert_MPIAIJ_MPIAIJKokkos));
6861: #endif
6862: #if defined(PETSC_HAVE_MKL_SPARSE)
6863: PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatConvert_mpiaij_mpiaijmkl_C", MatConvert_MPIAIJ_MPIAIJMKL));
6864: #endif
6865: PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatConvert_mpiaij_mpiaijcrl_C", MatConvert_MPIAIJ_MPIAIJCRL));
6866: PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatConvert_mpiaij_mpibaij_C", MatConvert_MPIAIJ_MPIBAIJ));
6867: PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatConvert_mpiaij_mpisbaij_C", MatConvert_MPIAIJ_MPISBAIJ));
6868: PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatConvert_mpiaij_mpidense_C", MatConvert_MPIAIJ_MPIDense));
6869: #if defined(PETSC_HAVE_ELEMENTAL)
6870: PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatConvert_mpiaij_elemental_C", MatConvert_MPIAIJ_Elemental));
6871: #endif
6872: #if defined(PETSC_HAVE_SCALAPACK) && (defined(PETSC_USE_REAL_SINGLE) || defined(PETSC_USE_REAL_DOUBLE))
6873: PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatConvert_mpiaij_scalapack_C", MatConvert_AIJ_ScaLAPACK));
6874: #endif
6875: PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatConvert_mpiaij_is_C", MatConvert_XAIJ_IS));
6876: PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatConvert_mpiaij_mpisell_C", MatConvert_MPIAIJ_MPISELL));
6877: #if defined(PETSC_HAVE_HYPRE)
6878: PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatConvert_mpiaij_hypre_C", MatConvert_AIJ_HYPRE));
6879: PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatProductSetFromOptions_transpose_mpiaij_mpiaij_C", MatProductSetFromOptions_Transpose_AIJ_AIJ));
6880: #endif
6881: PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatProductSetFromOptions_is_mpiaij_C", MatProductSetFromOptions_IS_XAIJ));
6882: PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatProductSetFromOptions_mpiaij_mpiaij_C", MatProductSetFromOptions_MPIAIJ));
6883: PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatSetPreallocationCOO_C", MatSetPreallocationCOO_MPIAIJ));
6884: PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatSetValuesCOO_C", MatSetValuesCOO_MPIAIJ));
6885: PetscCall(PetscObjectChangeTypeName((PetscObject)B, MATMPIAIJ));
6886: PetscFunctionReturn(PETSC_SUCCESS);
6887: }
6889: /*@
6890: MatCreateMPIAIJWithSplitArrays - creates a `MATMPIAIJ` matrix using arrays that contain the "diagonal"
6891: and "off-diagonal" part of the matrix in CSR format.
6893: Collective
6895: Input Parameters:
6896: + comm - MPI communicator
6897: . m - number of local rows (Cannot be `PETSC_DECIDE`)
6898: . n - This value should be the same as the local size used in creating the
6899: x vector for the matrix-vector product $y = Ax$. (or `PETSC_DECIDE` to have
6900: calculated if `N` is given) For square matrices `n` is almost always `m`.
6901: . M - number of global rows (or `PETSC_DETERMINE` to have calculated if `m` is given)
6902: . N - number of global columns (or `PETSC_DETERMINE` to have calculated if `n` is given)
6903: . i - row indices for "diagonal" portion of matrix; that is i[0] = 0, i[row] = i[row-1] + number of elements in that row of the matrix
6904: . j - column indices, which must be local, i.e., based off the start column of the diagonal portion
6905: . a - matrix values
6906: . oi - row indices for "off-diagonal" portion of matrix; that is oi[0] = 0, oi[row] = oi[row-1] + number of elements in that row of the matrix
6907: . oj - column indices, which must be global, representing global columns in the `MATMPIAIJ` matrix
6908: - oa - matrix values
6910: Output Parameter:
6911: . mat - the matrix
6913: Level: advanced
6915: Notes:
6916: The `i`, `j`, and `a` arrays ARE NOT copied by this routine into the internal format used by PETSc (even in Fortran). The user
6917: must free the arrays once the matrix has been destroyed and not before.
6919: The `i` and `j` indices are 0 based
6921: See `MatCreateAIJ()` for the definition of "diagonal" and "off-diagonal" portion of the matrix
6923: This sets local rows and cannot be used to set off-processor values.
6925: Use of this routine is discouraged because it is inflexible and cumbersome to use. It is extremely rare that a
6926: legacy application natively assembles into exactly this split format. The code to do so is nontrivial and does
6927: not easily support in-place reassembly. It is recommended to use MatSetValues() (or a variant thereof) because
6928: the resulting assembly is easier to implement, will work with any matrix format, and the user does not have to
6929: keep track of the underlying array. Use `MatSetOption`(A,`MAT_NO_OFF_PROC_ENTRIES`,`PETSC_TRUE`) to disable all
6930: communication if it is known that only local entries will be set.
6932: .seealso: [](ch_matrices), `Mat`, `MatCreate()`, `MatCreateSeqAIJ()`, `MatSetValues()`, `MatMPIAIJSetPreallocation()`, `MatMPIAIJSetPreallocationCSR()`,
6933: `MATMPIAIJ`, `MatCreateAIJ()`, `MatCreateMPIAIJWithArrays()`
6934: @*/
6935: PetscErrorCode MatCreateMPIAIJWithSplitArrays(MPI_Comm comm, PetscInt m, PetscInt n, PetscInt M, PetscInt N, PetscInt i[], PetscInt j[], PetscScalar a[], PetscInt oi[], PetscInt oj[], PetscScalar oa[], Mat *mat)
6936: {
6937: Mat_MPIAIJ *maij;
6939: PetscFunctionBegin;
6940: PetscCheck(m >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "local number of rows (m) cannot be PETSC_DECIDE, or negative");
6941: PetscCheck(i[0] == 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "i (row indices) must start with 0");
6942: PetscCheck(oi[0] == 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "oi (row indices) must start with 0");
6943: PetscCall(MatCreate(comm, mat));
6944: PetscCall(MatSetSizes(*mat, m, n, M, N));
6945: PetscCall(MatSetType(*mat, MATMPIAIJ));
6946: maij = (Mat_MPIAIJ *)(*mat)->data;
6948: (*mat)->preallocated = PETSC_TRUE;
6950: PetscCall(PetscLayoutSetUp((*mat)->rmap));
6951: PetscCall(PetscLayoutSetUp((*mat)->cmap));
6953: PetscCall(MatCreateSeqAIJWithArrays(PETSC_COMM_SELF, m, n, i, j, a, &maij->A));
6954: PetscCall(MatCreateSeqAIJWithArrays(PETSC_COMM_SELF, m, (*mat)->cmap->N, oi, oj, oa, &maij->B));
6956: PetscCall(MatSetOption(*mat, MAT_NO_OFF_PROC_ENTRIES, PETSC_TRUE));
6957: PetscCall(MatAssemblyBegin(*mat, MAT_FINAL_ASSEMBLY));
6958: PetscCall(MatAssemblyEnd(*mat, MAT_FINAL_ASSEMBLY));
6959: PetscCall(MatSetOption(*mat, MAT_NO_OFF_PROC_ENTRIES, PETSC_FALSE));
6960: PetscCall(MatSetOption(*mat, MAT_NEW_NONZERO_LOCATION_ERR, PETSC_TRUE));
6961: PetscFunctionReturn(PETSC_SUCCESS);
6962: }
6964: typedef struct {
6965: Mat *mp; /* intermediate products */
6966: PetscBool *mptmp; /* is the intermediate product temporary ? */
6967: PetscInt cp; /* number of intermediate products */
6969: /* support for MatGetBrowsOfAoCols_MPIAIJ for P_oth */
6970: PetscInt *startsj_s, *startsj_r;
6971: PetscScalar *bufa;
6972: Mat P_oth;
6974: /* may take advantage of merging product->B */
6975: Mat Bloc; /* B-local by merging diag and off-diag */
6977: /* cusparse does not have support to split between symbolic and numeric phases.
6978: When api_user is true, we don't need to update the numerical values
6979: of the temporary storage */
6980: PetscBool reusesym;
6982: /* support for COO values insertion */
6983: PetscScalar *coo_v, *coo_w; /* store on-process and off-process COO scalars, and used as MPI recv/send buffers respectively */
6984: PetscInt **own; /* own[i] points to address of on-process COO indices for Mat mp[i] */
6985: PetscInt **off; /* off[i] points to address of off-process COO indices for Mat mp[i] */
6986: PetscBool hasoffproc; /* if true, have off-process values insertion (i.e. AtB or PtAP) */
6987: PetscSF sf; /* used for non-local values insertion and memory malloc */
6988: PetscMemType mtype;
6990: /* customization */
6991: PetscBool abmerge;
6992: PetscBool P_oth_bind;
6993: } MatMatMPIAIJBACKEND;
6995: static PetscErrorCode MatProductCtxDestroy_MatMatMPIAIJBACKEND(PetscCtxRt data)
6996: {
6997: MatMatMPIAIJBACKEND *mmdata = *(MatMatMPIAIJBACKEND **)data;
6998: PetscInt i;
7000: PetscFunctionBegin;
7001: PetscCall(PetscFree2(mmdata->startsj_s, mmdata->startsj_r));
7002: PetscCall(PetscFree(mmdata->bufa));
7003: PetscCall(PetscSFFree(mmdata->sf, mmdata->mtype, mmdata->coo_v));
7004: PetscCall(PetscSFFree(mmdata->sf, mmdata->mtype, mmdata->coo_w));
7005: PetscCall(MatDestroy(&mmdata->P_oth));
7006: PetscCall(MatDestroy(&mmdata->Bloc));
7007: PetscCall(PetscSFDestroy(&mmdata->sf));
7008: for (i = 0; i < mmdata->cp; i++) PetscCall(MatDestroy(&mmdata->mp[i]));
7009: PetscCall(PetscFree2(mmdata->mp, mmdata->mptmp));
7010: PetscCall(PetscFree(mmdata->own[0]));
7011: PetscCall(PetscFree(mmdata->own));
7012: PetscCall(PetscFree(mmdata->off[0]));
7013: PetscCall(PetscFree(mmdata->off));
7014: PetscCall(PetscFree(mmdata));
7015: PetscFunctionReturn(PETSC_SUCCESS);
7016: }
7018: /* Copy selected n entries with indices in idx[] of A to v[].
7019: If idx is NULL, copy the whole data array of A to v[]
7020: */
7021: static PetscErrorCode MatSeqAIJCopySubArray(Mat A, PetscInt n, const PetscInt idx[], PetscScalar v[])
7022: {
7023: PetscErrorCode (*f)(Mat, PetscInt, const PetscInt[], PetscScalar[]);
7025: PetscFunctionBegin;
7026: PetscCall(PetscObjectQueryFunction((PetscObject)A, "MatSeqAIJCopySubArray_C", &f));
7027: if (f) PetscCall((*f)(A, n, idx, v));
7028: else {
7029: const PetscScalar *vv;
7031: PetscCall(MatSeqAIJGetArrayRead(A, &vv));
7032: if (n && idx) {
7033: PetscScalar *w = v;
7034: const PetscInt *oi = idx;
7036: for (PetscInt j = 0; j < n; j++) *w++ = vv[*oi++];
7037: } else {
7038: PetscCall(PetscArraycpy(v, vv, n));
7039: }
7040: PetscCall(MatSeqAIJRestoreArrayRead(A, &vv));
7041: }
7042: PetscFunctionReturn(PETSC_SUCCESS);
7043: }
7045: static PetscErrorCode MatProductNumeric_MPIAIJBACKEND(Mat C)
7046: {
7047: MatMatMPIAIJBACKEND *mmdata;
7048: PetscInt i, n_d, n_o;
7050: PetscFunctionBegin;
7051: MatCheckProduct(C, 1);
7052: PetscCheck(C->product->data, PetscObjectComm((PetscObject)C), PETSC_ERR_PLIB, "Product data empty");
7053: mmdata = (MatMatMPIAIJBACKEND *)C->product->data;
7054: if (!mmdata->reusesym) { /* update temporary matrices */
7055: if (mmdata->P_oth) PetscCall(MatGetBrowsOfAoCols_MPIAIJ(C->product->A, C->product->B, MAT_REUSE_MATRIX, &mmdata->startsj_s, &mmdata->startsj_r, &mmdata->bufa, &mmdata->P_oth));
7056: if (mmdata->Bloc) PetscCall(MatMPIAIJGetLocalMatMerge(C->product->B, MAT_REUSE_MATRIX, NULL, &mmdata->Bloc));
7057: }
7058: mmdata->reusesym = PETSC_FALSE;
7060: for (i = 0; i < mmdata->cp; i++) {
7061: PetscCheck(mmdata->mp[i]->ops->productnumeric, PetscObjectComm((PetscObject)mmdata->mp[i]), PETSC_ERR_PLIB, "Missing numeric op for %s", MatProductTypes[mmdata->mp[i]->product->type]);
7062: PetscCall((*mmdata->mp[i]->ops->productnumeric)(mmdata->mp[i]));
7063: }
7064: for (i = 0, n_d = 0, n_o = 0; i < mmdata->cp; i++) {
7065: PetscInt noff;
7067: PetscCall(PetscIntCast(mmdata->off[i + 1] - mmdata->off[i], &noff));
7068: if (mmdata->mptmp[i]) continue;
7069: if (noff) {
7070: PetscInt nown;
7072: PetscCall(PetscIntCast(mmdata->own[i + 1] - mmdata->own[i], &nown));
7073: PetscCall(MatSeqAIJCopySubArray(mmdata->mp[i], noff, mmdata->off[i], mmdata->coo_w + n_o));
7074: PetscCall(MatSeqAIJCopySubArray(mmdata->mp[i], nown, mmdata->own[i], mmdata->coo_v + n_d));
7075: n_o += noff;
7076: n_d += nown;
7077: } else {
7078: Mat_SeqAIJ *mm = (Mat_SeqAIJ *)mmdata->mp[i]->data;
7080: PetscCall(MatSeqAIJCopySubArray(mmdata->mp[i], mm->nz, NULL, mmdata->coo_v + n_d));
7081: n_d += mm->nz;
7082: }
7083: }
7084: if (mmdata->hasoffproc) { /* offprocess insertion */
7085: PetscCall(PetscSFGatherBegin(mmdata->sf, MPIU_SCALAR, mmdata->coo_w, mmdata->coo_v + n_d));
7086: PetscCall(PetscSFGatherEnd(mmdata->sf, MPIU_SCALAR, mmdata->coo_w, mmdata->coo_v + n_d));
7087: }
7088: PetscCall(MatSetValuesCOO(C, mmdata->coo_v, INSERT_VALUES));
7089: PetscFunctionReturn(PETSC_SUCCESS);
7090: }
7092: /* Support for Pt * A, A * P, or Pt * A * P */
7093: #define MAX_NUMBER_INTERMEDIATE 4
7094: PetscErrorCode MatProductSymbolic_MPIAIJBACKEND(Mat C)
7095: {
7096: Mat_Product *product = C->product;
7097: Mat A, P, mp[MAX_NUMBER_INTERMEDIATE]; /* A, P and a series of intermediate matrices */
7098: Mat_MPIAIJ *a, *p;
7099: MatMatMPIAIJBACKEND *mmdata;
7100: ISLocalToGlobalMapping P_oth_l2g = NULL;
7101: IS glob = NULL;
7102: const char *prefix;
7103: char pprefix[256];
7104: const PetscInt *globidx, *P_oth_idx;
7105: PetscInt i, j, cp, m, n, M, N, *coo_i, *coo_j;
7106: PetscCount ncoo, ncoo_d, ncoo_o, ncoo_oown;
7107: PetscInt cmapt[MAX_NUMBER_INTERMEDIATE], rmapt[MAX_NUMBER_INTERMEDIATE]; /* col/row map type for each Mat in mp[]. */
7108: /* type-0: consecutive, start from 0; type-1: consecutive with */
7109: /* a base offset; type-2: sparse with a local to global map table */
7110: const PetscInt *cmapa[MAX_NUMBER_INTERMEDIATE], *rmapa[MAX_NUMBER_INTERMEDIATE]; /* col/row local to global map array (table) for type-2 map type */
7112: MatProductType ptype;
7113: PetscBool mptmp[MAX_NUMBER_INTERMEDIATE], hasoffproc = PETSC_FALSE, iscuda, iship, iskokk;
7114: PetscMPIInt size;
7116: PetscFunctionBegin;
7117: MatCheckProduct(C, 1);
7118: PetscCheck(!product->data, PetscObjectComm((PetscObject)C), PETSC_ERR_PLIB, "Product data not empty");
7119: ptype = product->type;
7120: if (product->A->symmetric == PETSC_BOOL3_TRUE && ptype == MATPRODUCT_AtB) {
7121: ptype = MATPRODUCT_AB;
7122: product->symbolic_used_the_fact_A_is_symmetric = PETSC_TRUE;
7123: }
7124: switch (ptype) {
7125: case MATPRODUCT_AB:
7126: A = product->A;
7127: P = product->B;
7128: m = A->rmap->n;
7129: n = P->cmap->n;
7130: M = A->rmap->N;
7131: N = P->cmap->N;
7132: hasoffproc = PETSC_FALSE; /* will not scatter mat product values to other processes */
7133: break;
7134: case MATPRODUCT_AtB:
7135: P = product->A;
7136: A = product->B;
7137: m = P->cmap->n;
7138: n = A->cmap->n;
7139: M = P->cmap->N;
7140: N = A->cmap->N;
7141: hasoffproc = PETSC_TRUE;
7142: break;
7143: case MATPRODUCT_PtAP:
7144: A = product->A;
7145: P = product->B;
7146: m = P->cmap->n;
7147: n = P->cmap->n;
7148: M = P->cmap->N;
7149: N = P->cmap->N;
7150: hasoffproc = PETSC_TRUE;
7151: break;
7152: default:
7153: SETERRQ(PetscObjectComm((PetscObject)C), PETSC_ERR_PLIB, "Not for product type %s", MatProductTypes[ptype]);
7154: }
7155: PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)C), &size));
7156: if (size == 1) hasoffproc = PETSC_FALSE;
7158: /* defaults */
7159: for (i = 0; i < MAX_NUMBER_INTERMEDIATE; i++) {
7160: mp[i] = NULL;
7161: mptmp[i] = PETSC_FALSE;
7162: rmapt[i] = -1;
7163: cmapt[i] = -1;
7164: rmapa[i] = NULL;
7165: cmapa[i] = NULL;
7166: }
7168: /* customization */
7169: PetscCall(PetscNew(&mmdata));
7170: mmdata->reusesym = product->api_user;
7171: if (ptype == MATPRODUCT_AB) {
7172: if (product->api_user) {
7173: PetscOptionsBegin(PetscObjectComm((PetscObject)C), ((PetscObject)C)->prefix, "MatMatMult", "Mat");
7174: PetscCall(PetscOptionsBool("-matmatmult_backend_mergeB", "Merge product->B local matrices", "MatMatMult", mmdata->abmerge, &mmdata->abmerge, NULL));
7175: PetscCall(PetscOptionsBool("-matmatmult_backend_pothbind", "Bind P_oth to CPU", "MatBindToCPU", mmdata->P_oth_bind, &mmdata->P_oth_bind, NULL));
7176: PetscOptionsEnd();
7177: } else {
7178: PetscOptionsBegin(PetscObjectComm((PetscObject)C), ((PetscObject)C)->prefix, "MatProduct_AB", "Mat");
7179: PetscCall(PetscOptionsBool("-mat_product_algorithm_backend_mergeB", "Merge product->B local matrices", "MatMatMult", mmdata->abmerge, &mmdata->abmerge, NULL));
7180: PetscCall(PetscOptionsBool("-mat_product_algorithm_backend_pothbind", "Bind P_oth to CPU", "MatBindToCPU", mmdata->P_oth_bind, &mmdata->P_oth_bind, NULL));
7181: PetscOptionsEnd();
7182: }
7183: } else if (ptype == MATPRODUCT_PtAP) {
7184: if (product->api_user) {
7185: PetscOptionsBegin(PetscObjectComm((PetscObject)C), ((PetscObject)C)->prefix, "MatPtAP", "Mat");
7186: PetscCall(PetscOptionsBool("-matptap_backend_pothbind", "Bind P_oth to CPU", "MatBindToCPU", mmdata->P_oth_bind, &mmdata->P_oth_bind, NULL));
7187: PetscOptionsEnd();
7188: } else {
7189: PetscOptionsBegin(PetscObjectComm((PetscObject)C), ((PetscObject)C)->prefix, "MatProduct_PtAP", "Mat");
7190: PetscCall(PetscOptionsBool("-mat_product_algorithm_backend_pothbind", "Bind P_oth to CPU", "MatBindToCPU", mmdata->P_oth_bind, &mmdata->P_oth_bind, NULL));
7191: PetscOptionsEnd();
7192: }
7193: }
7194: a = (Mat_MPIAIJ *)A->data;
7195: p = (Mat_MPIAIJ *)P->data;
7196: PetscCall(MatSetSizes(C, m, n, M, N));
7197: PetscCall(PetscLayoutSetUp(C->rmap));
7198: PetscCall(PetscLayoutSetUp(C->cmap));
7199: PetscCall(MatSetType(C, ((PetscObject)A)->type_name));
7200: PetscCall(MatGetOptionsPrefix(C, &prefix));
7202: cp = 0;
7203: switch (ptype) {
7204: case MATPRODUCT_AB: /* A * P */
7205: PetscCall(MatGetBrowsOfAoCols_MPIAIJ(A, P, MAT_INITIAL_MATRIX, &mmdata->startsj_s, &mmdata->startsj_r, &mmdata->bufa, &mmdata->P_oth));
7207: /* A_diag * P_local (merged or not) */
7208: if (mmdata->abmerge) { /* P's diagonal and off-diag blocks are merged to one matrix, then multiplied by A_diag */
7209: /* P is product->B */
7210: PetscCall(MatMPIAIJGetLocalMatMerge(P, MAT_INITIAL_MATRIX, &glob, &mmdata->Bloc));
7211: PetscCall(MatProductCreate(a->A, mmdata->Bloc, NULL, &mp[cp]));
7212: PetscCall(MatProductSetType(mp[cp], MATPRODUCT_AB));
7213: PetscCall(MatProductSetFill(mp[cp], product->fill));
7214: PetscCall(PetscSNPrintf(pprefix, sizeof(pprefix), "backend_p%" PetscInt_FMT "_", cp));
7215: PetscCall(MatSetOptionsPrefix(mp[cp], prefix));
7216: PetscCall(MatAppendOptionsPrefix(mp[cp], pprefix));
7217: mp[cp]->product->api_user = product->api_user;
7218: PetscCall(MatProductSetFromOptions(mp[cp]));
7219: PetscCall((*mp[cp]->ops->productsymbolic)(mp[cp]));
7220: PetscCall(ISGetIndices(glob, &globidx));
7221: rmapt[cp] = 1;
7222: cmapt[cp] = 2;
7223: cmapa[cp] = globidx;
7224: mptmp[cp] = PETSC_FALSE;
7225: cp++;
7226: } else { /* A_diag * P_diag and A_diag * P_off */
7227: PetscCall(MatProductCreate(a->A, p->A, NULL, &mp[cp]));
7228: PetscCall(MatProductSetType(mp[cp], MATPRODUCT_AB));
7229: PetscCall(MatProductSetFill(mp[cp], product->fill));
7230: PetscCall(PetscSNPrintf(pprefix, sizeof(pprefix), "backend_p%" PetscInt_FMT "_", cp));
7231: PetscCall(MatSetOptionsPrefix(mp[cp], prefix));
7232: PetscCall(MatAppendOptionsPrefix(mp[cp], pprefix));
7233: mp[cp]->product->api_user = product->api_user;
7234: PetscCall(MatProductSetFromOptions(mp[cp]));
7235: PetscCall((*mp[cp]->ops->productsymbolic)(mp[cp]));
7236: rmapt[cp] = 1;
7237: cmapt[cp] = 1;
7238: mptmp[cp] = PETSC_FALSE;
7239: cp++;
7240: PetscCall(MatProductCreate(a->A, p->B, NULL, &mp[cp]));
7241: PetscCall(MatProductSetType(mp[cp], MATPRODUCT_AB));
7242: PetscCall(MatProductSetFill(mp[cp], product->fill));
7243: PetscCall(PetscSNPrintf(pprefix, sizeof(pprefix), "backend_p%" PetscInt_FMT "_", cp));
7244: PetscCall(MatSetOptionsPrefix(mp[cp], prefix));
7245: PetscCall(MatAppendOptionsPrefix(mp[cp], pprefix));
7246: mp[cp]->product->api_user = product->api_user;
7247: PetscCall(MatProductSetFromOptions(mp[cp]));
7248: PetscCall((*mp[cp]->ops->productsymbolic)(mp[cp]));
7249: rmapt[cp] = 1;
7250: cmapt[cp] = 2;
7251: cmapa[cp] = p->garray;
7252: mptmp[cp] = PETSC_FALSE;
7253: cp++;
7254: }
7256: /* A_off * P_other */
7257: if (mmdata->P_oth) {
7258: PetscCall(MatSeqAIJCompactOutExtraColumns_SeqAIJ(mmdata->P_oth, &P_oth_l2g)); /* make P_oth use local col ids */
7259: PetscCall(ISLocalToGlobalMappingGetIndices(P_oth_l2g, &P_oth_idx));
7260: PetscCall(MatSetType(mmdata->P_oth, ((PetscObject)a->B)->type_name));
7261: PetscCall(MatBindToCPU(mmdata->P_oth, mmdata->P_oth_bind));
7262: PetscCall(MatProductCreate(a->B, mmdata->P_oth, NULL, &mp[cp]));
7263: PetscCall(MatProductSetType(mp[cp], MATPRODUCT_AB));
7264: PetscCall(MatProductSetFill(mp[cp], product->fill));
7265: PetscCall(PetscSNPrintf(pprefix, sizeof(pprefix), "backend_p%" PetscInt_FMT "_", cp));
7266: PetscCall(MatSetOptionsPrefix(mp[cp], prefix));
7267: PetscCall(MatAppendOptionsPrefix(mp[cp], pprefix));
7268: mp[cp]->product->api_user = product->api_user;
7269: PetscCall(MatProductSetFromOptions(mp[cp]));
7270: PetscCall((*mp[cp]->ops->productsymbolic)(mp[cp]));
7271: rmapt[cp] = 1;
7272: cmapt[cp] = 2;
7273: cmapa[cp] = P_oth_idx;
7274: mptmp[cp] = PETSC_FALSE;
7275: cp++;
7276: }
7277: break;
7279: case MATPRODUCT_AtB: /* (P^t * A): P_diag * A_loc + P_off * A_loc */
7280: /* A is product->B */
7281: PetscCall(MatMPIAIJGetLocalMatMerge(A, MAT_INITIAL_MATRIX, &glob, &mmdata->Bloc));
7282: if (A == P) { /* when A==P, we can take advantage of the already merged mmdata->Bloc */
7283: PetscCall(MatProductCreate(mmdata->Bloc, mmdata->Bloc, NULL, &mp[cp]));
7284: PetscCall(MatProductSetType(mp[cp], MATPRODUCT_AtB));
7285: PetscCall(MatProductSetFill(mp[cp], product->fill));
7286: PetscCall(PetscSNPrintf(pprefix, sizeof(pprefix), "backend_p%" PetscInt_FMT "_", cp));
7287: PetscCall(MatSetOptionsPrefix(mp[cp], prefix));
7288: PetscCall(MatAppendOptionsPrefix(mp[cp], pprefix));
7289: mp[cp]->product->api_user = product->api_user;
7290: PetscCall(MatProductSetFromOptions(mp[cp]));
7291: PetscCall((*mp[cp]->ops->productsymbolic)(mp[cp]));
7292: PetscCall(ISGetIndices(glob, &globidx));
7293: rmapt[cp] = 2;
7294: rmapa[cp] = globidx;
7295: cmapt[cp] = 2;
7296: cmapa[cp] = globidx;
7297: mptmp[cp] = PETSC_FALSE;
7298: cp++;
7299: } else {
7300: PetscCall(MatProductCreate(p->A, mmdata->Bloc, NULL, &mp[cp]));
7301: PetscCall(MatProductSetType(mp[cp], MATPRODUCT_AtB));
7302: PetscCall(MatProductSetFill(mp[cp], product->fill));
7303: PetscCall(PetscSNPrintf(pprefix, sizeof(pprefix), "backend_p%" PetscInt_FMT "_", cp));
7304: PetscCall(MatSetOptionsPrefix(mp[cp], prefix));
7305: PetscCall(MatAppendOptionsPrefix(mp[cp], pprefix));
7306: mp[cp]->product->api_user = product->api_user;
7307: PetscCall(MatProductSetFromOptions(mp[cp]));
7308: PetscCall((*mp[cp]->ops->productsymbolic)(mp[cp]));
7309: PetscCall(ISGetIndices(glob, &globidx));
7310: rmapt[cp] = 1;
7311: cmapt[cp] = 2;
7312: cmapa[cp] = globidx;
7313: mptmp[cp] = PETSC_FALSE;
7314: cp++;
7315: PetscCall(MatProductCreate(p->B, mmdata->Bloc, NULL, &mp[cp]));
7316: PetscCall(MatProductSetType(mp[cp], MATPRODUCT_AtB));
7317: PetscCall(MatProductSetFill(mp[cp], product->fill));
7318: PetscCall(PetscSNPrintf(pprefix, sizeof(pprefix), "backend_p%" PetscInt_FMT "_", cp));
7319: PetscCall(MatSetOptionsPrefix(mp[cp], prefix));
7320: PetscCall(MatAppendOptionsPrefix(mp[cp], pprefix));
7321: mp[cp]->product->api_user = product->api_user;
7322: PetscCall(MatProductSetFromOptions(mp[cp]));
7323: PetscCall((*mp[cp]->ops->productsymbolic)(mp[cp]));
7324: rmapt[cp] = 2;
7325: rmapa[cp] = p->garray;
7326: cmapt[cp] = 2;
7327: cmapa[cp] = globidx;
7328: mptmp[cp] = PETSC_FALSE;
7329: cp++;
7330: }
7331: break;
7332: case MATPRODUCT_PtAP:
7333: PetscCall(MatGetBrowsOfAoCols_MPIAIJ(A, P, MAT_INITIAL_MATRIX, &mmdata->startsj_s, &mmdata->startsj_r, &mmdata->bufa, &mmdata->P_oth));
7334: /* P is product->B */
7335: PetscCall(MatMPIAIJGetLocalMatMerge(P, MAT_INITIAL_MATRIX, &glob, &mmdata->Bloc));
7336: PetscCall(MatProductCreate(a->A, mmdata->Bloc, NULL, &mp[cp]));
7337: PetscCall(MatProductSetType(mp[cp], MATPRODUCT_PtAP));
7338: PetscCall(MatProductSetFill(mp[cp], product->fill));
7339: PetscCall(PetscSNPrintf(pprefix, sizeof(pprefix), "backend_p%" PetscInt_FMT "_", cp));
7340: PetscCall(MatSetOptionsPrefix(mp[cp], prefix));
7341: PetscCall(MatAppendOptionsPrefix(mp[cp], pprefix));
7342: mp[cp]->product->api_user = product->api_user;
7343: PetscCall(MatProductSetFromOptions(mp[cp]));
7344: PetscCall((*mp[cp]->ops->productsymbolic)(mp[cp]));
7345: PetscCall(ISGetIndices(glob, &globidx));
7346: rmapt[cp] = 2;
7347: rmapa[cp] = globidx;
7348: cmapt[cp] = 2;
7349: cmapa[cp] = globidx;
7350: mptmp[cp] = PETSC_FALSE;
7351: cp++;
7352: if (mmdata->P_oth) {
7353: PetscCall(MatSeqAIJCompactOutExtraColumns_SeqAIJ(mmdata->P_oth, &P_oth_l2g));
7354: PetscCall(ISLocalToGlobalMappingGetIndices(P_oth_l2g, &P_oth_idx));
7355: PetscCall(MatSetType(mmdata->P_oth, ((PetscObject)a->B)->type_name));
7356: PetscCall(MatBindToCPU(mmdata->P_oth, mmdata->P_oth_bind));
7357: PetscCall(MatProductCreate(a->B, mmdata->P_oth, NULL, &mp[cp]));
7358: PetscCall(MatProductSetType(mp[cp], MATPRODUCT_AB));
7359: PetscCall(MatProductSetFill(mp[cp], product->fill));
7360: PetscCall(PetscSNPrintf(pprefix, sizeof(pprefix), "backend_p%" PetscInt_FMT "_", cp));
7361: PetscCall(MatSetOptionsPrefix(mp[cp], prefix));
7362: PetscCall(MatAppendOptionsPrefix(mp[cp], pprefix));
7363: mp[cp]->product->api_user = product->api_user;
7364: PetscCall(MatProductSetFromOptions(mp[cp]));
7365: PetscCall((*mp[cp]->ops->productsymbolic)(mp[cp]));
7366: mptmp[cp] = PETSC_TRUE;
7367: cp++;
7368: PetscCall(MatProductCreate(mmdata->Bloc, mp[1], NULL, &mp[cp]));
7369: PetscCall(MatProductSetType(mp[cp], MATPRODUCT_AtB));
7370: PetscCall(MatProductSetFill(mp[cp], product->fill));
7371: PetscCall(PetscSNPrintf(pprefix, sizeof(pprefix), "backend_p%" PetscInt_FMT "_", cp));
7372: PetscCall(MatSetOptionsPrefix(mp[cp], prefix));
7373: PetscCall(MatAppendOptionsPrefix(mp[cp], pprefix));
7374: mp[cp]->product->api_user = product->api_user;
7375: PetscCall(MatProductSetFromOptions(mp[cp]));
7376: PetscCall((*mp[cp]->ops->productsymbolic)(mp[cp]));
7377: rmapt[cp] = 2;
7378: rmapa[cp] = globidx;
7379: cmapt[cp] = 2;
7380: cmapa[cp] = P_oth_idx;
7381: mptmp[cp] = PETSC_FALSE;
7382: cp++;
7383: }
7384: break;
7385: default:
7386: SETERRQ(PetscObjectComm((PetscObject)C), PETSC_ERR_PLIB, "Not for product type %s", MatProductTypes[ptype]);
7387: }
7388: /* sanity check */
7389: if (size > 1)
7390: for (i = 0; i < cp; i++) PetscCheck(rmapt[i] != 2 || hasoffproc, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Unexpected offproc map type for product %" PetscInt_FMT, i);
7392: PetscCall(PetscMalloc2(cp, &mmdata->mp, cp, &mmdata->mptmp));
7393: for (i = 0; i < cp; i++) {
7394: mmdata->mp[i] = mp[i];
7395: mmdata->mptmp[i] = mptmp[i];
7396: }
7397: mmdata->cp = cp;
7398: C->product->data = mmdata;
7399: C->product->destroy = MatProductCtxDestroy_MatMatMPIAIJBACKEND;
7400: C->ops->productnumeric = MatProductNumeric_MPIAIJBACKEND;
7402: /* memory type */
7403: mmdata->mtype = PETSC_MEMTYPE_HOST;
7404: PetscCall(PetscObjectTypeCompareAny((PetscObject)C, &iscuda, MATSEQAIJCUSPARSE, MATMPIAIJCUSPARSE, ""));
7405: PetscCall(PetscObjectTypeCompareAny((PetscObject)C, &iship, MATSEQAIJHIPSPARSE, MATMPIAIJHIPSPARSE, ""));
7406: PetscCall(PetscObjectTypeCompareAny((PetscObject)C, &iskokk, MATSEQAIJKOKKOS, MATMPIAIJKOKKOS, ""));
7407: if (iscuda) mmdata->mtype = PETSC_MEMTYPE_CUDA;
7408: else if (iship) mmdata->mtype = PETSC_MEMTYPE_HIP;
7409: else if (iskokk) mmdata->mtype = PETSC_MEMTYPE_KOKKOS;
7411: /* prepare coo coordinates for values insertion */
7413: /* count total nonzeros of those intermediate seqaij Mats
7414: ncoo_d: # of nonzeros of matrices that do not have offproc entries
7415: ncoo_o: # of nonzeros (of matrices that might have offproc entries) that will be inserted to remote procs
7416: ncoo_oown: # of nonzeros (of matrices that might have offproc entries) that will be inserted locally
7417: */
7418: for (cp = 0, ncoo_d = 0, ncoo_o = 0, ncoo_oown = 0; cp < mmdata->cp; cp++) {
7419: Mat_SeqAIJ *mm = (Mat_SeqAIJ *)mp[cp]->data;
7420: if (mptmp[cp]) continue;
7421: if (rmapt[cp] == 2 && hasoffproc) { /* the rows need to be scatter to all processes (might include self) */
7422: const PetscInt *rmap = rmapa[cp];
7423: const PetscInt mr = mp[cp]->rmap->n;
7424: const PetscInt rs = C->rmap->rstart;
7425: const PetscInt re = C->rmap->rend;
7426: const PetscInt *ii = mm->i;
7427: for (i = 0; i < mr; i++) {
7428: const PetscInt gr = rmap[i];
7429: const PetscInt nz = ii[i + 1] - ii[i];
7430: if (gr < rs || gr >= re) ncoo_o += nz; /* this row is offproc */
7431: else ncoo_oown += nz; /* this row is local */
7432: }
7433: } else ncoo_d += mm->nz;
7434: }
7436: /*
7437: ncoo: total number of nonzeros (including those inserted by remote procs) belonging to this proc
7439: ncoo = ncoo_d + ncoo_oown + ncoo2, which ncoo2 is number of nonzeros inserted to me by other procs.
7441: off[0] points to a big index array, which is shared by off[1,2,...]. Similarly, for own[0].
7443: off[p]: points to the segment for matrix mp[p], storing location of nonzeros that mp[p] will insert to others
7444: own[p]: points to the segment for matrix mp[p], storing location of nonzeros that mp[p] will insert locally
7445: so, off[p+1]-off[p] is the number of nonzeros that mp[p] will send to others.
7447: coo_i/j/v[]: [ncoo] row/col/val of nonzeros belonging to this proc.
7448: Ex. coo_i[]: the beginning part (of size ncoo_d + ncoo_oown) stores i of local nonzeros, and the remaining part stores i of nonzeros I will receive.
7449: */
7450: PetscCall(PetscCalloc1(mmdata->cp + 1, &mmdata->off)); /* +1 to make a csr-like data structure */
7451: PetscCall(PetscCalloc1(mmdata->cp + 1, &mmdata->own));
7453: /* gather (i,j) of nonzeros inserted by remote procs */
7454: if (hasoffproc) {
7455: PetscSF msf;
7456: PetscInt ncoo2, *coo_i2, *coo_j2;
7458: PetscCall(PetscMalloc1(ncoo_o, &mmdata->off[0]));
7459: PetscCall(PetscMalloc1(ncoo_oown, &mmdata->own[0]));
7460: PetscCall(PetscMalloc2(ncoo_o, &coo_i, ncoo_o, &coo_j)); /* to collect (i,j) of entries to be sent to others */
7462: for (cp = 0, ncoo_o = 0; cp < mmdata->cp; cp++) {
7463: Mat_SeqAIJ *mm = (Mat_SeqAIJ *)mp[cp]->data;
7464: PetscInt *idxoff = mmdata->off[cp];
7465: PetscInt *idxown = mmdata->own[cp];
7466: if (!mptmp[cp] && rmapt[cp] == 2) { /* row map is sparse */
7467: const PetscInt *rmap = rmapa[cp];
7468: const PetscInt *cmap = cmapa[cp];
7469: const PetscInt *ii = mm->i;
7470: PetscInt *coi = coo_i + ncoo_o;
7471: PetscInt *coj = coo_j + ncoo_o;
7472: const PetscInt mr = mp[cp]->rmap->n;
7473: const PetscInt rs = C->rmap->rstart;
7474: const PetscInt re = C->rmap->rend;
7475: const PetscInt cs = C->cmap->rstart;
7476: for (i = 0; i < mr; i++) {
7477: const PetscInt *jj = mm->j + ii[i];
7478: const PetscInt gr = rmap[i];
7479: const PetscInt nz = ii[i + 1] - ii[i];
7480: if (gr < rs || gr >= re) { /* this is an offproc row */
7481: for (j = ii[i]; j < ii[i + 1]; j++) {
7482: *coi++ = gr;
7483: *idxoff++ = j;
7484: }
7485: if (!cmapt[cp]) { /* already global */
7486: for (j = 0; j < nz; j++) *coj++ = jj[j];
7487: } else if (cmapt[cp] == 1) { /* local to global for owned columns of C */
7488: for (j = 0; j < nz; j++) *coj++ = jj[j] + cs;
7489: } else { /* offdiag */
7490: for (j = 0; j < nz; j++) *coj++ = cmap[jj[j]];
7491: }
7492: ncoo_o += nz;
7493: } else { /* this is a local row */
7494: for (j = ii[i]; j < ii[i + 1]; j++) *idxown++ = j;
7495: }
7496: }
7497: }
7498: mmdata->off[cp + 1] = idxoff;
7499: mmdata->own[cp + 1] = idxown;
7500: }
7502: PetscCall(PetscSFCreate(PetscObjectComm((PetscObject)C), &mmdata->sf));
7503: PetscInt incoo_o;
7504: PetscCall(PetscIntCast(ncoo_o, &incoo_o));
7505: PetscCall(PetscSFSetGraphLayout(mmdata->sf, C->rmap, incoo_o /*nleaves*/, NULL /*ilocal*/, PETSC_OWN_POINTER, coo_i));
7506: PetscCall(PetscSFGetMultiSF(mmdata->sf, &msf));
7507: PetscCall(PetscSFGetGraph(msf, &ncoo2 /*nroots*/, NULL, NULL, NULL));
7508: ncoo = ncoo_d + ncoo_oown + ncoo2;
7509: PetscCall(PetscMalloc2(ncoo, &coo_i2, ncoo, &coo_j2));
7510: PetscCall(PetscSFGatherBegin(mmdata->sf, MPIU_INT, coo_i, coo_i2 + ncoo_d + ncoo_oown)); /* put (i,j) of remote nonzeros at back */
7511: PetscCall(PetscSFGatherEnd(mmdata->sf, MPIU_INT, coo_i, coo_i2 + ncoo_d + ncoo_oown));
7512: PetscCall(PetscSFGatherBegin(mmdata->sf, MPIU_INT, coo_j, coo_j2 + ncoo_d + ncoo_oown));
7513: PetscCall(PetscSFGatherEnd(mmdata->sf, MPIU_INT, coo_j, coo_j2 + ncoo_d + ncoo_oown));
7514: PetscCall(PetscFree2(coo_i, coo_j));
7515: /* allocate MPI send buffer to collect nonzero values to be sent to remote procs */
7516: PetscCall(PetscSFMalloc(mmdata->sf, mmdata->mtype, ncoo_o * sizeof(PetscScalar), (void **)&mmdata->coo_w));
7517: coo_i = coo_i2;
7518: coo_j = coo_j2;
7519: } else { /* no offproc values insertion */
7520: ncoo = ncoo_d;
7521: PetscCall(PetscMalloc2(ncoo, &coo_i, ncoo, &coo_j));
7523: PetscCall(PetscSFCreate(PetscObjectComm((PetscObject)C), &mmdata->sf));
7524: PetscCall(PetscSFSetGraph(mmdata->sf, 0, 0, NULL, PETSC_OWN_POINTER, NULL, PETSC_OWN_POINTER));
7525: PetscCall(PetscSFSetUp(mmdata->sf));
7526: }
7527: mmdata->hasoffproc = hasoffproc;
7529: /* gather (i,j) of nonzeros inserted locally */
7530: for (cp = 0, ncoo_d = 0; cp < mmdata->cp; cp++) {
7531: Mat_SeqAIJ *mm = (Mat_SeqAIJ *)mp[cp]->data;
7532: PetscInt *coi = coo_i + ncoo_d;
7533: PetscInt *coj = coo_j + ncoo_d;
7534: const PetscInt *jj = mm->j;
7535: const PetscInt *ii = mm->i;
7536: const PetscInt *cmap = cmapa[cp];
7537: const PetscInt *rmap = rmapa[cp];
7538: const PetscInt mr = mp[cp]->rmap->n;
7539: const PetscInt rs = C->rmap->rstart;
7540: const PetscInt re = C->rmap->rend;
7541: const PetscInt cs = C->cmap->rstart;
7543: if (mptmp[cp]) continue;
7544: if (rmapt[cp] == 1) { /* consecutive rows */
7545: /* fill coo_i */
7546: for (i = 0; i < mr; i++) {
7547: const PetscInt gr = i + rs;
7548: for (j = ii[i]; j < ii[i + 1]; j++) coi[j] = gr;
7549: }
7550: /* fill coo_j */
7551: if (!cmapt[cp]) { /* type-0, already global */
7552: PetscCall(PetscArraycpy(coj, jj, mm->nz));
7553: } else if (cmapt[cp] == 1) { /* type-1, local to global for consecutive columns of C */
7554: for (j = 0; j < mm->nz; j++) coj[j] = jj[j] + cs; /* lid + col start */
7555: } else { /* type-2, local to global for sparse columns */
7556: for (j = 0; j < mm->nz; j++) coj[j] = cmap[jj[j]];
7557: }
7558: ncoo_d += mm->nz;
7559: } else if (rmapt[cp] == 2) { /* sparse rows */
7560: for (i = 0; i < mr; i++) {
7561: const PetscInt *jj = mm->j + ii[i];
7562: const PetscInt gr = rmap[i];
7563: const PetscInt nz = ii[i + 1] - ii[i];
7564: if (gr >= rs && gr < re) { /* local rows */
7565: for (j = ii[i]; j < ii[i + 1]; j++) *coi++ = gr;
7566: if (!cmapt[cp]) { /* type-0, already global */
7567: for (j = 0; j < nz; j++) *coj++ = jj[j];
7568: } else if (cmapt[cp] == 1) { /* local to global for owned columns of C */
7569: for (j = 0; j < nz; j++) *coj++ = jj[j] + cs;
7570: } else { /* type-2, local to global for sparse columns */
7571: for (j = 0; j < nz; j++) *coj++ = cmap[jj[j]];
7572: }
7573: ncoo_d += nz;
7574: }
7575: }
7576: }
7577: }
7578: if (glob) PetscCall(ISRestoreIndices(glob, &globidx));
7579: PetscCall(ISDestroy(&glob));
7580: if (P_oth_l2g) PetscCall(ISLocalToGlobalMappingRestoreIndices(P_oth_l2g, &P_oth_idx));
7581: PetscCall(ISLocalToGlobalMappingDestroy(&P_oth_l2g));
7582: /* allocate an array to store all nonzeros (inserted locally or remotely) belonging to this proc */
7583: PetscCall(PetscSFMalloc(mmdata->sf, mmdata->mtype, ncoo * sizeof(PetscScalar), (void **)&mmdata->coo_v));
7585: /* set block sizes */
7586: A = product->A;
7587: P = product->B;
7588: switch (ptype) {
7589: case MATPRODUCT_PtAP:
7590: PetscCall(MatSetBlockSizes(C, P->cmap->bs, P->cmap->bs));
7591: break;
7592: case MATPRODUCT_RARt:
7593: PetscCall(MatSetBlockSizes(C, P->rmap->bs, P->rmap->bs));
7594: break;
7595: case MATPRODUCT_ABC:
7596: PetscCall(MatSetBlockSizesFromMats(C, A, product->C));
7597: break;
7598: case MATPRODUCT_AB:
7599: PetscCall(MatSetBlockSizesFromMats(C, A, P));
7600: break;
7601: case MATPRODUCT_AtB:
7602: PetscCall(MatSetBlockSizes(C, A->cmap->bs, P->cmap->bs));
7603: break;
7604: case MATPRODUCT_ABt:
7605: PetscCall(MatSetBlockSizes(C, A->rmap->bs, P->rmap->bs));
7606: break;
7607: default:
7608: SETERRQ(PetscObjectComm((PetscObject)C), PETSC_ERR_PLIB, "Not for ProductType %s", MatProductTypes[ptype]);
7609: }
7611: /* preallocate with COO data */
7612: PetscCall(MatSetPreallocationCOO(C, ncoo, coo_i, coo_j));
7613: PetscCall(PetscFree2(coo_i, coo_j));
7614: PetscFunctionReturn(PETSC_SUCCESS);
7615: }
7617: PetscErrorCode MatProductSetFromOptions_MPIAIJBACKEND(Mat mat)
7618: {
7619: Mat_Product *product = mat->product;
7620: #if defined(PETSC_HAVE_DEVICE)
7621: PetscBool match = PETSC_FALSE;
7622: PetscBool usecpu = PETSC_FALSE;
7623: #else
7624: PetscBool match = PETSC_TRUE;
7625: #endif
7627: PetscFunctionBegin;
7628: MatCheckProduct(mat, 1);
7629: #if defined(PETSC_HAVE_DEVICE)
7630: if (!product->A->boundtocpu && !product->B->boundtocpu) PetscCall(PetscObjectTypeCompare((PetscObject)product->B, ((PetscObject)product->A)->type_name, &match));
7631: if (match) { /* we can always fallback to the CPU if requested */
7632: switch (product->type) {
7633: case MATPRODUCT_AB:
7634: if (product->api_user) {
7635: PetscOptionsBegin(PetscObjectComm((PetscObject)mat), ((PetscObject)mat)->prefix, "MatMatMult", "Mat");
7636: PetscCall(PetscOptionsBool("-matmatmult_backend_cpu", "Use CPU code", "MatMatMult", usecpu, &usecpu, NULL));
7637: PetscOptionsEnd();
7638: } else {
7639: PetscOptionsBegin(PetscObjectComm((PetscObject)mat), ((PetscObject)mat)->prefix, "MatProduct_AB", "Mat");
7640: PetscCall(PetscOptionsBool("-mat_product_algorithm_backend_cpu", "Use CPU code", "MatMatMult", usecpu, &usecpu, NULL));
7641: PetscOptionsEnd();
7642: }
7643: break;
7644: case MATPRODUCT_AtB:
7645: if (product->api_user) {
7646: PetscOptionsBegin(PetscObjectComm((PetscObject)mat), ((PetscObject)mat)->prefix, "MatTransposeMatMult", "Mat");
7647: PetscCall(PetscOptionsBool("-mattransposematmult_backend_cpu", "Use CPU code", "MatTransposeMatMult", usecpu, &usecpu, NULL));
7648: PetscOptionsEnd();
7649: } else {
7650: PetscOptionsBegin(PetscObjectComm((PetscObject)mat), ((PetscObject)mat)->prefix, "MatProduct_AtB", "Mat");
7651: PetscCall(PetscOptionsBool("-mat_product_algorithm_backend_cpu", "Use CPU code", "MatTransposeMatMult", usecpu, &usecpu, NULL));
7652: PetscOptionsEnd();
7653: }
7654: break;
7655: case MATPRODUCT_PtAP:
7656: if (product->api_user) {
7657: PetscOptionsBegin(PetscObjectComm((PetscObject)mat), ((PetscObject)mat)->prefix, "MatPtAP", "Mat");
7658: PetscCall(PetscOptionsBool("-matptap_backend_cpu", "Use CPU code", "MatPtAP", usecpu, &usecpu, NULL));
7659: PetscOptionsEnd();
7660: } else {
7661: PetscOptionsBegin(PetscObjectComm((PetscObject)mat), ((PetscObject)mat)->prefix, "MatProduct_PtAP", "Mat");
7662: PetscCall(PetscOptionsBool("-mat_product_algorithm_backend_cpu", "Use CPU code", "MatPtAP", usecpu, &usecpu, NULL));
7663: PetscOptionsEnd();
7664: }
7665: break;
7666: default:
7667: break;
7668: }
7669: match = (PetscBool)!usecpu;
7670: }
7671: #endif
7672: if (match) {
7673: switch (product->type) {
7674: case MATPRODUCT_AB:
7675: case MATPRODUCT_AtB:
7676: case MATPRODUCT_PtAP:
7677: mat->ops->productsymbolic = MatProductSymbolic_MPIAIJBACKEND;
7678: break;
7679: default:
7680: break;
7681: }
7682: }
7683: /* fallback to MPIAIJ ops */
7684: if (!mat->ops->productsymbolic) PetscCall(MatProductSetFromOptions_MPIAIJ(mat));
7685: PetscFunctionReturn(PETSC_SUCCESS);
7686: }
7688: /*
7689: Produces a set of block column indices of the matrix row, one for each block represented in the original row
7691: n - the number of block indices in cc[]
7692: cc - the block indices (must be large enough to contain the indices)
7693: */
7694: static inline PetscErrorCode MatCollapseRow(Mat Amat, PetscInt row, PetscInt bs, PetscInt *n, PetscInt *cc)
7695: {
7696: PetscInt cnt = -1, nidx, j;
7697: const PetscInt *idx;
7699: PetscFunctionBegin;
7700: PetscCall(MatGetRow(Amat, row, &nidx, &idx, NULL));
7701: if (nidx) {
7702: cnt = 0;
7703: cc[cnt] = idx[0] / bs;
7704: for (j = 1; j < nidx; j++) {
7705: if (cc[cnt] < idx[j] / bs) cc[++cnt] = idx[j] / bs;
7706: }
7707: }
7708: PetscCall(MatRestoreRow(Amat, row, &nidx, &idx, NULL));
7709: *n = cnt + 1;
7710: PetscFunctionReturn(PETSC_SUCCESS);
7711: }
7713: /*
7714: Produces a set of block column indices of the matrix block row, one for each block represented in the original set of rows
7716: ncollapsed - the number of block indices
7717: collapsed - the block indices (must be large enough to contain the indices)
7718: */
7719: static inline PetscErrorCode MatCollapseRows(Mat Amat, PetscInt start, PetscInt bs, PetscInt *w0, PetscInt *w1, PetscInt *w2, PetscInt *ncollapsed, PetscInt **collapsed)
7720: {
7721: PetscInt i, nprev, *cprev = w0, ncur = 0, *ccur = w1, *merged = w2, *cprevtmp;
7723: PetscFunctionBegin;
7724: PetscCall(MatCollapseRow(Amat, start, bs, &nprev, cprev));
7725: for (i = start + 1; i < start + bs; i++) {
7726: PetscCall(MatCollapseRow(Amat, i, bs, &ncur, ccur));
7727: PetscCall(PetscMergeIntArray(nprev, cprev, ncur, ccur, &nprev, &merged));
7728: cprevtmp = cprev;
7729: cprev = merged;
7730: merged = cprevtmp;
7731: }
7732: *ncollapsed = nprev;
7733: if (collapsed) *collapsed = cprev;
7734: PetscFunctionReturn(PETSC_SUCCESS);
7735: }
7737: // PetscClangLinter pragma disable: -fdoc-sowing-chars
7738: /*
7739: MatCreateGraph_Simple_AIJ - create simple scalar matrix (graph) from potentially blocked matrix
7741: Input Parameters:
7742: + Amat - matrix
7743: . symmetrize - make the result symmetric
7744: . scale - scale with diagonal
7745: . filter - threshold for filter
7746: . index_size - length of `index`
7747: - index - indices of unknown purpose
7749: Output Parameter:
7750: . a_Gmat - output scalar graph >= 0
7752: Level: developer
7754: .seealso: `MATAIJ`
7755: */
7756: PETSC_INTERN PetscErrorCode MatCreateGraph_Simple_AIJ(Mat Amat, PetscBool symmetrize, PetscBool scale, PetscReal filter, PetscInt index_size, PetscInt index[], Mat *a_Gmat)
7757: {
7758: PetscInt Istart, Iend, Ii, jj, kk, ncols, nloc, NN, MM, bs;
7759: MPI_Comm comm;
7760: Mat Gmat;
7761: PetscBool ismpiaij, isseqaij;
7762: Mat a, b, c;
7763: MatType jtype;
7765: PetscFunctionBegin;
7766: PetscCall(PetscObjectGetComm((PetscObject)Amat, &comm));
7767: PetscCall(MatGetOwnershipRange(Amat, &Istart, &Iend));
7768: PetscCall(MatGetSize(Amat, &MM, &NN));
7769: PetscCall(MatGetBlockSize(Amat, &bs));
7770: nloc = (Iend - Istart) / bs;
7772: PetscCall(PetscObjectBaseTypeCompare((PetscObject)Amat, MATSEQAIJ, &isseqaij));
7773: PetscCall(PetscObjectBaseTypeCompare((PetscObject)Amat, MATMPIAIJ, &ismpiaij));
7774: PetscCheck(isseqaij || ismpiaij, comm, PETSC_ERR_USER, "Require (MPI)AIJ matrix type");
7776: /* TODO GPU: these calls are potentially expensive if matrices are large and we want to use the GPU */
7777: /* A solution consists in providing a new API, MatAIJGetCollapsedAIJ, and each class can provide a fast
7778: implementation */
7779: if (bs > 1) {
7780: PetscCall(MatGetType(Amat, &jtype));
7781: PetscCall(MatCreate(comm, &Gmat));
7782: PetscCall(MatSetType(Gmat, jtype));
7783: PetscCall(MatSetSizes(Gmat, nloc, nloc, PETSC_DETERMINE, PETSC_DETERMINE));
7784: PetscCall(MatSetBlockSizes(Gmat, 1, 1));
7785: if (isseqaij || ((Mat_MPIAIJ *)Amat->data)->garray) {
7786: PetscInt *d_nnz, *o_nnz;
7787: MatScalar *aa, val, *AA;
7788: PetscInt *aj, *ai, *AJ, nc, nmax = 0;
7790: if (isseqaij) {
7791: a = Amat;
7792: b = NULL;
7793: } else {
7794: Mat_MPIAIJ *d = (Mat_MPIAIJ *)Amat->data;
7795: a = d->A;
7796: b = d->B;
7797: }
7798: PetscCall(PetscInfo(Amat, "New bs>1 Graph. nloc=%" PetscInt_FMT "\n", nloc));
7799: PetscCall(PetscMalloc2(nloc, &d_nnz, (isseqaij ? 0 : nloc), &o_nnz));
7800: for (c = a, kk = 0; c && kk < 2; c = b, kk++) {
7801: PetscInt *nnz = (c == a) ? d_nnz : o_nnz;
7802: const PetscInt *cols1, *cols2;
7804: for (PetscInt brow = 0, nc1, nc2, ok = 1; brow < nloc * bs; brow += bs) { // block rows
7805: PetscCall(MatGetRow(c, brow, &nc2, &cols2, NULL));
7806: nnz[brow / bs] = nc2 / bs;
7807: if (nc2 % bs) ok = 0;
7808: if (nnz[brow / bs] > nmax) nmax = nnz[brow / bs];
7809: for (PetscInt ii = 1; ii < bs; ii++) { // check for non-dense blocks
7810: PetscCall(MatGetRow(c, brow + ii, &nc1, &cols1, NULL));
7811: if (nc1 != nc2) ok = 0;
7812: else {
7813: for (PetscInt jj = 0; jj < nc1 && ok == 1; jj++) {
7814: if (cols1[jj] != cols2[jj]) ok = 0;
7815: if (cols1[jj] % bs != jj % bs) ok = 0;
7816: }
7817: }
7818: PetscCall(MatRestoreRow(c, brow + ii, &nc1, &cols1, NULL));
7819: }
7820: PetscCall(MatRestoreRow(c, brow, &nc2, &cols2, NULL));
7821: if (!ok) {
7822: PetscCall(PetscFree2(d_nnz, o_nnz));
7823: PetscCall(PetscInfo(Amat, "Found sparse blocks - revert to slow method\n"));
7824: goto old_bs;
7825: }
7826: }
7827: }
7828: PetscCall(MatSeqAIJSetPreallocation(Gmat, 0, d_nnz));
7829: PetscCall(MatMPIAIJSetPreallocation(Gmat, 0, d_nnz, 0, o_nnz));
7830: PetscCall(PetscFree2(d_nnz, o_nnz));
7831: PetscCall(PetscMalloc2(nmax, &AA, nmax, &AJ));
7832: // diag
7833: for (PetscInt brow = 0, n, grow; brow < nloc * bs; brow += bs) { // block rows
7834: Mat_SeqAIJ *aseq = (Mat_SeqAIJ *)a->data;
7836: ai = aseq->i;
7837: n = ai[brow + 1] - ai[brow];
7838: aj = aseq->j + ai[brow];
7839: for (PetscInt k = 0; k < n; k += bs) { // block columns
7840: AJ[k / bs] = aj[k] / bs + Istart / bs; // diag starts at (Istart,Istart)
7841: val = 0;
7842: if (index_size == 0) {
7843: for (PetscInt ii = 0; ii < bs; ii++) { // rows in block
7844: aa = aseq->a + ai[brow + ii] + k;
7845: for (PetscInt jj = 0; jj < bs; jj++) { // columns in block
7846: val += PetscAbs(PetscRealPart(aa[jj])); // a sort of norm
7847: }
7848: }
7849: } else { // use (index,index) value if provided
7850: for (PetscInt iii = 0; iii < index_size; iii++) { // rows in block
7851: PetscInt ii = index[iii];
7852: aa = aseq->a + ai[brow + ii] + k;
7853: for (PetscInt jjj = 0; jjj < index_size; jjj++) { // columns in block
7854: PetscInt jj = index[jjj];
7855: val += PetscAbs(PetscRealPart(aa[jj]));
7856: }
7857: }
7858: }
7859: PetscAssert(k / bs < nmax, comm, PETSC_ERR_USER, "k / bs (%" PetscInt_FMT ") >= nmax (%" PetscInt_FMT ")", k / bs, nmax);
7860: AA[k / bs] = val;
7861: }
7862: grow = Istart / bs + brow / bs;
7863: PetscCall(MatSetValues(Gmat, 1, &grow, n / bs, AJ, AA, ADD_VALUES));
7864: }
7865: // off-diag
7866: if (ismpiaij) {
7867: Mat_MPIAIJ *aij = (Mat_MPIAIJ *)Amat->data;
7868: const PetscScalar *vals;
7869: const PetscInt *cols, *garray = aij->garray;
7871: PetscCheck(garray, PETSC_COMM_SELF, PETSC_ERR_USER, "No garray ?");
7872: for (PetscInt brow = 0, grow; brow < nloc * bs; brow += bs) { // block rows
7873: PetscCall(MatGetRow(b, brow, &ncols, &cols, NULL));
7874: for (PetscInt k = 0, cidx = 0; k < ncols; k += bs, cidx++) {
7875: PetscAssert(k / bs < nmax, comm, PETSC_ERR_USER, "k / bs >= nmax");
7876: AA[k / bs] = 0;
7877: AJ[cidx] = garray[cols[k]] / bs;
7878: }
7879: nc = ncols / bs;
7880: PetscCall(MatRestoreRow(b, brow, &ncols, &cols, NULL));
7881: if (index_size == 0) {
7882: for (PetscInt ii = 0; ii < bs; ii++) { // rows in block
7883: PetscCall(MatGetRow(b, brow + ii, &ncols, &cols, &vals));
7884: for (PetscInt k = 0; k < ncols; k += bs) {
7885: for (PetscInt jj = 0; jj < bs; jj++) { // cols in block
7886: PetscAssert(k / bs < nmax, comm, PETSC_ERR_USER, "k / bs (%" PetscInt_FMT ") >= nmax (%" PetscInt_FMT ")", k / bs, nmax);
7887: AA[k / bs] += PetscAbs(PetscRealPart(vals[k + jj]));
7888: }
7889: }
7890: PetscCall(MatRestoreRow(b, brow + ii, &ncols, &cols, &vals));
7891: }
7892: } else { // use (index,index) value if provided
7893: for (PetscInt iii = 0; iii < index_size; iii++) { // rows in block
7894: PetscInt ii = index[iii];
7895: PetscCall(MatGetRow(b, brow + ii, &ncols, &cols, &vals));
7896: for (PetscInt k = 0; k < ncols; k += bs) {
7897: for (PetscInt jjj = 0; jjj < index_size; jjj++) { // cols in block
7898: PetscInt jj = index[jjj];
7899: AA[k / bs] += PetscAbs(PetscRealPart(vals[k + jj]));
7900: }
7901: }
7902: PetscCall(MatRestoreRow(b, brow + ii, &ncols, &cols, &vals));
7903: }
7904: }
7905: grow = Istart / bs + brow / bs;
7906: PetscCall(MatSetValues(Gmat, 1, &grow, nc, AJ, AA, ADD_VALUES));
7907: }
7908: }
7909: PetscCall(MatAssemblyBegin(Gmat, MAT_FINAL_ASSEMBLY));
7910: PetscCall(MatAssemblyEnd(Gmat, MAT_FINAL_ASSEMBLY));
7911: PetscCall(PetscFree2(AA, AJ));
7912: } else {
7913: const PetscScalar *vals;
7914: const PetscInt *idx;
7915: PetscInt *d_nnz, *o_nnz, *w0, *w1, *w2;
7916: old_bs:
7917: /*
7918: Determine the preallocation needed for the scalar matrix derived from the vector matrix.
7919: */
7920: PetscCall(PetscInfo(Amat, "OLD bs>1 CreateGraph\n"));
7921: PetscCall(PetscMalloc2(nloc, &d_nnz, (isseqaij ? 0 : nloc), &o_nnz));
7922: if (isseqaij) {
7923: PetscInt max_d_nnz;
7925: /*
7926: Determine exact preallocation count for (sequential) scalar matrix
7927: */
7928: PetscCall(MatSeqAIJGetMaxRowNonzeros(Amat, &max_d_nnz));
7929: max_d_nnz = PetscMin(nloc, bs * max_d_nnz);
7930: PetscCall(PetscMalloc3(max_d_nnz, &w0, max_d_nnz, &w1, max_d_nnz, &w2));
7931: for (Ii = 0, jj = 0; Ii < Iend; Ii += bs, jj++) PetscCall(MatCollapseRows(Amat, Ii, bs, w0, w1, w2, &d_nnz[jj], NULL));
7932: PetscCall(PetscFree3(w0, w1, w2));
7933: } else if (ismpiaij) {
7934: Mat Daij, Oaij;
7935: const PetscInt *garray;
7936: PetscInt max_d_nnz;
7938: PetscCall(MatMPIAIJGetSeqAIJ(Amat, &Daij, &Oaij, &garray));
7939: /*
7940: Determine exact preallocation count for diagonal block portion of scalar matrix
7941: */
7942: PetscCall(MatSeqAIJGetMaxRowNonzeros(Daij, &max_d_nnz));
7943: max_d_nnz = PetscMin(nloc, bs * max_d_nnz);
7944: PetscCall(PetscMalloc3(max_d_nnz, &w0, max_d_nnz, &w1, max_d_nnz, &w2));
7945: for (Ii = 0, jj = 0; Ii < Iend - Istart; Ii += bs, jj++) PetscCall(MatCollapseRows(Daij, Ii, bs, w0, w1, w2, &d_nnz[jj], NULL));
7946: PetscCall(PetscFree3(w0, w1, w2));
7947: /*
7948: Over estimate (usually grossly over), preallocation count for off-diagonal portion of scalar matrix
7949: */
7950: for (Ii = 0, jj = 0; Ii < Iend - Istart; Ii += bs, jj++) {
7951: o_nnz[jj] = 0;
7952: for (kk = 0; kk < bs; kk++) { /* rows that get collapsed to a single row */
7953: PetscCall(MatGetRow(Oaij, Ii + kk, &ncols, NULL, NULL));
7954: o_nnz[jj] += ncols;
7955: PetscCall(MatRestoreRow(Oaij, Ii + kk, &ncols, NULL, NULL));
7956: }
7957: if (o_nnz[jj] > (NN / bs - nloc)) o_nnz[jj] = NN / bs - nloc;
7958: }
7959: } else SETERRQ(comm, PETSC_ERR_USER, "Require AIJ matrix type");
7960: /* get scalar copy (norms) of matrix */
7961: PetscCall(MatSeqAIJSetPreallocation(Gmat, 0, d_nnz));
7962: PetscCall(MatMPIAIJSetPreallocation(Gmat, 0, d_nnz, 0, o_nnz));
7963: PetscCall(PetscFree2(d_nnz, o_nnz));
7964: for (Ii = Istart; Ii < Iend; Ii++) {
7965: PetscInt dest_row = Ii / bs;
7967: PetscCall(MatGetRow(Amat, Ii, &ncols, &idx, &vals));
7968: for (jj = 0; jj < ncols; jj++) {
7969: PetscInt dest_col = idx[jj] / bs;
7970: PetscScalar sv = PetscAbs(PetscRealPart(vals[jj]));
7972: PetscCall(MatSetValues(Gmat, 1, &dest_row, 1, &dest_col, &sv, ADD_VALUES));
7973: }
7974: PetscCall(MatRestoreRow(Amat, Ii, &ncols, &idx, &vals));
7975: }
7976: PetscCall(MatAssemblyBegin(Gmat, MAT_FINAL_ASSEMBLY));
7977: PetscCall(MatAssemblyEnd(Gmat, MAT_FINAL_ASSEMBLY));
7978: }
7979: } else {
7980: if (symmetrize || filter >= 0 || scale) PetscCall(MatDuplicate(Amat, MAT_COPY_VALUES, &Gmat));
7981: else {
7982: Gmat = Amat;
7983: PetscCall(PetscObjectReference((PetscObject)Gmat));
7984: }
7985: if (isseqaij) {
7986: a = Gmat;
7987: b = NULL;
7988: } else {
7989: Mat_MPIAIJ *d = (Mat_MPIAIJ *)Gmat->data;
7990: a = d->A;
7991: b = d->B;
7992: }
7993: if (filter >= 0 || scale) {
7994: /* take absolute value of each entry */
7995: for (c = a, kk = 0; c && kk < 2; c = b, kk++) {
7996: MatInfo info;
7997: PetscScalar *avals;
7999: PetscCall(MatGetInfo(c, MAT_LOCAL, &info));
8000: PetscCall(MatSeqAIJGetArray(c, &avals));
8001: for (int jj = 0; jj < info.nz_used; jj++) avals[jj] = PetscAbsScalar(avals[jj]);
8002: PetscCall(MatSeqAIJRestoreArray(c, &avals));
8003: }
8004: }
8005: }
8006: if (symmetrize) {
8007: PetscBool isset, issym;
8009: PetscCall(MatIsSymmetricKnown(Amat, &isset, &issym));
8010: if (!isset || !issym) {
8011: Mat matTrans;
8013: PetscCall(MatTranspose(Gmat, MAT_INITIAL_MATRIX, &matTrans));
8014: PetscCall(MatAXPY(Gmat, 1.0, matTrans, Gmat->structurally_symmetric == PETSC_BOOL3_TRUE ? SAME_NONZERO_PATTERN : DIFFERENT_NONZERO_PATTERN));
8015: PetscCall(MatDestroy(&matTrans));
8016: }
8017: PetscCall(MatSetOption(Gmat, MAT_SYMMETRIC, PETSC_TRUE));
8018: } else if (Amat != Gmat) PetscCall(MatPropagateSymmetryOptions(Amat, Gmat));
8019: if (scale) {
8020: /* scale c for all diagonal values = 1 or -1 */
8021: Vec diag;
8023: PetscCall(MatCreateVecs(Gmat, &diag, NULL));
8024: PetscCall(MatGetDiagonal(Gmat, diag));
8025: PetscCall(VecReciprocal(diag));
8026: PetscCall(VecSqrtAbs(diag));
8027: PetscCall(MatDiagonalScale(Gmat, diag, diag));
8028: PetscCall(VecDestroy(&diag));
8029: }
8030: PetscCall(MatViewFromOptions(Gmat, NULL, "-mat_graph_view"));
8031: if (filter >= 0) {
8032: PetscCall(MatFilter(Gmat, filter, PETSC_TRUE, PETSC_TRUE));
8033: PetscCall(MatViewFromOptions(Gmat, NULL, "-mat_filter_graph_view"));
8034: }
8035: *a_Gmat = Gmat;
8036: PetscFunctionReturn(PETSC_SUCCESS);
8037: }
8039: PETSC_INTERN PetscErrorCode MatGetCurrentMemType_MPIAIJ(Mat A, PetscMemType *memtype)
8040: {
8041: Mat_MPIAIJ *mpiaij = (Mat_MPIAIJ *)A->data;
8042: PetscMemType mD = PETSC_MEMTYPE_HOST, mO = PETSC_MEMTYPE_HOST;
8044: PetscFunctionBegin;
8045: if (mpiaij->A) PetscCall(MatGetCurrentMemType(mpiaij->A, &mD));
8046: if (mpiaij->B) PetscCall(MatGetCurrentMemType(mpiaij->B, &mO));
8047: *memtype = (mD == mO) ? mD : PETSC_MEMTYPE_HOST;
8048: PetscFunctionReturn(PETSC_SUCCESS);
8049: }
8051: /*
8052: Special version for direct calls from Fortran
8053: */
8055: /* Change these macros so can be used in void function */
8056: /* Identical to PetscCallVoid, except it assigns to *_ierr */
8057: #undef PetscCall
8058: #define PetscCall(...) \
8059: do { \
8060: PetscErrorCode ierr_msv_mpiaij = __VA_ARGS__; \
8061: if (PetscUnlikely(ierr_msv_mpiaij)) { \
8062: *_ierr = PetscError(PETSC_COMM_SELF, __LINE__, PETSC_FUNCTION_NAME, __FILE__, ierr_msv_mpiaij, PETSC_ERROR_REPEAT, " "); \
8063: return; \
8064: } \
8065: } while (0)
8067: #undef SETERRQ
8068: #define SETERRQ(comm, ierr, ...) \
8069: do { \
8070: *_ierr = PetscError(comm, __LINE__, PETSC_FUNCTION_NAME, __FILE__, ierr, PETSC_ERROR_INITIAL, __VA_ARGS__); \
8071: return; \
8072: } while (0)
8074: #if defined(PETSC_HAVE_FORTRAN_CAPS)
8075: #define matsetvaluesmpiaij_ MATSETVALUESMPIAIJ
8076: #elif !defined(PETSC_HAVE_FORTRAN_UNDERSCORE)
8077: #define matsetvaluesmpiaij_ matsetvaluesmpiaij
8078: #else
8079: #endif
8080: PETSC_EXTERN void matsetvaluesmpiaij_(Mat *mmat, PetscInt *mm, const PetscInt im[], PetscInt *mn, const PetscInt in[], const PetscScalar v[], InsertMode *maddv, PetscErrorCode *_ierr)
8081: {
8082: Mat mat = *mmat;
8083: PetscInt m = *mm, n = *mn;
8084: InsertMode addv = *maddv;
8085: Mat_MPIAIJ *aij = (Mat_MPIAIJ *)mat->data;
8086: PetscScalar value;
8088: MatCheckPreallocated(mat, 1);
8089: if (mat->insertmode == NOT_SET_VALUES) mat->insertmode = addv;
8090: else PetscCheck(mat->insertmode == addv, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Cannot mix add values and insert values");
8091: {
8092: PetscInt i, j, rstart = mat->rmap->rstart, rend = mat->rmap->rend;
8093: PetscInt cstart = mat->cmap->rstart, cend = mat->cmap->rend, row, col;
8094: PetscBool roworiented = aij->roworiented;
8096: /* Some Variables required in the macro */
8097: Mat A = aij->A;
8098: Mat_SeqAIJ *a = (Mat_SeqAIJ *)A->data;
8099: PetscInt *aimax = a->imax, *ai = a->i, *ailen = a->ilen, *aj = a->j;
8100: MatScalar *aa;
8101: PetscBool ignorezeroentries = ((a->ignorezeroentries && (addv == ADD_VALUES)) ? PETSC_TRUE : PETSC_FALSE);
8102: Mat B = aij->B;
8103: Mat_SeqAIJ *b = (Mat_SeqAIJ *)B->data;
8104: PetscInt *bimax = b->imax, *bi = b->i, *bilen = b->ilen, *bj = b->j, bm = aij->B->rmap->n, am = aij->A->rmap->n;
8105: MatScalar *ba;
8106: /* This variable below is only for the PETSC_HAVE_VIENNACL or PETSC_HAVE_CUDA cases, but we define it in all cases because we
8107: * cannot use "#if defined" inside a macro. */
8108: PETSC_UNUSED PetscBool inserted = PETSC_FALSE;
8110: PetscInt *rp1, *rp2, ii, nrow1, nrow2, _i, rmax1, rmax2, N, low1, high1, low2, high2, t, lastcol1, lastcol2;
8111: PetscInt nonew = a->nonew;
8112: MatScalar *ap1, *ap2;
8114: PetscFunctionBegin;
8115: PetscCall(MatSeqAIJGetArray(A, &aa));
8116: PetscCall(MatSeqAIJGetArray(B, &ba));
8117: for (i = 0; i < m; i++) {
8118: if (im[i] < 0) continue;
8119: PetscCheck(im[i] < mat->rmap->N, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Row too large: row %" PetscInt_FMT " max %" PetscInt_FMT, im[i], mat->rmap->N - 1);
8120: if (im[i] >= rstart && im[i] < rend) {
8121: row = im[i] - rstart;
8122: lastcol1 = -1;
8123: rp1 = aj + ai[row];
8124: ap1 = aa + ai[row];
8125: rmax1 = aimax[row];
8126: nrow1 = ailen[row];
8127: low1 = 0;
8128: high1 = nrow1;
8129: lastcol2 = -1;
8130: rp2 = bj + bi[row];
8131: ap2 = ba + bi[row];
8132: rmax2 = bimax[row];
8133: nrow2 = bilen[row];
8134: low2 = 0;
8135: high2 = nrow2;
8137: for (j = 0; j < n; j++) {
8138: if (roworiented) value = v[i * n + j];
8139: else value = v[i + j * m];
8140: if (ignorezeroentries && value == 0.0 && (addv == ADD_VALUES) && im[i] != in[j]) continue;
8141: if (in[j] >= cstart && in[j] < cend) {
8142: col = in[j] - cstart;
8143: MatSetValues_SeqAIJ_A_Private(row, col, value, addv, im[i], in[j]);
8144: } else if (in[j] < 0) continue;
8145: else if (PetscUnlikelyDebug(in[j] >= mat->cmap->N)) {
8146: SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Column too large: col %" PetscInt_FMT " max %" PetscInt_FMT, in[j], mat->cmap->N - 1);
8147: } else {
8148: if (mat->was_assembled) {
8149: if (!aij->colmap) PetscCall(MatCreateColmap_MPIAIJ_Private(mat));
8150: #if defined(PETSC_USE_CTABLE)
8151: PetscCall(PetscHMapIGetWithDefault(aij->colmap, in[j] + 1, 0, &col));
8152: col--;
8153: #else
8154: col = aij->colmap[in[j]] - 1;
8155: #endif
8156: if (col < 0 && !((Mat_SeqAIJ *)aij->A->data)->nonew) {
8157: PetscCall(MatDisAssemble_MPIAIJ(mat, PETSC_FALSE));
8158: col = in[j];
8159: /* Reinitialize the variables required by MatSetValues_SeqAIJ_B_Private() */
8160: B = aij->B;
8161: b = (Mat_SeqAIJ *)B->data;
8162: bimax = b->imax;
8163: bi = b->i;
8164: bilen = b->ilen;
8165: bj = b->j;
8166: rp2 = bj + bi[row];
8167: ap2 = ba + bi[row];
8168: rmax2 = bimax[row];
8169: nrow2 = bilen[row];
8170: low2 = 0;
8171: high2 = nrow2;
8172: bm = aij->B->rmap->n;
8173: ba = b->a;
8174: inserted = PETSC_FALSE;
8175: }
8176: } else col = in[j];
8177: MatSetValues_SeqAIJ_B_Private(row, col, value, addv, im[i], in[j]);
8178: }
8179: }
8180: } else if (!aij->donotstash) {
8181: if (roworiented) {
8182: PetscCall(MatStashValuesRow_Private(&mat->stash, im[i], n, in, v + i * n, (PetscBool)(ignorezeroentries && (addv == ADD_VALUES))));
8183: } else {
8184: PetscCall(MatStashValuesCol_Private(&mat->stash, im[i], n, in, v + i, m, (PetscBool)(ignorezeroentries && (addv == ADD_VALUES))));
8185: }
8186: }
8187: }
8188: PetscCall(MatSeqAIJRestoreArray(A, &aa));
8189: PetscCall(MatSeqAIJRestoreArray(B, &ba));
8190: }
8191: PetscFunctionReturnVoid();
8192: }
8194: /* Undefining these here since they were redefined from their original definition above! No
8195: * other PETSc functions should be defined past this point, as it is impossible to recover the
8196: * original definitions */
8197: #undef PetscCall
8198: #undef SETERRQ