Actual source code: mpibaij.c

  1: #include <../src/mat/impls/baij/mpi/mpibaij.h>

  3: #include <petsc/private/hashseti.h>
  4: #include <petscblaslapack.h>
  5: #include <petscsf.h>

  7: #if PetscDefined(HAVE_LIBXSMM)
  8: PETSC_INTERN PetscErrorCode MatConvert_MPIBAIJ_MPIBAIJLIBXSMM(Mat, MatType, MatReuse, Mat *);
  9: #endif

 11: static PetscErrorCode MatDestroy_MPIBAIJ(Mat mat)
 12: {
 13:   Mat_MPIBAIJ *baij = (Mat_MPIBAIJ *)mat->data;

 15:   PetscFunctionBegin;
 16:   PetscCall(PetscLogObjectState((PetscObject)mat, "Rows=%" PetscInt_FMT ",Cols=%" PetscInt_FMT, mat->rmap->N, mat->cmap->N));
 17:   PetscCall(MatStashDestroy_Private(&mat->stash));
 18:   PetscCall(MatStashDestroy_Private(&mat->bstash));
 19:   PetscCall(MatDestroy(&baij->A));
 20:   PetscCall(MatDestroy(&baij->B));
 21: #if PetscDefined(USE_CTABLE)
 22:   PetscCall(PetscHMapIDestroy(&baij->colmap));
 23: #else
 24:   PetscCall(PetscFree(baij->colmap));
 25: #endif
 26:   PetscCall(PetscFree(baij->garray));
 27:   PetscCall(VecDestroy(&baij->lvec));
 28:   PetscCall(VecScatterDestroy(&baij->Mvctx));
 29:   PetscCall(PetscFree2(baij->rowvalues, baij->rowindices));
 30:   PetscCall(PetscFree(baij->barray));
 31:   PetscCall(PetscFree2(baij->hd, baij->ht));
 32:   PetscCall(PetscFree(baij->rangebs));
 33:   PetscCall(PetscFree(mat->data));

 35:   PetscCall(PetscObjectChangeTypeName((PetscObject)mat, NULL));
 36:   PetscCall(PetscObjectComposeFunction((PetscObject)mat, "MatStoreValues_C", NULL));
 37:   PetscCall(PetscObjectComposeFunction((PetscObject)mat, "MatRetrieveValues_C", NULL));
 38:   PetscCall(PetscObjectComposeFunction((PetscObject)mat, "MatGetMultPetscSF_C", NULL));
 39:   PetscCall(PetscObjectComposeFunction((PetscObject)mat, "MatMPIBAIJSetPreallocation_C", NULL));
 40:   PetscCall(PetscObjectComposeFunction((PetscObject)mat, "MatMPIBAIJSetPreallocationCSR_C", NULL));
 41:   PetscCall(PetscObjectComposeFunction((PetscObject)mat, "MatDiagonalScaleLocal_C", NULL));
 42:   PetscCall(PetscObjectComposeFunction((PetscObject)mat, "MatSetHashTableFactor_C", NULL));
 43:   PetscCall(PetscObjectComposeFunction((PetscObject)mat, "MatProductSetFromOptions_mpibaij_mpidense_C", NULL));
 44:   PetscCall(PetscObjectComposeFunction((PetscObject)mat, "MatConvert_mpibaij_mpisbaij_C", NULL));
 45:   PetscCall(PetscObjectComposeFunction((PetscObject)mat, "MatConvert_mpibaij_mpiadj_C", NULL));
 46:   PetscCall(PetscObjectComposeFunction((PetscObject)mat, "MatConvert_mpibaij_mpiaij_C", NULL));
 47: #if PetscDefined(HAVE_HYPRE)
 48:   PetscCall(PetscObjectComposeFunction((PetscObject)mat, "MatConvert_mpibaij_hypre_C", NULL));
 49: #endif
 50:   PetscCall(PetscObjectComposeFunction((PetscObject)mat, "MatConvert_mpibaij_is_C", NULL));
 51: #if PetscDefined(HAVE_LIBXSMM)
 52:   PetscCall(PetscObjectComposeFunction((PetscObject)mat, "MatConvert_mpibaij_mpibaijlibxsmm_C", NULL));
 53:   PetscCall(PetscObjectComposeFunction((PetscObject)mat, "MatProductSetFromOptions_mpibaijlibxsmm_mpidense_C", NULL));
 54:   PetscCall(PetscObjectComposeFunction((PetscObject)mat, "MatConvert_mpibaijlibxsmm_mpibaij_C", NULL));
 55: #endif
 56:   PetscFunctionReturn(PETSC_SUCCESS);
 57: }

 59: /* defines MatSetValues_MPI_Hash(), MatAssemblyBegin_MPI_Hash(), and  MatAssemblyEnd_MPI_Hash() */
 60: #define TYPE BAIJ
 61: #include "../src/mat/impls/aij/mpi/mpihashmat.h"
 62: #undef TYPE

 64: #if PetscDefined(HAVE_HYPRE)
 65: PETSC_INTERN PetscErrorCode MatConvert_AIJ_HYPRE(Mat, MatType, MatReuse, Mat *);
 66: #endif

 68: static PetscErrorCode MatGetRowMaxAbs_MPIBAIJ(Mat A, Vec v, PetscInt idx[])
 69: {
 70:   Mat_MPIBAIJ       *a = (Mat_MPIBAIJ *)A->data;
 71:   PetscInt           i, *idxb = NULL, m = A->rmap->n, bs = A->cmap->bs;
 72:   PetscScalar       *vv;
 73:   Vec                vB, vA;
 74:   const PetscScalar *va, *vb;

 76:   PetscFunctionBegin;
 77:   PetscCall(MatCreateVecs(a->A, NULL, &vA));
 78:   PetscCall(MatGetRowMaxAbs(a->A, vA, idx));

 80:   PetscCall(VecGetArrayRead(vA, &va));
 81:   if (idx) {
 82:     for (i = 0; i < m; i++) {
 83:       if (PetscAbsScalar(va[i])) idx[i] += A->cmap->rstart;
 84:     }
 85:   }

 87:   PetscCall(MatCreateVecs(a->B, NULL, &vB));
 88:   PetscCall(PetscMalloc1(m, &idxb));
 89:   PetscCall(MatGetRowMaxAbs(a->B, vB, idxb));

 91:   PetscCall(VecGetArrayWrite(v, &vv));
 92:   PetscCall(VecGetArrayRead(vB, &vb));
 93:   for (i = 0; i < m; i++) {
 94:     if (PetscAbsScalar(va[i]) < PetscAbsScalar(vb[i])) {
 95:       vv[i] = vb[i];
 96:       if (idx) idx[i] = bs * a->garray[idxb[i] / bs] + (idxb[i] % bs);
 97:     } else {
 98:       vv[i] = va[i];
 99:       if (idx && PetscAbsScalar(va[i]) == PetscAbsScalar(vb[i]) && idxb[i] != -1 && idx[i] > bs * a->garray[idxb[i] / bs] + (idxb[i] % bs)) idx[i] = bs * a->garray[idxb[i] / bs] + (idxb[i] % bs);
100:     }
101:   }
102:   PetscCall(VecRestoreArrayWrite(v, &vv));
103:   PetscCall(VecRestoreArrayRead(vA, &va));
104:   PetscCall(VecRestoreArrayRead(vB, &vb));
105:   PetscCall(PetscFree(idxb));
106:   PetscCall(VecDestroy(&vA));
107:   PetscCall(VecDestroy(&vB));
108:   PetscFunctionReturn(PETSC_SUCCESS);
109: }

111: static PetscErrorCode MatGetRowSumAbs_MPIBAIJ(Mat A, Vec v)
112: {
113:   Mat_MPIBAIJ *a = (Mat_MPIBAIJ *)A->data;
114:   Vec          vB, vA;

116:   PetscFunctionBegin;
117:   PetscCall(MatCreateVecs(a->A, NULL, &vA));
118:   PetscCall(MatGetRowSumAbs(a->A, vA));
119:   PetscCall(MatCreateVecs(a->B, NULL, &vB));
120:   PetscCall(MatGetRowSumAbs(a->B, vB));
121:   PetscCall(VecAXPY(vA, 1.0, vB));
122:   PetscCall(VecDestroy(&vB));
123:   PetscCall(VecCopy(vA, v));
124:   PetscCall(VecDestroy(&vA));
125:   PetscFunctionReturn(PETSC_SUCCESS);
126: }

128: static PetscErrorCode MatStoreValues_MPIBAIJ(Mat mat)
129: {
130:   Mat_MPIBAIJ *aij = (Mat_MPIBAIJ *)mat->data;

132:   PetscFunctionBegin;
133:   PetscCall(MatStoreValues(aij->A));
134:   PetscCall(MatStoreValues(aij->B));
135:   PetscFunctionReturn(PETSC_SUCCESS);
136: }

138: static PetscErrorCode MatRetrieveValues_MPIBAIJ(Mat mat)
139: {
140:   Mat_MPIBAIJ *aij = (Mat_MPIBAIJ *)mat->data;

142:   PetscFunctionBegin;
143:   PetscCall(MatRetrieveValues(aij->A));
144:   PetscCall(MatRetrieveValues(aij->B));
145:   PetscFunctionReturn(PETSC_SUCCESS);
146: }

148: /*
149:      Local utility routine that creates a mapping from the global column
150:    number to the local number in the off-diagonal part of the local
151:    storage of the matrix.  This is done in a non scalable way since the
152:    length of colmap equals the global matrix length.
153: */
154: PetscErrorCode MatCreateColmap_MPIBAIJ_Private(Mat mat)
155: {
156:   Mat_MPIBAIJ *baij = (Mat_MPIBAIJ *)mat->data;
157:   Mat_SeqBAIJ *B    = (Mat_SeqBAIJ *)baij->B->data;
158:   PetscInt     nbs = B->nbs, i, bs = mat->rmap->bs;

160:   PetscFunctionBegin;
161: #if PetscDefined(USE_CTABLE)
162:   PetscCall(PetscHMapICreateWithSize(baij->nbs, &baij->colmap));
163:   for (i = 0; i < nbs; i++) PetscCall(PetscHMapISet(baij->colmap, baij->garray[i] + 1, i * bs + 1));
164: #else
165:   PetscCall(PetscCalloc1(baij->Nbs + 1, &baij->colmap));
166:   for (i = 0; i < nbs; i++) baij->colmap[baij->garray[i]] = i * bs + 1;
167: #endif
168:   PetscFunctionReturn(PETSC_SUCCESS);
169: }

171: #define MatSetValues_SeqBAIJ_A_Private(row, col, value, addv, orow, ocol) \
172:   do { \
173:     brow = (row) / bs; \
174:     rp   = PetscSafePointerPlusOffset(aj, ai[brow]); \
175:     if (!A->structure_only) ap = PetscSafePointerPlusOffset(aa, bs2 * ai[brow]); \
176:     rmax = aimax[brow]; \
177:     nrow = ailen[brow]; \
178:     bcol = (col) / bs; \
179:     ridx = (row) % bs; \
180:     cidx = (col) % bs; \
181:     low  = 0; \
182:     high = nrow; \
183:     while (high - low > 3) { \
184:       t = (low + high) / 2; \
185:       if (rp[t] > bcol) high = t; \
186:       else low = t; \
187:     } \
188:     for (_i = low; _i < high; _i++) { \
189:       if (rp[_i] > bcol) break; \
190:       if (rp[_i] == bcol) { \
191:         if (A->structure_only) goto a_noinsert; \
192:         bap = ap + bs2 * _i + bs * cidx + ridx; \
193:         if (addv == ADD_VALUES) *bap += value; \
194:         else *bap = value; \
195:         goto a_noinsert; \
196:       } \
197:     } \
198:     if (a->nonew == 1) goto a_noinsert; \
199:     PetscCheck(a->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); \
200:     if (A->structure_only) MatSeqXAIJReallocateAIJ_structure_only(A, a->mbs, bs2, nrow, brow, bcol, rmax, ai, aj, rp, aimax, a->nonew, MatScalar); \
201:     else MatSeqXAIJReallocateAIJ(A, a->mbs, bs2, nrow, brow, bcol, rmax, aa, ai, aj, rp, ap, aimax, a->nonew, MatScalar); \
202:     N = nrow++ - 1; \
203:     /* shift up all the later entries in this row */ \
204:     PetscCall(PetscArraymove(rp + _i + 1, rp + _i, N - _i + 1)); \
205:     rp[_i] = bcol; \
206:     if (!A->structure_only) { \
207:       PetscCall(PetscArraymove(ap + bs2 * (_i + 1), ap + bs2 * _i, bs2 * (N - _i + 1))); \
208:       PetscCall(PetscArrayzero(ap + bs2 * _i, bs2)); \
209:       ap[bs2 * _i + bs * cidx + ridx] = value; \
210:     } \
211:   a_noinsert:; \
212:     ailen[brow] = nrow; \
213:   } while (0)

215: #define MatSetValues_SeqBAIJ_B_Private(row, col, value, addv, orow, ocol) \
216:   do { \
217:     brow = (row) / bs; \
218:     rp   = PetscSafePointerPlusOffset(bj, bi[brow]); \
219:     if (!B->structure_only) ap = PetscSafePointerPlusOffset(ba, bs2 * bi[brow]); \
220:     rmax = bimax[brow]; \
221:     nrow = bilen[brow]; \
222:     bcol = (col) / bs; \
223:     ridx = (row) % bs; \
224:     cidx = (col) % bs; \
225:     low  = 0; \
226:     high = nrow; \
227:     while (high - low > 3) { \
228:       t = (low + high) / 2; \
229:       if (rp[t] > bcol) high = t; \
230:       else low = t; \
231:     } \
232:     for (_i = low; _i < high; _i++) { \
233:       if (rp[_i] > bcol) break; \
234:       if (rp[_i] == bcol) { \
235:         if (B->structure_only) goto b_noinsert; \
236:         bap = ap + bs2 * _i + bs * cidx + ridx; \
237:         if (addv == ADD_VALUES) *bap += value; \
238:         else *bap = value; \
239:         goto b_noinsert; \
240:       } \
241:     } \
242:     if (b->nonew == 1) goto b_noinsert; \
243:     PetscCheck(b->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); \
244:     if (B->structure_only) MatSeqXAIJReallocateAIJ_structure_only(B, b->mbs, bs2, nrow, brow, bcol, rmax, bi, bj, rp, bimax, b->nonew, MatScalar); \
245:     else MatSeqXAIJReallocateAIJ(B, b->mbs, bs2, nrow, brow, bcol, rmax, ba, bi, bj, rp, ap, bimax, b->nonew, MatScalar); \
246:     N = nrow++ - 1; \
247:     /* shift up all the later entries in this row */ \
248:     PetscCall(PetscArraymove(rp + _i + 1, rp + _i, N - _i + 1)); \
249:     rp[_i] = bcol; \
250:     if (!B->structure_only) { \
251:       PetscCall(PetscArraymove(ap + bs2 * (_i + 1), ap + bs2 * _i, bs2 * (N - _i + 1))); \
252:       PetscCall(PetscArrayzero(ap + bs2 * _i, bs2)); \
253:       ap[bs2 * _i + bs * cidx + ridx] = value; \
254:     } \
255:   b_noinsert:; \
256:     bilen[brow] = nrow; \
257:   } while (0)

259: static PetscErrorCode MatSetValues_MPIBAIJ(Mat mat, PetscInt m, const PetscInt im[], PetscInt n, const PetscInt in[], const PetscScalar v[], InsertMode addv)
260: {
261:   Mat_MPIBAIJ *baij        = (Mat_MPIBAIJ *)mat->data;
262:   MatScalar    value       = 0.0;
263:   PetscBool    roworiented = baij->roworiented;
264:   PetscInt     i, j, row, col;
265:   PetscInt     rstart_orig = mat->rmap->rstart;
266:   PetscInt     rend_orig = mat->rmap->rend, cstart_orig = mat->cmap->rstart;
267:   PetscInt     cend_orig = mat->cmap->rend, bs = mat->rmap->bs;

269:   /* Some Variables required in the macro */
270:   Mat          A     = baij->A;
271:   Mat_SeqBAIJ *a     = (Mat_SeqBAIJ *)A->data;
272:   PetscInt    *aimax = a->imax, *ai = a->i, *ailen = a->ilen, *aj = a->j;
273:   MatScalar   *aa = a->a;

275:   Mat          B     = baij->B;
276:   Mat_SeqBAIJ *b     = (Mat_SeqBAIJ *)B->data;
277:   PetscInt    *bimax = b->imax, *bi = b->i, *bilen = b->ilen, *bj = b->j;
278:   MatScalar   *ba = b->a;

280:   PetscInt  *rp, ii, nrow, _i, rmax, N, brow, bcol;
281:   PetscInt   low, high, t, ridx, cidx, bs2 = a->bs2;
282:   MatScalar *ap = NULL, *bap;

284:   PetscFunctionBegin;
285:   for (i = 0; i < m; i++) {
286:     if (im[i] < 0) continue;
287:     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);
288:     if (im[i] >= rstart_orig && im[i] < rend_orig) {
289:       row = im[i] - rstart_orig;
290:       for (j = 0; j < n; j++) {
291:         if (in[j] >= cstart_orig && in[j] < cend_orig) {
292:           col = in[j] - cstart_orig;
293:           if (!mat->structure_only) {
294:             if (roworiented) value = v[i * n + j];
295:             else value = v[i + j * m];
296:           }
297:           MatSetValues_SeqBAIJ_A_Private(row, col, value, addv, im[i], in[j]);
298:         } else if (in[j] < 0) {
299:           continue;
300:         } else {
301:           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);
302:           if (mat->was_assembled) {
303:             if (!baij->colmap) PetscCall(MatCreateColmap_MPIBAIJ_Private(mat));
304: #if PetscDefined(USE_CTABLE)
305:             PetscCall(PetscHMapIGetWithDefault(baij->colmap, in[j] / bs + 1, 0, &col));
306:             col = col - 1;
307: #else
308:             col = baij->colmap[in[j] / bs] - 1;
309: #endif
310:             if (col < 0 && !((Mat_SeqBAIJ *)baij->B->data)->nonew) {
311:               PetscCall(MatDisAssemble_MPIBAIJ(mat));
312:               col = in[j];
313:               /* Reinitialize the variables required by MatSetValues_SeqBAIJ_B_Private() */
314:               B     = baij->B;
315:               b     = (Mat_SeqBAIJ *)B->data;
316:               bimax = b->imax;
317:               bi    = b->i;
318:               bilen = b->ilen;
319:               bj    = b->j;
320:               ba    = b->a;
321:             } else {
322:               PetscCheck(col >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Inserting a new nonzero (%" PetscInt_FMT ", %" PetscInt_FMT ") into matrix", im[i], in[j]);
323:               col += in[j] % bs;
324:             }
325:           } else col = in[j];
326:           if (!mat->structure_only) {
327:             if (roworiented) value = v[i * n + j];
328:             else value = v[i + j * m];
329:           }
330:           MatSetValues_SeqBAIJ_B_Private(row, col, value, addv, im[i], in[j]);
331:           /* PetscCall(MatSetValues_SeqBAIJ(baij->B,1,&row,1,&col,&value,addv)); */
332:         }
333:       }
334:     } else {
335:       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]);
336:       if (!baij->donotstash) {
337:         mat->assembled = PETSC_FALSE;
338:         if (roworiented) {
339:           PetscCall(MatStashValuesRow_Private(&mat->stash, im[i], n, in, PetscSafePointerPlusOffset(v, i * n), PETSC_FALSE));
340:         } else {
341:           PetscCall(MatStashValuesCol_Private(&mat->stash, im[i], n, in, PetscSafePointerPlusOffset(v, i), m, PETSC_FALSE));
342:         }
343:       }
344:     }
345:   }
346:   PetscFunctionReturn(PETSC_SUCCESS);
347: }

349: static inline PetscErrorCode MatSetValuesBlocked_SeqBAIJ_Inlined(Mat A, PetscInt row, PetscInt col, const PetscScalar v[], InsertMode is, PetscInt orow, PetscInt ocol)
350: {
351:   Mat_SeqBAIJ       *a = (Mat_SeqBAIJ *)A->data;
352:   PetscInt          *rp, low, high, t, ii, jj, nrow, i, rmax, N;
353:   PetscInt          *imax = a->imax, *ai = a->i, *ailen = a->ilen;
354:   PetscInt          *aj = a->j, nonew = a->nonew, bs2 = a->bs2, bs = A->rmap->bs;
355:   PetscBool          roworiented = a->roworiented;
356:   const PetscScalar *value       = v;
357:   MatScalar         *ap = NULL, *aa = a->a, *bap;

359:   PetscFunctionBegin;
360:   rp    = aj + ai[row];
361:   ap    = PetscSafePointerPlusOffset(aa, bs2 * ai[row]);
362:   rmax  = imax[row];
363:   nrow  = ailen[row];
364:   value = v;
365:   low   = 0;
366:   high  = nrow;
367:   while (high - low > 7) {
368:     t = (low + high) / 2;
369:     if (rp[t] > col) high = t;
370:     else low = t;
371:   }
372:   for (i = low; i < high; i++) {
373:     if (rp[i] > col) break;
374:     if (rp[i] == col) {
375:       if (A->structure_only) goto noinsert2;
376:       bap = ap + bs2 * i;
377:       if (roworiented) {
378:         if (is == ADD_VALUES) {
379:           for (ii = 0; ii < bs; ii++) {
380:             for (jj = ii; jj < bs2; jj += bs) bap[jj] += *value++;
381:           }
382:         } else {
383:           for (ii = 0; ii < bs; ii++) {
384:             for (jj = ii; jj < bs2; jj += bs) bap[jj] = *value++;
385:           }
386:         }
387:       } else {
388:         if (is == ADD_VALUES) {
389:           for (ii = 0; ii < bs; ii++, value += bs) {
390:             for (jj = 0; jj < bs; jj++) bap[jj] += value[jj];
391:             bap += bs;
392:           }
393:         } else {
394:           for (ii = 0; ii < bs; ii++, value += bs) {
395:             for (jj = 0; jj < bs; jj++) bap[jj] = value[jj];
396:             bap += bs;
397:           }
398:         }
399:       }
400:       goto noinsert2;
401:     }
402:   }
403:   if (nonew == 1) goto noinsert2;
404:   PetscCheck(nonew != -1, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Inserting a new global block indexed nonzero block (%" PetscInt_FMT ", %" PetscInt_FMT ") in the matrix", orow, ocol);
405:   if (A->structure_only) MatSeqXAIJReallocateAIJ_structure_only(A, a->mbs, bs2, nrow, row, col, rmax, ai, aj, rp, imax, nonew, MatScalar);
406:   else MatSeqXAIJReallocateAIJ(A, a->mbs, bs2, nrow, row, col, rmax, aa, ai, aj, rp, ap, imax, nonew, MatScalar);
407:   N = nrow++ - 1;
408:   high++;
409:   /* shift up all the later entries in this row */
410:   PetscCall(PetscArraymove(rp + i + 1, rp + i, N - i + 1));
411:   rp[i] = col;
412:   if (!A->structure_only) {
413:     PetscCall(PetscArraymove(ap + bs2 * (i + 1), ap + bs2 * i, bs2 * (N - i + 1)));
414:     bap = ap + bs2 * i;
415:     if (roworiented) {
416:       for (ii = 0; ii < bs; ii++) {
417:         for (jj = ii; jj < bs2; jj += bs) bap[jj] = *value++;
418:       }
419:     } else {
420:       for (ii = 0; ii < bs; ii++) {
421:         for (jj = 0; jj < bs; jj++) *bap++ = *value++;
422:       }
423:     }
424:   }
425: noinsert2:;
426:   ailen[row] = nrow;
427:   PetscFunctionReturn(PETSC_SUCCESS);
428: }

430: /*
431:     This routine should be optimized so that the block copy at ** Here a copy is required ** below is not needed
432:     by passing additional stride information into the MatSetValuesBlocked_SeqBAIJ_Inlined() routine
433: */
434: static PetscErrorCode MatSetValuesBlocked_MPIBAIJ(Mat mat, PetscInt m, const PetscInt im[], PetscInt n, const PetscInt in[], const PetscScalar v[], InsertMode addv)
435: {
436:   Mat_MPIBAIJ       *baij = (Mat_MPIBAIJ *)mat->data;
437:   const PetscScalar *value;
438:   MatScalar         *barray      = baij->barray;
439:   PetscBool          roworiented = baij->roworiented;
440:   PetscInt           i, j, ii, jj, row, col, rstart = baij->rstartbs;
441:   PetscInt           rend = baij->rendbs, cstart = baij->cstartbs, stepval;
442:   PetscInt           cend = baij->cendbs, bs = mat->rmap->bs, bs2 = baij->bs2;

444:   PetscFunctionBegin;
445:   if (!mat->structure_only && !barray) {
446:     PetscCall(PetscMalloc1(bs2, &barray));
447:     baij->barray = barray;
448:   }

450:   if (roworiented) stepval = (n - 1) * bs;
451:   else stepval = (m - 1) * bs;

453:   for (i = 0; i < m; i++) {
454:     if (im[i] < 0) continue;
455:     PetscCheck(im[i] < baij->Mbs, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Block indexed row too large %" PetscInt_FMT " max %" PetscInt_FMT, im[i], baij->Mbs - 1);
456:     if (im[i] >= rstart && im[i] < rend) {
457:       row = im[i] - rstart;
458:       for (j = 0; j < n; j++) {
459:         if (!mat->structure_only) {
460:           /* If NumCol = 1 then a copy is not required */
461:           if (roworiented && (n == 1)) {
462:             barray = (MatScalar *)v + i * bs2;
463:           } else if ((!roworiented) && (m == 1)) {
464:             barray = (MatScalar *)v + j * bs2;
465:           } else { /* Here a copy is required */
466:             if (roworiented) {
467:               value = v + (i * (stepval + bs) + j) * bs;
468:             } else {
469:               value = v + (j * (stepval + bs) + i) * bs;
470:             }
471:             for (ii = 0; ii < bs; ii++, value += bs + stepval) {
472:               for (jj = 0; jj < bs; jj++) barray[jj] = value[jj];
473:               barray += bs;
474:             }
475:             barray -= bs2;
476:           }
477:         }

479:         if (in[j] >= cstart && in[j] < cend) {
480:           col = in[j] - cstart;
481:           PetscCall(MatSetValuesBlocked_SeqBAIJ_Inlined(baij->A, row, col, barray, addv, im[i], in[j]));
482:         } else if (in[j] < 0) {
483:           continue;
484:         } else {
485:           PetscCheck(in[j] < baij->Nbs, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Block indexed column too large %" PetscInt_FMT " max %" PetscInt_FMT, in[j], baij->Nbs - 1);
486:           if (mat->was_assembled) {
487:             if (!baij->colmap) PetscCall(MatCreateColmap_MPIBAIJ_Private(mat));

489: #if PetscDefined(USE_CTABLE)
490:             PetscCall(PetscHMapIGetWithDefault(baij->colmap, in[j] + 1, 0, &col));
491:             col = col < 1 ? -1 : (col - 1) / bs;
492: #else
493:             col = baij->colmap[in[j]] < 1 ? -1 : (baij->colmap[in[j]] - 1) / bs;
494: #endif
495:             if (col < 0 && !((Mat_SeqBAIJ *)baij->B->data)->nonew) {
496:               PetscCall(MatDisAssemble_MPIBAIJ(mat));
497:               col = in[j];
498:             } else PetscCheck(col >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Inserting a new blocked indexed nonzero block (%" PetscInt_FMT ", %" PetscInt_FMT ") into matrix", im[i], in[j]);
499:           } else col = in[j];
500:           PetscCall(MatSetValuesBlocked_SeqBAIJ_Inlined(baij->B, row, col, barray, addv, im[i], in[j]));
501:         }
502:       }
503:     } else {
504:       PetscCheck(!mat->nooffprocentries, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Setting off process block indexed row %" PetscInt_FMT " even though MatSetOption(,MAT_NO_OFF_PROC_ENTRIES,PETSC_TRUE) was set", im[i]);
505:       if (!baij->donotstash) {
506:         if (roworiented) {
507:           PetscCall(MatStashValuesRowBlocked_Private(&mat->bstash, im[i], n, in, v, m, n, i));
508:         } else {
509:           PetscCall(MatStashValuesColBlocked_Private(&mat->bstash, im[i], n, in, v, m, n, i));
510:         }
511:       }
512:     }
513:   }
514:   PetscFunctionReturn(PETSC_SUCCESS);
515: }

517: #define HASH_KEY             0.6180339887
518: #define HASH(size, key, tmp) (tmp = (key) * HASH_KEY, (PetscInt)((size) * ((tmp) - (PetscInt)(tmp))))
519: /* #define HASH(size,key) ((PetscInt)((size)*fmod(((key)*HASH_KEY),1))) */
520: /* #define HASH(size,key,tmp) ((PetscInt)((size)*fmod(((key)*HASH_KEY),1))) */
521: static PetscErrorCode MatSetValues_MPIBAIJ_HT(Mat mat, PetscInt m, const PetscInt im[], PetscInt n, const PetscInt in[], const PetscScalar v[], InsertMode addv)
522: {
523:   Mat_MPIBAIJ *baij        = (Mat_MPIBAIJ *)mat->data;
524:   PetscBool    roworiented = baij->roworiented;
525:   PetscInt     i, j, row, col;
526:   PetscInt     rstart_orig = mat->rmap->rstart;
527:   PetscInt     rend_orig = mat->rmap->rend, Nbs = baij->Nbs;
528:   PetscInt     h1, key, size = baij->ht_size, bs = mat->rmap->bs, *HT = baij->ht, idx;
529:   PetscReal    tmp;
530:   MatScalar  **HD       = baij->hd, value;
531:   PetscInt     total_ct = baij->ht_total_ct, insert_ct = baij->ht_insert_ct;

533:   PetscFunctionBegin;
534:   for (i = 0; i < m; i++) {
535:     if (PetscDefined(USE_DEBUG)) {
536:       PetscCheck(im[i] >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Negative row");
537:       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);
538:     }
539:     row = im[i];
540:     if (row >= rstart_orig && row < rend_orig) {
541:       for (j = 0; j < n; j++) {
542:         col = in[j];
543:         if (roworiented) value = v[i * n + j];
544:         else value = v[i + j * m];
545:         /* Look up PetscInto the Hash Table */
546:         key = (row / bs) * Nbs + (col / bs) + 1;
547:         h1  = HASH(size, key, tmp);

549:         idx = h1;
550:         if (PetscDefined(USE_DEBUG)) {
551:           insert_ct++;
552:           total_ct++;
553:           if (HT[idx] != key) {
554:             for (idx = h1; (idx < size) && (HT[idx] != key); idx++, total_ct++);
555:             if (idx == size) {
556:               for (idx = 0; (idx < h1) && (HT[idx] != key); idx++, total_ct++);
557:               PetscCheck(idx != h1, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "(%" PetscInt_FMT ",%" PetscInt_FMT ") has no entry in the hash table", row, col);
558:             }
559:           }
560:         } else if (HT[idx] != key) {
561:           for (idx = h1; (idx < size) && (HT[idx] != key); idx++);
562:           if (idx == size) {
563:             for (idx = 0; (idx < h1) && (HT[idx] != key); idx++);
564:             PetscCheck(idx != h1, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "(%" PetscInt_FMT ",%" PetscInt_FMT ") has no entry in the hash table", row, col);
565:           }
566:         }
567:         /* A HASH table entry is found, so insert the values at the correct address */
568:         if (addv == ADD_VALUES) *(HD[idx] + (col % bs) * bs + (row % bs)) += value;
569:         else *(HD[idx] + (col % bs) * bs + (row % bs)) = value;
570:       }
571:     } else if (!baij->donotstash) {
572:       if (roworiented) {
573:         PetscCall(MatStashValuesRow_Private(&mat->stash, im[i], n, in, v + i * n, PETSC_FALSE));
574:       } else {
575:         PetscCall(MatStashValuesCol_Private(&mat->stash, im[i], n, in, v + i, m, PETSC_FALSE));
576:       }
577:     }
578:   }
579:   if (PetscDefined(USE_DEBUG)) {
580:     baij->ht_total_ct += total_ct;
581:     baij->ht_insert_ct += insert_ct;
582:   }
583:   PetscFunctionReturn(PETSC_SUCCESS);
584: }

586: static PetscErrorCode MatSetValuesBlocked_MPIBAIJ_HT(Mat mat, PetscInt m, const PetscInt im[], PetscInt n, const PetscInt in[], const PetscScalar v[], InsertMode addv)
587: {
588:   Mat_MPIBAIJ       *baij        = (Mat_MPIBAIJ *)mat->data;
589:   PetscBool          roworiented = baij->roworiented;
590:   PetscInt           i, j, ii, jj, row, col;
591:   PetscInt           rstart = baij->rstartbs;
592:   PetscInt           rend = mat->rmap->rend, stepval, bs = mat->rmap->bs, bs2 = baij->bs2, nbs2 = n * bs2;
593:   PetscInt           h1, key, size = baij->ht_size, idx, *HT = baij->ht, Nbs = baij->Nbs;
594:   PetscReal          tmp;
595:   MatScalar        **HD = baij->hd, *baij_a;
596:   const PetscScalar *v_t, *value;
597:   PetscInt           total_ct = baij->ht_total_ct, insert_ct = baij->ht_insert_ct;

599:   PetscFunctionBegin;
600:   if (roworiented) stepval = (n - 1) * bs;
601:   else stepval = (m - 1) * bs;

603:   for (i = 0; i < m; i++) {
604:     if (PetscDefined(USE_DEBUG)) {
605:       PetscCheck(im[i] >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Negative row: %" PetscInt_FMT, im[i]);
606:       PetscCheck(im[i] < baij->Mbs, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Row too large: row %" PetscInt_FMT " max %" PetscInt_FMT, im[i], baij->Mbs - 1);
607:     }
608:     row = im[i];
609:     v_t = v + i * nbs2;
610:     if (row >= rstart && row < rend) {
611:       for (j = 0; j < n; j++) {
612:         col = in[j];

614:         /* Look up into the Hash Table */
615:         key = row * Nbs + col + 1;
616:         h1  = HASH(size, key, tmp);

618:         idx = h1;
619:         if (PetscDefined(USE_DEBUG)) {
620:           total_ct++;
621:           insert_ct++;
622:           if (HT[idx] != key) {
623:             for (idx = h1; (idx < size) && (HT[idx] != key); idx++, total_ct++);
624:             if (idx == size) {
625:               for (idx = 0; (idx < h1) && (HT[idx] != key); idx++, total_ct++);
626:               PetscCheck(idx != h1, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "(%" PetscInt_FMT ",%" PetscInt_FMT ") has no entry in the hash table", row, col);
627:             }
628:           }
629:         } else if (HT[idx] != key) {
630:           for (idx = h1; (idx < size) && (HT[idx] != key); idx++);
631:           if (idx == size) {
632:             for (idx = 0; (idx < h1) && (HT[idx] != key); idx++);
633:             PetscCheck(idx != h1, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "(%" PetscInt_FMT ",%" PetscInt_FMT ") has no entry in the hash table", row, col);
634:           }
635:         }
636:         baij_a = HD[idx];
637:         if (roworiented) {
638:           /*value = v + i*(stepval+bs)*bs + j*bs;*/
639:           /* value = v + (i*(stepval+bs)+j)*bs; */
640:           value = v_t;
641:           v_t += bs;
642:           if (addv == ADD_VALUES) {
643:             for (ii = 0; ii < bs; ii++, value += stepval) {
644:               for (jj = ii; jj < bs2; jj += bs) baij_a[jj] += *value++;
645:             }
646:           } else {
647:             for (ii = 0; ii < bs; ii++, value += stepval) {
648:               for (jj = ii; jj < bs2; jj += bs) baij_a[jj] = *value++;
649:             }
650:           }
651:         } else {
652:           value = v + j * (stepval + bs) * bs + i * bs;
653:           if (addv == ADD_VALUES) {
654:             for (ii = 0; ii < bs; ii++, value += stepval, baij_a += bs) {
655:               for (jj = 0; jj < bs; jj++) baij_a[jj] += *value++;
656:             }
657:           } else {
658:             for (ii = 0; ii < bs; ii++, value += stepval, baij_a += bs) {
659:               for (jj = 0; jj < bs; jj++) baij_a[jj] = *value++;
660:             }
661:           }
662:         }
663:       }
664:     } else {
665:       if (!baij->donotstash) {
666:         if (roworiented) {
667:           PetscCall(MatStashValuesRowBlocked_Private(&mat->bstash, im[i], n, in, v, m, n, i));
668:         } else {
669:           PetscCall(MatStashValuesColBlocked_Private(&mat->bstash, im[i], n, in, v, m, n, i));
670:         }
671:       }
672:     }
673:   }
674:   if (PetscDefined(USE_DEBUG)) {
675:     baij->ht_total_ct += total_ct;
676:     baij->ht_insert_ct += insert_ct;
677:   }
678:   PetscFunctionReturn(PETSC_SUCCESS);
679: }

681: static PetscErrorCode MatGetValues_MPIBAIJ(Mat mat, PetscInt m, const PetscInt idxm[], PetscInt n, const PetscInt idxn[], PetscScalar v[])
682: {
683:   Mat_MPIBAIJ *baij = (Mat_MPIBAIJ *)mat->data;
684:   PetscInt     bs = mat->rmap->bs, i, j, bsrstart = mat->rmap->rstart, bsrend = mat->rmap->rend;
685:   PetscInt     bscstart = mat->cmap->rstart, bscend = mat->cmap->rend, row, col, data;
686:   PetscBool    roworiented = baij->roworiented;
687:   PetscScalar *value;

689:   PetscFunctionBegin;
690:   for (i = 0; i < m; i++) {
691:     if (idxm[i] < 0) continue; /* negative row */
692:     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);
693:     PetscCheck(idxm[i] >= bsrstart && idxm[i] < bsrend, PETSC_COMM_SELF, PETSC_ERR_SUP, "Only local values currently supported");
694:     row = idxm[i] - bsrstart;
695:     for (j = 0; j < n; j++) {
696:       if (idxn[j] < 0) continue; /* negative column */
697:       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);
698:       value = roworiented ? &v[j + i * n] : &v[i + j * m];
699:       if (idxn[j] >= bscstart && idxn[j] < bscend) {
700:         col = idxn[j] - bscstart;
701:         PetscCall(MatGetValues_SeqBAIJ(baij->A, 1, &row, 1, &col, value));
702:       } else {
703:         if (!baij->colmap) PetscCall(MatCreateColmap_MPIBAIJ_Private(mat));
704: #if PetscDefined(USE_CTABLE)
705:         PetscCall(PetscHMapIGetWithDefault(baij->colmap, idxn[j] / bs + 1, 0, &data));
706:         data--;
707: #else
708:         data = baij->colmap[idxn[j] / bs] - 1;
709: #endif
710:         if (data < 0 || baij->garray[data / bs] != idxn[j] / bs) *value = 0.0;
711:         else {
712:           col = data + idxn[j] % bs;
713:           PetscCall(MatGetValues_SeqBAIJ(baij->B, 1, &row, 1, &col, value));
714:         }
715:       }
716:     }
717:   }
718:   PetscFunctionReturn(PETSC_SUCCESS);
719: }

721: static PetscErrorCode MatNorm_MPIBAIJ(Mat mat, NormType type, PetscReal *nrm)
722: {
723:   Mat_MPIBAIJ *baij = (Mat_MPIBAIJ *)mat->data;
724:   Mat_SeqBAIJ *amat = (Mat_SeqBAIJ *)baij->A->data, *bmat = (Mat_SeqBAIJ *)baij->B->data;
725:   PetscInt     i, j, bs2 = baij->bs2, bs = baij->A->rmap->bs, nz, row, col;
726:   PetscReal    sum = 0.0;
727:   MatScalar   *v;

729:   PetscFunctionBegin;
730:   if (baij->size == 1) {
731:     PetscCall(MatNorm(baij->A, type, nrm));
732:   } else {
733:     if (type == NORM_FROBENIUS) {
734:       v  = amat->a;
735:       nz = amat->nz * bs2;
736:       for (i = 0; i < nz; i++) {
737:         sum += PetscRealPart(PetscConj(*v) * (*v));
738:         v++;
739:       }
740:       v  = bmat->a;
741:       nz = bmat->nz * bs2;
742:       for (i = 0; i < nz; i++) {
743:         sum += PetscRealPart(PetscConj(*v) * (*v));
744:         v++;
745:       }
746:       PetscCallMPI(MPIU_Allreduce(&sum, nrm, 1, MPIU_REAL, MPIU_SUM, PetscObjectComm((PetscObject)mat)));
747:       *nrm = PetscSqrtReal(*nrm);
748:     } else if (type == NORM_1) { /* max column sum */
749:       Vec          col, bcol;
750:       PetscScalar *array;
751:       PetscInt    *jj, *garray = baij->garray;

753:       PetscCall(MatCreateVecs(mat, &col, NULL));
754:       PetscCall(VecGetArrayWrite(col, &array));
755:       v  = amat->a;
756:       jj = amat->j;
757:       for (i = 0; i < amat->nz; i++) {
758:         for (j = 0; j < bs; j++) {
759:           PetscInt col = bs * *jj + j; /* column index */

761:           for (row = 0; row < bs; row++) array[col] += PetscAbsScalar(*v++);
762:         }
763:         jj++;
764:       }
765:       PetscCall(VecRestoreArrayWrite(col, &array));
766:       PetscCall(MatCreateVecs(baij->B, &bcol, NULL));
767:       PetscCall(VecGetArrayWrite(bcol, &array));
768:       v  = bmat->a;
769:       jj = bmat->j;
770:       for (i = 0; i < bmat->nz; i++) {
771:         for (j = 0; j < bs; j++) {
772:           PetscInt col = bs * *jj + j; /* column index */

774:           for (row = 0; row < bs; row++) array[col] += PetscAbsScalar(*v++);
775:         }
776:         jj++;
777:       }
778:       PetscCall(VecSetValuesBlocked(col, bmat->nbs, garray, array, ADD_VALUES));
779:       PetscCall(VecRestoreArrayWrite(bcol, &array));
780:       PetscCall(VecDestroy(&bcol));
781:       PetscCall(VecAssemblyBegin(col));
782:       PetscCall(VecAssemblyEnd(col));
783:       PetscCall(VecNorm(col, NORM_INFINITY, nrm));
784:       PetscCall(VecDestroy(&col));
785:     } else if (type == NORM_INFINITY) { /* max row sum */
786:       PetscReal *sums;
787:       PetscCall(PetscMalloc1(bs, &sums));
788:       sum = 0.0;
789:       for (j = 0; j < amat->mbs; j++) {
790:         for (row = 0; row < bs; row++) sums[row] = 0.0;
791:         v  = amat->a + bs2 * amat->i[j];
792:         nz = amat->i[j + 1] - amat->i[j];
793:         for (i = 0; i < nz; i++) {
794:           for (col = 0; col < bs; col++) {
795:             for (row = 0; row < bs; row++) {
796:               sums[row] += PetscAbsScalar(*v);
797:               v++;
798:             }
799:           }
800:         }
801:         v  = bmat->a + bs2 * bmat->i[j];
802:         nz = bmat->i[j + 1] - bmat->i[j];
803:         for (i = 0; i < nz; i++) {
804:           for (col = 0; col < bs; col++) {
805:             for (row = 0; row < bs; row++) {
806:               sums[row] += PetscAbsScalar(*v);
807:               v++;
808:             }
809:           }
810:         }
811:         for (row = 0; row < bs; row++) {
812:           if (sums[row] > sum) sum = sums[row];
813:         }
814:       }
815:       PetscCallMPI(MPIU_Allreduce(&sum, nrm, 1, MPIU_REAL, MPIU_MAX, PetscObjectComm((PetscObject)mat)));
816:       PetscCall(PetscFree(sums));
817:     } else SETERRQ(PetscObjectComm((PetscObject)mat), PETSC_ERR_SUP, "No support for this norm yet");
818:   }
819:   PetscFunctionReturn(PETSC_SUCCESS);
820: }

822: /*
823:   Creates the hash table, and sets the table
824:   This table is created only once.
825:   If new entries need to be added to the matrix
826:   then the hash table has to be destroyed and
827:   recreated.
828: */
829: static PetscErrorCode MatCreateHashTable_MPIBAIJ_Private(Mat mat, PetscReal factor)
830: {
831:   Mat_MPIBAIJ *baij = (Mat_MPIBAIJ *)mat->data;
832:   Mat          A = baij->A, B = baij->B;
833:   Mat_SeqBAIJ *a = (Mat_SeqBAIJ *)A->data, *b = (Mat_SeqBAIJ *)B->data;
834:   PetscInt     i, j, k, nz = a->nz + b->nz, h1, *ai = a->i, *aj = a->j, *bi = b->i, *bj = b->j;
835:   PetscInt     ht_size, bs2 = baij->bs2, rstart = baij->rstartbs;
836:   PetscInt     cstart = baij->cstartbs, *garray = baij->garray, row, col, Nbs = baij->Nbs;
837:   PetscInt    *HT, key;
838:   MatScalar  **HD;
839:   PetscReal    tmp;
840:   PetscInt     ct = 0, max = 0;

842:   PetscFunctionBegin;
843:   if (baij->ht) PetscFunctionReturn(PETSC_SUCCESS);

845:   baij->ht_size = (PetscInt)(factor * nz);
846:   ht_size       = baij->ht_size;

848:   /* Allocate Memory for Hash Table */
849:   PetscCall(PetscCalloc2(ht_size, &baij->hd, ht_size, &baij->ht));
850:   HD = baij->hd;
851:   HT = baij->ht;

853:   /* Loop Over A */
854:   for (i = 0; i < a->mbs; i++) {
855:     for (j = ai[i]; j < ai[i + 1]; j++) {
856:       row = i + rstart;
857:       col = aj[j] + cstart;

859:       key = row * Nbs + col + 1;
860:       h1  = HASH(ht_size, key, tmp);
861:       for (k = 0; k < ht_size; k++) {
862:         if (!HT[(h1 + k) % ht_size]) {
863:           HT[(h1 + k) % ht_size] = key;
864:           HD[(h1 + k) % ht_size] = a->a + j * bs2;
865:           break;
866:         } else if (PetscDefined(USE_INFO)) ct++;
867:       }
868:       if (PetscDefined(USE_INFO) && k > max) max = k;
869:     }
870:   }
871:   /* Loop Over B */
872:   for (i = 0; i < b->mbs; i++) {
873:     for (j = bi[i]; j < bi[i + 1]; j++) {
874:       row = i + rstart;
875:       col = garray[bj[j]];
876:       key = row * Nbs + col + 1;
877:       h1  = HASH(ht_size, key, tmp);
878:       for (k = 0; k < ht_size; k++) {
879:         if (!HT[(h1 + k) % ht_size]) {
880:           HT[(h1 + k) % ht_size] = key;
881:           HD[(h1 + k) % ht_size] = b->a + j * bs2;
882:           break;
883:         } else if (PetscDefined(USE_INFO)) ct++;
884:       }
885:       if (PetscDefined(USE_INFO) && k > max) max = k;
886:     }
887:   }

889:   /* Print Summary */
890:   if (PetscDefined(USE_INFO)) {
891:     for (i = 0, j = 0; i < ht_size; i++) {
892:       if (HT[i]) j++;
893:     }
894:     PetscCall(PetscInfo(mat, "Average Search = %5.2g,max search = %" PetscInt_FMT "\n", (!j) ? 0.0 : (double)(((PetscReal)(ct + j)) / j), max));
895:   }
896:   PetscFunctionReturn(PETSC_SUCCESS);
897: }

899: static PetscErrorCode MatAssemblyBegin_MPIBAIJ(Mat mat, MatAssemblyType mode)
900: {
901:   Mat_MPIBAIJ *baij = (Mat_MPIBAIJ *)mat->data;
902:   PetscInt     nstash, reallocs;

904:   PetscFunctionBegin;
905:   if (baij->donotstash || mat->nooffprocentries) PetscFunctionReturn(PETSC_SUCCESS);

907:   PetscCall(MatStashScatterBegin_Private(mat, &mat->stash, mat->rmap->range));
908:   PetscCall(MatStashScatterBegin_Private(mat, &mat->bstash, baij->rangebs));
909:   PetscCall(MatStashGetInfo_Private(&mat->stash, &nstash, &reallocs));
910:   PetscCall(PetscInfo(mat, "Stash has %" PetscInt_FMT " entries, uses %" PetscInt_FMT " mallocs.\n", nstash, reallocs));
911:   PetscCall(MatStashGetInfo_Private(&mat->bstash, &nstash, &reallocs));
912:   PetscCall(PetscInfo(mat, "Block-Stash has %" PetscInt_FMT " entries, uses %" PetscInt_FMT " mallocs.\n", nstash, reallocs));
913:   PetscFunctionReturn(PETSC_SUCCESS);
914: }

916: static PetscErrorCode MatAssemblyEnd_MPIBAIJ(Mat mat, MatAssemblyType mode)
917: {
918:   Mat_MPIBAIJ *baij = (Mat_MPIBAIJ *)mat->data;
919:   Mat_SeqBAIJ *a    = (Mat_SeqBAIJ *)baij->A->data;
920:   PetscInt     i, j, rstart, ncols, flg, bs2 = baij->bs2;
921:   PetscInt    *row, *col;
922:   PetscBool    r1, r2, r3, all_assembled;
923:   MatScalar   *val;
924:   PetscMPIInt  n;

926:   PetscFunctionBegin;
927:   /* do not use 'b=(Mat_SeqBAIJ*)baij->B->data' as B can be reset in disassembly */
928:   if (!baij->donotstash && !mat->nooffprocentries) {
929:     while (1) {
930:       PetscCall(MatStashScatterGetMesg_Private(&mat->stash, &n, &row, &col, &val, &flg));
931:       if (!flg) break;

933:       for (i = 0; i < n;) {
934:         /* Now identify the consecutive vals belonging to the same row */
935:         for (j = i, rstart = row[j]; j < n; j++) {
936:           if (row[j] != rstart) break;
937:         }
938:         if (j < n) ncols = j - i;
939:         else ncols = n - i;
940:         /* Now assemble all these values with a single function call */
941:         PetscCall(MatSetValues_MPIBAIJ(mat, 1, row + i, ncols, col + i, val + i, mat->insertmode));
942:         i = j;
943:       }
944:     }
945:     PetscCall(MatStashScatterEnd_Private(&mat->stash));
946:     /* Now process the block-stash. Since the values are stashed column-oriented,
947:        set the row-oriented flag to column-oriented, and after MatSetValues()
948:        restore the original flags */
949:     r1 = baij->roworiented;
950:     r2 = a->roworiented;
951:     r3 = ((Mat_SeqBAIJ *)baij->B->data)->roworiented;

953:     baij->roworiented                           = PETSC_FALSE;
954:     a->roworiented                              = PETSC_FALSE;
955:     ((Mat_SeqBAIJ *)baij->B->data)->roworiented = PETSC_FALSE;
956:     while (1) {
957:       PetscCall(MatStashScatterGetMesg_Private(&mat->bstash, &n, &row, &col, &val, &flg));
958:       if (!flg) break;

960:       for (i = 0; i < n;) {
961:         /* Now identify the consecutive vals belonging to the same row */
962:         for (j = i, rstart = row[j]; j < n; j++) {
963:           if (row[j] != rstart) break;
964:         }
965:         if (j < n) ncols = j - i;
966:         else ncols = n - i;
967:         PetscCall(MatSetValuesBlocked_MPIBAIJ(mat, 1, row + i, ncols, col + i, val + i * bs2, mat->insertmode));
968:         i = j;
969:       }
970:     }
971:     PetscCall(MatStashScatterEnd_Private(&mat->bstash));

973:     baij->roworiented                           = r1;
974:     a->roworiented                              = r2;
975:     ((Mat_SeqBAIJ *)baij->B->data)->roworiented = r3;
976:   }

978:   PetscCall(MatAssemblyBegin(baij->A, mode));
979:   PetscCall(MatAssemblyEnd(baij->A, mode));

981:   /* determine if any process has disassembled, if so we must
982:      also disassemble ourselves, in order that we may reassemble. */
983:   /*
984:      if nonzero structure of submatrix B cannot change then we know that
985:      no process disassembled thus we can skip this stuff
986:   */
987:   if (!((Mat_SeqBAIJ *)baij->B->data)->nonew) {
988:     PetscCallMPI(MPIU_Allreduce(&mat->was_assembled, &all_assembled, 1, MPI_C_BOOL, MPI_LAND, PetscObjectComm((PetscObject)mat)));
989:     if (mat->was_assembled && !all_assembled) PetscCall(MatDisAssemble_MPIBAIJ(mat));
990:   }

992:   if (!mat->was_assembled && mode == MAT_FINAL_ASSEMBLY) PetscCall(MatSetUpMultiply_MPIBAIJ(mat));
993:   PetscCall(MatAssemblyBegin(baij->B, mode));
994:   PetscCall(MatAssemblyEnd(baij->B, mode));

996:   if (PetscDefined(USE_INFO) && baij->ht && mode == MAT_FINAL_ASSEMBLY) {
997:     PetscCall(PetscInfo(mat, "Average Hash Table Search in MatSetValues = %5.2f\n", (double)((PetscReal)baij->ht_total_ct) / baij->ht_insert_ct));

999:     baij->ht_total_ct  = 0;
1000:     baij->ht_insert_ct = 0;
1001:   }
1002:   if (baij->ht_flag && !baij->ht && mode == MAT_FINAL_ASSEMBLY) {
1003:     PetscCall(MatCreateHashTable_MPIBAIJ_Private(mat, baij->ht_fact));

1005:     mat->ops->setvalues        = MatSetValues_MPIBAIJ_HT;
1006:     mat->ops->setvaluesblocked = MatSetValuesBlocked_MPIBAIJ_HT;
1007:   }

1009:   PetscCall(PetscFree2(baij->rowvalues, baij->rowindices));

1011:   /* if no new nonzero locations are allowed in matrix then only set the matrix state the first time through */
1012:   if ((!mat->was_assembled && mode == MAT_FINAL_ASSEMBLY) || !((Mat_SeqBAIJ *)baij->A->data)->nonew) {
1013:     mat->nonzerostate = baij->A->nonzerostate + baij->B->nonzerostate;
1014:     PetscCallMPI(MPIU_Allreduce(MPI_IN_PLACE, &mat->nonzerostate, 1, MPIU_INT64, MPI_SUM, PetscObjectComm((PetscObject)mat)));
1015:   }
1016:   PetscFunctionReturn(PETSC_SUCCESS);
1017: }

1019: #include <petscdraw.h>
1020: static PetscErrorCode MatView_MPIBAIJ_ASCIIorDraworSocket(Mat mat, PetscViewer viewer)
1021: {
1022:   Mat_MPIBAIJ      *baij = (Mat_MPIBAIJ *)mat->data;
1023:   PetscMPIInt       rank = baij->rank;
1024:   PetscBool         isascii, isdraw;
1025:   PetscViewer       sviewer;
1026:   PetscViewerFormat format;

1028:   PetscFunctionBegin;
1029:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERASCII, &isascii));
1030:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERDRAW, &isdraw));
1031:   if (isascii) {
1032:     PetscCall(PetscViewerGetFormat(viewer, &format));
1033:     if (format == PETSC_VIEWER_ASCII_INFO_DETAIL) {
1034:       MatInfo info;
1035:       PetscCallMPI(MPI_Comm_rank(PetscObjectComm((PetscObject)mat), &rank));
1036:       PetscCall(MatGetInfo(mat, MAT_LOCAL, &info));
1037:       PetscCall(PetscViewerASCIIPushSynchronized(viewer));
1038:       PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, "[%d] Local rows %" PetscInt_FMT " nz %" PetscInt_FMT " nz alloced %" PetscInt_FMT " bs %" PetscInt_FMT " mem %g\n", rank, mat->rmap->n, (PetscInt)info.nz_used, (PetscInt)info.nz_allocated,
1039:                                                    mat->rmap->bs, info.memory));
1040:       PetscCall(MatGetInfo(baij->A, MAT_LOCAL, &info));
1041:       PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, "[%d] on-diagonal part: nz %" PetscInt_FMT " \n", rank, (PetscInt)info.nz_used));
1042:       PetscCall(MatGetInfo(baij->B, MAT_LOCAL, &info));
1043:       PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, "[%d] off-diagonal part: nz %" PetscInt_FMT " \n", rank, (PetscInt)info.nz_used));
1044:       PetscCall(PetscViewerFlush(viewer));
1045:       PetscCall(PetscViewerASCIIPopSynchronized(viewer));
1046:       PetscCall(PetscViewerASCIIPrintf(viewer, "Information on VecScatter used in matrix-vector product: \n"));
1047:       PetscCall(VecScatterView(baij->Mvctx, viewer));
1048:       PetscFunctionReturn(PETSC_SUCCESS);
1049:     } else if (format == PETSC_VIEWER_ASCII_INFO || format == PETSC_VIEWER_ASCII_FACTOR_INFO) PetscFunctionReturn(PETSC_SUCCESS);
1050:   }

1052:   if (isdraw) {
1053:     PetscDraw draw;
1054:     PetscBool isnull;
1055:     PetscCall(PetscViewerDrawGetDraw(viewer, 0, &draw));
1056:     PetscCall(PetscDrawIsNull(draw, &isnull));
1057:     if (isnull) PetscFunctionReturn(PETSC_SUCCESS);
1058:   }

1060:   { /* assemble the entire matrix onto first process */
1061:     Mat A, Av;
1062:     IS  isrow, iscol;

1064:     PetscCall(ISCreateStride(PetscObjectComm((PetscObject)mat), rank == 0 ? mat->rmap->N : 0, 0, 1, &isrow));
1065:     PetscCall(ISCreateStride(PetscObjectComm((PetscObject)mat), rank == 0 ? mat->cmap->N : 0, 0, 1, &iscol));
1066:     PetscCall(MatCreateSubMatrix(mat, isrow, iscol, MAT_INITIAL_MATRIX, &A));
1067:     PetscCall(MatMPIBAIJGetSeqBAIJ(A, &Av, NULL, NULL));
1068:     PetscCall(ISDestroy(&isrow));
1069:     PetscCall(ISDestroy(&iscol));
1070:     /*
1071:        Everyone has to call to draw the matrix since the graphics waits are
1072:        synchronized across all processors that share the PetscDraw object
1073:     */
1074:     PetscCall(PetscViewerGetSubViewer(viewer, PETSC_COMM_SELF, &sviewer));
1075:     if (rank == 0) {
1076:       if (((PetscObject)mat)->name) PetscCall(PetscObjectSetName((PetscObject)Av, ((PetscObject)mat)->name));
1077:       PetscCall(MatView_SeqBAIJ(Av, sviewer));
1078:     }
1079:     PetscCall(PetscViewerRestoreSubViewer(viewer, PETSC_COMM_SELF, &sviewer));
1080:     PetscCall(MatDestroy(&A));
1081:   }
1082:   PetscFunctionReturn(PETSC_SUCCESS);
1083: }

1085: /* Used for both MPIBAIJ and MPISBAIJ matrices */
1086: PetscErrorCode MatView_MPIBAIJ_Binary(Mat mat, PetscViewer viewer)
1087: {
1088:   Mat_MPIBAIJ    *aij    = (Mat_MPIBAIJ *)mat->data;
1089:   Mat_SeqBAIJ    *A      = (Mat_SeqBAIJ *)aij->A->data;
1090:   Mat_SeqBAIJ    *B      = (Mat_SeqBAIJ *)aij->B->data;
1091:   const PetscInt *garray = aij->garray;
1092:   PetscInt        header[4], M, N, m, rs, cs, bs, cnt, i, j, ja, jb, k, l;
1093:   PetscCount      nz, hnz;
1094:   PetscInt       *rowlens, *colidxs;
1095:   PetscScalar    *matvals;
1096:   PetscMPIInt     rank;

1098:   PetscFunctionBegin;
1099:   PetscCall(PetscViewerSetUp(viewer));

1101:   M  = mat->rmap->N;
1102:   N  = mat->cmap->N;
1103:   m  = mat->rmap->n;
1104:   rs = mat->rmap->rstart;
1105:   cs = mat->cmap->rstart;
1106:   bs = mat->rmap->bs;
1107:   nz = bs * bs * (A->nz + B->nz);

1109:   /* write matrix header */
1110:   header[0] = MAT_FILE_CLASSID;
1111:   header[1] = M;
1112:   header[2] = N;
1113:   PetscCallMPI(MPI_Reduce(&nz, &hnz, 1, MPIU_COUNT, MPI_SUM, 0, PetscObjectComm((PetscObject)mat)));
1114:   PetscCallMPI(MPI_Comm_rank(PetscObjectComm((PetscObject)mat), &rank));
1115:   if (rank == 0) PetscCall(PetscIntCast(hnz, &header[3]));
1116:   PetscCall(PetscViewerBinaryWrite(viewer, header, 4, PETSC_INT));

1118:   /* fill in and store row lengths */
1119:   PetscCall(PetscMalloc1(m, &rowlens));
1120:   for (cnt = 0, i = 0; i < A->mbs; i++)
1121:     for (j = 0; j < bs; j++) rowlens[cnt++] = bs * (A->i[i + 1] - A->i[i] + B->i[i + 1] - B->i[i]);
1122:   PetscCall(PetscViewerBinaryWriteAll(viewer, rowlens, m, rs, M, PETSC_INT));
1123:   PetscCall(PetscFree(rowlens));

1125:   /* fill in and store column indices */
1126:   PetscCall(PetscMalloc1(nz, &colidxs));
1127:   for (cnt = 0, i = 0; i < A->mbs; i++) {
1128:     for (k = 0; k < bs; k++) {
1129:       for (jb = B->i[i]; jb < B->i[i + 1]; jb++) {
1130:         if (garray[B->j[jb]] > cs / bs) break;
1131:         for (l = 0; l < bs; l++) colidxs[cnt++] = bs * garray[B->j[jb]] + l;
1132:       }
1133:       for (ja = A->i[i]; ja < A->i[i + 1]; ja++)
1134:         for (l = 0; l < bs; l++) colidxs[cnt++] = bs * A->j[ja] + l + cs;
1135:       for (; jb < B->i[i + 1]; jb++)
1136:         for (l = 0; l < bs; l++) colidxs[cnt++] = bs * garray[B->j[jb]] + l;
1137:     }
1138:   }
1139:   PetscCheck(cnt == nz, PETSC_COMM_SELF, PETSC_ERR_LIB, "Internal PETSc error: cnt = %" PetscInt_FMT " nz = %" PetscCount_FMT, cnt, nz);
1140:   PetscCall(PetscViewerBinaryWriteAll(viewer, colidxs, nz, PETSC_DECIDE, PETSC_DECIDE, PETSC_INT));
1141:   PetscCall(PetscFree(colidxs));

1143:   /* fill in and store nonzero values */
1144:   PetscCall(PetscMalloc1(nz, &matvals));
1145:   for (cnt = 0, i = 0; i < A->mbs; i++) {
1146:     for (k = 0; k < bs; k++) {
1147:       for (jb = B->i[i]; jb < B->i[i + 1]; jb++) {
1148:         if (garray[B->j[jb]] > cs / bs) break;
1149:         for (l = 0; l < bs; l++) matvals[cnt++] = B->a[bs * (bs * jb + l) + k];
1150:       }
1151:       for (ja = A->i[i]; ja < A->i[i + 1]; ja++)
1152:         for (l = 0; l < bs; l++) matvals[cnt++] = A->a[bs * (bs * ja + l) + k];
1153:       for (; jb < B->i[i + 1]; jb++)
1154:         for (l = 0; l < bs; l++) matvals[cnt++] = B->a[bs * (bs * jb + l) + k];
1155:     }
1156:   }
1157:   PetscCall(PetscViewerBinaryWriteAll(viewer, matvals, nz, PETSC_DECIDE, PETSC_DECIDE, PETSC_SCALAR));
1158:   PetscCall(PetscFree(matvals));

1160:   /* write block size option to the viewer's .info file */
1161:   PetscCall(MatView_Binary_BlockSizes(mat, viewer));
1162:   PetscFunctionReturn(PETSC_SUCCESS);
1163: }

1165: PetscErrorCode MatView_MPIBAIJ(Mat mat, PetscViewer viewer)
1166: {
1167:   PetscBool isascii, isdraw, issocket, isbinary;

1169:   PetscFunctionBegin;
1170:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERASCII, &isascii));
1171:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERDRAW, &isdraw));
1172:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERSOCKET, &issocket));
1173:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERBINARY, &isbinary));
1174:   if (isascii || isdraw || issocket) PetscCall(MatView_MPIBAIJ_ASCIIorDraworSocket(mat, viewer));
1175:   else if (isbinary) PetscCall(MatView_MPIBAIJ_Binary(mat, viewer));
1176:   PetscFunctionReturn(PETSC_SUCCESS);
1177: }

1179: static PetscErrorCode MatMult_MPIBAIJ(Mat A, Vec xx, Vec yy)
1180: {
1181:   Mat_MPIBAIJ *a = (Mat_MPIBAIJ *)A->data;
1182:   PetscInt     nt;

1184:   PetscFunctionBegin;
1185:   PetscCall(VecGetLocalSize(xx, &nt));
1186:   PetscCheck(nt == A->cmap->n, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Incompatible partition of A and xx");
1187:   PetscCall(VecGetLocalSize(yy, &nt));
1188:   PetscCheck(nt == A->rmap->n, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Incompatible partition of A and yy");
1189:   PetscCall(VecScatterBegin(a->Mvctx, xx, a->lvec, INSERT_VALUES, SCATTER_FORWARD));
1190:   PetscUseTypeMethod(a->A, mult, xx, yy);
1191:   PetscCall(VecScatterEnd(a->Mvctx, xx, a->lvec, INSERT_VALUES, SCATTER_FORWARD));
1192:   PetscUseTypeMethod(a->B, multadd, a->lvec, yy, yy);
1193:   PetscFunctionReturn(PETSC_SUCCESS);
1194: }

1196: static PetscErrorCode MatMultAdd_MPIBAIJ(Mat A, Vec xx, Vec yy, Vec zz)
1197: {
1198:   Mat_MPIBAIJ *a = (Mat_MPIBAIJ *)A->data;

1200:   PetscFunctionBegin;
1201:   PetscCall(VecScatterBegin(a->Mvctx, xx, a->lvec, INSERT_VALUES, SCATTER_FORWARD));
1202:   PetscUseTypeMethod(a->A, multadd, xx, yy, zz);
1203:   PetscCall(VecScatterEnd(a->Mvctx, xx, a->lvec, INSERT_VALUES, SCATTER_FORWARD));
1204:   PetscUseTypeMethod(a->B, multadd, a->lvec, zz, zz);
1205:   PetscFunctionReturn(PETSC_SUCCESS);
1206: }

1208: static PetscErrorCode MatMultTranspose_MPIBAIJ(Mat A, Vec xx, Vec yy)
1209: {
1210:   Mat_MPIBAIJ *a = (Mat_MPIBAIJ *)A->data;

1212:   PetscFunctionBegin;
1213:   /* do nondiagonal part */
1214:   PetscUseTypeMethod(a->B, multtranspose, xx, a->lvec);
1215:   /* do local part */
1216:   PetscUseTypeMethod(a->A, multtranspose, xx, yy);
1217:   /* add partial results together */
1218:   PetscCall(VecScatterBegin(a->Mvctx, a->lvec, yy, ADD_VALUES, SCATTER_REVERSE));
1219:   PetscCall(VecScatterEnd(a->Mvctx, a->lvec, yy, ADD_VALUES, SCATTER_REVERSE));
1220:   PetscFunctionReturn(PETSC_SUCCESS);
1221: }

1223: static PetscErrorCode MatMultTransposeAdd_MPIBAIJ(Mat A, Vec xx, Vec yy, Vec zz)
1224: {
1225:   Mat_MPIBAIJ *a = (Mat_MPIBAIJ *)A->data;

1227:   PetscFunctionBegin;
1228:   /* do nondiagonal part */
1229:   PetscUseTypeMethod(a->B, multtranspose, xx, a->lvec);
1230:   /* do local part */
1231:   PetscUseTypeMethod(a->A, multtransposeadd, xx, yy, zz);
1232:   /* add partial results together */
1233:   PetscCall(VecScatterBegin(a->Mvctx, a->lvec, zz, ADD_VALUES, SCATTER_REVERSE));
1234:   PetscCall(VecScatterEnd(a->Mvctx, a->lvec, zz, ADD_VALUES, SCATTER_REVERSE));
1235:   PetscFunctionReturn(PETSC_SUCCESS);
1236: }

1238: /*
1239:   This only works correctly for square matrices where the subblock A->A is the
1240:    diagonal block
1241: */
1242: static PetscErrorCode MatGetDiagonal_MPIBAIJ(Mat A, Vec v)
1243: {
1244:   PetscFunctionBegin;
1245:   PetscCheck(A->rmap->N == A->cmap->N, PETSC_COMM_SELF, PETSC_ERR_SUP, "Supports only square matrix where A->A is diag block");
1246:   PetscCall(MatGetDiagonal(((Mat_MPIBAIJ *)A->data)->A, v));
1247:   PetscFunctionReturn(PETSC_SUCCESS);
1248: }

1250: static PetscErrorCode MatScale_MPIBAIJ(Mat A, PetscScalar aa)
1251: {
1252:   Mat_MPIBAIJ *a = (Mat_MPIBAIJ *)A->data;

1254:   PetscFunctionBegin;
1255:   PetscCall(MatScale(a->A, aa));
1256:   PetscCall(MatScale(a->B, aa));
1257:   PetscFunctionReturn(PETSC_SUCCESS);
1258: }

1260: static PetscErrorCode MatGetRow_MPIBAIJ(Mat matin, PetscInt row, PetscInt *nz, PetscInt **idx, PetscScalar **v)
1261: {
1262:   Mat_MPIBAIJ *mat = (Mat_MPIBAIJ *)matin->data;
1263:   PetscScalar *vworkA, *vworkB, **pvA, **pvB, *v_p;
1264:   PetscInt     bs = matin->rmap->bs, bs2 = mat->bs2, i, *cworkA, *cworkB, **pcA, **pcB;
1265:   PetscInt     nztot, nzA, nzB, lrow, brstart = matin->rmap->rstart, brend = matin->rmap->rend;
1266:   PetscInt    *cmap, *idx_p, cstart = mat->cstartbs;

1268:   PetscFunctionBegin;
1269:   PetscCheck(row >= brstart && row < brend, PETSC_COMM_SELF, PETSC_ERR_SUP, "Only local rows");
1270:   PetscCheck(!mat->getrowactive, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Already active");
1271:   mat->getrowactive = PETSC_TRUE;

1273:   if (!mat->rowvalues && (idx || v)) {
1274:     /*
1275:         allocate enough space to hold information from the longest row.
1276:     */
1277:     Mat_SeqBAIJ *Aa = (Mat_SeqBAIJ *)mat->A->data, *Ba = (Mat_SeqBAIJ *)mat->B->data;
1278:     PetscInt     max = 1, mbs = mat->mbs, tmp;
1279:     for (i = 0; i < mbs; i++) {
1280:       tmp = Aa->i[i + 1] - Aa->i[i] + Ba->i[i + 1] - Ba->i[i];
1281:       if (max < tmp) max = tmp;
1282:     }
1283:     PetscCall(PetscMalloc2(max * bs2, &mat->rowvalues, max * bs2, &mat->rowindices));
1284:   }
1285:   lrow = row - brstart;

1287:   pvA = &vworkA;
1288:   pcA = &cworkA;
1289:   pvB = &vworkB;
1290:   pcB = &cworkB;
1291:   if (!v) {
1292:     pvA = NULL;
1293:     pvB = NULL;
1294:   }
1295:   if (!idx) {
1296:     pcA = NULL;
1297:     if (!v) pcB = NULL;
1298:   }
1299:   PetscUseTypeMethod(mat->A, getrow, lrow, &nzA, pcA, pvA);
1300:   PetscUseTypeMethod(mat->B, getrow, lrow, &nzB, pcB, pvB);
1301:   nztot = nzA + nzB;

1303:   cmap = mat->garray;
1304:   if (v || idx) {
1305:     if (nztot) {
1306:       /* Sort by increasing column numbers, assuming A and B already sorted */
1307:       PetscInt imark = -1;
1308:       if (v) {
1309:         *v = v_p = mat->rowvalues;
1310:         for (i = 0; i < nzB; i++) {
1311:           if (cmap[cworkB[i] / bs] < cstart) v_p[i] = vworkB[i];
1312:           else break;
1313:         }
1314:         imark = i;
1315:         for (i = 0; i < nzA; i++) v_p[imark + i] = vworkA[i];
1316:         for (i = imark; i < nzB; i++) v_p[nzA + i] = vworkB[i];
1317:       }
1318:       if (idx) {
1319:         *idx = idx_p = mat->rowindices;
1320:         if (imark > -1) {
1321:           for (i = 0; i < imark; i++) idx_p[i] = cmap[cworkB[i] / bs] * bs + cworkB[i] % bs;
1322:         } else {
1323:           for (i = 0; i < nzB; i++) {
1324:             if (cmap[cworkB[i] / bs] < cstart) idx_p[i] = cmap[cworkB[i] / bs] * bs + cworkB[i] % bs;
1325:             else break;
1326:           }
1327:           imark = i;
1328:         }
1329:         for (i = 0; i < nzA; i++) idx_p[imark + i] = cstart * bs + cworkA[i];
1330:         for (i = imark; i < nzB; i++) idx_p[nzA + i] = cmap[cworkB[i] / bs] * bs + cworkB[i] % bs;
1331:       }
1332:     } else {
1333:       if (idx) *idx = NULL;
1334:       if (v) *v = NULL;
1335:     }
1336:   }
1337:   *nz = nztot;
1338:   PetscUseTypeMethod(mat->A, restorerow, lrow, &nzA, pcA, pvA);
1339:   PetscUseTypeMethod(mat->B, restorerow, lrow, &nzB, pcB, pvB);
1340:   PetscFunctionReturn(PETSC_SUCCESS);
1341: }

1343: static PetscErrorCode MatRestoreRow_MPIBAIJ(Mat mat, PetscInt row, PetscInt *nz, PetscInt **idx, PetscScalar **v)
1344: {
1345:   Mat_MPIBAIJ *baij = (Mat_MPIBAIJ *)mat->data;

1347:   PetscFunctionBegin;
1348:   PetscCheck(baij->getrowactive, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "MatGetRow not called");
1349:   baij->getrowactive = PETSC_FALSE;
1350:   PetscFunctionReturn(PETSC_SUCCESS);
1351: }

1353: static PetscErrorCode MatZeroEntries_MPIBAIJ(Mat A)
1354: {
1355:   Mat_MPIBAIJ *l = (Mat_MPIBAIJ *)A->data;

1357:   PetscFunctionBegin;
1358:   PetscCall(MatZeroEntries(l->A));
1359:   PetscCall(MatZeroEntries(l->B));
1360:   PetscFunctionReturn(PETSC_SUCCESS);
1361: }

1363: static PetscErrorCode MatGetInfo_MPIBAIJ(Mat matin, MatInfoType flag, MatInfo *info)
1364: {
1365:   Mat_MPIBAIJ   *a = (Mat_MPIBAIJ *)matin->data;
1366:   Mat            A = a->A, B = a->B;
1367:   PetscLogDouble irecv[5];

1369:   PetscFunctionBegin;
1370:   info->block_size = (PetscReal)matin->rmap->bs;

1372:   PetscCall(MatGetInfo(A, MAT_LOCAL, info));

1374:   irecv[0] = info->nz_used;
1375:   irecv[1] = info->nz_allocated;
1376:   irecv[2] = info->nz_unneeded;
1377:   irecv[3] = info->memory;
1378:   irecv[4] = info->mallocs;

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

1382:   irecv[0] += info->nz_used;
1383:   irecv[1] += info->nz_allocated;
1384:   irecv[2] += info->nz_unneeded;
1385:   irecv[3] += info->memory;
1386:   irecv[4] += info->mallocs;

1388:   if (flag == MAT_LOCAL) {
1389:     info->nz_used      = irecv[0];
1390:     info->nz_allocated = irecv[1];
1391:     info->nz_unneeded  = irecv[2];
1392:     info->memory       = irecv[3];
1393:     info->mallocs      = irecv[4];
1394:   } else if (flag == MAT_GLOBAL_MAX) {
1395:     PetscCallMPI(MPIU_Allreduce(MPI_IN_PLACE, irecv, 5, MPIU_PETSCLOGDOUBLE, MPI_MAX, PetscObjectComm((PetscObject)matin)));

1397:     info->nz_used      = irecv[0];
1398:     info->nz_allocated = irecv[1];
1399:     info->nz_unneeded  = irecv[2];
1400:     info->memory       = irecv[3];
1401:     info->mallocs      = irecv[4];
1402:   } else if (flag == MAT_GLOBAL_SUM) {
1403:     PetscCallMPI(MPIU_Allreduce(MPI_IN_PLACE, irecv, 5, MPIU_PETSCLOGDOUBLE, MPI_SUM, PetscObjectComm((PetscObject)matin)));

1405:     info->nz_used      = irecv[0];
1406:     info->nz_allocated = irecv[1];
1407:     info->nz_unneeded  = irecv[2];
1408:     info->memory       = irecv[3];
1409:     info->mallocs      = irecv[4];
1410:   } else SETERRQ(PetscObjectComm((PetscObject)matin), PETSC_ERR_ARG_WRONG, "Unknown MatInfoType argument %d", (int)flag);
1411:   info->fill_ratio_given  = 0; /* no parallel LU/ILU/Cholesky */
1412:   info->fill_ratio_needed = 0;
1413:   info->factor_mallocs    = 0;
1414:   PetscFunctionReturn(PETSC_SUCCESS);
1415: }

1417: static PetscErrorCode MatSetOption_MPIBAIJ(Mat A, MatOption op, PetscBool flg)
1418: {
1419:   Mat_MPIBAIJ *a = (Mat_MPIBAIJ *)A->data;

1421:   PetscFunctionBegin;
1422:   switch (op) {
1423:   case MAT_NEW_NONZERO_LOCATIONS:
1424:   case MAT_NEW_NONZERO_ALLOCATION_ERR:
1425:   case MAT_UNUSED_NONZERO_LOCATION_ERR:
1426:   case MAT_KEEP_NONZERO_PATTERN:
1427:   case MAT_NEW_NONZERO_LOCATION_ERR:
1428:   case MAT_ROW_ORIENTED:
1429:     MatCheckPreallocated(A, 1);
1430:     if (op == MAT_ROW_ORIENTED) a->roworiented = flg;
1431:     PetscCall(MatSetOption(a->A, op, flg));
1432:     PetscCall(MatSetOption(a->B, op, flg));
1433:     break;
1434:   case MAT_STRUCTURE_ONLY:
1435:     if (a->A) PetscCall(MatSetOption(a->A, op, flg));
1436:     if (a->B) PetscCall(MatSetOption(a->B, op, flg));
1437:     break;
1438:   case MAT_IGNORE_OFF_PROC_ENTRIES:
1439:     a->donotstash = flg;
1440:     break;
1441:   case MAT_USE_HASH_TABLE:
1442:     a->ht_flag = flg;
1443:     a->ht_fact = 1.39;
1444:     break;
1445:   case MAT_SPD:
1446:   case MAT_SYMMETRIC:
1447:   case MAT_STRUCTURALLY_SYMMETRIC:
1448:   case MAT_HERMITIAN:
1449:   case MAT_SYMMETRY_ETERNAL:
1450:   case MAT_STRUCTURAL_SYMMETRY_ETERNAL:
1451:   case MAT_SPD_ETERNAL:
1452:     /* if the diagonal matrix is square it inherits some of the properties above */
1453:     if (a->A && A->rmap->n == A->cmap->n) PetscCall(MatSetOption(a->A, op, flg));
1454:     break;
1455:   default:
1456:     break;
1457:   }
1458:   PetscFunctionReturn(PETSC_SUCCESS);
1459: }

1461: static PetscErrorCode MatTranspose_MPIBAIJ(Mat A, MatReuse reuse, Mat *matout)
1462: {
1463:   Mat_MPIBAIJ *baij = (Mat_MPIBAIJ *)A->data;
1464:   Mat_SeqBAIJ *Aloc;
1465:   Mat          B;
1466:   PetscInt     M = A->rmap->N, N = A->cmap->N, *ai, *aj, i, *rvals, j, k, col;
1467:   PetscInt     bs = A->rmap->bs, mbs = baij->mbs;
1468:   MatScalar   *a;

1470:   PetscFunctionBegin;
1471:   if (reuse == MAT_REUSE_MATRIX) PetscCall(MatTransposeCheckNonzeroState_Private(A, *matout));
1472:   if (reuse == MAT_INITIAL_MATRIX || reuse == MAT_INPLACE_MATRIX) {
1473:     PetscCall(MatCreate(PetscObjectComm((PetscObject)A), &B));
1474:     PetscCall(MatSetSizes(B, A->cmap->n, A->rmap->n, N, M));
1475:     PetscCall(MatSetType(B, ((PetscObject)A)->type_name));
1476:     /* Do not know preallocation information, but must set block size */
1477:     PetscCall(MatMPIBAIJSetPreallocation(B, A->rmap->bs, PETSC_DECIDE, NULL, PETSC_DECIDE, NULL));
1478:   } else {
1479:     B = *matout;
1480:   }

1482:   /* copy over the A part */
1483:   Aloc = (Mat_SeqBAIJ *)baij->A->data;
1484:   ai   = Aloc->i;
1485:   aj   = Aloc->j;
1486:   a    = Aloc->a;
1487:   PetscCall(PetscMalloc1(bs, &rvals));

1489:   for (i = 0; i < mbs; i++) {
1490:     rvals[0] = bs * (baij->rstartbs + i);
1491:     for (j = 1; j < bs; j++) rvals[j] = rvals[j - 1] + 1;
1492:     for (j = ai[i]; j < ai[i + 1]; j++) {
1493:       col = (baij->cstartbs + aj[j]) * bs;
1494:       for (k = 0; k < bs; k++) {
1495:         PetscCall(MatSetValues_MPIBAIJ(B, 1, &col, bs, rvals, a, INSERT_VALUES));

1497:         col++;
1498:         a += bs;
1499:       }
1500:     }
1501:   }
1502:   /* copy over the B part */
1503:   Aloc = (Mat_SeqBAIJ *)baij->B->data;
1504:   ai   = Aloc->i;
1505:   aj   = Aloc->j;
1506:   a    = Aloc->a;
1507:   for (i = 0; i < mbs; i++) {
1508:     rvals[0] = bs * (baij->rstartbs + i);
1509:     for (j = 1; j < bs; j++) rvals[j] = rvals[j - 1] + 1;
1510:     for (j = ai[i]; j < ai[i + 1]; j++) {
1511:       col = baij->garray[aj[j]] * bs;
1512:       for (k = 0; k < bs; k++) {
1513:         PetscCall(MatSetValues_MPIBAIJ(B, 1, &col, bs, rvals, a, INSERT_VALUES));
1514:         col++;
1515:         a += bs;
1516:       }
1517:     }
1518:   }
1519:   PetscCall(PetscFree(rvals));
1520:   PetscCall(MatAssemblyBegin(B, MAT_FINAL_ASSEMBLY));
1521:   PetscCall(MatAssemblyEnd(B, MAT_FINAL_ASSEMBLY));

1523:   if (reuse == MAT_INITIAL_MATRIX || reuse == MAT_REUSE_MATRIX) *matout = B;
1524:   else PetscCall(MatHeaderMerge(A, &B));
1525:   PetscFunctionReturn(PETSC_SUCCESS);
1526: }

1528: static PetscErrorCode MatDiagonalScale_MPIBAIJ(Mat mat, Vec ll, Vec rr)
1529: {
1530:   Mat_MPIBAIJ *baij = (Mat_MPIBAIJ *)mat->data;
1531:   Mat          a = baij->A, b = baij->B;
1532:   PetscInt     s1, s2, s3;

1534:   PetscFunctionBegin;
1535:   PetscCall(MatGetLocalSize(mat, &s2, &s3));
1536:   if (rr) {
1537:     PetscCall(VecGetLocalSize(rr, &s1));
1538:     PetscCheck(s1 == s3, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "right vector non-conforming local size");
1539:     /* Overlap communication with computation. */
1540:     PetscCall(VecScatterBegin(baij->Mvctx, rr, baij->lvec, INSERT_VALUES, SCATTER_FORWARD));
1541:   }
1542:   if (ll) {
1543:     PetscCall(VecGetLocalSize(ll, &s1));
1544:     PetscCheck(s1 == s2, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "left vector non-conforming local size");
1545:     PetscUseTypeMethod(b, diagonalscale, ll, NULL);
1546:   }
1547:   /* scale  the diagonal block */
1548:   PetscUseTypeMethod(a, diagonalscale, ll, rr);

1550:   if (rr) {
1551:     /* Do a scatter end and then right scale the off-diagonal block */
1552:     PetscCall(VecScatterEnd(baij->Mvctx, rr, baij->lvec, INSERT_VALUES, SCATTER_FORWARD));
1553:     PetscUseTypeMethod(b, diagonalscale, NULL, baij->lvec);
1554:   }
1555:   /* MatDiagonalScale() cannot be used on the blocks: they are on PETSC_COMM_SELF while ll and rr
1556:      are parallel, so the interface's communicator check rejects them. Advance the block states
1557:      here instead, as the interface would. MatDiagonalScale_MPIAIJ() does not need this because
1558:      MatSeqAIJRestoreArray() advances the state for it. */
1559:   PetscCall(PetscObjectStateIncrease((PetscObject)a));
1560:   PetscCall(PetscObjectStateIncrease((PetscObject)b));
1561:   PetscFunctionReturn(PETSC_SUCCESS);
1562: }

1564: static PetscErrorCode MatZeroRows_MPIBAIJ(Mat A, PetscInt N, const PetscInt rows[], PetscScalar diag, Vec x, Vec b)
1565: {
1566:   Mat_MPIBAIJ *l = (Mat_MPIBAIJ *)A->data;
1567:   PetscInt    *lrows;
1568:   PetscInt     r, len;
1569:   PetscBool    cong;

1571:   PetscFunctionBegin;
1572:   /* get locally owned rows */
1573:   PetscCall(MatZeroRowsMapLocal_Private(A, N, rows, &len, &lrows));
1574:   /* fix right-hand side if needed */
1575:   if (x && b) {
1576:     const PetscScalar *xx;
1577:     PetscScalar       *bb;

1579:     PetscCall(VecGetArrayRead(x, &xx));
1580:     PetscCall(VecGetArray(b, &bb));
1581:     for (r = 0; r < len; ++r) bb[lrows[r]] = diag * xx[lrows[r]];
1582:     PetscCall(VecRestoreArrayRead(x, &xx));
1583:     PetscCall(VecRestoreArray(b, &bb));
1584:   }

1586:   /* actually zap the local rows */
1587:   /*
1588:         Zero the required rows. If the "diagonal block" of the matrix
1589:      is square and the user wishes to set the diagonal we use separate
1590:      code so that MatSetValues() is not called for each diagonal allocating
1591:      new memory, thus calling lots of mallocs and slowing things down.

1593:   */
1594:   /* must zero l->B before l->A because the (diag) case below may put values into l->B*/
1595:   PetscCall(MatZeroRows_SeqBAIJ(l->B, len, lrows, 0.0, NULL, NULL));
1596:   PetscCall(PetscObjectStateIncrease((PetscObject)l->B));
1597:   PetscCall(MatHasCongruentLayouts(A, &cong));
1598:   if ((diag != 0.0) && cong) {
1599:     PetscCall(MatZeroRows_SeqBAIJ(l->A, len, lrows, diag, NULL, NULL));
1600:   } else if (diag != 0.0) {
1601:     PetscCall(MatZeroRows_SeqBAIJ(l->A, len, lrows, 0.0, NULL, NULL));
1602:     PetscCheck(!((Mat_SeqBAIJ *)l->A->data)->nonew, PETSC_COMM_SELF, PETSC_ERR_SUP, "MatZeroRows() on rectangular matrices cannot be used with the Mat options MAT_NEW_NONZERO_LOCATIONS, MAT_NEW_NONZERO_LOCATION_ERR, and MAT_NEW_NONZERO_ALLOCATION_ERR");
1603:     for (r = 0; r < len; ++r) {
1604:       const PetscInt row = lrows[r] + A->rmap->rstart;
1605:       PetscCall(MatSetValues(A, 1, &row, 1, &row, &diag, INSERT_VALUES));
1606:     }
1607:     PetscCall(MatAssemblyBegin(A, MAT_FINAL_ASSEMBLY));
1608:     PetscCall(MatAssemblyEnd(A, MAT_FINAL_ASSEMBLY));
1609:   } else {
1610:     PetscCall(MatZeroRows_SeqBAIJ(l->A, len, lrows, 0.0, NULL, NULL));
1611:   }
1612:   /* MatZeroRows() cannot be used on the blocks: it honors -mat_view, which would print each
1613:      sequential block as well (see mat_tests-ex12_5). Advance the diagonal block's state here
1614:      instead, as the interface would; MatInvertBlockDiagonal_MPIBAIJ() caches on that state. */
1615:   PetscCall(PetscObjectStateIncrease((PetscObject)l->A));
1616:   PetscCall(PetscFree(lrows));

1618:   /* only change matrix nonzero state if pattern was allowed to be changed */
1619:   if (!((Mat_SeqBAIJ *)l->A->data)->keepnonzeropattern || !((Mat_SeqBAIJ *)l->A->data)->nonew) {
1620:     A->nonzerostate = l->A->nonzerostate + l->B->nonzerostate;
1621:     PetscCallMPI(MPIU_Allreduce(MPI_IN_PLACE, &A->nonzerostate, 1, MPIU_INT64, MPI_SUM, PetscObjectComm((PetscObject)A)));
1622:   }
1623:   PetscFunctionReturn(PETSC_SUCCESS);
1624: }

1626: static PetscErrorCode MatZeroRowsColumns_MPIBAIJ(Mat A, PetscInt N, const PetscInt rows[], PetscScalar diag, Vec x, Vec b)
1627: {
1628:   Mat_MPIBAIJ       *l = (Mat_MPIBAIJ *)A->data;
1629:   PetscMPIInt        n, p = 0;
1630:   PetscInt           i, j, k, r, len = 0, row, col, count;
1631:   PetscInt          *lrows, *owners = A->rmap->range;
1632:   PetscSFNode       *rrows;
1633:   PetscSF            sf;
1634:   const PetscScalar *xx;
1635:   PetscScalar       *bb, *mask;
1636:   Vec                xmask, lmask;
1637:   Mat_SeqBAIJ       *baij = (Mat_SeqBAIJ *)l->B->data;
1638:   PetscInt           bs = A->rmap->bs, bs2 = baij->bs2;
1639:   PetscScalar       *aa;

1641:   PetscFunctionBegin;
1642:   PetscCall(PetscMPIIntCast(A->rmap->n, &n));
1643:   /* create PetscSF where leaves are input rows and roots are owned rows */
1644:   PetscCall(PetscMalloc1(n, &lrows));
1645:   for (r = 0; r < n; ++r) lrows[r] = -1;
1646:   PetscCall(PetscMalloc1(N, &rrows));
1647:   for (r = 0; r < N; ++r) {
1648:     const PetscInt idx = rows[r];
1649:     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);
1650:     if (idx < owners[p] || owners[p + 1] <= idx) { /* short-circuit the search if the last p owns this row too */
1651:       PetscCall(PetscLayoutFindOwner(A->rmap, idx, &p));
1652:     }
1653:     rrows[r].rank  = p;
1654:     rrows[r].index = rows[r] - owners[p];
1655:   }
1656:   PetscCall(PetscSFCreate(PetscObjectComm((PetscObject)A), &sf));
1657:   PetscCall(PetscSFSetGraph(sf, n, N, NULL, PETSC_OWN_POINTER, rrows, PETSC_OWN_POINTER));
1658:   /* collect flags for rows to be zeroed */
1659:   PetscCall(PetscSFReduceBegin(sf, MPIU_INT, (PetscInt *)rows, lrows, MPI_LOR));
1660:   PetscCall(PetscSFReduceEnd(sf, MPIU_INT, (PetscInt *)rows, lrows, MPI_LOR));
1661:   PetscCall(PetscSFDestroy(&sf));
1662:   /* compress and put in row numbers */
1663:   for (r = 0; r < n; ++r)
1664:     if (lrows[r] >= 0) lrows[len++] = r;
1665:   /* zero diagonal part of matrix */
1666:   PetscCall(MatZeroRowsColumns(l->A, len, lrows, diag, x, b));
1667:   /* handle off-diagonal part of matrix */
1668:   PetscCall(MatCreateVecs(A, &xmask, NULL));
1669:   PetscCall(VecDuplicate(l->lvec, &lmask));
1670:   PetscCall(VecGetArray(xmask, &bb));
1671:   for (i = 0; i < len; i++) bb[lrows[i]] = 1;
1672:   PetscCall(VecRestoreArray(xmask, &bb));
1673:   PetscCall(VecScatterBegin(l->Mvctx, xmask, lmask, ADD_VALUES, SCATTER_FORWARD));
1674:   PetscCall(VecScatterEnd(l->Mvctx, xmask, lmask, ADD_VALUES, SCATTER_FORWARD));
1675:   PetscCall(VecDestroy(&xmask));
1676:   if (x) {
1677:     PetscCall(VecScatterBegin(l->Mvctx, x, l->lvec, INSERT_VALUES, SCATTER_FORWARD));
1678:     PetscCall(VecScatterEnd(l->Mvctx, x, l->lvec, INSERT_VALUES, SCATTER_FORWARD));
1679:     PetscCall(VecGetArrayRead(l->lvec, &xx));
1680:     PetscCall(VecGetArray(b, &bb));
1681:   }
1682:   PetscCall(VecGetArray(lmask, &mask));
1683:   /* remove zeroed rows of off-diagonal matrix */
1684:   for (i = 0; i < len; ++i) {
1685:     row   = lrows[i];
1686:     count = (baij->i[row / bs + 1] - baij->i[row / bs]) * bs;
1687:     aa    = PetscSafePointerPlusOffset(baij->a, baij->i[row / bs] * bs2 + (row % bs));
1688:     for (k = 0; k < count; ++k) {
1689:       aa[0] = 0.0;
1690:       aa += bs;
1691:     }
1692:   }
1693:   /* loop over all elements of off process part of matrix zeroing removed columns */
1694:   for (i = 0; i < l->B->rmap->N; ++i) {
1695:     row = i / bs;
1696:     for (j = baij->i[row]; j < baij->i[row + 1]; ++j) {
1697:       for (k = 0; k < bs; ++k) {
1698:         col = bs * baij->j[j] + k;
1699:         if (PetscAbsScalar(mask[col])) {
1700:           aa = baij->a + j * bs2 + (i % bs) + bs * k;
1701:           if (x) bb[i] -= aa[0] * xx[col];
1702:           aa[0] = 0.0;
1703:         }
1704:       }
1705:     }
1706:   }
1707:   if (x) {
1708:     PetscCall(VecRestoreArray(b, &bb));
1709:     PetscCall(VecRestoreArrayRead(l->lvec, &xx));
1710:   }
1711:   PetscCall(PetscObjectStateIncrease((PetscObject)l->B));
1712:   PetscCall(VecRestoreArray(lmask, &mask));
1713:   PetscCall(VecDestroy(&lmask));
1714:   PetscCall(PetscFree(lrows));

1716:   /* only change matrix nonzero state if pattern was allowed to be changed */
1717:   if (!((Mat_SeqBAIJ *)l->A->data)->nonew) {
1718:     A->nonzerostate = l->A->nonzerostate + l->B->nonzerostate;
1719:     PetscCallMPI(MPIU_Allreduce(MPI_IN_PLACE, &A->nonzerostate, 1, MPIU_INT64, MPI_SUM, PetscObjectComm((PetscObject)A)));
1720:   }
1721:   PetscFunctionReturn(PETSC_SUCCESS);
1722: }

1724: static PetscErrorCode MatSetUnfactored_MPIBAIJ(Mat A)
1725: {
1726:   Mat_MPIBAIJ *a = (Mat_MPIBAIJ *)A->data;

1728:   PetscFunctionBegin;
1729:   PetscCall(MatSetUnfactored(a->A));
1730:   PetscFunctionReturn(PETSC_SUCCESS);
1731: }

1733: static PetscErrorCode MatDuplicate_MPIBAIJ(Mat, MatDuplicateOption, Mat *);

1735: static PetscErrorCode MatEqual_MPIBAIJ(Mat A, Mat B, PetscBool *flag)
1736: {
1737:   Mat_MPIBAIJ *matB = (Mat_MPIBAIJ *)B->data, *matA = (Mat_MPIBAIJ *)A->data;
1738:   Mat          a, b, c, d;

1740:   PetscFunctionBegin;
1741:   a = matA->A;
1742:   b = matA->B;
1743:   c = matB->A;
1744:   d = matB->B;

1746:   PetscCall(MatEqual(a, c, flag));
1747:   if (*flag) PetscCall(MatEqual(b, d, flag));
1748:   PetscCallMPI(MPIU_Allreduce(MPI_IN_PLACE, flag, 1, MPI_C_BOOL, MPI_LAND, PetscObjectComm((PetscObject)A)));
1749:   PetscFunctionReturn(PETSC_SUCCESS);
1750: }

1752: static PetscErrorCode MatCopy_MPIBAIJ(Mat A, Mat B, MatStructure str)
1753: {
1754:   Mat_MPIBAIJ *a = (Mat_MPIBAIJ *)A->data;
1755:   Mat_MPIBAIJ *b = (Mat_MPIBAIJ *)B->data;

1757:   PetscFunctionBegin;
1758:   /* If the two matrices don't have the same copy implementation, they aren't compatible for fast copy. */
1759:   if (str != SAME_NONZERO_PATTERN || A->ops->copy != B->ops->copy) {
1760:     PetscCall(MatCopy_Basic(A, B, str));
1761:   } else {
1762:     PetscCall(MatCopy(a->A, b->A, str));
1763:     PetscCall(MatCopy(a->B, b->B, str));
1764:   }
1765:   PetscCall(PetscObjectStateIncrease((PetscObject)B));
1766:   PetscFunctionReturn(PETSC_SUCCESS);
1767: }

1769: PetscErrorCode MatAXPYGetPreallocation_MPIBAIJ(Mat Y, const PetscInt *yltog, Mat X, const PetscInt *xltog, PetscInt *nnz)
1770: {
1771:   PetscInt     bs = Y->rmap->bs, m = Y->rmap->N / bs;
1772:   Mat_SeqBAIJ *x = (Mat_SeqBAIJ *)X->data;
1773:   Mat_SeqBAIJ *y = (Mat_SeqBAIJ *)Y->data;

1775:   PetscFunctionBegin;
1776:   PetscCall(MatAXPYGetPreallocation_MPIX_private(m, x->i, x->j, xltog, y->i, y->j, yltog, nnz));
1777:   PetscFunctionReturn(PETSC_SUCCESS);
1778: }

1780: static PetscErrorCode MatAXPY_MPIBAIJ(Mat Y, PetscScalar a, Mat X, MatStructure str)
1781: {
1782:   Mat_MPIBAIJ *xx = (Mat_MPIBAIJ *)X->data, *yy = (Mat_MPIBAIJ *)Y->data;
1783:   PetscBLASInt bnz, one                         = 1;
1784:   Mat_SeqBAIJ *x, *y;
1785:   PetscInt     bs2 = Y->rmap->bs * Y->rmap->bs;

1787:   PetscFunctionBegin;
1788:   if (str == SAME_NONZERO_PATTERN) {
1789:     PetscScalar alpha = a;
1790:     x                 = (Mat_SeqBAIJ *)xx->A->data;
1791:     y                 = (Mat_SeqBAIJ *)yy->A->data;
1792:     PetscCall(PetscBLASIntCast(x->nz * bs2, &bnz));
1793:     PetscCallBLAS("BLASaxpy", BLASaxpy_(&bnz, &alpha, x->a, &one, y->a, &one));
1794:     x = (Mat_SeqBAIJ *)xx->B->data;
1795:     y = (Mat_SeqBAIJ *)yy->B->data;
1796:     PetscCall(PetscBLASIntCast(x->nz * bs2, &bnz));
1797:     PetscCallBLAS("BLASaxpy", BLASaxpy_(&bnz, &alpha, x->a, &one, y->a, &one));
1798:     /* the blocks' values were changed directly, so advance their states as MatAXPY() on each
1799:        block would; MatInvertBlockDiagonal_SeqBAIJ() caches on the diagonal block's state */
1800:     PetscCall(PetscObjectStateIncrease((PetscObject)yy->A));
1801:     PetscCall(PetscObjectStateIncrease((PetscObject)yy->B));
1802:     PetscCall(PetscObjectStateIncrease((PetscObject)Y));
1803:   } else if (str == SUBSET_NONZERO_PATTERN) { /* nonzeros of X is a subset of Y's */
1804:     PetscCall(MatAXPY_Basic(Y, a, X, str));
1805:   } else {
1806:     Mat       B;
1807:     PetscInt *nnz_d, *nnz_o, bs = Y->rmap->bs;
1808:     PetscCall(PetscMalloc1(yy->A->rmap->N, &nnz_d));
1809:     PetscCall(PetscMalloc1(yy->B->rmap->N, &nnz_o));
1810:     PetscCall(MatCreate(PetscObjectComm((PetscObject)Y), &B));
1811:     PetscCall(PetscObjectSetName((PetscObject)B, ((PetscObject)Y)->name));
1812:     PetscCall(MatSetSizes(B, Y->rmap->n, Y->cmap->n, Y->rmap->N, Y->cmap->N));
1813:     PetscCall(MatSetBlockSizesFromMats(B, Y, Y));
1814:     PetscCall(MatSetType(B, MATMPIBAIJ));
1815:     PetscCall(MatAXPYGetPreallocation_SeqBAIJ(yy->A, xx->A, nnz_d));
1816:     PetscCall(MatAXPYGetPreallocation_MPIBAIJ(yy->B, yy->garray, xx->B, xx->garray, nnz_o));
1817:     PetscCall(MatMPIBAIJSetPreallocation(B, bs, 0, nnz_d, 0, nnz_o));
1818:     /* MatAXPY_BasicWithPreallocation() for BAIJ matrix is much slower than AIJ, even for bs=1 ! */
1819:     PetscCall(MatAXPY_BasicWithPreallocation(B, Y, a, X, str));
1820:     PetscCall(MatHeaderMerge(Y, &B));
1821:     PetscCall(PetscFree(nnz_d));
1822:     PetscCall(PetscFree(nnz_o));
1823:   }
1824:   PetscFunctionReturn(PETSC_SUCCESS);
1825: }

1827: static PetscErrorCode MatConjugate_MPIBAIJ(Mat mat)
1828: {
1829:   Mat_MPIBAIJ *a = (Mat_MPIBAIJ *)mat->data;

1831:   PetscFunctionBegin;
1832:   PetscCall(MatConjugate(a->A));
1833:   PetscCall(MatConjugate(a->B));
1834:   PetscFunctionReturn(PETSC_SUCCESS);
1835: }

1837: static PetscErrorCode MatRealPart_MPIBAIJ(Mat A)
1838: {
1839:   Mat_MPIBAIJ *a = (Mat_MPIBAIJ *)A->data;

1841:   PetscFunctionBegin;
1842:   PetscCall(MatRealPart(a->A));
1843:   PetscCall(MatRealPart(a->B));
1844:   PetscFunctionReturn(PETSC_SUCCESS);
1845: }

1847: static PetscErrorCode MatImaginaryPart_MPIBAIJ(Mat A)
1848: {
1849:   Mat_MPIBAIJ *a = (Mat_MPIBAIJ *)A->data;

1851:   PetscFunctionBegin;
1852:   PetscCall(MatImaginaryPart(a->A));
1853:   PetscCall(MatImaginaryPart(a->B));
1854:   PetscFunctionReturn(PETSC_SUCCESS);
1855: }

1857: static PetscErrorCode MatCreateSubMatrix_MPIBAIJ(Mat mat, IS isrow, IS iscol, MatReuse call, Mat *newmat)
1858: {
1859:   IS       iscol_local;
1860:   PetscInt csize;

1862:   PetscFunctionBegin;
1863:   PetscCall(ISGetLocalSize(iscol, &csize));
1864:   if (call == MAT_REUSE_MATRIX) {
1865:     PetscCall(PetscObjectQuery((PetscObject)*newmat, "ISAllGather", (PetscObject *)&iscol_local));
1866:     PetscCheck(iscol_local, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Submatrix passed in was not used before, cannot reuse");
1867:   } else {
1868:     PetscCall(ISAllGather(iscol, &iscol_local));
1869:   }
1870:   PetscCall(MatCreateSubMatrix_MPIBAIJ_Private(mat, isrow, iscol_local, csize, call, newmat, PETSC_FALSE));
1871:   if (call == MAT_INITIAL_MATRIX) {
1872:     PetscCall(PetscObjectCompose((PetscObject)*newmat, "ISAllGather", (PetscObject)iscol_local));
1873:     PetscCall(ISDestroy(&iscol_local));
1874:   }
1875:   PetscFunctionReturn(PETSC_SUCCESS);
1876: }

1878: /*
1879:   Not great since it makes two copies of the submatrix, first an SeqBAIJ
1880:   in local and then by concatenating the local matrices the end result.
1881:   Writing it directly would be much like MatCreateSubMatrices_MPIBAIJ().
1882:   This routine is used for BAIJ and SBAIJ matrices (unfortunate dependency).
1883: */
1884: PetscErrorCode MatCreateSubMatrix_MPIBAIJ_Private(Mat mat, IS isrow, IS iscol, PetscInt csize, MatReuse call, Mat *newmat, PetscBool sym)
1885: {
1886:   PetscMPIInt  rank, size;
1887:   PetscInt     i, m, n, rstart, row, rend, nz, j, bs, nlocal, dlen, olen, jend, mglobal;
1888:   PetscInt    *cwork, *ii, *jj, *dlens, *olens;
1889:   Mat          M, Mreuse;
1890:   MatScalar   *vwork, *aa;
1891:   MPI_Comm     comm;
1892:   IS           isrow_new, iscol_new;
1893:   PetscBool    nooffprocentries, roworiented;
1894:   Mat_SeqBAIJ *aij;

1896:   PetscFunctionBegin;
1897:   PetscCall(PetscObjectGetComm((PetscObject)mat, &comm));
1898:   PetscCallMPI(MPI_Comm_rank(comm, &rank));
1899:   PetscCallMPI(MPI_Comm_size(comm, &size));
1900:   /* The compression and expansion should be avoided. Doesn't point
1901:      out errors, might change the indices, hence buggey */
1902:   PetscCall(ISCompressIndicesGeneral(mat->rmap->N, mat->rmap->n, mat->rmap->bs, 1, &isrow, &isrow_new));
1903:   if (isrow == iscol) {
1904:     iscol_new = isrow_new;
1905:     PetscCall(PetscObjectReference((PetscObject)iscol_new));
1906:   } else PetscCall(ISCompressIndicesGeneral(mat->cmap->N, mat->cmap->n, mat->cmap->bs, 1, &iscol, &iscol_new));

1908:   if (call == MAT_REUSE_MATRIX) {
1909:     PetscCall(PetscObjectQuery((PetscObject)*newmat, "SubMatrix", (PetscObject *)&Mreuse));
1910:     PetscCheck(Mreuse, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Submatrix passed in was not used before, cannot reuse");
1911:     PetscCall(MatCreateSubMatrices_MPIBAIJ_local(mat, 1, &isrow_new, &iscol_new, MAT_REUSE_MATRIX, &Mreuse, sym));
1912:   } else {
1913:     PetscCall(MatCreateSubMatrices_MPIBAIJ_local(mat, 1, &isrow_new, &iscol_new, MAT_INITIAL_MATRIX, &Mreuse, sym));
1914:   }
1915:   PetscCall(ISDestroy(&isrow_new));
1916:   PetscCall(ISDestroy(&iscol_new));
1917:   /*
1918:       m - number of local rows
1919:       n - number of columns (same on all processors)
1920:       rstart - first row in new global matrix generated
1921:   */
1922:   PetscCall(MatGetBlockSize(mat, &bs));
1923:   PetscCall(MatGetSize(Mreuse, &m, &n));
1924:   m = m / bs;
1925:   n = n / bs;

1927:   if (call == MAT_INITIAL_MATRIX) {
1928:     aij = (Mat_SeqBAIJ *)Mreuse->data;
1929:     ii  = aij->i;
1930:     jj  = aij->j;

1932:     /*
1933:         Determine the number of non-zeros in the diagonal and off-diagonal
1934:         portions of the matrix in order to do correct preallocation
1935:     */

1937:     /* first get start and end of "diagonal" columns */
1938:     if (csize == PETSC_DECIDE) {
1939:       PetscCall(ISGetSize(isrow, &mglobal));
1940:       if (mglobal == n * bs) { /* square matrix */
1941:         nlocal = m;
1942:       } else {
1943:         nlocal = n / size + ((n % size) > rank);
1944:       }
1945:     } else {
1946:       nlocal = csize / bs;
1947:     }
1948:     PetscCallMPI(MPI_Scan(&nlocal, &rend, 1, MPIU_INT, MPI_SUM, comm));
1949:     rstart = rend - nlocal;
1950:     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);

1952:     /* next, compute all the lengths */
1953:     PetscCall(PetscMalloc2(m + 1, &dlens, m + 1, &olens));
1954:     for (i = 0; i < m; i++) {
1955:       jend = ii[i + 1] - ii[i];
1956:       olen = 0;
1957:       dlen = 0;
1958:       for (j = 0; j < jend; j++) {
1959:         if (*jj < rstart || *jj >= rend) olen++;
1960:         else dlen++;
1961:         jj++;
1962:       }
1963:       olens[i] = olen;
1964:       dlens[i] = dlen;
1965:     }
1966:     PetscCall(MatCreate(comm, &M));
1967:     PetscCall(MatSetSizes(M, bs * m, bs * nlocal, PETSC_DECIDE, bs * n));
1968:     PetscCall(MatSetType(M, sym ? ((PetscObject)mat)->type_name : MATMPIBAIJ));
1969:     PetscCall(MatSetOption(M, MAT_STRUCTURE_ONLY, mat->structure_only));
1970:     PetscCall(MatMPIBAIJSetPreallocation(M, bs, 0, dlens, 0, olens));
1971:     PetscCall(MatMPISBAIJSetPreallocation(M, bs, 0, dlens, 0, olens));
1972:     PetscCall(PetscFree2(dlens, olens));
1973:   } else {
1974:     PetscInt ml, nl;

1976:     M = *newmat;
1977:     PetscCall(MatGetLocalSize(M, &ml, &nl));
1978:     PetscCheck(ml == m * bs, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Previous matrix must be same size/layout as request");
1979:     PetscCall(MatZeroEntries(M));
1980:     /*
1981:          The next two lines are needed so we may call MatSetValues_MPIAIJ() below directly,
1982:        rather than the slower MatSetValues().
1983:     */
1984:     M->was_assembled = PETSC_TRUE;
1985:     M->assembled     = PETSC_FALSE;
1986:   }
1987:   roworiented = ((Mat_MPIBAIJ *)M->data)->roworiented;
1988:   PetscCall(MatSetOption(M, MAT_ROW_ORIENTED, PETSC_FALSE));
1989:   PetscCall(MatGetOwnershipRange(M, &rstart, &rend));
1990:   aij = (Mat_SeqBAIJ *)Mreuse->data;
1991:   ii  = aij->i;
1992:   jj  = aij->j;
1993:   aa  = aij->a;
1994:   for (i = 0; i < m; i++) {
1995:     row   = rstart / bs + i;
1996:     nz    = ii[i + 1] - ii[i];
1997:     cwork = jj;
1998:     jj    = PetscSafePointerPlusOffset(jj, nz);
1999:     vwork = aa;
2000:     aa    = PetscSafePointerPlusOffset(aa, nz * bs * bs);
2001:     PetscUseTypeMethod(M, setvaluesblocked, 1, &row, nz, cwork, vwork, INSERT_VALUES);
2002:   }

2004:   PetscCall(MatSetOption(M, MAT_ROW_ORIENTED, roworiented));
2005:   nooffprocentries    = M->nooffprocentries;
2006:   M->nooffprocentries = PETSC_TRUE;
2007:   PetscCall(MatAssemblyBegin(M, MAT_FINAL_ASSEMBLY));
2008:   PetscCall(MatAssemblyEnd(M, MAT_FINAL_ASSEMBLY));
2009:   M->nooffprocentries = nooffprocentries;
2010:   *newmat             = M;

2012:   /* save submatrix used in processor for next request */
2013:   if (call == MAT_INITIAL_MATRIX) {
2014:     PetscCall(PetscObjectCompose((PetscObject)M, "SubMatrix", (PetscObject)Mreuse));
2015:     PetscCall(PetscObjectDereference((PetscObject)Mreuse));
2016:   }
2017:   PetscFunctionReturn(PETSC_SUCCESS);
2018: }

2020: static PetscErrorCode MatPermute_MPIBAIJ(Mat A, IS rowp, IS colp, Mat *B)
2021: {
2022:   MPI_Comm        comm, pcomm;
2023:   PetscInt        clocal_size, nrows, bs = A->rmap->bs;
2024:   const PetscInt *rows, *idx[2];
2025:   PetscMPIInt     size;
2026:   IS              crowp, lcolp, is[] = {rowp, colp};
2027:   PetscLayout     map[] = {A->rmap, A->cmap};
2028:   PetscBool       local = PETSC_TRUE;

2030:   PetscFunctionBegin;
2031:   PetscCall(PetscObjectGetComm((PetscObject)A, &comm));
2032:   for (PetscInt k = 0; k < 2; ++k) {
2033:     PetscInt n;

2035:     PetscCall(ISGetLocalSize(is[k], &n));
2036:     PetscCall(ISGetIndices(is[k], &idx[k]));
2037:     if (n != map[k]->n) local = PETSC_FALSE;
2038:     for (PetscInt i = 0; i < n && local == PETSC_TRUE; i += bs) {
2039:       PetscInt first = idx[k][i];

2041:       if (first < map[k]->rstart || first >= map[k]->rend || first % bs) local = PETSC_FALSE;
2042:       for (PetscInt j = 1; j < bs; ++j)
2043:         if (idx[k][i + j] != first + j) local = PETSC_FALSE;
2044:     }
2045:   }
2046:   PetscCallMPI(MPIU_Allreduce(MPI_IN_PLACE, &local, 1, MPI_C_BOOL, MPI_LAND, comm));
2047:   if (local == PETSC_TRUE) {
2048:     Mat_MPIBAIJ *a     = (Mat_MPIBAIJ *)A->data;
2049:     Mat_SeqBAIJ *seq[] = {(Mat_SeqBAIJ *)a->A->data, (Mat_SeqBAIJ *)a->B->data};
2050:     PetscInt    *dest[2], *nnz[2], *cols;
2051:     PetscInt     maxnz = 0;

2053:     /* reuse the MatMult() PetscSF to map only the off-process block columns */
2054:     PetscCall(PetscMalloc4(a->nbs, &dest[0], seq[1]->nbs, &dest[1], a->mbs, &nnz[0], a->mbs, &nnz[1]));
2055:     for (PetscInt i = 0; i < a->nbs; ++i) dest[0][idx[1][i * bs] / bs - a->cstartbs] = a->cstartbs + i;
2056:     PetscCall(PetscSFBcastBegin(a->Mvctx, MPIU_INT, dest[0], dest[1], MPI_REPLACE));
2057:     for (PetscInt i = 0; i < a->mbs; ++i) {
2058:       PetscInt r = idx[0][i * bs] / bs - a->rstartbs;

2060:       for (PetscInt k = 0; k < 2; ++k) {
2061:         nnz[k][i] = seq[k]->i[r + 1] - seq[k]->i[r];
2062:         maxnz     = PetscMax(maxnz, nnz[k][i]);
2063:       }
2064:     }
2065:     PetscCall(MatCreate(comm, B));
2066:     PetscCall(PetscLayoutDestroy(&(*B)->rmap));
2067:     PetscCall(PetscLayoutDestroy(&(*B)->cmap));
2068:     PetscCall(PetscLayoutCreateFromRanges(comm, A->rmap->range, PETSC_COPY_VALUES, bs, &(*B)->rmap));
2069:     PetscCall(PetscLayoutCreateFromRanges(comm, A->cmap->range, PETSC_COPY_VALUES, bs, &(*B)->cmap));
2070:     PetscCall(MatSetType(*B, MATMPIBAIJ));
2071:     PetscCall(MatSetOption(*B, MAT_STRUCTURE_ONLY, A->structure_only));
2072:     PetscCall(MatMPIBAIJSetPreallocation(*B, bs, 0, nnz[0], 0, nnz[1]));
2073:     PetscCall(MatSetOption(*B, MAT_ROW_ORIENTED, PETSC_FALSE));
2074:     PetscCall(PetscSFBcastEnd(a->Mvctx, MPIU_INT, dest[0], dest[1], MPI_REPLACE));
2075:     PetscCall(PetscMalloc1(maxnz, &cols));
2076:     for (PetscInt i = 0; i < a->mbs; ++i) {
2077:       PetscInt r = idx[0][i * bs] / bs - a->rstartbs, row = a->rstartbs + i;

2079:       for (PetscInt k = 0; k < 2; ++k) {
2080:         PetscInt start = seq[k]->i[r], n = nnz[k][i];

2082:         if (n == 0) continue;
2083:         for (PetscInt j = 0; j < n; ++j) cols[j] = dest[k][seq[k]->j[start + j]];
2084:         PetscUseTypeMethod(*B, setvaluesblocked, 1, &row, n, cols, A->structure_only == PETSC_TRUE ? NULL : seq[k]->a + (PetscCount)start * a->bs2, INSERT_VALUES);
2085:       }
2086:     }
2087:     (*B)->nooffprocentries = PETSC_TRUE;
2088:     PetscCall(MatAssemblyBegin(*B, MAT_FINAL_ASSEMBLY));
2089:     PetscCall(MatAssemblyEnd(*B, MAT_FINAL_ASSEMBLY));
2090:     (*B)->nooffprocentries = PETSC_FALSE;
2091:     PetscCall(PetscFree(cols));
2092:     PetscCall(PetscFree4(dest[0], dest[1], nnz[0], nnz[1]));
2093:   }
2094:   for (PetscInt k = 0; k < 2; ++k) PetscCall(ISRestoreIndices(is[k], &idx[k]));
2095:   if (local == PETSC_TRUE) PetscFunctionReturn(PETSC_SUCCESS);

2097:   /* make a collective version of 'rowp' */
2098:   PetscCall(PetscObjectGetComm((PetscObject)rowp, &pcomm));
2099:   if (pcomm == comm) {
2100:     crowp = rowp;
2101:   } else {
2102:     PetscCall(ISGetSize(rowp, &nrows));
2103:     PetscCall(ISGetIndices(rowp, &rows));
2104:     PetscCall(ISCreateGeneral(comm, nrows, rows, PETSC_COPY_VALUES, &crowp));
2105:     PetscCall(ISRestoreIndices(rowp, &rows));
2106:   }
2107:   PetscCall(ISSetPermutation(crowp));
2108:   /* make a local version of 'colp' */
2109:   PetscCall(PetscObjectGetComm((PetscObject)colp, &pcomm));
2110:   PetscCallMPI(MPI_Comm_size(pcomm, &size));
2111:   if (size == 1) {
2112:     lcolp = colp;
2113:   } else {
2114:     PetscCall(ISAllGather(colp, &lcolp));
2115:   }
2116:   PetscCall(ISSetPermutation(lcolp));
2117:   /* now we just get the submatrix */
2118:   PetscCall(MatGetLocalSize(A, NULL, &clocal_size));
2119:   PetscCall(MatCreateSubMatrix_MPIBAIJ_Private(A, crowp, lcolp, clocal_size, MAT_INITIAL_MATRIX, B, PETSC_FALSE));
2120:   /* clean up */
2121:   if (pcomm != comm) PetscCall(ISDestroy(&crowp));
2122:   if (size > 1) PetscCall(ISDestroy(&lcolp));
2123:   PetscFunctionReturn(PETSC_SUCCESS);
2124: }

2126: static PetscErrorCode MatGetGhosts_MPIBAIJ(Mat mat, PetscInt *nghosts, const PetscInt *ghosts[])
2127: {
2128:   Mat_MPIBAIJ *baij = (Mat_MPIBAIJ *)mat->data;
2129:   Mat_SeqBAIJ *B    = (Mat_SeqBAIJ *)baij->B->data;

2131:   PetscFunctionBegin;
2132:   if (nghosts) *nghosts = B->nbs;
2133:   if (ghosts) *ghosts = baij->garray;
2134:   PetscFunctionReturn(PETSC_SUCCESS);
2135: }

2137: static PetscErrorCode MatGetSeqNonzeroStructure_MPIBAIJ(Mat A, Mat *newmat)
2138: {
2139:   Mat          B;
2140:   Mat_MPIBAIJ *a  = (Mat_MPIBAIJ *)A->data;
2141:   Mat_SeqBAIJ *ad = (Mat_SeqBAIJ *)a->A->data, *bd = (Mat_SeqBAIJ *)a->B->data;
2142:   Mat_SeqAIJ  *b;
2143:   PetscMPIInt  size, rank, *recvcounts = NULL, *displs = NULL;
2144:   PetscInt     sendcount, i, *rstarts = A->rmap->range, n, cnt, j, bs = A->rmap->bs;
2145:   PetscInt     m, *garray = a->garray, *lens, *jsendbuf, *a_jsendbuf, *b_jsendbuf;

2147:   PetscFunctionBegin;
2148:   PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)A), &size));
2149:   PetscCallMPI(MPI_Comm_rank(PetscObjectComm((PetscObject)A), &rank));

2151:   /*   Tell every processor the number of nonzeros per row  */
2152:   PetscCall(PetscMalloc1(A->rmap->N / bs, &lens));
2153:   for (i = A->rmap->rstart / bs; i < A->rmap->rend / bs; i++) lens[i] = ad->i[i - A->rmap->rstart / bs + 1] - ad->i[i - A->rmap->rstart / bs] + bd->i[i - A->rmap->rstart / bs + 1] - bd->i[i - A->rmap->rstart / bs];
2154:   PetscCall(PetscMalloc1(2 * size, &recvcounts));
2155:   displs = recvcounts + size;
2156:   for (i = 0; i < size; i++) {
2157:     PetscCall(PetscMPIIntCast(A->rmap->range[i + 1] / bs - A->rmap->range[i] / bs, &recvcounts[i]));
2158:     PetscCall(PetscMPIIntCast(A->rmap->range[i] / bs, &displs[i]));
2159:   }
2160:   PetscCallMPI(MPI_Allgatherv(MPI_IN_PLACE, 0, MPI_DATATYPE_NULL, lens, recvcounts, displs, MPIU_INT, PetscObjectComm((PetscObject)A)));
2161:   /* Create the sequential matrix of the same type as the local block diagonal  */
2162:   PetscCall(MatCreate(PETSC_COMM_SELF, &B));
2163:   PetscCall(MatSetSizes(B, A->rmap->N / bs, A->cmap->N / bs, PETSC_DETERMINE, PETSC_DETERMINE));
2164:   PetscCall(MatSetType(B, MATSEQAIJ));
2165:   PetscCall(MatSetOption(B, MAT_STRUCTURE_ONLY, PETSC_TRUE));
2166:   PetscCall(MatSeqAIJSetPreallocation(B, 0, lens));
2167:   b = (Mat_SeqAIJ *)B->data;

2169:   /*     Copy my part of matrix column indices over  */
2170:   sendcount  = ad->nz + bd->nz;
2171:   jsendbuf   = b->j + b->i[rstarts[rank] / bs];
2172:   a_jsendbuf = ad->j;
2173:   b_jsendbuf = bd->j;
2174:   n          = A->rmap->rend / bs - A->rmap->rstart / bs;
2175:   cnt        = 0;
2176:   for (i = 0; i < n; i++) {
2177:     /* put in lower diagonal portion */
2178:     m = bd->i[i + 1] - bd->i[i];
2179:     while (m > 0) {
2180:       /* is it above diagonal (in bd (compressed) numbering) */
2181:       if (garray[*b_jsendbuf] > A->rmap->rstart / bs + i) break;
2182:       jsendbuf[cnt++] = garray[*b_jsendbuf++];
2183:       m--;
2184:     }

2186:     /* put in diagonal portion */
2187:     for (j = ad->i[i]; j < ad->i[i + 1]; j++) jsendbuf[cnt++] = A->rmap->rstart / bs + *a_jsendbuf++;

2189:     /* put in upper diagonal portion */
2190:     while (m-- > 0) jsendbuf[cnt++] = garray[*b_jsendbuf++];
2191:   }
2192:   PetscCheck(cnt == sendcount, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Corrupted PETSc matrix: nz given %" PetscInt_FMT " actual nz %" PetscInt_FMT, sendcount, cnt);

2194:   /*  Gather all column indices to all processors  */
2195:   for (i = 0; i < size; i++) {
2196:     recvcounts[i] = 0;
2197:     for (j = A->rmap->range[i] / bs; j < A->rmap->range[i + 1] / bs; j++) recvcounts[i] += lens[j];
2198:   }
2199:   displs[0] = 0;
2200:   for (i = 1; i < size; i++) displs[i] = displs[i - 1] + recvcounts[i - 1];
2201:   PetscCallMPI(MPI_Allgatherv(MPI_IN_PLACE, 0, MPI_DATATYPE_NULL, b->j, recvcounts, displs, MPIU_INT, PetscObjectComm((PetscObject)A)));
2202:   /*  Assemble the matrix into usable form (note numerical values not yet set)  */
2203:   /* set the b->ilen (length of each row) values */
2204:   PetscCall(PetscArraycpy(b->ilen, lens, A->rmap->N / bs));
2205:   /* set the b->i indices */
2206:   b->i[0] = 0;
2207:   for (i = 1; i <= A->rmap->N / bs; i++) b->i[i] = b->i[i - 1] + lens[i - 1];
2208:   PetscCall(PetscFree(lens));
2209:   PetscCall(MatAssemblyBegin(B, MAT_FINAL_ASSEMBLY));
2210:   PetscCall(MatAssemblyEnd(B, MAT_FINAL_ASSEMBLY));
2211:   PetscCall(PetscFree(recvcounts));

2213:   PetscCall(MatPropagateSymmetryOptions(A, B));
2214:   *newmat = B;
2215:   PetscFunctionReturn(PETSC_SUCCESS);
2216: }

2218: static PetscErrorCode MatSOR_MPIBAIJ(Mat matin, Vec bb, PetscReal omega, MatSORType flag, PetscReal fshift, PetscInt its, PetscInt lits, Vec xx)
2219: {
2220:   Mat_MPIBAIJ *mat = (Mat_MPIBAIJ *)matin->data;
2221:   Vec          bb1 = NULL;

2223:   PetscFunctionBegin;
2224:   if (flag == SOR_APPLY_UPPER) {
2225:     PetscUseTypeMethod(mat->A, sor, bb, omega, flag, fshift, lits, 1, xx);
2226:     PetscFunctionReturn(PETSC_SUCCESS);
2227:   }

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

2231:   if ((flag & SOR_LOCAL_SYMMETRIC_SWEEP) == SOR_LOCAL_SYMMETRIC_SWEEP) {
2232:     if (flag & SOR_ZERO_INITIAL_GUESS) {
2233:       PetscUseTypeMethod(mat->A, sor, bb, omega, flag, fshift, lits, 1, xx);
2234:       its--;
2235:     }

2237:     while (its--) {
2238:       PetscCall(VecScatterBegin(mat->Mvctx, xx, mat->lvec, INSERT_VALUES, SCATTER_FORWARD));
2239:       PetscCall(VecScatterEnd(mat->Mvctx, xx, mat->lvec, INSERT_VALUES, SCATTER_FORWARD));

2241:       /* update rhs: bb1 = bb - B*x */
2242:       PetscCall(VecScale(mat->lvec, -1.0));
2243:       PetscUseTypeMethod(mat->B, multadd, mat->lvec, bb, bb1);

2245:       /* local sweep */
2246:       PetscUseTypeMethod(mat->A, sor, bb1, omega, SOR_SYMMETRIC_SWEEP, fshift, lits, 1, xx);
2247:     }
2248:   } else if (flag & SOR_LOCAL_FORWARD_SWEEP) {
2249:     if (flag & SOR_ZERO_INITIAL_GUESS) {
2250:       PetscUseTypeMethod(mat->A, sor, bb, omega, flag, fshift, lits, 1, xx);
2251:       its--;
2252:     }
2253:     while (its--) {
2254:       PetscCall(VecScatterBegin(mat->Mvctx, xx, mat->lvec, INSERT_VALUES, SCATTER_FORWARD));
2255:       PetscCall(VecScatterEnd(mat->Mvctx, xx, mat->lvec, INSERT_VALUES, SCATTER_FORWARD));

2257:       /* update rhs: bb1 = bb - B*x */
2258:       PetscCall(VecScale(mat->lvec, -1.0));
2259:       PetscUseTypeMethod(mat->B, multadd, mat->lvec, bb, bb1);

2261:       /* local sweep */
2262:       PetscUseTypeMethod(mat->A, sor, bb1, omega, SOR_FORWARD_SWEEP, fshift, lits, 1, xx);
2263:     }
2264:   } else if (flag & SOR_LOCAL_BACKWARD_SWEEP) {
2265:     if (flag & SOR_ZERO_INITIAL_GUESS) {
2266:       PetscUseTypeMethod(mat->A, sor, bb, omega, flag, fshift, lits, 1, xx);
2267:       its--;
2268:     }
2269:     while (its--) {
2270:       PetscCall(VecScatterBegin(mat->Mvctx, xx, mat->lvec, INSERT_VALUES, SCATTER_FORWARD));
2271:       PetscCall(VecScatterEnd(mat->Mvctx, xx, mat->lvec, INSERT_VALUES, SCATTER_FORWARD));

2273:       /* update rhs: bb1 = bb - B*x */
2274:       PetscCall(VecScale(mat->lvec, -1.0));
2275:       PetscUseTypeMethod(mat->B, multadd, mat->lvec, bb, bb1);

2277:       /* local sweep */
2278:       PetscUseTypeMethod(mat->A, sor, bb1, omega, SOR_BACKWARD_SWEEP, fshift, lits, 1, xx);
2279:     }
2280:   } else SETERRQ(PetscObjectComm((PetscObject)matin), PETSC_ERR_SUP, "Parallel version of SOR requested not supported");

2282:   PetscCall(VecDestroy(&bb1));
2283:   PetscFunctionReturn(PETSC_SUCCESS);
2284: }

2286: static PetscErrorCode MatGetColumnReductions_MPIBAIJ(Mat A, PetscInt type, PetscReal *reductions)
2287: {
2288:   Mat_MPIBAIJ *aij = (Mat_MPIBAIJ *)A->data;
2289:   PetscInt     m, N, i, *garray = aij->garray;
2290:   PetscInt     ib, jb, bs = A->rmap->bs;
2291:   Mat_SeqBAIJ *a_aij = (Mat_SeqBAIJ *)aij->A->data;
2292:   MatScalar   *a_val = a_aij->a;
2293:   Mat_SeqBAIJ *b_aij = (Mat_SeqBAIJ *)aij->B->data;
2294:   MatScalar   *b_val = b_aij->a;

2296:   PetscFunctionBegin;
2297:   PetscCall(MatGetSize(A, &m, &N));
2298:   PetscCall(PetscArrayzero(reductions, N));
2299:   if (type == NORM_2) {
2300:     for (i = a_aij->i[0]; i < a_aij->i[aij->A->rmap->n / bs]; i++) {
2301:       for (jb = 0; jb < bs; jb++) {
2302:         for (ib = 0; ib < bs; ib++) {
2303:           reductions[A->cmap->rstart + a_aij->j[i] * bs + jb] += PetscAbsScalar(*a_val * *a_val);
2304:           a_val++;
2305:         }
2306:       }
2307:     }
2308:     for (i = b_aij->i[0]; i < b_aij->i[aij->B->rmap->n / bs]; i++) {
2309:       for (jb = 0; jb < bs; jb++) {
2310:         for (ib = 0; ib < bs; ib++) {
2311:           reductions[garray[b_aij->j[i]] * bs + jb] += PetscAbsScalar(*b_val * *b_val);
2312:           b_val++;
2313:         }
2314:       }
2315:     }
2316:   } else if (type == NORM_1) {
2317:     for (i = a_aij->i[0]; i < a_aij->i[aij->A->rmap->n / bs]; i++) {
2318:       for (jb = 0; jb < bs; jb++) {
2319:         for (ib = 0; ib < bs; ib++) {
2320:           reductions[A->cmap->rstart + a_aij->j[i] * bs + jb] += PetscAbsScalar(*a_val);
2321:           a_val++;
2322:         }
2323:       }
2324:     }
2325:     for (i = b_aij->i[0]; i < b_aij->i[aij->B->rmap->n / bs]; i++) {
2326:       for (jb = 0; jb < bs; jb++) {
2327:         for (ib = 0; ib < bs; ib++) {
2328:           reductions[garray[b_aij->j[i]] * bs + jb] += PetscAbsScalar(*b_val);
2329:           b_val++;
2330:         }
2331:       }
2332:     }
2333:   } else if (type == NORM_INFINITY) {
2334:     for (i = a_aij->i[0]; i < a_aij->i[aij->A->rmap->n / bs]; i++) {
2335:       for (jb = 0; jb < bs; jb++) {
2336:         for (ib = 0; ib < bs; ib++) {
2337:           PetscInt col    = A->cmap->rstart + a_aij->j[i] * bs + jb;
2338:           reductions[col] = PetscMax(PetscAbsScalar(*a_val), reductions[col]);
2339:           a_val++;
2340:         }
2341:       }
2342:     }
2343:     for (i = b_aij->i[0]; i < b_aij->i[aij->B->rmap->n / bs]; i++) {
2344:       for (jb = 0; jb < bs; jb++) {
2345:         for (ib = 0; ib < bs; ib++) {
2346:           PetscInt col    = garray[b_aij->j[i]] * bs + jb;
2347:           reductions[col] = PetscMax(PetscAbsScalar(*b_val), reductions[col]);
2348:           b_val++;
2349:         }
2350:       }
2351:     }
2352:   } else if (type == REDUCTION_SUM_REALPART || type == REDUCTION_MEAN_REALPART) {
2353:     for (i = a_aij->i[0]; i < a_aij->i[aij->A->rmap->n / bs]; i++) {
2354:       for (jb = 0; jb < bs; jb++) {
2355:         for (ib = 0; ib < bs; ib++) {
2356:           reductions[A->cmap->rstart + a_aij->j[i] * bs + jb] += PetscRealPart(*a_val);
2357:           a_val++;
2358:         }
2359:       }
2360:     }
2361:     for (i = b_aij->i[0]; i < b_aij->i[aij->B->rmap->n / bs]; i++) {
2362:       for (jb = 0; jb < bs; jb++) {
2363:         for (ib = 0; ib < bs; ib++) {
2364:           reductions[garray[b_aij->j[i]] * bs + jb] += PetscRealPart(*b_val);
2365:           b_val++;
2366:         }
2367:       }
2368:     }
2369:   } else {
2370:     PetscCheck(type == REDUCTION_SUM_IMAGINARYPART || type == REDUCTION_MEAN_IMAGINARYPART, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_WRONG, "Unknown reduction type");
2371:     for (i = a_aij->i[0]; i < a_aij->i[aij->A->rmap->n / bs]; i++) {
2372:       for (jb = 0; jb < bs; jb++) {
2373:         for (ib = 0; ib < bs; ib++) {
2374:           reductions[A->cmap->rstart + a_aij->j[i] * bs + jb] += PetscImaginaryPart(*a_val);
2375:           a_val++;
2376:         }
2377:       }
2378:     }
2379:     for (i = b_aij->i[0]; i < b_aij->i[aij->B->rmap->n / bs]; i++) {
2380:       for (jb = 0; jb < bs; jb++) {
2381:         for (ib = 0; ib < bs; ib++) {
2382:           reductions[garray[b_aij->j[i]] * bs + jb] += PetscImaginaryPart(*b_val);
2383:           b_val++;
2384:         }
2385:       }
2386:     }
2387:   }
2388:   PetscCallMPI(MPIU_Allreduce(MPI_IN_PLACE, reductions, N, MPIU_REAL, type == NORM_INFINITY ? MPIU_MAX : MPIU_SUM, PetscObjectComm((PetscObject)A)));
2389:   if (type == NORM_2) {
2390:     for (i = 0; i < N; i++) reductions[i] = PetscSqrtReal(reductions[i]);
2391:   } else if (type == REDUCTION_MEAN_REALPART || type == REDUCTION_MEAN_IMAGINARYPART) {
2392:     for (i = 0; i < N; i++) reductions[i] /= m;
2393:   }
2394:   PetscFunctionReturn(PETSC_SUCCESS);
2395: }

2397: static PetscErrorCode MatInvertBlockDiagonal_MPIBAIJ(Mat A, const PetscScalar **values)
2398: {
2399:   Mat_MPIBAIJ *a = (Mat_MPIBAIJ *)A->data;

2401:   PetscFunctionBegin;
2402:   PetscCall(MatInvertBlockDiagonal(a->A, values));
2403:   A->factorerrortype             = a->A->factorerrortype;
2404:   A->factorerror_zeropivot_value = a->A->factorerror_zeropivot_value;
2405:   A->factorerror_zeropivot_row   = a->A->factorerror_zeropivot_row;
2406:   PetscFunctionReturn(PETSC_SUCCESS);
2407: }

2409: static PetscErrorCode MatShift_MPIBAIJ(Mat Y, PetscScalar a)
2410: {
2411:   Mat_MPIBAIJ *maij = (Mat_MPIBAIJ *)Y->data;
2412:   Mat_SeqBAIJ *aij  = (Mat_SeqBAIJ *)maij->A->data;

2414:   PetscFunctionBegin;
2415:   if (!Y->preallocated) {
2416:     PetscCall(MatMPIBAIJSetPreallocation(Y, Y->rmap->bs, 1, NULL, 0, NULL));
2417:   } else if (!aij->nz) {
2418:     PetscInt nonew = aij->nonew;
2419:     PetscCall(MatSeqBAIJSetPreallocation(maij->A, Y->rmap->bs, 1, NULL));
2420:     aij->nonew = nonew;
2421:   }
2422:   PetscCall(MatShift_Basic(Y, a));
2423:   PetscFunctionReturn(PETSC_SUCCESS);
2424: }

2426: static PetscErrorCode MatGetDiagonalBlock_MPIBAIJ(Mat A, Mat *a)
2427: {
2428:   PetscFunctionBegin;
2429:   *a = ((Mat_MPIBAIJ *)A->data)->A;
2430:   PetscFunctionReturn(PETSC_SUCCESS);
2431: }

2433: static PetscErrorCode MatEliminateZeros_MPIBAIJ(Mat A, PetscBool keep)
2434: {
2435:   Mat_MPIBAIJ *a = (Mat_MPIBAIJ *)A->data;

2437:   PetscFunctionBegin;
2438:   PetscCall(MatEliminateZeros_SeqBAIJ(a->A, keep));        // possibly keep zero diagonal coefficients
2439:   PetscCall(MatEliminateZeros_SeqBAIJ(a->B, PETSC_FALSE)); // never keep zero diagonal coefficients
2440:   PetscFunctionReturn(PETSC_SUCCESS);
2441: }

2443: static struct _MatOps MatOps_Values = {MatSetValues_MPIBAIJ,
2444:                                        MatGetRow_MPIBAIJ,
2445:                                        MatRestoreRow_MPIBAIJ,
2446:                                        MatMult_MPIBAIJ,
2447:                                        /* 4*/ MatMultAdd_MPIBAIJ,
2448:                                        MatMultTranspose_MPIBAIJ,
2449:                                        MatMultTransposeAdd_MPIBAIJ,
2450:                                        NULL,
2451:                                        NULL,
2452:                                        NULL,
2453:                                        /*10*/ NULL,
2454:                                        NULL,
2455:                                        NULL,
2456:                                        MatSOR_MPIBAIJ,
2457:                                        MatTranspose_MPIBAIJ,
2458:                                        /*15*/ MatGetInfo_MPIBAIJ,
2459:                                        MatEqual_MPIBAIJ,
2460:                                        MatGetDiagonal_MPIBAIJ,
2461:                                        MatDiagonalScale_MPIBAIJ,
2462:                                        MatNorm_MPIBAIJ,
2463:                                        /*20*/ MatAssemblyBegin_MPIBAIJ,
2464:                                        MatAssemblyEnd_MPIBAIJ,
2465:                                        MatSetOption_MPIBAIJ,
2466:                                        MatZeroEntries_MPIBAIJ,
2467:                                        /*24*/ MatZeroRows_MPIBAIJ,
2468:                                        NULL,
2469:                                        NULL,
2470:                                        NULL,
2471:                                        NULL,
2472:                                        /*29*/ MatSetUp_MPI_Hash,
2473:                                        NULL,
2474:                                        NULL,
2475:                                        MatGetDiagonalBlock_MPIBAIJ,
2476:                                        NULL,
2477:                                        /*34*/ MatDuplicate_MPIBAIJ,
2478:                                        NULL,
2479:                                        NULL,
2480:                                        NULL,
2481:                                        NULL,
2482:                                        /*39*/ MatAXPY_MPIBAIJ,
2483:                                        MatCreateSubMatrices_MPIBAIJ,
2484:                                        MatIncreaseOverlap_MPIBAIJ,
2485:                                        MatGetValues_MPIBAIJ,
2486:                                        MatCopy_MPIBAIJ,
2487:                                        /*44*/ NULL,
2488:                                        MatScale_MPIBAIJ,
2489:                                        MatShift_MPIBAIJ,
2490:                                        NULL,
2491:                                        MatZeroRowsColumns_MPIBAIJ,
2492:                                        /*49*/ NULL,
2493:                                        NULL,
2494:                                        NULL,
2495:                                        NULL,
2496:                                        NULL,
2497:                                        /*54*/ MatFDColoringCreate_MPIXAIJ,
2498:                                        NULL,
2499:                                        MatSetUnfactored_MPIBAIJ,
2500:                                        MatPermute_MPIBAIJ,
2501:                                        MatSetValuesBlocked_MPIBAIJ,
2502:                                        /*59*/ MatCreateSubMatrix_MPIBAIJ,
2503:                                        MatDestroy_MPIBAIJ,
2504:                                        MatView_MPIBAIJ,
2505:                                        NULL,
2506:                                        NULL,
2507:                                        /*64*/ NULL,
2508:                                        NULL,
2509:                                        NULL,
2510:                                        NULL,
2511:                                        MatGetRowMaxAbs_MPIBAIJ,
2512:                                        /*69*/ NULL,
2513:                                        NULL,
2514:                                        NULL,
2515:                                        MatFDColoringApply_BAIJ,
2516:                                        NULL,
2517:                                        /*74*/ NULL,
2518:                                        NULL,
2519:                                        NULL,
2520:                                        NULL,
2521:                                        MatLoad_MPIBAIJ,
2522:                                        /*79*/ NULL,
2523:                                        NULL,
2524:                                        NULL,
2525:                                        NULL,
2526:                                        NULL,
2527:                                        /*84*/ NULL,
2528:                                        NULL,
2529:                                        NULL,
2530:                                        NULL,
2531:                                        NULL,
2532:                                        /*89*/ NULL,
2533:                                        NULL,
2534:                                        NULL,
2535:                                        NULL,
2536:                                        MatConjugate_MPIBAIJ,
2537:                                        /*94*/ NULL,
2538:                                        NULL,
2539:                                        MatRealPart_MPIBAIJ,
2540:                                        MatImaginaryPart_MPIBAIJ,
2541:                                        NULL,
2542:                                        /*99*/ NULL,
2543:                                        NULL,
2544:                                        NULL,
2545:                                        NULL,
2546:                                        NULL,
2547:                                        /*104*/ MatGetSeqNonzeroStructure_MPIBAIJ,
2548:                                        NULL,
2549:                                        MatGetGhosts_MPIBAIJ,
2550:                                        NULL,
2551:                                        NULL,
2552:                                        /*109*/ NULL,
2553:                                        NULL,
2554:                                        NULL,
2555:                                        NULL,
2556:                                        MatGetMultiProcBlock_MPIBAIJ,
2557:                                        /*114*/ NULL,
2558:                                        MatGetColumnReductions_MPIBAIJ,
2559:                                        MatInvertBlockDiagonal_MPIBAIJ,
2560:                                        NULL,
2561:                                        NULL,
2562:                                        /*119*/ NULL,
2563:                                        NULL,
2564:                                        NULL,
2565:                                        NULL,
2566:                                        NULL,
2567:                                        /*124*/ NULL,
2568:                                        MatSetBlockSizes_Default,
2569:                                        NULL,
2570:                                        MatFDColoringSetUp_MPIXAIJ,
2571:                                        NULL,
2572:                                        /*129*/ MatCreateMPIMatConcatenateSeqMat_MPIBAIJ,
2573:                                        NULL,
2574:                                        NULL,
2575:                                        NULL,
2576:                                        NULL,
2577:                                        /*134*/ NULL,
2578:                                        MatEliminateZeros_MPIBAIJ,
2579:                                        MatGetRowSumAbs_MPIBAIJ,
2580:                                        NULL,
2581:                                        NULL,
2582:                                        /*139*/ NULL,
2583:                                        MatCopyHashToXAIJ_MPI_Hash,
2584:                                        NULL,
2585:                                        NULL,
2586:                                        NULL,
2587:                                        /*144*/ NULL,
2588:                                        NULL,
2589:                                        NULL,
2590:                                        NULL};

2592: PETSC_INTERN PetscErrorCode MatConvert_MPIBAIJ_MPISBAIJ(Mat, MatType, MatReuse, Mat *);
2593: PETSC_INTERN PetscErrorCode MatConvert_XAIJ_IS(Mat, MatType, MatReuse, Mat *);

2595: static PetscErrorCode MatMPIBAIJSetPreallocationCSR_MPIBAIJ(Mat B, PetscInt bs, const PetscInt ii[], const PetscInt jj[], const PetscScalar V[])
2596: {
2597:   PetscInt        m, rstart, cstart, cend;
2598:   PetscInt        i, j, dlen, olen, nz, nz_max = 0, *d_nnz = NULL, *o_nnz = NULL;
2599:   const PetscInt *JJ          = NULL;
2600:   PetscScalar    *values      = NULL;
2601:   PetscBool       roworiented = ((Mat_MPIBAIJ *)B->data)->roworiented;
2602:   PetscBool       nooffprocentries;

2604:   PetscFunctionBegin;
2605:   PetscCall(PetscLayoutSetBlockSize(B->rmap, bs));
2606:   PetscCall(PetscLayoutSetBlockSize(B->cmap, bs));
2607:   PetscCall(PetscLayoutSetUp(B->rmap));
2608:   PetscCall(PetscLayoutSetUp(B->cmap));
2609:   PetscCall(PetscLayoutGetBlockSize(B->rmap, &bs));
2610:   m      = B->rmap->n / bs;
2611:   rstart = B->rmap->rstart / bs;
2612:   cstart = B->cmap->rstart / bs;
2613:   cend   = B->cmap->rend / bs;

2615:   PetscCheck(!ii[0], PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "ii[0] must be 0 but it is %" PetscInt_FMT, ii[0]);
2616:   PetscCall(PetscMalloc2(m, &d_nnz, m, &o_nnz));
2617:   for (i = 0; i < m; i++) {
2618:     nz = ii[i + 1] - ii[i];
2619:     PetscCheck(nz >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Local row %" PetscInt_FMT " has a negative number of columns %" PetscInt_FMT, i, nz);
2620:     nz_max = PetscMax(nz_max, nz);
2621:     dlen   = 0;
2622:     olen   = 0;
2623:     JJ     = jj + ii[i];
2624:     for (j = 0; j < nz; j++) {
2625:       if (*JJ < cstart || *JJ >= cend) olen++;
2626:       else dlen++;
2627:       JJ++;
2628:     }
2629:     d_nnz[i] = dlen;
2630:     o_nnz[i] = olen;
2631:   }
2632:   PetscCall(MatMPIBAIJSetPreallocation(B, bs, 0, d_nnz, 0, o_nnz));
2633:   PetscCall(PetscFree2(d_nnz, o_nnz));

2635:   values = (PetscScalar *)V;
2636:   if (!values) PetscCall(PetscCalloc1(bs * bs * nz_max, &values));
2637:   for (i = 0; i < m; i++) {
2638:     PetscInt        row   = i + rstart;
2639:     PetscInt        ncols = ii[i + 1] - ii[i];
2640:     const PetscInt *icols = jj + ii[i];
2641:     if (bs == 1 || !roworiented) { /* block ordering matches the non-nested layout of MatSetValues so we can insert entire rows */
2642:       const PetscScalar *svals = values + (V ? (bs * bs * ii[i]) : 0);
2643:       PetscCall(MatSetValuesBlocked_MPIBAIJ(B, 1, &row, ncols, icols, svals, INSERT_VALUES));
2644:     } else { /* block ordering does not match so we can only insert one block at a time. */
2645:       PetscInt j;
2646:       for (j = 0; j < ncols; j++) {
2647:         const PetscScalar *svals = values + (V ? (bs * bs * (ii[i] + j)) : 0);
2648:         PetscCall(MatSetValuesBlocked_MPIBAIJ(B, 1, &row, 1, &icols[j], svals, INSERT_VALUES));
2649:       }
2650:     }
2651:   }

2653:   if (!V) PetscCall(PetscFree(values));
2654:   nooffprocentries    = B->nooffprocentries;
2655:   B->nooffprocentries = PETSC_TRUE;
2656:   PetscCall(MatAssemblyBegin(B, MAT_FINAL_ASSEMBLY));
2657:   PetscCall(MatAssemblyEnd(B, MAT_FINAL_ASSEMBLY));
2658:   B->nooffprocentries = nooffprocentries;

2660:   PetscCall(MatSetOption(B, MAT_NEW_NONZERO_LOCATION_ERR, PETSC_TRUE));
2661:   PetscFunctionReturn(PETSC_SUCCESS);
2662: }

2664: /*@
2665:   MatMPIBAIJSetPreallocationCSR - Creates a sparse parallel matrix in `MATBAIJ` format using the given nonzero structure and (optional) numerical values

2667:   Collective

2669:   Input Parameters:
2670: + B  - the matrix
2671: . bs - the block size
2672: . i  - the indices into `j` for the start of each local row (starts with zero)
2673: . j  - the column indices for each local row (starts with zero) these must be sorted for each row
2674: - v  - optional values in the matrix, use `NULL` if not provided

2676:   Level: advanced

2678:   Notes:
2679:   The `i`, `j`, and `v` arrays ARE copied by this routine into the internal format used by PETSc;
2680:   thus you CANNOT change the matrix entries by changing the values of `v` after you have
2681:   called this routine.

2683:   The order of the entries in values is specified by the `MatOption` `MAT_ROW_ORIENTED`.  For example, C programs
2684:   may want to use the default `MAT_ROW_ORIENTED` with value `PETSC_TRUE` and use an array v[nnz][bs][bs] where the second index is
2685:   over rows within a block and the last index is over columns within a block row.  Fortran programs will likely set
2686:   `MAT_ROW_ORIENTED` with value `PETSC_FALSE` and use a Fortran array v(bs,bs,nnz) in which the first index is over rows within a
2687:   block column and the second index is over columns within a block.

2689:   Though this routine has Preallocation() in the name it also sets the exact nonzero locations of the matrix entries and usually the numerical values as well

2691: .seealso: `Mat`, `MatCreate()`, `MatCreateSeqAIJ()`, `MatSetValues()`, `MatMPIBAIJSetPreallocation()`, `MatCreateAIJ()`, `MATMPIAIJ`, `MatCreateMPIBAIJWithArrays()`, `MATMPIBAIJ`
2692: @*/
2693: PetscErrorCode MatMPIBAIJSetPreallocationCSR(Mat B, PetscInt bs, const PetscInt i[], const PetscInt j[], const PetscScalar v[])
2694: {
2695:   PetscFunctionBegin;
2699:   PetscTryMethod(B, "MatMPIBAIJSetPreallocationCSR_C", (Mat, PetscInt, const PetscInt[], const PetscInt[], const PetscScalar[]), (B, bs, i, j, v));
2700:   PetscFunctionReturn(PETSC_SUCCESS);
2701: }

2703: PetscErrorCode MatMPIBAIJSetPreallocation_MPIBAIJ(Mat B, PetscInt bs, PetscInt d_nz, const PetscInt *d_nnz, PetscInt o_nz, const PetscInt *o_nnz)
2704: {
2705:   Mat_MPIBAIJ *b = (Mat_MPIBAIJ *)B->data;
2706:   PetscInt     i;
2707:   PetscMPIInt  size;

2709:   PetscFunctionBegin;
2710:   if (B->hash_active) {
2711:     B->ops[0]      = b->cops;
2712:     B->hash_active = PETSC_FALSE;
2713:   }
2714:   if (!B->preallocated) PetscCall(MatStashCreate_Private(PetscObjectComm((PetscObject)B), bs, &B->bstash));
2715:   PetscCall(MatSetBlockSize(B, bs));
2716:   PetscCall(PetscLayoutSetUp(B->rmap));
2717:   PetscCall(PetscLayoutSetUp(B->cmap));
2718:   PetscCall(PetscLayoutGetBlockSize(B->rmap, &bs));

2720:   if (d_nnz) {
2721:     for (i = 0; i < B->rmap->n / bs; i++) PetscCheck(d_nnz[i] >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "d_nnz cannot be less than -1: local row %" PetscInt_FMT " value %" PetscInt_FMT, i, d_nnz[i]);
2722:   }
2723:   if (o_nnz) {
2724:     for (i = 0; i < B->rmap->n / bs; i++) PetscCheck(o_nnz[i] >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "o_nnz cannot be less than -1: local row %" PetscInt_FMT " value %" PetscInt_FMT, i, o_nnz[i]);
2725:   }

2727:   b->bs2 = bs * bs;
2728:   b->mbs = B->rmap->n / bs;
2729:   b->nbs = B->cmap->n / bs;
2730:   b->Mbs = B->rmap->N / bs;
2731:   b->Nbs = B->cmap->N / bs;

2733:   for (i = 0; i <= b->size; i++) b->rangebs[i] = B->rmap->range[i] / bs;
2734:   b->rstartbs = B->rmap->rstart / bs;
2735:   b->rendbs   = B->rmap->rend / bs;
2736:   b->cstartbs = B->cmap->rstart / bs;
2737:   b->cendbs   = B->cmap->rend / bs;

2739: #if PetscDefined(USE_CTABLE)
2740:   PetscCall(PetscHMapIDestroy(&b->colmap));
2741: #else
2742:   PetscCall(PetscFree(b->colmap));
2743: #endif
2744:   PetscCall(PetscFree(b->garray));
2745:   PetscCall(VecDestroy(&b->lvec));
2746:   PetscCall(VecScatterDestroy(&b->Mvctx));

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

2750:   MatSeqXAIJGetOptions_Private(b->B);
2751:   PetscCall(MatDestroy(&b->B));
2752:   PetscCall(MatCreate(PETSC_COMM_SELF, &b->B));
2753:   PetscCall(MatSetSizes(b->B, B->rmap->n, size > 1 ? B->cmap->N : 0, B->rmap->n, size > 1 ? B->cmap->N : 0));
2754:   PetscCall(MatSetType(b->B, MATSEQBAIJ));
2755:   MatSeqXAIJRestoreOptions_Private(b->B);
2756:   PetscCall(MatSetOption(b->B, MAT_STRUCTURE_ONLY, B->structure_only));

2758:   MatSeqXAIJGetOptions_Private(b->A);
2759:   PetscCall(MatDestroy(&b->A));
2760:   PetscCall(MatCreate(PETSC_COMM_SELF, &b->A));
2761:   PetscCall(MatSetSizes(b->A, B->rmap->n, B->cmap->n, B->rmap->n, B->cmap->n));
2762:   PetscCall(MatSetType(b->A, MATSEQBAIJ));
2763:   MatSeqXAIJRestoreOptions_Private(b->A);
2764:   PetscCall(MatSetOption(b->A, MAT_STRUCTURE_ONLY, B->structure_only));

2766:   PetscCall(MatSeqBAIJSetPreallocation(b->A, bs, d_nz, d_nnz));
2767:   PetscCall(MatSeqBAIJSetPreallocation(b->B, bs, o_nz, o_nnz));
2768:   B->preallocated  = PETSC_TRUE;
2769:   B->was_assembled = PETSC_FALSE;
2770:   B->assembled     = PETSC_FALSE;
2771:   PetscFunctionReturn(PETSC_SUCCESS);
2772: }

2774: extern PetscErrorCode MatDiagonalScaleLocal_MPIBAIJ(Mat, Vec);
2775: extern PetscErrorCode MatSetHashTableFactor_MPIBAIJ(Mat, PetscReal);

2777: PETSC_INTERN PetscErrorCode MatConvert_MPIBAIJ_MPIAdj(Mat B, MatType newtype, MatReuse reuse, Mat *adj)
2778: {
2779:   Mat_MPIBAIJ    *b = (Mat_MPIBAIJ *)B->data;
2780:   Mat_SeqBAIJ    *d = (Mat_SeqBAIJ *)b->A->data, *o = (Mat_SeqBAIJ *)b->B->data;
2781:   PetscInt        M = B->rmap->n / B->rmap->bs, i, *ii, *jj, cnt, j, k, rstart = B->rmap->rstart / B->rmap->bs;
2782:   const PetscInt *id = d->i, *jd = d->j, *io = o->i, *jo = o->j, *garray = b->garray;

2784:   PetscFunctionBegin;
2785:   PetscCall(PetscMalloc1(M + 1, &ii));
2786:   ii[0] = 0;
2787:   for (i = 0; i < M; i++) {
2788:     PetscCheck((id[i + 1] - id[i]) >= 0, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Indices wrong %" PetscInt_FMT " %" PetscInt_FMT " %" PetscInt_FMT, i, id[i], id[i + 1]);
2789:     PetscCheck((io[i + 1] - io[i]) >= 0, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Indices wrong %" PetscInt_FMT " %" PetscInt_FMT " %" PetscInt_FMT, i, io[i], io[i + 1]);
2790:     ii[i + 1] = ii[i] + id[i + 1] - id[i] + io[i + 1] - io[i];
2791:     /* remove one from count of matrix has diagonal */
2792:     for (j = id[i]; j < id[i + 1]; j++) {
2793:       if (jd[j] == i) {
2794:         ii[i + 1]--;
2795:         break;
2796:       }
2797:     }
2798:   }
2799:   PetscCall(PetscMalloc1(ii[M], &jj));
2800:   cnt = 0;
2801:   for (i = 0; i < M; i++) {
2802:     for (j = io[i]; j < io[i + 1]; j++) {
2803:       if (garray[jo[j]] > rstart) break;
2804:       jj[cnt++] = garray[jo[j]];
2805:     }
2806:     for (k = id[i]; k < id[i + 1]; k++) {
2807:       if (jd[k] != i) jj[cnt++] = rstart + jd[k];
2808:     }
2809:     for (; j < io[i + 1]; j++) jj[cnt++] = garray[jo[j]];
2810:   }
2811:   PetscCall(MatCreateMPIAdj(PetscObjectComm((PetscObject)B), M, B->cmap->N / B->rmap->bs, ii, jj, NULL, adj));
2812:   PetscFunctionReturn(PETSC_SUCCESS);
2813: }

2815: #include <../src/mat/impls/aij/mpi/mpiaij.h>

2817: PETSC_INTERN PetscErrorCode MatConvert_SeqBAIJ_SeqAIJ(Mat, MatType, MatReuse, Mat *);

2819: PETSC_INTERN PetscErrorCode MatConvert_MPIBAIJ_MPIAIJ(Mat A, MatType newtype, MatReuse reuse, Mat *newmat)
2820: {
2821:   Mat_MPIBAIJ *a = (Mat_MPIBAIJ *)A->data;
2822:   Mat_MPIAIJ  *b;
2823:   Mat          B;
2824:   PetscBool    nooffprocentries;

2826:   PetscFunctionBegin;
2827:   PetscCheck(A->assembled, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "Matrix must be assembled");

2829:   if (reuse == MAT_REUSE_MATRIX) {
2830:     B = *newmat;
2831:   } else {
2832:     PetscCall(MatCreate(PetscObjectComm((PetscObject)A), &B));
2833:     PetscCall(MatSetType(B, MATMPIAIJ));
2834:     PetscCall(MatSetSizes(B, A->rmap->n, A->cmap->n, A->rmap->N, A->cmap->N));
2835:     PetscCall(MatSetBlockSizes(B, A->rmap->bs, A->cmap->bs));
2836:     PetscCall(MatSeqAIJSetPreallocation(B, 0, NULL));
2837:     PetscCall(MatMPIAIJSetPreallocation(B, 0, NULL, 0, NULL));
2838:   }
2839:   b = (Mat_MPIAIJ *)B->data;

2841:   if (reuse == MAT_REUSE_MATRIX) {
2842:     PetscCall(MatConvert_SeqBAIJ_SeqAIJ(a->A, MATSEQAIJ, MAT_REUSE_MATRIX, &b->A));
2843:     PetscCall(MatConvert_SeqBAIJ_SeqAIJ(a->B, MATSEQAIJ, MAT_REUSE_MATRIX, &b->B));
2844:   } else {
2845:     PetscInt   *garray = a->garray;
2846:     Mat_SeqAIJ *bB;
2847:     PetscInt    bs, nnz;
2848:     PetscCall(MatDestroy(&b->A));
2849:     PetscCall(MatDestroy(&b->B));
2850:     /* just clear out the data structure */
2851:     PetscCall(MatDisAssemble_MPIAIJ(B, PETSC_FALSE));
2852:     PetscCall(MatConvert_SeqBAIJ_SeqAIJ(a->A, MATSEQAIJ, MAT_INITIAL_MATRIX, &b->A));
2853:     PetscCall(MatConvert_SeqBAIJ_SeqAIJ(a->B, MATSEQAIJ, MAT_INITIAL_MATRIX, &b->B));

2855:     /* Global numbering for b->B columns */
2856:     bB  = (Mat_SeqAIJ *)b->B->data;
2857:     bs  = A->rmap->bs;
2858:     nnz = bB->i[A->rmap->n];
2859:     for (PetscInt k = 0; k < nnz; k++) {
2860:       PetscInt bj = bB->j[k] / bs;
2861:       PetscInt br = bB->j[k] % bs;
2862:       bB->j[k]    = garray[bj] * bs + br;
2863:     }
2864:   }
2865:   nooffprocentries    = B->nooffprocentries;
2866:   B->nooffprocentries = PETSC_TRUE;
2867:   PetscCall(MatAssemblyBegin(B, MAT_FINAL_ASSEMBLY));
2868:   PetscCall(MatAssemblyEnd(B, MAT_FINAL_ASSEMBLY));
2869:   B->nooffprocentries = nooffprocentries;

2871:   if (reuse == MAT_INPLACE_MATRIX) {
2872:     PetscCall(MatHeaderReplace(A, &B));
2873:   } else {
2874:     *newmat = B;
2875:   }
2876:   PetscFunctionReturn(PETSC_SUCCESS);
2877: }

2879: /*MC
2880:    MATMPIBAIJ - MATMPIBAIJ = "mpibaij" - A matrix type to be used for distributed block sparse matrices.

2882:    Options Database Keys:
2883: + -mat_type mpibaij              - sets the matrix type to `MATMPIBAIJ` during a call to `MatSetFromOptions()`
2884: . -mat_block_size bs             - set the blocksize used to store the matrix
2885: . -mat_baij_mult_version version - indicate the version of the matrix-vector product to use  (0 often indicates using BLAS)
2886: - -mat_use_hash_table fact       - set hash table factor

2888:    Level: beginner

2890:    Notes:
2891:     Call `MatSetOption(A, MAT_STRUCTURE_ONLY, PETSC_TRUE)` before preallocation or `MatSetUp()` to store only the nonzero pattern.
2892:     The assembled matrix has no numerical value array. Row and column indices supplied during insertion are retained, while numerical values are ignored.
2893:     Such matrices can be used for structural operations, but not for numerical operations.

2895: .seealso: `Mat`, `MATBAIJ`, `MATSEQBAIJ`, `MatCreateBAIJ`
2896: M*/

2898: static PetscErrorCode MatMPIBAIJ_MPIDenseDestroy(PetscCtxRt ctx)
2899: {
2900:   MPIAIJ_MPIDense *data = *(MPIAIJ_MPIDense **)ctx;

2902:   PetscFunctionBegin;
2903:   PetscCall(MatDestroy(&data->source));
2904:   PetscCall(MatMPIDenseScatterDestroy_Private(data));
2905:   PetscCall(PetscFree(data));
2906:   PetscFunctionReturn(PETSC_SUCCESS);
2907: }

2909: static PetscErrorCode MatMatMultNumeric_MPIBAIJ_MPIDense(Mat A, Mat B, Mat C)
2910: {
2911:   Mat_MPIBAIJ     *baij   = (Mat_MPIBAIJ *)A->data;
2912:   Mat_MPIDense    *bdense = (Mat_MPIDense *)B->data;
2913:   Mat_MPIDense    *cdense = (Mat_MPIDense *)C->data;
2914:   Mat              workB;
2915:   MPIAIJ_MPIDense *data;
2916:   PetscInt         bs;

2918:   PetscFunctionBegin;
2919:   MatCheckProduct(C, 3);
2920:   PetscCheck(C->product->data, PetscObjectComm((PetscObject)C), PETSC_ERR_PLIB, "Product data empty");
2921:   data = (MPIAIJ_MPIDense *)C->product->data;
2922:   PetscCall(MatGetBlockSize(A, &bs));
2923:   PetscCall(MatMPIDenseScatterUpdateLDA_Private(baij->Mvctx, bs, B, C, data));
2924:   if (!cdense->A->product) {
2925:     PetscCall(MatProductCreateWithMat(baij->A, bdense->A, NULL, cdense->A));
2926:     PetscCall(MatProductSetType(cdense->A, MATPRODUCT_AB));
2927:     PetscCall(MatProductSetFromOptions(cdense->A));
2928:     PetscCall(MatProductSymbolic(cdense->A));
2929:   } else PetscCall(MatProductReplaceMats(baij->A, bdense->A, NULL, cdense->A));
2930:   PetscCall(MatProductNumeric(cdense->A));

2932:   if (data->workB->cmap->n == B->cmap->N) {
2933:     workB = data->workB;
2934:     PetscCall(MatMPIDenseScatter_Private(baij->Mvctx, baij->B->cmap->n, bs, workB, data, B, C));
2935:     if (data->source) {
2936:       PetscCall(MatProductReplaceMats(baij->B, workB, NULL, data->source));
2937:       PetscCall(MatProductNumeric(data->source));
2938:       PetscCall(MatAXPY(cdense->A, 1.0, data->source, SAME_NONZERO_PATTERN));
2939:     }
2940:   } else {
2941:     Mat           Bb, Cb, workC;
2942:     Mat_MPIDense *cbdense;
2943:     PetscInt      BN = B->cmap->N, n = data->workB->cmap->n, cols;

2945:     PetscCheck(n > 0, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Column batch size must be positive");
2946:     for (PetscInt i = 0; i < BN; i += n) {
2947:       cols  = PetscMin(n, BN - i);
2948:       workB = data->workB;
2949:       workC = data->source;
2950:       if (cols != n) {
2951:         PetscCall(MatDenseGetSubMatrix(data->workB, PETSC_DECIDE, PETSC_DECIDE, 0, cols, &workB));
2952:         if (workC) PetscCall(MatDenseGetSubMatrix(data->source, PETSC_DECIDE, PETSC_DECIDE, 0, cols, &workC));
2953:       }
2954:       PetscCall(MatDenseGetSubMatrix(B, PETSC_DECIDE, PETSC_DECIDE, i, i + cols, &Bb));
2955:       PetscCall(MatDenseGetSubMatrix(C, PETSC_DECIDE, PETSC_DECIDE, i, i + cols, &Cb));
2956:       PetscCall(MatMPIDenseScatter_Private(baij->Mvctx, baij->B->cmap->n, bs, workB, data, Bb, C));
2957:       if (workC) {
2958:         cbdense = (Mat_MPIDense *)Cb->data;
2959:         PetscCall(MatProductReplaceMats(baij->B, workB, NULL, workC));
2960:         PetscCall(MatProductNumeric(workC));
2961:         PetscCall(MatAXPY(cbdense->A, 1.0, workC, SAME_NONZERO_PATTERN));
2962:       }
2963:       if (cols != n) {
2964:         if (workC) PetscCall(MatDenseRestoreSubMatrix(data->source, &workC));
2965:         PetscCall(MatDenseRestoreSubMatrix(data->workB, &workB));
2966:       }
2967:       PetscCall(MatDenseRestoreSubMatrix(B, &Bb));
2968:       PetscCall(MatDenseRestoreSubMatrix(C, &Cb));
2969:     }
2970:   }
2971:   PetscFunctionReturn(PETSC_SUCCESS);
2972: }

2974: static PetscErrorCode MatMatMultSymbolic_MPIBAIJ_MPIDense(Mat A, Mat B, PetscReal fill, Mat C)
2975: {
2976:   Mat_MPIBAIJ     *baij = (Mat_MPIBAIJ *)A->data;
2977:   MPIAIJ_MPIDense *data;
2978:   VecScatter       ctx = baij->Mvctx;
2979:   PetscInt         nz  = baij->B->cmap->n, bs;
2980:   PetscInt         Am = A->rmap->n, BN = B->cmap->N, Bbn, numBb;
2981:   Mat              workB1, workC1;

2983:   PetscFunctionBegin;
2984:   MatCheckProduct(C, 4);
2985:   PetscCheck(!C->product->data, PetscObjectComm((PetscObject)C), PETSC_ERR_PLIB, "Product data not empty");
2986:   PetscCall(MatDenseSetUpProduct_Private(C, A->rmap, B->cmap, B, NULL));
2987:   PetscCall(MatGetBlockSize(A, &bs));
2988:   PetscCall(PetscNew(&data));
2989:   PetscCall(MatMPIDenseScatterSetUp_Private(ctx, nz, bs, Am, B, C, data, &Bbn, &numBb));

2991:   PetscCall(MatProductClear(baij->A));
2992:   PetscCall(MatProductClear(((Mat_MPIDense *)B->data)->A));
2993:   PetscCall(MatProductClear(((Mat_MPIDense *)C->data)->A));
2994:   PetscCall(MatProductCreateWithMat(baij->A, ((Mat_MPIDense *)B->data)->A, NULL, ((Mat_MPIDense *)C->data)->A));
2995:   PetscCall(MatProductSetType(((Mat_MPIDense *)C->data)->A, MATPRODUCT_AB));
2996:   PetscCall(MatProductSetFromOptions(((Mat_MPIDense *)C->data)->A));
2997:   PetscCall(MatProductSymbolic(((Mat_MPIDense *)C->data)->A));

2999:   if (nz) {
3000:     PetscCall(MatCreateSeqDense(PETSC_COMM_SELF, Am, Bbn ? Bbn : BN, NULL, &data->source));
3001:     PetscCall(MatProductCreateWithMat(baij->B, data->workB, NULL, data->source));
3002:     PetscCall(MatProductSetType(data->source, MATPRODUCT_AB));
3003:     PetscCall(MatProductSetFromOptions(data->source));
3004:     PetscCall(MatProductSymbolic(data->source));
3005:     if (numBb && BN % Bbn) {
3006:       PetscCall(MatDenseGetSubMatrix(data->workB, PETSC_DECIDE, PETSC_DECIDE, 0, BN % Bbn, &workB1));
3007:       PetscCall(MatDenseGetSubMatrix(data->source, PETSC_DECIDE, PETSC_DECIDE, 0, BN % Bbn, &workC1));
3008:       PetscCall(MatProductCreateWithMat(baij->B, workB1, NULL, workC1));
3009:       PetscCall(MatProductSetType(workC1, MATPRODUCT_AB));
3010:       PetscCall(MatProductSetFromOptions(workC1));
3011:       PetscCall(MatProductSymbolic(workC1));
3012:       PetscCall(MatDenseRestoreSubMatrix(data->source, &workC1));
3013:       PetscCall(MatDenseRestoreSubMatrix(data->workB, &workB1));
3014:     }
3015:   }

3017:   C->product->data       = data;
3018:   C->product->destroy    = MatMPIBAIJ_MPIDenseDestroy;
3019:   C->ops->matmultnumeric = MatMatMultNumeric_MPIBAIJ_MPIDense;
3020:   PetscFunctionReturn(PETSC_SUCCESS);
3021: }

3023: PETSC_INTERN PetscErrorCode MatProductSetFromOptions_MPIBAIJ_MPIDense(Mat C)
3024: {
3025:   Mat_Product *product = C->product;

3027:   PetscFunctionBegin;
3028:   MatCheckProduct(C, 1);
3029:   if (product->type == MATPRODUCT_AB) {
3030:     C->ops->matmultsymbolic = MatMatMultSymbolic_MPIBAIJ_MPIDense;
3031:     C->ops->productsymbolic = MatProductSymbolic_AB;
3032:   }
3033:   PetscFunctionReturn(PETSC_SUCCESS);
3034: }

3036: static PetscErrorCode MatGetMultPetscSF_MPIBAIJ(Mat A, PetscSF *sf)
3037: {
3038:   Mat_MPIBAIJ *a = (Mat_MPIBAIJ *)A->data;

3040:   PetscFunctionBegin;
3041:   *sf = a->Mvctx;
3042:   PetscFunctionReturn(PETSC_SUCCESS);
3043: }

3045: PETSC_EXTERN PetscErrorCode MatCreate_MPIBAIJ(Mat B)
3046: {
3047:   Mat_MPIBAIJ *b;
3048:   PetscBool    flg = PETSC_FALSE;

3050:   PetscFunctionBegin;
3051:   PetscCall(PetscNew(&b));
3052:   B->data      = (void *)b;
3053:   B->ops[0]    = MatOps_Values;
3054:   B->assembled = PETSC_FALSE;

3056:   B->insertmode = NOT_SET_VALUES;
3057:   PetscCallMPI(MPI_Comm_rank(PetscObjectComm((PetscObject)B), &b->rank));
3058:   PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)B), &b->size));

3060:   /* build local table of row and column ownerships */
3061:   PetscCall(PetscMalloc1(b->size + 1, &b->rangebs));

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

3066:   b->donotstash  = PETSC_FALSE;
3067:   b->colmap      = NULL;
3068:   b->garray      = NULL;
3069:   b->roworiented = PETSC_TRUE;

3071:   /* stuff used in block assembly */
3072:   b->barray = NULL;

3074:   /* stuff used for matrix vector multiply */
3075:   b->lvec  = NULL;
3076:   b->Mvctx = NULL;

3078:   /* stuff for MatGetRow() */
3079:   b->rowindices   = NULL;
3080:   b->rowvalues    = NULL;
3081:   b->getrowactive = PETSC_FALSE;

3083:   /* hash table stuff */
3084:   b->ht           = NULL;
3085:   b->hd           = NULL;
3086:   b->ht_size      = 0;
3087:   b->ht_flag      = PETSC_FALSE;
3088:   b->ht_fact      = 0;
3089:   b->ht_total_ct  = 0;
3090:   b->ht_insert_ct = 0;

3092:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatConvert_mpibaij_mpiadj_C", MatConvert_MPIBAIJ_MPIAdj));
3093:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatConvert_mpibaij_mpiaij_C", MatConvert_MPIBAIJ_MPIAIJ));
3094:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatConvert_mpibaij_mpisbaij_C", MatConvert_MPIBAIJ_MPISBAIJ));
3095: #if PetscDefined(HAVE_HYPRE)
3096:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatConvert_mpibaij_hypre_C", MatConvert_AIJ_HYPRE));
3097: #endif
3098:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatStoreValues_C", MatStoreValues_MPIBAIJ));
3099:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatRetrieveValues_C", MatRetrieveValues_MPIBAIJ));
3100:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatMPIBAIJSetPreallocation_C", MatMPIBAIJSetPreallocation_MPIBAIJ));
3101:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatMPIBAIJSetPreallocationCSR_C", MatMPIBAIJSetPreallocationCSR_MPIBAIJ));
3102:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatDiagonalScaleLocal_C", MatDiagonalScaleLocal_MPIBAIJ));
3103:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatSetHashTableFactor_C", MatSetHashTableFactor_MPIBAIJ));
3104:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatConvert_mpibaij_is_C", MatConvert_XAIJ_IS));
3105:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatGetMultPetscSF_C", MatGetMultPetscSF_MPIBAIJ));
3106:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatProductSetFromOptions_mpibaij_mpidense_C", MatProductSetFromOptions_MPIBAIJ_MPIDense));
3107: #if PetscDefined(HAVE_LIBXSMM)
3108:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatConvert_mpibaij_mpibaijlibxsmm_C", MatConvert_MPIBAIJ_MPIBAIJLIBXSMM));
3109: #endif
3110:   PetscCall(PetscObjectChangeTypeName((PetscObject)B, MATMPIBAIJ));

3112:   PetscOptionsBegin(PetscObjectComm((PetscObject)B), NULL, "Options for loading MPIBAIJ matrix 1", "Mat");
3113:   PetscCall(PetscOptionsName("-mat_use_hash_table", "Use hash table to save time in constructing matrix", "MatSetOption", &flg));
3114:   if (flg) {
3115:     PetscReal fact = 1.39;
3116:     PetscCall(MatSetOption(B, MAT_USE_HASH_TABLE, PETSC_TRUE));
3117:     PetscCall(PetscOptionsReal("-mat_use_hash_table", "Use hash table factor", "MatMPIBAIJSetHashTableFactor", fact, &fact, NULL));
3118:     if (fact <= 1.0) fact = 1.39;
3119:     PetscCall(MatMPIBAIJSetHashTableFactor(B, fact));
3120:     PetscCall(PetscInfo(B, "Hash table Factor used %5.2g\n", (double)fact));
3121:   }
3122:   PetscOptionsEnd();
3123:   PetscFunctionReturn(PETSC_SUCCESS);
3124: }

3126: // PetscClangLinter pragma disable: -fdoc-section-header-unknown
3127: /*MC
3128:    MATBAIJ - MATBAIJ = "baij" - A matrix type to be used for block sparse matrices.

3130:    This matrix type is identical to `MATSEQBAIJ` when constructed with a single process communicator,
3131:    and `MATMPIBAIJ` otherwise.

3133:    Options Database Keys:
3134: . -mat_type baij - sets the matrix type to `MATBAIJ` during a call to `MatSetFromOptions()`

3136:   Level: beginner

3138:   Notes:
3139:   Call `MatSetOption(A, MAT_STRUCTURE_ONLY, PETSC_TRUE)` before preallocation or `MatSetUp()` to store only the nonzero pattern.
3140:   The assembled matrix has no numerical value array. Row and column indices supplied during insertion are retained, while numerical values are ignored.
3141:   Such matrices can be used for structural operations, but not for numerical operations.

3143: .seealso: `Mat`, `MatCreateBAIJ()`, `MATSEQBAIJ`, `MATMPIBAIJ`, `MatMPIBAIJSetPreallocation()`, `MatMPIBAIJSetPreallocationCSR()`
3144: M*/

3146: /*@
3147:   MatMPIBAIJSetPreallocation - Allocates memory for a sparse parallel matrix in `MATMPIBAIJ` format
3148:   (block compressed row).

3150:   Collective

3152:   Input Parameters:
3153: + B     - the matrix
3154: . bs    - size of block, the blocks are ALWAYS square. One can use `MatSetBlockSizes()` to set a different row and column blocksize but the row
3155:           blocksize always defines the size of the blocks. The column blocksize sets the blocksize of the vectors obtained with `MatCreateVecs()`
3156: . d_nz  - number of block nonzeros per block row in diagonal portion of local
3157:            submatrix  (same for all local rows)
3158: . d_nnz - array containing the number of block nonzeros in the various block rows
3159:            of the in diagonal portion of the local (possibly different for each block
3160:            row) or `NULL`.  If you plan to factor the matrix you must leave room for the diagonal entry and
3161:            set it even if it is zero.
3162: . o_nz  - number of block nonzeros per block row in the off-diagonal portion of local
3163:            submatrix (same for all local rows).
3164: - o_nnz - array containing the number of nonzeros in the various block rows of the
3165:            off-diagonal portion of the local submatrix (possibly different for
3166:            each block row) or `NULL`.

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

3170:   Options Database Keys:
3171: + -mat_block_size          - size of the blocks to use
3172: - -mat_use_hash_table fact - set hash table factor

3174:   Level: intermediate

3176:   Notes:
3177:   For good matrix assembly performance
3178:   the user should preallocate the matrix storage by setting the parameters
3179:   `d_nz` (or `d_nnz`) and `o_nz` (or `o_nnz`).  By setting these parameters accurately,
3180:   performance can be increased by more than a factor of 50.

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

3185:   Storage Information:
3186:   For a square global matrix we define each processor's diagonal portion
3187:   to be its local rows and the corresponding columns (a square submatrix);
3188:   each processor's off-diagonal portion encompasses the remainder of the
3189:   local matrix (a rectangular submatrix).

3191:   The user can specify preallocated storage for the diagonal part of
3192:   the local submatrix with either `d_nz` or `d_nnz` (not both).  Set
3193:   `d_nz` = `PETSC_DEFAULT` and `d_nnz` = `NULL` for PETSc to control dynamic
3194:   memory allocation.  Likewise, specify preallocated storage for the
3195:   off-diagonal part of the local submatrix with `o_nz` or `o_nnz` (not both).

3197:   Consider a processor that owns rows 3, 4 and 5 of a parallel matrix. In
3198:   the figure below we depict these three local rows and all columns (0-11).

3200: .vb
3201:            0 1 2 3 4 5 6 7 8 9 10 11
3202:           --------------------------
3203:    row 3  |o o o d d d o o o o  o  o
3204:    row 4  |o o o d d d o o o o  o  o
3205:    row 5  |o o o d d d o o o o  o  o
3206:           --------------------------
3207: .ve

3209:   Thus, any entries in the d locations are stored in the d (diagonal)
3210:   submatrix, and any entries in the o locations are stored in the
3211:   o (off-diagonal) submatrix.  Note that the d and the o submatrices are
3212:   stored simply in the `MATSEQBAIJ` format for compressed row storage.

3214:   Now `d_nz` should indicate the number of block nonzeros per row in the d matrix,
3215:   and `o_nz` should indicate the number of block nonzeros per row in the o matrix.
3216:   In general, for PDE problems in which most nonzeros are near the diagonal,
3217:   one expects `d_nz` >> `o_nz`.

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

3224: .seealso: `Mat`, `MATMPIBAIJ`, `MatCreate()`, `MatCreateSeqBAIJ()`, `MatSetValues()`, `MatCreateBAIJ()`, `MatMPIBAIJSetPreallocationCSR()`, `PetscSplitOwnership()`
3225: @*/
3226: PetscErrorCode MatMPIBAIJSetPreallocation(Mat B, PetscInt bs, PetscInt d_nz, const PetscInt d_nnz[], PetscInt o_nz, const PetscInt o_nnz[])
3227: {
3228:   PetscFunctionBegin;
3232:   PetscTryMethod(B, "MatMPIBAIJSetPreallocation_C", (Mat, PetscInt, PetscInt, const PetscInt[], PetscInt, const PetscInt[]), (B, bs, d_nz, d_nnz, o_nz, o_nnz));
3233:   PetscFunctionReturn(PETSC_SUCCESS);
3234: }

3236: // PetscClangLinter pragma disable: -fdoc-section-header-unknown
3237: /*@
3238:   MatCreateBAIJ - Creates a sparse parallel matrix in `MATBAIJ` format
3239:   (block compressed row).

3241:   Collective

3243:   Input Parameters:
3244: + comm  - MPI communicator
3245: . bs    - size of block, the blocks are ALWAYS square. One can use `MatSetBlockSizes()` to set a different row and column blocksize but the row
3246:           blocksize always defines the size of the blocks. The column blocksize sets the blocksize of the vectors obtained with `MatCreateVecs()`
3247: . m     - number of local rows (or `PETSC_DECIDE` to have calculated if M is given)
3248:           This value should be the same as the local size used in creating the
3249:           y vector for the matrix-vector product y = Ax.
3250: . n     - number of local columns (or `PETSC_DECIDE` to have calculated if N is given)
3251:           This value should be the same as the local size used in creating the
3252:           x vector for the matrix-vector product y = Ax.
3253: . M     - number of global rows (or `PETSC_DETERMINE` to have calculated if m is given)
3254: . N     - number of global columns (or `PETSC_DETERMINE` to have calculated if n is given)
3255: . d_nz  - number of nonzero blocks per block row in diagonal portion of local
3256:           submatrix  (same for all local rows)
3257: . d_nnz - array containing the number of nonzero blocks in the various block rows
3258:           of the in diagonal portion of the local (possibly different for each block
3259:           row) or NULL.  If you plan to factor the matrix you must leave room for the diagonal entry
3260:           and set it even if it is zero.
3261: . o_nz  - number of nonzero blocks per block row in the off-diagonal portion of local
3262:           submatrix (same for all local rows).
3263: - o_nnz - array containing the number of nonzero blocks in the various block rows of the
3264:           off-diagonal portion of the local submatrix (possibly different for
3265:           each block row) or NULL.

3267:   Output Parameter:
3268: . A - the matrix

3270:   Options Database Keys:
3271: + -mat_block_size          - size of the blocks to use
3272: - -mat_use_hash_table fact - set hash table factor

3274:   Level: intermediate

3276:   Notes:
3277:   It is recommended that one use `MatCreateFromOptions()` or the `MatCreate()`, `MatSetType()` and/or `MatSetFromOptions()`,
3278:   MatXXXXSetPreallocation() paradigm instead of this routine directly.
3279:   [MatXXXXSetPreallocation() is, for example, `MatSeqBAIJSetPreallocation()`]

3281:   For good matrix assembly performance
3282:   the user should preallocate the matrix storage by setting the parameters
3283:   `d_nz` (or `d_nnz`) and `o_nz` (or `o_nnz`).  By setting these parameters accurately,
3284:   performance can be increased by more than a factor of 50.

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

3288:   A nonzero block is any block that as 1 or more nonzeros in it

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

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

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

3299:   Storage Information:
3300:   For a square global matrix we define each processor's diagonal portion
3301:   to be its local rows and the corresponding columns (a square submatrix);
3302:   each processor's off-diagonal portion encompasses the remainder of the
3303:   local matrix (a rectangular submatrix).

3305:   The user can specify preallocated storage for the diagonal part of
3306:   the local submatrix with either d_nz or d_nnz (not both).  Set
3307:   `d_nz` = `PETSC_DEFAULT` and `d_nnz` = `NULL` for PETSc to control dynamic
3308:   memory allocation.  Likewise, specify preallocated storage for the
3309:   off-diagonal part of the local submatrix with `o_nz` or `o_nnz` (not both).

3311:   Consider a processor that owns rows 3, 4 and 5 of a parallel matrix. In
3312:   the figure below we depict these three local rows and all columns (0-11).

3314: .vb
3315:            0 1 2 3 4 5 6 7 8 9 10 11
3316:           --------------------------
3317:    row 3  |o o o d d d o o o o  o  o
3318:    row 4  |o o o d d d o o o o  o  o
3319:    row 5  |o o o d d d o o o o  o  o
3320:           --------------------------
3321: .ve

3323:   Thus, any entries in the d locations are stored in the d (diagonal)
3324:   submatrix, and any entries in the o locations are stored in the
3325:   o (off-diagonal) submatrix.  Note that the d and the o submatrices are
3326:   stored simply in the `MATSEQBAIJ` format for compressed row storage.

3328:   Now `d_nz` should indicate the number of block nonzeros per row in the d matrix,
3329:   and `o_nz` should indicate the number of block nonzeros per row in the o matrix.
3330:   In general, for PDE problems in which most nonzeros are near the diagonal,
3331:   one expects `d_nz` >> `o_nz`.

3333: .seealso: `Mat`, `MatCreate()`, `MatCreateSeqBAIJ()`, `MatSetValues()`, `MatMPIBAIJSetPreallocation()`, `MatMPIBAIJSetPreallocationCSR()`,
3334:           `MatGetOwnershipRange()`, `MatGetOwnershipRanges()`, `MatGetOwnershipRangeColumn()`, `MatGetOwnershipRangesColumn()`, `PetscLayout`
3335: @*/
3336: PetscErrorCode MatCreateBAIJ(MPI_Comm comm, PetscInt bs, PetscInt m, PetscInt n, PetscInt M, PetscInt N, PetscInt d_nz, const PetscInt d_nnz[], PetscInt o_nz, const PetscInt o_nnz[], Mat *A)
3337: {
3338:   PetscMPIInt size;

3340:   PetscFunctionBegin;
3341:   PetscCall(MatCreate(comm, A));
3342:   PetscCall(MatSetSizes(*A, m, n, M, N));
3343:   PetscCallMPI(MPI_Comm_size(comm, &size));
3344:   if (size > 1) {
3345:     PetscCall(MatSetType(*A, MATMPIBAIJ));
3346:     PetscCall(MatMPIBAIJSetPreallocation(*A, bs, d_nz, d_nnz, o_nz, o_nnz));
3347:   } else {
3348:     PetscCall(MatSetType(*A, MATSEQBAIJ));
3349:     PetscCall(MatSeqBAIJSetPreallocation(*A, bs, d_nz, d_nnz));
3350:   }
3351:   PetscFunctionReturn(PETSC_SUCCESS);
3352: }

3354: static PetscErrorCode MatDuplicate_MPIBAIJ(Mat matin, MatDuplicateOption cpvalues, Mat *newmat)
3355: {
3356:   Mat          mat;
3357:   Mat_MPIBAIJ *a, *oldmat = (Mat_MPIBAIJ *)matin->data;
3358:   PetscInt     len = 0;

3360:   PetscFunctionBegin;
3361:   *newmat = NULL;
3362:   PetscCall(MatCreate(PetscObjectComm((PetscObject)matin), &mat));
3363:   PetscCall(MatSetSizes(mat, matin->rmap->n, matin->cmap->n, matin->rmap->N, matin->cmap->N));
3364:   PetscCall(MatSetType(mat, ((PetscObject)matin)->type_name));
3365:   PetscCall(MatSetOption(mat, MAT_STRUCTURE_ONLY, matin->structure_only));

3367:   PetscCall(PetscLayoutReference(matin->rmap, &mat->rmap));
3368:   PetscCall(PetscLayoutReference(matin->cmap, &mat->cmap));
3369:   if (matin->hash_active) PetscCall(MatSetUp(mat));
3370:   else {
3371:     mat->factortype   = matin->factortype;
3372:     mat->preallocated = PETSC_TRUE;
3373:     mat->assembled    = PETSC_TRUE;
3374:     mat->insertmode   = NOT_SET_VALUES;

3376:     a             = (Mat_MPIBAIJ *)mat->data;
3377:     mat->rmap->bs = matin->rmap->bs;
3378:     a->bs2        = oldmat->bs2;
3379:     a->mbs        = oldmat->mbs;
3380:     a->nbs        = oldmat->nbs;
3381:     a->Mbs        = oldmat->Mbs;
3382:     a->Nbs        = oldmat->Nbs;

3384:     a->size         = oldmat->size;
3385:     a->rank         = oldmat->rank;
3386:     a->donotstash   = oldmat->donotstash;
3387:     a->roworiented  = oldmat->roworiented;
3388:     a->rowindices   = NULL;
3389:     a->rowvalues    = NULL;
3390:     a->getrowactive = PETSC_FALSE;
3391:     a->barray       = NULL;
3392:     a->rstartbs     = oldmat->rstartbs;
3393:     a->rendbs       = oldmat->rendbs;
3394:     a->cstartbs     = oldmat->cstartbs;
3395:     a->cendbs       = oldmat->cendbs;

3397:     /* hash table stuff */
3398:     a->ht           = NULL;
3399:     a->hd           = NULL;
3400:     a->ht_size      = 0;
3401:     a->ht_flag      = oldmat->ht_flag;
3402:     a->ht_fact      = oldmat->ht_fact;
3403:     a->ht_total_ct  = 0;
3404:     a->ht_insert_ct = 0;

3406:     PetscCall(PetscArraycpy(a->rangebs, oldmat->rangebs, a->size + 1));
3407:     if (oldmat->colmap) {
3408: #if PetscDefined(USE_CTABLE)
3409:       PetscCall(PetscHMapIDuplicate(oldmat->colmap, &a->colmap));
3410: #else
3411:       PetscCall(PetscMalloc1(a->Nbs, &a->colmap));
3412:       PetscCall(PetscArraycpy(a->colmap, oldmat->colmap, a->Nbs));
3413: #endif
3414:     } else a->colmap = NULL;

3416:     if (oldmat->garray && (len = ((Mat_SeqBAIJ *)oldmat->B->data)->nbs)) {
3417:       PetscCall(PetscMalloc1(len, &a->garray));
3418:       PetscCall(PetscArraycpy(a->garray, oldmat->garray, len));
3419:     } else a->garray = NULL;

3421:     PetscCall(MatStashCreate_Private(PetscObjectComm((PetscObject)matin), matin->rmap->bs, &mat->bstash));
3422:     if (oldmat->lvec) PetscCall(VecDuplicate(oldmat->lvec, &a->lvec));
3423:     if (oldmat->Mvctx) {
3424:       a->Mvctx = oldmat->Mvctx;
3425:       PetscCall(PetscObjectReference((PetscObject)oldmat->Mvctx));
3426:     }

3428:     PetscCall(MatDuplicate(oldmat->A, cpvalues, &a->A));
3429:     PetscCall(MatDuplicate(oldmat->B, cpvalues, &a->B));
3430:   }
3431:   PetscCall(PetscFunctionListDuplicate(((PetscObject)matin)->qlist, &((PetscObject)mat)->qlist));
3432:   *newmat = mat;
3433:   PetscFunctionReturn(PETSC_SUCCESS);
3434: }

3436: /* Used for both MPIBAIJ and MPISBAIJ matrices */
3437: PetscErrorCode MatLoad_MPIBAIJ_Binary(Mat mat, PetscViewer viewer)
3438: {
3439:   PetscInt     header[4], M, N, nz, bs, m, n, mbs, nbs, rows, cols, sum, i, j, k;
3440:   PetscInt    *rowidxs, *colidxs, rs, cs, ce;
3441:   PetscScalar *matvals;
3442:   PetscBool    nooffprocentries = mat->nooffprocentries;

3444:   PetscFunctionBegin;
3445:   PetscCall(PetscViewerSetUp(viewer));

3447:   /* read in matrix header */
3448:   PetscCall(PetscViewerBinaryRead(viewer, header, 4, NULL, PETSC_INT));
3449:   PetscCheck(header[0] == MAT_FILE_CLASSID, PetscObjectComm((PetscObject)viewer), PETSC_ERR_FILE_UNEXPECTED, "Not a matrix object in file");
3450:   M  = header[1];
3451:   N  = header[2];
3452:   nz = header[3];
3453:   PetscCheck(M >= 0, PetscObjectComm((PetscObject)viewer), PETSC_ERR_FILE_UNEXPECTED, "Matrix row size (%" PetscInt_FMT ") in file is negative", M);
3454:   PetscCheck(N >= 0, PetscObjectComm((PetscObject)viewer), PETSC_ERR_FILE_UNEXPECTED, "Matrix column size (%" PetscInt_FMT ") in file is negative", N);
3455:   PetscCheck(nz >= 0, PETSC_COMM_SELF, PETSC_ERR_FILE_UNEXPECTED, "Matrix stored in special format on disk, cannot load as MPIBAIJ");

3457:   /* set block sizes from the viewer's .info file */
3458:   PetscCall(MatLoad_Binary_BlockSizes(mat, viewer));
3459:   /* set local sizes if not set already */
3460:   if (mat->rmap->n < 0 && M == N) mat->rmap->n = mat->cmap->n;
3461:   if (mat->cmap->n < 0 && M == N) mat->cmap->n = mat->rmap->n;
3462:   /* set global sizes if not set already */
3463:   if (mat->rmap->N < 0) mat->rmap->N = M;
3464:   if (mat->cmap->N < 0) mat->cmap->N = N;
3465:   PetscCall(PetscLayoutSetUp(mat->rmap));
3466:   PetscCall(PetscLayoutSetUp(mat->cmap));

3468:   /* check if the matrix sizes are correct */
3469:   PetscCall(MatGetSize(mat, &rows, &cols));
3470:   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);
3471:   PetscCall(MatGetBlockSize(mat, &bs));
3472:   PetscCall(MatGetLocalSize(mat, &m, &n));
3473:   PetscCall(PetscLayoutGetRange(mat->rmap, &rs, NULL));
3474:   PetscCall(PetscLayoutGetRange(mat->cmap, &cs, &ce));
3475:   mbs = m / bs;
3476:   nbs = n / bs;

3478:   /* read in row lengths and build row indices */
3479:   PetscCall(PetscMalloc1(m + 1, &rowidxs));
3480:   PetscCall(PetscViewerBinaryReadAll(viewer, rowidxs + 1, m, PETSC_DECIDE, M, PETSC_INT));
3481:   rowidxs[0] = 0;
3482:   for (i = 0; i < m; i++) rowidxs[i + 1] += rowidxs[i];
3483:   PetscCallMPI(MPIU_Allreduce(&rowidxs[m], &sum, 1, MPIU_INT, MPI_SUM, PetscObjectComm((PetscObject)viewer)));
3484:   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);

3486:   /* read in column indices and matrix values */
3487:   PetscCall(PetscMalloc2(rowidxs[m], &colidxs, rowidxs[m], &matvals));
3488:   PetscCall(PetscViewerBinaryReadAll(viewer, colidxs, rowidxs[m], PETSC_DETERMINE, PETSC_DETERMINE, PETSC_INT));
3489:   PetscCall(PetscViewerBinaryReadAll(viewer, matvals, rowidxs[m], PETSC_DETERMINE, PETSC_DETERMINE, PETSC_SCALAR));

3491:   {                /* preallocate matrix storage */
3492:     PetscBT    bt; /* helper bit set to count diagonal nonzeros */
3493:     PetscHSetI ht; /* helper hash set to count off-diagonal nonzeros */
3494:     PetscBool  sbaij, done;
3495:     PetscInt  *d_nnz, *o_nnz;

3497:     PetscCall(PetscBTCreate(nbs, &bt));
3498:     PetscCall(PetscHSetICreate(&ht));
3499:     PetscCall(PetscCalloc2(mbs, &d_nnz, mbs, &o_nnz));
3500:     PetscCall(PetscObjectTypeCompare((PetscObject)mat, MATMPISBAIJ, &sbaij));
3501:     for (i = 0; i < mbs; i++) {
3502:       PetscCall(PetscBTMemzero(nbs, bt));
3503:       PetscCall(PetscHSetIClear(ht));
3504:       for (k = 0; k < bs; k++) {
3505:         const PetscInt row = bs * i + k;

3507:         for (j = rowidxs[row]; j < rowidxs[row + 1]; j++) {
3508:           const PetscInt col = colidxs[j];

3510:           if (!sbaij || col / bs >= rs / bs + i) {
3511:             if (col >= cs && col < ce) {
3512:               if (!PetscBTLookupSet(bt, (col - cs) / bs)) d_nnz[i]++;
3513:             } else {
3514:               PetscCall(PetscHSetIQueryAdd(ht, col / bs, &done));
3515:               if (done) o_nnz[i]++;
3516:             }
3517:           }
3518:         }
3519:       }
3520:     }
3521:     PetscCall(PetscBTDestroy(&bt));
3522:     PetscCall(PetscHSetIDestroy(&ht));
3523:     PetscCall(MatMPIBAIJSetPreallocation(mat, bs, 0, d_nnz, 0, o_nnz));
3524:     PetscCall(MatMPISBAIJSetPreallocation(mat, bs, 0, d_nnz, 0, o_nnz));
3525:     PetscCall(PetscFree2(d_nnz, o_nnz));
3526:   }

3528:   /* store matrix values */
3529:   for (i = 0; i < m; i++) {
3530:     PetscInt row = rs + i, s = rowidxs[i], e = rowidxs[i + 1];
3531:     PetscUseTypeMethod(mat, setvalues, 1, &row, e - s, colidxs + s, matvals + s, INSERT_VALUES);
3532:   }

3534:   PetscCall(PetscFree(rowidxs));
3535:   PetscCall(PetscFree2(colidxs, matvals));
3536:   mat->nooffprocentries = PETSC_TRUE;
3537:   PetscCall(MatAssemblyBegin(mat, MAT_FINAL_ASSEMBLY));
3538:   PetscCall(MatAssemblyEnd(mat, MAT_FINAL_ASSEMBLY));
3539:   mat->nooffprocentries = nooffprocentries;
3540:   PetscFunctionReturn(PETSC_SUCCESS);
3541: }

3543: PetscErrorCode MatLoad_MPIBAIJ(Mat mat, PetscViewer viewer)
3544: {
3545:   PetscBool isbinary;

3547:   PetscFunctionBegin;
3548:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERBINARY, &isbinary));
3549:   PetscCheck(isbinary, PetscObjectComm((PetscObject)viewer), PETSC_ERR_SUP, "Viewer type %s not yet supported for reading %s matrices", ((PetscObject)viewer)->type_name, ((PetscObject)mat)->type_name);
3550:   PetscCall(MatLoad_MPIBAIJ_Binary(mat, viewer));
3551:   PetscFunctionReturn(PETSC_SUCCESS);
3552: }

3554: /*@
3555:   MatMPIBAIJSetHashTableFactor - Sets the factor required to compute the size of the matrices hash table

3557:   Input Parameters:
3558: + mat  - the matrix
3559: - fact - factor

3561:   Options Database Key:
3562: . -mat_use_hash_table fact - provide the factor

3564:   Level: advanced

3566: .seealso: `Mat`, `MATMPIBAIJ`, `MatSetOption()`
3567: @*/
3568: PetscErrorCode MatMPIBAIJSetHashTableFactor(Mat mat, PetscReal fact)
3569: {
3570:   PetscFunctionBegin;
3571:   PetscTryMethod(mat, "MatSetHashTableFactor_C", (Mat, PetscReal), (mat, fact));
3572:   PetscFunctionReturn(PETSC_SUCCESS);
3573: }

3575: PetscErrorCode MatSetHashTableFactor_MPIBAIJ(Mat mat, PetscReal fact)
3576: {
3577:   Mat_MPIBAIJ *baij;

3579:   PetscFunctionBegin;
3580:   baij          = (Mat_MPIBAIJ *)mat->data;
3581:   baij->ht_fact = fact;
3582:   PetscFunctionReturn(PETSC_SUCCESS);
3583: }

3585: /*@
3586:   MatMPIBAIJGetSeqBAIJ - Get the on-process (diagonal block) and off-process (off-diagonal block) sequential matrices
3587:   that make up a `MATMPIBAIJ` or `MATMPISBAIJ` matrix, together with the local-to-global column map for the off-diagonal block.

3589:   Not Collective

3591:   Input Parameter:
3592: . A - the `MATMPIBAIJ` or `MATMPISBAIJ` matrix

3594:   Output Parameters:
3595: + Ad     - the diagonal block (`MATSEQBAIJ` or `MATSEQSBAIJ`), or `NULL` if not needed
3596: . Ao     - the off-diagonal block `MATSEQBAIJ`, or `NULL` if not needed
3597: - colmap - the local-to-global column index map for `Ao`, or `NULL` if not needed

3599:   Level: advanced

3601: .seealso: `Mat`, `MATMPIBAIJ`, `MATMPISBAIJ`, `MATSEQBAIJ`, `MATSEQSBAIJ`, `MatMPIAIJGetSeqAIJ()`
3602: @*/
3603: PetscErrorCode MatMPIBAIJGetSeqBAIJ(Mat A, Mat *Ad, Mat *Ao, const PetscInt *colmap[])
3604: {
3605:   Mat_MPIBAIJ *a = (Mat_MPIBAIJ *)A->data;
3606:   PetscBool    flg;

3608:   PetscFunctionBegin;
3609:   PetscCall(PetscObjectTypeCompareAny((PetscObject)A, &flg, MATMPIBAIJ, MATMPISBAIJ, ""));
3610:   PetscCheck(flg, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "This function requires a MATMPIBAIJ or MATMPISBAIJ matrix as input");
3611:   if (Ad) *Ad = a->A;
3612:   if (Ao) *Ao = a->B;
3613:   if (colmap) *colmap = a->garray;
3614:   PetscFunctionReturn(PETSC_SUCCESS);
3615: }

3617: /*
3618:     Special version for direct calls from Fortran (to eliminate two function call overheads
3619: */
3620: #if PetscDefined(HAVE_FORTRAN_CAPS)
3621:   #define matmpibaijsetvaluesblocked_ MATMPIBAIJSETVALUESBLOCKED
3622: #elif !PetscDefined(HAVE_FORTRAN_UNDERSCORE)
3623:   #define matmpibaijsetvaluesblocked_ matmpibaijsetvaluesblocked
3624: #endif

3626: // PetscClangLinter pragma disable: -fdoc-synopsis-matching-symbol-name
3627: /*@
3628:   MatMPIBAIJSetValuesBlocked - Direct Fortran call to replace call to `MatSetValuesBlocked()`

3630:   Collective

3632:   Input Parameters:
3633: + matin  - the matrix
3634: . min    - number of input rows
3635: . im     - input rows
3636: . nin    - number of input columns
3637: . in     - input columns
3638: . v      - numerical values input
3639: - addvin - `INSERT_VALUES` or `ADD_VALUES`

3641:   Level: advanced

3643:   Developer Notes:
3644:   This has a complete copy of `MatSetValuesBlocked_MPIBAIJ()` which is terrible code un-reuse.

3646: .seealso: `Mat`, `MatSetValuesBlocked()`
3647: @*/
3648: PETSC_EXTERN PetscErrorCode matmpibaijsetvaluesblocked_(Mat *matin, PetscInt *min, const PetscInt im[], PetscInt *nin, const PetscInt in[], const MatScalar v[], InsertMode *addvin)
3649: {
3650:   /* convert input arguments to C version */
3651:   Mat        mat = *matin;
3652:   PetscInt   m = *min, n = *nin;
3653:   InsertMode addv = *addvin;

3655:   Mat_MPIBAIJ     *baij = (Mat_MPIBAIJ *)mat->data;
3656:   const MatScalar *value;
3657:   MatScalar       *barray      = baij->barray;
3658:   PetscBool        roworiented = baij->roworiented;
3659:   PetscInt         i, j, ii, jj, row, col, rstart = baij->rstartbs;
3660:   PetscInt         rend = baij->rendbs, cstart = baij->cstartbs, stepval;
3661:   PetscInt         cend = baij->cendbs, bs = mat->rmap->bs, bs2 = baij->bs2;

3663:   PetscFunctionBegin;
3664:   /* tasks normally handled by MatSetValuesBlocked() */
3665:   if (mat->insertmode == NOT_SET_VALUES) mat->insertmode = addv;
3666:   else PetscCheck(mat->insertmode == addv, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Cannot mix add values and insert values");
3667:   PetscCheck(!mat->factortype, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
3668:   if (mat->assembled) {
3669:     mat->was_assembled = PETSC_TRUE;
3670:     mat->assembled     = PETSC_FALSE;
3671:   }
3672:   PetscCall(PetscLogEventBegin(MAT_SetValues, mat, 0, 0, 0));

3674:   if (!barray) {
3675:     PetscCall(PetscMalloc1(bs2, &barray));
3676:     baij->barray = barray;
3677:   }

3679:   if (roworiented) stepval = (n - 1) * bs;
3680:   else stepval = (m - 1) * bs;

3682:   for (i = 0; i < m; i++) {
3683:     if (im[i] < 0) continue;
3684:     PetscCheck(im[i] < baij->Mbs, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Row too large, row %" PetscInt_FMT " max %" PetscInt_FMT, im[i], baij->Mbs - 1);
3685:     if (im[i] >= rstart && im[i] < rend) {
3686:       row = im[i] - rstart;
3687:       for (j = 0; j < n; j++) {
3688:         /* If NumCol = 1 then a copy is not required */
3689:         if (roworiented && (n == 1)) {
3690:           barray = (MatScalar *)v + i * bs2;
3691:         } else if ((!roworiented) && (m == 1)) {
3692:           barray = (MatScalar *)v + j * bs2;
3693:         } else { /* Here a copy is required */
3694:           if (roworiented) {
3695:             value = v + i * (stepval + bs) * bs + j * bs;
3696:           } else {
3697:             value = v + j * (stepval + bs) * bs + i * bs;
3698:           }
3699:           for (ii = 0; ii < bs; ii++, value += stepval) {
3700:             for (jj = 0; jj < bs; jj++) *barray++ = *value++;
3701:           }
3702:           barray -= bs2;
3703:         }

3705:         if (in[j] >= cstart && in[j] < cend) {
3706:           col = in[j] - cstart;
3707:           PetscCall(MatSetValuesBlocked_SeqBAIJ_Inlined(baij->A, row, col, barray, addv, im[i], in[j]));
3708:         } else if (in[j] < 0) {
3709:           continue;
3710:         } else {
3711:           PetscCheck(in[j] < baij->Nbs, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Column too large, col %" PetscInt_FMT " max %" PetscInt_FMT, in[j], baij->Nbs - 1);
3712:           if (mat->was_assembled) {
3713:             if (!baij->colmap) PetscCall(MatCreateColmap_MPIBAIJ_Private(mat));

3715: #if PetscDefined(USE_CTABLE)
3716:             if (PetscDefined(USE_DEBUG)) {
3717:               PetscInt data;
3718:               PetscCall(PetscHMapIGetWithDefault(baij->colmap, in[j] + 1, 0, &data));
3719:               PetscCheck((data - 1) % bs == 0, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Incorrect colmap");
3720:             }
3721: #else
3722:             if (PetscDefined(USE_DEBUG)) PetscCheck((baij->colmap[in[j]] - 1) % bs == 0, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Incorrect colmap");
3723: #endif
3724: #if PetscDefined(USE_CTABLE)
3725:             PetscCall(PetscHMapIGetWithDefault(baij->colmap, in[j] + 1, 0, &col));
3726:             col = (col - 1) / bs;
3727: #else
3728:             col = (baij->colmap[in[j]] - 1) / bs;
3729: #endif
3730:             if (col < 0 && !((Mat_SeqBAIJ *)baij->A->data)->nonew) {
3731:               PetscCall(MatDisAssemble_MPIBAIJ(mat));
3732:               col = in[j];
3733:             }
3734:           } else col = in[j];
3735:           PetscCall(MatSetValuesBlocked_SeqBAIJ_Inlined(baij->B, row, col, barray, addv, im[i], in[j]));
3736:         }
3737:       }
3738:     } else {
3739:       if (!baij->donotstash) {
3740:         if (roworiented) {
3741:           PetscCall(MatStashValuesRowBlocked_Private(&mat->bstash, im[i], n, in, v, m, n, i));
3742:         } else {
3743:           PetscCall(MatStashValuesColBlocked_Private(&mat->bstash, im[i], n, in, v, m, n, i));
3744:         }
3745:       }
3746:     }
3747:   }

3749:   /* task normally handled by MatSetValuesBlocked() */
3750:   PetscCall(PetscLogEventEnd(MAT_SetValues, mat, 0, 0, 0));
3751:   PetscFunctionReturn(PETSC_SUCCESS);
3752: }

3754: /*@
3755:   MatCreateMPIBAIJWithArrays - creates a `MATMPIBAIJ` matrix using arrays that contain in standard block CSR format for the local rows.

3757:   Collective

3759:   Input Parameters:
3760: + comm - MPI communicator
3761: . bs   - the block size, only a block size of 1 is supported
3762: . m    - number of local rows (Cannot be `PETSC_DECIDE`)
3763: . n    - This value should be the same as the local size used in creating the
3764:          x vector for the matrix-vector product $y = Ax$. (or `PETSC_DECIDE` to have
3765:          calculated if `N` is given) For square matrices `n` is almost always `m`.
3766: . M    - number of global rows (or `PETSC_DETERMINE` to have calculated if `m` is given)
3767: . N    - number of global columns (or `PETSC_DETERMINE` to have calculated if `n` is given)
3768: . i    - row indices; that is i[0] = 0, i[row] = i[row-1] + number of block elements in that rowth block row of the matrix
3769: . j    - column indices
3770: - a    - matrix values

3772:   Output Parameter:
3773: . mat - the matrix

3775:   Level: intermediate

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

3782:   The order of the entries in values is the same as the block compressed sparse row storage format; that is, it is
3783:   the same as a three dimensional array in Fortran values(bs,bs,nnz) that contains the first column of the first
3784:   block, followed by the second column of the first block etc etc.  That is, the blocks are contiguous in memory
3785:   with column-major ordering within blocks.

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

3789: .seealso: `Mat`, `MatCreate()`, `MatCreateSeqAIJ()`, `MatSetValues()`, `MatMPIAIJSetPreallocation()`, `MatMPIAIJSetPreallocationCSR()`,
3790:           `MATMPIAIJ`, `MatCreateAIJ()`, `MatCreateMPIAIJWithSplitArrays()`
3791: @*/
3792: PetscErrorCode MatCreateMPIBAIJWithArrays(MPI_Comm comm, PetscInt bs, PetscInt m, PetscInt n, PetscInt M, PetscInt N, const PetscInt i[], const PetscInt j[], const PetscScalar a[], Mat *mat)
3793: {
3794:   PetscFunctionBegin;
3795:   PetscCheck(!i[0], PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "i (row indices) must start with 0");
3796:   PetscCheck(m >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "local number of rows (m) cannot be PETSC_DECIDE, or negative");
3797:   PetscCall(MatCreate(comm, mat));
3798:   PetscCall(MatSetSizes(*mat, m, n, M, N));
3799:   PetscCall(MatSetType(*mat, MATMPIBAIJ));
3800:   PetscCall(MatSetBlockSize(*mat, bs));
3801:   PetscCall(MatSetUp(*mat));
3802:   PetscCall(MatSetOption(*mat, MAT_ROW_ORIENTED, PETSC_FALSE));
3803:   PetscCall(MatMPIBAIJSetPreallocationCSR(*mat, bs, i, j, a));
3804:   PetscCall(MatSetOption(*mat, MAT_ROW_ORIENTED, PETSC_TRUE));
3805:   PetscFunctionReturn(PETSC_SUCCESS);
3806: }

3808: PetscErrorCode MatCreateMPIMatConcatenateSeqMat_MPIBAIJ(MPI_Comm comm, Mat inmat, PetscInt n, MatReuse scall, Mat *outmat)
3809: {
3810:   PetscInt     m, N, i, rstart, nnz, Ii, bs, cbs;
3811:   PetscInt    *indx;
3812:   PetscScalar *values;

3814:   PetscFunctionBegin;
3815:   PetscCall(MatGetSize(inmat, &m, &N));
3816:   if (scall == MAT_INITIAL_MATRIX) { /* symbolic phase */
3817:     Mat_SeqBAIJ *a = (Mat_SeqBAIJ *)inmat->data;
3818:     PetscInt    *dnz, *onz, mbs, Nbs, nbs;
3819:     PetscInt    *bindx, rmax = a->rmax, j;
3820:     PetscMPIInt  rank, size;

3822:     PetscCall(MatGetBlockSizes(inmat, &bs, &cbs));
3823:     mbs = m / bs;
3824:     Nbs = N / cbs;
3825:     if (n == PETSC_DECIDE) PetscCall(PetscSplitOwnershipBlock(comm, cbs, &n, &N));
3826:     nbs = n / cbs;

3828:     PetscCall(PetscMalloc1(rmax, &bindx));
3829:     MatPreallocateBegin(comm, mbs, nbs, dnz, onz); /* inline function, output __end and __rstart are used below */

3831:     PetscCallMPI(MPI_Comm_rank(comm, &rank));
3832:     PetscCallMPI(MPI_Comm_size(comm, &size));
3833:     if (rank == size - 1) {
3834:       /* Check sum(nbs) = Nbs */
3835:       PetscCheck(__end == Nbs, PETSC_COMM_SELF, PETSC_ERR_ARG_INCOMP, "Sum of local block columns %" PetscInt_FMT " != global block columns %" PetscInt_FMT, __end, Nbs);
3836:     }

3838:     rstart = __rstart; /* block rstart of *outmat; see inline function MatPreallocateBegin */
3839:     for (i = 0; i < mbs; i++) {
3840:       PetscCall(MatGetRow_SeqBAIJ(inmat, i * bs, &nnz, &indx, NULL)); /* non-blocked nnz and indx */
3841:       nnz = nnz / bs;
3842:       for (j = 0; j < nnz; j++) bindx[j] = indx[j * bs] / bs;
3843:       PetscCall(MatPreallocateSet(i + rstart, nnz, bindx, dnz, onz));
3844:       PetscCall(MatRestoreRow_SeqBAIJ(inmat, i * bs, &nnz, &indx, NULL));
3845:     }
3846:     PetscCall(PetscFree(bindx));

3848:     PetscCall(MatCreate(comm, outmat));
3849:     PetscCall(MatSetSizes(*outmat, m, n, PETSC_DETERMINE, PETSC_DETERMINE));
3850:     PetscCall(MatSetBlockSizes(*outmat, bs, cbs));
3851:     PetscCall(MatSetType(*outmat, MATBAIJ));
3852:     PetscCall(MatSeqBAIJSetPreallocation(*outmat, bs, 0, dnz));
3853:     PetscCall(MatMPIBAIJSetPreallocation(*outmat, bs, 0, dnz, 0, onz));
3854:     MatPreallocateEnd(dnz, onz);
3855:     PetscCall(MatSetOption(*outmat, MAT_NO_OFF_PROC_ENTRIES, PETSC_TRUE));
3856:   }

3858:   /* numeric phase */
3859:   PetscCall(MatGetBlockSizes(inmat, &bs, &cbs));
3860:   PetscCall(MatGetOwnershipRange(*outmat, &rstart, NULL));

3862:   for (i = 0; i < m; i++) {
3863:     PetscCall(MatGetRow_SeqBAIJ(inmat, i, &nnz, &indx, &values));
3864:     Ii = i + rstart;
3865:     PetscCall(MatSetValues(*outmat, 1, &Ii, nnz, indx, values, INSERT_VALUES));
3866:     PetscCall(MatRestoreRow_SeqBAIJ(inmat, i, &nnz, &indx, &values));
3867:   }
3868:   PetscCall(MatAssemblyBegin(*outmat, MAT_FINAL_ASSEMBLY));
3869:   PetscCall(MatAssemblyEnd(*outmat, MAT_FINAL_ASSEMBLY));
3870:   PetscFunctionReturn(PETSC_SUCCESS);
3871: }