Actual source code: mpimatmatmult.c


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

 14: #if defined(PETSC_HAVE_HYPRE)
 15: PETSC_INTERN PetscErrorCode MatMatMultSymbolic_AIJ_AIJ_wHYPRE(Mat,Mat,PetscReal,Mat);
 16: #endif

 18: PETSC_INTERN PetscErrorCode MatProductSymbolic_AB_MPIAIJ_MPIAIJ(Mat C)
 19: {
 20:   PetscErrorCode      ierr;
 21:   Mat_Product         *product = C->product;
 22:   Mat                 A=product->A,B=product->B;
 23:   MatProductAlgorithm alg=product->alg;
 24:   PetscReal           fill=product->fill;
 25:   PetscBool           flg;

 28:   /* scalable */
 29:   PetscStrcmp(alg,"scalable",&flg);
 30:   if (flg) {
 31:     MatMatMultSymbolic_MPIAIJ_MPIAIJ(A,B,fill,C);
 32:     return(0);
 33:   }

 35:   /* nonscalable */
 36:   PetscStrcmp(alg,"nonscalable",&flg);
 37:   if (flg) {
 38:     MatMatMultSymbolic_MPIAIJ_MPIAIJ_nonscalable(A,B,fill,C);
 39:     return(0);
 40:   }

 42:   /* seqmpi */
 43:   PetscStrcmp(alg,"seqmpi",&flg);
 44:   if (flg) {
 45:     MatMatMultSymbolic_MPIAIJ_MPIAIJ_seqMPI(A,B,fill,C);
 46:     return(0);
 47:   }

 49:   /* backend general code */
 50:   PetscStrcmp(alg,"backend",&flg);
 51:   if (flg) {
 52:     MatProductSymbolic_MPIAIJBACKEND(C);
 53:     return(0);
 54:   }

 56: #if defined(PETSC_HAVE_HYPRE)
 57:   PetscStrcmp(alg,"hypre",&flg);
 58:   if (flg) {
 59:     MatMatMultSymbolic_AIJ_AIJ_wHYPRE(A,B,fill,C);
 60:     return(0);
 61:   }
 62: #endif
 63:   SETERRQ(PetscObjectComm((PetscObject)C),PETSC_ERR_SUP,"Mat Product Algorithm is not supported");
 64: }

 66: PetscErrorCode MatDestroy_MPIAIJ_MatMatMult(void *data)
 67: {
 69:   Mat_APMPI      *ptap = (Mat_APMPI*)data;

 72:   PetscFree2(ptap->startsj_s,ptap->startsj_r);
 73:   PetscFree(ptap->bufa);
 74:   MatDestroy(&ptap->P_loc);
 75:   MatDestroy(&ptap->P_oth);
 76:   MatDestroy(&ptap->Pt);
 77:   PetscFree(ptap->api);
 78:   PetscFree(ptap->apj);
 79:   PetscFree(ptap->apa);
 80:   PetscFree(ptap);
 81:   return(0);
 82: }

 84: PetscErrorCode MatMatMultNumeric_MPIAIJ_MPIAIJ_nonscalable(Mat A,Mat P,Mat C)
 85: {
 86:   PetscErrorCode    ierr;
 87:   Mat_MPIAIJ        *a  =(Mat_MPIAIJ*)A->data,*c=(Mat_MPIAIJ*)C->data;
 88:   Mat_SeqAIJ        *ad =(Mat_SeqAIJ*)(a->A)->data,*ao=(Mat_SeqAIJ*)(a->B)->data;
 89:   Mat_SeqAIJ        *cd =(Mat_SeqAIJ*)(c->A)->data,*co=(Mat_SeqAIJ*)(c->B)->data;
 90:   PetscScalar       *cda=cd->a,*coa=co->a;
 91:   Mat_SeqAIJ        *p_loc,*p_oth;
 92:   PetscScalar       *apa,*ca;
 93:   PetscInt          cm =C->rmap->n;
 94:   Mat_APMPI         *ptap;
 95:   PetscInt          *api,*apj,*apJ,i,k;
 96:   PetscInt          cstart=C->cmap->rstart;
 97:   PetscInt          cdnz,conz,k0,k1;
 98:   const PetscScalar *dummy;
 99:   MPI_Comm          comm;
100:   PetscMPIInt       size;

103:   MatCheckProduct(C,3);
104:   ptap = (Mat_APMPI*)C->product->data;
105:   if (!ptap) SETERRQ(PetscObjectComm((PetscObject)C),PETSC_ERR_ARG_WRONGSTATE,"PtAP cannot be computed. Missing data");
106:   PetscObjectGetComm((PetscObject)A,&comm);
107:   MPI_Comm_size(comm,&size);

109:   if (!ptap->P_oth && size>1) SETERRQ(PetscObjectComm((PetscObject)C),PETSC_ERR_ARG_WRONGSTATE,"AP cannot be reused. Do not call MatProductClear()");

111:   /* 1) get P_oth = ptap->P_oth  and P_loc = ptap->P_loc */
112:   /*-----------------------------------------------------*/
113:   /* update numerical values of P_oth and P_loc */
114:   MatGetBrowsOfAoCols_MPIAIJ(A,P,MAT_REUSE_MATRIX,&ptap->startsj_s,&ptap->startsj_r,&ptap->bufa,&ptap->P_oth);
115:   MatMPIAIJGetLocalMat(P,MAT_REUSE_MATRIX,&ptap->P_loc);

117:   /* 2) compute numeric C_loc = A_loc*P = Ad*P_loc + Ao*P_oth */
118:   /*----------------------------------------------------------*/
119:   /* get data from symbolic products */
120:   p_loc = (Mat_SeqAIJ*)(ptap->P_loc)->data;
121:   p_oth = NULL;
122:   if (size >1) {
123:     p_oth = (Mat_SeqAIJ*)(ptap->P_oth)->data;
124:   }

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

129:   api = ptap->api;
130:   apj = ptap->apj;
131:   /* trigger copy to CPU */
132:   MatSeqAIJGetArrayRead(a->A,&dummy);
133:   MatSeqAIJRestoreArrayRead(a->A,&dummy);
134:   MatSeqAIJGetArrayRead(a->B,&dummy);
135:   MatSeqAIJRestoreArrayRead(a->B,&dummy);
136:   for (i=0; i<cm; i++) {
137:     /* compute apa = A[i,:]*P */
138:     AProw_nonscalable(i,ad,ao,p_loc,p_oth,apa);

140:     /* set values in C */
141:     apJ  = apj + api[i];
142:     cdnz = cd->i[i+1] - cd->i[i];
143:     conz = co->i[i+1] - co->i[i];

145:     /* 1st off-diagonal part of C */
146:     ca = coa + co->i[i];
147:     k  = 0;
148:     for (k0=0; k0<conz; k0++) {
149:       if (apJ[k] >= cstart) break;
150:       ca[k0]      = apa[apJ[k]];
151:       apa[apJ[k++]] = 0.0;
152:     }

154:     /* diagonal part of C */
155:     ca = cda + cd->i[i];
156:     for (k1=0; k1<cdnz; k1++) {
157:       ca[k1]      = apa[apJ[k]];
158:       apa[apJ[k++]] = 0.0;
159:     }

161:     /* 2nd off-diagonal part of C */
162:     ca = coa + co->i[i];
163:     for (; k0<conz; k0++) {
164:       ca[k0]      = apa[apJ[k]];
165:       apa[apJ[k++]] = 0.0;
166:     }
167:   }
168:   MatAssemblyBegin(C,MAT_FINAL_ASSEMBLY);
169:   MatAssemblyEnd(C,MAT_FINAL_ASSEMBLY);
170:   return(0);
171: }

173: PetscErrorCode MatMatMultSymbolic_MPIAIJ_MPIAIJ_nonscalable(Mat A,Mat P,PetscReal fill,Mat C)
174: {
175:   PetscErrorCode     ierr;
176:   MPI_Comm           comm;
177:   PetscMPIInt        size;
178:   Mat_APMPI          *ptap;
179:   PetscFreeSpaceList free_space=NULL,current_space=NULL;
180:   Mat_MPIAIJ         *a=(Mat_MPIAIJ*)A->data;
181:   Mat_SeqAIJ         *ad=(Mat_SeqAIJ*)(a->A)->data,*ao=(Mat_SeqAIJ*)(a->B)->data,*p_loc,*p_oth;
182:   PetscInt           *pi_loc,*pj_loc,*pi_oth,*pj_oth,*dnz,*onz;
183:   PetscInt           *adi=ad->i,*adj=ad->j,*aoi=ao->i,*aoj=ao->j,rstart=A->rmap->rstart;
184:   PetscInt           *lnk,i,pnz,row,*api,*apj,*Jptr,apnz,nspacedouble=0,j,nzi;
185:   PetscInt           am=A->rmap->n,pN=P->cmap->N,pn=P->cmap->n,pm=P->rmap->n;
186:   PetscBT            lnkbt;
187:   PetscReal          afill;
188:   MatType            mtype;

191:   MatCheckProduct(C,4);
192:   if (C->product->data) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_PLIB,"Extra product struct not empty");
193:   PetscObjectGetComm((PetscObject)A,&comm);
194:   MPI_Comm_size(comm,&size);

196:   /* create struct Mat_APMPI and attached it to C later */
197:   PetscNew(&ptap);

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

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

205:   p_loc  = (Mat_SeqAIJ*)(ptap->P_loc)->data;
206:   pi_loc = p_loc->i; pj_loc = p_loc->j;
207:   if (size > 1) {
208:     p_oth  = (Mat_SeqAIJ*)(ptap->P_oth)->data;
209:     pi_oth = p_oth->i; pj_oth = p_oth->j;
210:   } else {
211:     p_oth = NULL;
212:     pi_oth = NULL; pj_oth = NULL;
213:   }

215:   /* first, compute symbolic AP = A_loc*P = A_diag*P_loc + A_off*P_oth */
216:   /*-------------------------------------------------------------------*/
217:   PetscMalloc1(am+2,&api);
218:   ptap->api = api;
219:   api[0]    = 0;

221:   /* create and initialize a linked list */
222:   PetscLLCondensedCreate(pN,pN,&lnk,&lnkbt);

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

228:   MatPreallocateInitialize(comm,am,pn,dnz,onz);
229:   for (i=0; i<am; i++) {
230:     /* diagonal portion of A */
231:     nzi = adi[i+1] - adi[i];
232:     for (j=0; j<nzi; j++) {
233:       row  = *adj++;
234:       pnz  = pi_loc[row+1] - pi_loc[row];
235:       Jptr = pj_loc + pi_loc[row];
236:       /* add non-zero cols of P into the sorted linked list lnk */
237:       PetscLLCondensedAddSorted(pnz,Jptr,lnk,lnkbt);
238:     }
239:     /* off-diagonal portion of A */
240:     nzi = aoi[i+1] - aoi[i];
241:     for (j=0; j<nzi; j++) {
242:       row  = *aoj++;
243:       pnz  = pi_oth[row+1] - pi_oth[row];
244:       Jptr = pj_oth + pi_oth[row];
245:       PetscLLCondensedAddSorted(pnz,Jptr,lnk,lnkbt);
246:     }
247:     /* add possible missing diagonal entry */
248:     if (C->force_diagonals) {
249:       j = i + rstart; /* column index */
250:       PetscLLCondensedAddSorted(1,&j,lnk,lnkbt);
251:     }

253:     apnz     = lnk[0];
254:     api[i+1] = api[i] + apnz;

256:     /* if free space is not available, double the total space in the list */
257:     if (current_space->local_remaining<apnz) {
258:       PetscFreeSpaceGet(PetscIntSumTruncate(apnz,current_space->total_array_size),&current_space);
259:       nspacedouble++;
260:     }

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

266:     current_space->array           += apnz;
267:     current_space->local_used      += apnz;
268:     current_space->local_remaining -= apnz;
269:   }

271:   /* Allocate space for apj, initialize apj, and */
272:   /* destroy list of free space and other temporary array(s) */
273:   PetscMalloc1(api[am]+1,&ptap->apj);
274:   apj  = ptap->apj;
275:   PetscFreeSpaceContiguous(&free_space,ptap->apj);
276:   PetscLLDestroy(lnk,lnkbt);

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

281:   /* set and assemble symbolic parallel matrix C */
282:   /*---------------------------------------------*/
283:   MatSetSizes(C,am,pn,PETSC_DETERMINE,PETSC_DETERMINE);
284:   MatSetBlockSizesFromMats(C,A,P);

286:   MatGetType(A,&mtype);
287:   MatSetType(C,mtype);
288:   MatMPIAIJSetPreallocation(C,0,dnz,0,onz);
289:   MatPreallocateFinalize(dnz,onz);

291:   MatSetValues_MPIAIJ_CopyFromCSRFormat_Symbolic(C, apj, api);
292:   MatAssemblyBegin(C,MAT_FINAL_ASSEMBLY);
293:   MatAssemblyEnd(C,MAT_FINAL_ASSEMBLY);
294:   MatSetOption(C,MAT_NEW_NONZERO_LOCATION_ERR,PETSC_TRUE);

296:   C->ops->matmultnumeric = MatMatMultNumeric_MPIAIJ_MPIAIJ_nonscalable;
297:   C->ops->productnumeric = MatProductNumeric_AB;

299:   /* attach the supporting struct to C for reuse */
300:   C->product->data    = ptap;
301:   C->product->destroy = MatDestroy_MPIAIJ_MatMatMult;

303:   /* set MatInfo */
304:   afill = (PetscReal)api[am]/(adi[am]+aoi[am]+pi_loc[pm]+1) + 1.e-5;
305:   if (afill < 1.0) afill = 1.0;
306:   C->info.mallocs           = nspacedouble;
307:   C->info.fill_ratio_given  = fill;
308:   C->info.fill_ratio_needed = afill;

310: #if defined(PETSC_USE_INFO)
311:   if (api[am]) {
312:     PetscInfo3(C,"Reallocs %D; Fill ratio: given %g needed %g.\n",nspacedouble,(double)fill,(double)afill);
313:     PetscInfo1(C,"Use MatMatMult(A,B,MatReuse,%g,&C) for best performance.;\n",(double)afill);
314:   } else {
315:     PetscInfo(C,"Empty matrix product\n");
316:   }
317: #endif
318:   return(0);
319: }

321: /* ------------------------------------------------------- */
322: static PetscErrorCode MatMatMultSymbolic_MPIAIJ_MPIDense(Mat,Mat,PetscReal,Mat);
323: static PetscErrorCode MatMatMultNumeric_MPIAIJ_MPIDense(Mat,Mat,Mat);

325: static PetscErrorCode MatProductSetFromOptions_MPIAIJ_MPIDense_AB(Mat C)
326: {
327:   Mat_Product *product = C->product;
328:   Mat         A = product->A,B=product->B;

331:   if (A->cmap->rstart != B->rmap->rstart || A->cmap->rend != B->rmap->rend)
332:     SETERRQ4(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Matrix local dimensions are incompatible, (%D, %D) != (%D,%D)",A->cmap->rstart,A->cmap->rend,B->rmap->rstart,B->rmap->rend);

334:   C->ops->matmultsymbolic = MatMatMultSymbolic_MPIAIJ_MPIDense;
335:   C->ops->productsymbolic = MatProductSymbolic_AB;
336:   return(0);
337: }
338: /* -------------------------------------------------------------------- */
339: static PetscErrorCode MatProductSetFromOptions_MPIAIJ_MPIDense_AtB(Mat C)
340: {
341:   Mat_Product *product = C->product;
342:   Mat         A = product->A,B=product->B;

345:   if (A->rmap->rstart != B->rmap->rstart || A->rmap->rend != B->rmap->rend)
346:     SETERRQ4(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Matrix local dimensions are incompatible, (%D, %D) != (%D,%D)",A->rmap->rstart,A->rmap->rend,B->rmap->rstart,B->rmap->rend);

348:   C->ops->transposematmultsymbolic = MatTransposeMatMultSymbolic_MPIAIJ_MPIDense;
349:   C->ops->productsymbolic          = MatProductSymbolic_AtB;
350:   return(0);
351: }

353: /* --------------------------------------------------------------------- */
354: PETSC_INTERN PetscErrorCode MatProductSetFromOptions_MPIAIJ_MPIDense(Mat C)
355: {
357:   Mat_Product    *product = C->product;

360:   switch (product->type) {
361:   case MATPRODUCT_AB:
362:     MatProductSetFromOptions_MPIAIJ_MPIDense_AB(C);
363:     break;
364:   case MATPRODUCT_AtB:
365:     MatProductSetFromOptions_MPIAIJ_MPIDense_AtB(C);
366:     break;
367:   default:
368:     break;
369:   }
370:   return(0);
371: }
372: /* ------------------------------------------------------- */

374: typedef struct {
375:   Mat          workB,workB1;
376:   MPI_Request  *rwaits,*swaits;
377:   PetscInt     nsends,nrecvs;
378:   MPI_Datatype *stype,*rtype;
379:   PetscInt     blda;
380: } MPIAIJ_MPIDense;

382: PetscErrorCode MatMPIAIJ_MPIDenseDestroy(void *ctx)
383: {
384:   MPIAIJ_MPIDense *contents = (MPIAIJ_MPIDense*)ctx;
385:   PetscErrorCode  ierr;
386:   PetscInt        i;

389:   MatDestroy(&contents->workB);
390:   MatDestroy(&contents->workB1);
391:   for (i=0; i<contents->nsends; i++) {
392:     MPI_Type_free(&contents->stype[i]);
393:   }
394:   for (i=0; i<contents->nrecvs; i++) {
395:     MPI_Type_free(&contents->rtype[i]);
396:   }
397:   PetscFree4(contents->stype,contents->rtype,contents->rwaits,contents->swaits);
398:   PetscFree(contents);
399:   return(0);
400: }

402: static PetscErrorCode MatMatMultSymbolic_MPIAIJ_MPIDense(Mat A,Mat B,PetscReal fill,Mat C)
403: {
404:   PetscErrorCode  ierr;
405:   Mat_MPIAIJ      *aij=(Mat_MPIAIJ*)A->data;
406:   PetscInt        nz=aij->B->cmap->n,nsends,nrecvs,i,nrows_to,j,blda,clda,m,M,n,N;
407:   MPIAIJ_MPIDense *contents;
408:   VecScatter      ctx=aij->Mvctx;
409:   PetscInt        Am=A->rmap->n,Bm=B->rmap->n,BN=B->cmap->N,Bbn,Bbn1,bs,nrows_from,numBb;
410:   MPI_Comm        comm;
411:   MPI_Datatype    type1,*stype,*rtype;
412:   const PetscInt  *sindices,*sstarts,*rstarts;
413:   PetscMPIInt     *disp;
414:   PetscBool       cisdense;

417:   MatCheckProduct(C,4);
418:   if (C->product->data) SETERRQ(PetscObjectComm((PetscObject)C),PETSC_ERR_PLIB,"Product data not empty");
419:   PetscObjectGetComm((PetscObject)A,&comm);
420:   PetscObjectBaseTypeCompare((PetscObject)C,MATMPIDENSE,&cisdense);
421:   if (!cisdense) {
422:     MatSetType(C,((PetscObject)B)->type_name);
423:   }
424:   MatGetLocalSize(C,&m,&n);
425:   MatGetSize(C,&M,&N);
426:   if (m == PETSC_DECIDE || n == PETSC_DECIDE || M == PETSC_DECIDE || N == PETSC_DECIDE) {
427:     MatSetSizes(C,Am,B->cmap->n,A->rmap->N,BN);
428:   }
429:   MatSetBlockSizesFromMats(C,A,B);
430:   MatSetUp(C);
431:   MatDenseGetLDA(B,&blda);
432:   MatDenseGetLDA(C,&clda);
433:   PetscNew(&contents);

435:   VecScatterGetRemote_Private(ctx,PETSC_TRUE/*send*/,&nsends,&sstarts,&sindices,NULL,NULL);
436:   VecScatterGetRemoteOrdered_Private(ctx,PETSC_FALSE/*recv*/,&nrecvs,&rstarts,NULL,NULL,NULL);

438:   /* Create column block of B and C for memory scalability when BN is too large */
439:   /* Estimate Bbn, column size of Bb */
440:   if (nz) {
441:     Bbn1 = 2*Am*BN/nz;
442:     if (!Bbn1) Bbn1 = 1;
443:   } else Bbn1 = BN;

445:   bs = PetscAbs(B->cmap->bs);
446:   Bbn1 = Bbn1/bs *bs; /* Bbn1 is a multiple of bs */
447:   if (Bbn1 > BN) Bbn1 = BN;
448:   MPI_Allreduce(&Bbn1,&Bbn,1,MPIU_INT,MPI_MAX,comm);

450:   /* Enable runtime option for Bbn */
451:   PetscOptionsBegin(comm,((PetscObject)C)->prefix,"MatMatMult","Mat");
452:   PetscOptionsInt("-matmatmult_Bbn","Number of columns in Bb","MatMatMult",Bbn,&Bbn,NULL);
453:   PetscOptionsEnd();
454:   Bbn  = PetscMin(Bbn,BN);

456:   if (Bbn > 0 && Bbn < BN) {
457:     numBb = BN/Bbn;
458:     Bbn1 = BN - numBb*Bbn;
459:   } else numBb = 0;

461:   if (numBb) {
462:     PetscInfo3(C,"use Bb, BN=%D, Bbn=%D; numBb=%D\n",BN,Bbn,numBb);
463:     if (Bbn1) { /* Create workB1 for the remaining columns */
464:       PetscInfo2(C,"use Bb1, BN=%D, Bbn1=%D\n",BN,Bbn1);
465:       /* Create work matrix used to store off processor rows of B needed for local product */
466:       MatCreateSeqDense(PETSC_COMM_SELF,nz,Bbn1,NULL,&contents->workB1);
467:     } else contents->workB1 = NULL;
468:   }

470:   /* Create work matrix used to store off processor rows of B needed for local product */
471:   MatCreateSeqDense(PETSC_COMM_SELF,nz,Bbn,NULL,&contents->workB);

473:   /* Use MPI derived data type to reduce memory required by the send/recv buffers */
474:   PetscMalloc4(nsends,&stype,nrecvs,&rtype,nrecvs,&contents->rwaits,nsends,&contents->swaits);
475:   contents->stype  = stype;
476:   contents->nsends = nsends;

478:   contents->rtype  = rtype;
479:   contents->nrecvs = nrecvs;
480:   contents->blda   = blda;

482:   PetscMalloc1(Bm+1,&disp);
483:   for (i=0; i<nsends; i++) {
484:     nrows_to = sstarts[i+1]-sstarts[i];
485:     for (j=0; j<nrows_to; j++){
486:       disp[j] = sindices[sstarts[i]+j]; /* rowB to be sent */
487:     }
488:     MPI_Type_create_indexed_block(nrows_to,1,(const PetscMPIInt *)disp,MPIU_SCALAR,&type1);

490:     MPI_Type_create_resized(type1,0,blda*sizeof(PetscScalar),&stype[i]);
491:     MPI_Type_commit(&stype[i]);
492:     MPI_Type_free(&type1);
493:   }

495:   for (i=0; i<nrecvs; i++) {
496:     /* received values from a process form a (nrows_from x Bbn) row block in workB (column-wise) */
497:     nrows_from = rstarts[i+1]-rstarts[i];
498:     disp[0] = 0;
499:     MPI_Type_create_indexed_block(1, nrows_from, (const PetscMPIInt *)disp, MPIU_SCALAR, &type1);
500:     MPI_Type_create_resized(type1, 0, nz*sizeof(PetscScalar), &rtype[i]);
501:     MPI_Type_commit(&rtype[i]);
502:     MPI_Type_free(&type1);
503:   }

505:   PetscFree(disp);
506:   VecScatterRestoreRemote_Private(ctx,PETSC_TRUE/*send*/,&nsends,&sstarts,&sindices,NULL,NULL);
507:   VecScatterRestoreRemoteOrdered_Private(ctx,PETSC_FALSE/*recv*/,&nrecvs,&rstarts,NULL,NULL,NULL);
508:   MatSetOption(C,MAT_NO_OFF_PROC_ENTRIES,PETSC_TRUE);
509:   MatAssemblyBegin(C,MAT_FINAL_ASSEMBLY);
510:   MatAssemblyEnd(C,MAT_FINAL_ASSEMBLY);
511:   MatSetOption(C,MAT_NEW_NONZERO_LOCATION_ERR,PETSC_TRUE);

513:   C->product->data = contents;
514:   C->product->destroy = MatMPIAIJ_MPIDenseDestroy;
515:   C->ops->matmultnumeric = MatMatMultNumeric_MPIAIJ_MPIDense;
516:   return(0);
517: }

519: PETSC_INTERN PetscErrorCode MatMatMultNumericAdd_SeqAIJ_SeqDense(Mat,Mat,Mat,const PetscBool);
520: /*
521:     Performs an efficient scatter on the rows of B needed by this process; this is
522:     a modification of the VecScatterBegin_() routines.

524:     Input: Bbidx = 0: B = Bb
525:                  = 1: B = Bb1, see MatMatMultSymbolic_MPIAIJ_MPIDense()
526: */
527: PetscErrorCode MatMPIDenseScatter(Mat A,Mat B,PetscInt Bbidx,Mat C,Mat *outworkB)
528: {
529:   Mat_MPIAIJ        *aij = (Mat_MPIAIJ*)A->data;
530:   PetscErrorCode    ierr;
531:   const PetscScalar *b;
532:   PetscScalar       *rvalues;
533:   VecScatter        ctx = aij->Mvctx;
534:   const PetscInt    *sindices,*sstarts,*rstarts;
535:   const PetscMPIInt *sprocs,*rprocs;
536:   PetscInt          i,nsends,nrecvs;
537:   MPI_Request       *swaits,*rwaits;
538:   MPI_Comm          comm;
539:   PetscMPIInt       tag=((PetscObject)ctx)->tag,ncols=B->cmap->N,nrows=aij->B->cmap->n,nsends_mpi,nrecvs_mpi;
540:   MPIAIJ_MPIDense   *contents;
541:   Mat               workB;
542:   MPI_Datatype      *stype,*rtype;
543:   PetscInt          blda;

546:   MatCheckProduct(C,4);
547:   if (!C->product->data) SETERRQ(PetscObjectComm((PetscObject)C),PETSC_ERR_PLIB,"Product data empty");
548:   contents = (MPIAIJ_MPIDense*)C->product->data;
549:   VecScatterGetRemote_Private(ctx,PETSC_TRUE/*send*/,&nsends,&sstarts,&sindices,&sprocs,NULL/*bs*/);
550:   VecScatterGetRemoteOrdered_Private(ctx,PETSC_FALSE/*recv*/,&nrecvs,&rstarts,NULL,&rprocs,NULL/*bs*/);
551:   PetscMPIIntCast(nsends,&nsends_mpi);
552:   PetscMPIIntCast(nrecvs,&nrecvs_mpi);
553:   if (Bbidx == 0) {
554:     workB = *outworkB = contents->workB;
555:   } else {
556:     workB = *outworkB = contents->workB1;
557:   }
558:   if (nrows != workB->rmap->n) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_PLIB,"Number of rows of workB %D not equal to columns of aij->B %D",workB->cmap->n,nrows);
559:   swaits = contents->swaits;
560:   rwaits = contents->rwaits;

562:   MatDenseGetArrayRead(B,&b);
563:   MatDenseGetLDA(B,&blda);
564:   if (blda != contents->blda) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,"Cannot reuse an input matrix with lda %D != %D",blda,contents->blda);
565:   MatDenseGetArray(workB,&rvalues);

567:   /* Post recv, use MPI derived data type to save memory */
568:   PetscObjectGetComm((PetscObject)C,&comm);
569:   rtype = contents->rtype;
570:   for (i=0; i<nrecvs; i++) {
571:     MPI_Irecv(rvalues+(rstarts[i]-rstarts[0]),ncols,rtype[i],rprocs[i],tag,comm,rwaits+i);
572:   }

574:   stype = contents->stype;
575:   for (i=0; i<nsends; i++) {
576:     MPI_Isend(b,ncols,stype[i],sprocs[i],tag,comm,swaits+i);
577:   }

579:   if (nrecvs) {MPI_Waitall(nrecvs_mpi,rwaits,MPI_STATUSES_IGNORE);}
580:   if (nsends) {MPI_Waitall(nsends_mpi,swaits,MPI_STATUSES_IGNORE);}

582:   VecScatterRestoreRemote_Private(ctx,PETSC_TRUE/*send*/,&nsends,&sstarts,&sindices,&sprocs,NULL);
583:   VecScatterRestoreRemoteOrdered_Private(ctx,PETSC_FALSE/*recv*/,&nrecvs,&rstarts,NULL,&rprocs,NULL);
584:   MatDenseRestoreArrayRead(B,&b);
585:   MatDenseRestoreArray(workB,&rvalues);
586:   return(0);
587: }

589: static PetscErrorCode MatMatMultNumeric_MPIAIJ_MPIDense(Mat A,Mat B,Mat C)
590: {
591:   PetscErrorCode  ierr;
592:   Mat_MPIAIJ      *aij    = (Mat_MPIAIJ*)A->data;
593:   Mat_MPIDense    *bdense = (Mat_MPIDense*)B->data;
594:   Mat_MPIDense    *cdense = (Mat_MPIDense*)C->data;
595:   Mat             workB;
596:   MPIAIJ_MPIDense *contents;

599:   MatCheckProduct(C,3);
600:   if (!C->product->data) SETERRQ(PetscObjectComm((PetscObject)C),PETSC_ERR_PLIB,"Product data empty");
601:   contents = (MPIAIJ_MPIDense*)C->product->data;
602:   /* diagonal block of A times all local rows of B */
603:   /* TODO: this calls a symbolic multiplication every time, which could be avoided */
604:   MatMatMult(aij->A,bdense->A,MAT_REUSE_MATRIX,PETSC_DEFAULT,&cdense->A);
605:   if (contents->workB->cmap->n == B->cmap->N) {
606:     /* get off processor parts of B needed to complete C=A*B */
607:     MatMPIDenseScatter(A,B,0,C,&workB);

609:     /* off-diagonal block of A times nonlocal rows of B */
610:     MatMatMultNumericAdd_SeqAIJ_SeqDense(aij->B,workB,cdense->A,PETSC_TRUE);
611:   } else {
612:     Mat      Bb,Cb;
613:     PetscInt BN=B->cmap->N,n=contents->workB->cmap->n,i;
614:     if (n <= 0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,"Column block size %D must be positive",n);

616:     for (i=0; i<BN; i+=n) {
617:       MatDenseGetSubMatrix(B,i,PetscMin(i+n,BN),&Bb);
618:       MatDenseGetSubMatrix(C,i,PetscMin(i+n,BN),&Cb);

620:       /* get off processor parts of B needed to complete C=A*B */
621:       MatMPIDenseScatter(A,Bb,i+n>BN,C,&workB);

623:       /* off-diagonal block of A times nonlocal rows of B */
624:       cdense = (Mat_MPIDense*)Cb->data;
625:       MatMatMultNumericAdd_SeqAIJ_SeqDense(aij->B,workB,cdense->A,PETSC_TRUE);

627:       MatDenseRestoreSubMatrix(B,&Bb);
628:       MatDenseRestoreSubMatrix(C,&Cb);
629:     }
630:   }
631:   return(0);
632: }

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

656:   MatCheckProduct(C,3);
657:   ptap = (Mat_APMPI*)C->product->data;
658:   if (!ptap) SETERRQ(PetscObjectComm((PetscObject)C),PETSC_ERR_ARG_WRONGSTATE,"PtAP cannot be computed. Missing data");
659:   PetscObjectGetComm((PetscObject)C,&comm);
660:   MPI_Comm_size(comm,&size);
661:   if (!ptap->P_oth && size>1) SETERRQ(PetscObjectComm((PetscObject)C),PETSC_ERR_ARG_WRONGSTATE,"AP cannot be reused. Do not call MatProductClear()");

663:   apa_sparse = ptap->apa;

665:   /* 1) get P_oth = ptap->P_oth  and P_loc = ptap->P_loc */
666:   /*-----------------------------------------------------*/
667:   /* update numerical values of P_oth and P_loc */
668:   MatGetBrowsOfAoCols_MPIAIJ(A,P,MAT_REUSE_MATRIX,&ptap->startsj_s,&ptap->startsj_r,&ptap->bufa,&ptap->P_oth);
669:   MatMPIAIJGetLocalMat(P,MAT_REUSE_MATRIX,&ptap->P_loc);

671:   /* 2) compute numeric C_loc = A_loc*P = Ad*P_loc + Ao*P_oth */
672:   /*----------------------------------------------------------*/
673:   /* get data from symbolic products */
674:   p_loc = (Mat_SeqAIJ*)(ptap->P_loc)->data;
675:   pi_loc = p_loc->i; pj_loc = p_loc->j; pa_loc = p_loc->a;
676:   if (size >1) {
677:     p_oth = (Mat_SeqAIJ*)(ptap->P_oth)->data;
678:     pi_oth = p_oth->i; pj_oth = p_oth->j; pa_oth = p_oth->a;
679:   } else {
680:     p_oth = NULL; pi_oth = NULL; pj_oth = NULL; pa_oth = NULL;
681:   }

683:   /* trigger copy to CPU */
684:   MatSeqAIJGetArrayRead(a->A,&dummy);
685:   MatSeqAIJRestoreArrayRead(a->A,&dummy);
686:   MatSeqAIJGetArrayRead(a->B,&dummy);
687:   MatSeqAIJRestoreArrayRead(a->B,&dummy);
688:   api = ptap->api;
689:   apj = ptap->apj;
690:   for (i=0; i<cm; i++) {
691:     apJ = apj + api[i];

693:     /* diagonal portion of A */
694:     anz = adi[i+1] - adi[i];
695:     adj = ad->j + adi[i];
696:     ada = ad->a + adi[i];
697:     for (j=0; j<anz; j++) {
698:       row = adj[j];
699:       pnz = pi_loc[row+1] - pi_loc[row];
700:       pj  = pj_loc + pi_loc[row];
701:       pa  = pa_loc + pi_loc[row];
702:       /* perform sparse axpy */
703:       valtmp = ada[j];
704:       nextp  = 0;
705:       for (k=0; nextp<pnz; k++) {
706:         if (apJ[k] == pj[nextp]) { /* column of AP == column of P */
707:           apa_sparse[k] += valtmp*pa[nextp++];
708:         }
709:       }
710:       PetscLogFlops(2.0*pnz);
711:     }

713:     /* off-diagonal portion of A */
714:     anz = aoi[i+1] - aoi[i];
715:     aoj = ao->j + aoi[i];
716:     aoa = ao->a + aoi[i];
717:     for (j=0; j<anz; j++) {
718:       row = aoj[j];
719:       pnz = pi_oth[row+1] - pi_oth[row];
720:       pj  = pj_oth + pi_oth[row];
721:       pa  = pa_oth + pi_oth[row];
722:       /* perform sparse axpy */
723:       valtmp = aoa[j];
724:       nextp  = 0;
725:       for (k=0; nextp<pnz; k++) {
726:         if (apJ[k] == pj[nextp]) { /* column of AP == column of P */
727:           apa_sparse[k] += valtmp*pa[nextp++];
728:         }
729:       }
730:       PetscLogFlops(2.0*pnz);
731:     }

733:     /* set values in C */
734:     cdnz = cd->i[i+1] - cd->i[i];
735:     conz = co->i[i+1] - co->i[i];

737:     /* 1st off-diagonal part of C */
738:     ca = coa + co->i[i];
739:     k  = 0;
740:     for (k0=0; k0<conz; k0++) {
741:       if (apJ[k] >= cstart) break;
742:       ca[k0]        = apa_sparse[k];
743:       apa_sparse[k] = 0.0;
744:       k++;
745:     }

747:     /* diagonal part of C */
748:     ca = cda + cd->i[i];
749:     for (k1=0; k1<cdnz; k1++) {
750:       ca[k1]        = apa_sparse[k];
751:       apa_sparse[k] = 0.0;
752:       k++;
753:     }

755:     /* 2nd off-diagonal part of C */
756:     ca = coa + co->i[i];
757:     for (; k0<conz; k0++) {
758:       ca[k0]        = apa_sparse[k];
759:       apa_sparse[k] = 0.0;
760:       k++;
761:     }
762:   }
763:   MatAssemblyBegin(C,MAT_FINAL_ASSEMBLY);
764:   MatAssemblyEnd(C,MAT_FINAL_ASSEMBLY);
765:   return(0);
766: }

768: /* same as MatMatMultSymbolic_MPIAIJ_MPIAIJ_nonscalable(), except using LLCondensed to avoid O(BN) memory requirement */
769: PetscErrorCode MatMatMultSymbolic_MPIAIJ_MPIAIJ(Mat A,Mat P,PetscReal fill,Mat C)
770: {
771:   PetscErrorCode     ierr;
772:   MPI_Comm           comm;
773:   PetscMPIInt        size;
774:   Mat_APMPI          *ptap;
775:   PetscFreeSpaceList free_space = NULL,current_space=NULL;
776:   Mat_MPIAIJ         *a  = (Mat_MPIAIJ*)A->data;
777:   Mat_SeqAIJ         *ad = (Mat_SeqAIJ*)(a->A)->data,*ao=(Mat_SeqAIJ*)(a->B)->data,*p_loc,*p_oth;
778:   PetscInt           *pi_loc,*pj_loc,*pi_oth,*pj_oth,*dnz,*onz;
779:   PetscInt           *adi=ad->i,*adj=ad->j,*aoi=ao->i,*aoj=ao->j,rstart=A->rmap->rstart;
780:   PetscInt           i,pnz,row,*api,*apj,*Jptr,apnz,nspacedouble=0,j,nzi,*lnk,apnz_max=1;
781:   PetscInt           am=A->rmap->n,pn=P->cmap->n,pm=P->rmap->n,lsize=pn+20;
782:   PetscReal          afill;
783:   MatType            mtype;

786:   MatCheckProduct(C,4);
787:   if (C->product->data) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_PLIB,"Extra product struct not empty");
788:   PetscObjectGetComm((PetscObject)A,&comm);
789:   MPI_Comm_size(comm,&size);

791:   /* create struct Mat_APMPI and attached it to C later */
792:   PetscNew(&ptap);

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

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

800:   p_loc  = (Mat_SeqAIJ*)(ptap->P_loc)->data;
801:   pi_loc = p_loc->i; pj_loc = p_loc->j;
802:   if (size > 1) {
803:     p_oth  = (Mat_SeqAIJ*)(ptap->P_oth)->data;
804:     pi_oth = p_oth->i; pj_oth = p_oth->j;
805:   } else {
806:     p_oth  = NULL;
807:     pi_oth = NULL; pj_oth = NULL;
808:   }

810:   /* first, compute symbolic AP = A_loc*P = A_diag*P_loc + A_off*P_oth */
811:   /*-------------------------------------------------------------------*/
812:   PetscMalloc1(am+2,&api);
813:   ptap->api = api;
814:   api[0]    = 0;

816:   PetscLLCondensedCreate_Scalable(lsize,&lnk);

818:   /* Initial FreeSpace size is fill*(nnz(A)+nnz(P)) */
819:   PetscFreeSpaceGet(PetscRealIntMultTruncate(fill,PetscIntSumTruncate(adi[am],PetscIntSumTruncate(aoi[am],pi_loc[pm]))),&free_space);
820:   current_space = free_space;
821:   MatPreallocateInitialize(comm,am,pn,dnz,onz);
822:   for (i=0; i<am; i++) {
823:     /* diagonal portion of A */
824:     nzi = adi[i+1] - adi[i];
825:     for (j=0; j<nzi; j++) {
826:       row  = *adj++;
827:       pnz  = pi_loc[row+1] - pi_loc[row];
828:       Jptr = pj_loc + pi_loc[row];
829:       /* Expand list if it is not long enough */
830:       if (pnz+apnz_max > lsize) {
831:         lsize = pnz+apnz_max;
832:         PetscLLCondensedExpand_Scalable(lsize, &lnk);
833:       }
834:       /* add non-zero cols of P into the sorted linked list lnk */
835:       PetscLLCondensedAddSorted_Scalable(pnz,Jptr,lnk);
836:       apnz     = *lnk; /* The first element in the list is the number of items in the list */
837:       api[i+1] = api[i] + apnz;
838:       if (apnz > apnz_max) apnz_max = apnz + 1; /* '1' for diagonal entry */
839:     }
840:     /* off-diagonal portion of A */
841:     nzi = aoi[i+1] - aoi[i];
842:     for (j=0; j<nzi; j++) {
843:       row  = *aoj++;
844:       pnz  = pi_oth[row+1] - pi_oth[row];
845:       Jptr = pj_oth + pi_oth[row];
846:       /* Expand list if it is not long enough */
847:       if (pnz+apnz_max > lsize) {
848:         lsize = pnz + apnz_max;
849:         PetscLLCondensedExpand_Scalable(lsize, &lnk);
850:       }
851:       /* add non-zero cols of P into the sorted linked list lnk */
852:       PetscLLCondensedAddSorted_Scalable(pnz,Jptr,lnk);
853:       apnz     = *lnk;  /* The first element in the list is the number of items in the list */
854:       api[i+1] = api[i] + apnz;
855:       if (apnz > apnz_max) apnz_max = apnz + 1; /* '1' for diagonal entry */
856:     }

858:     /* add missing diagonal entry */
859:     if (C->force_diagonals) {
860:       j = i + rstart; /* column index */
861:       PetscLLCondensedAddSorted_Scalable(1,&j,lnk);
862:     }

864:     apnz     = *lnk;
865:     api[i+1] = api[i] + apnz;
866:     if (apnz > apnz_max) apnz_max = apnz;

868:     /* if free space is not available, double the total space in the list */
869:     if (current_space->local_remaining<apnz) {
870:       PetscFreeSpaceGet(PetscIntSumTruncate(apnz,current_space->total_array_size),&current_space);
871:       nspacedouble++;
872:     }

874:     /* Copy data into free space, then initialize lnk */
875:     PetscLLCondensedClean_Scalable(apnz,current_space->array,lnk);
876:     MatPreallocateSet(i+rstart,apnz,current_space->array,dnz,onz);

878:     current_space->array           += apnz;
879:     current_space->local_used      += apnz;
880:     current_space->local_remaining -= apnz;
881:   }

883:   /* Allocate space for apj, initialize apj, and */
884:   /* destroy list of free space and other temporary array(s) */
885:   PetscMalloc1(api[am]+1,&ptap->apj);
886:   apj  = ptap->apj;
887:   PetscFreeSpaceContiguous(&free_space,ptap->apj);
888:   PetscLLCondensedDestroy_Scalable(lnk);

890:   /* create and assemble symbolic parallel matrix C */
891:   /*----------------------------------------------------*/
892:   MatSetSizes(C,am,pn,PETSC_DETERMINE,PETSC_DETERMINE);
893:   MatSetBlockSizesFromMats(C,A,P);
894:   MatGetType(A,&mtype);
895:   MatSetType(C,mtype);
896:   MatMPIAIJSetPreallocation(C,0,dnz,0,onz);
897:   MatPreallocateFinalize(dnz,onz);

899:   /* malloc apa for assembly C */
900:   PetscCalloc1(apnz_max,&ptap->apa);

902:   MatSetValues_MPIAIJ_CopyFromCSRFormat_Symbolic(C, apj, api);
903:   MatAssemblyBegin(C,MAT_FINAL_ASSEMBLY);
904:   MatAssemblyEnd(C,MAT_FINAL_ASSEMBLY);
905:   MatSetOption(C,MAT_NEW_NONZERO_LOCATION_ERR,PETSC_TRUE);

907:   C->ops->matmultnumeric = MatMatMultNumeric_MPIAIJ_MPIAIJ;
908:   C->ops->productnumeric = MatProductNumeric_AB;

910:   /* attach the supporting struct to C for reuse */
911:   C->product->data    = ptap;
912:   C->product->destroy = MatDestroy_MPIAIJ_MatMatMult;

914:   /* set MatInfo */
915:   afill = (PetscReal)api[am]/(adi[am]+aoi[am]+pi_loc[pm]+1) + 1.e-5;
916:   if (afill < 1.0) afill = 1.0;
917:   C->info.mallocs           = nspacedouble;
918:   C->info.fill_ratio_given  = fill;
919:   C->info.fill_ratio_needed = afill;

921: #if defined(PETSC_USE_INFO)
922:   if (api[am]) {
923:     PetscInfo3(C,"Reallocs %D; Fill ratio: given %g needed %g.\n",nspacedouble,(double)fill,(double)afill);
924:     PetscInfo1(C,"Use MatMatMult(A,B,MatReuse,%g,&C) for best performance.;\n",(double)afill);
925:   } else {
926:     PetscInfo(C,"Empty matrix product\n");
927:   }
928: #endif
929:   return(0);
930: }

932: /* This function is needed for the seqMPI matrix-matrix multiplication.  */
933: /* Three input arrays are merged to one output array. The size of the    */
934: /* output array is also output. Duplicate entries only show up once.     */
935: static void Merge3SortedArrays(PetscInt  size1, PetscInt *in1,
936:                                PetscInt  size2, PetscInt *in2,
937:                                PetscInt  size3, PetscInt *in3,
938:                                PetscInt *size4, PetscInt *out)
939: {
940:   int i = 0, j = 0, k = 0, l = 0;

942:   /* Traverse all three arrays */
943:   while (i<size1 && j<size2 && k<size3) {
944:     if (in1[i] < in2[j] && in1[i] < in3[k]) {
945:       out[l++] = in1[i++];
946:     }
947:     else if (in2[j] < in1[i] && in2[j] < in3[k]) {
948:       out[l++] = in2[j++];
949:     }
950:     else if (in3[k] < in1[i] && in3[k] < in2[j]) {
951:       out[l++] = in3[k++];
952:     }
953:     else if (in1[i] == in2[j] && in1[i] < in3[k]) {
954:       out[l++] = in1[i];
955:       i++, j++;
956:     }
957:     else if (in1[i] == in3[k] && in1[i] < in2[j]) {
958:       out[l++] = in1[i];
959:       i++, k++;
960:     }
961:     else if (in3[k] == in2[j] && in2[j] < in1[i])  {
962:       out[l++] = in2[j];
963:       k++, j++;
964:     }
965:     else if (in1[i] == in2[j] && in1[i] == in3[k]) {
966:       out[l++] = in1[i];
967:       i++, j++, k++;
968:     }
969:   }

971:   /* Traverse two remaining arrays */
972:   while (i<size1 && j<size2) {
973:     if (in1[i] < in2[j]) {
974:       out[l++] = in1[i++];
975:     }
976:     else if (in1[i] > in2[j]) {
977:       out[l++] = in2[j++];
978:     }
979:     else {
980:       out[l++] = in1[i];
981:       i++, j++;
982:     }
983:   }

985:   while (i<size1 && k<size3) {
986:     if (in1[i] < in3[k]) {
987:       out[l++] = in1[i++];
988:     }
989:     else if (in1[i] > in3[k]) {
990:       out[l++] = in3[k++];
991:     }
992:     else {
993:       out[l++] = in1[i];
994:       i++, k++;
995:     }
996:   }

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

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

1016:   *size4 = l;
1017: }

1019: /* This matrix-matrix multiplication algorithm divides the multiplication into three multiplications and  */
1020: /* adds up the products. Two of these three multiplications are performed with existing (sequential)      */
1021: /* matrix-matrix multiplications.  */
1022: PetscErrorCode MatMatMultSymbolic_MPIAIJ_MPIAIJ_seqMPI(Mat A, Mat P, PetscReal fill, Mat C)
1023: {
1024:   PetscErrorCode     ierr;
1025:   MPI_Comm           comm;
1026:   PetscMPIInt        size;
1027:   Mat_APMPI          *ptap;
1028:   PetscFreeSpaceList free_space_diag=NULL, current_space=NULL;
1029:   Mat_MPIAIJ         *a  =(Mat_MPIAIJ*)A->data;
1030:   Mat_SeqAIJ         *ad =(Mat_SeqAIJ*)(a->A)->data,*ao=(Mat_SeqAIJ*)(a->B)->data,*p_loc;
1031:   Mat_MPIAIJ         *p  =(Mat_MPIAIJ*)P->data;
1032:   Mat_SeqAIJ         *adpd_seq, *p_off, *aopoth_seq;
1033:   PetscInt           adponz, adpdnz;
1034:   PetscInt           *pi_loc,*dnz,*onz;
1035:   PetscInt           *adi=ad->i,*adj=ad->j,*aoi=ao->i,rstart=A->rmap->rstart;
1036:   PetscInt           *lnk,i, i1=0,pnz,row,*adpoi,*adpoj, *api, *adpoJ, *aopJ, *apJ,*Jptr, aopnz, nspacedouble=0,j,nzi,
1037:                      *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;

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

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

1057:   /* get P_oth by taking rows of P (= non-zero cols of local A) from other processors */
1058:   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:   MatMPIAIJGetLocalMat(P,MAT_INITIAL_MATRIX,&ptap->P_loc);


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

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

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

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

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

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

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

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

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


1103:   /* Symbolic calc of the A_diag * p_loc_off */
1104:   /* Initial FreeSpace size is fill*(nnz(A)+nnz(P)) */
1105:   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++) {
1116:         j_temp[i1] = p->garray[Jptr[i1]];
1117:       }
1118:       /* add non-zero cols of P into the sorted linked list lnk */
1119:       PetscLLCondensedAddSorted(pnz,j_temp,lnk,lnkbt);
1120:     }

1122:     adponz     = lnk[0];
1123:     adpoi[i+1] = adpoi[i] + adponz;

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

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

1134:     current_space->array           += adponz;
1135:     current_space->local_used      += adponz;
1136:     current_space->local_remaining -= adponz;
1137:   }

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

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

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

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

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

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

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

1178:     aopJ += aopnz;
1179:     adpoJ += adponz;
1180:     adpdJ += adpdnz;
1181:     apJ += apnz;
1182:     api[i+1] = api[i] + apnz;
1183:   }

1185:   /* malloc apa to store dense row A[i,:]*P */
1186:   PetscCalloc1(pN+2,&ptap->apa);

1188:   /* create and assemble symbolic parallel matrix C */
1189:   MatSetSizes(C,am,pn,PETSC_DETERMINE,PETSC_DETERMINE);
1190:   MatSetBlockSizesFromMats(C,A,P);
1191:   MatGetType(A,&mtype);
1192:   MatSetType(C,mtype);
1193:   MatMPIAIJSetPreallocation(C,0,dnz,0,onz);
1194:   MatPreallocateFinalize(dnz,onz);

1196:   MatSetValues_MPIAIJ_CopyFromCSRFormat_Symbolic(C, apj, api);
1197:   MatAssemblyBegin(C,MAT_FINAL_ASSEMBLY);
1198:   MatAssemblyEnd(C,MAT_FINAL_ASSEMBLY);
1199:   MatSetOption(C,MAT_NEW_NONZERO_LOCATION_ERR,PETSC_TRUE);

1201:   C->ops->matmultnumeric = MatMatMultNumeric_MPIAIJ_MPIAIJ_nonscalable;
1202:   C->ops->productnumeric = MatProductNumeric_AB;

1204:   /* attach the supporting struct to C for reuse */
1205:   C->product->data    = ptap;
1206:   C->product->destroy = MatDestroy_MPIAIJ_MatMatMult;

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

1215: #if defined(PETSC_USE_INFO)
1216:   if (api[am]) {
1217:     PetscInfo3(C,"Reallocs %D; Fill ratio: given %g needed %g.\n",nspacedouble,(double)fill,(double)afill);
1218:     PetscInfo1(C,"Use MatMatMult(A,B,MatReuse,%g,&C) for best performance.;\n",(double)afill);
1219:   } else {
1220:     PetscInfo(C,"Empty matrix product\n");
1221:   }
1222: #endif

1224:   MatDestroy(&aopoth);
1225:   MatDestroy(&adpd);
1226:   PetscFree(j_temp);
1227:   PetscFree(adpoj);
1228:   PetscFree(adpoi);
1229:   return(0);
1230: }

1232: /*-------------------------------------------------------------------------*/
1233: /* This routine only works when scall=MAT_REUSE_MATRIX! */
1234: PetscErrorCode MatTransposeMatMultNumeric_MPIAIJ_MPIAIJ_matmatmult(Mat P,Mat A,Mat C)
1235: {
1237:   Mat_APMPI      *ptap;
1238:   Mat            Pt;

1241:   MatCheckProduct(C,3);
1242:   ptap = (Mat_APMPI*)C->product->data;
1243:   if (!ptap) SETERRQ(PetscObjectComm((PetscObject)C),PETSC_ERR_ARG_WRONGSTATE,"PtAP cannot be computed. Missing data");
1244:   if (!ptap->Pt) SETERRQ(PetscObjectComm((PetscObject)C),PETSC_ERR_ARG_WRONGSTATE,"PtA cannot be reused. Do not call MatProductClear()");

1246:   Pt   = ptap->Pt;
1247:   MatTranspose(P,MAT_REUSE_MATRIX,&Pt);
1248:   MatMatMultNumeric_MPIAIJ_MPIAIJ(Pt,A,C);
1249:   return(0);
1250: }

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

1281:   PetscObjectGetComm((PetscObject)A,&comm);
1282:   MPI_Comm_size(comm,&size);
1283:   MPI_Comm_rank(comm,&rank);

1285:   /* create symbolic parallel matrix C */
1286:   MatGetType(A,&mtype);
1287:   MatSetType(C,mtype);

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

1291:   /* create struct Mat_APMPI and attached it to C later */
1292:   PetscNew(&ptap);
1293:   ptap->reuse = MAT_INITIAL_MATRIX;

1295:   /* (0) compute Rd = Pd^T, Ro = Po^T  */
1296:   /* --------------------------------- */
1297:   MatTranspose_SeqAIJ(p->A,MAT_INITIAL_MATRIX,&ptap->Rd);
1298:   MatTranspose_SeqAIJ(p->B,MAT_INITIAL_MATRIX,&ptap->Ro);

1300:   /* (1) compute symbolic A_loc */
1301:   /* ---------------------------*/
1302:   MatMPIAIJGetLocalMat(A,MAT_INITIAL_MATRIX,&ptap->A_loc);

1304:   /* (2-1) compute symbolic C_oth = Ro*A_loc  */
1305:   /* ------------------------------------ */
1306:   MatGetOptionsPrefix(A,&prefix);
1307:   MatSetOptionsPrefix(ptap->Ro,prefix);
1308:   MatAppendOptionsPrefix(ptap->Ro,"inner_offdiag_");
1309:   MatCreate(PETSC_COMM_SELF,&ptap->C_oth);
1310:   MatMatMultSymbolic_SeqAIJ_SeqAIJ(ptap->Ro,ptap->A_loc,fill,ptap->C_oth);

1312:   /* (3) send coj of C_oth to other processors  */
1313:   /* ------------------------------------------ */
1314:   /* determine row ownership */
1315:   PetscLayoutCreate(comm,&rowmap);
1316:   rowmap->n  = pn;
1317:   rowmap->bs = 1;
1318:   PetscLayoutSetUp(rowmap);
1319:   owners = rowmap->range;

1321:   /* determine the number of messages to send, their lengths */
1322:   PetscMalloc4(size,&len_s,size,&len_si,size,&sstatus,size+2,&owners_co);
1323:   PetscArrayzero(len_s,size);
1324:   PetscArrayzero(len_si,size);

1326:   c_oth = (Mat_SeqAIJ*)ptap->C_oth->data;
1327:   coi   = c_oth->i; coj = c_oth->j;
1328:   con   = ptap->C_oth->rmap->n;
1329:   proc  = 0;
1330:   for (i=0; i<con; i++) {
1331:     while (prmap[i] >= owners[proc+1]) proc++;
1332:     len_si[proc]++;               /* num of rows in Co(=Pt*A) to be sent to [proc] */
1333:     len_s[proc] += coi[i+1] - coi[i]; /* num of nonzeros in Co to be sent to [proc] */
1334:   }

1336:   len          = 0; /* max length of buf_si[], see (4) */
1337:   owners_co[0] = 0;
1338:   nsend        = 0;
1339:   for (proc=0; proc<size; proc++) {
1340:     owners_co[proc+1] = owners_co[proc] + len_si[proc];
1341:     if (len_s[proc]) {
1342:       nsend++;
1343:       len_si[proc] = 2*(len_si[proc] + 1); /* length of buf_si to be sent to [proc] */
1344:       len         += len_si[proc];
1345:     }
1346:   }

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

1352:   /* post the Irecv and Isend of coj */
1353:   PetscCommGetNewTag(comm,&tagj);
1354:   PetscPostIrecvInt(comm,tagj,nrecv,id_r,len_r,&buf_rj,&rwaits);
1355:   PetscMalloc1(nsend+1,&swaits);
1356:   for (proc=0, k=0; proc<size; proc++) {
1357:     if (!len_s[proc]) continue;
1358:     i    = owners_co[proc];
1359:     MPI_Isend(coj+coi[i],len_s[proc],MPIU_INT,proc,tagj,comm,swaits+k);
1360:     k++;
1361:   }

1363:   /* (2-2) compute symbolic C_loc = Rd*A_loc */
1364:   /* ---------------------------------------- */
1365:   MatSetOptionsPrefix(ptap->Rd,prefix);
1366:   MatAppendOptionsPrefix(ptap->Rd,"inner_diag_");
1367:   MatCreate(PETSC_COMM_SELF,&ptap->C_loc);
1368:   MatMatMultSymbolic_SeqAIJ_SeqAIJ(ptap->Rd,ptap->A_loc,fill,ptap->C_loc);
1369:   c_loc = (Mat_SeqAIJ*)ptap->C_loc->data;

1371:   /* receives coj are complete */
1372:   for (i=0; i<nrecv; i++) {
1373:     MPI_Waitany(nrecv,rwaits,&icompleted,&rstatus);
1374:   }
1375:   PetscFree(rwaits);
1376:   if (nsend) {MPI_Waitall(nsend,swaits,sstatus);}

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

1381:   /* create and initialize a linked list */
1382:   PetscTableCreate(an,aN,&ta); /* for compute Crmax */
1383:   MatRowMergeMax_SeqAIJ(a_loc,ptap->A_loc->rmap->N,ta);

1385:   for (k=0; k<nrecv; k++) {/* k-th received message */
1386:     Jptr = buf_rj[k];
1387:     for (j=0; j<len_r[k]; j++) {
1388:       PetscTableAdd(ta,*(Jptr+j)+1,1,INSERT_VALUES);
1389:     }
1390:   }
1391:   PetscTableGetCount(ta,&Crmax);
1392:   PetscTableDestroy(&ta);

1394:   /* (4) send and recv coi */
1395:   /*-----------------------*/
1396:   PetscCommGetNewTag(comm,&tagi);
1397:   PetscPostIrecvInt(comm,tagi,nrecv,id_r,len_ri,&buf_ri,&rwaits);
1398:   PetscMalloc1(len+1,&buf_s);
1399:   buf_si = buf_s;  /* points to the beginning of k-th msg to be sent */
1400:   for (proc=0,k=0; proc<size; proc++) {
1401:     if (!len_s[proc]) continue;
1402:     /* form outgoing message for i-structure:
1403:          buf_si[0]:                 nrows to be sent
1404:                [1:nrows]:           row index (global)
1405:                [nrows+1:2*nrows+1]: i-structure index
1406:     */
1407:     /*-------------------------------------------*/
1408:     nrows       = len_si[proc]/2 - 1; /* num of rows in Co to be sent to [proc] */
1409:     buf_si_i    = buf_si + nrows+1;
1410:     buf_si[0]   = nrows;
1411:     buf_si_i[0] = 0;
1412:     nrows       = 0;
1413:     for (i=owners_co[proc]; i<owners_co[proc+1]; i++) {
1414:       nzi = coi[i+1] - coi[i];
1415:       buf_si_i[nrows+1] = buf_si_i[nrows] + nzi;  /* i-structure */
1416:       buf_si[nrows+1]   = prmap[i] -owners[proc]; /* local row index */
1417:       nrows++;
1418:     }
1419:     MPI_Isend(buf_si,len_si[proc],MPIU_INT,proc,tagi,comm,swaits+k);
1420:     k++;
1421:     buf_si += len_si[proc];
1422:   }
1423:   for (i=0; i<nrecv; i++) {
1424:     MPI_Waitany(nrecv,rwaits,&icompleted,&rstatus);
1425:   }
1426:   PetscFree(rwaits);
1427:   if (nsend) {MPI_Waitall(nsend,swaits,sstatus);}

1429:   PetscFree4(len_s,len_si,sstatus,owners_co);
1430:   PetscFree(len_ri);
1431:   PetscFree(swaits);
1432:   PetscFree(buf_s);

1434:   /* (5) compute the local portion of C      */
1435:   /* ------------------------------------------ */
1436:   /* set initial free space to be Crmax, sufficient for holding nozeros in each row of C */
1437:   PetscFreeSpaceGet(Crmax,&free_space);
1438:   current_space = free_space;

1440:   PetscMalloc3(nrecv,&buf_ri_k,nrecv,&nextrow,nrecv,&nextci);
1441:   for (k=0; k<nrecv; k++) {
1442:     buf_ri_k[k] = buf_ri[k]; /* beginning of k-th recved i-structure */
1443:     nrows       = *buf_ri_k[k];
1444:     nextrow[k]  = buf_ri_k[k] + 1;  /* next row number of k-th recved i-structure */
1445:     nextci[k]   = buf_ri_k[k] + (nrows + 1); /* poins to the next i-structure of k-th recved i-structure  */
1446:   }

1448:   MatPreallocateInitialize(comm,pn,an,dnz,onz);
1449:   PetscLLCondensedCreate(Crmax,aN,&lnk,&lnkbt);
1450:   for (i=0; i<pn; i++) { /* for each local row of C */
1451:     /* add C_loc into C */
1452:     nzi  = c_loc->i[i+1] - c_loc->i[i];
1453:     Jptr = c_loc->j + c_loc->i[i];
1454:     PetscLLCondensedAddSorted(nzi,Jptr,lnk,lnkbt);

1456:     /* add received col data into lnk */
1457:     for (k=0; k<nrecv; k++) { /* k-th received message */
1458:       if (i == *nextrow[k]) { /* i-th row */
1459:         nzi  = *(nextci[k]+1) - *nextci[k];
1460:         Jptr = buf_rj[k] + *nextci[k];
1461:         PetscLLCondensedAddSorted(nzi,Jptr,lnk,lnkbt);
1462:         nextrow[k]++; nextci[k]++;
1463:       }
1464:     }

1466:     /* add missing diagonal entry */
1467:     if (C->force_diagonals) {
1468:       k = i + owners[rank]; /* column index */
1469:       PetscLLCondensedAddSorted(1,&k,lnk,lnkbt);
1470:     }

1472:     nzi = lnk[0];

1474:     /* copy data into free space, then initialize lnk */
1475:     PetscLLCondensedClean(aN,nzi,current_space->array,lnk,lnkbt);
1476:     MatPreallocateSet(i+owners[rank],nzi,current_space->array,dnz,onz);
1477:   }
1478:   PetscFree3(buf_ri_k,nextrow,nextci);
1479:   PetscLLDestroy(lnk,lnkbt);
1480:   PetscFreeSpaceDestroy(free_space);

1482:   /* local sizes and preallocation */
1483:   MatSetSizes(C,pn,an,PETSC_DETERMINE,PETSC_DETERMINE);
1484:   if (P->cmap->bs > 0) {PetscLayoutSetBlockSize(C->rmap,P->cmap->bs);}
1485:   if (A->cmap->bs > 0) {PetscLayoutSetBlockSize(C->cmap,A->cmap->bs);}
1486:   MatMPIAIJSetPreallocation(C,0,dnz,0,onz);
1487:   MatPreallocateFinalize(dnz,onz);

1489:   /* add C_loc and C_oth to C */
1490:   MatGetOwnershipRange(C,&rstart,NULL);
1491:   for (i=0; i<pn; i++) {
1492:     ncols = c_loc->i[i+1] - c_loc->i[i];
1493:     cols  = c_loc->j + c_loc->i[i];
1494:     row   = rstart + i;
1495:     MatSetValues(C,1,(const PetscInt*)&row,ncols,(const PetscInt*)cols,NULL,INSERT_VALUES);

1497:     if (C->force_diagonals) {
1498:       MatSetValues(C,1,(const PetscInt*)&row,1,(const PetscInt*)&row,NULL,INSERT_VALUES);
1499:     }
1500:   }
1501:   for (i=0; i<con; i++) {
1502:     ncols = c_oth->i[i+1] - c_oth->i[i];
1503:     cols  = c_oth->j + c_oth->i[i];
1504:     row   = prmap[i];
1505:     MatSetValues(C,1,(const PetscInt*)&row,ncols,(const PetscInt*)cols,NULL,INSERT_VALUES);
1506:   }
1507:   MatAssemblyBegin(C,MAT_FINAL_ASSEMBLY);
1508:   MatAssemblyEnd(C,MAT_FINAL_ASSEMBLY);
1509:   MatSetOption(C,MAT_NEW_NONZERO_LOCATION_ERR,PETSC_TRUE);

1511:   /* members in merge */
1512:   PetscFree(id_r);
1513:   PetscFree(len_r);
1514:   PetscFree(buf_ri[0]);
1515:   PetscFree(buf_ri);
1516:   PetscFree(buf_rj[0]);
1517:   PetscFree(buf_rj);
1518:   PetscLayoutDestroy(&rowmap);

1520:   /* attach the supporting struct to C for reuse */
1521:   C->product->data    = ptap;
1522:   C->product->destroy = MatDestroy_MPIAIJ_PtAP;
1523:   return(0);
1524: }

1526: PetscErrorCode MatTransposeMatMultNumeric_MPIAIJ_MPIAIJ_nonscalable(Mat P,Mat A,Mat C)
1527: {
1528:   PetscErrorCode    ierr;
1529:   Mat_MPIAIJ        *p=(Mat_MPIAIJ*)P->data;
1530:   Mat_SeqAIJ        *c_seq;
1531:   Mat_APMPI         *ptap;
1532:   Mat               A_loc,C_loc,C_oth;
1533:   PetscInt          i,rstart,rend,cm,ncols,row;
1534:   const PetscInt    *cols;
1535:   const PetscScalar *vals;

1538:   MatCheckProduct(C,3);
1539:   ptap = (Mat_APMPI*)C->product->data;
1540:   if (!ptap) SETERRQ(PetscObjectComm((PetscObject)C),PETSC_ERR_ARG_WRONGSTATE,"PtAP cannot be computed. Missing data");
1541:   if (!ptap->A_loc) SETERRQ(PetscObjectComm((PetscObject)C),PETSC_ERR_ARG_WRONGSTATE,"PtA cannot be reused. Do not call MatProductClear()");
1542:   MatZeroEntries(C);

1544:   if (ptap->reuse == MAT_REUSE_MATRIX) {
1545:     /* These matrices are obtained in MatTransposeMatMultSymbolic() */
1546:     /* 1) get R = Pd^T, Ro = Po^T */
1547:     /*----------------------------*/
1548:     MatTranspose_SeqAIJ(p->A,MAT_REUSE_MATRIX,&ptap->Rd);
1549:     MatTranspose_SeqAIJ(p->B,MAT_REUSE_MATRIX,&ptap->Ro);

1551:     /* 2) compute numeric A_loc */
1552:     /*--------------------------*/
1553:     MatMPIAIJGetLocalMat(A,MAT_REUSE_MATRIX,&ptap->A_loc);
1554:   }

1556:   /* 3) C_loc = Rd*A_loc, C_oth = Ro*A_loc */
1557:   A_loc = ptap->A_loc;
1558:   ((ptap->C_loc)->ops->matmultnumeric)(ptap->Rd,A_loc,ptap->C_loc);
1559:   ((ptap->C_oth)->ops->matmultnumeric)(ptap->Ro,A_loc,ptap->C_oth);
1560:   C_loc = ptap->C_loc;
1561:   C_oth = ptap->C_oth;

1563:   /* add C_loc and C_oth to C */
1564:   MatGetOwnershipRange(C,&rstart,&rend);

1566:   /* C_loc -> C */
1567:   cm    = C_loc->rmap->N;
1568:   c_seq = (Mat_SeqAIJ*)C_loc->data;
1569:   cols = c_seq->j;
1570:   vals = c_seq->a;
1571:   for (i=0; i<cm; i++) {
1572:     ncols = c_seq->i[i+1] - c_seq->i[i];
1573:     row = rstart + i;
1574:     MatSetValues(C,1,&row,ncols,cols,vals,ADD_VALUES);
1575:     cols += ncols; vals += ncols;
1576:   }

1578:   /* Co -> C, off-processor part */
1579:   cm    = C_oth->rmap->N;
1580:   c_seq = (Mat_SeqAIJ*)C_oth->data;
1581:   cols  = c_seq->j;
1582:   vals  = c_seq->a;
1583:   for (i=0; i<cm; i++) {
1584:     ncols = c_seq->i[i+1] - c_seq->i[i];
1585:     row = p->garray[i];
1586:     MatSetValues(C,1,&row,ncols,cols,vals,ADD_VALUES);
1587:     cols += ncols; vals += ncols;
1588:   }
1589:   MatAssemblyBegin(C,MAT_FINAL_ASSEMBLY);
1590:   MatAssemblyEnd(C,MAT_FINAL_ASSEMBLY);
1591:   MatSetOption(C,MAT_NEW_NONZERO_LOCATION_ERR,PETSC_TRUE);

1593:   ptap->reuse = MAT_REUSE_MATRIX;
1594:   return(0);
1595: }

1597: PetscErrorCode MatTransposeMatMultNumeric_MPIAIJ_MPIAIJ(Mat P,Mat A,Mat C)
1598: {
1599:   PetscErrorCode      ierr;
1600:   Mat_Merge_SeqsToMPI *merge;
1601:   Mat_MPIAIJ          *p =(Mat_MPIAIJ*)P->data;
1602:   Mat_SeqAIJ          *pd=(Mat_SeqAIJ*)(p->A)->data,*po=(Mat_SeqAIJ*)(p->B)->data;
1603:   Mat_APMPI           *ptap;
1604:   PetscInt            *adj;
1605:   PetscInt            i,j,k,anz,pnz,row,*cj,nexta;
1606:   MatScalar           *ada,*ca,valtmp;
1607:   PetscInt            am=A->rmap->n,cm=C->rmap->n,pon=(p->B)->cmap->n;
1608:   MPI_Comm            comm;
1609:   PetscMPIInt         size,rank,taga,*len_s;
1610:   PetscInt            *owners,proc,nrows,**buf_ri_k,**nextrow,**nextci;
1611:   PetscInt            **buf_ri,**buf_rj;
1612:   PetscInt            cnz=0,*bj_i,*bi,*bj,bnz,nextcj;  /* bi,bj,ba: local array of C(mpi mat) */
1613:   MPI_Request         *s_waits,*r_waits;
1614:   MPI_Status          *status;
1615:   MatScalar           **abuf_r,*ba_i,*pA,*coa,*ba;
1616:   const PetscScalar   *dummy;
1617:   PetscInt            *ai,*aj,*coi,*coj,*poJ,*pdJ;
1618:   Mat                 A_loc;
1619:   Mat_SeqAIJ          *a_loc;

1622:   MatCheckProduct(C,3);
1623:   ptap = (Mat_APMPI*)C->product->data;
1624:   if (!ptap) SETERRQ(PetscObjectComm((PetscObject)C),PETSC_ERR_ARG_WRONGSTATE,"PtAP cannot be computed. Missing data");
1625:   if (!ptap->A_loc) SETERRQ(PetscObjectComm((PetscObject)C),PETSC_ERR_ARG_WRONGSTATE,"PtA cannot be reused. Do not call MatProductClear()");
1626:   PetscObjectGetComm((PetscObject)C,&comm);
1627:   MPI_Comm_size(comm,&size);
1628:   MPI_Comm_rank(comm,&rank);

1630:   merge = ptap->merge;

1632:   /* 2) compute numeric C_seq = P_loc^T*A_loc */
1633:   /*------------------------------------------*/
1634:   /* get data from symbolic products */
1635:   coi    = merge->coi; coj = merge->coj;
1636:   PetscCalloc1(coi[pon]+1,&coa);
1637:   bi     = merge->bi; bj = merge->bj;
1638:   owners = merge->rowmap->range;
1639:   PetscCalloc1(bi[cm]+1,&ba);

1641:   /* get A_loc by taking all local rows of A */
1642:   A_loc = ptap->A_loc;
1643:   MatMPIAIJGetLocalMat(A,MAT_REUSE_MATRIX,&A_loc);
1644:   a_loc = (Mat_SeqAIJ*)(A_loc)->data;
1645:   ai    = a_loc->i;
1646:   aj    = a_loc->j;

1648:   /* trigger copy to CPU */
1649:   MatSeqAIJGetArrayRead(p->A,&dummy);
1650:   MatSeqAIJRestoreArrayRead(p->A,&dummy);
1651:   MatSeqAIJGetArrayRead(p->B,&dummy);
1652:   MatSeqAIJRestoreArrayRead(p->B,&dummy);
1653:   for (i=0; i<am; i++) {
1654:     anz = ai[i+1] - ai[i];
1655:     adj = aj + ai[i];
1656:     ada = a_loc->a + ai[i];

1658:     /* 2-b) Compute Cseq = P_loc[i,:]^T*A[i,:] using outer product */
1659:     /*-------------------------------------------------------------*/
1660:     /* put the value into Co=(p->B)^T*A (off-diagonal part, send to others) */
1661:     pnz = po->i[i+1] - po->i[i];
1662:     poJ = po->j + po->i[i];
1663:     pA  = po->a + po->i[i];
1664:     for (j=0; j<pnz; j++) {
1665:       row = poJ[j];
1666:       cj  = coj + coi[row];
1667:       ca  = coa + coi[row];
1668:       /* perform sparse axpy */
1669:       nexta  = 0;
1670:       valtmp = pA[j];
1671:       for (k=0; nexta<anz; k++) {
1672:         if (cj[k] == adj[nexta]) {
1673:           ca[k] += valtmp*ada[nexta];
1674:           nexta++;
1675:         }
1676:       }
1677:       PetscLogFlops(2.0*anz);
1678:     }

1680:     /* put the value into Cd (diagonal part) */
1681:     pnz = pd->i[i+1] - pd->i[i];
1682:     pdJ = pd->j + pd->i[i];
1683:     pA  = pd->a + pd->i[i];
1684:     for (j=0; j<pnz; j++) {
1685:       row = pdJ[j];
1686:       cj  = bj + bi[row];
1687:       ca  = ba + bi[row];
1688:       /* perform sparse axpy */
1689:       nexta  = 0;
1690:       valtmp = pA[j];
1691:       for (k=0; nexta<anz; k++) {
1692:         if (cj[k] == adj[nexta]) {
1693:           ca[k] += valtmp*ada[nexta];
1694:           nexta++;
1695:         }
1696:       }
1697:       PetscLogFlops(2.0*anz);
1698:     }
1699:   }

1701:   /* 3) send and recv matrix values coa */
1702:   /*------------------------------------*/
1703:   buf_ri = merge->buf_ri;
1704:   buf_rj = merge->buf_rj;
1705:   len_s  = merge->len_s;
1706:   PetscCommGetNewTag(comm,&taga);
1707:   PetscPostIrecvScalar(comm,taga,merge->nrecv,merge->id_r,merge->len_r,&abuf_r,&r_waits);

1709:   PetscMalloc2(merge->nsend+1,&s_waits,size,&status);
1710:   for (proc=0,k=0; proc<size; proc++) {
1711:     if (!len_s[proc]) continue;
1712:     i    = merge->owners_co[proc];
1713:     MPI_Isend(coa+coi[i],len_s[proc],MPIU_MATSCALAR,proc,taga,comm,s_waits+k);
1714:     k++;
1715:   }
1716:   if (merge->nrecv) {MPI_Waitall(merge->nrecv,r_waits,status);}
1717:   if (merge->nsend) {MPI_Waitall(merge->nsend,s_waits,status);}

1719:   PetscFree2(s_waits,status);
1720:   PetscFree(r_waits);
1721:   PetscFree(coa);

1723:   /* 4) insert local Cseq and received values into Cmpi */
1724:   /*----------------------------------------------------*/
1725:   PetscMalloc3(merge->nrecv,&buf_ri_k,merge->nrecv,&nextrow,merge->nrecv,&nextci);
1726:   for (k=0; k<merge->nrecv; k++) {
1727:     buf_ri_k[k] = buf_ri[k]; /* beginning of k-th recved i-structure */
1728:     nrows       = *(buf_ri_k[k]);
1729:     nextrow[k]  = buf_ri_k[k]+1;  /* next row number of k-th recved i-structure */
1730:     nextci[k]   = buf_ri_k[k] + (nrows + 1); /* poins to the next i-structure of k-th recved i-structure  */
1731:   }

1733:   for (i=0; i<cm; i++) {
1734:     row  = owners[rank] + i; /* global row index of C_seq */
1735:     bj_i = bj + bi[i];  /* col indices of the i-th row of C */
1736:     ba_i = ba + bi[i];
1737:     bnz  = bi[i+1] - bi[i];
1738:     /* add received vals into ba */
1739:     for (k=0; k<merge->nrecv; k++) { /* k-th received message */
1740:       /* i-th row */
1741:       if (i == *nextrow[k]) {
1742:         cnz    = *(nextci[k]+1) - *nextci[k];
1743:         cj     = buf_rj[k] + *(nextci[k]);
1744:         ca     = abuf_r[k] + *(nextci[k]);
1745:         nextcj = 0;
1746:         for (j=0; nextcj<cnz; j++) {
1747:           if (bj_i[j] == cj[nextcj]) { /* bcol == ccol */
1748:             ba_i[j] += ca[nextcj++];
1749:           }
1750:         }
1751:         nextrow[k]++; nextci[k]++;
1752:         PetscLogFlops(2.0*cnz);
1753:       }
1754:     }
1755:     MatSetValues(C,1,&row,bnz,bj_i,ba_i,INSERT_VALUES);
1756:   }
1757:   MatAssemblyBegin(C,MAT_FINAL_ASSEMBLY);
1758:   MatAssemblyEnd(C,MAT_FINAL_ASSEMBLY);

1760:   PetscFree(ba);
1761:   PetscFree(abuf_r[0]);
1762:   PetscFree(abuf_r);
1763:   PetscFree3(buf_ri_k,nextrow,nextci);
1764:   return(0);
1765: }

1767: PetscErrorCode MatTransposeMatMultSymbolic_MPIAIJ_MPIAIJ(Mat P,Mat A,PetscReal fill,Mat C)
1768: {
1769:   PetscErrorCode      ierr;
1770:   Mat                 A_loc;
1771:   Mat_APMPI           *ptap;
1772:   PetscFreeSpaceList  free_space=NULL,current_space=NULL;
1773:   Mat_MPIAIJ          *p=(Mat_MPIAIJ*)P->data,*a=(Mat_MPIAIJ*)A->data;
1774:   PetscInt            *pdti,*pdtj,*poti,*potj,*ptJ;
1775:   PetscInt            nnz;
1776:   PetscInt            *lnk,*owners_co,*coi,*coj,i,k,pnz,row;
1777:   PetscInt            am  =A->rmap->n,pn=P->cmap->n;
1778:   MPI_Comm            comm;
1779:   PetscMPIInt         size,rank,tagi,tagj,*len_si,*len_s,*len_ri;
1780:   PetscInt            **buf_rj,**buf_ri,**buf_ri_k;
1781:   PetscInt            len,proc,*dnz,*onz,*owners;
1782:   PetscInt            nzi,*bi,*bj;
1783:   PetscInt            nrows,*buf_s,*buf_si,*buf_si_i,**nextrow,**nextci;
1784:   MPI_Request         *swaits,*rwaits;
1785:   MPI_Status          *sstatus,rstatus;
1786:   Mat_Merge_SeqsToMPI *merge;
1787:   PetscInt            *ai,*aj,*Jptr,anz,*prmap=p->garray,pon,nspacedouble=0,j;
1788:   PetscReal           afill  =1.0,afill_tmp;
1789:   PetscInt            rstart = P->cmap->rstart,rmax,aN=A->cmap->N,Armax;
1790:   Mat_SeqAIJ          *a_loc;
1791:   PetscTable          ta;
1792:   MatType             mtype;

1795:   PetscObjectGetComm((PetscObject)A,&comm);
1796:   /* check if matrix local sizes are compatible */
1797:   if (A->rmap->rstart != P->rmap->rstart || A->rmap->rend != P->rmap->rend) SETERRQ4(comm,PETSC_ERR_ARG_SIZ,"Matrix local dimensions are incompatible, A (%D, %D) != P (%D,%D)",A->rmap->rstart,A->rmap->rend,P->rmap->rstart,P->rmap->rend);

1799:   MPI_Comm_size(comm,&size);
1800:   MPI_Comm_rank(comm,&rank);

1802:   /* create struct Mat_APMPI and attached it to C later */
1803:   PetscNew(&ptap);

1805:   /* get A_loc by taking all local rows of A */
1806:   MatMPIAIJGetLocalMat(A,MAT_INITIAL_MATRIX,&A_loc);

1808:   ptap->A_loc = A_loc;
1809:   a_loc       = (Mat_SeqAIJ*)(A_loc)->data;
1810:   ai          = a_loc->i;
1811:   aj          = a_loc->j;

1813:   /* determine symbolic Co=(p->B)^T*A - send to others */
1814:   /*----------------------------------------------------*/
1815:   MatGetSymbolicTranspose_SeqAIJ(p->A,&pdti,&pdtj);
1816:   MatGetSymbolicTranspose_SeqAIJ(p->B,&poti,&potj);
1817:   pon = (p->B)->cmap->n; /* total num of rows to be sent to other processors
1818:                          >= (num of nonzero rows of C_seq) - pn */
1819:   PetscMalloc1(pon+1,&coi);
1820:   coi[0] = 0;

1822:   /* set initial free space to be fill*(nnz(p->B) + nnz(A)) */
1823:   nnz           = PetscRealIntMultTruncate(fill,PetscIntSumTruncate(poti[pon],ai[am]));
1824:   PetscFreeSpaceGet(nnz,&free_space);
1825:   current_space = free_space;

1827:   /* create and initialize a linked list */
1828:   PetscTableCreate(A->cmap->n + a->B->cmap->N,aN,&ta);
1829:   MatRowMergeMax_SeqAIJ(a_loc,am,ta);
1830:   PetscTableGetCount(ta,&Armax);

1832:   PetscLLCondensedCreate_Scalable(Armax,&lnk);

1834:   for (i=0; i<pon; i++) {
1835:     pnz = poti[i+1] - poti[i];
1836:     ptJ = potj + poti[i];
1837:     for (j=0; j<pnz; j++) {
1838:       row  = ptJ[j]; /* row of A_loc == col of Pot */
1839:       anz  = ai[row+1] - ai[row];
1840:       Jptr = aj + ai[row];
1841:       /* add non-zero cols of AP into the sorted linked list lnk */
1842:       PetscLLCondensedAddSorted_Scalable(anz,Jptr,lnk);
1843:     }
1844:     nnz = lnk[0];

1846:     /* If free space is not available, double the total space in the list */
1847:     if (current_space->local_remaining<nnz) {
1848:       PetscFreeSpaceGet(PetscIntSumTruncate(nnz,current_space->total_array_size),&current_space);
1849:       nspacedouble++;
1850:     }

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

1855:     current_space->array           += nnz;
1856:     current_space->local_used      += nnz;
1857:     current_space->local_remaining -= nnz;

1859:     coi[i+1] = coi[i] + nnz;
1860:   }

1862:   PetscMalloc1(coi[pon]+1,&coj);
1863:   PetscFreeSpaceContiguous(&free_space,coj);
1864:   PetscLLCondensedDestroy_Scalable(lnk); /* must destroy to get a new one for C */

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

1869:   /* send j-array (coj) of Co to other processors */
1870:   /*----------------------------------------------*/
1871:   /* determine row ownership */
1872:   PetscNew(&merge);
1873:   PetscLayoutCreate(comm,&merge->rowmap);

1875:   merge->rowmap->n  = pn;
1876:   merge->rowmap->bs = 1;

1878:   PetscLayoutSetUp(merge->rowmap);
1879:   owners = merge->rowmap->range;

1881:   /* determine the number of messages to send, their lengths */
1882:   PetscCalloc1(size,&len_si);
1883:   PetscCalloc1(size,&merge->len_s);

1885:   len_s        = merge->len_s;
1886:   merge->nsend = 0;

1888:   PetscMalloc1(size+2,&owners_co);

1890:   proc = 0;
1891:   for (i=0; i<pon; i++) {
1892:     while (prmap[i] >= owners[proc+1]) proc++;
1893:     len_si[proc]++;  /* num of rows in Co to be sent to [proc] */
1894:     len_s[proc] += coi[i+1] - coi[i];
1895:   }

1897:   len          = 0; /* max length of buf_si[] */
1898:   owners_co[0] = 0;
1899:   for (proc=0; proc<size; proc++) {
1900:     owners_co[proc+1] = owners_co[proc] + len_si[proc];
1901:     if (len_si[proc]) {
1902:       merge->nsend++;
1903:       len_si[proc] = 2*(len_si[proc] + 1);
1904:       len         += len_si[proc];
1905:     }
1906:   }

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

1912:   /* post the Irecv and Isend of coj */
1913:   PetscCommGetNewTag(comm,&tagj);
1914:   PetscPostIrecvInt(comm,tagj,merge->nrecv,merge->id_r,merge->len_r,&buf_rj,&rwaits);
1915:   PetscMalloc1(merge->nsend+1,&swaits);
1916:   for (proc=0, k=0; proc<size; proc++) {
1917:     if (!len_s[proc]) continue;
1918:     i    = owners_co[proc];
1919:     MPI_Isend(coj+coi[i],len_s[proc],MPIU_INT,proc,tagj,comm,swaits+k);
1920:     k++;
1921:   }

1923:   /* receives and sends of coj are complete */
1924:   PetscMalloc1(size,&sstatus);
1925:   for (i=0; i<merge->nrecv; i++) {
1926:     PETSC_UNUSED PetscMPIInt icompleted;
1927:     MPI_Waitany(merge->nrecv,rwaits,&icompleted,&rstatus);
1928:   }
1929:   PetscFree(rwaits);
1930:   if (merge->nsend) {MPI_Waitall(merge->nsend,swaits,sstatus);}

1932:   /* add received column indices into table to update Armax */
1933:   /* Armax can be as large as aN if a P[row,:] is dense, see src/ksp/ksp/tutorials/ex56.c! */
1934:   for (k=0; k<merge->nrecv; k++) {/* k-th received message */
1935:     Jptr = buf_rj[k];
1936:     for (j=0; j<merge->len_r[k]; j++) {
1937:       PetscTableAdd(ta,*(Jptr+j)+1,1,INSERT_VALUES);
1938:     }
1939:   }
1940:   PetscTableGetCount(ta,&Armax);
1941:   /* printf("Armax %d, an %d + Bn %d = %d, aN %d\n",Armax,A->cmap->n,a->B->cmap->N,A->cmap->n+a->B->cmap->N,aN); */

1943:   /* send and recv coi */
1944:   /*-------------------*/
1945:   PetscCommGetNewTag(comm,&tagi);
1946:   PetscPostIrecvInt(comm,tagi,merge->nrecv,merge->id_r,len_ri,&buf_ri,&rwaits);
1947:   PetscMalloc1(len+1,&buf_s);
1948:   buf_si = buf_s;  /* points to the beginning of k-th msg to be sent */
1949:   for (proc=0,k=0; proc<size; proc++) {
1950:     if (!len_s[proc]) continue;
1951:     /* form outgoing message for i-structure:
1952:          buf_si[0]:                 nrows to be sent
1953:                [1:nrows]:           row index (global)
1954:                [nrows+1:2*nrows+1]: i-structure index
1955:     */
1956:     /*-------------------------------------------*/
1957:     nrows       = len_si[proc]/2 - 1;
1958:     buf_si_i    = buf_si + nrows+1;
1959:     buf_si[0]   = nrows;
1960:     buf_si_i[0] = 0;
1961:     nrows       = 0;
1962:     for (i=owners_co[proc]; i<owners_co[proc+1]; i++) {
1963:       nzi               = coi[i+1] - coi[i];
1964:       buf_si_i[nrows+1] = buf_si_i[nrows] + nzi;  /* i-structure */
1965:       buf_si[nrows+1]   = prmap[i] -owners[proc]; /* local row index */
1966:       nrows++;
1967:     }
1968:     MPI_Isend(buf_si,len_si[proc],MPIU_INT,proc,tagi,comm,swaits+k);
1969:     k++;
1970:     buf_si += len_si[proc];
1971:   }
1972:   i = merge->nrecv;
1973:   while (i--) {
1974:     PETSC_UNUSED PetscMPIInt icompleted;
1975:     MPI_Waitany(merge->nrecv,rwaits,&icompleted,&rstatus);
1976:   }
1977:   PetscFree(rwaits);
1978:   if (merge->nsend) {MPI_Waitall(merge->nsend,swaits,sstatus);}
1979:   PetscFree(len_si);
1980:   PetscFree(len_ri);
1981:   PetscFree(swaits);
1982:   PetscFree(sstatus);
1983:   PetscFree(buf_s);

1985:   /* compute the local portion of C (mpi mat) */
1986:   /*------------------------------------------*/
1987:   /* allocate bi array and free space for accumulating nonzero column info */
1988:   PetscMalloc1(pn+1,&bi);
1989:   bi[0] = 0;

1991:   /* set initial free space to be fill*(nnz(P) + nnz(AP)) */
1992:   nnz           = PetscRealIntMultTruncate(fill,PetscIntSumTruncate(pdti[pn],PetscIntSumTruncate(poti[pon],ai[am])));
1993:   PetscFreeSpaceGet(nnz,&free_space);
1994:   current_space = free_space;

1996:   PetscMalloc3(merge->nrecv,&buf_ri_k,merge->nrecv,&nextrow,merge->nrecv,&nextci);
1997:   for (k=0; k<merge->nrecv; k++) {
1998:     buf_ri_k[k] = buf_ri[k]; /* beginning of k-th recved i-structure */
1999:     nrows       = *buf_ri_k[k];
2000:     nextrow[k]  = buf_ri_k[k] + 1;  /* next row number of k-th recved i-structure */
2001:     nextci[k]   = buf_ri_k[k] + (nrows + 1); /* points to the next i-structure of k-th received i-structure  */
2002:   }

2004:   PetscLLCondensedCreate_Scalable(Armax,&lnk);
2005:   MatPreallocateInitialize(comm,pn,A->cmap->n,dnz,onz);
2006:   rmax = 0;
2007:   for (i=0; i<pn; i++) {
2008:     /* add pdt[i,:]*AP into lnk */
2009:     pnz = pdti[i+1] - pdti[i];
2010:     ptJ = pdtj + pdti[i];
2011:     for (j=0; j<pnz; j++) {
2012:       row  = ptJ[j];  /* row of AP == col of Pt */
2013:       anz  = ai[row+1] - ai[row];
2014:       Jptr = aj + ai[row];
2015:       /* add non-zero cols of AP into the sorted linked list lnk */
2016:       PetscLLCondensedAddSorted_Scalable(anz,Jptr,lnk);
2017:     }

2019:     /* add received col data into lnk */
2020:     for (k=0; k<merge->nrecv; k++) { /* k-th received message */
2021:       if (i == *nextrow[k]) { /* i-th row */
2022:         nzi  = *(nextci[k]+1) - *nextci[k];
2023:         Jptr = buf_rj[k] + *nextci[k];
2024:         PetscLLCondensedAddSorted_Scalable(nzi,Jptr,lnk);
2025:         nextrow[k]++; nextci[k]++;
2026:       }
2027:     }

2029:     /* add missing diagonal entry */
2030:     if (C->force_diagonals) {
2031:       k = i + owners[rank]; /* column index */
2032:       PetscLLCondensedAddSorted_Scalable(1,&k,lnk);
2033:     }

2035:     nnz = lnk[0];

2037:     /* if free space is not available, make more free space */
2038:     if (current_space->local_remaining<nnz) {
2039:       PetscFreeSpaceGet(PetscIntSumTruncate(nnz,current_space->total_array_size),&current_space);
2040:       nspacedouble++;
2041:     }
2042:     /* copy data into free space, then initialize lnk */
2043:     PetscLLCondensedClean_Scalable(nnz,current_space->array,lnk);
2044:     MatPreallocateSet(i+owners[rank],nnz,current_space->array,dnz,onz);

2046:     current_space->array           += nnz;
2047:     current_space->local_used      += nnz;
2048:     current_space->local_remaining -= nnz;

2050:     bi[i+1] = bi[i] + nnz;
2051:     if (nnz > rmax) rmax = nnz;
2052:   }
2053:   PetscFree3(buf_ri_k,nextrow,nextci);

2055:   PetscMalloc1(bi[pn]+1,&bj);
2056:   PetscFreeSpaceContiguous(&free_space,bj);
2057:   afill_tmp = (PetscReal)bi[pn]/(pdti[pn] + poti[pon] + ai[am]+1);
2058:   if (afill_tmp > afill) afill = afill_tmp;
2059:   PetscLLCondensedDestroy_Scalable(lnk);
2060:   PetscTableDestroy(&ta);
2061:   MatRestoreSymbolicTranspose_SeqAIJ(p->A,&pdti,&pdtj);
2062:   MatRestoreSymbolicTranspose_SeqAIJ(p->B,&poti,&potj);

2064:   /* create symbolic parallel matrix C - why cannot be assembled in Numeric part   */
2065:   /*-------------------------------------------------------------------------------*/
2066:   MatSetSizes(C,pn,A->cmap->n,PETSC_DETERMINE,PETSC_DETERMINE);
2067:   MatSetBlockSizes(C,PetscAbs(P->cmap->bs),PetscAbs(A->cmap->bs));
2068:   MatGetType(A,&mtype);
2069:   MatSetType(C,mtype);
2070:   MatMPIAIJSetPreallocation(C,0,dnz,0,onz);
2071:   MatPreallocateFinalize(dnz,onz);
2072:   MatSetBlockSize(C,1);
2073:   MatSetOption(C,MAT_NO_OFF_PROC_ENTRIES,PETSC_TRUE);
2074:   for (i=0; i<pn; i++) {
2075:     row  = i + rstart;
2076:     nnz  = bi[i+1] - bi[i];
2077:     Jptr = bj + bi[i];
2078:     MatSetValues(C,1,&row,nnz,Jptr,NULL,INSERT_VALUES);
2079:   }
2080:   MatAssemblyBegin(C,MAT_FINAL_ASSEMBLY);
2081:   MatAssemblyEnd(C,MAT_FINAL_ASSEMBLY);
2082:   MatSetOption(C,MAT_NEW_NONZERO_LOCATION_ERR,PETSC_TRUE);
2083:   merge->bi        = bi;
2084:   merge->bj        = bj;
2085:   merge->coi       = coi;
2086:   merge->coj       = coj;
2087:   merge->buf_ri    = buf_ri;
2088:   merge->buf_rj    = buf_rj;
2089:   merge->owners_co = owners_co;

2091:   /* attach the supporting struct to C for reuse */
2092:   C->product->data    = ptap;
2093:   C->product->destroy = MatDestroy_MPIAIJ_PtAP;
2094:   ptap->merge         = merge;

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

2098: #if defined(PETSC_USE_INFO)
2099:   if (bi[pn] != 0) {
2100:     PetscInfo3(C,"Reallocs %D; Fill ratio: given %g needed %g.\n",nspacedouble,(double)fill,(double)afill);
2101:     PetscInfo1(C,"Use MatTransposeMatMult(A,B,MatReuse,%g,&C) for best performance.\n",(double)afill);
2102:   } else {
2103:     PetscInfo(C,"Empty matrix product\n");
2104:   }
2105: #endif
2106:   return(0);
2107: }

2109: /* ---------------------------------------------------------------- */
2110: static PetscErrorCode MatProductSymbolic_AtB_MPIAIJ_MPIAIJ(Mat C)
2111: {
2113:   Mat_Product    *product = C->product;
2114:   Mat            A=product->A,B=product->B;
2115:   PetscReal      fill=product->fill;
2116:   PetscBool      flg;

2119:   /* scalable */
2120:   PetscStrcmp(product->alg,"scalable",&flg);
2121:   if (flg) {
2122:     MatTransposeMatMultSymbolic_MPIAIJ_MPIAIJ(A,B,fill,C);
2123:     goto next;
2124:   }

2126:   /* nonscalable */
2127:   PetscStrcmp(product->alg,"nonscalable",&flg);
2128:   if (flg) {
2129:     MatTransposeMatMultSymbolic_MPIAIJ_MPIAIJ_nonscalable(A,B,fill,C);
2130:     goto next;
2131:   }

2133:   /* matmatmult */
2134:   PetscStrcmp(product->alg,"at*b",&flg);
2135:   if (flg) {
2136:     Mat       At;
2137:     Mat_APMPI *ptap;

2139:     MatTranspose(A,MAT_INITIAL_MATRIX,&At);
2140:     MatMatMultSymbolic_MPIAIJ_MPIAIJ(At,B,fill,C);
2141:     ptap = (Mat_APMPI*)C->product->data;
2142:     if (ptap) {
2143:       ptap->Pt = At;
2144:       C->product->destroy = MatDestroy_MPIAIJ_PtAP;
2145:     }
2146:     C->ops->transposematmultnumeric = MatTransposeMatMultNumeric_MPIAIJ_MPIAIJ_matmatmult;
2147:     goto next;
2148:   }

2150:   /* backend general code */
2151:   PetscStrcmp(product->alg,"backend",&flg);
2152:   if (flg) {
2153:     MatProductSymbolic_MPIAIJBACKEND(C);
2154:     return(0);
2155:   }

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

2159: next:
2160:   C->ops->productnumeric = MatProductNumeric_AtB;
2161:   return(0);
2162: }

2164: /* ---------------------------------------------------------------- */
2165: /* Set options for MatMatMultxxx_MPIAIJ_MPIAIJ */
2166: static PetscErrorCode MatProductSetFromOptions_MPIAIJ_AB(Mat C)
2167: {
2169:   Mat_Product    *product = C->product;
2170:   Mat            A=product->A,B=product->B;
2171: #if defined(PETSC_HAVE_HYPRE)
2172:   const char     *algTypes[5] = {"scalable","nonscalable","seqmpi","backend","hypre"};
2173:   PetscInt       nalg = 5;
2174: #else
2175:   const char     *algTypes[4] = {"scalable","nonscalable","seqmpi","backend",};
2176:   PetscInt       nalg = 4;
2177: #endif
2178:   PetscInt       alg = 1; /* set nonscalable algorithm as default */
2179:   PetscBool      flg;
2180:   MPI_Comm       comm;

2183:   /* Check matrix local sizes */
2184:   PetscObjectGetComm((PetscObject)C,&comm);
2185:   if (A->cmap->rstart != B->rmap->rstart || A->cmap->rend != B->rmap->rend) SETERRQ4(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Matrix local dimensions are incompatible, (%D, %D) != (%D,%D)",A->cmap->rstart,A->cmap->rend,B->rmap->rstart,B->rmap->rend);

2187:   /* Set "nonscalable" as default algorithm */
2188:   PetscStrcmp(C->product->alg,"default",&flg);
2189:   if (flg) {
2190:     MatProductSetAlgorithm(C,(MatProductAlgorithm)algTypes[alg]);

2192:     /* Set "scalable" as default if BN and local nonzeros of A and B are large */
2193:     if (B->cmap->N > 100000) { /* may switch to scalable algorithm as default */
2194:       MatInfo     Ainfo,Binfo;
2195:       PetscInt    nz_local;
2196:       PetscBool   alg_scalable_loc=PETSC_FALSE,alg_scalable;

2198:       MatGetInfo(A,MAT_LOCAL,&Ainfo);
2199:       MatGetInfo(B,MAT_LOCAL,&Binfo);
2200:       nz_local = (PetscInt)(Ainfo.nz_allocated + Binfo.nz_allocated);

2202:       if (B->cmap->N > product->fill*nz_local) alg_scalable_loc = PETSC_TRUE;
2203:       MPIU_Allreduce(&alg_scalable_loc,&alg_scalable,1,MPIU_BOOL,MPI_LOR,comm);

2205:       if (alg_scalable) {
2206:         alg  = 0; /* scalable algorithm would 50% slower than nonscalable algorithm */
2207:         MatProductSetAlgorithm(C,(MatProductAlgorithm)algTypes[alg]);
2208:         PetscInfo2(B,"Use scalable algorithm, BN %D, fill*nz_allocated %g\n",B->cmap->N,product->fill*nz_local);
2209:       }
2210:     }
2211:   }

2213:   /* Get runtime option */
2214:   if (product->api_user) {
2215:     PetscOptionsBegin(PetscObjectComm((PetscObject)C),((PetscObject)C)->prefix,"MatMatMult","Mat");
2216:     PetscOptionsEList("-matmatmult_via","Algorithmic approach","MatMatMult",algTypes,nalg,algTypes[alg],&alg,&flg);
2217:     PetscOptionsEnd();
2218:   } else {
2219:     PetscOptionsBegin(PetscObjectComm((PetscObject)C),((PetscObject)C)->prefix,"MatProduct_AB","Mat");
2220:     PetscOptionsEList("-matproduct_ab_via","Algorithmic approach","MatMatMult",algTypes,nalg,algTypes[alg],&alg,&flg);
2221:     PetscOptionsEnd();
2222:   }
2223:   if (flg) {
2224:     MatProductSetAlgorithm(C,(MatProductAlgorithm)algTypes[alg]);
2225:   }

2227:   C->ops->productsymbolic = MatProductSymbolic_AB_MPIAIJ_MPIAIJ;
2228:   return(0);
2229: }

2231: /* Set options for MatTransposeMatMultXXX_MPIAIJ_MPIAIJ */
2232: static PetscErrorCode MatProductSetFromOptions_MPIAIJ_AtB(Mat C)
2233: {
2235:   Mat_Product    *product = C->product;
2236:   Mat            A=product->A,B=product->B;
2237:   const char     *algTypes[4] = {"scalable","nonscalable","at*b","backend"};
2238:   PetscInt       nalg = 4;
2239:   PetscInt       alg = 1; /* set default algorithm  */
2240:   PetscBool      flg;
2241:   MPI_Comm       comm;

2244:   /* Check matrix local sizes */
2245:   PetscObjectGetComm((PetscObject)C,&comm);
2246:   if (A->rmap->rstart != B->rmap->rstart || A->rmap->rend != B->rmap->rend) SETERRQ4(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Matrix local dimensions are incompatible, A (%D, %D) != B (%D,%D)",A->rmap->rstart,A->rmap->rend,B->rmap->rstart,B->rmap->rend);

2248:   /* Set default algorithm */
2249:   PetscStrcmp(C->product->alg,"default",&flg);
2250:   if (flg) {
2251:     MatProductSetAlgorithm(C,(MatProductAlgorithm)algTypes[alg]);
2252:   }

2254:   /* Set "scalable" as default if BN and local nonzeros of A and B are large */
2255:   if (alg && B->cmap->N > 100000) { /* may switch to scalable algorithm as default */
2256:     MatInfo     Ainfo,Binfo;
2257:     PetscInt    nz_local;
2258:     PetscBool   alg_scalable_loc=PETSC_FALSE,alg_scalable;

2260:     MatGetInfo(A,MAT_LOCAL,&Ainfo);
2261:     MatGetInfo(B,MAT_LOCAL,&Binfo);
2262:     nz_local = (PetscInt)(Ainfo.nz_allocated + Binfo.nz_allocated);

2264:     if (B->cmap->N > product->fill*nz_local) alg_scalable_loc = PETSC_TRUE;
2265:     MPIU_Allreduce(&alg_scalable_loc,&alg_scalable,1,MPIU_BOOL,MPI_LOR,comm);

2267:     if (alg_scalable) {
2268:       alg  = 0; /* scalable algorithm would 50% slower than nonscalable algorithm */
2269:       MatProductSetAlgorithm(C,(MatProductAlgorithm)algTypes[alg]);
2270:       PetscInfo2(B,"Use scalable algorithm, BN %D, fill*nz_allocated %g\n",B->cmap->N,product->fill*nz_local);
2271:     }
2272:   }

2274:   /* Get runtime option */
2275:   if (product->api_user) {
2276:     PetscOptionsBegin(PetscObjectComm((PetscObject)C),((PetscObject)C)->prefix,"MatTransposeMatMult","Mat");
2277:     PetscOptionsEList("-mattransposematmult_via","Algorithmic approach","MatTransposeMatMult",algTypes,nalg,algTypes[alg],&alg,&flg);
2278:     PetscOptionsEnd();
2279:   } else {
2280:     PetscOptionsBegin(PetscObjectComm((PetscObject)C),((PetscObject)C)->prefix,"MatProduct_AtB","Mat");
2281:     PetscOptionsEList("-matproduct_atb_via","Algorithmic approach","MatTransposeMatMult",algTypes,nalg,algTypes[alg],&alg,&flg);
2282:     PetscOptionsEnd();
2283:   }
2284:   if (flg) {
2285:     MatProductSetAlgorithm(C,(MatProductAlgorithm)algTypes[alg]);
2286:   }

2288:   C->ops->productsymbolic = MatProductSymbolic_AtB_MPIAIJ_MPIAIJ;
2289:   return(0);
2290: }

2292: static PetscErrorCode MatProductSetFromOptions_MPIAIJ_PtAP(Mat C)
2293: {
2295:   Mat_Product    *product = C->product;
2296:   Mat            A=product->A,P=product->B;
2297:   MPI_Comm       comm;
2298:   PetscBool      flg;
2299:   PetscInt       alg=1; /* set default algorithm */
2300: #if !defined(PETSC_HAVE_HYPRE)
2301:   const char     *algTypes[5] = {"scalable","nonscalable","allatonce","allatonce_merged","backend"};
2302:   PetscInt       nalg=5;
2303: #else
2304:   const char     *algTypes[6] = {"scalable","nonscalable","allatonce","allatonce_merged","backend","hypre"};
2305:   PetscInt       nalg=6;
2306: #endif
2307:   PetscInt       pN=P->cmap->N;

2310:   /* Check matrix local sizes */
2311:   PetscObjectGetComm((PetscObject)C,&comm);
2312:   if (A->rmap->rstart != P->rmap->rstart || A->rmap->rend != P->rmap->rend) SETERRQ4(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Matrix local dimensions are incompatible, Arow (%D, %D) != Prow (%D,%D)",A->rmap->rstart,A->rmap->rend,P->rmap->rstart,P->rmap->rend);
2313:   if (A->cmap->rstart != P->rmap->rstart || A->cmap->rend != P->rmap->rend) SETERRQ4(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Matrix local dimensions are incompatible, Acol (%D, %D) != Prow (%D,%D)",A->cmap->rstart,A->cmap->rend,P->rmap->rstart,P->rmap->rend);

2315:   /* Set "nonscalable" as default algorithm */
2316:   PetscStrcmp(C->product->alg,"default",&flg);
2317:   if (flg) {
2318:     MatProductSetAlgorithm(C,(MatProductAlgorithm)algTypes[alg]);

2320:     /* Set "scalable" as default if BN and local nonzeros of A and B are large */
2321:     if (pN > 100000) {
2322:       MatInfo     Ainfo,Pinfo;
2323:       PetscInt    nz_local;
2324:       PetscBool   alg_scalable_loc=PETSC_FALSE,alg_scalable;

2326:       MatGetInfo(A,MAT_LOCAL,&Ainfo);
2327:       MatGetInfo(P,MAT_LOCAL,&Pinfo);
2328:       nz_local = (PetscInt)(Ainfo.nz_allocated + Pinfo.nz_allocated);

2330:       if (pN > product->fill*nz_local) alg_scalable_loc = PETSC_TRUE;
2331:       MPIU_Allreduce(&alg_scalable_loc,&alg_scalable,1,MPIU_BOOL,MPI_LOR,comm);

2333:       if (alg_scalable) {
2334:         alg = 0; /* scalable algorithm would 50% slower than nonscalable algorithm */
2335:         MatProductSetAlgorithm(C,(MatProductAlgorithm)algTypes[alg]);
2336:       }
2337:     }
2338:   }

2340:   /* Get runtime option */
2341:   if (product->api_user) {
2342:     PetscOptionsBegin(PetscObjectComm((PetscObject)C),((PetscObject)C)->prefix,"MatPtAP","Mat");
2343:     PetscOptionsEList("-matptap_via","Algorithmic approach","MatPtAP",algTypes,nalg,algTypes[alg],&alg,&flg);
2344:     PetscOptionsEnd();
2345:   } else {
2346:     PetscOptionsBegin(PetscObjectComm((PetscObject)C),((PetscObject)C)->prefix,"MatProduct_PtAP","Mat");
2347:     PetscOptionsEList("-matproduct_ptap_via","Algorithmic approach","MatPtAP",algTypes,nalg,algTypes[alg],&alg,&flg);
2348:     PetscOptionsEnd();
2349:   }
2350:   if (flg) {
2351:     MatProductSetAlgorithm(C,(MatProductAlgorithm)algTypes[alg]);
2352:   }

2354:   C->ops->productsymbolic = MatProductSymbolic_PtAP_MPIAIJ_MPIAIJ;
2355:   return(0);
2356: }

2358: static PetscErrorCode MatProductSetFromOptions_MPIAIJ_RARt(Mat C)
2359: {
2360:   Mat_Product *product = C->product;
2361:   Mat         A = product->A,R=product->B;

2364:   /* Check matrix local sizes */
2365:   if (A->cmap->n != R->cmap->n || A->rmap->n != R->cmap->n) SETERRQ4(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Matrix local dimensions are incompatible, A local (%D, %D), R local (%D,%D)",A->rmap->n,A->rmap->n,R->rmap->n,R->cmap->n);

2367:   C->ops->productsymbolic = MatProductSymbolic_RARt_MPIAIJ_MPIAIJ;
2368:   return(0);
2369: }

2371: /*
2372:  Set options for ABC = A*B*C = A*(B*C); ABC's algorithm must be chosen from AB's algorithm
2373: */
2374: static PetscErrorCode MatProductSetFromOptions_MPIAIJ_ABC(Mat C)
2375: {
2377:   Mat_Product    *product = C->product;
2378:   PetscBool      flg = PETSC_FALSE;
2379:   PetscInt       alg = 1; /* default algorithm */
2380:   const char     *algTypes[3] = {"scalable","nonscalable","seqmpi"};
2381:   PetscInt       nalg = 3;

2384:   /* Set default algorithm */
2385:   PetscStrcmp(C->product->alg,"default",&flg);
2386:   if (flg) {
2387:     MatProductSetAlgorithm(C,(MatProductAlgorithm)algTypes[alg]);
2388:   }

2390:   /* Get runtime option */
2391:   if (product->api_user) {
2392:     PetscOptionsBegin(PetscObjectComm((PetscObject)C),((PetscObject)C)->prefix,"MatMatMatMult","Mat");
2393:     PetscOptionsEList("-matmatmatmult_via","Algorithmic approach","MatMatMatMult",algTypes,nalg,algTypes[alg],&alg,&flg);
2394:     PetscOptionsEnd();
2395:   } else {
2396:     PetscOptionsBegin(PetscObjectComm((PetscObject)C),((PetscObject)C)->prefix,"MatProduct_ABC","Mat");
2397:     PetscOptionsEList("-matproduct_abc_via","Algorithmic approach","MatProduct_ABC",algTypes,nalg,algTypes[alg],&alg,&flg);
2398:     PetscOptionsEnd();
2399:   }
2400:   if (flg) {
2401:     MatProductSetAlgorithm(C,(MatProductAlgorithm)algTypes[alg]);
2402:   }

2404:   C->ops->matmatmultsymbolic = MatMatMatMultSymbolic_MPIAIJ_MPIAIJ_MPIAIJ;
2405:   C->ops->productsymbolic    = MatProductSymbolic_ABC;
2406:   return(0);
2407: }

2409: PETSC_INTERN PetscErrorCode MatProductSetFromOptions_MPIAIJ(Mat C)
2410: {
2412:   Mat_Product    *product = C->product;

2415:   switch (product->type) {
2416:   case MATPRODUCT_AB:
2417:     MatProductSetFromOptions_MPIAIJ_AB(C);
2418:     break;
2419:   case MATPRODUCT_AtB:
2420:     MatProductSetFromOptions_MPIAIJ_AtB(C);
2421:     break;
2422:   case MATPRODUCT_PtAP:
2423:     MatProductSetFromOptions_MPIAIJ_PtAP(C);
2424:     break;
2425:   case MATPRODUCT_RARt:
2426:     MatProductSetFromOptions_MPIAIJ_RARt(C);
2427:     break;
2428:   case MATPRODUCT_ABC:
2429:     MatProductSetFromOptions_MPIAIJ_ABC(C);
2430:     break;
2431:   default:
2432:     break;
2433:   }
2434:   return(0);
2435: }