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) {
 41:     PetscCall(MatMatMultSymbolic_MPIAIJ_MPIAIJ(A, B, fill, C));
 42:     PetscFunctionReturn(PETSC_SUCCESS);
 43:   }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

347:   PetscFunctionBegin;
348:   if (A->cmap->rstart != B->rmap->rstart || A->cmap->rend != B->rmap->rend)
349:     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);

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

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

361:   PetscFunctionBegin;
362:   if (A->rmap->rstart != B->rmap->rstart || A->rmap->rend != B->rmap->rend)
363:     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);

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

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

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

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

398: static PetscErrorCode MatMPIAIJ_MPIDenseDestroy(PetscCtxRt ctx)
399: {
400:   MPIAIJ_MPIDense *contents = *(MPIAIJ_MPIDense **)ctx;

402:   PetscFunctionBegin;
403:   PetscCall(MatMPIDenseScatterDestroy_Private(contents));
404:   PetscCall(PetscFree(contents));
405:   PetscFunctionReturn(PETSC_SUCCESS);
406: }

408: PETSC_INTERN PetscErrorCode MatMPIDenseScatterSetUp_Private(VecScatter ctx, PetscInt nrows, PetscInt bs, PetscInt Am, Mat B, Mat C, MPIAIJ_MPIDense *contents, PetscInt *batchSize, PetscInt *numBatches)
409: {
410:   PetscInt        Bm = B->rmap->n, BN = B->cmap->N, Bbn, Bbs, numBb;
411:   MPI_Comm        comm;
412:   MPI_Datatype    type1;
413:   const PetscInt *sindices, *sstarts, *rstarts;
414:   PetscMPIInt    *disp;
415:   PetscMPIInt     nsends, nrecvs, nrows_to, nrows_from, bs_mpi;

417:   PetscFunctionBegin;
418:   PetscCall(PetscObjectGetComm((PetscObject)C, &comm));
419:   PetscCall(MatDenseGetLDA(B, &contents->blda));
420:   PetscCall(VecScatterGetRemote_Private(ctx, PETSC_TRUE, &nsends, &sstarts, &sindices, NULL, NULL));
421:   PetscCall(VecScatterGetRemoteOrdered_Private(ctx, PETSC_FALSE, &nrecvs, &rstarts, NULL, NULL, NULL));

423:   /* Create column block of B and C for memory scalability when BN is too large */
424:   /* Estimate Bbn, column size of Bb */
425:   if (nrows) {
426:     Bbn = 2 * Am * BN / nrows;
427:     if (!Bbn) Bbn = 1;
428:   } else Bbn = BN;
429:   Bbs = B->cmap->bs;
430:   Bbn = Bbn / Bbs * Bbs;
431:   if (Bbn > BN) Bbn = BN;
432:   PetscCallMPI(MPIU_Allreduce(MPI_IN_PLACE, &Bbn, 1, MPIU_INT, MPI_MAX, comm));

434:   /* Enable runtime option for Bbn */
435:   PetscOptionsBegin(comm, ((PetscObject)C)->prefix, "MatProduct", "Mat");
436:   PetscCall(PetscOptionsDeprecated("-matmatmult_Bbn", "-matproduct_batch_size", "3.25", NULL));
437:   PetscCall(PetscOptionsBoundedInt("-matproduct_batch_size", "Number of dense columns per batch", "MatProduct", Bbn, &Bbn, NULL, 0));
438:   PetscOptionsEnd();
439:   Bbn = PetscMin(Bbn, BN);

441:   if (Bbn > 0 && Bbn < BN) numBb = BN / Bbn;
442:   else numBb = 0;
443:   if (numBb) PetscCall(PetscInfo(C, "Using column batches of size %" PetscInt_FMT " for %" PetscInt_FMT " dense columns\n", Bbn, BN));
444:   /* Create work matrix used to store off processor rows of B needed for local product */
445:   PetscCall(MatCreateSeqDense(PETSC_COMM_SELF, nrows, Bbn ? Bbn : BN, NULL, &contents->workB));

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

452:   PetscCall(PetscMalloc1(PetscMax(Bm, 1), &disp));
453:   PetscCall(PetscMPIIntCast(bs, &bs_mpi));
454:   for (PetscMPIInt i = 0; i < nsends; i++) {
455:     PetscCall(PetscMPIIntCast(sstarts[i + 1] - sstarts[i], &nrows_to));
456:     for (PetscInt j = 0; j < nrows_to; j++) PetscCall(PetscMPIIntCast(sindices[sstarts[i] + j] * bs, &disp[j]));
457:     PetscCallMPI(MPI_Type_create_indexed_block(nrows_to, bs_mpi, disp, MPIU_SCALAR, &type1));
458:     PetscCallMPI(MPI_Type_create_resized(type1, 0, contents->blda * sizeof(PetscScalar), &contents->stype[i]));
459:     PetscCallMPI(MPI_Type_commit(&contents->stype[i]));
460:     PetscCallMPI(MPI_Type_free(&type1));
461:   }

463:   for (PetscMPIInt i = 0; i < nrecvs; i++) {
464:     /* received values from a process form a (nrows_from x Bbn) row block in workB (column-wise) */
465:     PetscCall(PetscMPIIntCast((rstarts[i + 1] - rstarts[i]) * bs, &nrows_from));
466:     disp[0] = 0;
467:     PetscCallMPI(MPI_Type_create_indexed_block(1, nrows_from, disp, MPIU_SCALAR, &type1));
468:     PetscCallMPI(MPI_Type_create_resized(type1, 0, nrows * sizeof(PetscScalar), &contents->rtype[i]));
469:     PetscCallMPI(MPI_Type_commit(&contents->rtype[i]));
470:     PetscCallMPI(MPI_Type_free(&type1));
471:   }

473:   PetscCall(PetscFree(disp));
474:   PetscCall(VecScatterRestoreRemote_Private(ctx, PETSC_TRUE /*send*/, &nsends, &sstarts, &sindices, NULL, NULL));
475:   PetscCall(VecScatterRestoreRemoteOrdered_Private(ctx, PETSC_FALSE /*recv*/, &nrecvs, &rstarts, NULL, NULL, NULL));
476:   if (batchSize) *batchSize = Bbn;
477:   if (numBatches) *numBatches = numBb;
478:   PetscFunctionReturn(PETSC_SUCCESS);
479: }

481: static PetscErrorCode MatMatMultSymbolic_MPIAIJ_MPIDense(Mat A, Mat B, PetscReal fill, Mat C)
482: {
483:   Mat_MPIAIJ      *aij = (Mat_MPIAIJ *)A->data;
484:   MPIAIJ_MPIDense *contents;
485:   PetscInt         nz  = aij->B->cmap->n;
486:   VecScatter       ctx = aij->Mvctx;
487:   PetscInt         Am = A->rmap->n, BN = B->cmap->N;
488:   PetscBool        cisdense;

490:   PetscFunctionBegin;
491:   MatCheckProduct(C, 4);
492:   PetscCheck(!C->product->data, PetscObjectComm((PetscObject)C), PETSC_ERR_PLIB, "Product data not empty");
493:   PetscCall(PetscObjectBaseTypeCompare((PetscObject)C, MATMPIDENSE, &cisdense));
494:   if (!cisdense) PetscCall(MatSetType(C, ((PetscObject)B)->type_name));
495:   PetscCall(MatSetSizes(C, Am, B->cmap->n, A->rmap->N, BN));
496:   PetscCall(MatSetBlockSizesFromMats(C, A, B));
497:   PetscCall(MatSetUp(C));
498:   PetscCall(PetscNew(&contents));
499:   PetscCall(MatMPIDenseScatterSetUp_Private(ctx, nz, 1, Am, B, C, contents, NULL, NULL));
500:   PetscCall(MatSetOption(C, MAT_NO_OFF_PROC_ENTRIES, PETSC_TRUE));
501:   PetscCall(MatAssemblyBegin(C, MAT_FINAL_ASSEMBLY));
502:   PetscCall(MatAssemblyEnd(C, MAT_FINAL_ASSEMBLY));
503:   PetscCall(MatProductClear(aij->A));
504:   PetscCall(MatProductClear(((Mat_MPIDense *)B->data)->A));
505:   PetscCall(MatProductClear(((Mat_MPIDense *)C->data)->A));
506:   PetscCall(MatProductCreateWithMat(aij->A, ((Mat_MPIDense *)B->data)->A, NULL, ((Mat_MPIDense *)C->data)->A));
507:   PetscCall(MatProductSetType(((Mat_MPIDense *)C->data)->A, MATPRODUCT_AB));
508:   PetscCall(MatProductSetFromOptions(((Mat_MPIDense *)C->data)->A));
509:   PetscCall(MatProductSymbolic(((Mat_MPIDense *)C->data)->A));
510:   C->product->data       = contents;
511:   C->product->destroy    = MatMPIAIJ_MPIDenseDestroy;
512:   C->ops->matmultnumeric = MatMatMultNumeric_MPIAIJ_MPIDense;
513:   PetscFunctionReturn(PETSC_SUCCESS);
514: }

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

518: /*
519:     Performs an efficient scatter on the rows of B needed by this process; this is
520:     a modification of the VecScatterBegin_() routines.
521: */

523: PETSC_INTERN PetscErrorCode MatMPIDenseScatter_Private(VecScatter ctx, PetscInt nrows, PetscInt bs, Mat workB, MPIAIJ_MPIDense *contents, Mat B, Mat C)
524: {
525:   const PetscScalar *b;
526:   PetscScalar       *rvalues;
527:   const PetscInt    *sindices, *sstarts, *rstarts;
528:   const PetscMPIInt *sprocs, *rprocs;
529:   PetscMPIInt        nsends, nrecvs;
530:   MPI_Comm           comm;
531:   PetscMPIInt        tag = ((PetscObject)ctx)->tag, ncols, nsends_mpi, nrecvs_mpi;
532:   PetscInt           blda;

534:   PetscFunctionBegin;
535:   MatCheckProduct(C, 7);
536:   PetscCheck(C->product->data, PetscObjectComm((PetscObject)C), PETSC_ERR_PLIB, "Product data empty");
537:   PetscCall(PetscMPIIntCast(B->cmap->N, &ncols));
538:   PetscCall(VecScatterGetRemote_Private(ctx, PETSC_TRUE /*send*/, &nsends, &sstarts, &sindices, &sprocs, NULL /*bs*/));
539:   PetscCall(VecScatterGetRemoteOrdered_Private(ctx, PETSC_FALSE /*recv*/, &nrecvs, &rstarts, NULL, &rprocs, NULL /*bs*/));
540:   PetscCall(PetscMPIIntCast(nsends, &nsends_mpi));
541:   PetscCall(PetscMPIIntCast(nrecvs, &nrecvs_mpi));
542:   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);

544:   PetscCall(MatDenseGetArrayRead(B, &b));
545:   PetscCall(MatDenseGetLDA(B, &blda));
546:   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);
547:   PetscCall(MatDenseGetArray(workB, &rvalues));

549:   /* Post recv, use MPI derived data type to save memory */
550:   PetscCall(PetscObjectGetComm((PetscObject)C, &comm));
551:   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));
552:   for (PetscMPIInt i = 0; i < nsends; i++) PetscCallMPI(MPIU_Isend(b, ncols, contents->stype[i], sprocs[i], tag, comm, contents->swaits + i));

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

557:   PetscCall(VecScatterRestoreRemote_Private(ctx, PETSC_TRUE /*send*/, &nsends, &sstarts, &sindices, &sprocs, NULL));
558:   PetscCall(VecScatterRestoreRemoteOrdered_Private(ctx, PETSC_FALSE /*recv*/, &nrecvs, &rstarts, NULL, &rprocs, NULL));
559:   PetscCall(MatDenseRestoreArrayRead(B, &b));
560:   PetscCall(MatDenseRestoreArray(workB, &rvalues));
561:   PetscFunctionReturn(PETSC_SUCCESS);
562: }

564: static PetscErrorCode MatMPIDenseScatter(Mat A, Mat B, Mat workB, Mat C)
565: {
566:   Mat_MPIAIJ      *aij = (Mat_MPIAIJ *)A->data;
567:   MPIAIJ_MPIDense *contents;

569:   PetscFunctionBegin;
570:   contents = (MPIAIJ_MPIDense *)C->product->data;
571:   PetscCall(MatMPIDenseScatter_Private(aij->Mvctx, aij->B->cmap->n, 1, workB, contents, B, C));
572:   PetscFunctionReturn(PETSC_SUCCESS);
573: }

575: static PetscErrorCode MatMatMultNumeric_MPIAIJ_MPIDense(Mat A, Mat B, Mat C)
576: {
577:   Mat_MPIAIJ      *aij    = (Mat_MPIAIJ *)A->data;
578:   Mat_MPIDense    *bdense = (Mat_MPIDense *)B->data;
579:   Mat_MPIDense    *cdense = (Mat_MPIDense *)C->data;
580:   Mat              workB;
581:   MPIAIJ_MPIDense *contents;

583:   PetscFunctionBegin;
584:   MatCheckProduct(C, 3);
585:   PetscCheck(C->product->data, PetscObjectComm((PetscObject)C), PETSC_ERR_PLIB, "Product data empty");
586:   contents = (MPIAIJ_MPIDense *)C->product->data;
587:   /* diagonal block of A times all local rows of B, first make sure that everything is up-to-date */
588:   if (!cdense->A->product) {
589:     PetscCall(MatProductCreateWithMat(aij->A, bdense->A, NULL, cdense->A));
590:     PetscCall(MatProductSetType(cdense->A, MATPRODUCT_AB));
591:     PetscCall(MatProductSetFromOptions(cdense->A));
592:     PetscCall(MatProductSymbolic(cdense->A));
593:   } else PetscCall(MatProductReplaceMats(aij->A, bdense->A, NULL, cdense->A));
594:   if (PetscDefined(HAVE_CUPM) && !cdense->A->product->clear) {
595:     PetscBool flg;

597:     PetscCall(PetscObjectTypeCompare((PetscObject)C, MATMPIDENSE, &flg));
598:     if (flg) PetscCall(PetscObjectTypeCompare((PetscObject)A, MATMPIAIJ, &flg));
599:     if (!flg) cdense->A->product->clear = PETSC_TRUE; /* if either A or C is a device Mat, make sure MatProductClear() is called */
600:   }
601:   PetscCall(MatProductNumeric(cdense->A));
602:   if (contents->workB->cmap->n == B->cmap->N) {
603:     /* get off processor parts of B needed to complete C=A*B */
604:     workB = contents->workB;
605:     PetscCall(MatMPIDenseScatter(A, B, workB, C));

607:     /* off-diagonal block of A times nonlocal rows of B */
608:     PetscCall(MatMatMultNumericAdd_SeqAIJ_SeqDense(aij->B, workB, cdense->A, PETSC_TRUE));
609:   } else {
610:     Mat       Bb, Cb;
611:     PetscInt  BN = B->cmap->N, n = contents->workB->cmap->n, cols;
612:     PetscBool ccpu;

614:     PetscCheck(n > 0, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Column block size %" PetscInt_FMT " must be positive", n);
615:     /* Prevent from unneeded copies back and forth from the GPU
616:        when getting and restoring the submatrix
617:        We need a proper GPU code for AIJ * dense in parallel */
618:     PetscCall(MatBoundToCPU(C, &ccpu));
619:     PetscCall(MatBindToCPU(C, PETSC_TRUE));
620:     for (PetscInt i = 0; i < BN; i += n) {
621:       cols  = PetscMin(n, BN - i);
622:       workB = contents->workB;
623:       if (cols != n) PetscCall(MatDenseGetSubMatrix(contents->workB, PETSC_DECIDE, PETSC_DECIDE, 0, cols, &workB));
624:       PetscCall(MatDenseGetSubMatrix(B, PETSC_DECIDE, PETSC_DECIDE, i, i + cols, &Bb));
625:       PetscCall(MatDenseGetSubMatrix(C, PETSC_DECIDE, PETSC_DECIDE, i, i + cols, &Cb));

627:       /* get off processor parts of B needed to complete C=A*B */
628:       PetscCall(MatMPIDenseScatter(A, Bb, workB, C));

630:       /* off-diagonal block of A times nonlocal rows of B */
631:       cdense = (Mat_MPIDense *)Cb->data;
632:       PetscCall(MatMatMultNumericAdd_SeqAIJ_SeqDense(aij->B, workB, cdense->A, PETSC_TRUE));
633:       if (cols != n) PetscCall(MatDenseRestoreSubMatrix(contents->workB, &workB));
634:       PetscCall(MatDenseRestoreSubMatrix(B, &Bb));
635:       PetscCall(MatDenseRestoreSubMatrix(C, &Cb));
636:     }
637:     PetscCall(MatBindToCPU(C, ccpu));
638:   }
639:   PetscFunctionReturn(PETSC_SUCCESS);
640: }

642: PetscErrorCode MatMatMultNumeric_MPIAIJ_MPIAIJ(Mat A, Mat P, Mat C)
643: {
644:   Mat_MPIAIJ          *a = (Mat_MPIAIJ *)A->data, *c = (Mat_MPIAIJ *)C->data;
645:   Mat_SeqAIJ          *ad = (Mat_SeqAIJ *)a->A->data, *ao = (Mat_SeqAIJ *)a->B->data;
646:   Mat_SeqAIJ          *cd = (Mat_SeqAIJ *)c->A->data, *co = (Mat_SeqAIJ *)c->B->data;
647:   PetscInt            *adi = ad->i, *adj, *aoi = ao->i, *aoj;
648:   PetscScalar         *ada, *aoa, *cda = cd->a, *coa = co->a;
649:   Mat_SeqAIJ          *p_loc, *p_oth;
650:   PetscInt            *pi_loc, *pj_loc, *pi_oth, *pj_oth, *pj;
651:   PetscScalar         *pa_loc, *pa_oth, *pa, valtmp, *ca;
652:   PetscInt             cm = C->rmap->n, anz, pnz;
653:   MatProductCtx_APMPI *ptap;
654:   PetscScalar         *apa_sparse;
655:   const PetscScalar   *dummy;
656:   PetscInt            *api, *apj, *apJ, i, j, k, row;
657:   PetscInt             cstart = C->cmap->rstart;
658:   PetscInt             cdnz, conz, k0, k1, nextp;
659:   MPI_Comm             comm;
660:   PetscMPIInt          size;

662:   PetscFunctionBegin;
663:   MatCheckProduct(C, 3);
664:   ptap = (MatProductCtx_APMPI *)C->product->data;
665:   PetscCheck(ptap, PetscObjectComm((PetscObject)C), PETSC_ERR_ARG_WRONGSTATE, "PtAP cannot be computed. Missing data");
666:   PetscCall(PetscObjectGetComm((PetscObject)C, &comm));
667:   PetscCallMPI(MPI_Comm_size(comm, &size));
668:   PetscCheck(ptap->P_oth || size <= 1, PetscObjectComm((PetscObject)C), PETSC_ERR_ARG_WRONGSTATE, "AP cannot be reused. Do not call MatProductClear()");

670:   /* flag CPU mask for C */
671: #if PetscDefined(HAVE_DEVICE)
672:   if (C->offloadmask != PETSC_OFFLOAD_UNALLOCATED) C->offloadmask = PETSC_OFFLOAD_CPU;
673:   if (c->A->offloadmask != PETSC_OFFLOAD_UNALLOCATED) c->A->offloadmask = PETSC_OFFLOAD_CPU;
674:   if (c->B->offloadmask != PETSC_OFFLOAD_UNALLOCATED) c->B->offloadmask = PETSC_OFFLOAD_CPU;
675: #endif
676:   apa_sparse = ptap->apa;

678:   /* 1) get P_oth = ptap->P_oth  and P_loc = ptap->P_loc */
679:   /* update numerical values of P_oth and P_loc */
680:   PetscCall(MatGetBrowsOfAoCols_MPIAIJ(A, P, MAT_REUSE_MATRIX, &ptap->startsj_s, &ptap->startsj_r, &ptap->bufa, &ptap->P_oth));
681:   PetscCall(MatMPIAIJGetLocalMat(P, MAT_REUSE_MATRIX, &ptap->P_loc));

683:   /* 2) compute numeric C_loc = A_loc*P = Ad*P_loc + Ao*P_oth */
684:   /* get data from symbolic products */
685:   p_loc  = (Mat_SeqAIJ *)ptap->P_loc->data;
686:   pi_loc = p_loc->i;
687:   pj_loc = p_loc->j;
688:   pa_loc = p_loc->a;
689:   if (size > 1) {
690:     p_oth  = (Mat_SeqAIJ *)ptap->P_oth->data;
691:     pi_oth = p_oth->i;
692:     pj_oth = p_oth->j;
693:     pa_oth = p_oth->a;
694:   } else {
695:     p_oth  = NULL;
696:     pi_oth = NULL;
697:     pj_oth = NULL;
698:     pa_oth = NULL;
699:   }

701:   /* trigger copy to CPU */
702:   PetscCall(MatSeqAIJGetArrayRead(a->A, &dummy));
703:   PetscCall(MatSeqAIJRestoreArrayRead(a->A, &dummy));
704:   PetscCall(MatSeqAIJGetArrayRead(a->B, &dummy));
705:   PetscCall(MatSeqAIJRestoreArrayRead(a->B, &dummy));
706:   api = ptap->api;
707:   apj = ptap->apj;
708:   for (i = 0; i < cm; i++) {
709:     apJ = apj + api[i];

711:     /* diagonal portion of A */
712:     anz = adi[i + 1] - adi[i];
713:     adj = ad->j + adi[i];
714:     ada = ad->a + adi[i];
715:     for (j = 0; j < anz; j++) {
716:       row = adj[j];
717:       pnz = pi_loc[row + 1] - pi_loc[row];
718:       pj  = pj_loc + pi_loc[row];
719:       pa  = pa_loc + pi_loc[row];
720:       /* perform sparse axpy */
721:       valtmp = ada[j];
722:       nextp  = 0;
723:       for (k = 0; nextp < pnz; k++) {
724:         if (apJ[k] == pj[nextp]) { /* column of AP == column of P */
725:           apa_sparse[k] += valtmp * pa[nextp++];
726:         }
727:       }
728:       PetscCall(PetscLogFlops(2.0 * pnz));
729:     }

731:     /* off-diagonal portion of A */
732:     anz = aoi[i + 1] - aoi[i];
733:     aoj = PetscSafePointerPlusOffset(ao->j, aoi[i]);
734:     aoa = PetscSafePointerPlusOffset(ao->a, aoi[i]);
735:     for (j = 0; j < anz; j++) {
736:       row = aoj[j];
737:       pnz = pi_oth[row + 1] - pi_oth[row];
738:       pj  = pj_oth + pi_oth[row];
739:       pa  = pa_oth + pi_oth[row];
740:       /* perform sparse axpy */
741:       valtmp = aoa[j];
742:       nextp  = 0;
743:       for (k = 0; nextp < pnz; k++) {
744:         if (apJ[k] == pj[nextp]) { /* column of AP == column of P */
745:           apa_sparse[k] += valtmp * pa[nextp++];
746:         }
747:       }
748:       PetscCall(PetscLogFlops(2.0 * pnz));
749:     }

751:     /* set values in C */
752:     cdnz = cd->i[i + 1] - cd->i[i];
753:     conz = co->i[i + 1] - co->i[i];

755:     /* 1st off-diagonal part of C */
756:     ca = PetscSafePointerPlusOffset(coa, co->i[i]);
757:     k  = 0;
758:     for (k0 = 0; k0 < conz; k0++) {
759:       if (apJ[k] >= cstart) break;
760:       ca[k0]        = apa_sparse[k];
761:       apa_sparse[k] = 0.0;
762:       k++;
763:     }

765:     /* diagonal part of C */
766:     ca = cda + cd->i[i];
767:     for (k1 = 0; k1 < cdnz; k1++) {
768:       ca[k1]        = apa_sparse[k];
769:       apa_sparse[k] = 0.0;
770:       k++;
771:     }

773:     /* 2nd off-diagonal part of C */
774:     ca = PetscSafePointerPlusOffset(coa, co->i[i]);
775:     for (; k0 < conz; k0++) {
776:       ca[k0]        = apa_sparse[k];
777:       apa_sparse[k] = 0.0;
778:       k++;
779:     }
780:   }
781:   PetscCall(MatAssemblyBegin(C, MAT_FINAL_ASSEMBLY));
782:   PetscCall(MatAssemblyEnd(C, MAT_FINAL_ASSEMBLY));
783:   PetscFunctionReturn(PETSC_SUCCESS);
784: }

786: /* same as MatMatMultSymbolic_MPIAIJ_MPIAIJ_nonscalable(), except using LLCondensed to avoid O(BN) memory requirement */
787: PetscErrorCode MatMatMultSymbolic_MPIAIJ_MPIAIJ(Mat A, Mat P, PetscReal fill, Mat C)
788: {
789:   MPI_Comm             comm;
790:   PetscMPIInt          size;
791:   MatProductCtx_APMPI *ptap;
792:   PetscFreeSpaceList   free_space = NULL, current_space = NULL;
793:   Mat_MPIAIJ          *a  = (Mat_MPIAIJ *)A->data;
794:   Mat_SeqAIJ          *ad = (Mat_SeqAIJ *)a->A->data, *ao = (Mat_SeqAIJ *)a->B->data, *p_loc, *p_oth;
795:   PetscInt            *pi_loc, *pj_loc, *pi_oth, *pj_oth, *dnz, *onz;
796:   PetscInt            *adi = ad->i, *adj = ad->j, *aoi = ao->i, *aoj = ao->j, rstart = A->rmap->rstart;
797:   PetscInt             i, pnz, row, *api, *apj, *Jptr, apnz, nspacedouble = 0, j, nzi, *lnk, apnz_max = 1;
798:   PetscInt             am = A->rmap->n, pn = P->cmap->n, pm = P->rmap->n, lsize = pn + 20;
799:   PetscReal            afill;
800:   MatType              mtype;

802:   PetscFunctionBegin;
803:   MatCheckProduct(C, 4);
804:   PetscCheck(!C->product->data, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Extra product struct not empty");
805:   PetscCall(PetscObjectGetComm((PetscObject)A, &comm));
806:   PetscCallMPI(MPI_Comm_size(comm, &size));

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

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

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

817:   p_loc  = (Mat_SeqAIJ *)ptap->P_loc->data;
818:   pi_loc = p_loc->i;
819:   pj_loc = p_loc->j;
820:   if (size > 1) {
821:     p_oth  = (Mat_SeqAIJ *)ptap->P_oth->data;
822:     pi_oth = p_oth->i;
823:     pj_oth = p_oth->j;
824:   } else {
825:     p_oth  = NULL;
826:     pi_oth = NULL;
827:     pj_oth = NULL;
828:   }

830:   /* first, compute symbolic AP = A_loc*P = A_diag*P_loc + A_off*P_oth */
831:   PetscCall(PetscMalloc1(am + 1, &api));
832:   ptap->api = api;
833:   api[0]    = 0;

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

837:   /* Initial FreeSpace size is fill*(nnz(A)+nnz(P)) */
838:   PetscCall(PetscFreeSpaceGet(PetscRealIntMultTruncate(fill, PetscIntSumTruncate(adi[am], PetscIntSumTruncate(aoi[am], pi_loc[pm]))), &free_space));
839:   current_space = free_space;
840:   MatPreallocateBegin(comm, am, pn, dnz, onz);
841:   for (i = 0; i < am; i++) {
842:     /* diagonal portion of A */
843:     nzi = adi[i + 1] - adi[i];
844:     for (j = 0; j < nzi; j++) {
845:       row  = *adj++;
846:       pnz  = pi_loc[row + 1] - pi_loc[row];
847:       Jptr = pj_loc + pi_loc[row];
848:       /* Expand list if it is not long enough */
849:       if (pnz + apnz_max > lsize) {
850:         lsize = pnz + apnz_max;
851:         PetscCall(PetscLLCondensedExpand_Scalable(lsize, &lnk));
852:       }
853:       /* add non-zero cols of P into the sorted linked list lnk */
854:       PetscCall(PetscLLCondensedAddSorted_Scalable(pnz, Jptr, lnk));
855:       apnz       = *lnk; /* The first element in the list is the number of items in the list */
856:       api[i + 1] = api[i] + apnz;
857:       if (apnz > apnz_max) apnz_max = apnz + 1; /* '1' for diagonal entry */
858:     }
859:     /* off-diagonal portion of A */
860:     nzi = aoi[i + 1] - aoi[i];
861:     for (j = 0; j < nzi; j++) {
862:       row  = *aoj++;
863:       pnz  = pi_oth[row + 1] - pi_oth[row];
864:       Jptr = pj_oth + pi_oth[row];
865:       /* Expand list if it is not long enough */
866:       if (pnz + apnz_max > lsize) {
867:         lsize = pnz + apnz_max;
868:         PetscCall(PetscLLCondensedExpand_Scalable(lsize, &lnk));
869:       }
870:       /* add non-zero cols of P into the sorted linked list lnk */
871:       PetscCall(PetscLLCondensedAddSorted_Scalable(pnz, Jptr, lnk));
872:       apnz       = *lnk; /* The first element in the list is the number of items in the list */
873:       api[i + 1] = api[i] + apnz;
874:       if (apnz > apnz_max) apnz_max = apnz + 1; /* '1' for diagonal entry */
875:     }

877:     /* add missing diagonal entry */
878:     if (C->force_diagonals) {
879:       j = i + rstart; /* column index */
880:       PetscCall(PetscLLCondensedAddSorted_Scalable(1, &j, lnk));
881:     }

883:     apnz       = *lnk;
884:     api[i + 1] = api[i] + apnz;
885:     if (apnz > apnz_max) apnz_max = apnz;

887:     /* if free space is not available, double the total space in the list */
888:     if (current_space->local_remaining < apnz) {
889:       PetscCall(PetscFreeSpaceGet(PetscIntSumTruncate(apnz, current_space->total_array_size), &current_space));
890:       nspacedouble++;
891:     }

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

897:     current_space->array += apnz;
898:     current_space->local_used += apnz;
899:     current_space->local_remaining -= apnz;
900:   }

902:   /* Allocate space for apj, initialize apj, and */
903:   /* destroy list of free space and other temporary array(s) */
904:   PetscCall(PetscMalloc1(api[am], &ptap->apj));
905:   apj = ptap->apj;
906:   PetscCall(PetscFreeSpaceContiguous(&free_space, ptap->apj));
907:   PetscCall(PetscLLCondensedDestroy_Scalable(lnk));

909:   /* create and assemble symbolic parallel matrix C */
910:   PetscCall(MatSetSizes(C, am, pn, PETSC_DETERMINE, PETSC_DETERMINE));
911:   PetscCall(MatSetBlockSizesFromMats(C, A, P));
912:   PetscCall(MatGetType(A, &mtype));
913:   PetscCall(MatSetType(C, mtype));
914:   PetscCall(MatMPIAIJSetPreallocation(C, 0, dnz, 0, onz));
915:   MatPreallocateEnd(dnz, onz);

917:   /* malloc apa for assembly C */
918:   PetscCall(PetscCalloc1(apnz_max, &ptap->apa));

920:   PetscCall(MatSetValues_MPIAIJ_CopyFromCSRFormat_Symbolic(C, apj, api));
921:   PetscCall(MatSetOption(C, MAT_NO_OFF_PROC_ENTRIES, PETSC_TRUE));
922:   PetscCall(MatAssemblyBegin(C, MAT_FINAL_ASSEMBLY));
923:   PetscCall(MatAssemblyEnd(C, MAT_FINAL_ASSEMBLY));
924:   PetscCall(MatSetOption(C, MAT_NEW_NONZERO_LOCATION_ERR, PETSC_TRUE));

926:   C->ops->matmultnumeric = MatMatMultNumeric_MPIAIJ_MPIAIJ;
927:   C->ops->productnumeric = MatProductNumeric_AB;

929:   /* attach the supporting struct to C for reuse */
930:   C->product->data    = ptap;
931:   C->product->destroy = MatProductCtxDestroy_MPIAIJ_MatMatMult;

933:   /* set MatInfo */
934:   afill = (PetscReal)api[am] / (adi[am] + aoi[am] + pi_loc[pm] + 1) + 1.e-5;
935:   if (afill < 1.0) afill = 1.0;
936:   C->info.mallocs           = nspacedouble;
937:   C->info.fill_ratio_given  = fill;
938:   C->info.fill_ratio_needed = afill;

940:   if (PetscDefined(USE_INFO)) {
941:     if (api[am]) {
942:       PetscCall(PetscInfo(C, "Reallocs %" PetscInt_FMT "; Fill ratio: given %g needed %g.\n", nspacedouble, (double)fill, (double)afill));
943:       PetscCall(PetscInfo(C, "Use MatMatMult(A,B,MatReuse,%g,&C) for best performance.;\n", (double)afill));
944:     } else PetscCall(PetscInfo(C, "Empty matrix product\n"));
945:   }
946:   PetscFunctionReturn(PETSC_SUCCESS);
947: }

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

956:   /* Traverse all three arrays */
957:   while (i < size1 && j < size2 && k < size3) {
958:     if (in1[i] < in2[j] && in1[i] < in3[k]) {
959:       out[l++] = in1[i++];
960:     } else if (in2[j] < in1[i] && in2[j] < in3[k]) {
961:       out[l++] = in2[j++];
962:     } else if (in3[k] < in1[i] && in3[k] < in2[j]) {
963:       out[l++] = in3[k++];
964:     } else if (in1[i] == in2[j] && in1[i] < in3[k]) {
965:       out[l++] = in1[i];
966:       i++, j++;
967:     } else if (in1[i] == in3[k] && in1[i] < in2[j]) {
968:       out[l++] = in1[i];
969:       i++, k++;
970:     } else if (in3[k] == in2[j] && in2[j] < in1[i]) {
971:       out[l++] = in2[j];
972:       k++, j++;
973:     } else if (in1[i] == in2[j] && in1[i] == in3[k]) {
974:       out[l++] = in1[i];
975:       i++, j++, k++;
976:     }
977:   }

979:   /* Traverse two remaining arrays */
980:   while (i < size1 && j < size2) {
981:     if (in1[i] < in2[j]) {
982:       out[l++] = in1[i++];
983:     } else if (in1[i] > in2[j]) {
984:       out[l++] = in2[j++];
985:     } else {
986:       out[l++] = in1[i];
987:       i++, j++;
988:     }
989:   }

991:   while (i < size1 && k < size3) {
992:     if (in1[i] < in3[k]) {
993:       out[l++] = in1[i++];
994:     } else if (in1[i] > in3[k]) {
995:       out[l++] = in3[k++];
996:     } else {
997:       out[l++] = in1[i];
998:       i++, k++;
999:     }
1000:   }

1002:   while (k < size3 && j < size2) {
1003:     if (in3[k] < in2[j]) {
1004:       out[l++] = in3[k++];
1005:     } else if (in3[k] > in2[j]) {
1006:       out[l++] = in2[j++];
1007:     } else {
1008:       out[l++] = in3[k];
1009:       k++, j++;
1010:     }
1011:   }

1013:   /* Traverse one remaining array */
1014:   while (i < size1) out[l++] = in1[i++];
1015:   while (j < size2) out[l++] = in2[j++];
1016:   while (k < size3) out[l++] = in3[k++];

1018:   *size4 = l;
1019: }

1021: /* This matrix-matrix multiplication algorithm divides the multiplication into three multiplications and  */
1022: /* adds up the products. Two of these three multiplications are performed with existing (sequential)      */
1023: /* matrix-matrix multiplications.  */
1024: PetscErrorCode MatMatMultSymbolic_MPIAIJ_MPIAIJ_seqMPI(Mat A, Mat P, PetscReal fill, Mat C)
1025: {
1026:   MPI_Comm             comm;
1027:   PetscMPIInt          size;
1028:   MatProductCtx_APMPI *ptap;
1029:   PetscFreeSpaceList   free_space_diag = NULL, current_space = NULL;
1030:   Mat_MPIAIJ          *a  = (Mat_MPIAIJ *)A->data;
1031:   Mat_SeqAIJ          *ad = (Mat_SeqAIJ *)a->A->data, *ao = (Mat_SeqAIJ *)a->B->data, *p_loc;
1032:   Mat_MPIAIJ          *p = (Mat_MPIAIJ *)P->data;
1033:   Mat_SeqAIJ          *adpd_seq, *p_off, *aopoth_seq;
1034:   PetscInt             adponz, adpdnz;
1035:   PetscInt            *pi_loc, *dnz, *onz;
1036:   PetscInt            *adi = ad->i, *adj = ad->j, *aoi = ao->i, rstart = A->rmap->rstart;
1037:   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;
1038:   PetscInt             am = A->rmap->n, pN = P->cmap->N, pn = P->cmap->n, pm = P->rmap->n, p_colstart, p_colend;
1039:   PetscBT              lnkbt;
1040:   PetscReal            afill;
1041:   PetscMPIInt          rank;
1042:   Mat                  adpd, aopoth;
1043:   MatType              mtype;
1044:   const char          *prefix;

1046:   PetscFunctionBegin;
1047:   MatCheckProduct(C, 4);
1048:   PetscCheck(!C->product->data, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Extra product struct not empty");
1049:   PetscCall(PetscObjectGetComm((PetscObject)A, &comm));
1050:   PetscCallMPI(MPI_Comm_size(comm, &size));
1051:   PetscCallMPI(MPI_Comm_rank(comm, &rank));
1052:   PetscCall(MatGetOwnershipRangeColumn(P, &p_colstart, &p_colend));

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

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

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

1063:   p_loc  = (Mat_SeqAIJ *)ptap->P_loc->data;
1064:   pi_loc = p_loc->i;

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

1070:   adpoi[0]  = 0;
1071:   ptap->api = api;
1072:   api[0]    = 0;

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

1078:   /* Symbolic calc of A_loc_diag * P_loc_diag */
1079:   PetscCall(MatGetOptionsPrefix(A, &prefix));
1080:   PetscCall(MatProductCreate(a->A, p->A, NULL, &adpd));
1081:   PetscCall(MatGetOptionsPrefix(A, &prefix));
1082:   PetscCall(MatSetOptionsPrefix(adpd, prefix));
1083:   PetscCall(MatAppendOptionsPrefix(adpd, "inner_diag_"));

1085:   PetscCall(MatProductSetType(adpd, MATPRODUCT_AB));
1086:   PetscCall(MatProductSetAlgorithm(adpd, "sorted"));
1087:   PetscCall(MatProductSetFill(adpd, fill));
1088:   PetscCall(MatProductSetFromOptions(adpd));

1090:   adpd->force_diagonals = C->force_diagonals;
1091:   PetscCall(MatProductSymbolic(adpd));

1093:   adpd_seq = (Mat_SeqAIJ *)((adpd)->data);
1094:   adpdi    = adpd_seq->i;
1095:   adpdj    = adpd_seq->j;
1096:   p_off    = (Mat_SeqAIJ *)p->B->data;
1097:   poff_i   = p_off->i;
1098:   poff_j   = p_off->j;

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

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

1108:   for (i = 0; i < am; i++) {
1109:     /* A_diag * P_loc_off */
1110:     nzi = adi[i + 1] - adi[i];
1111:     for (j = 0; j < nzi; j++) {
1112:       row  = *adj++;
1113:       pnz  = poff_i[row + 1] - poff_i[row];
1114:       Jptr = poff_j + poff_i[row];
1115:       for (i1 = 0; i1 < pnz; i1++) j_temp[i1] = p->garray[Jptr[i1]];
1116:       /* add non-zero cols of P into the sorted linked list lnk */
1117:       PetscCall(PetscLLCondensedAddSorted(pnz, j_temp, lnk, lnkbt));
1118:     }

1120:     adponz       = lnk[0];
1121:     adpoi[i + 1] = adpoi[i] + adponz;

1123:     /* if free space is not available, double the total space in the list */
1124:     if (current_space->local_remaining < adponz) {
1125:       PetscCall(PetscFreeSpaceGet(PetscIntSumTruncate(adponz, current_space->total_array_size), &current_space));
1126:       nspacedouble++;
1127:     }

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

1132:     current_space->array += adponz;
1133:     current_space->local_used += adponz;
1134:     current_space->local_remaining -= adponz;
1135:   }

1137:   /* Symbolic calc of A_off * P_oth */
1138:   PetscCall(MatSetOptionsPrefix(a->B, prefix));
1139:   PetscCall(MatAppendOptionsPrefix(a->B, "inner_offdiag_"));
1140:   PetscCall(MatCreate(PETSC_COMM_SELF, &aopoth));
1141:   PetscCall(MatMatMultSymbolic_SeqAIJ_SeqAIJ(a->B, ptap->P_oth, fill, aopoth));
1142:   aopoth_seq = (Mat_SeqAIJ *)((aopoth)->data);
1143:   aopothi    = aopoth_seq->i;
1144:   aopothj    = aopoth_seq->j;

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

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

1152:   /* Copy from linked list to j-array */
1153:   PetscCall(PetscFreeSpaceContiguous(&free_space_diag, adpoj));
1154:   PetscCall(PetscLLDestroy(lnk, lnkbt));

1156:   adpoJ = adpoj;
1157:   adpdJ = adpdj;
1158:   aopJ  = aopothj;
1159:   apj   = ptap->apj;
1160:   apJ   = apj; /* still empty */

1162:   /* Merge j-arrays of A_off * P, A_diag * P_loc_off, and */
1163:   /* A_diag * P_loc_diag to get A*P */
1164:   for (i = 0; i < am; i++) {
1165:     aopnz  = aopothi[i + 1] - aopothi[i];
1166:     adponz = adpoi[i + 1] - adpoi[i];
1167:     adpdnz = adpdi[i + 1] - adpdi[i];

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

1175:     aopJ += aopnz;
1176:     adpoJ += adponz;
1177:     adpdJ += adpdnz;
1178:     apJ += apnz;
1179:     api[i + 1] = api[i] + apnz;
1180:   }

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

1185:   /* create and assemble symbolic parallel matrix C */
1186:   PetscCall(MatSetSizes(C, am, pn, PETSC_DETERMINE, PETSC_DETERMINE));
1187:   PetscCall(MatSetBlockSizesFromMats(C, A, P));
1188:   PetscCall(MatGetType(A, &mtype));
1189:   PetscCall(MatSetType(C, mtype));
1190:   PetscCall(MatMPIAIJSetPreallocation(C, 0, dnz, 0, onz));
1191:   MatPreallocateEnd(dnz, onz);

1193:   PetscCall(MatSetValues_MPIAIJ_CopyFromCSRFormat_Symbolic(C, apj, api));
1194:   PetscCall(MatSetOption(C, MAT_NO_OFF_PROC_ENTRIES, PETSC_TRUE));
1195:   PetscCall(MatAssemblyBegin(C, MAT_FINAL_ASSEMBLY));
1196:   PetscCall(MatAssemblyEnd(C, MAT_FINAL_ASSEMBLY));
1197:   PetscCall(MatSetOption(C, MAT_NEW_NONZERO_LOCATION_ERR, PETSC_TRUE));

1199:   C->ops->matmultnumeric = MatMatMultNumeric_MPIAIJ_MPIAIJ_nonscalable;
1200:   C->ops->productnumeric = MatProductNumeric_AB;

1202:   /* attach the supporting struct to C for reuse */
1203:   C->product->data    = ptap;
1204:   C->product->destroy = MatProductCtxDestroy_MPIAIJ_MatMatMult;

1206:   /* set MatInfo */
1207:   afill = (PetscReal)api[am] / (adi[am] + aoi[am] + pi_loc[pm] + 1) + 1.e-5;
1208:   if (afill < 1.0) afill = 1.0;
1209:   C->info.mallocs           = nspacedouble;
1210:   C->info.fill_ratio_given  = fill;
1211:   C->info.fill_ratio_needed = afill;

1213:   if (PetscDefined(USE_INFO)) {
1214:     if (api[am]) {
1215:       PetscCall(PetscInfo(C, "Reallocs %" PetscInt_FMT "; Fill ratio: given %g needed %g.\n", nspacedouble, (double)fill, (double)afill));
1216:       PetscCall(PetscInfo(C, "Use MatMatMult(A,B,MatReuse,%g,&C) for best performance.;\n", (double)afill));
1217:     } else PetscCall(PetscInfo(C, "Empty matrix product\n"));
1218:   }

1220:   PetscCall(MatDestroy(&aopoth));
1221:   PetscCall(MatDestroy(&adpd));
1222:   PetscCall(PetscFree(j_temp));
1223:   PetscCall(PetscFree(adpoj));
1224:   PetscCall(PetscFree(adpoi));
1225:   PetscFunctionReturn(PETSC_SUCCESS);
1226: }

1228: /* This routine only works when scall=MAT_REUSE_MATRIX! */
1229: PetscErrorCode MatTransposeMatMultNumeric_MPIAIJ_MPIAIJ_matmatmult(Mat P, Mat A, Mat C)
1230: {
1231:   MatProductCtx_APMPI *ptap;
1232:   Mat                  Pt;

1234:   PetscFunctionBegin;
1235:   MatCheckProduct(C, 3);
1236:   ptap = (MatProductCtx_APMPI *)C->product->data;
1237:   PetscCheck(ptap, PetscObjectComm((PetscObject)C), PETSC_ERR_ARG_WRONGSTATE, "PtAP cannot be computed. Missing data");
1238:   PetscCheck(ptap->Pt, PetscObjectComm((PetscObject)C), PETSC_ERR_ARG_WRONGSTATE, "PtA cannot be reused. Do not call MatProductClear()");

1240:   Pt = ptap->Pt;
1241:   PetscCall(MatTransposeSetPrecursor(P, Pt));
1242:   PetscCall(MatTranspose(P, MAT_REUSE_MATRIX, &Pt));
1243:   PetscCall(MatMatMultNumeric_MPIAIJ_MPIAIJ(Pt, A, C));
1244:   PetscFunctionReturn(PETSC_SUCCESS);
1245: }

1247: /* This routine is modified from MatPtAPSymbolic_MPIAIJ_MPIAIJ() */
1248: PetscErrorCode MatTransposeMatMultSymbolic_MPIAIJ_MPIAIJ_nonscalable(Mat P, Mat A, PetscReal fill, Mat C)
1249: {
1250:   MatProductCtx_APMPI     *ptap;
1251:   Mat_MPIAIJ              *p = (Mat_MPIAIJ *)P->data;
1252:   MPI_Comm                 comm;
1253:   PetscMPIInt              size, rank;
1254:   PetscFreeSpaceList       free_space = NULL, current_space = NULL;
1255:   PetscInt                 pn = P->cmap->n, aN = A->cmap->N, an = A->cmap->n;
1256:   PetscInt                *lnk, i, k, rstart;
1257:   PetscBT                  lnkbt;
1258:   PetscMPIInt              tagi, tagj, *len_si, *len_s, *len_ri, nrecv, proc, nsend;
1259:   PETSC_UNUSED PetscMPIInt icompleted = 0;
1260:   PetscInt               **buf_rj, **buf_ri, **buf_ri_k, row, ncols, *cols;
1261:   PetscInt                 len, *dnz, *onz, *owners, nzi;
1262:   PetscInt                 nrows, *buf_s, *buf_si, *buf_si_i, **nextrow, **nextci;
1263:   MPI_Request             *swaits, *rwaits;
1264:   MPI_Status              *sstatus, rstatus;
1265:   PetscLayout              rowmap;
1266:   PetscInt                *owners_co, *coi, *coj; /* i and j array of (p->B)^T*A*P - used in the communication */
1267:   PetscMPIInt             *len_r, *id_r;          /* array of length of comm->size, store send/recv matrix values */
1268:   PetscInt                *Jptr, *prmap = p->garray, con, j, Crmax;
1269:   Mat_SeqAIJ              *a_loc, *c_loc, *c_oth;
1270:   PetscHMapI               ta;
1271:   MatType                  mtype;
1272:   const char              *prefix;

1274:   PetscFunctionBegin;
1275:   PetscCall(PetscObjectGetComm((PetscObject)A, &comm));
1276:   PetscCallMPI(MPI_Comm_size(comm, &size));
1277:   PetscCallMPI(MPI_Comm_rank(comm, &rank));

1279:   /* create symbolic parallel matrix C */
1280:   PetscCall(MatGetType(A, &mtype));
1281:   PetscCall(MatSetType(C, mtype));

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

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

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

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

1295:   /* (2-1) compute symbolic C_oth = Ro*A_loc  */
1296:   PetscCall(MatGetOptionsPrefix(A, &prefix));
1297:   PetscCall(MatSetOptionsPrefix(ptap->Ro, prefix));
1298:   PetscCall(MatAppendOptionsPrefix(ptap->Ro, "inner_offdiag_"));
1299:   PetscCall(MatCreate(PETSC_COMM_SELF, &ptap->C_oth));
1300:   PetscCall(MatMatMultSymbolic_SeqAIJ_SeqAIJ(ptap->Ro, ptap->A_loc, fill, ptap->C_oth));

1302:   /* (3) send coj of C_oth to other processors  */
1303:   /* determine row ownership */
1304:   PetscCall(PetscLayoutCreate(comm, &rowmap));
1305:   rowmap->n  = pn;
1306:   rowmap->bs = 1;
1307:   PetscCall(PetscLayoutSetUp(rowmap));
1308:   owners = rowmap->range;

1310:   /* determine the number of messages to send, their lengths */
1311:   PetscCall(PetscMalloc4(size, &len_s, size, &len_si, size, &sstatus, size + 1, &owners_co));
1312:   PetscCall(PetscArrayzero(len_s, size));
1313:   PetscCall(PetscArrayzero(len_si, size));

1315:   c_oth = (Mat_SeqAIJ *)ptap->C_oth->data;
1316:   coi   = c_oth->i;
1317:   coj   = c_oth->j;
1318:   con   = ptap->C_oth->rmap->n;
1319:   proc  = 0;
1320:   for (i = 0; i < con; i++) {
1321:     while (prmap[i] >= owners[proc + 1]) proc++;
1322:     len_si[proc]++;                     /* num of rows in Co(=Pt*A) to be sent to [proc] */
1323:     len_s[proc] += coi[i + 1] - coi[i]; /* num of nonzeros in Co to be sent to [proc] */
1324:   }

1326:   len          = 0; /* max length of buf_si[], see (4) */
1327:   owners_co[0] = 0;
1328:   nsend        = 0;
1329:   for (proc = 0; proc < size; proc++) {
1330:     owners_co[proc + 1] = owners_co[proc] + len_si[proc];
1331:     if (len_s[proc]) {
1332:       nsend++;
1333:       len_si[proc] = 2 * (len_si[proc] + 1); /* length of buf_si to be sent to [proc] */
1334:       len += len_si[proc];
1335:     }
1336:   }

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

1342:   /* post the Irecv and Isend of coj */
1343:   PetscCall(PetscCommGetNewTag(comm, &tagj));
1344:   PetscCall(PetscPostIrecvInt(comm, tagj, nrecv, id_r, len_r, &buf_rj, &rwaits));
1345:   PetscCall(PetscMalloc1(nsend, &swaits));
1346:   for (proc = 0, k = 0; proc < size; proc++) {
1347:     if (!len_s[proc]) continue;
1348:     i = owners_co[proc];
1349:     PetscCallMPI(MPIU_Isend(coj + coi[i], len_s[proc], MPIU_INT, proc, tagj, comm, swaits + k));
1350:     k++;
1351:   }

1353:   /* (2-2) compute symbolic C_loc = Rd*A_loc */
1354:   PetscCall(MatSetOptionsPrefix(ptap->Rd, prefix));
1355:   PetscCall(MatAppendOptionsPrefix(ptap->Rd, "inner_diag_"));
1356:   PetscCall(MatCreate(PETSC_COMM_SELF, &ptap->C_loc));
1357:   PetscCall(MatMatMultSymbolic_SeqAIJ_SeqAIJ(ptap->Rd, ptap->A_loc, fill, ptap->C_loc));
1358:   c_loc = (Mat_SeqAIJ *)ptap->C_loc->data;

1360:   /* receives coj are complete */
1361:   for (i = 0; i < nrecv; i++) PetscCallMPI(MPI_Waitany(nrecv, rwaits, &icompleted, &rstatus));
1362:   PetscCall(PetscFree(rwaits));
1363:   if (nsend) PetscCallMPI(MPI_Waitall(nsend, swaits, sstatus));

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

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

1372:   for (k = 0; k < nrecv; k++) { /* k-th received message */
1373:     Jptr = buf_rj[k];
1374:     for (j = 0; j < len_r[k]; j++) PetscCall(PetscHMapISet(ta, *(Jptr + j) + 1, 1));
1375:   }
1376:   PetscCall(PetscHMapIGetSize(ta, &Crmax));
1377:   PetscCall(PetscHMapIDestroy(&ta));

1379:   /* (4) send and recv coi */
1380:   PetscCall(PetscCommGetNewTag(comm, &tagi));
1381:   PetscCall(PetscPostIrecvInt(comm, tagi, nrecv, id_r, len_ri, &buf_ri, &rwaits));
1382:   PetscCall(PetscMalloc1(len, &buf_s));
1383:   buf_si = buf_s; /* points to the beginning of k-th msg to be sent */
1384:   for (proc = 0, k = 0; proc < size; proc++) {
1385:     if (!len_s[proc]) continue;
1386:     /* form outgoing message for i-structure:
1387:          buf_si[0]:                 nrows to be sent
1388:                [1:nrows]:           row index (global)
1389:                [nrows+1:2*nrows+1]: i-structure index
1390:     */
1391:     nrows       = len_si[proc] / 2 - 1; /* num of rows in Co to be sent to [proc] */
1392:     buf_si_i    = buf_si + nrows + 1;
1393:     buf_si[0]   = nrows;
1394:     buf_si_i[0] = 0;
1395:     nrows       = 0;
1396:     for (i = owners_co[proc]; i < owners_co[proc + 1]; i++) {
1397:       nzi                 = coi[i + 1] - coi[i];
1398:       buf_si_i[nrows + 1] = buf_si_i[nrows] + nzi;   /* i-structure */
1399:       buf_si[nrows + 1]   = prmap[i] - owners[proc]; /* local row index */
1400:       nrows++;
1401:     }
1402:     PetscCallMPI(MPIU_Isend(buf_si, len_si[proc], MPIU_INT, proc, tagi, comm, swaits + k));
1403:     k++;
1404:     buf_si += len_si[proc];
1405:   }
1406:   for (i = 0; i < nrecv; i++) PetscCallMPI(MPI_Waitany(nrecv, rwaits, &icompleted, &rstatus));
1407:   PetscCall(PetscFree(rwaits));
1408:   if (nsend) PetscCallMPI(MPI_Waitall(nsend, swaits, sstatus));

1410:   PetscCall(PetscFree4(len_s, len_si, sstatus, owners_co));
1411:   PetscCall(PetscFree(len_ri));
1412:   PetscCall(PetscFree(swaits));
1413:   PetscCall(PetscFree(buf_s));

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

1420:   PetscCall(PetscMalloc3(nrecv, &buf_ri_k, nrecv, &nextrow, nrecv, &nextci));
1421:   for (k = 0; k < nrecv; k++) {
1422:     buf_ri_k[k] = buf_ri[k]; /* beginning of k-th recved i-structure */
1423:     nrows       = *buf_ri_k[k];
1424:     nextrow[k]  = buf_ri_k[k] + 1;           /* next row number of k-th recved i-structure */
1425:     nextci[k]   = buf_ri_k[k] + (nrows + 1); /* points to the next i-structure of k-th recved i-structure  */
1426:   }

1428:   MatPreallocateBegin(comm, pn, an, dnz, onz);
1429:   PetscCall(PetscLLCondensedCreate(Crmax, aN, &lnk, &lnkbt));
1430:   for (i = 0; i < pn; i++) { /* for each local row of C */
1431:     /* add C_loc into C */
1432:     nzi  = c_loc->i[i + 1] - c_loc->i[i];
1433:     Jptr = c_loc->j + c_loc->i[i];
1434:     PetscCall(PetscLLCondensedAddSorted(nzi, Jptr, lnk, lnkbt));

1436:     /* add received col data into lnk */
1437:     for (k = 0; k < nrecv; k++) { /* k-th received message */
1438:       if (i == *nextrow[k]) {     /* i-th row */
1439:         nzi  = *(nextci[k] + 1) - *nextci[k];
1440:         Jptr = buf_rj[k] + *nextci[k];
1441:         PetscCall(PetscLLCondensedAddSorted(nzi, Jptr, lnk, lnkbt));
1442:         nextrow[k]++;
1443:         nextci[k]++;
1444:       }
1445:     }

1447:     /* add missing diagonal entry */
1448:     if (C->force_diagonals) {
1449:       k = i + owners[rank]; /* column index */
1450:       PetscCall(PetscLLCondensedAddSorted(1, &k, lnk, lnkbt));
1451:     }

1453:     nzi = lnk[0];

1455:     /* copy data into free space, then initialize lnk */
1456:     PetscCall(PetscLLCondensedClean(aN, nzi, current_space->array, lnk, lnkbt));
1457:     PetscCall(MatPreallocateSet(i + owners[rank], nzi, current_space->array, dnz, onz));
1458:   }
1459:   PetscCall(PetscFree3(buf_ri_k, nextrow, nextci));
1460:   PetscCall(PetscLLDestroy(lnk, lnkbt));
1461:   PetscCall(PetscFreeSpaceDestroy(free_space));

1463:   /* local sizes and preallocation */
1464:   PetscCall(MatSetSizes(C, pn, an, PETSC_DETERMINE, PETSC_DETERMINE));
1465:   PetscCall(PetscLayoutSetBlockSize(C->rmap, P->cmap->bs));
1466:   PetscCall(PetscLayoutSetBlockSize(C->cmap, A->cmap->bs));
1467:   PetscCall(MatMPIAIJSetPreallocation(C, 0, dnz, 0, onz));
1468:   MatPreallocateEnd(dnz, onz);

1470:   /* add C_loc and C_oth to C */
1471:   PetscCall(MatGetOwnershipRange(C, &rstart, NULL));
1472:   for (i = 0; i < pn; i++) {
1473:     ncols = c_loc->i[i + 1] - c_loc->i[i];
1474:     cols  = c_loc->j + c_loc->i[i];
1475:     row   = rstart + i;
1476:     PetscCall(MatSetValues(C, 1, (const PetscInt *)&row, ncols, (const PetscInt *)cols, NULL, INSERT_VALUES));

1478:     if (C->force_diagonals) PetscCall(MatSetValues(C, 1, (const PetscInt *)&row, 1, (const PetscInt *)&row, NULL, INSERT_VALUES));
1479:   }
1480:   for (i = 0; i < con; i++) {
1481:     ncols = c_oth->i[i + 1] - c_oth->i[i];
1482:     cols  = c_oth->j + c_oth->i[i];
1483:     row   = prmap[i];
1484:     PetscCall(MatSetValues(C, 1, (const PetscInt *)&row, ncols, (const PetscInt *)cols, NULL, INSERT_VALUES));
1485:   }
1486:   PetscCall(MatAssemblyBegin(C, MAT_FINAL_ASSEMBLY));
1487:   PetscCall(MatAssemblyEnd(C, MAT_FINAL_ASSEMBLY));
1488:   PetscCall(MatSetOption(C, MAT_NEW_NONZERO_LOCATION_ERR, PETSC_TRUE));

1490:   /* members in merge */
1491:   PetscCall(PetscFree(id_r));
1492:   PetscCall(PetscFree(len_r));
1493:   PetscCall(PetscFree(buf_ri[0]));
1494:   PetscCall(PetscFree(buf_ri));
1495:   PetscCall(PetscFree(buf_rj[0]));
1496:   PetscCall(PetscFree(buf_rj));
1497:   PetscCall(PetscLayoutDestroy(&rowmap));

1499:   /* attach the supporting struct to C for reuse */
1500:   C->product->data    = ptap;
1501:   C->product->destroy = MatProductCtxDestroy_MPIAIJ_PtAP;
1502:   PetscFunctionReturn(PETSC_SUCCESS);
1503: }

1505: PetscErrorCode MatTransposeMatMultNumeric_MPIAIJ_MPIAIJ_nonscalable(Mat P, Mat A, Mat C)
1506: {
1507:   Mat_MPIAIJ          *p = (Mat_MPIAIJ *)P->data;
1508:   Mat_SeqAIJ          *c_seq;
1509:   MatProductCtx_APMPI *ptap;
1510:   Mat                  A_loc, C_loc, C_oth;
1511:   PetscInt             i, rstart, rend, cm, ncols, row;
1512:   const PetscInt      *cols;
1513:   const PetscScalar   *vals;

1515:   PetscFunctionBegin;
1516:   MatCheckProduct(C, 3);
1517:   ptap = (MatProductCtx_APMPI *)C->product->data;
1518:   PetscCheck(ptap, PetscObjectComm((PetscObject)C), PETSC_ERR_ARG_WRONGSTATE, "PtAP cannot be computed. Missing data");
1519:   PetscCheck(ptap->A_loc, PetscObjectComm((PetscObject)C), PETSC_ERR_ARG_WRONGSTATE, "PtA cannot be reused. Do not call MatProductClear()");
1520:   PetscCall(MatZeroEntries(C));

1522:   /* These matrices are obtained in MatTransposeMatMultSymbolic() */
1523:   /* 1) get R = Pd^T, Ro = Po^T */
1524:   PetscCall(MatTransposeSetPrecursor(p->A, ptap->Rd));
1525:   PetscCall(MatTranspose(p->A, MAT_REUSE_MATRIX, &ptap->Rd));
1526:   PetscCall(MatTransposeSetPrecursor(p->B, ptap->Ro));
1527:   PetscCall(MatTranspose(p->B, MAT_REUSE_MATRIX, &ptap->Ro));

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

1532:   /* 3) C_loc = Rd*A_loc, C_oth = Ro*A_loc */
1533:   A_loc = ptap->A_loc;
1534:   PetscCall(ptap->C_loc->ops->matmultnumeric(ptap->Rd, A_loc, ptap->C_loc));
1535:   PetscCall(ptap->C_oth->ops->matmultnumeric(ptap->Ro, A_loc, ptap->C_oth));
1536:   C_loc = ptap->C_loc;
1537:   C_oth = ptap->C_oth;

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

1542:   /* C_loc -> C */
1543:   cm    = C_loc->rmap->N;
1544:   c_seq = (Mat_SeqAIJ *)C_loc->data;
1545:   cols  = c_seq->j;
1546:   vals  = c_seq->a;
1547:   for (i = 0; i < cm; i++) {
1548:     ncols = c_seq->i[i + 1] - c_seq->i[i];
1549:     row   = rstart + i;
1550:     PetscCall(MatSetValues(C, 1, &row, ncols, cols, vals, ADD_VALUES));
1551:     cols += ncols;
1552:     vals += ncols;
1553:   }

1555:   /* Co -> C, off-processor part */
1556:   cm    = C_oth->rmap->N;
1557:   c_seq = (Mat_SeqAIJ *)C_oth->data;
1558:   cols  = c_seq->j;
1559:   vals  = c_seq->a;
1560:   for (i = 0; i < cm; i++) {
1561:     ncols = c_seq->i[i + 1] - c_seq->i[i];
1562:     row   = p->garray[i];
1563:     PetscCall(MatSetValues(C, 1, &row, ncols, cols, vals, ADD_VALUES));
1564:     cols += ncols;
1565:     vals += ncols;
1566:   }
1567:   PetscCall(MatAssemblyBegin(C, MAT_FINAL_ASSEMBLY));
1568:   PetscCall(MatAssemblyEnd(C, MAT_FINAL_ASSEMBLY));
1569:   PetscCall(MatSetOption(C, MAT_NEW_NONZERO_LOCATION_ERR, PETSC_TRUE));
1570:   PetscFunctionReturn(PETSC_SUCCESS);
1571: }

1573: PetscErrorCode MatTransposeMatMultNumeric_MPIAIJ_MPIAIJ(Mat P, Mat A, Mat C)
1574: {
1575:   MatMergeSeqsToMPI   *merge;
1576:   Mat_MPIAIJ          *p  = (Mat_MPIAIJ *)P->data;
1577:   Mat_SeqAIJ          *pd = (Mat_SeqAIJ *)p->A->data, *po = (Mat_SeqAIJ *)p->B->data;
1578:   MatProductCtx_APMPI *ap;
1579:   PetscInt            *adj;
1580:   PetscInt             i, j, k, anz, pnz, row, *cj, nexta;
1581:   MatScalar           *ada, *ca, valtmp;
1582:   PetscInt             am = A->rmap->n, cm = C->rmap->n, pon = (p->B)->cmap->n;
1583:   MPI_Comm             comm;
1584:   PetscMPIInt          size, rank, taga, *len_s, proc;
1585:   PetscInt            *owners, nrows, **buf_ri_k, **nextrow, **nextci;
1586:   PetscInt           **buf_ri, **buf_rj;
1587:   PetscInt             cnz = 0, *bj_i, *bi, *bj, bnz, nextcj; /* bi,bj,ba: local array of C(mpi mat) */
1588:   MPI_Request         *s_waits, *r_waits;
1589:   MPI_Status          *status;
1590:   MatScalar          **abuf_r, *ba_i, *pA, *coa, *ba;
1591:   const PetscScalar   *dummy;
1592:   PetscInt            *ai, *aj, *coi, *coj, *poJ, *pdJ;
1593:   Mat                  A_loc;
1594:   Mat_SeqAIJ          *a_loc;

1596:   PetscFunctionBegin;
1597:   MatCheckProduct(C, 3);
1598:   ap = (MatProductCtx_APMPI *)C->product->data;
1599:   PetscCheck(ap, PetscObjectComm((PetscObject)C), PETSC_ERR_ARG_WRONGSTATE, "PtA cannot be computed. Missing data");
1600:   PetscCheck(ap->A_loc, PetscObjectComm((PetscObject)C), PETSC_ERR_ARG_WRONGSTATE, "PtA cannot be reused. Do not call MatProductClear()");
1601:   PetscCall(PetscObjectGetComm((PetscObject)C, &comm));
1602:   PetscCallMPI(MPI_Comm_size(comm, &size));
1603:   PetscCallMPI(MPI_Comm_rank(comm, &rank));

1605:   merge = ap->merge;

1607:   /* 2) compute numeric C_seq = P_loc^T*A_loc */
1608:   /* get data from symbolic products */
1609:   coi = merge->coi;
1610:   coj = merge->coj;
1611:   PetscCall(PetscCalloc1(coi[pon], &coa));
1612:   bi     = merge->bi;
1613:   bj     = merge->bj;
1614:   owners = merge->rowmap->range;
1615:   PetscCall(PetscCalloc1(bi[cm], &ba));

1617:   /* get A_loc by taking all local rows of A */
1618:   A_loc = ap->A_loc;
1619:   PetscCall(MatMPIAIJGetLocalMat(A, MAT_REUSE_MATRIX, &A_loc));
1620:   a_loc = (Mat_SeqAIJ *)A_loc->data;
1621:   ai    = a_loc->i;
1622:   aj    = a_loc->j;

1624:   /* trigger copy to CPU */
1625:   PetscCall(MatSeqAIJGetArrayRead(p->A, &dummy));
1626:   PetscCall(MatSeqAIJRestoreArrayRead(p->A, &dummy));
1627:   PetscCall(MatSeqAIJGetArrayRead(p->B, &dummy));
1628:   PetscCall(MatSeqAIJRestoreArrayRead(p->B, &dummy));
1629:   for (i = 0; i < am; i++) {
1630:     anz = ai[i + 1] - ai[i];
1631:     adj = aj + ai[i];
1632:     ada = a_loc->a + ai[i];

1634:     /* 2-b) Compute Cseq = P_loc[i,:]^T*A[i,:] using outer product */
1635:     /* put the value into Co=(p->B)^T*A (off-diagonal part, send to others) */
1636:     pnz = po->i[i + 1] - po->i[i];
1637:     poJ = po->j + po->i[i];
1638:     pA  = po->a + po->i[i];
1639:     for (j = 0; j < pnz; j++) {
1640:       row = poJ[j];
1641:       cj  = coj + coi[row];
1642:       ca  = coa + coi[row];
1643:       /* perform sparse axpy */
1644:       nexta  = 0;
1645:       valtmp = pA[j];
1646:       for (k = 0; nexta < anz; k++) {
1647:         if (cj[k] == adj[nexta]) {
1648:           ca[k] += valtmp * ada[nexta];
1649:           nexta++;
1650:         }
1651:       }
1652:       PetscCall(PetscLogFlops(2.0 * anz));
1653:     }

1655:     /* put the value into Cd (diagonal part) */
1656:     pnz = pd->i[i + 1] - pd->i[i];
1657:     pdJ = pd->j + pd->i[i];
1658:     pA  = pd->a + pd->i[i];
1659:     for (j = 0; j < pnz; j++) {
1660:       row = pdJ[j];
1661:       cj  = bj + bi[row];
1662:       ca  = ba + bi[row];
1663:       /* perform sparse axpy */
1664:       nexta  = 0;
1665:       valtmp = pA[j];
1666:       for (k = 0; nexta < anz; k++) {
1667:         if (cj[k] == adj[nexta]) {
1668:           ca[k] += valtmp * ada[nexta];
1669:           nexta++;
1670:         }
1671:       }
1672:       PetscCall(PetscLogFlops(2.0 * anz));
1673:     }
1674:   }

1676:   /* 3) send and recv matrix values coa */
1677:   buf_ri = merge->buf_ri;
1678:   buf_rj = merge->buf_rj;
1679:   len_s  = merge->len_s;
1680:   PetscCall(PetscCommGetNewTag(comm, &taga));
1681:   PetscCall(PetscPostIrecvScalar(comm, taga, merge->nrecv, merge->id_r, merge->len_r, &abuf_r, &r_waits));

1683:   PetscCall(PetscMalloc2(merge->nsend, &s_waits, size, &status));
1684:   for (proc = 0, k = 0; proc < size; proc++) {
1685:     if (!len_s[proc]) continue;
1686:     i = merge->owners_co[proc];
1687:     PetscCallMPI(MPIU_Isend(coa + coi[i], len_s[proc], MPIU_MATSCALAR, proc, taga, comm, s_waits + k));
1688:     k++;
1689:   }
1690:   if (merge->nrecv) PetscCallMPI(MPI_Waitall(merge->nrecv, r_waits, status));
1691:   if (merge->nsend) PetscCallMPI(MPI_Waitall(merge->nsend, s_waits, status));

1693:   PetscCall(PetscFree2(s_waits, status));
1694:   PetscCall(PetscFree(r_waits));
1695:   PetscCall(PetscFree(coa));

1697:   /* 4) insert local Cseq and received values into Cmpi */
1698:   PetscCall(PetscMalloc3(merge->nrecv, &buf_ri_k, merge->nrecv, &nextrow, merge->nrecv, &nextci));
1699:   for (k = 0; k < merge->nrecv; k++) {
1700:     buf_ri_k[k] = buf_ri[k]; /* beginning of k-th recved i-structure */
1701:     nrows       = *buf_ri_k[k];
1702:     nextrow[k]  = buf_ri_k[k] + 1;           /* next row number of k-th recved i-structure */
1703:     nextci[k]   = buf_ri_k[k] + (nrows + 1); /* points to the next i-structure of k-th recved i-structure  */
1704:   }

1706:   for (i = 0; i < cm; i++) {
1707:     row  = owners[rank] + i; /* global row index of C_seq */
1708:     bj_i = bj + bi[i];       /* col indices of the i-th row of C */
1709:     ba_i = ba + bi[i];
1710:     bnz  = bi[i + 1] - bi[i];
1711:     /* add received vals into ba */
1712:     for (k = 0; k < merge->nrecv; k++) { /* k-th received message */
1713:       /* i-th row */
1714:       if (i == *nextrow[k]) {
1715:         cnz    = *(nextci[k] + 1) - *nextci[k];
1716:         cj     = buf_rj[k] + *nextci[k];
1717:         ca     = abuf_r[k] + *nextci[k];
1718:         nextcj = 0;
1719:         for (j = 0; nextcj < cnz; j++) {
1720:           if (bj_i[j] == cj[nextcj]) { /* bcol == ccol */
1721:             ba_i[j] += ca[nextcj++];
1722:           }
1723:         }
1724:         nextrow[k]++;
1725:         nextci[k]++;
1726:         PetscCall(PetscLogFlops(2.0 * cnz));
1727:       }
1728:     }
1729:     PetscCall(MatSetValues(C, 1, &row, bnz, bj_i, ba_i, INSERT_VALUES));
1730:   }
1731:   PetscCall(MatAssemblyBegin(C, MAT_FINAL_ASSEMBLY));
1732:   PetscCall(MatAssemblyEnd(C, MAT_FINAL_ASSEMBLY));

1734:   PetscCall(PetscFree(ba));
1735:   PetscCall(PetscFree(abuf_r[0]));
1736:   PetscCall(PetscFree(abuf_r));
1737:   PetscCall(PetscFree3(buf_ri_k, nextrow, nextci));
1738:   PetscFunctionReturn(PETSC_SUCCESS);
1739: }

1741: PetscErrorCode MatTransposeMatMultSymbolic_MPIAIJ_MPIAIJ(Mat P, Mat A, PetscReal fill, Mat C)
1742: {
1743:   Mat                  A_loc;
1744:   MatProductCtx_APMPI *ap;
1745:   PetscFreeSpaceList   free_space = NULL, current_space = NULL;
1746:   Mat_MPIAIJ          *p = (Mat_MPIAIJ *)P->data, *a = (Mat_MPIAIJ *)A->data;
1747:   PetscInt            *pdti, *pdtj, *poti, *potj, *ptJ;
1748:   PetscInt             nnz;
1749:   PetscInt            *lnk, *owners_co, *coi, *coj, i, k, pnz, row;
1750:   PetscInt             am = A->rmap->n, pn = P->cmap->n;
1751:   MPI_Comm             comm;
1752:   PetscMPIInt          size, rank, tagi, tagj, *len_si, *len_s, *len_ri, proc;
1753:   PetscInt           **buf_rj, **buf_ri, **buf_ri_k;
1754:   PetscInt             len, *dnz, *onz, *owners;
1755:   PetscInt             nzi, *bi, *bj;
1756:   PetscInt             nrows, *buf_s, *buf_si, *buf_si_i, **nextrow, **nextci;
1757:   MPI_Request         *swaits, *rwaits;
1758:   MPI_Status          *sstatus, rstatus;
1759:   MatMergeSeqsToMPI   *merge;
1760:   PetscInt            *ai, *aj, *Jptr, anz, *prmap = p->garray, pon, nspacedouble = 0, j;
1761:   PetscReal            afill  = 1.0, afill_tmp;
1762:   PetscInt             rstart = P->cmap->rstart, rmax, Armax;
1763:   Mat_SeqAIJ          *a_loc;
1764:   PetscHMapI           ta;
1765:   MatType              mtype;

1767:   PetscFunctionBegin;
1768:   PetscCall(PetscObjectGetComm((PetscObject)A, &comm));
1769:   /* check if matrix local sizes are compatible */
1770:   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,
1771:              A->rmap->rend, P->rmap->rstart, P->rmap->rend);

1773:   PetscCallMPI(MPI_Comm_size(comm, &size));
1774:   PetscCallMPI(MPI_Comm_rank(comm, &rank));

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

1779:   /* get A_loc by taking all local rows of A */
1780:   PetscCall(MatMPIAIJGetLocalMat(A, MAT_INITIAL_MATRIX, &A_loc));

1782:   ap->A_loc = A_loc;
1783:   a_loc     = (Mat_SeqAIJ *)A_loc->data;
1784:   ai        = a_loc->i;
1785:   aj        = a_loc->j;

1787:   /* determine symbolic Co=(p->B)^T*A - send to others */
1788:   PetscCall(MatGetSymbolicTranspose_SeqAIJ(p->A, &pdti, &pdtj));
1789:   PetscCall(MatGetSymbolicTranspose_SeqAIJ(p->B, &poti, &potj));
1790:   pon = (p->B)->cmap->n; /* total num of rows to be sent to other processors
1791:                          >= (num of nonzero rows of C_seq) - pn */
1792:   PetscCall(PetscMalloc1(pon + 1, &coi));
1793:   coi[0] = 0;

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

1800:   /* create and initialize a linked list */
1801:   PetscCall(PetscHMapICreateWithSize(A->cmap->n + a->B->cmap->N, &ta));
1802:   MatRowMergeMax_SeqAIJ(a_loc, am, ta);
1803:   PetscCall(PetscHMapIGetSize(ta, &Armax));

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

1807:   for (i = 0; i < pon; i++) {
1808:     pnz = poti[i + 1] - poti[i];
1809:     ptJ = potj + poti[i];
1810:     for (j = 0; j < pnz; j++) {
1811:       row  = ptJ[j]; /* row of A_loc == col of Pot */
1812:       anz  = ai[row + 1] - ai[row];
1813:       Jptr = aj + ai[row];
1814:       /* add non-zero cols of AP into the sorted linked list lnk */
1815:       PetscCall(PetscLLCondensedAddSorted_Scalable(anz, Jptr, lnk));
1816:     }
1817:     nnz = lnk[0];

1819:     /* If free space is not available, double the total space in the list */
1820:     if (current_space->local_remaining < nnz) {
1821:       PetscCall(PetscFreeSpaceGet(PetscIntSumTruncate(nnz, current_space->total_array_size), &current_space));
1822:       nspacedouble++;
1823:     }

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

1828:     current_space->array += nnz;
1829:     current_space->local_used += nnz;
1830:     current_space->local_remaining -= nnz;

1832:     coi[i + 1] = coi[i] + nnz;
1833:   }

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

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

1842:   /* send j-array (coj) of Co to other processors */
1843:   /* determine row ownership */
1844:   PetscCall(PetscNew(&merge));
1845:   PetscCall(PetscLayoutCreate(comm, &merge->rowmap));

1847:   merge->rowmap->n  = pn;
1848:   merge->rowmap->bs = 1;

1850:   PetscCall(PetscLayoutSetUp(merge->rowmap));
1851:   owners = merge->rowmap->range;

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

1857:   len_s        = merge->len_s;
1858:   merge->nsend = 0;

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

1862:   proc = 0;
1863:   for (i = 0; i < pon; i++) {
1864:     while (prmap[i] >= owners[proc + 1]) proc++;
1865:     len_si[proc]++; /* num of rows in Co to be sent to [proc] */
1866:     len_s[proc] += coi[i + 1] - coi[i];
1867:   }

1869:   len          = 0; /* max length of buf_si[] */
1870:   owners_co[0] = 0;
1871:   for (proc = 0; proc < size; proc++) {
1872:     owners_co[proc + 1] = owners_co[proc] + len_si[proc];
1873:     if (len_s[proc]) {
1874:       merge->nsend++;
1875:       len_si[proc] = 2 * (len_si[proc] + 1);
1876:       len += len_si[proc];
1877:     }
1878:   }

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

1884:   /* post the Irecv and Isend of coj */
1885:   PetscCall(PetscCommGetNewTag(comm, &tagj));
1886:   PetscCall(PetscPostIrecvInt(comm, tagj, merge->nrecv, merge->id_r, merge->len_r, &buf_rj, &rwaits));
1887:   PetscCall(PetscMalloc1(merge->nsend, &swaits));
1888:   for (proc = 0, k = 0; proc < size; proc++) {
1889:     if (!len_s[proc]) continue;
1890:     i = owners_co[proc];
1891:     PetscCallMPI(MPIU_Isend(coj + coi[i], len_s[proc], MPIU_INT, proc, tagj, comm, swaits + k));
1892:     k++;
1893:   }

1895:   /* receives and sends of coj are complete */
1896:   PetscCall(PetscMalloc1(size, &sstatus));
1897:   for (i = 0; i < merge->nrecv; i++) {
1898:     PETSC_UNUSED PetscMPIInt icompleted;
1899:     PetscCallMPI(MPI_Waitany(merge->nrecv, rwaits, &icompleted, &rstatus));
1900:   }
1901:   PetscCall(PetscFree(rwaits));
1902:   if (merge->nsend) PetscCallMPI(MPI_Waitall(merge->nsend, swaits, sstatus));

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

1912:   /* send and recv coi */
1913:   PetscCall(PetscCommGetNewTag(comm, &tagi));
1914:   PetscCall(PetscPostIrecvInt(comm, tagi, merge->nrecv, merge->id_r, len_ri, &buf_ri, &rwaits));
1915:   PetscCall(PetscMalloc1(len, &buf_s));
1916:   buf_si = buf_s; /* points to the beginning of k-th msg to be sent */
1917:   for (proc = 0, k = 0; proc < size; proc++) {
1918:     if (!len_s[proc]) continue;
1919:     /* form outgoing message for i-structure:
1920:          buf_si[0]:                 nrows to be sent
1921:                [1:nrows]:           row index (global)
1922:                [nrows+1:2*nrows+1]: i-structure index
1923:     */
1924:     nrows       = len_si[proc] / 2 - 1;
1925:     buf_si_i    = buf_si + nrows + 1;
1926:     buf_si[0]   = nrows;
1927:     buf_si_i[0] = 0;
1928:     nrows       = 0;
1929:     for (i = owners_co[proc]; i < owners_co[proc + 1]; i++) {
1930:       nzi                 = coi[i + 1] - coi[i];
1931:       buf_si_i[nrows + 1] = buf_si_i[nrows] + nzi;   /* i-structure */
1932:       buf_si[nrows + 1]   = prmap[i] - owners[proc]; /* local row index */
1933:       nrows++;
1934:     }
1935:     PetscCallMPI(MPIU_Isend(buf_si, len_si[proc], MPIU_INT, proc, tagi, comm, swaits + k));
1936:     k++;
1937:     buf_si += len_si[proc];
1938:   }
1939:   i = merge->nrecv;
1940:   while (i--) {
1941:     PETSC_UNUSED PetscMPIInt icompleted;
1942:     PetscCallMPI(MPI_Waitany(merge->nrecv, rwaits, &icompleted, &rstatus));
1943:   }
1944:   PetscCall(PetscFree(rwaits));
1945:   if (merge->nsend) PetscCallMPI(MPI_Waitall(merge->nsend, swaits, sstatus));
1946:   PetscCall(PetscFree(len_si));
1947:   PetscCall(PetscFree(len_ri));
1948:   PetscCall(PetscFree(swaits));
1949:   PetscCall(PetscFree(sstatus));
1950:   PetscCall(PetscFree(buf_s));

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

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

1962:   PetscCall(PetscMalloc3(merge->nrecv, &buf_ri_k, merge->nrecv, &nextrow, merge->nrecv, &nextci));
1963:   for (k = 0; k < merge->nrecv; k++) {
1964:     buf_ri_k[k] = buf_ri[k]; /* beginning of k-th recved i-structure */
1965:     nrows       = *buf_ri_k[k];
1966:     nextrow[k]  = buf_ri_k[k] + 1;           /* next row number of k-th recved i-structure */
1967:     nextci[k]   = buf_ri_k[k] + (nrows + 1); /* points to the next i-structure of k-th received i-structure  */
1968:   }

1970:   PetscCall(PetscLLCondensedCreate_Scalable(Armax, &lnk));
1971:   MatPreallocateBegin(comm, pn, A->cmap->n, dnz, onz);
1972:   rmax = 0;
1973:   for (i = 0; i < pn; i++) {
1974:     /* add pdt[i,:]*AP into lnk */
1975:     pnz = pdti[i + 1] - pdti[i];
1976:     ptJ = pdtj + pdti[i];
1977:     for (j = 0; j < pnz; j++) {
1978:       row  = ptJ[j]; /* row of AP == col of Pt */
1979:       anz  = ai[row + 1] - ai[row];
1980:       Jptr = aj + ai[row];
1981:       /* add non-zero cols of AP into the sorted linked list lnk */
1982:       PetscCall(PetscLLCondensedAddSorted_Scalable(anz, Jptr, lnk));
1983:     }

1985:     /* add received col data into lnk */
1986:     for (k = 0; k < merge->nrecv; k++) { /* k-th received message */
1987:       if (i == *nextrow[k]) {            /* i-th row */
1988:         nzi  = *(nextci[k] + 1) - *nextci[k];
1989:         Jptr = buf_rj[k] + *nextci[k];
1990:         PetscCall(PetscLLCondensedAddSorted_Scalable(nzi, Jptr, lnk));
1991:         nextrow[k]++;
1992:         nextci[k]++;
1993:       }
1994:     }

1996:     /* add missing diagonal entry */
1997:     if (C->force_diagonals) {
1998:       k = i + owners[rank]; /* column index */
1999:       PetscCall(PetscLLCondensedAddSorted_Scalable(1, &k, lnk));
2000:     }

2002:     nnz = lnk[0];

2004:     /* if free space is not available, make more free space */
2005:     if (current_space->local_remaining < nnz) {
2006:       PetscCall(PetscFreeSpaceGet(PetscIntSumTruncate(nnz, current_space->total_array_size), &current_space));
2007:       nspacedouble++;
2008:     }
2009:     /* copy data into free space, then initialize lnk */
2010:     PetscCall(PetscLLCondensedClean_Scalable(nnz, current_space->array, lnk));
2011:     PetscCall(MatPreallocateSet(i + owners[rank], nnz, current_space->array, dnz, onz));

2013:     current_space->array += nnz;
2014:     current_space->local_used += nnz;
2015:     current_space->local_remaining -= nnz;

2017:     bi[i + 1] = bi[i] + nnz;
2018:     if (nnz > rmax) rmax = nnz;
2019:   }
2020:   PetscCall(PetscFree3(buf_ri_k, nextrow, nextci));

2022:   PetscCall(PetscMalloc1(bi[pn], &bj));
2023:   PetscCall(PetscFreeSpaceContiguous(&free_space, bj));
2024:   afill_tmp = (PetscReal)bi[pn] / (pdti[pn] + poti[pon] + ai[am] + 1);
2025:   if (afill_tmp > afill) afill = afill_tmp;
2026:   PetscCall(PetscLLCondensedDestroy_Scalable(lnk));
2027:   PetscCall(PetscHMapIDestroy(&ta));
2028:   PetscCall(MatRestoreSymbolicTranspose_SeqAIJ(p->A, &pdti, &pdtj));
2029:   PetscCall(MatRestoreSymbolicTranspose_SeqAIJ(p->B, &poti, &potj));

2031:   /* create symbolic parallel matrix C - why cannot be assembled in Numeric part   */
2032:   PetscCall(MatSetSizes(C, pn, A->cmap->n, PETSC_DETERMINE, PETSC_DETERMINE));
2033:   PetscCall(MatSetBlockSizes(C, P->cmap->bs, A->cmap->bs));
2034:   PetscCall(MatGetType(A, &mtype));
2035:   PetscCall(MatSetType(C, mtype));
2036:   PetscCall(MatMPIAIJSetPreallocation(C, 0, dnz, 0, onz));
2037:   MatPreallocateEnd(dnz, onz);
2038:   PetscCall(MatSetBlockSize(C, 1));
2039:   PetscCall(MatSetOption(C, MAT_NO_OFF_PROC_ENTRIES, PETSC_TRUE));
2040:   for (i = 0; i < pn; i++) {
2041:     row  = i + rstart;
2042:     nnz  = bi[i + 1] - bi[i];
2043:     Jptr = bj + bi[i];
2044:     PetscCall(MatSetValues(C, 1, &row, nnz, Jptr, NULL, INSERT_VALUES));
2045:   }
2046:   PetscCall(MatAssemblyBegin(C, MAT_FINAL_ASSEMBLY));
2047:   PetscCall(MatAssemblyEnd(C, MAT_FINAL_ASSEMBLY));
2048:   PetscCall(MatSetOption(C, MAT_NEW_NONZERO_LOCATION_ERR, PETSC_TRUE));
2049:   merge->bi        = bi;
2050:   merge->bj        = bj;
2051:   merge->coi       = coi;
2052:   merge->coj       = coj;
2053:   merge->buf_ri    = buf_ri;
2054:   merge->buf_rj    = buf_rj;
2055:   merge->owners_co = owners_co;

2057:   /* attach the supporting struct to C for reuse */
2058:   C->product->data    = ap;
2059:   C->product->destroy = MatProductCtxDestroy_MPIAIJ_PtAP;
2060:   ap->merge           = merge;

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

2064:   if (PetscDefined(USE_INFO)) {
2065:     if (bi[pn] != 0) {
2066:       PetscCall(PetscInfo(C, "Reallocs %" PetscInt_FMT "; Fill ratio: given %g needed %g.\n", nspacedouble, (double)fill, (double)afill));
2067:       PetscCall(PetscInfo(C, "Use MatTransposeMatMult(A,B,MatReuse,%g,&C) for best performance.\n", (double)afill));
2068:     } else PetscCall(PetscInfo(C, "Empty matrix product\n"));
2069:   }
2070:   PetscFunctionReturn(PETSC_SUCCESS);
2071: }

2073: static PetscErrorCode MatProductSymbolic_AtB_MPIAIJ_MPIAIJ(Mat C)
2074: {
2075:   Mat_Product *product = C->product;
2076:   Mat          A = product->A, B = product->B;
2077:   PetscReal    fill = product->fill;
2078:   PetscBool    flg;

2080:   PetscFunctionBegin;
2081:   /* scalable */
2082:   PetscCall(PetscStrcmp(product->alg, "scalable", &flg));
2083:   if (flg) {
2084:     PetscCall(MatTransposeMatMultSymbolic_MPIAIJ_MPIAIJ(A, B, fill, C));
2085:     goto next;
2086:   }

2088:   /* nonscalable */
2089:   PetscCall(PetscStrcmp(product->alg, "nonscalable", &flg));
2090:   if (flg) {
2091:     PetscCall(MatTransposeMatMultSymbolic_MPIAIJ_MPIAIJ_nonscalable(A, B, fill, C));
2092:     goto next;
2093:   }

2095:   /* matmatmult */
2096:   PetscCall(PetscStrcmp(product->alg, "at*b", &flg));
2097:   if (flg) {
2098:     Mat                  At;
2099:     MatProductCtx_APMPI *ptap;

2101:     PetscCall(MatTranspose(A, MAT_INITIAL_MATRIX, &At));
2102:     PetscCall(MatMatMultSymbolic_MPIAIJ_MPIAIJ(At, B, fill, C));
2103:     ptap = (MatProductCtx_APMPI *)C->product->data;
2104:     if (ptap) {
2105:       ptap->Pt            = At;
2106:       C->product->destroy = MatProductCtxDestroy_MPIAIJ_PtAP;
2107:     }
2108:     C->ops->transposematmultnumeric = MatTransposeMatMultNumeric_MPIAIJ_MPIAIJ_matmatmult;
2109:     goto next;
2110:   }

2112:   /* backend general code */
2113:   PetscCall(PetscStrcmp(product->alg, "backend", &flg));
2114:   if (flg) {
2115:     PetscCall(MatProductSymbolic_MPIAIJBACKEND(C));
2116:     PetscFunctionReturn(PETSC_SUCCESS);
2117:   }

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

2121: next:
2122:   C->ops->productnumeric = MatProductNumeric_AtB;
2123:   PetscFunctionReturn(PETSC_SUCCESS);
2124: }

2126: /* Set options for MatMatMultxxx_MPIAIJ_MPIAIJ */
2127: static PetscErrorCode MatProductSetFromOptions_MPIAIJ_AB(Mat C)
2128: {
2129:   Mat_Product *product = C->product;
2130:   Mat          A = product->A, B = product->B;
2131: #if PetscDefined(HAVE_HYPRE)
2132:   const char *algTypes[5] = {"scalable", "nonscalable", "seqmpi", "backend", "hypre"};
2133:   PetscInt    nalg        = 5;
2134: #else
2135:   const char *algTypes[4] = {
2136:     "scalable",
2137:     "nonscalable",
2138:     "seqmpi",
2139:     "backend",
2140:   };
2141:   PetscInt nalg = 4;
2142: #endif
2143:   PetscInt  alg = 1; /* set nonscalable algorithm as default */
2144:   PetscBool flg;
2145:   MPI_Comm  comm;

2147:   PetscFunctionBegin;
2148:   PetscCall(PetscObjectGetComm((PetscObject)C, &comm));

2150:   /* Set "nonscalable" as default algorithm */
2151:   PetscCall(PetscStrcmp(C->product->alg, "default", &flg));
2152:   if (flg) {
2153:     PetscCall(MatProductSetAlgorithm(C, algTypes[alg]));

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

2161:       PetscCall(MatGetInfo(A, MAT_LOCAL, &Ainfo));
2162:       PetscCall(MatGetInfo(B, MAT_LOCAL, &Binfo));
2163:       nz_local = (PetscInt)(Ainfo.nz_allocated + Binfo.nz_allocated);

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

2168:       if (alg_scalable) {
2169:         alg = 0; /* scalable algorithm would 50% slower than nonscalable algorithm */
2170:         PetscCall(MatProductSetAlgorithm(C, algTypes[alg]));
2171:         PetscCall(PetscInfo(B, "Use scalable algorithm, BN %" PetscInt_FMT ", fill*nz_allocated %g\n", B->cmap->N, (double)(product->fill * nz_local)));
2172:       }
2173:     }
2174:   }

2176:   /* Get runtime option */
2177:   if (product->api_user) {
2178:     PetscOptionsBegin(PetscObjectComm((PetscObject)C), ((PetscObject)C)->prefix, "MatMatMult", "Mat");
2179:     PetscCall(PetscOptionsEList("-matmatmult_via", "Algorithmic approach", "MatMatMult", algTypes, nalg, algTypes[alg], &alg, &flg));
2180:     PetscOptionsEnd();
2181:   } else {
2182:     PetscOptionsBegin(PetscObjectComm((PetscObject)C), ((PetscObject)C)->prefix, "MatProduct_AB", "Mat");
2183:     PetscCall(PetscOptionsEList("-mat_product_algorithm", "Algorithmic approach", "MatMatMult", algTypes, nalg, algTypes[alg], &alg, &flg));
2184:     PetscOptionsEnd();
2185:   }
2186:   if (flg) PetscCall(MatProductSetAlgorithm(C, algTypes[alg]));

2188:   C->ops->productsymbolic = MatProductSymbolic_AB_MPIAIJ_MPIAIJ;
2189:   PetscFunctionReturn(PETSC_SUCCESS);
2190: }

2192: static PetscErrorCode MatProductSetFromOptions_MPIAIJ_ABt(Mat C)
2193: {
2194:   PetscFunctionBegin;
2195:   PetscCall(MatProductSetFromOptions_MPIAIJ_AB(C));
2196:   C->ops->productsymbolic = MatProductSymbolic_ABt_MPIAIJ_MPIAIJ;
2197:   PetscFunctionReturn(PETSC_SUCCESS);
2198: }

2200: /* Set options for MatTransposeMatMultXXX_MPIAIJ_MPIAIJ */
2201: static PetscErrorCode MatProductSetFromOptions_MPIAIJ_AtB(Mat C)
2202: {
2203:   Mat_Product *product = C->product;
2204:   Mat          A = product->A, B = product->B;
2205:   const char  *algTypes[4] = {"scalable", "nonscalable", "at*b", "backend"};
2206:   PetscInt     nalg        = 4;
2207:   PetscInt     alg         = 1; /* set default algorithm  */
2208:   PetscBool    flg;
2209:   MPI_Comm     comm;

2211:   PetscFunctionBegin;
2212:   /* Check matrix local sizes */
2213:   PetscCall(PetscObjectGetComm((PetscObject)C, &comm));
2214:   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 ")",
2215:              A->rmap->rstart, A->rmap->rend, B->rmap->rstart, B->rmap->rend);

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

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

2227:     PetscCall(MatGetInfo(A, MAT_LOCAL, &Ainfo));
2228:     PetscCall(MatGetInfo(B, MAT_LOCAL, &Binfo));
2229:     nz_local = (PetscInt)(Ainfo.nz_allocated + Binfo.nz_allocated);

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

2234:     if (alg_scalable) {
2235:       alg = 0; /* scalable algorithm would 50% slower than nonscalable algorithm */
2236:       PetscCall(MatProductSetAlgorithm(C, algTypes[alg]));
2237:       PetscCall(PetscInfo(B, "Use scalable algorithm, BN %" PetscInt_FMT ", fill*nz_allocated %g\n", B->cmap->N, (double)(product->fill * nz_local)));
2238:     }
2239:   }

2241:   /* Get runtime option */
2242:   if (product->api_user) {
2243:     PetscOptionsBegin(PetscObjectComm((PetscObject)C), ((PetscObject)C)->prefix, "MatTransposeMatMult", "Mat");
2244:     PetscCall(PetscOptionsEList("-mattransposematmult_via", "Algorithmic approach", "MatTransposeMatMult", algTypes, nalg, algTypes[alg], &alg, &flg));
2245:     PetscOptionsEnd();
2246:   } else {
2247:     PetscOptionsBegin(PetscObjectComm((PetscObject)C), ((PetscObject)C)->prefix, "MatProduct_AtB", "Mat");
2248:     PetscCall(PetscOptionsEList("-mat_product_algorithm", "Algorithmic approach", "MatTransposeMatMult", algTypes, nalg, algTypes[alg], &alg, &flg));
2249:     PetscOptionsEnd();
2250:   }
2251:   if (flg) PetscCall(MatProductSetAlgorithm(C, algTypes[alg]));

2253:   C->ops->productsymbolic = MatProductSymbolic_AtB_MPIAIJ_MPIAIJ;
2254:   PetscFunctionReturn(PETSC_SUCCESS);
2255: }

2257: static PetscErrorCode MatProductSetFromOptions_MPIAIJ_PtAP(Mat C)
2258: {
2259:   Mat_Product *product = C->product;
2260:   Mat          A = product->A, P = product->B;
2261:   MPI_Comm     comm;
2262:   PetscBool    flg;
2263:   PetscInt     alg = 1; /* set default algorithm */
2264: #if !PetscDefined(HAVE_HYPRE)
2265:   const char *algTypes[5] = {"scalable", "nonscalable", "allatonce", "allatonce_merged", "backend"};
2266:   PetscInt    nalg        = 5;
2267: #else
2268:   const char *algTypes[6] = {"scalable", "nonscalable", "allatonce", "allatonce_merged", "backend", "hypre"};
2269:   PetscInt    nalg        = 6;
2270: #endif
2271:   PetscInt pN = P->cmap->N;

2273:   PetscFunctionBegin;
2274:   /* Check matrix local sizes */
2275:   PetscCall(PetscObjectGetComm((PetscObject)C, &comm));
2276:   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 ")",
2277:              A->rmap->rstart, A->rmap->rend, P->rmap->rstart, P->rmap->rend);
2278:   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 ")",
2279:              A->cmap->rstart, A->cmap->rend, P->rmap->rstart, P->rmap->rend);

2281:   /* Set "nonscalable" as default algorithm */
2282:   PetscCall(PetscStrcmp(C->product->alg, "default", &flg));
2283:   if (flg) {
2284:     PetscCall(MatProductSetAlgorithm(C, algTypes[alg]));

2286:     /* Set "scalable" as default if BN and local nonzeros of A and B are large */
2287:     if (pN > 100000) {
2288:       MatInfo   Ainfo, Pinfo;
2289:       PetscInt  nz_local;
2290:       PetscBool alg_scalable = PETSC_FALSE;

2292:       PetscCall(MatGetInfo(A, MAT_LOCAL, &Ainfo));
2293:       PetscCall(MatGetInfo(P, MAT_LOCAL, &Pinfo));
2294:       nz_local = (PetscInt)(Ainfo.nz_allocated + Pinfo.nz_allocated);

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

2299:       if (alg_scalable) {
2300:         alg = 0; /* scalable algorithm would 50% slower than nonscalable algorithm */
2301:         PetscCall(MatProductSetAlgorithm(C, algTypes[alg]));
2302:       }
2303:     }
2304:   }

2306:   /* Get runtime option */
2307:   if (product->api_user) {
2308:     PetscOptionsBegin(PetscObjectComm((PetscObject)C), ((PetscObject)C)->prefix, "MatPtAP", "Mat");
2309:     PetscCall(PetscOptionsEList("-matptap_via", "Algorithmic approach", "MatPtAP", algTypes, nalg, algTypes[alg], &alg, &flg));
2310:     PetscOptionsEnd();
2311:   } else {
2312:     PetscOptionsBegin(PetscObjectComm((PetscObject)C), ((PetscObject)C)->prefix, "MatProduct_PtAP", "Mat");
2313:     PetscCall(PetscOptionsEList("-mat_product_algorithm", "Algorithmic approach", "MatPtAP", algTypes, nalg, algTypes[alg], &alg, &flg));
2314:     PetscOptionsEnd();
2315:   }
2316:   if (flg) PetscCall(MatProductSetAlgorithm(C, algTypes[alg]));

2318:   C->ops->productsymbolic = MatProductSymbolic_PtAP_MPIAIJ_MPIAIJ;
2319:   PetscFunctionReturn(PETSC_SUCCESS);
2320: }

2322: static PetscErrorCode MatProductSetFromOptions_MPIAIJ_RARt(Mat C)
2323: {
2324:   Mat_Product *product = C->product;
2325:   Mat          A = product->A, R = product->B;

2327:   PetscFunctionBegin;
2328:   /* Check matrix local sizes */
2329:   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,
2330:              A->rmap->n, R->rmap->n, R->cmap->n);

2332:   C->ops->productsymbolic = MatProductSymbolic_RARt_MPIAIJ_MPIAIJ;
2333:   PetscFunctionReturn(PETSC_SUCCESS);
2334: }

2336: /*
2337:  Set options for ABC = A*B*C = A*(B*C); ABC's algorithm must be chosen from AB's algorithm
2338: */
2339: static PetscErrorCode MatProductSetFromOptions_MPIAIJ_ABC(Mat C)
2340: {
2341:   Mat_Product *product     = C->product;
2342:   PetscBool    flg         = PETSC_FALSE;
2343:   PetscInt     alg         = 1; /* default algorithm */
2344:   const char  *algTypes[3] = {"scalable", "nonscalable", "seqmpi"};
2345:   PetscInt     nalg        = 3;

2347:   PetscFunctionBegin;
2348:   /* Set default algorithm */
2349:   PetscCall(PetscStrcmp(C->product->alg, "default", &flg));
2350:   if (flg) PetscCall(MatProductSetAlgorithm(C, algTypes[alg]));

2352:   /* Get runtime option */
2353:   if (product->api_user) {
2354:     PetscOptionsBegin(PetscObjectComm((PetscObject)C), ((PetscObject)C)->prefix, "MatMatMatMult", "Mat");
2355:     PetscCall(PetscOptionsEList("-matmatmatmult_via", "Algorithmic approach", "MatMatMatMult", algTypes, nalg, algTypes[alg], &alg, &flg));
2356:     PetscOptionsEnd();
2357:   } else {
2358:     PetscOptionsBegin(PetscObjectComm((PetscObject)C), ((PetscObject)C)->prefix, "MatProduct_ABC", "Mat");
2359:     PetscCall(PetscOptionsEList("-mat_product_algorithm", "Algorithmic approach", "MatProduct_ABC", algTypes, nalg, algTypes[alg], &alg, &flg));
2360:     PetscOptionsEnd();
2361:   }
2362:   if (flg) PetscCall(MatProductSetAlgorithm(C, algTypes[alg]));

2364:   C->ops->matmatmultsymbolic = MatMatMatMultSymbolic_MPIAIJ_MPIAIJ_MPIAIJ;
2365:   C->ops->productsymbolic    = MatProductSymbolic_ABC;
2366:   PetscFunctionReturn(PETSC_SUCCESS);
2367: }

2369: PETSC_INTERN PetscErrorCode MatProductSetFromOptions_MPIAIJ(Mat C)
2370: {
2371:   Mat_Product *product = C->product;

2373:   PetscFunctionBegin;
2374:   switch (product->type) {
2375:   case MATPRODUCT_AB:
2376:     PetscCall(MatProductSetFromOptions_MPIAIJ_AB(C));
2377:     break;
2378:   case MATPRODUCT_ABt:
2379:     PetscCall(MatProductSetFromOptions_MPIAIJ_ABt(C));
2380:     break;
2381:   case MATPRODUCT_AtB:
2382:     PetscCall(MatProductSetFromOptions_MPIAIJ_AtB(C));
2383:     break;
2384:   case MATPRODUCT_PtAP:
2385:     PetscCall(MatProductSetFromOptions_MPIAIJ_PtAP(C));
2386:     break;
2387:   case MATPRODUCT_RARt:
2388:     PetscCall(MatProductSetFromOptions_MPIAIJ_RARt(C));
2389:     break;
2390:   case MATPRODUCT_ABC:
2391:     PetscCall(MatProductSetFromOptions_MPIAIJ_ABC(C));
2392:     break;
2393:   default:
2394:     break;
2395:   }
2396:   PetscFunctionReturn(PETSC_SUCCESS);
2397: }