Actual source code: mpimatmatmult.c

  1: /*
  2:   Defines matrix-matrix product routines for pairs of MPIAIJ matrices
  3:           C = A * B
  4: */
  5: #include <../src/mat/impls/aij/seq/aij.h>
  6: #include <../src/mat/utils/freespace.h>
  7: #include <../src/mat/impls/aij/mpi/mpiaij.h>
  8: #include <petscbt.h>
  9: #include <../src/mat/impls/dense/mpi/mpidense.h>
 10: #include <petsc/private/vecimpl.h>
 11: #include <petsc/private/sfimpl.h>

 13: #if PetscDefined(HAVE_HYPRE)
 14: PETSC_INTERN PetscErrorCode MatMatMultSymbolic_AIJ_AIJ_wHYPRE(Mat, Mat, PetscReal, Mat);
 15: #endif

 17: PETSC_INTERN PetscErrorCode MatProductSymbolic_ABt_MPIAIJ_MPIAIJ(Mat C)
 18: {
 19:   Mat_Product *product = C->product;
 20:   Mat          B       = product->B;

 22:   PetscFunctionBegin;
 23:   PetscCall(MatTranspose(B, MAT_INITIAL_MATRIX, &product->B));
 24:   PetscCall(MatDestroy(&B));
 25:   PetscCall(MatProductSymbolic_AB_MPIAIJ_MPIAIJ(C));
 26:   PetscFunctionReturn(PETSC_SUCCESS);
 27: }

 29: PETSC_INTERN PetscErrorCode MatProductSymbolic_AB_MPIAIJ_MPIAIJ(Mat C)
 30: {
 31:   Mat_Product        *product = C->product;
 32:   Mat                 A = product->A, B = product->B;
 33:   MatProductAlgorithm alg  = product->alg;
 34:   PetscReal           fill = product->fill;
 35:   PetscBool           flg;

 37:   PetscFunctionBegin;
 38:   /* scalable */
 39:   PetscCall(PetscStrcmp(alg, "scalable", &flg));
 40:   if (flg || C->structure_only) {
 41:     if (C->structure_only) PetscCall(MatProductSetAlgorithm(C, "scalable"));
 42:     PetscCall(MatMatMultSymbolic_MPIAIJ_MPIAIJ(A, B, fill, C));
 43:     PetscFunctionReturn(PETSC_SUCCESS);
 44:   }

 46:   /* nonscalable */
 47:   PetscCall(PetscStrcmp(alg, "nonscalable", &flg));
 48:   if (flg) {
 49:     PetscCall(MatMatMultSymbolic_MPIAIJ_MPIAIJ_nonscalable(A, B, fill, C));
 50:     PetscFunctionReturn(PETSC_SUCCESS);
 51:   }

 53:   /* seqmpi */
 54:   PetscCall(PetscStrcmp(alg, "seqmpi", &flg));
 55:   if (flg) {
 56:     PetscCall(MatMatMultSymbolic_MPIAIJ_MPIAIJ_seqMPI(A, B, fill, C));
 57:     PetscFunctionReturn(PETSC_SUCCESS);
 58:   }

 60:   /* backend general code */
 61:   PetscCall(PetscStrcmp(alg, "backend", &flg));
 62:   if (flg) {
 63:     PetscCall(MatProductSymbolic_MPIAIJBACKEND(C));
 64:     PetscFunctionReturn(PETSC_SUCCESS);
 65:   }

 67: #if PetscDefined(HAVE_HYPRE)
 68:   PetscCall(PetscStrcmp(alg, "hypre", &flg));
 69:   if (flg) {
 70:     PetscCall(MatMatMultSymbolic_AIJ_AIJ_wHYPRE(A, B, fill, C));
 71:     PetscFunctionReturn(PETSC_SUCCESS);
 72:   }
 73: #endif
 74:   SETERRQ(PetscObjectComm((PetscObject)C), PETSC_ERR_SUP, "Mat Product Algorithm is not supported");
 75: }

 77: PetscErrorCode MatProductCtxDestroy_MPIAIJ_MatMatMult(PetscCtxRt data)
 78: {
 79:   MatProductCtx_APMPI *ptap = *(MatProductCtx_APMPI **)data;

 81:   PetscFunctionBegin;
 82:   PetscCall(PetscFree2(ptap->startsj_s, ptap->startsj_r));
 83:   PetscCall(PetscFree(ptap->bufa));
 84:   PetscCall(MatDestroy(&ptap->P_loc));
 85:   PetscCall(MatDestroy(&ptap->P_oth));
 86:   PetscCall(MatDestroy(&ptap->Pt));
 87:   PetscCall(PetscFree(ptap->api));
 88:   PetscCall(PetscFree(ptap->apj));
 89:   PetscCall(PetscFree(ptap->apa));
 90:   PetscCall(PetscFree(ptap));
 91:   PetscFunctionReturn(PETSC_SUCCESS);
 92: }

 94: PetscErrorCode MatMatMultNumeric_MPIAIJ_MPIAIJ_nonscalable(Mat A, Mat P, Mat C)
 95: {
 96:   Mat_MPIAIJ          *a = (Mat_MPIAIJ *)A->data, *c = (Mat_MPIAIJ *)C->data;
 97:   Mat_SeqAIJ          *ad = (Mat_SeqAIJ *)a->A->data, *ao = (Mat_SeqAIJ *)a->B->data;
 98:   Mat_SeqAIJ          *cd = (Mat_SeqAIJ *)c->A->data, *co = (Mat_SeqAIJ *)c->B->data;
 99:   PetscScalar         *cda, *coa;
100:   Mat_SeqAIJ          *p_loc, *p_oth;
101:   PetscScalar         *apa, *ca;
102:   PetscInt             cm = C->rmap->n;
103:   MatProductCtx_APMPI *ptap;
104:   PetscInt            *api, *apj, *apJ, i, k;
105:   PetscInt             cstart = C->cmap->rstart;
106:   PetscInt             cdnz, conz, k0, k1;
107:   const PetscScalar   *dummy1, *dummy2, *dummy3, *dummy4;
108:   MPI_Comm             comm;
109:   PetscMPIInt          size;

111:   PetscFunctionBegin;
112:   MatCheckProduct(C, 3);
113:   ptap = (MatProductCtx_APMPI *)C->product->data;
114:   PetscCheck(ptap, PetscObjectComm((PetscObject)C), PETSC_ERR_ARG_WRONGSTATE, "PtAP cannot be computed. Missing data");
115:   PetscCall(PetscObjectGetComm((PetscObject)A, &comm));
116:   PetscCallMPI(MPI_Comm_size(comm, &size));
117:   PetscCheck(ptap->P_oth || size <= 1, PetscObjectComm((PetscObject)C), PETSC_ERR_ARG_WRONGSTATE, "AP cannot be reused. Do not call MatProductClear()");

119:   /* flag CPU mask for C */
120: #if PetscDefined(HAVE_DEVICE)
121:   if (C->offloadmask != PETSC_OFFLOAD_UNALLOCATED) C->offloadmask = PETSC_OFFLOAD_CPU;
122:   if (c->A->offloadmask != PETSC_OFFLOAD_UNALLOCATED) c->A->offloadmask = PETSC_OFFLOAD_CPU;
123:   if (c->B->offloadmask != PETSC_OFFLOAD_UNALLOCATED) c->B->offloadmask = PETSC_OFFLOAD_CPU;
124: #endif

126:   /* 1) get P_oth = ptap->P_oth  and P_loc = ptap->P_loc */
127:   /* update numerical values of P_oth and P_loc */
128:   PetscCall(MatGetBrowsOfAoCols_MPIAIJ(A, P, MAT_REUSE_MATRIX, &ptap->startsj_s, &ptap->startsj_r, &ptap->bufa, &ptap->P_oth));
129:   PetscCall(MatMPIAIJGetLocalMat(P, MAT_REUSE_MATRIX, &ptap->P_loc));

131:   /* 2) compute numeric C_loc = A_loc*P = Ad*P_loc + Ao*P_oth */
132:   /* get data from symbolic products */
133:   p_loc = (Mat_SeqAIJ *)ptap->P_loc->data;
134:   p_oth = NULL;
135:   if (size > 1) p_oth = (Mat_SeqAIJ *)ptap->P_oth->data;

137:   /* get apa for storing dense row A[i,:]*P */
138:   apa = ptap->apa;

140:   api = ptap->api;
141:   apj = ptap->apj;
142:   /* trigger copy to CPU */
143:   PetscCall(MatSeqAIJGetArrayRead(a->A, &dummy1));
144:   PetscCall(MatSeqAIJGetArrayRead(a->B, &dummy2));
145:   PetscCall(MatSeqAIJGetArrayRead(ptap->P_loc, &dummy3));
146:   if (ptap->P_oth) PetscCall(MatSeqAIJGetArrayRead(ptap->P_oth, &dummy4));
147:   PetscCall(MatSeqAIJGetArrayWrite(c->A, &cda));
148:   PetscCall(MatSeqAIJGetArrayWrite(c->B, &coa));
149:   for (i = 0; i < cm; i++) {
150:     /* compute apa = A[i,:]*P */
151:     AProw_nonscalable(i, ad, ao, p_loc, p_oth, apa);

153:     /* set values in C */
154:     apJ  = PetscSafePointerPlusOffset(apj, api[i]);
155:     cdnz = cd->i[i + 1] - cd->i[i];
156:     conz = co->i[i + 1] - co->i[i];

158:     /* 1st off-diagonal part of C */
159:     ca = PetscSafePointerPlusOffset(coa, co->i[i]);
160:     k  = 0;
161:     for (k0 = 0; k0 < conz; k0++) {
162:       if (apJ[k] >= cstart) break;
163:       ca[k0]        = apa[apJ[k]];
164:       apa[apJ[k++]] = 0.0;
165:     }

167:     /* diagonal part of C */
168:     ca = PetscSafePointerPlusOffset(cda, cd->i[i]);
169:     for (k1 = 0; k1 < cdnz; k1++) {
170:       ca[k1]        = apa[apJ[k]];
171:       apa[apJ[k++]] = 0.0;
172:     }

174:     /* 2nd off-diagonal part of C */
175:     ca = PetscSafePointerPlusOffset(coa, co->i[i]);
176:     for (; k0 < conz; k0++) {
177:       ca[k0]        = apa[apJ[k]];
178:       apa[apJ[k++]] = 0.0;
179:     }
180:   }
181:   PetscCall(MatSeqAIJRestoreArrayRead(a->A, &dummy1));
182:   PetscCall(MatSeqAIJRestoreArrayRead(a->B, &dummy2));
183:   PetscCall(MatSeqAIJRestoreArrayRead(ptap->P_loc, &dummy3));
184:   if (ptap->P_oth) PetscCall(MatSeqAIJRestoreArrayRead(ptap->P_oth, &dummy4));
185:   PetscCall(MatSeqAIJRestoreArrayWrite(c->A, &cda));
186:   PetscCall(MatSeqAIJRestoreArrayWrite(c->B, &coa));

188:   PetscCall(MatAssemblyBegin(C, MAT_FINAL_ASSEMBLY));
189:   PetscCall(MatAssemblyEnd(C, MAT_FINAL_ASSEMBLY));
190:   PetscFunctionReturn(PETSC_SUCCESS);
191: }

193: PetscErrorCode MatMatMultSymbolic_MPIAIJ_MPIAIJ_nonscalable(Mat A, Mat P, PetscReal fill, Mat C)
194: {
195:   MPI_Comm             comm;
196:   PetscMPIInt          size;
197:   MatProductCtx_APMPI *ptap;
198:   PetscFreeSpaceList   free_space = NULL, current_space = NULL;
199:   Mat_MPIAIJ          *a  = (Mat_MPIAIJ *)A->data;
200:   Mat_SeqAIJ          *ad = (Mat_SeqAIJ *)a->A->data, *ao = (Mat_SeqAIJ *)a->B->data, *p_loc, *p_oth;
201:   PetscInt            *pi_loc, *pj_loc, *pi_oth, *pj_oth, *dnz, *onz;
202:   PetscInt            *adi = ad->i, *adj = ad->j, *aoi = ao->i, *aoj = ao->j, rstart = A->rmap->rstart;
203:   PetscInt            *lnk, i, pnz, row, *api, *apj, *Jptr, apnz, nspacedouble = 0, j, nzi;
204:   PetscInt             am = A->rmap->n, pN = P->cmap->N, pn = P->cmap->n, pm = P->rmap->n;
205:   PetscBT              lnkbt;
206:   PetscReal            afill;
207:   MatType              mtype;

209:   PetscFunctionBegin;
210:   MatCheckProduct(C, 4);
211:   PetscCheck(!C->product->data, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Extra product struct not empty");
212:   PetscCall(PetscObjectGetComm((PetscObject)A, &comm));
213:   PetscCallMPI(MPI_Comm_size(comm, &size));

215:   /* create struct MatProductCtx_APMPI and attached it to C later */
216:   PetscCall(PetscNew(&ptap));

218:   /* get P_oth by taking rows of P (= non-zero cols of local A) from other processors */
219:   PetscCall(MatGetBrowsOfAoCols_MPIAIJ(A, P, MAT_INITIAL_MATRIX, &ptap->startsj_s, &ptap->startsj_r, &ptap->bufa, &ptap->P_oth));

221:   /* get P_loc by taking all local rows of P */
222:   PetscCall(MatMPIAIJGetLocalMat(P, MAT_INITIAL_MATRIX, &ptap->P_loc));

224:   p_loc  = (Mat_SeqAIJ *)ptap->P_loc->data;
225:   pi_loc = p_loc->i;
226:   pj_loc = p_loc->j;
227:   if (size > 1) {
228:     p_oth  = (Mat_SeqAIJ *)ptap->P_oth->data;
229:     pi_oth = p_oth->i;
230:     pj_oth = p_oth->j;
231:   } else {
232:     p_oth  = NULL;
233:     pi_oth = NULL;
234:     pj_oth = NULL;
235:   }

237:   /* first, compute symbolic AP = A_loc*P = A_diag*P_loc + A_off*P_oth */
238:   PetscCall(PetscMalloc1(am + 1, &api));
239:   ptap->api = api;
240:   api[0]    = 0;

242:   /* create and initialize a linked list */
243:   PetscCall(PetscLLCondensedCreate(pN, pN, &lnk, &lnkbt));

245:   /* Initial FreeSpace size is fill*(nnz(A)+nnz(P)) */
246:   PetscCall(PetscFreeSpaceGet(PetscRealIntMultTruncate(fill, PetscIntSumTruncate(adi[am], PetscIntSumTruncate(aoi[am], pi_loc[pm]))), &free_space));
247:   current_space = free_space;

249:   MatPreallocateBegin(comm, am, pn, dnz, onz);
250:   for (i = 0; i < am; i++) {
251:     /* diagonal portion of A */
252:     nzi = adi[i + 1] - adi[i];
253:     for (j = 0; j < nzi; j++) {
254:       row  = *adj++;
255:       pnz  = pi_loc[row + 1] - pi_loc[row];
256:       Jptr = pj_loc + pi_loc[row];
257:       /* add non-zero cols of P into the sorted linked list lnk */
258:       PetscCall(PetscLLCondensedAddSorted(pnz, Jptr, lnk, lnkbt));
259:     }
260:     /* off-diagonal portion of A */
261:     nzi = aoi[i + 1] - aoi[i];
262:     for (j = 0; j < nzi; j++) {
263:       row  = *aoj++;
264:       pnz  = pi_oth[row + 1] - pi_oth[row];
265:       Jptr = pj_oth + pi_oth[row];
266:       PetscCall(PetscLLCondensedAddSorted(pnz, Jptr, lnk, lnkbt));
267:     }
268:     /* add possible missing diagonal entry */
269:     if (C->force_diagonals) {
270:       j = i + rstart; /* column index */
271:       PetscCall(PetscLLCondensedAddSorted(1, &j, lnk, lnkbt));
272:     }

274:     apnz       = lnk[0];
275:     api[i + 1] = api[i] + apnz;

277:     /* if free space is not available, double the total space in the list */
278:     if (current_space->local_remaining < apnz) {
279:       PetscCall(PetscFreeSpaceGet(PetscIntSumTruncate(apnz, current_space->total_array_size), &current_space));
280:       nspacedouble++;
281:     }

283:     /* Copy data into free space, then initialize lnk */
284:     PetscCall(PetscLLCondensedClean(pN, apnz, current_space->array, lnk, lnkbt));
285:     PetscCall(MatPreallocateSet(i + rstart, apnz, current_space->array, dnz, onz));

287:     current_space->array += apnz;
288:     current_space->local_used += apnz;
289:     current_space->local_remaining -= apnz;
290:   }

292:   /* Allocate space for apj, initialize apj, and */
293:   /* destroy list of free space and other temporary array(s) */
294:   PetscCall(PetscMalloc1(api[am], &ptap->apj));
295:   apj = ptap->apj;
296:   PetscCall(PetscFreeSpaceContiguous(&free_space, ptap->apj));
297:   PetscCall(PetscLLDestroy(lnk, lnkbt));

299:   /* malloc apa to store dense row A[i,:]*P */
300:   PetscCall(PetscCalloc1(pN, &ptap->apa));

302:   /* set and assemble symbolic parallel matrix C */
303:   PetscCall(MatSetSizes(C, am, pn, PETSC_DETERMINE, PETSC_DETERMINE));
304:   PetscCall(MatSetBlockSizesFromMats(C, A, P));

306:   PetscCall(MatGetType(A, &mtype));
307:   PetscCall(MatSetType(C, mtype));
308:   PetscCall(MatMPIAIJSetPreallocation(C, 0, dnz, 0, onz));
309:   MatPreallocateEnd(dnz, onz);

311:   PetscCall(MatSetValues_MPIAIJ_CopyFromCSRFormat_Symbolic(C, apj, api));
312:   PetscCall(MatSetOption(C, MAT_NO_OFF_PROC_ENTRIES, PETSC_TRUE));
313:   PetscCall(MatAssemblyBegin(C, MAT_FINAL_ASSEMBLY));
314:   PetscCall(MatAssemblyEnd(C, MAT_FINAL_ASSEMBLY));
315:   PetscCall(MatSetOption(C, MAT_NEW_NONZERO_LOCATION_ERR, PETSC_TRUE));

317:   C->ops->matmultnumeric = MatMatMultNumeric_MPIAIJ_MPIAIJ_nonscalable;
318:   C->ops->productnumeric = MatProductNumeric_AB;

320:   /* attach the supporting struct to C for reuse */
321:   C->product->data    = ptap;
322:   C->product->destroy = MatProductCtxDestroy_MPIAIJ_MatMatMult;

324:   /* set MatInfo */
325:   afill = (PetscReal)api[am] / (adi[am] + aoi[am] + pi_loc[pm] + 1) + 1.e-5;
326:   if (afill < 1.0) afill = 1.0;
327:   C->info.mallocs           = nspacedouble;
328:   C->info.fill_ratio_given  = fill;
329:   C->info.fill_ratio_needed = afill;

331:   if (PetscDefined(USE_INFO)) {
332:     if (api[am]) {
333:       PetscCall(PetscInfo(C, "Reallocs %" PetscInt_FMT "; Fill ratio: given %g needed %g.\n", nspacedouble, (double)fill, (double)afill));
334:       PetscCall(PetscInfo(C, "Use MatMatMult(A,B,MatReuse,%g,&C) for best performance.;\n", (double)afill));
335:     } else PetscCall(PetscInfo(C, "Empty matrix product\n"));
336:   }
337:   PetscFunctionReturn(PETSC_SUCCESS);
338: }

340: static PetscErrorCode MatMatMultSymbolic_MPIAIJ_MPIDense(Mat, Mat, PetscReal, Mat);
341: static PetscErrorCode MatMatMultNumeric_MPIAIJ_MPIDense(Mat, Mat, Mat);

343: static PetscErrorCode MatProductSetFromOptions_MPIAIJ_MPIDense_AB(Mat C)
344: {
345:   Mat_Product *product = C->product;
346:   Mat          A = product->A, B = product->B;

348:   PetscFunctionBegin;
349:   if (A->cmap->rstart != B->rmap->rstart || A->cmap->rend != B->rmap->rend)
350:     SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Matrix local dimensions are incompatible, (%" PetscInt_FMT ", %" PetscInt_FMT ") != (%" PetscInt_FMT ",%" PetscInt_FMT ")", A->cmap->rstart, A->cmap->rend, B->rmap->rstart, B->rmap->rend);

352:   C->ops->matmultsymbolic = MatMatMultSymbolic_MPIAIJ_MPIDense;
353:   C->ops->productsymbolic = MatProductSymbolic_AB;
354:   PetscFunctionReturn(PETSC_SUCCESS);
355: }

357: static PetscErrorCode MatProductSetFromOptions_MPIAIJ_MPIDense_AtB(Mat C)
358: {
359:   Mat_Product *product = C->product;
360:   Mat          A = product->A, B = product->B;

362:   PetscFunctionBegin;
363:   if (A->rmap->rstart != B->rmap->rstart || A->rmap->rend != B->rmap->rend)
364:     SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Matrix local dimensions are incompatible, (%" PetscInt_FMT ", %" PetscInt_FMT ") != (%" PetscInt_FMT ",%" PetscInt_FMT ")", A->rmap->rstart, A->rmap->rend, B->rmap->rstart, B->rmap->rend);

366:   C->ops->transposematmultsymbolic = MatTransposeMatMultSymbolic_MPIAIJ_MPIDense;
367:   C->ops->productsymbolic          = MatProductSymbolic_AtB;
368:   PetscFunctionReturn(PETSC_SUCCESS);
369: }

371: PETSC_INTERN PetscErrorCode MatProductSetFromOptions_MPIAIJ_MPIDense(Mat C)
372: {
373:   Mat_Product *product = C->product;

375:   PetscFunctionBegin;
376:   switch (product->type) {
377:   case MATPRODUCT_AB:
378:     PetscCall(MatProductSetFromOptions_MPIAIJ_MPIDense_AB(C));
379:     break;
380:   case MATPRODUCT_AtB:
381:     PetscCall(MatProductSetFromOptions_MPIAIJ_MPIDense_AtB(C));
382:     break;
383:   default:
384:     break;
385:   }
386:   PetscFunctionReturn(PETSC_SUCCESS);
387: }

389: PETSC_INTERN PetscErrorCode MatMPIDenseScatterDestroy_Private(MPIAIJ_MPIDense *contents)
390: {
391:   PetscFunctionBegin;
392:   PetscCall(MatDestroy(&contents->workB));
393:   PetscCall(PetscSFDestroy(&contents->sf[0]));
394:   PetscCall(PetscSFDestroy(&contents->sf[1]));
395:   for (PetscInt i = 0; i < contents->nsends; i++) PetscCallMPI(MPI_Type_free(&contents->stype[i]));
396:   for (PetscInt i = 0; i < contents->nrecvs; i++) PetscCallMPI(MPI_Type_free(&contents->rtype[i]));
397:   PetscCall(PetscFree4(contents->stype, contents->rtype, contents->rwaits, contents->swaits));
398:   PetscFunctionReturn(PETSC_SUCCESS);
399: }

401: typedef struct {
402:   MPIAIJ_MPIDense scatter;
403:   Mat             workC; /* off-diagonal contribution A_o * workB on the device route, NULL otherwise */
404: } MPIAIJ_MPIDense_AB;

406: static PetscErrorCode MatMPIAIJ_MPIDenseDestroy(PetscCtxRt ctx)
407: {
408:   MPIAIJ_MPIDense_AB *data = *(MPIAIJ_MPIDense_AB **)ctx;

410:   PetscFunctionBegin;
411:   PetscCall(MatDestroy(&data->workC));
412:   PetscCall(MatMPIDenseScatterDestroy_Private(&data->scatter));
413:   PetscCall(PetscFree(data));
414:   PetscFunctionReturn(PETSC_SUCCESS);
415: }

417: /* Creates the parts of the scatter that depend on contents->blda: the strided PetscSFs on the device, the send datatypes on the host */
418: static PetscErrorCode MatMPIDenseScatterSetUpLDA_Private(VecScatter ctx, PetscInt bs, Mat B, MPIAIJ_MPIDense *contents)
419: {
420:   PetscInt        nrows = contents->workB->rmap->n;
421:   MPI_Datatype    type1;
422:   const PetscInt *sindices, *sstarts;
423:   PetscMPIInt    *disp;
424:   PetscMPIInt     nsends, nrows_to, bs_mpi;

426:   PetscFunctionBegin;
427:   if (contents->ondevice) {
428:     PetscCheck(ctx->vscat.bs <= 1 || contents->blda % ctx->vscat.bs == 0, PETSC_COMM_SELF, PETSC_ERR_ARG_INCOMP, "Leading dimension %" PetscInt_FMT " of the dense matrix must be a multiple of the block size %" PetscInt_FMT, contents->blda, ctx->vscat.bs);
429:     PetscCall(PetscSFCreateStridedSF(ctx, contents->ncols[0], contents->blda, nrows, &contents->sf[0]));
430:     if (contents->ncols[1] > 0) PetscCall(PetscSFCreateStridedSF(ctx, contents->ncols[1], contents->blda, nrows, &contents->sf[1]));
431:   } else {
432:     PetscCall(VecScatterGetRemote_Private(ctx, PETSC_TRUE, &nsends, &sstarts, &sindices, NULL, NULL));
433:     PetscCall(PetscMalloc1(PetscMax(B->rmap->n, 1), &disp));
434:     PetscCall(PetscMPIIntCast(bs, &bs_mpi));
435:     for (PetscMPIInt i = 0; i < nsends; i++) {
436:       PetscCall(PetscMPIIntCast(sstarts[i + 1] - sstarts[i], &nrows_to));
437:       for (PetscInt j = 0; j < nrows_to; j++) PetscCall(PetscMPIIntCast(sindices[sstarts[i] + j] * bs, &disp[j]));
438:       PetscCallMPI(MPI_Type_create_indexed_block(nrows_to, bs_mpi, disp, MPIU_SCALAR, &type1));
439:       PetscCallMPI(MPI_Type_create_resized(type1, 0, contents->blda * sizeof(PetscScalar), &contents->stype[i]));
440:       PetscCallMPI(MPI_Type_commit(&contents->stype[i]));
441:       PetscCallMPI(MPI_Type_free(&type1));
442:     }
443:     PetscCall(PetscFree(disp));
444:     PetscCall(VecScatterRestoreRemote_Private(ctx, PETSC_TRUE, &nsends, &sstarts, &sindices, NULL, NULL));
445:   }
446:   PetscFunctionReturn(PETSC_SUCCESS);
447: }

449: PETSC_INTERN PetscErrorCode MatMPIDenseScatterSetUp_Private(VecScatter ctx, PetscInt nrows, PetscInt bs, PetscInt Am, Mat B, Mat C, MPIAIJ_MPIDense *contents, PetscInt *batchSize, PetscInt *numBatches)
450: {
451:   PetscInt        BN = B->cmap->N, Bbn, Bbs, numBb, ncols;
452:   MPI_Comm        comm;
453:   MPI_Datatype    type1;
454:   const PetscInt *rstarts;
455:   PetscMPIInt     nsends, nrecvs, nrows_from, disp = 0;
456:   PetscBool       flg;

458:   PetscFunctionBegin;
459:   PetscCall(PetscObjectGetComm((PetscObject)C, &comm));
460:   PetscCall(MatDenseGetLDA(B, &contents->blda));
461:   PetscCall(PetscObjectGetId((PetscObject)B, &contents->bid));

463:   /* Create column block of B and C for memory scalability when BN is too large */
464:   /* Estimate Bbn, column size of Bb */
465:   if (nrows) {
466:     Bbn = 2 * Am * BN / nrows;
467:     if (!Bbn) Bbn = 1;
468:   } else Bbn = BN;
469:   Bbs = B->cmap->bs;
470:   Bbn = Bbn / Bbs * Bbs;
471:   if (Bbn > BN) Bbn = BN;
472:   PetscCallMPI(MPIU_Allreduce(MPI_IN_PLACE, &Bbn, 1, MPIU_INT, MPI_MAX, comm));

474:   /* Enable runtime option for Bbn */
475:   PetscOptionsBegin(comm, ((PetscObject)C)->prefix, "MatProduct", "Mat");
476:   PetscCall(PetscOptionsDeprecated("-matmatmult_Bbn", "-matproduct_batch_size", "3.25", NULL));
477:   PetscCall(PetscOptionsBoundedInt("-matproduct_batch_size", "Number of dense columns per batch", "MatProduct", Bbn, &Bbn, NULL, 0));
478:   PetscOptionsEnd();
479:   Bbn = PetscMin(Bbn, BN);

481:   if (Bbn > 0 && Bbn < BN) numBb = BN / Bbn;
482:   else numBb = 0;
483:   if (numBb) PetscCall(PetscInfo(C, "Using column batches of size %" PetscInt_FMT " for %" PetscInt_FMT " dense columns\n", Bbn, BN));
484:   ncols = Bbn ? Bbn : BN;

486:   /* Create work matrix used to store off processor rows of B needed for local product, with the same type as the local block of B */
487:   PetscCall(MatCreate(PETSC_COMM_SELF, &contents->workB));
488:   PetscCall(MatSetSizes(contents->workB, nrows, ncols, nrows, ncols));
489:   PetscCall(MatSetType(contents->workB, ((PetscObject)((Mat_MPIDense *)B->data)->A)->type_name));
490:   PetscCall(MatSetUp(contents->workB));

492:   PetscCall(PetscObjectTypeCompare((PetscObject)((Mat_MPIDense *)B->data)->A, MATSEQDENSE, &flg));
493:   contents->ondevice = (PetscBool)!flg;
494:   if (contents->ondevice) {
495:     /* Use strided PetscSFs, which support device memory, instead of the MPI derived data types below */
496:     contents->ncols[0] = ncols;
497:     if (numBb > 0 && BN % Bbn != 0) contents->ncols[1] = BN % Bbn;
498:   } else {
499:     PetscCall(VecScatterGetRemote_Private(ctx, PETSC_TRUE, &nsends, NULL, NULL, NULL, NULL));
500:     PetscCall(VecScatterGetRemoteOrdered_Private(ctx, PETSC_FALSE, &nrecvs, &rstarts, NULL, NULL, NULL));

502:     /* Use MPI derived data type to reduce memory required by the send/recv buffers */
503:     PetscCall(PetscMalloc4(nsends, &contents->stype, nrecvs, &contents->rtype, nrecvs, &contents->rwaits, nsends, &contents->swaits));
504:     contents->nsends = nsends;
505:     contents->nrecvs = nrecvs;

507:     for (PetscMPIInt i = 0; i < nrecvs; i++) {
508:       /* received values from a process form a (nrows_from x Bbn) row block in workB (column-wise) */
509:       PetscCall(PetscMPIIntCast((rstarts[i + 1] - rstarts[i]) * bs, &nrows_from));
510:       PetscCallMPI(MPI_Type_create_indexed_block(1, nrows_from, &disp, MPIU_SCALAR, &type1));
511:       PetscCallMPI(MPI_Type_create_resized(type1, 0, nrows * sizeof(PetscScalar), &contents->rtype[i]));
512:       PetscCallMPI(MPI_Type_commit(&contents->rtype[i]));
513:       PetscCallMPI(MPI_Type_free(&type1));
514:     }

516:     PetscCall(VecScatterRestoreRemote_Private(ctx, PETSC_TRUE /*send*/, &nsends, NULL, NULL, NULL, NULL));
517:     PetscCall(VecScatterRestoreRemoteOrdered_Private(ctx, PETSC_FALSE /*recv*/, &nrecvs, &rstarts, NULL, NULL, NULL));
518:   }
519:   PetscCall(MatMPIDenseScatterSetUpLDA_Private(ctx, bs, B, contents));
520:   if (batchSize) *batchSize = Bbn;
521:   if (numBatches) *numBatches = numBb;
522:   PetscFunctionReturn(PETSC_SUCCESS);
523: }

525: /* Recreates the parts of the scatter that depend on the leading dimension when a new input B has a different one */
526: PETSC_INTERN PetscErrorCode MatMPIDenseScatterUpdateLDA_Private(VecScatter ctx, PetscInt bs, Mat B, Mat C, MPIAIJ_MPIDense *contents)
527: {
528:   PetscObjectId id;
529:   PetscInt      blda;
530:   PetscBool     update;

532:   PetscFunctionBegin;
533:   PetscCall(PetscObjectGetId((PetscObject)B, &id));
534:   if (id == contents->bid) PetscFunctionReturn(PETSC_SUCCESS);
535:   PetscCall(MatDenseGetLDA(B, &blda));
536:   update = (PetscBool)(blda != contents->blda);
537:   if (contents->ondevice) PetscCallMPI(MPIU_Allreduce(MPI_IN_PLACE, &update, 1, MPI_C_BOOL, MPI_LOR, PetscObjectComm((PetscObject)C)));
538:   if (update) {
539:     PetscCall(PetscInfo(C, "Setting up the scatter again for a dense input with leading dimension %" PetscInt_FMT " instead of %" PetscInt_FMT "\n", blda, contents->blda));
540:     PetscCall(PetscSFDestroy(&contents->sf[0]));
541:     PetscCall(PetscSFDestroy(&contents->sf[1]));
542:     for (PetscInt i = 0; i < contents->nsends; i++) PetscCallMPI(MPI_Type_free(&contents->stype[i]));
543:     contents->blda = blda;
544:     PetscCall(MatMPIDenseScatterSetUpLDA_Private(ctx, bs, B, contents));
545:   }
546:   contents->bid = id;
547:   PetscFunctionReturn(PETSC_SUCCESS);
548: }

550: static PetscErrorCode MatMatMultSymbolic_MPIAIJ_MPIDense(Mat A, Mat B, PetscReal fill, Mat C)
551: {
552:   Mat_MPIAIJ         *aij = (Mat_MPIAIJ *)A->data;
553:   MPIAIJ_MPIDense_AB *data;
554:   PetscInt            nz  = aij->B->cmap->n;
555:   VecScatter          ctx = aij->Mvctx;
556:   PetscInt            Am = A->rmap->n, BN = B->cmap->N, Bbn, numBb;
557:   Mat                 workB1, workC1;
558:   const char         *ctype;
559:   PetscBool           cisdense;

561:   PetscFunctionBegin;
562:   MatCheckProduct(C, 4);
563:   PetscCheck(!C->product->data, PetscObjectComm((PetscObject)C), PETSC_ERR_PLIB, "Product data not empty");
564:   PetscCall(PetscObjectBaseTypeCompare((PetscObject)C, MATMPIDENSE, &cisdense));
565:   if (!cisdense) {
566:     PetscCall(MatSetType(C, ((PetscObject)B)->type_name));
567:     PetscCall(MatSetVecType(C, B->defaultvectype));
568:   }
569:   PetscCall(MatSetSizes(C, Am, B->cmap->n, A->rmap->N, BN));
570:   PetscCall(MatSetBlockSizesFromMats(C, A, B));
571:   PetscCall(MatSetUp(C));
572:   /* The cuSPARSE and hipSPARSE symbolic below re-types a host local block of C in place, so capture the type
573:      of the local block of C now to give the work matrix the type the numeric will add it to */
574:   ctype = ((PetscObject)((Mat_MPIDense *)C->data)->A)->type_name;
575:   PetscCall(PetscNew(&data));
576:   PetscCall(MatMPIDenseScatterSetUp_Private(ctx, nz, 1, Am, B, C, &data->scatter, &Bbn, &numBb));
577:   PetscCall(MatSetOption(C, MAT_NO_OFF_PROC_ENTRIES, PETSC_TRUE));
578:   PetscCall(MatAssemblyBegin(C, MAT_FINAL_ASSEMBLY));
579:   PetscCall(MatAssemblyEnd(C, MAT_FINAL_ASSEMBLY));
580:   PetscCall(MatProductClear(aij->A));
581:   PetscCall(MatProductClear(((Mat_MPIDense *)B->data)->A));
582:   PetscCall(MatProductClear(((Mat_MPIDense *)C->data)->A));
583:   if (data->scatter.ondevice && nz) {
584:     /* On the device route the off-diagonal contribution is computed into a work matrix and added to the local
585:        block of C, rather than accumulated in place by a host kernel */
586:     PetscCall(MatCreate(PETSC_COMM_SELF, &data->workC));
587:     PetscCall(MatSetSizes(data->workC, Am, Bbn ? Bbn : BN, Am, Bbn ? Bbn : BN));
588:     PetscCall(MatSetType(data->workC, ctype));
589:     PetscCall(MatSetUp(data->workC));
590:     PetscCall(MatProductCreateWithMat(aij->B, data->scatter.workB, NULL, data->workC));
591:     PetscCall(MatProductSetType(data->workC, MATPRODUCT_AB));
592:     PetscCall(MatProductSetFromOptions(data->workC));
593:     PetscCall(MatProductSymbolic(data->workC));
594:     if (numBb && BN % Bbn) {
595:       /* the last column batch is smaller, set up the product on the sub-matrices the numeric will use for it */
596:       PetscCall(MatDenseGetSubMatrix(data->scatter.workB, PETSC_DECIDE, PETSC_DECIDE, 0, BN % Bbn, &workB1));
597:       PetscCall(MatDenseGetSubMatrix(data->workC, PETSC_DECIDE, PETSC_DECIDE, 0, BN % Bbn, &workC1));
598:       PetscCall(MatProductCreateWithMat(aij->B, workB1, NULL, workC1));
599:       PetscCall(MatProductSetType(workC1, MATPRODUCT_AB));
600:       PetscCall(MatProductSetFromOptions(workC1));
601:       PetscCall(MatProductSymbolic(workC1));
602:       PetscCall(MatDenseRestoreSubMatrix(data->workC, &workC1));
603:       PetscCall(MatDenseRestoreSubMatrix(data->scatter.workB, &workB1));
604:     }
605:   }
606:   PetscCall(MatProductCreateWithMat(aij->A, ((Mat_MPIDense *)B->data)->A, NULL, ((Mat_MPIDense *)C->data)->A));
607:   PetscCall(MatProductSetType(((Mat_MPIDense *)C->data)->A, MATPRODUCT_AB));
608:   PetscCall(MatProductSetFromOptions(((Mat_MPIDense *)C->data)->A));
609:   PetscCall(MatProductSymbolic(((Mat_MPIDense *)C->data)->A));
610:   C->product->data       = data;
611:   C->product->destroy    = MatMPIAIJ_MPIDenseDestroy;
612:   C->ops->matmultnumeric = MatMatMultNumeric_MPIAIJ_MPIDense;
613:   PetscFunctionReturn(PETSC_SUCCESS);
614: }

616: PETSC_INTERN PetscErrorCode MatMatMultNumericAdd_SeqAIJ_SeqDense(Mat, Mat, Mat, const PetscBool);

618: /*
619:     Performs an efficient scatter on the rows of B needed by this process; this is
620:     a modification of the VecScatterBegin_() routines.
621: */
622: static PetscErrorCode MatMPIDenseScatterHost_Private(VecScatter ctx, PetscInt bs, Mat workB, MPIAIJ_MPIDense *contents, Mat B, Mat C)
623: {
624:   const PetscScalar *b;
625:   PetscScalar       *rvalues;
626:   const PetscInt    *sindices, *sstarts, *rstarts;
627:   const PetscMPIInt *sprocs, *rprocs;
628:   PetscMPIInt        nsends, nrecvs;
629:   MPI_Comm           comm;
630:   PetscMPIInt        tag = ((PetscObject)ctx)->tag, ncols, nsends_mpi, nrecvs_mpi;

632:   PetscFunctionBegin;
633:   PetscCall(PetscMPIIntCast(B->cmap->N, &ncols));
634:   PetscCall(VecScatterGetRemote_Private(ctx, PETSC_TRUE /*send*/, &nsends, &sstarts, &sindices, &sprocs, NULL /*bs*/));
635:   PetscCall(VecScatterGetRemoteOrdered_Private(ctx, PETSC_FALSE /*recv*/, &nrecvs, &rstarts, NULL, &rprocs, NULL /*bs*/));
636:   PetscCall(PetscMPIIntCast(nsends, &nsends_mpi));
637:   PetscCall(PetscMPIIntCast(nrecvs, &nrecvs_mpi));

639:   PetscCall(MatDenseGetArrayRead(B, &b));
640:   PetscCall(MatDenseGetArray(workB, &rvalues));

642:   /* Post recv, use MPI derived data type to save memory */
643:   PetscCall(PetscObjectGetComm((PetscObject)C, &comm));
644:   for (PetscMPIInt i = 0; i < nrecvs; i++) PetscCallMPI(MPIU_Irecv(rvalues + ((rstarts[i] - rstarts[0]) * bs), ncols, contents->rtype[i], rprocs[i], tag, comm, contents->rwaits + i));
645:   for (PetscMPIInt i = 0; i < nsends; i++) PetscCallMPI(MPIU_Isend(b, ncols, contents->stype[i], sprocs[i], tag, comm, contents->swaits + i));

647:   if (nrecvs) PetscCallMPI(MPI_Waitall(nrecvs_mpi, contents->rwaits, MPI_STATUSES_IGNORE));
648:   if (nsends) PetscCallMPI(MPI_Waitall(nsends_mpi, contents->swaits, MPI_STATUSES_IGNORE));

650:   PetscCall(VecScatterRestoreRemote_Private(ctx, PETSC_TRUE /*send*/, &nsends, &sstarts, &sindices, &sprocs, NULL));
651:   PetscCall(VecScatterRestoreRemoteOrdered_Private(ctx, PETSC_FALSE /*recv*/, &nrecvs, &rstarts, NULL, &rprocs, NULL));
652:   PetscCall(MatDenseRestoreArrayRead(B, &b));
653:   PetscCall(MatDenseRestoreArray(workB, &rvalues));
654:   PetscFunctionReturn(PETSC_SUCCESS);
655: }

657: /*
658:    Same as MatMPIDenseScatterHost_Private(), but using the strided PetscSFs set up in
659:    MatMPIDenseScatterSetUp_Private() so that the data never leaves the device. The scatter is split in two
660:    halves so that a caller can run other work while the off-process rows of B are in flight
661: */
662: static PetscErrorCode MatMPIDenseScatterDeviceBegin_Private(Mat workB, MPIAIJ_MPIDense *contents, Mat B)
663: {
664:   PetscSF      sf;
665:   PetscInt     k = 0;
666:   PetscMemType bmtype, wmtype;

668:   PetscFunctionBegin;
669:   PetscCheck(!contents->sfinuse, PETSC_COMM_SELF, PETSC_ERR_PLIB, "A scatter is already in flight");
670:   if (B->cmap->N != contents->ncols[0]) k = 1;
671:   PetscCheck(contents->sf[k] && contents->ncols[k] == B->cmap->N, PETSC_COMM_SELF, PETSC_ERR_PLIB, "No scatter set up for %" PetscInt_FMT " columns", B->cmap->N);
672:   sf = contents->sf[k];
673:   /* every entry of workB is overwritten, so write-only access is enough */
674:   PetscCall(MatDenseGetArrayReadAndMemType(B, &contents->barray, &bmtype));
675:   PetscCall(MatDenseGetArrayWriteAndMemType(workB, &contents->warray, &wmtype));
676:   PetscCall(PetscSFBcastWithMemTypeBegin(sf, sf->vscat.unit, bmtype, contents->barray, wmtype, contents->warray, MPI_REPLACE));
677:   contents->sfinuse = sf;
678:   PetscFunctionReturn(PETSC_SUCCESS);
679: }

681: static PetscErrorCode MatMPIDenseScatterDeviceEnd_Private(Mat workB, MPIAIJ_MPIDense *contents, Mat B)
682: {
683:   PetscSF sf = contents->sfinuse;

685:   PetscFunctionBegin;
686:   PetscCheck(sf, PETSC_COMM_SELF, PETSC_ERR_PLIB, "No scatter in flight");
687:   PetscCall(PetscSFBcastEnd(sf, sf->vscat.unit, contents->barray, contents->warray, MPI_REPLACE));
688:   PetscCall(MatDenseRestoreArrayWriteAndMemType(workB, &contents->warray));
689:   PetscCall(MatDenseRestoreArrayReadAndMemType(B, &contents->barray));
690:   contents->sfinuse = NULL;
691:   PetscFunctionReturn(PETSC_SUCCESS);
692: }

694: /*
695:    The checks the host and device scatters share; on the device route they are done by the begin half
696: */
697: static PetscErrorCode MatMPIDenseScatterCheck_Private(PetscInt nrows, Mat workB, MPIAIJ_MPIDense *contents, Mat B, Mat C)
698: {
699:   PetscInt blda;

701:   PetscFunctionBegin;
702:   MatCheckProduct(C, 5);
703:   PetscCheck(C->product->data, PetscObjectComm((PetscObject)C), PETSC_ERR_PLIB, "Product data empty");
704:   PetscCheck(nrows == workB->rmap->n, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Number of rows of workB %" PetscInt_FMT " not equal to columns of off-diagonal block %" PetscInt_FMT, workB->rmap->n, nrows);
705:   PetscCall(MatDenseGetLDA(B, &blda));
706:   PetscCheck(blda == contents->blda, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Cannot reuse an input matrix with lda %" PetscInt_FMT " != %" PetscInt_FMT, blda, contents->blda);
707:   PetscFunctionReturn(PETSC_SUCCESS);
708: }

710: PETSC_INTERN PetscErrorCode MatMPIDenseScatter_Private(VecScatter ctx, PetscInt nrows, PetscInt bs, Mat workB, MPIAIJ_MPIDense *contents, Mat B, Mat C)
711: {
712:   PetscFunctionBegin;
713:   PetscCall(MatMPIDenseScatterCheck_Private(nrows, workB, contents, B, C));
714:   if (contents->ondevice) {
715:     PetscCall(MatMPIDenseScatterDeviceBegin_Private(workB, contents, B));
716:     PetscCall(MatMPIDenseScatterDeviceEnd_Private(workB, contents, B));
717:   } else PetscCall(MatMPIDenseScatterHost_Private(ctx, bs, workB, contents, B, C));
718:   PetscFunctionReturn(PETSC_SUCCESS);
719: }

721: /*
722:    Starts the scatter of the off-process rows of B into workB. On the device route only the begin half of the
723:    PetscSF broadcast is posted, so the caller must complete it with MatMPIDenseScatterEnd(); the host scatter
724:    is blocking and is done entirely here
725: */
726: static PetscErrorCode MatMPIDenseScatterBegin(Mat A, Mat B, Mat workB, Mat C)
727: {
728:   Mat_MPIAIJ      *aij      = (Mat_MPIAIJ *)A->data;
729:   MPIAIJ_MPIDense *contents = &((MPIAIJ_MPIDense_AB *)C->product->data)->scatter;

731:   PetscFunctionBegin;
732:   if (contents->ondevice) {
733:     PetscCall(MatMPIDenseScatterCheck_Private(aij->B->cmap->n, workB, contents, B, C));
734:     PetscCall(MatMPIDenseScatterDeviceBegin_Private(workB, contents, B));
735:   } else PetscCall(MatMPIDenseScatter_Private(aij->Mvctx, aij->B->cmap->n, 1, workB, contents, B, C));
736:   PetscFunctionReturn(PETSC_SUCCESS);
737: }

739: static PetscErrorCode MatMPIDenseScatterEnd(Mat B, Mat workB, Mat C)
740: {
741:   MPIAIJ_MPIDense *contents = &((MPIAIJ_MPIDense_AB *)C->product->data)->scatter;

743:   PetscFunctionBegin;
744:   if (contents->ondevice) PetscCall(MatMPIDenseScatterDeviceEnd_Private(workB, contents, B));
745:   PetscFunctionReturn(PETSC_SUCCESS);
746: }

748: /*
749:    Computes C = A * B, creating the nested product and its symbolic the first time. When clear is true the
750:    product is cleared by the numeric, so that the symbolic is redone on the next call
751: */
752: static PetscErrorCode MatMPIAIJ_MPIDenseProductNumeric_Private(Mat A, Mat B, Mat C, PetscBool clear)
753: {
754:   PetscFunctionBegin;
755:   if (!C->product) {
756:     PetscCall(MatProductCreateWithMat(A, B, NULL, C));
757:     PetscCall(MatProductSetType(C, MATPRODUCT_AB));
758:     PetscCall(MatProductSetFromOptions(C));
759:     PetscCall(MatProductSymbolic(C));
760:   } else PetscCall(MatProductReplaceMats(A, B, NULL, C));
761:   if (clear && !C->product->clear) C->product->clear = PETSC_TRUE;
762:   PetscCall(MatProductNumeric(C));
763:   PetscFunctionReturn(PETSC_SUCCESS);
764: }

766: static PetscErrorCode MatMatMultNumeric_MPIAIJ_MPIDense(Mat A, Mat B, Mat C)
767: {
768:   Mat_MPIAIJ         *aij    = (Mat_MPIAIJ *)A->data;
769:   Mat_MPIDense       *bdense = (Mat_MPIDense *)B->data;
770:   Mat_MPIDense       *cdense = (Mat_MPIDense *)C->data;
771:   Mat                 workB;
772:   MPIAIJ_MPIDense    *contents;
773:   MPIAIJ_MPIDense_AB *data;
774:   PetscBool           clear = PETSC_FALSE, flg, overlap;

776:   PetscFunctionBegin;
777:   MatCheckProduct(C, 3);
778:   PetscCheck(C->product->data, PetscObjectComm((PetscObject)C), PETSC_ERR_PLIB, "Product data empty");
779:   data     = (MPIAIJ_MPIDense_AB *)C->product->data;
780:   contents = &data->scatter;
781:   if (PetscDefined(HAVE_CUPM)) {
782:     PetscCall(PetscObjectTypeCompare((PetscObject)C, MATMPIDENSE, &flg));
783:     if (flg) PetscCall(PetscObjectTypeCompare((PetscObject)A, MATMPIAIJ, &flg));
784:     clear = (PetscBool)!flg; /* if either A or C is a device Mat, make sure MatProductClear() is called */
785:   }
786:   /* The device scatter is non-blocking, so when there are no column batches start it before the product of the
787:      diagonal block below to overlap the communication with that product, as MatMult_MPIAIJ() does. The host
788:      scatter is blocking, so it is left where it is */
789:   PetscCall(MatMPIDenseScatterUpdateLDA_Private(aij->Mvctx, 1, B, C, contents));
790:   overlap = (PetscBool)(contents->ondevice && contents->workB->cmap->n == B->cmap->N);
791:   if (overlap) PetscCall(MatMPIDenseScatterBegin(A, B, contents->workB, C));
792:   /* diagonal block of A times all local rows of B, first make sure that everything is up-to-date */
793:   PetscCall(MatMPIAIJ_MPIDenseProductNumeric_Private(aij->A, bdense->A, cdense->A, clear));
794:   if (contents->workB->cmap->n == B->cmap->N) {
795:     /* get off processor parts of B needed to complete C=A*B */
796:     workB = contents->workB;
797:     if (!overlap) PetscCall(MatMPIDenseScatterBegin(A, B, workB, C));
798:     PetscCall(MatMPIDenseScatterEnd(B, workB, C));

800:     /* off-diagonal block of A times nonlocal rows of B */
801:     if (data->workC) {
802:       PetscCall(MatMPIAIJ_MPIDenseProductNumeric_Private(aij->B, workB, data->workC, clear));
803:       PetscCall(MatAXPY(cdense->A, 1.0, data->workC, SAME_NONZERO_PATTERN));
804:     } else if (!contents->ondevice) PetscCall(MatMatMultNumericAdd_SeqAIJ_SeqDense(aij->B, workB, cdense->A, PETSC_TRUE)); /* the device route has no work matrix only when the off-diagonal block has no columns */
805:   } else {
806:     Mat       Bb, Cb, workC;
807:     PetscInt  BN = B->cmap->N, n = contents->workB->cmap->n, cols;
808:     PetscBool ccpu = PETSC_FALSE;

810:     PetscCheck(n > 0, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Column block size %" PetscInt_FMT " must be positive", n);
811:     /* The host route accumulates into the local block of C on the host, bind C to the CPU to avoid copies back
812:        and forth from the device when getting and restoring the sub-matrices */
813:     if (!contents->ondevice) {
814:       PetscCall(MatBoundToCPU(C, &ccpu));
815:       PetscCall(MatBindToCPU(C, PETSC_TRUE));
816:     }
817:     for (PetscInt i = 0; i < BN; i += n) {
818:       cols  = PetscMin(n, BN - i);
819:       workB = contents->workB;
820:       workC = data->workC;
821:       if (cols != n) {
822:         PetscCall(MatDenseGetSubMatrix(contents->workB, PETSC_DECIDE, PETSC_DECIDE, 0, cols, &workB));
823:         if (workC) PetscCall(MatDenseGetSubMatrix(data->workC, PETSC_DECIDE, PETSC_DECIDE, 0, cols, &workC));
824:       }
825:       PetscCall(MatDenseGetSubMatrix(B, PETSC_DECIDE, PETSC_DECIDE, i, i + cols, &Bb));
826:       PetscCall(MatDenseGetSubMatrix(C, PETSC_DECIDE, PETSC_DECIDE, i, i + cols, &Cb));

828:       /* get off processor parts of B needed to complete C=A*B */
829:       PetscCall(MatMPIDenseScatterBegin(A, Bb, workB, C));
830:       PetscCall(MatMPIDenseScatterEnd(Bb, workB, C));

832:       /* off-diagonal block of A times nonlocal rows of B */
833:       if (workC) {
834:         PetscCall(MatMPIAIJ_MPIDenseProductNumeric_Private(aij->B, workB, workC, clear));
835:         PetscCall(MatAXPY(((Mat_MPIDense *)Cb->data)->A, 1.0, workC, SAME_NONZERO_PATTERN));
836:       } else if (!contents->ondevice) PetscCall(MatMatMultNumericAdd_SeqAIJ_SeqDense(aij->B, workB, ((Mat_MPIDense *)Cb->data)->A, PETSC_TRUE));
837:       if (cols != n) {
838:         if (workC) PetscCall(MatDenseRestoreSubMatrix(data->workC, &workC));
839:         PetscCall(MatDenseRestoreSubMatrix(contents->workB, &workB));
840:       }
841:       PetscCall(MatDenseRestoreSubMatrix(B, &Bb));
842:       PetscCall(MatDenseRestoreSubMatrix(C, &Cb));
843:     }
844:     if (!contents->ondevice) PetscCall(MatBindToCPU(C, ccpu));
845:   }
846:   PetscFunctionReturn(PETSC_SUCCESS);
847: }

849: PetscErrorCode MatMatMultNumeric_MPIAIJ_MPIAIJ(Mat A, Mat P, Mat C)
850: {
851:   Mat_MPIAIJ          *a = (Mat_MPIAIJ *)A->data, *c = (Mat_MPIAIJ *)C->data;
852:   Mat_SeqAIJ          *ad = (Mat_SeqAIJ *)a->A->data, *ao = (Mat_SeqAIJ *)a->B->data;
853:   Mat_SeqAIJ          *cd = (Mat_SeqAIJ *)c->A->data, *co = (Mat_SeqAIJ *)c->B->data;
854:   PetscInt            *adi = ad->i, *adj, *aoi = ao->i, *aoj;
855:   PetscScalar         *ada, *aoa, *cda = cd->a, *coa = co->a;
856:   Mat_SeqAIJ          *p_loc, *p_oth;
857:   PetscInt            *pi_loc, *pj_loc, *pi_oth, *pj_oth, *pj;
858:   PetscScalar         *pa_loc, *pa_oth, *pa, valtmp, *ca;
859:   PetscInt             cm = C->rmap->n, anz, pnz;
860:   MatProductCtx_APMPI *ptap;
861:   PetscScalar         *apa_sparse;
862:   const PetscScalar   *dummy;
863:   PetscInt            *api, *apj, *apJ, i, j, k, row;
864:   PetscInt             cstart = C->cmap->rstart;
865:   PetscInt             cdnz, conz, k0, k1, nextp;
866:   MPI_Comm             comm;
867:   PetscMPIInt          size;

869:   PetscFunctionBegin;
870:   MatCheckProduct(C, 3);
871:   ptap = (MatProductCtx_APMPI *)C->product->data;
872:   PetscCheck(ptap, PetscObjectComm((PetscObject)C), PETSC_ERR_ARG_WRONGSTATE, "PtAP cannot be computed. Missing data");
873:   PetscCall(PetscObjectGetComm((PetscObject)C, &comm));
874:   PetscCallMPI(MPI_Comm_size(comm, &size));
875:   PetscCheck(ptap->P_oth || size <= 1, PetscObjectComm((PetscObject)C), PETSC_ERR_ARG_WRONGSTATE, "AP cannot be reused. Do not call MatProductClear()");

877:   /* flag CPU mask for C */
878: #if PetscDefined(HAVE_DEVICE)
879:   if (C->offloadmask != PETSC_OFFLOAD_UNALLOCATED) C->offloadmask = PETSC_OFFLOAD_CPU;
880:   if (c->A->offloadmask != PETSC_OFFLOAD_UNALLOCATED) c->A->offloadmask = PETSC_OFFLOAD_CPU;
881:   if (c->B->offloadmask != PETSC_OFFLOAD_UNALLOCATED) c->B->offloadmask = PETSC_OFFLOAD_CPU;
882: #endif
883:   apa_sparse = ptap->apa;

885:   /* 1) get P_oth = ptap->P_oth  and P_loc = ptap->P_loc */
886:   /* update numerical values of P_oth and P_loc */
887:   PetscCall(MatGetBrowsOfAoCols_MPIAIJ(A, P, MAT_REUSE_MATRIX, &ptap->startsj_s, &ptap->startsj_r, &ptap->bufa, &ptap->P_oth));
888:   PetscCall(MatMPIAIJGetLocalMat(P, MAT_REUSE_MATRIX, &ptap->P_loc));

890:   /* 2) compute numeric C_loc = A_loc*P = Ad*P_loc + Ao*P_oth */
891:   /* get data from symbolic products */
892:   p_loc  = (Mat_SeqAIJ *)ptap->P_loc->data;
893:   pi_loc = p_loc->i;
894:   pj_loc = p_loc->j;
895:   pa_loc = p_loc->a;
896:   if (size > 1) {
897:     p_oth  = (Mat_SeqAIJ *)ptap->P_oth->data;
898:     pi_oth = p_oth->i;
899:     pj_oth = p_oth->j;
900:     pa_oth = p_oth->a;
901:   } else {
902:     p_oth  = NULL;
903:     pi_oth = NULL;
904:     pj_oth = NULL;
905:     pa_oth = NULL;
906:   }

908:   /* trigger copy to CPU */
909:   PetscCall(MatSeqAIJGetArrayRead(a->A, &dummy));
910:   PetscCall(MatSeqAIJRestoreArrayRead(a->A, &dummy));
911:   PetscCall(MatSeqAIJGetArrayRead(a->B, &dummy));
912:   PetscCall(MatSeqAIJRestoreArrayRead(a->B, &dummy));
913:   api = ptap->api;
914:   apj = ptap->apj;
915:   for (i = 0; i < cm; i++) {
916:     apJ = apj + api[i];

918:     /* diagonal portion of A */
919:     anz = adi[i + 1] - adi[i];
920:     adj = ad->j + adi[i];
921:     ada = ad->a + adi[i];
922:     for (j = 0; j < anz; j++) {
923:       row = adj[j];
924:       pnz = pi_loc[row + 1] - pi_loc[row];
925:       pj  = pj_loc + pi_loc[row];
926:       pa  = pa_loc + pi_loc[row];
927:       /* perform sparse axpy */
928:       valtmp = ada[j];
929:       nextp  = 0;
930:       for (k = 0; nextp < pnz; k++) {
931:         if (apJ[k] == pj[nextp]) { /* column of AP == column of P */
932:           apa_sparse[k] += valtmp * pa[nextp++];
933:         }
934:       }
935:       PetscCall(PetscLogFlops(2.0 * pnz));
936:     }

938:     /* off-diagonal portion of A */
939:     anz = aoi[i + 1] - aoi[i];
940:     aoj = PetscSafePointerPlusOffset(ao->j, aoi[i]);
941:     aoa = PetscSafePointerPlusOffset(ao->a, aoi[i]);
942:     for (j = 0; j < anz; j++) {
943:       row = aoj[j];
944:       pnz = pi_oth[row + 1] - pi_oth[row];
945:       pj  = pj_oth + pi_oth[row];
946:       pa  = pa_oth + pi_oth[row];
947:       /* perform sparse axpy */
948:       valtmp = aoa[j];
949:       nextp  = 0;
950:       for (k = 0; nextp < pnz; k++) {
951:         if (apJ[k] == pj[nextp]) { /* column of AP == column of P */
952:           apa_sparse[k] += valtmp * pa[nextp++];
953:         }
954:       }
955:       PetscCall(PetscLogFlops(2.0 * pnz));
956:     }

958:     /* set values in C */
959:     cdnz = cd->i[i + 1] - cd->i[i];
960:     conz = co->i[i + 1] - co->i[i];

962:     /* 1st off-diagonal part of C */
963:     ca = PetscSafePointerPlusOffset(coa, co->i[i]);
964:     k  = 0;
965:     for (k0 = 0; k0 < conz; k0++) {
966:       if (apJ[k] >= cstart) break;
967:       ca[k0]        = apa_sparse[k];
968:       apa_sparse[k] = 0.0;
969:       k++;
970:     }

972:     /* diagonal part of C */
973:     ca = cda + cd->i[i];
974:     for (k1 = 0; k1 < cdnz; k1++) {
975:       ca[k1]        = apa_sparse[k];
976:       apa_sparse[k] = 0.0;
977:       k++;
978:     }

980:     /* 2nd off-diagonal part of C */
981:     ca = PetscSafePointerPlusOffset(coa, co->i[i]);
982:     for (; k0 < conz; k0++) {
983:       ca[k0]        = apa_sparse[k];
984:       apa_sparse[k] = 0.0;
985:       k++;
986:     }
987:   }
988:   PetscCall(MatAssemblyBegin(C, MAT_FINAL_ASSEMBLY));
989:   PetscCall(MatAssemblyEnd(C, MAT_FINAL_ASSEMBLY));
990:   PetscFunctionReturn(PETSC_SUCCESS);
991: }

993: /* same as MatMatMultSymbolic_MPIAIJ_MPIAIJ_nonscalable(), except using LLCondensed to avoid O(BN) memory requirement */
994: PetscErrorCode MatMatMultSymbolic_MPIAIJ_MPIAIJ(Mat A, Mat P, PetscReal fill, Mat C)
995: {
996:   MPI_Comm             comm;
997:   PetscMPIInt          size;
998:   MatProductCtx_APMPI *ptap;
999:   PetscFreeSpaceList   free_space = NULL, current_space = NULL;
1000:   Mat_MPIAIJ          *a  = (Mat_MPIAIJ *)A->data;
1001:   Mat_SeqAIJ          *ad = (Mat_SeqAIJ *)a->A->data, *ao = (Mat_SeqAIJ *)a->B->data, *p_loc, *p_oth;
1002:   PetscInt            *pi_loc, *pj_loc, *pi_oth, *pj_oth, *dnz, *onz;
1003:   PetscInt            *adi = ad->i, *adj = ad->j, *aoi = ao->i, *aoj = ao->j, rstart = A->rmap->rstart;
1004:   PetscInt             i, pnz, row, *api, *apj, *Jptr, apnz, nspacedouble = 0, j, nzi, *lnk, apnz_max = 1;
1005:   PetscInt             am = A->rmap->n, pn = P->cmap->n, pm = P->rmap->n, lsize = pn + 20;
1006:   PetscReal            afill;
1007:   MatType              mtype;

1009:   PetscFunctionBegin;
1010:   MatCheckProduct(C, 4);
1011:   PetscCheck(!C->product->data, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Extra product struct not empty");
1012:   PetscCall(PetscObjectGetComm((PetscObject)A, &comm));
1013:   PetscCallMPI(MPI_Comm_size(comm, &size));

1015:   /* create struct MatProductCtx_APMPI and attached it to C later */
1016:   PetscCall(PetscNew(&ptap));

1018:   /* get P_oth by taking rows of P (= non-zero cols of local A) from other processors */
1019:   PetscCall(MatGetBrowsOfAoCols_MPIAIJ_Private(A, P, MAT_INITIAL_MATRIX, C->structure_only, &ptap->startsj_s, &ptap->startsj_r, &ptap->bufa, &ptap->P_oth));

1021:   /* get P_loc by taking all local rows of P */
1022:   PetscCall(MatMPIAIJGetLocalMat_Private(P, MAT_INITIAL_MATRIX, C->structure_only, &ptap->P_loc));

1024:   p_loc  = (Mat_SeqAIJ *)ptap->P_loc->data;
1025:   pi_loc = p_loc->i;
1026:   pj_loc = p_loc->j;
1027:   if (size > 1) {
1028:     p_oth  = (Mat_SeqAIJ *)ptap->P_oth->data;
1029:     pi_oth = p_oth->i;
1030:     pj_oth = p_oth->j;
1031:   } else {
1032:     p_oth  = NULL;
1033:     pi_oth = NULL;
1034:     pj_oth = NULL;
1035:   }

1037:   /* first, compute symbolic AP = A_loc*P = A_diag*P_loc + A_off*P_oth */
1038:   PetscCall(PetscMalloc1(am + 1, &api));
1039:   ptap->api = api;
1040:   api[0]    = 0;

1042:   PetscCall(PetscLLCondensedCreate_Scalable(lsize, &lnk));

1044:   /* Initial FreeSpace size is fill*(nnz(A)+nnz(P)) */
1045:   PetscCall(PetscFreeSpaceGet(PetscRealIntMultTruncate(fill, PetscIntSumTruncate(adi[am], PetscIntSumTruncate(aoi[am], pi_loc[pm]))), &free_space));
1046:   current_space = free_space;
1047:   MatPreallocateBegin(comm, am, pn, dnz, onz);
1048:   for (i = 0; i < am; i++) {
1049:     /* diagonal portion of A */
1050:     nzi = adi[i + 1] - adi[i];
1051:     for (j = 0; j < nzi; j++) {
1052:       row  = *adj++;
1053:       pnz  = pi_loc[row + 1] - pi_loc[row];
1054:       Jptr = pj_loc + pi_loc[row];
1055:       /* Expand list if it is not long enough */
1056:       if (pnz + apnz_max > lsize) {
1057:         lsize = pnz + apnz_max;
1058:         PetscCall(PetscLLCondensedExpand_Scalable(lsize, &lnk));
1059:       }
1060:       /* add non-zero cols of P into the sorted linked list lnk */
1061:       PetscCall(PetscLLCondensedAddSorted_Scalable(pnz, Jptr, lnk));
1062:       apnz       = *lnk; /* The first element in the list is the number of items in the list */
1063:       api[i + 1] = api[i] + apnz;
1064:       if (apnz > apnz_max) apnz_max = apnz + 1; /* '1' for diagonal entry */
1065:     }
1066:     /* off-diagonal portion of A */
1067:     nzi = aoi[i + 1] - aoi[i];
1068:     for (j = 0; j < nzi; j++) {
1069:       row  = *aoj++;
1070:       pnz  = pi_oth[row + 1] - pi_oth[row];
1071:       Jptr = pj_oth + pi_oth[row];
1072:       /* Expand list if it is not long enough */
1073:       if (pnz + apnz_max > lsize) {
1074:         lsize = pnz + apnz_max;
1075:         PetscCall(PetscLLCondensedExpand_Scalable(lsize, &lnk));
1076:       }
1077:       /* add non-zero cols of P into the sorted linked list lnk */
1078:       PetscCall(PetscLLCondensedAddSorted_Scalable(pnz, Jptr, lnk));
1079:       apnz       = *lnk; /* The first element in the list is the number of items in the list */
1080:       api[i + 1] = api[i] + apnz;
1081:       if (apnz > apnz_max) apnz_max = apnz + 1; /* '1' for diagonal entry */
1082:     }

1084:     /* add missing diagonal entry */
1085:     if (C->force_diagonals) {
1086:       j = i + rstart; /* column index */
1087:       PetscCall(PetscLLCondensedAddSorted_Scalable(1, &j, lnk));
1088:     }

1090:     apnz       = *lnk;
1091:     api[i + 1] = api[i] + apnz;
1092:     if (apnz > apnz_max) apnz_max = apnz;

1094:     /* if free space is not available, double the total space in the list */
1095:     if (current_space->local_remaining < apnz) {
1096:       PetscCall(PetscFreeSpaceGet(PetscIntSumTruncate(apnz, current_space->total_array_size), &current_space));
1097:       nspacedouble++;
1098:     }

1100:     /* Copy data into free space, then initialize lnk */
1101:     PetscCall(PetscLLCondensedClean_Scalable(apnz, current_space->array, lnk));
1102:     PetscCall(MatPreallocateSet(i + rstart, apnz, current_space->array, dnz, onz));

1104:     current_space->array += apnz;
1105:     current_space->local_used += apnz;
1106:     current_space->local_remaining -= apnz;
1107:   }

1109:   /* Allocate space for apj, initialize apj, and */
1110:   /* destroy list of free space and other temporary array(s) */
1111:   PetscCall(PetscMalloc1(api[am], &ptap->apj));
1112:   apj = ptap->apj;
1113:   PetscCall(PetscFreeSpaceContiguous(&free_space, ptap->apj));
1114:   PetscCall(PetscLLCondensedDestroy_Scalable(lnk));

1116:   /* create and assemble symbolic parallel matrix C */
1117:   PetscCall(MatSetSizes(C, am, pn, PETSC_DETERMINE, PETSC_DETERMINE));
1118:   PetscCall(MatSetBlockSizesFromMats(C, A, P));
1119:   PetscCall(MatGetType(A, &mtype));
1120:   PetscCall(MatSetType(C, C->structure_only ? MATMPIAIJ : mtype));
1121:   PetscCall(MatMPIAIJSetPreallocation(C, 0, dnz, 0, onz));
1122:   MatPreallocateEnd(dnz, onz);

1124:   /* malloc apa for assembly C */
1125:   if (!C->structure_only) PetscCall(PetscCalloc1(apnz_max, &ptap->apa));

1127:   PetscCall(MatSetValues_MPIAIJ_CopyFromCSRFormat_Symbolic(C, apj, api));
1128:   PetscCall(MatSetOption(C, MAT_NO_OFF_PROC_ENTRIES, PETSC_TRUE));
1129:   PetscCall(MatAssemblyBegin(C, MAT_FINAL_ASSEMBLY));
1130:   PetscCall(MatAssemblyEnd(C, MAT_FINAL_ASSEMBLY));
1131:   PetscCall(MatSetOption(C, MAT_NEW_NONZERO_LOCATION_ERR, PETSC_TRUE));

1133:   C->ops->matmultnumeric = MatMatMultNumeric_MPIAIJ_MPIAIJ;
1134:   C->ops->productnumeric = MatProductNumeric_AB;

1136:   /* attach the supporting struct to C for reuse */
1137:   C->product->data    = ptap;
1138:   C->product->destroy = MatProductCtxDestroy_MPIAIJ_MatMatMult;

1140:   /* set MatInfo */
1141:   afill = (PetscReal)api[am] / (adi[am] + aoi[am] + pi_loc[pm] + 1) + 1.e-5;
1142:   if (afill < 1.0) afill = 1.0;
1143:   C->info.mallocs           = nspacedouble;
1144:   C->info.fill_ratio_given  = fill;
1145:   C->info.fill_ratio_needed = afill;

1147:   if (PetscDefined(USE_INFO)) {
1148:     if (api[am]) {
1149:       PetscCall(PetscInfo(C, "Reallocs %" PetscInt_FMT "; Fill ratio: given %g needed %g.\n", nspacedouble, (double)fill, (double)afill));
1150:       PetscCall(PetscInfo(C, "Use MatMatMult(A,B,MatReuse,%g,&C) for best performance.;\n", (double)afill));
1151:     } else PetscCall(PetscInfo(C, "Empty matrix product\n"));
1152:   }
1153:   PetscFunctionReturn(PETSC_SUCCESS);
1154: }

1156: /* This function is needed for the seqMPI matrix-matrix multiplication.  */
1157: /* Three input arrays are merged to one output array. The size of the    */
1158: /* output array is also output. Duplicate entries only show up once.     */
1159: static void Merge3SortedArrays(PetscInt size1, PetscInt *in1, PetscInt size2, PetscInt *in2, PetscInt size3, PetscInt *in3, PetscInt *size4, PetscInt *out)
1160: {
1161:   int i = 0, j = 0, k = 0, l = 0;

1163:   /* Traverse all three arrays */
1164:   while (i < size1 && j < size2 && k < size3) {
1165:     if (in1[i] < in2[j] && in1[i] < in3[k]) {
1166:       out[l++] = in1[i++];
1167:     } else if (in2[j] < in1[i] && in2[j] < in3[k]) {
1168:       out[l++] = in2[j++];
1169:     } else if (in3[k] < in1[i] && in3[k] < in2[j]) {
1170:       out[l++] = in3[k++];
1171:     } else if (in1[i] == in2[j] && in1[i] < in3[k]) {
1172:       out[l++] = in1[i];
1173:       i++, j++;
1174:     } else if (in1[i] == in3[k] && in1[i] < in2[j]) {
1175:       out[l++] = in1[i];
1176:       i++, k++;
1177:     } else if (in3[k] == in2[j] && in2[j] < in1[i]) {
1178:       out[l++] = in2[j];
1179:       k++, j++;
1180:     } else if (in1[i] == in2[j] && in1[i] == in3[k]) {
1181:       out[l++] = in1[i];
1182:       i++, j++, k++;
1183:     }
1184:   }

1186:   /* Traverse two remaining arrays */
1187:   while (i < size1 && j < size2) {
1188:     if (in1[i] < in2[j]) {
1189:       out[l++] = in1[i++];
1190:     } else if (in1[i] > in2[j]) {
1191:       out[l++] = in2[j++];
1192:     } else {
1193:       out[l++] = in1[i];
1194:       i++, j++;
1195:     }
1196:   }

1198:   while (i < size1 && k < size3) {
1199:     if (in1[i] < in3[k]) {
1200:       out[l++] = in1[i++];
1201:     } else if (in1[i] > in3[k]) {
1202:       out[l++] = in3[k++];
1203:     } else {
1204:       out[l++] = in1[i];
1205:       i++, k++;
1206:     }
1207:   }

1209:   while (k < size3 && j < size2) {
1210:     if (in3[k] < in2[j]) {
1211:       out[l++] = in3[k++];
1212:     } else if (in3[k] > in2[j]) {
1213:       out[l++] = in2[j++];
1214:     } else {
1215:       out[l++] = in3[k];
1216:       k++, j++;
1217:     }
1218:   }

1220:   /* Traverse one remaining array */
1221:   while (i < size1) out[l++] = in1[i++];
1222:   while (j < size2) out[l++] = in2[j++];
1223:   while (k < size3) out[l++] = in3[k++];

1225:   *size4 = l;
1226: }

1228: /* This matrix-matrix multiplication algorithm divides the multiplication into three multiplications and  */
1229: /* adds up the products. Two of these three multiplications are performed with existing (sequential)      */
1230: /* matrix-matrix multiplications.  */
1231: PetscErrorCode MatMatMultSymbolic_MPIAIJ_MPIAIJ_seqMPI(Mat A, Mat P, PetscReal fill, Mat C)
1232: {
1233:   MPI_Comm             comm;
1234:   PetscMPIInt          size;
1235:   MatProductCtx_APMPI *ptap;
1236:   PetscFreeSpaceList   free_space_diag = NULL, current_space = NULL;
1237:   Mat_MPIAIJ          *a  = (Mat_MPIAIJ *)A->data;
1238:   Mat_SeqAIJ          *ad = (Mat_SeqAIJ *)a->A->data, *ao = (Mat_SeqAIJ *)a->B->data, *p_loc;
1239:   Mat_MPIAIJ          *p = (Mat_MPIAIJ *)P->data;
1240:   Mat_SeqAIJ          *adpd_seq, *p_off, *aopoth_seq;
1241:   PetscInt             adponz, adpdnz;
1242:   PetscInt            *pi_loc, *dnz, *onz;
1243:   PetscInt            *adi = ad->i, *adj = ad->j, *aoi = ao->i, rstart = A->rmap->rstart;
1244:   PetscInt            *lnk, i, i1 = 0, pnz, row, *adpoi, *adpoj, *api, *adpoJ, *aopJ, *apJ, *Jptr, aopnz, nspacedouble = 0, j, nzi, *apj, apnz, *adpdi, *adpdj, *adpdJ, *poff_i, *poff_j, *j_temp, *aopothi, *aopothj;
1245:   PetscInt             am = A->rmap->n, pN = P->cmap->N, pn = P->cmap->n, pm = P->rmap->n, p_colstart, p_colend;
1246:   PetscBT              lnkbt;
1247:   PetscReal            afill;
1248:   PetscMPIInt          rank;
1249:   Mat                  adpd, aopoth;
1250:   MatType              mtype;
1251:   const char          *prefix;

1253:   PetscFunctionBegin;
1254:   MatCheckProduct(C, 4);
1255:   PetscCheck(!C->product->data, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Extra product struct not empty");
1256:   PetscCall(PetscObjectGetComm((PetscObject)A, &comm));
1257:   PetscCallMPI(MPI_Comm_size(comm, &size));
1258:   PetscCallMPI(MPI_Comm_rank(comm, &rank));
1259:   PetscCall(MatGetOwnershipRangeColumn(P, &p_colstart, &p_colend));

1261:   /* create struct MatProductCtx_APMPI and attached it to C later */
1262:   PetscCall(PetscNew(&ptap));

1264:   /* get P_oth by taking rows of P (= non-zero cols of local A) from other processors */
1265:   PetscCall(MatGetBrowsOfAoCols_MPIAIJ(A, P, MAT_INITIAL_MATRIX, &ptap->startsj_s, &ptap->startsj_r, &ptap->bufa, &ptap->P_oth));

1267:   /* get P_loc by taking all local rows of P */
1268:   PetscCall(MatMPIAIJGetLocalMat(P, MAT_INITIAL_MATRIX, &ptap->P_loc));

1270:   p_loc  = (Mat_SeqAIJ *)ptap->P_loc->data;
1271:   pi_loc = p_loc->i;

1273:   /* Allocate memory for the i arrays of the matrices A*P, A_diag*P_off and A_offd * P */
1274:   PetscCall(PetscMalloc1(am + 1, &api));
1275:   PetscCall(PetscMalloc1(am + 1, &adpoi));

1277:   adpoi[0]  = 0;
1278:   ptap->api = api;
1279:   api[0]    = 0;

1281:   /* create and initialize a linked list, will be used for both A_diag * P_loc_off and A_offd * P_oth */
1282:   PetscCall(PetscLLCondensedCreate(pN, pN, &lnk, &lnkbt));
1283:   MatPreallocateBegin(comm, am, pn, dnz, onz);

1285:   /* Symbolic calc of A_loc_diag * P_loc_diag */
1286:   PetscCall(MatGetOptionsPrefix(A, &prefix));
1287:   PetscCall(MatProductCreate(a->A, p->A, NULL, &adpd));
1288:   PetscCall(MatGetOptionsPrefix(A, &prefix));
1289:   PetscCall(MatSetOptionsPrefix(adpd, prefix));
1290:   PetscCall(MatAppendOptionsPrefix(adpd, "inner_diag_"));

1292:   PetscCall(MatProductSetType(adpd, MATPRODUCT_AB));
1293:   PetscCall(MatProductSetAlgorithm(adpd, "sorted"));
1294:   PetscCall(MatProductSetFill(adpd, fill));
1295:   PetscCall(MatProductSetFromOptions(adpd));

1297:   adpd->force_diagonals = C->force_diagonals;
1298:   PetscCall(MatProductSymbolic(adpd));

1300:   adpd_seq = (Mat_SeqAIJ *)adpd->data;
1301:   adpdi    = adpd_seq->i;
1302:   adpdj    = adpd_seq->j;
1303:   p_off    = (Mat_SeqAIJ *)p->B->data;
1304:   poff_i   = p_off->i;
1305:   poff_j   = p_off->j;

1307:   /* j_temp stores indices of a result row before they are added to the linked list */
1308:   PetscCall(PetscMalloc1(pN, &j_temp));

1310:   /* Symbolic calc of the A_diag * p_loc_off */
1311:   /* Initial FreeSpace size is fill*(nnz(A)+nnz(P)) */
1312:   PetscCall(PetscFreeSpaceGet(PetscRealIntMultTruncate(fill, PetscIntSumTruncate(adi[am], PetscIntSumTruncate(aoi[am], pi_loc[pm]))), &free_space_diag));
1313:   current_space = free_space_diag;

1315:   for (i = 0; i < am; i++) {
1316:     /* A_diag * P_loc_off */
1317:     nzi = adi[i + 1] - adi[i];
1318:     for (j = 0; j < nzi; j++) {
1319:       row  = *adj++;
1320:       pnz  = poff_i[row + 1] - poff_i[row];
1321:       Jptr = poff_j + poff_i[row];
1322:       for (i1 = 0; i1 < pnz; i1++) j_temp[i1] = p->garray[Jptr[i1]];
1323:       /* add non-zero cols of P into the sorted linked list lnk */
1324:       PetscCall(PetscLLCondensedAddSorted(pnz, j_temp, lnk, lnkbt));
1325:     }

1327:     adponz       = lnk[0];
1328:     adpoi[i + 1] = adpoi[i] + adponz;

1330:     /* if free space is not available, double the total space in the list */
1331:     if (current_space->local_remaining < adponz) {
1332:       PetscCall(PetscFreeSpaceGet(PetscIntSumTruncate(adponz, current_space->total_array_size), &current_space));
1333:       nspacedouble++;
1334:     }

1336:     /* Copy data into free space, then initialize lnk */
1337:     PetscCall(PetscLLCondensedClean(pN, adponz, current_space->array, lnk, lnkbt));

1339:     current_space->array += adponz;
1340:     current_space->local_used += adponz;
1341:     current_space->local_remaining -= adponz;
1342:   }

1344:   /* Symbolic calc of A_off * P_oth */
1345:   PetscCall(MatSetOptionsPrefix(a->B, prefix));
1346:   PetscCall(MatAppendOptionsPrefix(a->B, "inner_offdiag_"));
1347:   PetscCall(MatCreate(PETSC_COMM_SELF, &aopoth));
1348:   PetscCall(MatMatMultSymbolic_SeqAIJ_SeqAIJ(a->B, ptap->P_oth, fill, aopoth));
1349:   aopoth_seq = (Mat_SeqAIJ *)aopoth->data;
1350:   aopothi    = aopoth_seq->i;
1351:   aopothj    = aopoth_seq->j;

1353:   /* Allocate space for apj, adpj, aopj, ... */
1354:   /* destroy lists of free space and other temporary array(s) */

1356:   PetscCall(PetscMalloc1(aopothi[am] + adpoi[am] + adpdi[am], &ptap->apj));
1357:   PetscCall(PetscMalloc1(adpoi[am], &adpoj));

1359:   /* Copy from linked list to j-array */
1360:   PetscCall(PetscFreeSpaceContiguous(&free_space_diag, adpoj));
1361:   PetscCall(PetscLLDestroy(lnk, lnkbt));

1363:   adpoJ = adpoj;
1364:   adpdJ = adpdj;
1365:   aopJ  = aopothj;
1366:   apj   = ptap->apj;
1367:   apJ   = apj; /* still empty */

1369:   /* Merge j-arrays of A_off * P, A_diag * P_loc_off, and */
1370:   /* A_diag * P_loc_diag to get A*P */
1371:   for (i = 0; i < am; i++) {
1372:     aopnz  = aopothi[i + 1] - aopothi[i];
1373:     adponz = adpoi[i + 1] - adpoi[i];
1374:     adpdnz = adpdi[i + 1] - adpdi[i];

1376:     /* Correct indices from A_diag*P_diag */
1377:     for (i1 = 0; i1 < adpdnz; i1++) adpdJ[i1] += p_colstart;
1378:     /* Merge j-arrays of A_diag * P_loc_off and A_diag * P_loc_diag and A_off * P_oth */
1379:     Merge3SortedArrays(adponz, adpoJ, adpdnz, adpdJ, aopnz, aopJ, &apnz, apJ);
1380:     PetscCall(MatPreallocateSet(i + rstart, apnz, apJ, dnz, onz));

1382:     aopJ += aopnz;
1383:     adpoJ += adponz;
1384:     adpdJ += adpdnz;
1385:     apJ += apnz;
1386:     api[i + 1] = api[i] + apnz;
1387:   }

1389:   /* malloc apa to store dense row A[i,:]*P */
1390:   PetscCall(PetscCalloc1(pN, &ptap->apa));

1392:   /* create and assemble symbolic parallel matrix C */
1393:   PetscCall(MatSetSizes(C, am, pn, PETSC_DETERMINE, PETSC_DETERMINE));
1394:   PetscCall(MatSetBlockSizesFromMats(C, A, P));
1395:   PetscCall(MatGetType(A, &mtype));
1396:   PetscCall(MatSetType(C, mtype));
1397:   PetscCall(MatMPIAIJSetPreallocation(C, 0, dnz, 0, onz));
1398:   MatPreallocateEnd(dnz, onz);

1400:   PetscCall(MatSetValues_MPIAIJ_CopyFromCSRFormat_Symbolic(C, apj, api));
1401:   PetscCall(MatSetOption(C, MAT_NO_OFF_PROC_ENTRIES, PETSC_TRUE));
1402:   PetscCall(MatAssemblyBegin(C, MAT_FINAL_ASSEMBLY));
1403:   PetscCall(MatAssemblyEnd(C, MAT_FINAL_ASSEMBLY));
1404:   PetscCall(MatSetOption(C, MAT_NEW_NONZERO_LOCATION_ERR, PETSC_TRUE));

1406:   C->ops->matmultnumeric = MatMatMultNumeric_MPIAIJ_MPIAIJ_nonscalable;
1407:   C->ops->productnumeric = MatProductNumeric_AB;

1409:   /* attach the supporting struct to C for reuse */
1410:   C->product->data    = ptap;
1411:   C->product->destroy = MatProductCtxDestroy_MPIAIJ_MatMatMult;

1413:   /* set MatInfo */
1414:   afill = (PetscReal)api[am] / (adi[am] + aoi[am] + pi_loc[pm] + 1) + 1.e-5;
1415:   if (afill < 1.0) afill = 1.0;
1416:   C->info.mallocs           = nspacedouble;
1417:   C->info.fill_ratio_given  = fill;
1418:   C->info.fill_ratio_needed = afill;

1420:   if (PetscDefined(USE_INFO)) {
1421:     if (api[am]) {
1422:       PetscCall(PetscInfo(C, "Reallocs %" PetscInt_FMT "; Fill ratio: given %g needed %g.\n", nspacedouble, (double)fill, (double)afill));
1423:       PetscCall(PetscInfo(C, "Use MatMatMult(A,B,MatReuse,%g,&C) for best performance.;\n", (double)afill));
1424:     } else PetscCall(PetscInfo(C, "Empty matrix product\n"));
1425:   }

1427:   PetscCall(MatDestroy(&aopoth));
1428:   PetscCall(MatDestroy(&adpd));
1429:   PetscCall(PetscFree(j_temp));
1430:   PetscCall(PetscFree(adpoj));
1431:   PetscCall(PetscFree(adpoi));
1432:   PetscFunctionReturn(PETSC_SUCCESS);
1433: }

1435: /* This routine only works when scall=MAT_REUSE_MATRIX! */
1436: PetscErrorCode MatTransposeMatMultNumeric_MPIAIJ_MPIAIJ_matmatmult(Mat P, Mat A, Mat C)
1437: {
1438:   MatProductCtx_APMPI *ptap;
1439:   Mat                  Pt;

1441:   PetscFunctionBegin;
1442:   MatCheckProduct(C, 3);
1443:   ptap = (MatProductCtx_APMPI *)C->product->data;
1444:   PetscCheck(ptap, PetscObjectComm((PetscObject)C), PETSC_ERR_ARG_WRONGSTATE, "PtAP cannot be computed. Missing data");
1445:   PetscCheck(ptap->Pt, PetscObjectComm((PetscObject)C), PETSC_ERR_ARG_WRONGSTATE, "PtA cannot be reused. Do not call MatProductClear()");

1447:   Pt = ptap->Pt;
1448:   PetscCall(MatTransposeSetPrecursor(P, Pt));
1449:   PetscCall(MatTranspose(P, MAT_REUSE_MATRIX, &Pt));
1450:   PetscCall(MatMatMultNumeric_MPIAIJ_MPIAIJ(Pt, A, C));
1451:   PetscFunctionReturn(PETSC_SUCCESS);
1452: }

1454: /* This routine is modified from MatPtAPSymbolic_MPIAIJ_MPIAIJ() */
1455: PetscErrorCode MatTransposeMatMultSymbolic_MPIAIJ_MPIAIJ_nonscalable(Mat P, Mat A, PetscReal fill, Mat C)
1456: {
1457:   MatProductCtx_APMPI     *ptap;
1458:   Mat_MPIAIJ              *p = (Mat_MPIAIJ *)P->data;
1459:   MPI_Comm                 comm;
1460:   PetscMPIInt              size, rank;
1461:   PetscFreeSpaceList       free_space = NULL, current_space = NULL;
1462:   PetscInt                 pn = P->cmap->n, aN = A->cmap->N, an = A->cmap->n;
1463:   PetscInt                *lnk, i, k, rstart;
1464:   PetscBT                  lnkbt;
1465:   PetscMPIInt              tagi, tagj, *len_si, *len_s, *len_ri, nrecv, proc, nsend;
1466:   PETSC_UNUSED PetscMPIInt icompleted = 0;
1467:   PetscInt               **buf_rj, **buf_ri, **buf_ri_k, row, ncols, *cols;
1468:   PetscInt                 len, *dnz, *onz, *owners, nzi;
1469:   PetscInt                 nrows, *buf_s, *buf_si, *buf_si_i, **nextrow, **nextci;
1470:   MPI_Request             *swaits, *rwaits;
1471:   MPI_Status              *sstatus, rstatus;
1472:   PetscLayout              rowmap;
1473:   PetscInt                *owners_co, *coi, *coj; /* i and j array of (p->B)^T*A*P - used in the communication */
1474:   PetscMPIInt             *len_r, *id_r;          /* array of length of comm->size, store send/recv matrix values */
1475:   PetscInt                *Jptr, *prmap = p->garray, con, j, Crmax;
1476:   Mat_SeqAIJ              *a_loc, *c_loc, *c_oth;
1477:   PetscHMapI               ta;
1478:   MatType                  mtype;
1479:   const char              *prefix;

1481:   PetscFunctionBegin;
1482:   PetscCall(PetscObjectGetComm((PetscObject)A, &comm));
1483:   PetscCallMPI(MPI_Comm_size(comm, &size));
1484:   PetscCallMPI(MPI_Comm_rank(comm, &rank));

1486:   /* create symbolic parallel matrix C */
1487:   PetscCall(MatGetType(A, &mtype));
1488:   PetscCall(MatSetType(C, mtype));

1490:   C->ops->transposematmultnumeric = MatTransposeMatMultNumeric_MPIAIJ_MPIAIJ_nonscalable;

1492:   /* create struct MatProductCtx_APMPI and attached it to C later */
1493:   PetscCall(PetscNew(&ptap));

1495:   /* (0) compute Rd = Pd^T, Ro = Po^T  */
1496:   PetscCall(MatTranspose(p->A, MAT_INITIAL_MATRIX, &ptap->Rd));
1497:   PetscCall(MatTranspose(p->B, MAT_INITIAL_MATRIX, &ptap->Ro));

1499:   /* (1) compute symbolic A_loc */
1500:   PetscCall(MatMPIAIJGetLocalMat(A, MAT_INITIAL_MATRIX, &ptap->A_loc));

1502:   /* (2-1) compute symbolic C_oth = Ro*A_loc  */
1503:   PetscCall(MatGetOptionsPrefix(A, &prefix));
1504:   PetscCall(MatSetOptionsPrefix(ptap->Ro, prefix));
1505:   PetscCall(MatAppendOptionsPrefix(ptap->Ro, "inner_offdiag_"));
1506:   PetscCall(MatCreate(PETSC_COMM_SELF, &ptap->C_oth));
1507:   PetscCall(MatMatMultSymbolic_SeqAIJ_SeqAIJ(ptap->Ro, ptap->A_loc, fill, ptap->C_oth));

1509:   /* (3) send coj of C_oth to other processors  */
1510:   /* determine row ownership */
1511:   PetscCall(PetscLayoutCreate(comm, &rowmap));
1512:   rowmap->n  = pn;
1513:   rowmap->bs = 1;
1514:   PetscCall(PetscLayoutSetUp(rowmap));
1515:   owners = rowmap->range;

1517:   /* determine the number of messages to send, their lengths */
1518:   PetscCall(PetscMalloc4(size, &len_s, size, &len_si, size, &sstatus, size + 1, &owners_co));
1519:   PetscCall(PetscArrayzero(len_s, size));
1520:   PetscCall(PetscArrayzero(len_si, size));

1522:   c_oth = (Mat_SeqAIJ *)ptap->C_oth->data;
1523:   coi   = c_oth->i;
1524:   coj   = c_oth->j;
1525:   con   = ptap->C_oth->rmap->n;
1526:   proc  = 0;
1527:   for (i = 0; i < con; i++) {
1528:     while (prmap[i] >= owners[proc + 1]) proc++;
1529:     len_si[proc]++;                     /* num of rows in Co(=Pt*A) to be sent to [proc] */
1530:     len_s[proc] += coi[i + 1] - coi[i]; /* num of nonzeros in Co to be sent to [proc] */
1531:   }

1533:   len          = 0; /* max length of buf_si[], see (4) */
1534:   owners_co[0] = 0;
1535:   nsend        = 0;
1536:   for (proc = 0; proc < size; proc++) {
1537:     owners_co[proc + 1] = owners_co[proc] + len_si[proc];
1538:     if (len_s[proc]) {
1539:       nsend++;
1540:       len_si[proc] = 2 * (len_si[proc] + 1); /* length of buf_si to be sent to [proc] */
1541:       len += len_si[proc];
1542:     }
1543:   }

1545:   /* determine the number and length of messages to receive for coi and coj  */
1546:   PetscCall(PetscGatherNumberOfMessages(comm, NULL, len_s, &nrecv));
1547:   PetscCall(PetscGatherMessageLengths2(comm, nsend, nrecv, len_s, len_si, &id_r, &len_r, &len_ri));

1549:   /* post the Irecv and Isend of coj */
1550:   PetscCall(PetscCommGetNewTag(comm, &tagj));
1551:   PetscCall(PetscPostIrecvInt(comm, tagj, nrecv, id_r, len_r, &buf_rj, &rwaits));
1552:   PetscCall(PetscMalloc1(nsend, &swaits));
1553:   for (proc = 0, k = 0; proc < size; proc++) {
1554:     if (!len_s[proc]) continue;
1555:     i = owners_co[proc];
1556:     PetscCallMPI(MPIU_Isend(coj + coi[i], len_s[proc], MPIU_INT, proc, tagj, comm, swaits + k));
1557:     k++;
1558:   }

1560:   /* (2-2) compute symbolic C_loc = Rd*A_loc */
1561:   PetscCall(MatSetOptionsPrefix(ptap->Rd, prefix));
1562:   PetscCall(MatAppendOptionsPrefix(ptap->Rd, "inner_diag_"));
1563:   PetscCall(MatCreate(PETSC_COMM_SELF, &ptap->C_loc));
1564:   PetscCall(MatMatMultSymbolic_SeqAIJ_SeqAIJ(ptap->Rd, ptap->A_loc, fill, ptap->C_loc));
1565:   c_loc = (Mat_SeqAIJ *)ptap->C_loc->data;

1567:   /* receives coj are complete */
1568:   for (i = 0; i < nrecv; i++) PetscCallMPI(MPI_Waitany(nrecv, rwaits, &icompleted, &rstatus));
1569:   PetscCall(PetscFree(rwaits));
1570:   if (nsend) PetscCallMPI(MPI_Waitall(nsend, swaits, sstatus));

1572:   /* add received column indices into ta to update Crmax */
1573:   a_loc = (Mat_SeqAIJ *)ptap->A_loc->data;

1575:   /* create and initialize a linked list */
1576:   PetscCall(PetscHMapICreateWithSize(an, &ta)); /* for compute Crmax */
1577:   MatRowMergeMax_SeqAIJ(a_loc, ptap->A_loc->rmap->N, ta);

1579:   for (k = 0; k < nrecv; k++) { /* k-th received message */
1580:     Jptr = buf_rj[k];
1581:     for (j = 0; j < len_r[k]; j++) PetscCall(PetscHMapISet(ta, *(Jptr + j) + 1, 1));
1582:   }
1583:   PetscCall(PetscHMapIGetSize(ta, &Crmax));
1584:   PetscCall(PetscHMapIDestroy(&ta));

1586:   /* (4) send and recv coi */
1587:   PetscCall(PetscCommGetNewTag(comm, &tagi));
1588:   PetscCall(PetscPostIrecvInt(comm, tagi, nrecv, id_r, len_ri, &buf_ri, &rwaits));
1589:   PetscCall(PetscMalloc1(len, &buf_s));
1590:   buf_si = buf_s; /* points to the beginning of k-th msg to be sent */
1591:   for (proc = 0, k = 0; proc < size; proc++) {
1592:     if (!len_s[proc]) continue;
1593:     /* form outgoing message for i-structure:
1594:          buf_si[0]:                 nrows to be sent
1595:                [1:nrows]:           row index (global)
1596:                [nrows+1:2*nrows+1]: i-structure index
1597:     */
1598:     nrows       = len_si[proc] / 2 - 1; /* num of rows in Co to be sent to [proc] */
1599:     buf_si_i    = buf_si + nrows + 1;
1600:     buf_si[0]   = nrows;
1601:     buf_si_i[0] = 0;
1602:     nrows       = 0;
1603:     for (i = owners_co[proc]; i < owners_co[proc + 1]; i++) {
1604:       nzi                 = coi[i + 1] - coi[i];
1605:       buf_si_i[nrows + 1] = buf_si_i[nrows] + nzi;   /* i-structure */
1606:       buf_si[nrows + 1]   = prmap[i] - owners[proc]; /* local row index */
1607:       nrows++;
1608:     }
1609:     PetscCallMPI(MPIU_Isend(buf_si, len_si[proc], MPIU_INT, proc, tagi, comm, swaits + k));
1610:     k++;
1611:     buf_si += len_si[proc];
1612:   }
1613:   for (i = 0; i < nrecv; i++) PetscCallMPI(MPI_Waitany(nrecv, rwaits, &icompleted, &rstatus));
1614:   PetscCall(PetscFree(rwaits));
1615:   if (nsend) PetscCallMPI(MPI_Waitall(nsend, swaits, sstatus));

1617:   PetscCall(PetscFree4(len_s, len_si, sstatus, owners_co));
1618:   PetscCall(PetscFree(len_ri));
1619:   PetscCall(PetscFree(swaits));
1620:   PetscCall(PetscFree(buf_s));

1622:   /* (5) compute the local portion of C      */
1623:   /* set initial free space to be Crmax, sufficient for holding nonzeros in each row of C */
1624:   PetscCall(PetscFreeSpaceGet(Crmax, &free_space));
1625:   current_space = free_space;

1627:   PetscCall(PetscMalloc3(nrecv, &buf_ri_k, nrecv, &nextrow, nrecv, &nextci));
1628:   for (k = 0; k < nrecv; k++) {
1629:     buf_ri_k[k] = buf_ri[k]; /* beginning of k-th recved i-structure */
1630:     nrows       = *buf_ri_k[k];
1631:     nextrow[k]  = buf_ri_k[k] + 1;           /* next row number of k-th recved i-structure */
1632:     nextci[k]   = buf_ri_k[k] + (nrows + 1); /* points to the next i-structure of k-th recved i-structure  */
1633:   }

1635:   MatPreallocateBegin(comm, pn, an, dnz, onz);
1636:   PetscCall(PetscLLCondensedCreate(Crmax, aN, &lnk, &lnkbt));
1637:   for (i = 0; i < pn; i++) { /* for each local row of C */
1638:     /* add C_loc into C */
1639:     nzi  = c_loc->i[i + 1] - c_loc->i[i];
1640:     Jptr = c_loc->j + c_loc->i[i];
1641:     PetscCall(PetscLLCondensedAddSorted(nzi, Jptr, lnk, lnkbt));

1643:     /* add received col data into lnk */
1644:     for (k = 0; k < nrecv; k++) { /* k-th received message */
1645:       if (i == *nextrow[k]) {     /* i-th row */
1646:         nzi  = *(nextci[k] + 1) - *nextci[k];
1647:         Jptr = buf_rj[k] + *nextci[k];
1648:         PetscCall(PetscLLCondensedAddSorted(nzi, Jptr, lnk, lnkbt));
1649:         nextrow[k]++;
1650:         nextci[k]++;
1651:       }
1652:     }

1654:     /* add missing diagonal entry */
1655:     if (C->force_diagonals) {
1656:       k = i + owners[rank]; /* column index */
1657:       PetscCall(PetscLLCondensedAddSorted(1, &k, lnk, lnkbt));
1658:     }

1660:     nzi = lnk[0];

1662:     /* copy data into free space, then initialize lnk */
1663:     PetscCall(PetscLLCondensedClean(aN, nzi, current_space->array, lnk, lnkbt));
1664:     PetscCall(MatPreallocateSet(i + owners[rank], nzi, current_space->array, dnz, onz));
1665:   }
1666:   PetscCall(PetscFree3(buf_ri_k, nextrow, nextci));
1667:   PetscCall(PetscLLDestroy(lnk, lnkbt));
1668:   PetscCall(PetscFreeSpaceDestroy(free_space));

1670:   /* local sizes and preallocation */
1671:   PetscCall(MatSetSizes(C, pn, an, PETSC_DETERMINE, PETSC_DETERMINE));
1672:   PetscCall(PetscLayoutSetBlockSize(C->rmap, P->cmap->bs));
1673:   PetscCall(PetscLayoutSetBlockSize(C->cmap, A->cmap->bs));
1674:   PetscCall(MatMPIAIJSetPreallocation(C, 0, dnz, 0, onz));
1675:   MatPreallocateEnd(dnz, onz);

1677:   /* add C_loc and C_oth to C */
1678:   PetscCall(MatGetOwnershipRange(C, &rstart, NULL));
1679:   for (i = 0; i < pn; i++) {
1680:     ncols = c_loc->i[i + 1] - c_loc->i[i];
1681:     cols  = c_loc->j + c_loc->i[i];
1682:     row   = rstart + i;
1683:     PetscCall(MatSetValues(C, 1, (const PetscInt *)&row, ncols, (const PetscInt *)cols, NULL, INSERT_VALUES));

1685:     if (C->force_diagonals) PetscCall(MatSetValues(C, 1, (const PetscInt *)&row, 1, (const PetscInt *)&row, NULL, INSERT_VALUES));
1686:   }
1687:   for (i = 0; i < con; i++) {
1688:     ncols = c_oth->i[i + 1] - c_oth->i[i];
1689:     cols  = c_oth->j + c_oth->i[i];
1690:     row   = prmap[i];
1691:     PetscCall(MatSetValues(C, 1, (const PetscInt *)&row, ncols, (const PetscInt *)cols, NULL, INSERT_VALUES));
1692:   }
1693:   PetscCall(MatAssemblyBegin(C, MAT_FINAL_ASSEMBLY));
1694:   PetscCall(MatAssemblyEnd(C, MAT_FINAL_ASSEMBLY));
1695:   PetscCall(MatSetOption(C, MAT_NEW_NONZERO_LOCATION_ERR, PETSC_TRUE));

1697:   /* members in merge */
1698:   PetscCall(PetscFree(id_r));
1699:   PetscCall(PetscFree(len_r));
1700:   PetscCall(PetscFree(buf_ri[0]));
1701:   PetscCall(PetscFree(buf_ri));
1702:   PetscCall(PetscFree(buf_rj[0]));
1703:   PetscCall(PetscFree(buf_rj));
1704:   PetscCall(PetscLayoutDestroy(&rowmap));

1706:   /* attach the supporting struct to C for reuse */
1707:   C->product->data    = ptap;
1708:   C->product->destroy = MatProductCtxDestroy_MPIAIJ_PtAP;
1709:   PetscFunctionReturn(PETSC_SUCCESS);
1710: }

1712: PetscErrorCode MatTransposeMatMultNumeric_MPIAIJ_MPIAIJ_nonscalable(Mat P, Mat A, Mat C)
1713: {
1714:   Mat_MPIAIJ          *p = (Mat_MPIAIJ *)P->data;
1715:   Mat_SeqAIJ          *c_seq;
1716:   MatProductCtx_APMPI *ptap;
1717:   Mat                  A_loc, C_loc, C_oth;
1718:   PetscInt             i, rstart, rend, cm, ncols, row;
1719:   const PetscInt      *cols;
1720:   const PetscScalar   *vals;

1722:   PetscFunctionBegin;
1723:   MatCheckProduct(C, 3);
1724:   ptap = (MatProductCtx_APMPI *)C->product->data;
1725:   PetscCheck(ptap, PetscObjectComm((PetscObject)C), PETSC_ERR_ARG_WRONGSTATE, "PtAP cannot be computed. Missing data");
1726:   PetscCheck(ptap->A_loc, PetscObjectComm((PetscObject)C), PETSC_ERR_ARG_WRONGSTATE, "PtA cannot be reused. Do not call MatProductClear()");
1727:   PetscCall(MatZeroEntries(C));

1729:   /* These matrices are obtained in MatTransposeMatMultSymbolic() */
1730:   /* 1) get R = Pd^T, Ro = Po^T */
1731:   PetscCall(MatTransposeSetPrecursor(p->A, ptap->Rd));
1732:   PetscCall(MatTranspose(p->A, MAT_REUSE_MATRIX, &ptap->Rd));
1733:   PetscCall(MatTransposeSetPrecursor(p->B, ptap->Ro));
1734:   PetscCall(MatTranspose(p->B, MAT_REUSE_MATRIX, &ptap->Ro));

1736:   /* 2) compute numeric A_loc */
1737:   PetscCall(MatMPIAIJGetLocalMat(A, MAT_REUSE_MATRIX, &ptap->A_loc));

1739:   /* 3) C_loc = Rd*A_loc, C_oth = Ro*A_loc */
1740:   A_loc = ptap->A_loc;
1741:   PetscCall(ptap->C_loc->ops->matmultnumeric(ptap->Rd, A_loc, ptap->C_loc));
1742:   PetscCall(ptap->C_oth->ops->matmultnumeric(ptap->Ro, A_loc, ptap->C_oth));
1743:   C_loc = ptap->C_loc;
1744:   C_oth = ptap->C_oth;

1746:   /* add C_loc and C_oth to C */
1747:   PetscCall(MatGetOwnershipRange(C, &rstart, &rend));

1749:   /* C_loc -> C */
1750:   cm    = C_loc->rmap->N;
1751:   c_seq = (Mat_SeqAIJ *)C_loc->data;
1752:   cols  = c_seq->j;
1753:   vals  = c_seq->a;
1754:   for (i = 0; i < cm; i++) {
1755:     ncols = c_seq->i[i + 1] - c_seq->i[i];
1756:     row   = rstart + i;
1757:     PetscCall(MatSetValues(C, 1, &row, ncols, cols, vals, ADD_VALUES));
1758:     cols += ncols;
1759:     vals += ncols;
1760:   }

1762:   /* Co -> C, off-processor part */
1763:   cm    = C_oth->rmap->N;
1764:   c_seq = (Mat_SeqAIJ *)C_oth->data;
1765:   cols  = c_seq->j;
1766:   vals  = c_seq->a;
1767:   for (i = 0; i < cm; i++) {
1768:     ncols = c_seq->i[i + 1] - c_seq->i[i];
1769:     row   = p->garray[i];
1770:     PetscCall(MatSetValues(C, 1, &row, ncols, cols, vals, ADD_VALUES));
1771:     cols += ncols;
1772:     vals += ncols;
1773:   }
1774:   PetscCall(MatAssemblyBegin(C, MAT_FINAL_ASSEMBLY));
1775:   PetscCall(MatAssemblyEnd(C, MAT_FINAL_ASSEMBLY));
1776:   PetscCall(MatSetOption(C, MAT_NEW_NONZERO_LOCATION_ERR, PETSC_TRUE));
1777:   PetscFunctionReturn(PETSC_SUCCESS);
1778: }

1780: PetscErrorCode MatTransposeMatMultNumeric_MPIAIJ_MPIAIJ(Mat P, Mat A, Mat C)
1781: {
1782:   MatMergeSeqsToMPI   *merge;
1783:   Mat_MPIAIJ          *p  = (Mat_MPIAIJ *)P->data;
1784:   Mat_SeqAIJ          *pd = (Mat_SeqAIJ *)p->A->data, *po = (Mat_SeqAIJ *)p->B->data;
1785:   MatProductCtx_APMPI *ap;
1786:   PetscInt            *adj;
1787:   PetscInt             i, j, k, anz, pnz, row, *cj, nexta;
1788:   MatScalar           *ada, *ca, valtmp;
1789:   PetscInt             am = A->rmap->n, cm = C->rmap->n, pon = p->B->cmap->n;
1790:   MPI_Comm             comm;
1791:   PetscMPIInt          size, rank, taga, *len_s, proc;
1792:   PetscInt            *owners, nrows, **buf_ri_k, **nextrow, **nextci;
1793:   PetscInt           **buf_ri, **buf_rj;
1794:   PetscInt             cnz = 0, *bj_i, *bi, *bj, bnz, nextcj; /* bi,bj,ba: local array of C(mpi mat) */
1795:   MPI_Request         *s_waits, *r_waits;
1796:   MPI_Status          *status;
1797:   MatScalar          **abuf_r, *ba_i, *pA, *coa, *ba;
1798:   const PetscScalar   *dummy;
1799:   PetscInt            *ai, *aj, *coi, *coj, *poJ, *pdJ;
1800:   Mat                  A_loc;
1801:   Mat_SeqAIJ          *a_loc;

1803:   PetscFunctionBegin;
1804:   MatCheckProduct(C, 3);
1805:   ap = (MatProductCtx_APMPI *)C->product->data;
1806:   PetscCheck(ap, PetscObjectComm((PetscObject)C), PETSC_ERR_ARG_WRONGSTATE, "PtA cannot be computed. Missing data");
1807:   PetscCheck(ap->A_loc, PetscObjectComm((PetscObject)C), PETSC_ERR_ARG_WRONGSTATE, "PtA cannot be reused. Do not call MatProductClear()");
1808:   PetscCall(PetscObjectGetComm((PetscObject)C, &comm));
1809:   PetscCallMPI(MPI_Comm_size(comm, &size));
1810:   PetscCallMPI(MPI_Comm_rank(comm, &rank));

1812:   merge = ap->merge;

1814:   /* 2) compute numeric C_seq = P_loc^T*A_loc */
1815:   /* get data from symbolic products */
1816:   coi = merge->coi;
1817:   coj = merge->coj;
1818:   PetscCall(PetscCalloc1(coi[pon], &coa));
1819:   bi     = merge->bi;
1820:   bj     = merge->bj;
1821:   owners = merge->rowmap->range;
1822:   PetscCall(PetscCalloc1(bi[cm], &ba));

1824:   /* get A_loc by taking all local rows of A */
1825:   A_loc = ap->A_loc;
1826:   PetscCall(MatMPIAIJGetLocalMat(A, MAT_REUSE_MATRIX, &A_loc));
1827:   a_loc = (Mat_SeqAIJ *)A_loc->data;
1828:   ai    = a_loc->i;
1829:   aj    = a_loc->j;

1831:   /* trigger copy to CPU */
1832:   PetscCall(MatSeqAIJGetArrayRead(p->A, &dummy));
1833:   PetscCall(MatSeqAIJRestoreArrayRead(p->A, &dummy));
1834:   PetscCall(MatSeqAIJGetArrayRead(p->B, &dummy));
1835:   PetscCall(MatSeqAIJRestoreArrayRead(p->B, &dummy));
1836:   for (i = 0; i < am; i++) {
1837:     anz = ai[i + 1] - ai[i];
1838:     adj = aj + ai[i];
1839:     ada = a_loc->a + ai[i];

1841:     /* 2-b) Compute Cseq = P_loc[i,:]^T*A[i,:] using outer product */
1842:     /* put the value into Co=(p->B)^T*A (off-diagonal part, send to others) */
1843:     pnz = po->i[i + 1] - po->i[i];
1844:     poJ = po->j + po->i[i];
1845:     pA  = po->a + po->i[i];
1846:     for (j = 0; j < pnz; j++) {
1847:       row = poJ[j];
1848:       cj  = coj + coi[row];
1849:       ca  = coa + coi[row];
1850:       /* perform sparse axpy */
1851:       nexta  = 0;
1852:       valtmp = pA[j];
1853:       for (k = 0; nexta < anz; k++) {
1854:         if (cj[k] == adj[nexta]) {
1855:           ca[k] += valtmp * ada[nexta];
1856:           nexta++;
1857:         }
1858:       }
1859:       PetscCall(PetscLogFlops(2.0 * anz));
1860:     }

1862:     /* put the value into Cd (diagonal part) */
1863:     pnz = pd->i[i + 1] - pd->i[i];
1864:     pdJ = pd->j + pd->i[i];
1865:     pA  = pd->a + pd->i[i];
1866:     for (j = 0; j < pnz; j++) {
1867:       row = pdJ[j];
1868:       cj  = bj + bi[row];
1869:       ca  = ba + bi[row];
1870:       /* perform sparse axpy */
1871:       nexta  = 0;
1872:       valtmp = pA[j];
1873:       for (k = 0; nexta < anz; k++) {
1874:         if (cj[k] == adj[nexta]) {
1875:           ca[k] += valtmp * ada[nexta];
1876:           nexta++;
1877:         }
1878:       }
1879:       PetscCall(PetscLogFlops(2.0 * anz));
1880:     }
1881:   }

1883:   /* 3) send and recv matrix values coa */
1884:   buf_ri = merge->buf_ri;
1885:   buf_rj = merge->buf_rj;
1886:   len_s  = merge->len_s;
1887:   PetscCall(PetscCommGetNewTag(comm, &taga));
1888:   PetscCall(PetscPostIrecvScalar(comm, taga, merge->nrecv, merge->id_r, merge->len_r, &abuf_r, &r_waits));

1890:   PetscCall(PetscMalloc2(merge->nsend, &s_waits, size, &status));
1891:   for (proc = 0, k = 0; proc < size; proc++) {
1892:     if (!len_s[proc]) continue;
1893:     i = merge->owners_co[proc];
1894:     PetscCallMPI(MPIU_Isend(coa + coi[i], len_s[proc], MPIU_MATSCALAR, proc, taga, comm, s_waits + k));
1895:     k++;
1896:   }
1897:   if (merge->nrecv) PetscCallMPI(MPI_Waitall(merge->nrecv, r_waits, status));
1898:   if (merge->nsend) PetscCallMPI(MPI_Waitall(merge->nsend, s_waits, status));

1900:   PetscCall(PetscFree2(s_waits, status));
1901:   PetscCall(PetscFree(r_waits));
1902:   PetscCall(PetscFree(coa));

1904:   /* 4) insert local Cseq and received values into Cmpi */
1905:   PetscCall(PetscMalloc3(merge->nrecv, &buf_ri_k, merge->nrecv, &nextrow, merge->nrecv, &nextci));
1906:   for (k = 0; k < merge->nrecv; k++) {
1907:     buf_ri_k[k] = buf_ri[k]; /* beginning of k-th recved i-structure */
1908:     nrows       = *buf_ri_k[k];
1909:     nextrow[k]  = buf_ri_k[k] + 1;           /* next row number of k-th recved i-structure */
1910:     nextci[k]   = buf_ri_k[k] + (nrows + 1); /* points to the next i-structure of k-th recved i-structure  */
1911:   }

1913:   for (i = 0; i < cm; i++) {
1914:     row  = owners[rank] + i; /* global row index of C_seq */
1915:     bj_i = bj + bi[i];       /* col indices of the i-th row of C */
1916:     ba_i = ba + bi[i];
1917:     bnz  = bi[i + 1] - bi[i];
1918:     /* add received vals into ba */
1919:     for (k = 0; k < merge->nrecv; k++) { /* k-th received message */
1920:       /* i-th row */
1921:       if (i == *nextrow[k]) {
1922:         cnz    = *(nextci[k] + 1) - *nextci[k];
1923:         cj     = buf_rj[k] + *nextci[k];
1924:         ca     = abuf_r[k] + *nextci[k];
1925:         nextcj = 0;
1926:         for (j = 0; nextcj < cnz; j++) {
1927:           if (bj_i[j] == cj[nextcj]) { /* bcol == ccol */
1928:             ba_i[j] += ca[nextcj++];
1929:           }
1930:         }
1931:         nextrow[k]++;
1932:         nextci[k]++;
1933:         PetscCall(PetscLogFlops(2.0 * cnz));
1934:       }
1935:     }
1936:     PetscCall(MatSetValues(C, 1, &row, bnz, bj_i, ba_i, INSERT_VALUES));
1937:   }
1938:   PetscCall(MatAssemblyBegin(C, MAT_FINAL_ASSEMBLY));
1939:   PetscCall(MatAssemblyEnd(C, MAT_FINAL_ASSEMBLY));

1941:   PetscCall(PetscFree(ba));
1942:   PetscCall(PetscFree(abuf_r[0]));
1943:   PetscCall(PetscFree(abuf_r));
1944:   PetscCall(PetscFree3(buf_ri_k, nextrow, nextci));
1945:   PetscFunctionReturn(PETSC_SUCCESS);
1946: }

1948: PetscErrorCode MatTransposeMatMultSymbolic_MPIAIJ_MPIAIJ(Mat P, Mat A, PetscReal fill, Mat C)
1949: {
1950:   Mat                  A_loc;
1951:   MatProductCtx_APMPI *ap;
1952:   PetscFreeSpaceList   free_space = NULL, current_space = NULL;
1953:   Mat_MPIAIJ          *p = (Mat_MPIAIJ *)P->data, *a = (Mat_MPIAIJ *)A->data;
1954:   PetscInt            *pdti, *pdtj, *poti, *potj, *ptJ;
1955:   PetscInt             nnz;
1956:   PetscInt            *lnk, *owners_co, *coi, *coj, i, k, pnz, row;
1957:   PetscInt             am = A->rmap->n, pn = P->cmap->n;
1958:   MPI_Comm             comm;
1959:   PetscMPIInt          size, rank, tagi, tagj, *len_si, *len_s, *len_ri, proc;
1960:   PetscInt           **buf_rj, **buf_ri, **buf_ri_k;
1961:   PetscInt             len, *dnz, *onz, *owners;
1962:   PetscInt             nzi, *bi, *bj;
1963:   PetscInt             nrows, *buf_s, *buf_si, *buf_si_i, **nextrow, **nextci;
1964:   MPI_Request         *swaits, *rwaits;
1965:   MPI_Status          *sstatus, rstatus;
1966:   MatMergeSeqsToMPI   *merge;
1967:   PetscInt            *ai, *aj, *Jptr, anz, *prmap = p->garray, pon, nspacedouble = 0, j;
1968:   PetscReal            afill  = 1.0, afill_tmp;
1969:   PetscInt             rstart = P->cmap->rstart, rmax, Armax;
1970:   Mat_SeqAIJ          *a_loc;
1971:   PetscHMapI           ta;
1972:   MatType              mtype;

1974:   PetscFunctionBegin;
1975:   PetscCall(PetscObjectGetComm((PetscObject)A, &comm));
1976:   /* check if matrix local sizes are compatible */
1977:   PetscCheck(A->rmap->rstart == P->rmap->rstart && A->rmap->rend == P->rmap->rend, comm, PETSC_ERR_ARG_SIZ, "Matrix local dimensions are incompatible, A (%" PetscInt_FMT ", %" PetscInt_FMT ") != P (%" PetscInt_FMT ",%" PetscInt_FMT ")", A->rmap->rstart,
1978:              A->rmap->rend, P->rmap->rstart, P->rmap->rend);

1980:   PetscCallMPI(MPI_Comm_size(comm, &size));
1981:   PetscCallMPI(MPI_Comm_rank(comm, &rank));

1983:   /* create struct MatProductCtx_APMPI and attached it to C later */
1984:   PetscCall(PetscNew(&ap));

1986:   /* get A_loc by taking all local rows of A */
1987:   PetscCall(MatMPIAIJGetLocalMat_Private(A, MAT_INITIAL_MATRIX, C->structure_only, &A_loc));

1989:   ap->A_loc = A_loc;
1990:   a_loc     = (Mat_SeqAIJ *)A_loc->data;
1991:   ai        = a_loc->i;
1992:   aj        = a_loc->j;

1994:   /* determine symbolic Co=(p->B)^T*A - send to others */
1995:   PetscCall(MatGetSymbolicTranspose_SeqAIJ(p->A, &pdti, &pdtj));
1996:   PetscCall(MatGetSymbolicTranspose_SeqAIJ(p->B, &poti, &potj));
1997:   pon = p->B->cmap->n; /* total num of rows to be sent to other processors
1998:                          >= (num of nonzero rows of C_seq) - pn */
1999:   PetscCall(PetscMalloc1(pon + 1, &coi));
2000:   coi[0] = 0;

2002:   /* set initial free space to be fill*(nnz(p->B) + nnz(A)) */
2003:   nnz = PetscRealIntMultTruncate(fill, PetscIntSumTruncate(poti[pon], ai[am]));
2004:   PetscCall(PetscFreeSpaceGet(nnz, &free_space));
2005:   current_space = free_space;

2007:   /* create and initialize a linked list */
2008:   PetscCall(PetscHMapICreateWithSize(A->cmap->n + a->B->cmap->N, &ta));
2009:   MatRowMergeMax_SeqAIJ(a_loc, am, ta);
2010:   PetscCall(PetscHMapIGetSize(ta, &Armax));

2012:   PetscCall(PetscLLCondensedCreate_Scalable(Armax, &lnk));

2014:   for (i = 0; i < pon; i++) {
2015:     pnz = poti[i + 1] - poti[i];
2016:     ptJ = potj + poti[i];
2017:     for (j = 0; j < pnz; j++) {
2018:       row  = ptJ[j]; /* row of A_loc == col of Pot */
2019:       anz  = ai[row + 1] - ai[row];
2020:       Jptr = aj + ai[row];
2021:       /* add non-zero cols of AP into the sorted linked list lnk */
2022:       PetscCall(PetscLLCondensedAddSorted_Scalable(anz, Jptr, lnk));
2023:     }
2024:     nnz = lnk[0];

2026:     /* If free space is not available, double the total space in the list */
2027:     if (current_space->local_remaining < nnz) {
2028:       PetscCall(PetscFreeSpaceGet(PetscIntSumTruncate(nnz, current_space->total_array_size), &current_space));
2029:       nspacedouble++;
2030:     }

2032:     /* Copy data into free space, and zero out denserows */
2033:     PetscCall(PetscLLCondensedClean_Scalable(nnz, current_space->array, lnk));

2035:     current_space->array += nnz;
2036:     current_space->local_used += nnz;
2037:     current_space->local_remaining -= nnz;

2039:     coi[i + 1] = coi[i] + nnz;
2040:   }

2042:   PetscCall(PetscMalloc1(coi[pon], &coj));
2043:   PetscCall(PetscFreeSpaceContiguous(&free_space, coj));
2044:   PetscCall(PetscLLCondensedDestroy_Scalable(lnk)); /* must destroy to get a new one for C */

2046:   afill_tmp = (PetscReal)coi[pon] / (poti[pon] + ai[am] + 1);
2047:   if (afill_tmp > afill) afill = afill_tmp;

2049:   /* send j-array (coj) of Co to other processors */
2050:   /* determine row ownership */
2051:   PetscCall(PetscNew(&merge));
2052:   PetscCall(PetscLayoutCreate(comm, &merge->rowmap));

2054:   merge->rowmap->n  = pn;
2055:   merge->rowmap->bs = 1;

2057:   PetscCall(PetscLayoutSetUp(merge->rowmap));
2058:   owners = merge->rowmap->range;

2060:   /* determine the number of messages to send, their lengths */
2061:   PetscCall(PetscCalloc1(size, &len_si));
2062:   PetscCall(PetscCalloc1(size, &merge->len_s));

2064:   len_s        = merge->len_s;
2065:   merge->nsend = 0;

2067:   PetscCall(PetscMalloc1(size + 1, &owners_co));

2069:   proc = 0;
2070:   for (i = 0; i < pon; i++) {
2071:     while (prmap[i] >= owners[proc + 1]) proc++;
2072:     len_si[proc]++; /* num of rows in Co to be sent to [proc] */
2073:     len_s[proc] += coi[i + 1] - coi[i];
2074:   }

2076:   len          = 0; /* max length of buf_si[] */
2077:   owners_co[0] = 0;
2078:   for (proc = 0; proc < size; proc++) {
2079:     owners_co[proc + 1] = owners_co[proc] + len_si[proc];
2080:     if (len_s[proc]) {
2081:       merge->nsend++;
2082:       len_si[proc] = 2 * (len_si[proc] + 1);
2083:       len += len_si[proc];
2084:     }
2085:   }

2087:   /* determine the number and length of messages to receive for coi and coj  */
2088:   PetscCall(PetscGatherNumberOfMessages(comm, NULL, len_s, &merge->nrecv));
2089:   PetscCall(PetscGatherMessageLengths2(comm, merge->nsend, merge->nrecv, len_s, len_si, &merge->id_r, &merge->len_r, &len_ri));

2091:   /* post the Irecv and Isend of coj */
2092:   PetscCall(PetscCommGetNewTag(comm, &tagj));
2093:   PetscCall(PetscPostIrecvInt(comm, tagj, merge->nrecv, merge->id_r, merge->len_r, &buf_rj, &rwaits));
2094:   PetscCall(PetscMalloc1(merge->nsend, &swaits));
2095:   for (proc = 0, k = 0; proc < size; proc++) {
2096:     if (!len_s[proc]) continue;
2097:     i = owners_co[proc];
2098:     PetscCallMPI(MPIU_Isend(coj + coi[i], len_s[proc], MPIU_INT, proc, tagj, comm, swaits + k));
2099:     k++;
2100:   }

2102:   /* receives and sends of coj are complete */
2103:   PetscCall(PetscMalloc1(size, &sstatus));
2104:   for (i = 0; i < merge->nrecv; i++) {
2105:     PETSC_UNUSED PetscMPIInt icompleted;
2106:     PetscCallMPI(MPI_Waitany(merge->nrecv, rwaits, &icompleted, &rstatus));
2107:   }
2108:   PetscCall(PetscFree(rwaits));
2109:   if (merge->nsend) PetscCallMPI(MPI_Waitall(merge->nsend, swaits, sstatus));

2111:   /* add received column indices into table to update Armax */
2112:   /* Armax can be as large as aN if a P[row,:] is dense, see src/ksp/ksp/tutorials/ex56.c! */
2113:   for (k = 0; k < merge->nrecv; k++) { /* k-th received message */
2114:     Jptr = buf_rj[k];
2115:     for (j = 0; j < merge->len_r[k]; j++) PetscCall(PetscHMapISet(ta, *(Jptr + j) + 1, 1));
2116:   }
2117:   PetscCall(PetscHMapIGetSize(ta, &Armax));

2119:   /* send and recv coi */
2120:   PetscCall(PetscCommGetNewTag(comm, &tagi));
2121:   PetscCall(PetscPostIrecvInt(comm, tagi, merge->nrecv, merge->id_r, len_ri, &buf_ri, &rwaits));
2122:   PetscCall(PetscMalloc1(len, &buf_s));
2123:   buf_si = buf_s; /* points to the beginning of k-th msg to be sent */
2124:   for (proc = 0, k = 0; proc < size; proc++) {
2125:     if (!len_s[proc]) continue;
2126:     /* form outgoing message for i-structure:
2127:          buf_si[0]:                 nrows to be sent
2128:                [1:nrows]:           row index (global)
2129:                [nrows+1:2*nrows+1]: i-structure index
2130:     */
2131:     nrows       = len_si[proc] / 2 - 1;
2132:     buf_si_i    = buf_si + nrows + 1;
2133:     buf_si[0]   = nrows;
2134:     buf_si_i[0] = 0;
2135:     nrows       = 0;
2136:     for (i = owners_co[proc]; i < owners_co[proc + 1]; i++) {
2137:       nzi                 = coi[i + 1] - coi[i];
2138:       buf_si_i[nrows + 1] = buf_si_i[nrows] + nzi;   /* i-structure */
2139:       buf_si[nrows + 1]   = prmap[i] - owners[proc]; /* local row index */
2140:       nrows++;
2141:     }
2142:     PetscCallMPI(MPIU_Isend(buf_si, len_si[proc], MPIU_INT, proc, tagi, comm, swaits + k));
2143:     k++;
2144:     buf_si += len_si[proc];
2145:   }
2146:   i = merge->nrecv;
2147:   while (i--) {
2148:     PETSC_UNUSED PetscMPIInt icompleted;
2149:     PetscCallMPI(MPI_Waitany(merge->nrecv, rwaits, &icompleted, &rstatus));
2150:   }
2151:   PetscCall(PetscFree(rwaits));
2152:   if (merge->nsend) PetscCallMPI(MPI_Waitall(merge->nsend, swaits, sstatus));
2153:   PetscCall(PetscFree(len_si));
2154:   PetscCall(PetscFree(len_ri));
2155:   PetscCall(PetscFree(swaits));
2156:   PetscCall(PetscFree(sstatus));
2157:   PetscCall(PetscFree(buf_s));

2159:   /* compute the local portion of C (mpi mat) */
2160:   /* allocate bi array and free space for accumulating nonzero column info */
2161:   PetscCall(PetscMalloc1(pn + 1, &bi));
2162:   bi[0] = 0;

2164:   /* set initial free space to be fill*(nnz(P) + nnz(AP)) */
2165:   nnz = PetscRealIntMultTruncate(fill, PetscIntSumTruncate(pdti[pn], PetscIntSumTruncate(poti[pon], ai[am])));
2166:   PetscCall(PetscFreeSpaceGet(nnz, &free_space));
2167:   current_space = free_space;

2169:   PetscCall(PetscMalloc3(merge->nrecv, &buf_ri_k, merge->nrecv, &nextrow, merge->nrecv, &nextci));
2170:   for (k = 0; k < merge->nrecv; k++) {
2171:     buf_ri_k[k] = buf_ri[k]; /* beginning of k-th recved i-structure */
2172:     nrows       = *buf_ri_k[k];
2173:     nextrow[k]  = buf_ri_k[k] + 1;           /* next row number of k-th recved i-structure */
2174:     nextci[k]   = buf_ri_k[k] + (nrows + 1); /* points to the next i-structure of k-th received i-structure  */
2175:   }

2177:   PetscCall(PetscLLCondensedCreate_Scalable(Armax, &lnk));
2178:   MatPreallocateBegin(comm, pn, A->cmap->n, dnz, onz);
2179:   rmax = 0;
2180:   for (i = 0; i < pn; i++) {
2181:     /* add pdt[i,:]*AP into lnk */
2182:     pnz = pdti[i + 1] - pdti[i];
2183:     ptJ = pdtj + pdti[i];
2184:     for (j = 0; j < pnz; j++) {
2185:       row  = ptJ[j]; /* row of AP == col of Pt */
2186:       anz  = ai[row + 1] - ai[row];
2187:       Jptr = aj + ai[row];
2188:       /* add non-zero cols of AP into the sorted linked list lnk */
2189:       PetscCall(PetscLLCondensedAddSorted_Scalable(anz, Jptr, lnk));
2190:     }

2192:     /* add received col data into lnk */
2193:     for (k = 0; k < merge->nrecv; k++) { /* k-th received message */
2194:       if (i == *nextrow[k]) {            /* i-th row */
2195:         nzi  = *(nextci[k] + 1) - *nextci[k];
2196:         Jptr = buf_rj[k] + *nextci[k];
2197:         PetscCall(PetscLLCondensedAddSorted_Scalable(nzi, Jptr, lnk));
2198:         nextrow[k]++;
2199:         nextci[k]++;
2200:       }
2201:     }

2203:     /* add missing diagonal entry */
2204:     if (C->force_diagonals) {
2205:       k = i + owners[rank]; /* column index */
2206:       PetscCall(PetscLLCondensedAddSorted_Scalable(1, &k, lnk));
2207:     }

2209:     nnz = lnk[0];

2211:     /* if free space is not available, make more free space */
2212:     if (current_space->local_remaining < nnz) {
2213:       PetscCall(PetscFreeSpaceGet(PetscIntSumTruncate(nnz, current_space->total_array_size), &current_space));
2214:       nspacedouble++;
2215:     }
2216:     /* copy data into free space, then initialize lnk */
2217:     PetscCall(PetscLLCondensedClean_Scalable(nnz, current_space->array, lnk));
2218:     PetscCall(MatPreallocateSet(i + owners[rank], nnz, current_space->array, dnz, onz));

2220:     current_space->array += nnz;
2221:     current_space->local_used += nnz;
2222:     current_space->local_remaining -= nnz;

2224:     bi[i + 1] = bi[i] + nnz;
2225:     if (nnz > rmax) rmax = nnz;
2226:   }
2227:   PetscCall(PetscFree3(buf_ri_k, nextrow, nextci));

2229:   PetscCall(PetscMalloc1(bi[pn], &bj));
2230:   PetscCall(PetscFreeSpaceContiguous(&free_space, bj));
2231:   afill_tmp = (PetscReal)bi[pn] / (pdti[pn] + poti[pon] + ai[am] + 1);
2232:   if (afill_tmp > afill) afill = afill_tmp;
2233:   PetscCall(PetscLLCondensedDestroy_Scalable(lnk));
2234:   PetscCall(PetscHMapIDestroy(&ta));
2235:   PetscCall(MatRestoreSymbolicTranspose_SeqAIJ(p->A, &pdti, &pdtj));
2236:   PetscCall(MatRestoreSymbolicTranspose_SeqAIJ(p->B, &poti, &potj));

2238:   /* create symbolic parallel matrix C - why cannot be assembled in Numeric part   */
2239:   PetscCall(MatSetSizes(C, pn, A->cmap->n, PETSC_DETERMINE, PETSC_DETERMINE));
2240:   PetscCall(MatSetBlockSizes(C, P->cmap->bs, A->cmap->bs));
2241:   PetscCall(MatGetType(A, &mtype));
2242:   PetscCall(MatSetType(C, C->structure_only ? MATMPIAIJ : mtype));
2243:   PetscCall(MatMPIAIJSetPreallocation(C, 0, dnz, 0, onz));
2244:   MatPreallocateEnd(dnz, onz);
2245:   PetscCall(MatSetBlockSize(C, 1));
2246:   PetscCall(MatSetOption(C, MAT_NO_OFF_PROC_ENTRIES, PETSC_TRUE));
2247:   for (i = 0; i < pn; i++) {
2248:     row  = i + rstart;
2249:     nnz  = bi[i + 1] - bi[i];
2250:     Jptr = bj + bi[i];
2251:     PetscCall(MatSetValues(C, 1, &row, nnz, Jptr, NULL, INSERT_VALUES));
2252:   }
2253:   PetscCall(MatAssemblyBegin(C, MAT_FINAL_ASSEMBLY));
2254:   PetscCall(MatAssemblyEnd(C, MAT_FINAL_ASSEMBLY));
2255:   PetscCall(MatSetOption(C, MAT_NEW_NONZERO_LOCATION_ERR, PETSC_TRUE));
2256:   merge->bi        = bi;
2257:   merge->bj        = bj;
2258:   merge->coi       = coi;
2259:   merge->coj       = coj;
2260:   merge->buf_ri    = buf_ri;
2261:   merge->buf_rj    = buf_rj;
2262:   merge->owners_co = owners_co;

2264:   /* attach the supporting struct to C for reuse */
2265:   C->product->data    = ap;
2266:   C->product->destroy = MatProductCtxDestroy_MPIAIJ_PtAP;
2267:   ap->merge           = merge;

2269:   C->ops->mattransposemultnumeric = MatTransposeMatMultNumeric_MPIAIJ_MPIAIJ;

2271:   if (PetscDefined(USE_INFO)) {
2272:     if (bi[pn] != 0) {
2273:       PetscCall(PetscInfo(C, "Reallocs %" PetscInt_FMT "; Fill ratio: given %g needed %g.\n", nspacedouble, (double)fill, (double)afill));
2274:       PetscCall(PetscInfo(C, "Use MatTransposeMatMult(A,B,MatReuse,%g,&C) for best performance.\n", (double)afill));
2275:     } else PetscCall(PetscInfo(C, "Empty matrix product\n"));
2276:   }
2277:   PetscFunctionReturn(PETSC_SUCCESS);
2278: }

2280: static PetscErrorCode MatProductSymbolic_AtB_MPIAIJ_MPIAIJ(Mat C)
2281: {
2282:   Mat_Product *product = C->product;
2283:   Mat          A = product->A, B = product->B;
2284:   PetscReal    fill = product->fill;
2285:   PetscBool    flg;

2287:   PetscFunctionBegin;
2288:   /* scalable */
2289:   PetscCall(PetscStrcmp(product->alg, "scalable", &flg));
2290:   if (flg || C->structure_only) {
2291:     if (C->structure_only) PetscCall(MatProductSetAlgorithm(C, "scalable"));
2292:     PetscCall(MatTransposeMatMultSymbolic_MPIAIJ_MPIAIJ(A, B, fill, C));
2293:     goto next;
2294:   }

2296:   /* nonscalable */
2297:   PetscCall(PetscStrcmp(product->alg, "nonscalable", &flg));
2298:   if (flg) {
2299:     PetscCall(MatTransposeMatMultSymbolic_MPIAIJ_MPIAIJ_nonscalable(A, B, fill, C));
2300:     goto next;
2301:   }

2303:   /* matmatmult */
2304:   PetscCall(PetscStrcmp(product->alg, "at*b", &flg));
2305:   if (flg) {
2306:     Mat                  At;
2307:     MatProductCtx_APMPI *ptap;

2309:     PetscCall(MatTranspose(A, MAT_INITIAL_MATRIX, &At));
2310:     PetscCall(MatMatMultSymbolic_MPIAIJ_MPIAIJ(At, B, fill, C));
2311:     ptap = (MatProductCtx_APMPI *)C->product->data;
2312:     if (ptap) {
2313:       ptap->Pt            = At;
2314:       C->product->destroy = MatProductCtxDestroy_MPIAIJ_PtAP;
2315:     }
2316:     C->ops->transposematmultnumeric = MatTransposeMatMultNumeric_MPIAIJ_MPIAIJ_matmatmult;
2317:     goto next;
2318:   }

2320:   /* backend general code */
2321:   PetscCall(PetscStrcmp(product->alg, "backend", &flg));
2322:   if (flg) {
2323:     PetscCall(MatProductSymbolic_MPIAIJBACKEND(C));
2324:     PetscFunctionReturn(PETSC_SUCCESS);
2325:   }

2327:   SETERRQ(PETSC_COMM_SELF, PETSC_ERR_SUP, "MatProduct type is not supported");

2329: next:
2330:   C->ops->productnumeric = MatProductNumeric_AtB;
2331:   PetscFunctionReturn(PETSC_SUCCESS);
2332: }

2334: /* Set options for MatMatMultxxx_MPIAIJ_MPIAIJ */
2335: static PetscErrorCode MatProductSetFromOptions_MPIAIJ_AB(Mat C)
2336: {
2337:   Mat_Product *product = C->product;
2338:   Mat          A = product->A, B = product->B;
2339: #if PetscDefined(HAVE_HYPRE)
2340:   const char *algTypes[5] = {"scalable", "nonscalable", "seqmpi", "backend", "hypre"};
2341:   PetscInt    nalg        = 5;
2342: #else
2343:   const char *algTypes[4] = {
2344:     "scalable",
2345:     "nonscalable",
2346:     "seqmpi",
2347:     "backend",
2348:   };
2349:   PetscInt nalg = 4;
2350: #endif
2351:   PetscInt  alg = 1; /* set nonscalable algorithm as default */
2352:   PetscBool flg;
2353:   MPI_Comm  comm;

2355:   PetscFunctionBegin;
2356:   PetscCall(PetscObjectGetComm((PetscObject)C, &comm));

2358:   /* Set "nonscalable" as default algorithm */
2359:   PetscCall(PetscStrcmp(C->product->alg, "default", &flg));
2360:   if (flg) {
2361:     PetscCall(MatProductSetAlgorithm(C, algTypes[alg]));

2363:     /* Set "scalable" as default if BN and local nonzeros of A and B are large */
2364:     if (B->cmap->N > 100000) { /* may switch to scalable algorithm as default */
2365:       MatInfo   Ainfo, Binfo;
2366:       PetscInt  nz_local;
2367:       PetscBool alg_scalable = PETSC_FALSE;

2369:       PetscCall(MatGetInfo(A, MAT_LOCAL, &Ainfo));
2370:       PetscCall(MatGetInfo(B, MAT_LOCAL, &Binfo));
2371:       nz_local = (PetscInt)(Ainfo.nz_allocated + Binfo.nz_allocated);

2373:       if (B->cmap->N > product->fill * nz_local) alg_scalable = PETSC_TRUE;
2374:       PetscCallMPI(MPIU_Allreduce(MPI_IN_PLACE, &alg_scalable, 1, MPI_C_BOOL, MPI_LOR, comm));

2376:       if (alg_scalable) {
2377:         alg = 0; /* scalable algorithm would 50% slower than nonscalable algorithm */
2378:         PetscCall(MatProductSetAlgorithm(C, algTypes[alg]));
2379:         PetscCall(PetscInfo(B, "Use scalable algorithm, BN %" PetscInt_FMT ", fill*nz_allocated %g\n", B->cmap->N, (double)(product->fill * nz_local)));
2380:       }
2381:     }
2382:   }

2384:   /* Get runtime option */
2385:   if (product->api_user) {
2386:     PetscOptionsBegin(PetscObjectComm((PetscObject)C), ((PetscObject)C)->prefix, "MatMatMult", "Mat");
2387:     PetscCall(PetscOptionsEList("-matmatmult_via", "Algorithmic approach", "MatMatMult", algTypes, nalg, algTypes[alg], &alg, &flg));
2388:     PetscOptionsEnd();
2389:   } else {
2390:     PetscOptionsBegin(PetscObjectComm((PetscObject)C), ((PetscObject)C)->prefix, "MatProduct_AB", "Mat");
2391:     PetscCall(PetscOptionsEList("-mat_product_algorithm", "Algorithmic approach", "MatMatMult", algTypes, nalg, algTypes[alg], &alg, &flg));
2392:     PetscOptionsEnd();
2393:   }
2394:   if (flg) PetscCall(MatProductSetAlgorithm(C, algTypes[alg]));

2396:   C->ops->productsymbolic = MatProductSymbolic_AB_MPIAIJ_MPIAIJ;
2397:   PetscFunctionReturn(PETSC_SUCCESS);
2398: }

2400: static PetscErrorCode MatProductSetFromOptions_MPIAIJ_ABt(Mat C)
2401: {
2402:   PetscFunctionBegin;
2403:   PetscCall(MatProductSetFromOptions_MPIAIJ_AB(C));
2404:   C->ops->productsymbolic = MatProductSymbolic_ABt_MPIAIJ_MPIAIJ;
2405:   PetscFunctionReturn(PETSC_SUCCESS);
2406: }

2408: /* Set options for MatTransposeMatMultXXX_MPIAIJ_MPIAIJ */
2409: static PetscErrorCode MatProductSetFromOptions_MPIAIJ_AtB(Mat C)
2410: {
2411:   Mat_Product *product = C->product;
2412:   Mat          A = product->A, B = product->B;
2413:   const char  *algTypes[4] = {"scalable", "nonscalable", "at*b", "backend"};
2414:   PetscInt     nalg        = 4;
2415:   PetscInt     alg         = 1; /* set default algorithm  */
2416:   PetscBool    flg;
2417:   MPI_Comm     comm;

2419:   PetscFunctionBegin;
2420:   /* Check matrix local sizes */
2421:   PetscCall(PetscObjectGetComm((PetscObject)C, &comm));
2422:   PetscCheck(A->rmap->rstart == B->rmap->rstart && A->rmap->rend == B->rmap->rend, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Matrix local dimensions are incompatible, A (%" PetscInt_FMT ", %" PetscInt_FMT ") != B (%" PetscInt_FMT ",%" PetscInt_FMT ")",
2423:              A->rmap->rstart, A->rmap->rend, B->rmap->rstart, B->rmap->rend);

2425:   /* Set default algorithm */
2426:   PetscCall(PetscStrcmp(C->product->alg, "default", &flg));
2427:   if (flg) PetscCall(MatProductSetAlgorithm(C, algTypes[alg]));

2429:   /* Set "scalable" as default if BN and local nonzeros of A and B are large */
2430:   if (alg && B->cmap->N > 100000) { /* may switch to scalable algorithm as default */
2431:     MatInfo   Ainfo, Binfo;
2432:     PetscInt  nz_local;
2433:     PetscBool alg_scalable = PETSC_FALSE;

2435:     PetscCall(MatGetInfo(A, MAT_LOCAL, &Ainfo));
2436:     PetscCall(MatGetInfo(B, MAT_LOCAL, &Binfo));
2437:     nz_local = (PetscInt)(Ainfo.nz_allocated + Binfo.nz_allocated);

2439:     if (B->cmap->N > product->fill * nz_local) alg_scalable = PETSC_TRUE;
2440:     PetscCallMPI(MPIU_Allreduce(MPI_IN_PLACE, &alg_scalable, 1, MPI_C_BOOL, MPI_LOR, comm));

2442:     if (alg_scalable) {
2443:       alg = 0; /* scalable algorithm would 50% slower than nonscalable algorithm */
2444:       PetscCall(MatProductSetAlgorithm(C, algTypes[alg]));
2445:       PetscCall(PetscInfo(B, "Use scalable algorithm, BN %" PetscInt_FMT ", fill*nz_allocated %g\n", B->cmap->N, (double)(product->fill * nz_local)));
2446:     }
2447:   }

2449:   /* Get runtime option */
2450:   if (product->api_user) {
2451:     PetscOptionsBegin(PetscObjectComm((PetscObject)C), ((PetscObject)C)->prefix, "MatTransposeMatMult", "Mat");
2452:     PetscCall(PetscOptionsEList("-mattransposematmult_via", "Algorithmic approach", "MatTransposeMatMult", algTypes, nalg, algTypes[alg], &alg, &flg));
2453:     PetscOptionsEnd();
2454:   } else {
2455:     PetscOptionsBegin(PetscObjectComm((PetscObject)C), ((PetscObject)C)->prefix, "MatProduct_AtB", "Mat");
2456:     PetscCall(PetscOptionsEList("-mat_product_algorithm", "Algorithmic approach", "MatTransposeMatMult", algTypes, nalg, algTypes[alg], &alg, &flg));
2457:     PetscOptionsEnd();
2458:   }
2459:   if (flg) PetscCall(MatProductSetAlgorithm(C, algTypes[alg]));

2461:   C->ops->productsymbolic = MatProductSymbolic_AtB_MPIAIJ_MPIAIJ;
2462:   PetscFunctionReturn(PETSC_SUCCESS);
2463: }

2465: static PetscErrorCode MatProductSetFromOptions_MPIAIJ_PtAP(Mat C)
2466: {
2467:   Mat_Product *product = C->product;
2468:   Mat          A = product->A, P = product->B;
2469:   MPI_Comm     comm;
2470:   PetscBool    flg;
2471:   PetscInt     alg = 1; /* set default algorithm */
2472: #if !PetscDefined(HAVE_HYPRE)
2473:   const char *algTypes[5] = {"scalable", "nonscalable", "allatonce", "allatonce_merged", "backend"};
2474:   PetscInt    nalg        = 5;
2475: #else
2476:   const char *algTypes[6] = {"scalable", "nonscalable", "allatonce", "allatonce_merged", "backend", "hypre"};
2477:   PetscInt    nalg        = 6;
2478: #endif
2479:   PetscInt pN = P->cmap->N;

2481:   PetscFunctionBegin;
2482:   /* Check matrix local sizes */
2483:   PetscCall(PetscObjectGetComm((PetscObject)C, &comm));
2484:   PetscCheck(A->rmap->rstart == P->rmap->rstart && A->rmap->rend == P->rmap->rend, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Matrix local dimensions are incompatible, Arow (%" PetscInt_FMT ", %" PetscInt_FMT ") != Prow (%" PetscInt_FMT ",%" PetscInt_FMT ")",
2485:              A->rmap->rstart, A->rmap->rend, P->rmap->rstart, P->rmap->rend);
2486:   PetscCheck(A->cmap->rstart == P->rmap->rstart && A->cmap->rend == P->rmap->rend, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Matrix local dimensions are incompatible, Acol (%" PetscInt_FMT ", %" PetscInt_FMT ") != Prow (%" PetscInt_FMT ",%" PetscInt_FMT ")",
2487:              A->cmap->rstart, A->cmap->rend, P->rmap->rstart, P->rmap->rend);

2489:   /* Set "nonscalable" as default algorithm */
2490:   PetscCall(PetscStrcmp(C->product->alg, "default", &flg));
2491:   if (flg) {
2492:     PetscCall(MatProductSetAlgorithm(C, algTypes[alg]));

2494:     /* Set "scalable" as default if BN and local nonzeros of A and B are large */
2495:     if (pN > 100000) {
2496:       MatInfo   Ainfo, Pinfo;
2497:       PetscInt  nz_local;
2498:       PetscBool alg_scalable = PETSC_FALSE;

2500:       PetscCall(MatGetInfo(A, MAT_LOCAL, &Ainfo));
2501:       PetscCall(MatGetInfo(P, MAT_LOCAL, &Pinfo));
2502:       nz_local = (PetscInt)(Ainfo.nz_allocated + Pinfo.nz_allocated);

2504:       if (pN > product->fill * nz_local) alg_scalable = PETSC_TRUE;
2505:       PetscCallMPI(MPIU_Allreduce(MPI_IN_PLACE, &alg_scalable, 1, MPI_C_BOOL, MPI_LOR, comm));

2507:       if (alg_scalable) {
2508:         alg = 0; /* scalable algorithm would 50% slower than nonscalable algorithm */
2509:         PetscCall(MatProductSetAlgorithm(C, algTypes[alg]));
2510:       }
2511:     }
2512:   }

2514:   /* Get runtime option */
2515:   if (product->api_user) {
2516:     PetscOptionsBegin(PetscObjectComm((PetscObject)C), ((PetscObject)C)->prefix, "MatPtAP", "Mat");
2517:     PetscCall(PetscOptionsEList("-matptap_via", "Algorithmic approach", "MatPtAP", algTypes, nalg, algTypes[alg], &alg, &flg));
2518:     PetscOptionsEnd();
2519:   } else {
2520:     PetscOptionsBegin(PetscObjectComm((PetscObject)C), ((PetscObject)C)->prefix, "MatProduct_PtAP", "Mat");
2521:     PetscCall(PetscOptionsEList("-mat_product_algorithm", "Algorithmic approach", "MatPtAP", algTypes, nalg, algTypes[alg], &alg, &flg));
2522:     PetscOptionsEnd();
2523:   }
2524:   if (flg) PetscCall(MatProductSetAlgorithm(C, algTypes[alg]));

2526:   C->ops->productsymbolic = MatProductSymbolic_PtAP_MPIAIJ_MPIAIJ;
2527:   PetscFunctionReturn(PETSC_SUCCESS);
2528: }

2530: static PetscErrorCode MatProductSetFromOptions_MPIAIJ_RARt(Mat C)
2531: {
2532:   Mat_Product *product = C->product;
2533:   Mat          A = product->A, R = product->B;

2535:   PetscFunctionBegin;
2536:   /* Check matrix local sizes */
2537:   PetscCheck(A->cmap->n == R->cmap->n && A->rmap->n == R->cmap->n, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Matrix local dimensions are incompatible, A local (%" PetscInt_FMT ", %" PetscInt_FMT "), R local (%" PetscInt_FMT ",%" PetscInt_FMT ")", A->rmap->n,
2538:              A->rmap->n, R->rmap->n, R->cmap->n);

2540:   C->ops->productsymbolic = MatProductSymbolic_RARt_MPIAIJ_MPIAIJ;
2541:   PetscFunctionReturn(PETSC_SUCCESS);
2542: }

2544: /*
2545:  Set options for ABC = A*B*C = A*(B*C); ABC's algorithm must be chosen from AB's algorithm
2546: */
2547: static PetscErrorCode MatProductSetFromOptions_MPIAIJ_ABC(Mat C)
2548: {
2549:   Mat_Product *product     = C->product;
2550:   PetscBool    flg         = PETSC_FALSE;
2551:   PetscInt     alg         = 1; /* default algorithm */
2552:   const char  *algTypes[3] = {"scalable", "nonscalable", "seqmpi"};
2553:   PetscInt     nalg        = 3;

2555:   PetscFunctionBegin;
2556:   /* Set default algorithm */
2557:   PetscCall(PetscStrcmp(C->product->alg, "default", &flg));
2558:   if (flg) PetscCall(MatProductSetAlgorithm(C, algTypes[alg]));

2560:   /* Get runtime option */
2561:   if (product->api_user) {
2562:     PetscOptionsBegin(PetscObjectComm((PetscObject)C), ((PetscObject)C)->prefix, "MatMatMatMult", "Mat");
2563:     PetscCall(PetscOptionsEList("-matmatmatmult_via", "Algorithmic approach", "MatMatMatMult", algTypes, nalg, algTypes[alg], &alg, &flg));
2564:     PetscOptionsEnd();
2565:   } else {
2566:     PetscOptionsBegin(PetscObjectComm((PetscObject)C), ((PetscObject)C)->prefix, "MatProduct_ABC", "Mat");
2567:     PetscCall(PetscOptionsEList("-mat_product_algorithm", "Algorithmic approach", "MatProduct_ABC", algTypes, nalg, algTypes[alg], &alg, &flg));
2568:     PetscOptionsEnd();
2569:   }
2570:   if (flg) PetscCall(MatProductSetAlgorithm(C, algTypes[alg]));

2572:   C->ops->matmatmultsymbolic = MatMatMatMultSymbolic_MPIAIJ_MPIAIJ_MPIAIJ;
2573:   C->ops->productsymbolic    = MatProductSymbolic_ABC;
2574:   PetscFunctionReturn(PETSC_SUCCESS);
2575: }

2577: PETSC_INTERN PetscErrorCode MatProductSetFromOptions_MPIAIJ(Mat C)
2578: {
2579:   Mat_Product *product = C->product;

2581:   PetscFunctionBegin;
2582:   switch (product->type) {
2583:   case MATPRODUCT_AB:
2584:     PetscCall(MatProductSetFromOptions_MPIAIJ_AB(C));
2585:     break;
2586:   case MATPRODUCT_ABt:
2587:     PetscCall(MatProductSetFromOptions_MPIAIJ_ABt(C));
2588:     break;
2589:   case MATPRODUCT_AtB:
2590:     PetscCall(MatProductSetFromOptions_MPIAIJ_AtB(C));
2591:     break;
2592:   case MATPRODUCT_PtAP:
2593:     PetscCall(MatProductSetFromOptions_MPIAIJ_PtAP(C));
2594:     break;
2595:   case MATPRODUCT_RARt:
2596:     PetscCall(MatProductSetFromOptions_MPIAIJ_RARt(C));
2597:     break;
2598:   case MATPRODUCT_ABC:
2599:     PetscCall(MatProductSetFromOptions_MPIAIJ_ABC(C));
2600:     break;
2601:   default:
2602:     break;
2603:   }
2604:   PetscFunctionReturn(PETSC_SUCCESS);
2605: }