Actual source code: mpimatmatmult.c

petsc-master 2019-08-15
Report Typos and Errors

  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/vecscatterimpl.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 MatMatMult_MPIAIJ_MPIAIJ(Mat A,Mat B,MatReuse scall,PetscReal fill, Mat *C)
 19: {
 21: #if defined(PETSC_HAVE_HYPRE)
 22:   const char     *algTypes[4] = {"scalable","nonscalable","seqmpi","hypre"};
 23:   PetscInt       nalg = 4;
 24: #else
 25:   const char     *algTypes[3] = {"scalable","nonscalable","seqmpi"};
 26:   PetscInt       nalg = 3;
 27: #endif
 28:   PetscInt       alg = 1; /* set nonscalable algorithm as default */
 29:   MPI_Comm       comm;
 30:   PetscBool      flg;

 33:   if (scall == MAT_INITIAL_MATRIX) {
 34:     PetscObjectGetComm((PetscObject)A,&comm);
 35:     if (A->cmap->rstart != B->rmap->rstart || A->cmap->rend != B->rmap->rend) SETERRQ4(comm,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);

 37:     PetscOptionsBegin(PetscObjectComm((PetscObject)A),((PetscObject)A)->prefix,"MatMatMult","Mat");
 38:     PetscOptionsEList("-matmatmult_via","Algorithmic approach","MatMatMult",algTypes,nalg,algTypes[1],&alg,&flg);
 39:     PetscOptionsEnd();

 41:     if (!flg && B->cmap->N > 100000) { /* may switch to scalable algorithm as default */
 42:       MatInfo     Ainfo,Binfo;
 43:       PetscInt    nz_local;
 44:       PetscBool   alg_scalable_loc=PETSC_FALSE,alg_scalable;

 46:       MatGetInfo(A,MAT_LOCAL,&Ainfo);
 47:       MatGetInfo(B,MAT_LOCAL,&Binfo);
 48:       nz_local = (PetscInt)(Ainfo.nz_allocated + Binfo.nz_allocated);

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

 53:       if (alg_scalable) {
 54:         alg  = 0; /* scalable algorithm would 50% slower than nonscalable algorithm */
 55:         PetscInfo2(B,"Use scalable algorithm, BN %D, fill*nz_allocated %g\n",B->cmap->N,fill*nz_local);
 56:       }
 57:     }

 59:     PetscLogEventBegin(MAT_MatMultSymbolic,A,B,0,0);
 60:     switch (alg) {
 61:     case 1:
 62:       MatMatMultSymbolic_MPIAIJ_MPIAIJ_nonscalable(A,B,fill,C);
 63:       break;
 64:     case 2:
 65:       MatMatMultSymbolic_MPIAIJ_MPIAIJ_seqMPI(A,B,fill,C);
 66:       break;
 67: #if defined(PETSC_HAVE_HYPRE)
 68:     case 3:
 69:       MatMatMultSymbolic_AIJ_AIJ_wHYPRE(A,B,fill,C);
 70:       break;
 71: #endif
 72:     default:
 73:       MatMatMultSymbolic_MPIAIJ_MPIAIJ(A,B,fill,C);
 74:       break;
 75:     }
 76:     PetscLogEventEnd(MAT_MatMultSymbolic,A,B,0,0);

 78:     if (alg == 0 || alg == 1) {
 79:       Mat_MPIAIJ *c  = (Mat_MPIAIJ*)(*C)->data;
 80:       Mat_APMPI  *ap = c->ap;
 81:       PetscOptionsBegin(PetscObjectComm((PetscObject)(*C)),((PetscObject)(*C))->prefix,"MatFreeIntermediateDataStructures","Mat");
 82:       ap->freestruct = PETSC_FALSE;
 83:       PetscOptionsBool("-mat_freeintermediatedatastructures","Free intermediate data structures", "MatFreeIntermediateDataStructures",ap->freestruct,&ap->freestruct, NULL);
 84:       PetscOptionsEnd();
 85:     }
 86:   }

 88:   PetscLogEventBegin(MAT_MatMultNumeric,A,B,0,0);
 89:   (*(*C)->ops->matmultnumeric)(A,B,*C);
 90:   PetscLogEventEnd(MAT_MatMultNumeric,A,B,0,0);
 91:   return(0);
 92: }

 94: PetscErrorCode MatDestroy_MPIAIJ_MatMatMult(Mat A)
 95: {
 97:   Mat_MPIAIJ     *a    = (Mat_MPIAIJ*)A->data;
 98:   Mat_APMPI      *ptap = a->ap;

101:   PetscFree2(ptap->startsj_s,ptap->startsj_r);
102:   PetscFree(ptap->bufa);
103:   MatDestroy(&ptap->P_loc);
104:   MatDestroy(&ptap->P_oth);
105:   MatDestroy(&ptap->Pt);
106:   PetscFree(ptap->api);
107:   PetscFree(ptap->apj);
108:   PetscFree(ptap->apa);
109:   ptap->destroy(A);
110:   PetscFree(ptap);
111:   return(0);
112: }

114: PetscErrorCode MatMatMultNumeric_MPIAIJ_MPIAIJ_nonscalable(Mat A,Mat P,Mat C)
115: {
117:   Mat_MPIAIJ     *a  =(Mat_MPIAIJ*)A->data,*c=(Mat_MPIAIJ*)C->data;
118:   Mat_SeqAIJ     *ad =(Mat_SeqAIJ*)(a->A)->data,*ao=(Mat_SeqAIJ*)(a->B)->data;
119:   Mat_SeqAIJ     *cd =(Mat_SeqAIJ*)(c->A)->data,*co=(Mat_SeqAIJ*)(c->B)->data;
120:   PetscScalar    *cda=cd->a,*coa=co->a;
121:   Mat_SeqAIJ     *p_loc,*p_oth;
122:   PetscScalar    *apa,*ca;
123:   PetscInt       cm   =C->rmap->n;
124:   Mat_APMPI      *ptap=c->ap;
125:   PetscInt       *api,*apj,*apJ,i,k;
126:   PetscInt       cstart=C->cmap->rstart;
127:   PetscInt       cdnz,conz,k0,k1;
128:   MPI_Comm       comm;
129:   PetscMPIInt    size;

132:   PetscObjectGetComm((PetscObject)A,&comm);
133:   MPI_Comm_size(comm,&size);

135:   if (!ptap->P_oth && size>1) SETERRQ(comm,PETSC_ERR_ARG_WRONGSTATE,"AP cannot be reused. Do not call MatFreeIntermediateDataStructures() or use '-mat_freeintermediatedatastructures'");

137:   /* 1) get P_oth = ptap->P_oth  and P_loc = ptap->P_loc */
138:   /*-----------------------------------------------------*/
139:   /* update numerical values of P_oth and P_loc */
140:   MatGetBrowsOfAoCols_MPIAIJ(A,P,MAT_REUSE_MATRIX,&ptap->startsj_s,&ptap->startsj_r,&ptap->bufa,&ptap->P_oth);
141:   MatMPIAIJGetLocalMat(P,MAT_REUSE_MATRIX,&ptap->P_loc);

143:   /* 2) compute numeric C_loc = A_loc*P = Ad*P_loc + Ao*P_oth */
144:   /*----------------------------------------------------------*/
145:   /* get data from symbolic products */
146:   p_loc = (Mat_SeqAIJ*)(ptap->P_loc)->data;
147:   p_oth = NULL;
148:   if (size >1) {
149:     p_oth = (Mat_SeqAIJ*)(ptap->P_oth)->data;
150:   }

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

155:   api = ptap->api;
156:   apj = ptap->apj;
157:   for (i=0; i<cm; i++) {
158:     /* compute apa = A[i,:]*P */
159:     AProw_nonscalable(i,ad,ao,p_loc,p_oth,apa);

161:     /* set values in C */
162:     apJ  = apj + api[i];
163:     cdnz = cd->i[i+1] - cd->i[i];
164:     conz = co->i[i+1] - co->i[i];

166:     /* 1st off-diagoanl part of C */
167:     ca = coa + co->i[i];
168:     k  = 0;
169:     for (k0=0; k0<conz; k0++) {
170:       if (apJ[k] >= cstart) break;
171:       ca[k0]      = apa[apJ[k]];
172:       apa[apJ[k++]] = 0.0;
173:     }

175:     /* diagonal part of C */
176:     ca = cda + cd->i[i];
177:     for (k1=0; k1<cdnz; k1++) {
178:       ca[k1]      = apa[apJ[k]];
179:       apa[apJ[k++]] = 0.0;
180:     }

182:     /* 2nd off-diagoanl part of C */
183:     ca = coa + co->i[i];
184:     for (; k0<conz; k0++) {
185:       ca[k0]      = apa[apJ[k]];
186:       apa[apJ[k++]] = 0.0;
187:     }
188:   }
189:   MatAssemblyBegin(C,MAT_FINAL_ASSEMBLY);
190:   MatAssemblyEnd(C,MAT_FINAL_ASSEMBLY);

192:   if (ptap->freestruct) {
193:     MatFreeIntermediateDataStructures(C);
194:   }
195:   return(0);
196: }

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

217:   PetscObjectGetComm((PetscObject)A,&comm);
218:   MPI_Comm_size(comm,&size);

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

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

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

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

239:   /* first, compute symbolic AP = A_loc*P = A_diag*P_loc + A_off*P_oth */
240:   /*-------------------------------------------------------------------*/
241:   PetscMalloc1(am+2,&api);
242:   ptap->api = api;
243:   api[0]    = 0;

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

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

252:   MatPreallocateInitialize(comm,am,pn,dnz,onz);
253:   for (i=0; i<am; i++) {
254:     /* diagonal portion of A */
255:     nzi = adi[i+1] - adi[i];
256:     for (j=0; j<nzi; j++) {
257:       row  = *adj++;
258:       pnz  = pi_loc[row+1] - pi_loc[row];
259:       Jptr = pj_loc + pi_loc[row];
260:       /* add non-zero cols of P into the sorted linked list lnk */
261:       PetscLLCondensedAddSorted(pnz,Jptr,lnk,lnkbt);
262:     }
263:     /* off-diagonal portion of A */
264:     nzi = aoi[i+1] - aoi[i];
265:     for (j=0; j<nzi; j++) {
266:       row  = *aoj++;
267:       pnz  = pi_oth[row+1] - pi_oth[row];
268:       Jptr = pj_oth + pi_oth[row];
269:       PetscLLCondensedAddSorted(pnz,Jptr,lnk,lnkbt);
270:     }

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

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

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

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

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

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

300:   /* create and assemble symbolic parallel matrix Cmpi */
301:   /*----------------------------------------------------*/
302:   MatCreate(comm,&Cmpi);
303:   MatSetSizes(Cmpi,am,pn,PETSC_DETERMINE,PETSC_DETERMINE);
304:   MatSetBlockSizesFromMats(Cmpi,A,P);

306:   MatGetType(A,&mtype);
307:   MatSetType(Cmpi,mtype);
308:   MatMPIAIJSetPreallocation(Cmpi,0,dnz,0,onz);

310:   MatSetValues_MPIAIJ_CopyFromCSRFormat_Symbolic(Cmpi, apj, api);
311:   MatAssemblyBegin(Cmpi,MAT_FINAL_ASSEMBLY);
312:   MatAssemblyEnd(Cmpi,MAT_FINAL_ASSEMBLY);
313:   MatPreallocateFinalize(dnz,onz);

315:   ptap->destroy        = Cmpi->ops->destroy;
316:   ptap->duplicate      = Cmpi->ops->duplicate;
317:   Cmpi->ops->matmultnumeric = MatMatMultNumeric_MPIAIJ_MPIAIJ_nonscalable;
318:   Cmpi->ops->destroy   = MatDestroy_MPIAIJ_MatMatMult;
319:   Cmpi->ops->freeintermediatedatastructures = MatFreeIntermediateDataStructures_MPIAIJ_AP;

321:   /* attach the supporting struct to Cmpi for reuse */
322:   c       = (Mat_MPIAIJ*)Cmpi->data;
323:   c->ap = ptap;

325:   *C = Cmpi;

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

334: #if defined(PETSC_USE_INFO)
335:   if (api[am]) {
336:     PetscInfo3(Cmpi,"Reallocs %D; Fill ratio: given %g needed %g.\n",nspacedouble,(double)fill,(double)afill);
337:     PetscInfo1(Cmpi,"Use MatMatMult(A,B,MatReuse,%g,&C) for best performance.;\n",(double)afill);
338:   } else {
339:     PetscInfo(Cmpi,"Empty matrix product\n");
340:   }
341: #endif
342:   return(0);
343: }

345: PETSC_INTERN PetscErrorCode MatMatMult_MPIAIJ_MPIDense(Mat A,Mat B,MatReuse scall,PetscReal fill,Mat *C)
346: {

350:   if (scall == MAT_INITIAL_MATRIX) {
351:     PetscLogEventBegin(MAT_MatMultSymbolic,A,B,0,0);
352:     MatMatMultSymbolic_MPIAIJ_MPIDense(A,B,fill,C);
353:     PetscLogEventEnd(MAT_MatMultSymbolic,A,B,0,0);
354:   }
355:   PetscLogEventBegin(MAT_MatMultNumeric,A,B,0,0);
356:   MatMatMultNumeric_MPIAIJ_MPIDense(A,B,*C);
357:   PetscLogEventEnd(MAT_MatMultNumeric,A,B,0,0);
358:   return(0);
359: }

361: typedef struct {
362:   Mat         workB;
363:   PetscScalar *rvalues,*svalues;
364:   MPI_Request *rwaits,*swaits;
365: } MPIAIJ_MPIDense;

367: PetscErrorCode MatMPIAIJ_MPIDenseDestroy(void *ctx)
368: {
369:   MPIAIJ_MPIDense *contents = (MPIAIJ_MPIDense*) ctx;
370:   PetscErrorCode  ierr;

373:   MatDestroy(&contents->workB);
374:   PetscFree4(contents->rvalues,contents->svalues,contents->rwaits,contents->swaits);
375:   PetscFree(contents);
376:   return(0);
377: }

379: /*
380:     This is a "dummy function" that handles the case where matrix C was created as a dense matrix
381:   directly by the user and passed to MatMatMult() with the MAT_REUSE_MATRIX option

383:   It is the same as MatMatMultSymbolic_MPIAIJ_MPIDense() except does not create C
384: */
385: PetscErrorCode MatMatMultNumeric_MPIDense(Mat A,Mat B,Mat C)
386: {
387:   PetscErrorCode         ierr;
388:   PetscBool              flg;
389:   Mat_MPIAIJ             *aij = (Mat_MPIAIJ*) A->data;
390:   PetscInt               nz   = aij->B->cmap->n,to_n,to_entries,from_n,from_entries;
391:   PetscContainer         container;
392:   MPIAIJ_MPIDense        *contents;
393:   VecScatter             ctx   = aij->Mvctx;

396:   PetscObjectTypeCompare((PetscObject)B,MATMPIDENSE,&flg);
397:   if (!flg) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,"Second matrix must be mpidense");

399:   /* Handle case where where user provided the final C matrix rather than calling MatMatMult() with MAT_INITIAL_MATRIX*/
400:   PetscObjectTypeCompare((PetscObject)A,MATMPIAIJ,&flg);
401:   if (!flg) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,"First matrix must be MPIAIJ");

403:   C->ops->matmultnumeric = MatMatMultNumeric_MPIAIJ_MPIDense;

405:   PetscNew(&contents);
406:   /* Create work matrix used to store off processor rows of B needed for local product */
407:   MatCreateSeqDense(PETSC_COMM_SELF,nz,B->cmap->N,NULL,&contents->workB);
408:   /* Create work arrays needed */
409:   VecScatterGetRemoteCount_Private(ctx,PETSC_TRUE/*send*/,&to_n,&to_entries);
410:   VecScatterGetRemoteCount_Private(ctx,PETSC_FALSE/*recv*/,&from_n,&from_entries);
411:   PetscMalloc4(B->cmap->N*from_entries,&contents->rvalues,B->cmap->N*to_entries,&contents->svalues,from_n,&contents->rwaits,to_n,&contents->swaits);

413:   PetscContainerCreate(PetscObjectComm((PetscObject)A),&container);
414:   PetscContainerSetPointer(container,contents);
415:   PetscContainerSetUserDestroy(container,MatMPIAIJ_MPIDenseDestroy);
416:   PetscObjectCompose((PetscObject)C,"workB",(PetscObject)container);
417:   PetscContainerDestroy(&container);

419:   (*C->ops->matmultnumeric)(A,B,C);
420:   return(0);
421: }

423: PetscErrorCode MatMatMultSymbolic_MPIAIJ_MPIDense(Mat A,Mat B,PetscReal fill,Mat *C)
424: {
425:   PetscErrorCode         ierr;
426:   Mat_MPIAIJ             *aij = (Mat_MPIAIJ*) A->data;
427:   PetscInt               nz   = aij->B->cmap->n,to_n,to_entries,from_n,from_entries;
428:   PetscContainer         container;
429:   MPIAIJ_MPIDense        *contents;
430:   VecScatter             ctx   = aij->Mvctx;
431:   PetscInt               m     = A->rmap->n,n=B->cmap->n;

434:   MatCreate(PetscObjectComm((PetscObject)B),C);
435:   MatSetSizes(*C,m,n,A->rmap->N,B->cmap->N);
436:   MatSetBlockSizesFromMats(*C,A,B);
437:   MatSetType(*C,MATMPIDENSE);
438:   MatMPIDenseSetPreallocation(*C,NULL);
439:   MatAssemblyBegin(*C,MAT_FINAL_ASSEMBLY);
440:   MatAssemblyEnd(*C,MAT_FINAL_ASSEMBLY);

442:   (*C)->ops->matmultnumeric = MatMatMultNumeric_MPIAIJ_MPIDense;

444:   PetscNew(&contents);
445:   /* Create work matrix used to store off processor rows of B needed for local product */
446:   MatCreateSeqDense(PETSC_COMM_SELF,nz,B->cmap->N,NULL,&contents->workB);
447:   /* Create work arrays needed */
448:   VecScatterGetRemoteCount_Private(ctx,PETSC_TRUE/*send*/,&to_n,&to_entries);
449:   VecScatterGetRemoteCount_Private(ctx,PETSC_FALSE/*recv*/,&from_n,&from_entries);
450:   PetscMalloc4(B->cmap->N*from_entries,&contents->rvalues,B->cmap->N*to_entries,&contents->svalues,from_n,&contents->rwaits,to_n,&contents->swaits);

452:   PetscContainerCreate(PetscObjectComm((PetscObject)A),&container);
453:   PetscContainerSetPointer(container,contents);
454:   PetscContainerSetUserDestroy(container,MatMPIAIJ_MPIDenseDestroy);
455:   PetscObjectCompose((PetscObject)(*C),"workB",(PetscObject)container);
456:   PetscContainerDestroy(&container);
457:   return(0);
458: }

460: /*
461:     Performs an efficient scatter on the rows of B needed by this process; this is
462:     a modification of the VecScatterBegin_() routines.
463: */
464: PetscErrorCode MatMPIDenseScatter(Mat A,Mat B,Mat C,Mat *outworkB)
465: {
466:   Mat_MPIAIJ             *aij = (Mat_MPIAIJ*)A->data;
467:   PetscErrorCode         ierr;
468:   const PetscScalar      *b;
469:   PetscScalar            *w,*svalues,*rvalues;
470:   VecScatter             ctx   = aij->Mvctx;
471:   PetscInt               i,j,k;
472:   const PetscInt         *sindices,*sstarts,*rindices,*rstarts;
473:   const PetscMPIInt      *sprocs,*rprocs;
474:   PetscInt               nsends,nrecvs,nrecvs2;
475:   MPI_Request            *swaits,*rwaits;
476:   MPI_Comm               comm;
477:   PetscMPIInt            tag  = ((PetscObject)ctx)->tag,ncols = B->cmap->N, nrows = aij->B->cmap->n,imdex,nrowsB = B->rmap->n,nsends_mpi,nrecvs_mpi;
478:   MPI_Status             status;
479:   MPIAIJ_MPIDense        *contents;
480:   PetscContainer         container;
481:   Mat                    workB;

484:   PetscObjectGetComm((PetscObject)A,&comm);
485:   PetscObjectQuery((PetscObject)C,"workB",(PetscObject*)&container);
486:   if (!container) SETERRQ(comm,PETSC_ERR_PLIB,"Container does not exist");
487:   PetscContainerGetPointer(container,(void**)&contents);

489:   workB = *outworkB = contents->workB;
490:   if (nrows != workB->rmap->n) SETERRQ2(comm,PETSC_ERR_PLIB,"Number of rows of workB %D not equal to columns of aij->B %D",nrows,workB->cmap->n);
491:   VecScatterGetRemote_Private(ctx,PETSC_TRUE/*send*/,&nsends,&sstarts,&sindices,&sprocs,NULL/*bs*/);
492:   VecScatterGetRemoteOrdered_Private(ctx,PETSC_FALSE/*recv*/,&nrecvs,&rstarts,&rindices,&rprocs,NULL/*bs*/);
493:   PetscMPIIntCast(nsends,&nsends_mpi);
494:   PetscMPIIntCast(nrecvs,&nrecvs_mpi);
495:   svalues = contents->svalues;
496:   rvalues = contents->rvalues;
497:   swaits  = contents->swaits;
498:   rwaits  = contents->rwaits;

500:   MatDenseGetArrayRead(B,&b);
501:   MatDenseGetArray(workB,&w);

503:   for (i=0; i<nrecvs; i++) {
504:     MPI_Irecv(rvalues+ncols*(rstarts[i]-rstarts[0]),ncols*(rstarts[i+1]-rstarts[i]),MPIU_SCALAR,rprocs[i],tag,comm,rwaits+i);
505:   }

507:   for (i=0; i<nsends; i++) {
508:     /* pack a message at a time */
509:     for (j=0; j<sstarts[i+1]-sstarts[i]; j++) {
510:       for (k=0; k<ncols; k++) {
511:         svalues[ncols*(sstarts[i]-sstarts[0]+j) + k] = b[sindices[sstarts[i]+j] + nrowsB*k];
512:       }
513:     }
514:     MPI_Isend(svalues+ncols*(sstarts[i]-sstarts[0]),ncols*(sstarts[i+1]-sstarts[i]),MPIU_SCALAR,sprocs[i],tag,comm,swaits+i);
515:   }

517:   nrecvs2 = nrecvs;
518:   while (nrecvs2) {
519:     MPI_Waitany(nrecvs_mpi,rwaits,&imdex,&status);
520:     nrecvs2--;
521:     /* unpack a message at a time */
522:     for (j=0; j<rstarts[imdex+1]-rstarts[imdex]; j++) {
523:       for (k=0; k<ncols; k++) {
524:         w[rindices[rstarts[imdex]+j] + nrows*k] = rvalues[ncols*(rstarts[imdex]-rstarts[0]+j) + k];
525:       }
526:     }
527:   }
528:   if (nsends) {MPI_Waitall(nsends_mpi,swaits,MPI_STATUSES_IGNORE);}

530:   VecScatterRestoreRemote_Private(ctx,PETSC_TRUE/*send*/,&nsends,&sstarts,&sindices,&sprocs,NULL/*bs*/);
531:   VecScatterRestoreRemoteOrdered_Private(ctx,PETSC_FALSE/*recv*/,&nrecvs,&rstarts,&rindices,&rprocs,NULL/*bs*/);
532:   MatDenseRestoreArrayRead(B,&b);
533:   MatDenseRestoreArray(workB,&w);
534:   MatAssemblyBegin(workB,MAT_FINAL_ASSEMBLY);
535:   MatAssemblyEnd(workB,MAT_FINAL_ASSEMBLY);
536:   return(0);

538: }
539: extern PetscErrorCode MatMatMultNumericAdd_SeqAIJ_SeqDense(Mat,Mat,Mat);

541: PetscErrorCode MatMatMultNumeric_MPIAIJ_MPIDense(Mat A,Mat B,Mat C)
542: {
544:   Mat_MPIAIJ     *aij    = (Mat_MPIAIJ*)A->data;
545:   Mat_MPIDense   *bdense = (Mat_MPIDense*)B->data;
546:   Mat_MPIDense   *cdense = (Mat_MPIDense*)C->data;
547:   Mat            workB;

550:   /* diagonal block of A times all local rows of B*/
551:   MatMatMultNumeric_SeqAIJ_SeqDense(aij->A,bdense->A,cdense->A);

553:   /* get off processor parts of B needed to complete the product */
554:   MatMPIDenseScatter(A,B,C,&workB);

556:   /* off-diagonal block of A times nonlocal rows of B */
557:   MatMatMultNumericAdd_SeqAIJ_SeqDense(aij->B,workB,cdense->A);
558:   MatAssemblyBegin(C,MAT_FINAL_ASSEMBLY);
559:   MatAssemblyEnd(C,MAT_FINAL_ASSEMBLY);
560:   return(0);
561: }

563: PetscErrorCode MatMatMultNumeric_MPIAIJ_MPIAIJ(Mat A,Mat P,Mat C)
564: {
566:   Mat_MPIAIJ     *a   = (Mat_MPIAIJ*)A->data,*c=(Mat_MPIAIJ*)C->data;
567:   Mat_SeqAIJ     *ad  = (Mat_SeqAIJ*)(a->A)->data,*ao=(Mat_SeqAIJ*)(a->B)->data;
568:   Mat_SeqAIJ     *cd  = (Mat_SeqAIJ*)(c->A)->data,*co=(Mat_SeqAIJ*)(c->B)->data;
569:   PetscInt       *adi = ad->i,*adj,*aoi=ao->i,*aoj;
570:   PetscScalar    *ada,*aoa,*cda=cd->a,*coa=co->a;
571:   Mat_SeqAIJ     *p_loc,*p_oth;
572:   PetscInt       *pi_loc,*pj_loc,*pi_oth,*pj_oth,*pj;
573:   PetscScalar    *pa_loc,*pa_oth,*pa,valtmp,*ca;
574:   PetscInt       cm    = C->rmap->n,anz,pnz;
575:   Mat_APMPI      *ptap = c->ap;
576:   PetscScalar    *apa_sparse;
577:   PetscInt       *api,*apj,*apJ,i,j,k,row;
578:   PetscInt       cstart = C->cmap->rstart;
579:   PetscInt       cdnz,conz,k0,k1,nextp;
580:   MPI_Comm       comm;
581:   PetscMPIInt    size;

584:   PetscObjectGetComm((PetscObject)C,&comm);
585:   MPI_Comm_size(comm,&size);

587:   if (!ptap->P_oth && size>1) {
588:     SETERRQ(comm,PETSC_ERR_ARG_WRONGSTATE,"AP cannot be reused. Do not call MatFreeIntermediateDataStructures() or use '-mat_freeintermediatedatastructures'");
589:   }
590:   apa_sparse = ptap->apa;

592:   /* 1) get P_oth = ptap->P_oth  and P_loc = ptap->P_loc */
593:   /*-----------------------------------------------------*/
594:   /* update numerical values of P_oth and P_loc */
595:   MatGetBrowsOfAoCols_MPIAIJ(A,P,MAT_REUSE_MATRIX,&ptap->startsj_s,&ptap->startsj_r,&ptap->bufa,&ptap->P_oth);
596:   MatMPIAIJGetLocalMat(P,MAT_REUSE_MATRIX,&ptap->P_loc);

598:   /* 2) compute numeric C_loc = A_loc*P = Ad*P_loc + Ao*P_oth */
599:   /*----------------------------------------------------------*/
600:   /* get data from symbolic products */
601:   p_loc = (Mat_SeqAIJ*)(ptap->P_loc)->data;
602:   pi_loc = p_loc->i; pj_loc = p_loc->j; pa_loc = p_loc->a;
603:   if (size >1) {
604:     p_oth = (Mat_SeqAIJ*)(ptap->P_oth)->data;
605:     pi_oth = p_oth->i; pj_oth = p_oth->j; pa_oth = p_oth->a;
606:   } else {
607:     p_oth = NULL; pi_oth = NULL; pj_oth = NULL; pa_oth = NULL;
608:   }

610:   api = ptap->api;
611:   apj = ptap->apj;
612:   for (i=0; i<cm; i++) {
613:     apJ = apj + api[i];

615:     /* diagonal portion of A */
616:     anz = adi[i+1] - adi[i];
617:     adj = ad->j + adi[i];
618:     ada = ad->a + adi[i];
619:     for (j=0; j<anz; j++) {
620:       row = adj[j];
621:       pnz = pi_loc[row+1] - pi_loc[row];
622:       pj  = pj_loc + pi_loc[row];
623:       pa  = pa_loc + pi_loc[row];
624:       /* perform sparse axpy */
625:       valtmp = ada[j];
626:       nextp  = 0;
627:       for (k=0; nextp<pnz; k++) {
628:         if (apJ[k] == pj[nextp]) { /* column of AP == column of P */
629:           apa_sparse[k] += valtmp*pa[nextp++];
630:         }
631:       }
632:       PetscLogFlops(2.0*pnz);
633:     }

635:     /* off-diagonal portion of A */
636:     anz = aoi[i+1] - aoi[i];
637:     aoj = ao->j + aoi[i];
638:     aoa = ao->a + aoi[i];
639:     for (j=0; j<anz; j++) {
640:       row = aoj[j];
641:       pnz = pi_oth[row+1] - pi_oth[row];
642:       pj  = pj_oth + pi_oth[row];
643:       pa  = pa_oth + pi_oth[row];
644:       /* perform sparse axpy */
645:       valtmp = aoa[j];
646:       nextp  = 0;
647:       for (k=0; nextp<pnz; k++) {
648:         if (apJ[k] == pj[nextp]) { /* column of AP == column of P */
649:           apa_sparse[k] += valtmp*pa[nextp++];
650:         }
651:       }
652:       PetscLogFlops(2.0*pnz);
653:     }

655:     /* set values in C */
656:     cdnz = cd->i[i+1] - cd->i[i];
657:     conz = co->i[i+1] - co->i[i];

659:     /* 1st off-diagoanl part of C */
660:     ca = coa + co->i[i];
661:     k  = 0;
662:     for (k0=0; k0<conz; k0++) {
663:       if (apJ[k] >= cstart) break;
664:       ca[k0]        = apa_sparse[k];
665:       apa_sparse[k] = 0.0;
666:       k++;
667:     }

669:     /* diagonal part of C */
670:     ca = cda + cd->i[i];
671:     for (k1=0; k1<cdnz; k1++) {
672:       ca[k1]        = apa_sparse[k];
673:       apa_sparse[k] = 0.0;
674:       k++;
675:     }

677:     /* 2nd off-diagoanl part of C */
678:     ca = coa + co->i[i];
679:     for (; k0<conz; k0++) {
680:       ca[k0]        = apa_sparse[k];
681:       apa_sparse[k] = 0.0;
682:       k++;
683:     }
684:   }
685:   MatAssemblyBegin(C,MAT_FINAL_ASSEMBLY);
686:   MatAssemblyEnd(C,MAT_FINAL_ASSEMBLY);

688:   if (ptap->freestruct) {
689:     MatFreeIntermediateDataStructures(C);
690:   }
691:   return(0);
692: }

694: /* same as MatMatMultSymbolic_MPIAIJ_MPIAIJ_nonscalable(), except using LLCondensed to avoid O(BN) memory requirement */
695: PetscErrorCode MatMatMultSymbolic_MPIAIJ_MPIAIJ(Mat A,Mat P,PetscReal fill,Mat *C)
696: {
697:   PetscErrorCode     ierr;
698:   MPI_Comm           comm;
699:   PetscMPIInt        size;
700:   Mat                Cmpi;
701:   Mat_APMPI          *ptap;
702:   PetscFreeSpaceList free_space = NULL,current_space=NULL;
703:   Mat_MPIAIJ         *a         = (Mat_MPIAIJ*)A->data,*c;
704:   Mat_SeqAIJ         *ad        = (Mat_SeqAIJ*)(a->A)->data,*ao=(Mat_SeqAIJ*)(a->B)->data,*p_loc,*p_oth;
705:   PetscInt           *pi_loc,*pj_loc,*pi_oth,*pj_oth,*dnz,*onz;
706:   PetscInt           *adi=ad->i,*adj=ad->j,*aoi=ao->i,*aoj=ao->j,rstart=A->rmap->rstart;
707:   PetscInt           i,pnz,row,*api,*apj,*Jptr,apnz,nspacedouble=0,j,nzi,*lnk,apnz_max=0;
708:   PetscInt           am=A->rmap->n,pn=P->cmap->n,pm=P->rmap->n,lsize=pn+20;
709:   PetscReal          afill;
710:   MatType            mtype;

713:   PetscObjectGetComm((PetscObject)A,&comm);
714:   MPI_Comm_size(comm,&size);

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

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

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

725:   p_loc  = (Mat_SeqAIJ*)(ptap->P_loc)->data;
726:   pi_loc = p_loc->i; pj_loc = p_loc->j;
727:   if (size > 1) {
728:     p_oth  = (Mat_SeqAIJ*)(ptap->P_oth)->data;
729:     pi_oth = p_oth->i; pj_oth = p_oth->j;
730:   } else {
731:     p_oth  = NULL;
732:     pi_oth = NULL; pj_oth = NULL;
733:   }

735:   /* first, compute symbolic AP = A_loc*P = A_diag*P_loc + A_off*P_oth */
736:   /*-------------------------------------------------------------------*/
737:   PetscMalloc1(am+2,&api);
738:   ptap->api = api;
739:   api[0]    = 0;

741:   PetscLLCondensedCreate_Scalable(lsize,&lnk);

743:   /* Initial FreeSpace size is fill*(nnz(A)+nnz(P)) */
744:   PetscFreeSpaceGet(PetscRealIntMultTruncate(fill,PetscIntSumTruncate(adi[am],PetscIntSumTruncate(aoi[am],pi_loc[pm]))),&free_space);
745:   current_space = free_space;
746:   MatPreallocateInitialize(comm,am,pn,dnz,onz);
747:   for (i=0; i<am; i++) {
748:     /* diagonal portion of A */
749:     nzi = adi[i+1] - adi[i];
750:     for (j=0; j<nzi; j++) {
751:       row  = *adj++;
752:       pnz  = pi_loc[row+1] - pi_loc[row];
753:       Jptr = pj_loc + pi_loc[row];
754:       /* Expand list if it is not long enough */
755:       if (pnz+apnz_max > lsize) {
756:         lsize = pnz+apnz_max;
757:         PetscLLCondensedExpand_Scalable(lsize, &lnk);
758:       }
759:       /* add non-zero cols of P into the sorted linked list lnk */
760:       PetscLLCondensedAddSorted_Scalable(pnz,Jptr,lnk);
761:       apnz     = *lnk; /* The first element in the list is the number of items in the list */
762:       api[i+1] = api[i] + apnz;
763:       if (apnz > apnz_max) apnz_max = apnz;
764:     }
765:     /* off-diagonal portion of A */
766:     nzi = aoi[i+1] - aoi[i];
767:     for (j=0; j<nzi; j++) {
768:       row  = *aoj++;
769:       pnz  = pi_oth[row+1] - pi_oth[row];
770:       Jptr = pj_oth + pi_oth[row];
771:       /* Expand list if it is not long enough */
772:       if (pnz+apnz_max > lsize) {
773:         lsize = pnz + apnz_max;
774:         PetscLLCondensedExpand_Scalable(lsize, &lnk);
775:       }
776:       /* add non-zero cols of P into the sorted linked list lnk */
777:       PetscLLCondensedAddSorted_Scalable(pnz,Jptr,lnk);
778:       apnz     = *lnk;  /* The first element in the list is the number of items in the list */
779:       api[i+1] = api[i] + apnz;
780:       if (apnz > apnz_max) apnz_max = apnz;
781:     }
782:     apnz     = *lnk;
783:     api[i+1] = api[i] + apnz;
784:     if (apnz > apnz_max) apnz_max = apnz;

786:     /* if free space is not available, double the total space in the list */
787:     if (current_space->local_remaining<apnz) {
788:       PetscFreeSpaceGet(PetscIntSumTruncate(apnz,current_space->total_array_size),&current_space);
789:       nspacedouble++;
790:     }

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

796:     current_space->array           += apnz;
797:     current_space->local_used      += apnz;
798:     current_space->local_remaining -= apnz;
799:   }

801:   /* Allocate space for apj, initialize apj, and */
802:   /* destroy list of free space and other temporary array(s) */
803:   PetscMalloc1(api[am]+1,&ptap->apj);
804:   apj  = ptap->apj;
805:   PetscFreeSpaceContiguous(&free_space,ptap->apj);
806:   PetscLLCondensedDestroy_Scalable(lnk);

808:   /* create and assemble symbolic parallel matrix Cmpi */
809:   /*----------------------------------------------------*/
810:   MatCreate(comm,&Cmpi);
811:   MatSetSizes(Cmpi,am,pn,PETSC_DETERMINE,PETSC_DETERMINE);
812:   MatSetBlockSizesFromMats(Cmpi,A,P);
813:   MatGetType(A,&mtype);
814:   MatSetType(Cmpi,mtype);
815:   MatMPIAIJSetPreallocation(Cmpi,0,dnz,0,onz);

817:   /* malloc apa for assembly Cmpi */
818:   PetscCalloc1(apnz_max,&ptap->apa);

820:   MatSetValues_MPIAIJ_CopyFromCSRFormat_Symbolic(Cmpi, apj, api);
821:   MatAssemblyBegin(Cmpi,MAT_FINAL_ASSEMBLY);
822:   MatAssemblyEnd(Cmpi,MAT_FINAL_ASSEMBLY);
823:   MatPreallocateFinalize(dnz,onz);

825:   ptap->destroy             = Cmpi->ops->destroy;
826:   ptap->duplicate           = Cmpi->ops->duplicate;
827:   Cmpi->ops->matmultnumeric = MatMatMultNumeric_MPIAIJ_MPIAIJ;
828:   Cmpi->ops->destroy        = MatDestroy_MPIAIJ_MatMatMult;
829:   Cmpi->ops->freeintermediatedatastructures = MatFreeIntermediateDataStructures_MPIAIJ_AP;

831:   /* attach the supporting struct to Cmpi for reuse */
832:   c       = (Mat_MPIAIJ*)Cmpi->data;
833:   c->ap = ptap;
834:   *C = Cmpi;

836:   /* set MatInfo */
837:   afill = (PetscReal)api[am]/(adi[am]+aoi[am]+pi_loc[pm]+1) + 1.e-5;
838:   if (afill < 1.0) afill = 1.0;
839:   Cmpi->info.mallocs           = nspacedouble;
840:   Cmpi->info.fill_ratio_given  = fill;
841:   Cmpi->info.fill_ratio_needed = afill;

843: #if defined(PETSC_USE_INFO)
844:   if (api[am]) {
845:     PetscInfo3(Cmpi,"Reallocs %D; Fill ratio: given %g needed %g.\n",nspacedouble,(double)fill,(double)afill);
846:     PetscInfo1(Cmpi,"Use MatMatMult(A,B,MatReuse,%g,&C) for best performance.;\n",(double)afill);
847:   } else {
848:     PetscInfo(Cmpi,"Empty matrix product\n");
849:   }
850: #endif
851:   return(0);
852: }

854: /* This function is needed for the seqMPI matrix-matrix multiplication.  */
855: /* Three input arrays are merged to one output array. The size of the    */
856: /* output array is also output. Duplicate entries only show up once.     */
857: static void Merge3SortedArrays(PetscInt  size1, PetscInt *in1,
858:                                PetscInt  size2, PetscInt *in2,
859:                                PetscInt  size3, PetscInt *in3,
860:                                PetscInt *size4, PetscInt *out)
861: {
862:   int i = 0, j = 0, k = 0, l = 0;

864:   /* Traverse all three arrays */
865:   while (i<size1 && j<size2 && k<size3) {
866:     if (in1[i] < in2[j] && in1[i] < in3[k]) {
867:       out[l++] = in1[i++];
868:     }
869:     else if(in2[j] < in1[i] && in2[j] < in3[k]) {
870:       out[l++] = in2[j++];
871:     }
872:     else if(in3[k] < in1[i] && in3[k] < in2[j]) {
873:       out[l++] = in3[k++];
874:     }
875:     else if(in1[i] == in2[j] && in1[i] < in3[k]) {
876:       out[l++] = in1[i];
877:       i++, j++;
878:     }
879:     else if(in1[i] == in3[k] && in1[i] < in2[j]) {
880:       out[l++] = in1[i];
881:       i++, k++;
882:     }
883:     else if(in3[k] == in2[j] && in2[j] < in1[i])  {
884:       out[l++] = in2[j];
885:       k++, j++;
886:     }
887:     else if(in1[i] == in2[j] && in1[i] == in3[k]) {
888:       out[l++] = in1[i];
889:       i++, j++, k++;
890:     }
891:   }

893:   /* Traverse two remaining arrays */
894:   while (i<size1 && j<size2) {
895:     if (in1[i] < in2[j]) {
896:       out[l++] = in1[i++];
897:     }
898:     else if(in1[i] > in2[j]) {
899:       out[l++] = in2[j++];
900:     }
901:     else {
902:       out[l++] = in1[i];
903:       i++, j++;
904:     }
905:   }

907:   while (i<size1 && k<size3) {
908:     if (in1[i] < in3[k]) {
909:       out[l++] = in1[i++];
910:     }
911:     else if(in1[i] > in3[k]) {
912:       out[l++] = in3[k++];
913:     }
914:     else {
915:       out[l++] = in1[i];
916:       i++, k++;
917:     }
918:   }

920:   while (k<size3 && j<size2)  {
921:     if (in3[k] < in2[j]) {
922:       out[l++] = in3[k++];
923:     }
924:     else if(in3[k] > in2[j]) {
925:       out[l++] = in2[j++];
926:     }
927:     else {
928:       out[l++] = in3[k];
929:       k++, j++;
930:     }
931:   }

933:   /* Traverse one remaining array */
934:   while (i<size1) out[l++] = in1[i++];
935:   while (j<size2) out[l++] = in2[j++];
936:   while (k<size3) out[l++] = in3[k++];

938:   *size4 = l;
939: }

941: /* This matrix-matrix multiplication algorithm divides the multiplication into three multiplications and  */
942: /* adds up the products. Two of these three multiplications are performed with existing (sequential)      */
943: /* matrix-matrix multiplications.  */
944: PetscErrorCode MatMatMultSymbolic_MPIAIJ_MPIAIJ_seqMPI(Mat A, Mat P, PetscReal fill, Mat *C)
945: {
946:   PetscErrorCode     ierr;
947:   MPI_Comm           comm;
948:   PetscMPIInt        size;
949:   Mat                Cmpi;
950:   Mat_APMPI          *ptap;
951:   PetscFreeSpaceList free_space_diag=NULL, current_space=NULL;
952:   Mat_MPIAIJ         *a        =(Mat_MPIAIJ*)A->data;
953:   Mat_SeqAIJ         *ad       =(Mat_SeqAIJ*)(a->A)->data,*ao=(Mat_SeqAIJ*)(a->B)->data,*p_loc;
954:   Mat_MPIAIJ         *p        =(Mat_MPIAIJ*)P->data;
955:   Mat_MPIAIJ         *c;
956:   Mat_SeqAIJ         *adpd_seq, *p_off, *aopoth_seq;
957:   PetscInt           adponz, adpdnz;
958:   PetscInt           *pi_loc,*dnz,*onz;
959:   PetscInt           *adi=ad->i,*adj=ad->j,*aoi=ao->i,rstart=A->rmap->rstart;
960:   PetscInt           *lnk,i, i1=0,pnz,row,*adpoi,*adpoj, *api, *adpoJ, *aopJ, *apJ,*Jptr, aopnz, nspacedouble=0,j,nzi,
961:                      *apj,apnz, *adpdi, *adpdj, *adpdJ, *poff_i, *poff_j, *j_temp, *aopothi, *aopothj;
962:   PetscInt           am=A->rmap->n,pN=P->cmap->N,pn=P->cmap->n,pm=P->rmap->n, p_colstart, p_colend;
963:   PetscBT            lnkbt;
964:   PetscReal          afill;
965:   PetscMPIInt        rank;
966:   Mat                adpd, aopoth;
967:   MatType            mtype;
968:   const char         *prefix;

971:   PetscObjectGetComm((PetscObject)A,&comm);
972:   MPI_Comm_size(comm,&size);
973:   MPI_Comm_rank(comm, &rank);
974:   MatGetOwnershipRangeColumn(P, &p_colstart, &p_colend);

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

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

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


986:   p_loc  = (Mat_SeqAIJ*)(ptap->P_loc)->data;
987:   pi_loc = p_loc->i;

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

993:   adpoi[0]    = 0;
994:   ptap->api = api;
995:   api[0] = 0;

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

1001:   /* Symbolic calc of A_loc_diag * P_loc_diag */
1002:   MatGetOptionsPrefix(A,&prefix);
1003:   MatSetOptionsPrefix(a->A,prefix);
1004:   MatAppendOptionsPrefix(a->A,"inner_diag_");
1005:   MatMatMultSymbolic_SeqAIJ_SeqAIJ(a->A, p->A, fill, &adpd);
1006:   adpd_seq = (Mat_SeqAIJ*)((adpd)->data);
1007:   adpdi = adpd_seq->i; adpdj = adpd_seq->j;
1008:   p_off = (Mat_SeqAIJ*)((p->B)->data);
1009:   poff_i = p_off->i; poff_j = p_off->j;

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


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

1020:   for (i=0; i<am; i++) {
1021:     /* A_diag * P_loc_off */
1022:     nzi = adi[i+1] - adi[i];
1023:     for (j=0; j<nzi; j++) {
1024:       row  = *adj++;
1025:       pnz  = poff_i[row+1] - poff_i[row];
1026:       Jptr = poff_j + poff_i[row];
1027:       for(i1 = 0; i1 < pnz; i1++) {
1028:         j_temp[i1] = p->garray[Jptr[i1]];
1029:       }
1030:       /* add non-zero cols of P into the sorted linked list lnk */
1031:       PetscLLCondensedAddSorted(pnz,j_temp,lnk,lnkbt);
1032:     }

1034:     adponz     = lnk[0];
1035:     adpoi[i+1] = adpoi[i] + adponz;

1037:     /* if free space is not available, double the total space in the list */
1038:     if (current_space->local_remaining<adponz) {
1039:       PetscFreeSpaceGet(PetscIntSumTruncate(adponz,current_space->total_array_size),&current_space);
1040:       nspacedouble++;
1041:     }

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

1046:     current_space->array           += adponz;
1047:     current_space->local_used      += adponz;
1048:     current_space->local_remaining -= adponz;
1049:   }

1051:   /* Symbolic calc of A_off * P_oth */
1052:   MatSetOptionsPrefix(a->B,prefix);
1053:   MatAppendOptionsPrefix(a->B,"inner_offdiag_");
1054:   MatMatMultSymbolic_SeqAIJ_SeqAIJ(a->B, ptap->P_oth, fill, &aopoth);
1055:   aopoth_seq = (Mat_SeqAIJ*)((aopoth)->data);
1056:   aopothi = aopoth_seq->i; aopothj = aopoth_seq->j;

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

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

1064:   /* Copy from linked list to j-array */
1065:   PetscFreeSpaceContiguous(&free_space_diag,adpoj);
1066:   PetscLLDestroy(lnk,lnkbt);

1068:   adpoJ = adpoj;
1069:   adpdJ = adpdj;
1070:   aopJ = aopothj;
1071:   apj  = ptap->apj;
1072:   apJ = apj; /* still empty */

1074:   /* Merge j-arrays of A_off * P, A_diag * P_loc_off, and */
1075:   /* A_diag * P_loc_diag to get A*P */
1076:   for (i = 0; i < am; i++) {
1077:     aopnz  =  aopothi[i+1] -  aopothi[i];
1078:     adponz = adpoi[i+1] - adpoi[i];
1079:     adpdnz = adpdi[i+1] - adpdi[i];

1081:     /* Correct indices from A_diag*P_diag */
1082:     for(i1 = 0; i1 < adpdnz; i1++) {
1083:       adpdJ[i1] += p_colstart;
1084:     }
1085:     /* Merge j-arrays of A_diag * P_loc_off and A_diag * P_loc_diag and A_off * P_oth */
1086:     Merge3SortedArrays(adponz, adpoJ, adpdnz, adpdJ, aopnz, aopJ, &apnz, apJ);
1087:     MatPreallocateSet(i+rstart, apnz, apJ, dnz, onz);

1089:     aopJ += aopnz;
1090:     adpoJ += adponz;
1091:     adpdJ += adpdnz;
1092:     apJ += apnz;
1093:     api[i+1] = api[i] + apnz;
1094:   }

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

1099:   /* create and assemble symbolic parallel matrix Cmpi */
1100:   MatCreate(comm,&Cmpi);
1101:   MatSetSizes(Cmpi,am,pn,PETSC_DETERMINE,PETSC_DETERMINE);
1102:   MatSetBlockSizesFromMats(Cmpi,A,P);
1103:   MatGetType(A,&mtype);
1104:   MatSetType(Cmpi,mtype);
1105:   MatMPIAIJSetPreallocation(Cmpi,0,dnz,0,onz);


1108:   MatSetValues_MPIAIJ_CopyFromCSRFormat_Symbolic(Cmpi, apj, api);
1109:   MatAssemblyBegin(Cmpi,MAT_FINAL_ASSEMBLY);
1110:   MatAssemblyEnd(Cmpi,MAT_FINAL_ASSEMBLY);
1111:   MatPreallocateFinalize(dnz,onz);


1114:   ptap->destroy        = Cmpi->ops->destroy;
1115:   ptap->duplicate      = Cmpi->ops->duplicate;
1116:   Cmpi->ops->matmultnumeric = MatMatMultNumeric_MPIAIJ_MPIAIJ_nonscalable;
1117:   Cmpi->ops->destroy   = MatDestroy_MPIAIJ_MatMatMult;

1119:   /* attach the supporting struct to Cmpi for reuse */
1120:   c       = (Mat_MPIAIJ*)Cmpi->data;
1121:   c->ap = ptap;
1122:   *C = Cmpi;

1124:   /* set MatInfo */
1125:   afill = (PetscReal)api[am]/(adi[am]+aoi[am]+pi_loc[pm]+1) + 1.e-5;
1126:   if (afill < 1.0) afill = 1.0;
1127:   Cmpi->info.mallocs           = nspacedouble;
1128:   Cmpi->info.fill_ratio_given  = fill;
1129:   Cmpi->info.fill_ratio_needed = afill;

1131: #if defined(PETSC_USE_INFO)
1132:   if (api[am]) {
1133:     PetscInfo3(Cmpi,"Reallocs %D; Fill ratio: given %g needed %g.\n",nspacedouble,(double)fill,(double)afill);
1134:     PetscInfo1(Cmpi,"Use MatMatMult(A,B,MatReuse,%g,&C) for best performance.;\n",(double)afill);
1135:   } else {
1136:     PetscInfo(Cmpi,"Empty matrix product\n");
1137:   }
1138: #endif

1140:   MatDestroy(&aopoth);
1141:   MatDestroy(&adpd);
1142:   PetscFree(j_temp);
1143:   PetscFree(adpoj);
1144:   PetscFree(adpoi);
1145:   return(0);
1146: }


1149: /*-------------------------------------------------------------------------*/
1150: PetscErrorCode MatTransposeMatMult_MPIAIJ_MPIAIJ(Mat P,Mat A,MatReuse scall,PetscReal fill,Mat *C)
1151: {
1153:   const char     *algTypes[3] = {"scalable","nonscalable","matmatmult"};
1154:   PetscInt       aN=A->cmap->N,alg=1; /* set default algorithm */
1155:   PetscBool      flg;

1158:   if (scall == MAT_INITIAL_MATRIX) {
1159:     PetscOptionsBegin(PetscObjectComm((PetscObject)A),((PetscObject)A)->prefix,"MatTransposeMatMult","Mat");
1160:     PetscOptionsEList("-mattransposematmult_via","Algorithmic approach","MatTransposeMatMult",algTypes,3,algTypes[1],&alg,&flg);
1161:     PetscOptionsEnd();

1163:     PetscLogEventBegin(MAT_TransposeMatMultSymbolic,P,A,0,0);
1164:     switch (alg) {
1165:     case 1:
1166:       if (!flg && aN > 100000) { /* may switch to scalable algorithm as default */
1167:         MatInfo     Ainfo,Pinfo;
1168:         PetscInt    nz_local;
1169:         PetscBool   alg_scalable_loc=PETSC_FALSE,alg_scalable;
1170:         MPI_Comm    comm;

1172:         MatGetInfo(A,MAT_LOCAL,&Ainfo);
1173:         MatGetInfo(P,MAT_LOCAL,&Pinfo);
1174:         nz_local = (PetscInt)(Ainfo.nz_allocated + Pinfo.nz_allocated); /* estimated local nonzero entries */

1176:         if (aN > fill*nz_local) alg_scalable_loc = PETSC_TRUE;
1177:         PetscObjectGetComm((PetscObject)A,&comm);
1178:         MPIU_Allreduce(&alg_scalable_loc,&alg_scalable,1,MPIU_BOOL,MPI_LOR,comm);

1180:         if (alg_scalable) {
1181:           alg  = 0; /* scalable algorithm would slower than nonscalable algorithm */
1182:           MatTransposeMatMultSymbolic_MPIAIJ_MPIAIJ(P,A,fill,C);
1183:           break;
1184:         }
1185:       }
1186:       MatTransposeMatMultSymbolic_MPIAIJ_MPIAIJ_nonscalable(P,A,fill,C);
1187:       break;
1188:     case 2:
1189:     {
1190:       Mat         Pt;
1191:       Mat_APMPI   *ptap;
1192:       Mat_MPIAIJ  *c;
1193:       MatTranspose(P,MAT_INITIAL_MATRIX,&Pt);
1194:       MatMatMult(Pt,A,MAT_INITIAL_MATRIX,fill,C);
1195:       c        = (Mat_MPIAIJ*)(*C)->data;
1196:       ptap     = c->ap;
1197:       if (ptap) {
1198:        ptap->Pt = Pt;
1199:        (*C)->ops->freeintermediatedatastructures = MatFreeIntermediateDataStructures_MPIAIJ_AP;
1200:       }
1201:       (*C)->ops->mattransposemultnumeric = MatTransposeMatMultNumeric_MPIAIJ_MPIAIJ_matmatmult;
1202:       return(0);
1203:     }
1204:       break;
1205:     default: /* scalable algorithm */
1206:       MatTransposeMatMultSymbolic_MPIAIJ_MPIAIJ(P,A,fill,C);
1207:       break;
1208:     }
1209:     PetscLogEventEnd(MAT_TransposeMatMultSymbolic,P,A,0,0);

1211:     {
1212:       Mat_MPIAIJ *c  = (Mat_MPIAIJ*)(*C)->data;
1213:       Mat_APMPI  *ap = c->ap;
1214:       PetscOptionsBegin(PetscObjectComm((PetscObject)(*C)),((PetscObject)(*C))->prefix,"MatFreeIntermediateDataStructures","Mat");
1215:       ap->freestruct = PETSC_FALSE;
1216:       PetscOptionsBool("-mat_freeintermediatedatastructures","Free intermediate data structures", "MatFreeIntermediateDataStructures",ap->freestruct,&ap->freestruct, NULL);
1217:       PetscOptionsEnd();
1218:     }
1219:   }

1221:   PetscLogEventBegin(MAT_TransposeMatMultNumeric,P,A,0,0);
1222:   (*(*C)->ops->mattransposemultnumeric)(P,A,*C);
1223:   PetscLogEventEnd(MAT_TransposeMatMultNumeric,P,A,0,0);
1224:   return(0);
1225: }

1227: /* This routine only works when scall=MAT_REUSE_MATRIX! */
1228: PetscErrorCode MatTransposeMatMultNumeric_MPIAIJ_MPIAIJ_matmatmult(Mat P,Mat A,Mat C)
1229: {
1231:   Mat_MPIAIJ     *c=(Mat_MPIAIJ*)C->data;
1232:   Mat_APMPI      *ptap= c->ap;
1233:   Mat            Pt;

1236:   if (!ptap->Pt) {
1237:     MPI_Comm comm;
1238:     PetscObjectGetComm((PetscObject)C,&comm);
1239:     SETERRQ(comm,PETSC_ERR_ARG_WRONGSTATE,"PtA cannot be reused. Do not call MatFreeIntermediateDataStructures() or use '-mat_freeintermediatedatastructures'");
1240:   }

1242:   Pt=ptap->Pt;
1243:   MatTranspose(P,MAT_REUSE_MATRIX,&Pt);
1244:   MatMatMultNumeric(Pt,A,C);

1246:   /* supporting struct ptap consumes almost same amount of memory as C=PtAP, release it if C will not be updated by A and P */
1247:   if (ptap->freestruct) {
1248:     MatFreeIntermediateDataStructures(C);
1249:   }
1250:   return(0);
1251: }

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

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

1286:   /* create symbolic parallel matrix Cmpi */
1287:   MatCreate(comm,&Cmpi);
1288:   MatGetType(A,&mtype);
1289:   MatSetType(Cmpi,mtype);

1291:   Cmpi->ops->mattransposemultnumeric = MatTransposeMatMultNumeric_MPIAIJ_MPIAIJ_nonscalable;

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

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

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

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

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

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

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

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

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

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

1364:   /* (2-2) compute symbolic C_loc = Rd*A_loc */
1365:   /* ---------------------------------------- */
1366:   MatSetOptionsPrefix(ptap->Rd,prefix);
1367:   MatAppendOptionsPrefix(ptap->Rd,"inner_diag_");
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 Cmpi      */
1435:   /* ------------------------------------------ */
1436:   /* set initial free space to be Crmax, sufficient for holding nozeros in each row of Cmpi */
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++) {
1451:     /* add C_loc into Cmpi */
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:     }
1465:     nzi = lnk[0];

1467:     /* copy data into free space, then initialize lnk */
1468:     PetscLLCondensedClean(aN,nzi,current_space->array,lnk,lnkbt);
1469:     MatPreallocateSet(i+owners[rank],nzi,current_space->array,dnz,onz);
1470:   }
1471:   PetscFree3(buf_ri_k,nextrow,nextci);
1472:   PetscLLDestroy(lnk,lnkbt);
1473:   PetscFreeSpaceDestroy(free_space);

1475:   /* local sizes and preallocation */
1476:   MatSetSizes(Cmpi,pn,an,PETSC_DETERMINE,PETSC_DETERMINE);
1477:   if (P->cmap->bs > 0) {PetscLayoutSetBlockSize(Cmpi->rmap,P->cmap->bs);}
1478:   if (A->cmap->bs > 0) {PetscLayoutSetBlockSize(Cmpi->cmap,A->cmap->bs);}
1479:   MatMPIAIJSetPreallocation(Cmpi,0,dnz,0,onz);
1480:   MatPreallocateFinalize(dnz,onz);

1482:   /* members in merge */
1483:   PetscFree(id_r);
1484:   PetscFree(len_r);
1485:   PetscFree(buf_ri[0]);
1486:   PetscFree(buf_ri);
1487:   PetscFree(buf_rj[0]);
1488:   PetscFree(buf_rj);
1489:   PetscLayoutDestroy(&rowmap);

1491:   /* attach the supporting struct to Cmpi for reuse */
1492:   c = (Mat_MPIAIJ*)Cmpi->data;
1493:   c->ap         = ptap;
1494:   ptap->destroy = Cmpi->ops->destroy;

1496:   /* Cmpi is not ready for use - assembly will be done by MatPtAPNumeric() */
1497:   Cmpi->assembled        = PETSC_FALSE;
1498:   Cmpi->ops->destroy     = MatDestroy_MPIAIJ_PtAP;
1499:   Cmpi->ops->freeintermediatedatastructures = MatFreeIntermediateDataStructures_MPIAIJ_AP;

1501:   *C                     = Cmpi;
1502:   return(0);
1503: }

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

1517:   if (!ptap->A_loc) {
1518:     MPI_Comm comm;
1519:     PetscObjectGetComm((PetscObject)C,&comm);
1520:     SETERRQ(comm,PETSC_ERR_ARG_WRONGSTATE,"PtA cannot be reused. Do not call MatFreeIntermediateDataStructures() or use '-mat_freeintermediatedatastructures'");
1521:   }

1523:   MatZeroEntries(C);

1525:   if (ptap->reuse == MAT_REUSE_MATRIX) {
1526:     /* These matrices are obtained in MatTransposeMatMultSymbolic() */
1527:     /* 1) get R = Pd^T, Ro = Po^T */
1528:     /*----------------------------*/
1529:     MatTranspose_SeqAIJ(p->A,MAT_REUSE_MATRIX,&ptap->Rd);
1530:     MatTranspose_SeqAIJ(p->B,MAT_REUSE_MATRIX,&ptap->Ro);

1532:     /* 2) compute numeric A_loc */
1533:     /*--------------------------*/
1534:     MatMPIAIJGetLocalMat(A,MAT_REUSE_MATRIX,&ptap->A_loc);
1535:   }

1537:   /* 3) C_loc = Rd*A_loc, C_oth = Ro*A_loc */
1538:   A_loc = ptap->A_loc;
1539:   ((ptap->C_loc)->ops->matmultnumeric)(ptap->Rd,A_loc,ptap->C_loc);
1540:   ((ptap->C_oth)->ops->matmultnumeric)(ptap->Ro,A_loc,ptap->C_oth);
1541:   C_loc = ptap->C_loc;
1542:   C_oth = ptap->C_oth;

1544:   /* add C_loc and Co to to C */
1545:   MatGetOwnershipRange(C,&rstart,&rend);

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

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

1573:   ptap->reuse = MAT_REUSE_MATRIX;

1575:   /* supporting struct ptap consumes almost same amount of memory as C=PtAP, release it if C will not be updated by A and P */
1576:   if (ptap->freestruct) {
1577:     MatFreeIntermediateDataStructures(C);
1578:   }
1579:   return(0);
1580: }

1582: PetscErrorCode MatTransposeMatMultNumeric_MPIAIJ_MPIAIJ(Mat P,Mat A,Mat C)
1583: {
1584:   PetscErrorCode      ierr;
1585:   Mat_Merge_SeqsToMPI *merge;
1586:   Mat_MPIAIJ          *p =(Mat_MPIAIJ*)P->data,*c=(Mat_MPIAIJ*)C->data;
1587:   Mat_SeqAIJ          *pd=(Mat_SeqAIJ*)(p->A)->data,*po=(Mat_SeqAIJ*)(p->B)->data;
1588:   Mat_APMPI           *ptap;
1589:   PetscInt            *adj;
1590:   PetscInt            i,j,k,anz,pnz,row,*cj,nexta;
1591:   MatScalar           *ada,*ca,valtmp;
1592:   PetscInt            am  =A->rmap->n,cm=C->rmap->n,pon=(p->B)->cmap->n;
1593:   MPI_Comm            comm;
1594:   PetscMPIInt         size,rank,taga,*len_s;
1595:   PetscInt            *owners,proc,nrows,**buf_ri_k,**nextrow,**nextci;
1596:   PetscInt            **buf_ri,**buf_rj;
1597:   PetscInt            cnz=0,*bj_i,*bi,*bj,bnz,nextcj;  /* bi,bj,ba: local array of C(mpi mat) */
1598:   MPI_Request         *s_waits,*r_waits;
1599:   MPI_Status          *status;
1600:   MatScalar           **abuf_r,*ba_i,*pA,*coa,*ba;
1601:   PetscInt            *ai,*aj,*coi,*coj,*poJ,*pdJ;
1602:   Mat                 A_loc;
1603:   Mat_SeqAIJ          *a_loc;

1606:   PetscObjectGetComm((PetscObject)C,&comm);
1607:   MPI_Comm_size(comm,&size);
1608:   MPI_Comm_rank(comm,&rank);

1610:   ptap  = c->ap;
1611:   if (!ptap->A_loc) SETERRQ(comm,PETSC_ERR_ARG_WRONGSTATE,"PtA cannot be reused. Do not call MatFreeIntermediateDataStructures() or use '-mat_freeintermediatedatastructures'");
1612:   merge = ptap->merge;

1614:   /* 2) compute numeric C_seq = P_loc^T*A_loc */
1615:   /*------------------------------------------*/
1616:   /* get data from symbolic products */
1617:   coi    = merge->coi; coj = merge->coj;
1618:   PetscCalloc1(coi[pon]+1,&coa);
1619:   bi     = merge->bi; bj = merge->bj;
1620:   owners = merge->rowmap->range;
1621:   PetscCalloc1(bi[cm]+1,&ba);

1623:   /* get A_loc by taking all local rows of A */
1624:   A_loc = ptap->A_loc;
1625:   MatMPIAIJGetLocalMat(A,MAT_REUSE_MATRIX,&A_loc);
1626:   a_loc = (Mat_SeqAIJ*)(A_loc)->data;
1627:   ai    = a_loc->i;
1628:   aj    = a_loc->j;

1630:   for (i=0; i<am; i++) {
1631:     anz = ai[i+1] - ai[i];
1632:     adj = aj + ai[i];
1633:     ada = a_loc->a + ai[i];

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

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

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

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

1696:   PetscFree2(s_waits,status);
1697:   PetscFree(r_waits);
1698:   PetscFree(coa);

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

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

1737:   PetscFree(ba);
1738:   PetscFree(abuf_r[0]);
1739:   PetscFree(abuf_r);
1740:   PetscFree3(buf_ri_k,nextrow,nextci);

1742:   if (ptap->freestruct) {
1743:     MatFreeIntermediateDataStructures(C);
1744:   }
1745:   return(0);
1746: }

1748: PetscErrorCode MatTransposeMatMultSymbolic_MPIAIJ_MPIAIJ(Mat P,Mat A,PetscReal fill,Mat *C)
1749: {
1750:   PetscErrorCode      ierr;
1751:   Mat                 Cmpi,A_loc,POt,PDt;
1752:   Mat_APMPI           *ptap;
1753:   PetscFreeSpaceList  free_space=NULL,current_space=NULL;
1754:   Mat_MPIAIJ          *p=(Mat_MPIAIJ*)P->data,*a=(Mat_MPIAIJ*)A->data,*c;
1755:   PetscInt            *pdti,*pdtj,*poti,*potj,*ptJ;
1756:   PetscInt            nnz;
1757:   PetscInt            *lnk,*owners_co,*coi,*coj,i,k,pnz,row;
1758:   PetscInt            am  =A->rmap->n,pn=P->cmap->n;
1759:   MPI_Comm            comm;
1760:   PetscMPIInt         size,rank,tagi,tagj,*len_si,*len_s,*len_ri;
1761:   PetscInt            **buf_rj,**buf_ri,**buf_ri_k;
1762:   PetscInt            len,proc,*dnz,*onz,*owners;
1763:   PetscInt            nzi,*bi,*bj;
1764:   PetscInt            nrows,*buf_s,*buf_si,*buf_si_i,**nextrow,**nextci;
1765:   MPI_Request         *swaits,*rwaits;
1766:   MPI_Status          *sstatus,rstatus;
1767:   Mat_Merge_SeqsToMPI *merge;
1768:   PetscInt            *ai,*aj,*Jptr,anz,*prmap=p->garray,pon,nspacedouble=0,j;
1769:   PetscReal           afill  =1.0,afill_tmp;
1770:   PetscInt            rstart = P->cmap->rstart,rmax,aN=A->cmap->N,Armax;
1771:   Mat_SeqAIJ          *a_loc,*pdt,*pot;
1772:   PetscTable          ta;
1773:   MatType             mtype;

1776:   PetscObjectGetComm((PetscObject)A,&comm);
1777:   /* check if matrix local sizes are compatible */
1778:   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);

1780:   MPI_Comm_size(comm,&size);
1781:   MPI_Comm_rank(comm,&rank);

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

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

1789:   ptap->A_loc = A_loc;
1790:   a_loc       = (Mat_SeqAIJ*)(A_loc)->data;
1791:   ai          = a_loc->i;
1792:   aj          = a_loc->j;

1794:   /* determine symbolic Co=(p->B)^T*A - send to others */
1795:   /*----------------------------------------------------*/
1796:   MatTransposeSymbolic_SeqAIJ(p->A,&PDt);
1797:   pdt  = (Mat_SeqAIJ*)PDt->data;
1798:   pdti = pdt->i; pdtj = pdt->j;

1800:   MatTransposeSymbolic_SeqAIJ(p->B,&POt);
1801:   pot  = (Mat_SeqAIJ*)POt->data;
1802:   poti = pot->i; potj = pot->j;

1804:   /* then, compute symbolic Co = (p->B)^T*A */
1805:   pon    = (p->B)->cmap->n; /* total num of rows to be sent to other processors
1806:                          >= (num of nonzero rows of C_seq) - pn */
1807:   PetscMalloc1(pon+1,&coi);
1808:   coi[0] = 0;

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

1815:   /* create and initialize a linked list */
1816:   PetscTableCreate(A->cmap->n + a->B->cmap->N,aN,&ta);
1817:   MatRowMergeMax_SeqAIJ(a_loc,am,ta);
1818:   PetscTableGetCount(ta,&Armax);

1820:   PetscLLCondensedCreate_Scalable(Armax,&lnk);

1822:   for (i=0; i<pon; i++) {
1823:     pnz = poti[i+1] - poti[i];
1824:     ptJ = potj + poti[i];
1825:     for (j=0; j<pnz; j++) {
1826:       row  = ptJ[j]; /* row of A_loc == col of Pot */
1827:       anz  = ai[row+1] - ai[row];
1828:       Jptr = aj + ai[row];
1829:       /* add non-zero cols of AP into the sorted linked list lnk */
1830:       PetscLLCondensedAddSorted_Scalable(anz,Jptr,lnk);
1831:     }
1832:     nnz = lnk[0];

1834:     /* If free space is not available, double the total space in the list */
1835:     if (current_space->local_remaining<nnz) {
1836:       PetscFreeSpaceGet(PetscIntSumTruncate(nnz,current_space->total_array_size),&current_space);
1837:       nspacedouble++;
1838:     }

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

1843:     current_space->array           += nnz;
1844:     current_space->local_used      += nnz;
1845:     current_space->local_remaining -= nnz;

1847:     coi[i+1] = coi[i] + nnz;
1848:   }

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

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

1857:   /* send j-array (coj) of Co to other processors */
1858:   /*----------------------------------------------*/
1859:   /* determine row ownership */
1860:   PetscNew(&merge);
1861:   PetscLayoutCreate(comm,&merge->rowmap);

1863:   merge->rowmap->n  = pn;
1864:   merge->rowmap->bs = 1;

1866:   PetscLayoutSetUp(merge->rowmap);
1867:   owners = merge->rowmap->range;

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

1873:   len_s        = merge->len_s;
1874:   merge->nsend = 0;

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

1878:   proc = 0;
1879:   for (i=0; i<pon; i++) {
1880:     while (prmap[i] >= owners[proc+1]) proc++;
1881:     len_si[proc]++;  /* num of rows in Co to be sent to [proc] */
1882:     len_s[proc] += coi[i+1] - coi[i];
1883:   }

1885:   len          = 0; /* max length of buf_si[] */
1886:   owners_co[0] = 0;
1887:   for (proc=0; proc<size; proc++) {
1888:     owners_co[proc+1] = owners_co[proc] + len_si[proc];
1889:     if (len_si[proc]) {
1890:       merge->nsend++;
1891:       len_si[proc] = 2*(len_si[proc] + 1);
1892:       len         += len_si[proc];
1893:     }
1894:   }

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

1900:   /* post the Irecv and Isend of coj */
1901:   PetscCommGetNewTag(comm,&tagj);
1902:   PetscPostIrecvInt(comm,tagj,merge->nrecv,merge->id_r,merge->len_r,&buf_rj,&rwaits);
1903:   PetscMalloc1(merge->nsend+1,&swaits);
1904:   for (proc=0, k=0; proc<size; proc++) {
1905:     if (!len_s[proc]) continue;
1906:     i    = owners_co[proc];
1907:     MPI_Isend(coj+coi[i],len_s[proc],MPIU_INT,proc,tagj,comm,swaits+k);
1908:     k++;
1909:   }

1911:   /* receives and sends of coj are complete */
1912:   PetscMalloc1(size,&sstatus);
1913:   for (i=0; i<merge->nrecv; i++) {
1914:     PetscMPIInt icompleted;
1915:     MPI_Waitany(merge->nrecv,rwaits,&icompleted,&rstatus);
1916:   }
1917:   PetscFree(rwaits);
1918:   if (merge->nsend) {MPI_Waitall(merge->nsend,swaits,sstatus);}

1920:   /* add received column indices into table to update Armax */
1921:   /* Armax can be as large as aN if a P[row,:] is dense, see src/ksp/ksp/examples/tutorials/ex56.c! */
1922:   for (k=0; k<merge->nrecv; k++) {/* k-th received message */
1923:     Jptr = buf_rj[k];
1924:     for (j=0; j<merge->len_r[k]; j++) {
1925:       PetscTableAdd(ta,*(Jptr+j)+1,1,INSERT_VALUES);
1926:     }
1927:   }
1928:   PetscTableGetCount(ta,&Armax);
1929:   /* 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); */

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

1973:   /* compute the local portion of C (mpi mat) */
1974:   /*------------------------------------------*/
1975:   /* allocate bi array and free space for accumulating nonzero column info */
1976:   PetscMalloc1(pn+1,&bi);
1977:   bi[0] = 0;

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

1984:   PetscMalloc3(merge->nrecv,&buf_ri_k,merge->nrecv,&nextrow,merge->nrecv,&nextci);
1985:   for (k=0; k<merge->nrecv; k++) {
1986:     buf_ri_k[k] = buf_ri[k]; /* beginning of k-th recved i-structure */
1987:     nrows       = *buf_ri_k[k];
1988:     nextrow[k]  = buf_ri_k[k] + 1;  /* next row number of k-th recved i-structure */
1989:     nextci[k]   = buf_ri_k[k] + (nrows + 1); /* points to the next i-structure of k-th recieved i-structure  */
1990:   }

1992:   PetscLLCondensedCreate_Scalable(Armax,&lnk);
1993:   MatPreallocateInitialize(comm,pn,A->cmap->n,dnz,onz);
1994:   rmax = 0;
1995:   for (i=0; i<pn; i++) {
1996:     /* add pdt[i,:]*AP into lnk */
1997:     pnz = pdti[i+1] - pdti[i];
1998:     ptJ = pdtj + pdti[i];
1999:     for (j=0; j<pnz; j++) {
2000:       row  = ptJ[j];  /* row of AP == col of Pt */
2001:       anz  = ai[row+1] - ai[row];
2002:       Jptr = aj + ai[row];
2003:       /* add non-zero cols of AP into the sorted linked list lnk */
2004:       PetscLLCondensedAddSorted_Scalable(anz,Jptr,lnk);
2005:     }

2007:     /* add received col data into lnk */
2008:     for (k=0; k<merge->nrecv; k++) { /* k-th received message */
2009:       if (i == *nextrow[k]) { /* i-th row */
2010:         nzi  = *(nextci[k]+1) - *nextci[k];
2011:         Jptr = buf_rj[k] + *nextci[k];
2012:         PetscLLCondensedAddSorted_Scalable(nzi,Jptr,lnk);
2013:         nextrow[k]++; nextci[k]++;
2014:       }
2015:     }
2016:     nnz = lnk[0];

2018:     /* if free space is not available, make more free space */
2019:     if (current_space->local_remaining<nnz) {
2020:       PetscFreeSpaceGet(PetscIntSumTruncate(nnz,current_space->total_array_size),&current_space);
2021:       nspacedouble++;
2022:     }
2023:     /* copy data into free space, then initialize lnk */
2024:     PetscLLCondensedClean_Scalable(nnz,current_space->array,lnk);
2025:     MatPreallocateSet(i+owners[rank],nnz,current_space->array,dnz,onz);

2027:     current_space->array           += nnz;
2028:     current_space->local_used      += nnz;
2029:     current_space->local_remaining -= nnz;

2031:     bi[i+1] = bi[i] + nnz;
2032:     if (nnz > rmax) rmax = nnz;
2033:   }
2034:   PetscFree3(buf_ri_k,nextrow,nextci);

2036:   PetscMalloc1(bi[pn]+1,&bj);
2037:   PetscFreeSpaceContiguous(&free_space,bj);
2038:   afill_tmp = (PetscReal)bi[pn]/(pdti[pn] + poti[pon] + ai[am]+1);
2039:   if (afill_tmp > afill) afill = afill_tmp;
2040:   PetscLLCondensedDestroy_Scalable(lnk);
2041:   PetscTableDestroy(&ta);

2043:   MatDestroy(&POt);
2044:   MatDestroy(&PDt);

2046:   /* create symbolic parallel matrix Cmpi - why cannot be assembled in Numeric part   */
2047:   /*----------------------------------------------------------------------------------*/
2048:   MatCreate(comm,&Cmpi);
2049:   MatSetSizes(Cmpi,pn,A->cmap->n,PETSC_DETERMINE,PETSC_DETERMINE);
2050:   MatSetBlockSizes(Cmpi,PetscAbs(P->cmap->bs),PetscAbs(A->cmap->bs));
2051:   MatGetType(A,&mtype);
2052:   MatSetType(Cmpi,mtype);
2053:   MatMPIAIJSetPreallocation(Cmpi,0,dnz,0,onz);
2054:   MatPreallocateFinalize(dnz,onz);
2055:   MatSetBlockSize(Cmpi,1);
2056:   for (i=0; i<pn; i++) {
2057:     row  = i + rstart;
2058:     nnz  = bi[i+1] - bi[i];
2059:     Jptr = bj + bi[i];
2060:     MatSetValues(Cmpi,1,&row,nnz,Jptr,NULL,INSERT_VALUES);
2061:   }
2062:   MatAssemblyBegin(Cmpi,MAT_FINAL_ASSEMBLY);
2063:   MatAssemblyEnd(Cmpi,MAT_FINAL_ASSEMBLY);
2064:   merge->bi        = bi;
2065:   merge->bj        = bj;
2066:   merge->coi       = coi;
2067:   merge->coj       = coj;
2068:   merge->buf_ri    = buf_ri;
2069:   merge->buf_rj    = buf_rj;
2070:   merge->owners_co = owners_co;

2072:   /* attach the supporting struct to Cmpi for reuse */
2073:   c = (Mat_MPIAIJ*)Cmpi->data;

2075:   c->ap       = ptap;
2076:   ptap->api   = NULL;
2077:   ptap->apj   = NULL;
2078:   ptap->merge = merge;
2079:   ptap->apa   = NULL;
2080:   ptap->destroy   = Cmpi->ops->destroy;
2081:   ptap->duplicate = Cmpi->ops->duplicate;

2083:   Cmpi->ops->mattransposemultnumeric = MatTransposeMatMultNumeric_MPIAIJ_MPIAIJ;
2084:   Cmpi->ops->destroy                 = MatDestroy_MPIAIJ_PtAP;
2085:   Cmpi->ops->freeintermediatedatastructures = MatFreeIntermediateDataStructures_MPIAIJ_AP;

2087:   *C = Cmpi;
2088: #if defined(PETSC_USE_INFO)
2089:   if (bi[pn] != 0) {
2090:     PetscInfo3(Cmpi,"Reallocs %D; Fill ratio: given %g needed %g.\n",nspacedouble,(double)fill,(double)afill);
2091:     PetscInfo1(Cmpi,"Use MatTransposeMatMult(A,B,MatReuse,%g,&C) for best performance.\n",(double)afill);
2092:   } else {
2093:     PetscInfo(Cmpi,"Empty matrix product\n");
2094:   }
2095: #endif
2096:   return(0);
2097: }