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