Actual source code: matscalapack.c

petsc-main 2021-04-20
Report Typos and Errors
  1: #include <petsc/private/petscscalapack.h>

  3: #define DEFAULT_BLOCKSIZE 64

  5: /*
  6:     The variable Petsc_ScaLAPACK_keyval is used to indicate an MPI attribute that
  7:   is attached to a communicator, in this case the attribute is a Mat_ScaLAPACK_Grid
  8: */
  9: static PetscMPIInt Petsc_ScaLAPACK_keyval = MPI_KEYVAL_INVALID;

 11: static PetscErrorCode Petsc_ScaLAPACK_keyval_free(void)
 12: {

 16:   PetscInfo(NULL,"Freeing Petsc_ScaLAPACK_keyval\n");
 17:   MPI_Comm_free_keyval(&Petsc_ScaLAPACK_keyval);
 18:   return(0);
 19: }

 21: static PetscErrorCode MatView_ScaLAPACK(Mat A,PetscViewer viewer)
 22: {
 23:   PetscErrorCode    ierr;
 24:   Mat_ScaLAPACK     *a = (Mat_ScaLAPACK*)A->data;
 25:   PetscBool         iascii;
 26:   PetscViewerFormat format;
 27:   Mat               Adense;

 30:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERASCII,&iascii);
 31:   if (iascii) {
 32:     PetscViewerGetFormat(viewer,&format);
 33:     if (format == PETSC_VIEWER_ASCII_INFO || format == PETSC_VIEWER_ASCII_INFO_DETAIL) {
 34:       PetscViewerASCIIPrintf(viewer,"block sizes: %d,%d\n",(int)a->mb,(int)a->nb);
 35:       PetscViewerASCIIPrintf(viewer,"grid height=%d, grid width=%d\n",(int)a->grid->nprow,(int)a->grid->npcol);
 36:       PetscViewerASCIIPrintf(viewer,"coordinates of process owning first row and column: (%d,%d)\n",(int)a->rsrc,(int)a->csrc);
 37:       PetscViewerASCIIPrintf(viewer,"dimension of largest local matrix: %d x %d\n",(int)a->locr,(int)a->locc);
 38:       return(0);
 39:     } else if (format == PETSC_VIEWER_ASCII_FACTOR_INFO) {
 40:       return(0);
 41:     }
 42:   }
 43:   /* convert to dense format and call MatView() */
 44:   MatConvert(A,MATDENSE,MAT_INITIAL_MATRIX,&Adense);
 45:   MatView(Adense,viewer);
 46:   MatDestroy(&Adense);
 47:   return(0);
 48: }

 50: static PetscErrorCode MatGetInfo_ScaLAPACK(Mat A,MatInfoType flag,MatInfo *info)
 51: {
 53:   Mat_ScaLAPACK  *a = (Mat_ScaLAPACK*)A->data;
 54:   PetscLogDouble isend[2],irecv[2];

 57:   info->block_size = 1.0;

 59:   isend[0] = a->lld*a->locc;     /* locally allocated */
 60:   isend[1] = a->locr*a->locc;    /* used submatrix */
 61:   if (flag == MAT_LOCAL || flag == MAT_GLOBAL_MAX) {
 62:     info->nz_allocated   = isend[0];
 63:     info->nz_used        = isend[1];
 64:   } else if (flag == MAT_GLOBAL_MAX) {
 65:     MPIU_Allreduce(isend,irecv,2,MPIU_PETSCLOGDOUBLE,MPIU_MAX,PetscObjectComm((PetscObject)A));
 66:     info->nz_allocated   = irecv[0];
 67:     info->nz_used        = irecv[1];
 68:   } else if (flag == MAT_GLOBAL_SUM) {
 69:     MPIU_Allreduce(isend,irecv,2,MPIU_PETSCLOGDOUBLE,MPIU_SUM,PetscObjectComm((PetscObject)A));
 70:     info->nz_allocated   = irecv[0];
 71:     info->nz_used        = irecv[1];
 72:   }

 74:   info->nz_unneeded       = 0;
 75:   info->assemblies        = A->num_ass;
 76:   info->mallocs           = 0;
 77:   info->memory            = ((PetscObject)A)->mem;
 78:   info->fill_ratio_given  = 0;
 79:   info->fill_ratio_needed = 0;
 80:   info->factor_mallocs    = 0;
 81:   return(0);
 82: }

 84: PetscErrorCode MatSetOption_ScaLAPACK(Mat A,MatOption op,PetscBool flg)
 85: {
 87:   switch (op) {
 88:     case MAT_NEW_NONZERO_LOCATIONS:
 89:     case MAT_NEW_NONZERO_LOCATION_ERR:
 90:     case MAT_NEW_NONZERO_ALLOCATION_ERR:
 91:     case MAT_SYMMETRIC:
 92:     case MAT_SORTED_FULL:
 93:     case MAT_HERMITIAN:
 94:       break;
 95:     default:
 96:       SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Unsupported option %s",MatOptions[op]);
 97:   }
 98:   return(0);
 99: }

101: static PetscErrorCode MatSetValues_ScaLAPACK(Mat A,PetscInt nr,const PetscInt *rows,PetscInt nc,const PetscInt *cols,const PetscScalar *vals,InsertMode imode)
102: {
103:   Mat_ScaLAPACK  *a = (Mat_ScaLAPACK*)A->data;
105:   PetscInt       i,j;
106:   PetscBLASInt   gridx,gcidx,lridx,lcidx,rsrc,csrc;

109:   for (i=0;i<nr;i++) {
110:     if (rows[i] < 0) continue;
111:     PetscBLASIntCast(rows[i]+1,&gridx);
112:     for (j=0;j<nc;j++) {
113:       if (cols[j] < 0) continue;
114:       PetscBLASIntCast(cols[j]+1,&gcidx);
115:       PetscStackCallBLAS("SCALAPACKinfog2l",SCALAPACKinfog2l_(&gridx,&gcidx,a->desc,&a->grid->nprow,&a->grid->npcol,&a->grid->myrow,&a->grid->mycol,&lridx,&lcidx,&rsrc,&csrc));
116:       if (rsrc==a->grid->myrow && csrc==a->grid->mycol) {
117:         switch (imode) {
118:           case INSERT_VALUES: a->loc[lridx-1+(lcidx-1)*a->lld] = vals[i*nc+j]; break;
119:           case ADD_VALUES: a->loc[lridx-1+(lcidx-1)*a->lld] += vals[i*nc+j]; break;
120:           default: SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"No support for InsertMode %d",(int)imode);
121:         }
122:       } else {
123:         if (A->nooffprocentries) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,"Setting off process entry even though MatSetOption(,MAT_NO_OFF_PROC_ENTRIES,PETSC_TRUE) was set");
124:         A->assembled = PETSC_FALSE;
125:         MatStashValuesRow_Private(&A->stash,rows[i],1,cols+j,vals+i*nc+j,(PetscBool)(imode==ADD_VALUES));
126:       }
127:     }
128:   }
129:   return(0);
130: }

132: static PetscErrorCode MatMultXXXYYY_ScaLAPACK(Mat A,PetscBool transpose,PetscScalar beta,const PetscScalar *x,PetscScalar *y)
133: {
135:   Mat_ScaLAPACK  *a = (Mat_ScaLAPACK*)A->data;
136:   PetscScalar    *x2d,*y2d,alpha=1.0;
137:   const PetscInt *ranges;
138:   PetscBLASInt   xdesc[9],ydesc[9],x2desc[9],y2desc[9],mb,nb,lszx,lszy,zero=0,one=1,xlld,ylld,info;

141:   if (transpose) {

143:     /* create ScaLAPACK descriptors for vectors (1d block distribution) */
144:     PetscLayoutGetRanges(A->rmap,&ranges);
145:     PetscBLASIntCast(ranges[1],&mb);  /* x block size */
146:     xlld = PetscMax(1,A->rmap->n);
147:     PetscStackCallBLAS("SCALAPACKdescinit",SCALAPACKdescinit_(xdesc,&a->M,&one,&mb,&one,&zero,&zero,&a->grid->ictxcol,&xlld,&info));
149:     PetscLayoutGetRanges(A->cmap,&ranges);
150:     PetscBLASIntCast(ranges[1],&nb);  /* y block size */
151:     ylld = 1;
152:     PetscStackCallBLAS("SCALAPACKdescinit",SCALAPACKdescinit_(ydesc,&one,&a->N,&one,&nb,&zero,&zero,&a->grid->ictxrow,&ylld,&info));

155:     /* allocate 2d vectors */
156:     lszx = SCALAPACKnumroc_(&a->M,&a->mb,&a->grid->myrow,&a->rsrc,&a->grid->nprow);
157:     lszy = SCALAPACKnumroc_(&a->N,&a->nb,&a->grid->mycol,&a->csrc,&a->grid->npcol);
158:     PetscMalloc2(lszx,&x2d,lszy,&y2d);
159:     xlld = PetscMax(1,lszx);

161:     /* create ScaLAPACK descriptors for vectors (2d block distribution) */
162:     PetscStackCallBLAS("SCALAPACKdescinit",SCALAPACKdescinit_(x2desc,&a->M,&one,&a->mb,&one,&zero,&zero,&a->grid->ictxt,&xlld,&info));
164:     PetscStackCallBLAS("SCALAPACKdescinit",SCALAPACKdescinit_(y2desc,&one,&a->N,&one,&a->nb,&zero,&zero,&a->grid->ictxt,&ylld,&info));

167:     /* redistribute x as a column of a 2d matrix */
168:     PetscStackCallBLAS("SCALAPACKgemr2d",SCALAPACKgemr2d_(&a->M,&one,(PetscScalar*)x,&one,&one,xdesc,x2d,&one,&one,x2desc,&a->grid->ictxcol));

170:     /* redistribute y as a row of a 2d matrix */
171:     if (beta!=0.0) PetscStackCallBLAS("SCALAPACKgemr2d",SCALAPACKgemr2d_(&one,&a->N,y,&one,&one,ydesc,y2d,&one,&one,y2desc,&a->grid->ictxrow));

173:     /* call PBLAS subroutine */
174:     PetscStackCallBLAS("PBLASgemv",PBLASgemv_("T",&a->M,&a->N,&alpha,a->loc,&one,&one,a->desc,x2d,&one,&one,x2desc,&one,&beta,y2d,&one,&one,y2desc,&one));

176:     /* redistribute y from a row of a 2d matrix */
177:     PetscStackCallBLAS("SCALAPACKgemr2d",SCALAPACKgemr2d_(&one,&a->N,y2d,&one,&one,y2desc,y,&one,&one,ydesc,&a->grid->ictxrow));

179:   } else {   /* non-transpose */

181:     /* create ScaLAPACK descriptors for vectors (1d block distribution) */
182:     PetscLayoutGetRanges(A->cmap,&ranges);
183:     PetscBLASIntCast(ranges[1],&nb);  /* x block size */
184:     xlld = 1;
185:     PetscStackCallBLAS("SCALAPACKdescinit",SCALAPACKdescinit_(xdesc,&one,&a->N,&one,&nb,&zero,&zero,&a->grid->ictxrow,&xlld,&info));
187:     PetscLayoutGetRanges(A->rmap,&ranges);
188:     PetscBLASIntCast(ranges[1],&mb);  /* y block size */
189:     ylld = PetscMax(1,A->rmap->n);
190:     PetscStackCallBLAS("SCALAPACKdescinit",SCALAPACKdescinit_(ydesc,&a->M,&one,&mb,&one,&zero,&zero,&a->grid->ictxcol,&ylld,&info));

193:     /* allocate 2d vectors */
194:     lszy = SCALAPACKnumroc_(&a->M,&a->mb,&a->grid->myrow,&a->rsrc,&a->grid->nprow);
195:     lszx = SCALAPACKnumroc_(&a->N,&a->nb,&a->grid->mycol,&a->csrc,&a->grid->npcol);
196:     PetscMalloc2(lszx,&x2d,lszy,&y2d);
197:     ylld = PetscMax(1,lszy);

199:     /* create ScaLAPACK descriptors for vectors (2d block distribution) */
200:     PetscStackCallBLAS("SCALAPACKdescinit",SCALAPACKdescinit_(x2desc,&one,&a->N,&one,&a->nb,&zero,&zero,&a->grid->ictxt,&xlld,&info));
202:     PetscStackCallBLAS("SCALAPACKdescinit",SCALAPACKdescinit_(y2desc,&a->M,&one,&a->mb,&one,&zero,&zero,&a->grid->ictxt,&ylld,&info));

205:     /* redistribute x as a row of a 2d matrix */
206:     PetscStackCallBLAS("SCALAPACKgemr2d",SCALAPACKgemr2d_(&one,&a->N,(PetscScalar*)x,&one,&one,xdesc,x2d,&one,&one,x2desc,&a->grid->ictxrow));

208:     /* redistribute y as a column of a 2d matrix */
209:     if (beta!=0.0) PetscStackCallBLAS("SCALAPACKgemr2d",SCALAPACKgemr2d_(&a->M,&one,y,&one,&one,ydesc,y2d,&one,&one,y2desc,&a->grid->ictxcol));

211:     /* call PBLAS subroutine */
212:     PetscStackCallBLAS("PBLASgemv",PBLASgemv_("N",&a->M,&a->N,&alpha,a->loc,&one,&one,a->desc,x2d,&one,&one,x2desc,&one,&beta,y2d,&one,&one,y2desc,&one));

214:     /* redistribute y from a column of a 2d matrix */
215:     PetscStackCallBLAS("SCALAPACKgemr2d",SCALAPACKgemr2d_(&a->M,&one,y2d,&one,&one,y2desc,y,&one,&one,ydesc,&a->grid->ictxcol));

217:   }
218:   PetscFree2(x2d,y2d);
219:   return(0);
220: }

222: static PetscErrorCode MatMult_ScaLAPACK(Mat A,Vec x,Vec y)
223: {
224:   PetscErrorCode    ierr;
225:   const PetscScalar *xarray;
226:   PetscScalar       *yarray;

229:   VecGetArrayRead(x,&xarray);
230:   VecGetArray(y,&yarray);
231:   MatMultXXXYYY_ScaLAPACK(A,PETSC_FALSE,0.0,xarray,yarray);
232:   VecRestoreArrayRead(x,&xarray);
233:   VecRestoreArray(y,&yarray);
234:   return(0);
235: }

237: static PetscErrorCode MatMultTranspose_ScaLAPACK(Mat A,Vec x,Vec y)
238: {
239:   PetscErrorCode    ierr;
240:   const PetscScalar *xarray;
241:   PetscScalar       *yarray;

244:   VecGetArrayRead(x,&xarray);
245:   VecGetArray(y,&yarray);
246:   MatMultXXXYYY_ScaLAPACK(A,PETSC_TRUE,0.0,xarray,yarray);
247:   VecRestoreArrayRead(x,&xarray);
248:   VecRestoreArray(y,&yarray);
249:   return(0);
250: }

252: static PetscErrorCode MatMultAdd_ScaLAPACK(Mat A,Vec x,Vec y,Vec z)
253: {
254:   PetscErrorCode    ierr;
255:   const PetscScalar *xarray;
256:   PetscScalar       *zarray;

259:   if (y != z) { VecCopy(y,z); }
260:   VecGetArrayRead(x,&xarray);
261:   VecGetArray(z,&zarray);
262:   MatMultXXXYYY_ScaLAPACK(A,PETSC_FALSE,1.0,xarray,zarray);
263:   VecRestoreArrayRead(x,&xarray);
264:   VecRestoreArray(z,&zarray);
265:   return(0);
266: }

268: static PetscErrorCode MatMultTransposeAdd_ScaLAPACK(Mat A,Vec x,Vec y,Vec z)
269: {
270:   PetscErrorCode    ierr;
271:   const PetscScalar *xarray;
272:   PetscScalar       *zarray;

275:   if (y != z) { VecCopy(y,z); }
276:   VecGetArrayRead(x,&xarray);
277:   VecGetArray(z,&zarray);
278:   MatMultXXXYYY_ScaLAPACK(A,PETSC_TRUE,1.0,xarray,zarray);
279:   VecRestoreArrayRead(x,&xarray);
280:   VecRestoreArray(z,&zarray);
281:   return(0);
282: }

284: PetscErrorCode MatMatMultNumeric_ScaLAPACK(Mat A,Mat B,Mat C)
285: {
286:   Mat_ScaLAPACK *a = (Mat_ScaLAPACK*)A->data;
287:   Mat_ScaLAPACK *b = (Mat_ScaLAPACK*)B->data;
288:   Mat_ScaLAPACK *c = (Mat_ScaLAPACK*)C->data;
289:   PetscScalar   sone=1.0,zero=0.0;
290:   PetscBLASInt  one=1;

293:   PetscStackCallBLAS("PBLASgemm",PBLASgemm_("N","N",&a->M,&b->N,&a->N,&sone,a->loc,&one,&one,a->desc,b->loc,&one,&one,b->desc,&zero,c->loc,&one,&one,c->desc));
294:   C->assembled = PETSC_TRUE;
295:   return(0);
296: }

298: PetscErrorCode MatMatMultSymbolic_ScaLAPACK(Mat A,Mat B,PetscReal fill,Mat C)
299: {

303:   MatSetSizes(C,A->rmap->n,B->cmap->n,PETSC_DECIDE,PETSC_DECIDE);
304:   MatSetType(C,MATSCALAPACK);
305:   MatSetUp(C);
306:   C->ops->matmultnumeric = MatMatMultNumeric_ScaLAPACK;
307:   return(0);
308: }

310: static PetscErrorCode MatMatTransposeMultNumeric_ScaLAPACK(Mat A,Mat B,Mat C)
311: {
312:   Mat_ScaLAPACK *a = (Mat_ScaLAPACK*)A->data;
313:   Mat_ScaLAPACK *b = (Mat_ScaLAPACK*)B->data;
314:   Mat_ScaLAPACK *c = (Mat_ScaLAPACK*)C->data;
315:   PetscScalar   sone=1.0,zero=0.0;
316:   PetscBLASInt  one=1;

319:   PetscStackCallBLAS("PBLASgemm",PBLASgemm_("N","T",&a->M,&b->M,&a->N,&sone,a->loc,&one,&one,a->desc,b->loc,&one,&one,b->desc,&zero,c->loc,&one,&one,c->desc));
320:   C->assembled = PETSC_TRUE;
321:   return(0);
322: }

324: static PetscErrorCode MatMatTransposeMultSymbolic_ScaLAPACK(Mat A,Mat B,PetscReal fill,Mat C)
325: {

329:   MatSetSizes(C,A->rmap->n,B->rmap->n,PETSC_DECIDE,PETSC_DECIDE);
330:   MatSetType(C,MATSCALAPACK);
331:   MatSetUp(C);
332:   return(0);
333: }

335: /* --------------------------------------- */
336: static PetscErrorCode MatProductSetFromOptions_ScaLAPACK_AB(Mat C)
337: {
339:   C->ops->matmultsymbolic = MatMatMultSymbolic_ScaLAPACK;
340:   C->ops->productsymbolic = MatProductSymbolic_AB;
341:   return(0);
342: }

344: static PetscErrorCode MatProductSetFromOptions_ScaLAPACK_ABt(Mat C)
345: {
347:   C->ops->mattransposemultsymbolic = MatMatTransposeMultSymbolic_ScaLAPACK;
348:   C->ops->productsymbolic          = MatProductSymbolic_ABt;
349:   return(0);
350: }

352: PETSC_INTERN PetscErrorCode MatProductSetFromOptions_ScaLAPACK(Mat C)
353: {
355:   Mat_Product    *product = C->product;

358:   switch (product->type) {
359:     case MATPRODUCT_AB:
360:       MatProductSetFromOptions_ScaLAPACK_AB(C);
361:       break;
362:     case MATPRODUCT_ABt:
363:       MatProductSetFromOptions_ScaLAPACK_ABt(C);
364:       break;
365:     default: SETERRQ1(PetscObjectComm((PetscObject)C),PETSC_ERR_SUP,"MatProduct type %s is not supported for ScaLAPACK and ScaLAPACK matrices",MatProductTypes[product->type]);
366:   }
367:   return(0);
368: }
369: /* --------------------------------------- */

371: static PetscErrorCode MatGetDiagonal_ScaLAPACK(Mat A,Vec D)
372: {
373:   PetscErrorCode    ierr;
374:   Mat_ScaLAPACK     *a = (Mat_ScaLAPACK*)A->data;
375:   PetscScalar       *darray,*d2d,v;
376:   const PetscInt    *ranges;
377:   PetscBLASInt      j,ddesc[9],d2desc[9],mb,nb,lszd,zero=0,one=1,dlld,info;

380:   VecGetArray(D,&darray);

382:   if (A->rmap->N<=A->cmap->N) {   /* row version */

384:     /* create ScaLAPACK descriptor for vector (1d block distribution) */
385:     PetscLayoutGetRanges(A->rmap,&ranges);
386:     PetscBLASIntCast(ranges[1],&mb);  /* D block size */
387:     dlld = PetscMax(1,A->rmap->n);
388:     PetscStackCallBLAS("SCALAPACKdescinit",SCALAPACKdescinit_(ddesc,&a->M,&one,&mb,&one,&zero,&zero,&a->grid->ictxcol,&dlld,&info));

391:     /* allocate 2d vector */
392:     lszd = SCALAPACKnumroc_(&a->M,&a->mb,&a->grid->myrow,&a->rsrc,&a->grid->nprow);
393:     PetscCalloc1(lszd,&d2d);
394:     dlld = PetscMax(1,lszd);

396:     /* create ScaLAPACK descriptor for vector (2d block distribution) */
397:     PetscStackCallBLAS("SCALAPACKdescinit",SCALAPACKdescinit_(d2desc,&a->M,&one,&a->mb,&one,&zero,&zero,&a->grid->ictxt,&dlld,&info));

400:     /* collect diagonal */
401:     for (j=1;j<=a->M;j++) {
402:       PetscStackCallBLAS("SCALAPACKelget",SCALAPACKelget_("R"," ",&v,a->loc,&j,&j,a->desc));
403:       PetscStackCallBLAS("SCALAPACKelset",SCALAPACKelset_(d2d,&j,&one,d2desc,&v));
404:     }

406:     /* redistribute d from a column of a 2d matrix */
407:     PetscStackCallBLAS("SCALAPACKgemr2d",SCALAPACKgemr2d_(&a->M,&one,d2d,&one,&one,d2desc,darray,&one,&one,ddesc,&a->grid->ictxcol));
408:     PetscFree(d2d);

410:   } else {   /* column version */

412:     /* create ScaLAPACK descriptor for vector (1d block distribution) */
413:     PetscLayoutGetRanges(A->cmap,&ranges);
414:     PetscBLASIntCast(ranges[1],&nb);  /* D block size */
415:     dlld = 1;
416:     PetscStackCallBLAS("SCALAPACKdescinit",SCALAPACKdescinit_(ddesc,&one,&a->N,&one,&nb,&zero,&zero,&a->grid->ictxrow,&dlld,&info));

419:     /* allocate 2d vector */
420:     lszd = SCALAPACKnumroc_(&a->N,&a->nb,&a->grid->mycol,&a->csrc,&a->grid->npcol);
421:     PetscCalloc1(lszd,&d2d);

423:     /* create ScaLAPACK descriptor for vector (2d block distribution) */
424:     PetscStackCallBLAS("SCALAPACKdescinit",SCALAPACKdescinit_(d2desc,&one,&a->N,&one,&a->nb,&zero,&zero,&a->grid->ictxt,&dlld,&info));

427:     /* collect diagonal */
428:     for (j=1;j<=a->N;j++) {
429:       PetscStackCallBLAS("SCALAPACKelget",SCALAPACKelget_("C"," ",&v,a->loc,&j,&j,a->desc));
430:       PetscStackCallBLAS("SCALAPACKelset",SCALAPACKelset_(d2d,&one,&j,d2desc,&v));
431:     }

433:     /* redistribute d from a row of a 2d matrix */
434:     PetscStackCallBLAS("SCALAPACKgemr2d",SCALAPACKgemr2d_(&one,&a->N,d2d,&one,&one,d2desc,darray,&one,&one,ddesc,&a->grid->ictxrow));
435:     PetscFree(d2d);
436:   }

438:   VecRestoreArray(D,&darray);
439:   VecAssemblyBegin(D);
440:   VecAssemblyEnd(D);
441:   return(0);
442: }

444: static PetscErrorCode MatDiagonalScale_ScaLAPACK(Mat A,Vec L,Vec R)
445: {
446:   PetscErrorCode    ierr;
447:   Mat_ScaLAPACK     *a = (Mat_ScaLAPACK*)A->data;
448:   const PetscScalar *d;
449:   const PetscInt    *ranges;
450:   PetscScalar       *d2d;
451:   PetscBLASInt      i,j,ddesc[9],d2desc[9],mb,nb,lszd,zero=0,one=1,dlld,info;

454:   if (R) {
455:     VecGetArrayRead(R,(const PetscScalar **)&d);
456:     /* create ScaLAPACK descriptor for vector (1d block distribution) */
457:     PetscLayoutGetRanges(A->cmap,&ranges);
458:     PetscBLASIntCast(ranges[1],&nb);  /* D block size */
459:     dlld = 1;
460:     PetscStackCallBLAS("SCALAPACKdescinit",SCALAPACKdescinit_(ddesc,&one,&a->N,&one,&nb,&zero,&zero,&a->grid->ictxrow,&dlld,&info));

463:     /* allocate 2d vector */
464:     lszd = SCALAPACKnumroc_(&a->N,&a->nb,&a->grid->mycol,&a->csrc,&a->grid->npcol);
465:     PetscCalloc1(lszd,&d2d);

467:     /* create ScaLAPACK descriptor for vector (2d block distribution) */
468:     PetscStackCallBLAS("SCALAPACKdescinit",SCALAPACKdescinit_(d2desc,&one,&a->N,&one,&a->nb,&zero,&zero,&a->grid->ictxt,&dlld,&info));

471:     /* redistribute d to a row of a 2d matrix */
472:     PetscStackCallBLAS("SCALAPACKgemr2d",SCALAPACKgemr2d_(&one,&a->N,(PetscScalar*)d,&one,&one,ddesc,d2d,&one,&one,d2desc,&a->grid->ictxrow));

474:     /* broadcast along process columns */
475:     if (!a->grid->myrow) Cdgebs2d(a->grid->ictxt,"C"," ",1,lszd,d2d,dlld);
476:     else Cdgebr2d(a->grid->ictxt,"C"," ",1,lszd,d2d,dlld,0,a->grid->mycol);

478:     /* local scaling */
479:     for (j=0;j<a->locc;j++) for (i=0;i<a->locr;i++) a->loc[i+j*a->lld] *= d2d[j];

481:     PetscFree(d2d);
482:     VecRestoreArrayRead(R,(const PetscScalar **)&d);
483:   }
484:   if (L) {
485:     VecGetArrayRead(L,(const PetscScalar **)&d);
486:     /* create ScaLAPACK descriptor for vector (1d block distribution) */
487:     PetscLayoutGetRanges(A->rmap,&ranges);
488:     PetscBLASIntCast(ranges[1],&mb);  /* D block size */
489:     dlld = PetscMax(1,A->rmap->n);
490:     PetscStackCallBLAS("SCALAPACKdescinit",SCALAPACKdescinit_(ddesc,&a->M,&one,&mb,&one,&zero,&zero,&a->grid->ictxcol,&dlld,&info));

493:     /* allocate 2d vector */
494:     lszd = SCALAPACKnumroc_(&a->M,&a->mb,&a->grid->myrow,&a->rsrc,&a->grid->nprow);
495:     PetscCalloc1(lszd,&d2d);
496:     dlld = PetscMax(1,lszd);

498:     /* create ScaLAPACK descriptor for vector (2d block distribution) */
499:     PetscStackCallBLAS("SCALAPACKdescinit",SCALAPACKdescinit_(d2desc,&a->M,&one,&a->mb,&one,&zero,&zero,&a->grid->ictxt,&dlld,&info));

502:     /* redistribute d to a column of a 2d matrix */
503:     PetscStackCallBLAS("SCALAPACKgemr2d",SCALAPACKgemr2d_(&a->M,&one,(PetscScalar*)d,&one,&one,ddesc,d2d,&one,&one,d2desc,&a->grid->ictxcol));

505:     /* broadcast along process rows */
506:     if (!a->grid->mycol) Cdgebs2d(a->grid->ictxt,"R"," ",lszd,1,d2d,dlld);
507:     else Cdgebr2d(a->grid->ictxt,"R"," ",lszd,1,d2d,dlld,a->grid->myrow,0);

509:     /* local scaling */
510:     for (i=0;i<a->locr;i++) for (j=0;j<a->locc;j++) a->loc[i+j*a->lld] *= d2d[i];

512:     PetscFree(d2d);
513:     VecRestoreArrayRead(L,(const PetscScalar **)&d);
514:   }
515:   return(0);
516: }

518: static PetscErrorCode MatMissingDiagonal_ScaLAPACK(Mat A,PetscBool *missing,PetscInt *d)
519: {
521:   *missing = PETSC_FALSE;
522:   return(0);
523: }

525: static PetscErrorCode MatScale_ScaLAPACK(Mat X,PetscScalar a)
526: {
527:   Mat_ScaLAPACK *x = (Mat_ScaLAPACK*)X->data;
528:   PetscBLASInt  n,one=1;

531:   n = x->lld*x->locc;
532:   PetscStackCallBLAS("BLASscal",BLASscal_(&n,&a,x->loc,&one));
533:   return(0);
534: }

536: static PetscErrorCode MatShift_ScaLAPACK(Mat X,PetscScalar alpha)
537: {
538:   Mat_ScaLAPACK *x = (Mat_ScaLAPACK*)X->data;
539:   PetscBLASInt  i,n;
540:   PetscScalar   v;

543:   n = PetscMin(x->M,x->N);
544:   for (i=1;i<=n;i++) {
545:     PetscStackCallBLAS("SCALAPACKelget",SCALAPACKelget_("-"," ",&v,x->loc,&i,&i,x->desc));
546:     v += alpha;
547:     PetscStackCallBLAS("SCALAPACKelset",SCALAPACKelset_(x->loc,&i,&i,x->desc,&v));
548:   }
549:   return(0);
550: }

552: static PetscErrorCode MatAXPY_ScaLAPACK(Mat Y,PetscScalar alpha,Mat X,MatStructure str)
553: {
555:   Mat_ScaLAPACK  *x = (Mat_ScaLAPACK*)X->data;
556:   Mat_ScaLAPACK  *y = (Mat_ScaLAPACK*)Y->data;
557:   PetscBLASInt   one=1;
558:   PetscScalar    beta=1.0;

561:   MatScaLAPACKCheckDistribution(Y,1,X,3);
562:   PetscStackCallBLAS("SCALAPACKmatadd",SCALAPACKmatadd_(&x->M,&x->N,&alpha,x->loc,&one,&one,x->desc,&beta,y->loc,&one,&one,y->desc));
563:   PetscObjectStateIncrease((PetscObject)Y);
564:   return(0);
565: }

567: static PetscErrorCode MatCopy_ScaLAPACK(Mat A,Mat B,MatStructure str)
568: {
570:   Mat_ScaLAPACK  *a = (Mat_ScaLAPACK*)A->data;
571:   Mat_ScaLAPACK  *b = (Mat_ScaLAPACK*)B->data;

574:   PetscArraycpy(b->loc,a->loc,a->lld*a->locc);
575:   PetscObjectStateIncrease((PetscObject)B);
576:   return(0);
577: }

579: static PetscErrorCode MatDuplicate_ScaLAPACK(Mat A,MatDuplicateOption op,Mat *B)
580: {
581:   Mat            Bs;
582:   MPI_Comm       comm;
583:   Mat_ScaLAPACK  *a = (Mat_ScaLAPACK*)A->data,*b;

587:   PetscObjectGetComm((PetscObject)A,&comm);
588:   MatCreate(comm,&Bs);
589:   MatSetSizes(Bs,A->rmap->n,A->cmap->n,PETSC_DECIDE,PETSC_DECIDE);
590:   MatSetType(Bs,MATSCALAPACK);
591:   b = (Mat_ScaLAPACK*)Bs->data;
592:   b->M    = a->M;
593:   b->N    = a->N;
594:   b->mb   = a->mb;
595:   b->nb   = a->nb;
596:   b->rsrc = a->rsrc;
597:   b->csrc = a->csrc;
598:   MatSetUp(Bs);
599:   *B = Bs;
600:   if (op == MAT_COPY_VALUES) {
601:     PetscArraycpy(b->loc,a->loc,a->lld*a->locc);
602:   }
603:   Bs->assembled = PETSC_TRUE;
604:   return(0);
605: }

607: static PetscErrorCode MatTranspose_ScaLAPACK(Mat A,MatReuse reuse,Mat *B)
608: {
610:   Mat_ScaLAPACK  *a = (Mat_ScaLAPACK*)A->data, *b;
611:   Mat            Bs = *B;
612:   PetscBLASInt   one=1;
613:   PetscScalar    sone=1.0,zero=0.0;
614: #if defined(PETSC_USE_COMPLEX)
615:   PetscInt       i,j;
616: #endif

619:   if (reuse == MAT_INITIAL_MATRIX) {
620:     MatCreateScaLAPACK(PetscObjectComm((PetscObject)A),a->nb,a->mb,a->N,a->M,a->csrc,a->rsrc,&Bs);
621:     *B = Bs;
622:   } else SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Only MAT_INITIAL_MATRIX supported");
623:   b = (Mat_ScaLAPACK*)Bs->data;
624:   PetscStackCallBLAS("PBLAStran",PBLAStran_(&a->N,&a->M,&sone,a->loc,&one,&one,a->desc,&zero,b->loc,&one,&one,b->desc));
625: #if defined(PETSC_USE_COMPLEX)
626:   /* undo conjugation */
627:   for (i=0;i<b->locr;i++) for (j=0;j<b->locc;j++) b->loc[i+j*b->lld] = PetscConj(b->loc[i+j*b->lld]);
628: #endif
629:   Bs->assembled = PETSC_TRUE;
630:   return(0);
631: }

633: static PetscErrorCode MatConjugate_ScaLAPACK(Mat A)
634: {
635:   Mat_ScaLAPACK *a = (Mat_ScaLAPACK*)A->data;
636:   PetscInt      i,j;

639:   for (i=0;i<a->locr;i++) for (j=0;j<a->locc;j++) a->loc[i+j*a->lld] = PetscConj(a->loc[i+j*a->lld]);
640:   return(0);
641: }

643: static PetscErrorCode MatHermitianTranspose_ScaLAPACK(Mat A,MatReuse reuse,Mat *B)
644: {
646:   Mat_ScaLAPACK  *a = (Mat_ScaLAPACK*)A->data, *b;
647:   Mat            Bs = *B;
648:   PetscBLASInt   one=1;
649:   PetscScalar    sone=1.0,zero=0.0;

652:   if (reuse == MAT_INITIAL_MATRIX) {
653:     MatCreateScaLAPACK(PetscObjectComm((PetscObject)A),a->nb,a->mb,a->N,a->M,a->csrc,a->rsrc,&Bs);
654:     *B = Bs;
655:   } else SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Only MAT_INITIAL_MATRIX supported");
656:   b = (Mat_ScaLAPACK*)Bs->data;
657:   PetscStackCallBLAS("PBLAStran",PBLAStran_(&a->N,&a->M,&sone,a->loc,&one,&one,a->desc,&zero,b->loc,&one,&one,b->desc));
658:   Bs->assembled = PETSC_TRUE;
659:   return(0);
660: }

662: static PetscErrorCode MatSolve_ScaLAPACK(Mat A,Vec B,Vec X)
663: {
665:   Mat_ScaLAPACK  *a = (Mat_ScaLAPACK*)A->data;
666:   PetscScalar    *x,*x2d;
667:   const PetscInt *ranges;
668:   PetscBLASInt   xdesc[9],x2desc[9],mb,lszx,zero=0,one=1,xlld,nrhs=1,info;

671:   VecCopy(B,X);
672:   VecGetArray(X,&x);

674:   /* create ScaLAPACK descriptor for a vector (1d block distribution) */
675:   PetscLayoutGetRanges(A->rmap,&ranges);
676:   PetscBLASIntCast(ranges[1],&mb);  /* x block size */
677:   xlld = PetscMax(1,A->rmap->n);
678:   PetscStackCallBLAS("SCALAPACKdescinit",SCALAPACKdescinit_(xdesc,&a->M,&one,&mb,&one,&zero,&zero,&a->grid->ictxcol,&xlld,&info));

681:   /* allocate 2d vector */
682:   lszx = SCALAPACKnumroc_(&a->M,&a->mb,&a->grid->myrow,&a->rsrc,&a->grid->nprow);
683:   PetscMalloc1(lszx,&x2d);
684:   xlld = PetscMax(1,lszx);

686:   /* create ScaLAPACK descriptor for a vector (2d block distribution) */
687:   PetscStackCallBLAS("SCALAPACKdescinit",SCALAPACKdescinit_(x2desc,&a->M,&one,&a->mb,&one,&zero,&zero,&a->grid->ictxt,&xlld,&info));

690:   /* redistribute x as a column of a 2d matrix */
691:   PetscStackCallBLAS("SCALAPACKgemr2d",SCALAPACKgemr2d_(&a->M,&one,x,&one,&one,xdesc,x2d,&one,&one,x2desc,&a->grid->ictxcol));

693:   /* call ScaLAPACK subroutine */
694:   switch (A->factortype) {
695:     case MAT_FACTOR_LU:
696:       PetscStackCallBLAS("SCALAPACKgetrs",SCALAPACKgetrs_("N",&a->M,&nrhs,a->loc,&one,&one,a->desc,a->pivots,x2d,&one,&one,x2desc,&info));
698:       break;
699:     case MAT_FACTOR_CHOLESKY:
700:       PetscStackCallBLAS("SCALAPACKpotrs",SCALAPACKpotrs_("L",&a->M,&nrhs,a->loc,&one,&one,a->desc,x2d,&one,&one,x2desc,&info));
702:       break;
703:     default:
704:       SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"Unfactored Matrix or Unsupported MatFactorType");
705:   }

707:   /* redistribute x from a column of a 2d matrix */
708:   PetscStackCallBLAS("SCALAPACKgemr2d",SCALAPACKgemr2d_(&a->M,&one,x2d,&one,&one,x2desc,x,&one,&one,xdesc,&a->grid->ictxcol));

710:   PetscFree(x2d);
711:   VecRestoreArray(X,&x);
712:   return(0);
713: }

715: static PetscErrorCode MatSolveAdd_ScaLAPACK(Mat A,Vec B,Vec Y,Vec X)
716: {

720:   MatSolve_ScaLAPACK(A,B,X);
721:   VecAXPY(X,1,Y);
722:   return(0);
723: }

725: static PetscErrorCode MatMatSolve_ScaLAPACK(Mat A,Mat B,Mat X)
726: {
728:   Mat_ScaLAPACK *a = (Mat_ScaLAPACK*)A->data,*b,*x;
729:   PetscBool      flg1,flg2;
730:   PetscBLASInt   one=1,info;

733:   PetscObjectTypeCompare((PetscObject)B,MATSCALAPACK,&flg1);
734:   PetscObjectTypeCompare((PetscObject)X,MATSCALAPACK,&flg2);
735:   if (!(flg1 && flg2)) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"Both B and X must be of type MATSCALAPACK");
736:   MatScaLAPACKCheckDistribution(B,1,X,2);
737:   b = (Mat_ScaLAPACK*)B->data;
738:   x = (Mat_ScaLAPACK*)X->data;
739:   PetscArraycpy(x->loc,b->loc,b->lld*b->locc);

741:   switch (A->factortype) {
742:     case MAT_FACTOR_LU:
743:       PetscStackCallBLAS("SCALAPACKgetrs",SCALAPACKgetrs_("N",&a->M,&x->N,a->loc,&one,&one,a->desc,a->pivots,x->loc,&one,&one,x->desc,&info));
745:       break;
746:     case MAT_FACTOR_CHOLESKY:
747:       PetscStackCallBLAS("SCALAPACKpotrs",SCALAPACKpotrs_("L",&a->M,&x->N,a->loc,&one,&one,a->desc,x->loc,&one,&one,x->desc,&info));
749:       break;
750:     default:
751:       SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"Unfactored Matrix or Unsupported MatFactorType");
752:   }
753:   return(0);
754: }

756: static PetscErrorCode MatLUFactor_ScaLAPACK(Mat A,IS row,IS col,const MatFactorInfo *factorinfo)
757: {
759:   Mat_ScaLAPACK  *a = (Mat_ScaLAPACK*)A->data;
760:   PetscBLASInt   one=1,info;

763:   if (!a->pivots) {
764:     PetscMalloc1(a->locr+a->mb,&a->pivots);
765:     PetscLogObjectMemory((PetscObject)A,a->locr*sizeof(PetscBLASInt));
766:   }
767:   PetscStackCallBLAS("SCALAPACKgetrf",SCALAPACKgetrf_(&a->M,&a->N,a->loc,&one,&one,a->desc,a->pivots,&info));
769:   A->factortype = MAT_FACTOR_LU;
770:   A->assembled  = PETSC_TRUE;

772:   PetscFree(A->solvertype);
773:   PetscStrallocpy(MATSOLVERSCALAPACK,&A->solvertype);
774:   return(0);
775: }

777: static PetscErrorCode MatLUFactorNumeric_ScaLAPACK(Mat F,Mat A,const MatFactorInfo *info)
778: {

782:   MatCopy(A,F,SAME_NONZERO_PATTERN);
783:   MatLUFactor_ScaLAPACK(F,0,0,info);
784:   return(0);
785: }

787: static PetscErrorCode MatLUFactorSymbolic_ScaLAPACK(Mat F,Mat A,IS r,IS c,const MatFactorInfo *info)
788: {
790:   /* F is created and allocated by MatGetFactor_scalapack_petsc(), skip this routine. */
791:   return(0);
792: }

794: static PetscErrorCode MatCholeskyFactor_ScaLAPACK(Mat A,IS perm,const MatFactorInfo *factorinfo)
795: {
797:   Mat_ScaLAPACK  *a = (Mat_ScaLAPACK*)A->data;
798:   PetscBLASInt   one=1,info;

801:   PetscStackCallBLAS("SCALAPACKpotrf",SCALAPACKpotrf_("L",&a->M,a->loc,&one,&one,a->desc,&info));
803:   A->factortype = MAT_FACTOR_CHOLESKY;
804:   A->assembled  = PETSC_TRUE;

806:   PetscFree(A->solvertype);
807:   PetscStrallocpy(MATSOLVERSCALAPACK,&A->solvertype);
808:   return(0);
809: }

811: static PetscErrorCode MatCholeskyFactorNumeric_ScaLAPACK(Mat F,Mat A,const MatFactorInfo *info)
812: {

816:   MatCopy(A,F,SAME_NONZERO_PATTERN);
817:   MatCholeskyFactor_ScaLAPACK(F,0,info);
818:   return(0);
819: }

821: static PetscErrorCode MatCholeskyFactorSymbolic_ScaLAPACK(Mat F,Mat A,IS perm,const MatFactorInfo *info)
822: {
824:   /* F is created and allocated by MatGetFactor_scalapack_petsc(), skip this routine. */
825:   return(0);
826: }

828: PetscErrorCode MatFactorGetSolverType_scalapack_scalapack(Mat A,MatSolverType *type)
829: {
831:   *type = MATSOLVERSCALAPACK;
832:   return(0);
833: }

835: static PetscErrorCode MatGetFactor_scalapack_scalapack(Mat A,MatFactorType ftype,Mat *F)
836: {
837:   Mat            B;
838:   Mat_ScaLAPACK  *a = (Mat_ScaLAPACK*)A->data;

842:   /* Create the factorization matrix */
843:   MatCreateScaLAPACK(PetscObjectComm((PetscObject)A),a->mb,a->nb,a->M,a->N,a->rsrc,a->csrc,&B);
844:   B->factortype = ftype;
845:   PetscFree(B->solvertype);
846:   PetscStrallocpy(MATSOLVERSCALAPACK,&B->solvertype);

848:   PetscObjectComposeFunction((PetscObject)B,"MatFactorGetSolverType_C",MatFactorGetSolverType_scalapack_scalapack);
849:   *F = B;
850:   return(0);
851: }

853: PETSC_EXTERN PetscErrorCode MatSolverTypeRegister_ScaLAPACK(void)
854: {

858:   MatSolverTypeRegister(MATSOLVERSCALAPACK,MATSCALAPACK,MAT_FACTOR_LU,MatGetFactor_scalapack_scalapack);
859:   MatSolverTypeRegister(MATSOLVERSCALAPACK,MATSCALAPACK,MAT_FACTOR_CHOLESKY,MatGetFactor_scalapack_scalapack);
860:   return(0);
861: }

863: static PetscErrorCode MatNorm_ScaLAPACK(Mat A,NormType type,PetscReal *nrm)
864: {
866:   Mat_ScaLAPACK  *a = (Mat_ScaLAPACK*)A->data;
867:   PetscBLASInt   one=1,lwork=0;
868:   const char     *ntype;
869:   PetscScalar    *work=NULL,dummy;

872:   switch (type){
873:     case NORM_1:
874:       ntype = "1";
875:       lwork = PetscMax(a->locr,a->locc);
876:       break;
877:     case NORM_FROBENIUS:
878:       ntype = "F";
879:       work  = &dummy;
880:       break;
881:     case NORM_INFINITY:
882:       ntype = "I";
883:       lwork = PetscMax(a->locr,a->locc);
884:       break;
885:     default:
886:       SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Unsupported norm type");
887:   }
888:   if (lwork) { PetscMalloc1(lwork,&work); }
889:   *nrm = SCALAPACKlange_(ntype,&a->M,&a->N,a->loc,&one,&one,a->desc,work);
890:   if (lwork) { PetscFree(work); }
891:   return(0);
892: }

894: static PetscErrorCode MatZeroEntries_ScaLAPACK(Mat A)
895: {
896:   Mat_ScaLAPACK  *a = (Mat_ScaLAPACK*)A->data;

900:   PetscArrayzero(a->loc,a->lld*a->locc);
901:   return(0);
902: }

904: static PetscErrorCode MatGetOwnershipIS_ScaLAPACK(Mat A,IS *rows,IS *cols)
905: {
906:   Mat_ScaLAPACK  *a = (Mat_ScaLAPACK*)A->data;
908:   PetscInt       i,n,nb,isrc,nproc,iproc,*idx;

911:   if (rows) {
912:     n     = a->locr;
913:     nb    = a->mb;
914:     isrc  = a->rsrc;
915:     nproc = a->grid->nprow;
916:     iproc = a->grid->myrow;
917:     PetscMalloc1(n,&idx);
918:     for (i=0;i<n;i++) idx[i] = nproc*nb*(i/nb) + i%nb + ((nproc+iproc-isrc)%nproc)*nb;
919:     ISCreateGeneral(PETSC_COMM_SELF,n,idx,PETSC_OWN_POINTER,rows);
920:   }
921:   if (cols) {
922:     n     = a->locc;
923:     nb    = a->nb;
924:     isrc  = a->csrc;
925:     nproc = a->grid->npcol;
926:     iproc = a->grid->mycol;
927:     PetscMalloc1(n,&idx);
928:     for (i=0;i<n;i++) idx[i] = nproc*nb*(i/nb) + i%nb + ((nproc+iproc-isrc)%nproc)*nb;
929:     ISCreateGeneral(PETSC_COMM_SELF,n,idx,PETSC_OWN_POINTER,cols);
930:   }
931:   return(0);
932: }

934: static PetscErrorCode MatConvert_ScaLAPACK_Dense(Mat A,MatType newtype,MatReuse reuse,Mat *B)
935: {
937:   Mat_ScaLAPACK  *a = (Mat_ScaLAPACK*)A->data;
938:   Mat            Bmpi;
939:   MPI_Comm       comm;
940:   PetscInt       i,M=A->rmap->N,N=A->cmap->N,m,n,rstart,rend,nz;
941:   const PetscInt *ranges,*branges,*cwork;
942:   const PetscScalar *vwork;
943:   PetscBLASInt   bdesc[9],bmb,zero=0,one=1,lld,info;
944:   PetscScalar    *barray;
945:   PetscBool      differ=PETSC_FALSE;
946:   PetscMPIInt    size;

949:   PetscObjectGetComm((PetscObject)A,&comm);
950:   PetscLayoutGetRanges(A->rmap,&ranges);

952:   if (reuse == MAT_REUSE_MATRIX) { /* check if local sizes differ in A and B */
953:     MPI_Comm_size(comm,&size);
954:     PetscLayoutGetRanges((*B)->rmap,&branges);
955:     for (i=0;i<size;i++) if (ranges[i+1]!=branges[i+1]) { differ=PETSC_TRUE; break; }
956:   }

958:   if (reuse == MAT_REUSE_MATRIX && differ) { /* special case, use auxiliary dense matrix */
959:     MatCreate(comm,&Bmpi);
960:     m = PETSC_DECIDE;
961:     PetscSplitOwnershipEqual(comm,&m,&M);
962:     n = PETSC_DECIDE;
963:     PetscSplitOwnershipEqual(comm,&n,&N);
964:     MatSetSizes(Bmpi,m,n,M,N);
965:     MatSetType(Bmpi,MATDENSE);
966:     MatSetUp(Bmpi);

968:     /* create ScaLAPACK descriptor for B (1d block distribution) */
969:     PetscBLASIntCast(ranges[1],&bmb);  /* row block size */
970:     lld = PetscMax(A->rmap->n,1);  /* local leading dimension */
971:     PetscStackCallBLAS("SCALAPACKdescinit",SCALAPACKdescinit_(bdesc,&a->M,&a->N,&bmb,&a->N,&zero,&zero,&a->grid->ictxcol,&lld,&info));

974:     /* redistribute matrix */
975:     MatDenseGetArray(Bmpi,&barray);
976:     PetscStackCallBLAS("SCALAPACKgemr2d",SCALAPACKgemr2d_(&a->M,&a->N,a->loc,&one,&one,a->desc,barray,&one,&one,bdesc,&a->grid->ictxcol));
977:     MatDenseRestoreArray(Bmpi,&barray);
978:     MatAssemblyBegin(Bmpi,MAT_FINAL_ASSEMBLY);
979:     MatAssemblyEnd(Bmpi,MAT_FINAL_ASSEMBLY);

981:     /* transfer rows of auxiliary matrix to the final matrix B */
982:     MatGetOwnershipRange(Bmpi,&rstart,&rend);
983:     for (i=rstart;i<rend;i++) {
984:       MatGetRow(Bmpi,i,&nz,&cwork,&vwork);
985:       MatSetValues(*B,1,&i,nz,cwork,vwork,INSERT_VALUES);
986:       MatRestoreRow(Bmpi,i,&nz,&cwork,&vwork);
987:     }
988:     MatAssemblyBegin(*B,MAT_FINAL_ASSEMBLY);
989:     MatAssemblyEnd(*B,MAT_FINAL_ASSEMBLY);
990:     MatDestroy(&Bmpi);

992:   } else {  /* normal cases */

994:     if (reuse == MAT_REUSE_MATRIX) Bmpi = *B;
995:     else {
996:       MatCreate(comm,&Bmpi);
997:       m = PETSC_DECIDE;
998:       PetscSplitOwnershipEqual(comm,&m,&M);
999:       n = PETSC_DECIDE;
1000:       PetscSplitOwnershipEqual(comm,&n,&N);
1001:       MatSetSizes(Bmpi,m,n,M,N);
1002:       MatSetType(Bmpi,MATDENSE);
1003:       MatSetUp(Bmpi);
1004:     }

1006:     /* create ScaLAPACK descriptor for B (1d block distribution) */
1007:     PetscBLASIntCast(ranges[1],&bmb);  /* row block size */
1008:     lld = PetscMax(A->rmap->n,1);  /* local leading dimension */
1009:     PetscStackCallBLAS("SCALAPACKdescinit",SCALAPACKdescinit_(bdesc,&a->M,&a->N,&bmb,&a->N,&zero,&zero,&a->grid->ictxcol,&lld,&info));

1012:     /* redistribute matrix */
1013:     MatDenseGetArray(Bmpi,&barray);
1014:     PetscStackCallBLAS("SCALAPACKgemr2d",SCALAPACKgemr2d_(&a->M,&a->N,a->loc,&one,&one,a->desc,barray,&one,&one,bdesc,&a->grid->ictxcol));
1015:     MatDenseRestoreArray(Bmpi,&barray);

1017:     MatAssemblyBegin(Bmpi,MAT_FINAL_ASSEMBLY);
1018:     MatAssemblyEnd(Bmpi,MAT_FINAL_ASSEMBLY);
1019:     if (reuse == MAT_INPLACE_MATRIX) {
1020:       MatHeaderReplace(A,&Bmpi);
1021:     } else *B = Bmpi;
1022:   }
1023:   return(0);
1024: }

1026: PETSC_INTERN PetscErrorCode MatConvert_Dense_ScaLAPACK(Mat A,MatType newtype,MatReuse reuse,Mat *B)
1027: {
1029:   Mat_ScaLAPACK  *b;
1030:   Mat            Bmpi;
1031:   MPI_Comm       comm;
1032:   PetscInt       M=A->rmap->N,N=A->cmap->N,m,n;
1033:   const PetscInt *ranges;
1034:   PetscBLASInt   adesc[9],amb,zero=0,one=1,lld,info;
1035:   PetscScalar    *aarray;
1036:   PetscInt       lda;

1039:   PetscObjectGetComm((PetscObject)A,&comm);

1041:   if (reuse == MAT_REUSE_MATRIX) Bmpi = *B;
1042:   else {
1043:     MatCreate(comm,&Bmpi);
1044:     m = PETSC_DECIDE;
1045:     PetscSplitOwnershipEqual(comm,&m,&M);
1046:     n = PETSC_DECIDE;
1047:     PetscSplitOwnershipEqual(comm,&n,&N);
1048:     MatSetSizes(Bmpi,m,n,M,N);
1049:     MatSetType(Bmpi,MATSCALAPACK);
1050:     MatSetUp(Bmpi);
1051:   }
1052:   b = (Mat_ScaLAPACK*)Bmpi->data;

1054:   /* create ScaLAPACK descriptor for A (1d block distribution) */
1055:   PetscLayoutGetRanges(A->rmap,&ranges);
1056:   PetscBLASIntCast(ranges[1],&amb);  /* row block size */
1057:   MatDenseGetLDA(A,&lda);
1058:   lld = PetscMax(lda,1);  /* local leading dimension */
1059:   PetscStackCallBLAS("SCALAPACKdescinit",SCALAPACKdescinit_(adesc,&b->M,&b->N,&amb,&b->N,&zero,&zero,&b->grid->ictxcol,&lld,&info));

1062:   /* redistribute matrix */
1063:   MatDenseGetArray(A,&aarray);
1064:   PetscStackCallBLAS("SCALAPACKgemr2d",SCALAPACKgemr2d_(&b->M,&b->N,aarray,&one,&one,adesc,b->loc,&one,&one,b->desc,&b->grid->ictxcol));
1065:   MatDenseRestoreArray(A,&aarray);

1067:   MatAssemblyBegin(Bmpi,MAT_FINAL_ASSEMBLY);
1068:   MatAssemblyEnd(Bmpi,MAT_FINAL_ASSEMBLY);
1069:   if (reuse == MAT_INPLACE_MATRIX) {
1070:     MatHeaderReplace(A,&Bmpi);
1071:   } else *B = Bmpi;
1072:   return(0);
1073: }

1075: PETSC_INTERN PetscErrorCode MatConvert_AIJ_ScaLAPACK(Mat A,MatType newtype,MatReuse reuse,Mat *newmat)
1076: {
1077:   Mat               mat_scal;
1078:   PetscErrorCode    ierr;
1079:   PetscInt          M=A->rmap->N,N=A->cmap->N,rstart=A->rmap->rstart,rend=A->rmap->rend,m,n,row,ncols;
1080:   const PetscInt    *cols;
1081:   const PetscScalar *vals;

1084:   if (reuse == MAT_REUSE_MATRIX) {
1085:     mat_scal = *newmat;
1086:     MatZeroEntries(mat_scal);
1087:   } else {
1088:     MatCreate(PetscObjectComm((PetscObject)A),&mat_scal);
1089:     m = PETSC_DECIDE;
1090:     PetscSplitOwnershipEqual(PetscObjectComm((PetscObject)A),&m,&M);
1091:     n = PETSC_DECIDE;
1092:     PetscSplitOwnershipEqual(PetscObjectComm((PetscObject)A),&n,&N);
1093:     MatSetSizes(mat_scal,m,n,M,N);
1094:     MatSetType(mat_scal,MATSCALAPACK);
1095:     MatSetUp(mat_scal);
1096:   }
1097:   for (row=rstart;row<rend;row++) {
1098:     MatGetRow(A,row,&ncols,&cols,&vals);
1099:     MatSetValues(mat_scal,1,&row,ncols,cols,vals,INSERT_VALUES);
1100:     MatRestoreRow(A,row,&ncols,&cols,&vals);
1101:   }
1102:   MatAssemblyBegin(mat_scal,MAT_FINAL_ASSEMBLY);
1103:   MatAssemblyEnd(mat_scal,MAT_FINAL_ASSEMBLY);

1105:   if (reuse == MAT_INPLACE_MATRIX) { MatHeaderReplace(A,&mat_scal); }
1106:   else *newmat = mat_scal;
1107:   return(0);
1108: }

1110: PETSC_INTERN PetscErrorCode MatConvert_SBAIJ_ScaLAPACK(Mat A, MatType newtype,MatReuse reuse,Mat *newmat)
1111: {
1112:   Mat               mat_scal;
1113:   PetscErrorCode    ierr;
1114:   PetscInt          M=A->rmap->N,N=A->cmap->N,m,n,row,ncols,j,rstart=A->rmap->rstart,rend=A->rmap->rend;
1115:   const PetscInt    *cols;
1116:   const PetscScalar *vals;
1117:   PetscScalar       v;

1120:   if (reuse == MAT_REUSE_MATRIX) {
1121:     mat_scal = *newmat;
1122:     MatZeroEntries(mat_scal);
1123:   } else {
1124:     MatCreate(PetscObjectComm((PetscObject)A),&mat_scal);
1125:     m = PETSC_DECIDE;
1126:     PetscSplitOwnershipEqual(PetscObjectComm((PetscObject)A),&m,&M);
1127:     n = PETSC_DECIDE;
1128:     PetscSplitOwnershipEqual(PetscObjectComm((PetscObject)A),&n,&N);
1129:     MatSetSizes(mat_scal,m,n,M,N);
1130:     MatSetType(mat_scal,MATSCALAPACK);
1131:     MatSetUp(mat_scal);
1132:   }
1133:   MatGetRowUpperTriangular(A);
1134:   for (row=rstart;row<rend;row++) {
1135:     MatGetRow(A,row,&ncols,&cols,&vals);
1136:     MatSetValues(mat_scal,1,&row,ncols,cols,vals,ADD_VALUES);
1137:     for (j=0;j<ncols;j++) { /* lower triangular part */
1138:       if (cols[j] == row) continue;
1139:       v    = A->hermitian ? PetscConj(vals[j]) : vals[j];
1140:       MatSetValues(mat_scal,1,&cols[j],1,&row,&v,ADD_VALUES);
1141:     }
1142:     MatRestoreRow(A,row,&ncols,&cols,&vals);
1143:   }
1144:   MatRestoreRowUpperTriangular(A);
1145:   MatAssemblyBegin(mat_scal,MAT_FINAL_ASSEMBLY);
1146:   MatAssemblyEnd(mat_scal,MAT_FINAL_ASSEMBLY);

1148:   if (reuse == MAT_INPLACE_MATRIX) { MatHeaderReplace(A,&mat_scal); }
1149:   else *newmat = mat_scal;
1150:   return(0);
1151: }

1153: static PetscErrorCode MatScaLAPACKSetPreallocation(Mat A)
1154: {
1155:   Mat_ScaLAPACK  *a = (Mat_ScaLAPACK*)A->data;
1157:   PetscInt       sz=0;

1160:   PetscLayoutSetUp(A->rmap);
1161:   PetscLayoutSetUp(A->cmap);
1162:   if (!a->lld) a->lld = a->locr;

1164:   PetscFree(a->loc);
1165:   PetscIntMultError(a->lld,a->locc,&sz);
1166:   PetscCalloc1(sz,&a->loc);
1167:   PetscLogObjectMemory((PetscObject)A,sz*sizeof(PetscScalar));

1169:   A->preallocated = PETSC_TRUE;
1170:   return(0);
1171: }

1173: static PetscErrorCode MatDestroy_ScaLAPACK(Mat A)
1174: {
1175:   Mat_ScaLAPACK      *a = (Mat_ScaLAPACK*)A->data;
1176:   PetscErrorCode     ierr;
1177:   Mat_ScaLAPACK_Grid *grid;
1178:   PetscBool          flg;
1179:   MPI_Comm           icomm;

1182:   MatStashDestroy_Private(&A->stash);
1183:   PetscFree(a->loc);
1184:   PetscFree(a->pivots);
1185:   PetscCommDuplicate(PetscObjectComm((PetscObject)A),&icomm,NULL);
1186:   MPI_Comm_get_attr(icomm,Petsc_ScaLAPACK_keyval,(void**)&grid,(int*)&flg);
1187:   if (--grid->grid_refct == 0) {
1188:     Cblacs_gridexit(grid->ictxt);
1189:     Cblacs_gridexit(grid->ictxrow);
1190:     Cblacs_gridexit(grid->ictxcol);
1191:     PetscFree(grid);
1192:     MPI_Comm_delete_attr(icomm,Petsc_ScaLAPACK_keyval);
1193:   }
1194:   PetscCommDestroy(&icomm);
1195:   PetscObjectComposeFunction((PetscObject)A,"MatGetOwnershipIS_C",NULL);
1196:   PetscObjectComposeFunction((PetscObject)A,"MatFactorGetSolverType_C",NULL);
1197:   PetscObjectComposeFunction((PetscObject)A,"MatScaLAPACKSetBlockSizes_C",NULL);
1198:   PetscObjectComposeFunction((PetscObject)A,"MatScaLAPACKGetBlockSizes_C",NULL);
1199:   PetscFree(A->data);
1200:   return(0);
1201: }

1203: PETSC_STATIC_INLINE PetscErrorCode MatScaLAPACKCheckLayout(PetscLayout map)
1204: {
1206:   const PetscInt *ranges;
1207:   PetscMPIInt    size;
1208:   PetscInt       i,n;

1211:   MPI_Comm_size(map->comm,&size);
1212:   if (size>2) {
1213:     PetscLayoutGetRanges(map,&ranges);
1214:     n = ranges[1]-ranges[0];
1215:     for (i=1;i<size-1;i++) if (ranges[i+1]-ranges[i]!=n) break;
1216:     if (i<size-1 && ranges[i+1]-ranges[i]!=0 && ranges[i+2]-ranges[i+1]!=0) SETERRQ(map->comm,PETSC_ERR_SUP,"MATSCALAPACK must have equal local sizes in all processes (except possibly the last one), consider using MatCreateScaLAPACK");
1217:   }
1218:   return(0);
1219: }

1221: PetscErrorCode MatSetUp_ScaLAPACK(Mat A)
1222: {
1223:   Mat_ScaLAPACK  *a = (Mat_ScaLAPACK*)A->data;
1225:   PetscBLASInt   info=0;

1228:   PetscLayoutSetUp(A->rmap);
1229:   PetscLayoutSetUp(A->cmap);

1231:   /* check that the layout is as enforced by MatCreateScaLAPACK */
1232:   MatScaLAPACKCheckLayout(A->rmap);
1233:   MatScaLAPACKCheckLayout(A->cmap);

1235:   /* compute local sizes */
1236:   PetscBLASIntCast(A->rmap->N,&a->M);
1237:   PetscBLASIntCast(A->cmap->N,&a->N);
1238:   a->locr = SCALAPACKnumroc_(&a->M,&a->mb,&a->grid->myrow,&a->rsrc,&a->grid->nprow);
1239:   a->locc = SCALAPACKnumroc_(&a->N,&a->nb,&a->grid->mycol,&a->csrc,&a->grid->npcol);
1240:   a->lld  = PetscMax(1,a->locr);

1242:   /* allocate local array */
1243:   MatScaLAPACKSetPreallocation(A);

1245:   /* set up ScaLAPACK descriptor */
1246:   PetscStackCallBLAS("SCALAPACKdescinit",SCALAPACKdescinit_(a->desc,&a->M,&a->N,&a->mb,&a->nb,&a->rsrc,&a->csrc,&a->grid->ictxt,&a->lld,&info));
1248:   return(0);
1249: }

1251: PetscErrorCode MatAssemblyBegin_ScaLAPACK(Mat A,MatAssemblyType type)
1252: {
1254:   PetscInt       nstash,reallocs;

1257:   if (A->nooffprocentries) return(0);
1258:   MatStashScatterBegin_Private(A,&A->stash,NULL);
1259:   MatStashGetInfo_Private(&A->stash,&nstash,&reallocs);
1260:   PetscInfo2(A,"Stash has %D entries, uses %D mallocs.\n",nstash,reallocs);
1261:   return(0);
1262: }

1264: PetscErrorCode MatAssemblyEnd_ScaLAPACK(Mat A,MatAssemblyType type)
1265: {
1267:   Mat_ScaLAPACK  *a = (Mat_ScaLAPACK*)A->data;
1268:   PetscMPIInt    n;
1269:   PetscInt       i,flg,*row,*col;
1270:   PetscScalar    *val;
1271:   PetscBLASInt   gridx,gcidx,lridx,lcidx,rsrc,csrc;

1274:   if (A->nooffprocentries) return(0);
1275:   while (1) {
1276:     MatStashScatterGetMesg_Private(&A->stash,&n,&row,&col,&val,&flg);
1277:     if (!flg) break;
1278:     for (i=0;i<n;i++) {
1279:       PetscBLASIntCast(row[i]+1,&gridx);
1280:       PetscBLASIntCast(col[i]+1,&gcidx);
1281:       PetscStackCallBLAS("SCALAPACKinfog2l",SCALAPACKinfog2l_(&gridx,&gcidx,a->desc,&a->grid->nprow,&a->grid->npcol,&a->grid->myrow,&a->grid->mycol,&lridx,&lcidx,&rsrc,&csrc));
1282:       if (rsrc!=a->grid->myrow || csrc!=a->grid->mycol) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_LIB,"Something went wrong, received value does not belong to this process");
1283:       switch (A->insertmode) {
1284:         case INSERT_VALUES: a->loc[lridx-1+(lcidx-1)*a->lld] = val[i]; break;
1285:         case ADD_VALUES: a->loc[lridx-1+(lcidx-1)*a->lld] += val[i]; break;
1286:         default: SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"No support for InsertMode %d",(int)A->insertmode);
1287:       }
1288:     }
1289:   }
1290:   MatStashScatterEnd_Private(&A->stash);
1291:   return(0);
1292: }

1294: PetscErrorCode MatLoad_ScaLAPACK(Mat newMat,PetscViewer viewer)
1295: {
1297:   Mat            Adense,As;
1298:   MPI_Comm       comm;

1301:   PetscObjectGetComm((PetscObject)newMat,&comm);
1302:   MatCreate(comm,&Adense);
1303:   MatSetType(Adense,MATDENSE);
1304:   MatLoad(Adense,viewer);
1305:   MatConvert(Adense,MATSCALAPACK,MAT_INITIAL_MATRIX,&As);
1306:   MatDestroy(&Adense);
1307:   MatHeaderReplace(newMat,&As);
1308:   return(0);
1309: }

1311: /* -------------------------------------------------------------------*/
1312: static struct _MatOps MatOps_Values = {
1313:        MatSetValues_ScaLAPACK,
1314:        0,
1315:        0,
1316:        MatMult_ScaLAPACK,
1317: /* 4*/ MatMultAdd_ScaLAPACK,
1318:        MatMultTranspose_ScaLAPACK,
1319:        MatMultTransposeAdd_ScaLAPACK,
1320:        MatSolve_ScaLAPACK,
1321:        MatSolveAdd_ScaLAPACK,
1322:        0,
1323: /*10*/ 0,
1324:        MatLUFactor_ScaLAPACK,
1325:        MatCholeskyFactor_ScaLAPACK,
1326:        0,
1327:        MatTranspose_ScaLAPACK,
1328: /*15*/ MatGetInfo_ScaLAPACK,
1329:        0,
1330:        MatGetDiagonal_ScaLAPACK,
1331:        MatDiagonalScale_ScaLAPACK,
1332:        MatNorm_ScaLAPACK,
1333: /*20*/ MatAssemblyBegin_ScaLAPACK,
1334:        MatAssemblyEnd_ScaLAPACK,
1335:        MatSetOption_ScaLAPACK,
1336:        MatZeroEntries_ScaLAPACK,
1337: /*24*/ 0,
1338:        MatLUFactorSymbolic_ScaLAPACK,
1339:        MatLUFactorNumeric_ScaLAPACK,
1340:        MatCholeskyFactorSymbolic_ScaLAPACK,
1341:        MatCholeskyFactorNumeric_ScaLAPACK,
1342: /*29*/ MatSetUp_ScaLAPACK,
1343:        0,
1344:        0,
1345:        0,
1346:        0,
1347: /*34*/ MatDuplicate_ScaLAPACK,
1348:        0,
1349:        0,
1350:        0,
1351:        0,
1352: /*39*/ MatAXPY_ScaLAPACK,
1353:        0,
1354:        0,
1355:        0,
1356:        MatCopy_ScaLAPACK,
1357: /*44*/ 0,
1358:        MatScale_ScaLAPACK,
1359:        MatShift_ScaLAPACK,
1360:        0,
1361:        0,
1362: /*49*/ 0,
1363:        0,
1364:        0,
1365:        0,
1366:        0,
1367: /*54*/ 0,
1368:        0,
1369:        0,
1370:        0,
1371:        0,
1372: /*59*/ 0,
1373:        MatDestroy_ScaLAPACK,
1374:        MatView_ScaLAPACK,
1375:        0,
1376:        0,
1377: /*64*/ 0,
1378:        0,
1379:        0,
1380:        0,
1381:        0,
1382: /*69*/ 0,
1383:        0,
1384:        MatConvert_ScaLAPACK_Dense,
1385:        0,
1386:        0,
1387: /*74*/ 0,
1388:        0,
1389:        0,
1390:        0,
1391:        0,
1392: /*79*/ 0,
1393:        0,
1394:        0,
1395:        0,
1396:        MatLoad_ScaLAPACK,
1397: /*84*/ 0,
1398:        0,
1399:        0,
1400:        0,
1401:        0,
1402: /*89*/ 0,
1403:        0,
1404:        MatMatMultNumeric_ScaLAPACK,
1405:        0,
1406:        0,
1407: /*94*/ 0,
1408:        0,
1409:        0,
1410:        MatMatTransposeMultNumeric_ScaLAPACK,
1411:        0,
1412: /*99*/ MatProductSetFromOptions_ScaLAPACK,
1413:        0,
1414:        0,
1415:        MatConjugate_ScaLAPACK,
1416:        0,
1417: /*104*/0,
1418:        0,
1419:        0,
1420:        0,
1421:        0,
1422: /*109*/MatMatSolve_ScaLAPACK,
1423:        0,
1424:        0,
1425:        0,
1426:        MatMissingDiagonal_ScaLAPACK,
1427: /*114*/0,
1428:        0,
1429:        0,
1430:        0,
1431:        0,
1432: /*119*/0,
1433:        MatHermitianTranspose_ScaLAPACK,
1434:        0,
1435:        0,
1436:        0,
1437: /*124*/0,
1438:        0,
1439:        0,
1440:        0,
1441:        0,
1442: /*129*/0,
1443:        0,
1444:        0,
1445:        0,
1446:        0,
1447: /*134*/0,
1448:        0,
1449:        0,
1450:        0,
1451:        0,
1452:        0,
1453: /*140*/0,
1454:        0,
1455:        0,
1456:        0,
1457:        0,
1458: /*145*/0,
1459:        0,
1460:        0
1461: };

1463: static PetscErrorCode MatStashScatterBegin_ScaLAPACK(Mat mat,MatStash *stash,PetscInt *owners)
1464: {
1465:   PetscInt           *owner,*startv,*starti,tag1=stash->tag1,tag2=stash->tag2,bs2;
1466:   PetscInt           size=stash->size,nsends;
1467:   PetscErrorCode     ierr;
1468:   PetscInt           count,*sindices,**rindices,i,j,l;
1469:   PetscScalar        **rvalues,*svalues;
1470:   MPI_Comm           comm = stash->comm;
1471:   MPI_Request        *send_waits,*recv_waits,*recv_waits1,*recv_waits2;
1472:   PetscMPIInt        *sizes,*nlengths,nreceives;
1473:   PetscInt           *sp_idx,*sp_idy;
1474:   PetscScalar        *sp_val;
1475:   PetscMatStashSpace space,space_next;
1476:   PetscBLASInt       gridx,gcidx,lridx,lcidx,rsrc,csrc;
1477:   Mat_ScaLAPACK      *a = (Mat_ScaLAPACK*)mat->data;

1480:   {                             /* make sure all processors are either in INSERTMODE or ADDMODE */
1481:     InsertMode addv;
1482:     MPIU_Allreduce((PetscEnum*)&mat->insertmode,(PetscEnum*)&addv,1,MPIU_ENUM,MPI_BOR,PetscObjectComm((PetscObject)mat));
1483:     if (addv == (ADD_VALUES|INSERT_VALUES)) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Some processors inserted others added");
1484:     mat->insertmode = addv; /* in case this processor had no cache */
1485:   }

1487:   bs2 = stash->bs*stash->bs;

1489:   /*  first count number of contributors to each processor */
1490:   PetscCalloc1(size,&nlengths);
1491:   PetscMalloc1(stash->n+1,&owner);

1493:   i     = j    = 0;
1494:   space = stash->space_head;
1495:   while (space) {
1496:     space_next = space->next;
1497:     for (l=0; l<space->local_used; l++) {
1498:       PetscBLASIntCast(space->idx[l]+1,&gridx);
1499:       PetscBLASIntCast(space->idy[l]+1,&gcidx);
1500:       PetscStackCallBLAS("SCALAPACKinfog2l",SCALAPACKinfog2l_(&gridx,&gcidx,a->desc,&a->grid->nprow,&a->grid->npcol,&a->grid->myrow,&a->grid->mycol,&lridx,&lcidx,&rsrc,&csrc));
1501:       j = Cblacs_pnum(a->grid->ictxt,rsrc,csrc);
1502:       nlengths[j]++; owner[i] = j;
1503:       i++;
1504:     }
1505:     space = space_next;
1506:   }

1508:   /* Now check what procs get messages - and compute nsends. */
1509:   PetscCalloc1(size,&sizes);
1510:   for (i=0, nsends=0; i<size; i++) {
1511:     if (nlengths[i]) {
1512:       sizes[i] = 1; nsends++;
1513:     }
1514:   }

1516:   {PetscMPIInt *onodes,*olengths;
1517:    /* Determine the number of messages to expect, their lengths, from from-ids */
1518:    PetscGatherNumberOfMessages(comm,sizes,nlengths,&nreceives);
1519:    PetscGatherMessageLengths(comm,nsends,nreceives,nlengths,&onodes,&olengths);
1520:    /* since clubbing row,col - lengths are multiplied by 2 */
1521:    for (i=0; i<nreceives; i++) olengths[i] *=2;
1522:    PetscPostIrecvInt(comm,tag1,nreceives,onodes,olengths,&rindices,&recv_waits1);
1523:    /* values are size 'bs2' lengths (and remove earlier factor 2 */
1524:    for (i=0; i<nreceives; i++) olengths[i] = olengths[i]*bs2/2;
1525:    PetscPostIrecvScalar(comm,tag2,nreceives,onodes,olengths,&rvalues,&recv_waits2);
1526:    PetscFree(onodes);
1527:    PetscFree(olengths);}

1529:   /* do sends:
1530:       1) starts[i] gives the starting index in svalues for stuff going to
1531:          the ith processor
1532:   */
1533:   PetscMalloc2(bs2*stash->n,&svalues,2*(stash->n+1),&sindices);
1534:   PetscMalloc1(2*nsends,&send_waits);
1535:   PetscMalloc2(size,&startv,size,&starti);
1536:   /* use 2 sends the first with all_a, the next with all_i and all_j */
1537:   startv[0] = 0; starti[0] = 0;
1538:   for (i=1; i<size; i++) {
1539:     startv[i] = startv[i-1] + nlengths[i-1];
1540:     starti[i] = starti[i-1] + 2*nlengths[i-1];
1541:   }

1543:   i     = 0;
1544:   space = stash->space_head;
1545:   while (space) {
1546:     space_next = space->next;
1547:     sp_idx     = space->idx;
1548:     sp_idy     = space->idy;
1549:     sp_val     = space->val;
1550:     for (l=0; l<space->local_used; l++) {
1551:       j = owner[i];
1552:       if (bs2 == 1) {
1553:         svalues[startv[j]] = sp_val[l];
1554:       } else {
1555:         PetscInt    k;
1556:         PetscScalar *buf1,*buf2;
1557:         buf1 = svalues+bs2*startv[j];
1558:         buf2 = space->val + bs2*l;
1559:         for (k=0; k<bs2; k++) buf1[k] = buf2[k];
1560:       }
1561:       sindices[starti[j]]             = sp_idx[l];
1562:       sindices[starti[j]+nlengths[j]] = sp_idy[l];
1563:       startv[j]++;
1564:       starti[j]++;
1565:       i++;
1566:     }
1567:     space = space_next;
1568:   }
1569:   startv[0] = 0;
1570:   for (i=1; i<size; i++) startv[i] = startv[i-1] + nlengths[i-1];

1572:   for (i=0,count=0; i<size; i++) {
1573:     if (sizes[i]) {
1574:       MPI_Isend(sindices+2*startv[i],2*nlengths[i],MPIU_INT,i,tag1,comm,send_waits+count++);
1575:       MPI_Isend(svalues+bs2*startv[i],bs2*nlengths[i],MPIU_SCALAR,i,tag2,comm,send_waits+count++);
1576:     }
1577:   }
1578: #if defined(PETSC_USE_INFO)
1579:   PetscInfo1(NULL,"No of messages: %d \n",nsends);
1580:   for (i=0; i<size; i++) {
1581:     if (sizes[i]) {
1582:       PetscInfo2(NULL,"Mesg_to: %d: size: %d bytes\n",i,nlengths[i]*(bs2*sizeof(PetscScalar)+2*sizeof(PetscInt)));
1583:     }
1584:   }
1585: #endif
1586:   PetscFree(nlengths);
1587:   PetscFree(owner);
1588:   PetscFree2(startv,starti);
1589:   PetscFree(sizes);

1591:   /* recv_waits need to be contiguous for MatStashScatterGetMesg_Private() */
1592:   PetscMalloc1(2*nreceives,&recv_waits);

1594:   for (i=0; i<nreceives; i++) {
1595:     recv_waits[2*i]   = recv_waits1[i];
1596:     recv_waits[2*i+1] = recv_waits2[i];
1597:   }
1598:   stash->recv_waits = recv_waits;

1600:   PetscFree(recv_waits1);
1601:   PetscFree(recv_waits2);

1603:   stash->svalues         = svalues;
1604:   stash->sindices        = sindices;
1605:   stash->rvalues         = rvalues;
1606:   stash->rindices        = rindices;
1607:   stash->send_waits      = send_waits;
1608:   stash->nsends          = nsends;
1609:   stash->nrecvs          = nreceives;
1610:   stash->reproduce_count = 0;
1611:   return(0);
1612: }

1614: static PetscErrorCode MatScaLAPACKSetBlockSizes_ScaLAPACK(Mat A,PetscInt mb,PetscInt nb)
1615: {
1617:   Mat_ScaLAPACK  *a = (Mat_ScaLAPACK*)A->data;

1620:   if (A->preallocated) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ORDER,"Cannot change block sizes after MatSetUp");
1621:   if (mb<1 && mb!=PETSC_DECIDE) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"mb %D must be at least 1",mb);
1622:   if (nb<1 && nb!=PETSC_DECIDE) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"nb %D must be at least 1",nb);
1623:   PetscBLASIntCast((mb==PETSC_DECIDE)?DEFAULT_BLOCKSIZE:mb,&a->mb);
1624:   PetscBLASIntCast((nb==PETSC_DECIDE)?a->mb:nb,&a->nb);
1625:   return(0);
1626: }

1628: /*@
1629:    MatScaLAPACKSetBlockSizes - Sets the block sizes to be used for the distibution of
1630:    the ScaLAPACK matrix

1632:    Logically Collective on A

1634:    Input Parameter:
1635: +  A  - a MATSCALAPACK matrix
1636: .  mb - the row block size
1637: -  nb - the column block size

1639:    Level: intermediate

1641: .seealso: MatCreateScaLAPACK(), MatScaLAPACKGetBlockSizes()
1642: @*/
1643: PetscErrorCode MatScaLAPACKSetBlockSizes(Mat A,PetscInt mb,PetscInt nb)
1644: {

1651:   PetscTryMethod(A,"MatScaLAPACKSetBlockSizes_C",(Mat,PetscInt,PetscInt),(A,mb,nb));
1652:   return(0);
1653: }

1655: static PetscErrorCode MatScaLAPACKGetBlockSizes_ScaLAPACK(Mat A,PetscInt *mb,PetscInt *nb)
1656: {
1657:   Mat_ScaLAPACK *a = (Mat_ScaLAPACK*)A->data;

1660:   if (mb) *mb = a->mb;
1661:   if (nb) *nb = a->nb;
1662:   return(0);
1663: }

1665: /*@
1666:    MatScaLAPACKGetBlockSizes - Gets the block sizes used in the distibution of
1667:    the ScaLAPACK matrix

1669:    Not collective

1671:    Input Parameter:
1672: .  A  - a MATSCALAPACK matrix

1674:    Output Parameters:
1675: +  mb - the row block size
1676: -  nb - the column block size

1678:    Level: intermediate

1680: .seealso: MatCreateScaLAPACK(), MatScaLAPACKSetBlockSizes()
1681: @*/
1682: PetscErrorCode MatScaLAPACKGetBlockSizes(Mat A,PetscInt *mb,PetscInt *nb)
1683: {

1688:   PetscUseMethod(A,"MatScaLAPACKGetBlockSizes_C",(Mat,PetscInt*,PetscInt*),(A,mb,nb));
1689:   return(0);
1690: }

1692: PETSC_INTERN PetscErrorCode MatStashScatterGetMesg_Ref(MatStash*,PetscMPIInt*,PetscInt**,PetscInt**,PetscScalar**,PetscInt*);
1693: PETSC_INTERN PetscErrorCode MatStashScatterEnd_Ref(MatStash*);

1695: /*MC
1696:    MATSCALAPACK = "scalapack" - A matrix type for dense matrices using the ScaLAPACK package

1698:    Use ./configure --download-scalapack to install PETSc to use ScaLAPACK

1700:    Use -pc_type lu -pc_factor_mat_solver_type scalapack to use this direct solver

1702:    Options Database Keys:
1703: +  -mat_type scalapack - sets the matrix type to "scalapack" during a call to MatSetFromOptions()
1704: .  -mat_scalapack_grid_height - sets Grid Height for 2D cyclic ordering of internal matrix
1705: -  -mat_scalapack_block_sizes - size of the blocks to use (one or two integers separated by comma)

1707:    Level: beginner

1709: .seealso: MATDENSE, MATELEMENTAL
1710: M*/

1712: PETSC_EXTERN PetscErrorCode MatCreate_ScaLAPACK(Mat A)
1713: {
1714:   Mat_ScaLAPACK      *a;
1715:   PetscErrorCode     ierr;
1716:   PetscBool          flg,flg1;
1717:   Mat_ScaLAPACK_Grid *grid;
1718:   MPI_Comm           icomm;
1719:   PetscBLASInt       nprow,npcol,myrow,mycol;
1720:   PetscInt           optv1,k=2,array[2]={0,0};
1721:   PetscMPIInt        size;

1724:   PetscMemcpy(A->ops,&MatOps_Values,sizeof(struct _MatOps));
1725:   A->insertmode = NOT_SET_VALUES;

1727:   MatStashCreate_Private(PetscObjectComm((PetscObject)A),1,&A->stash);
1728:   A->stash.ScatterBegin   = MatStashScatterBegin_ScaLAPACK;
1729:   A->stash.ScatterGetMesg = MatStashScatterGetMesg_Ref;
1730:   A->stash.ScatterEnd     = MatStashScatterEnd_Ref;
1731:   A->stash.ScatterDestroy = NULL;

1733:   PetscNewLog(A,&a);
1734:   A->data = (void*)a;

1736:   /* Grid needs to be shared between multiple Mats on the same communicator, implement by attribute caching on the MPI_Comm */
1737:   if (Petsc_ScaLAPACK_keyval == MPI_KEYVAL_INVALID) {
1738:     MPI_Comm_create_keyval(MPI_COMM_NULL_COPY_FN,MPI_COMM_NULL_DELETE_FN,&Petsc_ScaLAPACK_keyval,(void*)0);
1739:     PetscRegisterFinalize(Petsc_ScaLAPACK_keyval_free);
1740:   }
1741:   PetscCommDuplicate(PetscObjectComm((PetscObject)A),&icomm,NULL);
1742:   MPI_Comm_get_attr(icomm,Petsc_ScaLAPACK_keyval,(void**)&grid,(int*)&flg);
1743:   if (!flg) {
1744:     PetscNewLog(A,&grid);

1746:     MPI_Comm_size(icomm,&size);
1747:     grid->nprow = (PetscInt) (PetscSqrtReal((PetscReal)size) + 0.001);

1749:     PetscOptionsBegin(PetscObjectComm((PetscObject)A),((PetscObject)A)->prefix,"ScaLAPACK Grid Options","Mat");
1750:     PetscOptionsInt("-mat_scalapack_grid_height","Grid Height","None",grid->nprow,&optv1,&flg1);
1751:     if (flg1) {
1752:       if (size % optv1) SETERRQ2(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_INCOMP,"Grid Height %D must evenly divide CommSize %D",optv1,size);
1753:       grid->nprow = optv1;
1754:     }
1755:     PetscOptionsEnd();

1757:     if (size % grid->nprow) grid->nprow = 1;  /* cannot use a squarish grid, use a 1d grid */
1758:     grid->npcol = size/grid->nprow;
1759:     PetscBLASIntCast(grid->nprow,&nprow);
1760:     PetscBLASIntCast(grid->npcol,&npcol);
1761:     grid->ictxt = Csys2blacs_handle(icomm);
1762:     Cblacs_gridinit(&grid->ictxt,"R",nprow,npcol);
1763:     Cblacs_gridinfo(grid->ictxt,&nprow,&npcol,&myrow,&mycol);
1764:     grid->grid_refct = 1;
1765:     grid->nprow      = nprow;
1766:     grid->npcol      = npcol;
1767:     grid->myrow      = myrow;
1768:     grid->mycol      = mycol;
1769:     /* auxiliary 1d BLACS contexts for 1xsize and sizex1 grids */
1770:     grid->ictxrow = Csys2blacs_handle(icomm);
1771:     Cblacs_gridinit(&grid->ictxrow,"R",1,size);
1772:     grid->ictxcol = Csys2blacs_handle(icomm);
1773:     Cblacs_gridinit(&grid->ictxcol,"R",size,1);
1774:     MPI_Comm_set_attr(icomm,Petsc_ScaLAPACK_keyval,(void*)grid);

1776:   } else grid->grid_refct++;
1777:   PetscCommDestroy(&icomm);
1778:   a->grid = grid;
1779:   a->mb   = DEFAULT_BLOCKSIZE;
1780:   a->nb   = DEFAULT_BLOCKSIZE;

1782:   PetscOptionsBegin(PetscObjectComm((PetscObject)A),NULL,"ScaLAPACK Options","Mat");
1783:   PetscOptionsIntArray("-mat_scalapack_block_sizes","Size of the blocks to use (one or two comma-separated integers)","MatCreateScaLAPACK",array,&k,&flg);
1784:   if (flg) {
1785:     a->mb = array[0];
1786:     a->nb = (k>1)? array[1]: a->mb;
1787:   }
1788:   PetscOptionsEnd();

1790:   PetscObjectComposeFunction((PetscObject)A,"MatGetOwnershipIS_C",MatGetOwnershipIS_ScaLAPACK);
1791:   PetscObjectComposeFunction((PetscObject)A,"MatScaLAPACKSetBlockSizes_C",MatScaLAPACKSetBlockSizes_ScaLAPACK);
1792:   PetscObjectComposeFunction((PetscObject)A,"MatScaLAPACKGetBlockSizes_C",MatScaLAPACKGetBlockSizes_ScaLAPACK);
1793:   PetscObjectChangeTypeName((PetscObject)A,MATSCALAPACK);
1794:   return(0);
1795: }

1797: /*@C
1798:    MatCreateScaLAPACK - Creates a dense parallel matrix in ScaLAPACK format
1799:    (2D block cyclic distribution).

1801:    Collective

1803:    Input Parameters:
1804: +  comm - MPI communicator
1805: .  mb   - row block size (or PETSC_DECIDE to have it set)
1806: .  nb   - column block size (or PETSC_DECIDE to have it set)
1807: .  M    - number of global rows
1808: .  N    - number of global columns
1809: .  rsrc - coordinate of process that owns the first row of the distributed matrix
1810: -  csrc - coordinate of process that owns the first column of the distributed matrix

1812:    Output Parameter:
1813: .  A - the matrix

1815:    Options Database Keys:
1816: .  -mat_scalapack_block_sizes - size of the blocks to use (one or two integers separated by comma)

1818:    It is recommended that one use the MatCreate(), MatSetType() and/or MatSetFromOptions(),
1819:    MatXXXXSetPreallocation() paradigm instead of this routine directly.
1820:    [MatXXXXSetPreallocation() is, for example, MatSeqAIJSetPreallocation]

1822:    Notes:
1823:    If PETSC_DECIDE is used for the block sizes, then an appropriate value
1824:    is chosen.

1826:    Storage Information:
1827:    Storate is completely managed by ScaLAPACK, so this requires PETSc to be
1828:    configured with ScaLAPACK. In particular, PETSc's local sizes lose
1829:    significance and are thus ignored. The block sizes refer to the values
1830:    used for the distributed matrix, not the same meaning as in BAIJ.

1832:    Level: intermediate

1834: .seealso: MatCreate(), MatCreateDense(), MatSetValues()
1835: @*/
1836: PetscErrorCode MatCreateScaLAPACK(MPI_Comm comm,PetscInt mb,PetscInt nb,PetscInt M,PetscInt N,PetscInt rsrc,PetscInt csrc,Mat *A)
1837: {
1839:   Mat_ScaLAPACK  *a;
1840:   PetscInt       m,n;

1843:   MatCreate(comm,A);
1844:   MatSetType(*A,MATSCALAPACK);
1845:   if (M==PETSC_DECIDE || N==PETSC_DECIDE) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,"Cannot use PETSC_DECIDE for matrix dimensions");
1846:   /* rows and columns are NOT distributed according to PetscSplitOwnership */
1847:   m = PETSC_DECIDE;
1848:   PetscSplitOwnershipEqual(comm,&m,&M);
1849:   n = PETSC_DECIDE;
1850:   PetscSplitOwnershipEqual(comm,&n,&N);
1851:   MatSetSizes(*A,m,n,M,N);
1852:   a = (Mat_ScaLAPACK*)(*A)->data;
1853:   PetscBLASIntCast(M,&a->M);
1854:   PetscBLASIntCast(N,&a->N);
1855:   PetscBLASIntCast((mb==PETSC_DECIDE)?DEFAULT_BLOCKSIZE:mb,&a->mb);
1856:   PetscBLASIntCast((nb==PETSC_DECIDE)?a->mb:nb,&a->nb);
1857:   PetscBLASIntCast(rsrc,&a->rsrc);
1858:   PetscBLASIntCast(csrc,&a->csrc);
1859:   MatSetUp(*A);
1860:   return(0);
1861: }