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:   PetscCall((*a->A->ops->multadd)(a->A, xx, yy, zz));
1081:   PetscCall(VecScatterEnd(Mvctx, xx, a->lvec, INSERT_VALUES, SCATTER_FORWARD));
1082:   PetscCall((*a->B->ops->multadd)(a->B, 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:   PetscCall((*a->B->ops->multtranspose)(a->B, xx, a->lvec));
1093:   /* do local part */
1094:   PetscCall((*a->A->ops->multtranspose)(a->A, 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:   PetscCall((*a->B->ops->multtranspose)(a->B, xx, a->lvec));
1148:   /* do local part */
1149:   PetscCall((*a->A->ops->multtransposeadd)(a->A, 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:     PetscCall((*mat->A->ops->sor)(mat->A, 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:       PetscCall((*mat->A->ops->sor)(mat->A, 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:       PetscCall((*mat->B->ops->multadd)(mat->B, mat->lvec, bb, bb1));

1424:       /* local sweep */
1425:       PetscCall((*mat->A->ops->sor)(mat->A, 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:       PetscCall((*mat->A->ops->sor)(mat->A, 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:       PetscCall((*mat->B->ops->multadd)(mat->B, mat->lvec, bb, bb1));

1440:       /* local sweep */
1441:       PetscCall((*mat->A->ops->sor)(mat->A, 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:       PetscCall((*mat->A->ops->sor)(mat->A, 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:       PetscCall((*mat->B->ops->multadd)(mat->B, mat->lvec, bb, bb1));

1456:       /* local sweep */
1457:       PetscCall((*mat->A->ops->sor)(mat->A, 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:     PetscCall((*mat->A->ops->sor)(mat->A, 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:     PetscCall((*mat->A->ops->sor)(mat->A, 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:   PetscCall((*mat->A->ops->getrow)(mat->A, lrow, &nzA, pcA, pvA));
1747:   PetscCall((*mat->B->ops->getrow)(mat->B, 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:   PetscCall((*mat->A->ops->restorerow)(mat->A, lrow, &nzA, pcA, pvA));
1786:   PetscCall((*mat->B->ops->restorerow)(mat->B, 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:                                        NULL,
2823:                                        MatTransposeMatMultNumeric_MPIAIJ_MPIAIJ,
2824:                                        NULL,
2825:                                        NULL,
2826:                                        /*124*/ NULL,
2827:                                        NULL,
2828:                                        MatSetBlockSizes_MPIAIJ,
2829:                                        NULL,
2830:                                        MatFDColoringSetUp_MPIXAIJ,
2831:                                        /*129*/ MatFindOffBlockDiagonalEntries_MPIAIJ,
2832:                                        MatCreateMPIMatConcatenateSeqMat_MPIAIJ,
2833:                                        NULL,
2834:                                        NULL,
2835:                                        NULL,
2836:                                        /*134*/ MatCreateGraph_Simple_AIJ,
2837:                                        NULL,
2838:                                        MatEliminateZeros_MPIAIJ,
2839:                                        MatGetRowSumAbs_MPIAIJ,
2840:                                        NULL,
2841:                                        /*139*/ NULL,
2842:                                        NULL,
2843:                                        MatCopyHashToXAIJ_MPI_Hash,
2844:                                        MatGetCurrentMemType_MPIAIJ,
2845:                                        NULL,
2846:                                        /*144*/ MatADot_Default,
2847:                                        MatANorm_Default,
2848:                                        NULL,
2849:                                        NULL};

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

3440:   Collective

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

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

3453:   Level: advanced

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

3707:   PetscCall(PetscFree(colsub));

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

3936:   Collective

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

3944:   Level: developer

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

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

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

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

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

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

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

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

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

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

3996:   Collective

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

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

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

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

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

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

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

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

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

4083:   Level: intermediate

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

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

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

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

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

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

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

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

4129:   Collective

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

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

4146:   Level: intermediate

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

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

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

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

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

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

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

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

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

4201:   Deprecated: Use `MatUpdateMPIAIJWithArray()`

4203:   Collective

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

4217:   Level: deprecated

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

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

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

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

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

4275:   Collective

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

4281:   Level: intermediate

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

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

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

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

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

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

4341:   Collective

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

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

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

4377:   Level: intermediate

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

4533:   Not Collective

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

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

4543:   Level: intermediate

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

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

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

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

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

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

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

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

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

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

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

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

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

4645: /*@
4646:   MatCreateMPIAIJSumSeqAIJNumeric - Fill the numerical values of an `MATMPIAIJ` matrix previously created by
4647:   `MatCreateMPIAIJSumSeqAIJSymbolic()` by summing the local `MATSEQAIJ` contributions from each process.

4649:   Collective

4651:   Input Parameters:
4652: + seqmat - the local `MATSEQAIJ` contribution from this process
4653: - mpimat - the target `MATMPIAIJ` matrix created by `MatCreateMPIAIJSumSeqAIJSymbolic()`

4655:   Level: developer

4657: .seealso: `Mat`, `MATMPIAIJ`, `MATSEQAIJ`, `MatCreateMPIAIJSumSeqAIJSymbolic()`, `MatCreateMPIAIJSumSeqAIJ()`
4658: @*/
4659: PetscErrorCode MatCreateMPIAIJSumSeqAIJNumeric(Mat seqmat, Mat mpimat)
4660: {
4661:   MPI_Comm           comm;
4662:   Mat_SeqAIJ        *a = (Mat_SeqAIJ *)seqmat->data;
4663:   PetscMPIInt        size, rank, taga, *len_s;
4664:   PetscInt           N = mpimat->cmap->N, i, j, *owners, *ai = a->i, *aj, m;
4665:   PetscMPIInt        proc, k;
4666:   PetscInt         **buf_ri, **buf_rj;
4667:   PetscInt           anzi, *bj_i, *bi, *bj, arow, bnzi, nextaj;
4668:   PetscInt           nrows, **buf_ri_k, **nextrow, **nextai;
4669:   MPI_Request       *s_waits, *r_waits;
4670:   MPI_Status        *status;
4671:   const MatScalar   *aa, *a_a;
4672:   MatScalar        **abuf_r, *ba_i;
4673:   MatMergeSeqsToMPI *merge;
4674:   PetscContainer     container;

4676:   PetscFunctionBegin;
4677:   PetscCall(PetscObjectGetComm((PetscObject)mpimat, &comm));
4678:   PetscCall(PetscLogEventBegin(MAT_Seqstompinum, seqmat, 0, 0, 0));

4680:   PetscCallMPI(MPI_Comm_size(comm, &size));
4681:   PetscCallMPI(MPI_Comm_rank(comm, &rank));

4683:   PetscCall(PetscObjectQuery((PetscObject)mpimat, "MatMergeSeqsToMPI", (PetscObject *)&container));
4684:   PetscCheck(container, PetscObjectComm((PetscObject)mpimat), PETSC_ERR_PLIB, "Mat not created from MatCreateMPIAIJSumSeqAIJSymbolic");
4685:   PetscCall(PetscContainerGetPointer(container, &merge));
4686:   PetscCall(MatSeqAIJGetArrayRead(seqmat, &a_a));
4687:   aa = a_a;

4689:   bi     = merge->bi;
4690:   bj     = merge->bj;
4691:   buf_ri = merge->buf_ri;
4692:   buf_rj = merge->buf_rj;

4694:   PetscCall(PetscMalloc1(size, &status));
4695:   owners = merge->rowmap->range;
4696:   len_s  = merge->len_s;

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

4702:   PetscCall(PetscMalloc1(merge->nsend + 1, &s_waits));
4703:   for (proc = 0, k = 0; proc < size; proc++) {
4704:     if (!len_s[proc]) continue;
4705:     i = owners[proc];
4706:     PetscCallMPI(MPIU_Isend(aa + ai[i], len_s[proc], MPIU_MATSCALAR, proc, taga, comm, s_waits + k));
4707:     k++;
4708:   }

4710:   if (merge->nrecv) PetscCallMPI(MPI_Waitall(merge->nrecv, r_waits, status));
4711:   if (merge->nsend) PetscCallMPI(MPI_Waitall(merge->nsend, s_waits, status));
4712:   PetscCall(PetscFree(status));

4714:   PetscCall(PetscFree(s_waits));
4715:   PetscCall(PetscFree(r_waits));

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

4721:   for (k = 0; k < merge->nrecv; k++) {
4722:     buf_ri_k[k] = buf_ri[k]; /* beginning of k-th recved i-structure */
4723:     nrows       = *buf_ri_k[k];
4724:     nextrow[k]  = buf_ri_k[k] + 1;           /* next row number of k-th recved i-structure */
4725:     nextai[k]   = buf_ri_k[k] + (nrows + 1); /* points to the next i-structure of k-th recved i-structure  */
4726:   }

4728:   /* set values of ba */
4729:   m = merge->rowmap->n;
4730:   for (i = 0; i < m; i++) {
4731:     arow = owners[rank] + i;
4732:     bj_i = bj + bi[i]; /* col indices of the i-th row of mpimat */
4733:     bnzi = bi[i + 1] - bi[i];
4734:     PetscCall(PetscArrayzero(ba_i, bnzi));

4736:     /* add local non-zero vals of this proc's seqmat into ba */
4737:     anzi   = ai[arow + 1] - ai[arow];
4738:     aj     = a->j + ai[arow];
4739:     aa     = a_a + ai[arow];
4740:     nextaj = 0;
4741:     for (j = 0; nextaj < anzi; j++) {
4742:       if (*(bj_i + j) == aj[nextaj]) { /* bcol == acol */
4743:         ba_i[j] += aa[nextaj++];
4744:       }
4745:     }

4747:     /* add received vals into ba */
4748:     for (k = 0; k < merge->nrecv; k++) { /* k-th received message */
4749:       /* i-th row */
4750:       if (i == *nextrow[k]) {
4751:         anzi   = *(nextai[k] + 1) - *nextai[k];
4752:         aj     = buf_rj[k] + *nextai[k];
4753:         aa     = abuf_r[k] + *nextai[k];
4754:         nextaj = 0;
4755:         for (j = 0; nextaj < anzi; j++) {
4756:           if (*(bj_i + j) == aj[nextaj]) { /* bcol == acol */
4757:             ba_i[j] += aa[nextaj++];
4758:           }
4759:         }
4760:         nextrow[k]++;
4761:         nextai[k]++;
4762:       }
4763:     }
4764:     PetscCall(MatSetValues(mpimat, 1, &arow, bnzi, bj_i, ba_i, INSERT_VALUES));
4765:   }
4766:   PetscCall(MatSeqAIJRestoreArrayRead(seqmat, &a_a));
4767:   PetscCall(MatAssemblyBegin(mpimat, MAT_FINAL_ASSEMBLY));
4768:   PetscCall(MatAssemblyEnd(mpimat, MAT_FINAL_ASSEMBLY));

4770:   PetscCall(PetscFree(abuf_r[0]));
4771:   PetscCall(PetscFree(abuf_r));
4772:   PetscCall(PetscFree(ba_i));
4773:   PetscCall(PetscFree3(buf_ri_k, nextrow, nextai));
4774:   PetscCall(PetscLogEventEnd(MAT_Seqstompinum, seqmat, 0, 0, 0));
4775:   PetscFunctionReturn(PETSC_SUCCESS);
4776: }

4778: /*@
4779:   MatCreateMPIAIJSumSeqAIJSymbolic - Create the symbolic (nonzero-pattern) portion of an `MATMPIAIJ` matrix
4780:   obtained by summing local `MATSEQAIJ` contributions from each process.

4782:   Collective

4784:   Input Parameters:
4785: + comm   - the communicator
4786: . seqmat - the local `MATSEQAIJ` contribution from this process
4787: . m      - the number of local rows for the resulting `MATMPIAIJ` matrix, or `PETSC_DECIDE`
4788: - n      - the number of local columns for the resulting `MATMPIAIJ` matrix, or `PETSC_DECIDE`

4790:   Output Parameter:
4791: . mpimat - the newly created `MATMPIAIJ` matrix

4793:   Level: developer

4795:   Note:
4796:   The numerical values are filled in by a subsequent call to `MatCreateMPIAIJSumSeqAIJNumeric()`.

4798: .seealso: `Mat`, `MATMPIAIJ`, `MATSEQAIJ`, `MatCreateMPIAIJSumSeqAIJNumeric()`, `MatCreateMPIAIJSumSeqAIJ()`
4799: @*/
4800: PetscErrorCode MatCreateMPIAIJSumSeqAIJSymbolic(MPI_Comm comm, Mat seqmat, PetscInt m, PetscInt n, Mat *mpimat)
4801: {
4802:   Mat                B_mpi;
4803:   Mat_SeqAIJ        *a = (Mat_SeqAIJ *)seqmat->data;
4804:   PetscMPIInt        size, rank, tagi, tagj, *len_s, *len_si, *len_ri;
4805:   PetscInt         **buf_rj, **buf_ri, **buf_ri_k;
4806:   PetscInt           M = seqmat->rmap->n, N = seqmat->cmap->n, i, *owners, *ai = a->i, *aj = a->j;
4807:   PetscInt           len, *dnz, *onz, bs, cbs;
4808:   PetscInt           k, anzi, *bi, *bj, *lnk, nlnk, arow, bnzi;
4809:   PetscInt           nrows, *buf_s, *buf_si, *buf_si_i, **nextrow, **nextai;
4810:   MPI_Request       *si_waits, *sj_waits, *ri_waits, *rj_waits;
4811:   MPI_Status        *status;
4812:   PetscFreeSpaceList free_space = NULL, current_space = NULL;
4813:   PetscBT            lnkbt;
4814:   MatMergeSeqsToMPI *merge;
4815:   PetscContainer     container;

4817:   PetscFunctionBegin;
4818:   PetscCall(PetscLogEventBegin(MAT_Seqstompisym, seqmat, 0, 0, 0));

4820:   /* make sure it is a PETSc comm */
4821:   PetscCall(PetscCommDuplicate(comm, &comm, NULL));
4822:   PetscCallMPI(MPI_Comm_size(comm, &size));
4823:   PetscCallMPI(MPI_Comm_rank(comm, &rank));

4825:   PetscCall(PetscNew(&merge));
4826:   PetscCall(PetscMalloc1(size, &status));

4828:   /* determine row ownership */
4829:   PetscCall(PetscLayoutCreate(comm, &merge->rowmap));
4830:   PetscCall(PetscLayoutSetLocalSize(merge->rowmap, m));
4831:   PetscCall(PetscLayoutSetSize(merge->rowmap, M));
4832:   PetscCall(PetscLayoutSetBlockSize(merge->rowmap, 1));
4833:   PetscCall(PetscLayoutSetUp(merge->rowmap));
4834:   PetscCall(PetscMalloc1(size, &len_si));
4835:   PetscCall(PetscMalloc1(size, &merge->len_s));

4837:   m      = merge->rowmap->n;
4838:   owners = merge->rowmap->range;

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

4843:   len          = 0; /* length of buf_si[] */
4844:   merge->nsend = 0;
4845:   for (PetscMPIInt proc = 0; proc < size; proc++) {
4846:     len_si[proc] = 0;
4847:     if (proc == rank) {
4848:       len_s[proc] = 0;
4849:     } else {
4850:       PetscCall(PetscMPIIntCast(owners[proc + 1] - owners[proc] + 1, &len_si[proc]));
4851:       PetscCall(PetscMPIIntCast(ai[owners[proc + 1]] - ai[owners[proc]], &len_s[proc])); /* num of rows to be sent to [proc] */
4852:     }
4853:     if (len_s[proc]) {
4854:       merge->nsend++;
4855:       nrows = 0;
4856:       for (i = owners[proc]; i < owners[proc + 1]; i++) {
4857:         if (ai[i + 1] > ai[i]) nrows++;
4858:       }
4859:       PetscCall(PetscMPIIntCast(2 * (nrows + 1), &len_si[proc]));
4860:       len += len_si[proc];
4861:     }
4862:   }

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

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

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

4875:   for (PetscMPIInt proc = 0, k = 0; proc < size; proc++) {
4876:     if (!len_s[proc]) continue;
4877:     i = owners[proc];
4878:     PetscCallMPI(MPIU_Isend(aj + ai[i], len_s[proc], MPIU_INT, proc, tagj, comm, sj_waits + k));
4879:     k++;
4880:   }

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

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

4890:   PetscCall(PetscMalloc1(len + 1, &buf_s));
4891:   buf_si = buf_s; /* points to the beginning of k-th msg to be sent */
4892:   for (PetscMPIInt proc = 0, k = 0; proc < size; proc++) {
4893:     if (!len_s[proc]) continue;
4894:     /* form outgoing message for i-structure:
4895:          buf_si[0]:                 nrows to be sent
4896:                [1:nrows]:           row index (global)
4897:                [nrows+1:2*nrows+1]: i-structure index
4898:     */
4899:     nrows       = len_si[proc] / 2 - 1;
4900:     buf_si_i    = buf_si + nrows + 1;
4901:     buf_si[0]   = nrows;
4902:     buf_si_i[0] = 0;
4903:     nrows       = 0;
4904:     for (i = owners[proc]; i < owners[proc + 1]; i++) {
4905:       anzi = ai[i + 1] - ai[i];
4906:       if (anzi) {
4907:         buf_si_i[nrows + 1] = buf_si_i[nrows] + anzi; /* i-structure */
4908:         buf_si[nrows + 1]   = i - owners[proc];       /* local row index */
4909:         nrows++;
4910:       }
4911:     }
4912:     PetscCallMPI(MPIU_Isend(buf_si, len_si[proc], MPIU_INT, proc, tagi, comm, si_waits + k));
4913:     k++;
4914:     buf_si += len_si[proc];
4915:   }

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

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

4923:   PetscCall(PetscFree(len_si));
4924:   PetscCall(PetscFree(len_ri));
4925:   PetscCall(PetscFree(rj_waits));
4926:   PetscCall(PetscFree2(si_waits, sj_waits));
4927:   PetscCall(PetscFree(ri_waits));
4928:   PetscCall(PetscFree(buf_s));
4929:   PetscCall(PetscFree(status));

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

4936:   /* create and initialize a linked list */
4937:   nlnk = N + 1;
4938:   PetscCall(PetscLLCreate(N, N, nlnk, lnk, lnkbt));

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

4944:   current_space = free_space;

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

4949:   for (k = 0; k < merge->nrecv; k++) {
4950:     buf_ri_k[k] = buf_ri[k]; /* beginning of k-th recved i-structure */
4951:     nrows       = *buf_ri_k[k];
4952:     nextrow[k]  = buf_ri_k[k] + 1;           /* next row number of k-th recved i-structure */
4953:     nextai[k]   = buf_ri_k[k] + (nrows + 1); /* points to the next i-structure of k-th recved i-structure  */
4954:   }

4956:   MatPreallocateBegin(comm, m, n, dnz, onz);
4957:   len = 0;
4958:   for (i = 0; i < m; i++) {
4959:     bnzi = 0;
4960:     /* add local non-zero cols of this proc's seqmat into lnk */
4961:     arow = owners[rank] + i;
4962:     anzi = ai[arow + 1] - ai[arow];
4963:     aj   = a->j + ai[arow];
4964:     PetscCall(PetscLLAddSorted(anzi, aj, N, &nlnk, lnk, lnkbt));
4965:     bnzi += nlnk;
4966:     /* add received col data into lnk */
4967:     for (k = 0; k < merge->nrecv; k++) { /* k-th received message */
4968:       if (i == *nextrow[k]) {            /* i-th row */
4969:         anzi = *(nextai[k] + 1) - *nextai[k];
4970:         aj   = buf_rj[k] + *nextai[k];
4971:         PetscCall(PetscLLAddSorted(anzi, aj, N, &nlnk, lnk, lnkbt));
4972:         bnzi += nlnk;
4973:         nextrow[k]++;
4974:         nextai[k]++;
4975:       }
4976:     }
4977:     if (len < bnzi) len = bnzi; /* =max(bnzi) */

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

4985:     current_space->array += bnzi;
4986:     current_space->local_used += bnzi;
4987:     current_space->local_remaining -= bnzi;

4989:     bi[i + 1] = bi[i] + bnzi;
4990:   }

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

4994:   PetscCall(PetscMalloc1(bi[m], &bj));
4995:   PetscCall(PetscFreeSpaceContiguous(&free_space, bj));
4996:   PetscCall(PetscLLDestroy(lnk, lnkbt));

4998:   /* create symbolic parallel matrix B_mpi */
4999:   PetscCall(MatGetBlockSizes(seqmat, &bs, &cbs));
5000:   PetscCall(MatCreate(comm, &B_mpi));
5001:   if (n == PETSC_DECIDE) PetscCall(MatSetSizes(B_mpi, m, n, PETSC_DETERMINE, N));
5002:   else PetscCall(MatSetSizes(B_mpi, m, n, PETSC_DETERMINE, PETSC_DETERMINE));
5003:   PetscCall(MatSetBlockSizes(B_mpi, bs, cbs));
5004:   PetscCall(MatSetType(B_mpi, MATMPIAIJ));
5005:   PetscCall(MatMPIAIJSetPreallocation(B_mpi, 0, dnz, 0, onz));
5006:   MatPreallocateEnd(dnz, onz);
5007:   PetscCall(MatSetOption(B_mpi, MAT_NEW_NONZERO_ALLOCATION_ERR, PETSC_FALSE));

5009:   /* B_mpi is not ready for use - assembly will be done by MatCreateMPIAIJSumSeqAIJNumeric() */
5010:   B_mpi->assembled = PETSC_FALSE;
5011:   merge->bi        = bi;
5012:   merge->bj        = bj;
5013:   merge->buf_ri    = buf_ri;
5014:   merge->buf_rj    = buf_rj;
5015:   merge->coi       = NULL;
5016:   merge->coj       = NULL;
5017:   merge->owners_co = NULL;

5019:   PetscCall(PetscCommDestroy(&comm));

5021:   /* attach the supporting struct to B_mpi for reuse */
5022:   PetscCall(PetscContainerCreate(PETSC_COMM_SELF, &container));
5023:   PetscCall(PetscContainerSetPointer(container, merge));
5024:   PetscCall(PetscContainerSetCtxDestroy(container, MatMergeSeqsToMPIDestroy));
5025:   PetscCall(PetscObjectCompose((PetscObject)B_mpi, "MatMergeSeqsToMPI", (PetscObject)container));
5026:   PetscCall(PetscContainerDestroy(&container));
5027:   *mpimat = B_mpi;

5029:   PetscCall(PetscLogEventEnd(MAT_Seqstompisym, seqmat, 0, 0, 0));
5030:   PetscFunctionReturn(PETSC_SUCCESS);
5031: }

5033: /*@
5034:   MatCreateMPIAIJSumSeqAIJ - Creates a `MATMPIAIJ` matrix by adding sequential
5035:   matrices from each processor

5037:   Collective

5039:   Input Parameters:
5040: + comm   - the communicators the parallel matrix will live on
5041: . seqmat - the input sequential matrices
5042: . m      - number of local rows (or `PETSC_DECIDE`)
5043: . n      - number of local columns (or `PETSC_DECIDE`)
5044: - scall  - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`

5046:   Output Parameter:
5047: . mpimat - the parallel matrix generated

5049:   Level: advanced

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

5056: .seealso: [](ch_matrices), `Mat`, `MatCreateAIJ()`
5057: @*/
5058: PetscErrorCode MatCreateMPIAIJSumSeqAIJ(MPI_Comm comm, Mat seqmat, PetscInt m, PetscInt n, MatReuse scall, Mat *mpimat)
5059: {
5060:   PetscMPIInt size;

5062:   PetscFunctionBegin;
5063:   PetscCallMPI(MPI_Comm_size(comm, &size));
5064:   if (size == 1) {
5065:     PetscCall(PetscLogEventBegin(MAT_Seqstompi, seqmat, 0, 0, 0));
5066:     if (scall == MAT_INITIAL_MATRIX) PetscCall(MatDuplicate(seqmat, MAT_COPY_VALUES, mpimat));
5067:     else PetscCall(MatCopy(seqmat, *mpimat, SAME_NONZERO_PATTERN));
5068:     PetscCall(PetscLogEventEnd(MAT_Seqstompi, seqmat, 0, 0, 0));
5069:     PetscFunctionReturn(PETSC_SUCCESS);
5070:   }
5071:   PetscCall(PetscLogEventBegin(MAT_Seqstompi, seqmat, 0, 0, 0));
5072:   if (scall == MAT_INITIAL_MATRIX) PetscCall(MatCreateMPIAIJSumSeqAIJSymbolic(comm, seqmat, m, n, mpimat));
5073:   PetscCall(MatCreateMPIAIJSumSeqAIJNumeric(seqmat, *mpimat));
5074:   PetscCall(PetscLogEventEnd(MAT_Seqstompi, seqmat, 0, 0, 0));
5075:   PetscFunctionReturn(PETSC_SUCCESS);
5076: }

5078: /*@
5079:   MatAIJGetLocalMat - Creates a `MATSEQAIJ` from a `MATAIJ` matrix.

5081:   Not Collective

5083:   Input Parameter:
5084: . A - the matrix

5086:   Output Parameter:
5087: . A_loc - the local sequential matrix generated

5089:   Level: developer

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

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

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

5100:   Destroy the matrix with `MatDestroy()`

5102: .seealso: [](ch_matrices), `Mat`, `MatMPIAIJGetLocalMat()`
5103: @*/
5104: PetscErrorCode MatAIJGetLocalMat(Mat A, Mat *A_loc)
5105: {
5106:   PetscBool mpi;

5108:   PetscFunctionBegin;
5109:   PetscCall(PetscObjectTypeCompare((PetscObject)A, MATMPIAIJ, &mpi));
5110:   if (mpi) PetscCall(MatMPIAIJGetLocalMat(A, MAT_INITIAL_MATRIX, A_loc));
5111:   else {
5112:     *A_loc = A;
5113:     PetscCall(PetscObjectReference((PetscObject)*A_loc));
5114:   }
5115:   PetscFunctionReturn(PETSC_SUCCESS);
5116: }

5118: /*@
5119:   MatMPIAIJGetLocalMat - Creates a `MATSEQAIJ` from a `MATMPIAIJ` matrix.

5121:   Not Collective

5123:   Input Parameters:
5124: + A     - the matrix
5125: - scall - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`

5127:   Output Parameter:
5128: . A_loc - the local sequential matrix generated

5130:   Level: developer

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

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

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

5144: .seealso: [](ch_matrices), `Mat`, `MATMPIAIJ`, `MatGetOwnershipRange()`, `MatMPIAIJGetLocalMatCondensed()`, `MatMPIAIJGetLocalMatMerge()`
5145: @*/
5146: PetscErrorCode MatMPIAIJGetLocalMat(Mat A, MatReuse scall, Mat *A_loc)
5147: {
5148:   Mat_MPIAIJ        *mpimat = (Mat_MPIAIJ *)A->data;
5149:   Mat_SeqAIJ        *mat, *a, *b;
5150:   PetscInt          *ai, *aj, *bi, *bj, *cmap = mpimat->garray;
5151:   const PetscScalar *aa, *ba, *aav, *bav;
5152:   PetscScalar       *ca, *cam;
5153:   PetscMPIInt        size;
5154:   PetscInt           am = A->rmap->n, i, j, k, cstart = A->cmap->rstart;
5155:   PetscInt          *ci, *cj, col, ncols_d, ncols_o, jo;
5156:   PetscBool          match;

5158:   PetscFunctionBegin;
5159:   PetscCall(PetscStrbeginswith(((PetscObject)A)->type_name, MATMPIAIJ, &match));
5160:   PetscCheck(match, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "Requires MATMPIAIJ matrix as input");
5161:   PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)A), &size));
5162:   if (size == 1) {
5163:     if (scall == MAT_INITIAL_MATRIX) {
5164:       PetscCall(PetscObjectReference((PetscObject)mpimat->A));
5165:       *A_loc = mpimat->A;
5166:     } else if (scall == MAT_REUSE_MATRIX) {
5167:       PetscCall(MatCopy(mpimat->A, *A_loc, SAME_NONZERO_PATTERN));
5168:     }
5169:     PetscFunctionReturn(PETSC_SUCCESS);
5170:   }

5172:   PetscCall(PetscLogEventBegin(MAT_Getlocalmat, A, 0, 0, 0));
5173:   a  = (Mat_SeqAIJ *)mpimat->A->data;
5174:   b  = (Mat_SeqAIJ *)mpimat->B->data;
5175:   ai = a->i;
5176:   aj = a->j;
5177:   bi = b->i;
5178:   bj = b->j;
5179:   PetscCall(MatSeqAIJGetArrayRead(mpimat->A, &aav));
5180:   PetscCall(MatSeqAIJGetArrayRead(mpimat->B, &bav));
5181:   aa = aav;
5182:   ba = bav;
5183:   if (scall == MAT_INITIAL_MATRIX) {
5184:     PetscCall(PetscMalloc1(1 + am, &ci));
5185:     ci[0] = 0;
5186:     for (i = 0; i < am; i++) ci[i + 1] = ci[i] + (ai[i + 1] - ai[i]) + (bi[i + 1] - bi[i]);
5187:     PetscCall(PetscMalloc1(1 + ci[am], &cj));
5188:     PetscCall(PetscMalloc1(1 + ci[am], &ca));
5189:     k = 0;
5190:     for (i = 0; i < am; i++) {
5191:       ncols_o = bi[i + 1] - bi[i];
5192:       ncols_d = ai[i + 1] - ai[i];
5193:       /* off-diagonal portion of A */
5194:       for (jo = 0; jo < ncols_o; jo++) {
5195:         col = cmap[*bj];
5196:         if (col >= cstart) break;
5197:         cj[k] = col;
5198:         bj++;
5199:         ca[k++] = *ba++;
5200:       }
5201:       /* diagonal portion of A */
5202:       for (j = 0; j < ncols_d; j++) {
5203:         cj[k]   = cstart + *aj++;
5204:         ca[k++] = *aa++;
5205:       }
5206:       /* off-diagonal portion of A */
5207:       for (j = jo; j < ncols_o; j++) {
5208:         cj[k]   = cmap[*bj++];
5209:         ca[k++] = *ba++;
5210:       }
5211:     }
5212:     /* put together the new matrix */
5213:     PetscCall(MatCreateSeqAIJWithArrays(PETSC_COMM_SELF, am, A->cmap->N, ci, cj, ca, A_loc));
5214:     /* MatCreateSeqAIJWithArrays flags matrix so PETSc doesn't free the user's arrays. */
5215:     /* Since these are PETSc arrays, change flags to free them as necessary. */
5216:     mat          = (Mat_SeqAIJ *)(*A_loc)->data;
5217:     mat->free_a  = PETSC_TRUE;
5218:     mat->free_ij = PETSC_TRUE;
5219:     mat->nonew   = 0;
5220:   } else if (scall == MAT_REUSE_MATRIX) {
5221:     mat = (Mat_SeqAIJ *)(*A_loc)->data;
5222:     ci  = mat->i;
5223:     cj  = mat->j;
5224:     PetscCall(MatSeqAIJGetArrayWrite(*A_loc, &cam));
5225:     for (i = 0; i < am; i++) {
5226:       /* off-diagonal portion of A */
5227:       ncols_o = bi[i + 1] - bi[i];
5228:       for (jo = 0; jo < ncols_o; jo++) {
5229:         col = cmap[*bj];
5230:         if (col >= cstart) break;
5231:         *cam++ = *ba++;
5232:         bj++;
5233:       }
5234:       /* diagonal portion of A */
5235:       ncols_d = ai[i + 1] - ai[i];
5236:       for (j = 0; j < ncols_d; j++) *cam++ = *aa++;
5237:       /* off-diagonal portion of A */
5238:       for (j = jo; j < ncols_o; j++) {
5239:         *cam++ = *ba++;
5240:         bj++;
5241:       }
5242:     }
5243:     PetscCall(MatSeqAIJRestoreArrayWrite(*A_loc, &cam));
5244:   } else SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Invalid MatReuse %d", (int)scall);
5245:   PetscCall(MatSeqAIJRestoreArrayRead(mpimat->A, &aav));
5246:   PetscCall(MatSeqAIJRestoreArrayRead(mpimat->B, &bav));
5247:   PetscCall(PetscLogEventEnd(MAT_Getlocalmat, A, 0, 0, 0));
5248:   PetscFunctionReturn(PETSC_SUCCESS);
5249: }

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

5255:   Not Collective

5257:   Input Parameters:
5258: + A     - the matrix
5259: - scall - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`

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

5265:   Level: developer

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

5271: .seealso: [](ch_matrices), `Mat`, `MATMPIAIJ`, `MatGetOwnershipRange()`, `MatMPIAIJGetLocalMat()`, `MatMPIAIJGetLocalMatCondensed()`
5272: @*/
5273: PetscErrorCode MatMPIAIJGetLocalMatMerge(Mat A, MatReuse scall, IS *glob, Mat *A_loc)
5274: {
5275:   Mat             Ao, Ad;
5276:   const PetscInt *cmap;
5277:   PetscMPIInt     size;
5278:   PetscErrorCode (*f)(Mat, MatReuse, IS *, Mat *);

5280:   PetscFunctionBegin;
5281:   PetscCall(MatMPIAIJGetSeqAIJ(A, &Ad, &Ao, &cmap));
5282:   PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)A), &size));
5283:   if (size == 1) {
5284:     if (scall == MAT_INITIAL_MATRIX) {
5285:       PetscCall(PetscObjectReference((PetscObject)Ad));
5286:       *A_loc = Ad;
5287:     } else if (scall == MAT_REUSE_MATRIX) {
5288:       PetscCall(MatCopy(Ad, *A_loc, SAME_NONZERO_PATTERN));
5289:     }
5290:     if (glob) PetscCall(ISCreateStride(PetscObjectComm((PetscObject)Ad), Ad->cmap->n, Ad->cmap->rstart, 1, glob));
5291:     PetscFunctionReturn(PETSC_SUCCESS);
5292:   }
5293:   PetscCall(PetscObjectQueryFunction((PetscObject)A, "MatMPIAIJGetLocalMatMerge_C", &f));
5294:   PetscCall(PetscLogEventBegin(MAT_Getlocalmat, A, 0, 0, 0));
5295:   if (f) PetscCall((*f)(A, scall, glob, A_loc));
5296:   else {
5297:     Mat_SeqAIJ        *a = (Mat_SeqAIJ *)Ad->data;
5298:     Mat_SeqAIJ        *b = (Mat_SeqAIJ *)Ao->data;
5299:     Mat_SeqAIJ        *c;
5300:     PetscInt          *ai = a->i, *aj = a->j;
5301:     PetscInt          *bi = b->i, *bj = b->j;
5302:     PetscInt          *ci, *cj;
5303:     const PetscScalar *aa, *ba;
5304:     PetscScalar       *ca;
5305:     PetscInt           i, j, am, dn, on;

5307:     PetscCall(MatGetLocalSize(Ad, &am, &dn));
5308:     PetscCall(MatGetLocalSize(Ao, NULL, &on));
5309:     PetscCall(MatSeqAIJGetArrayRead(Ad, &aa));
5310:     PetscCall(MatSeqAIJGetArrayRead(Ao, &ba));
5311:     if (scall == MAT_INITIAL_MATRIX) {
5312:       PetscInt k;
5313:       PetscCall(PetscMalloc1(1 + am, &ci));
5314:       PetscCall(PetscMalloc1(ai[am] + bi[am], &cj));
5315:       PetscCall(PetscMalloc1(ai[am] + bi[am], &ca));
5316:       ci[0] = 0;
5317:       for (i = 0, k = 0; i < am; i++) {
5318:         const PetscInt ncols_o = bi[i + 1] - bi[i];
5319:         const PetscInt ncols_d = ai[i + 1] - ai[i];
5320:         ci[i + 1]              = ci[i] + ncols_o + ncols_d;
5321:         /* diagonal portion of A */
5322:         for (j = 0; j < ncols_d; j++, k++) {
5323:           cj[k] = *aj++;
5324:           ca[k] = *aa++;
5325:         }
5326:         /* off-diagonal portion of A */
5327:         for (j = 0; j < ncols_o; j++, k++) {
5328:           cj[k] = dn + *bj++;
5329:           ca[k] = *ba++;
5330:         }
5331:       }
5332:       /* put together the new matrix */
5333:       PetscCall(MatCreateSeqAIJWithArrays(PETSC_COMM_SELF, am, dn + on, ci, cj, ca, A_loc));
5334:       /* MatCreateSeqAIJWithArrays flags matrix so PETSc doesn't free the user's arrays. */
5335:       /* Since these are PETSc arrays, change flags to free them as necessary. */
5336:       c          = (Mat_SeqAIJ *)(*A_loc)->data;
5337:       c->free_a  = PETSC_TRUE;
5338:       c->free_ij = PETSC_TRUE;
5339:       c->nonew   = 0;
5340:       PetscCall(MatSetType(*A_loc, ((PetscObject)Ad)->type_name));
5341:     } else if (scall == MAT_REUSE_MATRIX) {
5342:       PetscCall(MatSeqAIJGetArrayWrite(*A_loc, &ca));
5343:       for (i = 0; i < am; i++) {
5344:         const PetscInt ncols_d = ai[i + 1] - ai[i];
5345:         const PetscInt ncols_o = bi[i + 1] - bi[i];
5346:         /* diagonal portion of A */
5347:         for (j = 0; j < ncols_d; j++) *ca++ = *aa++;
5348:         /* off-diagonal portion of A */
5349:         for (j = 0; j < ncols_o; j++) *ca++ = *ba++;
5350:       }
5351:       PetscCall(MatSeqAIJRestoreArrayWrite(*A_loc, &ca));
5352:     } else SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Invalid MatReuse %d", (int)scall);
5353:     PetscCall(MatSeqAIJRestoreArrayRead(Ad, &aa));
5354:     PetscCall(MatSeqAIJRestoreArrayRead(Ao, &aa));
5355:     if (glob) {
5356:       PetscInt cst, *gidx;

5358:       PetscCall(MatGetOwnershipRangeColumn(A, &cst, NULL));
5359:       PetscCall(PetscMalloc1(dn + on, &gidx));
5360:       for (i = 0; i < dn; i++) gidx[i] = cst + i;
5361:       for (i = 0; i < on; i++) gidx[i + dn] = cmap[i];
5362:       PetscCall(ISCreateGeneral(PetscObjectComm((PetscObject)Ad), dn + on, gidx, PETSC_OWN_POINTER, glob));
5363:     }
5364:   }
5365:   PetscCall(PetscLogEventEnd(MAT_Getlocalmat, A, 0, 0, 0));
5366:   PetscFunctionReturn(PETSC_SUCCESS);
5367: }

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

5372:   Not Collective

5374:   Input Parameters:
5375: + A     - the matrix
5376: . scall - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`
5377: . row   - index set of rows to extract (or `NULL`)
5378: - col   - index set of columns to extract (or `NULL`)

5380:   Output Parameter:
5381: . A_loc - the local sequential matrix generated

5383:   Level: developer

5385: .seealso: [](ch_matrices), `Mat`, `MATMPIAIJ`, `MatGetOwnershipRange()`, `MatMPIAIJGetLocalMat()`
5386: @*/
5387: PetscErrorCode MatMPIAIJGetLocalMatCondensed(Mat A, MatReuse scall, IS *row, IS *col, Mat *A_loc)
5388: {
5389:   Mat_MPIAIJ *a = (Mat_MPIAIJ *)A->data;
5390:   PetscInt    i, start, end, ncols, nzA, nzB, *cmap, imark, *idx;
5391:   IS          isrowa, iscola;
5392:   Mat        *aloc;
5393:   PetscBool   match;

5395:   PetscFunctionBegin;
5396:   PetscCall(PetscObjectTypeCompare((PetscObject)A, MATMPIAIJ, &match));
5397:   PetscCheck(match, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "Requires MATMPIAIJ matrix as input");
5398:   PetscCall(PetscLogEventBegin(MAT_Getlocalmatcondensed, A, 0, 0, 0));
5399:   if (!row) {
5400:     start = A->rmap->rstart;
5401:     end   = A->rmap->rend;
5402:     PetscCall(ISCreateStride(PETSC_COMM_SELF, end - start, start, 1, &isrowa));
5403:   } else {
5404:     isrowa = *row;
5405:   }
5406:   if (!col) {
5407:     start = A->cmap->rstart;
5408:     cmap  = a->garray;
5409:     nzA   = a->A->cmap->n;
5410:     nzB   = a->B->cmap->n;
5411:     PetscCall(PetscMalloc1(nzA + nzB, &idx));
5412:     ncols = 0;
5413:     for (i = 0; i < nzB; i++) {
5414:       if (cmap[i] < start) idx[ncols++] = cmap[i];
5415:       else break;
5416:     }
5417:     imark = i;
5418:     for (i = 0; i < nzA; i++) idx[ncols++] = start + i;
5419:     for (i = imark; i < nzB; i++) idx[ncols++] = cmap[i];
5420:     PetscCall(ISCreateGeneral(PETSC_COMM_SELF, ncols, idx, PETSC_OWN_POINTER, &iscola));
5421:   } else {
5422:     iscola = *col;
5423:   }
5424:   if (scall != MAT_INITIAL_MATRIX) {
5425:     PetscCall(PetscMalloc1(1, &aloc));
5426:     aloc[0] = *A_loc;
5427:   }
5428:   PetscCall(MatCreateSubMatrices(A, 1, &isrowa, &iscola, scall, &aloc));
5429:   if (!col) { /* attach global id of condensed columns */
5430:     PetscCall(PetscObjectCompose((PetscObject)aloc[0], "_petsc_GetLocalMatCondensed_iscol", (PetscObject)iscola));
5431:   }
5432:   *A_loc = aloc[0];
5433:   PetscCall(PetscFree(aloc));
5434:   if (!row) PetscCall(ISDestroy(&isrowa));
5435:   if (!col) PetscCall(ISDestroy(&iscola));
5436:   PetscCall(PetscLogEventEnd(MAT_Getlocalmatcondensed, A, 0, 0, 0));
5437:   PetscFunctionReturn(PETSC_SUCCESS);
5438: }

5440: /*
5441:  * Create a sequential AIJ matrix based on row indices. a whole column is extracted once a row is matched.
5442:  * Row could be local or remote.The routine is designed to be scalable in memory so that nothing is based
5443:  * on a global size.
5444:  * */
5445: static PetscErrorCode MatCreateSeqSubMatrixWithRows_Private(Mat P, IS rows, Mat *P_oth)
5446: {
5447:   Mat_MPIAIJ            *p  = (Mat_MPIAIJ *)P->data;
5448:   Mat_SeqAIJ            *pd = (Mat_SeqAIJ *)p->A->data, *po = (Mat_SeqAIJ *)p->B->data, *p_oth;
5449:   PetscInt               plocalsize, nrows, *ilocal, *oilocal, i, lidx, *nrcols, *nlcols, ncol;
5450:   PetscMPIInt            owner;
5451:   PetscSFNode           *iremote, *oiremote;
5452:   const PetscInt        *lrowindices;
5453:   PetscSF                sf, osf;
5454:   PetscInt               pcstart, *roffsets, *loffsets, *pnnz, j;
5455:   PetscInt               ontotalcols, dntotalcols, ntotalcols, nout;
5456:   MPI_Comm               comm;
5457:   ISLocalToGlobalMapping mapping;
5458:   const PetscScalar     *pd_a, *po_a;

5460:   PetscFunctionBegin;
5461:   PetscCall(PetscObjectGetComm((PetscObject)P, &comm));
5462:   /* plocalsize is the number of roots
5463:    * nrows is the number of leaves
5464:    * */
5465:   PetscCall(MatGetLocalSize(P, &plocalsize, NULL));
5466:   PetscCall(ISGetLocalSize(rows, &nrows));
5467:   PetscCall(PetscCalloc1(nrows, &iremote));
5468:   PetscCall(ISGetIndices(rows, &lrowindices));
5469:   for (i = 0; i < nrows; i++) {
5470:     /* Find a remote index and an owner for a row
5471:      * The row could be local or remote
5472:      * */
5473:     owner = 0;
5474:     lidx  = 0;
5475:     PetscCall(PetscLayoutFindOwnerIndex(P->rmap, lrowindices[i], &owner, &lidx));
5476:     iremote[i].index = lidx;
5477:     iremote[i].rank  = owner;
5478:   }
5479:   /* Create SF to communicate how many nonzero columns for each row */
5480:   PetscCall(PetscSFCreate(comm, &sf));
5481:   /* SF will figure out the number of nonzero columns for each row, and their
5482:    * offsets
5483:    * */
5484:   PetscCall(PetscSFSetGraph(sf, plocalsize, nrows, NULL, PETSC_OWN_POINTER, iremote, PETSC_OWN_POINTER));
5485:   PetscCall(PetscSFSetFromOptions(sf));
5486:   PetscCall(PetscSFSetUp(sf));

5488:   PetscCall(PetscCalloc1(2 * (plocalsize + 1), &roffsets));
5489:   PetscCall(PetscCalloc1(2 * plocalsize, &nrcols));
5490:   PetscCall(PetscCalloc1(nrows, &pnnz));
5491:   roffsets[0] = 0;
5492:   roffsets[1] = 0;
5493:   for (i = 0; i < plocalsize; i++) {
5494:     /* diagonal */
5495:     nrcols[i * 2 + 0] = pd->i[i + 1] - pd->i[i];
5496:     /* off-diagonal */
5497:     nrcols[i * 2 + 1] = po->i[i + 1] - po->i[i];
5498:     /* compute offsets so that we relative location for each row */
5499:     roffsets[(i + 1) * 2 + 0] = roffsets[i * 2 + 0] + nrcols[i * 2 + 0];
5500:     roffsets[(i + 1) * 2 + 1] = roffsets[i * 2 + 1] + nrcols[i * 2 + 1];
5501:   }
5502:   PetscCall(PetscCalloc1(2 * nrows, &nlcols));
5503:   PetscCall(PetscCalloc1(2 * nrows, &loffsets));
5504:   /* 'r' means root, and 'l' means leaf */
5505:   PetscCall(PetscSFBcastBegin(sf, MPIU_2INT, nrcols, nlcols, MPI_REPLACE));
5506:   PetscCall(PetscSFBcastBegin(sf, MPIU_2INT, roffsets, loffsets, MPI_REPLACE));
5507:   PetscCall(PetscSFBcastEnd(sf, MPIU_2INT, nrcols, nlcols, MPI_REPLACE));
5508:   PetscCall(PetscSFBcastEnd(sf, MPIU_2INT, roffsets, loffsets, MPI_REPLACE));
5509:   PetscCall(PetscSFDestroy(&sf));
5510:   PetscCall(PetscFree(roffsets));
5511:   PetscCall(PetscFree(nrcols));
5512:   dntotalcols = 0;
5513:   ontotalcols = 0;
5514:   ncol        = 0;
5515:   for (i = 0; i < nrows; i++) {
5516:     pnnz[i] = nlcols[i * 2 + 0] + nlcols[i * 2 + 1];
5517:     ncol    = PetscMax(pnnz[i], ncol);
5518:     /* diagonal */
5519:     dntotalcols += nlcols[i * 2 + 0];
5520:     /* off-diagonal */
5521:     ontotalcols += nlcols[i * 2 + 1];
5522:   }
5523:   /* We do not need to figure the right number of columns
5524:    * since all the calculations will be done by going through the raw data
5525:    * */
5526:   PetscCall(MatCreateSeqAIJ(PETSC_COMM_SELF, nrows, ncol, 0, pnnz, P_oth));
5527:   PetscCall(MatSetUp(*P_oth));
5528:   PetscCall(PetscFree(pnnz));
5529:   p_oth = (Mat_SeqAIJ *)(*P_oth)->data;
5530:   /* diagonal */
5531:   PetscCall(PetscCalloc1(dntotalcols, &iremote));
5532:   /* off-diagonal */
5533:   PetscCall(PetscCalloc1(ontotalcols, &oiremote));
5534:   /* diagonal */
5535:   PetscCall(PetscCalloc1(dntotalcols, &ilocal));
5536:   /* off-diagonal */
5537:   PetscCall(PetscCalloc1(ontotalcols, &oilocal));
5538:   dntotalcols = 0;
5539:   ontotalcols = 0;
5540:   ntotalcols  = 0;
5541:   for (i = 0; i < nrows; i++) {
5542:     owner = 0;
5543:     PetscCall(PetscLayoutFindOwnerIndex(P->rmap, lrowindices[i], &owner, NULL));
5544:     /* Set iremote for diag matrix */
5545:     for (j = 0; j < nlcols[i * 2 + 0]; j++) {
5546:       iremote[dntotalcols].index = loffsets[i * 2 + 0] + j;
5547:       iremote[dntotalcols].rank  = owner;
5548:       /* P_oth is seqAIJ so that ilocal need to point to the first part of memory */
5549:       ilocal[dntotalcols++] = ntotalcols++;
5550:     }
5551:     /* off-diagonal */
5552:     for (j = 0; j < nlcols[i * 2 + 1]; j++) {
5553:       oiremote[ontotalcols].index = loffsets[i * 2 + 1] + j;
5554:       oiremote[ontotalcols].rank  = owner;
5555:       oilocal[ontotalcols++]      = ntotalcols++;
5556:     }
5557:   }
5558:   PetscCall(ISRestoreIndices(rows, &lrowindices));
5559:   PetscCall(PetscFree(loffsets));
5560:   PetscCall(PetscFree(nlcols));
5561:   PetscCall(PetscSFCreate(comm, &sf));
5562:   /* P serves as roots and P_oth is leaves
5563:    * Diag matrix
5564:    * */
5565:   PetscCall(PetscSFSetGraph(sf, pd->i[plocalsize], dntotalcols, ilocal, PETSC_OWN_POINTER, iremote, PETSC_OWN_POINTER));
5566:   PetscCall(PetscSFSetFromOptions(sf));
5567:   PetscCall(PetscSFSetUp(sf));

5569:   PetscCall(PetscSFCreate(comm, &osf));
5570:   /* off-diagonal */
5571:   PetscCall(PetscSFSetGraph(osf, po->i[plocalsize], ontotalcols, oilocal, PETSC_OWN_POINTER, oiremote, PETSC_OWN_POINTER));
5572:   PetscCall(PetscSFSetFromOptions(osf));
5573:   PetscCall(PetscSFSetUp(osf));
5574:   PetscCall(MatSeqAIJGetArrayRead(p->A, &pd_a));
5575:   PetscCall(MatSeqAIJGetArrayRead(p->B, &po_a));
5576:   /* operate on the matrix internal data to save memory */
5577:   PetscCall(PetscSFBcastBegin(sf, MPIU_SCALAR, pd_a, p_oth->a, MPI_REPLACE));
5578:   PetscCall(PetscSFBcastBegin(osf, MPIU_SCALAR, po_a, p_oth->a, MPI_REPLACE));
5579:   PetscCall(MatGetOwnershipRangeColumn(P, &pcstart, NULL));
5580:   /* Convert to global indices for diag matrix */
5581:   for (i = 0; i < pd->i[plocalsize]; i++) pd->j[i] += pcstart;
5582:   PetscCall(PetscSFBcastBegin(sf, MPIU_INT, pd->j, p_oth->j, MPI_REPLACE));
5583:   /* We want P_oth store global indices */
5584:   PetscCall(ISLocalToGlobalMappingCreate(comm, 1, p->B->cmap->n, p->garray, PETSC_COPY_VALUES, &mapping));
5585:   /* Use memory scalable approach */
5586:   PetscCall(ISLocalToGlobalMappingSetType(mapping, ISLOCALTOGLOBALMAPPINGHASH));
5587:   PetscCall(ISLocalToGlobalMappingApply(mapping, po->i[plocalsize], po->j, po->j));
5588:   PetscCall(PetscSFBcastBegin(osf, MPIU_INT, po->j, p_oth->j, MPI_REPLACE));
5589:   PetscCall(PetscSFBcastEnd(sf, MPIU_INT, pd->j, p_oth->j, MPI_REPLACE));
5590:   /* Convert back to local indices */
5591:   for (i = 0; i < pd->i[plocalsize]; i++) pd->j[i] -= pcstart;
5592:   PetscCall(PetscSFBcastEnd(osf, MPIU_INT, po->j, p_oth->j, MPI_REPLACE));
5593:   nout = 0;
5594:   PetscCall(ISGlobalToLocalMappingApply(mapping, IS_GTOLM_DROP, po->i[plocalsize], po->j, &nout, po->j));
5595:   PetscCheck(nout == po->i[plocalsize], comm, PETSC_ERR_ARG_INCOMP, "n %" PetscInt_FMT " does not equal to nout %" PetscInt_FMT " ", po->i[plocalsize], nout);
5596:   PetscCall(ISLocalToGlobalMappingDestroy(&mapping));
5597:   /* Exchange values */
5598:   PetscCall(PetscSFBcastEnd(sf, MPIU_SCALAR, pd_a, p_oth->a, MPI_REPLACE));
5599:   PetscCall(PetscSFBcastEnd(osf, MPIU_SCALAR, po_a, p_oth->a, MPI_REPLACE));
5600:   PetscCall(MatSeqAIJRestoreArrayRead(p->A, &pd_a));
5601:   PetscCall(MatSeqAIJRestoreArrayRead(p->B, &po_a));
5602:   /* Stop PETSc from shrinking memory */
5603:   for (i = 0; i < nrows; i++) p_oth->ilen[i] = p_oth->imax[i];
5604:   PetscCall(MatAssemblyBegin(*P_oth, MAT_FINAL_ASSEMBLY));
5605:   PetscCall(MatAssemblyEnd(*P_oth, MAT_FINAL_ASSEMBLY));
5606:   /* Attach PetscSF objects to P_oth so that we can reuse it later */
5607:   PetscCall(PetscObjectCompose((PetscObject)*P_oth, "diagsf", (PetscObject)sf));
5608:   PetscCall(PetscObjectCompose((PetscObject)*P_oth, "offdiagsf", (PetscObject)osf));
5609:   PetscCall(PetscSFDestroy(&sf));
5610:   PetscCall(PetscSFDestroy(&osf));
5611:   PetscFunctionReturn(PETSC_SUCCESS);
5612: }

5614: /*
5615:  * Creates a SeqAIJ matrix by taking rows of B that equal to nonzero columns of local A
5616:  * This supports MPIAIJ and MAIJ
5617:  * */
5618: PetscErrorCode MatGetBrowsOfAcols_MPIXAIJ(Mat A, Mat P, PetscInt dof, MatReuse reuse, Mat *P_oth)
5619: {
5620:   Mat_MPIAIJ *a = (Mat_MPIAIJ *)A->data, *p = (Mat_MPIAIJ *)P->data;
5621:   Mat_SeqAIJ *p_oth;
5622:   IS          rows, map;
5623:   PetscHMapI  hamp;
5624:   PetscInt    i, htsize, *rowindices, off, *mapping, key, count;
5625:   MPI_Comm    comm;
5626:   PetscSF     sf, osf;
5627:   PetscBool   has;

5629:   PetscFunctionBegin;
5630:   PetscCall(PetscObjectGetComm((PetscObject)A, &comm));
5631:   PetscCall(PetscLogEventBegin(MAT_GetBrowsOfAocols, A, P, 0, 0));
5632:   /* If it is the first time, create an index set of off-diag nonzero columns of A,
5633:    *  and then create a submatrix (that often is an overlapping matrix)
5634:    * */
5635:   if (reuse == MAT_INITIAL_MATRIX) {
5636:     /* Use a hash table to figure out unique keys */
5637:     PetscCall(PetscHMapICreateWithSize(a->B->cmap->n, &hamp));
5638:     PetscCall(PetscCalloc1(a->B->cmap->n, &mapping));
5639:     count = 0;
5640:     /* Assume that  a->g is sorted, otherwise the following does not make sense */
5641:     for (i = 0; i < a->B->cmap->n; i++) {
5642:       key = a->garray[i] / dof;
5643:       PetscCall(PetscHMapIHas(hamp, key, &has));
5644:       if (!has) {
5645:         mapping[i] = count;
5646:         PetscCall(PetscHMapISet(hamp, key, count++));
5647:       } else {
5648:         /* Current 'i' has the same value the previous step */
5649:         mapping[i] = count - 1;
5650:       }
5651:     }
5652:     PetscCall(ISCreateGeneral(comm, a->B->cmap->n, mapping, PETSC_OWN_POINTER, &map));
5653:     PetscCall(PetscHMapIGetSize(hamp, &htsize));
5654:     PetscCheck(htsize == count, comm, PETSC_ERR_ARG_INCOMP, " Size of hash map %" PetscInt_FMT " is inconsistent with count %" PetscInt_FMT, htsize, count);
5655:     PetscCall(PetscCalloc1(htsize, &rowindices));
5656:     off = 0;
5657:     PetscCall(PetscHMapIGetKeys(hamp, &off, rowindices));
5658:     PetscCall(PetscHMapIDestroy(&hamp));
5659:     PetscCall(PetscSortInt(htsize, rowindices));
5660:     PetscCall(ISCreateGeneral(comm, htsize, rowindices, PETSC_OWN_POINTER, &rows));
5661:     /* In case, the matrix was already created but users want to recreate the matrix */
5662:     PetscCall(MatDestroy(P_oth));
5663:     PetscCall(MatCreateSeqSubMatrixWithRows_Private(P, rows, P_oth));
5664:     PetscCall(PetscObjectCompose((PetscObject)*P_oth, "aoffdiagtopothmapping", (PetscObject)map));
5665:     PetscCall(ISDestroy(&map));
5666:     PetscCall(ISDestroy(&rows));
5667:   } else if (reuse == MAT_REUSE_MATRIX) {
5668:     /* If matrix was already created, we simply update values using SF objects
5669:      * that as attached to the matrix earlier.
5670:      */
5671:     const PetscScalar *pd_a, *po_a;

5673:     PetscCall(PetscObjectQuery((PetscObject)*P_oth, "diagsf", (PetscObject *)&sf));
5674:     PetscCall(PetscObjectQuery((PetscObject)*P_oth, "offdiagsf", (PetscObject *)&osf));
5675:     PetscCheck(sf && osf, comm, PETSC_ERR_ARG_NULL, "Matrix is not initialized yet");
5676:     p_oth = (Mat_SeqAIJ *)(*P_oth)->data;
5677:     /* Update values in place */
5678:     PetscCall(MatSeqAIJGetArrayRead(p->A, &pd_a));
5679:     PetscCall(MatSeqAIJGetArrayRead(p->B, &po_a));
5680:     PetscCall(PetscSFBcastBegin(sf, MPIU_SCALAR, pd_a, p_oth->a, MPI_REPLACE));
5681:     PetscCall(PetscSFBcastBegin(osf, MPIU_SCALAR, po_a, p_oth->a, MPI_REPLACE));
5682:     PetscCall(PetscSFBcastEnd(sf, MPIU_SCALAR, pd_a, p_oth->a, MPI_REPLACE));
5683:     PetscCall(PetscSFBcastEnd(osf, MPIU_SCALAR, po_a, p_oth->a, MPI_REPLACE));
5684:     PetscCall(MatSeqAIJRestoreArrayRead(p->A, &pd_a));
5685:     PetscCall(MatSeqAIJRestoreArrayRead(p->B, &po_a));
5686:   } else SETERRQ(comm, PETSC_ERR_ARG_UNKNOWN_TYPE, "Unknown reuse type");
5687:   PetscCall(PetscLogEventEnd(MAT_GetBrowsOfAocols, A, P, 0, 0));
5688:   PetscFunctionReturn(PETSC_SUCCESS);
5689: }

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

5694:   Collective

5696:   Input Parameters:
5697: + A     - the first matrix in `MATMPIAIJ` format
5698: . B     - the second matrix in `MATMPIAIJ` format
5699: - scall - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`

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

5706:   Level: developer

5708: .seealso: `Mat`, `MATMPIAIJ`, `IS`, `MatReuse`
5709: @*/
5710: PetscErrorCode MatGetBrowsOfAcols(Mat A, Mat B, MatReuse scall, IS *rowb, IS *colb, Mat *B_seq)
5711: {
5712:   Mat_MPIAIJ *a = (Mat_MPIAIJ *)A->data;
5713:   PetscInt   *idx, i, start, ncols, nzA, nzB, *cmap, imark;
5714:   IS          isrowb, iscolb;
5715:   Mat        *bseq = NULL;

5717:   PetscFunctionBegin;
5718:   PetscCheck(A->cmap->rstart == B->rmap->rstart && A->cmap->rend == B->rmap->rend, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Matrix local dimensions are incompatible, (%" PetscInt_FMT ", %" PetscInt_FMT ") != (%" PetscInt_FMT ",%" PetscInt_FMT ")",
5719:              A->cmap->rstart, A->cmap->rend, B->rmap->rstart, B->rmap->rend);
5720:   PetscCall(PetscLogEventBegin(MAT_GetBrowsOfAcols, A, B, 0, 0));

5722:   if (scall == MAT_INITIAL_MATRIX) {
5723:     start = A->cmap->rstart;
5724:     cmap  = a->garray;
5725:     nzA   = a->A->cmap->n;
5726:     nzB   = a->B->cmap->n;
5727:     PetscCall(PetscMalloc1(nzA + nzB, &idx));
5728:     ncols = 0;
5729:     for (i = 0; i < nzB; i++) { /* row < local row index */
5730:       if (cmap[i] < start) idx[ncols++] = cmap[i];
5731:       else break;
5732:     }
5733:     imark = i;
5734:     for (i = 0; i < nzA; i++) idx[ncols++] = start + i;   /* local rows */
5735:     for (i = imark; i < nzB; i++) idx[ncols++] = cmap[i]; /* row > local row index */
5736:     PetscCall(ISCreateGeneral(PETSC_COMM_SELF, ncols, idx, PETSC_OWN_POINTER, &isrowb));
5737:     PetscCall(ISCreateStride(PETSC_COMM_SELF, B->cmap->N, 0, 1, &iscolb));
5738:   } else {
5739:     PetscCheck(rowb && colb, PETSC_COMM_SELF, PETSC_ERR_SUP, "IS rowb and colb must be provided for MAT_REUSE_MATRIX");
5740:     isrowb = *rowb;
5741:     iscolb = *colb;
5742:     PetscCall(PetscMalloc1(1, &bseq));
5743:     bseq[0] = *B_seq;
5744:   }
5745:   PetscCall(MatCreateSubMatrices(B, 1, &isrowb, &iscolb, scall, &bseq));
5746:   *B_seq = bseq[0];
5747:   PetscCall(PetscFree(bseq));
5748:   if (!rowb) {
5749:     PetscCall(ISDestroy(&isrowb));
5750:   } else {
5751:     *rowb = isrowb;
5752:   }
5753:   if (!colb) {
5754:     PetscCall(ISDestroy(&iscolb));
5755:   } else {
5756:     *colb = iscolb;
5757:   }
5758:   PetscCall(PetscLogEventEnd(MAT_GetBrowsOfAcols, A, B, 0, 0));
5759:   PetscFunctionReturn(PETSC_SUCCESS);
5760: }

5762: // PetscClangLinter pragma disable: -fdoc-sowing-chars
5763: /*
5764:   MatGetBrowsOfAoCols_MPIAIJ - Creates a `MATSEQAIJ` matrix by taking rows of B that equal to nonzero columns
5765:   of the OFF-DIAGONAL portion of local A

5767:   Collective

5769:   Input Parameters:
5770: + A     - the first matrix in `MATMPIAIJ` format
5771: . B     - the second matrix in `MATMPIAIJ` format
5772: - scall - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`

5774:   Output Parameters:
5775: + startsj_s - starting point in B's sending j-arrays, saved for MAT_REUSE (or NULL)
5776: . startsj_r - starting point in B's receiving j-arrays, saved for MAT_REUSE (or NULL)
5777: . bufa_ptr  - array for sending matrix values, saved for MAT_REUSE (or NULL)
5778: - B_oth     - the sequential matrix generated with size aBn=a->B->cmap->n by B->cmap->N

5780:   Level: developer

5782:   Developer Note:
5783:   This directly accesses information inside the VecScatter associated with the matrix-vector product
5784:   for this matrix. This is not desirable.

5786: .seealso: [](ch_mat), `Mat`, `MATMPIAIJ`
5787: */
5788: PetscErrorCode MatGetBrowsOfAoCols_MPIAIJ(Mat A, Mat B, MatReuse scall, PetscInt **startsj_s, PetscInt **startsj_r, MatScalar **bufa_ptr, Mat *B_oth)
5789: {
5790:   Mat_MPIAIJ        *a = (Mat_MPIAIJ *)A->data;
5791:   VecScatter         ctx;
5792:   MPI_Comm           comm;
5793:   const PetscMPIInt *rprocs, *sprocs;
5794:   PetscMPIInt        nrecvs, nsends;
5795:   const PetscInt    *srow, *rstarts, *sstarts;
5796:   PetscInt          *rowlen, *bufj, *bufJ, ncols = 0, aBn = a->B->cmap->n, row, *b_othi, *b_othj, *rvalues = NULL, *svalues = NULL, *cols, sbs, rbs;
5797:   PetscInt           i, j, k = 0, l, ll, nrows, *rstartsj = NULL, *sstartsj, len;
5798:   PetscScalar       *b_otha, *bufa, *bufA, *vals = NULL;
5799:   MPI_Request       *reqs = NULL, *rwaits = NULL, *swaits = NULL;
5800:   PetscMPIInt        size, tag, rank, nreqs;

5802:   PetscFunctionBegin;
5803:   PetscCall(PetscObjectGetComm((PetscObject)A, &comm));
5804:   PetscCallMPI(MPI_Comm_size(comm, &size));

5806:   PetscCheck(A->cmap->rstart == B->rmap->rstart && A->cmap->rend == B->rmap->rend, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Matrix local dimensions are incompatible, (%" PetscInt_FMT ", %" PetscInt_FMT ") != (%" PetscInt_FMT ",%" PetscInt_FMT ")",
5807:              A->cmap->rstart, A->cmap->rend, B->rmap->rstart, B->rmap->rend);
5808:   PetscCall(PetscLogEventBegin(MAT_GetBrowsOfAocols, A, B, 0, 0));
5809:   PetscCallMPI(MPI_Comm_rank(comm, &rank));

5811:   if (size == 1) {
5812:     startsj_s = NULL;
5813:     bufa_ptr  = NULL;
5814:     *B_oth    = NULL;
5815:     PetscFunctionReturn(PETSC_SUCCESS);
5816:   }

5818:   ctx = a->Mvctx;
5819:   tag = ((PetscObject)ctx)->tag;

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

5829:   if (!startsj_s || !bufa_ptr) scall = MAT_INITIAL_MATRIX;
5830:   if (scall == MAT_INITIAL_MATRIX) {
5831:     /* i-array */
5832:     /*  post receives */
5833:     if (nrecvs) PetscCall(PetscMalloc1(rbs * (rstarts[nrecvs] - rstarts[0]), &rvalues)); /* rstarts can be NULL when nrecvs=0 */
5834:     for (i = 0; i < nrecvs; i++) {
5835:       rowlen = rvalues + rstarts[i] * rbs;
5836:       nrows  = (rstarts[i + 1] - rstarts[i]) * rbs; /* num of indices to be received */
5837:       PetscCallMPI(MPIU_Irecv(rowlen, nrows, MPIU_INT, rprocs[i], tag, comm, rwaits + i));
5838:     }

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

5843:     sstartsj[0] = 0;
5844:     rstartsj[0] = 0;
5845:     len         = 0; /* total length of j or a array to be sent */
5846:     if (nsends) {
5847:       k = sstarts[0]; /* ATTENTION: sstarts[0] and rstarts[0] are not necessarily zero */
5848:       PetscCall(PetscMalloc1(sbs * (sstarts[nsends] - sstarts[0]), &svalues));
5849:     }
5850:     for (i = 0; i < nsends; i++) {
5851:       rowlen = svalues + (sstarts[i] - sstarts[0]) * sbs;
5852:       nrows  = sstarts[i + 1] - sstarts[i]; /* num of block rows */
5853:       for (j = 0; j < nrows; j++) {
5854:         row = srow[k] + B->rmap->range[rank]; /* global row idx */
5855:         for (l = 0; l < sbs; l++) {
5856:           PetscCall(MatGetRow_MPIAIJ(B, row + l, &ncols, NULL, NULL)); /* rowlength */

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

5860:           len += ncols;
5861:           PetscCall(MatRestoreRow_MPIAIJ(B, row + l, &ncols, NULL, NULL));
5862:         }
5863:         k++;
5864:       }
5865:       PetscCallMPI(MPIU_Isend(rowlen, nrows * sbs, MPIU_INT, sprocs[i], tag, comm, swaits + i));

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

5873:     /* allocate buffers for sending j and a arrays */
5874:     PetscCall(PetscMalloc1(len, &bufj));
5875:     PetscCall(PetscMalloc1(len, &bufa));

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

5880:     b_othi[0] = 0;
5881:     len       = 0; /* total length of j or a array to be received */
5882:     k         = 0;
5883:     for (i = 0; i < nrecvs; i++) {
5884:       rowlen = rvalues + (rstarts[i] - rstarts[0]) * rbs;
5885:       nrows  = (rstarts[i + 1] - rstarts[i]) * rbs; /* num of rows to be received */
5886:       for (j = 0; j < nrows; j++) {
5887:         b_othi[k + 1] = b_othi[k] + rowlen[j];
5888:         PetscCall(PetscIntSumError(rowlen[j], len, &len));
5889:         k++;
5890:       }
5891:       rstartsj[i + 1] = len; /* starting point of (i+1)-th incoming msg in bufj and bufa */
5892:     }
5893:     PetscCall(PetscFree(rvalues));

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

5899:     /* j-array */
5900:     /*  post receives of j-array */
5901:     for (i = 0; i < nrecvs; i++) {
5902:       nrows = rstartsj[i + 1] - rstartsj[i]; /* length of the msg received */
5903:       PetscCallMPI(MPIU_Irecv(PetscSafePointerPlusOffset(b_othj, rstartsj[i]), nrows, MPIU_INT, rprocs[i], tag, comm, rwaits + i));
5904:     }

5906:     /* pack the outgoing message j-array */
5907:     if (nsends) k = sstarts[0];
5908:     for (i = 0; i < nsends; i++) {
5909:       nrows = sstarts[i + 1] - sstarts[i]; /* num of block rows */
5910:       bufJ  = PetscSafePointerPlusOffset(bufj, sstartsj[i]);
5911:       for (j = 0; j < nrows; j++) {
5912:         row = srow[k++] + B->rmap->range[rank]; /* global row idx */
5913:         for (ll = 0; ll < sbs; ll++) {
5914:           PetscCall(MatGetRow_MPIAIJ(B, row + ll, &ncols, &cols, NULL));
5915:           for (l = 0; l < ncols; l++) *bufJ++ = cols[l];
5916:           PetscCall(MatRestoreRow_MPIAIJ(B, row + ll, &ncols, &cols, NULL));
5917:         }
5918:       }
5919:       PetscCallMPI(MPIU_Isend(PetscSafePointerPlusOffset(bufj, sstartsj[i]), sstartsj[i + 1] - sstartsj[i], MPIU_INT, sprocs[i], tag, comm, swaits + i));
5920:     }

5922:     /* recvs and sends of j-array are completed */
5923:     if (nreqs) PetscCallMPI(MPI_Waitall(nreqs, reqs, MPI_STATUSES_IGNORE));
5924:   } else if (scall == MAT_REUSE_MATRIX) {
5925:     sstartsj = *startsj_s;
5926:     rstartsj = *startsj_r;
5927:     bufa     = *bufa_ptr;
5928:     PetscCall(MatSeqAIJGetArrayWrite(*B_oth, &b_otha));
5929:   } else SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Matrix P does not possess an object container");

5931:   /* a-array */
5932:   /*  post receives of a-array */
5933:   for (i = 0; i < nrecvs; i++) {
5934:     nrows = rstartsj[i + 1] - rstartsj[i]; /* length of the msg received */
5935:     PetscCallMPI(MPIU_Irecv(PetscSafePointerPlusOffset(b_otha, rstartsj[i]), nrows, MPIU_SCALAR, rprocs[i], tag, comm, rwaits + i));
5936:   }

5938:   /* pack the outgoing message a-array */
5939:   if (nsends) k = sstarts[0];
5940:   for (i = 0; i < nsends; i++) {
5941:     nrows = sstarts[i + 1] - sstarts[i]; /* num of block rows */
5942:     bufA  = PetscSafePointerPlusOffset(bufa, sstartsj[i]);
5943:     for (j = 0; j < nrows; j++) {
5944:       row = srow[k++] + B->rmap->range[rank]; /* global row idx */
5945:       for (ll = 0; ll < sbs; ll++) {
5946:         PetscCall(MatGetRow_MPIAIJ(B, row + ll, &ncols, NULL, &vals));
5947:         for (l = 0; l < ncols; l++) *bufA++ = vals[l];
5948:         PetscCall(MatRestoreRow_MPIAIJ(B, row + ll, &ncols, NULL, &vals));
5949:       }
5950:     }
5951:     PetscCallMPI(MPIU_Isend(PetscSafePointerPlusOffset(bufa, sstartsj[i]), sstartsj[i + 1] - sstartsj[i], MPIU_SCALAR, sprocs[i], tag, comm, swaits + i));
5952:   }
5953:   /* recvs and sends of a-array are completed */
5954:   if (nreqs) PetscCallMPI(MPI_Waitall(nreqs, reqs, MPI_STATUSES_IGNORE));
5955:   PetscCall(PetscFree(reqs));

5957:   if (scall == MAT_INITIAL_MATRIX) {
5958:     Mat_SeqAIJ *b_oth;

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

5963:     /* MatCreateSeqAIJWithArrays flags matrix so PETSc doesn't free the user's arrays. */
5964:     /* Since these are PETSc arrays, change flags to free them as necessary. */
5965:     b_oth          = (Mat_SeqAIJ *)(*B_oth)->data;
5966:     b_oth->free_a  = PETSC_TRUE;
5967:     b_oth->free_ij = PETSC_TRUE;
5968:     b_oth->nonew   = 0;

5970:     PetscCall(PetscFree(bufj));
5971:     if (!startsj_s || !bufa_ptr) {
5972:       PetscCall(PetscFree2(sstartsj, rstartsj));
5973:       PetscCall(PetscFree(bufa_ptr));
5974:     } else {
5975:       *startsj_s = sstartsj;
5976:       *startsj_r = rstartsj;
5977:       *bufa_ptr  = bufa;
5978:     }
5979:   } else if (scall == MAT_REUSE_MATRIX) {
5980:     PetscCall(MatSeqAIJRestoreArrayWrite(*B_oth, &b_otha));
5981:   }

5983:   PetscCall(VecScatterRestoreRemote_Private(ctx, PETSC_TRUE, &nsends, &sstarts, &srow, &sprocs, &sbs));
5984:   PetscCall(VecScatterRestoreRemoteOrdered_Private(ctx, PETSC_FALSE, &nrecvs, &rstarts, NULL, &rprocs, &rbs));
5985:   PetscCall(PetscLogEventEnd(MAT_GetBrowsOfAocols, A, B, 0, 0));
5986:   PetscFunctionReturn(PETSC_SUCCESS);
5987: }

5989: PETSC_INTERN PetscErrorCode MatConvert_MPIAIJ_MPIAIJCRL(Mat, MatType, MatReuse, Mat *);
5990: PETSC_INTERN PetscErrorCode MatConvert_MPIAIJ_MPIAIJPERM(Mat, MatType, MatReuse, Mat *);
5991: PETSC_INTERN PetscErrorCode MatConvert_MPIAIJ_MPIAIJSELL(Mat, MatType, MatReuse, Mat *);
5992: #if defined(PETSC_HAVE_MKL_SPARSE)
5993: PETSC_INTERN PetscErrorCode MatConvert_MPIAIJ_MPIAIJMKL(Mat, MatType, MatReuse, Mat *);
5994: #endif
5995: PETSC_INTERN PetscErrorCode MatConvert_MPIAIJ_MPIBAIJ(Mat, MatType, MatReuse, Mat *);
5996: PETSC_INTERN PetscErrorCode MatConvert_MPIAIJ_MPISBAIJ(Mat, MatType, MatReuse, Mat *);
5997: #if defined(PETSC_HAVE_ELEMENTAL)
5998: PETSC_INTERN PetscErrorCode MatConvert_MPIAIJ_Elemental(Mat, MatType, MatReuse, Mat *);
5999: #endif
6000: #if defined(PETSC_HAVE_SCALAPACK) && (defined(PETSC_USE_REAL_SINGLE) || defined(PETSC_USE_REAL_DOUBLE))
6001: PETSC_INTERN PetscErrorCode MatConvert_AIJ_ScaLAPACK(Mat, MatType, MatReuse, Mat *);
6002: #endif
6003: #if defined(PETSC_HAVE_HYPRE)
6004: PETSC_INTERN PetscErrorCode MatConvert_AIJ_HYPRE(Mat, MatType, MatReuse, Mat *);
6005: #endif
6006: #if defined(PETSC_HAVE_CUDA)
6007: PETSC_INTERN PetscErrorCode MatConvert_MPIAIJ_MPIAIJCUSPARSE(Mat, MatType, MatReuse, Mat *);
6008: #endif
6009: #if defined(PETSC_HAVE_HIP)
6010: PETSC_INTERN PetscErrorCode MatConvert_MPIAIJ_MPIAIJHIPSPARSE(Mat, MatType, MatReuse, Mat *);
6011: #endif
6012: #if defined(PETSC_HAVE_KOKKOS_KERNELS)
6013: PETSC_INTERN PetscErrorCode MatConvert_MPIAIJ_MPIAIJKokkos(Mat, MatType, MatReuse, Mat *);
6014: #endif
6015: PETSC_INTERN PetscErrorCode MatConvert_MPIAIJ_MPISELL(Mat, MatType, MatReuse, Mat *);
6016: PETSC_INTERN PetscErrorCode MatConvert_XAIJ_IS(Mat, MatType, MatReuse, Mat *);
6017: PETSC_INTERN PetscErrorCode MatProductSetFromOptions_IS_XAIJ(Mat);

6019: /*
6020:     Computes (B'*A')' since computing B*A directly is untenable

6022:                n                       p                          p
6023:         [             ]       [             ]         [                 ]
6024:       m [      A      ]  *  n [       B     ]   =   m [         C       ]
6025:         [             ]       [             ]         [                 ]

6027: */
6028: static PetscErrorCode MatMatMultNumeric_MPIDense_MPIAIJ(Mat A, Mat B, Mat C)
6029: {
6030:   Mat At, Bt, Ct;

6032:   PetscFunctionBegin;
6033:   PetscCall(MatTranspose(A, MAT_INITIAL_MATRIX, &At));
6034:   PetscCall(MatTranspose(B, MAT_INITIAL_MATRIX, &Bt));
6035:   PetscCall(MatMatMult(Bt, At, MAT_INITIAL_MATRIX, PETSC_CURRENT, &Ct));
6036:   PetscCall(MatDestroy(&At));
6037:   PetscCall(MatDestroy(&Bt));
6038:   PetscCall(MatTransposeSetPrecursor(Ct, C));
6039:   PetscCall(MatTranspose(Ct, MAT_REUSE_MATRIX, &C));
6040:   PetscCall(MatDestroy(&Ct));
6041:   PetscFunctionReturn(PETSC_SUCCESS);
6042: }

6044: static PetscErrorCode MatMatMultSymbolic_MPIDense_MPIAIJ(Mat A, Mat B, PetscReal fill, Mat C)
6045: {
6046:   PetscBool cisdense;

6048:   PetscFunctionBegin;
6049:   PetscCheck(A->cmap->n == B->rmap->n, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "A->cmap->n %" PetscInt_FMT " != B->rmap->n %" PetscInt_FMT, A->cmap->n, B->rmap->n);
6050:   PetscCall(MatSetSizes(C, A->rmap->n, B->cmap->n, A->rmap->N, B->cmap->N));
6051:   PetscCall(MatSetBlockSizesFromMats(C, A, B));
6052:   PetscCall(PetscObjectTypeCompareAny((PetscObject)C, &cisdense, MATMPIDENSE, MATMPIDENSECUDA, MATMPIDENSEHIP, ""));
6053:   if (!cisdense) PetscCall(MatSetType(C, ((PetscObject)A)->type_name));
6054:   PetscCall(MatSetUp(C));

6056:   C->ops->matmultnumeric = MatMatMultNumeric_MPIDense_MPIAIJ;
6057:   PetscFunctionReturn(PETSC_SUCCESS);
6058: }

6060: static PetscErrorCode MatProductSetFromOptions_MPIDense_MPIAIJ_AB(Mat C)
6061: {
6062:   Mat_Product *product = C->product;
6063:   Mat          A = product->A, B = product->B;

6065:   PetscFunctionBegin;
6066:   PetscCheck(A->cmap->rstart == B->rmap->rstart && A->cmap->rend == B->rmap->rend, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Matrix local dimensions are incompatible, (%" PetscInt_FMT ", %" PetscInt_FMT ") != (%" PetscInt_FMT ",%" PetscInt_FMT ")",
6067:              A->cmap->rstart, A->cmap->rend, B->rmap->rstart, B->rmap->rend);
6068:   C->ops->matmultsymbolic = MatMatMultSymbolic_MPIDense_MPIAIJ;
6069:   C->ops->productsymbolic = MatProductSymbolic_AB;
6070:   PetscFunctionReturn(PETSC_SUCCESS);
6071: }

6073: PETSC_INTERN PetscErrorCode MatProductSetFromOptions_MPIDense_MPIAIJ(Mat C)
6074: {
6075:   Mat_Product *product = C->product;

6077:   PetscFunctionBegin;
6078:   if (product->type == MATPRODUCT_AB) PetscCall(MatProductSetFromOptions_MPIDense_MPIAIJ_AB(C));
6079:   PetscFunctionReturn(PETSC_SUCCESS);
6080: }

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

6085:   Input Parameters:

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

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

6092:     For Set1, j1[] contains column indices of the nonzeros.
6093:     For the k-th row (0<=k<m), [rowBegin1[k],rowEnd1[k]) index into j1[] and point to the begin/end nonzero in row k
6094:     respectively (note rowEnd1[k] is not necessarily equal to rwoBegin1[k+1]). Indices in this range of j1[] are sorted,
6095:     but might have repeats. jmap1[t+1] - jmap1[t] is the number of repeats for the t-th unique nonzero in Set1.

6097:     Similar for Set2.

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

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

6103:     i[],j[]: the CSR of the merged matrix, which has m rows.
6104:     imap1[]: the k-th unique nonzero in Set1 (k=0,1,...) corresponds to imap1[k]-th unique nonzero in the merged matrix.
6105:     imap2[]: similar to imap1[], but for Set2.
6106:     Note we order nonzeros row-by-row and from left to right.
6107: */
6108: static PetscErrorCode MatMergeEntries_Internal(Mat mat, const PetscInt j1[], const PetscInt j2[], const PetscCount rowBegin1[], const PetscCount rowEnd1[], const PetscCount rowBegin2[], const PetscCount rowEnd2[], const PetscCount jmap1[], const PetscCount jmap2[], PetscCount imap1[], PetscCount imap2[], PetscInt i[], PetscInt j[])
6109: {
6110:   PetscInt   r, m; /* Row index of mat */
6111:   PetscCount t, t1, t2, b1, e1, b2, e2;

6113:   PetscFunctionBegin;
6114:   PetscCall(MatGetLocalSize(mat, &m, NULL));
6115:   t1 = t2 = t = 0; /* Count unique nonzeros of in Set1, Set1 and the merged respectively */
6116:   i[0]        = 0;
6117:   for (r = 0; r < m; r++) { /* Do row by row merging */
6118:     b1 = rowBegin1[r];
6119:     e1 = rowEnd1[r];
6120:     b2 = rowBegin2[r];
6121:     e2 = rowEnd2[r];
6122:     while (b1 < e1 && b2 < e2) {
6123:       if (j1[b1] == j2[b2]) { /* Same column index and hence same nonzero */
6124:         j[t]      = j1[b1];
6125:         imap1[t1] = t;
6126:         imap2[t2] = t;
6127:         b1 += jmap1[t1 + 1] - jmap1[t1]; /* Jump to next unique local nonzero */
6128:         b2 += jmap2[t2 + 1] - jmap2[t2]; /* Jump to next unique remote nonzero */
6129:         t1++;
6130:         t2++;
6131:         t++;
6132:       } else if (j1[b1] < j2[b2]) {
6133:         j[t]      = j1[b1];
6134:         imap1[t1] = t;
6135:         b1 += jmap1[t1 + 1] - jmap1[t1];
6136:         t1++;
6137:         t++;
6138:       } else {
6139:         j[t]      = j2[b2];
6140:         imap2[t2] = t;
6141:         b2 += jmap2[t2 + 1] - jmap2[t2];
6142:         t2++;
6143:         t++;
6144:       }
6145:     }
6146:     /* Merge the remaining in either j1[] or j2[] */
6147:     while (b1 < e1) {
6148:       j[t]      = j1[b1];
6149:       imap1[t1] = t;
6150:       b1 += jmap1[t1 + 1] - jmap1[t1];
6151:       t1++;
6152:       t++;
6153:     }
6154:     while (b2 < e2) {
6155:       j[t]      = j2[b2];
6156:       imap2[t2] = t;
6157:       b2 += jmap2[t2 + 1] - jmap2[t2];
6158:       t2++;
6159:       t++;
6160:     }
6161:     PetscCall(PetscIntCast(t, i + r + 1));
6162:   }
6163:   PetscFunctionReturn(PETSC_SUCCESS);
6164: }

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

6169:   Input Parameters:
6170:     mat: an MPI matrix that provides row and column layout information for splitting. Let's say its number of local rows is m.
6171:     n,i[],j[],perm[]: there are n input entries, belonging to m rows. Row/col indices of the entries are stored in i[] and j[]
6172:       respectively, along with a permutation array perm[]. Length of the i[],j[],perm[] arrays is n.

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

6177:   Output Parameters:
6178:     j[],perm[]: the routine needs to sort j[] within each row along with perm[].
6179:     rowBegin[],rowMid[],rowEnd[]: of length m, and the memory is preallocated and zeroed by the caller.
6180:       They contain indices pointing to j[]. For 0<=r<m, [rowBegin[r],rowMid[r]) point to begin/end entries of row r of the diagonal block,
6181:       and [rowMid[r],rowEnd[r]) point to begin/end entries of row r of the off-diagonal block.

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

6191:       Atot: number of entries belonging to the diagonal block
6192:       Annz: number of unique nonzeros belonging to the diagonal block.

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

6196:     Aperm[],Bperm[],Ajmap[] and Bjmap[] are allocated separately by this routine with PetscMalloc1().
6197: */
6198: static PetscErrorCode MatSplitEntries_Internal(Mat mat, PetscCount n, const PetscInt i[], PetscInt j[], PetscCount perm[], PetscCount rowBegin[], PetscCount rowMid[], PetscCount rowEnd[], PetscCount *Atot_, PetscCount **Aperm_, PetscCount *Annz_, PetscCount **Ajmap_, PetscCount *Btot_, PetscCount **Bperm_, PetscCount *Bnnz_, PetscCount **Bjmap_)
6199: {
6200:   PetscInt    cstart, cend, rstart, rend, row, col;
6201:   PetscCount  Atot = 0, Btot = 0; /* Total number of nonzeros in the diagonal and off-diagonal blocks */
6202:   PetscCount  Annz = 0, Bnnz = 0; /* Number of unique nonzeros in the diagonal and off-diagonal blocks */
6203:   PetscCount  k, m, p, q, r, s, mid;
6204:   PetscCount *Aperm, *Bperm, *Ajmap, *Bjmap;

6206:   PetscFunctionBegin;
6207:   PetscCall(PetscLayoutGetRange(mat->rmap, &rstart, &rend));
6208:   PetscCall(PetscLayoutGetRange(mat->cmap, &cstart, &cend));
6209:   m = rend - rstart;

6211:   /* Skip negative rows */
6212:   for (k = 0; k < n; k++)
6213:     if (i[k] >= 0) break;

6215:   /* Process [k,n): sort and partition each local row into diag and offdiag portions,
6216:      fill rowBegin[], rowMid[], rowEnd[], and count Atot, Btot, Annz, Bnnz.
6217:   */
6218:   while (k < n) {
6219:     row = i[k];
6220:     /* Entries in [k,s) are in one row. Shift diagonal block col indices so that diag is ahead of offdiag after sorting the row */
6221:     for (s = k; s < n; s++)
6222:       if (i[s] != row) break;

6224:     /* Shift diag columns to range of [-PETSC_INT_MAX, -1] */
6225:     for (p = k; p < s; p++) {
6226:       if (j[p] >= cstart && j[p] < cend) j[p] -= PETSC_INT_MAX;
6227:     }
6228:     PetscCall(PetscSortIntWithCountArray(s - k, j + k, perm + k));
6229:     PetscCall(PetscSortedIntUpperBound(j, k, s, -1, &mid)); /* Separate [k,s) into [k,mid) for diag and [mid,s) for offdiag */
6230:     rowBegin[row - rstart] = k;
6231:     rowMid[row - rstart]   = mid;
6232:     rowEnd[row - rstart]   = s;
6233:     PetscCheck(k == s || j[s - 1] < mat->cmap->N, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Column index %" PetscInt_FMT " is >= matrix column size %" PetscInt_FMT, j[s - 1], mat->cmap->N);

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

6239:     /* Count unique nonzeros of this diag row */
6240:     for (p = k; p < mid;) {
6241:       col = j[p];
6242:       do {
6243:         j[p] += PETSC_INT_MAX; /* Revert the modified diagonal indices */
6244:         p++;
6245:       } while (p < mid && j[p] == col);
6246:       Annz++;
6247:     }

6249:     /* Count unique nonzeros of this offdiag row */
6250:     for (p = mid; p < s;) {
6251:       col = j[p];
6252:       do {
6253:         p++;
6254:       } while (p < s && j[p] == col);
6255:       Bnnz++;
6256:     }
6257:     k = s;
6258:   }

6260:   /* Allocation according to Atot, Btot, Annz, Bnnz */
6261:   PetscCall(PetscMalloc1(Atot, &Aperm));
6262:   PetscCall(PetscMalloc1(Btot, &Bperm));
6263:   PetscCall(PetscMalloc1(Annz + 1, &Ajmap));
6264:   PetscCall(PetscMalloc1(Bnnz + 1, &Bjmap));

6266:   /* Re-scan indices and copy diag/offdiag permutation indices to Aperm, Bperm and also fill Ajmap and Bjmap */
6267:   Ajmap[0] = Bjmap[0] = Atot = Btot = Annz = Bnnz = 0;
6268:   for (r = 0; r < m; r++) {
6269:     k   = rowBegin[r];
6270:     mid = rowMid[r];
6271:     s   = rowEnd[r];
6272:     PetscCall(PetscArraycpy(PetscSafePointerPlusOffset(Aperm, Atot), PetscSafePointerPlusOffset(perm, k), mid - k));
6273:     PetscCall(PetscArraycpy(PetscSafePointerPlusOffset(Bperm, Btot), PetscSafePointerPlusOffset(perm, mid), s - mid));
6274:     Atot += mid - k;
6275:     Btot += s - mid;

6277:     /* Scan column indices in this row and find out how many repeats each unique nonzero has */
6278:     for (p = k; p < mid;) {
6279:       col = j[p];
6280:       q   = p;
6281:       do {
6282:         p++;
6283:       } while (p < mid && j[p] == col);
6284:       Ajmap[Annz + 1] = Ajmap[Annz] + (p - q);
6285:       Annz++;
6286:     }

6288:     for (p = mid; p < s;) {
6289:       col = j[p];
6290:       q   = p;
6291:       do {
6292:         p++;
6293:       } while (p < s && j[p] == col);
6294:       Bjmap[Bnnz + 1] = Bjmap[Bnnz] + (p - q);
6295:       Bnnz++;
6296:     }
6297:   }
6298:   /* Output */
6299:   *Aperm_ = Aperm;
6300:   *Annz_  = Annz;
6301:   *Atot_  = Atot;
6302:   *Ajmap_ = Ajmap;
6303:   *Bperm_ = Bperm;
6304:   *Bnnz_  = Bnnz;
6305:   *Btot_  = Btot;
6306:   *Bjmap_ = Bjmap;
6307:   PetscFunctionReturn(PETSC_SUCCESS);
6308: }

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

6313:   Input Parameters:
6314:     nnz1: number of unique nonzeros in a set that was used to produce imap[], jmap[]
6315:     nnz:  number of unique nonzeros in the merged matrix
6316:     imap[nnz1]: i-th nonzero in the set is the imap[i]-th nonzero in the merged matrix
6317:     jmap[nnz1+1]: i-th nonzero in the set has jmap[i+1] - jmap[i] repeats in the set

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

6322:   Example:
6323:     nnz1 = 4
6324:     nnz  = 6
6325:     imap = [1,3,4,5]
6326:     jmap = [0,3,5,6,7]
6327:    then,
6328:     jmap_new = [0,0,3,3,5,6,7]
6329: */
6330: static PetscErrorCode ExpandJmap_Internal(PetscCount nnz1, PetscCount nnz, const PetscCount imap[], const PetscCount jmap[], PetscCount jmap_new[])
6331: {
6332:   PetscCount k, p;

6334:   PetscFunctionBegin;
6335:   jmap_new[0] = 0;
6336:   p           = nnz;                /* p loops over jmap_new[] backwards */
6337:   for (k = nnz1 - 1; k >= 0; k--) { /* k loops over imap[] */
6338:     for (; p > imap[k]; p--) jmap_new[p] = jmap[k + 1];
6339:   }
6340:   for (; p >= 0; p--) jmap_new[p] = jmap[0];
6341:   PetscFunctionReturn(PETSC_SUCCESS);
6342: }

6344: static PetscErrorCode MatCOOStructDestroy_MPIAIJ(PetscCtxRt data)
6345: {
6346:   MatCOOStruct_MPIAIJ *coo = *(MatCOOStruct_MPIAIJ **)data;

6348:   PetscFunctionBegin;
6349:   PetscCall(PetscSFDestroy(&coo->sf));
6350:   PetscCall(PetscFree(coo->Aperm1));
6351:   PetscCall(PetscFree(coo->Bperm1));
6352:   PetscCall(PetscFree(coo->Ajmap1));
6353:   PetscCall(PetscFree(coo->Bjmap1));
6354:   PetscCall(PetscFree(coo->Aimap2));
6355:   PetscCall(PetscFree(coo->Bimap2));
6356:   PetscCall(PetscFree(coo->Aperm2));
6357:   PetscCall(PetscFree(coo->Bperm2));
6358:   PetscCall(PetscFree(coo->Ajmap2));
6359:   PetscCall(PetscFree(coo->Bjmap2));
6360:   PetscCall(PetscFree(coo->Cperm1));
6361:   PetscCall(PetscFree2(coo->sendbuf, coo->recvbuf));
6362:   PetscCall(PetscFree(coo));
6363:   PetscFunctionReturn(PETSC_SUCCESS);
6364: }

6366: PetscErrorCode MatSetPreallocationCOO_MPIAIJ(Mat mat, PetscCount coo_n, PetscInt coo_i[], PetscInt coo_j[])
6367: {
6368:   MPI_Comm             comm;
6369:   PetscMPIInt          rank, size;
6370:   PetscInt             m, n, M, N, rstart, rend, cstart, cend; /* Sizes, indices of row/col, therefore with type PetscInt */
6371:   PetscCount           k, p, q, rem;                           /* Loop variables over coo arrays */
6372:   Mat_MPIAIJ          *mpiaij = (Mat_MPIAIJ *)mat->data;
6373:   PetscContainer       container;
6374:   MatCOOStruct_MPIAIJ *coo;

6376:   PetscFunctionBegin;
6377:   PetscCall(PetscFree(mpiaij->garray));
6378:   PetscCall(VecDestroy(&mpiaij->lvec));
6379: #if defined(PETSC_USE_CTABLE)
6380:   PetscCall(PetscHMapIDestroy(&mpiaij->colmap));
6381: #else
6382:   PetscCall(PetscFree(mpiaij->colmap));
6383: #endif
6384:   PetscCall(VecScatterDestroy(&mpiaij->Mvctx));
6385:   mat->assembled     = PETSC_FALSE;
6386:   mat->was_assembled = PETSC_FALSE;

6388:   PetscCall(PetscObjectGetComm((PetscObject)mat, &comm));
6389:   PetscCallMPI(MPI_Comm_size(comm, &size));
6390:   PetscCallMPI(MPI_Comm_rank(comm, &rank));
6391:   PetscCall(PetscLayoutSetUp(mat->rmap));
6392:   PetscCall(PetscLayoutSetUp(mat->cmap));
6393:   PetscCall(PetscLayoutGetRange(mat->rmap, &rstart, &rend));
6394:   PetscCall(PetscLayoutGetRange(mat->cmap, &cstart, &cend));
6395:   PetscCall(MatGetLocalSize(mat, &m, &n));
6396:   PetscCall(MatGetSize(mat, &M, &N));

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

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

6406:   /* Manipulate indices so that entries with negative row or col indices will have smallest
6407:      row indices, local entries will have greater but negative row indices, and remote entries
6408:      will have positive row indices.
6409:   */
6410:   for (k = 0; k < n1; k++) {
6411:     if (i1[k] < 0 || j1[k] < 0) i1[k] = PETSC_INT_MIN;                /* e.g., -2^31, minimal to move them ahead */
6412:     else if (i1[k] >= rstart && i1[k] < rend) i1[k] -= PETSC_INT_MAX; /* e.g., minus 2^31-1 to shift local rows to range of [-PETSC_INT_MAX, -1] */
6413:     else {
6414:       PetscCheck(!mat->nooffprocentries, PETSC_COMM_SELF, PETSC_ERR_USER_INPUT, "MAT_NO_OFF_PROC_ENTRIES is set but insert to remote rows");
6415:       if (mpiaij->donotstash) i1[k] = PETSC_INT_MIN; /* Ignore offproc entries as if they had negative indices */
6416:     }
6417:   }

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

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

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

6430:   PetscCheck(n1 == 0 || i1[n1 - 1] < M, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "COO row index %" PetscInt_FMT " is >= the matrix row size %" PetscInt_FMT, i1[n1 - 1], M);

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

6440:   PetscCall(PetscLayoutGetRanges(mat->rmap, &ranges));
6441:   PetscCall(PetscMalloc2(maxNsend, &sendto, maxNsend, &nentries));
6442:   for (k = rem; k < n1;) {
6443:     PetscMPIInt owner;
6444:     PetscInt    firstRow, lastRow;

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

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

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

6460:       PetscCall(PetscMalloc2(maxNsend2, &sendto2, maxNsend2, &nentries2));
6461:       PetscCall(PetscArraycpy(sendto2, sendto, maxNsend));
6462:       PetscCall(PetscArraycpy(nentries2, nentries, maxNsend));
6463:       PetscCall(PetscFree2(sendto, nentries));
6464:       sendto   = sendto2;
6465:       nentries = nentries2;
6466:       maxNsend = maxNsend2;
6467:     }
6468:     sendto[nsend] = owner;
6469:     PetscCall(PetscIntCast(p - k, &nentries[nsend]));
6470:     nsend++;
6471:     k = p;
6472:   }

6474:   /* Build 1st SF to know offsets on remote to send data */
6475:   PetscSF      sf1;
6476:   PetscInt     nroots = 1, nroots2 = 0;
6477:   PetscInt     nleaves = nsend, nleaves2 = 0;
6478:   PetscInt    *offsets;
6479:   PetscSFNode *iremote;

6481:   PetscCall(PetscSFCreate(comm, &sf1));
6482:   PetscCall(PetscMalloc1(nsend, &iremote));
6483:   PetscCall(PetscMalloc1(nsend, &offsets));
6484:   for (k = 0; k < nsend; k++) {
6485:     iremote[k].rank  = sendto[k];
6486:     iremote[k].index = 0;
6487:     nleaves2 += nentries[k];
6488:     PetscCheck(nleaves2 >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Number of SF leaves is too large for PetscInt");
6489:   }
6490:   PetscCall(PetscSFSetGraph(sf1, nroots, nleaves, NULL, PETSC_OWN_POINTER, iremote, PETSC_OWN_POINTER));
6491:   PetscCall(PetscSFFetchAndOpWithMemTypeBegin(sf1, MPIU_INT, PETSC_MEMTYPE_HOST, &nroots2 /*rootdata*/, PETSC_MEMTYPE_HOST, nentries /*leafdata*/, PETSC_MEMTYPE_HOST, offsets /*leafupdate*/, MPI_SUM));
6492:   PetscCall(PetscSFFetchAndOpEnd(sf1, MPIU_INT, &nroots2, nentries, offsets, MPI_SUM)); /* Would nroots2 overflow, we check offsets[] below */
6493:   PetscCall(PetscSFDestroy(&sf1));
6494:   PetscAssert(nleaves2 == n1 - rem, PETSC_COMM_SELF, PETSC_ERR_PLIB, "nleaves2 %" PetscInt_FMT " != number of remote entries %" PetscCount_FMT, nleaves2, n1 - rem);

6496:   /* Build 2nd SF to send remote COOs to their owner */
6497:   PetscSF sf2;
6498:   nroots  = nroots2;
6499:   nleaves = nleaves2;
6500:   PetscCall(PetscSFCreate(comm, &sf2));
6501:   PetscCall(PetscSFSetFromOptions(sf2));
6502:   PetscCall(PetscMalloc1(nleaves, &iremote));
6503:   p = 0;
6504:   for (k = 0; k < nsend; k++) {
6505:     PetscCheck(offsets[k] >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Number of SF roots is too large for PetscInt");
6506:     for (q = 0; q < nentries[k]; q++, p++) {
6507:       iremote[p].rank = sendto[k];
6508:       PetscCall(PetscIntCast(offsets[k] + q, &iremote[p].index));
6509:     }
6510:   }
6511:   PetscCall(PetscSFSetGraph(sf2, nroots, nleaves, NULL, PETSC_OWN_POINTER, iremote, PETSC_OWN_POINTER));

6513:   /* Send the remote COOs to their owner */
6514:   PetscInt    n2 = nroots, *i2, *j2; /* Buffers for received COOs from other ranks, along with a permutation array */
6515:   PetscCount *perm2;                 /* Though PetscInt is enough for remote entries, we use PetscCount here as we want to reuse MatSplitEntries_Internal() */
6516:   PetscCall(PetscMalloc3(n2, &i2, n2, &j2, n2, &perm2));
6517:   PetscAssert(rem == 0 || i1 != NULL, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Cannot add nonzero offset to null");
6518:   PetscAssert(rem == 0 || j1 != NULL, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Cannot add nonzero offset to null");
6519:   PetscInt *i1prem = PetscSafePointerPlusOffset(i1, rem);
6520:   PetscInt *j1prem = PetscSafePointerPlusOffset(j1, rem);
6521:   PetscCall(PetscSFReduceWithMemTypeBegin(sf2, MPIU_INT, PETSC_MEMTYPE_HOST, i1prem, PETSC_MEMTYPE_HOST, i2, MPI_REPLACE));
6522:   PetscCall(PetscSFReduceEnd(sf2, MPIU_INT, i1prem, i2, MPI_REPLACE));
6523:   PetscCall(PetscSFReduceWithMemTypeBegin(sf2, MPIU_INT, PETSC_MEMTYPE_HOST, j1prem, PETSC_MEMTYPE_HOST, j2, MPI_REPLACE));
6524:   PetscCall(PetscSFReduceEnd(sf2, MPIU_INT, j1prem, j2, MPI_REPLACE));

6526:   PetscCall(PetscFree(offsets));
6527:   PetscCall(PetscFree2(sendto, nentries));

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

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

6540:   /* Support for HYPRE matrices, kind of a hack.
6541:      Swap min column with diagonal so that diagonal values will go first */
6542:   PetscBool hypre;
6543:   PetscCall(PetscStrcmp("_internal_COO_mat_for_hypre", ((PetscObject)mat)->name, &hypre));
6544:   if (hypre) {
6545:     PetscInt *minj;
6546:     PetscBT   hasdiag;

6548:     PetscCall(PetscBTCreate(m, &hasdiag));
6549:     PetscCall(PetscMalloc1(m, &minj));
6550:     for (k = 0; k < m; k++) minj[k] = PETSC_INT_MAX;
6551:     for (k = i1start; k < rem; k++) {
6552:       if (j1[k] < cstart || j1[k] >= cend) continue;
6553:       const PetscInt rindex = i1[k] - rstart;
6554:       if ((j1[k] - cstart) == rindex) PetscCall(PetscBTSet(hasdiag, rindex));
6555:       minj[rindex] = PetscMin(minj[rindex], j1[k]);
6556:     }
6557:     for (k = 0; k < n2; k++) {
6558:       if (j2[k] < cstart || j2[k] >= cend) continue;
6559:       const PetscInt rindex = i2[k] - rstart;
6560:       if ((j2[k] - cstart) == rindex) PetscCall(PetscBTSet(hasdiag, rindex));
6561:       minj[rindex] = PetscMin(minj[rindex], j2[k]);
6562:     }
6563:     for (k = i1start; k < rem; k++) {
6564:       const PetscInt rindex = i1[k] - rstart;
6565:       if (j1[k] < cstart || j1[k] >= cend || !PetscBTLookup(hasdiag, rindex)) continue;
6566:       if (j1[k] == minj[rindex]) j1[k] = i1[k] + (cstart - rstart);
6567:       else if ((j1[k] - cstart) == rindex) j1[k] = minj[rindex];
6568:     }
6569:     for (k = 0; k < n2; k++) {
6570:       const PetscInt rindex = i2[k] - rstart;
6571:       if (j2[k] < cstart || j2[k] >= cend || !PetscBTLookup(hasdiag, rindex)) continue;
6572:       if (j2[k] == minj[rindex]) j2[k] = i2[k] + (cstart - rstart);
6573:       else if ((j2[k] - cstart) == rindex) j2[k] = minj[rindex];
6574:     }
6575:     PetscCall(PetscBTDestroy(&hasdiag));
6576:     PetscCall(PetscFree(minj));
6577:   }

6579:   /* Split local COOs and received COOs into diag/offdiag portions */
6580:   PetscCount *rowBegin1, *rowMid1, *rowEnd1;
6581:   PetscCount *Ajmap1, *Aperm1, *Bjmap1, *Bperm1;
6582:   PetscCount  Annz1, Bnnz1, Atot1, Btot1;
6583:   PetscCount *rowBegin2, *rowMid2, *rowEnd2;
6584:   PetscCount *Ajmap2, *Aperm2, *Bjmap2, *Bperm2;
6585:   PetscCount  Annz2, Bnnz2, Atot2, Btot2;

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

6592:   /* Merge local COOs with received COOs: diag with diag, offdiag with offdiag */
6593:   PetscInt *Ai, *Bi;
6594:   PetscInt *Aj, *Bj;

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

6601:   PetscCount *Aimap1, *Bimap1, *Aimap2, *Bimap2;
6602:   PetscCall(PetscMalloc1(Annz1, &Aimap1));
6603:   PetscCall(PetscMalloc1(Bnnz1, &Bimap1));
6604:   PetscCall(PetscMalloc1(Annz2, &Aimap2));
6605:   PetscCall(PetscMalloc1(Bnnz2, &Bimap2));

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

6610:   /* Expand Ajmap1/Bjmap1 to make them based off nonzeros in A/B, since we     */
6611:   /* expect nonzeros in A/B most likely have local contributing entries        */
6612:   PetscInt    Annz = Ai[m];
6613:   PetscInt    Bnnz = Bi[m];
6614:   PetscCount *Ajmap1_new, *Bjmap1_new;

6616:   PetscCall(PetscMalloc1(Annz + 1, &Ajmap1_new));
6617:   PetscCall(PetscMalloc1(Bnnz + 1, &Bjmap1_new));

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

6622:   PetscCall(PetscFree(Aimap1));
6623:   PetscCall(PetscFree(Ajmap1));
6624:   PetscCall(PetscFree(Bimap1));
6625:   PetscCall(PetscFree(Bjmap1));
6626:   PetscCall(PetscFree3(rowBegin1, rowMid1, rowEnd1));
6627:   PetscCall(PetscFree3(rowBegin2, rowMid2, rowEnd2));
6628:   PetscCall(PetscFree(perm1));
6629:   PetscCall(PetscFree3(i2, j2, perm2));

6631:   Ajmap1 = Ajmap1_new;
6632:   Bjmap1 = Bjmap1_new;

6634:   /* Reallocate Aj, Bj once we know actual numbers of unique nonzeros in A and B */
6635:   if (Annz < Annz1 + Annz2) {
6636:     PetscInt *Aj_new;
6637:     PetscCall(PetscMalloc1(Annz, &Aj_new));
6638:     PetscCall(PetscArraycpy(Aj_new, Aj, Annz));
6639:     PetscCall(PetscFree(Aj));
6640:     Aj = Aj_new;
6641:   }

6643:   if (Bnnz < Bnnz1 + Bnnz2) {
6644:     PetscInt *Bj_new;
6645:     PetscCall(PetscMalloc1(Bnnz, &Bj_new));
6646:     PetscCall(PetscArraycpy(Bj_new, Bj, Bnnz));
6647:     PetscCall(PetscFree(Bj));
6648:     Bj = Bj_new;
6649:   }

6651:   /* Create new submatrices for on-process and off-process coupling                  */
6652:   PetscScalar     *Aa, *Ba;
6653:   MatType          rtype;
6654:   Mat_SeqAIJ      *a, *b;
6655:   PetscObjectState state;
6656:   PetscCall(PetscCalloc1(Annz, &Aa)); /* Zero matrix on device */
6657:   PetscCall(PetscCalloc1(Bnnz, &Ba));
6658:   /* make Aj[] local, i.e, based off the start column of the diagonal portion */
6659:   if (cstart) {
6660:     for (k = 0; k < Annz; k++) Aj[k] -= cstart;
6661:   }

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

6665:   MatSeqXAIJGetOptions_Private(mpiaij->A);
6666:   PetscCall(MatDestroy(&mpiaij->A));
6667:   PetscCall(MatCreateSeqAIJWithArrays(PETSC_COMM_SELF, m, n, Ai, Aj, Aa, &mpiaij->A));
6668:   PetscCall(MatSetBlockSizesFromMats(mpiaij->A, mat, mat));
6669:   MatSeqXAIJRestoreOptions_Private(mpiaij->A);

6671:   MatSeqXAIJGetOptions_Private(mpiaij->B);
6672:   PetscCall(MatDestroy(&mpiaij->B));
6673:   PetscCall(MatCreateSeqAIJWithArrays(PETSC_COMM_SELF, m, mat->cmap->N, Bi, Bj, Ba, &mpiaij->B));
6674:   PetscCall(MatSetBlockSizesFromMats(mpiaij->B, mat, mat));
6675:   MatSeqXAIJRestoreOptions_Private(mpiaij->B);

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

6682:   a          = (Mat_SeqAIJ *)mpiaij->A->data;
6683:   b          = (Mat_SeqAIJ *)mpiaij->B->data;
6684:   a->free_a  = PETSC_TRUE;
6685:   a->free_ij = PETSC_TRUE;
6686:   b->free_a  = PETSC_TRUE;
6687:   b->free_ij = PETSC_TRUE;
6688:   a->maxnz   = a->nz;
6689:   b->maxnz   = b->nz;

6691:   /* conversion must happen AFTER multiply setup */
6692:   PetscCall(MatConvert(mpiaij->A, rtype, MAT_INPLACE_MATRIX, &mpiaij->A));
6693:   PetscCall(MatConvert(mpiaij->B, rtype, MAT_INPLACE_MATRIX, &mpiaij->B));
6694:   PetscCall(VecDestroy(&mpiaij->lvec));
6695:   PetscCall(MatCreateVecs(mpiaij->B, &mpiaij->lvec, NULL));

6697:   // Put the COO struct in a container and then attach that to the matrix
6698:   PetscCall(PetscMalloc1(1, &coo));
6699:   coo->n       = coo_n;
6700:   coo->sf      = sf2;
6701:   coo->sendlen = nleaves;
6702:   coo->recvlen = nroots;
6703:   coo->Annz    = Annz;
6704:   coo->Bnnz    = Bnnz;
6705:   coo->Annz2   = Annz2;
6706:   coo->Bnnz2   = Bnnz2;
6707:   coo->Atot1   = Atot1;
6708:   coo->Atot2   = Atot2;
6709:   coo->Btot1   = Btot1;
6710:   coo->Btot2   = Btot2;
6711:   coo->Ajmap1  = Ajmap1;
6712:   coo->Aperm1  = Aperm1;
6713:   coo->Bjmap1  = Bjmap1;
6714:   coo->Bperm1  = Bperm1;
6715:   coo->Aimap2  = Aimap2;
6716:   coo->Ajmap2  = Ajmap2;
6717:   coo->Aperm2  = Aperm2;
6718:   coo->Bimap2  = Bimap2;
6719:   coo->Bjmap2  = Bjmap2;
6720:   coo->Bperm2  = Bperm2;
6721:   coo->Cperm1  = Cperm1;
6722:   // Allocate in preallocation. If not used, it has zero cost on host
6723:   PetscCall(PetscMalloc2(coo->sendlen, &coo->sendbuf, coo->recvlen, &coo->recvbuf));
6724:   PetscCall(PetscContainerCreate(PETSC_COMM_SELF, &container));
6725:   PetscCall(PetscContainerSetPointer(container, coo));
6726:   PetscCall(PetscContainerSetCtxDestroy(container, MatCOOStructDestroy_MPIAIJ));
6727:   PetscCall(PetscObjectCompose((PetscObject)mat, "__PETSc_MatCOOStruct_Host", (PetscObject)container));
6728:   PetscCall(PetscContainerDestroy(&container));
6729:   PetscFunctionReturn(PETSC_SUCCESS);
6730: }

6732: static PetscErrorCode MatSetValuesCOO_MPIAIJ(Mat mat, const PetscScalar v[], InsertMode imode)
6733: {
6734:   Mat_MPIAIJ          *mpiaij = (Mat_MPIAIJ *)mat->data;
6735:   Mat                  A = mpiaij->A, B = mpiaij->B;
6736:   PetscScalar         *Aa, *Ba;
6737:   PetscScalar         *sendbuf, *recvbuf;
6738:   const PetscCount    *Ajmap1, *Ajmap2, *Aimap2;
6739:   const PetscCount    *Bjmap1, *Bjmap2, *Bimap2;
6740:   const PetscCount    *Aperm1, *Aperm2, *Bperm1, *Bperm2;
6741:   const PetscCount    *Cperm1;
6742:   PetscContainer       container;
6743:   MatCOOStruct_MPIAIJ *coo;

6745:   PetscFunctionBegin;
6746:   PetscCall(PetscObjectQuery((PetscObject)mat, "__PETSc_MatCOOStruct_Host", (PetscObject *)&container));
6747:   PetscCheck(container, PetscObjectComm((PetscObject)mat), PETSC_ERR_PLIB, "Not found MatCOOStruct on this matrix");
6748:   PetscCall(PetscContainerGetPointer(container, &coo));
6749:   sendbuf = coo->sendbuf;
6750:   recvbuf = coo->recvbuf;
6751:   Ajmap1  = coo->Ajmap1;
6752:   Ajmap2  = coo->Ajmap2;
6753:   Aimap2  = coo->Aimap2;
6754:   Bjmap1  = coo->Bjmap1;
6755:   Bjmap2  = coo->Bjmap2;
6756:   Bimap2  = coo->Bimap2;
6757:   Aperm1  = coo->Aperm1;
6758:   Aperm2  = coo->Aperm2;
6759:   Bperm1  = coo->Bperm1;
6760:   Bperm2  = coo->Bperm2;
6761:   Cperm1  = coo->Cperm1;

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

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

6769:   /* Send remote entries to their owner and overlap the communication with local computation */
6770:   PetscCall(PetscSFReduceWithMemTypeBegin(coo->sf, MPIU_SCALAR, PETSC_MEMTYPE_HOST, sendbuf, PETSC_MEMTYPE_HOST, recvbuf, MPI_REPLACE));
6771:   /* Add local entries to A and B */
6772:   for (PetscCount i = 0; i < coo->Annz; i++) { /* All nonzeros in A are either zero'ed or added with a value (i.e., initialized) */
6773:     PetscScalar sum = 0.0;                     /* Do partial summation first to improve numerical stability */
6774:     for (PetscCount k = Ajmap1[i]; k < Ajmap1[i + 1]; k++) sum += v[Aperm1[k]];
6775:     Aa[i] = (imode == INSERT_VALUES ? 0.0 : Aa[i]) + sum;
6776:   }
6777:   for (PetscCount i = 0; i < coo->Bnnz; i++) {
6778:     PetscScalar sum = 0.0;
6779:     for (PetscCount k = Bjmap1[i]; k < Bjmap1[i + 1]; k++) sum += v[Bperm1[k]];
6780:     Ba[i] = (imode == INSERT_VALUES ? 0.0 : Ba[i]) + sum;
6781:   }
6782:   PetscCall(PetscSFReduceEnd(coo->sf, MPIU_SCALAR, sendbuf, recvbuf, MPI_REPLACE));

6784:   /* Add received remote entries to A and B */
6785:   for (PetscCount i = 0; i < coo->Annz2; i++) {
6786:     for (PetscCount k = Ajmap2[i]; k < Ajmap2[i + 1]; k++) Aa[Aimap2[i]] += recvbuf[Aperm2[k]];
6787:   }
6788:   for (PetscCount i = 0; i < coo->Bnnz2; i++) {
6789:     for (PetscCount k = Bjmap2[i]; k < Bjmap2[i + 1]; k++) Ba[Bimap2[i]] += recvbuf[Bperm2[k]];
6790:   }
6791:   PetscCall(MatSeqAIJRestoreArray(A, &Aa));
6792:   PetscCall(MatSeqAIJRestoreArray(B, &Ba));
6793:   PetscFunctionReturn(PETSC_SUCCESS);
6794: }

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

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

6802:    Level: beginner

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

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

6812: .seealso: [](ch_matrices), `Mat`, `MATSEQAIJ`, `MATAIJ`, `MatCreateAIJ()`
6813: M*/
6814: PETSC_EXTERN PetscErrorCode MatCreate_MPIAIJ(Mat B)
6815: {
6816:   Mat_MPIAIJ *b;
6817:   PetscMPIInt size;

6819:   PetscFunctionBegin;
6820:   PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)B), &size));

6822:   PetscCall(PetscNew(&b));
6823:   B->data       = (void *)b;
6824:   B->ops[0]     = MatOps_Values;
6825:   B->assembled  = PETSC_FALSE;
6826:   B->insertmode = NOT_SET_VALUES;
6827:   b->size       = size;

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

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

6834:   b->donotstash  = PETSC_FALSE;
6835:   b->colmap      = NULL;
6836:   b->garray      = NULL;
6837:   b->roworiented = PETSC_TRUE;

6839:   /* stuff used for matrix vector multiply */
6840:   b->lvec  = NULL;
6841:   b->Mvctx = NULL;

6843:   /* stuff for MatGetRow() */
6844:   b->rowindices   = NULL;
6845:   b->rowvalues    = NULL;
6846:   b->getrowactive = PETSC_FALSE;

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

6851:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatMPIAIJSetUseScalableIncreaseOverlap_C", MatMPIAIJSetUseScalableIncreaseOverlap_MPIAIJ));
6852:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatStoreValues_C", MatStoreValues_MPIAIJ));
6853:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatRetrieveValues_C", MatRetrieveValues_MPIAIJ));
6854:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatIsTranspose_C", MatIsTranspose_MPIAIJ));
6855:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatMPIAIJSetPreallocation_C", MatMPIAIJSetPreallocation_MPIAIJ));
6856:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatResetPreallocation_C", MatResetPreallocation_MPIAIJ));
6857:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatResetHash_C", MatResetHash_MPIAIJ));
6858:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatMPIAIJSetPreallocationCSR_C", MatMPIAIJSetPreallocationCSR_MPIAIJ));
6859:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatDiagonalScaleLocal_C", MatDiagonalScaleLocal_MPIAIJ));
6860:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatConvert_mpiaij_mpiaijperm_C", MatConvert_MPIAIJ_MPIAIJPERM));
6861:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatConvert_mpiaij_mpiaijsell_C", MatConvert_MPIAIJ_MPIAIJSELL));
6862: #if defined(PETSC_HAVE_CUDA)
6863:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatConvert_mpiaij_mpiaijcusparse_C", MatConvert_MPIAIJ_MPIAIJCUSPARSE));
6864: #endif
6865: #if defined(PETSC_HAVE_HIP)
6866:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatConvert_mpiaij_mpiaijhipsparse_C", MatConvert_MPIAIJ_MPIAIJHIPSPARSE));
6867: #endif
6868: #if defined(PETSC_HAVE_KOKKOS_KERNELS)
6869:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatConvert_mpiaij_mpiaijkokkos_C", MatConvert_MPIAIJ_MPIAIJKokkos));
6870: #endif
6871: #if defined(PETSC_HAVE_MKL_SPARSE)
6872:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatConvert_mpiaij_mpiaijmkl_C", MatConvert_MPIAIJ_MPIAIJMKL));
6873: #endif
6874:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatConvert_mpiaij_mpiaijcrl_C", MatConvert_MPIAIJ_MPIAIJCRL));
6875:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatConvert_mpiaij_mpibaij_C", MatConvert_MPIAIJ_MPIBAIJ));
6876:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatConvert_mpiaij_mpisbaij_C", MatConvert_MPIAIJ_MPISBAIJ));
6877:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatConvert_mpiaij_mpidense_C", MatConvert_MPIAIJ_MPIDense));
6878: #if defined(PETSC_HAVE_ELEMENTAL)
6879:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatConvert_mpiaij_elemental_C", MatConvert_MPIAIJ_Elemental));
6880: #endif
6881: #if defined(PETSC_HAVE_SCALAPACK) && (defined(PETSC_USE_REAL_SINGLE) || defined(PETSC_USE_REAL_DOUBLE))
6882:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatConvert_mpiaij_scalapack_C", MatConvert_AIJ_ScaLAPACK));
6883: #endif
6884:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatConvert_mpiaij_is_C", MatConvert_XAIJ_IS));
6885:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatConvert_mpiaij_mpisell_C", MatConvert_MPIAIJ_MPISELL));
6886: #if defined(PETSC_HAVE_HYPRE)
6887:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatConvert_mpiaij_hypre_C", MatConvert_AIJ_HYPRE));
6888:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatProductSetFromOptions_transpose_mpiaij_mpiaij_C", MatProductSetFromOptions_Transpose_AIJ_AIJ));
6889: #endif
6890:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatProductSetFromOptions_is_mpiaij_C", MatProductSetFromOptions_IS_XAIJ));
6891:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatProductSetFromOptions_mpiaij_mpiaij_C", MatProductSetFromOptions_MPIAIJ));
6892:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatSetPreallocationCOO_C", MatSetPreallocationCOO_MPIAIJ));
6893:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatSetValuesCOO_C", MatSetValuesCOO_MPIAIJ));
6894:   PetscCall(PetscObjectChangeTypeName((PetscObject)B, MATMPIAIJ));
6895:   PetscFunctionReturn(PETSC_SUCCESS);
6896: }

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

6902:   Collective

6904:   Input Parameters:
6905: + comm - MPI communicator
6906: . m    - number of local rows (Cannot be `PETSC_DECIDE`)
6907: . n    - This value should be the same as the local size used in creating the
6908:          x vector for the matrix-vector product $y = Ax$. (or `PETSC_DECIDE` to have
6909:          calculated if `N` is given) For square matrices `n` is almost always `m`.
6910: . M    - number of global rows (or `PETSC_DETERMINE` to have calculated if `m` is given)
6911: . N    - number of global columns (or `PETSC_DETERMINE` to have calculated if `n` is given)
6912: . i    - row indices for "diagonal" portion of matrix; that is i[0] = 0, i[row] = i[row-1] + number of elements in that row of the matrix
6913: . j    - column indices, which must be local, i.e., based off the start column of the diagonal portion
6914: . a    - matrix values
6915: . oi   - row indices for "off-diagonal" portion of matrix; that is oi[0] = 0, oi[row] = oi[row-1] + number of elements in that row of the matrix
6916: . oj   - column indices, which must be global, representing global columns in the `MATMPIAIJ` matrix
6917: - oa   - matrix values

6919:   Output Parameter:
6920: . mat - the matrix

6922:   Level: advanced

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

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

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

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

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

6941: .seealso: [](ch_matrices), `Mat`, `MatCreate()`, `MatCreateSeqAIJ()`, `MatSetValues()`, `MatMPIAIJSetPreallocation()`, `MatMPIAIJSetPreallocationCSR()`,
6942:           `MATMPIAIJ`, `MatCreateAIJ()`, `MatCreateMPIAIJWithArrays()`
6943: @*/
6944: PetscErrorCode MatCreateMPIAIJWithSplitArrays(MPI_Comm comm, PetscInt m, PetscInt n, PetscInt M, PetscInt N, PetscInt i[], PetscInt j[], PetscScalar a[], PetscInt oi[], PetscInt oj[], PetscScalar oa[], Mat *mat)
6945: {
6946:   Mat_MPIAIJ *maij;

6948:   PetscFunctionBegin;
6949:   PetscCheck(m >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "local number of rows (m) cannot be PETSC_DECIDE, or negative");
6950:   PetscCheck(i[0] == 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "i (row indices) must start with 0");
6951:   PetscCheck(oi[0] == 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "oi (row indices) must start with 0");
6952:   PetscCall(MatCreate(comm, mat));
6953:   PetscCall(MatSetSizes(*mat, m, n, M, N));
6954:   PetscCall(MatSetType(*mat, MATMPIAIJ));
6955:   maij = (Mat_MPIAIJ *)(*mat)->data;

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

6959:   PetscCall(PetscLayoutSetUp((*mat)->rmap));
6960:   PetscCall(PetscLayoutSetUp((*mat)->cmap));

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

6965:   PetscCall(MatSetOption(*mat, MAT_NO_OFF_PROC_ENTRIES, PETSC_TRUE));
6966:   PetscCall(MatAssemblyBegin(*mat, MAT_FINAL_ASSEMBLY));
6967:   PetscCall(MatAssemblyEnd(*mat, MAT_FINAL_ASSEMBLY));
6968:   PetscCall(MatSetOption(*mat, MAT_NO_OFF_PROC_ENTRIES, PETSC_FALSE));
6969:   PetscCall(MatSetOption(*mat, MAT_NEW_NONZERO_LOCATION_ERR, PETSC_TRUE));
6970:   PetscFunctionReturn(PETSC_SUCCESS);
6971: }

6973: typedef struct {
6974:   Mat       *mp;    /* intermediate products */
6975:   PetscBool *mptmp; /* is the intermediate product temporary ? */
6976:   PetscInt   cp;    /* number of intermediate products */

6978:   /* support for MatGetBrowsOfAoCols_MPIAIJ for P_oth */
6979:   PetscInt    *startsj_s, *startsj_r;
6980:   PetscScalar *bufa;
6981:   Mat          P_oth;

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

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

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

6999:   /* customization */
7000:   PetscBool abmerge;
7001:   PetscBool P_oth_bind;
7002: } MatMatMPIAIJBACKEND;

7004: static PetscErrorCode MatProductCtxDestroy_MatMatMPIAIJBACKEND(PetscCtxRt data)
7005: {
7006:   MatMatMPIAIJBACKEND *mmdata = *(MatMatMPIAIJBACKEND **)data;
7007:   PetscInt             i;

7009:   PetscFunctionBegin;
7010:   PetscCall(PetscFree2(mmdata->startsj_s, mmdata->startsj_r));
7011:   PetscCall(PetscFree(mmdata->bufa));
7012:   PetscCall(PetscSFFree(mmdata->sf, mmdata->mtype, mmdata->coo_v));
7013:   PetscCall(PetscSFFree(mmdata->sf, mmdata->mtype, mmdata->coo_w));
7014:   PetscCall(MatDestroy(&mmdata->P_oth));
7015:   PetscCall(MatDestroy(&mmdata->Bloc));
7016:   PetscCall(PetscSFDestroy(&mmdata->sf));
7017:   for (i = 0; i < mmdata->cp; i++) PetscCall(MatDestroy(&mmdata->mp[i]));
7018:   PetscCall(PetscFree2(mmdata->mp, mmdata->mptmp));
7019:   PetscCall(PetscFree(mmdata->own[0]));
7020:   PetscCall(PetscFree(mmdata->own));
7021:   PetscCall(PetscFree(mmdata->off[0]));
7022:   PetscCall(PetscFree(mmdata->off));
7023:   PetscCall(PetscFree(mmdata));
7024:   PetscFunctionReturn(PETSC_SUCCESS);
7025: }

7027: /* Copy selected n entries with indices in idx[] of A to v[].
7028:    If idx is NULL, copy the whole data array of A to v[]
7029:  */
7030: static PetscErrorCode MatSeqAIJCopySubArray(Mat A, PetscInt n, const PetscInt idx[], PetscScalar v[])
7031: {
7032:   PetscErrorCode (*f)(Mat, PetscInt, const PetscInt[], PetscScalar[]);

7034:   PetscFunctionBegin;
7035:   PetscCall(PetscObjectQueryFunction((PetscObject)A, "MatSeqAIJCopySubArray_C", &f));
7036:   if (f) PetscCall((*f)(A, n, idx, v));
7037:   else {
7038:     const PetscScalar *vv;

7040:     PetscCall(MatSeqAIJGetArrayRead(A, &vv));
7041:     if (n && idx) {
7042:       PetscScalar    *w  = v;
7043:       const PetscInt *oi = idx;
7044:       PetscInt        j;

7046:       for (j = 0; j < n; j++) *w++ = vv[*oi++];
7047:     } else {
7048:       PetscCall(PetscArraycpy(v, vv, n));
7049:     }
7050:     PetscCall(MatSeqAIJRestoreArrayRead(A, &vv));
7051:   }
7052:   PetscFunctionReturn(PETSC_SUCCESS);
7053: }

7055: static PetscErrorCode MatProductNumeric_MPIAIJBACKEND(Mat C)
7056: {
7057:   MatMatMPIAIJBACKEND *mmdata;
7058:   PetscInt             i, n_d, n_o;

7060:   PetscFunctionBegin;
7061:   MatCheckProduct(C, 1);
7062:   PetscCheck(C->product->data, PetscObjectComm((PetscObject)C), PETSC_ERR_PLIB, "Product data empty");
7063:   mmdata = (MatMatMPIAIJBACKEND *)C->product->data;
7064:   if (!mmdata->reusesym) { /* update temporary matrices */
7065:     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));
7066:     if (mmdata->Bloc) PetscCall(MatMPIAIJGetLocalMatMerge(C->product->B, MAT_REUSE_MATRIX, NULL, &mmdata->Bloc));
7067:   }
7068:   mmdata->reusesym = PETSC_FALSE;

7070:   for (i = 0; i < mmdata->cp; i++) {
7071:     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]);
7072:     PetscCall((*mmdata->mp[i]->ops->productnumeric)(mmdata->mp[i]));
7073:   }
7074:   for (i = 0, n_d = 0, n_o = 0; i < mmdata->cp; i++) {
7075:     PetscInt noff;

7077:     PetscCall(PetscIntCast(mmdata->off[i + 1] - mmdata->off[i], &noff));
7078:     if (mmdata->mptmp[i]) continue;
7079:     if (noff) {
7080:       PetscInt nown;

7082:       PetscCall(PetscIntCast(mmdata->own[i + 1] - mmdata->own[i], &nown));
7083:       PetscCall(MatSeqAIJCopySubArray(mmdata->mp[i], noff, mmdata->off[i], mmdata->coo_w + n_o));
7084:       PetscCall(MatSeqAIJCopySubArray(mmdata->mp[i], nown, mmdata->own[i], mmdata->coo_v + n_d));
7085:       n_o += noff;
7086:       n_d += nown;
7087:     } else {
7088:       Mat_SeqAIJ *mm = (Mat_SeqAIJ *)mmdata->mp[i]->data;

7090:       PetscCall(MatSeqAIJCopySubArray(mmdata->mp[i], mm->nz, NULL, mmdata->coo_v + n_d));
7091:       n_d += mm->nz;
7092:     }
7093:   }
7094:   if (mmdata->hasoffproc) { /* offprocess insertion */
7095:     PetscCall(PetscSFGatherBegin(mmdata->sf, MPIU_SCALAR, mmdata->coo_w, mmdata->coo_v + n_d));
7096:     PetscCall(PetscSFGatherEnd(mmdata->sf, MPIU_SCALAR, mmdata->coo_w, mmdata->coo_v + n_d));
7097:   }
7098:   PetscCall(MatSetValuesCOO(C, mmdata->coo_v, INSERT_VALUES));
7099:   PetscFunctionReturn(PETSC_SUCCESS);
7100: }

7102: /* Support for Pt * A, A * P, or Pt * A * P */
7103: #define MAX_NUMBER_INTERMEDIATE 4
7104: PetscErrorCode MatProductSymbolic_MPIAIJBACKEND(Mat C)
7105: {
7106:   Mat_Product           *product = C->product;
7107:   Mat                    A, P, mp[MAX_NUMBER_INTERMEDIATE]; /* A, P and a series of intermediate matrices */
7108:   Mat_MPIAIJ            *a, *p;
7109:   MatMatMPIAIJBACKEND   *mmdata;
7110:   ISLocalToGlobalMapping P_oth_l2g = NULL;
7111:   IS                     glob      = NULL;
7112:   const char            *prefix;
7113:   char                   pprefix[256];
7114:   const PetscInt        *globidx, *P_oth_idx;
7115:   PetscInt               i, j, cp, m, n, M, N, *coo_i, *coo_j;
7116:   PetscCount             ncoo, ncoo_d, ncoo_o, ncoo_oown;
7117:   PetscInt               cmapt[MAX_NUMBER_INTERMEDIATE], rmapt[MAX_NUMBER_INTERMEDIATE]; /* col/row map type for each Mat in mp[]. */
7118:                                                                                          /* type-0: consecutive, start from 0; type-1: consecutive with */
7119:                                                                                          /* a base offset; type-2: sparse with a local to global map table */
7120:   const PetscInt *cmapa[MAX_NUMBER_INTERMEDIATE], *rmapa[MAX_NUMBER_INTERMEDIATE];       /* col/row local to global map array (table) for type-2 map type */

7122:   MatProductType ptype;
7123:   PetscBool      mptmp[MAX_NUMBER_INTERMEDIATE], hasoffproc = PETSC_FALSE, iscuda, iship, iskokk;
7124:   PetscMPIInt    size;

7126:   PetscFunctionBegin;
7127:   MatCheckProduct(C, 1);
7128:   PetscCheck(!product->data, PetscObjectComm((PetscObject)C), PETSC_ERR_PLIB, "Product data not empty");
7129:   ptype = product->type;
7130:   if (product->A->symmetric == PETSC_BOOL3_TRUE && ptype == MATPRODUCT_AtB) {
7131:     ptype                                          = MATPRODUCT_AB;
7132:     product->symbolic_used_the_fact_A_is_symmetric = PETSC_TRUE;
7133:   }
7134:   switch (ptype) {
7135:   case MATPRODUCT_AB:
7136:     A          = product->A;
7137:     P          = product->B;
7138:     m          = A->rmap->n;
7139:     n          = P->cmap->n;
7140:     M          = A->rmap->N;
7141:     N          = P->cmap->N;
7142:     hasoffproc = PETSC_FALSE; /* will not scatter mat product values to other processes */
7143:     break;
7144:   case MATPRODUCT_AtB:
7145:     P          = product->A;
7146:     A          = product->B;
7147:     m          = P->cmap->n;
7148:     n          = A->cmap->n;
7149:     M          = P->cmap->N;
7150:     N          = A->cmap->N;
7151:     hasoffproc = PETSC_TRUE;
7152:     break;
7153:   case MATPRODUCT_PtAP:
7154:     A          = product->A;
7155:     P          = product->B;
7156:     m          = P->cmap->n;
7157:     n          = P->cmap->n;
7158:     M          = P->cmap->N;
7159:     N          = P->cmap->N;
7160:     hasoffproc = PETSC_TRUE;
7161:     break;
7162:   default:
7163:     SETERRQ(PetscObjectComm((PetscObject)C), PETSC_ERR_PLIB, "Not for product type %s", MatProductTypes[ptype]);
7164:   }
7165:   PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)C), &size));
7166:   if (size == 1) hasoffproc = PETSC_FALSE;

7168:   /* defaults */
7169:   for (i = 0; i < MAX_NUMBER_INTERMEDIATE; i++) {
7170:     mp[i]    = NULL;
7171:     mptmp[i] = PETSC_FALSE;
7172:     rmapt[i] = -1;
7173:     cmapt[i] = -1;
7174:     rmapa[i] = NULL;
7175:     cmapa[i] = NULL;
7176:   }

7178:   /* customization */
7179:   PetscCall(PetscNew(&mmdata));
7180:   mmdata->reusesym = product->api_user;
7181:   if (ptype == MATPRODUCT_AB) {
7182:     if (product->api_user) {
7183:       PetscOptionsBegin(PetscObjectComm((PetscObject)C), ((PetscObject)C)->prefix, "MatMatMult", "Mat");
7184:       PetscCall(PetscOptionsBool("-matmatmult_backend_mergeB", "Merge product->B local matrices", "MatMatMult", mmdata->abmerge, &mmdata->abmerge, NULL));
7185:       PetscCall(PetscOptionsBool("-matmatmult_backend_pothbind", "Bind P_oth to CPU", "MatBindToCPU", mmdata->P_oth_bind, &mmdata->P_oth_bind, NULL));
7186:       PetscOptionsEnd();
7187:     } else {
7188:       PetscOptionsBegin(PetscObjectComm((PetscObject)C), ((PetscObject)C)->prefix, "MatProduct_AB", "Mat");
7189:       PetscCall(PetscOptionsBool("-mat_product_algorithm_backend_mergeB", "Merge product->B local matrices", "MatMatMult", mmdata->abmerge, &mmdata->abmerge, NULL));
7190:       PetscCall(PetscOptionsBool("-mat_product_algorithm_backend_pothbind", "Bind P_oth to CPU", "MatBindToCPU", mmdata->P_oth_bind, &mmdata->P_oth_bind, NULL));
7191:       PetscOptionsEnd();
7192:     }
7193:   } else if (ptype == MATPRODUCT_PtAP) {
7194:     if (product->api_user) {
7195:       PetscOptionsBegin(PetscObjectComm((PetscObject)C), ((PetscObject)C)->prefix, "MatPtAP", "Mat");
7196:       PetscCall(PetscOptionsBool("-matptap_backend_pothbind", "Bind P_oth to CPU", "MatBindToCPU", mmdata->P_oth_bind, &mmdata->P_oth_bind, NULL));
7197:       PetscOptionsEnd();
7198:     } else {
7199:       PetscOptionsBegin(PetscObjectComm((PetscObject)C), ((PetscObject)C)->prefix, "MatProduct_PtAP", "Mat");
7200:       PetscCall(PetscOptionsBool("-mat_product_algorithm_backend_pothbind", "Bind P_oth to CPU", "MatBindToCPU", mmdata->P_oth_bind, &mmdata->P_oth_bind, NULL));
7201:       PetscOptionsEnd();
7202:     }
7203:   }
7204:   a = (Mat_MPIAIJ *)A->data;
7205:   p = (Mat_MPIAIJ *)P->data;
7206:   PetscCall(MatSetSizes(C, m, n, M, N));
7207:   PetscCall(PetscLayoutSetUp(C->rmap));
7208:   PetscCall(PetscLayoutSetUp(C->cmap));
7209:   PetscCall(MatSetType(C, ((PetscObject)A)->type_name));
7210:   PetscCall(MatGetOptionsPrefix(C, &prefix));

7212:   cp = 0;
7213:   switch (ptype) {
7214:   case MATPRODUCT_AB: /* A * P */
7215:     PetscCall(MatGetBrowsOfAoCols_MPIAIJ(A, P, MAT_INITIAL_MATRIX, &mmdata->startsj_s, &mmdata->startsj_r, &mmdata->bufa, &mmdata->P_oth));

7217:     /* A_diag * P_local (merged or not) */
7218:     if (mmdata->abmerge) { /* P's diagonal and off-diag blocks are merged to one matrix, then multiplied by A_diag */
7219:       /* P is product->B */
7220:       PetscCall(MatMPIAIJGetLocalMatMerge(P, MAT_INITIAL_MATRIX, &glob, &mmdata->Bloc));
7221:       PetscCall(MatProductCreate(a->A, mmdata->Bloc, NULL, &mp[cp]));
7222:       PetscCall(MatProductSetType(mp[cp], MATPRODUCT_AB));
7223:       PetscCall(MatProductSetFill(mp[cp], product->fill));
7224:       PetscCall(PetscSNPrintf(pprefix, sizeof(pprefix), "backend_p%" PetscInt_FMT "_", cp));
7225:       PetscCall(MatSetOptionsPrefix(mp[cp], prefix));
7226:       PetscCall(MatAppendOptionsPrefix(mp[cp], pprefix));
7227:       mp[cp]->product->api_user = product->api_user;
7228:       PetscCall(MatProductSetFromOptions(mp[cp]));
7229:       PetscCall((*mp[cp]->ops->productsymbolic)(mp[cp]));
7230:       PetscCall(ISGetIndices(glob, &globidx));
7231:       rmapt[cp] = 1;
7232:       cmapt[cp] = 2;
7233:       cmapa[cp] = globidx;
7234:       mptmp[cp] = PETSC_FALSE;
7235:       cp++;
7236:     } else { /* A_diag * P_diag and A_diag * P_off */
7237:       PetscCall(MatProductCreate(a->A, p->A, NULL, &mp[cp]));
7238:       PetscCall(MatProductSetType(mp[cp], MATPRODUCT_AB));
7239:       PetscCall(MatProductSetFill(mp[cp], product->fill));
7240:       PetscCall(PetscSNPrintf(pprefix, sizeof(pprefix), "backend_p%" PetscInt_FMT "_", cp));
7241:       PetscCall(MatSetOptionsPrefix(mp[cp], prefix));
7242:       PetscCall(MatAppendOptionsPrefix(mp[cp], pprefix));
7243:       mp[cp]->product->api_user = product->api_user;
7244:       PetscCall(MatProductSetFromOptions(mp[cp]));
7245:       PetscCall((*mp[cp]->ops->productsymbolic)(mp[cp]));
7246:       rmapt[cp] = 1;
7247:       cmapt[cp] = 1;
7248:       mptmp[cp] = PETSC_FALSE;
7249:       cp++;
7250:       PetscCall(MatProductCreate(a->A, p->B, NULL, &mp[cp]));
7251:       PetscCall(MatProductSetType(mp[cp], MATPRODUCT_AB));
7252:       PetscCall(MatProductSetFill(mp[cp], product->fill));
7253:       PetscCall(PetscSNPrintf(pprefix, sizeof(pprefix), "backend_p%" PetscInt_FMT "_", cp));
7254:       PetscCall(MatSetOptionsPrefix(mp[cp], prefix));
7255:       PetscCall(MatAppendOptionsPrefix(mp[cp], pprefix));
7256:       mp[cp]->product->api_user = product->api_user;
7257:       PetscCall(MatProductSetFromOptions(mp[cp]));
7258:       PetscCall((*mp[cp]->ops->productsymbolic)(mp[cp]));
7259:       rmapt[cp] = 1;
7260:       cmapt[cp] = 2;
7261:       cmapa[cp] = p->garray;
7262:       mptmp[cp] = PETSC_FALSE;
7263:       cp++;
7264:     }

7266:     /* A_off * P_other */
7267:     if (mmdata->P_oth) {
7268:       PetscCall(MatSeqAIJCompactOutExtraColumns_SeqAIJ(mmdata->P_oth, &P_oth_l2g)); /* make P_oth use local col ids */
7269:       PetscCall(ISLocalToGlobalMappingGetIndices(P_oth_l2g, &P_oth_idx));
7270:       PetscCall(MatSetType(mmdata->P_oth, ((PetscObject)a->B)->type_name));
7271:       PetscCall(MatBindToCPU(mmdata->P_oth, mmdata->P_oth_bind));
7272:       PetscCall(MatProductCreate(a->B, mmdata->P_oth, NULL, &mp[cp]));
7273:       PetscCall(MatProductSetType(mp[cp], MATPRODUCT_AB));
7274:       PetscCall(MatProductSetFill(mp[cp], product->fill));
7275:       PetscCall(PetscSNPrintf(pprefix, sizeof(pprefix), "backend_p%" PetscInt_FMT "_", cp));
7276:       PetscCall(MatSetOptionsPrefix(mp[cp], prefix));
7277:       PetscCall(MatAppendOptionsPrefix(mp[cp], pprefix));
7278:       mp[cp]->product->api_user = product->api_user;
7279:       PetscCall(MatProductSetFromOptions(mp[cp]));
7280:       PetscCall((*mp[cp]->ops->productsymbolic)(mp[cp]));
7281:       rmapt[cp] = 1;
7282:       cmapt[cp] = 2;
7283:       cmapa[cp] = P_oth_idx;
7284:       mptmp[cp] = PETSC_FALSE;
7285:       cp++;
7286:     }
7287:     break;

7289:   case MATPRODUCT_AtB: /* (P^t * A): P_diag * A_loc + P_off * A_loc */
7290:     /* A is product->B */
7291:     PetscCall(MatMPIAIJGetLocalMatMerge(A, MAT_INITIAL_MATRIX, &glob, &mmdata->Bloc));
7292:     if (A == P) { /* when A==P, we can take advantage of the already merged mmdata->Bloc */
7293:       PetscCall(MatProductCreate(mmdata->Bloc, mmdata->Bloc, NULL, &mp[cp]));
7294:       PetscCall(MatProductSetType(mp[cp], MATPRODUCT_AtB));
7295:       PetscCall(MatProductSetFill(mp[cp], product->fill));
7296:       PetscCall(PetscSNPrintf(pprefix, sizeof(pprefix), "backend_p%" PetscInt_FMT "_", cp));
7297:       PetscCall(MatSetOptionsPrefix(mp[cp], prefix));
7298:       PetscCall(MatAppendOptionsPrefix(mp[cp], pprefix));
7299:       mp[cp]->product->api_user = product->api_user;
7300:       PetscCall(MatProductSetFromOptions(mp[cp]));
7301:       PetscCall((*mp[cp]->ops->productsymbolic)(mp[cp]));
7302:       PetscCall(ISGetIndices(glob, &globidx));
7303:       rmapt[cp] = 2;
7304:       rmapa[cp] = globidx;
7305:       cmapt[cp] = 2;
7306:       cmapa[cp] = globidx;
7307:       mptmp[cp] = PETSC_FALSE;
7308:       cp++;
7309:     } else {
7310:       PetscCall(MatProductCreate(p->A, mmdata->Bloc, NULL, &mp[cp]));
7311:       PetscCall(MatProductSetType(mp[cp], MATPRODUCT_AtB));
7312:       PetscCall(MatProductSetFill(mp[cp], product->fill));
7313:       PetscCall(PetscSNPrintf(pprefix, sizeof(pprefix), "backend_p%" PetscInt_FMT "_", cp));
7314:       PetscCall(MatSetOptionsPrefix(mp[cp], prefix));
7315:       PetscCall(MatAppendOptionsPrefix(mp[cp], pprefix));
7316:       mp[cp]->product->api_user = product->api_user;
7317:       PetscCall(MatProductSetFromOptions(mp[cp]));
7318:       PetscCall((*mp[cp]->ops->productsymbolic)(mp[cp]));
7319:       PetscCall(ISGetIndices(glob, &globidx));
7320:       rmapt[cp] = 1;
7321:       cmapt[cp] = 2;
7322:       cmapa[cp] = globidx;
7323:       mptmp[cp] = PETSC_FALSE;
7324:       cp++;
7325:       PetscCall(MatProductCreate(p->B, mmdata->Bloc, NULL, &mp[cp]));
7326:       PetscCall(MatProductSetType(mp[cp], MATPRODUCT_AtB));
7327:       PetscCall(MatProductSetFill(mp[cp], product->fill));
7328:       PetscCall(PetscSNPrintf(pprefix, sizeof(pprefix), "backend_p%" PetscInt_FMT "_", cp));
7329:       PetscCall(MatSetOptionsPrefix(mp[cp], prefix));
7330:       PetscCall(MatAppendOptionsPrefix(mp[cp], pprefix));
7331:       mp[cp]->product->api_user = product->api_user;
7332:       PetscCall(MatProductSetFromOptions(mp[cp]));
7333:       PetscCall((*mp[cp]->ops->productsymbolic)(mp[cp]));
7334:       rmapt[cp] = 2;
7335:       rmapa[cp] = p->garray;
7336:       cmapt[cp] = 2;
7337:       cmapa[cp] = globidx;
7338:       mptmp[cp] = PETSC_FALSE;
7339:       cp++;
7340:     }
7341:     break;
7342:   case MATPRODUCT_PtAP:
7343:     PetscCall(MatGetBrowsOfAoCols_MPIAIJ(A, P, MAT_INITIAL_MATRIX, &mmdata->startsj_s, &mmdata->startsj_r, &mmdata->bufa, &mmdata->P_oth));
7344:     /* P is product->B */
7345:     PetscCall(MatMPIAIJGetLocalMatMerge(P, MAT_INITIAL_MATRIX, &glob, &mmdata->Bloc));
7346:     PetscCall(MatProductCreate(a->A, mmdata->Bloc, NULL, &mp[cp]));
7347:     PetscCall(MatProductSetType(mp[cp], MATPRODUCT_PtAP));
7348:     PetscCall(MatProductSetFill(mp[cp], product->fill));
7349:     PetscCall(PetscSNPrintf(pprefix, sizeof(pprefix), "backend_p%" PetscInt_FMT "_", cp));
7350:     PetscCall(MatSetOptionsPrefix(mp[cp], prefix));
7351:     PetscCall(MatAppendOptionsPrefix(mp[cp], pprefix));
7352:     mp[cp]->product->api_user = product->api_user;
7353:     PetscCall(MatProductSetFromOptions(mp[cp]));
7354:     PetscCall((*mp[cp]->ops->productsymbolic)(mp[cp]));
7355:     PetscCall(ISGetIndices(glob, &globidx));
7356:     rmapt[cp] = 2;
7357:     rmapa[cp] = globidx;
7358:     cmapt[cp] = 2;
7359:     cmapa[cp] = globidx;
7360:     mptmp[cp] = PETSC_FALSE;
7361:     cp++;
7362:     if (mmdata->P_oth) {
7363:       PetscCall(MatSeqAIJCompactOutExtraColumns_SeqAIJ(mmdata->P_oth, &P_oth_l2g));
7364:       PetscCall(ISLocalToGlobalMappingGetIndices(P_oth_l2g, &P_oth_idx));
7365:       PetscCall(MatSetType(mmdata->P_oth, ((PetscObject)a->B)->type_name));
7366:       PetscCall(MatBindToCPU(mmdata->P_oth, mmdata->P_oth_bind));
7367:       PetscCall(MatProductCreate(a->B, mmdata->P_oth, NULL, &mp[cp]));
7368:       PetscCall(MatProductSetType(mp[cp], MATPRODUCT_AB));
7369:       PetscCall(MatProductSetFill(mp[cp], product->fill));
7370:       PetscCall(PetscSNPrintf(pprefix, sizeof(pprefix), "backend_p%" PetscInt_FMT "_", cp));
7371:       PetscCall(MatSetOptionsPrefix(mp[cp], prefix));
7372:       PetscCall(MatAppendOptionsPrefix(mp[cp], pprefix));
7373:       mp[cp]->product->api_user = product->api_user;
7374:       PetscCall(MatProductSetFromOptions(mp[cp]));
7375:       PetscCall((*mp[cp]->ops->productsymbolic)(mp[cp]));
7376:       mptmp[cp] = PETSC_TRUE;
7377:       cp++;
7378:       PetscCall(MatProductCreate(mmdata->Bloc, mp[1], NULL, &mp[cp]));
7379:       PetscCall(MatProductSetType(mp[cp], MATPRODUCT_AtB));
7380:       PetscCall(MatProductSetFill(mp[cp], product->fill));
7381:       PetscCall(PetscSNPrintf(pprefix, sizeof(pprefix), "backend_p%" PetscInt_FMT "_", cp));
7382:       PetscCall(MatSetOptionsPrefix(mp[cp], prefix));
7383:       PetscCall(MatAppendOptionsPrefix(mp[cp], pprefix));
7384:       mp[cp]->product->api_user = product->api_user;
7385:       PetscCall(MatProductSetFromOptions(mp[cp]));
7386:       PetscCall((*mp[cp]->ops->productsymbolic)(mp[cp]));
7387:       rmapt[cp] = 2;
7388:       rmapa[cp] = globidx;
7389:       cmapt[cp] = 2;
7390:       cmapa[cp] = P_oth_idx;
7391:       mptmp[cp] = PETSC_FALSE;
7392:       cp++;
7393:     }
7394:     break;
7395:   default:
7396:     SETERRQ(PetscObjectComm((PetscObject)C), PETSC_ERR_PLIB, "Not for product type %s", MatProductTypes[ptype]);
7397:   }
7398:   /* sanity check */
7399:   if (size > 1)
7400:     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);

7402:   PetscCall(PetscMalloc2(cp, &mmdata->mp, cp, &mmdata->mptmp));
7403:   for (i = 0; i < cp; i++) {
7404:     mmdata->mp[i]    = mp[i];
7405:     mmdata->mptmp[i] = mptmp[i];
7406:   }
7407:   mmdata->cp             = cp;
7408:   C->product->data       = mmdata;
7409:   C->product->destroy    = MatProductCtxDestroy_MatMatMPIAIJBACKEND;
7410:   C->ops->productnumeric = MatProductNumeric_MPIAIJBACKEND;

7412:   /* memory type */
7413:   mmdata->mtype = PETSC_MEMTYPE_HOST;
7414:   PetscCall(PetscObjectTypeCompareAny((PetscObject)C, &iscuda, MATSEQAIJCUSPARSE, MATMPIAIJCUSPARSE, ""));
7415:   PetscCall(PetscObjectTypeCompareAny((PetscObject)C, &iship, MATSEQAIJHIPSPARSE, MATMPIAIJHIPSPARSE, ""));
7416:   PetscCall(PetscObjectTypeCompareAny((PetscObject)C, &iskokk, MATSEQAIJKOKKOS, MATMPIAIJKOKKOS, ""));
7417:   if (iscuda) mmdata->mtype = PETSC_MEMTYPE_CUDA;
7418:   else if (iship) mmdata->mtype = PETSC_MEMTYPE_HIP;
7419:   else if (iskokk) mmdata->mtype = PETSC_MEMTYPE_KOKKOS;

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

7423:   /* count total nonzeros of those intermediate seqaij Mats
7424:     ncoo_d:    # of nonzeros of matrices that do not have offproc entries
7425:     ncoo_o:    # of nonzeros (of matrices that might have offproc entries) that will be inserted to remote procs
7426:     ncoo_oown: # of nonzeros (of matrices that might have offproc entries) that will be inserted locally
7427:   */
7428:   for (cp = 0, ncoo_d = 0, ncoo_o = 0, ncoo_oown = 0; cp < mmdata->cp; cp++) {
7429:     Mat_SeqAIJ *mm = (Mat_SeqAIJ *)mp[cp]->data;
7430:     if (mptmp[cp]) continue;
7431:     if (rmapt[cp] == 2 && hasoffproc) { /* the rows need to be scatter to all processes (might include self) */
7432:       const PetscInt *rmap = rmapa[cp];
7433:       const PetscInt  mr   = mp[cp]->rmap->n;
7434:       const PetscInt  rs   = C->rmap->rstart;
7435:       const PetscInt  re   = C->rmap->rend;
7436:       const PetscInt *ii   = mm->i;
7437:       for (i = 0; i < mr; i++) {
7438:         const PetscInt gr = rmap[i];
7439:         const PetscInt nz = ii[i + 1] - ii[i];
7440:         if (gr < rs || gr >= re) ncoo_o += nz; /* this row is offproc */
7441:         else ncoo_oown += nz;                  /* this row is local */
7442:       }
7443:     } else ncoo_d += mm->nz;
7444:   }

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

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

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

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

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

7463:   /* gather (i,j) of nonzeros inserted by remote procs */
7464:   if (hasoffproc) {
7465:     PetscSF  msf;
7466:     PetscInt ncoo2, *coo_i2, *coo_j2;

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

7472:     for (cp = 0, ncoo_o = 0; cp < mmdata->cp; cp++) {
7473:       Mat_SeqAIJ *mm     = (Mat_SeqAIJ *)mp[cp]->data;
7474:       PetscInt   *idxoff = mmdata->off[cp];
7475:       PetscInt   *idxown = mmdata->own[cp];
7476:       if (!mptmp[cp] && rmapt[cp] == 2) { /* row map is sparse */
7477:         const PetscInt *rmap = rmapa[cp];
7478:         const PetscInt *cmap = cmapa[cp];
7479:         const PetscInt *ii   = mm->i;
7480:         PetscInt       *coi  = coo_i + ncoo_o;
7481:         PetscInt       *coj  = coo_j + ncoo_o;
7482:         const PetscInt  mr   = mp[cp]->rmap->n;
7483:         const PetscInt  rs   = C->rmap->rstart;
7484:         const PetscInt  re   = C->rmap->rend;
7485:         const PetscInt  cs   = C->cmap->rstart;
7486:         for (i = 0; i < mr; i++) {
7487:           const PetscInt *jj = mm->j + ii[i];
7488:           const PetscInt  gr = rmap[i];
7489:           const PetscInt  nz = ii[i + 1] - ii[i];
7490:           if (gr < rs || gr >= re) { /* this is an offproc row */
7491:             for (j = ii[i]; j < ii[i + 1]; j++) {
7492:               *coi++    = gr;
7493:               *idxoff++ = j;
7494:             }
7495:             if (!cmapt[cp]) { /* already global */
7496:               for (j = 0; j < nz; j++) *coj++ = jj[j];
7497:             } else if (cmapt[cp] == 1) { /* local to global for owned columns of C */
7498:               for (j = 0; j < nz; j++) *coj++ = jj[j] + cs;
7499:             } else { /* offdiag */
7500:               for (j = 0; j < nz; j++) *coj++ = cmap[jj[j]];
7501:             }
7502:             ncoo_o += nz;
7503:           } else { /* this is a local row */
7504:             for (j = ii[i]; j < ii[i + 1]; j++) *idxown++ = j;
7505:           }
7506:         }
7507:       }
7508:       mmdata->off[cp + 1] = idxoff;
7509:       mmdata->own[cp + 1] = idxown;
7510:     }

7512:     PetscCall(PetscSFCreate(PetscObjectComm((PetscObject)C), &mmdata->sf));
7513:     PetscInt incoo_o;
7514:     PetscCall(PetscIntCast(ncoo_o, &incoo_o));
7515:     PetscCall(PetscSFSetGraphLayout(mmdata->sf, C->rmap, incoo_o /*nleaves*/, NULL /*ilocal*/, PETSC_OWN_POINTER, coo_i));
7516:     PetscCall(PetscSFGetMultiSF(mmdata->sf, &msf));
7517:     PetscCall(PetscSFGetGraph(msf, &ncoo2 /*nroots*/, NULL, NULL, NULL));
7518:     ncoo = ncoo_d + ncoo_oown + ncoo2;
7519:     PetscCall(PetscMalloc2(ncoo, &coo_i2, ncoo, &coo_j2));
7520:     PetscCall(PetscSFGatherBegin(mmdata->sf, MPIU_INT, coo_i, coo_i2 + ncoo_d + ncoo_oown)); /* put (i,j) of remote nonzeros at back */
7521:     PetscCall(PetscSFGatherEnd(mmdata->sf, MPIU_INT, coo_i, coo_i2 + ncoo_d + ncoo_oown));
7522:     PetscCall(PetscSFGatherBegin(mmdata->sf, MPIU_INT, coo_j, coo_j2 + ncoo_d + ncoo_oown));
7523:     PetscCall(PetscSFGatherEnd(mmdata->sf, MPIU_INT, coo_j, coo_j2 + ncoo_d + ncoo_oown));
7524:     PetscCall(PetscFree2(coo_i, coo_j));
7525:     /* allocate MPI send buffer to collect nonzero values to be sent to remote procs */
7526:     PetscCall(PetscSFMalloc(mmdata->sf, mmdata->mtype, ncoo_o * sizeof(PetscScalar), (void **)&mmdata->coo_w));
7527:     coo_i = coo_i2;
7528:     coo_j = coo_j2;
7529:   } else { /* no offproc values insertion */
7530:     ncoo = ncoo_d;
7531:     PetscCall(PetscMalloc2(ncoo, &coo_i, ncoo, &coo_j));

7533:     PetscCall(PetscSFCreate(PetscObjectComm((PetscObject)C), &mmdata->sf));
7534:     PetscCall(PetscSFSetGraph(mmdata->sf, 0, 0, NULL, PETSC_OWN_POINTER, NULL, PETSC_OWN_POINTER));
7535:     PetscCall(PetscSFSetUp(mmdata->sf));
7536:   }
7537:   mmdata->hasoffproc = hasoffproc;

7539:   /* gather (i,j) of nonzeros inserted locally */
7540:   for (cp = 0, ncoo_d = 0; cp < mmdata->cp; cp++) {
7541:     Mat_SeqAIJ     *mm   = (Mat_SeqAIJ *)mp[cp]->data;
7542:     PetscInt       *coi  = coo_i + ncoo_d;
7543:     PetscInt       *coj  = coo_j + ncoo_d;
7544:     const PetscInt *jj   = mm->j;
7545:     const PetscInt *ii   = mm->i;
7546:     const PetscInt *cmap = cmapa[cp];
7547:     const PetscInt *rmap = rmapa[cp];
7548:     const PetscInt  mr   = mp[cp]->rmap->n;
7549:     const PetscInt  rs   = C->rmap->rstart;
7550:     const PetscInt  re   = C->rmap->rend;
7551:     const PetscInt  cs   = C->cmap->rstart;

7553:     if (mptmp[cp]) continue;
7554:     if (rmapt[cp] == 1) { /* consecutive rows */
7555:       /* fill coo_i */
7556:       for (i = 0; i < mr; i++) {
7557:         const PetscInt gr = i + rs;
7558:         for (j = ii[i]; j < ii[i + 1]; j++) coi[j] = gr;
7559:       }
7560:       /* fill coo_j */
7561:       if (!cmapt[cp]) { /* type-0, already global */
7562:         PetscCall(PetscArraycpy(coj, jj, mm->nz));
7563:       } else if (cmapt[cp] == 1) {                        /* type-1, local to global for consecutive columns of C */
7564:         for (j = 0; j < mm->nz; j++) coj[j] = jj[j] + cs; /* lid + col start */
7565:       } else {                                            /* type-2, local to global for sparse columns */
7566:         for (j = 0; j < mm->nz; j++) coj[j] = cmap[jj[j]];
7567:       }
7568:       ncoo_d += mm->nz;
7569:     } else if (rmapt[cp] == 2) { /* sparse rows */
7570:       for (i = 0; i < mr; i++) {
7571:         const PetscInt *jj = mm->j + ii[i];
7572:         const PetscInt  gr = rmap[i];
7573:         const PetscInt  nz = ii[i + 1] - ii[i];
7574:         if (gr >= rs && gr < re) { /* local rows */
7575:           for (j = ii[i]; j < ii[i + 1]; j++) *coi++ = gr;
7576:           if (!cmapt[cp]) { /* type-0, already global */
7577:             for (j = 0; j < nz; j++) *coj++ = jj[j];
7578:           } else if (cmapt[cp] == 1) { /* local to global for owned columns of C */
7579:             for (j = 0; j < nz; j++) *coj++ = jj[j] + cs;
7580:           } else { /* type-2, local to global for sparse columns */
7581:             for (j = 0; j < nz; j++) *coj++ = cmap[jj[j]];
7582:           }
7583:           ncoo_d += nz;
7584:         }
7585:       }
7586:     }
7587:   }
7588:   if (glob) PetscCall(ISRestoreIndices(glob, &globidx));
7589:   PetscCall(ISDestroy(&glob));
7590:   if (P_oth_l2g) PetscCall(ISLocalToGlobalMappingRestoreIndices(P_oth_l2g, &P_oth_idx));
7591:   PetscCall(ISLocalToGlobalMappingDestroy(&P_oth_l2g));
7592:   /* allocate an array to store all nonzeros (inserted locally or remotely) belonging to this proc */
7593:   PetscCall(PetscSFMalloc(mmdata->sf, mmdata->mtype, ncoo * sizeof(PetscScalar), (void **)&mmdata->coo_v));

7595:   /* set block sizes */
7596:   A = product->A;
7597:   P = product->B;
7598:   switch (ptype) {
7599:   case MATPRODUCT_PtAP:
7600:     PetscCall(MatSetBlockSizes(C, P->cmap->bs, P->cmap->bs));
7601:     break;
7602:   case MATPRODUCT_RARt:
7603:     PetscCall(MatSetBlockSizes(C, P->rmap->bs, P->rmap->bs));
7604:     break;
7605:   case MATPRODUCT_ABC:
7606:     PetscCall(MatSetBlockSizesFromMats(C, A, product->C));
7607:     break;
7608:   case MATPRODUCT_AB:
7609:     PetscCall(MatSetBlockSizesFromMats(C, A, P));
7610:     break;
7611:   case MATPRODUCT_AtB:
7612:     PetscCall(MatSetBlockSizes(C, A->cmap->bs, P->cmap->bs));
7613:     break;
7614:   case MATPRODUCT_ABt:
7615:     PetscCall(MatSetBlockSizes(C, A->rmap->bs, P->rmap->bs));
7616:     break;
7617:   default:
7618:     SETERRQ(PetscObjectComm((PetscObject)C), PETSC_ERR_PLIB, "Not for ProductType %s", MatProductTypes[ptype]);
7619:   }

7621:   /* preallocate with COO data */
7622:   PetscCall(MatSetPreallocationCOO(C, ncoo, coo_i, coo_j));
7623:   PetscCall(PetscFree2(coo_i, coo_j));
7624:   PetscFunctionReturn(PETSC_SUCCESS);
7625: }

7627: PetscErrorCode MatProductSetFromOptions_MPIAIJBACKEND(Mat mat)
7628: {
7629:   Mat_Product *product = mat->product;
7630: #if defined(PETSC_HAVE_DEVICE)
7631:   PetscBool match  = PETSC_FALSE;
7632:   PetscBool usecpu = PETSC_FALSE;
7633: #else
7634:   PetscBool match = PETSC_TRUE;
7635: #endif

7637:   PetscFunctionBegin;
7638:   MatCheckProduct(mat, 1);
7639: #if defined(PETSC_HAVE_DEVICE)
7640:   if (!product->A->boundtocpu && !product->B->boundtocpu) PetscCall(PetscObjectTypeCompare((PetscObject)product->B, ((PetscObject)product->A)->type_name, &match));
7641:   if (match) { /* we can always fallback to the CPU if requested */
7642:     switch (product->type) {
7643:     case MATPRODUCT_AB:
7644:       if (product->api_user) {
7645:         PetscOptionsBegin(PetscObjectComm((PetscObject)mat), ((PetscObject)mat)->prefix, "MatMatMult", "Mat");
7646:         PetscCall(PetscOptionsBool("-matmatmult_backend_cpu", "Use CPU code", "MatMatMult", usecpu, &usecpu, NULL));
7647:         PetscOptionsEnd();
7648:       } else {
7649:         PetscOptionsBegin(PetscObjectComm((PetscObject)mat), ((PetscObject)mat)->prefix, "MatProduct_AB", "Mat");
7650:         PetscCall(PetscOptionsBool("-mat_product_algorithm_backend_cpu", "Use CPU code", "MatMatMult", usecpu, &usecpu, NULL));
7651:         PetscOptionsEnd();
7652:       }
7653:       break;
7654:     case MATPRODUCT_AtB:
7655:       if (product->api_user) {
7656:         PetscOptionsBegin(PetscObjectComm((PetscObject)mat), ((PetscObject)mat)->prefix, "MatTransposeMatMult", "Mat");
7657:         PetscCall(PetscOptionsBool("-mattransposematmult_backend_cpu", "Use CPU code", "MatTransposeMatMult", usecpu, &usecpu, NULL));
7658:         PetscOptionsEnd();
7659:       } else {
7660:         PetscOptionsBegin(PetscObjectComm((PetscObject)mat), ((PetscObject)mat)->prefix, "MatProduct_AtB", "Mat");
7661:         PetscCall(PetscOptionsBool("-mat_product_algorithm_backend_cpu", "Use CPU code", "MatTransposeMatMult", usecpu, &usecpu, NULL));
7662:         PetscOptionsEnd();
7663:       }
7664:       break;
7665:     case MATPRODUCT_PtAP:
7666:       if (product->api_user) {
7667:         PetscOptionsBegin(PetscObjectComm((PetscObject)mat), ((PetscObject)mat)->prefix, "MatPtAP", "Mat");
7668:         PetscCall(PetscOptionsBool("-matptap_backend_cpu", "Use CPU code", "MatPtAP", usecpu, &usecpu, NULL));
7669:         PetscOptionsEnd();
7670:       } else {
7671:         PetscOptionsBegin(PetscObjectComm((PetscObject)mat), ((PetscObject)mat)->prefix, "MatProduct_PtAP", "Mat");
7672:         PetscCall(PetscOptionsBool("-mat_product_algorithm_backend_cpu", "Use CPU code", "MatPtAP", usecpu, &usecpu, NULL));
7673:         PetscOptionsEnd();
7674:       }
7675:       break;
7676:     default:
7677:       break;
7678:     }
7679:     match = (PetscBool)!usecpu;
7680:   }
7681: #endif
7682:   if (match) {
7683:     switch (product->type) {
7684:     case MATPRODUCT_AB:
7685:     case MATPRODUCT_AtB:
7686:     case MATPRODUCT_PtAP:
7687:       mat->ops->productsymbolic = MatProductSymbolic_MPIAIJBACKEND;
7688:       break;
7689:     default:
7690:       break;
7691:     }
7692:   }
7693:   /* fallback to MPIAIJ ops */
7694:   if (!mat->ops->productsymbolic) PetscCall(MatProductSetFromOptions_MPIAIJ(mat));
7695:   PetscFunctionReturn(PETSC_SUCCESS);
7696: }

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

7701:    n - the number of block indices in cc[]
7702:    cc - the block indices (must be large enough to contain the indices)
7703: */
7704: static inline PetscErrorCode MatCollapseRow(Mat Amat, PetscInt row, PetscInt bs, PetscInt *n, PetscInt *cc)
7705: {
7706:   PetscInt        cnt = -1, nidx, j;
7707:   const PetscInt *idx;

7709:   PetscFunctionBegin;
7710:   PetscCall(MatGetRow(Amat, row, &nidx, &idx, NULL));
7711:   if (nidx) {
7712:     cnt     = 0;
7713:     cc[cnt] = idx[0] / bs;
7714:     for (j = 1; j < nidx; j++) {
7715:       if (cc[cnt] < idx[j] / bs) cc[++cnt] = idx[j] / bs;
7716:     }
7717:   }
7718:   PetscCall(MatRestoreRow(Amat, row, &nidx, &idx, NULL));
7719:   *n = cnt + 1;
7720:   PetscFunctionReturn(PETSC_SUCCESS);
7721: }

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

7726:     ncollapsed - the number of block indices
7727:     collapsed - the block indices (must be large enough to contain the indices)
7728: */
7729: static inline PetscErrorCode MatCollapseRows(Mat Amat, PetscInt start, PetscInt bs, PetscInt *w0, PetscInt *w1, PetscInt *w2, PetscInt *ncollapsed, PetscInt **collapsed)
7730: {
7731:   PetscInt i, nprev, *cprev = w0, ncur = 0, *ccur = w1, *merged = w2, *cprevtmp;

7733:   PetscFunctionBegin;
7734:   PetscCall(MatCollapseRow(Amat, start, bs, &nprev, cprev));
7735:   for (i = start + 1; i < start + bs; i++) {
7736:     PetscCall(MatCollapseRow(Amat, i, bs, &ncur, ccur));
7737:     PetscCall(PetscMergeIntArray(nprev, cprev, ncur, ccur, &nprev, &merged));
7738:     cprevtmp = cprev;
7739:     cprev    = merged;
7740:     merged   = cprevtmp;
7741:   }
7742:   *ncollapsed = nprev;
7743:   if (collapsed) *collapsed = cprev;
7744:   PetscFunctionReturn(PETSC_SUCCESS);
7745: }

7747: // PetscClangLinter pragma disable: -fdoc-sowing-chars
7748: /*
7749:   MatCreateGraph_Simple_AIJ - create simple scalar matrix (graph) from potentially blocked matrix

7751:   Input Parameters:
7752: + Amat       - matrix
7753: . symmetrize - make the result symmetric
7754: . scale      - scale with diagonal
7755: . filter     - threshold for filter
7756: . index_size - length of `index`
7757: - index      - indices of unknown purpose

7759:   Output Parameter:
7760: . a_Gmat - output scalar graph >= 0

7762:   Level: developer

7764: .seealso: `MATAIJ`
7765: */
7766: PETSC_INTERN PetscErrorCode MatCreateGraph_Simple_AIJ(Mat Amat, PetscBool symmetrize, PetscBool scale, PetscReal filter, PetscInt index_size, PetscInt index[], Mat *a_Gmat)
7767: {
7768:   PetscInt  Istart, Iend, Ii, jj, kk, ncols, nloc, NN, MM, bs;
7769:   MPI_Comm  comm;
7770:   Mat       Gmat;
7771:   PetscBool ismpiaij, isseqaij;
7772:   Mat       a, b, c;
7773:   MatType   jtype;

7775:   PetscFunctionBegin;
7776:   PetscCall(PetscObjectGetComm((PetscObject)Amat, &comm));
7777:   PetscCall(MatGetOwnershipRange(Amat, &Istart, &Iend));
7778:   PetscCall(MatGetSize(Amat, &MM, &NN));
7779:   PetscCall(MatGetBlockSize(Amat, &bs));
7780:   nloc = (Iend - Istart) / bs;

7782:   PetscCall(PetscObjectBaseTypeCompare((PetscObject)Amat, MATSEQAIJ, &isseqaij));
7783:   PetscCall(PetscObjectBaseTypeCompare((PetscObject)Amat, MATMPIAIJ, &ismpiaij));
7784:   PetscCheck(isseqaij || ismpiaij, comm, PETSC_ERR_USER, "Require (MPI)AIJ matrix type");

7786:   /* TODO GPU: these calls are potentially expensive if matrices are large and we want to use the GPU */
7787:   /* A solution consists in providing a new API, MatAIJGetCollapsedAIJ, and each class can provide a fast
7788:      implementation */
7789:   if (bs > 1) {
7790:     PetscCall(MatGetType(Amat, &jtype));
7791:     PetscCall(MatCreate(comm, &Gmat));
7792:     PetscCall(MatSetType(Gmat, jtype));
7793:     PetscCall(MatSetSizes(Gmat, nloc, nloc, PETSC_DETERMINE, PETSC_DETERMINE));
7794:     PetscCall(MatSetBlockSizes(Gmat, 1, 1));
7795:     if (isseqaij || ((Mat_MPIAIJ *)Amat->data)->garray) {
7796:       PetscInt  *d_nnz, *o_nnz;
7797:       MatScalar *aa, val, *AA;
7798:       PetscInt  *aj, *ai, *AJ, nc, nmax = 0;

7800:       if (isseqaij) {
7801:         a = Amat;
7802:         b = NULL;
7803:       } else {
7804:         Mat_MPIAIJ *d = (Mat_MPIAIJ *)Amat->data;
7805:         a             = d->A;
7806:         b             = d->B;
7807:       }
7808:       PetscCall(PetscInfo(Amat, "New bs>1 Graph. nloc=%" PetscInt_FMT "\n", nloc));
7809:       PetscCall(PetscMalloc2(nloc, &d_nnz, (isseqaij ? 0 : nloc), &o_nnz));
7810:       for (c = a, kk = 0; c && kk < 2; c = b, kk++) {
7811:         PetscInt       *nnz = (c == a) ? d_nnz : o_nnz;
7812:         const PetscInt *cols1, *cols2;

7814:         for (PetscInt brow = 0, nc1, nc2, ok = 1; brow < nloc * bs; brow += bs) { // block rows
7815:           PetscCall(MatGetRow(c, brow, &nc2, &cols2, NULL));
7816:           nnz[brow / bs] = nc2 / bs;
7817:           if (nc2 % bs) ok = 0;
7818:           if (nnz[brow / bs] > nmax) nmax = nnz[brow / bs];
7819:           for (PetscInt ii = 1; ii < bs; ii++) { // check for non-dense blocks
7820:             PetscCall(MatGetRow(c, brow + ii, &nc1, &cols1, NULL));
7821:             if (nc1 != nc2) ok = 0;
7822:             else {
7823:               for (PetscInt jj = 0; jj < nc1 && ok == 1; jj++) {
7824:                 if (cols1[jj] != cols2[jj]) ok = 0;
7825:                 if (cols1[jj] % bs != jj % bs) ok = 0;
7826:               }
7827:             }
7828:             PetscCall(MatRestoreRow(c, brow + ii, &nc1, &cols1, NULL));
7829:           }
7830:           PetscCall(MatRestoreRow(c, brow, &nc2, &cols2, NULL));
7831:           if (!ok) {
7832:             PetscCall(PetscFree2(d_nnz, o_nnz));
7833:             PetscCall(PetscInfo(Amat, "Found sparse blocks - revert to slow method\n"));
7834:             goto old_bs;
7835:           }
7836:         }
7837:       }
7838:       PetscCall(MatSeqAIJSetPreallocation(Gmat, 0, d_nnz));
7839:       PetscCall(MatMPIAIJSetPreallocation(Gmat, 0, d_nnz, 0, o_nnz));
7840:       PetscCall(PetscFree2(d_nnz, o_nnz));
7841:       PetscCall(PetscMalloc2(nmax, &AA, nmax, &AJ));
7842:       // diag
7843:       for (PetscInt brow = 0, n, grow; brow < nloc * bs; brow += bs) { // block rows
7844:         Mat_SeqAIJ *aseq = (Mat_SeqAIJ *)a->data;

7846:         ai = aseq->i;
7847:         n  = ai[brow + 1] - ai[brow];
7848:         aj = aseq->j + ai[brow];
7849:         for (PetscInt k = 0; k < n; k += bs) {   // block columns
7850:           AJ[k / bs] = aj[k] / bs + Istart / bs; // diag starts at (Istart,Istart)
7851:           val        = 0;
7852:           if (index_size == 0) {
7853:             for (PetscInt ii = 0; ii < bs; ii++) { // rows in block
7854:               aa = aseq->a + ai[brow + ii] + k;
7855:               for (PetscInt jj = 0; jj < bs; jj++) {    // columns in block
7856:                 val += PetscAbs(PetscRealPart(aa[jj])); // a sort of norm
7857:               }
7858:             }
7859:           } else {                                            // use (index,index) value if provided
7860:             for (PetscInt iii = 0; iii < index_size; iii++) { // rows in block
7861:               PetscInt ii = index[iii];
7862:               aa          = aseq->a + ai[brow + ii] + k;
7863:               for (PetscInt jjj = 0; jjj < index_size; jjj++) { // columns in block
7864:                 PetscInt jj = index[jjj];
7865:                 val += PetscAbs(PetscRealPart(aa[jj]));
7866:               }
7867:             }
7868:           }
7869:           PetscAssert(k / bs < nmax, comm, PETSC_ERR_USER, "k / bs (%" PetscInt_FMT ") >= nmax (%" PetscInt_FMT ")", k / bs, nmax);
7870:           AA[k / bs] = val;
7871:         }
7872:         grow = Istart / bs + brow / bs;
7873:         PetscCall(MatSetValues(Gmat, 1, &grow, n / bs, AJ, AA, ADD_VALUES));
7874:       }
7875:       // off-diag
7876:       if (ismpiaij) {
7877:         Mat_MPIAIJ        *aij = (Mat_MPIAIJ *)Amat->data;
7878:         const PetscScalar *vals;
7879:         const PetscInt    *cols, *garray = aij->garray;

7881:         PetscCheck(garray, PETSC_COMM_SELF, PETSC_ERR_USER, "No garray ?");
7882:         for (PetscInt brow = 0, grow; brow < nloc * bs; brow += bs) { // block rows
7883:           PetscCall(MatGetRow(b, brow, &ncols, &cols, NULL));
7884:           for (PetscInt k = 0, cidx = 0; k < ncols; k += bs, cidx++) {
7885:             PetscAssert(k / bs < nmax, comm, PETSC_ERR_USER, "k / bs >= nmax");
7886:             AA[k / bs] = 0;
7887:             AJ[cidx]   = garray[cols[k]] / bs;
7888:           }
7889:           nc = ncols / bs;
7890:           PetscCall(MatRestoreRow(b, brow, &ncols, &cols, NULL));
7891:           if (index_size == 0) {
7892:             for (PetscInt ii = 0; ii < bs; ii++) { // rows in block
7893:               PetscCall(MatGetRow(b, brow + ii, &ncols, &cols, &vals));
7894:               for (PetscInt k = 0; k < ncols; k += bs) {
7895:                 for (PetscInt jj = 0; jj < bs; jj++) { // cols in block
7896:                   PetscAssert(k / bs < nmax, comm, PETSC_ERR_USER, "k / bs (%" PetscInt_FMT ") >= nmax (%" PetscInt_FMT ")", k / bs, nmax);
7897:                   AA[k / bs] += PetscAbs(PetscRealPart(vals[k + jj]));
7898:                 }
7899:               }
7900:               PetscCall(MatRestoreRow(b, brow + ii, &ncols, &cols, &vals));
7901:             }
7902:           } else {                                            // use (index,index) value if provided
7903:             for (PetscInt iii = 0; iii < index_size; iii++) { // rows in block
7904:               PetscInt ii = index[iii];
7905:               PetscCall(MatGetRow(b, brow + ii, &ncols, &cols, &vals));
7906:               for (PetscInt k = 0; k < ncols; k += bs) {
7907:                 for (PetscInt jjj = 0; jjj < index_size; jjj++) { // cols in block
7908:                   PetscInt jj = index[jjj];
7909:                   AA[k / bs] += PetscAbs(PetscRealPart(vals[k + jj]));
7910:                 }
7911:               }
7912:               PetscCall(MatRestoreRow(b, brow + ii, &ncols, &cols, &vals));
7913:             }
7914:           }
7915:           grow = Istart / bs + brow / bs;
7916:           PetscCall(MatSetValues(Gmat, 1, &grow, nc, AJ, AA, ADD_VALUES));
7917:         }
7918:       }
7919:       PetscCall(MatAssemblyBegin(Gmat, MAT_FINAL_ASSEMBLY));
7920:       PetscCall(MatAssemblyEnd(Gmat, MAT_FINAL_ASSEMBLY));
7921:       PetscCall(PetscFree2(AA, AJ));
7922:     } else {
7923:       const PetscScalar *vals;
7924:       const PetscInt    *idx;
7925:       PetscInt          *d_nnz, *o_nnz, *w0, *w1, *w2;
7926:     old_bs:
7927:       /*
7928:        Determine the preallocation needed for the scalar matrix derived from the vector matrix.
7929:        */
7930:       PetscCall(PetscInfo(Amat, "OLD bs>1 CreateGraph\n"));
7931:       PetscCall(PetscMalloc2(nloc, &d_nnz, (isseqaij ? 0 : nloc), &o_nnz));
7932:       if (isseqaij) {
7933:         PetscInt max_d_nnz;

7935:         /*
7936:          Determine exact preallocation count for (sequential) scalar matrix
7937:          */
7938:         PetscCall(MatSeqAIJGetMaxRowNonzeros(Amat, &max_d_nnz));
7939:         max_d_nnz = PetscMin(nloc, bs * max_d_nnz);
7940:         PetscCall(PetscMalloc3(max_d_nnz, &w0, max_d_nnz, &w1, max_d_nnz, &w2));
7941:         for (Ii = 0, jj = 0; Ii < Iend; Ii += bs, jj++) PetscCall(MatCollapseRows(Amat, Ii, bs, w0, w1, w2, &d_nnz[jj], NULL));
7942:         PetscCall(PetscFree3(w0, w1, w2));
7943:       } else if (ismpiaij) {
7944:         Mat             Daij, Oaij;
7945:         const PetscInt *garray;
7946:         PetscInt        max_d_nnz;

7948:         PetscCall(MatMPIAIJGetSeqAIJ(Amat, &Daij, &Oaij, &garray));
7949:         /*
7950:          Determine exact preallocation count for diagonal block portion of scalar matrix
7951:          */
7952:         PetscCall(MatSeqAIJGetMaxRowNonzeros(Daij, &max_d_nnz));
7953:         max_d_nnz = PetscMin(nloc, bs * max_d_nnz);
7954:         PetscCall(PetscMalloc3(max_d_nnz, &w0, max_d_nnz, &w1, max_d_nnz, &w2));
7955:         for (Ii = 0, jj = 0; Ii < Iend - Istart; Ii += bs, jj++) PetscCall(MatCollapseRows(Daij, Ii, bs, w0, w1, w2, &d_nnz[jj], NULL));
7956:         PetscCall(PetscFree3(w0, w1, w2));
7957:         /*
7958:          Over estimate (usually grossly over), preallocation count for off-diagonal portion of scalar matrix
7959:          */
7960:         for (Ii = 0, jj = 0; Ii < Iend - Istart; Ii += bs, jj++) {
7961:           o_nnz[jj] = 0;
7962:           for (kk = 0; kk < bs; kk++) { /* rows that get collapsed to a single row */
7963:             PetscCall(MatGetRow(Oaij, Ii + kk, &ncols, NULL, NULL));
7964:             o_nnz[jj] += ncols;
7965:             PetscCall(MatRestoreRow(Oaij, Ii + kk, &ncols, NULL, NULL));
7966:           }
7967:           if (o_nnz[jj] > (NN / bs - nloc)) o_nnz[jj] = NN / bs - nloc;
7968:         }
7969:       } else SETERRQ(comm, PETSC_ERR_USER, "Require AIJ matrix type");
7970:       /* get scalar copy (norms) of matrix */
7971:       PetscCall(MatSeqAIJSetPreallocation(Gmat, 0, d_nnz));
7972:       PetscCall(MatMPIAIJSetPreallocation(Gmat, 0, d_nnz, 0, o_nnz));
7973:       PetscCall(PetscFree2(d_nnz, o_nnz));
7974:       for (Ii = Istart; Ii < Iend; Ii++) {
7975:         PetscInt dest_row = Ii / bs;

7977:         PetscCall(MatGetRow(Amat, Ii, &ncols, &idx, &vals));
7978:         for (jj = 0; jj < ncols; jj++) {
7979:           PetscInt    dest_col = idx[jj] / bs;
7980:           PetscScalar sv       = PetscAbs(PetscRealPart(vals[jj]));

7982:           PetscCall(MatSetValues(Gmat, 1, &dest_row, 1, &dest_col, &sv, ADD_VALUES));
7983:         }
7984:         PetscCall(MatRestoreRow(Amat, Ii, &ncols, &idx, &vals));
7985:       }
7986:       PetscCall(MatAssemblyBegin(Gmat, MAT_FINAL_ASSEMBLY));
7987:       PetscCall(MatAssemblyEnd(Gmat, MAT_FINAL_ASSEMBLY));
7988:     }
7989:   } else {
7990:     if (symmetrize || filter >= 0 || scale) PetscCall(MatDuplicate(Amat, MAT_COPY_VALUES, &Gmat));
7991:     else {
7992:       Gmat = Amat;
7993:       PetscCall(PetscObjectReference((PetscObject)Gmat));
7994:     }
7995:     if (isseqaij) {
7996:       a = Gmat;
7997:       b = NULL;
7998:     } else {
7999:       Mat_MPIAIJ *d = (Mat_MPIAIJ *)Gmat->data;
8000:       a             = d->A;
8001:       b             = d->B;
8002:     }
8003:     if (filter >= 0 || scale) {
8004:       /* take absolute value of each entry */
8005:       for (c = a, kk = 0; c && kk < 2; c = b, kk++) {
8006:         MatInfo      info;
8007:         PetscScalar *avals;

8009:         PetscCall(MatGetInfo(c, MAT_LOCAL, &info));
8010:         PetscCall(MatSeqAIJGetArray(c, &avals));
8011:         for (int jj = 0; jj < info.nz_used; jj++) avals[jj] = PetscAbsScalar(avals[jj]);
8012:         PetscCall(MatSeqAIJRestoreArray(c, &avals));
8013:       }
8014:     }
8015:   }
8016:   if (symmetrize) {
8017:     PetscBool isset, issym;

8019:     PetscCall(MatIsSymmetricKnown(Amat, &isset, &issym));
8020:     if (!isset || !issym) {
8021:       Mat matTrans;

8023:       PetscCall(MatTranspose(Gmat, MAT_INITIAL_MATRIX, &matTrans));
8024:       PetscCall(MatAXPY(Gmat, 1.0, matTrans, Gmat->structurally_symmetric == PETSC_BOOL3_TRUE ? SAME_NONZERO_PATTERN : DIFFERENT_NONZERO_PATTERN));
8025:       PetscCall(MatDestroy(&matTrans));
8026:     }
8027:     PetscCall(MatSetOption(Gmat, MAT_SYMMETRIC, PETSC_TRUE));
8028:   } else if (Amat != Gmat) PetscCall(MatPropagateSymmetryOptions(Amat, Gmat));
8029:   if (scale) {
8030:     /* scale c for all diagonal values = 1 or -1 */
8031:     Vec diag;

8033:     PetscCall(MatCreateVecs(Gmat, &diag, NULL));
8034:     PetscCall(MatGetDiagonal(Gmat, diag));
8035:     PetscCall(VecReciprocal(diag));
8036:     PetscCall(VecSqrtAbs(diag));
8037:     PetscCall(MatDiagonalScale(Gmat, diag, diag));
8038:     PetscCall(VecDestroy(&diag));
8039:   }
8040:   PetscCall(MatViewFromOptions(Gmat, NULL, "-mat_graph_view"));
8041:   if (filter >= 0) {
8042:     PetscCall(MatFilter(Gmat, filter, PETSC_TRUE, PETSC_TRUE));
8043:     PetscCall(MatViewFromOptions(Gmat, NULL, "-mat_filter_graph_view"));
8044:   }
8045:   *a_Gmat = Gmat;
8046:   PetscFunctionReturn(PETSC_SUCCESS);
8047: }

8049: PETSC_INTERN PetscErrorCode MatGetCurrentMemType_MPIAIJ(Mat A, PetscMemType *memtype)
8050: {
8051:   Mat_MPIAIJ  *mpiaij = (Mat_MPIAIJ *)A->data;
8052:   PetscMemType mD = PETSC_MEMTYPE_HOST, mO = PETSC_MEMTYPE_HOST;

8054:   PetscFunctionBegin;
8055:   if (mpiaij->A) PetscCall(MatGetCurrentMemType(mpiaij->A, &mD));
8056:   if (mpiaij->B) PetscCall(MatGetCurrentMemType(mpiaij->B, &mO));
8057:   *memtype = (mD == mO) ? mD : PETSC_MEMTYPE_HOST;
8058:   PetscFunctionReturn(PETSC_SUCCESS);
8059: }

8061: /*
8062:     Special version for direct calls from Fortran
8063: */

8065: /* Change these macros so can be used in void function */
8066: /* Identical to PetscCallVoid, except it assigns to *_ierr */
8067: #undef PetscCall
8068: #define PetscCall(...) \
8069:   do { \
8070:     PetscErrorCode ierr_msv_mpiaij = __VA_ARGS__; \
8071:     if (PetscUnlikely(ierr_msv_mpiaij)) { \
8072:       *_ierr = PetscError(PETSC_COMM_SELF, __LINE__, PETSC_FUNCTION_NAME, __FILE__, ierr_msv_mpiaij, PETSC_ERROR_REPEAT, " "); \
8073:       return; \
8074:     } \
8075:   } while (0)

8077: #undef SETERRQ
8078: #define SETERRQ(comm, ierr, ...) \
8079:   do { \
8080:     *_ierr = PetscError(comm, __LINE__, PETSC_FUNCTION_NAME, __FILE__, ierr, PETSC_ERROR_INITIAL, __VA_ARGS__); \
8081:     return; \
8082:   } while (0)

8084: #if defined(PETSC_HAVE_FORTRAN_CAPS)
8085:   #define matsetvaluesmpiaij_ MATSETVALUESMPIAIJ
8086: #elif !defined(PETSC_HAVE_FORTRAN_UNDERSCORE)
8087:   #define matsetvaluesmpiaij_ matsetvaluesmpiaij
8088: #else
8089: #endif
8090: PETSC_EXTERN void matsetvaluesmpiaij_(Mat *mmat, PetscInt *mm, const PetscInt im[], PetscInt *mn, const PetscInt in[], const PetscScalar v[], InsertMode *maddv, PetscErrorCode *_ierr)
8091: {
8092:   Mat         mat = *mmat;
8093:   PetscInt    m = *mm, n = *mn;
8094:   InsertMode  addv = *maddv;
8095:   Mat_MPIAIJ *aij  = (Mat_MPIAIJ *)mat->data;
8096:   PetscScalar value;

8098:   MatCheckPreallocated(mat, 1);
8099:   if (mat->insertmode == NOT_SET_VALUES) mat->insertmode = addv;
8100:   else PetscCheck(mat->insertmode == addv, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Cannot mix add values and insert values");
8101:   {
8102:     PetscInt  i, j, rstart = mat->rmap->rstart, rend = mat->rmap->rend;
8103:     PetscInt  cstart = mat->cmap->rstart, cend = mat->cmap->rend, row, col;
8104:     PetscBool roworiented = aij->roworiented;

8106:     /* Some Variables required in the macro */
8107:     Mat         A     = aij->A;
8108:     Mat_SeqAIJ *a     = (Mat_SeqAIJ *)A->data;
8109:     PetscInt   *aimax = a->imax, *ai = a->i, *ailen = a->ilen, *aj = a->j;
8110:     MatScalar  *aa;
8111:     PetscBool   ignorezeroentries = ((a->ignorezeroentries && (addv == ADD_VALUES)) ? PETSC_TRUE : PETSC_FALSE);
8112:     Mat         B                 = aij->B;
8113:     Mat_SeqAIJ *b                 = (Mat_SeqAIJ *)B->data;
8114:     PetscInt   *bimax = b->imax, *bi = b->i, *bilen = b->ilen, *bj = b->j, bm = aij->B->rmap->n, am = aij->A->rmap->n;
8115:     MatScalar  *ba;
8116:     /* This variable below is only for the PETSC_HAVE_VIENNACL or PETSC_HAVE_CUDA cases, but we define it in all cases because we
8117:      * cannot use "#if defined" inside a macro. */
8118:     PETSC_UNUSED PetscBool inserted = PETSC_FALSE;

8120:     PetscInt  *rp1, *rp2, ii, nrow1, nrow2, _i, rmax1, rmax2, N, low1, high1, low2, high2, t, lastcol1, lastcol2;
8121:     PetscInt   nonew = a->nonew;
8122:     MatScalar *ap1, *ap2;

8124:     PetscFunctionBegin;
8125:     PetscCall(MatSeqAIJGetArray(A, &aa));
8126:     PetscCall(MatSeqAIJGetArray(B, &ba));
8127:     for (i = 0; i < m; i++) {
8128:       if (im[i] < 0) continue;
8129:       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);
8130:       if (im[i] >= rstart && im[i] < rend) {
8131:         row      = im[i] - rstart;
8132:         lastcol1 = -1;
8133:         rp1      = aj + ai[row];
8134:         ap1      = aa + ai[row];
8135:         rmax1    = aimax[row];
8136:         nrow1    = ailen[row];
8137:         low1     = 0;
8138:         high1    = nrow1;
8139:         lastcol2 = -1;
8140:         rp2      = bj + bi[row];
8141:         ap2      = ba + bi[row];
8142:         rmax2    = bimax[row];
8143:         nrow2    = bilen[row];
8144:         low2     = 0;
8145:         high2    = nrow2;

8147:         for (j = 0; j < n; j++) {
8148:           if (roworiented) value = v[i * n + j];
8149:           else value = v[i + j * m];
8150:           if (ignorezeroentries && value == 0.0 && (addv == ADD_VALUES) && im[i] != in[j]) continue;
8151:           if (in[j] >= cstart && in[j] < cend) {
8152:             col = in[j] - cstart;
8153:             MatSetValues_SeqAIJ_A_Private(row, col, value, addv, im[i], in[j]);
8154:           } else if (in[j] < 0) continue;
8155:           else if (PetscUnlikelyDebug(in[j] >= mat->cmap->N)) {
8156:             SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Column too large: col %" PetscInt_FMT " max %" PetscInt_FMT, in[j], mat->cmap->N - 1);
8157:           } else {
8158:             if (mat->was_assembled) {
8159:               if (!aij->colmap) PetscCall(MatCreateColmap_MPIAIJ_Private(mat));
8160: #if defined(PETSC_USE_CTABLE)
8161:               PetscCall(PetscHMapIGetWithDefault(aij->colmap, in[j] + 1, 0, &col));
8162:               col--;
8163: #else
8164:               col = aij->colmap[in[j]] - 1;
8165: #endif
8166:               if (col < 0 && !((Mat_SeqAIJ *)aij->A->data)->nonew) {
8167:                 PetscCall(MatDisAssemble_MPIAIJ(mat, PETSC_FALSE));
8168:                 col = in[j];
8169:                 /* Reinitialize the variables required by MatSetValues_SeqAIJ_B_Private() */
8170:                 B        = aij->B;
8171:                 b        = (Mat_SeqAIJ *)B->data;
8172:                 bimax    = b->imax;
8173:                 bi       = b->i;
8174:                 bilen    = b->ilen;
8175:                 bj       = b->j;
8176:                 rp2      = bj + bi[row];
8177:                 ap2      = ba + bi[row];
8178:                 rmax2    = bimax[row];
8179:                 nrow2    = bilen[row];
8180:                 low2     = 0;
8181:                 high2    = nrow2;
8182:                 bm       = aij->B->rmap->n;
8183:                 ba       = b->a;
8184:                 inserted = PETSC_FALSE;
8185:               }
8186:             } else col = in[j];
8187:             MatSetValues_SeqAIJ_B_Private(row, col, value, addv, im[i], in[j]);
8188:           }
8189:         }
8190:       } else if (!aij->donotstash) {
8191:         if (roworiented) {
8192:           PetscCall(MatStashValuesRow_Private(&mat->stash, im[i], n, in, v + i * n, (PetscBool)(ignorezeroentries && (addv == ADD_VALUES))));
8193:         } else {
8194:           PetscCall(MatStashValuesCol_Private(&mat->stash, im[i], n, in, v + i, m, (PetscBool)(ignorezeroentries && (addv == ADD_VALUES))));
8195:         }
8196:       }
8197:     }
8198:     PetscCall(MatSeqAIJRestoreArray(A, &aa));
8199:     PetscCall(MatSeqAIJRestoreArray(B, &ba));
8200:   }
8201:   PetscFunctionReturnVoid();
8202: }

8204: /* Undefining these here since they were redefined from their original definition above! No
8205:  * other PETSc functions should be defined past this point, as it is impossible to recover the
8206:  * original definitions */
8207: #undef PetscCall
8208: #undef SETERRQ