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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

4908:   current_space = free_space;

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

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

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

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

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

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

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

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

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

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

4983:   PetscCall(PetscCommDestroy(&comm));

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

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

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

5001:   Collective

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

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

5013:   Level: advanced

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

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

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

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

5045:   Not Collective

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

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

5053:   Level: developer

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

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

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

5064:   Destroy the matrix with `MatDestroy()`

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

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

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

5085:   Not Collective

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

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

5094:   Level: developer

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

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

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

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

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

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

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

5219:   Not Collective

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

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

5229:   Level: developer

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

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

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

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

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

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

5336:   Not Collective

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

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

5347:   Level: developer

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

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

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

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

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

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

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

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

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

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

5658:   Collective

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

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

5670:   Level: developer

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

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

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

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

5730:     Collective

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

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

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

5746:     Level: developer

5748: */

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

6047:   Input Parameters:

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

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

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

6059:     Similar for Set2.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

6764:    Level: beginner

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

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

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

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

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

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

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

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

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

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

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

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

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

6864:   Collective

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

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

6884:   Level: advanced

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

7712:  Input Parameter:
7713:  . Amat - matrix
7714:  - symmetrize - make the result symmetric
7715:  + scale - scale with diagonal

7717:  Output Parameter:
7718:  . a_Gmat - output scalar graph >= 0

7720: */
7721: PETSC_INTERN PetscErrorCode MatCreateGraph_Simple_AIJ(Mat Amat, PetscBool symmetrize, PetscBool scale, PetscReal filter, PetscInt index_size, PetscInt index[], Mat *a_Gmat)
7722: {
7723:   PetscInt  Istart, Iend, Ii, jj, kk, ncols, nloc, NN, MM, bs;
7724:   MPI_Comm  comm;
7725:   Mat       Gmat;
7726:   PetscBool ismpiaij, isseqaij;
7727:   Mat       a, b, c;
7728:   MatType   jtype;

7730:   PetscFunctionBegin;
7731:   PetscCall(PetscObjectGetComm((PetscObject)Amat, &comm));
7732:   PetscCall(MatGetOwnershipRange(Amat, &Istart, &Iend));
7733:   PetscCall(MatGetSize(Amat, &MM, &NN));
7734:   PetscCall(MatGetBlockSize(Amat, &bs));
7735:   nloc = (Iend - Istart) / bs;

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

7741:   /* TODO GPU: these calls are potentially expensive if matrices are large and we want to use the GPU */
7742:   /* A solution consists in providing a new API, MatAIJGetCollapsedAIJ, and each class can provide a fast
7743:      implementation */
7744:   if (bs > 1) {
7745:     PetscCall(MatGetType(Amat, &jtype));
7746:     PetscCall(MatCreate(comm, &Gmat));
7747:     PetscCall(MatSetType(Gmat, jtype));
7748:     PetscCall(MatSetSizes(Gmat, nloc, nloc, PETSC_DETERMINE, PETSC_DETERMINE));
7749:     PetscCall(MatSetBlockSizes(Gmat, 1, 1));
7750:     if (isseqaij || ((Mat_MPIAIJ *)Amat->data)->garray) {
7751:       PetscInt  *d_nnz, *o_nnz;
7752:       MatScalar *aa, val, *AA;
7753:       PetscInt  *aj, *ai, *AJ, nc, nmax = 0;

7755:       if (isseqaij) {
7756:         a = Amat;
7757:         b = NULL;
7758:       } else {
7759:         Mat_MPIAIJ *d = (Mat_MPIAIJ *)Amat->data;
7760:         a             = d->A;
7761:         b             = d->B;
7762:       }
7763:       PetscCall(PetscInfo(Amat, "New bs>1 Graph. nloc=%" PetscInt_FMT "\n", nloc));
7764:       PetscCall(PetscMalloc2(nloc, &d_nnz, (isseqaij ? 0 : nloc), &o_nnz));
7765:       for (c = a, kk = 0; c && kk < 2; c = b, kk++) {
7766:         PetscInt       *nnz = (c == a) ? d_nnz : o_nnz;
7767:         const PetscInt *cols1, *cols2;

7769:         for (PetscInt brow = 0, nc1, nc2, ok = 1; brow < nloc * bs; brow += bs) { // block rows
7770:           PetscCall(MatGetRow(c, brow, &nc2, &cols2, NULL));
7771:           nnz[brow / bs] = nc2 / bs;
7772:           if (nc2 % bs) ok = 0;
7773:           if (nnz[brow / bs] > nmax) nmax = nnz[brow / bs];
7774:           for (PetscInt ii = 1; ii < bs; ii++) { // check for non-dense blocks
7775:             PetscCall(MatGetRow(c, brow + ii, &nc1, &cols1, NULL));
7776:             if (nc1 != nc2) ok = 0;
7777:             else {
7778:               for (PetscInt jj = 0; jj < nc1 && ok == 1; jj++) {
7779:                 if (cols1[jj] != cols2[jj]) ok = 0;
7780:                 if (cols1[jj] % bs != jj % bs) ok = 0;
7781:               }
7782:             }
7783:             PetscCall(MatRestoreRow(c, brow + ii, &nc1, &cols1, NULL));
7784:           }
7785:           PetscCall(MatRestoreRow(c, brow, &nc2, &cols2, NULL));
7786:           if (!ok) {
7787:             PetscCall(PetscFree2(d_nnz, o_nnz));
7788:             PetscCall(PetscInfo(Amat, "Found sparse blocks - revert to slow method\n"));
7789:             goto old_bs;
7790:           }
7791:         }
7792:       }
7793:       PetscCall(MatSeqAIJSetPreallocation(Gmat, 0, d_nnz));
7794:       PetscCall(MatMPIAIJSetPreallocation(Gmat, 0, d_nnz, 0, o_nnz));
7795:       PetscCall(PetscFree2(d_nnz, o_nnz));
7796:       PetscCall(PetscMalloc2(nmax, &AA, nmax, &AJ));
7797:       // diag
7798:       for (PetscInt brow = 0, n, grow; brow < nloc * bs; brow += bs) { // block rows
7799:         Mat_SeqAIJ *aseq = (Mat_SeqAIJ *)a->data;

7801:         ai = aseq->i;
7802:         n  = ai[brow + 1] - ai[brow];
7803:         aj = aseq->j + ai[brow];
7804:         for (PetscInt k = 0; k < n; k += bs) {   // block columns
7805:           AJ[k / bs] = aj[k] / bs + Istart / bs; // diag starts at (Istart,Istart)
7806:           val        = 0;
7807:           if (index_size == 0) {
7808:             for (PetscInt ii = 0; ii < bs; ii++) { // rows in block
7809:               aa = aseq->a + ai[brow + ii] + k;
7810:               for (PetscInt jj = 0; jj < bs; jj++) {    // columns in block
7811:                 val += PetscAbs(PetscRealPart(aa[jj])); // a sort of norm
7812:               }
7813:             }
7814:           } else {                                            // use (index,index) value if provided
7815:             for (PetscInt iii = 0; iii < index_size; iii++) { // rows in block
7816:               PetscInt ii = index[iii];
7817:               aa          = aseq->a + ai[brow + ii] + k;
7818:               for (PetscInt jjj = 0; jjj < index_size; jjj++) { // columns in block
7819:                 PetscInt jj = index[jjj];
7820:                 val += PetscAbs(PetscRealPart(aa[jj]));
7821:               }
7822:             }
7823:           }
7824:           PetscAssert(k / bs < nmax, comm, PETSC_ERR_USER, "k / bs (%" PetscInt_FMT ") >= nmax (%" PetscInt_FMT ")", k / bs, nmax);
7825:           AA[k / bs] = val;
7826:         }
7827:         grow = Istart / bs + brow / bs;
7828:         PetscCall(MatSetValues(Gmat, 1, &grow, n / bs, AJ, AA, ADD_VALUES));
7829:       }
7830:       // off-diag
7831:       if (ismpiaij) {
7832:         Mat_MPIAIJ        *aij = (Mat_MPIAIJ *)Amat->data;
7833:         const PetscScalar *vals;
7834:         const PetscInt    *cols, *garray = aij->garray;

7836:         PetscCheck(garray, PETSC_COMM_SELF, PETSC_ERR_USER, "No garray ?");
7837:         for (PetscInt brow = 0, grow; brow < nloc * bs; brow += bs) { // block rows
7838:           PetscCall(MatGetRow(b, brow, &ncols, &cols, NULL));
7839:           for (PetscInt k = 0, cidx = 0; k < ncols; k += bs, cidx++) {
7840:             PetscAssert(k / bs < nmax, comm, PETSC_ERR_USER, "k / bs >= nmax");
7841:             AA[k / bs] = 0;
7842:             AJ[cidx]   = garray[cols[k]] / bs;
7843:           }
7844:           nc = ncols / bs;
7845:           PetscCall(MatRestoreRow(b, brow, &ncols, &cols, NULL));
7846:           if (index_size == 0) {
7847:             for (PetscInt ii = 0; ii < bs; ii++) { // rows in block
7848:               PetscCall(MatGetRow(b, brow + ii, &ncols, &cols, &vals));
7849:               for (PetscInt k = 0; k < ncols; k += bs) {
7850:                 for (PetscInt jj = 0; jj < bs; jj++) { // cols in block
7851:                   PetscAssert(k / bs < nmax, comm, PETSC_ERR_USER, "k / bs (%" PetscInt_FMT ") >= nmax (%" PetscInt_FMT ")", k / bs, nmax);
7852:                   AA[k / bs] += PetscAbs(PetscRealPart(vals[k + jj]));
7853:                 }
7854:               }
7855:               PetscCall(MatRestoreRow(b, brow + ii, &ncols, &cols, &vals));
7856:             }
7857:           } else {                                            // use (index,index) value if provided
7858:             for (PetscInt iii = 0; iii < index_size; iii++) { // rows in block
7859:               PetscInt ii = index[iii];
7860:               PetscCall(MatGetRow(b, brow + ii, &ncols, &cols, &vals));
7861:               for (PetscInt k = 0; k < ncols; k += bs) {
7862:                 for (PetscInt jjj = 0; jjj < index_size; jjj++) { // cols in block
7863:                   PetscInt jj = index[jjj];
7864:                   AA[k / bs] += PetscAbs(PetscRealPart(vals[k + jj]));
7865:                 }
7866:               }
7867:               PetscCall(MatRestoreRow(b, brow + ii, &ncols, &cols, &vals));
7868:             }
7869:           }
7870:           grow = Istart / bs + brow / bs;
7871:           PetscCall(MatSetValues(Gmat, 1, &grow, nc, AJ, AA, ADD_VALUES));
7872:         }
7873:       }
7874:       PetscCall(MatAssemblyBegin(Gmat, MAT_FINAL_ASSEMBLY));
7875:       PetscCall(MatAssemblyEnd(Gmat, MAT_FINAL_ASSEMBLY));
7876:       PetscCall(PetscFree2(AA, AJ));
7877:     } else {
7878:       const PetscScalar *vals;
7879:       const PetscInt    *idx;
7880:       PetscInt          *d_nnz, *o_nnz, *w0, *w1, *w2;
7881:     old_bs:
7882:       /*
7883:        Determine the preallocation needed for the scalar matrix derived from the vector matrix.
7884:        */
7885:       PetscCall(PetscInfo(Amat, "OLD bs>1 CreateGraph\n"));
7886:       PetscCall(PetscMalloc2(nloc, &d_nnz, (isseqaij ? 0 : nloc), &o_nnz));
7887:       if (isseqaij) {
7888:         PetscInt max_d_nnz;

7890:         /*
7891:          Determine exact preallocation count for (sequential) scalar matrix
7892:          */
7893:         PetscCall(MatSeqAIJGetMaxRowNonzeros(Amat, &max_d_nnz));
7894:         max_d_nnz = PetscMin(nloc, bs * max_d_nnz);
7895:         PetscCall(PetscMalloc3(max_d_nnz, &w0, max_d_nnz, &w1, max_d_nnz, &w2));
7896:         for (Ii = 0, jj = 0; Ii < Iend; Ii += bs, jj++) PetscCall(MatCollapseRows(Amat, Ii, bs, w0, w1, w2, &d_nnz[jj], NULL));
7897:         PetscCall(PetscFree3(w0, w1, w2));
7898:       } else if (ismpiaij) {
7899:         Mat             Daij, Oaij;
7900:         const PetscInt *garray;
7901:         PetscInt        max_d_nnz;

7903:         PetscCall(MatMPIAIJGetSeqAIJ(Amat, &Daij, &Oaij, &garray));
7904:         /*
7905:          Determine exact preallocation count for diagonal block portion of scalar matrix
7906:          */
7907:         PetscCall(MatSeqAIJGetMaxRowNonzeros(Daij, &max_d_nnz));
7908:         max_d_nnz = PetscMin(nloc, bs * max_d_nnz);
7909:         PetscCall(PetscMalloc3(max_d_nnz, &w0, max_d_nnz, &w1, max_d_nnz, &w2));
7910:         for (Ii = 0, jj = 0; Ii < Iend - Istart; Ii += bs, jj++) PetscCall(MatCollapseRows(Daij, Ii, bs, w0, w1, w2, &d_nnz[jj], NULL));
7911:         PetscCall(PetscFree3(w0, w1, w2));
7912:         /*
7913:          Over estimate (usually grossly over), preallocation count for off-diagonal portion of scalar matrix
7914:          */
7915:         for (Ii = 0, jj = 0; Ii < Iend - Istart; Ii += bs, jj++) {
7916:           o_nnz[jj] = 0;
7917:           for (kk = 0; kk < bs; kk++) { /* rows that get collapsed to a single row */
7918:             PetscCall(MatGetRow(Oaij, Ii + kk, &ncols, NULL, NULL));
7919:             o_nnz[jj] += ncols;
7920:             PetscCall(MatRestoreRow(Oaij, Ii + kk, &ncols, NULL, NULL));
7921:           }
7922:           if (o_nnz[jj] > (NN / bs - nloc)) o_nnz[jj] = NN / bs - nloc;
7923:         }
7924:       } else SETERRQ(comm, PETSC_ERR_USER, "Require AIJ matrix type");
7925:       /* get scalar copy (norms) of matrix */
7926:       PetscCall(MatSeqAIJSetPreallocation(Gmat, 0, d_nnz));
7927:       PetscCall(MatMPIAIJSetPreallocation(Gmat, 0, d_nnz, 0, o_nnz));
7928:       PetscCall(PetscFree2(d_nnz, o_nnz));
7929:       for (Ii = Istart; Ii < Iend; Ii++) {
7930:         PetscInt dest_row = Ii / bs;

7932:         PetscCall(MatGetRow(Amat, Ii, &ncols, &idx, &vals));
7933:         for (jj = 0; jj < ncols; jj++) {
7934:           PetscInt    dest_col = idx[jj] / bs;
7935:           PetscScalar sv       = PetscAbs(PetscRealPart(vals[jj]));

7937:           PetscCall(MatSetValues(Gmat, 1, &dest_row, 1, &dest_col, &sv, ADD_VALUES));
7938:         }
7939:         PetscCall(MatRestoreRow(Amat, Ii, &ncols, &idx, &vals));
7940:       }
7941:       PetscCall(MatAssemblyBegin(Gmat, MAT_FINAL_ASSEMBLY));
7942:       PetscCall(MatAssemblyEnd(Gmat, MAT_FINAL_ASSEMBLY));
7943:     }
7944:   } else {
7945:     if (symmetrize || filter >= 0 || scale) PetscCall(MatDuplicate(Amat, MAT_COPY_VALUES, &Gmat));
7946:     else {
7947:       Gmat = Amat;
7948:       PetscCall(PetscObjectReference((PetscObject)Gmat));
7949:     }
7950:     if (isseqaij) {
7951:       a = Gmat;
7952:       b = NULL;
7953:     } else {
7954:       Mat_MPIAIJ *d = (Mat_MPIAIJ *)Gmat->data;
7955:       a             = d->A;
7956:       b             = d->B;
7957:     }
7958:     if (filter >= 0 || scale) {
7959:       /* take absolute value of each entry */
7960:       for (c = a, kk = 0; c && kk < 2; c = b, kk++) {
7961:         MatInfo      info;
7962:         PetscScalar *avals;

7964:         PetscCall(MatGetInfo(c, MAT_LOCAL, &info));
7965:         PetscCall(MatSeqAIJGetArray(c, &avals));
7966:         for (int jj = 0; jj < info.nz_used; jj++) avals[jj] = PetscAbsScalar(avals[jj]);
7967:         PetscCall(MatSeqAIJRestoreArray(c, &avals));
7968:       }
7969:     }
7970:   }
7971:   if (symmetrize) {
7972:     PetscBool isset, issym;

7974:     PetscCall(MatIsSymmetricKnown(Amat, &isset, &issym));
7975:     if (!isset || !issym) {
7976:       Mat matTrans;

7978:       PetscCall(MatTranspose(Gmat, MAT_INITIAL_MATRIX, &matTrans));
7979:       PetscCall(MatAXPY(Gmat, 1.0, matTrans, Gmat->structurally_symmetric == PETSC_BOOL3_TRUE ? SAME_NONZERO_PATTERN : DIFFERENT_NONZERO_PATTERN));
7980:       PetscCall(MatDestroy(&matTrans));
7981:     }
7982:     PetscCall(MatSetOption(Gmat, MAT_SYMMETRIC, PETSC_TRUE));
7983:   } else if (Amat != Gmat) PetscCall(MatPropagateSymmetryOptions(Amat, Gmat));
7984:   if (scale) {
7985:     /* scale c for all diagonal values = 1 or -1 */
7986:     Vec diag;

7988:     PetscCall(MatCreateVecs(Gmat, &diag, NULL));
7989:     PetscCall(MatGetDiagonal(Gmat, diag));
7990:     PetscCall(VecReciprocal(diag));
7991:     PetscCall(VecSqrtAbs(diag));
7992:     PetscCall(MatDiagonalScale(Gmat, diag, diag));
7993:     PetscCall(VecDestroy(&diag));
7994:   }
7995:   PetscCall(MatViewFromOptions(Gmat, NULL, "-mat_graph_view"));
7996:   if (filter >= 0) {
7997:     PetscCall(MatFilter(Gmat, filter, PETSC_TRUE, PETSC_TRUE));
7998:     PetscCall(MatViewFromOptions(Gmat, NULL, "-mat_filter_graph_view"));
7999:   }
8000:   *a_Gmat = Gmat;
8001:   PetscFunctionReturn(PETSC_SUCCESS);
8002: }

8004: PETSC_INTERN PetscErrorCode MatGetCurrentMemType_MPIAIJ(Mat A, PetscMemType *memtype)
8005: {
8006:   Mat_MPIAIJ  *mpiaij = (Mat_MPIAIJ *)A->data;
8007:   PetscMemType mD = PETSC_MEMTYPE_HOST, mO = PETSC_MEMTYPE_HOST;

8009:   PetscFunctionBegin;
8010:   if (mpiaij->A) PetscCall(MatGetCurrentMemType(mpiaij->A, &mD));
8011:   if (mpiaij->B) PetscCall(MatGetCurrentMemType(mpiaij->B, &mO));
8012:   *memtype = (mD == mO) ? mD : PETSC_MEMTYPE_HOST;
8013:   PetscFunctionReturn(PETSC_SUCCESS);
8014: }

8016: /*
8017:     Special version for direct calls from Fortran
8018: */

8020: /* Change these macros so can be used in void function */
8021: /* Identical to PetscCallVoid, except it assigns to *_ierr */
8022: #undef PetscCall
8023: #define PetscCall(...) \
8024:   do { \
8025:     PetscErrorCode ierr_msv_mpiaij = __VA_ARGS__; \
8026:     if (PetscUnlikely(ierr_msv_mpiaij)) { \
8027:       *_ierr = PetscError(PETSC_COMM_SELF, __LINE__, PETSC_FUNCTION_NAME, __FILE__, ierr_msv_mpiaij, PETSC_ERROR_REPEAT, " "); \
8028:       return; \
8029:     } \
8030:   } while (0)

8032: #undef SETERRQ
8033: #define SETERRQ(comm, ierr, ...) \
8034:   do { \
8035:     *_ierr = PetscError(comm, __LINE__, PETSC_FUNCTION_NAME, __FILE__, ierr, PETSC_ERROR_INITIAL, __VA_ARGS__); \
8036:     return; \
8037:   } while (0)

8039: #if defined(PETSC_HAVE_FORTRAN_CAPS)
8040:   #define matsetvaluesmpiaij_ MATSETVALUESMPIAIJ
8041: #elif !defined(PETSC_HAVE_FORTRAN_UNDERSCORE)
8042:   #define matsetvaluesmpiaij_ matsetvaluesmpiaij
8043: #else
8044: #endif
8045: PETSC_EXTERN void matsetvaluesmpiaij_(Mat *mmat, PetscInt *mm, const PetscInt im[], PetscInt *mn, const PetscInt in[], const PetscScalar v[], InsertMode *maddv, PetscErrorCode *_ierr)
8046: {
8047:   Mat         mat = *mmat;
8048:   PetscInt    m = *mm, n = *mn;
8049:   InsertMode  addv = *maddv;
8050:   Mat_MPIAIJ *aij  = (Mat_MPIAIJ *)mat->data;
8051:   PetscScalar value;

8053:   MatCheckPreallocated(mat, 1);
8054:   if (mat->insertmode == NOT_SET_VALUES) mat->insertmode = addv;
8055:   else PetscCheck(mat->insertmode == addv, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Cannot mix add values and insert values");
8056:   {
8057:     PetscInt  i, j, rstart = mat->rmap->rstart, rend = mat->rmap->rend;
8058:     PetscInt  cstart = mat->cmap->rstart, cend = mat->cmap->rend, row, col;
8059:     PetscBool roworiented = aij->roworiented;

8061:     /* Some Variables required in the macro */
8062:     Mat         A     = aij->A;
8063:     Mat_SeqAIJ *a     = (Mat_SeqAIJ *)A->data;
8064:     PetscInt   *aimax = a->imax, *ai = a->i, *ailen = a->ilen, *aj = a->j;
8065:     MatScalar  *aa;
8066:     PetscBool   ignorezeroentries = ((a->ignorezeroentries && (addv == ADD_VALUES)) ? PETSC_TRUE : PETSC_FALSE);
8067:     Mat         B                 = aij->B;
8068:     Mat_SeqAIJ *b                 = (Mat_SeqAIJ *)B->data;
8069:     PetscInt   *bimax = b->imax, *bi = b->i, *bilen = b->ilen, *bj = b->j, bm = aij->B->rmap->n, am = aij->A->rmap->n;
8070:     MatScalar  *ba;
8071:     /* This variable below is only for the PETSC_HAVE_VIENNACL or PETSC_HAVE_CUDA cases, but we define it in all cases because we
8072:      * cannot use "#if defined" inside a macro. */
8073:     PETSC_UNUSED PetscBool inserted = PETSC_FALSE;

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

8079:     PetscFunctionBegin;
8080:     PetscCall(MatSeqAIJGetArray(A, &aa));
8081:     PetscCall(MatSeqAIJGetArray(B, &ba));
8082:     for (i = 0; i < m; i++) {
8083:       if (im[i] < 0) continue;
8084:       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);
8085:       if (im[i] >= rstart && im[i] < rend) {
8086:         row      = im[i] - rstart;
8087:         lastcol1 = -1;
8088:         rp1      = aj + ai[row];
8089:         ap1      = aa + ai[row];
8090:         rmax1    = aimax[row];
8091:         nrow1    = ailen[row];
8092:         low1     = 0;
8093:         high1    = nrow1;
8094:         lastcol2 = -1;
8095:         rp2      = bj + bi[row];
8096:         ap2      = ba + bi[row];
8097:         rmax2    = bimax[row];
8098:         nrow2    = bilen[row];
8099:         low2     = 0;
8100:         high2    = nrow2;

8102:         for (j = 0; j < n; j++) {
8103:           if (roworiented) value = v[i * n + j];
8104:           else value = v[i + j * m];
8105:           if (ignorezeroentries && value == 0.0 && (addv == ADD_VALUES) && im[i] != in[j]) continue;
8106:           if (in[j] >= cstart && in[j] < cend) {
8107:             col = in[j] - cstart;
8108:             MatSetValues_SeqAIJ_A_Private(row, col, value, addv, im[i], in[j]);
8109:           } else if (in[j] < 0) continue;
8110:           else if (PetscUnlikelyDebug(in[j] >= mat->cmap->N)) {
8111:             SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Column too large: col %" PetscInt_FMT " max %" PetscInt_FMT, in[j], mat->cmap->N - 1);
8112:           } else {
8113:             if (mat->was_assembled) {
8114:               if (!aij->colmap) PetscCall(MatCreateColmap_MPIAIJ_Private(mat));
8115: #if defined(PETSC_USE_CTABLE)
8116:               PetscCall(PetscHMapIGetWithDefault(aij->colmap, in[j] + 1, 0, &col));
8117:               col--;
8118: #else
8119:               col = aij->colmap[in[j]] - 1;
8120: #endif
8121:               if (col < 0 && !((Mat_SeqAIJ *)aij->A->data)->nonew) {
8122:                 PetscCall(MatDisAssemble_MPIAIJ(mat, PETSC_FALSE));
8123:                 col = in[j];
8124:                 /* Reinitialize the variables required by MatSetValues_SeqAIJ_B_Private() */
8125:                 B        = aij->B;
8126:                 b        = (Mat_SeqAIJ *)B->data;
8127:                 bimax    = b->imax;
8128:                 bi       = b->i;
8129:                 bilen    = b->ilen;
8130:                 bj       = b->j;
8131:                 rp2      = bj + bi[row];
8132:                 ap2      = ba + bi[row];
8133:                 rmax2    = bimax[row];
8134:                 nrow2    = bilen[row];
8135:                 low2     = 0;
8136:                 high2    = nrow2;
8137:                 bm       = aij->B->rmap->n;
8138:                 ba       = b->a;
8139:                 inserted = PETSC_FALSE;
8140:               }
8141:             } else col = in[j];
8142:             MatSetValues_SeqAIJ_B_Private(row, col, value, addv, im[i], in[j]);
8143:           }
8144:         }
8145:       } else if (!aij->donotstash) {
8146:         if (roworiented) {
8147:           PetscCall(MatStashValuesRow_Private(&mat->stash, im[i], n, in, v + i * n, (PetscBool)(ignorezeroentries && (addv == ADD_VALUES))));
8148:         } else {
8149:           PetscCall(MatStashValuesCol_Private(&mat->stash, im[i], n, in, v + i, m, (PetscBool)(ignorezeroentries && (addv == ADD_VALUES))));
8150:         }
8151:       }
8152:     }
8153:     PetscCall(MatSeqAIJRestoreArray(A, &aa));
8154:     PetscCall(MatSeqAIJRestoreArray(B, &ba));
8155:   }
8156:   PetscFunctionReturnVoid();
8157: }

8159: /* Undefining these here since they were redefined from their original definition above! No
8160:  * other PETSc functions should be defined past this point, as it is impossible to recover the
8161:  * original definitions */
8162: #undef PetscCall
8163: #undef SETERRQ