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 PetscDefined(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, "MatGetMultPetscSF_C", NULL));
67: PetscCall(PetscObjectComposeFunction((PetscObject)mat, "MatIsTranspose_C", NULL));
68: PetscCall(PetscObjectComposeFunction((PetscObject)mat, "MatMPIAIJSetPreallocation_C", NULL));
69: PetscCall(PetscObjectComposeFunction((PetscObject)mat, "MatResetPreallocation_C", NULL));
70: PetscCall(PetscObjectComposeFunction((PetscObject)mat, "MatResetHash_C", NULL));
71: PetscCall(PetscObjectComposeFunction((PetscObject)mat, "MatMPIAIJSetPreallocationCSR_C", NULL));
72: PetscCall(PetscObjectComposeFunction((PetscObject)mat, "MatDiagonalScaleLocal_C", NULL));
73: PetscCall(PetscObjectComposeFunction((PetscObject)mat, "MatConvert_mpiaij_mpibaij_C", NULL));
74: PetscCall(PetscObjectComposeFunction((PetscObject)mat, "MatConvert_mpiaij_mpisbaij_C", NULL));
75: #if PetscDefined(HAVE_CUDA)
76: PetscCall(PetscObjectComposeFunction((PetscObject)mat, "MatConvert_mpiaij_mpiaijcusparse_C", NULL));
77: #endif
78: #if PetscDefined(HAVE_HIP)
79: PetscCall(PetscObjectComposeFunction((PetscObject)mat, "MatConvert_mpiaij_mpiaijhipsparse_C", NULL));
80: #endif
81: #if PetscDefined(HAVE_KOKKOS_KERNELS)
82: PetscCall(PetscObjectComposeFunction((PetscObject)mat, "MatConvert_mpiaij_mpiaijkokkos_C", NULL));
83: #endif
84: PetscCall(PetscObjectComposeFunction((PetscObject)mat, "MatConvert_mpiaij_mpidense_C", NULL));
85: #if PetscDefined(HAVE_ELEMENTAL)
86: PetscCall(PetscObjectComposeFunction((PetscObject)mat, "MatConvert_mpiaij_elemental_C", NULL));
87: #endif
88: #if PetscDefined(HAVE_SCALAPACK) && (PetscDefined(USE_REAL_SINGLE) || PetscDefined(USE_REAL_DOUBLE))
89: PetscCall(PetscObjectComposeFunction((PetscObject)mat, "MatConvert_mpiaij_scalapack_C", NULL));
90: #endif
91: #if PetscDefined(HAVE_HYPRE)
92: PetscCall(PetscObjectComposeFunction((PetscObject)mat, "MatConvert_mpiaij_hypre_C", NULL));
93: PetscCall(PetscObjectComposeFunction((PetscObject)mat, "MatProductSetFromOptions_transpose_mpiaij_mpiaij_C", NULL));
94: #endif
95: PetscCall(PetscObjectComposeFunction((PetscObject)mat, "MatConvert_mpiaij_is_C", NULL));
96: PetscCall(PetscObjectComposeFunction((PetscObject)mat, "MatProductSetFromOptions_is_mpiaij_C", NULL));
97: PetscCall(PetscObjectComposeFunction((PetscObject)mat, "MatProductSetFromOptions_mpiaij_mpiaij_C", NULL));
98: PetscCall(PetscObjectComposeFunction((PetscObject)mat, "MatMPIAIJSetUseScalableIncreaseOverlap_C", NULL));
99: PetscCall(PetscObjectComposeFunction((PetscObject)mat, "MatConvert_mpiaij_mpiaijperm_C", NULL));
100: PetscCall(PetscObjectComposeFunction((PetscObject)mat, "MatConvert_mpiaij_mpiaijsell_C", NULL));
101: #if PetscDefined(HAVE_MKL_SPARSE)
102: PetscCall(PetscObjectComposeFunction((PetscObject)mat, "MatConvert_mpiaij_mpiaijmkl_C", NULL));
103: #endif
104: PetscCall(PetscObjectComposeFunction((PetscObject)mat, "MatConvert_mpiaij_mpiaijcrl_C", NULL));
105: PetscCall(PetscObjectComposeFunction((PetscObject)mat, "MatConvert_mpiaij_is_C", NULL));
106: PetscCall(PetscObjectComposeFunction((PetscObject)mat, "MatConvert_mpiaij_mpisell_C", NULL));
107: PetscCall(PetscObjectComposeFunction((PetscObject)mat, "MatSetPreallocationCOO_C", NULL));
108: PetscCall(PetscObjectComposeFunction((PetscObject)mat, "MatSetValuesCOO_C", NULL));
109: PetscFunctionReturn(PETSC_SUCCESS);
110: }
112: static PetscErrorCode MatGetRowIJ_MPIAIJ(Mat A, PetscInt oshift, PetscBool symmetric, PetscBool inodecompressed, PetscInt *m, const PetscInt *ia[], const PetscInt *ja[], PetscBool *done)
113: {
114: Mat B;
116: PetscFunctionBegin;
117: PetscCall(MatMPIAIJGetLocalMat(A, MAT_INITIAL_MATRIX, &B));
118: PetscCall(PetscObjectCompose((PetscObject)A, "MatGetRowIJ_MPIAIJ", (PetscObject)B));
119: PetscCall(MatGetRowIJ(B, oshift, symmetric, inodecompressed, m, ia, ja, done));
120: PetscCall(MatDestroy(&B));
121: PetscFunctionReturn(PETSC_SUCCESS);
122: }
124: static PetscErrorCode MatRestoreRowIJ_MPIAIJ(Mat A, PetscInt oshift, PetscBool symmetric, PetscBool inodecompressed, PetscInt *m, const PetscInt *ia[], const PetscInt *ja[], PetscBool *done)
125: {
126: Mat B;
128: PetscFunctionBegin;
129: PetscCall(PetscObjectQuery((PetscObject)A, "MatGetRowIJ_MPIAIJ", (PetscObject *)&B));
130: PetscCall(MatRestoreRowIJ(B, oshift, symmetric, inodecompressed, m, ia, ja, done));
131: PetscCall(PetscObjectCompose((PetscObject)A, "MatGetRowIJ_MPIAIJ", NULL));
132: PetscFunctionReturn(PETSC_SUCCESS);
133: }
135: /*MC
136: MATAIJCRL - MATAIJCRL = "aijcrl" - A matrix type to be used for sparse matrices.
138: This matrix type is identical to `MATSEQAIJCRL` when constructed with a single process communicator,
139: and `MATMPIAIJCRL` otherwise. As a result, for single process communicators,
140: `MatSeqAIJSetPreallocation()` is supported, and similarly `MatMPIAIJSetPreallocation()` is supported
141: for communicators controlling multiple processes. It is recommended that you call both of
142: the above preallocation routines for simplicity.
144: Options Database Key:
145: . -mat_type aijcrl - sets the matrix type to `MATMPIAIJCRL` during a call to `MatSetFromOptions()`
147: Level: beginner
149: .seealso: [](ch_matrices), `Mat`, `MatCreateMPIAIJCRL`, `MATSEQAIJCRL`, `MATMPIAIJCRL`, `MATSEQAIJ`, `MATMPIAIJ`, `MATAIJ`
150: M*/
152: static PetscErrorCode MatBindToCPU_MPIAIJ(Mat A, PetscBool flg)
153: {
154: Mat_MPIAIJ *a = (Mat_MPIAIJ *)A->data;
156: PetscFunctionBegin;
157: #if PetscDefined(HAVE_CUDA) || PetscDefined(HAVE_HIP) || PetscDefined(HAVE_VIENNACL)
158: A->boundtocpu = flg;
159: #endif
160: if (a->A) PetscCall(MatBindToCPU(a->A, flg));
161: if (a->B) PetscCall(MatBindToCPU(a->B, flg));
163: /* In addition to binding the diagonal and off-diagonal matrices, bind the local vectors used for matrix-vector products.
164: * This maybe seems a little odd for a MatBindToCPU() call to do, but it makes no sense for the binding of these vectors
165: * to differ from the parent matrix. */
166: if (a->lvec) PetscCall(VecBindToCPU(a->lvec, flg));
167: if (a->diag) PetscCall(VecBindToCPU(a->diag, flg));
168: PetscFunctionReturn(PETSC_SUCCESS);
169: }
171: static PetscErrorCode MatSetBlockSizes_MPIAIJ(Mat M, PetscInt rbs, PetscInt cbs)
172: {
173: Mat_MPIAIJ *mat = (Mat_MPIAIJ *)M->data;
175: PetscFunctionBegin;
176: if (mat->A) {
177: PetscCall(MatSetBlockSizes(mat->A, rbs, cbs));
178: PetscCall(MatSetBlockSizes(mat->B, rbs, 1));
179: }
180: PetscFunctionReturn(PETSC_SUCCESS);
181: }
183: static PetscErrorCode MatFindNonzeroRows_MPIAIJ(Mat M, IS *keptrows)
184: {
185: Mat_MPIAIJ *mat = (Mat_MPIAIJ *)M->data;
186: Mat_SeqAIJ *a = (Mat_SeqAIJ *)mat->A->data;
187: Mat_SeqAIJ *b = (Mat_SeqAIJ *)mat->B->data;
188: const PetscInt *ia, *ib;
189: const MatScalar *aa, *bb, *aav, *bav;
190: PetscInt na, nb, i, j, *rows, cnt = 0, n0rows;
191: PetscInt m = M->rmap->n, rstart = M->rmap->rstart;
193: PetscFunctionBegin;
194: *keptrows = NULL;
196: ia = a->i;
197: ib = b->i;
198: PetscCall(MatSeqAIJGetArrayRead(mat->A, &aav));
199: PetscCall(MatSeqAIJGetArrayRead(mat->B, &bav));
200: for (i = 0; i < m; i++) {
201: na = ia[i + 1] - ia[i];
202: nb = ib[i + 1] - ib[i];
203: if (!na && !nb) {
204: cnt++;
205: goto ok1;
206: }
207: aa = aav + ia[i];
208: for (j = 0; j < na; j++) {
209: if (aa[j] != 0.0) goto ok1;
210: }
211: bb = PetscSafePointerPlusOffset(bav, ib[i]);
212: for (j = 0; j < nb; j++) {
213: if (bb[j] != 0.0) goto ok1;
214: }
215: cnt++;
216: ok1:;
217: }
218: PetscCallMPI(MPIU_Allreduce(&cnt, &n0rows, 1, MPIU_INT, MPI_SUM, PetscObjectComm((PetscObject)M)));
219: if (!n0rows) {
220: PetscCall(MatSeqAIJRestoreArrayRead(mat->A, &aav));
221: PetscCall(MatSeqAIJRestoreArrayRead(mat->B, &bav));
222: PetscFunctionReturn(PETSC_SUCCESS);
223: }
224: PetscCall(PetscMalloc1(M->rmap->n - cnt, &rows));
225: cnt = 0;
226: for (i = 0; i < m; i++) {
227: na = ia[i + 1] - ia[i];
228: nb = ib[i + 1] - ib[i];
229: if (!na && !nb) continue;
230: aa = aav + ia[i];
231: for (j = 0; j < na; j++) {
232: if (aa[j] != 0.0) {
233: rows[cnt++] = rstart + i;
234: goto ok2;
235: }
236: }
237: bb = PetscSafePointerPlusOffset(bav, ib[i]);
238: for (j = 0; j < nb; j++) {
239: if (bb[j] != 0.0) {
240: rows[cnt++] = rstart + i;
241: goto ok2;
242: }
243: }
244: ok2:;
245: }
246: PetscCall(ISCreateGeneral(PetscObjectComm((PetscObject)M), cnt, rows, PETSC_OWN_POINTER, keptrows));
247: PetscCall(MatSeqAIJRestoreArrayRead(mat->A, &aav));
248: PetscCall(MatSeqAIJRestoreArrayRead(mat->B, &bav));
249: PetscFunctionReturn(PETSC_SUCCESS);
250: }
252: static PetscErrorCode MatDiagonalSet_MPIAIJ(Mat Y, Vec D, InsertMode is)
253: {
254: Mat_MPIAIJ *aij = (Mat_MPIAIJ *)Y->data;
255: PetscBool cong;
257: PetscFunctionBegin;
258: PetscCall(MatHasCongruentLayouts(Y, &cong));
259: if (Y->assembled && cong) PetscCall(MatDiagonalSet(aij->A, D, is));
260: else PetscCall(MatDiagonalSet_Default(Y, D, is));
261: PetscFunctionReturn(PETSC_SUCCESS);
262: }
264: static PetscErrorCode MatFindZeroDiagonals_MPIAIJ(Mat M, IS *zrows)
265: {
266: Mat_MPIAIJ *aij = (Mat_MPIAIJ *)M->data;
267: PetscInt i, rstart, nrows, *rows;
269: PetscFunctionBegin;
270: *zrows = NULL;
271: PetscCall(MatFindZeroDiagonals_SeqAIJ_Private(aij->A, &nrows, &rows));
272: PetscCall(MatGetOwnershipRange(M, &rstart, NULL));
273: for (i = 0; i < nrows; i++) rows[i] += rstart;
274: PetscCall(ISCreateGeneral(PetscObjectComm((PetscObject)M), nrows, rows, PETSC_OWN_POINTER, zrows));
275: PetscFunctionReturn(PETSC_SUCCESS);
276: }
278: static PetscErrorCode MatGetColumnReductions_MPIAIJ(Mat A, PetscInt type, PetscReal *reductions)
279: {
280: Mat_MPIAIJ *aij = (Mat_MPIAIJ *)A->data;
281: PetscInt i, m, n, *garray = aij->garray;
282: Mat_SeqAIJ *a_aij = (Mat_SeqAIJ *)aij->A->data;
283: Mat_SeqAIJ *b_aij = (Mat_SeqAIJ *)aij->B->data;
284: const PetscScalar *dummy;
286: PetscFunctionBegin;
287: PetscCall(MatGetSize(A, &m, &n));
288: PetscCall(PetscArrayzero(reductions, n));
289: PetscCall(MatSeqAIJGetArrayRead(aij->A, &dummy));
290: PetscCall(MatSeqAIJRestoreArrayRead(aij->A, &dummy));
291: PetscCall(MatSeqAIJGetArrayRead(aij->B, &dummy));
292: PetscCall(MatSeqAIJRestoreArrayRead(aij->B, &dummy));
293: if (type == NORM_2) {
294: for (i = 0; i < a_aij->i[aij->A->rmap->n]; i++) reductions[A->cmap->rstart + a_aij->j[i]] += PetscAbsScalar(a_aij->a[i] * a_aij->a[i]);
295: for (i = 0; i < b_aij->i[aij->B->rmap->n]; i++) reductions[garray[b_aij->j[i]]] += PetscAbsScalar(b_aij->a[i] * b_aij->a[i]);
296: } else if (type == NORM_1) {
297: for (i = 0; i < a_aij->i[aij->A->rmap->n]; i++) reductions[A->cmap->rstart + a_aij->j[i]] += PetscAbsScalar(a_aij->a[i]);
298: for (i = 0; i < b_aij->i[aij->B->rmap->n]; i++) reductions[garray[b_aij->j[i]]] += PetscAbsScalar(b_aij->a[i]);
299: } else if (type == NORM_INFINITY) {
300: for (i = 0; i < a_aij->i[aij->A->rmap->n]; i++) reductions[A->cmap->rstart + a_aij->j[i]] = PetscMax(PetscAbsScalar(a_aij->a[i]), reductions[A->cmap->rstart + a_aij->j[i]]);
301: for (i = 0; i < b_aij->i[aij->B->rmap->n]; i++) reductions[garray[b_aij->j[i]]] = PetscMax(PetscAbsScalar(b_aij->a[i]), reductions[garray[b_aij->j[i]]]);
302: } else if (type == REDUCTION_SUM_REALPART || type == REDUCTION_MEAN_REALPART) {
303: for (i = 0; i < a_aij->i[aij->A->rmap->n]; i++) reductions[A->cmap->rstart + a_aij->j[i]] += PetscRealPart(a_aij->a[i]);
304: for (i = 0; i < b_aij->i[aij->B->rmap->n]; i++) reductions[garray[b_aij->j[i]]] += PetscRealPart(b_aij->a[i]);
305: } else {
306: PetscCheck(type == REDUCTION_SUM_IMAGINARYPART || type == REDUCTION_MEAN_IMAGINARYPART, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_WRONG, "Unknown reduction type");
307: for (i = 0; i < a_aij->i[aij->A->rmap->n]; i++) reductions[A->cmap->rstart + a_aij->j[i]] += PetscImaginaryPart(a_aij->a[i]);
308: for (i = 0; i < b_aij->i[aij->B->rmap->n]; i++) reductions[garray[b_aij->j[i]]] += PetscImaginaryPart(b_aij->a[i]);
309: }
310: PetscCallMPI(MPIU_Allreduce(MPI_IN_PLACE, reductions, n, MPIU_REAL, type == NORM_INFINITY ? MPIU_MAX : MPIU_SUM, PetscObjectComm((PetscObject)A)));
311: if (type == NORM_2) {
312: for (i = 0; i < n; i++) reductions[i] = PetscSqrtReal(reductions[i]);
313: } else if (type == REDUCTION_MEAN_REALPART || type == REDUCTION_MEAN_IMAGINARYPART) {
314: for (i = 0; i < n; i++) reductions[i] /= m;
315: }
316: PetscFunctionReturn(PETSC_SUCCESS);
317: }
319: static PetscErrorCode MatFindOffBlockDiagonalEntries_MPIAIJ(Mat A, IS *is)
320: {
321: Mat_MPIAIJ *a = (Mat_MPIAIJ *)A->data;
322: IS sis, gis;
323: const PetscInt *isis, *igis;
324: PetscInt n, *iis, nsis, ngis, rstart, i;
326: PetscFunctionBegin;
327: PetscCall(MatFindOffBlockDiagonalEntries(a->A, &sis));
328: PetscCall(MatFindNonzeroRows(a->B, &gis));
329: PetscCall(ISGetSize(gis, &ngis));
330: PetscCall(ISGetSize(sis, &nsis));
331: PetscCall(ISGetIndices(sis, &isis));
332: PetscCall(ISGetIndices(gis, &igis));
334: PetscCall(PetscMalloc1(ngis + nsis, &iis));
335: PetscCall(PetscArraycpy(iis, igis, ngis));
336: PetscCall(PetscArraycpy(iis + ngis, isis, nsis));
337: n = ngis + nsis;
338: PetscCall(PetscSortRemoveDupsInt(&n, iis));
339: PetscCall(MatGetOwnershipRange(A, &rstart, NULL));
340: for (i = 0; i < n; i++) iis[i] += rstart;
341: PetscCall(ISCreateGeneral(PetscObjectComm((PetscObject)A), n, iis, PETSC_OWN_POINTER, is));
343: PetscCall(ISRestoreIndices(sis, &isis));
344: PetscCall(ISRestoreIndices(gis, &igis));
345: PetscCall(ISDestroy(&sis));
346: PetscCall(ISDestroy(&gis));
347: PetscFunctionReturn(PETSC_SUCCESS);
348: }
350: /*
351: Local utility routine that creates a mapping from the global column
352: number to the local number in the off-diagonal part of the local
353: storage of the matrix. When PETSC_USE_CTABLE is used this is scalable at
354: a slightly higher hash table cost; without it it is not scalable (each processor
355: has an order N integer array but is fast to access.
356: */
357: PetscErrorCode MatCreateColmap_MPIAIJ_Private(Mat mat)
358: {
359: Mat_MPIAIJ *aij = (Mat_MPIAIJ *)mat->data;
360: PetscInt n = aij->B->cmap->n, i;
362: PetscFunctionBegin;
363: PetscCheck(!n || aij->garray, PETSC_COMM_SELF, PETSC_ERR_PLIB, "MPIAIJ Matrix was assembled but is missing garray");
364: #if PetscDefined(USE_CTABLE)
365: PetscCall(PetscHMapICreateWithSize(n, &aij->colmap));
366: for (i = 0; i < n; i++) PetscCall(PetscHMapISet(aij->colmap, aij->garray[i] + 1, i + 1));
367: #else
368: PetscCall(PetscCalloc1(mat->cmap->N + 1, &aij->colmap));
369: for (i = 0; i < n; i++) aij->colmap[aij->garray[i]] = i + 1;
370: #endif
371: PetscFunctionReturn(PETSC_SUCCESS);
372: }
374: #define MatSetValues_SeqAIJ_A_Private(row, col, value, addv, orow, ocol) \
375: do { \
376: if ((col) <= lastcol1) low1 = 0; \
377: else high1 = nrow1; \
378: lastcol1 = col; \
379: while (high1 - low1 > 5) { \
380: t = (low1 + high1) / 2; \
381: if (rp1[t] > (col)) high1 = t; \
382: else low1 = t; \
383: } \
384: for (_i = low1; _i < high1; _i++) { \
385: if (rp1[_i] > (col)) break; \
386: if (rp1[_i] == (col)) { \
387: if (A->structure_only) goto a_noinsert; \
388: if ((addv) == ADD_VALUES) { \
389: ap1[_i] += value; \
390: /* Not sure LogFlops will slow down the code or not */ \
391: (void)PetscLogFlops(1.0); \
392: } else ap1[_i] = value; \
393: goto a_noinsert; \
394: } \
395: } \
396: if (!A->structure_only && (value) == 0.0 && ignorezeroentries && (orow) != (ocol)) { \
397: low1 = 0; \
398: high1 = nrow1; \
399: goto a_noinsert; \
400: } \
401: if (nonew == 1) { \
402: low1 = 0; \
403: high1 = nrow1; \
404: goto a_noinsert; \
405: } \
406: 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); \
407: if (A->structure_only) MatSeqXAIJReallocateAIJ_structure_only(A, am, 1, nrow1, row, col, rmax1, ai, aj, rp1, aimax, nonew, MatScalar); \
408: else MatSeqXAIJReallocateAIJ(A, am, 1, nrow1, row, col, rmax1, aa, ai, aj, rp1, ap1, aimax, nonew, MatScalar); \
409: N = nrow1++ - 1; \
410: a->nz++; \
411: high1++; \
412: /* shift up all the later entries in this row */ \
413: PetscCall(PetscArraymove(rp1 + _i + 1, rp1 + _i, N - _i + 1)); \
414: rp1[_i] = col; \
415: if (!A->structure_only) { \
416: PetscCall(PetscArraymove(ap1 + _i + 1, ap1 + _i, N - _i + 1)); \
417: ap1[_i] = value; \
418: } \
419: a_noinsert:; \
420: ailen[row] = nrow1; \
421: } while (0)
423: #define MatSetValues_SeqAIJ_B_Private(row, col, value, addv, orow, ocol) \
424: do { \
425: if ((col) <= lastcol2) low2 = 0; \
426: else high2 = nrow2; \
427: lastcol2 = col; \
428: while (high2 - low2 > 5) { \
429: t = (low2 + high2) / 2; \
430: if (rp2[t] > (col)) high2 = t; \
431: else low2 = t; \
432: } \
433: for (_i = low2; _i < high2; _i++) { \
434: if (rp2[_i] > (col)) break; \
435: if (rp2[_i] == (col)) { \
436: if (B->structure_only) goto b_noinsert; \
437: if ((addv) == ADD_VALUES) { \
438: ap2[_i] += value; \
439: (void)PetscLogFlops(1.0); \
440: } else ap2[_i] = value; \
441: goto b_noinsert; \
442: } \
443: } \
444: if (!B->structure_only && (value) == 0.0 && ignorezeroentries) { \
445: low2 = 0; \
446: high2 = nrow2; \
447: goto b_noinsert; \
448: } \
449: if (nonew == 1) { \
450: low2 = 0; \
451: high2 = nrow2; \
452: goto b_noinsert; \
453: } \
454: 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); \
455: if (B->structure_only) MatSeqXAIJReallocateAIJ_structure_only(B, bm, 1, nrow2, row, col, rmax2, bi, bj, rp2, bimax, nonew, MatScalar); \
456: else MatSeqXAIJReallocateAIJ(B, bm, 1, nrow2, row, col, rmax2, ba, bi, bj, rp2, ap2, bimax, nonew, MatScalar); \
457: N = nrow2++ - 1; \
458: b->nz++; \
459: high2++; \
460: /* shift up all the later entries in this row */ \
461: PetscCall(PetscArraymove(rp2 + _i + 1, rp2 + _i, N - _i + 1)); \
462: rp2[_i] = col; \
463: if (!B->structure_only) { \
464: PetscCall(PetscArraymove(ap2 + _i + 1, ap2 + _i, N - _i + 1)); \
465: ap2[_i] = value; \
466: } \
467: b_noinsert:; \
468: bilen[row] = nrow2; \
469: } while (0)
471: static PetscErrorCode MatSetValuesRow_MPIAIJ(Mat A, PetscInt row, const PetscScalar v[])
472: {
473: Mat_MPIAIJ *mat = (Mat_MPIAIJ *)A->data;
474: Mat_SeqAIJ *a = (Mat_SeqAIJ *)mat->A->data, *b = (Mat_SeqAIJ *)mat->B->data;
475: PetscInt l, *garray = mat->garray, diag;
476: PetscScalar *aa, *ba;
478: PetscFunctionBegin;
479: /* code only works for square matrices A */
481: /* find size of row to the left of the diagonal part */
482: PetscCall(MatGetOwnershipRange(A, &diag, NULL));
483: row = row - diag;
484: for (l = 0; l < b->i[row + 1] - b->i[row]; l++) {
485: if (garray[b->j[b->i[row] + l]] > diag) break;
486: }
487: if (l) {
488: PetscCall(MatSeqAIJGetArray(mat->B, &ba));
489: PetscCall(PetscArraycpy(ba + b->i[row], v, l));
490: PetscCall(MatSeqAIJRestoreArray(mat->B, &ba));
491: }
493: /* diagonal part */
494: if (a->i[row + 1] - a->i[row]) {
495: PetscCall(MatSeqAIJGetArray(mat->A, &aa));
496: PetscCall(PetscArraycpy(aa + a->i[row], v + l, a->i[row + 1] - a->i[row]));
497: PetscCall(MatSeqAIJRestoreArray(mat->A, &aa));
498: }
500: /* right of diagonal part */
501: if (b->i[row + 1] - b->i[row] - l) {
502: PetscCall(MatSeqAIJGetArray(mat->B, &ba));
503: PetscCall(PetscArraycpy(ba + b->i[row] + l, v + l + a->i[row + 1] - a->i[row], b->i[row + 1] - b->i[row] - l));
504: PetscCall(MatSeqAIJRestoreArray(mat->B, &ba));
505: }
506: PetscFunctionReturn(PETSC_SUCCESS);
507: }
509: PetscErrorCode MatSetValues_MPIAIJ(Mat mat, PetscInt m, const PetscInt im[], PetscInt n, const PetscInt in[], const PetscScalar v[], InsertMode addv)
510: {
511: Mat_MPIAIJ *aij = (Mat_MPIAIJ *)mat->data;
512: PetscScalar value = 0.0;
513: PetscInt i, j, rstart = mat->rmap->rstart, rend = mat->rmap->rend;
514: PetscInt cstart = mat->cmap->rstart, cend = mat->cmap->rend, row, col;
515: PetscBool roworiented = aij->roworiented;
517: /* Some Variables required in the macro */
518: Mat A = aij->A;
519: Mat_SeqAIJ *a = (Mat_SeqAIJ *)A->data;
520: PetscInt *aimax = a->imax, *ai = a->i, *ailen = a->ilen, *aj = a->j;
521: const PetscBool ignorezeroentries = (PetscBool)(!mat->structure_only && a->ignorezeroentries);
522: Mat B = aij->B;
523: Mat_SeqAIJ *b = (Mat_SeqAIJ *)B->data;
524: PetscInt *bimax = b->imax, *bi = b->i, *bilen = b->ilen, *bj = b->j, bm = aij->B->rmap->n, am = aij->A->rmap->n;
525: MatScalar *aa, *ba;
526: PetscInt *rp1, *rp2, ii, nrow1, nrow2, _i, rmax1, rmax2, N, low1, high1, low2, high2, t, lastcol1, lastcol2;
527: PetscInt nonew;
528: MatScalar *ap1, *ap2;
530: PetscFunctionBegin;
531: PetscCall(MatSeqAIJGetArray(A, &aa));
532: PetscCall(MatSeqAIJGetArray(B, &ba));
533: for (i = 0; i < m; i++) {
534: if (im[i] < 0) continue;
535: 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);
536: if (im[i] >= rstart && im[i] < rend) {
537: row = im[i] - rstart;
538: lastcol1 = -1;
539: rp1 = PetscSafePointerPlusOffset(aj, ai[row]);
540: ap1 = PetscSafePointerPlusOffset(aa, ai[row]);
541: rmax1 = aimax[row];
542: nrow1 = ailen[row];
543: low1 = 0;
544: high1 = nrow1;
545: lastcol2 = -1;
546: rp2 = PetscSafePointerPlusOffset(bj, bi[row]);
547: ap2 = PetscSafePointerPlusOffset(ba, bi[row]);
548: rmax2 = bimax[row];
549: nrow2 = bilen[row];
550: low2 = 0;
551: high2 = nrow2;
553: for (j = 0; j < n; j++) {
554: if (v && !mat->structure_only) value = roworiented ? v[i * n + j] : v[i + j * m];
555: if (!mat->structure_only && ignorezeroentries && value == 0.0 && addv == ADD_VALUES && im[i] != in[j]) continue;
556: if (in[j] >= cstart && in[j] < cend) {
557: col = in[j] - cstart;
558: nonew = a->nonew;
559: MatSetValues_SeqAIJ_A_Private(row, col, value, addv, im[i], in[j]);
560: } else if (in[j] < 0) {
561: continue;
562: } else {
563: 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);
564: if (mat->was_assembled) {
565: if (!aij->colmap) PetscCall(MatCreateColmap_MPIAIJ_Private(mat));
566: #if PetscDefined(USE_CTABLE)
567: PetscCall(PetscHMapIGetWithDefault(aij->colmap, in[j] + 1, 0, &col)); /* map global col ids to local ones */
568: col--;
569: #else
570: col = aij->colmap[in[j]] - 1;
571: #endif
572: if (col < 0 && !((Mat_SeqAIJ *)aij->B->data)->nonew) { /* col < 0 means in[j] is a new col for B */
573: PetscCall(MatDisAssemble_MPIAIJ(mat, PETSC_FALSE)); /* Change aij->B from reduced/local format to expanded/global format */
574: col = in[j];
575: /* Reinitialize the variables required by MatSetValues_SeqAIJ_B_Private() */
576: B = aij->B;
577: b = (Mat_SeqAIJ *)B->data;
578: bimax = b->imax;
579: bi = b->i;
580: bilen = b->ilen;
581: bj = b->j;
582: ba = b->a;
583: rp2 = PetscSafePointerPlusOffset(bj, bi[row]);
584: ap2 = PetscSafePointerPlusOffset(ba, bi[row]);
585: rmax2 = bimax[row];
586: nrow2 = bilen[row];
587: low2 = 0;
588: high2 = nrow2;
589: bm = aij->B->rmap->n;
590: ba = b->a;
591: } else if (col < 0 && !(ignorezeroentries && value == 0.0)) {
592: 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]);
593: 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]));
594: }
595: } else col = in[j];
596: nonew = b->nonew;
597: MatSetValues_SeqAIJ_B_Private(row, col, value, addv, im[i], in[j]);
598: }
599: }
600: } else {
601: 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]);
602: if (!aij->donotstash) {
603: mat->assembled = PETSC_FALSE;
604: if (roworiented) {
605: PetscCall(MatStashValuesRow_Private(&mat->stash, im[i], n, in, PetscSafePointerPlusOffset(v, i * n), (PetscBool)(ignorezeroentries && addv == ADD_VALUES)));
606: } else {
607: PetscCall(MatStashValuesCol_Private(&mat->stash, im[i], n, in, PetscSafePointerPlusOffset(v, i), m, (PetscBool)(ignorezeroentries && addv == ADD_VALUES)));
608: }
609: }
610: }
611: }
612: PetscCall(MatSeqAIJRestoreArray(A, &aa)); /* aa, bb might have been free'd due to reallocation above. But we don't access them here */
613: PetscCall(MatSeqAIJRestoreArray(B, &ba));
614: PetscFunctionReturn(PETSC_SUCCESS);
615: }
617: /*
618: This function sets the j and ilen arrays (of the diagonal and off-diagonal part) of an MPIAIJ-matrix.
619: The values in mat_i have to be sorted and the values in mat_j have to be sorted for each row (CSR-like).
620: No off-processor parts off the matrix are allowed here and mat->was_assembled has to be PETSC_FALSE.
621: */
622: PetscErrorCode MatSetValues_MPIAIJ_CopyFromCSRFormat_Symbolic(Mat mat, const PetscInt mat_j[], const PetscInt mat_i[])
623: {
624: Mat_MPIAIJ *aij = (Mat_MPIAIJ *)mat->data;
625: Mat A = aij->A; /* diagonal part of the matrix */
626: Mat B = aij->B; /* off-diagonal part of the matrix */
627: Mat_SeqAIJ *a = (Mat_SeqAIJ *)A->data;
628: Mat_SeqAIJ *b = (Mat_SeqAIJ *)B->data;
629: PetscInt cstart = mat->cmap->rstart, cend = mat->cmap->rend, col;
630: PetscInt *ailen = a->ilen, *aj = a->j;
631: PetscInt *bilen = b->ilen, *bj = b->j;
632: PetscInt am = aij->A->rmap->n, j;
633: PetscInt diag_so_far = 0, dnz;
634: PetscInt offd_so_far = 0, onz;
636: PetscFunctionBegin;
637: /* Iterate over all rows of the matrix */
638: for (j = 0; j < am; j++) {
639: dnz = onz = 0;
640: /* Iterate over all non-zero columns of the current row */
641: for (col = mat_i[j]; col < mat_i[j + 1]; col++) {
642: /* If column is in the diagonal */
643: if (mat_j[col] >= cstart && mat_j[col] < cend) {
644: aj[diag_so_far++] = mat_j[col] - cstart;
645: dnz++;
646: } else { /* off-diagonal entries */
647: bj[offd_so_far++] = mat_j[col];
648: onz++;
649: }
650: }
651: ailen[j] = dnz;
652: bilen[j] = onz;
653: }
654: PetscFunctionReturn(PETSC_SUCCESS);
655: }
657: /*
658: This function sets the local j, a and ilen arrays (of the diagonal and off-diagonal part) of an MPIAIJ-matrix.
659: The values in mat_i have to be sorted and the values in mat_j have to be sorted for each row (CSR-like).
660: No off-processor parts off the matrix are allowed here, they are set at a later point by MatSetValues_MPIAIJ.
661: Also, mat->was_assembled has to be false, otherwise the statement aj[rowstart_diag+dnz_row] = mat_j[col] - cstart;
662: would not be true and the more complex MatSetValues_MPIAIJ has to be used.
663: */
664: PetscErrorCode MatSetValues_MPIAIJ_CopyFromCSRFormat(Mat mat, const PetscInt mat_j[], const PetscInt mat_i[], const PetscScalar mat_a[])
665: {
666: Mat_MPIAIJ *aij = (Mat_MPIAIJ *)mat->data;
667: Mat A = aij->A; /* diagonal part of the matrix */
668: Mat B = aij->B; /* off-diagonal part of the matrix */
669: Mat_SeqAIJ *aijd = (Mat_SeqAIJ *)aij->A->data, *aijo = (Mat_SeqAIJ *)aij->B->data;
670: Mat_SeqAIJ *a = (Mat_SeqAIJ *)A->data;
671: Mat_SeqAIJ *b = (Mat_SeqAIJ *)B->data;
672: PetscInt cstart = mat->cmap->rstart, cend = mat->cmap->rend;
673: PetscInt *ailen = a->ilen, *aj = a->j;
674: PetscInt *bilen = b->ilen, *bj = b->j;
675: PetscInt am = aij->A->rmap->n, j;
676: 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. */
677: PetscInt col, dnz_row, onz_row, rowstart_diag, rowstart_offd;
678: PetscScalar *aa = a->a, *ba = b->a;
680: PetscFunctionBegin;
681: /* Iterate over all rows of the matrix */
682: for (j = 0; j < am; j++) {
683: dnz_row = onz_row = 0;
684: rowstart_offd = full_offd_i[j];
685: rowstart_diag = full_diag_i[j];
686: /* Iterate over all non-zero columns of the current row */
687: for (col = mat_i[j]; col < mat_i[j + 1]; col++) {
688: /* If column is in the diagonal */
689: if (mat_j[col] >= cstart && mat_j[col] < cend) {
690: aj[rowstart_diag + dnz_row] = mat_j[col] - cstart;
691: aa[rowstart_diag + dnz_row] = mat_a[col];
692: dnz_row++;
693: } else { /* off-diagonal entries */
694: bj[rowstart_offd + onz_row] = mat_j[col];
695: ba[rowstart_offd + onz_row] = mat_a[col];
696: onz_row++;
697: }
698: }
699: ailen[j] = dnz_row;
700: bilen[j] = onz_row;
701: }
702: PetscFunctionReturn(PETSC_SUCCESS);
703: }
705: static PetscErrorCode MatGetValues_MPIAIJ(Mat mat, PetscInt m, const PetscInt idxm[], PetscInt n, const PetscInt idxn[], PetscScalar v[])
706: {
707: Mat_MPIAIJ *aij = (Mat_MPIAIJ *)mat->data;
708: PetscInt i, j, rstart = mat->rmap->rstart, rend = mat->rmap->rend;
709: PetscInt cstart = mat->cmap->rstart, cend = mat->cmap->rend, row, col;
710: PetscBool roworiented = aij->roworiented;
711: PetscScalar *value;
713: PetscFunctionBegin;
714: for (i = 0; i < m; i++) {
715: if (idxm[i] < 0) continue; /* negative row */
716: 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);
717: 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);
718: row = idxm[i] - rstart;
719: for (j = 0; j < n; j++) {
720: if (idxn[j] < 0) continue; /* negative column */
721: 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);
722: value = roworiented ? &v[j + i * n] : &v[i + j * m];
723: if (idxn[j] >= cstart && idxn[j] < cend) {
724: col = idxn[j] - cstart;
725: PetscCall(MatGetValues(aij->A, 1, &row, 1, &col, value));
726: } else {
727: if (!aij->colmap) PetscCall(MatCreateColmap_MPIAIJ_Private(mat));
728: #if PetscDefined(USE_CTABLE)
729: PetscCall(PetscHMapIGetWithDefault(aij->colmap, idxn[j] + 1, 0, &col));
730: col--;
731: #else
732: col = aij->colmap[idxn[j]] - 1;
733: #endif
734: if (col < 0 || aij->garray[col] != idxn[j]) *value = 0.0;
735: else PetscCall(MatGetValues(aij->B, 1, &row, 1, &col, value));
736: }
737: }
738: }
739: PetscFunctionReturn(PETSC_SUCCESS);
740: }
742: static PetscErrorCode MatAssemblyBegin_MPIAIJ(Mat mat, MatAssemblyType mode)
743: {
744: Mat_MPIAIJ *aij = (Mat_MPIAIJ *)mat->data;
745: PetscInt nstash, reallocs;
747: PetscFunctionBegin;
748: if (aij->donotstash || mat->nooffprocentries) PetscFunctionReturn(PETSC_SUCCESS);
750: PetscCall(MatStashScatterBegin_Private(mat, &mat->stash, mat->rmap->range));
751: PetscCall(MatStashGetInfo_Private(&mat->stash, &nstash, &reallocs));
752: PetscCall(PetscInfo(mat, "Stash has %" PetscInt_FMT " entries, uses %" PetscInt_FMT " mallocs.\n", nstash, reallocs));
753: PetscFunctionReturn(PETSC_SUCCESS);
754: }
756: PetscErrorCode MatAssemblyEnd_MPIAIJ(Mat mat, MatAssemblyType mode)
757: {
758: Mat_MPIAIJ *aij = (Mat_MPIAIJ *)mat->data;
759: PetscMPIInt n;
760: PetscInt i, j, rstart, ncols, flg;
761: PetscInt *row, *col;
762: PetscBool all_assembled;
763: PetscScalar *val;
765: /* do not use 'b = (Mat_SeqAIJ*)aij->B->data' as B can be reset in disassembly */
767: PetscFunctionBegin;
768: if (!aij->donotstash && !mat->nooffprocentries) {
769: while (1) {
770: PetscCall(MatStashScatterGetMesg_Private(&mat->stash, &n, &row, &col, &val, &flg));
771: if (!flg) break;
773: for (i = 0; i < n;) {
774: /* Now identify the consecutive vals belonging to the same row */
775: for (j = i, rstart = row[j]; j < n; j++) {
776: if (row[j] != rstart) break;
777: }
778: if (j < n) ncols = j - i;
779: else ncols = n - i;
780: /* Now assemble all these values with a single function call */
781: PetscCall(MatSetValues_MPIAIJ(mat, 1, row + i, ncols, col + i, val + i, mat->insertmode));
782: i = j;
783: }
784: }
785: PetscCall(MatStashScatterEnd_Private(&mat->stash));
786: }
787: #if PetscDefined(HAVE_DEVICE)
788: if (mat->offloadmask == PETSC_OFFLOAD_CPU) aij->A->offloadmask = PETSC_OFFLOAD_CPU;
789: /* We call MatBindToCPU() on aij->A and aij->B here, because if MatBindToCPU_MPIAIJ() is called before assembly, it cannot bind these. */
790: if (mat->boundtocpu) {
791: PetscCall(MatBindToCPU(aij->A, PETSC_TRUE));
792: PetscCall(MatBindToCPU(aij->B, PETSC_TRUE));
793: }
794: #endif
795: PetscCall(MatAssemblyBegin(aij->A, mode));
796: PetscCall(MatAssemblyEnd(aij->A, mode));
798: /* determine if any process has disassembled, if so we must
799: also disassemble ourself, in order that we may reassemble. */
800: /*
801: if nonzero structure of submatrix B cannot change then we know that
802: no process disassembled thus we can skip this stuff
803: */
804: if (!((Mat_SeqAIJ *)aij->B->data)->nonew) {
805: PetscCallMPI(MPIU_Allreduce(&mat->was_assembled, &all_assembled, 1, MPI_C_BOOL, MPI_LAND, PetscObjectComm((PetscObject)mat)));
806: if (mat->was_assembled && !all_assembled) { /* mat on this rank has reduced off-diag B with local col ids, but globally it does not */
807: PetscCall(MatDisAssemble_MPIAIJ(mat, PETSC_FALSE));
808: }
809: }
810: if (!mat->was_assembled && mode == MAT_FINAL_ASSEMBLY) PetscCall(MatSetUpMultiply_MPIAIJ(mat));
811: PetscCall(MatSetOption(aij->B, MAT_USE_INODES, PETSC_FALSE));
812: #if PetscDefined(HAVE_DEVICE)
813: if (mat->offloadmask == PETSC_OFFLOAD_CPU && aij->B->offloadmask != PETSC_OFFLOAD_UNALLOCATED) aij->B->offloadmask = PETSC_OFFLOAD_CPU;
814: #endif
815: PetscCall(MatAssemblyBegin(aij->B, mode));
816: PetscCall(MatAssemblyEnd(aij->B, mode));
818: PetscCall(PetscFree2(aij->rowvalues, aij->rowindices));
820: PetscCall(VecDestroy(&aij->diag));
822: /* if no new nonzero locations are allowed in matrix then only set the matrix state the first time through */
823: if ((!mat->was_assembled && mode == MAT_FINAL_ASSEMBLY) || !((Mat_SeqAIJ *)aij->A->data)->nonew) {
824: mat->nonzerostate = aij->A->nonzerostate + aij->B->nonzerostate;
825: PetscCallMPI(MPIU_Allreduce(MPI_IN_PLACE, &mat->nonzerostate, 1, MPIU_INT64, MPI_SUM, PetscObjectComm((PetscObject)mat)));
826: }
827: #if PetscDefined(HAVE_DEVICE)
828: mat->offloadmask = PETSC_OFFLOAD_BOTH;
829: #endif
830: PetscFunctionReturn(PETSC_SUCCESS);
831: }
833: static PetscErrorCode MatZeroEntries_MPIAIJ(Mat A)
834: {
835: Mat_MPIAIJ *l = (Mat_MPIAIJ *)A->data;
837: PetscFunctionBegin;
838: PetscCall(MatZeroEntries(l->A));
839: PetscCall(MatZeroEntries(l->B));
840: PetscFunctionReturn(PETSC_SUCCESS);
841: }
843: static PetscErrorCode MatZeroRows_MPIAIJ(Mat A, PetscInt N, const PetscInt rows[], PetscScalar diag, Vec x, Vec b)
844: {
845: Mat_MPIAIJ *mat = (Mat_MPIAIJ *)A->data;
846: PetscInt *lrows;
847: PetscInt r, len;
848: PetscBool cong;
850: PetscFunctionBegin;
851: /* get locally owned rows */
852: PetscCall(MatZeroRowsMapLocal_Private(A, N, rows, &len, &lrows));
853: PetscCall(MatHasCongruentLayouts(A, &cong));
854: /* fix right-hand side if needed */
855: if (x && b) {
856: const PetscScalar *xx;
857: PetscScalar *bb;
859: PetscCheck(cong, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "Need matching row/col layout");
860: PetscCall(VecGetArrayRead(x, &xx));
861: PetscCall(VecGetArray(b, &bb));
862: for (r = 0; r < len; ++r) bb[lrows[r]] = diag * xx[lrows[r]];
863: PetscCall(VecRestoreArrayRead(x, &xx));
864: PetscCall(VecRestoreArray(b, &bb));
865: }
867: if (diag != 0.0 && cong) {
868: PetscCall(MatZeroRows(mat->A, len, lrows, diag, NULL, NULL));
869: PetscCall(MatZeroRows(mat->B, len, lrows, 0.0, NULL, NULL));
870: } else if (diag != 0.0) { /* non-square or non congruent layouts -> if keepnonzeropattern is false, we allow for new insertion */
871: Mat_SeqAIJ *aijA = (Mat_SeqAIJ *)mat->A->data;
872: Mat_SeqAIJ *aijB = (Mat_SeqAIJ *)mat->B->data;
873: PetscInt nnwA, nnwB;
874: PetscBool nnzA, nnzB;
876: nnwA = aijA->nonew;
877: nnwB = aijB->nonew;
878: nnzA = aijA->keepnonzeropattern;
879: nnzB = aijB->keepnonzeropattern;
880: if (!nnzA) {
881: PetscCall(PetscInfo(mat->A, "Requested to not keep the pattern and add a nonzero diagonal; may encounter reallocations on diagonal block.\n"));
882: aijA->nonew = 0;
883: }
884: if (!nnzB) {
885: PetscCall(PetscInfo(mat->B, "Requested to not keep the pattern and add a nonzero diagonal; may encounter reallocations on off-diagonal block.\n"));
886: aijB->nonew = 0;
887: }
888: /* Must zero here before the next loop */
889: PetscCall(MatZeroRows(mat->A, len, lrows, 0.0, NULL, NULL));
890: PetscCall(MatZeroRows(mat->B, len, lrows, 0.0, NULL, NULL));
891: for (r = 0; r < len; ++r) {
892: const PetscInt row = lrows[r] + A->rmap->rstart;
893: if (row >= A->cmap->N) continue;
894: PetscCall(MatSetValues(A, 1, &row, 1, &row, &diag, INSERT_VALUES));
895: }
896: aijA->nonew = nnwA;
897: aijB->nonew = nnwB;
898: } else {
899: PetscCall(MatZeroRows(mat->A, len, lrows, 0.0, NULL, NULL));
900: PetscCall(MatZeroRows(mat->B, len, lrows, 0.0, NULL, NULL));
901: }
902: PetscCall(PetscFree(lrows));
903: PetscCall(MatAssemblyBegin(A, MAT_FINAL_ASSEMBLY));
904: PetscCall(MatAssemblyEnd(A, MAT_FINAL_ASSEMBLY));
906: /* only change matrix nonzero state if pattern was allowed to be changed */
907: if (!((Mat_SeqAIJ *)mat->A->data)->keepnonzeropattern || !((Mat_SeqAIJ *)mat->A->data)->nonew) {
908: A->nonzerostate = mat->A->nonzerostate + mat->B->nonzerostate;
909: PetscCallMPI(MPIU_Allreduce(MPI_IN_PLACE, &A->nonzerostate, 1, MPIU_INT64, MPI_SUM, PetscObjectComm((PetscObject)A)));
910: }
911: PetscFunctionReturn(PETSC_SUCCESS);
912: }
914: static PetscErrorCode MatZeroRowsColumns_MPIAIJ(Mat A, PetscInt N, const PetscInt rows[], PetscScalar diag, Vec x, Vec b)
915: {
916: Mat_MPIAIJ *l = (Mat_MPIAIJ *)A->data;
917: PetscInt n = A->rmap->n;
918: PetscInt i, j, r, m, len = 0;
919: PetscInt *lrows, *owners = A->rmap->range;
920: PetscMPIInt p = 0;
921: PetscSFNode *rrows;
922: PetscSF sf;
923: const PetscScalar *xx;
924: PetscScalar *bb, *mask, *aij_a;
925: Vec xmask, lmask;
926: Mat_SeqAIJ *aij = (Mat_SeqAIJ *)l->B->data;
927: const PetscInt *aj, *ii, *ridx;
928: PetscScalar *aa;
930: PetscFunctionBegin;
931: /* Create SF where leaves are input rows and roots are owned rows */
932: PetscCall(PetscMalloc1(n, &lrows));
933: for (r = 0; r < n; ++r) lrows[r] = -1;
934: PetscCall(PetscMalloc1(N, &rrows));
935: for (r = 0; r < N; ++r) {
936: const PetscInt idx = rows[r];
937: 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);
938: if (idx < owners[p] || owners[p + 1] <= idx) { /* short-circuit the search if the last p owns this row too */
939: PetscCall(PetscLayoutFindOwner(A->rmap, idx, &p));
940: }
941: rrows[r].rank = p;
942: rrows[r].index = rows[r] - owners[p];
943: }
944: PetscCall(PetscSFCreate(PetscObjectComm((PetscObject)A), &sf));
945: PetscCall(PetscSFSetGraph(sf, n, N, NULL, PETSC_OWN_POINTER, rrows, PETSC_OWN_POINTER));
946: /* Collect flags for rows to be zeroed */
947: PetscCall(PetscSFReduceBegin(sf, MPIU_INT, (PetscInt *)rows, lrows, MPI_LOR));
948: PetscCall(PetscSFReduceEnd(sf, MPIU_INT, (PetscInt *)rows, lrows, MPI_LOR));
949: PetscCall(PetscSFDestroy(&sf));
950: /* Compress and put in row numbers */
951: for (r = 0; r < n; ++r)
952: if (lrows[r] >= 0) lrows[len++] = r;
953: /* zero diagonal part of matrix */
954: PetscCall(MatZeroRowsColumns(l->A, len, lrows, diag, x, b));
955: /* handle off-diagonal part of matrix */
956: PetscCall(MatCreateVecs(A, &xmask, NULL));
957: PetscCall(VecDuplicate(l->lvec, &lmask));
958: PetscCall(VecGetArray(xmask, &bb));
959: for (i = 0; i < len; i++) bb[lrows[i]] = 1;
960: PetscCall(VecRestoreArray(xmask, &bb));
961: PetscCall(VecScatterBegin(l->Mvctx, xmask, lmask, ADD_VALUES, SCATTER_FORWARD));
962: PetscCall(VecScatterEnd(l->Mvctx, xmask, lmask, ADD_VALUES, SCATTER_FORWARD));
963: PetscCall(VecDestroy(&xmask));
964: if (x && b) { /* this code is buggy when the row and column layout don't match */
965: PetscBool cong;
967: PetscCall(MatHasCongruentLayouts(A, &cong));
968: PetscCheck(cong, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "Need matching row/col layout");
969: PetscCall(VecScatterBegin(l->Mvctx, x, l->lvec, INSERT_VALUES, SCATTER_FORWARD));
970: PetscCall(VecScatterEnd(l->Mvctx, x, l->lvec, INSERT_VALUES, SCATTER_FORWARD));
971: PetscCall(VecGetArrayRead(l->lvec, &xx));
972: PetscCall(VecGetArray(b, &bb));
973: }
974: PetscCall(VecGetArray(lmask, &mask));
975: /* remove zeroed rows of off-diagonal matrix */
976: PetscCall(MatSeqAIJGetArray(l->B, &aij_a));
977: ii = aij->i;
978: for (i = 0; i < len; i++) PetscCall(PetscArrayzero(PetscSafePointerPlusOffset(aij_a, ii[lrows[i]]), ii[lrows[i] + 1] - ii[lrows[i]]));
979: /* loop over all elements of off process part of matrix zeroing removed columns*/
980: if (aij->compressedrow.use) {
981: m = aij->compressedrow.nrows;
982: ii = aij->compressedrow.i;
983: ridx = aij->compressedrow.rindex;
984: for (i = 0; i < m; i++) {
985: n = ii[i + 1] - ii[i];
986: aj = aij->j + ii[i];
987: aa = aij_a + ii[i];
989: for (j = 0; j < n; j++) {
990: if (PetscAbsScalar(mask[*aj])) {
991: if (b) bb[*ridx] -= *aa * xx[*aj];
992: *aa = 0.0;
993: }
994: aa++;
995: aj++;
996: }
997: ridx++;
998: }
999: } else { /* do not use compressed row format */
1000: m = l->B->rmap->n;
1001: for (i = 0; i < m; i++) {
1002: n = ii[i + 1] - ii[i];
1003: aj = aij->j + ii[i];
1004: aa = aij_a + ii[i];
1005: for (j = 0; j < n; j++) {
1006: if (PetscAbsScalar(mask[*aj])) {
1007: if (b) bb[i] -= *aa * xx[*aj];
1008: *aa = 0.0;
1009: }
1010: aa++;
1011: aj++;
1012: }
1013: }
1014: }
1015: if (x && b) {
1016: PetscCall(VecRestoreArray(b, &bb));
1017: PetscCall(VecRestoreArrayRead(l->lvec, &xx));
1018: }
1019: PetscCall(MatSeqAIJRestoreArray(l->B, &aij_a));
1020: PetscCall(VecRestoreArray(lmask, &mask));
1021: PetscCall(VecDestroy(&lmask));
1022: PetscCall(PetscFree(lrows));
1024: /* only change matrix nonzero state if pattern was allowed to be changed */
1025: if (!((Mat_SeqAIJ *)l->A->data)->nonew) {
1026: A->nonzerostate = l->A->nonzerostate + l->B->nonzerostate;
1027: PetscCallMPI(MPIU_Allreduce(MPI_IN_PLACE, &A->nonzerostate, 1, MPIU_INT64, MPI_SUM, PetscObjectComm((PetscObject)A)));
1028: }
1029: PetscFunctionReturn(PETSC_SUCCESS);
1030: }
1032: static PetscErrorCode MatMult_MPIAIJ(Mat A, Vec xx, Vec yy)
1033: {
1034: Mat_MPIAIJ *a = (Mat_MPIAIJ *)A->data;
1035: PetscInt nt;
1036: VecScatter Mvctx = a->Mvctx;
1038: PetscFunctionBegin;
1039: PetscCall(VecGetLocalSize(xx, &nt));
1040: 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);
1041: PetscCall(VecScatterBegin(Mvctx, xx, a->lvec, INSERT_VALUES, SCATTER_FORWARD));
1042: PetscUseTypeMethod(a->A, mult, xx, yy);
1043: PetscCall(VecScatterEnd(Mvctx, xx, a->lvec, INSERT_VALUES, SCATTER_FORWARD));
1044: PetscUseTypeMethod(a->B, multadd, a->lvec, yy, yy);
1045: PetscFunctionReturn(PETSC_SUCCESS);
1046: }
1048: static PetscErrorCode MatMultDiagonalBlock_MPIAIJ(Mat A, Vec bb, Vec xx)
1049: {
1050: Mat_MPIAIJ *a = (Mat_MPIAIJ *)A->data;
1052: PetscFunctionBegin;
1053: PetscCall(MatMultDiagonalBlock(a->A, bb, xx));
1054: PetscFunctionReturn(PETSC_SUCCESS);
1055: }
1057: static PetscErrorCode MatMultAdd_MPIAIJ(Mat A, Vec xx, Vec yy, Vec zz)
1058: {
1059: Mat_MPIAIJ *a = (Mat_MPIAIJ *)A->data;
1060: VecScatter Mvctx = a->Mvctx;
1062: PetscFunctionBegin;
1063: PetscCall(VecScatterBegin(Mvctx, xx, a->lvec, INSERT_VALUES, SCATTER_FORWARD));
1064: PetscUseTypeMethod(a->A, multadd, xx, yy, zz);
1065: PetscCall(VecScatterEnd(Mvctx, xx, a->lvec, INSERT_VALUES, SCATTER_FORWARD));
1066: PetscUseTypeMethod(a->B, multadd, a->lvec, zz, zz);
1067: PetscFunctionReturn(PETSC_SUCCESS);
1068: }
1070: static PetscErrorCode MatMultTranspose_MPIAIJ(Mat A, Vec xx, Vec yy)
1071: {
1072: Mat_MPIAIJ *a = (Mat_MPIAIJ *)A->data;
1074: PetscFunctionBegin;
1075: /* do nondiagonal part */
1076: PetscUseTypeMethod(a->B, multtranspose, xx, a->lvec);
1077: /* do local part */
1078: PetscUseTypeMethod(a->A, multtranspose, xx, yy);
1079: /* add partial results together */
1080: PetscCall(VecScatterBegin(a->Mvctx, a->lvec, yy, ADD_VALUES, SCATTER_REVERSE));
1081: PetscCall(VecScatterEnd(a->Mvctx, a->lvec, yy, ADD_VALUES, SCATTER_REVERSE));
1082: PetscFunctionReturn(PETSC_SUCCESS);
1083: }
1085: static PetscErrorCode MatIsTranspose_MPIAIJ(Mat Amat, Mat Bmat, PetscReal tol, PetscBool *f)
1086: {
1087: MPI_Comm comm;
1088: Mat_MPIAIJ *Aij = (Mat_MPIAIJ *)Amat->data, *Bij = (Mat_MPIAIJ *)Bmat->data;
1089: Mat Adia = Aij->A, Bdia = Bij->A, Aoff, Boff, *Aoffs, *Boffs;
1090: IS Me, Notme;
1091: PetscInt M, N, first, last, *notme, i;
1092: PetscMPIInt size;
1094: PetscFunctionBegin;
1095: /* Easy test: symmetric diagonal block */
1096: PetscCall(MatIsTranspose(Adia, Bdia, tol, f));
1097: PetscCallMPI(MPIU_Allreduce(MPI_IN_PLACE, f, 1, MPI_C_BOOL, MPI_LAND, PetscObjectComm((PetscObject)Amat)));
1098: if (!*f) PetscFunctionReturn(PETSC_SUCCESS);
1099: PetscCall(PetscObjectGetComm((PetscObject)Amat, &comm));
1100: PetscCallMPI(MPI_Comm_size(comm, &size));
1101: if (size == 1) PetscFunctionReturn(PETSC_SUCCESS);
1103: /* Hard test: off-diagonal block. This takes a MatCreateSubMatrix. */
1104: PetscCall(MatGetSize(Amat, &M, &N));
1105: PetscCall(MatGetOwnershipRange(Amat, &first, &last));
1106: PetscCall(PetscMalloc1(N - last + first, ¬me));
1107: for (i = 0; i < first; i++) notme[i] = i;
1108: for (i = last; i < M; i++) notme[i - last + first] = i;
1109: PetscCall(ISCreateGeneral(MPI_COMM_SELF, N - last + first, notme, PETSC_COPY_VALUES, &Notme));
1110: PetscCall(ISCreateStride(MPI_COMM_SELF, last - first, first, 1, &Me));
1111: PetscCall(MatCreateSubMatrices(Amat, 1, &Me, &Notme, MAT_INITIAL_MATRIX, &Aoffs));
1112: Aoff = Aoffs[0];
1113: PetscCall(MatCreateSubMatrices(Bmat, 1, &Notme, &Me, MAT_INITIAL_MATRIX, &Boffs));
1114: Boff = Boffs[0];
1115: PetscCall(MatIsTranspose(Aoff, Boff, tol, f));
1116: PetscCall(MatDestroyMatrices(1, &Aoffs));
1117: PetscCall(MatDestroyMatrices(1, &Boffs));
1118: PetscCall(ISDestroy(&Me));
1119: PetscCall(ISDestroy(&Notme));
1120: PetscCall(PetscFree(notme));
1121: PetscFunctionReturn(PETSC_SUCCESS);
1122: }
1124: static PetscErrorCode MatMultTransposeAdd_MPIAIJ(Mat A, Vec xx, Vec yy, Vec zz)
1125: {
1126: Mat_MPIAIJ *a = (Mat_MPIAIJ *)A->data;
1128: PetscFunctionBegin;
1129: /* do nondiagonal part */
1130: PetscUseTypeMethod(a->B, multtranspose, xx, a->lvec);
1131: /* do local part */
1132: PetscUseTypeMethod(a->A, multtransposeadd, xx, yy, zz);
1133: /* add partial results together */
1134: PetscCall(VecScatterBegin(a->Mvctx, a->lvec, zz, ADD_VALUES, SCATTER_REVERSE));
1135: PetscCall(VecScatterEnd(a->Mvctx, a->lvec, zz, ADD_VALUES, SCATTER_REVERSE));
1136: PetscFunctionReturn(PETSC_SUCCESS);
1137: }
1139: /*
1140: This only works correctly for square matrices where the subblock A->A is the
1141: diagonal block
1142: */
1143: static PetscErrorCode MatGetDiagonal_MPIAIJ(Mat A, Vec v)
1144: {
1145: Mat_MPIAIJ *a = (Mat_MPIAIJ *)A->data;
1147: PetscFunctionBegin;
1148: PetscCheck(A->rmap->N == A->cmap->N, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "Supports only square matrix where A->A is diag block");
1149: 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");
1150: PetscCall(MatGetDiagonal(a->A, v));
1151: PetscFunctionReturn(PETSC_SUCCESS);
1152: }
1154: static PetscErrorCode MatScale_MPIAIJ(Mat A, PetscScalar aa)
1155: {
1156: Mat_MPIAIJ *a = (Mat_MPIAIJ *)A->data;
1158: PetscFunctionBegin;
1159: PetscCall(MatScale(a->A, aa));
1160: PetscCall(MatScale(a->B, aa));
1161: PetscFunctionReturn(PETSC_SUCCESS);
1162: }
1164: static PetscErrorCode MatView_MPIAIJ_Binary(Mat mat, PetscViewer viewer)
1165: {
1166: Mat_MPIAIJ *aij = (Mat_MPIAIJ *)mat->data;
1167: Mat_SeqAIJ *A = (Mat_SeqAIJ *)aij->A->data;
1168: Mat_SeqAIJ *B = (Mat_SeqAIJ *)aij->B->data;
1169: const PetscInt *garray = aij->garray;
1170: const PetscScalar *aa, *ba;
1171: PetscInt header[4], M, N, m, rs, cs, cnt, i, ja, jb;
1172: PetscInt64 nz, hnz;
1173: PetscInt *rowlens;
1174: PetscInt *colidxs;
1175: PetscScalar *matvals;
1176: PetscMPIInt rank;
1178: PetscFunctionBegin;
1179: PetscCall(PetscViewerSetUp(viewer));
1181: M = mat->rmap->N;
1182: N = mat->cmap->N;
1183: m = mat->rmap->n;
1184: rs = mat->rmap->rstart;
1185: cs = mat->cmap->rstart;
1186: nz = A->nz + B->nz;
1188: /* write matrix header */
1189: header[0] = MAT_FILE_CLASSID;
1190: header[1] = M;
1191: header[2] = N;
1192: PetscCallMPI(MPI_Reduce(&nz, &hnz, 1, MPIU_INT64, MPI_SUM, 0, PetscObjectComm((PetscObject)mat)));
1193: PetscCallMPI(MPI_Comm_rank(PetscObjectComm((PetscObject)mat), &rank));
1194: if (rank == 0) PetscCall(PetscIntCast(hnz, &header[3]));
1195: PetscCall(PetscViewerBinaryWrite(viewer, header, 4, PETSC_INT));
1197: /* fill in and store row lengths */
1198: PetscCall(PetscMalloc1(m, &rowlens));
1199: for (i = 0; i < m; i++) rowlens[i] = A->i[i + 1] - A->i[i] + B->i[i + 1] - B->i[i];
1200: PetscCall(PetscViewerBinaryWriteAll(viewer, rowlens, m, rs, M, PETSC_INT));
1201: PetscCall(PetscFree(rowlens));
1203: /* fill in and store column indices */
1204: PetscCall(PetscMalloc1(nz, &colidxs));
1205: for (cnt = 0, i = 0; i < m; i++) {
1206: for (jb = B->i[i]; jb < B->i[i + 1]; jb++) {
1207: if (garray[B->j[jb]] > cs) break;
1208: colidxs[cnt++] = garray[B->j[jb]];
1209: }
1210: for (ja = A->i[i]; ja < A->i[i + 1]; ja++) colidxs[cnt++] = A->j[ja] + cs;
1211: for (; jb < B->i[i + 1]; jb++) colidxs[cnt++] = garray[B->j[jb]];
1212: }
1213: PetscCheck(cnt == nz, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Internal PETSc error: cnt = %" PetscInt_FMT " nz = %" PetscInt64_FMT, cnt, nz);
1214: PetscCall(PetscViewerBinaryWriteAll(viewer, colidxs, nz, PETSC_DETERMINE, PETSC_DETERMINE, PETSC_INT));
1215: PetscCall(PetscFree(colidxs));
1217: /* fill in and store nonzero values */
1218: PetscCall(MatSeqAIJGetArrayRead(aij->A, &aa));
1219: PetscCall(MatSeqAIJGetArrayRead(aij->B, &ba));
1220: PetscCall(PetscMalloc1(nz, &matvals));
1221: for (cnt = 0, i = 0; i < m; i++) {
1222: for (jb = B->i[i]; jb < B->i[i + 1]; jb++) {
1223: if (garray[B->j[jb]] > cs) break;
1224: matvals[cnt++] = ba[jb];
1225: }
1226: for (ja = A->i[i]; ja < A->i[i + 1]; ja++) matvals[cnt++] = aa[ja];
1227: for (; jb < B->i[i + 1]; jb++) matvals[cnt++] = ba[jb];
1228: }
1229: PetscCall(MatSeqAIJRestoreArrayRead(aij->A, &aa));
1230: PetscCall(MatSeqAIJRestoreArrayRead(aij->B, &ba));
1231: PetscCheck(cnt == nz, PETSC_COMM_SELF, PETSC_ERR_LIB, "Internal PETSc error: cnt = %" PetscInt_FMT " nz = %" PetscInt64_FMT, cnt, nz);
1232: PetscCall(PetscViewerBinaryWriteAll(viewer, matvals, nz, PETSC_DETERMINE, PETSC_DETERMINE, PETSC_SCALAR));
1233: PetscCall(PetscFree(matvals));
1235: /* write block size option to the viewer's .info file */
1236: PetscCall(MatView_Binary_BlockSizes(mat, viewer));
1237: PetscFunctionReturn(PETSC_SUCCESS);
1238: }
1240: #include <petscdraw.h>
1241: static PetscErrorCode MatView_MPIAIJ_ASCIIorDraworSocket(Mat mat, PetscViewer viewer)
1242: {
1243: Mat_MPIAIJ *aij = (Mat_MPIAIJ *)mat->data;
1244: PetscMPIInt rank = aij->rank, size = aij->size;
1245: PetscBool isdraw, isascii, isbinary;
1246: PetscViewer sviewer;
1247: PetscViewerFormat format;
1249: PetscFunctionBegin;
1250: PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERDRAW, &isdraw));
1251: PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERASCII, &isascii));
1252: PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERBINARY, &isbinary));
1253: if (isascii) {
1254: PetscCall(PetscViewerGetFormat(viewer, &format));
1255: if (format == PETSC_VIEWER_LOAD_BALANCE) {
1256: PetscInt i, nmax = 0, nmin = PETSC_INT_MAX, navg = 0, *nz, nzlocal = ((Mat_SeqAIJ *)aij->A->data)->nz + ((Mat_SeqAIJ *)aij->B->data)->nz;
1257: PetscCall(PetscMalloc1(size, &nz));
1258: PetscCallMPI(MPI_Allgather(&nzlocal, 1, MPIU_INT, nz, 1, MPIU_INT, PetscObjectComm((PetscObject)mat)));
1259: for (i = 0; i < size; i++) {
1260: nmax = PetscMax(nmax, nz[i]);
1261: nmin = PetscMin(nmin, nz[i]);
1262: navg += nz[i];
1263: }
1264: PetscCall(PetscFree(nz));
1265: navg = navg / size;
1266: PetscCall(PetscViewerASCIIPrintf(viewer, "Load Balance - Nonzeros: Min %" PetscInt_FMT " avg %" PetscInt_FMT " max %" PetscInt_FMT "\n", nmin, navg, nmax));
1267: PetscFunctionReturn(PETSC_SUCCESS);
1268: }
1269: PetscCall(PetscViewerGetFormat(viewer, &format));
1270: if (format == PETSC_VIEWER_ASCII_INFO_DETAIL) {
1271: MatInfo info;
1272: PetscInt *inodes = NULL;
1274: PetscCallMPI(MPI_Comm_rank(PetscObjectComm((PetscObject)mat), &rank));
1275: PetscCall(MatGetInfo(mat, MAT_LOCAL, &info));
1276: PetscCall(MatInodeGetInodeSizes(aij->A, NULL, &inodes, NULL));
1277: PetscCall(PetscViewerASCIIPushSynchronized(viewer));
1278: if (!inodes) {
1279: 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,
1280: info.memory));
1281: } else {
1282: PetscCall(
1283: 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));
1284: }
1285: PetscCall(MatGetInfo(aij->A, MAT_LOCAL, &info));
1286: PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, "[%d] on-diagonal part: nz %" PetscInt_FMT " \n", rank, (PetscInt)info.nz_used));
1287: PetscCall(MatGetInfo(aij->B, MAT_LOCAL, &info));
1288: PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, "[%d] off-diagonal part: nz %" PetscInt_FMT " \n", rank, (PetscInt)info.nz_used));
1289: PetscCall(PetscViewerFlush(viewer));
1290: PetscCall(PetscViewerASCIIPopSynchronized(viewer));
1291: PetscCall(PetscViewerASCIIPrintf(viewer, "Information on VecScatter used in matrix-vector product: \n"));
1292: PetscCall(VecScatterView(aij->Mvctx, viewer));
1293: PetscFunctionReturn(PETSC_SUCCESS);
1294: } else if (format == PETSC_VIEWER_ASCII_INFO) {
1295: PetscInt inodecount, inodelimit, *inodes;
1296: PetscCall(MatInodeGetInodeSizes(aij->A, &inodecount, &inodes, &inodelimit));
1297: if (inodes) {
1298: PetscCall(PetscViewerASCIIPrintf(viewer, "using I-node (on process 0) routines: found %" PetscInt_FMT " nodes, limit used is %" PetscInt_FMT "\n", inodecount, inodelimit));
1299: } else {
1300: PetscCall(PetscViewerASCIIPrintf(viewer, "not using I-node (on process 0) routines\n"));
1301: }
1302: PetscFunctionReturn(PETSC_SUCCESS);
1303: } else if (format == PETSC_VIEWER_ASCII_FACTOR_INFO) {
1304: PetscFunctionReturn(PETSC_SUCCESS);
1305: }
1306: } else if (isbinary) {
1307: if (size == 1) {
1308: PetscCall(PetscObjectSetName((PetscObject)aij->A, ((PetscObject)mat)->name));
1309: PetscCall(MatView(aij->A, viewer));
1310: } else {
1311: PetscCall(MatView_MPIAIJ_Binary(mat, viewer));
1312: }
1313: PetscFunctionReturn(PETSC_SUCCESS);
1314: } else if (isascii && size == 1) {
1315: PetscCall(PetscObjectSetName((PetscObject)aij->A, ((PetscObject)mat)->name));
1316: PetscCall(MatView(aij->A, viewer));
1317: PetscFunctionReturn(PETSC_SUCCESS);
1318: } else if (isdraw) {
1319: PetscDraw draw;
1320: PetscBool isnull;
1321: PetscCall(PetscViewerDrawGetDraw(viewer, 0, &draw));
1322: PetscCall(PetscDrawIsNull(draw, &isnull));
1323: if (isnull) PetscFunctionReturn(PETSC_SUCCESS);
1324: }
1326: { /* assemble the entire matrix onto first process */
1327: Mat A, Av;
1328: IS isrow, iscol;
1330: PetscCall(ISCreateStride(PetscObjectComm((PetscObject)mat), rank == 0 ? mat->rmap->N : 0, 0, 1, &isrow));
1331: PetscCall(ISCreateStride(PetscObjectComm((PetscObject)mat), rank == 0 ? mat->cmap->N : 0, 0, 1, &iscol));
1332: PetscCall(MatCreateSubMatrix(mat, isrow, iscol, MAT_INITIAL_MATRIX, &A));
1333: PetscCall(MatMPIAIJGetSeqAIJ(A, &Av, NULL, NULL));
1334: PetscCall(ISDestroy(&iscol));
1335: PetscCall(ISDestroy(&isrow));
1336: /*
1337: Everyone has to call to draw the matrix since the graphics waits are
1338: synchronized across all processors that share the PetscDraw object
1339: */
1340: PetscCall(PetscViewerGetSubViewer(viewer, PETSC_COMM_SELF, &sviewer));
1341: if (rank == 0) {
1342: if (((PetscObject)mat)->name) PetscCall(PetscObjectSetName((PetscObject)Av, ((PetscObject)mat)->name));
1343: PetscCall(MatView_SeqAIJ(Av, sviewer));
1344: }
1345: PetscCall(PetscViewerRestoreSubViewer(viewer, PETSC_COMM_SELF, &sviewer));
1346: PetscCall(MatDestroy(&A));
1347: }
1348: PetscFunctionReturn(PETSC_SUCCESS);
1349: }
1351: PetscErrorCode MatView_MPIAIJ(Mat mat, PetscViewer viewer)
1352: {
1353: PetscBool isascii, isdraw, issocket, isbinary;
1355: PetscFunctionBegin;
1356: PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERASCII, &isascii));
1357: PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERDRAW, &isdraw));
1358: PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERBINARY, &isbinary));
1359: PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERSOCKET, &issocket));
1360: if (isascii || isdraw || isbinary || issocket) PetscCall(MatView_MPIAIJ_ASCIIorDraworSocket(mat, viewer));
1361: PetscFunctionReturn(PETSC_SUCCESS);
1362: }
1364: static PetscErrorCode MatSOR_MPIAIJ(Mat matin, Vec bb, PetscReal omega, MatSORType flag, PetscReal fshift, PetscInt its, PetscInt lits, Vec xx)
1365: {
1366: Mat_MPIAIJ *mat = (Mat_MPIAIJ *)matin->data;
1367: Vec bb1 = NULL;
1368: PetscBool hasop;
1370: PetscFunctionBegin;
1371: if (flag == SOR_APPLY_UPPER) {
1372: PetscUseTypeMethod(mat->A, sor, bb, omega, flag, fshift, lits, 1, xx);
1373: PetscFunctionReturn(PETSC_SUCCESS);
1374: }
1376: if (its > 1 || ~flag & SOR_ZERO_INITIAL_GUESS || flag & SOR_EISENSTAT) PetscCall(VecDuplicate(bb, &bb1));
1378: if ((flag & SOR_LOCAL_SYMMETRIC_SWEEP) == SOR_LOCAL_SYMMETRIC_SWEEP) {
1379: if (flag & SOR_ZERO_INITIAL_GUESS) {
1380: PetscUseTypeMethod(mat->A, sor, bb, omega, flag, fshift, lits, 1, xx);
1381: its--;
1382: }
1384: while (its--) {
1385: PetscCall(VecScatterBegin(mat->Mvctx, xx, mat->lvec, INSERT_VALUES, SCATTER_FORWARD));
1386: PetscCall(VecScatterEnd(mat->Mvctx, xx, mat->lvec, INSERT_VALUES, SCATTER_FORWARD));
1388: /* update rhs: bb1 = bb - B*x */
1389: PetscCall(VecScale(mat->lvec, -1.0));
1390: PetscUseTypeMethod(mat->B, multadd, mat->lvec, bb, bb1);
1392: /* local sweep */
1393: PetscUseTypeMethod(mat->A, sor, bb1, omega, SOR_SYMMETRIC_SWEEP, fshift, lits, 1, xx);
1394: }
1395: } else if (flag & SOR_LOCAL_FORWARD_SWEEP) {
1396: if (flag & SOR_ZERO_INITIAL_GUESS) {
1397: PetscUseTypeMethod(mat->A, sor, bb, omega, flag, fshift, lits, 1, xx);
1398: its--;
1399: }
1400: while (its--) {
1401: PetscCall(VecScatterBegin(mat->Mvctx, xx, mat->lvec, INSERT_VALUES, SCATTER_FORWARD));
1402: PetscCall(VecScatterEnd(mat->Mvctx, xx, mat->lvec, INSERT_VALUES, SCATTER_FORWARD));
1404: /* update rhs: bb1 = bb - B*x */
1405: PetscCall(VecScale(mat->lvec, -1.0));
1406: PetscUseTypeMethod(mat->B, multadd, mat->lvec, bb, bb1);
1408: /* local sweep */
1409: PetscUseTypeMethod(mat->A, sor, bb1, omega, SOR_FORWARD_SWEEP, fshift, lits, 1, xx);
1410: }
1411: } else if (flag & SOR_LOCAL_BACKWARD_SWEEP) {
1412: if (flag & SOR_ZERO_INITIAL_GUESS) {
1413: PetscUseTypeMethod(mat->A, sor, bb, omega, flag, fshift, lits, 1, xx);
1414: its--;
1415: }
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_BACKWARD_SWEEP, fshift, lits, 1, xx);
1426: }
1427: } else if (flag & SOR_EISENSTAT) {
1428: Vec xx1;
1430: PetscCall(VecDuplicate(bb, &xx1));
1431: PetscUseTypeMethod(mat->A, sor, bb, omega, (MatSORType)(SOR_ZERO_INITIAL_GUESS | SOR_LOCAL_BACKWARD_SWEEP), fshift, lits, 1, xx);
1433: PetscCall(VecScatterBegin(mat->Mvctx, xx, mat->lvec, INSERT_VALUES, SCATTER_FORWARD));
1434: PetscCall(VecScatterEnd(mat->Mvctx, xx, mat->lvec, INSERT_VALUES, SCATTER_FORWARD));
1435: if (!mat->diag) {
1436: PetscCall(MatCreateVecs(matin, &mat->diag, NULL));
1437: PetscCall(MatGetDiagonal(matin, mat->diag));
1438: }
1439: PetscCall(MatHasOperation(matin, MATOP_MULT_DIAGONAL_BLOCK, &hasop));
1440: if (hasop) PetscCall(MatMultDiagonalBlock(matin, xx, bb1));
1441: else PetscCall(VecPointwiseMult(bb1, mat->diag, xx));
1442: PetscCall(VecAYPX(bb1, (omega - 2.0) / omega, bb));
1444: PetscCall(MatMultAdd(mat->B, mat->lvec, bb1, bb1));
1446: /* local sweep */
1447: PetscUseTypeMethod(mat->A, sor, bb1, omega, (MatSORType)(SOR_ZERO_INITIAL_GUESS | SOR_LOCAL_FORWARD_SWEEP), fshift, lits, 1, xx1);
1448: PetscCall(VecAXPY(xx, 1.0, xx1));
1449: PetscCall(VecDestroy(&xx1));
1450: } else SETERRQ(PetscObjectComm((PetscObject)matin), PETSC_ERR_SUP, "Parallel SOR not supported");
1452: PetscCall(VecDestroy(&bb1));
1454: matin->factorerrortype = mat->A->factorerrortype;
1455: PetscFunctionReturn(PETSC_SUCCESS);
1456: }
1458: static PetscErrorCode MatPermute_MPIAIJ(Mat A, IS rowp, IS colp, Mat *B)
1459: {
1460: Mat aA, aB, Aperm;
1461: const PetscInt *rwant, *cwant, *gcols, *ai, *bi, *aj, *bj;
1462: PetscScalar *aa, *ba;
1463: PetscInt i, j, m, n, ng, anz, bnz, rmin, rmax, cmin, cmax;
1464: PetscInt *dnnz, *onnz, *tdnnz, *tonnz, *rdest, *cdest, *work, *gcdest;
1465: PetscSF rowsf = NULL, sf;
1466: IS parcolp = NULL;
1467: PetscBool done, local;
1469: PetscFunctionBegin;
1470: PetscCall(MatGetLocalSize(A, &m, &n));
1471: PetscCall(ISGetIndices(rowp, &rwant));
1472: PetscCall(ISGetIndices(colp, &cwant));
1473: PetscCall(PetscMalloc3(PetscMax(m, n), &work, m, &rdest, n, &cdest));
1475: PetscCall(ISGetMinMax(rowp, &rmin, &rmax));
1476: PetscCall(ISGetMinMax(colp, &cmin, &cmax));
1477: local = (PetscBool)(rmin >= A->rmap->rstart && rmax < A->rmap->rend && cmin >= A->cmap->rstart && cmax < A->cmap->rend);
1478: PetscCallMPI(MPIU_Allreduce(MPI_IN_PLACE, &local, 1, MPI_C_BOOL, MPI_LAND, PetscObjectComm((PetscObject)A)));
1479: if (local == PETSC_TRUE) {
1480: for (i = 0; i < m; i++) rdest[rwant[i] - A->rmap->rstart] = A->rmap->rstart + i;
1481: for (i = 0; i < n; i++) cdest[cwant[i] - A->cmap->rstart] = A->cmap->rstart + i;
1482: } else {
1483: /* Invert row permutation to find out where my rows should go */
1484: PetscCall(PetscSFCreate(PetscObjectComm((PetscObject)A), &rowsf));
1485: PetscCall(PetscSFSetGraphLayout(rowsf, A->rmap, A->rmap->n, NULL, PETSC_OWN_POINTER, rwant));
1486: PetscCall(PetscSFSetFromOptions(rowsf));
1487: for (i = 0; i < m; i++) work[i] = A->rmap->rstart + i;
1488: PetscCall(PetscSFReduceBegin(rowsf, MPIU_INT, work, rdest, MPI_REPLACE));
1489: PetscCall(PetscSFReduceEnd(rowsf, MPIU_INT, work, rdest, MPI_REPLACE));
1491: /* Invert column permutation to find out where my columns should go */
1492: PetscCall(PetscSFCreate(PetscObjectComm((PetscObject)A), &sf));
1493: PetscCall(PetscSFSetGraphLayout(sf, A->cmap, A->cmap->n, NULL, PETSC_OWN_POINTER, cwant));
1494: PetscCall(PetscSFSetFromOptions(sf));
1495: for (i = 0; i < n; i++) work[i] = A->cmap->rstart + i;
1496: PetscCall(PetscSFReduceBegin(sf, MPIU_INT, work, cdest, MPI_REPLACE));
1497: PetscCall(PetscSFReduceEnd(sf, MPIU_INT, work, cdest, MPI_REPLACE));
1498: PetscCall(PetscSFDestroy(&sf));
1499: }
1501: PetscCall(ISRestoreIndices(rowp, &rwant));
1502: PetscCall(ISRestoreIndices(colp, &cwant));
1503: PetscCall(MatMPIAIJGetSeqAIJ(A, &aA, &aB, &gcols));
1505: /* Find out where my gcols should go */
1506: PetscCall(MatGetSize(aB, NULL, &ng));
1507: PetscCall(PetscMalloc1(ng, &gcdest));
1508: PetscCall(PetscSFCreate(PetscObjectComm((PetscObject)A), &sf));
1509: PetscCall(PetscSFSetGraphLayout(sf, A->cmap, ng, NULL, PETSC_OWN_POINTER, gcols));
1510: PetscCall(PetscSFSetFromOptions(sf));
1511: PetscCall(PetscSFBcastBegin(sf, MPIU_INT, cdest, gcdest, MPI_REPLACE));
1512: PetscCall(PetscSFBcastEnd(sf, MPIU_INT, cdest, gcdest, MPI_REPLACE));
1513: PetscCall(PetscSFDestroy(&sf));
1515: PetscCall(PetscCalloc4(m, &dnnz, m, &onnz, m, &tdnnz, m, &tonnz));
1516: PetscCall(MatGetRowIJ(aA, 0, PETSC_FALSE, PETSC_FALSE, &anz, &ai, &aj, &done));
1517: PetscCall(MatGetRowIJ(aB, 0, PETSC_FALSE, PETSC_FALSE, &bnz, &bi, &bj, &done));
1518: for (i = 0; i < m; i++) {
1519: PetscInt row = rdest[i];
1520: PetscMPIInt rowner;
1522: if (local == PETSC_TRUE) {
1523: tdnnz[row - A->rmap->rstart] = ai[i + 1] - ai[i];
1524: tonnz[row - A->rmap->rstart] = bi[i + 1] - bi[i];
1525: continue;
1526: }
1527: PetscCall(PetscLayoutFindOwner(A->rmap, row, &rowner));
1528: for (j = ai[i]; j < ai[i + 1]; j++) {
1529: PetscInt col = cdest[aj[j]];
1530: PetscMPIInt cowner;
1531: PetscCall(PetscLayoutFindOwner(A->cmap, col, &cowner)); /* Could build an index for the columns to eliminate this search */
1532: if (rowner == cowner) dnnz[i]++;
1533: else onnz[i]++;
1534: }
1535: for (j = bi[i]; j < bi[i + 1]; j++) {
1536: PetscInt col = gcdest[bj[j]];
1537: PetscMPIInt cowner;
1538: PetscCall(PetscLayoutFindOwner(A->cmap, col, &cowner));
1539: if (rowner == cowner) dnnz[i]++;
1540: else onnz[i]++;
1541: }
1542: }
1543: if (local == PETSC_FALSE) {
1544: PetscCall(PetscSFBcastBegin(rowsf, MPIU_INT, dnnz, tdnnz, MPI_REPLACE));
1545: PetscCall(PetscSFBcastEnd(rowsf, MPIU_INT, dnnz, tdnnz, MPI_REPLACE));
1546: PetscCall(PetscSFBcastBegin(rowsf, MPIU_INT, onnz, tonnz, MPI_REPLACE));
1547: PetscCall(PetscSFBcastEnd(rowsf, MPIU_INT, onnz, tonnz, MPI_REPLACE));
1548: PetscCall(PetscSFDestroy(&rowsf));
1549: }
1551: PetscCall(MatCreateAIJ(PetscObjectComm((PetscObject)A), A->rmap->n, A->cmap->n, A->rmap->N, A->cmap->N, 0, tdnnz, 0, tonnz, &Aperm));
1552: PetscCall(MatSetBlockSizesFromMats(Aperm, A, A));
1553: PetscCall(MatSeqAIJGetArray(aA, &aa));
1554: PetscCall(MatSeqAIJGetArray(aB, &ba));
1555: for (i = 0; i < m; i++) {
1556: PetscInt *acols = dnnz, *bcols = onnz; /* Repurpose now-unneeded arrays */
1557: PetscInt rowlen;
1558: rowlen = ai[i + 1] - ai[i];
1559: for (PetscInt j0 = j = 0; j < rowlen; j0 = j) { /* rowlen could be larger than number of rows m, so sum in batches */
1560: for (; j < PetscMin(rowlen, j0 + m); j++) acols[j - j0] = cdest[aj[ai[i] + j]];
1561: PetscCall(MatSetValues(Aperm, 1, &rdest[i], j - j0, acols, aa + ai[i] + j0, INSERT_VALUES));
1562: }
1563: rowlen = bi[i + 1] - bi[i];
1564: for (PetscInt j0 = j = 0; j < rowlen; j0 = j) {
1565: for (; j < PetscMin(rowlen, j0 + m); j++) bcols[j - j0] = gcdest[bj[bi[i] + j]];
1566: PetscCall(MatSetValues(Aperm, 1, &rdest[i], j - j0, bcols, ba + bi[i] + j0, INSERT_VALUES));
1567: }
1568: }
1569: Aperm->nooffprocentries = local;
1570: PetscCall(MatAssemblyBegin(Aperm, MAT_FINAL_ASSEMBLY));
1571: PetscCall(MatAssemblyEnd(Aperm, MAT_FINAL_ASSEMBLY));
1572: Aperm->nooffprocentries = PETSC_FALSE;
1573: PetscCall(MatRestoreRowIJ(aA, 0, PETSC_FALSE, PETSC_FALSE, &anz, &ai, &aj, &done));
1574: PetscCall(MatRestoreRowIJ(aB, 0, PETSC_FALSE, PETSC_FALSE, &bnz, &bi, &bj, &done));
1575: PetscCall(MatSeqAIJRestoreArray(aA, &aa));
1576: PetscCall(MatSeqAIJRestoreArray(aB, &ba));
1577: PetscCall(PetscFree4(dnnz, onnz, tdnnz, tonnz));
1578: PetscCall(PetscFree3(work, rdest, cdest));
1579: PetscCall(PetscFree(gcdest));
1580: if (parcolp) PetscCall(ISDestroy(&colp));
1581: *B = Aperm;
1582: PetscFunctionReturn(PETSC_SUCCESS);
1583: }
1585: static PetscErrorCode MatGetGhosts_MPIAIJ(Mat mat, PetscInt *nghosts, const PetscInt *ghosts[])
1586: {
1587: Mat_MPIAIJ *aij = (Mat_MPIAIJ *)mat->data;
1589: PetscFunctionBegin;
1590: PetscCall(MatGetSize(aij->B, NULL, nghosts));
1591: if (ghosts) *ghosts = aij->garray;
1592: PetscFunctionReturn(PETSC_SUCCESS);
1593: }
1595: static PetscErrorCode MatGetInfo_MPIAIJ(Mat matin, MatInfoType flag, MatInfo *info)
1596: {
1597: Mat_MPIAIJ *mat = (Mat_MPIAIJ *)matin->data;
1598: Mat A = mat->A, B = mat->B;
1599: PetscLogDouble irecv[5];
1601: PetscFunctionBegin;
1602: info->block_size = 1.0;
1603: PetscCall(MatGetInfo(A, MAT_LOCAL, info));
1605: irecv[0] = info->nz_used;
1606: irecv[1] = info->nz_allocated;
1607: irecv[2] = info->nz_unneeded;
1608: irecv[3] = info->memory;
1609: irecv[4] = info->mallocs;
1611: PetscCall(MatGetInfo(B, MAT_LOCAL, info));
1613: irecv[0] += info->nz_used;
1614: irecv[1] += info->nz_allocated;
1615: irecv[2] += info->nz_unneeded;
1616: irecv[3] += info->memory;
1617: irecv[4] += info->mallocs;
1618: if (flag == MAT_LOCAL) {
1619: info->nz_used = irecv[0];
1620: info->nz_allocated = irecv[1];
1621: info->nz_unneeded = irecv[2];
1622: info->memory = irecv[3];
1623: info->mallocs = irecv[4];
1624: } else if (flag == MAT_GLOBAL_MAX) {
1625: PetscCallMPI(MPIU_Allreduce(MPI_IN_PLACE, irecv, 5, MPIU_PETSCLOGDOUBLE, MPI_MAX, PetscObjectComm((PetscObject)matin)));
1627: info->nz_used = irecv[0];
1628: info->nz_allocated = irecv[1];
1629: info->nz_unneeded = irecv[2];
1630: info->memory = irecv[3];
1631: info->mallocs = irecv[4];
1632: } else if (flag == MAT_GLOBAL_SUM) {
1633: PetscCallMPI(MPIU_Allreduce(MPI_IN_PLACE, irecv, 5, MPIU_PETSCLOGDOUBLE, MPI_SUM, PetscObjectComm((PetscObject)matin)));
1635: info->nz_used = irecv[0];
1636: info->nz_allocated = irecv[1];
1637: info->nz_unneeded = irecv[2];
1638: info->memory = irecv[3];
1639: info->mallocs = irecv[4];
1640: }
1641: info->fill_ratio_given = 0; /* no parallel LU/ILU/Cholesky */
1642: info->fill_ratio_needed = 0;
1643: info->factor_mallocs = 0;
1644: PetscFunctionReturn(PETSC_SUCCESS);
1645: }
1647: PetscErrorCode MatSetOption_MPIAIJ(Mat A, MatOption op, PetscBool flg)
1648: {
1649: Mat_MPIAIJ *a = (Mat_MPIAIJ *)A->data;
1651: PetscFunctionBegin;
1652: switch (op) {
1653: case MAT_NEW_NONZERO_LOCATIONS:
1654: case MAT_NEW_NONZERO_ALLOCATION_ERR:
1655: case MAT_UNUSED_NONZERO_LOCATION_ERR:
1656: case MAT_KEEP_NONZERO_PATTERN:
1657: case MAT_NEW_NONZERO_LOCATION_ERR:
1658: case MAT_USE_INODES:
1659: case MAT_IGNORE_ZERO_ENTRIES:
1660: case MAT_FORM_EXPLICIT_TRANSPOSE:
1661: case MAT_ROW_ORIENTED:
1662: MatCheckPreallocated(A, 1);
1663: if (op == MAT_ROW_ORIENTED) a->roworiented = flg;
1664: PetscCall(MatSetOption(a->A, op, flg));
1665: PetscCall(MatSetOption(a->B, op, flg));
1666: break;
1667: case MAT_STRUCTURE_ONLY:
1668: if (a->A) PetscCall(MatSetOption(a->A, op, flg));
1669: if (a->B) PetscCall(MatSetOption(a->B, op, flg));
1670: break;
1671: case MAT_IGNORE_OFF_PROC_ENTRIES:
1672: a->donotstash = flg;
1673: break;
1674: /* Symmetry flags are handled directly by MatSetOption() and they don't affect preallocation */
1675: case MAT_SPD:
1676: case MAT_SYMMETRIC:
1677: case MAT_STRUCTURALLY_SYMMETRIC:
1678: case MAT_HERMITIAN:
1679: case MAT_SYMMETRY_ETERNAL:
1680: case MAT_STRUCTURAL_SYMMETRY_ETERNAL:
1681: case MAT_SPD_ETERNAL:
1682: /* if the diagonal matrix is square it inherits some of the properties above */
1683: if (a->A && A->rmap->n == A->cmap->n) PetscCall(MatSetOption(a->A, op, flg));
1684: break;
1685: case MAT_SUBMAT_SINGLEIS:
1686: A->submat_singleis = flg;
1687: break;
1688: default:
1689: break;
1690: }
1691: PetscFunctionReturn(PETSC_SUCCESS);
1692: }
1694: PetscErrorCode MatGetRow_MPIAIJ(Mat matin, PetscInt row, PetscInt *nz, PetscInt **idx, PetscScalar **v)
1695: {
1696: Mat_MPIAIJ *mat = (Mat_MPIAIJ *)matin->data;
1697: PetscScalar *vworkA, *vworkB, **pvA, **pvB, *v_p;
1698: PetscInt i, *cworkA, *cworkB, **pcA, **pcB, cstart = matin->cmap->rstart;
1699: PetscInt nztot, nzA, nzB, lrow, rstart = matin->rmap->rstart, rend = matin->rmap->rend;
1700: PetscInt *cmap, *idx_p;
1702: PetscFunctionBegin;
1703: PetscCheck(!mat->getrowactive, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Already active");
1704: mat->getrowactive = PETSC_TRUE;
1706: if ((!mat->rowindices && (idx || v)) || (!mat->rowvalues && v)) {
1707: /*
1708: allocate enough space to hold information from the longest row.
1709: */
1710: Mat_SeqAIJ *Aa = (Mat_SeqAIJ *)mat->A->data, *Ba = (Mat_SeqAIJ *)mat->B->data;
1711: PetscInt max = 1, tmp;
1712: for (i = 0; i < matin->rmap->n; i++) {
1713: tmp = Aa->i[i + 1] - Aa->i[i] + Ba->i[i + 1] - Ba->i[i];
1714: if (max < tmp) max = tmp;
1715: }
1716: PetscCall(PetscFree2(mat->rowvalues, mat->rowindices));
1717: PetscCall(PetscMalloc2(v ? max : 0, &mat->rowvalues, max, &mat->rowindices));
1718: }
1720: PetscCheck(row >= rstart && row < rend, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Only local rows");
1721: lrow = row - rstart;
1723: pvA = &vworkA;
1724: pcA = &cworkA;
1725: pvB = &vworkB;
1726: pcB = &cworkB;
1727: if (!v) {
1728: pvA = NULL;
1729: pvB = NULL;
1730: }
1731: if (!idx) {
1732: pcA = NULL;
1733: if (!v) pcB = NULL;
1734: }
1735: PetscUseTypeMethod(mat->A, getrow, lrow, &nzA, pcA, pvA);
1736: PetscUseTypeMethod(mat->B, getrow, lrow, &nzB, pcB, pvB);
1737: nztot = nzA + nzB;
1739: cmap = mat->garray;
1740: if (v || idx) {
1741: if (nztot) {
1742: /* Sort by increasing column numbers, assuming A and B already sorted */
1743: PetscInt imark = -1;
1744: if (v) {
1745: *v = v_p = mat->rowvalues;
1746: for (i = 0; i < nzB; i++) {
1747: if (cmap[cworkB[i]] < cstart) v_p[i] = vworkB[i];
1748: else break;
1749: }
1750: imark = i;
1751: for (i = 0; i < nzA; i++) v_p[imark + i] = vworkA[i];
1752: for (i = imark; i < nzB; i++) v_p[nzA + i] = vworkB[i];
1753: }
1754: if (idx) {
1755: *idx = idx_p = mat->rowindices;
1756: if (imark > -1) {
1757: for (i = 0; i < imark; i++) idx_p[i] = cmap[cworkB[i]];
1758: } else {
1759: for (i = 0; i < nzB; i++) {
1760: if (cmap[cworkB[i]] < cstart) idx_p[i] = cmap[cworkB[i]];
1761: else break;
1762: }
1763: imark = i;
1764: }
1765: for (i = 0; i < nzA; i++) idx_p[imark + i] = cstart + cworkA[i];
1766: for (i = imark; i < nzB; i++) idx_p[nzA + i] = cmap[cworkB[i]];
1767: }
1768: } else {
1769: if (idx) *idx = NULL;
1770: if (v) *v = NULL;
1771: }
1772: }
1773: *nz = nztot;
1774: PetscUseTypeMethod(mat->A, restorerow, lrow, &nzA, pcA, pvA);
1775: PetscUseTypeMethod(mat->B, restorerow, lrow, &nzB, pcB, pvB);
1776: PetscFunctionReturn(PETSC_SUCCESS);
1777: }
1779: PetscErrorCode MatRestoreRow_MPIAIJ(Mat mat, PetscInt row, PetscInt *nz, PetscInt **idx, PetscScalar **v)
1780: {
1781: Mat_MPIAIJ *aij = (Mat_MPIAIJ *)mat->data;
1783: PetscFunctionBegin;
1784: PetscCheck(aij->getrowactive, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "MatGetRow() must be called first");
1785: aij->getrowactive = PETSC_FALSE;
1786: PetscFunctionReturn(PETSC_SUCCESS);
1787: }
1789: static PetscErrorCode MatNorm_MPIAIJ(Mat mat, NormType type, PetscReal *norm)
1790: {
1791: Mat_MPIAIJ *aij = (Mat_MPIAIJ *)mat->data;
1792: Mat_SeqAIJ *amat = (Mat_SeqAIJ *)aij->A->data, *bmat = (Mat_SeqAIJ *)aij->B->data;
1793: PetscInt i, j;
1794: PetscReal sum = 0.0;
1795: const MatScalar *v, *amata, *bmata;
1797: PetscFunctionBegin;
1798: if (aij->size == 1) {
1799: PetscCall(MatNorm(aij->A, type, norm));
1800: } else {
1801: PetscCall(MatSeqAIJGetArrayRead(aij->A, &amata));
1802: PetscCall(MatSeqAIJGetArrayRead(aij->B, &bmata));
1803: if (type == NORM_FROBENIUS) {
1804: v = amata;
1805: for (i = 0; i < amat->nz; i++) {
1806: sum += PetscRealPart(PetscConj(*v) * (*v));
1807: v++;
1808: }
1809: v = bmata;
1810: for (i = 0; i < bmat->nz; i++) {
1811: sum += PetscRealPart(PetscConj(*v) * (*v));
1812: v++;
1813: }
1814: PetscCallMPI(MPIU_Allreduce(&sum, norm, 1, MPIU_REAL, MPIU_SUM, PetscObjectComm((PetscObject)mat)));
1815: *norm = PetscSqrtReal(*norm);
1816: PetscCall(PetscLogFlops(2.0 * amat->nz + 2.0 * bmat->nz));
1817: } else if (type == NORM_1) { /* max column norm */
1818: Vec col, bcol;
1819: PetscScalar *array;
1820: PetscInt *jj, *garray = aij->garray;
1822: PetscCall(MatCreateVecs(mat, &col, NULL));
1823: PetscCall(VecGetArrayWrite(col, &array));
1824: v = amata;
1825: jj = amat->j;
1826: for (j = 0; j < amat->nz; j++) array[*jj++] += PetscAbsScalar(*v++);
1827: PetscCall(VecRestoreArrayWrite(col, &array));
1828: PetscCall(MatCreateVecs(aij->B, &bcol, NULL));
1829: PetscCall(VecGetArrayWrite(bcol, &array));
1830: v = bmata;
1831: jj = bmat->j;
1832: for (j = 0; j < bmat->nz; j++) array[*jj++] += PetscAbsScalar(*v++);
1833: PetscCall(VecSetValues(col, aij->B->cmap->n, garray, array, ADD_VALUES));
1834: PetscCall(VecRestoreArrayWrite(bcol, &array));
1835: PetscCall(VecDestroy(&bcol));
1836: PetscCall(VecAssemblyBegin(col));
1837: PetscCall(VecAssemblyEnd(col));
1838: PetscCall(VecNorm(col, NORM_INFINITY, norm));
1839: PetscCall(VecDestroy(&col));
1840: } else if (type == NORM_INFINITY) { /* max row norm */
1841: *norm = 0.0;
1842: for (j = 0; j < aij->A->rmap->n; j++) {
1843: v = PetscSafePointerPlusOffset(amata, amat->i[j]);
1844: sum = 0.0;
1845: for (i = 0; i < amat->i[j + 1] - amat->i[j]; i++) {
1846: sum += PetscAbsScalar(*v);
1847: v++;
1848: }
1849: v = PetscSafePointerPlusOffset(bmata, bmat->i[j]);
1850: for (i = 0; i < bmat->i[j + 1] - bmat->i[j]; i++) {
1851: sum += PetscAbsScalar(*v);
1852: v++;
1853: }
1854: if (sum > *norm) *norm = sum;
1855: }
1856: PetscCallMPI(MPIU_Allreduce(MPI_IN_PLACE, norm, 1, MPIU_REAL, MPIU_MAX, PetscObjectComm((PetscObject)mat)));
1857: PetscCall(PetscLogFlops(PetscMax(amat->nz + bmat->nz - 1, 0)));
1858: } else SETERRQ(PetscObjectComm((PetscObject)mat), PETSC_ERR_SUP, "No support for two norm");
1859: PetscCall(MatSeqAIJRestoreArrayRead(aij->A, &amata));
1860: PetscCall(MatSeqAIJRestoreArrayRead(aij->B, &bmata));
1861: }
1862: PetscFunctionReturn(PETSC_SUCCESS);
1863: }
1865: static PetscErrorCode MatTranspose_MPIAIJ(Mat A, MatReuse reuse, Mat *matout)
1866: {
1867: Mat_MPIAIJ *a = (Mat_MPIAIJ *)A->data, *b;
1868: Mat_SeqAIJ *Aloc = (Mat_SeqAIJ *)a->A->data, *Bloc = (Mat_SeqAIJ *)a->B->data, *sub_B_diag;
1869: 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;
1870: const PetscInt *ai, *aj, *bi, *bj, *B_diag_i;
1871: Mat B, A_diag, *B_diag;
1872: const MatScalar *pbv, *bv;
1874: PetscFunctionBegin;
1875: if (reuse == MAT_REUSE_MATRIX) PetscCall(MatTransposeCheckNonzeroState_Private(A, *matout));
1876: ma = A->rmap->n;
1877: na = A->cmap->n;
1878: mb = a->B->rmap->n;
1879: nb = a->B->cmap->n;
1880: ai = Aloc->i;
1881: aj = Aloc->j;
1882: bi = Bloc->i;
1883: bj = Bloc->j;
1884: if (reuse == MAT_INITIAL_MATRIX || *matout == A) {
1885: PetscInt *d_nnz, *g_nnz, *o_nnz;
1886: PetscSFNode *oloc;
1887: PETSC_UNUSED PetscSF sf;
1889: PetscCall(PetscMalloc4(na, &d_nnz, na, &o_nnz, nb, &g_nnz, nb, &oloc));
1890: /* compute d_nnz for preallocation */
1891: PetscCall(PetscArrayzero(d_nnz, na));
1892: for (i = 0; i < ai[ma]; i++) d_nnz[aj[i]]++;
1893: /* compute local off-diagonal contributions */
1894: PetscCall(PetscArrayzero(g_nnz, nb));
1895: for (i = 0; i < bi[ma]; i++) g_nnz[bj[i]]++;
1896: /* map those to global */
1897: PetscCall(PetscSFCreate(PetscObjectComm((PetscObject)A), &sf));
1898: PetscCall(PetscSFSetGraphLayout(sf, A->cmap, nb, NULL, PETSC_USE_POINTER, a->garray));
1899: PetscCall(PetscSFSetFromOptions(sf));
1900: PetscCall(PetscArrayzero(o_nnz, na));
1901: PetscCall(PetscSFReduceBegin(sf, MPIU_INT, g_nnz, o_nnz, MPI_SUM));
1902: PetscCall(PetscSFReduceEnd(sf, MPIU_INT, g_nnz, o_nnz, MPI_SUM));
1903: PetscCall(PetscSFDestroy(&sf));
1905: PetscCall(MatCreate(PetscObjectComm((PetscObject)A), &B));
1906: PetscCall(MatSetSizes(B, A->cmap->n, A->rmap->n, N, M));
1907: PetscCall(MatSetBlockSizes(B, A->cmap->bs, A->rmap->bs));
1908: PetscCall(MatSetType(B, ((PetscObject)A)->type_name));
1909: PetscCall(MatMPIAIJSetPreallocation(B, 0, d_nnz, 0, o_nnz));
1910: PetscCall(PetscFree4(d_nnz, o_nnz, g_nnz, oloc));
1911: } else {
1912: B = *matout;
1913: PetscCall(MatSetOption(B, MAT_NEW_NONZERO_ALLOCATION_ERR, PETSC_TRUE));
1914: }
1916: b = (Mat_MPIAIJ *)B->data;
1917: A_diag = a->A;
1918: B_diag = &b->A;
1919: sub_B_diag = (Mat_SeqAIJ *)(*B_diag)->data;
1920: A_diag_ncol = A_diag->cmap->N;
1921: B_diag_ilen = sub_B_diag->ilen;
1922: B_diag_i = sub_B_diag->i;
1924: /* Set ilen for diagonal of B */
1925: for (i = 0; i < A_diag_ncol; i++) B_diag_ilen[i] = B_diag_i[i + 1] - B_diag_i[i];
1927: /* Transpose the diagonal part of the matrix. In contrast to the off-diagonal part, this can be done
1928: very quickly (=without using MatSetValues), because all writes are local. */
1929: PetscCall(MatTransposeSetPrecursor(A_diag, *B_diag));
1930: PetscCall(MatTranspose(A_diag, MAT_REUSE_MATRIX, B_diag));
1932: /* copy over the B part */
1933: PetscCall(PetscMalloc1(bi[mb], &cols));
1934: PetscCall(MatSeqAIJGetArrayRead(a->B, &bv));
1935: pbv = bv;
1936: row = A->rmap->rstart;
1937: for (i = 0; i < bi[mb]; i++) cols[i] = a->garray[bj[i]];
1938: cols_tmp = cols;
1939: for (i = 0; i < mb; i++) {
1940: ncol = bi[i + 1] - bi[i];
1941: PetscCall(MatSetValues(B, ncol, cols_tmp, 1, &row, pbv, INSERT_VALUES));
1942: row++;
1943: if (pbv) pbv += ncol;
1944: if (cols_tmp) cols_tmp += ncol;
1945: }
1946: PetscCall(PetscFree(cols));
1947: PetscCall(MatSeqAIJRestoreArrayRead(a->B, &bv));
1949: PetscCall(MatAssemblyBegin(B, MAT_FINAL_ASSEMBLY));
1950: PetscCall(MatAssemblyEnd(B, MAT_FINAL_ASSEMBLY));
1951: if (reuse == MAT_INITIAL_MATRIX || reuse == MAT_REUSE_MATRIX) {
1952: *matout = B;
1953: } else {
1954: PetscCall(MatHeaderMerge(A, &B));
1955: }
1956: PetscFunctionReturn(PETSC_SUCCESS);
1957: }
1959: static PetscErrorCode MatDiagonalScale_MPIAIJ(Mat mat, Vec ll, Vec rr)
1960: {
1961: Mat_MPIAIJ *aij = (Mat_MPIAIJ *)mat->data;
1962: Mat a = aij->A, b = aij->B;
1963: PetscInt s1, s2, s3;
1965: PetscFunctionBegin;
1966: PetscCall(MatGetLocalSize(mat, &s2, &s3));
1967: if (rr) {
1968: PetscCall(VecGetLocalSize(rr, &s1));
1969: PetscCheck(s1 == s3, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "right vector non-conforming local size");
1970: /* Overlap communication with computation. */
1971: PetscCall(VecScatterBegin(aij->Mvctx, rr, aij->lvec, INSERT_VALUES, SCATTER_FORWARD));
1972: }
1973: if (ll) {
1974: PetscCall(VecGetLocalSize(ll, &s1));
1975: PetscCheck(s1 == s2, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "left vector non-conforming local size");
1976: PetscUseTypeMethod(b, diagonalscale, ll, NULL);
1977: }
1978: /* scale the diagonal block */
1979: PetscUseTypeMethod(a, diagonalscale, ll, rr);
1981: if (rr) {
1982: /* Do a scatter end and then right scale the off-diagonal block */
1983: PetscCall(VecScatterEnd(aij->Mvctx, rr, aij->lvec, INSERT_VALUES, SCATTER_FORWARD));
1984: PetscUseTypeMethod(b, diagonalscale, NULL, aij->lvec);
1985: }
1986: PetscFunctionReturn(PETSC_SUCCESS);
1987: }
1989: static PetscErrorCode MatSetUnfactored_MPIAIJ(Mat A)
1990: {
1991: Mat_MPIAIJ *a = (Mat_MPIAIJ *)A->data;
1993: PetscFunctionBegin;
1994: PetscCall(MatSetUnfactored(a->A));
1995: PetscFunctionReturn(PETSC_SUCCESS);
1996: }
1998: static PetscErrorCode MatEqual_MPIAIJ(Mat A, Mat B, PetscBool *flag)
1999: {
2000: Mat_MPIAIJ *matB = (Mat_MPIAIJ *)B->data, *matA = (Mat_MPIAIJ *)A->data;
2001: Mat a, b, c, d;
2003: PetscFunctionBegin;
2004: a = matA->A;
2005: b = matA->B;
2006: c = matB->A;
2007: d = matB->B;
2009: PetscCall(MatEqual(a, c, flag));
2010: if (*flag) PetscCall(MatEqual(b, d, flag));
2011: PetscCallMPI(MPIU_Allreduce(MPI_IN_PLACE, flag, 1, MPI_C_BOOL, MPI_LAND, PetscObjectComm((PetscObject)A)));
2012: PetscFunctionReturn(PETSC_SUCCESS);
2013: }
2015: static PetscErrorCode MatCopy_MPIAIJ(Mat A, Mat B, MatStructure str)
2016: {
2017: Mat_MPIAIJ *a = (Mat_MPIAIJ *)A->data;
2018: Mat_MPIAIJ *b = (Mat_MPIAIJ *)B->data;
2020: PetscFunctionBegin;
2021: /* If the two matrices don't have the same copy implementation, they aren't compatible for fast copy. */
2022: if (str != SAME_NONZERO_PATTERN || A->ops->copy != B->ops->copy) {
2023: /* because of the column compression in the off-processor part of the matrix a->B,
2024: the number of columns in a->B and b->B may be different, hence we cannot call
2025: the MatCopy() directly on the two parts. If need be, we can provide a more
2026: efficient copy than the MatCopy_Basic() by first uncompressing the a->B matrices
2027: then copying the submatrices */
2028: PetscCall(MatCopy_Basic(A, B, str));
2029: } else {
2030: PetscCall(MatCopy(a->A, b->A, str));
2031: PetscCall(MatCopy(a->B, b->B, str));
2032: }
2033: PetscCall(PetscObjectStateIncrease((PetscObject)B));
2034: PetscFunctionReturn(PETSC_SUCCESS);
2035: }
2037: /*
2038: Computes the number of nonzeros per row needed for preallocation when X and Y
2039: have different nonzero structure.
2040: */
2041: 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)
2042: {
2043: PetscInt i, j, k, nzx, nzy;
2045: PetscFunctionBegin;
2046: /* Set the number of nonzeros in the new matrix */
2047: for (i = 0; i < m; i++) {
2048: const PetscInt *xjj = PetscSafePointerPlusOffset(xj, xi[i]), *yjj = PetscSafePointerPlusOffset(yj, yi[i]);
2049: nzx = xi[i + 1] - xi[i];
2050: nzy = yi[i + 1] - yi[i];
2051: nnz[i] = 0;
2052: for (j = 0, k = 0; j < nzx; j++) { /* Point in X */
2053: for (; k < nzy && yltog[yjj[k]] < xltog[xjj[j]]; k++) nnz[i]++; /* Catch up to X */
2054: if (k < nzy && yltog[yjj[k]] == xltog[xjj[j]]) k++; /* Skip duplicate */
2055: nnz[i]++;
2056: }
2057: for (; k < nzy; k++) nnz[i]++;
2058: }
2059: PetscFunctionReturn(PETSC_SUCCESS);
2060: }
2062: /* This is the same as MatAXPYGetPreallocation_SeqAIJ, except that the local-to-global map is provided */
2063: static PetscErrorCode MatAXPYGetPreallocation_MPIAIJ(Mat Y, const PetscInt *yltog, Mat X, const PetscInt *xltog, PetscInt *nnz)
2064: {
2065: PetscInt m = Y->rmap->N;
2066: Mat_SeqAIJ *x = (Mat_SeqAIJ *)X->data;
2067: Mat_SeqAIJ *y = (Mat_SeqAIJ *)Y->data;
2069: PetscFunctionBegin;
2070: PetscCall(MatAXPYGetPreallocation_MPIX_private(m, x->i, x->j, xltog, y->i, y->j, yltog, nnz));
2071: PetscFunctionReturn(PETSC_SUCCESS);
2072: }
2074: static PetscErrorCode MatAXPY_MPIAIJ(Mat Y, PetscScalar a, Mat X, MatStructure str)
2075: {
2076: Mat_MPIAIJ *xx = (Mat_MPIAIJ *)X->data, *yy = (Mat_MPIAIJ *)Y->data;
2078: PetscFunctionBegin;
2079: if (str == SAME_NONZERO_PATTERN) {
2080: PetscCall(MatAXPY(yy->A, a, xx->A, str));
2081: PetscCall(MatAXPY(yy->B, a, xx->B, str));
2082: } else if (str == SUBSET_NONZERO_PATTERN) { /* nonzeros of X is a subset of Y's */
2083: PetscCall(MatAXPY_Basic(Y, a, X, str));
2084: } else {
2085: Mat B;
2086: PetscInt *nnz_d, *nnz_o;
2087: PetscBool subset = PETSC_TRUE;
2088: Mat_SeqAIJ *ya = (Mat_SeqAIJ *)yy->A->data, *yb = (Mat_SeqAIJ *)yy->B->data;
2090: PetscCall(PetscMalloc1(yy->A->rmap->N, &nnz_d));
2091: PetscCall(PetscMalloc1(yy->B->rmap->N, &nnz_o));
2092: PetscCall(MatAXPYGetPreallocation_SeqAIJ(yy->A, xx->A, nnz_d));
2093: PetscCall(MatAXPYGetPreallocation_MPIAIJ(yy->B, yy->garray, xx->B, xx->garray, nnz_o));
2094: /* nnz_d[i] and nnz_o[i] are the sizes of the unions of row i of the blocks of X and Y, so the pattern of X is contained in
2095: that of Y when, on every process, they equal the lengths of row i of the blocks of Y. Adding in place then keeps the nonzero
2096: pattern of Y, and its nonzero state, unchanged. */
2097: for (PetscInt i = 0; i < yy->A->rmap->N && subset; i++) subset = (PetscBool)(nnz_d[i] == ya->i[i + 1] - ya->i[i] && nnz_o[i] == yb->i[i + 1] - yb->i[i]);
2098: PetscCallMPI(MPIU_Allreduce(MPI_IN_PLACE, &subset, 1, MPI_C_BOOL, MPI_LAND, PetscObjectComm((PetscObject)Y)));
2099: if (subset) PetscCall(MatAXPY_Basic(Y, a, X, SUBSET_NONZERO_PATTERN));
2100: else {
2101: PetscCall(MatCreate(PetscObjectComm((PetscObject)Y), &B));
2102: PetscCall(PetscObjectSetName((PetscObject)B, ((PetscObject)Y)->name));
2103: PetscCall(MatSetLayouts(B, Y->rmap, Y->cmap));
2104: PetscCall(MatSetType(B, ((PetscObject)Y)->type_name));
2105: PetscCall(MatMPIAIJSetPreallocation(B, 0, nnz_d, 0, nnz_o));
2106: PetscCall(MatAXPY_BasicWithPreallocation(B, Y, a, X, str));
2107: PetscCall(MatHeaderMerge(Y, &B));
2108: }
2109: PetscCall(PetscFree(nnz_d));
2110: PetscCall(PetscFree(nnz_o));
2111: }
2112: PetscFunctionReturn(PETSC_SUCCESS);
2113: }
2115: PETSC_INTERN PetscErrorCode MatConjugate_SeqAIJ(Mat);
2117: static PetscErrorCode MatConjugate_MPIAIJ(Mat mat)
2118: {
2119: Mat_MPIAIJ *aij = (Mat_MPIAIJ *)mat->data;
2121: PetscFunctionBegin;
2122: PetscCall(MatConjugate_SeqAIJ(aij->A));
2123: PetscCall(MatConjugate_SeqAIJ(aij->B));
2124: PetscFunctionReturn(PETSC_SUCCESS);
2125: }
2127: static PetscErrorCode MatRealPart_MPIAIJ(Mat A)
2128: {
2129: Mat_MPIAIJ *a = (Mat_MPIAIJ *)A->data;
2131: PetscFunctionBegin;
2132: PetscCall(MatRealPart(a->A));
2133: PetscCall(MatRealPart(a->B));
2134: PetscFunctionReturn(PETSC_SUCCESS);
2135: }
2137: static PetscErrorCode MatImaginaryPart_MPIAIJ(Mat A)
2138: {
2139: Mat_MPIAIJ *a = (Mat_MPIAIJ *)A->data;
2141: PetscFunctionBegin;
2142: PetscCall(MatImaginaryPart(a->A));
2143: PetscCall(MatImaginaryPart(a->B));
2144: PetscFunctionReturn(PETSC_SUCCESS);
2145: }
2147: static PetscErrorCode MatGetRowMaxAbs_MPIAIJ(Mat A, Vec v, PetscInt idx[])
2148: {
2149: Mat_MPIAIJ *a = (Mat_MPIAIJ *)A->data;
2150: PetscInt i, *idxb = NULL, m = A->rmap->n;
2151: PetscScalar *vv;
2152: Vec vB, vA;
2153: const PetscScalar *va, *vb;
2155: PetscFunctionBegin;
2156: PetscCall(MatCreateVecs(a->A, NULL, &vA));
2157: PetscCall(MatGetRowMaxAbs(a->A, vA, idx));
2159: PetscCall(VecGetArrayRead(vA, &va));
2160: if (idx) {
2161: for (i = 0; i < m; i++) {
2162: if (PetscAbsScalar(va[i])) idx[i] += A->cmap->rstart;
2163: }
2164: }
2166: PetscCall(MatCreateVecs(a->B, NULL, &vB));
2167: PetscCall(PetscMalloc1(m, &idxb));
2168: PetscCall(MatGetRowMaxAbs(a->B, vB, idxb));
2170: PetscCall(VecGetArrayWrite(v, &vv));
2171: PetscCall(VecGetArrayRead(vB, &vb));
2172: for (i = 0; i < m; i++) {
2173: if (PetscAbsScalar(va[i]) < PetscAbsScalar(vb[i])) {
2174: vv[i] = vb[i];
2175: if (idx) idx[i] = a->garray[idxb[i]];
2176: } else {
2177: vv[i] = va[i];
2178: if (idx && PetscAbsScalar(va[i]) == PetscAbsScalar(vb[i]) && idxb[i] != -1 && idx[i] > a->garray[idxb[i]]) idx[i] = a->garray[idxb[i]];
2179: }
2180: }
2181: PetscCall(VecRestoreArrayWrite(v, &vv));
2182: PetscCall(VecRestoreArrayRead(vA, &va));
2183: PetscCall(VecRestoreArrayRead(vB, &vb));
2184: PetscCall(PetscFree(idxb));
2185: PetscCall(VecDestroy(&vA));
2186: PetscCall(VecDestroy(&vB));
2187: PetscFunctionReturn(PETSC_SUCCESS);
2188: }
2190: static PetscErrorCode MatGetRowSumAbs_MPIAIJ(Mat A, Vec v)
2191: {
2192: Mat_MPIAIJ *a = (Mat_MPIAIJ *)A->data;
2193: Vec vB, vA;
2195: PetscFunctionBegin;
2196: PetscCall(MatCreateVecs(a->A, NULL, &vA));
2197: PetscCall(MatGetRowSumAbs(a->A, vA));
2198: PetscCall(MatCreateVecs(a->B, NULL, &vB));
2199: PetscCall(MatGetRowSumAbs(a->B, vB));
2200: PetscCall(VecAXPY(vA, 1.0, vB));
2201: PetscCall(VecDestroy(&vB));
2202: PetscCall(VecCopy(vA, v));
2203: PetscCall(VecDestroy(&vA));
2204: PetscFunctionReturn(PETSC_SUCCESS);
2205: }
2207: static PetscErrorCode MatGetRowMinAbs_MPIAIJ(Mat A, Vec v, PetscInt idx[])
2208: {
2209: Mat_MPIAIJ *mat = (Mat_MPIAIJ *)A->data;
2210: PetscInt m = A->rmap->n, n = A->cmap->n;
2211: PetscInt cstart = A->cmap->rstart, cend = A->cmap->rend;
2212: PetscInt *cmap = mat->garray;
2213: PetscInt *diagIdx, *offdiagIdx;
2214: Vec diagV, offdiagV;
2215: PetscScalar *a, *diagA, *offdiagA;
2216: const PetscScalar *ba, *bav;
2217: PetscInt r, j, col, ncols, *bi, *bj;
2218: Mat B = mat->B;
2219: Mat_SeqAIJ *b = (Mat_SeqAIJ *)B->data;
2221: PetscFunctionBegin;
2222: /* When a process holds entire A and other processes have no entry */
2223: if (A->cmap->N == n) {
2224: PetscCall(VecGetArrayWrite(v, &diagA));
2225: PetscCall(VecCreateSeqWithArray(PETSC_COMM_SELF, 1, m, diagA, &diagV));
2226: PetscCall(MatGetRowMinAbs(mat->A, diagV, idx));
2227: PetscCall(VecDestroy(&diagV));
2228: PetscCall(VecRestoreArrayWrite(v, &diagA));
2229: PetscFunctionReturn(PETSC_SUCCESS);
2230: } else if (n == 0) {
2231: if (m) {
2232: PetscCall(VecGetArrayWrite(v, &a));
2233: for (r = 0; r < m; r++) {
2234: a[r] = 0.0;
2235: if (idx) idx[r] = -1;
2236: }
2237: PetscCall(VecRestoreArrayWrite(v, &a));
2238: }
2239: PetscFunctionReturn(PETSC_SUCCESS);
2240: }
2242: PetscCall(PetscMalloc2(m, &diagIdx, m, &offdiagIdx));
2243: PetscCall(VecCreateSeq(PETSC_COMM_SELF, m, &diagV));
2244: PetscCall(VecCreateSeq(PETSC_COMM_SELF, m, &offdiagV));
2245: PetscCall(MatGetRowMinAbs(mat->A, diagV, diagIdx));
2247: /* Get offdiagIdx[] for implicit 0.0 */
2248: PetscCall(MatSeqAIJGetArrayRead(B, &bav));
2249: ba = bav;
2250: bi = b->i;
2251: bj = b->j;
2252: PetscCall(VecGetArrayWrite(offdiagV, &offdiagA));
2253: for (r = 0; r < m; r++) {
2254: ncols = bi[r + 1] - bi[r];
2255: if (ncols == A->cmap->N - n) { /* Brow is dense */
2256: offdiagA[r] = *ba;
2257: offdiagIdx[r] = cmap[0];
2258: } else { /* Brow is sparse so already KNOW maximum is 0.0 or higher */
2259: offdiagA[r] = 0.0;
2261: /* Find first hole in the cmap */
2262: for (j = 0; j < ncols; j++) {
2263: col = cmap[bj[j]]; /* global column number = cmap[B column number] */
2264: if (col > j && j < cstart) {
2265: offdiagIdx[r] = j; /* global column number of first implicit 0.0 */
2266: break;
2267: } else if (col > j + n && j >= cstart) {
2268: offdiagIdx[r] = j + n; /* global column number of first implicit 0.0 */
2269: break;
2270: }
2271: }
2272: if (j == ncols && ncols < A->cmap->N - n) {
2273: /* a hole is outside compressed Bcols */
2274: if (ncols == 0) {
2275: if (cstart) {
2276: offdiagIdx[r] = 0;
2277: } else offdiagIdx[r] = cend;
2278: } else { /* ncols > 0 */
2279: offdiagIdx[r] = cmap[ncols - 1] + 1;
2280: if (offdiagIdx[r] == cstart) offdiagIdx[r] += n;
2281: }
2282: }
2283: }
2285: for (j = 0; j < ncols; j++) {
2286: if (PetscAbsScalar(offdiagA[r]) > PetscAbsScalar(*ba)) {
2287: offdiagA[r] = *ba;
2288: offdiagIdx[r] = cmap[*bj];
2289: }
2290: ba++;
2291: bj++;
2292: }
2293: }
2295: PetscCall(VecGetArrayWrite(v, &a));
2296: PetscCall(VecGetArrayRead(diagV, (const PetscScalar **)&diagA));
2297: for (r = 0; r < m; ++r) {
2298: if (PetscAbsScalar(diagA[r]) < PetscAbsScalar(offdiagA[r])) {
2299: a[r] = diagA[r];
2300: if (idx) idx[r] = cstart + diagIdx[r];
2301: } else if (PetscAbsScalar(diagA[r]) == PetscAbsScalar(offdiagA[r])) {
2302: a[r] = diagA[r];
2303: if (idx) {
2304: if (cstart + diagIdx[r] <= offdiagIdx[r]) {
2305: idx[r] = cstart + diagIdx[r];
2306: } else idx[r] = offdiagIdx[r];
2307: }
2308: } else {
2309: a[r] = offdiagA[r];
2310: if (idx) idx[r] = offdiagIdx[r];
2311: }
2312: }
2313: PetscCall(MatSeqAIJRestoreArrayRead(B, &bav));
2314: PetscCall(VecRestoreArrayWrite(v, &a));
2315: PetscCall(VecRestoreArrayRead(diagV, (const PetscScalar **)&diagA));
2316: PetscCall(VecRestoreArrayWrite(offdiagV, &offdiagA));
2317: PetscCall(VecDestroy(&diagV));
2318: PetscCall(VecDestroy(&offdiagV));
2319: PetscCall(PetscFree2(diagIdx, offdiagIdx));
2320: PetscFunctionReturn(PETSC_SUCCESS);
2321: }
2323: static PetscErrorCode MatGetRowMin_MPIAIJ(Mat A, Vec v, PetscInt idx[])
2324: {
2325: Mat_MPIAIJ *mat = (Mat_MPIAIJ *)A->data;
2326: PetscInt m = A->rmap->n, n = A->cmap->n;
2327: PetscInt cstart = A->cmap->rstart, cend = A->cmap->rend;
2328: PetscInt *cmap = mat->garray;
2329: PetscInt *diagIdx, *offdiagIdx;
2330: Vec diagV, offdiagV;
2331: PetscScalar *a, *diagA, *offdiagA;
2332: const PetscScalar *ba, *bav;
2333: PetscInt r, j, col, ncols, *bi, *bj;
2334: Mat B = mat->B;
2335: Mat_SeqAIJ *b = (Mat_SeqAIJ *)B->data;
2337: PetscFunctionBegin;
2338: /* When a process holds entire A and other processes have no entry */
2339: if (A->cmap->N == n) {
2340: PetscCall(VecGetArrayWrite(v, &diagA));
2341: PetscCall(VecCreateSeqWithArray(PETSC_COMM_SELF, 1, m, diagA, &diagV));
2342: PetscCall(MatGetRowMin(mat->A, diagV, idx));
2343: PetscCall(VecDestroy(&diagV));
2344: PetscCall(VecRestoreArrayWrite(v, &diagA));
2345: PetscFunctionReturn(PETSC_SUCCESS);
2346: } else if (n == 0) {
2347: if (m) {
2348: PetscCall(VecGetArrayWrite(v, &a));
2349: for (r = 0; r < m; r++) {
2350: a[r] = PETSC_MAX_REAL;
2351: if (idx) idx[r] = -1;
2352: }
2353: PetscCall(VecRestoreArrayWrite(v, &a));
2354: }
2355: PetscFunctionReturn(PETSC_SUCCESS);
2356: }
2358: PetscCall(PetscCalloc2(m, &diagIdx, m, &offdiagIdx));
2359: PetscCall(VecCreateSeq(PETSC_COMM_SELF, m, &diagV));
2360: PetscCall(VecCreateSeq(PETSC_COMM_SELF, m, &offdiagV));
2361: PetscCall(MatGetRowMin(mat->A, diagV, diagIdx));
2363: /* Get offdiagIdx[] for implicit 0.0 */
2364: PetscCall(MatSeqAIJGetArrayRead(B, &bav));
2365: ba = bav;
2366: bi = b->i;
2367: bj = b->j;
2368: PetscCall(VecGetArrayWrite(offdiagV, &offdiagA));
2369: for (r = 0; r < m; r++) {
2370: ncols = bi[r + 1] - bi[r];
2371: if (ncols == A->cmap->N - n) { /* Brow is dense */
2372: offdiagA[r] = *ba;
2373: offdiagIdx[r] = cmap[0];
2374: } else { /* Brow is sparse so already KNOW maximum is 0.0 or higher */
2375: offdiagA[r] = 0.0;
2377: /* Find first hole in the cmap */
2378: for (j = 0; j < ncols; j++) {
2379: col = cmap[bj[j]]; /* global column number = cmap[B column number] */
2380: if (col > j && j < cstart) {
2381: offdiagIdx[r] = j; /* global column number of first implicit 0.0 */
2382: break;
2383: } else if (col > j + n && j >= cstart) {
2384: offdiagIdx[r] = j + n; /* global column number of first implicit 0.0 */
2385: break;
2386: }
2387: }
2388: if (j == ncols && ncols < A->cmap->N - n) {
2389: /* a hole is outside compressed Bcols */
2390: if (ncols == 0) {
2391: if (cstart) {
2392: offdiagIdx[r] = 0;
2393: } else offdiagIdx[r] = cend;
2394: } else { /* ncols > 0 */
2395: offdiagIdx[r] = cmap[ncols - 1] + 1;
2396: if (offdiagIdx[r] == cstart) offdiagIdx[r] += n;
2397: }
2398: }
2399: }
2401: for (j = 0; j < ncols; j++) {
2402: if (PetscRealPart(offdiagA[r]) > PetscRealPart(*ba)) {
2403: offdiagA[r] = *ba;
2404: offdiagIdx[r] = cmap[*bj];
2405: }
2406: ba++;
2407: bj++;
2408: }
2409: }
2411: PetscCall(VecGetArrayWrite(v, &a));
2412: PetscCall(VecGetArrayRead(diagV, (const PetscScalar **)&diagA));
2413: for (r = 0; r < m; ++r) {
2414: if (PetscRealPart(diagA[r]) < PetscRealPart(offdiagA[r])) {
2415: a[r] = diagA[r];
2416: if (idx) idx[r] = cstart + diagIdx[r];
2417: } else if (PetscRealPart(diagA[r]) == PetscRealPart(offdiagA[r])) {
2418: a[r] = diagA[r];
2419: if (idx) {
2420: if (cstart + diagIdx[r] <= offdiagIdx[r]) {
2421: idx[r] = cstart + diagIdx[r];
2422: } else idx[r] = offdiagIdx[r];
2423: }
2424: } else {
2425: a[r] = offdiagA[r];
2426: if (idx) idx[r] = offdiagIdx[r];
2427: }
2428: }
2429: PetscCall(MatSeqAIJRestoreArrayRead(B, &bav));
2430: PetscCall(VecRestoreArrayWrite(v, &a));
2431: PetscCall(VecRestoreArrayRead(diagV, (const PetscScalar **)&diagA));
2432: PetscCall(VecRestoreArrayWrite(offdiagV, &offdiagA));
2433: PetscCall(VecDestroy(&diagV));
2434: PetscCall(VecDestroy(&offdiagV));
2435: PetscCall(PetscFree2(diagIdx, offdiagIdx));
2436: PetscFunctionReturn(PETSC_SUCCESS);
2437: }
2439: static PetscErrorCode MatGetRowMax_MPIAIJ(Mat A, Vec v, PetscInt idx[])
2440: {
2441: Mat_MPIAIJ *mat = (Mat_MPIAIJ *)A->data;
2442: PetscInt m = A->rmap->n, n = A->cmap->n;
2443: PetscInt cstart = A->cmap->rstart, cend = A->cmap->rend;
2444: PetscInt *cmap = mat->garray;
2445: PetscInt *diagIdx, *offdiagIdx;
2446: Vec diagV, offdiagV;
2447: PetscScalar *a, *diagA, *offdiagA;
2448: const PetscScalar *ba, *bav;
2449: PetscInt r, j, col, ncols, *bi, *bj;
2450: Mat B = mat->B;
2451: Mat_SeqAIJ *b = (Mat_SeqAIJ *)B->data;
2453: PetscFunctionBegin;
2454: /* When a process holds entire A and other processes have no entry */
2455: if (A->cmap->N == n) {
2456: PetscCall(VecGetArrayWrite(v, &diagA));
2457: PetscCall(VecCreateSeqWithArray(PETSC_COMM_SELF, 1, m, diagA, &diagV));
2458: PetscCall(MatGetRowMax(mat->A, diagV, idx));
2459: PetscCall(VecDestroy(&diagV));
2460: PetscCall(VecRestoreArrayWrite(v, &diagA));
2461: PetscFunctionReturn(PETSC_SUCCESS);
2462: } else if (n == 0) {
2463: if (m) {
2464: PetscCall(VecGetArrayWrite(v, &a));
2465: for (r = 0; r < m; r++) {
2466: a[r] = PETSC_MIN_REAL;
2467: if (idx) idx[r] = -1;
2468: }
2469: PetscCall(VecRestoreArrayWrite(v, &a));
2470: }
2471: PetscFunctionReturn(PETSC_SUCCESS);
2472: }
2474: PetscCall(PetscMalloc2(m, &diagIdx, m, &offdiagIdx));
2475: PetscCall(VecCreateSeq(PETSC_COMM_SELF, m, &diagV));
2476: PetscCall(VecCreateSeq(PETSC_COMM_SELF, m, &offdiagV));
2477: PetscCall(MatGetRowMax(mat->A, diagV, diagIdx));
2479: /* Get offdiagIdx[] for implicit 0.0 */
2480: PetscCall(MatSeqAIJGetArrayRead(B, &bav));
2481: ba = bav;
2482: bi = b->i;
2483: bj = b->j;
2484: PetscCall(VecGetArrayWrite(offdiagV, &offdiagA));
2485: for (r = 0; r < m; r++) {
2486: ncols = bi[r + 1] - bi[r];
2487: if (ncols == A->cmap->N - n) { /* Brow is dense */
2488: offdiagA[r] = *ba;
2489: offdiagIdx[r] = cmap[0];
2490: } else { /* Brow is sparse so already KNOW maximum is 0.0 or higher */
2491: offdiagA[r] = 0.0;
2493: /* Find first hole in the cmap */
2494: for (j = 0; j < ncols; j++) {
2495: col = cmap[bj[j]]; /* global column number = cmap[B column number] */
2496: if (col > j && j < cstart) {
2497: offdiagIdx[r] = j; /* global column number of first implicit 0.0 */
2498: break;
2499: } else if (col > j + n && j >= cstart) {
2500: offdiagIdx[r] = j + n; /* global column number of first implicit 0.0 */
2501: break;
2502: }
2503: }
2504: if (j == ncols && ncols < A->cmap->N - n) {
2505: /* a hole is outside compressed Bcols */
2506: if (ncols == 0) {
2507: if (cstart) {
2508: offdiagIdx[r] = 0;
2509: } else offdiagIdx[r] = cend;
2510: } else { /* ncols > 0 */
2511: offdiagIdx[r] = cmap[ncols - 1] + 1;
2512: if (offdiagIdx[r] == cstart) offdiagIdx[r] += n;
2513: }
2514: }
2515: }
2517: for (j = 0; j < ncols; j++) {
2518: if (PetscRealPart(offdiagA[r]) < PetscRealPart(*ba)) {
2519: offdiagA[r] = *ba;
2520: offdiagIdx[r] = cmap[*bj];
2521: }
2522: ba++;
2523: bj++;
2524: }
2525: }
2527: PetscCall(VecGetArrayWrite(v, &a));
2528: PetscCall(VecGetArrayRead(diagV, (const PetscScalar **)&diagA));
2529: for (r = 0; r < m; ++r) {
2530: if (PetscRealPart(diagA[r]) > PetscRealPart(offdiagA[r])) {
2531: a[r] = diagA[r];
2532: if (idx) idx[r] = cstart + diagIdx[r];
2533: } else if (PetscRealPart(diagA[r]) == PetscRealPart(offdiagA[r])) {
2534: a[r] = diagA[r];
2535: if (idx) {
2536: if (cstart + diagIdx[r] <= offdiagIdx[r]) {
2537: idx[r] = cstart + diagIdx[r];
2538: } else idx[r] = offdiagIdx[r];
2539: }
2540: } else {
2541: a[r] = offdiagA[r];
2542: if (idx) idx[r] = offdiagIdx[r];
2543: }
2544: }
2545: PetscCall(MatSeqAIJRestoreArrayRead(B, &bav));
2546: PetscCall(VecRestoreArrayWrite(v, &a));
2547: PetscCall(VecRestoreArrayRead(diagV, (const PetscScalar **)&diagA));
2548: PetscCall(VecRestoreArrayWrite(offdiagV, &offdiagA));
2549: PetscCall(VecDestroy(&diagV));
2550: PetscCall(VecDestroy(&offdiagV));
2551: PetscCall(PetscFree2(diagIdx, offdiagIdx));
2552: PetscFunctionReturn(PETSC_SUCCESS);
2553: }
2555: PetscErrorCode MatGetSeqNonzeroStructure_MPIAIJ(Mat mat, Mat *newmat)
2556: {
2557: Mat *dummy;
2559: PetscFunctionBegin;
2560: PetscCall(MatCreateSubMatrix_MPIAIJ_All(mat, MAT_DO_NOT_GET_VALUES, MAT_INITIAL_MATRIX, &dummy));
2561: *newmat = *dummy;
2562: PetscCall(PetscFree(dummy));
2563: PetscFunctionReturn(PETSC_SUCCESS);
2564: }
2566: static PetscErrorCode MatInvertBlockDiagonal_MPIAIJ(Mat A, const PetscScalar **values)
2567: {
2568: Mat_MPIAIJ *a = (Mat_MPIAIJ *)A->data;
2570: PetscFunctionBegin;
2571: PetscCall(MatInvertBlockDiagonal(a->A, values));
2572: A->factorerrortype = a->A->factorerrortype;
2573: PetscFunctionReturn(PETSC_SUCCESS);
2574: }
2576: static PetscErrorCode MatSetRandom_MPIAIJ(Mat x, PetscRandom rctx)
2577: {
2578: Mat_MPIAIJ *aij = (Mat_MPIAIJ *)x->data;
2579: PetscBool nooffprocentries = x->nooffprocentries;
2581: PetscFunctionBegin;
2582: PetscCheck(x->assembled || x->preallocated, PetscObjectComm((PetscObject)x), PETSC_ERR_ARG_WRONGSTATE, "MatSetRandom() on an unassembled and unpreallocated MATMPIAIJ is not allowed");
2583: PetscCall(MatSetRandom(aij->A, rctx));
2584: if (x->assembled) PetscCall(MatSetRandom(aij->B, rctx));
2585: else PetscCall(MatSetRandomSkipColumnRange_SeqAIJ_Private(aij->B, x->cmap->rstart, x->cmap->rend, rctx));
2586: PetscCall(MatSetOption(x, MAT_NO_OFF_PROC_ENTRIES, PETSC_TRUE));
2587: PetscCall(MatAssemblyBegin(x, MAT_FINAL_ASSEMBLY));
2588: PetscCall(MatAssemblyEnd(x, MAT_FINAL_ASSEMBLY));
2589: PetscCall(MatSetOption(x, MAT_NO_OFF_PROC_ENTRIES, nooffprocentries));
2590: PetscFunctionReturn(PETSC_SUCCESS);
2591: }
2593: static PetscErrorCode MatMPIAIJSetUseScalableIncreaseOverlap_MPIAIJ(Mat A, PetscBool sc)
2594: {
2595: PetscFunctionBegin;
2596: if (sc) A->ops->increaseoverlap = MatIncreaseOverlap_MPIAIJ_Scalable;
2597: else A->ops->increaseoverlap = MatIncreaseOverlap_MPIAIJ;
2598: PetscFunctionReturn(PETSC_SUCCESS);
2599: }
2601: /*@
2602: MatMPIAIJGetNumberNonzeros - gets the number of nonzeros in the matrix on this MPI process
2604: Not Collective
2606: Input Parameter:
2607: . A - the matrix
2609: Output Parameter:
2610: . nz - the number of nonzeros
2612: Level: advanced
2614: .seealso: [](ch_matrices), `Mat`, `MATMPIAIJ`
2615: @*/
2616: PetscErrorCode MatMPIAIJGetNumberNonzeros(Mat A, PetscCount *nz)
2617: {
2618: Mat_MPIAIJ *maij = (Mat_MPIAIJ *)A->data;
2619: Mat_SeqAIJ *aaij = (Mat_SeqAIJ *)maij->A->data, *baij = (Mat_SeqAIJ *)maij->B->data;
2620: PetscBool isaij;
2622: PetscFunctionBegin;
2623: PetscCall(PetscObjectBaseTypeCompare((PetscObject)A, MATMPIAIJ, &isaij));
2624: PetscCheck(isaij, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "Not for type %s", ((PetscObject)A)->type_name);
2625: *nz = aaij->i[A->rmap->n] + baij->i[A->rmap->n];
2626: PetscFunctionReturn(PETSC_SUCCESS);
2627: }
2629: /*@
2630: MatMPIAIJSetUseScalableIncreaseOverlap - Determine if the matrix uses a scalable algorithm to compute the overlap
2632: Collective
2634: Input Parameters:
2635: + A - the matrix
2636: - sc - `PETSC_TRUE` indicates use the scalable algorithm (default is not to use the scalable algorithm)
2638: Level: advanced
2640: .seealso: [](ch_matrices), `Mat`, `MATMPIAIJ`
2641: @*/
2642: PetscErrorCode MatMPIAIJSetUseScalableIncreaseOverlap(Mat A, PetscBool sc)
2643: {
2644: PetscFunctionBegin;
2645: PetscTryMethod(A, "MatMPIAIJSetUseScalableIncreaseOverlap_C", (Mat, PetscBool), (A, sc));
2646: PetscFunctionReturn(PETSC_SUCCESS);
2647: }
2649: PetscErrorCode MatSetFromOptions_MPIAIJ(Mat A, PetscOptionItems PetscOptionsObject)
2650: {
2651: PetscBool sc = PETSC_FALSE, flg;
2653: PetscFunctionBegin;
2654: PetscOptionsHeadBegin(PetscOptionsObject, "MPIAIJ options");
2655: if (A->ops->increaseoverlap == MatIncreaseOverlap_MPIAIJ_Scalable) sc = PETSC_TRUE;
2656: PetscCall(PetscOptionsBool("-mat_increase_overlap_scalable", "Use a scalable algorithm to compute the overlap", "MatIncreaseOverlap", sc, &sc, &flg));
2657: if (flg) PetscCall(MatMPIAIJSetUseScalableIncreaseOverlap(A, sc));
2658: PetscOptionsHeadEnd();
2659: PetscFunctionReturn(PETSC_SUCCESS);
2660: }
2662: static PetscErrorCode MatShift_MPIAIJ(Mat Y, PetscScalar a)
2663: {
2664: Mat_MPIAIJ *maij = (Mat_MPIAIJ *)Y->data;
2665: Mat_SeqAIJ *aij = (Mat_SeqAIJ *)maij->A->data;
2667: PetscFunctionBegin;
2668: if (!Y->preallocated) {
2669: PetscCall(MatMPIAIJSetPreallocation(Y, 1, NULL, 0, NULL));
2670: } else if (!aij->nz && PetscMax(Y->rmap->rstart, Y->cmap->rstart) < PetscMin(Y->rmap->rend, Y->cmap->rend)) {
2671: /* If maij->A has no nonzeros, preallocate it again only if one of the local rows has its diagonal entry in maij->A, otherwise
2672: its nonzero state would increase even though the shift creates no new nonzeros in it */
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: NULL,
2873: /*144*/ NULL,
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 PetscDefined(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);
2929: PetscCall(MatSetOption(b->B, MAT_STRUCTURE_ONLY, B->structure_only));
2931: MatSeqXAIJGetOptions_Private(b->A);
2932: PetscCall(MatDestroy(&b->A));
2933: PetscCall(MatCreate(PETSC_COMM_SELF, &b->A));
2934: PetscCall(MatSetSizes(b->A, B->rmap->n, B->cmap->n, B->rmap->n, B->cmap->n));
2935: PetscCall(MatSetBlockSizesFromMats(b->A, B, B));
2936: PetscCall(MatSetType(b->A, MATSEQAIJ));
2937: MatSeqXAIJRestoreOptions_Private(b->A);
2938: PetscCall(MatSetOption(b->A, MAT_STRUCTURE_ONLY, B->structure_only));
2940: PetscCall(MatSeqAIJSetPreallocation(b->A, d_nz, d_nnz));
2941: PetscCall(MatSeqAIJSetPreallocation(b->B, o_nz, o_nnz));
2942: B->preallocated = PETSC_TRUE;
2943: B->was_assembled = PETSC_FALSE;
2944: B->assembled = PETSC_FALSE;
2945: PetscFunctionReturn(PETSC_SUCCESS);
2946: }
2948: static PetscErrorCode MatResetPreallocation_MPIAIJ(Mat B)
2949: {
2950: Mat_MPIAIJ *b = (Mat_MPIAIJ *)B->data;
2951: PetscBool ondiagreset, offdiagreset, memoryreset;
2953: PetscFunctionBegin;
2955: 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()");
2956: if (B->num_ass == 0) PetscFunctionReturn(PETSC_SUCCESS);
2958: PetscCall(MatResetPreallocation_SeqAIJ_Private(b->A, &ondiagreset));
2959: PetscCall(MatResetPreallocation_SeqAIJ_Private(b->B, &offdiagreset));
2960: memoryreset = (PetscBool)(ondiagreset || offdiagreset);
2961: PetscCallMPI(MPIU_Allreduce(MPI_IN_PLACE, &memoryreset, 1, MPI_C_BOOL, MPI_LOR, PetscObjectComm((PetscObject)B)));
2962: if (!memoryreset) PetscFunctionReturn(PETSC_SUCCESS);
2964: PetscCall(PetscLayoutSetUp(B->rmap));
2965: PetscCall(PetscLayoutSetUp(B->cmap));
2966: 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");
2967: PetscCall(MatDisAssemble_MPIAIJ(B, PETSC_TRUE));
2968: PetscCall(VecScatterDestroy(&b->Mvctx));
2970: B->preallocated = PETSC_TRUE;
2971: B->was_assembled = PETSC_FALSE;
2972: B->assembled = PETSC_FALSE;
2973: /* Log that the state of this object has changed; this will help guarantee that preconditioners get re-setup */
2974: PetscCall(PetscObjectStateIncrease((PetscObject)B));
2975: PetscFunctionReturn(PETSC_SUCCESS);
2976: }
2978: PetscErrorCode MatDuplicate_MPIAIJ(Mat matin, MatDuplicateOption cpvalues, Mat *newmat)
2979: {
2980: Mat mat;
2981: Mat_MPIAIJ *a, *oldmat = (Mat_MPIAIJ *)matin->data;
2983: PetscFunctionBegin;
2984: *newmat = NULL;
2985: PetscCall(MatCreate(PetscObjectComm((PetscObject)matin), &mat));
2986: PetscCall(MatSetSizes(mat, matin->rmap->n, matin->cmap->n, matin->rmap->N, matin->cmap->N));
2987: PetscCall(MatSetBlockSizesFromMats(mat, matin, matin));
2988: PetscCall(MatSetType(mat, ((PetscObject)matin)->type_name));
2989: PetscCall(MatSetOption(mat, MAT_STRUCTURE_ONLY, matin->structure_only));
2990: a = (Mat_MPIAIJ *)mat->data;
2992: mat->factortype = matin->factortype;
2993: mat->assembled = matin->assembled;
2994: mat->insertmode = NOT_SET_VALUES;
2996: a->size = oldmat->size;
2997: a->rank = oldmat->rank;
2998: a->donotstash = oldmat->donotstash;
2999: a->roworiented = oldmat->roworiented;
3000: a->rowindices = NULL;
3001: a->rowvalues = NULL;
3002: a->getrowactive = PETSC_FALSE;
3004: PetscCall(PetscLayoutReference(matin->rmap, &mat->rmap));
3005: PetscCall(PetscLayoutReference(matin->cmap, &mat->cmap));
3006: if (matin->hash_active) PetscCall(MatSetUp(mat));
3007: else {
3008: mat->preallocated = matin->preallocated;
3009: if (oldmat->colmap) {
3010: #if PetscDefined(USE_CTABLE)
3011: PetscCall(PetscHMapIDuplicate(oldmat->colmap, &a->colmap));
3012: #else
3013: PetscCall(PetscMalloc1(mat->cmap->N, &a->colmap));
3014: PetscCall(PetscArraycpy(a->colmap, oldmat->colmap, mat->cmap->N));
3015: #endif
3016: } else a->colmap = NULL;
3017: if (oldmat->garray) {
3018: PetscInt len;
3019: len = oldmat->B->cmap->n;
3020: PetscCall(PetscMalloc1(len, &a->garray));
3021: if (len) PetscCall(PetscArraycpy(a->garray, oldmat->garray, len));
3022: } else a->garray = NULL;
3024: /* It may happen MatDuplicate is called with a non-assembled matrix
3025: In fact, MatDuplicate only requires the matrix to be preallocated
3026: This may happen inside a DMCreateMatrix_Shell */
3027: if (oldmat->lvec) PetscCall(VecDuplicate(oldmat->lvec, &a->lvec));
3028: if (oldmat->Mvctx) {
3029: a->Mvctx = oldmat->Mvctx;
3030: PetscCall(PetscObjectReference((PetscObject)oldmat->Mvctx));
3031: }
3032: PetscCall(MatDuplicate(oldmat->A, cpvalues, &a->A));
3033: PetscCall(MatDuplicate(oldmat->B, cpvalues, &a->B));
3034: }
3035: PetscCall(PetscFunctionListDuplicate(((PetscObject)matin)->qlist, &((PetscObject)mat)->qlist));
3036: *newmat = mat;
3037: PetscFunctionReturn(PETSC_SUCCESS);
3038: }
3040: PetscErrorCode MatLoad_MPIAIJ(Mat newMat, PetscViewer viewer)
3041: {
3042: PetscBool isbinary, ishdf5;
3044: PetscFunctionBegin;
3047: /* force binary viewer to load .info file if it has not yet done so */
3048: PetscCall(PetscViewerSetUp(viewer));
3049: PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERBINARY, &isbinary));
3050: PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERHDF5, &ishdf5));
3051: if (isbinary) {
3052: PetscCall(MatLoad_MPIAIJ_Binary(newMat, viewer));
3053: } else if (ishdf5) {
3054: #if PetscDefined(HAVE_HDF5)
3055: PetscCall(MatLoad_AIJ_HDF5(newMat, viewer));
3056: #else
3057: SETERRQ(PetscObjectComm((PetscObject)newMat), PETSC_ERR_SUP, "HDF5 not supported in this build.\nPlease reconfigure using --download-hdf5");
3058: #endif
3059: } else {
3060: 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);
3061: }
3062: PetscFunctionReturn(PETSC_SUCCESS);
3063: }
3065: PetscErrorCode MatLoad_MPIAIJ_Binary(Mat mat, PetscViewer viewer)
3066: {
3067: PetscInt header[4], M, N, m, nz, rows, cols, sum, i;
3068: PetscInt *rowidxs, *colidxs;
3069: PetscScalar *matvals;
3071: PetscFunctionBegin;
3072: PetscCall(PetscViewerSetUp(viewer));
3074: /* read in matrix header */
3075: PetscCall(PetscViewerBinaryRead(viewer, header, 4, NULL, PETSC_INT));
3076: PetscCheck(header[0] == MAT_FILE_CLASSID, PetscObjectComm((PetscObject)viewer), PETSC_ERR_FILE_UNEXPECTED, "Not a matrix object in file");
3077: M = header[1];
3078: N = header[2];
3079: nz = header[3];
3080: PetscCheck(M >= 0, PetscObjectComm((PetscObject)viewer), PETSC_ERR_FILE_UNEXPECTED, "Matrix row size (%" PetscInt_FMT ") in file is negative", M);
3081: PetscCheck(N >= 0, PetscObjectComm((PetscObject)viewer), PETSC_ERR_FILE_UNEXPECTED, "Matrix column size (%" PetscInt_FMT ") in file is negative", N);
3082: PetscCheck(nz >= 0, PETSC_COMM_SELF, PETSC_ERR_FILE_UNEXPECTED, "Matrix stored in special format on disk, cannot load as MPIAIJ");
3084: /* set block sizes from the viewer's .info file */
3085: PetscCall(MatLoad_Binary_BlockSizes(mat, viewer));
3086: /* set global sizes if not set already */
3087: if (mat->rmap->N < 0) mat->rmap->N = M;
3088: if (mat->cmap->N < 0) mat->cmap->N = N;
3089: PetscCall(PetscLayoutSetUp(mat->rmap));
3090: PetscCall(PetscLayoutSetUp(mat->cmap));
3092: /* check if the matrix sizes are correct */
3093: PetscCall(MatGetSize(mat, &rows, &cols));
3094: 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);
3096: /* read in row lengths and build row indices */
3097: PetscCall(MatGetLocalSize(mat, &m, NULL));
3098: PetscCall(PetscMalloc1(m + 1, &rowidxs));
3099: PetscCall(PetscViewerBinaryReadAll(viewer, rowidxs + 1, m, PETSC_DECIDE, M, PETSC_INT));
3100: rowidxs[0] = 0;
3101: for (i = 0; i < m; i++) rowidxs[i + 1] += rowidxs[i];
3102: if (nz != PETSC_INT_MAX) {
3103: PetscCallMPI(MPIU_Allreduce(&rowidxs[m], &sum, 1, MPIU_INT, MPI_SUM, PetscObjectComm((PetscObject)viewer)));
3104: 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);
3105: }
3107: /* read in column indices and matrix values */
3108: PetscCall(PetscMalloc2(rowidxs[m], &colidxs, rowidxs[m], &matvals));
3109: PetscCall(PetscViewerBinaryReadAll(viewer, colidxs, rowidxs[m], PETSC_DETERMINE, PETSC_DETERMINE, PETSC_INT));
3110: PetscCall(PetscViewerBinaryReadAll(viewer, matvals, rowidxs[m], PETSC_DETERMINE, PETSC_DETERMINE, PETSC_SCALAR));
3111: /* store matrix indices and values */
3112: PetscCall(MatMPIAIJSetPreallocationCSR(mat, rowidxs, colidxs, matvals));
3113: PetscCall(PetscFree(rowidxs));
3114: PetscCall(PetscFree2(colidxs, matvals));
3115: PetscFunctionReturn(PETSC_SUCCESS);
3116: }
3118: /* Not scalable because of ISAllGather() unless getting all columns. */
3119: static PetscErrorCode ISGetSeqIS_Private(Mat mat, IS iscol, IS *isseq)
3120: {
3121: IS iscol_local;
3122: PetscBool isstride;
3123: PetscMPIInt gisstride = 0;
3125: PetscFunctionBegin;
3126: /* check if we are grabbing all columns*/
3127: PetscCall(PetscObjectTypeCompare((PetscObject)iscol, ISSTRIDE, &isstride));
3129: if (isstride) {
3130: PetscInt start, len, mstart, mlen;
3131: PetscCall(ISStrideGetInfo(iscol, &start, NULL));
3132: PetscCall(ISGetLocalSize(iscol, &len));
3133: PetscCall(MatGetOwnershipRangeColumn(mat, &mstart, &mlen));
3134: if (mstart == start && mlen - mstart == len) gisstride = 1;
3135: }
3137: PetscCallMPI(MPIU_Allreduce(MPI_IN_PLACE, &gisstride, 1, MPI_INT, MPI_MIN, PetscObjectComm((PetscObject)mat)));
3138: if (gisstride) {
3139: PetscInt N;
3140: PetscCall(MatGetSize(mat, NULL, &N));
3141: PetscCall(ISCreateStride(PETSC_COMM_SELF, N, 0, 1, &iscol_local));
3142: PetscCall(ISSetIdentity(iscol_local));
3143: PetscCall(PetscInfo(mat, "Optimizing for obtaining all columns of the matrix; skipping ISAllGather()\n"));
3144: } else {
3145: PetscInt cbs;
3146: PetscCall(ISGetBlockSize(iscol, &cbs));
3147: PetscCall(ISAllGather(iscol, &iscol_local));
3148: PetscCall(ISSetBlockSize(iscol_local, cbs));
3149: }
3151: *isseq = iscol_local;
3152: PetscFunctionReturn(PETSC_SUCCESS);
3153: }
3155: /*
3156: Used by MatCreateSubMatrix_MPIAIJ_SameRowColDist() to avoid ISAllGather() and global size of iscol_local
3157: (see MatCreateSubMatrix_MPIAIJ_nonscalable)
3159: Input Parameters:
3160: + mat - matrix
3161: . isrow - parallel row index set; its local indices are a subset of local columns of `mat`,
3162: i.e., mat->rstart <= isrow[i] < mat->rend
3163: - iscol - parallel column index set; its local indices are a subset of local columns of `mat`,
3164: i.e., mat->cstart <= iscol[i] < mat->cend
3166: Output Parameters:
3167: + isrow_d - sequential row index set for retrieving mat->A
3168: . iscol_d - sequential column index set for retrieving mat->A
3169: . iscol_o - sequential column index set for retrieving mat->B
3170: - garray - column map; garray[i] indicates global location of iscol_o[i] in `iscol`
3171: */
3172: static PetscErrorCode ISGetSeqIS_SameColDist_Private(Mat mat, IS isrow, IS iscol, IS *isrow_d, IS *iscol_d, IS *iscol_o, PetscInt *garray[])
3173: {
3174: const PetscInt *is_idx;
3175: PetscInt ncols, isstart, *idx, m, rstart, *cmap1, count;
3176: PetscInt *cmap, *lcmap;
3177: Mat_MPIAIJ *a = (Mat_MPIAIJ *)mat->data;
3178: Mat B = a->B;
3179: PetscInt i, n, cstart, cend, Bn = B->cmap->N;
3180: MPI_Comm comm;
3181: PetscSF Mvctx = a->Mvctx;
3183: PetscFunctionBegin;
3184: PetscCall(PetscObjectGetComm((PetscObject)mat, &comm));
3185: PetscCall(ISGetLocalSize(iscol, &ncols));
3187: /* (1) cmap gives the submatrix column of each local column of mat, or -1 if it is not in iscol */
3188: PetscCall(MatGetLocalSize(mat, NULL, &n));
3189: PetscCall(PetscMalloc2(n, &cmap, Bn, &lcmap));
3190: for (i = 0; i < n; i++) cmap[i] = -1;
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(PetscMalloc1(ncols, &idx));
3199: for (i = 0; i < ncols; i++) {
3200: cmap[is_idx[i] - cstart] = i + isstart; /* global index of iscol[i] */
3201: idx[i] = is_idx[i] - cstart; /* local index of iscol[i] */
3202: }
3203: PetscCall(ISRestoreIndices(iscol, &is_idx));
3205: /* Get iscol_d */
3206: PetscCall(ISCreateGeneral(PETSC_COMM_SELF, ncols, idx, PETSC_OWN_POINTER, iscol_d));
3207: PetscCall(ISGetBlockSize(iscol, &i));
3208: PetscCall(ISSetBlockSize(*iscol_d, i));
3210: /* Get isrow_d */
3211: PetscCall(ISGetLocalSize(isrow, &m));
3212: rstart = mat->rmap->rstart;
3213: PetscCall(PetscMalloc1(m, &idx));
3214: PetscCall(ISGetIndices(isrow, &is_idx));
3215: for (i = 0; i < m; i++) idx[i] = is_idx[i] - rstart;
3216: PetscCall(ISRestoreIndices(isrow, &is_idx));
3218: PetscCall(ISCreateGeneral(PETSC_COMM_SELF, m, idx, PETSC_OWN_POINTER, isrow_d));
3219: PetscCall(ISGetBlockSize(isrow, &i));
3220: PetscCall(ISSetBlockSize(*isrow_d, i));
3222: /* (2) Broadcast cmap through aij->Mvctx to get lcmap, its values for the columns of B (see MatMult_MPIAIJ()) */
3223: PetscCall(PetscSFBcastBegin(Mvctx, MPIU_INT, cmap, lcmap, MPI_REPLACE));
3224: PetscCall(PetscSFBcastEnd(Mvctx, MPIU_INT, cmap, lcmap, MPI_REPLACE));
3226: /* (3) create sequential iscol_o (a subset of iscol) and isgarray */
3227: /* off-process column indices */
3228: count = 0;
3229: PetscCall(PetscMalloc1(Bn, &idx));
3230: PetscCall(PetscMalloc1(Bn, &cmap1));
3232: for (i = 0; i < Bn; i++) {
3233: if (lcmap[i] > -1) {
3234: idx[count] = i; /* local column index in off-diagonal part B */
3235: cmap1[count] = lcmap[i]; /* column index in submat */
3236: count++;
3237: }
3238: }
3240: PetscCall(ISCreateGeneral(PETSC_COMM_SELF, count, idx, PETSC_COPY_VALUES, iscol_o));
3241: /* cannot ensure iscol_o has same blocksize as iscol! */
3243: PetscCall(PetscFree(idx));
3244: *garray = cmap1;
3246: PetscCall(PetscFree2(cmap, lcmap));
3247: PetscFunctionReturn(PETSC_SUCCESS);
3248: }
3250: /* isrow and iscol have same processor distribution as mat, output *submat is a submatrix of local mat */
3251: PetscErrorCode MatCreateSubMatrix_MPIAIJ_SameRowColDist(Mat mat, IS isrow, IS iscol, MatReuse call, Mat *submat)
3252: {
3253: Mat_MPIAIJ *a = (Mat_MPIAIJ *)mat->data, *asub;
3254: Mat M = NULL;
3255: MPI_Comm comm;
3256: IS iscol_d, isrow_d, iscol_o;
3257: Mat Asub = NULL, Bsub = NULL;
3258: PetscInt n, count, M_size, N_size;
3260: PetscFunctionBegin;
3261: PetscCall(PetscObjectGetComm((PetscObject)mat, &comm));
3263: if (call == MAT_REUSE_MATRIX) {
3264: /* Retrieve isrow_d, iscol_d and iscol_o from submat */
3265: PetscCall(PetscObjectQuery((PetscObject)*submat, "isrow_d", (PetscObject *)&isrow_d));
3266: PetscCheck(isrow_d, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "isrow_d passed in was not used before, cannot reuse");
3268: PetscCall(PetscObjectQuery((PetscObject)*submat, "iscol_d", (PetscObject *)&iscol_d));
3269: PetscCheck(iscol_d, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "iscol_d passed in was not used before, cannot reuse");
3271: PetscCall(PetscObjectQuery((PetscObject)*submat, "iscol_o", (PetscObject *)&iscol_o));
3272: PetscCheck(iscol_o, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "iscol_o passed in was not used before, cannot reuse");
3274: /* Update diagonal and off-diagonal portions of submat */
3275: asub = (Mat_MPIAIJ *)(*submat)->data;
3276: PetscCall(MatCreateSubMatrix_SeqAIJ(a->A, isrow_d, iscol_d, PETSC_DECIDE, MAT_REUSE_MATRIX, &asub->A));
3277: PetscCall(ISGetLocalSize(iscol_o, &n));
3278: if (n) PetscCall(MatCreateSubMatrix_SeqAIJ(a->B, isrow_d, iscol_o, PETSC_DECIDE, MAT_REUSE_MATRIX, &asub->B));
3279: PetscCall(MatAssemblyBegin(*submat, MAT_FINAL_ASSEMBLY));
3280: PetscCall(MatAssemblyEnd(*submat, MAT_FINAL_ASSEMBLY));
3282: } else { /* call == MAT_INITIAL_MATRIX) */
3283: PetscInt *garray = NULL, *garray_compact;
3284: PetscInt BsubN;
3286: /* Create isrow_d, iscol_d, iscol_o and isgarray (replace isgarray with array?) */
3287: PetscCall(ISGetSeqIS_SameColDist_Private(mat, isrow, iscol, &isrow_d, &iscol_d, &iscol_o, &garray));
3289: /* Create local submatrices Asub and Bsub */
3290: PetscCall(MatCreateSubMatrix_SeqAIJ(a->A, isrow_d, iscol_d, PETSC_DECIDE, MAT_INITIAL_MATRIX, &Asub));
3291: PetscCall(MatCreateSubMatrix_SeqAIJ(a->B, isrow_d, iscol_o, PETSC_DECIDE, MAT_INITIAL_MATRIX, &Bsub));
3293: // Compact garray so its not of size Bn
3294: PetscCall(ISGetSize(iscol_o, &count));
3295: PetscCall(PetscMalloc1(count, &garray_compact));
3296: PetscCall(PetscArraycpy(garray_compact, garray, count));
3298: /* Create submatrix M */
3299: PetscCall(ISGetSize(isrow, &M_size));
3300: PetscCall(ISGetSize(iscol, &N_size));
3301: PetscCall(MatCreateMPIAIJWithSeqAIJ(comm, M_size, N_size, Asub, Bsub, garray_compact, &M));
3303: /* If Bsub has empty columns, compress iscol_o such that it will retrieve condensed Bsub from a->B during reuse */
3304: asub = (Mat_MPIAIJ *)M->data;
3306: PetscCall(ISGetLocalSize(iscol_o, &BsubN));
3307: n = asub->B->cmap->N;
3308: if (BsubN > n) {
3309: /* This case can be tested using ~petsc/src/tao/bound/tutorials/runplate2_3 */
3310: const PetscInt *idx;
3311: PetscInt i, j, *idx_new, *subgarray = asub->garray;
3312: PetscCall(PetscInfo(M, "submatrix Bn %" PetscInt_FMT " != BsubN %" PetscInt_FMT ", update iscol_o\n", n, BsubN));
3314: PetscCall(PetscMalloc1(n, &idx_new));
3315: j = 0;
3316: PetscCall(ISGetIndices(iscol_o, &idx));
3317: for (i = 0; i < n; i++) {
3318: if (j >= BsubN) break;
3319: while (subgarray[i] > garray[j]) j++;
3321: 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]);
3322: idx_new[i] = idx[j++];
3323: }
3324: PetscCall(ISRestoreIndices(iscol_o, &idx));
3326: PetscCall(ISDestroy(&iscol_o));
3327: PetscCall(ISCreateGeneral(PETSC_COMM_SELF, n, idx_new, PETSC_OWN_POINTER, &iscol_o));
3329: } 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);
3331: PetscCall(PetscFree(garray));
3332: *submat = M;
3334: /* Save isrow_d, iscol_d and iscol_o used in processor for next request */
3335: PetscCall(PetscObjectCompose((PetscObject)M, "isrow_d", (PetscObject)isrow_d));
3336: PetscCall(ISDestroy(&isrow_d));
3338: PetscCall(PetscObjectCompose((PetscObject)M, "iscol_d", (PetscObject)iscol_d));
3339: PetscCall(ISDestroy(&iscol_d));
3341: PetscCall(PetscObjectCompose((PetscObject)M, "iscol_o", (PetscObject)iscol_o));
3342: PetscCall(ISDestroy(&iscol_o));
3343: }
3344: PetscFunctionReturn(PETSC_SUCCESS);
3345: }
3347: PetscErrorCode MatCreateSubMatrix_MPIAIJ(Mat mat, IS isrow, IS iscol, MatReuse call, Mat *newmat)
3348: {
3349: IS iscol_local = NULL, isrow_d;
3350: PetscInt csize;
3351: PetscInt n, i, j, start, end;
3352: PetscBool sameRowDist = PETSC_FALSE, tsameDist[2];
3353: MPI_Comm comm;
3355: PetscFunctionBegin;
3356: /* If isrow has same processor distribution as mat,
3357: call MatCreateSubMatrix_MPIAIJ_SameRowDist() to avoid using a hash table with global size of iscol */
3358: if (call == MAT_REUSE_MATRIX) {
3359: PetscCall(PetscObjectQuery((PetscObject)*newmat, "isrow_d", (PetscObject *)&isrow_d));
3360: if (isrow_d) {
3361: sameRowDist = PETSC_TRUE;
3362: tsameDist[1] = PETSC_TRUE; /* sameColDist */
3363: } else {
3364: PetscCall(PetscObjectQuery((PetscObject)*newmat, "SubIScol", (PetscObject *)&iscol_local));
3365: if (iscol_local) {
3366: sameRowDist = PETSC_TRUE;
3367: tsameDist[1] = PETSC_FALSE; /* !sameColDist */
3368: }
3369: }
3370: } else {
3371: /* Check if isrow has same processor distribution as mat */
3372: tsameDist[0] = PETSC_FALSE;
3373: PetscCall(ISGetLocalSize(isrow, &n));
3374: if (!n) {
3375: tsameDist[0] = PETSC_TRUE;
3376: } else {
3377: PetscCall(ISGetMinMax(isrow, &i, &j));
3378: PetscCall(MatGetOwnershipRange(mat, &start, &end));
3379: if (i >= start && j < end) tsameDist[0] = PETSC_TRUE;
3380: }
3382: /* Check if iscol has same processor distribution as mat */
3383: tsameDist[1] = PETSC_FALSE;
3384: PetscCall(ISGetLocalSize(iscol, &n));
3385: if (!n) {
3386: tsameDist[1] = PETSC_TRUE;
3387: } else {
3388: PetscCall(ISGetMinMax(iscol, &i, &j));
3389: PetscCall(MatGetOwnershipRangeColumn(mat, &start, &end));
3390: if (i >= start && j < end) tsameDist[1] = PETSC_TRUE;
3391: }
3393: PetscCall(PetscObjectGetComm((PetscObject)mat, &comm));
3394: PetscCallMPI(MPIU_Allreduce(MPI_IN_PLACE, tsameDist, 2, MPI_C_BOOL, MPI_LAND, comm));
3395: sameRowDist = tsameDist[0];
3396: }
3398: if (sameRowDist) {
3399: if (tsameDist[1]) { /* sameRowDist & sameColDist */
3400: /* isrow and iscol have same processor distribution as mat */
3401: PetscCall(MatCreateSubMatrix_MPIAIJ_SameRowColDist(mat, isrow, iscol, call, newmat));
3402: PetscFunctionReturn(PETSC_SUCCESS);
3403: } else { /* sameRowDist */
3404: /* isrow has same processor distribution as mat */
3405: if (call == MAT_INITIAL_MATRIX) {
3406: PetscBool sorted;
3407: PetscCall(ISGetSeqIS_Private(mat, iscol, &iscol_local));
3408: PetscCall(ISGetLocalSize(iscol_local, &n)); /* local size of iscol_local = global columns of newmat */
3409: PetscCall(ISGetSize(iscol, &i));
3410: PetscCheck(n == i, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "n %" PetscInt_FMT " != size of iscol %" PetscInt_FMT, n, i);
3412: PetscCall(ISSorted(iscol_local, &sorted));
3413: if (sorted) {
3414: /* MatCreateSubMatrix_MPIAIJ_SameRowDist() requires iscol_local be sorted; it can have duplicate indices */
3415: PetscCall(MatCreateSubMatrix_MPIAIJ_SameRowDist(mat, isrow, iscol, iscol_local, MAT_INITIAL_MATRIX, newmat));
3416: PetscFunctionReturn(PETSC_SUCCESS);
3417: }
3418: } else { /* call == MAT_REUSE_MATRIX */
3419: IS iscol_sub;
3420: PetscCall(PetscObjectQuery((PetscObject)*newmat, "SubIScol", (PetscObject *)&iscol_sub));
3421: if (iscol_sub) {
3422: PetscCall(MatCreateSubMatrix_MPIAIJ_SameRowDist(mat, isrow, iscol, NULL, call, newmat));
3423: PetscFunctionReturn(PETSC_SUCCESS);
3424: }
3425: }
3426: }
3427: }
3429: /* General case: iscol -> iscol_local which has global size of iscol */
3430: if (call == MAT_REUSE_MATRIX) {
3431: PetscCall(PetscObjectQuery((PetscObject)*newmat, "ISAllGather", (PetscObject *)&iscol_local));
3432: PetscCheck(iscol_local, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Submatrix passed in was not used before, cannot reuse");
3433: } else {
3434: if (!iscol_local) PetscCall(ISGetSeqIS_Private(mat, iscol, &iscol_local));
3435: }
3437: PetscCall(ISGetLocalSize(iscol, &csize));
3438: PetscCall(MatCreateSubMatrix_MPIAIJ_nonscalable(mat, isrow, iscol_local, csize, call, newmat));
3440: if (call == MAT_INITIAL_MATRIX) {
3441: PetscCall(PetscObjectCompose((PetscObject)*newmat, "ISAllGather", (PetscObject)iscol_local));
3442: PetscCall(ISDestroy(&iscol_local));
3443: }
3444: PetscFunctionReturn(PETSC_SUCCESS);
3445: }
3447: /*@
3448: MatCreateMPIAIJWithSeqAIJ - creates a `MATMPIAIJ` matrix using `MATSEQAIJ` matrices that contain the "diagonal"
3449: and "off-diagonal" part of the matrix in CSR format.
3451: Collective
3453: Input Parameters:
3454: + comm - MPI communicator
3455: . M - the global row size
3456: . N - the global column size
3457: . A - "diagonal" portion of matrix
3458: . 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
3459: - 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.
3461: Output Parameter:
3462: . mat - the matrix, with input `A` as its local diagonal matrix
3464: Level: advanced
3466: Notes:
3467: See `MatCreateAIJ()` for the definition of "diagonal" and "off-diagonal" portion of the matrix.
3469: `A` and `B` becomes part of output mat. The user cannot use `A` and `B` anymore.
3471: 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
3472: `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
3473: `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`
3474: yourself, see algorithms in the private function `MatSetUpMultiply_MPIAIJ()`.
3476: 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.
3478: .seealso: [](ch_matrices), `Mat`, `MATMPIAIJ`, `MATSEQAIJ`, `MatCreateMPIAIJWithSplitArrays()`
3479: @*/
3480: PetscErrorCode MatCreateMPIAIJWithSeqAIJ(MPI_Comm comm, PetscInt M, PetscInt N, Mat A, Mat B, PetscInt *garray, Mat *mat)
3481: {
3482: PetscInt m, n;
3483: MatType mpi_mat_type;
3484: Mat_MPIAIJ *mpiaij;
3485: Mat C;
3487: PetscFunctionBegin;
3488: PetscCall(MatCreate(comm, &C));
3489: PetscCall(MatGetSize(A, &m, &n));
3490: PetscCheck(m == B->rmap->N, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Am %" PetscInt_FMT " != Bm %" PetscInt_FMT, m, B->rmap->N);
3491: 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);
3493: PetscCheck(A->structure_only == B->structure_only, PETSC_COMM_SELF, PETSC_ERR_ARG_INCOMP, "Diagonal and off-diagonal matrices must have the same MAT_STRUCTURE_ONLY option value");
3494: PetscCall(MatSetSizes(C, m, n, M, N));
3495: /* Determine the type of MPI matrix that should be created from the type of matrix A, which holds the "diagonal" portion. */
3496: PetscCall(MatGetMPIMatType_Private(A, &mpi_mat_type));
3497: PetscCall(MatSetType(C, mpi_mat_type));
3498: if (!garray) {
3499: const PetscScalar *ba;
3501: B->nonzerostate++;
3502: PetscCall(MatSeqAIJGetArrayRead(B, &ba)); /* Since we will destroy B's device copy, we need to make sure the host copy is up to date */
3503: PetscCall(MatSeqAIJRestoreArrayRead(B, &ba));
3504: }
3506: PetscCall(MatSetBlockSizes(C, A->rmap->bs, A->cmap->bs));
3507: PetscCall(PetscLayoutSetUp(C->rmap));
3508: PetscCall(PetscLayoutSetUp(C->cmap));
3510: mpiaij = (Mat_MPIAIJ *)C->data;
3511: mpiaij->A = A;
3512: mpiaij->B = B;
3513: mpiaij->garray = garray;
3514: C->preallocated = PETSC_TRUE;
3515: C->nooffprocentries = PETSC_TRUE; /* See MatAssemblyBegin_MPIAIJ. In effect, making MatAssemblyBegin a nop */
3517: PetscCall(MatSetOption(C, MAT_STRUCTURE_ONLY, A->structure_only));
3518: PetscCall(MatSetOption(C, MAT_NO_OFF_PROC_ENTRIES, PETSC_TRUE));
3519: PetscCall(MatAssemblyBegin(C, MAT_FINAL_ASSEMBLY));
3520: /* MatAssemblyEnd is critical here. It sets mat->offloadmask according to A and B's, and
3521: also gets mpiaij->B compacted (if garray is NULL), with its col ids and size reduced
3522: */
3523: PetscCall(MatAssemblyEnd(C, MAT_FINAL_ASSEMBLY));
3524: PetscCall(MatSetOption(C, MAT_NO_OFF_PROC_ENTRIES, PETSC_FALSE));
3525: PetscCall(MatSetOption(C, MAT_NEW_NONZERO_LOCATION_ERR, PETSC_TRUE));
3526: *mat = C;
3527: PetscFunctionReturn(PETSC_SUCCESS);
3528: }
3530: extern PetscErrorCode MatCreateSubMatrices_MPIAIJ_SingleIS_Local(Mat, PetscInt, const IS[], const IS[], MatReuse, PetscBool, Mat *);
3532: PetscErrorCode MatCreateSubMatrix_MPIAIJ_SameRowDist(Mat mat, IS isrow, IS iscol, IS iscol_local, MatReuse call, Mat *newmat)
3533: {
3534: PetscInt i, m, n, rstart, row, rend, nz, j, bs, cbs;
3535: PetscInt *ii, *jj, nlocal, *dlens, *olens, dlen, olen, jend, mglobal;
3536: Mat_MPIAIJ *a = (Mat_MPIAIJ *)mat->data;
3537: Mat M, Msub, B = a->B;
3538: MatScalar *aa;
3539: Mat_SeqAIJ *aij;
3540: PetscInt *garray = a->garray, *colsub, Ncols;
3541: PetscInt count, Bn = B->cmap->N, cstart = mat->cmap->rstart, cend = mat->cmap->rend;
3542: IS iscol_sub, iscmap;
3543: const PetscInt *is_idx, *cmap;
3544: PetscBool allcolumns = PETSC_FALSE, nooffprocentries;
3545: MPI_Comm comm;
3547: PetscFunctionBegin;
3548: PetscCall(PetscObjectGetComm((PetscObject)mat, &comm));
3549: if (call == MAT_REUSE_MATRIX) {
3550: PetscCall(PetscObjectQuery((PetscObject)*newmat, "SubIScol", (PetscObject *)&iscol_sub));
3551: PetscCheck(iscol_sub, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "SubIScol passed in was not used before, cannot reuse");
3552: PetscCall(ISGetLocalSize(iscol_sub, &count));
3554: PetscCall(PetscObjectQuery((PetscObject)*newmat, "Subcmap", (PetscObject *)&iscmap));
3555: PetscCheck(iscmap, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Subcmap passed in was not used before, cannot reuse");
3557: PetscCall(PetscObjectQuery((PetscObject)*newmat, "SubMatrix", (PetscObject *)&Msub));
3558: PetscCheck(Msub, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Submatrix passed in was not used before, cannot reuse");
3560: PetscCall(MatCreateSubMatrices_MPIAIJ_SingleIS_Local(mat, 1, &isrow, &iscol_sub, MAT_REUSE_MATRIX, PETSC_FALSE, &Msub));
3562: } else { /* call == MAT_INITIAL_MATRIX) */
3563: PetscBool flg;
3565: PetscCall(ISGetLocalSize(iscol, &n));
3566: PetscCall(ISGetSize(iscol, &Ncols));
3568: /* (1) iscol -> nonscalable iscol_local */
3569: /* Check for special case: each processor gets entire matrix columns */
3570: PetscCall(ISIdentity(iscol_local, &flg));
3571: if (flg && n == mat->cmap->N) allcolumns = PETSC_TRUE;
3572: PetscCallMPI(MPIU_Allreduce(MPI_IN_PLACE, &allcolumns, 1, MPI_C_BOOL, MPI_LAND, PetscObjectComm((PetscObject)mat)));
3573: if (allcolumns) {
3574: iscol_sub = iscol_local;
3575: PetscCall(PetscObjectReference((PetscObject)iscol_local));
3576: PetscCall(ISCreateStride(PETSC_COMM_SELF, n, 0, 1, &iscmap));
3578: } else {
3579: /* (2) iscol_local -> iscol_sub and iscmap. Implementation below requires iscol_local be sorted, it can have duplicate indices */
3580: PetscInt *idx, *cmap1, k;
3581: PetscCall(PetscMalloc1(Ncols, &idx));
3582: PetscCall(PetscMalloc1(Ncols, &cmap1));
3583: PetscCall(ISGetIndices(iscol_local, &is_idx));
3584: count = 0;
3585: k = 0;
3586: for (i = 0; i < Ncols; i++) {
3587: j = is_idx[i];
3588: if (j >= cstart && j < cend) {
3589: /* diagonal part of mat */
3590: idx[count] = j;
3591: cmap1[count++] = i; /* column index in submat */
3592: } else if (Bn) {
3593: /* off-diagonal part of mat */
3594: if (j == garray[k]) {
3595: idx[count] = j;
3596: cmap1[count++] = i; /* column index in submat */
3597: } else if (j > garray[k]) {
3598: while (j > garray[k] && k < Bn - 1) k++;
3599: if (j == garray[k]) {
3600: idx[count] = j;
3601: cmap1[count++] = i; /* column index in submat */
3602: }
3603: }
3604: }
3605: }
3606: PetscCall(ISRestoreIndices(iscol_local, &is_idx));
3608: PetscCall(ISCreateGeneral(PETSC_COMM_SELF, count, idx, PETSC_OWN_POINTER, &iscol_sub));
3609: PetscCall(ISGetBlockSize(iscol, &cbs));
3610: PetscCall(ISSetBlockSize(iscol_sub, cbs));
3612: PetscCall(ISCreateGeneral(PetscObjectComm((PetscObject)iscol_local), count, cmap1, PETSC_OWN_POINTER, &iscmap));
3613: }
3615: /* (3) Create sequential Msub */
3616: PetscCall(MatCreateSubMatrices_MPIAIJ_SingleIS_Local(mat, 1, &isrow, &iscol_sub, MAT_INITIAL_MATRIX, allcolumns, &Msub));
3617: }
3619: PetscCall(ISGetLocalSize(iscol_sub, &count));
3620: aij = (Mat_SeqAIJ *)Msub->data;
3621: ii = aij->i;
3622: PetscCall(ISGetIndices(iscmap, &cmap));
3624: /*
3625: m - number of local rows
3626: Ncols - number of columns (same on all processors)
3627: rstart - first row in new global matrix generated
3628: */
3629: PetscCall(MatGetSize(Msub, &m, NULL));
3631: if (call == MAT_INITIAL_MATRIX) {
3632: /* (4) Create parallel newmat */
3633: PetscMPIInt rank, size;
3634: PetscInt csize;
3636: PetscCallMPI(MPI_Comm_size(comm, &size));
3637: PetscCallMPI(MPI_Comm_rank(comm, &rank));
3639: /*
3640: Determine the number of non-zeros in the diagonal and off-diagonal
3641: portions of the matrix in order to do correct preallocation
3642: */
3644: /* first get start and end of "diagonal" columns */
3645: PetscCall(ISGetLocalSize(iscol, &csize));
3646: if (csize == PETSC_DECIDE) {
3647: PetscCall(ISGetSize(isrow, &mglobal));
3648: if (mglobal == Ncols) { /* square matrix */
3649: nlocal = m;
3650: } else {
3651: nlocal = Ncols / size + ((Ncols % size) > rank);
3652: }
3653: } else {
3654: nlocal = csize;
3655: }
3656: PetscCallMPI(MPI_Scan(&nlocal, &rend, 1, MPIU_INT, MPI_SUM, comm));
3657: rstart = rend - nlocal;
3658: 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);
3660: /* next, compute all the lengths */
3661: jj = aij->j;
3662: PetscCall(PetscMalloc1(2 * m + 1, &dlens));
3663: olens = dlens + m;
3664: for (i = 0; i < m; i++) {
3665: jend = ii[i + 1] - ii[i];
3666: olen = 0;
3667: dlen = 0;
3668: for (j = 0; j < jend; j++) {
3669: if (cmap[*jj] < rstart || cmap[*jj] >= rend) olen++;
3670: else dlen++;
3671: jj++;
3672: }
3673: olens[i] = olen;
3674: dlens[i] = dlen;
3675: }
3677: PetscCall(ISGetBlockSize(isrow, &bs));
3678: PetscCall(ISGetBlockSize(iscol, &cbs));
3680: PetscCall(MatCreate(comm, &M));
3681: PetscCall(MatSetSizes(M, m, nlocal, PETSC_DECIDE, Ncols));
3682: PetscCall(MatSetBlockSizes(M, bs, cbs));
3683: PetscCall(MatSetType(M, ((PetscObject)mat)->type_name));
3684: PetscCall(MatSetOption(M, MAT_STRUCTURE_ONLY, mat->structure_only));
3685: PetscCall(MatMPIAIJSetPreallocation(M, 0, dlens, 0, olens));
3686: PetscCall(PetscFree(dlens));
3688: } else { /* call == MAT_REUSE_MATRIX */
3689: M = *newmat;
3690: PetscCall(MatGetLocalSize(M, &i, NULL));
3691: PetscCheck(i == m, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Previous matrix must be same size/layout as request");
3692: PetscCall(MatZeroEntries(M));
3693: /*
3694: The next two lines are needed so we may call MatSetValues_MPIAIJ() below directly,
3695: rather than the slower MatSetValues().
3696: */
3697: M->was_assembled = PETSC_TRUE;
3698: M->assembled = PETSC_FALSE;
3699: }
3701: /* (5) Set values of Msub to *newmat */
3702: PetscCall(PetscMalloc1(count, &colsub));
3703: PetscCall(MatGetOwnershipRange(M, &rstart, NULL));
3705: jj = aij->j;
3706: PetscCall(MatSeqAIJGetArrayRead(Msub, (const PetscScalar **)&aa));
3707: for (i = 0; i < m; i++) {
3708: row = rstart + i;
3709: nz = ii[i + 1] - ii[i];
3710: for (j = 0; j < nz; j++) colsub[j] = cmap[jj[j]];
3711: PetscCall(MatSetValues_MPIAIJ(M, 1, &row, nz, colsub, aa, INSERT_VALUES));
3712: jj += nz;
3713: if (!mat->structure_only) aa += nz;
3714: }
3715: PetscCall(MatSeqAIJRestoreArrayRead(Msub, (const PetscScalar **)&aa));
3716: PetscCall(ISRestoreIndices(iscmap, &cmap));
3718: nooffprocentries = M->nooffprocentries;
3719: M->nooffprocentries = PETSC_TRUE;
3720: PetscCall(MatAssemblyBegin(M, MAT_FINAL_ASSEMBLY));
3721: PetscCall(MatAssemblyEnd(M, MAT_FINAL_ASSEMBLY));
3722: M->nooffprocentries = nooffprocentries;
3724: PetscCall(PetscFree(colsub));
3726: /* save Msub, iscol_sub and iscmap used in processor for next request */
3727: if (call == MAT_INITIAL_MATRIX) {
3728: *newmat = M;
3729: PetscCall(PetscObjectCompose((PetscObject)*newmat, "SubMatrix", (PetscObject)Msub));
3730: PetscCall(MatDestroy(&Msub));
3732: PetscCall(PetscObjectCompose((PetscObject)*newmat, "SubIScol", (PetscObject)iscol_sub));
3733: PetscCall(ISDestroy(&iscol_sub));
3735: PetscCall(PetscObjectCompose((PetscObject)*newmat, "Subcmap", (PetscObject)iscmap));
3736: PetscCall(ISDestroy(&iscmap));
3738: if (iscol_local) {
3739: PetscCall(PetscObjectCompose((PetscObject)*newmat, "ISAllGather", (PetscObject)iscol_local));
3740: PetscCall(ISDestroy(&iscol_local));
3741: }
3742: }
3743: PetscFunctionReturn(PETSC_SUCCESS);
3744: }
3746: /*
3747: Not great since it makes two copies of the submatrix, first an SeqAIJ
3748: in local and then by concatenating the local matrices the end result.
3749: Writing it directly would be much like MatCreateSubMatrices_MPIAIJ()
3751: This requires a sequential iscol with all indices.
3752: */
3753: PetscErrorCode MatCreateSubMatrix_MPIAIJ_nonscalable(Mat mat, IS isrow, IS iscol, PetscInt csize, MatReuse call, Mat *newmat)
3754: {
3755: PetscMPIInt rank, size;
3756: PetscInt i, m, n, rstart, row, rend, nz, *cwork, j, bs, cbs;
3757: PetscInt *ii, *jj, nlocal, *dlens, *olens, dlen, olen, jend, mglobal;
3758: Mat M, Mreuse;
3759: MatScalar *aa, *vwork;
3760: MPI_Comm comm;
3761: Mat_SeqAIJ *aij;
3762: PetscBool colflag, allcolumns = PETSC_FALSE, nooffprocentries;
3764: PetscFunctionBegin;
3765: PetscCall(PetscObjectGetComm((PetscObject)mat, &comm));
3766: PetscCallMPI(MPI_Comm_rank(comm, &rank));
3767: PetscCallMPI(MPI_Comm_size(comm, &size));
3769: /* Check for special case: each processor gets entire matrix columns */
3770: PetscCall(ISIdentity(iscol, &colflag));
3771: PetscCall(ISGetLocalSize(iscol, &n));
3772: if (colflag && n == mat->cmap->N) allcolumns = PETSC_TRUE;
3773: PetscCallMPI(MPIU_Allreduce(MPI_IN_PLACE, &allcolumns, 1, MPI_C_BOOL, MPI_LAND, PetscObjectComm((PetscObject)mat)));
3775: if (call == MAT_REUSE_MATRIX) {
3776: PetscCall(PetscObjectQuery((PetscObject)*newmat, "SubMatrix", (PetscObject *)&Mreuse));
3777: PetscCheck(Mreuse, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Submatrix passed in was not used before, cannot reuse");
3778: PetscCall(MatCreateSubMatrices_MPIAIJ_SingleIS_Local(mat, 1, &isrow, &iscol, MAT_REUSE_MATRIX, allcolumns, &Mreuse));
3779: } else {
3780: PetscCall(MatCreateSubMatrices_MPIAIJ_SingleIS_Local(mat, 1, &isrow, &iscol, MAT_INITIAL_MATRIX, allcolumns, &Mreuse));
3781: }
3783: /*
3784: m - number of local rows
3785: n - number of columns (same on all processors)
3786: rstart - first row in new global matrix generated
3787: */
3788: PetscCall(MatGetSize(Mreuse, &m, &n));
3789: PetscCall(MatGetBlockSizes(Mreuse, &bs, &cbs));
3790: if (call == MAT_INITIAL_MATRIX) {
3791: aij = (Mat_SeqAIJ *)Mreuse->data;
3792: ii = aij->i;
3793: jj = aij->j;
3795: /*
3796: Determine the number of non-zeros in the diagonal and off-diagonal
3797: portions of the matrix in order to do correct preallocation
3798: */
3800: /* first get start and end of "diagonal" columns */
3801: if (csize == PETSC_DECIDE) {
3802: PetscCall(ISGetSize(isrow, &mglobal));
3803: if (mglobal == n) { /* square matrix */
3804: nlocal = m;
3805: } else {
3806: nlocal = n / size + ((n % size) > rank);
3807: }
3808: } else {
3809: nlocal = csize;
3810: }
3811: PetscCallMPI(MPI_Scan(&nlocal, &rend, 1, MPIU_INT, MPI_SUM, comm));
3812: rstart = rend - nlocal;
3813: 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);
3815: /* next, compute all the lengths */
3816: PetscCall(PetscMalloc1(2 * m + 1, &dlens));
3817: olens = dlens + m;
3818: for (i = 0; i < m; i++) {
3819: jend = ii[i + 1] - ii[i];
3820: olen = 0;
3821: dlen = 0;
3822: for (j = 0; j < jend; j++) {
3823: if (*jj < rstart || *jj >= rend) olen++;
3824: else dlen++;
3825: jj++;
3826: }
3827: olens[i] = olen;
3828: dlens[i] = dlen;
3829: }
3830: PetscCall(MatCreate(comm, &M));
3831: PetscCall(MatSetSizes(M, m, nlocal, PETSC_DECIDE, n));
3832: PetscCall(MatSetBlockSizes(M, bs, cbs));
3833: PetscCall(MatSetType(M, ((PetscObject)mat)->type_name));
3834: PetscCall(MatSetOption(M, MAT_STRUCTURE_ONLY, mat->structure_only));
3835: PetscCall(MatMPIAIJSetPreallocation(M, 0, dlens, 0, olens));
3836: PetscCall(PetscFree(dlens));
3837: } else {
3838: PetscInt ml, nl;
3840: M = *newmat;
3841: PetscCall(MatGetLocalSize(M, &ml, &nl));
3842: PetscCheck(ml == m, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Previous matrix must be same size/layout as request");
3843: PetscCall(MatZeroEntries(M));
3844: /*
3845: The next two lines are needed so we may call MatSetValues_MPIAIJ() below directly,
3846: rather than the slower MatSetValues().
3847: */
3848: M->was_assembled = PETSC_TRUE;
3849: M->assembled = PETSC_FALSE;
3850: }
3851: PetscCall(MatGetOwnershipRange(M, &rstart, &rend));
3852: aij = (Mat_SeqAIJ *)Mreuse->data;
3853: ii = aij->i;
3854: jj = aij->j;
3856: /* trigger copy to CPU if needed */
3857: PetscCall(MatSeqAIJGetArrayRead(Mreuse, (const PetscScalar **)&aa));
3858: for (i = 0; i < m; i++) {
3859: row = rstart + i;
3860: nz = ii[i + 1] - ii[i];
3861: cwork = jj;
3862: jj = PetscSafePointerPlusOffset(jj, nz);
3863: vwork = aa;
3864: aa = PetscSafePointerPlusOffset(aa, nz);
3865: PetscCall(MatSetValues_MPIAIJ(M, 1, &row, nz, cwork, vwork, INSERT_VALUES));
3866: }
3867: PetscCall(MatSeqAIJRestoreArrayRead(Mreuse, (const PetscScalar **)&aa));
3869: nooffprocentries = M->nooffprocentries;
3870: M->nooffprocentries = PETSC_TRUE;
3871: PetscCall(MatAssemblyBegin(M, MAT_FINAL_ASSEMBLY));
3872: PetscCall(MatAssemblyEnd(M, MAT_FINAL_ASSEMBLY));
3873: M->nooffprocentries = nooffprocentries;
3874: *newmat = M;
3876: /* save submatrix used in processor for next request */
3877: if (call == MAT_INITIAL_MATRIX) {
3878: PetscCall(PetscObjectCompose((PetscObject)M, "SubMatrix", (PetscObject)Mreuse));
3879: PetscCall(MatDestroy(&Mreuse));
3880: }
3881: PetscFunctionReturn(PETSC_SUCCESS);
3882: }
3884: static PetscErrorCode MatMPIAIJSetPreallocationCSR_MPIAIJ(Mat B, const PetscInt Ii[], const PetscInt J[], const PetscScalar v[])
3885: {
3886: PetscInt m, cstart, cend, j, nnz, i, d, *ld;
3887: PetscInt *d_nnz, *o_nnz, nnz_max = 0, rstart, ii, irstart;
3888: const PetscInt *JJ;
3889: PetscBool nooffprocentries;
3890: Mat_MPIAIJ *Aij = (Mat_MPIAIJ *)B->data;
3892: PetscFunctionBegin;
3893: PetscCall(PetscLayoutSetUp(B->rmap));
3894: PetscCall(PetscLayoutSetUp(B->cmap));
3895: m = B->rmap->n;
3896: cstart = B->cmap->rstart;
3897: cend = B->cmap->rend;
3898: rstart = B->rmap->rstart;
3899: irstart = Ii[0];
3901: PetscCall(PetscCalloc2(m, &d_nnz, m, &o_nnz));
3903: if (PetscDefined(USE_DEBUG)) {
3904: for (i = 0; i < m; i++) {
3905: nnz = Ii[i + 1] - Ii[i];
3906: JJ = PetscSafePointerPlusOffset(J, Ii[i] - irstart);
3907: PetscCheck(nnz >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Local row %" PetscInt_FMT " has a negative %" PetscInt_FMT " number of columns", i, nnz);
3908: 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]);
3909: 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);
3910: }
3911: }
3913: for (i = 0; i < m; i++) {
3914: nnz = Ii[i + 1] - Ii[i];
3915: JJ = PetscSafePointerPlusOffset(J, Ii[i] - irstart);
3916: nnz_max = PetscMax(nnz_max, nnz);
3917: d = 0;
3918: for (j = 0; j < nnz; j++) {
3919: if (cstart <= JJ[j] && JJ[j] < cend) d++;
3920: }
3921: d_nnz[i] = d;
3922: o_nnz[i] = nnz - d;
3923: }
3924: PetscCall(MatMPIAIJSetPreallocation(B, 0, d_nnz, 0, o_nnz));
3925: PetscCall(PetscFree2(d_nnz, o_nnz));
3927: for (i = 0; i < m; i++) {
3928: ii = i + rstart;
3929: PetscCall(MatSetValues_MPIAIJ(B, 1, &ii, Ii[i + 1] - Ii[i], PetscSafePointerPlusOffset(J, Ii[i] - irstart), PetscSafePointerPlusOffset(v, Ii[i] - irstart), INSERT_VALUES));
3930: }
3931: nooffprocentries = B->nooffprocentries;
3932: B->nooffprocentries = PETSC_TRUE;
3933: PetscCall(MatAssemblyBegin(B, MAT_FINAL_ASSEMBLY));
3934: PetscCall(MatAssemblyEnd(B, MAT_FINAL_ASSEMBLY));
3935: B->nooffprocentries = nooffprocentries;
3937: /* count number of entries below block diagonal */
3938: PetscCall(PetscFree(Aij->ld));
3939: PetscCall(PetscCalloc1(m, &ld));
3940: Aij->ld = ld;
3941: for (i = 0; i < m; i++) {
3942: nnz = Ii[i + 1] - Ii[i];
3943: j = 0;
3944: while (j < nnz && J[j] < cstart) j++;
3945: ld[i] = j;
3946: if (J) J += nnz;
3947: }
3949: PetscCall(MatSetOption(B, MAT_NEW_NONZERO_LOCATION_ERR, PETSC_TRUE));
3950: PetscFunctionReturn(PETSC_SUCCESS);
3951: }
3953: /*@
3954: MatMPIAIJSetPreallocationCSR - Allocates memory for a sparse parallel matrix in `MATAIJ` format
3955: (the default parallel PETSc format).
3957: Collective
3959: Input Parameters:
3960: + B - the matrix
3961: . i - the indices into `j` for the start of each local row (indices start with zero)
3962: . j - the column indices for each local row (indices start with zero)
3963: - v - optional values in the matrix
3965: Level: developer
3967: Notes:
3968: The `i`, `j`, and `v` arrays ARE copied by this routine into the internal format used by PETSc;
3969: thus you CANNOT change the matrix entries by changing the values of `v` after you have
3970: called this routine. Use `MatCreateMPIAIJWithSplitArrays()` to avoid needing to copy the arrays.
3972: The `i` and `j` indices are 0 based, and `i` indices are indices corresponding to the local `j` array.
3974: A convenience routine for this functionality is `MatCreateMPIAIJWithArrays()`.
3976: You can update the matrix with new numerical values using `MatUpdateMPIAIJWithArrays()` after this call if the column indices in `j` are sorted.
3978: If you do **not** use `MatUpdateMPIAIJWithArrays()`, the column indices in `j` do not need to be sorted. If you will use
3979: `MatUpdateMPIAIJWithArrays()`, the column indices **must** be sorted.
3981: The format which is used for the sparse matrix input, is equivalent to a
3982: row-major ordering.. i.e for the following matrix, the input data expected is
3983: as shown
3984: .vb
3985: 1 0 0
3986: 2 0 3 P0
3987: -------
3988: 4 5 6 P1
3990: Process0 [P0] rows_owned=[0,1]
3991: i = {0,1,3} [size = nrow+1 = 2+1]
3992: j = {0,0,2} [size = 3]
3993: v = {1,2,3} [size = 3]
3995: Process1 [P1] rows_owned=[2]
3996: i = {0,3} [size = nrow+1 = 1+1]
3997: j = {0,1,2} [size = 3]
3998: v = {4,5,6} [size = 3]
3999: .ve
4001: .seealso: [](ch_matrices), `Mat`, `MATMPIAIJ`, `MatCreate()`, `MatCreateSeqAIJ()`, `MatSetValues()`, `MatMPIAIJSetPreallocation()`, `MatCreateAIJ()`,
4002: `MatCreateSeqAIJWithArrays()`, `MatCreateMPIAIJWithSplitArrays()`, `MatCreateMPIAIJWithArrays()`, `MatSetPreallocationCOO()`, `MatSetValuesCOO()`
4003: @*/
4004: PetscErrorCode MatMPIAIJSetPreallocationCSR(Mat B, const PetscInt i[], const PetscInt j[], const PetscScalar v[])
4005: {
4006: PetscFunctionBegin;
4007: PetscTryMethod(B, "MatMPIAIJSetPreallocationCSR_C", (Mat, const PetscInt[], const PetscInt[], const PetscScalar[]), (B, i, j, v));
4008: PetscFunctionReturn(PETSC_SUCCESS);
4009: }
4011: /*@
4012: MatMPIAIJSetPreallocation - Preallocates memory for a sparse parallel matrix in `MATMPIAIJ` format
4013: (the default parallel PETSc format). For good matrix assembly performance
4014: the user should preallocate the matrix storage by setting the parameters
4015: `d_nz` (or `d_nnz`) and `o_nz` (or `o_nnz`).
4017: Collective
4019: Input Parameters:
4020: + B - the matrix
4021: . d_nz - number of nonzeros per row in DIAGONAL portion of local submatrix
4022: (same value is used for all local rows)
4023: . d_nnz - array containing the number of nonzeros in the various rows of the
4024: DIAGONAL portion of the local submatrix (possibly different for each row)
4025: or `NULL` (`PETSC_NULL_INTEGER` in Fortran), if `d_nz` is used to specify the nonzero structure.
4026: The size of this array is equal to the number of local rows, i.e 'm'.
4027: For matrices that will be factored, you must leave room for (and set)
4028: the diagonal entry even if it is zero.
4029: . o_nz - number of nonzeros per row in the OFF-DIAGONAL portion of local
4030: submatrix (same value is used for all local rows).
4031: - o_nnz - array containing the number of nonzeros in the various rows of the
4032: OFF-DIAGONAL portion of the local submatrix (possibly different for
4033: each row) or `NULL` (`PETSC_NULL_INTEGER` in Fortran), if `o_nz` is used to specify the nonzero
4034: structure. The size of this array is equal to the number
4035: of local rows, i.e 'm'.
4037: Example Usage:
4038: Consider the following 8x8 matrix with 34 non-zero values, that is
4039: assembled across 3 processors. Lets assume that proc0 owns 3 rows,
4040: proc1 owns 3 rows, proc2 owns 2 rows. This division can be shown
4041: as follows
4043: .vb
4044: 1 2 0 | 0 3 0 | 0 4
4045: Proc0 0 5 6 | 7 0 0 | 8 0
4046: 9 0 10 | 11 0 0 | 12 0
4047: -------------------------------------
4048: 13 0 14 | 15 16 17 | 0 0
4049: Proc1 0 18 0 | 19 20 21 | 0 0
4050: 0 0 0 | 22 23 0 | 24 0
4051: -------------------------------------
4052: Proc2 25 26 27 | 0 0 28 | 29 0
4053: 30 0 0 | 31 32 33 | 0 34
4054: .ve
4056: This can be represented as a collection of submatrices as
4057: .vb
4058: A B C
4059: D E F
4060: G H I
4061: .ve
4063: Where the submatrices A,B,C are owned by proc0, D,E,F are
4064: owned by proc1, G,H,I are owned by proc2.
4066: The 'm' parameters for proc0,proc1,proc2 are 3,3,2 respectively.
4067: The 'n' parameters for proc0,proc1,proc2 are 3,3,2 respectively.
4068: The 'M','N' parameters are 8,8, and have the same values on all procs.
4070: The DIAGONAL submatrices corresponding to proc0,proc1,proc2 are
4071: submatrices [A], [E], [I] respectively. The OFF-DIAGONAL submatrices
4072: corresponding to proc0,proc1,proc2 are [BC], [DF], [GH] respectively.
4073: Internally, each processor stores the DIAGONAL part, and the OFF-DIAGONAL
4074: part as `MATSEQAIJ` matrices. For example, proc1 will store [E] as a `MATSEQAIJ`
4075: matrix, and [DF] as another `MATSEQAIJ` matrix.
4077: When `d_nz`, `o_nz` parameters are specified, `d_nz` storage elements are
4078: allocated for every row of the local DIAGONAL submatrix, and `o_nz`
4079: storage locations are allocated for every row of the OFF-DIAGONAL submatrix.
4080: One way to choose `d_nz` and `o_nz` is to use the maximum number of nonzeros over
4081: the local rows for each of the local DIAGONAL, and the OFF-DIAGONAL submatrices.
4082: In this case, the values of `d_nz`, `o_nz` are
4083: .vb
4084: proc0 dnz = 2, o_nz = 2
4085: proc1 dnz = 3, o_nz = 2
4086: proc2 dnz = 1, o_nz = 4
4087: .ve
4088: We are allocating `m`*(`d_nz`+`o_nz`) storage locations for every proc. This
4089: translates to 3*(2+2)=12 for proc0, 3*(3+2)=15 for proc1, 2*(1+4)=10
4090: for proc3. i.e we are using 12+15+10=37 storage locations to store
4091: 34 values.
4093: When `d_nnz`, `o_nnz` parameters are specified, the storage is specified
4094: for every row, corresponding to both DIAGONAL and OFF-DIAGONAL submatrices.
4095: In the above case the values for `d_nnz`, `o_nnz` are
4096: .vb
4097: proc0 d_nnz = [2,2,2] and o_nnz = [2,2,2]
4098: proc1 d_nnz = [3,3,2] and o_nnz = [2,1,1]
4099: proc2 d_nnz = [1,1] and o_nnz = [4,4]
4100: .ve
4101: Here the space allocated is sum of all the above values i.e 34, and
4102: hence pre-allocation is perfect.
4104: Level: intermediate
4106: Notes:
4107: If the *_nnz parameter is given then the *_nz parameter is ignored
4109: The `MATAIJ` format, also called compressed row storage (CSR), is compatible with standard Fortran
4110: storage. The stored row and column indices begin with zero.
4111: See [Sparse Matrices](sec_matsparse) for details.
4113: The parallel matrix is partitioned such that the first m0 rows belong to
4114: process 0, the next m1 rows belong to process 1, the next m2 rows belong
4115: to process 2 etc.. where m0,m1,m2... are the input parameter 'm'.
4117: The DIAGONAL portion of the local submatrix of a processor can be defined
4118: as the submatrix which is obtained by extraction the part corresponding to
4119: the rows r1-r2 and columns c1-c2 of the global matrix, where r1 is the
4120: first row that belongs to the processor, r2 is the last row belonging to
4121: the this processor, and c1-c2 is range of indices of the local part of a
4122: vector suitable for applying the matrix to. This is an mxn matrix. In the
4123: common case of a square matrix, the row and column ranges are the same and
4124: the DIAGONAL part is also square. The remaining portion of the local
4125: submatrix (mxN) constitute the OFF-DIAGONAL portion.
4127: If `o_nnz` and `d_nnz` are specified, then `o_nz` and `d_nz` are ignored.
4129: You can call `MatGetInfo()` to get information on how effective the preallocation was;
4130: for example the fields mallocs,nz_allocated,nz_used,nz_unneeded;
4131: You can also run with the option `-info` and look for messages with the string
4132: malloc in them to see if additional memory allocation was needed.
4134: .seealso: [](ch_matrices), `Mat`, [Sparse Matrices](sec_matsparse), `MATMPIAIJ`, `MATAIJ`, `MatCreate()`, `MatCreateSeqAIJ()`, `MatSetValues()`, `MatCreateAIJ()`, `MatMPIAIJSetPreallocationCSR()`,
4135: `MatGetInfo()`, `PetscSplitOwnership()`, `MatSetPreallocationCOO()`, `MatSetValuesCOO()`
4136: @*/
4137: PetscErrorCode MatMPIAIJSetPreallocation(Mat B, PetscInt d_nz, const PetscInt d_nnz[], PetscInt o_nz, const PetscInt o_nnz[])
4138: {
4139: PetscFunctionBegin;
4142: PetscTryMethod(B, "MatMPIAIJSetPreallocation_C", (Mat, PetscInt, const PetscInt[], PetscInt, const PetscInt[]), (B, d_nz, d_nnz, o_nz, o_nnz));
4143: PetscFunctionReturn(PETSC_SUCCESS);
4144: }
4146: /*@
4147: MatCreateMPIAIJWithArrays - creates a `MATMPIAIJ` matrix using arrays that contain in standard
4148: CSR format for the local rows.
4150: Collective
4152: Input Parameters:
4153: + comm - MPI communicator
4154: . m - number of local rows (Cannot be `PETSC_DECIDE`)
4155: . n - This value should be the same as the local size used in creating the
4156: x vector for the matrix-vector product $y = Ax$. (or `PETSC_DECIDE` to have
4157: calculated if `N` is given) For square matrices n is almost always `m`.
4158: . M - number of global rows (or `PETSC_DETERMINE` to have calculated if `m` is given)
4159: . N - number of global columns (or `PETSC_DETERMINE` to have calculated if `n` is given)
4160: . 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
4161: . j - global column indices
4162: - a - optional matrix values
4164: Output Parameter:
4165: . mat - the matrix
4167: Level: intermediate
4169: Notes:
4170: The `i`, `j`, and `a` arrays ARE copied by this routine into the internal format used by PETSc;
4171: thus you CANNOT change the matrix entries by changing the values of `a[]` after you have
4172: called this routine. Use `MatCreateMPIAIJWithSplitArrays()` to avoid needing to copy the arrays.
4174: The `i` and `j` indices are 0 based, and `i` indices are indices corresponding to the local `j` array.
4176: Once you have created the matrix you can update it with new numerical values using `MatUpdateMPIAIJWithArray()`
4178: If you do **not** use `MatUpdateMPIAIJWithArray()`, the column indices in `j` do not need to be sorted. If you will use
4179: `MatUpdateMPIAIJWithArrays()`, the column indices **must** be sorted.
4181: The format which is used for the sparse matrix input, is equivalent to a
4182: row-major ordering, i.e., for the following matrix, the input data expected is
4183: as shown
4184: .vb
4185: 1 0 0
4186: 2 0 3 P0
4187: -------
4188: 4 5 6 P1
4190: Process0 [P0] rows_owned=[0,1]
4191: i = {0,1,3} [size = nrow+1 = 2+1]
4192: j = {0,0,2} [size = 3]
4193: v = {1,2,3} [size = 3]
4195: Process1 [P1] rows_owned=[2]
4196: i = {0,3} [size = nrow+1 = 1+1]
4197: j = {0,1,2} [size = 3]
4198: v = {4,5,6} [size = 3]
4199: .ve
4201: .seealso: [](ch_matrices), `Mat`, `MatCreate()`, `MatCreateSeqAIJ()`, `MatSetValues()`, `MatMPIAIJSetPreallocation()`, `MatMPIAIJSetPreallocationCSR()`,
4202: `MATMPIAIJ`, `MatCreateAIJ()`, `MatCreateMPIAIJWithSplitArrays()`, `MatUpdateMPIAIJWithArray()`, `MatSetPreallocationCOO()`, `MatSetValuesCOO()`
4203: @*/
4204: PetscErrorCode MatCreateMPIAIJWithArrays(MPI_Comm comm, PetscInt m, PetscInt n, PetscInt M, PetscInt N, const PetscInt i[], const PetscInt j[], const PetscScalar a[], Mat *mat)
4205: {
4206: PetscFunctionBegin;
4207: PetscCheck(!i || !i[0], PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "i (row indices) must start with 0");
4208: PetscCheck(m >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "local number of rows (m) cannot be PETSC_DECIDE, or negative");
4209: PetscCall(MatCreate(comm, mat));
4210: PetscCall(MatSetSizes(*mat, m, n, M, N));
4211: /* PetscCall(MatSetBlockSizes(M,bs,cbs)); */
4212: PetscCall(MatSetType(*mat, MATMPIAIJ));
4213: PetscCall(MatMPIAIJSetPreallocationCSR(*mat, i, j, a));
4214: PetscFunctionReturn(PETSC_SUCCESS);
4215: }
4217: /*@
4218: MatUpdateMPIAIJWithArrays - updates a `MATMPIAIJ` matrix using arrays that contain in standard
4219: CSR format for the local rows. Only the numerical values are updated the other arrays must be identical to what was passed
4220: from `MatCreateMPIAIJWithArrays()`
4222: Deprecated: Use `MatUpdateMPIAIJWithArray()`
4224: Collective
4226: Input Parameters:
4227: + mat - the matrix
4228: . m - number of local rows (Cannot be `PETSC_DECIDE`)
4229: . n - This value should be the same as the local size used in creating the
4230: x vector for the matrix-vector product y = Ax. (or `PETSC_DECIDE` to have
4231: calculated if N is given) For square matrices n is almost always m.
4232: . M - number of global rows (or `PETSC_DETERMINE` to have calculated if m is given)
4233: . N - number of global columns (or `PETSC_DETERMINE` to have calculated if n is given)
4234: . Ii - row indices; that is Ii[0] = 0, Ii[row] = Ii[row-1] + number of elements in that row of the matrix
4235: . J - column indices
4236: - v - matrix values
4238: Level: deprecated
4240: .seealso: [](ch_matrices), `Mat`, `MATMPIAIJ`, `MatCreate()`, `MatCreateSeqAIJ()`, `MatSetValues()`, `MatMPIAIJSetPreallocation()`, `MatMPIAIJSetPreallocationCSR()`,
4241: `MatCreateAIJ()`, `MatCreateMPIAIJWithSplitArrays()`, `MatUpdateMPIAIJWithArray()`, `MatSetPreallocationCOO()`, `MatSetValuesCOO()`
4242: @*/
4243: PetscErrorCode MatUpdateMPIAIJWithArrays(Mat mat, PetscInt m, PetscInt n, PetscInt M, PetscInt N, const PetscInt Ii[], const PetscInt J[], const PetscScalar v[])
4244: {
4245: PetscInt nnz, i;
4246: PetscBool nooffprocentries;
4247: Mat_MPIAIJ *Aij = (Mat_MPIAIJ *)mat->data;
4248: Mat_SeqAIJ *Ad = (Mat_SeqAIJ *)Aij->A->data;
4249: PetscScalar *ad, *ao;
4250: PetscInt ldi, Iii, md;
4251: const PetscInt *Adi = Ad->i;
4252: PetscInt *ld = Aij->ld;
4254: PetscFunctionBegin;
4255: PetscCheck(Ii[0] == 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "i (row indices) must start with 0");
4256: PetscCheck(m >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "local number of rows (m) cannot be PETSC_DECIDE, or negative");
4257: PetscCheck(m == mat->rmap->n, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Local number of rows cannot change from call to MatUpdateMPIAIJWithArrays()");
4258: PetscCheck(n == mat->cmap->n, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Local number of columns cannot change from call to MatUpdateMPIAIJWithArrays()");
4260: PetscCall(MatSeqAIJGetArrayWrite(Aij->A, &ad));
4261: PetscCall(MatSeqAIJGetArrayWrite(Aij->B, &ao));
4263: for (i = 0; i < m; i++) {
4264: if (PetscDefined(USE_DEBUG)) {
4265: for (PetscInt j = Ii[i] + 1; j < Ii[i + 1]; ++j) {
4266: 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);
4267: 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);
4268: }
4269: }
4270: nnz = Ii[i + 1] - Ii[i];
4271: Iii = Ii[i];
4272: ldi = ld[i];
4273: md = Adi[i + 1] - Adi[i];
4274: PetscCall(PetscArraycpy(ao, v + Iii, ldi));
4275: PetscCall(PetscArraycpy(ad, v + Iii + ldi, md));
4276: PetscCall(PetscArraycpy(ao + ldi, v + Iii + ldi + md, nnz - ldi - md));
4277: ad += md;
4278: ao += nnz - md;
4279: }
4280: nooffprocentries = mat->nooffprocentries;
4281: mat->nooffprocentries = PETSC_TRUE;
4282: PetscCall(MatSeqAIJRestoreArrayWrite(Aij->A, &ad));
4283: PetscCall(MatSeqAIJRestoreArrayWrite(Aij->B, &ao));
4284: PetscCall(PetscObjectStateIncrease((PetscObject)Aij->A));
4285: PetscCall(PetscObjectStateIncrease((PetscObject)Aij->B));
4286: PetscCall(PetscObjectStateIncrease((PetscObject)mat));
4287: PetscCall(MatAssemblyBegin(mat, MAT_FINAL_ASSEMBLY));
4288: PetscCall(MatAssemblyEnd(mat, MAT_FINAL_ASSEMBLY));
4289: mat->nooffprocentries = nooffprocentries;
4290: PetscFunctionReturn(PETSC_SUCCESS);
4291: }
4293: /*@
4294: MatUpdateMPIAIJWithArray - updates an `MATMPIAIJ` matrix using an array that contains the nonzero values
4296: Collective
4298: Input Parameters:
4299: + mat - the matrix
4300: - v - matrix values, stored by row
4302: Level: intermediate
4304: Notes:
4305: The matrix must have been obtained with `MatCreateMPIAIJWithArrays()` or `MatMPIAIJSetPreallocationCSR()`
4307: The column indices in the call to `MatCreateMPIAIJWithArrays()` or `MatMPIAIJSetPreallocationCSR()` must have been sorted for this call to work correctly
4309: .seealso: [](ch_matrices), `Mat`, `MatCreate()`, `MatCreateSeqAIJ()`, `MatSetValues()`, `MatMPIAIJSetPreallocation()`, `MatMPIAIJSetPreallocationCSR()`,
4310: `MATMPIAIJ`, `MatCreateAIJ()`, `MatCreateMPIAIJWithSplitArrays()`, `MatUpdateMPIAIJWithArrays()`, `MatSetPreallocationCOO()`, `MatSetValuesCOO()`
4311: @*/
4312: PetscErrorCode MatUpdateMPIAIJWithArray(Mat mat, const PetscScalar v[])
4313: {
4314: PetscInt nnz, i, m;
4315: PetscBool nooffprocentries;
4316: Mat_MPIAIJ *Aij = (Mat_MPIAIJ *)mat->data;
4317: Mat_SeqAIJ *Ad = (Mat_SeqAIJ *)Aij->A->data;
4318: Mat_SeqAIJ *Ao = (Mat_SeqAIJ *)Aij->B->data;
4319: PetscScalar *ad, *ao;
4320: const PetscInt *Adi = Ad->i, *Adj = Ao->i;
4321: PetscInt ldi, Iii, md;
4322: PetscInt *ld = Aij->ld;
4324: PetscFunctionBegin;
4325: m = mat->rmap->n;
4327: PetscCall(MatSeqAIJGetArrayWrite(Aij->A, &ad));
4328: PetscCall(MatSeqAIJGetArrayWrite(Aij->B, &ao));
4329: Iii = 0;
4330: for (i = 0; i < m; i++) {
4331: nnz = Adi[i + 1] - Adi[i] + Adj[i + 1] - Adj[i];
4332: ldi = ld[i];
4333: md = Adi[i + 1] - Adi[i];
4334: PetscCall(PetscArraycpy(ad, v + Iii + ldi, md));
4335: ad += md;
4336: if (ao) {
4337: PetscCall(PetscArraycpy(ao, v + Iii, ldi));
4338: PetscCall(PetscArraycpy(ao + ldi, v + Iii + ldi + md, nnz - ldi - md));
4339: ao += nnz - md;
4340: }
4341: Iii += nnz;
4342: }
4343: nooffprocentries = mat->nooffprocentries;
4344: mat->nooffprocentries = PETSC_TRUE;
4345: PetscCall(MatSeqAIJRestoreArrayWrite(Aij->A, &ad));
4346: PetscCall(MatSeqAIJRestoreArrayWrite(Aij->B, &ao));
4347: PetscCall(PetscObjectStateIncrease((PetscObject)Aij->A));
4348: PetscCall(PetscObjectStateIncrease((PetscObject)Aij->B));
4349: PetscCall(PetscObjectStateIncrease((PetscObject)mat));
4350: PetscCall(MatAssemblyBegin(mat, MAT_FINAL_ASSEMBLY));
4351: PetscCall(MatAssemblyEnd(mat, MAT_FINAL_ASSEMBLY));
4352: mat->nooffprocentries = nooffprocentries;
4353: PetscFunctionReturn(PETSC_SUCCESS);
4354: }
4356: /*@
4357: MatCreateAIJ - Creates a sparse parallel matrix in `MATAIJ` format
4358: (the default parallel PETSc format). For good matrix assembly performance
4359: the user should preallocate the matrix storage by setting the parameters
4360: `d_nz` (or `d_nnz`) and `o_nz` (or `o_nnz`).
4362: Collective
4364: Input Parameters:
4365: + comm - MPI communicator
4366: . m - number of local rows (or `PETSC_DECIDE` to have calculated if M is given)
4367: This value should be the same as the local size used in creating the
4368: y vector for the matrix-vector product y = Ax.
4369: . n - This value should be the same as the local size used in creating the
4370: x vector for the matrix-vector product y = Ax. (or `PETSC_DECIDE` to have
4371: calculated if N is given) For square matrices n is almost always m.
4372: . M - number of global rows (or `PETSC_DETERMINE` to have calculated if m is given)
4373: . N - number of global columns (or `PETSC_DETERMINE` to have calculated if n is given)
4374: . d_nz - number of nonzeros per row in DIAGONAL portion of local submatrix
4375: (same value is used for all local rows)
4376: . d_nnz - array containing the number of nonzeros in the various rows of the
4377: DIAGONAL portion of the local submatrix (possibly different for each row)
4378: or `NULL`, if `d_nz` is used to specify the nonzero structure.
4379: The size of this array is equal to the number of local rows, i.e 'm'.
4380: . o_nz - number of nonzeros per row in the OFF-DIAGONAL portion of local
4381: submatrix (same value is used for all local rows).
4382: - o_nnz - array containing the number of nonzeros in the various rows of the
4383: OFF-DIAGONAL portion of the local submatrix (possibly different for
4384: each row) or `NULL`, if `o_nz` is used to specify the nonzero
4385: structure. The size of this array is equal to the number
4386: of local rows, i.e 'm'.
4388: Output Parameter:
4389: . A - the matrix
4391: Options Database Keys:
4392: + -mat_no_inode (true|false) - Do not use inodes
4393: . -mat_inode_limit limit - Sets inode limit (max limit=5)
4394: - -matmult_vecscatter_view viewer - View the vecscatter (i.e., communication pattern) used in `MatMult()` of sparse parallel matrices.
4395: See viewer types in manual of `MatView()`. Of them, ascii_matlab, draw or binary cause the `VecScatter`
4396: 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.
4398: Level: intermediate
4400: Notes:
4401: It is recommended that one use `MatCreateFromOptions()` or the `MatCreate()`, `MatSetType()` and/or `MatSetFromOptions()`,
4402: MatXXXXSetPreallocation() paradigm instead of this routine directly.
4403: [MatXXXXSetPreallocation() is, for example, `MatSeqAIJSetPreallocation()`]
4405: If the *_nnz parameter is given then the *_nz parameter is ignored
4407: The `m`,`n`,`M`,`N` parameters specify the size of the matrix, and its partitioning across
4408: processors, while `d_nz`,`d_nnz`,`o_nz`,`o_nnz` parameters specify the approximate
4409: storage requirements for this matrix.
4411: If `PETSC_DECIDE` or `PETSC_DETERMINE` is used for a particular argument on one
4412: processor than it must be used on all processors that share the object for
4413: that argument.
4415: If `m` and `n` are not `PETSC_DECIDE`, then the values determine the `PetscLayout` of the matrix and the ranges returned by
4416: `MatGetOwnershipRange()`, `MatGetOwnershipRanges()`, `MatGetOwnershipRangeColumn()`, and `MatGetOwnershipRangesColumn()`.
4418: The user MUST specify either the local or global matrix dimensions
4419: (possibly both).
4421: The parallel matrix is partitioned across processors such that the
4422: first `m0` rows belong to process 0, the next `m1` rows belong to
4423: process 1, the next `m2` rows belong to process 2, etc., where
4424: `m0`, `m1`, `m2`... are the input parameter `m` on each MPI process. I.e., each MPI process stores
4425: values corresponding to [m x N] submatrix.
4427: The columns are logically partitioned with the n0 columns belonging
4428: to 0th partition, the next n1 columns belonging to the next
4429: partition etc.. where n0,n1,n2... are the input parameter 'n'.
4431: The DIAGONAL portion of the local submatrix on any given processor
4432: is the submatrix corresponding to the rows and columns m,n
4433: corresponding to the given processor. i.e diagonal matrix on
4434: process 0 is [m0 x n0], diagonal matrix on process 1 is [m1 x n1]
4435: etc. The remaining portion of the local submatrix [m x (N-n)]
4436: constitute the OFF-DIAGONAL portion. The example below better
4437: illustrates this concept. The two matrices, the DIAGONAL portion and
4438: the OFF-DIAGONAL portion are each stored as `MATSEQAIJ` matrices.
4440: For a square global matrix we define each processor's diagonal portion
4441: to be its local rows and the corresponding columns (a square submatrix);
4442: each processor's off-diagonal portion encompasses the remainder of the
4443: local matrix (a rectangular submatrix).
4445: If `o_nnz`, `d_nnz` are specified, then `o_nz`, and `d_nz` are ignored.
4447: When calling this routine with a single process communicator, a matrix of
4448: type `MATSEQAIJ` is returned. If a matrix of type `MATMPIAIJ` is desired for this
4449: type of communicator, use the construction mechanism
4450: .vb
4451: MatCreate(..., &A);
4452: MatSetType(A, MATMPIAIJ);
4453: MatSetSizes(A, m, n, M, N);
4454: MatMPIAIJSetPreallocation(A, ...);
4455: .ve
4457: By default, this format uses inodes (identical nodes) when possible.
4458: We search for consecutive rows with the same nonzero structure, thereby
4459: reusing matrix information to achieve increased efficiency.
4461: Example Usage:
4462: Consider the following 8x8 matrix with 34 non-zero values, that is
4463: assembled across 3 processors. Lets assume that proc0 owns 3 rows,
4464: proc1 owns 3 rows, proc2 owns 2 rows. This division can be shown
4465: as follows
4467: .vb
4468: 1 2 0 | 0 3 0 | 0 4
4469: Proc0 0 5 6 | 7 0 0 | 8 0
4470: 9 0 10 | 11 0 0 | 12 0
4471: -------------------------------------
4472: 13 0 14 | 15 16 17 | 0 0
4473: Proc1 0 18 0 | 19 20 21 | 0 0
4474: 0 0 0 | 22 23 0 | 24 0
4475: -------------------------------------
4476: Proc2 25 26 27 | 0 0 28 | 29 0
4477: 30 0 0 | 31 32 33 | 0 34
4478: .ve
4480: This can be represented as a collection of submatrices as
4482: .vb
4483: A B C
4484: D E F
4485: G H I
4486: .ve
4488: Where the submatrices A,B,C are owned by proc0, D,E,F are
4489: owned by proc1, G,H,I are owned by proc2.
4491: The 'm' parameters for proc0,proc1,proc2 are 3,3,2 respectively.
4492: The 'n' parameters for proc0,proc1,proc2 are 3,3,2 respectively.
4493: The 'M','N' parameters are 8,8, and have the same values on all procs.
4495: The DIAGONAL submatrices corresponding to proc0,proc1,proc2 are
4496: submatrices [A], [E], [I] respectively. The OFF-DIAGONAL submatrices
4497: corresponding to proc0,proc1,proc2 are [BC], [DF], [GH] respectively.
4498: Internally, each processor stores the DIAGONAL part, and the OFF-DIAGONAL
4499: part as `MATSEQAIJ` matrices. For example, proc1 will store [E] as a `MATSEQAIJ`
4500: matrix, and [DF] as another SeqAIJ matrix.
4502: When `d_nz`, `o_nz` parameters are specified, `d_nz` storage elements are
4503: allocated for every row of the local DIAGONAL submatrix, and `o_nz`
4504: storage locations are allocated for every row of the OFF-DIAGONAL submatrix.
4505: One way to choose `d_nz` and `o_nz` is to use the maximum number of nonzeros over
4506: the local rows for each of the local DIAGONAL, and the OFF-DIAGONAL submatrices.
4507: In this case, the values of `d_nz`,`o_nz` are
4508: .vb
4509: proc0 dnz = 2, o_nz = 2
4510: proc1 dnz = 3, o_nz = 2
4511: proc2 dnz = 1, o_nz = 4
4512: .ve
4513: We are allocating m*(`d_nz`+`o_nz`) storage locations for every proc. This
4514: translates to 3*(2+2)=12 for proc0, 3*(3+2)=15 for proc1, 2*(1+4)=10
4515: for proc3. i.e we are using 12+15+10=37 storage locations to store
4516: 34 values.
4518: When `d_nnz`, `o_nnz` parameters are specified, the storage is specified
4519: for every row, corresponding to both DIAGONAL and OFF-DIAGONAL submatrices.
4520: In the above case the values for d_nnz,o_nnz are
4521: .vb
4522: proc0 d_nnz = [2,2,2] and o_nnz = [2,2,2]
4523: proc1 d_nnz = [3,3,2] and o_nnz = [2,1,1]
4524: proc2 d_nnz = [1,1] and o_nnz = [4,4]
4525: .ve
4526: Here the space allocated is sum of all the above values i.e 34, and
4527: hence pre-allocation is perfect.
4529: .seealso: [](ch_matrices), `Mat`, [Sparse Matrix Creation](sec_matsparse), `MatCreate()`, `MatCreateSeqAIJ()`, `MatSetValues()`, `MatMPIAIJSetPreallocation()`, `MatMPIAIJSetPreallocationCSR()`,
4530: `MATMPIAIJ`, `MatCreateMPIAIJWithArrays()`, `MatGetOwnershipRange()`, `MatGetOwnershipRanges()`, `MatGetOwnershipRangeColumn()`,
4531: `MatGetOwnershipRangesColumn()`, `PetscLayout`
4532: @*/
4533: 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)
4534: {
4535: PetscMPIInt size;
4537: PetscFunctionBegin;
4538: PetscCall(MatCreate(comm, A));
4539: PetscCall(MatSetSizes(*A, m, n, M, N));
4540: PetscCallMPI(MPI_Comm_size(comm, &size));
4541: if (size > 1) {
4542: PetscCall(MatSetType(*A, MATMPIAIJ));
4543: PetscCall(MatMPIAIJSetPreallocation(*A, d_nz, d_nnz, o_nz, o_nnz));
4544: } else {
4545: PetscCall(MatSetType(*A, MATSEQAIJ));
4546: PetscCall(MatSeqAIJSetPreallocation(*A, d_nz, d_nnz));
4547: }
4548: PetscFunctionReturn(PETSC_SUCCESS);
4549: }
4551: /*@
4552: MatMPIAIJGetSeqAIJ - Returns the local pieces of this distributed matrix
4554: Not Collective
4556: Input Parameter:
4557: . A - The `MATMPIAIJ` matrix
4559: Output Parameters:
4560: + Ad - The local diagonal block as a `MATSEQAIJ` matrix
4561: . Ao - The local off-diagonal block as a `MATSEQAIJ` matrix
4562: - colmap - An array mapping local column numbers of `Ao` to global column numbers of the parallel matrix
4564: Level: intermediate
4566: Note:
4567: The rows in `Ad` and `Ao` are in [0, Nr), where Nr is the number of local rows on this process. The columns
4568: 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
4569: the number of nonzero columns in the local off-diagonal piece of the matrix `A`. The array colmap maps these
4570: local column numbers to global column numbers in the original matrix.
4572: .seealso: [](ch_matrices), `Mat`, `MATMPIAIJ`, `MatMPIAIJGetLocalMat()`, `MatMPIAIJGetLocalMatCondensed()`, `MatCreateAIJ()`, `MATSEQAIJ`
4573: @*/
4574: PetscErrorCode MatMPIAIJGetSeqAIJ(Mat A, Mat *Ad, Mat *Ao, const PetscInt *colmap[])
4575: {
4576: Mat_MPIAIJ *a = (Mat_MPIAIJ *)A->data;
4577: PetscBool flg;
4579: PetscFunctionBegin;
4580: PetscCall(PetscStrbeginswith(((PetscObject)A)->type_name, MATMPIAIJ, &flg));
4581: PetscCheck(flg, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "This function requires a MATMPIAIJ matrix as input");
4582: if (Ad) *Ad = a->A;
4583: if (Ao) *Ao = a->B;
4584: if (colmap) *colmap = a->garray;
4585: PetscFunctionReturn(PETSC_SUCCESS);
4586: }
4588: static PetscErrorCode MatGetMultPetscSF_MPIAIJ(Mat A, PetscSF *sf)
4589: {
4590: Mat_MPIAIJ *a = (Mat_MPIAIJ *)A->data;
4592: PetscFunctionBegin;
4593: *sf = a->Mvctx;
4594: PetscFunctionReturn(PETSC_SUCCESS);
4595: }
4597: PetscErrorCode MatCreateMPIMatConcatenateSeqMat_MPIAIJ(MPI_Comm comm, Mat inmat, PetscInt n, MatReuse scall, Mat *outmat)
4598: {
4599: PetscInt m, N, i, rstart, nnz, Ii;
4600: PetscInt *indx;
4601: PetscScalar *values;
4602: MatType rootType;
4604: PetscFunctionBegin;
4605: PetscCall(MatGetSize(inmat, &m, &N));
4606: if (scall == MAT_INITIAL_MATRIX) { /* symbolic phase */
4607: PetscInt *dnz, *onz, sum, bs, cbs;
4609: if (n == PETSC_DECIDE) PetscCall(PetscSplitOwnership(comm, &n, &N));
4610: /* Check sum(n) = N */
4611: PetscCallMPI(MPIU_Allreduce(&n, &sum, 1, MPIU_INT, MPI_SUM, comm));
4612: PetscCheck(sum == N, PETSC_COMM_SELF, PETSC_ERR_ARG_INCOMP, "Sum of local columns %" PetscInt_FMT " != global columns %" PetscInt_FMT, sum, N);
4614: PetscCallMPI(MPI_Scan(&m, &rstart, 1, MPIU_INT, MPI_SUM, comm));
4615: rstart -= m;
4617: MatPreallocateBegin(comm, m, n, dnz, onz);
4618: for (i = 0; i < m; i++) {
4619: PetscCall(MatGetRow_SeqAIJ(inmat, i, &nnz, &indx, NULL));
4620: PetscCall(MatPreallocateSet(i + rstart, nnz, indx, dnz, onz));
4621: PetscCall(MatRestoreRow_SeqAIJ(inmat, i, &nnz, &indx, NULL));
4622: }
4624: PetscCall(MatCreate(comm, outmat));
4625: PetscCall(MatSetSizes(*outmat, m, n, PETSC_DETERMINE, PETSC_DETERMINE));
4626: PetscCall(MatGetBlockSizes(inmat, &bs, &cbs));
4627: PetscCall(MatSetBlockSizes(*outmat, bs, cbs));
4628: PetscCall(MatGetRootType_Private(inmat, &rootType));
4629: PetscCall(MatSetType(*outmat, rootType));
4630: PetscCall(MatSeqAIJSetPreallocation(*outmat, 0, dnz));
4631: PetscCall(MatMPIAIJSetPreallocation(*outmat, 0, dnz, 0, onz));
4632: MatPreallocateEnd(dnz, onz);
4633: PetscCall(MatSetOption(*outmat, MAT_NO_OFF_PROC_ENTRIES, PETSC_TRUE));
4634: }
4636: /* numeric phase */
4637: PetscCall(MatGetOwnershipRange(*outmat, &rstart, NULL));
4638: for (i = 0; i < m; i++) {
4639: PetscCall(MatGetRow_SeqAIJ(inmat, i, &nnz, &indx, &values));
4640: Ii = i + rstart;
4641: PetscCall(MatSetValues(*outmat, 1, &Ii, nnz, indx, values, INSERT_VALUES));
4642: PetscCall(MatRestoreRow_SeqAIJ(inmat, i, &nnz, &indx, &values));
4643: }
4644: PetscCall(MatAssemblyBegin(*outmat, MAT_FINAL_ASSEMBLY));
4645: PetscCall(MatAssemblyEnd(*outmat, MAT_FINAL_ASSEMBLY));
4646: PetscFunctionReturn(PETSC_SUCCESS);
4647: }
4649: static PetscErrorCode MatMergeSeqsToMPIDestroy(PetscCtxRt data)
4650: {
4651: MatMergeSeqsToMPI *merge = *(MatMergeSeqsToMPI **)data;
4653: PetscFunctionBegin;
4654: if (!merge) PetscFunctionReturn(PETSC_SUCCESS);
4655: PetscCall(PetscFree(merge->id_r));
4656: PetscCall(PetscFree(merge->len_s));
4657: PetscCall(PetscFree(merge->len_r));
4658: PetscCall(PetscFree(merge->bi));
4659: PetscCall(PetscFree(merge->bj));
4660: PetscCall(PetscFree(merge->buf_ri[0]));
4661: PetscCall(PetscFree(merge->buf_ri));
4662: PetscCall(PetscFree(merge->buf_rj[0]));
4663: PetscCall(PetscFree(merge->buf_rj));
4664: PetscCall(PetscFree(merge->coi));
4665: PetscCall(PetscFree(merge->coj));
4666: PetscCall(PetscFree(merge->owners_co));
4667: PetscCall(PetscLayoutDestroy(&merge->rowmap));
4668: PetscCall(PetscFree(merge));
4669: PetscFunctionReturn(PETSC_SUCCESS);
4670: }
4672: #include <../src/mat/utils/freespace.h>
4674: /*@
4675: MatCreateMPIAIJSumSeqAIJNumeric - Fill the numerical values of an `MATMPIAIJ` matrix previously created by
4676: `MatCreateMPIAIJSumSeqAIJSymbolic()` by summing the local `MATSEQAIJ` contributions from each process.
4678: Collective
4680: Input Parameters:
4681: + seqmat - the local `MATSEQAIJ` contribution from this process
4682: - mpimat - the target `MATMPIAIJ` matrix created by `MatCreateMPIAIJSumSeqAIJSymbolic()`
4684: Level: developer
4686: .seealso: `Mat`, `MATMPIAIJ`, `MATSEQAIJ`, `MatCreateMPIAIJSumSeqAIJSymbolic()`, `MatCreateMPIAIJSumSeqAIJ()`
4687: @*/
4688: PetscErrorCode MatCreateMPIAIJSumSeqAIJNumeric(Mat seqmat, Mat mpimat)
4689: {
4690: MPI_Comm comm;
4691: Mat_SeqAIJ *a = (Mat_SeqAIJ *)seqmat->data;
4692: PetscMPIInt size, rank, taga, *len_s;
4693: PetscInt N = mpimat->cmap->N, i, j, *owners, *ai = a->i, *aj, m;
4694: PetscMPIInt proc, k;
4695: PetscInt **buf_ri, **buf_rj;
4696: PetscInt anzi, *bj_i, *bi, *bj, arow, bnzi, nextaj;
4697: PetscInt nrows, **buf_ri_k, **nextrow, **nextai;
4698: MPI_Request *s_waits, *r_waits;
4699: MPI_Status *status;
4700: const MatScalar *aa, *a_a;
4701: MatScalar **abuf_r, *ba_i;
4702: MatMergeSeqsToMPI *merge;
4703: PetscContainer container;
4705: PetscFunctionBegin;
4706: PetscCall(PetscObjectGetComm((PetscObject)mpimat, &comm));
4707: PetscCall(PetscLogEventBegin(MAT_Seqstompinum, seqmat, 0, 0, 0));
4709: PetscCallMPI(MPI_Comm_size(comm, &size));
4710: PetscCallMPI(MPI_Comm_rank(comm, &rank));
4712: PetscCall(PetscObjectQuery((PetscObject)mpimat, "MatMergeSeqsToMPI", (PetscObject *)&container));
4713: PetscCheck(container, PetscObjectComm((PetscObject)mpimat), PETSC_ERR_PLIB, "Mat not created from MatCreateMPIAIJSumSeqAIJSymbolic");
4714: PetscCall(PetscContainerGetPointer(container, &merge));
4715: PetscCall(MatSeqAIJGetArrayRead(seqmat, &a_a));
4716: aa = a_a;
4718: bi = merge->bi;
4719: bj = merge->bj;
4720: buf_ri = merge->buf_ri;
4721: buf_rj = merge->buf_rj;
4723: PetscCall(PetscMalloc1(size, &status));
4724: owners = merge->rowmap->range;
4725: len_s = merge->len_s;
4727: /* send and recv matrix values */
4728: PetscCall(PetscObjectGetNewTag((PetscObject)mpimat, &taga));
4729: PetscCall(PetscPostIrecvScalar(comm, taga, merge->nrecv, merge->id_r, merge->len_r, &abuf_r, &r_waits));
4731: PetscCall(PetscMalloc1(merge->nsend + 1, &s_waits));
4732: for (proc = 0, k = 0; proc < size; proc++) {
4733: if (!len_s[proc]) continue;
4734: i = owners[proc];
4735: PetscCallMPI(MPIU_Isend(aa + ai[i], len_s[proc], MPIU_MATSCALAR, proc, taga, comm, s_waits + k));
4736: k++;
4737: }
4739: if (merge->nrecv) PetscCallMPI(MPI_Waitall(merge->nrecv, r_waits, status));
4740: if (merge->nsend) PetscCallMPI(MPI_Waitall(merge->nsend, s_waits, status));
4741: PetscCall(PetscFree(status));
4743: PetscCall(PetscFree(s_waits));
4744: PetscCall(PetscFree(r_waits));
4746: /* insert mat values of mpimat */
4747: PetscCall(PetscMalloc1(N, &ba_i));
4748: PetscCall(PetscMalloc3(merge->nrecv, &buf_ri_k, merge->nrecv, &nextrow, merge->nrecv, &nextai));
4750: for (k = 0; k < merge->nrecv; k++) {
4751: buf_ri_k[k] = buf_ri[k]; /* beginning of k-th recved i-structure */
4752: nrows = *buf_ri_k[k];
4753: nextrow[k] = buf_ri_k[k] + 1; /* next row number of k-th recved i-structure */
4754: nextai[k] = buf_ri_k[k] + (nrows + 1); /* points to the next i-structure of k-th recved i-structure */
4755: }
4757: /* set values of ba */
4758: m = merge->rowmap->n;
4759: for (i = 0; i < m; i++) {
4760: arow = owners[rank] + i;
4761: bj_i = bj + bi[i]; /* col indices of the i-th row of mpimat */
4762: bnzi = bi[i + 1] - bi[i];
4763: PetscCall(PetscArrayzero(ba_i, bnzi));
4765: /* add local non-zero vals of this proc's seqmat into ba */
4766: anzi = ai[arow + 1] - ai[arow];
4767: aj = a->j + ai[arow];
4768: aa = a_a + ai[arow];
4769: nextaj = 0;
4770: for (j = 0; nextaj < anzi; j++) {
4771: if (*(bj_i + j) == aj[nextaj]) { /* bcol == acol */
4772: ba_i[j] += aa[nextaj++];
4773: }
4774: }
4776: /* add received vals into ba */
4777: for (k = 0; k < merge->nrecv; k++) { /* k-th received message */
4778: /* i-th row */
4779: if (i == *nextrow[k]) {
4780: anzi = *(nextai[k] + 1) - *nextai[k];
4781: aj = buf_rj[k] + *nextai[k];
4782: aa = abuf_r[k] + *nextai[k];
4783: nextaj = 0;
4784: for (j = 0; nextaj < anzi; j++) {
4785: if (*(bj_i + j) == aj[nextaj]) { /* bcol == acol */
4786: ba_i[j] += aa[nextaj++];
4787: }
4788: }
4789: nextrow[k]++;
4790: nextai[k]++;
4791: }
4792: }
4793: PetscCall(MatSetValues(mpimat, 1, &arow, bnzi, bj_i, ba_i, INSERT_VALUES));
4794: }
4795: PetscCall(MatSeqAIJRestoreArrayRead(seqmat, &a_a));
4796: PetscCall(MatAssemblyBegin(mpimat, MAT_FINAL_ASSEMBLY));
4797: PetscCall(MatAssemblyEnd(mpimat, MAT_FINAL_ASSEMBLY));
4799: PetscCall(PetscFree(abuf_r[0]));
4800: PetscCall(PetscFree(abuf_r));
4801: PetscCall(PetscFree(ba_i));
4802: PetscCall(PetscFree3(buf_ri_k, nextrow, nextai));
4803: PetscCall(PetscLogEventEnd(MAT_Seqstompinum, seqmat, 0, 0, 0));
4804: PetscFunctionReturn(PETSC_SUCCESS);
4805: }
4807: /*@
4808: MatCreateMPIAIJSumSeqAIJSymbolic - Create the symbolic (nonzero-pattern) portion of an `MATMPIAIJ` matrix
4809: obtained by summing local `MATSEQAIJ` contributions from each process.
4811: Collective
4813: Input Parameters:
4814: + comm - the communicator
4815: . seqmat - the local `MATSEQAIJ` contribution from this process
4816: . m - the number of local rows for the resulting `MATMPIAIJ` matrix, or `PETSC_DECIDE`
4817: - n - the number of local columns for the resulting `MATMPIAIJ` matrix, or `PETSC_DECIDE`
4819: Output Parameter:
4820: . mpimat - the newly created `MATMPIAIJ` matrix
4822: Level: developer
4824: Note:
4825: The numerical values are filled in by a subsequent call to `MatCreateMPIAIJSumSeqAIJNumeric()`.
4827: .seealso: `Mat`, `MATMPIAIJ`, `MATSEQAIJ`, `MatCreateMPIAIJSumSeqAIJNumeric()`, `MatCreateMPIAIJSumSeqAIJ()`
4828: @*/
4829: PetscErrorCode MatCreateMPIAIJSumSeqAIJSymbolic(MPI_Comm comm, Mat seqmat, PetscInt m, PetscInt n, Mat *mpimat)
4830: {
4831: Mat B_mpi;
4832: Mat_SeqAIJ *a = (Mat_SeqAIJ *)seqmat->data;
4833: PetscMPIInt size, rank, tagi, tagj, *len_s, *len_si, *len_ri;
4834: PetscInt **buf_rj, **buf_ri, **buf_ri_k;
4835: PetscInt M = seqmat->rmap->n, N = seqmat->cmap->n, i, *owners, *ai = a->i, *aj = a->j;
4836: PetscInt len, *dnz, *onz, bs, cbs;
4837: PetscInt k, anzi, *bi, *bj, *lnk, nlnk, arow, bnzi;
4838: PetscInt nrows, *buf_s, *buf_si, *buf_si_i, **nextrow, **nextai;
4839: MPI_Request *si_waits, *sj_waits, *ri_waits, *rj_waits;
4840: MPI_Status *status;
4841: PetscFreeSpaceList free_space = NULL, current_space = NULL;
4842: PetscBT lnkbt;
4843: MatMergeSeqsToMPI *merge;
4844: PetscContainer container;
4846: PetscFunctionBegin;
4847: PetscCall(PetscLogEventBegin(MAT_Seqstompisym, seqmat, 0, 0, 0));
4849: /* make sure it is a PETSc comm */
4850: PetscCall(PetscCommDuplicate(comm, &comm, NULL));
4851: PetscCallMPI(MPI_Comm_size(comm, &size));
4852: PetscCallMPI(MPI_Comm_rank(comm, &rank));
4854: PetscCall(PetscNew(&merge));
4855: PetscCall(PetscMalloc1(size, &status));
4857: /* determine row ownership */
4858: PetscCall(PetscLayoutCreate(comm, &merge->rowmap));
4859: PetscCall(PetscLayoutSetLocalSize(merge->rowmap, m));
4860: PetscCall(PetscLayoutSetSize(merge->rowmap, M));
4861: PetscCall(PetscLayoutSetBlockSize(merge->rowmap, 1));
4862: PetscCall(PetscLayoutSetUp(merge->rowmap));
4863: PetscCall(PetscMalloc1(size, &len_si));
4864: PetscCall(PetscMalloc1(size, &merge->len_s));
4866: m = merge->rowmap->n;
4867: owners = merge->rowmap->range;
4869: /* determine the number of messages to send, their lengths */
4870: len_s = merge->len_s;
4872: len = 0; /* length of buf_si[] */
4873: merge->nsend = 0;
4874: for (PetscMPIInt proc = 0; proc < size; proc++) {
4875: len_si[proc] = 0;
4876: if (proc == rank) {
4877: len_s[proc] = 0;
4878: } else {
4879: PetscCall(PetscMPIIntCast(owners[proc + 1] - owners[proc] + 1, &len_si[proc]));
4880: PetscCall(PetscMPIIntCast(ai[owners[proc + 1]] - ai[owners[proc]], &len_s[proc])); /* num of rows to be sent to [proc] */
4881: }
4882: if (len_s[proc]) {
4883: merge->nsend++;
4884: nrows = 0;
4885: for (i = owners[proc]; i < owners[proc + 1]; i++) {
4886: if (ai[i + 1] > ai[i]) nrows++;
4887: }
4888: PetscCall(PetscMPIIntCast(2 * (nrows + 1), &len_si[proc]));
4889: len += len_si[proc];
4890: }
4891: }
4893: /* determine the number and length of messages to receive for ij-structure */
4894: PetscCall(PetscGatherNumberOfMessages(comm, NULL, len_s, &merge->nrecv));
4895: PetscCall(PetscGatherMessageLengths2(comm, merge->nsend, merge->nrecv, len_s, len_si, &merge->id_r, &merge->len_r, &len_ri));
4897: /* post the Irecv of j-structure */
4898: PetscCall(PetscCommGetNewTag(comm, &tagj));
4899: PetscCall(PetscPostIrecvInt(comm, tagj, merge->nrecv, merge->id_r, merge->len_r, &buf_rj, &rj_waits));
4901: /* post the Isend of j-structure */
4902: PetscCall(PetscMalloc2(merge->nsend, &si_waits, merge->nsend, &sj_waits));
4904: for (PetscMPIInt proc = 0, k = 0; proc < size; proc++) {
4905: if (!len_s[proc]) continue;
4906: i = owners[proc];
4907: PetscCallMPI(MPIU_Isend(aj + ai[i], len_s[proc], MPIU_INT, proc, tagj, comm, sj_waits + k));
4908: k++;
4909: }
4911: /* receives and sends of j-structure are complete */
4912: if (merge->nrecv) PetscCallMPI(MPI_Waitall(merge->nrecv, rj_waits, status));
4913: if (merge->nsend) PetscCallMPI(MPI_Waitall(merge->nsend, sj_waits, status));
4915: /* send and recv i-structure */
4916: PetscCall(PetscCommGetNewTag(comm, &tagi));
4917: PetscCall(PetscPostIrecvInt(comm, tagi, merge->nrecv, merge->id_r, len_ri, &buf_ri, &ri_waits));
4919: PetscCall(PetscMalloc1(len + 1, &buf_s));
4920: buf_si = buf_s; /* points to the beginning of k-th msg to be sent */
4921: for (PetscMPIInt proc = 0, k = 0; proc < size; proc++) {
4922: if (!len_s[proc]) continue;
4923: /* form outgoing message for i-structure:
4924: buf_si[0]: nrows to be sent
4925: [1:nrows]: row index (global)
4926: [nrows+1:2*nrows+1]: i-structure index
4927: */
4928: nrows = len_si[proc] / 2 - 1;
4929: buf_si_i = buf_si + nrows + 1;
4930: buf_si[0] = nrows;
4931: buf_si_i[0] = 0;
4932: nrows = 0;
4933: for (i = owners[proc]; i < owners[proc + 1]; i++) {
4934: anzi = ai[i + 1] - ai[i];
4935: if (anzi) {
4936: buf_si_i[nrows + 1] = buf_si_i[nrows] + anzi; /* i-structure */
4937: buf_si[nrows + 1] = i - owners[proc]; /* local row index */
4938: nrows++;
4939: }
4940: }
4941: PetscCallMPI(MPIU_Isend(buf_si, len_si[proc], MPIU_INT, proc, tagi, comm, si_waits + k));
4942: k++;
4943: buf_si += len_si[proc];
4944: }
4946: if (merge->nrecv) PetscCallMPI(MPI_Waitall(merge->nrecv, ri_waits, status));
4947: if (merge->nsend) PetscCallMPI(MPI_Waitall(merge->nsend, si_waits, status));
4949: PetscCall(PetscInfo(seqmat, "nsend: %d, nrecv: %d\n", merge->nsend, merge->nrecv));
4950: 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]));
4952: PetscCall(PetscFree(len_si));
4953: PetscCall(PetscFree(len_ri));
4954: PetscCall(PetscFree(rj_waits));
4955: PetscCall(PetscFree2(si_waits, sj_waits));
4956: PetscCall(PetscFree(ri_waits));
4957: PetscCall(PetscFree(buf_s));
4958: PetscCall(PetscFree(status));
4960: /* compute a local seq matrix in each processor */
4961: /* allocate bi array and free space for accumulating nonzero column info */
4962: PetscCall(PetscMalloc1(m + 1, &bi));
4963: bi[0] = 0;
4965: /* create and initialize a linked list */
4966: nlnk = N + 1;
4967: PetscCall(PetscLLCreate(N, N, nlnk, lnk, lnkbt));
4969: /* initial FreeSpace size is 2*(num of local nnz(seqmat)) */
4970: len = ai[owners[rank + 1]] - ai[owners[rank]];
4971: PetscCall(PetscFreeSpaceGet(PetscIntMultTruncate(2, len) + 1, &free_space));
4973: current_space = free_space;
4975: /* determine symbolic info for each local row */
4976: PetscCall(PetscMalloc3(merge->nrecv, &buf_ri_k, merge->nrecv, &nextrow, merge->nrecv, &nextai));
4978: for (k = 0; k < merge->nrecv; k++) {
4979: buf_ri_k[k] = buf_ri[k]; /* beginning of k-th recved i-structure */
4980: nrows = *buf_ri_k[k];
4981: nextrow[k] = buf_ri_k[k] + 1; /* next row number of k-th recved i-structure */
4982: nextai[k] = buf_ri_k[k] + (nrows + 1); /* points to the next i-structure of k-th recved i-structure */
4983: }
4985: MatPreallocateBegin(comm, m, n, dnz, onz);
4986: len = 0;
4987: for (i = 0; i < m; i++) {
4988: bnzi = 0;
4989: /* add local non-zero cols of this proc's seqmat into lnk */
4990: arow = owners[rank] + i;
4991: anzi = ai[arow + 1] - ai[arow];
4992: aj = a->j + ai[arow];
4993: PetscCall(PetscLLAddSorted(anzi, aj, N, &nlnk, lnk, lnkbt));
4994: bnzi += nlnk;
4995: /* add received col data into lnk */
4996: for (k = 0; k < merge->nrecv; k++) { /* k-th received message */
4997: if (i == *nextrow[k]) { /* i-th row */
4998: anzi = *(nextai[k] + 1) - *nextai[k];
4999: aj = buf_rj[k] + *nextai[k];
5000: PetscCall(PetscLLAddSorted(anzi, aj, N, &nlnk, lnk, lnkbt));
5001: bnzi += nlnk;
5002: nextrow[k]++;
5003: nextai[k]++;
5004: }
5005: }
5006: if (len < bnzi) len = bnzi; /* =max(bnzi) */
5008: /* if free space is not available, make more free space */
5009: if (current_space->local_remaining < bnzi) PetscCall(PetscFreeSpaceGet(PetscIntSumTruncate(bnzi, current_space->total_array_size), ¤t_space));
5010: /* copy data into free space, then initialize lnk */
5011: PetscCall(PetscLLClean(N, N, bnzi, lnk, current_space->array, lnkbt));
5012: PetscCall(MatPreallocateSet(i + owners[rank], bnzi, current_space->array, dnz, onz));
5014: current_space->array += bnzi;
5015: current_space->local_used += bnzi;
5016: current_space->local_remaining -= bnzi;
5018: bi[i + 1] = bi[i] + bnzi;
5019: }
5021: PetscCall(PetscFree3(buf_ri_k, nextrow, nextai));
5023: PetscCall(PetscMalloc1(bi[m], &bj));
5024: PetscCall(PetscFreeSpaceContiguous(&free_space, bj));
5025: PetscCall(PetscLLDestroy(lnk, lnkbt));
5027: /* create symbolic parallel matrix B_mpi */
5028: PetscCall(MatGetBlockSizes(seqmat, &bs, &cbs));
5029: PetscCall(MatCreate(comm, &B_mpi));
5030: if (n == PETSC_DECIDE) PetscCall(MatSetSizes(B_mpi, m, n, PETSC_DETERMINE, N));
5031: else PetscCall(MatSetSizes(B_mpi, m, n, PETSC_DETERMINE, PETSC_DETERMINE));
5032: PetscCall(MatSetBlockSizes(B_mpi, bs, cbs));
5033: PetscCall(MatSetType(B_mpi, MATMPIAIJ));
5034: PetscCall(MatMPIAIJSetPreallocation(B_mpi, 0, dnz, 0, onz));
5035: MatPreallocateEnd(dnz, onz);
5036: PetscCall(MatSetOption(B_mpi, MAT_NEW_NONZERO_ALLOCATION_ERR, PETSC_FALSE));
5038: /* B_mpi is not ready for use - assembly will be done by MatCreateMPIAIJSumSeqAIJNumeric() */
5039: B_mpi->assembled = PETSC_FALSE;
5040: merge->bi = bi;
5041: merge->bj = bj;
5042: merge->buf_ri = buf_ri;
5043: merge->buf_rj = buf_rj;
5044: merge->coi = NULL;
5045: merge->coj = NULL;
5046: merge->owners_co = NULL;
5048: PetscCall(PetscCommDestroy(&comm));
5050: /* attach the supporting struct to B_mpi for reuse */
5051: PetscCall(PetscContainerCreate(PETSC_COMM_SELF, &container));
5052: PetscCall(PetscContainerSetPointer(container, merge));
5053: PetscCall(PetscContainerSetCtxDestroy(container, MatMergeSeqsToMPIDestroy));
5054: PetscCall(PetscObjectCompose((PetscObject)B_mpi, "MatMergeSeqsToMPI", (PetscObject)container));
5055: PetscCall(PetscContainerDestroy(&container));
5056: *mpimat = B_mpi;
5058: PetscCall(PetscLogEventEnd(MAT_Seqstompisym, seqmat, 0, 0, 0));
5059: PetscFunctionReturn(PETSC_SUCCESS);
5060: }
5062: /*@
5063: MatCreateMPIAIJSumSeqAIJ - Creates a `MATMPIAIJ` matrix by adding sequential
5064: matrices from each processor
5066: Collective
5068: Input Parameters:
5069: + comm - the communicators the parallel matrix will live on
5070: . seqmat - the input sequential matrices
5071: . m - number of local rows (or `PETSC_DECIDE`)
5072: . n - number of local columns (or `PETSC_DECIDE`)
5073: - scall - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`
5075: Output Parameter:
5076: . mpimat - the parallel matrix generated
5078: Level: advanced
5080: Note:
5081: The dimensions of the sequential matrix in each processor MUST be the same.
5082: The input seqmat is included into the container `MatMergeSeqsToMPIDestroy`, and will be
5083: destroyed when `mpimat` is destroyed. Call `PetscObjectQuery()` to access `seqmat`.
5085: .seealso: [](ch_matrices), `Mat`, `MatCreateAIJ()`
5086: @*/
5087: PetscErrorCode MatCreateMPIAIJSumSeqAIJ(MPI_Comm comm, Mat seqmat, PetscInt m, PetscInt n, MatReuse scall, Mat *mpimat)
5088: {
5089: PetscMPIInt size;
5091: PetscFunctionBegin;
5092: PetscCallMPI(MPI_Comm_size(comm, &size));
5093: if (size == 1) {
5094: PetscCall(PetscLogEventBegin(MAT_Seqstompi, seqmat, 0, 0, 0));
5095: if (scall == MAT_INITIAL_MATRIX) PetscCall(MatDuplicate(seqmat, MAT_COPY_VALUES, mpimat));
5096: else PetscCall(MatCopy(seqmat, *mpimat, SAME_NONZERO_PATTERN));
5097: PetscCall(PetscLogEventEnd(MAT_Seqstompi, seqmat, 0, 0, 0));
5098: PetscFunctionReturn(PETSC_SUCCESS);
5099: }
5100: PetscCall(PetscLogEventBegin(MAT_Seqstompi, seqmat, 0, 0, 0));
5101: if (scall == MAT_INITIAL_MATRIX) PetscCall(MatCreateMPIAIJSumSeqAIJSymbolic(comm, seqmat, m, n, mpimat));
5102: PetscCall(MatCreateMPIAIJSumSeqAIJNumeric(seqmat, *mpimat));
5103: PetscCall(PetscLogEventEnd(MAT_Seqstompi, seqmat, 0, 0, 0));
5104: PetscFunctionReturn(PETSC_SUCCESS);
5105: }
5107: /*@
5108: MatAIJGetLocalMat - Creates a `MATSEQAIJ` from a `MATAIJ` matrix.
5110: Not Collective
5112: Input Parameter:
5113: . A - the matrix
5115: Output Parameter:
5116: . A_loc - the local sequential matrix generated
5118: Level: developer
5120: Notes:
5121: The matrix is created by taking `A`'s local rows and putting them into a sequential matrix
5122: with `mlocal` rows and `n` columns. Where `mlocal` is obtained with `MatGetLocalSize()` and
5123: `n` is the global column count obtained with `MatGetSize()`
5125: In other words combines the two parts of a parallel `MATMPIAIJ` matrix on each process to a single matrix.
5127: For parallel matrices this creates an entirely new matrix. If the matrix is sequential it merely increases the reference count.
5129: Destroy the matrix with `MatDestroy()`
5131: .seealso: [](ch_matrices), `Mat`, `MatMPIAIJGetLocalMat()`
5132: @*/
5133: PetscErrorCode MatAIJGetLocalMat(Mat A, Mat *A_loc)
5134: {
5135: PetscBool mpi;
5137: PetscFunctionBegin;
5138: PetscCall(PetscObjectTypeCompare((PetscObject)A, MATMPIAIJ, &mpi));
5139: if (mpi) PetscCall(MatMPIAIJGetLocalMat(A, MAT_INITIAL_MATRIX, A_loc));
5140: else {
5141: *A_loc = A;
5142: PetscCall(PetscObjectReference((PetscObject)*A_loc));
5143: }
5144: PetscFunctionReturn(PETSC_SUCCESS);
5145: }
5147: /*@
5148: MatMPIAIJGetLocalMat - Creates a `MATSEQAIJ` from a `MATMPIAIJ` matrix.
5150: Not Collective
5152: Input Parameters:
5153: + A - the matrix
5154: - scall - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`
5156: Output Parameter:
5157: . A_loc - the local sequential matrix generated
5159: Level: developer
5161: Notes:
5162: The matrix is created by taking all `A`'s local rows and putting them into a sequential
5163: matrix with `mlocal` rows and `n` columns.`mlocal` is the row count obtained with
5164: `MatGetLocalSize()` and `n` is the global column count obtained with `MatGetSize()`.
5166: In other words combines the two parts of a parallel `MATMPIAIJ` matrix on each process to a single matrix.
5168: When `A` is sequential and `MAT_INITIAL_MATRIX` is requested, the matrix returned is the diagonal part of `A` (which contains the entire matrix),
5169: 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
5170: then `MatCopy`(Adiag,*`A_loc`,`SAME_NONZERO_PATTERN`) is called to fill `A_loc`. Thus one can preallocate the appropriate sequential matrix `A_loc`
5171: 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.
5173: .seealso: [](ch_matrices), `Mat`, `MATMPIAIJ`, `MatGetOwnershipRange()`, `MatMPIAIJGetLocalMatCondensed()`, `MatMPIAIJGetLocalMatMerge()`
5174: @*/
5175: PetscErrorCode MatMPIAIJGetLocalMat(Mat A, MatReuse scall, Mat *A_loc)
5176: {
5177: PetscFunctionBegin;
5178: PetscCall(MatMPIAIJGetLocalMat_Private(A, scall, PETSC_FALSE, A_loc));
5179: PetscFunctionReturn(PETSC_SUCCESS);
5180: }
5182: PetscErrorCode MatMPIAIJGetLocalMat_Private(Mat A, MatReuse scall, PetscBool structure_only, Mat *A_loc)
5183: {
5184: Mat_MPIAIJ *mpimat = (Mat_MPIAIJ *)A->data;
5185: Mat_SeqAIJ *mat, *a, *b;
5186: PetscInt *ai, *aj, *bi, *bj, *cmap = mpimat->garray;
5187: const PetscScalar *aa, *ba, *aav = NULL, *bav = NULL;
5188: PetscScalar *ca = NULL, *cam;
5189: PetscMPIInt size;
5190: PetscInt am = A->rmap->n, i, j, k, cstart = A->cmap->rstart;
5191: PetscInt *ci, *cj, col, ncols_d, ncols_o, jo;
5192: PetscBool match;
5194: PetscFunctionBegin;
5195: PetscCheck(!structure_only || scall == MAT_INITIAL_MATRIX, PETSC_COMM_SELF, PETSC_ERR_SUP, "Structure-only extraction requires MAT_INITIAL_MATRIX");
5196: PetscCall(PetscStrbeginswith(((PetscObject)A)->type_name, MATMPIAIJ, &match));
5197: PetscCheck(match, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "Requires MATMPIAIJ matrix as input");
5198: PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)A), &size));
5199: if (size == 1 && !structure_only) {
5200: if (scall == MAT_INITIAL_MATRIX) {
5201: PetscCall(PetscObjectReference((PetscObject)mpimat->A));
5202: *A_loc = mpimat->A;
5203: } else if (scall == MAT_REUSE_MATRIX) PetscCall(MatCopy(mpimat->A, *A_loc, SAME_NONZERO_PATTERN));
5204: PetscFunctionReturn(PETSC_SUCCESS);
5205: }
5207: PetscCall(PetscLogEventBegin(MAT_Getlocalmat, A, 0, 0, 0));
5208: a = (Mat_SeqAIJ *)mpimat->A->data;
5209: b = (Mat_SeqAIJ *)mpimat->B->data;
5210: ai = a->i;
5211: aj = a->j;
5212: bi = b->i;
5213: bj = b->j;
5214: if (!structure_only) {
5215: PetscCall(MatSeqAIJGetArrayRead(mpimat->A, &aav));
5216: PetscCall(MatSeqAIJGetArrayRead(mpimat->B, &bav));
5217: }
5218: aa = aav;
5219: ba = bav;
5220: if (scall == MAT_INITIAL_MATRIX) {
5221: PetscCall(PetscMalloc1(1 + am, &ci));
5222: ci[0] = 0;
5223: for (i = 0; i < am; i++) ci[i + 1] = ci[i] + (ai[i + 1] - ai[i]) + (bi[i + 1] - bi[i]);
5224: PetscCall(PetscMalloc1(ci[am], &cj));
5225: if (!structure_only) PetscCall(PetscMalloc1(ci[am], &ca));
5226: k = 0;
5227: for (i = 0; i < am; i++) {
5228: ncols_o = bi[i + 1] - bi[i];
5229: ncols_d = ai[i + 1] - ai[i];
5230: /* off-diagonal portion of A */
5231: for (jo = 0; jo < ncols_o; jo++, bj++, k++) {
5232: col = cmap[*bj];
5233: if (col >= cstart) break;
5234: cj[k] = col;
5235: if (!structure_only) ca[k] = *ba++;
5236: }
5237: /* diagonal portion of A */
5238: for (j = 0; j < ncols_d; j++, k++) {
5239: cj[k] = cstart + *aj++;
5240: if (!structure_only) ca[k] = *aa++;
5241: }
5242: /* off-diagonal portion of A */
5243: for (j = jo; j < ncols_o; j++, k++) {
5244: cj[k] = cmap[*bj++];
5245: if (!structure_only) ca[k] = *ba++;
5246: }
5247: }
5248: /* put together the new matrix */
5249: PetscCall(MatCreateSeqAIJWithArrays(PETSC_COMM_SELF, am, A->cmap->N, ci, cj, ca, A_loc));
5250: PetscCall(MatSetOption(*A_loc, MAT_STRUCTURE_ONLY, structure_only));
5251: /* MatCreateSeqAIJWithArrays flags matrix so PETSc doesn't free the user's arrays. */
5252: /* Since these are PETSc arrays, change flags to free them as necessary. */
5253: mat = (Mat_SeqAIJ *)(*A_loc)->data;
5254: mat->free_a = PETSC_TRUE;
5255: mat->free_ij = PETSC_TRUE;
5256: mat->nonew = 0;
5257: } else if (scall == MAT_REUSE_MATRIX) {
5258: mat = (Mat_SeqAIJ *)(*A_loc)->data;
5259: ci = mat->i;
5260: cj = mat->j;
5261: PetscCall(MatSeqAIJGetArrayWrite(*A_loc, &cam));
5262: for (i = 0; i < am; i++) {
5263: /* off-diagonal portion of A */
5264: ncols_o = bi[i + 1] - bi[i];
5265: for (jo = 0; jo < ncols_o; jo++, bj++) {
5266: col = cmap[*bj];
5267: if (col >= cstart) break;
5268: *cam++ = *ba++;
5269: }
5270: /* diagonal portion of A */
5271: ncols_d = ai[i + 1] - ai[i];
5272: for (j = 0; j < ncols_d; j++) *cam++ = *aa++;
5273: /* off-diagonal portion of A */
5274: for (j = jo; j < ncols_o; j++, bj++) *cam++ = *ba++;
5275: }
5276: PetscCall(MatSeqAIJRestoreArrayWrite(*A_loc, &cam));
5277: } else SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Invalid MatReuse %d", (int)scall);
5278: if (!structure_only) {
5279: PetscCall(MatSeqAIJRestoreArrayRead(mpimat->A, &aav));
5280: PetscCall(MatSeqAIJRestoreArrayRead(mpimat->B, &bav));
5281: }
5282: PetscCall(PetscLogEventEnd(MAT_Getlocalmat, A, 0, 0, 0));
5283: PetscFunctionReturn(PETSC_SUCCESS);
5284: }
5286: /*@
5287: MatMPIAIJGetLocalMatMerge - Creates a `MATSEQAIJ` from a `MATMPIAIJ` matrix by taking all its local rows and putting them into a sequential matrix with
5288: mlocal rows and n columns. Where n is the sum of the number of columns of the diagonal and off-diagonal part
5290: Not Collective
5292: Input Parameters:
5293: + A - the matrix
5294: - scall - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`
5296: Output Parameters:
5297: + glob - sequential `IS` with global indices associated with the columns of the local sequential matrix generated (can be `NULL`)
5298: - A_loc - the local sequential matrix generated
5300: Level: developer
5302: Note:
5303: This is different from `MatMPIAIJGetLocalMat()` since the first columns in the returning matrix are those associated with the diagonal
5304: part, then those associated with the off-diagonal part (in its local ordering)
5306: .seealso: [](ch_matrices), `Mat`, `MATMPIAIJ`, `MatGetOwnershipRange()`, `MatMPIAIJGetLocalMat()`, `MatMPIAIJGetLocalMatCondensed()`
5307: @*/
5308: PetscErrorCode MatMPIAIJGetLocalMatMerge(Mat A, MatReuse scall, IS *glob, Mat *A_loc)
5309: {
5310: Mat Ao, Ad;
5311: const PetscInt *cmap;
5312: PetscMPIInt size;
5313: PetscErrorCode (*f)(Mat, MatReuse, IS *, Mat *);
5315: PetscFunctionBegin;
5316: PetscCall(MatMPIAIJGetSeqAIJ(A, &Ad, &Ao, &cmap));
5317: PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)A), &size));
5318: if (size == 1) {
5319: if (scall == MAT_INITIAL_MATRIX) {
5320: PetscCall(PetscObjectReference((PetscObject)Ad));
5321: *A_loc = Ad;
5322: } else if (scall == MAT_REUSE_MATRIX) {
5323: PetscCall(MatCopy(Ad, *A_loc, SAME_NONZERO_PATTERN));
5324: }
5325: if (glob) PetscCall(ISCreateStride(PetscObjectComm((PetscObject)Ad), Ad->cmap->n, Ad->cmap->rstart, 1, glob));
5326: PetscFunctionReturn(PETSC_SUCCESS);
5327: }
5328: PetscCall(PetscObjectQueryFunction((PetscObject)A, "MatMPIAIJGetLocalMatMerge_C", &f));
5329: PetscCall(PetscLogEventBegin(MAT_Getlocalmat, A, 0, 0, 0));
5330: if (f) PetscCall((*f)(A, scall, glob, A_loc));
5331: else {
5332: Mat_SeqAIJ *a = (Mat_SeqAIJ *)Ad->data;
5333: Mat_SeqAIJ *b = (Mat_SeqAIJ *)Ao->data;
5334: Mat_SeqAIJ *c;
5335: PetscInt *ai = a->i, *aj = a->j;
5336: PetscInt *bi = b->i, *bj = b->j;
5337: PetscInt *ci, *cj;
5338: const PetscScalar *aa, *ba;
5339: PetscScalar *ca;
5340: PetscInt i, j, am, dn, on;
5342: PetscCall(MatGetLocalSize(Ad, &am, &dn));
5343: PetscCall(MatGetLocalSize(Ao, NULL, &on));
5344: PetscCall(MatSeqAIJGetArrayRead(Ad, &aa));
5345: PetscCall(MatSeqAIJGetArrayRead(Ao, &ba));
5346: if (scall == MAT_INITIAL_MATRIX) {
5347: PetscInt k;
5348: PetscCall(PetscMalloc1(1 + am, &ci));
5349: PetscCall(PetscMalloc1(ai[am] + bi[am], &cj));
5350: PetscCall(PetscMalloc1(ai[am] + bi[am], &ca));
5351: ci[0] = 0;
5352: for (i = 0, k = 0; i < am; i++) {
5353: const PetscInt ncols_o = bi[i + 1] - bi[i];
5354: const PetscInt ncols_d = ai[i + 1] - ai[i];
5355: ci[i + 1] = ci[i] + ncols_o + ncols_d;
5356: /* diagonal portion of A */
5357: for (j = 0; j < ncols_d; j++, k++) {
5358: cj[k] = *aj++;
5359: ca[k] = *aa++;
5360: }
5361: /* off-diagonal portion of A */
5362: for (j = 0; j < ncols_o; j++, k++) {
5363: cj[k] = dn + *bj++;
5364: ca[k] = *ba++;
5365: }
5366: }
5367: /* put together the new matrix */
5368: PetscCall(MatCreateSeqAIJWithArrays(PETSC_COMM_SELF, am, dn + on, ci, cj, ca, A_loc));
5369: /* MatCreateSeqAIJWithArrays flags matrix so PETSc doesn't free the user's arrays. */
5370: /* Since these are PETSc arrays, change flags to free them as necessary. */
5371: c = (Mat_SeqAIJ *)(*A_loc)->data;
5372: c->free_a = PETSC_TRUE;
5373: c->free_ij = PETSC_TRUE;
5374: c->nonew = 0;
5375: PetscCall(MatSetType(*A_loc, ((PetscObject)Ad)->type_name));
5376: } else if (scall == MAT_REUSE_MATRIX) {
5377: PetscCall(MatSeqAIJGetArrayWrite(*A_loc, &ca));
5378: for (i = 0; i < am; i++) {
5379: const PetscInt ncols_d = ai[i + 1] - ai[i];
5380: const PetscInt ncols_o = bi[i + 1] - bi[i];
5381: /* diagonal portion of A */
5382: for (j = 0; j < ncols_d; j++) *ca++ = *aa++;
5383: /* off-diagonal portion of A */
5384: for (j = 0; j < ncols_o; j++) *ca++ = *ba++;
5385: }
5386: PetscCall(MatSeqAIJRestoreArrayWrite(*A_loc, &ca));
5387: } else SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Invalid MatReuse %d", (int)scall);
5388: PetscCall(MatSeqAIJRestoreArrayRead(Ad, &aa));
5389: PetscCall(MatSeqAIJRestoreArrayRead(Ao, &aa));
5390: if (glob) {
5391: PetscInt cst, *gidx;
5393: PetscCall(MatGetOwnershipRangeColumn(A, &cst, NULL));
5394: PetscCall(PetscMalloc1(dn + on, &gidx));
5395: for (i = 0; i < dn; i++) gidx[i] = cst + i;
5396: for (i = 0; i < on; i++) gidx[i + dn] = cmap[i];
5397: PetscCall(ISCreateGeneral(PetscObjectComm((PetscObject)Ad), dn + on, gidx, PETSC_OWN_POINTER, glob));
5398: }
5399: }
5400: PetscCall(PetscLogEventEnd(MAT_Getlocalmat, A, 0, 0, 0));
5401: PetscFunctionReturn(PETSC_SUCCESS);
5402: }
5404: /*@
5405: MatMPIAIJGetLocalMatCondensed - Creates a `MATSEQAIJ` matrix from an `MATMPIAIJ` matrix by taking all its local rows and NON-ZERO columns
5407: Not Collective
5409: Input Parameters:
5410: + A - the matrix
5411: . scall - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`
5412: . row - index set of rows to extract (or `NULL`)
5413: - col - index set of columns to extract (or `NULL`)
5415: Output Parameter:
5416: . A_loc - the local sequential matrix generated
5418: Level: developer
5420: .seealso: [](ch_matrices), `Mat`, `MATMPIAIJ`, `MatGetOwnershipRange()`, `MatMPIAIJGetLocalMat()`
5421: @*/
5422: PetscErrorCode MatMPIAIJGetLocalMatCondensed(Mat A, MatReuse scall, IS *row, IS *col, Mat *A_loc)
5423: {
5424: Mat_MPIAIJ *a = (Mat_MPIAIJ *)A->data;
5425: PetscInt i, start, end, ncols, nzA, nzB, *cmap, imark, *idx;
5426: IS isrowa, iscola;
5427: Mat *aloc;
5428: PetscBool match;
5430: PetscFunctionBegin;
5431: PetscCall(PetscObjectTypeCompare((PetscObject)A, MATMPIAIJ, &match));
5432: PetscCheck(match, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "Requires MATMPIAIJ matrix as input");
5433: PetscCall(PetscLogEventBegin(MAT_Getlocalmatcondensed, A, 0, 0, 0));
5434: if (!row) {
5435: start = A->rmap->rstart;
5436: end = A->rmap->rend;
5437: PetscCall(ISCreateStride(PETSC_COMM_SELF, end - start, start, 1, &isrowa));
5438: } else {
5439: isrowa = *row;
5440: }
5441: if (!col) {
5442: start = A->cmap->rstart;
5443: cmap = a->garray;
5444: nzA = a->A->cmap->n;
5445: nzB = a->B->cmap->n;
5446: PetscCall(PetscMalloc1(nzA + nzB, &idx));
5447: ncols = 0;
5448: for (i = 0; i < nzB; i++) {
5449: if (cmap[i] < start) idx[ncols++] = cmap[i];
5450: else break;
5451: }
5452: imark = i;
5453: for (i = 0; i < nzA; i++) idx[ncols++] = start + i;
5454: for (i = imark; i < nzB; i++) idx[ncols++] = cmap[i];
5455: PetscCall(ISCreateGeneral(PETSC_COMM_SELF, ncols, idx, PETSC_OWN_POINTER, &iscola));
5456: } else iscola = *col;
5457: if (scall != MAT_INITIAL_MATRIX) {
5458: PetscCall(PetscMalloc1(1, &aloc));
5459: aloc[0] = *A_loc;
5460: }
5461: PetscCall(MatCreateSubMatrices(A, 1, &isrowa, &iscola, scall, &aloc));
5462: if (!col) { /* attach global id of condensed columns */
5463: PetscCall(PetscObjectCompose((PetscObject)aloc[0], "_petsc_GetLocalMatCondensed_iscol", (PetscObject)iscola));
5464: }
5465: *A_loc = aloc[0];
5466: PetscCall(PetscFree(aloc));
5467: if (!row) PetscCall(ISDestroy(&isrowa));
5468: if (!col) PetscCall(ISDestroy(&iscola));
5469: PetscCall(PetscLogEventEnd(MAT_Getlocalmatcondensed, A, 0, 0, 0));
5470: PetscFunctionReturn(PETSC_SUCCESS);
5471: }
5473: /*
5474: * Create a sequential AIJ matrix based on row indices. a whole column is extracted once a row is matched.
5475: * Row could be local or remote.The routine is designed to be scalable in memory so that nothing is based
5476: * on a global size.
5477: * */
5478: static PetscErrorCode MatCreateSeqSubMatrixWithRows_Private(Mat P, IS rows, Mat *P_oth)
5479: {
5480: Mat_MPIAIJ *p = (Mat_MPIAIJ *)P->data;
5481: Mat_SeqAIJ *pd = (Mat_SeqAIJ *)p->A->data, *po = (Mat_SeqAIJ *)p->B->data, *p_oth;
5482: PetscInt plocalsize, nrows, *ilocal, *oilocal, i, lidx, *nrcols, *nlcols, ncol;
5483: PetscMPIInt owner;
5484: PetscSFNode *iremote, *oiremote;
5485: const PetscInt *lrowindices;
5486: PetscSF sf, osf;
5487: PetscInt pcstart, *roffsets, *loffsets, *pnnz, j;
5488: PetscInt ontotalcols, dntotalcols, ntotalcols, nout;
5489: MPI_Comm comm;
5490: ISLocalToGlobalMapping mapping;
5491: const PetscScalar *pd_a, *po_a;
5493: PetscFunctionBegin;
5494: PetscCall(PetscObjectGetComm((PetscObject)P, &comm));
5495: /* plocalsize is the number of roots
5496: * nrows is the number of leaves
5497: * */
5498: PetscCall(MatGetLocalSize(P, &plocalsize, NULL));
5499: PetscCall(ISGetLocalSize(rows, &nrows));
5500: PetscCall(PetscCalloc1(nrows, &iremote));
5501: PetscCall(ISGetIndices(rows, &lrowindices));
5502: for (i = 0; i < nrows; i++) {
5503: /* Find a remote index and an owner for a row
5504: * The row could be local or remote
5505: * */
5506: owner = 0;
5507: lidx = 0;
5508: PetscCall(PetscLayoutFindOwnerIndex(P->rmap, lrowindices[i], &owner, &lidx));
5509: iremote[i].index = lidx;
5510: iremote[i].rank = owner;
5511: }
5512: /* Create SF to communicate how many nonzero columns for each row */
5513: PetscCall(PetscSFCreate(comm, &sf));
5514: /* SF will figure out the number of nonzero columns for each row, and their
5515: * offsets
5516: * */
5517: PetscCall(PetscSFSetGraph(sf, plocalsize, nrows, NULL, PETSC_OWN_POINTER, iremote, PETSC_OWN_POINTER));
5518: PetscCall(PetscSFSetFromOptions(sf));
5519: PetscCall(PetscSFSetUp(sf));
5521: PetscCall(PetscCalloc1(2 * (plocalsize + 1), &roffsets));
5522: PetscCall(PetscCalloc1(2 * plocalsize, &nrcols));
5523: PetscCall(PetscCalloc1(nrows, &pnnz));
5524: roffsets[0] = 0;
5525: roffsets[1] = 0;
5526: for (i = 0; i < plocalsize; i++) {
5527: /* diagonal */
5528: nrcols[i * 2 + 0] = pd->i[i + 1] - pd->i[i];
5529: /* off-diagonal */
5530: nrcols[i * 2 + 1] = po->i[i + 1] - po->i[i];
5531: /* compute offsets so that we relative location for each row */
5532: roffsets[(i + 1) * 2 + 0] = roffsets[i * 2 + 0] + nrcols[i * 2 + 0];
5533: roffsets[(i + 1) * 2 + 1] = roffsets[i * 2 + 1] + nrcols[i * 2 + 1];
5534: }
5535: PetscCall(PetscCalloc1(2 * nrows, &nlcols));
5536: PetscCall(PetscCalloc1(2 * nrows, &loffsets));
5537: /* 'r' means root, and 'l' means leaf */
5538: PetscCall(PetscSFBcastBegin(sf, MPIU_2INT, nrcols, nlcols, MPI_REPLACE));
5539: PetscCall(PetscSFBcastBegin(sf, MPIU_2INT, roffsets, loffsets, MPI_REPLACE));
5540: PetscCall(PetscSFBcastEnd(sf, MPIU_2INT, nrcols, nlcols, MPI_REPLACE));
5541: PetscCall(PetscSFBcastEnd(sf, MPIU_2INT, roffsets, loffsets, MPI_REPLACE));
5542: PetscCall(PetscSFDestroy(&sf));
5543: PetscCall(PetscFree(roffsets));
5544: PetscCall(PetscFree(nrcols));
5545: dntotalcols = 0;
5546: ontotalcols = 0;
5547: ncol = 0;
5548: for (i = 0; i < nrows; i++) {
5549: pnnz[i] = nlcols[i * 2 + 0] + nlcols[i * 2 + 1];
5550: ncol = PetscMax(pnnz[i], ncol);
5551: /* diagonal */
5552: dntotalcols += nlcols[i * 2 + 0];
5553: /* off-diagonal */
5554: ontotalcols += nlcols[i * 2 + 1];
5555: }
5556: /* We do not need to figure the right number of columns
5557: * since all the calculations will be done by going through the raw data
5558: * */
5559: PetscCall(MatCreateSeqAIJ(PETSC_COMM_SELF, nrows, ncol, 0, pnnz, P_oth));
5560: PetscCall(MatSetUp(*P_oth));
5561: PetscCall(PetscFree(pnnz));
5562: p_oth = (Mat_SeqAIJ *)(*P_oth)->data;
5563: /* diagonal */
5564: PetscCall(PetscCalloc1(dntotalcols, &iremote));
5565: /* off-diagonal */
5566: PetscCall(PetscCalloc1(ontotalcols, &oiremote));
5567: /* diagonal */
5568: PetscCall(PetscCalloc1(dntotalcols, &ilocal));
5569: /* off-diagonal */
5570: PetscCall(PetscCalloc1(ontotalcols, &oilocal));
5571: dntotalcols = 0;
5572: ontotalcols = 0;
5573: ntotalcols = 0;
5574: for (i = 0; i < nrows; i++) {
5575: owner = 0;
5576: PetscCall(PetscLayoutFindOwnerIndex(P->rmap, lrowindices[i], &owner, NULL));
5577: /* Set iremote for diag matrix */
5578: for (j = 0; j < nlcols[i * 2 + 0]; j++) {
5579: iremote[dntotalcols].index = loffsets[i * 2 + 0] + j;
5580: iremote[dntotalcols].rank = owner;
5581: /* P_oth is seqAIJ so that ilocal need to point to the first part of memory */
5582: ilocal[dntotalcols++] = ntotalcols++;
5583: }
5584: /* off-diagonal */
5585: for (j = 0; j < nlcols[i * 2 + 1]; j++) {
5586: oiremote[ontotalcols].index = loffsets[i * 2 + 1] + j;
5587: oiremote[ontotalcols].rank = owner;
5588: oilocal[ontotalcols++] = ntotalcols++;
5589: }
5590: }
5591: PetscCall(ISRestoreIndices(rows, &lrowindices));
5592: PetscCall(PetscFree(loffsets));
5593: PetscCall(PetscFree(nlcols));
5594: PetscCall(PetscSFCreate(comm, &sf));
5595: /* P serves as roots and P_oth is leaves
5596: * Diag matrix
5597: * */
5598: PetscCall(PetscSFSetGraph(sf, pd->i[plocalsize], dntotalcols, ilocal, PETSC_OWN_POINTER, iremote, PETSC_OWN_POINTER));
5599: PetscCall(PetscSFSetFromOptions(sf));
5600: PetscCall(PetscSFSetUp(sf));
5602: PetscCall(PetscSFCreate(comm, &osf));
5603: /* off-diagonal */
5604: PetscCall(PetscSFSetGraph(osf, po->i[plocalsize], ontotalcols, oilocal, PETSC_OWN_POINTER, oiremote, PETSC_OWN_POINTER));
5605: PetscCall(PetscSFSetFromOptions(osf));
5606: PetscCall(PetscSFSetUp(osf));
5607: PetscCall(MatSeqAIJGetArrayRead(p->A, &pd_a));
5608: PetscCall(MatSeqAIJGetArrayRead(p->B, &po_a));
5609: /* operate on the matrix internal data to save memory */
5610: PetscCall(PetscSFBcastBegin(sf, MPIU_SCALAR, pd_a, p_oth->a, MPI_REPLACE));
5611: PetscCall(PetscSFBcastBegin(osf, MPIU_SCALAR, po_a, p_oth->a, MPI_REPLACE));
5612: PetscCall(MatGetOwnershipRangeColumn(P, &pcstart, NULL));
5613: /* Convert to global indices for diag matrix */
5614: for (i = 0; i < pd->i[plocalsize]; i++) pd->j[i] += pcstart;
5615: PetscCall(PetscSFBcastBegin(sf, MPIU_INT, pd->j, p_oth->j, MPI_REPLACE));
5616: /* We want P_oth store global indices */
5617: PetscCall(ISLocalToGlobalMappingCreate(comm, 1, p->B->cmap->n, p->garray, PETSC_COPY_VALUES, &mapping));
5618: /* Use memory scalable approach */
5619: PetscCall(ISLocalToGlobalMappingSetType(mapping, ISLOCALTOGLOBALMAPPINGHASH));
5620: PetscCall(ISLocalToGlobalMappingApply(mapping, po->i[plocalsize], po->j, po->j));
5621: PetscCall(PetscSFBcastBegin(osf, MPIU_INT, po->j, p_oth->j, MPI_REPLACE));
5622: PetscCall(PetscSFBcastEnd(sf, MPIU_INT, pd->j, p_oth->j, MPI_REPLACE));
5623: /* Convert back to local indices */
5624: for (i = 0; i < pd->i[plocalsize]; i++) pd->j[i] -= pcstart;
5625: PetscCall(PetscSFBcastEnd(osf, MPIU_INT, po->j, p_oth->j, MPI_REPLACE));
5626: nout = 0;
5627: PetscCall(ISGlobalToLocalMappingApply(mapping, IS_GTOLM_DROP, po->i[plocalsize], po->j, &nout, po->j));
5628: PetscCheck(nout == po->i[plocalsize], comm, PETSC_ERR_ARG_INCOMP, "n %" PetscInt_FMT " does not equal to nout %" PetscInt_FMT " ", po->i[plocalsize], nout);
5629: PetscCall(ISLocalToGlobalMappingDestroy(&mapping));
5630: /* Exchange values */
5631: PetscCall(PetscSFBcastEnd(sf, MPIU_SCALAR, pd_a, p_oth->a, MPI_REPLACE));
5632: PetscCall(PetscSFBcastEnd(osf, MPIU_SCALAR, po_a, p_oth->a, MPI_REPLACE));
5633: PetscCall(MatSeqAIJRestoreArrayRead(p->A, &pd_a));
5634: PetscCall(MatSeqAIJRestoreArrayRead(p->B, &po_a));
5635: /* Stop PETSc from shrinking memory */
5636: for (i = 0; i < nrows; i++) p_oth->ilen[i] = p_oth->imax[i];
5637: PetscCall(MatAssemblyBegin(*P_oth, MAT_FINAL_ASSEMBLY));
5638: PetscCall(MatAssemblyEnd(*P_oth, MAT_FINAL_ASSEMBLY));
5639: /* Attach PetscSF objects to P_oth so that we can reuse it later */
5640: PetscCall(PetscObjectCompose((PetscObject)*P_oth, "diagsf", (PetscObject)sf));
5641: PetscCall(PetscObjectCompose((PetscObject)*P_oth, "offdiagsf", (PetscObject)osf));
5642: PetscCall(PetscSFDestroy(&sf));
5643: PetscCall(PetscSFDestroy(&osf));
5644: PetscFunctionReturn(PETSC_SUCCESS);
5645: }
5647: /*
5648: * Creates a SeqAIJ matrix by taking rows of B that equal to nonzero columns of local A
5649: * This supports MPIAIJ and MAIJ
5650: * */
5651: PetscErrorCode MatGetBrowsOfAcols_MPIXAIJ(Mat A, Mat P, PetscInt dof, MatReuse reuse, Mat *P_oth)
5652: {
5653: Mat_MPIAIJ *a = (Mat_MPIAIJ *)A->data, *p = (Mat_MPIAIJ *)P->data;
5654: Mat_SeqAIJ *p_oth;
5655: IS rows, map;
5656: PetscHMapI hamp;
5657: PetscInt i, htsize, *rowindices, off, *mapping, key, count;
5658: MPI_Comm comm;
5659: PetscSF sf, osf;
5660: PetscBool has;
5662: PetscFunctionBegin;
5663: PetscCall(PetscObjectGetComm((PetscObject)A, &comm));
5664: PetscCall(PetscLogEventBegin(MAT_GetBrowsOfAocols, A, P, 0, 0));
5665: /* If it is the first time, create an index set of off-diag nonzero columns of A,
5666: * and then create a submatrix (that often is an overlapping matrix)
5667: * */
5668: if (reuse == MAT_INITIAL_MATRIX) {
5669: /* Use a hash table to figure out unique keys */
5670: PetscCall(PetscHMapICreateWithSize(a->B->cmap->n, &hamp));
5671: PetscCall(PetscCalloc1(a->B->cmap->n, &mapping));
5672: count = 0;
5673: /* Assume that a->g is sorted, otherwise the following does not make sense */
5674: for (i = 0; i < a->B->cmap->n; i++) {
5675: key = a->garray[i] / dof;
5676: PetscCall(PetscHMapIHas(hamp, key, &has));
5677: if (!has) {
5678: mapping[i] = count;
5679: PetscCall(PetscHMapISet(hamp, key, count++));
5680: } else {
5681: /* Current 'i' has the same value the previous step */
5682: mapping[i] = count - 1;
5683: }
5684: }
5685: PetscCall(ISCreateGeneral(comm, a->B->cmap->n, mapping, PETSC_OWN_POINTER, &map));
5686: PetscCall(PetscHMapIGetSize(hamp, &htsize));
5687: PetscCheck(htsize == count, comm, PETSC_ERR_ARG_INCOMP, " Size of hash map %" PetscInt_FMT " is inconsistent with count %" PetscInt_FMT, htsize, count);
5688: PetscCall(PetscCalloc1(htsize, &rowindices));
5689: off = 0;
5690: PetscCall(PetscHMapIGetKeys(hamp, &off, rowindices));
5691: PetscCall(PetscHMapIDestroy(&hamp));
5692: PetscCall(PetscSortInt(htsize, rowindices));
5693: PetscCall(ISCreateGeneral(comm, htsize, rowindices, PETSC_OWN_POINTER, &rows));
5694: /* In case, the matrix was already created but users want to recreate the matrix */
5695: PetscCall(MatDestroy(P_oth));
5696: PetscCall(MatCreateSeqSubMatrixWithRows_Private(P, rows, P_oth));
5697: PetscCall(PetscObjectCompose((PetscObject)*P_oth, "aoffdiagtopothmapping", (PetscObject)map));
5698: PetscCall(ISDestroy(&map));
5699: PetscCall(ISDestroy(&rows));
5700: } else if (reuse == MAT_REUSE_MATRIX) {
5701: /* If matrix was already created, we simply update values using SF objects
5702: * that as attached to the matrix earlier.
5703: */
5704: const PetscScalar *pd_a, *po_a;
5706: PetscCall(PetscObjectQuery((PetscObject)*P_oth, "diagsf", (PetscObject *)&sf));
5707: PetscCall(PetscObjectQuery((PetscObject)*P_oth, "offdiagsf", (PetscObject *)&osf));
5708: PetscCheck(sf && osf, comm, PETSC_ERR_ARG_NULL, "Matrix is not initialized yet");
5709: p_oth = (Mat_SeqAIJ *)(*P_oth)->data;
5710: /* Update values in place */
5711: PetscCall(MatSeqAIJGetArrayRead(p->A, &pd_a));
5712: PetscCall(MatSeqAIJGetArrayRead(p->B, &po_a));
5713: PetscCall(PetscSFBcastBegin(sf, MPIU_SCALAR, pd_a, p_oth->a, MPI_REPLACE));
5714: PetscCall(PetscSFBcastBegin(osf, MPIU_SCALAR, po_a, p_oth->a, MPI_REPLACE));
5715: PetscCall(PetscSFBcastEnd(sf, MPIU_SCALAR, pd_a, p_oth->a, MPI_REPLACE));
5716: PetscCall(PetscSFBcastEnd(osf, MPIU_SCALAR, po_a, p_oth->a, MPI_REPLACE));
5717: PetscCall(MatSeqAIJRestoreArrayRead(p->A, &pd_a));
5718: PetscCall(MatSeqAIJRestoreArrayRead(p->B, &po_a));
5719: } else SETERRQ(comm, PETSC_ERR_ARG_UNKNOWN_TYPE, "Unknown reuse type");
5720: PetscCall(PetscLogEventEnd(MAT_GetBrowsOfAocols, A, P, 0, 0));
5721: PetscFunctionReturn(PETSC_SUCCESS);
5722: }
5724: /*@
5725: MatGetBrowsOfAcols - Returns `IS` that contain rows of `B` that equal to nonzero columns of local `A`
5727: Collective
5729: Input Parameters:
5730: + A - the first matrix in `MATMPIAIJ` format
5731: . B - the second matrix in `MATMPIAIJ` format
5732: - scall - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`
5734: Output Parameters:
5735: + rowb - On input index sets of rows of B to extract (or `NULL`), modified on output
5736: . colb - On input index sets of columns of B to extract (or `NULL`), modified on output
5737: - B_seq - the sequential matrix generated
5739: Level: developer
5741: .seealso: `Mat`, `MATMPIAIJ`, `IS`, `MatReuse`
5742: @*/
5743: PetscErrorCode MatGetBrowsOfAcols(Mat A, Mat B, MatReuse scall, IS *rowb, IS *colb, Mat *B_seq)
5744: {
5745: Mat_MPIAIJ *a = (Mat_MPIAIJ *)A->data;
5746: PetscInt *idx, i, start, ncols, nzA, nzB, *cmap, imark;
5747: IS isrowb, iscolb;
5748: Mat *bseq = NULL;
5750: PetscFunctionBegin;
5751: 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 ")",
5752: A->cmap->rstart, A->cmap->rend, B->rmap->rstart, B->rmap->rend);
5753: PetscCall(PetscLogEventBegin(MAT_GetBrowsOfAcols, A, B, 0, 0));
5755: if (scall == MAT_INITIAL_MATRIX) {
5756: start = A->cmap->rstart;
5757: cmap = a->garray;
5758: nzA = a->A->cmap->n;
5759: nzB = a->B->cmap->n;
5760: PetscCall(PetscMalloc1(nzA + nzB, &idx));
5761: ncols = 0;
5762: for (i = 0; i < nzB; i++) { /* row < local row index */
5763: if (cmap[i] < start) idx[ncols++] = cmap[i];
5764: else break;
5765: }
5766: imark = i;
5767: for (i = 0; i < nzA; i++) idx[ncols++] = start + i; /* local rows */
5768: for (i = imark; i < nzB; i++) idx[ncols++] = cmap[i]; /* row > local row index */
5769: PetscCall(ISCreateGeneral(PETSC_COMM_SELF, ncols, idx, PETSC_OWN_POINTER, &isrowb));
5770: PetscCall(ISCreateStride(PETSC_COMM_SELF, B->cmap->N, 0, 1, &iscolb));
5771: } else {
5772: PetscCheck(rowb && colb, PETSC_COMM_SELF, PETSC_ERR_SUP, "IS rowb and colb must be provided for MAT_REUSE_MATRIX");
5773: isrowb = *rowb;
5774: iscolb = *colb;
5775: PetscCall(PetscMalloc1(1, &bseq));
5776: bseq[0] = *B_seq;
5777: }
5778: PetscCall(MatCreateSubMatrices(B, 1, &isrowb, &iscolb, scall, &bseq));
5779: *B_seq = bseq[0];
5780: PetscCall(PetscFree(bseq));
5781: if (!rowb) {
5782: PetscCall(ISDestroy(&isrowb));
5783: } else {
5784: *rowb = isrowb;
5785: }
5786: if (!colb) {
5787: PetscCall(ISDestroy(&iscolb));
5788: } else {
5789: *colb = iscolb;
5790: }
5791: PetscCall(PetscLogEventEnd(MAT_GetBrowsOfAcols, A, B, 0, 0));
5792: PetscFunctionReturn(PETSC_SUCCESS);
5793: }
5795: // PetscClangLinter pragma disable: -fdoc-sowing-chars
5796: /*
5797: MatGetBrowsOfAoCols_MPIAIJ - Creates a `MATSEQAIJ` matrix by taking rows of B that equal to nonzero columns
5798: of the OFF-DIAGONAL portion of local A
5800: Collective
5802: Input Parameters:
5803: + A - the first matrix in `MATMPIAIJ` format
5804: . B - the second matrix in `MATMPIAIJ` format
5805: - scall - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`
5807: Output Parameters:
5808: + startsj_s - starting point in B's sending j-arrays, saved for MAT_REUSE (or NULL)
5809: . startsj_r - starting point in B's receiving j-arrays, saved for MAT_REUSE (or NULL)
5810: . bufa_ptr - array for sending matrix values, saved for MAT_REUSE (or NULL)
5811: - B_oth - the sequential matrix generated with size aBn=a->B->cmap->n by B->cmap->N
5813: Level: developer
5815: Developer Note:
5816: This directly accesses information inside the VecScatter associated with the matrix-vector product
5817: for this matrix. This is not desirable.
5819: .seealso: [](ch_mat), `Mat`, `MATMPIAIJ`
5820: */
5821: PetscErrorCode MatGetBrowsOfAoCols_MPIAIJ(Mat A, Mat B, MatReuse scall, PetscInt **startsj_s, PetscInt **startsj_r, MatScalar **bufa_ptr, Mat *B_oth)
5822: {
5823: PetscFunctionBegin;
5824: PetscCall(MatGetBrowsOfAoCols_MPIAIJ_Private(A, B, scall, PETSC_FALSE, startsj_s, startsj_r, bufa_ptr, B_oth));
5825: PetscFunctionReturn(PETSC_SUCCESS);
5826: }
5828: PetscErrorCode MatGetBrowsOfAoCols_MPIAIJ_Private(Mat A, Mat B, MatReuse scall, PetscBool structure_only, PetscInt **startsj_s, PetscInt **startsj_r, MatScalar **bufa_ptr, Mat *B_oth)
5829: {
5830: Mat_MPIAIJ *a = (Mat_MPIAIJ *)A->data;
5831: VecScatter ctx;
5832: MPI_Comm comm;
5833: const PetscMPIInt *rprocs, *sprocs;
5834: PetscMPIInt nrecvs, nsends;
5835: const PetscInt *srow, *rstarts, *sstarts;
5836: PetscInt *rowlen, *bufj, *bufJ, ncols = 0, aBn = a->B->cmap->n, row, *b_othi, *b_othj, *rvalues = NULL, *svalues = NULL, *cols, sbs, rbs;
5837: PetscInt i, j, k = 0, l, ll, nrows, *rstartsj = NULL, *sstartsj, len;
5838: PetscScalar *b_otha = NULL, *bufa = NULL, *bufA, *vals = NULL;
5839: MPI_Request *reqs = NULL, *rwaits = NULL, *swaits = NULL;
5840: PetscMPIInt size, tag, rank, nreqs;
5842: PetscFunctionBegin;
5843: PetscCheck(!structure_only || scall == MAT_INITIAL_MATRIX, PETSC_COMM_SELF, PETSC_ERR_SUP, "Structure-only extraction requires MAT_INITIAL_MATRIX");
5844: PetscCall(PetscObjectGetComm((PetscObject)A, &comm));
5845: PetscCallMPI(MPI_Comm_size(comm, &size));
5847: 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 ")",
5848: A->cmap->rstart, A->cmap->rend, B->rmap->rstart, B->rmap->rend);
5849: PetscCall(PetscLogEventBegin(MAT_GetBrowsOfAocols, A, B, 0, 0));
5850: PetscCallMPI(MPI_Comm_rank(comm, &rank));
5852: if (size == 1) {
5853: startsj_s = NULL;
5854: bufa_ptr = NULL;
5855: *B_oth = NULL;
5856: PetscFunctionReturn(PETSC_SUCCESS);
5857: }
5859: ctx = a->Mvctx;
5860: tag = ((PetscObject)ctx)->tag;
5862: PetscCall(VecScatterGetRemote_Private(ctx, PETSC_TRUE /*send*/, &nsends, &sstarts, &srow, &sprocs, &sbs));
5863: /* rprocs[] must be ordered so that indices received from them are ordered in rvalues[], which is key to algorithms used in this subroutine */
5864: PetscCall(VecScatterGetRemoteOrdered_Private(ctx, PETSC_FALSE /*recv*/, &nrecvs, &rstarts, NULL /*indices not needed*/, &rprocs, &rbs));
5865: PetscCall(PetscMPIIntCast(nsends + nrecvs, &nreqs));
5866: PetscCall(PetscMalloc1(nreqs, &reqs));
5867: rwaits = reqs;
5868: swaits = PetscSafePointerPlusOffset(reqs, nrecvs);
5870: if (!startsj_s || !bufa_ptr) scall = MAT_INITIAL_MATRIX;
5871: if (scall == MAT_INITIAL_MATRIX) {
5872: /* i-array */
5873: /* post receives */
5874: if (nrecvs) PetscCall(PetscMalloc1(rbs * (rstarts[nrecvs] - rstarts[0]), &rvalues)); /* rstarts can be NULL when nrecvs=0 */
5875: for (i = 0; i < nrecvs; i++) {
5876: rowlen = rvalues + rstarts[i] * rbs;
5877: nrows = (rstarts[i + 1] - rstarts[i]) * rbs; /* num of indices to be received */
5878: PetscCallMPI(MPIU_Irecv(rowlen, nrows, MPIU_INT, rprocs[i], tag, comm, rwaits + i));
5879: }
5881: /* pack the outgoing message */
5882: PetscCall(PetscMalloc2(nsends + 1, &sstartsj, nrecvs + 1, &rstartsj));
5884: sstartsj[0] = 0;
5885: rstartsj[0] = 0;
5886: len = 0; /* total length of j or a array to be sent */
5887: if (nsends) {
5888: k = sstarts[0]; /* ATTENTION: sstarts[0] and rstarts[0] are not necessarily zero */
5889: PetscCall(PetscMalloc1(sbs * (sstarts[nsends] - sstarts[0]), &svalues));
5890: }
5891: for (i = 0; i < nsends; i++) {
5892: rowlen = svalues + (sstarts[i] - sstarts[0]) * sbs;
5893: nrows = sstarts[i + 1] - sstarts[i]; /* num of block rows */
5894: for (j = 0; j < nrows; j++) {
5895: row = srow[k] + B->rmap->range[rank]; /* global row idx */
5896: for (l = 0; l < sbs; l++) {
5897: PetscCall(MatGetRow_MPIAIJ(B, row + l, &ncols, NULL, NULL)); /* rowlength */
5899: rowlen[j * sbs + l] = ncols;
5901: len += ncols;
5902: PetscCall(MatRestoreRow_MPIAIJ(B, row + l, &ncols, NULL, NULL));
5903: }
5904: k++;
5905: }
5906: PetscCallMPI(MPIU_Isend(rowlen, nrows * sbs, MPIU_INT, sprocs[i], tag, comm, swaits + i));
5908: sstartsj[i + 1] = len; /* starting point of (i+1)-th outgoing msg in bufj and bufa */
5909: }
5910: /* recvs and sends of i-array are completed */
5911: if (nreqs) PetscCallMPI(MPI_Waitall(nreqs, reqs, MPI_STATUSES_IGNORE));
5912: PetscCall(PetscFree(svalues));
5914: /* allocate buffers for sending j and a arrays */
5915: PetscCall(PetscMalloc1(len, &bufj));
5916: if (!structure_only) PetscCall(PetscMalloc1(len, &bufa));
5918: /* create i-array of B_oth */
5919: PetscCall(PetscMalloc1(aBn + 1, &b_othi));
5921: b_othi[0] = 0;
5922: len = 0; /* total length of j or a array to be received */
5923: k = 0;
5924: for (i = 0; i < nrecvs; i++) {
5925: rowlen = rvalues + (rstarts[i] - rstarts[0]) * rbs;
5926: nrows = (rstarts[i + 1] - rstarts[i]) * rbs; /* num of rows to be received */
5927: for (j = 0; j < nrows; j++) {
5928: b_othi[k + 1] = b_othi[k] + rowlen[j];
5929: PetscCall(PetscIntSumError(rowlen[j], len, &len));
5930: k++;
5931: }
5932: rstartsj[i + 1] = len; /* starting point of (i+1)-th incoming msg in bufj and bufa */
5933: }
5934: PetscCall(PetscFree(rvalues));
5936: /* allocate space for j and a arrays of B_oth */
5937: PetscCall(PetscMalloc1(b_othi[aBn], &b_othj));
5938: if (!structure_only) PetscCall(PetscMalloc1(b_othi[aBn], &b_otha));
5940: /* j-array */
5941: /* post receives of j-array */
5942: for (i = 0; i < nrecvs; i++) {
5943: nrows = rstartsj[i + 1] - rstartsj[i]; /* length of the msg received */
5944: PetscCallMPI(MPIU_Irecv(PetscSafePointerPlusOffset(b_othj, rstartsj[i]), nrows, MPIU_INT, rprocs[i], tag, comm, rwaits + i));
5945: }
5947: /* pack the outgoing message j-array */
5948: if (nsends) k = sstarts[0];
5949: for (i = 0; i < nsends; i++) {
5950: nrows = sstarts[i + 1] - sstarts[i]; /* num of block rows */
5951: bufJ = PetscSafePointerPlusOffset(bufj, sstartsj[i]);
5952: for (j = 0; j < nrows; j++) {
5953: row = srow[k++] + B->rmap->range[rank]; /* global row idx */
5954: for (ll = 0; ll < sbs; ll++) {
5955: PetscCall(MatGetRow_MPIAIJ(B, row + ll, &ncols, &cols, NULL));
5956: for (l = 0; l < ncols; l++) *bufJ++ = cols[l];
5957: PetscCall(MatRestoreRow_MPIAIJ(B, row + ll, &ncols, &cols, NULL));
5958: }
5959: }
5960: PetscCallMPI(MPIU_Isend(PetscSafePointerPlusOffset(bufj, sstartsj[i]), sstartsj[i + 1] - sstartsj[i], MPIU_INT, sprocs[i], tag, comm, swaits + i));
5961: }
5963: /* recvs and sends of j-array are completed */
5964: if (nreqs) PetscCallMPI(MPI_Waitall(nreqs, reqs, MPI_STATUSES_IGNORE));
5965: } else if (scall == MAT_REUSE_MATRIX) {
5966: sstartsj = *startsj_s;
5967: rstartsj = *startsj_r;
5968: bufa = *bufa_ptr;
5969: PetscCall(MatSeqAIJGetArrayWrite(*B_oth, &b_otha));
5970: } else SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Matrix P does not possess an object container");
5972: if (!structure_only) {
5973: /* a-array */
5974: /* post receives of a-array */
5975: for (i = 0; i < nrecvs; i++) {
5976: nrows = rstartsj[i + 1] - rstartsj[i]; /* length of the msg received */
5977: PetscCallMPI(MPIU_Irecv(PetscSafePointerPlusOffset(b_otha, rstartsj[i]), nrows, MPIU_SCALAR, rprocs[i], tag, comm, rwaits + i));
5978: }
5980: /* pack the outgoing message a-array */
5981: if (nsends) k = sstarts[0];
5982: for (i = 0; i < nsends; i++) {
5983: nrows = sstarts[i + 1] - sstarts[i]; /* num of block rows */
5984: bufA = PetscSafePointerPlusOffset(bufa, sstartsj[i]);
5985: for (j = 0; j < nrows; j++) {
5986: row = srow[k++] + B->rmap->range[rank]; /* global row idx */
5987: for (ll = 0; ll < sbs; ll++) {
5988: PetscCall(MatGetRow_MPIAIJ(B, row + ll, &ncols, NULL, &vals));
5989: for (l = 0; l < ncols; l++) *bufA++ = vals[l];
5990: PetscCall(MatRestoreRow_MPIAIJ(B, row + ll, &ncols, NULL, &vals));
5991: }
5992: }
5993: PetscCallMPI(MPIU_Isend(PetscSafePointerPlusOffset(bufa, sstartsj[i]), sstartsj[i + 1] - sstartsj[i], MPIU_SCALAR, sprocs[i], tag, comm, swaits + i));
5994: }
5995: /* recvs and sends of a-array are completed */
5996: if (nreqs) PetscCallMPI(MPI_Waitall(nreqs, reqs, MPI_STATUSES_IGNORE));
5997: }
5998: PetscCall(PetscFree(reqs));
6000: if (scall == MAT_INITIAL_MATRIX) {
6001: Mat_SeqAIJ *b_oth;
6003: /* put together the new matrix */
6004: PetscCall(MatCreateSeqAIJWithArrays(PETSC_COMM_SELF, aBn, B->cmap->N, b_othi, b_othj, b_otha, B_oth));
6005: PetscCall(MatSetOption(*B_oth, MAT_STRUCTURE_ONLY, structure_only));
6007: /* MatCreateSeqAIJWithArrays flags matrix so PETSc doesn't free the user's arrays. */
6008: /* Since these are PETSc arrays, change flags to free them as necessary. */
6009: b_oth = (Mat_SeqAIJ *)(*B_oth)->data;
6010: b_oth->free_a = PETSC_TRUE;
6011: b_oth->free_ij = PETSC_TRUE;
6012: b_oth->nonew = 0;
6014: PetscCall(PetscFree(bufj));
6015: if (!startsj_s || !bufa_ptr) {
6016: PetscCall(PetscFree2(sstartsj, rstartsj));
6017: PetscCall(PetscFree(bufa_ptr));
6018: } else {
6019: *startsj_s = sstartsj;
6020: *startsj_r = rstartsj;
6021: *bufa_ptr = bufa;
6022: }
6023: } else if (scall == MAT_REUSE_MATRIX) {
6024: PetscCall(MatSeqAIJRestoreArrayWrite(*B_oth, &b_otha));
6025: }
6027: PetscCall(VecScatterRestoreRemote_Private(ctx, PETSC_TRUE, &nsends, &sstarts, &srow, &sprocs, &sbs));
6028: PetscCall(VecScatterRestoreRemoteOrdered_Private(ctx, PETSC_FALSE, &nrecvs, &rstarts, NULL, &rprocs, &rbs));
6029: PetscCall(PetscLogEventEnd(MAT_GetBrowsOfAocols, A, B, 0, 0));
6030: PetscFunctionReturn(PETSC_SUCCESS);
6031: }
6033: PETSC_INTERN PetscErrorCode MatConvert_MPIAIJ_MPIAIJCRL(Mat, MatType, MatReuse, Mat *);
6034: PETSC_INTERN PetscErrorCode MatConvert_MPIAIJ_MPIAIJPERM(Mat, MatType, MatReuse, Mat *);
6035: PETSC_INTERN PetscErrorCode MatConvert_MPIAIJ_MPIAIJSELL(Mat, MatType, MatReuse, Mat *);
6036: #if PetscDefined(HAVE_MKL_SPARSE)
6037: PETSC_INTERN PetscErrorCode MatConvert_MPIAIJ_MPIAIJMKL(Mat, MatType, MatReuse, Mat *);
6038: #endif
6039: PETSC_INTERN PetscErrorCode MatConvert_MPIAIJ_MPIBAIJ(Mat, MatType, MatReuse, Mat *);
6040: PETSC_INTERN PetscErrorCode MatConvert_MPIAIJ_MPISBAIJ(Mat, MatType, MatReuse, Mat *);
6041: #if PetscDefined(HAVE_ELEMENTAL)
6042: PETSC_INTERN PetscErrorCode MatConvert_MPIAIJ_Elemental(Mat, MatType, MatReuse, Mat *);
6043: #endif
6044: #if PetscDefined(HAVE_SCALAPACK) && (PetscDefined(USE_REAL_SINGLE) || PetscDefined(USE_REAL_DOUBLE))
6045: PETSC_INTERN PetscErrorCode MatConvert_AIJ_ScaLAPACK(Mat, MatType, MatReuse, Mat *);
6046: #endif
6047: #if PetscDefined(HAVE_HYPRE)
6048: PETSC_INTERN PetscErrorCode MatConvert_AIJ_HYPRE(Mat, MatType, MatReuse, Mat *);
6049: #endif
6050: #if PetscDefined(HAVE_CUDA)
6051: PETSC_INTERN PetscErrorCode MatConvert_MPIAIJ_MPIAIJCUSPARSE(Mat, MatType, MatReuse, Mat *);
6052: #endif
6053: #if PetscDefined(HAVE_HIP)
6054: PETSC_INTERN PetscErrorCode MatConvert_MPIAIJ_MPIAIJHIPSPARSE(Mat, MatType, MatReuse, Mat *);
6055: #endif
6056: #if PetscDefined(HAVE_KOKKOS_KERNELS)
6057: PETSC_INTERN PetscErrorCode MatConvert_MPIAIJ_MPIAIJKokkos(Mat, MatType, MatReuse, Mat *);
6058: #endif
6059: PETSC_INTERN PetscErrorCode MatConvert_MPIAIJ_MPISELL(Mat, MatType, MatReuse, Mat *);
6060: PETSC_INTERN PetscErrorCode MatConvert_XAIJ_IS(Mat, MatType, MatReuse, Mat *);
6061: PETSC_INTERN PetscErrorCode MatProductSetFromOptions_IS_XAIJ(Mat);
6063: /*
6064: Computes (B'*A')' since computing B*A directly is untenable
6066: n p p
6067: [ ] [ ] [ ]
6068: m [ A ] * n [ B ] = m [ C ]
6069: [ ] [ ] [ ]
6071: */
6072: static PetscErrorCode MatMatMultNumeric_MPIDense_MPIAIJ(Mat A, Mat B, Mat C)
6073: {
6074: Mat At, Bt, Ct;
6076: PetscFunctionBegin;
6077: PetscCall(MatTranspose(A, MAT_INITIAL_MATRIX, &At));
6078: PetscCall(MatTranspose(B, MAT_INITIAL_MATRIX, &Bt));
6079: PetscCall(MatMatMult(Bt, At, MAT_INITIAL_MATRIX, PETSC_CURRENT, &Ct));
6080: PetscCall(MatDestroy(&At));
6081: PetscCall(MatDestroy(&Bt));
6082: PetscCall(MatTransposeSetPrecursor(Ct, C));
6083: PetscCall(MatTranspose(Ct, MAT_REUSE_MATRIX, &C));
6084: PetscCall(MatDestroy(&Ct));
6085: PetscFunctionReturn(PETSC_SUCCESS);
6086: }
6088: static PetscErrorCode MatMatMultSymbolic_MPIDense_MPIAIJ(Mat A, Mat B, PetscReal fill, Mat C)
6089: {
6090: PetscFunctionBegin;
6091: 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);
6092: PetscCall(MatDenseSetUpProduct_Private(C, A->rmap, B->cmap, A, NULL));
6094: C->ops->matmultnumeric = MatMatMultNumeric_MPIDense_MPIAIJ;
6095: PetscFunctionReturn(PETSC_SUCCESS);
6096: }
6098: static PetscErrorCode MatProductSetFromOptions_MPIDense_MPIAIJ_AB(Mat C)
6099: {
6100: Mat_Product *product = C->product;
6101: Mat A = product->A, B = product->B;
6103: PetscFunctionBegin;
6104: 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 ")",
6105: A->cmap->rstart, A->cmap->rend, B->rmap->rstart, B->rmap->rend);
6106: C->ops->matmultsymbolic = MatMatMultSymbolic_MPIDense_MPIAIJ;
6107: C->ops->productsymbolic = MatProductSymbolic_AB;
6108: PetscFunctionReturn(PETSC_SUCCESS);
6109: }
6111: PETSC_INTERN PetscErrorCode MatProductSetFromOptions_MPIDense_MPIAIJ(Mat C)
6112: {
6113: Mat_Product *product = C->product;
6115: PetscFunctionBegin;
6116: if (product->type == MATPRODUCT_AB) PetscCall(MatProductSetFromOptions_MPIDense_MPIAIJ_AB(C));
6117: PetscFunctionReturn(PETSC_SUCCESS);
6118: }
6120: /*
6121: Merge two sets of sorted nonzeros and return a CSR for the merged (sequential) matrix
6123: Input Parameters:
6125: j1,rowBegin1,rowEnd1,jmap1: describe the first set of nonzeros (Set1)
6126: j2,rowBegin2,rowEnd2,jmap2: describe the second set of nonzeros (Set2)
6128: mat: both sets' nonzeros are on m rows, where m is the number of local rows of the matrix mat
6130: For Set1, j1[] contains column indices of the nonzeros.
6131: 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
6132: respectively (note rowEnd1[k] is not necessarily equal to rwoBegin1[k+1]). Indices in this range of j1[] are sorted,
6133: but might have repeats. jmap1[t+1] - jmap1[t] is the number of repeats for the t-th unique nonzero in Set1.
6135: Similar for Set2.
6137: This routine merges the two sets of nonzeros row by row and removes repeats.
6139: Output Parameters: (memory is allocated by the caller)
6141: i[],j[]: the CSR of the merged matrix, which has m rows.
6142: imap1[]: the k-th unique nonzero in Set1 (k=0,1,...) corresponds to imap1[k]-th unique nonzero in the merged matrix.
6143: imap2[]: similar to imap1[], but for Set2.
6144: Note we order nonzeros row-by-row and from left to right.
6145: */
6146: 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[])
6147: {
6148: PetscInt r, m; /* Row index of mat */
6149: PetscCount t, t1, t2, b1, e1, b2, e2;
6151: PetscFunctionBegin;
6152: PetscCall(MatGetLocalSize(mat, &m, NULL));
6153: t1 = t2 = t = 0; /* Count unique nonzeros of in Set1, Set1 and the merged respectively */
6154: i[0] = 0;
6155: for (r = 0; r < m; r++) { /* Do row by row merging */
6156: b1 = rowBegin1[r];
6157: e1 = rowEnd1[r];
6158: b2 = rowBegin2[r];
6159: e2 = rowEnd2[r];
6160: while (b1 < e1 && b2 < e2) {
6161: if (j1[b1] == j2[b2]) { /* Same column index and hence same nonzero */
6162: j[t] = j1[b1];
6163: imap1[t1] = t;
6164: imap2[t2] = t;
6165: b1 += jmap1[t1 + 1] - jmap1[t1]; /* Jump to next unique local nonzero */
6166: b2 += jmap2[t2 + 1] - jmap2[t2]; /* Jump to next unique remote nonzero */
6167: t1++;
6168: t2++;
6169: t++;
6170: } else if (j1[b1] < j2[b2]) {
6171: j[t] = j1[b1];
6172: imap1[t1] = t;
6173: b1 += jmap1[t1 + 1] - jmap1[t1];
6174: t1++;
6175: t++;
6176: } else {
6177: j[t] = j2[b2];
6178: imap2[t2] = t;
6179: b2 += jmap2[t2 + 1] - jmap2[t2];
6180: t2++;
6181: t++;
6182: }
6183: }
6184: /* Merge the remaining in either j1[] or j2[] */
6185: while (b1 < e1) {
6186: j[t] = j1[b1];
6187: imap1[t1] = t;
6188: b1 += jmap1[t1 + 1] - jmap1[t1];
6189: t1++;
6190: t++;
6191: }
6192: while (b2 < e2) {
6193: j[t] = j2[b2];
6194: imap2[t2] = t;
6195: b2 += jmap2[t2 + 1] - jmap2[t2];
6196: t2++;
6197: t++;
6198: }
6199: PetscCall(PetscIntCast(t, i + r + 1));
6200: }
6201: PetscFunctionReturn(PETSC_SUCCESS);
6202: }
6204: /*
6205: Split nonzeros in a block of local rows into two subsets: those in the diagonal block and those in the off-diagonal block
6207: Input Parameters:
6208: mat: an MPI matrix that provides row and column layout information for splitting. Let's say its number of local rows is m.
6209: 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[]
6210: respectively, along with a permutation array perm[]. Length of the i[],j[],perm[] arrays is n.
6212: i[] is already sorted, but within a row, j[] is not sorted and might have repeats.
6213: i[] might contain negative indices at the beginning, which means the corresponding entries should be ignored in the splitting.
6215: Output Parameters:
6216: j[],perm[]: the routine needs to sort j[] within each row along with perm[].
6217: rowBegin[],rowMid[],rowEnd[]: of length m, and the memory is preallocated and zeroed by the caller.
6218: 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,
6219: and [rowMid[r],rowEnd[r]) point to begin/end entries of row r of the off-diagonal block.
6221: Aperm[],Ajmap[],Atot,Annz: Arrays are allocated by this routine.
6222: Atot: number of entries belonging to the diagonal block.
6223: Annz: number of unique nonzeros belonging to the diagonal block.
6224: Aperm[Atot] stores values from perm[] for entries belonging to the diagonal block. Length of Aperm[] is Atot, though it may also count
6225: repeats (i.e., same 'i,j' pair).
6226: Ajmap[Annz+1] stores the number of repeats of each unique entry belonging to the diagonal block. More precisely, Ajmap[t+1] - Ajmap[t]
6227: is the number of repeats for the t-th unique entry in the diagonal block. Ajmap[0] is always 0.
6229: Atot: number of entries belonging to the diagonal block
6230: Annz: number of unique nonzeros belonging to the diagonal block.
6232: Bperm[], Bjmap[], Btot, Bnnz are similar but for the off-diagonal block.
6234: Aperm[],Bperm[],Ajmap[] and Bjmap[] are allocated separately by this routine with PetscMalloc1().
6235: */
6236: 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_)
6237: {
6238: PetscInt cstart, cend, rstart, rend, row, col;
6239: PetscCount Atot = 0, Btot = 0; /* Total number of nonzeros in the diagonal and off-diagonal blocks */
6240: PetscCount Annz = 0, Bnnz = 0; /* Number of unique nonzeros in the diagonal and off-diagonal blocks */
6241: PetscCount k, m, p, q, r, s, mid;
6242: PetscCount *Aperm, *Bperm, *Ajmap, *Bjmap;
6244: PetscFunctionBegin;
6245: PetscCall(PetscLayoutGetRange(mat->rmap, &rstart, &rend));
6246: PetscCall(PetscLayoutGetRange(mat->cmap, &cstart, &cend));
6247: m = rend - rstart;
6249: /* Skip negative rows */
6250: for (k = 0; k < n; k++)
6251: if (i[k] >= 0) break;
6253: /* Process [k,n): sort and partition each local row into diag and offdiag portions,
6254: fill rowBegin[], rowMid[], rowEnd[], and count Atot, Btot, Annz, Bnnz.
6255: */
6256: while (k < n) {
6257: row = i[k];
6258: /* Entries in [k,s) are in one row. Shift diagonal block col indices so that diag is ahead of offdiag after sorting the row */
6259: for (s = k; s < n; s++)
6260: if (i[s] != row) break;
6262: /* Shift diag columns to range of [-PETSC_INT_MAX, -1] */
6263: for (p = k; p < s; p++) {
6264: if (j[p] >= cstart && j[p] < cend) j[p] -= PETSC_INT_MAX;
6265: }
6266: PetscCall(PetscSortIntWithCountArray(s - k, j + k, perm + k));
6267: PetscCall(PetscSortedIntUpperBound(j, k, s, -1, &mid)); /* Separate [k,s) into [k,mid) for diag and [mid,s) for offdiag */
6268: rowBegin[row - rstart] = k;
6269: rowMid[row - rstart] = mid;
6270: rowEnd[row - rstart] = s;
6271: 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);
6273: /* Count nonzeros of this diag/offdiag row, which might have repeats */
6274: Atot += mid - k;
6275: Btot += s - mid;
6277: /* Count unique nonzeros of this diag row */
6278: for (p = k; p < mid;) {
6279: col = j[p];
6280: do {
6281: j[p] += PETSC_INT_MAX; /* Revert the modified diagonal indices */
6282: p++;
6283: } while (p < mid && j[p] == col);
6284: Annz++;
6285: }
6287: /* Count unique nonzeros of this offdiag row */
6288: for (p = mid; p < s;) {
6289: col = j[p];
6290: do {
6291: p++;
6292: } while (p < s && j[p] == col);
6293: Bnnz++;
6294: }
6295: k = s;
6296: }
6298: /* Allocation according to Atot, Btot, Annz, Bnnz */
6299: PetscCall(PetscMalloc1(Atot, &Aperm));
6300: PetscCall(PetscMalloc1(Btot, &Bperm));
6301: PetscCall(PetscMalloc1(Annz + 1, &Ajmap));
6302: PetscCall(PetscMalloc1(Bnnz + 1, &Bjmap));
6304: /* Re-scan indices and copy diag/offdiag permutation indices to Aperm, Bperm and also fill Ajmap and Bjmap */
6305: Ajmap[0] = Bjmap[0] = Atot = Btot = Annz = Bnnz = 0;
6306: for (r = 0; r < m; r++) {
6307: k = rowBegin[r];
6308: mid = rowMid[r];
6309: s = rowEnd[r];
6310: PetscCall(PetscArraycpy(PetscSafePointerPlusOffset(Aperm, Atot), PetscSafePointerPlusOffset(perm, k), mid - k));
6311: PetscCall(PetscArraycpy(PetscSafePointerPlusOffset(Bperm, Btot), PetscSafePointerPlusOffset(perm, mid), s - mid));
6312: Atot += mid - k;
6313: Btot += s - mid;
6315: /* Scan column indices in this row and find out how many repeats each unique nonzero has */
6316: for (p = k; p < mid;) {
6317: col = j[p];
6318: q = p;
6319: do {
6320: p++;
6321: } while (p < mid && j[p] == col);
6322: Ajmap[Annz + 1] = Ajmap[Annz] + (p - q);
6323: Annz++;
6324: }
6326: for (p = mid; p < s;) {
6327: col = j[p];
6328: q = p;
6329: do {
6330: p++;
6331: } while (p < s && j[p] == col);
6332: Bjmap[Bnnz + 1] = Bjmap[Bnnz] + (p - q);
6333: Bnnz++;
6334: }
6335: }
6336: /* Output */
6337: *Aperm_ = Aperm;
6338: *Annz_ = Annz;
6339: *Atot_ = Atot;
6340: *Ajmap_ = Ajmap;
6341: *Bperm_ = Bperm;
6342: *Bnnz_ = Bnnz;
6343: *Btot_ = Btot;
6344: *Bjmap_ = Bjmap;
6345: PetscFunctionReturn(PETSC_SUCCESS);
6346: }
6348: /*
6349: Expand the jmap[] array to make a new one in view of nonzeros in the merged matrix
6351: Input Parameters:
6352: nnz1: number of unique nonzeros in a set that was used to produce imap[], jmap[]
6353: nnz: number of unique nonzeros in the merged matrix
6354: imap[nnz1]: i-th nonzero in the set is the imap[i]-th nonzero in the merged matrix
6355: jmap[nnz1+1]: i-th nonzero in the set has jmap[i+1] - jmap[i] repeats in the set
6357: Output Parameter: (memory is allocated by the caller)
6358: jmap_new[nnz+1]: i-th nonzero in the merged matrix has jmap_new[i+1] - jmap_new[i] repeats in the set
6360: Example:
6361: nnz1 = 4
6362: nnz = 6
6363: imap = [1,3,4,5]
6364: jmap = [0,3,5,6,7]
6365: then,
6366: jmap_new = [0,0,3,3,5,6,7]
6367: */
6368: static PetscErrorCode ExpandJmap_Internal(PetscCount nnz1, PetscCount nnz, const PetscCount imap[], const PetscCount jmap[], PetscCount jmap_new[])
6369: {
6370: PetscCount k, p;
6372: PetscFunctionBegin;
6373: jmap_new[0] = 0;
6374: p = nnz; /* p loops over jmap_new[] backwards */
6375: for (k = nnz1 - 1; k >= 0; k--) { /* k loops over imap[] */
6376: for (; p > imap[k]; p--) jmap_new[p] = jmap[k + 1];
6377: }
6378: for (; p >= 0; p--) jmap_new[p] = jmap[0];
6379: PetscFunctionReturn(PETSC_SUCCESS);
6380: }
6382: static PetscErrorCode MatCOOStructDestroy_MPIAIJ(PetscCtxRt data)
6383: {
6384: MatCOOStruct_MPIAIJ *coo = *(MatCOOStruct_MPIAIJ **)data;
6386: PetscFunctionBegin;
6387: PetscCall(PetscSFDestroy(&coo->sf));
6388: PetscCall(PetscFree(coo->Aperm1));
6389: PetscCall(PetscFree(coo->Bperm1));
6390: PetscCall(PetscFree(coo->Ajmap1));
6391: PetscCall(PetscFree(coo->Bjmap1));
6392: PetscCall(PetscFree(coo->Aimap2));
6393: PetscCall(PetscFree(coo->Bimap2));
6394: PetscCall(PetscFree(coo->Aperm2));
6395: PetscCall(PetscFree(coo->Bperm2));
6396: PetscCall(PetscFree(coo->Ajmap2));
6397: PetscCall(PetscFree(coo->Bjmap2));
6398: PetscCall(PetscFree(coo->Cperm1));
6399: PetscCall(PetscFree2(coo->sendbuf, coo->recvbuf));
6400: PetscCall(PetscFree(coo));
6401: PetscFunctionReturn(PETSC_SUCCESS);
6402: }
6404: PetscErrorCode MatSetPreallocationCOO_MPIAIJ(Mat mat, PetscCount coo_n, PetscInt coo_i[], PetscInt coo_j[])
6405: {
6406: MPI_Comm comm;
6407: PetscMPIInt rank, size;
6408: PetscInt m, n, M, N, rstart, rend, cstart, cend; /* Sizes, indices of row/col, therefore with type PetscInt */
6409: PetscCount k, p, q, rem; /* Loop variables over coo arrays */
6410: Mat_MPIAIJ *mpiaij = (Mat_MPIAIJ *)mat->data;
6411: PetscContainer container;
6412: MatCOOStruct_MPIAIJ *coo;
6414: PetscFunctionBegin;
6415: // The A and B blocks built below leave B with compacted column indices, which MatSetValues_MPI_Hash() cannot fill
6416: if (mat->hash_active) {
6417: mat->ops[0] = mpiaij->cops;
6418: mat->hash_active = PETSC_FALSE;
6419: }
6420: PetscCall(PetscFree(mpiaij->garray));
6421: PetscCall(VecDestroy(&mpiaij->lvec));
6422: #if PetscDefined(USE_CTABLE)
6423: PetscCall(PetscHMapIDestroy(&mpiaij->colmap));
6424: #else
6425: PetscCall(PetscFree(mpiaij->colmap));
6426: #endif
6427: PetscCall(VecScatterDestroy(&mpiaij->Mvctx));
6428: mat->assembled = PETSC_FALSE;
6429: mat->was_assembled = PETSC_FALSE;
6431: PetscCall(PetscObjectGetComm((PetscObject)mat, &comm));
6432: PetscCallMPI(MPI_Comm_size(comm, &size));
6433: PetscCallMPI(MPI_Comm_rank(comm, &rank));
6434: PetscCall(PetscLayoutSetUp(mat->rmap));
6435: PetscCall(PetscLayoutSetUp(mat->cmap));
6436: PetscCall(PetscLayoutGetRange(mat->rmap, &rstart, &rend));
6437: PetscCall(PetscLayoutGetRange(mat->cmap, &cstart, &cend));
6438: PetscCall(MatGetLocalSize(mat, &m, &n));
6439: PetscCall(MatGetSize(mat, &M, &N));
6441: /* Sort (i,j) by row along with a permutation array, so that the to-be-ignored */
6442: /* entries come first, then local rows, then remote rows. */
6443: PetscCount n1 = coo_n, *perm1;
6444: PetscInt *i1 = coo_i, *j1 = coo_j;
6446: PetscCall(PetscMalloc1(n1, &perm1));
6447: for (k = 0; k < n1; k++) perm1[k] = k;
6449: /* Manipulate indices so that entries with negative row or col indices will have smallest
6450: row indices, local entries will have greater but negative row indices, and remote entries
6451: will have positive row indices.
6452: */
6453: for (k = 0; k < n1; k++) {
6454: if (i1[k] < 0 || j1[k] < 0) i1[k] = PETSC_INT_MIN; /* e.g., -2^31, minimal to move them ahead */
6455: 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] */
6456: else {
6457: PetscCheck(!mat->nooffprocentries, PETSC_COMM_SELF, PETSC_ERR_USER_INPUT, "MAT_NO_OFF_PROC_ENTRIES is set but insert to remote rows");
6458: if (mpiaij->donotstash) i1[k] = PETSC_INT_MIN; /* Ignore offproc entries as if they had negative indices */
6459: }
6460: }
6462: /* Sort by row; after that, [0,k) have ignored entries, [k,rem) have local rows and [rem,n1) have remote rows */
6463: PetscCall(PetscSortIntWithIntCountArrayPair(n1, i1, j1, perm1));
6465: /* Advance k to the first entry we need to take care of */
6466: for (k = 0; k < n1; k++)
6467: if (i1[k] > PETSC_INT_MIN) break;
6468: PetscCount i1start = k;
6470: PetscCall(PetscSortedIntUpperBound(i1, k, n1, rend - 1 - PETSC_INT_MAX, &rem)); /* rem is upper bound of the last local row */
6471: for (; k < rem; k++) i1[k] += PETSC_INT_MAX; /* Revert row indices of local rows*/
6473: 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);
6475: /* Send remote rows to their owner */
6476: /* Find which rows should be sent to which remote ranks*/
6477: PetscInt nsend = 0; /* Number of MPI processes to send data to */
6478: PetscMPIInt *sendto; /* [nsend], storing remote ranks */
6479: PetscInt *nentries; /* [nsend], storing number of entries sent to remote ranks; Assume PetscInt is big enough for this count, and error if not */
6480: const PetscInt *ranges;
6481: PetscInt maxNsend = size >= 128 ? 128 : size; /* Assume max 128 neighbors; realloc when needed */
6483: PetscCall(PetscLayoutGetRanges(mat->rmap, &ranges));
6484: PetscCall(PetscMalloc2(maxNsend, &sendto, maxNsend, &nentries));
6485: for (k = rem; k < n1;) {
6486: PetscMPIInt owner;
6487: PetscInt firstRow, lastRow;
6489: /* Locate a row range */
6490: firstRow = i1[k]; /* first row of this owner */
6491: PetscCall(PetscLayoutFindOwner(mat->rmap, firstRow, &owner));
6492: lastRow = ranges[owner + 1] - 1; /* last row of this owner */
6494: /* Find the first index 'p' in [k,n) with i1[p] belonging to next owner */
6495: PetscCall(PetscSortedIntUpperBound(i1, k, n1, lastRow, &p));
6497: /* All entries in [k,p) belong to this remote owner */
6498: if (nsend >= maxNsend) { /* Double the remote ranks arrays if not long enough */
6499: PetscMPIInt *sendto2;
6500: PetscInt *nentries2;
6501: PetscInt maxNsend2 = (maxNsend <= size / 2) ? maxNsend * 2 : size;
6503: PetscCall(PetscMalloc2(maxNsend2, &sendto2, maxNsend2, &nentries2));
6504: PetscCall(PetscArraycpy(sendto2, sendto, maxNsend));
6505: PetscCall(PetscArraycpy(nentries2, nentries, maxNsend));
6506: PetscCall(PetscFree2(sendto, nentries));
6507: sendto = sendto2;
6508: nentries = nentries2;
6509: maxNsend = maxNsend2;
6510: }
6511: sendto[nsend] = owner;
6512: PetscCall(PetscIntCast(p - k, &nentries[nsend]));
6513: nsend++;
6514: k = p;
6515: }
6517: /* Build 1st SF to know offsets on remote to send data */
6518: PetscSF sf1;
6519: PetscInt nroots = 1, nroots2 = 0;
6520: PetscInt nleaves = nsend, nleaves2 = 0;
6521: PetscInt *offsets;
6522: PetscSFNode *iremote;
6524: PetscCall(PetscSFCreate(comm, &sf1));
6525: PetscCall(PetscMalloc1(nsend, &iremote));
6526: PetscCall(PetscMalloc1(nsend, &offsets));
6527: for (k = 0; k < nsend; k++) {
6528: iremote[k].rank = sendto[k];
6529: iremote[k].index = 0;
6530: nleaves2 += nentries[k];
6531: PetscCheck(nleaves2 >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Number of SF leaves is too large for PetscInt");
6532: }
6533: PetscCall(PetscSFSetGraph(sf1, nroots, nleaves, NULL, PETSC_OWN_POINTER, iremote, PETSC_OWN_POINTER));
6534: PetscCall(PetscSFFetchAndOpWithMemTypeBegin(sf1, MPIU_INT, PETSC_MEMTYPE_HOST, &nroots2 /*rootdata*/, PETSC_MEMTYPE_HOST, nentries /*leafdata*/, PETSC_MEMTYPE_HOST, offsets /*leafupdate*/, MPI_SUM));
6535: PetscCall(PetscSFFetchAndOpEnd(sf1, MPIU_INT, &nroots2, nentries, offsets, MPI_SUM)); /* Would nroots2 overflow, we check offsets[] below */
6536: PetscCall(PetscSFDestroy(&sf1));
6537: PetscAssert(nleaves2 == n1 - rem, PETSC_COMM_SELF, PETSC_ERR_PLIB, "nleaves2 %" PetscInt_FMT " != number of remote entries %" PetscCount_FMT, nleaves2, n1 - rem);
6539: /* Build 2nd SF to send remote COOs to their owner */
6540: PetscSF sf2;
6541: nroots = nroots2;
6542: nleaves = nleaves2;
6543: PetscCall(PetscSFCreate(comm, &sf2));
6544: PetscCall(PetscSFSetFromOptions(sf2));
6545: PetscCall(PetscMalloc1(nleaves, &iremote));
6546: p = 0;
6547: for (k = 0; k < nsend; k++) {
6548: PetscCheck(offsets[k] >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Number of SF roots is too large for PetscInt");
6549: for (q = 0; q < nentries[k]; q++, p++) {
6550: iremote[p].rank = sendto[k];
6551: PetscCall(PetscIntCast(offsets[k] + q, &iremote[p].index));
6552: }
6553: }
6554: PetscCall(PetscSFSetGraph(sf2, nroots, nleaves, NULL, PETSC_OWN_POINTER, iremote, PETSC_OWN_POINTER));
6556: /* Send the remote COOs to their owner */
6557: PetscInt n2 = nroots, *i2, *j2; /* Buffers for received COOs from other ranks, along with a permutation array */
6558: PetscCount *perm2; /* Though PetscInt is enough for remote entries, we use PetscCount here as we want to reuse MatSplitEntries_Internal() */
6559: PetscCall(PetscMalloc3(n2, &i2, n2, &j2, n2, &perm2));
6560: PetscAssert(rem == 0 || i1 != NULL, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Cannot add nonzero offset to null");
6561: PetscAssert(rem == 0 || j1 != NULL, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Cannot add nonzero offset to null");
6562: PetscInt *i1prem = PetscSafePointerPlusOffset(i1, rem);
6563: PetscInt *j1prem = PetscSafePointerPlusOffset(j1, rem);
6564: PetscCall(PetscSFReduceWithMemTypeBegin(sf2, MPIU_INT, PETSC_MEMTYPE_HOST, i1prem, PETSC_MEMTYPE_HOST, i2, MPI_REPLACE));
6565: PetscCall(PetscSFReduceEnd(sf2, MPIU_INT, i1prem, i2, MPI_REPLACE));
6566: PetscCall(PetscSFReduceWithMemTypeBegin(sf2, MPIU_INT, PETSC_MEMTYPE_HOST, j1prem, PETSC_MEMTYPE_HOST, j2, MPI_REPLACE));
6567: PetscCall(PetscSFReduceEnd(sf2, MPIU_INT, j1prem, j2, MPI_REPLACE));
6569: PetscCall(PetscFree(offsets));
6570: PetscCall(PetscFree2(sendto, nentries));
6572: /* Sort received COOs by row along with the permutation array */
6573: for (k = 0; k < n2; k++) perm2[k] = k;
6574: PetscCall(PetscSortIntWithIntCountArrayPair(n2, i2, j2, perm2));
6576: /* sf2 only sends contiguous leafdata to contiguous rootdata. We record the permutation which will be used to fill leafdata */
6577: PetscCount *Cperm1;
6578: PetscAssert(rem == 0 || perm1 != NULL, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Cannot add nonzero offset to null");
6579: PetscCount *perm1prem = PetscSafePointerPlusOffset(perm1, rem);
6580: PetscCall(PetscMalloc1(nleaves, &Cperm1));
6581: PetscCall(PetscArraycpy(Cperm1, perm1prem, nleaves));
6583: /* Support for HYPRE matrices, kind of a hack.
6584: Swap min column with diagonal so that diagonal values will go first */
6585: PetscBool hypre;
6586: PetscCall(PetscStrcmp("_internal_COO_mat_for_hypre", ((PetscObject)mat)->name, &hypre));
6587: if (hypre) {
6588: PetscInt *minj;
6589: PetscBT hasdiag;
6591: PetscCall(PetscBTCreate(m, &hasdiag));
6592: PetscCall(PetscMalloc1(m, &minj));
6593: for (k = 0; k < m; k++) minj[k] = PETSC_INT_MAX;
6594: for (k = i1start; k < rem; k++) {
6595: if (j1[k] < cstart || j1[k] >= cend) continue;
6596: const PetscInt rindex = i1[k] - rstart;
6597: if ((j1[k] - cstart) == rindex) PetscCall(PetscBTSet(hasdiag, rindex));
6598: minj[rindex] = PetscMin(minj[rindex], j1[k]);
6599: }
6600: for (k = 0; k < n2; k++) {
6601: if (j2[k] < cstart || j2[k] >= cend) continue;
6602: const PetscInt rindex = i2[k] - rstart;
6603: if ((j2[k] - cstart) == rindex) PetscCall(PetscBTSet(hasdiag, rindex));
6604: minj[rindex] = PetscMin(minj[rindex], j2[k]);
6605: }
6606: for (k = i1start; k < rem; k++) {
6607: const PetscInt rindex = i1[k] - rstart;
6608: if (j1[k] < cstart || j1[k] >= cend || !PetscBTLookup(hasdiag, rindex)) continue;
6609: if (j1[k] == minj[rindex]) j1[k] = i1[k] + (cstart - rstart);
6610: else if ((j1[k] - cstart) == rindex) j1[k] = minj[rindex];
6611: }
6612: for (k = 0; k < n2; k++) {
6613: const PetscInt rindex = i2[k] - rstart;
6614: if (j2[k] < cstart || j2[k] >= cend || !PetscBTLookup(hasdiag, rindex)) continue;
6615: if (j2[k] == minj[rindex]) j2[k] = i2[k] + (cstart - rstart);
6616: else if ((j2[k] - cstart) == rindex) j2[k] = minj[rindex];
6617: }
6618: PetscCall(PetscBTDestroy(&hasdiag));
6619: PetscCall(PetscFree(minj));
6620: }
6622: /* Split local COOs and received COOs into diag/offdiag portions */
6623: PetscCount *rowBegin1, *rowMid1, *rowEnd1;
6624: PetscCount *Ajmap1, *Aperm1, *Bjmap1, *Bperm1;
6625: PetscCount Annz1, Bnnz1, Atot1, Btot1;
6626: PetscCount *rowBegin2, *rowMid2, *rowEnd2;
6627: PetscCount *Ajmap2, *Aperm2, *Bjmap2, *Bperm2;
6628: PetscCount Annz2, Bnnz2, Atot2, Btot2;
6630: PetscCall(PetscCalloc3(m, &rowBegin1, m, &rowMid1, m, &rowEnd1));
6631: PetscCall(PetscCalloc3(m, &rowBegin2, m, &rowMid2, m, &rowEnd2));
6632: PetscCall(MatSplitEntries_Internal(mat, rem, i1, j1, perm1, rowBegin1, rowMid1, rowEnd1, &Atot1, &Aperm1, &Annz1, &Ajmap1, &Btot1, &Bperm1, &Bnnz1, &Bjmap1));
6633: PetscCall(MatSplitEntries_Internal(mat, n2, i2, j2, perm2, rowBegin2, rowMid2, rowEnd2, &Atot2, &Aperm2, &Annz2, &Ajmap2, &Btot2, &Bperm2, &Bnnz2, &Bjmap2));
6635: /* Merge local COOs with received COOs: diag with diag, offdiag with offdiag */
6636: PetscInt *Ai, *Bi;
6637: PetscInt *Aj, *Bj;
6639: PetscCall(PetscMalloc1(m + 1, &Ai));
6640: PetscCall(PetscMalloc1(m + 1, &Bi));
6641: PetscCall(PetscMalloc1(Annz1 + Annz2, &Aj)); /* Since local and remote entries might have dups, we might allocate excess memory */
6642: PetscCall(PetscMalloc1(Bnnz1 + Bnnz2, &Bj));
6644: PetscCount *Aimap1, *Bimap1, *Aimap2, *Bimap2;
6645: PetscCall(PetscMalloc1(Annz1, &Aimap1));
6646: PetscCall(PetscMalloc1(Bnnz1, &Bimap1));
6647: PetscCall(PetscMalloc1(Annz2, &Aimap2));
6648: PetscCall(PetscMalloc1(Bnnz2, &Bimap2));
6650: PetscCall(MatMergeEntries_Internal(mat, j1, j2, rowBegin1, rowMid1, rowBegin2, rowMid2, Ajmap1, Ajmap2, Aimap1, Aimap2, Ai, Aj));
6651: PetscCall(MatMergeEntries_Internal(mat, j1, j2, rowMid1, rowEnd1, rowMid2, rowEnd2, Bjmap1, Bjmap2, Bimap1, Bimap2, Bi, Bj));
6653: /* Expand Ajmap1/Bjmap1 to make them based off nonzeros in A/B, since we */
6654: /* expect nonzeros in A/B most likely have local contributing entries */
6655: PetscInt Annz = Ai[m];
6656: PetscInt Bnnz = Bi[m];
6657: PetscCount *Ajmap1_new, *Bjmap1_new;
6659: PetscCall(PetscMalloc1(Annz + 1, &Ajmap1_new));
6660: PetscCall(PetscMalloc1(Bnnz + 1, &Bjmap1_new));
6662: PetscCall(ExpandJmap_Internal(Annz1, Annz, Aimap1, Ajmap1, Ajmap1_new));
6663: PetscCall(ExpandJmap_Internal(Bnnz1, Bnnz, Bimap1, Bjmap1, Bjmap1_new));
6665: PetscCall(PetscFree(Aimap1));
6666: PetscCall(PetscFree(Ajmap1));
6667: PetscCall(PetscFree(Bimap1));
6668: PetscCall(PetscFree(Bjmap1));
6669: PetscCall(PetscFree3(rowBegin1, rowMid1, rowEnd1));
6670: PetscCall(PetscFree3(rowBegin2, rowMid2, rowEnd2));
6671: PetscCall(PetscFree(perm1));
6672: PetscCall(PetscFree3(i2, j2, perm2));
6674: Ajmap1 = Ajmap1_new;
6675: Bjmap1 = Bjmap1_new;
6677: /* Reallocate Aj, Bj once we know actual numbers of unique nonzeros in A and B */
6678: if (Annz < Annz1 + Annz2) {
6679: PetscInt *Aj_new;
6680: PetscCall(PetscMalloc1(Annz, &Aj_new));
6681: PetscCall(PetscArraycpy(Aj_new, Aj, Annz));
6682: PetscCall(PetscFree(Aj));
6683: Aj = Aj_new;
6684: }
6686: if (Bnnz < Bnnz1 + Bnnz2) {
6687: PetscInt *Bj_new;
6688: PetscCall(PetscMalloc1(Bnnz, &Bj_new));
6689: PetscCall(PetscArraycpy(Bj_new, Bj, Bnnz));
6690: PetscCall(PetscFree(Bj));
6691: Bj = Bj_new;
6692: }
6694: /* Create new submatrices for on-process and off-process coupling */
6695: PetscScalar *Aa = NULL, *Ba = NULL;
6696: MatType rtype;
6697: Mat_SeqAIJ *a, *b;
6698: if (!mat->structure_only) {
6699: PetscCall(PetscCalloc1(Annz, &Aa)); /* Zero matrix on device */
6700: PetscCall(PetscCalloc1(Bnnz, &Ba));
6701: }
6702: /* make Aj[] local, i.e, based off the start column of the diagonal portion */
6703: if (cstart) {
6704: for (k = 0; k < Annz; k++) Aj[k] -= cstart;
6705: }
6707: PetscCall(MatGetRootType_Private(mat, &rtype));
6709: MatSeqXAIJGetOptions_Private(mpiaij->A);
6710: PetscCall(MatDestroy(&mpiaij->A));
6711: PetscCall(MatCreateSeqAIJWithArrays(PETSC_COMM_SELF, m, n, Ai, Aj, Aa, &mpiaij->A));
6712: PetscCall(MatSetBlockSizesFromMats(mpiaij->A, mat, mat));
6713: MatSeqXAIJRestoreOptions_Private(mpiaij->A);
6714: PetscCall(MatSetOption(mpiaij->A, MAT_STRUCTURE_ONLY, mat->structure_only));
6716: MatSeqXAIJGetOptions_Private(mpiaij->B);
6717: PetscCall(MatDestroy(&mpiaij->B));
6718: PetscCall(MatCreateSeqAIJWithArrays(PETSC_COMM_SELF, m, mat->cmap->N, Bi, Bj, Ba, &mpiaij->B));
6719: PetscCall(MatSetBlockSizesFromMats(mpiaij->B, mat, mat));
6720: MatSeqXAIJRestoreOptions_Private(mpiaij->B);
6721: PetscCall(MatSetOption(mpiaij->B, MAT_STRUCTURE_ONLY, mat->structure_only));
6723: PetscCall(MatSetUpMultiply_MPIAIJ(mat));
6724: mat->was_assembled = PETSC_TRUE; // was_assembled in effect means the Mvctx is built; doing so avoids redundant MatSetUpMultiply_MPIAIJ
6725: mat->nonzerostate = mpiaij->A->nonzerostate + mpiaij->B->nonzerostate;
6726: PetscCallMPI(MPIU_Allreduce(MPI_IN_PLACE, &mat->nonzerostate, 1, MPIU_INT64, MPI_SUM, PetscObjectComm((PetscObject)mat)));
6728: a = (Mat_SeqAIJ *)mpiaij->A->data;
6729: b = (Mat_SeqAIJ *)mpiaij->B->data;
6730: a->free_a = (PetscBool)!mat->structure_only;
6731: a->free_ij = PETSC_TRUE;
6732: b->free_a = (PetscBool)!mat->structure_only;
6733: b->free_ij = PETSC_TRUE;
6734: a->maxnz = a->nz;
6735: b->maxnz = b->nz;
6737: /* conversion must happen AFTER multiply setup */
6738: PetscCall(MatConvert(mpiaij->A, rtype, MAT_INPLACE_MATRIX, &mpiaij->A));
6739: PetscCall(MatConvert(mpiaij->B, rtype, MAT_INPLACE_MATRIX, &mpiaij->B));
6740: PetscCall(VecDestroy(&mpiaij->lvec));
6741: PetscCall(MatCreateVecs(mpiaij->B, &mpiaij->lvec, NULL));
6743: // Put the COO struct in a container and then attach that to the matrix
6744: PetscCall(PetscMalloc1(1, &coo));
6745: coo->n = coo_n;
6746: coo->sf = sf2;
6747: coo->sendlen = nleaves;
6748: coo->recvlen = nroots;
6749: coo->Annz = Annz;
6750: coo->Bnnz = Bnnz;
6751: coo->Annz2 = Annz2;
6752: coo->Bnnz2 = Bnnz2;
6753: coo->Atot1 = Atot1;
6754: coo->Atot2 = Atot2;
6755: coo->Btot1 = Btot1;
6756: coo->Btot2 = Btot2;
6757: coo->Ajmap1 = Ajmap1;
6758: coo->Aperm1 = Aperm1;
6759: coo->Bjmap1 = Bjmap1;
6760: coo->Bperm1 = Bperm1;
6761: coo->Aimap2 = Aimap2;
6762: coo->Ajmap2 = Ajmap2;
6763: coo->Aperm2 = Aperm2;
6764: coo->Bimap2 = Bimap2;
6765: coo->Bjmap2 = Bjmap2;
6766: coo->Bperm2 = Bperm2;
6767: coo->Cperm1 = Cperm1;
6768: // Allocate in preallocation. If not used, it has zero cost on host
6769: if (!mat->structure_only) PetscCall(PetscMalloc2(coo->sendlen, &coo->sendbuf, coo->recvlen, &coo->recvbuf));
6770: else coo->sendbuf = coo->recvbuf = NULL;
6771: coo->Anonzerostate = mpiaij->A->nonzerostate;
6772: coo->Bnonzerostate = mpiaij->B->nonzerostate;
6773: PetscCall(PetscContainerCreate(PETSC_COMM_SELF, &container));
6774: PetscCall(PetscContainerSetPointer(container, coo));
6775: PetscCall(PetscContainerSetCtxDestroy(container, MatCOOStructDestroy_MPIAIJ));
6776: PetscCall(PetscObjectCompose((PetscObject)mat, "__PETSc_MatCOOStruct_Host", (PetscObject)container));
6777: PetscCall(PetscContainerDestroy(&container));
6778: PetscFunctionReturn(PETSC_SUCCESS);
6779: }
6781: // PetscClangLinter pragma disable: -fdoc-internal-linkage
6782: /*@
6783: MatMPIAIJCheckCOONonzeroState - Checks that the COO maps built by `MatSetPreallocationCOO()` can still be used by
6784: `MatSetValuesCOO()` on a `MATMPIAIJ` matrix
6786: Not Collective
6788: Input Parameter:
6789: . mat - the `MATMPIAIJ` matrix
6791: Level: developer
6793: Notes:
6794: The maps address the nonzeros of the diagonal and off-diagonal blocks by position, so they are only valid while the blocks keep
6795: the nonzero patterns built by `MatSetPreallocationCOO()`. Any change to them, for example a new nonzero inserted with
6796: `MatSetValues()`, would make `MatSetValuesCOO()` write values into the wrong locations, so this routine generates an error
6797: instead. It also generates an error when `MatSetPreallocationCOO()` has not been called.
6799: The check is local to each MPI process, so only the processes whose blocks changed generate the error.
6801: The `MatSetValuesCOO()` implementations of `MATMPIAIJ` and its device subtypes call this routine before using the maps.
6803: .seealso: [](ch_matrices), `Mat`, `MATMPIAIJ`, `MatSetPreallocationCOO()`, `MatSetValuesCOO()`, `MatSeqAIJCheckCOONonzeroState()`
6804: @*/
6805: PetscErrorCode MatMPIAIJCheckCOONonzeroState(Mat mat)
6806: {
6807: Mat_MPIAIJ *mpiaij = (Mat_MPIAIJ *)mat->data;
6808: PetscContainer container;
6809: MatCOOStruct_MPIAIJ *coo;
6811: PetscFunctionBegin;
6812: PetscCall(PetscObjectQuery((PetscObject)mat, "__PETSc_MatCOOStruct_Host", (PetscObject *)&container));
6813: PetscCheck(container, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "MatSetPreallocationCOO() must be called before MatSetValuesCOO()");
6814: PetscCall(PetscContainerGetPointer(container, &coo));
6815: PetscCheck(coo->Anonzerostate == mpiaij->A->nonzerostate && coo->Bnonzerostate == mpiaij->B->nonzerostate, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "The nonzero pattern of the matrix has changed since MatSetPreallocationCOO(), for example because MatSetValues() inserted a new nonzero; call MatSetPreallocationCOO() again before MatSetValuesCOO(), or stop inserting new nonzeros with MatSetValues()");
6816: PetscFunctionReturn(PETSC_SUCCESS);
6817: }
6819: static PetscErrorCode MatSetValuesCOO_MPIAIJ(Mat mat, const PetscScalar v[], InsertMode imode)
6820: {
6821: Mat_MPIAIJ *mpiaij = (Mat_MPIAIJ *)mat->data;
6822: Mat A = mpiaij->A, B = mpiaij->B;
6823: PetscScalar *Aa, *Ba;
6824: PetscScalar *sendbuf, *recvbuf;
6825: const PetscCount *Ajmap1, *Ajmap2, *Aimap2;
6826: const PetscCount *Bjmap1, *Bjmap2, *Bimap2;
6827: const PetscCount *Aperm1, *Aperm2, *Bperm1, *Bperm2;
6828: const PetscCount *Cperm1;
6829: PetscContainer container;
6830: MatCOOStruct_MPIAIJ *coo;
6832: PetscFunctionBegin;
6833: PetscCall(MatMPIAIJCheckCOONonzeroState(mat));
6834: PetscCall(PetscObjectQuery((PetscObject)mat, "__PETSc_MatCOOStruct_Host", (PetscObject *)&container));
6835: PetscCall(PetscContainerGetPointer(container, &coo));
6836: sendbuf = coo->sendbuf;
6837: recvbuf = coo->recvbuf;
6838: Ajmap1 = coo->Ajmap1;
6839: Ajmap2 = coo->Ajmap2;
6840: Aimap2 = coo->Aimap2;
6841: Bjmap1 = coo->Bjmap1;
6842: Bjmap2 = coo->Bjmap2;
6843: Bimap2 = coo->Bimap2;
6844: Aperm1 = coo->Aperm1;
6845: Aperm2 = coo->Aperm2;
6846: Bperm1 = coo->Bperm1;
6847: Bperm2 = coo->Bperm2;
6848: Cperm1 = coo->Cperm1;
6850: PetscCall(MatSeqAIJGetArray(A, &Aa)); /* Might read and write matrix values */
6851: PetscCall(MatSeqAIJGetArray(B, &Ba));
6853: /* Pack entries to be sent to remote */
6854: for (PetscCount i = 0; i < coo->sendlen; i++) sendbuf[i] = v[Cperm1[i]];
6856: /* Send remote entries to their owner and overlap the communication with local computation */
6857: PetscCall(PetscSFReduceWithMemTypeBegin(coo->sf, MPIU_SCALAR, PETSC_MEMTYPE_HOST, sendbuf, PETSC_MEMTYPE_HOST, recvbuf, MPI_REPLACE));
6858: /* Add local entries to A and B */
6859: for (PetscCount i = 0; i < coo->Annz; i++) { /* All nonzeros in A are either zero'ed or added with a value (i.e., initialized) */
6860: PetscScalar sum = 0.0; /* Do partial summation first to improve numerical stability */
6861: for (PetscCount k = Ajmap1[i]; k < Ajmap1[i + 1]; k++) sum += v[Aperm1[k]];
6862: Aa[i] = (imode == INSERT_VALUES ? 0.0 : Aa[i]) + sum;
6863: }
6864: for (PetscCount i = 0; i < coo->Bnnz; i++) {
6865: PetscScalar sum = 0.0;
6866: for (PetscCount k = Bjmap1[i]; k < Bjmap1[i + 1]; k++) sum += v[Bperm1[k]];
6867: Ba[i] = (imode == INSERT_VALUES ? 0.0 : Ba[i]) + sum;
6868: }
6869: PetscCall(PetscSFReduceEnd(coo->sf, MPIU_SCALAR, sendbuf, recvbuf, MPI_REPLACE));
6871: /* Add received remote entries to A and B */
6872: for (PetscCount i = 0; i < coo->Annz2; i++) {
6873: for (PetscCount k = Ajmap2[i]; k < Ajmap2[i + 1]; k++) Aa[Aimap2[i]] += recvbuf[Aperm2[k]];
6874: }
6875: for (PetscCount i = 0; i < coo->Bnnz2; i++) {
6876: for (PetscCount k = Bjmap2[i]; k < Bjmap2[i + 1]; k++) Ba[Bimap2[i]] += recvbuf[Bperm2[k]];
6877: }
6878: PetscCall(MatSeqAIJRestoreArray(A, &Aa));
6879: PetscCall(MatSeqAIJRestoreArray(B, &Ba));
6880: PetscFunctionReturn(PETSC_SUCCESS);
6881: }
6883: /*MC
6884: MATMPIAIJ - MATMPIAIJ = "mpiaij" - A matrix type to be used for parallel sparse matrices.
6886: Options Database Keys:
6887: . -mat_type mpiaij - sets the matrix type to `MATMPIAIJ` during a call to `MatSetFromOptions()`
6889: Level: beginner
6891: Notes:
6892: `MatSetValues()` may be called with a `NULL` argument for the numerical values to insert zeros at the supplied row and column indices.
6894: Call `MatSetOption(A, MAT_STRUCTURE_ONLY, PETSC_TRUE)` before preallocation or `MatSetUp()` to store only the nonzero pattern.
6895: The assembled matrix has no numerical value array. Row and column indices supplied during insertion are retained, while numerical values are ignored.
6896: Such matrices can be used for structural operations, but not for numerical operations.
6898: .seealso: [](ch_matrices), `Mat`, `MATSEQAIJ`, `MATAIJ`, `MatCreateAIJ()`
6899: M*/
6900: PETSC_EXTERN PetscErrorCode MatCreate_MPIAIJ(Mat B)
6901: {
6902: Mat_MPIAIJ *b;
6903: PetscMPIInt size;
6905: PetscFunctionBegin;
6906: PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)B), &size));
6908: PetscCall(PetscNew(&b));
6909: B->data = (void *)b;
6910: B->ops[0] = MatOps_Values;
6911: B->assembled = PETSC_FALSE;
6912: B->insertmode = NOT_SET_VALUES;
6913: b->size = size;
6915: PetscCallMPI(MPI_Comm_rank(PetscObjectComm((PetscObject)B), &b->rank));
6917: /* build cache for off array entries formed */
6918: PetscCall(MatStashCreate_Private(PetscObjectComm((PetscObject)B), 1, &B->stash));
6920: b->donotstash = PETSC_FALSE;
6921: b->colmap = NULL;
6922: b->garray = NULL;
6923: b->roworiented = PETSC_TRUE;
6925: /* stuff used for matrix vector multiply */
6926: b->lvec = NULL;
6927: b->Mvctx = NULL;
6929: /* stuff for MatGetRow() */
6930: b->rowindices = NULL;
6931: b->rowvalues = NULL;
6932: b->getrowactive = PETSC_FALSE;
6934: /* flexible pointer used in CUSPARSE classes */
6935: b->spptr = NULL;
6937: PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatMPIAIJSetUseScalableIncreaseOverlap_C", MatMPIAIJSetUseScalableIncreaseOverlap_MPIAIJ));
6938: PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatStoreValues_C", MatStoreValues_MPIAIJ));
6939: PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatRetrieveValues_C", MatRetrieveValues_MPIAIJ));
6940: PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatIsTranspose_C", MatIsTranspose_MPIAIJ));
6941: PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatMPIAIJSetPreallocation_C", MatMPIAIJSetPreallocation_MPIAIJ));
6942: PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatResetPreallocation_C", MatResetPreallocation_MPIAIJ));
6943: PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatResetHash_C", MatResetHash_MPIAIJ));
6944: PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatMPIAIJSetPreallocationCSR_C", MatMPIAIJSetPreallocationCSR_MPIAIJ));
6945: PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatDiagonalScaleLocal_C", MatDiagonalScaleLocal_MPIAIJ));
6946: PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatConvert_mpiaij_mpiaijperm_C", MatConvert_MPIAIJ_MPIAIJPERM));
6947: PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatConvert_mpiaij_mpiaijsell_C", MatConvert_MPIAIJ_MPIAIJSELL));
6948: #if PetscDefined(HAVE_CUDA)
6949: PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatConvert_mpiaij_mpiaijcusparse_C", MatConvert_MPIAIJ_MPIAIJCUSPARSE));
6950: #endif
6951: #if PetscDefined(HAVE_HIP)
6952: PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatConvert_mpiaij_mpiaijhipsparse_C", MatConvert_MPIAIJ_MPIAIJHIPSPARSE));
6953: #endif
6954: #if PetscDefined(HAVE_KOKKOS_KERNELS)
6955: PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatConvert_mpiaij_mpiaijkokkos_C", MatConvert_MPIAIJ_MPIAIJKokkos));
6956: #endif
6957: #if PetscDefined(HAVE_MKL_SPARSE)
6958: PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatConvert_mpiaij_mpiaijmkl_C", MatConvert_MPIAIJ_MPIAIJMKL));
6959: #endif
6960: PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatConvert_mpiaij_mpiaijcrl_C", MatConvert_MPIAIJ_MPIAIJCRL));
6961: PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatConvert_mpiaij_mpibaij_C", MatConvert_MPIAIJ_MPIBAIJ));
6962: PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatConvert_mpiaij_mpisbaij_C", MatConvert_MPIAIJ_MPISBAIJ));
6963: PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatConvert_mpiaij_mpidense_C", MatConvert_MPIAIJ_MPIDense));
6964: #if PetscDefined(HAVE_ELEMENTAL)
6965: PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatConvert_mpiaij_elemental_C", MatConvert_MPIAIJ_Elemental));
6966: #endif
6967: #if PetscDefined(HAVE_SCALAPACK) && (PetscDefined(USE_REAL_SINGLE) || PetscDefined(USE_REAL_DOUBLE))
6968: PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatConvert_mpiaij_scalapack_C", MatConvert_AIJ_ScaLAPACK));
6969: #endif
6970: PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatConvert_mpiaij_is_C", MatConvert_XAIJ_IS));
6971: PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatConvert_mpiaij_mpisell_C", MatConvert_MPIAIJ_MPISELL));
6972: #if PetscDefined(HAVE_HYPRE)
6973: PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatConvert_mpiaij_hypre_C", MatConvert_AIJ_HYPRE));
6974: PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatProductSetFromOptions_transpose_mpiaij_mpiaij_C", MatProductSetFromOptions_Transpose_AIJ_AIJ));
6975: #endif
6976: PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatProductSetFromOptions_is_mpiaij_C", MatProductSetFromOptions_IS_XAIJ));
6977: PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatProductSetFromOptions_mpiaij_mpiaij_C", MatProductSetFromOptions_MPIAIJ));
6978: PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatSetPreallocationCOO_C", MatSetPreallocationCOO_MPIAIJ));
6979: PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatSetValuesCOO_C", MatSetValuesCOO_MPIAIJ));
6980: PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatGetMultPetscSF_C", MatGetMultPetscSF_MPIAIJ));
6981: PetscCall(PetscObjectChangeTypeName((PetscObject)B, MATMPIAIJ));
6982: PetscFunctionReturn(PETSC_SUCCESS);
6983: }
6985: /*@
6986: MatCreateMPIAIJWithSplitArrays - creates a `MATMPIAIJ` matrix using arrays that contain the "diagonal"
6987: and "off-diagonal" part of the matrix in CSR format.
6989: Collective
6991: Input Parameters:
6992: + comm - MPI communicator
6993: . m - number of local rows (Cannot be `PETSC_DECIDE`)
6994: . n - This value should be the same as the local size used in creating the
6995: x vector for the matrix-vector product $y = Ax$. (or `PETSC_DECIDE` to have
6996: calculated if `N` is given) For square matrices `n` is almost always `m`.
6997: . M - number of global rows (or `PETSC_DETERMINE` to have calculated if `m` is given)
6998: . N - number of global columns (or `PETSC_DETERMINE` to have calculated if `n` is given)
6999: . 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
7000: . j - column indices, which must be local, i.e., based off the start column of the diagonal portion
7001: . a - matrix values
7002: . 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
7003: . oj - column indices, which must be global, representing global columns in the `MATMPIAIJ` matrix
7004: - oa - matrix values
7006: Output Parameter:
7007: . mat - the matrix
7009: Level: advanced
7011: Notes:
7012: The `i`, `j`, and `a` arrays ARE NOT copied by this routine into the internal format used by PETSc (even in Fortran). The user
7013: must free the arrays once the matrix has been destroyed and not before.
7015: The `i` and `j` indices are 0 based
7017: See `MatCreateAIJ()` for the definition of "diagonal" and "off-diagonal" portion of the matrix
7019: This sets local rows and cannot be used to set off-processor values.
7021: Use of this routine is discouraged because it is inflexible and cumbersome to use. It is extremely rare that a
7022: legacy application natively assembles into exactly this split format. The code to do so is nontrivial and does
7023: not easily support in-place reassembly. It is recommended to use MatSetValues() (or a variant thereof) because
7024: the resulting assembly is easier to implement, will work with any matrix format, and the user does not have to
7025: keep track of the underlying array. Use `MatSetOption`(A,`MAT_NO_OFF_PROC_ENTRIES`,`PETSC_TRUE`) to disable all
7026: communication if it is known that only local entries will be set.
7028: .seealso: [](ch_matrices), `Mat`, `MatCreate()`, `MatCreateSeqAIJ()`, `MatSetValues()`, `MatMPIAIJSetPreallocation()`, `MatMPIAIJSetPreallocationCSR()`,
7029: `MATMPIAIJ`, `MatCreateAIJ()`, `MatCreateMPIAIJWithArrays()`
7030: @*/
7031: 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)
7032: {
7033: Mat_MPIAIJ *maij;
7035: PetscFunctionBegin;
7036: PetscCheck(m >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "local number of rows (m) cannot be PETSC_DECIDE, or negative");
7037: PetscCheck(i[0] == 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "i (row indices) must start with 0");
7038: PetscCheck(oi[0] == 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "oi (row indices) must start with 0");
7039: PetscCall(MatCreate(comm, mat));
7040: PetscCall(MatSetSizes(*mat, m, n, M, N));
7041: PetscCall(MatSetType(*mat, MATMPIAIJ));
7042: maij = (Mat_MPIAIJ *)(*mat)->data;
7044: (*mat)->preallocated = PETSC_TRUE;
7046: PetscCall(PetscLayoutSetUp((*mat)->rmap));
7047: PetscCall(PetscLayoutSetUp((*mat)->cmap));
7049: PetscCall(MatCreateSeqAIJWithArrays(PETSC_COMM_SELF, m, n, i, j, a, &maij->A));
7050: PetscCall(MatCreateSeqAIJWithArrays(PETSC_COMM_SELF, m, (*mat)->cmap->N, oi, oj, oa, &maij->B));
7052: PetscCall(MatSetOption(*mat, MAT_NO_OFF_PROC_ENTRIES, PETSC_TRUE));
7053: PetscCall(MatAssemblyBegin(*mat, MAT_FINAL_ASSEMBLY));
7054: PetscCall(MatAssemblyEnd(*mat, MAT_FINAL_ASSEMBLY));
7055: PetscCall(MatSetOption(*mat, MAT_NO_OFF_PROC_ENTRIES, PETSC_FALSE));
7056: PetscCall(MatSetOption(*mat, MAT_NEW_NONZERO_LOCATION_ERR, PETSC_TRUE));
7057: PetscFunctionReturn(PETSC_SUCCESS);
7058: }
7060: typedef struct {
7061: Mat *mp; /* intermediate products */
7062: PetscBool *mptmp; /* is the intermediate product temporary ? */
7063: PetscInt cp; /* number of intermediate products */
7065: /* support for MatGetBrowsOfAoCols_MPIAIJ for P_oth */
7066: PetscInt *startsj_s, *startsj_r;
7067: PetscScalar *bufa;
7068: Mat P_oth;
7070: /* may take advantage of merging product->B */
7071: Mat Bloc; /* B-local by merging diag and off-diag */
7073: /* cusparse does not have support to split between symbolic and numeric phases.
7074: When api_user is true, we don't need to update the numerical values
7075: of the temporary storage */
7076: PetscBool reusesym;
7078: /* support for COO values insertion */
7079: PetscScalar *coo_v, *coo_w; /* store on-process and off-process COO scalars, and used as MPI recv/send buffers respectively */
7080: PetscInt **own; /* own[i] points to address of on-process COO indices for Mat mp[i] */
7081: PetscInt **off; /* off[i] points to address of off-process COO indices for Mat mp[i] */
7082: PetscBool hasoffproc; /* if true, have off-process values insertion (i.e. AtB or PtAP) */
7083: PetscSF sf; /* used for non-local values insertion and memory malloc */
7084: PetscMemType mtype;
7086: /* customization */
7087: PetscBool abmerge;
7088: PetscBool P_oth_bind;
7089: } MatMatMPIAIJBACKEND;
7091: static PetscErrorCode MatProductCtxDestroy_MatMatMPIAIJBACKEND(PetscCtxRt data)
7092: {
7093: MatMatMPIAIJBACKEND *mmdata = *(MatMatMPIAIJBACKEND **)data;
7094: PetscInt i;
7096: PetscFunctionBegin;
7097: PetscCall(PetscFree2(mmdata->startsj_s, mmdata->startsj_r));
7098: PetscCall(PetscFree(mmdata->bufa));
7099: PetscCall(PetscSFFree(mmdata->sf, mmdata->mtype, mmdata->coo_v));
7100: PetscCall(PetscSFFree(mmdata->sf, mmdata->mtype, mmdata->coo_w));
7101: PetscCall(MatDestroy(&mmdata->P_oth));
7102: PetscCall(MatDestroy(&mmdata->Bloc));
7103: PetscCall(PetscSFDestroy(&mmdata->sf));
7104: for (i = 0; i < mmdata->cp; i++) PetscCall(MatDestroy(&mmdata->mp[i]));
7105: PetscCall(PetscFree2(mmdata->mp, mmdata->mptmp));
7106: PetscCall(PetscFree(mmdata->own[0]));
7107: PetscCall(PetscFree(mmdata->own));
7108: PetscCall(PetscFree(mmdata->off[0]));
7109: PetscCall(PetscFree(mmdata->off));
7110: PetscCall(PetscFree(mmdata));
7111: PetscFunctionReturn(PETSC_SUCCESS);
7112: }
7114: /* Copy selected n entries with indices in idx[] of A to v[].
7115: If idx is NULL, copy the whole data array of A to v[]
7116: */
7117: static PetscErrorCode MatSeqAIJCopySubArray(Mat A, PetscInt n, const PetscInt idx[], PetscScalar v[])
7118: {
7119: PetscErrorCode (*f)(Mat, PetscInt, const PetscInt[], PetscScalar[]);
7121: PetscFunctionBegin;
7122: PetscCall(PetscObjectQueryFunction((PetscObject)A, "MatSeqAIJCopySubArray_C", &f));
7123: if (f) PetscCall((*f)(A, n, idx, v));
7124: else {
7125: const PetscScalar *vv;
7127: PetscCall(MatSeqAIJGetArrayRead(A, &vv));
7128: if (n && idx) {
7129: PetscScalar *w = v;
7130: const PetscInt *oi = idx;
7132: for (PetscInt j = 0; j < n; j++) *w++ = vv[*oi++];
7133: } else {
7134: PetscCall(PetscArraycpy(v, vv, n));
7135: }
7136: PetscCall(MatSeqAIJRestoreArrayRead(A, &vv));
7137: }
7138: PetscFunctionReturn(PETSC_SUCCESS);
7139: }
7141: static PetscErrorCode MatProductNumeric_MPIAIJBACKEND(Mat C)
7142: {
7143: MatMatMPIAIJBACKEND *mmdata;
7144: PetscInt i, n_d, n_o;
7146: PetscFunctionBegin;
7147: MatCheckProduct(C, 1);
7148: PetscCheck(C->product->data, PetscObjectComm((PetscObject)C), PETSC_ERR_PLIB, "Product data empty");
7149: mmdata = (MatMatMPIAIJBACKEND *)C->product->data;
7150: if (!mmdata->reusesym) { /* update temporary matrices */
7151: 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));
7152: if (mmdata->Bloc) PetscCall(MatMPIAIJGetLocalMatMerge(C->product->B, MAT_REUSE_MATRIX, NULL, &mmdata->Bloc));
7153: }
7154: mmdata->reusesym = PETSC_FALSE;
7156: for (i = 0; i < mmdata->cp; i++) {
7157: 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]);
7158: PetscCall((*mmdata->mp[i]->ops->productnumeric)(mmdata->mp[i]));
7159: }
7160: for (i = 0, n_d = 0, n_o = 0; i < mmdata->cp; i++) {
7161: PetscInt noff;
7163: PetscCall(PetscIntCast(mmdata->off[i + 1] - mmdata->off[i], &noff));
7164: if (mmdata->mptmp[i]) continue;
7165: if (noff) {
7166: PetscInt nown;
7168: PetscCall(PetscIntCast(mmdata->own[i + 1] - mmdata->own[i], &nown));
7169: PetscCall(MatSeqAIJCopySubArray(mmdata->mp[i], noff, mmdata->off[i], mmdata->coo_w + n_o));
7170: PetscCall(MatSeqAIJCopySubArray(mmdata->mp[i], nown, mmdata->own[i], mmdata->coo_v + n_d));
7171: n_o += noff;
7172: n_d += nown;
7173: } else {
7174: Mat_SeqAIJ *mm = (Mat_SeqAIJ *)mmdata->mp[i]->data;
7176: PetscCall(MatSeqAIJCopySubArray(mmdata->mp[i], mm->nz, NULL, mmdata->coo_v + n_d));
7177: n_d += mm->nz;
7178: }
7179: }
7180: if (mmdata->hasoffproc) { /* offprocess insertion */
7181: PetscCall(PetscSFGatherBegin(mmdata->sf, MPIU_SCALAR, mmdata->coo_w, mmdata->coo_v + n_d));
7182: PetscCall(PetscSFGatherEnd(mmdata->sf, MPIU_SCALAR, mmdata->coo_w, mmdata->coo_v + n_d));
7183: }
7184: PetscCall(MatSetValuesCOO(C, mmdata->coo_v, INSERT_VALUES));
7185: PetscFunctionReturn(PETSC_SUCCESS);
7186: }
7188: /* Support for Pt * A, A * P, or Pt * A * P */
7189: #define MAX_NUMBER_INTERMEDIATE 4
7190: PetscErrorCode MatProductSymbolic_MPIAIJBACKEND(Mat C)
7191: {
7192: Mat_Product *product = C->product;
7193: Mat A, P, mp[MAX_NUMBER_INTERMEDIATE]; /* A, P and a series of intermediate matrices */
7194: Mat_MPIAIJ *a, *p;
7195: MatMatMPIAIJBACKEND *mmdata;
7196: ISLocalToGlobalMapping P_oth_l2g = NULL;
7197: IS glob = NULL;
7198: const char *prefix;
7199: char pprefix[256];
7200: const PetscInt *globidx, *P_oth_idx;
7201: PetscInt i, j, cp, m, n, M, N, *coo_i, *coo_j;
7202: PetscCount ncoo, ncoo_d, ncoo_o, ncoo_oown;
7203: PetscInt cmapt[MAX_NUMBER_INTERMEDIATE], rmapt[MAX_NUMBER_INTERMEDIATE]; /* col/row map type for each Mat in mp[]. */
7204: /* type-0: consecutive, start from 0; type-1: consecutive with */
7205: /* a base offset; type-2: sparse with a local to global map table */
7206: const PetscInt *cmapa[MAX_NUMBER_INTERMEDIATE], *rmapa[MAX_NUMBER_INTERMEDIATE]; /* col/row local to global map array (table) for type-2 map type */
7208: MatProductType ptype;
7209: PetscBool mptmp[MAX_NUMBER_INTERMEDIATE], hasoffproc = PETSC_FALSE, iscuda, iship, iskokk;
7210: PetscMPIInt size;
7212: PetscFunctionBegin;
7213: MatCheckProduct(C, 1);
7214: PetscCheck(!product->data, PetscObjectComm((PetscObject)C), PETSC_ERR_PLIB, "Product data not empty");
7215: ptype = product->type;
7216: if (product->A->symmetric == PETSC_BOOL3_TRUE && ptype == MATPRODUCT_AtB) {
7217: ptype = MATPRODUCT_AB;
7218: product->symbolic_used_the_fact_A_is_symmetric = PETSC_TRUE;
7219: }
7220: switch (ptype) {
7221: case MATPRODUCT_AB:
7222: A = product->A;
7223: P = product->B;
7224: m = A->rmap->n;
7225: n = P->cmap->n;
7226: M = A->rmap->N;
7227: N = P->cmap->N;
7228: hasoffproc = PETSC_FALSE; /* will not scatter mat product values to other processes */
7229: break;
7230: case MATPRODUCT_AtB:
7231: P = product->A;
7232: A = product->B;
7233: m = P->cmap->n;
7234: n = A->cmap->n;
7235: M = P->cmap->N;
7236: N = A->cmap->N;
7237: hasoffproc = PETSC_TRUE;
7238: break;
7239: case MATPRODUCT_PtAP:
7240: A = product->A;
7241: P = product->B;
7242: m = P->cmap->n;
7243: n = P->cmap->n;
7244: M = P->cmap->N;
7245: N = P->cmap->N;
7246: hasoffproc = PETSC_TRUE;
7247: break;
7248: default:
7249: SETERRQ(PetscObjectComm((PetscObject)C), PETSC_ERR_PLIB, "Not for product type %s", MatProductTypes[ptype]);
7250: }
7251: PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)C), &size));
7252: if (size == 1) hasoffproc = PETSC_FALSE;
7254: /* defaults */
7255: for (i = 0; i < MAX_NUMBER_INTERMEDIATE; i++) {
7256: mp[i] = NULL;
7257: mptmp[i] = PETSC_FALSE;
7258: rmapt[i] = -1;
7259: cmapt[i] = -1;
7260: rmapa[i] = NULL;
7261: cmapa[i] = NULL;
7262: }
7264: /* customization */
7265: PetscCall(PetscNew(&mmdata));
7266: mmdata->reusesym = product->api_user;
7267: if (ptype == MATPRODUCT_AB) {
7268: if (product->api_user) {
7269: PetscOptionsBegin(PetscObjectComm((PetscObject)C), ((PetscObject)C)->prefix, "MatMatMult", "Mat");
7270: PetscCall(PetscOptionsBool("-matmatmult_backend_mergeB", "Merge product->B local matrices", "MatMatMult", mmdata->abmerge, &mmdata->abmerge, NULL));
7271: PetscCall(PetscOptionsBool("-matmatmult_backend_pothbind", "Bind P_oth to CPU", "MatBindToCPU", mmdata->P_oth_bind, &mmdata->P_oth_bind, NULL));
7272: PetscOptionsEnd();
7273: } else {
7274: PetscOptionsBegin(PetscObjectComm((PetscObject)C), ((PetscObject)C)->prefix, "MatProduct_AB", "Mat");
7275: PetscCall(PetscOptionsBool("-mat_product_algorithm_backend_mergeB", "Merge product->B local matrices", "MatMatMult", mmdata->abmerge, &mmdata->abmerge, NULL));
7276: PetscCall(PetscOptionsBool("-mat_product_algorithm_backend_pothbind", "Bind P_oth to CPU", "MatBindToCPU", mmdata->P_oth_bind, &mmdata->P_oth_bind, NULL));
7277: PetscOptionsEnd();
7278: }
7279: } else if (ptype == MATPRODUCT_PtAP) {
7280: if (product->api_user) {
7281: PetscOptionsBegin(PetscObjectComm((PetscObject)C), ((PetscObject)C)->prefix, "MatPtAP", "Mat");
7282: PetscCall(PetscOptionsBool("-matptap_backend_pothbind", "Bind P_oth to CPU", "MatBindToCPU", mmdata->P_oth_bind, &mmdata->P_oth_bind, NULL));
7283: PetscOptionsEnd();
7284: } else {
7285: PetscOptionsBegin(PetscObjectComm((PetscObject)C), ((PetscObject)C)->prefix, "MatProduct_PtAP", "Mat");
7286: PetscCall(PetscOptionsBool("-mat_product_algorithm_backend_pothbind", "Bind P_oth to CPU", "MatBindToCPU", mmdata->P_oth_bind, &mmdata->P_oth_bind, NULL));
7287: PetscOptionsEnd();
7288: }
7289: }
7290: a = (Mat_MPIAIJ *)A->data;
7291: p = (Mat_MPIAIJ *)P->data;
7292: PetscCall(MatSetSizes(C, m, n, M, N));
7293: PetscCall(PetscLayoutSetUp(C->rmap));
7294: PetscCall(PetscLayoutSetUp(C->cmap));
7295: PetscCall(MatSetType(C, ((PetscObject)A)->type_name));
7296: PetscCall(MatGetOptionsPrefix(C, &prefix));
7298: cp = 0;
7299: switch (ptype) {
7300: case MATPRODUCT_AB: /* A * P */
7301: PetscCall(MatGetBrowsOfAoCols_MPIAIJ(A, P, MAT_INITIAL_MATRIX, &mmdata->startsj_s, &mmdata->startsj_r, &mmdata->bufa, &mmdata->P_oth));
7303: /* A_diag * P_local (merged or not) */
7304: if (mmdata->abmerge) { /* P's diagonal and off-diag blocks are merged to one matrix, then multiplied by A_diag */
7305: /* P is product->B */
7306: PetscCall(MatMPIAIJGetLocalMatMerge(P, MAT_INITIAL_MATRIX, &glob, &mmdata->Bloc));
7307: PetscCall(MatProductCreate(a->A, mmdata->Bloc, NULL, &mp[cp]));
7308: PetscCall(MatProductSetType(mp[cp], MATPRODUCT_AB));
7309: PetscCall(MatProductSetFill(mp[cp], product->fill));
7310: PetscCall(PetscSNPrintf(pprefix, sizeof(pprefix), "backend_p%" PetscInt_FMT "_", cp));
7311: PetscCall(MatSetOptionsPrefix(mp[cp], prefix));
7312: PetscCall(MatAppendOptionsPrefix(mp[cp], pprefix));
7313: mp[cp]->product->api_user = product->api_user;
7314: PetscCall(MatProductSetFromOptions(mp[cp]));
7315: PetscCall((*mp[cp]->ops->productsymbolic)(mp[cp]));
7316: PetscCall(ISGetIndices(glob, &globidx));
7317: rmapt[cp] = 1;
7318: cmapt[cp] = 2;
7319: cmapa[cp] = globidx;
7320: mptmp[cp] = PETSC_FALSE;
7321: cp++;
7322: } else { /* A_diag * P_diag and A_diag * P_off */
7323: PetscCall(MatProductCreate(a->A, p->A, NULL, &mp[cp]));
7324: PetscCall(MatProductSetType(mp[cp], MATPRODUCT_AB));
7325: PetscCall(MatProductSetFill(mp[cp], product->fill));
7326: PetscCall(PetscSNPrintf(pprefix, sizeof(pprefix), "backend_p%" PetscInt_FMT "_", cp));
7327: PetscCall(MatSetOptionsPrefix(mp[cp], prefix));
7328: PetscCall(MatAppendOptionsPrefix(mp[cp], pprefix));
7329: mp[cp]->product->api_user = product->api_user;
7330: PetscCall(MatProductSetFromOptions(mp[cp]));
7331: PetscCall((*mp[cp]->ops->productsymbolic)(mp[cp]));
7332: rmapt[cp] = 1;
7333: cmapt[cp] = 1;
7334: mptmp[cp] = PETSC_FALSE;
7335: cp++;
7336: PetscCall(MatProductCreate(a->A, p->B, NULL, &mp[cp]));
7337: PetscCall(MatProductSetType(mp[cp], MATPRODUCT_AB));
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: rmapt[cp] = 1;
7346: cmapt[cp] = 2;
7347: cmapa[cp] = p->garray;
7348: mptmp[cp] = PETSC_FALSE;
7349: cp++;
7350: }
7352: /* A_off * P_other */
7353: if (mmdata->P_oth) {
7354: PetscCall(MatSeqAIJCompactOutExtraColumns_SeqAIJ(mmdata->P_oth, &P_oth_l2g)); /* make P_oth use local col ids */
7355: PetscCall(ISLocalToGlobalMappingGetIndices(P_oth_l2g, &P_oth_idx));
7356: PetscCall(MatSetType(mmdata->P_oth, ((PetscObject)a->B)->type_name));
7357: PetscCall(MatBindToCPU(mmdata->P_oth, mmdata->P_oth_bind));
7358: PetscCall(MatProductCreate(a->B, mmdata->P_oth, NULL, &mp[cp]));
7359: PetscCall(MatProductSetType(mp[cp], MATPRODUCT_AB));
7360: PetscCall(MatProductSetFill(mp[cp], product->fill));
7361: PetscCall(PetscSNPrintf(pprefix, sizeof(pprefix), "backend_p%" PetscInt_FMT "_", cp));
7362: PetscCall(MatSetOptionsPrefix(mp[cp], prefix));
7363: PetscCall(MatAppendOptionsPrefix(mp[cp], pprefix));
7364: mp[cp]->product->api_user = product->api_user;
7365: PetscCall(MatProductSetFromOptions(mp[cp]));
7366: PetscCall((*mp[cp]->ops->productsymbolic)(mp[cp]));
7367: rmapt[cp] = 1;
7368: cmapt[cp] = 2;
7369: cmapa[cp] = P_oth_idx;
7370: mptmp[cp] = PETSC_FALSE;
7371: cp++;
7372: }
7373: break;
7375: case MATPRODUCT_AtB: /* (P^t * A): P_diag * A_loc + P_off * A_loc */
7376: /* A is product->B */
7377: PetscCall(MatMPIAIJGetLocalMatMerge(A, MAT_INITIAL_MATRIX, &glob, &mmdata->Bloc));
7378: if (A == P) { /* when A==P, we can take advantage of the already merged mmdata->Bloc */
7379: PetscCall(MatProductCreate(mmdata->Bloc, mmdata->Bloc, NULL, &mp[cp]));
7380: PetscCall(MatProductSetType(mp[cp], MATPRODUCT_AtB));
7381: PetscCall(MatProductSetFill(mp[cp], product->fill));
7382: PetscCall(PetscSNPrintf(pprefix, sizeof(pprefix), "backend_p%" PetscInt_FMT "_", cp));
7383: PetscCall(MatSetOptionsPrefix(mp[cp], prefix));
7384: PetscCall(MatAppendOptionsPrefix(mp[cp], pprefix));
7385: mp[cp]->product->api_user = product->api_user;
7386: PetscCall(MatProductSetFromOptions(mp[cp]));
7387: PetscCall((*mp[cp]->ops->productsymbolic)(mp[cp]));
7388: PetscCall(ISGetIndices(glob, &globidx));
7389: rmapt[cp] = 2;
7390: rmapa[cp] = globidx;
7391: cmapt[cp] = 2;
7392: cmapa[cp] = globidx;
7393: mptmp[cp] = PETSC_FALSE;
7394: cp++;
7395: } else {
7396: PetscCall(MatProductCreate(p->A, mmdata->Bloc, NULL, &mp[cp]));
7397: PetscCall(MatProductSetType(mp[cp], MATPRODUCT_AtB));
7398: PetscCall(MatProductSetFill(mp[cp], product->fill));
7399: PetscCall(PetscSNPrintf(pprefix, sizeof(pprefix), "backend_p%" PetscInt_FMT "_", cp));
7400: PetscCall(MatSetOptionsPrefix(mp[cp], prefix));
7401: PetscCall(MatAppendOptionsPrefix(mp[cp], pprefix));
7402: mp[cp]->product->api_user = product->api_user;
7403: PetscCall(MatProductSetFromOptions(mp[cp]));
7404: PetscCall((*mp[cp]->ops->productsymbolic)(mp[cp]));
7405: PetscCall(ISGetIndices(glob, &globidx));
7406: rmapt[cp] = 1;
7407: cmapt[cp] = 2;
7408: cmapa[cp] = globidx;
7409: mptmp[cp] = PETSC_FALSE;
7410: cp++;
7411: PetscCall(MatProductCreate(p->B, mmdata->Bloc, NULL, &mp[cp]));
7412: PetscCall(MatProductSetType(mp[cp], MATPRODUCT_AtB));
7413: PetscCall(MatProductSetFill(mp[cp], product->fill));
7414: PetscCall(PetscSNPrintf(pprefix, sizeof(pprefix), "backend_p%" PetscInt_FMT "_", cp));
7415: PetscCall(MatSetOptionsPrefix(mp[cp], prefix));
7416: PetscCall(MatAppendOptionsPrefix(mp[cp], pprefix));
7417: mp[cp]->product->api_user = product->api_user;
7418: PetscCall(MatProductSetFromOptions(mp[cp]));
7419: PetscCall((*mp[cp]->ops->productsymbolic)(mp[cp]));
7420: rmapt[cp] = 2;
7421: rmapa[cp] = p->garray;
7422: cmapt[cp] = 2;
7423: cmapa[cp] = globidx;
7424: mptmp[cp] = PETSC_FALSE;
7425: cp++;
7426: }
7427: break;
7428: case MATPRODUCT_PtAP:
7429: PetscCall(MatGetBrowsOfAoCols_MPIAIJ(A, P, MAT_INITIAL_MATRIX, &mmdata->startsj_s, &mmdata->startsj_r, &mmdata->bufa, &mmdata->P_oth));
7430: /* P is product->B */
7431: PetscCall(MatMPIAIJGetLocalMatMerge(P, MAT_INITIAL_MATRIX, &glob, &mmdata->Bloc));
7432: PetscCall(MatProductCreate(a->A, mmdata->Bloc, NULL, &mp[cp]));
7433: PetscCall(MatProductSetType(mp[cp], MATPRODUCT_PtAP));
7434: PetscCall(MatProductSetFill(mp[cp], product->fill));
7435: PetscCall(PetscSNPrintf(pprefix, sizeof(pprefix), "backend_p%" PetscInt_FMT "_", cp));
7436: PetscCall(MatSetOptionsPrefix(mp[cp], prefix));
7437: PetscCall(MatAppendOptionsPrefix(mp[cp], pprefix));
7438: mp[cp]->product->api_user = product->api_user;
7439: PetscCall(MatProductSetFromOptions(mp[cp]));
7440: PetscCall((*mp[cp]->ops->productsymbolic)(mp[cp]));
7441: PetscCall(ISGetIndices(glob, &globidx));
7442: rmapt[cp] = 2;
7443: rmapa[cp] = globidx;
7444: cmapt[cp] = 2;
7445: cmapa[cp] = globidx;
7446: mptmp[cp] = PETSC_FALSE;
7447: cp++;
7448: if (mmdata->P_oth) {
7449: PetscCall(MatSeqAIJCompactOutExtraColumns_SeqAIJ(mmdata->P_oth, &P_oth_l2g));
7450: PetscCall(ISLocalToGlobalMappingGetIndices(P_oth_l2g, &P_oth_idx));
7451: PetscCall(MatSetType(mmdata->P_oth, ((PetscObject)a->B)->type_name));
7452: PetscCall(MatBindToCPU(mmdata->P_oth, mmdata->P_oth_bind));
7453: PetscCall(MatProductCreate(a->B, mmdata->P_oth, NULL, &mp[cp]));
7454: PetscCall(MatProductSetType(mp[cp], MATPRODUCT_AB));
7455: PetscCall(MatProductSetFill(mp[cp], product->fill));
7456: PetscCall(PetscSNPrintf(pprefix, sizeof(pprefix), "backend_p%" PetscInt_FMT "_", cp));
7457: PetscCall(MatSetOptionsPrefix(mp[cp], prefix));
7458: PetscCall(MatAppendOptionsPrefix(mp[cp], pprefix));
7459: mp[cp]->product->api_user = product->api_user;
7460: PetscCall(MatProductSetFromOptions(mp[cp]));
7461: PetscCall((*mp[cp]->ops->productsymbolic)(mp[cp]));
7462: mptmp[cp] = PETSC_TRUE;
7463: cp++;
7464: PetscCall(MatProductCreate(mmdata->Bloc, mp[1], NULL, &mp[cp]));
7465: PetscCall(MatProductSetType(mp[cp], MATPRODUCT_AtB));
7466: PetscCall(MatProductSetFill(mp[cp], product->fill));
7467: PetscCall(PetscSNPrintf(pprefix, sizeof(pprefix), "backend_p%" PetscInt_FMT "_", cp));
7468: PetscCall(MatSetOptionsPrefix(mp[cp], prefix));
7469: PetscCall(MatAppendOptionsPrefix(mp[cp], pprefix));
7470: mp[cp]->product->api_user = product->api_user;
7471: PetscCall(MatProductSetFromOptions(mp[cp]));
7472: PetscCall((*mp[cp]->ops->productsymbolic)(mp[cp]));
7473: rmapt[cp] = 2;
7474: rmapa[cp] = globidx;
7475: cmapt[cp] = 2;
7476: cmapa[cp] = P_oth_idx;
7477: mptmp[cp] = PETSC_FALSE;
7478: cp++;
7479: }
7480: break;
7481: default:
7482: SETERRQ(PetscObjectComm((PetscObject)C), PETSC_ERR_PLIB, "Not for product type %s", MatProductTypes[ptype]);
7483: }
7484: /* sanity check */
7485: if (size > 1)
7486: 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);
7488: PetscCall(PetscMalloc2(cp, &mmdata->mp, cp, &mmdata->mptmp));
7489: for (i = 0; i < cp; i++) {
7490: mmdata->mp[i] = mp[i];
7491: mmdata->mptmp[i] = mptmp[i];
7492: }
7493: mmdata->cp = cp;
7494: C->product->data = mmdata;
7495: C->product->destroy = MatProductCtxDestroy_MatMatMPIAIJBACKEND;
7496: C->ops->productnumeric = MatProductNumeric_MPIAIJBACKEND;
7498: /* memory type */
7499: mmdata->mtype = PETSC_MEMTYPE_HOST;
7500: PetscCall(PetscObjectTypeCompareAny((PetscObject)C, &iscuda, MATSEQAIJCUSPARSE, MATMPIAIJCUSPARSE, ""));
7501: PetscCall(PetscObjectTypeCompareAny((PetscObject)C, &iship, MATSEQAIJHIPSPARSE, MATMPIAIJHIPSPARSE, ""));
7502: PetscCall(PetscObjectTypeCompareAny((PetscObject)C, &iskokk, MATSEQAIJKOKKOS, MATMPIAIJKOKKOS, ""));
7503: if (iscuda) mmdata->mtype = PETSC_MEMTYPE_CUDA;
7504: else if (iship) mmdata->mtype = PETSC_MEMTYPE_HIP;
7505: else if (iskokk) mmdata->mtype = PETSC_MEMTYPE_KOKKOS;
7507: /* prepare coo coordinates for values insertion */
7509: /* count total nonzeros of those intermediate seqaij Mats
7510: ncoo_d: # of nonzeros of matrices that do not have offproc entries
7511: ncoo_o: # of nonzeros (of matrices that might have offproc entries) that will be inserted to remote procs
7512: ncoo_oown: # of nonzeros (of matrices that might have offproc entries) that will be inserted locally
7513: */
7514: for (cp = 0, ncoo_d = 0, ncoo_o = 0, ncoo_oown = 0; cp < mmdata->cp; cp++) {
7515: Mat_SeqAIJ *mm = (Mat_SeqAIJ *)mp[cp]->data;
7516: if (mptmp[cp]) continue;
7517: if (rmapt[cp] == 2 && hasoffproc) { /* the rows need to be scatter to all processes (might include self) */
7518: const PetscInt *rmap = rmapa[cp];
7519: const PetscInt mr = mp[cp]->rmap->n;
7520: const PetscInt rs = C->rmap->rstart;
7521: const PetscInt re = C->rmap->rend;
7522: const PetscInt *ii = mm->i;
7523: for (i = 0; i < mr; i++) {
7524: const PetscInt gr = rmap[i];
7525: const PetscInt nz = ii[i + 1] - ii[i];
7526: if (gr < rs || gr >= re) ncoo_o += nz; /* this row is offproc */
7527: else ncoo_oown += nz; /* this row is local */
7528: }
7529: } else ncoo_d += mm->nz;
7530: }
7532: /*
7533: ncoo: total number of nonzeros (including those inserted by remote procs) belonging to this proc
7535: ncoo = ncoo_d + ncoo_oown + ncoo2, which ncoo2 is number of nonzeros inserted to me by other procs.
7537: off[0] points to a big index array, which is shared by off[1,2,...]. Similarly, for own[0].
7539: off[p]: points to the segment for matrix mp[p], storing location of nonzeros that mp[p] will insert to others
7540: own[p]: points to the segment for matrix mp[p], storing location of nonzeros that mp[p] will insert locally
7541: so, off[p+1]-off[p] is the number of nonzeros that mp[p] will send to others.
7543: coo_i/j/v[]: [ncoo] row/col/val of nonzeros belonging to this proc.
7544: 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.
7545: */
7546: PetscCall(PetscCalloc1(mmdata->cp + 1, &mmdata->off)); /* +1 to make a csr-like data structure */
7547: PetscCall(PetscCalloc1(mmdata->cp + 1, &mmdata->own));
7549: /* gather (i,j) of nonzeros inserted by remote procs */
7550: if (hasoffproc) {
7551: PetscSF msf;
7552: PetscInt ncoo2, *coo_i2, *coo_j2;
7554: PetscCall(PetscMalloc1(ncoo_o, &mmdata->off[0]));
7555: PetscCall(PetscMalloc1(ncoo_oown, &mmdata->own[0]));
7556: PetscCall(PetscMalloc2(ncoo_o, &coo_i, ncoo_o, &coo_j)); /* to collect (i,j) of entries to be sent to others */
7558: for (cp = 0, ncoo_o = 0; cp < mmdata->cp; cp++) {
7559: Mat_SeqAIJ *mm = (Mat_SeqAIJ *)mp[cp]->data;
7560: PetscInt *idxoff = mmdata->off[cp];
7561: PetscInt *idxown = mmdata->own[cp];
7562: if (!mptmp[cp] && rmapt[cp] == 2) { /* row map is sparse */
7563: const PetscInt *rmap = rmapa[cp];
7564: const PetscInt *cmap = cmapa[cp];
7565: const PetscInt *ii = mm->i;
7566: PetscInt *coi = coo_i + ncoo_o;
7567: PetscInt *coj = coo_j + ncoo_o;
7568: const PetscInt mr = mp[cp]->rmap->n;
7569: const PetscInt rs = C->rmap->rstart;
7570: const PetscInt re = C->rmap->rend;
7571: const PetscInt cs = C->cmap->rstart;
7572: for (i = 0; i < mr; i++) {
7573: const PetscInt *jj = mm->j + ii[i];
7574: const PetscInt gr = rmap[i];
7575: const PetscInt nz = ii[i + 1] - ii[i];
7576: if (gr < rs || gr >= re) { /* this is an offproc row */
7577: for (j = ii[i]; j < ii[i + 1]; j++) {
7578: *coi++ = gr;
7579: *idxoff++ = j;
7580: }
7581: if (!cmapt[cp]) { /* already global */
7582: for (j = 0; j < nz; j++) *coj++ = jj[j];
7583: } else if (cmapt[cp] == 1) { /* local to global for owned columns of C */
7584: for (j = 0; j < nz; j++) *coj++ = jj[j] + cs;
7585: } else { /* offdiag */
7586: for (j = 0; j < nz; j++) *coj++ = cmap[jj[j]];
7587: }
7588: ncoo_o += nz;
7589: } else { /* this is a local row */
7590: for (j = ii[i]; j < ii[i + 1]; j++) *idxown++ = j;
7591: }
7592: }
7593: }
7594: mmdata->off[cp + 1] = idxoff;
7595: mmdata->own[cp + 1] = idxown;
7596: }
7598: PetscCall(PetscSFCreate(PetscObjectComm((PetscObject)C), &mmdata->sf));
7599: PetscInt incoo_o;
7600: PetscCall(PetscIntCast(ncoo_o, &incoo_o));
7601: PetscCall(PetscSFSetGraphLayout(mmdata->sf, C->rmap, incoo_o /*nleaves*/, NULL /*ilocal*/, PETSC_OWN_POINTER, coo_i));
7602: PetscCall(PetscSFGetMultiSF(mmdata->sf, &msf));
7603: PetscCall(PetscSFGetGraph(msf, &ncoo2 /*nroots*/, NULL, NULL, NULL));
7604: ncoo = ncoo_d + ncoo_oown + ncoo2;
7605: PetscCall(PetscMalloc2(ncoo, &coo_i2, ncoo, &coo_j2));
7606: PetscCall(PetscSFGatherBegin(mmdata->sf, MPIU_INT, coo_i, coo_i2 + ncoo_d + ncoo_oown)); /* put (i,j) of remote nonzeros at back */
7607: PetscCall(PetscSFGatherEnd(mmdata->sf, MPIU_INT, coo_i, coo_i2 + ncoo_d + ncoo_oown));
7608: PetscCall(PetscSFGatherBegin(mmdata->sf, MPIU_INT, coo_j, coo_j2 + ncoo_d + ncoo_oown));
7609: PetscCall(PetscSFGatherEnd(mmdata->sf, MPIU_INT, coo_j, coo_j2 + ncoo_d + ncoo_oown));
7610: PetscCall(PetscFree2(coo_i, coo_j));
7611: /* allocate MPI send buffer to collect nonzero values to be sent to remote procs */
7612: PetscCall(PetscSFMalloc(mmdata->sf, mmdata->mtype, ncoo_o * sizeof(PetscScalar), (void **)&mmdata->coo_w));
7613: coo_i = coo_i2;
7614: coo_j = coo_j2;
7615: } else { /* no offproc values insertion */
7616: ncoo = ncoo_d;
7617: PetscCall(PetscMalloc2(ncoo, &coo_i, ncoo, &coo_j));
7619: PetscCall(PetscSFCreate(PetscObjectComm((PetscObject)C), &mmdata->sf));
7620: PetscCall(PetscSFSetGraph(mmdata->sf, 0, 0, NULL, PETSC_OWN_POINTER, NULL, PETSC_OWN_POINTER));
7621: PetscCall(PetscSFSetUp(mmdata->sf));
7622: }
7623: mmdata->hasoffproc = hasoffproc;
7625: /* gather (i,j) of nonzeros inserted locally */
7626: for (cp = 0, ncoo_d = 0; cp < mmdata->cp; cp++) {
7627: Mat_SeqAIJ *mm = (Mat_SeqAIJ *)mp[cp]->data;
7628: PetscInt *coi = coo_i + ncoo_d;
7629: PetscInt *coj = coo_j + ncoo_d;
7630: const PetscInt *jj = mm->j;
7631: const PetscInt *ii = mm->i;
7632: const PetscInt *cmap = cmapa[cp];
7633: const PetscInt *rmap = rmapa[cp];
7634: const PetscInt mr = mp[cp]->rmap->n;
7635: const PetscInt rs = C->rmap->rstart;
7636: const PetscInt re = C->rmap->rend;
7637: const PetscInt cs = C->cmap->rstart;
7639: if (mptmp[cp]) continue;
7640: if (rmapt[cp] == 1) { /* consecutive rows */
7641: /* fill coo_i */
7642: for (i = 0; i < mr; i++) {
7643: const PetscInt gr = i + rs;
7644: for (j = ii[i]; j < ii[i + 1]; j++) coi[j] = gr;
7645: }
7646: /* fill coo_j */
7647: if (!cmapt[cp]) { /* type-0, already global */
7648: PetscCall(PetscArraycpy(coj, jj, mm->nz));
7649: } else if (cmapt[cp] == 1) { /* type-1, local to global for consecutive columns of C */
7650: for (j = 0; j < mm->nz; j++) coj[j] = jj[j] + cs; /* lid + col start */
7651: } else { /* type-2, local to global for sparse columns */
7652: for (j = 0; j < mm->nz; j++) coj[j] = cmap[jj[j]];
7653: }
7654: ncoo_d += mm->nz;
7655: } else if (rmapt[cp] == 2) { /* sparse rows */
7656: for (i = 0; i < mr; i++) {
7657: const PetscInt *jj = mm->j + ii[i];
7658: const PetscInt gr = rmap[i];
7659: const PetscInt nz = ii[i + 1] - ii[i];
7660: if (gr >= rs && gr < re) { /* local rows */
7661: for (j = ii[i]; j < ii[i + 1]; j++) *coi++ = gr;
7662: if (!cmapt[cp]) { /* type-0, already global */
7663: for (j = 0; j < nz; j++) *coj++ = jj[j];
7664: } else if (cmapt[cp] == 1) { /* local to global for owned columns of C */
7665: for (j = 0; j < nz; j++) *coj++ = jj[j] + cs;
7666: } else { /* type-2, local to global for sparse columns */
7667: for (j = 0; j < nz; j++) *coj++ = cmap[jj[j]];
7668: }
7669: ncoo_d += nz;
7670: }
7671: }
7672: }
7673: }
7674: if (glob) PetscCall(ISRestoreIndices(glob, &globidx));
7675: PetscCall(ISDestroy(&glob));
7676: if (P_oth_l2g) PetscCall(ISLocalToGlobalMappingRestoreIndices(P_oth_l2g, &P_oth_idx));
7677: PetscCall(ISLocalToGlobalMappingDestroy(&P_oth_l2g));
7678: /* allocate an array to store all nonzeros (inserted locally or remotely) belonging to this proc */
7679: PetscCall(PetscSFMalloc(mmdata->sf, mmdata->mtype, ncoo * sizeof(PetscScalar), (void **)&mmdata->coo_v));
7681: /* set block sizes */
7682: A = product->A;
7683: P = product->B;
7684: switch (ptype) {
7685: case MATPRODUCT_PtAP:
7686: PetscCall(MatSetBlockSizes(C, P->cmap->bs, P->cmap->bs));
7687: break;
7688: case MATPRODUCT_RARt:
7689: PetscCall(MatSetBlockSizes(C, P->rmap->bs, P->rmap->bs));
7690: break;
7691: case MATPRODUCT_ABC:
7692: PetscCall(MatSetBlockSizesFromMats(C, A, product->C));
7693: break;
7694: case MATPRODUCT_AB:
7695: PetscCall(MatSetBlockSizesFromMats(C, A, P));
7696: break;
7697: case MATPRODUCT_AtB:
7698: PetscCall(MatSetBlockSizes(C, A->cmap->bs, P->cmap->bs));
7699: break;
7700: case MATPRODUCT_ABt:
7701: PetscCall(MatSetBlockSizes(C, A->rmap->bs, P->rmap->bs));
7702: break;
7703: default:
7704: SETERRQ(PetscObjectComm((PetscObject)C), PETSC_ERR_PLIB, "Not for ProductType %s", MatProductTypes[ptype]);
7705: }
7707: /* preallocate with COO data */
7708: PetscCall(MatSetPreallocationCOO(C, ncoo, coo_i, coo_j));
7709: PetscCall(PetscFree2(coo_i, coo_j));
7710: PetscFunctionReturn(PETSC_SUCCESS);
7711: }
7713: PetscErrorCode MatProductSetFromOptions_MPIAIJBACKEND(Mat mat)
7714: {
7715: Mat_Product *product = mat->product;
7716: #if PetscDefined(HAVE_DEVICE)
7717: PetscBool match = PETSC_FALSE;
7718: PetscBool usecpu = PETSC_FALSE;
7719: #else
7720: PetscBool match = PETSC_TRUE;
7721: #endif
7723: PetscFunctionBegin;
7724: MatCheckProduct(mat, 1);
7725: #if PetscDefined(HAVE_DEVICE)
7726: if (!product->A->boundtocpu && !product->B->boundtocpu) PetscCall(PetscObjectTypeCompare((PetscObject)product->B, ((PetscObject)product->A)->type_name, &match));
7727: if (match) { /* we can always fallback to the CPU if requested */
7728: switch (product->type) {
7729: case MATPRODUCT_AB:
7730: if (product->api_user) {
7731: PetscOptionsBegin(PetscObjectComm((PetscObject)mat), ((PetscObject)mat)->prefix, "MatMatMult", "Mat");
7732: PetscCall(PetscOptionsBool("-matmatmult_backend_cpu", "Use CPU code", "MatMatMult", usecpu, &usecpu, NULL));
7733: PetscOptionsEnd();
7734: } else {
7735: PetscOptionsBegin(PetscObjectComm((PetscObject)mat), ((PetscObject)mat)->prefix, "MatProduct_AB", "Mat");
7736: PetscCall(PetscOptionsBool("-mat_product_algorithm_backend_cpu", "Use CPU code", "MatMatMult", usecpu, &usecpu, NULL));
7737: PetscOptionsEnd();
7738: }
7739: break;
7740: case MATPRODUCT_AtB:
7741: if (product->api_user) {
7742: PetscOptionsBegin(PetscObjectComm((PetscObject)mat), ((PetscObject)mat)->prefix, "MatTransposeMatMult", "Mat");
7743: PetscCall(PetscOptionsBool("-mattransposematmult_backend_cpu", "Use CPU code", "MatTransposeMatMult", usecpu, &usecpu, NULL));
7744: PetscOptionsEnd();
7745: } else {
7746: PetscOptionsBegin(PetscObjectComm((PetscObject)mat), ((PetscObject)mat)->prefix, "MatProduct_AtB", "Mat");
7747: PetscCall(PetscOptionsBool("-mat_product_algorithm_backend_cpu", "Use CPU code", "MatTransposeMatMult", usecpu, &usecpu, NULL));
7748: PetscOptionsEnd();
7749: }
7750: break;
7751: case MATPRODUCT_PtAP:
7752: if (product->api_user) {
7753: PetscOptionsBegin(PetscObjectComm((PetscObject)mat), ((PetscObject)mat)->prefix, "MatPtAP", "Mat");
7754: PetscCall(PetscOptionsBool("-matptap_backend_cpu", "Use CPU code", "MatPtAP", usecpu, &usecpu, NULL));
7755: PetscOptionsEnd();
7756: } else {
7757: PetscOptionsBegin(PetscObjectComm((PetscObject)mat), ((PetscObject)mat)->prefix, "MatProduct_PtAP", "Mat");
7758: PetscCall(PetscOptionsBool("-mat_product_algorithm_backend_cpu", "Use CPU code", "MatPtAP", usecpu, &usecpu, NULL));
7759: PetscOptionsEnd();
7760: }
7761: break;
7762: default:
7763: break;
7764: }
7765: match = (PetscBool)!usecpu;
7766: }
7767: #endif
7768: if (match) {
7769: switch (product->type) {
7770: case MATPRODUCT_AB:
7771: case MATPRODUCT_AtB:
7772: case MATPRODUCT_PtAP:
7773: mat->ops->productsymbolic = MatProductSymbolic_MPIAIJBACKEND;
7774: break;
7775: default:
7776: break;
7777: }
7778: }
7779: /* fallback to MPIAIJ ops */
7780: if (!mat->ops->productsymbolic) PetscCall(MatProductSetFromOptions_MPIAIJ(mat));
7781: PetscFunctionReturn(PETSC_SUCCESS);
7782: }
7784: /*
7785: Produces a set of block column indices of the matrix row, one for each block represented in the original row
7787: n - the number of block indices in cc[]
7788: cc - the block indices (must be large enough to contain the indices)
7789: */
7790: static inline PetscErrorCode MatCollapseRow(Mat Amat, PetscInt row, PetscInt bs, PetscInt *n, PetscInt *cc)
7791: {
7792: PetscInt cnt = -1, nidx, j;
7793: const PetscInt *idx;
7795: PetscFunctionBegin;
7796: PetscCall(MatGetRow(Amat, row, &nidx, &idx, NULL));
7797: if (nidx) {
7798: cnt = 0;
7799: cc[cnt] = idx[0] / bs;
7800: for (j = 1; j < nidx; j++) {
7801: if (cc[cnt] < idx[j] / bs) cc[++cnt] = idx[j] / bs;
7802: }
7803: }
7804: PetscCall(MatRestoreRow(Amat, row, &nidx, &idx, NULL));
7805: *n = cnt + 1;
7806: PetscFunctionReturn(PETSC_SUCCESS);
7807: }
7809: /*
7810: Produces a set of block column indices of the matrix block row, one for each block represented in the original set of rows
7812: ncollapsed - the number of block indices
7813: collapsed - the block indices (must be large enough to contain the indices)
7814: */
7815: static inline PetscErrorCode MatCollapseRows(Mat Amat, PetscInt start, PetscInt bs, PetscInt *w0, PetscInt *w1, PetscInt *w2, PetscInt *ncollapsed, PetscInt **collapsed)
7816: {
7817: PetscInt i, nprev, *cprev = w0, ncur = 0, *ccur = w1, *merged = w2, *cprevtmp;
7819: PetscFunctionBegin;
7820: PetscCall(MatCollapseRow(Amat, start, bs, &nprev, cprev));
7821: for (i = start + 1; i < start + bs; i++) {
7822: PetscCall(MatCollapseRow(Amat, i, bs, &ncur, ccur));
7823: PetscCall(PetscMergeIntArray(nprev, cprev, ncur, ccur, &nprev, &merged));
7824: cprevtmp = cprev;
7825: cprev = merged;
7826: merged = cprevtmp;
7827: }
7828: *ncollapsed = nprev;
7829: if (collapsed) *collapsed = cprev;
7830: PetscFunctionReturn(PETSC_SUCCESS);
7831: }
7833: PETSC_INTERN PetscErrorCode MatCreateGraph_Simple_AIJ(Mat Amat, PetscBool symmetrize, PetscBool scale, PetscReal filter, PetscInt index_size, PetscInt index[], Mat *a_Gmat)
7834: {
7835: PetscInt Istart, Iend, Ii, jj, kk, ncols, nloc, NN, MM, bs;
7836: MPI_Comm comm;
7837: Mat Gmat;
7838: PetscBool ismpiaij, isseqaij;
7839: Mat a, b, c;
7840: MatType jtype;
7842: PetscFunctionBegin;
7843: PetscCall(PetscObjectGetComm((PetscObject)Amat, &comm));
7844: PetscCall(MatGetOwnershipRange(Amat, &Istart, &Iend));
7845: PetscCall(MatGetSize(Amat, &MM, &NN));
7846: PetscCall(MatGetBlockSize(Amat, &bs));
7847: nloc = (Iend - Istart) / bs;
7849: PetscCall(PetscObjectBaseTypeCompare((PetscObject)Amat, MATSEQAIJ, &isseqaij));
7850: PetscCall(PetscObjectBaseTypeCompare((PetscObject)Amat, MATMPIAIJ, &ismpiaij));
7851: PetscCheck(isseqaij || ismpiaij, comm, PETSC_ERR_USER, "Require (MPI)AIJ matrix type");
7853: /* TODO GPU: these calls are potentially expensive if matrices are large and we want to use the GPU */
7854: /* A solution consists in providing a new API, MatAIJGetCollapsedAIJ, and each class can provide a fast
7855: implementation */
7856: if (bs > 1) {
7857: PetscCall(MatGetType(Amat, &jtype));
7858: PetscCall(MatCreate(comm, &Gmat));
7859: PetscCall(MatSetType(Gmat, jtype));
7860: PetscCall(MatSetSizes(Gmat, nloc, nloc, PETSC_DETERMINE, PETSC_DETERMINE));
7861: PetscCall(MatSetBlockSizes(Gmat, 1, 1));
7862: if (isseqaij || ((Mat_MPIAIJ *)Amat->data)->garray) {
7863: PetscInt *d_nnz, *o_nnz;
7864: MatScalar *aa, val, *AA;
7865: PetscInt *aj, *ai, *AJ, nc, nmax = 0;
7867: if (isseqaij) {
7868: a = Amat;
7869: b = NULL;
7870: } else {
7871: Mat_MPIAIJ *d = (Mat_MPIAIJ *)Amat->data;
7872: a = d->A;
7873: b = d->B;
7874: }
7875: PetscCall(PetscInfo(Amat, "New bs>1 Graph. nloc=%" PetscInt_FMT "\n", nloc));
7876: PetscCall(PetscMalloc2(nloc, &d_nnz, (isseqaij ? 0 : nloc), &o_nnz));
7877: for (c = a, kk = 0; c && kk < 2; c = b, kk++) {
7878: PetscInt *nnz = (c == a) ? d_nnz : o_nnz;
7879: const PetscInt *cols1, *cols2;
7881: for (PetscInt brow = 0, nc1, nc2, ok = 1; brow < nloc * bs; brow += bs) { // block rows
7882: PetscCall(MatGetRow(c, brow, &nc2, &cols2, NULL));
7883: nnz[brow / bs] = nc2 / bs;
7884: if (nc2 % bs) ok = 0;
7885: if (nnz[brow / bs] > nmax) nmax = nnz[brow / bs];
7886: for (PetscInt ii = 1; ii < bs; ii++) { // check for non-dense blocks
7887: PetscCall(MatGetRow(c, brow + ii, &nc1, &cols1, NULL));
7888: if (nc1 != nc2) ok = 0;
7889: else {
7890: for (PetscInt jj = 0; jj < nc1 && ok == 1; jj++) {
7891: if (cols1[jj] != cols2[jj]) ok = 0;
7892: if (cols1[jj] % bs != jj % bs) ok = 0;
7893: }
7894: }
7895: PetscCall(MatRestoreRow(c, brow + ii, &nc1, &cols1, NULL));
7896: }
7897: PetscCall(MatRestoreRow(c, brow, &nc2, &cols2, NULL));
7898: if (!ok) {
7899: PetscCall(PetscFree2(d_nnz, o_nnz));
7900: PetscCall(PetscInfo(Amat, "Found sparse blocks - revert to slow method\n"));
7901: goto old_bs;
7902: }
7903: }
7904: }
7905: PetscCall(MatSeqAIJSetPreallocation(Gmat, 0, d_nnz));
7906: PetscCall(MatMPIAIJSetPreallocation(Gmat, 0, d_nnz, 0, o_nnz));
7907: PetscCall(PetscFree2(d_nnz, o_nnz));
7908: PetscCall(PetscMalloc2(nmax, &AA, nmax, &AJ));
7909: // diag
7910: for (PetscInt brow = 0, n, grow; brow < nloc * bs; brow += bs) { // block rows
7911: Mat_SeqAIJ *aseq = (Mat_SeqAIJ *)a->data;
7913: ai = aseq->i;
7914: n = ai[brow + 1] - ai[brow];
7915: aj = aseq->j + ai[brow];
7916: for (PetscInt k = 0; k < n; k += bs) { // block columns
7917: AJ[k / bs] = aj[k] / bs + Istart / bs; // diag starts at (Istart,Istart)
7918: val = 0;
7919: if (index_size == 0) {
7920: for (PetscInt ii = 0; ii < bs; ii++) { // rows in block
7921: aa = aseq->a + ai[brow + ii] + k;
7922: for (PetscInt jj = 0; jj < bs; jj++) { // columns in block
7923: val += PetscAbs(PetscRealPart(aa[jj])); // a sort of norm
7924: }
7925: }
7926: } else { // use (index,index) value if provided
7927: for (PetscInt iii = 0; iii < index_size; iii++) { // rows in block
7928: PetscInt ii = index[iii];
7929: aa = aseq->a + ai[brow + ii] + k;
7930: for (PetscInt jjj = 0; jjj < index_size; jjj++) { // columns in block
7931: PetscInt jj = index[jjj];
7932: val += PetscAbs(PetscRealPart(aa[jj]));
7933: }
7934: }
7935: }
7936: PetscAssert(k / bs < nmax, comm, PETSC_ERR_USER, "k / bs (%" PetscInt_FMT ") >= nmax (%" PetscInt_FMT ")", k / bs, nmax);
7937: AA[k / bs] = val;
7938: }
7939: grow = Istart / bs + brow / bs;
7940: PetscCall(MatSetValues(Gmat, 1, &grow, n / bs, AJ, AA, ADD_VALUES));
7941: }
7942: // off-diag
7943: if (ismpiaij) {
7944: Mat_MPIAIJ *aij = (Mat_MPIAIJ *)Amat->data;
7945: const PetscScalar *vals;
7946: const PetscInt *cols, *garray = aij->garray;
7948: PetscCheck(garray, PETSC_COMM_SELF, PETSC_ERR_USER, "No garray ?");
7949: for (PetscInt brow = 0, grow; brow < nloc * bs; brow += bs) { // block rows
7950: PetscCall(MatGetRow(b, brow, &ncols, &cols, NULL));
7951: for (PetscInt k = 0, cidx = 0; k < ncols; k += bs, cidx++) {
7952: PetscAssert(k / bs < nmax, comm, PETSC_ERR_USER, "k / bs >= nmax");
7953: AA[k / bs] = 0;
7954: AJ[cidx] = garray[cols[k]] / bs;
7955: }
7956: nc = ncols / bs;
7957: PetscCall(MatRestoreRow(b, brow, &ncols, &cols, NULL));
7958: if (index_size == 0) {
7959: for (PetscInt ii = 0; ii < bs; ii++) { // rows in block
7960: PetscCall(MatGetRow(b, brow + ii, &ncols, &cols, &vals));
7961: for (PetscInt k = 0; k < ncols; k += bs) {
7962: for (PetscInt jj = 0; jj < bs; jj++) { // cols in block
7963: PetscAssert(k / bs < nmax, comm, PETSC_ERR_USER, "k / bs (%" PetscInt_FMT ") >= nmax (%" PetscInt_FMT ")", k / bs, nmax);
7964: AA[k / bs] += PetscAbs(PetscRealPart(vals[k + jj]));
7965: }
7966: }
7967: PetscCall(MatRestoreRow(b, brow + ii, &ncols, &cols, &vals));
7968: }
7969: } else { // use (index,index) value if provided
7970: for (PetscInt iii = 0; iii < index_size; iii++) { // rows in block
7971: PetscInt ii = index[iii];
7972: PetscCall(MatGetRow(b, brow + ii, &ncols, &cols, &vals));
7973: for (PetscInt k = 0; k < ncols; k += bs) {
7974: for (PetscInt jjj = 0; jjj < index_size; jjj++) { // cols in block
7975: PetscInt jj = index[jjj];
7976: AA[k / bs] += PetscAbs(PetscRealPart(vals[k + jj]));
7977: }
7978: }
7979: PetscCall(MatRestoreRow(b, brow + ii, &ncols, &cols, &vals));
7980: }
7981: }
7982: grow = Istart / bs + brow / bs;
7983: PetscCall(MatSetValues(Gmat, 1, &grow, nc, AJ, AA, ADD_VALUES));
7984: }
7985: }
7986: PetscCall(MatAssemblyBegin(Gmat, MAT_FINAL_ASSEMBLY));
7987: PetscCall(MatAssemblyEnd(Gmat, MAT_FINAL_ASSEMBLY));
7988: PetscCall(PetscFree2(AA, AJ));
7989: } else {
7990: const PetscScalar *vals;
7991: const PetscInt *idx;
7992: PetscInt *d_nnz, *o_nnz, *w0, *w1, *w2;
7993: old_bs:
7994: /*
7995: Determine the preallocation needed for the scalar matrix derived from the vector matrix.
7996: */
7997: PetscCall(PetscInfo(Amat, "OLD bs>1 CreateGraph\n"));
7998: PetscCall(PetscMalloc2(nloc, &d_nnz, (isseqaij ? 0 : nloc), &o_nnz));
7999: if (isseqaij) {
8000: PetscInt max_d_nnz;
8002: /*
8003: Determine exact preallocation count for (sequential) scalar matrix
8004: */
8005: PetscCall(MatSeqAIJGetMaxRowNonzeros(Amat, &max_d_nnz));
8006: max_d_nnz = PetscMin(nloc, bs * max_d_nnz);
8007: PetscCall(PetscMalloc3(max_d_nnz, &w0, max_d_nnz, &w1, max_d_nnz, &w2));
8008: for (Ii = 0, jj = 0; Ii < Iend; Ii += bs, jj++) PetscCall(MatCollapseRows(Amat, Ii, bs, w0, w1, w2, &d_nnz[jj], NULL));
8009: PetscCall(PetscFree3(w0, w1, w2));
8010: } else if (ismpiaij) {
8011: Mat Daij, Oaij;
8012: const PetscInt *garray;
8013: PetscInt max_d_nnz;
8015: PetscCall(MatMPIAIJGetSeqAIJ(Amat, &Daij, &Oaij, &garray));
8016: /*
8017: Determine exact preallocation count for diagonal block portion of scalar matrix
8018: */
8019: PetscCall(MatSeqAIJGetMaxRowNonzeros(Daij, &max_d_nnz));
8020: max_d_nnz = PetscMin(nloc, bs * max_d_nnz);
8021: PetscCall(PetscMalloc3(max_d_nnz, &w0, max_d_nnz, &w1, max_d_nnz, &w2));
8022: for (Ii = 0, jj = 0; Ii < Iend - Istart; Ii += bs, jj++) PetscCall(MatCollapseRows(Daij, Ii, bs, w0, w1, w2, &d_nnz[jj], NULL));
8023: PetscCall(PetscFree3(w0, w1, w2));
8024: /*
8025: Over estimate (usually grossly over), preallocation count for off-diagonal portion of scalar matrix
8026: */
8027: for (Ii = 0, jj = 0; Ii < Iend - Istart; Ii += bs, jj++) {
8028: o_nnz[jj] = 0;
8029: for (kk = 0; kk < bs; kk++) { /* rows that get collapsed to a single row */
8030: PetscCall(MatGetRow(Oaij, Ii + kk, &ncols, NULL, NULL));
8031: o_nnz[jj] += ncols;
8032: PetscCall(MatRestoreRow(Oaij, Ii + kk, &ncols, NULL, NULL));
8033: }
8034: if (o_nnz[jj] > (NN / bs - nloc)) o_nnz[jj] = NN / bs - nloc;
8035: }
8036: } else SETERRQ(comm, PETSC_ERR_USER, "Require AIJ matrix type");
8037: /* get scalar copy (norms) of matrix */
8038: PetscCall(MatSeqAIJSetPreallocation(Gmat, 0, d_nnz));
8039: PetscCall(MatMPIAIJSetPreallocation(Gmat, 0, d_nnz, 0, o_nnz));
8040: PetscCall(PetscFree2(d_nnz, o_nnz));
8041: for (Ii = Istart; Ii < Iend; Ii++) {
8042: PetscInt dest_row = Ii / bs;
8044: PetscCall(MatGetRow(Amat, Ii, &ncols, &idx, &vals));
8045: for (jj = 0; jj < ncols; jj++) {
8046: PetscInt dest_col = idx[jj] / bs;
8047: PetscScalar sv = PetscAbs(PetscRealPart(vals[jj]));
8049: PetscCall(MatSetValues(Gmat, 1, &dest_row, 1, &dest_col, &sv, ADD_VALUES));
8050: }
8051: PetscCall(MatRestoreRow(Amat, Ii, &ncols, &idx, &vals));
8052: }
8053: PetscCall(MatAssemblyBegin(Gmat, MAT_FINAL_ASSEMBLY));
8054: PetscCall(MatAssemblyEnd(Gmat, MAT_FINAL_ASSEMBLY));
8055: }
8056: } else {
8057: if (symmetrize || filter >= 0 || scale) PetscCall(MatDuplicate(Amat, MAT_COPY_VALUES, &Gmat));
8058: else {
8059: Gmat = Amat;
8060: PetscCall(PetscObjectReference((PetscObject)Gmat));
8061: }
8062: if (isseqaij) {
8063: a = Gmat;
8064: b = NULL;
8065: } else {
8066: Mat_MPIAIJ *d = (Mat_MPIAIJ *)Gmat->data;
8067: a = d->A;
8068: b = d->B;
8069: }
8070: if (filter >= 0 || scale) {
8071: /* take absolute value of each entry */
8072: for (c = a, kk = 0; c && kk < 2; c = b, kk++) {
8073: MatInfo info;
8074: PetscScalar *avals;
8076: PetscCall(MatGetInfo(c, MAT_LOCAL, &info));
8077: PetscCall(MatSeqAIJGetArray(c, &avals));
8078: for (int jj = 0; jj < info.nz_used; jj++) avals[jj] = PetscAbsScalar(avals[jj]);
8079: PetscCall(MatSeqAIJRestoreArray(c, &avals));
8080: }
8081: }
8082: }
8083: if (symmetrize) {
8084: PetscBool isset, issym;
8086: PetscCall(MatIsSymmetricKnown(Amat, &isset, &issym));
8087: if (!isset || !issym) {
8088: Mat matTrans;
8090: PetscCall(MatTranspose(Gmat, MAT_INITIAL_MATRIX, &matTrans));
8091: PetscCall(MatAXPY(Gmat, 1.0, matTrans, Gmat->structurally_symmetric == PETSC_BOOL3_TRUE ? SAME_NONZERO_PATTERN : DIFFERENT_NONZERO_PATTERN));
8092: PetscCall(MatDestroy(&matTrans));
8093: }
8094: PetscCall(MatSetOption(Gmat, MAT_SYMMETRIC, PETSC_TRUE));
8095: } else if (Amat != Gmat) PetscCall(MatPropagateSymmetryOptions(Amat, Gmat));
8096: if (scale) {
8097: /* scale c for all diagonal values = 1 or -1 */
8098: Vec diag;
8100: PetscCall(MatCreateVecs(Gmat, &diag, NULL));
8101: PetscCall(MatGetDiagonal(Gmat, diag));
8102: PetscCall(VecReciprocal(diag));
8103: PetscCall(VecSqrtAbs(diag));
8104: PetscCall(MatDiagonalScale(Gmat, diag, diag));
8105: PetscCall(VecDestroy(&diag));
8106: }
8107: PetscCall(MatViewFromOptions(Gmat, NULL, "-mat_graph_view"));
8108: if (filter >= 0) {
8109: PetscCall(MatFilter(Gmat, filter, PETSC_TRUE, PETSC_TRUE));
8110: PetscCall(MatViewFromOptions(Gmat, NULL, "-mat_filter_graph_view"));
8111: }
8112: *a_Gmat = Gmat;
8113: PetscFunctionReturn(PETSC_SUCCESS);
8114: }
8116: PETSC_INTERN PetscErrorCode MatGetCurrentMemType_MPIAIJ(Mat A, PetscMemType *memtype)
8117: {
8118: Mat_MPIAIJ *mpiaij = (Mat_MPIAIJ *)A->data;
8119: PetscMemType mD = PETSC_MEMTYPE_HOST, mO = PETSC_MEMTYPE_HOST;
8121: PetscFunctionBegin;
8122: if (mpiaij->A) PetscCall(MatGetCurrentMemType(mpiaij->A, &mD));
8123: if (mpiaij->B) PetscCall(MatGetCurrentMemType(mpiaij->B, &mO));
8124: *memtype = (mD == mO) ? mD : PETSC_MEMTYPE_HOST;
8125: PetscFunctionReturn(PETSC_SUCCESS);
8126: }
8128: /*
8129: Special version for direct calls from Fortran
8130: */
8132: /* Change these macros so can be used in void function */
8133: /* Identical to PetscCallVoid, except it assigns to *_ierr */
8134: #undef PetscCall
8135: #define PetscCall(...) \
8136: do { \
8137: PetscErrorCode ierr_msv_mpiaij = __VA_ARGS__; \
8138: if (PetscUnlikely(ierr_msv_mpiaij)) { \
8139: *_ierr = PetscError(PETSC_COMM_SELF, __LINE__, PETSC_FUNCTION_NAME, __FILE__, ierr_msv_mpiaij, PETSC_ERROR_REPEAT, " "); \
8140: return; \
8141: } \
8142: } while (0)
8144: #undef SETERRQ
8145: #define SETERRQ(comm, ierr, ...) \
8146: do { \
8147: *_ierr = PetscError(comm, __LINE__, PETSC_FUNCTION_NAME, __FILE__, ierr, PETSC_ERROR_INITIAL, __VA_ARGS__); \
8148: return; \
8149: } while (0)
8151: #if PetscDefined(HAVE_FORTRAN_CAPS)
8152: #define matsetvaluesmpiaij_ MATSETVALUESMPIAIJ
8153: #elif !PetscDefined(HAVE_FORTRAN_UNDERSCORE)
8154: #define matsetvaluesmpiaij_ matsetvaluesmpiaij
8155: #else
8156: #endif
8157: PETSC_EXTERN void matsetvaluesmpiaij_(Mat *mmat, PetscInt *mm, const PetscInt im[], PetscInt *mn, const PetscInt in[], const PetscScalar v[], InsertMode *maddv, PetscErrorCode *_ierr)
8158: {
8159: Mat mat = *mmat;
8160: PetscInt m = *mm, n = *mn;
8161: InsertMode addv = *maddv;
8162: Mat_MPIAIJ *aij = (Mat_MPIAIJ *)mat->data;
8163: PetscScalar value;
8165: MatCheckPreallocated(mat, 1);
8166: if (mat->insertmode == NOT_SET_VALUES) mat->insertmode = addv;
8167: else PetscCheck(mat->insertmode == addv, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Cannot mix add values and insert values");
8168: {
8169: PetscInt i, j, rstart = mat->rmap->rstart, rend = mat->rmap->rend;
8170: PetscInt cstart = mat->cmap->rstart, cend = mat->cmap->rend, row, col;
8171: PetscBool roworiented = aij->roworiented;
8173: /* Some Variables required in the macro */
8174: Mat A = aij->A;
8175: Mat_SeqAIJ *a = (Mat_SeqAIJ *)A->data;
8176: PetscInt *aimax = a->imax, *ai = a->i, *ailen = a->ilen, *aj = a->j;
8177: MatScalar *aa;
8178: PetscBool ignorezeroentries = (a->ignorezeroentries && addv == ADD_VALUES) ? PETSC_TRUE : PETSC_FALSE;
8179: Mat B = aij->B;
8180: Mat_SeqAIJ *b = (Mat_SeqAIJ *)B->data;
8181: PetscInt *bimax = b->imax, *bi = b->i, *bilen = b->ilen, *bj = b->j, bm = aij->B->rmap->n, am = aij->A->rmap->n;
8182: MatScalar *ba;
8183: /* This variable below is only for the PETSC_HAVE_VIENNACL or PETSC_HAVE_CUDA cases, but we define it in all cases because we
8184: * cannot use "#if defined" inside a macro. */
8185: PETSC_UNUSED PetscBool inserted = PETSC_FALSE;
8187: PetscInt *rp1, *rp2, ii, nrow1, nrow2, _i, rmax1, rmax2, N, low1, high1, low2, high2, t, lastcol1, lastcol2;
8188: PetscInt nonew = a->nonew;
8189: MatScalar *ap1, *ap2;
8191: PetscFunctionBegin;
8192: PetscCall(MatSeqAIJGetArray(A, &aa));
8193: PetscCall(MatSeqAIJGetArray(B, &ba));
8194: for (i = 0; i < m; i++) {
8195: if (im[i] < 0) continue;
8196: 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);
8197: if (im[i] >= rstart && im[i] < rend) {
8198: row = im[i] - rstart;
8199: lastcol1 = -1;
8200: rp1 = aj + ai[row];
8201: ap1 = aa + ai[row];
8202: rmax1 = aimax[row];
8203: nrow1 = ailen[row];
8204: low1 = 0;
8205: high1 = nrow1;
8206: lastcol2 = -1;
8207: rp2 = bj + bi[row];
8208: ap2 = ba + bi[row];
8209: rmax2 = bimax[row];
8210: nrow2 = bilen[row];
8211: low2 = 0;
8212: high2 = nrow2;
8214: for (j = 0; j < n; j++) {
8215: if (roworiented) value = v[i * n + j];
8216: else value = v[i + j * m];
8217: if (ignorezeroentries && value == 0.0 && addv == ADD_VALUES && im[i] != in[j]) continue;
8218: if (in[j] >= cstart && in[j] < cend) {
8219: col = in[j] - cstart;
8220: MatSetValues_SeqAIJ_A_Private(row, col, value, addv, im[i], in[j]);
8221: } else if (in[j] < 0) continue;
8222: else if (PetscUnlikelyDebug(in[j] >= mat->cmap->N)) {
8223: SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Column too large: col %" PetscInt_FMT " max %" PetscInt_FMT, in[j], mat->cmap->N - 1);
8224: } else {
8225: if (mat->was_assembled) {
8226: if (!aij->colmap) PetscCall(MatCreateColmap_MPIAIJ_Private(mat));
8227: #if PetscDefined(USE_CTABLE)
8228: PetscCall(PetscHMapIGetWithDefault(aij->colmap, in[j] + 1, 0, &col));
8229: col--;
8230: #else
8231: col = aij->colmap[in[j]] - 1;
8232: #endif
8233: if (col < 0 && !((Mat_SeqAIJ *)aij->A->data)->nonew) {
8234: PetscCall(MatDisAssemble_MPIAIJ(mat, PETSC_FALSE));
8235: col = in[j];
8236: /* Reinitialize the variables required by MatSetValues_SeqAIJ_B_Private() */
8237: B = aij->B;
8238: b = (Mat_SeqAIJ *)B->data;
8239: bimax = b->imax;
8240: bi = b->i;
8241: bilen = b->ilen;
8242: bj = b->j;
8243: rp2 = bj + bi[row];
8244: ap2 = ba + bi[row];
8245: rmax2 = bimax[row];
8246: nrow2 = bilen[row];
8247: low2 = 0;
8248: high2 = nrow2;
8249: bm = aij->B->rmap->n;
8250: ba = b->a;
8251: inserted = PETSC_FALSE;
8252: }
8253: } else col = in[j];
8254: MatSetValues_SeqAIJ_B_Private(row, col, value, addv, im[i], in[j]);
8255: }
8256: }
8257: } else if (!aij->donotstash) {
8258: if (roworiented) {
8259: PetscCall(MatStashValuesRow_Private(&mat->stash, im[i], n, in, v + i * n, (PetscBool)(ignorezeroentries && addv == ADD_VALUES)));
8260: } else {
8261: PetscCall(MatStashValuesCol_Private(&mat->stash, im[i], n, in, v + i, m, (PetscBool)(ignorezeroentries && addv == ADD_VALUES)));
8262: }
8263: }
8264: }
8265: PetscCall(MatSeqAIJRestoreArray(A, &aa));
8266: PetscCall(MatSeqAIJRestoreArray(B, &ba));
8267: }
8268: PetscFunctionReturnVoid();
8269: }
8271: /* Undefining these here since they were redefined from their original definition above! No
8272: * other PETSc functions should be defined past this point, as it is impossible to recover the
8273: * original definitions */
8274: #undef PetscCall
8275: #undef SETERRQ