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: aij->rowvalues = NULL;
822: PetscCall(VecDestroy(&aij->diag));
824: /* if no new nonzero locations are allowed in matrix then only set the matrix state the first time through */
825: if ((!mat->was_assembled && mode == MAT_FINAL_ASSEMBLY) || !((Mat_SeqAIJ *)aij->A->data)->nonew) {
826: mat->nonzerostate = aij->A->nonzerostate + aij->B->nonzerostate;
827: PetscCallMPI(MPIU_Allreduce(MPI_IN_PLACE, &mat->nonzerostate, 1, MPIU_INT64, MPI_SUM, PetscObjectComm((PetscObject)mat)));
828: }
829: #if PetscDefined(HAVE_DEVICE)
830: mat->offloadmask = PETSC_OFFLOAD_BOTH;
831: #endif
832: PetscFunctionReturn(PETSC_SUCCESS);
833: }
835: static PetscErrorCode MatZeroEntries_MPIAIJ(Mat A)
836: {
837: Mat_MPIAIJ *l = (Mat_MPIAIJ *)A->data;
839: PetscFunctionBegin;
840: PetscCall(MatZeroEntries(l->A));
841: PetscCall(MatZeroEntries(l->B));
842: PetscFunctionReturn(PETSC_SUCCESS);
843: }
845: static PetscErrorCode MatZeroRows_MPIAIJ(Mat A, PetscInt N, const PetscInt rows[], PetscScalar diag, Vec x, Vec b)
846: {
847: Mat_MPIAIJ *mat = (Mat_MPIAIJ *)A->data;
848: PetscInt *lrows;
849: PetscInt r, len;
850: PetscBool cong;
852: PetscFunctionBegin;
853: /* get locally owned rows */
854: PetscCall(MatZeroRowsMapLocal_Private(A, N, rows, &len, &lrows));
855: PetscCall(MatHasCongruentLayouts(A, &cong));
856: /* fix right-hand side if needed */
857: if (x && b) {
858: const PetscScalar *xx;
859: PetscScalar *bb;
861: PetscCheck(cong, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "Need matching row/col layout");
862: PetscCall(VecGetArrayRead(x, &xx));
863: PetscCall(VecGetArray(b, &bb));
864: for (r = 0; r < len; ++r) bb[lrows[r]] = diag * xx[lrows[r]];
865: PetscCall(VecRestoreArrayRead(x, &xx));
866: PetscCall(VecRestoreArray(b, &bb));
867: }
869: if (diag != 0.0 && cong) {
870: PetscCall(MatZeroRows(mat->A, len, lrows, diag, NULL, NULL));
871: PetscCall(MatZeroRows(mat->B, len, lrows, 0.0, NULL, NULL));
872: } else if (diag != 0.0) { /* non-square or non congruent layouts -> if keepnonzeropattern is false, we allow for new insertion */
873: Mat_SeqAIJ *aijA = (Mat_SeqAIJ *)mat->A->data;
874: Mat_SeqAIJ *aijB = (Mat_SeqAIJ *)mat->B->data;
875: PetscInt nnwA, nnwB;
876: PetscBool nnzA, nnzB;
878: nnwA = aijA->nonew;
879: nnwB = aijB->nonew;
880: nnzA = aijA->keepnonzeropattern;
881: nnzB = aijB->keepnonzeropattern;
882: if (!nnzA) {
883: PetscCall(PetscInfo(mat->A, "Requested to not keep the pattern and add a nonzero diagonal; may encounter reallocations on diagonal block.\n"));
884: aijA->nonew = 0;
885: }
886: if (!nnzB) {
887: PetscCall(PetscInfo(mat->B, "Requested to not keep the pattern and add a nonzero diagonal; may encounter reallocations on off-diagonal block.\n"));
888: aijB->nonew = 0;
889: }
890: /* Must zero here before the next loop */
891: PetscCall(MatZeroRows(mat->A, len, lrows, 0.0, NULL, NULL));
892: PetscCall(MatZeroRows(mat->B, len, lrows, 0.0, NULL, NULL));
893: for (r = 0; r < len; ++r) {
894: const PetscInt row = lrows[r] + A->rmap->rstart;
895: if (row >= A->cmap->N) continue;
896: PetscCall(MatSetValues(A, 1, &row, 1, &row, &diag, INSERT_VALUES));
897: }
898: aijA->nonew = nnwA;
899: aijB->nonew = nnwB;
900: } else {
901: PetscCall(MatZeroRows(mat->A, len, lrows, 0.0, NULL, NULL));
902: PetscCall(MatZeroRows(mat->B, len, lrows, 0.0, NULL, NULL));
903: }
904: PetscCall(PetscFree(lrows));
905: PetscCall(MatAssemblyBegin(A, MAT_FINAL_ASSEMBLY));
906: PetscCall(MatAssemblyEnd(A, MAT_FINAL_ASSEMBLY));
908: /* only change matrix nonzero state if pattern was allowed to be changed */
909: if (!((Mat_SeqAIJ *)mat->A->data)->keepnonzeropattern || !((Mat_SeqAIJ *)mat->A->data)->nonew) {
910: A->nonzerostate = mat->A->nonzerostate + mat->B->nonzerostate;
911: PetscCallMPI(MPIU_Allreduce(MPI_IN_PLACE, &A->nonzerostate, 1, MPIU_INT64, MPI_SUM, PetscObjectComm((PetscObject)A)));
912: }
913: PetscFunctionReturn(PETSC_SUCCESS);
914: }
916: static PetscErrorCode MatZeroRowsColumns_MPIAIJ(Mat A, PetscInt N, const PetscInt rows[], PetscScalar diag, Vec x, Vec b)
917: {
918: Mat_MPIAIJ *l = (Mat_MPIAIJ *)A->data;
919: PetscInt n = A->rmap->n;
920: PetscInt i, j, r, m, len = 0;
921: PetscInt *lrows, *owners = A->rmap->range;
922: PetscMPIInt p = 0;
923: PetscSFNode *rrows;
924: PetscSF sf;
925: const PetscScalar *xx;
926: PetscScalar *bb, *mask, *aij_a;
927: Vec xmask, lmask;
928: Mat_SeqAIJ *aij = (Mat_SeqAIJ *)l->B->data;
929: const PetscInt *aj, *ii, *ridx;
930: PetscScalar *aa;
932: PetscFunctionBegin;
933: /* Create SF where leaves are input rows and roots are owned rows */
934: PetscCall(PetscMalloc1(n, &lrows));
935: for (r = 0; r < n; ++r) lrows[r] = -1;
936: PetscCall(PetscMalloc1(N, &rrows));
937: for (r = 0; r < N; ++r) {
938: const PetscInt idx = rows[r];
939: 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);
940: if (idx < owners[p] || owners[p + 1] <= idx) { /* short-circuit the search if the last p owns this row too */
941: PetscCall(PetscLayoutFindOwner(A->rmap, idx, &p));
942: }
943: rrows[r].rank = p;
944: rrows[r].index = rows[r] - owners[p];
945: }
946: PetscCall(PetscSFCreate(PetscObjectComm((PetscObject)A), &sf));
947: PetscCall(PetscSFSetGraph(sf, n, N, NULL, PETSC_OWN_POINTER, rrows, PETSC_OWN_POINTER));
948: /* Collect flags for rows to be zeroed */
949: PetscCall(PetscSFReduceBegin(sf, MPIU_INT, (PetscInt *)rows, lrows, MPI_LOR));
950: PetscCall(PetscSFReduceEnd(sf, MPIU_INT, (PetscInt *)rows, lrows, MPI_LOR));
951: PetscCall(PetscSFDestroy(&sf));
952: /* Compress and put in row numbers */
953: for (r = 0; r < n; ++r)
954: if (lrows[r] >= 0) lrows[len++] = r;
955: /* zero diagonal part of matrix */
956: PetscCall(MatZeroRowsColumns(l->A, len, lrows, diag, x, b));
957: /* handle off-diagonal part of matrix */
958: PetscCall(MatCreateVecs(A, &xmask, NULL));
959: PetscCall(VecDuplicate(l->lvec, &lmask));
960: PetscCall(VecGetArray(xmask, &bb));
961: for (i = 0; i < len; i++) bb[lrows[i]] = 1;
962: PetscCall(VecRestoreArray(xmask, &bb));
963: PetscCall(VecScatterBegin(l->Mvctx, xmask, lmask, ADD_VALUES, SCATTER_FORWARD));
964: PetscCall(VecScatterEnd(l->Mvctx, xmask, lmask, ADD_VALUES, SCATTER_FORWARD));
965: PetscCall(VecDestroy(&xmask));
966: if (x && b) { /* this code is buggy when the row and column layout don't match */
967: PetscBool cong;
969: PetscCall(MatHasCongruentLayouts(A, &cong));
970: PetscCheck(cong, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "Need matching row/col layout");
971: PetscCall(VecScatterBegin(l->Mvctx, x, l->lvec, INSERT_VALUES, SCATTER_FORWARD));
972: PetscCall(VecScatterEnd(l->Mvctx, x, l->lvec, INSERT_VALUES, SCATTER_FORWARD));
973: PetscCall(VecGetArrayRead(l->lvec, &xx));
974: PetscCall(VecGetArray(b, &bb));
975: }
976: PetscCall(VecGetArray(lmask, &mask));
977: /* remove zeroed rows of off-diagonal matrix */
978: PetscCall(MatSeqAIJGetArray(l->B, &aij_a));
979: ii = aij->i;
980: for (i = 0; i < len; i++) PetscCall(PetscArrayzero(PetscSafePointerPlusOffset(aij_a, ii[lrows[i]]), ii[lrows[i] + 1] - ii[lrows[i]]));
981: /* loop over all elements of off process part of matrix zeroing removed columns*/
982: if (aij->compressedrow.use) {
983: m = aij->compressedrow.nrows;
984: ii = aij->compressedrow.i;
985: ridx = aij->compressedrow.rindex;
986: for (i = 0; i < m; i++) {
987: n = ii[i + 1] - ii[i];
988: aj = aij->j + ii[i];
989: aa = aij_a + ii[i];
991: for (j = 0; j < n; j++) {
992: if (PetscAbsScalar(mask[*aj])) {
993: if (b) bb[*ridx] -= *aa * xx[*aj];
994: *aa = 0.0;
995: }
996: aa++;
997: aj++;
998: }
999: ridx++;
1000: }
1001: } else { /* do not use compressed row format */
1002: m = l->B->rmap->n;
1003: for (i = 0; i < m; i++) {
1004: n = ii[i + 1] - ii[i];
1005: aj = aij->j + ii[i];
1006: aa = aij_a + ii[i];
1007: for (j = 0; j < n; j++) {
1008: if (PetscAbsScalar(mask[*aj])) {
1009: if (b) bb[i] -= *aa * xx[*aj];
1010: *aa = 0.0;
1011: }
1012: aa++;
1013: aj++;
1014: }
1015: }
1016: }
1017: if (x && b) {
1018: PetscCall(VecRestoreArray(b, &bb));
1019: PetscCall(VecRestoreArrayRead(l->lvec, &xx));
1020: }
1021: PetscCall(MatSeqAIJRestoreArray(l->B, &aij_a));
1022: PetscCall(VecRestoreArray(lmask, &mask));
1023: PetscCall(VecDestroy(&lmask));
1024: PetscCall(PetscFree(lrows));
1026: /* only change matrix nonzero state if pattern was allowed to be changed */
1027: if (!((Mat_SeqAIJ *)l->A->data)->nonew) {
1028: A->nonzerostate = l->A->nonzerostate + l->B->nonzerostate;
1029: PetscCallMPI(MPIU_Allreduce(MPI_IN_PLACE, &A->nonzerostate, 1, MPIU_INT64, MPI_SUM, PetscObjectComm((PetscObject)A)));
1030: }
1031: PetscFunctionReturn(PETSC_SUCCESS);
1032: }
1034: static PetscErrorCode MatMult_MPIAIJ(Mat A, Vec xx, Vec yy)
1035: {
1036: Mat_MPIAIJ *a = (Mat_MPIAIJ *)A->data;
1037: PetscInt nt;
1038: VecScatter Mvctx = a->Mvctx;
1040: PetscFunctionBegin;
1041: PetscCall(VecGetLocalSize(xx, &nt));
1042: 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);
1043: PetscCall(VecScatterBegin(Mvctx, xx, a->lvec, INSERT_VALUES, SCATTER_FORWARD));
1044: PetscUseTypeMethod(a->A, mult, xx, yy);
1045: PetscCall(VecScatterEnd(Mvctx, xx, a->lvec, INSERT_VALUES, SCATTER_FORWARD));
1046: PetscUseTypeMethod(a->B, multadd, a->lvec, yy, yy);
1047: PetscFunctionReturn(PETSC_SUCCESS);
1048: }
1050: static PetscErrorCode MatMultDiagonalBlock_MPIAIJ(Mat A, Vec bb, Vec xx)
1051: {
1052: Mat_MPIAIJ *a = (Mat_MPIAIJ *)A->data;
1054: PetscFunctionBegin;
1055: PetscCall(MatMultDiagonalBlock(a->A, bb, xx));
1056: PetscFunctionReturn(PETSC_SUCCESS);
1057: }
1059: static PetscErrorCode MatMultAdd_MPIAIJ(Mat A, Vec xx, Vec yy, Vec zz)
1060: {
1061: Mat_MPIAIJ *a = (Mat_MPIAIJ *)A->data;
1062: VecScatter Mvctx = a->Mvctx;
1064: PetscFunctionBegin;
1065: PetscCall(VecScatterBegin(Mvctx, xx, a->lvec, INSERT_VALUES, SCATTER_FORWARD));
1066: PetscUseTypeMethod(a->A, multadd, xx, yy, zz);
1067: PetscCall(VecScatterEnd(Mvctx, xx, a->lvec, INSERT_VALUES, SCATTER_FORWARD));
1068: PetscUseTypeMethod(a->B, multadd, a->lvec, zz, zz);
1069: PetscFunctionReturn(PETSC_SUCCESS);
1070: }
1072: static PetscErrorCode MatMultTranspose_MPIAIJ(Mat A, Vec xx, Vec yy)
1073: {
1074: Mat_MPIAIJ *a = (Mat_MPIAIJ *)A->data;
1076: PetscFunctionBegin;
1077: /* do nondiagonal part */
1078: PetscUseTypeMethod(a->B, multtranspose, xx, a->lvec);
1079: /* do local part */
1080: PetscUseTypeMethod(a->A, multtranspose, xx, yy);
1081: /* add partial results together */
1082: PetscCall(VecScatterBegin(a->Mvctx, a->lvec, yy, ADD_VALUES, SCATTER_REVERSE));
1083: PetscCall(VecScatterEnd(a->Mvctx, a->lvec, yy, ADD_VALUES, SCATTER_REVERSE));
1084: PetscFunctionReturn(PETSC_SUCCESS);
1085: }
1087: static PetscErrorCode MatIsTranspose_MPIAIJ(Mat Amat, Mat Bmat, PetscReal tol, PetscBool *f)
1088: {
1089: MPI_Comm comm;
1090: Mat_MPIAIJ *Aij = (Mat_MPIAIJ *)Amat->data, *Bij = (Mat_MPIAIJ *)Bmat->data;
1091: Mat Adia = Aij->A, Bdia = Bij->A, Aoff, Boff, *Aoffs, *Boffs;
1092: IS Me, Notme;
1093: PetscInt M, N, first, last, *notme, i;
1094: PetscMPIInt size;
1096: PetscFunctionBegin;
1097: /* Easy test: symmetric diagonal block */
1098: PetscCall(MatIsTranspose(Adia, Bdia, tol, f));
1099: PetscCallMPI(MPIU_Allreduce(MPI_IN_PLACE, f, 1, MPI_C_BOOL, MPI_LAND, PetscObjectComm((PetscObject)Amat)));
1100: if (!*f) PetscFunctionReturn(PETSC_SUCCESS);
1101: PetscCall(PetscObjectGetComm((PetscObject)Amat, &comm));
1102: PetscCallMPI(MPI_Comm_size(comm, &size));
1103: if (size == 1) PetscFunctionReturn(PETSC_SUCCESS);
1105: /* Hard test: off-diagonal block. This takes a MatCreateSubMatrix. */
1106: PetscCall(MatGetSize(Amat, &M, &N));
1107: PetscCall(MatGetOwnershipRange(Amat, &first, &last));
1108: PetscCall(PetscMalloc1(N - last + first, ¬me));
1109: for (i = 0; i < first; i++) notme[i] = i;
1110: for (i = last; i < M; i++) notme[i - last + first] = i;
1111: PetscCall(ISCreateGeneral(MPI_COMM_SELF, N - last + first, notme, PETSC_COPY_VALUES, &Notme));
1112: PetscCall(ISCreateStride(MPI_COMM_SELF, last - first, first, 1, &Me));
1113: PetscCall(MatCreateSubMatrices(Amat, 1, &Me, &Notme, MAT_INITIAL_MATRIX, &Aoffs));
1114: Aoff = Aoffs[0];
1115: PetscCall(MatCreateSubMatrices(Bmat, 1, &Notme, &Me, MAT_INITIAL_MATRIX, &Boffs));
1116: Boff = Boffs[0];
1117: PetscCall(MatIsTranspose(Aoff, Boff, tol, f));
1118: PetscCall(MatDestroyMatrices(1, &Aoffs));
1119: PetscCall(MatDestroyMatrices(1, &Boffs));
1120: PetscCall(ISDestroy(&Me));
1121: PetscCall(ISDestroy(&Notme));
1122: PetscCall(PetscFree(notme));
1123: PetscFunctionReturn(PETSC_SUCCESS);
1124: }
1126: static PetscErrorCode MatMultTransposeAdd_MPIAIJ(Mat A, Vec xx, Vec yy, Vec zz)
1127: {
1128: Mat_MPIAIJ *a = (Mat_MPIAIJ *)A->data;
1130: PetscFunctionBegin;
1131: /* do nondiagonal part */
1132: PetscUseTypeMethod(a->B, multtranspose, xx, a->lvec);
1133: /* do local part */
1134: PetscUseTypeMethod(a->A, multtransposeadd, xx, yy, zz);
1135: /* add partial results together */
1136: PetscCall(VecScatterBegin(a->Mvctx, a->lvec, zz, ADD_VALUES, SCATTER_REVERSE));
1137: PetscCall(VecScatterEnd(a->Mvctx, a->lvec, zz, ADD_VALUES, SCATTER_REVERSE));
1138: PetscFunctionReturn(PETSC_SUCCESS);
1139: }
1141: /*
1142: This only works correctly for square matrices where the subblock A->A is the
1143: diagonal block
1144: */
1145: static PetscErrorCode MatGetDiagonal_MPIAIJ(Mat A, Vec v)
1146: {
1147: Mat_MPIAIJ *a = (Mat_MPIAIJ *)A->data;
1149: PetscFunctionBegin;
1150: PetscCheck(A->rmap->N == A->cmap->N, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "Supports only square matrix where A->A is diag block");
1151: 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");
1152: PetscCall(MatGetDiagonal(a->A, v));
1153: PetscFunctionReturn(PETSC_SUCCESS);
1154: }
1156: static PetscErrorCode MatScale_MPIAIJ(Mat A, PetscScalar aa)
1157: {
1158: Mat_MPIAIJ *a = (Mat_MPIAIJ *)A->data;
1160: PetscFunctionBegin;
1161: PetscCall(MatScale(a->A, aa));
1162: PetscCall(MatScale(a->B, aa));
1163: PetscFunctionReturn(PETSC_SUCCESS);
1164: }
1166: static PetscErrorCode MatView_MPIAIJ_Binary(Mat mat, PetscViewer viewer)
1167: {
1168: Mat_MPIAIJ *aij = (Mat_MPIAIJ *)mat->data;
1169: Mat_SeqAIJ *A = (Mat_SeqAIJ *)aij->A->data;
1170: Mat_SeqAIJ *B = (Mat_SeqAIJ *)aij->B->data;
1171: const PetscInt *garray = aij->garray;
1172: const PetscScalar *aa, *ba;
1173: PetscInt header[4], M, N, m, rs, cs, cnt, i, ja, jb;
1174: PetscInt64 nz, hnz;
1175: PetscInt *rowlens;
1176: PetscInt *colidxs;
1177: PetscScalar *matvals;
1178: PetscMPIInt rank;
1180: PetscFunctionBegin;
1181: PetscCall(PetscViewerSetUp(viewer));
1183: M = mat->rmap->N;
1184: N = mat->cmap->N;
1185: m = mat->rmap->n;
1186: rs = mat->rmap->rstart;
1187: cs = mat->cmap->rstart;
1188: nz = A->nz + B->nz;
1190: /* write matrix header */
1191: header[0] = MAT_FILE_CLASSID;
1192: header[1] = M;
1193: header[2] = N;
1194: PetscCallMPI(MPI_Reduce(&nz, &hnz, 1, MPIU_INT64, MPI_SUM, 0, PetscObjectComm((PetscObject)mat)));
1195: PetscCallMPI(MPI_Comm_rank(PetscObjectComm((PetscObject)mat), &rank));
1196: if (rank == 0) PetscCall(PetscIntCast(hnz, &header[3]));
1197: PetscCall(PetscViewerBinaryWrite(viewer, header, 4, PETSC_INT));
1199: /* fill in and store row lengths */
1200: PetscCall(PetscMalloc1(m, &rowlens));
1201: for (i = 0; i < m; i++) rowlens[i] = A->i[i + 1] - A->i[i] + B->i[i + 1] - B->i[i];
1202: PetscCall(PetscViewerBinaryWriteAll(viewer, rowlens, m, rs, M, PETSC_INT));
1203: PetscCall(PetscFree(rowlens));
1205: /* fill in and store column indices */
1206: PetscCall(PetscMalloc1(nz, &colidxs));
1207: for (cnt = 0, i = 0; i < m; i++) {
1208: for (jb = B->i[i]; jb < B->i[i + 1]; jb++) {
1209: if (garray[B->j[jb]] > cs) break;
1210: colidxs[cnt++] = garray[B->j[jb]];
1211: }
1212: for (ja = A->i[i]; ja < A->i[i + 1]; ja++) colidxs[cnt++] = A->j[ja] + cs;
1213: for (; jb < B->i[i + 1]; jb++) colidxs[cnt++] = garray[B->j[jb]];
1214: }
1215: PetscCheck(cnt == nz, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Internal PETSc error: cnt = %" PetscInt_FMT " nz = %" PetscInt64_FMT, cnt, nz);
1216: PetscCall(PetscViewerBinaryWriteAll(viewer, colidxs, nz, PETSC_DETERMINE, PETSC_DETERMINE, PETSC_INT));
1217: PetscCall(PetscFree(colidxs));
1219: /* fill in and store nonzero values */
1220: PetscCall(MatSeqAIJGetArrayRead(aij->A, &aa));
1221: PetscCall(MatSeqAIJGetArrayRead(aij->B, &ba));
1222: PetscCall(PetscMalloc1(nz, &matvals));
1223: for (cnt = 0, i = 0; i < m; i++) {
1224: for (jb = B->i[i]; jb < B->i[i + 1]; jb++) {
1225: if (garray[B->j[jb]] > cs) break;
1226: matvals[cnt++] = ba[jb];
1227: }
1228: for (ja = A->i[i]; ja < A->i[i + 1]; ja++) matvals[cnt++] = aa[ja];
1229: for (; jb < B->i[i + 1]; jb++) matvals[cnt++] = ba[jb];
1230: }
1231: PetscCall(MatSeqAIJRestoreArrayRead(aij->A, &aa));
1232: PetscCall(MatSeqAIJRestoreArrayRead(aij->B, &ba));
1233: PetscCheck(cnt == nz, PETSC_COMM_SELF, PETSC_ERR_LIB, "Internal PETSc error: cnt = %" PetscInt_FMT " nz = %" PetscInt64_FMT, cnt, nz);
1234: PetscCall(PetscViewerBinaryWriteAll(viewer, matvals, nz, PETSC_DETERMINE, PETSC_DETERMINE, PETSC_SCALAR));
1235: PetscCall(PetscFree(matvals));
1237: /* write block size option to the viewer's .info file */
1238: PetscCall(MatView_Binary_BlockSizes(mat, viewer));
1239: PetscFunctionReturn(PETSC_SUCCESS);
1240: }
1242: #include <petscdraw.h>
1243: static PetscErrorCode MatView_MPIAIJ_ASCIIorDraworSocket(Mat mat, PetscViewer viewer)
1244: {
1245: Mat_MPIAIJ *aij = (Mat_MPIAIJ *)mat->data;
1246: PetscMPIInt rank = aij->rank, size = aij->size;
1247: PetscBool isdraw, isascii, isbinary;
1248: PetscViewer sviewer;
1249: PetscViewerFormat format;
1251: PetscFunctionBegin;
1252: PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERDRAW, &isdraw));
1253: PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERASCII, &isascii));
1254: PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERBINARY, &isbinary));
1255: if (isascii) {
1256: PetscCall(PetscViewerGetFormat(viewer, &format));
1257: if (format == PETSC_VIEWER_LOAD_BALANCE) {
1258: PetscInt i, nmax = 0, nmin = PETSC_INT_MAX, navg = 0, *nz, nzlocal = ((Mat_SeqAIJ *)aij->A->data)->nz + ((Mat_SeqAIJ *)aij->B->data)->nz;
1259: PetscCall(PetscMalloc1(size, &nz));
1260: PetscCallMPI(MPI_Allgather(&nzlocal, 1, MPIU_INT, nz, 1, MPIU_INT, PetscObjectComm((PetscObject)mat)));
1261: for (i = 0; i < size; i++) {
1262: nmax = PetscMax(nmax, nz[i]);
1263: nmin = PetscMin(nmin, nz[i]);
1264: navg += nz[i];
1265: }
1266: PetscCall(PetscFree(nz));
1267: navg = navg / size;
1268: PetscCall(PetscViewerASCIIPrintf(viewer, "Load Balance - Nonzeros: Min %" PetscInt_FMT " avg %" PetscInt_FMT " max %" PetscInt_FMT "\n", nmin, navg, nmax));
1269: PetscFunctionReturn(PETSC_SUCCESS);
1270: }
1271: PetscCall(PetscViewerGetFormat(viewer, &format));
1272: if (format == PETSC_VIEWER_ASCII_INFO_DETAIL) {
1273: MatInfo info;
1274: PetscInt *inodes = NULL;
1276: PetscCallMPI(MPI_Comm_rank(PetscObjectComm((PetscObject)mat), &rank));
1277: PetscCall(MatGetInfo(mat, MAT_LOCAL, &info));
1278: PetscCall(MatInodeGetInodeSizes(aij->A, NULL, &inodes, NULL));
1279: PetscCall(PetscViewerASCIIPushSynchronized(viewer));
1280: if (!inodes) {
1281: 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,
1282: info.memory));
1283: } else {
1284: PetscCall(
1285: 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));
1286: }
1287: PetscCall(MatGetInfo(aij->A, MAT_LOCAL, &info));
1288: PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, "[%d] on-diagonal part: nz %" PetscInt_FMT " \n", rank, (PetscInt)info.nz_used));
1289: PetscCall(MatGetInfo(aij->B, MAT_LOCAL, &info));
1290: PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, "[%d] off-diagonal part: nz %" PetscInt_FMT " \n", rank, (PetscInt)info.nz_used));
1291: PetscCall(PetscViewerFlush(viewer));
1292: PetscCall(PetscViewerASCIIPopSynchronized(viewer));
1293: PetscCall(PetscViewerASCIIPrintf(viewer, "Information on VecScatter used in matrix-vector product: \n"));
1294: PetscCall(VecScatterView(aij->Mvctx, viewer));
1295: PetscFunctionReturn(PETSC_SUCCESS);
1296: } else if (format == PETSC_VIEWER_ASCII_INFO) {
1297: PetscInt inodecount, inodelimit, *inodes;
1298: PetscCall(MatInodeGetInodeSizes(aij->A, &inodecount, &inodes, &inodelimit));
1299: if (inodes) {
1300: PetscCall(PetscViewerASCIIPrintf(viewer, "using I-node (on process 0) routines: found %" PetscInt_FMT " nodes, limit used is %" PetscInt_FMT "\n", inodecount, inodelimit));
1301: } else {
1302: PetscCall(PetscViewerASCIIPrintf(viewer, "not using I-node (on process 0) routines\n"));
1303: }
1304: PetscFunctionReturn(PETSC_SUCCESS);
1305: } else if (format == PETSC_VIEWER_ASCII_FACTOR_INFO) {
1306: PetscFunctionReturn(PETSC_SUCCESS);
1307: }
1308: } else if (isbinary) {
1309: if (size == 1) {
1310: PetscCall(PetscObjectSetName((PetscObject)aij->A, ((PetscObject)mat)->name));
1311: PetscCall(MatView(aij->A, viewer));
1312: } else {
1313: PetscCall(MatView_MPIAIJ_Binary(mat, viewer));
1314: }
1315: PetscFunctionReturn(PETSC_SUCCESS);
1316: } else if (isascii && size == 1) {
1317: PetscCall(PetscObjectSetName((PetscObject)aij->A, ((PetscObject)mat)->name));
1318: PetscCall(MatView(aij->A, viewer));
1319: PetscFunctionReturn(PETSC_SUCCESS);
1320: } else if (isdraw) {
1321: PetscDraw draw;
1322: PetscBool isnull;
1323: PetscCall(PetscViewerDrawGetDraw(viewer, 0, &draw));
1324: PetscCall(PetscDrawIsNull(draw, &isnull));
1325: if (isnull) PetscFunctionReturn(PETSC_SUCCESS);
1326: }
1328: { /* assemble the entire matrix onto first process */
1329: Mat A, Av;
1330: IS isrow, iscol;
1332: PetscCall(ISCreateStride(PetscObjectComm((PetscObject)mat), rank == 0 ? mat->rmap->N : 0, 0, 1, &isrow));
1333: PetscCall(ISCreateStride(PetscObjectComm((PetscObject)mat), rank == 0 ? mat->cmap->N : 0, 0, 1, &iscol));
1334: PetscCall(MatCreateSubMatrix(mat, isrow, iscol, MAT_INITIAL_MATRIX, &A));
1335: PetscCall(MatMPIAIJGetSeqAIJ(A, &Av, NULL, NULL));
1336: PetscCall(ISDestroy(&iscol));
1337: PetscCall(ISDestroy(&isrow));
1338: /*
1339: Everyone has to call to draw the matrix since the graphics waits are
1340: synchronized across all processors that share the PetscDraw object
1341: */
1342: PetscCall(PetscViewerGetSubViewer(viewer, PETSC_COMM_SELF, &sviewer));
1343: if (rank == 0) {
1344: if (((PetscObject)mat)->name) PetscCall(PetscObjectSetName((PetscObject)Av, ((PetscObject)mat)->name));
1345: PetscCall(MatView_SeqAIJ(Av, sviewer));
1346: }
1347: PetscCall(PetscViewerRestoreSubViewer(viewer, PETSC_COMM_SELF, &sviewer));
1348: PetscCall(MatDestroy(&A));
1349: }
1350: PetscFunctionReturn(PETSC_SUCCESS);
1351: }
1353: PetscErrorCode MatView_MPIAIJ(Mat mat, PetscViewer viewer)
1354: {
1355: PetscBool isascii, isdraw, issocket, isbinary;
1357: PetscFunctionBegin;
1358: PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERASCII, &isascii));
1359: PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERDRAW, &isdraw));
1360: PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERBINARY, &isbinary));
1361: PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERSOCKET, &issocket));
1362: if (isascii || isdraw || isbinary || issocket) PetscCall(MatView_MPIAIJ_ASCIIorDraworSocket(mat, viewer));
1363: PetscFunctionReturn(PETSC_SUCCESS);
1364: }
1366: static PetscErrorCode MatSOR_MPIAIJ(Mat matin, Vec bb, PetscReal omega, MatSORType flag, PetscReal fshift, PetscInt its, PetscInt lits, Vec xx)
1367: {
1368: Mat_MPIAIJ *mat = (Mat_MPIAIJ *)matin->data;
1369: Vec bb1 = NULL;
1370: PetscBool hasop;
1372: PetscFunctionBegin;
1373: if (flag == SOR_APPLY_UPPER) {
1374: PetscUseTypeMethod(mat->A, sor, bb, omega, flag, fshift, lits, 1, xx);
1375: PetscFunctionReturn(PETSC_SUCCESS);
1376: }
1378: if (its > 1 || ~flag & SOR_ZERO_INITIAL_GUESS || flag & SOR_EISENSTAT) PetscCall(VecDuplicate(bb, &bb1));
1380: if ((flag & SOR_LOCAL_SYMMETRIC_SWEEP) == SOR_LOCAL_SYMMETRIC_SWEEP) {
1381: if (flag & SOR_ZERO_INITIAL_GUESS) {
1382: PetscUseTypeMethod(mat->A, sor, bb, omega, flag, fshift, lits, 1, xx);
1383: its--;
1384: }
1386: while (its--) {
1387: PetscCall(VecScatterBegin(mat->Mvctx, xx, mat->lvec, INSERT_VALUES, SCATTER_FORWARD));
1388: PetscCall(VecScatterEnd(mat->Mvctx, xx, mat->lvec, INSERT_VALUES, SCATTER_FORWARD));
1390: /* update rhs: bb1 = bb - B*x */
1391: PetscCall(VecScale(mat->lvec, -1.0));
1392: PetscUseTypeMethod(mat->B, multadd, mat->lvec, bb, bb1);
1394: /* local sweep */
1395: PetscUseTypeMethod(mat->A, sor, bb1, omega, SOR_SYMMETRIC_SWEEP, fshift, lits, 1, xx);
1396: }
1397: } else if (flag & SOR_LOCAL_FORWARD_SWEEP) {
1398: if (flag & SOR_ZERO_INITIAL_GUESS) {
1399: PetscUseTypeMethod(mat->A, sor, bb, omega, flag, fshift, lits, 1, xx);
1400: its--;
1401: }
1402: while (its--) {
1403: PetscCall(VecScatterBegin(mat->Mvctx, xx, mat->lvec, INSERT_VALUES, SCATTER_FORWARD));
1404: PetscCall(VecScatterEnd(mat->Mvctx, xx, mat->lvec, INSERT_VALUES, SCATTER_FORWARD));
1406: /* update rhs: bb1 = bb - B*x */
1407: PetscCall(VecScale(mat->lvec, -1.0));
1408: PetscUseTypeMethod(mat->B, multadd, mat->lvec, bb, bb1);
1410: /* local sweep */
1411: PetscUseTypeMethod(mat->A, sor, bb1, omega, SOR_FORWARD_SWEEP, fshift, lits, 1, xx);
1412: }
1413: } else if (flag & SOR_LOCAL_BACKWARD_SWEEP) {
1414: if (flag & SOR_ZERO_INITIAL_GUESS) {
1415: PetscUseTypeMethod(mat->A, sor, bb, omega, flag, fshift, lits, 1, xx);
1416: its--;
1417: }
1418: while (its--) {
1419: PetscCall(VecScatterBegin(mat->Mvctx, xx, mat->lvec, INSERT_VALUES, SCATTER_FORWARD));
1420: PetscCall(VecScatterEnd(mat->Mvctx, xx, mat->lvec, INSERT_VALUES, SCATTER_FORWARD));
1422: /* update rhs: bb1 = bb - B*x */
1423: PetscCall(VecScale(mat->lvec, -1.0));
1424: PetscUseTypeMethod(mat->B, multadd, mat->lvec, bb, bb1);
1426: /* local sweep */
1427: PetscUseTypeMethod(mat->A, sor, bb1, omega, SOR_BACKWARD_SWEEP, fshift, lits, 1, xx);
1428: }
1429: } else if (flag & SOR_EISENSTAT) {
1430: Vec xx1;
1432: PetscCall(VecDuplicate(bb, &xx1));
1433: PetscUseTypeMethod(mat->A, sor, bb, omega, (MatSORType)(SOR_ZERO_INITIAL_GUESS | SOR_LOCAL_BACKWARD_SWEEP), fshift, lits, 1, xx);
1435: PetscCall(VecScatterBegin(mat->Mvctx, xx, mat->lvec, INSERT_VALUES, SCATTER_FORWARD));
1436: PetscCall(VecScatterEnd(mat->Mvctx, xx, mat->lvec, INSERT_VALUES, SCATTER_FORWARD));
1437: if (!mat->diag) {
1438: PetscCall(MatCreateVecs(matin, &mat->diag, NULL));
1439: PetscCall(MatGetDiagonal(matin, mat->diag));
1440: }
1441: PetscCall(MatHasOperation(matin, MATOP_MULT_DIAGONAL_BLOCK, &hasop));
1442: if (hasop) PetscCall(MatMultDiagonalBlock(matin, xx, bb1));
1443: else PetscCall(VecPointwiseMult(bb1, mat->diag, xx));
1444: PetscCall(VecAYPX(bb1, (omega - 2.0) / omega, bb));
1446: PetscCall(MatMultAdd(mat->B, mat->lvec, bb1, bb1));
1448: /* local sweep */
1449: PetscUseTypeMethod(mat->A, sor, bb1, omega, (MatSORType)(SOR_ZERO_INITIAL_GUESS | SOR_LOCAL_FORWARD_SWEEP), fshift, lits, 1, xx1);
1450: PetscCall(VecAXPY(xx, 1.0, xx1));
1451: PetscCall(VecDestroy(&xx1));
1452: } else SETERRQ(PetscObjectComm((PetscObject)matin), PETSC_ERR_SUP, "Parallel SOR not supported");
1454: PetscCall(VecDestroy(&bb1));
1456: matin->factorerrortype = mat->A->factorerrortype;
1457: PetscFunctionReturn(PETSC_SUCCESS);
1458: }
1460: static PetscErrorCode MatPermute_MPIAIJ(Mat A, IS rowp, IS colp, Mat *B)
1461: {
1462: Mat aA, aB, Aperm;
1463: const PetscInt *rwant, *cwant, *gcols, *ai, *bi, *aj, *bj;
1464: PetscScalar *aa, *ba;
1465: PetscInt i, j, m, n, ng, anz, bnz, *dnnz, *onnz, *tdnnz, *tonnz, *rdest, *cdest, *work, *gcdest;
1466: PetscSF rowsf, sf;
1467: IS parcolp = NULL;
1468: PetscBool done;
1470: PetscFunctionBegin;
1471: PetscCall(MatGetLocalSize(A, &m, &n));
1472: PetscCall(ISGetIndices(rowp, &rwant));
1473: PetscCall(ISGetIndices(colp, &cwant));
1474: PetscCall(PetscMalloc3(PetscMax(m, n), &work, m, &rdest, n, &cdest));
1476: /* Invert row permutation to find out where my rows should go */
1477: PetscCall(PetscSFCreate(PetscObjectComm((PetscObject)A), &rowsf));
1478: PetscCall(PetscSFSetGraphLayout(rowsf, A->rmap, A->rmap->n, NULL, PETSC_OWN_POINTER, rwant));
1479: PetscCall(PetscSFSetFromOptions(rowsf));
1480: for (i = 0; i < m; i++) work[i] = A->rmap->rstart + i;
1481: PetscCall(PetscSFReduceBegin(rowsf, MPIU_INT, work, rdest, MPI_REPLACE));
1482: PetscCall(PetscSFReduceEnd(rowsf, MPIU_INT, work, rdest, MPI_REPLACE));
1484: /* Invert column permutation to find out where my columns should go */
1485: PetscCall(PetscSFCreate(PetscObjectComm((PetscObject)A), &sf));
1486: PetscCall(PetscSFSetGraphLayout(sf, A->cmap, A->cmap->n, NULL, PETSC_OWN_POINTER, cwant));
1487: PetscCall(PetscSFSetFromOptions(sf));
1488: for (i = 0; i < n; i++) work[i] = A->cmap->rstart + i;
1489: PetscCall(PetscSFReduceBegin(sf, MPIU_INT, work, cdest, MPI_REPLACE));
1490: PetscCall(PetscSFReduceEnd(sf, MPIU_INT, work, cdest, MPI_REPLACE));
1491: PetscCall(PetscSFDestroy(&sf));
1493: PetscCall(ISRestoreIndices(rowp, &rwant));
1494: PetscCall(ISRestoreIndices(colp, &cwant));
1495: PetscCall(MatMPIAIJGetSeqAIJ(A, &aA, &aB, &gcols));
1497: /* Find out where my gcols should go */
1498: PetscCall(MatGetSize(aB, NULL, &ng));
1499: PetscCall(PetscMalloc1(ng, &gcdest));
1500: PetscCall(PetscSFCreate(PetscObjectComm((PetscObject)A), &sf));
1501: PetscCall(PetscSFSetGraphLayout(sf, A->cmap, ng, NULL, PETSC_OWN_POINTER, gcols));
1502: PetscCall(PetscSFSetFromOptions(sf));
1503: PetscCall(PetscSFBcastBegin(sf, MPIU_INT, cdest, gcdest, MPI_REPLACE));
1504: PetscCall(PetscSFBcastEnd(sf, MPIU_INT, cdest, gcdest, MPI_REPLACE));
1505: PetscCall(PetscSFDestroy(&sf));
1507: PetscCall(PetscCalloc4(m, &dnnz, m, &onnz, m, &tdnnz, m, &tonnz));
1508: PetscCall(MatGetRowIJ(aA, 0, PETSC_FALSE, PETSC_FALSE, &anz, &ai, &aj, &done));
1509: PetscCall(MatGetRowIJ(aB, 0, PETSC_FALSE, PETSC_FALSE, &bnz, &bi, &bj, &done));
1510: for (i = 0; i < m; i++) {
1511: PetscInt row = rdest[i];
1512: PetscMPIInt rowner;
1513: PetscCall(PetscLayoutFindOwner(A->rmap, row, &rowner));
1514: for (j = ai[i]; j < ai[i + 1]; j++) {
1515: PetscInt col = cdest[aj[j]];
1516: PetscMPIInt cowner;
1517: PetscCall(PetscLayoutFindOwner(A->cmap, col, &cowner)); /* Could build an index for the columns to eliminate this search */
1518: if (rowner == cowner) dnnz[i]++;
1519: else onnz[i]++;
1520: }
1521: for (j = bi[i]; j < bi[i + 1]; j++) {
1522: PetscInt col = gcdest[bj[j]];
1523: PetscMPIInt cowner;
1524: PetscCall(PetscLayoutFindOwner(A->cmap, col, &cowner));
1525: if (rowner == cowner) dnnz[i]++;
1526: else onnz[i]++;
1527: }
1528: }
1529: PetscCall(PetscSFBcastBegin(rowsf, MPIU_INT, dnnz, tdnnz, MPI_REPLACE));
1530: PetscCall(PetscSFBcastEnd(rowsf, MPIU_INT, dnnz, tdnnz, MPI_REPLACE));
1531: PetscCall(PetscSFBcastBegin(rowsf, MPIU_INT, onnz, tonnz, MPI_REPLACE));
1532: PetscCall(PetscSFBcastEnd(rowsf, MPIU_INT, onnz, tonnz, MPI_REPLACE));
1533: PetscCall(PetscSFDestroy(&rowsf));
1535: PetscCall(MatCreateAIJ(PetscObjectComm((PetscObject)A), A->rmap->n, A->cmap->n, A->rmap->N, A->cmap->N, 0, tdnnz, 0, tonnz, &Aperm));
1536: PetscCall(MatSetBlockSizesFromMats(Aperm, A, A));
1537: PetscCall(MatSeqAIJGetArray(aA, &aa));
1538: PetscCall(MatSeqAIJGetArray(aB, &ba));
1539: for (i = 0; i < m; i++) {
1540: PetscInt *acols = dnnz, *bcols = onnz; /* Repurpose now-unneeded arrays */
1541: PetscInt rowlen;
1542: rowlen = ai[i + 1] - ai[i];
1543: for (PetscInt j0 = j = 0; j < rowlen; j0 = j) { /* rowlen could be larger than number of rows m, so sum in batches */
1544: for (; j < PetscMin(rowlen, j0 + m); j++) acols[j - j0] = cdest[aj[ai[i] + j]];
1545: PetscCall(MatSetValues(Aperm, 1, &rdest[i], j - j0, acols, aa + ai[i] + j0, INSERT_VALUES));
1546: }
1547: rowlen = bi[i + 1] - bi[i];
1548: for (PetscInt j0 = j = 0; j < rowlen; j0 = j) {
1549: for (; j < PetscMin(rowlen, j0 + m); j++) bcols[j - j0] = gcdest[bj[bi[i] + j]];
1550: PetscCall(MatSetValues(Aperm, 1, &rdest[i], j - j0, bcols, ba + bi[i] + j0, INSERT_VALUES));
1551: }
1552: }
1553: PetscCall(MatAssemblyBegin(Aperm, MAT_FINAL_ASSEMBLY));
1554: PetscCall(MatAssemblyEnd(Aperm, MAT_FINAL_ASSEMBLY));
1555: PetscCall(MatRestoreRowIJ(aA, 0, PETSC_FALSE, PETSC_FALSE, &anz, &ai, &aj, &done));
1556: PetscCall(MatRestoreRowIJ(aB, 0, PETSC_FALSE, PETSC_FALSE, &bnz, &bi, &bj, &done));
1557: PetscCall(MatSeqAIJRestoreArray(aA, &aa));
1558: PetscCall(MatSeqAIJRestoreArray(aB, &ba));
1559: PetscCall(PetscFree4(dnnz, onnz, tdnnz, tonnz));
1560: PetscCall(PetscFree3(work, rdest, cdest));
1561: PetscCall(PetscFree(gcdest));
1562: if (parcolp) PetscCall(ISDestroy(&colp));
1563: *B = Aperm;
1564: PetscFunctionReturn(PETSC_SUCCESS);
1565: }
1567: static PetscErrorCode MatGetGhosts_MPIAIJ(Mat mat, PetscInt *nghosts, const PetscInt *ghosts[])
1568: {
1569: Mat_MPIAIJ *aij = (Mat_MPIAIJ *)mat->data;
1571: PetscFunctionBegin;
1572: PetscCall(MatGetSize(aij->B, NULL, nghosts));
1573: if (ghosts) *ghosts = aij->garray;
1574: PetscFunctionReturn(PETSC_SUCCESS);
1575: }
1577: static PetscErrorCode MatGetInfo_MPIAIJ(Mat matin, MatInfoType flag, MatInfo *info)
1578: {
1579: Mat_MPIAIJ *mat = (Mat_MPIAIJ *)matin->data;
1580: Mat A = mat->A, B = mat->B;
1581: PetscLogDouble irecv[5];
1583: PetscFunctionBegin;
1584: info->block_size = 1.0;
1585: PetscCall(MatGetInfo(A, MAT_LOCAL, info));
1587: irecv[0] = info->nz_used;
1588: irecv[1] = info->nz_allocated;
1589: irecv[2] = info->nz_unneeded;
1590: irecv[3] = info->memory;
1591: irecv[4] = info->mallocs;
1593: PetscCall(MatGetInfo(B, MAT_LOCAL, info));
1595: irecv[0] += info->nz_used;
1596: irecv[1] += info->nz_allocated;
1597: irecv[2] += info->nz_unneeded;
1598: irecv[3] += info->memory;
1599: irecv[4] += info->mallocs;
1600: if (flag == MAT_LOCAL) {
1601: info->nz_used = irecv[0];
1602: info->nz_allocated = irecv[1];
1603: info->nz_unneeded = irecv[2];
1604: info->memory = irecv[3];
1605: info->mallocs = irecv[4];
1606: } else if (flag == MAT_GLOBAL_MAX) {
1607: PetscCallMPI(MPIU_Allreduce(MPI_IN_PLACE, irecv, 5, MPIU_PETSCLOGDOUBLE, MPI_MAX, PetscObjectComm((PetscObject)matin)));
1609: info->nz_used = irecv[0];
1610: info->nz_allocated = irecv[1];
1611: info->nz_unneeded = irecv[2];
1612: info->memory = irecv[3];
1613: info->mallocs = irecv[4];
1614: } else if (flag == MAT_GLOBAL_SUM) {
1615: PetscCallMPI(MPIU_Allreduce(MPI_IN_PLACE, irecv, 5, MPIU_PETSCLOGDOUBLE, MPI_SUM, PetscObjectComm((PetscObject)matin)));
1617: info->nz_used = irecv[0];
1618: info->nz_allocated = irecv[1];
1619: info->nz_unneeded = irecv[2];
1620: info->memory = irecv[3];
1621: info->mallocs = irecv[4];
1622: }
1623: info->fill_ratio_given = 0; /* no parallel LU/ILU/Cholesky */
1624: info->fill_ratio_needed = 0;
1625: info->factor_mallocs = 0;
1626: PetscFunctionReturn(PETSC_SUCCESS);
1627: }
1629: PetscErrorCode MatSetOption_MPIAIJ(Mat A, MatOption op, PetscBool flg)
1630: {
1631: Mat_MPIAIJ *a = (Mat_MPIAIJ *)A->data;
1633: PetscFunctionBegin;
1634: switch (op) {
1635: case MAT_NEW_NONZERO_LOCATIONS:
1636: case MAT_NEW_NONZERO_ALLOCATION_ERR:
1637: case MAT_UNUSED_NONZERO_LOCATION_ERR:
1638: case MAT_KEEP_NONZERO_PATTERN:
1639: case MAT_NEW_NONZERO_LOCATION_ERR:
1640: case MAT_USE_INODES:
1641: case MAT_IGNORE_ZERO_ENTRIES:
1642: case MAT_FORM_EXPLICIT_TRANSPOSE:
1643: case MAT_ROW_ORIENTED:
1644: MatCheckPreallocated(A, 1);
1645: if (op == MAT_ROW_ORIENTED) a->roworiented = flg;
1646: PetscCall(MatSetOption(a->A, op, flg));
1647: PetscCall(MatSetOption(a->B, op, flg));
1648: break;
1649: case MAT_STRUCTURE_ONLY:
1650: if (a->A) PetscCall(MatSetOption(a->A, op, flg));
1651: if (a->B) PetscCall(MatSetOption(a->B, op, flg));
1652: break;
1653: case MAT_IGNORE_OFF_PROC_ENTRIES:
1654: a->donotstash = flg;
1655: break;
1656: /* Symmetry flags are handled directly by MatSetOption() and they don't affect preallocation */
1657: case MAT_SPD:
1658: case MAT_SYMMETRIC:
1659: case MAT_STRUCTURALLY_SYMMETRIC:
1660: case MAT_HERMITIAN:
1661: case MAT_SYMMETRY_ETERNAL:
1662: case MAT_STRUCTURAL_SYMMETRY_ETERNAL:
1663: case MAT_SPD_ETERNAL:
1664: /* if the diagonal matrix is square it inherits some of the properties above */
1665: if (a->A && A->rmap->n == A->cmap->n) PetscCall(MatSetOption(a->A, op, flg));
1666: break;
1667: case MAT_SUBMAT_SINGLEIS:
1668: A->submat_singleis = flg;
1669: break;
1670: default:
1671: break;
1672: }
1673: PetscFunctionReturn(PETSC_SUCCESS);
1674: }
1676: PetscErrorCode MatGetRow_MPIAIJ(Mat matin, PetscInt row, PetscInt *nz, PetscInt **idx, PetscScalar **v)
1677: {
1678: Mat_MPIAIJ *mat = (Mat_MPIAIJ *)matin->data;
1679: PetscScalar *vworkA, *vworkB, **pvA, **pvB, *v_p;
1680: PetscInt i, *cworkA, *cworkB, **pcA, **pcB, cstart = matin->cmap->rstart;
1681: PetscInt nztot, nzA, nzB, lrow, rstart = matin->rmap->rstart, rend = matin->rmap->rend;
1682: PetscInt *cmap, *idx_p;
1684: PetscFunctionBegin;
1685: PetscCheck(!mat->getrowactive, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Already active");
1686: mat->getrowactive = PETSC_TRUE;
1688: if ((!mat->rowindices && (idx || v)) || (!mat->rowvalues && v)) {
1689: /*
1690: allocate enough space to hold information from the longest row.
1691: */
1692: Mat_SeqAIJ *Aa = (Mat_SeqAIJ *)mat->A->data, *Ba = (Mat_SeqAIJ *)mat->B->data;
1693: PetscInt max = 1, tmp;
1694: for (i = 0; i < matin->rmap->n; i++) {
1695: tmp = Aa->i[i + 1] - Aa->i[i] + Ba->i[i + 1] - Ba->i[i];
1696: if (max < tmp) max = tmp;
1697: }
1698: PetscCall(PetscFree2(mat->rowvalues, mat->rowindices));
1699: PetscCall(PetscMalloc2(v ? max : 0, &mat->rowvalues, max, &mat->rowindices));
1700: }
1702: PetscCheck(row >= rstart && row < rend, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Only local rows");
1703: lrow = row - rstart;
1705: pvA = &vworkA;
1706: pcA = &cworkA;
1707: pvB = &vworkB;
1708: pcB = &cworkB;
1709: if (!v) {
1710: pvA = NULL;
1711: pvB = NULL;
1712: }
1713: if (!idx) {
1714: pcA = NULL;
1715: if (!v) pcB = NULL;
1716: }
1717: PetscUseTypeMethod(mat->A, getrow, lrow, &nzA, pcA, pvA);
1718: PetscUseTypeMethod(mat->B, getrow, lrow, &nzB, pcB, pvB);
1719: nztot = nzA + nzB;
1721: cmap = mat->garray;
1722: if (v || idx) {
1723: if (nztot) {
1724: /* Sort by increasing column numbers, assuming A and B already sorted */
1725: PetscInt imark = -1;
1726: if (v) {
1727: *v = v_p = mat->rowvalues;
1728: for (i = 0; i < nzB; i++) {
1729: if (cmap[cworkB[i]] < cstart) v_p[i] = vworkB[i];
1730: else break;
1731: }
1732: imark = i;
1733: for (i = 0; i < nzA; i++) v_p[imark + i] = vworkA[i];
1734: for (i = imark; i < nzB; i++) v_p[nzA + i] = vworkB[i];
1735: }
1736: if (idx) {
1737: *idx = idx_p = mat->rowindices;
1738: if (imark > -1) {
1739: for (i = 0; i < imark; i++) idx_p[i] = cmap[cworkB[i]];
1740: } else {
1741: for (i = 0; i < nzB; i++) {
1742: if (cmap[cworkB[i]] < cstart) idx_p[i] = cmap[cworkB[i]];
1743: else break;
1744: }
1745: imark = i;
1746: }
1747: for (i = 0; i < nzA; i++) idx_p[imark + i] = cstart + cworkA[i];
1748: for (i = imark; i < nzB; i++) idx_p[nzA + i] = cmap[cworkB[i]];
1749: }
1750: } else {
1751: if (idx) *idx = NULL;
1752: if (v) *v = NULL;
1753: }
1754: }
1755: *nz = nztot;
1756: PetscUseTypeMethod(mat->A, restorerow, lrow, &nzA, pcA, pvA);
1757: PetscUseTypeMethod(mat->B, restorerow, lrow, &nzB, pcB, pvB);
1758: PetscFunctionReturn(PETSC_SUCCESS);
1759: }
1761: PetscErrorCode MatRestoreRow_MPIAIJ(Mat mat, PetscInt row, PetscInt *nz, PetscInt **idx, PetscScalar **v)
1762: {
1763: Mat_MPIAIJ *aij = (Mat_MPIAIJ *)mat->data;
1765: PetscFunctionBegin;
1766: PetscCheck(aij->getrowactive, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "MatGetRow() must be called first");
1767: aij->getrowactive = PETSC_FALSE;
1768: PetscFunctionReturn(PETSC_SUCCESS);
1769: }
1771: static PetscErrorCode MatNorm_MPIAIJ(Mat mat, NormType type, PetscReal *norm)
1772: {
1773: Mat_MPIAIJ *aij = (Mat_MPIAIJ *)mat->data;
1774: Mat_SeqAIJ *amat = (Mat_SeqAIJ *)aij->A->data, *bmat = (Mat_SeqAIJ *)aij->B->data;
1775: PetscInt i, j;
1776: PetscReal sum = 0.0;
1777: const MatScalar *v, *amata, *bmata;
1779: PetscFunctionBegin;
1780: if (aij->size == 1) {
1781: PetscCall(MatNorm(aij->A, type, norm));
1782: } else {
1783: PetscCall(MatSeqAIJGetArrayRead(aij->A, &amata));
1784: PetscCall(MatSeqAIJGetArrayRead(aij->B, &bmata));
1785: if (type == NORM_FROBENIUS) {
1786: v = amata;
1787: for (i = 0; i < amat->nz; i++) {
1788: sum += PetscRealPart(PetscConj(*v) * (*v));
1789: v++;
1790: }
1791: v = bmata;
1792: for (i = 0; i < bmat->nz; i++) {
1793: sum += PetscRealPart(PetscConj(*v) * (*v));
1794: v++;
1795: }
1796: PetscCallMPI(MPIU_Allreduce(&sum, norm, 1, MPIU_REAL, MPIU_SUM, PetscObjectComm((PetscObject)mat)));
1797: *norm = PetscSqrtReal(*norm);
1798: PetscCall(PetscLogFlops(2.0 * amat->nz + 2.0 * bmat->nz));
1799: } else if (type == NORM_1) { /* max column norm */
1800: Vec col, bcol;
1801: PetscScalar *array;
1802: PetscInt *jj, *garray = aij->garray;
1804: PetscCall(MatCreateVecs(mat, &col, NULL));
1805: PetscCall(VecGetArrayWrite(col, &array));
1806: v = amata;
1807: jj = amat->j;
1808: for (j = 0; j < amat->nz; j++) array[*jj++] += PetscAbsScalar(*v++);
1809: PetscCall(VecRestoreArrayWrite(col, &array));
1810: PetscCall(MatCreateVecs(aij->B, &bcol, NULL));
1811: PetscCall(VecGetArrayWrite(bcol, &array));
1812: v = bmata;
1813: jj = bmat->j;
1814: for (j = 0; j < bmat->nz; j++) array[*jj++] += PetscAbsScalar(*v++);
1815: PetscCall(VecSetValues(col, aij->B->cmap->n, garray, array, ADD_VALUES));
1816: PetscCall(VecRestoreArrayWrite(bcol, &array));
1817: PetscCall(VecDestroy(&bcol));
1818: PetscCall(VecAssemblyBegin(col));
1819: PetscCall(VecAssemblyEnd(col));
1820: PetscCall(VecNorm(col, NORM_INFINITY, norm));
1821: PetscCall(VecDestroy(&col));
1822: } else if (type == NORM_INFINITY) { /* max row norm */
1823: *norm = 0.0;
1824: for (j = 0; j < aij->A->rmap->n; j++) {
1825: v = PetscSafePointerPlusOffset(amata, amat->i[j]);
1826: sum = 0.0;
1827: for (i = 0; i < amat->i[j + 1] - amat->i[j]; i++) {
1828: sum += PetscAbsScalar(*v);
1829: v++;
1830: }
1831: v = PetscSafePointerPlusOffset(bmata, bmat->i[j]);
1832: for (i = 0; i < bmat->i[j + 1] - bmat->i[j]; i++) {
1833: sum += PetscAbsScalar(*v);
1834: v++;
1835: }
1836: if (sum > *norm) *norm = sum;
1837: }
1838: PetscCallMPI(MPIU_Allreduce(MPI_IN_PLACE, norm, 1, MPIU_REAL, MPIU_MAX, PetscObjectComm((PetscObject)mat)));
1839: PetscCall(PetscLogFlops(PetscMax(amat->nz + bmat->nz - 1, 0)));
1840: } else SETERRQ(PetscObjectComm((PetscObject)mat), PETSC_ERR_SUP, "No support for two norm");
1841: PetscCall(MatSeqAIJRestoreArrayRead(aij->A, &amata));
1842: PetscCall(MatSeqAIJRestoreArrayRead(aij->B, &bmata));
1843: }
1844: PetscFunctionReturn(PETSC_SUCCESS);
1845: }
1847: static PetscErrorCode MatTranspose_MPIAIJ(Mat A, MatReuse reuse, Mat *matout)
1848: {
1849: Mat_MPIAIJ *a = (Mat_MPIAIJ *)A->data, *b;
1850: Mat_SeqAIJ *Aloc = (Mat_SeqAIJ *)a->A->data, *Bloc = (Mat_SeqAIJ *)a->B->data, *sub_B_diag;
1851: 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;
1852: const PetscInt *ai, *aj, *bi, *bj, *B_diag_i;
1853: Mat B, A_diag, *B_diag;
1854: const MatScalar *pbv, *bv;
1856: PetscFunctionBegin;
1857: if (reuse == MAT_REUSE_MATRIX) PetscCall(MatTransposeCheckNonzeroState_Private(A, *matout));
1858: ma = A->rmap->n;
1859: na = A->cmap->n;
1860: mb = a->B->rmap->n;
1861: nb = a->B->cmap->n;
1862: ai = Aloc->i;
1863: aj = Aloc->j;
1864: bi = Bloc->i;
1865: bj = Bloc->j;
1866: if (reuse == MAT_INITIAL_MATRIX || *matout == A) {
1867: PetscInt *d_nnz, *g_nnz, *o_nnz;
1868: PetscSFNode *oloc;
1869: PETSC_UNUSED PetscSF sf;
1871: PetscCall(PetscMalloc4(na, &d_nnz, na, &o_nnz, nb, &g_nnz, nb, &oloc));
1872: /* compute d_nnz for preallocation */
1873: PetscCall(PetscArrayzero(d_nnz, na));
1874: for (i = 0; i < ai[ma]; i++) d_nnz[aj[i]]++;
1875: /* compute local off-diagonal contributions */
1876: PetscCall(PetscArrayzero(g_nnz, nb));
1877: for (i = 0; i < bi[ma]; i++) g_nnz[bj[i]]++;
1878: /* map those to global */
1879: PetscCall(PetscSFCreate(PetscObjectComm((PetscObject)A), &sf));
1880: PetscCall(PetscSFSetGraphLayout(sf, A->cmap, nb, NULL, PETSC_USE_POINTER, a->garray));
1881: PetscCall(PetscSFSetFromOptions(sf));
1882: PetscCall(PetscArrayzero(o_nnz, na));
1883: PetscCall(PetscSFReduceBegin(sf, MPIU_INT, g_nnz, o_nnz, MPI_SUM));
1884: PetscCall(PetscSFReduceEnd(sf, MPIU_INT, g_nnz, o_nnz, MPI_SUM));
1885: PetscCall(PetscSFDestroy(&sf));
1887: PetscCall(MatCreate(PetscObjectComm((PetscObject)A), &B));
1888: PetscCall(MatSetSizes(B, A->cmap->n, A->rmap->n, N, M));
1889: PetscCall(MatSetBlockSizes(B, A->cmap->bs, A->rmap->bs));
1890: PetscCall(MatSetType(B, ((PetscObject)A)->type_name));
1891: PetscCall(MatMPIAIJSetPreallocation(B, 0, d_nnz, 0, o_nnz));
1892: PetscCall(PetscFree4(d_nnz, o_nnz, g_nnz, oloc));
1893: } else {
1894: B = *matout;
1895: PetscCall(MatSetOption(B, MAT_NEW_NONZERO_ALLOCATION_ERR, PETSC_TRUE));
1896: }
1898: b = (Mat_MPIAIJ *)B->data;
1899: A_diag = a->A;
1900: B_diag = &b->A;
1901: sub_B_diag = (Mat_SeqAIJ *)(*B_diag)->data;
1902: A_diag_ncol = A_diag->cmap->N;
1903: B_diag_ilen = sub_B_diag->ilen;
1904: B_diag_i = sub_B_diag->i;
1906: /* Set ilen for diagonal of B */
1907: for (i = 0; i < A_diag_ncol; i++) B_diag_ilen[i] = B_diag_i[i + 1] - B_diag_i[i];
1909: /* Transpose the diagonal part of the matrix. In contrast to the off-diagonal part, this can be done
1910: very quickly (=without using MatSetValues), because all writes are local. */
1911: PetscCall(MatTransposeSetPrecursor(A_diag, *B_diag));
1912: PetscCall(MatTranspose(A_diag, MAT_REUSE_MATRIX, B_diag));
1914: /* copy over the B part */
1915: PetscCall(PetscMalloc1(bi[mb], &cols));
1916: PetscCall(MatSeqAIJGetArrayRead(a->B, &bv));
1917: pbv = bv;
1918: row = A->rmap->rstart;
1919: for (i = 0; i < bi[mb]; i++) cols[i] = a->garray[bj[i]];
1920: cols_tmp = cols;
1921: for (i = 0; i < mb; i++) {
1922: ncol = bi[i + 1] - bi[i];
1923: PetscCall(MatSetValues(B, ncol, cols_tmp, 1, &row, pbv, INSERT_VALUES));
1924: row++;
1925: if (pbv) pbv += ncol;
1926: if (cols_tmp) cols_tmp += ncol;
1927: }
1928: PetscCall(PetscFree(cols));
1929: PetscCall(MatSeqAIJRestoreArrayRead(a->B, &bv));
1931: PetscCall(MatAssemblyBegin(B, MAT_FINAL_ASSEMBLY));
1932: PetscCall(MatAssemblyEnd(B, MAT_FINAL_ASSEMBLY));
1933: if (reuse == MAT_INITIAL_MATRIX || reuse == MAT_REUSE_MATRIX) {
1934: *matout = B;
1935: } else {
1936: PetscCall(MatHeaderMerge(A, &B));
1937: }
1938: PetscFunctionReturn(PETSC_SUCCESS);
1939: }
1941: static PetscErrorCode MatDiagonalScale_MPIAIJ(Mat mat, Vec ll, Vec rr)
1942: {
1943: Mat_MPIAIJ *aij = (Mat_MPIAIJ *)mat->data;
1944: Mat a = aij->A, b = aij->B;
1945: PetscInt s1, s2, s3;
1947: PetscFunctionBegin;
1948: PetscCall(MatGetLocalSize(mat, &s2, &s3));
1949: if (rr) {
1950: PetscCall(VecGetLocalSize(rr, &s1));
1951: PetscCheck(s1 == s3, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "right vector non-conforming local size");
1952: /* Overlap communication with computation. */
1953: PetscCall(VecScatterBegin(aij->Mvctx, rr, aij->lvec, INSERT_VALUES, SCATTER_FORWARD));
1954: }
1955: if (ll) {
1956: PetscCall(VecGetLocalSize(ll, &s1));
1957: PetscCheck(s1 == s2, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "left vector non-conforming local size");
1958: PetscUseTypeMethod(b, diagonalscale, ll, NULL);
1959: }
1960: /* scale the diagonal block */
1961: PetscUseTypeMethod(a, diagonalscale, ll, rr);
1963: if (rr) {
1964: /* Do a scatter end and then right scale the off-diagonal block */
1965: PetscCall(VecScatterEnd(aij->Mvctx, rr, aij->lvec, INSERT_VALUES, SCATTER_FORWARD));
1966: PetscUseTypeMethod(b, diagonalscale, NULL, aij->lvec);
1967: }
1968: PetscFunctionReturn(PETSC_SUCCESS);
1969: }
1971: static PetscErrorCode MatSetUnfactored_MPIAIJ(Mat A)
1972: {
1973: Mat_MPIAIJ *a = (Mat_MPIAIJ *)A->data;
1975: PetscFunctionBegin;
1976: PetscCall(MatSetUnfactored(a->A));
1977: PetscFunctionReturn(PETSC_SUCCESS);
1978: }
1980: static PetscErrorCode MatEqual_MPIAIJ(Mat A, Mat B, PetscBool *flag)
1981: {
1982: Mat_MPIAIJ *matB = (Mat_MPIAIJ *)B->data, *matA = (Mat_MPIAIJ *)A->data;
1983: Mat a, b, c, d;
1985: PetscFunctionBegin;
1986: a = matA->A;
1987: b = matA->B;
1988: c = matB->A;
1989: d = matB->B;
1991: PetscCall(MatEqual(a, c, flag));
1992: if (*flag) PetscCall(MatEqual(b, d, flag));
1993: PetscCallMPI(MPIU_Allreduce(MPI_IN_PLACE, flag, 1, MPI_C_BOOL, MPI_LAND, PetscObjectComm((PetscObject)A)));
1994: PetscFunctionReturn(PETSC_SUCCESS);
1995: }
1997: static PetscErrorCode MatCopy_MPIAIJ(Mat A, Mat B, MatStructure str)
1998: {
1999: Mat_MPIAIJ *a = (Mat_MPIAIJ *)A->data;
2000: Mat_MPIAIJ *b = (Mat_MPIAIJ *)B->data;
2002: PetscFunctionBegin;
2003: /* If the two matrices don't have the same copy implementation, they aren't compatible for fast copy. */
2004: if (str != SAME_NONZERO_PATTERN || A->ops->copy != B->ops->copy) {
2005: /* because of the column compression in the off-processor part of the matrix a->B,
2006: the number of columns in a->B and b->B may be different, hence we cannot call
2007: the MatCopy() directly on the two parts. If need be, we can provide a more
2008: efficient copy than the MatCopy_Basic() by first uncompressing the a->B matrices
2009: then copying the submatrices */
2010: PetscCall(MatCopy_Basic(A, B, str));
2011: } else {
2012: PetscCall(MatCopy(a->A, b->A, str));
2013: PetscCall(MatCopy(a->B, b->B, str));
2014: }
2015: PetscCall(PetscObjectStateIncrease((PetscObject)B));
2016: PetscFunctionReturn(PETSC_SUCCESS);
2017: }
2019: /*
2020: Computes the number of nonzeros per row needed for preallocation when X and Y
2021: have different nonzero structure.
2022: */
2023: 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)
2024: {
2025: PetscInt i, j, k, nzx, nzy;
2027: PetscFunctionBegin;
2028: /* Set the number of nonzeros in the new matrix */
2029: for (i = 0; i < m; i++) {
2030: const PetscInt *xjj = PetscSafePointerPlusOffset(xj, xi[i]), *yjj = PetscSafePointerPlusOffset(yj, yi[i]);
2031: nzx = xi[i + 1] - xi[i];
2032: nzy = yi[i + 1] - yi[i];
2033: nnz[i] = 0;
2034: for (j = 0, k = 0; j < nzx; j++) { /* Point in X */
2035: for (; k < nzy && yltog[yjj[k]] < xltog[xjj[j]]; k++) nnz[i]++; /* Catch up to X */
2036: if (k < nzy && yltog[yjj[k]] == xltog[xjj[j]]) k++; /* Skip duplicate */
2037: nnz[i]++;
2038: }
2039: for (; k < nzy; k++) nnz[i]++;
2040: }
2041: PetscFunctionReturn(PETSC_SUCCESS);
2042: }
2044: /* This is the same as MatAXPYGetPreallocation_SeqAIJ, except that the local-to-global map is provided */
2045: static PetscErrorCode MatAXPYGetPreallocation_MPIAIJ(Mat Y, const PetscInt *yltog, Mat X, const PetscInt *xltog, PetscInt *nnz)
2046: {
2047: PetscInt m = Y->rmap->N;
2048: Mat_SeqAIJ *x = (Mat_SeqAIJ *)X->data;
2049: Mat_SeqAIJ *y = (Mat_SeqAIJ *)Y->data;
2051: PetscFunctionBegin;
2052: PetscCall(MatAXPYGetPreallocation_MPIX_private(m, x->i, x->j, xltog, y->i, y->j, yltog, nnz));
2053: PetscFunctionReturn(PETSC_SUCCESS);
2054: }
2056: static PetscErrorCode MatAXPY_MPIAIJ(Mat Y, PetscScalar a, Mat X, MatStructure str)
2057: {
2058: Mat_MPIAIJ *xx = (Mat_MPIAIJ *)X->data, *yy = (Mat_MPIAIJ *)Y->data;
2060: PetscFunctionBegin;
2061: if (str == SAME_NONZERO_PATTERN) {
2062: PetscCall(MatAXPY(yy->A, a, xx->A, str));
2063: PetscCall(MatAXPY(yy->B, a, xx->B, str));
2064: } else if (str == SUBSET_NONZERO_PATTERN) { /* nonzeros of X is a subset of Y's */
2065: PetscCall(MatAXPY_Basic(Y, a, X, str));
2066: } else {
2067: Mat B;
2068: PetscInt *nnz_d, *nnz_o;
2069: PetscBool subset = PETSC_TRUE;
2070: Mat_SeqAIJ *ya = (Mat_SeqAIJ *)yy->A->data, *yb = (Mat_SeqAIJ *)yy->B->data;
2072: PetscCall(PetscMalloc1(yy->A->rmap->N, &nnz_d));
2073: PetscCall(PetscMalloc1(yy->B->rmap->N, &nnz_o));
2074: PetscCall(MatAXPYGetPreallocation_SeqAIJ(yy->A, xx->A, nnz_d));
2075: PetscCall(MatAXPYGetPreallocation_MPIAIJ(yy->B, yy->garray, xx->B, xx->garray, nnz_o));
2076: /* 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
2077: 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
2078: pattern of Y, and its nonzero state, unchanged. */
2079: 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]);
2080: PetscCallMPI(MPIU_Allreduce(MPI_IN_PLACE, &subset, 1, MPI_C_BOOL, MPI_LAND, PetscObjectComm((PetscObject)Y)));
2081: if (subset) PetscCall(MatAXPY_Basic(Y, a, X, SUBSET_NONZERO_PATTERN));
2082: else {
2083: PetscCall(MatCreate(PetscObjectComm((PetscObject)Y), &B));
2084: PetscCall(PetscObjectSetName((PetscObject)B, ((PetscObject)Y)->name));
2085: PetscCall(MatSetLayouts(B, Y->rmap, Y->cmap));
2086: PetscCall(MatSetType(B, ((PetscObject)Y)->type_name));
2087: PetscCall(MatMPIAIJSetPreallocation(B, 0, nnz_d, 0, nnz_o));
2088: PetscCall(MatAXPY_BasicWithPreallocation(B, Y, a, X, str));
2089: PetscCall(MatHeaderMerge(Y, &B));
2090: }
2091: PetscCall(PetscFree(nnz_d));
2092: PetscCall(PetscFree(nnz_o));
2093: }
2094: PetscFunctionReturn(PETSC_SUCCESS);
2095: }
2097: PETSC_INTERN PetscErrorCode MatConjugate_SeqAIJ(Mat);
2099: static PetscErrorCode MatConjugate_MPIAIJ(Mat mat)
2100: {
2101: Mat_MPIAIJ *aij = (Mat_MPIAIJ *)mat->data;
2103: PetscFunctionBegin;
2104: PetscCall(MatConjugate_SeqAIJ(aij->A));
2105: PetscCall(MatConjugate_SeqAIJ(aij->B));
2106: PetscFunctionReturn(PETSC_SUCCESS);
2107: }
2109: static PetscErrorCode MatRealPart_MPIAIJ(Mat A)
2110: {
2111: Mat_MPIAIJ *a = (Mat_MPIAIJ *)A->data;
2113: PetscFunctionBegin;
2114: PetscCall(MatRealPart(a->A));
2115: PetscCall(MatRealPart(a->B));
2116: PetscFunctionReturn(PETSC_SUCCESS);
2117: }
2119: static PetscErrorCode MatImaginaryPart_MPIAIJ(Mat A)
2120: {
2121: Mat_MPIAIJ *a = (Mat_MPIAIJ *)A->data;
2123: PetscFunctionBegin;
2124: PetscCall(MatImaginaryPart(a->A));
2125: PetscCall(MatImaginaryPart(a->B));
2126: PetscFunctionReturn(PETSC_SUCCESS);
2127: }
2129: static PetscErrorCode MatGetRowMaxAbs_MPIAIJ(Mat A, Vec v, PetscInt idx[])
2130: {
2131: Mat_MPIAIJ *a = (Mat_MPIAIJ *)A->data;
2132: PetscInt i, *idxb = NULL, m = A->rmap->n;
2133: PetscScalar *vv;
2134: Vec vB, vA;
2135: const PetscScalar *va, *vb;
2137: PetscFunctionBegin;
2138: PetscCall(MatCreateVecs(a->A, NULL, &vA));
2139: PetscCall(MatGetRowMaxAbs(a->A, vA, idx));
2141: PetscCall(VecGetArrayRead(vA, &va));
2142: if (idx) {
2143: for (i = 0; i < m; i++) {
2144: if (PetscAbsScalar(va[i])) idx[i] += A->cmap->rstart;
2145: }
2146: }
2148: PetscCall(MatCreateVecs(a->B, NULL, &vB));
2149: PetscCall(PetscMalloc1(m, &idxb));
2150: PetscCall(MatGetRowMaxAbs(a->B, vB, idxb));
2152: PetscCall(VecGetArrayWrite(v, &vv));
2153: PetscCall(VecGetArrayRead(vB, &vb));
2154: for (i = 0; i < m; i++) {
2155: if (PetscAbsScalar(va[i]) < PetscAbsScalar(vb[i])) {
2156: vv[i] = vb[i];
2157: if (idx) idx[i] = a->garray[idxb[i]];
2158: } else {
2159: vv[i] = va[i];
2160: if (idx && PetscAbsScalar(va[i]) == PetscAbsScalar(vb[i]) && idxb[i] != -1 && idx[i] > a->garray[idxb[i]]) idx[i] = a->garray[idxb[i]];
2161: }
2162: }
2163: PetscCall(VecRestoreArrayWrite(v, &vv));
2164: PetscCall(VecRestoreArrayRead(vA, &va));
2165: PetscCall(VecRestoreArrayRead(vB, &vb));
2166: PetscCall(PetscFree(idxb));
2167: PetscCall(VecDestroy(&vA));
2168: PetscCall(VecDestroy(&vB));
2169: PetscFunctionReturn(PETSC_SUCCESS);
2170: }
2172: static PetscErrorCode MatGetRowSumAbs_MPIAIJ(Mat A, Vec v)
2173: {
2174: Mat_MPIAIJ *a = (Mat_MPIAIJ *)A->data;
2175: Vec vB, vA;
2177: PetscFunctionBegin;
2178: PetscCall(MatCreateVecs(a->A, NULL, &vA));
2179: PetscCall(MatGetRowSumAbs(a->A, vA));
2180: PetscCall(MatCreateVecs(a->B, NULL, &vB));
2181: PetscCall(MatGetRowSumAbs(a->B, vB));
2182: PetscCall(VecAXPY(vA, 1.0, vB));
2183: PetscCall(VecDestroy(&vB));
2184: PetscCall(VecCopy(vA, v));
2185: PetscCall(VecDestroy(&vA));
2186: PetscFunctionReturn(PETSC_SUCCESS);
2187: }
2189: static PetscErrorCode MatGetRowMinAbs_MPIAIJ(Mat A, Vec v, PetscInt idx[])
2190: {
2191: Mat_MPIAIJ *mat = (Mat_MPIAIJ *)A->data;
2192: PetscInt m = A->rmap->n, n = A->cmap->n;
2193: PetscInt cstart = A->cmap->rstart, cend = A->cmap->rend;
2194: PetscInt *cmap = mat->garray;
2195: PetscInt *diagIdx, *offdiagIdx;
2196: Vec diagV, offdiagV;
2197: PetscScalar *a, *diagA, *offdiagA;
2198: const PetscScalar *ba, *bav;
2199: PetscInt r, j, col, ncols, *bi, *bj;
2200: Mat B = mat->B;
2201: Mat_SeqAIJ *b = (Mat_SeqAIJ *)B->data;
2203: PetscFunctionBegin;
2204: /* When a process holds entire A and other processes have no entry */
2205: if (A->cmap->N == n) {
2206: PetscCall(VecGetArrayWrite(v, &diagA));
2207: PetscCall(VecCreateSeqWithArray(PETSC_COMM_SELF, 1, m, diagA, &diagV));
2208: PetscCall(MatGetRowMinAbs(mat->A, diagV, idx));
2209: PetscCall(VecDestroy(&diagV));
2210: PetscCall(VecRestoreArrayWrite(v, &diagA));
2211: PetscFunctionReturn(PETSC_SUCCESS);
2212: } else if (n == 0) {
2213: if (m) {
2214: PetscCall(VecGetArrayWrite(v, &a));
2215: for (r = 0; r < m; r++) {
2216: a[r] = 0.0;
2217: if (idx) idx[r] = -1;
2218: }
2219: PetscCall(VecRestoreArrayWrite(v, &a));
2220: }
2221: PetscFunctionReturn(PETSC_SUCCESS);
2222: }
2224: PetscCall(PetscMalloc2(m, &diagIdx, m, &offdiagIdx));
2225: PetscCall(VecCreateSeq(PETSC_COMM_SELF, m, &diagV));
2226: PetscCall(VecCreateSeq(PETSC_COMM_SELF, m, &offdiagV));
2227: PetscCall(MatGetRowMinAbs(mat->A, diagV, diagIdx));
2229: /* Get offdiagIdx[] for implicit 0.0 */
2230: PetscCall(MatSeqAIJGetArrayRead(B, &bav));
2231: ba = bav;
2232: bi = b->i;
2233: bj = b->j;
2234: PetscCall(VecGetArrayWrite(offdiagV, &offdiagA));
2235: for (r = 0; r < m; r++) {
2236: ncols = bi[r + 1] - bi[r];
2237: if (ncols == A->cmap->N - n) { /* Brow is dense */
2238: offdiagA[r] = *ba;
2239: offdiagIdx[r] = cmap[0];
2240: } else { /* Brow is sparse so already KNOW maximum is 0.0 or higher */
2241: offdiagA[r] = 0.0;
2243: /* Find first hole in the cmap */
2244: for (j = 0; j < ncols; j++) {
2245: col = cmap[bj[j]]; /* global column number = cmap[B column number] */
2246: if (col > j && j < cstart) {
2247: offdiagIdx[r] = j; /* global column number of first implicit 0.0 */
2248: break;
2249: } else if (col > j + n && j >= cstart) {
2250: offdiagIdx[r] = j + n; /* global column number of first implicit 0.0 */
2251: break;
2252: }
2253: }
2254: if (j == ncols && ncols < A->cmap->N - n) {
2255: /* a hole is outside compressed Bcols */
2256: if (ncols == 0) {
2257: if (cstart) {
2258: offdiagIdx[r] = 0;
2259: } else offdiagIdx[r] = cend;
2260: } else { /* ncols > 0 */
2261: offdiagIdx[r] = cmap[ncols - 1] + 1;
2262: if (offdiagIdx[r] == cstart) offdiagIdx[r] += n;
2263: }
2264: }
2265: }
2267: for (j = 0; j < ncols; j++) {
2268: if (PetscAbsScalar(offdiagA[r]) > PetscAbsScalar(*ba)) {
2269: offdiagA[r] = *ba;
2270: offdiagIdx[r] = cmap[*bj];
2271: }
2272: ba++;
2273: bj++;
2274: }
2275: }
2277: PetscCall(VecGetArrayWrite(v, &a));
2278: PetscCall(VecGetArrayRead(diagV, (const PetscScalar **)&diagA));
2279: for (r = 0; r < m; ++r) {
2280: if (PetscAbsScalar(diagA[r]) < PetscAbsScalar(offdiagA[r])) {
2281: a[r] = diagA[r];
2282: if (idx) idx[r] = cstart + diagIdx[r];
2283: } else if (PetscAbsScalar(diagA[r]) == PetscAbsScalar(offdiagA[r])) {
2284: a[r] = diagA[r];
2285: if (idx) {
2286: if (cstart + diagIdx[r] <= offdiagIdx[r]) {
2287: idx[r] = cstart + diagIdx[r];
2288: } else idx[r] = offdiagIdx[r];
2289: }
2290: } else {
2291: a[r] = offdiagA[r];
2292: if (idx) idx[r] = offdiagIdx[r];
2293: }
2294: }
2295: PetscCall(MatSeqAIJRestoreArrayRead(B, &bav));
2296: PetscCall(VecRestoreArrayWrite(v, &a));
2297: PetscCall(VecRestoreArrayRead(diagV, (const PetscScalar **)&diagA));
2298: PetscCall(VecRestoreArrayWrite(offdiagV, &offdiagA));
2299: PetscCall(VecDestroy(&diagV));
2300: PetscCall(VecDestroy(&offdiagV));
2301: PetscCall(PetscFree2(diagIdx, offdiagIdx));
2302: PetscFunctionReturn(PETSC_SUCCESS);
2303: }
2305: static PetscErrorCode MatGetRowMin_MPIAIJ(Mat A, Vec v, PetscInt idx[])
2306: {
2307: Mat_MPIAIJ *mat = (Mat_MPIAIJ *)A->data;
2308: PetscInt m = A->rmap->n, n = A->cmap->n;
2309: PetscInt cstart = A->cmap->rstart, cend = A->cmap->rend;
2310: PetscInt *cmap = mat->garray;
2311: PetscInt *diagIdx, *offdiagIdx;
2312: Vec diagV, offdiagV;
2313: PetscScalar *a, *diagA, *offdiagA;
2314: const PetscScalar *ba, *bav;
2315: PetscInt r, j, col, ncols, *bi, *bj;
2316: Mat B = mat->B;
2317: Mat_SeqAIJ *b = (Mat_SeqAIJ *)B->data;
2319: PetscFunctionBegin;
2320: /* When a process holds entire A and other processes have no entry */
2321: if (A->cmap->N == n) {
2322: PetscCall(VecGetArrayWrite(v, &diagA));
2323: PetscCall(VecCreateSeqWithArray(PETSC_COMM_SELF, 1, m, diagA, &diagV));
2324: PetscCall(MatGetRowMin(mat->A, diagV, idx));
2325: PetscCall(VecDestroy(&diagV));
2326: PetscCall(VecRestoreArrayWrite(v, &diagA));
2327: PetscFunctionReturn(PETSC_SUCCESS);
2328: } else if (n == 0) {
2329: if (m) {
2330: PetscCall(VecGetArrayWrite(v, &a));
2331: for (r = 0; r < m; r++) {
2332: a[r] = PETSC_MAX_REAL;
2333: if (idx) idx[r] = -1;
2334: }
2335: PetscCall(VecRestoreArrayWrite(v, &a));
2336: }
2337: PetscFunctionReturn(PETSC_SUCCESS);
2338: }
2340: PetscCall(PetscCalloc2(m, &diagIdx, m, &offdiagIdx));
2341: PetscCall(VecCreateSeq(PETSC_COMM_SELF, m, &diagV));
2342: PetscCall(VecCreateSeq(PETSC_COMM_SELF, m, &offdiagV));
2343: PetscCall(MatGetRowMin(mat->A, diagV, diagIdx));
2345: /* Get offdiagIdx[] for implicit 0.0 */
2346: PetscCall(MatSeqAIJGetArrayRead(B, &bav));
2347: ba = bav;
2348: bi = b->i;
2349: bj = b->j;
2350: PetscCall(VecGetArrayWrite(offdiagV, &offdiagA));
2351: for (r = 0; r < m; r++) {
2352: ncols = bi[r + 1] - bi[r];
2353: if (ncols == A->cmap->N - n) { /* Brow is dense */
2354: offdiagA[r] = *ba;
2355: offdiagIdx[r] = cmap[0];
2356: } else { /* Brow is sparse so already KNOW maximum is 0.0 or higher */
2357: offdiagA[r] = 0.0;
2359: /* Find first hole in the cmap */
2360: for (j = 0; j < ncols; j++) {
2361: col = cmap[bj[j]]; /* global column number = cmap[B column number] */
2362: if (col > j && j < cstart) {
2363: offdiagIdx[r] = j; /* global column number of first implicit 0.0 */
2364: break;
2365: } else if (col > j + n && j >= cstart) {
2366: offdiagIdx[r] = j + n; /* global column number of first implicit 0.0 */
2367: break;
2368: }
2369: }
2370: if (j == ncols && ncols < A->cmap->N - n) {
2371: /* a hole is outside compressed Bcols */
2372: if (ncols == 0) {
2373: if (cstart) {
2374: offdiagIdx[r] = 0;
2375: } else offdiagIdx[r] = cend;
2376: } else { /* ncols > 0 */
2377: offdiagIdx[r] = cmap[ncols - 1] + 1;
2378: if (offdiagIdx[r] == cstart) offdiagIdx[r] += n;
2379: }
2380: }
2381: }
2383: for (j = 0; j < ncols; j++) {
2384: if (PetscRealPart(offdiagA[r]) > PetscRealPart(*ba)) {
2385: offdiagA[r] = *ba;
2386: offdiagIdx[r] = cmap[*bj];
2387: }
2388: ba++;
2389: bj++;
2390: }
2391: }
2393: PetscCall(VecGetArrayWrite(v, &a));
2394: PetscCall(VecGetArrayRead(diagV, (const PetscScalar **)&diagA));
2395: for (r = 0; r < m; ++r) {
2396: if (PetscRealPart(diagA[r]) < PetscRealPart(offdiagA[r])) {
2397: a[r] = diagA[r];
2398: if (idx) idx[r] = cstart + diagIdx[r];
2399: } else if (PetscRealPart(diagA[r]) == PetscRealPart(offdiagA[r])) {
2400: a[r] = diagA[r];
2401: if (idx) {
2402: if (cstart + diagIdx[r] <= offdiagIdx[r]) {
2403: idx[r] = cstart + diagIdx[r];
2404: } else idx[r] = offdiagIdx[r];
2405: }
2406: } else {
2407: a[r] = offdiagA[r];
2408: if (idx) idx[r] = offdiagIdx[r];
2409: }
2410: }
2411: PetscCall(MatSeqAIJRestoreArrayRead(B, &bav));
2412: PetscCall(VecRestoreArrayWrite(v, &a));
2413: PetscCall(VecRestoreArrayRead(diagV, (const PetscScalar **)&diagA));
2414: PetscCall(VecRestoreArrayWrite(offdiagV, &offdiagA));
2415: PetscCall(VecDestroy(&diagV));
2416: PetscCall(VecDestroy(&offdiagV));
2417: PetscCall(PetscFree2(diagIdx, offdiagIdx));
2418: PetscFunctionReturn(PETSC_SUCCESS);
2419: }
2421: static PetscErrorCode MatGetRowMax_MPIAIJ(Mat A, Vec v, PetscInt idx[])
2422: {
2423: Mat_MPIAIJ *mat = (Mat_MPIAIJ *)A->data;
2424: PetscInt m = A->rmap->n, n = A->cmap->n;
2425: PetscInt cstart = A->cmap->rstart, cend = A->cmap->rend;
2426: PetscInt *cmap = mat->garray;
2427: PetscInt *diagIdx, *offdiagIdx;
2428: Vec diagV, offdiagV;
2429: PetscScalar *a, *diagA, *offdiagA;
2430: const PetscScalar *ba, *bav;
2431: PetscInt r, j, col, ncols, *bi, *bj;
2432: Mat B = mat->B;
2433: Mat_SeqAIJ *b = (Mat_SeqAIJ *)B->data;
2435: PetscFunctionBegin;
2436: /* When a process holds entire A and other processes have no entry */
2437: if (A->cmap->N == n) {
2438: PetscCall(VecGetArrayWrite(v, &diagA));
2439: PetscCall(VecCreateSeqWithArray(PETSC_COMM_SELF, 1, m, diagA, &diagV));
2440: PetscCall(MatGetRowMax(mat->A, diagV, idx));
2441: PetscCall(VecDestroy(&diagV));
2442: PetscCall(VecRestoreArrayWrite(v, &diagA));
2443: PetscFunctionReturn(PETSC_SUCCESS);
2444: } else if (n == 0) {
2445: if (m) {
2446: PetscCall(VecGetArrayWrite(v, &a));
2447: for (r = 0; r < m; r++) {
2448: a[r] = PETSC_MIN_REAL;
2449: if (idx) idx[r] = -1;
2450: }
2451: PetscCall(VecRestoreArrayWrite(v, &a));
2452: }
2453: PetscFunctionReturn(PETSC_SUCCESS);
2454: }
2456: PetscCall(PetscMalloc2(m, &diagIdx, m, &offdiagIdx));
2457: PetscCall(VecCreateSeq(PETSC_COMM_SELF, m, &diagV));
2458: PetscCall(VecCreateSeq(PETSC_COMM_SELF, m, &offdiagV));
2459: PetscCall(MatGetRowMax(mat->A, diagV, diagIdx));
2461: /* Get offdiagIdx[] for implicit 0.0 */
2462: PetscCall(MatSeqAIJGetArrayRead(B, &bav));
2463: ba = bav;
2464: bi = b->i;
2465: bj = b->j;
2466: PetscCall(VecGetArrayWrite(offdiagV, &offdiagA));
2467: for (r = 0; r < m; r++) {
2468: ncols = bi[r + 1] - bi[r];
2469: if (ncols == A->cmap->N - n) { /* Brow is dense */
2470: offdiagA[r] = *ba;
2471: offdiagIdx[r] = cmap[0];
2472: } else { /* Brow is sparse so already KNOW maximum is 0.0 or higher */
2473: offdiagA[r] = 0.0;
2475: /* Find first hole in the cmap */
2476: for (j = 0; j < ncols; j++) {
2477: col = cmap[bj[j]]; /* global column number = cmap[B column number] */
2478: if (col > j && j < cstart) {
2479: offdiagIdx[r] = j; /* global column number of first implicit 0.0 */
2480: break;
2481: } else if (col > j + n && j >= cstart) {
2482: offdiagIdx[r] = j + n; /* global column number of first implicit 0.0 */
2483: break;
2484: }
2485: }
2486: if (j == ncols && ncols < A->cmap->N - n) {
2487: /* a hole is outside compressed Bcols */
2488: if (ncols == 0) {
2489: if (cstart) {
2490: offdiagIdx[r] = 0;
2491: } else offdiagIdx[r] = cend;
2492: } else { /* ncols > 0 */
2493: offdiagIdx[r] = cmap[ncols - 1] + 1;
2494: if (offdiagIdx[r] == cstart) offdiagIdx[r] += n;
2495: }
2496: }
2497: }
2499: for (j = 0; j < ncols; j++) {
2500: if (PetscRealPart(offdiagA[r]) < PetscRealPart(*ba)) {
2501: offdiagA[r] = *ba;
2502: offdiagIdx[r] = cmap[*bj];
2503: }
2504: ba++;
2505: bj++;
2506: }
2507: }
2509: PetscCall(VecGetArrayWrite(v, &a));
2510: PetscCall(VecGetArrayRead(diagV, (const PetscScalar **)&diagA));
2511: for (r = 0; r < m; ++r) {
2512: if (PetscRealPart(diagA[r]) > PetscRealPart(offdiagA[r])) {
2513: a[r] = diagA[r];
2514: if (idx) idx[r] = cstart + diagIdx[r];
2515: } else if (PetscRealPart(diagA[r]) == PetscRealPart(offdiagA[r])) {
2516: a[r] = diagA[r];
2517: if (idx) {
2518: if (cstart + diagIdx[r] <= offdiagIdx[r]) {
2519: idx[r] = cstart + diagIdx[r];
2520: } else idx[r] = offdiagIdx[r];
2521: }
2522: } else {
2523: a[r] = offdiagA[r];
2524: if (idx) idx[r] = offdiagIdx[r];
2525: }
2526: }
2527: PetscCall(MatSeqAIJRestoreArrayRead(B, &bav));
2528: PetscCall(VecRestoreArrayWrite(v, &a));
2529: PetscCall(VecRestoreArrayRead(diagV, (const PetscScalar **)&diagA));
2530: PetscCall(VecRestoreArrayWrite(offdiagV, &offdiagA));
2531: PetscCall(VecDestroy(&diagV));
2532: PetscCall(VecDestroy(&offdiagV));
2533: PetscCall(PetscFree2(diagIdx, offdiagIdx));
2534: PetscFunctionReturn(PETSC_SUCCESS);
2535: }
2537: PetscErrorCode MatGetSeqNonzeroStructure_MPIAIJ(Mat mat, Mat *newmat)
2538: {
2539: Mat *dummy;
2541: PetscFunctionBegin;
2542: PetscCall(MatCreateSubMatrix_MPIAIJ_All(mat, MAT_DO_NOT_GET_VALUES, MAT_INITIAL_MATRIX, &dummy));
2543: *newmat = *dummy;
2544: PetscCall(PetscFree(dummy));
2545: PetscFunctionReturn(PETSC_SUCCESS);
2546: }
2548: static PetscErrorCode MatInvertBlockDiagonal_MPIAIJ(Mat A, const PetscScalar **values)
2549: {
2550: Mat_MPIAIJ *a = (Mat_MPIAIJ *)A->data;
2552: PetscFunctionBegin;
2553: PetscCall(MatInvertBlockDiagonal(a->A, values));
2554: A->factorerrortype = a->A->factorerrortype;
2555: PetscFunctionReturn(PETSC_SUCCESS);
2556: }
2558: static PetscErrorCode MatSetRandom_MPIAIJ(Mat x, PetscRandom rctx)
2559: {
2560: Mat_MPIAIJ *aij = (Mat_MPIAIJ *)x->data;
2561: PetscBool nooffprocentries = x->nooffprocentries;
2563: PetscFunctionBegin;
2564: PetscCheck(x->assembled || x->preallocated, PetscObjectComm((PetscObject)x), PETSC_ERR_ARG_WRONGSTATE, "MatSetRandom() on an unassembled and unpreallocated MATMPIAIJ is not allowed");
2565: PetscCall(MatSetRandom(aij->A, rctx));
2566: if (x->assembled) PetscCall(MatSetRandom(aij->B, rctx));
2567: else PetscCall(MatSetRandomSkipColumnRange_SeqAIJ_Private(aij->B, x->cmap->rstart, x->cmap->rend, rctx));
2568: PetscCall(MatSetOption(x, MAT_NO_OFF_PROC_ENTRIES, PETSC_TRUE));
2569: PetscCall(MatAssemblyBegin(x, MAT_FINAL_ASSEMBLY));
2570: PetscCall(MatAssemblyEnd(x, MAT_FINAL_ASSEMBLY));
2571: PetscCall(MatSetOption(x, MAT_NO_OFF_PROC_ENTRIES, nooffprocentries));
2572: PetscFunctionReturn(PETSC_SUCCESS);
2573: }
2575: static PetscErrorCode MatMPIAIJSetUseScalableIncreaseOverlap_MPIAIJ(Mat A, PetscBool sc)
2576: {
2577: PetscFunctionBegin;
2578: if (sc) A->ops->increaseoverlap = MatIncreaseOverlap_MPIAIJ_Scalable;
2579: else A->ops->increaseoverlap = MatIncreaseOverlap_MPIAIJ;
2580: PetscFunctionReturn(PETSC_SUCCESS);
2581: }
2583: /*@
2584: MatMPIAIJGetNumberNonzeros - gets the number of nonzeros in the matrix on this MPI rank
2586: Not Collective
2588: Input Parameter:
2589: . A - the matrix
2591: Output Parameter:
2592: . nz - the number of nonzeros
2594: Level: advanced
2596: .seealso: [](ch_matrices), `Mat`, `MATMPIAIJ`
2597: @*/
2598: PetscErrorCode MatMPIAIJGetNumberNonzeros(Mat A, PetscCount *nz)
2599: {
2600: Mat_MPIAIJ *maij = (Mat_MPIAIJ *)A->data;
2601: Mat_SeqAIJ *aaij = (Mat_SeqAIJ *)maij->A->data, *baij = (Mat_SeqAIJ *)maij->B->data;
2602: PetscBool isaij;
2604: PetscFunctionBegin;
2605: PetscCall(PetscObjectBaseTypeCompare((PetscObject)A, MATMPIAIJ, &isaij));
2606: PetscCheck(isaij, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "Not for type %s", ((PetscObject)A)->type_name);
2607: *nz = aaij->i[A->rmap->n] + baij->i[A->rmap->n];
2608: PetscFunctionReturn(PETSC_SUCCESS);
2609: }
2611: /*@
2612: MatMPIAIJSetUseScalableIncreaseOverlap - Determine if the matrix uses a scalable algorithm to compute the overlap
2614: Collective
2616: Input Parameters:
2617: + A - the matrix
2618: - sc - `PETSC_TRUE` indicates use the scalable algorithm (default is not to use the scalable algorithm)
2620: Level: advanced
2622: .seealso: [](ch_matrices), `Mat`, `MATMPIAIJ`
2623: @*/
2624: PetscErrorCode MatMPIAIJSetUseScalableIncreaseOverlap(Mat A, PetscBool sc)
2625: {
2626: PetscFunctionBegin;
2627: PetscTryMethod(A, "MatMPIAIJSetUseScalableIncreaseOverlap_C", (Mat, PetscBool), (A, sc));
2628: PetscFunctionReturn(PETSC_SUCCESS);
2629: }
2631: PetscErrorCode MatSetFromOptions_MPIAIJ(Mat A, PetscOptionItems PetscOptionsObject)
2632: {
2633: PetscBool sc = PETSC_FALSE, flg;
2635: PetscFunctionBegin;
2636: PetscOptionsHeadBegin(PetscOptionsObject, "MPIAIJ options");
2637: if (A->ops->increaseoverlap == MatIncreaseOverlap_MPIAIJ_Scalable) sc = PETSC_TRUE;
2638: PetscCall(PetscOptionsBool("-mat_increase_overlap_scalable", "Use a scalable algorithm to compute the overlap", "MatIncreaseOverlap", sc, &sc, &flg));
2639: if (flg) PetscCall(MatMPIAIJSetUseScalableIncreaseOverlap(A, sc));
2640: PetscOptionsHeadEnd();
2641: PetscFunctionReturn(PETSC_SUCCESS);
2642: }
2644: static PetscErrorCode MatShift_MPIAIJ(Mat Y, PetscScalar a)
2645: {
2646: Mat_MPIAIJ *maij = (Mat_MPIAIJ *)Y->data;
2647: Mat_SeqAIJ *aij = (Mat_SeqAIJ *)maij->A->data;
2649: PetscFunctionBegin;
2650: if (!Y->preallocated) {
2651: PetscCall(MatMPIAIJSetPreallocation(Y, 1, NULL, 0, NULL));
2652: } else if (!aij->nz && PetscMax(Y->rmap->rstart, Y->cmap->rstart) < PetscMin(Y->rmap->rend, Y->cmap->rend)) {
2653: /* If maij->A has no nonzeros, preallocate it again only if one of the local rows has its diagonal entry in maij->A, otherwise
2654: its nonzero state would increase even though the shift creates no new nonzeros in it */
2655: PetscInt nonew = aij->nonew;
2656: PetscCall(MatSeqAIJSetPreallocation(maij->A, 1, NULL));
2657: aij->nonew = nonew;
2658: }
2659: PetscCall(MatShift_Basic(Y, a));
2660: PetscFunctionReturn(PETSC_SUCCESS);
2661: }
2663: static PetscErrorCode MatInvertVariableBlockDiagonal_MPIAIJ(Mat A, PetscInt nblocks, const PetscInt *bsizes, PetscScalar *diag)
2664: {
2665: Mat_MPIAIJ *a = (Mat_MPIAIJ *)A->data;
2667: PetscFunctionBegin;
2668: PetscCall(MatInvertVariableBlockDiagonal(a->A, nblocks, bsizes, diag));
2669: PetscFunctionReturn(PETSC_SUCCESS);
2670: }
2672: static PetscErrorCode MatEliminateZeros_MPIAIJ(Mat A, PetscBool keep)
2673: {
2674: Mat_MPIAIJ *a = (Mat_MPIAIJ *)A->data;
2676: PetscFunctionBegin;
2677: PetscCall(MatEliminateZeros_SeqAIJ(a->A, keep)); // possibly keep zero diagonal coefficients
2678: PetscCall(MatEliminateZeros_SeqAIJ(a->B, PETSC_FALSE)); // never keep zero diagonal coefficients
2679: PetscFunctionReturn(PETSC_SUCCESS);
2680: }
2682: static PetscErrorCode MatGetOrdering_MPIAIJ(Mat A, MatOrderingType type, IS *rperm, IS *cperm)
2683: {
2684: Mat_MPIAIJ *a = (Mat_MPIAIJ *)A->data;
2685: IS lrowperm, lcolperm;
2686: PetscInt i, rstart, rend, *idx;
2687: const PetscInt *lidx;
2689: PetscFunctionBegin;
2690: PetscCall(MatGetOrdering(a->A, type, &lrowperm, &lcolperm));
2691: PetscCall(MatGetOwnershipRange(A, &rstart, &rend));
2692: /* Remap row index set to global space */
2693: PetscCall(ISGetIndices(lrowperm, &lidx));
2694: PetscCall(PetscMalloc1(rend - rstart, &idx));
2695: for (i = 0; i + rstart < rend; i++) idx[i] = rstart + lidx[i];
2696: PetscCall(ISRestoreIndices(lrowperm, &lidx));
2697: PetscCall(ISDestroy(&lrowperm));
2698: PetscCall(ISCreateGeneral(PetscObjectComm((PetscObject)A), rend - rstart, idx, PETSC_OWN_POINTER, rperm));
2699: PetscCall(ISSetPermutation(*rperm));
2700: /* Remap column index set to global space */
2701: PetscCall(ISGetIndices(lcolperm, &lidx));
2702: PetscCall(PetscMalloc1(rend - rstart, &idx));
2703: for (i = 0; i + rstart < rend; i++) idx[i] = rstart + lidx[i];
2704: PetscCall(ISRestoreIndices(lcolperm, &lidx));
2705: PetscCall(ISDestroy(&lcolperm));
2706: PetscCall(ISCreateGeneral(PetscObjectComm((PetscObject)A), rend - rstart, idx, PETSC_OWN_POINTER, cperm));
2707: PetscCall(ISSetPermutation(*cperm));
2708: PetscFunctionReturn(PETSC_SUCCESS);
2709: }
2711: static struct _MatOps MatOps_Values = {MatSetValues_MPIAIJ,
2712: MatGetRow_MPIAIJ,
2713: MatRestoreRow_MPIAIJ,
2714: MatMult_MPIAIJ,
2715: /* 4*/ MatMultAdd_MPIAIJ,
2716: MatMultTranspose_MPIAIJ,
2717: MatMultTransposeAdd_MPIAIJ,
2718: NULL,
2719: NULL,
2720: NULL,
2721: /*10*/ NULL,
2722: NULL,
2723: NULL,
2724: MatSOR_MPIAIJ,
2725: MatTranspose_MPIAIJ,
2726: /*15*/ MatGetInfo_MPIAIJ,
2727: MatEqual_MPIAIJ,
2728: MatGetDiagonal_MPIAIJ,
2729: MatDiagonalScale_MPIAIJ,
2730: MatNorm_MPIAIJ,
2731: /*20*/ MatAssemblyBegin_MPIAIJ,
2732: MatAssemblyEnd_MPIAIJ,
2733: MatSetOption_MPIAIJ,
2734: MatZeroEntries_MPIAIJ,
2735: /*24*/ MatZeroRows_MPIAIJ,
2736: NULL,
2737: NULL,
2738: NULL,
2739: NULL,
2740: /*29*/ MatSetUp_MPI_Hash,
2741: NULL,
2742: NULL,
2743: MatGetDiagonalBlock_MPIAIJ,
2744: NULL,
2745: /*34*/ MatDuplicate_MPIAIJ,
2746: NULL,
2747: NULL,
2748: NULL,
2749: NULL,
2750: /*39*/ MatAXPY_MPIAIJ,
2751: MatCreateSubMatrices_MPIAIJ,
2752: MatIncreaseOverlap_MPIAIJ,
2753: MatGetValues_MPIAIJ,
2754: MatCopy_MPIAIJ,
2755: /*44*/ MatGetRowMax_MPIAIJ,
2756: MatScale_MPIAIJ,
2757: MatShift_MPIAIJ,
2758: MatDiagonalSet_MPIAIJ,
2759: MatZeroRowsColumns_MPIAIJ,
2760: /*49*/ MatSetRandom_MPIAIJ,
2761: MatGetRowIJ_MPIAIJ,
2762: MatRestoreRowIJ_MPIAIJ,
2763: NULL,
2764: NULL,
2765: /*54*/ MatFDColoringCreate_MPIXAIJ,
2766: NULL,
2767: MatSetUnfactored_MPIAIJ,
2768: MatPermute_MPIAIJ,
2769: NULL,
2770: /*59*/ MatCreateSubMatrix_MPIAIJ,
2771: MatDestroy_MPIAIJ,
2772: MatView_MPIAIJ,
2773: NULL,
2774: NULL,
2775: /*64*/ MatMatMatMultNumeric_MPIAIJ_MPIAIJ_MPIAIJ,
2776: NULL,
2777: NULL,
2778: NULL,
2779: MatGetRowMaxAbs_MPIAIJ,
2780: /*69*/ MatGetRowMinAbs_MPIAIJ,
2781: NULL,
2782: NULL,
2783: MatFDColoringApply_AIJ,
2784: MatSetFromOptions_MPIAIJ,
2785: MatFindZeroDiagonals_MPIAIJ,
2786: /*75*/ NULL,
2787: NULL,
2788: NULL,
2789: MatLoad_MPIAIJ,
2790: NULL,
2791: /*80*/ NULL,
2792: NULL,
2793: NULL,
2794: /*83*/ NULL,
2795: NULL,
2796: MatMatMultNumeric_MPIAIJ_MPIAIJ,
2797: MatPtAPNumeric_MPIAIJ_MPIAIJ,
2798: NULL,
2799: NULL,
2800: /*89*/ MatBindToCPU_MPIAIJ,
2801: MatProductSetFromOptions_MPIAIJ,
2802: NULL,
2803: NULL,
2804: MatConjugate_MPIAIJ,
2805: /*94*/ NULL,
2806: MatSetValuesRow_MPIAIJ,
2807: MatRealPart_MPIAIJ,
2808: MatImaginaryPart_MPIAIJ,
2809: NULL,
2810: /*99*/ NULL,
2811: NULL,
2812: NULL,
2813: MatGetRowMin_MPIAIJ,
2814: NULL,
2815: /*104*/ MatGetSeqNonzeroStructure_MPIAIJ,
2816: NULL,
2817: MatGetGhosts_MPIAIJ,
2818: NULL,
2819: NULL,
2820: /*109*/ MatMultDiagonalBlock_MPIAIJ,
2821: NULL,
2822: NULL,
2823: NULL,
2824: MatGetMultiProcBlock_MPIAIJ,
2825: /*114*/ MatFindNonzeroRows_MPIAIJ,
2826: MatGetColumnReductions_MPIAIJ,
2827: MatInvertBlockDiagonal_MPIAIJ,
2828: MatInvertVariableBlockDiagonal_MPIAIJ,
2829: MatCreateSubMatricesMPI_MPIAIJ,
2830: /*119*/ NULL,
2831: MatTransposeMatMultNumeric_MPIAIJ_MPIAIJ,
2832: NULL,
2833: NULL,
2834: NULL,
2835: /*124*/ NULL,
2836: MatSetBlockSizes_MPIAIJ,
2837: NULL,
2838: MatFDColoringSetUp_MPIXAIJ,
2839: MatFindOffBlockDiagonalEntries_MPIAIJ,
2840: /*129*/ MatCreateMPIMatConcatenateSeqMat_MPIAIJ,
2841: NULL,
2842: NULL,
2843: NULL,
2844: MatCreateGraph_Simple_AIJ,
2845: /*134*/ NULL,
2846: MatEliminateZeros_MPIAIJ,
2847: MatGetRowSumAbs_MPIAIJ,
2848: NULL,
2849: NULL,
2850: /*139*/ NULL,
2851: MatCopyHashToXAIJ_MPI_Hash,
2852: MatGetCurrentMemType_MPIAIJ,
2853: NULL,
2854: NULL,
2855: /*144*/ NULL,
2856: NULL,
2857: NULL,
2858: MatGetOrdering_MPIAIJ};
2860: static PetscErrorCode MatStoreValues_MPIAIJ(Mat mat)
2861: {
2862: Mat_MPIAIJ *aij = (Mat_MPIAIJ *)mat->data;
2864: PetscFunctionBegin;
2865: PetscCall(MatStoreValues(aij->A));
2866: PetscCall(MatStoreValues(aij->B));
2867: PetscFunctionReturn(PETSC_SUCCESS);
2868: }
2870: static PetscErrorCode MatRetrieveValues_MPIAIJ(Mat mat)
2871: {
2872: Mat_MPIAIJ *aij = (Mat_MPIAIJ *)mat->data;
2874: PetscFunctionBegin;
2875: PetscCall(MatRetrieveValues(aij->A));
2876: PetscCall(MatRetrieveValues(aij->B));
2877: PetscFunctionReturn(PETSC_SUCCESS);
2878: }
2880: PetscErrorCode MatMPIAIJSetPreallocation_MPIAIJ(Mat B, PetscInt d_nz, const PetscInt d_nnz[], PetscInt o_nz, const PetscInt o_nnz[])
2881: {
2882: Mat_MPIAIJ *b = (Mat_MPIAIJ *)B->data;
2883: PetscMPIInt size;
2885: PetscFunctionBegin;
2886: if (B->hash_active) {
2887: B->ops[0] = b->cops;
2888: B->hash_active = PETSC_FALSE;
2889: }
2890: PetscCall(PetscLayoutSetUp(B->rmap));
2891: PetscCall(PetscLayoutSetUp(B->cmap));
2893: #if PetscDefined(USE_CTABLE)
2894: PetscCall(PetscHMapIDestroy(&b->colmap));
2895: #else
2896: PetscCall(PetscFree(b->colmap));
2897: #endif
2898: PetscCall(PetscFree(b->garray));
2899: PetscCall(VecDestroy(&b->lvec));
2900: PetscCall(VecScatterDestroy(&b->Mvctx));
2902: PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)B), &size));
2904: MatSeqXAIJGetOptions_Private(b->B);
2905: PetscCall(MatDestroy(&b->B));
2906: PetscCall(MatCreate(PETSC_COMM_SELF, &b->B));
2907: PetscCall(MatSetSizes(b->B, B->rmap->n, size > 1 ? B->cmap->N : 0, B->rmap->n, size > 1 ? B->cmap->N : 0));
2908: PetscCall(MatSetBlockSizesFromMats(b->B, B, B));
2909: PetscCall(MatSetType(b->B, MATSEQAIJ));
2910: MatSeqXAIJRestoreOptions_Private(b->B);
2911: PetscCall(MatSetOption(b->B, MAT_STRUCTURE_ONLY, B->structure_only));
2913: MatSeqXAIJGetOptions_Private(b->A);
2914: PetscCall(MatDestroy(&b->A));
2915: PetscCall(MatCreate(PETSC_COMM_SELF, &b->A));
2916: PetscCall(MatSetSizes(b->A, B->rmap->n, B->cmap->n, B->rmap->n, B->cmap->n));
2917: PetscCall(MatSetBlockSizesFromMats(b->A, B, B));
2918: PetscCall(MatSetType(b->A, MATSEQAIJ));
2919: MatSeqXAIJRestoreOptions_Private(b->A);
2920: PetscCall(MatSetOption(b->A, MAT_STRUCTURE_ONLY, B->structure_only));
2922: PetscCall(MatSeqAIJSetPreallocation(b->A, d_nz, d_nnz));
2923: PetscCall(MatSeqAIJSetPreallocation(b->B, o_nz, o_nnz));
2924: B->preallocated = PETSC_TRUE;
2925: B->was_assembled = PETSC_FALSE;
2926: B->assembled = PETSC_FALSE;
2927: PetscFunctionReturn(PETSC_SUCCESS);
2928: }
2930: static PetscErrorCode MatResetPreallocation_MPIAIJ(Mat B)
2931: {
2932: Mat_MPIAIJ *b = (Mat_MPIAIJ *)B->data;
2933: PetscBool ondiagreset, offdiagreset, memoryreset;
2935: PetscFunctionBegin;
2937: 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()");
2938: if (B->num_ass == 0) PetscFunctionReturn(PETSC_SUCCESS);
2940: PetscCall(MatResetPreallocation_SeqAIJ_Private(b->A, &ondiagreset));
2941: PetscCall(MatResetPreallocation_SeqAIJ_Private(b->B, &offdiagreset));
2942: memoryreset = (PetscBool)(ondiagreset || offdiagreset);
2943: PetscCallMPI(MPIU_Allreduce(MPI_IN_PLACE, &memoryreset, 1, MPI_C_BOOL, MPI_LOR, PetscObjectComm((PetscObject)B)));
2944: if (!memoryreset) PetscFunctionReturn(PETSC_SUCCESS);
2946: PetscCall(PetscLayoutSetUp(B->rmap));
2947: PetscCall(PetscLayoutSetUp(B->cmap));
2948: 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");
2949: PetscCall(MatDisAssemble_MPIAIJ(B, PETSC_TRUE));
2950: PetscCall(VecScatterDestroy(&b->Mvctx));
2952: B->preallocated = PETSC_TRUE;
2953: B->was_assembled = PETSC_FALSE;
2954: B->assembled = PETSC_FALSE;
2955: /* Log that the state of this object has changed; this will help guarantee that preconditioners get re-setup */
2956: PetscCall(PetscObjectStateIncrease((PetscObject)B));
2957: PetscFunctionReturn(PETSC_SUCCESS);
2958: }
2960: PetscErrorCode MatDuplicate_MPIAIJ(Mat matin, MatDuplicateOption cpvalues, Mat *newmat)
2961: {
2962: Mat mat;
2963: Mat_MPIAIJ *a, *oldmat = (Mat_MPIAIJ *)matin->data;
2965: PetscFunctionBegin;
2966: *newmat = NULL;
2967: PetscCall(MatCreate(PetscObjectComm((PetscObject)matin), &mat));
2968: PetscCall(MatSetSizes(mat, matin->rmap->n, matin->cmap->n, matin->rmap->N, matin->cmap->N));
2969: PetscCall(MatSetBlockSizesFromMats(mat, matin, matin));
2970: PetscCall(MatSetType(mat, ((PetscObject)matin)->type_name));
2971: PetscCall(MatSetOption(mat, MAT_STRUCTURE_ONLY, matin->structure_only));
2972: a = (Mat_MPIAIJ *)mat->data;
2974: mat->factortype = matin->factortype;
2975: mat->assembled = matin->assembled;
2976: mat->insertmode = NOT_SET_VALUES;
2978: a->size = oldmat->size;
2979: a->rank = oldmat->rank;
2980: a->donotstash = oldmat->donotstash;
2981: a->roworiented = oldmat->roworiented;
2982: a->rowindices = NULL;
2983: a->rowvalues = NULL;
2984: a->getrowactive = PETSC_FALSE;
2986: PetscCall(PetscLayoutReference(matin->rmap, &mat->rmap));
2987: PetscCall(PetscLayoutReference(matin->cmap, &mat->cmap));
2988: if (matin->hash_active) PetscCall(MatSetUp(mat));
2989: else {
2990: mat->preallocated = matin->preallocated;
2991: if (oldmat->colmap) {
2992: #if PetscDefined(USE_CTABLE)
2993: PetscCall(PetscHMapIDuplicate(oldmat->colmap, &a->colmap));
2994: #else
2995: PetscCall(PetscMalloc1(mat->cmap->N, &a->colmap));
2996: PetscCall(PetscArraycpy(a->colmap, oldmat->colmap, mat->cmap->N));
2997: #endif
2998: } else a->colmap = NULL;
2999: if (oldmat->garray) {
3000: PetscInt len;
3001: len = oldmat->B->cmap->n;
3002: PetscCall(PetscMalloc1(len, &a->garray));
3003: if (len) PetscCall(PetscArraycpy(a->garray, oldmat->garray, len));
3004: } else a->garray = NULL;
3006: /* It may happen MatDuplicate is called with a non-assembled matrix
3007: In fact, MatDuplicate only requires the matrix to be preallocated
3008: This may happen inside a DMCreateMatrix_Shell */
3009: if (oldmat->lvec) PetscCall(VecDuplicate(oldmat->lvec, &a->lvec));
3010: if (oldmat->Mvctx) {
3011: a->Mvctx = oldmat->Mvctx;
3012: PetscCall(PetscObjectReference((PetscObject)oldmat->Mvctx));
3013: }
3014: PetscCall(MatDuplicate(oldmat->A, cpvalues, &a->A));
3015: PetscCall(MatDuplicate(oldmat->B, cpvalues, &a->B));
3016: }
3017: PetscCall(PetscFunctionListDuplicate(((PetscObject)matin)->qlist, &((PetscObject)mat)->qlist));
3018: *newmat = mat;
3019: PetscFunctionReturn(PETSC_SUCCESS);
3020: }
3022: PetscErrorCode MatLoad_MPIAIJ(Mat newMat, PetscViewer viewer)
3023: {
3024: PetscBool isbinary, ishdf5;
3026: PetscFunctionBegin;
3029: /* force binary viewer to load .info file if it has not yet done so */
3030: PetscCall(PetscViewerSetUp(viewer));
3031: PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERBINARY, &isbinary));
3032: PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERHDF5, &ishdf5));
3033: if (isbinary) {
3034: PetscCall(MatLoad_MPIAIJ_Binary(newMat, viewer));
3035: } else if (ishdf5) {
3036: #if PetscDefined(HAVE_HDF5)
3037: PetscCall(MatLoad_AIJ_HDF5(newMat, viewer));
3038: #else
3039: SETERRQ(PetscObjectComm((PetscObject)newMat), PETSC_ERR_SUP, "HDF5 not supported in this build.\nPlease reconfigure using --download-hdf5");
3040: #endif
3041: } else {
3042: 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);
3043: }
3044: PetscFunctionReturn(PETSC_SUCCESS);
3045: }
3047: PetscErrorCode MatLoad_MPIAIJ_Binary(Mat mat, PetscViewer viewer)
3048: {
3049: PetscInt header[4], M, N, m, nz, rows, cols, sum, i;
3050: PetscInt *rowidxs, *colidxs;
3051: PetscScalar *matvals;
3053: PetscFunctionBegin;
3054: PetscCall(PetscViewerSetUp(viewer));
3056: /* read in matrix header */
3057: PetscCall(PetscViewerBinaryRead(viewer, header, 4, NULL, PETSC_INT));
3058: PetscCheck(header[0] == MAT_FILE_CLASSID, PetscObjectComm((PetscObject)viewer), PETSC_ERR_FILE_UNEXPECTED, "Not a matrix object in file");
3059: M = header[1];
3060: N = header[2];
3061: nz = header[3];
3062: PetscCheck(M >= 0, PetscObjectComm((PetscObject)viewer), PETSC_ERR_FILE_UNEXPECTED, "Matrix row size (%" PetscInt_FMT ") in file is negative", M);
3063: PetscCheck(N >= 0, PetscObjectComm((PetscObject)viewer), PETSC_ERR_FILE_UNEXPECTED, "Matrix column size (%" PetscInt_FMT ") in file is negative", N);
3064: PetscCheck(nz >= 0, PETSC_COMM_SELF, PETSC_ERR_FILE_UNEXPECTED, "Matrix stored in special format on disk, cannot load as MPIAIJ");
3066: /* set block sizes from the viewer's .info file */
3067: PetscCall(MatLoad_Binary_BlockSizes(mat, viewer));
3068: /* set global sizes if not set already */
3069: if (mat->rmap->N < 0) mat->rmap->N = M;
3070: if (mat->cmap->N < 0) mat->cmap->N = N;
3071: PetscCall(PetscLayoutSetUp(mat->rmap));
3072: PetscCall(PetscLayoutSetUp(mat->cmap));
3074: /* check if the matrix sizes are correct */
3075: PetscCall(MatGetSize(mat, &rows, &cols));
3076: 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);
3078: /* read in row lengths and build row indices */
3079: PetscCall(MatGetLocalSize(mat, &m, NULL));
3080: PetscCall(PetscMalloc1(m + 1, &rowidxs));
3081: PetscCall(PetscViewerBinaryReadAll(viewer, rowidxs + 1, m, PETSC_DECIDE, M, PETSC_INT));
3082: rowidxs[0] = 0;
3083: for (i = 0; i < m; i++) rowidxs[i + 1] += rowidxs[i];
3084: if (nz != PETSC_INT_MAX) {
3085: PetscCallMPI(MPIU_Allreduce(&rowidxs[m], &sum, 1, MPIU_INT, MPI_SUM, PetscObjectComm((PetscObject)viewer)));
3086: 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);
3087: }
3089: /* read in column indices and matrix values */
3090: PetscCall(PetscMalloc2(rowidxs[m], &colidxs, rowidxs[m], &matvals));
3091: PetscCall(PetscViewerBinaryReadAll(viewer, colidxs, rowidxs[m], PETSC_DETERMINE, PETSC_DETERMINE, PETSC_INT));
3092: PetscCall(PetscViewerBinaryReadAll(viewer, matvals, rowidxs[m], PETSC_DETERMINE, PETSC_DETERMINE, PETSC_SCALAR));
3093: /* store matrix indices and values */
3094: PetscCall(MatMPIAIJSetPreallocationCSR(mat, rowidxs, colidxs, matvals));
3095: PetscCall(PetscFree(rowidxs));
3096: PetscCall(PetscFree2(colidxs, matvals));
3097: PetscFunctionReturn(PETSC_SUCCESS);
3098: }
3100: /* Not scalable because of ISAllGather() unless getting all columns. */
3101: static PetscErrorCode ISGetSeqIS_Private(Mat mat, IS iscol, IS *isseq)
3102: {
3103: IS iscol_local;
3104: PetscBool isstride;
3105: PetscMPIInt gisstride = 0;
3107: PetscFunctionBegin;
3108: /* check if we are grabbing all columns*/
3109: PetscCall(PetscObjectTypeCompare((PetscObject)iscol, ISSTRIDE, &isstride));
3111: if (isstride) {
3112: PetscInt start, len, mstart, mlen;
3113: PetscCall(ISStrideGetInfo(iscol, &start, NULL));
3114: PetscCall(ISGetLocalSize(iscol, &len));
3115: PetscCall(MatGetOwnershipRangeColumn(mat, &mstart, &mlen));
3116: if (mstart == start && mlen - mstart == len) gisstride = 1;
3117: }
3119: PetscCallMPI(MPIU_Allreduce(MPI_IN_PLACE, &gisstride, 1, MPI_INT, MPI_MIN, PetscObjectComm((PetscObject)mat)));
3120: if (gisstride) {
3121: PetscInt N;
3122: PetscCall(MatGetSize(mat, NULL, &N));
3123: PetscCall(ISCreateStride(PETSC_COMM_SELF, N, 0, 1, &iscol_local));
3124: PetscCall(ISSetIdentity(iscol_local));
3125: PetscCall(PetscInfo(mat, "Optimizing for obtaining all columns of the matrix; skipping ISAllGather()\n"));
3126: } else {
3127: PetscInt cbs;
3128: PetscCall(ISGetBlockSize(iscol, &cbs));
3129: PetscCall(ISAllGather(iscol, &iscol_local));
3130: PetscCall(ISSetBlockSize(iscol_local, cbs));
3131: }
3133: *isseq = iscol_local;
3134: PetscFunctionReturn(PETSC_SUCCESS);
3135: }
3137: /*
3138: Used by MatCreateSubMatrix_MPIAIJ_SameRowColDist() to avoid ISAllGather() and global size of iscol_local
3139: (see MatCreateSubMatrix_MPIAIJ_nonscalable)
3141: Input Parameters:
3142: + mat - matrix
3143: . isrow - parallel row index set; its local indices are a subset of local columns of `mat`,
3144: i.e., mat->rstart <= isrow[i] < mat->rend
3145: - iscol - parallel column index set; its local indices are a subset of local columns of `mat`,
3146: i.e., mat->cstart <= iscol[i] < mat->cend
3148: Output Parameters:
3149: + isrow_d - sequential row index set for retrieving mat->A
3150: . iscol_d - sequential column index set for retrieving mat->A
3151: . iscol_o - sequential column index set for retrieving mat->B
3152: - garray - column map; garray[i] indicates global location of iscol_o[i] in `iscol`
3153: */
3154: static PetscErrorCode ISGetSeqIS_SameColDist_Private(Mat mat, IS isrow, IS iscol, IS *isrow_d, IS *iscol_d, IS *iscol_o, PetscInt *garray[])
3155: {
3156: const PetscInt *is_idx;
3157: PetscInt ncols, isstart, *idx, m, rstart, *cmap1, count;
3158: PetscInt *cmap, *lcmap;
3159: Mat_MPIAIJ *a = (Mat_MPIAIJ *)mat->data;
3160: Mat B = a->B;
3161: PetscInt i, n, cstart, cend, Bn = B->cmap->N;
3162: MPI_Comm comm;
3163: PetscSF Mvctx = a->Mvctx;
3165: PetscFunctionBegin;
3166: PetscCall(PetscObjectGetComm((PetscObject)mat, &comm));
3167: PetscCall(ISGetLocalSize(iscol, &ncols));
3169: /* (1) cmap gives the submatrix column of each local column of mat, or -1 if it is not in iscol */
3170: PetscCall(MatGetLocalSize(mat, NULL, &n));
3171: PetscCall(PetscMalloc2(n, &cmap, Bn, &lcmap));
3172: for (i = 0; i < n; i++) cmap[i] = -1;
3174: /* Get start indices */
3175: PetscCallMPI(MPI_Scan(&ncols, &isstart, 1, MPIU_INT, MPI_SUM, comm));
3176: isstart -= ncols;
3177: PetscCall(MatGetOwnershipRangeColumn(mat, &cstart, &cend));
3179: PetscCall(ISGetIndices(iscol, &is_idx));
3180: PetscCall(PetscMalloc1(ncols, &idx));
3181: for (i = 0; i < ncols; i++) {
3182: cmap[is_idx[i] - cstart] = i + isstart; /* global index of iscol[i] */
3183: idx[i] = is_idx[i] - cstart; /* local index of iscol[i] */
3184: }
3185: PetscCall(ISRestoreIndices(iscol, &is_idx));
3187: /* Get iscol_d */
3188: PetscCall(ISCreateGeneral(PETSC_COMM_SELF, ncols, idx, PETSC_OWN_POINTER, iscol_d));
3189: PetscCall(ISGetBlockSize(iscol, &i));
3190: PetscCall(ISSetBlockSize(*iscol_d, i));
3192: /* Get isrow_d */
3193: PetscCall(ISGetLocalSize(isrow, &m));
3194: rstart = mat->rmap->rstart;
3195: PetscCall(PetscMalloc1(m, &idx));
3196: PetscCall(ISGetIndices(isrow, &is_idx));
3197: for (i = 0; i < m; i++) idx[i] = is_idx[i] - rstart;
3198: PetscCall(ISRestoreIndices(isrow, &is_idx));
3200: PetscCall(ISCreateGeneral(PETSC_COMM_SELF, m, idx, PETSC_OWN_POINTER, isrow_d));
3201: PetscCall(ISGetBlockSize(isrow, &i));
3202: PetscCall(ISSetBlockSize(*isrow_d, i));
3204: /* (2) Broadcast cmap through aij->Mvctx to get lcmap, its values for the columns of B (see MatMult_MPIAIJ()) */
3205: PetscCall(PetscSFBcastBegin(Mvctx, MPIU_INT, cmap, lcmap, MPI_REPLACE));
3206: PetscCall(PetscSFBcastEnd(Mvctx, MPIU_INT, cmap, lcmap, MPI_REPLACE));
3208: /* (3) create sequential iscol_o (a subset of iscol) and isgarray */
3209: /* off-process column indices */
3210: count = 0;
3211: PetscCall(PetscMalloc1(Bn, &idx));
3212: PetscCall(PetscMalloc1(Bn, &cmap1));
3214: for (i = 0; i < Bn; i++) {
3215: if (lcmap[i] > -1) {
3216: idx[count] = i; /* local column index in off-diagonal part B */
3217: cmap1[count] = lcmap[i]; /* column index in submat */
3218: count++;
3219: }
3220: }
3222: PetscCall(ISCreateGeneral(PETSC_COMM_SELF, count, idx, PETSC_COPY_VALUES, iscol_o));
3223: /* cannot ensure iscol_o has same blocksize as iscol! */
3225: PetscCall(PetscFree(idx));
3226: *garray = cmap1;
3228: PetscCall(PetscFree2(cmap, lcmap));
3229: PetscFunctionReturn(PETSC_SUCCESS);
3230: }
3232: /* isrow and iscol have same processor distribution as mat, output *submat is a submatrix of local mat */
3233: PetscErrorCode MatCreateSubMatrix_MPIAIJ_SameRowColDist(Mat mat, IS isrow, IS iscol, MatReuse call, Mat *submat)
3234: {
3235: Mat_MPIAIJ *a = (Mat_MPIAIJ *)mat->data, *asub;
3236: Mat M = NULL;
3237: MPI_Comm comm;
3238: IS iscol_d, isrow_d, iscol_o;
3239: Mat Asub = NULL, Bsub = NULL;
3240: PetscInt n, count, M_size, N_size;
3242: PetscFunctionBegin;
3243: PetscCall(PetscObjectGetComm((PetscObject)mat, &comm));
3245: if (call == MAT_REUSE_MATRIX) {
3246: /* Retrieve isrow_d, iscol_d and iscol_o from submat */
3247: PetscCall(PetscObjectQuery((PetscObject)*submat, "isrow_d", (PetscObject *)&isrow_d));
3248: PetscCheck(isrow_d, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "isrow_d passed in was not used before, cannot reuse");
3250: PetscCall(PetscObjectQuery((PetscObject)*submat, "iscol_d", (PetscObject *)&iscol_d));
3251: PetscCheck(iscol_d, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "iscol_d passed in was not used before, cannot reuse");
3253: PetscCall(PetscObjectQuery((PetscObject)*submat, "iscol_o", (PetscObject *)&iscol_o));
3254: PetscCheck(iscol_o, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "iscol_o passed in was not used before, cannot reuse");
3256: /* Update diagonal and off-diagonal portions of submat */
3257: asub = (Mat_MPIAIJ *)(*submat)->data;
3258: PetscCall(MatCreateSubMatrix_SeqAIJ(a->A, isrow_d, iscol_d, PETSC_DECIDE, MAT_REUSE_MATRIX, &asub->A));
3259: PetscCall(ISGetLocalSize(iscol_o, &n));
3260: if (n) PetscCall(MatCreateSubMatrix_SeqAIJ(a->B, isrow_d, iscol_o, PETSC_DECIDE, MAT_REUSE_MATRIX, &asub->B));
3261: PetscCall(MatAssemblyBegin(*submat, MAT_FINAL_ASSEMBLY));
3262: PetscCall(MatAssemblyEnd(*submat, MAT_FINAL_ASSEMBLY));
3264: } else { /* call == MAT_INITIAL_MATRIX) */
3265: PetscInt *garray = NULL, *garray_compact;
3266: PetscInt BsubN;
3268: /* Create isrow_d, iscol_d, iscol_o and isgarray (replace isgarray with array?) */
3269: PetscCall(ISGetSeqIS_SameColDist_Private(mat, isrow, iscol, &isrow_d, &iscol_d, &iscol_o, &garray));
3271: /* Create local submatrices Asub and Bsub */
3272: PetscCall(MatCreateSubMatrix_SeqAIJ(a->A, isrow_d, iscol_d, PETSC_DECIDE, MAT_INITIAL_MATRIX, &Asub));
3273: PetscCall(MatCreateSubMatrix_SeqAIJ(a->B, isrow_d, iscol_o, PETSC_DECIDE, MAT_INITIAL_MATRIX, &Bsub));
3275: // Compact garray so its not of size Bn
3276: PetscCall(ISGetSize(iscol_o, &count));
3277: PetscCall(PetscMalloc1(count, &garray_compact));
3278: PetscCall(PetscArraycpy(garray_compact, garray, count));
3280: /* Create submatrix M */
3281: PetscCall(ISGetSize(isrow, &M_size));
3282: PetscCall(ISGetSize(iscol, &N_size));
3283: PetscCall(MatCreateMPIAIJWithSeqAIJ(comm, M_size, N_size, Asub, Bsub, garray_compact, &M));
3285: /* If Bsub has empty columns, compress iscol_o such that it will retrieve condensed Bsub from a->B during reuse */
3286: asub = (Mat_MPIAIJ *)M->data;
3288: PetscCall(ISGetLocalSize(iscol_o, &BsubN));
3289: n = asub->B->cmap->N;
3290: if (BsubN > n) {
3291: /* This case can be tested using ~petsc/src/tao/bound/tutorials/runplate2_3 */
3292: const PetscInt *idx;
3293: PetscInt i, j, *idx_new, *subgarray = asub->garray;
3294: PetscCall(PetscInfo(M, "submatrix Bn %" PetscInt_FMT " != BsubN %" PetscInt_FMT ", update iscol_o\n", n, BsubN));
3296: PetscCall(PetscMalloc1(n, &idx_new));
3297: j = 0;
3298: PetscCall(ISGetIndices(iscol_o, &idx));
3299: for (i = 0; i < n; i++) {
3300: if (j >= BsubN) break;
3301: while (subgarray[i] > garray[j]) j++;
3303: 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]);
3304: idx_new[i] = idx[j++];
3305: }
3306: PetscCall(ISRestoreIndices(iscol_o, &idx));
3308: PetscCall(ISDestroy(&iscol_o));
3309: PetscCall(ISCreateGeneral(PETSC_COMM_SELF, n, idx_new, PETSC_OWN_POINTER, &iscol_o));
3311: } 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);
3313: PetscCall(PetscFree(garray));
3314: *submat = M;
3316: /* Save isrow_d, iscol_d and iscol_o used in processor for next request */
3317: PetscCall(PetscObjectCompose((PetscObject)M, "isrow_d", (PetscObject)isrow_d));
3318: PetscCall(ISDestroy(&isrow_d));
3320: PetscCall(PetscObjectCompose((PetscObject)M, "iscol_d", (PetscObject)iscol_d));
3321: PetscCall(ISDestroy(&iscol_d));
3323: PetscCall(PetscObjectCompose((PetscObject)M, "iscol_o", (PetscObject)iscol_o));
3324: PetscCall(ISDestroy(&iscol_o));
3325: }
3326: PetscFunctionReturn(PETSC_SUCCESS);
3327: }
3329: PetscErrorCode MatCreateSubMatrix_MPIAIJ(Mat mat, IS isrow, IS iscol, MatReuse call, Mat *newmat)
3330: {
3331: IS iscol_local = NULL, isrow_d;
3332: PetscInt csize;
3333: PetscInt n, i, j, start, end;
3334: PetscBool sameRowDist = PETSC_FALSE, tsameDist[2];
3335: MPI_Comm comm;
3337: PetscFunctionBegin;
3338: /* If isrow has same processor distribution as mat,
3339: call MatCreateSubMatrix_MPIAIJ_SameRowDist() to avoid using a hash table with global size of iscol */
3340: if (call == MAT_REUSE_MATRIX) {
3341: PetscCall(PetscObjectQuery((PetscObject)*newmat, "isrow_d", (PetscObject *)&isrow_d));
3342: if (isrow_d) {
3343: sameRowDist = PETSC_TRUE;
3344: tsameDist[1] = PETSC_TRUE; /* sameColDist */
3345: } else {
3346: PetscCall(PetscObjectQuery((PetscObject)*newmat, "SubIScol", (PetscObject *)&iscol_local));
3347: if (iscol_local) {
3348: sameRowDist = PETSC_TRUE;
3349: tsameDist[1] = PETSC_FALSE; /* !sameColDist */
3350: }
3351: }
3352: } else {
3353: /* Check if isrow has same processor distribution as mat */
3354: tsameDist[0] = PETSC_FALSE;
3355: PetscCall(ISGetLocalSize(isrow, &n));
3356: if (!n) {
3357: tsameDist[0] = PETSC_TRUE;
3358: } else {
3359: PetscCall(ISGetMinMax(isrow, &i, &j));
3360: PetscCall(MatGetOwnershipRange(mat, &start, &end));
3361: if (i >= start && j < end) tsameDist[0] = PETSC_TRUE;
3362: }
3364: /* Check if iscol has same processor distribution as mat */
3365: tsameDist[1] = PETSC_FALSE;
3366: PetscCall(ISGetLocalSize(iscol, &n));
3367: if (!n) {
3368: tsameDist[1] = PETSC_TRUE;
3369: } else {
3370: PetscCall(ISGetMinMax(iscol, &i, &j));
3371: PetscCall(MatGetOwnershipRangeColumn(mat, &start, &end));
3372: if (i >= start && j < end) tsameDist[1] = PETSC_TRUE;
3373: }
3375: PetscCall(PetscObjectGetComm((PetscObject)mat, &comm));
3376: PetscCallMPI(MPIU_Allreduce(MPI_IN_PLACE, tsameDist, 2, MPI_C_BOOL, MPI_LAND, comm));
3377: sameRowDist = tsameDist[0];
3378: }
3380: if (sameRowDist) {
3381: if (tsameDist[1]) { /* sameRowDist & sameColDist */
3382: /* isrow and iscol have same processor distribution as mat */
3383: PetscCall(MatCreateSubMatrix_MPIAIJ_SameRowColDist(mat, isrow, iscol, call, newmat));
3384: PetscFunctionReturn(PETSC_SUCCESS);
3385: } else { /* sameRowDist */
3386: /* isrow has same processor distribution as mat */
3387: if (call == MAT_INITIAL_MATRIX) {
3388: PetscBool sorted;
3389: PetscCall(ISGetSeqIS_Private(mat, iscol, &iscol_local));
3390: PetscCall(ISGetLocalSize(iscol_local, &n)); /* local size of iscol_local = global columns of newmat */
3391: PetscCall(ISGetSize(iscol, &i));
3392: PetscCheck(n == i, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "n %" PetscInt_FMT " != size of iscol %" PetscInt_FMT, n, i);
3394: PetscCall(ISSorted(iscol_local, &sorted));
3395: if (sorted) {
3396: /* MatCreateSubMatrix_MPIAIJ_SameRowDist() requires iscol_local be sorted; it can have duplicate indices */
3397: PetscCall(MatCreateSubMatrix_MPIAIJ_SameRowDist(mat, isrow, iscol, iscol_local, MAT_INITIAL_MATRIX, newmat));
3398: PetscFunctionReturn(PETSC_SUCCESS);
3399: }
3400: } else { /* call == MAT_REUSE_MATRIX */
3401: IS iscol_sub;
3402: PetscCall(PetscObjectQuery((PetscObject)*newmat, "SubIScol", (PetscObject *)&iscol_sub));
3403: if (iscol_sub) {
3404: PetscCall(MatCreateSubMatrix_MPIAIJ_SameRowDist(mat, isrow, iscol, NULL, call, newmat));
3405: PetscFunctionReturn(PETSC_SUCCESS);
3406: }
3407: }
3408: }
3409: }
3411: /* General case: iscol -> iscol_local which has global size of iscol */
3412: if (call == MAT_REUSE_MATRIX) {
3413: PetscCall(PetscObjectQuery((PetscObject)*newmat, "ISAllGather", (PetscObject *)&iscol_local));
3414: PetscCheck(iscol_local, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Submatrix passed in was not used before, cannot reuse");
3415: } else {
3416: if (!iscol_local) PetscCall(ISGetSeqIS_Private(mat, iscol, &iscol_local));
3417: }
3419: PetscCall(ISGetLocalSize(iscol, &csize));
3420: PetscCall(MatCreateSubMatrix_MPIAIJ_nonscalable(mat, isrow, iscol_local, csize, call, newmat));
3422: if (call == MAT_INITIAL_MATRIX) {
3423: PetscCall(PetscObjectCompose((PetscObject)*newmat, "ISAllGather", (PetscObject)iscol_local));
3424: PetscCall(ISDestroy(&iscol_local));
3425: }
3426: PetscFunctionReturn(PETSC_SUCCESS);
3427: }
3429: /*@
3430: MatCreateMPIAIJWithSeqAIJ - creates a `MATMPIAIJ` matrix using `MATSEQAIJ` matrices that contain the "diagonal"
3431: and "off-diagonal" part of the matrix in CSR format.
3433: Collective
3435: Input Parameters:
3436: + comm - MPI communicator
3437: . M - the global row size
3438: . N - the global column size
3439: . A - "diagonal" portion of matrix
3440: . 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
3441: - 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.
3443: Output Parameter:
3444: . mat - the matrix, with input `A` as its local diagonal matrix
3446: Level: advanced
3448: Notes:
3449: See `MatCreateAIJ()` for the definition of "diagonal" and "off-diagonal" portion of the matrix.
3451: `A` and `B` becomes part of output mat. The user cannot use `A` and `B` anymore.
3453: 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
3454: `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
3455: `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`
3456: yourself, see algorithms in the private function `MatSetUpMultiply_MPIAIJ()`.
3458: 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.
3460: .seealso: [](ch_matrices), `Mat`, `MATMPIAIJ`, `MATSEQAIJ`, `MatCreateMPIAIJWithSplitArrays()`
3461: @*/
3462: PetscErrorCode MatCreateMPIAIJWithSeqAIJ(MPI_Comm comm, PetscInt M, PetscInt N, Mat A, Mat B, PetscInt *garray, Mat *mat)
3463: {
3464: PetscInt m, n;
3465: MatType mpi_mat_type;
3466: Mat_MPIAIJ *mpiaij;
3467: Mat C;
3469: PetscFunctionBegin;
3470: PetscCall(MatCreate(comm, &C));
3471: PetscCall(MatGetSize(A, &m, &n));
3472: PetscCheck(m == B->rmap->N, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Am %" PetscInt_FMT " != Bm %" PetscInt_FMT, m, B->rmap->N);
3473: 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);
3475: 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");
3476: PetscCall(MatSetSizes(C, m, n, M, N));
3477: /* Determine the type of MPI matrix that should be created from the type of matrix A, which holds the "diagonal" portion. */
3478: PetscCall(MatGetMPIMatType_Private(A, &mpi_mat_type));
3479: PetscCall(MatSetType(C, mpi_mat_type));
3480: if (!garray) {
3481: const PetscScalar *ba;
3483: B->nonzerostate++;
3484: PetscCall(MatSeqAIJGetArrayRead(B, &ba)); /* Since we will destroy B's device copy, we need to make sure the host copy is up to date */
3485: PetscCall(MatSeqAIJRestoreArrayRead(B, &ba));
3486: }
3488: PetscCall(MatSetBlockSizes(C, A->rmap->bs, A->cmap->bs));
3489: PetscCall(PetscLayoutSetUp(C->rmap));
3490: PetscCall(PetscLayoutSetUp(C->cmap));
3492: mpiaij = (Mat_MPIAIJ *)C->data;
3493: mpiaij->A = A;
3494: mpiaij->B = B;
3495: mpiaij->garray = garray;
3496: C->preallocated = PETSC_TRUE;
3497: C->nooffprocentries = PETSC_TRUE; /* See MatAssemblyBegin_MPIAIJ. In effect, making MatAssemblyBegin a nop */
3499: PetscCall(MatSetOption(C, MAT_STRUCTURE_ONLY, A->structure_only));
3500: PetscCall(MatSetOption(C, MAT_NO_OFF_PROC_ENTRIES, PETSC_TRUE));
3501: PetscCall(MatAssemblyBegin(C, MAT_FINAL_ASSEMBLY));
3502: /* MatAssemblyEnd is critical here. It sets mat->offloadmask according to A and B's, and
3503: also gets mpiaij->B compacted (if garray is NULL), with its col ids and size reduced
3504: */
3505: PetscCall(MatAssemblyEnd(C, MAT_FINAL_ASSEMBLY));
3506: PetscCall(MatSetOption(C, MAT_NO_OFF_PROC_ENTRIES, PETSC_FALSE));
3507: PetscCall(MatSetOption(C, MAT_NEW_NONZERO_LOCATION_ERR, PETSC_TRUE));
3508: *mat = C;
3509: PetscFunctionReturn(PETSC_SUCCESS);
3510: }
3512: extern PetscErrorCode MatCreateSubMatrices_MPIAIJ_SingleIS_Local(Mat, PetscInt, const IS[], const IS[], MatReuse, PetscBool, Mat *);
3514: PetscErrorCode MatCreateSubMatrix_MPIAIJ_SameRowDist(Mat mat, IS isrow, IS iscol, IS iscol_local, MatReuse call, Mat *newmat)
3515: {
3516: PetscInt i, m, n, rstart, row, rend, nz, j, bs, cbs;
3517: PetscInt *ii, *jj, nlocal, *dlens, *olens, dlen, olen, jend, mglobal;
3518: Mat_MPIAIJ *a = (Mat_MPIAIJ *)mat->data;
3519: Mat M, Msub, B = a->B;
3520: MatScalar *aa;
3521: Mat_SeqAIJ *aij;
3522: PetscInt *garray = a->garray, *colsub, Ncols;
3523: PetscInt count, Bn = B->cmap->N, cstart = mat->cmap->rstart, cend = mat->cmap->rend;
3524: IS iscol_sub, iscmap;
3525: const PetscInt *is_idx, *cmap;
3526: PetscBool allcolumns = PETSC_FALSE;
3527: MPI_Comm comm;
3529: PetscFunctionBegin;
3530: PetscCall(PetscObjectGetComm((PetscObject)mat, &comm));
3531: if (call == MAT_REUSE_MATRIX) {
3532: PetscCall(PetscObjectQuery((PetscObject)*newmat, "SubIScol", (PetscObject *)&iscol_sub));
3533: PetscCheck(iscol_sub, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "SubIScol passed in was not used before, cannot reuse");
3534: PetscCall(ISGetLocalSize(iscol_sub, &count));
3536: PetscCall(PetscObjectQuery((PetscObject)*newmat, "Subcmap", (PetscObject *)&iscmap));
3537: PetscCheck(iscmap, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Subcmap passed in was not used before, cannot reuse");
3539: PetscCall(PetscObjectQuery((PetscObject)*newmat, "SubMatrix", (PetscObject *)&Msub));
3540: PetscCheck(Msub, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Submatrix passed in was not used before, cannot reuse");
3542: PetscCall(MatCreateSubMatrices_MPIAIJ_SingleIS_Local(mat, 1, &isrow, &iscol_sub, MAT_REUSE_MATRIX, PETSC_FALSE, &Msub));
3544: } else { /* call == MAT_INITIAL_MATRIX) */
3545: PetscBool flg;
3547: PetscCall(ISGetLocalSize(iscol, &n));
3548: PetscCall(ISGetSize(iscol, &Ncols));
3550: /* (1) iscol -> nonscalable iscol_local */
3551: /* Check for special case: each processor gets entire matrix columns */
3552: PetscCall(ISIdentity(iscol_local, &flg));
3553: if (flg && n == mat->cmap->N) allcolumns = PETSC_TRUE;
3554: PetscCallMPI(MPIU_Allreduce(MPI_IN_PLACE, &allcolumns, 1, MPI_C_BOOL, MPI_LAND, PetscObjectComm((PetscObject)mat)));
3555: if (allcolumns) {
3556: iscol_sub = iscol_local;
3557: PetscCall(PetscObjectReference((PetscObject)iscol_local));
3558: PetscCall(ISCreateStride(PETSC_COMM_SELF, n, 0, 1, &iscmap));
3560: } else {
3561: /* (2) iscol_local -> iscol_sub and iscmap. Implementation below requires iscol_local be sorted, it can have duplicate indices */
3562: PetscInt *idx, *cmap1, k;
3563: PetscCall(PetscMalloc1(Ncols, &idx));
3564: PetscCall(PetscMalloc1(Ncols, &cmap1));
3565: PetscCall(ISGetIndices(iscol_local, &is_idx));
3566: count = 0;
3567: k = 0;
3568: for (i = 0; i < Ncols; i++) {
3569: j = is_idx[i];
3570: if (j >= cstart && j < cend) {
3571: /* diagonal part of mat */
3572: idx[count] = j;
3573: cmap1[count++] = i; /* column index in submat */
3574: } else if (Bn) {
3575: /* off-diagonal part of mat */
3576: if (j == garray[k]) {
3577: idx[count] = j;
3578: cmap1[count++] = i; /* column index in submat */
3579: } else if (j > garray[k]) {
3580: while (j > garray[k] && k < Bn - 1) k++;
3581: if (j == garray[k]) {
3582: idx[count] = j;
3583: cmap1[count++] = i; /* column index in submat */
3584: }
3585: }
3586: }
3587: }
3588: PetscCall(ISRestoreIndices(iscol_local, &is_idx));
3590: PetscCall(ISCreateGeneral(PETSC_COMM_SELF, count, idx, PETSC_OWN_POINTER, &iscol_sub));
3591: PetscCall(ISGetBlockSize(iscol, &cbs));
3592: PetscCall(ISSetBlockSize(iscol_sub, cbs));
3594: PetscCall(ISCreateGeneral(PetscObjectComm((PetscObject)iscol_local), count, cmap1, PETSC_OWN_POINTER, &iscmap));
3595: }
3597: /* (3) Create sequential Msub */
3598: PetscCall(MatCreateSubMatrices_MPIAIJ_SingleIS_Local(mat, 1, &isrow, &iscol_sub, MAT_INITIAL_MATRIX, allcolumns, &Msub));
3599: }
3601: PetscCall(ISGetLocalSize(iscol_sub, &count));
3602: aij = (Mat_SeqAIJ *)Msub->data;
3603: ii = aij->i;
3604: PetscCall(ISGetIndices(iscmap, &cmap));
3606: /*
3607: m - number of local rows
3608: Ncols - number of columns (same on all processors)
3609: rstart - first row in new global matrix generated
3610: */
3611: PetscCall(MatGetSize(Msub, &m, NULL));
3613: if (call == MAT_INITIAL_MATRIX) {
3614: /* (4) Create parallel newmat */
3615: PetscMPIInt rank, size;
3616: PetscInt csize;
3618: PetscCallMPI(MPI_Comm_size(comm, &size));
3619: PetscCallMPI(MPI_Comm_rank(comm, &rank));
3621: /*
3622: Determine the number of non-zeros in the diagonal and off-diagonal
3623: portions of the matrix in order to do correct preallocation
3624: */
3626: /* first get start and end of "diagonal" columns */
3627: PetscCall(ISGetLocalSize(iscol, &csize));
3628: if (csize == PETSC_DECIDE) {
3629: PetscCall(ISGetSize(isrow, &mglobal));
3630: if (mglobal == Ncols) { /* square matrix */
3631: nlocal = m;
3632: } else {
3633: nlocal = Ncols / size + ((Ncols % size) > rank);
3634: }
3635: } else {
3636: nlocal = csize;
3637: }
3638: PetscCallMPI(MPI_Scan(&nlocal, &rend, 1, MPIU_INT, MPI_SUM, comm));
3639: rstart = rend - nlocal;
3640: 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);
3642: /* next, compute all the lengths */
3643: jj = aij->j;
3644: PetscCall(PetscMalloc1(2 * m + 1, &dlens));
3645: olens = dlens + m;
3646: for (i = 0; i < m; i++) {
3647: jend = ii[i + 1] - ii[i];
3648: olen = 0;
3649: dlen = 0;
3650: for (j = 0; j < jend; j++) {
3651: if (cmap[*jj] < rstart || cmap[*jj] >= rend) olen++;
3652: else dlen++;
3653: jj++;
3654: }
3655: olens[i] = olen;
3656: dlens[i] = dlen;
3657: }
3659: PetscCall(ISGetBlockSize(isrow, &bs));
3660: PetscCall(ISGetBlockSize(iscol, &cbs));
3662: PetscCall(MatCreate(comm, &M));
3663: PetscCall(MatSetSizes(M, m, nlocal, PETSC_DECIDE, Ncols));
3664: PetscCall(MatSetBlockSizes(M, bs, cbs));
3665: PetscCall(MatSetType(M, ((PetscObject)mat)->type_name));
3666: PetscCall(MatSetOption(M, MAT_STRUCTURE_ONLY, mat->structure_only));
3667: PetscCall(MatMPIAIJSetPreallocation(M, 0, dlens, 0, olens));
3668: PetscCall(PetscFree(dlens));
3670: } else { /* call == MAT_REUSE_MATRIX */
3671: M = *newmat;
3672: PetscCall(MatGetLocalSize(M, &i, NULL));
3673: PetscCheck(i == m, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Previous matrix must be same size/layout as request");
3674: PetscCall(MatZeroEntries(M));
3675: /*
3676: The next two lines are needed so we may call MatSetValues_MPIAIJ() below directly,
3677: rather than the slower MatSetValues().
3678: */
3679: M->was_assembled = PETSC_TRUE;
3680: M->assembled = PETSC_FALSE;
3681: }
3683: /* (5) Set values of Msub to *newmat */
3684: PetscCall(PetscMalloc1(count, &colsub));
3685: PetscCall(MatGetOwnershipRange(M, &rstart, NULL));
3687: jj = aij->j;
3688: PetscCall(MatSeqAIJGetArrayRead(Msub, (const PetscScalar **)&aa));
3689: for (i = 0; i < m; i++) {
3690: row = rstart + i;
3691: nz = ii[i + 1] - ii[i];
3692: for (j = 0; j < nz; j++) colsub[j] = cmap[jj[j]];
3693: PetscCall(MatSetValues_MPIAIJ(M, 1, &row, nz, colsub, aa, INSERT_VALUES));
3694: jj += nz;
3695: if (!mat->structure_only) aa += nz;
3696: }
3697: PetscCall(MatSeqAIJRestoreArrayRead(Msub, (const PetscScalar **)&aa));
3698: PetscCall(ISRestoreIndices(iscmap, &cmap));
3700: PetscCall(MatAssemblyBegin(M, MAT_FINAL_ASSEMBLY));
3701: PetscCall(MatAssemblyEnd(M, MAT_FINAL_ASSEMBLY));
3703: PetscCall(PetscFree(colsub));
3705: /* save Msub, iscol_sub and iscmap used in processor for next request */
3706: if (call == MAT_INITIAL_MATRIX) {
3707: *newmat = M;
3708: PetscCall(PetscObjectCompose((PetscObject)*newmat, "SubMatrix", (PetscObject)Msub));
3709: PetscCall(MatDestroy(&Msub));
3711: PetscCall(PetscObjectCompose((PetscObject)*newmat, "SubIScol", (PetscObject)iscol_sub));
3712: PetscCall(ISDestroy(&iscol_sub));
3714: PetscCall(PetscObjectCompose((PetscObject)*newmat, "Subcmap", (PetscObject)iscmap));
3715: PetscCall(ISDestroy(&iscmap));
3717: if (iscol_local) {
3718: PetscCall(PetscObjectCompose((PetscObject)*newmat, "ISAllGather", (PetscObject)iscol_local));
3719: PetscCall(ISDestroy(&iscol_local));
3720: }
3721: }
3722: PetscFunctionReturn(PETSC_SUCCESS);
3723: }
3725: /*
3726: Not great since it makes two copies of the submatrix, first an SeqAIJ
3727: in local and then by concatenating the local matrices the end result.
3728: Writing it directly would be much like MatCreateSubMatrices_MPIAIJ()
3730: This requires a sequential iscol with all indices.
3731: */
3732: PetscErrorCode MatCreateSubMatrix_MPIAIJ_nonscalable(Mat mat, IS isrow, IS iscol, PetscInt csize, MatReuse call, Mat *newmat)
3733: {
3734: PetscMPIInt rank, size;
3735: PetscInt i, m, n, rstart, row, rend, nz, *cwork, j, bs, cbs;
3736: PetscInt *ii, *jj, nlocal, *dlens, *olens, dlen, olen, jend, mglobal;
3737: Mat M, Mreuse;
3738: MatScalar *aa, *vwork;
3739: MPI_Comm comm;
3740: Mat_SeqAIJ *aij;
3741: PetscBool colflag, allcolumns = PETSC_FALSE;
3743: PetscFunctionBegin;
3744: PetscCall(PetscObjectGetComm((PetscObject)mat, &comm));
3745: PetscCallMPI(MPI_Comm_rank(comm, &rank));
3746: PetscCallMPI(MPI_Comm_size(comm, &size));
3748: /* Check for special case: each processor gets entire matrix columns */
3749: PetscCall(ISIdentity(iscol, &colflag));
3750: PetscCall(ISGetLocalSize(iscol, &n));
3751: if (colflag && n == mat->cmap->N) allcolumns = PETSC_TRUE;
3752: PetscCallMPI(MPIU_Allreduce(MPI_IN_PLACE, &allcolumns, 1, MPI_C_BOOL, MPI_LAND, PetscObjectComm((PetscObject)mat)));
3754: if (call == MAT_REUSE_MATRIX) {
3755: PetscCall(PetscObjectQuery((PetscObject)*newmat, "SubMatrix", (PetscObject *)&Mreuse));
3756: PetscCheck(Mreuse, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Submatrix passed in was not used before, cannot reuse");
3757: PetscCall(MatCreateSubMatrices_MPIAIJ_SingleIS_Local(mat, 1, &isrow, &iscol, MAT_REUSE_MATRIX, allcolumns, &Mreuse));
3758: } else {
3759: PetscCall(MatCreateSubMatrices_MPIAIJ_SingleIS_Local(mat, 1, &isrow, &iscol, MAT_INITIAL_MATRIX, allcolumns, &Mreuse));
3760: }
3762: /*
3763: m - number of local rows
3764: n - number of columns (same on all processors)
3765: rstart - first row in new global matrix generated
3766: */
3767: PetscCall(MatGetSize(Mreuse, &m, &n));
3768: PetscCall(MatGetBlockSizes(Mreuse, &bs, &cbs));
3769: if (call == MAT_INITIAL_MATRIX) {
3770: aij = (Mat_SeqAIJ *)Mreuse->data;
3771: ii = aij->i;
3772: jj = aij->j;
3774: /*
3775: Determine the number of non-zeros in the diagonal and off-diagonal
3776: portions of the matrix in order to do correct preallocation
3777: */
3779: /* first get start and end of "diagonal" columns */
3780: if (csize == PETSC_DECIDE) {
3781: PetscCall(ISGetSize(isrow, &mglobal));
3782: if (mglobal == n) { /* square matrix */
3783: nlocal = m;
3784: } else {
3785: nlocal = n / size + ((n % size) > rank);
3786: }
3787: } else {
3788: nlocal = csize;
3789: }
3790: PetscCallMPI(MPI_Scan(&nlocal, &rend, 1, MPIU_INT, MPI_SUM, comm));
3791: rstart = rend - nlocal;
3792: 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);
3794: /* next, compute all the lengths */
3795: PetscCall(PetscMalloc1(2 * m + 1, &dlens));
3796: olens = dlens + m;
3797: for (i = 0; i < m; i++) {
3798: jend = ii[i + 1] - ii[i];
3799: olen = 0;
3800: dlen = 0;
3801: for (j = 0; j < jend; j++) {
3802: if (*jj < rstart || *jj >= rend) olen++;
3803: else dlen++;
3804: jj++;
3805: }
3806: olens[i] = olen;
3807: dlens[i] = dlen;
3808: }
3809: PetscCall(MatCreate(comm, &M));
3810: PetscCall(MatSetSizes(M, m, nlocal, PETSC_DECIDE, n));
3811: PetscCall(MatSetBlockSizes(M, bs, cbs));
3812: PetscCall(MatSetType(M, ((PetscObject)mat)->type_name));
3813: PetscCall(MatSetOption(M, MAT_STRUCTURE_ONLY, mat->structure_only));
3814: PetscCall(MatMPIAIJSetPreallocation(M, 0, dlens, 0, olens));
3815: PetscCall(PetscFree(dlens));
3816: } else {
3817: PetscInt ml, nl;
3819: M = *newmat;
3820: PetscCall(MatGetLocalSize(M, &ml, &nl));
3821: PetscCheck(ml == m, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Previous matrix must be same size/layout as request");
3822: PetscCall(MatZeroEntries(M));
3823: /*
3824: The next two lines are needed so we may call MatSetValues_MPIAIJ() below directly,
3825: rather than the slower MatSetValues().
3826: */
3827: M->was_assembled = PETSC_TRUE;
3828: M->assembled = PETSC_FALSE;
3829: }
3830: PetscCall(MatGetOwnershipRange(M, &rstart, &rend));
3831: aij = (Mat_SeqAIJ *)Mreuse->data;
3832: ii = aij->i;
3833: jj = aij->j;
3835: /* trigger copy to CPU if needed */
3836: PetscCall(MatSeqAIJGetArrayRead(Mreuse, (const PetscScalar **)&aa));
3837: for (i = 0; i < m; i++) {
3838: row = rstart + i;
3839: nz = ii[i + 1] - ii[i];
3840: cwork = jj;
3841: jj = PetscSafePointerPlusOffset(jj, nz);
3842: vwork = aa;
3843: aa = PetscSafePointerPlusOffset(aa, nz);
3844: PetscCall(MatSetValues_MPIAIJ(M, 1, &row, nz, cwork, vwork, INSERT_VALUES));
3845: }
3846: PetscCall(MatSeqAIJRestoreArrayRead(Mreuse, (const PetscScalar **)&aa));
3848: PetscCall(MatAssemblyBegin(M, MAT_FINAL_ASSEMBLY));
3849: PetscCall(MatAssemblyEnd(M, MAT_FINAL_ASSEMBLY));
3850: *newmat = M;
3852: /* save submatrix used in processor for next request */
3853: if (call == MAT_INITIAL_MATRIX) {
3854: PetscCall(PetscObjectCompose((PetscObject)M, "SubMatrix", (PetscObject)Mreuse));
3855: PetscCall(MatDestroy(&Mreuse));
3856: }
3857: PetscFunctionReturn(PETSC_SUCCESS);
3858: }
3860: static PetscErrorCode MatMPIAIJSetPreallocationCSR_MPIAIJ(Mat B, const PetscInt Ii[], const PetscInt J[], const PetscScalar v[])
3861: {
3862: PetscInt m, cstart, cend, j, nnz, i, d, *ld;
3863: PetscInt *d_nnz, *o_nnz, nnz_max = 0, rstart, ii, irstart;
3864: const PetscInt *JJ;
3865: PetscBool nooffprocentries;
3866: Mat_MPIAIJ *Aij = (Mat_MPIAIJ *)B->data;
3868: PetscFunctionBegin;
3869: PetscCall(PetscLayoutSetUp(B->rmap));
3870: PetscCall(PetscLayoutSetUp(B->cmap));
3871: m = B->rmap->n;
3872: cstart = B->cmap->rstart;
3873: cend = B->cmap->rend;
3874: rstart = B->rmap->rstart;
3875: irstart = Ii[0];
3877: PetscCall(PetscCalloc2(m, &d_nnz, m, &o_nnz));
3879: if (PetscDefined(USE_DEBUG)) {
3880: for (i = 0; i < m; i++) {
3881: nnz = Ii[i + 1] - Ii[i];
3882: JJ = PetscSafePointerPlusOffset(J, Ii[i] - irstart);
3883: PetscCheck(nnz >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Local row %" PetscInt_FMT " has a negative %" PetscInt_FMT " number of columns", i, nnz);
3884: 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]);
3885: 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);
3886: }
3887: }
3889: for (i = 0; i < m; i++) {
3890: nnz = Ii[i + 1] - Ii[i];
3891: JJ = PetscSafePointerPlusOffset(J, Ii[i] - irstart);
3892: nnz_max = PetscMax(nnz_max, nnz);
3893: d = 0;
3894: for (j = 0; j < nnz; j++) {
3895: if (cstart <= JJ[j] && JJ[j] < cend) d++;
3896: }
3897: d_nnz[i] = d;
3898: o_nnz[i] = nnz - d;
3899: }
3900: PetscCall(MatMPIAIJSetPreallocation(B, 0, d_nnz, 0, o_nnz));
3901: PetscCall(PetscFree2(d_nnz, o_nnz));
3903: for (i = 0; i < m; i++) {
3904: ii = i + rstart;
3905: PetscCall(MatSetValues_MPIAIJ(B, 1, &ii, Ii[i + 1] - Ii[i], PetscSafePointerPlusOffset(J, Ii[i] - irstart), PetscSafePointerPlusOffset(v, Ii[i] - irstart), INSERT_VALUES));
3906: }
3907: nooffprocentries = B->nooffprocentries;
3908: B->nooffprocentries = PETSC_TRUE;
3909: PetscCall(MatAssemblyBegin(B, MAT_FINAL_ASSEMBLY));
3910: PetscCall(MatAssemblyEnd(B, MAT_FINAL_ASSEMBLY));
3911: B->nooffprocentries = nooffprocentries;
3913: /* count number of entries below block diagonal */
3914: PetscCall(PetscFree(Aij->ld));
3915: PetscCall(PetscCalloc1(m, &ld));
3916: Aij->ld = ld;
3917: for (i = 0; i < m; i++) {
3918: nnz = Ii[i + 1] - Ii[i];
3919: j = 0;
3920: while (j < nnz && J[j] < cstart) j++;
3921: ld[i] = j;
3922: if (J) J += nnz;
3923: }
3925: PetscCall(MatSetOption(B, MAT_NEW_NONZERO_LOCATION_ERR, PETSC_TRUE));
3926: PetscFunctionReturn(PETSC_SUCCESS);
3927: }
3929: /*@
3930: MatMPIAIJSetPreallocationCSR - Allocates memory for a sparse parallel matrix in `MATAIJ` format
3931: (the default parallel PETSc format).
3933: Collective
3935: Input Parameters:
3936: + B - the matrix
3937: . i - the indices into `j` for the start of each local row (indices start with zero)
3938: . j - the column indices for each local row (indices start with zero)
3939: - v - optional values in the matrix
3941: Level: developer
3943: Notes:
3944: The `i`, `j`, and `v` arrays ARE copied by this routine into the internal format used by PETSc;
3945: thus you CANNOT change the matrix entries by changing the values of `v` after you have
3946: called this routine. Use `MatCreateMPIAIJWithSplitArrays()` to avoid needing to copy the arrays.
3948: The `i` and `j` indices are 0 based, and `i` indices are indices corresponding to the local `j` array.
3950: A convenience routine for this functionality is `MatCreateMPIAIJWithArrays()`.
3952: You can update the matrix with new numerical values using `MatUpdateMPIAIJWithArrays()` after this call if the column indices in `j` are sorted.
3954: If you do **not** use `MatUpdateMPIAIJWithArrays()`, the column indices in `j` do not need to be sorted. If you will use
3955: `MatUpdateMPIAIJWithArrays()`, the column indices **must** be sorted.
3957: The format which is used for the sparse matrix input, is equivalent to a
3958: row-major ordering.. i.e for the following matrix, the input data expected is
3959: as shown
3960: .vb
3961: 1 0 0
3962: 2 0 3 P0
3963: -------
3964: 4 5 6 P1
3966: Process0 [P0] rows_owned=[0,1]
3967: i = {0,1,3} [size = nrow+1 = 2+1]
3968: j = {0,0,2} [size = 3]
3969: v = {1,2,3} [size = 3]
3971: Process1 [P1] rows_owned=[2]
3972: i = {0,3} [size = nrow+1 = 1+1]
3973: j = {0,1,2} [size = 3]
3974: v = {4,5,6} [size = 3]
3975: .ve
3977: .seealso: [](ch_matrices), `Mat`, `MATMPIAIJ`, `MatCreate()`, `MatCreateSeqAIJ()`, `MatSetValues()`, `MatMPIAIJSetPreallocation()`, `MatCreateAIJ()`,
3978: `MatCreateSeqAIJWithArrays()`, `MatCreateMPIAIJWithSplitArrays()`, `MatCreateMPIAIJWithArrays()`, `MatSetPreallocationCOO()`, `MatSetValuesCOO()`
3979: @*/
3980: PetscErrorCode MatMPIAIJSetPreallocationCSR(Mat B, const PetscInt i[], const PetscInt j[], const PetscScalar v[])
3981: {
3982: PetscFunctionBegin;
3983: PetscTryMethod(B, "MatMPIAIJSetPreallocationCSR_C", (Mat, const PetscInt[], const PetscInt[], const PetscScalar[]), (B, i, j, v));
3984: PetscFunctionReturn(PETSC_SUCCESS);
3985: }
3987: /*@
3988: MatMPIAIJSetPreallocation - Preallocates memory for a sparse parallel matrix in `MATMPIAIJ` format
3989: (the default parallel PETSc format). For good matrix assembly performance
3990: the user should preallocate the matrix storage by setting the parameters
3991: `d_nz` (or `d_nnz`) and `o_nz` (or `o_nnz`).
3993: Collective
3995: Input Parameters:
3996: + B - the matrix
3997: . d_nz - number of nonzeros per row in DIAGONAL portion of local submatrix
3998: (same value is used for all local rows)
3999: . d_nnz - array containing the number of nonzeros in the various rows of the
4000: DIAGONAL portion of the local submatrix (possibly different for each row)
4001: or `NULL` (`PETSC_NULL_INTEGER` in Fortran), if `d_nz` is used to specify the nonzero structure.
4002: The size of this array is equal to the number of local rows, i.e 'm'.
4003: For matrices that will be factored, you must leave room for (and set)
4004: the diagonal entry even if it is zero.
4005: . o_nz - number of nonzeros per row in the OFF-DIAGONAL portion of local
4006: submatrix (same value is used for all local rows).
4007: - o_nnz - array containing the number of nonzeros in the various rows of the
4008: OFF-DIAGONAL portion of the local submatrix (possibly different for
4009: each row) or `NULL` (`PETSC_NULL_INTEGER` in Fortran), if `o_nz` is used to specify the nonzero
4010: structure. The size of this array is equal to the number
4011: of local rows, i.e 'm'.
4013: Example Usage:
4014: Consider the following 8x8 matrix with 34 non-zero values, that is
4015: assembled across 3 processors. Lets assume that proc0 owns 3 rows,
4016: proc1 owns 3 rows, proc2 owns 2 rows. This division can be shown
4017: as follows
4019: .vb
4020: 1 2 0 | 0 3 0 | 0 4
4021: Proc0 0 5 6 | 7 0 0 | 8 0
4022: 9 0 10 | 11 0 0 | 12 0
4023: -------------------------------------
4024: 13 0 14 | 15 16 17 | 0 0
4025: Proc1 0 18 0 | 19 20 21 | 0 0
4026: 0 0 0 | 22 23 0 | 24 0
4027: -------------------------------------
4028: Proc2 25 26 27 | 0 0 28 | 29 0
4029: 30 0 0 | 31 32 33 | 0 34
4030: .ve
4032: This can be represented as a collection of submatrices as
4033: .vb
4034: A B C
4035: D E F
4036: G H I
4037: .ve
4039: Where the submatrices A,B,C are owned by proc0, D,E,F are
4040: owned by proc1, G,H,I are owned by proc2.
4042: The 'm' parameters for proc0,proc1,proc2 are 3,3,2 respectively.
4043: The 'n' parameters for proc0,proc1,proc2 are 3,3,2 respectively.
4044: The 'M','N' parameters are 8,8, and have the same values on all procs.
4046: The DIAGONAL submatrices corresponding to proc0,proc1,proc2 are
4047: submatrices [A], [E], [I] respectively. The OFF-DIAGONAL submatrices
4048: corresponding to proc0,proc1,proc2 are [BC], [DF], [GH] respectively.
4049: Internally, each processor stores the DIAGONAL part, and the OFF-DIAGONAL
4050: part as `MATSEQAIJ` matrices. For example, proc1 will store [E] as a `MATSEQAIJ`
4051: matrix, and [DF] as another `MATSEQAIJ` matrix.
4053: When `d_nz`, `o_nz` parameters are specified, `d_nz` storage elements are
4054: allocated for every row of the local DIAGONAL submatrix, and `o_nz`
4055: storage locations are allocated for every row of the OFF-DIAGONAL submatrix.
4056: One way to choose `d_nz` and `o_nz` is to use the maximum number of nonzeros over
4057: the local rows for each of the local DIAGONAL, and the OFF-DIAGONAL submatrices.
4058: In this case, the values of `d_nz`, `o_nz` are
4059: .vb
4060: proc0 dnz = 2, o_nz = 2
4061: proc1 dnz = 3, o_nz = 2
4062: proc2 dnz = 1, o_nz = 4
4063: .ve
4064: We are allocating `m`*(`d_nz`+`o_nz`) storage locations for every proc. This
4065: translates to 3*(2+2)=12 for proc0, 3*(3+2)=15 for proc1, 2*(1+4)=10
4066: for proc3. i.e we are using 12+15+10=37 storage locations to store
4067: 34 values.
4069: When `d_nnz`, `o_nnz` parameters are specified, the storage is specified
4070: for every row, corresponding to both DIAGONAL and OFF-DIAGONAL submatrices.
4071: In the above case the values for `d_nnz`, `o_nnz` are
4072: .vb
4073: proc0 d_nnz = [2,2,2] and o_nnz = [2,2,2]
4074: proc1 d_nnz = [3,3,2] and o_nnz = [2,1,1]
4075: proc2 d_nnz = [1,1] and o_nnz = [4,4]
4076: .ve
4077: Here the space allocated is sum of all the above values i.e 34, and
4078: hence pre-allocation is perfect.
4080: Level: intermediate
4082: Notes:
4083: If the *_nnz parameter is given then the *_nz parameter is ignored
4085: The `MATAIJ` format, also called compressed row storage (CSR), is compatible with standard Fortran
4086: storage. The stored row and column indices begin with zero.
4087: See [Sparse Matrices](sec_matsparse) for details.
4089: The parallel matrix is partitioned such that the first m0 rows belong to
4090: process 0, the next m1 rows belong to process 1, the next m2 rows belong
4091: to process 2 etc.. where m0,m1,m2... are the input parameter 'm'.
4093: The DIAGONAL portion of the local submatrix of a processor can be defined
4094: as the submatrix which is obtained by extraction the part corresponding to
4095: the rows r1-r2 and columns c1-c2 of the global matrix, where r1 is the
4096: first row that belongs to the processor, r2 is the last row belonging to
4097: the this processor, and c1-c2 is range of indices of the local part of a
4098: vector suitable for applying the matrix to. This is an mxn matrix. In the
4099: common case of a square matrix, the row and column ranges are the same and
4100: the DIAGONAL part is also square. The remaining portion of the local
4101: submatrix (mxN) constitute the OFF-DIAGONAL portion.
4103: If `o_nnz` and `d_nnz` are specified, then `o_nz` and `d_nz` are ignored.
4105: You can call `MatGetInfo()` to get information on how effective the preallocation was;
4106: for example the fields mallocs,nz_allocated,nz_used,nz_unneeded;
4107: You can also run with the option `-info` and look for messages with the string
4108: malloc in them to see if additional memory allocation was needed.
4110: .seealso: [](ch_matrices), `Mat`, [Sparse Matrices](sec_matsparse), `MATMPIAIJ`, `MATAIJ`, `MatCreate()`, `MatCreateSeqAIJ()`, `MatSetValues()`, `MatCreateAIJ()`, `MatMPIAIJSetPreallocationCSR()`,
4111: `MatGetInfo()`, `PetscSplitOwnership()`, `MatSetPreallocationCOO()`, `MatSetValuesCOO()`
4112: @*/
4113: PetscErrorCode MatMPIAIJSetPreallocation(Mat B, PetscInt d_nz, const PetscInt d_nnz[], PetscInt o_nz, const PetscInt o_nnz[])
4114: {
4115: PetscFunctionBegin;
4118: PetscTryMethod(B, "MatMPIAIJSetPreallocation_C", (Mat, PetscInt, const PetscInt[], PetscInt, const PetscInt[]), (B, d_nz, d_nnz, o_nz, o_nnz));
4119: PetscFunctionReturn(PETSC_SUCCESS);
4120: }
4122: /*@
4123: MatCreateMPIAIJWithArrays - creates a `MATMPIAIJ` matrix using arrays that contain in standard
4124: CSR format for the local rows.
4126: Collective
4128: Input Parameters:
4129: + comm - MPI communicator
4130: . m - number of local rows (Cannot be `PETSC_DECIDE`)
4131: . n - This value should be the same as the local size used in creating the
4132: x vector for the matrix-vector product $y = Ax$. (or `PETSC_DECIDE` to have
4133: calculated if `N` is given) For square matrices n is almost always `m`.
4134: . M - number of global rows (or `PETSC_DETERMINE` to have calculated if `m` is given)
4135: . N - number of global columns (or `PETSC_DETERMINE` to have calculated if `n` is given)
4136: . 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
4137: . j - global column indices
4138: - a - optional matrix values
4140: Output Parameter:
4141: . mat - the matrix
4143: Level: intermediate
4145: Notes:
4146: The `i`, `j`, and `a` arrays ARE copied by this routine into the internal format used by PETSc;
4147: thus you CANNOT change the matrix entries by changing the values of `a[]` after you have
4148: called this routine. Use `MatCreateMPIAIJWithSplitArrays()` to avoid needing to copy the arrays.
4150: The `i` and `j` indices are 0 based, and `i` indices are indices corresponding to the local `j` array.
4152: Once you have created the matrix you can update it with new numerical values using `MatUpdateMPIAIJWithArray()`
4154: If you do **not** use `MatUpdateMPIAIJWithArray()`, the column indices in `j` do not need to be sorted. If you will use
4155: `MatUpdateMPIAIJWithArrays()`, the column indices **must** be sorted.
4157: The format which is used for the sparse matrix input, is equivalent to a
4158: row-major ordering, i.e., for the following matrix, the input data expected is
4159: as shown
4160: .vb
4161: 1 0 0
4162: 2 0 3 P0
4163: -------
4164: 4 5 6 P1
4166: Process0 [P0] rows_owned=[0,1]
4167: i = {0,1,3} [size = nrow+1 = 2+1]
4168: j = {0,0,2} [size = 3]
4169: v = {1,2,3} [size = 3]
4171: Process1 [P1] rows_owned=[2]
4172: i = {0,3} [size = nrow+1 = 1+1]
4173: j = {0,1,2} [size = 3]
4174: v = {4,5,6} [size = 3]
4175: .ve
4177: .seealso: [](ch_matrices), `Mat`, `MatCreate()`, `MatCreateSeqAIJ()`, `MatSetValues()`, `MatMPIAIJSetPreallocation()`, `MatMPIAIJSetPreallocationCSR()`,
4178: `MATMPIAIJ`, `MatCreateAIJ()`, `MatCreateMPIAIJWithSplitArrays()`, `MatUpdateMPIAIJWithArray()`, `MatSetPreallocationCOO()`, `MatSetValuesCOO()`
4179: @*/
4180: PetscErrorCode MatCreateMPIAIJWithArrays(MPI_Comm comm, PetscInt m, PetscInt n, PetscInt M, PetscInt N, const PetscInt i[], const PetscInt j[], const PetscScalar a[], Mat *mat)
4181: {
4182: PetscFunctionBegin;
4183: PetscCheck(!i || !i[0], PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "i (row indices) must start with 0");
4184: PetscCheck(m >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "local number of rows (m) cannot be PETSC_DECIDE, or negative");
4185: PetscCall(MatCreate(comm, mat));
4186: PetscCall(MatSetSizes(*mat, m, n, M, N));
4187: /* PetscCall(MatSetBlockSizes(M,bs,cbs)); */
4188: PetscCall(MatSetType(*mat, MATMPIAIJ));
4189: PetscCall(MatMPIAIJSetPreallocationCSR(*mat, i, j, a));
4190: PetscFunctionReturn(PETSC_SUCCESS);
4191: }
4193: /*@
4194: MatUpdateMPIAIJWithArrays - updates a `MATMPIAIJ` matrix using arrays that contain in standard
4195: CSR format for the local rows. Only the numerical values are updated the other arrays must be identical to what was passed
4196: from `MatCreateMPIAIJWithArrays()`
4198: Deprecated: Use `MatUpdateMPIAIJWithArray()`
4200: Collective
4202: Input Parameters:
4203: + mat - the matrix
4204: . m - number of local rows (Cannot be `PETSC_DECIDE`)
4205: . n - This value should be the same as the local size used in creating the
4206: x vector for the matrix-vector product y = Ax. (or `PETSC_DECIDE` to have
4207: calculated if N is given) For square matrices n is almost always m.
4208: . M - number of global rows (or `PETSC_DETERMINE` to have calculated if m is given)
4209: . N - number of global columns (or `PETSC_DETERMINE` to have calculated if n is given)
4210: . Ii - row indices; that is Ii[0] = 0, Ii[row] = Ii[row-1] + number of elements in that row of the matrix
4211: . J - column indices
4212: - v - matrix values
4214: Level: deprecated
4216: .seealso: [](ch_matrices), `Mat`, `MATMPIAIJ`, `MatCreate()`, `MatCreateSeqAIJ()`, `MatSetValues()`, `MatMPIAIJSetPreallocation()`, `MatMPIAIJSetPreallocationCSR()`,
4217: `MatCreateAIJ()`, `MatCreateMPIAIJWithSplitArrays()`, `MatUpdateMPIAIJWithArray()`, `MatSetPreallocationCOO()`, `MatSetValuesCOO()`
4218: @*/
4219: PetscErrorCode MatUpdateMPIAIJWithArrays(Mat mat, PetscInt m, PetscInt n, PetscInt M, PetscInt N, const PetscInt Ii[], const PetscInt J[], const PetscScalar v[])
4220: {
4221: PetscInt nnz, i;
4222: PetscBool nooffprocentries;
4223: Mat_MPIAIJ *Aij = (Mat_MPIAIJ *)mat->data;
4224: Mat_SeqAIJ *Ad = (Mat_SeqAIJ *)Aij->A->data;
4225: PetscScalar *ad, *ao;
4226: PetscInt ldi, Iii, md;
4227: const PetscInt *Adi = Ad->i;
4228: PetscInt *ld = Aij->ld;
4230: PetscFunctionBegin;
4231: PetscCheck(Ii[0] == 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "i (row indices) must start with 0");
4232: PetscCheck(m >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "local number of rows (m) cannot be PETSC_DECIDE, or negative");
4233: PetscCheck(m == mat->rmap->n, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Local number of rows cannot change from call to MatUpdateMPIAIJWithArrays()");
4234: PetscCheck(n == mat->cmap->n, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Local number of columns cannot change from call to MatUpdateMPIAIJWithArrays()");
4236: PetscCall(MatSeqAIJGetArrayWrite(Aij->A, &ad));
4237: PetscCall(MatSeqAIJGetArrayWrite(Aij->B, &ao));
4239: for (i = 0; i < m; i++) {
4240: if (PetscDefined(USE_DEBUG)) {
4241: for (PetscInt j = Ii[i] + 1; j < Ii[i + 1]; ++j) {
4242: 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);
4243: 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);
4244: }
4245: }
4246: nnz = Ii[i + 1] - Ii[i];
4247: Iii = Ii[i];
4248: ldi = ld[i];
4249: md = Adi[i + 1] - Adi[i];
4250: PetscCall(PetscArraycpy(ao, v + Iii, ldi));
4251: PetscCall(PetscArraycpy(ad, v + Iii + ldi, md));
4252: PetscCall(PetscArraycpy(ao + ldi, v + Iii + ldi + md, nnz - ldi - md));
4253: ad += md;
4254: ao += nnz - md;
4255: }
4256: nooffprocentries = mat->nooffprocentries;
4257: mat->nooffprocentries = PETSC_TRUE;
4258: PetscCall(MatSeqAIJRestoreArrayWrite(Aij->A, &ad));
4259: PetscCall(MatSeqAIJRestoreArrayWrite(Aij->B, &ao));
4260: PetscCall(PetscObjectStateIncrease((PetscObject)Aij->A));
4261: PetscCall(PetscObjectStateIncrease((PetscObject)Aij->B));
4262: PetscCall(PetscObjectStateIncrease((PetscObject)mat));
4263: PetscCall(MatAssemblyBegin(mat, MAT_FINAL_ASSEMBLY));
4264: PetscCall(MatAssemblyEnd(mat, MAT_FINAL_ASSEMBLY));
4265: mat->nooffprocentries = nooffprocentries;
4266: PetscFunctionReturn(PETSC_SUCCESS);
4267: }
4269: /*@
4270: MatUpdateMPIAIJWithArray - updates an `MATMPIAIJ` matrix using an array that contains the nonzero values
4272: Collective
4274: Input Parameters:
4275: + mat - the matrix
4276: - v - matrix values, stored by row
4278: Level: intermediate
4280: Notes:
4281: The matrix must have been obtained with `MatCreateMPIAIJWithArrays()` or `MatMPIAIJSetPreallocationCSR()`
4283: The column indices in the call to `MatCreateMPIAIJWithArrays()` or `MatMPIAIJSetPreallocationCSR()` must have been sorted for this call to work correctly
4285: .seealso: [](ch_matrices), `Mat`, `MatCreate()`, `MatCreateSeqAIJ()`, `MatSetValues()`, `MatMPIAIJSetPreallocation()`, `MatMPIAIJSetPreallocationCSR()`,
4286: `MATMPIAIJ`, `MatCreateAIJ()`, `MatCreateMPIAIJWithSplitArrays()`, `MatUpdateMPIAIJWithArrays()`, `MatSetPreallocationCOO()`, `MatSetValuesCOO()`
4287: @*/
4288: PetscErrorCode MatUpdateMPIAIJWithArray(Mat mat, const PetscScalar v[])
4289: {
4290: PetscInt nnz, i, m;
4291: PetscBool nooffprocentries;
4292: Mat_MPIAIJ *Aij = (Mat_MPIAIJ *)mat->data;
4293: Mat_SeqAIJ *Ad = (Mat_SeqAIJ *)Aij->A->data;
4294: Mat_SeqAIJ *Ao = (Mat_SeqAIJ *)Aij->B->data;
4295: PetscScalar *ad, *ao;
4296: const PetscInt *Adi = Ad->i, *Adj = Ao->i;
4297: PetscInt ldi, Iii, md;
4298: PetscInt *ld = Aij->ld;
4300: PetscFunctionBegin;
4301: m = mat->rmap->n;
4303: PetscCall(MatSeqAIJGetArrayWrite(Aij->A, &ad));
4304: PetscCall(MatSeqAIJGetArrayWrite(Aij->B, &ao));
4305: Iii = 0;
4306: for (i = 0; i < m; i++) {
4307: nnz = Adi[i + 1] - Adi[i] + Adj[i + 1] - Adj[i];
4308: ldi = ld[i];
4309: md = Adi[i + 1] - Adi[i];
4310: PetscCall(PetscArraycpy(ad, v + Iii + ldi, md));
4311: ad += md;
4312: if (ao) {
4313: PetscCall(PetscArraycpy(ao, v + Iii, ldi));
4314: PetscCall(PetscArraycpy(ao + ldi, v + Iii + ldi + md, nnz - ldi - md));
4315: ao += nnz - md;
4316: }
4317: Iii += nnz;
4318: }
4319: nooffprocentries = mat->nooffprocentries;
4320: mat->nooffprocentries = PETSC_TRUE;
4321: PetscCall(MatSeqAIJRestoreArrayWrite(Aij->A, &ad));
4322: PetscCall(MatSeqAIJRestoreArrayWrite(Aij->B, &ao));
4323: PetscCall(PetscObjectStateIncrease((PetscObject)Aij->A));
4324: PetscCall(PetscObjectStateIncrease((PetscObject)Aij->B));
4325: PetscCall(PetscObjectStateIncrease((PetscObject)mat));
4326: PetscCall(MatAssemblyBegin(mat, MAT_FINAL_ASSEMBLY));
4327: PetscCall(MatAssemblyEnd(mat, MAT_FINAL_ASSEMBLY));
4328: mat->nooffprocentries = nooffprocentries;
4329: PetscFunctionReturn(PETSC_SUCCESS);
4330: }
4332: /*@
4333: MatCreateAIJ - Creates a sparse parallel matrix in `MATAIJ` format
4334: (the default parallel PETSc format). For good matrix assembly performance
4335: the user should preallocate the matrix storage by setting the parameters
4336: `d_nz` (or `d_nnz`) and `o_nz` (or `o_nnz`).
4338: Collective
4340: Input Parameters:
4341: + comm - MPI communicator
4342: . m - number of local rows (or `PETSC_DECIDE` to have calculated if M is given)
4343: This value should be the same as the local size used in creating the
4344: y vector for the matrix-vector product y = Ax.
4345: . n - This value should be the same as the local size used in creating the
4346: x vector for the matrix-vector product y = Ax. (or `PETSC_DECIDE` to have
4347: calculated if N is given) For square matrices n is almost always m.
4348: . M - number of global rows (or `PETSC_DETERMINE` to have calculated if m is given)
4349: . N - number of global columns (or `PETSC_DETERMINE` to have calculated if n is given)
4350: . d_nz - number of nonzeros per row in DIAGONAL portion of local submatrix
4351: (same value is used for all local rows)
4352: . d_nnz - array containing the number of nonzeros in the various rows of the
4353: DIAGONAL portion of the local submatrix (possibly different for each row)
4354: or `NULL`, if `d_nz` is used to specify the nonzero structure.
4355: The size of this array is equal to the number of local rows, i.e 'm'.
4356: . o_nz - number of nonzeros per row in the OFF-DIAGONAL portion of local
4357: submatrix (same value is used for all local rows).
4358: - o_nnz - array containing the number of nonzeros in the various rows of the
4359: OFF-DIAGONAL portion of the local submatrix (possibly different for
4360: each row) or `NULL`, if `o_nz` is used to specify the nonzero
4361: structure. The size of this array is equal to the number
4362: of local rows, i.e 'm'.
4364: Output Parameter:
4365: . A - the matrix
4367: Options Database Keys:
4368: + -mat_no_inode - Do not use inodes
4369: . -mat_inode_limit limit - Sets inode limit (max limit=5)
4370: - -matmult_vecscatter_view viewer - View the vecscatter (i.e., communication pattern) used in `MatMult()` of sparse parallel matrices.
4371: See viewer types in manual of `MatView()`. Of them, ascii_matlab, draw or binary cause the `VecScatter`
4372: 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.
4374: Level: intermediate
4376: Notes:
4377: It is recommended that one use `MatCreateFromOptions()` or the `MatCreate()`, `MatSetType()` and/or `MatSetFromOptions()`,
4378: MatXXXXSetPreallocation() paradigm instead of this routine directly.
4379: [MatXXXXSetPreallocation() is, for example, `MatSeqAIJSetPreallocation()`]
4381: If the *_nnz parameter is given then the *_nz parameter is ignored
4383: The `m`,`n`,`M`,`N` parameters specify the size of the matrix, and its partitioning across
4384: processors, while `d_nz`,`d_nnz`,`o_nz`,`o_nnz` parameters specify the approximate
4385: storage requirements for this matrix.
4387: If `PETSC_DECIDE` or `PETSC_DETERMINE` is used for a particular argument on one
4388: processor than it must be used on all processors that share the object for
4389: that argument.
4391: If `m` and `n` are not `PETSC_DECIDE`, then the values determine the `PetscLayout` of the matrix and the ranges returned by
4392: `MatGetOwnershipRange()`, `MatGetOwnershipRanges()`, `MatGetOwnershipRangeColumn()`, and `MatGetOwnershipRangesColumn()`.
4394: The user MUST specify either the local or global matrix dimensions
4395: (possibly both).
4397: The parallel matrix is partitioned across processors such that the
4398: first `m0` rows belong to process 0, the next `m1` rows belong to
4399: process 1, the next `m2` rows belong to process 2, etc., where
4400: `m0`, `m1`, `m2`... are the input parameter `m` on each MPI process. I.e., each MPI process stores
4401: values corresponding to [m x N] submatrix.
4403: The columns are logically partitioned with the n0 columns belonging
4404: to 0th partition, the next n1 columns belonging to the next
4405: partition etc.. where n0,n1,n2... are the input parameter 'n'.
4407: The DIAGONAL portion of the local submatrix on any given processor
4408: is the submatrix corresponding to the rows and columns m,n
4409: corresponding to the given processor. i.e diagonal matrix on
4410: process 0 is [m0 x n0], diagonal matrix on process 1 is [m1 x n1]
4411: etc. The remaining portion of the local submatrix [m x (N-n)]
4412: constitute the OFF-DIAGONAL portion. The example below better
4413: illustrates this concept. The two matrices, the DIAGONAL portion and
4414: the OFF-DIAGONAL portion are each stored as `MATSEQAIJ` matrices.
4416: For a square global matrix we define each processor's diagonal portion
4417: to be its local rows and the corresponding columns (a square submatrix);
4418: each processor's off-diagonal portion encompasses the remainder of the
4419: local matrix (a rectangular submatrix).
4421: If `o_nnz`, `d_nnz` are specified, then `o_nz`, and `d_nz` are ignored.
4423: When calling this routine with a single process communicator, a matrix of
4424: type `MATSEQAIJ` is returned. If a matrix of type `MATMPIAIJ` is desired for this
4425: type of communicator, use the construction mechanism
4426: .vb
4427: MatCreate(..., &A);
4428: MatSetType(A, MATMPIAIJ);
4429: MatSetSizes(A, m, n, M, N);
4430: MatMPIAIJSetPreallocation(A, ...);
4431: .ve
4433: By default, this format uses inodes (identical nodes) when possible.
4434: We search for consecutive rows with the same nonzero structure, thereby
4435: reusing matrix information to achieve increased efficiency.
4437: Example Usage:
4438: Consider the following 8x8 matrix with 34 non-zero values, that is
4439: assembled across 3 processors. Lets assume that proc0 owns 3 rows,
4440: proc1 owns 3 rows, proc2 owns 2 rows. This division can be shown
4441: as follows
4443: .vb
4444: 1 2 0 | 0 3 0 | 0 4
4445: Proc0 0 5 6 | 7 0 0 | 8 0
4446: 9 0 10 | 11 0 0 | 12 0
4447: -------------------------------------
4448: 13 0 14 | 15 16 17 | 0 0
4449: Proc1 0 18 0 | 19 20 21 | 0 0
4450: 0 0 0 | 22 23 0 | 24 0
4451: -------------------------------------
4452: Proc2 25 26 27 | 0 0 28 | 29 0
4453: 30 0 0 | 31 32 33 | 0 34
4454: .ve
4456: This can be represented as a collection of submatrices as
4458: .vb
4459: A B C
4460: D E F
4461: G H I
4462: .ve
4464: Where the submatrices A,B,C are owned by proc0, D,E,F are
4465: owned by proc1, G,H,I are owned by proc2.
4467: The 'm' parameters for proc0,proc1,proc2 are 3,3,2 respectively.
4468: The 'n' parameters for proc0,proc1,proc2 are 3,3,2 respectively.
4469: The 'M','N' parameters are 8,8, and have the same values on all procs.
4471: The DIAGONAL submatrices corresponding to proc0,proc1,proc2 are
4472: submatrices [A], [E], [I] respectively. The OFF-DIAGONAL submatrices
4473: corresponding to proc0,proc1,proc2 are [BC], [DF], [GH] respectively.
4474: Internally, each processor stores the DIAGONAL part, and the OFF-DIAGONAL
4475: part as `MATSEQAIJ` matrices. For example, proc1 will store [E] as a `MATSEQAIJ`
4476: matrix, and [DF] as another SeqAIJ matrix.
4478: When `d_nz`, `o_nz` parameters are specified, `d_nz` storage elements are
4479: allocated for every row of the local DIAGONAL submatrix, and `o_nz`
4480: storage locations are allocated for every row of the OFF-DIAGONAL submatrix.
4481: One way to choose `d_nz` and `o_nz` is to use the maximum number of nonzeros over
4482: the local rows for each of the local DIAGONAL, and the OFF-DIAGONAL submatrices.
4483: In this case, the values of `d_nz`,`o_nz` are
4484: .vb
4485: proc0 dnz = 2, o_nz = 2
4486: proc1 dnz = 3, o_nz = 2
4487: proc2 dnz = 1, o_nz = 4
4488: .ve
4489: We are allocating m*(`d_nz`+`o_nz`) storage locations for every proc. This
4490: translates to 3*(2+2)=12 for proc0, 3*(3+2)=15 for proc1, 2*(1+4)=10
4491: for proc3. i.e we are using 12+15+10=37 storage locations to store
4492: 34 values.
4494: When `d_nnz`, `o_nnz` parameters are specified, the storage is specified
4495: for every row, corresponding to both DIAGONAL and OFF-DIAGONAL submatrices.
4496: In the above case the values for d_nnz,o_nnz are
4497: .vb
4498: proc0 d_nnz = [2,2,2] and o_nnz = [2,2,2]
4499: proc1 d_nnz = [3,3,2] and o_nnz = [2,1,1]
4500: proc2 d_nnz = [1,1] and o_nnz = [4,4]
4501: .ve
4502: Here the space allocated is sum of all the above values i.e 34, and
4503: hence pre-allocation is perfect.
4505: .seealso: [](ch_matrices), `Mat`, [Sparse Matrix Creation](sec_matsparse), `MatCreate()`, `MatCreateSeqAIJ()`, `MatSetValues()`, `MatMPIAIJSetPreallocation()`, `MatMPIAIJSetPreallocationCSR()`,
4506: `MATMPIAIJ`, `MatCreateMPIAIJWithArrays()`, `MatGetOwnershipRange()`, `MatGetOwnershipRanges()`, `MatGetOwnershipRangeColumn()`,
4507: `MatGetOwnershipRangesColumn()`, `PetscLayout`
4508: @*/
4509: 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)
4510: {
4511: PetscMPIInt size;
4513: PetscFunctionBegin;
4514: PetscCall(MatCreate(comm, A));
4515: PetscCall(MatSetSizes(*A, m, n, M, N));
4516: PetscCallMPI(MPI_Comm_size(comm, &size));
4517: if (size > 1) {
4518: PetscCall(MatSetType(*A, MATMPIAIJ));
4519: PetscCall(MatMPIAIJSetPreallocation(*A, d_nz, d_nnz, o_nz, o_nnz));
4520: } else {
4521: PetscCall(MatSetType(*A, MATSEQAIJ));
4522: PetscCall(MatSeqAIJSetPreallocation(*A, d_nz, d_nnz));
4523: }
4524: PetscFunctionReturn(PETSC_SUCCESS);
4525: }
4527: /*@
4528: MatMPIAIJGetSeqAIJ - Returns the local pieces of this distributed matrix
4530: Not Collective
4532: Input Parameter:
4533: . A - The `MATMPIAIJ` matrix
4535: Output Parameters:
4536: + Ad - The local diagonal block as a `MATSEQAIJ` matrix
4537: . Ao - The local off-diagonal block as a `MATSEQAIJ` matrix
4538: - colmap - An array mapping local column numbers of `Ao` to global column numbers of the parallel matrix
4540: Level: intermediate
4542: Note:
4543: The rows in `Ad` and `Ao` are in [0, Nr), where Nr is the number of local rows on this process. The columns
4544: 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
4545: the number of nonzero columns in the local off-diagonal piece of the matrix `A`. The array colmap maps these
4546: local column numbers to global column numbers in the original matrix.
4548: .seealso: [](ch_matrices), `Mat`, `MATMPIAIJ`, `MatMPIAIJGetLocalMat()`, `MatMPIAIJGetLocalMatCondensed()`, `MatCreateAIJ()`, `MATSEQAIJ`
4549: @*/
4550: PetscErrorCode MatMPIAIJGetSeqAIJ(Mat A, Mat *Ad, Mat *Ao, const PetscInt *colmap[])
4551: {
4552: Mat_MPIAIJ *a = (Mat_MPIAIJ *)A->data;
4553: PetscBool flg;
4555: PetscFunctionBegin;
4556: PetscCall(PetscStrbeginswith(((PetscObject)A)->type_name, MATMPIAIJ, &flg));
4557: PetscCheck(flg, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "This function requires a MATMPIAIJ matrix as input");
4558: if (Ad) *Ad = a->A;
4559: if (Ao) *Ao = a->B;
4560: if (colmap) *colmap = a->garray;
4561: PetscFunctionReturn(PETSC_SUCCESS);
4562: }
4564: static PetscErrorCode MatGetMultPetscSF_MPIAIJ(Mat A, PetscSF *sf)
4565: {
4566: Mat_MPIAIJ *a = (Mat_MPIAIJ *)A->data;
4568: PetscFunctionBegin;
4569: *sf = a->Mvctx;
4570: PetscFunctionReturn(PETSC_SUCCESS);
4571: }
4573: PetscErrorCode MatCreateMPIMatConcatenateSeqMat_MPIAIJ(MPI_Comm comm, Mat inmat, PetscInt n, MatReuse scall, Mat *outmat)
4574: {
4575: PetscInt m, N, i, rstart, nnz, Ii;
4576: PetscInt *indx;
4577: PetscScalar *values;
4578: MatType rootType;
4580: PetscFunctionBegin;
4581: PetscCall(MatGetSize(inmat, &m, &N));
4582: if (scall == MAT_INITIAL_MATRIX) { /* symbolic phase */
4583: PetscInt *dnz, *onz, sum, bs, cbs;
4585: if (n == PETSC_DECIDE) PetscCall(PetscSplitOwnership(comm, &n, &N));
4586: /* Check sum(n) = N */
4587: PetscCallMPI(MPIU_Allreduce(&n, &sum, 1, MPIU_INT, MPI_SUM, comm));
4588: PetscCheck(sum == N, PETSC_COMM_SELF, PETSC_ERR_ARG_INCOMP, "Sum of local columns %" PetscInt_FMT " != global columns %" PetscInt_FMT, sum, N);
4590: PetscCallMPI(MPI_Scan(&m, &rstart, 1, MPIU_INT, MPI_SUM, comm));
4591: rstart -= m;
4593: MatPreallocateBegin(comm, m, n, dnz, onz);
4594: for (i = 0; i < m; i++) {
4595: PetscCall(MatGetRow_SeqAIJ(inmat, i, &nnz, &indx, NULL));
4596: PetscCall(MatPreallocateSet(i + rstart, nnz, indx, dnz, onz));
4597: PetscCall(MatRestoreRow_SeqAIJ(inmat, i, &nnz, &indx, NULL));
4598: }
4600: PetscCall(MatCreate(comm, outmat));
4601: PetscCall(MatSetSizes(*outmat, m, n, PETSC_DETERMINE, PETSC_DETERMINE));
4602: PetscCall(MatGetBlockSizes(inmat, &bs, &cbs));
4603: PetscCall(MatSetBlockSizes(*outmat, bs, cbs));
4604: PetscCall(MatGetRootType_Private(inmat, &rootType));
4605: PetscCall(MatSetType(*outmat, rootType));
4606: PetscCall(MatSeqAIJSetPreallocation(*outmat, 0, dnz));
4607: PetscCall(MatMPIAIJSetPreallocation(*outmat, 0, dnz, 0, onz));
4608: MatPreallocateEnd(dnz, onz);
4609: PetscCall(MatSetOption(*outmat, MAT_NO_OFF_PROC_ENTRIES, PETSC_TRUE));
4610: }
4612: /* numeric phase */
4613: PetscCall(MatGetOwnershipRange(*outmat, &rstart, NULL));
4614: for (i = 0; i < m; i++) {
4615: PetscCall(MatGetRow_SeqAIJ(inmat, i, &nnz, &indx, &values));
4616: Ii = i + rstart;
4617: PetscCall(MatSetValues(*outmat, 1, &Ii, nnz, indx, values, INSERT_VALUES));
4618: PetscCall(MatRestoreRow_SeqAIJ(inmat, i, &nnz, &indx, &values));
4619: }
4620: PetscCall(MatAssemblyBegin(*outmat, MAT_FINAL_ASSEMBLY));
4621: PetscCall(MatAssemblyEnd(*outmat, MAT_FINAL_ASSEMBLY));
4622: PetscFunctionReturn(PETSC_SUCCESS);
4623: }
4625: static PetscErrorCode MatMergeSeqsToMPIDestroy(PetscCtxRt data)
4626: {
4627: MatMergeSeqsToMPI *merge = *(MatMergeSeqsToMPI **)data;
4629: PetscFunctionBegin;
4630: if (!merge) PetscFunctionReturn(PETSC_SUCCESS);
4631: PetscCall(PetscFree(merge->id_r));
4632: PetscCall(PetscFree(merge->len_s));
4633: PetscCall(PetscFree(merge->len_r));
4634: PetscCall(PetscFree(merge->bi));
4635: PetscCall(PetscFree(merge->bj));
4636: PetscCall(PetscFree(merge->buf_ri[0]));
4637: PetscCall(PetscFree(merge->buf_ri));
4638: PetscCall(PetscFree(merge->buf_rj[0]));
4639: PetscCall(PetscFree(merge->buf_rj));
4640: PetscCall(PetscFree(merge->coi));
4641: PetscCall(PetscFree(merge->coj));
4642: PetscCall(PetscFree(merge->owners_co));
4643: PetscCall(PetscLayoutDestroy(&merge->rowmap));
4644: PetscCall(PetscFree(merge));
4645: PetscFunctionReturn(PETSC_SUCCESS);
4646: }
4648: #include <../src/mat/utils/freespace.h>
4650: /*@
4651: MatCreateMPIAIJSumSeqAIJNumeric - Fill the numerical values of an `MATMPIAIJ` matrix previously created by
4652: `MatCreateMPIAIJSumSeqAIJSymbolic()` by summing the local `MATSEQAIJ` contributions from each process.
4654: Collective
4656: Input Parameters:
4657: + seqmat - the local `MATSEQAIJ` contribution from this process
4658: - mpimat - the target `MATMPIAIJ` matrix created by `MatCreateMPIAIJSumSeqAIJSymbolic()`
4660: Level: developer
4662: .seealso: `Mat`, `MATMPIAIJ`, `MATSEQAIJ`, `MatCreateMPIAIJSumSeqAIJSymbolic()`, `MatCreateMPIAIJSumSeqAIJ()`
4663: @*/
4664: PetscErrorCode MatCreateMPIAIJSumSeqAIJNumeric(Mat seqmat, Mat mpimat)
4665: {
4666: MPI_Comm comm;
4667: Mat_SeqAIJ *a = (Mat_SeqAIJ *)seqmat->data;
4668: PetscMPIInt size, rank, taga, *len_s;
4669: PetscInt N = mpimat->cmap->N, i, j, *owners, *ai = a->i, *aj, m;
4670: PetscMPIInt proc, k;
4671: PetscInt **buf_ri, **buf_rj;
4672: PetscInt anzi, *bj_i, *bi, *bj, arow, bnzi, nextaj;
4673: PetscInt nrows, **buf_ri_k, **nextrow, **nextai;
4674: MPI_Request *s_waits, *r_waits;
4675: MPI_Status *status;
4676: const MatScalar *aa, *a_a;
4677: MatScalar **abuf_r, *ba_i;
4678: MatMergeSeqsToMPI *merge;
4679: PetscContainer container;
4681: PetscFunctionBegin;
4682: PetscCall(PetscObjectGetComm((PetscObject)mpimat, &comm));
4683: PetscCall(PetscLogEventBegin(MAT_Seqstompinum, seqmat, 0, 0, 0));
4685: PetscCallMPI(MPI_Comm_size(comm, &size));
4686: PetscCallMPI(MPI_Comm_rank(comm, &rank));
4688: PetscCall(PetscObjectQuery((PetscObject)mpimat, "MatMergeSeqsToMPI", (PetscObject *)&container));
4689: PetscCheck(container, PetscObjectComm((PetscObject)mpimat), PETSC_ERR_PLIB, "Mat not created from MatCreateMPIAIJSumSeqAIJSymbolic");
4690: PetscCall(PetscContainerGetPointer(container, &merge));
4691: PetscCall(MatSeqAIJGetArrayRead(seqmat, &a_a));
4692: aa = a_a;
4694: bi = merge->bi;
4695: bj = merge->bj;
4696: buf_ri = merge->buf_ri;
4697: buf_rj = merge->buf_rj;
4699: PetscCall(PetscMalloc1(size, &status));
4700: owners = merge->rowmap->range;
4701: len_s = merge->len_s;
4703: /* send and recv matrix values */
4704: PetscCall(PetscObjectGetNewTag((PetscObject)mpimat, &taga));
4705: PetscCall(PetscPostIrecvScalar(comm, taga, merge->nrecv, merge->id_r, merge->len_r, &abuf_r, &r_waits));
4707: PetscCall(PetscMalloc1(merge->nsend + 1, &s_waits));
4708: for (proc = 0, k = 0; proc < size; proc++) {
4709: if (!len_s[proc]) continue;
4710: i = owners[proc];
4711: PetscCallMPI(MPIU_Isend(aa + ai[i], len_s[proc], MPIU_MATSCALAR, proc, taga, comm, s_waits + k));
4712: k++;
4713: }
4715: if (merge->nrecv) PetscCallMPI(MPI_Waitall(merge->nrecv, r_waits, status));
4716: if (merge->nsend) PetscCallMPI(MPI_Waitall(merge->nsend, s_waits, status));
4717: PetscCall(PetscFree(status));
4719: PetscCall(PetscFree(s_waits));
4720: PetscCall(PetscFree(r_waits));
4722: /* insert mat values of mpimat */
4723: PetscCall(PetscMalloc1(N, &ba_i));
4724: PetscCall(PetscMalloc3(merge->nrecv, &buf_ri_k, merge->nrecv, &nextrow, merge->nrecv, &nextai));
4726: for (k = 0; k < merge->nrecv; k++) {
4727: buf_ri_k[k] = buf_ri[k]; /* beginning of k-th recved i-structure */
4728: nrows = *buf_ri_k[k];
4729: nextrow[k] = buf_ri_k[k] + 1; /* next row number of k-th recved i-structure */
4730: nextai[k] = buf_ri_k[k] + (nrows + 1); /* points to the next i-structure of k-th recved i-structure */
4731: }
4733: /* set values of ba */
4734: m = merge->rowmap->n;
4735: for (i = 0; i < m; i++) {
4736: arow = owners[rank] + i;
4737: bj_i = bj + bi[i]; /* col indices of the i-th row of mpimat */
4738: bnzi = bi[i + 1] - bi[i];
4739: PetscCall(PetscArrayzero(ba_i, bnzi));
4741: /* add local non-zero vals of this proc's seqmat into ba */
4742: anzi = ai[arow + 1] - ai[arow];
4743: aj = a->j + ai[arow];
4744: aa = a_a + ai[arow];
4745: nextaj = 0;
4746: for (j = 0; nextaj < anzi; j++) {
4747: if (*(bj_i + j) == aj[nextaj]) { /* bcol == acol */
4748: ba_i[j] += aa[nextaj++];
4749: }
4750: }
4752: /* add received vals into ba */
4753: for (k = 0; k < merge->nrecv; k++) { /* k-th received message */
4754: /* i-th row */
4755: if (i == *nextrow[k]) {
4756: anzi = *(nextai[k] + 1) - *nextai[k];
4757: aj = buf_rj[k] + *nextai[k];
4758: aa = abuf_r[k] + *nextai[k];
4759: nextaj = 0;
4760: for (j = 0; nextaj < anzi; j++) {
4761: if (*(bj_i + j) == aj[nextaj]) { /* bcol == acol */
4762: ba_i[j] += aa[nextaj++];
4763: }
4764: }
4765: nextrow[k]++;
4766: nextai[k]++;
4767: }
4768: }
4769: PetscCall(MatSetValues(mpimat, 1, &arow, bnzi, bj_i, ba_i, INSERT_VALUES));
4770: }
4771: PetscCall(MatSeqAIJRestoreArrayRead(seqmat, &a_a));
4772: PetscCall(MatAssemblyBegin(mpimat, MAT_FINAL_ASSEMBLY));
4773: PetscCall(MatAssemblyEnd(mpimat, MAT_FINAL_ASSEMBLY));
4775: PetscCall(PetscFree(abuf_r[0]));
4776: PetscCall(PetscFree(abuf_r));
4777: PetscCall(PetscFree(ba_i));
4778: PetscCall(PetscFree3(buf_ri_k, nextrow, nextai));
4779: PetscCall(PetscLogEventEnd(MAT_Seqstompinum, seqmat, 0, 0, 0));
4780: PetscFunctionReturn(PETSC_SUCCESS);
4781: }
4783: /*@
4784: MatCreateMPIAIJSumSeqAIJSymbolic - Create the symbolic (nonzero-pattern) portion of an `MATMPIAIJ` matrix
4785: obtained by summing local `MATSEQAIJ` contributions from each process.
4787: Collective
4789: Input Parameters:
4790: + comm - the communicator
4791: . seqmat - the local `MATSEQAIJ` contribution from this process
4792: . m - the number of local rows for the resulting `MATMPIAIJ` matrix, or `PETSC_DECIDE`
4793: - n - the number of local columns for the resulting `MATMPIAIJ` matrix, or `PETSC_DECIDE`
4795: Output Parameter:
4796: . mpimat - the newly created `MATMPIAIJ` matrix
4798: Level: developer
4800: Note:
4801: The numerical values are filled in by a subsequent call to `MatCreateMPIAIJSumSeqAIJNumeric()`.
4803: .seealso: `Mat`, `MATMPIAIJ`, `MATSEQAIJ`, `MatCreateMPIAIJSumSeqAIJNumeric()`, `MatCreateMPIAIJSumSeqAIJ()`
4804: @*/
4805: PetscErrorCode MatCreateMPIAIJSumSeqAIJSymbolic(MPI_Comm comm, Mat seqmat, PetscInt m, PetscInt n, Mat *mpimat)
4806: {
4807: Mat B_mpi;
4808: Mat_SeqAIJ *a = (Mat_SeqAIJ *)seqmat->data;
4809: PetscMPIInt size, rank, tagi, tagj, *len_s, *len_si, *len_ri;
4810: PetscInt **buf_rj, **buf_ri, **buf_ri_k;
4811: PetscInt M = seqmat->rmap->n, N = seqmat->cmap->n, i, *owners, *ai = a->i, *aj = a->j;
4812: PetscInt len, *dnz, *onz, bs, cbs;
4813: PetscInt k, anzi, *bi, *bj, *lnk, nlnk, arow, bnzi;
4814: PetscInt nrows, *buf_s, *buf_si, *buf_si_i, **nextrow, **nextai;
4815: MPI_Request *si_waits, *sj_waits, *ri_waits, *rj_waits;
4816: MPI_Status *status;
4817: PetscFreeSpaceList free_space = NULL, current_space = NULL;
4818: PetscBT lnkbt;
4819: MatMergeSeqsToMPI *merge;
4820: PetscContainer container;
4822: PetscFunctionBegin;
4823: PetscCall(PetscLogEventBegin(MAT_Seqstompisym, seqmat, 0, 0, 0));
4825: /* make sure it is a PETSc comm */
4826: PetscCall(PetscCommDuplicate(comm, &comm, NULL));
4827: PetscCallMPI(MPI_Comm_size(comm, &size));
4828: PetscCallMPI(MPI_Comm_rank(comm, &rank));
4830: PetscCall(PetscNew(&merge));
4831: PetscCall(PetscMalloc1(size, &status));
4833: /* determine row ownership */
4834: PetscCall(PetscLayoutCreate(comm, &merge->rowmap));
4835: PetscCall(PetscLayoutSetLocalSize(merge->rowmap, m));
4836: PetscCall(PetscLayoutSetSize(merge->rowmap, M));
4837: PetscCall(PetscLayoutSetBlockSize(merge->rowmap, 1));
4838: PetscCall(PetscLayoutSetUp(merge->rowmap));
4839: PetscCall(PetscMalloc1(size, &len_si));
4840: PetscCall(PetscMalloc1(size, &merge->len_s));
4842: m = merge->rowmap->n;
4843: owners = merge->rowmap->range;
4845: /* determine the number of messages to send, their lengths */
4846: len_s = merge->len_s;
4848: len = 0; /* length of buf_si[] */
4849: merge->nsend = 0;
4850: for (PetscMPIInt proc = 0; proc < size; proc++) {
4851: len_si[proc] = 0;
4852: if (proc == rank) {
4853: len_s[proc] = 0;
4854: } else {
4855: PetscCall(PetscMPIIntCast(owners[proc + 1] - owners[proc] + 1, &len_si[proc]));
4856: PetscCall(PetscMPIIntCast(ai[owners[proc + 1]] - ai[owners[proc]], &len_s[proc])); /* num of rows to be sent to [proc] */
4857: }
4858: if (len_s[proc]) {
4859: merge->nsend++;
4860: nrows = 0;
4861: for (i = owners[proc]; i < owners[proc + 1]; i++) {
4862: if (ai[i + 1] > ai[i]) nrows++;
4863: }
4864: PetscCall(PetscMPIIntCast(2 * (nrows + 1), &len_si[proc]));
4865: len += len_si[proc];
4866: }
4867: }
4869: /* determine the number and length of messages to receive for ij-structure */
4870: PetscCall(PetscGatherNumberOfMessages(comm, NULL, len_s, &merge->nrecv));
4871: PetscCall(PetscGatherMessageLengths2(comm, merge->nsend, merge->nrecv, len_s, len_si, &merge->id_r, &merge->len_r, &len_ri));
4873: /* post the Irecv of j-structure */
4874: PetscCall(PetscCommGetNewTag(comm, &tagj));
4875: PetscCall(PetscPostIrecvInt(comm, tagj, merge->nrecv, merge->id_r, merge->len_r, &buf_rj, &rj_waits));
4877: /* post the Isend of j-structure */
4878: PetscCall(PetscMalloc2(merge->nsend, &si_waits, merge->nsend, &sj_waits));
4880: for (PetscMPIInt proc = 0, k = 0; proc < size; proc++) {
4881: if (!len_s[proc]) continue;
4882: i = owners[proc];
4883: PetscCallMPI(MPIU_Isend(aj + ai[i], len_s[proc], MPIU_INT, proc, tagj, comm, sj_waits + k));
4884: k++;
4885: }
4887: /* receives and sends of j-structure are complete */
4888: if (merge->nrecv) PetscCallMPI(MPI_Waitall(merge->nrecv, rj_waits, status));
4889: if (merge->nsend) PetscCallMPI(MPI_Waitall(merge->nsend, sj_waits, status));
4891: /* send and recv i-structure */
4892: PetscCall(PetscCommGetNewTag(comm, &tagi));
4893: PetscCall(PetscPostIrecvInt(comm, tagi, merge->nrecv, merge->id_r, len_ri, &buf_ri, &ri_waits));
4895: PetscCall(PetscMalloc1(len + 1, &buf_s));
4896: buf_si = buf_s; /* points to the beginning of k-th msg to be sent */
4897: for (PetscMPIInt proc = 0, k = 0; proc < size; proc++) {
4898: if (!len_s[proc]) continue;
4899: /* form outgoing message for i-structure:
4900: buf_si[0]: nrows to be sent
4901: [1:nrows]: row index (global)
4902: [nrows+1:2*nrows+1]: i-structure index
4903: */
4904: nrows = len_si[proc] / 2 - 1;
4905: buf_si_i = buf_si + nrows + 1;
4906: buf_si[0] = nrows;
4907: buf_si_i[0] = 0;
4908: nrows = 0;
4909: for (i = owners[proc]; i < owners[proc + 1]; i++) {
4910: anzi = ai[i + 1] - ai[i];
4911: if (anzi) {
4912: buf_si_i[nrows + 1] = buf_si_i[nrows] + anzi; /* i-structure */
4913: buf_si[nrows + 1] = i - owners[proc]; /* local row index */
4914: nrows++;
4915: }
4916: }
4917: PetscCallMPI(MPIU_Isend(buf_si, len_si[proc], MPIU_INT, proc, tagi, comm, si_waits + k));
4918: k++;
4919: buf_si += len_si[proc];
4920: }
4922: if (merge->nrecv) PetscCallMPI(MPI_Waitall(merge->nrecv, ri_waits, status));
4923: if (merge->nsend) PetscCallMPI(MPI_Waitall(merge->nsend, si_waits, status));
4925: PetscCall(PetscInfo(seqmat, "nsend: %d, nrecv: %d\n", merge->nsend, merge->nrecv));
4926: 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]));
4928: PetscCall(PetscFree(len_si));
4929: PetscCall(PetscFree(len_ri));
4930: PetscCall(PetscFree(rj_waits));
4931: PetscCall(PetscFree2(si_waits, sj_waits));
4932: PetscCall(PetscFree(ri_waits));
4933: PetscCall(PetscFree(buf_s));
4934: PetscCall(PetscFree(status));
4936: /* compute a local seq matrix in each processor */
4937: /* allocate bi array and free space for accumulating nonzero column info */
4938: PetscCall(PetscMalloc1(m + 1, &bi));
4939: bi[0] = 0;
4941: /* create and initialize a linked list */
4942: nlnk = N + 1;
4943: PetscCall(PetscLLCreate(N, N, nlnk, lnk, lnkbt));
4945: /* initial FreeSpace size is 2*(num of local nnz(seqmat)) */
4946: len = ai[owners[rank + 1]] - ai[owners[rank]];
4947: PetscCall(PetscFreeSpaceGet(PetscIntMultTruncate(2, len) + 1, &free_space));
4949: current_space = free_space;
4951: /* determine symbolic info for each local row */
4952: PetscCall(PetscMalloc3(merge->nrecv, &buf_ri_k, merge->nrecv, &nextrow, merge->nrecv, &nextai));
4954: for (k = 0; k < merge->nrecv; k++) {
4955: buf_ri_k[k] = buf_ri[k]; /* beginning of k-th recved i-structure */
4956: nrows = *buf_ri_k[k];
4957: nextrow[k] = buf_ri_k[k] + 1; /* next row number of k-th recved i-structure */
4958: nextai[k] = buf_ri_k[k] + (nrows + 1); /* points to the next i-structure of k-th recved i-structure */
4959: }
4961: MatPreallocateBegin(comm, m, n, dnz, onz);
4962: len = 0;
4963: for (i = 0; i < m; i++) {
4964: bnzi = 0;
4965: /* add local non-zero cols of this proc's seqmat into lnk */
4966: arow = owners[rank] + i;
4967: anzi = ai[arow + 1] - ai[arow];
4968: aj = a->j + ai[arow];
4969: PetscCall(PetscLLAddSorted(anzi, aj, N, &nlnk, lnk, lnkbt));
4970: bnzi += nlnk;
4971: /* add received col data into lnk */
4972: for (k = 0; k < merge->nrecv; k++) { /* k-th received message */
4973: if (i == *nextrow[k]) { /* i-th row */
4974: anzi = *(nextai[k] + 1) - *nextai[k];
4975: aj = buf_rj[k] + *nextai[k];
4976: PetscCall(PetscLLAddSorted(anzi, aj, N, &nlnk, lnk, lnkbt));
4977: bnzi += nlnk;
4978: nextrow[k]++;
4979: nextai[k]++;
4980: }
4981: }
4982: if (len < bnzi) len = bnzi; /* =max(bnzi) */
4984: /* if free space is not available, make more free space */
4985: if (current_space->local_remaining < bnzi) PetscCall(PetscFreeSpaceGet(PetscIntSumTruncate(bnzi, current_space->total_array_size), ¤t_space));
4986: /* copy data into free space, then initialize lnk */
4987: PetscCall(PetscLLClean(N, N, bnzi, lnk, current_space->array, lnkbt));
4988: PetscCall(MatPreallocateSet(i + owners[rank], bnzi, current_space->array, dnz, onz));
4990: current_space->array += bnzi;
4991: current_space->local_used += bnzi;
4992: current_space->local_remaining -= bnzi;
4994: bi[i + 1] = bi[i] + bnzi;
4995: }
4997: PetscCall(PetscFree3(buf_ri_k, nextrow, nextai));
4999: PetscCall(PetscMalloc1(bi[m], &bj));
5000: PetscCall(PetscFreeSpaceContiguous(&free_space, bj));
5001: PetscCall(PetscLLDestroy(lnk, lnkbt));
5003: /* create symbolic parallel matrix B_mpi */
5004: PetscCall(MatGetBlockSizes(seqmat, &bs, &cbs));
5005: PetscCall(MatCreate(comm, &B_mpi));
5006: if (n == PETSC_DECIDE) PetscCall(MatSetSizes(B_mpi, m, n, PETSC_DETERMINE, N));
5007: else PetscCall(MatSetSizes(B_mpi, m, n, PETSC_DETERMINE, PETSC_DETERMINE));
5008: PetscCall(MatSetBlockSizes(B_mpi, bs, cbs));
5009: PetscCall(MatSetType(B_mpi, MATMPIAIJ));
5010: PetscCall(MatMPIAIJSetPreallocation(B_mpi, 0, dnz, 0, onz));
5011: MatPreallocateEnd(dnz, onz);
5012: PetscCall(MatSetOption(B_mpi, MAT_NEW_NONZERO_ALLOCATION_ERR, PETSC_FALSE));
5014: /* B_mpi is not ready for use - assembly will be done by MatCreateMPIAIJSumSeqAIJNumeric() */
5015: B_mpi->assembled = PETSC_FALSE;
5016: merge->bi = bi;
5017: merge->bj = bj;
5018: merge->buf_ri = buf_ri;
5019: merge->buf_rj = buf_rj;
5020: merge->coi = NULL;
5021: merge->coj = NULL;
5022: merge->owners_co = NULL;
5024: PetscCall(PetscCommDestroy(&comm));
5026: /* attach the supporting struct to B_mpi for reuse */
5027: PetscCall(PetscContainerCreate(PETSC_COMM_SELF, &container));
5028: PetscCall(PetscContainerSetPointer(container, merge));
5029: PetscCall(PetscContainerSetCtxDestroy(container, MatMergeSeqsToMPIDestroy));
5030: PetscCall(PetscObjectCompose((PetscObject)B_mpi, "MatMergeSeqsToMPI", (PetscObject)container));
5031: PetscCall(PetscContainerDestroy(&container));
5032: *mpimat = B_mpi;
5034: PetscCall(PetscLogEventEnd(MAT_Seqstompisym, seqmat, 0, 0, 0));
5035: PetscFunctionReturn(PETSC_SUCCESS);
5036: }
5038: /*@
5039: MatCreateMPIAIJSumSeqAIJ - Creates a `MATMPIAIJ` matrix by adding sequential
5040: matrices from each processor
5042: Collective
5044: Input Parameters:
5045: + comm - the communicators the parallel matrix will live on
5046: . seqmat - the input sequential matrices
5047: . m - number of local rows (or `PETSC_DECIDE`)
5048: . n - number of local columns (or `PETSC_DECIDE`)
5049: - scall - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`
5051: Output Parameter:
5052: . mpimat - the parallel matrix generated
5054: Level: advanced
5056: Note:
5057: The dimensions of the sequential matrix in each processor MUST be the same.
5058: The input seqmat is included into the container `MatMergeSeqsToMPIDestroy`, and will be
5059: destroyed when `mpimat` is destroyed. Call `PetscObjectQuery()` to access `seqmat`.
5061: .seealso: [](ch_matrices), `Mat`, `MatCreateAIJ()`
5062: @*/
5063: PetscErrorCode MatCreateMPIAIJSumSeqAIJ(MPI_Comm comm, Mat seqmat, PetscInt m, PetscInt n, MatReuse scall, Mat *mpimat)
5064: {
5065: PetscMPIInt size;
5067: PetscFunctionBegin;
5068: PetscCallMPI(MPI_Comm_size(comm, &size));
5069: if (size == 1) {
5070: PetscCall(PetscLogEventBegin(MAT_Seqstompi, seqmat, 0, 0, 0));
5071: if (scall == MAT_INITIAL_MATRIX) PetscCall(MatDuplicate(seqmat, MAT_COPY_VALUES, mpimat));
5072: else PetscCall(MatCopy(seqmat, *mpimat, SAME_NONZERO_PATTERN));
5073: PetscCall(PetscLogEventEnd(MAT_Seqstompi, seqmat, 0, 0, 0));
5074: PetscFunctionReturn(PETSC_SUCCESS);
5075: }
5076: PetscCall(PetscLogEventBegin(MAT_Seqstompi, seqmat, 0, 0, 0));
5077: if (scall == MAT_INITIAL_MATRIX) PetscCall(MatCreateMPIAIJSumSeqAIJSymbolic(comm, seqmat, m, n, mpimat));
5078: PetscCall(MatCreateMPIAIJSumSeqAIJNumeric(seqmat, *mpimat));
5079: PetscCall(PetscLogEventEnd(MAT_Seqstompi, seqmat, 0, 0, 0));
5080: PetscFunctionReturn(PETSC_SUCCESS);
5081: }
5083: /*@
5084: MatAIJGetLocalMat - Creates a `MATSEQAIJ` from a `MATAIJ` matrix.
5086: Not Collective
5088: Input Parameter:
5089: . A - the matrix
5091: Output Parameter:
5092: . A_loc - the local sequential matrix generated
5094: Level: developer
5096: Notes:
5097: The matrix is created by taking `A`'s local rows and putting them into a sequential matrix
5098: with `mlocal` rows and `n` columns. Where `mlocal` is obtained with `MatGetLocalSize()` and
5099: `n` is the global column count obtained with `MatGetSize()`
5101: In other words combines the two parts of a parallel `MATMPIAIJ` matrix on each process to a single matrix.
5103: For parallel matrices this creates an entirely new matrix. If the matrix is sequential it merely increases the reference count.
5105: Destroy the matrix with `MatDestroy()`
5107: .seealso: [](ch_matrices), `Mat`, `MatMPIAIJGetLocalMat()`
5108: @*/
5109: PetscErrorCode MatAIJGetLocalMat(Mat A, Mat *A_loc)
5110: {
5111: PetscBool mpi;
5113: PetscFunctionBegin;
5114: PetscCall(PetscObjectTypeCompare((PetscObject)A, MATMPIAIJ, &mpi));
5115: if (mpi) PetscCall(MatMPIAIJGetLocalMat(A, MAT_INITIAL_MATRIX, A_loc));
5116: else {
5117: *A_loc = A;
5118: PetscCall(PetscObjectReference((PetscObject)*A_loc));
5119: }
5120: PetscFunctionReturn(PETSC_SUCCESS);
5121: }
5123: /*@
5124: MatMPIAIJGetLocalMat - Creates a `MATSEQAIJ` from a `MATMPIAIJ` matrix.
5126: Not Collective
5128: Input Parameters:
5129: + A - the matrix
5130: - scall - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`
5132: Output Parameter:
5133: . A_loc - the local sequential matrix generated
5135: Level: developer
5137: Notes:
5138: The matrix is created by taking all `A`'s local rows and putting them into a sequential
5139: matrix with `mlocal` rows and `n` columns.`mlocal` is the row count obtained with
5140: `MatGetLocalSize()` and `n` is the global column count obtained with `MatGetSize()`.
5142: In other words combines the two parts of a parallel `MATMPIAIJ` matrix on each process to a single matrix.
5144: When `A` is sequential and `MAT_INITIAL_MATRIX` is requested, the matrix returned is the diagonal part of `A` (which contains the entire matrix),
5145: 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
5146: then `MatCopy`(Adiag,*`A_loc`,`SAME_NONZERO_PATTERN`) is called to fill `A_loc`. Thus one can preallocate the appropriate sequential matrix `A_loc`
5147: 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.
5149: .seealso: [](ch_matrices), `Mat`, `MATMPIAIJ`, `MatGetOwnershipRange()`, `MatMPIAIJGetLocalMatCondensed()`, `MatMPIAIJGetLocalMatMerge()`
5150: @*/
5151: PetscErrorCode MatMPIAIJGetLocalMat(Mat A, MatReuse scall, Mat *A_loc)
5152: {
5153: PetscFunctionBegin;
5154: PetscCall(MatMPIAIJGetLocalMat_Private(A, scall, PETSC_FALSE, A_loc));
5155: PetscFunctionReturn(PETSC_SUCCESS);
5156: }
5158: PetscErrorCode MatMPIAIJGetLocalMat_Private(Mat A, MatReuse scall, PetscBool structure_only, Mat *A_loc)
5159: {
5160: Mat_MPIAIJ *mpimat = (Mat_MPIAIJ *)A->data;
5161: Mat_SeqAIJ *mat, *a, *b;
5162: PetscInt *ai, *aj, *bi, *bj, *cmap = mpimat->garray;
5163: const PetscScalar *aa, *ba, *aav = NULL, *bav = NULL;
5164: PetscScalar *ca = NULL, *cam;
5165: PetscMPIInt size;
5166: PetscInt am = A->rmap->n, i, j, k, cstart = A->cmap->rstart;
5167: PetscInt *ci, *cj, col, ncols_d, ncols_o, jo;
5168: PetscBool match;
5170: PetscFunctionBegin;
5171: PetscCheck(!structure_only || scall == MAT_INITIAL_MATRIX, PETSC_COMM_SELF, PETSC_ERR_SUP, "Structure-only extraction requires MAT_INITIAL_MATRIX");
5172: PetscCall(PetscStrbeginswith(((PetscObject)A)->type_name, MATMPIAIJ, &match));
5173: PetscCheck(match, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "Requires MATMPIAIJ matrix as input");
5174: PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)A), &size));
5175: if (size == 1 && !structure_only) {
5176: if (scall == MAT_INITIAL_MATRIX) {
5177: PetscCall(PetscObjectReference((PetscObject)mpimat->A));
5178: *A_loc = mpimat->A;
5179: } else if (scall == MAT_REUSE_MATRIX) PetscCall(MatCopy(mpimat->A, *A_loc, SAME_NONZERO_PATTERN));
5180: PetscFunctionReturn(PETSC_SUCCESS);
5181: }
5183: PetscCall(PetscLogEventBegin(MAT_Getlocalmat, A, 0, 0, 0));
5184: a = (Mat_SeqAIJ *)mpimat->A->data;
5185: b = (Mat_SeqAIJ *)mpimat->B->data;
5186: ai = a->i;
5187: aj = a->j;
5188: bi = b->i;
5189: bj = b->j;
5190: if (!structure_only) {
5191: PetscCall(MatSeqAIJGetArrayRead(mpimat->A, &aav));
5192: PetscCall(MatSeqAIJGetArrayRead(mpimat->B, &bav));
5193: }
5194: aa = aav;
5195: ba = bav;
5196: if (scall == MAT_INITIAL_MATRIX) {
5197: PetscCall(PetscMalloc1(1 + am, &ci));
5198: ci[0] = 0;
5199: for (i = 0; i < am; i++) ci[i + 1] = ci[i] + (ai[i + 1] - ai[i]) + (bi[i + 1] - bi[i]);
5200: PetscCall(PetscMalloc1(ci[am], &cj));
5201: if (!structure_only) PetscCall(PetscMalloc1(ci[am], &ca));
5202: k = 0;
5203: for (i = 0; i < am; i++) {
5204: ncols_o = bi[i + 1] - bi[i];
5205: ncols_d = ai[i + 1] - ai[i];
5206: /* off-diagonal portion of A */
5207: for (jo = 0; jo < ncols_o; jo++, bj++, k++) {
5208: col = cmap[*bj];
5209: if (col >= cstart) break;
5210: cj[k] = col;
5211: if (!structure_only) ca[k] = *ba++;
5212: }
5213: /* diagonal portion of A */
5214: for (j = 0; j < ncols_d; j++, k++) {
5215: cj[k] = cstart + *aj++;
5216: if (!structure_only) ca[k] = *aa++;
5217: }
5218: /* off-diagonal portion of A */
5219: for (j = jo; j < ncols_o; j++, k++) {
5220: cj[k] = cmap[*bj++];
5221: if (!structure_only) ca[k] = *ba++;
5222: }
5223: }
5224: /* put together the new matrix */
5225: PetscCall(MatCreateSeqAIJWithArrays(PETSC_COMM_SELF, am, A->cmap->N, ci, cj, ca, A_loc));
5226: PetscCall(MatSetOption(*A_loc, MAT_STRUCTURE_ONLY, structure_only));
5227: /* MatCreateSeqAIJWithArrays flags matrix so PETSc doesn't free the user's arrays. */
5228: /* Since these are PETSc arrays, change flags to free them as necessary. */
5229: mat = (Mat_SeqAIJ *)(*A_loc)->data;
5230: mat->free_a = PETSC_TRUE;
5231: mat->free_ij = PETSC_TRUE;
5232: mat->nonew = 0;
5233: } else if (scall == MAT_REUSE_MATRIX) {
5234: mat = (Mat_SeqAIJ *)(*A_loc)->data;
5235: ci = mat->i;
5236: cj = mat->j;
5237: PetscCall(MatSeqAIJGetArrayWrite(*A_loc, &cam));
5238: for (i = 0; i < am; i++) {
5239: /* off-diagonal portion of A */
5240: ncols_o = bi[i + 1] - bi[i];
5241: for (jo = 0; jo < ncols_o; jo++, bj++) {
5242: col = cmap[*bj];
5243: if (col >= cstart) break;
5244: *cam++ = *ba++;
5245: }
5246: /* diagonal portion of A */
5247: ncols_d = ai[i + 1] - ai[i];
5248: for (j = 0; j < ncols_d; j++) *cam++ = *aa++;
5249: /* off-diagonal portion of A */
5250: for (j = jo; j < ncols_o; j++, bj++) *cam++ = *ba++;
5251: }
5252: PetscCall(MatSeqAIJRestoreArrayWrite(*A_loc, &cam));
5253: } else SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Invalid MatReuse %d", (int)scall);
5254: if (!structure_only) {
5255: PetscCall(MatSeqAIJRestoreArrayRead(mpimat->A, &aav));
5256: PetscCall(MatSeqAIJRestoreArrayRead(mpimat->B, &bav));
5257: }
5258: PetscCall(PetscLogEventEnd(MAT_Getlocalmat, A, 0, 0, 0));
5259: PetscFunctionReturn(PETSC_SUCCESS);
5260: }
5262: /*@
5263: MatMPIAIJGetLocalMatMerge - Creates a `MATSEQAIJ` from a `MATMPIAIJ` matrix by taking all its local rows and putting them into a sequential matrix with
5264: mlocal rows and n columns. Where n is the sum of the number of columns of the diagonal and off-diagonal part
5266: Not Collective
5268: Input Parameters:
5269: + A - the matrix
5270: - scall - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`
5272: Output Parameters:
5273: + glob - sequential `IS` with global indices associated with the columns of the local sequential matrix generated (can be `NULL`)
5274: - A_loc - the local sequential matrix generated
5276: Level: developer
5278: Note:
5279: This is different from `MatMPIAIJGetLocalMat()` since the first columns in the returning matrix are those associated with the diagonal
5280: part, then those associated with the off-diagonal part (in its local ordering)
5282: .seealso: [](ch_matrices), `Mat`, `MATMPIAIJ`, `MatGetOwnershipRange()`, `MatMPIAIJGetLocalMat()`, `MatMPIAIJGetLocalMatCondensed()`
5283: @*/
5284: PetscErrorCode MatMPIAIJGetLocalMatMerge(Mat A, MatReuse scall, IS *glob, Mat *A_loc)
5285: {
5286: Mat Ao, Ad;
5287: const PetscInt *cmap;
5288: PetscMPIInt size;
5289: PetscErrorCode (*f)(Mat, MatReuse, IS *, Mat *);
5291: PetscFunctionBegin;
5292: PetscCall(MatMPIAIJGetSeqAIJ(A, &Ad, &Ao, &cmap));
5293: PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)A), &size));
5294: if (size == 1) {
5295: if (scall == MAT_INITIAL_MATRIX) {
5296: PetscCall(PetscObjectReference((PetscObject)Ad));
5297: *A_loc = Ad;
5298: } else if (scall == MAT_REUSE_MATRIX) {
5299: PetscCall(MatCopy(Ad, *A_loc, SAME_NONZERO_PATTERN));
5300: }
5301: if (glob) PetscCall(ISCreateStride(PetscObjectComm((PetscObject)Ad), Ad->cmap->n, Ad->cmap->rstart, 1, glob));
5302: PetscFunctionReturn(PETSC_SUCCESS);
5303: }
5304: PetscCall(PetscObjectQueryFunction((PetscObject)A, "MatMPIAIJGetLocalMatMerge_C", &f));
5305: PetscCall(PetscLogEventBegin(MAT_Getlocalmat, A, 0, 0, 0));
5306: if (f) PetscCall((*f)(A, scall, glob, A_loc));
5307: else {
5308: Mat_SeqAIJ *a = (Mat_SeqAIJ *)Ad->data;
5309: Mat_SeqAIJ *b = (Mat_SeqAIJ *)Ao->data;
5310: Mat_SeqAIJ *c;
5311: PetscInt *ai = a->i, *aj = a->j;
5312: PetscInt *bi = b->i, *bj = b->j;
5313: PetscInt *ci, *cj;
5314: const PetscScalar *aa, *ba;
5315: PetscScalar *ca;
5316: PetscInt i, j, am, dn, on;
5318: PetscCall(MatGetLocalSize(Ad, &am, &dn));
5319: PetscCall(MatGetLocalSize(Ao, NULL, &on));
5320: PetscCall(MatSeqAIJGetArrayRead(Ad, &aa));
5321: PetscCall(MatSeqAIJGetArrayRead(Ao, &ba));
5322: if (scall == MAT_INITIAL_MATRIX) {
5323: PetscInt k;
5324: PetscCall(PetscMalloc1(1 + am, &ci));
5325: PetscCall(PetscMalloc1(ai[am] + bi[am], &cj));
5326: PetscCall(PetscMalloc1(ai[am] + bi[am], &ca));
5327: ci[0] = 0;
5328: for (i = 0, k = 0; i < am; i++) {
5329: const PetscInt ncols_o = bi[i + 1] - bi[i];
5330: const PetscInt ncols_d = ai[i + 1] - ai[i];
5331: ci[i + 1] = ci[i] + ncols_o + ncols_d;
5332: /* diagonal portion of A */
5333: for (j = 0; j < ncols_d; j++, k++) {
5334: cj[k] = *aj++;
5335: ca[k] = *aa++;
5336: }
5337: /* off-diagonal portion of A */
5338: for (j = 0; j < ncols_o; j++, k++) {
5339: cj[k] = dn + *bj++;
5340: ca[k] = *ba++;
5341: }
5342: }
5343: /* put together the new matrix */
5344: PetscCall(MatCreateSeqAIJWithArrays(PETSC_COMM_SELF, am, dn + on, ci, cj, ca, A_loc));
5345: /* MatCreateSeqAIJWithArrays flags matrix so PETSc doesn't free the user's arrays. */
5346: /* Since these are PETSc arrays, change flags to free them as necessary. */
5347: c = (Mat_SeqAIJ *)(*A_loc)->data;
5348: c->free_a = PETSC_TRUE;
5349: c->free_ij = PETSC_TRUE;
5350: c->nonew = 0;
5351: PetscCall(MatSetType(*A_loc, ((PetscObject)Ad)->type_name));
5352: } else if (scall == MAT_REUSE_MATRIX) {
5353: PetscCall(MatSeqAIJGetArrayWrite(*A_loc, &ca));
5354: for (i = 0; i < am; i++) {
5355: const PetscInt ncols_d = ai[i + 1] - ai[i];
5356: const PetscInt ncols_o = bi[i + 1] - bi[i];
5357: /* diagonal portion of A */
5358: for (j = 0; j < ncols_d; j++) *ca++ = *aa++;
5359: /* off-diagonal portion of A */
5360: for (j = 0; j < ncols_o; j++) *ca++ = *ba++;
5361: }
5362: PetscCall(MatSeqAIJRestoreArrayWrite(*A_loc, &ca));
5363: } else SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Invalid MatReuse %d", (int)scall);
5364: PetscCall(MatSeqAIJRestoreArrayRead(Ad, &aa));
5365: PetscCall(MatSeqAIJRestoreArrayRead(Ao, &aa));
5366: if (glob) {
5367: PetscInt cst, *gidx;
5369: PetscCall(MatGetOwnershipRangeColumn(A, &cst, NULL));
5370: PetscCall(PetscMalloc1(dn + on, &gidx));
5371: for (i = 0; i < dn; i++) gidx[i] = cst + i;
5372: for (i = 0; i < on; i++) gidx[i + dn] = cmap[i];
5373: PetscCall(ISCreateGeneral(PetscObjectComm((PetscObject)Ad), dn + on, gidx, PETSC_OWN_POINTER, glob));
5374: }
5375: }
5376: PetscCall(PetscLogEventEnd(MAT_Getlocalmat, A, 0, 0, 0));
5377: PetscFunctionReturn(PETSC_SUCCESS);
5378: }
5380: /*@
5381: MatMPIAIJGetLocalMatCondensed - Creates a `MATSEQAIJ` matrix from an `MATMPIAIJ` matrix by taking all its local rows and NON-ZERO columns
5383: Not Collective
5385: Input Parameters:
5386: + A - the matrix
5387: . scall - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`
5388: . row - index set of rows to extract (or `NULL`)
5389: - col - index set of columns to extract (or `NULL`)
5391: Output Parameter:
5392: . A_loc - the local sequential matrix generated
5394: Level: developer
5396: .seealso: [](ch_matrices), `Mat`, `MATMPIAIJ`, `MatGetOwnershipRange()`, `MatMPIAIJGetLocalMat()`
5397: @*/
5398: PetscErrorCode MatMPIAIJGetLocalMatCondensed(Mat A, MatReuse scall, IS *row, IS *col, Mat *A_loc)
5399: {
5400: Mat_MPIAIJ *a = (Mat_MPIAIJ *)A->data;
5401: PetscInt i, start, end, ncols, nzA, nzB, *cmap, imark, *idx;
5402: IS isrowa, iscola;
5403: Mat *aloc;
5404: PetscBool match;
5406: PetscFunctionBegin;
5407: PetscCall(PetscObjectTypeCompare((PetscObject)A, MATMPIAIJ, &match));
5408: PetscCheck(match, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "Requires MATMPIAIJ matrix as input");
5409: PetscCall(PetscLogEventBegin(MAT_Getlocalmatcondensed, A, 0, 0, 0));
5410: if (!row) {
5411: start = A->rmap->rstart;
5412: end = A->rmap->rend;
5413: PetscCall(ISCreateStride(PETSC_COMM_SELF, end - start, start, 1, &isrowa));
5414: } else {
5415: isrowa = *row;
5416: }
5417: if (!col) {
5418: start = A->cmap->rstart;
5419: cmap = a->garray;
5420: nzA = a->A->cmap->n;
5421: nzB = a->B->cmap->n;
5422: PetscCall(PetscMalloc1(nzA + nzB, &idx));
5423: ncols = 0;
5424: for (i = 0; i < nzB; i++) {
5425: if (cmap[i] < start) idx[ncols++] = cmap[i];
5426: else break;
5427: }
5428: imark = i;
5429: for (i = 0; i < nzA; i++) idx[ncols++] = start + i;
5430: for (i = imark; i < nzB; i++) idx[ncols++] = cmap[i];
5431: PetscCall(ISCreateGeneral(PETSC_COMM_SELF, ncols, idx, PETSC_OWN_POINTER, &iscola));
5432: } else iscola = *col;
5433: if (scall != MAT_INITIAL_MATRIX) {
5434: PetscCall(PetscMalloc1(1, &aloc));
5435: aloc[0] = *A_loc;
5436: }
5437: PetscCall(MatCreateSubMatrices(A, 1, &isrowa, &iscola, scall, &aloc));
5438: if (!col) { /* attach global id of condensed columns */
5439: PetscCall(PetscObjectCompose((PetscObject)aloc[0], "_petsc_GetLocalMatCondensed_iscol", (PetscObject)iscola));
5440: }
5441: *A_loc = aloc[0];
5442: PetscCall(PetscFree(aloc));
5443: if (!row) PetscCall(ISDestroy(&isrowa));
5444: if (!col) PetscCall(ISDestroy(&iscola));
5445: PetscCall(PetscLogEventEnd(MAT_Getlocalmatcondensed, A, 0, 0, 0));
5446: PetscFunctionReturn(PETSC_SUCCESS);
5447: }
5449: /*
5450: * Create a sequential AIJ matrix based on row indices. a whole column is extracted once a row is matched.
5451: * Row could be local or remote.The routine is designed to be scalable in memory so that nothing is based
5452: * on a global size.
5453: * */
5454: static PetscErrorCode MatCreateSeqSubMatrixWithRows_Private(Mat P, IS rows, Mat *P_oth)
5455: {
5456: Mat_MPIAIJ *p = (Mat_MPIAIJ *)P->data;
5457: Mat_SeqAIJ *pd = (Mat_SeqAIJ *)p->A->data, *po = (Mat_SeqAIJ *)p->B->data, *p_oth;
5458: PetscInt plocalsize, nrows, *ilocal, *oilocal, i, lidx, *nrcols, *nlcols, ncol;
5459: PetscMPIInt owner;
5460: PetscSFNode *iremote, *oiremote;
5461: const PetscInt *lrowindices;
5462: PetscSF sf, osf;
5463: PetscInt pcstart, *roffsets, *loffsets, *pnnz, j;
5464: PetscInt ontotalcols, dntotalcols, ntotalcols, nout;
5465: MPI_Comm comm;
5466: ISLocalToGlobalMapping mapping;
5467: const PetscScalar *pd_a, *po_a;
5469: PetscFunctionBegin;
5470: PetscCall(PetscObjectGetComm((PetscObject)P, &comm));
5471: /* plocalsize is the number of roots
5472: * nrows is the number of leaves
5473: * */
5474: PetscCall(MatGetLocalSize(P, &plocalsize, NULL));
5475: PetscCall(ISGetLocalSize(rows, &nrows));
5476: PetscCall(PetscCalloc1(nrows, &iremote));
5477: PetscCall(ISGetIndices(rows, &lrowindices));
5478: for (i = 0; i < nrows; i++) {
5479: /* Find a remote index and an owner for a row
5480: * The row could be local or remote
5481: * */
5482: owner = 0;
5483: lidx = 0;
5484: PetscCall(PetscLayoutFindOwnerIndex(P->rmap, lrowindices[i], &owner, &lidx));
5485: iremote[i].index = lidx;
5486: iremote[i].rank = owner;
5487: }
5488: /* Create SF to communicate how many nonzero columns for each row */
5489: PetscCall(PetscSFCreate(comm, &sf));
5490: /* SF will figure out the number of nonzero columns for each row, and their
5491: * offsets
5492: * */
5493: PetscCall(PetscSFSetGraph(sf, plocalsize, nrows, NULL, PETSC_OWN_POINTER, iremote, PETSC_OWN_POINTER));
5494: PetscCall(PetscSFSetFromOptions(sf));
5495: PetscCall(PetscSFSetUp(sf));
5497: PetscCall(PetscCalloc1(2 * (plocalsize + 1), &roffsets));
5498: PetscCall(PetscCalloc1(2 * plocalsize, &nrcols));
5499: PetscCall(PetscCalloc1(nrows, &pnnz));
5500: roffsets[0] = 0;
5501: roffsets[1] = 0;
5502: for (i = 0; i < plocalsize; i++) {
5503: /* diagonal */
5504: nrcols[i * 2 + 0] = pd->i[i + 1] - pd->i[i];
5505: /* off-diagonal */
5506: nrcols[i * 2 + 1] = po->i[i + 1] - po->i[i];
5507: /* compute offsets so that we relative location for each row */
5508: roffsets[(i + 1) * 2 + 0] = roffsets[i * 2 + 0] + nrcols[i * 2 + 0];
5509: roffsets[(i + 1) * 2 + 1] = roffsets[i * 2 + 1] + nrcols[i * 2 + 1];
5510: }
5511: PetscCall(PetscCalloc1(2 * nrows, &nlcols));
5512: PetscCall(PetscCalloc1(2 * nrows, &loffsets));
5513: /* 'r' means root, and 'l' means leaf */
5514: PetscCall(PetscSFBcastBegin(sf, MPIU_2INT, nrcols, nlcols, MPI_REPLACE));
5515: PetscCall(PetscSFBcastBegin(sf, MPIU_2INT, roffsets, loffsets, MPI_REPLACE));
5516: PetscCall(PetscSFBcastEnd(sf, MPIU_2INT, nrcols, nlcols, MPI_REPLACE));
5517: PetscCall(PetscSFBcastEnd(sf, MPIU_2INT, roffsets, loffsets, MPI_REPLACE));
5518: PetscCall(PetscSFDestroy(&sf));
5519: PetscCall(PetscFree(roffsets));
5520: PetscCall(PetscFree(nrcols));
5521: dntotalcols = 0;
5522: ontotalcols = 0;
5523: ncol = 0;
5524: for (i = 0; i < nrows; i++) {
5525: pnnz[i] = nlcols[i * 2 + 0] + nlcols[i * 2 + 1];
5526: ncol = PetscMax(pnnz[i], ncol);
5527: /* diagonal */
5528: dntotalcols += nlcols[i * 2 + 0];
5529: /* off-diagonal */
5530: ontotalcols += nlcols[i * 2 + 1];
5531: }
5532: /* We do not need to figure the right number of columns
5533: * since all the calculations will be done by going through the raw data
5534: * */
5535: PetscCall(MatCreateSeqAIJ(PETSC_COMM_SELF, nrows, ncol, 0, pnnz, P_oth));
5536: PetscCall(MatSetUp(*P_oth));
5537: PetscCall(PetscFree(pnnz));
5538: p_oth = (Mat_SeqAIJ *)(*P_oth)->data;
5539: /* diagonal */
5540: PetscCall(PetscCalloc1(dntotalcols, &iremote));
5541: /* off-diagonal */
5542: PetscCall(PetscCalloc1(ontotalcols, &oiremote));
5543: /* diagonal */
5544: PetscCall(PetscCalloc1(dntotalcols, &ilocal));
5545: /* off-diagonal */
5546: PetscCall(PetscCalloc1(ontotalcols, &oilocal));
5547: dntotalcols = 0;
5548: ontotalcols = 0;
5549: ntotalcols = 0;
5550: for (i = 0; i < nrows; i++) {
5551: owner = 0;
5552: PetscCall(PetscLayoutFindOwnerIndex(P->rmap, lrowindices[i], &owner, NULL));
5553: /* Set iremote for diag matrix */
5554: for (j = 0; j < nlcols[i * 2 + 0]; j++) {
5555: iremote[dntotalcols].index = loffsets[i * 2 + 0] + j;
5556: iremote[dntotalcols].rank = owner;
5557: /* P_oth is seqAIJ so that ilocal need to point to the first part of memory */
5558: ilocal[dntotalcols++] = ntotalcols++;
5559: }
5560: /* off-diagonal */
5561: for (j = 0; j < nlcols[i * 2 + 1]; j++) {
5562: oiremote[ontotalcols].index = loffsets[i * 2 + 1] + j;
5563: oiremote[ontotalcols].rank = owner;
5564: oilocal[ontotalcols++] = ntotalcols++;
5565: }
5566: }
5567: PetscCall(ISRestoreIndices(rows, &lrowindices));
5568: PetscCall(PetscFree(loffsets));
5569: PetscCall(PetscFree(nlcols));
5570: PetscCall(PetscSFCreate(comm, &sf));
5571: /* P serves as roots and P_oth is leaves
5572: * Diag matrix
5573: * */
5574: PetscCall(PetscSFSetGraph(sf, pd->i[plocalsize], dntotalcols, ilocal, PETSC_OWN_POINTER, iremote, PETSC_OWN_POINTER));
5575: PetscCall(PetscSFSetFromOptions(sf));
5576: PetscCall(PetscSFSetUp(sf));
5578: PetscCall(PetscSFCreate(comm, &osf));
5579: /* off-diagonal */
5580: PetscCall(PetscSFSetGraph(osf, po->i[plocalsize], ontotalcols, oilocal, PETSC_OWN_POINTER, oiremote, PETSC_OWN_POINTER));
5581: PetscCall(PetscSFSetFromOptions(osf));
5582: PetscCall(PetscSFSetUp(osf));
5583: PetscCall(MatSeqAIJGetArrayRead(p->A, &pd_a));
5584: PetscCall(MatSeqAIJGetArrayRead(p->B, &po_a));
5585: /* operate on the matrix internal data to save memory */
5586: PetscCall(PetscSFBcastBegin(sf, MPIU_SCALAR, pd_a, p_oth->a, MPI_REPLACE));
5587: PetscCall(PetscSFBcastBegin(osf, MPIU_SCALAR, po_a, p_oth->a, MPI_REPLACE));
5588: PetscCall(MatGetOwnershipRangeColumn(P, &pcstart, NULL));
5589: /* Convert to global indices for diag matrix */
5590: for (i = 0; i < pd->i[plocalsize]; i++) pd->j[i] += pcstart;
5591: PetscCall(PetscSFBcastBegin(sf, MPIU_INT, pd->j, p_oth->j, MPI_REPLACE));
5592: /* We want P_oth store global indices */
5593: PetscCall(ISLocalToGlobalMappingCreate(comm, 1, p->B->cmap->n, p->garray, PETSC_COPY_VALUES, &mapping));
5594: /* Use memory scalable approach */
5595: PetscCall(ISLocalToGlobalMappingSetType(mapping, ISLOCALTOGLOBALMAPPINGHASH));
5596: PetscCall(ISLocalToGlobalMappingApply(mapping, po->i[plocalsize], po->j, po->j));
5597: PetscCall(PetscSFBcastBegin(osf, MPIU_INT, po->j, p_oth->j, MPI_REPLACE));
5598: PetscCall(PetscSFBcastEnd(sf, MPIU_INT, pd->j, p_oth->j, MPI_REPLACE));
5599: /* Convert back to local indices */
5600: for (i = 0; i < pd->i[plocalsize]; i++) pd->j[i] -= pcstart;
5601: PetscCall(PetscSFBcastEnd(osf, MPIU_INT, po->j, p_oth->j, MPI_REPLACE));
5602: nout = 0;
5603: PetscCall(ISGlobalToLocalMappingApply(mapping, IS_GTOLM_DROP, po->i[plocalsize], po->j, &nout, po->j));
5604: PetscCheck(nout == po->i[plocalsize], comm, PETSC_ERR_ARG_INCOMP, "n %" PetscInt_FMT " does not equal to nout %" PetscInt_FMT " ", po->i[plocalsize], nout);
5605: PetscCall(ISLocalToGlobalMappingDestroy(&mapping));
5606: /* Exchange values */
5607: PetscCall(PetscSFBcastEnd(sf, MPIU_SCALAR, pd_a, p_oth->a, MPI_REPLACE));
5608: PetscCall(PetscSFBcastEnd(osf, MPIU_SCALAR, po_a, p_oth->a, MPI_REPLACE));
5609: PetscCall(MatSeqAIJRestoreArrayRead(p->A, &pd_a));
5610: PetscCall(MatSeqAIJRestoreArrayRead(p->B, &po_a));
5611: /* Stop PETSc from shrinking memory */
5612: for (i = 0; i < nrows; i++) p_oth->ilen[i] = p_oth->imax[i];
5613: PetscCall(MatAssemblyBegin(*P_oth, MAT_FINAL_ASSEMBLY));
5614: PetscCall(MatAssemblyEnd(*P_oth, MAT_FINAL_ASSEMBLY));
5615: /* Attach PetscSF objects to P_oth so that we can reuse it later */
5616: PetscCall(PetscObjectCompose((PetscObject)*P_oth, "diagsf", (PetscObject)sf));
5617: PetscCall(PetscObjectCompose((PetscObject)*P_oth, "offdiagsf", (PetscObject)osf));
5618: PetscCall(PetscSFDestroy(&sf));
5619: PetscCall(PetscSFDestroy(&osf));
5620: PetscFunctionReturn(PETSC_SUCCESS);
5621: }
5623: /*
5624: * Creates a SeqAIJ matrix by taking rows of B that equal to nonzero columns of local A
5625: * This supports MPIAIJ and MAIJ
5626: * */
5627: PetscErrorCode MatGetBrowsOfAcols_MPIXAIJ(Mat A, Mat P, PetscInt dof, MatReuse reuse, Mat *P_oth)
5628: {
5629: Mat_MPIAIJ *a = (Mat_MPIAIJ *)A->data, *p = (Mat_MPIAIJ *)P->data;
5630: Mat_SeqAIJ *p_oth;
5631: IS rows, map;
5632: PetscHMapI hamp;
5633: PetscInt i, htsize, *rowindices, off, *mapping, key, count;
5634: MPI_Comm comm;
5635: PetscSF sf, osf;
5636: PetscBool has;
5638: PetscFunctionBegin;
5639: PetscCall(PetscObjectGetComm((PetscObject)A, &comm));
5640: PetscCall(PetscLogEventBegin(MAT_GetBrowsOfAocols, A, P, 0, 0));
5641: /* If it is the first time, create an index set of off-diag nonzero columns of A,
5642: * and then create a submatrix (that often is an overlapping matrix)
5643: * */
5644: if (reuse == MAT_INITIAL_MATRIX) {
5645: /* Use a hash table to figure out unique keys */
5646: PetscCall(PetscHMapICreateWithSize(a->B->cmap->n, &hamp));
5647: PetscCall(PetscCalloc1(a->B->cmap->n, &mapping));
5648: count = 0;
5649: /* Assume that a->g is sorted, otherwise the following does not make sense */
5650: for (i = 0; i < a->B->cmap->n; i++) {
5651: key = a->garray[i] / dof;
5652: PetscCall(PetscHMapIHas(hamp, key, &has));
5653: if (!has) {
5654: mapping[i] = count;
5655: PetscCall(PetscHMapISet(hamp, key, count++));
5656: } else {
5657: /* Current 'i' has the same value the previous step */
5658: mapping[i] = count - 1;
5659: }
5660: }
5661: PetscCall(ISCreateGeneral(comm, a->B->cmap->n, mapping, PETSC_OWN_POINTER, &map));
5662: PetscCall(PetscHMapIGetSize(hamp, &htsize));
5663: PetscCheck(htsize == count, comm, PETSC_ERR_ARG_INCOMP, " Size of hash map %" PetscInt_FMT " is inconsistent with count %" PetscInt_FMT, htsize, count);
5664: PetscCall(PetscCalloc1(htsize, &rowindices));
5665: off = 0;
5666: PetscCall(PetscHMapIGetKeys(hamp, &off, rowindices));
5667: PetscCall(PetscHMapIDestroy(&hamp));
5668: PetscCall(PetscSortInt(htsize, rowindices));
5669: PetscCall(ISCreateGeneral(comm, htsize, rowindices, PETSC_OWN_POINTER, &rows));
5670: /* In case, the matrix was already created but users want to recreate the matrix */
5671: PetscCall(MatDestroy(P_oth));
5672: PetscCall(MatCreateSeqSubMatrixWithRows_Private(P, rows, P_oth));
5673: PetscCall(PetscObjectCompose((PetscObject)*P_oth, "aoffdiagtopothmapping", (PetscObject)map));
5674: PetscCall(ISDestroy(&map));
5675: PetscCall(ISDestroy(&rows));
5676: } else if (reuse == MAT_REUSE_MATRIX) {
5677: /* If matrix was already created, we simply update values using SF objects
5678: * that as attached to the matrix earlier.
5679: */
5680: const PetscScalar *pd_a, *po_a;
5682: PetscCall(PetscObjectQuery((PetscObject)*P_oth, "diagsf", (PetscObject *)&sf));
5683: PetscCall(PetscObjectQuery((PetscObject)*P_oth, "offdiagsf", (PetscObject *)&osf));
5684: PetscCheck(sf && osf, comm, PETSC_ERR_ARG_NULL, "Matrix is not initialized yet");
5685: p_oth = (Mat_SeqAIJ *)(*P_oth)->data;
5686: /* Update values in place */
5687: PetscCall(MatSeqAIJGetArrayRead(p->A, &pd_a));
5688: PetscCall(MatSeqAIJGetArrayRead(p->B, &po_a));
5689: PetscCall(PetscSFBcastBegin(sf, MPIU_SCALAR, pd_a, p_oth->a, MPI_REPLACE));
5690: PetscCall(PetscSFBcastBegin(osf, MPIU_SCALAR, po_a, p_oth->a, MPI_REPLACE));
5691: PetscCall(PetscSFBcastEnd(sf, MPIU_SCALAR, pd_a, p_oth->a, MPI_REPLACE));
5692: PetscCall(PetscSFBcastEnd(osf, MPIU_SCALAR, po_a, p_oth->a, MPI_REPLACE));
5693: PetscCall(MatSeqAIJRestoreArrayRead(p->A, &pd_a));
5694: PetscCall(MatSeqAIJRestoreArrayRead(p->B, &po_a));
5695: } else SETERRQ(comm, PETSC_ERR_ARG_UNKNOWN_TYPE, "Unknown reuse type");
5696: PetscCall(PetscLogEventEnd(MAT_GetBrowsOfAocols, A, P, 0, 0));
5697: PetscFunctionReturn(PETSC_SUCCESS);
5698: }
5700: /*@
5701: MatGetBrowsOfAcols - Returns `IS` that contain rows of `B` that equal to nonzero columns of local `A`
5703: Collective
5705: Input Parameters:
5706: + A - the first matrix in `MATMPIAIJ` format
5707: . B - the second matrix in `MATMPIAIJ` format
5708: - scall - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`
5710: Output Parameters:
5711: + rowb - On input index sets of rows of B to extract (or `NULL`), modified on output
5712: . colb - On input index sets of columns of B to extract (or `NULL`), modified on output
5713: - B_seq - the sequential matrix generated
5715: Level: developer
5717: .seealso: `Mat`, `MATMPIAIJ`, `IS`, `MatReuse`
5718: @*/
5719: PetscErrorCode MatGetBrowsOfAcols(Mat A, Mat B, MatReuse scall, IS *rowb, IS *colb, Mat *B_seq)
5720: {
5721: Mat_MPIAIJ *a = (Mat_MPIAIJ *)A->data;
5722: PetscInt *idx, i, start, ncols, nzA, nzB, *cmap, imark;
5723: IS isrowb, iscolb;
5724: Mat *bseq = NULL;
5726: PetscFunctionBegin;
5727: 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 ")",
5728: A->cmap->rstart, A->cmap->rend, B->rmap->rstart, B->rmap->rend);
5729: PetscCall(PetscLogEventBegin(MAT_GetBrowsOfAcols, A, B, 0, 0));
5731: if (scall == MAT_INITIAL_MATRIX) {
5732: start = A->cmap->rstart;
5733: cmap = a->garray;
5734: nzA = a->A->cmap->n;
5735: nzB = a->B->cmap->n;
5736: PetscCall(PetscMalloc1(nzA + nzB, &idx));
5737: ncols = 0;
5738: for (i = 0; i < nzB; i++) { /* row < local row index */
5739: if (cmap[i] < start) idx[ncols++] = cmap[i];
5740: else break;
5741: }
5742: imark = i;
5743: for (i = 0; i < nzA; i++) idx[ncols++] = start + i; /* local rows */
5744: for (i = imark; i < nzB; i++) idx[ncols++] = cmap[i]; /* row > local row index */
5745: PetscCall(ISCreateGeneral(PETSC_COMM_SELF, ncols, idx, PETSC_OWN_POINTER, &isrowb));
5746: PetscCall(ISCreateStride(PETSC_COMM_SELF, B->cmap->N, 0, 1, &iscolb));
5747: } else {
5748: PetscCheck(rowb && colb, PETSC_COMM_SELF, PETSC_ERR_SUP, "IS rowb and colb must be provided for MAT_REUSE_MATRIX");
5749: isrowb = *rowb;
5750: iscolb = *colb;
5751: PetscCall(PetscMalloc1(1, &bseq));
5752: bseq[0] = *B_seq;
5753: }
5754: PetscCall(MatCreateSubMatrices(B, 1, &isrowb, &iscolb, scall, &bseq));
5755: *B_seq = bseq[0];
5756: PetscCall(PetscFree(bseq));
5757: if (!rowb) {
5758: PetscCall(ISDestroy(&isrowb));
5759: } else {
5760: *rowb = isrowb;
5761: }
5762: if (!colb) {
5763: PetscCall(ISDestroy(&iscolb));
5764: } else {
5765: *colb = iscolb;
5766: }
5767: PetscCall(PetscLogEventEnd(MAT_GetBrowsOfAcols, A, B, 0, 0));
5768: PetscFunctionReturn(PETSC_SUCCESS);
5769: }
5771: // PetscClangLinter pragma disable: -fdoc-sowing-chars
5772: /*
5773: MatGetBrowsOfAoCols_MPIAIJ - Creates a `MATSEQAIJ` matrix by taking rows of B that equal to nonzero columns
5774: of the OFF-DIAGONAL portion of local A
5776: Collective
5778: Input Parameters:
5779: + A - the first matrix in `MATMPIAIJ` format
5780: . B - the second matrix in `MATMPIAIJ` format
5781: - scall - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`
5783: Output Parameters:
5784: + startsj_s - starting point in B's sending j-arrays, saved for MAT_REUSE (or NULL)
5785: . startsj_r - starting point in B's receiving j-arrays, saved for MAT_REUSE (or NULL)
5786: . bufa_ptr - array for sending matrix values, saved for MAT_REUSE (or NULL)
5787: - B_oth - the sequential matrix generated with size aBn=a->B->cmap->n by B->cmap->N
5789: Level: developer
5791: Developer Note:
5792: This directly accesses information inside the VecScatter associated with the matrix-vector product
5793: for this matrix. This is not desirable.
5795: .seealso: [](ch_mat), `Mat`, `MATMPIAIJ`
5796: */
5797: PetscErrorCode MatGetBrowsOfAoCols_MPIAIJ(Mat A, Mat B, MatReuse scall, PetscInt **startsj_s, PetscInt **startsj_r, MatScalar **bufa_ptr, Mat *B_oth)
5798: {
5799: PetscFunctionBegin;
5800: PetscCall(MatGetBrowsOfAoCols_MPIAIJ_Private(A, B, scall, PETSC_FALSE, startsj_s, startsj_r, bufa_ptr, B_oth));
5801: PetscFunctionReturn(PETSC_SUCCESS);
5802: }
5804: 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)
5805: {
5806: Mat_MPIAIJ *a = (Mat_MPIAIJ *)A->data;
5807: VecScatter ctx;
5808: MPI_Comm comm;
5809: const PetscMPIInt *rprocs, *sprocs;
5810: PetscMPIInt nrecvs, nsends;
5811: const PetscInt *srow, *rstarts, *sstarts;
5812: PetscInt *rowlen, *bufj, *bufJ, ncols = 0, aBn = a->B->cmap->n, row, *b_othi, *b_othj, *rvalues = NULL, *svalues = NULL, *cols, sbs, rbs;
5813: PetscInt i, j, k = 0, l, ll, nrows, *rstartsj = NULL, *sstartsj, len;
5814: PetscScalar *b_otha = NULL, *bufa = NULL, *bufA, *vals = NULL;
5815: MPI_Request *reqs = NULL, *rwaits = NULL, *swaits = NULL;
5816: PetscMPIInt size, tag, rank, nreqs;
5818: PetscFunctionBegin;
5819: PetscCheck(!structure_only || scall == MAT_INITIAL_MATRIX, PETSC_COMM_SELF, PETSC_ERR_SUP, "Structure-only extraction requires MAT_INITIAL_MATRIX");
5820: PetscCall(PetscObjectGetComm((PetscObject)A, &comm));
5821: PetscCallMPI(MPI_Comm_size(comm, &size));
5823: 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 ")",
5824: A->cmap->rstart, A->cmap->rend, B->rmap->rstart, B->rmap->rend);
5825: PetscCall(PetscLogEventBegin(MAT_GetBrowsOfAocols, A, B, 0, 0));
5826: PetscCallMPI(MPI_Comm_rank(comm, &rank));
5828: if (size == 1) {
5829: startsj_s = NULL;
5830: bufa_ptr = NULL;
5831: *B_oth = NULL;
5832: PetscFunctionReturn(PETSC_SUCCESS);
5833: }
5835: ctx = a->Mvctx;
5836: tag = ((PetscObject)ctx)->tag;
5838: PetscCall(VecScatterGetRemote_Private(ctx, PETSC_TRUE /*send*/, &nsends, &sstarts, &srow, &sprocs, &sbs));
5839: /* rprocs[] must be ordered so that indices received from them are ordered in rvalues[], which is key to algorithms used in this subroutine */
5840: PetscCall(VecScatterGetRemoteOrdered_Private(ctx, PETSC_FALSE /*recv*/, &nrecvs, &rstarts, NULL /*indices not needed*/, &rprocs, &rbs));
5841: PetscCall(PetscMPIIntCast(nsends + nrecvs, &nreqs));
5842: PetscCall(PetscMalloc1(nreqs, &reqs));
5843: rwaits = reqs;
5844: swaits = PetscSafePointerPlusOffset(reqs, nrecvs);
5846: if (!startsj_s || !bufa_ptr) scall = MAT_INITIAL_MATRIX;
5847: if (scall == MAT_INITIAL_MATRIX) {
5848: /* i-array */
5849: /* post receives */
5850: if (nrecvs) PetscCall(PetscMalloc1(rbs * (rstarts[nrecvs] - rstarts[0]), &rvalues)); /* rstarts can be NULL when nrecvs=0 */
5851: for (i = 0; i < nrecvs; i++) {
5852: rowlen = rvalues + rstarts[i] * rbs;
5853: nrows = (rstarts[i + 1] - rstarts[i]) * rbs; /* num of indices to be received */
5854: PetscCallMPI(MPIU_Irecv(rowlen, nrows, MPIU_INT, rprocs[i], tag, comm, rwaits + i));
5855: }
5857: /* pack the outgoing message */
5858: PetscCall(PetscMalloc2(nsends + 1, &sstartsj, nrecvs + 1, &rstartsj));
5860: sstartsj[0] = 0;
5861: rstartsj[0] = 0;
5862: len = 0; /* total length of j or a array to be sent */
5863: if (nsends) {
5864: k = sstarts[0]; /* ATTENTION: sstarts[0] and rstarts[0] are not necessarily zero */
5865: PetscCall(PetscMalloc1(sbs * (sstarts[nsends] - sstarts[0]), &svalues));
5866: }
5867: for (i = 0; i < nsends; i++) {
5868: rowlen = svalues + (sstarts[i] - sstarts[0]) * sbs;
5869: nrows = sstarts[i + 1] - sstarts[i]; /* num of block rows */
5870: for (j = 0; j < nrows; j++) {
5871: row = srow[k] + B->rmap->range[rank]; /* global row idx */
5872: for (l = 0; l < sbs; l++) {
5873: PetscCall(MatGetRow_MPIAIJ(B, row + l, &ncols, NULL, NULL)); /* rowlength */
5875: rowlen[j * sbs + l] = ncols;
5877: len += ncols;
5878: PetscCall(MatRestoreRow_MPIAIJ(B, row + l, &ncols, NULL, NULL));
5879: }
5880: k++;
5881: }
5882: PetscCallMPI(MPIU_Isend(rowlen, nrows * sbs, MPIU_INT, sprocs[i], tag, comm, swaits + i));
5884: sstartsj[i + 1] = len; /* starting point of (i+1)-th outgoing msg in bufj and bufa */
5885: }
5886: /* recvs and sends of i-array are completed */
5887: if (nreqs) PetscCallMPI(MPI_Waitall(nreqs, reqs, MPI_STATUSES_IGNORE));
5888: PetscCall(PetscFree(svalues));
5890: /* allocate buffers for sending j and a arrays */
5891: PetscCall(PetscMalloc1(len, &bufj));
5892: if (!structure_only) PetscCall(PetscMalloc1(len, &bufa));
5894: /* create i-array of B_oth */
5895: PetscCall(PetscMalloc1(aBn + 1, &b_othi));
5897: b_othi[0] = 0;
5898: len = 0; /* total length of j or a array to be received */
5899: k = 0;
5900: for (i = 0; i < nrecvs; i++) {
5901: rowlen = rvalues + (rstarts[i] - rstarts[0]) * rbs;
5902: nrows = (rstarts[i + 1] - rstarts[i]) * rbs; /* num of rows to be received */
5903: for (j = 0; j < nrows; j++) {
5904: b_othi[k + 1] = b_othi[k] + rowlen[j];
5905: PetscCall(PetscIntSumError(rowlen[j], len, &len));
5906: k++;
5907: }
5908: rstartsj[i + 1] = len; /* starting point of (i+1)-th incoming msg in bufj and bufa */
5909: }
5910: PetscCall(PetscFree(rvalues));
5912: /* allocate space for j and a arrays of B_oth */
5913: PetscCall(PetscMalloc1(b_othi[aBn], &b_othj));
5914: if (!structure_only) PetscCall(PetscMalloc1(b_othi[aBn], &b_otha));
5916: /* j-array */
5917: /* post receives of j-array */
5918: for (i = 0; i < nrecvs; i++) {
5919: nrows = rstartsj[i + 1] - rstartsj[i]; /* length of the msg received */
5920: PetscCallMPI(MPIU_Irecv(PetscSafePointerPlusOffset(b_othj, rstartsj[i]), nrows, MPIU_INT, rprocs[i], tag, comm, rwaits + i));
5921: }
5923: /* pack the outgoing message j-array */
5924: if (nsends) k = sstarts[0];
5925: for (i = 0; i < nsends; i++) {
5926: nrows = sstarts[i + 1] - sstarts[i]; /* num of block rows */
5927: bufJ = PetscSafePointerPlusOffset(bufj, sstartsj[i]);
5928: for (j = 0; j < nrows; j++) {
5929: row = srow[k++] + B->rmap->range[rank]; /* global row idx */
5930: for (ll = 0; ll < sbs; ll++) {
5931: PetscCall(MatGetRow_MPIAIJ(B, row + ll, &ncols, &cols, NULL));
5932: for (l = 0; l < ncols; l++) *bufJ++ = cols[l];
5933: PetscCall(MatRestoreRow_MPIAIJ(B, row + ll, &ncols, &cols, NULL));
5934: }
5935: }
5936: PetscCallMPI(MPIU_Isend(PetscSafePointerPlusOffset(bufj, sstartsj[i]), sstartsj[i + 1] - sstartsj[i], MPIU_INT, sprocs[i], tag, comm, swaits + i));
5937: }
5939: /* recvs and sends of j-array are completed */
5940: if (nreqs) PetscCallMPI(MPI_Waitall(nreqs, reqs, MPI_STATUSES_IGNORE));
5941: } else if (scall == MAT_REUSE_MATRIX) {
5942: sstartsj = *startsj_s;
5943: rstartsj = *startsj_r;
5944: bufa = *bufa_ptr;
5945: PetscCall(MatSeqAIJGetArrayWrite(*B_oth, &b_otha));
5946: } else SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Matrix P does not possess an object container");
5948: if (!structure_only) {
5949: /* a-array */
5950: /* post receives of a-array */
5951: for (i = 0; i < nrecvs; i++) {
5952: nrows = rstartsj[i + 1] - rstartsj[i]; /* length of the msg received */
5953: PetscCallMPI(MPIU_Irecv(PetscSafePointerPlusOffset(b_otha, rstartsj[i]), nrows, MPIU_SCALAR, rprocs[i], tag, comm, rwaits + i));
5954: }
5956: /* pack the outgoing message a-array */
5957: if (nsends) k = sstarts[0];
5958: for (i = 0; i < nsends; i++) {
5959: nrows = sstarts[i + 1] - sstarts[i]; /* num of block rows */
5960: bufA = PetscSafePointerPlusOffset(bufa, sstartsj[i]);
5961: for (j = 0; j < nrows; j++) {
5962: row = srow[k++] + B->rmap->range[rank]; /* global row idx */
5963: for (ll = 0; ll < sbs; ll++) {
5964: PetscCall(MatGetRow_MPIAIJ(B, row + ll, &ncols, NULL, &vals));
5965: for (l = 0; l < ncols; l++) *bufA++ = vals[l];
5966: PetscCall(MatRestoreRow_MPIAIJ(B, row + ll, &ncols, NULL, &vals));
5967: }
5968: }
5969: PetscCallMPI(MPIU_Isend(PetscSafePointerPlusOffset(bufa, sstartsj[i]), sstartsj[i + 1] - sstartsj[i], MPIU_SCALAR, sprocs[i], tag, comm, swaits + i));
5970: }
5971: /* recvs and sends of a-array are completed */
5972: if (nreqs) PetscCallMPI(MPI_Waitall(nreqs, reqs, MPI_STATUSES_IGNORE));
5973: }
5974: PetscCall(PetscFree(reqs));
5976: if (scall == MAT_INITIAL_MATRIX) {
5977: Mat_SeqAIJ *b_oth;
5979: /* put together the new matrix */
5980: PetscCall(MatCreateSeqAIJWithArrays(PETSC_COMM_SELF, aBn, B->cmap->N, b_othi, b_othj, b_otha, B_oth));
5981: PetscCall(MatSetOption(*B_oth, MAT_STRUCTURE_ONLY, structure_only));
5983: /* MatCreateSeqAIJWithArrays flags matrix so PETSc doesn't free the user's arrays. */
5984: /* Since these are PETSc arrays, change flags to free them as necessary. */
5985: b_oth = (Mat_SeqAIJ *)(*B_oth)->data;
5986: b_oth->free_a = PETSC_TRUE;
5987: b_oth->free_ij = PETSC_TRUE;
5988: b_oth->nonew = 0;
5990: PetscCall(PetscFree(bufj));
5991: if (!startsj_s || !bufa_ptr) {
5992: PetscCall(PetscFree2(sstartsj, rstartsj));
5993: PetscCall(PetscFree(bufa_ptr));
5994: } else {
5995: *startsj_s = sstartsj;
5996: *startsj_r = rstartsj;
5997: *bufa_ptr = bufa;
5998: }
5999: } else if (scall == MAT_REUSE_MATRIX) {
6000: PetscCall(MatSeqAIJRestoreArrayWrite(*B_oth, &b_otha));
6001: }
6003: PetscCall(VecScatterRestoreRemote_Private(ctx, PETSC_TRUE, &nsends, &sstarts, &srow, &sprocs, &sbs));
6004: PetscCall(VecScatterRestoreRemoteOrdered_Private(ctx, PETSC_FALSE, &nrecvs, &rstarts, NULL, &rprocs, &rbs));
6005: PetscCall(PetscLogEventEnd(MAT_GetBrowsOfAocols, A, B, 0, 0));
6006: PetscFunctionReturn(PETSC_SUCCESS);
6007: }
6009: PETSC_INTERN PetscErrorCode MatConvert_MPIAIJ_MPIAIJCRL(Mat, MatType, MatReuse, Mat *);
6010: PETSC_INTERN PetscErrorCode MatConvert_MPIAIJ_MPIAIJPERM(Mat, MatType, MatReuse, Mat *);
6011: PETSC_INTERN PetscErrorCode MatConvert_MPIAIJ_MPIAIJSELL(Mat, MatType, MatReuse, Mat *);
6012: #if PetscDefined(HAVE_MKL_SPARSE)
6013: PETSC_INTERN PetscErrorCode MatConvert_MPIAIJ_MPIAIJMKL(Mat, MatType, MatReuse, Mat *);
6014: #endif
6015: PETSC_INTERN PetscErrorCode MatConvert_MPIAIJ_MPIBAIJ(Mat, MatType, MatReuse, Mat *);
6016: PETSC_INTERN PetscErrorCode MatConvert_MPIAIJ_MPISBAIJ(Mat, MatType, MatReuse, Mat *);
6017: #if PetscDefined(HAVE_ELEMENTAL)
6018: PETSC_INTERN PetscErrorCode MatConvert_MPIAIJ_Elemental(Mat, MatType, MatReuse, Mat *);
6019: #endif
6020: #if PetscDefined(HAVE_SCALAPACK) && (PetscDefined(USE_REAL_SINGLE) || PetscDefined(USE_REAL_DOUBLE))
6021: PETSC_INTERN PetscErrorCode MatConvert_AIJ_ScaLAPACK(Mat, MatType, MatReuse, Mat *);
6022: #endif
6023: #if PetscDefined(HAVE_HYPRE)
6024: PETSC_INTERN PetscErrorCode MatConvert_AIJ_HYPRE(Mat, MatType, MatReuse, Mat *);
6025: #endif
6026: #if PetscDefined(HAVE_CUDA)
6027: PETSC_INTERN PetscErrorCode MatConvert_MPIAIJ_MPIAIJCUSPARSE(Mat, MatType, MatReuse, Mat *);
6028: #endif
6029: #if PetscDefined(HAVE_HIP)
6030: PETSC_INTERN PetscErrorCode MatConvert_MPIAIJ_MPIAIJHIPSPARSE(Mat, MatType, MatReuse, Mat *);
6031: #endif
6032: #if PetscDefined(HAVE_KOKKOS_KERNELS)
6033: PETSC_INTERN PetscErrorCode MatConvert_MPIAIJ_MPIAIJKokkos(Mat, MatType, MatReuse, Mat *);
6034: #endif
6035: PETSC_INTERN PetscErrorCode MatConvert_MPIAIJ_MPISELL(Mat, MatType, MatReuse, Mat *);
6036: PETSC_INTERN PetscErrorCode MatConvert_XAIJ_IS(Mat, MatType, MatReuse, Mat *);
6037: PETSC_INTERN PetscErrorCode MatProductSetFromOptions_IS_XAIJ(Mat);
6039: /*
6040: Computes (B'*A')' since computing B*A directly is untenable
6042: n p p
6043: [ ] [ ] [ ]
6044: m [ A ] * n [ B ] = m [ C ]
6045: [ ] [ ] [ ]
6047: */
6048: static PetscErrorCode MatMatMultNumeric_MPIDense_MPIAIJ(Mat A, Mat B, Mat C)
6049: {
6050: Mat At, Bt, Ct;
6052: PetscFunctionBegin;
6053: PetscCall(MatTranspose(A, MAT_INITIAL_MATRIX, &At));
6054: PetscCall(MatTranspose(B, MAT_INITIAL_MATRIX, &Bt));
6055: PetscCall(MatMatMult(Bt, At, MAT_INITIAL_MATRIX, PETSC_CURRENT, &Ct));
6056: PetscCall(MatDestroy(&At));
6057: PetscCall(MatDestroy(&Bt));
6058: PetscCall(MatTransposeSetPrecursor(Ct, C));
6059: PetscCall(MatTranspose(Ct, MAT_REUSE_MATRIX, &C));
6060: PetscCall(MatDestroy(&Ct));
6061: PetscFunctionReturn(PETSC_SUCCESS);
6062: }
6064: static PetscErrorCode MatMatMultSymbolic_MPIDense_MPIAIJ(Mat A, Mat B, PetscReal fill, Mat C)
6065: {
6066: PetscBool cisdense;
6068: PetscFunctionBegin;
6069: 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);
6070: PetscCall(MatSetSizes(C, A->rmap->n, B->cmap->n, A->rmap->N, B->cmap->N));
6071: PetscCall(MatSetBlockSizesFromMats(C, A, B));
6072: PetscCall(PetscObjectTypeCompareAny((PetscObject)C, &cisdense, MATMPIDENSE, MATMPIDENSECUDA, MATMPIDENSEHIP, ""));
6073: if (!cisdense) {
6074: PetscCall(MatSetType(C, ((PetscObject)A)->type_name));
6075: PetscCall(MatSetVecType(C, A->defaultvectype));
6076: }
6077: PetscCall(MatSetUp(C));
6079: C->ops->matmultnumeric = MatMatMultNumeric_MPIDense_MPIAIJ;
6080: PetscFunctionReturn(PETSC_SUCCESS);
6081: }
6083: static PetscErrorCode MatProductSetFromOptions_MPIDense_MPIAIJ_AB(Mat C)
6084: {
6085: Mat_Product *product = C->product;
6086: Mat A = product->A, B = product->B;
6088: PetscFunctionBegin;
6089: 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 ")",
6090: A->cmap->rstart, A->cmap->rend, B->rmap->rstart, B->rmap->rend);
6091: C->ops->matmultsymbolic = MatMatMultSymbolic_MPIDense_MPIAIJ;
6092: C->ops->productsymbolic = MatProductSymbolic_AB;
6093: PetscFunctionReturn(PETSC_SUCCESS);
6094: }
6096: PETSC_INTERN PetscErrorCode MatProductSetFromOptions_MPIDense_MPIAIJ(Mat C)
6097: {
6098: Mat_Product *product = C->product;
6100: PetscFunctionBegin;
6101: if (product->type == MATPRODUCT_AB) PetscCall(MatProductSetFromOptions_MPIDense_MPIAIJ_AB(C));
6102: PetscFunctionReturn(PETSC_SUCCESS);
6103: }
6105: /*
6106: Merge two sets of sorted nonzeros and return a CSR for the merged (sequential) matrix
6108: Input Parameters:
6110: j1,rowBegin1,rowEnd1,jmap1: describe the first set of nonzeros (Set1)
6111: j2,rowBegin2,rowEnd2,jmap2: describe the second set of nonzeros (Set2)
6113: mat: both sets' nonzeros are on m rows, where m is the number of local rows of the matrix mat
6115: For Set1, j1[] contains column indices of the nonzeros.
6116: 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
6117: respectively (note rowEnd1[k] is not necessarily equal to rwoBegin1[k+1]). Indices in this range of j1[] are sorted,
6118: but might have repeats. jmap1[t+1] - jmap1[t] is the number of repeats for the t-th unique nonzero in Set1.
6120: Similar for Set2.
6122: This routine merges the two sets of nonzeros row by row and removes repeats.
6124: Output Parameters: (memory is allocated by the caller)
6126: i[],j[]: the CSR of the merged matrix, which has m rows.
6127: imap1[]: the k-th unique nonzero in Set1 (k=0,1,...) corresponds to imap1[k]-th unique nonzero in the merged matrix.
6128: imap2[]: similar to imap1[], but for Set2.
6129: Note we order nonzeros row-by-row and from left to right.
6130: */
6131: 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[])
6132: {
6133: PetscInt r, m; /* Row index of mat */
6134: PetscCount t, t1, t2, b1, e1, b2, e2;
6136: PetscFunctionBegin;
6137: PetscCall(MatGetLocalSize(mat, &m, NULL));
6138: t1 = t2 = t = 0; /* Count unique nonzeros of in Set1, Set1 and the merged respectively */
6139: i[0] = 0;
6140: for (r = 0; r < m; r++) { /* Do row by row merging */
6141: b1 = rowBegin1[r];
6142: e1 = rowEnd1[r];
6143: b2 = rowBegin2[r];
6144: e2 = rowEnd2[r];
6145: while (b1 < e1 && b2 < e2) {
6146: if (j1[b1] == j2[b2]) { /* Same column index and hence same nonzero */
6147: j[t] = j1[b1];
6148: imap1[t1] = t;
6149: imap2[t2] = t;
6150: b1 += jmap1[t1 + 1] - jmap1[t1]; /* Jump to next unique local nonzero */
6151: b2 += jmap2[t2 + 1] - jmap2[t2]; /* Jump to next unique remote nonzero */
6152: t1++;
6153: t2++;
6154: t++;
6155: } else if (j1[b1] < j2[b2]) {
6156: j[t] = j1[b1];
6157: imap1[t1] = t;
6158: b1 += jmap1[t1 + 1] - jmap1[t1];
6159: t1++;
6160: t++;
6161: } else {
6162: j[t] = j2[b2];
6163: imap2[t2] = t;
6164: b2 += jmap2[t2 + 1] - jmap2[t2];
6165: t2++;
6166: t++;
6167: }
6168: }
6169: /* Merge the remaining in either j1[] or j2[] */
6170: while (b1 < e1) {
6171: j[t] = j1[b1];
6172: imap1[t1] = t;
6173: b1 += jmap1[t1 + 1] - jmap1[t1];
6174: t1++;
6175: t++;
6176: }
6177: while (b2 < e2) {
6178: j[t] = j2[b2];
6179: imap2[t2] = t;
6180: b2 += jmap2[t2 + 1] - jmap2[t2];
6181: t2++;
6182: t++;
6183: }
6184: PetscCall(PetscIntCast(t, i + r + 1));
6185: }
6186: PetscFunctionReturn(PETSC_SUCCESS);
6187: }
6189: /*
6190: Split nonzeros in a block of local rows into two subsets: those in the diagonal block and those in the off-diagonal block
6192: Input Parameters:
6193: mat: an MPI matrix that provides row and column layout information for splitting. Let's say its number of local rows is m.
6194: 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[]
6195: respectively, along with a permutation array perm[]. Length of the i[],j[],perm[] arrays is n.
6197: i[] is already sorted, but within a row, j[] is not sorted and might have repeats.
6198: i[] might contain negative indices at the beginning, which means the corresponding entries should be ignored in the splitting.
6200: Output Parameters:
6201: j[],perm[]: the routine needs to sort j[] within each row along with perm[].
6202: rowBegin[],rowMid[],rowEnd[]: of length m, and the memory is preallocated and zeroed by the caller.
6203: 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,
6204: and [rowMid[r],rowEnd[r]) point to begin/end entries of row r of the off-diagonal block.
6206: Aperm[],Ajmap[],Atot,Annz: Arrays are allocated by this routine.
6207: Atot: number of entries belonging to the diagonal block.
6208: Annz: number of unique nonzeros belonging to the diagonal block.
6209: Aperm[Atot] stores values from perm[] for entries belonging to the diagonal block. Length of Aperm[] is Atot, though it may also count
6210: repeats (i.e., same 'i,j' pair).
6211: Ajmap[Annz+1] stores the number of repeats of each unique entry belonging to the diagonal block. More precisely, Ajmap[t+1] - Ajmap[t]
6212: is the number of repeats for the t-th unique entry in the diagonal block. Ajmap[0] is always 0.
6214: Atot: number of entries belonging to the diagonal block
6215: Annz: number of unique nonzeros belonging to the diagonal block.
6217: Bperm[], Bjmap[], Btot, Bnnz are similar but for the off-diagonal block.
6219: Aperm[],Bperm[],Ajmap[] and Bjmap[] are allocated separately by this routine with PetscMalloc1().
6220: */
6221: 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_)
6222: {
6223: PetscInt cstart, cend, rstart, rend, row, col;
6224: PetscCount Atot = 0, Btot = 0; /* Total number of nonzeros in the diagonal and off-diagonal blocks */
6225: PetscCount Annz = 0, Bnnz = 0; /* Number of unique nonzeros in the diagonal and off-diagonal blocks */
6226: PetscCount k, m, p, q, r, s, mid;
6227: PetscCount *Aperm, *Bperm, *Ajmap, *Bjmap;
6229: PetscFunctionBegin;
6230: PetscCall(PetscLayoutGetRange(mat->rmap, &rstart, &rend));
6231: PetscCall(PetscLayoutGetRange(mat->cmap, &cstart, &cend));
6232: m = rend - rstart;
6234: /* Skip negative rows */
6235: for (k = 0; k < n; k++)
6236: if (i[k] >= 0) break;
6238: /* Process [k,n): sort and partition each local row into diag and offdiag portions,
6239: fill rowBegin[], rowMid[], rowEnd[], and count Atot, Btot, Annz, Bnnz.
6240: */
6241: while (k < n) {
6242: row = i[k];
6243: /* Entries in [k,s) are in one row. Shift diagonal block col indices so that diag is ahead of offdiag after sorting the row */
6244: for (s = k; s < n; s++)
6245: if (i[s] != row) break;
6247: /* Shift diag columns to range of [-PETSC_INT_MAX, -1] */
6248: for (p = k; p < s; p++) {
6249: if (j[p] >= cstart && j[p] < cend) j[p] -= PETSC_INT_MAX;
6250: }
6251: PetscCall(PetscSortIntWithCountArray(s - k, j + k, perm + k));
6252: PetscCall(PetscSortedIntUpperBound(j, k, s, -1, &mid)); /* Separate [k,s) into [k,mid) for diag and [mid,s) for offdiag */
6253: rowBegin[row - rstart] = k;
6254: rowMid[row - rstart] = mid;
6255: rowEnd[row - rstart] = s;
6256: 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);
6258: /* Count nonzeros of this diag/offdiag row, which might have repeats */
6259: Atot += mid - k;
6260: Btot += s - mid;
6262: /* Count unique nonzeros of this diag row */
6263: for (p = k; p < mid;) {
6264: col = j[p];
6265: do {
6266: j[p] += PETSC_INT_MAX; /* Revert the modified diagonal indices */
6267: p++;
6268: } while (p < mid && j[p] == col);
6269: Annz++;
6270: }
6272: /* Count unique nonzeros of this offdiag row */
6273: for (p = mid; p < s;) {
6274: col = j[p];
6275: do {
6276: p++;
6277: } while (p < s && j[p] == col);
6278: Bnnz++;
6279: }
6280: k = s;
6281: }
6283: /* Allocation according to Atot, Btot, Annz, Bnnz */
6284: PetscCall(PetscMalloc1(Atot, &Aperm));
6285: PetscCall(PetscMalloc1(Btot, &Bperm));
6286: PetscCall(PetscMalloc1(Annz + 1, &Ajmap));
6287: PetscCall(PetscMalloc1(Bnnz + 1, &Bjmap));
6289: /* Re-scan indices and copy diag/offdiag permutation indices to Aperm, Bperm and also fill Ajmap and Bjmap */
6290: Ajmap[0] = Bjmap[0] = Atot = Btot = Annz = Bnnz = 0;
6291: for (r = 0; r < m; r++) {
6292: k = rowBegin[r];
6293: mid = rowMid[r];
6294: s = rowEnd[r];
6295: PetscCall(PetscArraycpy(PetscSafePointerPlusOffset(Aperm, Atot), PetscSafePointerPlusOffset(perm, k), mid - k));
6296: PetscCall(PetscArraycpy(PetscSafePointerPlusOffset(Bperm, Btot), PetscSafePointerPlusOffset(perm, mid), s - mid));
6297: Atot += mid - k;
6298: Btot += s - mid;
6300: /* Scan column indices in this row and find out how many repeats each unique nonzero has */
6301: for (p = k; p < mid;) {
6302: col = j[p];
6303: q = p;
6304: do {
6305: p++;
6306: } while (p < mid && j[p] == col);
6307: Ajmap[Annz + 1] = Ajmap[Annz] + (p - q);
6308: Annz++;
6309: }
6311: for (p = mid; p < s;) {
6312: col = j[p];
6313: q = p;
6314: do {
6315: p++;
6316: } while (p < s && j[p] == col);
6317: Bjmap[Bnnz + 1] = Bjmap[Bnnz] + (p - q);
6318: Bnnz++;
6319: }
6320: }
6321: /* Output */
6322: *Aperm_ = Aperm;
6323: *Annz_ = Annz;
6324: *Atot_ = Atot;
6325: *Ajmap_ = Ajmap;
6326: *Bperm_ = Bperm;
6327: *Bnnz_ = Bnnz;
6328: *Btot_ = Btot;
6329: *Bjmap_ = Bjmap;
6330: PetscFunctionReturn(PETSC_SUCCESS);
6331: }
6333: /*
6334: Expand the jmap[] array to make a new one in view of nonzeros in the merged matrix
6336: Input Parameters:
6337: nnz1: number of unique nonzeros in a set that was used to produce imap[], jmap[]
6338: nnz: number of unique nonzeros in the merged matrix
6339: imap[nnz1]: i-th nonzero in the set is the imap[i]-th nonzero in the merged matrix
6340: jmap[nnz1+1]: i-th nonzero in the set has jmap[i+1] - jmap[i] repeats in the set
6342: Output Parameter: (memory is allocated by the caller)
6343: jmap_new[nnz+1]: i-th nonzero in the merged matrix has jmap_new[i+1] - jmap_new[i] repeats in the set
6345: Example:
6346: nnz1 = 4
6347: nnz = 6
6348: imap = [1,3,4,5]
6349: jmap = [0,3,5,6,7]
6350: then,
6351: jmap_new = [0,0,3,3,5,6,7]
6352: */
6353: static PetscErrorCode ExpandJmap_Internal(PetscCount nnz1, PetscCount nnz, const PetscCount imap[], const PetscCount jmap[], PetscCount jmap_new[])
6354: {
6355: PetscCount k, p;
6357: PetscFunctionBegin;
6358: jmap_new[0] = 0;
6359: p = nnz; /* p loops over jmap_new[] backwards */
6360: for (k = nnz1 - 1; k >= 0; k--) { /* k loops over imap[] */
6361: for (; p > imap[k]; p--) jmap_new[p] = jmap[k + 1];
6362: }
6363: for (; p >= 0; p--) jmap_new[p] = jmap[0];
6364: PetscFunctionReturn(PETSC_SUCCESS);
6365: }
6367: static PetscErrorCode MatCOOStructDestroy_MPIAIJ(PetscCtxRt data)
6368: {
6369: MatCOOStruct_MPIAIJ *coo = *(MatCOOStruct_MPIAIJ **)data;
6371: PetscFunctionBegin;
6372: PetscCall(PetscSFDestroy(&coo->sf));
6373: PetscCall(PetscFree(coo->Aperm1));
6374: PetscCall(PetscFree(coo->Bperm1));
6375: PetscCall(PetscFree(coo->Ajmap1));
6376: PetscCall(PetscFree(coo->Bjmap1));
6377: PetscCall(PetscFree(coo->Aimap2));
6378: PetscCall(PetscFree(coo->Bimap2));
6379: PetscCall(PetscFree(coo->Aperm2));
6380: PetscCall(PetscFree(coo->Bperm2));
6381: PetscCall(PetscFree(coo->Ajmap2));
6382: PetscCall(PetscFree(coo->Bjmap2));
6383: PetscCall(PetscFree(coo->Cperm1));
6384: PetscCall(PetscFree2(coo->sendbuf, coo->recvbuf));
6385: PetscCall(PetscFree(coo));
6386: PetscFunctionReturn(PETSC_SUCCESS);
6387: }
6389: PetscErrorCode MatSetPreallocationCOO_MPIAIJ(Mat mat, PetscCount coo_n, PetscInt coo_i[], PetscInt coo_j[])
6390: {
6391: MPI_Comm comm;
6392: PetscMPIInt rank, size;
6393: PetscInt m, n, M, N, rstart, rend, cstart, cend; /* Sizes, indices of row/col, therefore with type PetscInt */
6394: PetscCount k, p, q, rem; /* Loop variables over coo arrays */
6395: Mat_MPIAIJ *mpiaij = (Mat_MPIAIJ *)mat->data;
6396: PetscContainer container;
6397: MatCOOStruct_MPIAIJ *coo;
6399: PetscFunctionBegin;
6400: // The A and B blocks built below leave B with compacted column indices, which MatSetValues_MPI_Hash() cannot fill
6401: if (mat->hash_active) {
6402: mat->ops[0] = mpiaij->cops;
6403: mat->hash_active = PETSC_FALSE;
6404: }
6405: PetscCall(PetscFree(mpiaij->garray));
6406: PetscCall(VecDestroy(&mpiaij->lvec));
6407: #if PetscDefined(USE_CTABLE)
6408: PetscCall(PetscHMapIDestroy(&mpiaij->colmap));
6409: #else
6410: PetscCall(PetscFree(mpiaij->colmap));
6411: #endif
6412: PetscCall(VecScatterDestroy(&mpiaij->Mvctx));
6413: mat->assembled = PETSC_FALSE;
6414: mat->was_assembled = PETSC_FALSE;
6416: PetscCall(PetscObjectGetComm((PetscObject)mat, &comm));
6417: PetscCallMPI(MPI_Comm_size(comm, &size));
6418: PetscCallMPI(MPI_Comm_rank(comm, &rank));
6419: PetscCall(PetscLayoutSetUp(mat->rmap));
6420: PetscCall(PetscLayoutSetUp(mat->cmap));
6421: PetscCall(PetscLayoutGetRange(mat->rmap, &rstart, &rend));
6422: PetscCall(PetscLayoutGetRange(mat->cmap, &cstart, &cend));
6423: PetscCall(MatGetLocalSize(mat, &m, &n));
6424: PetscCall(MatGetSize(mat, &M, &N));
6426: /* Sort (i,j) by row along with a permutation array, so that the to-be-ignored */
6427: /* entries come first, then local rows, then remote rows. */
6428: PetscCount n1 = coo_n, *perm1;
6429: PetscInt *i1 = coo_i, *j1 = coo_j;
6431: PetscCall(PetscMalloc1(n1, &perm1));
6432: for (k = 0; k < n1; k++) perm1[k] = k;
6434: /* Manipulate indices so that entries with negative row or col indices will have smallest
6435: row indices, local entries will have greater but negative row indices, and remote entries
6436: will have positive row indices.
6437: */
6438: for (k = 0; k < n1; k++) {
6439: if (i1[k] < 0 || j1[k] < 0) i1[k] = PETSC_INT_MIN; /* e.g., -2^31, minimal to move them ahead */
6440: 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] */
6441: else {
6442: PetscCheck(!mat->nooffprocentries, PETSC_COMM_SELF, PETSC_ERR_USER_INPUT, "MAT_NO_OFF_PROC_ENTRIES is set but insert to remote rows");
6443: if (mpiaij->donotstash) i1[k] = PETSC_INT_MIN; /* Ignore offproc entries as if they had negative indices */
6444: }
6445: }
6447: /* Sort by row; after that, [0,k) have ignored entries, [k,rem) have local rows and [rem,n1) have remote rows */
6448: PetscCall(PetscSortIntWithIntCountArrayPair(n1, i1, j1, perm1));
6450: /* Advance k to the first entry we need to take care of */
6451: for (k = 0; k < n1; k++)
6452: if (i1[k] > PETSC_INT_MIN) break;
6453: PetscCount i1start = k;
6455: PetscCall(PetscSortedIntUpperBound(i1, k, n1, rend - 1 - PETSC_INT_MAX, &rem)); /* rem is upper bound of the last local row */
6456: for (; k < rem; k++) i1[k] += PETSC_INT_MAX; /* Revert row indices of local rows*/
6458: 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);
6460: /* Send remote rows to their owner */
6461: /* Find which rows should be sent to which remote ranks*/
6462: PetscInt nsend = 0; /* Number of MPI ranks to send data to */
6463: PetscMPIInt *sendto; /* [nsend], storing remote ranks */
6464: PetscInt *nentries; /* [nsend], storing number of entries sent to remote ranks; Assume PetscInt is big enough for this count, and error if not */
6465: const PetscInt *ranges;
6466: PetscInt maxNsend = size >= 128 ? 128 : size; /* Assume max 128 neighbors; realloc when needed */
6468: PetscCall(PetscLayoutGetRanges(mat->rmap, &ranges));
6469: PetscCall(PetscMalloc2(maxNsend, &sendto, maxNsend, &nentries));
6470: for (k = rem; k < n1;) {
6471: PetscMPIInt owner;
6472: PetscInt firstRow, lastRow;
6474: /* Locate a row range */
6475: firstRow = i1[k]; /* first row of this owner */
6476: PetscCall(PetscLayoutFindOwner(mat->rmap, firstRow, &owner));
6477: lastRow = ranges[owner + 1] - 1; /* last row of this owner */
6479: /* Find the first index 'p' in [k,n) with i1[p] belonging to next owner */
6480: PetscCall(PetscSortedIntUpperBound(i1, k, n1, lastRow, &p));
6482: /* All entries in [k,p) belong to this remote owner */
6483: if (nsend >= maxNsend) { /* Double the remote ranks arrays if not long enough */
6484: PetscMPIInt *sendto2;
6485: PetscInt *nentries2;
6486: PetscInt maxNsend2 = (maxNsend <= size / 2) ? maxNsend * 2 : size;
6488: PetscCall(PetscMalloc2(maxNsend2, &sendto2, maxNsend2, &nentries2));
6489: PetscCall(PetscArraycpy(sendto2, sendto, maxNsend));
6490: PetscCall(PetscArraycpy(nentries2, nentries, maxNsend));
6491: PetscCall(PetscFree2(sendto, nentries));
6492: sendto = sendto2;
6493: nentries = nentries2;
6494: maxNsend = maxNsend2;
6495: }
6496: sendto[nsend] = owner;
6497: PetscCall(PetscIntCast(p - k, &nentries[nsend]));
6498: nsend++;
6499: k = p;
6500: }
6502: /* Build 1st SF to know offsets on remote to send data */
6503: PetscSF sf1;
6504: PetscInt nroots = 1, nroots2 = 0;
6505: PetscInt nleaves = nsend, nleaves2 = 0;
6506: PetscInt *offsets;
6507: PetscSFNode *iremote;
6509: PetscCall(PetscSFCreate(comm, &sf1));
6510: PetscCall(PetscMalloc1(nsend, &iremote));
6511: PetscCall(PetscMalloc1(nsend, &offsets));
6512: for (k = 0; k < nsend; k++) {
6513: iremote[k].rank = sendto[k];
6514: iremote[k].index = 0;
6515: nleaves2 += nentries[k];
6516: PetscCheck(nleaves2 >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Number of SF leaves is too large for PetscInt");
6517: }
6518: PetscCall(PetscSFSetGraph(sf1, nroots, nleaves, NULL, PETSC_OWN_POINTER, iremote, PETSC_OWN_POINTER));
6519: PetscCall(PetscSFFetchAndOpWithMemTypeBegin(sf1, MPIU_INT, PETSC_MEMTYPE_HOST, &nroots2 /*rootdata*/, PETSC_MEMTYPE_HOST, nentries /*leafdata*/, PETSC_MEMTYPE_HOST, offsets /*leafupdate*/, MPI_SUM));
6520: PetscCall(PetscSFFetchAndOpEnd(sf1, MPIU_INT, &nroots2, nentries, offsets, MPI_SUM)); /* Would nroots2 overflow, we check offsets[] below */
6521: PetscCall(PetscSFDestroy(&sf1));
6522: PetscAssert(nleaves2 == n1 - rem, PETSC_COMM_SELF, PETSC_ERR_PLIB, "nleaves2 %" PetscInt_FMT " != number of remote entries %" PetscCount_FMT, nleaves2, n1 - rem);
6524: /* Build 2nd SF to send remote COOs to their owner */
6525: PetscSF sf2;
6526: nroots = nroots2;
6527: nleaves = nleaves2;
6528: PetscCall(PetscSFCreate(comm, &sf2));
6529: PetscCall(PetscSFSetFromOptions(sf2));
6530: PetscCall(PetscMalloc1(nleaves, &iremote));
6531: p = 0;
6532: for (k = 0; k < nsend; k++) {
6533: PetscCheck(offsets[k] >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Number of SF roots is too large for PetscInt");
6534: for (q = 0; q < nentries[k]; q++, p++) {
6535: iremote[p].rank = sendto[k];
6536: PetscCall(PetscIntCast(offsets[k] + q, &iremote[p].index));
6537: }
6538: }
6539: PetscCall(PetscSFSetGraph(sf2, nroots, nleaves, NULL, PETSC_OWN_POINTER, iremote, PETSC_OWN_POINTER));
6541: /* Send the remote COOs to their owner */
6542: PetscInt n2 = nroots, *i2, *j2; /* Buffers for received COOs from other ranks, along with a permutation array */
6543: PetscCount *perm2; /* Though PetscInt is enough for remote entries, we use PetscCount here as we want to reuse MatSplitEntries_Internal() */
6544: PetscCall(PetscMalloc3(n2, &i2, n2, &j2, n2, &perm2));
6545: PetscAssert(rem == 0 || i1 != NULL, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Cannot add nonzero offset to null");
6546: PetscAssert(rem == 0 || j1 != NULL, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Cannot add nonzero offset to null");
6547: PetscInt *i1prem = PetscSafePointerPlusOffset(i1, rem);
6548: PetscInt *j1prem = PetscSafePointerPlusOffset(j1, rem);
6549: PetscCall(PetscSFReduceWithMemTypeBegin(sf2, MPIU_INT, PETSC_MEMTYPE_HOST, i1prem, PETSC_MEMTYPE_HOST, i2, MPI_REPLACE));
6550: PetscCall(PetscSFReduceEnd(sf2, MPIU_INT, i1prem, i2, MPI_REPLACE));
6551: PetscCall(PetscSFReduceWithMemTypeBegin(sf2, MPIU_INT, PETSC_MEMTYPE_HOST, j1prem, PETSC_MEMTYPE_HOST, j2, MPI_REPLACE));
6552: PetscCall(PetscSFReduceEnd(sf2, MPIU_INT, j1prem, j2, MPI_REPLACE));
6554: PetscCall(PetscFree(offsets));
6555: PetscCall(PetscFree2(sendto, nentries));
6557: /* Sort received COOs by row along with the permutation array */
6558: for (k = 0; k < n2; k++) perm2[k] = k;
6559: PetscCall(PetscSortIntWithIntCountArrayPair(n2, i2, j2, perm2));
6561: /* sf2 only sends contiguous leafdata to contiguous rootdata. We record the permutation which will be used to fill leafdata */
6562: PetscCount *Cperm1;
6563: PetscAssert(rem == 0 || perm1 != NULL, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Cannot add nonzero offset to null");
6564: PetscCount *perm1prem = PetscSafePointerPlusOffset(perm1, rem);
6565: PetscCall(PetscMalloc1(nleaves, &Cperm1));
6566: PetscCall(PetscArraycpy(Cperm1, perm1prem, nleaves));
6568: /* Support for HYPRE matrices, kind of a hack.
6569: Swap min column with diagonal so that diagonal values will go first */
6570: PetscBool hypre;
6571: PetscCall(PetscStrcmp("_internal_COO_mat_for_hypre", ((PetscObject)mat)->name, &hypre));
6572: if (hypre) {
6573: PetscInt *minj;
6574: PetscBT hasdiag;
6576: PetscCall(PetscBTCreate(m, &hasdiag));
6577: PetscCall(PetscMalloc1(m, &minj));
6578: for (k = 0; k < m; k++) minj[k] = PETSC_INT_MAX;
6579: for (k = i1start; k < rem; k++) {
6580: if (j1[k] < cstart || j1[k] >= cend) continue;
6581: const PetscInt rindex = i1[k] - rstart;
6582: if ((j1[k] - cstart) == rindex) PetscCall(PetscBTSet(hasdiag, rindex));
6583: minj[rindex] = PetscMin(minj[rindex], j1[k]);
6584: }
6585: for (k = 0; k < n2; k++) {
6586: if (j2[k] < cstart || j2[k] >= cend) continue;
6587: const PetscInt rindex = i2[k] - rstart;
6588: if ((j2[k] - cstart) == rindex) PetscCall(PetscBTSet(hasdiag, rindex));
6589: minj[rindex] = PetscMin(minj[rindex], j2[k]);
6590: }
6591: for (k = i1start; k < rem; k++) {
6592: const PetscInt rindex = i1[k] - rstart;
6593: if (j1[k] < cstart || j1[k] >= cend || !PetscBTLookup(hasdiag, rindex)) continue;
6594: if (j1[k] == minj[rindex]) j1[k] = i1[k] + (cstart - rstart);
6595: else if ((j1[k] - cstart) == rindex) j1[k] = minj[rindex];
6596: }
6597: for (k = 0; k < n2; k++) {
6598: const PetscInt rindex = i2[k] - rstart;
6599: if (j2[k] < cstart || j2[k] >= cend || !PetscBTLookup(hasdiag, rindex)) continue;
6600: if (j2[k] == minj[rindex]) j2[k] = i2[k] + (cstart - rstart);
6601: else if ((j2[k] - cstart) == rindex) j2[k] = minj[rindex];
6602: }
6603: PetscCall(PetscBTDestroy(&hasdiag));
6604: PetscCall(PetscFree(minj));
6605: }
6607: /* Split local COOs and received COOs into diag/offdiag portions */
6608: PetscCount *rowBegin1, *rowMid1, *rowEnd1;
6609: PetscCount *Ajmap1, *Aperm1, *Bjmap1, *Bperm1;
6610: PetscCount Annz1, Bnnz1, Atot1, Btot1;
6611: PetscCount *rowBegin2, *rowMid2, *rowEnd2;
6612: PetscCount *Ajmap2, *Aperm2, *Bjmap2, *Bperm2;
6613: PetscCount Annz2, Bnnz2, Atot2, Btot2;
6615: PetscCall(PetscCalloc3(m, &rowBegin1, m, &rowMid1, m, &rowEnd1));
6616: PetscCall(PetscCalloc3(m, &rowBegin2, m, &rowMid2, m, &rowEnd2));
6617: PetscCall(MatSplitEntries_Internal(mat, rem, i1, j1, perm1, rowBegin1, rowMid1, rowEnd1, &Atot1, &Aperm1, &Annz1, &Ajmap1, &Btot1, &Bperm1, &Bnnz1, &Bjmap1));
6618: PetscCall(MatSplitEntries_Internal(mat, n2, i2, j2, perm2, rowBegin2, rowMid2, rowEnd2, &Atot2, &Aperm2, &Annz2, &Ajmap2, &Btot2, &Bperm2, &Bnnz2, &Bjmap2));
6620: /* Merge local COOs with received COOs: diag with diag, offdiag with offdiag */
6621: PetscInt *Ai, *Bi;
6622: PetscInt *Aj, *Bj;
6624: PetscCall(PetscMalloc1(m + 1, &Ai));
6625: PetscCall(PetscMalloc1(m + 1, &Bi));
6626: PetscCall(PetscMalloc1(Annz1 + Annz2, &Aj)); /* Since local and remote entries might have dups, we might allocate excess memory */
6627: PetscCall(PetscMalloc1(Bnnz1 + Bnnz2, &Bj));
6629: PetscCount *Aimap1, *Bimap1, *Aimap2, *Bimap2;
6630: PetscCall(PetscMalloc1(Annz1, &Aimap1));
6631: PetscCall(PetscMalloc1(Bnnz1, &Bimap1));
6632: PetscCall(PetscMalloc1(Annz2, &Aimap2));
6633: PetscCall(PetscMalloc1(Bnnz2, &Bimap2));
6635: PetscCall(MatMergeEntries_Internal(mat, j1, j2, rowBegin1, rowMid1, rowBegin2, rowMid2, Ajmap1, Ajmap2, Aimap1, Aimap2, Ai, Aj));
6636: PetscCall(MatMergeEntries_Internal(mat, j1, j2, rowMid1, rowEnd1, rowMid2, rowEnd2, Bjmap1, Bjmap2, Bimap1, Bimap2, Bi, Bj));
6638: /* Expand Ajmap1/Bjmap1 to make them based off nonzeros in A/B, since we */
6639: /* expect nonzeros in A/B most likely have local contributing entries */
6640: PetscInt Annz = Ai[m];
6641: PetscInt Bnnz = Bi[m];
6642: PetscCount *Ajmap1_new, *Bjmap1_new;
6644: PetscCall(PetscMalloc1(Annz + 1, &Ajmap1_new));
6645: PetscCall(PetscMalloc1(Bnnz + 1, &Bjmap1_new));
6647: PetscCall(ExpandJmap_Internal(Annz1, Annz, Aimap1, Ajmap1, Ajmap1_new));
6648: PetscCall(ExpandJmap_Internal(Bnnz1, Bnnz, Bimap1, Bjmap1, Bjmap1_new));
6650: PetscCall(PetscFree(Aimap1));
6651: PetscCall(PetscFree(Ajmap1));
6652: PetscCall(PetscFree(Bimap1));
6653: PetscCall(PetscFree(Bjmap1));
6654: PetscCall(PetscFree3(rowBegin1, rowMid1, rowEnd1));
6655: PetscCall(PetscFree3(rowBegin2, rowMid2, rowEnd2));
6656: PetscCall(PetscFree(perm1));
6657: PetscCall(PetscFree3(i2, j2, perm2));
6659: Ajmap1 = Ajmap1_new;
6660: Bjmap1 = Bjmap1_new;
6662: /* Reallocate Aj, Bj once we know actual numbers of unique nonzeros in A and B */
6663: if (Annz < Annz1 + Annz2) {
6664: PetscInt *Aj_new;
6665: PetscCall(PetscMalloc1(Annz, &Aj_new));
6666: PetscCall(PetscArraycpy(Aj_new, Aj, Annz));
6667: PetscCall(PetscFree(Aj));
6668: Aj = Aj_new;
6669: }
6671: if (Bnnz < Bnnz1 + Bnnz2) {
6672: PetscInt *Bj_new;
6673: PetscCall(PetscMalloc1(Bnnz, &Bj_new));
6674: PetscCall(PetscArraycpy(Bj_new, Bj, Bnnz));
6675: PetscCall(PetscFree(Bj));
6676: Bj = Bj_new;
6677: }
6679: /* Create new submatrices for on-process and off-process coupling */
6680: PetscScalar *Aa = NULL, *Ba = NULL;
6681: MatType rtype;
6682: Mat_SeqAIJ *a, *b;
6683: if (!mat->structure_only) {
6684: PetscCall(PetscCalloc1(Annz, &Aa)); /* Zero matrix on device */
6685: PetscCall(PetscCalloc1(Bnnz, &Ba));
6686: }
6687: /* make Aj[] local, i.e, based off the start column of the diagonal portion */
6688: if (cstart) {
6689: for (k = 0; k < Annz; k++) Aj[k] -= cstart;
6690: }
6692: PetscCall(MatGetRootType_Private(mat, &rtype));
6694: MatSeqXAIJGetOptions_Private(mpiaij->A);
6695: PetscCall(MatDestroy(&mpiaij->A));
6696: PetscCall(MatCreateSeqAIJWithArrays(PETSC_COMM_SELF, m, n, Ai, Aj, Aa, &mpiaij->A));
6697: PetscCall(MatSetBlockSizesFromMats(mpiaij->A, mat, mat));
6698: MatSeqXAIJRestoreOptions_Private(mpiaij->A);
6699: PetscCall(MatSetOption(mpiaij->A, MAT_STRUCTURE_ONLY, mat->structure_only));
6701: MatSeqXAIJGetOptions_Private(mpiaij->B);
6702: PetscCall(MatDestroy(&mpiaij->B));
6703: PetscCall(MatCreateSeqAIJWithArrays(PETSC_COMM_SELF, m, mat->cmap->N, Bi, Bj, Ba, &mpiaij->B));
6704: PetscCall(MatSetBlockSizesFromMats(mpiaij->B, mat, mat));
6705: MatSeqXAIJRestoreOptions_Private(mpiaij->B);
6706: PetscCall(MatSetOption(mpiaij->B, MAT_STRUCTURE_ONLY, mat->structure_only));
6708: PetscCall(MatSetUpMultiply_MPIAIJ(mat));
6709: mat->was_assembled = PETSC_TRUE; // was_assembled in effect means the Mvctx is built; doing so avoids redundant MatSetUpMultiply_MPIAIJ
6710: mat->nonzerostate = mpiaij->A->nonzerostate + mpiaij->B->nonzerostate;
6711: PetscCallMPI(MPIU_Allreduce(MPI_IN_PLACE, &mat->nonzerostate, 1, MPIU_INT64, MPI_SUM, PetscObjectComm((PetscObject)mat)));
6713: a = (Mat_SeqAIJ *)mpiaij->A->data;
6714: b = (Mat_SeqAIJ *)mpiaij->B->data;
6715: a->free_a = (PetscBool)!mat->structure_only;
6716: a->free_ij = PETSC_TRUE;
6717: b->free_a = (PetscBool)!mat->structure_only;
6718: b->free_ij = PETSC_TRUE;
6719: a->maxnz = a->nz;
6720: b->maxnz = b->nz;
6722: /* conversion must happen AFTER multiply setup */
6723: PetscCall(MatConvert(mpiaij->A, rtype, MAT_INPLACE_MATRIX, &mpiaij->A));
6724: PetscCall(MatConvert(mpiaij->B, rtype, MAT_INPLACE_MATRIX, &mpiaij->B));
6725: PetscCall(VecDestroy(&mpiaij->lvec));
6726: PetscCall(MatCreateVecs(mpiaij->B, &mpiaij->lvec, NULL));
6728: // Put the COO struct in a container and then attach that to the matrix
6729: PetscCall(PetscMalloc1(1, &coo));
6730: coo->n = coo_n;
6731: coo->sf = sf2;
6732: coo->sendlen = nleaves;
6733: coo->recvlen = nroots;
6734: coo->Annz = Annz;
6735: coo->Bnnz = Bnnz;
6736: coo->Annz2 = Annz2;
6737: coo->Bnnz2 = Bnnz2;
6738: coo->Atot1 = Atot1;
6739: coo->Atot2 = Atot2;
6740: coo->Btot1 = Btot1;
6741: coo->Btot2 = Btot2;
6742: coo->Ajmap1 = Ajmap1;
6743: coo->Aperm1 = Aperm1;
6744: coo->Bjmap1 = Bjmap1;
6745: coo->Bperm1 = Bperm1;
6746: coo->Aimap2 = Aimap2;
6747: coo->Ajmap2 = Ajmap2;
6748: coo->Aperm2 = Aperm2;
6749: coo->Bimap2 = Bimap2;
6750: coo->Bjmap2 = Bjmap2;
6751: coo->Bperm2 = Bperm2;
6752: coo->Cperm1 = Cperm1;
6753: // Allocate in preallocation. If not used, it has zero cost on host
6754: if (!mat->structure_only) PetscCall(PetscMalloc2(coo->sendlen, &coo->sendbuf, coo->recvlen, &coo->recvbuf));
6755: else coo->sendbuf = coo->recvbuf = NULL;
6756: coo->Anonzerostate = mpiaij->A->nonzerostate;
6757: coo->Bnonzerostate = mpiaij->B->nonzerostate;
6758: PetscCall(PetscContainerCreate(PETSC_COMM_SELF, &container));
6759: PetscCall(PetscContainerSetPointer(container, coo));
6760: PetscCall(PetscContainerSetCtxDestroy(container, MatCOOStructDestroy_MPIAIJ));
6761: PetscCall(PetscObjectCompose((PetscObject)mat, "__PETSc_MatCOOStruct_Host", (PetscObject)container));
6762: PetscCall(PetscContainerDestroy(&container));
6763: PetscFunctionReturn(PETSC_SUCCESS);
6764: }
6766: // PetscClangLinter pragma disable: -fdoc-internal-linkage
6767: /*@
6768: MatMPIAIJCheckCOONonzeroState - Checks that the COO maps built by `MatSetPreallocationCOO()` can still be used by
6769: `MatSetValuesCOO()` on a `MATMPIAIJ` matrix
6771: Not Collective
6773: Input Parameter:
6774: . mat - the `MATMPIAIJ` matrix
6776: Level: developer
6778: Notes:
6779: The maps address the nonzeros of the diagonal and off-diagonal blocks by position, so they are only valid while the blocks keep
6780: the nonzero patterns built by `MatSetPreallocationCOO()`. Any change to them, for example a new nonzero inserted with
6781: `MatSetValues()`, would make `MatSetValuesCOO()` write values into the wrong locations, so this routine generates an error
6782: instead. It also generates an error when `MatSetPreallocationCOO()` has not been called.
6784: The check is local to each MPI process, so only the processes whose blocks changed generate the error.
6786: The `MatSetValuesCOO()` implementations of `MATMPIAIJ` and its device subtypes call this routine before using the maps.
6788: .seealso: [](ch_matrices), `Mat`, `MATMPIAIJ`, `MatSetPreallocationCOO()`, `MatSetValuesCOO()`, `MatSeqAIJCheckCOONonzeroState()`
6789: @*/
6790: PetscErrorCode MatMPIAIJCheckCOONonzeroState(Mat mat)
6791: {
6792: Mat_MPIAIJ *mpiaij = (Mat_MPIAIJ *)mat->data;
6793: PetscContainer container;
6794: MatCOOStruct_MPIAIJ *coo;
6796: PetscFunctionBegin;
6797: PetscCall(PetscObjectQuery((PetscObject)mat, "__PETSc_MatCOOStruct_Host", (PetscObject *)&container));
6798: PetscCheck(container, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "MatSetPreallocationCOO() must be called before MatSetValuesCOO()");
6799: PetscCall(PetscContainerGetPointer(container, &coo));
6800: 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()");
6801: PetscFunctionReturn(PETSC_SUCCESS);
6802: }
6804: static PetscErrorCode MatSetValuesCOO_MPIAIJ(Mat mat, const PetscScalar v[], InsertMode imode)
6805: {
6806: Mat_MPIAIJ *mpiaij = (Mat_MPIAIJ *)mat->data;
6807: Mat A = mpiaij->A, B = mpiaij->B;
6808: PetscScalar *Aa, *Ba;
6809: PetscScalar *sendbuf, *recvbuf;
6810: const PetscCount *Ajmap1, *Ajmap2, *Aimap2;
6811: const PetscCount *Bjmap1, *Bjmap2, *Bimap2;
6812: const PetscCount *Aperm1, *Aperm2, *Bperm1, *Bperm2;
6813: const PetscCount *Cperm1;
6814: PetscContainer container;
6815: MatCOOStruct_MPIAIJ *coo;
6817: PetscFunctionBegin;
6818: PetscCall(MatMPIAIJCheckCOONonzeroState(mat));
6819: PetscCall(PetscObjectQuery((PetscObject)mat, "__PETSc_MatCOOStruct_Host", (PetscObject *)&container));
6820: PetscCall(PetscContainerGetPointer(container, &coo));
6821: sendbuf = coo->sendbuf;
6822: recvbuf = coo->recvbuf;
6823: Ajmap1 = coo->Ajmap1;
6824: Ajmap2 = coo->Ajmap2;
6825: Aimap2 = coo->Aimap2;
6826: Bjmap1 = coo->Bjmap1;
6827: Bjmap2 = coo->Bjmap2;
6828: Bimap2 = coo->Bimap2;
6829: Aperm1 = coo->Aperm1;
6830: Aperm2 = coo->Aperm2;
6831: Bperm1 = coo->Bperm1;
6832: Bperm2 = coo->Bperm2;
6833: Cperm1 = coo->Cperm1;
6835: PetscCall(MatSeqAIJGetArray(A, &Aa)); /* Might read and write matrix values */
6836: PetscCall(MatSeqAIJGetArray(B, &Ba));
6838: /* Pack entries to be sent to remote */
6839: for (PetscCount i = 0; i < coo->sendlen; i++) sendbuf[i] = v[Cperm1[i]];
6841: /* Send remote entries to their owner and overlap the communication with local computation */
6842: PetscCall(PetscSFReduceWithMemTypeBegin(coo->sf, MPIU_SCALAR, PETSC_MEMTYPE_HOST, sendbuf, PETSC_MEMTYPE_HOST, recvbuf, MPI_REPLACE));
6843: /* Add local entries to A and B */
6844: for (PetscCount i = 0; i < coo->Annz; i++) { /* All nonzeros in A are either zero'ed or added with a value (i.e., initialized) */
6845: PetscScalar sum = 0.0; /* Do partial summation first to improve numerical stability */
6846: for (PetscCount k = Ajmap1[i]; k < Ajmap1[i + 1]; k++) sum += v[Aperm1[k]];
6847: Aa[i] = (imode == INSERT_VALUES ? 0.0 : Aa[i]) + sum;
6848: }
6849: for (PetscCount i = 0; i < coo->Bnnz; i++) {
6850: PetscScalar sum = 0.0;
6851: for (PetscCount k = Bjmap1[i]; k < Bjmap1[i + 1]; k++) sum += v[Bperm1[k]];
6852: Ba[i] = (imode == INSERT_VALUES ? 0.0 : Ba[i]) + sum;
6853: }
6854: PetscCall(PetscSFReduceEnd(coo->sf, MPIU_SCALAR, sendbuf, recvbuf, MPI_REPLACE));
6856: /* Add received remote entries to A and B */
6857: for (PetscCount i = 0; i < coo->Annz2; i++) {
6858: for (PetscCount k = Ajmap2[i]; k < Ajmap2[i + 1]; k++) Aa[Aimap2[i]] += recvbuf[Aperm2[k]];
6859: }
6860: for (PetscCount i = 0; i < coo->Bnnz2; i++) {
6861: for (PetscCount k = Bjmap2[i]; k < Bjmap2[i + 1]; k++) Ba[Bimap2[i]] += recvbuf[Bperm2[k]];
6862: }
6863: PetscCall(MatSeqAIJRestoreArray(A, &Aa));
6864: PetscCall(MatSeqAIJRestoreArray(B, &Ba));
6865: PetscFunctionReturn(PETSC_SUCCESS);
6866: }
6868: /*MC
6869: MATMPIAIJ - MATMPIAIJ = "mpiaij" - A matrix type to be used for parallel sparse matrices.
6871: Options Database Keys:
6872: . -mat_type mpiaij - sets the matrix type to `MATMPIAIJ` during a call to `MatSetFromOptions()`
6874: Level: beginner
6876: Notes:
6877: `MatSetValues()` may be called with a `NULL` argument for the numerical values to insert zeros at the supplied row and column indices.
6879: Call `MatSetOption(A, MAT_STRUCTURE_ONLY, PETSC_TRUE)` before preallocation or `MatSetUp()` to store only the nonzero pattern.
6880: The assembled matrix has no numerical value array. Row and column indices supplied during insertion are retained, while numerical values are ignored.
6881: Such matrices can be used for structural operations, but not for numerical operations.
6883: .seealso: [](ch_matrices), `Mat`, `MATSEQAIJ`, `MATAIJ`, `MatCreateAIJ()`
6884: M*/
6885: PETSC_EXTERN PetscErrorCode MatCreate_MPIAIJ(Mat B)
6886: {
6887: Mat_MPIAIJ *b;
6888: PetscMPIInt size;
6890: PetscFunctionBegin;
6891: PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)B), &size));
6893: PetscCall(PetscNew(&b));
6894: B->data = (void *)b;
6895: B->ops[0] = MatOps_Values;
6896: B->assembled = PETSC_FALSE;
6897: B->insertmode = NOT_SET_VALUES;
6898: b->size = size;
6900: PetscCallMPI(MPI_Comm_rank(PetscObjectComm((PetscObject)B), &b->rank));
6902: /* build cache for off array entries formed */
6903: PetscCall(MatStashCreate_Private(PetscObjectComm((PetscObject)B), 1, &B->stash));
6905: b->donotstash = PETSC_FALSE;
6906: b->colmap = NULL;
6907: b->garray = NULL;
6908: b->roworiented = PETSC_TRUE;
6910: /* stuff used for matrix vector multiply */
6911: b->lvec = NULL;
6912: b->Mvctx = NULL;
6914: /* stuff for MatGetRow() */
6915: b->rowindices = NULL;
6916: b->rowvalues = NULL;
6917: b->getrowactive = PETSC_FALSE;
6919: /* flexible pointer used in CUSPARSE classes */
6920: b->spptr = NULL;
6922: PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatMPIAIJSetUseScalableIncreaseOverlap_C", MatMPIAIJSetUseScalableIncreaseOverlap_MPIAIJ));
6923: PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatStoreValues_C", MatStoreValues_MPIAIJ));
6924: PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatRetrieveValues_C", MatRetrieveValues_MPIAIJ));
6925: PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatIsTranspose_C", MatIsTranspose_MPIAIJ));
6926: PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatMPIAIJSetPreallocation_C", MatMPIAIJSetPreallocation_MPIAIJ));
6927: PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatResetPreallocation_C", MatResetPreallocation_MPIAIJ));
6928: PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatResetHash_C", MatResetHash_MPIAIJ));
6929: PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatMPIAIJSetPreallocationCSR_C", MatMPIAIJSetPreallocationCSR_MPIAIJ));
6930: PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatDiagonalScaleLocal_C", MatDiagonalScaleLocal_MPIAIJ));
6931: PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatConvert_mpiaij_mpiaijperm_C", MatConvert_MPIAIJ_MPIAIJPERM));
6932: PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatConvert_mpiaij_mpiaijsell_C", MatConvert_MPIAIJ_MPIAIJSELL));
6933: #if PetscDefined(HAVE_CUDA)
6934: PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatConvert_mpiaij_mpiaijcusparse_C", MatConvert_MPIAIJ_MPIAIJCUSPARSE));
6935: #endif
6936: #if PetscDefined(HAVE_HIP)
6937: PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatConvert_mpiaij_mpiaijhipsparse_C", MatConvert_MPIAIJ_MPIAIJHIPSPARSE));
6938: #endif
6939: #if PetscDefined(HAVE_KOKKOS_KERNELS)
6940: PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatConvert_mpiaij_mpiaijkokkos_C", MatConvert_MPIAIJ_MPIAIJKokkos));
6941: #endif
6942: #if PetscDefined(HAVE_MKL_SPARSE)
6943: PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatConvert_mpiaij_mpiaijmkl_C", MatConvert_MPIAIJ_MPIAIJMKL));
6944: #endif
6945: PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatConvert_mpiaij_mpiaijcrl_C", MatConvert_MPIAIJ_MPIAIJCRL));
6946: PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatConvert_mpiaij_mpibaij_C", MatConvert_MPIAIJ_MPIBAIJ));
6947: PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatConvert_mpiaij_mpisbaij_C", MatConvert_MPIAIJ_MPISBAIJ));
6948: PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatConvert_mpiaij_mpidense_C", MatConvert_MPIAIJ_MPIDense));
6949: #if PetscDefined(HAVE_ELEMENTAL)
6950: PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatConvert_mpiaij_elemental_C", MatConvert_MPIAIJ_Elemental));
6951: #endif
6952: #if PetscDefined(HAVE_SCALAPACK) && (PetscDefined(USE_REAL_SINGLE) || PetscDefined(USE_REAL_DOUBLE))
6953: PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatConvert_mpiaij_scalapack_C", MatConvert_AIJ_ScaLAPACK));
6954: #endif
6955: PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatConvert_mpiaij_is_C", MatConvert_XAIJ_IS));
6956: PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatConvert_mpiaij_mpisell_C", MatConvert_MPIAIJ_MPISELL));
6957: #if PetscDefined(HAVE_HYPRE)
6958: PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatConvert_mpiaij_hypre_C", MatConvert_AIJ_HYPRE));
6959: PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatProductSetFromOptions_transpose_mpiaij_mpiaij_C", MatProductSetFromOptions_Transpose_AIJ_AIJ));
6960: #endif
6961: PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatProductSetFromOptions_is_mpiaij_C", MatProductSetFromOptions_IS_XAIJ));
6962: PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatProductSetFromOptions_mpiaij_mpiaij_C", MatProductSetFromOptions_MPIAIJ));
6963: PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatSetPreallocationCOO_C", MatSetPreallocationCOO_MPIAIJ));
6964: PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatSetValuesCOO_C", MatSetValuesCOO_MPIAIJ));
6965: PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatGetMultPetscSF_C", MatGetMultPetscSF_MPIAIJ));
6966: PetscCall(PetscObjectChangeTypeName((PetscObject)B, MATMPIAIJ));
6967: PetscFunctionReturn(PETSC_SUCCESS);
6968: }
6970: /*@
6971: MatCreateMPIAIJWithSplitArrays - creates a `MATMPIAIJ` matrix using arrays that contain the "diagonal"
6972: and "off-diagonal" part of the matrix in CSR format.
6974: Collective
6976: Input Parameters:
6977: + comm - MPI communicator
6978: . m - number of local rows (Cannot be `PETSC_DECIDE`)
6979: . n - This value should be the same as the local size used in creating the
6980: x vector for the matrix-vector product $y = Ax$. (or `PETSC_DECIDE` to have
6981: calculated if `N` is given) For square matrices `n` is almost always `m`.
6982: . M - number of global rows (or `PETSC_DETERMINE` to have calculated if `m` is given)
6983: . N - number of global columns (or `PETSC_DETERMINE` to have calculated if `n` is given)
6984: . 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
6985: . j - column indices, which must be local, i.e., based off the start column of the diagonal portion
6986: . a - matrix values
6987: . 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
6988: . oj - column indices, which must be global, representing global columns in the `MATMPIAIJ` matrix
6989: - oa - matrix values
6991: Output Parameter:
6992: . mat - the matrix
6994: Level: advanced
6996: Notes:
6997: The `i`, `j`, and `a` arrays ARE NOT copied by this routine into the internal format used by PETSc (even in Fortran). The user
6998: must free the arrays once the matrix has been destroyed and not before.
7000: The `i` and `j` indices are 0 based
7002: See `MatCreateAIJ()` for the definition of "diagonal" and "off-diagonal" portion of the matrix
7004: This sets local rows and cannot be used to set off-processor values.
7006: Use of this routine is discouraged because it is inflexible and cumbersome to use. It is extremely rare that a
7007: legacy application natively assembles into exactly this split format. The code to do so is nontrivial and does
7008: not easily support in-place reassembly. It is recommended to use MatSetValues() (or a variant thereof) because
7009: the resulting assembly is easier to implement, will work with any matrix format, and the user does not have to
7010: keep track of the underlying array. Use `MatSetOption`(A,`MAT_NO_OFF_PROC_ENTRIES`,`PETSC_TRUE`) to disable all
7011: communication if it is known that only local entries will be set.
7013: .seealso: [](ch_matrices), `Mat`, `MatCreate()`, `MatCreateSeqAIJ()`, `MatSetValues()`, `MatMPIAIJSetPreallocation()`, `MatMPIAIJSetPreallocationCSR()`,
7014: `MATMPIAIJ`, `MatCreateAIJ()`, `MatCreateMPIAIJWithArrays()`
7015: @*/
7016: 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)
7017: {
7018: Mat_MPIAIJ *maij;
7020: PetscFunctionBegin;
7021: PetscCheck(m >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "local number of rows (m) cannot be PETSC_DECIDE, or negative");
7022: PetscCheck(i[0] == 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "i (row indices) must start with 0");
7023: PetscCheck(oi[0] == 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "oi (row indices) must start with 0");
7024: PetscCall(MatCreate(comm, mat));
7025: PetscCall(MatSetSizes(*mat, m, n, M, N));
7026: PetscCall(MatSetType(*mat, MATMPIAIJ));
7027: maij = (Mat_MPIAIJ *)(*mat)->data;
7029: (*mat)->preallocated = PETSC_TRUE;
7031: PetscCall(PetscLayoutSetUp((*mat)->rmap));
7032: PetscCall(PetscLayoutSetUp((*mat)->cmap));
7034: PetscCall(MatCreateSeqAIJWithArrays(PETSC_COMM_SELF, m, n, i, j, a, &maij->A));
7035: PetscCall(MatCreateSeqAIJWithArrays(PETSC_COMM_SELF, m, (*mat)->cmap->N, oi, oj, oa, &maij->B));
7037: PetscCall(MatSetOption(*mat, MAT_NO_OFF_PROC_ENTRIES, PETSC_TRUE));
7038: PetscCall(MatAssemblyBegin(*mat, MAT_FINAL_ASSEMBLY));
7039: PetscCall(MatAssemblyEnd(*mat, MAT_FINAL_ASSEMBLY));
7040: PetscCall(MatSetOption(*mat, MAT_NO_OFF_PROC_ENTRIES, PETSC_FALSE));
7041: PetscCall(MatSetOption(*mat, MAT_NEW_NONZERO_LOCATION_ERR, PETSC_TRUE));
7042: PetscFunctionReturn(PETSC_SUCCESS);
7043: }
7045: typedef struct {
7046: Mat *mp; /* intermediate products */
7047: PetscBool *mptmp; /* is the intermediate product temporary ? */
7048: PetscInt cp; /* number of intermediate products */
7050: /* support for MatGetBrowsOfAoCols_MPIAIJ for P_oth */
7051: PetscInt *startsj_s, *startsj_r;
7052: PetscScalar *bufa;
7053: Mat P_oth;
7055: /* may take advantage of merging product->B */
7056: Mat Bloc; /* B-local by merging diag and off-diag */
7058: /* cusparse does not have support to split between symbolic and numeric phases.
7059: When api_user is true, we don't need to update the numerical values
7060: of the temporary storage */
7061: PetscBool reusesym;
7063: /* support for COO values insertion */
7064: PetscScalar *coo_v, *coo_w; /* store on-process and off-process COO scalars, and used as MPI recv/send buffers respectively */
7065: PetscInt **own; /* own[i] points to address of on-process COO indices for Mat mp[i] */
7066: PetscInt **off; /* off[i] points to address of off-process COO indices for Mat mp[i] */
7067: PetscBool hasoffproc; /* if true, have off-process values insertion (i.e. AtB or PtAP) */
7068: PetscSF sf; /* used for non-local values insertion and memory malloc */
7069: PetscMemType mtype;
7071: /* customization */
7072: PetscBool abmerge;
7073: PetscBool P_oth_bind;
7074: } MatMatMPIAIJBACKEND;
7076: static PetscErrorCode MatProductCtxDestroy_MatMatMPIAIJBACKEND(PetscCtxRt data)
7077: {
7078: MatMatMPIAIJBACKEND *mmdata = *(MatMatMPIAIJBACKEND **)data;
7079: PetscInt i;
7081: PetscFunctionBegin;
7082: PetscCall(PetscFree2(mmdata->startsj_s, mmdata->startsj_r));
7083: PetscCall(PetscFree(mmdata->bufa));
7084: PetscCall(PetscSFFree(mmdata->sf, mmdata->mtype, mmdata->coo_v));
7085: PetscCall(PetscSFFree(mmdata->sf, mmdata->mtype, mmdata->coo_w));
7086: PetscCall(MatDestroy(&mmdata->P_oth));
7087: PetscCall(MatDestroy(&mmdata->Bloc));
7088: PetscCall(PetscSFDestroy(&mmdata->sf));
7089: for (i = 0; i < mmdata->cp; i++) PetscCall(MatDestroy(&mmdata->mp[i]));
7090: PetscCall(PetscFree2(mmdata->mp, mmdata->mptmp));
7091: PetscCall(PetscFree(mmdata->own[0]));
7092: PetscCall(PetscFree(mmdata->own));
7093: PetscCall(PetscFree(mmdata->off[0]));
7094: PetscCall(PetscFree(mmdata->off));
7095: PetscCall(PetscFree(mmdata));
7096: PetscFunctionReturn(PETSC_SUCCESS);
7097: }
7099: /* Copy selected n entries with indices in idx[] of A to v[].
7100: If idx is NULL, copy the whole data array of A to v[]
7101: */
7102: static PetscErrorCode MatSeqAIJCopySubArray(Mat A, PetscInt n, const PetscInt idx[], PetscScalar v[])
7103: {
7104: PetscErrorCode (*f)(Mat, PetscInt, const PetscInt[], PetscScalar[]);
7106: PetscFunctionBegin;
7107: PetscCall(PetscObjectQueryFunction((PetscObject)A, "MatSeqAIJCopySubArray_C", &f));
7108: if (f) PetscCall((*f)(A, n, idx, v));
7109: else {
7110: const PetscScalar *vv;
7112: PetscCall(MatSeqAIJGetArrayRead(A, &vv));
7113: if (n && idx) {
7114: PetscScalar *w = v;
7115: const PetscInt *oi = idx;
7117: for (PetscInt j = 0; j < n; j++) *w++ = vv[*oi++];
7118: } else {
7119: PetscCall(PetscArraycpy(v, vv, n));
7120: }
7121: PetscCall(MatSeqAIJRestoreArrayRead(A, &vv));
7122: }
7123: PetscFunctionReturn(PETSC_SUCCESS);
7124: }
7126: static PetscErrorCode MatProductNumeric_MPIAIJBACKEND(Mat C)
7127: {
7128: MatMatMPIAIJBACKEND *mmdata;
7129: PetscInt i, n_d, n_o;
7131: PetscFunctionBegin;
7132: MatCheckProduct(C, 1);
7133: PetscCheck(C->product->data, PetscObjectComm((PetscObject)C), PETSC_ERR_PLIB, "Product data empty");
7134: mmdata = (MatMatMPIAIJBACKEND *)C->product->data;
7135: if (!mmdata->reusesym) { /* update temporary matrices */
7136: 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));
7137: if (mmdata->Bloc) PetscCall(MatMPIAIJGetLocalMatMerge(C->product->B, MAT_REUSE_MATRIX, NULL, &mmdata->Bloc));
7138: }
7139: mmdata->reusesym = PETSC_FALSE;
7141: for (i = 0; i < mmdata->cp; i++) {
7142: 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]);
7143: PetscCall((*mmdata->mp[i]->ops->productnumeric)(mmdata->mp[i]));
7144: }
7145: for (i = 0, n_d = 0, n_o = 0; i < mmdata->cp; i++) {
7146: PetscInt noff;
7148: PetscCall(PetscIntCast(mmdata->off[i + 1] - mmdata->off[i], &noff));
7149: if (mmdata->mptmp[i]) continue;
7150: if (noff) {
7151: PetscInt nown;
7153: PetscCall(PetscIntCast(mmdata->own[i + 1] - mmdata->own[i], &nown));
7154: PetscCall(MatSeqAIJCopySubArray(mmdata->mp[i], noff, mmdata->off[i], mmdata->coo_w + n_o));
7155: PetscCall(MatSeqAIJCopySubArray(mmdata->mp[i], nown, mmdata->own[i], mmdata->coo_v + n_d));
7156: n_o += noff;
7157: n_d += nown;
7158: } else {
7159: Mat_SeqAIJ *mm = (Mat_SeqAIJ *)mmdata->mp[i]->data;
7161: PetscCall(MatSeqAIJCopySubArray(mmdata->mp[i], mm->nz, NULL, mmdata->coo_v + n_d));
7162: n_d += mm->nz;
7163: }
7164: }
7165: if (mmdata->hasoffproc) { /* offprocess insertion */
7166: PetscCall(PetscSFGatherBegin(mmdata->sf, MPIU_SCALAR, mmdata->coo_w, mmdata->coo_v + n_d));
7167: PetscCall(PetscSFGatherEnd(mmdata->sf, MPIU_SCALAR, mmdata->coo_w, mmdata->coo_v + n_d));
7168: }
7169: PetscCall(MatSetValuesCOO(C, mmdata->coo_v, INSERT_VALUES));
7170: PetscFunctionReturn(PETSC_SUCCESS);
7171: }
7173: /* Support for Pt * A, A * P, or Pt * A * P */
7174: #define MAX_NUMBER_INTERMEDIATE 4
7175: PetscErrorCode MatProductSymbolic_MPIAIJBACKEND(Mat C)
7176: {
7177: Mat_Product *product = C->product;
7178: Mat A, P, mp[MAX_NUMBER_INTERMEDIATE]; /* A, P and a series of intermediate matrices */
7179: Mat_MPIAIJ *a, *p;
7180: MatMatMPIAIJBACKEND *mmdata;
7181: ISLocalToGlobalMapping P_oth_l2g = NULL;
7182: IS glob = NULL;
7183: const char *prefix;
7184: char pprefix[256];
7185: const PetscInt *globidx, *P_oth_idx;
7186: PetscInt i, j, cp, m, n, M, N, *coo_i, *coo_j;
7187: PetscCount ncoo, ncoo_d, ncoo_o, ncoo_oown;
7188: PetscInt cmapt[MAX_NUMBER_INTERMEDIATE], rmapt[MAX_NUMBER_INTERMEDIATE]; /* col/row map type for each Mat in mp[]. */
7189: /* type-0: consecutive, start from 0; type-1: consecutive with */
7190: /* a base offset; type-2: sparse with a local to global map table */
7191: const PetscInt *cmapa[MAX_NUMBER_INTERMEDIATE], *rmapa[MAX_NUMBER_INTERMEDIATE]; /* col/row local to global map array (table) for type-2 map type */
7193: MatProductType ptype;
7194: PetscBool mptmp[MAX_NUMBER_INTERMEDIATE], hasoffproc = PETSC_FALSE, iscuda, iship, iskokk;
7195: PetscMPIInt size;
7197: PetscFunctionBegin;
7198: MatCheckProduct(C, 1);
7199: PetscCheck(!product->data, PetscObjectComm((PetscObject)C), PETSC_ERR_PLIB, "Product data not empty");
7200: ptype = product->type;
7201: if (product->A->symmetric == PETSC_BOOL3_TRUE && ptype == MATPRODUCT_AtB) {
7202: ptype = MATPRODUCT_AB;
7203: product->symbolic_used_the_fact_A_is_symmetric = PETSC_TRUE;
7204: }
7205: switch (ptype) {
7206: case MATPRODUCT_AB:
7207: A = product->A;
7208: P = product->B;
7209: m = A->rmap->n;
7210: n = P->cmap->n;
7211: M = A->rmap->N;
7212: N = P->cmap->N;
7213: hasoffproc = PETSC_FALSE; /* will not scatter mat product values to other processes */
7214: break;
7215: case MATPRODUCT_AtB:
7216: P = product->A;
7217: A = product->B;
7218: m = P->cmap->n;
7219: n = A->cmap->n;
7220: M = P->cmap->N;
7221: N = A->cmap->N;
7222: hasoffproc = PETSC_TRUE;
7223: break;
7224: case MATPRODUCT_PtAP:
7225: A = product->A;
7226: P = product->B;
7227: m = P->cmap->n;
7228: n = P->cmap->n;
7229: M = P->cmap->N;
7230: N = P->cmap->N;
7231: hasoffproc = PETSC_TRUE;
7232: break;
7233: default:
7234: SETERRQ(PetscObjectComm((PetscObject)C), PETSC_ERR_PLIB, "Not for product type %s", MatProductTypes[ptype]);
7235: }
7236: PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)C), &size));
7237: if (size == 1) hasoffproc = PETSC_FALSE;
7239: /* defaults */
7240: for (i = 0; i < MAX_NUMBER_INTERMEDIATE; i++) {
7241: mp[i] = NULL;
7242: mptmp[i] = PETSC_FALSE;
7243: rmapt[i] = -1;
7244: cmapt[i] = -1;
7245: rmapa[i] = NULL;
7246: cmapa[i] = NULL;
7247: }
7249: /* customization */
7250: PetscCall(PetscNew(&mmdata));
7251: mmdata->reusesym = product->api_user;
7252: if (ptype == MATPRODUCT_AB) {
7253: if (product->api_user) {
7254: PetscOptionsBegin(PetscObjectComm((PetscObject)C), ((PetscObject)C)->prefix, "MatMatMult", "Mat");
7255: PetscCall(PetscOptionsBool("-matmatmult_backend_mergeB", "Merge product->B local matrices", "MatMatMult", mmdata->abmerge, &mmdata->abmerge, NULL));
7256: PetscCall(PetscOptionsBool("-matmatmult_backend_pothbind", "Bind P_oth to CPU", "MatBindToCPU", mmdata->P_oth_bind, &mmdata->P_oth_bind, NULL));
7257: PetscOptionsEnd();
7258: } else {
7259: PetscOptionsBegin(PetscObjectComm((PetscObject)C), ((PetscObject)C)->prefix, "MatProduct_AB", "Mat");
7260: PetscCall(PetscOptionsBool("-mat_product_algorithm_backend_mergeB", "Merge product->B local matrices", "MatMatMult", mmdata->abmerge, &mmdata->abmerge, NULL));
7261: PetscCall(PetscOptionsBool("-mat_product_algorithm_backend_pothbind", "Bind P_oth to CPU", "MatBindToCPU", mmdata->P_oth_bind, &mmdata->P_oth_bind, NULL));
7262: PetscOptionsEnd();
7263: }
7264: } else if (ptype == MATPRODUCT_PtAP) {
7265: if (product->api_user) {
7266: PetscOptionsBegin(PetscObjectComm((PetscObject)C), ((PetscObject)C)->prefix, "MatPtAP", "Mat");
7267: PetscCall(PetscOptionsBool("-matptap_backend_pothbind", "Bind P_oth to CPU", "MatBindToCPU", mmdata->P_oth_bind, &mmdata->P_oth_bind, NULL));
7268: PetscOptionsEnd();
7269: } else {
7270: PetscOptionsBegin(PetscObjectComm((PetscObject)C), ((PetscObject)C)->prefix, "MatProduct_PtAP", "Mat");
7271: PetscCall(PetscOptionsBool("-mat_product_algorithm_backend_pothbind", "Bind P_oth to CPU", "MatBindToCPU", mmdata->P_oth_bind, &mmdata->P_oth_bind, NULL));
7272: PetscOptionsEnd();
7273: }
7274: }
7275: a = (Mat_MPIAIJ *)A->data;
7276: p = (Mat_MPIAIJ *)P->data;
7277: PetscCall(MatSetSizes(C, m, n, M, N));
7278: PetscCall(PetscLayoutSetUp(C->rmap));
7279: PetscCall(PetscLayoutSetUp(C->cmap));
7280: PetscCall(MatSetType(C, ((PetscObject)A)->type_name));
7281: PetscCall(MatGetOptionsPrefix(C, &prefix));
7283: cp = 0;
7284: switch (ptype) {
7285: case MATPRODUCT_AB: /* A * P */
7286: PetscCall(MatGetBrowsOfAoCols_MPIAIJ(A, P, MAT_INITIAL_MATRIX, &mmdata->startsj_s, &mmdata->startsj_r, &mmdata->bufa, &mmdata->P_oth));
7288: /* A_diag * P_local (merged or not) */
7289: if (mmdata->abmerge) { /* P's diagonal and off-diag blocks are merged to one matrix, then multiplied by A_diag */
7290: /* P is product->B */
7291: PetscCall(MatMPIAIJGetLocalMatMerge(P, MAT_INITIAL_MATRIX, &glob, &mmdata->Bloc));
7292: PetscCall(MatProductCreate(a->A, mmdata->Bloc, NULL, &mp[cp]));
7293: PetscCall(MatProductSetType(mp[cp], MATPRODUCT_AB));
7294: PetscCall(MatProductSetFill(mp[cp], product->fill));
7295: PetscCall(PetscSNPrintf(pprefix, sizeof(pprefix), "backend_p%" PetscInt_FMT "_", cp));
7296: PetscCall(MatSetOptionsPrefix(mp[cp], prefix));
7297: PetscCall(MatAppendOptionsPrefix(mp[cp], pprefix));
7298: mp[cp]->product->api_user = product->api_user;
7299: PetscCall(MatProductSetFromOptions(mp[cp]));
7300: PetscCall((*mp[cp]->ops->productsymbolic)(mp[cp]));
7301: PetscCall(ISGetIndices(glob, &globidx));
7302: rmapt[cp] = 1;
7303: cmapt[cp] = 2;
7304: cmapa[cp] = globidx;
7305: mptmp[cp] = PETSC_FALSE;
7306: cp++;
7307: } else { /* A_diag * P_diag and A_diag * P_off */
7308: PetscCall(MatProductCreate(a->A, p->A, NULL, &mp[cp]));
7309: PetscCall(MatProductSetType(mp[cp], MATPRODUCT_AB));
7310: PetscCall(MatProductSetFill(mp[cp], product->fill));
7311: PetscCall(PetscSNPrintf(pprefix, sizeof(pprefix), "backend_p%" PetscInt_FMT "_", cp));
7312: PetscCall(MatSetOptionsPrefix(mp[cp], prefix));
7313: PetscCall(MatAppendOptionsPrefix(mp[cp], pprefix));
7314: mp[cp]->product->api_user = product->api_user;
7315: PetscCall(MatProductSetFromOptions(mp[cp]));
7316: PetscCall((*mp[cp]->ops->productsymbolic)(mp[cp]));
7317: rmapt[cp] = 1;
7318: cmapt[cp] = 1;
7319: mptmp[cp] = PETSC_FALSE;
7320: cp++;
7321: PetscCall(MatProductCreate(a->A, p->B, NULL, &mp[cp]));
7322: PetscCall(MatProductSetType(mp[cp], MATPRODUCT_AB));
7323: PetscCall(MatProductSetFill(mp[cp], product->fill));
7324: PetscCall(PetscSNPrintf(pprefix, sizeof(pprefix), "backend_p%" PetscInt_FMT "_", cp));
7325: PetscCall(MatSetOptionsPrefix(mp[cp], prefix));
7326: PetscCall(MatAppendOptionsPrefix(mp[cp], pprefix));
7327: mp[cp]->product->api_user = product->api_user;
7328: PetscCall(MatProductSetFromOptions(mp[cp]));
7329: PetscCall((*mp[cp]->ops->productsymbolic)(mp[cp]));
7330: rmapt[cp] = 1;
7331: cmapt[cp] = 2;
7332: cmapa[cp] = p->garray;
7333: mptmp[cp] = PETSC_FALSE;
7334: cp++;
7335: }
7337: /* A_off * P_other */
7338: if (mmdata->P_oth) {
7339: PetscCall(MatSeqAIJCompactOutExtraColumns_SeqAIJ(mmdata->P_oth, &P_oth_l2g)); /* make P_oth use local col ids */
7340: PetscCall(ISLocalToGlobalMappingGetIndices(P_oth_l2g, &P_oth_idx));
7341: PetscCall(MatSetType(mmdata->P_oth, ((PetscObject)a->B)->type_name));
7342: PetscCall(MatBindToCPU(mmdata->P_oth, mmdata->P_oth_bind));
7343: PetscCall(MatProductCreate(a->B, mmdata->P_oth, NULL, &mp[cp]));
7344: PetscCall(MatProductSetType(mp[cp], MATPRODUCT_AB));
7345: PetscCall(MatProductSetFill(mp[cp], product->fill));
7346: PetscCall(PetscSNPrintf(pprefix, sizeof(pprefix), "backend_p%" PetscInt_FMT "_", cp));
7347: PetscCall(MatSetOptionsPrefix(mp[cp], prefix));
7348: PetscCall(MatAppendOptionsPrefix(mp[cp], pprefix));
7349: mp[cp]->product->api_user = product->api_user;
7350: PetscCall(MatProductSetFromOptions(mp[cp]));
7351: PetscCall((*mp[cp]->ops->productsymbolic)(mp[cp]));
7352: rmapt[cp] = 1;
7353: cmapt[cp] = 2;
7354: cmapa[cp] = P_oth_idx;
7355: mptmp[cp] = PETSC_FALSE;
7356: cp++;
7357: }
7358: break;
7360: case MATPRODUCT_AtB: /* (P^t * A): P_diag * A_loc + P_off * A_loc */
7361: /* A is product->B */
7362: PetscCall(MatMPIAIJGetLocalMatMerge(A, MAT_INITIAL_MATRIX, &glob, &mmdata->Bloc));
7363: if (A == P) { /* when A==P, we can take advantage of the already merged mmdata->Bloc */
7364: PetscCall(MatProductCreate(mmdata->Bloc, mmdata->Bloc, NULL, &mp[cp]));
7365: PetscCall(MatProductSetType(mp[cp], MATPRODUCT_AtB));
7366: PetscCall(MatProductSetFill(mp[cp], product->fill));
7367: PetscCall(PetscSNPrintf(pprefix, sizeof(pprefix), "backend_p%" PetscInt_FMT "_", cp));
7368: PetscCall(MatSetOptionsPrefix(mp[cp], prefix));
7369: PetscCall(MatAppendOptionsPrefix(mp[cp], pprefix));
7370: mp[cp]->product->api_user = product->api_user;
7371: PetscCall(MatProductSetFromOptions(mp[cp]));
7372: PetscCall((*mp[cp]->ops->productsymbolic)(mp[cp]));
7373: PetscCall(ISGetIndices(glob, &globidx));
7374: rmapt[cp] = 2;
7375: rmapa[cp] = globidx;
7376: cmapt[cp] = 2;
7377: cmapa[cp] = globidx;
7378: mptmp[cp] = PETSC_FALSE;
7379: cp++;
7380: } else {
7381: PetscCall(MatProductCreate(p->A, mmdata->Bloc, NULL, &mp[cp]));
7382: PetscCall(MatProductSetType(mp[cp], MATPRODUCT_AtB));
7383: PetscCall(MatProductSetFill(mp[cp], product->fill));
7384: PetscCall(PetscSNPrintf(pprefix, sizeof(pprefix), "backend_p%" PetscInt_FMT "_", cp));
7385: PetscCall(MatSetOptionsPrefix(mp[cp], prefix));
7386: PetscCall(MatAppendOptionsPrefix(mp[cp], pprefix));
7387: mp[cp]->product->api_user = product->api_user;
7388: PetscCall(MatProductSetFromOptions(mp[cp]));
7389: PetscCall((*mp[cp]->ops->productsymbolic)(mp[cp]));
7390: PetscCall(ISGetIndices(glob, &globidx));
7391: rmapt[cp] = 1;
7392: cmapt[cp] = 2;
7393: cmapa[cp] = globidx;
7394: mptmp[cp] = PETSC_FALSE;
7395: cp++;
7396: PetscCall(MatProductCreate(p->B, 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: rmapt[cp] = 2;
7406: rmapa[cp] = p->garray;
7407: cmapt[cp] = 2;
7408: cmapa[cp] = globidx;
7409: mptmp[cp] = PETSC_FALSE;
7410: cp++;
7411: }
7412: break;
7413: case MATPRODUCT_PtAP:
7414: PetscCall(MatGetBrowsOfAoCols_MPIAIJ(A, P, MAT_INITIAL_MATRIX, &mmdata->startsj_s, &mmdata->startsj_r, &mmdata->bufa, &mmdata->P_oth));
7415: /* P is product->B */
7416: PetscCall(MatMPIAIJGetLocalMatMerge(P, MAT_INITIAL_MATRIX, &glob, &mmdata->Bloc));
7417: PetscCall(MatProductCreate(a->A, mmdata->Bloc, NULL, &mp[cp]));
7418: PetscCall(MatProductSetType(mp[cp], MATPRODUCT_PtAP));
7419: PetscCall(MatProductSetFill(mp[cp], product->fill));
7420: PetscCall(PetscSNPrintf(pprefix, sizeof(pprefix), "backend_p%" PetscInt_FMT "_", cp));
7421: PetscCall(MatSetOptionsPrefix(mp[cp], prefix));
7422: PetscCall(MatAppendOptionsPrefix(mp[cp], pprefix));
7423: mp[cp]->product->api_user = product->api_user;
7424: PetscCall(MatProductSetFromOptions(mp[cp]));
7425: PetscCall((*mp[cp]->ops->productsymbolic)(mp[cp]));
7426: PetscCall(ISGetIndices(glob, &globidx));
7427: rmapt[cp] = 2;
7428: rmapa[cp] = globidx;
7429: cmapt[cp] = 2;
7430: cmapa[cp] = globidx;
7431: mptmp[cp] = PETSC_FALSE;
7432: cp++;
7433: if (mmdata->P_oth) {
7434: PetscCall(MatSeqAIJCompactOutExtraColumns_SeqAIJ(mmdata->P_oth, &P_oth_l2g));
7435: PetscCall(ISLocalToGlobalMappingGetIndices(P_oth_l2g, &P_oth_idx));
7436: PetscCall(MatSetType(mmdata->P_oth, ((PetscObject)a->B)->type_name));
7437: PetscCall(MatBindToCPU(mmdata->P_oth, mmdata->P_oth_bind));
7438: PetscCall(MatProductCreate(a->B, mmdata->P_oth, NULL, &mp[cp]));
7439: PetscCall(MatProductSetType(mp[cp], MATPRODUCT_AB));
7440: PetscCall(MatProductSetFill(mp[cp], product->fill));
7441: PetscCall(PetscSNPrintf(pprefix, sizeof(pprefix), "backend_p%" PetscInt_FMT "_", cp));
7442: PetscCall(MatSetOptionsPrefix(mp[cp], prefix));
7443: PetscCall(MatAppendOptionsPrefix(mp[cp], pprefix));
7444: mp[cp]->product->api_user = product->api_user;
7445: PetscCall(MatProductSetFromOptions(mp[cp]));
7446: PetscCall((*mp[cp]->ops->productsymbolic)(mp[cp]));
7447: mptmp[cp] = PETSC_TRUE;
7448: cp++;
7449: PetscCall(MatProductCreate(mmdata->Bloc, mp[1], NULL, &mp[cp]));
7450: PetscCall(MatProductSetType(mp[cp], MATPRODUCT_AtB));
7451: PetscCall(MatProductSetFill(mp[cp], product->fill));
7452: PetscCall(PetscSNPrintf(pprefix, sizeof(pprefix), "backend_p%" PetscInt_FMT "_", cp));
7453: PetscCall(MatSetOptionsPrefix(mp[cp], prefix));
7454: PetscCall(MatAppendOptionsPrefix(mp[cp], pprefix));
7455: mp[cp]->product->api_user = product->api_user;
7456: PetscCall(MatProductSetFromOptions(mp[cp]));
7457: PetscCall((*mp[cp]->ops->productsymbolic)(mp[cp]));
7458: rmapt[cp] = 2;
7459: rmapa[cp] = globidx;
7460: cmapt[cp] = 2;
7461: cmapa[cp] = P_oth_idx;
7462: mptmp[cp] = PETSC_FALSE;
7463: cp++;
7464: }
7465: break;
7466: default:
7467: SETERRQ(PetscObjectComm((PetscObject)C), PETSC_ERR_PLIB, "Not for product type %s", MatProductTypes[ptype]);
7468: }
7469: /* sanity check */
7470: if (size > 1)
7471: 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);
7473: PetscCall(PetscMalloc2(cp, &mmdata->mp, cp, &mmdata->mptmp));
7474: for (i = 0; i < cp; i++) {
7475: mmdata->mp[i] = mp[i];
7476: mmdata->mptmp[i] = mptmp[i];
7477: }
7478: mmdata->cp = cp;
7479: C->product->data = mmdata;
7480: C->product->destroy = MatProductCtxDestroy_MatMatMPIAIJBACKEND;
7481: C->ops->productnumeric = MatProductNumeric_MPIAIJBACKEND;
7483: /* memory type */
7484: mmdata->mtype = PETSC_MEMTYPE_HOST;
7485: PetscCall(PetscObjectTypeCompareAny((PetscObject)C, &iscuda, MATSEQAIJCUSPARSE, MATMPIAIJCUSPARSE, ""));
7486: PetscCall(PetscObjectTypeCompareAny((PetscObject)C, &iship, MATSEQAIJHIPSPARSE, MATMPIAIJHIPSPARSE, ""));
7487: PetscCall(PetscObjectTypeCompareAny((PetscObject)C, &iskokk, MATSEQAIJKOKKOS, MATMPIAIJKOKKOS, ""));
7488: if (iscuda) mmdata->mtype = PETSC_MEMTYPE_CUDA;
7489: else if (iship) mmdata->mtype = PETSC_MEMTYPE_HIP;
7490: else if (iskokk) mmdata->mtype = PETSC_MEMTYPE_KOKKOS;
7492: /* prepare coo coordinates for values insertion */
7494: /* count total nonzeros of those intermediate seqaij Mats
7495: ncoo_d: # of nonzeros of matrices that do not have offproc entries
7496: ncoo_o: # of nonzeros (of matrices that might have offproc entries) that will be inserted to remote procs
7497: ncoo_oown: # of nonzeros (of matrices that might have offproc entries) that will be inserted locally
7498: */
7499: for (cp = 0, ncoo_d = 0, ncoo_o = 0, ncoo_oown = 0; cp < mmdata->cp; cp++) {
7500: Mat_SeqAIJ *mm = (Mat_SeqAIJ *)mp[cp]->data;
7501: if (mptmp[cp]) continue;
7502: if (rmapt[cp] == 2 && hasoffproc) { /* the rows need to be scatter to all processes (might include self) */
7503: const PetscInt *rmap = rmapa[cp];
7504: const PetscInt mr = mp[cp]->rmap->n;
7505: const PetscInt rs = C->rmap->rstart;
7506: const PetscInt re = C->rmap->rend;
7507: const PetscInt *ii = mm->i;
7508: for (i = 0; i < mr; i++) {
7509: const PetscInt gr = rmap[i];
7510: const PetscInt nz = ii[i + 1] - ii[i];
7511: if (gr < rs || gr >= re) ncoo_o += nz; /* this row is offproc */
7512: else ncoo_oown += nz; /* this row is local */
7513: }
7514: } else ncoo_d += mm->nz;
7515: }
7517: /*
7518: ncoo: total number of nonzeros (including those inserted by remote procs) belonging to this proc
7520: ncoo = ncoo_d + ncoo_oown + ncoo2, which ncoo2 is number of nonzeros inserted to me by other procs.
7522: off[0] points to a big index array, which is shared by off[1,2,...]. Similarly, for own[0].
7524: off[p]: points to the segment for matrix mp[p], storing location of nonzeros that mp[p] will insert to others
7525: own[p]: points to the segment for matrix mp[p], storing location of nonzeros that mp[p] will insert locally
7526: so, off[p+1]-off[p] is the number of nonzeros that mp[p] will send to others.
7528: coo_i/j/v[]: [ncoo] row/col/val of nonzeros belonging to this proc.
7529: 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.
7530: */
7531: PetscCall(PetscCalloc1(mmdata->cp + 1, &mmdata->off)); /* +1 to make a csr-like data structure */
7532: PetscCall(PetscCalloc1(mmdata->cp + 1, &mmdata->own));
7534: /* gather (i,j) of nonzeros inserted by remote procs */
7535: if (hasoffproc) {
7536: PetscSF msf;
7537: PetscInt ncoo2, *coo_i2, *coo_j2;
7539: PetscCall(PetscMalloc1(ncoo_o, &mmdata->off[0]));
7540: PetscCall(PetscMalloc1(ncoo_oown, &mmdata->own[0]));
7541: PetscCall(PetscMalloc2(ncoo_o, &coo_i, ncoo_o, &coo_j)); /* to collect (i,j) of entries to be sent to others */
7543: for (cp = 0, ncoo_o = 0; cp < mmdata->cp; cp++) {
7544: Mat_SeqAIJ *mm = (Mat_SeqAIJ *)mp[cp]->data;
7545: PetscInt *idxoff = mmdata->off[cp];
7546: PetscInt *idxown = mmdata->own[cp];
7547: if (!mptmp[cp] && rmapt[cp] == 2) { /* row map is sparse */
7548: const PetscInt *rmap = rmapa[cp];
7549: const PetscInt *cmap = cmapa[cp];
7550: const PetscInt *ii = mm->i;
7551: PetscInt *coi = coo_i + ncoo_o;
7552: PetscInt *coj = coo_j + ncoo_o;
7553: const PetscInt mr = mp[cp]->rmap->n;
7554: const PetscInt rs = C->rmap->rstart;
7555: const PetscInt re = C->rmap->rend;
7556: const PetscInt cs = C->cmap->rstart;
7557: for (i = 0; i < mr; i++) {
7558: const PetscInt *jj = mm->j + ii[i];
7559: const PetscInt gr = rmap[i];
7560: const PetscInt nz = ii[i + 1] - ii[i];
7561: if (gr < rs || gr >= re) { /* this is an offproc row */
7562: for (j = ii[i]; j < ii[i + 1]; j++) {
7563: *coi++ = gr;
7564: *idxoff++ = j;
7565: }
7566: if (!cmapt[cp]) { /* already global */
7567: for (j = 0; j < nz; j++) *coj++ = jj[j];
7568: } else if (cmapt[cp] == 1) { /* local to global for owned columns of C */
7569: for (j = 0; j < nz; j++) *coj++ = jj[j] + cs;
7570: } else { /* offdiag */
7571: for (j = 0; j < nz; j++) *coj++ = cmap[jj[j]];
7572: }
7573: ncoo_o += nz;
7574: } else { /* this is a local row */
7575: for (j = ii[i]; j < ii[i + 1]; j++) *idxown++ = j;
7576: }
7577: }
7578: }
7579: mmdata->off[cp + 1] = idxoff;
7580: mmdata->own[cp + 1] = idxown;
7581: }
7583: PetscCall(PetscSFCreate(PetscObjectComm((PetscObject)C), &mmdata->sf));
7584: PetscInt incoo_o;
7585: PetscCall(PetscIntCast(ncoo_o, &incoo_o));
7586: PetscCall(PetscSFSetGraphLayout(mmdata->sf, C->rmap, incoo_o /*nleaves*/, NULL /*ilocal*/, PETSC_OWN_POINTER, coo_i));
7587: PetscCall(PetscSFGetMultiSF(mmdata->sf, &msf));
7588: PetscCall(PetscSFGetGraph(msf, &ncoo2 /*nroots*/, NULL, NULL, NULL));
7589: ncoo = ncoo_d + ncoo_oown + ncoo2;
7590: PetscCall(PetscMalloc2(ncoo, &coo_i2, ncoo, &coo_j2));
7591: PetscCall(PetscSFGatherBegin(mmdata->sf, MPIU_INT, coo_i, coo_i2 + ncoo_d + ncoo_oown)); /* put (i,j) of remote nonzeros at back */
7592: PetscCall(PetscSFGatherEnd(mmdata->sf, MPIU_INT, coo_i, coo_i2 + ncoo_d + ncoo_oown));
7593: PetscCall(PetscSFGatherBegin(mmdata->sf, MPIU_INT, coo_j, coo_j2 + ncoo_d + ncoo_oown));
7594: PetscCall(PetscSFGatherEnd(mmdata->sf, MPIU_INT, coo_j, coo_j2 + ncoo_d + ncoo_oown));
7595: PetscCall(PetscFree2(coo_i, coo_j));
7596: /* allocate MPI send buffer to collect nonzero values to be sent to remote procs */
7597: PetscCall(PetscSFMalloc(mmdata->sf, mmdata->mtype, ncoo_o * sizeof(PetscScalar), (void **)&mmdata->coo_w));
7598: coo_i = coo_i2;
7599: coo_j = coo_j2;
7600: } else { /* no offproc values insertion */
7601: ncoo = ncoo_d;
7602: PetscCall(PetscMalloc2(ncoo, &coo_i, ncoo, &coo_j));
7604: PetscCall(PetscSFCreate(PetscObjectComm((PetscObject)C), &mmdata->sf));
7605: PetscCall(PetscSFSetGraph(mmdata->sf, 0, 0, NULL, PETSC_OWN_POINTER, NULL, PETSC_OWN_POINTER));
7606: PetscCall(PetscSFSetUp(mmdata->sf));
7607: }
7608: mmdata->hasoffproc = hasoffproc;
7610: /* gather (i,j) of nonzeros inserted locally */
7611: for (cp = 0, ncoo_d = 0; cp < mmdata->cp; cp++) {
7612: Mat_SeqAIJ *mm = (Mat_SeqAIJ *)mp[cp]->data;
7613: PetscInt *coi = coo_i + ncoo_d;
7614: PetscInt *coj = coo_j + ncoo_d;
7615: const PetscInt *jj = mm->j;
7616: const PetscInt *ii = mm->i;
7617: const PetscInt *cmap = cmapa[cp];
7618: const PetscInt *rmap = rmapa[cp];
7619: const PetscInt mr = mp[cp]->rmap->n;
7620: const PetscInt rs = C->rmap->rstart;
7621: const PetscInt re = C->rmap->rend;
7622: const PetscInt cs = C->cmap->rstart;
7624: if (mptmp[cp]) continue;
7625: if (rmapt[cp] == 1) { /* consecutive rows */
7626: /* fill coo_i */
7627: for (i = 0; i < mr; i++) {
7628: const PetscInt gr = i + rs;
7629: for (j = ii[i]; j < ii[i + 1]; j++) coi[j] = gr;
7630: }
7631: /* fill coo_j */
7632: if (!cmapt[cp]) { /* type-0, already global */
7633: PetscCall(PetscArraycpy(coj, jj, mm->nz));
7634: } else if (cmapt[cp] == 1) { /* type-1, local to global for consecutive columns of C */
7635: for (j = 0; j < mm->nz; j++) coj[j] = jj[j] + cs; /* lid + col start */
7636: } else { /* type-2, local to global for sparse columns */
7637: for (j = 0; j < mm->nz; j++) coj[j] = cmap[jj[j]];
7638: }
7639: ncoo_d += mm->nz;
7640: } else if (rmapt[cp] == 2) { /* sparse rows */
7641: for (i = 0; i < mr; i++) {
7642: const PetscInt *jj = mm->j + ii[i];
7643: const PetscInt gr = rmap[i];
7644: const PetscInt nz = ii[i + 1] - ii[i];
7645: if (gr >= rs && gr < re) { /* local rows */
7646: for (j = ii[i]; j < ii[i + 1]; j++) *coi++ = gr;
7647: if (!cmapt[cp]) { /* type-0, already global */
7648: for (j = 0; j < nz; j++) *coj++ = jj[j];
7649: } else if (cmapt[cp] == 1) { /* local to global for owned columns of C */
7650: for (j = 0; j < nz; j++) *coj++ = jj[j] + cs;
7651: } else { /* type-2, local to global for sparse columns */
7652: for (j = 0; j < nz; j++) *coj++ = cmap[jj[j]];
7653: }
7654: ncoo_d += nz;
7655: }
7656: }
7657: }
7658: }
7659: if (glob) PetscCall(ISRestoreIndices(glob, &globidx));
7660: PetscCall(ISDestroy(&glob));
7661: if (P_oth_l2g) PetscCall(ISLocalToGlobalMappingRestoreIndices(P_oth_l2g, &P_oth_idx));
7662: PetscCall(ISLocalToGlobalMappingDestroy(&P_oth_l2g));
7663: /* allocate an array to store all nonzeros (inserted locally or remotely) belonging to this proc */
7664: PetscCall(PetscSFMalloc(mmdata->sf, mmdata->mtype, ncoo * sizeof(PetscScalar), (void **)&mmdata->coo_v));
7666: /* set block sizes */
7667: A = product->A;
7668: P = product->B;
7669: switch (ptype) {
7670: case MATPRODUCT_PtAP:
7671: PetscCall(MatSetBlockSizes(C, P->cmap->bs, P->cmap->bs));
7672: break;
7673: case MATPRODUCT_RARt:
7674: PetscCall(MatSetBlockSizes(C, P->rmap->bs, P->rmap->bs));
7675: break;
7676: case MATPRODUCT_ABC:
7677: PetscCall(MatSetBlockSizesFromMats(C, A, product->C));
7678: break;
7679: case MATPRODUCT_AB:
7680: PetscCall(MatSetBlockSizesFromMats(C, A, P));
7681: break;
7682: case MATPRODUCT_AtB:
7683: PetscCall(MatSetBlockSizes(C, A->cmap->bs, P->cmap->bs));
7684: break;
7685: case MATPRODUCT_ABt:
7686: PetscCall(MatSetBlockSizes(C, A->rmap->bs, P->rmap->bs));
7687: break;
7688: default:
7689: SETERRQ(PetscObjectComm((PetscObject)C), PETSC_ERR_PLIB, "Not for ProductType %s", MatProductTypes[ptype]);
7690: }
7692: /* preallocate with COO data */
7693: PetscCall(MatSetPreallocationCOO(C, ncoo, coo_i, coo_j));
7694: PetscCall(PetscFree2(coo_i, coo_j));
7695: PetscFunctionReturn(PETSC_SUCCESS);
7696: }
7698: PetscErrorCode MatProductSetFromOptions_MPIAIJBACKEND(Mat mat)
7699: {
7700: Mat_Product *product = mat->product;
7701: #if PetscDefined(HAVE_DEVICE)
7702: PetscBool match = PETSC_FALSE;
7703: PetscBool usecpu = PETSC_FALSE;
7704: #else
7705: PetscBool match = PETSC_TRUE;
7706: #endif
7708: PetscFunctionBegin;
7709: MatCheckProduct(mat, 1);
7710: #if PetscDefined(HAVE_DEVICE)
7711: if (!product->A->boundtocpu && !product->B->boundtocpu) PetscCall(PetscObjectTypeCompare((PetscObject)product->B, ((PetscObject)product->A)->type_name, &match));
7712: if (match) { /* we can always fallback to the CPU if requested */
7713: switch (product->type) {
7714: case MATPRODUCT_AB:
7715: if (product->api_user) {
7716: PetscOptionsBegin(PetscObjectComm((PetscObject)mat), ((PetscObject)mat)->prefix, "MatMatMult", "Mat");
7717: PetscCall(PetscOptionsBool("-matmatmult_backend_cpu", "Use CPU code", "MatMatMult", usecpu, &usecpu, NULL));
7718: PetscOptionsEnd();
7719: } else {
7720: PetscOptionsBegin(PetscObjectComm((PetscObject)mat), ((PetscObject)mat)->prefix, "MatProduct_AB", "Mat");
7721: PetscCall(PetscOptionsBool("-mat_product_algorithm_backend_cpu", "Use CPU code", "MatMatMult", usecpu, &usecpu, NULL));
7722: PetscOptionsEnd();
7723: }
7724: break;
7725: case MATPRODUCT_AtB:
7726: if (product->api_user) {
7727: PetscOptionsBegin(PetscObjectComm((PetscObject)mat), ((PetscObject)mat)->prefix, "MatTransposeMatMult", "Mat");
7728: PetscCall(PetscOptionsBool("-mattransposematmult_backend_cpu", "Use CPU code", "MatTransposeMatMult", usecpu, &usecpu, NULL));
7729: PetscOptionsEnd();
7730: } else {
7731: PetscOptionsBegin(PetscObjectComm((PetscObject)mat), ((PetscObject)mat)->prefix, "MatProduct_AtB", "Mat");
7732: PetscCall(PetscOptionsBool("-mat_product_algorithm_backend_cpu", "Use CPU code", "MatTransposeMatMult", usecpu, &usecpu, NULL));
7733: PetscOptionsEnd();
7734: }
7735: break;
7736: case MATPRODUCT_PtAP:
7737: if (product->api_user) {
7738: PetscOptionsBegin(PetscObjectComm((PetscObject)mat), ((PetscObject)mat)->prefix, "MatPtAP", "Mat");
7739: PetscCall(PetscOptionsBool("-matptap_backend_cpu", "Use CPU code", "MatPtAP", usecpu, &usecpu, NULL));
7740: PetscOptionsEnd();
7741: } else {
7742: PetscOptionsBegin(PetscObjectComm((PetscObject)mat), ((PetscObject)mat)->prefix, "MatProduct_PtAP", "Mat");
7743: PetscCall(PetscOptionsBool("-mat_product_algorithm_backend_cpu", "Use CPU code", "MatPtAP", usecpu, &usecpu, NULL));
7744: PetscOptionsEnd();
7745: }
7746: break;
7747: default:
7748: break;
7749: }
7750: match = (PetscBool)!usecpu;
7751: }
7752: #endif
7753: if (match) {
7754: switch (product->type) {
7755: case MATPRODUCT_AB:
7756: case MATPRODUCT_AtB:
7757: case MATPRODUCT_PtAP:
7758: mat->ops->productsymbolic = MatProductSymbolic_MPIAIJBACKEND;
7759: break;
7760: default:
7761: break;
7762: }
7763: }
7764: /* fallback to MPIAIJ ops */
7765: if (!mat->ops->productsymbolic) PetscCall(MatProductSetFromOptions_MPIAIJ(mat));
7766: PetscFunctionReturn(PETSC_SUCCESS);
7767: }
7769: /*
7770: Produces a set of block column indices of the matrix row, one for each block represented in the original row
7772: n - the number of block indices in cc[]
7773: cc - the block indices (must be large enough to contain the indices)
7774: */
7775: static inline PetscErrorCode MatCollapseRow(Mat Amat, PetscInt row, PetscInt bs, PetscInt *n, PetscInt *cc)
7776: {
7777: PetscInt cnt = -1, nidx, j;
7778: const PetscInt *idx;
7780: PetscFunctionBegin;
7781: PetscCall(MatGetRow(Amat, row, &nidx, &idx, NULL));
7782: if (nidx) {
7783: cnt = 0;
7784: cc[cnt] = idx[0] / bs;
7785: for (j = 1; j < nidx; j++) {
7786: if (cc[cnt] < idx[j] / bs) cc[++cnt] = idx[j] / bs;
7787: }
7788: }
7789: PetscCall(MatRestoreRow(Amat, row, &nidx, &idx, NULL));
7790: *n = cnt + 1;
7791: PetscFunctionReturn(PETSC_SUCCESS);
7792: }
7794: /*
7795: Produces a set of block column indices of the matrix block row, one for each block represented in the original set of rows
7797: ncollapsed - the number of block indices
7798: collapsed - the block indices (must be large enough to contain the indices)
7799: */
7800: static inline PetscErrorCode MatCollapseRows(Mat Amat, PetscInt start, PetscInt bs, PetscInt *w0, PetscInt *w1, PetscInt *w2, PetscInt *ncollapsed, PetscInt **collapsed)
7801: {
7802: PetscInt i, nprev, *cprev = w0, ncur = 0, *ccur = w1, *merged = w2, *cprevtmp;
7804: PetscFunctionBegin;
7805: PetscCall(MatCollapseRow(Amat, start, bs, &nprev, cprev));
7806: for (i = start + 1; i < start + bs; i++) {
7807: PetscCall(MatCollapseRow(Amat, i, bs, &ncur, ccur));
7808: PetscCall(PetscMergeIntArray(nprev, cprev, ncur, ccur, &nprev, &merged));
7809: cprevtmp = cprev;
7810: cprev = merged;
7811: merged = cprevtmp;
7812: }
7813: *ncollapsed = nprev;
7814: if (collapsed) *collapsed = cprev;
7815: PetscFunctionReturn(PETSC_SUCCESS);
7816: }
7818: PETSC_INTERN PetscErrorCode MatCreateGraph_Simple_AIJ(Mat Amat, PetscBool symmetrize, PetscBool scale, PetscReal filter, PetscInt index_size, PetscInt index[], Mat *a_Gmat)
7819: {
7820: PetscInt Istart, Iend, Ii, jj, kk, ncols, nloc, NN, MM, bs;
7821: MPI_Comm comm;
7822: Mat Gmat;
7823: PetscBool ismpiaij, isseqaij;
7824: Mat a, b, c;
7825: MatType jtype;
7827: PetscFunctionBegin;
7828: PetscCall(PetscObjectGetComm((PetscObject)Amat, &comm));
7829: PetscCall(MatGetOwnershipRange(Amat, &Istart, &Iend));
7830: PetscCall(MatGetSize(Amat, &MM, &NN));
7831: PetscCall(MatGetBlockSize(Amat, &bs));
7832: nloc = (Iend - Istart) / bs;
7834: PetscCall(PetscObjectBaseTypeCompare((PetscObject)Amat, MATSEQAIJ, &isseqaij));
7835: PetscCall(PetscObjectBaseTypeCompare((PetscObject)Amat, MATMPIAIJ, &ismpiaij));
7836: PetscCheck(isseqaij || ismpiaij, comm, PETSC_ERR_USER, "Require (MPI)AIJ matrix type");
7838: /* TODO GPU: these calls are potentially expensive if matrices are large and we want to use the GPU */
7839: /* A solution consists in providing a new API, MatAIJGetCollapsedAIJ, and each class can provide a fast
7840: implementation */
7841: if (bs > 1) {
7842: PetscCall(MatGetType(Amat, &jtype));
7843: PetscCall(MatCreate(comm, &Gmat));
7844: PetscCall(MatSetType(Gmat, jtype));
7845: PetscCall(MatSetSizes(Gmat, nloc, nloc, PETSC_DETERMINE, PETSC_DETERMINE));
7846: PetscCall(MatSetBlockSizes(Gmat, 1, 1));
7847: if (isseqaij || ((Mat_MPIAIJ *)Amat->data)->garray) {
7848: PetscInt *d_nnz, *o_nnz;
7849: MatScalar *aa, val, *AA;
7850: PetscInt *aj, *ai, *AJ, nc, nmax = 0;
7852: if (isseqaij) {
7853: a = Amat;
7854: b = NULL;
7855: } else {
7856: Mat_MPIAIJ *d = (Mat_MPIAIJ *)Amat->data;
7857: a = d->A;
7858: b = d->B;
7859: }
7860: PetscCall(PetscInfo(Amat, "New bs>1 Graph. nloc=%" PetscInt_FMT "\n", nloc));
7861: PetscCall(PetscMalloc2(nloc, &d_nnz, (isseqaij ? 0 : nloc), &o_nnz));
7862: for (c = a, kk = 0; c && kk < 2; c = b, kk++) {
7863: PetscInt *nnz = (c == a) ? d_nnz : o_nnz;
7864: const PetscInt *cols1, *cols2;
7866: for (PetscInt brow = 0, nc1, nc2, ok = 1; brow < nloc * bs; brow += bs) { // block rows
7867: PetscCall(MatGetRow(c, brow, &nc2, &cols2, NULL));
7868: nnz[brow / bs] = nc2 / bs;
7869: if (nc2 % bs) ok = 0;
7870: if (nnz[brow / bs] > nmax) nmax = nnz[brow / bs];
7871: for (PetscInt ii = 1; ii < bs; ii++) { // check for non-dense blocks
7872: PetscCall(MatGetRow(c, brow + ii, &nc1, &cols1, NULL));
7873: if (nc1 != nc2) ok = 0;
7874: else {
7875: for (PetscInt jj = 0; jj < nc1 && ok == 1; jj++) {
7876: if (cols1[jj] != cols2[jj]) ok = 0;
7877: if (cols1[jj] % bs != jj % bs) ok = 0;
7878: }
7879: }
7880: PetscCall(MatRestoreRow(c, brow + ii, &nc1, &cols1, NULL));
7881: }
7882: PetscCall(MatRestoreRow(c, brow, &nc2, &cols2, NULL));
7883: if (!ok) {
7884: PetscCall(PetscFree2(d_nnz, o_nnz));
7885: PetscCall(PetscInfo(Amat, "Found sparse blocks - revert to slow method\n"));
7886: goto old_bs;
7887: }
7888: }
7889: }
7890: PetscCall(MatSeqAIJSetPreallocation(Gmat, 0, d_nnz));
7891: PetscCall(MatMPIAIJSetPreallocation(Gmat, 0, d_nnz, 0, o_nnz));
7892: PetscCall(PetscFree2(d_nnz, o_nnz));
7893: PetscCall(PetscMalloc2(nmax, &AA, nmax, &AJ));
7894: // diag
7895: for (PetscInt brow = 0, n, grow; brow < nloc * bs; brow += bs) { // block rows
7896: Mat_SeqAIJ *aseq = (Mat_SeqAIJ *)a->data;
7898: ai = aseq->i;
7899: n = ai[brow + 1] - ai[brow];
7900: aj = aseq->j + ai[brow];
7901: for (PetscInt k = 0; k < n; k += bs) { // block columns
7902: AJ[k / bs] = aj[k] / bs + Istart / bs; // diag starts at (Istart,Istart)
7903: val = 0;
7904: if (index_size == 0) {
7905: for (PetscInt ii = 0; ii < bs; ii++) { // rows in block
7906: aa = aseq->a + ai[brow + ii] + k;
7907: for (PetscInt jj = 0; jj < bs; jj++) { // columns in block
7908: val += PetscAbs(PetscRealPart(aa[jj])); // a sort of norm
7909: }
7910: }
7911: } else { // use (index,index) value if provided
7912: for (PetscInt iii = 0; iii < index_size; iii++) { // rows in block
7913: PetscInt ii = index[iii];
7914: aa = aseq->a + ai[brow + ii] + k;
7915: for (PetscInt jjj = 0; jjj < index_size; jjj++) { // columns in block
7916: PetscInt jj = index[jjj];
7917: val += PetscAbs(PetscRealPart(aa[jj]));
7918: }
7919: }
7920: }
7921: PetscAssert(k / bs < nmax, comm, PETSC_ERR_USER, "k / bs (%" PetscInt_FMT ") >= nmax (%" PetscInt_FMT ")", k / bs, nmax);
7922: AA[k / bs] = val;
7923: }
7924: grow = Istart / bs + brow / bs;
7925: PetscCall(MatSetValues(Gmat, 1, &grow, n / bs, AJ, AA, ADD_VALUES));
7926: }
7927: // off-diag
7928: if (ismpiaij) {
7929: Mat_MPIAIJ *aij = (Mat_MPIAIJ *)Amat->data;
7930: const PetscScalar *vals;
7931: const PetscInt *cols, *garray = aij->garray;
7933: PetscCheck(garray, PETSC_COMM_SELF, PETSC_ERR_USER, "No garray ?");
7934: for (PetscInt brow = 0, grow; brow < nloc * bs; brow += bs) { // block rows
7935: PetscCall(MatGetRow(b, brow, &ncols, &cols, NULL));
7936: for (PetscInt k = 0, cidx = 0; k < ncols; k += bs, cidx++) {
7937: PetscAssert(k / bs < nmax, comm, PETSC_ERR_USER, "k / bs >= nmax");
7938: AA[k / bs] = 0;
7939: AJ[cidx] = garray[cols[k]] / bs;
7940: }
7941: nc = ncols / bs;
7942: PetscCall(MatRestoreRow(b, brow, &ncols, &cols, NULL));
7943: if (index_size == 0) {
7944: for (PetscInt ii = 0; ii < bs; ii++) { // rows in block
7945: PetscCall(MatGetRow(b, brow + ii, &ncols, &cols, &vals));
7946: for (PetscInt k = 0; k < ncols; k += bs) {
7947: for (PetscInt jj = 0; jj < bs; jj++) { // cols in block
7948: PetscAssert(k / bs < nmax, comm, PETSC_ERR_USER, "k / bs (%" PetscInt_FMT ") >= nmax (%" PetscInt_FMT ")", k / bs, nmax);
7949: AA[k / bs] += PetscAbs(PetscRealPart(vals[k + jj]));
7950: }
7951: }
7952: PetscCall(MatRestoreRow(b, brow + ii, &ncols, &cols, &vals));
7953: }
7954: } else { // use (index,index) value if provided
7955: for (PetscInt iii = 0; iii < index_size; iii++) { // rows in block
7956: PetscInt ii = index[iii];
7957: PetscCall(MatGetRow(b, brow + ii, &ncols, &cols, &vals));
7958: for (PetscInt k = 0; k < ncols; k += bs) {
7959: for (PetscInt jjj = 0; jjj < index_size; jjj++) { // cols in block
7960: PetscInt jj = index[jjj];
7961: AA[k / bs] += PetscAbs(PetscRealPart(vals[k + jj]));
7962: }
7963: }
7964: PetscCall(MatRestoreRow(b, brow + ii, &ncols, &cols, &vals));
7965: }
7966: }
7967: grow = Istart / bs + brow / bs;
7968: PetscCall(MatSetValues(Gmat, 1, &grow, nc, AJ, AA, ADD_VALUES));
7969: }
7970: }
7971: PetscCall(MatAssemblyBegin(Gmat, MAT_FINAL_ASSEMBLY));
7972: PetscCall(MatAssemblyEnd(Gmat, MAT_FINAL_ASSEMBLY));
7973: PetscCall(PetscFree2(AA, AJ));
7974: } else {
7975: const PetscScalar *vals;
7976: const PetscInt *idx;
7977: PetscInt *d_nnz, *o_nnz, *w0, *w1, *w2;
7978: old_bs:
7979: /*
7980: Determine the preallocation needed for the scalar matrix derived from the vector matrix.
7981: */
7982: PetscCall(PetscInfo(Amat, "OLD bs>1 CreateGraph\n"));
7983: PetscCall(PetscMalloc2(nloc, &d_nnz, (isseqaij ? 0 : nloc), &o_nnz));
7984: if (isseqaij) {
7985: PetscInt max_d_nnz;
7987: /*
7988: Determine exact preallocation count for (sequential) scalar matrix
7989: */
7990: PetscCall(MatSeqAIJGetMaxRowNonzeros(Amat, &max_d_nnz));
7991: max_d_nnz = PetscMin(nloc, bs * max_d_nnz);
7992: PetscCall(PetscMalloc3(max_d_nnz, &w0, max_d_nnz, &w1, max_d_nnz, &w2));
7993: for (Ii = 0, jj = 0; Ii < Iend; Ii += bs, jj++) PetscCall(MatCollapseRows(Amat, Ii, bs, w0, w1, w2, &d_nnz[jj], NULL));
7994: PetscCall(PetscFree3(w0, w1, w2));
7995: } else if (ismpiaij) {
7996: Mat Daij, Oaij;
7997: const PetscInt *garray;
7998: PetscInt max_d_nnz;
8000: PetscCall(MatMPIAIJGetSeqAIJ(Amat, &Daij, &Oaij, &garray));
8001: /*
8002: Determine exact preallocation count for diagonal block portion of scalar matrix
8003: */
8004: PetscCall(MatSeqAIJGetMaxRowNonzeros(Daij, &max_d_nnz));
8005: max_d_nnz = PetscMin(nloc, bs * max_d_nnz);
8006: PetscCall(PetscMalloc3(max_d_nnz, &w0, max_d_nnz, &w1, max_d_nnz, &w2));
8007: for (Ii = 0, jj = 0; Ii < Iend - Istart; Ii += bs, jj++) PetscCall(MatCollapseRows(Daij, Ii, bs, w0, w1, w2, &d_nnz[jj], NULL));
8008: PetscCall(PetscFree3(w0, w1, w2));
8009: /*
8010: Over estimate (usually grossly over), preallocation count for off-diagonal portion of scalar matrix
8011: */
8012: for (Ii = 0, jj = 0; Ii < Iend - Istart; Ii += bs, jj++) {
8013: o_nnz[jj] = 0;
8014: for (kk = 0; kk < bs; kk++) { /* rows that get collapsed to a single row */
8015: PetscCall(MatGetRow(Oaij, Ii + kk, &ncols, NULL, NULL));
8016: o_nnz[jj] += ncols;
8017: PetscCall(MatRestoreRow(Oaij, Ii + kk, &ncols, NULL, NULL));
8018: }
8019: if (o_nnz[jj] > (NN / bs - nloc)) o_nnz[jj] = NN / bs - nloc;
8020: }
8021: } else SETERRQ(comm, PETSC_ERR_USER, "Require AIJ matrix type");
8022: /* get scalar copy (norms) of matrix */
8023: PetscCall(MatSeqAIJSetPreallocation(Gmat, 0, d_nnz));
8024: PetscCall(MatMPIAIJSetPreallocation(Gmat, 0, d_nnz, 0, o_nnz));
8025: PetscCall(PetscFree2(d_nnz, o_nnz));
8026: for (Ii = Istart; Ii < Iend; Ii++) {
8027: PetscInt dest_row = Ii / bs;
8029: PetscCall(MatGetRow(Amat, Ii, &ncols, &idx, &vals));
8030: for (jj = 0; jj < ncols; jj++) {
8031: PetscInt dest_col = idx[jj] / bs;
8032: PetscScalar sv = PetscAbs(PetscRealPart(vals[jj]));
8034: PetscCall(MatSetValues(Gmat, 1, &dest_row, 1, &dest_col, &sv, ADD_VALUES));
8035: }
8036: PetscCall(MatRestoreRow(Amat, Ii, &ncols, &idx, &vals));
8037: }
8038: PetscCall(MatAssemblyBegin(Gmat, MAT_FINAL_ASSEMBLY));
8039: PetscCall(MatAssemblyEnd(Gmat, MAT_FINAL_ASSEMBLY));
8040: }
8041: } else {
8042: if (symmetrize || filter >= 0 || scale) PetscCall(MatDuplicate(Amat, MAT_COPY_VALUES, &Gmat));
8043: else {
8044: Gmat = Amat;
8045: PetscCall(PetscObjectReference((PetscObject)Gmat));
8046: }
8047: if (isseqaij) {
8048: a = Gmat;
8049: b = NULL;
8050: } else {
8051: Mat_MPIAIJ *d = (Mat_MPIAIJ *)Gmat->data;
8052: a = d->A;
8053: b = d->B;
8054: }
8055: if (filter >= 0 || scale) {
8056: /* take absolute value of each entry */
8057: for (c = a, kk = 0; c && kk < 2; c = b, kk++) {
8058: MatInfo info;
8059: PetscScalar *avals;
8061: PetscCall(MatGetInfo(c, MAT_LOCAL, &info));
8062: PetscCall(MatSeqAIJGetArray(c, &avals));
8063: for (int jj = 0; jj < info.nz_used; jj++) avals[jj] = PetscAbsScalar(avals[jj]);
8064: PetscCall(MatSeqAIJRestoreArray(c, &avals));
8065: }
8066: }
8067: }
8068: if (symmetrize) {
8069: PetscBool isset, issym;
8071: PetscCall(MatIsSymmetricKnown(Amat, &isset, &issym));
8072: if (!isset || !issym) {
8073: Mat matTrans;
8075: PetscCall(MatTranspose(Gmat, MAT_INITIAL_MATRIX, &matTrans));
8076: PetscCall(MatAXPY(Gmat, 1.0, matTrans, Gmat->structurally_symmetric == PETSC_BOOL3_TRUE ? SAME_NONZERO_PATTERN : DIFFERENT_NONZERO_PATTERN));
8077: PetscCall(MatDestroy(&matTrans));
8078: }
8079: PetscCall(MatSetOption(Gmat, MAT_SYMMETRIC, PETSC_TRUE));
8080: } else if (Amat != Gmat) PetscCall(MatPropagateSymmetryOptions(Amat, Gmat));
8081: if (scale) {
8082: /* scale c for all diagonal values = 1 or -1 */
8083: Vec diag;
8085: PetscCall(MatCreateVecs(Gmat, &diag, NULL));
8086: PetscCall(MatGetDiagonal(Gmat, diag));
8087: PetscCall(VecReciprocal(diag));
8088: PetscCall(VecSqrtAbs(diag));
8089: PetscCall(MatDiagonalScale(Gmat, diag, diag));
8090: PetscCall(VecDestroy(&diag));
8091: }
8092: PetscCall(MatViewFromOptions(Gmat, NULL, "-mat_graph_view"));
8093: if (filter >= 0) {
8094: PetscCall(MatFilter(Gmat, filter, PETSC_TRUE, PETSC_TRUE));
8095: PetscCall(MatViewFromOptions(Gmat, NULL, "-mat_filter_graph_view"));
8096: }
8097: *a_Gmat = Gmat;
8098: PetscFunctionReturn(PETSC_SUCCESS);
8099: }
8101: PETSC_INTERN PetscErrorCode MatGetCurrentMemType_MPIAIJ(Mat A, PetscMemType *memtype)
8102: {
8103: Mat_MPIAIJ *mpiaij = (Mat_MPIAIJ *)A->data;
8104: PetscMemType mD = PETSC_MEMTYPE_HOST, mO = PETSC_MEMTYPE_HOST;
8106: PetscFunctionBegin;
8107: if (mpiaij->A) PetscCall(MatGetCurrentMemType(mpiaij->A, &mD));
8108: if (mpiaij->B) PetscCall(MatGetCurrentMemType(mpiaij->B, &mO));
8109: *memtype = (mD == mO) ? mD : PETSC_MEMTYPE_HOST;
8110: PetscFunctionReturn(PETSC_SUCCESS);
8111: }
8113: /*
8114: Special version for direct calls from Fortran
8115: */
8117: /* Change these macros so can be used in void function */
8118: /* Identical to PetscCallVoid, except it assigns to *_ierr */
8119: #undef PetscCall
8120: #define PetscCall(...) \
8121: do { \
8122: PetscErrorCode ierr_msv_mpiaij = __VA_ARGS__; \
8123: if (PetscUnlikely(ierr_msv_mpiaij)) { \
8124: *_ierr = PetscError(PETSC_COMM_SELF, __LINE__, PETSC_FUNCTION_NAME, __FILE__, ierr_msv_mpiaij, PETSC_ERROR_REPEAT, " "); \
8125: return; \
8126: } \
8127: } while (0)
8129: #undef SETERRQ
8130: #define SETERRQ(comm, ierr, ...) \
8131: do { \
8132: *_ierr = PetscError(comm, __LINE__, PETSC_FUNCTION_NAME, __FILE__, ierr, PETSC_ERROR_INITIAL, __VA_ARGS__); \
8133: return; \
8134: } while (0)
8136: #if PetscDefined(HAVE_FORTRAN_CAPS)
8137: #define matsetvaluesmpiaij_ MATSETVALUESMPIAIJ
8138: #elif !PetscDefined(HAVE_FORTRAN_UNDERSCORE)
8139: #define matsetvaluesmpiaij_ matsetvaluesmpiaij
8140: #else
8141: #endif
8142: PETSC_EXTERN void matsetvaluesmpiaij_(Mat *mmat, PetscInt *mm, const PetscInt im[], PetscInt *mn, const PetscInt in[], const PetscScalar v[], InsertMode *maddv, PetscErrorCode *_ierr)
8143: {
8144: Mat mat = *mmat;
8145: PetscInt m = *mm, n = *mn;
8146: InsertMode addv = *maddv;
8147: Mat_MPIAIJ *aij = (Mat_MPIAIJ *)mat->data;
8148: PetscScalar value;
8150: MatCheckPreallocated(mat, 1);
8151: if (mat->insertmode == NOT_SET_VALUES) mat->insertmode = addv;
8152: else PetscCheck(mat->insertmode == addv, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Cannot mix add values and insert values");
8153: {
8154: PetscInt i, j, rstart = mat->rmap->rstart, rend = mat->rmap->rend;
8155: PetscInt cstart = mat->cmap->rstart, cend = mat->cmap->rend, row, col;
8156: PetscBool roworiented = aij->roworiented;
8158: /* Some Variables required in the macro */
8159: Mat A = aij->A;
8160: Mat_SeqAIJ *a = (Mat_SeqAIJ *)A->data;
8161: PetscInt *aimax = a->imax, *ai = a->i, *ailen = a->ilen, *aj = a->j;
8162: MatScalar *aa;
8163: PetscBool ignorezeroentries = (a->ignorezeroentries && addv == ADD_VALUES) ? PETSC_TRUE : PETSC_FALSE;
8164: Mat B = aij->B;
8165: Mat_SeqAIJ *b = (Mat_SeqAIJ *)B->data;
8166: PetscInt *bimax = b->imax, *bi = b->i, *bilen = b->ilen, *bj = b->j, bm = aij->B->rmap->n, am = aij->A->rmap->n;
8167: MatScalar *ba;
8168: /* This variable below is only for the PETSC_HAVE_VIENNACL or PETSC_HAVE_CUDA cases, but we define it in all cases because we
8169: * cannot use "#if defined" inside a macro. */
8170: PETSC_UNUSED PetscBool inserted = PETSC_FALSE;
8172: PetscInt *rp1, *rp2, ii, nrow1, nrow2, _i, rmax1, rmax2, N, low1, high1, low2, high2, t, lastcol1, lastcol2;
8173: PetscInt nonew = a->nonew;
8174: MatScalar *ap1, *ap2;
8176: PetscFunctionBegin;
8177: PetscCall(MatSeqAIJGetArray(A, &aa));
8178: PetscCall(MatSeqAIJGetArray(B, &ba));
8179: for (i = 0; i < m; i++) {
8180: if (im[i] < 0) continue;
8181: 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);
8182: if (im[i] >= rstart && im[i] < rend) {
8183: row = im[i] - rstart;
8184: lastcol1 = -1;
8185: rp1 = aj + ai[row];
8186: ap1 = aa + ai[row];
8187: rmax1 = aimax[row];
8188: nrow1 = ailen[row];
8189: low1 = 0;
8190: high1 = nrow1;
8191: lastcol2 = -1;
8192: rp2 = bj + bi[row];
8193: ap2 = ba + bi[row];
8194: rmax2 = bimax[row];
8195: nrow2 = bilen[row];
8196: low2 = 0;
8197: high2 = nrow2;
8199: for (j = 0; j < n; j++) {
8200: if (roworiented) value = v[i * n + j];
8201: else value = v[i + j * m];
8202: if (ignorezeroentries && value == 0.0 && addv == ADD_VALUES && im[i] != in[j]) continue;
8203: if (in[j] >= cstart && in[j] < cend) {
8204: col = in[j] - cstart;
8205: MatSetValues_SeqAIJ_A_Private(row, col, value, addv, im[i], in[j]);
8206: } else if (in[j] < 0) continue;
8207: else if (PetscUnlikelyDebug(in[j] >= mat->cmap->N)) {
8208: SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Column too large: col %" PetscInt_FMT " max %" PetscInt_FMT, in[j], mat->cmap->N - 1);
8209: } else {
8210: if (mat->was_assembled) {
8211: if (!aij->colmap) PetscCall(MatCreateColmap_MPIAIJ_Private(mat));
8212: #if PetscDefined(USE_CTABLE)
8213: PetscCall(PetscHMapIGetWithDefault(aij->colmap, in[j] + 1, 0, &col));
8214: col--;
8215: #else
8216: col = aij->colmap[in[j]] - 1;
8217: #endif
8218: if (col < 0 && !((Mat_SeqAIJ *)aij->A->data)->nonew) {
8219: PetscCall(MatDisAssemble_MPIAIJ(mat, PETSC_FALSE));
8220: col = in[j];
8221: /* Reinitialize the variables required by MatSetValues_SeqAIJ_B_Private() */
8222: B = aij->B;
8223: b = (Mat_SeqAIJ *)B->data;
8224: bimax = b->imax;
8225: bi = b->i;
8226: bilen = b->ilen;
8227: bj = b->j;
8228: rp2 = bj + bi[row];
8229: ap2 = ba + bi[row];
8230: rmax2 = bimax[row];
8231: nrow2 = bilen[row];
8232: low2 = 0;
8233: high2 = nrow2;
8234: bm = aij->B->rmap->n;
8235: ba = b->a;
8236: inserted = PETSC_FALSE;
8237: }
8238: } else col = in[j];
8239: MatSetValues_SeqAIJ_B_Private(row, col, value, addv, im[i], in[j]);
8240: }
8241: }
8242: } else if (!aij->donotstash) {
8243: if (roworiented) {
8244: PetscCall(MatStashValuesRow_Private(&mat->stash, im[i], n, in, v + i * n, (PetscBool)(ignorezeroentries && addv == ADD_VALUES)));
8245: } else {
8246: PetscCall(MatStashValuesCol_Private(&mat->stash, im[i], n, in, v + i, m, (PetscBool)(ignorezeroentries && addv == ADD_VALUES)));
8247: }
8248: }
8249: }
8250: PetscCall(MatSeqAIJRestoreArray(A, &aa));
8251: PetscCall(MatSeqAIJRestoreArray(B, &ba));
8252: }
8253: PetscFunctionReturnVoid();
8254: }
8256: /* Undefining these here since they were redefined from their original definition above! No
8257: * other PETSc functions should be defined past this point, as it is impossible to recover the
8258: * original definitions */
8259: #undef PetscCall
8260: #undef SETERRQ