Actual source code: mpiaij.c

  1: #include <../src/mat/impls/aij/mpi/mpiaij.h>
  2: #include <petsc/private/vecimpl.h>
  3: #include <petsc/private/sfimpl.h>
  4: #include <petsc/private/isimpl.h>
  5: #include <petscblaslapack.h>
  6: #include <petscsf.h>
  7: #include <petsc/private/hashmapi.h>

  9: /* defines MatSetValues_MPI_Hash(), MatAssemblyBegin_MPI_Hash(), and MatAssemblyEnd_MPI_Hash() */
 10: #define TYPE AIJ
 11: #define TYPE_AIJ
 12: #include "../src/mat/impls/aij/mpi/mpihashmat.h"
 13: #undef TYPE
 14: #undef TYPE_AIJ

 16: static PetscErrorCode MatReset_MPIAIJ(Mat mat)
 17: {
 18:   Mat_MPIAIJ *aij = (Mat_MPIAIJ *)mat->data;

 20:   PetscFunctionBegin;
 21:   PetscCall(PetscLogObjectState((PetscObject)mat, "Rows=%" PetscInt_FMT ", Cols=%" PetscInt_FMT, mat->rmap->N, mat->cmap->N));
 22:   PetscCall(MatStashDestroy_Private(&mat->stash));
 23:   PetscCall(VecDestroy(&aij->diag));
 24:   PetscCall(MatDestroy(&aij->A));
 25:   PetscCall(MatDestroy(&aij->B));
 26: #if defined(PETSC_USE_CTABLE)
 27:   PetscCall(PetscHMapIDestroy(&aij->colmap));
 28: #else
 29:   PetscCall(PetscFree(aij->colmap));
 30: #endif
 31:   PetscCall(PetscFree(aij->garray));
 32:   PetscCall(VecDestroy(&aij->lvec));
 33:   PetscCall(VecScatterDestroy(&aij->Mvctx));
 34:   PetscCall(PetscFree2(aij->rowvalues, aij->rowindices));
 35:   PetscCall(PetscFree(aij->ld));
 36:   PetscFunctionReturn(PETSC_SUCCESS);
 37: }

 39: static PetscErrorCode MatResetHash_MPIAIJ(Mat mat)
 40: {
 41:   Mat_MPIAIJ *aij = (Mat_MPIAIJ *)mat->data;
 42:   /* Save the nonzero states of the component matrices because those are what are used to determine
 43:     the nonzero state of mat */
 44:   PetscObjectState Astate = aij->A->nonzerostate, Bstate = aij->B->nonzerostate;

 46:   PetscFunctionBegin;
 47:   PetscCall(MatReset_MPIAIJ(mat));
 48:   PetscCall(MatSetUp_MPI_Hash(mat));
 49:   aij->A->nonzerostate = ++Astate, aij->B->nonzerostate = ++Bstate;
 50:   PetscFunctionReturn(PETSC_SUCCESS);
 51: }

 53: PetscErrorCode MatDestroy_MPIAIJ(Mat mat)
 54: {
 55:   PetscFunctionBegin;
 56:   PetscCall(MatReset_MPIAIJ(mat));

 58:   PetscCall(PetscFree(mat->data));

 60:   /* may be created by MatCreateMPIAIJSumSeqAIJSymbolic */
 61:   PetscCall(PetscObjectCompose((PetscObject)mat, "MatMergeSeqsToMPI", NULL));

 63:   PetscCall(PetscObjectChangeTypeName((PetscObject)mat, NULL));
 64:   PetscCall(PetscObjectComposeFunction((PetscObject)mat, "MatStoreValues_C", NULL));
 65:   PetscCall(PetscObjectComposeFunction((PetscObject)mat, "MatRetrieveValues_C", NULL));
 66:   PetscCall(PetscObjectComposeFunction((PetscObject)mat, "MatIsTranspose_C", NULL));
 67:   PetscCall(PetscObjectComposeFunction((PetscObject)mat, "MatMPIAIJSetPreallocation_C", NULL));
 68:   PetscCall(PetscObjectComposeFunction((PetscObject)mat, "MatResetPreallocation_C", NULL));
 69:   PetscCall(PetscObjectComposeFunction((PetscObject)mat, "MatResetHash_C", NULL));
 70:   PetscCall(PetscObjectComposeFunction((PetscObject)mat, "MatMPIAIJSetPreallocationCSR_C", NULL));
 71:   PetscCall(PetscObjectComposeFunction((PetscObject)mat, "MatDiagonalScaleLocal_C", NULL));
 72:   PetscCall(PetscObjectComposeFunction((PetscObject)mat, "MatConvert_mpiaij_mpibaij_C", NULL));
 73:   PetscCall(PetscObjectComposeFunction((PetscObject)mat, "MatConvert_mpiaij_mpisbaij_C", NULL));
 74: #if defined(PETSC_HAVE_CUDA)
 75:   PetscCall(PetscObjectComposeFunction((PetscObject)mat, "MatConvert_mpiaij_mpiaijcusparse_C", NULL));
 76: #endif
 77: #if defined(PETSC_HAVE_HIP)
 78:   PetscCall(PetscObjectComposeFunction((PetscObject)mat, "MatConvert_mpiaij_mpiaijhipsparse_C", NULL));
 79: #endif
 80: #if defined(PETSC_HAVE_KOKKOS_KERNELS)
 81:   PetscCall(PetscObjectComposeFunction((PetscObject)mat, "MatConvert_mpiaij_mpiaijkokkos_C", NULL));
 82: #endif
 83:   PetscCall(PetscObjectComposeFunction((PetscObject)mat, "MatConvert_mpiaij_mpidense_C", NULL));
 84: #if defined(PETSC_HAVE_ELEMENTAL)
 85:   PetscCall(PetscObjectComposeFunction((PetscObject)mat, "MatConvert_mpiaij_elemental_C", NULL));
 86: #endif
 87: #if defined(PETSC_HAVE_SCALAPACK) && (defined(PETSC_USE_REAL_SINGLE) || defined(PETSC_USE_REAL_DOUBLE))
 88:   PetscCall(PetscObjectComposeFunction((PetscObject)mat, "MatConvert_mpiaij_scalapack_C", NULL));
 89: #endif
 90: #if defined(PETSC_HAVE_HYPRE)
 91:   PetscCall(PetscObjectComposeFunction((PetscObject)mat, "MatConvert_mpiaij_hypre_C", NULL));
 92:   PetscCall(PetscObjectComposeFunction((PetscObject)mat, "MatProductSetFromOptions_transpose_mpiaij_mpiaij_C", NULL));
 93: #endif
 94:   PetscCall(PetscObjectComposeFunction((PetscObject)mat, "MatConvert_mpiaij_is_C", NULL));
 95:   PetscCall(PetscObjectComposeFunction((PetscObject)mat, "MatProductSetFromOptions_is_mpiaij_C", NULL));
 96:   PetscCall(PetscObjectComposeFunction((PetscObject)mat, "MatProductSetFromOptions_mpiaij_mpiaij_C", NULL));
 97:   PetscCall(PetscObjectComposeFunction((PetscObject)mat, "MatMPIAIJSetUseScalableIncreaseOverlap_C", NULL));
 98:   PetscCall(PetscObjectComposeFunction((PetscObject)mat, "MatConvert_mpiaij_mpiaijperm_C", NULL));
 99:   PetscCall(PetscObjectComposeFunction((PetscObject)mat, "MatConvert_mpiaij_mpiaijsell_C", NULL));
100: #if defined(PETSC_HAVE_MKL_SPARSE)
101:   PetscCall(PetscObjectComposeFunction((PetscObject)mat, "MatConvert_mpiaij_mpiaijmkl_C", NULL));
102: #endif
103:   PetscCall(PetscObjectComposeFunction((PetscObject)mat, "MatConvert_mpiaij_mpiaijcrl_C", NULL));
104:   PetscCall(PetscObjectComposeFunction((PetscObject)mat, "MatConvert_mpiaij_is_C", NULL));
105:   PetscCall(PetscObjectComposeFunction((PetscObject)mat, "MatConvert_mpiaij_mpisell_C", NULL));
106:   PetscCall(PetscObjectComposeFunction((PetscObject)mat, "MatSetPreallocationCOO_C", NULL));
107:   PetscCall(PetscObjectComposeFunction((PetscObject)mat, "MatSetValuesCOO_C", NULL));
108:   PetscFunctionReturn(PETSC_SUCCESS);
109: }

111: static PetscErrorCode MatGetRowIJ_MPIAIJ(Mat A, PetscInt oshift, PetscBool symmetric, PetscBool inodecompressed, PetscInt *m, const PetscInt *ia[], const PetscInt *ja[], PetscBool *done)
112: {
113:   Mat B;

115:   PetscFunctionBegin;
116:   PetscCall(MatMPIAIJGetLocalMat(A, MAT_INITIAL_MATRIX, &B));
117:   PetscCall(PetscObjectCompose((PetscObject)A, "MatGetRowIJ_MPIAIJ", (PetscObject)B));
118:   PetscCall(MatGetRowIJ(B, oshift, symmetric, inodecompressed, m, ia, ja, done));
119:   PetscCall(MatDestroy(&B));
120:   PetscFunctionReturn(PETSC_SUCCESS);
121: }

123: static PetscErrorCode MatRestoreRowIJ_MPIAIJ(Mat A, PetscInt oshift, PetscBool symmetric, PetscBool inodecompressed, PetscInt *m, const PetscInt *ia[], const PetscInt *ja[], PetscBool *done)
124: {
125:   Mat B;

127:   PetscFunctionBegin;
128:   PetscCall(PetscObjectQuery((PetscObject)A, "MatGetRowIJ_MPIAIJ", (PetscObject *)&B));
129:   PetscCall(MatRestoreRowIJ(B, oshift, symmetric, inodecompressed, m, ia, ja, done));
130:   PetscCall(PetscObjectCompose((PetscObject)A, "MatGetRowIJ_MPIAIJ", NULL));
131:   PetscFunctionReturn(PETSC_SUCCESS);
132: }

134: /*MC
135:    MATAIJ - MATAIJ = "aij" - A matrix type to be used for sparse matrices.

137:    This matrix type is identical to` MATSEQAIJ` when constructed with a single process communicator,
138:    and `MATMPIAIJ` otherwise.  As a result, for single process communicators,
139:   `MatSeqAIJSetPreallocation()` is supported, and similarly `MatMPIAIJSetPreallocation()` is supported
140:   for communicators controlling multiple processes.  It is recommended that you call both of
141:   the above preallocation routines for simplicity.

143:    Options Database Key:
144: . -mat_type aij - sets the matrix type to `MATAIJ` during a call to `MatSetFromOptions()`

146:   Developer Note:
147:   Level: beginner

149:     Subclasses include `MATAIJCUSPARSE`, `MATAIJPERM`, `MATAIJSELL`, `MATAIJMKL`, `MATAIJCRL`, `MATAIJKOKKOS`,and also automatically switches over to use inodes when
150:    enough exist.

152: .seealso: [](ch_matrices), `Mat`, `MATMPIAIJ`, `MATSEQAIJ`, `MatCreateAIJ()`, `MatCreateSeqAIJ()`, `MATBAIJ`
153: M*/

155: /*MC
156:    MATAIJCRL - MATAIJCRL = "aijcrl" - A matrix type to be used for sparse matrices.

158:    This matrix type is identical to `MATSEQAIJCRL` when constructed with a single process communicator,
159:    and `MATMPIAIJCRL` otherwise.  As a result, for single process communicators,
160:    `MatSeqAIJSetPreallocation()` is supported, and similarly `MatMPIAIJSetPreallocation()` is supported
161:   for communicators controlling multiple processes.  It is recommended that you call both of
162:   the above preallocation routines for simplicity.

164:    Options Database Key:
165: . -mat_type aijcrl - sets the matrix type to `MATMPIAIJCRL` during a call to `MatSetFromOptions()`

167:   Level: beginner

169: .seealso: [](ch_matrices), `Mat`, `MatCreateMPIAIJCRL`, `MATSEQAIJCRL`, `MATMPIAIJCRL`, `MATSEQAIJ`, `MATMPIAIJ`, `MATAIJ`
170: M*/

172: static PetscErrorCode MatBindToCPU_MPIAIJ(Mat A, PetscBool flg)
173: {
174:   Mat_MPIAIJ *a = (Mat_MPIAIJ *)A->data;

176:   PetscFunctionBegin;
177: #if defined(PETSC_HAVE_CUDA) || defined(PETSC_HAVE_HIP) || defined(PETSC_HAVE_VIENNACL)
178:   A->boundtocpu = flg;
179: #endif
180:   if (a->A) PetscCall(MatBindToCPU(a->A, flg));
181:   if (a->B) PetscCall(MatBindToCPU(a->B, flg));

183:   /* In addition to binding the diagonal and off-diagonal matrices, bind the local vectors used for matrix-vector products.
184:    * This maybe seems a little odd for a MatBindToCPU() call to do, but it makes no sense for the binding of these vectors
185:    * to differ from the parent matrix. */
186:   if (a->lvec) PetscCall(VecBindToCPU(a->lvec, flg));
187:   if (a->diag) PetscCall(VecBindToCPU(a->diag, flg));
188:   PetscFunctionReturn(PETSC_SUCCESS);
189: }

191: static PetscErrorCode MatSetBlockSizes_MPIAIJ(Mat M, PetscInt rbs, PetscInt cbs)
192: {
193:   Mat_MPIAIJ *mat = (Mat_MPIAIJ *)M->data;

195:   PetscFunctionBegin;
196:   if (mat->A) {
197:     PetscCall(MatSetBlockSizes(mat->A, rbs, cbs));
198:     PetscCall(MatSetBlockSizes(mat->B, rbs, 1));
199:   }
200:   PetscFunctionReturn(PETSC_SUCCESS);
201: }

203: static PetscErrorCode MatFindNonzeroRows_MPIAIJ(Mat M, IS *keptrows)
204: {
205:   Mat_MPIAIJ      *mat = (Mat_MPIAIJ *)M->data;
206:   Mat_SeqAIJ      *a   = (Mat_SeqAIJ *)mat->A->data;
207:   Mat_SeqAIJ      *b   = (Mat_SeqAIJ *)mat->B->data;
208:   const PetscInt  *ia, *ib;
209:   const MatScalar *aa, *bb, *aav, *bav;
210:   PetscInt         na, nb, i, j, *rows, cnt = 0, n0rows;
211:   PetscInt         m = M->rmap->n, rstart = M->rmap->rstart;

213:   PetscFunctionBegin;
214:   *keptrows = NULL;

216:   ia = a->i;
217:   ib = b->i;
218:   PetscCall(MatSeqAIJGetArrayRead(mat->A, &aav));
219:   PetscCall(MatSeqAIJGetArrayRead(mat->B, &bav));
220:   for (i = 0; i < m; i++) {
221:     na = ia[i + 1] - ia[i];
222:     nb = ib[i + 1] - ib[i];
223:     if (!na && !nb) {
224:       cnt++;
225:       goto ok1;
226:     }
227:     aa = aav + ia[i];
228:     for (j = 0; j < na; j++) {
229:       if (aa[j] != 0.0) goto ok1;
230:     }
231:     bb = PetscSafePointerPlusOffset(bav, ib[i]);
232:     for (j = 0; j < nb; j++) {
233:       if (bb[j] != 0.0) goto ok1;
234:     }
235:     cnt++;
236:   ok1:;
237:   }
238:   PetscCallMPI(MPIU_Allreduce(&cnt, &n0rows, 1, MPIU_INT, MPI_SUM, PetscObjectComm((PetscObject)M)));
239:   if (!n0rows) {
240:     PetscCall(MatSeqAIJRestoreArrayRead(mat->A, &aav));
241:     PetscCall(MatSeqAIJRestoreArrayRead(mat->B, &bav));
242:     PetscFunctionReturn(PETSC_SUCCESS);
243:   }
244:   PetscCall(PetscMalloc1(M->rmap->n - cnt, &rows));
245:   cnt = 0;
246:   for (i = 0; i < m; i++) {
247:     na = ia[i + 1] - ia[i];
248:     nb = ib[i + 1] - ib[i];
249:     if (!na && !nb) continue;
250:     aa = aav + ia[i];
251:     for (j = 0; j < na; j++) {
252:       if (aa[j] != 0.0) {
253:         rows[cnt++] = rstart + i;
254:         goto ok2;
255:       }
256:     }
257:     bb = PetscSafePointerPlusOffset(bav, ib[i]);
258:     for (j = 0; j < nb; j++) {
259:       if (bb[j] != 0.0) {
260:         rows[cnt++] = rstart + i;
261:         goto ok2;
262:       }
263:     }
264:   ok2:;
265:   }
266:   PetscCall(ISCreateGeneral(PetscObjectComm((PetscObject)M), cnt, rows, PETSC_OWN_POINTER, keptrows));
267:   PetscCall(MatSeqAIJRestoreArrayRead(mat->A, &aav));
268:   PetscCall(MatSeqAIJRestoreArrayRead(mat->B, &bav));
269:   PetscFunctionReturn(PETSC_SUCCESS);
270: }

272: static PetscErrorCode MatDiagonalSet_MPIAIJ(Mat Y, Vec D, InsertMode is)
273: {
274:   Mat_MPIAIJ *aij = (Mat_MPIAIJ *)Y->data;
275:   PetscBool   cong;

277:   PetscFunctionBegin;
278:   PetscCall(MatHasCongruentLayouts(Y, &cong));
279:   if (Y->assembled && cong) PetscCall(MatDiagonalSet(aij->A, D, is));
280:   else PetscCall(MatDiagonalSet_Default(Y, D, is));
281:   PetscFunctionReturn(PETSC_SUCCESS);
282: }

284: static PetscErrorCode MatFindZeroDiagonals_MPIAIJ(Mat M, IS *zrows)
285: {
286:   Mat_MPIAIJ *aij = (Mat_MPIAIJ *)M->data;
287:   PetscInt    i, rstart, nrows, *rows;

289:   PetscFunctionBegin;
290:   *zrows = NULL;
291:   PetscCall(MatFindZeroDiagonals_SeqAIJ_Private(aij->A, &nrows, &rows));
292:   PetscCall(MatGetOwnershipRange(M, &rstart, NULL));
293:   for (i = 0; i < nrows; i++) rows[i] += rstart;
294:   PetscCall(ISCreateGeneral(PetscObjectComm((PetscObject)M), nrows, rows, PETSC_OWN_POINTER, zrows));
295:   PetscFunctionReturn(PETSC_SUCCESS);
296: }

298: static PetscErrorCode MatGetColumnReductions_MPIAIJ(Mat A, PetscInt type, PetscReal *reductions)
299: {
300:   Mat_MPIAIJ        *aij = (Mat_MPIAIJ *)A->data;
301:   PetscInt           i, m, n, *garray = aij->garray;
302:   Mat_SeqAIJ        *a_aij = (Mat_SeqAIJ *)aij->A->data;
303:   Mat_SeqAIJ        *b_aij = (Mat_SeqAIJ *)aij->B->data;
304:   PetscReal         *work;
305:   const PetscScalar *dummy;

307:   PetscFunctionBegin;
308:   PetscCall(MatGetSize(A, &m, &n));
309:   PetscCall(PetscCalloc1(n, &work));
310:   PetscCall(MatSeqAIJGetArrayRead(aij->A, &dummy));
311:   PetscCall(MatSeqAIJRestoreArrayRead(aij->A, &dummy));
312:   PetscCall(MatSeqAIJGetArrayRead(aij->B, &dummy));
313:   PetscCall(MatSeqAIJRestoreArrayRead(aij->B, &dummy));
314:   if (type == NORM_2) {
315:     for (i = 0; i < a_aij->i[aij->A->rmap->n]; i++) work[A->cmap->rstart + a_aij->j[i]] += PetscAbsScalar(a_aij->a[i] * a_aij->a[i]);
316:     for (i = 0; i < b_aij->i[aij->B->rmap->n]; i++) work[garray[b_aij->j[i]]] += PetscAbsScalar(b_aij->a[i] * b_aij->a[i]);
317:   } else if (type == NORM_1) {
318:     for (i = 0; i < a_aij->i[aij->A->rmap->n]; i++) work[A->cmap->rstart + a_aij->j[i]] += PetscAbsScalar(a_aij->a[i]);
319:     for (i = 0; i < b_aij->i[aij->B->rmap->n]; i++) work[garray[b_aij->j[i]]] += PetscAbsScalar(b_aij->a[i]);
320:   } else if (type == NORM_INFINITY) {
321:     for (i = 0; i < a_aij->i[aij->A->rmap->n]; i++) work[A->cmap->rstart + a_aij->j[i]] = PetscMax(PetscAbsScalar(a_aij->a[i]), work[A->cmap->rstart + a_aij->j[i]]);
322:     for (i = 0; i < b_aij->i[aij->B->rmap->n]; i++) work[garray[b_aij->j[i]]] = PetscMax(PetscAbsScalar(b_aij->a[i]), work[garray[b_aij->j[i]]]);
323:   } else if (type == REDUCTION_SUM_REALPART || type == REDUCTION_MEAN_REALPART) {
324:     for (i = 0; i < a_aij->i[aij->A->rmap->n]; i++) work[A->cmap->rstart + a_aij->j[i]] += PetscRealPart(a_aij->a[i]);
325:     for (i = 0; i < b_aij->i[aij->B->rmap->n]; i++) work[garray[b_aij->j[i]]] += PetscRealPart(b_aij->a[i]);
326:   } else if (type == REDUCTION_SUM_IMAGINARYPART || type == REDUCTION_MEAN_IMAGINARYPART) {
327:     for (i = 0; i < a_aij->i[aij->A->rmap->n]; i++) work[A->cmap->rstart + a_aij->j[i]] += PetscImaginaryPart(a_aij->a[i]);
328:     for (i = 0; i < b_aij->i[aij->B->rmap->n]; i++) work[garray[b_aij->j[i]]] += PetscImaginaryPart(b_aij->a[i]);
329:   } else SETERRQ(PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_WRONG, "Unknown reduction type");
330:   if (type == NORM_INFINITY) {
331:     PetscCallMPI(MPIU_Allreduce(work, reductions, n, MPIU_REAL, MPIU_MAX, PetscObjectComm((PetscObject)A)));
332:   } else {
333:     PetscCallMPI(MPIU_Allreduce(work, reductions, n, MPIU_REAL, MPIU_SUM, PetscObjectComm((PetscObject)A)));
334:   }
335:   PetscCall(PetscFree(work));
336:   if (type == NORM_2) {
337:     for (i = 0; i < n; i++) reductions[i] = PetscSqrtReal(reductions[i]);
338:   } else if (type == REDUCTION_MEAN_REALPART || type == REDUCTION_MEAN_IMAGINARYPART) {
339:     for (i = 0; i < n; i++) reductions[i] /= m;
340:   }
341:   PetscFunctionReturn(PETSC_SUCCESS);
342: }

344: static PetscErrorCode MatFindOffBlockDiagonalEntries_MPIAIJ(Mat A, IS *is)
345: {
346:   Mat_MPIAIJ     *a = (Mat_MPIAIJ *)A->data;
347:   IS              sis, gis;
348:   const PetscInt *isis, *igis;
349:   PetscInt        n, *iis, nsis, ngis, rstart, i;

351:   PetscFunctionBegin;
352:   PetscCall(MatFindOffBlockDiagonalEntries(a->A, &sis));
353:   PetscCall(MatFindNonzeroRows(a->B, &gis));
354:   PetscCall(ISGetSize(gis, &ngis));
355:   PetscCall(ISGetSize(sis, &nsis));
356:   PetscCall(ISGetIndices(sis, &isis));
357:   PetscCall(ISGetIndices(gis, &igis));

359:   PetscCall(PetscMalloc1(ngis + nsis, &iis));
360:   PetscCall(PetscArraycpy(iis, igis, ngis));
361:   PetscCall(PetscArraycpy(iis + ngis, isis, nsis));
362:   n = ngis + nsis;
363:   PetscCall(PetscSortRemoveDupsInt(&n, iis));
364:   PetscCall(MatGetOwnershipRange(A, &rstart, NULL));
365:   for (i = 0; i < n; i++) iis[i] += rstart;
366:   PetscCall(ISCreateGeneral(PetscObjectComm((PetscObject)A), n, iis, PETSC_OWN_POINTER, is));

368:   PetscCall(ISRestoreIndices(sis, &isis));
369:   PetscCall(ISRestoreIndices(gis, &igis));
370:   PetscCall(ISDestroy(&sis));
371:   PetscCall(ISDestroy(&gis));
372:   PetscFunctionReturn(PETSC_SUCCESS);
373: }

375: /*
376:   Local utility routine that creates a mapping from the global column
377: number to the local number in the off-diagonal part of the local
378: storage of the matrix.  When PETSC_USE_CTABLE is used this is scalable at
379: a slightly higher hash table cost; without it it is not scalable (each processor
380: has an order N integer array but is fast to access.
381: */
382: PetscErrorCode MatCreateColmap_MPIAIJ_Private(Mat mat)
383: {
384:   Mat_MPIAIJ *aij = (Mat_MPIAIJ *)mat->data;
385:   PetscInt    n   = aij->B->cmap->n, i;

387:   PetscFunctionBegin;
388:   PetscCheck(!n || aij->garray, PETSC_COMM_SELF, PETSC_ERR_PLIB, "MPIAIJ Matrix was assembled but is missing garray");
389: #if defined(PETSC_USE_CTABLE)
390:   PetscCall(PetscHMapICreateWithSize(n, &aij->colmap));
391:   for (i = 0; i < n; i++) PetscCall(PetscHMapISet(aij->colmap, aij->garray[i] + 1, i + 1));
392: #else
393:   PetscCall(PetscCalloc1(mat->cmap->N + 1, &aij->colmap));
394:   for (i = 0; i < n; i++) aij->colmap[aij->garray[i]] = i + 1;
395: #endif
396:   PetscFunctionReturn(PETSC_SUCCESS);
397: }

399: #define MatSetValues_SeqAIJ_A_Private(row, col, value, addv, orow, ocol) \
400:   do { \
401:     if (col <= lastcol1) low1 = 0; \
402:     else high1 = nrow1; \
403:     lastcol1 = col; \
404:     while (high1 - low1 > 5) { \
405:       t = (low1 + high1) / 2; \
406:       if (rp1[t] > col) high1 = t; \
407:       else low1 = t; \
408:     } \
409:     for (_i = low1; _i < high1; _i++) { \
410:       if (rp1[_i] > col) break; \
411:       if (rp1[_i] == col) { \
412:         if (addv == ADD_VALUES) { \
413:           ap1[_i] += value; \
414:           /* Not sure LogFlops will slow down the code or not */ \
415:           (void)PetscLogFlops(1.0); \
416:         } else ap1[_i] = value; \
417:         goto a_noinsert; \
418:       } \
419:     } \
420:     if (value == 0.0 && ignorezeroentries && row != col) { \
421:       low1  = 0; \
422:       high1 = nrow1; \
423:       goto a_noinsert; \
424:     } \
425:     if (nonew == 1) { \
426:       low1  = 0; \
427:       high1 = nrow1; \
428:       goto a_noinsert; \
429:     } \
430:     PetscCheck(nonew != -1, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Inserting a new nonzero at global row/column (%" PetscInt_FMT ", %" PetscInt_FMT ") into matrix", orow, ocol); \
431:     MatSeqXAIJReallocateAIJ(A, am, 1, nrow1, row, col, rmax1, aa, ai, aj, rp1, ap1, aimax, nonew, MatScalar); \
432:     N = nrow1++ - 1; \
433:     a->nz++; \
434:     high1++; \
435:     /* shift up all the later entries in this row */ \
436:     PetscCall(PetscArraymove(rp1 + _i + 1, rp1 + _i, N - _i + 1)); \
437:     PetscCall(PetscArraymove(ap1 + _i + 1, ap1 + _i, N - _i + 1)); \
438:     rp1[_i] = col; \
439:     ap1[_i] = value; \
440:   a_noinsert:; \
441:     ailen[row] = nrow1; \
442:   } while (0)

444: #define MatSetValues_SeqAIJ_B_Private(row, col, value, addv, orow, ocol) \
445:   do { \
446:     if (col <= lastcol2) low2 = 0; \
447:     else high2 = nrow2; \
448:     lastcol2 = col; \
449:     while (high2 - low2 > 5) { \
450:       t = (low2 + high2) / 2; \
451:       if (rp2[t] > col) high2 = t; \
452:       else low2 = t; \
453:     } \
454:     for (_i = low2; _i < high2; _i++) { \
455:       if (rp2[_i] > col) break; \
456:       if (rp2[_i] == col) { \
457:         if (addv == ADD_VALUES) { \
458:           ap2[_i] += value; \
459:           (void)PetscLogFlops(1.0); \
460:         } else ap2[_i] = value; \
461:         goto b_noinsert; \
462:       } \
463:     } \
464:     if (value == 0.0 && ignorezeroentries) { \
465:       low2  = 0; \
466:       high2 = nrow2; \
467:       goto b_noinsert; \
468:     } \
469:     if (nonew == 1) { \
470:       low2  = 0; \
471:       high2 = nrow2; \
472:       goto b_noinsert; \
473:     } \
474:     PetscCheck(nonew != -1, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Inserting a new nonzero at global row/column (%" PetscInt_FMT ", %" PetscInt_FMT ") into matrix", orow, ocol); \
475:     MatSeqXAIJReallocateAIJ(B, bm, 1, nrow2, row, col, rmax2, ba, bi, bj, rp2, ap2, bimax, nonew, MatScalar); \
476:     N = nrow2++ - 1; \
477:     b->nz++; \
478:     high2++; \
479:     /* shift up all the later entries in this row */ \
480:     PetscCall(PetscArraymove(rp2 + _i + 1, rp2 + _i, N - _i + 1)); \
481:     PetscCall(PetscArraymove(ap2 + _i + 1, ap2 + _i, N - _i + 1)); \
482:     rp2[_i] = col; \
483:     ap2[_i] = value; \
484:   b_noinsert:; \
485:     bilen[row] = nrow2; \
486:   } while (0)

488: static PetscErrorCode MatSetValuesRow_MPIAIJ(Mat A, PetscInt row, const PetscScalar v[])
489: {
490:   Mat_MPIAIJ  *mat = (Mat_MPIAIJ *)A->data;
491:   Mat_SeqAIJ  *a = (Mat_SeqAIJ *)mat->A->data, *b = (Mat_SeqAIJ *)mat->B->data;
492:   PetscInt     l, *garray                         = mat->garray, diag;
493:   PetscScalar *aa, *ba;

495:   PetscFunctionBegin;
496:   /* code only works for square matrices A */

498:   /* find size of row to the left of the diagonal part */
499:   PetscCall(MatGetOwnershipRange(A, &diag, NULL));
500:   row = row - diag;
501:   for (l = 0; l < b->i[row + 1] - b->i[row]; l++) {
502:     if (garray[b->j[b->i[row] + l]] > diag) break;
503:   }
504:   if (l) {
505:     PetscCall(MatSeqAIJGetArray(mat->B, &ba));
506:     PetscCall(PetscArraycpy(ba + b->i[row], v, l));
507:     PetscCall(MatSeqAIJRestoreArray(mat->B, &ba));
508:   }

510:   /* diagonal part */
511:   if (a->i[row + 1] - a->i[row]) {
512:     PetscCall(MatSeqAIJGetArray(mat->A, &aa));
513:     PetscCall(PetscArraycpy(aa + a->i[row], v + l, a->i[row + 1] - a->i[row]));
514:     PetscCall(MatSeqAIJRestoreArray(mat->A, &aa));
515:   }

517:   /* right of diagonal part */
518:   if (b->i[row + 1] - b->i[row] - l) {
519:     PetscCall(MatSeqAIJGetArray(mat->B, &ba));
520:     PetscCall(PetscArraycpy(ba + b->i[row] + l, v + l + a->i[row + 1] - a->i[row], b->i[row + 1] - b->i[row] - l));
521:     PetscCall(MatSeqAIJRestoreArray(mat->B, &ba));
522:   }
523:   PetscFunctionReturn(PETSC_SUCCESS);
524: }

526: PetscErrorCode MatSetValues_MPIAIJ(Mat mat, PetscInt m, const PetscInt im[], PetscInt n, const PetscInt in[], const PetscScalar v[], InsertMode addv)
527: {
528:   Mat_MPIAIJ *aij   = (Mat_MPIAIJ *)mat->data;
529:   PetscScalar value = 0.0;
530:   PetscInt    i, j, rstart = mat->rmap->rstart, rend = mat->rmap->rend;
531:   PetscInt    cstart = mat->cmap->rstart, cend = mat->cmap->rend, row, col;
532:   PetscBool   roworiented = aij->roworiented;

534:   /* Some Variables required in the macro */
535:   Mat         A     = aij->A;
536:   Mat_SeqAIJ *a     = (Mat_SeqAIJ *)A->data;
537:   PetscInt   *aimax = a->imax, *ai = a->i, *ailen = a->ilen, *aj = a->j;
538:   PetscBool   ignorezeroentries = a->ignorezeroentries;
539:   Mat         B                 = aij->B;
540:   Mat_SeqAIJ *b                 = (Mat_SeqAIJ *)B->data;
541:   PetscInt   *bimax = b->imax, *bi = b->i, *bilen = b->ilen, *bj = b->j, bm = aij->B->rmap->n, am = aij->A->rmap->n;
542:   MatScalar  *aa, *ba;
543:   PetscInt   *rp1, *rp2, ii, nrow1, nrow2, _i, rmax1, rmax2, N, low1, high1, low2, high2, t, lastcol1, lastcol2;
544:   PetscInt    nonew;
545:   MatScalar  *ap1, *ap2;

547:   PetscFunctionBegin;
548:   PetscCall(MatSeqAIJGetArray(A, &aa));
549:   PetscCall(MatSeqAIJGetArray(B, &ba));
550:   for (i = 0; i < m; i++) {
551:     if (im[i] < 0) continue;
552:     PetscCheck(im[i] < mat->rmap->N, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Row too large: row %" PetscInt_FMT " max %" PetscInt_FMT, im[i], mat->rmap->N - 1);
553:     if (im[i] >= rstart && im[i] < rend) {
554:       row      = im[i] - rstart;
555:       lastcol1 = -1;
556:       rp1      = PetscSafePointerPlusOffset(aj, ai[row]);
557:       ap1      = PetscSafePointerPlusOffset(aa, ai[row]);
558:       rmax1    = aimax[row];
559:       nrow1    = ailen[row];
560:       low1     = 0;
561:       high1    = nrow1;
562:       lastcol2 = -1;
563:       rp2      = PetscSafePointerPlusOffset(bj, bi[row]);
564:       ap2      = PetscSafePointerPlusOffset(ba, bi[row]);
565:       rmax2    = bimax[row];
566:       nrow2    = bilen[row];
567:       low2     = 0;
568:       high2    = nrow2;

570:       for (j = 0; j < n; j++) {
571:         if (v) value = roworiented ? v[i * n + j] : v[i + j * m];
572:         if (ignorezeroentries && value == 0.0 && (addv == ADD_VALUES) && im[i] != in[j]) continue;
573:         if (in[j] >= cstart && in[j] < cend) {
574:           col   = in[j] - cstart;
575:           nonew = a->nonew;
576:           MatSetValues_SeqAIJ_A_Private(row, col, value, addv, im[i], in[j]);
577:         } else if (in[j] < 0) {
578:           continue;
579:         } else {
580:           PetscCheck(in[j] < mat->cmap->N, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Column too large: col %" PetscInt_FMT " max %" PetscInt_FMT, in[j], mat->cmap->N - 1);
581:           if (mat->was_assembled) {
582:             if (!aij->colmap) PetscCall(MatCreateColmap_MPIAIJ_Private(mat));
583: #if defined(PETSC_USE_CTABLE)
584:             PetscCall(PetscHMapIGetWithDefault(aij->colmap, in[j] + 1, 0, &col)); /* map global col ids to local ones */
585:             col--;
586: #else
587:             col = aij->colmap[in[j]] - 1;
588: #endif
589:             if (col < 0 && !((Mat_SeqAIJ *)aij->B->data)->nonew) { /* col < 0 means in[j] is a new col for B */
590:               PetscCall(MatDisAssemble_MPIAIJ(mat, PETSC_FALSE));  /* Change aij->B from reduced/local format to expanded/global format */
591:               col = in[j];
592:               /* Reinitialize the variables required by MatSetValues_SeqAIJ_B_Private() */
593:               B     = aij->B;
594:               b     = (Mat_SeqAIJ *)B->data;
595:               bimax = b->imax;
596:               bi    = b->i;
597:               bilen = b->ilen;
598:               bj    = b->j;
599:               ba    = b->a;
600:               rp2   = PetscSafePointerPlusOffset(bj, bi[row]);
601:               ap2   = PetscSafePointerPlusOffset(ba, bi[row]);
602:               rmax2 = bimax[row];
603:               nrow2 = bilen[row];
604:               low2  = 0;
605:               high2 = nrow2;
606:               bm    = aij->B->rmap->n;
607:               ba    = b->a;
608:             } else if (col < 0 && !(ignorezeroentries && value == 0.0)) {
609:               PetscCheck(1 == ((Mat_SeqAIJ *)aij->B->data)->nonew, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Inserting a new nonzero at global row/column (%" PetscInt_FMT ", %" PetscInt_FMT ") into matrix", im[i], in[j]);
610:               PetscCall(PetscInfo(mat, "Skipping of insertion of new nonzero location in off-diagonal portion of matrix %g(%" PetscInt_FMT ",%" PetscInt_FMT ")\n", (double)PetscRealPart(value), im[i], in[j]));
611:             }
612:           } else col = in[j];
613:           nonew = b->nonew;
614:           MatSetValues_SeqAIJ_B_Private(row, col, value, addv, im[i], in[j]);
615:         }
616:       }
617:     } else {
618:       PetscCheck(!mat->nooffprocentries, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Setting off process row %" PetscInt_FMT " even though MatSetOption(,MAT_NO_OFF_PROC_ENTRIES,PETSC_TRUE) was set", im[i]);
619:       if (!aij->donotstash) {
620:         mat->assembled = PETSC_FALSE;
621:         if (roworiented) {
622:           PetscCall(MatStashValuesRow_Private(&mat->stash, im[i], n, in, PetscSafePointerPlusOffset(v, i * n), (PetscBool)(ignorezeroentries && (addv == ADD_VALUES))));
623:         } else {
624:           PetscCall(MatStashValuesCol_Private(&mat->stash, im[i], n, in, PetscSafePointerPlusOffset(v, i), m, (PetscBool)(ignorezeroentries && (addv == ADD_VALUES))));
625:         }
626:       }
627:     }
628:   }
629:   PetscCall(MatSeqAIJRestoreArray(A, &aa)); /* aa, bb might have been free'd due to reallocation above. But we don't access them here */
630:   PetscCall(MatSeqAIJRestoreArray(B, &ba));
631:   PetscFunctionReturn(PETSC_SUCCESS);
632: }

634: /*
635:     This function sets the j and ilen arrays (of the diagonal and off-diagonal part) of an MPIAIJ-matrix.
636:     The values in mat_i have to be sorted and the values in mat_j have to be sorted for each row (CSR-like).
637:     No off-processor parts off the matrix are allowed here and mat->was_assembled has to be PETSC_FALSE.
638: */
639: PetscErrorCode MatSetValues_MPIAIJ_CopyFromCSRFormat_Symbolic(Mat mat, const PetscInt mat_j[], const PetscInt mat_i[])
640: {
641:   Mat_MPIAIJ *aij    = (Mat_MPIAIJ *)mat->data;
642:   Mat         A      = aij->A; /* diagonal part of the matrix */
643:   Mat         B      = aij->B; /* off-diagonal part of the matrix */
644:   Mat_SeqAIJ *a      = (Mat_SeqAIJ *)A->data;
645:   Mat_SeqAIJ *b      = (Mat_SeqAIJ *)B->data;
646:   PetscInt    cstart = mat->cmap->rstart, cend = mat->cmap->rend, col;
647:   PetscInt   *ailen = a->ilen, *aj = a->j;
648:   PetscInt   *bilen = b->ilen, *bj = b->j;
649:   PetscInt    am          = aij->A->rmap->n, j;
650:   PetscInt    diag_so_far = 0, dnz;
651:   PetscInt    offd_so_far = 0, onz;

653:   PetscFunctionBegin;
654:   /* Iterate over all rows of the matrix */
655:   for (j = 0; j < am; j++) {
656:     dnz = onz = 0;
657:     /*  Iterate over all non-zero columns of the current row */
658:     for (col = mat_i[j]; col < mat_i[j + 1]; col++) {
659:       /* If column is in the diagonal */
660:       if (mat_j[col] >= cstart && mat_j[col] < cend) {
661:         aj[diag_so_far++] = mat_j[col] - cstart;
662:         dnz++;
663:       } else { /* off-diagonal entries */
664:         bj[offd_so_far++] = mat_j[col];
665:         onz++;
666:       }
667:     }
668:     ailen[j] = dnz;
669:     bilen[j] = onz;
670:   }
671:   PetscFunctionReturn(PETSC_SUCCESS);
672: }

674: /*
675:     This function sets the local j, a and ilen arrays (of the diagonal and off-diagonal part) of an MPIAIJ-matrix.
676:     The values in mat_i have to be sorted and the values in mat_j have to be sorted for each row (CSR-like).
677:     No off-processor parts off the matrix are allowed here, they are set at a later point by MatSetValues_MPIAIJ.
678:     Also, mat->was_assembled has to be false, otherwise the statement aj[rowstart_diag+dnz_row] = mat_j[col] - cstart;
679:     would not be true and the more complex MatSetValues_MPIAIJ has to be used.
680: */
681: PetscErrorCode MatSetValues_MPIAIJ_CopyFromCSRFormat(Mat mat, const PetscInt mat_j[], const PetscInt mat_i[], const PetscScalar mat_a[])
682: {
683:   Mat_MPIAIJ  *aij  = (Mat_MPIAIJ *)mat->data;
684:   Mat          A    = aij->A; /* diagonal part of the matrix */
685:   Mat          B    = aij->B; /* off-diagonal part of the matrix */
686:   Mat_SeqAIJ  *aijd = (Mat_SeqAIJ *)aij->A->data, *aijo = (Mat_SeqAIJ *)aij->B->data;
687:   Mat_SeqAIJ  *a      = (Mat_SeqAIJ *)A->data;
688:   Mat_SeqAIJ  *b      = (Mat_SeqAIJ *)B->data;
689:   PetscInt     cstart = mat->cmap->rstart, cend = mat->cmap->rend;
690:   PetscInt    *ailen = a->ilen, *aj = a->j;
691:   PetscInt    *bilen = b->ilen, *bj = b->j;
692:   PetscInt     am          = aij->A->rmap->n, j;
693:   PetscInt    *full_diag_i = aijd->i, *full_offd_i = aijo->i; /* These variables can also include non-local elements, which are set at a later point. */
694:   PetscInt     col, dnz_row, onz_row, rowstart_diag, rowstart_offd;
695:   PetscScalar *aa = a->a, *ba = b->a;

697:   PetscFunctionBegin;
698:   /* Iterate over all rows of the matrix */
699:   for (j = 0; j < am; j++) {
700:     dnz_row = onz_row = 0;
701:     rowstart_offd     = full_offd_i[j];
702:     rowstart_diag     = full_diag_i[j];
703:     /*  Iterate over all non-zero columns of the current row */
704:     for (col = mat_i[j]; col < mat_i[j + 1]; col++) {
705:       /* If column is in the diagonal */
706:       if (mat_j[col] >= cstart && mat_j[col] < cend) {
707:         aj[rowstart_diag + dnz_row] = mat_j[col] - cstart;
708:         aa[rowstart_diag + dnz_row] = mat_a[col];
709:         dnz_row++;
710:       } else { /* off-diagonal entries */
711:         bj[rowstart_offd + onz_row] = mat_j[col];
712:         ba[rowstart_offd + onz_row] = mat_a[col];
713:         onz_row++;
714:       }
715:     }
716:     ailen[j] = dnz_row;
717:     bilen[j] = onz_row;
718:   }
719:   PetscFunctionReturn(PETSC_SUCCESS);
720: }

722: static PetscErrorCode MatGetValues_MPIAIJ(Mat mat, PetscInt m, const PetscInt idxm[], PetscInt n, const PetscInt idxn[], PetscScalar v[])
723: {
724:   Mat_MPIAIJ *aij = (Mat_MPIAIJ *)mat->data;
725:   PetscInt    i, j, rstart = mat->rmap->rstart, rend = mat->rmap->rend;
726:   PetscInt    cstart = mat->cmap->rstart, cend = mat->cmap->rend, row, col;

728:   PetscFunctionBegin;
729:   for (i = 0; i < m; i++) {
730:     if (idxm[i] < 0) continue; /* negative row */
731:     PetscCheck(idxm[i] < mat->rmap->N, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Row too large: row %" PetscInt_FMT " max %" PetscInt_FMT, idxm[i], mat->rmap->N - 1);
732:     PetscCheck(idxm[i] >= rstart && idxm[i] < rend, PETSC_COMM_SELF, PETSC_ERR_SUP, "Only local values currently supported, row requested %" PetscInt_FMT " range [%" PetscInt_FMT " %" PetscInt_FMT ")", idxm[i], rstart, rend);
733:     row = idxm[i] - rstart;
734:     for (j = 0; j < n; j++) {
735:       if (idxn[j] < 0) continue; /* negative column */
736:       PetscCheck(idxn[j] < mat->cmap->N, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Column too large: col %" PetscInt_FMT " max %" PetscInt_FMT, idxn[j], mat->cmap->N - 1);
737:       if (idxn[j] >= cstart && idxn[j] < cend) {
738:         col = idxn[j] - cstart;
739:         PetscCall(MatGetValues(aij->A, 1, &row, 1, &col, v + i * n + j));
740:       } else {
741:         if (!aij->colmap) PetscCall(MatCreateColmap_MPIAIJ_Private(mat));
742: #if defined(PETSC_USE_CTABLE)
743:         PetscCall(PetscHMapIGetWithDefault(aij->colmap, idxn[j] + 1, 0, &col));
744:         col--;
745: #else
746:         col = aij->colmap[idxn[j]] - 1;
747: #endif
748:         if ((col < 0) || (aij->garray[col] != idxn[j])) *(v + i * n + j) = 0.0;
749:         else PetscCall(MatGetValues(aij->B, 1, &row, 1, &col, v + i * n + j));
750:       }
751:     }
752:   }
753:   PetscFunctionReturn(PETSC_SUCCESS);
754: }

756: static PetscErrorCode MatAssemblyBegin_MPIAIJ(Mat mat, MatAssemblyType mode)
757: {
758:   Mat_MPIAIJ *aij = (Mat_MPIAIJ *)mat->data;
759:   PetscInt    nstash, reallocs;

761:   PetscFunctionBegin;
762:   if (aij->donotstash || mat->nooffprocentries) PetscFunctionReturn(PETSC_SUCCESS);

764:   PetscCall(MatStashScatterBegin_Private(mat, &mat->stash, mat->rmap->range));
765:   PetscCall(MatStashGetInfo_Private(&mat->stash, &nstash, &reallocs));
766:   PetscCall(PetscInfo(mat, "Stash has %" PetscInt_FMT " entries, uses %" PetscInt_FMT " mallocs.\n", nstash, reallocs));
767:   PetscFunctionReturn(PETSC_SUCCESS);
768: }

770: PetscErrorCode MatAssemblyEnd_MPIAIJ(Mat mat, MatAssemblyType mode)
771: {
772:   Mat_MPIAIJ  *aij = (Mat_MPIAIJ *)mat->data;
773:   PetscMPIInt  n;
774:   PetscInt     i, j, rstart, ncols, flg;
775:   PetscInt    *row, *col;
776:   PetscBool    all_assembled;
777:   PetscScalar *val;

779:   /* do not use 'b = (Mat_SeqAIJ*)aij->B->data' as B can be reset in disassembly */

781:   PetscFunctionBegin;
782:   if (!aij->donotstash && !mat->nooffprocentries) {
783:     while (1) {
784:       PetscCall(MatStashScatterGetMesg_Private(&mat->stash, &n, &row, &col, &val, &flg));
785:       if (!flg) break;

787:       for (i = 0; i < n;) {
788:         /* Now identify the consecutive vals belonging to the same row */
789:         for (j = i, rstart = row[j]; j < n; j++) {
790:           if (row[j] != rstart) break;
791:         }
792:         if (j < n) ncols = j - i;
793:         else ncols = n - i;
794:         /* Now assemble all these values with a single function call */
795:         PetscCall(MatSetValues_MPIAIJ(mat, 1, row + i, ncols, col + i, val + i, mat->insertmode));
796:         i = j;
797:       }
798:     }
799:     PetscCall(MatStashScatterEnd_Private(&mat->stash));
800:   }
801: #if defined(PETSC_HAVE_DEVICE)
802:   if (mat->offloadmask == PETSC_OFFLOAD_CPU) aij->A->offloadmask = PETSC_OFFLOAD_CPU;
803:   /* We call MatBindToCPU() on aij->A and aij->B here, because if MatBindToCPU_MPIAIJ() is called before assembly, it cannot bind these. */
804:   if (mat->boundtocpu) {
805:     PetscCall(MatBindToCPU(aij->A, PETSC_TRUE));
806:     PetscCall(MatBindToCPU(aij->B, PETSC_TRUE));
807:   }
808: #endif
809:   PetscCall(MatAssemblyBegin(aij->A, mode));
810:   PetscCall(MatAssemblyEnd(aij->A, mode));

812:   /* determine if any process has disassembled, if so we must
813:      also disassemble ourself, in order that we may reassemble. */
814:   /*
815:      if nonzero structure of submatrix B cannot change then we know that
816:      no process disassembled thus we can skip this stuff
817:   */
818:   if (!((Mat_SeqAIJ *)aij->B->data)->nonew) {
819:     PetscCallMPI(MPIU_Allreduce(&mat->was_assembled, &all_assembled, 1, MPI_C_BOOL, MPI_LAND, PetscObjectComm((PetscObject)mat)));
820:     if (mat->was_assembled && !all_assembled) { /* mat on this rank has reduced off-diag B with local col ids, but globally it does not */
821:       PetscCall(MatDisAssemble_MPIAIJ(mat, PETSC_FALSE));
822:     }
823:   }
824:   if (!mat->was_assembled && mode == MAT_FINAL_ASSEMBLY) PetscCall(MatSetUpMultiply_MPIAIJ(mat));
825:   PetscCall(MatSetOption(aij->B, MAT_USE_INODES, PETSC_FALSE));
826: #if defined(PETSC_HAVE_DEVICE)
827:   if (mat->offloadmask == PETSC_OFFLOAD_CPU && aij->B->offloadmask != PETSC_OFFLOAD_UNALLOCATED) aij->B->offloadmask = PETSC_OFFLOAD_CPU;
828: #endif
829:   PetscCall(MatAssemblyBegin(aij->B, mode));
830:   PetscCall(MatAssemblyEnd(aij->B, mode));

832:   PetscCall(PetscFree2(aij->rowvalues, aij->rowindices));

834:   aij->rowvalues = NULL;

836:   PetscCall(VecDestroy(&aij->diag));

838:   /* if no new nonzero locations are allowed in matrix then only set the matrix state the first time through */
839:   if ((!mat->was_assembled && mode == MAT_FINAL_ASSEMBLY) || !((Mat_SeqAIJ *)aij->A->data)->nonew) {
840:     PetscObjectState state = aij->A->nonzerostate + aij->B->nonzerostate;
841:     PetscCallMPI(MPIU_Allreduce(&state, &mat->nonzerostate, 1, MPIU_INT64, MPI_SUM, PetscObjectComm((PetscObject)mat)));
842:   }
843: #if defined(PETSC_HAVE_DEVICE)
844:   mat->offloadmask = PETSC_OFFLOAD_BOTH;
845: #endif
846:   PetscFunctionReturn(PETSC_SUCCESS);
847: }

849: static PetscErrorCode MatZeroEntries_MPIAIJ(Mat A)
850: {
851:   Mat_MPIAIJ *l = (Mat_MPIAIJ *)A->data;

853:   PetscFunctionBegin;
854:   PetscCall(MatZeroEntries(l->A));
855:   PetscCall(MatZeroEntries(l->B));
856:   PetscFunctionReturn(PETSC_SUCCESS);
857: }

859: static PetscErrorCode MatZeroRows_MPIAIJ(Mat A, PetscInt N, const PetscInt rows[], PetscScalar diag, Vec x, Vec b)
860: {
861:   Mat_MPIAIJ *mat = (Mat_MPIAIJ *)A->data;
862:   PetscInt   *lrows;
863:   PetscInt    r, len;
864:   PetscBool   cong;

866:   PetscFunctionBegin;
867:   /* get locally owned rows */
868:   PetscCall(MatZeroRowsMapLocal_Private(A, N, rows, &len, &lrows));
869:   PetscCall(MatHasCongruentLayouts(A, &cong));
870:   /* fix right-hand side if needed */
871:   if (x && b) {
872:     const PetscScalar *xx;
873:     PetscScalar       *bb;

875:     PetscCheck(cong, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "Need matching row/col layout");
876:     PetscCall(VecGetArrayRead(x, &xx));
877:     PetscCall(VecGetArray(b, &bb));
878:     for (r = 0; r < len; ++r) bb[lrows[r]] = diag * xx[lrows[r]];
879:     PetscCall(VecRestoreArrayRead(x, &xx));
880:     PetscCall(VecRestoreArray(b, &bb));
881:   }

883:   if (diag != 0.0 && cong) {
884:     PetscCall(MatZeroRows(mat->A, len, lrows, diag, NULL, NULL));
885:     PetscCall(MatZeroRows(mat->B, len, lrows, 0.0, NULL, NULL));
886:   } else if (diag != 0.0) { /* non-square or non congruent layouts -> if keepnonzeropattern is false, we allow for new insertion */
887:     Mat_SeqAIJ *aijA = (Mat_SeqAIJ *)mat->A->data;
888:     Mat_SeqAIJ *aijB = (Mat_SeqAIJ *)mat->B->data;
889:     PetscInt    nnwA, nnwB;
890:     PetscBool   nnzA, nnzB;

892:     nnwA = aijA->nonew;
893:     nnwB = aijB->nonew;
894:     nnzA = aijA->keepnonzeropattern;
895:     nnzB = aijB->keepnonzeropattern;
896:     if (!nnzA) {
897:       PetscCall(PetscInfo(mat->A, "Requested to not keep the pattern and add a nonzero diagonal; may encounter reallocations on diagonal block.\n"));
898:       aijA->nonew = 0;
899:     }
900:     if (!nnzB) {
901:       PetscCall(PetscInfo(mat->B, "Requested to not keep the pattern and add a nonzero diagonal; may encounter reallocations on off-diagonal block.\n"));
902:       aijB->nonew = 0;
903:     }
904:     /* Must zero here before the next loop */
905:     PetscCall(MatZeroRows(mat->A, len, lrows, 0.0, NULL, NULL));
906:     PetscCall(MatZeroRows(mat->B, len, lrows, 0.0, NULL, NULL));
907:     for (r = 0; r < len; ++r) {
908:       const PetscInt row = lrows[r] + A->rmap->rstart;
909:       if (row >= A->cmap->N) continue;
910:       PetscCall(MatSetValues(A, 1, &row, 1, &row, &diag, INSERT_VALUES));
911:     }
912:     aijA->nonew = nnwA;
913:     aijB->nonew = nnwB;
914:   } else {
915:     PetscCall(MatZeroRows(mat->A, len, lrows, 0.0, NULL, NULL));
916:     PetscCall(MatZeroRows(mat->B, len, lrows, 0.0, NULL, NULL));
917:   }
918:   PetscCall(PetscFree(lrows));
919:   PetscCall(MatAssemblyBegin(A, MAT_FINAL_ASSEMBLY));
920:   PetscCall(MatAssemblyEnd(A, MAT_FINAL_ASSEMBLY));

922:   /* only change matrix nonzero state if pattern was allowed to be changed */
923:   if (!((Mat_SeqAIJ *)mat->A->data)->keepnonzeropattern || !((Mat_SeqAIJ *)mat->A->data)->nonew) {
924:     PetscObjectState state = mat->A->nonzerostate + mat->B->nonzerostate;
925:     PetscCallMPI(MPIU_Allreduce(&state, &A->nonzerostate, 1, MPIU_INT64, MPI_SUM, PetscObjectComm((PetscObject)A)));
926:   }
927:   PetscFunctionReturn(PETSC_SUCCESS);
928: }

930: static PetscErrorCode MatZeroRowsColumns_MPIAIJ(Mat A, PetscInt N, const PetscInt rows[], PetscScalar diag, Vec x, Vec b)
931: {
932:   Mat_MPIAIJ        *l = (Mat_MPIAIJ *)A->data;
933:   PetscInt           n = A->rmap->n;
934:   PetscInt           i, j, r, m, len = 0;
935:   PetscInt          *lrows, *owners = A->rmap->range;
936:   PetscMPIInt        p = 0;
937:   PetscSFNode       *rrows;
938:   PetscSF            sf;
939:   const PetscScalar *xx;
940:   PetscScalar       *bb, *mask, *aij_a;
941:   Vec                xmask, lmask;
942:   Mat_SeqAIJ        *aij = (Mat_SeqAIJ *)l->B->data;
943:   const PetscInt    *aj, *ii, *ridx;
944:   PetscScalar       *aa;

946:   PetscFunctionBegin;
947:   /* Create SF where leaves are input rows and roots are owned rows */
948:   PetscCall(PetscMalloc1(n, &lrows));
949:   for (r = 0; r < n; ++r) lrows[r] = -1;
950:   PetscCall(PetscMalloc1(N, &rrows));
951:   for (r = 0; r < N; ++r) {
952:     const PetscInt idx = rows[r];
953:     PetscCheck(idx >= 0 && A->rmap->N > idx, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Row %" PetscInt_FMT " out of range [0,%" PetscInt_FMT ")", idx, A->rmap->N);
954:     if (idx < owners[p] || owners[p + 1] <= idx) { /* short-circuit the search if the last p owns this row too */
955:       PetscCall(PetscLayoutFindOwner(A->rmap, idx, &p));
956:     }
957:     rrows[r].rank  = p;
958:     rrows[r].index = rows[r] - owners[p];
959:   }
960:   PetscCall(PetscSFCreate(PetscObjectComm((PetscObject)A), &sf));
961:   PetscCall(PetscSFSetGraph(sf, n, N, NULL, PETSC_OWN_POINTER, rrows, PETSC_OWN_POINTER));
962:   /* Collect flags for rows to be zeroed */
963:   PetscCall(PetscSFReduceBegin(sf, MPIU_INT, (PetscInt *)rows, lrows, MPI_LOR));
964:   PetscCall(PetscSFReduceEnd(sf, MPIU_INT, (PetscInt *)rows, lrows, MPI_LOR));
965:   PetscCall(PetscSFDestroy(&sf));
966:   /* Compress and put in row numbers */
967:   for (r = 0; r < n; ++r)
968:     if (lrows[r] >= 0) lrows[len++] = r;
969:   /* zero diagonal part of matrix */
970:   PetscCall(MatZeroRowsColumns(l->A, len, lrows, diag, x, b));
971:   /* handle off-diagonal part of matrix */
972:   PetscCall(MatCreateVecs(A, &xmask, NULL));
973:   PetscCall(VecDuplicate(l->lvec, &lmask));
974:   PetscCall(VecGetArray(xmask, &bb));
975:   for (i = 0; i < len; i++) bb[lrows[i]] = 1;
976:   PetscCall(VecRestoreArray(xmask, &bb));
977:   PetscCall(VecScatterBegin(l->Mvctx, xmask, lmask, ADD_VALUES, SCATTER_FORWARD));
978:   PetscCall(VecScatterEnd(l->Mvctx, xmask, lmask, ADD_VALUES, SCATTER_FORWARD));
979:   PetscCall(VecDestroy(&xmask));
980:   if (x && b) { /* this code is buggy when the row and column layout don't match */
981:     PetscBool cong;

983:     PetscCall(MatHasCongruentLayouts(A, &cong));
984:     PetscCheck(cong, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "Need matching row/col layout");
985:     PetscCall(VecScatterBegin(l->Mvctx, x, l->lvec, INSERT_VALUES, SCATTER_FORWARD));
986:     PetscCall(VecScatterEnd(l->Mvctx, x, l->lvec, INSERT_VALUES, SCATTER_FORWARD));
987:     PetscCall(VecGetArrayRead(l->lvec, &xx));
988:     PetscCall(VecGetArray(b, &bb));
989:   }
990:   PetscCall(VecGetArray(lmask, &mask));
991:   /* remove zeroed rows of off-diagonal matrix */
992:   PetscCall(MatSeqAIJGetArray(l->B, &aij_a));
993:   ii = aij->i;
994:   for (i = 0; i < len; i++) PetscCall(PetscArrayzero(PetscSafePointerPlusOffset(aij_a, ii[lrows[i]]), ii[lrows[i] + 1] - ii[lrows[i]]));
995:   /* loop over all elements of off process part of matrix zeroing removed columns*/
996:   if (aij->compressedrow.use) {
997:     m    = aij->compressedrow.nrows;
998:     ii   = aij->compressedrow.i;
999:     ridx = aij->compressedrow.rindex;
1000:     for (i = 0; i < m; i++) {
1001:       n  = ii[i + 1] - ii[i];
1002:       aj = aij->j + ii[i];
1003:       aa = aij_a + ii[i];

1005:       for (j = 0; j < n; j++) {
1006:         if (PetscAbsScalar(mask[*aj])) {
1007:           if (b) bb[*ridx] -= *aa * xx[*aj];
1008:           *aa = 0.0;
1009:         }
1010:         aa++;
1011:         aj++;
1012:       }
1013:       ridx++;
1014:     }
1015:   } else { /* do not use compressed row format */
1016:     m = l->B->rmap->n;
1017:     for (i = 0; i < m; i++) {
1018:       n  = ii[i + 1] - ii[i];
1019:       aj = aij->j + ii[i];
1020:       aa = aij_a + ii[i];
1021:       for (j = 0; j < n; j++) {
1022:         if (PetscAbsScalar(mask[*aj])) {
1023:           if (b) bb[i] -= *aa * xx[*aj];
1024:           *aa = 0.0;
1025:         }
1026:         aa++;
1027:         aj++;
1028:       }
1029:     }
1030:   }
1031:   if (x && b) {
1032:     PetscCall(VecRestoreArray(b, &bb));
1033:     PetscCall(VecRestoreArrayRead(l->lvec, &xx));
1034:   }
1035:   PetscCall(MatSeqAIJRestoreArray(l->B, &aij_a));
1036:   PetscCall(VecRestoreArray(lmask, &mask));
1037:   PetscCall(VecDestroy(&lmask));
1038:   PetscCall(PetscFree(lrows));

1040:   /* only change matrix nonzero state if pattern was allowed to be changed */
1041:   if (!((Mat_SeqAIJ *)l->A->data)->nonew) {
1042:     PetscObjectState state = l->A->nonzerostate + l->B->nonzerostate;
1043:     PetscCallMPI(MPIU_Allreduce(&state, &A->nonzerostate, 1, MPIU_INT64, MPI_SUM, PetscObjectComm((PetscObject)A)));
1044:   }
1045:   PetscFunctionReturn(PETSC_SUCCESS);
1046: }

1048: static PetscErrorCode MatMult_MPIAIJ(Mat A, Vec xx, Vec yy)
1049: {
1050:   Mat_MPIAIJ *a = (Mat_MPIAIJ *)A->data;
1051:   PetscInt    nt;
1052:   VecScatter  Mvctx = a->Mvctx;

1054:   PetscFunctionBegin;
1055:   PetscCall(VecGetLocalSize(xx, &nt));
1056:   PetscCheck(nt == A->cmap->n, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Incompatible partition of A (%" PetscInt_FMT ") and xx (%" PetscInt_FMT ")", A->cmap->n, nt);
1057:   PetscCall(VecScatterBegin(Mvctx, xx, a->lvec, INSERT_VALUES, SCATTER_FORWARD));
1058:   PetscUseTypeMethod(a->A, mult, xx, yy);
1059:   PetscCall(VecScatterEnd(Mvctx, xx, a->lvec, INSERT_VALUES, SCATTER_FORWARD));
1060:   PetscUseTypeMethod(a->B, multadd, a->lvec, yy, yy);
1061:   PetscFunctionReturn(PETSC_SUCCESS);
1062: }

1064: static PetscErrorCode MatMultDiagonalBlock_MPIAIJ(Mat A, Vec bb, Vec xx)
1065: {
1066:   Mat_MPIAIJ *a = (Mat_MPIAIJ *)A->data;

1068:   PetscFunctionBegin;
1069:   PetscCall(MatMultDiagonalBlock(a->A, bb, xx));
1070:   PetscFunctionReturn(PETSC_SUCCESS);
1071: }

1073: static PetscErrorCode MatMultAdd_MPIAIJ(Mat A, Vec xx, Vec yy, Vec zz)
1074: {
1075:   Mat_MPIAIJ *a     = (Mat_MPIAIJ *)A->data;
1076:   VecScatter  Mvctx = a->Mvctx;

1078:   PetscFunctionBegin;
1079:   PetscCall(VecScatterBegin(Mvctx, xx, a->lvec, INSERT_VALUES, SCATTER_FORWARD));
1080:   PetscUseTypeMethod(a->A, multadd, xx, yy, zz);
1081:   PetscCall(VecScatterEnd(Mvctx, xx, a->lvec, INSERT_VALUES, SCATTER_FORWARD));
1082:   PetscUseTypeMethod(a->B, multadd, a->lvec, zz, zz);
1083:   PetscFunctionReturn(PETSC_SUCCESS);
1084: }

1086: static PetscErrorCode MatMultTranspose_MPIAIJ(Mat A, Vec xx, Vec yy)
1087: {
1088:   Mat_MPIAIJ *a = (Mat_MPIAIJ *)A->data;

1090:   PetscFunctionBegin;
1091:   /* do nondiagonal part */
1092:   PetscUseTypeMethod(a->B, multtranspose, xx, a->lvec);
1093:   /* do local part */
1094:   PetscUseTypeMethod(a->A, multtranspose, xx, yy);
1095:   /* add partial results together */
1096:   PetscCall(VecScatterBegin(a->Mvctx, a->lvec, yy, ADD_VALUES, SCATTER_REVERSE));
1097:   PetscCall(VecScatterEnd(a->Mvctx, a->lvec, yy, ADD_VALUES, SCATTER_REVERSE));
1098:   PetscFunctionReturn(PETSC_SUCCESS);
1099: }

1101: static PetscErrorCode MatIsTranspose_MPIAIJ(Mat Amat, Mat Bmat, PetscReal tol, PetscBool *f)
1102: {
1103:   MPI_Comm    comm;
1104:   Mat_MPIAIJ *Aij = (Mat_MPIAIJ *)Amat->data, *Bij = (Mat_MPIAIJ *)Bmat->data;
1105:   Mat         Adia = Aij->A, Bdia = Bij->A, Aoff, Boff, *Aoffs, *Boffs;
1106:   IS          Me, Notme;
1107:   PetscInt    M, N, first, last, *notme, i;
1108:   PetscBool   lf;
1109:   PetscMPIInt size;

1111:   PetscFunctionBegin;
1112:   /* Easy test: symmetric diagonal block */
1113:   PetscCall(MatIsTranspose(Adia, Bdia, tol, &lf));
1114:   PetscCallMPI(MPIU_Allreduce(&lf, f, 1, MPI_C_BOOL, MPI_LAND, PetscObjectComm((PetscObject)Amat)));
1115:   if (!*f) PetscFunctionReturn(PETSC_SUCCESS);
1116:   PetscCall(PetscObjectGetComm((PetscObject)Amat, &comm));
1117:   PetscCallMPI(MPI_Comm_size(comm, &size));
1118:   if (size == 1) PetscFunctionReturn(PETSC_SUCCESS);

1120:   /* Hard test: off-diagonal block. This takes a MatCreateSubMatrix. */
1121:   PetscCall(MatGetSize(Amat, &M, &N));
1122:   PetscCall(MatGetOwnershipRange(Amat, &first, &last));
1123:   PetscCall(PetscMalloc1(N - last + first, &notme));
1124:   for (i = 0; i < first; i++) notme[i] = i;
1125:   for (i = last; i < M; i++) notme[i - last + first] = i;
1126:   PetscCall(ISCreateGeneral(MPI_COMM_SELF, N - last + first, notme, PETSC_COPY_VALUES, &Notme));
1127:   PetscCall(ISCreateStride(MPI_COMM_SELF, last - first, first, 1, &Me));
1128:   PetscCall(MatCreateSubMatrices(Amat, 1, &Me, &Notme, MAT_INITIAL_MATRIX, &Aoffs));
1129:   Aoff = Aoffs[0];
1130:   PetscCall(MatCreateSubMatrices(Bmat, 1, &Notme, &Me, MAT_INITIAL_MATRIX, &Boffs));
1131:   Boff = Boffs[0];
1132:   PetscCall(MatIsTranspose(Aoff, Boff, tol, f));
1133:   PetscCall(MatDestroyMatrices(1, &Aoffs));
1134:   PetscCall(MatDestroyMatrices(1, &Boffs));
1135:   PetscCall(ISDestroy(&Me));
1136:   PetscCall(ISDestroy(&Notme));
1137:   PetscCall(PetscFree(notme));
1138:   PetscFunctionReturn(PETSC_SUCCESS);
1139: }

1141: static PetscErrorCode MatMultTransposeAdd_MPIAIJ(Mat A, Vec xx, Vec yy, Vec zz)
1142: {
1143:   Mat_MPIAIJ *a = (Mat_MPIAIJ *)A->data;

1145:   PetscFunctionBegin;
1146:   /* do nondiagonal part */
1147:   PetscUseTypeMethod(a->B, multtranspose, xx, a->lvec);
1148:   /* do local part */
1149:   PetscUseTypeMethod(a->A, multtransposeadd, xx, yy, zz);
1150:   /* add partial results together */
1151:   PetscCall(VecScatterBegin(a->Mvctx, a->lvec, zz, ADD_VALUES, SCATTER_REVERSE));
1152:   PetscCall(VecScatterEnd(a->Mvctx, a->lvec, zz, ADD_VALUES, SCATTER_REVERSE));
1153:   PetscFunctionReturn(PETSC_SUCCESS);
1154: }

1156: /*
1157:   This only works correctly for square matrices where the subblock A->A is the
1158:    diagonal block
1159: */
1160: static PetscErrorCode MatGetDiagonal_MPIAIJ(Mat A, Vec v)
1161: {
1162:   Mat_MPIAIJ *a = (Mat_MPIAIJ *)A->data;

1164:   PetscFunctionBegin;
1165:   PetscCheck(A->rmap->N == A->cmap->N, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "Supports only square matrix where A->A is diag block");
1166:   PetscCheck(A->rmap->rstart == A->cmap->rstart && A->rmap->rend == A->cmap->rend, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "row partition must equal col partition");
1167:   PetscCall(MatGetDiagonal(a->A, v));
1168:   PetscFunctionReturn(PETSC_SUCCESS);
1169: }

1171: static PetscErrorCode MatScale_MPIAIJ(Mat A, PetscScalar aa)
1172: {
1173:   Mat_MPIAIJ *a = (Mat_MPIAIJ *)A->data;

1175:   PetscFunctionBegin;
1176:   PetscCall(MatScale(a->A, aa));
1177:   PetscCall(MatScale(a->B, aa));
1178:   PetscFunctionReturn(PETSC_SUCCESS);
1179: }

1181: static PetscErrorCode MatView_MPIAIJ_Binary(Mat mat, PetscViewer viewer)
1182: {
1183:   Mat_MPIAIJ        *aij    = (Mat_MPIAIJ *)mat->data;
1184:   Mat_SeqAIJ        *A      = (Mat_SeqAIJ *)aij->A->data;
1185:   Mat_SeqAIJ        *B      = (Mat_SeqAIJ *)aij->B->data;
1186:   const PetscInt    *garray = aij->garray;
1187:   const PetscScalar *aa, *ba;
1188:   PetscInt           header[4], M, N, m, rs, cs, cnt, i, ja, jb;
1189:   PetscInt64         nz, hnz;
1190:   PetscInt          *rowlens;
1191:   PetscInt          *colidxs;
1192:   PetscScalar       *matvals;
1193:   PetscMPIInt        rank;

1195:   PetscFunctionBegin;
1196:   PetscCall(PetscViewerSetUp(viewer));

1198:   M  = mat->rmap->N;
1199:   N  = mat->cmap->N;
1200:   m  = mat->rmap->n;
1201:   rs = mat->rmap->rstart;
1202:   cs = mat->cmap->rstart;
1203:   nz = A->nz + B->nz;

1205:   /* write matrix header */
1206:   header[0] = MAT_FILE_CLASSID;
1207:   header[1] = M;
1208:   header[2] = N;
1209:   PetscCallMPI(MPI_Reduce(&nz, &hnz, 1, MPIU_INT64, MPI_SUM, 0, PetscObjectComm((PetscObject)mat)));
1210:   PetscCallMPI(MPI_Comm_rank(PetscObjectComm((PetscObject)mat), &rank));
1211:   if (rank == 0) PetscCall(PetscIntCast(hnz, &header[3]));
1212:   PetscCall(PetscViewerBinaryWrite(viewer, header, 4, PETSC_INT));

1214:   /* fill in and store row lengths  */
1215:   PetscCall(PetscMalloc1(m, &rowlens));
1216:   for (i = 0; i < m; i++) rowlens[i] = A->i[i + 1] - A->i[i] + B->i[i + 1] - B->i[i];
1217:   PetscCall(PetscViewerBinaryWriteAll(viewer, rowlens, m, rs, M, PETSC_INT));
1218:   PetscCall(PetscFree(rowlens));

1220:   /* fill in and store column indices */
1221:   PetscCall(PetscMalloc1(nz, &colidxs));
1222:   for (cnt = 0, i = 0; i < m; i++) {
1223:     for (jb = B->i[i]; jb < B->i[i + 1]; jb++) {
1224:       if (garray[B->j[jb]] > cs) break;
1225:       colidxs[cnt++] = garray[B->j[jb]];
1226:     }
1227:     for (ja = A->i[i]; ja < A->i[i + 1]; ja++) colidxs[cnt++] = A->j[ja] + cs;
1228:     for (; jb < B->i[i + 1]; jb++) colidxs[cnt++] = garray[B->j[jb]];
1229:   }
1230:   PetscCheck(cnt == nz, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Internal PETSc error: cnt = %" PetscInt_FMT " nz = %" PetscInt64_FMT, cnt, nz);
1231:   PetscCall(PetscViewerBinaryWriteAll(viewer, colidxs, nz, PETSC_DETERMINE, PETSC_DETERMINE, PETSC_INT));
1232:   PetscCall(PetscFree(colidxs));

1234:   /* fill in and store nonzero values */
1235:   PetscCall(MatSeqAIJGetArrayRead(aij->A, &aa));
1236:   PetscCall(MatSeqAIJGetArrayRead(aij->B, &ba));
1237:   PetscCall(PetscMalloc1(nz, &matvals));
1238:   for (cnt = 0, i = 0; i < m; i++) {
1239:     for (jb = B->i[i]; jb < B->i[i + 1]; jb++) {
1240:       if (garray[B->j[jb]] > cs) break;
1241:       matvals[cnt++] = ba[jb];
1242:     }
1243:     for (ja = A->i[i]; ja < A->i[i + 1]; ja++) matvals[cnt++] = aa[ja];
1244:     for (; jb < B->i[i + 1]; jb++) matvals[cnt++] = ba[jb];
1245:   }
1246:   PetscCall(MatSeqAIJRestoreArrayRead(aij->A, &aa));
1247:   PetscCall(MatSeqAIJRestoreArrayRead(aij->B, &ba));
1248:   PetscCheck(cnt == nz, PETSC_COMM_SELF, PETSC_ERR_LIB, "Internal PETSc error: cnt = %" PetscInt_FMT " nz = %" PetscInt64_FMT, cnt, nz);
1249:   PetscCall(PetscViewerBinaryWriteAll(viewer, matvals, nz, PETSC_DETERMINE, PETSC_DETERMINE, PETSC_SCALAR));
1250:   PetscCall(PetscFree(matvals));

1252:   /* write block size option to the viewer's .info file */
1253:   PetscCall(MatView_Binary_BlockSizes(mat, viewer));
1254:   PetscFunctionReturn(PETSC_SUCCESS);
1255: }

1257: #include <petscdraw.h>
1258: static PetscErrorCode MatView_MPIAIJ_ASCIIorDraworSocket(Mat mat, PetscViewer viewer)
1259: {
1260:   Mat_MPIAIJ       *aij  = (Mat_MPIAIJ *)mat->data;
1261:   PetscMPIInt       rank = aij->rank, size = aij->size;
1262:   PetscBool         isdraw, isascii, isbinary;
1263:   PetscViewer       sviewer;
1264:   PetscViewerFormat format;

1266:   PetscFunctionBegin;
1267:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERDRAW, &isdraw));
1268:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERASCII, &isascii));
1269:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERBINARY, &isbinary));
1270:   if (isascii) {
1271:     PetscCall(PetscViewerGetFormat(viewer, &format));
1272:     if (format == PETSC_VIEWER_LOAD_BALANCE) {
1273:       PetscInt i, nmax = 0, nmin = PETSC_INT_MAX, navg = 0, *nz, nzlocal = ((Mat_SeqAIJ *)aij->A->data)->nz + ((Mat_SeqAIJ *)aij->B->data)->nz;
1274:       PetscCall(PetscMalloc1(size, &nz));
1275:       PetscCallMPI(MPI_Allgather(&nzlocal, 1, MPIU_INT, nz, 1, MPIU_INT, PetscObjectComm((PetscObject)mat)));
1276:       for (i = 0; i < size; i++) {
1277:         nmax = PetscMax(nmax, nz[i]);
1278:         nmin = PetscMin(nmin, nz[i]);
1279:         navg += nz[i];
1280:       }
1281:       PetscCall(PetscFree(nz));
1282:       navg = navg / size;
1283:       PetscCall(PetscViewerASCIIPrintf(viewer, "Load Balance - Nonzeros: Min %" PetscInt_FMT "  avg %" PetscInt_FMT "  max %" PetscInt_FMT "\n", nmin, navg, nmax));
1284:       PetscFunctionReturn(PETSC_SUCCESS);
1285:     }
1286:     PetscCall(PetscViewerGetFormat(viewer, &format));
1287:     if (format == PETSC_VIEWER_ASCII_INFO_DETAIL) {
1288:       MatInfo   info;
1289:       PetscInt *inodes = NULL;

1291:       PetscCallMPI(MPI_Comm_rank(PetscObjectComm((PetscObject)mat), &rank));
1292:       PetscCall(MatGetInfo(mat, MAT_LOCAL, &info));
1293:       PetscCall(MatInodeGetInodeSizes(aij->A, NULL, &inodes, NULL));
1294:       PetscCall(PetscViewerASCIIPushSynchronized(viewer));
1295:       if (!inodes) {
1296:         PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, "[%d] Local rows %" PetscInt_FMT " nz %" PetscInt_FMT " nz alloced %" PetscInt_FMT " mem %g, not using I-node routines\n", rank, mat->rmap->n, (PetscInt)info.nz_used, (PetscInt)info.nz_allocated,
1297:                                                      info.memory));
1298:       } else {
1299:         PetscCall(
1300:           PetscViewerASCIISynchronizedPrintf(viewer, "[%d] Local rows %" PetscInt_FMT " nz %" PetscInt_FMT " nz alloced %" PetscInt_FMT " mem %g, using I-node routines\n", rank, mat->rmap->n, (PetscInt)info.nz_used, (PetscInt)info.nz_allocated, info.memory));
1301:       }
1302:       PetscCall(MatGetInfo(aij->A, MAT_LOCAL, &info));
1303:       PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, "[%d] on-diagonal part: nz %" PetscInt_FMT " \n", rank, (PetscInt)info.nz_used));
1304:       PetscCall(MatGetInfo(aij->B, MAT_LOCAL, &info));
1305:       PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, "[%d] off-diagonal part: nz %" PetscInt_FMT " \n", rank, (PetscInt)info.nz_used));
1306:       PetscCall(PetscViewerFlush(viewer));
1307:       PetscCall(PetscViewerASCIIPopSynchronized(viewer));
1308:       PetscCall(PetscViewerASCIIPrintf(viewer, "Information on VecScatter used in matrix-vector product: \n"));
1309:       PetscCall(VecScatterView(aij->Mvctx, viewer));
1310:       PetscFunctionReturn(PETSC_SUCCESS);
1311:     } else if (format == PETSC_VIEWER_ASCII_INFO) {
1312:       PetscInt inodecount, inodelimit, *inodes;
1313:       PetscCall(MatInodeGetInodeSizes(aij->A, &inodecount, &inodes, &inodelimit));
1314:       if (inodes) {
1315:         PetscCall(PetscViewerASCIIPrintf(viewer, "using I-node (on process 0) routines: found %" PetscInt_FMT " nodes, limit used is %" PetscInt_FMT "\n", inodecount, inodelimit));
1316:       } else {
1317:         PetscCall(PetscViewerASCIIPrintf(viewer, "not using I-node (on process 0) routines\n"));
1318:       }
1319:       PetscFunctionReturn(PETSC_SUCCESS);
1320:     } else if (format == PETSC_VIEWER_ASCII_FACTOR_INFO) {
1321:       PetscFunctionReturn(PETSC_SUCCESS);
1322:     }
1323:   } else if (isbinary) {
1324:     if (size == 1) {
1325:       PetscCall(PetscObjectSetName((PetscObject)aij->A, ((PetscObject)mat)->name));
1326:       PetscCall(MatView(aij->A, viewer));
1327:     } else {
1328:       PetscCall(MatView_MPIAIJ_Binary(mat, viewer));
1329:     }
1330:     PetscFunctionReturn(PETSC_SUCCESS);
1331:   } else if (isascii && size == 1) {
1332:     PetscCall(PetscObjectSetName((PetscObject)aij->A, ((PetscObject)mat)->name));
1333:     PetscCall(MatView(aij->A, viewer));
1334:     PetscFunctionReturn(PETSC_SUCCESS);
1335:   } else if (isdraw) {
1336:     PetscDraw draw;
1337:     PetscBool isnull;
1338:     PetscCall(PetscViewerDrawGetDraw(viewer, 0, &draw));
1339:     PetscCall(PetscDrawIsNull(draw, &isnull));
1340:     if (isnull) PetscFunctionReturn(PETSC_SUCCESS);
1341:   }

1343:   { /* assemble the entire matrix onto first processor */
1344:     Mat A = NULL, Av;
1345:     IS  isrow, iscol;

1347:     PetscCall(ISCreateStride(PetscObjectComm((PetscObject)mat), rank == 0 ? mat->rmap->N : 0, 0, 1, &isrow));
1348:     PetscCall(ISCreateStride(PetscObjectComm((PetscObject)mat), rank == 0 ? mat->cmap->N : 0, 0, 1, &iscol));
1349:     PetscCall(MatCreateSubMatrix(mat, isrow, iscol, MAT_INITIAL_MATRIX, &A));
1350:     PetscCall(MatMPIAIJGetSeqAIJ(A, &Av, NULL, NULL));
1351:     /*  The commented code uses MatCreateSubMatrices instead */
1352:     /*
1353:     Mat *AA, A = NULL, Av;
1354:     IS  isrow,iscol;

1356:     PetscCall(ISCreateStride(PetscObjectComm((PetscObject)mat),rank == 0 ? mat->rmap->N : 0,0,1,&isrow));
1357:     PetscCall(ISCreateStride(PetscObjectComm((PetscObject)mat),rank == 0 ? mat->cmap->N : 0,0,1,&iscol));
1358:     PetscCall(MatCreateSubMatrices(mat,1,&isrow,&iscol,MAT_INITIAL_MATRIX,&AA));
1359:     if (rank == 0) {
1360:        PetscCall(PetscObjectReference((PetscObject)AA[0]));
1361:        A    = AA[0];
1362:        Av   = AA[0];
1363:     }
1364:     PetscCall(MatDestroySubMatrices(1,&AA));
1365: */
1366:     PetscCall(ISDestroy(&iscol));
1367:     PetscCall(ISDestroy(&isrow));
1368:     /*
1369:        Everyone has to call to draw the matrix since the graphics waits are
1370:        synchronized across all processors that share the PetscDraw object
1371:     */
1372:     PetscCall(PetscViewerGetSubViewer(viewer, PETSC_COMM_SELF, &sviewer));
1373:     if (rank == 0) {
1374:       if (((PetscObject)mat)->name) PetscCall(PetscObjectSetName((PetscObject)Av, ((PetscObject)mat)->name));
1375:       PetscCall(MatView_SeqAIJ(Av, sviewer));
1376:     }
1377:     PetscCall(PetscViewerRestoreSubViewer(viewer, PETSC_COMM_SELF, &sviewer));
1378:     PetscCall(MatDestroy(&A));
1379:   }
1380:   PetscFunctionReturn(PETSC_SUCCESS);
1381: }

1383: PetscErrorCode MatView_MPIAIJ(Mat mat, PetscViewer viewer)
1384: {
1385:   PetscBool isascii, isdraw, issocket, isbinary;

1387:   PetscFunctionBegin;
1388:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERASCII, &isascii));
1389:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERDRAW, &isdraw));
1390:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERBINARY, &isbinary));
1391:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERSOCKET, &issocket));
1392:   if (isascii || isdraw || isbinary || issocket) PetscCall(MatView_MPIAIJ_ASCIIorDraworSocket(mat, viewer));
1393:   PetscFunctionReturn(PETSC_SUCCESS);
1394: }

1396: static PetscErrorCode MatSOR_MPIAIJ(Mat matin, Vec bb, PetscReal omega, MatSORType flag, PetscReal fshift, PetscInt its, PetscInt lits, Vec xx)
1397: {
1398:   Mat_MPIAIJ *mat = (Mat_MPIAIJ *)matin->data;
1399:   Vec         bb1 = NULL;
1400:   PetscBool   hasop;

1402:   PetscFunctionBegin;
1403:   if (flag == SOR_APPLY_UPPER) {
1404:     PetscUseTypeMethod(mat->A, sor, bb, omega, flag, fshift, lits, 1, xx);
1405:     PetscFunctionReturn(PETSC_SUCCESS);
1406:   }

1408:   if (its > 1 || ~flag & SOR_ZERO_INITIAL_GUESS || flag & SOR_EISENSTAT) PetscCall(VecDuplicate(bb, &bb1));

1410:   if ((flag & SOR_LOCAL_SYMMETRIC_SWEEP) == SOR_LOCAL_SYMMETRIC_SWEEP) {
1411:     if (flag & SOR_ZERO_INITIAL_GUESS) {
1412:       PetscUseTypeMethod(mat->A, sor, bb, omega, flag, fshift, lits, 1, xx);
1413:       its--;
1414:     }

1416:     while (its--) {
1417:       PetscCall(VecScatterBegin(mat->Mvctx, xx, mat->lvec, INSERT_VALUES, SCATTER_FORWARD));
1418:       PetscCall(VecScatterEnd(mat->Mvctx, xx, mat->lvec, INSERT_VALUES, SCATTER_FORWARD));

1420:       /* update rhs: bb1 = bb - B*x */
1421:       PetscCall(VecScale(mat->lvec, -1.0));
1422:       PetscUseTypeMethod(mat->B, multadd, mat->lvec, bb, bb1);

1424:       /* local sweep */
1425:       PetscUseTypeMethod(mat->A, sor, bb1, omega, SOR_SYMMETRIC_SWEEP, fshift, lits, 1, xx);
1426:     }
1427:   } else if (flag & SOR_LOCAL_FORWARD_SWEEP) {
1428:     if (flag & SOR_ZERO_INITIAL_GUESS) {
1429:       PetscUseTypeMethod(mat->A, sor, bb, omega, flag, fshift, lits, 1, xx);
1430:       its--;
1431:     }
1432:     while (its--) {
1433:       PetscCall(VecScatterBegin(mat->Mvctx, xx, mat->lvec, INSERT_VALUES, SCATTER_FORWARD));
1434:       PetscCall(VecScatterEnd(mat->Mvctx, xx, mat->lvec, INSERT_VALUES, SCATTER_FORWARD));

1436:       /* update rhs: bb1 = bb - B*x */
1437:       PetscCall(VecScale(mat->lvec, -1.0));
1438:       PetscUseTypeMethod(mat->B, multadd, mat->lvec, bb, bb1);

1440:       /* local sweep */
1441:       PetscUseTypeMethod(mat->A, sor, bb1, omega, SOR_FORWARD_SWEEP, fshift, lits, 1, xx);
1442:     }
1443:   } else if (flag & SOR_LOCAL_BACKWARD_SWEEP) {
1444:     if (flag & SOR_ZERO_INITIAL_GUESS) {
1445:       PetscUseTypeMethod(mat->A, sor, bb, omega, flag, fshift, lits, 1, xx);
1446:       its--;
1447:     }
1448:     while (its--) {
1449:       PetscCall(VecScatterBegin(mat->Mvctx, xx, mat->lvec, INSERT_VALUES, SCATTER_FORWARD));
1450:       PetscCall(VecScatterEnd(mat->Mvctx, xx, mat->lvec, INSERT_VALUES, SCATTER_FORWARD));

1452:       /* update rhs: bb1 = bb - B*x */
1453:       PetscCall(VecScale(mat->lvec, -1.0));
1454:       PetscUseTypeMethod(mat->B, multadd, mat->lvec, bb, bb1);

1456:       /* local sweep */
1457:       PetscUseTypeMethod(mat->A, sor, bb1, omega, SOR_BACKWARD_SWEEP, fshift, lits, 1, xx);
1458:     }
1459:   } else if (flag & SOR_EISENSTAT) {
1460:     Vec xx1;

1462:     PetscCall(VecDuplicate(bb, &xx1));
1463:     PetscUseTypeMethod(mat->A, sor, bb, omega, (MatSORType)(SOR_ZERO_INITIAL_GUESS | SOR_LOCAL_BACKWARD_SWEEP), fshift, lits, 1, xx);

1465:     PetscCall(VecScatterBegin(mat->Mvctx, xx, mat->lvec, INSERT_VALUES, SCATTER_FORWARD));
1466:     PetscCall(VecScatterEnd(mat->Mvctx, xx, mat->lvec, INSERT_VALUES, SCATTER_FORWARD));
1467:     if (!mat->diag) {
1468:       PetscCall(MatCreateVecs(matin, &mat->diag, NULL));
1469:       PetscCall(MatGetDiagonal(matin, mat->diag));
1470:     }
1471:     PetscCall(MatHasOperation(matin, MATOP_MULT_DIAGONAL_BLOCK, &hasop));
1472:     if (hasop) PetscCall(MatMultDiagonalBlock(matin, xx, bb1));
1473:     else PetscCall(VecPointwiseMult(bb1, mat->diag, xx));
1474:     PetscCall(VecAYPX(bb1, (omega - 2.0) / omega, bb));

1476:     PetscCall(MatMultAdd(mat->B, mat->lvec, bb1, bb1));

1478:     /* local sweep */
1479:     PetscUseTypeMethod(mat->A, sor, bb1, omega, (MatSORType)(SOR_ZERO_INITIAL_GUESS | SOR_LOCAL_FORWARD_SWEEP), fshift, lits, 1, xx1);
1480:     PetscCall(VecAXPY(xx, 1.0, xx1));
1481:     PetscCall(VecDestroy(&xx1));
1482:   } else SETERRQ(PetscObjectComm((PetscObject)matin), PETSC_ERR_SUP, "Parallel SOR not supported");

1484:   PetscCall(VecDestroy(&bb1));

1486:   matin->factorerrortype = mat->A->factorerrortype;
1487:   PetscFunctionReturn(PETSC_SUCCESS);
1488: }

1490: static PetscErrorCode MatPermute_MPIAIJ(Mat A, IS rowp, IS colp, Mat *B)
1491: {
1492:   Mat             aA, aB, Aperm;
1493:   const PetscInt *rwant, *cwant, *gcols, *ai, *bi, *aj, *bj;
1494:   PetscScalar    *aa, *ba;
1495:   PetscInt        i, j, m, n, ng, anz, bnz, *dnnz, *onnz, *tdnnz, *tonnz, *rdest, *cdest, *work, *gcdest;
1496:   PetscSF         rowsf, sf;
1497:   IS              parcolp = NULL;
1498:   PetscBool       done;

1500:   PetscFunctionBegin;
1501:   PetscCall(MatGetLocalSize(A, &m, &n));
1502:   PetscCall(ISGetIndices(rowp, &rwant));
1503:   PetscCall(ISGetIndices(colp, &cwant));
1504:   PetscCall(PetscMalloc3(PetscMax(m, n), &work, m, &rdest, n, &cdest));

1506:   /* Invert row permutation to find out where my rows should go */
1507:   PetscCall(PetscSFCreate(PetscObjectComm((PetscObject)A), &rowsf));
1508:   PetscCall(PetscSFSetGraphLayout(rowsf, A->rmap, A->rmap->n, NULL, PETSC_OWN_POINTER, rwant));
1509:   PetscCall(PetscSFSetFromOptions(rowsf));
1510:   for (i = 0; i < m; i++) work[i] = A->rmap->rstart + i;
1511:   PetscCall(PetscSFReduceBegin(rowsf, MPIU_INT, work, rdest, MPI_REPLACE));
1512:   PetscCall(PetscSFReduceEnd(rowsf, MPIU_INT, work, rdest, MPI_REPLACE));

1514:   /* Invert column permutation to find out where my columns should go */
1515:   PetscCall(PetscSFCreate(PetscObjectComm((PetscObject)A), &sf));
1516:   PetscCall(PetscSFSetGraphLayout(sf, A->cmap, A->cmap->n, NULL, PETSC_OWN_POINTER, cwant));
1517:   PetscCall(PetscSFSetFromOptions(sf));
1518:   for (i = 0; i < n; i++) work[i] = A->cmap->rstart + i;
1519:   PetscCall(PetscSFReduceBegin(sf, MPIU_INT, work, cdest, MPI_REPLACE));
1520:   PetscCall(PetscSFReduceEnd(sf, MPIU_INT, work, cdest, MPI_REPLACE));
1521:   PetscCall(PetscSFDestroy(&sf));

1523:   PetscCall(ISRestoreIndices(rowp, &rwant));
1524:   PetscCall(ISRestoreIndices(colp, &cwant));
1525:   PetscCall(MatMPIAIJGetSeqAIJ(A, &aA, &aB, &gcols));

1527:   /* Find out where my gcols should go */
1528:   PetscCall(MatGetSize(aB, NULL, &ng));
1529:   PetscCall(PetscMalloc1(ng, &gcdest));
1530:   PetscCall(PetscSFCreate(PetscObjectComm((PetscObject)A), &sf));
1531:   PetscCall(PetscSFSetGraphLayout(sf, A->cmap, ng, NULL, PETSC_OWN_POINTER, gcols));
1532:   PetscCall(PetscSFSetFromOptions(sf));
1533:   PetscCall(PetscSFBcastBegin(sf, MPIU_INT, cdest, gcdest, MPI_REPLACE));
1534:   PetscCall(PetscSFBcastEnd(sf, MPIU_INT, cdest, gcdest, MPI_REPLACE));
1535:   PetscCall(PetscSFDestroy(&sf));

1537:   PetscCall(PetscCalloc4(m, &dnnz, m, &onnz, m, &tdnnz, m, &tonnz));
1538:   PetscCall(MatGetRowIJ(aA, 0, PETSC_FALSE, PETSC_FALSE, &anz, &ai, &aj, &done));
1539:   PetscCall(MatGetRowIJ(aB, 0, PETSC_FALSE, PETSC_FALSE, &bnz, &bi, &bj, &done));
1540:   for (i = 0; i < m; i++) {
1541:     PetscInt    row = rdest[i];
1542:     PetscMPIInt rowner;
1543:     PetscCall(PetscLayoutFindOwner(A->rmap, row, &rowner));
1544:     for (j = ai[i]; j < ai[i + 1]; j++) {
1545:       PetscInt    col = cdest[aj[j]];
1546:       PetscMPIInt cowner;
1547:       PetscCall(PetscLayoutFindOwner(A->cmap, col, &cowner)); /* Could build an index for the columns to eliminate this search */
1548:       if (rowner == cowner) dnnz[i]++;
1549:       else onnz[i]++;
1550:     }
1551:     for (j = bi[i]; j < bi[i + 1]; j++) {
1552:       PetscInt    col = gcdest[bj[j]];
1553:       PetscMPIInt cowner;
1554:       PetscCall(PetscLayoutFindOwner(A->cmap, col, &cowner));
1555:       if (rowner == cowner) dnnz[i]++;
1556:       else onnz[i]++;
1557:     }
1558:   }
1559:   PetscCall(PetscSFBcastBegin(rowsf, MPIU_INT, dnnz, tdnnz, MPI_REPLACE));
1560:   PetscCall(PetscSFBcastEnd(rowsf, MPIU_INT, dnnz, tdnnz, MPI_REPLACE));
1561:   PetscCall(PetscSFBcastBegin(rowsf, MPIU_INT, onnz, tonnz, MPI_REPLACE));
1562:   PetscCall(PetscSFBcastEnd(rowsf, MPIU_INT, onnz, tonnz, MPI_REPLACE));
1563:   PetscCall(PetscSFDestroy(&rowsf));

1565:   PetscCall(MatCreateAIJ(PetscObjectComm((PetscObject)A), A->rmap->n, A->cmap->n, A->rmap->N, A->cmap->N, 0, tdnnz, 0, tonnz, &Aperm));
1566:   PetscCall(MatSeqAIJGetArray(aA, &aa));
1567:   PetscCall(MatSeqAIJGetArray(aB, &ba));
1568:   for (i = 0; i < m; i++) {
1569:     PetscInt *acols = dnnz, *bcols = onnz; /* Repurpose now-unneeded arrays */
1570:     PetscInt  j0, rowlen;
1571:     rowlen = ai[i + 1] - ai[i];
1572:     for (j0 = j = 0; j < rowlen; j0 = j) { /* rowlen could be larger than number of rows m, so sum in batches */
1573:       for (; j < PetscMin(rowlen, j0 + m); j++) acols[j - j0] = cdest[aj[ai[i] + j]];
1574:       PetscCall(MatSetValues(Aperm, 1, &rdest[i], j - j0, acols, aa + ai[i] + j0, INSERT_VALUES));
1575:     }
1576:     rowlen = bi[i + 1] - bi[i];
1577:     for (j0 = j = 0; j < rowlen; j0 = j) {
1578:       for (; j < PetscMin(rowlen, j0 + m); j++) bcols[j - j0] = gcdest[bj[bi[i] + j]];
1579:       PetscCall(MatSetValues(Aperm, 1, &rdest[i], j - j0, bcols, ba + bi[i] + j0, INSERT_VALUES));
1580:     }
1581:   }
1582:   PetscCall(MatAssemblyBegin(Aperm, MAT_FINAL_ASSEMBLY));
1583:   PetscCall(MatAssemblyEnd(Aperm, MAT_FINAL_ASSEMBLY));
1584:   PetscCall(MatRestoreRowIJ(aA, 0, PETSC_FALSE, PETSC_FALSE, &anz, &ai, &aj, &done));
1585:   PetscCall(MatRestoreRowIJ(aB, 0, PETSC_FALSE, PETSC_FALSE, &bnz, &bi, &bj, &done));
1586:   PetscCall(MatSeqAIJRestoreArray(aA, &aa));
1587:   PetscCall(MatSeqAIJRestoreArray(aB, &ba));
1588:   PetscCall(PetscFree4(dnnz, onnz, tdnnz, tonnz));
1589:   PetscCall(PetscFree3(work, rdest, cdest));
1590:   PetscCall(PetscFree(gcdest));
1591:   if (parcolp) PetscCall(ISDestroy(&colp));
1592:   *B = Aperm;
1593:   PetscFunctionReturn(PETSC_SUCCESS);
1594: }

1596: static PetscErrorCode MatGetGhosts_MPIAIJ(Mat mat, PetscInt *nghosts, const PetscInt *ghosts[])
1597: {
1598:   Mat_MPIAIJ *aij = (Mat_MPIAIJ *)mat->data;

1600:   PetscFunctionBegin;
1601:   PetscCall(MatGetSize(aij->B, NULL, nghosts));
1602:   if (ghosts) *ghosts = aij->garray;
1603:   PetscFunctionReturn(PETSC_SUCCESS);
1604: }

1606: static PetscErrorCode MatGetInfo_MPIAIJ(Mat matin, MatInfoType flag, MatInfo *info)
1607: {
1608:   Mat_MPIAIJ    *mat = (Mat_MPIAIJ *)matin->data;
1609:   Mat            A = mat->A, B = mat->B;
1610:   PetscLogDouble isend[5], irecv[5];

1612:   PetscFunctionBegin;
1613:   info->block_size = 1.0;
1614:   PetscCall(MatGetInfo(A, MAT_LOCAL, info));

1616:   isend[0] = info->nz_used;
1617:   isend[1] = info->nz_allocated;
1618:   isend[2] = info->nz_unneeded;
1619:   isend[3] = info->memory;
1620:   isend[4] = info->mallocs;

1622:   PetscCall(MatGetInfo(B, MAT_LOCAL, info));

1624:   isend[0] += info->nz_used;
1625:   isend[1] += info->nz_allocated;
1626:   isend[2] += info->nz_unneeded;
1627:   isend[3] += info->memory;
1628:   isend[4] += info->mallocs;
1629:   if (flag == MAT_LOCAL) {
1630:     info->nz_used      = isend[0];
1631:     info->nz_allocated = isend[1];
1632:     info->nz_unneeded  = isend[2];
1633:     info->memory       = isend[3];
1634:     info->mallocs      = isend[4];
1635:   } else if (flag == MAT_GLOBAL_MAX) {
1636:     PetscCallMPI(MPIU_Allreduce(isend, irecv, 5, MPIU_PETSCLOGDOUBLE, MPI_MAX, PetscObjectComm((PetscObject)matin)));

1638:     info->nz_used      = irecv[0];
1639:     info->nz_allocated = irecv[1];
1640:     info->nz_unneeded  = irecv[2];
1641:     info->memory       = irecv[3];
1642:     info->mallocs      = irecv[4];
1643:   } else if (flag == MAT_GLOBAL_SUM) {
1644:     PetscCallMPI(MPIU_Allreduce(isend, irecv, 5, MPIU_PETSCLOGDOUBLE, MPI_SUM, PetscObjectComm((PetscObject)matin)));

1646:     info->nz_used      = irecv[0];
1647:     info->nz_allocated = irecv[1];
1648:     info->nz_unneeded  = irecv[2];
1649:     info->memory       = irecv[3];
1650:     info->mallocs      = irecv[4];
1651:   }
1652:   info->fill_ratio_given  = 0; /* no parallel LU/ILU/Cholesky */
1653:   info->fill_ratio_needed = 0;
1654:   info->factor_mallocs    = 0;
1655:   PetscFunctionReturn(PETSC_SUCCESS);
1656: }

1658: PetscErrorCode MatSetOption_MPIAIJ(Mat A, MatOption op, PetscBool flg)
1659: {
1660:   Mat_MPIAIJ *a = (Mat_MPIAIJ *)A->data;

1662:   PetscFunctionBegin;
1663:   switch (op) {
1664:   case MAT_NEW_NONZERO_LOCATIONS:
1665:   case MAT_NEW_NONZERO_ALLOCATION_ERR:
1666:   case MAT_UNUSED_NONZERO_LOCATION_ERR:
1667:   case MAT_KEEP_NONZERO_PATTERN:
1668:   case MAT_NEW_NONZERO_LOCATION_ERR:
1669:   case MAT_USE_INODES:
1670:   case MAT_IGNORE_ZERO_ENTRIES:
1671:   case MAT_FORM_EXPLICIT_TRANSPOSE:
1672:     MatCheckPreallocated(A, 1);
1673:     PetscCall(MatSetOption(a->A, op, flg));
1674:     PetscCall(MatSetOption(a->B, op, flg));
1675:     break;
1676:   case MAT_ROW_ORIENTED:
1677:     MatCheckPreallocated(A, 1);
1678:     a->roworiented = flg;

1680:     PetscCall(MatSetOption(a->A, op, flg));
1681:     PetscCall(MatSetOption(a->B, op, flg));
1682:     break;
1683:   case MAT_IGNORE_OFF_PROC_ENTRIES:
1684:     a->donotstash = flg;
1685:     break;
1686:   /* Symmetry flags are handled directly by MatSetOption() and they don't affect preallocation */
1687:   case MAT_SPD:
1688:   case MAT_SYMMETRIC:
1689:   case MAT_STRUCTURALLY_SYMMETRIC:
1690:   case MAT_HERMITIAN:
1691:   case MAT_SYMMETRY_ETERNAL:
1692:   case MAT_STRUCTURAL_SYMMETRY_ETERNAL:
1693:   case MAT_SPD_ETERNAL:
1694:     /* if the diagonal matrix is square it inherits some of the properties above */
1695:     if (a->A && A->rmap->n == A->cmap->n) PetscCall(MatSetOption(a->A, op, flg));
1696:     break;
1697:   case MAT_SUBMAT_SINGLEIS:
1698:     A->submat_singleis = flg;
1699:     break;
1700:   default:
1701:     break;
1702:   }
1703:   PetscFunctionReturn(PETSC_SUCCESS);
1704: }

1706: PetscErrorCode MatGetRow_MPIAIJ(Mat matin, PetscInt row, PetscInt *nz, PetscInt **idx, PetscScalar **v)
1707: {
1708:   Mat_MPIAIJ  *mat = (Mat_MPIAIJ *)matin->data;
1709:   PetscScalar *vworkA, *vworkB, **pvA, **pvB, *v_p;
1710:   PetscInt     i, *cworkA, *cworkB, **pcA, **pcB, cstart = matin->cmap->rstart;
1711:   PetscInt     nztot, nzA, nzB, lrow, rstart = matin->rmap->rstart, rend = matin->rmap->rend;
1712:   PetscInt    *cmap, *idx_p;

1714:   PetscFunctionBegin;
1715:   PetscCheck(!mat->getrowactive, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Already active");
1716:   mat->getrowactive = PETSC_TRUE;

1718:   if (!mat->rowvalues && (idx || v)) {
1719:     /*
1720:         allocate enough space to hold information from the longest row.
1721:     */
1722:     Mat_SeqAIJ *Aa = (Mat_SeqAIJ *)mat->A->data, *Ba = (Mat_SeqAIJ *)mat->B->data;
1723:     PetscInt    max = 1, tmp;
1724:     for (i = 0; i < matin->rmap->n; i++) {
1725:       tmp = Aa->i[i + 1] - Aa->i[i] + Ba->i[i + 1] - Ba->i[i];
1726:       if (max < tmp) max = tmp;
1727:     }
1728:     PetscCall(PetscMalloc2(max, &mat->rowvalues, max, &mat->rowindices));
1729:   }

1731:   PetscCheck(row >= rstart && row < rend, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Only local rows");
1732:   lrow = row - rstart;

1734:   pvA = &vworkA;
1735:   pcA = &cworkA;
1736:   pvB = &vworkB;
1737:   pcB = &cworkB;
1738:   if (!v) {
1739:     pvA = NULL;
1740:     pvB = NULL;
1741:   }
1742:   if (!idx) {
1743:     pcA = NULL;
1744:     if (!v) pcB = NULL;
1745:   }
1746:   PetscUseTypeMethod(mat->A, getrow, lrow, &nzA, pcA, pvA);
1747:   PetscUseTypeMethod(mat->B, getrow, lrow, &nzB, pcB, pvB);
1748:   nztot = nzA + nzB;

1750:   cmap = mat->garray;
1751:   if (v || idx) {
1752:     if (nztot) {
1753:       /* Sort by increasing column numbers, assuming A and B already sorted */
1754:       PetscInt imark = -1;
1755:       if (v) {
1756:         *v = v_p = mat->rowvalues;
1757:         for (i = 0; i < nzB; i++) {
1758:           if (cmap[cworkB[i]] < cstart) v_p[i] = vworkB[i];
1759:           else break;
1760:         }
1761:         imark = i;
1762:         for (i = 0; i < nzA; i++) v_p[imark + i] = vworkA[i];
1763:         for (i = imark; i < nzB; i++) v_p[nzA + i] = vworkB[i];
1764:       }
1765:       if (idx) {
1766:         *idx = idx_p = mat->rowindices;
1767:         if (imark > -1) {
1768:           for (i = 0; i < imark; i++) idx_p[i] = cmap[cworkB[i]];
1769:         } else {
1770:           for (i = 0; i < nzB; i++) {
1771:             if (cmap[cworkB[i]] < cstart) idx_p[i] = cmap[cworkB[i]];
1772:             else break;
1773:           }
1774:           imark = i;
1775:         }
1776:         for (i = 0; i < nzA; i++) idx_p[imark + i] = cstart + cworkA[i];
1777:         for (i = imark; i < nzB; i++) idx_p[nzA + i] = cmap[cworkB[i]];
1778:       }
1779:     } else {
1780:       if (idx) *idx = NULL;
1781:       if (v) *v = NULL;
1782:     }
1783:   }
1784:   *nz = nztot;
1785:   PetscUseTypeMethod(mat->A, restorerow, lrow, &nzA, pcA, pvA);
1786:   PetscUseTypeMethod(mat->B, restorerow, lrow, &nzB, pcB, pvB);
1787:   PetscFunctionReturn(PETSC_SUCCESS);
1788: }

1790: PetscErrorCode MatRestoreRow_MPIAIJ(Mat mat, PetscInt row, PetscInt *nz, PetscInt **idx, PetscScalar **v)
1791: {
1792:   Mat_MPIAIJ *aij = (Mat_MPIAIJ *)mat->data;

1794:   PetscFunctionBegin;
1795:   PetscCheck(aij->getrowactive, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "MatGetRow() must be called first");
1796:   aij->getrowactive = PETSC_FALSE;
1797:   PetscFunctionReturn(PETSC_SUCCESS);
1798: }

1800: static PetscErrorCode MatNorm_MPIAIJ(Mat mat, NormType type, PetscReal *norm)
1801: {
1802:   Mat_MPIAIJ      *aij  = (Mat_MPIAIJ *)mat->data;
1803:   Mat_SeqAIJ      *amat = (Mat_SeqAIJ *)aij->A->data, *bmat = (Mat_SeqAIJ *)aij->B->data;
1804:   PetscInt         i, j;
1805:   PetscReal        sum = 0.0;
1806:   const MatScalar *v, *amata, *bmata;

1808:   PetscFunctionBegin;
1809:   if (aij->size == 1) {
1810:     PetscCall(MatNorm(aij->A, type, norm));
1811:   } else {
1812:     PetscCall(MatSeqAIJGetArrayRead(aij->A, &amata));
1813:     PetscCall(MatSeqAIJGetArrayRead(aij->B, &bmata));
1814:     if (type == NORM_FROBENIUS) {
1815:       v = amata;
1816:       for (i = 0; i < amat->nz; i++) {
1817:         sum += PetscRealPart(PetscConj(*v) * (*v));
1818:         v++;
1819:       }
1820:       v = bmata;
1821:       for (i = 0; i < bmat->nz; i++) {
1822:         sum += PetscRealPart(PetscConj(*v) * (*v));
1823:         v++;
1824:       }
1825:       PetscCallMPI(MPIU_Allreduce(&sum, norm, 1, MPIU_REAL, MPIU_SUM, PetscObjectComm((PetscObject)mat)));
1826:       *norm = PetscSqrtReal(*norm);
1827:       PetscCall(PetscLogFlops(2.0 * amat->nz + 2.0 * bmat->nz));
1828:     } else if (type == NORM_1) { /* max column norm */
1829:       Vec          col, bcol;
1830:       PetscScalar *array;
1831:       PetscInt    *jj, *garray = aij->garray;

1833:       PetscCall(MatCreateVecs(mat, &col, NULL));
1834:       PetscCall(VecSet(col, 0.0));
1835:       PetscCall(VecGetArrayWrite(col, &array));
1836:       v  = amata;
1837:       jj = amat->j;
1838:       for (j = 0; j < amat->nz; j++) array[*jj++] += PetscAbsScalar(*v++);
1839:       PetscCall(VecRestoreArrayWrite(col, &array));
1840:       PetscCall(MatCreateVecs(aij->B, &bcol, NULL));
1841:       PetscCall(VecSet(bcol, 0.0));
1842:       PetscCall(VecGetArrayWrite(bcol, &array));
1843:       v  = bmata;
1844:       jj = bmat->j;
1845:       for (j = 0; j < bmat->nz; j++) array[*jj++] += PetscAbsScalar(*v++);
1846:       PetscCall(VecSetValues(col, aij->B->cmap->n, garray, array, ADD_VALUES));
1847:       PetscCall(VecRestoreArrayWrite(bcol, &array));
1848:       PetscCall(VecDestroy(&bcol));
1849:       PetscCall(VecAssemblyBegin(col));
1850:       PetscCall(VecAssemblyEnd(col));
1851:       PetscCall(VecNorm(col, NORM_INFINITY, norm));
1852:       PetscCall(VecDestroy(&col));
1853:     } else if (type == NORM_INFINITY) { /* max row norm */
1854:       PetscReal ntemp = 0.0;
1855:       for (j = 0; j < aij->A->rmap->n; j++) {
1856:         v   = PetscSafePointerPlusOffset(amata, amat->i[j]);
1857:         sum = 0.0;
1858:         for (i = 0; i < amat->i[j + 1] - amat->i[j]; i++) {
1859:           sum += PetscAbsScalar(*v);
1860:           v++;
1861:         }
1862:         v = PetscSafePointerPlusOffset(bmata, bmat->i[j]);
1863:         for (i = 0; i < bmat->i[j + 1] - bmat->i[j]; i++) {
1864:           sum += PetscAbsScalar(*v);
1865:           v++;
1866:         }
1867:         if (sum > ntemp) ntemp = sum;
1868:       }
1869:       PetscCallMPI(MPIU_Allreduce(&ntemp, norm, 1, MPIU_REAL, MPIU_MAX, PetscObjectComm((PetscObject)mat)));
1870:       PetscCall(PetscLogFlops(PetscMax(amat->nz + bmat->nz - 1, 0)));
1871:     } else SETERRQ(PetscObjectComm((PetscObject)mat), PETSC_ERR_SUP, "No support for two norm");
1872:     PetscCall(MatSeqAIJRestoreArrayRead(aij->A, &amata));
1873:     PetscCall(MatSeqAIJRestoreArrayRead(aij->B, &bmata));
1874:   }
1875:   PetscFunctionReturn(PETSC_SUCCESS);
1876: }

1878: static PetscErrorCode MatTranspose_MPIAIJ(Mat A, MatReuse reuse, Mat *matout)
1879: {
1880:   Mat_MPIAIJ      *a    = (Mat_MPIAIJ *)A->data, *b;
1881:   Mat_SeqAIJ      *Aloc = (Mat_SeqAIJ *)a->A->data, *Bloc = (Mat_SeqAIJ *)a->B->data, *sub_B_diag;
1882:   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;
1883:   const PetscInt  *ai, *aj, *bi, *bj, *B_diag_i;
1884:   Mat              B, A_diag, *B_diag;
1885:   const MatScalar *pbv, *bv;

1887:   PetscFunctionBegin;
1888:   if (reuse == MAT_REUSE_MATRIX) PetscCall(MatTransposeCheckNonzeroState_Private(A, *matout));
1889:   ma = A->rmap->n;
1890:   na = A->cmap->n;
1891:   mb = a->B->rmap->n;
1892:   nb = a->B->cmap->n;
1893:   ai = Aloc->i;
1894:   aj = Aloc->j;
1895:   bi = Bloc->i;
1896:   bj = Bloc->j;
1897:   if (reuse == MAT_INITIAL_MATRIX || *matout == A) {
1898:     PetscInt            *d_nnz, *g_nnz, *o_nnz;
1899:     PetscSFNode         *oloc;
1900:     PETSC_UNUSED PetscSF sf;

1902:     PetscCall(PetscMalloc4(na, &d_nnz, na, &o_nnz, nb, &g_nnz, nb, &oloc));
1903:     /* compute d_nnz for preallocation */
1904:     PetscCall(PetscArrayzero(d_nnz, na));
1905:     for (i = 0; i < ai[ma]; i++) d_nnz[aj[i]]++;
1906:     /* compute local off-diagonal contributions */
1907:     PetscCall(PetscArrayzero(g_nnz, nb));
1908:     for (i = 0; i < bi[ma]; i++) g_nnz[bj[i]]++;
1909:     /* map those to global */
1910:     PetscCall(PetscSFCreate(PetscObjectComm((PetscObject)A), &sf));
1911:     PetscCall(PetscSFSetGraphLayout(sf, A->cmap, nb, NULL, PETSC_USE_POINTER, a->garray));
1912:     PetscCall(PetscSFSetFromOptions(sf));
1913:     PetscCall(PetscArrayzero(o_nnz, na));
1914:     PetscCall(PetscSFReduceBegin(sf, MPIU_INT, g_nnz, o_nnz, MPI_SUM));
1915:     PetscCall(PetscSFReduceEnd(sf, MPIU_INT, g_nnz, o_nnz, MPI_SUM));
1916:     PetscCall(PetscSFDestroy(&sf));

1918:     PetscCall(MatCreate(PetscObjectComm((PetscObject)A), &B));
1919:     PetscCall(MatSetSizes(B, A->cmap->n, A->rmap->n, N, M));
1920:     PetscCall(MatSetBlockSizes(B, A->cmap->bs, A->rmap->bs));
1921:     PetscCall(MatSetType(B, ((PetscObject)A)->type_name));
1922:     PetscCall(MatMPIAIJSetPreallocation(B, 0, d_nnz, 0, o_nnz));
1923:     PetscCall(PetscFree4(d_nnz, o_nnz, g_nnz, oloc));
1924:   } else {
1925:     B = *matout;
1926:     PetscCall(MatSetOption(B, MAT_NEW_NONZERO_ALLOCATION_ERR, PETSC_TRUE));
1927:   }

1929:   b           = (Mat_MPIAIJ *)B->data;
1930:   A_diag      = a->A;
1931:   B_diag      = &b->A;
1932:   sub_B_diag  = (Mat_SeqAIJ *)(*B_diag)->data;
1933:   A_diag_ncol = A_diag->cmap->N;
1934:   B_diag_ilen = sub_B_diag->ilen;
1935:   B_diag_i    = sub_B_diag->i;

1937:   /* Set ilen for diagonal of B */
1938:   for (i = 0; i < A_diag_ncol; i++) B_diag_ilen[i] = B_diag_i[i + 1] - B_diag_i[i];

1940:   /* Transpose the diagonal part of the matrix. In contrast to the off-diagonal part, this can be done
1941:   very quickly (=without using MatSetValues), because all writes are local. */
1942:   PetscCall(MatTransposeSetPrecursor(A_diag, *B_diag));
1943:   PetscCall(MatTranspose(A_diag, MAT_REUSE_MATRIX, B_diag));

1945:   /* copy over the B part */
1946:   PetscCall(PetscMalloc1(bi[mb], &cols));
1947:   PetscCall(MatSeqAIJGetArrayRead(a->B, &bv));
1948:   pbv = bv;
1949:   row = A->rmap->rstart;
1950:   for (i = 0; i < bi[mb]; i++) cols[i] = a->garray[bj[i]];
1951:   cols_tmp = cols;
1952:   for (i = 0; i < mb; i++) {
1953:     ncol = bi[i + 1] - bi[i];
1954:     PetscCall(MatSetValues(B, ncol, cols_tmp, 1, &row, pbv, INSERT_VALUES));
1955:     row++;
1956:     if (pbv) pbv += ncol;
1957:     if (cols_tmp) cols_tmp += ncol;
1958:   }
1959:   PetscCall(PetscFree(cols));
1960:   PetscCall(MatSeqAIJRestoreArrayRead(a->B, &bv));

1962:   PetscCall(MatAssemblyBegin(B, MAT_FINAL_ASSEMBLY));
1963:   PetscCall(MatAssemblyEnd(B, MAT_FINAL_ASSEMBLY));
1964:   if (reuse == MAT_INITIAL_MATRIX || reuse == MAT_REUSE_MATRIX) {
1965:     *matout = B;
1966:   } else {
1967:     PetscCall(MatHeaderMerge(A, &B));
1968:   }
1969:   PetscFunctionReturn(PETSC_SUCCESS);
1970: }

1972: static PetscErrorCode MatDiagonalScale_MPIAIJ(Mat mat, Vec ll, Vec rr)
1973: {
1974:   Mat_MPIAIJ *aij = (Mat_MPIAIJ *)mat->data;
1975:   Mat         a = aij->A, b = aij->B;
1976:   PetscInt    s1, s2, s3;

1978:   PetscFunctionBegin;
1979:   PetscCall(MatGetLocalSize(mat, &s2, &s3));
1980:   if (rr) {
1981:     PetscCall(VecGetLocalSize(rr, &s1));
1982:     PetscCheck(s1 == s3, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "right vector non-conforming local size");
1983:     /* Overlap communication with computation. */
1984:     PetscCall(VecScatterBegin(aij->Mvctx, rr, aij->lvec, INSERT_VALUES, SCATTER_FORWARD));
1985:   }
1986:   if (ll) {
1987:     PetscCall(VecGetLocalSize(ll, &s1));
1988:     PetscCheck(s1 == s2, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "left vector non-conforming local size");
1989:     PetscUseTypeMethod(b, diagonalscale, ll, NULL);
1990:   }
1991:   /* scale  the diagonal block */
1992:   PetscUseTypeMethod(a, diagonalscale, ll, rr);

1994:   if (rr) {
1995:     /* Do a scatter end and then right scale the off-diagonal block */
1996:     PetscCall(VecScatterEnd(aij->Mvctx, rr, aij->lvec, INSERT_VALUES, SCATTER_FORWARD));
1997:     PetscUseTypeMethod(b, diagonalscale, NULL, aij->lvec);
1998:   }
1999:   PetscFunctionReturn(PETSC_SUCCESS);
2000: }

2002: static PetscErrorCode MatSetUnfactored_MPIAIJ(Mat A)
2003: {
2004:   Mat_MPIAIJ *a = (Mat_MPIAIJ *)A->data;

2006:   PetscFunctionBegin;
2007:   PetscCall(MatSetUnfactored(a->A));
2008:   PetscFunctionReturn(PETSC_SUCCESS);
2009: }

2011: static PetscErrorCode MatEqual_MPIAIJ(Mat A, Mat B, PetscBool *flag)
2012: {
2013:   Mat_MPIAIJ *matB = (Mat_MPIAIJ *)B->data, *matA = (Mat_MPIAIJ *)A->data;
2014:   Mat         a, b, c, d;
2015:   PetscBool   flg;

2017:   PetscFunctionBegin;
2018:   a = matA->A;
2019:   b = matA->B;
2020:   c = matB->A;
2021:   d = matB->B;

2023:   PetscCall(MatEqual(a, c, &flg));
2024:   if (flg) PetscCall(MatEqual(b, d, &flg));
2025:   PetscCallMPI(MPIU_Allreduce(&flg, flag, 1, MPI_C_BOOL, MPI_LAND, PetscObjectComm((PetscObject)A)));
2026:   PetscFunctionReturn(PETSC_SUCCESS);
2027: }

2029: static PetscErrorCode MatCopy_MPIAIJ(Mat A, Mat B, MatStructure str)
2030: {
2031:   Mat_MPIAIJ *a = (Mat_MPIAIJ *)A->data;
2032:   Mat_MPIAIJ *b = (Mat_MPIAIJ *)B->data;

2034:   PetscFunctionBegin;
2035:   /* If the two matrices don't have the same copy implementation, they aren't compatible for fast copy. */
2036:   if ((str != SAME_NONZERO_PATTERN) || (A->ops->copy != B->ops->copy)) {
2037:     /* because of the column compression in the off-processor part of the matrix a->B,
2038:        the number of columns in a->B and b->B may be different, hence we cannot call
2039:        the MatCopy() directly on the two parts. If need be, we can provide a more
2040:        efficient copy than the MatCopy_Basic() by first uncompressing the a->B matrices
2041:        then copying the submatrices */
2042:     PetscCall(MatCopy_Basic(A, B, str));
2043:   } else {
2044:     PetscCall(MatCopy(a->A, b->A, str));
2045:     PetscCall(MatCopy(a->B, b->B, str));
2046:   }
2047:   PetscCall(PetscObjectStateIncrease((PetscObject)B));
2048:   PetscFunctionReturn(PETSC_SUCCESS);
2049: }

2051: /*
2052:    Computes the number of nonzeros per row needed for preallocation when X and Y
2053:    have different nonzero structure.
2054: */
2055: 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)
2056: {
2057:   PetscInt i, j, k, nzx, nzy;

2059:   PetscFunctionBegin;
2060:   /* Set the number of nonzeros in the new matrix */
2061:   for (i = 0; i < m; i++) {
2062:     const PetscInt *xjj = PetscSafePointerPlusOffset(xj, xi[i]), *yjj = PetscSafePointerPlusOffset(yj, yi[i]);
2063:     nzx    = xi[i + 1] - xi[i];
2064:     nzy    = yi[i + 1] - yi[i];
2065:     nnz[i] = 0;
2066:     for (j = 0, k = 0; j < nzx; j++) {                                /* Point in X */
2067:       for (; k < nzy && yltog[yjj[k]] < xltog[xjj[j]]; k++) nnz[i]++; /* Catch up to X */
2068:       if (k < nzy && yltog[yjj[k]] == xltog[xjj[j]]) k++;             /* Skip duplicate */
2069:       nnz[i]++;
2070:     }
2071:     for (; k < nzy; k++) nnz[i]++;
2072:   }
2073:   PetscFunctionReturn(PETSC_SUCCESS);
2074: }

2076: /* This is the same as MatAXPYGetPreallocation_SeqAIJ, except that the local-to-global map is provided */
2077: static PetscErrorCode MatAXPYGetPreallocation_MPIAIJ(Mat Y, const PetscInt *yltog, Mat X, const PetscInt *xltog, PetscInt *nnz)
2078: {
2079:   PetscInt    m = Y->rmap->N;
2080:   Mat_SeqAIJ *x = (Mat_SeqAIJ *)X->data;
2081:   Mat_SeqAIJ *y = (Mat_SeqAIJ *)Y->data;

2083:   PetscFunctionBegin;
2084:   PetscCall(MatAXPYGetPreallocation_MPIX_private(m, x->i, x->j, xltog, y->i, y->j, yltog, nnz));
2085:   PetscFunctionReturn(PETSC_SUCCESS);
2086: }

2088: static PetscErrorCode MatAXPY_MPIAIJ(Mat Y, PetscScalar a, Mat X, MatStructure str)
2089: {
2090:   Mat_MPIAIJ *xx = (Mat_MPIAIJ *)X->data, *yy = (Mat_MPIAIJ *)Y->data;

2092:   PetscFunctionBegin;
2093:   if (str == SAME_NONZERO_PATTERN) {
2094:     PetscCall(MatAXPY(yy->A, a, xx->A, str));
2095:     PetscCall(MatAXPY(yy->B, a, xx->B, str));
2096:   } else if (str == SUBSET_NONZERO_PATTERN) { /* nonzeros of X is a subset of Y's */
2097:     PetscCall(MatAXPY_Basic(Y, a, X, str));
2098:   } else {
2099:     Mat       B;
2100:     PetscInt *nnz_d, *nnz_o;

2102:     PetscCall(PetscMalloc1(yy->A->rmap->N, &nnz_d));
2103:     PetscCall(PetscMalloc1(yy->B->rmap->N, &nnz_o));
2104:     PetscCall(MatCreate(PetscObjectComm((PetscObject)Y), &B));
2105:     PetscCall(PetscObjectSetName((PetscObject)B, ((PetscObject)Y)->name));
2106:     PetscCall(MatSetLayouts(B, Y->rmap, Y->cmap));
2107:     PetscCall(MatSetType(B, ((PetscObject)Y)->type_name));
2108:     PetscCall(MatAXPYGetPreallocation_SeqAIJ(yy->A, xx->A, nnz_d));
2109:     PetscCall(MatAXPYGetPreallocation_MPIAIJ(yy->B, yy->garray, xx->B, xx->garray, nnz_o));
2110:     PetscCall(MatMPIAIJSetPreallocation(B, 0, nnz_d, 0, nnz_o));
2111:     PetscCall(MatAXPY_BasicWithPreallocation(B, Y, a, X, str));
2112:     PetscCall(MatHeaderMerge(Y, &B));
2113:     PetscCall(PetscFree(nnz_d));
2114:     PetscCall(PetscFree(nnz_o));
2115:   }
2116:   PetscFunctionReturn(PETSC_SUCCESS);
2117: }

2119: PETSC_INTERN PetscErrorCode MatConjugate_SeqAIJ(Mat);

2121: static PetscErrorCode MatConjugate_MPIAIJ(Mat mat)
2122: {
2123:   Mat_MPIAIJ *aij = (Mat_MPIAIJ *)mat->data;

2125:   PetscFunctionBegin;
2126:   PetscCall(MatConjugate_SeqAIJ(aij->A));
2127:   PetscCall(MatConjugate_SeqAIJ(aij->B));
2128:   PetscFunctionReturn(PETSC_SUCCESS);
2129: }

2131: static PetscErrorCode MatRealPart_MPIAIJ(Mat A)
2132: {
2133:   Mat_MPIAIJ *a = (Mat_MPIAIJ *)A->data;

2135:   PetscFunctionBegin;
2136:   PetscCall(MatRealPart(a->A));
2137:   PetscCall(MatRealPart(a->B));
2138:   PetscFunctionReturn(PETSC_SUCCESS);
2139: }

2141: static PetscErrorCode MatImaginaryPart_MPIAIJ(Mat A)
2142: {
2143:   Mat_MPIAIJ *a = (Mat_MPIAIJ *)A->data;

2145:   PetscFunctionBegin;
2146:   PetscCall(MatImaginaryPart(a->A));
2147:   PetscCall(MatImaginaryPart(a->B));
2148:   PetscFunctionReturn(PETSC_SUCCESS);
2149: }

2151: static PetscErrorCode MatGetRowMaxAbs_MPIAIJ(Mat A, Vec v, PetscInt idx[])
2152: {
2153:   Mat_MPIAIJ        *a = (Mat_MPIAIJ *)A->data;
2154:   PetscInt           i, *idxb = NULL, m = A->rmap->n;
2155:   PetscScalar       *vv;
2156:   Vec                vB, vA;
2157:   const PetscScalar *va, *vb;

2159:   PetscFunctionBegin;
2160:   PetscCall(MatCreateVecs(a->A, NULL, &vA));
2161:   PetscCall(MatGetRowMaxAbs(a->A, vA, idx));

2163:   PetscCall(VecGetArrayRead(vA, &va));
2164:   if (idx) {
2165:     for (i = 0; i < m; i++) {
2166:       if (PetscAbsScalar(va[i])) idx[i] += A->cmap->rstart;
2167:     }
2168:   }

2170:   PetscCall(MatCreateVecs(a->B, NULL, &vB));
2171:   PetscCall(PetscMalloc1(m, &idxb));
2172:   PetscCall(MatGetRowMaxAbs(a->B, vB, idxb));

2174:   PetscCall(VecGetArrayWrite(v, &vv));
2175:   PetscCall(VecGetArrayRead(vB, &vb));
2176:   for (i = 0; i < m; i++) {
2177:     if (PetscAbsScalar(va[i]) < PetscAbsScalar(vb[i])) {
2178:       vv[i] = vb[i];
2179:       if (idx) idx[i] = a->garray[idxb[i]];
2180:     } else {
2181:       vv[i] = va[i];
2182:       if (idx && PetscAbsScalar(va[i]) == PetscAbsScalar(vb[i]) && idxb[i] != -1 && idx[i] > a->garray[idxb[i]]) idx[i] = a->garray[idxb[i]];
2183:     }
2184:   }
2185:   PetscCall(VecRestoreArrayWrite(v, &vv));
2186:   PetscCall(VecRestoreArrayRead(vA, &va));
2187:   PetscCall(VecRestoreArrayRead(vB, &vb));
2188:   PetscCall(PetscFree(idxb));
2189:   PetscCall(VecDestroy(&vA));
2190:   PetscCall(VecDestroy(&vB));
2191:   PetscFunctionReturn(PETSC_SUCCESS);
2192: }

2194: static PetscErrorCode MatGetRowSumAbs_MPIAIJ(Mat A, Vec v)
2195: {
2196:   Mat_MPIAIJ *a = (Mat_MPIAIJ *)A->data;
2197:   Vec         vB, vA;

2199:   PetscFunctionBegin;
2200:   PetscCall(MatCreateVecs(a->A, NULL, &vA));
2201:   PetscCall(MatGetRowSumAbs(a->A, vA));
2202:   PetscCall(MatCreateVecs(a->B, NULL, &vB));
2203:   PetscCall(MatGetRowSumAbs(a->B, vB));
2204:   PetscCall(VecAXPY(vA, 1.0, vB));
2205:   PetscCall(VecDestroy(&vB));
2206:   PetscCall(VecCopy(vA, v));
2207:   PetscCall(VecDestroy(&vA));
2208:   PetscFunctionReturn(PETSC_SUCCESS);
2209: }

2211: static PetscErrorCode MatGetRowMinAbs_MPIAIJ(Mat A, Vec v, PetscInt idx[])
2212: {
2213:   Mat_MPIAIJ        *mat = (Mat_MPIAIJ *)A->data;
2214:   PetscInt           m = A->rmap->n, n = A->cmap->n;
2215:   PetscInt           cstart = A->cmap->rstart, cend = A->cmap->rend;
2216:   PetscInt          *cmap = mat->garray;
2217:   PetscInt          *diagIdx, *offdiagIdx;
2218:   Vec                diagV, offdiagV;
2219:   PetscScalar       *a, *diagA, *offdiagA;
2220:   const PetscScalar *ba, *bav;
2221:   PetscInt           r, j, col, ncols, *bi, *bj;
2222:   Mat                B = mat->B;
2223:   Mat_SeqAIJ        *b = (Mat_SeqAIJ *)B->data;

2225:   PetscFunctionBegin;
2226:   /* When a process holds entire A and other processes have no entry */
2227:   if (A->cmap->N == n) {
2228:     PetscCall(VecGetArrayWrite(v, &diagA));
2229:     PetscCall(VecCreateSeqWithArray(PETSC_COMM_SELF, 1, m, diagA, &diagV));
2230:     PetscCall(MatGetRowMinAbs(mat->A, diagV, idx));
2231:     PetscCall(VecDestroy(&diagV));
2232:     PetscCall(VecRestoreArrayWrite(v, &diagA));
2233:     PetscFunctionReturn(PETSC_SUCCESS);
2234:   } else if (n == 0) {
2235:     if (m) {
2236:       PetscCall(VecGetArrayWrite(v, &a));
2237:       for (r = 0; r < m; r++) {
2238:         a[r] = 0.0;
2239:         if (idx) idx[r] = -1;
2240:       }
2241:       PetscCall(VecRestoreArrayWrite(v, &a));
2242:     }
2243:     PetscFunctionReturn(PETSC_SUCCESS);
2244:   }

2246:   PetscCall(PetscMalloc2(m, &diagIdx, m, &offdiagIdx));
2247:   PetscCall(VecCreateSeq(PETSC_COMM_SELF, m, &diagV));
2248:   PetscCall(VecCreateSeq(PETSC_COMM_SELF, m, &offdiagV));
2249:   PetscCall(MatGetRowMinAbs(mat->A, diagV, diagIdx));

2251:   /* Get offdiagIdx[] for implicit 0.0 */
2252:   PetscCall(MatSeqAIJGetArrayRead(B, &bav));
2253:   ba = bav;
2254:   bi = b->i;
2255:   bj = b->j;
2256:   PetscCall(VecGetArrayWrite(offdiagV, &offdiagA));
2257:   for (r = 0; r < m; r++) {
2258:     ncols = bi[r + 1] - bi[r];
2259:     if (ncols == A->cmap->N - n) { /* Brow is dense */
2260:       offdiagA[r]   = *ba;
2261:       offdiagIdx[r] = cmap[0];
2262:     } else { /* Brow is sparse so already KNOW maximum is 0.0 or higher */
2263:       offdiagA[r] = 0.0;

2265:       /* Find first hole in the cmap */
2266:       for (j = 0; j < ncols; j++) {
2267:         col = cmap[bj[j]]; /* global column number = cmap[B column number] */
2268:         if (col > j && j < cstart) {
2269:           offdiagIdx[r] = j; /* global column number of first implicit 0.0 */
2270:           break;
2271:         } else if (col > j + n && j >= cstart) {
2272:           offdiagIdx[r] = j + n; /* global column number of first implicit 0.0 */
2273:           break;
2274:         }
2275:       }
2276:       if (j == ncols && ncols < A->cmap->N - n) {
2277:         /* a hole is outside compressed Bcols */
2278:         if (ncols == 0) {
2279:           if (cstart) {
2280:             offdiagIdx[r] = 0;
2281:           } else offdiagIdx[r] = cend;
2282:         } else { /* ncols > 0 */
2283:           offdiagIdx[r] = cmap[ncols - 1] + 1;
2284:           if (offdiagIdx[r] == cstart) offdiagIdx[r] += n;
2285:         }
2286:       }
2287:     }

2289:     for (j = 0; j < ncols; j++) {
2290:       if (PetscAbsScalar(offdiagA[r]) > PetscAbsScalar(*ba)) {
2291:         offdiagA[r]   = *ba;
2292:         offdiagIdx[r] = cmap[*bj];
2293:       }
2294:       ba++;
2295:       bj++;
2296:     }
2297:   }

2299:   PetscCall(VecGetArrayWrite(v, &a));
2300:   PetscCall(VecGetArrayRead(diagV, (const PetscScalar **)&diagA));
2301:   for (r = 0; r < m; ++r) {
2302:     if (PetscAbsScalar(diagA[r]) < PetscAbsScalar(offdiagA[r])) {
2303:       a[r] = diagA[r];
2304:       if (idx) idx[r] = cstart + diagIdx[r];
2305:     } else if (PetscAbsScalar(diagA[r]) == PetscAbsScalar(offdiagA[r])) {
2306:       a[r] = diagA[r];
2307:       if (idx) {
2308:         if (cstart + diagIdx[r] <= offdiagIdx[r]) {
2309:           idx[r] = cstart + diagIdx[r];
2310:         } else idx[r] = offdiagIdx[r];
2311:       }
2312:     } else {
2313:       a[r] = offdiagA[r];
2314:       if (idx) idx[r] = offdiagIdx[r];
2315:     }
2316:   }
2317:   PetscCall(MatSeqAIJRestoreArrayRead(B, &bav));
2318:   PetscCall(VecRestoreArrayWrite(v, &a));
2319:   PetscCall(VecRestoreArrayRead(diagV, (const PetscScalar **)&diagA));
2320:   PetscCall(VecRestoreArrayWrite(offdiagV, &offdiagA));
2321:   PetscCall(VecDestroy(&diagV));
2322:   PetscCall(VecDestroy(&offdiagV));
2323:   PetscCall(PetscFree2(diagIdx, offdiagIdx));
2324:   PetscFunctionReturn(PETSC_SUCCESS);
2325: }

2327: static PetscErrorCode MatGetRowMin_MPIAIJ(Mat A, Vec v, PetscInt idx[])
2328: {
2329:   Mat_MPIAIJ        *mat = (Mat_MPIAIJ *)A->data;
2330:   PetscInt           m = A->rmap->n, n = A->cmap->n;
2331:   PetscInt           cstart = A->cmap->rstart, cend = A->cmap->rend;
2332:   PetscInt          *cmap = mat->garray;
2333:   PetscInt          *diagIdx, *offdiagIdx;
2334:   Vec                diagV, offdiagV;
2335:   PetscScalar       *a, *diagA, *offdiagA;
2336:   const PetscScalar *ba, *bav;
2337:   PetscInt           r, j, col, ncols, *bi, *bj;
2338:   Mat                B = mat->B;
2339:   Mat_SeqAIJ        *b = (Mat_SeqAIJ *)B->data;

2341:   PetscFunctionBegin;
2342:   /* When a process holds entire A and other processes have no entry */
2343:   if (A->cmap->N == n) {
2344:     PetscCall(VecGetArrayWrite(v, &diagA));
2345:     PetscCall(VecCreateSeqWithArray(PETSC_COMM_SELF, 1, m, diagA, &diagV));
2346:     PetscCall(MatGetRowMin(mat->A, diagV, idx));
2347:     PetscCall(VecDestroy(&diagV));
2348:     PetscCall(VecRestoreArrayWrite(v, &diagA));
2349:     PetscFunctionReturn(PETSC_SUCCESS);
2350:   } else if (n == 0) {
2351:     if (m) {
2352:       PetscCall(VecGetArrayWrite(v, &a));
2353:       for (r = 0; r < m; r++) {
2354:         a[r] = PETSC_MAX_REAL;
2355:         if (idx) idx[r] = -1;
2356:       }
2357:       PetscCall(VecRestoreArrayWrite(v, &a));
2358:     }
2359:     PetscFunctionReturn(PETSC_SUCCESS);
2360:   }

2362:   PetscCall(PetscCalloc2(m, &diagIdx, m, &offdiagIdx));
2363:   PetscCall(VecCreateSeq(PETSC_COMM_SELF, m, &diagV));
2364:   PetscCall(VecCreateSeq(PETSC_COMM_SELF, m, &offdiagV));
2365:   PetscCall(MatGetRowMin(mat->A, diagV, diagIdx));

2367:   /* Get offdiagIdx[] for implicit 0.0 */
2368:   PetscCall(MatSeqAIJGetArrayRead(B, &bav));
2369:   ba = bav;
2370:   bi = b->i;
2371:   bj = b->j;
2372:   PetscCall(VecGetArrayWrite(offdiagV, &offdiagA));
2373:   for (r = 0; r < m; r++) {
2374:     ncols = bi[r + 1] - bi[r];
2375:     if (ncols == A->cmap->N - n) { /* Brow is dense */
2376:       offdiagA[r]   = *ba;
2377:       offdiagIdx[r] = cmap[0];
2378:     } else { /* Brow is sparse so already KNOW maximum is 0.0 or higher */
2379:       offdiagA[r] = 0.0;

2381:       /* Find first hole in the cmap */
2382:       for (j = 0; j < ncols; j++) {
2383:         col = cmap[bj[j]]; /* global column number = cmap[B column number] */
2384:         if (col > j && j < cstart) {
2385:           offdiagIdx[r] = j; /* global column number of first implicit 0.0 */
2386:           break;
2387:         } else if (col > j + n && j >= cstart) {
2388:           offdiagIdx[r] = j + n; /* global column number of first implicit 0.0 */
2389:           break;
2390:         }
2391:       }
2392:       if (j == ncols && ncols < A->cmap->N - n) {
2393:         /* a hole is outside compressed Bcols */
2394:         if (ncols == 0) {
2395:           if (cstart) {
2396:             offdiagIdx[r] = 0;
2397:           } else offdiagIdx[r] = cend;
2398:         } else { /* ncols > 0 */
2399:           offdiagIdx[r] = cmap[ncols - 1] + 1;
2400:           if (offdiagIdx[r] == cstart) offdiagIdx[r] += n;
2401:         }
2402:       }
2403:     }

2405:     for (j = 0; j < ncols; j++) {
2406:       if (PetscRealPart(offdiagA[r]) > PetscRealPart(*ba)) {
2407:         offdiagA[r]   = *ba;
2408:         offdiagIdx[r] = cmap[*bj];
2409:       }
2410:       ba++;
2411:       bj++;
2412:     }
2413:   }

2415:   PetscCall(VecGetArrayWrite(v, &a));
2416:   PetscCall(VecGetArrayRead(diagV, (const PetscScalar **)&diagA));
2417:   for (r = 0; r < m; ++r) {
2418:     if (PetscRealPart(diagA[r]) < PetscRealPart(offdiagA[r])) {
2419:       a[r] = diagA[r];
2420:       if (idx) idx[r] = cstart + diagIdx[r];
2421:     } else if (PetscRealPart(diagA[r]) == PetscRealPart(offdiagA[r])) {
2422:       a[r] = diagA[r];
2423:       if (idx) {
2424:         if (cstart + diagIdx[r] <= offdiagIdx[r]) {
2425:           idx[r] = cstart + diagIdx[r];
2426:         } else idx[r] = offdiagIdx[r];
2427:       }
2428:     } else {
2429:       a[r] = offdiagA[r];
2430:       if (idx) idx[r] = offdiagIdx[r];
2431:     }
2432:   }
2433:   PetscCall(MatSeqAIJRestoreArrayRead(B, &bav));
2434:   PetscCall(VecRestoreArrayWrite(v, &a));
2435:   PetscCall(VecRestoreArrayRead(diagV, (const PetscScalar **)&diagA));
2436:   PetscCall(VecRestoreArrayWrite(offdiagV, &offdiagA));
2437:   PetscCall(VecDestroy(&diagV));
2438:   PetscCall(VecDestroy(&offdiagV));
2439:   PetscCall(PetscFree2(diagIdx, offdiagIdx));
2440:   PetscFunctionReturn(PETSC_SUCCESS);
2441: }

2443: static PetscErrorCode MatGetRowMax_MPIAIJ(Mat A, Vec v, PetscInt idx[])
2444: {
2445:   Mat_MPIAIJ        *mat = (Mat_MPIAIJ *)A->data;
2446:   PetscInt           m = A->rmap->n, n = A->cmap->n;
2447:   PetscInt           cstart = A->cmap->rstart, cend = A->cmap->rend;
2448:   PetscInt          *cmap = mat->garray;
2449:   PetscInt          *diagIdx, *offdiagIdx;
2450:   Vec                diagV, offdiagV;
2451:   PetscScalar       *a, *diagA, *offdiagA;
2452:   const PetscScalar *ba, *bav;
2453:   PetscInt           r, j, col, ncols, *bi, *bj;
2454:   Mat                B = mat->B;
2455:   Mat_SeqAIJ        *b = (Mat_SeqAIJ *)B->data;

2457:   PetscFunctionBegin;
2458:   /* When a process holds entire A and other processes have no entry */
2459:   if (A->cmap->N == n) {
2460:     PetscCall(VecGetArrayWrite(v, &diagA));
2461:     PetscCall(VecCreateSeqWithArray(PETSC_COMM_SELF, 1, m, diagA, &diagV));
2462:     PetscCall(MatGetRowMax(mat->A, diagV, idx));
2463:     PetscCall(VecDestroy(&diagV));
2464:     PetscCall(VecRestoreArrayWrite(v, &diagA));
2465:     PetscFunctionReturn(PETSC_SUCCESS);
2466:   } else if (n == 0) {
2467:     if (m) {
2468:       PetscCall(VecGetArrayWrite(v, &a));
2469:       for (r = 0; r < m; r++) {
2470:         a[r] = PETSC_MIN_REAL;
2471:         if (idx) idx[r] = -1;
2472:       }
2473:       PetscCall(VecRestoreArrayWrite(v, &a));
2474:     }
2475:     PetscFunctionReturn(PETSC_SUCCESS);
2476:   }

2478:   PetscCall(PetscMalloc2(m, &diagIdx, m, &offdiagIdx));
2479:   PetscCall(VecCreateSeq(PETSC_COMM_SELF, m, &diagV));
2480:   PetscCall(VecCreateSeq(PETSC_COMM_SELF, m, &offdiagV));
2481:   PetscCall(MatGetRowMax(mat->A, diagV, diagIdx));

2483:   /* Get offdiagIdx[] for implicit 0.0 */
2484:   PetscCall(MatSeqAIJGetArrayRead(B, &bav));
2485:   ba = bav;
2486:   bi = b->i;
2487:   bj = b->j;
2488:   PetscCall(VecGetArrayWrite(offdiagV, &offdiagA));
2489:   for (r = 0; r < m; r++) {
2490:     ncols = bi[r + 1] - bi[r];
2491:     if (ncols == A->cmap->N - n) { /* Brow is dense */
2492:       offdiagA[r]   = *ba;
2493:       offdiagIdx[r] = cmap[0];
2494:     } else { /* Brow is sparse so already KNOW maximum is 0.0 or higher */
2495:       offdiagA[r] = 0.0;

2497:       /* Find first hole in the cmap */
2498:       for (j = 0; j < ncols; j++) {
2499:         col = cmap[bj[j]]; /* global column number = cmap[B column number] */
2500:         if (col > j && j < cstart) {
2501:           offdiagIdx[r] = j; /* global column number of first implicit 0.0 */
2502:           break;
2503:         } else if (col > j + n && j >= cstart) {
2504:           offdiagIdx[r] = j + n; /* global column number of first implicit 0.0 */
2505:           break;
2506:         }
2507:       }
2508:       if (j == ncols && ncols < A->cmap->N - n) {
2509:         /* a hole is outside compressed Bcols */
2510:         if (ncols == 0) {
2511:           if (cstart) {
2512:             offdiagIdx[r] = 0;
2513:           } else offdiagIdx[r] = cend;
2514:         } else { /* ncols > 0 */
2515:           offdiagIdx[r] = cmap[ncols - 1] + 1;
2516:           if (offdiagIdx[r] == cstart) offdiagIdx[r] += n;
2517:         }
2518:       }
2519:     }

2521:     for (j = 0; j < ncols; j++) {
2522:       if (PetscRealPart(offdiagA[r]) < PetscRealPart(*ba)) {
2523:         offdiagA[r]   = *ba;
2524:         offdiagIdx[r] = cmap[*bj];
2525:       }
2526:       ba++;
2527:       bj++;
2528:     }
2529:   }

2531:   PetscCall(VecGetArrayWrite(v, &a));
2532:   PetscCall(VecGetArrayRead(diagV, (const PetscScalar **)&diagA));
2533:   for (r = 0; r < m; ++r) {
2534:     if (PetscRealPart(diagA[r]) > PetscRealPart(offdiagA[r])) {
2535:       a[r] = diagA[r];
2536:       if (idx) idx[r] = cstart + diagIdx[r];
2537:     } else if (PetscRealPart(diagA[r]) == PetscRealPart(offdiagA[r])) {
2538:       a[r] = diagA[r];
2539:       if (idx) {
2540:         if (cstart + diagIdx[r] <= offdiagIdx[r]) {
2541:           idx[r] = cstart + diagIdx[r];
2542:         } else idx[r] = offdiagIdx[r];
2543:       }
2544:     } else {
2545:       a[r] = offdiagA[r];
2546:       if (idx) idx[r] = offdiagIdx[r];
2547:     }
2548:   }
2549:   PetscCall(MatSeqAIJRestoreArrayRead(B, &bav));
2550:   PetscCall(VecRestoreArrayWrite(v, &a));
2551:   PetscCall(VecRestoreArrayRead(diagV, (const PetscScalar **)&diagA));
2552:   PetscCall(VecRestoreArrayWrite(offdiagV, &offdiagA));
2553:   PetscCall(VecDestroy(&diagV));
2554:   PetscCall(VecDestroy(&offdiagV));
2555:   PetscCall(PetscFree2(diagIdx, offdiagIdx));
2556:   PetscFunctionReturn(PETSC_SUCCESS);
2557: }

2559: PetscErrorCode MatGetSeqNonzeroStructure_MPIAIJ(Mat mat, Mat *newmat)
2560: {
2561:   Mat *dummy;

2563:   PetscFunctionBegin;
2564:   PetscCall(MatCreateSubMatrix_MPIAIJ_All(mat, MAT_DO_NOT_GET_VALUES, MAT_INITIAL_MATRIX, &dummy));
2565:   *newmat = *dummy;
2566:   PetscCall(PetscFree(dummy));
2567:   PetscFunctionReturn(PETSC_SUCCESS);
2568: }

2570: static PetscErrorCode MatInvertBlockDiagonal_MPIAIJ(Mat A, const PetscScalar **values)
2571: {
2572:   Mat_MPIAIJ *a = (Mat_MPIAIJ *)A->data;

2574:   PetscFunctionBegin;
2575:   PetscCall(MatInvertBlockDiagonal(a->A, values));
2576:   A->factorerrortype = a->A->factorerrortype;
2577:   PetscFunctionReturn(PETSC_SUCCESS);
2578: }

2580: static PetscErrorCode MatSetRandom_MPIAIJ(Mat x, PetscRandom rctx)
2581: {
2582:   Mat_MPIAIJ *aij = (Mat_MPIAIJ *)x->data;

2584:   PetscFunctionBegin;
2585:   PetscCheck(x->assembled || x->preallocated, PetscObjectComm((PetscObject)x), PETSC_ERR_ARG_WRONGSTATE, "MatSetRandom on an unassembled and unpreallocated MATMPIAIJ is not allowed");
2586:   PetscCall(MatSetRandom(aij->A, rctx));
2587:   if (x->assembled) {
2588:     PetscCall(MatSetRandom(aij->B, rctx));
2589:   } else {
2590:     PetscCall(MatSetRandomSkipColumnRange_SeqAIJ_Private(aij->B, x->cmap->rstart, x->cmap->rend, rctx));
2591:   }
2592:   PetscCall(MatAssemblyBegin(x, MAT_FINAL_ASSEMBLY));
2593:   PetscCall(MatAssemblyEnd(x, MAT_FINAL_ASSEMBLY));
2594:   PetscFunctionReturn(PETSC_SUCCESS);
2595: }

2597: static PetscErrorCode MatMPIAIJSetUseScalableIncreaseOverlap_MPIAIJ(Mat A, PetscBool sc)
2598: {
2599:   PetscFunctionBegin;
2600:   if (sc) A->ops->increaseoverlap = MatIncreaseOverlap_MPIAIJ_Scalable;
2601:   else A->ops->increaseoverlap = MatIncreaseOverlap_MPIAIJ;
2602:   PetscFunctionReturn(PETSC_SUCCESS);
2603: }

2605: /*@
2606:   MatMPIAIJGetNumberNonzeros - gets the number of nonzeros in the matrix on this MPI rank

2608:   Not Collective

2610:   Input Parameter:
2611: . A - the matrix

2613:   Output Parameter:
2614: . nz - the number of nonzeros

2616:   Level: advanced

2618: .seealso: [](ch_matrices), `Mat`, `MATMPIAIJ`
2619: @*/
2620: PetscErrorCode MatMPIAIJGetNumberNonzeros(Mat A, PetscCount *nz)
2621: {
2622:   Mat_MPIAIJ *maij = (Mat_MPIAIJ *)A->data;
2623:   Mat_SeqAIJ *aaij = (Mat_SeqAIJ *)maij->A->data, *baij = (Mat_SeqAIJ *)maij->B->data;
2624:   PetscBool   isaij;

2626:   PetscFunctionBegin;
2627:   PetscCall(PetscObjectBaseTypeCompare((PetscObject)A, MATMPIAIJ, &isaij));
2628:   PetscCheck(isaij, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "Not for type %s", ((PetscObject)A)->type_name);
2629:   *nz = aaij->i[A->rmap->n] + baij->i[A->rmap->n];
2630:   PetscFunctionReturn(PETSC_SUCCESS);
2631: }

2633: /*@
2634:   MatMPIAIJSetUseScalableIncreaseOverlap - Determine if the matrix uses a scalable algorithm to compute the overlap

2636:   Collective

2638:   Input Parameters:
2639: + A  - the matrix
2640: - sc - `PETSC_TRUE` indicates use the scalable algorithm (default is not to use the scalable algorithm)

2642:   Level: advanced

2644: .seealso: [](ch_matrices), `Mat`, `MATMPIAIJ`
2645: @*/
2646: PetscErrorCode MatMPIAIJSetUseScalableIncreaseOverlap(Mat A, PetscBool sc)
2647: {
2648:   PetscFunctionBegin;
2649:   PetscTryMethod(A, "MatMPIAIJSetUseScalableIncreaseOverlap_C", (Mat, PetscBool), (A, sc));
2650:   PetscFunctionReturn(PETSC_SUCCESS);
2651: }

2653: PetscErrorCode MatSetFromOptions_MPIAIJ(Mat A, PetscOptionItems PetscOptionsObject)
2654: {
2655:   PetscBool sc = PETSC_FALSE, flg;

2657:   PetscFunctionBegin;
2658:   PetscOptionsHeadBegin(PetscOptionsObject, "MPIAIJ options");
2659:   if (A->ops->increaseoverlap == MatIncreaseOverlap_MPIAIJ_Scalable) sc = PETSC_TRUE;
2660:   PetscCall(PetscOptionsBool("-mat_increase_overlap_scalable", "Use a scalable algorithm to compute the overlap", "MatIncreaseOverlap", sc, &sc, &flg));
2661:   if (flg) PetscCall(MatMPIAIJSetUseScalableIncreaseOverlap(A, sc));
2662:   PetscOptionsHeadEnd();
2663:   PetscFunctionReturn(PETSC_SUCCESS);
2664: }

2666: static PetscErrorCode MatShift_MPIAIJ(Mat Y, PetscScalar a)
2667: {
2668:   Mat_MPIAIJ *maij = (Mat_MPIAIJ *)Y->data;
2669:   Mat_SeqAIJ *aij  = (Mat_SeqAIJ *)maij->A->data;

2671:   PetscFunctionBegin;
2672:   if (!Y->preallocated) {
2673:     PetscCall(MatMPIAIJSetPreallocation(Y, 1, NULL, 0, NULL));
2674:   } else if (!aij->nz) { /* It does not matter if diagonals of Y only partially lie in maij->A. We just need an estimated preallocation. */
2675:     PetscInt nonew = aij->nonew;
2676:     PetscCall(MatSeqAIJSetPreallocation(maij->A, 1, NULL));
2677:     aij->nonew = nonew;
2678:   }
2679:   PetscCall(MatShift_Basic(Y, a));
2680:   PetscFunctionReturn(PETSC_SUCCESS);
2681: }

2683: static PetscErrorCode MatInvertVariableBlockDiagonal_MPIAIJ(Mat A, PetscInt nblocks, const PetscInt *bsizes, PetscScalar *diag)
2684: {
2685:   Mat_MPIAIJ *a = (Mat_MPIAIJ *)A->data;

2687:   PetscFunctionBegin;
2688:   PetscCall(MatInvertVariableBlockDiagonal(a->A, nblocks, bsizes, diag));
2689:   PetscFunctionReturn(PETSC_SUCCESS);
2690: }

2692: static PetscErrorCode MatEliminateZeros_MPIAIJ(Mat A, PetscBool keep)
2693: {
2694:   Mat_MPIAIJ *a = (Mat_MPIAIJ *)A->data;

2696:   PetscFunctionBegin;
2697:   PetscCall(MatEliminateZeros_SeqAIJ(a->A, keep));        // possibly keep zero diagonal coefficients
2698:   PetscCall(MatEliminateZeros_SeqAIJ(a->B, PETSC_FALSE)); // never keep zero diagonal coefficients
2699:   PetscFunctionReturn(PETSC_SUCCESS);
2700: }

2702: static struct _MatOps MatOps_Values = {MatSetValues_MPIAIJ,
2703:                                        MatGetRow_MPIAIJ,
2704:                                        MatRestoreRow_MPIAIJ,
2705:                                        MatMult_MPIAIJ,
2706:                                        /* 4*/ MatMultAdd_MPIAIJ,
2707:                                        MatMultTranspose_MPIAIJ,
2708:                                        MatMultTransposeAdd_MPIAIJ,
2709:                                        NULL,
2710:                                        NULL,
2711:                                        NULL,
2712:                                        /*10*/ NULL,
2713:                                        NULL,
2714:                                        NULL,
2715:                                        MatSOR_MPIAIJ,
2716:                                        MatTranspose_MPIAIJ,
2717:                                        /*15*/ MatGetInfo_MPIAIJ,
2718:                                        MatEqual_MPIAIJ,
2719:                                        MatGetDiagonal_MPIAIJ,
2720:                                        MatDiagonalScale_MPIAIJ,
2721:                                        MatNorm_MPIAIJ,
2722:                                        /*20*/ MatAssemblyBegin_MPIAIJ,
2723:                                        MatAssemblyEnd_MPIAIJ,
2724:                                        MatSetOption_MPIAIJ,
2725:                                        MatZeroEntries_MPIAIJ,
2726:                                        /*24*/ MatZeroRows_MPIAIJ,
2727:                                        NULL,
2728:                                        NULL,
2729:                                        NULL,
2730:                                        NULL,
2731:                                        /*29*/ MatSetUp_MPI_Hash,
2732:                                        NULL,
2733:                                        NULL,
2734:                                        MatGetDiagonalBlock_MPIAIJ,
2735:                                        NULL,
2736:                                        /*34*/ MatDuplicate_MPIAIJ,
2737:                                        NULL,
2738:                                        NULL,
2739:                                        NULL,
2740:                                        NULL,
2741:                                        /*39*/ MatAXPY_MPIAIJ,
2742:                                        MatCreateSubMatrices_MPIAIJ,
2743:                                        MatIncreaseOverlap_MPIAIJ,
2744:                                        MatGetValues_MPIAIJ,
2745:                                        MatCopy_MPIAIJ,
2746:                                        /*44*/ MatGetRowMax_MPIAIJ,
2747:                                        MatScale_MPIAIJ,
2748:                                        MatShift_MPIAIJ,
2749:                                        MatDiagonalSet_MPIAIJ,
2750:                                        MatZeroRowsColumns_MPIAIJ,
2751:                                        /*49*/ MatSetRandom_MPIAIJ,
2752:                                        MatGetRowIJ_MPIAIJ,
2753:                                        MatRestoreRowIJ_MPIAIJ,
2754:                                        NULL,
2755:                                        NULL,
2756:                                        /*54*/ MatFDColoringCreate_MPIXAIJ,
2757:                                        NULL,
2758:                                        MatSetUnfactored_MPIAIJ,
2759:                                        MatPermute_MPIAIJ,
2760:                                        NULL,
2761:                                        /*59*/ MatCreateSubMatrix_MPIAIJ,
2762:                                        MatDestroy_MPIAIJ,
2763:                                        MatView_MPIAIJ,
2764:                                        NULL,
2765:                                        NULL,
2766:                                        /*64*/ MatMatMatMultNumeric_MPIAIJ_MPIAIJ_MPIAIJ,
2767:                                        NULL,
2768:                                        NULL,
2769:                                        NULL,
2770:                                        MatGetRowMaxAbs_MPIAIJ,
2771:                                        /*69*/ MatGetRowMinAbs_MPIAIJ,
2772:                                        NULL,
2773:                                        NULL,
2774:                                        MatFDColoringApply_AIJ,
2775:                                        MatSetFromOptions_MPIAIJ,
2776:                                        MatFindZeroDiagonals_MPIAIJ,
2777:                                        /*75*/ NULL,
2778:                                        NULL,
2779:                                        NULL,
2780:                                        MatLoad_MPIAIJ,
2781:                                        NULL,
2782:                                        /*80*/ NULL,
2783:                                        NULL,
2784:                                        NULL,
2785:                                        /*83*/ NULL,
2786:                                        NULL,
2787:                                        MatMatMultNumeric_MPIAIJ_MPIAIJ,
2788:                                        MatPtAPNumeric_MPIAIJ_MPIAIJ,
2789:                                        NULL,
2790:                                        NULL,
2791:                                        /*89*/ MatBindToCPU_MPIAIJ,
2792:                                        MatProductSetFromOptions_MPIAIJ,
2793:                                        NULL,
2794:                                        NULL,
2795:                                        MatConjugate_MPIAIJ,
2796:                                        /*94*/ NULL,
2797:                                        MatSetValuesRow_MPIAIJ,
2798:                                        MatRealPart_MPIAIJ,
2799:                                        MatImaginaryPart_MPIAIJ,
2800:                                        NULL,
2801:                                        /*99*/ NULL,
2802:                                        NULL,
2803:                                        NULL,
2804:                                        MatGetRowMin_MPIAIJ,
2805:                                        NULL,
2806:                                        /*104*/ MatGetSeqNonzeroStructure_MPIAIJ,
2807:                                        NULL,
2808:                                        MatGetGhosts_MPIAIJ,
2809:                                        NULL,
2810:                                        NULL,
2811:                                        /*109*/ MatMultDiagonalBlock_MPIAIJ,
2812:                                        NULL,
2813:                                        NULL,
2814:                                        NULL,
2815:                                        MatGetMultiProcBlock_MPIAIJ,
2816:                                        /*114*/ MatFindNonzeroRows_MPIAIJ,
2817:                                        MatGetColumnReductions_MPIAIJ,
2818:                                        MatInvertBlockDiagonal_MPIAIJ,
2819:                                        MatInvertVariableBlockDiagonal_MPIAIJ,
2820:                                        MatCreateSubMatricesMPI_MPIAIJ,
2821:                                        /*119*/ NULL,
2822:                                        MatTransposeMatMultNumeric_MPIAIJ_MPIAIJ,
2823:                                        NULL,
2824:                                        NULL,
2825:                                        NULL,
2826:                                        /*124*/ NULL,
2827:                                        MatSetBlockSizes_MPIAIJ,
2828:                                        NULL,
2829:                                        MatFDColoringSetUp_MPIXAIJ,
2830:                                        MatFindOffBlockDiagonalEntries_MPIAIJ,
2831:                                        /*129*/ MatCreateMPIMatConcatenateSeqMat_MPIAIJ,
2832:                                        NULL,
2833:                                        NULL,
2834:                                        NULL,
2835:                                        MatCreateGraph_Simple_AIJ,
2836:                                        /*134*/ NULL,
2837:                                        MatEliminateZeros_MPIAIJ,
2838:                                        MatGetRowSumAbs_MPIAIJ,
2839:                                        NULL,
2840:                                        NULL,
2841:                                        /*139*/ NULL,
2842:                                        MatCopyHashToXAIJ_MPI_Hash,
2843:                                        MatGetCurrentMemType_MPIAIJ,
2844:                                        NULL,
2845:                                        MatADot_Default,
2846:                                        /*144*/ MatANorm_Default,
2847:                                        NULL,
2848:                                        NULL};

2850: static PetscErrorCode MatStoreValues_MPIAIJ(Mat mat)
2851: {
2852:   Mat_MPIAIJ *aij = (Mat_MPIAIJ *)mat->data;

2854:   PetscFunctionBegin;
2855:   PetscCall(MatStoreValues(aij->A));
2856:   PetscCall(MatStoreValues(aij->B));
2857:   PetscFunctionReturn(PETSC_SUCCESS);
2858: }

2860: static PetscErrorCode MatRetrieveValues_MPIAIJ(Mat mat)
2861: {
2862:   Mat_MPIAIJ *aij = (Mat_MPIAIJ *)mat->data;

2864:   PetscFunctionBegin;
2865:   PetscCall(MatRetrieveValues(aij->A));
2866:   PetscCall(MatRetrieveValues(aij->B));
2867:   PetscFunctionReturn(PETSC_SUCCESS);
2868: }

2870: PetscErrorCode MatMPIAIJSetPreallocation_MPIAIJ(Mat B, PetscInt d_nz, const PetscInt d_nnz[], PetscInt o_nz, const PetscInt o_nnz[])
2871: {
2872:   Mat_MPIAIJ *b = (Mat_MPIAIJ *)B->data;
2873:   PetscMPIInt size;

2875:   PetscFunctionBegin;
2876:   if (B->hash_active) {
2877:     B->ops[0]      = b->cops;
2878:     B->hash_active = PETSC_FALSE;
2879:   }
2880:   PetscCall(PetscLayoutSetUp(B->rmap));
2881:   PetscCall(PetscLayoutSetUp(B->cmap));

2883: #if defined(PETSC_USE_CTABLE)
2884:   PetscCall(PetscHMapIDestroy(&b->colmap));
2885: #else
2886:   PetscCall(PetscFree(b->colmap));
2887: #endif
2888:   PetscCall(PetscFree(b->garray));
2889:   PetscCall(VecDestroy(&b->lvec));
2890:   PetscCall(VecScatterDestroy(&b->Mvctx));

2892:   PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)B), &size));

2894:   MatSeqXAIJGetOptions_Private(b->B);
2895:   PetscCall(MatDestroy(&b->B));
2896:   PetscCall(MatCreate(PETSC_COMM_SELF, &b->B));
2897:   PetscCall(MatSetSizes(b->B, B->rmap->n, size > 1 ? B->cmap->N : 0, B->rmap->n, size > 1 ? B->cmap->N : 0));
2898:   PetscCall(MatSetBlockSizesFromMats(b->B, B, B));
2899:   PetscCall(MatSetType(b->B, MATSEQAIJ));
2900:   MatSeqXAIJRestoreOptions_Private(b->B);

2902:   MatSeqXAIJGetOptions_Private(b->A);
2903:   PetscCall(MatDestroy(&b->A));
2904:   PetscCall(MatCreate(PETSC_COMM_SELF, &b->A));
2905:   PetscCall(MatSetSizes(b->A, B->rmap->n, B->cmap->n, B->rmap->n, B->cmap->n));
2906:   PetscCall(MatSetBlockSizesFromMats(b->A, B, B));
2907:   PetscCall(MatSetType(b->A, MATSEQAIJ));
2908:   MatSeqXAIJRestoreOptions_Private(b->A);

2910:   PetscCall(MatSeqAIJSetPreallocation(b->A, d_nz, d_nnz));
2911:   PetscCall(MatSeqAIJSetPreallocation(b->B, o_nz, o_nnz));
2912:   B->preallocated  = PETSC_TRUE;
2913:   B->was_assembled = PETSC_FALSE;
2914:   B->assembled     = PETSC_FALSE;
2915:   PetscFunctionReturn(PETSC_SUCCESS);
2916: }

2918: static PetscErrorCode MatResetPreallocation_MPIAIJ(Mat B)
2919: {
2920:   Mat_MPIAIJ *b = (Mat_MPIAIJ *)B->data;
2921:   PetscBool   ondiagreset, offdiagreset, memoryreset;

2923:   PetscFunctionBegin;
2925:   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()");
2926:   if (B->num_ass == 0) PetscFunctionReturn(PETSC_SUCCESS);

2928:   PetscCall(MatResetPreallocation_SeqAIJ_Private(b->A, &ondiagreset));
2929:   PetscCall(MatResetPreallocation_SeqAIJ_Private(b->B, &offdiagreset));
2930:   memoryreset = (PetscBool)(ondiagreset || offdiagreset);
2931:   PetscCallMPI(MPIU_Allreduce(MPI_IN_PLACE, &memoryreset, 1, MPI_C_BOOL, MPI_LOR, PetscObjectComm((PetscObject)B)));
2932:   if (!memoryreset) PetscFunctionReturn(PETSC_SUCCESS);

2934:   PetscCall(PetscLayoutSetUp(B->rmap));
2935:   PetscCall(PetscLayoutSetUp(B->cmap));
2936:   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");
2937:   PetscCall(MatDisAssemble_MPIAIJ(B, PETSC_TRUE));
2938:   PetscCall(VecScatterDestroy(&b->Mvctx));

2940:   B->preallocated  = PETSC_TRUE;
2941:   B->was_assembled = PETSC_FALSE;
2942:   B->assembled     = PETSC_FALSE;
2943:   /* Log that the state of this object has changed; this will help guarantee that preconditioners get re-setup */
2944:   PetscCall(PetscObjectStateIncrease((PetscObject)B));
2945:   PetscFunctionReturn(PETSC_SUCCESS);
2946: }

2948: PetscErrorCode MatDuplicate_MPIAIJ(Mat matin, MatDuplicateOption cpvalues, Mat *newmat)
2949: {
2950:   Mat         mat;
2951:   Mat_MPIAIJ *a, *oldmat = (Mat_MPIAIJ *)matin->data;

2953:   PetscFunctionBegin;
2954:   *newmat = NULL;
2955:   PetscCall(MatCreate(PetscObjectComm((PetscObject)matin), &mat));
2956:   PetscCall(MatSetSizes(mat, matin->rmap->n, matin->cmap->n, matin->rmap->N, matin->cmap->N));
2957:   PetscCall(MatSetBlockSizesFromMats(mat, matin, matin));
2958:   PetscCall(MatSetType(mat, ((PetscObject)matin)->type_name));
2959:   a = (Mat_MPIAIJ *)mat->data;

2961:   mat->factortype = matin->factortype;
2962:   mat->assembled  = matin->assembled;
2963:   mat->insertmode = NOT_SET_VALUES;

2965:   a->size         = oldmat->size;
2966:   a->rank         = oldmat->rank;
2967:   a->donotstash   = oldmat->donotstash;
2968:   a->roworiented  = oldmat->roworiented;
2969:   a->rowindices   = NULL;
2970:   a->rowvalues    = NULL;
2971:   a->getrowactive = PETSC_FALSE;

2973:   PetscCall(PetscLayoutReference(matin->rmap, &mat->rmap));
2974:   PetscCall(PetscLayoutReference(matin->cmap, &mat->cmap));
2975:   if (matin->hash_active) PetscCall(MatSetUp(mat));
2976:   else {
2977:     mat->preallocated = matin->preallocated;
2978:     if (oldmat->colmap) {
2979: #if defined(PETSC_USE_CTABLE)
2980:       PetscCall(PetscHMapIDuplicate(oldmat->colmap, &a->colmap));
2981: #else
2982:       PetscCall(PetscMalloc1(mat->cmap->N, &a->colmap));
2983:       PetscCall(PetscArraycpy(a->colmap, oldmat->colmap, mat->cmap->N));
2984: #endif
2985:     } else a->colmap = NULL;
2986:     if (oldmat->garray) {
2987:       PetscInt len;
2988:       len = oldmat->B->cmap->n;
2989:       PetscCall(PetscMalloc1(len, &a->garray));
2990:       if (len) PetscCall(PetscArraycpy(a->garray, oldmat->garray, len));
2991:     } else a->garray = NULL;

2993:     /* It may happen MatDuplicate is called with a non-assembled matrix
2994:       In fact, MatDuplicate only requires the matrix to be preallocated
2995:       This may happen inside a DMCreateMatrix_Shell */
2996:     if (oldmat->lvec) PetscCall(VecDuplicate(oldmat->lvec, &a->lvec));
2997:     if (oldmat->Mvctx) {
2998:       a->Mvctx = oldmat->Mvctx;
2999:       PetscCall(PetscObjectReference((PetscObject)oldmat->Mvctx));
3000:     }
3001:     PetscCall(MatDuplicate(oldmat->A, cpvalues, &a->A));
3002:     PetscCall(MatDuplicate(oldmat->B, cpvalues, &a->B));
3003:   }
3004:   PetscCall(PetscFunctionListDuplicate(((PetscObject)matin)->qlist, &((PetscObject)mat)->qlist));
3005:   *newmat = mat;
3006:   PetscFunctionReturn(PETSC_SUCCESS);
3007: }

3009: PetscErrorCode MatLoad_MPIAIJ(Mat newMat, PetscViewer viewer)
3010: {
3011:   PetscBool isbinary, ishdf5;

3013:   PetscFunctionBegin;
3016:   /* force binary viewer to load .info file if it has not yet done so */
3017:   PetscCall(PetscViewerSetUp(viewer));
3018:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERBINARY, &isbinary));
3019:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERHDF5, &ishdf5));
3020:   if (isbinary) {
3021:     PetscCall(MatLoad_MPIAIJ_Binary(newMat, viewer));
3022:   } else if (ishdf5) {
3023: #if defined(PETSC_HAVE_HDF5)
3024:     PetscCall(MatLoad_AIJ_HDF5(newMat, viewer));
3025: #else
3026:     SETERRQ(PetscObjectComm((PetscObject)newMat), PETSC_ERR_SUP, "HDF5 not supported in this build.\nPlease reconfigure using --download-hdf5");
3027: #endif
3028:   } else {
3029:     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);
3030:   }
3031:   PetscFunctionReturn(PETSC_SUCCESS);
3032: }

3034: PetscErrorCode MatLoad_MPIAIJ_Binary(Mat mat, PetscViewer viewer)
3035: {
3036:   PetscInt     header[4], M, N, m, nz, rows, cols, sum, i;
3037:   PetscInt    *rowidxs, *colidxs;
3038:   PetscScalar *matvals;

3040:   PetscFunctionBegin;
3041:   PetscCall(PetscViewerSetUp(viewer));

3043:   /* read in matrix header */
3044:   PetscCall(PetscViewerBinaryRead(viewer, header, 4, NULL, PETSC_INT));
3045:   PetscCheck(header[0] == MAT_FILE_CLASSID, PetscObjectComm((PetscObject)viewer), PETSC_ERR_FILE_UNEXPECTED, "Not a matrix object in file");
3046:   M  = header[1];
3047:   N  = header[2];
3048:   nz = header[3];
3049:   PetscCheck(M >= 0, PetscObjectComm((PetscObject)viewer), PETSC_ERR_FILE_UNEXPECTED, "Matrix row size (%" PetscInt_FMT ") in file is negative", M);
3050:   PetscCheck(N >= 0, PetscObjectComm((PetscObject)viewer), PETSC_ERR_FILE_UNEXPECTED, "Matrix column size (%" PetscInt_FMT ") in file is negative", N);
3051:   PetscCheck(nz >= 0, PETSC_COMM_SELF, PETSC_ERR_FILE_UNEXPECTED, "Matrix stored in special format on disk, cannot load as MPIAIJ");

3053:   /* set block sizes from the viewer's .info file */
3054:   PetscCall(MatLoad_Binary_BlockSizes(mat, viewer));
3055:   /* set global sizes if not set already */
3056:   if (mat->rmap->N < 0) mat->rmap->N = M;
3057:   if (mat->cmap->N < 0) mat->cmap->N = N;
3058:   PetscCall(PetscLayoutSetUp(mat->rmap));
3059:   PetscCall(PetscLayoutSetUp(mat->cmap));

3061:   /* check if the matrix sizes are correct */
3062:   PetscCall(MatGetSize(mat, &rows, &cols));
3063:   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);

3065:   /* read in row lengths and build row indices */
3066:   PetscCall(MatGetLocalSize(mat, &m, NULL));
3067:   PetscCall(PetscMalloc1(m + 1, &rowidxs));
3068:   PetscCall(PetscViewerBinaryReadAll(viewer, rowidxs + 1, m, PETSC_DECIDE, M, PETSC_INT));
3069:   rowidxs[0] = 0;
3070:   for (i = 0; i < m; i++) rowidxs[i + 1] += rowidxs[i];
3071:   if (nz != PETSC_INT_MAX) {
3072:     PetscCallMPI(MPIU_Allreduce(&rowidxs[m], &sum, 1, MPIU_INT, MPI_SUM, PetscObjectComm((PetscObject)viewer)));
3073:     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);
3074:   }

3076:   /* read in column indices and matrix values */
3077:   PetscCall(PetscMalloc2(rowidxs[m], &colidxs, rowidxs[m], &matvals));
3078:   PetscCall(PetscViewerBinaryReadAll(viewer, colidxs, rowidxs[m], PETSC_DETERMINE, PETSC_DETERMINE, PETSC_INT));
3079:   PetscCall(PetscViewerBinaryReadAll(viewer, matvals, rowidxs[m], PETSC_DETERMINE, PETSC_DETERMINE, PETSC_SCALAR));
3080:   /* store matrix indices and values */
3081:   PetscCall(MatMPIAIJSetPreallocationCSR(mat, rowidxs, colidxs, matvals));
3082:   PetscCall(PetscFree(rowidxs));
3083:   PetscCall(PetscFree2(colidxs, matvals));
3084:   PetscFunctionReturn(PETSC_SUCCESS);
3085: }

3087: /* Not scalable because of ISAllGather() unless getting all columns. */
3088: static PetscErrorCode ISGetSeqIS_Private(Mat mat, IS iscol, IS *isseq)
3089: {
3090:   IS          iscol_local;
3091:   PetscBool   isstride;
3092:   PetscMPIInt gisstride = 0;

3094:   PetscFunctionBegin;
3095:   /* check if we are grabbing all columns*/
3096:   PetscCall(PetscObjectTypeCompare((PetscObject)iscol, ISSTRIDE, &isstride));

3098:   if (isstride) {
3099:     PetscInt start, len, mstart, mlen;
3100:     PetscCall(ISStrideGetInfo(iscol, &start, NULL));
3101:     PetscCall(ISGetLocalSize(iscol, &len));
3102:     PetscCall(MatGetOwnershipRangeColumn(mat, &mstart, &mlen));
3103:     if (mstart == start && mlen - mstart == len) gisstride = 1;
3104:   }

3106:   PetscCallMPI(MPIU_Allreduce(MPI_IN_PLACE, &gisstride, 1, MPI_INT, MPI_MIN, PetscObjectComm((PetscObject)mat)));
3107:   if (gisstride) {
3108:     PetscInt N;
3109:     PetscCall(MatGetSize(mat, NULL, &N));
3110:     PetscCall(ISCreateStride(PETSC_COMM_SELF, N, 0, 1, &iscol_local));
3111:     PetscCall(ISSetIdentity(iscol_local));
3112:     PetscCall(PetscInfo(mat, "Optimizing for obtaining all columns of the matrix; skipping ISAllGather()\n"));
3113:   } else {
3114:     PetscInt cbs;
3115:     PetscCall(ISGetBlockSize(iscol, &cbs));
3116:     PetscCall(ISAllGather(iscol, &iscol_local));
3117:     PetscCall(ISSetBlockSize(iscol_local, cbs));
3118:   }

3120:   *isseq = iscol_local;
3121:   PetscFunctionReturn(PETSC_SUCCESS);
3122: }

3124: /*
3125:  Used by MatCreateSubMatrix_MPIAIJ_SameRowColDist() to avoid ISAllGather() and global size of iscol_local
3126:  (see MatCreateSubMatrix_MPIAIJ_nonscalable)

3128:  Input Parameters:
3129: +   mat - matrix
3130: .   isrow - parallel row index set; its local indices are a subset of local columns of `mat`,
3131:            i.e., mat->rstart <= isrow[i] < mat->rend
3132: -   iscol - parallel column index set; its local indices are a subset of local columns of `mat`,
3133:            i.e., mat->cstart <= iscol[i] < mat->cend

3135:  Output Parameters:
3136: +   isrow_d - sequential row index set for retrieving mat->A
3137: .   iscol_d - sequential  column index set for retrieving mat->A
3138: .   iscol_o - sequential column index set for retrieving mat->B
3139: -   garray - column map; garray[i] indicates global location of iscol_o[i] in `iscol`
3140:  */
3141: static PetscErrorCode ISGetSeqIS_SameColDist_Private(Mat mat, IS isrow, IS iscol, IS *isrow_d, IS *iscol_d, IS *iscol_o, PetscInt *garray[])
3142: {
3143:   Vec             x, cmap;
3144:   const PetscInt *is_idx;
3145:   PetscScalar    *xarray, *cmaparray;
3146:   PetscInt        ncols, isstart, *idx, m, rstart, *cmap1, count;
3147:   Mat_MPIAIJ     *a    = (Mat_MPIAIJ *)mat->data;
3148:   Mat             B    = a->B;
3149:   Vec             lvec = a->lvec, lcmap;
3150:   PetscInt        i, cstart, cend, Bn = B->cmap->N;
3151:   MPI_Comm        comm;
3152:   VecScatter      Mvctx = a->Mvctx;

3154:   PetscFunctionBegin;
3155:   PetscCall(PetscObjectGetComm((PetscObject)mat, &comm));
3156:   PetscCall(ISGetLocalSize(iscol, &ncols));

3158:   /* (1) iscol is a sub-column vector of mat, pad it with '-1.' to form a full vector x */
3159:   PetscCall(MatCreateVecs(mat, &x, NULL));
3160:   PetscCall(VecSet(x, -1.0));
3161:   PetscCall(VecDuplicate(x, &cmap));
3162:   PetscCall(VecSet(cmap, -1.0));

3164:   /* Get start indices */
3165:   PetscCallMPI(MPI_Scan(&ncols, &isstart, 1, MPIU_INT, MPI_SUM, comm));
3166:   isstart -= ncols;
3167:   PetscCall(MatGetOwnershipRangeColumn(mat, &cstart, &cend));

3169:   PetscCall(ISGetIndices(iscol, &is_idx));
3170:   PetscCall(VecGetArray(x, &xarray));
3171:   PetscCall(VecGetArray(cmap, &cmaparray));
3172:   PetscCall(PetscMalloc1(ncols, &idx));
3173:   for (i = 0; i < ncols; i++) {
3174:     xarray[is_idx[i] - cstart]    = (PetscScalar)is_idx[i];
3175:     cmaparray[is_idx[i] - cstart] = i + isstart;        /* global index of iscol[i] */
3176:     idx[i]                        = is_idx[i] - cstart; /* local index of iscol[i]  */
3177:   }
3178:   PetscCall(VecRestoreArray(x, &xarray));
3179:   PetscCall(VecRestoreArray(cmap, &cmaparray));
3180:   PetscCall(ISRestoreIndices(iscol, &is_idx));

3182:   /* Get iscol_d */
3183:   PetscCall(ISCreateGeneral(PETSC_COMM_SELF, ncols, idx, PETSC_OWN_POINTER, iscol_d));
3184:   PetscCall(ISGetBlockSize(iscol, &i));
3185:   PetscCall(ISSetBlockSize(*iscol_d, i));

3187:   /* Get isrow_d */
3188:   PetscCall(ISGetLocalSize(isrow, &m));
3189:   rstart = mat->rmap->rstart;
3190:   PetscCall(PetscMalloc1(m, &idx));
3191:   PetscCall(ISGetIndices(isrow, &is_idx));
3192:   for (i = 0; i < m; i++) idx[i] = is_idx[i] - rstart;
3193:   PetscCall(ISRestoreIndices(isrow, &is_idx));

3195:   PetscCall(ISCreateGeneral(PETSC_COMM_SELF, m, idx, PETSC_OWN_POINTER, isrow_d));
3196:   PetscCall(ISGetBlockSize(isrow, &i));
3197:   PetscCall(ISSetBlockSize(*isrow_d, i));

3199:   /* (2) Scatter x and cmap using aij->Mvctx to get their off-process portions (see MatMult_MPIAIJ) */
3200:   PetscCall(VecScatterBegin(Mvctx, x, lvec, INSERT_VALUES, SCATTER_FORWARD));
3201:   PetscCall(VecScatterEnd(Mvctx, x, lvec, INSERT_VALUES, SCATTER_FORWARD));

3203:   PetscCall(VecDuplicate(lvec, &lcmap));

3205:   PetscCall(VecScatterBegin(Mvctx, cmap, lcmap, INSERT_VALUES, SCATTER_FORWARD));
3206:   PetscCall(VecScatterEnd(Mvctx, cmap, lcmap, INSERT_VALUES, SCATTER_FORWARD));

3208:   /* (3) create sequential iscol_o (a subset of iscol) and isgarray */
3209:   /* off-process column indices */
3210:   count = 0;
3211:   PetscCall(PetscMalloc1(Bn, &idx));
3212:   PetscCall(PetscMalloc1(Bn, &cmap1));

3214:   PetscCall(VecGetArray(lvec, &xarray));
3215:   PetscCall(VecGetArray(lcmap, &cmaparray));
3216:   for (i = 0; i < Bn; i++) {
3217:     if (PetscRealPart(xarray[i]) > -1.0) {
3218:       idx[count]   = i;                                     /* local column index in off-diagonal part B */
3219:       cmap1[count] = (PetscInt)PetscRealPart(cmaparray[i]); /* column index in submat */
3220:       count++;
3221:     }
3222:   }
3223:   PetscCall(VecRestoreArray(lvec, &xarray));
3224:   PetscCall(VecRestoreArray(lcmap, &cmaparray));

3226:   PetscCall(ISCreateGeneral(PETSC_COMM_SELF, count, idx, PETSC_COPY_VALUES, iscol_o));
3227:   /* cannot ensure iscol_o has same blocksize as iscol! */

3229:   PetscCall(PetscFree(idx));
3230:   *garray = cmap1;

3232:   PetscCall(VecDestroy(&x));
3233:   PetscCall(VecDestroy(&cmap));
3234:   PetscCall(VecDestroy(&lcmap));
3235:   PetscFunctionReturn(PETSC_SUCCESS);
3236: }

3238: /* isrow and iscol have same processor distribution as mat, output *submat is a submatrix of local mat */
3239: PetscErrorCode MatCreateSubMatrix_MPIAIJ_SameRowColDist(Mat mat, IS isrow, IS iscol, MatReuse call, Mat *submat)
3240: {
3241:   Mat_MPIAIJ *a = (Mat_MPIAIJ *)mat->data, *asub;
3242:   Mat         M = NULL;
3243:   MPI_Comm    comm;
3244:   IS          iscol_d, isrow_d, iscol_o;
3245:   Mat         Asub = NULL, Bsub = NULL;
3246:   PetscInt    n, count, M_size, N_size;

3248:   PetscFunctionBegin;
3249:   PetscCall(PetscObjectGetComm((PetscObject)mat, &comm));

3251:   if (call == MAT_REUSE_MATRIX) {
3252:     /* Retrieve isrow_d, iscol_d and iscol_o from submat */
3253:     PetscCall(PetscObjectQuery((PetscObject)*submat, "isrow_d", (PetscObject *)&isrow_d));
3254:     PetscCheck(isrow_d, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "isrow_d passed in was not used before, cannot reuse");

3256:     PetscCall(PetscObjectQuery((PetscObject)*submat, "iscol_d", (PetscObject *)&iscol_d));
3257:     PetscCheck(iscol_d, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "iscol_d passed in was not used before, cannot reuse");

3259:     PetscCall(PetscObjectQuery((PetscObject)*submat, "iscol_o", (PetscObject *)&iscol_o));
3260:     PetscCheck(iscol_o, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "iscol_o passed in was not used before, cannot reuse");

3262:     /* Update diagonal and off-diagonal portions of submat */
3263:     asub = (Mat_MPIAIJ *)(*submat)->data;
3264:     PetscCall(MatCreateSubMatrix_SeqAIJ(a->A, isrow_d, iscol_d, PETSC_DECIDE, MAT_REUSE_MATRIX, &asub->A));
3265:     PetscCall(ISGetLocalSize(iscol_o, &n));
3266:     if (n) PetscCall(MatCreateSubMatrix_SeqAIJ(a->B, isrow_d, iscol_o, PETSC_DECIDE, MAT_REUSE_MATRIX, &asub->B));
3267:     PetscCall(MatAssemblyBegin(*submat, MAT_FINAL_ASSEMBLY));
3268:     PetscCall(MatAssemblyEnd(*submat, MAT_FINAL_ASSEMBLY));

3270:   } else { /* call == MAT_INITIAL_MATRIX) */
3271:     PetscInt *garray, *garray_compact;
3272:     PetscInt  BsubN;

3274:     /* Create isrow_d, iscol_d, iscol_o and isgarray (replace isgarray with array?) */
3275:     PetscCall(ISGetSeqIS_SameColDist_Private(mat, isrow, iscol, &isrow_d, &iscol_d, &iscol_o, &garray));

3277:     /* Create local submatrices Asub and Bsub */
3278:     PetscCall(MatCreateSubMatrix_SeqAIJ(a->A, isrow_d, iscol_d, PETSC_DECIDE, MAT_INITIAL_MATRIX, &Asub));
3279:     PetscCall(MatCreateSubMatrix_SeqAIJ(a->B, isrow_d, iscol_o, PETSC_DECIDE, MAT_INITIAL_MATRIX, &Bsub));

3281:     // Compact garray so its not of size Bn
3282:     PetscCall(ISGetSize(iscol_o, &count));
3283:     PetscCall(PetscMalloc1(count, &garray_compact));
3284:     PetscCall(PetscArraycpy(garray_compact, garray, count));

3286:     /* Create submatrix M */
3287:     PetscCall(ISGetSize(isrow, &M_size));
3288:     PetscCall(ISGetSize(iscol, &N_size));
3289:     PetscCall(MatCreateMPIAIJWithSeqAIJ(comm, M_size, N_size, Asub, Bsub, garray_compact, &M));

3291:     /* If Bsub has empty columns, compress iscol_o such that it will retrieve condensed Bsub from a->B during reuse */
3292:     asub = (Mat_MPIAIJ *)M->data;

3294:     PetscCall(ISGetLocalSize(iscol_o, &BsubN));
3295:     n = asub->B->cmap->N;
3296:     if (BsubN > n) {
3297:       /* This case can be tested using ~petsc/src/tao/bound/tutorials/runplate2_3 */
3298:       const PetscInt *idx;
3299:       PetscInt        i, j, *idx_new, *subgarray = asub->garray;
3300:       PetscCall(PetscInfo(M, "submatrix Bn %" PetscInt_FMT " != BsubN %" PetscInt_FMT ", update iscol_o\n", n, BsubN));

3302:       PetscCall(PetscMalloc1(n, &idx_new));
3303:       j = 0;
3304:       PetscCall(ISGetIndices(iscol_o, &idx));
3305:       for (i = 0; i < n; i++) {
3306:         if (j >= BsubN) break;
3307:         while (subgarray[i] > garray[j]) j++;

3309:         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]);
3310:         idx_new[i] = idx[j++];
3311:       }
3312:       PetscCall(ISRestoreIndices(iscol_o, &idx));

3314:       PetscCall(ISDestroy(&iscol_o));
3315:       PetscCall(ISCreateGeneral(PETSC_COMM_SELF, n, idx_new, PETSC_OWN_POINTER, &iscol_o));

3317:     } 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);

3319:     PetscCall(PetscFree(garray));
3320:     *submat = M;

3322:     /* Save isrow_d, iscol_d and iscol_o used in processor for next request */
3323:     PetscCall(PetscObjectCompose((PetscObject)M, "isrow_d", (PetscObject)isrow_d));
3324:     PetscCall(ISDestroy(&isrow_d));

3326:     PetscCall(PetscObjectCompose((PetscObject)M, "iscol_d", (PetscObject)iscol_d));
3327:     PetscCall(ISDestroy(&iscol_d));

3329:     PetscCall(PetscObjectCompose((PetscObject)M, "iscol_o", (PetscObject)iscol_o));
3330:     PetscCall(ISDestroy(&iscol_o));
3331:   }
3332:   PetscFunctionReturn(PETSC_SUCCESS);
3333: }

3335: PetscErrorCode MatCreateSubMatrix_MPIAIJ(Mat mat, IS isrow, IS iscol, MatReuse call, Mat *newmat)
3336: {
3337:   IS        iscol_local = NULL, isrow_d;
3338:   PetscInt  csize;
3339:   PetscInt  n, i, j, start, end;
3340:   PetscBool sameRowDist = PETSC_FALSE, sameDist[2], tsameDist[2];
3341:   MPI_Comm  comm;

3343:   PetscFunctionBegin;
3344:   /* If isrow has same processor distribution as mat,
3345:      call MatCreateSubMatrix_MPIAIJ_SameRowDist() to avoid using a hash table with global size of iscol */
3346:   if (call == MAT_REUSE_MATRIX) {
3347:     PetscCall(PetscObjectQuery((PetscObject)*newmat, "isrow_d", (PetscObject *)&isrow_d));
3348:     if (isrow_d) {
3349:       sameRowDist  = PETSC_TRUE;
3350:       tsameDist[1] = PETSC_TRUE; /* sameColDist */
3351:     } else {
3352:       PetscCall(PetscObjectQuery((PetscObject)*newmat, "SubIScol", (PetscObject *)&iscol_local));
3353:       if (iscol_local) {
3354:         sameRowDist  = PETSC_TRUE;
3355:         tsameDist[1] = PETSC_FALSE; /* !sameColDist */
3356:       }
3357:     }
3358:   } else {
3359:     /* Check if isrow has same processor distribution as mat */
3360:     sameDist[0] = PETSC_FALSE;
3361:     PetscCall(ISGetLocalSize(isrow, &n));
3362:     if (!n) {
3363:       sameDist[0] = PETSC_TRUE;
3364:     } else {
3365:       PetscCall(ISGetMinMax(isrow, &i, &j));
3366:       PetscCall(MatGetOwnershipRange(mat, &start, &end));
3367:       if (i >= start && j < end) sameDist[0] = PETSC_TRUE;
3368:     }

3370:     /* Check if iscol has same processor distribution as mat */
3371:     sameDist[1] = PETSC_FALSE;
3372:     PetscCall(ISGetLocalSize(iscol, &n));
3373:     if (!n) {
3374:       sameDist[1] = PETSC_TRUE;
3375:     } else {
3376:       PetscCall(ISGetMinMax(iscol, &i, &j));
3377:       PetscCall(MatGetOwnershipRangeColumn(mat, &start, &end));
3378:       if (i >= start && j < end) sameDist[1] = PETSC_TRUE;
3379:     }

3381:     PetscCall(PetscObjectGetComm((PetscObject)mat, &comm));
3382:     PetscCallMPI(MPIU_Allreduce(&sameDist, &tsameDist, 2, MPI_C_BOOL, MPI_LAND, comm));
3383:     sameRowDist = tsameDist[0];
3384:   }

3386:   if (sameRowDist) {
3387:     if (tsameDist[1]) { /* sameRowDist & sameColDist */
3388:       /* isrow and iscol have same processor distribution as mat */
3389:       PetscCall(MatCreateSubMatrix_MPIAIJ_SameRowColDist(mat, isrow, iscol, call, newmat));
3390:       PetscFunctionReturn(PETSC_SUCCESS);
3391:     } else { /* sameRowDist */
3392:       /* isrow has same processor distribution as mat */
3393:       if (call == MAT_INITIAL_MATRIX) {
3394:         PetscBool sorted;
3395:         PetscCall(ISGetSeqIS_Private(mat, iscol, &iscol_local));
3396:         PetscCall(ISGetLocalSize(iscol_local, &n)); /* local size of iscol_local = global columns of newmat */
3397:         PetscCall(ISGetSize(iscol, &i));
3398:         PetscCheck(n == i, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "n %" PetscInt_FMT " != size of iscol %" PetscInt_FMT, n, i);

3400:         PetscCall(ISSorted(iscol_local, &sorted));
3401:         if (sorted) {
3402:           /* MatCreateSubMatrix_MPIAIJ_SameRowDist() requires iscol_local be sorted; it can have duplicate indices */
3403:           PetscCall(MatCreateSubMatrix_MPIAIJ_SameRowDist(mat, isrow, iscol, iscol_local, MAT_INITIAL_MATRIX, newmat));
3404:           PetscFunctionReturn(PETSC_SUCCESS);
3405:         }
3406:       } else { /* call == MAT_REUSE_MATRIX */
3407:         IS iscol_sub;
3408:         PetscCall(PetscObjectQuery((PetscObject)*newmat, "SubIScol", (PetscObject *)&iscol_sub));
3409:         if (iscol_sub) {
3410:           PetscCall(MatCreateSubMatrix_MPIAIJ_SameRowDist(mat, isrow, iscol, NULL, call, newmat));
3411:           PetscFunctionReturn(PETSC_SUCCESS);
3412:         }
3413:       }
3414:     }
3415:   }

3417:   /* General case: iscol -> iscol_local which has global size of iscol */
3418:   if (call == MAT_REUSE_MATRIX) {
3419:     PetscCall(PetscObjectQuery((PetscObject)*newmat, "ISAllGather", (PetscObject *)&iscol_local));
3420:     PetscCheck(iscol_local, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Submatrix passed in was not used before, cannot reuse");
3421:   } else {
3422:     if (!iscol_local) PetscCall(ISGetSeqIS_Private(mat, iscol, &iscol_local));
3423:   }

3425:   PetscCall(ISGetLocalSize(iscol, &csize));
3426:   PetscCall(MatCreateSubMatrix_MPIAIJ_nonscalable(mat, isrow, iscol_local, csize, call, newmat));

3428:   if (call == MAT_INITIAL_MATRIX) {
3429:     PetscCall(PetscObjectCompose((PetscObject)*newmat, "ISAllGather", (PetscObject)iscol_local));
3430:     PetscCall(ISDestroy(&iscol_local));
3431:   }
3432:   PetscFunctionReturn(PETSC_SUCCESS);
3433: }

3435: /*@C
3436:   MatCreateMPIAIJWithSeqAIJ - creates a `MATMPIAIJ` matrix using `MATSEQAIJ` matrices that contain the "diagonal"
3437:   and "off-diagonal" part of the matrix in CSR format.

3439:   Collective

3441:   Input Parameters:
3442: + comm   - MPI communicator
3443: . M      - the global row size
3444: . N      - the global column size
3445: . A      - "diagonal" portion of matrix
3446: . 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
3447: - 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.

3449:   Output Parameter:
3450: . mat - the matrix, with input `A` as its local diagonal matrix

3452:   Level: advanced

3454:   Notes:
3455:   See `MatCreateAIJ()` for the definition of "diagonal" and "off-diagonal" portion of the matrix.

3457:   `A` and `B` becomes part of output mat. The user cannot use `A` and `B` anymore.

3459:   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
3460:   `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
3461:   `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`
3462:   yourself, see algorithms in the private function `MatSetUpMultiply_MPIAIJ()`.

3464:   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.

3466: .seealso: [](ch_matrices), `Mat`, `MATMPIAIJ`, `MATSEQAIJ`, `MatCreateMPIAIJWithSplitArrays()`
3467: @*/
3468: PetscErrorCode MatCreateMPIAIJWithSeqAIJ(MPI_Comm comm, PetscInt M, PetscInt N, Mat A, Mat B, PetscInt *garray, Mat *mat)
3469: {
3470:   PetscInt    m, n;
3471:   MatType     mpi_mat_type;
3472:   Mat_MPIAIJ *mpiaij;
3473:   Mat         C;

3475:   PetscFunctionBegin;
3476:   PetscCall(MatCreate(comm, &C));
3477:   PetscCall(MatGetSize(A, &m, &n));
3478:   PetscCheck(m == B->rmap->N, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Am %" PetscInt_FMT " != Bm %" PetscInt_FMT, m, B->rmap->N);
3479:   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);

3481:   PetscCall(MatSetSizes(C, m, n, M, N));
3482:   /* Determine the type of MPI matrix that should be created from the type of matrix A, which holds the "diagonal" portion. */
3483:   PetscCall(MatGetMPIMatType_Private(A, &mpi_mat_type));
3484:   PetscCall(MatSetType(C, mpi_mat_type));
3485:   if (!garray) {
3486:     const PetscScalar *ba;

3488:     B->nonzerostate++;
3489:     PetscCall(MatSeqAIJGetArrayRead(B, &ba)); /* Since we will destroy B's device copy, we need to make sure the host copy is up to date */
3490:     PetscCall(MatSeqAIJRestoreArrayRead(B, &ba));
3491:   }

3493:   PetscCall(MatSetBlockSizes(C, A->rmap->bs, A->cmap->bs));
3494:   PetscCall(PetscLayoutSetUp(C->rmap));
3495:   PetscCall(PetscLayoutSetUp(C->cmap));

3497:   mpiaij              = (Mat_MPIAIJ *)C->data;
3498:   mpiaij->A           = A;
3499:   mpiaij->B           = B;
3500:   mpiaij->garray      = garray;
3501:   C->preallocated     = PETSC_TRUE;
3502:   C->nooffprocentries = PETSC_TRUE; /* See MatAssemblyBegin_MPIAIJ. In effect, making MatAssemblyBegin a nop */

3504:   PetscCall(MatSetOption(C, MAT_NO_OFF_PROC_ENTRIES, PETSC_TRUE));
3505:   PetscCall(MatAssemblyBegin(C, MAT_FINAL_ASSEMBLY));
3506:   /* MatAssemblyEnd is critical here. It sets mat->offloadmask according to A and B's, and
3507:    also gets mpiaij->B compacted (if garray is NULL), with its col ids and size reduced
3508:    */
3509:   PetscCall(MatAssemblyEnd(C, MAT_FINAL_ASSEMBLY));
3510:   PetscCall(MatSetOption(C, MAT_NO_OFF_PROC_ENTRIES, PETSC_FALSE));
3511:   PetscCall(MatSetOption(C, MAT_NEW_NONZERO_LOCATION_ERR, PETSC_TRUE));
3512:   *mat = C;
3513:   PetscFunctionReturn(PETSC_SUCCESS);
3514: }

3516: extern PetscErrorCode MatCreateSubMatrices_MPIAIJ_SingleIS_Local(Mat, PetscInt, const IS[], const IS[], MatReuse, PetscBool, Mat *);

3518: PetscErrorCode MatCreateSubMatrix_MPIAIJ_SameRowDist(Mat mat, IS isrow, IS iscol, IS iscol_local, MatReuse call, Mat *newmat)
3519: {
3520:   PetscInt        i, m, n, rstart, row, rend, nz, j, bs, cbs;
3521:   PetscInt       *ii, *jj, nlocal, *dlens, *olens, dlen, olen, jend, mglobal;
3522:   Mat_MPIAIJ     *a = (Mat_MPIAIJ *)mat->data;
3523:   Mat             M, Msub, B = a->B;
3524:   MatScalar      *aa;
3525:   Mat_SeqAIJ     *aij;
3526:   PetscInt       *garray = a->garray, *colsub, Ncols;
3527:   PetscInt        count, Bn = B->cmap->N, cstart = mat->cmap->rstart, cend = mat->cmap->rend;
3528:   IS              iscol_sub, iscmap;
3529:   const PetscInt *is_idx, *cmap;
3530:   PetscBool       allcolumns = PETSC_FALSE;
3531:   MPI_Comm        comm;

3533:   PetscFunctionBegin;
3534:   PetscCall(PetscObjectGetComm((PetscObject)mat, &comm));
3535:   if (call == MAT_REUSE_MATRIX) {
3536:     PetscCall(PetscObjectQuery((PetscObject)*newmat, "SubIScol", (PetscObject *)&iscol_sub));
3537:     PetscCheck(iscol_sub, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "SubIScol passed in was not used before, cannot reuse");
3538:     PetscCall(ISGetLocalSize(iscol_sub, &count));

3540:     PetscCall(PetscObjectQuery((PetscObject)*newmat, "Subcmap", (PetscObject *)&iscmap));
3541:     PetscCheck(iscmap, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Subcmap passed in was not used before, cannot reuse");

3543:     PetscCall(PetscObjectQuery((PetscObject)*newmat, "SubMatrix", (PetscObject *)&Msub));
3544:     PetscCheck(Msub, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Submatrix passed in was not used before, cannot reuse");

3546:     PetscCall(MatCreateSubMatrices_MPIAIJ_SingleIS_Local(mat, 1, &isrow, &iscol_sub, MAT_REUSE_MATRIX, PETSC_FALSE, &Msub));

3548:   } else { /* call == MAT_INITIAL_MATRIX) */
3549:     PetscBool flg;

3551:     PetscCall(ISGetLocalSize(iscol, &n));
3552:     PetscCall(ISGetSize(iscol, &Ncols));

3554:     /* (1) iscol -> nonscalable iscol_local */
3555:     /* Check for special case: each processor gets entire matrix columns */
3556:     PetscCall(ISIdentity(iscol_local, &flg));
3557:     if (flg && n == mat->cmap->N) allcolumns = PETSC_TRUE;
3558:     PetscCallMPI(MPIU_Allreduce(MPI_IN_PLACE, &allcolumns, 1, MPI_C_BOOL, MPI_LAND, PetscObjectComm((PetscObject)mat)));
3559:     if (allcolumns) {
3560:       iscol_sub = iscol_local;
3561:       PetscCall(PetscObjectReference((PetscObject)iscol_local));
3562:       PetscCall(ISCreateStride(PETSC_COMM_SELF, n, 0, 1, &iscmap));

3564:     } else {
3565:       /* (2) iscol_local -> iscol_sub and iscmap. Implementation below requires iscol_local be sorted, it can have duplicate indices */
3566:       PetscInt *idx, *cmap1, k;
3567:       PetscCall(PetscMalloc1(Ncols, &idx));
3568:       PetscCall(PetscMalloc1(Ncols, &cmap1));
3569:       PetscCall(ISGetIndices(iscol_local, &is_idx));
3570:       count = 0;
3571:       k     = 0;
3572:       for (i = 0; i < Ncols; i++) {
3573:         j = is_idx[i];
3574:         if (j >= cstart && j < cend) {
3575:           /* diagonal part of mat */
3576:           idx[count]     = j;
3577:           cmap1[count++] = i; /* column index in submat */
3578:         } else if (Bn) {
3579:           /* off-diagonal part of mat */
3580:           if (j == garray[k]) {
3581:             idx[count]     = j;
3582:             cmap1[count++] = i; /* column index in submat */
3583:           } else if (j > garray[k]) {
3584:             while (j > garray[k] && k < Bn - 1) k++;
3585:             if (j == garray[k]) {
3586:               idx[count]     = j;
3587:               cmap1[count++] = i; /* column index in submat */
3588:             }
3589:           }
3590:         }
3591:       }
3592:       PetscCall(ISRestoreIndices(iscol_local, &is_idx));

3594:       PetscCall(ISCreateGeneral(PETSC_COMM_SELF, count, idx, PETSC_OWN_POINTER, &iscol_sub));
3595:       PetscCall(ISGetBlockSize(iscol, &cbs));
3596:       PetscCall(ISSetBlockSize(iscol_sub, cbs));

3598:       PetscCall(ISCreateGeneral(PetscObjectComm((PetscObject)iscol_local), count, cmap1, PETSC_OWN_POINTER, &iscmap));
3599:     }

3601:     /* (3) Create sequential Msub */
3602:     PetscCall(MatCreateSubMatrices_MPIAIJ_SingleIS_Local(mat, 1, &isrow, &iscol_sub, MAT_INITIAL_MATRIX, allcolumns, &Msub));
3603:   }

3605:   PetscCall(ISGetLocalSize(iscol_sub, &count));
3606:   aij = (Mat_SeqAIJ *)Msub->data;
3607:   ii  = aij->i;
3608:   PetscCall(ISGetIndices(iscmap, &cmap));

3610:   /*
3611:       m - number of local rows
3612:       Ncols - number of columns (same on all processors)
3613:       rstart - first row in new global matrix generated
3614:   */
3615:   PetscCall(MatGetSize(Msub, &m, NULL));

3617:   if (call == MAT_INITIAL_MATRIX) {
3618:     /* (4) Create parallel newmat */
3619:     PetscMPIInt rank, size;
3620:     PetscInt    csize;

3622:     PetscCallMPI(MPI_Comm_size(comm, &size));
3623:     PetscCallMPI(MPI_Comm_rank(comm, &rank));

3625:     /*
3626:         Determine the number of non-zeros in the diagonal and off-diagonal
3627:         portions of the matrix in order to do correct preallocation
3628:     */

3630:     /* first get start and end of "diagonal" columns */
3631:     PetscCall(ISGetLocalSize(iscol, &csize));
3632:     if (csize == PETSC_DECIDE) {
3633:       PetscCall(ISGetSize(isrow, &mglobal));
3634:       if (mglobal == Ncols) { /* square matrix */
3635:         nlocal = m;
3636:       } else {
3637:         nlocal = Ncols / size + ((Ncols % size) > rank);
3638:       }
3639:     } else {
3640:       nlocal = csize;
3641:     }
3642:     PetscCallMPI(MPI_Scan(&nlocal, &rend, 1, MPIU_INT, MPI_SUM, comm));
3643:     rstart = rend - nlocal;
3644:     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);

3646:     /* next, compute all the lengths */
3647:     jj = aij->j;
3648:     PetscCall(PetscMalloc1(2 * m + 1, &dlens));
3649:     olens = dlens + m;
3650:     for (i = 0; i < m; i++) {
3651:       jend = ii[i + 1] - ii[i];
3652:       olen = 0;
3653:       dlen = 0;
3654:       for (j = 0; j < jend; j++) {
3655:         if (cmap[*jj] < rstart || cmap[*jj] >= rend) olen++;
3656:         else dlen++;
3657:         jj++;
3658:       }
3659:       olens[i] = olen;
3660:       dlens[i] = dlen;
3661:     }

3663:     PetscCall(ISGetBlockSize(isrow, &bs));
3664:     PetscCall(ISGetBlockSize(iscol, &cbs));

3666:     PetscCall(MatCreate(comm, &M));
3667:     PetscCall(MatSetSizes(M, m, nlocal, PETSC_DECIDE, Ncols));
3668:     PetscCall(MatSetBlockSizes(M, bs, cbs));
3669:     PetscCall(MatSetType(M, ((PetscObject)mat)->type_name));
3670:     PetscCall(MatMPIAIJSetPreallocation(M, 0, dlens, 0, olens));
3671:     PetscCall(PetscFree(dlens));

3673:   } else { /* call == MAT_REUSE_MATRIX */
3674:     M = *newmat;
3675:     PetscCall(MatGetLocalSize(M, &i, NULL));
3676:     PetscCheck(i == m, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Previous matrix must be same size/layout as request");
3677:     PetscCall(MatZeroEntries(M));
3678:     /*
3679:          The next two lines are needed so we may call MatSetValues_MPIAIJ() below directly,
3680:        rather than the slower MatSetValues().
3681:     */
3682:     M->was_assembled = PETSC_TRUE;
3683:     M->assembled     = PETSC_FALSE;
3684:   }

3686:   /* (5) Set values of Msub to *newmat */
3687:   PetscCall(PetscMalloc1(count, &colsub));
3688:   PetscCall(MatGetOwnershipRange(M, &rstart, NULL));

3690:   jj = aij->j;
3691:   PetscCall(MatSeqAIJGetArrayRead(Msub, (const PetscScalar **)&aa));
3692:   for (i = 0; i < m; i++) {
3693:     row = rstart + i;
3694:     nz  = ii[i + 1] - ii[i];
3695:     for (j = 0; j < nz; j++) colsub[j] = cmap[jj[j]];
3696:     PetscCall(MatSetValues_MPIAIJ(M, 1, &row, nz, colsub, aa, INSERT_VALUES));
3697:     jj += nz;
3698:     aa += nz;
3699:   }
3700:   PetscCall(MatSeqAIJRestoreArrayRead(Msub, (const PetscScalar **)&aa));
3701:   PetscCall(ISRestoreIndices(iscmap, &cmap));

3703:   PetscCall(MatAssemblyBegin(M, MAT_FINAL_ASSEMBLY));
3704:   PetscCall(MatAssemblyEnd(M, MAT_FINAL_ASSEMBLY));

3706:   PetscCall(PetscFree(colsub));

3708:   /* save Msub, iscol_sub and iscmap used in processor for next request */
3709:   if (call == MAT_INITIAL_MATRIX) {
3710:     *newmat = M;
3711:     PetscCall(PetscObjectCompose((PetscObject)*newmat, "SubMatrix", (PetscObject)Msub));
3712:     PetscCall(MatDestroy(&Msub));

3714:     PetscCall(PetscObjectCompose((PetscObject)*newmat, "SubIScol", (PetscObject)iscol_sub));
3715:     PetscCall(ISDestroy(&iscol_sub));

3717:     PetscCall(PetscObjectCompose((PetscObject)*newmat, "Subcmap", (PetscObject)iscmap));
3718:     PetscCall(ISDestroy(&iscmap));

3720:     if (iscol_local) {
3721:       PetscCall(PetscObjectCompose((PetscObject)*newmat, "ISAllGather", (PetscObject)iscol_local));
3722:       PetscCall(ISDestroy(&iscol_local));
3723:     }
3724:   }
3725:   PetscFunctionReturn(PETSC_SUCCESS);
3726: }

3728: /*
3729:     Not great since it makes two copies of the submatrix, first an SeqAIJ
3730:   in local and then by concatenating the local matrices the end result.
3731:   Writing it directly would be much like MatCreateSubMatrices_MPIAIJ()

3733:   This requires a sequential iscol with all indices.
3734: */
3735: PetscErrorCode MatCreateSubMatrix_MPIAIJ_nonscalable(Mat mat, IS isrow, IS iscol, PetscInt csize, MatReuse call, Mat *newmat)
3736: {
3737:   PetscMPIInt rank, size;
3738:   PetscInt    i, m, n, rstart, row, rend, nz, *cwork, j, bs, cbs;
3739:   PetscInt   *ii, *jj, nlocal, *dlens, *olens, dlen, olen, jend, mglobal;
3740:   Mat         M, Mreuse;
3741:   MatScalar  *aa, *vwork;
3742:   MPI_Comm    comm;
3743:   Mat_SeqAIJ *aij;
3744:   PetscBool   colflag, allcolumns = PETSC_FALSE;

3746:   PetscFunctionBegin;
3747:   PetscCall(PetscObjectGetComm((PetscObject)mat, &comm));
3748:   PetscCallMPI(MPI_Comm_rank(comm, &rank));
3749:   PetscCallMPI(MPI_Comm_size(comm, &size));

3751:   /* Check for special case: each processor gets entire matrix columns */
3752:   PetscCall(ISIdentity(iscol, &colflag));
3753:   PetscCall(ISGetLocalSize(iscol, &n));
3754:   if (colflag && n == mat->cmap->N) allcolumns = PETSC_TRUE;
3755:   PetscCallMPI(MPIU_Allreduce(MPI_IN_PLACE, &allcolumns, 1, MPI_C_BOOL, MPI_LAND, PetscObjectComm((PetscObject)mat)));

3757:   if (call == MAT_REUSE_MATRIX) {
3758:     PetscCall(PetscObjectQuery((PetscObject)*newmat, "SubMatrix", (PetscObject *)&Mreuse));
3759:     PetscCheck(Mreuse, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Submatrix passed in was not used before, cannot reuse");
3760:     PetscCall(MatCreateSubMatrices_MPIAIJ_SingleIS_Local(mat, 1, &isrow, &iscol, MAT_REUSE_MATRIX, allcolumns, &Mreuse));
3761:   } else {
3762:     PetscCall(MatCreateSubMatrices_MPIAIJ_SingleIS_Local(mat, 1, &isrow, &iscol, MAT_INITIAL_MATRIX, allcolumns, &Mreuse));
3763:   }

3765:   /*
3766:       m - number of local rows
3767:       n - number of columns (same on all processors)
3768:       rstart - first row in new global matrix generated
3769:   */
3770:   PetscCall(MatGetSize(Mreuse, &m, &n));
3771:   PetscCall(MatGetBlockSizes(Mreuse, &bs, &cbs));
3772:   if (call == MAT_INITIAL_MATRIX) {
3773:     aij = (Mat_SeqAIJ *)Mreuse->data;
3774:     ii  = aij->i;
3775:     jj  = aij->j;

3777:     /*
3778:         Determine the number of non-zeros in the diagonal and off-diagonal
3779:         portions of the matrix in order to do correct preallocation
3780:     */

3782:     /* first get start and end of "diagonal" columns */
3783:     if (csize == PETSC_DECIDE) {
3784:       PetscCall(ISGetSize(isrow, &mglobal));
3785:       if (mglobal == n) { /* square matrix */
3786:         nlocal = m;
3787:       } else {
3788:         nlocal = n / size + ((n % size) > rank);
3789:       }
3790:     } else {
3791:       nlocal = csize;
3792:     }
3793:     PetscCallMPI(MPI_Scan(&nlocal, &rend, 1, MPIU_INT, MPI_SUM, comm));
3794:     rstart = rend - nlocal;
3795:     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);

3797:     /* next, compute all the lengths */
3798:     PetscCall(PetscMalloc1(2 * m + 1, &dlens));
3799:     olens = dlens + m;
3800:     for (i = 0; i < m; i++) {
3801:       jend = ii[i + 1] - ii[i];
3802:       olen = 0;
3803:       dlen = 0;
3804:       for (j = 0; j < jend; j++) {
3805:         if (*jj < rstart || *jj >= rend) olen++;
3806:         else dlen++;
3807:         jj++;
3808:       }
3809:       olens[i] = olen;
3810:       dlens[i] = dlen;
3811:     }
3812:     PetscCall(MatCreate(comm, &M));
3813:     PetscCall(MatSetSizes(M, m, nlocal, PETSC_DECIDE, n));
3814:     PetscCall(MatSetBlockSizes(M, bs, cbs));
3815:     PetscCall(MatSetType(M, ((PetscObject)mat)->type_name));
3816:     PetscCall(MatMPIAIJSetPreallocation(M, 0, dlens, 0, olens));
3817:     PetscCall(PetscFree(dlens));
3818:   } else {
3819:     PetscInt ml, nl;

3821:     M = *newmat;
3822:     PetscCall(MatGetLocalSize(M, &ml, &nl));
3823:     PetscCheck(ml == m, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Previous matrix must be same size/layout as request");
3824:     PetscCall(MatZeroEntries(M));
3825:     /*
3826:          The next two lines are needed so we may call MatSetValues_MPIAIJ() below directly,
3827:        rather than the slower MatSetValues().
3828:     */
3829:     M->was_assembled = PETSC_TRUE;
3830:     M->assembled     = PETSC_FALSE;
3831:   }
3832:   PetscCall(MatGetOwnershipRange(M, &rstart, &rend));
3833:   aij = (Mat_SeqAIJ *)Mreuse->data;
3834:   ii  = aij->i;
3835:   jj  = aij->j;

3837:   /* trigger copy to CPU if needed */
3838:   PetscCall(MatSeqAIJGetArrayRead(Mreuse, (const PetscScalar **)&aa));
3839:   for (i = 0; i < m; i++) {
3840:     row   = rstart + i;
3841:     nz    = ii[i + 1] - ii[i];
3842:     cwork = jj;
3843:     jj    = PetscSafePointerPlusOffset(jj, nz);
3844:     vwork = aa;
3845:     aa    = PetscSafePointerPlusOffset(aa, nz);
3846:     PetscCall(MatSetValues_MPIAIJ(M, 1, &row, nz, cwork, vwork, INSERT_VALUES));
3847:   }
3848:   PetscCall(MatSeqAIJRestoreArrayRead(Mreuse, (const PetscScalar **)&aa));

3850:   PetscCall(MatAssemblyBegin(M, MAT_FINAL_ASSEMBLY));
3851:   PetscCall(MatAssemblyEnd(M, MAT_FINAL_ASSEMBLY));
3852:   *newmat = M;

3854:   /* save submatrix used in processor for next request */
3855:   if (call == MAT_INITIAL_MATRIX) {
3856:     PetscCall(PetscObjectCompose((PetscObject)M, "SubMatrix", (PetscObject)Mreuse));
3857:     PetscCall(MatDestroy(&Mreuse));
3858:   }
3859:   PetscFunctionReturn(PETSC_SUCCESS);
3860: }

3862: static PetscErrorCode MatMPIAIJSetPreallocationCSR_MPIAIJ(Mat B, const PetscInt Ii[], const PetscInt J[], const PetscScalar v[])
3863: {
3864:   PetscInt        m, cstart, cend, j, nnz, i, d, *ld;
3865:   PetscInt       *d_nnz, *o_nnz, nnz_max = 0, rstart, ii, irstart;
3866:   const PetscInt *JJ;
3867:   PetscBool       nooffprocentries;
3868:   Mat_MPIAIJ     *Aij = (Mat_MPIAIJ *)B->data;

3870:   PetscFunctionBegin;
3871:   PetscCall(PetscLayoutSetUp(B->rmap));
3872:   PetscCall(PetscLayoutSetUp(B->cmap));
3873:   m       = B->rmap->n;
3874:   cstart  = B->cmap->rstart;
3875:   cend    = B->cmap->rend;
3876:   rstart  = B->rmap->rstart;
3877:   irstart = Ii[0];

3879:   PetscCall(PetscCalloc2(m, &d_nnz, m, &o_nnz));

3881:   if (PetscDefined(USE_DEBUG)) {
3882:     for (i = 0; i < m; i++) {
3883:       nnz = Ii[i + 1] - Ii[i];
3884:       JJ  = PetscSafePointerPlusOffset(J, Ii[i] - irstart);
3885:       PetscCheck(nnz >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Local row %" PetscInt_FMT " has a negative %" PetscInt_FMT " number of columns", i, nnz);
3886:       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]);
3887:       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);
3888:     }
3889:   }

3891:   for (i = 0; i < m; i++) {
3892:     nnz     = Ii[i + 1] - Ii[i];
3893:     JJ      = PetscSafePointerPlusOffset(J, Ii[i] - irstart);
3894:     nnz_max = PetscMax(nnz_max, nnz);
3895:     d       = 0;
3896:     for (j = 0; j < nnz; j++) {
3897:       if (cstart <= JJ[j] && JJ[j] < cend) d++;
3898:     }
3899:     d_nnz[i] = d;
3900:     o_nnz[i] = nnz - d;
3901:   }
3902:   PetscCall(MatMPIAIJSetPreallocation(B, 0, d_nnz, 0, o_nnz));
3903:   PetscCall(PetscFree2(d_nnz, o_nnz));

3905:   for (i = 0; i < m; i++) {
3906:     ii = i + rstart;
3907:     PetscCall(MatSetValues_MPIAIJ(B, 1, &ii, Ii[i + 1] - Ii[i], PetscSafePointerPlusOffset(J, Ii[i] - irstart), PetscSafePointerPlusOffset(v, Ii[i] - irstart), INSERT_VALUES));
3908:   }
3909:   nooffprocentries    = B->nooffprocentries;
3910:   B->nooffprocentries = PETSC_TRUE;
3911:   PetscCall(MatAssemblyBegin(B, MAT_FINAL_ASSEMBLY));
3912:   PetscCall(MatAssemblyEnd(B, MAT_FINAL_ASSEMBLY));
3913:   B->nooffprocentries = nooffprocentries;

3915:   /* count number of entries below block diagonal */
3916:   PetscCall(PetscFree(Aij->ld));
3917:   PetscCall(PetscCalloc1(m, &ld));
3918:   Aij->ld = ld;
3919:   for (i = 0; i < m; i++) {
3920:     nnz = Ii[i + 1] - Ii[i];
3921:     j   = 0;
3922:     while (j < nnz && J[j] < cstart) j++;
3923:     ld[i] = j;
3924:     if (J) J += nnz;
3925:   }

3927:   PetscCall(MatSetOption(B, MAT_NEW_NONZERO_LOCATION_ERR, PETSC_TRUE));
3928:   PetscFunctionReturn(PETSC_SUCCESS);
3929: }

3931: /*@
3932:   MatMPIAIJSetPreallocationCSR - Allocates memory for a sparse parallel matrix in `MATAIJ` format
3933:   (the default parallel PETSc format).

3935:   Collective

3937:   Input Parameters:
3938: + B - the matrix
3939: . i - the indices into `j` for the start of each local row (indices start with zero)
3940: . j - the column indices for each local row (indices start with zero)
3941: - v - optional values in the matrix

3943:   Level: developer

3945:   Notes:
3946:   The `i`, `j`, and `v` arrays ARE copied by this routine into the internal format used by PETSc;
3947:   thus you CANNOT change the matrix entries by changing the values of `v` after you have
3948:   called this routine. Use `MatCreateMPIAIJWithSplitArrays()` to avoid needing to copy the arrays.

3950:   The `i` and `j` indices are 0 based, and `i` indices are indices corresponding to the local `j` array.

3952:   A convenience routine for this functionality is `MatCreateMPIAIJWithArrays()`.

3954:   You can update the matrix with new numerical values using `MatUpdateMPIAIJWithArrays()` after this call if the column indices in `j` are sorted.

3956:   If you do **not** use `MatUpdateMPIAIJWithArrays()`, the column indices in `j` do not need to be sorted. If you will use
3957:   `MatUpdateMPIAIJWithArrays()`, the column indices **must** be sorted.

3959:   The format which is used for the sparse matrix input, is equivalent to a
3960:   row-major ordering.. i.e for the following matrix, the input data expected is
3961:   as shown
3962: .vb
3963:         1 0 0
3964:         2 0 3     P0
3965:        -------
3966:         4 5 6     P1

3968:      Process0 [P0] rows_owned=[0,1]
3969:         i =  {0,1,3}  [size = nrow+1  = 2+1]
3970:         j =  {0,0,2}  [size = 3]
3971:         v =  {1,2,3}  [size = 3]

3973:      Process1 [P1] rows_owned=[2]
3974:         i =  {0,3}    [size = nrow+1  = 1+1]
3975:         j =  {0,1,2}  [size = 3]
3976:         v =  {4,5,6}  [size = 3]
3977: .ve

3979: .seealso: [](ch_matrices), `Mat`, `MATMPIAIJ`, `MatCreate()`, `MatCreateSeqAIJ()`, `MatSetValues()`, `MatMPIAIJSetPreallocation()`, `MatCreateAIJ()`,
3980:           `MatCreateSeqAIJWithArrays()`, `MatCreateMPIAIJWithSplitArrays()`, `MatCreateMPIAIJWithArrays()`, `MatSetPreallocationCOO()`, `MatSetValuesCOO()`
3981: @*/
3982: PetscErrorCode MatMPIAIJSetPreallocationCSR(Mat B, const PetscInt i[], const PetscInt j[], const PetscScalar v[])
3983: {
3984:   PetscFunctionBegin;
3985:   PetscTryMethod(B, "MatMPIAIJSetPreallocationCSR_C", (Mat, const PetscInt[], const PetscInt[], const PetscScalar[]), (B, i, j, v));
3986:   PetscFunctionReturn(PETSC_SUCCESS);
3987: }

3989: /*@
3990:   MatMPIAIJSetPreallocation - Preallocates memory for a sparse parallel matrix in `MATMPIAIJ` format
3991:   (the default parallel PETSc format).  For good matrix assembly performance
3992:   the user should preallocate the matrix storage by setting the parameters
3993:   `d_nz` (or `d_nnz`) and `o_nz` (or `o_nnz`).

3995:   Collective

3997:   Input Parameters:
3998: + B     - the matrix
3999: . d_nz  - number of nonzeros per row in DIAGONAL portion of local submatrix
4000:            (same value is used for all local rows)
4001: . d_nnz - array containing the number of nonzeros in the various rows of the
4002:            DIAGONAL portion of the local submatrix (possibly different for each row)
4003:            or `NULL` (`PETSC_NULL_INTEGER` in Fortran), if `d_nz` is used to specify the nonzero structure.
4004:            The size of this array is equal to the number of local rows, i.e 'm'.
4005:            For matrices that will be factored, you must leave room for (and set)
4006:            the diagonal entry even if it is zero.
4007: . o_nz  - number of nonzeros per row in the OFF-DIAGONAL portion of local
4008:            submatrix (same value is used for all local rows).
4009: - o_nnz - array containing the number of nonzeros in the various rows of the
4010:            OFF-DIAGONAL portion of the local submatrix (possibly different for
4011:            each row) or `NULL` (`PETSC_NULL_INTEGER` in Fortran), if `o_nz` is used to specify the nonzero
4012:            structure. The size of this array is equal to the number
4013:            of local rows, i.e 'm'.

4015:   Example Usage:
4016:   Consider the following 8x8 matrix with 34 non-zero values, that is
4017:   assembled across 3 processors. Lets assume that proc0 owns 3 rows,
4018:   proc1 owns 3 rows, proc2 owns 2 rows. This division can be shown
4019:   as follows

4021: .vb
4022:             1  2  0  |  0  3  0  |  0  4
4023:     Proc0   0  5  6  |  7  0  0  |  8  0
4024:             9  0 10  | 11  0  0  | 12  0
4025:     -------------------------------------
4026:            13  0 14  | 15 16 17  |  0  0
4027:     Proc1   0 18  0  | 19 20 21  |  0  0
4028:             0  0  0  | 22 23  0  | 24  0
4029:     -------------------------------------
4030:     Proc2  25 26 27  |  0  0 28  | 29  0
4031:            30  0  0  | 31 32 33  |  0 34
4032: .ve

4034:   This can be represented as a collection of submatrices as
4035: .vb
4036:       A B C
4037:       D E F
4038:       G H I
4039: .ve

4041:   Where the submatrices A,B,C are owned by proc0, D,E,F are
4042:   owned by proc1, G,H,I are owned by proc2.

4044:   The 'm' parameters for proc0,proc1,proc2 are 3,3,2 respectively.
4045:   The 'n' parameters for proc0,proc1,proc2 are 3,3,2 respectively.
4046:   The 'M','N' parameters are 8,8, and have the same values on all procs.

4048:   The DIAGONAL submatrices corresponding to proc0,proc1,proc2 are
4049:   submatrices [A], [E], [I] respectively. The OFF-DIAGONAL submatrices
4050:   corresponding to proc0,proc1,proc2 are [BC], [DF], [GH] respectively.
4051:   Internally, each processor stores the DIAGONAL part, and the OFF-DIAGONAL
4052:   part as `MATSEQAIJ` matrices. For example, proc1 will store [E] as a `MATSEQAIJ`
4053:   matrix, and [DF] as another `MATSEQAIJ` matrix.

4055:   When `d_nz`, `o_nz` parameters are specified, `d_nz` storage elements are
4056:   allocated for every row of the local DIAGONAL submatrix, and `o_nz`
4057:   storage locations are allocated for every row of the OFF-DIAGONAL submatrix.
4058:   One way to choose `d_nz` and `o_nz` is to use the maximum number of nonzeros over
4059:   the local rows for each of the local DIAGONAL, and the OFF-DIAGONAL submatrices.
4060:   In this case, the values of `d_nz`, `o_nz` are
4061: .vb
4062:      proc0  dnz = 2, o_nz = 2
4063:      proc1  dnz = 3, o_nz = 2
4064:      proc2  dnz = 1, o_nz = 4
4065: .ve
4066:   We are allocating `m`*(`d_nz`+`o_nz`) storage locations for every proc. This
4067:   translates to 3*(2+2)=12 for proc0, 3*(3+2)=15 for proc1, 2*(1+4)=10
4068:   for proc3. i.e we are using 12+15+10=37 storage locations to store
4069:   34 values.

4071:   When `d_nnz`, `o_nnz` parameters are specified, the storage is specified
4072:   for every row, corresponding to both DIAGONAL and OFF-DIAGONAL submatrices.
4073:   In the above case the values for `d_nnz`, `o_nnz` are
4074: .vb
4075:      proc0 d_nnz = [2,2,2] and o_nnz = [2,2,2]
4076:      proc1 d_nnz = [3,3,2] and o_nnz = [2,1,1]
4077:      proc2 d_nnz = [1,1]   and o_nnz = [4,4]
4078: .ve
4079:   Here the space allocated is sum of all the above values i.e 34, and
4080:   hence pre-allocation is perfect.

4082:   Level: intermediate

4084:   Notes:
4085:   If the *_nnz parameter is given then the *_nz parameter is ignored

4087:   The `MATAIJ` format, also called compressed row storage (CSR), is compatible with standard Fortran
4088:   storage.  The stored row and column indices begin with zero.
4089:   See [Sparse Matrices](sec_matsparse) for details.

4091:   The parallel matrix is partitioned such that the first m0 rows belong to
4092:   process 0, the next m1 rows belong to process 1, the next m2 rows belong
4093:   to process 2 etc.. where m0,m1,m2... are the input parameter 'm'.

4095:   The DIAGONAL portion of the local submatrix of a processor can be defined
4096:   as the submatrix which is obtained by extraction the part corresponding to
4097:   the rows r1-r2 and columns c1-c2 of the global matrix, where r1 is the
4098:   first row that belongs to the processor, r2 is the last row belonging to
4099:   the this processor, and c1-c2 is range of indices of the local part of a
4100:   vector suitable for applying the matrix to.  This is an mxn matrix.  In the
4101:   common case of a square matrix, the row and column ranges are the same and
4102:   the DIAGONAL part is also square. The remaining portion of the local
4103:   submatrix (mxN) constitute the OFF-DIAGONAL portion.

4105:   If `o_nnz` and `d_nnz` are specified, then `o_nz` and `d_nz` are ignored.

4107:   You can call `MatGetInfo()` to get information on how effective the preallocation was;
4108:   for example the fields mallocs,nz_allocated,nz_used,nz_unneeded;
4109:   You can also run with the option `-info` and look for messages with the string
4110:   malloc in them to see if additional memory allocation was needed.

4112: .seealso: [](ch_matrices), `Mat`, [Sparse Matrices](sec_matsparse), `MATMPIAIJ`, `MATAIJ`, `MatCreate()`, `MatCreateSeqAIJ()`, `MatSetValues()`, `MatCreateAIJ()`, `MatMPIAIJSetPreallocationCSR()`,
4113:           `MatGetInfo()`, `PetscSplitOwnership()`, `MatSetPreallocationCOO()`, `MatSetValuesCOO()`
4114: @*/
4115: PetscErrorCode MatMPIAIJSetPreallocation(Mat B, PetscInt d_nz, const PetscInt d_nnz[], PetscInt o_nz, const PetscInt o_nnz[])
4116: {
4117:   PetscFunctionBegin;
4120:   PetscTryMethod(B, "MatMPIAIJSetPreallocation_C", (Mat, PetscInt, const PetscInt[], PetscInt, const PetscInt[]), (B, d_nz, d_nnz, o_nz, o_nnz));
4121:   PetscFunctionReturn(PETSC_SUCCESS);
4122: }

4124: /*@
4125:   MatCreateMPIAIJWithArrays - creates a `MATMPIAIJ` matrix using arrays that contain in standard
4126:   CSR format for the local rows.

4128:   Collective

4130:   Input Parameters:
4131: + comm - MPI communicator
4132: . m    - number of local rows (Cannot be `PETSC_DECIDE`)
4133: . n    - This value should be the same as the local size used in creating the
4134:          x vector for the matrix-vector product $ y = Ax$. (or `PETSC_DECIDE` to have
4135:          calculated if `N` is given) For square matrices n is almost always `m`.
4136: . M    - number of global rows (or `PETSC_DETERMINE` to have calculated if `m` is given)
4137: . N    - number of global columns (or `PETSC_DETERMINE` to have calculated if `n` is given)
4138: . 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
4139: . j    - global column indices
4140: - a    - optional matrix values

4142:   Output Parameter:
4143: . mat - the matrix

4145:   Level: intermediate

4147:   Notes:
4148:   The `i`, `j`, and `a` arrays ARE copied by this routine into the internal format used by PETSc;
4149:   thus you CANNOT change the matrix entries by changing the values of `a[]` after you have
4150:   called this routine. Use `MatCreateMPIAIJWithSplitArrays()` to avoid needing to copy the arrays.

4152:   The `i` and `j` indices are 0 based, and `i` indices are indices corresponding to the local `j` array.

4154:   Once you have created the matrix you can update it with new numerical values using `MatUpdateMPIAIJWithArray()`

4156:   If you do **not** use `MatUpdateMPIAIJWithArray()`, the column indices in `j` do not need to be sorted. If you will use
4157:   `MatUpdateMPIAIJWithArrays()`, the column indices **must** be sorted.

4159:   The format which is used for the sparse matrix input, is equivalent to a
4160:   row-major ordering, i.e., for the following matrix, the input data expected is
4161:   as shown
4162: .vb
4163:         1 0 0
4164:         2 0 3     P0
4165:        -------
4166:         4 5 6     P1

4168:      Process0 [P0] rows_owned=[0,1]
4169:         i =  {0,1,3}  [size = nrow+1  = 2+1]
4170:         j =  {0,0,2}  [size = 3]
4171:         v =  {1,2,3}  [size = 3]

4173:      Process1 [P1] rows_owned=[2]
4174:         i =  {0,3}    [size = nrow+1  = 1+1]
4175:         j =  {0,1,2}  [size = 3]
4176:         v =  {4,5,6}  [size = 3]
4177: .ve

4179: .seealso: [](ch_matrices), `Mat`, `MatCreate()`, `MatCreateSeqAIJ()`, `MatSetValues()`, `MatMPIAIJSetPreallocation()`, `MatMPIAIJSetPreallocationCSR()`,
4180:           `MATMPIAIJ`, `MatCreateAIJ()`, `MatCreateMPIAIJWithSplitArrays()`, `MatUpdateMPIAIJWithArray()`, `MatSetPreallocationCOO()`, `MatSetValuesCOO()`
4181: @*/
4182: PetscErrorCode MatCreateMPIAIJWithArrays(MPI_Comm comm, PetscInt m, PetscInt n, PetscInt M, PetscInt N, const PetscInt i[], const PetscInt j[], const PetscScalar a[], Mat *mat)
4183: {
4184:   PetscFunctionBegin;
4185:   PetscCheck(!i || !i[0], PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "i (row indices) must start with 0");
4186:   PetscCheck(m >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "local number of rows (m) cannot be PETSC_DECIDE, or negative");
4187:   PetscCall(MatCreate(comm, mat));
4188:   PetscCall(MatSetSizes(*mat, m, n, M, N));
4189:   /* PetscCall(MatSetBlockSizes(M,bs,cbs)); */
4190:   PetscCall(MatSetType(*mat, MATMPIAIJ));
4191:   PetscCall(MatMPIAIJSetPreallocationCSR(*mat, i, j, a));
4192:   PetscFunctionReturn(PETSC_SUCCESS);
4193: }

4195: /*@
4196:   MatUpdateMPIAIJWithArrays - updates a `MATMPIAIJ` matrix using arrays that contain in standard
4197:   CSR format for the local rows. Only the numerical values are updated the other arrays must be identical to what was passed
4198:   from `MatCreateMPIAIJWithArrays()`

4200:   Deprecated: Use `MatUpdateMPIAIJWithArray()`

4202:   Collective

4204:   Input Parameters:
4205: + mat - the matrix
4206: . m   - number of local rows (Cannot be `PETSC_DECIDE`)
4207: . n   - This value should be the same as the local size used in creating the
4208:        x vector for the matrix-vector product y = Ax. (or `PETSC_DECIDE` to have
4209:        calculated if N is given) For square matrices n is almost always m.
4210: . M   - number of global rows (or `PETSC_DETERMINE` to have calculated if m is given)
4211: . N   - number of global columns (or `PETSC_DETERMINE` to have calculated if n is given)
4212: . Ii  - row indices; that is Ii[0] = 0, Ii[row] = Ii[row-1] + number of elements in that row of the matrix
4213: . J   - column indices
4214: - v   - matrix values

4216:   Level: deprecated

4218: .seealso: [](ch_matrices), `Mat`, `MATMPIAIJ`, `MatCreate()`, `MatCreateSeqAIJ()`, `MatSetValues()`, `MatMPIAIJSetPreallocation()`, `MatMPIAIJSetPreallocationCSR()`,
4219:           `MatCreateAIJ()`, `MatCreateMPIAIJWithSplitArrays()`, `MatUpdateMPIAIJWithArray()`, `MatSetPreallocationCOO()`, `MatSetValuesCOO()`
4220: @*/
4221: PetscErrorCode MatUpdateMPIAIJWithArrays(Mat mat, PetscInt m, PetscInt n, PetscInt M, PetscInt N, const PetscInt Ii[], const PetscInt J[], const PetscScalar v[])
4222: {
4223:   PetscInt        nnz, i;
4224:   PetscBool       nooffprocentries;
4225:   Mat_MPIAIJ     *Aij = (Mat_MPIAIJ *)mat->data;
4226:   Mat_SeqAIJ     *Ad  = (Mat_SeqAIJ *)Aij->A->data;
4227:   PetscScalar    *ad, *ao;
4228:   PetscInt        ldi, Iii, md;
4229:   const PetscInt *Adi = Ad->i;
4230:   PetscInt       *ld  = Aij->ld;

4232:   PetscFunctionBegin;
4233:   PetscCheck(Ii[0] == 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "i (row indices) must start with 0");
4234:   PetscCheck(m >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "local number of rows (m) cannot be PETSC_DECIDE, or negative");
4235:   PetscCheck(m == mat->rmap->n, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Local number of rows cannot change from call to MatUpdateMPIAIJWithArrays()");
4236:   PetscCheck(n == mat->cmap->n, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Local number of columns cannot change from call to MatUpdateMPIAIJWithArrays()");

4238:   PetscCall(MatSeqAIJGetArrayWrite(Aij->A, &ad));
4239:   PetscCall(MatSeqAIJGetArrayWrite(Aij->B, &ao));

4241:   for (i = 0; i < m; i++) {
4242:     if (PetscDefined(USE_DEBUG)) {
4243:       for (PetscInt j = Ii[i] + 1; j < Ii[i + 1]; ++j) {
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 not sorted", j - Ii[i], J[j], i);
4245:         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);
4246:       }
4247:     }
4248:     nnz = Ii[i + 1] - Ii[i];
4249:     Iii = Ii[i];
4250:     ldi = ld[i];
4251:     md  = Adi[i + 1] - Adi[i];
4252:     PetscCall(PetscArraycpy(ao, v + Iii, ldi));
4253:     PetscCall(PetscArraycpy(ad, v + Iii + ldi, md));
4254:     PetscCall(PetscArraycpy(ao + ldi, v + Iii + ldi + md, nnz - ldi - md));
4255:     ad += md;
4256:     ao += nnz - md;
4257:   }
4258:   nooffprocentries      = mat->nooffprocentries;
4259:   mat->nooffprocentries = PETSC_TRUE;
4260:   PetscCall(MatSeqAIJRestoreArrayWrite(Aij->A, &ad));
4261:   PetscCall(MatSeqAIJRestoreArrayWrite(Aij->B, &ao));
4262:   PetscCall(PetscObjectStateIncrease((PetscObject)Aij->A));
4263:   PetscCall(PetscObjectStateIncrease((PetscObject)Aij->B));
4264:   PetscCall(PetscObjectStateIncrease((PetscObject)mat));
4265:   PetscCall(MatAssemblyBegin(mat, MAT_FINAL_ASSEMBLY));
4266:   PetscCall(MatAssemblyEnd(mat, MAT_FINAL_ASSEMBLY));
4267:   mat->nooffprocentries = nooffprocentries;
4268:   PetscFunctionReturn(PETSC_SUCCESS);
4269: }

4271: /*@
4272:   MatUpdateMPIAIJWithArray - updates an `MATMPIAIJ` matrix using an array that contains the nonzero values

4274:   Collective

4276:   Input Parameters:
4277: + mat - the matrix
4278: - v   - matrix values, stored by row

4280:   Level: intermediate

4282:   Notes:
4283:   The matrix must have been obtained with `MatCreateMPIAIJWithArrays()` or `MatMPIAIJSetPreallocationCSR()`

4285:   The column indices in the call to `MatCreateMPIAIJWithArrays()` or `MatMPIAIJSetPreallocationCSR()` must have been sorted for this call to work correctly

4287: .seealso: [](ch_matrices), `Mat`, `MatCreate()`, `MatCreateSeqAIJ()`, `MatSetValues()`, `MatMPIAIJSetPreallocation()`, `MatMPIAIJSetPreallocationCSR()`,
4288:           `MATMPIAIJ`, `MatCreateAIJ()`, `MatCreateMPIAIJWithSplitArrays()`, `MatUpdateMPIAIJWithArrays()`, `MatSetPreallocationCOO()`, `MatSetValuesCOO()`
4289: @*/
4290: PetscErrorCode MatUpdateMPIAIJWithArray(Mat mat, const PetscScalar v[])
4291: {
4292:   PetscInt        nnz, i, m;
4293:   PetscBool       nooffprocentries;
4294:   Mat_MPIAIJ     *Aij = (Mat_MPIAIJ *)mat->data;
4295:   Mat_SeqAIJ     *Ad  = (Mat_SeqAIJ *)Aij->A->data;
4296:   Mat_SeqAIJ     *Ao  = (Mat_SeqAIJ *)Aij->B->data;
4297:   PetscScalar    *ad, *ao;
4298:   const PetscInt *Adi = Ad->i, *Adj = Ao->i;
4299:   PetscInt        ldi, Iii, md;
4300:   PetscInt       *ld = Aij->ld;

4302:   PetscFunctionBegin;
4303:   m = mat->rmap->n;

4305:   PetscCall(MatSeqAIJGetArrayWrite(Aij->A, &ad));
4306:   PetscCall(MatSeqAIJGetArrayWrite(Aij->B, &ao));
4307:   Iii = 0;
4308:   for (i = 0; i < m; i++) {
4309:     nnz = Adi[i + 1] - Adi[i] + Adj[i + 1] - Adj[i];
4310:     ldi = ld[i];
4311:     md  = Adi[i + 1] - Adi[i];
4312:     PetscCall(PetscArraycpy(ad, v + Iii + ldi, md));
4313:     ad += md;
4314:     if (ao) {
4315:       PetscCall(PetscArraycpy(ao, v + Iii, ldi));
4316:       PetscCall(PetscArraycpy(ao + ldi, v + Iii + ldi + md, nnz - ldi - md));
4317:       ao += nnz - md;
4318:     }
4319:     Iii += nnz;
4320:   }
4321:   nooffprocentries      = mat->nooffprocentries;
4322:   mat->nooffprocentries = PETSC_TRUE;
4323:   PetscCall(MatSeqAIJRestoreArrayWrite(Aij->A, &ad));
4324:   PetscCall(MatSeqAIJRestoreArrayWrite(Aij->B, &ao));
4325:   PetscCall(PetscObjectStateIncrease((PetscObject)Aij->A));
4326:   PetscCall(PetscObjectStateIncrease((PetscObject)Aij->B));
4327:   PetscCall(PetscObjectStateIncrease((PetscObject)mat));
4328:   PetscCall(MatAssemblyBegin(mat, MAT_FINAL_ASSEMBLY));
4329:   PetscCall(MatAssemblyEnd(mat, MAT_FINAL_ASSEMBLY));
4330:   mat->nooffprocentries = nooffprocentries;
4331:   PetscFunctionReturn(PETSC_SUCCESS);
4332: }

4334: /*@
4335:   MatCreateAIJ - Creates a sparse parallel matrix in `MATAIJ` format
4336:   (the default parallel PETSc format).  For good matrix assembly performance
4337:   the user should preallocate the matrix storage by setting the parameters
4338:   `d_nz` (or `d_nnz`) and `o_nz` (or `o_nnz`).

4340:   Collective

4342:   Input Parameters:
4343: + comm  - MPI communicator
4344: . m     - number of local rows (or `PETSC_DECIDE` to have calculated if M is given)
4345:           This value should be the same as the local size used in creating the
4346:           y vector for the matrix-vector product y = Ax.
4347: . n     - This value should be the same as the local size used in creating the
4348:           x vector for the matrix-vector product y = Ax. (or `PETSC_DECIDE` to have
4349:           calculated if N is given) For square matrices n is almost always m.
4350: . M     - number of global rows (or `PETSC_DETERMINE` to have calculated if m is given)
4351: . N     - number of global columns (or `PETSC_DETERMINE` to have calculated if n is given)
4352: . d_nz  - number of nonzeros per row in DIAGONAL portion of local submatrix
4353:           (same value is used for all local rows)
4354: . d_nnz - array containing the number of nonzeros in the various rows of the
4355:           DIAGONAL portion of the local submatrix (possibly different for each row)
4356:           or `NULL`, if `d_nz` is used to specify the nonzero structure.
4357:           The size of this array is equal to the number of local rows, i.e 'm'.
4358: . o_nz  - number of nonzeros per row in the OFF-DIAGONAL portion of local
4359:           submatrix (same value is used for all local rows).
4360: - o_nnz - array containing the number of nonzeros in the various rows of the
4361:           OFF-DIAGONAL portion of the local submatrix (possibly different for
4362:           each row) or `NULL`, if `o_nz` is used to specify the nonzero
4363:           structure. The size of this array is equal to the number
4364:           of local rows, i.e 'm'.

4366:   Output Parameter:
4367: . A - the matrix

4369:   Options Database Keys:
4370: + -mat_no_inode                   - Do not use inodes
4371: . -mat_inode_limit limit          - Sets inode limit (max limit=5)
4372: - -matmult_vecscatter_view viewer - View the vecscatter (i.e., communication pattern) used in `MatMult()` of sparse parallel matrices.
4373:                                     See viewer types in manual of `MatView()`. Of them, ascii_matlab, draw or binary cause the `VecScatter`
4374:                                     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.

4376:   Level: intermediate

4378:   Notes:
4379:   It is recommended that one use `MatCreateFromOptions()` or the `MatCreate()`, `MatSetType()` and/or `MatSetFromOptions()`,
4380:   MatXXXXSetPreallocation() paradigm instead of this routine directly.
4381:   [MatXXXXSetPreallocation() is, for example, `MatSeqAIJSetPreallocation()`]

4383:   If the *_nnz parameter is given then the *_nz parameter is ignored

4385:   The `m`,`n`,`M`,`N` parameters specify the size of the matrix, and its partitioning across
4386:   processors, while `d_nz`,`d_nnz`,`o_nz`,`o_nnz` parameters specify the approximate
4387:   storage requirements for this matrix.

4389:   If `PETSC_DECIDE` or  `PETSC_DETERMINE` is used for a particular argument on one
4390:   processor than it must be used on all processors that share the object for
4391:   that argument.

4393:   If `m` and `n` are not `PETSC_DECIDE`, then the values determine the `PetscLayout` of the matrix and the ranges returned by
4394:   `MatGetOwnershipRange()`, `MatGetOwnershipRanges()`, `MatGetOwnershipRangeColumn()`, and `MatGetOwnershipRangesColumn()`.

4396:   The user MUST specify either the local or global matrix dimensions
4397:   (possibly both).

4399:   The parallel matrix is partitioned across processors such that the
4400:   first `m0` rows belong to process 0, the next `m1` rows belong to
4401:   process 1, the next `m2` rows belong to process 2, etc., where
4402:   `m0`, `m1`, `m2`... are the input parameter `m` on each MPI process. I.e., each MPI process stores
4403:   values corresponding to [m x N] submatrix.

4405:   The columns are logically partitioned with the n0 columns belonging
4406:   to 0th partition, the next n1 columns belonging to the next
4407:   partition etc.. where n0,n1,n2... are the input parameter 'n'.

4409:   The DIAGONAL portion of the local submatrix on any given processor
4410:   is the submatrix corresponding to the rows and columns m,n
4411:   corresponding to the given processor. i.e diagonal matrix on
4412:   process 0 is [m0 x n0], diagonal matrix on process 1 is [m1 x n1]
4413:   etc. The remaining portion of the local submatrix [m x (N-n)]
4414:   constitute the OFF-DIAGONAL portion. The example below better
4415:   illustrates this concept. The two matrices, the DIAGONAL portion and
4416:   the OFF-DIAGONAL portion are each stored as `MATSEQAIJ` matrices.

4418:   For a square global matrix we define each processor's diagonal portion
4419:   to be its local rows and the corresponding columns (a square submatrix);
4420:   each processor's off-diagonal portion encompasses the remainder of the
4421:   local matrix (a rectangular submatrix).

4423:   If `o_nnz`, `d_nnz` are specified, then `o_nz`, and `d_nz` are ignored.

4425:   When calling this routine with a single process communicator, a matrix of
4426:   type `MATSEQAIJ` is returned.  If a matrix of type `MATMPIAIJ` is desired for this
4427:   type of communicator, use the construction mechanism
4428: .vb
4429:   MatCreate(..., &A);
4430:   MatSetType(A, MATMPIAIJ);
4431:   MatSetSizes(A, m, n, M, N);
4432:   MatMPIAIJSetPreallocation(A, ...);
4433: .ve

4435:   By default, this format uses inodes (identical nodes) when possible.
4436:   We search for consecutive rows with the same nonzero structure, thereby
4437:   reusing matrix information to achieve increased efficiency.

4439:   Example Usage:
4440:   Consider the following 8x8 matrix with 34 non-zero values, that is
4441:   assembled across 3 processors. Lets assume that proc0 owns 3 rows,
4442:   proc1 owns 3 rows, proc2 owns 2 rows. This division can be shown
4443:   as follows

4445: .vb
4446:             1  2  0  |  0  3  0  |  0  4
4447:     Proc0   0  5  6  |  7  0  0  |  8  0
4448:             9  0 10  | 11  0  0  | 12  0
4449:     -------------------------------------
4450:            13  0 14  | 15 16 17  |  0  0
4451:     Proc1   0 18  0  | 19 20 21  |  0  0
4452:             0  0  0  | 22 23  0  | 24  0
4453:     -------------------------------------
4454:     Proc2  25 26 27  |  0  0 28  | 29  0
4455:            30  0  0  | 31 32 33  |  0 34
4456: .ve

4458:   This can be represented as a collection of submatrices as

4460: .vb
4461:       A B C
4462:       D E F
4463:       G H I
4464: .ve

4466:   Where the submatrices A,B,C are owned by proc0, D,E,F are
4467:   owned by proc1, G,H,I are owned by proc2.

4469:   The 'm' parameters for proc0,proc1,proc2 are 3,3,2 respectively.
4470:   The 'n' parameters for proc0,proc1,proc2 are 3,3,2 respectively.
4471:   The 'M','N' parameters are 8,8, and have the same values on all procs.

4473:   The DIAGONAL submatrices corresponding to proc0,proc1,proc2 are
4474:   submatrices [A], [E], [I] respectively. The OFF-DIAGONAL submatrices
4475:   corresponding to proc0,proc1,proc2 are [BC], [DF], [GH] respectively.
4476:   Internally, each processor stores the DIAGONAL part, and the OFF-DIAGONAL
4477:   part as `MATSEQAIJ` matrices. For example, proc1 will store [E] as a `MATSEQAIJ`
4478:   matrix, and [DF] as another SeqAIJ matrix.

4480:   When `d_nz`, `o_nz` parameters are specified, `d_nz` storage elements are
4481:   allocated for every row of the local DIAGONAL submatrix, and `o_nz`
4482:   storage locations are allocated for every row of the OFF-DIAGONAL submatrix.
4483:   One way to choose `d_nz` and `o_nz` is to use the maximum number of nonzeros over
4484:   the local rows for each of the local DIAGONAL, and the OFF-DIAGONAL submatrices.
4485:   In this case, the values of `d_nz`,`o_nz` are
4486: .vb
4487:      proc0  dnz = 2, o_nz = 2
4488:      proc1  dnz = 3, o_nz = 2
4489:      proc2  dnz = 1, o_nz = 4
4490: .ve
4491:   We are allocating m*(`d_nz`+`o_nz`) storage locations for every proc. This
4492:   translates to 3*(2+2)=12 for proc0, 3*(3+2)=15 for proc1, 2*(1+4)=10
4493:   for proc3. i.e we are using 12+15+10=37 storage locations to store
4494:   34 values.

4496:   When `d_nnz`, `o_nnz` parameters are specified, the storage is specified
4497:   for every row, corresponding to both DIAGONAL and OFF-DIAGONAL submatrices.
4498:   In the above case the values for d_nnz,o_nnz are
4499: .vb
4500:      proc0 d_nnz = [2,2,2] and o_nnz = [2,2,2]
4501:      proc1 d_nnz = [3,3,2] and o_nnz = [2,1,1]
4502:      proc2 d_nnz = [1,1]   and o_nnz = [4,4]
4503: .ve
4504:   Here the space allocated is sum of all the above values i.e 34, and
4505:   hence pre-allocation is perfect.

4507: .seealso: [](ch_matrices), `Mat`, [Sparse Matrix Creation](sec_matsparse), `MatCreate()`, `MatCreateSeqAIJ()`, `MatSetValues()`, `MatMPIAIJSetPreallocation()`, `MatMPIAIJSetPreallocationCSR()`,
4508:           `MATMPIAIJ`, `MatCreateMPIAIJWithArrays()`, `MatGetOwnershipRange()`, `MatGetOwnershipRanges()`, `MatGetOwnershipRangeColumn()`,
4509:           `MatGetOwnershipRangesColumn()`, `PetscLayout`
4510: @*/
4511: 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)
4512: {
4513:   PetscMPIInt size;

4515:   PetscFunctionBegin;
4516:   PetscCall(MatCreate(comm, A));
4517:   PetscCall(MatSetSizes(*A, m, n, M, N));
4518:   PetscCallMPI(MPI_Comm_size(comm, &size));
4519:   if (size > 1) {
4520:     PetscCall(MatSetType(*A, MATMPIAIJ));
4521:     PetscCall(MatMPIAIJSetPreallocation(*A, d_nz, d_nnz, o_nz, o_nnz));
4522:   } else {
4523:     PetscCall(MatSetType(*A, MATSEQAIJ));
4524:     PetscCall(MatSeqAIJSetPreallocation(*A, d_nz, d_nnz));
4525:   }
4526:   PetscFunctionReturn(PETSC_SUCCESS);
4527: }

4529: /*@C
4530:   MatMPIAIJGetSeqAIJ - Returns the local pieces of this distributed matrix

4532:   Not Collective

4534:   Input Parameter:
4535: . A - The `MATMPIAIJ` matrix

4537:   Output Parameters:
4538: + Ad     - The local diagonal block as a `MATSEQAIJ` matrix
4539: . Ao     - The local off-diagonal block as a `MATSEQAIJ` matrix
4540: - colmap - An array mapping local column numbers of `Ao` to global column numbers of the parallel matrix

4542:   Level: intermediate

4544:   Note:
4545:   The rows in `Ad` and `Ao` are in [0, Nr), where Nr is the number of local rows on this process. The columns
4546:   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
4547:   the number of nonzero columns in the local off-diagonal piece of the matrix `A`. The array colmap maps these
4548:   local column numbers to global column numbers in the original matrix.

4550: .seealso: [](ch_matrices), `Mat`, `MATMPIAIJ`, `MatMPIAIJGetLocalMat()`, `MatMPIAIJGetLocalMatCondensed()`, `MatCreateAIJ()`, `MATSEQAIJ`
4551: @*/
4552: PetscErrorCode MatMPIAIJGetSeqAIJ(Mat A, Mat *Ad, Mat *Ao, const PetscInt *colmap[])
4553: {
4554:   Mat_MPIAIJ *a = (Mat_MPIAIJ *)A->data;
4555:   PetscBool   flg;

4557:   PetscFunctionBegin;
4558:   PetscCall(PetscStrbeginswith(((PetscObject)A)->type_name, MATMPIAIJ, &flg));
4559:   PetscCheck(flg, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "This function requires a MATMPIAIJ matrix as input");
4560:   if (Ad) *Ad = a->A;
4561:   if (Ao) *Ao = a->B;
4562:   if (colmap) *colmap = a->garray;
4563:   PetscFunctionReturn(PETSC_SUCCESS);
4564: }

4566: PetscErrorCode MatCreateMPIMatConcatenateSeqMat_MPIAIJ(MPI_Comm comm, Mat inmat, PetscInt n, MatReuse scall, Mat *outmat)
4567: {
4568:   PetscInt     m, N, i, rstart, nnz, Ii;
4569:   PetscInt    *indx;
4570:   PetscScalar *values;
4571:   MatType      rootType;

4573:   PetscFunctionBegin;
4574:   PetscCall(MatGetSize(inmat, &m, &N));
4575:   if (scall == MAT_INITIAL_MATRIX) { /* symbolic phase */
4576:     PetscInt *dnz, *onz, sum, bs, cbs;

4578:     if (n == PETSC_DECIDE) PetscCall(PetscSplitOwnership(comm, &n, &N));
4579:     /* Check sum(n) = N */
4580:     PetscCallMPI(MPIU_Allreduce(&n, &sum, 1, MPIU_INT, MPI_SUM, comm));
4581:     PetscCheck(sum == N, PETSC_COMM_SELF, PETSC_ERR_ARG_INCOMP, "Sum of local columns %" PetscInt_FMT " != global columns %" PetscInt_FMT, sum, N);

4583:     PetscCallMPI(MPI_Scan(&m, &rstart, 1, MPIU_INT, MPI_SUM, comm));
4584:     rstart -= m;

4586:     MatPreallocateBegin(comm, m, n, dnz, onz);
4587:     for (i = 0; i < m; i++) {
4588:       PetscCall(MatGetRow_SeqAIJ(inmat, i, &nnz, &indx, NULL));
4589:       PetscCall(MatPreallocateSet(i + rstart, nnz, indx, dnz, onz));
4590:       PetscCall(MatRestoreRow_SeqAIJ(inmat, i, &nnz, &indx, NULL));
4591:     }

4593:     PetscCall(MatCreate(comm, outmat));
4594:     PetscCall(MatSetSizes(*outmat, m, n, PETSC_DETERMINE, PETSC_DETERMINE));
4595:     PetscCall(MatGetBlockSizes(inmat, &bs, &cbs));
4596:     PetscCall(MatSetBlockSizes(*outmat, bs, cbs));
4597:     PetscCall(MatGetRootType_Private(inmat, &rootType));
4598:     PetscCall(MatSetType(*outmat, rootType));
4599:     PetscCall(MatSeqAIJSetPreallocation(*outmat, 0, dnz));
4600:     PetscCall(MatMPIAIJSetPreallocation(*outmat, 0, dnz, 0, onz));
4601:     MatPreallocateEnd(dnz, onz);
4602:     PetscCall(MatSetOption(*outmat, MAT_NO_OFF_PROC_ENTRIES, PETSC_TRUE));
4603:   }

4605:   /* numeric phase */
4606:   PetscCall(MatGetOwnershipRange(*outmat, &rstart, NULL));
4607:   for (i = 0; i < m; i++) {
4608:     PetscCall(MatGetRow_SeqAIJ(inmat, i, &nnz, &indx, &values));
4609:     Ii = i + rstart;
4610:     PetscCall(MatSetValues(*outmat, 1, &Ii, nnz, indx, values, INSERT_VALUES));
4611:     PetscCall(MatRestoreRow_SeqAIJ(inmat, i, &nnz, &indx, &values));
4612:   }
4613:   PetscCall(MatAssemblyBegin(*outmat, MAT_FINAL_ASSEMBLY));
4614:   PetscCall(MatAssemblyEnd(*outmat, MAT_FINAL_ASSEMBLY));
4615:   PetscFunctionReturn(PETSC_SUCCESS);
4616: }

4618: static PetscErrorCode MatMergeSeqsToMPIDestroy(PetscCtxRt data)
4619: {
4620:   MatMergeSeqsToMPI *merge = *(MatMergeSeqsToMPI **)data;

4622:   PetscFunctionBegin;
4623:   if (!merge) PetscFunctionReturn(PETSC_SUCCESS);
4624:   PetscCall(PetscFree(merge->id_r));
4625:   PetscCall(PetscFree(merge->len_s));
4626:   PetscCall(PetscFree(merge->len_r));
4627:   PetscCall(PetscFree(merge->bi));
4628:   PetscCall(PetscFree(merge->bj));
4629:   PetscCall(PetscFree(merge->buf_ri[0]));
4630:   PetscCall(PetscFree(merge->buf_ri));
4631:   PetscCall(PetscFree(merge->buf_rj[0]));
4632:   PetscCall(PetscFree(merge->buf_rj));
4633:   PetscCall(PetscFree(merge->coi));
4634:   PetscCall(PetscFree(merge->coj));
4635:   PetscCall(PetscFree(merge->owners_co));
4636:   PetscCall(PetscLayoutDestroy(&merge->rowmap));
4637:   PetscCall(PetscFree(merge));
4638:   PetscFunctionReturn(PETSC_SUCCESS);
4639: }

4641: #include <../src/mat/utils/freespace.h>
4642: #include <petscbt.h>

4644: PetscErrorCode MatCreateMPIAIJSumSeqAIJNumeric(Mat seqmat, Mat mpimat)
4645: {
4646:   MPI_Comm           comm;
4647:   Mat_SeqAIJ        *a = (Mat_SeqAIJ *)seqmat->data;
4648:   PetscMPIInt        size, rank, taga, *len_s;
4649:   PetscInt           N = mpimat->cmap->N, i, j, *owners, *ai = a->i, *aj, m;
4650:   PetscMPIInt        proc, k;
4651:   PetscInt         **buf_ri, **buf_rj;
4652:   PetscInt           anzi, *bj_i, *bi, *bj, arow, bnzi, nextaj;
4653:   PetscInt           nrows, **buf_ri_k, **nextrow, **nextai;
4654:   MPI_Request       *s_waits, *r_waits;
4655:   MPI_Status        *status;
4656:   const MatScalar   *aa, *a_a;
4657:   MatScalar        **abuf_r, *ba_i;
4658:   MatMergeSeqsToMPI *merge;
4659:   PetscContainer     container;

4661:   PetscFunctionBegin;
4662:   PetscCall(PetscObjectGetComm((PetscObject)mpimat, &comm));
4663:   PetscCall(PetscLogEventBegin(MAT_Seqstompinum, seqmat, 0, 0, 0));

4665:   PetscCallMPI(MPI_Comm_size(comm, &size));
4666:   PetscCallMPI(MPI_Comm_rank(comm, &rank));

4668:   PetscCall(PetscObjectQuery((PetscObject)mpimat, "MatMergeSeqsToMPI", (PetscObject *)&container));
4669:   PetscCheck(container, PetscObjectComm((PetscObject)mpimat), PETSC_ERR_PLIB, "Mat not created from MatCreateMPIAIJSumSeqAIJSymbolic");
4670:   PetscCall(PetscContainerGetPointer(container, &merge));
4671:   PetscCall(MatSeqAIJGetArrayRead(seqmat, &a_a));
4672:   aa = a_a;

4674:   bi     = merge->bi;
4675:   bj     = merge->bj;
4676:   buf_ri = merge->buf_ri;
4677:   buf_rj = merge->buf_rj;

4679:   PetscCall(PetscMalloc1(size, &status));
4680:   owners = merge->rowmap->range;
4681:   len_s  = merge->len_s;

4683:   /* send and recv matrix values */
4684:   PetscCall(PetscObjectGetNewTag((PetscObject)mpimat, &taga));
4685:   PetscCall(PetscPostIrecvScalar(comm, taga, merge->nrecv, merge->id_r, merge->len_r, &abuf_r, &r_waits));

4687:   PetscCall(PetscMalloc1(merge->nsend + 1, &s_waits));
4688:   for (proc = 0, k = 0; proc < size; proc++) {
4689:     if (!len_s[proc]) continue;
4690:     i = owners[proc];
4691:     PetscCallMPI(MPIU_Isend(aa + ai[i], len_s[proc], MPIU_MATSCALAR, proc, taga, comm, s_waits + k));
4692:     k++;
4693:   }

4695:   if (merge->nrecv) PetscCallMPI(MPI_Waitall(merge->nrecv, r_waits, status));
4696:   if (merge->nsend) PetscCallMPI(MPI_Waitall(merge->nsend, s_waits, status));
4697:   PetscCall(PetscFree(status));

4699:   PetscCall(PetscFree(s_waits));
4700:   PetscCall(PetscFree(r_waits));

4702:   /* insert mat values of mpimat */
4703:   PetscCall(PetscMalloc1(N, &ba_i));
4704:   PetscCall(PetscMalloc3(merge->nrecv, &buf_ri_k, merge->nrecv, &nextrow, merge->nrecv, &nextai));

4706:   for (k = 0; k < merge->nrecv; k++) {
4707:     buf_ri_k[k] = buf_ri[k]; /* beginning of k-th recved i-structure */
4708:     nrows       = *buf_ri_k[k];
4709:     nextrow[k]  = buf_ri_k[k] + 1;           /* next row number of k-th recved i-structure */
4710:     nextai[k]   = buf_ri_k[k] + (nrows + 1); /* points to the next i-structure of k-th recved i-structure  */
4711:   }

4713:   /* set values of ba */
4714:   m = merge->rowmap->n;
4715:   for (i = 0; i < m; i++) {
4716:     arow = owners[rank] + i;
4717:     bj_i = bj + bi[i]; /* col indices of the i-th row of mpimat */
4718:     bnzi = bi[i + 1] - bi[i];
4719:     PetscCall(PetscArrayzero(ba_i, bnzi));

4721:     /* add local non-zero vals of this proc's seqmat into ba */
4722:     anzi   = ai[arow + 1] - ai[arow];
4723:     aj     = a->j + ai[arow];
4724:     aa     = a_a + ai[arow];
4725:     nextaj = 0;
4726:     for (j = 0; nextaj < anzi; j++) {
4727:       if (*(bj_i + j) == aj[nextaj]) { /* bcol == acol */
4728:         ba_i[j] += aa[nextaj++];
4729:       }
4730:     }

4732:     /* add received vals into ba */
4733:     for (k = 0; k < merge->nrecv; k++) { /* k-th received message */
4734:       /* i-th row */
4735:       if (i == *nextrow[k]) {
4736:         anzi   = *(nextai[k] + 1) - *nextai[k];
4737:         aj     = buf_rj[k] + *nextai[k];
4738:         aa     = abuf_r[k] + *nextai[k];
4739:         nextaj = 0;
4740:         for (j = 0; nextaj < anzi; j++) {
4741:           if (*(bj_i + j) == aj[nextaj]) { /* bcol == acol */
4742:             ba_i[j] += aa[nextaj++];
4743:           }
4744:         }
4745:         nextrow[k]++;
4746:         nextai[k]++;
4747:       }
4748:     }
4749:     PetscCall(MatSetValues(mpimat, 1, &arow, bnzi, bj_i, ba_i, INSERT_VALUES));
4750:   }
4751:   PetscCall(MatSeqAIJRestoreArrayRead(seqmat, &a_a));
4752:   PetscCall(MatAssemblyBegin(mpimat, MAT_FINAL_ASSEMBLY));
4753:   PetscCall(MatAssemblyEnd(mpimat, MAT_FINAL_ASSEMBLY));

4755:   PetscCall(PetscFree(abuf_r[0]));
4756:   PetscCall(PetscFree(abuf_r));
4757:   PetscCall(PetscFree(ba_i));
4758:   PetscCall(PetscFree3(buf_ri_k, nextrow, nextai));
4759:   PetscCall(PetscLogEventEnd(MAT_Seqstompinum, seqmat, 0, 0, 0));
4760:   PetscFunctionReturn(PETSC_SUCCESS);
4761: }

4763: PetscErrorCode MatCreateMPIAIJSumSeqAIJSymbolic(MPI_Comm comm, Mat seqmat, PetscInt m, PetscInt n, Mat *mpimat)
4764: {
4765:   Mat                B_mpi;
4766:   Mat_SeqAIJ        *a = (Mat_SeqAIJ *)seqmat->data;
4767:   PetscMPIInt        size, rank, tagi, tagj, *len_s, *len_si, *len_ri;
4768:   PetscInt         **buf_rj, **buf_ri, **buf_ri_k;
4769:   PetscInt           M = seqmat->rmap->n, N = seqmat->cmap->n, i, *owners, *ai = a->i, *aj = a->j;
4770:   PetscInt           len, *dnz, *onz, bs, cbs;
4771:   PetscInt           k, anzi, *bi, *bj, *lnk, nlnk, arow, bnzi;
4772:   PetscInt           nrows, *buf_s, *buf_si, *buf_si_i, **nextrow, **nextai;
4773:   MPI_Request       *si_waits, *sj_waits, *ri_waits, *rj_waits;
4774:   MPI_Status        *status;
4775:   PetscFreeSpaceList free_space = NULL, current_space = NULL;
4776:   PetscBT            lnkbt;
4777:   MatMergeSeqsToMPI *merge;
4778:   PetscContainer     container;

4780:   PetscFunctionBegin;
4781:   PetscCall(PetscLogEventBegin(MAT_Seqstompisym, seqmat, 0, 0, 0));

4783:   /* make sure it is a PETSc comm */
4784:   PetscCall(PetscCommDuplicate(comm, &comm, NULL));
4785:   PetscCallMPI(MPI_Comm_size(comm, &size));
4786:   PetscCallMPI(MPI_Comm_rank(comm, &rank));

4788:   PetscCall(PetscNew(&merge));
4789:   PetscCall(PetscMalloc1(size, &status));

4791:   /* determine row ownership */
4792:   PetscCall(PetscLayoutCreate(comm, &merge->rowmap));
4793:   PetscCall(PetscLayoutSetLocalSize(merge->rowmap, m));
4794:   PetscCall(PetscLayoutSetSize(merge->rowmap, M));
4795:   PetscCall(PetscLayoutSetBlockSize(merge->rowmap, 1));
4796:   PetscCall(PetscLayoutSetUp(merge->rowmap));
4797:   PetscCall(PetscMalloc1(size, &len_si));
4798:   PetscCall(PetscMalloc1(size, &merge->len_s));

4800:   m      = merge->rowmap->n;
4801:   owners = merge->rowmap->range;

4803:   /* determine the number of messages to send, their lengths */
4804:   len_s = merge->len_s;

4806:   len          = 0; /* length of buf_si[] */
4807:   merge->nsend = 0;
4808:   for (PetscMPIInt proc = 0; proc < size; proc++) {
4809:     len_si[proc] = 0;
4810:     if (proc == rank) {
4811:       len_s[proc] = 0;
4812:     } else {
4813:       PetscCall(PetscMPIIntCast(owners[proc + 1] - owners[proc] + 1, &len_si[proc]));
4814:       PetscCall(PetscMPIIntCast(ai[owners[proc + 1]] - ai[owners[proc]], &len_s[proc])); /* num of rows to be sent to [proc] */
4815:     }
4816:     if (len_s[proc]) {
4817:       merge->nsend++;
4818:       nrows = 0;
4819:       for (i = owners[proc]; i < owners[proc + 1]; i++) {
4820:         if (ai[i + 1] > ai[i]) nrows++;
4821:       }
4822:       PetscCall(PetscMPIIntCast(2 * (nrows + 1), &len_si[proc]));
4823:       len += len_si[proc];
4824:     }
4825:   }

4827:   /* determine the number and length of messages to receive for ij-structure */
4828:   PetscCall(PetscGatherNumberOfMessages(comm, NULL, len_s, &merge->nrecv));
4829:   PetscCall(PetscGatherMessageLengths2(comm, merge->nsend, merge->nrecv, len_s, len_si, &merge->id_r, &merge->len_r, &len_ri));

4831:   /* post the Irecv of j-structure */
4832:   PetscCall(PetscCommGetNewTag(comm, &tagj));
4833:   PetscCall(PetscPostIrecvInt(comm, tagj, merge->nrecv, merge->id_r, merge->len_r, &buf_rj, &rj_waits));

4835:   /* post the Isend of j-structure */
4836:   PetscCall(PetscMalloc2(merge->nsend, &si_waits, merge->nsend, &sj_waits));

4838:   for (PetscMPIInt proc = 0, k = 0; proc < size; proc++) {
4839:     if (!len_s[proc]) continue;
4840:     i = owners[proc];
4841:     PetscCallMPI(MPIU_Isend(aj + ai[i], len_s[proc], MPIU_INT, proc, tagj, comm, sj_waits + k));
4842:     k++;
4843:   }

4845:   /* receives and sends of j-structure are complete */
4846:   if (merge->nrecv) PetscCallMPI(MPI_Waitall(merge->nrecv, rj_waits, status));
4847:   if (merge->nsend) PetscCallMPI(MPI_Waitall(merge->nsend, sj_waits, status));

4849:   /* send and recv i-structure */
4850:   PetscCall(PetscCommGetNewTag(comm, &tagi));
4851:   PetscCall(PetscPostIrecvInt(comm, tagi, merge->nrecv, merge->id_r, len_ri, &buf_ri, &ri_waits));

4853:   PetscCall(PetscMalloc1(len + 1, &buf_s));
4854:   buf_si = buf_s; /* points to the beginning of k-th msg to be sent */
4855:   for (PetscMPIInt proc = 0, k = 0; proc < size; proc++) {
4856:     if (!len_s[proc]) continue;
4857:     /* form outgoing message for i-structure:
4858:          buf_si[0]:                 nrows to be sent
4859:                [1:nrows]:           row index (global)
4860:                [nrows+1:2*nrows+1]: i-structure index
4861:     */
4862:     nrows       = len_si[proc] / 2 - 1;
4863:     buf_si_i    = buf_si + nrows + 1;
4864:     buf_si[0]   = nrows;
4865:     buf_si_i[0] = 0;
4866:     nrows       = 0;
4867:     for (i = owners[proc]; i < owners[proc + 1]; i++) {
4868:       anzi = ai[i + 1] - ai[i];
4869:       if (anzi) {
4870:         buf_si_i[nrows + 1] = buf_si_i[nrows] + anzi; /* i-structure */
4871:         buf_si[nrows + 1]   = i - owners[proc];       /* local row index */
4872:         nrows++;
4873:       }
4874:     }
4875:     PetscCallMPI(MPIU_Isend(buf_si, len_si[proc], MPIU_INT, proc, tagi, comm, si_waits + k));
4876:     k++;
4877:     buf_si += len_si[proc];
4878:   }

4880:   if (merge->nrecv) PetscCallMPI(MPI_Waitall(merge->nrecv, ri_waits, status));
4881:   if (merge->nsend) PetscCallMPI(MPI_Waitall(merge->nsend, si_waits, status));

4883:   PetscCall(PetscInfo(seqmat, "nsend: %d, nrecv: %d\n", merge->nsend, merge->nrecv));
4884:   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]));

4886:   PetscCall(PetscFree(len_si));
4887:   PetscCall(PetscFree(len_ri));
4888:   PetscCall(PetscFree(rj_waits));
4889:   PetscCall(PetscFree2(si_waits, sj_waits));
4890:   PetscCall(PetscFree(ri_waits));
4891:   PetscCall(PetscFree(buf_s));
4892:   PetscCall(PetscFree(status));

4894:   /* compute a local seq matrix in each processor */
4895:   /* allocate bi array and free space for accumulating nonzero column info */
4896:   PetscCall(PetscMalloc1(m + 1, &bi));
4897:   bi[0] = 0;

4899:   /* create and initialize a linked list */
4900:   nlnk = N + 1;
4901:   PetscCall(PetscLLCreate(N, N, nlnk, lnk, lnkbt));

4903:   /* initial FreeSpace size is 2*(num of local nnz(seqmat)) */
4904:   len = ai[owners[rank + 1]] - ai[owners[rank]];
4905:   PetscCall(PetscFreeSpaceGet(PetscIntMultTruncate(2, len) + 1, &free_space));

4907:   current_space = free_space;

4909:   /* determine symbolic info for each local row */
4910:   PetscCall(PetscMalloc3(merge->nrecv, &buf_ri_k, merge->nrecv, &nextrow, merge->nrecv, &nextai));

4912:   for (k = 0; k < merge->nrecv; k++) {
4913:     buf_ri_k[k] = buf_ri[k]; /* beginning of k-th recved i-structure */
4914:     nrows       = *buf_ri_k[k];
4915:     nextrow[k]  = buf_ri_k[k] + 1;           /* next row number of k-th recved i-structure */
4916:     nextai[k]   = buf_ri_k[k] + (nrows + 1); /* points to the next i-structure of k-th recved i-structure  */
4917:   }

4919:   MatPreallocateBegin(comm, m, n, dnz, onz);
4920:   len = 0;
4921:   for (i = 0; i < m; i++) {
4922:     bnzi = 0;
4923:     /* add local non-zero cols of this proc's seqmat into lnk */
4924:     arow = owners[rank] + i;
4925:     anzi = ai[arow + 1] - ai[arow];
4926:     aj   = a->j + ai[arow];
4927:     PetscCall(PetscLLAddSorted(anzi, aj, N, &nlnk, lnk, lnkbt));
4928:     bnzi += nlnk;
4929:     /* add received col data into lnk */
4930:     for (k = 0; k < merge->nrecv; k++) { /* k-th received message */
4931:       if (i == *nextrow[k]) {            /* i-th row */
4932:         anzi = *(nextai[k] + 1) - *nextai[k];
4933:         aj   = buf_rj[k] + *nextai[k];
4934:         PetscCall(PetscLLAddSorted(anzi, aj, N, &nlnk, lnk, lnkbt));
4935:         bnzi += nlnk;
4936:         nextrow[k]++;
4937:         nextai[k]++;
4938:       }
4939:     }
4940:     if (len < bnzi) len = bnzi; /* =max(bnzi) */

4942:     /* if free space is not available, make more free space */
4943:     if (current_space->local_remaining < bnzi) PetscCall(PetscFreeSpaceGet(PetscIntSumTruncate(bnzi, current_space->total_array_size), &current_space));
4944:     /* copy data into free space, then initialize lnk */
4945:     PetscCall(PetscLLClean(N, N, bnzi, lnk, current_space->array, lnkbt));
4946:     PetscCall(MatPreallocateSet(i + owners[rank], bnzi, current_space->array, dnz, onz));

4948:     current_space->array += bnzi;
4949:     current_space->local_used += bnzi;
4950:     current_space->local_remaining -= bnzi;

4952:     bi[i + 1] = bi[i] + bnzi;
4953:   }

4955:   PetscCall(PetscFree3(buf_ri_k, nextrow, nextai));

4957:   PetscCall(PetscMalloc1(bi[m], &bj));
4958:   PetscCall(PetscFreeSpaceContiguous(&free_space, bj));
4959:   PetscCall(PetscLLDestroy(lnk, lnkbt));

4961:   /* create symbolic parallel matrix B_mpi */
4962:   PetscCall(MatGetBlockSizes(seqmat, &bs, &cbs));
4963:   PetscCall(MatCreate(comm, &B_mpi));
4964:   if (n == PETSC_DECIDE) PetscCall(MatSetSizes(B_mpi, m, n, PETSC_DETERMINE, N));
4965:   else PetscCall(MatSetSizes(B_mpi, m, n, PETSC_DETERMINE, PETSC_DETERMINE));
4966:   PetscCall(MatSetBlockSizes(B_mpi, bs, cbs));
4967:   PetscCall(MatSetType(B_mpi, MATMPIAIJ));
4968:   PetscCall(MatMPIAIJSetPreallocation(B_mpi, 0, dnz, 0, onz));
4969:   MatPreallocateEnd(dnz, onz);
4970:   PetscCall(MatSetOption(B_mpi, MAT_NEW_NONZERO_ALLOCATION_ERR, PETSC_FALSE));

4972:   /* B_mpi is not ready for use - assembly will be done by MatCreateMPIAIJSumSeqAIJNumeric() */
4973:   B_mpi->assembled = PETSC_FALSE;
4974:   merge->bi        = bi;
4975:   merge->bj        = bj;
4976:   merge->buf_ri    = buf_ri;
4977:   merge->buf_rj    = buf_rj;
4978:   merge->coi       = NULL;
4979:   merge->coj       = NULL;
4980:   merge->owners_co = NULL;

4982:   PetscCall(PetscCommDestroy(&comm));

4984:   /* attach the supporting struct to B_mpi for reuse */
4985:   PetscCall(PetscContainerCreate(PETSC_COMM_SELF, &container));
4986:   PetscCall(PetscContainerSetPointer(container, merge));
4987:   PetscCall(PetscContainerSetCtxDestroy(container, MatMergeSeqsToMPIDestroy));
4988:   PetscCall(PetscObjectCompose((PetscObject)B_mpi, "MatMergeSeqsToMPI", (PetscObject)container));
4989:   PetscCall(PetscContainerDestroy(&container));
4990:   *mpimat = B_mpi;

4992:   PetscCall(PetscLogEventEnd(MAT_Seqstompisym, seqmat, 0, 0, 0));
4993:   PetscFunctionReturn(PETSC_SUCCESS);
4994: }

4996: /*@
4997:   MatCreateMPIAIJSumSeqAIJ - Creates a `MATMPIAIJ` matrix by adding sequential
4998:   matrices from each processor

5000:   Collective

5002:   Input Parameters:
5003: + comm   - the communicators the parallel matrix will live on
5004: . seqmat - the input sequential matrices
5005: . m      - number of local rows (or `PETSC_DECIDE`)
5006: . n      - number of local columns (or `PETSC_DECIDE`)
5007: - scall  - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`

5009:   Output Parameter:
5010: . mpimat - the parallel matrix generated

5012:   Level: advanced

5014:   Note:
5015:   The dimensions of the sequential matrix in each processor MUST be the same.
5016:   The input seqmat is included into the container `MatMergeSeqsToMPIDestroy`, and will be
5017:   destroyed when `mpimat` is destroyed. Call `PetscObjectQuery()` to access `seqmat`.

5019: .seealso: [](ch_matrices), `Mat`, `MatCreateAIJ()`
5020: @*/
5021: PetscErrorCode MatCreateMPIAIJSumSeqAIJ(MPI_Comm comm, Mat seqmat, PetscInt m, PetscInt n, MatReuse scall, Mat *mpimat)
5022: {
5023:   PetscMPIInt size;

5025:   PetscFunctionBegin;
5026:   PetscCallMPI(MPI_Comm_size(comm, &size));
5027:   if (size == 1) {
5028:     PetscCall(PetscLogEventBegin(MAT_Seqstompi, seqmat, 0, 0, 0));
5029:     if (scall == MAT_INITIAL_MATRIX) PetscCall(MatDuplicate(seqmat, MAT_COPY_VALUES, mpimat));
5030:     else PetscCall(MatCopy(seqmat, *mpimat, SAME_NONZERO_PATTERN));
5031:     PetscCall(PetscLogEventEnd(MAT_Seqstompi, seqmat, 0, 0, 0));
5032:     PetscFunctionReturn(PETSC_SUCCESS);
5033:   }
5034:   PetscCall(PetscLogEventBegin(MAT_Seqstompi, seqmat, 0, 0, 0));
5035:   if (scall == MAT_INITIAL_MATRIX) PetscCall(MatCreateMPIAIJSumSeqAIJSymbolic(comm, seqmat, m, n, mpimat));
5036:   PetscCall(MatCreateMPIAIJSumSeqAIJNumeric(seqmat, *mpimat));
5037:   PetscCall(PetscLogEventEnd(MAT_Seqstompi, seqmat, 0, 0, 0));
5038:   PetscFunctionReturn(PETSC_SUCCESS);
5039: }

5041: /*@
5042:   MatAIJGetLocalMat - Creates a `MATSEQAIJ` from a `MATAIJ` matrix.

5044:   Not Collective

5046:   Input Parameter:
5047: . A - the matrix

5049:   Output Parameter:
5050: . A_loc - the local sequential matrix generated

5052:   Level: developer

5054:   Notes:
5055:   The matrix is created by taking `A`'s local rows and putting them into a sequential matrix
5056:   with `mlocal` rows and `n` columns. Where `mlocal` is obtained with `MatGetLocalSize()` and
5057:   `n` is the global column count obtained with `MatGetSize()`

5059:   In other words combines the two parts of a parallel `MATMPIAIJ` matrix on each process to a single matrix.

5061:   For parallel matrices this creates an entirely new matrix. If the matrix is sequential it merely increases the reference count.

5063:   Destroy the matrix with `MatDestroy()`

5065: .seealso: [](ch_matrices), `Mat`, `MatMPIAIJGetLocalMat()`
5066: @*/
5067: PetscErrorCode MatAIJGetLocalMat(Mat A, Mat *A_loc)
5068: {
5069:   PetscBool mpi;

5071:   PetscFunctionBegin;
5072:   PetscCall(PetscObjectTypeCompare((PetscObject)A, MATMPIAIJ, &mpi));
5073:   if (mpi) PetscCall(MatMPIAIJGetLocalMat(A, MAT_INITIAL_MATRIX, A_loc));
5074:   else {
5075:     *A_loc = A;
5076:     PetscCall(PetscObjectReference((PetscObject)*A_loc));
5077:   }
5078:   PetscFunctionReturn(PETSC_SUCCESS);
5079: }

5081: /*@
5082:   MatMPIAIJGetLocalMat - Creates a `MATSEQAIJ` from a `MATMPIAIJ` matrix.

5084:   Not Collective

5086:   Input Parameters:
5087: + A     - the matrix
5088: - scall - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`

5090:   Output Parameter:
5091: . A_loc - the local sequential matrix generated

5093:   Level: developer

5095:   Notes:
5096:   The matrix is created by taking all `A`'s local rows and putting them into a sequential
5097:   matrix with `mlocal` rows and `n` columns.`mlocal` is the row count obtained with
5098:   `MatGetLocalSize()` and `n` is the global column count obtained with `MatGetSize()`.

5100:   In other words combines the two parts of a parallel `MATMPIAIJ` matrix on each process to a single matrix.

5102:   When `A` is sequential and `MAT_INITIAL_MATRIX` is requested, the matrix returned is the diagonal part of `A` (which contains the entire matrix),
5103:   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
5104:   then `MatCopy`(Adiag,*`A_loc`,`SAME_NONZERO_PATTERN`) is called to fill `A_loc`. Thus one can preallocate the appropriate sequential matrix `A_loc`
5105:   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.

5107: .seealso: [](ch_matrices), `Mat`, `MATMPIAIJ`, `MatGetOwnershipRange()`, `MatMPIAIJGetLocalMatCondensed()`, `MatMPIAIJGetLocalMatMerge()`
5108: @*/
5109: PetscErrorCode MatMPIAIJGetLocalMat(Mat A, MatReuse scall, Mat *A_loc)
5110: {
5111:   Mat_MPIAIJ        *mpimat = (Mat_MPIAIJ *)A->data;
5112:   Mat_SeqAIJ        *mat, *a, *b;
5113:   PetscInt          *ai, *aj, *bi, *bj, *cmap = mpimat->garray;
5114:   const PetscScalar *aa, *ba, *aav, *bav;
5115:   PetscScalar       *ca, *cam;
5116:   PetscMPIInt        size;
5117:   PetscInt           am = A->rmap->n, i, j, k, cstart = A->cmap->rstart;
5118:   PetscInt          *ci, *cj, col, ncols_d, ncols_o, jo;
5119:   PetscBool          match;

5121:   PetscFunctionBegin;
5122:   PetscCall(PetscStrbeginswith(((PetscObject)A)->type_name, MATMPIAIJ, &match));
5123:   PetscCheck(match, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "Requires MATMPIAIJ matrix as input");
5124:   PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)A), &size));
5125:   if (size == 1) {
5126:     if (scall == MAT_INITIAL_MATRIX) {
5127:       PetscCall(PetscObjectReference((PetscObject)mpimat->A));
5128:       *A_loc = mpimat->A;
5129:     } else if (scall == MAT_REUSE_MATRIX) {
5130:       PetscCall(MatCopy(mpimat->A, *A_loc, SAME_NONZERO_PATTERN));
5131:     }
5132:     PetscFunctionReturn(PETSC_SUCCESS);
5133:   }

5135:   PetscCall(PetscLogEventBegin(MAT_Getlocalmat, A, 0, 0, 0));
5136:   a  = (Mat_SeqAIJ *)mpimat->A->data;
5137:   b  = (Mat_SeqAIJ *)mpimat->B->data;
5138:   ai = a->i;
5139:   aj = a->j;
5140:   bi = b->i;
5141:   bj = b->j;
5142:   PetscCall(MatSeqAIJGetArrayRead(mpimat->A, &aav));
5143:   PetscCall(MatSeqAIJGetArrayRead(mpimat->B, &bav));
5144:   aa = aav;
5145:   ba = bav;
5146:   if (scall == MAT_INITIAL_MATRIX) {
5147:     PetscCall(PetscMalloc1(1 + am, &ci));
5148:     ci[0] = 0;
5149:     for (i = 0; i < am; i++) ci[i + 1] = ci[i] + (ai[i + 1] - ai[i]) + (bi[i + 1] - bi[i]);
5150:     PetscCall(PetscMalloc1(1 + ci[am], &cj));
5151:     PetscCall(PetscMalloc1(1 + ci[am], &ca));
5152:     k = 0;
5153:     for (i = 0; i < am; i++) {
5154:       ncols_o = bi[i + 1] - bi[i];
5155:       ncols_d = ai[i + 1] - ai[i];
5156:       /* off-diagonal portion of A */
5157:       for (jo = 0; jo < ncols_o; jo++) {
5158:         col = cmap[*bj];
5159:         if (col >= cstart) break;
5160:         cj[k] = col;
5161:         bj++;
5162:         ca[k++] = *ba++;
5163:       }
5164:       /* diagonal portion of A */
5165:       for (j = 0; j < ncols_d; j++) {
5166:         cj[k]   = cstart + *aj++;
5167:         ca[k++] = *aa++;
5168:       }
5169:       /* off-diagonal portion of A */
5170:       for (j = jo; j < ncols_o; j++) {
5171:         cj[k]   = cmap[*bj++];
5172:         ca[k++] = *ba++;
5173:       }
5174:     }
5175:     /* put together the new matrix */
5176:     PetscCall(MatCreateSeqAIJWithArrays(PETSC_COMM_SELF, am, A->cmap->N, ci, cj, ca, A_loc));
5177:     /* MatCreateSeqAIJWithArrays flags matrix so PETSc doesn't free the user's arrays. */
5178:     /* Since these are PETSc arrays, change flags to free them as necessary. */
5179:     mat          = (Mat_SeqAIJ *)(*A_loc)->data;
5180:     mat->free_a  = PETSC_TRUE;
5181:     mat->free_ij = PETSC_TRUE;
5182:     mat->nonew   = 0;
5183:   } else if (scall == MAT_REUSE_MATRIX) {
5184:     mat = (Mat_SeqAIJ *)(*A_loc)->data;
5185:     ci  = mat->i;
5186:     cj  = mat->j;
5187:     PetscCall(MatSeqAIJGetArrayWrite(*A_loc, &cam));
5188:     for (i = 0; i < am; i++) {
5189:       /* off-diagonal portion of A */
5190:       ncols_o = bi[i + 1] - bi[i];
5191:       for (jo = 0; jo < ncols_o; jo++) {
5192:         col = cmap[*bj];
5193:         if (col >= cstart) break;
5194:         *cam++ = *ba++;
5195:         bj++;
5196:       }
5197:       /* diagonal portion of A */
5198:       ncols_d = ai[i + 1] - ai[i];
5199:       for (j = 0; j < ncols_d; j++) *cam++ = *aa++;
5200:       /* off-diagonal portion of A */
5201:       for (j = jo; j < ncols_o; j++) {
5202:         *cam++ = *ba++;
5203:         bj++;
5204:       }
5205:     }
5206:     PetscCall(MatSeqAIJRestoreArrayWrite(*A_loc, &cam));
5207:   } else SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Invalid MatReuse %d", (int)scall);
5208:   PetscCall(MatSeqAIJRestoreArrayRead(mpimat->A, &aav));
5209:   PetscCall(MatSeqAIJRestoreArrayRead(mpimat->B, &bav));
5210:   PetscCall(PetscLogEventEnd(MAT_Getlocalmat, A, 0, 0, 0));
5211:   PetscFunctionReturn(PETSC_SUCCESS);
5212: }

5214: /*@
5215:   MatMPIAIJGetLocalMatMerge - Creates a `MATSEQAIJ` from a `MATMPIAIJ` matrix by taking all its local rows and putting them into a sequential matrix with
5216:   mlocal rows and n columns. Where n is the sum of the number of columns of the diagonal and off-diagonal part

5218:   Not Collective

5220:   Input Parameters:
5221: + A     - the matrix
5222: - scall - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`

5224:   Output Parameters:
5225: + glob  - sequential `IS` with global indices associated with the columns of the local sequential matrix generated (can be `NULL`)
5226: - A_loc - the local sequential matrix generated

5228:   Level: developer

5230:   Note:
5231:   This is different from `MatMPIAIJGetLocalMat()` since the first columns in the returning matrix are those associated with the diagonal
5232:   part, then those associated with the off-diagonal part (in its local ordering)

5234: .seealso: [](ch_matrices), `Mat`, `MATMPIAIJ`, `MatGetOwnershipRange()`, `MatMPIAIJGetLocalMat()`, `MatMPIAIJGetLocalMatCondensed()`
5235: @*/
5236: PetscErrorCode MatMPIAIJGetLocalMatMerge(Mat A, MatReuse scall, IS *glob, Mat *A_loc)
5237: {
5238:   Mat             Ao, Ad;
5239:   const PetscInt *cmap;
5240:   PetscMPIInt     size;
5241:   PetscErrorCode (*f)(Mat, MatReuse, IS *, Mat *);

5243:   PetscFunctionBegin;
5244:   PetscCall(MatMPIAIJGetSeqAIJ(A, &Ad, &Ao, &cmap));
5245:   PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)A), &size));
5246:   if (size == 1) {
5247:     if (scall == MAT_INITIAL_MATRIX) {
5248:       PetscCall(PetscObjectReference((PetscObject)Ad));
5249:       *A_loc = Ad;
5250:     } else if (scall == MAT_REUSE_MATRIX) {
5251:       PetscCall(MatCopy(Ad, *A_loc, SAME_NONZERO_PATTERN));
5252:     }
5253:     if (glob) PetscCall(ISCreateStride(PetscObjectComm((PetscObject)Ad), Ad->cmap->n, Ad->cmap->rstart, 1, glob));
5254:     PetscFunctionReturn(PETSC_SUCCESS);
5255:   }
5256:   PetscCall(PetscObjectQueryFunction((PetscObject)A, "MatMPIAIJGetLocalMatMerge_C", &f));
5257:   PetscCall(PetscLogEventBegin(MAT_Getlocalmat, A, 0, 0, 0));
5258:   if (f) PetscCall((*f)(A, scall, glob, A_loc));
5259:   else {
5260:     Mat_SeqAIJ        *a = (Mat_SeqAIJ *)Ad->data;
5261:     Mat_SeqAIJ        *b = (Mat_SeqAIJ *)Ao->data;
5262:     Mat_SeqAIJ        *c;
5263:     PetscInt          *ai = a->i, *aj = a->j;
5264:     PetscInt          *bi = b->i, *bj = b->j;
5265:     PetscInt          *ci, *cj;
5266:     const PetscScalar *aa, *ba;
5267:     PetscScalar       *ca;
5268:     PetscInt           i, j, am, dn, on;

5270:     PetscCall(MatGetLocalSize(Ad, &am, &dn));
5271:     PetscCall(MatGetLocalSize(Ao, NULL, &on));
5272:     PetscCall(MatSeqAIJGetArrayRead(Ad, &aa));
5273:     PetscCall(MatSeqAIJGetArrayRead(Ao, &ba));
5274:     if (scall == MAT_INITIAL_MATRIX) {
5275:       PetscInt k;
5276:       PetscCall(PetscMalloc1(1 + am, &ci));
5277:       PetscCall(PetscMalloc1(ai[am] + bi[am], &cj));
5278:       PetscCall(PetscMalloc1(ai[am] + bi[am], &ca));
5279:       ci[0] = 0;
5280:       for (i = 0, k = 0; i < am; i++) {
5281:         const PetscInt ncols_o = bi[i + 1] - bi[i];
5282:         const PetscInt ncols_d = ai[i + 1] - ai[i];
5283:         ci[i + 1]              = ci[i] + ncols_o + ncols_d;
5284:         /* diagonal portion of A */
5285:         for (j = 0; j < ncols_d; j++, k++) {
5286:           cj[k] = *aj++;
5287:           ca[k] = *aa++;
5288:         }
5289:         /* off-diagonal portion of A */
5290:         for (j = 0; j < ncols_o; j++, k++) {
5291:           cj[k] = dn + *bj++;
5292:           ca[k] = *ba++;
5293:         }
5294:       }
5295:       /* put together the new matrix */
5296:       PetscCall(MatCreateSeqAIJWithArrays(PETSC_COMM_SELF, am, dn + on, ci, cj, ca, A_loc));
5297:       /* MatCreateSeqAIJWithArrays flags matrix so PETSc doesn't free the user's arrays. */
5298:       /* Since these are PETSc arrays, change flags to free them as necessary. */
5299:       c          = (Mat_SeqAIJ *)(*A_loc)->data;
5300:       c->free_a  = PETSC_TRUE;
5301:       c->free_ij = PETSC_TRUE;
5302:       c->nonew   = 0;
5303:       PetscCall(MatSetType(*A_loc, ((PetscObject)Ad)->type_name));
5304:     } else if (scall == MAT_REUSE_MATRIX) {
5305:       PetscCall(MatSeqAIJGetArrayWrite(*A_loc, &ca));
5306:       for (i = 0; i < am; i++) {
5307:         const PetscInt ncols_d = ai[i + 1] - ai[i];
5308:         const PetscInt ncols_o = bi[i + 1] - bi[i];
5309:         /* diagonal portion of A */
5310:         for (j = 0; j < ncols_d; j++) *ca++ = *aa++;
5311:         /* off-diagonal portion of A */
5312:         for (j = 0; j < ncols_o; j++) *ca++ = *ba++;
5313:       }
5314:       PetscCall(MatSeqAIJRestoreArrayWrite(*A_loc, &ca));
5315:     } else SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Invalid MatReuse %d", (int)scall);
5316:     PetscCall(MatSeqAIJRestoreArrayRead(Ad, &aa));
5317:     PetscCall(MatSeqAIJRestoreArrayRead(Ao, &aa));
5318:     if (glob) {
5319:       PetscInt cst, *gidx;

5321:       PetscCall(MatGetOwnershipRangeColumn(A, &cst, NULL));
5322:       PetscCall(PetscMalloc1(dn + on, &gidx));
5323:       for (i = 0; i < dn; i++) gidx[i] = cst + i;
5324:       for (i = 0; i < on; i++) gidx[i + dn] = cmap[i];
5325:       PetscCall(ISCreateGeneral(PetscObjectComm((PetscObject)Ad), dn + on, gidx, PETSC_OWN_POINTER, glob));
5326:     }
5327:   }
5328:   PetscCall(PetscLogEventEnd(MAT_Getlocalmat, A, 0, 0, 0));
5329:   PetscFunctionReturn(PETSC_SUCCESS);
5330: }

5332: /*@C
5333:   MatMPIAIJGetLocalMatCondensed - Creates a `MATSEQAIJ` matrix from an `MATMPIAIJ` matrix by taking all its local rows and NON-ZERO columns

5335:   Not Collective

5337:   Input Parameters:
5338: + A     - the matrix
5339: . scall - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`
5340: . row   - index set of rows to extract (or `NULL`)
5341: - col   - index set of columns to extract (or `NULL`)

5343:   Output Parameter:
5344: . A_loc - the local sequential matrix generated

5346:   Level: developer

5348: .seealso: [](ch_matrices), `Mat`, `MATMPIAIJ`, `MatGetOwnershipRange()`, `MatMPIAIJGetLocalMat()`
5349: @*/
5350: PetscErrorCode MatMPIAIJGetLocalMatCondensed(Mat A, MatReuse scall, IS *row, IS *col, Mat *A_loc)
5351: {
5352:   Mat_MPIAIJ *a = (Mat_MPIAIJ *)A->data;
5353:   PetscInt    i, start, end, ncols, nzA, nzB, *cmap, imark, *idx;
5354:   IS          isrowa, iscola;
5355:   Mat        *aloc;
5356:   PetscBool   match;

5358:   PetscFunctionBegin;
5359:   PetscCall(PetscObjectTypeCompare((PetscObject)A, MATMPIAIJ, &match));
5360:   PetscCheck(match, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "Requires MATMPIAIJ matrix as input");
5361:   PetscCall(PetscLogEventBegin(MAT_Getlocalmatcondensed, A, 0, 0, 0));
5362:   if (!row) {
5363:     start = A->rmap->rstart;
5364:     end   = A->rmap->rend;
5365:     PetscCall(ISCreateStride(PETSC_COMM_SELF, end - start, start, 1, &isrowa));
5366:   } else {
5367:     isrowa = *row;
5368:   }
5369:   if (!col) {
5370:     start = A->cmap->rstart;
5371:     cmap  = a->garray;
5372:     nzA   = a->A->cmap->n;
5373:     nzB   = a->B->cmap->n;
5374:     PetscCall(PetscMalloc1(nzA + nzB, &idx));
5375:     ncols = 0;
5376:     for (i = 0; i < nzB; i++) {
5377:       if (cmap[i] < start) idx[ncols++] = cmap[i];
5378:       else break;
5379:     }
5380:     imark = i;
5381:     for (i = 0; i < nzA; i++) idx[ncols++] = start + i;
5382:     for (i = imark; i < nzB; i++) idx[ncols++] = cmap[i];
5383:     PetscCall(ISCreateGeneral(PETSC_COMM_SELF, ncols, idx, PETSC_OWN_POINTER, &iscola));
5384:   } else {
5385:     iscola = *col;
5386:   }
5387:   if (scall != MAT_INITIAL_MATRIX) {
5388:     PetscCall(PetscMalloc1(1, &aloc));
5389:     aloc[0] = *A_loc;
5390:   }
5391:   PetscCall(MatCreateSubMatrices(A, 1, &isrowa, &iscola, scall, &aloc));
5392:   if (!col) { /* attach global id of condensed columns */
5393:     PetscCall(PetscObjectCompose((PetscObject)aloc[0], "_petsc_GetLocalMatCondensed_iscol", (PetscObject)iscola));
5394:   }
5395:   *A_loc = aloc[0];
5396:   PetscCall(PetscFree(aloc));
5397:   if (!row) PetscCall(ISDestroy(&isrowa));
5398:   if (!col) PetscCall(ISDestroy(&iscola));
5399:   PetscCall(PetscLogEventEnd(MAT_Getlocalmatcondensed, A, 0, 0, 0));
5400:   PetscFunctionReturn(PETSC_SUCCESS);
5401: }

5403: /*
5404:  * Create a sequential AIJ matrix based on row indices. a whole column is extracted once a row is matched.
5405:  * Row could be local or remote.The routine is designed to be scalable in memory so that nothing is based
5406:  * on a global size.
5407:  * */
5408: static PetscErrorCode MatCreateSeqSubMatrixWithRows_Private(Mat P, IS rows, Mat *P_oth)
5409: {
5410:   Mat_MPIAIJ            *p  = (Mat_MPIAIJ *)P->data;
5411:   Mat_SeqAIJ            *pd = (Mat_SeqAIJ *)p->A->data, *po = (Mat_SeqAIJ *)p->B->data, *p_oth;
5412:   PetscInt               plocalsize, nrows, *ilocal, *oilocal, i, lidx, *nrcols, *nlcols, ncol;
5413:   PetscMPIInt            owner;
5414:   PetscSFNode           *iremote, *oiremote;
5415:   const PetscInt        *lrowindices;
5416:   PetscSF                sf, osf;
5417:   PetscInt               pcstart, *roffsets, *loffsets, *pnnz, j;
5418:   PetscInt               ontotalcols, dntotalcols, ntotalcols, nout;
5419:   MPI_Comm               comm;
5420:   ISLocalToGlobalMapping mapping;
5421:   const PetscScalar     *pd_a, *po_a;

5423:   PetscFunctionBegin;
5424:   PetscCall(PetscObjectGetComm((PetscObject)P, &comm));
5425:   /* plocalsize is the number of roots
5426:    * nrows is the number of leaves
5427:    * */
5428:   PetscCall(MatGetLocalSize(P, &plocalsize, NULL));
5429:   PetscCall(ISGetLocalSize(rows, &nrows));
5430:   PetscCall(PetscCalloc1(nrows, &iremote));
5431:   PetscCall(ISGetIndices(rows, &lrowindices));
5432:   for (i = 0; i < nrows; i++) {
5433:     /* Find a remote index and an owner for a row
5434:      * The row could be local or remote
5435:      * */
5436:     owner = 0;
5437:     lidx  = 0;
5438:     PetscCall(PetscLayoutFindOwnerIndex(P->rmap, lrowindices[i], &owner, &lidx));
5439:     iremote[i].index = lidx;
5440:     iremote[i].rank  = owner;
5441:   }
5442:   /* Create SF to communicate how many nonzero columns for each row */
5443:   PetscCall(PetscSFCreate(comm, &sf));
5444:   /* SF will figure out the number of nonzero columns for each row, and their
5445:    * offsets
5446:    * */
5447:   PetscCall(PetscSFSetGraph(sf, plocalsize, nrows, NULL, PETSC_OWN_POINTER, iremote, PETSC_OWN_POINTER));
5448:   PetscCall(PetscSFSetFromOptions(sf));
5449:   PetscCall(PetscSFSetUp(sf));

5451:   PetscCall(PetscCalloc1(2 * (plocalsize + 1), &roffsets));
5452:   PetscCall(PetscCalloc1(2 * plocalsize, &nrcols));
5453:   PetscCall(PetscCalloc1(nrows, &pnnz));
5454:   roffsets[0] = 0;
5455:   roffsets[1] = 0;
5456:   for (i = 0; i < plocalsize; i++) {
5457:     /* diagonal */
5458:     nrcols[i * 2 + 0] = pd->i[i + 1] - pd->i[i];
5459:     /* off-diagonal */
5460:     nrcols[i * 2 + 1] = po->i[i + 1] - po->i[i];
5461:     /* compute offsets so that we relative location for each row */
5462:     roffsets[(i + 1) * 2 + 0] = roffsets[i * 2 + 0] + nrcols[i * 2 + 0];
5463:     roffsets[(i + 1) * 2 + 1] = roffsets[i * 2 + 1] + nrcols[i * 2 + 1];
5464:   }
5465:   PetscCall(PetscCalloc1(2 * nrows, &nlcols));
5466:   PetscCall(PetscCalloc1(2 * nrows, &loffsets));
5467:   /* 'r' means root, and 'l' means leaf */
5468:   PetscCall(PetscSFBcastBegin(sf, MPIU_2INT, nrcols, nlcols, MPI_REPLACE));
5469:   PetscCall(PetscSFBcastBegin(sf, MPIU_2INT, roffsets, loffsets, MPI_REPLACE));
5470:   PetscCall(PetscSFBcastEnd(sf, MPIU_2INT, nrcols, nlcols, MPI_REPLACE));
5471:   PetscCall(PetscSFBcastEnd(sf, MPIU_2INT, roffsets, loffsets, MPI_REPLACE));
5472:   PetscCall(PetscSFDestroy(&sf));
5473:   PetscCall(PetscFree(roffsets));
5474:   PetscCall(PetscFree(nrcols));
5475:   dntotalcols = 0;
5476:   ontotalcols = 0;
5477:   ncol        = 0;
5478:   for (i = 0; i < nrows; i++) {
5479:     pnnz[i] = nlcols[i * 2 + 0] + nlcols[i * 2 + 1];
5480:     ncol    = PetscMax(pnnz[i], ncol);
5481:     /* diagonal */
5482:     dntotalcols += nlcols[i * 2 + 0];
5483:     /* off-diagonal */
5484:     ontotalcols += nlcols[i * 2 + 1];
5485:   }
5486:   /* We do not need to figure the right number of columns
5487:    * since all the calculations will be done by going through the raw data
5488:    * */
5489:   PetscCall(MatCreateSeqAIJ(PETSC_COMM_SELF, nrows, ncol, 0, pnnz, P_oth));
5490:   PetscCall(MatSetUp(*P_oth));
5491:   PetscCall(PetscFree(pnnz));
5492:   p_oth = (Mat_SeqAIJ *)(*P_oth)->data;
5493:   /* diagonal */
5494:   PetscCall(PetscCalloc1(dntotalcols, &iremote));
5495:   /* off-diagonal */
5496:   PetscCall(PetscCalloc1(ontotalcols, &oiremote));
5497:   /* diagonal */
5498:   PetscCall(PetscCalloc1(dntotalcols, &ilocal));
5499:   /* off-diagonal */
5500:   PetscCall(PetscCalloc1(ontotalcols, &oilocal));
5501:   dntotalcols = 0;
5502:   ontotalcols = 0;
5503:   ntotalcols  = 0;
5504:   for (i = 0; i < nrows; i++) {
5505:     owner = 0;
5506:     PetscCall(PetscLayoutFindOwnerIndex(P->rmap, lrowindices[i], &owner, NULL));
5507:     /* Set iremote for diag matrix */
5508:     for (j = 0; j < nlcols[i * 2 + 0]; j++) {
5509:       iremote[dntotalcols].index = loffsets[i * 2 + 0] + j;
5510:       iremote[dntotalcols].rank  = owner;
5511:       /* P_oth is seqAIJ so that ilocal need to point to the first part of memory */
5512:       ilocal[dntotalcols++] = ntotalcols++;
5513:     }
5514:     /* off-diagonal */
5515:     for (j = 0; j < nlcols[i * 2 + 1]; j++) {
5516:       oiremote[ontotalcols].index = loffsets[i * 2 + 1] + j;
5517:       oiremote[ontotalcols].rank  = owner;
5518:       oilocal[ontotalcols++]      = ntotalcols++;
5519:     }
5520:   }
5521:   PetscCall(ISRestoreIndices(rows, &lrowindices));
5522:   PetscCall(PetscFree(loffsets));
5523:   PetscCall(PetscFree(nlcols));
5524:   PetscCall(PetscSFCreate(comm, &sf));
5525:   /* P serves as roots and P_oth is leaves
5526:    * Diag matrix
5527:    * */
5528:   PetscCall(PetscSFSetGraph(sf, pd->i[plocalsize], dntotalcols, ilocal, PETSC_OWN_POINTER, iremote, PETSC_OWN_POINTER));
5529:   PetscCall(PetscSFSetFromOptions(sf));
5530:   PetscCall(PetscSFSetUp(sf));

5532:   PetscCall(PetscSFCreate(comm, &osf));
5533:   /* off-diagonal */
5534:   PetscCall(PetscSFSetGraph(osf, po->i[plocalsize], ontotalcols, oilocal, PETSC_OWN_POINTER, oiremote, PETSC_OWN_POINTER));
5535:   PetscCall(PetscSFSetFromOptions(osf));
5536:   PetscCall(PetscSFSetUp(osf));
5537:   PetscCall(MatSeqAIJGetArrayRead(p->A, &pd_a));
5538:   PetscCall(MatSeqAIJGetArrayRead(p->B, &po_a));
5539:   /* operate on the matrix internal data to save memory */
5540:   PetscCall(PetscSFBcastBegin(sf, MPIU_SCALAR, pd_a, p_oth->a, MPI_REPLACE));
5541:   PetscCall(PetscSFBcastBegin(osf, MPIU_SCALAR, po_a, p_oth->a, MPI_REPLACE));
5542:   PetscCall(MatGetOwnershipRangeColumn(P, &pcstart, NULL));
5543:   /* Convert to global indices for diag matrix */
5544:   for (i = 0; i < pd->i[plocalsize]; i++) pd->j[i] += pcstart;
5545:   PetscCall(PetscSFBcastBegin(sf, MPIU_INT, pd->j, p_oth->j, MPI_REPLACE));
5546:   /* We want P_oth store global indices */
5547:   PetscCall(ISLocalToGlobalMappingCreate(comm, 1, p->B->cmap->n, p->garray, PETSC_COPY_VALUES, &mapping));
5548:   /* Use memory scalable approach */
5549:   PetscCall(ISLocalToGlobalMappingSetType(mapping, ISLOCALTOGLOBALMAPPINGHASH));
5550:   PetscCall(ISLocalToGlobalMappingApply(mapping, po->i[plocalsize], po->j, po->j));
5551:   PetscCall(PetscSFBcastBegin(osf, MPIU_INT, po->j, p_oth->j, MPI_REPLACE));
5552:   PetscCall(PetscSFBcastEnd(sf, MPIU_INT, pd->j, p_oth->j, MPI_REPLACE));
5553:   /* Convert back to local indices */
5554:   for (i = 0; i < pd->i[plocalsize]; i++) pd->j[i] -= pcstart;
5555:   PetscCall(PetscSFBcastEnd(osf, MPIU_INT, po->j, p_oth->j, MPI_REPLACE));
5556:   nout = 0;
5557:   PetscCall(ISGlobalToLocalMappingApply(mapping, IS_GTOLM_DROP, po->i[plocalsize], po->j, &nout, po->j));
5558:   PetscCheck(nout == po->i[plocalsize], comm, PETSC_ERR_ARG_INCOMP, "n %" PetscInt_FMT " does not equal to nout %" PetscInt_FMT " ", po->i[plocalsize], nout);
5559:   PetscCall(ISLocalToGlobalMappingDestroy(&mapping));
5560:   /* Exchange values */
5561:   PetscCall(PetscSFBcastEnd(sf, MPIU_SCALAR, pd_a, p_oth->a, MPI_REPLACE));
5562:   PetscCall(PetscSFBcastEnd(osf, MPIU_SCALAR, po_a, p_oth->a, MPI_REPLACE));
5563:   PetscCall(MatSeqAIJRestoreArrayRead(p->A, &pd_a));
5564:   PetscCall(MatSeqAIJRestoreArrayRead(p->B, &po_a));
5565:   /* Stop PETSc from shrinking memory */
5566:   for (i = 0; i < nrows; i++) p_oth->ilen[i] = p_oth->imax[i];
5567:   PetscCall(MatAssemblyBegin(*P_oth, MAT_FINAL_ASSEMBLY));
5568:   PetscCall(MatAssemblyEnd(*P_oth, MAT_FINAL_ASSEMBLY));
5569:   /* Attach PetscSF objects to P_oth so that we can reuse it later */
5570:   PetscCall(PetscObjectCompose((PetscObject)*P_oth, "diagsf", (PetscObject)sf));
5571:   PetscCall(PetscObjectCompose((PetscObject)*P_oth, "offdiagsf", (PetscObject)osf));
5572:   PetscCall(PetscSFDestroy(&sf));
5573:   PetscCall(PetscSFDestroy(&osf));
5574:   PetscFunctionReturn(PETSC_SUCCESS);
5575: }

5577: /*
5578:  * Creates a SeqAIJ matrix by taking rows of B that equal to nonzero columns of local A
5579:  * This supports MPIAIJ and MAIJ
5580:  * */
5581: PetscErrorCode MatGetBrowsOfAcols_MPIXAIJ(Mat A, Mat P, PetscInt dof, MatReuse reuse, Mat *P_oth)
5582: {
5583:   Mat_MPIAIJ *a = (Mat_MPIAIJ *)A->data, *p = (Mat_MPIAIJ *)P->data;
5584:   Mat_SeqAIJ *p_oth;
5585:   IS          rows, map;
5586:   PetscHMapI  hamp;
5587:   PetscInt    i, htsize, *rowindices, off, *mapping, key, count;
5588:   MPI_Comm    comm;
5589:   PetscSF     sf, osf;
5590:   PetscBool   has;

5592:   PetscFunctionBegin;
5593:   PetscCall(PetscObjectGetComm((PetscObject)A, &comm));
5594:   PetscCall(PetscLogEventBegin(MAT_GetBrowsOfAocols, A, P, 0, 0));
5595:   /* If it is the first time, create an index set of off-diag nonzero columns of A,
5596:    *  and then create a submatrix (that often is an overlapping matrix)
5597:    * */
5598:   if (reuse == MAT_INITIAL_MATRIX) {
5599:     /* Use a hash table to figure out unique keys */
5600:     PetscCall(PetscHMapICreateWithSize(a->B->cmap->n, &hamp));
5601:     PetscCall(PetscCalloc1(a->B->cmap->n, &mapping));
5602:     count = 0;
5603:     /* Assume that  a->g is sorted, otherwise the following does not make sense */
5604:     for (i = 0; i < a->B->cmap->n; i++) {
5605:       key = a->garray[i] / dof;
5606:       PetscCall(PetscHMapIHas(hamp, key, &has));
5607:       if (!has) {
5608:         mapping[i] = count;
5609:         PetscCall(PetscHMapISet(hamp, key, count++));
5610:       } else {
5611:         /* Current 'i' has the same value the previous step */
5612:         mapping[i] = count - 1;
5613:       }
5614:     }
5615:     PetscCall(ISCreateGeneral(comm, a->B->cmap->n, mapping, PETSC_OWN_POINTER, &map));
5616:     PetscCall(PetscHMapIGetSize(hamp, &htsize));
5617:     PetscCheck(htsize == count, comm, PETSC_ERR_ARG_INCOMP, " Size of hash map %" PetscInt_FMT " is inconsistent with count %" PetscInt_FMT, htsize, count);
5618:     PetscCall(PetscCalloc1(htsize, &rowindices));
5619:     off = 0;
5620:     PetscCall(PetscHMapIGetKeys(hamp, &off, rowindices));
5621:     PetscCall(PetscHMapIDestroy(&hamp));
5622:     PetscCall(PetscSortInt(htsize, rowindices));
5623:     PetscCall(ISCreateGeneral(comm, htsize, rowindices, PETSC_OWN_POINTER, &rows));
5624:     /* In case, the matrix was already created but users want to recreate the matrix */
5625:     PetscCall(MatDestroy(P_oth));
5626:     PetscCall(MatCreateSeqSubMatrixWithRows_Private(P, rows, P_oth));
5627:     PetscCall(PetscObjectCompose((PetscObject)*P_oth, "aoffdiagtopothmapping", (PetscObject)map));
5628:     PetscCall(ISDestroy(&map));
5629:     PetscCall(ISDestroy(&rows));
5630:   } else if (reuse == MAT_REUSE_MATRIX) {
5631:     /* If matrix was already created, we simply update values using SF objects
5632:      * that as attached to the matrix earlier.
5633:      */
5634:     const PetscScalar *pd_a, *po_a;

5636:     PetscCall(PetscObjectQuery((PetscObject)*P_oth, "diagsf", (PetscObject *)&sf));
5637:     PetscCall(PetscObjectQuery((PetscObject)*P_oth, "offdiagsf", (PetscObject *)&osf));
5638:     PetscCheck(sf && osf, comm, PETSC_ERR_ARG_NULL, "Matrix is not initialized yet");
5639:     p_oth = (Mat_SeqAIJ *)(*P_oth)->data;
5640:     /* Update values in place */
5641:     PetscCall(MatSeqAIJGetArrayRead(p->A, &pd_a));
5642:     PetscCall(MatSeqAIJGetArrayRead(p->B, &po_a));
5643:     PetscCall(PetscSFBcastBegin(sf, MPIU_SCALAR, pd_a, p_oth->a, MPI_REPLACE));
5644:     PetscCall(PetscSFBcastBegin(osf, MPIU_SCALAR, po_a, p_oth->a, MPI_REPLACE));
5645:     PetscCall(PetscSFBcastEnd(sf, MPIU_SCALAR, pd_a, p_oth->a, MPI_REPLACE));
5646:     PetscCall(PetscSFBcastEnd(osf, MPIU_SCALAR, po_a, p_oth->a, MPI_REPLACE));
5647:     PetscCall(MatSeqAIJRestoreArrayRead(p->A, &pd_a));
5648:     PetscCall(MatSeqAIJRestoreArrayRead(p->B, &po_a));
5649:   } else SETERRQ(comm, PETSC_ERR_ARG_UNKNOWN_TYPE, "Unknown reuse type");
5650:   PetscCall(PetscLogEventEnd(MAT_GetBrowsOfAocols, A, P, 0, 0));
5651:   PetscFunctionReturn(PETSC_SUCCESS);
5652: }

5654: /*@C
5655:   MatGetBrowsOfAcols - Returns `IS` that contain rows of `B` that equal to nonzero columns of local `A`

5657:   Collective

5659:   Input Parameters:
5660: + A     - the first matrix in `MATMPIAIJ` format
5661: . B     - the second matrix in `MATMPIAIJ` format
5662: - scall - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`

5664:   Output Parameters:
5665: + rowb  - On input index sets of rows of B to extract (or `NULL`), modified on output
5666: . colb  - On input index sets of columns of B to extract (or `NULL`), modified on output
5667: - B_seq - the sequential matrix generated

5669:   Level: developer

5671: .seealso: `Mat`, `MATMPIAIJ`, `IS`, `MatReuse`
5672: @*/
5673: PetscErrorCode MatGetBrowsOfAcols(Mat A, Mat B, MatReuse scall, IS *rowb, IS *colb, Mat *B_seq)
5674: {
5675:   Mat_MPIAIJ *a = (Mat_MPIAIJ *)A->data;
5676:   PetscInt   *idx, i, start, ncols, nzA, nzB, *cmap, imark;
5677:   IS          isrowb, iscolb;
5678:   Mat        *bseq = NULL;

5680:   PetscFunctionBegin;
5681:   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 ")",
5682:              A->cmap->rstart, A->cmap->rend, B->rmap->rstart, B->rmap->rend);
5683:   PetscCall(PetscLogEventBegin(MAT_GetBrowsOfAcols, A, B, 0, 0));

5685:   if (scall == MAT_INITIAL_MATRIX) {
5686:     start = A->cmap->rstart;
5687:     cmap  = a->garray;
5688:     nzA   = a->A->cmap->n;
5689:     nzB   = a->B->cmap->n;
5690:     PetscCall(PetscMalloc1(nzA + nzB, &idx));
5691:     ncols = 0;
5692:     for (i = 0; i < nzB; i++) { /* row < local row index */
5693:       if (cmap[i] < start) idx[ncols++] = cmap[i];
5694:       else break;
5695:     }
5696:     imark = i;
5697:     for (i = 0; i < nzA; i++) idx[ncols++] = start + i;   /* local rows */
5698:     for (i = imark; i < nzB; i++) idx[ncols++] = cmap[i]; /* row > local row index */
5699:     PetscCall(ISCreateGeneral(PETSC_COMM_SELF, ncols, idx, PETSC_OWN_POINTER, &isrowb));
5700:     PetscCall(ISCreateStride(PETSC_COMM_SELF, B->cmap->N, 0, 1, &iscolb));
5701:   } else {
5702:     PetscCheck(rowb && colb, PETSC_COMM_SELF, PETSC_ERR_SUP, "IS rowb and colb must be provided for MAT_REUSE_MATRIX");
5703:     isrowb = *rowb;
5704:     iscolb = *colb;
5705:     PetscCall(PetscMalloc1(1, &bseq));
5706:     bseq[0] = *B_seq;
5707:   }
5708:   PetscCall(MatCreateSubMatrices(B, 1, &isrowb, &iscolb, scall, &bseq));
5709:   *B_seq = bseq[0];
5710:   PetscCall(PetscFree(bseq));
5711:   if (!rowb) {
5712:     PetscCall(ISDestroy(&isrowb));
5713:   } else {
5714:     *rowb = isrowb;
5715:   }
5716:   if (!colb) {
5717:     PetscCall(ISDestroy(&iscolb));
5718:   } else {
5719:     *colb = iscolb;
5720:   }
5721:   PetscCall(PetscLogEventEnd(MAT_GetBrowsOfAcols, A, B, 0, 0));
5722:   PetscFunctionReturn(PETSC_SUCCESS);
5723: }

5725: /*
5726:     MatGetBrowsOfAoCols_MPIAIJ - Creates a `MATSEQAIJ` matrix by taking rows of B that equal to nonzero columns
5727:     of the OFF-DIAGONAL portion of local A

5729:     Collective

5731:    Input Parameters:
5732: +    A,B - the matrices in `MATMPIAIJ` format
5733: -    scall - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`

5735:    Output Parameter:
5736: +    startsj_s - starting point in B's sending j-arrays, saved for MAT_REUSE (or NULL)
5737: .    startsj_r - starting point in B's receiving j-arrays, saved for MAT_REUSE (or NULL)
5738: .    bufa_ptr - array for sending matrix values, saved for MAT_REUSE (or NULL)
5739: -    B_oth - the sequential matrix generated with size aBn=a->B->cmap->n by B->cmap->N

5741:     Developer Note:
5742:     This directly accesses information inside the VecScatter associated with the matrix-vector product
5743:      for this matrix. This is not desirable..

5745:     Level: developer

5747: */

5749: PetscErrorCode MatGetBrowsOfAoCols_MPIAIJ(Mat A, Mat B, MatReuse scall, PetscInt **startsj_s, PetscInt **startsj_r, MatScalar **bufa_ptr, Mat *B_oth)
5750: {
5751:   Mat_MPIAIJ        *a = (Mat_MPIAIJ *)A->data;
5752:   VecScatter         ctx;
5753:   MPI_Comm           comm;
5754:   const PetscMPIInt *rprocs, *sprocs;
5755:   PetscMPIInt        nrecvs, nsends;
5756:   const PetscInt    *srow, *rstarts, *sstarts;
5757:   PetscInt          *rowlen, *bufj, *bufJ, ncols = 0, aBn = a->B->cmap->n, row, *b_othi, *b_othj, *rvalues = NULL, *svalues = NULL, *cols, sbs, rbs;
5758:   PetscInt           i, j, k = 0, l, ll, nrows, *rstartsj = NULL, *sstartsj, len;
5759:   PetscScalar       *b_otha, *bufa, *bufA, *vals = NULL;
5760:   MPI_Request       *reqs = NULL, *rwaits = NULL, *swaits = NULL;
5761:   PetscMPIInt        size, tag, rank, nreqs;

5763:   PetscFunctionBegin;
5764:   PetscCall(PetscObjectGetComm((PetscObject)A, &comm));
5765:   PetscCallMPI(MPI_Comm_size(comm, &size));

5767:   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 ")",
5768:              A->cmap->rstart, A->cmap->rend, B->rmap->rstart, B->rmap->rend);
5769:   PetscCall(PetscLogEventBegin(MAT_GetBrowsOfAocols, A, B, 0, 0));
5770:   PetscCallMPI(MPI_Comm_rank(comm, &rank));

5772:   if (size == 1) {
5773:     startsj_s = NULL;
5774:     bufa_ptr  = NULL;
5775:     *B_oth    = NULL;
5776:     PetscFunctionReturn(PETSC_SUCCESS);
5777:   }

5779:   ctx = a->Mvctx;
5780:   tag = ((PetscObject)ctx)->tag;

5782:   PetscCall(VecScatterGetRemote_Private(ctx, PETSC_TRUE /*send*/, &nsends, &sstarts, &srow, &sprocs, &sbs));
5783:   /* rprocs[] must be ordered so that indices received from them are ordered in rvalues[], which is key to algorithms used in this subroutine */
5784:   PetscCall(VecScatterGetRemoteOrdered_Private(ctx, PETSC_FALSE /*recv*/, &nrecvs, &rstarts, NULL /*indices not needed*/, &rprocs, &rbs));
5785:   PetscCall(PetscMPIIntCast(nsends + nrecvs, &nreqs));
5786:   PetscCall(PetscMalloc1(nreqs, &reqs));
5787:   rwaits = reqs;
5788:   swaits = PetscSafePointerPlusOffset(reqs, nrecvs);

5790:   if (!startsj_s || !bufa_ptr) scall = MAT_INITIAL_MATRIX;
5791:   if (scall == MAT_INITIAL_MATRIX) {
5792:     /* i-array */
5793:     /*  post receives */
5794:     if (nrecvs) PetscCall(PetscMalloc1(rbs * (rstarts[nrecvs] - rstarts[0]), &rvalues)); /* rstarts can be NULL when nrecvs=0 */
5795:     for (i = 0; i < nrecvs; i++) {
5796:       rowlen = rvalues + rstarts[i] * rbs;
5797:       nrows  = (rstarts[i + 1] - rstarts[i]) * rbs; /* num of indices to be received */
5798:       PetscCallMPI(MPIU_Irecv(rowlen, nrows, MPIU_INT, rprocs[i], tag, comm, rwaits + i));
5799:     }

5801:     /* pack the outgoing message */
5802:     PetscCall(PetscMalloc2(nsends + 1, &sstartsj, nrecvs + 1, &rstartsj));

5804:     sstartsj[0] = 0;
5805:     rstartsj[0] = 0;
5806:     len         = 0; /* total length of j or a array to be sent */
5807:     if (nsends) {
5808:       k = sstarts[0]; /* ATTENTION: sstarts[0] and rstarts[0] are not necessarily zero */
5809:       PetscCall(PetscMalloc1(sbs * (sstarts[nsends] - sstarts[0]), &svalues));
5810:     }
5811:     for (i = 0; i < nsends; i++) {
5812:       rowlen = svalues + (sstarts[i] - sstarts[0]) * sbs;
5813:       nrows  = sstarts[i + 1] - sstarts[i]; /* num of block rows */
5814:       for (j = 0; j < nrows; j++) {
5815:         row = srow[k] + B->rmap->range[rank]; /* global row idx */
5816:         for (l = 0; l < sbs; l++) {
5817:           PetscCall(MatGetRow_MPIAIJ(B, row + l, &ncols, NULL, NULL)); /* rowlength */

5819:           rowlen[j * sbs + l] = ncols;

5821:           len += ncols;
5822:           PetscCall(MatRestoreRow_MPIAIJ(B, row + l, &ncols, NULL, NULL));
5823:         }
5824:         k++;
5825:       }
5826:       PetscCallMPI(MPIU_Isend(rowlen, nrows * sbs, MPIU_INT, sprocs[i], tag, comm, swaits + i));

5828:       sstartsj[i + 1] = len; /* starting point of (i+1)-th outgoing msg in bufj and bufa */
5829:     }
5830:     /* recvs and sends of i-array are completed */
5831:     if (nreqs) PetscCallMPI(MPI_Waitall(nreqs, reqs, MPI_STATUSES_IGNORE));
5832:     PetscCall(PetscFree(svalues));

5834:     /* allocate buffers for sending j and a arrays */
5835:     PetscCall(PetscMalloc1(len, &bufj));
5836:     PetscCall(PetscMalloc1(len, &bufa));

5838:     /* create i-array of B_oth */
5839:     PetscCall(PetscMalloc1(aBn + 1, &b_othi));

5841:     b_othi[0] = 0;
5842:     len       = 0; /* total length of j or a array to be received */
5843:     k         = 0;
5844:     for (i = 0; i < nrecvs; i++) {
5845:       rowlen = rvalues + (rstarts[i] - rstarts[0]) * rbs;
5846:       nrows  = (rstarts[i + 1] - rstarts[i]) * rbs; /* num of rows to be received */
5847:       for (j = 0; j < nrows; j++) {
5848:         b_othi[k + 1] = b_othi[k] + rowlen[j];
5849:         PetscCall(PetscIntSumError(rowlen[j], len, &len));
5850:         k++;
5851:       }
5852:       rstartsj[i + 1] = len; /* starting point of (i+1)-th incoming msg in bufj and bufa */
5853:     }
5854:     PetscCall(PetscFree(rvalues));

5856:     /* allocate space for j and a arrays of B_oth */
5857:     PetscCall(PetscMalloc1(b_othi[aBn], &b_othj));
5858:     PetscCall(PetscMalloc1(b_othi[aBn], &b_otha));

5860:     /* j-array */
5861:     /*  post receives of j-array */
5862:     for (i = 0; i < nrecvs; i++) {
5863:       nrows = rstartsj[i + 1] - rstartsj[i]; /* length of the msg received */
5864:       PetscCallMPI(MPIU_Irecv(PetscSafePointerPlusOffset(b_othj, rstartsj[i]), nrows, MPIU_INT, rprocs[i], tag, comm, rwaits + i));
5865:     }

5867:     /* pack the outgoing message j-array */
5868:     if (nsends) k = sstarts[0];
5869:     for (i = 0; i < nsends; i++) {
5870:       nrows = sstarts[i + 1] - sstarts[i]; /* num of block rows */
5871:       bufJ  = PetscSafePointerPlusOffset(bufj, sstartsj[i]);
5872:       for (j = 0; j < nrows; j++) {
5873:         row = srow[k++] + B->rmap->range[rank]; /* global row idx */
5874:         for (ll = 0; ll < sbs; ll++) {
5875:           PetscCall(MatGetRow_MPIAIJ(B, row + ll, &ncols, &cols, NULL));
5876:           for (l = 0; l < ncols; l++) *bufJ++ = cols[l];
5877:           PetscCall(MatRestoreRow_MPIAIJ(B, row + ll, &ncols, &cols, NULL));
5878:         }
5879:       }
5880:       PetscCallMPI(MPIU_Isend(PetscSafePointerPlusOffset(bufj, sstartsj[i]), sstartsj[i + 1] - sstartsj[i], MPIU_INT, sprocs[i], tag, comm, swaits + i));
5881:     }

5883:     /* recvs and sends of j-array are completed */
5884:     if (nreqs) PetscCallMPI(MPI_Waitall(nreqs, reqs, MPI_STATUSES_IGNORE));
5885:   } else if (scall == MAT_REUSE_MATRIX) {
5886:     sstartsj = *startsj_s;
5887:     rstartsj = *startsj_r;
5888:     bufa     = *bufa_ptr;
5889:     PetscCall(MatSeqAIJGetArrayWrite(*B_oth, &b_otha));
5890:   } else SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Matrix P does not possess an object container");

5892:   /* a-array */
5893:   /*  post receives of a-array */
5894:   for (i = 0; i < nrecvs; i++) {
5895:     nrows = rstartsj[i + 1] - rstartsj[i]; /* length of the msg received */
5896:     PetscCallMPI(MPIU_Irecv(PetscSafePointerPlusOffset(b_otha, rstartsj[i]), nrows, MPIU_SCALAR, rprocs[i], tag, comm, rwaits + i));
5897:   }

5899:   /* pack the outgoing message a-array */
5900:   if (nsends) k = sstarts[0];
5901:   for (i = 0; i < nsends; i++) {
5902:     nrows = sstarts[i + 1] - sstarts[i]; /* num of block rows */
5903:     bufA  = PetscSafePointerPlusOffset(bufa, sstartsj[i]);
5904:     for (j = 0; j < nrows; j++) {
5905:       row = srow[k++] + B->rmap->range[rank]; /* global row idx */
5906:       for (ll = 0; ll < sbs; ll++) {
5907:         PetscCall(MatGetRow_MPIAIJ(B, row + ll, &ncols, NULL, &vals));
5908:         for (l = 0; l < ncols; l++) *bufA++ = vals[l];
5909:         PetscCall(MatRestoreRow_MPIAIJ(B, row + ll, &ncols, NULL, &vals));
5910:       }
5911:     }
5912:     PetscCallMPI(MPIU_Isend(PetscSafePointerPlusOffset(bufa, sstartsj[i]), sstartsj[i + 1] - sstartsj[i], MPIU_SCALAR, sprocs[i], tag, comm, swaits + i));
5913:   }
5914:   /* recvs and sends of a-array are completed */
5915:   if (nreqs) PetscCallMPI(MPI_Waitall(nreqs, reqs, MPI_STATUSES_IGNORE));
5916:   PetscCall(PetscFree(reqs));

5918:   if (scall == MAT_INITIAL_MATRIX) {
5919:     Mat_SeqAIJ *b_oth;

5921:     /* put together the new matrix */
5922:     PetscCall(MatCreateSeqAIJWithArrays(PETSC_COMM_SELF, aBn, B->cmap->N, b_othi, b_othj, b_otha, B_oth));

5924:     /* MatCreateSeqAIJWithArrays flags matrix so PETSc doesn't free the user's arrays. */
5925:     /* Since these are PETSc arrays, change flags to free them as necessary. */
5926:     b_oth          = (Mat_SeqAIJ *)(*B_oth)->data;
5927:     b_oth->free_a  = PETSC_TRUE;
5928:     b_oth->free_ij = PETSC_TRUE;
5929:     b_oth->nonew   = 0;

5931:     PetscCall(PetscFree(bufj));
5932:     if (!startsj_s || !bufa_ptr) {
5933:       PetscCall(PetscFree2(sstartsj, rstartsj));
5934:       PetscCall(PetscFree(bufa_ptr));
5935:     } else {
5936:       *startsj_s = sstartsj;
5937:       *startsj_r = rstartsj;
5938:       *bufa_ptr  = bufa;
5939:     }
5940:   } else if (scall == MAT_REUSE_MATRIX) {
5941:     PetscCall(MatSeqAIJRestoreArrayWrite(*B_oth, &b_otha));
5942:   }

5944:   PetscCall(VecScatterRestoreRemote_Private(ctx, PETSC_TRUE, &nsends, &sstarts, &srow, &sprocs, &sbs));
5945:   PetscCall(VecScatterRestoreRemoteOrdered_Private(ctx, PETSC_FALSE, &nrecvs, &rstarts, NULL, &rprocs, &rbs));
5946:   PetscCall(PetscLogEventEnd(MAT_GetBrowsOfAocols, A, B, 0, 0));
5947:   PetscFunctionReturn(PETSC_SUCCESS);
5948: }

5950: PETSC_INTERN PetscErrorCode MatConvert_MPIAIJ_MPIAIJCRL(Mat, MatType, MatReuse, Mat *);
5951: PETSC_INTERN PetscErrorCode MatConvert_MPIAIJ_MPIAIJPERM(Mat, MatType, MatReuse, Mat *);
5952: PETSC_INTERN PetscErrorCode MatConvert_MPIAIJ_MPIAIJSELL(Mat, MatType, MatReuse, Mat *);
5953: #if defined(PETSC_HAVE_MKL_SPARSE)
5954: PETSC_INTERN PetscErrorCode MatConvert_MPIAIJ_MPIAIJMKL(Mat, MatType, MatReuse, Mat *);
5955: #endif
5956: PETSC_INTERN PetscErrorCode MatConvert_MPIAIJ_MPIBAIJ(Mat, MatType, MatReuse, Mat *);
5957: PETSC_INTERN PetscErrorCode MatConvert_MPIAIJ_MPISBAIJ(Mat, MatType, MatReuse, Mat *);
5958: #if defined(PETSC_HAVE_ELEMENTAL)
5959: PETSC_INTERN PetscErrorCode MatConvert_MPIAIJ_Elemental(Mat, MatType, MatReuse, Mat *);
5960: #endif
5961: #if defined(PETSC_HAVE_SCALAPACK) && (defined(PETSC_USE_REAL_SINGLE) || defined(PETSC_USE_REAL_DOUBLE))
5962: PETSC_INTERN PetscErrorCode MatConvert_AIJ_ScaLAPACK(Mat, MatType, MatReuse, Mat *);
5963: #endif
5964: #if defined(PETSC_HAVE_HYPRE)
5965: PETSC_INTERN PetscErrorCode MatConvert_AIJ_HYPRE(Mat, MatType, MatReuse, Mat *);
5966: #endif
5967: #if defined(PETSC_HAVE_CUDA)
5968: PETSC_INTERN PetscErrorCode MatConvert_MPIAIJ_MPIAIJCUSPARSE(Mat, MatType, MatReuse, Mat *);
5969: #endif
5970: #if defined(PETSC_HAVE_HIP)
5971: PETSC_INTERN PetscErrorCode MatConvert_MPIAIJ_MPIAIJHIPSPARSE(Mat, MatType, MatReuse, Mat *);
5972: #endif
5973: #if defined(PETSC_HAVE_KOKKOS_KERNELS)
5974: PETSC_INTERN PetscErrorCode MatConvert_MPIAIJ_MPIAIJKokkos(Mat, MatType, MatReuse, Mat *);
5975: #endif
5976: PETSC_INTERN PetscErrorCode MatConvert_MPIAIJ_MPISELL(Mat, MatType, MatReuse, Mat *);
5977: PETSC_INTERN PetscErrorCode MatConvert_XAIJ_IS(Mat, MatType, MatReuse, Mat *);
5978: PETSC_INTERN PetscErrorCode MatProductSetFromOptions_IS_XAIJ(Mat);

5980: /*
5981:     Computes (B'*A')' since computing B*A directly is untenable

5983:                n                       p                          p
5984:         [             ]       [             ]         [                 ]
5985:       m [      A      ]  *  n [       B     ]   =   m [         C       ]
5986:         [             ]       [             ]         [                 ]

5988: */
5989: static PetscErrorCode MatMatMultNumeric_MPIDense_MPIAIJ(Mat A, Mat B, Mat C)
5990: {
5991:   Mat At, Bt, Ct;

5993:   PetscFunctionBegin;
5994:   PetscCall(MatTranspose(A, MAT_INITIAL_MATRIX, &At));
5995:   PetscCall(MatTranspose(B, MAT_INITIAL_MATRIX, &Bt));
5996:   PetscCall(MatMatMult(Bt, At, MAT_INITIAL_MATRIX, PETSC_CURRENT, &Ct));
5997:   PetscCall(MatDestroy(&At));
5998:   PetscCall(MatDestroy(&Bt));
5999:   PetscCall(MatTransposeSetPrecursor(Ct, C));
6000:   PetscCall(MatTranspose(Ct, MAT_REUSE_MATRIX, &C));
6001:   PetscCall(MatDestroy(&Ct));
6002:   PetscFunctionReturn(PETSC_SUCCESS);
6003: }

6005: static PetscErrorCode MatMatMultSymbolic_MPIDense_MPIAIJ(Mat A, Mat B, PetscReal fill, Mat C)
6006: {
6007:   PetscBool cisdense;

6009:   PetscFunctionBegin;
6010:   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);
6011:   PetscCall(MatSetSizes(C, A->rmap->n, B->cmap->n, A->rmap->N, B->cmap->N));
6012:   PetscCall(MatSetBlockSizesFromMats(C, A, B));
6013:   PetscCall(PetscObjectTypeCompareAny((PetscObject)C, &cisdense, MATMPIDENSE, MATMPIDENSECUDA, MATMPIDENSEHIP, ""));
6014:   if (!cisdense) PetscCall(MatSetType(C, ((PetscObject)A)->type_name));
6015:   PetscCall(MatSetUp(C));

6017:   C->ops->matmultnumeric = MatMatMultNumeric_MPIDense_MPIAIJ;
6018:   PetscFunctionReturn(PETSC_SUCCESS);
6019: }

6021: static PetscErrorCode MatProductSetFromOptions_MPIDense_MPIAIJ_AB(Mat C)
6022: {
6023:   Mat_Product *product = C->product;
6024:   Mat          A = product->A, B = product->B;

6026:   PetscFunctionBegin;
6027:   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 ")",
6028:              A->cmap->rstart, A->cmap->rend, B->rmap->rstart, B->rmap->rend);
6029:   C->ops->matmultsymbolic = MatMatMultSymbolic_MPIDense_MPIAIJ;
6030:   C->ops->productsymbolic = MatProductSymbolic_AB;
6031:   PetscFunctionReturn(PETSC_SUCCESS);
6032: }

6034: PETSC_INTERN PetscErrorCode MatProductSetFromOptions_MPIDense_MPIAIJ(Mat C)
6035: {
6036:   Mat_Product *product = C->product;

6038:   PetscFunctionBegin;
6039:   if (product->type == MATPRODUCT_AB) PetscCall(MatProductSetFromOptions_MPIDense_MPIAIJ_AB(C));
6040:   PetscFunctionReturn(PETSC_SUCCESS);
6041: }

6043: /*
6044:    Merge two sets of sorted nonzeros and return a CSR for the merged (sequential) matrix

6046:   Input Parameters:

6048:     j1,rowBegin1,rowEnd1,jmap1: describe the first set of nonzeros (Set1)
6049:     j2,rowBegin2,rowEnd2,jmap2: describe the second set of nonzeros (Set2)

6051:     mat: both sets' nonzeros are on m rows, where m is the number of local rows of the matrix mat

6053:     For Set1, j1[] contains column indices of the nonzeros.
6054:     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
6055:     respectively (note rowEnd1[k] is not necessarily equal to rwoBegin1[k+1]). Indices in this range of j1[] are sorted,
6056:     but might have repeats. jmap1[t+1] - jmap1[t] is the number of repeats for the t-th unique nonzero in Set1.

6058:     Similar for Set2.

6060:     This routine merges the two sets of nonzeros row by row and removes repeats.

6062:   Output Parameters: (memory is allocated by the caller)

6064:     i[],j[]: the CSR of the merged matrix, which has m rows.
6065:     imap1[]: the k-th unique nonzero in Set1 (k=0,1,...) corresponds to imap1[k]-th unique nonzero in the merged matrix.
6066:     imap2[]: similar to imap1[], but for Set2.
6067:     Note we order nonzeros row-by-row and from left to right.
6068: */
6069: 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[])
6070: {
6071:   PetscInt   r, m; /* Row index of mat */
6072:   PetscCount t, t1, t2, b1, e1, b2, e2;

6074:   PetscFunctionBegin;
6075:   PetscCall(MatGetLocalSize(mat, &m, NULL));
6076:   t1 = t2 = t = 0; /* Count unique nonzeros of in Set1, Set1 and the merged respectively */
6077:   i[0]        = 0;
6078:   for (r = 0; r < m; r++) { /* Do row by row merging */
6079:     b1 = rowBegin1[r];
6080:     e1 = rowEnd1[r];
6081:     b2 = rowBegin2[r];
6082:     e2 = rowEnd2[r];
6083:     while (b1 < e1 && b2 < e2) {
6084:       if (j1[b1] == j2[b2]) { /* Same column index and hence same nonzero */
6085:         j[t]      = j1[b1];
6086:         imap1[t1] = t;
6087:         imap2[t2] = t;
6088:         b1 += jmap1[t1 + 1] - jmap1[t1]; /* Jump to next unique local nonzero */
6089:         b2 += jmap2[t2 + 1] - jmap2[t2]; /* Jump to next unique remote nonzero */
6090:         t1++;
6091:         t2++;
6092:         t++;
6093:       } else if (j1[b1] < j2[b2]) {
6094:         j[t]      = j1[b1];
6095:         imap1[t1] = t;
6096:         b1 += jmap1[t1 + 1] - jmap1[t1];
6097:         t1++;
6098:         t++;
6099:       } else {
6100:         j[t]      = j2[b2];
6101:         imap2[t2] = t;
6102:         b2 += jmap2[t2 + 1] - jmap2[t2];
6103:         t2++;
6104:         t++;
6105:       }
6106:     }
6107:     /* Merge the remaining in either j1[] or j2[] */
6108:     while (b1 < e1) {
6109:       j[t]      = j1[b1];
6110:       imap1[t1] = t;
6111:       b1 += jmap1[t1 + 1] - jmap1[t1];
6112:       t1++;
6113:       t++;
6114:     }
6115:     while (b2 < e2) {
6116:       j[t]      = j2[b2];
6117:       imap2[t2] = t;
6118:       b2 += jmap2[t2 + 1] - jmap2[t2];
6119:       t2++;
6120:       t++;
6121:     }
6122:     PetscCall(PetscIntCast(t, i + r + 1));
6123:   }
6124:   PetscFunctionReturn(PETSC_SUCCESS);
6125: }

6127: /*
6128:   Split nonzeros in a block of local rows into two subsets: those in the diagonal block and those in the off-diagonal block

6130:   Input Parameters:
6131:     mat: an MPI matrix that provides row and column layout information for splitting. Let's say its number of local rows is m.
6132:     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[]
6133:       respectively, along with a permutation array perm[]. Length of the i[],j[],perm[] arrays is n.

6135:       i[] is already sorted, but within a row, j[] is not sorted and might have repeats.
6136:       i[] might contain negative indices at the beginning, which means the corresponding entries should be ignored in the splitting.

6138:   Output Parameters:
6139:     j[],perm[]: the routine needs to sort j[] within each row along with perm[].
6140:     rowBegin[],rowMid[],rowEnd[]: of length m, and the memory is preallocated and zeroed by the caller.
6141:       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,
6142:       and [rowMid[r],rowEnd[r]) point to begin/end entries of row r of the off-diagonal block.

6144:     Aperm[],Ajmap[],Atot,Annz: Arrays are allocated by this routine.
6145:       Atot: number of entries belonging to the diagonal block.
6146:       Annz: number of unique nonzeros belonging to the diagonal block.
6147:       Aperm[Atot] stores values from perm[] for entries belonging to the diagonal block. Length of Aperm[] is Atot, though it may also count
6148:         repeats (i.e., same 'i,j' pair).
6149:       Ajmap[Annz+1] stores the number of repeats of each unique entry belonging to the diagonal block. More precisely, Ajmap[t+1] - Ajmap[t]
6150:         is the number of repeats for the t-th unique entry in the diagonal block. Ajmap[0] is always 0.

6152:       Atot: number of entries belonging to the diagonal block
6153:       Annz: number of unique nonzeros belonging to the diagonal block.

6155:     Bperm[], Bjmap[], Btot, Bnnz are similar but for the off-diagonal block.

6157:     Aperm[],Bperm[],Ajmap[] and Bjmap[] are allocated separately by this routine with PetscMalloc1().
6158: */
6159: 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_)
6160: {
6161:   PetscInt    cstart, cend, rstart, rend, row, col;
6162:   PetscCount  Atot = 0, Btot = 0; /* Total number of nonzeros in the diagonal and off-diagonal blocks */
6163:   PetscCount  Annz = 0, Bnnz = 0; /* Number of unique nonzeros in the diagonal and off-diagonal blocks */
6164:   PetscCount  k, m, p, q, r, s, mid;
6165:   PetscCount *Aperm, *Bperm, *Ajmap, *Bjmap;

6167:   PetscFunctionBegin;
6168:   PetscCall(PetscLayoutGetRange(mat->rmap, &rstart, &rend));
6169:   PetscCall(PetscLayoutGetRange(mat->cmap, &cstart, &cend));
6170:   m = rend - rstart;

6172:   /* Skip negative rows */
6173:   for (k = 0; k < n; k++)
6174:     if (i[k] >= 0) break;

6176:   /* Process [k,n): sort and partition each local row into diag and offdiag portions,
6177:      fill rowBegin[], rowMid[], rowEnd[], and count Atot, Btot, Annz, Bnnz.
6178:   */
6179:   while (k < n) {
6180:     row = i[k];
6181:     /* Entries in [k,s) are in one row. Shift diagonal block col indices so that diag is ahead of offdiag after sorting the row */
6182:     for (s = k; s < n; s++)
6183:       if (i[s] != row) break;

6185:     /* Shift diag columns to range of [-PETSC_INT_MAX, -1] */
6186:     for (p = k; p < s; p++) {
6187:       if (j[p] >= cstart && j[p] < cend) j[p] -= PETSC_INT_MAX;
6188:     }
6189:     PetscCall(PetscSortIntWithCountArray(s - k, j + k, perm + k));
6190:     PetscCall(PetscSortedIntUpperBound(j, k, s, -1, &mid)); /* Separate [k,s) into [k,mid) for diag and [mid,s) for offdiag */
6191:     rowBegin[row - rstart] = k;
6192:     rowMid[row - rstart]   = mid;
6193:     rowEnd[row - rstart]   = s;
6194:     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);

6196:     /* Count nonzeros of this diag/offdiag row, which might have repeats */
6197:     Atot += mid - k;
6198:     Btot += s - mid;

6200:     /* Count unique nonzeros of this diag row */
6201:     for (p = k; p < mid;) {
6202:       col = j[p];
6203:       do {
6204:         j[p] += PETSC_INT_MAX; /* Revert the modified diagonal indices */
6205:         p++;
6206:       } while (p < mid && j[p] == col);
6207:       Annz++;
6208:     }

6210:     /* Count unique nonzeros of this offdiag row */
6211:     for (p = mid; p < s;) {
6212:       col = j[p];
6213:       do {
6214:         p++;
6215:       } while (p < s && j[p] == col);
6216:       Bnnz++;
6217:     }
6218:     k = s;
6219:   }

6221:   /* Allocation according to Atot, Btot, Annz, Bnnz */
6222:   PetscCall(PetscMalloc1(Atot, &Aperm));
6223:   PetscCall(PetscMalloc1(Btot, &Bperm));
6224:   PetscCall(PetscMalloc1(Annz + 1, &Ajmap));
6225:   PetscCall(PetscMalloc1(Bnnz + 1, &Bjmap));

6227:   /* Re-scan indices and copy diag/offdiag permutation indices to Aperm, Bperm and also fill Ajmap and Bjmap */
6228:   Ajmap[0] = Bjmap[0] = Atot = Btot = Annz = Bnnz = 0;
6229:   for (r = 0; r < m; r++) {
6230:     k   = rowBegin[r];
6231:     mid = rowMid[r];
6232:     s   = rowEnd[r];
6233:     PetscCall(PetscArraycpy(PetscSafePointerPlusOffset(Aperm, Atot), PetscSafePointerPlusOffset(perm, k), mid - k));
6234:     PetscCall(PetscArraycpy(PetscSafePointerPlusOffset(Bperm, Btot), PetscSafePointerPlusOffset(perm, mid), s - mid));
6235:     Atot += mid - k;
6236:     Btot += s - mid;

6238:     /* Scan column indices in this row and find out how many repeats each unique nonzero has */
6239:     for (p = k; p < mid;) {
6240:       col = j[p];
6241:       q   = p;
6242:       do {
6243:         p++;
6244:       } while (p < mid && j[p] == col);
6245:       Ajmap[Annz + 1] = Ajmap[Annz] + (p - q);
6246:       Annz++;
6247:     }

6249:     for (p = mid; p < s;) {
6250:       col = j[p];
6251:       q   = p;
6252:       do {
6253:         p++;
6254:       } while (p < s && j[p] == col);
6255:       Bjmap[Bnnz + 1] = Bjmap[Bnnz] + (p - q);
6256:       Bnnz++;
6257:     }
6258:   }
6259:   /* Output */
6260:   *Aperm_ = Aperm;
6261:   *Annz_  = Annz;
6262:   *Atot_  = Atot;
6263:   *Ajmap_ = Ajmap;
6264:   *Bperm_ = Bperm;
6265:   *Bnnz_  = Bnnz;
6266:   *Btot_  = Btot;
6267:   *Bjmap_ = Bjmap;
6268:   PetscFunctionReturn(PETSC_SUCCESS);
6269: }

6271: /*
6272:   Expand the jmap[] array to make a new one in view of nonzeros in the merged matrix

6274:   Input Parameters:
6275:     nnz1: number of unique nonzeros in a set that was used to produce imap[], jmap[]
6276:     nnz:  number of unique nonzeros in the merged matrix
6277:     imap[nnz1]: i-th nonzero in the set is the imap[i]-th nonzero in the merged matrix
6278:     jmap[nnz1+1]: i-th nonzero in the set has jmap[i+1] - jmap[i] repeats in the set

6280:   Output Parameter: (memory is allocated by the caller)
6281:     jmap_new[nnz+1]: i-th nonzero in the merged matrix has jmap_new[i+1] - jmap_new[i] repeats in the set

6283:   Example:
6284:     nnz1 = 4
6285:     nnz  = 6
6286:     imap = [1,3,4,5]
6287:     jmap = [0,3,5,6,7]
6288:    then,
6289:     jmap_new = [0,0,3,3,5,6,7]
6290: */
6291: static PetscErrorCode ExpandJmap_Internal(PetscCount nnz1, PetscCount nnz, const PetscCount imap[], const PetscCount jmap[], PetscCount jmap_new[])
6292: {
6293:   PetscCount k, p;

6295:   PetscFunctionBegin;
6296:   jmap_new[0] = 0;
6297:   p           = nnz;                /* p loops over jmap_new[] backwards */
6298:   for (k = nnz1 - 1; k >= 0; k--) { /* k loops over imap[] */
6299:     for (; p > imap[k]; p--) jmap_new[p] = jmap[k + 1];
6300:   }
6301:   for (; p >= 0; p--) jmap_new[p] = jmap[0];
6302:   PetscFunctionReturn(PETSC_SUCCESS);
6303: }

6305: static PetscErrorCode MatCOOStructDestroy_MPIAIJ(PetscCtxRt data)
6306: {
6307:   MatCOOStruct_MPIAIJ *coo = *(MatCOOStruct_MPIAIJ **)data;

6309:   PetscFunctionBegin;
6310:   PetscCall(PetscSFDestroy(&coo->sf));
6311:   PetscCall(PetscFree(coo->Aperm1));
6312:   PetscCall(PetscFree(coo->Bperm1));
6313:   PetscCall(PetscFree(coo->Ajmap1));
6314:   PetscCall(PetscFree(coo->Bjmap1));
6315:   PetscCall(PetscFree(coo->Aimap2));
6316:   PetscCall(PetscFree(coo->Bimap2));
6317:   PetscCall(PetscFree(coo->Aperm2));
6318:   PetscCall(PetscFree(coo->Bperm2));
6319:   PetscCall(PetscFree(coo->Ajmap2));
6320:   PetscCall(PetscFree(coo->Bjmap2));
6321:   PetscCall(PetscFree(coo->Cperm1));
6322:   PetscCall(PetscFree2(coo->sendbuf, coo->recvbuf));
6323:   PetscCall(PetscFree(coo));
6324:   PetscFunctionReturn(PETSC_SUCCESS);
6325: }

6327: PetscErrorCode MatSetPreallocationCOO_MPIAIJ(Mat mat, PetscCount coo_n, PetscInt coo_i[], PetscInt coo_j[])
6328: {
6329:   MPI_Comm             comm;
6330:   PetscMPIInt          rank, size;
6331:   PetscInt             m, n, M, N, rstart, rend, cstart, cend; /* Sizes, indices of row/col, therefore with type PetscInt */
6332:   PetscCount           k, p, q, rem;                           /* Loop variables over coo arrays */
6333:   Mat_MPIAIJ          *mpiaij = (Mat_MPIAIJ *)mat->data;
6334:   PetscContainer       container;
6335:   MatCOOStruct_MPIAIJ *coo;

6337:   PetscFunctionBegin;
6338:   PetscCall(PetscFree(mpiaij->garray));
6339:   PetscCall(VecDestroy(&mpiaij->lvec));
6340: #if defined(PETSC_USE_CTABLE)
6341:   PetscCall(PetscHMapIDestroy(&mpiaij->colmap));
6342: #else
6343:   PetscCall(PetscFree(mpiaij->colmap));
6344: #endif
6345:   PetscCall(VecScatterDestroy(&mpiaij->Mvctx));
6346:   mat->assembled     = PETSC_FALSE;
6347:   mat->was_assembled = PETSC_FALSE;

6349:   PetscCall(PetscObjectGetComm((PetscObject)mat, &comm));
6350:   PetscCallMPI(MPI_Comm_size(comm, &size));
6351:   PetscCallMPI(MPI_Comm_rank(comm, &rank));
6352:   PetscCall(PetscLayoutSetUp(mat->rmap));
6353:   PetscCall(PetscLayoutSetUp(mat->cmap));
6354:   PetscCall(PetscLayoutGetRange(mat->rmap, &rstart, &rend));
6355:   PetscCall(PetscLayoutGetRange(mat->cmap, &cstart, &cend));
6356:   PetscCall(MatGetLocalSize(mat, &m, &n));
6357:   PetscCall(MatGetSize(mat, &M, &N));

6359:   /* Sort (i,j) by row along with a permutation array, so that the to-be-ignored */
6360:   /* entries come first, then local rows, then remote rows.                     */
6361:   PetscCount n1 = coo_n, *perm1;
6362:   PetscInt  *i1 = coo_i, *j1 = coo_j;

6364:   PetscCall(PetscMalloc1(n1, &perm1));
6365:   for (k = 0; k < n1; k++) perm1[k] = k;

6367:   /* Manipulate indices so that entries with negative row or col indices will have smallest
6368:      row indices, local entries will have greater but negative row indices, and remote entries
6369:      will have positive row indices.
6370:   */
6371:   for (k = 0; k < n1; k++) {
6372:     if (i1[k] < 0 || j1[k] < 0) i1[k] = PETSC_INT_MIN;                /* e.g., -2^31, minimal to move them ahead */
6373:     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] */
6374:     else {
6375:       PetscCheck(!mat->nooffprocentries, PETSC_COMM_SELF, PETSC_ERR_USER_INPUT, "MAT_NO_OFF_PROC_ENTRIES is set but insert to remote rows");
6376:       if (mpiaij->donotstash) i1[k] = PETSC_INT_MIN; /* Ignore offproc entries as if they had negative indices */
6377:     }
6378:   }

6380:   /* Sort by row; after that, [0,k) have ignored entries, [k,rem) have local rows and [rem,n1) have remote rows */
6381:   PetscCall(PetscSortIntWithIntCountArrayPair(n1, i1, j1, perm1));

6383:   /* Advance k to the first entry we need to take care of */
6384:   for (k = 0; k < n1; k++)
6385:     if (i1[k] > PETSC_INT_MIN) break;
6386:   PetscCount i1start = k;

6388:   PetscCall(PetscSortedIntUpperBound(i1, k, n1, rend - 1 - PETSC_INT_MAX, &rem)); /* rem is upper bound of the last local row */
6389:   for (; k < rem; k++) i1[k] += PETSC_INT_MAX;                                    /* Revert row indices of local rows*/

6391:   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);

6393:   /*           Send remote rows to their owner                                  */
6394:   /* Find which rows should be sent to which remote ranks*/
6395:   PetscInt        nsend = 0; /* Number of MPI ranks to send data to */
6396:   PetscMPIInt    *sendto;    /* [nsend], storing remote ranks */
6397:   PetscInt       *nentries;  /* [nsend], storing number of entries sent to remote ranks; Assume PetscInt is big enough for this count, and error if not */
6398:   const PetscInt *ranges;
6399:   PetscInt        maxNsend = size >= 128 ? 128 : size; /* Assume max 128 neighbors; realloc when needed */

6401:   PetscCall(PetscLayoutGetRanges(mat->rmap, &ranges));
6402:   PetscCall(PetscMalloc2(maxNsend, &sendto, maxNsend, &nentries));
6403:   for (k = rem; k < n1;) {
6404:     PetscMPIInt owner;
6405:     PetscInt    firstRow, lastRow;

6407:     /* Locate a row range */
6408:     firstRow = i1[k]; /* first row of this owner */
6409:     PetscCall(PetscLayoutFindOwner(mat->rmap, firstRow, &owner));
6410:     lastRow = ranges[owner + 1] - 1; /* last row of this owner */

6412:     /* Find the first index 'p' in [k,n) with i1[p] belonging to next owner */
6413:     PetscCall(PetscSortedIntUpperBound(i1, k, n1, lastRow, &p));

6415:     /* All entries in [k,p) belong to this remote owner */
6416:     if (nsend >= maxNsend) { /* Double the remote ranks arrays if not long enough */
6417:       PetscMPIInt *sendto2;
6418:       PetscInt    *nentries2;
6419:       PetscInt     maxNsend2 = (maxNsend <= size / 2) ? maxNsend * 2 : size;

6421:       PetscCall(PetscMalloc2(maxNsend2, &sendto2, maxNsend2, &nentries2));
6422:       PetscCall(PetscArraycpy(sendto2, sendto, maxNsend));
6423:       PetscCall(PetscArraycpy(nentries2, nentries, maxNsend));
6424:       PetscCall(PetscFree2(sendto, nentries));
6425:       sendto   = sendto2;
6426:       nentries = nentries2;
6427:       maxNsend = maxNsend2;
6428:     }
6429:     sendto[nsend] = owner;
6430:     PetscCall(PetscIntCast(p - k, &nentries[nsend]));
6431:     nsend++;
6432:     k = p;
6433:   }

6435:   /* Build 1st SF to know offsets on remote to send data */
6436:   PetscSF      sf1;
6437:   PetscInt     nroots = 1, nroots2 = 0;
6438:   PetscInt     nleaves = nsend, nleaves2 = 0;
6439:   PetscInt    *offsets;
6440:   PetscSFNode *iremote;

6442:   PetscCall(PetscSFCreate(comm, &sf1));
6443:   PetscCall(PetscMalloc1(nsend, &iremote));
6444:   PetscCall(PetscMalloc1(nsend, &offsets));
6445:   for (k = 0; k < nsend; k++) {
6446:     iremote[k].rank  = sendto[k];
6447:     iremote[k].index = 0;
6448:     nleaves2 += nentries[k];
6449:     PetscCheck(nleaves2 >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Number of SF leaves is too large for PetscInt");
6450:   }
6451:   PetscCall(PetscSFSetGraph(sf1, nroots, nleaves, NULL, PETSC_OWN_POINTER, iremote, PETSC_OWN_POINTER));
6452:   PetscCall(PetscSFFetchAndOpWithMemTypeBegin(sf1, MPIU_INT, PETSC_MEMTYPE_HOST, &nroots2 /*rootdata*/, PETSC_MEMTYPE_HOST, nentries /*leafdata*/, PETSC_MEMTYPE_HOST, offsets /*leafupdate*/, MPI_SUM));
6453:   PetscCall(PetscSFFetchAndOpEnd(sf1, MPIU_INT, &nroots2, nentries, offsets, MPI_SUM)); /* Would nroots2 overflow, we check offsets[] below */
6454:   PetscCall(PetscSFDestroy(&sf1));
6455:   PetscAssert(nleaves2 == n1 - rem, PETSC_COMM_SELF, PETSC_ERR_PLIB, "nleaves2 %" PetscInt_FMT " != number of remote entries %" PetscCount_FMT, nleaves2, n1 - rem);

6457:   /* Build 2nd SF to send remote COOs to their owner */
6458:   PetscSF sf2;
6459:   nroots  = nroots2;
6460:   nleaves = nleaves2;
6461:   PetscCall(PetscSFCreate(comm, &sf2));
6462:   PetscCall(PetscSFSetFromOptions(sf2));
6463:   PetscCall(PetscMalloc1(nleaves, &iremote));
6464:   p = 0;
6465:   for (k = 0; k < nsend; k++) {
6466:     PetscCheck(offsets[k] >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Number of SF roots is too large for PetscInt");
6467:     for (q = 0; q < nentries[k]; q++, p++) {
6468:       iremote[p].rank = sendto[k];
6469:       PetscCall(PetscIntCast(offsets[k] + q, &iremote[p].index));
6470:     }
6471:   }
6472:   PetscCall(PetscSFSetGraph(sf2, nroots, nleaves, NULL, PETSC_OWN_POINTER, iremote, PETSC_OWN_POINTER));

6474:   /* Send the remote COOs to their owner */
6475:   PetscInt    n2 = nroots, *i2, *j2; /* Buffers for received COOs from other ranks, along with a permutation array */
6476:   PetscCount *perm2;                 /* Though PetscInt is enough for remote entries, we use PetscCount here as we want to reuse MatSplitEntries_Internal() */
6477:   PetscCall(PetscMalloc3(n2, &i2, n2, &j2, n2, &perm2));
6478:   PetscAssert(rem == 0 || i1 != NULL, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Cannot add nonzero offset to null");
6479:   PetscAssert(rem == 0 || j1 != NULL, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Cannot add nonzero offset to null");
6480:   PetscInt *i1prem = PetscSafePointerPlusOffset(i1, rem);
6481:   PetscInt *j1prem = PetscSafePointerPlusOffset(j1, rem);
6482:   PetscCall(PetscSFReduceWithMemTypeBegin(sf2, MPIU_INT, PETSC_MEMTYPE_HOST, i1prem, PETSC_MEMTYPE_HOST, i2, MPI_REPLACE));
6483:   PetscCall(PetscSFReduceEnd(sf2, MPIU_INT, i1prem, i2, MPI_REPLACE));
6484:   PetscCall(PetscSFReduceWithMemTypeBegin(sf2, MPIU_INT, PETSC_MEMTYPE_HOST, j1prem, PETSC_MEMTYPE_HOST, j2, MPI_REPLACE));
6485:   PetscCall(PetscSFReduceEnd(sf2, MPIU_INT, j1prem, j2, MPI_REPLACE));

6487:   PetscCall(PetscFree(offsets));
6488:   PetscCall(PetscFree2(sendto, nentries));

6490:   /* Sort received COOs by row along with the permutation array     */
6491:   for (k = 0; k < n2; k++) perm2[k] = k;
6492:   PetscCall(PetscSortIntWithIntCountArrayPair(n2, i2, j2, perm2));

6494:   /* sf2 only sends contiguous leafdata to contiguous rootdata. We record the permutation which will be used to fill leafdata */
6495:   PetscCount *Cperm1;
6496:   PetscAssert(rem == 0 || perm1 != NULL, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Cannot add nonzero offset to null");
6497:   PetscCount *perm1prem = PetscSafePointerPlusOffset(perm1, rem);
6498:   PetscCall(PetscMalloc1(nleaves, &Cperm1));
6499:   PetscCall(PetscArraycpy(Cperm1, perm1prem, nleaves));

6501:   /* Support for HYPRE matrices, kind of a hack.
6502:      Swap min column with diagonal so that diagonal values will go first */
6503:   PetscBool hypre;
6504:   PetscCall(PetscStrcmp("_internal_COO_mat_for_hypre", ((PetscObject)mat)->name, &hypre));
6505:   if (hypre) {
6506:     PetscInt *minj;
6507:     PetscBT   hasdiag;

6509:     PetscCall(PetscBTCreate(m, &hasdiag));
6510:     PetscCall(PetscMalloc1(m, &minj));
6511:     for (k = 0; k < m; k++) minj[k] = PETSC_INT_MAX;
6512:     for (k = i1start; k < rem; k++) {
6513:       if (j1[k] < cstart || j1[k] >= cend) continue;
6514:       const PetscInt rindex = i1[k] - rstart;
6515:       if ((j1[k] - cstart) == rindex) PetscCall(PetscBTSet(hasdiag, rindex));
6516:       minj[rindex] = PetscMin(minj[rindex], j1[k]);
6517:     }
6518:     for (k = 0; k < n2; k++) {
6519:       if (j2[k] < cstart || j2[k] >= cend) continue;
6520:       const PetscInt rindex = i2[k] - rstart;
6521:       if ((j2[k] - cstart) == rindex) PetscCall(PetscBTSet(hasdiag, rindex));
6522:       minj[rindex] = PetscMin(minj[rindex], j2[k]);
6523:     }
6524:     for (k = i1start; k < rem; k++) {
6525:       const PetscInt rindex = i1[k] - rstart;
6526:       if (j1[k] < cstart || j1[k] >= cend || !PetscBTLookup(hasdiag, rindex)) continue;
6527:       if (j1[k] == minj[rindex]) j1[k] = i1[k] + (cstart - rstart);
6528:       else if ((j1[k] - cstart) == rindex) j1[k] = minj[rindex];
6529:     }
6530:     for (k = 0; k < n2; k++) {
6531:       const PetscInt rindex = i2[k] - rstart;
6532:       if (j2[k] < cstart || j2[k] >= cend || !PetscBTLookup(hasdiag, rindex)) continue;
6533:       if (j2[k] == minj[rindex]) j2[k] = i2[k] + (cstart - rstart);
6534:       else if ((j2[k] - cstart) == rindex) j2[k] = minj[rindex];
6535:     }
6536:     PetscCall(PetscBTDestroy(&hasdiag));
6537:     PetscCall(PetscFree(minj));
6538:   }

6540:   /* Split local COOs and received COOs into diag/offdiag portions */
6541:   PetscCount *rowBegin1, *rowMid1, *rowEnd1;
6542:   PetscCount *Ajmap1, *Aperm1, *Bjmap1, *Bperm1;
6543:   PetscCount  Annz1, Bnnz1, Atot1, Btot1;
6544:   PetscCount *rowBegin2, *rowMid2, *rowEnd2;
6545:   PetscCount *Ajmap2, *Aperm2, *Bjmap2, *Bperm2;
6546:   PetscCount  Annz2, Bnnz2, Atot2, Btot2;

6548:   PetscCall(PetscCalloc3(m, &rowBegin1, m, &rowMid1, m, &rowEnd1));
6549:   PetscCall(PetscCalloc3(m, &rowBegin2, m, &rowMid2, m, &rowEnd2));
6550:   PetscCall(MatSplitEntries_Internal(mat, rem, i1, j1, perm1, rowBegin1, rowMid1, rowEnd1, &Atot1, &Aperm1, &Annz1, &Ajmap1, &Btot1, &Bperm1, &Bnnz1, &Bjmap1));
6551:   PetscCall(MatSplitEntries_Internal(mat, n2, i2, j2, perm2, rowBegin2, rowMid2, rowEnd2, &Atot2, &Aperm2, &Annz2, &Ajmap2, &Btot2, &Bperm2, &Bnnz2, &Bjmap2));

6553:   /* Merge local COOs with received COOs: diag with diag, offdiag with offdiag */
6554:   PetscInt *Ai, *Bi;
6555:   PetscInt *Aj, *Bj;

6557:   PetscCall(PetscMalloc1(m + 1, &Ai));
6558:   PetscCall(PetscMalloc1(m + 1, &Bi));
6559:   PetscCall(PetscMalloc1(Annz1 + Annz2, &Aj)); /* Since local and remote entries might have dups, we might allocate excess memory */
6560:   PetscCall(PetscMalloc1(Bnnz1 + Bnnz2, &Bj));

6562:   PetscCount *Aimap1, *Bimap1, *Aimap2, *Bimap2;
6563:   PetscCall(PetscMalloc1(Annz1, &Aimap1));
6564:   PetscCall(PetscMalloc1(Bnnz1, &Bimap1));
6565:   PetscCall(PetscMalloc1(Annz2, &Aimap2));
6566:   PetscCall(PetscMalloc1(Bnnz2, &Bimap2));

6568:   PetscCall(MatMergeEntries_Internal(mat, j1, j2, rowBegin1, rowMid1, rowBegin2, rowMid2, Ajmap1, Ajmap2, Aimap1, Aimap2, Ai, Aj));
6569:   PetscCall(MatMergeEntries_Internal(mat, j1, j2, rowMid1, rowEnd1, rowMid2, rowEnd2, Bjmap1, Bjmap2, Bimap1, Bimap2, Bi, Bj));

6571:   /* Expand Ajmap1/Bjmap1 to make them based off nonzeros in A/B, since we     */
6572:   /* expect nonzeros in A/B most likely have local contributing entries        */
6573:   PetscInt    Annz = Ai[m];
6574:   PetscInt    Bnnz = Bi[m];
6575:   PetscCount *Ajmap1_new, *Bjmap1_new;

6577:   PetscCall(PetscMalloc1(Annz + 1, &Ajmap1_new));
6578:   PetscCall(PetscMalloc1(Bnnz + 1, &Bjmap1_new));

6580:   PetscCall(ExpandJmap_Internal(Annz1, Annz, Aimap1, Ajmap1, Ajmap1_new));
6581:   PetscCall(ExpandJmap_Internal(Bnnz1, Bnnz, Bimap1, Bjmap1, Bjmap1_new));

6583:   PetscCall(PetscFree(Aimap1));
6584:   PetscCall(PetscFree(Ajmap1));
6585:   PetscCall(PetscFree(Bimap1));
6586:   PetscCall(PetscFree(Bjmap1));
6587:   PetscCall(PetscFree3(rowBegin1, rowMid1, rowEnd1));
6588:   PetscCall(PetscFree3(rowBegin2, rowMid2, rowEnd2));
6589:   PetscCall(PetscFree(perm1));
6590:   PetscCall(PetscFree3(i2, j2, perm2));

6592:   Ajmap1 = Ajmap1_new;
6593:   Bjmap1 = Bjmap1_new;

6595:   /* Reallocate Aj, Bj once we know actual numbers of unique nonzeros in A and B */
6596:   if (Annz < Annz1 + Annz2) {
6597:     PetscInt *Aj_new;
6598:     PetscCall(PetscMalloc1(Annz, &Aj_new));
6599:     PetscCall(PetscArraycpy(Aj_new, Aj, Annz));
6600:     PetscCall(PetscFree(Aj));
6601:     Aj = Aj_new;
6602:   }

6604:   if (Bnnz < Bnnz1 + Bnnz2) {
6605:     PetscInt *Bj_new;
6606:     PetscCall(PetscMalloc1(Bnnz, &Bj_new));
6607:     PetscCall(PetscArraycpy(Bj_new, Bj, Bnnz));
6608:     PetscCall(PetscFree(Bj));
6609:     Bj = Bj_new;
6610:   }

6612:   /* Create new submatrices for on-process and off-process coupling                  */
6613:   PetscScalar     *Aa, *Ba;
6614:   MatType          rtype;
6615:   Mat_SeqAIJ      *a, *b;
6616:   PetscObjectState state;
6617:   PetscCall(PetscCalloc1(Annz, &Aa)); /* Zero matrix on device */
6618:   PetscCall(PetscCalloc1(Bnnz, &Ba));
6619:   /* make Aj[] local, i.e, based off the start column of the diagonal portion */
6620:   if (cstart) {
6621:     for (k = 0; k < Annz; k++) Aj[k] -= cstart;
6622:   }

6624:   PetscCall(MatGetRootType_Private(mat, &rtype));

6626:   MatSeqXAIJGetOptions_Private(mpiaij->A);
6627:   PetscCall(MatDestroy(&mpiaij->A));
6628:   PetscCall(MatCreateSeqAIJWithArrays(PETSC_COMM_SELF, m, n, Ai, Aj, Aa, &mpiaij->A));
6629:   PetscCall(MatSetBlockSizesFromMats(mpiaij->A, mat, mat));
6630:   MatSeqXAIJRestoreOptions_Private(mpiaij->A);

6632:   MatSeqXAIJGetOptions_Private(mpiaij->B);
6633:   PetscCall(MatDestroy(&mpiaij->B));
6634:   PetscCall(MatCreateSeqAIJWithArrays(PETSC_COMM_SELF, m, mat->cmap->N, Bi, Bj, Ba, &mpiaij->B));
6635:   PetscCall(MatSetBlockSizesFromMats(mpiaij->B, mat, mat));
6636:   MatSeqXAIJRestoreOptions_Private(mpiaij->B);

6638:   PetscCall(MatSetUpMultiply_MPIAIJ(mat));
6639:   mat->was_assembled = PETSC_TRUE; // was_assembled in effect means the Mvctx is built; doing so avoids redundant MatSetUpMultiply_MPIAIJ
6640:   state              = mpiaij->A->nonzerostate + mpiaij->B->nonzerostate;
6641:   PetscCallMPI(MPIU_Allreduce(&state, &mat->nonzerostate, 1, MPIU_INT64, MPI_SUM, PetscObjectComm((PetscObject)mat)));

6643:   a          = (Mat_SeqAIJ *)mpiaij->A->data;
6644:   b          = (Mat_SeqAIJ *)mpiaij->B->data;
6645:   a->free_a  = PETSC_TRUE;
6646:   a->free_ij = PETSC_TRUE;
6647:   b->free_a  = PETSC_TRUE;
6648:   b->free_ij = PETSC_TRUE;
6649:   a->maxnz   = a->nz;
6650:   b->maxnz   = b->nz;

6652:   /* conversion must happen AFTER multiply setup */
6653:   PetscCall(MatConvert(mpiaij->A, rtype, MAT_INPLACE_MATRIX, &mpiaij->A));
6654:   PetscCall(MatConvert(mpiaij->B, rtype, MAT_INPLACE_MATRIX, &mpiaij->B));
6655:   PetscCall(VecDestroy(&mpiaij->lvec));
6656:   PetscCall(MatCreateVecs(mpiaij->B, &mpiaij->lvec, NULL));

6658:   // Put the COO struct in a container and then attach that to the matrix
6659:   PetscCall(PetscMalloc1(1, &coo));
6660:   coo->n       = coo_n;
6661:   coo->sf      = sf2;
6662:   coo->sendlen = nleaves;
6663:   coo->recvlen = nroots;
6664:   coo->Annz    = Annz;
6665:   coo->Bnnz    = Bnnz;
6666:   coo->Annz2   = Annz2;
6667:   coo->Bnnz2   = Bnnz2;
6668:   coo->Atot1   = Atot1;
6669:   coo->Atot2   = Atot2;
6670:   coo->Btot1   = Btot1;
6671:   coo->Btot2   = Btot2;
6672:   coo->Ajmap1  = Ajmap1;
6673:   coo->Aperm1  = Aperm1;
6674:   coo->Bjmap1  = Bjmap1;
6675:   coo->Bperm1  = Bperm1;
6676:   coo->Aimap2  = Aimap2;
6677:   coo->Ajmap2  = Ajmap2;
6678:   coo->Aperm2  = Aperm2;
6679:   coo->Bimap2  = Bimap2;
6680:   coo->Bjmap2  = Bjmap2;
6681:   coo->Bperm2  = Bperm2;
6682:   coo->Cperm1  = Cperm1;
6683:   // Allocate in preallocation. If not used, it has zero cost on host
6684:   PetscCall(PetscMalloc2(coo->sendlen, &coo->sendbuf, coo->recvlen, &coo->recvbuf));
6685:   PetscCall(PetscContainerCreate(PETSC_COMM_SELF, &container));
6686:   PetscCall(PetscContainerSetPointer(container, coo));
6687:   PetscCall(PetscContainerSetCtxDestroy(container, MatCOOStructDestroy_MPIAIJ));
6688:   PetscCall(PetscObjectCompose((PetscObject)mat, "__PETSc_MatCOOStruct_Host", (PetscObject)container));
6689:   PetscCall(PetscContainerDestroy(&container));
6690:   PetscFunctionReturn(PETSC_SUCCESS);
6691: }

6693: static PetscErrorCode MatSetValuesCOO_MPIAIJ(Mat mat, const PetscScalar v[], InsertMode imode)
6694: {
6695:   Mat_MPIAIJ          *mpiaij = (Mat_MPIAIJ *)mat->data;
6696:   Mat                  A = mpiaij->A, B = mpiaij->B;
6697:   PetscScalar         *Aa, *Ba;
6698:   PetscScalar         *sendbuf, *recvbuf;
6699:   const PetscCount    *Ajmap1, *Ajmap2, *Aimap2;
6700:   const PetscCount    *Bjmap1, *Bjmap2, *Bimap2;
6701:   const PetscCount    *Aperm1, *Aperm2, *Bperm1, *Bperm2;
6702:   const PetscCount    *Cperm1;
6703:   PetscContainer       container;
6704:   MatCOOStruct_MPIAIJ *coo;

6706:   PetscFunctionBegin;
6707:   PetscCall(PetscObjectQuery((PetscObject)mat, "__PETSc_MatCOOStruct_Host", (PetscObject *)&container));
6708:   PetscCheck(container, PetscObjectComm((PetscObject)mat), PETSC_ERR_PLIB, "Not found MatCOOStruct on this matrix");
6709:   PetscCall(PetscContainerGetPointer(container, &coo));
6710:   sendbuf = coo->sendbuf;
6711:   recvbuf = coo->recvbuf;
6712:   Ajmap1  = coo->Ajmap1;
6713:   Ajmap2  = coo->Ajmap2;
6714:   Aimap2  = coo->Aimap2;
6715:   Bjmap1  = coo->Bjmap1;
6716:   Bjmap2  = coo->Bjmap2;
6717:   Bimap2  = coo->Bimap2;
6718:   Aperm1  = coo->Aperm1;
6719:   Aperm2  = coo->Aperm2;
6720:   Bperm1  = coo->Bperm1;
6721:   Bperm2  = coo->Bperm2;
6722:   Cperm1  = coo->Cperm1;

6724:   PetscCall(MatSeqAIJGetArray(A, &Aa)); /* Might read and write matrix values */
6725:   PetscCall(MatSeqAIJGetArray(B, &Ba));

6727:   /* Pack entries to be sent to remote */
6728:   for (PetscCount i = 0; i < coo->sendlen; i++) sendbuf[i] = v[Cperm1[i]];

6730:   /* Send remote entries to their owner and overlap the communication with local computation */
6731:   PetscCall(PetscSFReduceWithMemTypeBegin(coo->sf, MPIU_SCALAR, PETSC_MEMTYPE_HOST, sendbuf, PETSC_MEMTYPE_HOST, recvbuf, MPI_REPLACE));
6732:   /* Add local entries to A and B */
6733:   for (PetscCount i = 0; i < coo->Annz; i++) { /* All nonzeros in A are either zero'ed or added with a value (i.e., initialized) */
6734:     PetscScalar sum = 0.0;                     /* Do partial summation first to improve numerical stability */
6735:     for (PetscCount k = Ajmap1[i]; k < Ajmap1[i + 1]; k++) sum += v[Aperm1[k]];
6736:     Aa[i] = (imode == INSERT_VALUES ? 0.0 : Aa[i]) + sum;
6737:   }
6738:   for (PetscCount i = 0; i < coo->Bnnz; i++) {
6739:     PetscScalar sum = 0.0;
6740:     for (PetscCount k = Bjmap1[i]; k < Bjmap1[i + 1]; k++) sum += v[Bperm1[k]];
6741:     Ba[i] = (imode == INSERT_VALUES ? 0.0 : Ba[i]) + sum;
6742:   }
6743:   PetscCall(PetscSFReduceEnd(coo->sf, MPIU_SCALAR, sendbuf, recvbuf, MPI_REPLACE));

6745:   /* Add received remote entries to A and B */
6746:   for (PetscCount i = 0; i < coo->Annz2; i++) {
6747:     for (PetscCount k = Ajmap2[i]; k < Ajmap2[i + 1]; k++) Aa[Aimap2[i]] += recvbuf[Aperm2[k]];
6748:   }
6749:   for (PetscCount i = 0; i < coo->Bnnz2; i++) {
6750:     for (PetscCount k = Bjmap2[i]; k < Bjmap2[i + 1]; k++) Ba[Bimap2[i]] += recvbuf[Bperm2[k]];
6751:   }
6752:   PetscCall(MatSeqAIJRestoreArray(A, &Aa));
6753:   PetscCall(MatSeqAIJRestoreArray(B, &Ba));
6754:   PetscFunctionReturn(PETSC_SUCCESS);
6755: }

6757: /*MC
6758:    MATMPIAIJ - MATMPIAIJ = "mpiaij" - A matrix type to be used for parallel sparse matrices.

6760:    Options Database Keys:
6761: . -mat_type mpiaij - sets the matrix type to `MATMPIAIJ` during a call to `MatSetFromOptions()`

6763:    Level: beginner

6765:    Notes:
6766:    `MatSetValues()` may be called for this matrix type with a `NULL` argument for the numerical values,
6767:     in this case the values associated with the rows and columns one passes in are set to zero
6768:     in the matrix

6770:     `MatSetOptions`(,`MAT_STRUCTURE_ONLY`,`PETSC_TRUE`) may be called for this matrix type. In this no
6771:     space is allocated for the nonzero entries and any entries passed with `MatSetValues()` are ignored

6773: .seealso: [](ch_matrices), `Mat`, `MATSEQAIJ`, `MATAIJ`, `MatCreateAIJ()`
6774: M*/
6775: PETSC_EXTERN PetscErrorCode MatCreate_MPIAIJ(Mat B)
6776: {
6777:   Mat_MPIAIJ *b;
6778:   PetscMPIInt size;

6780:   PetscFunctionBegin;
6781:   PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)B), &size));

6783:   PetscCall(PetscNew(&b));
6784:   B->data       = (void *)b;
6785:   B->ops[0]     = MatOps_Values;
6786:   B->assembled  = PETSC_FALSE;
6787:   B->insertmode = NOT_SET_VALUES;
6788:   b->size       = size;

6790:   PetscCallMPI(MPI_Comm_rank(PetscObjectComm((PetscObject)B), &b->rank));

6792:   /* build cache for off array entries formed */
6793:   PetscCall(MatStashCreate_Private(PetscObjectComm((PetscObject)B), 1, &B->stash));

6795:   b->donotstash  = PETSC_FALSE;
6796:   b->colmap      = NULL;
6797:   b->garray      = NULL;
6798:   b->roworiented = PETSC_TRUE;

6800:   /* stuff used for matrix vector multiply */
6801:   b->lvec  = NULL;
6802:   b->Mvctx = NULL;

6804:   /* stuff for MatGetRow() */
6805:   b->rowindices   = NULL;
6806:   b->rowvalues    = NULL;
6807:   b->getrowactive = PETSC_FALSE;

6809:   /* flexible pointer used in CUSPARSE classes */
6810:   b->spptr = NULL;

6812:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatMPIAIJSetUseScalableIncreaseOverlap_C", MatMPIAIJSetUseScalableIncreaseOverlap_MPIAIJ));
6813:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatStoreValues_C", MatStoreValues_MPIAIJ));
6814:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatRetrieveValues_C", MatRetrieveValues_MPIAIJ));
6815:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatIsTranspose_C", MatIsTranspose_MPIAIJ));
6816:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatMPIAIJSetPreallocation_C", MatMPIAIJSetPreallocation_MPIAIJ));
6817:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatResetPreallocation_C", MatResetPreallocation_MPIAIJ));
6818:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatResetHash_C", MatResetHash_MPIAIJ));
6819:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatMPIAIJSetPreallocationCSR_C", MatMPIAIJSetPreallocationCSR_MPIAIJ));
6820:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatDiagonalScaleLocal_C", MatDiagonalScaleLocal_MPIAIJ));
6821:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatConvert_mpiaij_mpiaijperm_C", MatConvert_MPIAIJ_MPIAIJPERM));
6822:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatConvert_mpiaij_mpiaijsell_C", MatConvert_MPIAIJ_MPIAIJSELL));
6823: #if defined(PETSC_HAVE_CUDA)
6824:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatConvert_mpiaij_mpiaijcusparse_C", MatConvert_MPIAIJ_MPIAIJCUSPARSE));
6825: #endif
6826: #if defined(PETSC_HAVE_HIP)
6827:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatConvert_mpiaij_mpiaijhipsparse_C", MatConvert_MPIAIJ_MPIAIJHIPSPARSE));
6828: #endif
6829: #if defined(PETSC_HAVE_KOKKOS_KERNELS)
6830:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatConvert_mpiaij_mpiaijkokkos_C", MatConvert_MPIAIJ_MPIAIJKokkos));
6831: #endif
6832: #if defined(PETSC_HAVE_MKL_SPARSE)
6833:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatConvert_mpiaij_mpiaijmkl_C", MatConvert_MPIAIJ_MPIAIJMKL));
6834: #endif
6835:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatConvert_mpiaij_mpiaijcrl_C", MatConvert_MPIAIJ_MPIAIJCRL));
6836:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatConvert_mpiaij_mpibaij_C", MatConvert_MPIAIJ_MPIBAIJ));
6837:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatConvert_mpiaij_mpisbaij_C", MatConvert_MPIAIJ_MPISBAIJ));
6838:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatConvert_mpiaij_mpidense_C", MatConvert_MPIAIJ_MPIDense));
6839: #if defined(PETSC_HAVE_ELEMENTAL)
6840:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatConvert_mpiaij_elemental_C", MatConvert_MPIAIJ_Elemental));
6841: #endif
6842: #if defined(PETSC_HAVE_SCALAPACK) && (defined(PETSC_USE_REAL_SINGLE) || defined(PETSC_USE_REAL_DOUBLE))
6843:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatConvert_mpiaij_scalapack_C", MatConvert_AIJ_ScaLAPACK));
6844: #endif
6845:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatConvert_mpiaij_is_C", MatConvert_XAIJ_IS));
6846:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatConvert_mpiaij_mpisell_C", MatConvert_MPIAIJ_MPISELL));
6847: #if defined(PETSC_HAVE_HYPRE)
6848:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatConvert_mpiaij_hypre_C", MatConvert_AIJ_HYPRE));
6849:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatProductSetFromOptions_transpose_mpiaij_mpiaij_C", MatProductSetFromOptions_Transpose_AIJ_AIJ));
6850: #endif
6851:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatProductSetFromOptions_is_mpiaij_C", MatProductSetFromOptions_IS_XAIJ));
6852:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatProductSetFromOptions_mpiaij_mpiaij_C", MatProductSetFromOptions_MPIAIJ));
6853:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatSetPreallocationCOO_C", MatSetPreallocationCOO_MPIAIJ));
6854:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatSetValuesCOO_C", MatSetValuesCOO_MPIAIJ));
6855:   PetscCall(PetscObjectChangeTypeName((PetscObject)B, MATMPIAIJ));
6856:   PetscFunctionReturn(PETSC_SUCCESS);
6857: }

6859: /*@
6860:   MatCreateMPIAIJWithSplitArrays - creates a `MATMPIAIJ` matrix using arrays that contain the "diagonal"
6861:   and "off-diagonal" part of the matrix in CSR format.

6863:   Collective

6865:   Input Parameters:
6866: + comm - MPI communicator
6867: . m    - number of local rows (Cannot be `PETSC_DECIDE`)
6868: . n    - This value should be the same as the local size used in creating the
6869:          x vector for the matrix-vector product $y = Ax$. (or `PETSC_DECIDE` to have
6870:          calculated if `N` is given) For square matrices `n` is almost always `m`.
6871: . M    - number of global rows (or `PETSC_DETERMINE` to have calculated if `m` is given)
6872: . N    - number of global columns (or `PETSC_DETERMINE` to have calculated if `n` is given)
6873: . 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
6874: . j    - column indices, which must be local, i.e., based off the start column of the diagonal portion
6875: . a    - matrix values
6876: . 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
6877: . oj   - column indices, which must be global, representing global columns in the `MATMPIAIJ` matrix
6878: - oa   - matrix values

6880:   Output Parameter:
6881: . mat - the matrix

6883:   Level: advanced

6885:   Notes:
6886:   The `i`, `j`, and `a` arrays ARE NOT copied by this routine into the internal format used by PETSc (even in Fortran). The user
6887:   must free the arrays once the matrix has been destroyed and not before.

6889:   The `i` and `j` indices are 0 based

6891:   See `MatCreateAIJ()` for the definition of "diagonal" and "off-diagonal" portion of the matrix

6893:   This sets local rows and cannot be used to set off-processor values.

6895:   Use of this routine is discouraged because it is inflexible and cumbersome to use. It is extremely rare that a
6896:   legacy application natively assembles into exactly this split format. The code to do so is nontrivial and does
6897:   not easily support in-place reassembly. It is recommended to use MatSetValues() (or a variant thereof) because
6898:   the resulting assembly is easier to implement, will work with any matrix format, and the user does not have to
6899:   keep track of the underlying array. Use `MatSetOption`(A,`MAT_NO_OFF_PROC_ENTRIES`,`PETSC_TRUE`) to disable all
6900:   communication if it is known that only local entries will be set.

6902: .seealso: [](ch_matrices), `Mat`, `MatCreate()`, `MatCreateSeqAIJ()`, `MatSetValues()`, `MatMPIAIJSetPreallocation()`, `MatMPIAIJSetPreallocationCSR()`,
6903:           `MATMPIAIJ`, `MatCreateAIJ()`, `MatCreateMPIAIJWithArrays()`
6904: @*/
6905: 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)
6906: {
6907:   Mat_MPIAIJ *maij;

6909:   PetscFunctionBegin;
6910:   PetscCheck(m >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "local number of rows (m) cannot be PETSC_DECIDE, or negative");
6911:   PetscCheck(i[0] == 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "i (row indices) must start with 0");
6912:   PetscCheck(oi[0] == 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "oi (row indices) must start with 0");
6913:   PetscCall(MatCreate(comm, mat));
6914:   PetscCall(MatSetSizes(*mat, m, n, M, N));
6915:   PetscCall(MatSetType(*mat, MATMPIAIJ));
6916:   maij = (Mat_MPIAIJ *)(*mat)->data;

6918:   (*mat)->preallocated = PETSC_TRUE;

6920:   PetscCall(PetscLayoutSetUp((*mat)->rmap));
6921:   PetscCall(PetscLayoutSetUp((*mat)->cmap));

6923:   PetscCall(MatCreateSeqAIJWithArrays(PETSC_COMM_SELF, m, n, i, j, a, &maij->A));
6924:   PetscCall(MatCreateSeqAIJWithArrays(PETSC_COMM_SELF, m, (*mat)->cmap->N, oi, oj, oa, &maij->B));

6926:   PetscCall(MatSetOption(*mat, MAT_NO_OFF_PROC_ENTRIES, PETSC_TRUE));
6927:   PetscCall(MatAssemblyBegin(*mat, MAT_FINAL_ASSEMBLY));
6928:   PetscCall(MatAssemblyEnd(*mat, MAT_FINAL_ASSEMBLY));
6929:   PetscCall(MatSetOption(*mat, MAT_NO_OFF_PROC_ENTRIES, PETSC_FALSE));
6930:   PetscCall(MatSetOption(*mat, MAT_NEW_NONZERO_LOCATION_ERR, PETSC_TRUE));
6931:   PetscFunctionReturn(PETSC_SUCCESS);
6932: }

6934: typedef struct {
6935:   Mat       *mp;    /* intermediate products */
6936:   PetscBool *mptmp; /* is the intermediate product temporary ? */
6937:   PetscInt   cp;    /* number of intermediate products */

6939:   /* support for MatGetBrowsOfAoCols_MPIAIJ for P_oth */
6940:   PetscInt    *startsj_s, *startsj_r;
6941:   PetscScalar *bufa;
6942:   Mat          P_oth;

6944:   /* may take advantage of merging product->B */
6945:   Mat Bloc; /* B-local by merging diag and off-diag */

6947:   /* cusparse does not have support to split between symbolic and numeric phases.
6948:      When api_user is true, we don't need to update the numerical values
6949:      of the temporary storage */
6950:   PetscBool reusesym;

6952:   /* support for COO values insertion */
6953:   PetscScalar *coo_v, *coo_w; /* store on-process and off-process COO scalars, and used as MPI recv/send buffers respectively */
6954:   PetscInt   **own;           /* own[i] points to address of on-process COO indices for Mat mp[i] */
6955:   PetscInt   **off;           /* off[i] points to address of off-process COO indices for Mat mp[i] */
6956:   PetscBool    hasoffproc;    /* if true, have off-process values insertion (i.e. AtB or PtAP) */
6957:   PetscSF      sf;            /* used for non-local values insertion and memory malloc */
6958:   PetscMemType mtype;

6960:   /* customization */
6961:   PetscBool abmerge;
6962:   PetscBool P_oth_bind;
6963: } MatMatMPIAIJBACKEND;

6965: static PetscErrorCode MatProductCtxDestroy_MatMatMPIAIJBACKEND(PetscCtxRt data)
6966: {
6967:   MatMatMPIAIJBACKEND *mmdata = *(MatMatMPIAIJBACKEND **)data;
6968:   PetscInt             i;

6970:   PetscFunctionBegin;
6971:   PetscCall(PetscFree2(mmdata->startsj_s, mmdata->startsj_r));
6972:   PetscCall(PetscFree(mmdata->bufa));
6973:   PetscCall(PetscSFFree(mmdata->sf, mmdata->mtype, mmdata->coo_v));
6974:   PetscCall(PetscSFFree(mmdata->sf, mmdata->mtype, mmdata->coo_w));
6975:   PetscCall(MatDestroy(&mmdata->P_oth));
6976:   PetscCall(MatDestroy(&mmdata->Bloc));
6977:   PetscCall(PetscSFDestroy(&mmdata->sf));
6978:   for (i = 0; i < mmdata->cp; i++) PetscCall(MatDestroy(&mmdata->mp[i]));
6979:   PetscCall(PetscFree2(mmdata->mp, mmdata->mptmp));
6980:   PetscCall(PetscFree(mmdata->own[0]));
6981:   PetscCall(PetscFree(mmdata->own));
6982:   PetscCall(PetscFree(mmdata->off[0]));
6983:   PetscCall(PetscFree(mmdata->off));
6984:   PetscCall(PetscFree(mmdata));
6985:   PetscFunctionReturn(PETSC_SUCCESS);
6986: }

6988: /* Copy selected n entries with indices in idx[] of A to v[].
6989:    If idx is NULL, copy the whole data array of A to v[]
6990:  */
6991: static PetscErrorCode MatSeqAIJCopySubArray(Mat A, PetscInt n, const PetscInt idx[], PetscScalar v[])
6992: {
6993:   PetscErrorCode (*f)(Mat, PetscInt, const PetscInt[], PetscScalar[]);

6995:   PetscFunctionBegin;
6996:   PetscCall(PetscObjectQueryFunction((PetscObject)A, "MatSeqAIJCopySubArray_C", &f));
6997:   if (f) PetscCall((*f)(A, n, idx, v));
6998:   else {
6999:     const PetscScalar *vv;

7001:     PetscCall(MatSeqAIJGetArrayRead(A, &vv));
7002:     if (n && idx) {
7003:       PetscScalar    *w  = v;
7004:       const PetscInt *oi = idx;
7005:       PetscInt        j;

7007:       for (j = 0; j < n; j++) *w++ = vv[*oi++];
7008:     } else {
7009:       PetscCall(PetscArraycpy(v, vv, n));
7010:     }
7011:     PetscCall(MatSeqAIJRestoreArrayRead(A, &vv));
7012:   }
7013:   PetscFunctionReturn(PETSC_SUCCESS);
7014: }

7016: static PetscErrorCode MatProductNumeric_MPIAIJBACKEND(Mat C)
7017: {
7018:   MatMatMPIAIJBACKEND *mmdata;
7019:   PetscInt             i, n_d, n_o;

7021:   PetscFunctionBegin;
7022:   MatCheckProduct(C, 1);
7023:   PetscCheck(C->product->data, PetscObjectComm((PetscObject)C), PETSC_ERR_PLIB, "Product data empty");
7024:   mmdata = (MatMatMPIAIJBACKEND *)C->product->data;
7025:   if (!mmdata->reusesym) { /* update temporary matrices */
7026:     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));
7027:     if (mmdata->Bloc) PetscCall(MatMPIAIJGetLocalMatMerge(C->product->B, MAT_REUSE_MATRIX, NULL, &mmdata->Bloc));
7028:   }
7029:   mmdata->reusesym = PETSC_FALSE;

7031:   for (i = 0; i < mmdata->cp; i++) {
7032:     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]);
7033:     PetscCall((*mmdata->mp[i]->ops->productnumeric)(mmdata->mp[i]));
7034:   }
7035:   for (i = 0, n_d = 0, n_o = 0; i < mmdata->cp; i++) {
7036:     PetscInt noff;

7038:     PetscCall(PetscIntCast(mmdata->off[i + 1] - mmdata->off[i], &noff));
7039:     if (mmdata->mptmp[i]) continue;
7040:     if (noff) {
7041:       PetscInt nown;

7043:       PetscCall(PetscIntCast(mmdata->own[i + 1] - mmdata->own[i], &nown));
7044:       PetscCall(MatSeqAIJCopySubArray(mmdata->mp[i], noff, mmdata->off[i], mmdata->coo_w + n_o));
7045:       PetscCall(MatSeqAIJCopySubArray(mmdata->mp[i], nown, mmdata->own[i], mmdata->coo_v + n_d));
7046:       n_o += noff;
7047:       n_d += nown;
7048:     } else {
7049:       Mat_SeqAIJ *mm = (Mat_SeqAIJ *)mmdata->mp[i]->data;

7051:       PetscCall(MatSeqAIJCopySubArray(mmdata->mp[i], mm->nz, NULL, mmdata->coo_v + n_d));
7052:       n_d += mm->nz;
7053:     }
7054:   }
7055:   if (mmdata->hasoffproc) { /* offprocess insertion */
7056:     PetscCall(PetscSFGatherBegin(mmdata->sf, MPIU_SCALAR, mmdata->coo_w, mmdata->coo_v + n_d));
7057:     PetscCall(PetscSFGatherEnd(mmdata->sf, MPIU_SCALAR, mmdata->coo_w, mmdata->coo_v + n_d));
7058:   }
7059:   PetscCall(MatSetValuesCOO(C, mmdata->coo_v, INSERT_VALUES));
7060:   PetscFunctionReturn(PETSC_SUCCESS);
7061: }

7063: /* Support for Pt * A, A * P, or Pt * A * P */
7064: #define MAX_NUMBER_INTERMEDIATE 4
7065: PetscErrorCode MatProductSymbolic_MPIAIJBACKEND(Mat C)
7066: {
7067:   Mat_Product           *product = C->product;
7068:   Mat                    A, P, mp[MAX_NUMBER_INTERMEDIATE]; /* A, P and a series of intermediate matrices */
7069:   Mat_MPIAIJ            *a, *p;
7070:   MatMatMPIAIJBACKEND   *mmdata;
7071:   ISLocalToGlobalMapping P_oth_l2g = NULL;
7072:   IS                     glob      = NULL;
7073:   const char            *prefix;
7074:   char                   pprefix[256];
7075:   const PetscInt        *globidx, *P_oth_idx;
7076:   PetscInt               i, j, cp, m, n, M, N, *coo_i, *coo_j;
7077:   PetscCount             ncoo, ncoo_d, ncoo_o, ncoo_oown;
7078:   PetscInt               cmapt[MAX_NUMBER_INTERMEDIATE], rmapt[MAX_NUMBER_INTERMEDIATE]; /* col/row map type for each Mat in mp[]. */
7079:                                                                                          /* type-0: consecutive, start from 0; type-1: consecutive with */
7080:                                                                                          /* a base offset; type-2: sparse with a local to global map table */
7081:   const PetscInt *cmapa[MAX_NUMBER_INTERMEDIATE], *rmapa[MAX_NUMBER_INTERMEDIATE];       /* col/row local to global map array (table) for type-2 map type */

7083:   MatProductType ptype;
7084:   PetscBool      mptmp[MAX_NUMBER_INTERMEDIATE], hasoffproc = PETSC_FALSE, iscuda, iship, iskokk;
7085:   PetscMPIInt    size;

7087:   PetscFunctionBegin;
7088:   MatCheckProduct(C, 1);
7089:   PetscCheck(!product->data, PetscObjectComm((PetscObject)C), PETSC_ERR_PLIB, "Product data not empty");
7090:   ptype = product->type;
7091:   if (product->A->symmetric == PETSC_BOOL3_TRUE && ptype == MATPRODUCT_AtB) {
7092:     ptype                                          = MATPRODUCT_AB;
7093:     product->symbolic_used_the_fact_A_is_symmetric = PETSC_TRUE;
7094:   }
7095:   switch (ptype) {
7096:   case MATPRODUCT_AB:
7097:     A          = product->A;
7098:     P          = product->B;
7099:     m          = A->rmap->n;
7100:     n          = P->cmap->n;
7101:     M          = A->rmap->N;
7102:     N          = P->cmap->N;
7103:     hasoffproc = PETSC_FALSE; /* will not scatter mat product values to other processes */
7104:     break;
7105:   case MATPRODUCT_AtB:
7106:     P          = product->A;
7107:     A          = product->B;
7108:     m          = P->cmap->n;
7109:     n          = A->cmap->n;
7110:     M          = P->cmap->N;
7111:     N          = A->cmap->N;
7112:     hasoffproc = PETSC_TRUE;
7113:     break;
7114:   case MATPRODUCT_PtAP:
7115:     A          = product->A;
7116:     P          = product->B;
7117:     m          = P->cmap->n;
7118:     n          = P->cmap->n;
7119:     M          = P->cmap->N;
7120:     N          = P->cmap->N;
7121:     hasoffproc = PETSC_TRUE;
7122:     break;
7123:   default:
7124:     SETERRQ(PetscObjectComm((PetscObject)C), PETSC_ERR_PLIB, "Not for product type %s", MatProductTypes[ptype]);
7125:   }
7126:   PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)C), &size));
7127:   if (size == 1) hasoffproc = PETSC_FALSE;

7129:   /* defaults */
7130:   for (i = 0; i < MAX_NUMBER_INTERMEDIATE; i++) {
7131:     mp[i]    = NULL;
7132:     mptmp[i] = PETSC_FALSE;
7133:     rmapt[i] = -1;
7134:     cmapt[i] = -1;
7135:     rmapa[i] = NULL;
7136:     cmapa[i] = NULL;
7137:   }

7139:   /* customization */
7140:   PetscCall(PetscNew(&mmdata));
7141:   mmdata->reusesym = product->api_user;
7142:   if (ptype == MATPRODUCT_AB) {
7143:     if (product->api_user) {
7144:       PetscOptionsBegin(PetscObjectComm((PetscObject)C), ((PetscObject)C)->prefix, "MatMatMult", "Mat");
7145:       PetscCall(PetscOptionsBool("-matmatmult_backend_mergeB", "Merge product->B local matrices", "MatMatMult", mmdata->abmerge, &mmdata->abmerge, NULL));
7146:       PetscCall(PetscOptionsBool("-matmatmult_backend_pothbind", "Bind P_oth to CPU", "MatBindToCPU", mmdata->P_oth_bind, &mmdata->P_oth_bind, NULL));
7147:       PetscOptionsEnd();
7148:     } else {
7149:       PetscOptionsBegin(PetscObjectComm((PetscObject)C), ((PetscObject)C)->prefix, "MatProduct_AB", "Mat");
7150:       PetscCall(PetscOptionsBool("-mat_product_algorithm_backend_mergeB", "Merge product->B local matrices", "MatMatMult", mmdata->abmerge, &mmdata->abmerge, NULL));
7151:       PetscCall(PetscOptionsBool("-mat_product_algorithm_backend_pothbind", "Bind P_oth to CPU", "MatBindToCPU", mmdata->P_oth_bind, &mmdata->P_oth_bind, NULL));
7152:       PetscOptionsEnd();
7153:     }
7154:   } else if (ptype == MATPRODUCT_PtAP) {
7155:     if (product->api_user) {
7156:       PetscOptionsBegin(PetscObjectComm((PetscObject)C), ((PetscObject)C)->prefix, "MatPtAP", "Mat");
7157:       PetscCall(PetscOptionsBool("-matptap_backend_pothbind", "Bind P_oth to CPU", "MatBindToCPU", mmdata->P_oth_bind, &mmdata->P_oth_bind, NULL));
7158:       PetscOptionsEnd();
7159:     } else {
7160:       PetscOptionsBegin(PetscObjectComm((PetscObject)C), ((PetscObject)C)->prefix, "MatProduct_PtAP", "Mat");
7161:       PetscCall(PetscOptionsBool("-mat_product_algorithm_backend_pothbind", "Bind P_oth to CPU", "MatBindToCPU", mmdata->P_oth_bind, &mmdata->P_oth_bind, NULL));
7162:       PetscOptionsEnd();
7163:     }
7164:   }
7165:   a = (Mat_MPIAIJ *)A->data;
7166:   p = (Mat_MPIAIJ *)P->data;
7167:   PetscCall(MatSetSizes(C, m, n, M, N));
7168:   PetscCall(PetscLayoutSetUp(C->rmap));
7169:   PetscCall(PetscLayoutSetUp(C->cmap));
7170:   PetscCall(MatSetType(C, ((PetscObject)A)->type_name));
7171:   PetscCall(MatGetOptionsPrefix(C, &prefix));

7173:   cp = 0;
7174:   switch (ptype) {
7175:   case MATPRODUCT_AB: /* A * P */
7176:     PetscCall(MatGetBrowsOfAoCols_MPIAIJ(A, P, MAT_INITIAL_MATRIX, &mmdata->startsj_s, &mmdata->startsj_r, &mmdata->bufa, &mmdata->P_oth));

7178:     /* A_diag * P_local (merged or not) */
7179:     if (mmdata->abmerge) { /* P's diagonal and off-diag blocks are merged to one matrix, then multiplied by A_diag */
7180:       /* P is product->B */
7181:       PetscCall(MatMPIAIJGetLocalMatMerge(P, MAT_INITIAL_MATRIX, &glob, &mmdata->Bloc));
7182:       PetscCall(MatProductCreate(a->A, mmdata->Bloc, NULL, &mp[cp]));
7183:       PetscCall(MatProductSetType(mp[cp], MATPRODUCT_AB));
7184:       PetscCall(MatProductSetFill(mp[cp], product->fill));
7185:       PetscCall(PetscSNPrintf(pprefix, sizeof(pprefix), "backend_p%" PetscInt_FMT "_", cp));
7186:       PetscCall(MatSetOptionsPrefix(mp[cp], prefix));
7187:       PetscCall(MatAppendOptionsPrefix(mp[cp], pprefix));
7188:       mp[cp]->product->api_user = product->api_user;
7189:       PetscCall(MatProductSetFromOptions(mp[cp]));
7190:       PetscCall((*mp[cp]->ops->productsymbolic)(mp[cp]));
7191:       PetscCall(ISGetIndices(glob, &globidx));
7192:       rmapt[cp] = 1;
7193:       cmapt[cp] = 2;
7194:       cmapa[cp] = globidx;
7195:       mptmp[cp] = PETSC_FALSE;
7196:       cp++;
7197:     } else { /* A_diag * P_diag and A_diag * P_off */
7198:       PetscCall(MatProductCreate(a->A, p->A, NULL, &mp[cp]));
7199:       PetscCall(MatProductSetType(mp[cp], MATPRODUCT_AB));
7200:       PetscCall(MatProductSetFill(mp[cp], product->fill));
7201:       PetscCall(PetscSNPrintf(pprefix, sizeof(pprefix), "backend_p%" PetscInt_FMT "_", cp));
7202:       PetscCall(MatSetOptionsPrefix(mp[cp], prefix));
7203:       PetscCall(MatAppendOptionsPrefix(mp[cp], pprefix));
7204:       mp[cp]->product->api_user = product->api_user;
7205:       PetscCall(MatProductSetFromOptions(mp[cp]));
7206:       PetscCall((*mp[cp]->ops->productsymbolic)(mp[cp]));
7207:       rmapt[cp] = 1;
7208:       cmapt[cp] = 1;
7209:       mptmp[cp] = PETSC_FALSE;
7210:       cp++;
7211:       PetscCall(MatProductCreate(a->A, p->B, NULL, &mp[cp]));
7212:       PetscCall(MatProductSetType(mp[cp], MATPRODUCT_AB));
7213:       PetscCall(MatProductSetFill(mp[cp], product->fill));
7214:       PetscCall(PetscSNPrintf(pprefix, sizeof(pprefix), "backend_p%" PetscInt_FMT "_", cp));
7215:       PetscCall(MatSetOptionsPrefix(mp[cp], prefix));
7216:       PetscCall(MatAppendOptionsPrefix(mp[cp], pprefix));
7217:       mp[cp]->product->api_user = product->api_user;
7218:       PetscCall(MatProductSetFromOptions(mp[cp]));
7219:       PetscCall((*mp[cp]->ops->productsymbolic)(mp[cp]));
7220:       rmapt[cp] = 1;
7221:       cmapt[cp] = 2;
7222:       cmapa[cp] = p->garray;
7223:       mptmp[cp] = PETSC_FALSE;
7224:       cp++;
7225:     }

7227:     /* A_off * P_other */
7228:     if (mmdata->P_oth) {
7229:       PetscCall(MatSeqAIJCompactOutExtraColumns_SeqAIJ(mmdata->P_oth, &P_oth_l2g)); /* make P_oth use local col ids */
7230:       PetscCall(ISLocalToGlobalMappingGetIndices(P_oth_l2g, &P_oth_idx));
7231:       PetscCall(MatSetType(mmdata->P_oth, ((PetscObject)a->B)->type_name));
7232:       PetscCall(MatBindToCPU(mmdata->P_oth, mmdata->P_oth_bind));
7233:       PetscCall(MatProductCreate(a->B, mmdata->P_oth, NULL, &mp[cp]));
7234:       PetscCall(MatProductSetType(mp[cp], MATPRODUCT_AB));
7235:       PetscCall(MatProductSetFill(mp[cp], product->fill));
7236:       PetscCall(PetscSNPrintf(pprefix, sizeof(pprefix), "backend_p%" PetscInt_FMT "_", cp));
7237:       PetscCall(MatSetOptionsPrefix(mp[cp], prefix));
7238:       PetscCall(MatAppendOptionsPrefix(mp[cp], pprefix));
7239:       mp[cp]->product->api_user = product->api_user;
7240:       PetscCall(MatProductSetFromOptions(mp[cp]));
7241:       PetscCall((*mp[cp]->ops->productsymbolic)(mp[cp]));
7242:       rmapt[cp] = 1;
7243:       cmapt[cp] = 2;
7244:       cmapa[cp] = P_oth_idx;
7245:       mptmp[cp] = PETSC_FALSE;
7246:       cp++;
7247:     }
7248:     break;

7250:   case MATPRODUCT_AtB: /* (P^t * A): P_diag * A_loc + P_off * A_loc */
7251:     /* A is product->B */
7252:     PetscCall(MatMPIAIJGetLocalMatMerge(A, MAT_INITIAL_MATRIX, &glob, &mmdata->Bloc));
7253:     if (A == P) { /* when A==P, we can take advantage of the already merged mmdata->Bloc */
7254:       PetscCall(MatProductCreate(mmdata->Bloc, mmdata->Bloc, NULL, &mp[cp]));
7255:       PetscCall(MatProductSetType(mp[cp], MATPRODUCT_AtB));
7256:       PetscCall(MatProductSetFill(mp[cp], product->fill));
7257:       PetscCall(PetscSNPrintf(pprefix, sizeof(pprefix), "backend_p%" PetscInt_FMT "_", cp));
7258:       PetscCall(MatSetOptionsPrefix(mp[cp], prefix));
7259:       PetscCall(MatAppendOptionsPrefix(mp[cp], pprefix));
7260:       mp[cp]->product->api_user = product->api_user;
7261:       PetscCall(MatProductSetFromOptions(mp[cp]));
7262:       PetscCall((*mp[cp]->ops->productsymbolic)(mp[cp]));
7263:       PetscCall(ISGetIndices(glob, &globidx));
7264:       rmapt[cp] = 2;
7265:       rmapa[cp] = globidx;
7266:       cmapt[cp] = 2;
7267:       cmapa[cp] = globidx;
7268:       mptmp[cp] = PETSC_FALSE;
7269:       cp++;
7270:     } else {
7271:       PetscCall(MatProductCreate(p->A, mmdata->Bloc, NULL, &mp[cp]));
7272:       PetscCall(MatProductSetType(mp[cp], MATPRODUCT_AtB));
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:       PetscCall(ISGetIndices(glob, &globidx));
7281:       rmapt[cp] = 1;
7282:       cmapt[cp] = 2;
7283:       cmapa[cp] = globidx;
7284:       mptmp[cp] = PETSC_FALSE;
7285:       cp++;
7286:       PetscCall(MatProductCreate(p->B, mmdata->Bloc, NULL, &mp[cp]));
7287:       PetscCall(MatProductSetType(mp[cp], MATPRODUCT_AtB));
7288:       PetscCall(MatProductSetFill(mp[cp], product->fill));
7289:       PetscCall(PetscSNPrintf(pprefix, sizeof(pprefix), "backend_p%" PetscInt_FMT "_", cp));
7290:       PetscCall(MatSetOptionsPrefix(mp[cp], prefix));
7291:       PetscCall(MatAppendOptionsPrefix(mp[cp], pprefix));
7292:       mp[cp]->product->api_user = product->api_user;
7293:       PetscCall(MatProductSetFromOptions(mp[cp]));
7294:       PetscCall((*mp[cp]->ops->productsymbolic)(mp[cp]));
7295:       rmapt[cp] = 2;
7296:       rmapa[cp] = p->garray;
7297:       cmapt[cp] = 2;
7298:       cmapa[cp] = globidx;
7299:       mptmp[cp] = PETSC_FALSE;
7300:       cp++;
7301:     }
7302:     break;
7303:   case MATPRODUCT_PtAP:
7304:     PetscCall(MatGetBrowsOfAoCols_MPIAIJ(A, P, MAT_INITIAL_MATRIX, &mmdata->startsj_s, &mmdata->startsj_r, &mmdata->bufa, &mmdata->P_oth));
7305:     /* P is product->B */
7306:     PetscCall(MatMPIAIJGetLocalMatMerge(P, MAT_INITIAL_MATRIX, &glob, &mmdata->Bloc));
7307:     PetscCall(MatProductCreate(a->A, mmdata->Bloc, NULL, &mp[cp]));
7308:     PetscCall(MatProductSetType(mp[cp], MATPRODUCT_PtAP));
7309:     PetscCall(MatProductSetFill(mp[cp], product->fill));
7310:     PetscCall(PetscSNPrintf(pprefix, sizeof(pprefix), "backend_p%" PetscInt_FMT "_", cp));
7311:     PetscCall(MatSetOptionsPrefix(mp[cp], prefix));
7312:     PetscCall(MatAppendOptionsPrefix(mp[cp], pprefix));
7313:     mp[cp]->product->api_user = product->api_user;
7314:     PetscCall(MatProductSetFromOptions(mp[cp]));
7315:     PetscCall((*mp[cp]->ops->productsymbolic)(mp[cp]));
7316:     PetscCall(ISGetIndices(glob, &globidx));
7317:     rmapt[cp] = 2;
7318:     rmapa[cp] = globidx;
7319:     cmapt[cp] = 2;
7320:     cmapa[cp] = globidx;
7321:     mptmp[cp] = PETSC_FALSE;
7322:     cp++;
7323:     if (mmdata->P_oth) {
7324:       PetscCall(MatSeqAIJCompactOutExtraColumns_SeqAIJ(mmdata->P_oth, &P_oth_l2g));
7325:       PetscCall(ISLocalToGlobalMappingGetIndices(P_oth_l2g, &P_oth_idx));
7326:       PetscCall(MatSetType(mmdata->P_oth, ((PetscObject)a->B)->type_name));
7327:       PetscCall(MatBindToCPU(mmdata->P_oth, mmdata->P_oth_bind));
7328:       PetscCall(MatProductCreate(a->B, mmdata->P_oth, NULL, &mp[cp]));
7329:       PetscCall(MatProductSetType(mp[cp], MATPRODUCT_AB));
7330:       PetscCall(MatProductSetFill(mp[cp], product->fill));
7331:       PetscCall(PetscSNPrintf(pprefix, sizeof(pprefix), "backend_p%" PetscInt_FMT "_", cp));
7332:       PetscCall(MatSetOptionsPrefix(mp[cp], prefix));
7333:       PetscCall(MatAppendOptionsPrefix(mp[cp], pprefix));
7334:       mp[cp]->product->api_user = product->api_user;
7335:       PetscCall(MatProductSetFromOptions(mp[cp]));
7336:       PetscCall((*mp[cp]->ops->productsymbolic)(mp[cp]));
7337:       mptmp[cp] = PETSC_TRUE;
7338:       cp++;
7339:       PetscCall(MatProductCreate(mmdata->Bloc, mp[1], NULL, &mp[cp]));
7340:       PetscCall(MatProductSetType(mp[cp], MATPRODUCT_AtB));
7341:       PetscCall(MatProductSetFill(mp[cp], product->fill));
7342:       PetscCall(PetscSNPrintf(pprefix, sizeof(pprefix), "backend_p%" PetscInt_FMT "_", cp));
7343:       PetscCall(MatSetOptionsPrefix(mp[cp], prefix));
7344:       PetscCall(MatAppendOptionsPrefix(mp[cp], pprefix));
7345:       mp[cp]->product->api_user = product->api_user;
7346:       PetscCall(MatProductSetFromOptions(mp[cp]));
7347:       PetscCall((*mp[cp]->ops->productsymbolic)(mp[cp]));
7348:       rmapt[cp] = 2;
7349:       rmapa[cp] = globidx;
7350:       cmapt[cp] = 2;
7351:       cmapa[cp] = P_oth_idx;
7352:       mptmp[cp] = PETSC_FALSE;
7353:       cp++;
7354:     }
7355:     break;
7356:   default:
7357:     SETERRQ(PetscObjectComm((PetscObject)C), PETSC_ERR_PLIB, "Not for product type %s", MatProductTypes[ptype]);
7358:   }
7359:   /* sanity check */
7360:   if (size > 1)
7361:     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);

7363:   PetscCall(PetscMalloc2(cp, &mmdata->mp, cp, &mmdata->mptmp));
7364:   for (i = 0; i < cp; i++) {
7365:     mmdata->mp[i]    = mp[i];
7366:     mmdata->mptmp[i] = mptmp[i];
7367:   }
7368:   mmdata->cp             = cp;
7369:   C->product->data       = mmdata;
7370:   C->product->destroy    = MatProductCtxDestroy_MatMatMPIAIJBACKEND;
7371:   C->ops->productnumeric = MatProductNumeric_MPIAIJBACKEND;

7373:   /* memory type */
7374:   mmdata->mtype = PETSC_MEMTYPE_HOST;
7375:   PetscCall(PetscObjectTypeCompareAny((PetscObject)C, &iscuda, MATSEQAIJCUSPARSE, MATMPIAIJCUSPARSE, ""));
7376:   PetscCall(PetscObjectTypeCompareAny((PetscObject)C, &iship, MATSEQAIJHIPSPARSE, MATMPIAIJHIPSPARSE, ""));
7377:   PetscCall(PetscObjectTypeCompareAny((PetscObject)C, &iskokk, MATSEQAIJKOKKOS, MATMPIAIJKOKKOS, ""));
7378:   if (iscuda) mmdata->mtype = PETSC_MEMTYPE_CUDA;
7379:   else if (iship) mmdata->mtype = PETSC_MEMTYPE_HIP;
7380:   else if (iskokk) mmdata->mtype = PETSC_MEMTYPE_KOKKOS;

7382:   /* prepare coo coordinates for values insertion */

7384:   /* count total nonzeros of those intermediate seqaij Mats
7385:     ncoo_d:    # of nonzeros of matrices that do not have offproc entries
7386:     ncoo_o:    # of nonzeros (of matrices that might have offproc entries) that will be inserted to remote procs
7387:     ncoo_oown: # of nonzeros (of matrices that might have offproc entries) that will be inserted locally
7388:   */
7389:   for (cp = 0, ncoo_d = 0, ncoo_o = 0, ncoo_oown = 0; cp < mmdata->cp; cp++) {
7390:     Mat_SeqAIJ *mm = (Mat_SeqAIJ *)mp[cp]->data;
7391:     if (mptmp[cp]) continue;
7392:     if (rmapt[cp] == 2 && hasoffproc) { /* the rows need to be scatter to all processes (might include self) */
7393:       const PetscInt *rmap = rmapa[cp];
7394:       const PetscInt  mr   = mp[cp]->rmap->n;
7395:       const PetscInt  rs   = C->rmap->rstart;
7396:       const PetscInt  re   = C->rmap->rend;
7397:       const PetscInt *ii   = mm->i;
7398:       for (i = 0; i < mr; i++) {
7399:         const PetscInt gr = rmap[i];
7400:         const PetscInt nz = ii[i + 1] - ii[i];
7401:         if (gr < rs || gr >= re) ncoo_o += nz; /* this row is offproc */
7402:         else ncoo_oown += nz;                  /* this row is local */
7403:       }
7404:     } else ncoo_d += mm->nz;
7405:   }

7407:   /*
7408:     ncoo: total number of nonzeros (including those inserted by remote procs) belonging to this proc

7410:     ncoo = ncoo_d + ncoo_oown + ncoo2, which ncoo2 is number of nonzeros inserted to me by other procs.

7412:     off[0] points to a big index array, which is shared by off[1,2,...]. Similarly, for own[0].

7414:     off[p]: points to the segment for matrix mp[p], storing location of nonzeros that mp[p] will insert to others
7415:     own[p]: points to the segment for matrix mp[p], storing location of nonzeros that mp[p] will insert locally
7416:     so, off[p+1]-off[p] is the number of nonzeros that mp[p] will send to others.

7418:     coo_i/j/v[]: [ncoo] row/col/val of nonzeros belonging to this proc.
7419:     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.
7420:   */
7421:   PetscCall(PetscCalloc1(mmdata->cp + 1, &mmdata->off)); /* +1 to make a csr-like data structure */
7422:   PetscCall(PetscCalloc1(mmdata->cp + 1, &mmdata->own));

7424:   /* gather (i,j) of nonzeros inserted by remote procs */
7425:   if (hasoffproc) {
7426:     PetscSF  msf;
7427:     PetscInt ncoo2, *coo_i2, *coo_j2;

7429:     PetscCall(PetscMalloc1(ncoo_o, &mmdata->off[0]));
7430:     PetscCall(PetscMalloc1(ncoo_oown, &mmdata->own[0]));
7431:     PetscCall(PetscMalloc2(ncoo_o, &coo_i, ncoo_o, &coo_j)); /* to collect (i,j) of entries to be sent to others */

7433:     for (cp = 0, ncoo_o = 0; cp < mmdata->cp; cp++) {
7434:       Mat_SeqAIJ *mm     = (Mat_SeqAIJ *)mp[cp]->data;
7435:       PetscInt   *idxoff = mmdata->off[cp];
7436:       PetscInt   *idxown = mmdata->own[cp];
7437:       if (!mptmp[cp] && rmapt[cp] == 2) { /* row map is sparse */
7438:         const PetscInt *rmap = rmapa[cp];
7439:         const PetscInt *cmap = cmapa[cp];
7440:         const PetscInt *ii   = mm->i;
7441:         PetscInt       *coi  = coo_i + ncoo_o;
7442:         PetscInt       *coj  = coo_j + ncoo_o;
7443:         const PetscInt  mr   = mp[cp]->rmap->n;
7444:         const PetscInt  rs   = C->rmap->rstart;
7445:         const PetscInt  re   = C->rmap->rend;
7446:         const PetscInt  cs   = C->cmap->rstart;
7447:         for (i = 0; i < mr; i++) {
7448:           const PetscInt *jj = mm->j + ii[i];
7449:           const PetscInt  gr = rmap[i];
7450:           const PetscInt  nz = ii[i + 1] - ii[i];
7451:           if (gr < rs || gr >= re) { /* this is an offproc row */
7452:             for (j = ii[i]; j < ii[i + 1]; j++) {
7453:               *coi++    = gr;
7454:               *idxoff++ = j;
7455:             }
7456:             if (!cmapt[cp]) { /* already global */
7457:               for (j = 0; j < nz; j++) *coj++ = jj[j];
7458:             } else if (cmapt[cp] == 1) { /* local to global for owned columns of C */
7459:               for (j = 0; j < nz; j++) *coj++ = jj[j] + cs;
7460:             } else { /* offdiag */
7461:               for (j = 0; j < nz; j++) *coj++ = cmap[jj[j]];
7462:             }
7463:             ncoo_o += nz;
7464:           } else { /* this is a local row */
7465:             for (j = ii[i]; j < ii[i + 1]; j++) *idxown++ = j;
7466:           }
7467:         }
7468:       }
7469:       mmdata->off[cp + 1] = idxoff;
7470:       mmdata->own[cp + 1] = idxown;
7471:     }

7473:     PetscCall(PetscSFCreate(PetscObjectComm((PetscObject)C), &mmdata->sf));
7474:     PetscInt incoo_o;
7475:     PetscCall(PetscIntCast(ncoo_o, &incoo_o));
7476:     PetscCall(PetscSFSetGraphLayout(mmdata->sf, C->rmap, incoo_o /*nleaves*/, NULL /*ilocal*/, PETSC_OWN_POINTER, coo_i));
7477:     PetscCall(PetscSFGetMultiSF(mmdata->sf, &msf));
7478:     PetscCall(PetscSFGetGraph(msf, &ncoo2 /*nroots*/, NULL, NULL, NULL));
7479:     ncoo = ncoo_d + ncoo_oown + ncoo2;
7480:     PetscCall(PetscMalloc2(ncoo, &coo_i2, ncoo, &coo_j2));
7481:     PetscCall(PetscSFGatherBegin(mmdata->sf, MPIU_INT, coo_i, coo_i2 + ncoo_d + ncoo_oown)); /* put (i,j) of remote nonzeros at back */
7482:     PetscCall(PetscSFGatherEnd(mmdata->sf, MPIU_INT, coo_i, coo_i2 + ncoo_d + ncoo_oown));
7483:     PetscCall(PetscSFGatherBegin(mmdata->sf, MPIU_INT, coo_j, coo_j2 + ncoo_d + ncoo_oown));
7484:     PetscCall(PetscSFGatherEnd(mmdata->sf, MPIU_INT, coo_j, coo_j2 + ncoo_d + ncoo_oown));
7485:     PetscCall(PetscFree2(coo_i, coo_j));
7486:     /* allocate MPI send buffer to collect nonzero values to be sent to remote procs */
7487:     PetscCall(PetscSFMalloc(mmdata->sf, mmdata->mtype, ncoo_o * sizeof(PetscScalar), (void **)&mmdata->coo_w));
7488:     coo_i = coo_i2;
7489:     coo_j = coo_j2;
7490:   } else { /* no offproc values insertion */
7491:     ncoo = ncoo_d;
7492:     PetscCall(PetscMalloc2(ncoo, &coo_i, ncoo, &coo_j));

7494:     PetscCall(PetscSFCreate(PetscObjectComm((PetscObject)C), &mmdata->sf));
7495:     PetscCall(PetscSFSetGraph(mmdata->sf, 0, 0, NULL, PETSC_OWN_POINTER, NULL, PETSC_OWN_POINTER));
7496:     PetscCall(PetscSFSetUp(mmdata->sf));
7497:   }
7498:   mmdata->hasoffproc = hasoffproc;

7500:   /* gather (i,j) of nonzeros inserted locally */
7501:   for (cp = 0, ncoo_d = 0; cp < mmdata->cp; cp++) {
7502:     Mat_SeqAIJ     *mm   = (Mat_SeqAIJ *)mp[cp]->data;
7503:     PetscInt       *coi  = coo_i + ncoo_d;
7504:     PetscInt       *coj  = coo_j + ncoo_d;
7505:     const PetscInt *jj   = mm->j;
7506:     const PetscInt *ii   = mm->i;
7507:     const PetscInt *cmap = cmapa[cp];
7508:     const PetscInt *rmap = rmapa[cp];
7509:     const PetscInt  mr   = mp[cp]->rmap->n;
7510:     const PetscInt  rs   = C->rmap->rstart;
7511:     const PetscInt  re   = C->rmap->rend;
7512:     const PetscInt  cs   = C->cmap->rstart;

7514:     if (mptmp[cp]) continue;
7515:     if (rmapt[cp] == 1) { /* consecutive rows */
7516:       /* fill coo_i */
7517:       for (i = 0; i < mr; i++) {
7518:         const PetscInt gr = i + rs;
7519:         for (j = ii[i]; j < ii[i + 1]; j++) coi[j] = gr;
7520:       }
7521:       /* fill coo_j */
7522:       if (!cmapt[cp]) { /* type-0, already global */
7523:         PetscCall(PetscArraycpy(coj, jj, mm->nz));
7524:       } else if (cmapt[cp] == 1) {                        /* type-1, local to global for consecutive columns of C */
7525:         for (j = 0; j < mm->nz; j++) coj[j] = jj[j] + cs; /* lid + col start */
7526:       } else {                                            /* type-2, local to global for sparse columns */
7527:         for (j = 0; j < mm->nz; j++) coj[j] = cmap[jj[j]];
7528:       }
7529:       ncoo_d += mm->nz;
7530:     } else if (rmapt[cp] == 2) { /* sparse rows */
7531:       for (i = 0; i < mr; i++) {
7532:         const PetscInt *jj = mm->j + ii[i];
7533:         const PetscInt  gr = rmap[i];
7534:         const PetscInt  nz = ii[i + 1] - ii[i];
7535:         if (gr >= rs && gr < re) { /* local rows */
7536:           for (j = ii[i]; j < ii[i + 1]; j++) *coi++ = gr;
7537:           if (!cmapt[cp]) { /* type-0, already global */
7538:             for (j = 0; j < nz; j++) *coj++ = jj[j];
7539:           } else if (cmapt[cp] == 1) { /* local to global for owned columns of C */
7540:             for (j = 0; j < nz; j++) *coj++ = jj[j] + cs;
7541:           } else { /* type-2, local to global for sparse columns */
7542:             for (j = 0; j < nz; j++) *coj++ = cmap[jj[j]];
7543:           }
7544:           ncoo_d += nz;
7545:         }
7546:       }
7547:     }
7548:   }
7549:   if (glob) PetscCall(ISRestoreIndices(glob, &globidx));
7550:   PetscCall(ISDestroy(&glob));
7551:   if (P_oth_l2g) PetscCall(ISLocalToGlobalMappingRestoreIndices(P_oth_l2g, &P_oth_idx));
7552:   PetscCall(ISLocalToGlobalMappingDestroy(&P_oth_l2g));
7553:   /* allocate an array to store all nonzeros (inserted locally or remotely) belonging to this proc */
7554:   PetscCall(PetscSFMalloc(mmdata->sf, mmdata->mtype, ncoo * sizeof(PetscScalar), (void **)&mmdata->coo_v));

7556:   /* set block sizes */
7557:   A = product->A;
7558:   P = product->B;
7559:   switch (ptype) {
7560:   case MATPRODUCT_PtAP:
7561:     PetscCall(MatSetBlockSizes(C, P->cmap->bs, P->cmap->bs));
7562:     break;
7563:   case MATPRODUCT_RARt:
7564:     PetscCall(MatSetBlockSizes(C, P->rmap->bs, P->rmap->bs));
7565:     break;
7566:   case MATPRODUCT_ABC:
7567:     PetscCall(MatSetBlockSizesFromMats(C, A, product->C));
7568:     break;
7569:   case MATPRODUCT_AB:
7570:     PetscCall(MatSetBlockSizesFromMats(C, A, P));
7571:     break;
7572:   case MATPRODUCT_AtB:
7573:     PetscCall(MatSetBlockSizes(C, A->cmap->bs, P->cmap->bs));
7574:     break;
7575:   case MATPRODUCT_ABt:
7576:     PetscCall(MatSetBlockSizes(C, A->rmap->bs, P->rmap->bs));
7577:     break;
7578:   default:
7579:     SETERRQ(PetscObjectComm((PetscObject)C), PETSC_ERR_PLIB, "Not for ProductType %s", MatProductTypes[ptype]);
7580:   }

7582:   /* preallocate with COO data */
7583:   PetscCall(MatSetPreallocationCOO(C, ncoo, coo_i, coo_j));
7584:   PetscCall(PetscFree2(coo_i, coo_j));
7585:   PetscFunctionReturn(PETSC_SUCCESS);
7586: }

7588: PetscErrorCode MatProductSetFromOptions_MPIAIJBACKEND(Mat mat)
7589: {
7590:   Mat_Product *product = mat->product;
7591: #if defined(PETSC_HAVE_DEVICE)
7592:   PetscBool match  = PETSC_FALSE;
7593:   PetscBool usecpu = PETSC_FALSE;
7594: #else
7595:   PetscBool match = PETSC_TRUE;
7596: #endif

7598:   PetscFunctionBegin;
7599:   MatCheckProduct(mat, 1);
7600: #if defined(PETSC_HAVE_DEVICE)
7601:   if (!product->A->boundtocpu && !product->B->boundtocpu) PetscCall(PetscObjectTypeCompare((PetscObject)product->B, ((PetscObject)product->A)->type_name, &match));
7602:   if (match) { /* we can always fallback to the CPU if requested */
7603:     switch (product->type) {
7604:     case MATPRODUCT_AB:
7605:       if (product->api_user) {
7606:         PetscOptionsBegin(PetscObjectComm((PetscObject)mat), ((PetscObject)mat)->prefix, "MatMatMult", "Mat");
7607:         PetscCall(PetscOptionsBool("-matmatmult_backend_cpu", "Use CPU code", "MatMatMult", usecpu, &usecpu, NULL));
7608:         PetscOptionsEnd();
7609:       } else {
7610:         PetscOptionsBegin(PetscObjectComm((PetscObject)mat), ((PetscObject)mat)->prefix, "MatProduct_AB", "Mat");
7611:         PetscCall(PetscOptionsBool("-mat_product_algorithm_backend_cpu", "Use CPU code", "MatMatMult", usecpu, &usecpu, NULL));
7612:         PetscOptionsEnd();
7613:       }
7614:       break;
7615:     case MATPRODUCT_AtB:
7616:       if (product->api_user) {
7617:         PetscOptionsBegin(PetscObjectComm((PetscObject)mat), ((PetscObject)mat)->prefix, "MatTransposeMatMult", "Mat");
7618:         PetscCall(PetscOptionsBool("-mattransposematmult_backend_cpu", "Use CPU code", "MatTransposeMatMult", usecpu, &usecpu, NULL));
7619:         PetscOptionsEnd();
7620:       } else {
7621:         PetscOptionsBegin(PetscObjectComm((PetscObject)mat), ((PetscObject)mat)->prefix, "MatProduct_AtB", "Mat");
7622:         PetscCall(PetscOptionsBool("-mat_product_algorithm_backend_cpu", "Use CPU code", "MatTransposeMatMult", usecpu, &usecpu, NULL));
7623:         PetscOptionsEnd();
7624:       }
7625:       break;
7626:     case MATPRODUCT_PtAP:
7627:       if (product->api_user) {
7628:         PetscOptionsBegin(PetscObjectComm((PetscObject)mat), ((PetscObject)mat)->prefix, "MatPtAP", "Mat");
7629:         PetscCall(PetscOptionsBool("-matptap_backend_cpu", "Use CPU code", "MatPtAP", usecpu, &usecpu, NULL));
7630:         PetscOptionsEnd();
7631:       } else {
7632:         PetscOptionsBegin(PetscObjectComm((PetscObject)mat), ((PetscObject)mat)->prefix, "MatProduct_PtAP", "Mat");
7633:         PetscCall(PetscOptionsBool("-mat_product_algorithm_backend_cpu", "Use CPU code", "MatPtAP", usecpu, &usecpu, NULL));
7634:         PetscOptionsEnd();
7635:       }
7636:       break;
7637:     default:
7638:       break;
7639:     }
7640:     match = (PetscBool)!usecpu;
7641:   }
7642: #endif
7643:   if (match) {
7644:     switch (product->type) {
7645:     case MATPRODUCT_AB:
7646:     case MATPRODUCT_AtB:
7647:     case MATPRODUCT_PtAP:
7648:       mat->ops->productsymbolic = MatProductSymbolic_MPIAIJBACKEND;
7649:       break;
7650:     default:
7651:       break;
7652:     }
7653:   }
7654:   /* fallback to MPIAIJ ops */
7655:   if (!mat->ops->productsymbolic) PetscCall(MatProductSetFromOptions_MPIAIJ(mat));
7656:   PetscFunctionReturn(PETSC_SUCCESS);
7657: }

7659: /*
7660:    Produces a set of block column indices of the matrix row, one for each block represented in the original row

7662:    n - the number of block indices in cc[]
7663:    cc - the block indices (must be large enough to contain the indices)
7664: */
7665: static inline PetscErrorCode MatCollapseRow(Mat Amat, PetscInt row, PetscInt bs, PetscInt *n, PetscInt *cc)
7666: {
7667:   PetscInt        cnt = -1, nidx, j;
7668:   const PetscInt *idx;

7670:   PetscFunctionBegin;
7671:   PetscCall(MatGetRow(Amat, row, &nidx, &idx, NULL));
7672:   if (nidx) {
7673:     cnt     = 0;
7674:     cc[cnt] = idx[0] / bs;
7675:     for (j = 1; j < nidx; j++) {
7676:       if (cc[cnt] < idx[j] / bs) cc[++cnt] = idx[j] / bs;
7677:     }
7678:   }
7679:   PetscCall(MatRestoreRow(Amat, row, &nidx, &idx, NULL));
7680:   *n = cnt + 1;
7681:   PetscFunctionReturn(PETSC_SUCCESS);
7682: }

7684: /*
7685:     Produces a set of block column indices of the matrix block row, one for each block represented in the original set of rows

7687:     ncollapsed - the number of block indices
7688:     collapsed - the block indices (must be large enough to contain the indices)
7689: */
7690: static inline PetscErrorCode MatCollapseRows(Mat Amat, PetscInt start, PetscInt bs, PetscInt *w0, PetscInt *w1, PetscInt *w2, PetscInt *ncollapsed, PetscInt **collapsed)
7691: {
7692:   PetscInt i, nprev, *cprev = w0, ncur = 0, *ccur = w1, *merged = w2, *cprevtmp;

7694:   PetscFunctionBegin;
7695:   PetscCall(MatCollapseRow(Amat, start, bs, &nprev, cprev));
7696:   for (i = start + 1; i < start + bs; i++) {
7697:     PetscCall(MatCollapseRow(Amat, i, bs, &ncur, ccur));
7698:     PetscCall(PetscMergeIntArray(nprev, cprev, ncur, ccur, &nprev, &merged));
7699:     cprevtmp = cprev;
7700:     cprev    = merged;
7701:     merged   = cprevtmp;
7702:   }
7703:   *ncollapsed = nprev;
7704:   if (collapsed) *collapsed = cprev;
7705:   PetscFunctionReturn(PETSC_SUCCESS);
7706: }

7708: /*
7709:  MatCreateGraph_Simple_AIJ - create simple scalar matrix (graph) from potentially blocked matrix

7711:  Input Parameter:
7712:  . Amat - matrix
7713:  - symmetrize - make the result symmetric
7714:  + scale - scale with diagonal

7716:  Output Parameter:
7717:  . a_Gmat - output scalar graph >= 0

7719: */
7720: PETSC_INTERN PetscErrorCode MatCreateGraph_Simple_AIJ(Mat Amat, PetscBool symmetrize, PetscBool scale, PetscReal filter, PetscInt index_size, PetscInt index[], Mat *a_Gmat)
7721: {
7722:   PetscInt  Istart, Iend, Ii, jj, kk, ncols, nloc, NN, MM, bs;
7723:   MPI_Comm  comm;
7724:   Mat       Gmat;
7725:   PetscBool ismpiaij, isseqaij;
7726:   Mat       a, b, c;
7727:   MatType   jtype;

7729:   PetscFunctionBegin;
7730:   PetscCall(PetscObjectGetComm((PetscObject)Amat, &comm));
7731:   PetscCall(MatGetOwnershipRange(Amat, &Istart, &Iend));
7732:   PetscCall(MatGetSize(Amat, &MM, &NN));
7733:   PetscCall(MatGetBlockSize(Amat, &bs));
7734:   nloc = (Iend - Istart) / bs;

7736:   PetscCall(PetscObjectBaseTypeCompare((PetscObject)Amat, MATSEQAIJ, &isseqaij));
7737:   PetscCall(PetscObjectBaseTypeCompare((PetscObject)Amat, MATMPIAIJ, &ismpiaij));
7738:   PetscCheck(isseqaij || ismpiaij, comm, PETSC_ERR_USER, "Require (MPI)AIJ matrix type");

7740:   /* TODO GPU: these calls are potentially expensive if matrices are large and we want to use the GPU */
7741:   /* A solution consists in providing a new API, MatAIJGetCollapsedAIJ, and each class can provide a fast
7742:      implementation */
7743:   if (bs > 1) {
7744:     PetscCall(MatGetType(Amat, &jtype));
7745:     PetscCall(MatCreate(comm, &Gmat));
7746:     PetscCall(MatSetType(Gmat, jtype));
7747:     PetscCall(MatSetSizes(Gmat, nloc, nloc, PETSC_DETERMINE, PETSC_DETERMINE));
7748:     PetscCall(MatSetBlockSizes(Gmat, 1, 1));
7749:     if (isseqaij || ((Mat_MPIAIJ *)Amat->data)->garray) {
7750:       PetscInt  *d_nnz, *o_nnz;
7751:       MatScalar *aa, val, *AA;
7752:       PetscInt  *aj, *ai, *AJ, nc, nmax = 0;

7754:       if (isseqaij) {
7755:         a = Amat;
7756:         b = NULL;
7757:       } else {
7758:         Mat_MPIAIJ *d = (Mat_MPIAIJ *)Amat->data;
7759:         a             = d->A;
7760:         b             = d->B;
7761:       }
7762:       PetscCall(PetscInfo(Amat, "New bs>1 Graph. nloc=%" PetscInt_FMT "\n", nloc));
7763:       PetscCall(PetscMalloc2(nloc, &d_nnz, (isseqaij ? 0 : nloc), &o_nnz));
7764:       for (c = a, kk = 0; c && kk < 2; c = b, kk++) {
7765:         PetscInt       *nnz = (c == a) ? d_nnz : o_nnz;
7766:         const PetscInt *cols1, *cols2;

7768:         for (PetscInt brow = 0, nc1, nc2, ok = 1; brow < nloc * bs; brow += bs) { // block rows
7769:           PetscCall(MatGetRow(c, brow, &nc2, &cols2, NULL));
7770:           nnz[brow / bs] = nc2 / bs;
7771:           if (nc2 % bs) ok = 0;
7772:           if (nnz[brow / bs] > nmax) nmax = nnz[brow / bs];
7773:           for (PetscInt ii = 1; ii < bs; ii++) { // check for non-dense blocks
7774:             PetscCall(MatGetRow(c, brow + ii, &nc1, &cols1, NULL));
7775:             if (nc1 != nc2) ok = 0;
7776:             else {
7777:               for (PetscInt jj = 0; jj < nc1 && ok == 1; jj++) {
7778:                 if (cols1[jj] != cols2[jj]) ok = 0;
7779:                 if (cols1[jj] % bs != jj % bs) ok = 0;
7780:               }
7781:             }
7782:             PetscCall(MatRestoreRow(c, brow + ii, &nc1, &cols1, NULL));
7783:           }
7784:           PetscCall(MatRestoreRow(c, brow, &nc2, &cols2, NULL));
7785:           if (!ok) {
7786:             PetscCall(PetscFree2(d_nnz, o_nnz));
7787:             PetscCall(PetscInfo(Amat, "Found sparse blocks - revert to slow method\n"));
7788:             goto old_bs;
7789:           }
7790:         }
7791:       }
7792:       PetscCall(MatSeqAIJSetPreallocation(Gmat, 0, d_nnz));
7793:       PetscCall(MatMPIAIJSetPreallocation(Gmat, 0, d_nnz, 0, o_nnz));
7794:       PetscCall(PetscFree2(d_nnz, o_nnz));
7795:       PetscCall(PetscMalloc2(nmax, &AA, nmax, &AJ));
7796:       // diag
7797:       for (PetscInt brow = 0, n, grow; brow < nloc * bs; brow += bs) { // block rows
7798:         Mat_SeqAIJ *aseq = (Mat_SeqAIJ *)a->data;

7800:         ai = aseq->i;
7801:         n  = ai[brow + 1] - ai[brow];
7802:         aj = aseq->j + ai[brow];
7803:         for (PetscInt k = 0; k < n; k += bs) {   // block columns
7804:           AJ[k / bs] = aj[k] / bs + Istart / bs; // diag starts at (Istart,Istart)
7805:           val        = 0;
7806:           if (index_size == 0) {
7807:             for (PetscInt ii = 0; ii < bs; ii++) { // rows in block
7808:               aa = aseq->a + ai[brow + ii] + k;
7809:               for (PetscInt jj = 0; jj < bs; jj++) {    // columns in block
7810:                 val += PetscAbs(PetscRealPart(aa[jj])); // a sort of norm
7811:               }
7812:             }
7813:           } else {                                            // use (index,index) value if provided
7814:             for (PetscInt iii = 0; iii < index_size; iii++) { // rows in block
7815:               PetscInt ii = index[iii];
7816:               aa          = aseq->a + ai[brow + ii] + k;
7817:               for (PetscInt jjj = 0; jjj < index_size; jjj++) { // columns in block
7818:                 PetscInt jj = index[jjj];
7819:                 val += PetscAbs(PetscRealPart(aa[jj]));
7820:               }
7821:             }
7822:           }
7823:           PetscAssert(k / bs < nmax, comm, PETSC_ERR_USER, "k / bs (%" PetscInt_FMT ") >= nmax (%" PetscInt_FMT ")", k / bs, nmax);
7824:           AA[k / bs] = val;
7825:         }
7826:         grow = Istart / bs + brow / bs;
7827:         PetscCall(MatSetValues(Gmat, 1, &grow, n / bs, AJ, AA, ADD_VALUES));
7828:       }
7829:       // off-diag
7830:       if (ismpiaij) {
7831:         Mat_MPIAIJ        *aij = (Mat_MPIAIJ *)Amat->data;
7832:         const PetscScalar *vals;
7833:         const PetscInt    *cols, *garray = aij->garray;

7835:         PetscCheck(garray, PETSC_COMM_SELF, PETSC_ERR_USER, "No garray ?");
7836:         for (PetscInt brow = 0, grow; brow < nloc * bs; brow += bs) { // block rows
7837:           PetscCall(MatGetRow(b, brow, &ncols, &cols, NULL));
7838:           for (PetscInt k = 0, cidx = 0; k < ncols; k += bs, cidx++) {
7839:             PetscAssert(k / bs < nmax, comm, PETSC_ERR_USER, "k / bs >= nmax");
7840:             AA[k / bs] = 0;
7841:             AJ[cidx]   = garray[cols[k]] / bs;
7842:           }
7843:           nc = ncols / bs;
7844:           PetscCall(MatRestoreRow(b, brow, &ncols, &cols, NULL));
7845:           if (index_size == 0) {
7846:             for (PetscInt ii = 0; ii < bs; ii++) { // rows in block
7847:               PetscCall(MatGetRow(b, brow + ii, &ncols, &cols, &vals));
7848:               for (PetscInt k = 0; k < ncols; k += bs) {
7849:                 for (PetscInt jj = 0; jj < bs; jj++) { // cols in block
7850:                   PetscAssert(k / bs < nmax, comm, PETSC_ERR_USER, "k / bs (%" PetscInt_FMT ") >= nmax (%" PetscInt_FMT ")", k / bs, nmax);
7851:                   AA[k / bs] += PetscAbs(PetscRealPart(vals[k + jj]));
7852:                 }
7853:               }
7854:               PetscCall(MatRestoreRow(b, brow + ii, &ncols, &cols, &vals));
7855:             }
7856:           } else {                                            // use (index,index) value if provided
7857:             for (PetscInt iii = 0; iii < index_size; iii++) { // rows in block
7858:               PetscInt ii = index[iii];
7859:               PetscCall(MatGetRow(b, brow + ii, &ncols, &cols, &vals));
7860:               for (PetscInt k = 0; k < ncols; k += bs) {
7861:                 for (PetscInt jjj = 0; jjj < index_size; jjj++) { // cols in block
7862:                   PetscInt jj = index[jjj];
7863:                   AA[k / bs] += PetscAbs(PetscRealPart(vals[k + jj]));
7864:                 }
7865:               }
7866:               PetscCall(MatRestoreRow(b, brow + ii, &ncols, &cols, &vals));
7867:             }
7868:           }
7869:           grow = Istart / bs + brow / bs;
7870:           PetscCall(MatSetValues(Gmat, 1, &grow, nc, AJ, AA, ADD_VALUES));
7871:         }
7872:       }
7873:       PetscCall(MatAssemblyBegin(Gmat, MAT_FINAL_ASSEMBLY));
7874:       PetscCall(MatAssemblyEnd(Gmat, MAT_FINAL_ASSEMBLY));
7875:       PetscCall(PetscFree2(AA, AJ));
7876:     } else {
7877:       const PetscScalar *vals;
7878:       const PetscInt    *idx;
7879:       PetscInt          *d_nnz, *o_nnz, *w0, *w1, *w2;
7880:     old_bs:
7881:       /*
7882:        Determine the preallocation needed for the scalar matrix derived from the vector matrix.
7883:        */
7884:       PetscCall(PetscInfo(Amat, "OLD bs>1 CreateGraph\n"));
7885:       PetscCall(PetscMalloc2(nloc, &d_nnz, (isseqaij ? 0 : nloc), &o_nnz));
7886:       if (isseqaij) {
7887:         PetscInt max_d_nnz;

7889:         /*
7890:          Determine exact preallocation count for (sequential) scalar matrix
7891:          */
7892:         PetscCall(MatSeqAIJGetMaxRowNonzeros(Amat, &max_d_nnz));
7893:         max_d_nnz = PetscMin(nloc, bs * max_d_nnz);
7894:         PetscCall(PetscMalloc3(max_d_nnz, &w0, max_d_nnz, &w1, max_d_nnz, &w2));
7895:         for (Ii = 0, jj = 0; Ii < Iend; Ii += bs, jj++) PetscCall(MatCollapseRows(Amat, Ii, bs, w0, w1, w2, &d_nnz[jj], NULL));
7896:         PetscCall(PetscFree3(w0, w1, w2));
7897:       } else if (ismpiaij) {
7898:         Mat             Daij, Oaij;
7899:         const PetscInt *garray;
7900:         PetscInt        max_d_nnz;

7902:         PetscCall(MatMPIAIJGetSeqAIJ(Amat, &Daij, &Oaij, &garray));
7903:         /*
7904:          Determine exact preallocation count for diagonal block portion of scalar matrix
7905:          */
7906:         PetscCall(MatSeqAIJGetMaxRowNonzeros(Daij, &max_d_nnz));
7907:         max_d_nnz = PetscMin(nloc, bs * max_d_nnz);
7908:         PetscCall(PetscMalloc3(max_d_nnz, &w0, max_d_nnz, &w1, max_d_nnz, &w2));
7909:         for (Ii = 0, jj = 0; Ii < Iend - Istart; Ii += bs, jj++) PetscCall(MatCollapseRows(Daij, Ii, bs, w0, w1, w2, &d_nnz[jj], NULL));
7910:         PetscCall(PetscFree3(w0, w1, w2));
7911:         /*
7912:          Over estimate (usually grossly over), preallocation count for off-diagonal portion of scalar matrix
7913:          */
7914:         for (Ii = 0, jj = 0; Ii < Iend - Istart; Ii += bs, jj++) {
7915:           o_nnz[jj] = 0;
7916:           for (kk = 0; kk < bs; kk++) { /* rows that get collapsed to a single row */
7917:             PetscCall(MatGetRow(Oaij, Ii + kk, &ncols, NULL, NULL));
7918:             o_nnz[jj] += ncols;
7919:             PetscCall(MatRestoreRow(Oaij, Ii + kk, &ncols, NULL, NULL));
7920:           }
7921:           if (o_nnz[jj] > (NN / bs - nloc)) o_nnz[jj] = NN / bs - nloc;
7922:         }
7923:       } else SETERRQ(comm, PETSC_ERR_USER, "Require AIJ matrix type");
7924:       /* get scalar copy (norms) of matrix */
7925:       PetscCall(MatSeqAIJSetPreallocation(Gmat, 0, d_nnz));
7926:       PetscCall(MatMPIAIJSetPreallocation(Gmat, 0, d_nnz, 0, o_nnz));
7927:       PetscCall(PetscFree2(d_nnz, o_nnz));
7928:       for (Ii = Istart; Ii < Iend; Ii++) {
7929:         PetscInt dest_row = Ii / bs;

7931:         PetscCall(MatGetRow(Amat, Ii, &ncols, &idx, &vals));
7932:         for (jj = 0; jj < ncols; jj++) {
7933:           PetscInt    dest_col = idx[jj] / bs;
7934:           PetscScalar sv       = PetscAbs(PetscRealPart(vals[jj]));

7936:           PetscCall(MatSetValues(Gmat, 1, &dest_row, 1, &dest_col, &sv, ADD_VALUES));
7937:         }
7938:         PetscCall(MatRestoreRow(Amat, Ii, &ncols, &idx, &vals));
7939:       }
7940:       PetscCall(MatAssemblyBegin(Gmat, MAT_FINAL_ASSEMBLY));
7941:       PetscCall(MatAssemblyEnd(Gmat, MAT_FINAL_ASSEMBLY));
7942:     }
7943:   } else {
7944:     if (symmetrize || filter >= 0 || scale) PetscCall(MatDuplicate(Amat, MAT_COPY_VALUES, &Gmat));
7945:     else {
7946:       Gmat = Amat;
7947:       PetscCall(PetscObjectReference((PetscObject)Gmat));
7948:     }
7949:     if (isseqaij) {
7950:       a = Gmat;
7951:       b = NULL;
7952:     } else {
7953:       Mat_MPIAIJ *d = (Mat_MPIAIJ *)Gmat->data;
7954:       a             = d->A;
7955:       b             = d->B;
7956:     }
7957:     if (filter >= 0 || scale) {
7958:       /* take absolute value of each entry */
7959:       for (c = a, kk = 0; c && kk < 2; c = b, kk++) {
7960:         MatInfo      info;
7961:         PetscScalar *avals;

7963:         PetscCall(MatGetInfo(c, MAT_LOCAL, &info));
7964:         PetscCall(MatSeqAIJGetArray(c, &avals));
7965:         for (int jj = 0; jj < info.nz_used; jj++) avals[jj] = PetscAbsScalar(avals[jj]);
7966:         PetscCall(MatSeqAIJRestoreArray(c, &avals));
7967:       }
7968:     }
7969:   }
7970:   if (symmetrize) {
7971:     PetscBool isset, issym;

7973:     PetscCall(MatIsSymmetricKnown(Amat, &isset, &issym));
7974:     if (!isset || !issym) {
7975:       Mat matTrans;

7977:       PetscCall(MatTranspose(Gmat, MAT_INITIAL_MATRIX, &matTrans));
7978:       PetscCall(MatAXPY(Gmat, 1.0, matTrans, Gmat->structurally_symmetric == PETSC_BOOL3_TRUE ? SAME_NONZERO_PATTERN : DIFFERENT_NONZERO_PATTERN));
7979:       PetscCall(MatDestroy(&matTrans));
7980:     }
7981:     PetscCall(MatSetOption(Gmat, MAT_SYMMETRIC, PETSC_TRUE));
7982:   } else if (Amat != Gmat) PetscCall(MatPropagateSymmetryOptions(Amat, Gmat));
7983:   if (scale) {
7984:     /* scale c for all diagonal values = 1 or -1 */
7985:     Vec diag;

7987:     PetscCall(MatCreateVecs(Gmat, &diag, NULL));
7988:     PetscCall(MatGetDiagonal(Gmat, diag));
7989:     PetscCall(VecReciprocal(diag));
7990:     PetscCall(VecSqrtAbs(diag));
7991:     PetscCall(MatDiagonalScale(Gmat, diag, diag));
7992:     PetscCall(VecDestroy(&diag));
7993:   }
7994:   PetscCall(MatViewFromOptions(Gmat, NULL, "-mat_graph_view"));
7995:   if (filter >= 0) {
7996:     PetscCall(MatFilter(Gmat, filter, PETSC_TRUE, PETSC_TRUE));
7997:     PetscCall(MatViewFromOptions(Gmat, NULL, "-mat_filter_graph_view"));
7998:   }
7999:   *a_Gmat = Gmat;
8000:   PetscFunctionReturn(PETSC_SUCCESS);
8001: }

8003: PETSC_INTERN PetscErrorCode MatGetCurrentMemType_MPIAIJ(Mat A, PetscMemType *memtype)
8004: {
8005:   Mat_MPIAIJ  *mpiaij = (Mat_MPIAIJ *)A->data;
8006:   PetscMemType mD = PETSC_MEMTYPE_HOST, mO = PETSC_MEMTYPE_HOST;

8008:   PetscFunctionBegin;
8009:   if (mpiaij->A) PetscCall(MatGetCurrentMemType(mpiaij->A, &mD));
8010:   if (mpiaij->B) PetscCall(MatGetCurrentMemType(mpiaij->B, &mO));
8011:   *memtype = (mD == mO) ? mD : PETSC_MEMTYPE_HOST;
8012:   PetscFunctionReturn(PETSC_SUCCESS);
8013: }

8015: /*
8016:     Special version for direct calls from Fortran
8017: */

8019: /* Change these macros so can be used in void function */
8020: /* Identical to PetscCallVoid, except it assigns to *_ierr */
8021: #undef PetscCall
8022: #define PetscCall(...) \
8023:   do { \
8024:     PetscErrorCode ierr_msv_mpiaij = __VA_ARGS__; \
8025:     if (PetscUnlikely(ierr_msv_mpiaij)) { \
8026:       *_ierr = PetscError(PETSC_COMM_SELF, __LINE__, PETSC_FUNCTION_NAME, __FILE__, ierr_msv_mpiaij, PETSC_ERROR_REPEAT, " "); \
8027:       return; \
8028:     } \
8029:   } while (0)

8031: #undef SETERRQ
8032: #define SETERRQ(comm, ierr, ...) \
8033:   do { \
8034:     *_ierr = PetscError(comm, __LINE__, PETSC_FUNCTION_NAME, __FILE__, ierr, PETSC_ERROR_INITIAL, __VA_ARGS__); \
8035:     return; \
8036:   } while (0)

8038: #if defined(PETSC_HAVE_FORTRAN_CAPS)
8039:   #define matsetvaluesmpiaij_ MATSETVALUESMPIAIJ
8040: #elif !defined(PETSC_HAVE_FORTRAN_UNDERSCORE)
8041:   #define matsetvaluesmpiaij_ matsetvaluesmpiaij
8042: #else
8043: #endif
8044: PETSC_EXTERN void matsetvaluesmpiaij_(Mat *mmat, PetscInt *mm, const PetscInt im[], PetscInt *mn, const PetscInt in[], const PetscScalar v[], InsertMode *maddv, PetscErrorCode *_ierr)
8045: {
8046:   Mat         mat = *mmat;
8047:   PetscInt    m = *mm, n = *mn;
8048:   InsertMode  addv = *maddv;
8049:   Mat_MPIAIJ *aij  = (Mat_MPIAIJ *)mat->data;
8050:   PetscScalar value;

8052:   MatCheckPreallocated(mat, 1);
8053:   if (mat->insertmode == NOT_SET_VALUES) mat->insertmode = addv;
8054:   else PetscCheck(mat->insertmode == addv, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Cannot mix add values and insert values");
8055:   {
8056:     PetscInt  i, j, rstart = mat->rmap->rstart, rend = mat->rmap->rend;
8057:     PetscInt  cstart = mat->cmap->rstart, cend = mat->cmap->rend, row, col;
8058:     PetscBool roworiented = aij->roworiented;

8060:     /* Some Variables required in the macro */
8061:     Mat         A     = aij->A;
8062:     Mat_SeqAIJ *a     = (Mat_SeqAIJ *)A->data;
8063:     PetscInt   *aimax = a->imax, *ai = a->i, *ailen = a->ilen, *aj = a->j;
8064:     MatScalar  *aa;
8065:     PetscBool   ignorezeroentries = ((a->ignorezeroentries && (addv == ADD_VALUES)) ? PETSC_TRUE : PETSC_FALSE);
8066:     Mat         B                 = aij->B;
8067:     Mat_SeqAIJ *b                 = (Mat_SeqAIJ *)B->data;
8068:     PetscInt   *bimax = b->imax, *bi = b->i, *bilen = b->ilen, *bj = b->j, bm = aij->B->rmap->n, am = aij->A->rmap->n;
8069:     MatScalar  *ba;
8070:     /* This variable below is only for the PETSC_HAVE_VIENNACL or PETSC_HAVE_CUDA cases, but we define it in all cases because we
8071:      * cannot use "#if defined" inside a macro. */
8072:     PETSC_UNUSED PetscBool inserted = PETSC_FALSE;

8074:     PetscInt  *rp1, *rp2, ii, nrow1, nrow2, _i, rmax1, rmax2, N, low1, high1, low2, high2, t, lastcol1, lastcol2;
8075:     PetscInt   nonew = a->nonew;
8076:     MatScalar *ap1, *ap2;

8078:     PetscFunctionBegin;
8079:     PetscCall(MatSeqAIJGetArray(A, &aa));
8080:     PetscCall(MatSeqAIJGetArray(B, &ba));
8081:     for (i = 0; i < m; i++) {
8082:       if (im[i] < 0) continue;
8083:       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);
8084:       if (im[i] >= rstart && im[i] < rend) {
8085:         row      = im[i] - rstart;
8086:         lastcol1 = -1;
8087:         rp1      = aj + ai[row];
8088:         ap1      = aa + ai[row];
8089:         rmax1    = aimax[row];
8090:         nrow1    = ailen[row];
8091:         low1     = 0;
8092:         high1    = nrow1;
8093:         lastcol2 = -1;
8094:         rp2      = bj + bi[row];
8095:         ap2      = ba + bi[row];
8096:         rmax2    = bimax[row];
8097:         nrow2    = bilen[row];
8098:         low2     = 0;
8099:         high2    = nrow2;

8101:         for (j = 0; j < n; j++) {
8102:           if (roworiented) value = v[i * n + j];
8103:           else value = v[i + j * m];
8104:           if (ignorezeroentries && value == 0.0 && (addv == ADD_VALUES) && im[i] != in[j]) continue;
8105:           if (in[j] >= cstart && in[j] < cend) {
8106:             col = in[j] - cstart;
8107:             MatSetValues_SeqAIJ_A_Private(row, col, value, addv, im[i], in[j]);
8108:           } else if (in[j] < 0) continue;
8109:           else if (PetscUnlikelyDebug(in[j] >= mat->cmap->N)) {
8110:             SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Column too large: col %" PetscInt_FMT " max %" PetscInt_FMT, in[j], mat->cmap->N - 1);
8111:           } else {
8112:             if (mat->was_assembled) {
8113:               if (!aij->colmap) PetscCall(MatCreateColmap_MPIAIJ_Private(mat));
8114: #if defined(PETSC_USE_CTABLE)
8115:               PetscCall(PetscHMapIGetWithDefault(aij->colmap, in[j] + 1, 0, &col));
8116:               col--;
8117: #else
8118:               col = aij->colmap[in[j]] - 1;
8119: #endif
8120:               if (col < 0 && !((Mat_SeqAIJ *)aij->A->data)->nonew) {
8121:                 PetscCall(MatDisAssemble_MPIAIJ(mat, PETSC_FALSE));
8122:                 col = in[j];
8123:                 /* Reinitialize the variables required by MatSetValues_SeqAIJ_B_Private() */
8124:                 B        = aij->B;
8125:                 b        = (Mat_SeqAIJ *)B->data;
8126:                 bimax    = b->imax;
8127:                 bi       = b->i;
8128:                 bilen    = b->ilen;
8129:                 bj       = b->j;
8130:                 rp2      = bj + bi[row];
8131:                 ap2      = ba + bi[row];
8132:                 rmax2    = bimax[row];
8133:                 nrow2    = bilen[row];
8134:                 low2     = 0;
8135:                 high2    = nrow2;
8136:                 bm       = aij->B->rmap->n;
8137:                 ba       = b->a;
8138:                 inserted = PETSC_FALSE;
8139:               }
8140:             } else col = in[j];
8141:             MatSetValues_SeqAIJ_B_Private(row, col, value, addv, im[i], in[j]);
8142:           }
8143:         }
8144:       } else if (!aij->donotstash) {
8145:         if (roworiented) {
8146:           PetscCall(MatStashValuesRow_Private(&mat->stash, im[i], n, in, v + i * n, (PetscBool)(ignorezeroentries && (addv == ADD_VALUES))));
8147:         } else {
8148:           PetscCall(MatStashValuesCol_Private(&mat->stash, im[i], n, in, v + i, m, (PetscBool)(ignorezeroentries && (addv == ADD_VALUES))));
8149:         }
8150:       }
8151:     }
8152:     PetscCall(MatSeqAIJRestoreArray(A, &aa));
8153:     PetscCall(MatSeqAIJRestoreArray(B, &ba));
8154:   }
8155:   PetscFunctionReturnVoid();
8156: }

8158: /* Undefining these here since they were redefined from their original definition above! No
8159:  * other PETSc functions should be defined past this point, as it is impossible to recover the
8160:  * original definitions */
8161: #undef PetscCall
8162: #undef SETERRQ