Actual source code: mpiov.c

  1: /*
  2:    Routines to compute overlapping regions of a parallel MPI matrix
  3:   and to find submatrices that were shared across processors.
  4: */
  5: #include <../src/mat/impls/aij/seq/aij.h>
  6: #include <../src/mat/impls/aij/mpi/mpiaij.h>
  7: #include <petscsf.h>

  9: static PetscErrorCode MatIncreaseOverlap_MPIAIJ_Once(Mat, PetscInt, IS *);
 10: static PetscErrorCode MatIncreaseOverlap_MPIAIJ_Local(Mat, PetscInt, PetscBT *, PetscInt *, PetscInt **, PetscHMapI *);
 11: static PetscErrorCode MatIncreaseOverlap_MPIAIJ_Receive(Mat, PetscInt, PetscInt **, PetscInt **, PetscInt *);
 12: extern PetscErrorCode MatGetRow_MPIAIJ(Mat, PetscInt, PetscInt *, PetscInt **, PetscScalar **);
 13: extern PetscErrorCode MatRestoreRow_MPIAIJ(Mat, PetscInt, PetscInt *, PetscInt **, PetscScalar **);

 15: static PetscErrorCode MatIncreaseOverlap_MPIAIJ_Once_Scalable(Mat, PetscInt, IS *);
 16: static PetscErrorCode MatIncreaseOverlap_MPIAIJ_Local_Scalable(Mat, PetscInt, IS *);
 17: static PetscErrorCode MatIncreaseOverlap_MPIAIJ_Send_Scalable(Mat, PetscInt, PetscMPIInt, PetscMPIInt *, PetscInt *, PetscInt *, PetscInt **, PetscInt **);
 18: static PetscErrorCode MatIncreaseOverlap_MPIAIJ_Receive_Scalable(Mat, PetscInt, IS *, PetscInt, PetscInt *);

 20: /*
 21:    Takes a general IS and builds a block version of the IS that contains the given IS plus any needed values to fill out the blocks

 23:    The entire MatIncreaseOverlap_MPIAIJ() stack could be rewritten to respect the bs and it would offer higher performance but
 24:    that is a very major recoding job.

 26:    Possible scalability issues with this routine because it allocates space proportional to Nmax-Nmin
 27: */
 28: static PetscErrorCode ISAdjustForBlockSize(PetscInt bs, PetscInt imax, IS is[])
 29: {
 30:   PetscFunctionBegin;
 31:   for (PetscInt i = 0; i < imax; i++) {
 32:     if (!is[i]) break;
 33:     PetscInt        n = 0, N, Nmax, Nmin;
 34:     const PetscInt *idx;
 35:     PetscInt       *nidx = NULL;
 36:     MPI_Comm        comm;
 37:     PetscBT         bt;

 39:     PetscCall(ISGetLocalSize(is[i], &N));
 40:     if (N > 0) { /* Nmax and Nmin are garbage for empty IS */
 41:       PetscCall(ISGetIndices(is[i], &idx));
 42:       PetscCall(ISGetMinMax(is[i], &Nmin, &Nmax));
 43:       Nmin = Nmin / bs;
 44:       Nmax = Nmax / bs;
 45:       PetscCall(PetscBTCreate(Nmax - Nmin, &bt));
 46:       for (PetscInt j = 0; j < N; j++) {
 47:         if (!PetscBTLookupSet(bt, idx[j] / bs - Nmin)) n++;
 48:       }
 49:       PetscCall(PetscMalloc1(n, &nidx));
 50:       n = 0;
 51:       PetscCall(PetscBTMemzero(Nmax - Nmin, bt));
 52:       for (PetscInt j = 0; j < N; j++) {
 53:         if (!PetscBTLookupSet(bt, idx[j] / bs - Nmin)) nidx[n++] = idx[j] / bs;
 54:       }
 55:       PetscCall(PetscBTDestroy(&bt));
 56:       PetscCall(ISRestoreIndices(is[i], &idx));
 57:     }
 58:     PetscCall(PetscObjectGetComm((PetscObject)is[i], &comm));
 59:     PetscCall(ISDestroy(is + i));
 60:     PetscCall(ISCreateBlock(comm, bs, n, nidx, PETSC_OWN_POINTER, is + i));
 61:   }
 62:   PetscFunctionReturn(PETSC_SUCCESS);
 63: }

 65: PetscErrorCode MatIncreaseOverlap_MPIAIJ(Mat C, PetscInt imax, IS is[], PetscInt ov)
 66: {
 67:   PetscInt i;

 69:   PetscFunctionBegin;
 70:   PetscCheck(ov >= 0, PetscObjectComm((PetscObject)C), PETSC_ERR_ARG_OUTOFRANGE, "Negative overlap specified");
 71:   for (i = 0; i < ov; ++i) PetscCall(MatIncreaseOverlap_MPIAIJ_Once(C, imax, is));
 72:   if (C->rmap->bs > 1 && C->rmap->bs == C->cmap->bs) PetscCall(ISAdjustForBlockSize(C->rmap->bs, imax, is));
 73:   PetscFunctionReturn(PETSC_SUCCESS);
 74: }

 76: PetscErrorCode MatIncreaseOverlap_MPIAIJ_Scalable(Mat C, PetscInt imax, IS is[], PetscInt ov)
 77: {
 78:   PetscInt i;

 80:   PetscFunctionBegin;
 81:   PetscCheck(ov >= 0, PetscObjectComm((PetscObject)C), PETSC_ERR_ARG_OUTOFRANGE, "Negative overlap specified");
 82:   for (i = 0; i < ov; ++i) PetscCall(MatIncreaseOverlap_MPIAIJ_Once_Scalable(C, imax, is));
 83:   if (C->rmap->bs > 1 && C->rmap->bs == C->cmap->bs) PetscCall(ISAdjustForBlockSize(C->rmap->bs, imax, is));
 84:   PetscFunctionReturn(PETSC_SUCCESS);
 85: }

 87: static PetscErrorCode MatIncreaseOverlap_MPIAIJ_Once_Scalable(Mat mat, PetscInt nidx, IS is[])
 88: {
 89:   MPI_Comm        comm;
 90:   PetscInt       *length, length_i, tlength, *remoterows, nrrows, reducednrrows, *rrow_isids, j;
 91:   PetscInt       *tosizes, *tosizes_temp, *toffsets, *fromsizes, *todata, *fromdata;
 92:   PetscInt        nrecvrows, *sbsizes = NULL, *sbdata = NULL;
 93:   const PetscInt *indices_i, **indices;
 94:   PetscLayout     rmap;
 95:   PetscMPIInt     rank, size, *toranks, *fromranks, nto, nfrom, owner, *rrow_ranks;
 96:   PetscSF         sf;
 97:   PetscSFNode    *remote;

 99:   PetscFunctionBegin;
100:   PetscCall(PetscObjectGetComm((PetscObject)mat, &comm));
101:   PetscCallMPI(MPI_Comm_rank(comm, &rank));
102:   PetscCallMPI(MPI_Comm_size(comm, &size));
103:   /* get row map to determine where rows should be going */
104:   PetscCall(MatGetLayouts(mat, &rmap, NULL));
105:   /* retrieve IS data and put all together so that we
106:    * can optimize communication
107:    *  */
108:   PetscCall(PetscMalloc2(nidx, (PetscInt ***)&indices, nidx, &length));
109:   tlength = 0;
110:   for (PetscInt i = 0; i < nidx; i++) {
111:     PetscCall(ISGetLocalSize(is[i], &length[i]));
112:     tlength += length[i];
113:     PetscCall(ISGetIndices(is[i], &indices[i]));
114:   }
115:   /* find these rows on remote processors */
116:   PetscCall(PetscCalloc3(tlength, &remoterows, tlength, &rrow_ranks, tlength, &rrow_isids));
117:   PetscCall(PetscCalloc3(size, &toranks, 2 * size, &tosizes, size, &tosizes_temp));
118:   nrrows = 0;
119:   for (PetscInt i = 0; i < nidx; i++) {
120:     length_i  = length[i];
121:     indices_i = indices[i];
122:     for (PetscInt j = 0; j < length_i; j++) {
123:       owner = -1;
124:       PetscCall(PetscLayoutFindOwner(rmap, indices_i[j], &owner));
125:       /* remote processors */
126:       if (owner != rank) {
127:         tosizes_temp[owner]++;               /* number of rows to owner */
128:         rrow_ranks[nrrows]   = owner;        /* processor */
129:         rrow_isids[nrrows]   = i;            /* is id */
130:         remoterows[nrrows++] = indices_i[j]; /* row */
131:       }
132:     }
133:     PetscCall(ISRestoreIndices(is[i], &indices[i]));
134:   }
135:   PetscCall(PetscFree2(*(PetscInt ***)&indices, length));
136:   /* test if we need to exchange messages
137:    * generally speaking, we do not need to exchange
138:    * data when overlap is 1
139:    * */
140:   PetscCallMPI(MPIU_Allreduce(&nrrows, &reducednrrows, 1, MPIU_INT, MPI_MAX, comm));
141:   /* we do not have any messages
142:    * It usually corresponds to overlap 1
143:    * */
144:   if (!reducednrrows) {
145:     PetscCall(PetscFree3(toranks, tosizes, tosizes_temp));
146:     PetscCall(PetscFree3(remoterows, rrow_ranks, rrow_isids));
147:     PetscCall(MatIncreaseOverlap_MPIAIJ_Local_Scalable(mat, nidx, is));
148:     PetscFunctionReturn(PETSC_SUCCESS);
149:   }
150:   nto = 0;
151:   /* send sizes and ranks for building a two-sided communication */
152:   for (PetscMPIInt i = 0; i < size; i++) {
153:     if (tosizes_temp[i]) {
154:       tosizes[nto * 2] = tosizes_temp[i] * 2; /* size */
155:       tosizes_temp[i]  = nto;                 /* a map from processor to index */
156:       toranks[nto++]   = i;                   /* MPI process */
157:     }
158:   }
159:   PetscCall(PetscMalloc1(nto + 1, &toffsets));
160:   toffsets[0] = 0;
161:   for (PetscInt i = 0; i < nto; i++) {
162:     toffsets[i + 1]    = toffsets[i] + tosizes[2 * i]; /* offsets */
163:     tosizes[2 * i + 1] = toffsets[i];                  /* offsets to send */
164:   }
165:   /* send information to other processors */
166:   PetscCall(PetscCommBuildTwoSided(comm, 2, MPIU_INT, nto, toranks, tosizes, &nfrom, &fromranks, &fromsizes));
167:   nrecvrows = 0;
168:   for (PetscMPIInt i = 0; i < nfrom; i++) nrecvrows += fromsizes[2 * i];
169:   PetscCall(PetscMalloc1(nrecvrows, &remote));
170:   nrecvrows = 0;
171:   for (PetscMPIInt i = 0; i < nfrom; i++) {
172:     for (PetscInt j = 0; j < fromsizes[2 * i]; j++) {
173:       remote[nrecvrows].rank    = fromranks[i];
174:       remote[nrecvrows++].index = fromsizes[2 * i + 1] + j;
175:     }
176:   }
177:   PetscCall(PetscSFCreate(comm, &sf));
178:   PetscCall(PetscSFSetGraph(sf, nrecvrows, nrecvrows, NULL, PETSC_OWN_POINTER, remote, PETSC_OWN_POINTER));
179:   /* use two-sided communication by default since OPENMPI has some bugs for one-sided one */
180:   PetscCall(PetscSFSetType(sf, PETSCSFBASIC));
181:   PetscCall(PetscSFSetFromOptions(sf));
182:   /* message pair <no of is, row>  */
183:   PetscCall(PetscCalloc2(2 * nrrows, &todata, nrecvrows, &fromdata));
184:   for (PetscInt i = 0; i < nrrows; i++) {
185:     owner                 = rrow_ranks[i];       /* process */
186:     j                     = tosizes_temp[owner]; /* index */
187:     todata[toffsets[j]++] = rrow_isids[i];
188:     todata[toffsets[j]++] = remoterows[i];
189:   }
190:   PetscCall(PetscFree3(toranks, tosizes, tosizes_temp));
191:   PetscCall(PetscFree3(remoterows, rrow_ranks, rrow_isids));
192:   PetscCall(PetscFree(toffsets));
193:   PetscCall(PetscSFBcastBegin(sf, MPIU_INT, todata, fromdata, MPI_REPLACE));
194:   PetscCall(PetscSFBcastEnd(sf, MPIU_INT, todata, fromdata, MPI_REPLACE));
195:   PetscCall(PetscSFDestroy(&sf));
196:   /* send rows belonging to the remote so that then we could get the overlapping data back */
197:   PetscCall(MatIncreaseOverlap_MPIAIJ_Send_Scalable(mat, nidx, nfrom, fromranks, fromsizes, fromdata, &sbsizes, &sbdata));
198:   PetscCall(PetscFree2(todata, fromdata));
199:   PetscCall(PetscFree(fromsizes));
200:   PetscCall(PetscCommBuildTwoSided(comm, 2, MPIU_INT, nfrom, fromranks, sbsizes, &nto, &toranks, &tosizes));
201:   PetscCall(PetscFree(fromranks));
202:   nrecvrows = 0;
203:   for (PetscInt i = 0; i < nto; i++) nrecvrows += tosizes[2 * i];
204:   PetscCall(PetscCalloc1(nrecvrows, &todata));
205:   PetscCall(PetscMalloc1(nrecvrows, &remote));
206:   nrecvrows = 0;
207:   for (PetscInt i = 0; i < nto; i++) {
208:     for (PetscInt j = 0; j < tosizes[2 * i]; j++) {
209:       remote[nrecvrows].rank    = toranks[i];
210:       remote[nrecvrows++].index = tosizes[2 * i + 1] + j;
211:     }
212:   }
213:   PetscCall(PetscSFCreate(comm, &sf));
214:   PetscCall(PetscSFSetGraph(sf, nrecvrows, nrecvrows, NULL, PETSC_OWN_POINTER, remote, PETSC_OWN_POINTER));
215:   /* use two-sided communication by default since OPENMPI has some bugs for one-sided one */
216:   PetscCall(PetscSFSetType(sf, PETSCSFBASIC));
217:   PetscCall(PetscSFSetFromOptions(sf));
218:   /* overlap communication and computation */
219:   PetscCall(PetscSFBcastBegin(sf, MPIU_INT, sbdata, todata, MPI_REPLACE));
220:   PetscCall(MatIncreaseOverlap_MPIAIJ_Local_Scalable(mat, nidx, is));
221:   PetscCall(PetscSFBcastEnd(sf, MPIU_INT, sbdata, todata, MPI_REPLACE));
222:   PetscCall(PetscSFDestroy(&sf));
223:   PetscCall(PetscFree2(sbdata, sbsizes));
224:   PetscCall(MatIncreaseOverlap_MPIAIJ_Receive_Scalable(mat, nidx, is, nrecvrows, todata));
225:   PetscCall(PetscFree(toranks));
226:   PetscCall(PetscFree(tosizes));
227:   PetscCall(PetscFree(todata));
228:   PetscFunctionReturn(PETSC_SUCCESS);
229: }

231: static PetscErrorCode MatIncreaseOverlap_MPIAIJ_Receive_Scalable(Mat mat, PetscInt nidx, IS is[], PetscInt nrecvs, PetscInt *recvdata)
232: {
233:   PetscInt       *isz, isz_i, i, j, is_id, data_size;
234:   PetscInt        col, lsize, max_lsize, *indices_temp, *indices_i;
235:   const PetscInt *indices_i_temp;
236:   MPI_Comm       *iscomms;

238:   PetscFunctionBegin;
239:   max_lsize = 0;
240:   PetscCall(PetscMalloc1(nidx, &isz));
241:   for (i = 0; i < nidx; i++) {
242:     PetscCall(ISGetLocalSize(is[i], &lsize));
243:     max_lsize = lsize > max_lsize ? lsize : max_lsize;
244:     isz[i]    = lsize;
245:   }
246:   PetscCall(PetscMalloc2((max_lsize + nrecvs) * nidx, &indices_temp, nidx, &iscomms));
247:   for (i = 0; i < nidx; i++) {
248:     PetscCall(PetscCommDuplicate(PetscObjectComm((PetscObject)is[i]), &iscomms[i], NULL));
249:     PetscCall(ISGetIndices(is[i], &indices_i_temp));
250:     PetscCall(PetscArraycpy(PetscSafePointerPlusOffset(indices_temp, i * (max_lsize + nrecvs)), indices_i_temp, isz[i]));
251:     PetscCall(ISRestoreIndices(is[i], &indices_i_temp));
252:     PetscCall(ISDestroy(&is[i]));
253:   }
254:   /* retrieve information to get row id and its overlap */
255:   for (i = 0; i < nrecvs;) {
256:     is_id     = recvdata[i++];
257:     data_size = recvdata[i++];
258:     indices_i = indices_temp + (max_lsize + nrecvs) * is_id;
259:     isz_i     = isz[is_id];
260:     for (j = 0; j < data_size; j++) {
261:       col                = recvdata[i++];
262:       indices_i[isz_i++] = col;
263:     }
264:     isz[is_id] = isz_i;
265:   }
266:   /* remove duplicate entities */
267:   for (i = 0; i < nidx; i++) {
268:     indices_i = PetscSafePointerPlusOffset(indices_temp, (max_lsize + nrecvs) * i);
269:     isz_i     = isz[i];
270:     PetscCall(PetscSortRemoveDupsInt(&isz_i, indices_i));
271:     PetscCall(ISCreateGeneral(iscomms[i], isz_i, indices_i, PETSC_COPY_VALUES, &is[i]));
272:     PetscCall(PetscCommDestroy(&iscomms[i]));
273:   }
274:   PetscCall(PetscFree(isz));
275:   PetscCall(PetscFree2(indices_temp, iscomms));
276:   PetscFunctionReturn(PETSC_SUCCESS);
277: }

279: static PetscErrorCode MatIncreaseOverlap_MPIAIJ_Send_Scalable(Mat mat, PetscInt nidx, PetscMPIInt nfrom, PetscMPIInt *fromranks, PetscInt *fromsizes, PetscInt *fromrows, PetscInt **sbrowsizes, PetscInt **sbrows)
280: {
281:   PetscLayout     rmap, cmap;
282:   PetscInt        i, j, k, l, *rows_i, *rows_data_ptr, **rows_data, max_fszs, rows_pos, *rows_pos_i;
283:   PetscInt        is_id, tnz, an, bn, rstart, cstart, row, start, end, col, totalrows, *sbdata;
284:   PetscInt       *indv_counts, indvc_ij, *sbsizes, *indices_tmp, *offsets;
285:   const PetscInt *gcols, *ai, *aj, *bi, *bj;
286:   Mat             amat, bmat;
287:   PetscMPIInt     rank;
288:   PetscBool       done;
289:   MPI_Comm        comm;

291:   PetscFunctionBegin;
292:   PetscCall(PetscObjectGetComm((PetscObject)mat, &comm));
293:   PetscCallMPI(MPI_Comm_rank(comm, &rank));
294:   PetscCall(MatMPIAIJGetSeqAIJ(mat, &amat, &bmat, &gcols));
295:   /* Even if the mat is symmetric, we still assume it is not symmetric */
296:   PetscCall(MatGetRowIJ(amat, 0, PETSC_FALSE, PETSC_FALSE, &an, &ai, &aj, &done));
297:   PetscCheck(done, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "can not get row IJ ");
298:   PetscCall(MatGetRowIJ(bmat, 0, PETSC_FALSE, PETSC_FALSE, &bn, &bi, &bj, &done));
299:   PetscCheck(done, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "can not get row IJ ");
300:   /* total number of nonzero values is used to estimate the memory usage in the next step */
301:   tnz = ai[an] + bi[bn];
302:   PetscCall(MatGetLayouts(mat, &rmap, &cmap));
303:   PetscCall(PetscLayoutGetRange(rmap, &rstart, NULL));
304:   PetscCall(PetscLayoutGetRange(cmap, &cstart, NULL));
305:   /* to find the longest message */
306:   max_fszs = 0;
307:   for (i = 0; i < nfrom; i++) max_fszs = fromsizes[2 * i] > max_fszs ? fromsizes[2 * i] : max_fszs;
308:   /* better way to estimate number of nonzero in the mat??? */
309:   PetscCall(PetscCalloc5(max_fszs * nidx, &rows_data_ptr, nidx, &rows_data, nidx, &rows_pos_i, nfrom * nidx, &indv_counts, tnz, &indices_tmp));
310:   for (i = 0; i < nidx; i++) rows_data[i] = PetscSafePointerPlusOffset(rows_data_ptr, max_fszs * i);
311:   rows_pos  = 0;
312:   totalrows = 0;
313:   for (i = 0; i < nfrom; i++) {
314:     PetscCall(PetscArrayzero(rows_pos_i, nidx));
315:     /* group data together */
316:     for (j = 0; j < fromsizes[2 * i]; j += 2) {
317:       is_id                       = fromrows[rows_pos++]; /* no of is */
318:       rows_i                      = rows_data[is_id];
319:       rows_i[rows_pos_i[is_id]++] = fromrows[rows_pos++]; /* row */
320:     }
321:     /* estimate a space to avoid multiple allocations  */
322:     for (j = 0; j < nidx; j++) {
323:       indvc_ij = 0;
324:       rows_i   = rows_data[j];
325:       for (l = 0; l < rows_pos_i[j]; l++) {
326:         row   = rows_i[l] - rstart;
327:         start = ai[row];
328:         end   = ai[row + 1];
329:         for (k = start; k < end; k++) { /* Amat */
330:           col                     = aj[k] + cstart;
331:           indices_tmp[indvc_ij++] = col; /* do not count the rows from the original rank */
332:         }
333:         start = bi[row];
334:         end   = bi[row + 1];
335:         for (k = start; k < end; k++) { /* Bmat */
336:           col                     = gcols[bj[k]];
337:           indices_tmp[indvc_ij++] = col;
338:         }
339:       }
340:       PetscCall(PetscSortRemoveDupsInt(&indvc_ij, indices_tmp));
341:       indv_counts[i * nidx + j] = indvc_ij;
342:       totalrows += indvc_ij;
343:     }
344:   }
345:   /* message triple <no of is, number of rows, rows> */
346:   PetscCall(PetscCalloc2(totalrows + nidx * nfrom * 2, &sbdata, 2 * nfrom, &sbsizes));
347:   totalrows = 0;
348:   rows_pos  = 0;
349:   /* use this code again */
350:   for (i = 0; i < nfrom; i++) {
351:     PetscCall(PetscArrayzero(rows_pos_i, nidx));
352:     for (j = 0; j < fromsizes[2 * i]; j += 2) {
353:       is_id                       = fromrows[rows_pos++];
354:       rows_i                      = rows_data[is_id];
355:       rows_i[rows_pos_i[is_id]++] = fromrows[rows_pos++];
356:     }
357:     /* add data  */
358:     for (j = 0; j < nidx; j++) {
359:       if (!indv_counts[i * nidx + j]) continue;
360:       indvc_ij            = 0;
361:       sbdata[totalrows++] = j;
362:       sbdata[totalrows++] = indv_counts[i * nidx + j];
363:       sbsizes[2 * i] += 2;
364:       rows_i = rows_data[j];
365:       for (l = 0; l < rows_pos_i[j]; l++) {
366:         row   = rows_i[l] - rstart;
367:         start = ai[row];
368:         end   = ai[row + 1];
369:         for (k = start; k < end; k++) { /* Amat */
370:           col                     = aj[k] + cstart;
371:           indices_tmp[indvc_ij++] = col;
372:         }
373:         start = bi[row];
374:         end   = bi[row + 1];
375:         for (k = start; k < end; k++) { /* Bmat */
376:           col                     = gcols[bj[k]];
377:           indices_tmp[indvc_ij++] = col;
378:         }
379:       }
380:       PetscCall(PetscSortRemoveDupsInt(&indvc_ij, indices_tmp));
381:       sbsizes[2 * i] += indvc_ij;
382:       PetscCall(PetscArraycpy(sbdata + totalrows, indices_tmp, indvc_ij));
383:       totalrows += indvc_ij;
384:     }
385:   }
386:   PetscCall(PetscMalloc1(nfrom + 1, &offsets));
387:   offsets[0] = 0;
388:   for (i = 0; i < nfrom; i++) {
389:     offsets[i + 1]     = offsets[i] + sbsizes[2 * i];
390:     sbsizes[2 * i + 1] = offsets[i];
391:   }
392:   PetscCall(PetscFree(offsets));
393:   if (sbrowsizes) *sbrowsizes = sbsizes;
394:   if (sbrows) *sbrows = sbdata;
395:   PetscCall(PetscFree5(rows_data_ptr, rows_data, rows_pos_i, indv_counts, indices_tmp));
396:   PetscCall(MatRestoreRowIJ(amat, 0, PETSC_FALSE, PETSC_FALSE, &an, &ai, &aj, &done));
397:   PetscCall(MatRestoreRowIJ(bmat, 0, PETSC_FALSE, PETSC_FALSE, &bn, &bi, &bj, &done));
398:   PetscFunctionReturn(PETSC_SUCCESS);
399: }

401: static PetscErrorCode MatIncreaseOverlap_MPIAIJ_Local_Scalable(Mat mat, PetscInt nidx, IS is[])
402: {
403:   const PetscInt *gcols, *ai, *aj, *bi, *bj, *indices;
404:   PetscInt        tnz, an, bn, i, j, row, start, end, rstart, cstart, col, k, *indices_temp;
405:   PetscInt        lsize, lsize_tmp;
406:   PetscMPIInt     rank, owner;
407:   Mat             amat, bmat;
408:   PetscBool       done;
409:   PetscLayout     cmap, rmap;
410:   MPI_Comm        comm;

412:   PetscFunctionBegin;
413:   PetscCall(PetscObjectGetComm((PetscObject)mat, &comm));
414:   PetscCallMPI(MPI_Comm_rank(comm, &rank));
415:   PetscCall(MatMPIAIJGetSeqAIJ(mat, &amat, &bmat, &gcols));
416:   PetscCall(MatGetRowIJ(amat, 0, PETSC_FALSE, PETSC_FALSE, &an, &ai, &aj, &done));
417:   PetscCheck(done, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "can not get row IJ ");
418:   PetscCall(MatGetRowIJ(bmat, 0, PETSC_FALSE, PETSC_FALSE, &bn, &bi, &bj, &done));
419:   PetscCheck(done, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "can not get row IJ ");
420:   /* is it a safe way to compute number of nonzero values ? */
421:   tnz = ai[an] + bi[bn];
422:   PetscCall(MatGetLayouts(mat, &rmap, &cmap));
423:   PetscCall(PetscLayoutGetRange(rmap, &rstart, NULL));
424:   PetscCall(PetscLayoutGetRange(cmap, &cstart, NULL));
425:   /* it is a better way to estimate memory than the old implementation
426:    * where global size of matrix is used
427:    * */
428:   PetscCall(PetscMalloc1(tnz, &indices_temp));
429:   for (i = 0; i < nidx; i++) {
430:     MPI_Comm iscomm;

432:     PetscCall(ISGetLocalSize(is[i], &lsize));
433:     PetscCall(ISGetIndices(is[i], &indices));
434:     lsize_tmp = 0;
435:     for (j = 0; j < lsize; j++) {
436:       owner = -1;
437:       row   = indices[j];
438:       PetscCall(PetscLayoutFindOwner(rmap, row, &owner));
439:       if (owner != rank) continue;
440:       /* local number */
441:       row -= rstart;
442:       start = ai[row];
443:       end   = ai[row + 1];
444:       for (k = start; k < end; k++) { /* Amat */
445:         col                       = aj[k] + cstart;
446:         indices_temp[lsize_tmp++] = col;
447:       }
448:       start = bi[row];
449:       end   = bi[row + 1];
450:       for (k = start; k < end; k++) { /* Bmat */
451:         col                       = gcols[bj[k]];
452:         indices_temp[lsize_tmp++] = col;
453:       }
454:     }
455:     PetscCall(ISRestoreIndices(is[i], &indices));
456:     PetscCall(PetscCommDuplicate(PetscObjectComm((PetscObject)is[i]), &iscomm, NULL));
457:     PetscCall(ISDestroy(&is[i]));
458:     PetscCall(PetscSortRemoveDupsInt(&lsize_tmp, indices_temp));
459:     PetscCall(ISCreateGeneral(iscomm, lsize_tmp, indices_temp, PETSC_COPY_VALUES, &is[i]));
460:     PetscCall(PetscCommDestroy(&iscomm));
461:   }
462:   PetscCall(PetscFree(indices_temp));
463:   PetscCall(MatRestoreRowIJ(amat, 0, PETSC_FALSE, PETSC_FALSE, &an, &ai, &aj, &done));
464:   PetscCall(MatRestoreRowIJ(bmat, 0, PETSC_FALSE, PETSC_FALSE, &bn, &bi, &bj, &done));
465:   PetscFunctionReturn(PETSC_SUCCESS);
466: }

468: /*
469:   Sample message format:
470:   If a processor A wants processor B to process some elements corresponding
471:   to index sets is[1],is[5]
472:   mesg [0] = 2   (no of index sets in the mesg)
473:   -----------
474:   mesg [1] = 1 => is[1]
475:   mesg [2] = sizeof(is[1]);
476:   -----------
477:   mesg [3] = 5  => is[5]
478:   mesg [4] = sizeof(is[5]);
479:   -----------
480:   mesg [5]
481:   mesg [n]  datas[1]
482:   -----------
483:   mesg[n+1]
484:   mesg[m]  data(is[5])
485:   -----------

487:   Notes:
488:   nrqs - no of requests sent (or to be sent out)
489:   nrqr - no of requests received (which have to be or which have been processed)
490: */
491: static PetscErrorCode MatIncreaseOverlap_MPIAIJ_Once(Mat C, PetscInt imax, IS is[])
492: {
493:   Mat_MPIAIJ      *c = (Mat_MPIAIJ *)C->data;
494:   PetscMPIInt     *w1, *w2, nrqr, *w3, *w4, *onodes1, *olengths1, *onodes2, *olengths2;
495:   const PetscInt **idx, *idx_i;
496:   PetscInt        *n, **data, len;
497: #if PetscDefined(USE_CTABLE)
498:   PetscHMapI *table_data, table_data_i;
499:   PetscInt   *tdata, tcount, tcount_max;
500: #else
501:   PetscInt *data_i, *d_p;
502: #endif
503:   PetscMPIInt  size, rank, tag1, tag2, proc = 0, nrqs, *pa;
504:   PetscInt     M, k, **rbuf, row, msz, **outdat, **ptr, *isz1;
505:   PetscInt    *ctr, *tmp, *isz, **xdata, **rbuf2;
506:   PetscBT     *table;
507:   MPI_Comm     comm;
508:   MPI_Request *s_waits1, *r_waits1, *s_waits2, *r_waits2;
509:   MPI_Status  *recv_status;
510:   MPI_Comm    *iscomms;
511:   PetscByte   *t_p;

513:   PetscFunctionBegin;
514:   PetscCall(PetscObjectGetComm((PetscObject)C, &comm));
515:   size = c->size;
516:   rank = c->rank;
517:   M    = C->rmap->N;

519:   PetscCall(PetscObjectGetNewTag((PetscObject)C, &tag1));
520:   PetscCall(PetscObjectGetNewTag((PetscObject)C, &tag2));

522:   PetscCall(PetscMalloc2(imax, (PetscInt ***)&idx, imax, &n));

524:   for (PetscInt i = 0; i < imax; i++) {
525:     PetscCall(ISGetIndices(is[i], &idx[i]));
526:     PetscCall(ISGetLocalSize(is[i], &n[i]));
527:   }

529:   /* evaluate communication - mesg to who,length of mesg, and buffer space
530:      required. Based on this, buffers are allocated, and data copied into them  */
531:   PetscCall(PetscCalloc4(size, &w1, size, &w2, size, &w3, size, &w4));
532:   for (PetscInt i = 0; i < imax; i++) {
533:     PetscCall(PetscArrayzero(w4, size)); /* initialise work vector*/
534:     idx_i = idx[i];
535:     len   = n[i];
536:     for (PetscInt j = 0; j < len; j++) {
537:       row = idx_i[j];
538:       PetscCheck(row >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Index set cannot have negative entries");
539:       PetscCall(PetscLayoutFindOwner(C->rmap, row, &proc));
540:       w4[proc]++;
541:     }
542:     for (PetscMPIInt j = 0; j < size; j++) {
543:       if (w4[j]) {
544:         w1[j] += w4[j];
545:         w3[j]++;
546:       }
547:     }
548:   }

550:   nrqs     = 0; /* no of outgoing messages */
551:   msz      = 0; /* total mesg length (for all proc */
552:   w1[rank] = 0; /* no mesg sent to intself */
553:   w3[rank] = 0;
554:   for (PetscMPIInt i = 0; i < size; i++) {
555:     if (w1[i]) {
556:       w2[i] = 1;
557:       nrqs++;
558:     } /* there exists a message to proc i */
559:   }
560:   /* pa - is list of processors to communicate with */
561:   PetscCall(PetscMalloc1(nrqs, &pa));
562:   for (PetscMPIInt i = 0, j = 0; i < size; i++) {
563:     if (w1[i]) {
564:       pa[j] = i;
565:       j++;
566:     }
567:   }

569:   /* Each message would have a header = 1 + 2*(no of IS) + data */
570:   for (PetscMPIInt i = 0; i < nrqs; i++) {
571:     PetscMPIInt j = pa[i];
572:     w1[j] += w2[j] + 2 * w3[j];
573:     msz += w1[j];
574:   }

576:   /* Determine the number of messages to expect, their lengths, from from-ids */
577:   PetscCall(PetscGatherNumberOfMessages(comm, w2, w1, &nrqr));
578:   PetscCall(PetscGatherMessageLengths(comm, nrqs, nrqr, w1, &onodes1, &olengths1));

580:   /* Now post the Irecvs corresponding to these messages */
581:   PetscCall(PetscPostIrecvInt(comm, tag1, nrqr, onodes1, olengths1, &rbuf, &r_waits1));

583:   /* Allocate Memory for outgoing messages */
584:   PetscCall(PetscMalloc4(size, &outdat, size, &ptr, msz, &tmp, size, &ctr));
585:   PetscCall(PetscArrayzero(outdat, size));
586:   PetscCall(PetscArrayzero(ptr, size));

588:   {
589:     PetscInt *iptr = tmp, ict = 0;
590:     for (PetscMPIInt i = 0; i < nrqs; i++) {
591:       PetscMPIInt j = pa[i];
592:       iptr += ict;
593:       outdat[j] = iptr;
594:       ict       = w1[j];
595:     }
596:   }

598:   /* Form the outgoing messages */
599:   /* plug in the headers */
600:   for (PetscMPIInt i = 0; i < nrqs; i++) {
601:     PetscMPIInt j = pa[i];
602:     outdat[j][0]  = 0;
603:     PetscCall(PetscArrayzero(outdat[j] + 1, 2 * w3[j]));
604:     ptr[j] = outdat[j] + 2 * w3[j] + 1;
605:   }

607:   /* Memory for doing local proc's work */
608:   {
609:     PetscInt M_BPB_imax = 0;
610: #if PetscDefined(USE_CTABLE)
611:     PetscCall(PetscIntMultError(M / PETSC_BITS_PER_BYTE + 1, imax, &M_BPB_imax));
612:     PetscCall(PetscMalloc1(imax, &table_data));
613:     for (PetscInt i = 0; i < imax; i++) PetscCall(PetscHMapICreateWithSize(n[i], table_data + i));
614:     PetscCall(PetscCalloc4(imax, &table, imax, &data, imax, &isz, M_BPB_imax, &t_p));
615:     for (PetscInt i = 0; i < imax; i++) table[i] = t_p + (M / PETSC_BITS_PER_BYTE + 1) * i;
616: #else
617:     PetscInt Mimax = 0;
618:     PetscCall(PetscIntMultError(M, imax, &Mimax));
619:     PetscCall(PetscIntMultError(M / PETSC_BITS_PER_BYTE + 1, imax, &M_BPB_imax));
620:     PetscCall(PetscCalloc5(imax, &table, imax, &data, imax, &isz, Mimax, &d_p, M_BPB_imax, &t_p));
621:     for (PetscInt i = 0; i < imax; i++) {
622:       table[i] = t_p + (M / PETSC_BITS_PER_BYTE + 1) * i;
623:       data[i]  = d_p + M * i;
624:     }
625: #endif
626:   }

628:   /* Parse the IS and update local tables and the outgoing buf with the data */
629:   {
630:     PetscInt n_i, isz_i, *outdat_j, ctr_j;
631:     PetscBT  table_i;

633:     for (PetscInt i = 0; i < imax; i++) {
634:       PetscCall(PetscArrayzero(ctr, size));
635:       n_i     = n[i];
636:       table_i = table[i];
637:       idx_i   = idx[i];
638: #if PetscDefined(USE_CTABLE)
639:       table_data_i = table_data[i];
640: #else
641:       data_i = data[i];
642: #endif
643:       isz_i = isz[i];
644:       for (PetscInt j = 0; j < n_i; j++) { /* parse the indices of each IS */
645:         row = idx_i[j];
646:         PetscCall(PetscLayoutFindOwner(C->rmap, row, &proc));
647:         if (proc != rank) { /* copy to the outgoing buffer */
648:           ctr[proc]++;
649:           *ptr[proc] = row;
650:           ptr[proc]++;
651:         } else if (!PetscBTLookupSet(table_i, row)) {
652: #if PetscDefined(USE_CTABLE)
653:           PetscCall(PetscHMapISet(table_data_i, row + 1, isz_i + 1));
654: #else
655:           data_i[isz_i] = row; /* Update the local table */
656: #endif
657:           isz_i++;
658:         }
659:       }
660:       /* Update the headers for the current IS */
661:       for (PetscMPIInt j = 0; j < size; j++) { /* Can Optimise this loop by using pa[] */
662:         if ((ctr_j = ctr[j])) {
663:           outdat_j            = outdat[j];
664:           k                   = ++outdat_j[0];
665:           outdat_j[2 * k]     = ctr_j;
666:           outdat_j[2 * k - 1] = i;
667:         }
668:       }
669:       isz[i] = isz_i;
670:     }
671:   }

673:   /*  Now  post the sends */
674:   PetscCall(PetscMalloc1(nrqs, &s_waits1));
675:   for (PetscMPIInt i = 0; i < nrqs; ++i) {
676:     PetscMPIInt j = pa[i];
677:     PetscCallMPI(MPIU_Isend(outdat[j], w1[j], MPIU_INT, j, tag1, comm, s_waits1 + i));
678:   }

680:   /* No longer need the original indices */
681:   PetscCall(PetscMalloc1(imax, &iscomms));
682:   for (PetscInt i = 0; i < imax; ++i) {
683:     PetscCall(ISRestoreIndices(is[i], idx + i));
684:     PetscCall(PetscCommDuplicate(PetscObjectComm((PetscObject)is[i]), &iscomms[i], NULL));
685:   }
686:   PetscCall(PetscFree2(*(PetscInt ***)&idx, n));

688:   for (PetscInt i = 0; i < imax; ++i) PetscCall(ISDestroy(&is[i]));

690:   /* Do Local work */
691: #if PetscDefined(USE_CTABLE)
692:   PetscCall(MatIncreaseOverlap_MPIAIJ_Local(C, imax, table, isz, NULL, table_data));
693: #else
694:   PetscCall(MatIncreaseOverlap_MPIAIJ_Local(C, imax, table, isz, data, NULL));
695: #endif

697:   /* Receive messages */
698:   PetscCall(PetscMalloc1(nrqr, &recv_status));
699:   PetscCallMPI(MPI_Waitall(nrqr, r_waits1, recv_status));
700:   PetscCallMPI(MPI_Waitall(nrqs, s_waits1, MPI_STATUSES_IGNORE));

702:   /* Phase 1 sends are complete - deallocate buffers */
703:   PetscCall(PetscFree4(outdat, ptr, tmp, ctr));
704:   PetscCall(PetscFree4(w1, w2, w3, w4));

706:   PetscCall(PetscMalloc1(nrqr, &xdata));
707:   PetscCall(PetscMalloc1(nrqr, &isz1));
708:   PetscCall(MatIncreaseOverlap_MPIAIJ_Receive(C, nrqr, rbuf, xdata, isz1));
709:   PetscCall(PetscFree(rbuf[0]));
710:   PetscCall(PetscFree(rbuf));

712:   /* Send the data back */
713:   /* Do a global reduction to know the buffer space req for incoming messages */
714:   {
715:     PetscMPIInt *rw1;

717:     PetscCall(PetscCalloc1(size, &rw1));
718:     for (PetscMPIInt i = 0; i < nrqr; ++i) {
719:       proc = recv_status[i].MPI_SOURCE;
720:       PetscCheck(proc == onodes1[i], PETSC_COMM_SELF, PETSC_ERR_PLIB, "MPI_SOURCE mismatch");
721:       PetscCall(PetscMPIIntCast(isz1[i], &rw1[proc]));
722:     }
723:     PetscCall(PetscFree(onodes1));
724:     PetscCall(PetscFree(olengths1));

726:     /* Determine the number of messages to expect, their lengths, from from-ids */
727:     PetscCall(PetscGatherMessageLengths(comm, nrqr, nrqs, rw1, &onodes2, &olengths2));
728:     PetscCall(PetscFree(rw1));
729:   }
730:   /* Now post the Irecvs corresponding to these messages */
731:   PetscCall(PetscPostIrecvInt(comm, tag2, nrqs, onodes2, olengths2, &rbuf2, &r_waits2));

733:   /* Now  post the sends */
734:   PetscCall(PetscMalloc1(nrqr, &s_waits2));
735:   for (PetscMPIInt i = 0; i < nrqr; ++i) PetscCallMPI(MPIU_Isend(xdata[i], isz1[i], MPIU_INT, recv_status[i].MPI_SOURCE, tag2, comm, s_waits2 + i));

737:   /* receive work done on other processors */
738:   {
739:     PetscInt    is_no, ct1, max, *rbuf2_i, isz_i, jmax;
740:     PetscMPIInt idex;
741:     PetscBT     table_i;

743:     for (PetscMPIInt i = 0; i < nrqs; ++i) {
744:       PetscCallMPI(MPI_Waitany(nrqs, r_waits2, &idex, MPI_STATUS_IGNORE));
745:       /* Process the message */
746:       rbuf2_i = rbuf2[idex];
747:       ct1     = 2 * rbuf2_i[0] + 1;
748:       jmax    = rbuf2[idex][0];
749:       for (PetscInt j = 1; j <= jmax; j++) {
750:         max     = rbuf2_i[2 * j];
751:         is_no   = rbuf2_i[2 * j - 1];
752:         isz_i   = isz[is_no];
753:         table_i = table[is_no];
754: #if PetscDefined(USE_CTABLE)
755:         table_data_i = table_data[is_no];
756: #else
757:         data_i = data[is_no];
758: #endif
759:         for (k = 0; k < max; k++, ct1++) {
760:           row = rbuf2_i[ct1];
761:           if (!PetscBTLookupSet(table_i, row)) {
762: #if PetscDefined(USE_CTABLE)
763:             PetscCall(PetscHMapISet(table_data_i, row + 1, isz_i + 1));
764: #else
765:             data_i[isz_i] = row;
766: #endif
767:             isz_i++;
768:           }
769:         }
770:         isz[is_no] = isz_i;
771:       }
772:     }

774:     PetscCallMPI(MPI_Waitall(nrqr, s_waits2, MPI_STATUSES_IGNORE));
775:   }

777: #if PetscDefined(USE_CTABLE)
778:   tcount_max = 0;
779:   for (PetscInt i = 0; i < imax; ++i) {
780:     table_data_i = table_data[i];
781:     PetscCall(PetscHMapIGetSize(table_data_i, &tcount));
782:     if (tcount_max < tcount) tcount_max = tcount;
783:   }
784:   PetscCall(PetscMalloc1(tcount_max, &tdata));
785: #endif

787:   for (PetscInt i = 0; i < imax; ++i) {
788: #if PetscDefined(USE_CTABLE)
789:     PetscHashIter tpos;
790:     PetscInt      j;

792:     table_data_i = table_data[i];
793:     PetscHashIterBegin(table_data_i, tpos);
794:     while (!PetscHashIterAtEnd(table_data_i, tpos)) {
795:       PetscHashIterGetKey(table_data_i, tpos, k);
796:       PetscHashIterGetVal(table_data_i, tpos, j);
797:       PetscHashIterNext(table_data_i, tpos);
798:       tdata[--j] = --k;
799:     }
800:     PetscCall(ISCreateGeneral(iscomms[i], isz[i], tdata, PETSC_COPY_VALUES, is + i));
801: #else
802:     PetscCall(ISCreateGeneral(iscomms[i], isz[i], data[i], PETSC_COPY_VALUES, is + i));
803: #endif
804:     PetscCall(PetscCommDestroy(&iscomms[i]));
805:   }

807:   PetscCall(PetscFree(iscomms));
808:   PetscCall(PetscFree(onodes2));
809:   PetscCall(PetscFree(olengths2));

811:   PetscCall(PetscFree(pa));
812:   PetscCall(PetscFree(rbuf2[0]));
813:   PetscCall(PetscFree(rbuf2));
814:   PetscCall(PetscFree(s_waits1));
815:   PetscCall(PetscFree(r_waits1));
816:   PetscCall(PetscFree(s_waits2));
817:   PetscCall(PetscFree(r_waits2));
818:   PetscCall(PetscFree(recv_status));
819:   if (xdata) {
820:     PetscCall(PetscFree(xdata[0]));
821:     PetscCall(PetscFree(xdata));
822:   }
823:   PetscCall(PetscFree(isz1));
824: #if PetscDefined(USE_CTABLE)
825:   for (PetscInt i = 0; i < imax; i++) PetscCall(PetscHMapIDestroy(table_data + i));
826:   PetscCall(PetscFree(table_data));
827:   PetscCall(PetscFree(tdata));
828:   PetscCall(PetscFree4(table, data, isz, t_p));
829: #else
830:   PetscCall(PetscFree5(table, data, isz, d_p, t_p));
831: #endif
832:   PetscFunctionReturn(PETSC_SUCCESS);
833: }

835: /*
836:    MatIncreaseOverlap_MPIAIJ_Local - Called by MatincreaseOverlap, to do
837:        the work on the local processor.

839:      Inputs:
840:       C      - MAT_MPIAIJ;
841:       imax - total no of index sets processed at a time;
842:       table  - an array of char - size = m bits.

844:      Output:
845:       isz    - array containing the count of the solution elements corresponding
846:                to each index set;
847:       data or table_data  - pointer to the solutions
848: */
849: static PetscErrorCode MatIncreaseOverlap_MPIAIJ_Local(Mat C, PetscInt imax, PetscBT *table, PetscInt *isz, PetscInt **data, PetscHMapI *table_data)
850: {
851:   Mat_MPIAIJ *c = (Mat_MPIAIJ *)C->data;
852:   Mat         A = c->A, B = c->B;
853:   Mat_SeqAIJ *a = (Mat_SeqAIJ *)A->data, *b = (Mat_SeqAIJ *)B->data;
854:   PetscInt    start, end, val, max, rstart, cstart, *ai, *aj;
855:   PetscInt   *bi, *bj, *garray, i, j, k, row, isz_i;
856:   PetscBT     table_i;
857: #if PetscDefined(USE_CTABLE)
858:   PetscHMapI    table_data_i;
859:   PetscHashIter tpos;
860:   PetscInt      tcount, *tdata;
861: #else
862:   PetscInt *data_i;
863: #endif

865:   PetscFunctionBegin;
866:   rstart = C->rmap->rstart;
867:   cstart = C->cmap->rstart;
868:   ai     = a->i;
869:   aj     = a->j;
870:   bi     = b->i;
871:   bj     = b->j;
872:   garray = c->garray;

874:   for (i = 0; i < imax; i++) {
875: #if PetscDefined(USE_CTABLE)
876:     /* copy existing entries of table_data_i into tdata[] */
877:     table_data_i = table_data[i];
878:     PetscCall(PetscHMapIGetSize(table_data_i, &tcount));
879:     PetscCheck(tcount == isz[i], PETSC_COMM_SELF, PETSC_ERR_PLIB, " tcount %" PetscInt_FMT " != isz[%" PetscInt_FMT "] %" PetscInt_FMT, tcount, i, isz[i]);

881:     PetscCall(PetscMalloc1(tcount, &tdata));
882:     PetscHashIterBegin(table_data_i, tpos);
883:     while (!PetscHashIterAtEnd(table_data_i, tpos)) {
884:       PetscHashIterGetKey(table_data_i, tpos, row);
885:       PetscHashIterGetVal(table_data_i, tpos, j);
886:       PetscHashIterNext(table_data_i, tpos);
887:       tdata[--j] = --row;
888:       PetscCheck(j <= tcount - 1, PETSC_COMM_SELF, PETSC_ERR_PLIB, " j %" PetscInt_FMT " >= tcount %" PetscInt_FMT, j, tcount);
889:     }
890: #else
891:     data_i = data[i];
892: #endif
893:     table_i = table[i];
894:     isz_i   = isz[i];
895:     max     = isz[i];

897:     for (j = 0; j < max; j++) {
898: #if PetscDefined(USE_CTABLE)
899:       row = tdata[j] - rstart;
900: #else
901:       row = data_i[j] - rstart;
902: #endif
903:       start = ai[row];
904:       end   = ai[row + 1];
905:       for (k = start; k < end; k++) { /* Amat */
906:         val = aj[k] + cstart;
907:         if (!PetscBTLookupSet(table_i, val)) {
908: #if PetscDefined(USE_CTABLE)
909:           PetscCall(PetscHMapISet(table_data_i, val + 1, isz_i + 1));
910: #else
911:           data_i[isz_i] = val;
912: #endif
913:           isz_i++;
914:         }
915:       }
916:       start = bi[row];
917:       end   = bi[row + 1];
918:       for (k = start; k < end; k++) { /* Bmat */
919:         val = garray[bj[k]];
920:         if (!PetscBTLookupSet(table_i, val)) {
921: #if PetscDefined(USE_CTABLE)
922:           PetscCall(PetscHMapISet(table_data_i, val + 1, isz_i + 1));
923: #else
924:           data_i[isz_i] = val;
925: #endif
926:           isz_i++;
927:         }
928:       }
929:     }
930:     isz[i] = isz_i;

932: #if PetscDefined(USE_CTABLE)
933:     PetscCall(PetscFree(tdata));
934: #endif
935:   }
936:   PetscFunctionReturn(PETSC_SUCCESS);
937: }

939: /*
940:       MatIncreaseOverlap_MPIAIJ_Receive - Process the received messages,
941:          and return the output

943:          Input:
944:            C    - the matrix
945:            nrqr - no of messages being processed.
946:            rbuf - an array of pointers to the received requests

948:          Output:
949:            xdata - array of messages to be sent back
950:            isz1  - size of each message

952:   For better efficiency perhaps we should malloc separately each xdata[i],
953: then if a remalloc is required we need only copy the data for that one row
954: rather than all previous rows as it is now where a single large chunk of
955: memory is used.

957: */
958: static PetscErrorCode MatIncreaseOverlap_MPIAIJ_Receive(Mat C, PetscInt nrqr, PetscInt **rbuf, PetscInt **xdata, PetscInt *isz1)
959: {
960:   Mat_MPIAIJ *c = (Mat_MPIAIJ *)C->data;
961:   Mat         A = c->A, B = c->B;
962:   Mat_SeqAIJ *a = (Mat_SeqAIJ *)A->data, *b = (Mat_SeqAIJ *)B->data;
963:   PetscInt    rstart, cstart, *ai, *aj, *bi, *bj, *garray, i, j, k;
964:   PetscInt    row, total_sz, ct, ct1, ct2, ct3, mem_estimate, oct2, l, start, end;
965:   PetscInt    val, max1, max2, m, no_malloc = 0, *tmp, new_estimate, ctr;
966:   PetscInt   *rbuf_i, kmax, rbuf_0;
967:   PetscBT     xtable;

969:   PetscFunctionBegin;
970:   m      = C->rmap->N;
971:   rstart = C->rmap->rstart;
972:   cstart = C->cmap->rstart;
973:   ai     = a->i;
974:   aj     = a->j;
975:   bi     = b->i;
976:   bj     = b->j;
977:   garray = c->garray;

979:   for (i = 0, ct = 0, total_sz = 0; i < nrqr; ++i) {
980:     rbuf_i = rbuf[i];
981:     rbuf_0 = rbuf_i[0];
982:     ct += rbuf_0;
983:     for (j = 1; j <= rbuf_0; j++) total_sz += rbuf_i[2 * j];
984:   }

986:   if (C->rmap->n) max1 = ct * (a->nz + b->nz) / C->rmap->n;
987:   else max1 = 1;
988:   mem_estimate = 3 * ((total_sz > max1 ? total_sz : max1) + 1);
989:   if (nrqr) {
990:     PetscCall(PetscMalloc1(mem_estimate, &xdata[0]));
991:     ++no_malloc;
992:   }
993:   PetscCall(PetscBTCreate(m, &xtable));
994:   PetscCall(PetscArrayzero(isz1, nrqr));

996:   ct3 = 0;
997:   for (i = 0; i < nrqr; i++) { /* for easch mesg from proc i */
998:     rbuf_i = rbuf[i];
999:     rbuf_0 = rbuf_i[0];
1000:     ct1    = 2 * rbuf_0 + 1;
1001:     ct2    = ct1;
1002:     ct3 += ct1;
1003:     for (j = 1; j <= rbuf_0; j++) { /* for each IS from proc i*/
1004:       PetscCall(PetscBTMemzero(m, xtable));
1005:       oct2 = ct2;
1006:       kmax = rbuf_i[2 * j];
1007:       for (k = 0; k < kmax; k++, ct1++) {
1008:         row = rbuf_i[ct1];
1009:         if (!PetscBTLookupSet(xtable, row)) {
1010:           if (!(ct3 < mem_estimate)) {
1011:             new_estimate = (PetscInt)(1.5 * mem_estimate) + 1;
1012:             PetscCall(PetscMalloc1(new_estimate, &tmp));
1013:             PetscCall(PetscArraycpy(tmp, xdata[0], mem_estimate));
1014:             PetscCall(PetscFree(xdata[0]));
1015:             xdata[0]     = tmp;
1016:             mem_estimate = new_estimate;
1017:             ++no_malloc;
1018:             for (ctr = 1; ctr <= i; ctr++) xdata[ctr] = xdata[ctr - 1] + isz1[ctr - 1];
1019:           }
1020:           xdata[i][ct2++] = row;
1021:           ct3++;
1022:         }
1023:       }
1024:       for (k = oct2, max2 = ct2; k < max2; k++) {
1025:         row   = xdata[i][k] - rstart;
1026:         start = ai[row];
1027:         end   = ai[row + 1];
1028:         for (l = start; l < end; l++) {
1029:           val = aj[l] + cstart;
1030:           if (!PetscBTLookupSet(xtable, val)) {
1031:             if (!(ct3 < mem_estimate)) {
1032:               new_estimate = (PetscInt)(1.5 * mem_estimate) + 1;
1033:               PetscCall(PetscMalloc1(new_estimate, &tmp));
1034:               PetscCall(PetscArraycpy(tmp, xdata[0], mem_estimate));
1035:               PetscCall(PetscFree(xdata[0]));
1036:               xdata[0]     = tmp;
1037:               mem_estimate = new_estimate;
1038:               ++no_malloc;
1039:               for (ctr = 1; ctr <= i; ctr++) xdata[ctr] = xdata[ctr - 1] + isz1[ctr - 1];
1040:             }
1041:             xdata[i][ct2++] = val;
1042:             ct3++;
1043:           }
1044:         }
1045:         start = bi[row];
1046:         end   = bi[row + 1];
1047:         for (l = start; l < end; l++) {
1048:           val = garray[bj[l]];
1049:           if (!PetscBTLookupSet(xtable, val)) {
1050:             if (!(ct3 < mem_estimate)) {
1051:               new_estimate = (PetscInt)(1.5 * mem_estimate) + 1;
1052:               PetscCall(PetscMalloc1(new_estimate, &tmp));
1053:               PetscCall(PetscArraycpy(tmp, xdata[0], mem_estimate));
1054:               PetscCall(PetscFree(xdata[0]));
1055:               xdata[0]     = tmp;
1056:               mem_estimate = new_estimate;
1057:               ++no_malloc;
1058:               for (ctr = 1; ctr <= i; ctr++) xdata[ctr] = xdata[ctr - 1] + isz1[ctr - 1];
1059:             }
1060:             xdata[i][ct2++] = val;
1061:             ct3++;
1062:           }
1063:         }
1064:       }
1065:       /* Update the header*/
1066:       xdata[i][2 * j]     = ct2 - oct2; /* Undo the vector isz1 and use only a var*/
1067:       xdata[i][2 * j - 1] = rbuf_i[2 * j - 1];
1068:     }
1069:     xdata[i][0] = rbuf_0;
1070:     if (i + 1 < nrqr) xdata[i + 1] = xdata[i] + ct2;
1071:     isz1[i] = ct2; /* size of each message */
1072:   }
1073:   PetscCall(PetscBTDestroy(&xtable));
1074:   PetscCall(PetscInfo(C, "Allocated %" PetscInt_FMT " bytes, required %" PetscInt_FMT " bytes, no of mallocs = %" PetscInt_FMT "\n", mem_estimate, ct3, no_malloc));
1075:   PetscFunctionReturn(PETSC_SUCCESS);
1076: }

1078: extern PetscErrorCode MatCreateSubMatrices_MPIAIJ_Local(Mat, PetscInt, const IS[], const IS[], MatReuse, Mat *);
1079: /*
1080:     Every processor gets the entire matrix
1081: */
1082: PetscErrorCode MatCreateSubMatrix_MPIAIJ_All(Mat A, MatCreateSubMatrixOption flag, MatReuse scall, Mat *Bin[])
1083: {
1084:   Mat         B;
1085:   Mat_MPIAIJ *a = (Mat_MPIAIJ *)A->data;
1086:   Mat_SeqAIJ *b, *ad = (Mat_SeqAIJ *)a->A->data, *bd = (Mat_SeqAIJ *)a->B->data;
1087:   PetscMPIInt size, rank;
1088:   PetscInt    sendcount, *rstarts = A->rmap->range, n, cnt, j, nrecv = 0;
1089:   PetscInt    m, *b_sendj, *garray = a->garray, *lens, *jsendbuf, *a_jsendbuf, *b_jsendbuf;

1091:   PetscFunctionBegin;
1092:   PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)A), &size));
1093:   PetscCallMPI(MPI_Comm_rank(PetscObjectComm((PetscObject)A), &rank));
1094:   if (scall == MAT_INITIAL_MATRIX) {
1095:     /* Tell every processor the number of nonzeros per row */
1096:     PetscCall(PetscCalloc1(A->rmap->N, &lens));
1097:     for (PetscInt i = A->rmap->rstart; i < A->rmap->rend; i++) lens[i] = ad->i[i - A->rmap->rstart + 1] - ad->i[i - A->rmap->rstart] + bd->i[i - A->rmap->rstart + 1] - bd->i[i - A->rmap->rstart];

1099:     /* All MPI processes get the same matrix */
1100:     PetscCallMPI(MPIU_Allreduce(MPI_IN_PLACE, lens, A->rmap->N, MPIU_INT, MPI_SUM, PetscObjectComm((PetscObject)A)));

1102:     /*     Create the sequential matrix of the same type as the local block diagonal  */
1103:     PetscCall(MatCreate(PETSC_COMM_SELF, &B));
1104:     PetscCall(MatSetSizes(B, A->rmap->N, A->cmap->N, PETSC_DETERMINE, PETSC_DETERMINE));
1105:     PetscCall(MatSetBlockSizesFromMats(B, A, A));
1106:     PetscCall(MatSetType(B, ((PetscObject)a->A)->type_name));
1107:     PetscCall(MatSeqAIJSetPreallocation(B, 0, lens));
1108:     PetscCall(PetscCalloc1(2, Bin));
1109:     **Bin = B;
1110:     b     = (Mat_SeqAIJ *)B->data;

1112:     /* zero column space */
1113:     nrecv = 0;
1114:     for (PetscMPIInt i = 0; i < size; i++) {
1115:       for (j = A->rmap->range[i]; j < A->rmap->range[i + 1]; j++) nrecv += lens[j];
1116:     }
1117:     PetscCall(PetscArrayzero(b->j, nrecv));

1119:     /*   Copy my part of matrix column indices over    */
1120:     sendcount  = ad->nz + bd->nz;
1121:     jsendbuf   = PetscSafePointerPlusOffset(b->j, b->i[rstarts[rank]]);
1122:     a_jsendbuf = ad->j;
1123:     b_jsendbuf = bd->j;
1124:     n          = A->rmap->rend - A->rmap->rstart;
1125:     cnt        = 0;
1126:     for (PetscInt i = 0; i < n; i++) {
1127:       /* put in lower diagonal portion */
1128:       m = bd->i[i + 1] - bd->i[i];
1129:       while (m > 0) {
1130:         /* is it above diagonal (in bd (compressed) numbering) */
1131:         if (garray[*b_jsendbuf] > A->rmap->rstart + i) break;
1132:         jsendbuf[cnt++] = garray[*b_jsendbuf++];
1133:         m--;
1134:       }

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

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

1144:     /* send column indices, b->j was zeroed */
1145:     PetscCallMPI(MPIU_Allreduce(MPI_IN_PLACE, b->j, nrecv, MPIU_INT, MPI_SUM, PetscObjectComm((PetscObject)A)));

1147:     /*  Assemble the matrix into useable form (numerical values not yet set) */
1148:     /* set the b->ilen (length of each row) values */
1149:     PetscCall(PetscArraycpy(b->ilen, lens, A->rmap->N));
1150:     /* set the b->i indices */
1151:     b->i[0] = 0;
1152:     for (PetscInt i = 1; i <= A->rmap->N; i++) b->i[i] = b->i[i - 1] + lens[i - 1];
1153:     PetscCall(PetscFree(lens));
1154:     PetscCall(MatAssemblyBegin(B, MAT_FINAL_ASSEMBLY));
1155:     PetscCall(MatAssemblyEnd(B, MAT_FINAL_ASSEMBLY));

1157:   } else {
1158:     B = **Bin;
1159:     b = (Mat_SeqAIJ *)B->data;
1160:   }

1162:   /* Copy my part of matrix numerical values into the values location */
1163:   if (flag == MAT_GET_VALUES) {
1164:     const PetscScalar *ada, *bda, *a_sendbuf, *b_sendbuf;
1165:     MatScalar         *sendbuf;

1167:     /* initialize b->a */
1168:     PetscCall(PetscArrayzero(b->a, b->nz));

1170:     PetscCall(MatSeqAIJGetArrayRead(a->A, &ada));
1171:     PetscCall(MatSeqAIJGetArrayRead(a->B, &bda));
1172:     sendcount = ad->nz + bd->nz;
1173:     sendbuf   = PetscSafePointerPlusOffset(b->a, b->i[rstarts[rank]]);
1174:     a_sendbuf = ada;
1175:     b_sendbuf = bda;
1176:     b_sendj   = bd->j;
1177:     n         = A->rmap->rend - A->rmap->rstart;
1178:     cnt       = 0;
1179:     for (PetscInt i = 0; i < n; i++) {
1180:       /* put in lower diagonal portion */
1181:       m = bd->i[i + 1] - bd->i[i];
1182:       while (m > 0) {
1183:         /* is it above diagonal (in bd (compressed) numbering) */
1184:         if (garray[*b_sendj] > A->rmap->rstart + i) break;
1185:         sendbuf[cnt++] = *b_sendbuf++;
1186:         m--;
1187:         b_sendj++;
1188:       }

1190:       /* put in diagonal portion */
1191:       for (PetscInt j = ad->i[i]; j < ad->i[i + 1]; j++) sendbuf[cnt++] = *a_sendbuf++;

1193:       /* put in upper diagonal portion */
1194:       while (m-- > 0) {
1195:         sendbuf[cnt++] = *b_sendbuf++;
1196:         b_sendj++;
1197:       }
1198:     }
1199:     PetscCheck(cnt == sendcount, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Corrupted PETSc matrix: nz given %" PetscInt_FMT " actual nz %" PetscInt_FMT, sendcount, cnt);

1201:     /* send values, b->a was zeroed */
1202:     PetscCallMPI(MPIU_Allreduce(MPI_IN_PLACE, b->a, b->nz, MPIU_SCALAR, MPIU_SUM, PetscObjectComm((PetscObject)A)));

1204:     PetscCall(MatSeqAIJRestoreArrayRead(a->A, &ada));
1205:     PetscCall(MatSeqAIJRestoreArrayRead(a->B, &bda));
1206:   } /* endof (flag == MAT_GET_VALUES) */

1208:   PetscCall(MatPropagateSymmetryOptions(A, B));
1209:   PetscFunctionReturn(PETSC_SUCCESS);
1210: }

1212: PetscErrorCode MatCreateSubMatrices_MPIAIJ_SingleIS_Local(Mat C, PetscInt ismax, const IS isrow[], const IS iscol[], MatReuse scall, PetscBool allcolumns, Mat *submats)
1213: {
1214:   Mat_MPIAIJ     *c = (Mat_MPIAIJ *)C->data;
1215:   Mat             submat, A = c->A, B = c->B;
1216:   Mat_SeqAIJ     *a = (Mat_SeqAIJ *)A->data, *b = (Mat_SeqAIJ *)B->data, *subc;
1217:   Mat_SubSppt    *smatis1;
1218:   const PetscInt *icol, *irow;
1219:   PetscInt        cstart = C->cmap->rstart, cend = C->cmap->rend, rstart = C->rmap->rstart;
1220:   PetscInt        nzA, nzB, nrow, ncol, start, k, ct1, ct2, ct3, row, msz, tcol, max1, nnz, rmax, ncols, Crow, ctr_j, kmax, jcnt, lwrite, ib, jb;
1221:   PetscInt       *ai = a->i, *aj = a->j, *bi = b->i, *bj = b->j, *bmap = c->garray;
1222:   PetscInt       *req_size, *ctr, *tmp, *iptr, *lens, *cols, *sbuf1_j, *sbuf_aj_i, *rbuf1_i, *sbuf1_i, *rbuf2_i, *rbuf3_i, *cworkB, *subcols;
1223:   PetscInt      **sbuf1, **sbuf2, **rbuf1, **ptr, **rbuf3, **sbuf_aj, **rbuf2;
1224: #if PetscDefined(USE_CTABLE)
1225:   PetscInt  *cmap_loc, *rmap_loc;
1226:   PetscHMapI cmap, rmap;
1227: #else
1228:   PetscInt *cmap, *rmap;
1229: #endif
1230:   PetscMPIInt      rank, size, tag1, tag2, tag3, tag4, nrqr, nrqs = 0, proc, idex, end;
1231:   PetscMPIInt     *req_source1, *req_source2, *w1, *w2, *pa, *onodes1, *olengths1, *row2proc;
1232:   PetscScalar     *vworkA, *vworkB, *a_a, *b_a, *subvals = NULL, *suba = NULL, *vals, *sbuf_aa_i, *rbuf4_i;
1233:   PetscScalar    **rbuf4, **sbuf_aa;
1234:   PetscBool        isrowsorted, iscolsorted, direct_csr_reuse = PETSC_FALSE;
1235:   PetscObjectState submat_nonzerostate;
1236:   MPI_Request     *s_waits1, *r_waits1, *s_waits2, *r_waits2, *r_waits3, *r_waits4, *s_waits3 = NULL, *s_waits4;
1237:   MPI_Status      *r_status1, *r_status2, *s_status1, *s_status3 = NULL, *s_status2, *r_status3 = NULL, *r_status4, *s_status4;
1238:   MPI_Comm         comm;

1240:   PetscFunctionBegin;
1243:   PetscCheck(ismax == 1, PETSC_COMM_SELF, PETSC_ERR_SUP, "This routine only works when all processes have ismax=1");
1244:   PetscCall(PetscObjectGetComm((PetscObject)C, &comm));
1245:   size = c->size;
1246:   rank = c->rank;

1248:   PetscCall(ISSorted(iscol[0], &iscolsorted));
1249:   PetscCall(ISSorted(isrow[0], &isrowsorted));
1250:   PetscCall(ISGetIndices(isrow[0], &irow));
1251:   PetscCall(ISGetLocalSize(isrow[0], &nrow));
1252:   if (allcolumns) {
1253:     icol = NULL;
1254:     ncol = C->cmap->N;
1255:   } else {
1256:     PetscCall(ISGetIndices(iscol[0], &icol));
1257:     PetscCall(ISGetLocalSize(iscol[0], &ncol));
1258:   }

1260:   /* MAT_REUSE_MATRIX requires an unchanged pattern, so there are no values to update for a structure-only matrix */
1261:   if (C->structure_only && scall == MAT_REUSE_MATRIX) {
1262:     PetscCheck(submats[0]->rmap->n == nrow && submats[0]->cmap->n == ncol, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Cannot reuse matrix: wrong dimensions");
1263:     PetscCall(ISRestoreIndices(isrow[0], &irow));
1264:     if (!allcolumns) PetscCall(ISRestoreIndices(iscol[0], &icol));
1265:     PetscFunctionReturn(PETSC_SUCCESS);
1266:   }

1268:   PetscCall(MatSeqAIJGetArrayRead(A, (const PetscScalar **)&a_a));
1269:   PetscCall(MatSeqAIJGetArrayRead(B, (const PetscScalar **)&b_a));
1270:   if (scall == MAT_INITIAL_MATRIX) {
1271:     PetscInt *sbuf2_i, *cworkA, lwrite, ctmp;

1273:     /* Get some new tags to keep the communication clean */
1274:     tag1 = ((PetscObject)C)->tag;
1275:     PetscCall(PetscObjectGetNewTag((PetscObject)C, &tag2));
1276:     PetscCall(PetscObjectGetNewTag((PetscObject)C, &tag3));

1278:     /* evaluate communication - mesg to who, length of mesg, and buffer space
1279:      required. Based on this, buffers are allocated, and data copied into them */
1280:     PetscCall(PetscCalloc2(size, &w1, size, &w2));
1281:     PetscCall(PetscMalloc1(nrow, &row2proc));

1283:     /* w1[proc] = num of rows owned by proc -- to be requested */
1284:     proc = 0;
1285:     nrqs = 0; /* num of outgoing messages */
1286:     for (PetscInt j = 0; j < nrow; j++) {
1287:       row = irow[j];
1288:       if (!isrowsorted) proc = 0;
1289:       while (row >= C->rmap->range[proc + 1]) proc++;
1290:       w1[proc]++;
1291:       row2proc[j] = proc; /* map row index to proc */

1293:       if (proc != rank && !w2[proc]) {
1294:         w2[proc] = 1;
1295:         nrqs++;
1296:       }
1297:     }
1298:     w1[rank] = 0; /* rows owned by self will not be requested */

1300:     PetscCall(PetscMalloc1(nrqs, &pa)); /*(proc -array)*/
1301:     for (PetscMPIInt proc = 0, j = 0; proc < size; proc++) {
1302:       if (w1[proc]) pa[j++] = proc;
1303:     }

1305:     /* Each message would have a header = 1 + 2*(num of IS) + data (here,num of IS = 1) */
1306:     msz = 0; /* total mesg length (for all procs) */
1307:     for (PetscMPIInt i = 0; i < nrqs; i++) {
1308:       w1[pa[i]] += 3;
1309:       msz += w1[pa[i]];
1310:     }
1311:     PetscCall(PetscInfo(0, "Number of outgoing messages %d Total message length %" PetscInt_FMT "\n", nrqs, msz));

1313:     /* Determine nrqr, the number of messages to expect, their lengths, from from-ids */
1314:     /* if w2[proc]=1, a message of length w1[proc] will be sent to proc; */
1315:     PetscCall(PetscGatherNumberOfMessages(comm, w2, w1, &nrqr));

1317:     /* Input: nrqs: nsend; nrqr: nrecv; w1: msg length to be sent;
1318:        Output: onodes1: recv node-ids; olengths1: corresponding recv message length */
1319:     PetscCall(PetscGatherMessageLengths(comm, nrqs, nrqr, w1, &onodes1, &olengths1));

1321:     /* Now post the Irecvs corresponding to these messages */
1322:     PetscCall(PetscPostIrecvInt(comm, tag1, nrqr, onodes1, olengths1, &rbuf1, &r_waits1));

1324:     PetscCall(PetscFree(onodes1));
1325:     PetscCall(PetscFree(olengths1));

1327:     /* Allocate Memory for outgoing messages */
1328:     PetscCall(PetscMalloc4(size, &sbuf1, size, &ptr, 2 * msz, &tmp, size, &ctr));
1329:     PetscCall(PetscArrayzero(sbuf1, size));
1330:     PetscCall(PetscArrayzero(ptr, size));

1332:     /* subf1[pa[0]] = tmp, subf1[pa[i]] = subf1[pa[i-1]] + w1[pa[i-1]] */
1333:     iptr = tmp;
1334:     for (PetscMPIInt i = 0; i < nrqs; i++) {
1335:       sbuf1[pa[i]] = iptr;
1336:       iptr += w1[pa[i]];
1337:     }

1339:     /* Form the outgoing messages */
1340:     /* Initialize the header space */
1341:     for (PetscMPIInt i = 0; i < nrqs; i++) {
1342:       PetscCall(PetscArrayzero(sbuf1[pa[i]], 3));
1343:       ptr[pa[i]] = sbuf1[pa[i]] + 3;
1344:     }

1346:     /* Parse the isrow and copy data into outbuf */
1347:     PetscCall(PetscArrayzero(ctr, size));
1348:     for (PetscInt j = 0; j < nrow; j++) { /* parse the indices of each IS */
1349:       if (row2proc[j] != rank) {          /* copy to the outgoing buf */
1350:         *ptr[row2proc[j]] = irow[j];
1351:         ctr[row2proc[j]]++;
1352:         ptr[row2proc[j]]++;
1353:       }
1354:     }

1356:     /* Update the headers for the current IS */
1357:     for (PetscMPIInt j = 0; j < size; j++) { /* Can Optimise this loop too */
1358:       if ((ctr_j = ctr[j])) {
1359:         sbuf1_j            = sbuf1[j];
1360:         k                  = ++sbuf1_j[0];
1361:         sbuf1_j[2 * k]     = ctr_j;
1362:         sbuf1_j[2 * k - 1] = 0;
1363:       }
1364:     }

1366:     /* Now post the sends */
1367:     PetscCall(PetscMalloc1(nrqs, &s_waits1));
1368:     for (PetscMPIInt i = 0; i < nrqs; ++i) PetscCallMPI(MPIU_Isend(sbuf1[pa[i]], w1[pa[i]], MPIU_INT, pa[i], tag1, comm, s_waits1 + i));

1370:     /* Post Receives to capture the buffer size */
1371:     PetscCall(PetscMalloc4(nrqs, &r_status2, nrqr, &s_waits2, nrqs, &r_waits2, nrqr, &s_status2));
1372:     PetscCall(PetscMalloc3(nrqs, &req_source2, nrqs, &rbuf2, nrqs, &rbuf3));

1374:     if (nrqs) rbuf2[0] = tmp + msz;
1375:     for (PetscMPIInt i = 1; i < nrqs; ++i) rbuf2[i] = rbuf2[i - 1] + w1[pa[i - 1]];

1377:     for (PetscMPIInt i = 0; i < nrqs; ++i) PetscCallMPI(MPIU_Irecv(rbuf2[i], w1[pa[i]], MPIU_INT, pa[i], tag2, comm, r_waits2 + i));

1379:     PetscCall(PetscFree2(w1, w2));

1381:     /* Send to other procs the buf size they should allocate */
1382:     /* Receive messages*/
1383:     PetscCall(PetscMalloc1(nrqr, &r_status1));
1384:     PetscCall(PetscMalloc3(nrqr, &sbuf2, nrqr, &req_size, nrqr, &req_source1));

1386:     PetscCallMPI(MPI_Waitall(nrqr, r_waits1, r_status1));
1387:     for (PetscMPIInt i = 0; i < nrqr; ++i) {
1388:       req_size[i] = 0;
1389:       rbuf1_i     = rbuf1[i];
1390:       start       = 2 * rbuf1_i[0] + 1;
1391:       PetscCallMPI(MPI_Get_count(r_status1 + i, MPIU_INT, &end));
1392:       PetscCall(PetscMalloc1(end, &sbuf2[i]));
1393:       sbuf2_i = sbuf2[i];
1394:       for (PetscInt j = start; j < end; j++) {
1395:         k          = rbuf1_i[j] - rstart;
1396:         ncols      = ai[k + 1] - ai[k] + bi[k + 1] - bi[k];
1397:         sbuf2_i[j] = ncols;
1398:         req_size[i] += ncols;
1399:       }
1400:       req_source1[i] = r_status1[i].MPI_SOURCE;

1402:       /* form the header */
1403:       sbuf2_i[0] = req_size[i];
1404:       for (PetscInt j = 1; j < start; j++) sbuf2_i[j] = rbuf1_i[j];

1406:       PetscCallMPI(MPIU_Isend(sbuf2_i, end, MPIU_INT, req_source1[i], tag2, comm, s_waits2 + i));
1407:     }

1409:     PetscCall(PetscFree(r_status1));
1410:     PetscCall(PetscFree(r_waits1));

1412:     /* rbuf2 is received, Post recv column indices a->j */
1413:     PetscCallMPI(MPI_Waitall(nrqs, r_waits2, r_status2));

1415:     PetscCall(PetscMalloc4(nrqs, &r_waits3, nrqr, &s_waits3, nrqs, &r_status3, nrqr, &s_status3));
1416:     for (PetscMPIInt i = 0; i < nrqs; ++i) {
1417:       PetscCall(PetscMalloc1(rbuf2[i][0], &rbuf3[i]));
1418:       req_source2[i] = r_status2[i].MPI_SOURCE;
1419:       PetscCallMPI(MPIU_Irecv(rbuf3[i], rbuf2[i][0], MPIU_INT, req_source2[i], tag3, comm, r_waits3 + i));
1420:     }

1422:     /* Wait on sends1 and sends2 */
1423:     PetscCall(PetscMalloc1(nrqs, &s_status1));
1424:     PetscCallMPI(MPI_Waitall(nrqs, s_waits1, s_status1));
1425:     PetscCall(PetscFree(s_waits1));
1426:     PetscCall(PetscFree(s_status1));

1428:     PetscCallMPI(MPI_Waitall(nrqr, s_waits2, s_status2));
1429:     PetscCall(PetscFree4(r_status2, s_waits2, r_waits2, s_status2));

1431:     /* Now allocate sending buffers for a->j, and send them off */
1432:     PetscCall(PetscMalloc1(nrqr, &sbuf_aj));
1433:     jcnt = 0;
1434:     for (PetscMPIInt i = 0; i < nrqr; i++) jcnt += req_size[i];
1435:     if (nrqr) PetscCall(PetscMalloc1(jcnt, &sbuf_aj[0]));
1436:     for (PetscMPIInt i = 1; i < nrqr; i++) sbuf_aj[i] = sbuf_aj[i - 1] + req_size[i - 1];

1438:     for (PetscMPIInt i = 0; i < nrqr; i++) { /* for each requested message */
1439:       rbuf1_i   = rbuf1[i];
1440:       sbuf_aj_i = sbuf_aj[i];
1441:       ct1       = 2 * rbuf1_i[0] + 1;
1442:       ct2       = 0;
1443:       /* max1=rbuf1_i[0]; PetscCheck(max1 == 1,PETSC_COMM_SELF,PETSC_ERR_PLIB,"max1 %d != 1",max1); */

1445:       kmax = rbuf1[i][2];
1446:       for (PetscInt k = 0; k < kmax; k++, ct1++) { /* for each row */
1447:         row    = rbuf1_i[ct1] - rstart;
1448:         nzA    = ai[row + 1] - ai[row];
1449:         nzB    = bi[row + 1] - bi[row];
1450:         ncols  = nzA + nzB;
1451:         cworkA = PetscSafePointerPlusOffset(aj, ai[row]);
1452:         cworkB = PetscSafePointerPlusOffset(bj, bi[row]);

1454:         /* load the column indices for this row into cols*/
1455:         cols = PetscSafePointerPlusOffset(sbuf_aj_i, ct2);

1457:         lwrite = 0;
1458:         for (PetscInt l = 0; l < nzB; l++) {
1459:           if ((ctmp = bmap[cworkB[l]]) < cstart) cols[lwrite++] = ctmp;
1460:         }
1461:         for (PetscInt l = 0; l < nzA; l++) cols[lwrite++] = cstart + cworkA[l];
1462:         for (PetscInt l = 0; l < nzB; l++) {
1463:           if ((ctmp = bmap[cworkB[l]]) >= cend) cols[lwrite++] = ctmp;
1464:         }

1466:         ct2 += ncols;
1467:       }
1468:       PetscCallMPI(MPIU_Isend(sbuf_aj_i, req_size[i], MPIU_INT, req_source1[i], tag3, comm, s_waits3 + i));
1469:     }

1471:     /* create column map (cmap): global col of C -> local col of submat */
1472: #if PetscDefined(USE_CTABLE)
1473:     if (!allcolumns) {
1474:       PetscCall(PetscHMapICreateWithSize(ncol, &cmap));
1475:       PetscCall(PetscCalloc1(C->cmap->n, &cmap_loc));
1476:       for (PetscInt j = 0; j < ncol; j++) { /* use array cmap_loc[] for local col indices */
1477:         if (icol[j] >= cstart && icol[j] < cend) {
1478:           cmap_loc[icol[j] - cstart] = j + 1;
1479:         } else { /* use PetscHMapI for non-local col indices */
1480:           PetscCall(PetscHMapISet(cmap, icol[j] + 1, j + 1));
1481:         }
1482:       }
1483:     } else {
1484:       cmap     = NULL;
1485:       cmap_loc = NULL;
1486:     }
1487:     PetscCall(PetscCalloc1(C->rmap->n, &rmap_loc));
1488: #else
1489:     if (!allcolumns) {
1490:       PetscCall(PetscCalloc1(C->cmap->N, &cmap));
1491:       for (PetscInt j = 0; j < ncol; j++) cmap[icol[j]] = j + 1;
1492:     } else {
1493:       cmap = NULL;
1494:     }
1495: #endif

1497:     /* Create lens for MatSeqAIJSetPreallocation() */
1498:     PetscCall(PetscCalloc1(nrow, &lens));

1500:     /* Compute lens from local part of C */
1501:     for (PetscInt j = 0; j < nrow; j++) {
1502:       row = irow[j];
1503:       if (row2proc[j] == rank) {
1504:         /* diagonal part A = c->A */
1505:         ncols = ai[row - rstart + 1] - ai[row - rstart];
1506:         cols  = PetscSafePointerPlusOffset(aj, ai[row - rstart]);
1507:         if (!allcolumns) {
1508:           for (PetscInt k = 0; k < ncols; k++) {
1509: #if PetscDefined(USE_CTABLE)
1510:             tcol = cmap_loc[cols[k]];
1511: #else
1512:             tcol = cmap[cols[k] + cstart];
1513: #endif
1514:             if (tcol) lens[j]++;
1515:           }
1516:         } else { /* allcolumns */
1517:           lens[j] = ncols;
1518:         }

1520:         /* off-diagonal part B = c->B */
1521:         ncols = bi[row - rstart + 1] - bi[row - rstart];
1522:         cols  = PetscSafePointerPlusOffset(bj, bi[row - rstart]);
1523:         if (!allcolumns) {
1524:           for (PetscInt k = 0; k < ncols; k++) {
1525: #if PetscDefined(USE_CTABLE)
1526:             PetscCall(PetscHMapIGetWithDefault(cmap, bmap[cols[k]] + 1, 0, &tcol));
1527: #else
1528:             tcol = cmap[bmap[cols[k]]];
1529: #endif
1530:             if (tcol) lens[j]++;
1531:           }
1532:         } else { /* allcolumns */
1533:           lens[j] += ncols;
1534:         }
1535:       }
1536:     }

1538:     /* Create row map (rmap): global row of C -> local row of submat */
1539: #if PetscDefined(USE_CTABLE)
1540:     PetscCall(PetscHMapICreateWithSize(nrow, &rmap));
1541:     for (PetscInt j = 0; j < nrow; j++) {
1542:       row = irow[j];
1543:       if (row2proc[j] == rank) { /* a local row */
1544:         rmap_loc[row - rstart] = j;
1545:       } else {
1546:         PetscCall(PetscHMapISet(rmap, irow[j] + 1, j + 1));
1547:       }
1548:     }
1549: #else
1550:     PetscCall(PetscCalloc1(C->rmap->N, &rmap));
1551:     for (PetscInt j = 0; j < nrow; j++) rmap[irow[j]] = j;
1552: #endif

1554:     /* Update lens from offproc data */
1555:     /* recv a->j is done */
1556:     PetscCallMPI(MPI_Waitall(nrqs, r_waits3, r_status3));
1557:     for (PetscMPIInt i = 0; i < nrqs; i++) {
1558:       sbuf1_i = sbuf1[pa[i]];
1559:       /* jmax    = sbuf1_i[0]; PetscCheck(jmax == 1,PETSC_COMM_SELF,PETSC_ERR_PLIB,"jmax !=1"); */
1560:       ct1     = 2 + 1;
1561:       ct2     = 0;
1562:       rbuf2_i = rbuf2[i]; /* received length of C->j */
1563:       rbuf3_i = rbuf3[i]; /* received C->j */

1565:       /* is_no  = sbuf1_i[2*j-1]; PetscCheck(is_no == 0,PETSC_COMM_SELF,PETSC_ERR_PLIB,"is_no !=0"); */
1566:       max1 = sbuf1_i[2];
1567:       for (PetscInt k = 0; k < max1; k++, ct1++) {
1568: #if PetscDefined(USE_CTABLE)
1569:         PetscCall(PetscHMapIGetWithDefault(rmap, sbuf1_i[ct1] + 1, 0, &row));
1570:         row--;
1571:         PetscCheck(row >= 0, PETSC_COMM_SELF, PETSC_ERR_PLIB, "row not found in table");
1572: #else
1573:         row = rmap[sbuf1_i[ct1]]; /* the row index in submat */
1574: #endif
1575:         /* Now, store row index of submat in sbuf1_i[ct1] */
1576:         sbuf1_i[ct1] = row;

1578:         nnz = rbuf2_i[ct1];
1579:         if (!allcolumns) {
1580:           for (PetscMPIInt l = 0; l < nnz; l++, ct2++) {
1581: #if PetscDefined(USE_CTABLE)
1582:             if (rbuf3_i[ct2] >= cstart && rbuf3_i[ct2] < cend) {
1583:               tcol = cmap_loc[rbuf3_i[ct2] - cstart];
1584:             } else {
1585:               PetscCall(PetscHMapIGetWithDefault(cmap, rbuf3_i[ct2] + 1, 0, &tcol));
1586:             }
1587: #else
1588:             tcol = cmap[rbuf3_i[ct2]]; /* column index in submat */
1589: #endif
1590:             if (tcol) lens[row]++;
1591:           }
1592:         } else { /* allcolumns */
1593:           lens[row] += nnz;
1594:         }
1595:       }
1596:     }
1597:     PetscCallMPI(MPI_Waitall(nrqr, s_waits3, s_status3));
1598:     PetscCall(PetscFree4(r_waits3, s_waits3, r_status3, s_status3));

1600:     /* Create the submatrices */
1601:     PetscCall(MatCreate(PETSC_COMM_SELF, &submat));
1602:     PetscCall(MatSetSizes(submat, nrow, ncol, PETSC_DETERMINE, PETSC_DETERMINE));

1604:     PetscCall(ISGetBlockSize(isrow[0], &ib));
1605:     PetscCall(ISGetBlockSize(iscol[0], &jb));
1606:     if (ib > 1 || jb > 1) PetscCall(MatSetBlockSizes(submat, ib, jb));
1607:     PetscCall(MatSetType(submat, ((PetscObject)A)->type_name));
1608:     PetscCall(MatSetOption(submat, MAT_STRUCTURE_ONLY, C->structure_only));
1609:     PetscCall(MatSeqAIJSetPreallocation(submat, 0, lens));

1611:     /* create struct Mat_SubSppt and attached it to submat */
1612:     PetscCall(PetscNew(&smatis1));
1613:     subc            = (Mat_SeqAIJ *)submat->data;
1614:     subc->submatis1 = smatis1;

1616:     smatis1->id          = 0;
1617:     smatis1->nrqs        = nrqs;
1618:     smatis1->nrqr        = nrqr;
1619:     smatis1->rbuf1       = rbuf1;
1620:     smatis1->rbuf2       = rbuf2;
1621:     smatis1->rbuf3       = rbuf3;
1622:     smatis1->sbuf2       = sbuf2;
1623:     smatis1->req_source2 = req_source2;

1625:     smatis1->sbuf1 = sbuf1;
1626:     smatis1->ptr   = ptr;
1627:     smatis1->tmp   = tmp;
1628:     smatis1->ctr   = ctr;

1630:     smatis1->pa          = pa;
1631:     smatis1->req_size    = req_size;
1632:     smatis1->req_source1 = req_source1;

1634:     smatis1->allcolumns = allcolumns;
1635:     smatis1->singleis   = PETSC_TRUE;
1636:     smatis1->row2proc   = row2proc;
1637:     smatis1->rmap       = rmap;
1638:     smatis1->cmap       = cmap;
1639: #if PetscDefined(USE_CTABLE)
1640:     smatis1->rmap_loc = rmap_loc;
1641:     smatis1->cmap_loc = cmap_loc;
1642: #endif

1644:     submat->factortype = C->factortype;

1646:     /* compute rmax */
1647:     rmax = 0;
1648:     for (PetscMPIInt i = 0; i < nrow; i++) rmax = PetscMax(rmax, lens[i]);

1650:   } else { /* scall == MAT_REUSE_MATRIX */
1651:     submat = submats[0];
1652:     PetscCheck(submat->rmap->n == nrow && submat->cmap->n == ncol, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Cannot reuse matrix. wrong size");

1654:     subc        = (Mat_SeqAIJ *)submat->data;
1655:     rmax        = subc->rmax;
1656:     smatis1     = subc->submatis1;
1657:     nrqs        = smatis1->nrqs;
1658:     nrqr        = smatis1->nrqr;
1659:     rbuf1       = smatis1->rbuf1;
1660:     rbuf2       = smatis1->rbuf2;
1661:     rbuf3       = smatis1->rbuf3;
1662:     req_source2 = smatis1->req_source2;

1664:     sbuf1 = smatis1->sbuf1;
1665:     sbuf2 = smatis1->sbuf2;
1666:     ptr   = smatis1->ptr;
1667:     tmp   = smatis1->tmp;
1668:     ctr   = smatis1->ctr;

1670:     pa          = smatis1->pa;
1671:     req_size    = smatis1->req_size;
1672:     req_source1 = smatis1->req_source1;

1674:     allcolumns = smatis1->allcolumns;
1675:     row2proc   = smatis1->row2proc;
1676:     rmap       = smatis1->rmap;
1677:     cmap       = smatis1->cmap;
1678: #if PetscDefined(USE_CTABLE)
1679:     rmap_loc = smatis1->rmap_loc;
1680:     cmap_loc = smatis1->cmap_loc;
1681: #endif
1682:     PetscCall(MatGetNonzeroState(submat, &submat_nonzerostate));
1683:     // User changes to the submatrix graph invalidate the cached CSR positions.
1684:     direct_csr_reuse = (PetscBool)(iscolsorted && !allcolumns && submat_nonzerostate == smatis1->nonzerostate);
1685:     // Build owned-row maps only when reuse first needs them and the initial graph still matches.
1686:     if (direct_csr_reuse && !smatis1->csrcached) {
1687:       PetscInt nlocal_a = 0, nlocal_b = 0;

1689:       for (PetscInt j = 0; j < nrow; j++) {
1690:         row = irow[j];
1691:         if (row2proc[j] != rank) continue;
1692:         Crow = row - rstart;
1693:         for (PetscInt k = ai[Crow]; k < ai[Crow + 1]; k++) {
1694: #if PetscDefined(USE_CTABLE)
1695:           tcol = cmap_loc[aj[k]];
1696: #else
1697:           tcol = cmap[aj[k] + cstart];
1698: #endif
1699:           if (tcol) nlocal_a++;
1700:         }
1701:         for (PetscInt k = bi[Crow]; k < bi[Crow + 1]; k++) {
1702: #if PetscDefined(USE_CTABLE)
1703:           PetscCall(PetscHMapIGetWithDefault(cmap, bmap[bj[k]] + 1, 0, &tcol));
1704: #else
1705:           tcol = cmap[bmap[bj[k]]];
1706: #endif
1707:           if (tcol) nlocal_b++;
1708:         }
1709:       }
1710:       PetscCall(PetscMalloc2(nlocal_a, &smatis1->local_a_parent, nlocal_a, &smatis1->local_a_sub));
1711:       PetscCall(PetscMalloc2(nlocal_b, &smatis1->local_b_parent, nlocal_b, &smatis1->local_b_sub));
1712:       smatis1->nlocal_a = 0;
1713:       smatis1->nlocal_b = 0;
1714:       for (PetscInt j = 0; j < nrow; j++) {
1715:         PetscInt subrow_start, subrow_nnz;

1717:         row = irow[j];
1718:         if (row2proc[j] != rank) continue;
1719:         Crow = row - rstart;
1720: #if PetscDefined(USE_CTABLE)
1721:         row = rmap_loc[Crow];
1722: #else
1723:         row = rmap[row];
1724: #endif
1725:         subrow_start = subc->i[row];
1726:         subrow_nnz   = subc->i[row + 1] - subrow_start;
1727:         for (PetscInt k = ai[Crow]; k < ai[Crow + 1]; k++) {
1728:           PetscInt loc;

1730: #if PetscDefined(USE_CTABLE)
1731:           tcol = cmap_loc[aj[k]];
1732: #else
1733:           tcol = cmap[aj[k] + cstart];
1734: #endif
1735:           if (!tcol) continue;
1736:           PetscCall(PetscFindInt(tcol - 1, subrow_nnz, subc->j + subrow_start, &loc));
1737:           PetscCheck(loc >= 0, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Owned diagonal entry is missing from reused submatrix graph");
1738:           smatis1->local_a_parent[smatis1->nlocal_a] = k;
1739:           smatis1->local_a_sub[smatis1->nlocal_a++]  = subrow_start + loc;
1740:         }
1741:         for (PetscInt k = bi[Crow]; k < bi[Crow + 1]; k++) {
1742:           PetscInt loc;

1744: #if PetscDefined(USE_CTABLE)
1745:           PetscCall(PetscHMapIGetWithDefault(cmap, bmap[bj[k]] + 1, 0, &tcol));
1746: #else
1747:           tcol = cmap[bmap[bj[k]]];
1748: #endif
1749:           if (!tcol) continue;
1750:           PetscCall(PetscFindInt(tcol - 1, subrow_nnz, subc->j + subrow_start, &loc));
1751:           PetscCheck(loc >= 0, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Owned off-diagonal entry is missing from reused submatrix graph");
1752:           smatis1->local_b_parent[smatis1->nlocal_b] = k;
1753:           smatis1->local_b_sub[smatis1->nlocal_b++]  = subrow_start + loc;
1754:         }
1755:       }
1756:       PetscCheck(smatis1->nlocal_a == nlocal_a && smatis1->nlocal_b == nlocal_b, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Cached submatrix CSR map size changed during construction");
1757:       smatis1->csrcached = PETSC_TRUE;
1758:     }
1759:   }

1761:   /* Post recv matrix values */
1762:   PetscCall(PetscMalloc1(rmax, &subcols));
1763:   if (!C->structure_only) {
1764:     PetscCall(PetscMalloc2(nrqs, &rbuf4, rmax, &subvals));
1765:     PetscCall(PetscMalloc4(nrqs, &r_waits4, nrqr, &s_waits4, nrqs, &r_status4, nrqr, &s_status4));
1766:     PetscCall(PetscObjectGetNewTag((PetscObject)C, &tag4));
1767:     for (PetscMPIInt i = 0; i < nrqs; ++i) {
1768:       PetscCall(PetscMalloc1(rbuf2[i][0], &rbuf4[i]));
1769:       PetscCallMPI(MPIU_Irecv(rbuf4[i], rbuf2[i][0], MPIU_SCALAR, req_source2[i], tag4, comm, r_waits4 + i));
1770:     }

1772:     /* Allocate sending buffers for a->a, and send them off */
1773:     PetscCall(PetscMalloc1(nrqr, &sbuf_aa));
1774:     jcnt = 0;
1775:     for (PetscMPIInt i = 0; i < nrqr; i++) jcnt += req_size[i];
1776:     if (nrqr) PetscCall(PetscMalloc1(jcnt, &sbuf_aa[0]));
1777:     for (PetscMPIInt i = 1; i < nrqr; i++) sbuf_aa[i] = sbuf_aa[i - 1] + req_size[i - 1];

1779:     for (PetscMPIInt i = 0; i < nrqr; i++) {
1780:       rbuf1_i   = rbuf1[i];
1781:       sbuf_aa_i = sbuf_aa[i];
1782:       ct1       = 2 * rbuf1_i[0] + 1;
1783:       ct2       = 0;
1784:       /* max1=rbuf1_i[0]; PetscCheck(max1 == 1,PETSC_COMM_SELF,PETSC_ERR_PLIB,"max1 !=1"); */

1786:       kmax = rbuf1_i[2];
1787:       for (PetscInt k = 0; k < kmax; k++, ct1++) {
1788:         row    = rbuf1_i[ct1] - rstart;
1789:         nzA    = ai[row + 1] - ai[row];
1790:         nzB    = bi[row + 1] - bi[row];
1791:         ncols  = nzA + nzB;
1792:         cworkB = PetscSafePointerPlusOffset(bj, bi[row]);
1793:         vworkA = PetscSafePointerPlusOffset(a_a, ai[row]);
1794:         vworkB = PetscSafePointerPlusOffset(b_a, bi[row]);

1796:         /* load the column values for this row into vals*/
1797:         vals = PetscSafePointerPlusOffset(sbuf_aa_i, ct2);

1799:         lwrite = 0;
1800:         for (PetscInt l = 0; l < nzB; l++) {
1801:           if (bmap[cworkB[l]] < cstart) vals[lwrite++] = vworkB[l];
1802:         }
1803:         for (PetscInt l = 0; l < nzA; l++) vals[lwrite++] = vworkA[l];
1804:         for (PetscInt l = 0; l < nzB; l++) {
1805:           if (bmap[cworkB[l]] >= cend) vals[lwrite++] = vworkB[l];
1806:         }

1808:         ct2 += ncols;
1809:       }
1810:       PetscCallMPI(MPIU_Isend(sbuf_aa_i, req_size[i], MPIU_SCALAR, req_source1[i], tag4, comm, s_waits4 + i));
1811:     }
1812:   }

1814:   /* Assemble submat */
1815:   /* First assemble the local rows */
1816:   if (direct_csr_reuse) {
1817:     PetscCall(MatSeqAIJGetArray(submat, &suba));
1818:     for (PetscInt j = 0; j < smatis1->nlocal_a; j++) suba[smatis1->local_a_sub[j]] = a_a[smatis1->local_a_parent[j]];
1819:     for (PetscInt j = 0; j < smatis1->nlocal_b; j++) suba[smatis1->local_b_sub[j]] = b_a[smatis1->local_b_parent[j]];
1820:   } else {
1821:     for (PetscInt j = 0; j < nrow; j++) {
1822:       row = irow[j];
1823:       if (row2proc[j] != rank) continue;
1824:       Crow = row - rstart; /* local row index of C */
1825: #if PetscDefined(USE_CTABLE)
1826:       row = rmap_loc[Crow]; /* row index of submat */
1827: #else
1828:       row = rmap[row];
1829: #endif

1831:       if (allcolumns) {
1832:         PetscInt ncol = 0;

1834:         /* diagonal part A = c->A */
1835:         ncols = ai[Crow + 1] - ai[Crow];
1836:         cols  = PetscSafePointerPlusOffset(aj, ai[Crow]);
1837:         vals  = PetscSafePointerPlusOffset(a_a, ai[Crow]);
1838:         for (PetscInt k = 0; k < ncols; k++, ncol++) {
1839:           subcols[ncol] = cols[k] + cstart;
1840:           if (!C->structure_only) subvals[ncol] = vals[k];
1841:         }

1843:         /* off-diagonal part B = c->B */
1844:         ncols = bi[Crow + 1] - bi[Crow];
1845:         cols  = PetscSafePointerPlusOffset(bj, bi[Crow]);
1846:         vals  = PetscSafePointerPlusOffset(b_a, bi[Crow]);
1847:         for (PetscInt k = 0; k < ncols; k++, ncol++) {
1848:           subcols[ncol] = bmap[cols[k]];
1849:           if (!C->structure_only) subvals[ncol] = vals[k];
1850:         }

1852:         PetscCall(MatSetValues_SeqAIJ(submat, 1, &row, ncol, subcols, subvals, INSERT_VALUES));

1854:       } else { /* !allcolumns */
1855:         PetscInt ncol = 0;

1857: #if PetscDefined(USE_CTABLE)
1858:         /* diagonal part A = c->A */
1859:         ncols = ai[Crow + 1] - ai[Crow];
1860:         cols  = PetscSafePointerPlusOffset(aj, ai[Crow]);
1861:         vals  = PetscSafePointerPlusOffset(a_a, ai[Crow]);
1862:         for (PetscInt k = 0; k < ncols; k++) {
1863:           tcol = cmap_loc[cols[k]];
1864:           if (tcol) {
1865:             subcols[ncol] = --tcol;
1866:             if (!C->structure_only) subvals[ncol] = vals[k];
1867:             ncol++;
1868:           }
1869:         }

1871:         /* off-diagonal part B = c->B */
1872:         ncols = bi[Crow + 1] - bi[Crow];
1873:         cols  = PetscSafePointerPlusOffset(bj, bi[Crow]);
1874:         vals  = PetscSafePointerPlusOffset(b_a, bi[Crow]);
1875:         for (PetscInt k = 0; k < ncols; k++) {
1876:           PetscCall(PetscHMapIGetWithDefault(cmap, bmap[cols[k]] + 1, 0, &tcol));
1877:           if (tcol) {
1878:             subcols[ncol] = --tcol;
1879:             if (!C->structure_only) subvals[ncol] = vals[k];
1880:             ncol++;
1881:           }
1882:         }
1883: #else
1884:         /* diagonal part A = c->A */
1885:         ncols = ai[Crow + 1] - ai[Crow];
1886:         cols  = aj + ai[Crow];
1887:         vals  = PetscSafePointerPlusOffset(a_a, ai[Crow]);
1888:         for (PetscInt k = 0; k < ncols; k++) {
1889:           tcol = cmap[cols[k] + cstart];
1890:           if (tcol) {
1891:             subcols[ncol] = --tcol;
1892:             if (!C->structure_only) subvals[ncol] = vals[k];
1893:             ncol++;
1894:           }
1895:         }

1897:         /* off-diagonal part B = c->B */
1898:         ncols = bi[Crow + 1] - bi[Crow];
1899:         cols  = bj + bi[Crow];
1900:         vals  = PetscSafePointerPlusOffset(b_a, bi[Crow]);
1901:         for (PetscInt k = 0; k < ncols; k++) {
1902:           tcol = cmap[bmap[cols[k]]];
1903:           if (tcol) {
1904:             subcols[ncol] = --tcol;
1905:             if (!C->structure_only) subvals[ncol] = vals[k];
1906:             ncol++;
1907:           }
1908:         }
1909: #endif
1910:         PetscCall(MatSetValues_SeqAIJ(submat, 1, &row, ncol, subcols, subvals, INSERT_VALUES));
1911:       }
1912:     }
1913:   }

1915:   /* Now assemble the off-proc rows */
1916:   for (PetscMPIInt i = 0; i < nrqs; i++) { /* for each requested message */
1917:     /* recv values from other processes */
1918:     if (!C->structure_only) PetscCallMPI(MPI_Waitany(nrqs, r_waits4, &idex, r_status4 + i));
1919:     else idex = i;
1920:     sbuf1_i = sbuf1[pa[idex]];
1921:     /* jmax    = sbuf1_i[0]; PetscCheck(jmax == 1,PETSC_COMM_SELF,PETSC_ERR_PLIB,"jmax %d != 1",jmax); */
1922:     ct1     = 2 + 1;
1923:     ct2     = 0;                                      /* count of received C->j */
1924:     ct3     = 0;                                      /* count of received C->j that will be inserted into submat */
1925:     rbuf2_i = rbuf2[idex];                            /* int** received length of C->j from other processes */
1926:     rbuf3_i = rbuf3[idex];                            /* int** received C->j from other processes */
1927:     rbuf4_i = C->structure_only ? NULL : rbuf4[idex]; /* scalar** received C->a from other processes */

1929:     /* is_no = sbuf1_i[2*j-1]; PetscCheck(is_no == 0,PETSC_COMM_SELF,PETSC_ERR_PLIB,"is_no !=0"); */
1930:     max1 = sbuf1_i[2];                           /* num of rows */
1931:     for (PetscInt k = 0; k < max1; k++, ct1++) { /* for each recved row */
1932:       row = sbuf1_i[ct1];                        /* row index of submat */
1933:       if (!allcolumns) {
1934:         idex = 0;
1935:         if (scall == MAT_INITIAL_MATRIX || !iscolsorted) {
1936:           nnz = rbuf2_i[ct1];                         /* num of C entries in this row */
1937:           for (PetscInt l = 0; l < nnz; l++, ct2++) { /* for each recved column */
1938: #if PetscDefined(USE_CTABLE)
1939:             if (rbuf3_i[ct2] >= cstart && rbuf3_i[ct2] < cend) {
1940:               tcol = cmap_loc[rbuf3_i[ct2] - cstart];
1941:             } else {
1942:               PetscCall(PetscHMapIGetWithDefault(cmap, rbuf3_i[ct2] + 1, 0, &tcol));
1943:             }
1944: #else
1945:             tcol = cmap[rbuf3_i[ct2]];
1946: #endif
1947:             if (tcol) {
1948:               subcols[idex] = --tcol; /* may not be sorted */
1949:               if (!C->structure_only) subvals[idex] = rbuf4_i[ct2];
1950:               idex++;

1952:               /* We receive an entire column of C, but a subset of it needs to be inserted into submat.
1953:                For reuse, we replace received C->j with index that should be inserted to submat */
1954:               if (iscolsorted) rbuf3_i[ct3++] = ct2;
1955:             }
1956:           }
1957:           PetscCall(MatSetValues_SeqAIJ(submat, 1, &row, idex, subcols, subvals, INSERT_VALUES));
1958:         } else { /* scall == MAT_REUSE_MATRIX */
1959:           submat = submats[0];
1960:           subc   = (Mat_SeqAIJ *)submat->data;

1962:           nnz = subc->i[row + 1] - subc->i[row]; /* num of submat entries in this row */
1963:           for (PetscInt l = 0; l < nnz; l++) {
1964:             ct2 = rbuf3_i[ct3++]; /* index of rbuf4_i[] which needs to be inserted into submat */
1965:             if (direct_csr_reuse) suba[subc->i[row] + idex++] = rbuf4_i[ct2];
1966:             else subvals[idex++] = rbuf4_i[ct2];
1967:           }
1968:           if (!direct_csr_reuse) {
1969:             bj = subc->j + subc->i[row]; /* sorted column indices */
1970:             PetscCall(MatSetValues_SeqAIJ(submat, 1, &row, nnz, bj, subvals, INSERT_VALUES));
1971:           }
1972:         }
1973:       } else {              /* allcolumns */
1974:         nnz = rbuf2_i[ct1]; /* num of C entries in this row */
1975:         PetscCall(MatSetValues_SeqAIJ(submat, 1, &row, nnz, PetscSafePointerPlusOffset(rbuf3_i, ct2), PetscSafePointerPlusOffset(rbuf4_i, ct2), INSERT_VALUES));
1976:         ct2 += nnz;
1977:       }
1978:     }
1979:   }

1981:   /* sending a->a are done */
1982:   if (!C->structure_only) {
1983:     PetscCallMPI(MPI_Waitall(nrqr, s_waits4, s_status4));
1984:     PetscCall(PetscFree4(r_waits4, s_waits4, r_status4, s_status4));
1985:   }

1987:   if (direct_csr_reuse) PetscCall(MatSeqAIJRestoreArray(submat, &suba));
1988:   PetscCall(MatAssemblyBegin(submat, MAT_FINAL_ASSEMBLY));
1989:   PetscCall(MatAssemblyEnd(submat, MAT_FINAL_ASSEMBLY));
1990:   // Preserve the initial graph state even when no reuse maps have been built.
1991:   if (scall == MAT_INITIAL_MATRIX && !C->structure_only && iscolsorted && !allcolumns) PetscCall(MatGetNonzeroState(submat, &smatis1->nonzerostate));
1992:   submats[0] = submat;

1994:   /* Restore the indices */
1995:   PetscCall(ISRestoreIndices(isrow[0], &irow));
1996:   if (!allcolumns) PetscCall(ISRestoreIndices(iscol[0], &icol));

1998:   /* Destroy allocated memory */
1999:   PetscCall(PetscFree(subcols));
2000:   if (!C->structure_only) {
2001:     for (PetscMPIInt i = 0; i < nrqs; ++i) PetscCall(PetscFree(rbuf4[i]));
2002:     PetscCall(PetscFree2(rbuf4, subvals));
2003:     if (sbuf_aa) {
2004:       PetscCall(PetscFree(sbuf_aa[0]));
2005:       PetscCall(PetscFree(sbuf_aa));
2006:     }
2007:   }

2009:   if (scall == MAT_INITIAL_MATRIX) {
2010:     PetscCall(PetscFree(lens));
2011:     if (sbuf_aj) {
2012:       PetscCall(PetscFree(sbuf_aj[0]));
2013:       PetscCall(PetscFree(sbuf_aj));
2014:     }
2015:   }
2016:   PetscCall(MatSeqAIJRestoreArrayRead(A, (const PetscScalar **)&a_a));
2017:   PetscCall(MatSeqAIJRestoreArrayRead(B, (const PetscScalar **)&b_a));
2018:   PetscFunctionReturn(PETSC_SUCCESS);
2019: }

2021: static PetscErrorCode MatCreateSubMatrices_MPIAIJ_SingleIS(Mat C, PetscInt ismax, const IS isrow[], const IS iscol[], MatReuse scall, Mat *submat[])
2022: {
2023:   PetscInt  ncol;
2024:   PetscBool colflag, allcolumns = PETSC_FALSE;

2026:   PetscFunctionBegin;
2027:   /* Allocate memory to hold all the submatrices */
2028:   if (scall == MAT_INITIAL_MATRIX) PetscCall(PetscCalloc1(2, submat));

2030:   /* Check for special case: each processor gets entire matrix columns */
2031:   PetscCall(ISIdentity(iscol[0], &colflag));
2032:   PetscCall(ISGetLocalSize(iscol[0], &ncol));
2033:   if (colflag && ncol == C->cmap->N) allcolumns = PETSC_TRUE;

2035:   PetscCall(MatCreateSubMatrices_MPIAIJ_SingleIS_Local(C, ismax, isrow, iscol, scall, allcolumns, *submat));
2036:   PetscFunctionReturn(PETSC_SUCCESS);
2037: }

2039: PetscErrorCode MatCreateSubMatrices_MPIAIJ(Mat C, PetscInt ismax, const IS isrow[], const IS iscol[], MatReuse scall, Mat *submat[])
2040: {
2041:   PetscInt     nmax, nstages = 0, max_no, nrow, ncol, out[2];
2042:   PetscBool    rowflag, colflag, wantallmatrix = PETSC_FALSE;
2043:   Mat_SeqAIJ  *subc;
2044:   Mat_SubSppt *smat;

2046:   PetscFunctionBegin;
2047:   /* Check for special case: each processor has a single IS */
2048:   if (C->submat_singleis) { /* flag is set in PCSetUp_ASM() to skip MPI_Allreduce() */
2049:     PetscCall(MatCreateSubMatrices_MPIAIJ_SingleIS(C, ismax, isrow, iscol, scall, submat));
2050:     C->submat_singleis = PETSC_FALSE; /* resume its default value in case C will be used for non-single IS */
2051:     PetscFunctionReturn(PETSC_SUCCESS);
2052:   }

2054:   /* Collect global wantallmatrix and nstages */
2055:   if (!C->cmap->N) nmax = 20 * 1000000 / sizeof(PetscInt);
2056:   else nmax = 20 * 1000000 / (C->cmap->N * sizeof(PetscInt));
2057:   if (!nmax) nmax = 1;

2059:   if (scall == MAT_INITIAL_MATRIX) {
2060:     /* Collect global wantallmatrix and nstages */
2061:     if (ismax == 1 && C->rmap->N == C->cmap->N) {
2062:       PetscCall(ISIdentity(*isrow, &rowflag));
2063:       PetscCall(ISIdentity(*iscol, &colflag));
2064:       PetscCall(ISGetLocalSize(*isrow, &nrow));
2065:       PetscCall(ISGetLocalSize(*iscol, &ncol));
2066:       if (rowflag && colflag && nrow == C->rmap->N && ncol == C->cmap->N) {
2067:         wantallmatrix = PETSC_TRUE;

2069:         PetscCall(PetscOptionsGetBool(((PetscObject)C)->options, ((PetscObject)C)->prefix, "-use_fast_submatrix", &wantallmatrix, NULL));
2070:       }
2071:     }

2073:     /* Determine the number of stages through which submatrices are done
2074:        Each stage will extract nmax submatrices.
2075:        nmax is determined by the matrix column dimension.
2076:        If the original matrix has 20M columns, only one submatrix per stage is allowed, etc.
2077:     */
2078:     nstages = ismax / nmax + ((ismax % nmax) ? 1 : 0); /* local nstages */

2080:     out[0] = -1 * (PetscInt)wantallmatrix;
2081:     out[1] = nstages;
2082:     PetscCallMPI(MPIU_Allreduce(MPI_IN_PLACE, out, 2, MPIU_INT, MPI_MAX, PetscObjectComm((PetscObject)C)));
2083:     wantallmatrix = (PetscBool)(-out[0]);
2084:     nstages       = out[1]; /* Make sure every processor loops through the global nstages */

2086:   } else { /* MAT_REUSE_MATRIX */
2087:     if (ismax) {
2088:       subc = (Mat_SeqAIJ *)(*submat)[0]->data;
2089:       smat = subc->submatis1;
2090:     } else { /* (*submat)[0] is a dummy matrix */
2091:       smat = (Mat_SubSppt *)(*submat)[0]->data;
2092:     }
2093:     if (!smat) {
2094:       /* smat is not generated by MatCreateSubMatrix_MPIAIJ_All(...,MAT_INITIAL_MATRIX,...) */
2095:       wantallmatrix = PETSC_TRUE;
2096:     } else if (smat->singleis) {
2097:       PetscCall(MatCreateSubMatrices_MPIAIJ_SingleIS(C, ismax, isrow, iscol, scall, submat));
2098:       PetscFunctionReturn(PETSC_SUCCESS);
2099:     } else {
2100:       nstages = smat->nstages;
2101:     }
2102:   }

2104:   if (wantallmatrix) {
2105:     PetscCall(MatCreateSubMatrix_MPIAIJ_All(C, MAT_GET_VALUES, scall, submat));
2106:     PetscFunctionReturn(PETSC_SUCCESS);
2107:   }

2109:   /* Allocate memory to hold all the submatrices and dummy submatrices */
2110:   if (scall == MAT_INITIAL_MATRIX) PetscCall(PetscCalloc1(ismax + nstages, submat));

2112:   for (PetscInt i = 0, pos = 0; i < nstages; i++) {
2113:     if (pos + nmax <= ismax) max_no = nmax;
2114:     else if (pos >= ismax) max_no = 0;
2115:     else max_no = ismax - pos;

2117:     PetscCall(MatCreateSubMatrices_MPIAIJ_Local(C, max_no, PetscSafePointerPlusOffset(isrow, pos), PetscSafePointerPlusOffset(iscol, pos), scall, *submat + pos));
2118:     if (!max_no) {
2119:       if (scall == MAT_INITIAL_MATRIX) { /* submat[pos] is a dummy matrix */
2120:         smat          = (Mat_SubSppt *)(*submat)[pos]->data;
2121:         smat->nstages = nstages;
2122:       }
2123:       pos++; /* advance to next dummy matrix if any */
2124:     } else pos += max_no;
2125:   }

2127:   if (ismax && scall == MAT_INITIAL_MATRIX) {
2128:     /* save nstages for reuse */
2129:     subc          = (Mat_SeqAIJ *)(*submat)[0]->data;
2130:     smat          = subc->submatis1;
2131:     smat->nstages = nstages;
2132:   }
2133:   PetscFunctionReturn(PETSC_SUCCESS);
2134: }

2136: PetscErrorCode MatCreateSubMatrices_MPIAIJ_Local(Mat C, PetscInt ismax, const IS isrow[], const IS iscol[], MatReuse scall, Mat *submats)
2137: {
2138:   Mat_MPIAIJ      *c = (Mat_MPIAIJ *)C->data;
2139:   Mat              A = c->A;
2140:   Mat_SeqAIJ      *a = (Mat_SeqAIJ *)A->data, *b = (Mat_SeqAIJ *)c->B->data, *subc;
2141:   const PetscInt **icol, **irow;
2142:   PetscInt        *nrow, *ncol, start;
2143:   PetscMPIInt      nrqs = 0, *pa, proc = -1;
2144:   PetscMPIInt      rank, size, tag0, tag2, tag3, tag4, *w1, *w2, *w3, *w4, nrqr, *req_source1 = NULL, *req_source2;
2145:   PetscInt       **sbuf1, **sbuf2, k, ct1, ct2, **rbuf1, row;
2146:   PetscInt         msz, **ptr = NULL, *req_size = NULL, *ctr = NULL, *tmp = NULL, tcol;
2147:   PetscInt       **rbuf3 = NULL, **sbuf_aj, **rbuf2 = NULL, max1, max2;
2148:   PetscInt       **lens, is_no, ncols, *cols, mat_i, *mat_j, tmp2, jmax;
2149: #if PetscDefined(USE_CTABLE)
2150:   PetscHMapI *cmap, cmap_i = NULL, *rmap, rmap_i;
2151: #else
2152:   PetscInt **cmap, *cmap_i = NULL, **rmap, *rmap_i;
2153: #endif
2154:   const PetscInt *irow_i;
2155:   PetscInt        ctr_j, *sbuf1_j, *sbuf_aj_i, *rbuf1_i, kmax, *lens_i;
2156:   MPI_Request    *s_waits1, *r_waits1, *s_waits2, *r_waits2, *r_waits3;
2157:   MPI_Request    *r_waits4, *s_waits3, *s_waits4;
2158:   MPI_Comm        comm;
2159:   PetscScalar   **rbuf4 = NULL, *rbuf4_i, **sbuf_aa = NULL, *vals, *mat_a, *imat_a, *sbuf_aa_i;
2160:   PetscMPIInt    *onodes1, *olengths1, end, **row2proc, *row2proc_i;
2161:   PetscInt        ilen_row, *imat_ilen, *imat_j, *imat_i, old_row;
2162:   Mat_SubSppt    *smat_i;
2163:   PetscBool      *issorted, *allcolumns, colflag, iscsorted = PETSC_TRUE;
2164:   PetscInt       *sbuf1_i, *rbuf2_i, *rbuf3_i, ilen, jcnt;

2166:   PetscFunctionBegin;
2167:   PetscCall(PetscObjectGetComm((PetscObject)C, &comm));
2168:   size = c->size;
2169:   rank = c->rank;

2171:   PetscCall(PetscMalloc4(ismax, &row2proc, ismax, &cmap, ismax, &rmap, ismax + 1, &allcolumns));
2172:   PetscCall(PetscMalloc5(ismax, (PetscInt ***)&irow, ismax, (PetscInt ***)&icol, ismax, &nrow, ismax, &ncol, ismax, &issorted));

2174:   for (PetscInt i = 0; i < ismax; i++) {
2175:     PetscCall(ISSorted(iscol[i], &issorted[i]));
2176:     if (!issorted[i]) iscsorted = issorted[i];

2178:     PetscCall(ISSorted(isrow[i], &issorted[i]));

2180:     PetscCall(ISGetIndices(isrow[i], &irow[i]));
2181:     PetscCall(ISGetLocalSize(isrow[i], &nrow[i]));

2183:     /* Check for special case: allcolumn */
2184:     PetscCall(ISIdentity(iscol[i], &colflag));
2185:     PetscCall(ISGetLocalSize(iscol[i], &ncol[i]));
2186:     if (colflag && ncol[i] == C->cmap->N) {
2187:       allcolumns[i] = PETSC_TRUE;
2188:       icol[i]       = NULL;
2189:     } else {
2190:       allcolumns[i] = PETSC_FALSE;
2191:       PetscCall(ISGetIndices(iscol[i], &icol[i]));
2192:     }
2193:   }

2195:   if (scall == MAT_REUSE_MATRIX) {
2196:     /* Assumes new rows are same length as the old rows */
2197:     for (PetscInt i = 0; i < ismax; i++) {
2198:       PetscCheck(submats[i], PETSC_COMM_SELF, PETSC_ERR_ARG_NULL, "submats[%" PetscInt_FMT "] is null, cannot reuse", i);
2199:       subc = (Mat_SeqAIJ *)submats[i]->data;
2200:       PetscCheck(!(submats[i]->rmap->n != nrow[i]) && !(submats[i]->cmap->n != ncol[i]), PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Cannot reuse matrix. wrong size");

2202:       /* Initial matrix as if empty */
2203:       PetscCall(PetscArrayzero(subc->ilen, submats[i]->rmap->n));

2205:       smat_i = subc->submatis1;

2207:       nrqs        = smat_i->nrqs;
2208:       nrqr        = smat_i->nrqr;
2209:       rbuf1       = smat_i->rbuf1;
2210:       rbuf2       = smat_i->rbuf2;
2211:       rbuf3       = smat_i->rbuf3;
2212:       req_source2 = smat_i->req_source2;

2214:       sbuf1 = smat_i->sbuf1;
2215:       sbuf2 = smat_i->sbuf2;
2216:       ptr   = smat_i->ptr;
2217:       tmp   = smat_i->tmp;
2218:       ctr   = smat_i->ctr;

2220:       pa          = smat_i->pa;
2221:       req_size    = smat_i->req_size;
2222:       req_source1 = smat_i->req_source1;

2224:       allcolumns[i] = smat_i->allcolumns;
2225:       row2proc[i]   = smat_i->row2proc;
2226:       rmap[i]       = smat_i->rmap;
2227:       cmap[i]       = smat_i->cmap;
2228:     }

2230:     if (!ismax) { /* Get dummy submatrices and retrieve struct submatis1 */
2231:       PetscCheck(submats[0], PETSC_COMM_SELF, PETSC_ERR_ARG_NULL, "submats are null, cannot reuse");
2232:       smat_i = (Mat_SubSppt *)submats[0]->data;

2234:       nrqs        = smat_i->nrqs;
2235:       nrqr        = smat_i->nrqr;
2236:       rbuf1       = smat_i->rbuf1;
2237:       rbuf2       = smat_i->rbuf2;
2238:       rbuf3       = smat_i->rbuf3;
2239:       req_source2 = smat_i->req_source2;

2241:       sbuf1 = smat_i->sbuf1;
2242:       sbuf2 = smat_i->sbuf2;
2243:       ptr   = smat_i->ptr;
2244:       tmp   = smat_i->tmp;
2245:       ctr   = smat_i->ctr;

2247:       pa          = smat_i->pa;
2248:       req_size    = smat_i->req_size;
2249:       req_source1 = smat_i->req_source1;

2251:       allcolumns[0] = PETSC_FALSE;
2252:     }
2253:   } else { /* scall == MAT_INITIAL_MATRIX */
2254:     /* Get some new tags to keep the communication clean */
2255:     PetscCall(PetscObjectGetNewTag((PetscObject)C, &tag2));
2256:     PetscCall(PetscObjectGetNewTag((PetscObject)C, &tag3));

2258:     /* evaluate communication - mesg to who, length of mesg, and buffer space
2259:      required. Based on this, buffers are allocated, and data copied into them*/
2260:     PetscCall(PetscCalloc4(size, &w1, size, &w2, size, &w3, size, &w4)); /* mesg size, initialize work vectors */

2262:     for (PetscInt i = 0; i < ismax; i++) {
2263:       jmax   = nrow[i];
2264:       irow_i = irow[i];

2266:       PetscCall(PetscMalloc1(jmax, &row2proc_i));
2267:       row2proc[i] = row2proc_i;

2269:       if (issorted[i]) proc = 0;
2270:       for (PetscInt j = 0; j < jmax; j++) {
2271:         if (!issorted[i]) proc = 0;
2272:         row = irow_i[j];
2273:         while (row >= C->rmap->range[proc + 1]) proc++;
2274:         w4[proc]++;
2275:         row2proc_i[j] = proc; /* map row index to proc */
2276:       }
2277:       for (PetscMPIInt j = 0; j < size; j++) {
2278:         if (w4[j]) {
2279:           w1[j] += w4[j];
2280:           w3[j]++;
2281:           w4[j] = 0;
2282:         }
2283:       }
2284:     }

2286:     nrqs     = 0; /* no of outgoing messages */
2287:     msz      = 0; /* total mesg length (for all procs) */
2288:     w1[rank] = 0; /* no mesg sent to self */
2289:     w3[rank] = 0;
2290:     for (PetscMPIInt i = 0; i < size; i++) {
2291:       if (w1[i]) {
2292:         w2[i] = 1;
2293:         nrqs++;
2294:       } /* there exists a message to proc i */
2295:     }
2296:     PetscCall(PetscMalloc1(nrqs, &pa)); /*(proc -array)*/
2297:     for (PetscMPIInt i = 0, j = 0; i < size; i++) {
2298:       if (w1[i]) {
2299:         pa[j] = i;
2300:         j++;
2301:       }
2302:     }

2304:     /* Each message would have a header = 1 + 2*(no of IS) + data */
2305:     for (PetscMPIInt i = 0; i < nrqs; i++) {
2306:       PetscMPIInt j = pa[i];
2307:       w1[j] += w2[j] + 2 * w3[j];
2308:       msz += w1[j];
2309:     }
2310:     PetscCall(PetscInfo(0, "Number of outgoing messages %d Total message length %" PetscInt_FMT "\n", nrqs, msz));

2312:     /* Determine the number of messages to expect, their lengths, from from-ids */
2313:     PetscCall(PetscGatherNumberOfMessages(comm, w2, w1, &nrqr));
2314:     PetscCall(PetscGatherMessageLengths(comm, nrqs, nrqr, w1, &onodes1, &olengths1));

2316:     /* Now post the Irecvs corresponding to these messages */
2317:     PetscCall(PetscObjectGetNewTag((PetscObject)C, &tag0));
2318:     PetscCall(PetscPostIrecvInt(comm, tag0, nrqr, onodes1, olengths1, &rbuf1, &r_waits1));

2320:     /* Allocate Memory for outgoing messages */
2321:     PetscCall(PetscMalloc4(size, &sbuf1, size, &ptr, 2 * msz, &tmp, size, &ctr));
2322:     PetscCall(PetscArrayzero(sbuf1, size));
2323:     PetscCall(PetscArrayzero(ptr, size));

2325:     {
2326:       PetscInt *iptr = tmp;
2327:       k              = 0;
2328:       for (PetscMPIInt i = 0; i < nrqs; i++) {
2329:         PetscMPIInt j = pa[i];
2330:         iptr += k;
2331:         sbuf1[j] = iptr;
2332:         k        = w1[j];
2333:       }
2334:     }

2336:     /* Form the outgoing messages. Initialize the header space */
2337:     for (PetscMPIInt i = 0; i < nrqs; i++) {
2338:       PetscMPIInt j = pa[i];
2339:       sbuf1[j][0]   = 0;
2340:       PetscCall(PetscArrayzero(sbuf1[j] + 1, 2 * w3[j]));
2341:       ptr[j] = sbuf1[j] + 2 * w3[j] + 1;
2342:     }

2344:     /* Parse the isrow and copy data into outbuf */
2345:     for (PetscInt i = 0; i < ismax; i++) {
2346:       row2proc_i = row2proc[i];
2347:       PetscCall(PetscArrayzero(ctr, size));
2348:       irow_i = irow[i];
2349:       jmax   = nrow[i];
2350:       for (PetscInt j = 0; j < jmax; j++) { /* parse the indices of each IS */
2351:         proc = row2proc_i[j];
2352:         if (proc != rank) { /* copy to the outgoing buf */
2353:           ctr[proc]++;
2354:           *ptr[proc] = irow_i[j];
2355:           ptr[proc]++;
2356:         }
2357:       }
2358:       /* Update the headers for the current IS */
2359:       for (PetscMPIInt j = 0; j < size; j++) { /* Can Optimise this loop too */
2360:         if ((ctr_j = ctr[j])) {
2361:           sbuf1_j            = sbuf1[j];
2362:           k                  = ++sbuf1_j[0];
2363:           sbuf1_j[2 * k]     = ctr_j;
2364:           sbuf1_j[2 * k - 1] = i;
2365:         }
2366:       }
2367:     }

2369:     /*  Now  post the sends */
2370:     PetscCall(PetscMalloc1(nrqs, &s_waits1));
2371:     for (PetscMPIInt i = 0; i < nrqs; ++i) {
2372:       PetscMPIInt j = pa[i];
2373:       PetscCallMPI(MPIU_Isend(sbuf1[j], w1[j], MPIU_INT, j, tag0, comm, s_waits1 + i));
2374:     }

2376:     /* Post Receives to capture the buffer size */
2377:     PetscCall(PetscMalloc1(nrqs, &r_waits2));
2378:     PetscCall(PetscMalloc3(nrqs, &req_source2, nrqs, &rbuf2, nrqs, &rbuf3));
2379:     if (nrqs) rbuf2[0] = tmp + msz;
2380:     for (PetscMPIInt i = 1; i < nrqs; ++i) rbuf2[i] = rbuf2[i - 1] + w1[pa[i - 1]];
2381:     for (PetscMPIInt i = 0; i < nrqs; ++i) {
2382:       PetscMPIInt j = pa[i];
2383:       PetscCallMPI(MPIU_Irecv(rbuf2[i], w1[j], MPIU_INT, j, tag2, comm, r_waits2 + i));
2384:     }

2386:     /* Send to other procs the buf size they should allocate */
2387:     /* Receive messages*/
2388:     PetscCall(PetscMalloc1(nrqr, &s_waits2));
2389:     PetscCall(PetscMalloc3(nrqr, &sbuf2, nrqr, &req_size, nrqr, &req_source1));
2390:     {
2391:       PetscInt *sAi = a->i, *sBi = b->i, id, rstart = C->rmap->rstart;
2392:       PetscInt *sbuf2_i;

2394:       PetscCallMPI(MPI_Waitall(nrqr, r_waits1, MPI_STATUSES_IGNORE));
2395:       for (PetscMPIInt i = 0; i < nrqr; ++i) {
2396:         req_size[i] = 0;
2397:         rbuf1_i     = rbuf1[i];
2398:         start       = 2 * rbuf1_i[0] + 1;
2399:         end         = olengths1[i];
2400:         PetscCall(PetscMalloc1(end, &sbuf2[i]));
2401:         sbuf2_i = sbuf2[i];
2402:         for (PetscInt j = start; j < end; j++) {
2403:           id         = rbuf1_i[j] - rstart;
2404:           ncols      = sAi[id + 1] - sAi[id] + sBi[id + 1] - sBi[id];
2405:           sbuf2_i[j] = ncols;
2406:           req_size[i] += ncols;
2407:         }
2408:         req_source1[i] = onodes1[i];
2409:         /* form the header */
2410:         sbuf2_i[0] = req_size[i];
2411:         for (PetscInt j = 1; j < start; j++) sbuf2_i[j] = rbuf1_i[j];

2413:         PetscCallMPI(MPIU_Isend(sbuf2_i, end, MPIU_INT, req_source1[i], tag2, comm, s_waits2 + i));
2414:       }
2415:     }

2417:     PetscCall(PetscFree(onodes1));
2418:     PetscCall(PetscFree(olengths1));
2419:     PetscCall(PetscFree(r_waits1));
2420:     PetscCall(PetscFree4(w1, w2, w3, w4));

2422:     /* Receive messages*/
2423:     PetscCall(PetscMalloc1(nrqs, &r_waits3));
2424:     PetscCallMPI(MPI_Waitall(nrqs, r_waits2, MPI_STATUSES_IGNORE));
2425:     for (PetscMPIInt i = 0; i < nrqs; ++i) {
2426:       PetscCall(PetscMalloc1(rbuf2[i][0], &rbuf3[i]));
2427:       req_source2[i] = pa[i];
2428:       PetscCallMPI(MPIU_Irecv(rbuf3[i], rbuf2[i][0], MPIU_INT, req_source2[i], tag3, comm, r_waits3 + i));
2429:     }
2430:     PetscCall(PetscFree(r_waits2));

2432:     /* Wait on sends1 and sends2 */
2433:     PetscCallMPI(MPI_Waitall(nrqs, s_waits1, MPI_STATUSES_IGNORE));
2434:     PetscCallMPI(MPI_Waitall(nrqr, s_waits2, MPI_STATUSES_IGNORE));
2435:     PetscCall(PetscFree(s_waits1));
2436:     PetscCall(PetscFree(s_waits2));

2438:     /* Now allocate sending buffers for a->j, and send them off */
2439:     PetscCall(PetscMalloc1(nrqr, &sbuf_aj));
2440:     jcnt = 0;
2441:     for (PetscMPIInt i = 0; i < nrqr; i++) jcnt += req_size[i];
2442:     if (nrqr) PetscCall(PetscMalloc1(jcnt, &sbuf_aj[0]));
2443:     for (PetscMPIInt i = 1; i < nrqr; i++) sbuf_aj[i] = sbuf_aj[i - 1] + req_size[i - 1];

2445:     PetscCall(PetscMalloc1(nrqr, &s_waits3));
2446:     {
2447:       PetscInt  nzA, nzB, *a_i = a->i, *b_i = b->i, lwrite;
2448:       PetscInt *cworkA, *cworkB, cstart = C->cmap->rstart, rstart = C->rmap->rstart, *bmap = c->garray;
2449:       PetscInt  cend = C->cmap->rend;
2450:       PetscInt *a_j = a->j, *b_j = b->j, ctmp;

2452:       for (PetscMPIInt i = 0; i < nrqr; i++) {
2453:         rbuf1_i   = rbuf1[i];
2454:         sbuf_aj_i = sbuf_aj[i];
2455:         ct1       = 2 * rbuf1_i[0] + 1;
2456:         ct2       = 0;
2457:         for (PetscInt j = 1, max1 = rbuf1_i[0]; j <= max1; j++) {
2458:           kmax = rbuf1[i][2 * j];
2459:           for (PetscInt k = 0; k < kmax; k++, ct1++) {
2460:             row    = rbuf1_i[ct1] - rstart;
2461:             nzA    = a_i[row + 1] - a_i[row];
2462:             nzB    = b_i[row + 1] - b_i[row];
2463:             ncols  = nzA + nzB;
2464:             cworkA = PetscSafePointerPlusOffset(a_j, a_i[row]);
2465:             cworkB = PetscSafePointerPlusOffset(b_j, b_i[row]);

2467:             /* load the column indices for this row into cols */
2468:             cols = sbuf_aj_i + ct2;

2470:             lwrite = 0;
2471:             for (PetscInt l = 0; l < nzB; l++) {
2472:               if ((ctmp = bmap[cworkB[l]]) < cstart) cols[lwrite++] = ctmp;
2473:             }
2474:             for (PetscInt l = 0; l < nzA; l++) cols[lwrite++] = cstart + cworkA[l];
2475:             for (PetscInt l = 0; l < nzB; l++) {
2476:               if ((ctmp = bmap[cworkB[l]]) >= cend) cols[lwrite++] = ctmp;
2477:             }

2479:             ct2 += ncols;
2480:           }
2481:         }
2482:         PetscCallMPI(MPIU_Isend(sbuf_aj_i, req_size[i], MPIU_INT, req_source1[i], tag3, comm, s_waits3 + i));
2483:       }
2484:     }

2486:     /* create col map: global col of C -> local col of submatrices */
2487:     {
2488:       const PetscInt *icol_i;
2489: #if PetscDefined(USE_CTABLE)
2490:       for (PetscInt i = 0; i < ismax; i++) {
2491:         if (!allcolumns[i]) {
2492:           PetscCall(PetscHMapICreateWithSize(ncol[i], cmap + i));

2494:           jmax   = ncol[i];
2495:           icol_i = icol[i];
2496:           cmap_i = cmap[i];
2497:           for (PetscInt j = 0; j < jmax; j++) PetscCall(PetscHMapISet(cmap[i], icol_i[j] + 1, j + 1));
2498:         } else cmap[i] = NULL;
2499:       }
2500: #else
2501:       for (PetscInt i = 0; i < ismax; i++) {
2502:         if (!allcolumns[i]) {
2503:           PetscCall(PetscCalloc1(C->cmap->N, &cmap[i]));
2504:           jmax   = ncol[i];
2505:           icol_i = icol[i];
2506:           cmap_i = cmap[i];
2507:           for (PetscInt j = 0; j < jmax; j++) cmap_i[icol_i[j]] = j + 1;
2508:         } else cmap[i] = NULL;
2509:       }
2510: #endif
2511:     }

2513:     /* Create lens which is required for MatCreate... */
2514:     jcnt = 0;
2515:     for (PetscInt i = 0; i < ismax; i++) jcnt += nrow[i];
2516:     PetscCall(PetscMalloc1(ismax, &lens));

2518:     if (ismax) PetscCall(PetscCalloc1(jcnt, &lens[0]));
2519:     for (PetscInt i = 1; i < ismax; i++) lens[i] = PetscSafePointerPlusOffset(lens[i - 1], nrow[i - 1]);

2521:     /* Update lens from local data */
2522:     for (PetscInt i = 0; i < ismax; i++) {
2523:       row2proc_i = row2proc[i];
2524:       jmax       = nrow[i];
2525:       if (!allcolumns[i]) cmap_i = cmap[i];
2526:       irow_i = irow[i];
2527:       lens_i = lens[i];
2528:       for (PetscInt j = 0; j < jmax; j++) {
2529:         row  = irow_i[j];
2530:         proc = row2proc_i[j];
2531:         if (proc == rank) {
2532:           PetscCall(MatGetRow_MPIAIJ(C, row, &ncols, &cols, NULL));
2533:           if (!allcolumns[i]) {
2534:             for (PetscInt k = 0; k < ncols; k++) {
2535: #if PetscDefined(USE_CTABLE)
2536:               PetscCall(PetscHMapIGetWithDefault(cmap_i, cols[k] + 1, 0, &tcol));
2537: #else
2538:               tcol = cmap_i[cols[k]];
2539: #endif
2540:               if (tcol) lens_i[j]++;
2541:             }
2542:           } else { /* allcolumns */
2543:             lens_i[j] = ncols;
2544:           }
2545:           PetscCall(MatRestoreRow_MPIAIJ(C, row, &ncols, &cols, NULL));
2546:         }
2547:       }
2548:     }

2550:     /* Create row map: global row of C -> local row of submatrices */
2551: #if PetscDefined(USE_CTABLE)
2552:     for (PetscInt i = 0; i < ismax; i++) {
2553:       PetscCall(PetscHMapICreateWithSize(nrow[i], rmap + i));
2554:       irow_i = irow[i];
2555:       jmax   = nrow[i];
2556:       for (PetscInt j = 0; j < jmax; j++) PetscCall(PetscHMapISet(rmap[i], irow_i[j] + 1, j + 1));
2557:     }
2558: #else
2559:     for (PetscInt i = 0; i < ismax; i++) {
2560:       PetscCall(PetscCalloc1(C->rmap->N, &rmap[i]));
2561:       rmap_i = rmap[i];
2562:       irow_i = irow[i];
2563:       jmax   = nrow[i];
2564:       for (PetscInt j = 0; j < jmax; j++) rmap_i[irow_i[j]] = j;
2565:     }
2566: #endif

2568:     /* Update lens from offproc data */
2569:     {
2570:       PetscInt *rbuf2_i, *rbuf3_i, *sbuf1_i;

2572:       PetscCallMPI(MPI_Waitall(nrqs, r_waits3, MPI_STATUSES_IGNORE));
2573:       for (tmp2 = 0; tmp2 < nrqs; tmp2++) {
2574:         sbuf1_i = sbuf1[pa[tmp2]];
2575:         jmax    = sbuf1_i[0];
2576:         ct1     = 2 * jmax + 1;
2577:         ct2     = 0;
2578:         rbuf2_i = rbuf2[tmp2];
2579:         rbuf3_i = rbuf3[tmp2];
2580:         for (PetscInt j = 1; j <= jmax; j++) {
2581:           is_no  = sbuf1_i[2 * j - 1];
2582:           max1   = sbuf1_i[2 * j];
2583:           lens_i = lens[is_no];
2584:           if (!allcolumns[is_no]) cmap_i = cmap[is_no];
2585:           rmap_i = rmap[is_no];
2586:           for (PetscInt k = 0; k < max1; k++, ct1++) {
2587: #if PetscDefined(USE_CTABLE)
2588:             PetscCall(PetscHMapIGetWithDefault(rmap_i, sbuf1_i[ct1] + 1, 0, &row));
2589:             row--;
2590:             PetscCheck(row >= 0, PETSC_COMM_SELF, PETSC_ERR_PLIB, "row not found in table");
2591: #else
2592:             row = rmap_i[sbuf1_i[ct1]]; /* the val in the new matrix to be */
2593: #endif
2594:             max2 = rbuf2_i[ct1];
2595:             for (PetscInt l = 0; l < max2; l++, ct2++) {
2596:               if (!allcolumns[is_no]) {
2597: #if PetscDefined(USE_CTABLE)
2598:                 PetscCall(PetscHMapIGetWithDefault(cmap_i, rbuf3_i[ct2] + 1, 0, &tcol));
2599: #else
2600:                 tcol = cmap_i[rbuf3_i[ct2]];
2601: #endif
2602:                 if (tcol) lens_i[row]++;
2603:               } else {         /* allcolumns */
2604:                 lens_i[row]++; /* lens_i[row] += max2 ? */
2605:               }
2606:             }
2607:           }
2608:         }
2609:       }
2610:     }
2611:     PetscCall(PetscFree(r_waits3));
2612:     PetscCallMPI(MPI_Waitall(nrqr, s_waits3, MPI_STATUSES_IGNORE));
2613:     PetscCall(PetscFree(s_waits3));

2615:     /* Create the submatrices */
2616:     for (PetscInt i = 0; i < ismax; i++) {
2617:       PetscInt rbs, cbs;

2619:       PetscCall(ISGetBlockSize(isrow[i], &rbs));
2620:       PetscCall(ISGetBlockSize(iscol[i], &cbs));

2622:       PetscCall(MatCreate(PETSC_COMM_SELF, submats + i));
2623:       PetscCall(MatSetSizes(submats[i], nrow[i], ncol[i], PETSC_DETERMINE, PETSC_DETERMINE));

2625:       if (rbs > 1 || cbs > 1) PetscCall(MatSetBlockSizes(submats[i], rbs, cbs));
2626:       PetscCall(MatSetType(submats[i], ((PetscObject)A)->type_name));
2627:       PetscCall(MatSetOption(submats[i], MAT_STRUCTURE_ONLY, C->structure_only));
2628:       PetscCall(MatSeqAIJSetPreallocation(submats[i], 0, lens[i]));

2630:       /* create struct Mat_SubSppt and attached it to submat */
2631:       PetscCall(PetscNew(&smat_i));
2632:       subc            = (Mat_SeqAIJ *)submats[i]->data;
2633:       subc->submatis1 = smat_i;

2635:       submats[i]->factortype = C->factortype;

2637:       smat_i->id          = i;
2638:       smat_i->nrqs        = nrqs;
2639:       smat_i->nrqr        = nrqr;
2640:       smat_i->rbuf1       = rbuf1;
2641:       smat_i->rbuf2       = rbuf2;
2642:       smat_i->rbuf3       = rbuf3;
2643:       smat_i->sbuf2       = sbuf2;
2644:       smat_i->req_source2 = req_source2;

2646:       smat_i->sbuf1 = sbuf1;
2647:       smat_i->ptr   = ptr;
2648:       smat_i->tmp   = tmp;
2649:       smat_i->ctr   = ctr;

2651:       smat_i->pa          = pa;
2652:       smat_i->req_size    = req_size;
2653:       smat_i->req_source1 = req_source1;

2655:       smat_i->allcolumns = allcolumns[i];
2656:       smat_i->singleis   = PETSC_FALSE;
2657:       smat_i->row2proc   = row2proc[i];
2658:       smat_i->rmap       = rmap[i];
2659:       smat_i->cmap       = cmap[i];
2660:     }

2662:     if (!ismax) { /* Create dummy submats[0] for reuse struct subc */
2663:       PetscCall(MatCreate(PETSC_COMM_SELF, &submats[0]));
2664:       PetscCall(MatSetSizes(submats[0], 0, 0, PETSC_DETERMINE, PETSC_DETERMINE));
2665:       PetscCall(MatSetType(submats[0], MATDUMMY));

2667:       /* create struct Mat_SubSppt and attached it to submat */
2668:       PetscCall(PetscNew(&smat_i));
2669:       submats[0]->data = (void *)smat_i;

2671:       submats[0]->factortype = C->factortype;

2673:       smat_i->id          = 0;
2674:       smat_i->nrqs        = nrqs;
2675:       smat_i->nrqr        = nrqr;
2676:       smat_i->rbuf1       = rbuf1;
2677:       smat_i->rbuf2       = rbuf2;
2678:       smat_i->rbuf3       = rbuf3;
2679:       smat_i->sbuf2       = sbuf2;
2680:       smat_i->req_source2 = req_source2;

2682:       smat_i->sbuf1 = sbuf1;
2683:       smat_i->ptr   = ptr;
2684:       smat_i->tmp   = tmp;
2685:       smat_i->ctr   = ctr;

2687:       smat_i->pa          = pa;
2688:       smat_i->req_size    = req_size;
2689:       smat_i->req_source1 = req_source1;

2691:       smat_i->allcolumns = PETSC_FALSE;
2692:       smat_i->singleis   = PETSC_FALSE;
2693:       smat_i->row2proc   = NULL;
2694:       smat_i->rmap       = NULL;
2695:       smat_i->cmap       = NULL;
2696:     }

2698:     if (ismax) PetscCall(PetscFree(lens[0]));
2699:     PetscCall(PetscFree(lens));
2700:     if (sbuf_aj) {
2701:       PetscCall(PetscFree(sbuf_aj[0]));
2702:       PetscCall(PetscFree(sbuf_aj));
2703:     }

2705:   } /* endof scall == MAT_INITIAL_MATRIX */

2707:   if (!C->structure_only) {
2708:     /* Post recv matrix values */
2709:     PetscCall(PetscObjectGetNewTag((PetscObject)C, &tag4));
2710:     PetscCall(PetscMalloc1(nrqs, &rbuf4));
2711:     PetscCall(PetscMalloc1(nrqs, &r_waits4));
2712:     for (PetscMPIInt i = 0; i < nrqs; ++i) {
2713:       PetscCall(PetscMalloc1(rbuf2[i][0], &rbuf4[i]));
2714:       PetscCallMPI(MPIU_Irecv(rbuf4[i], rbuf2[i][0], MPIU_SCALAR, req_source2[i], tag4, comm, r_waits4 + i));
2715:     }

2717:     /* Allocate sending buffers for a->a, and send them off */
2718:     PetscCall(PetscMalloc1(nrqr, &sbuf_aa));
2719:     jcnt = 0;
2720:     for (PetscMPIInt i = 0; i < nrqr; i++) jcnt += req_size[i];
2721:     if (nrqr) PetscCall(PetscMalloc1(jcnt, &sbuf_aa[0]));
2722:     for (PetscMPIInt i = 1; i < nrqr; i++) sbuf_aa[i] = sbuf_aa[i - 1] + req_size[i - 1];

2724:     PetscCall(PetscMalloc1(nrqr, &s_waits4));
2725:     {
2726:       PetscInt     nzA, nzB, *a_i = a->i, *b_i = b->i, *cworkB, lwrite;
2727:       PetscInt     cstart = C->cmap->rstart, rstart = C->rmap->rstart, *bmap = c->garray;
2728:       PetscInt     cend = C->cmap->rend;
2729:       PetscInt    *b_j  = b->j;
2730:       PetscScalar *vworkA, *vworkB, *a_a, *b_a;

2732:       PetscCall(MatSeqAIJGetArrayRead(A, (const PetscScalar **)&a_a));
2733:       PetscCall(MatSeqAIJGetArrayRead(c->B, (const PetscScalar **)&b_a));
2734:       for (PetscMPIInt i = 0; i < nrqr; i++) {
2735:         rbuf1_i   = rbuf1[i];
2736:         sbuf_aa_i = sbuf_aa[i];
2737:         ct1       = 2 * rbuf1_i[0] + 1;
2738:         ct2       = 0;
2739:         for (PetscInt j = 1, max1 = rbuf1_i[0]; j <= max1; j++) {
2740:           kmax = rbuf1_i[2 * j];
2741:           for (PetscInt k = 0; k < kmax; k++, ct1++) {
2742:             row    = rbuf1_i[ct1] - rstart;
2743:             nzA    = a_i[row + 1] - a_i[row];
2744:             nzB    = b_i[row + 1] - b_i[row];
2745:             ncols  = nzA + nzB;
2746:             cworkB = PetscSafePointerPlusOffset(b_j, b_i[row]);
2747:             vworkA = PetscSafePointerPlusOffset(a_a, a_i[row]);
2748:             vworkB = PetscSafePointerPlusOffset(b_a, b_i[row]);

2750:             /* load the column values for this row into vals*/
2751:             vals = sbuf_aa_i + ct2;

2753:             lwrite = 0;
2754:             for (PetscInt l = 0; l < nzB; l++) {
2755:               if (bmap[cworkB[l]] < cstart) vals[lwrite++] = vworkB[l];
2756:             }
2757:             for (PetscInt l = 0; l < nzA; l++) vals[lwrite++] = vworkA[l];
2758:             for (PetscInt l = 0; l < nzB; l++) {
2759:               if (bmap[cworkB[l]] >= cend) vals[lwrite++] = vworkB[l];
2760:             }

2762:             ct2 += ncols;
2763:           }
2764:         }
2765:         PetscCallMPI(MPIU_Isend(sbuf_aa_i, req_size[i], MPIU_SCALAR, req_source1[i], tag4, comm, s_waits4 + i));
2766:       }
2767:       PetscCall(MatSeqAIJRestoreArrayRead(A, (const PetscScalar **)&a_a));
2768:       PetscCall(MatSeqAIJRestoreArrayRead(c->B, (const PetscScalar **)&b_a));
2769:     }
2770:   }

2772:   /* Assemble the matrices */
2773:   /* First assemble the local rows */
2774:   for (PetscInt i = 0; i < ismax; i++) {
2775:     row2proc_i = row2proc[i];
2776:     subc       = (Mat_SeqAIJ *)submats[i]->data;
2777:     imat_ilen  = subc->ilen;
2778:     imat_j     = subc->j;
2779:     imat_i     = subc->i;
2780:     PetscCall(MatSeqAIJGetArrayWrite(submats[i], &imat_a));

2782:     if (!allcolumns[i]) cmap_i = cmap[i];
2783:     rmap_i = rmap[i];
2784:     irow_i = irow[i];
2785:     jmax   = nrow[i];
2786:     for (PetscInt j = 0; j < jmax; j++) {
2787:       row  = irow_i[j];
2788:       proc = row2proc_i[j];
2789:       if (proc == rank) {
2790:         old_row = row;
2791: #if PetscDefined(USE_CTABLE)
2792:         PetscCall(PetscHMapIGetWithDefault(rmap_i, row + 1, 0, &row));
2793:         row--;
2794: #else
2795:         row = rmap_i[row];
2796: #endif
2797:         ilen_row = imat_ilen[row];
2798:         PetscCall(MatGetRow_MPIAIJ(C, old_row, &ncols, &cols, C->structure_only ? NULL : &vals));
2799:         mat_i = imat_i[row];
2800:         mat_a = PetscSafePointerPlusOffset(imat_a, mat_i);
2801:         mat_j = PetscSafePointerPlusOffset(imat_j, mat_i);
2802:         if (!allcolumns[i]) {
2803:           for (PetscInt k = 0; k < ncols; k++) {
2804: #if PetscDefined(USE_CTABLE)
2805:             PetscCall(PetscHMapIGetWithDefault(cmap_i, cols[k] + 1, 0, &tcol));
2806: #else
2807:             tcol = cmap_i[cols[k]];
2808: #endif
2809:             if (tcol) {
2810:               *mat_j++ = tcol - 1;
2811:               if (!C->structure_only) *mat_a++ = vals[k];
2812:               ilen_row++;
2813:             }
2814:           }
2815:         } else { /* allcolumns */
2816:           for (PetscInt k = 0; k < ncols; k++, ilen_row++) {
2817:             *mat_j++ = cols[k]; /* global col index! */
2818:             if (!C->structure_only) *mat_a++ = vals[k];
2819:           }
2820:         }
2821:         PetscCall(MatRestoreRow_MPIAIJ(C, old_row, &ncols, &cols, C->structure_only ? NULL : &vals));

2823:         imat_ilen[row] = ilen_row;
2824:       }
2825:     }
2826:     PetscCall(MatSeqAIJRestoreArrayWrite(submats[i], &imat_a));
2827:   }

2829:   /* Now assemble the off proc rows */
2830:   if (!C->structure_only) PetscCallMPI(MPI_Waitall(nrqs, r_waits4, MPI_STATUSES_IGNORE));
2831:   for (tmp2 = 0; tmp2 < nrqs; tmp2++) {
2832:     sbuf1_i = sbuf1[pa[tmp2]];
2833:     jmax    = sbuf1_i[0];
2834:     ct1     = 2 * jmax + 1;
2835:     ct2     = 0;
2836:     rbuf2_i = rbuf2[tmp2];
2837:     rbuf3_i = rbuf3[tmp2];
2838:     rbuf4_i = C->structure_only ? NULL : rbuf4[tmp2];
2839:     for (PetscInt j = 1; j <= jmax; j++) {
2840:       is_no  = sbuf1_i[2 * j - 1];
2841:       rmap_i = rmap[is_no];
2842:       if (!allcolumns[is_no]) cmap_i = cmap[is_no];
2843:       subc      = (Mat_SeqAIJ *)submats[is_no]->data;
2844:       imat_ilen = subc->ilen;
2845:       imat_j    = subc->j;
2846:       imat_i    = subc->i;
2847:       PetscCall(MatSeqAIJGetArrayWrite(submats[is_no], &imat_a));
2848:       max1 = sbuf1_i[2 * j];
2849:       for (PetscInt k = 0; k < max1; k++, ct1++) {
2850:         row = sbuf1_i[ct1];
2851: #if PetscDefined(USE_CTABLE)
2852:         PetscCall(PetscHMapIGetWithDefault(rmap_i, row + 1, 0, &row));
2853:         row--;
2854: #else
2855:         row = rmap_i[row];
2856: #endif
2857:         ilen  = imat_ilen[row];
2858:         mat_i = imat_i[row];
2859:         mat_a = PetscSafePointerPlusOffset(imat_a, mat_i);
2860:         mat_j = PetscSafePointerPlusOffset(imat_j, mat_i);
2861:         max2  = rbuf2_i[ct1];
2862:         if (!allcolumns[is_no]) {
2863:           for (PetscInt l = 0; l < max2; l++, ct2++) {
2864: #if PetscDefined(USE_CTABLE)
2865:             PetscCall(PetscHMapIGetWithDefault(cmap_i, rbuf3_i[ct2] + 1, 0, &tcol));
2866: #else
2867:             tcol = cmap_i[rbuf3_i[ct2]];
2868: #endif
2869:             if (tcol) {
2870:               *mat_j++ = tcol - 1;
2871:               if (!C->structure_only) *mat_a++ = rbuf4_i[ct2];
2872:               ilen++;
2873:             }
2874:           }
2875:         } else { /* allcolumns */
2876:           for (PetscInt l = 0; l < max2; l++, ct2++, ilen++) {
2877:             *mat_j++ = rbuf3_i[ct2]; /* same global column index of C */
2878:             if (!C->structure_only) *mat_a++ = rbuf4_i[ct2];
2879:           }
2880:         }
2881:         imat_ilen[row] = ilen;
2882:       }
2883:       PetscCall(MatSeqAIJRestoreArrayWrite(submats[is_no], &imat_a));
2884:     }
2885:   }

2887:   if (!iscsorted) { /* sort column indices of the rows */
2888:     for (PetscInt i = 0; i < ismax; i++) {
2889:       subc      = (Mat_SeqAIJ *)submats[i]->data;
2890:       imat_j    = subc->j;
2891:       imat_i    = subc->i;
2892:       imat_ilen = subc->ilen;

2894:       if (allcolumns[i]) continue;
2895:       PetscCall(MatSeqAIJGetArrayWrite(submats[i], &imat_a));
2896:       jmax = nrow[i];
2897:       for (PetscInt j = 0; j < jmax; j++) {
2898:         mat_i = imat_i[j];
2899:         mat_a = PetscSafePointerPlusOffset(imat_a, mat_i);
2900:         mat_j = PetscSafePointerPlusOffset(imat_j, mat_i);
2901:         if (C->structure_only) PetscCall(PetscSortInt(imat_ilen[j], mat_j));
2902:         else PetscCall(PetscSortIntWithScalarArray(imat_ilen[j], mat_j, mat_a));
2903:       }
2904:       PetscCall(MatSeqAIJRestoreArrayWrite(submats[i], &imat_a));
2905:     }
2906:   }

2908:   if (!C->structure_only) {
2909:     PetscCall(PetscFree(r_waits4));
2910:     PetscCallMPI(MPI_Waitall(nrqr, s_waits4, MPI_STATUSES_IGNORE));
2911:     PetscCall(PetscFree(s_waits4));
2912:   }

2914:   /* Restore the indices */
2915:   for (PetscInt i = 0; i < ismax; i++) {
2916:     PetscCall(ISRestoreIndices(isrow[i], irow + i));
2917:     if (!allcolumns[i]) PetscCall(ISRestoreIndices(iscol[i], icol + i));
2918:   }

2920:   for (PetscInt i = 0; i < ismax; i++) {
2921:     PetscCall(MatAssemblyBegin(submats[i], MAT_FINAL_ASSEMBLY));
2922:     PetscCall(MatAssemblyEnd(submats[i], MAT_FINAL_ASSEMBLY));
2923:   }

2925:   /* Destroy allocated memory */
2926:   if (sbuf_aa) {
2927:     PetscCall(PetscFree(sbuf_aa[0]));
2928:     PetscCall(PetscFree(sbuf_aa));
2929:   }
2930:   PetscCall(PetscFree5(*(PetscInt ***)&irow, *(PetscInt ***)&icol, nrow, ncol, issorted));

2932:   if (rbuf4) {
2933:     for (PetscMPIInt i = 0; i < nrqs; ++i) PetscCall(PetscFree(rbuf4[i]));
2934:     PetscCall(PetscFree(rbuf4));
2935:   }

2937:   PetscCall(PetscFree4(row2proc, cmap, rmap, allcolumns));
2938:   PetscFunctionReturn(PETSC_SUCCESS);
2939: }

2941: /*
2942:  Permute A & B into C's *local* index space using rowemb,dcolemb for A and rowemb,ocolemb for B.
2943:  Embeddings are supposed to be injections and the above implies that the range of rowemb is a subset
2944:  of [0,m), dcolemb is in [0,n) and ocolemb is in [N-n).
2945:  If pattern == DIFFERENT_NONZERO_PATTERN, C is preallocated according to A&B.
2946:  After that B's columns are mapped into C's global column space, so that C is in the "disassembled"
2947:  state, and needs to be "assembled" later by compressing B's column space.

2949:  This function may be called in lieu of preallocation, so C should not be expected to be preallocated.
2950:  Following this call, C->A & C->B have been created, even if empty.
2951:  */
2952: PetscErrorCode MatSetSeqMats_MPIAIJ(Mat C, IS rowemb, IS dcolemb, IS ocolemb, MatStructure pattern, Mat A, Mat B)
2953: {
2954:   /* If making this function public, change the error returned in this function away from _PLIB. */
2955:   Mat_MPIAIJ     *aij;
2956:   Mat_SeqAIJ     *Baij;
2957:   PetscBool       seqaij, Bdisassembled;
2958:   MatType         type;
2959:   PetscInt        m, n, *nz, ngcol, col, cstart, cend, shift, count;
2960:   PetscScalar     v;
2961:   const PetscInt *rowindices, *colindices;

2963:   PetscFunctionBegin;
2964:   /* Check to make sure the component matrices (and embeddings) are compatible with C. */
2965:   if (A) {
2966:     PetscCall(PetscObjectBaseTypeCompare((PetscObject)A, MATSEQAIJ, &seqaij));
2967:     PetscCheck(seqaij, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Diagonal matrix is of wrong type");
2968:     if (rowemb) {
2969:       PetscCall(ISGetLocalSize(rowemb, &m));
2970:       PetscCheck(m == A->rmap->n, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Row IS of size %" PetscInt_FMT " is incompatible with diag matrix row size %" PetscInt_FMT, m, A->rmap->n);
2971:     } else PetscCheck(C->rmap->n == A->rmap->n, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Diag seq matrix is row-incompatible with the MPIAIJ matrix");
2972:     if (dcolemb) {
2973:       PetscCall(ISGetLocalSize(dcolemb, &n));
2974:       PetscCheck(n == A->cmap->n, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Diag col IS of size %" PetscInt_FMT " is incompatible with diag matrix col size %" PetscInt_FMT, n, A->cmap->n);
2975:     } else PetscCheck(C->cmap->n == A->cmap->n, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Diag seq matrix is col-incompatible with the MPIAIJ matrix");
2976:   }
2977:   if (B) {
2978:     PetscCall(PetscObjectBaseTypeCompare((PetscObject)B, MATSEQAIJ, &seqaij));
2979:     PetscCheck(seqaij, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Off-diagonal matrix is of wrong type");
2980:     if (rowemb) {
2981:       PetscCall(ISGetLocalSize(rowemb, &m));
2982:       PetscCheck(m == B->rmap->n, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Row IS of size %" PetscInt_FMT " is incompatible with off-diag matrix row size %" PetscInt_FMT, m, B->rmap->n);
2983:     } else PetscCheck(C->rmap->n == B->rmap->n, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Off-diag seq matrix is row-incompatible with the MPIAIJ matrix");
2984:     if (ocolemb) {
2985:       PetscCall(ISGetLocalSize(ocolemb, &n));
2986:       PetscCheck(n == B->cmap->n, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Off-diag col IS of size %" PetscInt_FMT " is incompatible with off-diag matrix col size %" PetscInt_FMT, n, B->cmap->n);
2987:     } else PetscCheck(C->cmap->N - C->cmap->n == B->cmap->n, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Off-diag seq matrix is col-incompatible with the MPIAIJ matrix");
2988:   }

2990:   PetscCall(MatGetRootType_Private(C, &type));
2991:   aij = (Mat_MPIAIJ *)C->data;
2992:   if (!aij->A) {
2993:     /* Mimic parts of MatMPIAIJSetPreallocation() */
2994:     PetscCall(MatCreate(PETSC_COMM_SELF, &aij->A));
2995:     PetscCall(MatSetSizes(aij->A, C->rmap->n, C->cmap->n, C->rmap->n, C->cmap->n));
2996:     PetscCall(MatSetBlockSizesFromMats(aij->A, C, C));
2997:     PetscCall(MatSetType(aij->A, type));
2998:   }
2999:   if (A) PetscCall(MatSetSeqMat_SeqAIJ(aij->A, rowemb, dcolemb, pattern, A));
3000:   else PetscCall(MatSetUp(aij->A));
3001:   if (B) { /* Destroy the old matrix or the column map, depending on the sparsity pattern. */
3002:     /*
3003:       If pattern == DIFFERENT_NONZERO_PATTERN, we reallocate B and
3004:       need to "disassemble" B -- convert it to using C's global indices.
3005:       To insert the values we take the safer, albeit more expensive, route of MatSetValues().

3007:       If pattern == SUBSET_NONZERO_PATTERN, we do not "disassemble" B and do not reallocate;
3008:       we MatZeroValues(B) first, so there may be a bunch of zeros that, perhaps, could be compacted out.

3010:       TODO: Put B's values into aij->B's aij structure in place using the embedding ISs?
3011:       At least avoid calling MatSetValues() and the implied searches?
3012:     */

3014:     if (pattern == DIFFERENT_NONZERO_PATTERN) {
3015: #if PetscDefined(USE_CTABLE)
3016:       PetscCall(PetscHMapIDestroy(&aij->colmap));
3017: #else
3018:       PetscCall(PetscFree(aij->colmap));
3019:       /* A bit of a HACK: ideally we should deal with case aij->B all in one code block below. */
3020: #endif
3021:       ngcol = 0;
3022:       if (aij->lvec) PetscCall(VecGetSize(aij->lvec, &ngcol));
3023:       PetscCall(PetscFree(aij->garray));
3024:       PetscCall(VecDestroy(&aij->lvec));
3025:       PetscCall(VecScatterDestroy(&aij->Mvctx));
3026:     }
3027:     if (aij->B && pattern == DIFFERENT_NONZERO_PATTERN) PetscCall(MatDestroy(&aij->B));
3028:     if (aij->B && pattern == SUBSET_NONZERO_PATTERN) PetscCall(MatZeroEntries(aij->B));
3029:   }
3030:   Bdisassembled = PETSC_FALSE;
3031:   if (!aij->B) {
3032:     PetscCall(MatCreate(PETSC_COMM_SELF, &aij->B));
3033:     PetscCall(MatSetSizes(aij->B, C->rmap->n, C->cmap->N, C->rmap->n, C->cmap->N));
3034:     PetscCall(MatSetBlockSizesFromMats(aij->B, B, B));
3035:     PetscCall(MatSetType(aij->B, type));
3036:     Bdisassembled = PETSC_TRUE;
3037:   }
3038:   if (B) {
3039:     Baij       = (Mat_SeqAIJ *)B->data;
3040:     rowindices = NULL;
3041:     if (rowemb) PetscCall(ISGetIndices(rowemb, &rowindices));
3042:     if (pattern == DIFFERENT_NONZERO_PATTERN) {
3043:       PetscCall(PetscMalloc1(C->rmap->n, &nz));
3044:       if (rowemb) {
3045:         PetscCall(PetscArrayzero(nz, C->rmap->n));
3046:         for (PetscInt i = 0; i < B->rmap->n; i++) nz[rowindices[i]] = Baij->i[i + 1] - Baij->i[i];
3047:       } else {
3048:         for (PetscInt i = 0; i < B->rmap->n; i++) nz[i] = Baij->i[i + 1] - Baij->i[i];
3049:       }
3050:       PetscCall(MatSeqAIJSetPreallocation(aij->B, 0, nz));
3051:       PetscCall(PetscFree(nz));
3052:     }

3054:     PetscCall(PetscLayoutGetRange(C->cmap, &cstart, &cend));
3055:     shift      = cend - cstart;
3056:     count      = 0;
3057:     colindices = NULL;
3058:     if (ocolemb) PetscCall(ISGetIndices(ocolemb, &colindices));
3059:     for (PetscInt i = 0; i < B->rmap->n; i++) {
3060:       PetscInt row;
3061:       row = i;
3062:       if (rowindices) row = rowindices[i];
3063:       for (PetscInt j = Baij->i[i]; j < Baij->i[i + 1]; j++) {
3064:         col = Baij->j[count];
3065:         if (colindices) col = colindices[col];
3066:         if (Bdisassembled && col >= cstart) col += shift;
3067:         v = Baij->a[count];
3068:         PetscCall(MatSetValues(aij->B, 1, &row, 1, &col, &v, INSERT_VALUES));
3069:         ++count;
3070:       }
3071:     }
3072:     if (ocolemb) PetscCall(ISRestoreIndices(ocolemb, &colindices));
3073:     if (rowemb) PetscCall(ISRestoreIndices(rowemb, &rowindices));
3074:     /* No assembly for aij->B is necessary. */
3075:     /* FIXME: set aij->B's nonzerostate correctly. */
3076:   } else PetscCall(MatSetUp(aij->B));
3077:   C->preallocated  = PETSC_TRUE;
3078:   C->was_assembled = PETSC_FALSE;
3079:   C->assembled     = PETSC_FALSE;
3080:   /*
3081:       C will need to be assembled so that aij->B can be compressed into local form in MatSetUpMultiply_MPIAIJ().
3082:       Furthermore, its nonzerostate will need to be based on that of aij->A's and aij->B's.
3083:    */
3084:   PetscFunctionReturn(PETSC_SUCCESS);
3085: }

3087: /*
3088:   B uses local indices with column indices ranging between 0 and N-n; they  must be interpreted using garray.
3089:  */
3090: PetscErrorCode MatGetSeqMats_MPIAIJ(Mat C, Mat *A, Mat *B)
3091: {
3092:   Mat_MPIAIJ *aij = (Mat_MPIAIJ *)C->data;

3094:   PetscFunctionBegin;
3095:   PetscAssertPointer(A, 2);
3096:   PetscAssertPointer(B, 3);
3097:   /* FIXME: make sure C is assembled */
3098:   *A = aij->A;
3099:   *B = aij->B;
3100:   /* Note that we don't incref *A and *B, so be careful! */
3101:   PetscFunctionReturn(PETSC_SUCCESS);
3102: }

3104: /*
3105:   Extract MPI submatrices encoded by pairs of IS that may live on subcomms of C.
3106:   NOT SCALABLE due to the use of ISGetNonlocalIS() (see below).
3107: */
3108: static PetscErrorCode MatCreateSubMatricesMPI_MPIXAIJ(Mat C, PetscInt ismax, const IS isrow[], const IS iscol[], MatReuse scall, Mat *submat[], PetscErrorCode (*getsubmats_seq)(Mat, PetscInt, const IS[], const IS[], MatReuse, Mat **), PetscErrorCode (*getlocalmats)(Mat, Mat *, Mat *), PetscErrorCode (*setseqmat)(Mat, IS, IS, MatStructure, Mat), PetscErrorCode (*setseqmats)(Mat, IS, IS, IS, MatStructure, Mat, Mat))
3109: {
3110:   PetscMPIInt size, flag;
3111:   PetscInt    cismax, ispar;
3112:   Mat        *A, *B;
3113:   IS         *isrow_p, *iscol_p, *cisrow, *ciscol, *ciscol_p;

3115:   PetscFunctionBegin;
3116:   if (!ismax) PetscFunctionReturn(PETSC_SUCCESS);

3118:   cismax = 0;
3119:   for (PetscInt i = 0; i < ismax; ++i) {
3120:     PetscCallMPI(MPI_Comm_compare(((PetscObject)isrow[i])->comm, ((PetscObject)iscol[i])->comm, &flag));
3121:     PetscCheck(flag == MPI_IDENT, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Row and column index sets must have the same communicator");
3122:     PetscCallMPI(MPI_Comm_size(((PetscObject)isrow[i])->comm, &size));
3123:     if (size > 1) ++cismax;
3124:   }

3126:   /*
3127:      If cismax is zero on all C's ranks, then and only then can we use purely sequential matrix extraction.
3128:      ispar counts the number of parallel ISs across C's comm.
3129:   */
3130:   PetscCallMPI(MPIU_Allreduce(&cismax, &ispar, 1, MPIU_INT, MPI_MAX, PetscObjectComm((PetscObject)C)));
3131:   if (!ispar) { /* Sequential ISs only across C's comm, so can call the sequential matrix extraction subroutine. */
3132:     PetscCall((*getsubmats_seq)(C, ismax, isrow, iscol, scall, submat));
3133:     PetscFunctionReturn(PETSC_SUCCESS);
3134:   }

3136:   /* if (ispar) */
3137:   /*
3138:     Construct the "complements" -- the off-processor indices -- of the iscol ISs for parallel ISs only.
3139:     These are used to extract the off-diag portion of the resulting parallel matrix.
3140:     The row IS for the off-diag portion is the same as for the diag portion,
3141:     so we merely alias (without increfing) the row IS, while skipping those that are sequential.
3142:   */
3143:   PetscCall(PetscMalloc2(cismax, &cisrow, cismax, &ciscol));
3144:   PetscCall(PetscMalloc1(cismax, &ciscol_p));
3145:   for (PetscInt i = 0, ii = 0; i < ismax; ++i) {
3146:     PetscCallMPI(MPI_Comm_size(((PetscObject)isrow[i])->comm, &size));
3147:     if (size > 1) {
3148:       /*
3149:          TODO: This is the part that's ***NOT SCALABLE***.
3150:          To fix this we need to extract just the indices of C's nonzero columns
3151:          that lie on the intersection of isrow[i] and ciscol[ii] -- the nonlocal
3152:          part of iscol[i] -- without actually computing ciscol[ii]. This also has
3153:          to be done without serializing on the IS list, so, most likely, it is best
3154:          done by rewriting MatCreateSubMatrices_MPIAIJ() directly.
3155:       */
3156:       PetscCall(ISGetNonlocalIS(iscol[i], &ciscol[ii]));
3157:       /* Now we have to
3158:          (a) make sure ciscol[ii] is sorted, since, even if the off-proc indices
3159:              were sorted on each rank, concatenated they might no longer be sorted;
3160:          (b) Use ISSortPermutation() to construct ciscol_p, the mapping from the
3161:              indices in the nondecreasing order to the original index positions.
3162:          If ciscol[ii] is strictly increasing, the permutation IS is NULL.
3163:       */
3164:       PetscCall(ISSortPermutation(ciscol[ii], PETSC_FALSE, ciscol_p + ii));
3165:       if (ciscol_p[ii] != NULL) {
3166:         IS sorted;

3168:         /* preserve the cached ordering for subsequent extractions */
3169:         PetscCall(ISDuplicate(ciscol[ii], &sorted));
3170:         PetscCall(ISRestoreNonlocalIS(iscol[i], &ciscol[ii]));
3171:         ciscol[ii] = sorted;
3172:         PetscCall(ISSort(ciscol[ii]));
3173:       }
3174:       ++ii;
3175:     }
3176:   }
3177:   PetscCall(PetscMalloc2(ismax, &isrow_p, ismax, &iscol_p));
3178:   for (PetscInt i = 0, ii = 0; i < ismax; ++i) {
3179:     PetscInt        issize;
3180:     const PetscInt *indices;

3182:     /*
3183:        Permute the indices into a nondecreasing order. Reject row and col indices with duplicates.
3184:      */
3185:     PetscCall(ISSortPermutation(isrow[i], PETSC_FALSE, isrow_p + i));
3186:     PetscCall(ISSort(isrow[i]));
3187:     PetscCall(ISGetLocalSize(isrow[i], &issize));
3188:     PetscCall(ISGetIndices(isrow[i], &indices));
3189:     for (PetscInt j = 1; j < issize; ++j) {
3190:       PetscCheck(indices[j] != indices[j - 1], PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Repeated indices in row IS %" PetscInt_FMT ": indices at %" PetscInt_FMT " and %" PetscInt_FMT " are both %" PetscInt_FMT, i, j - 1, j, indices[j]);
3191:     }
3192:     PetscCall(ISRestoreIndices(isrow[i], &indices));
3193:     if (isrow[i] == iscol[i]) {
3194:       /* Row and column are the same IS; isrow[i] is already sorted, so reuse row permutation */
3195:       iscol_p[i] = isrow_p[i];
3196:       PetscCall(PetscObjectReference((PetscObject)iscol_p[i]));
3197:     } else {
3198:       PetscCall(ISSortPermutation(iscol[i], PETSC_FALSE, iscol_p + i));
3199:       PetscCall(ISSort(iscol[i]));
3200:       PetscCall(ISGetLocalSize(iscol[i], &issize));
3201:       PetscCall(ISGetIndices(iscol[i], &indices));
3202:       for (PetscInt j = 1; j < issize; ++j) {
3203:         PetscCheck(indices[j - 1] != indices[j], PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Repeated indices in col IS %" PetscInt_FMT ": indices at %" PetscInt_FMT " and %" PetscInt_FMT " are both %" PetscInt_FMT, i, j - 1, j, indices[j]);
3204:       }
3205:       PetscCall(ISRestoreIndices(iscol[i], &indices));
3206:     }
3207:     PetscCallMPI(MPI_Comm_size(((PetscObject)isrow[i])->comm, &size));
3208:     if (size > 1) {
3209:       cisrow[ii] = isrow[i];
3210:       ++ii;
3211:     }
3212:   }
3213:   /*
3214:     Allocate the necessary arrays to hold the resulting parallel matrices as well as the intermediate
3215:     array of sequential matrices underlying the resulting parallel matrices.
3216:     Which arrays to allocate is based on the value of MatReuse scall and whether ISs are sorted and/or
3217:     contain duplicates.

3219:     There are as many diag matrices as there are original index sets. There are only as many parallel
3220:     and off-diag matrices, as there are parallel (comm size > 1) index sets.

3222:     ARRAYS that can hold Seq matrices get allocated in any event -- either here or by getsubmats_seq():
3223:     - If the array of MPI matrices already exists and is being reused, we need to allocate the array
3224:       and extract the underlying seq matrices into it to serve as placeholders, into which getsubmats_seq
3225:       will deposite the extracted diag and off-diag parts. Thus, we allocate the A&B arrays and fill them
3226:       with A[i] and B[ii] extracted from the corresponding MPI submat.
3227:     - However, if the rows, A's column indices or B's column indices are not sorted, the extracted A[i] & B[ii]
3228:       will have a different order from what getsubmats_seq expects.  To handle this case -- indicated
3229:       by a nonzero isrow_p[i], iscol_p[i], or ciscol_p[ii] -- we duplicate A[i] --> AA[i], B[ii] --> BB[ii]
3230:       (retrieve composed AA[i] or BB[ii]) and reuse them here. AA[i] and BB[ii] are then used to permute its
3231:       values into A[i] and B[ii] sitting inside the corresponding submat.
3232:     - If no reuse is taking place then getsubmats_seq will allocate the A&B arrays and create the corresponding
3233:       A[i], B[ii], AA[i] or BB[ii] matrices.
3234:   */
3235:   /* Parallel matrix array is allocated here only if no reuse is taking place. If reused, it is passed in by the caller. */
3236:   if (scall == MAT_INITIAL_MATRIX) PetscCall(PetscMalloc1(ismax, submat));

3238:   /* Now obtain the sequential A and B submatrices separately. */
3239:   /* scall=MAT_REUSE_MATRIX is not handled yet, because getsubmats_seq() requires reuse of A and B */
3240:   PetscCall((*getsubmats_seq)(C, ismax, isrow, iscol, MAT_INITIAL_MATRIX, &A));
3241:   PetscCall((*getsubmats_seq)(C, cismax, cisrow, ciscol, MAT_INITIAL_MATRIX, &B));

3243:   /*
3244:     If scall == MAT_REUSE_MATRIX AND the permutations are NULL, we are done, since the sequential
3245:     matrices A & B have been extracted directly into the parallel matrices containing them, or
3246:     simply into the sequential matrix identical with the corresponding A (if size == 1).
3247:     Note that in that case colmap doesn't need to be rebuilt, since the matrices are expected
3248:     to have the same sparsity pattern.
3249:     Otherwise, A and/or B have to be properly embedded into C's index spaces and the correct colmap
3250:     must be constructed for C. This is done by setseqmat(s).
3251:   */
3252:   for (PetscInt i = 0, ii = 0; i < ismax; ++i) {
3253:     /*
3254:        TODO: cache ciscol, permutation ISs and maybe cisrow? What about isrow & iscol?
3255:        That way we can avoid sorting and computing permutations when reusing.
3256:        To this end:
3257:         - remove the old cache, if it exists, when extracting submatrices with MAT_INITIAL_MATRIX
3258:         - if caching arrays to hold the ISs, make and compose a container for them so that it can
3259:           be destroyed upon destruction of C (use PetscContainerUserDestroy() to clear out the contents).
3260:     */
3261:     MatStructure pattern = DIFFERENT_NONZERO_PATTERN;

3263:     PetscCallMPI(MPI_Comm_size(((PetscObject)isrow[i])->comm, &size));
3264:     /* Construct submat[i] from the Seq pieces A (and B, if necessary). */
3265:     if (size > 1) {
3266:       if (scall == MAT_INITIAL_MATRIX) {
3267:         MatType type;

3269:         PetscCall(MatGetRootType_Private(C, &type));
3270:         PetscCall(MatCreate(((PetscObject)isrow[i])->comm, (*submat) + i));
3271:         PetscCall(MatSetSizes((*submat)[i], A[i]->rmap->n, A[i]->cmap->n, PETSC_DETERMINE, PETSC_DETERMINE));
3272:         PetscCall(MatSetBlockSizesFromMats((*submat)[i], A[i], A[i]));
3273:         PetscCall(MatSetType((*submat)[i], type));
3274:         PetscCall(PetscLayoutSetUp((*submat)[i]->rmap));
3275:         PetscCall(PetscLayoutSetUp((*submat)[i]->cmap));
3276:       }
3277:       /*
3278:         For each parallel isrow[i], insert the extracted sequential matrices into the parallel matrix.
3279:       */
3280:       {
3281:         Mat AA = A[i], BB = B[ii];

3283:         if (AA || BB) {
3284:           PetscBool nooffprocentries = (*submat)[i]->nooffprocentries;

3286:           PetscCall(setseqmats((*submat)[i], isrow_p[i], iscol_p[i], ciscol_p[ii], pattern, AA, BB));
3287:           PetscCall(MatSetOption((*submat)[i], MAT_NO_OFF_PROC_ENTRIES, PETSC_TRUE)); /* only the local diagonal and off-diagonal blocks were filled */
3288:           PetscCall(MatAssemblyBegin((*submat)[i], MAT_FINAL_ASSEMBLY));
3289:           PetscCall(MatAssemblyEnd((*submat)[i], MAT_FINAL_ASSEMBLY));
3290:           PetscCall(MatSetOption((*submat)[i], MAT_NO_OFF_PROC_ENTRIES, nooffprocentries));
3291:         }
3292:         PetscCall(MatDestroy(&AA));
3293:       }
3294:       if (ciscol_p[ii] != NULL) PetscCall(ISDestroy(ciscol + ii));
3295:       else PetscCall(ISRestoreNonlocalIS(iscol[i], ciscol + ii));
3296:       PetscCall(ISDestroy(ciscol_p + ii));
3297:       ++ii;
3298:     } else { /* if (size == 1) */
3299:       if (scall == MAT_REUSE_MATRIX) PetscCall(MatDestroy(&(*submat)[i]));
3300:       if (isrow_p[i] || iscol_p[i]) {
3301:         PetscCall(MatDuplicate(A[i], MAT_DO_NOT_COPY_VALUES, (*submat) + i));
3302:         PetscCall(setseqmat((*submat)[i], isrow_p[i], iscol_p[i], pattern, A[i]));
3303:         /* Otherwise A is extracted straight into (*submats)[i]. */
3304:         /* TODO: Compose A[i] on (*submat([i] for future use, if ((isrow_p[i] || iscol_p[i]) && MAT_INITIAL_MATRIX). */
3305:         PetscCall(MatDestroy(A + i));
3306:       } else (*submat)[i] = A[i];
3307:     }
3308:     PetscCall(ISDestroy(&isrow_p[i]));
3309:     PetscCall(ISDestroy(&iscol_p[i]));
3310:   }
3311:   PetscCall(PetscFree2(cisrow, ciscol));
3312:   PetscCall(PetscFree2(isrow_p, iscol_p));
3313:   PetscCall(PetscFree(ciscol_p));
3314:   PetscCall(PetscFree(A));
3315:   PetscCall(MatDestroySubMatrices(cismax, &B));
3316:   PetscFunctionReturn(PETSC_SUCCESS);
3317: }

3319: PetscErrorCode MatCreateSubMatricesMPI_MPIAIJ(Mat C, PetscInt ismax, const IS isrow[], const IS iscol[], MatReuse scall, Mat *submat[])
3320: {
3321:   PetscFunctionBegin;
3322:   PetscCall(MatCreateSubMatricesMPI_MPIXAIJ(C, ismax, isrow, iscol, scall, submat, MatCreateSubMatrices_MPIAIJ, MatGetSeqMats_MPIAIJ, MatSetSeqMat_SeqAIJ, MatSetSeqMats_MPIAIJ));
3323:   PetscFunctionReturn(PETSC_SUCCESS);
3324: }