Actual source code: bddcprivate.c
petsc-3.13.6 2020-09-29
Report Typos and Errors

      1:  #include <../src/mat/impls/aij/seq/aij.h>
      2:  #include <../src/ksp/pc/impls/bddc/bddc.h>
      3:  #include <../src/ksp/pc/impls/bddc/bddcprivate.h>
      4:  #include <../src/mat/impls/dense/seq/dense.h>
      5:  #include <petscdmplex.h>
      6:  #include <petscblaslapack.h>
      7:  #include <petsc/private/sfimpl.h>
      8:  #include <petsc/private/dmpleximpl.h>
      9:  #include <petscdmda.h>

     11: static PetscErrorCode MatMPIAIJRestrict(Mat,MPI_Comm,Mat*);

     13: /* if range is true,  it returns B s.t. span{B} = range(A)
     14:    if range is false, it returns B s.t. range(B) _|_ range(A) */
     15: PetscErrorCode MatDenseOrthogonalRangeOrComplement(Mat A, PetscBool range, PetscInt lw, PetscScalar *work, PetscReal *rwork, Mat *B)
     16: {
     17: #if !defined(PETSC_USE_COMPLEX)
     18:   PetscScalar    *uwork,*data,*U, ds = 0.;
     19:   PetscReal      *sing;
     20:   PetscBLASInt   bM,bN,lwork,lierr,di = 1;
     21:   PetscInt       ulw,i,nr,nc,n;

     25:   MatGetSize(A,&nr,&nc);
     26:   if (!nr || !nc) return(0);

     28:   /* workspace */
     29:   if (!work) {
     30:     ulw  = PetscMax(PetscMax(1,5*PetscMin(nr,nc)),3*PetscMin(nr,nc)+PetscMax(nr,nc));
     31:     PetscMalloc1(ulw,&uwork);
     32:   } else {
     33:     ulw   = lw;
     34:     uwork = work;
     35:   }
     36:   n = PetscMin(nr,nc);
     37:   if (!rwork) {
     38:     PetscMalloc1(n,&sing);
     39:   } else {
     40:     sing = rwork;
     41:   }

     43:   /* SVD */
     44:   PetscMalloc1(nr*nr,&U);
     45:   PetscBLASIntCast(nr,&bM);
     46:   PetscBLASIntCast(nc,&bN);
     47:   PetscBLASIntCast(ulw,&lwork);
     48:   MatDenseGetArray(A,&data);
     49:   PetscFPTrapPush(PETSC_FP_TRAP_OFF);
     50:   PetscStackCallBLAS("LAPACKgesvd",LAPACKgesvd_("A","N",&bM,&bN,data,&bM,sing,U,&bM,&ds,&di,uwork,&lwork,&lierr));
     51:   PetscFPTrapPop();
     52:   if (lierr) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_LIB,"Error in GESVD Lapack routine %d",(int)lierr);
     53:   MatDenseRestoreArray(A,&data);
     54:   for (i=0;i<n;i++) if (sing[i] < PETSC_SMALL) break;
     55:   if (!rwork) {
     56:     PetscFree(sing);
     57:   }
     58:   if (!work) {
     59:     PetscFree(uwork);
     60:   }
     61:   /* create B */
     62:   if (!range) {
     63:     MatCreateSeqDense(PETSC_COMM_SELF,nr,nr-i,NULL,B);
     64:     MatDenseGetArray(*B,&data);
     65:     PetscArraycpy(data,U+nr*i,(nr-i)*nr);
     66:   } else {
     67:     MatCreateSeqDense(PETSC_COMM_SELF,nr,i,NULL,B);
     68:     MatDenseGetArray(*B,&data);
     69:     PetscArraycpy(data,U,i*nr);
     70:   }
     71:   MatDenseRestoreArray(*B,&data);
     72:   PetscFree(U);
     73: #else /* PETSC_USE_COMPLEX */
     75:   SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"Not implemented for complexes");
     76: #endif
     77:   return(0);
     78: }

     80: /* TODO REMOVE */
     81: #if defined(PRINT_GDET)
     82: static int inc = 0;
     83: static int lev = 0;
     84: #endif

     86: PetscErrorCode PCBDDCComputeNedelecChangeEdge(Mat lG, IS edge, IS extrow, IS extcol, IS corners, Mat* Gins, Mat* GKins, PetscScalar cvals[2], PetscScalar *work, PetscReal *rwork)
     87: {
     89:   Mat            GE,GEd;
     90:   PetscInt       rsize,csize,esize;
     91:   PetscScalar    *ptr;

     94:   ISGetSize(edge,&esize);
     95:   if (!esize) return(0);
     96:   ISGetSize(extrow,&rsize);
     97:   ISGetSize(extcol,&csize);

     99:   /* gradients */
    100:   ptr  = work + 5*esize;
    101:   MatCreateSubMatrix(lG,extrow,extcol,MAT_INITIAL_MATRIX,&GE);
    102:   MatCreateSeqDense(PETSC_COMM_SELF,rsize,csize,ptr,Gins);
    103:   MatConvert(GE,MATSEQDENSE,MAT_REUSE_MATRIX,Gins);
    104:   MatDestroy(&GE);

    106:   /* constants */
    107:   ptr += rsize*csize;
    108:   MatCreateSeqDense(PETSC_COMM_SELF,esize,csize,ptr,&GEd);
    109:   MatCreateSubMatrix(lG,edge,extcol,MAT_INITIAL_MATRIX,&GE);
    110:   MatConvert(GE,MATSEQDENSE,MAT_REUSE_MATRIX,&GEd);
    111:   MatDestroy(&GE);
    112:   MatDenseOrthogonalRangeOrComplement(GEd,PETSC_FALSE,5*esize,work,rwork,GKins);
    113:   MatDestroy(&GEd);

    115:   if (corners) {
    116:     Mat               GEc;
    117:     const PetscScalar *vals;
    118:     PetscScalar       v;

    120:     MatCreateSubMatrix(lG,edge,corners,MAT_INITIAL_MATRIX,&GEc);
    121:     MatTransposeMatMult(GEc,*GKins,MAT_INITIAL_MATRIX,1.0,&GEd);
    122:     MatDenseGetArrayRead(GEd,&vals);
    123:     /* v    = PetscAbsScalar(vals[0]) */;
    124:     v    = 1.;
    125:     cvals[0] = vals[0]/v;
    126:     cvals[1] = vals[1]/v;
    127:     MatDenseRestoreArrayRead(GEd,&vals);
    128:     MatScale(*GKins,1./v);
    129: #if defined(PRINT_GDET)
    130:     {
    131:       PetscViewer viewer;
    132:       char filename[256];
    133:       sprintf(filename,"Gdet_l%d_r%d_cc%d.m",lev,PetscGlobalRank,inc++);
    134:       PetscViewerASCIIOpen(PETSC_COMM_SELF,filename,&viewer);
    135:       PetscViewerPushFormat(viewer,PETSC_VIEWER_ASCII_MATLAB);
    136:       PetscObjectSetName((PetscObject)GEc,"GEc");
    137:       MatView(GEc,viewer);
    138:       PetscObjectSetName((PetscObject)(*GKins),"GK");
    139:       MatView(*GKins,viewer);
    140:       PetscObjectSetName((PetscObject)GEd,"Gproj");
    141:       MatView(GEd,viewer);
    142:       PetscViewerDestroy(&viewer);
    143:     }
    144: #endif
    145:     MatDestroy(&GEd);
    146:     MatDestroy(&GEc);
    147:   }

    149:   return(0);
    150: }

    152: PetscErrorCode PCBDDCNedelecSupport(PC pc)
    153: {
    154:   PC_BDDC                *pcbddc = (PC_BDDC*)pc->data;
    155:   Mat_IS                 *matis = (Mat_IS*)pc->pmat->data;
    156:   Mat                    G,T,conn,lG,lGt,lGis,lGall,lGe,lGinit;
    157:   Vec                    tvec;
    158:   PetscSF                sfv;
    159:   ISLocalToGlobalMapping el2g,vl2g,fl2g,al2g;
    160:   MPI_Comm               comm;
    161:   IS                     lned,primals,allprimals,nedfieldlocal;
    162:   IS                     *eedges,*extrows,*extcols,*alleedges;
    163:   PetscBT                btv,bte,btvc,btb,btbd,btvcand,btvi,btee,bter;
    164:   PetscScalar            *vals,*work;
    165:   PetscReal              *rwork;
    166:   const PetscInt         *idxs,*ii,*jj,*iit,*jjt;
    167:   PetscInt               ne,nv,Lv,order,n,field;
    168:   PetscInt               n_neigh,*neigh,*n_shared,**shared;
    169:   PetscInt               i,j,extmem,cum,maxsize,nee;
    170:   PetscInt               *extrow,*extrowcum,*marks,*vmarks,*gidxs;
    171:   PetscInt               *sfvleaves,*sfvroots;
    172:   PetscInt               *corners,*cedges;
    173:   PetscInt               *ecount,**eneighs,*vcount,**vneighs;
    174: #if defined(PETSC_USE_DEBUG)
    175:   PetscInt               *emarks;
    176: #endif
    177:   PetscBool              print,eerr,done,lrc[2],conforming,global,singular,setprimal;
    178:   PetscErrorCode         ierr;

    181:   /* If the discrete gradient is defined for a subset of dofs and global is true,
    182:      it assumes G is given in global ordering for all the dofs.
    183:      Otherwise, the ordering is global for the Nedelec field */
    184:   order      = pcbddc->nedorder;
    185:   conforming = pcbddc->conforming;
    186:   field      = pcbddc->nedfield;
    187:   global     = pcbddc->nedglobal;
    188:   setprimal  = PETSC_FALSE;
    189:   print      = PETSC_FALSE;
    190:   singular   = PETSC_FALSE;

    192:   /* Command line customization */
    193:   PetscOptionsBegin(PetscObjectComm((PetscObject)pc),((PetscObject)pc)->prefix,"BDDC Nedelec options","PC");
    194:   PetscOptionsBool("-pc_bddc_nedelec_field_primal","All edge dofs set as primals: Toselli's algorithm C",NULL,setprimal,&setprimal,NULL);
    195:   PetscOptionsBool("-pc_bddc_nedelec_singular","Infer nullspace from discrete gradient",NULL,singular,&singular,NULL);
    196:   PetscOptionsInt("-pc_bddc_nedelec_order","Test variable order code (to be removed)",NULL,order,&order,NULL);
    197:   /* print debug info TODO: to be removed */
    198:   PetscOptionsBool("-pc_bddc_nedelec_print","Print debug info",NULL,print,&print,NULL);
    199:   PetscOptionsEnd();

    201:   /* Return if there are no edges in the decomposition and the problem is not singular */
    202:   MatGetLocalToGlobalMapping(pc->pmat,&al2g,NULL);
    203:   ISLocalToGlobalMappingGetSize(al2g,&n);
    204:   PetscObjectGetComm((PetscObject)pc,&comm);
    205:   if (!singular) {
    206:     VecGetArrayRead(matis->counter,(const PetscScalar**)&vals);
    207:     lrc[0] = PETSC_FALSE;
    208:     for (i=0;i<n;i++) {
    209:       if (PetscRealPart(vals[i]) > 2.) {
    210:         lrc[0] = PETSC_TRUE;
    211:         break;
    212:       }
    213:     }
    214:     VecRestoreArrayRead(matis->counter,(const PetscScalar**)&vals);
    215:     MPIU_Allreduce(&lrc[0],&lrc[1],1,MPIU_BOOL,MPI_LOR,comm);
    216:     if (!lrc[1]) return(0);
    217:   }

    219:   /* Get Nedelec field */
    220:   if (pcbddc->n_ISForDofsLocal && field >= pcbddc->n_ISForDofsLocal) SETERRQ2(comm,PETSC_ERR_USER,"Invalid field for Nedelec %D: number of fields is %D",field,pcbddc->n_ISForDofsLocal);
    221:   if (pcbddc->n_ISForDofsLocal && field >= 0) {
    222:     PetscObjectReference((PetscObject)pcbddc->ISForDofsLocal[field]);
    223:     nedfieldlocal = pcbddc->ISForDofsLocal[field];
    224:     ISGetLocalSize(nedfieldlocal,&ne);
    225:   } else if (!pcbddc->n_ISForDofsLocal && field != PETSC_DECIDE) {
    226:     ne            = n;
    227:     nedfieldlocal = NULL;
    228:     global        = PETSC_TRUE;
    229:   } else if (field == PETSC_DECIDE) {
    230:     PetscInt rst,ren,*idx;

    232:     PetscArrayzero(matis->sf_leafdata,n);
    233:     PetscArrayzero(matis->sf_rootdata,pc->pmat->rmap->n);
    234:     MatGetOwnershipRange(pcbddc->discretegradient,&rst,&ren);
    235:     for (i=rst;i<ren;i++) {
    236:       PetscInt nc;

    238:       MatGetRow(pcbddc->discretegradient,i,&nc,NULL,NULL);
    239:       if (nc > 1) matis->sf_rootdata[i-rst] = 1;
    240:       MatRestoreRow(pcbddc->discretegradient,i,&nc,NULL,NULL);
    241:     }
    242:     PetscSFBcastBegin(matis->sf,MPIU_INT,matis->sf_rootdata,matis->sf_leafdata);
    243:     PetscSFBcastEnd(matis->sf,MPIU_INT,matis->sf_rootdata,matis->sf_leafdata);
    244:     PetscMalloc1(n,&idx);
    245:     for (i=0,ne=0;i<n;i++) if (matis->sf_leafdata[i]) idx[ne++] = i;
    246:     ISCreateGeneral(comm,ne,idx,PETSC_OWN_POINTER,&nedfieldlocal);
    247:   } else {
    248:     SETERRQ(comm,PETSC_ERR_USER,"When multiple fields are present, the Nedelec field has to be specified");
    249:   }

    251:   /* Sanity checks */
    252:   if (!order && !conforming) SETERRQ(comm,PETSC_ERR_SUP,"Variable order and non-conforming spaces are not supported at the same time");
    253:   if (pcbddc->user_ChangeOfBasisMatrix) SETERRQ(comm,PETSC_ERR_SUP,"Cannot generate Nedelec support with user defined change of basis");
    254:   if (order && ne%order) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_USER,"The number of local edge dofs %D it's not a multiple of the order %D",ne,order);

    256:   /* Just set primal dofs and return */
    257:   if (setprimal) {
    258:     IS       enedfieldlocal;
    259:     PetscInt *eidxs;

    261:     PetscMalloc1(ne,&eidxs);
    262:     VecGetArrayRead(matis->counter,(const PetscScalar**)&vals);
    263:     if (nedfieldlocal) {
    264:       ISGetIndices(nedfieldlocal,&idxs);
    265:       for (i=0,cum=0;i<ne;i++) {
    266:         if (PetscRealPart(vals[idxs[i]]) > 2.) {
    267:           eidxs[cum++] = idxs[i];
    268:         }
    269:       }
    270:       ISRestoreIndices(nedfieldlocal,&idxs);
    271:     } else {
    272:       for (i=0,cum=0;i<ne;i++) {
    273:         if (PetscRealPart(vals[i]) > 2.) {
    274:           eidxs[cum++] = i;
    275:         }
    276:       }
    277:     }
    278:     VecRestoreArrayRead(matis->counter,(const PetscScalar**)&vals);
    279:     ISCreateGeneral(comm,cum,eidxs,PETSC_COPY_VALUES,&enedfieldlocal);
    280:     PCBDDCSetPrimalVerticesLocalIS(pc,enedfieldlocal);
    281:     PetscFree(eidxs);
    282:     ISDestroy(&nedfieldlocal);
    283:     ISDestroy(&enedfieldlocal);
    284:     return(0);
    285:   }

    287:   /* Compute some l2g maps */
    288:   if (nedfieldlocal) {
    289:     IS is;

    291:     /* need to map from the local Nedelec field to local numbering */
    292:     ISLocalToGlobalMappingCreateIS(nedfieldlocal,&fl2g);
    293:     /* need to map from the local Nedelec field to global numbering for the whole dofs*/
    294:     ISLocalToGlobalMappingApplyIS(al2g,nedfieldlocal,&is);
    295:     ISLocalToGlobalMappingCreateIS(is,&al2g);
    296:     /* need to map from the local Nedelec field to global numbering (for Nedelec only) */
    297:     if (global) {
    298:       PetscObjectReference((PetscObject)al2g);
    299:       el2g = al2g;
    300:     } else {
    301:       IS gis;

    303:       ISRenumber(is,NULL,NULL,&gis);
    304:       ISLocalToGlobalMappingCreateIS(gis,&el2g);
    305:       ISDestroy(&gis);
    306:     }
    307:     ISDestroy(&is);
    308:   } else {
    309:     /* restore default */
    310:     pcbddc->nedfield = -1;
    311:     /* one ref for the destruction of al2g, one for el2g */
    312:     PetscObjectReference((PetscObject)al2g);
    313:     PetscObjectReference((PetscObject)al2g);
    314:     el2g = al2g;
    315:     fl2g = NULL;
    316:   }

    318:   /* Start communication to drop connections for interior edges (for cc analysis only) */
    319:   PetscArrayzero(matis->sf_leafdata,n);
    320:   PetscArrayzero(matis->sf_rootdata,pc->pmat->rmap->n);
    321:   if (nedfieldlocal) {
    322:     ISGetIndices(nedfieldlocal,&idxs);
    323:     for (i=0;i<ne;i++) matis->sf_leafdata[idxs[i]] = 1;
    324:     ISRestoreIndices(nedfieldlocal,&idxs);
    325:   } else {
    326:     for (i=0;i<ne;i++) matis->sf_leafdata[i] = 1;
    327:   }
    328:   PetscSFReduceBegin(matis->sf,MPIU_INT,matis->sf_leafdata,matis->sf_rootdata,MPI_SUM);
    329:   PetscSFReduceEnd(matis->sf,MPIU_INT,matis->sf_leafdata,matis->sf_rootdata,MPI_SUM);

    331:   if (!singular) { /* drop connections with interior edges to avoid unneeded communications and memory movements */
    332:     MatDuplicate(pcbddc->discretegradient,MAT_COPY_VALUES,&G);
    333:     MatSetOption(G,MAT_KEEP_NONZERO_PATTERN,PETSC_FALSE);
    334:     if (global) {
    335:       PetscInt rst;

    337:       MatGetOwnershipRange(G,&rst,NULL);
    338:       for (i=0,cum=0;i<pc->pmat->rmap->n;i++) {
    339:         if (matis->sf_rootdata[i] < 2) {
    340:           matis->sf_rootdata[cum++] = i + rst;
    341:         }
    342:       }
    343:       MatSetOption(G,MAT_NO_OFF_PROC_ZERO_ROWS,PETSC_TRUE);
    344:       MatZeroRows(G,cum,matis->sf_rootdata,0.,NULL,NULL);
    345:     } else {
    346:       PetscInt *tbz;

    348:       PetscMalloc1(ne,&tbz);
    349:       PetscSFBcastBegin(matis->sf,MPIU_INT,matis->sf_rootdata,matis->sf_leafdata);
    350:       PetscSFBcastEnd(matis->sf,MPIU_INT,matis->sf_rootdata,matis->sf_leafdata);
    351:       ISGetIndices(nedfieldlocal,&idxs);
    352:       for (i=0,cum=0;i<ne;i++)
    353:         if (matis->sf_leafdata[idxs[i]] == 1)
    354:           tbz[cum++] = i;
    355:       ISRestoreIndices(nedfieldlocal,&idxs);
    356:       ISLocalToGlobalMappingApply(el2g,cum,tbz,tbz);
    357:       MatZeroRows(G,cum,tbz,0.,NULL,NULL);
    358:       PetscFree(tbz);
    359:     }
    360:   } else { /* we need the entire G to infer the nullspace */
    361:     PetscObjectReference((PetscObject)pcbddc->discretegradient);
    362:     G    = pcbddc->discretegradient;
    363:   }

    365:   /* Extract subdomain relevant rows of G */
    366:   ISLocalToGlobalMappingGetIndices(el2g,&idxs);
    367:   ISCreateGeneral(comm,ne,idxs,PETSC_USE_POINTER,&lned);
    368:   MatCreateSubMatrix(G,lned,NULL,MAT_INITIAL_MATRIX,&lGall);
    369:   ISLocalToGlobalMappingRestoreIndices(el2g,&idxs);
    370:   ISDestroy(&lned);
    371:   MatConvert(lGall,MATIS,MAT_INITIAL_MATRIX,&lGis);
    372:   MatDestroy(&lGall);
    373:   MatISGetLocalMat(lGis,&lG);

    375:   /* SF for nodal dofs communications */
    376:   MatGetLocalSize(G,NULL,&Lv);
    377:   MatGetLocalToGlobalMapping(lGis,NULL,&vl2g);
    378:   PetscObjectReference((PetscObject)vl2g);
    379:   ISLocalToGlobalMappingGetSize(vl2g,&nv);
    380:   PetscSFCreate(comm,&sfv);
    381:   ISLocalToGlobalMappingGetIndices(vl2g,&idxs);
    382:   PetscSFSetGraphLayout(sfv,lGis->cmap,nv,NULL,PETSC_OWN_POINTER,idxs);
    383:   ISLocalToGlobalMappingRestoreIndices(vl2g,&idxs);
    384:   i    = singular ? 2 : 1;
    385:   PetscMalloc2(i*nv,&sfvleaves,i*Lv,&sfvroots);

    387:   /* Destroy temporary G created in MATIS format and modified G */
    388:   PetscObjectReference((PetscObject)lG);
    389:   MatDestroy(&lGis);
    390:   MatDestroy(&G);

    392:   if (print) {
    393:     PetscObjectSetName((PetscObject)lG,"initial_lG");
    394:     MatView(lG,NULL);
    395:   }

    397:   /* Save lG for values insertion in change of basis */
    398:   MatDuplicate(lG,MAT_COPY_VALUES,&lGinit);

    400:   /* Analyze the edge-nodes connections (duplicate lG) */
    401:   MatDuplicate(lG,MAT_COPY_VALUES,&lGe);
    402:   MatSetOption(lGe,MAT_KEEP_NONZERO_PATTERN,PETSC_FALSE);
    403:   PetscBTCreate(nv,&btv);
    404:   PetscBTCreate(ne,&bte);
    405:   PetscBTCreate(ne,&btb);
    406:   PetscBTCreate(ne,&btbd);
    407:   PetscBTCreate(nv,&btvcand);
    408:   /* need to import the boundary specification to ensure the
    409:      proper detection of coarse edges' endpoints */
    410:   if (pcbddc->DirichletBoundariesLocal) {
    411:     IS is;

    413:     if (fl2g) {
    414:       ISGlobalToLocalMappingApplyIS(fl2g,IS_GTOLM_MASK,pcbddc->DirichletBoundariesLocal,&is);
    415:     } else {
    416:       is = pcbddc->DirichletBoundariesLocal;
    417:     }
    418:     ISGetLocalSize(is,&cum);
    419:     ISGetIndices(is,&idxs);
    420:     for (i=0;i<cum;i++) {
    421:       if (idxs[i] >= 0) {
    422:         PetscBTSet(btb,idxs[i]);
    423:         PetscBTSet(btbd,idxs[i]);
    424:       }
    425:     }
    426:     ISRestoreIndices(is,&idxs);
    427:     if (fl2g) {
    428:       ISDestroy(&is);
    429:     }
    430:   }
    431:   if (pcbddc->NeumannBoundariesLocal) {
    432:     IS is;

    434:     if (fl2g) {
    435:       ISGlobalToLocalMappingApplyIS(fl2g,IS_GTOLM_MASK,pcbddc->NeumannBoundariesLocal,&is);
    436:     } else {
    437:       is = pcbddc->NeumannBoundariesLocal;
    438:     }
    439:     ISGetLocalSize(is,&cum);
    440:     ISGetIndices(is,&idxs);
    441:     for (i=0;i<cum;i++) {
    442:       if (idxs[i] >= 0) {
    443:         PetscBTSet(btb,idxs[i]);
    444:       }
    445:     }
    446:     ISRestoreIndices(is,&idxs);
    447:     if (fl2g) {
    448:       ISDestroy(&is);
    449:     }
    450:   }

    452:   /* Count neighs per dof */
    453:   ISLocalToGlobalMappingGetNodeInfo(el2g,NULL,&ecount,&eneighs);
    454:   ISLocalToGlobalMappingGetNodeInfo(vl2g,NULL,&vcount,&vneighs);

    456:   /* need to remove coarse faces' dofs and coarse edges' dirichlet dofs
    457:      for proper detection of coarse edges' endpoints */
    458:   PetscBTCreate(ne,&btee);
    459:   for (i=0;i<ne;i++) {
    460:     if ((ecount[i] > 2 && !PetscBTLookup(btbd,i)) || (ecount[i] == 2 && PetscBTLookup(btb,i))) {
    461:       PetscBTSet(btee,i);
    462:     }
    463:   }
    464:   PetscMalloc1(ne,&marks);
    465:   if (!conforming) {
    466:     MatTranspose(lGe,MAT_INITIAL_MATRIX,&lGt);
    467:     MatGetRowIJ(lGt,0,PETSC_FALSE,PETSC_FALSE,&i,&iit,&jjt,&done);
    468:   }
    469:   MatGetRowIJ(lGe,0,PETSC_FALSE,PETSC_FALSE,&i,&ii,&jj,&done);
    470:   MatSeqAIJGetArray(lGe,&vals);
    471:   cum  = 0;
    472:   for (i=0;i<ne;i++) {
    473:     /* eliminate rows corresponding to edge dofs belonging to coarse faces */
    474:     if (!PetscBTLookup(btee,i)) {
    475:       marks[cum++] = i;
    476:       continue;
    477:     }
    478:     /* set badly connected edge dofs as primal */
    479:     if (!conforming) {
    480:       if (ii[i+1]-ii[i] != order + 1) { /* every row of G on the coarse edge should list order+1 nodal dofs */
    481:         marks[cum++] = i;
    482:         PetscBTSet(bte,i);
    483:         for (j=ii[i];j<ii[i+1];j++) {
    484:           PetscBTSet(btv,jj[j]);
    485:         }
    486:       } else {
    487:         /* every edge dofs should be connected trough a certain number of nodal dofs
    488:            to other edge dofs belonging to coarse edges
    489:            - at most 2 endpoints
    490:            - order-1 interior nodal dofs
    491:            - no undefined nodal dofs (nconn < order)
    492:         */
    493:         PetscInt ends = 0,ints = 0, undef = 0;
    494:         for (j=ii[i];j<ii[i+1];j++) {
    495:           PetscInt v = jj[j],k;
    496:           PetscInt nconn = iit[v+1]-iit[v];
    497:           for (k=iit[v];k<iit[v+1];k++) if (!PetscBTLookup(btee,jjt[k])) nconn--;
    498:           if (nconn > order) ends++;
    499:           else if (nconn == order) ints++;
    500:           else undef++;
    501:         }
    502:         if (undef || ends > 2 || ints != order -1) {
    503:           marks[cum++] = i;
    504:           PetscBTSet(bte,i);
    505:           for (j=ii[i];j<ii[i+1];j++) {
    506:             PetscBTSet(btv,jj[j]);
    507:           }
    508:         }
    509:       }
    510:     }
    511:     /* We assume the order on the element edge is ii[i+1]-ii[i]-1 */
    512:     if (!order && ii[i+1] != ii[i]) {
    513:       PetscScalar val = 1./(ii[i+1]-ii[i]-1);
    514:       for (j=ii[i];j<ii[i+1];j++) vals[j] = val;
    515:     }
    516:   }
    517:   PetscBTDestroy(&btee);
    518:   MatSeqAIJRestoreArray(lGe,&vals);
    519:   MatRestoreRowIJ(lGe,0,PETSC_FALSE,PETSC_FALSE,&i,&ii,&jj,&done);
    520:   if (!conforming) {
    521:     MatRestoreRowIJ(lGt,0,PETSC_FALSE,PETSC_FALSE,&i,&iit,&jjt,&done);
    522:     MatDestroy(&lGt);
    523:   }
    524:   MatZeroRows(lGe,cum,marks,0.,NULL,NULL);

    526:   /* identify splitpoints and corner candidates */
    527:   MatTranspose(lGe,MAT_INITIAL_MATRIX,&lGt);
    528:   if (print) {
    529:     PetscObjectSetName((PetscObject)lGe,"edgerestr_lG");
    530:     MatView(lGe,NULL);
    531:     PetscObjectSetName((PetscObject)lGt,"edgerestr_lGt");
    532:     MatView(lGt,NULL);
    533:   }
    534:   MatGetRowIJ(lGt,0,PETSC_FALSE,PETSC_FALSE,&i,&ii,&jj,&done);
    535:   MatSeqAIJGetArray(lGt,&vals);
    536:   for (i=0;i<nv;i++) {
    537:     PetscInt  ord = order, test = ii[i+1]-ii[i], vc = vcount[i];
    538:     PetscBool sneighs = PETSC_TRUE, bdir = PETSC_FALSE;
    539:     if (!order) { /* variable order */
    540:       PetscReal vorder = 0.;

    542:       for (j=ii[i];j<ii[i+1];j++) vorder += PetscRealPart(vals[j]);
    543:       test = PetscFloorReal(vorder+10.*PETSC_SQRT_MACHINE_EPSILON);
    544:       if (vorder-test > PETSC_SQRT_MACHINE_EPSILON) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_PLIB,"Unexpected value for vorder: %g (%D)",vorder,test);
    545:       ord  = 1;
    546:     }
    547: #if defined(PETSC_USE_DEBUG)
    548:     if (test%ord) SETERRQ3(PETSC_COMM_SELF,PETSC_ERR_PLIB,"Unexpected number of edge dofs %D connected with nodal dof %D with order %D",test,i,ord);
    549: #endif
    550:     for (j=ii[i];j<ii[i+1] && sneighs;j++) {
    551:       if (PetscBTLookup(btbd,jj[j])) {
    552:         bdir = PETSC_TRUE;
    553:         break;
    554:       }
    555:       if (vc != ecount[jj[j]]) {
    556:         sneighs = PETSC_FALSE;
    557:       } else {
    558:         PetscInt k,*vn = vneighs[i], *en = eneighs[jj[j]];
    559:         for (k=0;k<vc;k++) {
    560:           if (vn[k] != en[k]) {
    561:             sneighs = PETSC_FALSE;
    562:             break;
    563:           }
    564:         }
    565:       }
    566:     }
    567:     if (!sneighs || test >= 3*ord || bdir) { /* splitpoints */
    568:       if (print) PetscPrintf(PETSC_COMM_SELF,"SPLITPOINT %D (%D %D %D)\n",i,!sneighs,test >= 3*ord,bdir);
    569:       PetscBTSet(btv,i);
    570:     } else if (test == ord) {
    571:       if (order == 1 || (!order && ii[i+1]-ii[i] == 1)) {
    572:         if (print) PetscPrintf(PETSC_COMM_SELF,"ENDPOINT %D\n",i);
    573:         PetscBTSet(btv,i);
    574:       } else {
    575:         if (print) PetscPrintf(PETSC_COMM_SELF,"CORNER CANDIDATE %D\n",i);
    576:         PetscBTSet(btvcand,i);
    577:       }
    578:     }
    579:   }
    580:   ISLocalToGlobalMappingRestoreNodeInfo(el2g,NULL,&ecount,&eneighs);
    581:   ISLocalToGlobalMappingRestoreNodeInfo(vl2g,NULL,&vcount,&vneighs);
    582:   PetscBTDestroy(&btbd);

    584:   /* a candidate is valid if it is connected to another candidate via a non-primal edge dof */
    585:   if (order != 1) {
    586:     if (print) PetscPrintf(PETSC_COMM_SELF,"INSPECTING CANDIDATES\n");
    587:     MatGetRowIJ(lGe,0,PETSC_FALSE,PETSC_FALSE,&i,&iit,&jjt,&done);
    588:     for (i=0;i<nv;i++) {
    589:       if (PetscBTLookup(btvcand,i)) {
    590:         PetscBool found = PETSC_FALSE;
    591:         for (j=ii[i];j<ii[i+1] && !found;j++) {
    592:           PetscInt k,e = jj[j];
    593:           if (PetscBTLookup(bte,e)) continue;
    594:           for (k=iit[e];k<iit[e+1];k++) {
    595:             PetscInt v = jjt[k];
    596:             if (v != i && PetscBTLookup(btvcand,v)) {
    597:               found = PETSC_TRUE;
    598:               break;
    599:             }
    600:           }
    601:         }
    602:         if (!found) {
    603:           if (print) PetscPrintf(PETSC_COMM_SELF,"  CANDIDATE %D CLEARED\n",i);
    604:           PetscBTClear(btvcand,i);
    605:         } else {
    606:           if (print) PetscPrintf(PETSC_COMM_SELF,"  CANDIDATE %D ACCEPTED\n",i);
    607:         }
    608:       }
    609:     }
    610:     MatRestoreRowIJ(lGe,0,PETSC_FALSE,PETSC_FALSE,&i,&iit,&jjt,&done);
    611:   }
    612:   MatSeqAIJRestoreArray(lGt,&vals);
    613:   MatRestoreRowIJ(lGt,0,PETSC_FALSE,PETSC_FALSE,&i,&ii,&jj,&done);
    614:   MatDestroy(&lGe);

    616:   /* Get the local G^T explicitly */
    617:   MatDestroy(&lGt);
    618:   MatTranspose(lG,MAT_INITIAL_MATRIX,&lGt);
    619:   MatSetOption(lGt,MAT_KEEP_NONZERO_PATTERN,PETSC_FALSE);

    621:   /* Mark interior nodal dofs */
    622:   ISLocalToGlobalMappingGetInfo(vl2g,&n_neigh,&neigh,&n_shared,&shared);
    623:   PetscBTCreate(nv,&btvi);
    624:   for (i=1;i<n_neigh;i++) {
    625:     for (j=0;j<n_shared[i];j++) {
    626:       PetscBTSet(btvi,shared[i][j]);
    627:     }
    628:   }
    629:   ISLocalToGlobalMappingRestoreInfo(vl2g,&n_neigh,&neigh,&n_shared,&shared);

    631:   /* communicate corners and splitpoints */
    632:   PetscMalloc1(nv,&vmarks);
    633:   PetscArrayzero(sfvleaves,nv);
    634:   PetscArrayzero(sfvroots,Lv);
    635:   for (i=0;i<nv;i++) if (PetscUnlikely(PetscBTLookup(btv,i))) sfvleaves[i] = 1;

    637:   if (print) {
    638:     IS tbz;

    640:     cum = 0;
    641:     for (i=0;i<nv;i++)
    642:       if (sfvleaves[i])
    643:         vmarks[cum++] = i;

    645:     ISCreateGeneral(PETSC_COMM_SELF,cum,vmarks,PETSC_COPY_VALUES,&tbz);
    646:     PetscObjectSetName((PetscObject)tbz,"corners_to_be_zeroed_local");
    647:     ISView(tbz,NULL);
    648:     ISDestroy(&tbz);
    649:   }

    651:   PetscSFReduceBegin(sfv,MPIU_INT,sfvleaves,sfvroots,MPI_SUM);
    652:   PetscSFReduceEnd(sfv,MPIU_INT,sfvleaves,sfvroots,MPI_SUM);
    653:   PetscSFBcastBegin(sfv,MPIU_INT,sfvroots,sfvleaves);
    654:   PetscSFBcastEnd(sfv,MPIU_INT,sfvroots,sfvleaves);

    656:   /* Zero rows of lGt corresponding to identified corners
    657:      and interior nodal dofs */
    658:   cum = 0;
    659:   for (i=0;i<nv;i++) {
    660:     if (sfvleaves[i]) {
    661:       vmarks[cum++] = i;
    662:       PetscBTSet(btv,i);
    663:     }
    664:     if (!PetscBTLookup(btvi,i)) vmarks[cum++] = i;
    665:   }
    666:   PetscBTDestroy(&btvi);
    667:   if (print) {
    668:     IS tbz;

    670:     ISCreateGeneral(PETSC_COMM_SELF,cum,vmarks,PETSC_COPY_VALUES,&tbz);
    671:     PetscObjectSetName((PetscObject)tbz,"corners_to_be_zeroed_with_interior");
    672:     ISView(tbz,NULL);
    673:     ISDestroy(&tbz);
    674:   }
    675:   MatZeroRows(lGt,cum,vmarks,0.,NULL,NULL);
    676:   PetscFree(vmarks);
    677:   PetscSFDestroy(&sfv);
    678:   PetscFree2(sfvleaves,sfvroots);

    680:   /* Recompute G */
    681:   MatDestroy(&lG);
    682:   MatTranspose(lGt,MAT_INITIAL_MATRIX,&lG);
    683:   if (print) {
    684:     PetscObjectSetName((PetscObject)lG,"used_lG");
    685:     MatView(lG,NULL);
    686:     PetscObjectSetName((PetscObject)lGt,"used_lGt");
    687:     MatView(lGt,NULL);
    688:   }

    690:   /* Get primal dofs (if any) */
    691:   cum = 0;
    692:   for (i=0;i<ne;i++) {
    693:     if (PetscUnlikely(PetscBTLookup(bte,i))) marks[cum++] = i;
    694:   }
    695:   if (fl2g) {
    696:     ISLocalToGlobalMappingApply(fl2g,cum,marks,marks);
    697:   }
    698:   ISCreateGeneral(comm,cum,marks,PETSC_COPY_VALUES,&primals);
    699:   if (print) {
    700:     PetscObjectSetName((PetscObject)primals,"prescribed_primal_dofs");
    701:     ISView(primals,NULL);
    702:   }
    703:   PetscBTDestroy(&bte);
    704:   /* TODO: what if the user passed in some of them ?  */
    705:   PCBDDCSetPrimalVerticesLocalIS(pc,primals);
    706:   ISDestroy(&primals);

    708:   /* Compute edge connectivity */
    709:   PetscObjectSetOptionsPrefix((PetscObject)lG,"econn_");

    711:   /* Symbolic conn = lG*lGt */
    712:   MatProductCreate(lG,lGt,NULL,&conn);
    713:   MatProductSetType(conn,MATPRODUCT_AB);
    714:   MatProductSetAlgorithm(conn,"default");
    715:   MatProductSetFill(conn,PETSC_DEFAULT);
    716:   PetscObjectSetOptionsPrefix((PetscObject)conn,"econn_");
    717:   MatProductSetFromOptions(conn);
    718:   MatProductSymbolic(conn);

    720:   MatGetRowIJ(conn,0,PETSC_FALSE,PETSC_FALSE,&i,&ii,&jj,&done);
    721:   if (fl2g) {
    722:     PetscBT   btf;
    723:     PetscInt  *iia,*jja,*iiu,*jju;
    724:     PetscBool rest = PETSC_FALSE,free = PETSC_FALSE;

    726:     /* create CSR for all local dofs */
    727:     PetscMalloc1(n+1,&iia);
    728:     if (pcbddc->mat_graph->nvtxs_csr) { /* the user has passed in a CSR graph */
    729:       if (pcbddc->mat_graph->nvtxs_csr != n) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_USER,"Invalid size of CSR graph %D. Should be %D",pcbddc->mat_graph->nvtxs_csr,n);
    730:       iiu = pcbddc->mat_graph->xadj;
    731:       jju = pcbddc->mat_graph->adjncy;
    732:     } else if (pcbddc->use_local_adj) {
    733:       rest = PETSC_TRUE;
    734:       MatGetRowIJ(matis->A,0,PETSC_TRUE,PETSC_FALSE,&i,(const PetscInt**)&iiu,(const PetscInt**)&jju,&done);
    735:     } else {
    736:       free   = PETSC_TRUE;
    737:       PetscMalloc2(n+1,&iiu,n,&jju);
    738:       iiu[0] = 0;
    739:       for (i=0;i<n;i++) {
    740:         iiu[i+1] = i+1;
    741:         jju[i]   = -1;
    742:       }
    743:     }

    745:     /* import sizes of CSR */
    746:     iia[0] = 0;
    747:     for (i=0;i<n;i++) iia[i+1] = iiu[i+1]-iiu[i];

    749:     /* overwrite entries corresponding to the Nedelec field */
    750:     PetscBTCreate(n,&btf);
    751:     ISGetIndices(nedfieldlocal,&idxs);
    752:     for (i=0;i<ne;i++) {
    753:       PetscBTSet(btf,idxs[i]);
    754:       iia[idxs[i]+1] = ii[i+1]-ii[i];
    755:     }

    757:     /* iia in CSR */
    758:     for (i=0;i<n;i++) iia[i+1] += iia[i];

    760:     /* jja in CSR */
    761:     PetscMalloc1(iia[n],&jja);
    762:     for (i=0;i<n;i++)
    763:       if (!PetscBTLookup(btf,i))
    764:         for (j=0;j<iiu[i+1]-iiu[i];j++)
    765:           jja[iia[i]+j] = jju[iiu[i]+j];

    767:     /* map edge dofs connectivity */
    768:     if (jj) {
    769:       ISLocalToGlobalMappingApply(fl2g,ii[ne],jj,(PetscInt *)jj);
    770:       for (i=0;i<ne;i++) {
    771:         PetscInt e = idxs[i];
    772:         for (j=0;j<ii[i+1]-ii[i];j++) jja[iia[e]+j] = jj[ii[i]+j];
    773:       }
    774:     }
    775:     ISRestoreIndices(nedfieldlocal,&idxs);
    776:     PCBDDCSetLocalAdjacencyGraph(pc,n,iia,jja,PETSC_OWN_POINTER);
    777:     if (rest) {
    778:       MatRestoreRowIJ(matis->A,0,PETSC_TRUE,PETSC_FALSE,&i,(const PetscInt**)&iiu,(const PetscInt**)&jju,&done);
    779:     }
    780:     if (free) {
    781:       PetscFree2(iiu,jju);
    782:     }
    783:     PetscBTDestroy(&btf);
    784:   } else {
    785:     PCBDDCSetLocalAdjacencyGraph(pc,n,ii,jj,PETSC_USE_POINTER);
    786:   }

    788:   /* Analyze interface for edge dofs */
    789:   PCBDDCAnalyzeInterface(pc);
    790:   pcbddc->mat_graph->twodim = PETSC_FALSE;

    792:   /* Get coarse edges in the edge space */
    793:   PCBDDCGraphGetCandidatesIS(pcbddc->mat_graph,NULL,NULL,&nee,&alleedges,&allprimals);
    794:   MatRestoreRowIJ(conn,0,PETSC_FALSE,PETSC_FALSE,&i,&ii,&jj,&done);

    796:   if (fl2g) {
    797:     ISGlobalToLocalMappingApplyIS(fl2g,IS_GTOLM_DROP,allprimals,&primals);
    798:     PetscMalloc1(nee,&eedges);
    799:     for (i=0;i<nee;i++) {
    800:       ISGlobalToLocalMappingApplyIS(fl2g,IS_GTOLM_DROP,alleedges[i],&eedges[i]);
    801:     }
    802:   } else {
    803:     eedges  = alleedges;
    804:     primals = allprimals;
    805:   }

    807:   /* Mark fine edge dofs with their coarse edge id */
    808:   PetscArrayzero(marks,ne);
    809:   ISGetLocalSize(primals,&cum);
    810:   ISGetIndices(primals,&idxs);
    811:   for (i=0;i<cum;i++) marks[idxs[i]] = nee+1;
    812:   ISRestoreIndices(primals,&idxs);
    813:   if (print) {
    814:     PetscObjectSetName((PetscObject)primals,"obtained_primal_dofs");
    815:     ISView(primals,NULL);
    816:   }

    818:   maxsize = 0;
    819:   for (i=0;i<nee;i++) {
    820:     PetscInt size,mark = i+1;

    822:     ISGetLocalSize(eedges[i],&size);
    823:     ISGetIndices(eedges[i],&idxs);
    824:     for (j=0;j<size;j++) marks[idxs[j]] = mark;
    825:     ISRestoreIndices(eedges[i],&idxs);
    826:     maxsize = PetscMax(maxsize,size);
    827:   }

    829:   /* Find coarse edge endpoints */
    830:   MatGetRowIJ(lG,0,PETSC_FALSE,PETSC_FALSE,&i,&ii,&jj,&done);
    831:   MatGetRowIJ(lGt,0,PETSC_FALSE,PETSC_FALSE,&i,&iit,&jjt,&done);
    832:   for (i=0;i<nee;i++) {
    833:     PetscInt mark = i+1,size;

    835:     ISGetLocalSize(eedges[i],&size);
    836:     if (!size && nedfieldlocal) continue;
    837:     if (!size) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_PLIB,"Unexpected zero sized edge %D",i);
    838:     ISGetIndices(eedges[i],&idxs);
    839:     if (print) {
    840:       PetscPrintf(PETSC_COMM_SELF,"ENDPOINTS ANALYSIS EDGE %D\n",i);
    841:       ISView(eedges[i],NULL);
    842:     }
    843:     for (j=0;j<size;j++) {
    844:       PetscInt k, ee = idxs[j];
    845:       if (print) PetscPrintf(PETSC_COMM_SELF,"  idx %D\n",ee);
    846:       for (k=ii[ee];k<ii[ee+1];k++) {
    847:         if (print) PetscPrintf(PETSC_COMM_SELF,"    inspect %D\n",jj[k]);
    848:         if (PetscBTLookup(btv,jj[k])) {
    849:           if (print) PetscPrintf(PETSC_COMM_SELF,"      corner found (already set) %D\n",jj[k]);
    850:         } else if (PetscBTLookup(btvcand,jj[k])) { /* is it ok? */
    851:           PetscInt  k2;
    852:           PetscBool corner = PETSC_FALSE;
    853:           for (k2 = iit[jj[k]];k2 < iit[jj[k]+1];k2++) {
    854:             if (print) PetscPrintf(PETSC_COMM_SELF,"        INSPECTING %D: mark %D (ref mark %D), boundary %D\n",jjt[k2],marks[jjt[k2]],mark,!!PetscBTLookup(btb,jjt[k2]));
    855:             /* it's a corner if either is connected with an edge dof belonging to a different cc or
    856:                if the edge dof lie on the natural part of the boundary */
    857:             if ((marks[jjt[k2]] && marks[jjt[k2]] != mark) || (!marks[jjt[k2]] && PetscBTLookup(btb,jjt[k2]))) {
    858:               corner = PETSC_TRUE;
    859:               break;
    860:             }
    861:           }
    862:           if (corner) { /* found the nodal dof corresponding to the endpoint of the edge */
    863:             if (print) PetscPrintf(PETSC_COMM_SELF,"        corner found %D\n",jj[k]);
    864:             PetscBTSet(btv,jj[k]);
    865:           } else {
    866:             if (print) PetscPrintf(PETSC_COMM_SELF,"        no corners found\n");
    867:           }
    868:         }
    869:       }
    870:     }
    871:     ISRestoreIndices(eedges[i],&idxs);
    872:   }
    873:   MatRestoreRowIJ(lGt,0,PETSC_FALSE,PETSC_FALSE,&i,&iit,&jjt,&done);
    874:   MatRestoreRowIJ(lG,0,PETSC_FALSE,PETSC_FALSE,&i,&ii,&jj,&done);
    875:   PetscBTDestroy(&btb);

    877:   /* Reset marked primal dofs */
    878:   ISGetLocalSize(primals,&cum);
    879:   ISGetIndices(primals,&idxs);
    880:   for (i=0;i<cum;i++) marks[idxs[i]] = 0;
    881:   ISRestoreIndices(primals,&idxs);

    883:   /* Now use the initial lG */
    884:   MatDestroy(&lG);
    885:   MatDestroy(&lGt);
    886:   lG   = lGinit;
    887:   MatTranspose(lG,MAT_INITIAL_MATRIX,&lGt);

    889:   /* Compute extended cols indices */
    890:   PetscBTCreate(nv,&btvc);
    891:   PetscBTCreate(nee,&bter);
    892:   MatGetRowIJ(lG,0,PETSC_FALSE,PETSC_FALSE,&i,&ii,&jj,&done);
    893:   MatSeqAIJGetMaxRowNonzeros(lG,&i);
    894:   i   *= maxsize;
    895:   PetscCalloc1(nee,&extcols);
    896:   PetscMalloc2(i,&extrow,i,&gidxs);
    897:   eerr = PETSC_FALSE;
    898:   for (i=0;i<nee;i++) {
    899:     PetscInt size,found = 0;

    901:     cum  = 0;
    902:     ISGetLocalSize(eedges[i],&size);
    903:     if (!size && nedfieldlocal) continue;
    904:     if (!size) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_PLIB,"Unexpected zero sized edge %D",i);
    905:     ISGetIndices(eedges[i],&idxs);
    906:     PetscBTMemzero(nv,btvc);
    907:     for (j=0;j<size;j++) {
    908:       PetscInt k,ee = idxs[j];
    909:       for (k=ii[ee];k<ii[ee+1];k++) {
    910:         PetscInt vv = jj[k];
    911:         if (!PetscBTLookup(btv,vv)) extrow[cum++] = vv;
    912:         else if (!PetscBTLookupSet(btvc,vv)) found++;
    913:       }
    914:     }
    915:     ISRestoreIndices(eedges[i],&idxs);
    916:     PetscSortRemoveDupsInt(&cum,extrow);
    917:     ISLocalToGlobalMappingApply(vl2g,cum,extrow,gidxs);
    918:     PetscSortIntWithArray(cum,gidxs,extrow);
    919:     ISCreateGeneral(PETSC_COMM_SELF,cum,extrow,PETSC_COPY_VALUES,&extcols[i]);
    920:     /* it may happen that endpoints are not defined at this point
    921:        if it is the case, mark this edge for a second pass */
    922:     if (cum != size -1 || found != 2) {
    923:       PetscBTSet(bter,i);
    924:       if (print) {
    925:         PetscObjectSetName((PetscObject)eedges[i],"error_edge");
    926:         ISView(eedges[i],NULL);
    927:         PetscObjectSetName((PetscObject)extcols[i],"error_extcol");
    928:         ISView(extcols[i],NULL);
    929:       }
    930:       eerr = PETSC_TRUE;
    931:     }
    932:   }
    933:   /* if (eerr) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_PLIB,"Unexpected SIZE OF EDGE > EXTCOL FIRST PASS"); */
    934:   MPIU_Allreduce(&eerr,&done,1,MPIU_BOOL,MPI_LOR,comm);
    935:   if (done) {
    936:     PetscInt *newprimals;

    938:     PetscMalloc1(ne,&newprimals);
    939:     ISGetLocalSize(primals,&cum);
    940:     ISGetIndices(primals,&idxs);
    941:     PetscArraycpy(newprimals,idxs,cum);
    942:     ISRestoreIndices(primals,&idxs);
    943:     MatGetRowIJ(lGt,0,PETSC_FALSE,PETSC_FALSE,&i,&iit,&jjt,&done);
    944:     if (print) PetscPrintf(PETSC_COMM_SELF,"DOING SECOND PASS (eerr %D)\n",eerr);
    945:     for (i=0;i<nee;i++) {
    946:       PetscBool has_candidates = PETSC_FALSE;
    947:       if (PetscBTLookup(bter,i)) {
    948:         PetscInt size,mark = i+1;

    950:         ISGetLocalSize(eedges[i],&size);
    951:         ISGetIndices(eedges[i],&idxs);
    952:         /* for (j=0;j<size;j++) newprimals[cum++] = idxs[j]; */
    953:         for (j=0;j<size;j++) {
    954:           PetscInt k,ee = idxs[j];
    955:           if (print) PetscPrintf(PETSC_COMM_SELF,"Inspecting edge dof %D [%D %D)\n",ee,ii[ee],ii[ee+1]);
    956:           for (k=ii[ee];k<ii[ee+1];k++) {
    957:             /* set all candidates located on the edge as corners */
    958:             if (PetscBTLookup(btvcand,jj[k])) {
    959:               PetscInt k2,vv = jj[k];
    960:               has_candidates = PETSC_TRUE;
    961:               if (print) PetscPrintf(PETSC_COMM_SELF,"  Candidate set to vertex %D\n",vv);
    962:               PetscBTSet(btv,vv);
    963:               /* set all edge dofs connected to candidate as primals */
    964:               for (k2=iit[vv];k2<iit[vv+1];k2++) {
    965:                 if (marks[jjt[k2]] == mark) {
    966:                   PetscInt k3,ee2 = jjt[k2];
    967:                   if (print) PetscPrintf(PETSC_COMM_SELF,"    Connected edge dof set to primal %D\n",ee2);
    968:                   newprimals[cum++] = ee2;
    969:                   /* finally set the new corners */
    970:                   for (k3=ii[ee2];k3<ii[ee2+1];k3++) {
    971:                     if (print) PetscPrintf(PETSC_COMM_SELF,"      Connected nodal dof set to vertex %D\n",jj[k3]);
    972:                     PetscBTSet(btv,jj[k3]);
    973:                   }
    974:                 }
    975:               }
    976:             } else {
    977:               if (print) PetscPrintf(PETSC_COMM_SELF,"  Not a candidate vertex %D\n",jj[k]);
    978:             }
    979:           }
    980:         }
    981:         if (!has_candidates) { /* circular edge */
    982:           PetscInt k, ee = idxs[0],*tmarks;

    984:           PetscCalloc1(ne,&tmarks);
    985:           if (print) PetscPrintf(PETSC_COMM_SELF,"  Circular edge %D\n",i);
    986:           for (k=ii[ee];k<ii[ee+1];k++) {
    987:             PetscInt k2;
    988:             if (print) PetscPrintf(PETSC_COMM_SELF,"    Set to corner %D\n",jj[k]);
    989:             PetscBTSet(btv,jj[k]);
    990:             for (k2=iit[jj[k]];k2<iit[jj[k]+1];k2++) tmarks[jjt[k2]]++;
    991:           }
    992:           for (j=0;j<size;j++) {
    993:             if (tmarks[idxs[j]] > 1) {
    994:               if (print) PetscPrintf(PETSC_COMM_SELF,"  Edge dof set to primal %D\n",idxs[j]);
    995:               newprimals[cum++] = idxs[j];
    996:             }
    997:           }
    998:           PetscFree(tmarks);
    999:         }
    1000:         ISRestoreIndices(eedges[i],&idxs);
    1001:       }
    1002:       ISDestroy(&extcols[i]);
    1003:     }
    1004:     PetscFree(extcols);
    1005:     MatRestoreRowIJ(lGt,0,PETSC_FALSE,PETSC_FALSE,&i,&iit,&jjt,&done);
    1006:     PetscSortRemoveDupsInt(&cum,newprimals);
    1007:     if (fl2g) {
    1008:       ISLocalToGlobalMappingApply(fl2g,cum,newprimals,newprimals);
    1009:       ISDestroy(&primals);
    1010:       for (i=0;i<nee;i++) {
    1011:         ISDestroy(&eedges[i]);
    1012:       }
    1013:       PetscFree(eedges);
    1014:     }
    1015:     PCBDDCGraphRestoreCandidatesIS(pcbddc->mat_graph,NULL,NULL,&nee,&alleedges,&allprimals);
    1016:     ISCreateGeneral(comm,cum,newprimals,PETSC_COPY_VALUES,&primals);
    1017:     PetscFree(newprimals);
    1018:     PCBDDCSetPrimalVerticesLocalIS(pc,primals);
    1019:     ISDestroy(&primals);
    1020:     PCBDDCAnalyzeInterface(pc);
    1021:     pcbddc->mat_graph->twodim = PETSC_FALSE;
    1022:     PCBDDCGraphGetCandidatesIS(pcbddc->mat_graph,NULL,NULL,&nee,&alleedges,&allprimals);
    1023:     if (fl2g) {
    1024:       ISGlobalToLocalMappingApplyIS(fl2g,IS_GTOLM_DROP,allprimals,&primals);
    1025:       PetscMalloc1(nee,&eedges);
    1026:       for (i=0;i<nee;i++) {
    1027:         ISGlobalToLocalMappingApplyIS(fl2g,IS_GTOLM_DROP,alleedges[i],&eedges[i]);
    1028:       }
    1029:     } else {
    1030:       eedges  = alleedges;
    1031:       primals = allprimals;
    1032:     }
    1033:     PetscCalloc1(nee,&extcols);

    1035:     /* Mark again */
    1036:     PetscArrayzero(marks,ne);
    1037:     for (i=0;i<nee;i++) {
    1038:       PetscInt size,mark = i+1;

    1040:       ISGetLocalSize(eedges[i],&size);
    1041:       ISGetIndices(eedges[i],&idxs);
    1042:       for (j=0;j<size;j++) marks[idxs[j]] = mark;
    1043:       ISRestoreIndices(eedges[i],&idxs);
    1044:     }
    1045:     if (print) {
    1046:       PetscObjectSetName((PetscObject)primals,"obtained_primal_dofs_secondpass");
    1047:       ISView(primals,NULL);
    1048:     }

    1050:     /* Recompute extended cols */
    1051:     eerr = PETSC_FALSE;
    1052:     for (i=0;i<nee;i++) {
    1053:       PetscInt size;

    1055:       cum  = 0;
    1056:       ISGetLocalSize(eedges[i],&size);
    1057:       if (!size && nedfieldlocal) continue;
    1058:       if (!size) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_PLIB,"Unexpected zero sized edge %D",i);
    1059:       ISGetIndices(eedges[i],&idxs);
    1060:       for (j=0;j<size;j++) {
    1061:         PetscInt k,ee = idxs[j];
    1062:         for (k=ii[ee];k<ii[ee+1];k++) if (!PetscBTLookup(btv,jj[k])) extrow[cum++] = jj[k];
    1063:       }
    1064:       ISRestoreIndices(eedges[i],&idxs);
    1065:       PetscSortRemoveDupsInt(&cum,extrow);
    1066:       ISLocalToGlobalMappingApply(vl2g,cum,extrow,gidxs);
    1067:       PetscSortIntWithArray(cum,gidxs,extrow);
    1068:       ISCreateGeneral(PETSC_COMM_SELF,cum,extrow,PETSC_COPY_VALUES,&extcols[i]);
    1069:       if (cum != size -1) {
    1070:         if (print) {
    1071:           PetscObjectSetName((PetscObject)eedges[i],"error_edge_secondpass");
    1072:           ISView(eedges[i],NULL);
    1073:           PetscObjectSetName((PetscObject)extcols[i],"error_extcol_secondpass");
    1074:           ISView(extcols[i],NULL);
    1075:         }
    1076:         eerr = PETSC_TRUE;
    1077:       }
    1078:     }
    1079:   }
    1080:   MatRestoreRowIJ(lG,0,PETSC_FALSE,PETSC_FALSE,&i,&ii,&jj,&done);
    1081:   PetscFree2(extrow,gidxs);
    1082:   PetscBTDestroy(&bter);
    1083:   if (print) { PCBDDCGraphASCIIView(pcbddc->mat_graph,5,PETSC_VIEWER_STDOUT_SELF); }
    1084:   /* an error should not occur at this point */
    1085:   if (eerr) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_PLIB,"Unexpected SIZE OF EDGE > EXTCOL SECOND PASS");

    1087:   /* Check the number of endpoints */
    1088:   MatGetRowIJ(lG,0,PETSC_FALSE,PETSC_FALSE,&i,&ii,&jj,&done);
    1089:   PetscMalloc1(2*nee,&corners);
    1090:   PetscMalloc1(nee,&cedges);
    1091:   for (i=0;i<nee;i++) {
    1092:     PetscInt size, found = 0, gc[2];

    1094:     /* init with defaults */
    1095:     cedges[i] = corners[i*2] = corners[i*2+1] = -1;
    1096:     ISGetLocalSize(eedges[i],&size);
    1097:     if (!size && nedfieldlocal) continue;
    1098:     if (!size) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_PLIB,"Unexpected zero sized edge %D",i);
    1099:     ISGetIndices(eedges[i],&idxs);
    1100:     PetscBTMemzero(nv,btvc);
    1101:     for (j=0;j<size;j++) {
    1102:       PetscInt k,ee = idxs[j];
    1103:       for (k=ii[ee];k<ii[ee+1];k++) {
    1104:         PetscInt vv = jj[k];
    1105:         if (PetscBTLookup(btv,vv) && !PetscBTLookupSet(btvc,vv)) {
    1106:           if (found == 2) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_PLIB,"Found more then two corners for edge %D",i);
    1107:           corners[i*2+found++] = vv;
    1108:         }
    1109:       }
    1110:     }
    1111:     if (found != 2) {
    1112:       PetscInt e;
    1113:       if (fl2g) {
    1114:         ISLocalToGlobalMappingApply(fl2g,1,idxs,&e);
    1115:       } else {
    1116:         e = idxs[0];
    1117:       }
    1118:       SETERRQ4(PETSC_COMM_SELF,PETSC_ERR_PLIB,"Found %D corners for edge %D (astart %D, estart %D)",found,i,e,idxs[0]);
    1119:     }

    1121:     /* get primal dof index on this coarse edge */
    1122:     ISLocalToGlobalMappingApply(vl2g,2,corners+2*i,gc);
    1123:     if (gc[0] > gc[1]) {
    1124:       PetscInt swap  = corners[2*i];
    1125:       corners[2*i]   = corners[2*i+1];
    1126:       corners[2*i+1] = swap;
    1127:     }
    1128:     cedges[i] = idxs[size-1];
    1129:     ISRestoreIndices(eedges[i],&idxs);
    1130:     if (print) PetscPrintf(PETSC_COMM_SELF,"EDGE %D: ce %D, corners (%D,%D)\n",i,cedges[i],corners[2*i],corners[2*i+1]);
    1131:   }
    1132:   MatRestoreRowIJ(lG,0,PETSC_FALSE,PETSC_FALSE,&i,&ii,&jj,&done);
    1133:   PetscBTDestroy(&btvc);

    1135: #if defined(PETSC_USE_DEBUG)
    1136:   /* Inspects columns of lG (rows of lGt) and make sure the change of basis will
    1137:      not interfere with neighbouring coarse edges */
    1138:   PetscMalloc1(nee+1,&emarks);
    1139:   MatGetRowIJ(lGt,0,PETSC_FALSE,PETSC_FALSE,&i,&ii,&jj,&done);
    1140:   for (i=0;i<nv;i++) {
    1141:     PetscInt emax = 0,eemax = 0;

    1143:     if (ii[i+1]==ii[i] || PetscBTLookup(btv,i)) continue;
    1144:     PetscArrayzero(emarks,nee+1);
    1145:     for (j=ii[i];j<ii[i+1];j++) emarks[marks[jj[j]]]++;
    1146:     for (j=1;j<nee+1;j++) {
    1147:       if (emax < emarks[j]) {
    1148:         emax = emarks[j];
    1149:         eemax = j;
    1150:       }
    1151:     }
    1152:     /* not relevant for edges */
    1153:     if (!eemax) continue;

    1155:     for (j=ii[i];j<ii[i+1];j++) {
    1156:       if (marks[jj[j]] && marks[jj[j]] != eemax) {
    1157:         SETERRQ4(PETSC_COMM_SELF,PETSC_ERR_SUP,"Found 2 coarse edges (id %D and %D) connected through the %D nodal dof at edge dof %D",marks[jj[j]]-1,eemax,i,jj[j]);
    1158:       }
    1159:     }
    1160:   }
    1161:   PetscFree(emarks);
    1162:   MatRestoreRowIJ(lGt,0,PETSC_FALSE,PETSC_FALSE,&i,&ii,&jj,&done);
    1163: #endif

    1165:   /* Compute extended rows indices for edge blocks of the change of basis */
    1166:   MatGetRowIJ(lGt,0,PETSC_FALSE,PETSC_FALSE,&i,&ii,&jj,&done);
    1167:   MatSeqAIJGetMaxRowNonzeros(lGt,&extmem);
    1168:   extmem *= maxsize;
    1169:   PetscMalloc1(extmem*nee,&extrow);
    1170:   PetscMalloc1(nee,&extrows);
    1171:   PetscCalloc1(nee,&extrowcum);
    1172:   for (i=0;i<nv;i++) {
    1173:     PetscInt mark = 0,size,start;

    1175:     if (ii[i+1]==ii[i] || PetscBTLookup(btv,i)) continue;
    1176:     for (j=ii[i];j<ii[i+1];j++)
    1177:       if (marks[jj[j]] && !mark)
    1178:         mark = marks[jj[j]];

    1180:     /* not relevant */
    1181:     if (!mark) continue;

    1183:     /* import extended row */
    1184:     mark--;
    1185:     start = mark*extmem+extrowcum[mark];
    1186:     size = ii[i+1]-ii[i];
    1187:     if (extrowcum[mark] + size > extmem) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_PLIB,"Not enough memory allocated %D > %D",extrowcum[mark] + size,extmem);
    1188:     PetscArraycpy(extrow+start,jj+ii[i],size);
    1189:     extrowcum[mark] += size;
    1190:   }
    1191:   MatRestoreRowIJ(lGt,0,PETSC_FALSE,PETSC_FALSE,&i,&ii,&jj,&done);
    1192:   MatDestroy(&lGt);
    1193:   PetscFree(marks);

    1195:   /* Compress extrows */
    1196:   cum  = 0;
    1197:   for (i=0;i<nee;i++) {
    1198:     PetscInt size = extrowcum[i],*start = extrow + i*extmem;
    1199:     PetscSortRemoveDupsInt(&size,start);
    1200:     ISCreateGeneral(PETSC_COMM_SELF,size,start,PETSC_USE_POINTER,&extrows[i]);
    1201:     cum  = PetscMax(cum,size);
    1202:   }
    1203:   PetscFree(extrowcum);
    1204:   PetscBTDestroy(&btv);
    1205:   PetscBTDestroy(&btvcand);

    1207:   /* Workspace for lapack inner calls and VecSetValues */
    1208:   PetscMalloc2((5+cum+maxsize)*maxsize,&work,maxsize,&rwork);

    1210:   /* Create change of basis matrix (preallocation can be improved) */
    1211:   MatCreate(comm,&T);
    1212:   MatSetSizes(T,pc->pmat->rmap->n,pc->pmat->rmap->n,
    1213:                        pc->pmat->rmap->N,pc->pmat->rmap->N);
    1214:   MatSetType(T,MATAIJ);
    1215:   MatSeqAIJSetPreallocation(T,10,NULL);
    1216:   MatMPIAIJSetPreallocation(T,10,NULL,10,NULL);
    1217:   MatSetLocalToGlobalMapping(T,al2g,al2g);
    1218:   MatSetOption(T,MAT_NEW_NONZERO_ALLOCATION_ERR,PETSC_FALSE);
    1219:   MatSetOption(T,MAT_ROW_ORIENTED,PETSC_FALSE);
    1220:   ISLocalToGlobalMappingDestroy(&al2g);

    1222:   /* Defaults to identity */
    1223:   MatCreateVecs(pc->pmat,&tvec,NULL);
    1224:   VecSet(tvec,1.0);
    1225:   MatDiagonalSet(T,tvec,INSERT_VALUES);
    1226:   VecDestroy(&tvec);

    1228:   /* Create discrete gradient for the coarser level if needed */
    1229:   MatDestroy(&pcbddc->nedcG);
    1230:   ISDestroy(&pcbddc->nedclocal);
    1231:   if (pcbddc->current_level < pcbddc->max_levels) {
    1232:     ISLocalToGlobalMapping cel2g,cvl2g;
    1233:     IS                     wis,gwis;
    1234:     PetscInt               cnv,cne;

    1236:     ISCreateGeneral(comm,nee,cedges,PETSC_COPY_VALUES,&wis);
    1237:     if (fl2g) {
    1238:       ISLocalToGlobalMappingApplyIS(fl2g,wis,&pcbddc->nedclocal);
    1239:     } else {
    1240:       PetscObjectReference((PetscObject)wis);
    1241:       pcbddc->nedclocal = wis;
    1242:     }
    1243:     ISLocalToGlobalMappingApplyIS(el2g,wis,&gwis);
    1244:     ISDestroy(&wis);
    1245:     ISRenumber(gwis,NULL,&cne,&wis);
    1246:     ISLocalToGlobalMappingCreateIS(wis,&cel2g);
    1247:     ISDestroy(&wis);
    1248:     ISDestroy(&gwis);

    1250:     ISCreateGeneral(comm,2*nee,corners,PETSC_USE_POINTER,&wis);
    1251:     ISLocalToGlobalMappingApplyIS(vl2g,wis,&gwis);
    1252:     ISDestroy(&wis);
    1253:     ISRenumber(gwis,NULL,&cnv,&wis);
    1254:     ISLocalToGlobalMappingCreateIS(wis,&cvl2g);
    1255:     ISDestroy(&wis);
    1256:     ISDestroy(&gwis);

    1258:     MatCreate(comm,&pcbddc->nedcG);
    1259:     MatSetSizes(pcbddc->nedcG,PETSC_DECIDE,PETSC_DECIDE,cne,cnv);
    1260:     MatSetType(pcbddc->nedcG,MATAIJ);
    1261:     MatSeqAIJSetPreallocation(pcbddc->nedcG,2,NULL);
    1262:     MatMPIAIJSetPreallocation(pcbddc->nedcG,2,NULL,2,NULL);
    1263:     MatSetLocalToGlobalMapping(pcbddc->nedcG,cel2g,cvl2g);
    1264:     ISLocalToGlobalMappingDestroy(&cel2g);
    1265:     ISLocalToGlobalMappingDestroy(&cvl2g);
    1266:   }
    1267:   ISLocalToGlobalMappingDestroy(&vl2g);

    1269: #if defined(PRINT_GDET)
    1270:   inc = 0;
    1271:   lev = pcbddc->current_level;
    1272: #endif

    1274:   /* Insert values in the change of basis matrix */
    1275:   for (i=0;i<nee;i++) {
    1276:     Mat         Gins = NULL, GKins = NULL;
    1277:     IS          cornersis = NULL;
    1278:     PetscScalar cvals[2];

    1280:     if (pcbddc->nedcG) {
    1281:       ISCreateGeneral(PETSC_COMM_SELF,2,corners+2*i,PETSC_USE_POINTER,&cornersis);
    1282:     }
    1283:     PCBDDCComputeNedelecChangeEdge(lG,eedges[i],extrows[i],extcols[i],cornersis,&Gins,&GKins,cvals,work,rwork);
    1284:     if (Gins && GKins) {
    1285:       const PetscScalar *data;
    1286:       const PetscInt    *rows,*cols;
    1287:       PetscInt          nrh,nch,nrc,ncc;

    1289:       ISGetIndices(eedges[i],&cols);
    1290:       /* H1 */
    1291:       ISGetIndices(extrows[i],&rows);
    1292:       MatGetSize(Gins,&nrh,&nch);
    1293:       MatDenseGetArrayRead(Gins,&data);
    1294:       MatSetValuesLocal(T,nrh,rows,nch,cols,data,INSERT_VALUES);
    1295:       MatDenseRestoreArrayRead(Gins,&data);
    1296:       ISRestoreIndices(extrows[i],&rows);
    1297:       /* complement */
    1298:       MatGetSize(GKins,&nrc,&ncc);
    1299:       if (!ncc) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_PLIB,"Constant function has not been generated for coarse edge %D",i);
    1300:       if (ncc + nch != nrc) SETERRQ4(PETSC_COMM_SELF,PETSC_ERR_PLIB,"The sum of the number of columns of GKins %D and Gins %D does not match %D for coarse edge %D",ncc,nch,nrc,i);
    1301:       if (ncc != 1 && pcbddc->nedcG) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_SUP,"Cannot generate the coarse discrete gradient for coarse edge %D with ncc %D",i,ncc);
    1302:       MatDenseGetArrayRead(GKins,&data);
    1303:       MatSetValuesLocal(T,nrc,cols,ncc,cols+nch,data,INSERT_VALUES);
    1304:       MatDenseRestoreArrayRead(GKins,&data);

    1306:       /* coarse discrete gradient */
    1307:       if (pcbddc->nedcG) {
    1308:         PetscInt cols[2];

    1310:         cols[0] = 2*i;
    1311:         cols[1] = 2*i+1;
    1312:         MatSetValuesLocal(pcbddc->nedcG,1,&i,2,cols,cvals,INSERT_VALUES);
    1313:       }
    1314:       ISRestoreIndices(eedges[i],&cols);
    1315:     }
    1316:     ISDestroy(&extrows[i]);
    1317:     ISDestroy(&extcols[i]);
    1318:     ISDestroy(&cornersis);
    1319:     MatDestroy(&Gins);
    1320:     MatDestroy(&GKins);
    1321:   }
    1322:   ISLocalToGlobalMappingDestroy(&el2g);

    1324:   /* Start assembling */
    1325:   MatAssemblyBegin(T,MAT_FINAL_ASSEMBLY);
    1326:   if (pcbddc->nedcG) {
    1327:     MatAssemblyBegin(pcbddc->nedcG,MAT_FINAL_ASSEMBLY);
    1328:   }

    1330:   /* Free */
    1331:   if (fl2g) {
    1332:     ISDestroy(&primals);
    1333:     for (i=0;i<nee;i++) {
    1334:       ISDestroy(&eedges[i]);
    1335:     }
    1336:     PetscFree(eedges);
    1337:   }

    1339:   /* hack mat_graph with primal dofs on the coarse edges */
    1340:   {
    1341:     PCBDDCGraph graph   = pcbddc->mat_graph;
    1342:     PetscInt    *oqueue = graph->queue;
    1343:     PetscInt    *ocptr  = graph->cptr;
    1344:     PetscInt    ncc,*idxs;

    1346:     /* find first primal edge */
    1347:     if (pcbddc->nedclocal) {
    1348:       ISGetIndices(pcbddc->nedclocal,(const PetscInt**)&idxs);
    1349:     } else {
    1350:       if (fl2g) {
    1351:         ISLocalToGlobalMappingApply(fl2g,nee,cedges,cedges);
    1352:       }
    1353:       idxs = cedges;
    1354:     }
    1355:     cum = 0;
    1356:     while (cum < nee && cedges[cum] < 0) cum++;

    1358:     /* adapt connected components */
    1359:     PetscMalloc2(graph->nvtxs+1,&graph->cptr,ocptr[graph->ncc],&graph->queue);
    1360:     graph->cptr[0] = 0;
    1361:     for (i=0,ncc=0;i<graph->ncc;i++) {
    1362:       PetscInt lc = ocptr[i+1]-ocptr[i];
    1363:       if (cum != nee && oqueue[ocptr[i+1]-1] == cedges[cum]) { /* this cc has a primal dof */
    1364:         graph->cptr[ncc+1] = graph->cptr[ncc]+1;
    1365:         graph->queue[graph->cptr[ncc]] = cedges[cum];
    1366:         ncc++;
    1367:         lc--;
    1368:         cum++;
    1369:         while (cum < nee && cedges[cum] < 0) cum++;
    1370:       }
    1371:       graph->cptr[ncc+1] = graph->cptr[ncc] + lc;
    1372:       for (j=0;j<lc;j++) graph->queue[graph->cptr[ncc]+j] = oqueue[ocptr[i]+j];
    1373:       ncc++;
    1374:     }
    1375:     graph->ncc = ncc;
    1376:     if (pcbddc->nedclocal) {
    1377:       ISRestoreIndices(pcbddc->nedclocal,(const PetscInt**)&idxs);
    1378:     }
    1379:     PetscFree2(ocptr,oqueue);
    1380:   }
    1381:   ISLocalToGlobalMappingDestroy(&fl2g);
    1382:   PCBDDCGraphRestoreCandidatesIS(pcbddc->mat_graph,NULL,NULL,&nee,&alleedges,&allprimals);
    1383:   PCBDDCGraphResetCSR(pcbddc->mat_graph);
    1384:   MatDestroy(&conn);

    1386:   ISDestroy(&nedfieldlocal);
    1387:   PetscFree(extrow);
    1388:   PetscFree2(work,rwork);
    1389:   PetscFree(corners);
    1390:   PetscFree(cedges);
    1391:   PetscFree(extrows);
    1392:   PetscFree(extcols);
    1393:   MatDestroy(&lG);

    1395:   /* Complete assembling */
    1396:   MatAssemblyEnd(T,MAT_FINAL_ASSEMBLY);
    1397:   if (pcbddc->nedcG) {
    1398:     MatAssemblyEnd(pcbddc->nedcG,MAT_FINAL_ASSEMBLY);
    1399: #if 0
    1400:     PetscObjectSetName((PetscObject)pcbddc->nedcG,"coarse_G");
    1401:     MatView(pcbddc->nedcG,NULL);
    1402: #endif
    1403:   }

    1405:   /* set change of basis */
    1406:   PCBDDCSetChangeOfBasisMat(pc,T,singular);
    1407:   MatDestroy(&T);

    1409:   return(0);
    1410: }

    1412: /* the near-null space of BDDC carries information on quadrature weights,
    1413:    and these can be collinear -> so cheat with MatNullSpaceCreate
    1414:    and create a suitable set of basis vectors first */
    1415: PetscErrorCode PCBDDCNullSpaceCreate(MPI_Comm comm, PetscBool has_const, PetscInt nvecs, Vec quad_vecs[], MatNullSpace *nnsp)
    1416: {
    1418:   PetscInt       i;

    1421:   for (i=0;i<nvecs;i++) {
    1422:     PetscInt first,last;

    1424:     VecGetOwnershipRange(quad_vecs[i],&first,&last);
    1425:     if (last-first < 2*nvecs && has_const) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"Not implemented");
    1426:     if (i>=first && i < last) {
    1427:       PetscScalar *data;
    1428:       VecGetArray(quad_vecs[i],&data);
    1429:       if (!has_const) {
    1430:         data[i-first] = 1.;
    1431:       } else {
    1432:         data[2*i-first] = 1./PetscSqrtReal(2.);
    1433:         data[2*i-first+1] = -1./PetscSqrtReal(2.);
    1434:       }
    1435:       VecRestoreArray(quad_vecs[i],&data);
    1436:     }
    1437:     PetscObjectStateIncrease((PetscObject)quad_vecs[i]);
    1438:   }
    1439:   MatNullSpaceCreate(comm,has_const,nvecs,quad_vecs,nnsp);
    1440:   for (i=0;i<nvecs;i++) { /* reset vectors */
    1441:     PetscInt first,last;
    1442:     VecLockReadPop(quad_vecs[i]);
    1443:     VecGetOwnershipRange(quad_vecs[i],&first,&last);
    1444:     if (i>=first && i < last) {
    1445:       PetscScalar *data;
    1446:       VecGetArray(quad_vecs[i],&data);
    1447:       if (!has_const) {
    1448:         data[i-first] = 0.;
    1449:       } else {
    1450:         data[2*i-first] = 0.;
    1451:         data[2*i-first+1] = 0.;
    1452:       }
    1453:       VecRestoreArray(quad_vecs[i],&data);
    1454:     }
    1455:     PetscObjectStateIncrease((PetscObject)quad_vecs[i]);
    1456:     VecLockReadPush(quad_vecs[i]);
    1457:   }
    1458:   return(0);
    1459: }

    1461: PetscErrorCode PCBDDCComputeNoNetFlux(Mat A, Mat divudotp, PetscBool transpose, IS vl2l, PCBDDCGraph graph, MatNullSpace *nnsp)
    1462: {
    1463:   Mat                    loc_divudotp;
    1464:   Vec                    p,v,vins,quad_vec,*quad_vecs;
    1465:   ISLocalToGlobalMapping map;
    1466:   PetscScalar            *vals;
    1467:   const PetscScalar      *array;
    1468:   PetscInt               i,maxneighs = 0,maxsize,*gidxs;
    1469:   PetscInt               n_neigh,*neigh,*n_shared,**shared;
    1470:   PetscMPIInt            rank;
    1471:   PetscErrorCode         ierr;

    1474:   ISLocalToGlobalMappingGetInfo(graph->l2gmap,&n_neigh,&neigh,&n_shared,&shared);
    1475:   for (i=0;i<n_neigh;i++) maxneighs = PetscMax(graph->count[shared[i][0]]+1,maxneighs);
    1476:   MPIU_Allreduce(MPI_IN_PLACE,&maxneighs,1,MPIU_INT,MPI_MAX,PetscObjectComm((PetscObject)A));
    1477:   if (!maxneighs) {
    1478:     ISLocalToGlobalMappingRestoreInfo(graph->l2gmap,&n_neigh,&neigh,&n_shared,&shared);
    1479:     *nnsp = NULL;
    1480:     return(0);
    1481:   }
    1482:   maxsize = 0;
    1483:   for (i=0;i<n_neigh;i++) maxsize = PetscMax(n_shared[i],maxsize);
    1484:   PetscMalloc2(maxsize,&gidxs,maxsize,&vals);
    1485:   /* create vectors to hold quadrature weights */
    1486:   MatCreateVecs(A,&quad_vec,NULL);
    1487:   if (!transpose) {
    1488:     MatGetLocalToGlobalMapping(A,&map,NULL);
    1489:   } else {
    1490:     MatGetLocalToGlobalMapping(A,NULL,&map);
    1491:   }
    1492:   VecDuplicateVecs(quad_vec,maxneighs,&quad_vecs);
    1493:   VecDestroy(&quad_vec);
    1494:   PCBDDCNullSpaceCreate(PetscObjectComm((PetscObject)A),PETSC_FALSE,maxneighs,quad_vecs,nnsp);
    1495:   for (i=0;i<maxneighs;i++) {
    1496:     VecLockReadPop(quad_vecs[i]);
    1497:   }

    1499:   /* compute local quad vec */
    1500:   MatISGetLocalMat(divudotp,&loc_divudotp);
    1501:   if (!transpose) {
    1502:     MatCreateVecs(loc_divudotp,&v,&p);
    1503:   } else {
    1504:     MatCreateVecs(loc_divudotp,&p,&v);
    1505:   }
    1506:   VecSet(p,1.);
    1507:   if (!transpose) {
    1508:     MatMultTranspose(loc_divudotp,p,v);
    1509:   } else {
    1510:     MatMult(loc_divudotp,p,v);
    1511:   }
    1512:   if (vl2l) {
    1513:     Mat        lA;
    1514:     VecScatter sc;

    1516:     MatISGetLocalMat(A,&lA);
    1517:     MatCreateVecs(lA,&vins,NULL);
    1518:     VecScatterCreate(v,NULL,vins,vl2l,&sc);
    1519:     VecScatterBegin(sc,v,vins,INSERT_VALUES,SCATTER_FORWARD);
    1520:     VecScatterEnd(sc,v,vins,INSERT_VALUES,SCATTER_FORWARD);
    1521:     VecScatterDestroy(&sc);
    1522:   } else {
    1523:     vins = v;
    1524:   }
    1525:   VecGetArrayRead(vins,&array);
    1526:   VecDestroy(&p);

    1528:   /* insert in global quadrature vecs */
    1529:   MPI_Comm_rank(PetscObjectComm((PetscObject)A),&rank);
    1530:   for (i=1;i<n_neigh;i++) {
    1531:     const PetscInt    *idxs;
    1532:     PetscInt          idx,nn,j;

    1534:     idxs = shared[i];
    1535:     nn   = n_shared[i];
    1536:     for (j=0;j<nn;j++) vals[j] = array[idxs[j]];
    1537:     PetscFindInt(rank,graph->count[idxs[0]],graph->neighbours_set[idxs[0]],&idx);
    1538:     idx  = -(idx+1);
    1539:     if (idx < 0 || idx >= maxneighs) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_PLIB,"Invalid index %D not in [0,%D)",idx,maxneighs);
    1540:     ISLocalToGlobalMappingApply(map,nn,idxs,gidxs);
    1541:     VecSetValues(quad_vecs[idx],nn,gidxs,vals,INSERT_VALUES);
    1542:   }
    1543:   ISLocalToGlobalMappingRestoreInfo(graph->l2gmap,&n_neigh,&neigh,&n_shared,&shared);
    1544:   VecRestoreArrayRead(vins,&array);
    1545:   if (vl2l) {
    1546:     VecDestroy(&vins);
    1547:   }
    1548:   VecDestroy(&v);
    1549:   PetscFree2(gidxs,vals);

    1551:   /* assemble near null space */
    1552:   for (i=0;i<maxneighs;i++) {
    1553:     VecAssemblyBegin(quad_vecs[i]);
    1554:   }
    1555:   for (i=0;i<maxneighs;i++) {
    1556:     VecAssemblyEnd(quad_vecs[i]);
    1557:     VecViewFromOptions(quad_vecs[i],NULL,"-pc_bddc_quad_vecs_view");
    1558:     VecLockReadPush(quad_vecs[i]);
    1559:   }
    1560:   VecDestroyVecs(maxneighs,&quad_vecs);
    1561:   return(0);
    1562: }

    1564: PetscErrorCode PCBDDCAddPrimalVerticesLocalIS(PC pc, IS primalv)
    1565: {
    1566:   PC_BDDC        *pcbddc = (PC_BDDC*)pc->data;

    1570:   if (primalv) {
    1571:     if (pcbddc->user_primal_vertices_local) {
    1572:       IS list[2], newp;

    1574:       list[0] = primalv;
    1575:       list[1] = pcbddc->user_primal_vertices_local;
    1576:       ISConcatenate(PetscObjectComm((PetscObject)pc),2,list,&newp);
    1577:       ISSortRemoveDups(newp);
    1578:       ISDestroy(&list[1]);
    1579:       pcbddc->user_primal_vertices_local = newp;
    1580:     } else {
    1581:       PCBDDCSetPrimalVerticesLocalIS(pc,primalv);
    1582:     }
    1583:   }
    1584:   return(0);
    1585: }

    1587: static PetscErrorCode func_coords_private(PetscInt dim, PetscReal t, const PetscReal X[], PetscInt Nf, PetscScalar *out, void *ctx)
    1588: {
    1589:   PetscInt f, *comp  = (PetscInt *)ctx;

    1592:   for (f=0;f<Nf;f++) out[f] = X[*comp];
    1593:   return(0);
    1594: }

    1596: PetscErrorCode PCBDDCComputeLocalTopologyInfo(PC pc)
    1597: {
    1599:   Vec            local,global;
    1600:   PC_BDDC        *pcbddc = (PC_BDDC*)pc->data;
    1601:   Mat_IS         *matis = (Mat_IS*)pc->pmat->data;
    1602:   PetscBool      monolithic = PETSC_FALSE;

    1605:   PetscOptionsBegin(PetscObjectComm((PetscObject)pc),((PetscObject)pc)->prefix,"BDDC topology options","PC");
    1606:   PetscOptionsBool("-pc_bddc_monolithic","Discard any information on dofs splitting",NULL,monolithic,&monolithic,NULL);
    1607:   PetscOptionsEnd();
    1608:   /* need to convert from global to local topology information and remove references to information in global ordering */
    1609:   MatCreateVecs(pc->pmat,&global,NULL);
    1610:   MatCreateVecs(matis->A,&local,NULL);
    1611:   VecBindToCPU(global,PETSC_TRUE);
    1612:   VecBindToCPU(local,PETSC_TRUE);
    1613:   if (monolithic) { /* just get block size to properly compute vertices */
    1614:     if (pcbddc->vertex_size == 1) {
    1615:       MatGetBlockSize(pc->pmat,&pcbddc->vertex_size);
    1616:     }
    1617:     goto boundary;
    1618:   }

    1620:   if (pcbddc->user_provided_isfordofs) {
    1621:     if (pcbddc->n_ISForDofs) {
    1622:       PetscInt i;

    1624:       PetscMalloc1(pcbddc->n_ISForDofs,&pcbddc->ISForDofsLocal);
    1625:       for (i=0;i<pcbddc->n_ISForDofs;i++) {
    1626:         PetscInt bs;

    1628:         PCBDDCGlobalToLocal(matis->rctx,global,local,pcbddc->ISForDofs[i],&pcbddc->ISForDofsLocal[i]);
    1629:         ISGetBlockSize(pcbddc->ISForDofs[i],&bs);
    1630:         ISSetBlockSize(pcbddc->ISForDofsLocal[i],bs);
    1631:         ISDestroy(&pcbddc->ISForDofs[i]);
    1632:       }
    1633:       pcbddc->n_ISForDofsLocal = pcbddc->n_ISForDofs;
    1634:       pcbddc->n_ISForDofs = 0;
    1635:       PetscFree(pcbddc->ISForDofs);
    1636:     }
    1637:   } else {
    1638:     if (!pcbddc->n_ISForDofsLocal) { /* field split not present */
    1639:       DM dm;

    1641:       MatGetDM(pc->pmat, &dm);
    1642:       if (!dm) {
    1643:         PCGetDM(pc, &dm);
    1644:       }
    1645:       if (dm) {
    1646:         IS      *fields;
    1647:         PetscInt nf,i;

    1649:         DMCreateFieldDecomposition(dm,&nf,NULL,&fields,NULL);
    1650:         PetscMalloc1(nf,&pcbddc->ISForDofsLocal);
    1651:         for (i=0;i<nf;i++) {
    1652:           PetscInt bs;

    1654:           PCBDDCGlobalToLocal(matis->rctx,global,local,fields[i],&pcbddc->ISForDofsLocal[i]);
    1655:           ISGetBlockSize(fields[i],&bs);
    1656:           ISSetBlockSize(pcbddc->ISForDofsLocal[i],bs);
    1657:           ISDestroy(&fields[i]);
    1658:         }
    1659:         PetscFree(fields);
    1660:         pcbddc->n_ISForDofsLocal = nf;
    1661:       } else { /* See if MATIS has fields attached by the conversion from MatNest */
    1662:         PetscContainer   c;

    1664:         PetscObjectQuery((PetscObject)pc->pmat,"_convert_nest_lfields",(PetscObject*)&c);
    1665:         if (c) {
    1666:           MatISLocalFields lf;
    1667:           PetscContainerGetPointer(c,(void**)&lf);
    1668:           PCBDDCSetDofsSplittingLocal(pc,lf->nr,lf->rf);
    1669:         } else { /* fallback, create the default fields if bs > 1 */
    1670:           PetscInt i, n = matis->A->rmap->n;
    1671:           MatGetBlockSize(pc->pmat,&i);
    1672:           if (i > 1) {
    1673:             pcbddc->n_ISForDofsLocal = i;
    1674:             PetscMalloc1(pcbddc->n_ISForDofsLocal,&pcbddc->ISForDofsLocal);
    1675:             for (i=0;i<pcbddc->n_ISForDofsLocal;i++) {
    1676:               ISCreateStride(PetscObjectComm((PetscObject)pc),n/pcbddc->n_ISForDofsLocal,i,pcbddc->n_ISForDofsLocal,&pcbddc->ISForDofsLocal[i]);
    1677:             }
    1678:           }
    1679:         }
    1680:       }
    1681:     } else {
    1682:       PetscInt i;
    1683:       for (i=0;i<pcbddc->n_ISForDofsLocal;i++) {
    1684:         PCBDDCConsistencyCheckIS(pc,MPI_LAND,&pcbddc->ISForDofsLocal[i]);
    1685:       }
    1686:     }
    1687:   }

    1689: boundary:
    1690:   if (!pcbddc->DirichletBoundariesLocal && pcbddc->DirichletBoundaries) {
    1691:     PCBDDCGlobalToLocal(matis->rctx,global,local,pcbddc->DirichletBoundaries,&pcbddc->DirichletBoundariesLocal);
    1692:   } else if (pcbddc->DirichletBoundariesLocal) {
    1693:     PCBDDCConsistencyCheckIS(pc,MPI_LAND,&pcbddc->DirichletBoundariesLocal);
    1694:   }
    1695:   if (!pcbddc->NeumannBoundariesLocal && pcbddc->NeumannBoundaries) {
    1696:     PCBDDCGlobalToLocal(matis->rctx,global,local,pcbddc->NeumannBoundaries,&pcbddc->NeumannBoundariesLocal);
    1697:   } else if (pcbddc->NeumannBoundariesLocal) {
    1698:     PCBDDCConsistencyCheckIS(pc,MPI_LOR,&pcbddc->NeumannBoundariesLocal);
    1699:   }
    1700:   if (!pcbddc->user_primal_vertices_local && pcbddc->user_primal_vertices) {
    1701:     PCBDDCGlobalToLocal(matis->rctx,global,local,pcbddc->user_primal_vertices,&pcbddc->user_primal_vertices_local);
    1702:   }
    1703:   VecDestroy(&global);
    1704:   VecDestroy(&local);
    1705:   /* detect local disconnected subdomains if requested (use matis->A) */
    1706:   if (pcbddc->detect_disconnected) {
    1707:     IS        primalv = NULL;
    1708:     PetscInt  i;
    1709:     PetscBool filter = pcbddc->detect_disconnected_filter;

    1711:     for (i=0;i<pcbddc->n_local_subs;i++) {
    1712:       ISDestroy(&pcbddc->local_subs[i]);
    1713:     }
    1714:     PetscFree(pcbddc->local_subs);
    1715:     PCBDDCDetectDisconnectedComponents(pc,filter,&pcbddc->n_local_subs,&pcbddc->local_subs,&primalv);
    1716:     PCBDDCAddPrimalVerticesLocalIS(pc,primalv);
    1717:     ISDestroy(&primalv);
    1718:   }
    1719:   /* early stage corner detection */
    1720:   {
    1721:     DM dm;

    1723:     MatGetDM(pc->pmat,&dm);
    1724:     if (!dm) {
    1725:       PCGetDM(pc,&dm);
    1726:     }
    1727:     if (dm) {
    1728:       PetscBool isda;

    1730:       PetscObjectTypeCompare((PetscObject)dm,DMDA,&isda);
    1731:       if (isda) {
    1732:         ISLocalToGlobalMapping l2l;
    1733:         IS                     corners;
    1734:         Mat                    lA;
    1735:         PetscBool              gl,lo;

    1737:         {
    1738:           Vec               cvec;
    1739:           const PetscScalar *coords;
    1740:           PetscInt          dof,n,cdim;
    1741:           PetscBool         memc = PETSC_TRUE;

    1743:           DMDAGetInfo(dm,NULL,NULL,NULL,NULL,NULL,NULL,NULL,&dof,NULL,NULL,NULL,NULL,NULL);
    1744:           DMGetCoordinates(dm,&cvec);
    1745:           VecGetLocalSize(cvec,&n);
    1746:           VecGetBlockSize(cvec,&cdim);
    1747:           n   /= cdim;
    1748:           PetscFree(pcbddc->mat_graph->coords);
    1749:           PetscMalloc1(dof*n*cdim,&pcbddc->mat_graph->coords);
    1750:           VecGetArrayRead(cvec,&coords);
    1751: #if defined(PETSC_USE_COMPLEX)
    1752:           memc = PETSC_FALSE;
    1753: #endif
    1754:           if (dof != 1) memc = PETSC_FALSE;
    1755:           if (memc) {
    1756:             PetscArraycpy(pcbddc->mat_graph->coords,coords,cdim*n*dof);
    1757:           } else { /* BDDC graph does not use any blocked information, we need to replicate the data */
    1758:             PetscReal *bcoords = pcbddc->mat_graph->coords;
    1759:             PetscInt  i, b, d;

    1761:             for (i=0;i<n;i++) {
    1762:               for (b=0;b<dof;b++) {
    1763:                 for (d=0;d<cdim;d++) {
    1764:                   bcoords[i*dof*cdim + b*cdim + d] = PetscRealPart(coords[i*cdim+d]);
    1765:                 }
    1766:               }
    1767:             }
    1768:           }
    1769:           VecRestoreArrayRead(cvec,&coords);
    1770:           pcbddc->mat_graph->cdim  = cdim;
    1771:           pcbddc->mat_graph->cnloc = dof*n;
    1772:           pcbddc->mat_graph->cloc  = PETSC_FALSE;
    1773:         }
    1774:         DMDAGetSubdomainCornersIS(dm,&corners);
    1775:         MatISGetLocalMat(pc->pmat,&lA);
    1776:         MatGetLocalToGlobalMapping(lA,&l2l,NULL);
    1777:         MatISRestoreLocalMat(pc->pmat,&lA);
    1778:         lo   = (PetscBool)(l2l && corners);
    1779:         MPIU_Allreduce(&lo,&gl,1,MPIU_BOOL,MPI_LAND,PetscObjectComm((PetscObject)pc));
    1780:         if (gl) { /* From PETSc's DMDA */
    1781:           const PetscInt    *idx;
    1782:           PetscInt          dof,bs,*idxout,n;

    1784:           DMDAGetInfo(dm,NULL,NULL,NULL,NULL,NULL,NULL,NULL,&dof,NULL,NULL,NULL,NULL,NULL);
    1785:           ISLocalToGlobalMappingGetBlockSize(l2l,&bs);
    1786:           ISGetLocalSize(corners,&n);
    1787:           ISGetIndices(corners,&idx);
    1788:           if (bs == dof) {
    1789:             PetscMalloc1(n,&idxout);
    1790:             ISLocalToGlobalMappingApplyBlock(l2l,n,idx,idxout);
    1791:           } else { /* the original DMDA local-to-local map have been modified */
    1792:             PetscInt i,d;

    1794:             PetscMalloc1(dof*n,&idxout);
    1795:             for (i=0;i<n;i++) for (d=0;d<dof;d++) idxout[dof*i+d] = dof*idx[i]+d;
    1796:             ISLocalToGlobalMappingApply(l2l,dof*n,idxout,idxout);

    1798:             bs = 1;
    1799:             n *= dof;
    1800:           }
    1801:           ISRestoreIndices(corners,&idx);
    1802:           DMDARestoreSubdomainCornersIS(dm,&corners);
    1803:           ISCreateBlock(PetscObjectComm((PetscObject)pc),bs,n,idxout,PETSC_OWN_POINTER,&corners);
    1804:           PCBDDCAddPrimalVerticesLocalIS(pc,corners);
    1805:           ISDestroy(&corners);
    1806:           pcbddc->corner_selected  = PETSC_TRUE;
    1807:           pcbddc->corner_selection = PETSC_TRUE;
    1808:         }
    1809:         if (corners) {
    1810:           DMDARestoreSubdomainCornersIS(dm,&corners);
    1811:         }
    1812:       }
    1813:     }
    1814:   }
    1815:   if (pcbddc->corner_selection && !pcbddc->mat_graph->cdim) {
    1816:     DM dm;

    1818:     MatGetDM(pc->pmat,&dm);
    1819:     if (!dm) {
    1820:       PCGetDM(pc,&dm);
    1821:     }
    1822:     if (dm) { /* this can get very expensive, I need to find a faster alternative */
    1823:       Vec            vcoords;
    1824:       PetscSection   section;
    1825:       PetscReal      *coords;
    1826:       PetscInt       d,cdim,nl,nf,**ctxs;
    1827:       PetscErrorCode (**funcs)(PetscInt, PetscReal, const PetscReal *, PetscInt, PetscScalar *, void *);

    1829:       DMGetCoordinateDim(dm,&cdim);
    1830:       DMGetLocalSection(dm,&section);
    1831:       PetscSectionGetNumFields(section,&nf);
    1832:       DMCreateGlobalVector(dm,&vcoords);
    1833:       VecGetLocalSize(vcoords,&nl);
    1834:       PetscMalloc1(nl*cdim,&coords);
    1835:       PetscMalloc2(nf,&funcs,nf,&ctxs);
    1836:       PetscMalloc1(nf,&ctxs[0]);
    1837:       for (d=0;d<nf;d++) funcs[d] = func_coords_private;
    1838:       for (d=1;d<nf;d++) ctxs[d] = ctxs[d-1] + 1;
    1839:       for (d=0;d<cdim;d++) {
    1840:         PetscInt          i;
    1841:         const PetscScalar *v;

    1843:         for (i=0;i<nf;i++) ctxs[i][0] = d;
    1844:         DMProjectFunction(dm,0.0,funcs,(void**)ctxs,INSERT_VALUES,vcoords);
    1845:         VecGetArrayRead(vcoords,&v);
    1846:         for (i=0;i<nl;i++) coords[i*cdim+d] = PetscRealPart(v[i]);
    1847:         VecRestoreArrayRead(vcoords,&v);
    1848:       }
    1849:       VecDestroy(&vcoords);
    1850:       PCSetCoordinates(pc,cdim,nl,coords);
    1851:       PetscFree(coords);
    1852:       PetscFree(ctxs[0]);
    1853:       PetscFree2(funcs,ctxs);
    1854:     }
    1855:   }
    1856:   return(0);
    1857: }

    1859: PetscErrorCode PCBDDCConsistencyCheckIS(PC pc, MPI_Op mop, IS *is)
    1860: {
    1861:   Mat_IS          *matis = (Mat_IS*)(pc->pmat->data);
    1862:   PetscErrorCode  ierr;
    1863:   IS              nis;
    1864:   const PetscInt  *idxs;
    1865:   PetscInt        i,nd,n = matis->A->rmap->n,*nidxs,nnd;
    1866:   PetscBool       *ld;

    1869:   if (mop != MPI_LAND && mop != MPI_LOR) SETERRQ(PetscObjectComm((PetscObject)(pc)),PETSC_ERR_SUP,"Supported are MPI_LAND and MPI_LOR");
    1870:   if (mop == MPI_LAND) {
    1871:     /* init rootdata with true */
    1872:     ld   = (PetscBool*) matis->sf_rootdata;
    1873:     for (i=0;i<pc->pmat->rmap->n;i++) ld[i] = PETSC_TRUE;
    1874:   } else {
    1875:     PetscArrayzero(matis->sf_rootdata,pc->pmat->rmap->n);
    1876:   }
    1877:   PetscArrayzero(matis->sf_leafdata,n);
    1878:   ISGetLocalSize(*is,&nd);
    1879:   ISGetIndices(*is,&idxs);
    1880:   ld   = (PetscBool*) matis->sf_leafdata;
    1881:   for (i=0;i<nd;i++)
    1882:     if (-1 < idxs[i] && idxs[i] < n)
    1883:       ld[idxs[i]] = PETSC_TRUE;
    1884:   ISRestoreIndices(*is,&idxs);
    1885:   PetscSFReduceBegin(matis->sf,MPIU_BOOL,matis->sf_leafdata,matis->sf_rootdata,mop);
    1886:   PetscSFReduceEnd(matis->sf,MPIU_BOOL,matis->sf_leafdata,matis->sf_rootdata,mop);
    1887:   PetscSFBcastBegin(matis->sf,MPIU_BOOL,matis->sf_rootdata,matis->sf_leafdata);
    1888:   PetscSFBcastEnd(matis->sf,MPIU_BOOL,matis->sf_rootdata,matis->sf_leafdata);
    1889:   if (mop == MPI_LAND) {
    1890:     PetscMalloc1(nd,&nidxs);
    1891:   } else {
    1892:     PetscMalloc1(n,&nidxs);
    1893:   }
    1894:   for (i=0,nnd=0;i<n;i++)
    1895:     if (ld[i])
    1896:       nidxs[nnd++] = i;
    1897:   ISCreateGeneral(PetscObjectComm((PetscObject)(*is)),nnd,nidxs,PETSC_OWN_POINTER,&nis);
    1898:   ISDestroy(is);
    1899:   *is  = nis;
    1900:   return(0);
    1901: }

    1903: PetscErrorCode PCBDDCBenignRemoveInterior(PC pc,Vec r,Vec z)
    1904: {
    1905:   PC_IS             *pcis = (PC_IS*)(pc->data);
    1906:   PC_BDDC           *pcbddc = (PC_BDDC*)(pc->data);
    1907:   PetscErrorCode    ierr;

    1910:   if (!pcbddc->benign_have_null) {
    1911:     return(0);
    1912:   }
    1913:   if (pcbddc->ChangeOfBasisMatrix) {
    1914:     Vec swap;

    1916:     MatMultTranspose(pcbddc->ChangeOfBasisMatrix,r,pcbddc->work_change);
    1917:     swap = pcbddc->work_change;
    1918:     pcbddc->work_change = r;
    1919:     r = swap;
    1920:   }
    1921:   VecScatterBegin(pcis->global_to_D,r,pcis->vec1_D,INSERT_VALUES,SCATTER_FORWARD);
    1922:   VecScatterEnd(pcis->global_to_D,r,pcis->vec1_D,INSERT_VALUES,SCATTER_FORWARD);
    1923:   KSPSolve(pcbddc->ksp_D,pcis->vec1_D,pcis->vec2_D);
    1924:   KSPCheckSolve(pcbddc->ksp_D,pc,pcis->vec2_D);
    1925:   VecSet(z,0.);
    1926:   VecScatterBegin(pcis->global_to_D,pcis->vec2_D,z,INSERT_VALUES,SCATTER_REVERSE);
    1927:   VecScatterEnd(pcis->global_to_D,pcis->vec2_D,z,INSERT_VALUES,SCATTER_REVERSE);
    1928:   if (pcbddc->ChangeOfBasisMatrix) {
    1929:     pcbddc->work_change = r;
    1930:     VecCopy(z,pcbddc->work_change);
    1931:     MatMult(pcbddc->ChangeOfBasisMatrix,pcbddc->work_change,z);
    1932:   }
    1933:   return(0);
    1934: }

    1936: PetscErrorCode PCBDDCBenignMatMult_Private_Private(Mat A, Vec x, Vec y, PetscBool transpose)
    1937: {
    1938:   PCBDDCBenignMatMult_ctx ctx;
    1939:   PetscErrorCode          ierr;
    1940:   PetscBool               apply_right,apply_left,reset_x;

    1943:   MatShellGetContext(A,&ctx);
    1944:   if (transpose) {
    1945:     apply_right = ctx->apply_left;
    1946:     apply_left = ctx->apply_right;
    1947:   } else {
    1948:     apply_right = ctx->apply_right;
    1949:     apply_left = ctx->apply_left;
    1950:   }
    1951:   reset_x = PETSC_FALSE;
    1952:   if (apply_right) {
    1953:     const PetscScalar *ax;
    1954:     PetscInt          nl,i;

    1956:     VecGetLocalSize(x,&nl);
    1957:     VecGetArrayRead(x,&ax);
    1958:     PetscArraycpy(ctx->work,ax,nl);
    1959:     VecRestoreArrayRead(x,&ax);
    1960:     for (i=0;i<ctx->benign_n;i++) {
    1961:       PetscScalar    sum,val;
    1962:       const PetscInt *idxs;
    1963:       PetscInt       nz,j;
    1964:       ISGetLocalSize(ctx->benign_zerodiag_subs[i],&nz);
    1965:       ISGetIndices(ctx->benign_zerodiag_subs[i],&idxs);
    1966:       sum = 0.;
    1967:       if (ctx->apply_p0) {
    1968:         val = ctx->work[idxs[nz-1]];
    1969:         for (j=0;j<nz-1;j++) {
    1970:           sum += ctx->work[idxs[j]];
    1971:           ctx->work[idxs[j]] += val;
    1972:         }
    1973:       } else {
    1974:         for (j=0;j<nz-1;j++) {
    1975:           sum += ctx->work[idxs[j]];
    1976:         }
    1977:       }
    1978:       ctx->work[idxs[nz-1]] -= sum;
    1979:       ISRestoreIndices(ctx->benign_zerodiag_subs[i],&idxs);
    1980:     }
    1981:     VecPlaceArray(x,ctx->work);
    1982:     reset_x = PETSC_TRUE;
    1983:   }
    1984:   if (transpose) {
    1985:     MatMultTranspose(ctx->A,x,y);
    1986:   } else {
    1987:     MatMult(ctx->A,x,y);
    1988:   }
    1989:   if (reset_x) {
    1990:     VecResetArray(x);
    1991:   }
    1992:   if (apply_left) {
    1993:     PetscScalar *ay;
    1994:     PetscInt    i;

    1996:     VecGetArray(y,&ay);
    1997:     for (i=0;i<ctx->benign_n;i++) {
    1998:       PetscScalar    sum,val;
    1999:       const PetscInt *idxs;
    2000:       PetscInt       nz,j;
    2001:       ISGetLocalSize(ctx->benign_zerodiag_subs[i],&nz);
    2002:       ISGetIndices(ctx->benign_zerodiag_subs[i],&idxs);
    2003:       val = -ay[idxs[nz-1]];
    2004:       if (ctx->apply_p0) {
    2005:         sum = 0.;
    2006:         for (j=0;j<nz-1;j++) {
    2007:           sum += ay[idxs[j]];
    2008:           ay[idxs[j]] += val;
    2009:         }
    2010:         ay[idxs[nz-1]] += sum;
    2011:       } else {
    2012:         for (j=0;j<nz-1;j++) {
    2013:           ay[idxs[j]] += val;
    2014:         }
    2015:         ay[idxs[nz-1]] = 0.;
    2016:       }
    2017:       ISRestoreIndices(ctx->benign_zerodiag_subs[i],&idxs);
    2018:     }
    2019:     VecRestoreArray(y,&ay);
    2020:   }
    2021:   return(0);
    2022: }

    2024: PetscErrorCode PCBDDCBenignMatMultTranspose_Private(Mat A, Vec x, Vec y)
    2025: {

    2029:   PCBDDCBenignMatMult_Private_Private(A,x,y,PETSC_TRUE);
    2030:   return(0);
    2031: }

    2033: PetscErrorCode PCBDDCBenignMatMult_Private(Mat A, Vec x, Vec y)
    2034: {

    2038:   PCBDDCBenignMatMult_Private_Private(A,x,y,PETSC_FALSE);
    2039:   return(0);
    2040: }

    2042: PetscErrorCode PCBDDCBenignShellMat(PC pc, PetscBool restore)
    2043: {
    2044:   PC_IS                   *pcis = (PC_IS*)pc->data;
    2045:   PC_BDDC                 *pcbddc = (PC_BDDC*)pc->data;
    2046:   PCBDDCBenignMatMult_ctx ctx;
    2047:   PetscErrorCode          ierr;

    2050:   if (!restore) {
    2051:     Mat                A_IB,A_BI;
    2052:     PetscScalar        *work;
    2053:     PCBDDCReuseSolvers reuse = pcbddc->sub_schurs ? pcbddc->sub_schurs->reuse_solver : NULL;

    2055:     if (pcbddc->benign_original_mat) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_PLIB,"Benign original mat has not been restored");
    2056:     if (!pcbddc->benign_change || !pcbddc->benign_n || pcbddc->benign_change_explicit) return(0);
    2057:     PetscMalloc1(pcis->n,&work);
    2058:     MatCreate(PETSC_COMM_SELF,&A_IB);
    2059:     MatSetSizes(A_IB,pcis->n-pcis->n_B,pcis->n_B,PETSC_DECIDE,PETSC_DECIDE);
    2060:     MatSetType(A_IB,MATSHELL);
    2061:     MatShellSetOperation(A_IB,MATOP_MULT,(void (*)(void))PCBDDCBenignMatMult_Private);
    2062:     MatShellSetOperation(A_IB,MATOP_MULT_TRANSPOSE,(void (*)(void))PCBDDCBenignMatMultTranspose_Private);
    2063:     PetscNew(&ctx);
    2064:     MatShellSetContext(A_IB,ctx);
    2065:     ctx->apply_left = PETSC_TRUE;
    2066:     ctx->apply_right = PETSC_FALSE;
    2067:     ctx->apply_p0 = PETSC_FALSE;
    2068:     ctx->benign_n = pcbddc->benign_n;
    2069:     if (reuse) {
    2070:       ctx->benign_zerodiag_subs = reuse->benign_zerodiag_subs;
    2071:       ctx->free = PETSC_FALSE;
    2072:     } else { /* TODO: could be optimized for successive solves */
    2073:       ISLocalToGlobalMapping N_to_D;
    2074:       PetscInt               i;

    2076:       ISLocalToGlobalMappingCreateIS(pcis->is_I_local,&N_to_D);
    2077:       PetscMalloc1(pcbddc->benign_n,&ctx->benign_zerodiag_subs);
    2078:       for (i=0;i<pcbddc->benign_n;i++) {
    2079:         ISGlobalToLocalMappingApplyIS(N_to_D,IS_GTOLM_DROP,pcbddc->benign_zerodiag_subs[i],&ctx->benign_zerodiag_subs[i]);
    2080:       }
    2081:       ISLocalToGlobalMappingDestroy(&N_to_D);
    2082:       ctx->free = PETSC_TRUE;
    2083:     }
    2084:     ctx->A = pcis->A_IB;
    2085:     ctx->work = work;
    2086:     MatSetUp(A_IB);
    2087:     MatAssemblyBegin(A_IB,MAT_FINAL_ASSEMBLY);
    2088:     MatAssemblyEnd(A_IB,MAT_FINAL_ASSEMBLY);
    2089:     pcis->A_IB = A_IB;

    2091:     /* A_BI as A_IB^T */
    2092:     MatCreateTranspose(A_IB,&A_BI);
    2093:     pcbddc->benign_original_mat = pcis->A_BI;
    2094:     pcis->A_BI = A_BI;
    2095:   } else {
    2096:     if (!pcbddc->benign_original_mat) {
    2097:       return(0);
    2098:     }
    2099:     MatShellGetContext(pcis->A_IB,&ctx);
    2100:     MatDestroy(&pcis->A_IB);
    2101:     pcis->A_IB = ctx->A;
    2102:     ctx->A = NULL;
    2103:     MatDestroy(&pcis->A_BI);
    2104:     pcis->A_BI = pcbddc->benign_original_mat;
    2105:     pcbddc->benign_original_mat = NULL;
    2106:     if (ctx->free) {
    2107:       PetscInt i;
    2108:       for (i=0;i<ctx->benign_n;i++) {
    2109:         ISDestroy(&ctx->benign_zerodiag_subs[i]);
    2110:       }
    2111:       PetscFree(ctx->benign_zerodiag_subs);
    2112:     }
    2113:     PetscFree(ctx->work);
    2114:     PetscFree(ctx);
    2115:   }
    2116:   return(0);
    2117: }

    2119: /* used just in bddc debug mode */
    2120: PetscErrorCode PCBDDCBenignProject(PC pc, IS is1, IS is2, Mat *B)
    2121: {
    2122:   PC_BDDC        *pcbddc = (PC_BDDC*)pc->data;
    2123:   Mat_IS         *matis = (Mat_IS*)pc->pmat->data;
    2124:   Mat            An;

    2128:   MatPtAP(matis->A,pcbddc->benign_change,MAT_INITIAL_MATRIX,2.0,&An);
    2129:   MatZeroRowsColumns(An,pcbddc->benign_n,pcbddc->benign_p0_lidx,1.0,NULL,NULL);
    2130:   if (is1) {
    2131:     MatCreateSubMatrix(An,is1,is2,MAT_INITIAL_MATRIX,B);
    2132:     MatDestroy(&An);
    2133:   } else {
    2134:     *B = An;
    2135:   }
    2136:   return(0);
    2137: }

    2139: /* TODO: add reuse flag */
    2140: PetscErrorCode MatSeqAIJCompress(Mat A, Mat *B)
    2141: {
    2142:   Mat            Bt;
    2143:   PetscScalar    *a,*bdata;
    2144:   const PetscInt *ii,*ij;
    2145:   PetscInt       m,n,i,nnz,*bii,*bij;
    2146:   PetscBool      flg_row;

    2150:   MatGetSize(A,&n,&m);
    2151:   MatGetRowIJ(A,0,PETSC_FALSE,PETSC_FALSE,&n,&ii,&ij,&flg_row);
    2152:   MatSeqAIJGetArray(A,&a);
    2153:   nnz = n;
    2154:   for (i=0;i<ii[n];i++) {
    2155:     if (PetscLikely(PetscAbsScalar(a[i]) > PETSC_SMALL)) nnz++;
    2156:   }
    2157:   PetscMalloc1(n+1,&bii);
    2158:   PetscMalloc1(nnz,&bij);
    2159:   PetscMalloc1(nnz,&bdata);
    2160:   nnz = 0;
    2161:   bii[0] = 0;
    2162:   for (i=0;i<n;i++) {
    2163:     PetscInt j;
    2164:     for (j=ii[i];j<ii[i+1];j++) {
    2165:       PetscScalar entry = a[j];
    2166:       if (PetscLikely(PetscAbsScalar(entry) > PETSC_SMALL) || (n == m && ij[j] == i)) {
    2167:         bij[nnz] = ij[j];
    2168:         bdata[nnz] = entry;
    2169:         nnz++;
    2170:       }
    2171:     }
    2172:     bii[i+1] = nnz;
    2173:   }
    2174:   MatSeqAIJRestoreArray(A,&a);
    2175:   MatCreateSeqAIJWithArrays(PetscObjectComm((PetscObject)A),n,m,bii,bij,bdata,&Bt);
    2176:   MatRestoreRowIJ(A,0,PETSC_FALSE,PETSC_FALSE,&n,&ii,&ij,&flg_row);
    2177:   {
    2178:     Mat_SeqAIJ *b = (Mat_SeqAIJ*)(Bt->data);
    2179:     b->free_a = PETSC_TRUE;
    2180:     b->free_ij = PETSC_TRUE;
    2181:   }
    2182:   if (*B == A) {
    2183:     MatDestroy(&A);
    2184:   }
    2185:   *B = Bt;
    2186:   return(0);
    2187: }

    2189: PetscErrorCode PCBDDCDetectDisconnectedComponents(PC pc, PetscBool filter, PetscInt *ncc, IS* cc[], IS* primalv)
    2190: {
    2191:   Mat                    B = NULL;
    2192:   DM                     dm;
    2193:   IS                     is_dummy,*cc_n;
    2194:   ISLocalToGlobalMapping l2gmap_dummy;
    2195:   PCBDDCGraph            graph;
    2196:   PetscInt               *xadj_filtered = NULL,*adjncy_filtered = NULL;
    2197:   PetscInt               i,n;
    2198:   PetscInt               *xadj,*adjncy;
    2199:   PetscBool              isplex = PETSC_FALSE;
    2200:   PetscErrorCode         ierr;

    2203:   if (ncc) *ncc = 0;
    2204:   if (cc) *cc = NULL;
    2205:   if (primalv) *primalv = NULL;
    2206:   PCBDDCGraphCreate(&graph);
    2207:   MatGetDM(pc->pmat,&dm);
    2208:   if (!dm) {
    2209:     PCGetDM(pc,&dm);
    2210:   }
    2211:   if (dm) {
    2212:     PetscObjectTypeCompare((PetscObject)dm,DMPLEX,&isplex);
    2213:   }
    2214:   if (filter) isplex = PETSC_FALSE;

    2216:   if (isplex) { /* this code has been modified from plexpartition.c */
    2217:     PetscInt       p, pStart, pEnd, a, adjSize, idx, size, nroots;
    2218:     PetscInt      *adj = NULL;
    2219:     IS             cellNumbering;
    2220:     const PetscInt *cellNum;
    2221:     PetscBool      useCone, useClosure;
    2222:     PetscSection   section;
    2223:     PetscSegBuffer adjBuffer;
    2224:     PetscSF        sfPoint;

    2228:     DMPlexGetHeightStratum(dm, 0, &pStart, &pEnd);
    2229:     DMGetPointSF(dm, &sfPoint);
    2230:     PetscSFGetGraph(sfPoint, &nroots, NULL, NULL, NULL);
    2231:     /* Build adjacency graph via a section/segbuffer */
    2232:     PetscSectionCreate(PetscObjectComm((PetscObject) dm), &section);
    2233:     PetscSectionSetChart(section, pStart, pEnd);
    2234:     PetscSegBufferCreate(sizeof(PetscInt),1000,&adjBuffer);
    2235:     /* Always use FVM adjacency to create partitioner graph */
    2236:     DMGetBasicAdjacency(dm, &useCone, &useClosure);
    2237:     DMSetBasicAdjacency(dm, PETSC_TRUE, PETSC_FALSE);
    2238:     DMPlexGetCellNumbering(dm, &cellNumbering);
    2239:     ISGetIndices(cellNumbering, &cellNum);
    2240:     for (n = 0, p = pStart; p < pEnd; p++) {
    2241:       /* Skip non-owned cells in parallel (ParMetis expects no overlap) */
    2242:       if (nroots > 0) {if (cellNum[p] < 0) continue;}
    2243:       adjSize = PETSC_DETERMINE;
    2244:       DMPlexGetAdjacency(dm, p, &adjSize, &adj);
    2245:       for (a = 0; a < adjSize; ++a) {
    2246:         const PetscInt point = adj[a];
    2247:         if (pStart <= point && point < pEnd) {
    2248:           PetscInt *PETSC_RESTRICT pBuf;
    2249:           PetscSectionAddDof(section, p, 1);
    2250:           PetscSegBufferGetInts(adjBuffer, 1, &pBuf);
    2251:           *pBuf = point;
    2252:         }
    2253:       }
    2254:       n++;
    2255:     }
    2256:     DMSetBasicAdjacency(dm, useCone, useClosure);
    2257:     /* Derive CSR graph from section/segbuffer */
    2258:     PetscSectionSetUp(section);
    2259:     PetscSectionGetStorageSize(section, &size);
    2260:     PetscMalloc1(n+1, &xadj);
    2261:     for (idx = 0, p = pStart; p < pEnd; p++) {
    2262:       if (nroots > 0) {if (cellNum[p] < 0) continue;}
    2263:       PetscSectionGetOffset(section, p, &(xadj[idx++]));
    2264:     }
    2265:     xadj[n] = size;
    2266:     PetscSegBufferExtractAlloc(adjBuffer, &adjncy);
    2267:     /* Clean up */
    2268:     PetscSegBufferDestroy(&adjBuffer);
    2269:     PetscSectionDestroy(&section);
    2270:     PetscFree(adj);
    2271:     graph->xadj = xadj;
    2272:     graph->adjncy = adjncy;
    2273:   } else {
    2274:     Mat       A;
    2275:     PetscBool isseqaij, flg_row;

    2277:     MatISGetLocalMat(pc->pmat,&A);
    2278:     if (!A->rmap->N || !A->cmap->N) {
    2279:       PCBDDCGraphDestroy(&graph);
    2280:       return(0);
    2281:     }
    2282:     PetscObjectBaseTypeCompare((PetscObject)A,MATSEQAIJ,&isseqaij);
    2283:     if (!isseqaij && filter) {
    2284:       PetscBool isseqdense;

    2286:       PetscObjectTypeCompare((PetscObject)A,MATSEQDENSE,&isseqdense);
    2287:       if (!isseqdense) {
    2288:         MatConvert(A,MATSEQAIJ,MAT_INITIAL_MATRIX,&B);
    2289:       } else { /* TODO: rectangular case and LDA */
    2290:         PetscScalar *array;
    2291:         PetscReal   chop=1.e-6;

    2293:         MatDuplicate(A,MAT_COPY_VALUES,&B);
    2294:         MatDenseGetArray(B,&array);
    2295:         MatGetSize(B,&n,NULL);
    2296:         for (i=0;i<n;i++) {
    2297:           PetscInt j;
    2298:           for (j=i+1;j<n;j++) {
    2299:             PetscReal thresh = chop*(PetscAbsScalar(array[i*(n+1)])+PetscAbsScalar(array[j*(n+1)]));
    2300:             if (PetscAbsScalar(array[i*n+j]) < thresh) array[i*n+j] = 0.;
    2301:             if (PetscAbsScalar(array[j*n+i]) < thresh) array[j*n+i] = 0.;
    2302:           }
    2303:         }
    2304:         MatDenseRestoreArray(B,&array);
    2305:         MatConvert(B,MATSEQAIJ,MAT_INPLACE_MATRIX,&B);
    2306:       }
    2307:     } else {
    2308:       PetscObjectReference((PetscObject)A);
    2309:       B = A;
    2310:     }
    2311:     MatGetRowIJ(B,0,PETSC_TRUE,PETSC_FALSE,&n,(const PetscInt**)&xadj,(const PetscInt**)&adjncy,&flg_row);

    2313:     /* if filter is true, then removes entries lower than PETSC_SMALL in magnitude */
    2314:     if (filter) {
    2315:       PetscScalar *data;
    2316:       PetscInt    j,cum;

    2318:       PetscCalloc2(n+1,&xadj_filtered,xadj[n],&adjncy_filtered);
    2319:       MatSeqAIJGetArray(B,&data);
    2320:       cum = 0;
    2321:       for (i=0;i<n;i++) {
    2322:         PetscInt t;

    2324:         for (j=xadj[i];j<xadj[i+1];j++) {
    2325:           if (PetscUnlikely(PetscAbsScalar(data[j]) < PETSC_SMALL)) {
    2326:             continue;
    2327:           }
    2328:           adjncy_filtered[cum+xadj_filtered[i]++] = adjncy[j];
    2329:         }
    2330:         t = xadj_filtered[i];
    2331:         xadj_filtered[i] = cum;
    2332:         cum += t;
    2333:       }
    2334:       MatSeqAIJRestoreArray(B,&data);
    2335:       graph->xadj = xadj_filtered;
    2336:       graph->adjncy = adjncy_filtered;
    2337:     } else {
    2338:       graph->xadj = xadj;
    2339:       graph->adjncy = adjncy;
    2340:     }
    2341:   }
    2342:   /* compute local connected components using PCBDDCGraph */
    2343:   ISCreateStride(PETSC_COMM_SELF,n,0,1,&is_dummy);
    2344:   ISLocalToGlobalMappingCreateIS(is_dummy,&l2gmap_dummy);
    2345:   ISDestroy(&is_dummy);
    2346:   PCBDDCGraphInit(graph,l2gmap_dummy,n,PETSC_MAX_INT);
    2347:   ISLocalToGlobalMappingDestroy(&l2gmap_dummy);
    2348:   PCBDDCGraphSetUp(graph,1,NULL,NULL,0,NULL,NULL);
    2349:   PCBDDCGraphComputeConnectedComponents(graph);

    2351:   /* partial clean up */
    2352:   PetscFree2(xadj_filtered,adjncy_filtered);
    2353:   if (B) {
    2354:     PetscBool flg_row;
    2355:     MatRestoreRowIJ(B,0,PETSC_TRUE,PETSC_FALSE,&n,(const PetscInt**)&xadj,(const PetscInt**)&adjncy,&flg_row);
    2356:     MatDestroy(&B);
    2357:   }
    2358:   if (isplex) {
    2359:     PetscFree(xadj);
    2360:     PetscFree(adjncy);
    2361:   }

    2363:   /* get back data */
    2364:   if (isplex) {
    2365:     if (ncc) *ncc = graph->ncc;
    2366:     if (cc || primalv) {
    2367:       Mat          A;
    2368:       PetscBT      btv,btvt;
    2369:       PetscSection subSection;
    2370:       PetscInt     *ids,cum,cump,*cids,*pids;

    2372:       DMPlexGetSubdomainSection(dm,&subSection);
    2373:       MatISGetLocalMat(pc->pmat,&A);
    2374:       PetscMalloc3(A->rmap->n,&ids,graph->ncc+1,&cids,A->rmap->n,&pids);
    2375:       PetscBTCreate(A->rmap->n,&btv);
    2376:       PetscBTCreate(A->rmap->n,&btvt);

    2378:       cids[0] = 0;
    2379:       for (i = 0, cump = 0, cum = 0; i < graph->ncc; i++) {
    2380:         PetscInt j;

    2382:         PetscBTMemzero(A->rmap->n,btvt);
    2383:         for (j = graph->cptr[i]; j < graph->cptr[i+1]; j++) {
    2384:           PetscInt k, size, *closure = NULL, cell = graph->queue[j];

    2386:           DMPlexGetTransitiveClosure(dm,cell,PETSC_TRUE,&size,&closure);
    2387:           for (k = 0; k < 2*size; k += 2) {
    2388:             PetscInt s, pp, p = closure[k], off, dof, cdof;

    2390:             PetscSectionGetConstraintDof(subSection,p,&cdof);
    2391:             PetscSectionGetOffset(subSection,p,&off);
    2392:             PetscSectionGetDof(subSection,p,&dof);
    2393:             for (s = 0; s < dof-cdof; s++) {
    2394:               if (PetscBTLookupSet(btvt,off+s)) continue;
    2395:               if (!PetscBTLookup(btv,off+s)) {
    2396:                 ids[cum++] = off+s;
    2397:               } else { /* cross-vertex */
    2398:                 pids[cump++] = off+s;
    2399:               }
    2400:             }
    2401:             DMPlexGetTreeParent(dm,p,&pp,NULL);
    2402:             if (pp != p) {
    2403:               PetscSectionGetConstraintDof(subSection,pp,&cdof);
    2404:               PetscSectionGetOffset(subSection,pp,&off);
    2405:               PetscSectionGetDof(subSection,pp,&dof);
    2406:               for (s = 0; s < dof-cdof; s++) {
    2407:                 if (PetscBTLookupSet(btvt,off+s)) continue;
    2408:                 if (!PetscBTLookup(btv,off+s)) {
    2409:                   ids[cum++] = off+s;
    2410:                 } else { /* cross-vertex */
    2411:                   pids[cump++] = off+s;
    2412:                 }
    2413:               }
    2414:             }
    2415:           }
    2416:           DMPlexRestoreTransitiveClosure(dm,cell,PETSC_TRUE,&size,&closure);
    2417:         }
    2418:         cids[i+1] = cum;
    2419:         /* mark dofs as already assigned */
    2420:         for (j = cids[i]; j < cids[i+1]; j++) {
    2421:           PetscBTSet(btv,ids[j]);
    2422:         }
    2423:       }
    2424:       if (cc) {
    2425:         PetscMalloc1(graph->ncc,&cc_n);
    2426:         for (i = 0; i < graph->ncc; i++) {
    2427:           ISCreateGeneral(PETSC_COMM_SELF,cids[i+1]-cids[i],ids+cids[i],PETSC_COPY_VALUES,&cc_n[i]);
    2428:         }
    2429:         *cc = cc_n;
    2430:       }
    2431:       if (primalv) {
    2432:         ISCreateGeneral(PetscObjectComm((PetscObject)pc),cump,pids,PETSC_COPY_VALUES,primalv);
    2433:       }
    2434:       PetscFree3(ids,cids,pids);
    2435:       PetscBTDestroy(&btv);
    2436:       PetscBTDestroy(&btvt);
    2437:     }
    2438:   } else {
    2439:     if (ncc) *ncc = graph->ncc;
    2440:     if (cc) {
    2441:       PetscMalloc1(graph->ncc,&cc_n);
    2442:       for (i=0;i<graph->ncc;i++) {
    2443:         ISCreateGeneral(PETSC_COMM_SELF,graph->cptr[i+1]-graph->cptr[i],graph->queue+graph->cptr[i],PETSC_COPY_VALUES,&cc_n[i]);
    2444:       }
    2445:       *cc = cc_n;
    2446:     }
    2447:   }
    2448:   /* clean up graph */
    2449:   graph->xadj = 0;
    2450:   graph->adjncy = 0;
    2451:   PCBDDCGraphDestroy(&graph);
    2452:   return(0);
    2453: }

    2455: PetscErrorCode PCBDDCBenignCheck(PC pc, IS zerodiag)
    2456: {
    2457:   PC_BDDC*       pcbddc = (PC_BDDC*)pc->data;
    2458:   PC_IS*         pcis = (PC_IS*)(pc->data);
    2459:   IS             dirIS = NULL;
    2460:   PetscInt       i;

    2464:   PCBDDCGraphGetDirichletDofs(pcbddc->mat_graph,&dirIS);
    2465:   if (zerodiag) {
    2466:     Mat            A;
    2467:     Vec            vec3_N;
    2468:     PetscScalar    *vals;
    2469:     const PetscInt *idxs;
    2470:     PetscInt       nz,*count;

    2472:     /* p0 */
    2473:     VecSet(pcis->vec1_N,0.);
    2474:     PetscMalloc1(pcis->n,&vals);
    2475:     ISGetLocalSize(zerodiag,&nz);
    2476:     ISGetIndices(zerodiag,&idxs);
    2477:     for (i=0;i<nz;i++) vals[i] = 1.;
    2478:     VecSetValues(pcis->vec1_N,nz,idxs,vals,INSERT_VALUES);
    2479:     VecAssemblyBegin(pcis->vec1_N);
    2480:     VecAssemblyEnd(pcis->vec1_N);
    2481:     /* v_I */
    2482:     VecSetRandom(pcis->vec2_N,NULL);
    2483:     for (i=0;i<nz;i++) vals[i] = 0.;
    2484:     VecSetValues(pcis->vec2_N,nz,idxs,vals,INSERT_VALUES);
    2485:     ISRestoreIndices(zerodiag,&idxs);
    2486:     ISGetIndices(pcis->is_B_local,&idxs);
    2487:     for (i=0;i<pcis->n_B;i++) vals[i] = 0.;
    2488:     VecSetValues(pcis->vec2_N,pcis->n_B,idxs,vals,INSERT_VALUES);
    2489:     ISRestoreIndices(pcis->is_B_local,&idxs);
    2490:     if (dirIS) {
    2491:       PetscInt n;

    2493:       ISGetLocalSize(dirIS,&n);
    2494:       ISGetIndices(dirIS,&idxs);
    2495:       for (i=0;i<n;i++) vals[i] = 0.;
    2496:       VecSetValues(pcis->vec2_N,n,idxs,vals,INSERT_VALUES);
    2497:       ISRestoreIndices(dirIS,&idxs);
    2498:     }
    2499:     VecAssemblyBegin(pcis->vec2_N);
    2500:     VecAssemblyEnd(pcis->vec2_N);
    2501:     VecDuplicate(pcis->vec1_N,&vec3_N);
    2502:     VecSet(vec3_N,0.);
    2503:     MatISGetLocalMat(pc->pmat,&A);
    2504:     MatMult(A,pcis->vec1_N,vec3_N);
    2505:     VecDot(vec3_N,pcis->vec2_N,&vals[0]);
    2506:     if (PetscAbsScalar(vals[0]) > 1.e-1) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Benign trick can not be applied! b(v_I,p_0) = %1.6e (should be numerically 0.)",PetscAbsScalar(vals[0]));
    2507:     PetscFree(vals);
    2508:     VecDestroy(&vec3_N);

    2510:     /* there should not be any pressure dofs lying on the interface */
    2511:     PetscCalloc1(pcis->n,&count);
    2512:     ISGetIndices(pcis->is_B_local,&idxs);
    2513:     for (i=0;i<pcis->n_B;i++) count[idxs[i]]++;
    2514:     ISRestoreIndices(pcis->is_B_local,&idxs);
    2515:     ISGetIndices(zerodiag,&idxs);
    2516:     for (i=0;i<nz;i++) if (count[idxs[i]]) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Benign trick can not be applied! pressure dof %D is an interface dof",idxs[i]);
    2517:     ISRestoreIndices(zerodiag,&idxs);
    2518:     PetscFree(count);
    2519:   }
    2520:   ISDestroy(&dirIS);

    2522:   /* check PCBDDCBenignGetOrSetP0 */
    2523:   VecSetRandom(pcis->vec1_global,NULL);
    2524:   for (i=0;i<pcbddc->benign_n;i++) pcbddc->benign_p0[i] = -PetscGlobalRank-i;
    2525:   PCBDDCBenignGetOrSetP0(pc,pcis->vec1_global,PETSC_FALSE);
    2526:   for (i=0;i<pcbddc->benign_n;i++) pcbddc->benign_p0[i] = 1;
    2527:   PCBDDCBenignGetOrSetP0(pc,pcis->vec1_global,PETSC_TRUE);
    2528:   for (i=0;i<pcbddc->benign_n;i++) {
    2529:     PetscInt val = PetscRealPart(pcbddc->benign_p0[i]);
    2530:     if (val != -PetscGlobalRank-i) SETERRQ3(PETSC_COMM_SELF,PETSC_ERR_PLIB,"Error testing PCBDDCBenignGetOrSetP0! Found %g at %D instead of %g",PetscRealPart(pcbddc->benign_p0[i]),i,-PetscGlobalRank-i);
    2531:   }
    2532:   return(0);
    2533: }

    2535: PetscErrorCode PCBDDCBenignDetectSaddlePoint(PC pc, PetscBool reuse, IS *zerodiaglocal)
    2536: {
    2537:   PC_BDDC*       pcbddc = (PC_BDDC*)pc->data;
    2538:   IS             pressures = NULL,zerodiag = NULL,*bzerodiag = NULL,zerodiag_save,*zerodiag_subs;
    2539:   PetscInt       nz,n,benign_n,bsp = 1;
    2540:   PetscInt       *interior_dofs,n_interior_dofs,nneu;
    2541:   PetscBool      sorted,have_null,has_null_pressures,recompute_zerodiag,checkb;

    2545:   if (reuse) goto project_b0;
    2546:   PetscSFDestroy(&pcbddc->benign_sf);
    2547:   MatDestroy(&pcbddc->benign_B0);
    2548:   for (n=0;n<pcbddc->benign_n;n++) {
    2549:     ISDestroy(&pcbddc->benign_zerodiag_subs[n]);
    2550:   }
    2551:   PetscFree(pcbddc->benign_zerodiag_subs);
    2552:   has_null_pressures = PETSC_TRUE;
    2553:   have_null = PETSC_TRUE;
    2554:   /* if a local information on dofs is present, gets pressure dofs from command line (uses the last field is not provided)
    2555:      Without local information, it uses only the zerodiagonal dofs (ok if the pressure block is all zero and it is a scalar field)
    2556:      Checks if all the pressure dofs in each subdomain have a zero diagonal
    2557:      If not, a change of basis on pressures is not needed
    2558:      since the local Schur complements are already SPD
    2559:   */
    2560:   if (pcbddc->n_ISForDofsLocal) {
    2561:     IS        iP = NULL;
    2562:     PetscInt  p,*pp;
    2563:     PetscBool flg;

    2565:     PetscMalloc1(pcbddc->n_ISForDofsLocal,&pp);
    2566:     n    = pcbddc->n_ISForDofsLocal;
    2567:     PetscOptionsBegin(PetscObjectComm((PetscObject)pc),((PetscObject)pc)->prefix,"BDDC benign options","PC");
    2568:     PetscOptionsIntArray("-pc_bddc_pressure_field","Field id for pressures",NULL,pp,&n,&flg);
    2569:     PetscOptionsEnd();
    2570:     if (!flg) {
    2571:       n = 1;
    2572:       pp[0] = pcbddc->n_ISForDofsLocal-1;
    2573:     }

    2575:     bsp = 0;
    2576:     for (p=0;p<n;p++) {
    2577:       PetscInt bs;

    2579:       if (pp[p] < 0 || pp[p] > pcbddc->n_ISForDofsLocal-1) SETERRQ1(PetscObjectComm((PetscObject)pc),PETSC_ERR_USER,"Invalid field id for pressures %D",pp[p]);
    2580:       ISGetBlockSize(pcbddc->ISForDofsLocal[pp[p]],&bs);
    2581:       bsp += bs;
    2582:     }
    2583:     PetscMalloc1(bsp,&bzerodiag);
    2584:     bsp  = 0;
    2585:     for (p=0;p<n;p++) {
    2586:       const PetscInt *idxs;
    2587:       PetscInt       b,bs,npl,*bidxs;

    2589:       ISGetBlockSize(pcbddc->ISForDofsLocal[pp[p]],&bs);
    2590:       ISGetLocalSize(pcbddc->ISForDofsLocal[pp[p]],&npl);
    2591:       ISGetIndices(pcbddc->ISForDofsLocal[pp[p]],&idxs);
    2592:       PetscMalloc1(npl/bs,&bidxs);
    2593:       for (b=0;b<bs;b++) {
    2594:         PetscInt i;

    2596:         for (i=0;i<npl/bs;i++) bidxs[i] = idxs[bs*i+b];
    2597:         ISCreateGeneral(PETSC_COMM_SELF,npl/bs,bidxs,PETSC_COPY_VALUES,&bzerodiag[bsp]);
    2598:         bsp++;
    2599:       }
    2600:       PetscFree(bidxs);
    2601:       ISRestoreIndices(pcbddc->ISForDofsLocal[pp[p]],&idxs);
    2602:     }
    2603:     ISConcatenate(PETSC_COMM_SELF,bsp,bzerodiag,&pressures);

    2605:     /* remove zeroed out pressures if we are setting up a BDDC solver for a saddle-point FETI-DP */
    2606:     PetscObjectQuery((PetscObject)pc,"__KSPFETIDP_lP",(PetscObject*)&iP);
    2607:     if (iP) {
    2608:       IS newpressures;

    2610:       ISDifference(pressures,iP,&newpressures);
    2611:       ISDestroy(&pressures);
    2612:       pressures = newpressures;
    2613:     }
    2614:     ISSorted(pressures,&sorted);
    2615:     if (!sorted) {
    2616:       ISSort(pressures);
    2617:     }
    2618:     PetscFree(pp);
    2619:   }

    2621:   /* pcis has not been setup yet, so get the local size from the subdomain matrix */
    2622:   MatGetLocalSize(pcbddc->local_mat,&n,NULL);
    2623:   if (!n) pcbddc->benign_change_explicit = PETSC_TRUE;
    2624:   MatFindZeroDiagonals(pcbddc->local_mat,&zerodiag);
    2625:   ISSorted(zerodiag,&sorted);
    2626:   if (!sorted) {
    2627:     ISSort(zerodiag);
    2628:   }
    2629:   PetscObjectReference((PetscObject)zerodiag);
    2630:   zerodiag_save = zerodiag;
    2631:   ISGetLocalSize(zerodiag,&nz);
    2632:   if (!nz) {
    2633:     if (n) have_null = PETSC_FALSE;
    2634:     has_null_pressures = PETSC_FALSE;
    2635:     ISDestroy(&zerodiag);
    2636:   }
    2637:   recompute_zerodiag = PETSC_FALSE;

    2639:   /* in case disconnected subdomains info is present, split the pressures accordingly (otherwise the benign trick could fail) */
    2640:   zerodiag_subs    = NULL;
    2641:   benign_n         = 0;
    2642:   n_interior_dofs  = 0;
    2643:   interior_dofs    = NULL;
    2644:   nneu             = 0;
    2645:   if (pcbddc->NeumannBoundariesLocal) {
    2646:     ISGetLocalSize(pcbddc->NeumannBoundariesLocal,&nneu);
    2647:   }
    2648:   checkb = (PetscBool)(!pcbddc->NeumannBoundariesLocal || pcbddc->current_level);
    2649:   if (checkb) { /* need to compute interior nodes */
    2650:     PetscInt n,i,j;
    2651:     PetscInt n_neigh,*neigh,*n_shared,**shared;
    2652:     PetscInt *iwork;

    2654:     ISLocalToGlobalMappingGetSize(pc->pmat->rmap->mapping,&n);
    2655:     ISLocalToGlobalMappingGetInfo(pc->pmat->rmap->mapping,&n_neigh,&neigh,&n_shared,&shared);
    2656:     PetscCalloc1(n,&iwork);
    2657:     PetscMalloc1(n,&interior_dofs);
    2658:     for (i=1;i<n_neigh;i++)
    2659:       for (j=0;j<n_shared[i];j++)
    2660:           iwork[shared[i][j]] += 1;
    2661:     for (i=0;i<n;i++)
    2662:       if (!iwork[i])
    2663:         interior_dofs[n_interior_dofs++] = i;
    2664:     PetscFree(iwork);
    2665:     ISLocalToGlobalMappingRestoreInfo(pc->pmat->rmap->mapping,&n_neigh,&neigh,&n_shared,&shared);
    2666:   }
    2667:   if (has_null_pressures) {
    2668:     IS             *subs;
    2669:     PetscInt       nsubs,i,j,nl;
    2670:     const PetscInt *idxs;
    2671:     PetscScalar    *array;
    2672:     Vec            *work;
    2673:     Mat_IS*        matis = (Mat_IS*)(pc->pmat->data);

    2675:     subs  = pcbddc->local_subs;
    2676:     nsubs = pcbddc->n_local_subs;
    2677:     /* these vectors are needed to check if the constant on pressures is in the kernel of the local operator B (i.e. B(v_I,p0) should be zero) */
    2678:     if (checkb) {
    2679:       VecDuplicateVecs(matis->y,2,&work);
    2680:       ISGetLocalSize(zerodiag,&nl);
    2681:       ISGetIndices(zerodiag,&idxs);
    2682:       /* work[0] = 1_p */
    2683:       VecSet(work[0],0.);
    2684:       VecGetArray(work[0],&array);
    2685:       for (j=0;j<nl;j++) array[idxs[j]] = 1.;
    2686:       VecRestoreArray(work[0],&array);
    2687:       /* work[0] = 1_v */
    2688:       VecSet(work[1],1.);
    2689:       VecGetArray(work[1],&array);
    2690:       for (j=0;j<nl;j++) array[idxs[j]] = 0.;
    2691:       VecRestoreArray(work[1],&array);
    2692:       ISRestoreIndices(zerodiag,&idxs);
    2693:     }

    2695:     if (nsubs > 1 || bsp > 1) {
    2696:       IS       *is;
    2697:       PetscInt b,totb;

    2699:       totb  = bsp;
    2700:       is    = bsp > 1 ? bzerodiag : &zerodiag;
    2701:       nsubs = PetscMax(nsubs,1);
    2702:       PetscCalloc1(nsubs*totb,&zerodiag_subs);
    2703:       for (b=0;b<totb;b++) {
    2704:         for (i=0;i<nsubs;i++) {
    2705:           ISLocalToGlobalMapping l2g;
    2706:           IS                     t_zerodiag_subs;
    2707:           PetscInt               nl;

    2709:           if (subs) {
    2710:             ISLocalToGlobalMappingCreateIS(subs[i],&l2g);
    2711:           } else {
    2712:             IS tis;

    2714:             MatGetLocalSize(pcbddc->local_mat,&nl,NULL);
    2715:             ISCreateStride(PETSC_COMM_SELF,nl,0,1,&tis);
    2716:             ISLocalToGlobalMappingCreateIS(tis,&l2g);
    2717:             ISDestroy(&tis);
    2718:           }
    2719:           ISGlobalToLocalMappingApplyIS(l2g,IS_GTOLM_DROP,is[b],&t_zerodiag_subs);
    2720:           ISGetLocalSize(t_zerodiag_subs,&nl);
    2721:           if (nl) {
    2722:             PetscBool valid = PETSC_TRUE;

    2724:             if (checkb) {
    2725:               VecSet(matis->x,0);
    2726:               ISGetLocalSize(subs[i],&nl);
    2727:               ISGetIndices(subs[i],&idxs);
    2728:               VecGetArray(matis->x,&array);
    2729:               for (j=0;j<nl;j++) array[idxs[j]] = 1.;
    2730:               VecRestoreArray(matis->x,&array);
    2731:               ISRestoreIndices(subs[i],&idxs);
    2732:               VecPointwiseMult(matis->x,work[0],matis->x);
    2733:               MatMult(matis->A,matis->x,matis->y);
    2734:               VecPointwiseMult(matis->y,work[1],matis->y);
    2735:               VecGetArray(matis->y,&array);
    2736:               for (j=0;j<n_interior_dofs;j++) {
    2737:                 if (PetscAbsScalar(array[interior_dofs[j]]) > PETSC_SMALL) {
    2738:                   valid = PETSC_FALSE;
    2739:                   break;
    2740:                 }
    2741:               }
    2742:               VecRestoreArray(matis->y,&array);
    2743:             }
    2744:             if (valid && nneu) {
    2745:               const PetscInt *idxs;
    2746:               PetscInt       nzb;

    2748:               ISGetIndices(pcbddc->NeumannBoundariesLocal,&idxs);
    2749:               ISGlobalToLocalMappingApply(l2g,IS_GTOLM_DROP,nneu,idxs,&nzb,NULL);
    2750:               ISRestoreIndices(pcbddc->NeumannBoundariesLocal,&idxs);
    2751:               if (nzb) valid = PETSC_FALSE;
    2752:             }
    2753:             if (valid && pressures) {
    2754:               IS       t_pressure_subs,tmp;
    2755:               PetscInt i1,i2;

    2757:               ISGlobalToLocalMappingApplyIS(l2g,IS_GTOLM_DROP,pressures,&t_pressure_subs);
    2758:               ISEmbed(t_zerodiag_subs,t_pressure_subs,PETSC_TRUE,&tmp);
    2759:               ISGetLocalSize(tmp,&i1);
    2760:               ISGetLocalSize(t_zerodiag_subs,&i2);
    2761:               if (i2 != i1) valid = PETSC_FALSE;
    2762:               ISDestroy(&t_pressure_subs);
    2763:               ISDestroy(&tmp);
    2764:             }
    2765:             if (valid) {
    2766:               ISLocalToGlobalMappingApplyIS(l2g,t_zerodiag_subs,&zerodiag_subs[benign_n]);
    2767:               benign_n++;
    2768:             } else recompute_zerodiag = PETSC_TRUE;
    2769:           }
    2770:           ISDestroy(&t_zerodiag_subs);
    2771:           ISLocalToGlobalMappingDestroy(&l2g);
    2772:         }
    2773:       }
    2774:     } else { /* there's just one subdomain (or zero if they have not been detected */
    2775:       PetscBool valid = PETSC_TRUE;

    2777:       if (nneu) valid = PETSC_FALSE;
    2778:       if (valid && pressures) {
    2779:         ISEqual(pressures,zerodiag,&valid);
    2780:       }
    2781:       if (valid && checkb) {
    2782:         MatMult(matis->A,work[0],matis->x);
    2783:         VecPointwiseMult(matis->x,work[1],matis->x);
    2784:         VecGetArray(matis->x,&array);
    2785:         for (j=0;j<n_interior_dofs;j++) {
    2786:           if (PetscAbsScalar(array[interior_dofs[j]]) > PETSC_SMALL) {
    2787:             valid = PETSC_FALSE;
    2788:             break;
    2789:           }
    2790:         }
    2791:         VecRestoreArray(matis->x,&array);
    2792:       }
    2793:       if (valid) {
    2794:         benign_n = 1;
    2795:         PetscMalloc1(benign_n,&zerodiag_subs);
    2796:         PetscObjectReference((PetscObject)zerodiag);
    2797:         zerodiag_subs[0] = zerodiag;
    2798:       }
    2799:     }
    2800:     if (checkb) {
    2801:       VecDestroyVecs(2,&work);
    2802:     }
    2803:   }
    2804:   PetscFree(interior_dofs);

    2806:   if (!benign_n) {
    2807:     PetscInt n;

    2809:     ISDestroy(&zerodiag);
    2810:     recompute_zerodiag = PETSC_FALSE;
    2811:     MatGetLocalSize(pcbddc->local_mat,&n,NULL);
    2812:     if (n) have_null = PETSC_FALSE;
    2813:   }

    2815:   /* final check for null pressures */
    2816:   if (zerodiag && pressures) {
    2817:     ISEqual(pressures,zerodiag,&have_null);
    2818:   }

    2820:   if (recompute_zerodiag) {
    2821:     ISDestroy(&zerodiag);
    2822:     if (benign_n == 1) {
    2823:       PetscObjectReference((PetscObject)zerodiag_subs[0]);
    2824:       zerodiag = zerodiag_subs[0];
    2825:     } else {
    2826:       PetscInt i,nzn,*new_idxs;

    2828:       nzn = 0;
    2829:       for (i=0;i<benign_n;i++) {
    2830:         PetscInt ns;
    2831:         ISGetLocalSize(zerodiag_subs[i],&ns);
    2832:         nzn += ns;
    2833:       }
    2834:       PetscMalloc1(nzn,&new_idxs);
    2835:       nzn = 0;
    2836:       for (i=0;i<benign_n;i++) {
    2837:         PetscInt ns,*idxs;
    2838:         ISGetLocalSize(zerodiag_subs[i],&ns);
    2839:         ISGetIndices(zerodiag_subs[i],(const PetscInt**)&idxs);
    2840:         PetscArraycpy(new_idxs+nzn,idxs,ns);
    2841:         ISRestoreIndices(zerodiag_subs[i],(const PetscInt**)&idxs);
    2842:         nzn += ns;
    2843:       }
    2844:       PetscSortInt(nzn,new_idxs);
    2845:       ISCreateGeneral(PETSC_COMM_SELF,nzn,new_idxs,PETSC_OWN_POINTER,&zerodiag);
    2846:     }
    2847:     have_null = PETSC_FALSE;
    2848:   }

    2850:   /* determines if the coarse solver will be singular or not */
    2851:   MPIU_Allreduce(&have_null,&pcbddc->benign_null,1,MPIU_BOOL,MPI_LAND,PetscObjectComm((PetscObject)pc));

    2853:   /* Prepare matrix to compute no-net-flux */
    2854:   if (pcbddc->compute_nonetflux && !pcbddc->divudotp) {
    2855:     Mat                    A,loc_divudotp;
    2856:     ISLocalToGlobalMapping rl2g,cl2g,l2gmap;
    2857:     IS                     row,col,isused = NULL;
    2858:     PetscInt               M,N,n,st,n_isused;

    2860:     if (pressures) {
    2861:       isused = pressures;
    2862:     } else {
    2863:       isused = zerodiag_save;
    2864:     }
    2865:     MatGetLocalToGlobalMapping(pc->pmat,&l2gmap,NULL);
    2866:     MatISGetLocalMat(pc->pmat,&A);
    2867:     MatGetLocalSize(A,&n,NULL);
    2868:     if (!isused && n) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_USER,"Don't know how to extract div u dot p! Please provide the pressure field");
    2869:     n_isused = 0;
    2870:     if (isused) {
    2871:       ISGetLocalSize(isused,&n_isused);
    2872:     }
    2873:     MPI_Scan(&n_isused,&st,1,MPIU_INT,MPI_SUM,PetscObjectComm((PetscObject)pc));
    2874:     st = st-n_isused;
    2875:     if (n) {
    2876:       const PetscInt *gidxs;

    2878:       MatCreateSubMatrix(A,isused,NULL,MAT_INITIAL_MATRIX,&loc_divudotp);
    2879:       ISLocalToGlobalMappingGetIndices(l2gmap,&gidxs);
    2880:       /* TODO: extend ISCreateStride with st = PETSC_DECIDE */
    2881:       ISCreateStride(PetscObjectComm((PetscObject)pc),n_isused,st,1,&row);
    2882:       ISCreateGeneral(PetscObjectComm((PetscObject)pc),n,gidxs,PETSC_COPY_VALUES,&col);
    2883:       ISLocalToGlobalMappingRestoreIndices(l2gmap,&gidxs);
    2884:     } else {
    2885:       MatCreateSeqAIJ(PETSC_COMM_SELF,0,0,1,NULL,&loc_divudotp);
    2886:       ISCreateStride(PetscObjectComm((PetscObject)pc),n_isused,st,1,&row);
    2887:       ISCreateGeneral(PetscObjectComm((PetscObject)pc),0,NULL,PETSC_COPY_VALUES,&col);
    2888:     }
    2889:     MatGetSize(pc->pmat,NULL,&N);
    2890:     ISGetSize(row,&M);
    2891:     ISLocalToGlobalMappingCreateIS(row,&rl2g);
    2892:     ISLocalToGlobalMappingCreateIS(col,&cl2g);
    2893:     ISDestroy(&row);
    2894:     ISDestroy(&col);
    2895:     MatCreate(PetscObjectComm((PetscObject)pc),&pcbddc->divudotp);
    2896:     MatSetType(pcbddc->divudotp,MATIS);
    2897:     MatSetSizes(pcbddc->divudotp,PETSC_DECIDE,PETSC_DECIDE,M,N);
    2898:     MatSetLocalToGlobalMapping(pcbddc->divudotp,rl2g,cl2g);
    2899:     ISLocalToGlobalMappingDestroy(&rl2g);
    2900:     ISLocalToGlobalMappingDestroy(&cl2g);
    2901:     MatISSetLocalMat(pcbddc->divudotp,loc_divudotp);
    2902:     MatDestroy(&loc_divudotp);
    2903:     MatAssemblyBegin(pcbddc->divudotp,MAT_FINAL_ASSEMBLY);
    2904:     MatAssemblyEnd(pcbddc->divudotp,MAT_FINAL_ASSEMBLY);
    2905:   }
    2906:   ISDestroy(&zerodiag_save);
    2907:   ISDestroy(&pressures);
    2908:   if (bzerodiag) {
    2909:     PetscInt i;

    2911:     for (i=0;i<bsp;i++) {
    2912:       ISDestroy(&bzerodiag[i]);
    2913:     }
    2914:     PetscFree(bzerodiag);
    2915:   }
    2916:   pcbddc->benign_n = benign_n;
    2917:   pcbddc->benign_zerodiag_subs = zerodiag_subs;

    2919:   /* determines if the problem has subdomains with 0 pressure block */
    2920:   have_null = (PetscBool)(!!pcbddc->benign_n);
    2921:   MPIU_Allreduce(&have_null,&pcbddc->benign_have_null,1,MPIU_BOOL,MPI_LOR,PetscObjectComm((PetscObject)pc));

    2923: project_b0:
    2924:   MatGetLocalSize(pcbddc->local_mat,&n,NULL);
    2925:   /* change of basis and p0 dofs */
    2926:   if (pcbddc->benign_n) {
    2927:     PetscInt i,s,*nnz;

    2929:     /* local change of basis for pressures */
    2930:     MatDestroy(&pcbddc->benign_change);
    2931:     MatCreate(PetscObjectComm((PetscObject)pcbddc->local_mat),&pcbddc->benign_change);
    2932:     MatSetType(pcbddc->benign_change,MATAIJ);
    2933:     MatSetSizes(pcbddc->benign_change,n,n,PETSC_DECIDE,PETSC_DECIDE);
    2934:     PetscMalloc1(n,&nnz);
    2935:     for (i=0;i<n;i++) nnz[i] = 1; /* defaults to identity */
    2936:     for (i=0;i<pcbddc->benign_n;i++) {
    2937:       const PetscInt *idxs;
    2938:       PetscInt       nzs,j;

    2940:       ISGetLocalSize(pcbddc->benign_zerodiag_subs[i],&nzs);
    2941:       ISGetIndices(pcbddc->benign_zerodiag_subs[i],&idxs);
    2942:       for (j=0;j<nzs-1;j++) nnz[idxs[j]] = 2; /* change on pressures */
    2943:       nnz[idxs[nzs-1]] = nzs; /* last local pressure dof in subdomain */
    2944:       ISRestoreIndices(pcbddc->benign_zerodiag_subs[i],&idxs);
    2945:     }
    2946:     MatSeqAIJSetPreallocation(pcbddc->benign_change,0,nnz);
    2947:     MatSetOption(pcbddc->benign_change,MAT_NEW_NONZERO_ALLOCATION_ERR,PETSC_TRUE);
    2948:     PetscFree(nnz);
    2949:     /* set identity by default */
    2950:     for (i=0;i<n;i++) {
    2951:       MatSetValue(pcbddc->benign_change,i,i,1.,INSERT_VALUES);
    2952:     }
    2953:     PetscFree3(pcbddc->benign_p0_lidx,pcbddc->benign_p0_gidx,pcbddc->benign_p0);
    2954:     PetscMalloc3(pcbddc->benign_n,&pcbddc->benign_p0_lidx,pcbddc->benign_n,&pcbddc->benign_p0_gidx,pcbddc->benign_n,&pcbddc->benign_p0);
    2955:     /* set change on pressures */
    2956:     for (s=0;s<pcbddc->benign_n;s++) {
    2957:       PetscScalar    *array;
    2958:       const PetscInt *idxs;
    2959:       PetscInt       nzs;

    2961:       ISGetLocalSize(pcbddc->benign_zerodiag_subs[s],&nzs);
    2962:       ISGetIndices(pcbddc->benign_zerodiag_subs[s],&idxs);
    2963:       for (i=0;i<nzs-1;i++) {
    2964:         PetscScalar vals[2];
    2965:         PetscInt    cols[2];

    2967:         cols[0] = idxs[i];
    2968:         cols[1] = idxs[nzs-1];
    2969:         vals[0] = 1.;
    2970:         vals[1] = 1.;
    2971:         MatSetValues(pcbddc->benign_change,1,cols,2,cols,vals,INSERT_VALUES);
    2972:       }
    2973:       PetscMalloc1(nzs,&array);
    2974:       for (i=0;i<nzs-1;i++) array[i] = -1.;
    2975:       array[nzs-1] = 1.;
    2976:       MatSetValues(pcbddc->benign_change,1,idxs+nzs-1,nzs,idxs,array,INSERT_VALUES);
    2977:       /* store local idxs for p0 */
    2978:       pcbddc->benign_p0_lidx[s] = idxs[nzs-1];
    2979:       ISRestoreIndices(pcbddc->benign_zerodiag_subs[s],&idxs);
    2980:       PetscFree(array);
    2981:     }
    2982:     MatAssemblyBegin(pcbddc->benign_change,MAT_FINAL_ASSEMBLY);
    2983:     MatAssemblyEnd(pcbddc->benign_change,MAT_FINAL_ASSEMBLY);

    2985:     /* project if needed */
    2986:     if (pcbddc->benign_change_explicit) {
    2987:       Mat M;

    2989:       MatPtAP(pcbddc->local_mat,pcbddc->benign_change,MAT_INITIAL_MATRIX,2.0,&M);
    2990:       MatDestroy(&pcbddc->local_mat);
    2991:       MatSeqAIJCompress(M,&pcbddc->local_mat);
    2992:       MatDestroy(&M);
    2993:     }
    2994:     /* store global idxs for p0 */
    2995:     ISLocalToGlobalMappingApply(pc->pmat->rmap->mapping,pcbddc->benign_n,pcbddc->benign_p0_lidx,pcbddc->benign_p0_gidx);
    2996:   }
    2997:   *zerodiaglocal = zerodiag;
    2998:   return(0);
    2999: }

    3001: PetscErrorCode PCBDDCBenignGetOrSetP0(PC pc, Vec v, PetscBool get)
    3002: {
    3003:   PC_BDDC*       pcbddc = (PC_BDDC*)pc->data;
    3004:   PetscScalar    *array;

    3008:   if (!pcbddc->benign_sf) {
    3009:     PetscSFCreate(PetscObjectComm((PetscObject)pc),&pcbddc->benign_sf);
    3010:     PetscSFSetGraphLayout(pcbddc->benign_sf,pc->pmat->rmap,pcbddc->benign_n,NULL,PETSC_OWN_POINTER,pcbddc->benign_p0_gidx);
    3011:   }
    3012:   if (get) {
    3013:     VecGetArrayRead(v,(const PetscScalar**)&array);
    3014:     PetscSFBcastBegin(pcbddc->benign_sf,MPIU_SCALAR,array,pcbddc->benign_p0);
    3015:     PetscSFBcastEnd(pcbddc->benign_sf,MPIU_SCALAR,array,pcbddc->benign_p0);
    3016:     VecRestoreArrayRead(v,(const PetscScalar**)&array);
    3017:   } else {
    3018:     VecGetArray(v,&array);
    3019:     PetscSFReduceBegin(pcbddc->benign_sf,MPIU_SCALAR,pcbddc->benign_p0,array,MPIU_REPLACE);
    3020:     PetscSFReduceEnd(pcbddc->benign_sf,MPIU_SCALAR,pcbddc->benign_p0,array,MPIU_REPLACE);
    3021:     VecRestoreArray(v,&array);
    3022:   }
    3023:   return(0);
    3024: }

    3026: PetscErrorCode PCBDDCBenignPopOrPushB0(PC pc, PetscBool pop)
    3027: {
    3028:   PC_BDDC*       pcbddc = (PC_BDDC*)pc->data;

    3032:   /* TODO: add error checking
    3033:     - avoid nested pop (or push) calls.
    3034:     - cannot push before pop.
    3035:     - cannot call this if pcbddc->local_mat is NULL
    3036:   */
    3037:   if (!pcbddc->benign_n) {
    3038:     return(0);
    3039:   }
    3040:   if (pop) {
    3041:     if (pcbddc->benign_change_explicit) {
    3042:       IS       is_p0;
    3043:       MatReuse reuse;

    3045:       /* extract B_0 */
    3046:       reuse = MAT_INITIAL_MATRIX;
    3047:       if (pcbddc->benign_B0) {
    3048:         reuse = MAT_REUSE_MATRIX;
    3049:       }
    3050:       ISCreateGeneral(PETSC_COMM_SELF,pcbddc->benign_n,pcbddc->benign_p0_lidx,PETSC_COPY_VALUES,&is_p0);
    3051:       MatCreateSubMatrix(pcbddc->local_mat,is_p0,NULL,reuse,&pcbddc->benign_B0);
    3052:       /* remove rows and cols from local problem */
    3053:       MatSetOption(pcbddc->local_mat,MAT_KEEP_NONZERO_PATTERN,PETSC_TRUE);
    3054:       MatSetOption(pcbddc->local_mat,MAT_NEW_NONZERO_LOCATION_ERR,PETSC_FALSE);
    3055:       MatZeroRowsColumnsIS(pcbddc->local_mat,is_p0,1.0,NULL,NULL);
    3056:       ISDestroy(&is_p0);
    3057:     } else {
    3058:       Mat_IS      *matis = (Mat_IS*)pc->pmat->data;
    3059:       PetscScalar *vals;
    3060:       PetscInt    i,n,*idxs_ins;

    3062:       VecGetLocalSize(matis->y,&n);
    3063:       PetscMalloc2(n,&idxs_ins,n,&vals);
    3064:       if (!pcbddc->benign_B0) {
    3065:         PetscInt *nnz;
    3066:         MatCreate(PetscObjectComm((PetscObject)pcbddc->local_mat),&pcbddc->benign_B0);
    3067:         MatSetType(pcbddc->benign_B0,MATAIJ);
    3068:         MatSetSizes(pcbddc->benign_B0,pcbddc->benign_n,n,PETSC_DECIDE,PETSC_DECIDE);
    3069:         PetscMalloc1(pcbddc->benign_n,&nnz);
    3070:         for (i=0;i<pcbddc->benign_n;i++) {
    3071:           ISGetLocalSize(pcbddc->benign_zerodiag_subs[i],&nnz[i]);
    3072:           nnz[i] = n - nnz[i];
    3073:         }
    3074:         MatSeqAIJSetPreallocation(pcbddc->benign_B0,0,nnz);
    3075:         MatSetOption(pcbddc->benign_B0,MAT_NEW_NONZERO_ALLOCATION_ERR,PETSC_TRUE);
    3076:         PetscFree(nnz);
    3077:       }

    3079:       for (i=0;i<pcbddc->benign_n;i++) {
    3080:         PetscScalar *array;
    3081:         PetscInt    *idxs,j,nz,cum;

    3083:         VecSet(matis->x,0.);
    3084:         ISGetLocalSize(pcbddc->benign_zerodiag_subs[i],&nz);
    3085:         ISGetIndices(pcbddc->benign_zerodiag_subs[i],(const PetscInt**)&idxs);
    3086:         for (j=0;j<nz;j++) vals[j] = 1.;
    3087:         VecSetValues(matis->x,nz,idxs,vals,INSERT_VALUES);
    3088:         VecAssemblyBegin(matis->x);
    3089:         VecAssemblyEnd(matis->x);
    3090:         VecSet(matis->y,0.);
    3091:         MatMult(matis->A,matis->x,matis->y);
    3092:         VecGetArray(matis->y,&array);
    3093:         cum = 0;
    3094:         for (j=0;j<n;j++) {
    3095:           if (PetscUnlikely(PetscAbsScalar(array[j]) > PETSC_SMALL)) {
    3096:             vals[cum] = array[j];
    3097:             idxs_ins[cum] = j;
    3098:             cum++;
    3099:           }
    3100:         }
    3101:         MatSetValues(pcbddc->benign_B0,1,&i,cum,idxs_ins,vals,INSERT_VALUES);
    3102:         VecRestoreArray(matis->y,&array);
    3103:         ISRestoreIndices(pcbddc->benign_zerodiag_subs[i],(const PetscInt**)&idxs);
    3104:       }
    3105:       MatAssemblyBegin(pcbddc->benign_B0,MAT_FINAL_ASSEMBLY);
    3106:       MatAssemblyEnd(pcbddc->benign_B0,MAT_FINAL_ASSEMBLY);
    3107:       PetscFree2(idxs_ins,vals);
    3108:     }
    3109:   } else { /* push */
    3110:     if (pcbddc->benign_change_explicit) {
    3111:       PetscInt i;

    3113:       for (i=0;i<pcbddc->benign_n;i++) {
    3114:         PetscScalar *B0_vals;
    3115:         PetscInt    *B0_cols,B0_ncol;

    3117:         MatGetRow(pcbddc->benign_B0,i,&B0_ncol,(const PetscInt**)&B0_cols,(const PetscScalar**)&B0_vals);
    3118:         MatSetValues(pcbddc->local_mat,1,pcbddc->benign_p0_lidx+i,B0_ncol,B0_cols,B0_vals,INSERT_VALUES);
    3119:         MatSetValues(pcbddc->local_mat,B0_ncol,B0_cols,1,pcbddc->benign_p0_lidx+i,B0_vals,INSERT_VALUES);
    3120:         MatSetValue(pcbddc->local_mat,pcbddc->benign_p0_lidx[i],pcbddc->benign_p0_lidx[i],0.0,INSERT_VALUES);
    3121:         MatRestoreRow(pcbddc->benign_B0,i,&B0_ncol,(const PetscInt**)&B0_cols,(const PetscScalar**)&B0_vals);
    3122:       }
    3123:       MatAssemblyBegin(pcbddc->local_mat,MAT_FINAL_ASSEMBLY);
    3124:       MatAssemblyEnd(pcbddc->local_mat,MAT_FINAL_ASSEMBLY);
    3125:     } else SETERRQ(PETSC_COMM_SELF,PETSC_ERR_PLIB,"Cannot push B0!");
    3126:   }
    3127:   return(0);
    3128: }

    3130: PetscErrorCode PCBDDCAdaptiveSelection(PC pc)
    3131: {
    3132:   PC_BDDC*        pcbddc = (PC_BDDC*)pc->data;
    3133:   PCBDDCSubSchurs sub_schurs = pcbddc->sub_schurs;
    3134:   PetscBLASInt    B_dummyint,B_neigs,B_ierr,B_lwork;
    3135:   PetscBLASInt    *B_iwork,*B_ifail;
    3136:   PetscScalar     *work,lwork;
    3137:   PetscScalar     *St,*S,*eigv;
    3138:   PetscScalar     *Sarray,*Starray;
    3139:   PetscReal       *eigs,thresh,lthresh,uthresh;
    3140:   PetscInt        i,nmax,nmin,nv,cum,mss,cum2,cumarray,maxneigs;
    3141:   PetscBool       allocated_S_St;
    3142: #if defined(PETSC_USE_COMPLEX)
    3143:   PetscReal       *rwork;
    3144: #endif
    3145:   PetscErrorCode  ierr;

    3148:   if (!sub_schurs) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_PLIB,"Adaptive selection of constraints requires SubSchurs data");
    3149:   if (!sub_schurs->schur_explicit) SETERRQ(PetscObjectComm((PetscObject)pc),PETSC_ERR_SUP,"Adaptive selection of constraints requires MUMPS and/or MKL_CPARDISO");
    3150:   if (sub_schurs->n_subs && (!sub_schurs->is_symmetric)) SETERRQ3(PETSC_COMM_SELF,PETSC_ERR_SUP,"Adaptive selection not yet implemented for this matrix pencil (herm %d, symm %d, posdef %d)",sub_schurs->is_hermitian,sub_schurs->is_symmetric,sub_schurs->is_posdef);
    3151:   PetscLogEventBegin(PC_BDDC_AdaptiveSetUp[pcbddc->current_level],pc,0,0,0);

    3153:   if (pcbddc->dbg_flag) {
    3154:     PetscViewerFlush(pcbddc->dbg_viewer);
    3155:     PetscViewerASCIIPrintf(pcbddc->dbg_viewer,"--------------------------------------------------\n");
    3156:     PetscViewerASCIIPrintf(pcbddc->dbg_viewer,"Check adaptive selection of constraints\n");
    3157:     PetscViewerASCIIPushSynchronized(pcbddc->dbg_viewer);
    3158:   }

    3160:   if (pcbddc->dbg_flag) {
    3161:     PetscViewerASCIISynchronizedPrintf(pcbddc->dbg_viewer,"Subdomain %04d cc %D (%d,%d).\n",PetscGlobalRank,sub_schurs->n_subs,sub_schurs->is_hermitian,sub_schurs->is_posdef);
    3162:   }

    3164:   /* max size of subsets */
    3165:   mss = 0;
    3166:   for (i=0;i<sub_schurs->n_subs;i++) {
    3167:     PetscInt subset_size;

    3169:     ISGetLocalSize(sub_schurs->is_subs[i],&subset_size);
    3170:     mss = PetscMax(mss,subset_size);
    3171:   }

    3173:   /* min/max and threshold */
    3174:   nmax = pcbddc->adaptive_nmax > 0 ? pcbddc->adaptive_nmax : mss;
    3175:   nmin = pcbddc->adaptive_nmin > 0 ? pcbddc->adaptive_nmin : 0;
    3176:   nmax = PetscMax(nmin,nmax);
    3177:   allocated_S_St = PETSC_FALSE;
    3178:   if (nmin || !sub_schurs->is_posdef) { /* XXX */
    3179:     allocated_S_St = PETSC_TRUE;
    3180:   }

    3182:   /* allocate lapack workspace */
    3183:   cum = cum2 = 0;
    3184:   maxneigs = 0;
    3185:   for (i=0;i<sub_schurs->n_subs;i++) {
    3186:     PetscInt n,subset_size;

    3188:     ISGetLocalSize(sub_schurs->is_subs[i],&subset_size);
    3189:     n = PetscMin(subset_size,nmax);
    3190:     cum += subset_size;
    3191:     cum2 += subset_size*n;
    3192:     maxneigs = PetscMax(maxneigs,n);
    3193:   }
    3194:   lwork = 0;
    3195:   if (mss) {
    3196:     if (sub_schurs->is_symmetric) {
    3197:       PetscScalar  sdummy = 0.;
    3198:       PetscBLASInt B_itype = 1;
    3199:       PetscBLASInt B_N = mss, idummy = 0;
    3200:       PetscReal    rdummy = 0.,zero = 0.0;
    3201:       PetscReal    eps = 0.0; /* dlamch? */

    3203:       B_lwork = -1;
    3204:       /* some implementations may complain about NULL pointers, even if we are querying */
    3205:       S = &sdummy;
    3206:       St = &sdummy;
    3207:       eigs = &rdummy;
    3208:       eigv = &sdummy;
    3209:       B_iwork = &idummy;
    3210:       B_ifail = &idummy;
    3211: #if defined(PETSC_USE_COMPLEX)
    3212:       rwork = &rdummy;
    3213: #endif
    3214:       thresh = 1.0;
    3215:       PetscFPTrapPush(PETSC_FP_TRAP_OFF);
    3216: #if defined(PETSC_USE_COMPLEX)
    3217:       PetscStackCallBLAS("LAPACKsygvx",LAPACKsygvx_(&B_itype,"V","V","L",&B_N,St,&B_N,S,&B_N,&zero,&thresh,&B_dummyint,&B_dummyint,&eps,&B_neigs,eigs,eigv,&B_N,&lwork,&B_lwork,rwork,B_iwork,B_ifail,&B_ierr));
    3218: #else
    3219:       PetscStackCallBLAS("LAPACKsygvx",LAPACKsygvx_(&B_itype,"V","V","L",&B_N,St,&B_N,S,&B_N,&zero,&thresh,&B_dummyint,&B_dummyint,&eps,&B_neigs,eigs,eigv,&B_N,&lwork,&B_lwork,B_iwork,B_ifail,&B_ierr));
    3220: #endif
    3221:       if (B_ierr != 0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_LIB,"Error in query to SYGVX Lapack routine %d",(int)B_ierr);
    3222:       PetscFPTrapPop();
    3223:     } else SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"Not yet implemented");
    3224:   }

    3226:   nv = 0;
    3227:   if (sub_schurs->is_vertices && pcbddc->use_vertices) { /* complement set of active subsets, each entry is a vertex (boundary made by active subsets, vertices and dirichlet dofs) */
    3228:     ISGetLocalSize(sub_schurs->is_vertices,&nv);
    3229:   }
    3230:   PetscBLASIntCast((PetscInt)PetscRealPart(lwork),&B_lwork);
    3231:   if (allocated_S_St) {
    3232:     PetscMalloc2(mss*mss,&S,mss*mss,&St);
    3233:   }
    3234:   PetscMalloc5(mss*mss,&eigv,mss,&eigs,B_lwork,&work,5*mss,&B_iwork,mss,&B_ifail);
    3235: #if defined(PETSC_USE_COMPLEX)
    3236:   PetscMalloc1(7*mss,&rwork);
    3237: #endif
    3238:   PetscMalloc5(nv+sub_schurs->n_subs,&pcbddc->adaptive_constraints_n,
    3239:                       nv+sub_schurs->n_subs+1,&pcbddc->adaptive_constraints_idxs_ptr,
    3240:                       nv+sub_schurs->n_subs+1,&pcbddc->adaptive_constraints_data_ptr,
    3241:                       nv+cum,&pcbddc->adaptive_constraints_idxs,
    3242:                       nv+cum2,&pcbddc->adaptive_constraints_data);
    3243:   PetscArrayzero(pcbddc->adaptive_constraints_n,nv+sub_schurs->n_subs);

    3245:   maxneigs = 0;
    3246:   cum = cumarray = 0;
    3247:   pcbddc->adaptive_constraints_idxs_ptr[0] = 0;
    3248:   pcbddc->adaptive_constraints_data_ptr[0] = 0;
    3249:   if (sub_schurs->is_vertices && pcbddc->use_vertices) {
    3250:     const PetscInt *idxs;

    3252:     ISGetIndices(sub_schurs->is_vertices,&idxs);
    3253:     for (cum=0;cum<nv;cum++) {
    3254:       pcbddc->adaptive_constraints_n[cum] = 1;
    3255:       pcbddc->adaptive_constraints_idxs[cum] = idxs[cum];
    3256:       pcbddc->adaptive_constraints_data[cum] = 1.0;
    3257:       pcbddc->adaptive_constraints_idxs_ptr[cum+1] = pcbddc->adaptive_constraints_idxs_ptr[cum]+1;
    3258:       pcbddc->adaptive_constraints_data_ptr[cum+1] = pcbddc->adaptive_constraints_data_ptr[cum]+1;
    3259:     }
    3260:     ISRestoreIndices(sub_schurs->is_vertices,&idxs);
    3261:   }

    3263:   if (mss) { /* multilevel */
    3264:     MatSeqAIJGetArray(sub_schurs->sum_S_Ej_inv_all,&Sarray);
    3265:     MatSeqAIJGetArray(sub_schurs->sum_S_Ej_tilda_all,&Starray);
    3266:   }

    3268:   lthresh = pcbddc->adaptive_threshold[0];
    3269:   uthresh = pcbddc->adaptive_threshold[1];
    3270:   for (i=0;i<sub_schurs->n_subs;i++) {
    3271:     const PetscInt *idxs;
    3272:     PetscReal      upper,lower;
    3273:     PetscInt       j,subset_size,eigs_start = 0;
    3274:     PetscBLASInt   B_N;
    3275:     PetscBool      same_data = PETSC_FALSE;
    3276:     PetscBool      scal = PETSC_FALSE;

    3278:     if (pcbddc->use_deluxe_scaling) {
    3279:       upper = PETSC_MAX_REAL;
    3280:       lower = uthresh;
    3281:     } else {
    3282:       if (!sub_schurs->is_posdef) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"Not yet implemented without deluxe scaling");
    3283:       upper = 1./uthresh;
    3284:       lower = 0.;
    3285:     }
    3286:     ISGetLocalSize(sub_schurs->is_subs[i],&subset_size);
    3287:     ISGetIndices(sub_schurs->is_subs[i],&idxs);
    3288:     PetscBLASIntCast(subset_size,&B_N);
    3289:     /* this is experimental: we assume the dofs have been properly grouped to have
    3290:        the diagonal blocks Schur complements either positive or negative definite (true for Stokes) */
    3291:     if (!sub_schurs->is_posdef) {
    3292:       Mat T;

    3294:       for (j=0;j<subset_size;j++) {
    3295:         if (PetscRealPart(*(Sarray+cumarray+j*(subset_size+1))) < 0.0) {
    3296:           MatCreateSeqDense(PETSC_COMM_SELF,subset_size,subset_size,Sarray+cumarray,&T);
    3297:           MatScale(T,-1.0);
    3298:           MatDestroy(&T);
    3299:           MatCreateSeqDense(PETSC_COMM_SELF,subset_size,subset_size,Starray+cumarray,&T);
    3300:           MatScale(T,-1.0);
    3301:           MatDestroy(&T);
    3302:           if (sub_schurs->change_primal_sub) {
    3303:             PetscInt       nz,k;
    3304:             const PetscInt *idxs;

    3306:             ISGetLocalSize(sub_schurs->change_primal_sub[i],&nz);
    3307:             ISGetIndices(sub_schurs->change_primal_sub[i],&idxs);
    3308:             for (k=0;k<nz;k++) {
    3309:               *( Sarray + cumarray + idxs[k]*(subset_size+1)) *= -1.0;
    3310:               *(Starray + cumarray + idxs[k]*(subset_size+1))  = 0.0;
    3311:             }
    3312:             ISRestoreIndices(sub_schurs->change_primal_sub[i],&idxs);
    3313:           }
    3314:           scal = PETSC_TRUE;
    3315:           break;
    3316:         }
    3317:       }
    3318:     }

    3320:     if (allocated_S_St) { /* S and S_t should be copied since we could need them later */
    3321:       if (sub_schurs->is_symmetric) {
    3322:         PetscInt j,k;
    3323:         if (sub_schurs->n_subs == 1) { /* zeroing memory to use PetscArraycmp() later */
    3324:           PetscArrayzero(S,subset_size*subset_size);
    3325:           PetscArrayzero(St,subset_size*subset_size);
    3326:         }
    3327:         for (j=0;j<subset_size;j++) {
    3328:           for (k=j;k<subset_size;k++) {
    3329:             S [j*subset_size+k] = Sarray [cumarray+j*subset_size+k];
    3330:             St[j*subset_size+k] = Starray[cumarray+j*subset_size+k];
    3331:           }
    3332:         }
    3333:       } else {
    3334:         PetscArraycpy(S,Sarray+cumarray,subset_size*subset_size);
    3335:         PetscArraycpy(St,Starray+cumarray,subset_size*subset_size);
    3336:       }
    3337:     } else {
    3338:       S = Sarray + cumarray;
    3339:       St = Starray + cumarray;
    3340:     }
    3341:     /* see if we can save some work */
    3342:     if (sub_schurs->n_subs == 1 && pcbddc->use_deluxe_scaling) {
    3343:       PetscArraycmp(S,St,subset_size*subset_size,&same_data);
    3344:     }

    3346:     if (same_data && !sub_schurs->change) { /* there's no need of constraints here */
    3347:       B_neigs = 0;
    3348:     } else {
    3349:       if (sub_schurs->is_symmetric) {
    3350:         PetscBLASInt B_itype = 1;
    3351:         PetscBLASInt B_IL, B_IU;
    3352:         PetscReal    eps = -1.0; /* dlamch? */
    3353:         PetscInt     nmin_s;
    3354:         PetscBool    compute_range;

    3356:         B_neigs = 0;
    3357:         compute_range = (PetscBool)!same_data;
    3358:         if (nmin >= subset_size) compute_range = PETSC_FALSE;

    3360:         if (pcbddc->dbg_flag) {
    3361:           PetscInt nc = 0;

    3363:           if (sub_schurs->change_primal_sub) {
    3364:             ISGetLocalSize(sub_schurs->change_primal_sub[i],&nc);
    3365:           }
    3366:           PetscViewerASCIISynchronizedPrintf(pcbddc->dbg_viewer,"Computing for sub %D/%D size %D count %D fid %D (range %d) (change %D).\n",i,sub_schurs->n_subs,subset_size,pcbddc->mat_graph->count[idxs[0]]+1,pcbddc->mat_graph->which_dof[idxs[0]],compute_range,nc);
    3367:         }

    3369:         PetscFPTrapPush(PETSC_FP_TRAP_OFF);
    3370:         if (compute_range) {

    3372:           /* ask for eigenvalues larger than thresh */
    3373:           if (sub_schurs->is_posdef) {
    3374: #if defined(PETSC_USE_COMPLEX)
    3375:             PetscStackCallBLAS("LAPACKsygvx",LAPACKsygvx_(&B_itype,"V","V","L",&B_N,St,&B_N,S,&B_N,&lower,&upper,&B_IL,&B_IU,&eps,&B_neigs,eigs,eigv,&B_N,work,&B_lwork,rwork,B_iwork,B_ifail,&B_ierr));
    3376: #else
    3377:             PetscStackCallBLAS("LAPACKsygvx",LAPACKsygvx_(&B_itype,"V","V","L",&B_N,St,&B_N,S,&B_N,&lower,&upper,&B_IL,&B_IU,&eps,&B_neigs,eigs,eigv,&B_N,work,&B_lwork,B_iwork,B_ifail,&B_ierr));
    3378: #endif
    3379:             PetscLogFlops((4.0*subset_size*subset_size*subset_size)/3.0);
    3380:           } else { /* no theory so far, but it works nicely */
    3381:             PetscInt  recipe = 0,recipe_m = 1;
    3382:             PetscReal bb[2];

    3384:             PetscOptionsGetInt(NULL,((PetscObject)pc)->prefix,"-pc_bddc_adaptive_recipe",&recipe,NULL);
    3385:             switch (recipe) {
    3386:             case 0:
    3387:               if (scal) { bb[0] = PETSC_MIN_REAL; bb[1] = lthresh; }
    3388:               else { bb[0] = uthresh; bb[1] = PETSC_MAX_REAL; }
    3389: #if defined(PETSC_USE_COMPLEX)
    3390:               PetscStackCallBLAS("LAPACKsygvx",LAPACKsygvx_(&B_itype,"V","V","L",&B_N,St,&B_N,S,&B_N,&bb[0],&bb[1],&B_IL,&B_IU,&eps,&B_neigs,eigs,eigv,&B_N,work,&B_lwork,rwork,B_iwork,B_ifail,&B_ierr));
    3391: #else
    3392:               PetscStackCallBLAS("LAPACKsygvx",LAPACKsygvx_(&B_itype,"V","V","L",&B_N,St,&B_N,S,&B_N,&bb[0],&bb[1],&B_IL,&B_IU,&eps,&B_neigs,eigs,eigv,&B_N,work,&B_lwork,B_iwork,B_ifail,&B_ierr));
    3393: #endif
    3394:               PetscLogFlops((4.0*subset_size*subset_size*subset_size)/3.0);
    3395:               break;
    3396:             case 1:
    3397:               bb[0] = PETSC_MIN_REAL; bb[1] = lthresh*lthresh;
    3398: #if defined(PETSC_USE_COMPLEX)
    3399:               PetscStackCallBLAS("LAPACKsygvx",LAPACKsygvx_(&B_itype,"V","V","L",&B_N,St,&B_N,S,&B_N,&bb[0],&bb[1],&B_IL,&B_IU,&eps,&B_neigs,eigs,eigv,&B_N,work,&B_lwork,rwork,B_iwork,B_ifail,&B_ierr));
    3400: #else
    3401:               PetscStackCallBLAS("LAPACKsygvx",LAPACKsygvx_(&B_itype,"V","V","L",&B_N,St,&B_N,S,&B_N,&bb[0],&bb[1],&B_IL,&B_IU,&eps,&B_neigs,eigs,eigv,&B_N,work,&B_lwork,B_iwork,B_ifail,&B_ierr));
    3402: #endif
    3403:               PetscLogFlops((4.0*subset_size*subset_size*subset_size)/3.0);
    3404:               if (!scal) {
    3405:                 PetscBLASInt B_neigs2 = 0;

    3407:                 bb[0] = PetscMax(lthresh*lthresh,uthresh); bb[1] = PETSC_MAX_REAL;
    3408:                 PetscArraycpy(S,Sarray+cumarray,subset_size*subset_size);
    3409:                 PetscArraycpy(St,Starray+cumarray,subset_size*subset_size);
    3410: #if defined(PETSC_USE_COMPLEX)
    3411:                 PetscStackCallBLAS("LAPACKsygvx",LAPACKsygvx_(&B_itype,"V","V","L",&B_N,St,&B_N,S,&B_N,&bb[0],&bb[1],&B_IL,&B_IU,&eps,&B_neigs2,eigs+B_neigs,eigv+B_neigs*B_N,&B_N,work,&B_lwork,rwork,B_iwork,B_ifail,&B_ierr));
    3412: #else
    3413:                 PetscStackCallBLAS("LAPACKsygvx",LAPACKsygvx_(&B_itype,"V","V","L",&B_N,St,&B_N,S,&B_N,&bb[0],&bb[1],&B_IL,&B_IU,&eps,&B_neigs2,eigs+B_neigs,eigv+B_neigs*B_N,&B_N,work,&B_lwork,B_iwork,B_ifail,&B_ierr));
    3414: #endif
    3415:                 PetscLogFlops((4.0*subset_size*subset_size*subset_size)/3.0);
    3416:                 B_neigs += B_neigs2;
    3417:               }
    3418:               break;
    3419:             case 2:
    3420:               if (scal) {
    3421:                 bb[0] = PETSC_MIN_REAL;
    3422:                 bb[1] = 0;
    3423: #if defined(PETSC_USE_COMPLEX)
    3424:                 PetscStackCallBLAS("LAPACKsygvx",LAPACKsygvx_(&B_itype,"V","V","L",&B_N,St,&B_N,S,&B_N,&bb[0],&bb[1],&B_IL,&B_IU,&eps,&B_neigs,eigs,eigv,&B_N,work,&B_lwork,rwork,B_iwork,B_ifail,&B_ierr));
    3425: #else
    3426:                 PetscStackCallBLAS("LAPACKsygvx",LAPACKsygvx_(&B_itype,"V","V","L",&B_N,St,&B_N,S,&B_N,&bb[0],&bb[1],&B_IL,&B_IU,&eps,&B_neigs,eigs,eigv,&B_N,work,&B_lwork,B_iwork,B_ifail,&B_ierr));
    3427: #endif
    3428:                 PetscLogFlops((4.0*subset_size*subset_size*subset_size)/3.0);
    3429:               } else {
    3430:                 PetscBLASInt B_neigs2 = 0;
    3431:                 PetscBool    import = PETSC_FALSE;

    3433:                 lthresh = PetscMax(lthresh,0.0);
    3434:                 if (lthresh > 0.0) {
    3435:                   bb[0] = PETSC_MIN_REAL;
    3436:                   bb[1] = lthresh*lthresh;

    3438:                   import = PETSC_TRUE;
    3439: #if defined(PETSC_USE_COMPLEX)
    3440:                   PetscStackCallBLAS("LAPACKsygvx",LAPACKsygvx_(&B_itype,"V","V","L",&B_N,St,&B_N,S,&B_N,&bb[0],&bb[1],&B_IL,&B_IU,&eps,&B_neigs,eigs,eigv,&B_N,work,&B_lwork,rwork,B_iwork,B_ifail,&B_ierr));
    3441: #else
    3442:                   PetscStackCallBLAS("LAPACKsygvx",LAPACKsygvx_(&B_itype,"V","V","L",&B_N,St,&B_N,S,&B_N,&bb[0],&bb[1],&B_IL,&B_IU,&eps,&B_neigs,eigs,eigv,&B_N,work,&B_lwork,B_iwork,B_ifail,&B_ierr));
    3443: #endif
    3444:                   PetscLogFlops((4.0*subset_size*subset_size*subset_size)/3.0);
    3445:                 }
    3446:                 bb[0] = PetscMax(lthresh*lthresh,uthresh);
    3447:                 bb[1] = PETSC_MAX_REAL;
    3448:                 if (import) {
    3449:                   PetscArraycpy(S,Sarray+cumarray,subset_size*subset_size);
    3450:                   PetscArraycpy(St,Starray+cumarray,subset_size*subset_size);
    3451:                 }
    3452: #if defined(PETSC_USE_COMPLEX)
    3453:                 PetscStackCallBLAS("LAPACKsygvx",LAPACKsygvx_(&B_itype,"V","V","L",&B_N,St,&B_N,S,&B_N,&bb[0],&bb[1],&B_IL,&B_IU,&eps,&B_neigs2,eigs+B_neigs,eigv+B_neigs*B_N,&B_N,work,&B_lwork,rwork,B_iwork,B_ifail,&B_ierr));
    3454: #else
    3455:                 PetscStackCallBLAS("LAPACKsygvx",LAPACKsygvx_(&B_itype,"V","V","L",&B_N,St,&B_N,S,&B_N,&bb[0],&bb[1],&B_IL,&B_IU,&eps,&B_neigs2,eigs+B_neigs,eigv+B_neigs*B_N,&B_N,work,&B_lwork,B_iwork,B_ifail,&B_ierr));
    3456: #endif
    3457:                 PetscLogFlops((4.0*subset_size*subset_size*subset_size)/3.0);
    3458:                 B_neigs += B_neigs2;
    3459:               }
    3460:               break;
    3461:             case 3:
    3462:               if (scal) {
    3463:                 PetscOptionsGetInt(NULL,((PetscObject)pc)->prefix,"-pc_bddc_adaptive_recipe3_min_scal",&recipe_m,NULL);
    3464:               } else {
    3465:                 PetscOptionsGetInt(NULL,((PetscObject)pc)->prefix,"-pc_bddc_adaptive_recipe3_min",&recipe_m,NULL);
    3466:               }
    3467:               if (!scal) {
    3468:                 bb[0] = uthresh;
    3469:                 bb[1] = PETSC_MAX_REAL;
    3470: #if defined(PETSC_USE_COMPLEX)
    3471:                 PetscStackCallBLAS("LAPACKsygvx",LAPACKsygvx_(&B_itype,"V","V","L",&B_N,St,&B_N,S,&B_N,&bb[0],&bb[1],&B_IL,&B_IU,&eps,&B_neigs,eigs,eigv,&B_N,work,&B_lwork,rwork,B_iwork,B_ifail,&B_ierr));
    3472: #else
    3473:                 PetscStackCallBLAS("LAPACKsygvx",LAPACKsygvx_(&B_itype,"V","V","L",&B_N,St,&B_N,S,&B_N,&bb[0],&bb[1],&B_IL,&B_IU,&eps,&B_neigs,eigs,eigv,&B_N,work,&B_lwork,B_iwork,B_ifail,&B_ierr));
    3474: #endif
    3475:                 PetscLogFlops((4.0*subset_size*subset_size*subset_size)/3.0);
    3476:               }
    3477:               if (recipe_m > 0 && B_N - B_neigs > 0) {
    3478:                 PetscBLASInt B_neigs2 = 0;

    3480:                 B_IL = 1;
    3481:                 PetscBLASIntCast(PetscMin(recipe_m,B_N - B_neigs),&B_IU);
    3482:                 PetscArraycpy(S,Sarray+cumarray,subset_size*subset_size);
    3483:                 PetscArraycpy(St,Starray+cumarray,subset_size*subset_size);
    3484: #if defined(PETSC_USE_COMPLEX)
    3485:                 PetscStackCallBLAS("LAPACKsygvx",LAPACKsygvx_(&B_itype,"V","I","L",&B_N,St,&B_N,S,&B_N,&lower,&upper,&B_IL,&B_IU,&eps,&B_neigs2,eigs+B_neigs,eigv+B_neigs*B_N,&B_N,work,&B_lwork,rwork,B_iwork,B_ifail,&B_ierr));
    3486: #else
    3487:                 PetscStackCallBLAS("LAPACKsygvx",LAPACKsygvx_(&B_itype,"V","I","L",&B_N,St,&B_N,S,&B_N,&lower,&upper,&B_IL,&B_IU,&eps,&B_neigs2,eigs+B_neigs,eigv+B_neigs*B_N,&B_N,work,&B_lwork,B_iwork,B_ifail,&B_ierr));
    3488: #endif
    3489:                 PetscLogFlops((4.0*subset_size*subset_size*subset_size)/3.0);
    3490:                 B_neigs += B_neigs2;
    3491:               }
    3492:               break;
    3493:             case 4:
    3494:               bb[0] = PETSC_MIN_REAL; bb[1] = lthresh;
    3495: #if defined(PETSC_USE_COMPLEX)
    3496:               PetscStackCallBLAS("LAPACKsygvx",LAPACKsygvx_(&B_itype,"V","V","L",&B_N,St,&B_N,S,&B_N,&bb[0],&bb[1],&B_IL,&B_IU,&eps,&B_neigs,eigs,eigv,&B_N,work,&B_lwork,rwork,B_iwork,B_ifail,&B_ierr));
    3497: #else
    3498:               PetscStackCallBLAS("LAPACKsygvx",LAPACKsygvx_(&B_itype,"V","V","L",&B_N,St,&B_N,S,&B_N,&bb[0],&bb[1],&B_IL,&B_IU,&eps,&B_neigs,eigs,eigv,&B_N,work,&B_lwork,B_iwork,B_ifail,&B_ierr));
    3499: #endif
    3500:               PetscLogFlops((4.0*subset_size*subset_size*subset_size)/3.0);
    3501:               {
    3502:                 PetscBLASInt B_neigs2 = 0;

    3504:                 bb[0] = PetscMax(lthresh+PETSC_SMALL,uthresh); bb[1] = PETSC_MAX_REAL;
    3505:                 PetscArraycpy(S,Sarray+cumarray,subset_size*subset_size);
    3506:                 PetscArraycpy(St,Starray+cumarray,subset_size*subset_size);
    3507: #if defined(PETSC_USE_COMPLEX)
    3508:                 PetscStackCallBLAS("LAPACKsygvx",LAPACKsygvx_(&B_itype,"V","V","L",&B_N,St,&B_N,S,&B_N,&bb[0],&bb[1],&B_IL,&B_IU,&eps,&B_neigs2,eigs+B_neigs,eigv+B_neigs*B_N,&B_N,work,&B_lwork,rwork,B_iwork,B_ifail,&B_ierr));
    3509: #else
    3510:                 PetscStackCallBLAS("LAPACKsygvx",LAPACKsygvx_(&B_itype,"V","V","L",&B_N,St,&B_N,S,&B_N,&bb[0],&bb[1],&B_IL,&B_IU,&eps,&B_neigs2,eigs+B_neigs,eigv+B_neigs*B_N,&B_N,work,&B_lwork,B_iwork,B_ifail,&B_ierr));
    3511: #endif
    3512:                 PetscLogFlops((4.0*subset_size*subset_size*subset_size)/3.0);
    3513:                 B_neigs += B_neigs2;
    3514:               }
    3515:               break;
    3516:             case 5: /* same as before: first compute all eigenvalues, then filter */
    3517: #if defined(PETSC_USE_COMPLEX)
    3518:               PetscStackCallBLAS("LAPACKsygvx",LAPACKsygvx_(&B_itype,"V","A","L",&B_N,St,&B_N,S,&B_N,&bb[0],&bb[1],&B_IL,&B_IU,&eps,&B_neigs,eigs,eigv,&B_N,work,&B_lwork,rwork,B_iwork,B_ifail,&B_ierr));
    3519: #else
    3520:               PetscStackCallBLAS("LAPACKsygvx",LAPACKsygvx_(&B_itype,"V","A","L",&B_N,St,&B_N,S,&B_N,&bb[0],&bb[1],&B_IL,&B_IU,&eps,&B_neigs,eigs,eigv,&B_N,work,&B_lwork,B_iwork,B_ifail,&B_ierr));
    3521: #endif
    3522:               PetscLogFlops((4.0*subset_size*subset_size*subset_size)/3.0);
    3523:               {
    3524:                 PetscInt e,k,ne;
    3525:                 for (e=0,ne=0;e<B_neigs;e++) {
    3526:                   if (eigs[e] < lthresh || eigs[e] > uthresh) {
    3527:                     for (k=0;k<B_N;k++) S[ne*B_N+k] = eigv[e*B_N+k];
    3528:                     eigs[ne] = eigs[e];
    3529:                     ne++;
    3530:                   }
    3531:                 }
    3532:                 PetscArraycpy(eigv,S,B_N*ne);
    3533:                 B_neigs = ne;
    3534:               }
    3535:               break;
    3536:             default:
    3537:               SETERRQ1(PetscObjectComm((PetscObject)pc),PETSC_ERR_SUP,"Unknown recipe %D",recipe);
    3538:               break;
    3539:             }
    3540:           }
    3541:         } else if (!same_data) { /* this is just to see all the eigenvalues */
    3542:           B_IU = PetscMax(1,PetscMin(B_N,nmax));
    3543:           B_IL = 1;
    3544: #if defined(PETSC_USE_COMPLEX)
    3545:           PetscStackCallBLAS("LAPACKsygvx",LAPACKsygvx_(&B_itype,"V","I","L",&B_N,St,&B_N,S,&B_N,&lower,&upper,&B_IL,&B_IU,&eps,&B_neigs,eigs,eigv,&B_N,work,&B_lwork,rwork,B_iwork,B_ifail,&B_ierr));
    3546: #else
    3547:           PetscStackCallBLAS("LAPACKsygvx",LAPACKsygvx_(&B_itype,"V","I","L",&B_N,St,&B_N,S,&B_N,&lower,&upper,&B_IL,&B_IU,&eps,&B_neigs,eigs,eigv,&B_N,work,&B_lwork,B_iwork,B_ifail,&B_ierr));
    3548: #endif
    3549:           PetscLogFlops((4.0*subset_size*subset_size*subset_size)/3.0);
    3550:         } else { /* same_data is true, so just get the adaptive functional requested by the user */
    3551:           PetscInt k;
    3552:           if (!sub_schurs->change_primal_sub) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_PLIB,"This should not happen");
    3553:           ISGetLocalSize(sub_schurs->change_primal_sub[i],&nmax);
    3554:           PetscBLASIntCast(nmax,&B_neigs);
    3555:           nmin = nmax;
    3556:           PetscArrayzero(eigv,subset_size*nmax);
    3557:           for (k=0;k<nmax;k++) {
    3558:             eigs[k] = 1./PETSC_SMALL;
    3559:             eigv[k*(subset_size+1)] = 1.0;
    3560:           }
    3561:         }
    3562:         PetscFPTrapPop();
    3563:         if (B_ierr) {
    3564:           if (B_ierr < 0 ) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_LIB,"Error in SYGVX Lapack routine: illegal value for argument %d",-(int)B_ierr);
    3565:           else if (B_ierr <= B_N) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_LIB,"Error in SYGVX Lapack routine: %d eigenvalues failed to converge",(int)B_ierr);
    3566:           else SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_LIB,"Error in SYGVX Lapack routine: leading minor of order %d is not positive definite",(int)B_ierr-B_N-1);
    3567:         }

    3569:         if (B_neigs > nmax) {
    3570:           if (pcbddc->dbg_flag) {
    3571:             PetscViewerASCIISynchronizedPrintf(pcbddc->dbg_viewer,"   found %d eigs, more than maximum required %D.\n",B_neigs,nmax);
    3572:           }
    3573:           if (pcbddc->use_deluxe_scaling) eigs_start = scal ? 0 : B_neigs-nmax;
    3574:           B_neigs = nmax;
    3575:         }

    3577:         nmin_s = PetscMin(nmin,B_N);
    3578:         if (B_neigs < nmin_s) {
    3579:           PetscBLASInt B_neigs2 = 0;

    3581:           if (pcbddc->use_deluxe_scaling) {
    3582:             if (scal) {
    3583:               B_IU = nmin_s;
    3584:               B_IL = B_neigs + 1;
    3585:             } else {
    3586:               B_IL = B_N - nmin_s + 1;
    3587:               B_IU = B_N - B_neigs;
    3588:             }
    3589:           } else {
    3590:             B_IL = B_neigs + 1;
    3591:             B_IU = nmin_s;
    3592:           }
    3593:           if (pcbddc->dbg_flag) {
    3594:             PetscViewerASCIISynchronizedPrintf(pcbddc->dbg_viewer,"   found %d eigs, less than minimum required %D. Asking for %d to %d incl (fortran like)\n",B_neigs,nmin,B_IL,B_IU);
    3595:           }
    3596:           if (sub_schurs->is_symmetric) {
    3597:             PetscInt j,k;
    3598:             for (j=0;j<subset_size;j++) {
    3599:               for (k=j;k<subset_size;k++) {
    3600:                 S [j*subset_size+k] = Sarray [cumarray+j*subset_size+k];
    3601:                 St[j*subset_size+k] = Starray[cumarray+j*subset_size+k];
    3602:               }
    3603:             }
    3604:           } else {
    3605:             PetscArraycpy(S,Sarray+cumarray,subset_size*subset_size);
    3606:             PetscArraycpy(St,Starray+cumarray,subset_size*subset_size);
    3607:           }
    3608:           PetscFPTrapPush(PETSC_FP_TRAP_OFF);
    3609: #if defined(PETSC_USE_COMPLEX)
    3610:           PetscStackCallBLAS("LAPACKsygvx",LAPACKsygvx_(&B_itype,"V","I","L",&B_N,St,&B_N,S,&B_N,&lower,&upper,&B_IL,&B_IU,&eps,&B_neigs2,eigs+B_neigs,eigv+B_neigs*subset_size,&B_N,work,&B_lwork,rwork,B_iwork,B_ifail,&B_ierr));
    3611: #else
    3612:           PetscStackCallBLAS("LAPACKsygvx",LAPACKsygvx_(&B_itype,"V","I","L",&B_N,St,&B_N,S,&B_N,&lower,&upper,&B_IL,&B_IU,&eps,&B_neigs2,eigs+B_neigs,eigv+B_neigs*subset_size,&B_N,work,&B_lwork,B_iwork,B_ifail,&B_ierr));
    3613: #endif
    3614:           PetscLogFlops((4.0*subset_size*subset_size*subset_size)/3.0);
    3615:           PetscFPTrapPop();
    3616:           B_neigs += B_neigs2;
    3617:         }
    3618:         if (B_ierr) {
    3619:           if (B_ierr < 0 ) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_LIB,"Error in SYGVX Lapack routine: illegal value for argument %d",-(int)B_ierr);
    3620:           else if (B_ierr <= B_N) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_LIB,"Error in SYGVX Lapack routine: %d eigenvalues failed to converge",(int)B_ierr);
    3621:           else SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_LIB,"Error in SYGVX Lapack routine: leading minor of order %d is not positive definite",(int)B_ierr-B_N-1);
    3622:         }
    3623:         if (pcbddc->dbg_flag) {
    3624:           PetscViewerASCIISynchronizedPrintf(pcbddc->dbg_viewer,"   -> Got %d eigs\n",B_neigs);
    3625:           for (j=0;j<B_neigs;j++) {
    3626:             if (eigs[j] == 0.0) {
    3627:               PetscViewerASCIISynchronizedPrintf(pcbddc->dbg_viewer,"     Inf\n");
    3628:             } else {
    3629:               if (pcbddc->use_deluxe_scaling) {
    3630:                 PetscViewerASCIISynchronizedPrintf(pcbddc->dbg_viewer,"     %1.6e\n",eigs[j+eigs_start]);
    3631:               } else {
    3632:                 PetscViewerASCIISynchronizedPrintf(pcbddc->dbg_viewer,"     %1.6e\n",1./eigs[j+eigs_start]);
    3633:               }
    3634:             }
    3635:           }
    3636:         }
    3637:       } else SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"Not yet implemented");
    3638:     }
    3639:     /* change the basis back to the original one */
    3640:     if (sub_schurs->change) {
    3641:       Mat change,phi,phit;

    3643:       if (pcbddc->dbg_flag > 2) {
    3644:         PetscInt ii;
    3645:         for (ii=0;ii<B_neigs;ii++) {
    3646:           PetscViewerASCIISynchronizedPrintf(pcbddc->dbg_viewer,"   -> Eigenvector (old basis) %d/%d (%d)\n",ii,B_neigs,B_N);
    3647:           for (j=0;j<B_N;j++) {
    3648: #if defined(PETSC_USE_COMPLEX)
    3649:             PetscReal r = PetscRealPart(eigv[(ii+eigs_start)*subset_size+j]);
    3650:             PetscReal c = PetscImaginaryPart(eigv[(ii+eigs_start)*subset_size+j]);
    3651:             PetscViewerASCIISynchronizedPrintf(pcbddc->dbg_viewer,"       %1.4e + %1.4e i\n",r,c);
    3652: #else
    3653:             PetscViewerASCIISynchronizedPrintf(pcbddc->dbg_viewer,"       %1.4e\n",eigv[(ii+eigs_start)*subset_size+j]);
    3654: #endif
    3655:           }
    3656:         }
    3657:       }
    3658:       KSPGetOperators(sub_schurs->change[i],&change,NULL);
    3659:       MatCreateSeqDense(PETSC_COMM_SELF,subset_size,B_neigs,eigv+eigs_start*subset_size,&phit);
    3660:       MatMatMult(change,phit,MAT_INITIAL_MATRIX,PETSC_DEFAULT,&phi);
    3661:       MatCopy(phi,phit,SAME_NONZERO_PATTERN);
    3662:       MatDestroy(&phit);
    3663:       MatDestroy(&phi);
    3664:     }
    3665:     maxneigs = PetscMax(B_neigs,maxneigs);
    3666:     pcbddc->adaptive_constraints_n[i+nv] = B_neigs;
    3667:     if (B_neigs) {
    3668:       PetscArraycpy(pcbddc->adaptive_constraints_data+pcbddc->adaptive_constraints_data_ptr[cum],eigv+eigs_start*subset_size,B_neigs*subset_size);

    3670:       if (pcbddc->dbg_flag > 1) {
    3671:         PetscInt ii;
    3672:         for (ii=0;ii<B_neigs;ii++) {
    3673:           PetscViewerASCIISynchronizedPrintf(pcbddc->dbg_viewer,"   -> Eigenvector %d/%d (%d)\n",ii,B_neigs,B_N);
    3674:           for (j=0;j<B_N;j++) {
    3675: #if defined(PETSC_USE_COMPLEX)
    3676:             PetscReal r = PetscRealPart(pcbddc->adaptive_constraints_data[ii*subset_size+j+pcbddc->adaptive_constraints_data_ptr[cum]]);
    3677:             PetscReal c = PetscImaginaryPart(pcbddc->adaptive_constraints_data[ii*subset_size+j+pcbddc->adaptive_constraints_data_ptr[cum]]);
    3678:             PetscViewerASCIISynchronizedPrintf(pcbddc->dbg_viewer,"       %1.4e + %1.4e i\n",r,c);
    3679: #else
    3680:             PetscViewerASCIISynchronizedPrintf(pcbddc->dbg_viewer,"       %1.4e\n",pcbddc->adaptive_constraints_data[ii*subset_size+j+pcbddc->adaptive_constraints_data_ptr[cum]]);
    3681: #endif
    3682:           }
    3683:         }
    3684:       }
    3685:       PetscArraycpy(pcbddc->adaptive_constraints_idxs+pcbddc->adaptive_constraints_idxs_ptr[cum],idxs,subset_size);
    3686:       pcbddc->adaptive_constraints_idxs_ptr[cum+1] = pcbddc->adaptive_constraints_idxs_ptr[cum] + subset_size;
    3687:       pcbddc->adaptive_constraints_data_ptr[cum+1] = pcbddc->adaptive_constraints_data_ptr[cum] + subset_size*B_neigs;
    3688:       cum++;
    3689:     }
    3690:     ISRestoreIndices(sub_schurs->is_subs[i],&idxs);
    3691:     /* shift for next computation */
    3692:     cumarray += subset_size*subset_size;
    3693:   }
    3694:   if (pcbddc->dbg_flag) {
    3695:     PetscViewerFlush(pcbddc->dbg_viewer);
    3696:   }

    3698:   if (mss) {
    3699:     MatSeqAIJRestoreArray(sub_schurs->sum_S_Ej_inv_all,&Sarray);
    3700:     MatSeqAIJRestoreArray(sub_schurs->sum_S_Ej_tilda_all,&Starray);
    3701:     /* destroy matrices (junk) */
    3702:     MatDestroy(&sub_schurs->sum_S_Ej_inv_all);
    3703:     MatDestroy(&sub_schurs->sum_S_Ej_tilda_all);
    3704:   }
    3705:   if (allocated_S_St) {
    3706:     PetscFree2(S,St);
    3707:   }
    3708:   PetscFree5(eigv,eigs,work,B_iwork,B_ifail);
    3709: #if defined(PETSC_USE_COMPLEX)
    3710:   PetscFree(rwork);
    3711: #endif
    3712:   if (pcbddc->dbg_flag) {
    3713:     PetscInt maxneigs_r;
    3714:     MPIU_Allreduce(&maxneigs,&maxneigs_r,1,MPIU_INT,MPI_MAX,PetscObjectComm((PetscObject)pc));
    3715:     PetscViewerASCIIPrintf(pcbddc->dbg_viewer,"Maximum number of constraints per cc %D\n",maxneigs_r);
    3716:   }
    3717:   PetscLogEventEnd(PC_BDDC_AdaptiveSetUp[pcbddc->current_level],pc,0,0,0);
    3718:   return(0);
    3719: }

    3721: PetscErrorCode PCBDDCSetUpSolvers(PC pc)
    3722: {
    3723:   PetscScalar    *coarse_submat_vals;

    3727:   /* Setup local scatters R_to_B and (optionally) R_to_D */
    3728:   /* PCBDDCSetUpLocalWorkVectors should be called first! */
    3729:   PCBDDCSetUpLocalScatters(pc);

    3731:   /* Setup local neumann solver ksp_R */
    3732:   /* PCBDDCSetUpLocalScatters should be called first! */
    3733:   PCBDDCSetUpLocalSolvers(pc,PETSC_FALSE,PETSC_TRUE);

    3735:   /*
    3736:      Setup local correction and local part of coarse basis.
    3737:      Gives back the dense local part of the coarse matrix in column major ordering
    3738:   */
    3739:   PCBDDCSetUpCorrection(pc,&coarse_submat_vals);

    3741:   /* Compute total number of coarse nodes and setup coarse solver */
    3742:   PCBDDCSetUpCoarseSolver(pc,coarse_submat_vals);

    3744:   /* free */
    3745:   PetscFree(coarse_submat_vals);
    3746:   return(0);
    3747: }

    3749: PetscErrorCode PCBDDCResetCustomization(PC pc)
    3750: {
    3751:   PC_BDDC        *pcbddc = (PC_BDDC*)pc->data;

    3755:   ISDestroy(&pcbddc->user_primal_vertices);
    3756:   ISDestroy(&pcbddc->user_primal_vertices_local);
    3757:   ISDestroy(&pcbddc->NeumannBoundaries);
    3758:   ISDestroy(&pcbddc->NeumannBoundariesLocal);
    3759:   ISDestroy(&pcbddc->DirichletBoundaries);
    3760:   MatNullSpaceDestroy(&pcbddc->onearnullspace);
    3761:   PetscFree(pcbddc->onearnullvecs_state);
    3762:   ISDestroy(&pcbddc->DirichletBoundariesLocal);
    3763:   PCBDDCSetDofsSplitting(pc,0,NULL);
    3764:   PCBDDCSetDofsSplittingLocal(pc,0,NULL);
    3765:   return(0);
    3766: }

    3768: PetscErrorCode PCBDDCResetTopography(PC pc)
    3769: {
    3770:   PC_BDDC        *pcbddc = (PC_BDDC*)pc->data;
    3771:   PetscInt       i;

    3775:   MatDestroy(&pcbddc->nedcG);
    3776:   ISDestroy(&pcbddc->nedclocal);
    3777:   MatDestroy(&pcbddc->discretegradient);
    3778:   MatDestroy(&pcbddc->user_ChangeOfBasisMatrix);
    3779:   MatDestroy(&pcbddc->ChangeOfBasisMatrix);
    3780:   MatDestroy(&pcbddc->switch_static_change);
    3781:   VecDestroy(&pcbddc->work_change);
    3782:   MatDestroy(&pcbddc->ConstraintMatrix);
    3783:   MatDestroy(&pcbddc->divudotp);
    3784:   ISDestroy(&pcbddc->divudotp_vl2l);
    3785:   PCBDDCGraphDestroy(&pcbddc->mat_graph);
    3786:   for (i=0;i<pcbddc->n_local_subs;i++) {
    3787:     ISDestroy(&pcbddc->local_subs[i]);
    3788:   }
    3789:   pcbddc->n_local_subs = 0;
    3790:   PetscFree(pcbddc->local_subs);
    3791:   PCBDDCSubSchursDestroy(&pcbddc->sub_schurs);
    3792:   pcbddc->graphanalyzed        = PETSC_FALSE;
    3793:   pcbddc->recompute_topography = PETSC_TRUE;
    3794:   pcbddc->corner_selected      = PETSC_FALSE;
    3795:   return(0);
    3796: }

    3798: PetscErrorCode PCBDDCResetSolvers(PC pc)
    3799: {
    3800:   PC_BDDC        *pcbddc = (PC_BDDC*)pc->data;

    3804:   VecDestroy(&pcbddc->coarse_vec);
    3805:   if (pcbddc->coarse_phi_B) {
    3806:     PetscScalar *array;
    3807:     MatDenseGetArray(pcbddc->coarse_phi_B,&array);
    3808:     PetscFree(array);
    3809:   }
    3810:   MatDestroy(&pcbddc->coarse_phi_B);
    3811:   MatDestroy(&pcbddc->coarse_phi_D);
    3812:   MatDestroy(&pcbddc->coarse_psi_B);
    3813:   MatDestroy(&pcbddc->coarse_psi_D);
    3814:   VecDestroy(&pcbddc->vec1_P);
    3815:   VecDestroy(&pcbddc->vec1_C);
    3816:   MatDestroy(&pcbddc->local_auxmat2);
    3817:   MatDestroy(&pcbddc->local_auxmat1);
    3818:   VecDestroy(&pcbddc->vec1_R);
    3819:   VecDestroy(&pcbddc->vec2_R);
    3820:   ISDestroy(&pcbddc->is_R_local);
    3821:   VecScatterDestroy(&pcbddc->R_to_B);
    3822:   VecScatterDestroy(&pcbddc->R_to_D);
    3823:   VecScatterDestroy(&pcbddc->coarse_loc_to_glob);
    3824:   KSPReset(pcbddc->ksp_D);
    3825:   KSPReset(pcbddc->ksp_R);
    3826:   KSPReset(pcbddc->coarse_ksp);
    3827:   MatDestroy(&pcbddc->local_mat);
    3828:   PetscFree(pcbddc->primal_indices_local_idxs);
    3829:   PetscFree2(pcbddc->local_primal_ref_node,pcbddc->local_primal_ref_mult);
    3830:   PetscFree(pcbddc->global_primal_indices);
    3831:   ISDestroy(&pcbddc->coarse_subassembling);
    3832:   MatDestroy(&pcbddc->benign_change);
    3833:   VecDestroy(&pcbddc->benign_vec);
    3834:   PCBDDCBenignShellMat(pc,PETSC_TRUE);
    3835:   MatDestroy(&pcbddc->benign_B0);
    3836:   PetscSFDestroy(&pcbddc->benign_sf);
    3837:   if (pcbddc->benign_zerodiag_subs) {
    3838:     PetscInt i;
    3839:     for (i=0;i<pcbddc->benign_n;i++) {
    3840:       ISDestroy(&pcbddc->benign_zerodiag_subs[i]);
    3841:     }
    3842:     PetscFree(pcbddc->benign_zerodiag_subs);
    3843:   }
    3844:   PetscFree3(pcbddc->benign_p0_lidx,pcbddc->benign_p0_gidx,pcbddc->benign_p0);
    3845:   return(0);
    3846: }

    3848: PetscErrorCode PCBDDCSetUpLocalWorkVectors(PC pc)
    3849: {
    3850:   PC_BDDC        *pcbddc = (PC_BDDC*)pc->data;
    3851:   PC_IS          *pcis = (PC_IS*)pc->data;
    3852:   VecType        impVecType;
    3853:   PetscInt       n_constraints,n_R,old_size;

    3857:   n_constraints = pcbddc->local_primal_size - pcbddc->benign_n - pcbddc->n_vertices;
    3858:   n_R = pcis->n - pcbddc->n_vertices;
    3859:   VecGetType(pcis->vec1_N,&impVecType);
    3860:   /* local work vectors (try to avoid unneeded work)*/
    3861:   /* R nodes */
    3862:   old_size = -1;
    3863:   if (pcbddc->vec1_R) {
    3864:     VecGetSize(pcbddc->vec1_R,&old_size);
    3865:   }
    3866:   if (n_R != old_size) {
    3867:     VecDestroy(&pcbddc->vec1_R);
    3868:     VecDestroy(&pcbddc->vec2_R);
    3869:     VecCreate(PetscObjectComm((PetscObject)pcis->vec1_N),&pcbddc->vec1_R);
    3870:     VecSetSizes(pcbddc->vec1_R,PETSC_DECIDE,n_R);
    3871:     VecSetType(pcbddc->vec1_R,impVecType);
    3872:     VecDuplicate(pcbddc->vec1_R,&pcbddc->vec2_R);
    3873:   }
    3874:   /* local primal dofs */
    3875:   old_size = -1;
    3876:   if (pcbddc->vec1_P) {
    3877:     VecGetSize(pcbddc->vec1_P,&old_size);
    3878:   }
    3879:   if (pcbddc->local_primal_size != old_size) {
    3880:     VecDestroy(&pcbddc->vec1_P);
    3881:     VecCreate(PetscObjectComm((PetscObject)pcis->vec1_N),&pcbddc->vec1_P);
    3882:     VecSetSizes(pcbddc->vec1_P,PETSC_DECIDE,pcbddc->local_primal_size);
    3883:     VecSetType(pcbddc->vec1_P,impVecType);
    3884:   }
    3885:   /* local explicit constraints */
    3886:   old_size = -1;
    3887:   if (pcbddc->vec1_C) {
    3888:     VecGetSize(pcbddc->vec1_C,&old_size);
    3889:   }
    3890:   if (n_constraints && n_constraints != old_size) {
    3891:     VecDestroy(&pcbddc->vec1_C);
    3892:     VecCreate(PetscObjectComm((PetscObject)pcis->vec1_N),&pcbddc->vec1_C);
    3893:     VecSetSizes(pcbddc->vec1_C,PETSC_DECIDE,n_constraints);
    3894:     VecSetType(pcbddc->vec1_C,impVecType);
    3895:   }
    3896:   return(0);
    3897: }

    3899: PetscErrorCode PCBDDCSetUpCorrection(PC pc, PetscScalar **coarse_submat_vals_n)
    3900: {
    3901:   PetscErrorCode  ierr;
    3902:   /* pointers to pcis and pcbddc */
    3903:   PC_IS*          pcis = (PC_IS*)pc->data;
    3904:   PC_BDDC*        pcbddc = (PC_BDDC*)pc->data;
    3905:   PCBDDCSubSchurs sub_schurs = pcbddc->sub_schurs;
    3906:   /* submatrices of local problem */
    3907:   Mat             A_RV,A_VR,A_VV,local_auxmat2_R;
    3908:   /* submatrices of local coarse problem */
    3909:   Mat             S_VV,S_CV,S_VC,S_CC;
    3910:   /* working matrices */
    3911:   Mat             C_CR;
    3912:   /* additional working stuff */
    3913:   PC              pc_R;
    3914:   Mat             F,Brhs = NULL;
    3915:   Vec             dummy_vec;
    3916:   PetscBool       isLU,isCHOL,need_benign_correction,sparserhs;
    3917:   PetscScalar     *coarse_submat_vals; /* TODO: use a PETSc matrix */
    3918:   PetscScalar     *work;
    3919:   PetscInt        *idx_V_B;
    3920:   PetscInt        lda_rhs,n,n_vertices,n_constraints,*p0_lidx_I;
    3921:   PetscInt        i,n_R,n_D,n_B;
    3922:   PetscScalar     one=1.0,m_one=-1.0;

    3925:   if (!pcbddc->symmetric_primal && pcbddc->benign_n) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"Non-symmetric primal basis computation with benign trick not yet implemented");
    3926:   PetscLogEventBegin(PC_BDDC_CorrectionSetUp[pcbddc->current_level],pc,0,0,0);

    3928:   /* Set Non-overlapping dimensions */
    3929:   n_vertices = pcbddc->n_vertices;
    3930:   n_constraints = pcbddc->local_primal_size - pcbddc->benign_n - n_vertices;
    3931:   n_B = pcis->n_B;
    3932:   n_D = pcis->n - n_B;
    3933:   n_R = pcis->n - n_vertices;

    3935:   /* vertices in boundary numbering */
    3936:   PetscMalloc1(n_vertices,&idx_V_B);
    3937:   ISGlobalToLocalMappingApply(pcis->BtoNmap,IS_GTOLM_DROP,n_vertices,pcbddc->local_primal_ref_node,&i,idx_V_B);
    3938:   if (i != n_vertices) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_PLIB,"Error in boundary numbering for BDDC vertices! %D != %D",n_vertices,i);

    3940:   /* Subdomain contribution (Non-overlapping) to coarse matrix  */
    3941:   PetscCalloc1(pcbddc->local_primal_size*pcbddc->local_primal_size,&coarse_submat_vals);
    3942:   MatCreateSeqDense(PETSC_COMM_SELF,n_vertices,n_vertices,coarse_submat_vals,&S_VV);
    3943:   MatSeqDenseSetLDA(S_VV,pcbddc->local_primal_size);
    3944:   MatCreateSeqDense(PETSC_COMM_SELF,n_constraints,n_vertices,coarse_submat_vals+n_vertices,&S_CV);
    3945:   MatSeqDenseSetLDA(S_CV,pcbddc->local_primal_size);
    3946:   MatCreateSeqDense(PETSC_COMM_SELF,n_vertices,n_constraints,coarse_submat_vals+pcbddc->local_primal_size*n_vertices,&S_VC);
    3947:   MatSeqDenseSetLDA(S_VC,pcbddc->local_primal_size);
    3948:   MatCreateSeqDense(PETSC_COMM_SELF,n_constraints,n_constraints,coarse_submat_vals+(pcbddc->local_primal_size+1)*n_vertices,&S_CC);
    3949:   MatSeqDenseSetLDA(S_CC,pcbddc->local_primal_size);

    3951:   /* determine if can use MatSolve routines instead of calling KSPSolve on ksp_R */
    3952:   KSPGetPC(pcbddc->ksp_R,&pc_R);
    3953:   PCSetUp(pc_R);
    3954:   PetscObjectTypeCompare((PetscObject)pc_R,PCLU,&isLU);
    3955:   PetscObjectTypeCompare((PetscObject)pc_R,PCCHOLESKY,&isCHOL);
    3956:   lda_rhs = n_R;
    3957:   need_benign_correction = PETSC_FALSE;
    3958:   if (isLU || isCHOL) {
    3959:     PCFactorGetMatrix(pc_R,&F);
    3960:   } else if (sub_schurs && sub_schurs->reuse_solver) {
    3961:     PCBDDCReuseSolvers reuse_solver = sub_schurs->reuse_solver;
    3962:     MatFactorType      type;

    3964:     F = reuse_solver->F;
    3965:     MatGetFactorType(F,&type);
    3966:     if (type == MAT_FACTOR_CHOLESKY) isCHOL = PETSC_TRUE;
    3967:     if (type == MAT_FACTOR_LU) isLU = PETSC_TRUE;
    3968:     MatGetSize(F,&lda_rhs,NULL);
    3969:     need_benign_correction = (PetscBool)(!!reuse_solver->benign_n);
    3970:   } else F = NULL;

    3972:   /* determine if we can use a sparse right-hand side */
    3973:   sparserhs = PETSC_FALSE;
    3974:   if (F) {
    3975:     MatSolverType solver;

    3977:     MatFactorGetSolverType(F,&solver);
    3978:     PetscStrcmp(solver,MATSOLVERMUMPS,&sparserhs);
    3979:   }

    3981:   /* allocate workspace */
    3982:   n = 0;
    3983:   if (n_constraints) {
    3984:     n += lda_rhs*n_constraints;
    3985:   }
    3986:   if (n_vertices) {
    3987:     n = PetscMax(2*lda_rhs*n_vertices,n);
    3988:     n = PetscMax((lda_rhs+n_B)*n_vertices,n);
    3989:   }
    3990:   if (!pcbddc->symmetric_primal) {
    3991:     n = PetscMax(2*lda_rhs*pcbddc->local_primal_size,n);
    3992:   }
    3993:   PetscMalloc1(n,&work);

    3995:   /* create dummy vector to modify rhs and sol of MatMatSolve (work array will never be used) */
    3996:   dummy_vec = NULL;
    3997:   if (need_benign_correction && lda_rhs != n_R && F) {
    3998:     VecCreate(PetscObjectComm((PetscObject)pcis->vec1_N),&dummy_vec);
    3999:     VecSetSizes(dummy_vec,lda_rhs,PETSC_DECIDE);
    4000:     VecSetType(dummy_vec,((PetscObject)pcis->vec1_N)->type_name);
    4001:   }

    4003:   MatDestroy(&pcbddc->local_auxmat1);
    4004:   MatDestroy(&pcbddc->local_auxmat2);

    4006:   /* Precompute stuffs needed for preprocessing and Section 1.5 Writing Application Codes with PETSc of BDDC*/
    4007:   if (n_constraints) {
    4008:     Mat         M3,C_B;
    4009:     IS          is_aux;
    4010:     PetscScalar *array,*array2;

    4012:     /* Extract constraints on R nodes: C_{CR}  */
    4013:     ISCreateStride(PETSC_COMM_SELF,n_constraints,n_vertices,1,&is_aux);
    4014:     MatCreateSubMatrix(pcbddc->ConstraintMatrix,is_aux,pcbddc->is_R_local,MAT_INITIAL_MATRIX,&C_CR);
    4015:     MatCreateSubMatrix(pcbddc->ConstraintMatrix,is_aux,pcis->is_B_local,MAT_INITIAL_MATRIX,&C_B);

    4017:     /* Assemble         local_auxmat2_R =        (- A_{RR}^{-1} C^T_{CR}) needed by BDDC setup */
    4018:     /* Assemble pcbddc->local_auxmat2   = R_to_B (- A_{RR}^{-1} C^T_{CR}) needed by BDDC Section 1.5 Writing Application Codes with PETSc */
    4019:     if (!sparserhs) {
    4020:       PetscArrayzero(work,lda_rhs*n_constraints);
    4021:       for (i=0;i<n_constraints;i++) {
    4022:         const PetscScalar *row_cmat_values;
    4023:         const PetscInt    *row_cmat_indices;
    4024:         PetscInt          size_of_constraint,j;

    4026:         MatGetRow(C_CR,i,&size_of_constraint,&row_cmat_indices,&row_cmat_values);
    4027:         for (j=0;j<size_of_constraint;j++) {
    4028:           work[row_cmat_indices[j]+i*lda_rhs] = -row_cmat_values[j];
    4029:         }
    4030:         MatRestoreRow(C_CR,i,&size_of_constraint,&row_cmat_indices,&row_cmat_values);
    4031:       }
    4032:       MatCreateSeqDense(PETSC_COMM_SELF,lda_rhs,n_constraints,work,&Brhs);
    4033:     } else {
    4034:       Mat tC_CR;

    4036:       MatScale(C_CR,-1.0);
    4037:       if (lda_rhs != n_R) {
    4038:         PetscScalar *aa;
    4039:         PetscInt    r,*ii,*jj;
    4040:         PetscBool   done;

    4042:         MatGetRowIJ(C_CR,0,PETSC_FALSE,PETSC_FALSE,&r,(const PetscInt**)&ii,(const PetscInt**)&jj,&done);
    4043:         if (!done) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_PLIB,"GetRowIJ failed");
    4044:         MatSeqAIJGetArray(C_CR,&aa);
    4045:         MatCreateSeqAIJWithArrays(PETSC_COMM_SELF,n_constraints,lda_rhs,ii,jj,aa,&tC_CR);
    4046:         MatRestoreRowIJ(C_CR,0,PETSC_FALSE,PETSC_FALSE,&r,(const PetscInt**)&ii,(const PetscInt**)&jj,&done);
    4047:         if (!done) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_PLIB,"RestoreRowIJ failed");
    4048:       } else {
    4049:         PetscObjectReference((PetscObject)C_CR);
    4050:         tC_CR = C_CR;
    4051:       }
    4052:       MatCreateTranspose(tC_CR,&Brhs);
    4053:       MatDestroy(&tC_CR);
    4054:     }
    4055:     MatCreateSeqDense(PETSC_COMM_SELF,lda_rhs,n_constraints,NULL,&local_auxmat2_R);
    4056:     if (F) {
    4057:       if (need_benign_correction) {
    4058:         PCBDDCReuseSolvers reuse_solver = sub_schurs->reuse_solver;

    4060:         /* rhs is already zero on interior dofs, no need to change the rhs */
    4061:         PetscArrayzero(reuse_solver->benign_save_vals,pcbddc->benign_n);
    4062:       }
    4063:       MatMatSolve(F,Brhs,local_auxmat2_R);
    4064:       if (need_benign_correction) {
    4065:         PetscScalar        *marr;
    4066:         PCBDDCReuseSolvers reuse_solver = sub_schurs->reuse_solver;

    4068:         MatDenseGetArray(local_auxmat2_R,&marr);
    4069:         if (lda_rhs != n_R) {
    4070:           for (i=0;i<n_constraints;i++) {
    4071:             VecPlaceArray(dummy_vec,marr+i*lda_rhs);
    4072:             PCBDDCReuseSolversBenignAdapt(reuse_solver,dummy_vec,NULL,PETSC_TRUE,PETSC_TRUE);
    4073:             VecResetArray(dummy_vec);
    4074:           }
    4075:         } else {
    4076:           for (i=0;i<n_constraints;i++) {
    4077:             VecPlaceArray(pcbddc->vec1_R,marr+i*lda_rhs);
    4078:             PCBDDCReuseSolversBenignAdapt(reuse_solver,pcbddc->vec1_R,NULL,PETSC_TRUE,PETSC_TRUE);
    4079:             VecResetArray(pcbddc->vec1_R);
    4080:           }
    4081:         }
    4082:         MatDenseRestoreArray(local_auxmat2_R,&marr);
    4083:       }
    4084:     } else {
    4085:       PetscScalar *marr;

    4087:       MatDenseGetArray(local_auxmat2_R,&marr);
    4088:       for (i=0;i<n_constraints;i++) {
    4089:         VecPlaceArray(pcbddc->vec1_R,work+i*lda_rhs);
    4090:         VecPlaceArray(pcbddc->vec2_R,marr+i*lda_rhs);
    4091:         KSPSolve(pcbddc->ksp_R,pcbddc->vec1_R,pcbddc->vec2_R);
    4092:         KSPCheckSolve(pcbddc->ksp_R,pc,pcbddc->vec2_R);
    4093:         VecResetArray(pcbddc->vec1_R);
    4094:         VecResetArray(pcbddc->vec2_R);
    4095:       }
    4096:       MatDenseRestoreArray(local_auxmat2_R,&marr);
    4097:     }
    4098:     if (sparserhs) {
    4099:       MatScale(C_CR,-1.0);
    4100:     }
    4101:     MatDestroy(&Brhs);
    4102:     if (!pcbddc->switch_static) {
    4103:       MatCreateSeqDense(PETSC_COMM_SELF,n_B,n_constraints,NULL,&pcbddc->local_auxmat2);
    4104:       MatDenseGetArray(pcbddc->local_auxmat2,&array);
    4105:       MatDenseGetArray(local_auxmat2_R,&array2);
    4106:       for (i=0;i<n_constraints;i++) {
    4107:         VecPlaceArray(pcbddc->vec1_R,array2+i*lda_rhs);
    4108:         VecPlaceArray(pcis->vec1_B,array+i*n_B);
    4109:         VecScatterBegin(pcbddc->R_to_B,pcbddc->vec1_R,pcis->vec1_B,INSERT_VALUES,SCATTER_FORWARD);
    4110:         VecScatterEnd(pcbddc->R_to_B,pcbddc->vec1_R,pcis->vec1_B,INSERT_VALUES,SCATTER_FORWARD);
    4111:         VecResetArray(pcis->vec1_B);
    4112:         VecResetArray(pcbddc->vec1_R);
    4113:       }
    4114:       MatDenseRestoreArray(local_auxmat2_R,&array2);
    4115:       MatDenseRestoreArray(pcbddc->local_auxmat2,&array);
    4116:       MatMatMult(C_B,pcbddc->local_auxmat2,MAT_INITIAL_MATRIX,PETSC_DEFAULT,&M3);
    4117:     } else {
    4118:       if (lda_rhs != n_R) {
    4119:         IS dummy;

    4121:         ISCreateStride(PETSC_COMM_SELF,n_R,0,1,&dummy);
    4122:         MatCreateSubMatrix(local_auxmat2_R,dummy,NULL,MAT_INITIAL_MATRIX,&pcbddc->local_auxmat2);
    4123:         ISDestroy(&dummy);
    4124:       } else {
    4125:         PetscObjectReference((PetscObject)local_auxmat2_R);
    4126:         pcbddc->local_auxmat2 = local_auxmat2_R;
    4127:       }
    4128:       MatMatMult(C_CR,pcbddc->local_auxmat2,MAT_INITIAL_MATRIX,PETSC_DEFAULT,&M3);
    4129:     }
    4130:     ISDestroy(&is_aux);
    4131:     /* Assemble explicitly S_CC = ( C_{CR} A_{RR}^{-1} C^T_{CR} )^{-1}  */
    4132:     MatScale(M3,m_one);
    4133:     if (isCHOL) {
    4134:       MatCholeskyFactor(M3,NULL,NULL);
    4135:     } else {
    4136:       MatLUFactor(M3,NULL,NULL,NULL);
    4137:     }
    4138:     MatSeqDenseInvertFactors_Private(M3);
    4139:     /* Assemble local_auxmat1 = S_CC*C_{CB} needed by BDDC Section 1.5 Writing Application Codes with PETSc in KSP and in preproc */
    4140:     MatMatMult(M3,C_B,MAT_INITIAL_MATRIX,PETSC_DEFAULT,&pcbddc->local_auxmat1);
    4141:     MatDestroy(&C_B);
    4142:     MatCopy(M3,S_CC,SAME_NONZERO_PATTERN); /* S_CC can have a different LDA, MatMatSolve doesn't support it */
    4143:     MatDestroy(&M3);
    4144:   }

    4146:   /* Get submatrices from subdomain matrix */
    4147:   if (n_vertices) {
    4148: #if defined(PETSC_HAVE_VIENNACL) || defined(PETSC_HAVE_CUDA)
    4149:     PetscBool oldpin;
    4150: #endif
    4151:     PetscBool isaij;
    4152:     IS        is_aux;

    4154:     if (sub_schurs && sub_schurs->reuse_solver) { /* is_R_local is not sorted, ISComplement doesn't like it */
    4155:       IS tis;

    4157:       ISDuplicate(pcbddc->is_R_local,&tis);
    4158:       ISSort(tis);
    4159:       ISComplement(tis,0,pcis->n,&is_aux);
    4160:       ISDestroy(&tis);
    4161:     } else {
    4162:       ISComplement(pcbddc->is_R_local,0,pcis->n,&is_aux);
    4163:     }
    4164: #if defined(PETSC_HAVE_VIENNACL) || defined(PETSC_HAVE_CUDA)
    4165:     oldpin = pcbddc->local_mat->boundtocpu;
    4166: #endif
    4167:     MatBindToCPU(pcbddc->local_mat,PETSC_TRUE);
    4168:     MatCreateSubMatrix(pcbddc->local_mat,pcbddc->is_R_local,is_aux,MAT_INITIAL_MATRIX,&A_RV);
    4169:     MatCreateSubMatrix(pcbddc->local_mat,is_aux,pcbddc->is_R_local,MAT_INITIAL_MATRIX,&A_VR);
    4170:     PetscObjectBaseTypeCompare((PetscObject)A_VR,MATSEQAIJ,&isaij);
    4171:     if (!isaij) { /* TODO REMOVE: MatMatMult(A_VR,A_RRmA_RV) below may raise an error */
    4172:       MatConvert(A_VR,MATSEQAIJ,MAT_INPLACE_MATRIX,&A_VR);
    4173:     }
    4174:     MatCreateSubMatrix(pcbddc->local_mat,is_aux,is_aux,MAT_INITIAL_MATRIX,&A_VV);
    4175: #if defined(PETSC_HAVE_VIENNACL) || defined(PETSC_HAVE_CUDA)
    4176:     MatBindToCPU(pcbddc->local_mat,oldpin);
    4177: #endif
    4178:     ISDestroy(&is_aux);
    4179:   }

    4181:   /* Matrix of coarse basis functions (local) */
    4182:   if (pcbddc->coarse_phi_B) {
    4183:     PetscInt on_B,on_primal,on_D=n_D;
    4184:     if (pcbddc->coarse_phi_D) {
    4185:       MatGetSize(pcbddc->coarse_phi_D,&on_D,NULL);
    4186:     }
    4187:     MatGetSize(pcbddc->coarse_phi_B,&on_B,&on_primal);
    4188:     if (on_B != n_B || on_primal != pcbddc->local_primal_size || on_D != n_D) {
    4189:       PetscScalar *marray;

    4191:       MatDenseGetArray(pcbddc->coarse_phi_B,&marray);
    4192:       PetscFree(marray);
    4193:       MatDestroy(&pcbddc->coarse_phi_B);
    4194:       MatDestroy(&pcbddc->coarse_psi_B);
    4195:       MatDestroy(&pcbddc->coarse_phi_D);
    4196:       MatDestroy(&pcbddc->coarse_psi_D);
    4197:     }
    4198:   }

    4200:   if (!pcbddc->coarse_phi_B) {
    4201:     PetscScalar *marr;

    4203:     /* memory size */
    4204:     n = n_B*pcbddc->local_primal_size;
    4205:     if (pcbddc->switch_static || pcbddc->dbg_flag) n += n_D*pcbddc->local_primal_size;
    4206:     if (!pcbddc->symmetric_primal) n *= 2;
    4207:     PetscCalloc1(n,&marr);
    4208:     MatCreateSeqDense(PETSC_COMM_SELF,n_B,pcbddc->local_primal_size,marr,&pcbddc->coarse_phi_B);
    4209:     marr += n_B*pcbddc->local_primal_size;
    4210:     if (pcbddc->switch_static || pcbddc->dbg_flag) {
    4211:       MatCreateSeqDense(PETSC_COMM_SELF,n_D,pcbddc->local_primal_size,marr,&pcbddc->coarse_phi_D);
    4212:       marr += n_D*pcbddc->local_primal_size;
    4213:     }
    4214:     if (!pcbddc->symmetric_primal) {
    4215:       MatCreateSeqDense(PETSC_COMM_SELF,n_B,pcbddc->local_primal_size,marr,&pcbddc->coarse_psi_B);
    4216:       marr += n_B*pcbddc->local_primal_size;
    4217:       if (pcbddc->switch_static || pcbddc->dbg_flag) {
    4218:         MatCreateSeqDense(PETSC_COMM_SELF,n_D,pcbddc->local_primal_size,marr,&pcbddc->coarse_psi_D);
    4219:       }
    4220:     } else {
    4221:       PetscObjectReference((PetscObject)pcbddc->coarse_phi_B);
    4222:       pcbddc->coarse_psi_B = pcbddc->coarse_phi_B;
    4223:       if (pcbddc->switch_static || pcbddc->dbg_flag) {
    4224:         PetscObjectReference((PetscObject)pcbddc->coarse_phi_D);
    4225:         pcbddc->coarse_psi_D = pcbddc->coarse_phi_D;
    4226:       }
    4227:     }
    4228:   }

    4230:   /* We are now ready to evaluate coarse basis functions and subdomain contribution to coarse problem */
    4231:   p0_lidx_I = NULL;
    4232:   if (pcbddc->benign_n && (pcbddc->switch_static || pcbddc->dbg_flag)) {
    4233:     const PetscInt *idxs;

    4235:     ISGetIndices(pcis->is_I_local,&idxs);
    4236:     PetscMalloc1(pcbddc->benign_n,&p0_lidx_I);
    4237:     for (i=0;i<pcbddc->benign_n;i++) {
    4238:       PetscFindInt(pcbddc->benign_p0_lidx[i],pcis->n-pcis->n_B,idxs,&p0_lidx_I[i]);
    4239:     }
    4240:     ISRestoreIndices(pcis->is_I_local,&idxs);
    4241:   }

    4243:   /* vertices */
    4244:   if (n_vertices) {
    4245:     PetscBool restoreavr = PETSC_FALSE;

    4247:     MatConvert(A_VV,MATDENSE,MAT_INPLACE_MATRIX,&A_VV);

    4249:     if (n_R) {
    4250:       Mat               A_RRmA_RV,A_RV_bcorr=NULL,S_VVt; /* S_VVt with LDA=N */
    4251:       PetscBLASInt      B_N,B_one = 1;
    4252:       const PetscScalar *x;
    4253:       PetscScalar       *y;

    4255:       MatScale(A_RV,m_one);
    4256:       if (need_benign_correction) {
    4257:         ISLocalToGlobalMapping RtoN;
    4258:         IS                     is_p0;
    4259:         PetscInt               *idxs_p0,n;

    4261:         PetscMalloc1(pcbddc->benign_n,&idxs_p0);
    4262:         ISLocalToGlobalMappingCreateIS(pcbddc->is_R_local,&RtoN);
    4263:         ISGlobalToLocalMappingApply(RtoN,IS_GTOLM_DROP,pcbddc->benign_n,pcbddc->benign_p0_lidx,&n,idxs_p0);
    4264:         if (n != pcbddc->benign_n) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_PLIB,"Error in R numbering for benign p0! %D != %D",n,pcbddc->benign_n);
    4265:         ISLocalToGlobalMappingDestroy(&RtoN);
    4266:         ISCreateGeneral(PETSC_COMM_SELF,n,idxs_p0,PETSC_OWN_POINTER,&is_p0);
    4267:         MatCreateSubMatrix(A_RV,is_p0,NULL,MAT_INITIAL_MATRIX,&A_RV_bcorr);
    4268:         ISDestroy(&is_p0);
    4269:       }

    4271:       MatCreateSeqDense(PETSC_COMM_SELF,lda_rhs,n_vertices,work,&A_RRmA_RV);
    4272:       if (!sparserhs || need_benign_correction) {
    4273:         if (lda_rhs == n_R) {
    4274:           MatConvert(A_RV,MATDENSE,MAT_INPLACE_MATRIX,&A_RV);
    4275:         } else {
    4276:           PetscScalar    *av,*array;
    4277:           const PetscInt *xadj,*adjncy;
    4278:           PetscInt       n;
    4279:           PetscBool      flg_row;

    4281:           array = work+lda_rhs*n_vertices;
    4282:           PetscArrayzero(array,lda_rhs*n_vertices);
    4283:           MatConvert(A_RV,MATSEQAIJ,MAT_INPLACE_MATRIX,&A_RV);
    4284:           MatGetRowIJ(A_RV,0,PETSC_FALSE,PETSC_FALSE,&n,&xadj,&adjncy,&flg_row);
    4285:           MatSeqAIJGetArray(A_RV,&av);
    4286:           for (i=0;i<n;i++) {
    4287:             PetscInt j;
    4288:             for (j=xadj[i];j<xadj[i+1];j++) array[lda_rhs*adjncy[j]+i] = av[j];
    4289:           }
    4290:           MatRestoreRowIJ(A_RV,0,PETSC_FALSE,PETSC_FALSE,&n,&xadj,&adjncy,&flg_row);
    4291:           MatDestroy(&A_RV);
    4292:           MatCreateSeqDense(PETSC_COMM_SELF,lda_rhs,n_vertices,array,&A_RV);
    4293:         }
    4294:         if (need_benign_correction) {
    4295:           PCBDDCReuseSolvers reuse_solver = sub_schurs->reuse_solver;
    4296:           PetscScalar        *marr;

    4298:           MatDenseGetArray(A_RV,&marr);
    4299:           /* need \Phi^T A_RV = (I+L)A_RV, L given by

    4301:                  | 0 0  0 | (V)
    4302:              L = | 0 0 -1 | (P-p0)
    4303:                  | 0 0 -1 | (p0)

    4305:           */
    4306:           for (i=0;i<reuse_solver->benign_n;i++) {
    4307:             const PetscScalar *vals;
    4308:             const PetscInt    *idxs,*idxs_zero;
    4309:             PetscInt          n,j,nz;

    4311:             ISGetLocalSize(reuse_solver->benign_zerodiag_subs[i],&nz);
    4312:             ISGetIndices(reuse_solver->benign_zerodiag_subs[i],&idxs_zero);
    4313:             MatGetRow(A_RV_bcorr,i,&n,&idxs,&vals);
    4314:             for (j=0;j<n;j++) {
    4315:               PetscScalar val = vals[j];
    4316:               PetscInt    k,col = idxs[j];
    4317:               for (k=0;k<nz;k++) marr[idxs_zero[k]+lda_rhs*col] -= val;
    4318:             }
    4319:             MatRestoreRow(A_RV_bcorr,i,&n,&idxs,&vals);
    4320:             ISRestoreIndices(reuse_solver->benign_zerodiag_subs[i],&idxs_zero);
    4321:           }
    4322:           MatDenseRestoreArray(A_RV,&marr);
    4323:         }
    4324:         PetscObjectReference((PetscObject)A_RV);
    4325:         Brhs = A_RV;
    4326:       } else {
    4327:         Mat tA_RVT,A_RVT;

    4329:         if (!pcbddc->symmetric_primal) {
    4330:           /* A_RV already scaled by -1 */
    4331:           MatTranspose(A_RV,MAT_INITIAL_MATRIX,&A_RVT);
    4332:         } else {
    4333:           restoreavr = PETSC_TRUE;
    4334:           MatScale(A_VR,-1.0);
    4335:           PetscObjectReference((PetscObject)A_VR);
    4336:           A_RVT = A_VR;
    4337:         }
    4338:         if (lda_rhs != n_R) {
    4339:           PetscScalar *aa;
    4340:           PetscInt    r,*ii,*jj;
    4341:           PetscBool   done;

    4343:           MatGetRowIJ(A_RVT,0,PETSC_FALSE,PETSC_FALSE,&r,(const PetscInt**)&ii,(const PetscInt**)&jj,&done);
    4344:           if (!done) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_PLIB,"GetRowIJ failed");
    4345:           MatSeqAIJGetArray(A_RVT,&aa);
    4346:           MatCreateSeqAIJWithArrays(PETSC_COMM_SELF,n_vertices,lda_rhs,ii,jj,aa,&tA_RVT);
    4347:           MatRestoreRowIJ(A_RVT,0,PETSC_FALSE,PETSC_FALSE,&r,(const PetscInt**)&ii,(const PetscInt**)&jj,&done);
    4348:           if (!done) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_PLIB,"RestoreRowIJ failed");
    4349:         } else {
    4350:           PetscObjectReference((PetscObject)A_RVT);
    4351:           tA_RVT = A_RVT;
    4352:         }
    4353:         MatCreateTranspose(tA_RVT,&Brhs);
    4354:         MatDestroy(&tA_RVT);
    4355:         MatDestroy(&A_RVT);
    4356:       }
    4357:       if (F) {
    4358:         /* need to correct the rhs */
    4359:         if (need_benign_correction) {
    4360:           PCBDDCReuseSolvers reuse_solver = sub_schurs->reuse_solver;
    4361:           PetscScalar        *marr;

    4363:           MatDenseGetArray(Brhs,&marr);
    4364:           if (lda_rhs != n_R) {
    4365:             for (i=0;i<n_vertices;i++) {
    4366:               VecPlaceArray(dummy_vec,marr+i*lda_rhs);
    4367:               PCBDDCReuseSolversBenignAdapt(reuse_solver,dummy_vec,NULL,PETSC_FALSE,PETSC_TRUE);
    4368:               VecResetArray(dummy_vec);
    4369:             }
    4370:           } else {
    4371:             for (i=0;i<n_vertices;i++) {
    4372:               VecPlaceArray(pcbddc->vec1_R,marr+i*lda_rhs);
    4373:               PCBDDCReuseSolversBenignAdapt(reuse_solver,pcbddc->vec1_R,NULL,PETSC_FALSE,PETSC_TRUE);
    4374:               VecResetArray(pcbddc->vec1_R);
    4375:             }
    4376:           }
    4377:           MatDenseRestoreArray(Brhs,&marr);
    4378:         }
    4379:         MatMatSolve(F,Brhs,A_RRmA_RV);
    4380:         if (restoreavr) {
    4381:           MatScale(A_VR,-1.0);
    4382:         }
    4383:         /* need to correct the solution */
    4384:         if (need_benign_correction) {
    4385:           PCBDDCReuseSolvers reuse_solver = sub_schurs->reuse_solver;
    4386:           PetscScalar        *marr;

    4388:           MatDenseGetArray(A_RRmA_RV,&marr);
    4389:           if (lda_rhs != n_R) {
    4390:             for (i=0;i<n_vertices;i++) {
    4391:               VecPlaceArray(dummy_vec,marr+i*lda_rhs);
    4392:               PCBDDCReuseSolversBenignAdapt(reuse_solver,dummy_vec,NULL,PETSC_TRUE,PETSC_TRUE);
    4393:               VecResetArray(dummy_vec);
    4394:             }
    4395:           } else {
    4396:             for (i=0;i<n_vertices;i++) {
    4397:               VecPlaceArray(pcbddc->vec1_R,marr+i*lda_rhs);
    4398:               PCBDDCReuseSolversBenignAdapt(reuse_solver,pcbddc->vec1_R,NULL,PETSC_TRUE,PETSC_TRUE);
    4399:               VecResetArray(pcbddc->vec1_R);
    4400:             }
    4401:           }
    4402:           MatDenseRestoreArray(A_RRmA_RV,&marr);
    4403:         }
    4404:       } else {
    4405:         MatDenseGetArray(Brhs,&y);
    4406:         for (i=0;i<n_vertices;i++) {
    4407:           VecPlaceArray(pcbddc->vec1_R,y+i*lda_rhs);
    4408:           VecPlaceArray(pcbddc->vec2_R,work+i*lda_rhs);
    4409:           KSPSolve(pcbddc->ksp_R,pcbddc->vec1_R,pcbddc->vec2_R);
    4410:           KSPCheckSolve(pcbddc->ksp_R,pc,pcbddc->vec2_R);
    4411:           VecResetArray(pcbddc->vec1_R);
    4412:           VecResetArray(pcbddc->vec2_R);
    4413:         }
    4414:         MatDenseRestoreArray(Brhs,&y);
    4415:       }
    4416:       MatDestroy(&A_RV);
    4417:       MatDestroy(&Brhs);
    4418:       /* S_VV and S_CV */
    4419:       if (n_constraints) {
    4420:         Mat B;

    4422:         PetscArrayzero(work+lda_rhs*n_vertices,n_B*n_vertices);
    4423:         for (i=0;i<n_vertices;i++) {
    4424:           VecPlaceArray(pcbddc->vec1_R,work+i*lda_rhs);
    4425:           VecPlaceArray(pcis->vec1_B,work+lda_rhs*n_vertices+i*n_B);
    4426:           VecScatterBegin(pcbddc->R_to_B,pcbddc->vec1_R,pcis->vec1_B,INSERT_VALUES,SCATTER_FORWARD);
    4427:           VecScatterEnd(pcbddc->R_to_B,pcbddc->vec1_R,pcis->vec1_B,INSERT_VALUES,SCATTER_FORWARD);
    4428:           VecResetArray(pcis->vec1_B);
    4429:           VecResetArray(pcbddc->vec1_R);
    4430:         }
    4431:         MatCreateSeqDense(PETSC_COMM_SELF,n_B,n_vertices,work+lda_rhs*n_vertices,&B);
    4432:         /* Reuse dense S_C = pcbddc->local_auxmat1 * B */
    4433:         MatProductCreateWithMat(pcbddc->local_auxmat1,B,NULL,S_CV);
    4434:         MatProductSetType(S_CV,MATPRODUCT_AB);
    4435:         MatProductSetFromOptions(S_CV);
    4436:         MatProductNumeric(S_CV);
    4437:         MatProductClear(S_CV);

    4439:         MatDestroy(&B);
    4440:         MatCreateSeqDense(PETSC_COMM_SELF,lda_rhs,n_vertices,work+lda_rhs*n_vertices,&B);
    4441:         /* Reuse B = local_auxmat2_R * S_CV */
    4442:         MatProductCreateWithMat(local_auxmat2_R,S_CV,NULL,B);
    4443:         MatProductSetType(B,MATPRODUCT_AB);
    4444:         MatProductSetFromOptions(B);
    4445:         MatProductNumeric(B);

    4447:         MatScale(S_CV,m_one);
    4448:         PetscBLASIntCast(lda_rhs*n_vertices,&B_N);
    4449:         PetscStackCallBLAS("BLASaxpy",BLASaxpy_(&B_N,&one,work+lda_rhs*n_vertices,&B_one,work,&B_one));
    4450:         MatDestroy(&B);
    4451:       }
    4452:       if (lda_rhs != n_R) {
    4453:         MatDestroy(&A_RRmA_RV);
    4454:         MatCreateSeqDense(PETSC_COMM_SELF,n_R,n_vertices,work,&A_RRmA_RV);
    4455:         MatSeqDenseSetLDA(A_RRmA_RV,lda_rhs);
    4456:       }
    4457:       MatMatMult(A_VR,A_RRmA_RV,MAT_INITIAL_MATRIX,PETSC_DEFAULT,&S_VVt);
    4458:       /* need A_VR * \Phi * A_RRmA_RV = A_VR * (I+L)^T * A_RRmA_RV, L given as before */
    4459:       if (need_benign_correction) {
    4460:         PCBDDCReuseSolvers reuse_solver = sub_schurs->reuse_solver;
    4461:         PetscScalar        *marr,*sums;

    4463:         PetscMalloc1(n_vertices,&sums);
    4464:         MatDenseGetArray(S_VVt,&marr);
    4465:         for (i=0;i<reuse_solver->benign_n;i++) {
    4466:           const PetscScalar *vals;
    4467:           const PetscInt    *idxs,*idxs_zero;
    4468:           PetscInt          n,j,nz;

    4470:           ISGetLocalSize(reuse_solver->benign_zerodiag_subs[i],&nz);
    4471:           ISGetIndices(reuse_solver->benign_zerodiag_subs[i],&idxs_zero);
    4472:           for (j=0;j<n_vertices;j++) {
    4473:             PetscInt k;
    4474:             sums[j] = 0.;
    4475:             for (k=0;k<nz;k++) sums[j] += work[idxs_zero[k]+j*lda_rhs];
    4476:           }
    4477:           MatGetRow(A_RV_bcorr,i,&n,&idxs,&vals);
    4478:           for (j=0;j<n;j++) {
    4479:             PetscScalar val = vals[j];
    4480:             PetscInt k;
    4481:             for (k=0;k<n_vertices;k++) {
    4482:               marr[idxs[j]+k*n_vertices] += val*sums[k];
    4483:             }
    4484:           }
    4485:           MatRestoreRow(A_RV_bcorr,i,&n,&idxs,&vals);
    4486:           ISRestoreIndices(reuse_solver->benign_zerodiag_subs[i],&idxs_zero);
    4487:         }
    4488:         PetscFree(sums);
    4489:         MatDenseRestoreArray(S_VVt,&marr);
    4490:         MatDestroy(&A_RV_bcorr);
    4491:       }
    4492:       MatDestroy(&A_RRmA_RV);
    4493:       PetscBLASIntCast(n_vertices*n_vertices,&B_N);
    4494:       MatDenseGetArrayRead(A_VV,&x);
    4495:       MatDenseGetArray(S_VVt,&y);
    4496:       PetscStackCallBLAS("BLASaxpy",BLASaxpy_(&B_N,&one,x,&B_one,y,&B_one));
    4497:       MatDenseRestoreArrayRead(A_VV,&x);
    4498:       MatDenseRestoreArray(S_VVt,&y);
    4499:       MatCopy(S_VVt,S_VV,SAME_NONZERO_PATTERN);
    4500:       MatDestroy(&S_VVt);
    4501:     } else {
    4502:       MatCopy(A_VV,S_VV,SAME_NONZERO_PATTERN);
    4503:     }
    4504:     MatDestroy(&A_VV);

    4506:     /* coarse basis functions */
    4507:     for (i=0;i<n_vertices;i++) {
    4508:       PetscScalar *y;

    4510:       VecPlaceArray(pcbddc->vec1_R,work+lda_rhs*i);
    4511:       MatDenseGetArray(pcbddc->coarse_phi_B,&y);
    4512:       VecPlaceArray(pcis->vec1_B,y+n_B*i);
    4513:       VecScatterBegin(pcbddc->R_to_B,pcbddc->vec1_R,pcis->vec1_B,INSERT_VALUES,SCATTER_FORWARD);
    4514:       VecScatterEnd(pcbddc->R_to_B,pcbddc->vec1_R,pcis->vec1_B,INSERT_VALUES,SCATTER_FORWARD);
    4515:       y[n_B*i+idx_V_B[i]] = 1.0;
    4516:       MatDenseRestoreArray(pcbddc->coarse_phi_B,&y);
    4517:       VecResetArray(pcis->vec1_B);

    4519:       if (pcbddc->switch_static || pcbddc->dbg_flag) {
    4520:         PetscInt j;

    4522:         MatDenseGetArray(pcbddc->coarse_phi_D,&y);
    4523:         VecPlaceArray(pcis->vec1_D,y+n_D*i);
    4524:         VecScatterBegin(pcbddc->R_to_D,pcbddc->vec1_R,pcis->vec1_D,INSERT_VALUES,SCATTER_FORWARD);
    4525:         VecScatterEnd(pcbddc->R_to_D,pcbddc->vec1_R,pcis->vec1_D,INSERT_VALUES,SCATTER_FORWARD);
    4526:         VecResetArray(pcis->vec1_D);
    4527:         for (j=0;j<pcbddc->benign_n;j++) y[n_D*i+p0_lidx_I[j]] = 0.0;
    4528:         MatDenseRestoreArray(pcbddc->coarse_phi_D,&y);
    4529:       }
    4530:       VecResetArray(pcbddc->vec1_R);
    4531:     }
    4532:     /* if n_R == 0 the object is not destroyed */
    4533:     MatDestroy(&A_RV);
    4534:   }
    4535:   VecDestroy(&dummy_vec);

    4537:   if (n_constraints) {
    4538:     Mat B;

    4540:     MatCreateSeqDense(PETSC_COMM_SELF,lda_rhs,n_constraints,work,&B);
    4541:     MatScale(S_CC,m_one);
    4542:     MatProductCreateWithMat(local_auxmat2_R,S_CC,NULL,B);
    4543:     MatProductSetType(B,MATPRODUCT_AB);
    4544:     MatProductSetFromOptions(B);
    4545:     MatProductNumeric(B);

    4547:     MatScale(S_CC,m_one);
    4548:     if (n_vertices) {
    4549:       if (isCHOL || need_benign_correction) { /* if we can solve the interior problem with cholesky, we should also be fine with transposing here */
    4550:         MatTranspose(S_CV,MAT_REUSE_MATRIX,&S_VC);
    4551:       } else {
    4552:         Mat S_VCt;

    4554:         if (lda_rhs != n_R) {
    4555:           MatDestroy(&B);
    4556:           MatCreateSeqDense(PETSC_COMM_SELF,n_R,n_constraints,work,&B);
    4557:           MatSeqDenseSetLDA(B,lda_rhs);
    4558:         }
    4559:         MatMatMult(A_VR,B,MAT_INITIAL_MATRIX,PETSC_DEFAULT,&S_VCt);
    4560:         MatCopy(S_VCt,S_VC,SAME_NONZERO_PATTERN);
    4561:         MatDestroy(&S_VCt);
    4562:       }
    4563:     }
    4564:     MatDestroy(&B);
    4565:     /* coarse basis functions */
    4566:     for (i=0;i<n_constraints;i++) {
    4567:       PetscScalar *y;

    4569:       VecPlaceArray(pcbddc->vec1_R,work+lda_rhs*i);
    4570:       MatDenseGetArray(pcbddc->coarse_phi_B,&y);
    4571:       VecPlaceArray(pcis->vec1_B,y+n_B*(i+n_vertices));
    4572:       VecScatterBegin(pcbddc->R_to_B,pcbddc->vec1_R,pcis->vec1_B,INSERT_VALUES,SCATTER_FORWARD);
    4573:       VecScatterEnd(pcbddc->R_to_B,pcbddc->vec1_R,pcis->vec1_B,INSERT_VALUES,SCATTER_FORWARD);
    4574:       MatDenseRestoreArray(pcbddc->coarse_phi_B,&y);
    4575:       VecResetArray(pcis->vec1_B);
    4576:       if (pcbddc->switch_static || pcbddc->dbg_flag) {
    4577:         PetscInt j;

    4579:         MatDenseGetArray(pcbddc->coarse_phi_D,&y);
    4580:         VecPlaceArray(pcis->vec1_D,y+n_D*(i+n_vertices));
    4581:         VecScatterBegin(pcbddc->R_to_D,pcbddc->vec1_R,pcis->vec1_D,INSERT_VALUES,SCATTER_FORWARD);
    4582:         VecScatterEnd(pcbddc->R_to_D,pcbddc->vec1_R,pcis->vec1_D,INSERT_VALUES,SCATTER_FORWARD);
    4583:         VecResetArray(pcis->vec1_D);
    4584:         for (j=0;j<pcbddc->benign_n;j++) y[n_D*i+p0_lidx_I[j]] = 0.0;
    4585:         MatDenseRestoreArray(pcbddc->coarse_phi_D,&y);
    4586:       }
    4587:       VecResetArray(pcbddc->vec1_R);
    4588:     }
    4589:   }
    4590:   if (n_constraints) {
    4591:     MatDestroy(&local_auxmat2_R);
    4592:   }
    4593:   PetscFree(p0_lidx_I);

    4595:   /* coarse matrix entries relative to B_0 */
    4596:   if (pcbddc->benign_n) {
    4597:     Mat               B0_B,B0_BPHI;
    4598:     IS                is_dummy;
    4599:     const PetscScalar *data;
    4600:     PetscInt          j;

    4602:     ISCreateStride(PETSC_COMM_SELF,pcbddc->benign_n,0,1,&is_dummy);
    4603:     MatCreateSubMatrix(pcbddc->benign_B0,is_dummy,pcis->is_B_local,MAT_INITIAL_MATRIX,&B0_B);
    4604:     ISDestroy(&is_dummy);
    4605:     MatMatMult(B0_B,pcbddc->coarse_phi_B,MAT_INITIAL_MATRIX,1.0,&B0_BPHI);
    4606:     MatConvert(B0_BPHI,MATSEQDENSE,MAT_INPLACE_MATRIX,&B0_BPHI);
    4607:     MatDenseGetArrayRead(B0_BPHI,&data);
    4608:     for (j=0;j<pcbddc->benign_n;j++) {
    4609:       PetscInt primal_idx = pcbddc->local_primal_size - pcbddc->benign_n + j;
    4610:       for (i=0;i<pcbddc->local_primal_size;i++) {
    4611:         coarse_submat_vals[primal_idx*pcbddc->local_primal_size+i] = data[i*pcbddc->benign_n+j];
    4612:         coarse_submat_vals[i*pcbddc->local_primal_size+primal_idx] = data[i*pcbddc->benign_n+j];
    4613:       }
    4614:     }
    4615:     MatDenseRestoreArrayRead(B0_BPHI,&data);
    4616:     MatDestroy(&B0_B);
    4617:     MatDestroy(&B0_BPHI);
    4618:   }

    4620:   /* compute other basis functions for non-symmetric problems */
    4621:   if (!pcbddc->symmetric_primal) {
    4622:     Mat         B_V=NULL,B_C=NULL;
    4623:     PetscScalar *marray;

    4625:     if (n_constraints) {
    4626:       Mat S_CCT,C_CRT;

    4628:       MatTranspose(C_CR,MAT_INITIAL_MATRIX,&C_CRT);
    4629:       MatTranspose(S_CC,MAT_INITIAL_MATRIX,&S_CCT);
    4630:       MatMatMult(C_CRT,S_CCT,MAT_INITIAL_MATRIX,PETSC_DEFAULT,&B_C);
    4631:       MatDestroy(&S_CCT);
    4632:       if (n_vertices) {
    4633:         Mat S_VCT;

    4635:         MatTranspose(S_VC,MAT_INITIAL_MATRIX,&S_VCT);
    4636:         MatMatMult(C_CRT,S_VCT,MAT_INITIAL_MATRIX,PETSC_DEFAULT,&B_V);
    4637:         MatDestroy(&S_VCT);
    4638:       }
    4639:       MatDestroy(&C_CRT);
    4640:     } else {
    4641:       MatCreateSeqDense(PETSC_COMM_SELF,n_R,n_vertices,NULL,&B_V);
    4642:     }
    4643:     if (n_vertices && n_R) {
    4644:       PetscScalar    *av,*marray;
    4645:       const PetscInt *xadj,*adjncy;
    4646:       PetscInt       n;
    4647:       PetscBool      flg_row;

    4649:       /* B_V = B_V - A_VR^T */
    4650:       MatConvert(A_VR,MATSEQAIJ,MAT_INPLACE_MATRIX,&A_VR);
    4651:       MatGetRowIJ(A_VR,0,PETSC_FALSE,PETSC_FALSE,&n,&xadj,&adjncy,&flg_row);
    4652:       MatSeqAIJGetArray(A_VR,&av);
    4653:       MatDenseGetArray(B_V,&marray);
    4654:       for (i=0;i<n;i++) {
    4655:         PetscInt j;
    4656:         for (j=xadj[i];j<xadj[i+1];j++) marray[i*n_R + adjncy[j]] -= av[j];
    4657:       }
    4658:       MatDenseRestoreArray(B_V,&marray);
    4659:       MatRestoreRowIJ(A_VR,0,PETSC_FALSE,PETSC_FALSE,&n,&xadj,&adjncy,&flg_row);
    4660:       MatDestroy(&A_VR);
    4661:     }

    4663:     /* currently there's no support for MatTransposeMatSolve(F,B,X) */
    4664:     if (n_vertices) {
    4665:       MatDenseGetArray(B_V,&marray);
    4666:       for (i=0;i<n_vertices;i++) {
    4667:         VecPlaceArray(pcbddc->vec1_R,marray+i*n_R);
    4668:         VecPlaceArray(pcbddc->vec2_R,work+i*n_R);
    4669:         KSPSolveTranspose(pcbddc->ksp_R,pcbddc->vec1_R,pcbddc->vec2_R);
    4670:         KSPCheckSolve(pcbddc->ksp_R,pc,pcbddc->vec2_R);
    4671:         VecResetArray(pcbddc->vec1_R);
    4672:         VecResetArray(pcbddc->vec2_R);
    4673:       }
    4674:       MatDenseRestoreArray(B_V,&marray);
    4675:     }
    4676:     if (B_C) {
    4677:       MatDenseGetArray(B_C,&marray);
    4678:       for (i=n_vertices;i<n_constraints+n_vertices;i++) {
    4679:         VecPlaceArray(pcbddc->vec1_R,marray+(i-n_vertices)*n_R);
    4680:         VecPlaceArray(pcbddc->vec2_R,work+i*n_R);
    4681:         KSPSolveTranspose(pcbddc->ksp_R,pcbddc->vec1_R,pcbddc->vec2_R);
    4682:         KSPCheckSolve(pcbddc->ksp_R,pc,pcbddc->vec2_R);
    4683:         VecResetArray(pcbddc->vec1_R);
    4684:         VecResetArray(pcbddc->vec2_R);
    4685:       }
    4686:       MatDenseRestoreArray(B_C,&marray);
    4687:     }
    4688:     /* coarse basis functions */
    4689:     for (i=0;i<pcbddc->local_primal_size;i++) {
    4690:       PetscScalar *y;

    4692:       VecPlaceArray(pcbddc->vec1_R,work+i*n_R);
    4693:       MatDenseGetArray(pcbddc->coarse_psi_B,&y);
    4694:       VecPlaceArray(pcis->vec1_B,y+n_B*i);
    4695:       VecScatterBegin(pcbddc->R_to_B,pcbddc->vec1_R,pcis->vec1_B,INSERT_VALUES,SCATTER_FORWARD);
    4696:       VecScatterEnd(pcbddc->R_to_B,pcbddc->vec1_R,pcis->vec1_B,INSERT_VALUES,SCATTER_FORWARD);
    4697:       if (i<n_vertices) {
    4698:         y[n_B*i+idx_V_B[i]] = 1.0;
    4699:       }
    4700:       MatDenseRestoreArray(pcbddc->coarse_psi_B,&y);
    4701:       VecResetArray(pcis->vec1_B);

    4703:       if (pcbddc->switch_static || pcbddc->dbg_flag) {
    4704:         MatDenseGetArray(pcbddc->coarse_psi_D,&y);
    4705:         VecPlaceArray(pcis->vec1_D,y+n_D*i);
    4706:         VecScatterBegin(pcbddc->R_to_D,pcbddc->vec1_R,pcis->vec1_D,INSERT_VALUES,SCATTER_FORWARD);
    4707:         VecScatterEnd(pcbddc->R_to_D,pcbddc->vec1_R,pcis->vec1_D,INSERT_VALUES,SCATTER_FORWARD);
    4708:         VecResetArray(pcis->vec1_D);
    4709:         MatDenseRestoreArray(pcbddc->coarse_psi_D,&y);
    4710:       }
    4711:       VecResetArray(pcbddc->vec1_R);
    4712:     }
    4713:     MatDestroy(&B_V);
    4714:     MatDestroy(&B_C);
    4715:   }

    4717:   /* free memory */
    4718:   PetscFree(idx_V_B);
    4719:   MatDestroy(&S_VV);
    4720:   MatDestroy(&S_CV);
    4721:   MatDestroy(&S_VC);
    4722:   MatDestroy(&S_CC);
    4723:   PetscFree(work);
    4724:   if (n_vertices) {
    4725:     MatDestroy(&A_VR);
    4726:   }
    4727:   if (n_constraints) {
    4728:     MatDestroy(&C_CR);
    4729:   }
    4730:   PetscLogEventEnd(PC_BDDC_CorrectionSetUp[pcbddc->current_level],pc,0,0,0);

    4732:   /* Checking coarse_sub_mat and coarse basis functios */
    4733:   /* Symmetric case     : It should be \Phi^{(j)^T} A^{(j)} \Phi^{(j)}=coarse_sub_mat */
    4734:   /* Non-symmetric case : It should be \Psi^{(j)^T} A^{(j)} \Phi^{(j)}=coarse_sub_mat */
    4735:   if (pcbddc->dbg_flag) {
    4736:     Mat         coarse_sub_mat;
    4737:     Mat         AUXMAT,TM1,TM2,TM3,TM4;
    4738:     Mat         coarse_phi_D,coarse_phi_B;
    4739:     Mat         coarse_psi_D,coarse_psi_B;
    4740:     Mat         A_II,A_BB,A_IB,A_BI;
    4741:     Mat         C_B,CPHI;
    4742:     IS          is_dummy;
    4743:     Vec         mones;
    4744:     MatType     checkmattype=MATSEQAIJ;
    4745:     PetscReal   real_value;

    4747:     if (pcbddc->benign_n && !pcbddc->benign_change_explicit) {
    4748:       Mat A;
    4749:       PCBDDCBenignProject(pc,NULL,NULL,&A);
    4750:       MatCreateSubMatrix(A,pcis->is_I_local,pcis->is_I_local,MAT_INITIAL_MATRIX,&A_II);
    4751:       MatCreateSubMatrix(A,pcis->is_I_local,pcis->is_B_local,MAT_INITIAL_MATRIX,&A_IB);
    4752:       MatCreateSubMatrix(A,pcis->is_B_local,pcis->is_I_local,MAT_INITIAL_MATRIX,&A_BI);
    4753:       MatCreateSubMatrix(A,pcis->is_B_local,pcis->is_B_local,MAT_INITIAL_MATRIX,&A_BB);
    4754:       MatDestroy(&A);
    4755:     } else {
    4756:       MatConvert(pcis->A_II,checkmattype,MAT_INITIAL_MATRIX,&A_II);
    4757:       MatConvert(pcis->A_IB,checkmattype,MAT_INITIAL_MATRIX,&A_IB);
    4758:       MatConvert(pcis->A_BI,checkmattype,MAT_INITIAL_MATRIX,&A_BI);
    4759:       MatConvert(pcis->A_BB,checkmattype,MAT_INITIAL_MATRIX,&A_BB);
    4760:     }
    4761:     MatConvert(pcbddc->coarse_phi_D,checkmattype,MAT_INITIAL_MATRIX,&coarse_phi_D);
    4762:     MatConvert(pcbddc->coarse_phi_B,checkmattype,MAT_INITIAL_MATRIX,&coarse_phi_B);
    4763:     if (!pcbddc->symmetric_primal) {
    4764:       MatConvert(pcbddc->coarse_psi_D,checkmattype,MAT_INITIAL_MATRIX,&coarse_psi_D);
    4765:       MatConvert(pcbddc->coarse_psi_B,checkmattype,MAT_INITIAL_MATRIX,&coarse_psi_B);
    4766:     }
    4767:     MatCreateSeqDense(PETSC_COMM_SELF,pcbddc->local_primal_size,pcbddc->local_primal_size,coarse_submat_vals,&coarse_sub_mat);

    4769:     PetscViewerASCIIPrintf(pcbddc->dbg_viewer,"--------------------------------------------------\n");
    4770:     PetscViewerASCIIPrintf(pcbddc->dbg_viewer,"Check coarse sub mat computation (symmetric %d)\n",pcbddc->symmetric_primal);
    4771:     PetscViewerFlush(pcbddc->dbg_viewer);
    4772:     if (!pcbddc->symmetric_primal) {
    4773:       MatMatMult(A_II,coarse_phi_D,MAT_INITIAL_MATRIX,1.0,&AUXMAT);
    4774:       MatTransposeMatMult(coarse_psi_D,AUXMAT,MAT_INITIAL_MATRIX,1.0,&TM1);
    4775:       MatDestroy(&AUXMAT);
    4776:       MatMatMult(A_BB,coarse_phi_B,MAT_INITIAL_MATRIX,1.0,&AUXMAT);
    4777:       MatTransposeMatMult(coarse_psi_B,AUXMAT,MAT_INITIAL_MATRIX,1.0,&TM2);
    4778:       MatDestroy(&AUXMAT);
    4779:       MatMatMult(A_IB,coarse_phi_B,MAT_INITIAL_MATRIX,1.0,&AUXMAT);
    4780:       MatTransposeMatMult(coarse_psi_D,AUXMAT,MAT_INITIAL_MATRIX,1.0,&TM3);
    4781:       MatDestroy(&AUXMAT);
    4782:       MatMatMult(A_BI,coarse_phi_D,MAT_INITIAL_MATRIX,1.0,&AUXMAT);
    4783:       MatTransposeMatMult(coarse_psi_B,AUXMAT,MAT_INITIAL_MATRIX,1.0,&TM4);
    4784:       MatDestroy(&AUXMAT);
    4785:     } else {
    4786:       MatPtAP(A_II,coarse_phi_D,MAT_INITIAL_MATRIX,1.0,&TM1);
    4787:       MatPtAP(A_BB,coarse_phi_B,MAT_INITIAL_MATRIX,1.0,&TM2);
    4788:       MatMatMult(A_IB,coarse_phi_B,MAT_INITIAL_MATRIX,1.0,&AUXMAT);
    4789:       MatTransposeMatMult(coarse_phi_D,AUXMAT,MAT_INITIAL_MATRIX,1.0,&TM3);
    4790:       MatDestroy(&AUXMAT);
    4791:       MatMatMult(A_BI,coarse_phi_D,MAT_INITIAL_MATRIX,1.0,&AUXMAT);
    4792:       MatTransposeMatMult(coarse_phi_B,AUXMAT,MAT_INITIAL_MATRIX,1.0,&TM4);
    4793:       MatDestroy(&AUXMAT);
    4794:     }
    4795:     MatAXPY(TM1,one,TM2,DIFFERENT_NONZERO_PATTERN);
    4796:     MatAXPY(TM1,one,TM3,DIFFERENT_NONZERO_PATTERN);
    4797:     MatAXPY(TM1,one,TM4,DIFFERENT_NONZERO_PATTERN);
    4798:     MatConvert(TM1,MATSEQDENSE,MAT_INPLACE_MATRIX,&TM1);
    4799:     if (pcbddc->benign_n) {
    4800:       Mat               B0_B,B0_BPHI;
    4801:       const PetscScalar *data2;
    4802:       PetscScalar       *data;
    4803:       PetscInt          j;

    4805:       ISCreateStride(PETSC_COMM_SELF,pcbddc->benign_n,0,1,&is_dummy);
    4806:       MatCreateSubMatrix(pcbddc->benign_B0,is_dummy,pcis->is_B_local,MAT_INITIAL_MATRIX,&B0_B);
    4807:       MatMatMult(B0_B,coarse_phi_B,MAT_INITIAL_MATRIX,1.0,&B0_BPHI);
    4808:       MatConvert(B0_BPHI,MATSEQDENSE,MAT_INPLACE_MATRIX,&B0_BPHI);
    4809:       MatDenseGetArray(TM1,&data);
    4810:       MatDenseGetArrayRead(B0_BPHI,&data2);
    4811:       for (j=0;j<pcbddc->benign_n;j++) {
    4812:         PetscInt primal_idx = pcbddc->local_primal_size - pcbddc->benign_n + j;
    4813:         for (i=0;i<pcbddc->local_primal_size;i++) {
    4814:           data[primal_idx*pcbddc->local_primal_size+i] += data2[i*pcbddc->benign_n+j];
    4815:           data[i*pcbddc->local_primal_size+primal_idx] += data2[i*pcbddc->benign_n+j];
    4816:         }
    4817:       }
    4818:       MatDenseRestoreArray(TM1,&data);
    4819:       MatDenseRestoreArrayRead(B0_BPHI,&data2);
    4820:       MatDestroy(&B0_B);
    4821:       ISDestroy(&is_dummy);
    4822:       MatDestroy(&B0_BPHI);
    4823:     }
    4824: #if 0
    4825:   {
    4826:     PetscViewer viewer;
    4827:     char filename[256];
    4828:     sprintf(filename,"details_local_coarse_mat%d_level%d.m",PetscGlobalRank,pcbddc->current_level);
    4829:     PetscViewerASCIIOpen(PETSC_COMM_SELF,filename,&viewer);
    4830:     PetscViewerPushFormat(viewer,PETSC_VIEWER_ASCII_MATLAB);
    4831:     PetscObjectSetName((PetscObject)coarse_sub_mat,"computed");
    4832:     MatView(coarse_sub_mat,viewer);
    4833:     PetscObjectSetName((PetscObject)TM1,"projected");
    4834:     MatView(TM1,viewer);
    4835:     if (pcbddc->coarse_phi_B) {
    4836:       PetscObjectSetName((PetscObject)pcbddc->coarse_phi_B,"phi_B");
    4837:       MatView(pcbddc->coarse_phi_B,viewer);
    4838:     }
    4839:     if (pcbddc->coarse_phi_D) {
    4840:       PetscObjectSetName((PetscObject)pcbddc->coarse_phi_D,"phi_D");
    4841:       MatView(pcbddc->coarse_phi_D,viewer);
    4842:     }
    4843:     if (pcbddc->coarse_psi_B) {
    4844:       PetscObjectSetName((PetscObject)pcbddc->coarse_psi_B,"psi_B");
    4845:       MatView(pcbddc->coarse_psi_B,viewer);
    4846:     }
    4847:     if (pcbddc->coarse_psi_D) {
    4848:       PetscObjectSetName((PetscObject)pcbddc->coarse_psi_D,"psi_D");
    4849:       MatView(pcbddc->coarse_psi_D,viewer);
    4850:     }
    4851:     PetscObjectSetName((PetscObject)pcbddc->local_mat,"A");
    4852:     MatView(pcbddc->local_mat,viewer);
    4853:     PetscObjectSetName((PetscObject)pcbddc->ConstraintMatrix,"C");
    4854:     MatView(pcbddc->ConstraintMatrix,viewer);
    4855:     PetscObjectSetName((PetscObject)pcis->is_I_local,"I");
    4856:     ISView(pcis->is_I_local,viewer);
    4857:     PetscObjectSetName((PetscObject)pcis->is_B_local,"B");
    4858:     ISView(pcis->is_B_local,viewer);
    4859:     PetscObjectSetName((PetscObject)pcbddc->is_R_local,"R");
    4860:     ISView(pcbddc->is_R_local,viewer);
    4861:     PetscViewerDestroy(&viewer);
    4862:   }
    4863: #endif
    4864:     MatAXPY(TM1,m_one,coarse_sub_mat,DIFFERENT_NONZERO_PATTERN);
    4865:     MatNorm(TM1,NORM_FROBENIUS,&real_value);
    4866:     PetscViewerASCIIPushSynchronized(pcbddc->dbg_viewer);
    4867:     PetscViewerASCIISynchronizedPrintf(pcbddc->dbg_viewer,"Subdomain %04d          matrix error % 1.14e\n",PetscGlobalRank,real_value);

    4869:     /* check constraints */
    4870:     ISCreateStride(PETSC_COMM_SELF,pcbddc->local_primal_size-pcbddc->benign_n,0,1,&is_dummy);
    4871:     MatCreateSubMatrix(pcbddc->ConstraintMatrix,is_dummy,pcis->is_B_local,MAT_INITIAL_MATRIX,&C_B);
    4872:     if (!pcbddc->benign_n) { /* TODO: add benign case */
    4873:       MatMatMult(C_B,coarse_phi_B,MAT_INITIAL_MATRIX,1.0,&CPHI);
    4874:     } else {
    4875:       PetscScalar *data;
    4876:       Mat         tmat;
    4877:       MatDenseGetArray(pcbddc->coarse_phi_B,&data);
    4878:       MatCreateSeqDense(PETSC_COMM_SELF,pcis->n_B,pcbddc->local_primal_size-pcbddc->benign_n,data,&tmat);
    4879:       MatDenseRestoreArray(pcbddc->coarse_phi_B,&data);
    4880:       MatMatMult(C_B,tmat,MAT_INITIAL_MATRIX,1.0,&CPHI);
    4881:       MatDestroy(&tmat);
    4882:     }
    4883:     MatCreateVecs(CPHI,&mones,NULL);
    4884:     VecSet(mones,-1.0);
    4885:     MatDiagonalSet(CPHI,mones,ADD_VALUES);
    4886:     MatNorm(CPHI,NORM_FROBENIUS,&real_value);
    4887:     PetscViewerASCIISynchronizedPrintf(pcbddc->dbg_viewer,"Subdomain %04d phi constraints error % 1.14e\n",PetscGlobalRank,real_value);
    4888:     if (!pcbddc->symmetric_primal) {
    4889:       MatMatMult(C_B,coarse_psi_B,MAT_REUSE_MATRIX,1.0,&CPHI);
    4890:       VecSet(mones,-1.0);
    4891:       MatDiagonalSet(CPHI,mones,ADD_VALUES);
    4892:       MatNorm(CPHI,NORM_FROBENIUS,&real_value);
    4893:       PetscViewerASCIISynchronizedPrintf(pcbddc->dbg_viewer,"Subdomain %04d psi constraints error % 1.14e\n",PetscGlobalRank,real_value);
    4894:     }
    4895:     MatDestroy(&C_B);
    4896:     MatDestroy(&CPHI);
    4897:     ISDestroy(&is_dummy);
    4898:     VecDestroy(&mones);
    4899:     PetscViewerFlush(pcbddc->dbg_viewer);
    4900:     MatDestroy(&A_II);
    4901:     MatDestroy(&A_BB);
    4902:     MatDestroy(&A_IB);
    4903:     MatDestroy(&A_BI);
    4904:     MatDestroy(&TM1);
    4905:     MatDestroy(&TM2);
    4906:     MatDestroy(&TM3);
    4907:     MatDestroy(&TM4);
    4908:     MatDestroy(&coarse_phi_D);
    4909:     MatDestroy(&coarse_phi_B);
    4910:     if (!pcbddc->symmetric_primal) {
    4911:       MatDestroy(&coarse_psi_D);
    4912:       MatDestroy(&coarse_psi_B);
    4913:     }
    4914:     MatDestroy(&coarse_sub_mat);
    4915:   }
    4916:   /* FINAL CUDA support (we cannot currently mix viennacl and cuda vectors */
    4917:   {
    4918:     PetscBool gpu;

    4920:     PetscObjectTypeCompare((PetscObject)pcis->vec1_N,VECSEQCUDA,&gpu);
    4921:     if (gpu) {
    4922:       if (pcbddc->local_auxmat1) {
    4923:         MatConvert(pcbddc->local_auxmat1,MATSEQDENSECUDA,MAT_INPLACE_MATRIX,&pcbddc->local_auxmat1);
    4924:       }
    4925:       if (pcbddc->local_auxmat2) {
    4926:         MatConvert(pcbddc->local_auxmat2,MATSEQDENSECUDA,MAT_INPLACE_MATRIX,&pcbddc->local_auxmat2);
    4927:       }
    4928:       if (pcbddc->coarse_phi_B) {
    4929:         MatConvert(pcbddc->coarse_phi_B,MATSEQDENSECUDA,MAT_INPLACE_MATRIX,&pcbddc->coarse_phi_B);
    4930:       }
    4931:       if (pcbddc->coarse_phi_D) {
    4932:         MatConvert(pcbddc->coarse_phi_D,MATSEQDENSECUDA,MAT_INPLACE_MATRIX,&pcbddc->coarse_phi_D);
    4933:       }
    4934:       if (pcbddc->coarse_psi_B) {
    4935:         MatConvert(pcbddc->coarse_psi_B,MATSEQDENSECUDA,MAT_INPLACE_MATRIX,&pcbddc->coarse_psi_B);
    4936:       }
    4937:       if (pcbddc->coarse_psi_D) {
    4938:         MatConvert(pcbddc->coarse_psi_D,MATSEQDENSECUDA,MAT_INPLACE_MATRIX,&pcbddc->coarse_psi_D);
    4939:       }
    4940:     }
    4941:   }
    4942:   /* get back data */
    4943:   *coarse_submat_vals_n = coarse_submat_vals;
    4944:   return(0);
    4945: }

    4947: PetscErrorCode MatCreateSubMatrixUnsorted(Mat A, IS isrow, IS iscol, Mat* B)
    4948: {
    4949:   Mat            *work_mat;
    4950:   IS             isrow_s,iscol_s;
    4951:   PetscBool      rsorted,csorted;
    4952:   PetscInt       rsize,*idxs_perm_r=NULL,csize,*idxs_perm_c=NULL;

    4956:   ISSorted(isrow,&rsorted);
    4957:   ISSorted(iscol,&csorted);
    4958:   ISGetLocalSize(isrow,&rsize);
    4959:   ISGetLocalSize(iscol,&csize);

    4961:   if (!rsorted) {
    4962:     const PetscInt *idxs;
    4963:     PetscInt *idxs_sorted,i;

    4965:     PetscMalloc1(rsize,&idxs_perm_r);
    4966:     PetscMalloc1(rsize,&idxs_sorted);
    4967:     for (i=0;i<rsize;i++) {
    4968:       idxs_perm_r[i] = i;
    4969:     }
    4970:     ISGetIndices(isrow,&idxs);
    4971:     PetscSortIntWithPermutation(rsize,idxs,idxs_perm_r);
    4972:     for (i=0;i<rsize;i++) {
    4973:       idxs_sorted[i] = idxs[idxs_perm_r[i]];
    4974:     }
    4975:     ISRestoreIndices(isrow,&idxs);
    4976:     ISCreateGeneral(PETSC_COMM_SELF,rsize,idxs_sorted,PETSC_OWN_POINTER,&isrow_s);
    4977:   } else {
    4978:     PetscObjectReference((PetscObject)isrow);
    4979:     isrow_s = isrow;
    4980:   }

    4982:   if (!csorted) {
    4983:     if (isrow == iscol) {
    4984:       PetscObjectReference((PetscObject)isrow_s);
    4985:       iscol_s = isrow_s;
    4986:     } else {
    4987:       const PetscInt *idxs;
    4988:       PetscInt       *idxs_sorted,i;

    4990:       PetscMalloc1(csize,&idxs_perm_c);
    4991:       PetscMalloc1(csize,&idxs_sorted);
    4992:       for (i=0;i<csize;i++) {
    4993:         idxs_perm_c[i] = i;
    4994:       }
    4995:       ISGetIndices(iscol,&idxs);
    4996:       PetscSortIntWithPermutation(csize,idxs,idxs_perm_c);
    4997:       for (i=0;i<csize;i++) {
    4998:         idxs_sorted[i] = idxs[idxs_perm_c[i]];
    4999:       }
    5000:       ISRestoreIndices(iscol,&idxs);
    5001:       ISCreateGeneral(PETSC_COMM_SELF,csize,idxs_sorted,PETSC_OWN_POINTER,&iscol_s);
    5002:     }
    5003:   } else {
    5004:     PetscObjectReference((PetscObject)iscol);
    5005:     iscol_s = iscol;
    5006:   }

    5008:   MatCreateSubMatrices(A,1,&isrow_s,&iscol_s,MAT_INITIAL_MATRIX,&work_mat);

    5010:   if (!rsorted || !csorted) {
    5011:     Mat      new_mat;
    5012:     IS       is_perm_r,is_perm_c;

    5014:     if (!rsorted) {
    5015:       PetscInt *idxs_r,i;
    5016:       PetscMalloc1(rsize,&idxs_r);
    5017:       for (i=0;i<rsize;i++) {
    5018:         idxs_r[idxs_perm_r[i]] = i;
    5019:       }
    5020:       PetscFree(idxs_perm_r);
    5021:       ISCreateGeneral(PETSC_COMM_SELF,rsize,idxs_r,PETSC_OWN_POINTER,&is_perm_r);
    5022:     } else {
    5023:       ISCreateStride(PETSC_COMM_SELF,rsize,0,1,&is_perm_r);
    5024:     }
    5025:     ISSetPermutation(is_perm_r);

    5027:     if (!csorted) {
    5028:       if (isrow_s == iscol_s) {
    5029:         PetscObjectReference((PetscObject)is_perm_r);
    5030:         is_perm_c = is_perm_r;
    5031:       } else {
    5032:         PetscInt *idxs_c,i;
    5033:         if (!idxs_perm_c) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_PLIB,"Permutation array not present");
    5034:         PetscMalloc1(csize,&idxs_c);
    5035:         for (i=0;i<csize;i++) {
    5036:           idxs_c[idxs_perm_c[i]] = i;
    5037:         }
    5038:         PetscFree(idxs_perm_c);
    5039:         ISCreateGeneral(PETSC_COMM_SELF,csize,idxs_c,PETSC_OWN_POINTER,&is_perm_c);
    5040:       }
    5041:     } else {
    5042:       ISCreateStride(PETSC_COMM_SELF,csize,0,1,&is_perm_c);
    5043:     }
    5044:     ISSetPermutation(is_perm_c);

    5046:     MatPermute(work_mat[0],is_perm_r,is_perm_c,&new_mat);
    5047:     MatDestroy(&work_mat[0]);
    5048:     work_mat[0] = new_mat;
    5049:     ISDestroy(&is_perm_r);
    5050:     ISDestroy(&is_perm_c);
    5051:   }

    5053:   PetscObjectReference((PetscObject)work_mat[0]);
    5054:   *B = work_mat[0];
    5055:   MatDestroyMatrices(1,&work_mat);
    5056:   ISDestroy(&isrow_s);
    5057:   ISDestroy(&iscol_s);
    5058:   return(0);
    5059: }

    5061: PetscErrorCode PCBDDCComputeLocalMatrix(PC pc, Mat ChangeOfBasisMatrix)
    5062: {
    5063:   Mat_IS*        matis = (Mat_IS*)pc->pmat->data;
    5064:   PC_BDDC*       pcbddc = (PC_BDDC*)pc->data;
    5065:   Mat            new_mat,lA;
    5066:   IS             is_local,is_global;
    5067:   PetscInt       local_size;
    5068:   PetscBool      isseqaij;

    5072:   MatDestroy(&pcbddc->local_mat);
    5073:   MatGetSize(matis->A,&local_size,NULL);
    5074:   ISCreateStride(PetscObjectComm((PetscObject)matis->A),local_size,0,1,&is_local);
    5075:   ISLocalToGlobalMappingApplyIS(pc->pmat->rmap->mapping,is_local,&is_global);
    5076:   ISDestroy(&is_local);
    5077:   MatCreateSubMatrixUnsorted(ChangeOfBasisMatrix,is_global,is_global,&new_mat);
    5078:   ISDestroy(&is_global);

    5080:   if (pcbddc->dbg_flag) {
    5081:     Vec       x,x_change;
    5082:     PetscReal error;

    5084:     MatCreateVecs(ChangeOfBasisMatrix,&x,&x_change);
    5085:     VecSetRandom(x,NULL);
    5086:     MatMult(ChangeOfBasisMatrix,x,x_change);
    5087:     VecScatterBegin(matis->cctx,x,matis->x,INSERT_VALUES,SCATTER_FORWARD);
    5088:     VecScatterEnd(matis->cctx,x,matis->x,INSERT_VALUES,SCATTER_FORWARD);
    5089:     MatMult(new_mat,matis->x,matis->y);
    5090:     if (!pcbddc->change_interior) {
    5091:       const PetscScalar *x,*y,*v;
    5092:       PetscReal         lerror = 0.;
    5093:       PetscInt          i;

    5095:       VecGetArrayRead(matis->x,&x);
    5096:       VecGetArrayRead(matis->y,&y);
    5097:       VecGetArrayRead(matis->counter,&v);
    5098:       for (i=0;i<local_size;i++)
    5099:         if (PetscRealPart(v[i]) < 1.5 && PetscAbsScalar(x[i]-y[i]) > lerror)
    5100:           lerror = PetscAbsScalar(x[i]-y[i]);
    5101:       VecRestoreArrayRead(matis->x,&x);
    5102:       VecRestoreArrayRead(matis->y,&y);
    5103:       VecRestoreArrayRead(matis->counter,&v);
    5104:       MPIU_Allreduce(&lerror,&error,1,MPIU_REAL,MPI_MAX,PetscObjectComm((PetscObject)pc));
    5105:       if (error > PETSC_SMALL) {
    5106:         if (!pcbddc->user_ChangeOfBasisMatrix || pcbddc->current_level) {
    5107:           SETERRQ1(PetscObjectComm((PetscObject)pc),PETSC_ERR_PLIB,"Error global vs local change on I: %1.6e",error);
    5108:         } else {
    5109:           SETERRQ1(PetscObjectComm((PetscObject)pc),PETSC_ERR_USER,"Error global vs local change on I: %1.6e",error);
    5110:         }
    5111:       }
    5112:     }
    5113:     VecScatterBegin(matis->rctx,matis->y,x,INSERT_VALUES,SCATTER_REVERSE);
    5114:     VecScatterEnd(matis->rctx,matis->y,x,INSERT_VALUES,SCATTER_REVERSE);
    5115:     VecAXPY(x,-1.0,x_change);
    5116:     VecNorm(x,NORM_INFINITY,&error);
    5117:     if (error > PETSC_SMALL) {
    5118:       if (!pcbddc->user_ChangeOfBasisMatrix || pcbddc->current_level) {
    5119:         SETERRQ1(PetscObjectComm((PetscObject)pc),PETSC_ERR_PLIB,"Error global vs local change on N: %1.6e",error);
    5120:       } else {
    5121:         SETERRQ1(PetscObjectComm((PetscObject)pc),PETSC_ERR_USER,"Error global vs local change on N: %1.6e",error);
    5122:       }
    5123:     }
    5124:     VecDestroy(&x);
    5125:     VecDestroy(&x_change);
    5126:   }

    5128:   /* lA is present if we are setting up an inner BDDC for a saddle point FETI-DP */
    5129:   PetscObjectQuery((PetscObject)pc,"__KSPFETIDP_lA" ,(PetscObject*)&lA);

    5131:   /* TODO: HOW TO WORK WITH BAIJ and SBAIJ and SEQDENSE? */
    5132:   PetscObjectBaseTypeCompare((PetscObject)matis->A,MATSEQAIJ,&isseqaij);
    5133:   if (isseqaij) {
    5134:     MatDestroy(&pcbddc->local_mat);
    5135:     MatPtAP(matis->A,new_mat,MAT_INITIAL_MATRIX,2.0,&pcbddc->local_mat);
    5136:     if (lA) {
    5137:       Mat work;
    5138:       MatPtAP(lA,new_mat,MAT_INITIAL_MATRIX,2.0,&work);
    5139:       PetscObjectCompose((PetscObject)pc,"__KSPFETIDP_lA" ,(PetscObject)work);
    5140:       MatDestroy(&work);
    5141:     }
    5142:   } else {
    5143:     Mat work_mat;

    5145:     MatDestroy(&pcbddc->local_mat);
    5146:     MatConvert(matis->A,MATSEQAIJ,MAT_INITIAL_MATRIX,&work_mat);
    5147:     MatPtAP(work_mat,new_mat,MAT_INITIAL_MATRIX,2.0,&pcbddc->local_mat);
    5148:     MatDestroy(&work_mat);
    5149:     if (lA) {
    5150:       Mat work;
    5151:       MatConvert(lA,MATSEQAIJ,MAT_INITIAL_MATRIX,&work_mat);
    5152:       MatPtAP(work_mat,new_mat,MAT_INITIAL_MATRIX,2.0,&work);
    5153:       PetscObjectCompose((PetscObject)pc,"__KSPFETIDP_lA" ,(PetscObject)work);
    5154:       MatDestroy(&work);
    5155:     }
    5156:   }
    5157:   if (matis->A->symmetric_set) {
    5158:     MatSetOption(pcbddc->local_mat,MAT_SYMMETRIC,matis->A->symmetric);
    5159: #if !defined(PETSC_USE_COMPLEX)
    5160:     MatSetOption(pcbddc->local_mat,MAT_HERMITIAN,matis->A->symmetric);
    5161: #endif
    5162:   }
    5163:   MatDestroy(&new_mat);
    5164:   return(0);
    5165: }

    5167: PetscErrorCode PCBDDCSetUpLocalScatters(PC pc)
    5168: {
    5169:   PC_IS*          pcis = (PC_IS*)(pc->data);
    5170:   PC_BDDC*        pcbddc = (PC_BDDC*)pc->data;
    5171:   PCBDDCSubSchurs sub_schurs = pcbddc->sub_schurs;
    5172:   PetscInt        *idx_R_local=NULL;
    5173:   PetscInt        n_vertices,i,j,n_R,n_D,n_B;
    5174:   PetscInt        vbs,bs;
    5175:   PetscBT         bitmask=NULL;
    5176:   PetscErrorCode  ierr;

    5179:   /*
    5180:     No need to setup local scatters if
    5181:       - primal space is unchanged
    5182:         AND
    5183:       - we actually have locally some primal dofs (could not be true in multilevel or for isolated subdomains)
    5184:         AND
    5185:       - we are not in debugging mode (this is needed since there are Synchronized prints at the end of the subroutine
    5186:   */
    5187:   if (!pcbddc->new_primal_space_local && pcbddc->local_primal_size && !pcbddc->dbg_flag) {
    5188:     return(0);
    5189:   }
    5190:   /* destroy old objects */
    5191:   ISDestroy(&pcbddc->is_R_local);
    5192:   VecScatterDestroy(&pcbddc->R_to_B);
    5193:   VecScatterDestroy(&pcbddc->R_to_D);
    5194:   /* Set Non-overlapping dimensions */
    5195:   n_B = pcis->n_B;
    5196:   n_D = pcis->n - n_B;
    5197:   n_vertices = pcbddc->n_vertices;

    5199:   /* Dohrmann's notation: dofs splitted in R (Remaining: all dofs but the vertices) and V (Vertices) */

    5201:   /* create auxiliary bitmask and allocate workspace */
    5202:   if (!sub_schurs || !sub_schurs->reuse_solver) {
    5203:     PetscMalloc1(pcis->n-n_vertices,&idx_R_local);
    5204:     PetscBTCreate(pcis->n,&bitmask);
    5205:     for (i=0;i<n_vertices;i++) {
    5206:       PetscBTSet(bitmask,pcbddc->local_primal_ref_node[i]);
    5207:     }

    5209:     for (i=0, n_R=0; i<pcis->n; i++) {
    5210:       if (!PetscBTLookup(bitmask,i)) {
    5211:         idx_R_local[n_R++] = i;
    5212:       }
    5213:     }
    5214:   } else { /* A different ordering (already computed) is present if we are reusing the Schur solver */
    5215:     PCBDDCReuseSolvers reuse_solver = sub_schurs->reuse_solver;

    5217:     ISGetIndices(reuse_solver->is_R,(const PetscInt**)&idx_R_local);
    5218:     ISGetLocalSize(reuse_solver->is_R,&n_R);
    5219:   }

    5221:   /* Block code */
    5222:   vbs = 1;
    5223:   MatGetBlockSize(pcbddc->local_mat,&bs);
    5224:   if (bs>1 && !(n_vertices%bs)) {
    5225:     PetscBool is_blocked = PETSC_TRUE;
    5226:     PetscInt  *vary;
    5227:     if (!sub_schurs || !sub_schurs->reuse_solver) {
    5228:       PetscMalloc1(pcis->n/bs,&vary);
    5229:       PetscArrayzero(vary,pcis->n/bs);
    5230:       /* Verify that the vertex indices correspond to each element in a block (code taken from sbaij2.c) */
    5231:       /* it is ok to check this way since local_primal_ref_node are always sorted by local numbering and idx_R_local is obtained as a complement */
    5232:       for (i=0; i<n_vertices; i++) vary[pcbddc->local_primal_ref_node[i]/bs]++;
    5233:       for (i=0; i<pcis->n/bs; i++) {
    5234:         if (vary[i]!=0 && vary[i]!=bs) {
    5235:           is_blocked = PETSC_FALSE;
    5236:           break;
    5237:         }
    5238:       }
    5239:       PetscFree(vary);
    5240:     } else {
    5241:       /* Verify directly the R set */
    5242:       for (i=0; i<n_R/bs; i++) {
    5243:         PetscInt j,node=idx_R_local[bs*i];
    5244:         for (j=1; j<bs; j++) {
    5245:           if (node != idx_R_local[bs*i+j]-j) {
    5246:             is_blocked = PETSC_FALSE;
    5247:             break;
    5248:           }
    5249:         }
    5250:       }
    5251:     }
    5252:     if (is_blocked) { /* build compressed IS for R nodes (complement of vertices) */
    5253:       vbs = bs;
    5254:       for (i=0;i<n_R/vbs;i++) {
    5255:         idx_R_local[i] = idx_R_local[vbs*i]/vbs;
    5256:       }
    5257:     }
    5258:   }
    5259:   ISCreateBlock(PETSC_COMM_SELF,vbs,n_R/vbs,idx_R_local,PETSC_COPY_VALUES,&pcbddc->is_R_local);
    5260:   if (sub_schurs && sub_schurs->reuse_solver) {
    5261:     PCBDDCReuseSolvers reuse_solver = sub_schurs->reuse_solver;

    5263:     ISRestoreIndices(reuse_solver->is_R,(const PetscInt**)&idx_R_local);
    5264:     ISDestroy(&reuse_solver->is_R);
    5265:     PetscObjectReference((PetscObject)pcbddc->is_R_local);
    5266:     reuse_solver->is_R = pcbddc->is_R_local;
    5267:   } else {
    5268:     PetscFree(idx_R_local);
    5269:   }

    5271:   /* print some info if requested */
    5272:   if (pcbddc->dbg_flag) {
    5273:     PetscViewerASCIIPrintf(pcbddc->dbg_viewer,"--------------------------------------------------\n");
    5274:     PetscViewerFlush(pcbddc->dbg_viewer);
    5275:     PetscViewerASCIIPushSynchronized(pcbddc->dbg_viewer);
    5276:     PetscViewerASCIISynchronizedPrintf(pcbddc->dbg_viewer,"Subdomain %04d local dimensions\n",PetscGlobalRank);
    5277:     PetscViewerASCIISynchronizedPrintf(pcbddc->dbg_viewer,"local_size = %D, dirichlet_size = %D, boundary_size = %D\n",pcis->n,n_D,n_B);
    5278:     PetscViewerASCIISynchronizedPrintf(pcbddc->dbg_viewer,"r_size = %D, v_size = %D, constraints = %D, local_primal_size = %D\n",n_R,n_vertices,pcbddc->local_primal_size-n_vertices-pcbddc->benign_n,pcbddc->local_primal_size);
    5279:     PetscViewerFlush(pcbddc->dbg_viewer);
    5280:   }

    5282:   /* VecScatters pcbddc->R_to_B and (optionally) pcbddc->R_to_D */
    5283:   if (!sub_schurs || !sub_schurs->reuse_solver) {
    5284:     IS       is_aux1,is_aux2;
    5285:     PetscInt *aux_array1,*aux_array2,*is_indices,*idx_R_local;

    5287:     ISGetIndices(pcbddc->is_R_local,(const PetscInt**)&idx_R_local);
    5288:     PetscMalloc1(pcis->n_B-n_vertices,&aux_array1);
    5289:     PetscMalloc1(pcis->n_B-n_vertices,&aux_array2);
    5290:     ISGetIndices(pcis->is_I_local,(const PetscInt**)&is_indices);
    5291:     for (i=0; i<n_D; i++) {
    5292:       PetscBTSet(bitmask,is_indices[i]);
    5293:     }
    5294:     ISRestoreIndices(pcis->is_I_local,(const PetscInt**)&is_indices);
    5295:     for (i=0, j=0; i<n_R; i++) {
    5296:       if (!PetscBTLookup(bitmask,idx_R_local[i])) {
    5297:         aux_array1[j++] = i;
    5298:       }
    5299:     }
    5300:     ISCreateGeneral(PETSC_COMM_SELF,j,aux_array1,PETSC_OWN_POINTER,&is_aux1);
    5301:     ISGetIndices(pcis->is_B_local,(const PetscInt**)&is_indices);
    5302:     for (i=0, j=0; i<n_B; i++) {
    5303:       if (!PetscBTLookup(bitmask,is_indices[i])) {
    5304:         aux_array2[j++] = i;
    5305:       }
    5306:     }
    5307:     ISRestoreIndices(pcis->is_B_local,(const PetscInt**)&is_indices);
    5308:     ISCreateGeneral(PETSC_COMM_SELF,j,aux_array2,PETSC_OWN_POINTER,&is_aux2);
    5309:     VecScatterCreate(pcbddc->vec1_R,is_aux1,pcis->vec1_B,is_aux2,&pcbddc->R_to_B);
    5310:     ISDestroy(&is_aux1);
    5311:     ISDestroy(&is_aux2);

    5313:     if (pcbddc->switch_static || pcbddc->dbg_flag) {
    5314:       PetscMalloc1(n_D,&aux_array1);
    5315:       for (i=0, j=0; i<n_R; i++) {
    5316:         if (PetscBTLookup(bitmask,idx_R_local[i])) {
    5317:           aux_array1[j++] = i;
    5318:         }
    5319:       }
    5320:       ISCreateGeneral(PETSC_COMM_SELF,j,aux_array1,PETSC_OWN_POINTER,&is_aux1);
    5321:       VecScatterCreate(pcbddc->vec1_R,is_aux1,pcis->vec1_D,(IS)0,&pcbddc->R_to_D);
    5322:       ISDestroy(&is_aux1);
    5323:     }
    5324:     PetscBTDestroy(&bitmask);
    5325:     ISRestoreIndices(pcbddc->is_R_local,(const PetscInt**)&idx_R_local);
    5326:   } else {
    5327:     PCBDDCReuseSolvers reuse_solver = sub_schurs->reuse_solver;
    5328:     IS                 tis;
    5329:     PetscInt           schur_size;

    5331:     ISGetLocalSize(reuse_solver->is_B,&schur_size);
    5332:     ISCreateStride(PETSC_COMM_SELF,schur_size,n_D,1,&tis);
    5333:     VecScatterCreate(pcbddc->vec1_R,tis,pcis->vec1_B,reuse_solver->is_B,&pcbddc->R_to_B);
    5334:     ISDestroy(&tis);
    5335:     if (pcbddc->switch_static || pcbddc->dbg_flag) {
    5336:       ISCreateStride(PETSC_COMM_SELF,n_D,0,1,&tis);
    5337:       VecScatterCreate(pcbddc->vec1_R,tis,pcis->vec1_D,(IS)0,&pcbddc->R_to_D);
    5338:       ISDestroy(&tis);
    5339:     }
    5340:   }
    5341:   return(0);
    5342: }

    5344: static PetscErrorCode MatNullSpacePropagateAny_Private(Mat A, IS is, Mat B)
    5345: {
    5346:   MatNullSpace   NullSpace;
    5347:   Mat            dmat;
    5348:   const Vec      *nullvecs;
    5349:   Vec            v,v2,*nullvecs2;
    5350:   VecScatter     sct = NULL;
    5351:   PetscContainer c;
    5352:   PetscScalar    *ddata;
    5353:   PetscInt       k,nnsp_size,bsiz,bsiz2,n,N,bs;
    5354:   PetscBool      nnsp_has_cnst;

    5358:   if (!is && !B) { /* MATIS */
    5359:     Mat_IS* matis = (Mat_IS*)A->data;

    5361:     if (!B) {
    5362:       MatISGetLocalMat(A,&B);
    5363:     }
    5364:     sct  = matis->cctx;
    5365:     PetscObjectReference((PetscObject)sct);
    5366:   } else {
    5367:     MatGetNullSpace(B,&NullSpace);
    5368:     if (!NullSpace) {
    5369:       MatGetNearNullSpace(B,&NullSpace);
    5370:     }
    5371:     if (NullSpace) return(0);
    5372:   }
    5373:   MatGetNullSpace(A,&NullSpace);
    5374:   if (!NullSpace) {
    5375:     MatGetNearNullSpace(A,&NullSpace);
    5376:   }
    5377:   if (!NullSpace) return(0);

    5379:   MatCreateVecs(A,&v,NULL);
    5380:   MatCreateVecs(B,&v2,NULL);
    5381:   if (!sct) {
    5382:     VecScatterCreate(v,is,v2,NULL,&sct);
    5383:   }
    5384:   MatNullSpaceGetVecs(NullSpace,&nnsp_has_cnst,&nnsp_size,(const Vec**)&nullvecs);
    5385:   bsiz = bsiz2 = nnsp_size+!!nnsp_has_cnst;
    5386:   PetscMalloc1(bsiz,&nullvecs2);
    5387:   VecGetBlockSize(v2,&bs);
    5388:   VecGetSize(v2,&N);
    5389:   VecGetLocalSize(v2,&n);
    5390:   PetscMalloc1(n*bsiz,&ddata);
    5391:   for (k=0;k<nnsp_size;k++) {
    5392:     VecCreateMPIWithArray(PetscObjectComm((PetscObject)B),bs,n,N,ddata + n*k,&nullvecs2[k]);
    5393:     VecScatterBegin(sct,nullvecs[k],nullvecs2[k],INSERT_VALUES,SCATTER_FORWARD);
    5394:     VecScatterEnd(sct,nullvecs[k],nullvecs2[k],INSERT_VALUES,SCATTER_FORWARD);
    5395:   }
    5396:   if (nnsp_has_cnst) {
    5397:     VecCreateMPIWithArray(PetscObjectComm((PetscObject)B),bs,n,N,ddata + n*nnsp_size,&nullvecs2[nnsp_size]);
    5398:     VecSet(nullvecs2[nnsp_size],1.0);
    5399:   }
    5400:   PCBDDCOrthonormalizeVecs(&bsiz2,nullvecs2);
    5401:   MatNullSpaceCreate(PetscObjectComm((PetscObject)B),PETSC_FALSE,bsiz2,nullvecs2,&NullSpace);

    5403:   MatCreateDense(PetscObjectComm((PetscObject)B),n,PETSC_DECIDE,N,bsiz2,ddata,&dmat);
    5404:   PetscContainerCreate(PetscObjectComm((PetscObject)B),&c);
    5405:   PetscContainerSetPointer(c,ddata);
    5406:   PetscContainerSetUserDestroy(c,PetscContainerUserDestroyDefault);
    5407:   PetscObjectCompose((PetscObject)dmat,"_PBDDC_Null_dmat_arr",(PetscObject)c);
    5408:   PetscContainerDestroy(&c);
    5409:   PetscObjectCompose((PetscObject)NullSpace,"_PBDDC_Null_dmat",(PetscObject)dmat);
    5410:   MatDestroy(&dmat);

    5412:   for (k=0;k<bsiz;k++) {
    5413:     VecDestroy(&nullvecs2[k]);
    5414:   }
    5415:   PetscFree(nullvecs2);
    5416:   MatSetNearNullSpace(B,NullSpace);
    5417:   MatNullSpaceDestroy(&NullSpace);
    5418:   VecDestroy(&v);
    5419:   VecDestroy(&v2);
    5420:   VecScatterDestroy(&sct);
    5421:   return(0);
    5422: }

    5424: PetscErrorCode PCBDDCSetUpLocalSolvers(PC pc, PetscBool dirichlet, PetscBool neumann)
    5425: {
    5426:   PC_BDDC        *pcbddc = (PC_BDDC*)pc->data;
    5427:   PC_IS          *pcis = (PC_IS*)pc->data;
    5428:   PC             pc_temp;
    5429:   Mat            A_RR;
    5430:   MatNullSpace   nnsp;
    5431:   MatReuse       reuse;
    5432:   PetscScalar    m_one = -1.0;
    5433:   PetscReal      value;
    5434:   PetscInt       n_D,n_R;
    5435:   PetscBool      issbaij,opts;
    5437:   void           (*f)(void) = 0;
    5438:   char           dir_prefix[256],neu_prefix[256],str_level[16];
    5439:   size_t         len;

    5442:   PetscLogEventBegin(PC_BDDC_LocalSolvers[pcbddc->current_level],pc,0,0,0);
    5443:   /* approximate solver, propagate NearNullSpace if needed */
    5444:   if (!pc->setupcalled && (pcbddc->NullSpace_corr[0] || pcbddc->NullSpace_corr[2])) {
    5445:     MatNullSpace gnnsp1,gnnsp2;
    5446:     PetscBool    lhas,ghas;

    5448:     MatGetNearNullSpace(pcbddc->local_mat,&nnsp);
    5449:     MatGetNearNullSpace(pc->pmat,&gnnsp1);
    5450:     MatGetNullSpace(pc->pmat,&gnnsp2);
    5451:     lhas = nnsp ? PETSC_TRUE : PETSC_FALSE;
    5452:     MPIU_Allreduce(&lhas,&ghas,1,MPIU_BOOL,MPI_LOR,PetscObjectComm((PetscObject)pc));
    5453:     if (!ghas && (gnnsp1 || gnnsp2)) {
    5454:       MatNullSpacePropagateAny_Private(pc->pmat,NULL,NULL);
    5455:     }
    5456:   }

    5458:   /* compute prefixes */
    5459:   PetscStrcpy(dir_prefix,"");
    5460:   PetscStrcpy(neu_prefix,"");
    5461:   if (!pcbddc->current_level) {
    5462:     PetscStrncpy(dir_prefix,((PetscObject)pc)->prefix,sizeof(dir_prefix));
    5463:     PetscStrncpy(neu_prefix,((PetscObject)pc)->prefix,sizeof(neu_prefix));
    5464:     PetscStrlcat(dir_prefix,"pc_bddc_dirichlet_",sizeof(dir_prefix));
    5465:     PetscStrlcat(neu_prefix,"pc_bddc_neumann_",sizeof(neu_prefix));
    5466:   } else {
    5467:     PetscSNPrintf(str_level,sizeof(str_level),"l%d_",(int)(pcbddc->current_level));
    5468:     PetscStrlen(((PetscObject)pc)->prefix,&len);
    5469:     len -= 15; /* remove "pc_bddc_coarse_" */
    5470:     if (pcbddc->current_level>1) len -= 3; /* remove "lX_" with X level number */
    5471:     if (pcbddc->current_level>10) len -= 1; /* remove another char from level number */
    5472:     /* Nonstandard use of PetscStrncpy() to only copy a portion of the input string */
    5473:     PetscStrncpy(dir_prefix,((PetscObject)pc)->prefix,len+1);
    5474:     PetscStrncpy(neu_prefix,((PetscObject)pc)->prefix,len+1);
    5475:     PetscStrlcat(dir_prefix,"pc_bddc_dirichlet_",sizeof(dir_prefix));
    5476:     PetscStrlcat(neu_prefix,"pc_bddc_neumann_",sizeof(neu_prefix));
    5477:     PetscStrlcat(dir_prefix,str_level,sizeof(dir_prefix));
    5478:     PetscStrlcat(neu_prefix,str_level,sizeof(neu_prefix));
    5479:   }

    5481:   /* DIRICHLET PROBLEM */
    5482:   if (dirichlet) {
    5483:     PCBDDCSubSchurs sub_schurs = pcbddc->sub_schurs;
    5484:     if (pcbddc->benign_n && !pcbddc->benign_change_explicit) {
    5485:       if (!sub_schurs || !sub_schurs->reuse_solver) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"Not yet implemented");
    5486:       if (pcbddc->dbg_flag) {
    5487:         Mat    A_IIn;

    5489:         PCBDDCBenignProject(pc,pcis->is_I_local,pcis->is_I_local,&A_IIn);
    5490:         MatDestroy(&pcis->A_II);
    5491:         pcis->A_II = A_IIn;
    5492:       }
    5493:     }
    5494:     if (pcbddc->local_mat->symmetric_set) {
    5495:       MatSetOption(pcis->A_II,MAT_SYMMETRIC,pcbddc->local_mat->symmetric);
    5496:     }
    5497:     /* Matrix for Dirichlet problem is pcis->A_II */
    5498:     n_D  = pcis->n - pcis->n_B;
    5499:     opts = PETSC_FALSE;
    5500:     if (!pcbddc->ksp_D) { /* create object if not yet build */
    5501:       opts = PETSC_TRUE;
    5502:       KSPCreate(PETSC_COMM_SELF,&pcbddc->ksp_D);
    5503:       PetscObjectIncrementTabLevel((PetscObject)pcbddc->ksp_D,(PetscObject)pc,1);
    5504:       /* default */
    5505:       KSPSetType(pcbddc->ksp_D,KSPPREONLY);
    5506:       KSPSetOptionsPrefix(pcbddc->ksp_D,dir_prefix);
    5507:       PetscObjectTypeCompare((PetscObject)pcis->pA_II,MATSEQSBAIJ,&issbaij);
    5508:       KSPGetPC(pcbddc->ksp_D,&pc_temp);
    5509:       if (issbaij) {
    5510:         PCSetType(pc_temp,PCCHOLESKY);
    5511:       } else {
    5512:         PCSetType(pc_temp,PCLU);
    5513:       }
    5514:       KSPSetErrorIfNotConverged(pcbddc->ksp_D,pc->erroriffailure);
    5515:     }
    5516:     MatSetOptionsPrefix(pcis->pA_II,((PetscObject)pcbddc->ksp_D)->prefix);
    5517:     KSPSetOperators(pcbddc->ksp_D,pcis->A_II,pcis->pA_II);
    5518:     /* Allow user's customization */
    5519:     if (opts) {
    5520:       KSPSetFromOptions(pcbddc->ksp_D);
    5521:     }
    5522:     MatGetNearNullSpace(pcis->pA_II,&nnsp);
    5523:     if (pcbddc->NullSpace_corr[0] && !nnsp) { /* approximate solver, propagate NearNullSpace */
    5524:       MatNullSpacePropagateAny_Private(pcbddc->local_mat,pcis->is_I_local,pcis->pA_II);
    5525:     }
    5526:     MatGetNearNullSpace(pcis->pA_II,&nnsp);
    5527:     KSPGetPC(pcbddc->ksp_D,&pc_temp);
    5528:     PetscObjectQueryFunction((PetscObject)pc_temp,"PCSetCoordinates_C",&f);
    5529:     if (f && pcbddc->mat_graph->cloc && !nnsp) {
    5530:       PetscReal      *coords = pcbddc->mat_graph->coords,*scoords;
    5531:       const PetscInt *idxs;
    5532:       PetscInt       cdim = pcbddc->mat_graph->cdim,nl,i,d;

    5534:       ISGetLocalSize(pcis->is_I_local,&nl);
    5535:       ISGetIndices(pcis->is_I_local,&idxs);
    5536:       PetscMalloc1(nl*cdim,&scoords);
    5537:       for (i=0;i<nl;i++) {
    5538:         for (d=0;d<cdim;d++) {
    5539:           scoords[i*cdim+d] = coords[idxs[i]*cdim+d];
    5540:         }
    5541:       }
    5542:       ISRestoreIndices(pcis->is_I_local,&idxs);
    5543:       PCSetCoordinates(pc_temp,cdim,nl,scoords);
    5544:       PetscFree(scoords);
    5545:     }
    5546:     if (sub_schurs && sub_schurs->reuse_solver) {
    5547:       PCBDDCReuseSolvers reuse_solver = sub_schurs->reuse_solver;

    5549:       KSPSetPC(pcbddc->ksp_D,reuse_solver->interior_solver);
    5550:     }

    5552:     /* umfpack interface has a bug when matrix dimension is zero. TODO solve from umfpack interface */
    5553:     if (!n_D) {
    5554:       KSPGetPC(pcbddc->ksp_D,&pc_temp);
    5555:       PCSetType(pc_temp,PCNONE);
    5556:     }
    5557:     KSPSetUp(pcbddc->ksp_D);
    5558:     /* set ksp_D into pcis data */
    5559:     PetscObjectReference((PetscObject)pcbddc->ksp_D);
    5560:     KSPDestroy(&pcis->ksp_D);
    5561:     pcis->ksp_D = pcbddc->ksp_D;
    5562:   }

    5564:   /* NEUMANN PROBLEM */
    5565:   A_RR = 0;
    5566:   if (neumann) {
    5567:     PCBDDCSubSchurs sub_schurs = pcbddc->sub_schurs;
    5568:     PetscInt        ibs,mbs;
    5569:     PetscBool       issbaij, reuse_neumann_solver;
    5570:     Mat_IS*         matis = (Mat_IS*)pc->pmat->data;

    5572:     reuse_neumann_solver = PETSC_FALSE;
    5573:     if (sub_schurs && sub_schurs->reuse_solver) {
    5574:       IS iP;

    5576:       reuse_neumann_solver = PETSC_TRUE;
    5577:       PetscObjectQuery((PetscObject)sub_schurs->A,"__KSPFETIDP_iP",(PetscObject*)&iP);
    5578:       if (iP) reuse_neumann_solver = PETSC_FALSE;
    5579:     }
    5580:     /* Matrix for Neumann problem is A_RR -> we need to create/reuse it at this point */
    5581:     ISGetSize(pcbddc->is_R_local,&n_R);
    5582:     if (pcbddc->ksp_R) { /* already created ksp */
    5583:       PetscInt nn_R;
    5584:       KSPGetOperators(pcbddc->ksp_R,NULL,&A_RR);
    5585:       PetscObjectReference((PetscObject)A_RR);
    5586:       MatGetSize(A_RR,&nn_R,NULL);
    5587:       if (nn_R != n_R) { /* old ksp is not reusable, so reset it */
    5588:         KSPReset(pcbddc->ksp_R);
    5589:         MatDestroy(&A_RR);
    5590:         reuse = MAT_INITIAL_MATRIX;
    5591:       } else { /* same sizes, but nonzero pattern depend on primal vertices so it can be changed */
    5592:         if (pcbddc->new_primal_space_local) { /* we are not sure the matrix will have the same nonzero pattern */
    5593:           MatDestroy(&A_RR);
    5594:           reuse = MAT_INITIAL_MATRIX;
    5595:         } else { /* safe to reuse the matrix */
    5596:           reuse = MAT_REUSE_MATRIX;
    5597:         }
    5598:       }
    5599:       /* last check */
    5600:       if (pc->flag == DIFFERENT_NONZERO_PATTERN) {
    5601:         MatDestroy(&A_RR);
    5602:         reuse = MAT_INITIAL_MATRIX;
    5603:       }
    5604:     } else { /* first time, so we need to create the matrix */
    5605:       reuse = MAT_INITIAL_MATRIX;
    5606:     }
    5607:     /* convert pcbddc->local_mat if needed later in PCBDDCSetUpCorrection
    5608:        TODO: Get Rid of these conversions */
    5609:     MatGetBlockSize(pcbddc->local_mat,&mbs);
    5610:     ISGetBlockSize(pcbddc->is_R_local,&ibs);
    5611:     PetscObjectTypeCompare((PetscObject)pcbddc->local_mat,MATSEQSBAIJ,&issbaij);
    5612:     if (ibs != mbs) { /* need to convert to SEQAIJ to extract any submatrix with is_R_local */
    5613:       if (matis->A == pcbddc->local_mat) {
    5614:         MatDestroy(&pcbddc->local_mat);
    5615:         MatConvert(matis->A,MATSEQAIJ,MAT_INITIAL_MATRIX,&pcbddc->local_mat);
    5616:       } else {
    5617:         MatConvert(pcbddc->local_mat,MATSEQAIJ,MAT_INPLACE_MATRIX,&pcbddc->local_mat);
    5618:       }
    5619:     } else if (issbaij) { /* need to convert to BAIJ to get offdiagonal blocks */
    5620:       if (matis->A == pcbddc->local_mat) {
    5621:         MatDestroy(&pcbddc->local_mat);
    5622:         MatConvert(matis->A,mbs > 1 ? MATSEQBAIJ : MATSEQAIJ,MAT_INITIAL_MATRIX,&pcbddc->local_mat);
    5623:       } else {
    5624:         MatConvert(pcbddc->local_mat,mbs > 1 ? MATSEQBAIJ : MATSEQAIJ,MAT_INPLACE_MATRIX,&pcbddc->local_mat);
    5625:       }
    5626:     }
    5627:     /* extract A_RR */
    5628:     if (reuse_neumann_solver) {
    5629:       PCBDDCReuseSolvers reuse_solver = sub_schurs->reuse_solver;

    5631:       if (pcbddc->dbg_flag) { /* we need A_RR to test the solver later */
    5632:         MatDestroy(&A_RR);
    5633:         if (reuse_solver->benign_n) { /* we are not using the explicit change of basis on the pressures */
    5634:           PCBDDCBenignProject(pc,pcbddc->is_R_local,pcbddc->is_R_local,&A_RR);
    5635:         } else {
    5636:           MatCreateSubMatrix(pcbddc->local_mat,pcbddc->is_R_local,pcbddc->is_R_local,MAT_INITIAL_MATRIX,&A_RR);
    5637:         }
    5638:       } else {
    5639:         MatDestroy(&A_RR);
    5640:         PCGetOperators(reuse_solver->correction_solver,&A_RR,NULL);
    5641:         PetscObjectReference((PetscObject)A_RR);
    5642:       }
    5643:     } else { /* we have to build the neumann solver, so we need to extract the relevant matrix */
    5644:       MatCreateSubMatrix(pcbddc->local_mat,pcbddc->is_R_local,pcbddc->is_R_local,reuse,&A_RR);
    5645:     }
    5646:     if (pcbddc->local_mat->symmetric_set) {
    5647:       MatSetOption(A_RR,MAT_SYMMETRIC,pcbddc->local_mat->symmetric);
    5648:     }
    5649:     opts = PETSC_FALSE;
    5650:     if (!pcbddc->ksp_R) { /* create object if not present */
    5651:       opts = PETSC_TRUE;
    5652:       KSPCreate(PETSC_COMM_SELF,&pcbddc->ksp_R);
    5653:       PetscObjectIncrementTabLevel((PetscObject)pcbddc->ksp_R,(PetscObject)pc,1);
    5654:       /* default */
    5655:       KSPSetType(pcbddc->ksp_R,KSPPREONLY);
    5656:       KSPSetOptionsPrefix(pcbddc->ksp_R,neu_prefix);
    5657:       KSPGetPC(pcbddc->ksp_R,&pc_temp);
    5658:       PetscObjectTypeCompare((PetscObject)A_RR,MATSEQSBAIJ,&issbaij);
    5659:       if (issbaij) {
    5660:         PCSetType(pc_temp,PCCHOLESKY);
    5661:       } else {
    5662:         PCSetType(pc_temp,PCLU);
    5663:       }
    5664:       KSPSetErrorIfNotConverged(pcbddc->ksp_R,pc->erroriffailure);
    5665:     }
    5666:     KSPSetOperators(pcbddc->ksp_R,A_RR,A_RR);
    5667:     MatSetOptionsPrefix(A_RR,((PetscObject)pcbddc->ksp_R)->prefix);
    5668:     if (opts) { /* Allow user's customization once */
    5669:       KSPSetFromOptions(pcbddc->ksp_R);
    5670:     }
    5671:     MatGetNearNullSpace(A_RR,&nnsp);
    5672:     if (pcbddc->NullSpace_corr[2] && !nnsp) { /* approximate solver, propagate NearNullSpace */
    5673:       MatNullSpacePropagateAny_Private(pcbddc->local_mat,pcbddc->is_R_local,A_RR);
    5674:     }
    5675:     MatGetNearNullSpace(A_RR,&nnsp);
    5676:     KSPGetPC(pcbddc->ksp_R,&pc_temp);
    5677:     PetscObjectQueryFunction((PetscObject)pc_temp,"PCSetCoordinates_C",&f);
    5678:     if (f && pcbddc->mat_graph->cloc && !nnsp) {
    5679:       PetscReal      *coords = pcbddc->mat_graph->coords,*scoords;
    5680:       const PetscInt *idxs;
    5681:       PetscInt       cdim = pcbddc->mat_graph->cdim,nl,i,d;

    5683:       ISGetLocalSize(pcbddc->is_R_local,&nl);
    5684:       ISGetIndices(pcbddc->is_R_local,&idxs);
    5685:       PetscMalloc1(nl*cdim,&scoords);
    5686:       for (i=0;i<nl;i++) {
    5687:         for (d=0;d<cdim;d++) {
    5688:           scoords[i*cdim+d] = coords[idxs[i]*cdim+d];
    5689:         }
    5690:       }
    5691:       ISRestoreIndices(pcbddc->is_R_local,&idxs);
    5692:       PCSetCoordinates(pc_temp,cdim,nl,scoords);
    5693:       PetscFree(scoords);
    5694:     }

    5696:     /* umfpack interface has a bug when matrix dimension is zero. TODO solve from umfpack interface */
    5697:     if (!n_R) {
    5698:       KSPGetPC(pcbddc->ksp_R,&pc_temp);
    5699:       PCSetType(pc_temp,PCNONE);
    5700:     }
    5701:     /* Reuse solver if it is present */
    5702:     if (reuse_neumann_solver) {
    5703:       PCBDDCReuseSolvers reuse_solver = sub_schurs->reuse_solver;

    5705:       KSPSetPC(pcbddc->ksp_R,reuse_solver->correction_solver);
    5706:     }
    5707:     KSPSetUp(pcbddc->ksp_R);
    5708:   }

    5710:   if (pcbddc->dbg_flag) {
    5711:     PetscViewerFlush(pcbddc->dbg_viewer);
    5712:     PetscViewerASCIIPushSynchronized(pcbddc->dbg_viewer);
    5713:     PetscViewerASCIIPrintf(pcbddc->dbg_viewer,"--------------------------------------------------\n");
    5714:   }
    5715:   PetscLogEventEnd(PC_BDDC_LocalSolvers[pcbddc->current_level],pc,0,0,0);

    5717:   /* adapt Dirichlet and Neumann solvers if a nullspace correction has been requested */
    5718:   if (pcbddc->NullSpace_corr[0]) {
    5719:     PCBDDCSetUseExactDirichlet(pc,PETSC_FALSE);
    5720:   }
    5721:   if (dirichlet && pcbddc->NullSpace_corr[0] && !pcbddc->switch_static) {
    5722:     PCBDDCNullSpaceAssembleCorrection(pc,PETSC_TRUE,pcbddc->NullSpace_corr[1]);
    5723:   }
    5724:   if (neumann && pcbddc->NullSpace_corr[2]) {
    5725:     PCBDDCNullSpaceAssembleCorrection(pc,PETSC_FALSE,pcbddc->NullSpace_corr[3]);
    5726:   }
    5727:   /* check Dirichlet and Neumann solvers */
    5728:   if (pcbddc->dbg_flag) {
    5729:     if (dirichlet) { /* Dirichlet */
    5730:       VecSetRandom(pcis->vec1_D,NULL);
    5731:       MatMult(pcis->A_II,pcis->vec1_D,pcis->vec2_D);
    5732:       KSPSolve(pcbddc->ksp_D,pcis->vec2_D,pcis->vec2_D);
    5733:       KSPCheckSolve(pcbddc->ksp_D,pc,pcis->vec2_D);
    5734:       VecAXPY(pcis->vec1_D,m_one,pcis->vec2_D);
    5735:       VecNorm(pcis->vec1_D,NORM_INFINITY,&value);
    5736:       PetscViewerASCIISynchronizedPrintf(pcbddc->dbg_viewer,"Subdomain %04d infinity error for Dirichlet solve (%s) = % 1.14e \n",PetscGlobalRank,((PetscObject)(pcbddc->ksp_D))->prefix,value);
    5737:       PetscViewerFlush(pcbddc->dbg_viewer);
    5738:     }
    5739:     if (neumann) { /* Neumann */
    5740:       VecSetRandom(pcbddc->vec1_R,NULL);
    5741:       MatMult(A_RR,pcbddc->vec1_R,pcbddc->vec2_R);
    5742:       KSPSolve(pcbddc->ksp_R,pcbddc->vec2_R,pcbddc->vec2_R);
    5743:       KSPCheckSolve(pcbddc->ksp_R,pc,pcbddc->vec2_R);
    5744:       VecAXPY(pcbddc->vec1_R,m_one,pcbddc->vec2_R);
    5745:       VecNorm(pcbddc->vec1_R,NORM_INFINITY,&value);
    5746:       PetscViewerASCIISynchronizedPrintf(pcbddc->dbg_viewer,"Subdomain %04d infinity error for Neumann solve (%s) = % 1.14e\n",PetscGlobalRank,((PetscObject)(pcbddc->ksp_R))->prefix,value);
    5747:       PetscViewerFlush(pcbddc->dbg_viewer);
    5748:     }
    5749:   }
    5750:   /* free Neumann problem's matrix */
    5751:   MatDestroy(&A_RR);
    5752:   return(0);
    5753: }

    5755: static PetscErrorCode  PCBDDCSolveSubstructureCorrection(PC pc, Vec inout_B, Vec inout_D, PetscBool applytranspose)
    5756: {
    5757:   PetscErrorCode  ierr;
    5758:   PC_BDDC*        pcbddc = (PC_BDDC*)(pc->data);
    5759:   PCBDDCSubSchurs sub_schurs = pcbddc->sub_schurs;
    5760:   PetscBool       reuse_solver = sub_schurs ? ( sub_schurs->reuse_solver ? PETSC_TRUE : PETSC_FALSE ) : PETSC_FALSE;

    5763:   if (!reuse_solver) {
    5764:     VecSet(pcbddc->vec1_R,0.);
    5765:   }
    5766:   if (!pcbddc->switch_static) {
    5767:     if (applytranspose && pcbddc->local_auxmat1) {
    5768:       MatMultTranspose(pcbddc->local_auxmat2,inout_B,pcbddc->vec1_C);
    5769:       MatMultTransposeAdd(pcbddc->local_auxmat1,pcbddc->vec1_C,inout_B,inout_B);
    5770:     }
    5771:     if (!reuse_solver) {
    5772:       VecScatterBegin(pcbddc->R_to_B,inout_B,pcbddc->vec1_R,INSERT_VALUES,SCATTER_REVERSE);
    5773:       VecScatterEnd(pcbddc->R_to_B,inout_B,pcbddc->vec1_R,INSERT_VALUES,SCATTER_REVERSE);
    5774:     } else {
    5775:       PCBDDCReuseSolvers reuse_solver = sub_schurs->reuse_solver;

    5777:       VecScatterBegin(reuse_solver->correction_scatter_B,inout_B,reuse_solver->rhs_B,INSERT_VALUES,SCATTER_FORWARD);
    5778:       VecScatterEnd(reuse_solver->correction_scatter_B,inout_B,reuse_solver->rhs_B,INSERT_VALUES,SCATTER_FORWARD);
    5779:     }
    5780:   } else {
    5781:     VecScatterBegin(pcbddc->R_to_B,inout_B,pcbddc->vec1_R,INSERT_VALUES,SCATTER_REVERSE);
    5782:     VecScatterEnd(pcbddc->R_to_B,inout_B,pcbddc->vec1_R,INSERT_VALUES,SCATTER_REVERSE);
    5783:     VecScatterBegin(pcbddc->R_to_D,inout_D,pcbddc->vec1_R,INSERT_VALUES,SCATTER_REVERSE);
    5784:     VecScatterEnd(pcbddc->R_to_D,inout_D,pcbddc->vec1_R,INSERT_VALUES,SCATTER_REVERSE);
    5785:     if (applytranspose && pcbddc->local_auxmat1) {
    5786:       MatMultTranspose(pcbddc->local_auxmat2,pcbddc->vec1_R,pcbddc->vec1_C);
    5787:       MatMultTransposeAdd(pcbddc->local_auxmat1,pcbddc->vec1_C,inout_B,inout_B);
    5788:       VecScatterBegin(pcbddc->R_to_B,inout_B,pcbddc->vec1_R,INSERT_VALUES,SCATTER_REVERSE);
    5789:       VecScatterEnd(pcbddc->R_to_B,inout_B,pcbddc->vec1_R,INSERT_VALUES,SCATTER_REVERSE);
    5790:     }
    5791:   }
    5792:   if (!reuse_solver || pcbddc->switch_static) {
    5793:     if (applytranspose) {
    5794:       KSPSolveTranspose(pcbddc->ksp_R,pcbddc->vec1_R,pcbddc->vec1_R);
    5795:     } else {
    5796:       KSPSolve(pcbddc->ksp_R,pcbddc->vec1_R,pcbddc->vec1_R);
    5797:     }
    5798:     KSPCheckSolve(pcbddc->ksp_R,pc,pcbddc->vec1_R);
    5799:   } else {
    5800:     PCBDDCReuseSolvers reuse_solver = sub_schurs->reuse_solver;

    5802:     if (applytranspose) {
    5803:       MatFactorSolveSchurComplementTranspose(reuse_solver->F,reuse_solver->rhs_B,reuse_solver->sol_B);
    5804:     } else {
    5805:       MatFactorSolveSchurComplement(reuse_solver->F,reuse_solver->rhs_B,reuse_solver->sol_B);
    5806:     }
    5807:   }
    5808:   VecSet(inout_B,0.);
    5809:   if (!pcbddc->switch_static) {
    5810:     if (!reuse_solver) {
    5811:       VecScatterBegin(pcbddc->R_to_B,pcbddc->vec1_R,inout_B,INSERT_VALUES,SCATTER_FORWARD);
    5812:       VecScatterEnd(pcbddc->R_to_B,pcbddc->vec1_R,inout_B,INSERT_VALUES,SCATTER_FORWARD);
    5813:     } else {
    5814:       PCBDDCReuseSolvers reuse_solver = sub_schurs->reuse_solver;

    5816:       VecScatterBegin(reuse_solver->correction_scatter_B,reuse_solver->sol_B,inout_B,INSERT_VALUES,SCATTER_REVERSE);
    5817:       VecScatterEnd(reuse_solver->correction_scatter_B,reuse_solver->sol_B,inout_B,INSERT_VALUES,SCATTER_REVERSE);
    5818:     }
    5819:     if (!applytranspose && pcbddc->local_auxmat1) {
    5820:       MatMult(pcbddc->local_auxmat1,inout_B,pcbddc->vec1_C);
    5821:       MatMultAdd(pcbddc->local_auxmat2,pcbddc->vec1_C,inout_B,inout_B);
    5822:     }
    5823:   } else {
    5824:     VecScatterBegin(pcbddc->R_to_B,pcbddc->vec1_R,inout_B,INSERT_VALUES,SCATTER_FORWARD);
    5825:     VecScatterEnd(pcbddc->R_to_B,pcbddc->vec1_R,inout_B,INSERT_VALUES,SCATTER_FORWARD);
    5826:     VecScatterBegin(pcbddc->R_to_D,pcbddc->vec1_R,inout_D,INSERT_VALUES,SCATTER_FORWARD);
    5827:     VecScatterEnd(pcbddc->R_to_D,pcbddc->vec1_R,inout_D,INSERT_VALUES,SCATTER_FORWARD);
    5828:     if (!applytranspose && pcbddc->local_auxmat1) {
    5829:       MatMult(pcbddc->local_auxmat1,inout_B,pcbddc->vec1_C);
    5830:       MatMultAdd(pcbddc->local_auxmat2,pcbddc->vec1_C,pcbddc->vec1_R,pcbddc->vec1_R);
    5831:     }
    5832:     VecScatterBegin(pcbddc->R_to_B,pcbddc->vec1_R,inout_B,INSERT_VALUES,SCATTER_FORWARD);
    5833:     VecScatterEnd(pcbddc->R_to_B,pcbddc->vec1_R,inout_B,INSERT_VALUES,SCATTER_FORWARD);
    5834:     VecScatterBegin(pcbddc->R_to_D,pcbddc->vec1_R,inout_D,INSERT_VALUES,SCATTER_FORWARD);
    5835:     VecScatterEnd(pcbddc->R_to_D,pcbddc->vec1_R,inout_D,INSERT_VALUES,SCATTER_FORWARD);
    5836:   }
    5837:   return(0);
    5838: }

    5840: /* parameter apply transpose determines if the interface preconditioner should be applied transposed or not */
    5841: PetscErrorCode  PCBDDCApplyInterfacePreconditioner(PC pc, PetscBool applytranspose)
    5842: {
    5844:   PC_BDDC*        pcbddc = (PC_BDDC*)(pc->data);
    5845:   PC_IS*            pcis = (PC_IS*)  (pc->data);
    5846:   const PetscScalar zero = 0.0;

    5849:   /* Application of PSI^T or PHI^T (depending on applytranspose, see comment above) */
    5850:   if (!pcbddc->benign_apply_coarse_only) {
    5851:     if (applytranspose) {
    5852:       MatMultTranspose(pcbddc->coarse_phi_B,pcis->vec1_B,pcbddc->vec1_P);
    5853:       if (pcbddc->switch_static) { MatMultTransposeAdd(pcbddc->coarse_phi_D,pcis->vec1_D,pcbddc->vec1_P,pcbddc->vec1_P); }
    5854:     } else {
    5855:       MatMultTranspose(pcbddc->coarse_psi_B,pcis->vec1_B,pcbddc->vec1_P);
    5856:       if (pcbddc->switch_static) { MatMultTransposeAdd(pcbddc->coarse_psi_D,pcis->vec1_D,pcbddc->vec1_P,pcbddc->vec1_P); }
    5857:     }
    5858:   } else {
    5859:     VecSet(pcbddc->vec1_P,zero);
    5860:   }

    5862:   /* add p0 to the last value of vec1_P holding the coarse dof relative to p0 */
    5863:   if (pcbddc->benign_n) {
    5864:     PetscScalar *array;
    5865:     PetscInt    j;

    5867:     VecGetArray(pcbddc->vec1_P,&array);
    5868:     for (j=0;j<pcbddc->benign_n;j++) array[pcbddc->local_primal_size-pcbddc->benign_n+j] += pcbddc->benign_p0[j];
    5869:     VecRestoreArray(pcbddc->vec1_P,&array);
    5870:   }

    5872:   /* start communications from local primal nodes to rhs of coarse solver */
    5873:   VecSet(pcbddc->coarse_vec,zero);
    5874:   PCBDDCScatterCoarseDataBegin(pc,ADD_VALUES,SCATTER_FORWARD);
    5875:   PCBDDCScatterCoarseDataEnd(pc,ADD_VALUES,SCATTER_FORWARD);

    5877:   /* Coarse solution -> rhs and sol updated inside PCBDDCScattarCoarseDataBegin/End */
    5878:   if (pcbddc->coarse_ksp) {
    5879:     Mat          coarse_mat;
    5880:     Vec          rhs,sol;
    5881:     MatNullSpace nullsp;
    5882:     PetscBool    isbddc = PETSC_FALSE;

    5884:     if (pcbddc->benign_have_null) {
    5885:       PC        coarse_pc;

    5887:       KSPGetPC(pcbddc->coarse_ksp,&coarse_pc);
    5888:       PetscObjectTypeCompare((PetscObject)coarse_pc,PCBDDC,&isbddc);
    5889:       /* we need to propagate to coarser levels the need for a possible benign correction */
    5890:       if (isbddc && pcbddc->benign_apply_coarse_only && !pcbddc->benign_skip_correction) {
    5891:         PC_BDDC* coarsepcbddc = (PC_BDDC*)(coarse_pc->data);
    5892:         coarsepcbddc->benign_skip_correction = PETSC_FALSE;
    5893:         coarsepcbddc->benign_apply_coarse_only = PETSC_TRUE;
    5894:       }
    5895:     }
    5896:     KSPGetRhs(pcbddc->coarse_ksp,&rhs);
    5897:     KSPGetSolution(pcbddc->coarse_ksp,&sol);
    5898:     KSPGetOperators(pcbddc->coarse_ksp,&coarse_mat,NULL);
    5899:     if (applytranspose) {
    5900:       if (pcbddc->benign_apply_coarse_only) SETERRQ(PetscObjectComm((PetscObject)pcbddc->coarse_ksp),PETSC_ERR_SUP,"Not yet implemented");
    5901:       KSPSolveTranspose(pcbddc->coarse_ksp,rhs,sol);
    5902:       KSPCheckSolve(pcbddc->coarse_ksp,pc,sol);
    5903:       MatGetTransposeNullSpace(coarse_mat,&nullsp);
    5904:       if (nullsp) {
    5905:         MatNullSpaceRemove(nullsp,sol);
    5906:       }
    5907:     } else {
    5908:       MatGetNullSpace(coarse_mat,&nullsp);
    5909:       if (pcbddc->benign_apply_coarse_only && isbddc) { /* need just to apply the coarse preconditioner during presolve */
    5910:         PC        coarse_pc;

    5912:         if (nullsp) {
    5913:           MatNullSpaceRemove(nullsp,rhs);
    5914:         }
    5915:         KSPGetPC(pcbddc->coarse_ksp,&coarse_pc);
    5916:         PCPreSolve(coarse_pc,pcbddc->coarse_ksp);
    5917:         PCBDDCBenignRemoveInterior(coarse_pc,rhs,sol);
    5918:         PCPostSolve(coarse_pc,pcbddc->coarse_ksp);
    5919:       } else {
    5920:         KSPSolve(pcbddc->coarse_ksp,rhs,sol);
    5921:         KSPCheckSolve(pcbddc->coarse_ksp,pc,sol);
    5922:         if (nullsp) {
    5923:           MatNullSpaceRemove(nullsp,sol);
    5924:         }
    5925:       }
    5926:     }
    5927:     /* we don't need the benign correction at coarser levels anymore */
    5928:     if (pcbddc->benign_have_null && isbddc) {
    5929:       PC        coarse_pc;
    5930:       PC_BDDC*  coarsepcbddc;

    5932:       KSPGetPC(pcbddc->coarse_ksp,&coarse_pc);
    5933:       coarsepcbddc = (PC_BDDC*)(coarse_pc->data);
    5934:       coarsepcbddc->benign_skip_correction = PETSC_TRUE;
    5935:       coarsepcbddc->benign_apply_coarse_only = PETSC_FALSE;
    5936:     }
    5937:   }

    5939:   /* Local solution on R nodes */
    5940:   if (pcis->n && !pcbddc->benign_apply_coarse_only) {
    5941:     PCBDDCSolveSubstructureCorrection(pc,pcis->vec1_B,pcis->vec1_D,applytranspose);
    5942:   }
    5943:   /* communications from coarse sol to local primal nodes */
    5944:   PCBDDCScatterCoarseDataBegin(pc,INSERT_VALUES,SCATTER_REVERSE);
    5945:   PCBDDCScatterCoarseDataEnd(pc,INSERT_VALUES,SCATTER_REVERSE);

    5947:   /* Sum contributions from the two levels */
    5948:   if (!pcbddc->benign_apply_coarse_only) {
    5949:     if (applytranspose) {
    5950:       MatMultAdd(pcbddc->coarse_psi_B,pcbddc->vec1_P,pcis->vec1_B,pcis->vec1_B);
    5951:       if (pcbddc->switch_static) { MatMultAdd(pcbddc->coarse_psi_D,pcbddc->vec1_P,pcis->vec1_D,pcis->vec1_D); }
    5952:     } else {
    5953:       MatMultAdd(pcbddc->coarse_phi_B,pcbddc->vec1_P,pcis->vec1_B,pcis->vec1_B);
    5954:       if (pcbddc->switch_static) { MatMultAdd(pcbddc->coarse_phi_D,pcbddc->vec1_P,pcis->vec1_D,pcis->vec1_D); }
    5955:     }
    5956:     /* store p0 */
    5957:     if (pcbddc->benign_n) {
    5958:       PetscScalar *array;
    5959:       PetscInt    j;

    5961:       VecGetArray(pcbddc->vec1_P,&array);
    5962:       for (j=0;j<pcbddc->benign_n;j++) pcbddc->benign_p0[j] = array[pcbddc->local_primal_size-pcbddc->benign_n+j];
    5963:       VecRestoreArray(pcbddc->vec1_P,&array);
    5964:     }
    5965:   } else { /* expand the coarse solution */
    5966:     if (applytranspose) {
    5967:       MatMult(pcbddc->coarse_psi_B,pcbddc->vec1_P,pcis->vec1_B);
    5968:     } else {
    5969:       MatMult(pcbddc->coarse_phi_B,pcbddc->vec1_P,pcis->vec1_B);
    5970:     }
    5971:   }
    5972:   return(0);
    5973: }

    5975: PetscErrorCode PCBDDCScatterCoarseDataBegin(PC pc,InsertMode imode, ScatterMode smode)
    5976: {
    5977:   PC_BDDC*          pcbddc = (PC_BDDC*)(pc->data);
    5978:   Vec               from,to;
    5979:   const PetscScalar *array;
    5980:   PetscErrorCode    ierr;

    5983:   if (smode == SCATTER_REVERSE) { /* from global to local -> get data from coarse solution */
    5984:     from = pcbddc->coarse_vec;
    5985:     to = pcbddc->vec1_P;
    5986:     if (pcbddc->coarse_ksp) { /* get array from coarse processes */
    5987:       Vec tvec;

    5989:       KSPGetRhs(pcbddc->coarse_ksp,&tvec);
    5990:       VecResetArray(tvec);
    5991:       KSPGetSolution(pcbddc->coarse_ksp,&tvec);
    5992:       VecGetArrayRead(tvec,&array);
    5993:       VecPlaceArray(from,array);
    5994:       VecRestoreArrayRead(tvec,&array);
    5995:     }
    5996:   } else { /* from local to global -> put data in coarse right hand side */
    5997:     from = pcbddc->vec1_P;
    5998:     to = pcbddc->coarse_vec;
    5999:   }
    6000:   VecScatterBegin(pcbddc->coarse_loc_to_glob,from,to,imode,smode);
    6001:   return(0);
    6002: }

    6004: PetscErrorCode PCBDDCScatterCoarseDataEnd(PC pc, InsertMode imode, ScatterMode smode)
    6005: {
    6006:   PC_BDDC*          pcbddc = (PC_BDDC*)(pc->data);
    6007:   Vec               from,to;
    6008:   const PetscScalar *array;
    6009:   PetscErrorCode    ierr;

    6012:   if (smode == SCATTER_REVERSE) { /* from global to local -> get data from coarse solution */
    6013:     from = pcbddc->coarse_vec;
    6014:     to = pcbddc->vec1_P;
    6015:   } else { /* from local to global -> put data in coarse right hand side */
    6016:     from = pcbddc->vec1_P;
    6017:     to = pcbddc->coarse_vec;
    6018:   }
    6019:   VecScatterEnd(pcbddc->coarse_loc_to_glob,from,to,imode,smode);
    6020:   if (smode == SCATTER_FORWARD) {
    6021:     if (pcbddc->coarse_ksp) { /* get array from coarse processes */
    6022:       Vec tvec;

    6024:       KSPGetRhs(pcbddc->coarse_ksp,&tvec);
    6025:       VecGetArrayRead(to,&array);
    6026:       VecPlaceArray(tvec,array);
    6027:       VecRestoreArrayRead(to,&array);
    6028:     }
    6029:   } else {
    6030:     if (pcbddc->coarse_ksp) { /* restore array of pcbddc->coarse_vec */
    6031:      VecResetArray(from);
    6032:     }
    6033:   }
    6034:   return(0);
    6035: }

    6037: PetscErrorCode PCBDDCConstraintsSetUp(PC pc)
    6038: {
    6039:   PetscErrorCode    ierr;
    6040:   PC_IS*            pcis = (PC_IS*)(pc->data);
    6041:   PC_BDDC*          pcbddc = (PC_BDDC*)pc->data;
    6042:   Mat_IS*           matis = (Mat_IS*)pc->pmat->data;
    6043:   /* one and zero */
    6044:   PetscScalar       one=1.0,zero=0.0;
    6045:   /* space to store constraints and their local indices */
    6046:   PetscScalar       *constraints_data;
    6047:   PetscInt          *constraints_idxs,*constraints_idxs_B;
    6048:   PetscInt          *constraints_idxs_ptr,*constraints_data_ptr;
    6049:   PetscInt          *constraints_n;
    6050:   /* iterators */
    6051:   PetscInt          i,j,k,total_counts,total_counts_cc,cum;
    6052:   /* BLAS integers */
    6053:   PetscBLASInt      lwork,lierr;
    6054:   PetscBLASInt      Blas_N,Blas_M,Blas_K,Blas_one=1;
    6055:   PetscBLASInt      Blas_LDA,Blas_LDB,Blas_LDC;
    6056:   /* reuse */
    6057:   PetscInt          olocal_primal_size,olocal_primal_size_cc;
    6058:   PetscInt          *olocal_primal_ref_node,*olocal_primal_ref_mult;
    6059:   /* change of basis */
    6060:   PetscBool         qr_needed;
    6061:   PetscBT           change_basis,qr_needed_idx;
    6062:   /* auxiliary stuff */
    6063:   PetscInt          *nnz,*is_indices;
    6064:   PetscInt          ncc;
    6065:   /* some quantities */
    6066:   PetscInt          n_vertices,total_primal_vertices,valid_constraints;
    6067:   PetscInt          size_of_constraint,max_size_of_constraint=0,max_constraints,temp_constraints;
    6068:   PetscReal         tol; /* tolerance for retaining eigenmodes */

    6071:   tol  = PetscSqrtReal(PETSC_SMALL);
    6072:   /* Destroy Mat objects computed previously */
    6073:   MatDestroy(&pcbddc->ChangeOfBasisMatrix);
    6074:   MatDestroy(&pcbddc->ConstraintMatrix);
    6075:   MatDestroy(&pcbddc->switch_static_change);
    6076:   /* save info on constraints from previous setup (if any) */
    6077:   olocal_primal_size = pcbddc->local_primal_size;
    6078:   olocal_primal_size_cc = pcbddc->local_primal_size_cc;
    6079:   PetscMalloc2(olocal_primal_size_cc,&olocal_primal_ref_node,olocal_primal_size_cc,&olocal_primal_ref_mult);
    6080:   PetscArraycpy(olocal_primal_ref_node,pcbddc->local_primal_ref_node,olocal_primal_size_cc);
    6081:   PetscArraycpy(olocal_primal_ref_mult,pcbddc->local_primal_ref_mult,olocal_primal_size_cc);
    6082:   PetscFree2(pcbddc->local_primal_ref_node,pcbddc->local_primal_ref_mult);
    6083:   PetscFree(pcbddc->primal_indices_local_idxs);

    6085:   if (!pcbddc->adaptive_selection) {
    6086:     IS           ISForVertices,*ISForFaces,*ISForEdges;
    6087:     MatNullSpace nearnullsp;
    6088:     const Vec    *nearnullvecs;
    6089:     Vec          *localnearnullsp;
    6090:     PetscScalar  *array;
    6091:     PetscInt     n_ISForFaces,n_ISForEdges,nnsp_size;
    6092:     PetscBool    nnsp_has_cnst;
    6093:     /* LAPACK working arrays for SVD or POD */
    6094:     PetscBool    skip_lapack,boolforchange;
    6095:     PetscScalar  *work;
    6096:     PetscReal    *singular_vals;
    6097: #if defined(PETSC_USE_COMPLEX)
    6098:     PetscReal    *rwork;
    6099: #endif
    6100:     PetscScalar  *temp_basis = NULL,*correlation_mat = NULL;
    6101:     PetscBLASInt dummy_int=1;
    6102:     PetscScalar  dummy_scalar=1.;
    6103:     PetscBool    use_pod = PETSC_FALSE;

    6105:     /* MKL SVD with same input gives different results on different processes! */
    6106: #if defined(PETSC_MISSING_LAPACK_GESVD) || defined(PETSC_HAVE_MKL)
    6107:     use_pod = PETSC_TRUE;
    6108: #endif
    6109:     /* Get index sets for faces, edges and vertices from graph */
    6110:     PCBDDCGraphGetCandidatesIS(pcbddc->mat_graph,&n_ISForFaces,&ISForFaces,&n_ISForEdges,&ISForEdges,&ISForVertices);
    6111:     /* print some info */
    6112:     if (pcbddc->dbg_flag && (!pcbddc->sub_schurs || pcbddc->sub_schurs_rebuild)) {
    6113:       PetscInt nv;

    6115:       PCBDDCGraphASCIIView(pcbddc->mat_graph,pcbddc->dbg_flag,pcbddc->dbg_viewer);
    6116:       ISGetSize(ISForVertices,&nv);
    6117:       PetscViewerASCIIPushSynchronized(pcbddc->dbg_viewer);
    6118:       PetscViewerASCIISynchronizedPrintf(pcbddc->dbg_viewer,"--------------------------------------------------------------\n");
    6119:       PetscViewerASCIISynchronizedPrintf(pcbddc->dbg_viewer,"Subdomain %04d got %02d local candidate vertices (%D)\n",PetscGlobalRank,nv,pcbddc->use_vertices);
    6120:       PetscViewerASCIISynchronizedPrintf(pcbddc->dbg_viewer,"Subdomain %04d got %02d local candidate edges    (%D)\n",PetscGlobalRank,n_ISForEdges,pcbddc->use_edges);
    6121:       PetscViewerASCIISynchronizedPrintf(pcbddc->dbg_viewer,"Subdomain %04d got %02d local candidate faces    (%D)\n",PetscGlobalRank,n_ISForFaces,pcbddc->use_faces);
    6122:       PetscViewerFlush(pcbddc->dbg_viewer);
    6123:       PetscViewerASCIIPopSynchronized(pcbddc->dbg_viewer);
    6124:     }

    6126:     /* free unneeded index sets */
    6127:     if (!pcbddc->use_vertices) {
    6128:       ISDestroy(&ISForVertices);
    6129:     }
    6130:     if (!pcbddc->use_edges) {
    6131:       for (i=0;i<n_ISForEdges;i++) {
    6132:         ISDestroy(&ISForEdges[i]);
    6133:       }
    6134:       PetscFree(ISForEdges);
    6135:       n_ISForEdges = 0;
    6136:     }
    6137:     if (!pcbddc->use_faces) {
    6138:       for (i=0;i<n_ISForFaces;i++) {
    6139:         ISDestroy(&ISForFaces[i]);
    6140:       }
    6141:       PetscFree(ISForFaces);
    6142:       n_ISForFaces = 0;
    6143:     }

    6145:     /* check if near null space is attached to global mat */
    6146:     if (pcbddc->use_nnsp) {
    6147:       MatGetNearNullSpace(pc->pmat,&nearnullsp);
    6148:     } else nearnullsp = NULL;

    6150:     if (nearnullsp) {
    6151:       MatNullSpaceGetVecs(nearnullsp,&nnsp_has_cnst,&nnsp_size,&nearnullvecs);
    6152:       /* remove any stored info */
    6153:       MatNullSpaceDestroy(&pcbddc->onearnullspace);
    6154:       PetscFree(pcbddc->onearnullvecs_state);
    6155:       /* store information for BDDC solver reuse */
    6156:       PetscObjectReference((PetscObject)nearnullsp);
    6157:       pcbddc->onearnullspace = nearnullsp;
    6158:       PetscMalloc1(nnsp_size,&pcbddc->onearnullvecs_state);
    6159:       for (i=0;i<nnsp_size;i++) {
    6160:         PetscObjectStateGet((PetscObject)nearnullvecs[i],&pcbddc->onearnullvecs_state[i]);
    6161:       }
    6162:     } else { /* if near null space is not provided BDDC uses constants by default */
    6163:       nnsp_size = 0;
    6164:       nnsp_has_cnst = PETSC_TRUE;
    6165:     }
    6166:     /* get max number of constraints on a single cc */
    6167:     max_constraints = nnsp_size;
    6168:     if (nnsp_has_cnst) max_constraints++;

    6170:     /*
    6171:          Evaluate maximum storage size needed by the procedure
    6172:          - Indices for connected component i stored at "constraints_idxs + constraints_idxs_ptr[i]"
    6173:          - Values for constraints on connected component i stored at "constraints_data + constraints_data_ptr[i]"
    6174:          There can be multiple constraints per connected component
    6175:                                                                                                                                                            */
    6176:     n_vertices = 0;
    6177:     if (ISForVertices) {
    6178:       ISGetSize(ISForVertices,&n_vertices);
    6179:     }
    6180:     ncc = n_vertices+n_ISForFaces+n_ISForEdges;
    6181:     PetscMalloc3(ncc+1,&constraints_idxs_ptr,ncc+1,&constraints_data_ptr,ncc,&constraints_n);

    6183:     total_counts = n_ISForFaces+n_ISForEdges;
    6184:     total_counts *= max_constraints;
    6185:     total_counts += n_vertices;
    6186:     PetscBTCreate(total_counts,&change_basis);

    6188:     total_counts = 0;
    6189:     max_size_of_constraint = 0;
    6190:     for (i=0;i<n_ISForEdges+n_ISForFaces;i++) {
    6191:       IS used_is;
    6192:       if (i<n_ISForEdges) {
    6193:         used_is = ISForEdges[i];
    6194:       } else {
    6195:         used_is = ISForFaces[i-n_ISForEdges];
    6196:       }
    6197:       ISGetSize(used_is,&j);
    6198:       total_counts += j;
    6199:       max_size_of_constraint = PetscMax(j,max_size_of_constraint);
    6200:     }
    6201:     PetscMalloc3(total_counts*max_constraints+n_vertices,&constraints_data,total_counts+n_vertices,&constraints_idxs,total_counts+n_vertices,&constraints_idxs_B);

    6203:     /* get local part of global near null space vectors */
    6204:     PetscMalloc1(nnsp_size,&localnearnullsp);
    6205:     for (k=0;k<nnsp_size;k++) {
    6206:       VecDuplicate(pcis->vec1_N,&localnearnullsp[k]);
    6207:       VecScatterBegin(matis->rctx,nearnullvecs[k],localnearnullsp[k],INSERT_VALUES,SCATTER_FORWARD);
    6208:       VecScatterEnd(matis->rctx,nearnullvecs[k],localnearnullsp[k],INSERT_VALUES,SCATTER_FORWARD);
    6209:     }

    6211:     /* whether or not to skip lapack calls */
    6212:     skip_lapack = PETSC_TRUE;
    6213:     if (n_ISForFaces+n_ISForEdges && max_constraints > 1 && !pcbddc->use_nnsp_true) skip_lapack = PETSC_FALSE;

    6215:     /* First we issue queries to allocate optimal workspace for LAPACKgesvd (or LAPACKsyev if SVD is missing) */
    6216:     if (!skip_lapack) {
    6217:       PetscScalar temp_work;

    6219:       if (use_pod) {
    6220:         /* Proper Orthogonal Decomposition (POD) using the snapshot method */
    6221:         PetscMalloc1(max_constraints*max_constraints,&correlation_mat);
    6222:         PetscMalloc1(max_constraints,&singular_vals);
    6223:         PetscMalloc1(max_size_of_constraint*max_constraints,&temp_basis);
    6224: #if defined(PETSC_USE_COMPLEX)
    6225:         PetscMalloc1(3*max_constraints,&rwork);
    6226: #endif
    6227:         /* now we evaluate the optimal workspace using query with lwork=-1 */
    6228:         PetscBLASIntCast(max_constraints,&Blas_N);
    6229:         PetscBLASIntCast(max_constraints,&Blas_LDA);
    6230:         lwork = -1;
    6231:         PetscFPTrapPush(PETSC_FP_TRAP_OFF);
    6232: #if !defined(PETSC_USE_COMPLEX)
    6233:         PetscStackCallBLAS("LAPACKsyev",LAPACKsyev_("V","U",&Blas_N,correlation_mat,&Blas_LDA,singular_vals,&temp_work,&lwork,&lierr));
    6234: #else
    6235:         PetscStackCallBLAS("LAPACKsyev",LAPACKsyev_("V","U",&Blas_N,correlation_mat,&Blas_LDA,singular_vals,&temp_work,&lwork,rwork,&lierr));
    6236: #endif
    6237:         PetscFPTrapPop();
    6238:         if (lierr) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_LIB,"Error in query to SYEV Lapack routine %d",(int)lierr);
    6239:       } else {
    6240: #if !defined(PETSC_MISSING_LAPACK_GESVD)
    6241:         /* SVD */
    6242:         PetscInt max_n,min_n;
    6243:         max_n = max_size_of_constraint;
    6244:         min_n = max_constraints;
    6245:         if (max_size_of_constraint < max_constraints) {
    6246:           min_n = max_size_of_constraint;
    6247:           max_n = max_constraints;
    6248:         }
    6249:         PetscMalloc1(min_n,&singular_vals);
    6250: #if defined(PETSC_USE_COMPLEX)
    6251:         PetscMalloc1(5*min_n,&rwork);
    6252: #endif
    6253:         /* now we evaluate the optimal workspace using query with lwork=-1 */
    6254:         lwork = -1;
    6255:         PetscBLASIntCast(max_n,&Blas_M);
    6256:         PetscBLASIntCast(min_n,&Blas_N);
    6257:         PetscBLASIntCast(max_n,&Blas_LDA);
    6258:         PetscFPTrapPush(PETSC_FP_TRAP_OFF);
    6259: #if !defined(PETSC_USE_COMPLEX)
    6260:         PetscStackCallBLAS("LAPACKgesvd",LAPACKgesvd_("O","N",&Blas_M,&Blas_N,&constraints_data[0],&Blas_LDA,singular_vals,&dummy_scalar,&dummy_int,&dummy_scalar,&dummy_int,&temp_work,&lwork,&lierr));
    6261: #else
    6262:         PetscStackCallBLAS("LAPACKgesvd",LAPACKgesvd_("O","N",&Blas_M,&Blas_N,&constraints_data[0],&Blas_LDA,singular_vals,&dummy_scalar,&dummy_int,&dummy_scalar,&dummy_int,&temp_work,&lwork,rwork,&lierr));
    6263: #endif
    6264:         PetscFPTrapPop();
    6265:         if (lierr) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_LIB,"Error in query to GESVD Lapack routine %d",(int)lierr);
    6266: #else
    6267:         SETERRQ(PETSC_COMM_SELF,PETSC_ERR_LIB,"This should not happen");
    6268: #endif /* on missing GESVD */
    6269:       }
    6270:       /* Allocate optimal workspace */
    6271:       PetscBLASIntCast((PetscInt)PetscRealPart(temp_work),&lwork);
    6272:       PetscMalloc1(lwork,&work);
    6273:     }
    6274:     /* Now we can loop on constraining sets */
    6275:     total_counts = 0;
    6276:     constraints_idxs_ptr[0] = 0;
    6277:     constraints_data_ptr[0] = 0;
    6278:     /* vertices */
    6279:     if (n_vertices) {
    6280:       ISGetIndices(ISForVertices,(const PetscInt**)&is_indices);
    6281:       PetscArraycpy(constraints_idxs,is_indices,n_vertices);
    6282:       for (i=0;i<n_vertices;i++) {
    6283:         constraints_n[total_counts] = 1;
    6284:         constraints_data[total_counts] = 1.0;
    6285:         constraints_idxs_ptr[total_counts+1] = constraints_idxs_ptr[total_counts]+1;
    6286:         constraints_data_ptr[total_counts+1] = constraints_data_ptr[total_counts]+1;
    6287:         total_counts++;
    6288:       }
    6289:       ISRestoreIndices(ISForVertices,(const PetscInt**)&is_indices);
    6290:       n_vertices = total_counts;
    6291:     }

    6293:     /* edges and faces */
    6294:     total_counts_cc = total_counts;
    6295:     for (ncc=0;ncc<n_ISForEdges+n_ISForFaces;ncc++) {
    6296:       IS        used_is;
    6297:       PetscBool idxs_copied = PETSC_FALSE;

    6299:       if (ncc<n_ISForEdges) {
    6300:         used_is = ISForEdges[ncc];
    6301:         boolforchange = pcbddc->use_change_of_basis; /* change or not the basis on the edge */
    6302:       } else {
    6303:         used_is = ISForFaces[ncc-n_ISForEdges];
    6304:         boolforchange = (PetscBool)(pcbddc->use_change_of_basis && pcbddc->use_change_on_faces); /* change or not the basis on the face */
    6305:       }
    6306:       temp_constraints = 0;          /* zero the number of constraints I have on this conn comp */

    6308:       ISGetSize(used_is,&size_of_constraint);
    6309:       ISGetIndices(used_is,(const PetscInt**)&is_indices);
    6310:       /* change of basis should not be performed on local periodic nodes */
    6311:       if (pcbddc->mat_graph->mirrors && pcbddc->mat_graph->mirrors[is_indices[0]]) boolforchange = PETSC_FALSE;
    6312:       if (nnsp_has_cnst) {
    6313:         PetscScalar quad_value;

    6315:         PetscArraycpy(constraints_idxs + constraints_idxs_ptr[total_counts_cc],is_indices,size_of_constraint);
    6316:         idxs_copied = PETSC_TRUE;

    6318:         if (!pcbddc->use_nnsp_true) {
    6319:           quad_value = (PetscScalar)(1.0/PetscSqrtReal((PetscReal)size_of_constraint));
    6320:         } else {
    6321:           quad_value = 1.0;
    6322:         }
    6323:         for (j=0;j<size_of_constraint;j++) {
    6324:           constraints_data[constraints_data_ptr[total_counts_cc]+j] = quad_value;
    6325:         }
    6326:         temp_constraints++;
    6327:         total_counts++;
    6328:       }
    6329:       for (k=0;k<nnsp_size;k++) {
    6330:         PetscReal real_value;
    6331:         PetscScalar *ptr_to_data;

    6333:         VecGetArrayRead(localnearnullsp[k],(const PetscScalar**)&array);
    6334:         ptr_to_data = &constraints_data[constraints_data_ptr[total_counts_cc]+temp_constraints*size_of_constraint];
    6335:         for (j=0;j<size_of_constraint;j++) {
    6336:           ptr_to_data[j] = array[is_indices[j]];
    6337:         }
    6338:         VecRestoreArrayRead(localnearnullsp[k],(const PetscScalar**)&array);
    6339:         /* check if array is null on the connected component */
    6340:         PetscBLASIntCast(size_of_constraint,&Blas_N);
    6341:         PetscStackCallBLAS("BLASasum",real_value = BLASasum_(&Blas_N,ptr_to_data,&Blas_one));
    6342:         if (real_value > tol*size_of_constraint) { /* keep indices and values */
    6343:           temp_constraints++;
    6344:           total_counts++;
    6345:           if (!idxs_copied) {
    6346:             PetscArraycpy(constraints_idxs + constraints_idxs_ptr[total_counts_cc],is_indices,size_of_constraint);
    6347:             idxs_copied = PETSC_TRUE;
    6348:           }
    6349:         }
    6350:       }
    6351:       ISRestoreIndices(used_is,(const PetscInt**)&is_indices);
    6352:       valid_constraints = temp_constraints;
    6353:       if (!pcbddc->use_nnsp_true && temp_constraints) {
    6354:         if (temp_constraints == 1) { /* just normalize the constraint */
    6355:           PetscScalar norm,*ptr_to_data;

    6357:           ptr_to_data = &constraints_data[constraints_data_ptr[total_counts_cc]];
    6358:           PetscBLASIntCast(size_of_constraint,&Blas_N);
    6359:           PetscStackCallBLAS("BLASdot",norm = BLASdot_(&Blas_N,ptr_to_data,&Blas_one,ptr_to_data,&Blas_one));
    6360:           norm = 1.0/PetscSqrtReal(PetscRealPart(norm));
    6361:           PetscStackCallBLAS("BLASscal",BLASscal_(&Blas_N,&norm,ptr_to_data,&Blas_one));
    6362:         } else { /* perform SVD */
    6363:           PetscScalar *ptr_to_data = &constraints_data[constraints_data_ptr[total_counts_cc]];

    6365:           if (use_pod) {
    6366:             /* SVD: Y = U*S*V^H                -> U (eigenvectors of Y*Y^H) = Y*V*(S)^\dag
    6367:                POD: Y^H*Y = V*D*V^H, D = S^H*S -> U = Y*V*D^(-1/2)
    6368:                -> When PETSC_USE_COMPLEX and PETSC_MISSING_LAPACK_GESVD are defined
    6369:                   the constraints basis will differ (by a complex factor with absolute value equal to 1)
    6370:                   from that computed using LAPACKgesvd
    6371:                -> This is due to a different computation of eigenvectors in LAPACKheev
    6372:                -> The quality of the POD-computed basis will be the same */
    6373:             PetscArrayzero(correlation_mat,temp_constraints*temp_constraints);
    6374:             /* Store upper triangular part of correlation matrix */
    6375:             PetscBLASIntCast(size_of_constraint,&Blas_N);
    6376:             PetscFPTrapPush(PETSC_FP_TRAP_OFF);
    6377:             for (j=0;j<temp_constraints;j++) {
    6378:               for (k=0;k<j+1;k++) {
    6379:                 PetscStackCallBLAS("BLASdot",correlation_mat[j*temp_constraints+k] = BLASdot_(&Blas_N,ptr_to_data+k*size_of_constraint,&Blas_one,ptr_to_data+j*size_of_constraint,&Blas_one));
    6380:               }
    6381:             }
    6382:             /* compute eigenvalues and eigenvectors of correlation matrix */
    6383:             PetscBLASIntCast(temp_constraints,&Blas_N);
    6384:             PetscBLASIntCast(temp_constraints,&Blas_LDA);
    6385: #if !defined(PETSC_USE_COMPLEX)
    6386:             PetscStackCallBLAS("LAPACKsyev",LAPACKsyev_("V","U",&Blas_N,correlation_mat,&Blas_LDA,singular_vals,work,&lwork,&lierr));
    6387: #else
    6388:             PetscStackCallBLAS("LAPACKsyev",LAPACKsyev_("V","U",&Blas_N,correlation_mat,&Blas_LDA,singular_vals,work,&lwork,rwork,&lierr));
    6389: #endif
    6390:             PetscFPTrapPop();
    6391:             if (lierr) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_LIB,"Error in SYEV Lapack routine %d",(int)lierr);
    6392:             /* retain eigenvalues greater than tol: note that LAPACKsyev gives eigs in ascending order */
    6393:             j = 0;
    6394:             while (j < temp_constraints && singular_vals[j]/singular_vals[temp_constraints-1] < tol) j++;
    6395:             total_counts = total_counts-j;
    6396:             valid_constraints = temp_constraints-j;
    6397:             /* scale and copy POD basis into used quadrature memory */
    6398:             PetscBLASIntCast(size_of_constraint,&Blas_M);
    6399:             PetscBLASIntCast(temp_constraints,&Blas_N);
    6400:             PetscBLASIntCast(temp_constraints,&Blas_K);
    6401:             PetscBLASIntCast(size_of_constraint,&Blas_LDA);
    6402:             PetscBLASIntCast(temp_constraints,&Blas_LDB);
    6403:             PetscBLASIntCast(size_of_constraint,&Blas_LDC);
    6404:             if (j<temp_constraints) {
    6405:               PetscInt ii;
    6406:               for (k=j;k<temp_constraints;k++) singular_vals[k] = 1.0/PetscSqrtReal(singular_vals[k]);
    6407:               PetscFPTrapPush(PETSC_FP_TRAP_OFF);
    6408:               PetscStackCallBLAS("BLASgemm",BLASgemm_("N","N",&Blas_M,&Blas_N,&Blas_K,&one,ptr_to_data,&Blas_LDA,correlation_mat,&Blas_LDB,&zero,temp_basis,&Blas_LDC));
    6409:               PetscFPTrapPop();
    6410:               for (k=0;k<temp_constraints-j;k++) {
    6411:                 for (ii=0;ii<size_of_constraint;ii++) {
    6412:                   ptr_to_data[k*size_of_constraint+ii] = singular_vals[temp_constraints-1-k]*temp_basis[(temp_constraints-1-k)*size_of_constraint+ii];
    6413:                 }
    6414:               }
    6415:             }
    6416:           } else {
    6417: #if !defined(PETSC_MISSING_LAPACK_GESVD)
    6418:             PetscBLASIntCast(size_of_constraint,&Blas_M);
    6419:             PetscBLASIntCast(temp_constraints,&Blas_N);
    6420:             PetscBLASIntCast(size_of_constraint,&Blas_LDA);
    6421:             PetscFPTrapPush(PETSC_FP_TRAP_OFF);
    6422: #if !defined(PETSC_USE_COMPLEX)
    6423:             PetscStackCallBLAS("LAPACKgesvd",LAPACKgesvd_("O","N",&Blas_M,&Blas_N,ptr_to_data,&Blas_LDA,singular_vals,&dummy_scalar,&dummy_int,&dummy_scalar,&dummy_int,work,&lwork,&lierr));
    6424: #else
    6425:             PetscStackCallBLAS("LAPACKgesvd",LAPACKgesvd_("O","N",&Blas_M,&Blas_N,ptr_to_data,&Blas_LDA,singular_vals,&dummy_scalar,&dummy_int,&dummy_scalar,&dummy_int,work,&lwork,rwork,&lierr));
    6426: #endif
    6427:             if (lierr) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_LIB,"Error in GESVD Lapack routine %d",(int)lierr);
    6428:             PetscFPTrapPop();
    6429:             /* retain eigenvalues greater than tol: note that LAPACKgesvd gives eigs in descending order */
    6430:             k = temp_constraints;
    6431:             if (k > size_of_constraint) k = size_of_constraint;
    6432:             j = 0;
    6433:             while (j < k && singular_vals[k-j-1]/singular_vals[0] < tol) j++;
    6434:             valid_constraints = k-j;
    6435:             total_counts = total_counts-temp_constraints+valid_constraints;
    6436: #else
    6437:             SETERRQ(PETSC_COMM_SELF,PETSC_ERR_LIB,"This should not happen");
    6438: #endif /* on missing GESVD */
    6439:           }
    6440:         }
    6441:       }
    6442:       /* update pointers information */
    6443:       if (valid_constraints) {
    6444:         constraints_n[total_counts_cc] = valid_constraints;
    6445:         constraints_idxs_ptr[total_counts_cc+1] = constraints_idxs_ptr[total_counts_cc]+size_of_constraint;
    6446:         constraints_data_ptr[total_counts_cc+1] = constraints_data_ptr[total_counts_cc]+size_of_constraint*valid_constraints;
    6447:         /* set change_of_basis flag */
    6448:         if (boolforchange) {
    6449:           PetscBTSet(change_basis,total_counts_cc);
    6450:         }
    6451:         total_counts_cc++;
    6452:       }
    6453:     }
    6454:     /* free workspace */
    6455:     if (!skip_lapack) {
    6456:       PetscFree(work);
    6457: #if defined(PETSC_USE_COMPLEX)
    6458:       PetscFree(rwork);
    6459: #endif
    6460:       PetscFree(singular_vals);
    6461:       PetscFree(correlation_mat);
    6462:       PetscFree(temp_basis);
    6463:     }
    6464:     for (k=0;k<nnsp_size;k++) {
    6465:       VecDestroy(&localnearnullsp[k]);
    6466:     }
    6467:     PetscFree(localnearnullsp);
    6468:     /* free index sets of faces, edges and vertices */
    6469:     for (i=0;i<n_ISForFaces;i++) {
    6470:       ISDestroy(&ISForFaces[i]);
    6471:     }
    6472:     if (n_ISForFaces) {
    6473:       PetscFree(ISForFaces);
    6474:     }
    6475:     for (i=0;i<n_ISForEdges;i++) {
    6476:       ISDestroy(&ISForEdges[i]);
    6477:     }
    6478:     if (n_ISForEdges) {
    6479:       PetscFree(ISForEdges);
    6480:     }
    6481:     ISDestroy(&ISForVertices);
    6482:   } else {
    6483:     PCBDDCSubSchurs sub_schurs = pcbddc->sub_schurs;

    6485:     total_counts = 0;
    6486:     n_vertices = 0;
    6487:     if (sub_schurs->is_vertices && pcbddc->use_vertices) {
    6488:       ISGetLocalSize(sub_schurs->is_vertices,&n_vertices);
    6489:     }
    6490:     max_constraints = 0;
    6491:     total_counts_cc = 0;
    6492:     for (i=0;i<sub_schurs->n_subs+n_vertices;i++) {
    6493:       total_counts += pcbddc->adaptive_constraints_n[i];
    6494:       if (pcbddc->adaptive_constraints_n[i]) total_counts_cc++;
    6495:       max_constraints = PetscMax(max_constraints,pcbddc->adaptive_constraints_n[i]);
    6496:     }
    6497:     constraints_idxs_ptr = pcbddc->adaptive_constraints_idxs_ptr;
    6498:     constraints_data_ptr = pcbddc->adaptive_constraints_data_ptr;
    6499:     constraints_idxs = pcbddc->adaptive_constraints_idxs;
    6500:     constraints_data = pcbddc->adaptive_constraints_data;
    6501:     /* constraints_n differs from pcbddc->adaptive_constraints_n */
    6502:     PetscMalloc1(total_counts_cc,&constraints_n);
    6503:     total_counts_cc = 0;
    6504:     for (i=0;i<sub_schurs->n_subs+n_vertices;i++) {
    6505:       if (pcbddc->adaptive_constraints_n[i]) {
    6506:         constraints_n[total_counts_cc++] = pcbddc->adaptive_constraints_n[i];
    6507:       }
    6508:     }

    6510:     max_size_of_constraint = 0;
    6511:     for (i=0;i<total_counts_cc;i++) max_size_of_constraint = PetscMax(max_size_of_constraint,constraints_idxs_ptr[i+1]-constraints_idxs_ptr[i]);
    6512:     PetscMalloc1(constraints_idxs_ptr[total_counts_cc],&constraints_idxs_B);
    6513:     /* Change of basis */
    6514:     PetscBTCreate(total_counts_cc,&change_basis);
    6515:     if (pcbddc->use_change_of_basis) {
    6516:       for (i=0;i<sub_schurs->n_subs;i++) {
    6517:         if (PetscBTLookup(sub_schurs->is_edge,i) || pcbddc->use_change_on_faces) {
    6518:           PetscBTSet(change_basis,i+n_vertices);
    6519:         }
    6520:       }
    6521:     }
    6522:   }
    6523:   pcbddc->local_primal_size = total_counts;
    6524:   PetscMalloc1(pcbddc->local_primal_size+pcbddc->benign_n,&pcbddc->primal_indices_local_idxs);

    6526:   /* map constraints_idxs in boundary numbering */
    6527:   ISGlobalToLocalMappingApply(pcis->BtoNmap,IS_GTOLM_DROP,constraints_idxs_ptr[total_counts_cc],constraints_idxs,&i,constraints_idxs_B);
    6528:   if (i != constraints_idxs_ptr[total_counts_cc]) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_PLIB,"Error in boundary numbering for constraints indices %D != %D",constraints_idxs_ptr[total_counts_cc],i);

    6530:   /* Create constraint matrix */
    6531:   MatCreate(PETSC_COMM_SELF,&pcbddc->ConstraintMatrix);
    6532:   MatSetType(pcbddc->ConstraintMatrix,MATAIJ);
    6533:   MatSetSizes(pcbddc->ConstraintMatrix,pcbddc->local_primal_size,pcis->n,pcbddc->local_primal_size,pcis->n);

    6535:   /* find primal_dofs: subdomain corners plus dofs selected as primal after change of basis */
    6536:   /* determine if a QR strategy is needed for change of basis */
    6537:   qr_needed = pcbddc->use_qr_single;
    6538:   PetscBTCreate(total_counts_cc,&qr_needed_idx);
    6539:   total_primal_vertices=0;
    6540:   pcbddc->local_primal_size_cc = 0;
    6541:   for (i=0;i<total_counts_cc;i++) {
    6542:     size_of_constraint = constraints_idxs_ptr[i+1]-constraints_idxs_ptr[i];
    6543:     if (size_of_constraint == 1 && pcbddc->mat_graph->custom_minimal_size) {
    6544:       pcbddc->primal_indices_local_idxs[total_primal_vertices++] = constraints_idxs[constraints_idxs_ptr[i]];
    6545:       pcbddc->local_primal_size_cc += 1;
    6546:     } else if (PetscBTLookup(change_basis,i)) {
    6547:       for (k=0;k<constraints_n[i];k++) {
    6548:         pcbddc->primal_indices_local_idxs[total_primal_vertices++] = constraints_idxs[constraints_idxs_ptr[i]+k];
    6549:       }
    6550:       pcbddc->local_primal_size_cc += constraints_n[i];
    6551:       if (constraints_n[i] > 1 || pcbddc->use_qr_single) {
    6552:         PetscBTSet(qr_needed_idx,i);
    6553:         qr_needed = PETSC_TRUE;
    6554:       }
    6555:     } else {
    6556:       pcbddc->local_primal_size_cc += 1;
    6557:     }
    6558:   }
    6559:   /* note that the local variable n_vertices used below stores the number of pointwise constraints */
    6560:   pcbddc->n_vertices = total_primal_vertices;
    6561:   /* permute indices in order to have a sorted set of vertices */
    6562:   PetscSortInt(total_primal_vertices,pcbddc->primal_indices_local_idxs);
    6563:   PetscMalloc2(pcbddc->local_primal_size_cc+pcbddc->benign_n,&pcbddc->local_primal_ref_node,pcbddc->local_primal_size_cc+pcbddc->benign_n,&pcbddc->local_primal_ref_mult);
    6564:   PetscArraycpy(pcbddc->local_primal_ref_node,pcbddc->primal_indices_local_idxs,total_primal_vertices);
    6565:   for (i=0;i<total_primal_vertices;i++) pcbddc->local_primal_ref_mult[i] = 1;

    6567:   /* nonzero structure of constraint matrix */
    6568:   /* and get reference dof for local constraints */
    6569:   PetscMalloc1(pcbddc->local_primal_size,&nnz);
    6570:   for (i=0;i<total_primal_vertices;i++) nnz[i] = 1;

    6572:   j = total_primal_vertices;
    6573:   total_counts = total_primal_vertices;
    6574:   cum = total_primal_vertices;
    6575:   for (i=n_vertices;i<total_counts_cc;i++) {
    6576:     if (!PetscBTLookup(change_basis,i)) {
    6577:       pcbddc->local_primal_ref_node[cum] = constraints_idxs[constraints_idxs_ptr[i]];
    6578:       pcbddc->local_primal_ref_mult[cum] = constraints_n[i];
    6579:       cum++;
    6580:       size_of_constraint = constraints_idxs_ptr[i+1]-constraints_idxs_ptr[i];
    6581:       for (k=0;k<constraints_n[i];k++) {
    6582:         pcbddc->primal_indices_local_idxs[total_counts++] = constraints_idxs[constraints_idxs_ptr[i]+k];
    6583:         nnz[j+k] = size_of_constraint;
    6584:       }
    6585:       j += constraints_n[i];
    6586:     }
    6587:   }
    6588:   MatSeqAIJSetPreallocation(pcbddc->ConstraintMatrix,0,nnz);
    6589:   MatSetOption(pcbddc->ConstraintMatrix,MAT_NEW_NONZERO_ALLOCATION_ERR,PETSC_TRUE);
    6590:   PetscFree(nnz);

    6592:   /* set values in constraint matrix */
    6593:   for (i=0;i<total_primal_vertices;i++) {
    6594:     MatSetValue(pcbddc->ConstraintMatrix,i,pcbddc->local_primal_ref_node[i],1.0,INSERT_VALUES);
    6595:   }
    6596:   total_counts = total_primal_vertices;
    6597:   for (i=n_vertices;i<total_counts_cc;i++) {
    6598:     if (!PetscBTLookup(change_basis,i)) {
    6599:       PetscInt *cols;

    6601:       size_of_constraint = constraints_idxs_ptr[i+1]-constraints_idxs_ptr[i];
    6602:       cols = constraints_idxs+constraints_idxs_ptr[i];
    6603:       for (k=0;k<constraints_n[i];k++) {
    6604:         PetscInt    row = total_counts+k;
    6605:         PetscScalar *vals;

    6607:         vals = constraints_data+constraints_data_ptr[i]+k*size_of_constraint;
    6608:         MatSetValues(pcbddc->ConstraintMatrix,1,&row,size_of_constraint,cols,vals,INSERT_VALUES);
    6609:       }
    6610:       total_counts += constraints_n[i];
    6611:     }
    6612:   }
    6613:   /* assembling */
    6614:   MatAssemblyBegin(pcbddc->ConstraintMatrix,MAT_FINAL_ASSEMBLY);
    6615:   MatAssemblyEnd(pcbddc->ConstraintMatrix,MAT_FINAL_ASSEMBLY);
    6616:   MatViewFromOptions(pcbddc->ConstraintMatrix,(PetscObject)pc,"-pc_bddc_constraint_mat_view");

    6618:   /* Create matrix for change of basis. We don't need it in case pcbddc->use_change_of_basis is FALSE */
    6619:   if (pcbddc->use_change_of_basis) {
    6620:     /* dual and primal dofs on a single cc */
    6621:     PetscInt     dual_dofs,primal_dofs;
    6622:     /* working stuff for GEQRF */
    6623:     PetscScalar  *qr_basis = NULL,*qr_tau = NULL,*qr_work = NULL,lqr_work_t;
    6624:     PetscBLASInt lqr_work;
    6625:     /* working stuff for UNGQR */
    6626:     PetscScalar  *gqr_work = NULL,lgqr_work_t=0.0;
    6627:     PetscBLASInt lgqr_work;
    6628:     /* working stuff for TRTRS */
    6629:     PetscScalar  *trs_rhs = NULL;
    6630:     PetscBLASInt Blas_NRHS;
    6631:     /* pointers for values insertion into change of basis matrix */
    6632:     PetscInt     *start_rows,*start_cols;
    6633:     PetscScalar  *start_vals;
    6634:     /* working stuff for values insertion */
    6635:     PetscBT      is_primal;
    6636:     PetscInt     *aux_primal_numbering_B;
    6637:     /* matrix sizes */
    6638:     PetscInt     global_size,local_size;
    6639:     /* temporary change of basis */
    6640:     Mat          localChangeOfBasisMatrix;
    6641:     /* extra space for debugging */
    6642:     PetscScalar  *dbg_work = NULL;

    6644:     /* local temporary change of basis acts on local interfaces -> dimension is n_B x n_B */
    6645:     MatCreate(PETSC_COMM_SELF,&localChangeOfBasisMatrix);
    6646:     MatSetType(localChangeOfBasisMatrix,MATAIJ);
    6647:     MatSetSizes(localChangeOfBasisMatrix,pcis->n,pcis->n,pcis->n,pcis->n);
    6648:     /* nonzeros for local mat */
    6649:     PetscMalloc1(pcis->n,&nnz);
    6650:     if (!pcbddc->benign_change || pcbddc->fake_change) {
    6651:       for (i=0;i<pcis->n;i++) nnz[i]=1;
    6652:     } else {
    6653:       const PetscInt *ii;
    6654:       PetscInt       n;
    6655:       PetscBool      flg_row;
    6656:       MatGetRowIJ(pcbddc->benign_change,0,PETSC_FALSE,PETSC_FALSE,&n,&ii,NULL,&flg_row);
    6657:       for (i=0;i<n;i++) nnz[i] = ii[i+1]-ii[i];
    6658:       MatRestoreRowIJ(pcbddc->benign_change,0,PETSC_FALSE,PETSC_FALSE,&n,&ii,NULL,&flg_row);
    6659:     }
    6660:     for (i=n_vertices;i<total_counts_cc;i++) {
    6661:       if (PetscBTLookup(change_basis,i)) {
    6662:         size_of_constraint = constraints_idxs_ptr[i+1]-constraints_idxs_ptr[i];
    6663:         if (PetscBTLookup(qr_needed_idx,i)) {
    6664:           for (j=0;j<size_of_constraint;j++) nnz[constraints_idxs[constraints_idxs_ptr[i]+j]] = size_of_constraint;
    6665:         } else {
    6666:           nnz[constraints_idxs[constraints_idxs_ptr[i]]] = size_of_constraint;
    6667:           for (j=1;j<size_of_constraint;j++) nnz[constraints_idxs[constraints_idxs_ptr[i]+j]] = 2;
    6668:         }
    6669:       }
    6670:     }
    6671:     MatSeqAIJSetPreallocation(localChangeOfBasisMatrix,0,nnz);
    6672:     MatSetOption(localChangeOfBasisMatrix,MAT_NEW_NONZERO_ALLOCATION_ERR,PETSC_TRUE);
    6673:     PetscFree(nnz);
    6674:     /* Set interior change in the matrix */
    6675:     if (!pcbddc->benign_change || pcbddc->fake_change) {
    6676:       for (i=0;i<pcis->n;i++) {
    6677:         MatSetValue(localChangeOfBasisMatrix,i,i,1.0,INSERT_VALUES);
    6678:       }
    6679:     } else {
    6680:       const PetscInt *ii,*jj;
    6681:       PetscScalar    *aa;
    6682:       PetscInt       n;
    6683:       PetscBool      flg_row;
    6684:       MatGetRowIJ(pcbddc->benign_change,0,PETSC_FALSE,PETSC_FALSE,&n,&ii,&jj,&flg_row);
    6685:       MatSeqAIJGetArray(pcbddc->benign_change,&aa);
    6686:       for (i=0;i<n;i++) {
    6687:         MatSetValues(localChangeOfBasisMatrix,1,&i,ii[i+1]-ii[i],jj+ii[i],aa+ii[i],INSERT_VALUES);
    6688:       }
    6689:       MatSeqAIJRestoreArray(pcbddc->benign_change,&aa);
    6690:       MatRestoreRowIJ(pcbddc->benign_change,0,PETSC_FALSE,PETSC_FALSE,&n,&ii,&jj,&flg_row);
    6691:     }

    6693:     if (pcbddc->dbg_flag) {
    6694:       PetscViewerASCIISynchronizedPrintf(pcbddc->dbg_viewer,"--------------------------------------------------------------\n");
    6695:       PetscViewerASCIISynchronizedPrintf(pcbddc->dbg_viewer,"Checking change of basis computation for subdomain %04d\n",PetscGlobalRank);
    6696:     }

    6699:     /* Now we loop on the constraints which need a change of basis */
    6700:     /*
    6701:        Change of basis matrix is evaluated similarly to the FIRST APPROACH in
    6702:        Klawonn and Widlund, Dual-primal FETI-DP methods for linear elasticity, (see Sect 6.2.1)

    6704:        Basic blocks of change of basis matrix T computed by

    6706:           - Using the following block transformation if there is only a primal dof on the cc (and -pc_bddc_use_qr_single is not specified)

    6708:             | 1        0   ...        0         s_1/S |
    6709:             | 0        1   ...        0         s_2/S |
    6710:             |              ...                        |
    6711:             | 0        ...            1     s_{n-1}/S |
    6712:             | -s_1/s_n ...    -s_{n-1}/s_n      s_n/S |

    6714:             with S = \sum_{i=1}^n s_i^2
    6715:             NOTE: in the above example, the primal dof is the last one of the edge in LOCAL ordering
    6716:                   in the current implementation, the primal dof is the first one of the edge in GLOBAL ordering

    6718:           - QR decomposition of constraints otherwise
    6719:     */
    6720:     if (qr_needed && max_size_of_constraint) {
    6721:       /* space to store Q */
    6722:       PetscMalloc1(max_size_of_constraint*max_size_of_constraint,&qr_basis);
    6723:       /* array to store scaling factors for reflectors */
    6724:       PetscMalloc1(max_constraints,&qr_tau);
    6725:       /* first we issue queries for optimal work */
    6726:       PetscBLASIntCast(max_size_of_constraint,&Blas_M);
    6727:       PetscBLASIntCast(max_constraints,&Blas_N);
    6728:       PetscBLASIntCast(max_size_of_constraint,&Blas_LDA);
    6729:       lqr_work = -1;
    6730:       PetscStackCallBLAS("LAPACKgeqrf",LAPACKgeqrf_(&Blas_M,&Blas_N,qr_basis,&Blas_LDA,qr_tau,&lqr_work_t,&lqr_work,&lierr));
    6731:       if (lierr) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_LIB,"Error in query to GEQRF Lapack routine %d",(int)lierr);
    6732:       PetscBLASIntCast((PetscInt)PetscRealPart(lqr_work_t),&lqr_work);
    6733:       PetscMalloc1((PetscInt)PetscRealPart(lqr_work_t),&qr_work);
    6734:       lgqr_work = -1;
    6735:       PetscBLASIntCast(max_size_of_constraint,&Blas_M);
    6736:       PetscBLASIntCast(max_size_of_constraint,&Blas_N);
    6737:       PetscBLASIntCast(max_constraints,&Blas_K);
    6738:       PetscBLASIntCast(max_size_of_constraint,&Blas_LDA);
    6739:       if (Blas_K>Blas_M) Blas_K=Blas_M; /* adjust just for computing optimal work */
    6740:       PetscStackCallBLAS("LAPACKorgqr",LAPACKorgqr_(&Blas_M,&Blas_N,&Blas_K,qr_basis,&Blas_LDA,qr_tau,&lgqr_work_t,&lgqr_work,&lierr));
    6741:       if (lierr) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_LIB,"Error in query to ORGQR/UNGQR Lapack routine %d",(int)lierr);
    6742:       PetscBLASIntCast((PetscInt)PetscRealPart(lgqr_work_t),&lgqr_work);
    6743:       PetscMalloc1((PetscInt)PetscRealPart(lgqr_work_t),&gqr_work);
    6744:       /* array to store rhs and solution of triangular solver */
    6745:       PetscMalloc1(max_constraints*max_constraints,&trs_rhs);
    6746:       /* allocating workspace for check */
    6747:       if (pcbddc->dbg_flag) {
    6748:         PetscMalloc1(max_size_of_constraint*(max_constraints+max_size_of_constraint),&dbg_work);
    6749:       }
    6750:     }
    6751:     /* array to store whether a node is primal or not */
    6752:     PetscBTCreate(pcis->n_B,&is_primal);
    6753:     PetscMalloc1(total_primal_vertices,&aux_primal_numbering_B);
    6754:     ISGlobalToLocalMappingApply(pcis->BtoNmap,IS_GTOLM_DROP,total_primal_vertices,pcbddc->local_primal_ref_node,&i,aux_primal_numbering_B);
    6755:     if (i != total_primal_vertices) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_PLIB,"Error in boundary numbering for BDDC vertices! %D != %D",total_primal_vertices,i);
    6756:     for (i=0;i<total_primal_vertices;i++) {
    6757:       PetscBTSet(is_primal,aux_primal_numbering_B[i]);
    6758:     }
    6759:     PetscFree(aux_primal_numbering_B);

    6761:     /* loop on constraints and see whether or not they need a change of basis and compute it */
    6762:     for (total_counts=n_vertices;total_counts<total_counts_cc;total_counts++) {
    6763:       size_of_constraint = constraints_idxs_ptr[total_counts+1]-constraints_idxs_ptr[total_counts];
    6764:       if (PetscBTLookup(change_basis,total_counts)) {
    6765:         /* get constraint info */
    6766:         primal_dofs = constraints_n[total_counts];
    6767:         dual_dofs = size_of_constraint-primal_dofs;

    6769:         if (pcbddc->dbg_flag) {
    6770:           PetscViewerASCIISynchronizedPrintf(pcbddc->dbg_viewer,"Constraints %D: %D need a change of basis (size %D)\n",total_counts,primal_dofs,size_of_constraint);
    6771:         }

    6773:         if (PetscBTLookup(qr_needed_idx,total_counts)) { /* QR */

    6775:           /* copy quadrature constraints for change of basis check */
    6776:           if (pcbddc->dbg_flag) {
    6777:             PetscArraycpy(dbg_work,&constraints_data[constraints_data_ptr[total_counts]],size_of_constraint*primal_dofs);
    6778:           }
    6779:           /* copy temporary constraints into larger work vector (in order to store all columns of Q) */
    6780:           PetscArraycpy(qr_basis,&constraints_data[constraints_data_ptr[total_counts]],size_of_constraint*primal_dofs);

    6782:           /* compute QR decomposition of constraints */
    6783:           PetscBLASIntCast(size_of_constraint,&Blas_M);
    6784:           PetscBLASIntCast(primal_dofs,&Blas_N);
    6785:           PetscBLASIntCast(size_of_constraint,&Blas_LDA);
    6786:           PetscFPTrapPush(PETSC_FP_TRAP_OFF);
    6787:           PetscStackCallBLAS("LAPACKgeqrf",LAPACKgeqrf_(&Blas_M,&Blas_N,qr_basis,&Blas_LDA,qr_tau,qr_work,&lqr_work,&lierr));
    6788:           if (lierr) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_LIB,"Error in GEQRF Lapack routine %d",(int)lierr);
    6789:           PetscFPTrapPop();

    6791:           /* explictly compute R^-T */
    6792:           PetscArrayzero(trs_rhs,primal_dofs*primal_dofs);
    6793:           for (j=0;j<primal_dofs;j++) trs_rhs[j*(primal_dofs+1)] = 1.0;
    6794:           PetscBLASIntCast(primal_dofs,&Blas_N);
    6795:           PetscBLASIntCast(primal_dofs,&Blas_NRHS);
    6796:           PetscBLASIntCast(size_of_constraint,&Blas_LDA);
    6797:           PetscBLASIntCast(primal_dofs,&Blas_LDB);
    6798:           PetscFPTrapPush(PETSC_FP_TRAP_OFF);
    6799:           PetscStackCallBLAS("LAPACKtrtrs",LAPACKtrtrs_("U","T","N",&Blas_N,&Blas_NRHS,qr_basis,&Blas_LDA,trs_rhs,&Blas_LDB,&lierr));
    6800:           if (lierr) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_LIB,"Error in TRTRS Lapack routine %d",(int)lierr);
    6801:           PetscFPTrapPop();

    6803:           /* explicitly compute all columns of Q (Q = [Q1 | Q2] ) overwriting QR factorization in qr_basis */
    6804:           PetscBLASIntCast(size_of_constraint,&Blas_M);
    6805:           PetscBLASIntCast(size_of_constraint,&Blas_N);
    6806:           PetscBLASIntCast(primal_dofs,&Blas_K);
    6807:           PetscBLASIntCast(size_of_constraint,&Blas_LDA);
    6808:           PetscFPTrapPush(PETSC_FP_TRAP_OFF);
    6809:           PetscStackCallBLAS("LAPACKorgqr",LAPACKorgqr_(&Blas_M,&Blas_N,&Blas_K,qr_basis,&Blas_LDA,qr_tau,gqr_work,&lgqr_work,&lierr));
    6810:           if (lierr) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_LIB,"Error in ORGQR/UNGQR Lapack routine %d",(int)lierr);
    6811:           PetscFPTrapPop();

    6813:           /* first primal_dofs columns of Q need to be re-scaled in order to be unitary w.r.t constraints
    6814:              i.e. C_{pxn}*Q_{nxn} should be equal to [I_pxp | 0_pxd] (see check below)
    6815:              where n=size_of_constraint, p=primal_dofs, d=dual_dofs (n=p+d), I and 0 identity and null matrix resp. */
    6816:           PetscBLASIntCast(size_of_constraint,&Blas_M);
    6817:           PetscBLASIntCast(primal_dofs,&Blas_N);
    6818:           PetscBLASIntCast(primal_dofs,&Blas_K);
    6819:           PetscBLASIntCast(size_of_constraint,&Blas_LDA);
    6820:           PetscBLASIntCast(primal_dofs,&Blas_LDB);
    6821:           PetscBLASIntCast(size_of_constraint,&Blas_LDC);
    6822:           PetscFPTrapPush(PETSC_FP_TRAP_OFF);
    6823:           PetscStackCallBLAS("BLASgemm",BLASgemm_("N","N",&Blas_M,&Blas_N,&Blas_K,&one,qr_basis,&Blas_LDA,trs_rhs,&Blas_LDB,&zero,constraints_data+constraints_data_ptr[total_counts],&Blas_LDC));
    6824:           PetscFPTrapPop();
    6825:           PetscArraycpy(qr_basis,&constraints_data[constraints_data_ptr[total_counts]],size_of_constraint*primal_dofs);

    6827:           /* insert values in change of basis matrix respecting global ordering of new primal dofs */
    6828:           start_rows = &constraints_idxs[constraints_idxs_ptr[total_counts]];
    6829:           /* insert cols for primal dofs */
    6830:           for (j=0;j<primal_dofs;j++) {
    6831:             start_vals = &qr_basis[j*size_of_constraint];
    6832:             start_cols = &constraints_idxs[constraints_idxs_ptr[total_counts]+j];
    6833:             MatSetValues(localChangeOfBasisMatrix,size_of_constraint,start_rows,1,start_cols,start_vals,INSERT_VALUES);
    6834:           }
    6835:           /* insert cols for dual dofs */
    6836:           for (j=0,k=0;j<dual_dofs;k++) {
    6837:             if (!PetscBTLookup(is_primal,constraints_idxs_B[constraints_idxs_ptr[total_counts]+k])) {
    6838:               start_vals = &qr_basis[(primal_dofs+j)*size_of_constraint];
    6839:               start_cols = &constraints_idxs[constraints_idxs_ptr[total_counts]+k];
    6840:               MatSetValues(localChangeOfBasisMatrix,size_of_constraint,start_rows,1,start_cols,start_vals,INSERT_VALUES);
    6841:               j++;
    6842:             }
    6843:           }

    6845:           /* check change of basis */
    6846:           if (pcbddc->dbg_flag) {
    6847:             PetscInt   ii,jj;
    6848:             PetscBool valid_qr=PETSC_TRUE;
    6849:             PetscBLASIntCast(primal_dofs,&Blas_M);
    6850:             PetscBLASIntCast(size_of_constraint,&Blas_N);
    6851:             PetscBLASIntCast(size_of_constraint,&Blas_K);
    6852:             PetscBLASIntCast(size_of_constraint,&Blas_LDA);
    6853:             PetscBLASIntCast(size_of_constraint,&Blas_LDB);
    6854:             PetscBLASIntCast(primal_dofs,&Blas_LDC);
    6855:             PetscFPTrapPush(PETSC_FP_TRAP_OFF);
    6856:             PetscStackCallBLAS("BLASgemm",BLASgemm_("T","N",&Blas_M,&Blas_N,&Blas_K,&one,dbg_work,&Blas_LDA,qr_basis,&Blas_LDB,&zero,&dbg_work[size_of_constraint*primal_dofs],&Blas_LDC));
    6857:             PetscFPTrapPop();
    6858:             for (jj=0;jj<size_of_constraint;jj++) {
    6859:               for (ii=0;ii<primal_dofs;ii++) {
    6860:                 if (ii != jj && PetscAbsScalar(dbg_work[size_of_constraint*primal_dofs+jj*primal_dofs+ii]) > 1.e-12) valid_qr = PETSC_FALSE;
    6861:                 if (ii == jj && PetscAbsScalar(dbg_work[size_of_constraint*primal_dofs+jj*primal_dofs+ii]-(PetscReal)1) > 1.e-12) valid_qr = PETSC_FALSE;
    6862:               }
    6863:             }
    6864:             if (!valid_qr) {
    6865:               PetscViewerASCIISynchronizedPrintf(pcbddc->dbg_viewer,"\t-> wrong change of basis!\n");
    6866:               for (jj=0;jj<size_of_constraint;jj++) {
    6867:                 for (ii=0;ii<primal_dofs;ii++) {
    6868:                   if (ii != jj && PetscAbsScalar(dbg_work[size_of_constraint*primal_dofs+jj*primal_dofs+ii]) > 1.e-12) {
    6869:                     PetscViewerASCIISynchronizedPrintf(pcbddc->dbg_viewer,"\tQr basis function %D is not orthogonal to constraint %D (%1.14e)!\n",jj,ii,PetscAbsScalar(dbg_work[size_of_constraint*primal_dofs+jj*primal_dofs+ii]));
    6870:                   }
    6871:                   if (ii == jj && PetscAbsScalar(dbg_work[size_of_constraint*primal_dofs+jj*primal_dofs+ii]-(PetscReal)1) > 1.e-12) {
    6872:                     PetscViewerASCIISynchronizedPrintf(pcbddc->dbg_viewer,"\tQr basis function %D is not unitary w.r.t constraint %D (%1.14e)!\n",jj,ii,PetscAbsScalar(dbg_work[size_of_constraint*primal_dofs+jj*primal_dofs+ii]));
    6873:                   }
    6874:                 }
    6875:               }
    6876:             } else {
    6877:               PetscViewerASCIISynchronizedPrintf(pcbddc->dbg_viewer,"\t-> right change of basis!\n");
    6878:             }
    6879:           }
    6880:         } else { /* simple transformation block */
    6881:           PetscInt    row,col;
    6882:           PetscScalar val,norm;

    6884:           PetscBLASIntCast(size_of_constraint,&Blas_N);
    6885:           PetscStackCallBLAS("BLASdot",norm = BLASdot_(&Blas_N,constraints_data+constraints_data_ptr[total_counts],&Blas_one,constraints_data+constraints_data_ptr[total_counts],&Blas_one));
    6886:           for (j=0;j<size_of_constraint;j++) {
    6887:             PetscInt row_B = constraints_idxs_B[constraints_idxs_ptr[total_counts]+j];
    6888:             row = constraints_idxs[constraints_idxs_ptr[total_counts]+j];
    6889:             if (!PetscBTLookup(is_primal,row_B)) {
    6890:               col = constraints_idxs[constraints_idxs_ptr[total_counts]];
    6891:               MatSetValue(localChangeOfBasisMatrix,row,row,1.0,INSERT_VALUES);
    6892:               MatSetValue(localChangeOfBasisMatrix,row,col,constraints_data[constraints_data_ptr[total_counts]+j]/norm,INSERT_VALUES);
    6893:             } else {
    6894:               for (k=0;k<size_of_constraint;k++) {
    6895:                 col = constraints_idxs[constraints_idxs_ptr[total_counts]+k];
    6896:                 if (row != col) {
    6897:                   val = -constraints_data[constraints_data_ptr[total_counts]+k]/constraints_data[constraints_data_ptr[total_counts]];
    6898:                 } else {
    6899:                   val = constraints_data[constraints_data_ptr[total_counts]]/norm;
    6900:                 }
    6901:                 MatSetValue(localChangeOfBasisMatrix,row,col,val,INSERT_VALUES);
    6902:               }
    6903:             }
    6904:           }
    6905:           if (pcbddc->dbg_flag) {
    6906:             PetscViewerASCIISynchronizedPrintf(pcbddc->dbg_viewer,"\t-> using standard change of basis\n");
    6907:           }
    6908:         }
    6909:       } else {
    6910:         if (pcbddc->dbg_flag) {
    6911:           PetscViewerASCIISynchronizedPrintf(pcbddc->dbg_viewer,"Constraint %D does not need a change of basis (size %D)\n",total_counts,size_of_constraint);
    6912:         }
    6913:       }
    6914:     }

    6916:     /* free workspace */
    6917:     if (qr_needed) {
    6918:       if (pcbddc->dbg_flag) {
    6919:         PetscFree(dbg_work);
    6920:       }
    6921:       PetscFree(trs_rhs);
    6922:       PetscFree(qr_tau);
    6923:       PetscFree(qr_work);
    6924:       PetscFree(gqr_work);
    6925:       PetscFree(qr_basis);
    6926:     }
    6927:     PetscBTDestroy(&is_primal);
    6928:     MatAssemblyBegin(localChangeOfBasisMatrix,MAT_FINAL_ASSEMBLY);
    6929:     MatAssemblyEnd(localChangeOfBasisMatrix,MAT_FINAL_ASSEMBLY);

    6931:     /* assembling of global change of variable */
    6932:     if (!pcbddc->fake_change) {
    6933:       Mat      tmat;
    6934:       PetscInt bs;

    6936:       VecGetSize(pcis->vec1_global,&global_size);
    6937:       VecGetLocalSize(pcis->vec1_global,&local_size);
    6938:       MatDuplicate(pc->pmat,MAT_DO_NOT_COPY_VALUES,&tmat);
    6939:       MatISSetLocalMat(tmat,localChangeOfBasisMatrix);
    6940:       MatAssemblyBegin(tmat,MAT_FINAL_ASSEMBLY);
    6941:       MatAssemblyEnd(tmat,MAT_FINAL_ASSEMBLY);
    6942:       MatCreate(PetscObjectComm((PetscObject)pc),&pcbddc->ChangeOfBasisMatrix);
    6943:       MatSetType(pcbddc->ChangeOfBasisMatrix,MATAIJ);
    6944:       MatGetBlockSize(pc->pmat,&bs);
    6945:       MatSetBlockSize(pcbddc->ChangeOfBasisMatrix,bs);
    6946:       MatSetSizes(pcbddc->ChangeOfBasisMatrix,local_size,local_size,global_size,global_size);
    6947:       MatISSetMPIXAIJPreallocation_Private(tmat,pcbddc->ChangeOfBasisMatrix,PETSC_TRUE);
    6948:       MatConvert(tmat,MATAIJ,MAT_REUSE_MATRIX,&pcbddc->ChangeOfBasisMatrix);
    6949:       MatDestroy(&tmat);
    6950:       VecSet(pcis->vec1_global,0.0);
    6951:       VecSet(pcis->vec1_N,1.0);
    6952:       VecScatterBegin(matis->rctx,pcis->vec1_N,pcis->vec1_global,ADD_VALUES,SCATTER_REVERSE);
    6953:       VecScatterEnd(matis->rctx,pcis->vec1_N,pcis->vec1_global,ADD_VALUES,SCATTER_REVERSE);
    6954:       VecReciprocal(pcis->vec1_global);
    6955:       MatDiagonalScale(pcbddc->ChangeOfBasisMatrix,pcis->vec1_global,NULL);

    6957:       /* check */
    6958:       if (pcbddc->dbg_flag) {
    6959:         PetscReal error;
    6960:         Vec       x,x_change;

    6962:         VecDuplicate(pcis->vec1_global,&x);
    6963:         VecDuplicate(pcis->vec1_global,&x_change);
    6964:         VecSetRandom(x,NULL);
    6965:         VecCopy(x,pcis->vec1_global);
    6966:         VecScatterBegin(matis->rctx,x,pcis->vec1_N,INSERT_VALUES,SCATTER_FORWARD);
    6967:         VecScatterEnd(matis->rctx,x,pcis->vec1_N,INSERT_VALUES,SCATTER_FORWARD);
    6968:         MatMult(localChangeOfBasisMatrix,pcis->vec1_N,pcis->vec2_N);
    6969:         VecScatterBegin(matis->rctx,pcis->vec2_N,x,INSERT_VALUES,SCATTER_REVERSE);
    6970:         VecScatterEnd(matis->rctx,pcis->vec2_N,x,INSERT_VALUES,SCATTER_REVERSE);
    6971:         MatMult(pcbddc->ChangeOfBasisMatrix,pcis->vec1_global,x_change);
    6972:         VecAXPY(x,-1.0,x_change);
    6973:         VecNorm(x,NORM_INFINITY,&error);
    6974:         if (error > PETSC_SMALL) {
    6975:           SETERRQ1(PetscObjectComm((PetscObject)pc),PETSC_ERR_PLIB,"Error global vs local change on N: %1.6e",error);
    6976:         }
    6977:         VecDestroy(&x);
    6978:         VecDestroy(&x_change);
    6979:       }
    6980:       /* adapt sub_schurs computed (if any) */
    6981:       if (pcbddc->use_deluxe_scaling) {
    6982:         PCBDDCSubSchurs sub_schurs=pcbddc->sub_schurs;

    6984:         if (pcbddc->use_change_of_basis && pcbddc->adaptive_userdefined) SETERRQ(PetscObjectComm((PetscObject)pc),PETSC_ERR_SUP,"Cannot mix automatic change of basis, adaptive selection and user-defined constraints");
    6985:         if (sub_schurs && sub_schurs->S_Ej_all) {
    6986:           Mat                    S_new,tmat;
    6987:           IS                     is_all_N,is_V_Sall = NULL;

    6989:           ISLocalToGlobalMappingApplyIS(pcis->BtoNmap,sub_schurs->is_Ej_all,&is_all_N);
    6990:           MatCreateSubMatrix(localChangeOfBasisMatrix,is_all_N,is_all_N,MAT_INITIAL_MATRIX,&tmat);
    6991:           if (pcbddc->deluxe_zerorows) {
    6992:             ISLocalToGlobalMapping NtoSall;
    6993:             IS                     is_V;
    6994:             ISCreateGeneral(PETSC_COMM_SELF,pcbddc->n_vertices,pcbddc->local_primal_ref_node,PETSC_COPY_VALUES,&is_V);
    6995:             ISLocalToGlobalMappingCreateIS(is_all_N,&NtoSall);
    6996:             ISGlobalToLocalMappingApplyIS(NtoSall,IS_GTOLM_DROP,is_V,&is_V_Sall);
    6997:             ISLocalToGlobalMappingDestroy(&NtoSall);
    6998:             ISDestroy(&is_V);
    6999:           }
    7000:           ISDestroy(&is_all_N);
    7001:           MatPtAP(sub_schurs->S_Ej_all,tmat,MAT_INITIAL_MATRIX,1.0,&S_new);
    7002:           MatDestroy(&sub_schurs->S_Ej_all);
    7003:           PetscObjectReference((PetscObject)S_new);
    7004:           if (pcbddc->deluxe_zerorows) {
    7005:             const PetscScalar *array;
    7006:             const PetscInt    *idxs_V,*idxs_all;
    7007:             PetscInt          i,n_V;

    7009:             MatZeroRowsColumnsIS(S_new,is_V_Sall,1.,NULL,NULL);
    7010:             ISGetLocalSize(is_V_Sall,&n_V);
    7011:             ISGetIndices(is_V_Sall,&idxs_V);
    7012:             ISGetIndices(sub_schurs->is_Ej_all,&idxs_all);
    7013:             VecGetArrayRead(pcis->D,&array);
    7014:             for (i=0;i<n_V;i++) {
    7015:               PetscScalar val;
    7016:               PetscInt    idx;

    7018:               idx = idxs_V[i];
    7019:               val = array[idxs_all[idxs_V[i]]];
    7020:               MatSetValue(S_new,idx,idx,val,INSERT_VALUES);
    7021:             }
    7022:             MatAssemblyBegin(S_new,MAT_FINAL_ASSEMBLY);
    7023:             MatAssemblyEnd(S_new,MAT_FINAL_ASSEMBLY);
    7024:             VecRestoreArrayRead(pcis->D,&array);
    7025:             ISRestoreIndices(sub_schurs->is_Ej_all,&idxs_all);
    7026:             ISRestoreIndices(is_V_Sall,&idxs_V);
    7027:           }
    7028:           sub_schurs->S_Ej_all = S_new;
    7029:           MatDestroy(&S_new);
    7030:           if (sub_schurs->sum_S_Ej_all) {
    7031:             MatPtAP(sub_schurs->sum_S_Ej_all,tmat,MAT_INITIAL_MATRIX,1.0,&S_new);
    7032:             MatDestroy(&sub_schurs->sum_S_Ej_all);
    7033:             PetscObjectReference((PetscObject)S_new);
    7034:             if (pcbddc->deluxe_zerorows) {
    7035:               MatZeroRowsColumnsIS(S_new,is_V_Sall,1.,NULL,NULL);
    7036:             }
    7037:             sub_schurs->sum_S_Ej_all = S_new;
    7038:             MatDestroy(&S_new);
    7039:           }
    7040:           ISDestroy(&is_V_Sall);
    7041:           MatDestroy(&tmat);
    7042:         }
    7043:         /* destroy any change of basis context in sub_schurs */
    7044:         if (sub_schurs && sub_schurs->change) {
    7045:           PetscInt i;

    7047:           for (i=0;i<sub_schurs->n_subs;i++) {
    7048:             KSPDestroy(&sub_schurs->change[i]);
    7049:           }
    7050:           PetscFree(sub_schurs->change);
    7051:         }
    7052:       }
    7053:       if (pcbddc->switch_static) { /* need to save the local change */
    7054:         pcbddc->switch_static_change = localChangeOfBasisMatrix;
    7055:       } else {
    7056:         MatDestroy(&localChangeOfBasisMatrix);
    7057:       }
    7058:       /* determine if any process has changed the pressures locally */
    7059:       pcbddc->change_interior = pcbddc->benign_have_null;
    7060:     } else { /* fake change (get back change of basis into ConstraintMatrix and info on qr) */
    7061:       MatDestroy(&pcbddc->ConstraintMatrix);
    7062:       pcbddc->ConstraintMatrix = localChangeOfBasisMatrix;
    7063:       pcbddc->use_qr_single = qr_needed;
    7064:     }
    7065:   } else if (pcbddc->user_ChangeOfBasisMatrix || pcbddc->benign_saddle_point) {
    7066:     if (!pcbddc->benign_have_null && pcbddc->user_ChangeOfBasisMatrix) {
    7067:       PetscObjectReference((PetscObject)pcbddc->user_ChangeOfBasisMatrix);
    7068:       pcbddc->ChangeOfBasisMatrix = pcbddc->user_ChangeOfBasisMatrix;
    7069:     } else {
    7070:       Mat benign_global = NULL;
    7071:       if (pcbddc->benign_have_null) {
    7072:         Mat M;

    7074:         pcbddc->change_interior = PETSC_TRUE;
    7075:         VecCopy(matis->counter,pcis->vec1_N);
    7076:         VecReciprocal(pcis->vec1_N);
    7077:         MatDuplicate(pc->pmat,MAT_DO_NOT_COPY_VALUES,&benign_global);
    7078:         if (pcbddc->benign_change) {
    7079:           MatDuplicate(pcbddc->benign_change,MAT_COPY_VALUES,&M);
    7080:           MatDiagonalScale(M,pcis->vec1_N,NULL);
    7081:         } else {
    7082:           MatCreateSeqAIJ(PETSC_COMM_SELF,pcis->n,pcis->n,1,NULL,&M);
    7083:           MatDiagonalSet(M,pcis->vec1_N,INSERT_VALUES);
    7084:         }
    7085:         MatISSetLocalMat(benign_global,M);
    7086:         MatDestroy(&M);
    7087:         MatAssemblyBegin(benign_global,MAT_FINAL_ASSEMBLY);
    7088:         MatAssemblyEnd(benign_global,MAT_FINAL_ASSEMBLY);
    7089:       }
    7090:       if (pcbddc->user_ChangeOfBasisMatrix) {
    7091:         MatMatMult(pcbddc->user_ChangeOfBasisMatrix,benign_global,MAT_INITIAL_MATRIX,PETSC_DEFAULT,&pcbddc->ChangeOfBasisMatrix);
    7092:         MatDestroy(&benign_global);
    7093:       } else if (pcbddc->benign_have_null) {
    7094:         pcbddc->ChangeOfBasisMatrix = benign_global;
    7095:       }
    7096:     }
    7097:     if (pcbddc->switch_static && pcbddc->ChangeOfBasisMatrix) { /* need to save the local change */
    7098:       IS             is_global;
    7099:       const PetscInt *gidxs;

    7101:       ISLocalToGlobalMappingGetIndices(pc->pmat->rmap->mapping,&gidxs);
    7102:       ISCreateGeneral(PetscObjectComm((PetscObject)pc),pcis->n,gidxs,PETSC_COPY_VALUES,&is_global);
    7103:       ISLocalToGlobalMappingRestoreIndices(pc->pmat->rmap->mapping,&gidxs);
    7104:       MatCreateSubMatrixUnsorted(pcbddc->ChangeOfBasisMatrix,is_global,is_global,&pcbddc->switch_static_change);
    7105:       ISDestroy(&is_global);
    7106:     }
    7107:   }
    7108:   if (!pcbddc->fake_change && pcbddc->ChangeOfBasisMatrix && !pcbddc->work_change) {
    7109:     VecDuplicate(pcis->vec1_global,&pcbddc->work_change);
    7110:   }

    7112:   if (!pcbddc->fake_change) {
    7113:     /* add pressure dofs to set of primal nodes for numbering purposes */
    7114:     for (i=0;i<pcbddc->benign_n;i++) {
    7115:       pcbddc->local_primal_ref_node[pcbddc->local_primal_size_cc] = pcbddc->benign_p0_lidx[i];
    7116:       pcbddc->primal_indices_local_idxs[pcbddc->local_primal_size] = pcbddc->benign_p0_lidx[i];
    7117:       pcbddc->local_primal_ref_mult[pcbddc->local_primal_size_cc] = 1;
    7118:       pcbddc->local_primal_size_cc++;
    7119:       pcbddc->local_primal_size++;
    7120:     }

    7122:     /* check if a new primal space has been introduced (also take into account benign trick) */
    7123:     pcbddc->new_primal_space_local = PETSC_TRUE;
    7124:     if (olocal_primal_size == pcbddc->local_primal_size) {
    7125:       PetscArraycmp(pcbddc->local_primal_ref_node,olocal_primal_ref_node,olocal_primal_size_cc,&pcbddc->new_primal_space_local);
    7126:       pcbddc->new_primal_space_local = (PetscBool)(!pcbddc->new_primal_space_local);
    7127:       if (!pcbddc->new_primal_space_local) {
    7128:         PetscArraycmp(pcbddc->local_primal_ref_mult,olocal_primal_ref_mult,olocal_primal_size_cc,&pcbddc->new_primal_space_local);
    7129:         pcbddc->new_primal_space_local = (PetscBool)(!pcbddc->new_primal_space_local);
    7130:       }
    7131:     }
    7132:     /* new_primal_space will be used for numbering of coarse dofs, so it should be the same across all subdomains */
    7133:     MPIU_Allreduce(&pcbddc->new_primal_space_local,&pcbddc->new_primal_space,1,MPIU_BOOL,MPI_LOR,PetscObjectComm((PetscObject)pc));
    7134:   }
    7135:   PetscFree2(olocal_primal_ref_node,olocal_primal_ref_mult);

    7137:   /* flush dbg viewer */
    7138:   if (pcbddc->dbg_flag) {
    7139:     PetscViewerFlush(pcbddc->dbg_viewer);
    7140:   }

    7142:   /* free workspace */
    7143:   PetscBTDestroy(&qr_needed_idx);
    7144:   PetscBTDestroy(&change_basis);
    7145:   if (!pcbddc->adaptive_selection) {
    7146:     PetscFree3(constraints_idxs_ptr,constraints_data_ptr,constraints_n);
    7147:     PetscFree3(constraints_data,constraints_idxs,constraints_idxs_B);
    7148:   } else {
    7149:     PetscFree5(pcbddc->adaptive_constraints_n,
    7150:                       pcbddc->adaptive_constraints_idxs_ptr,
    7151:                       pcbddc->adaptive_constraints_data_ptr,
    7152:                       pcbddc->adaptive_constraints_idxs,
    7153:                       pcbddc->adaptive_constraints_data);
    7154:     PetscFree(constraints_n);
    7155:     PetscFree(constraints_idxs_B);
    7156:   }
    7157:   return(0);
    7158: }

    7160: PetscErrorCode PCBDDCAnalyzeInterface(PC pc)
    7161: {
    7162:   ISLocalToGlobalMapping map;
    7163:   PC_BDDC                *pcbddc = (PC_BDDC*)pc->data;
    7164:   Mat_IS                 *matis  = (Mat_IS*)pc->pmat->data;
    7165:   PetscInt               i,N;
    7166:   PetscBool              rcsr = PETSC_FALSE;
    7167:   PetscErrorCode         ierr;

    7170:   if (pcbddc->recompute_topography) {
    7171:     pcbddc->graphanalyzed = PETSC_FALSE;
    7172:     /* Reset previously computed graph */
    7173:     PCBDDCGraphReset(pcbddc->mat_graph);
    7174:     /* Init local Graph struct */
    7175:     MatGetSize(pc->pmat,&N,NULL);
    7176:     MatGetLocalToGlobalMapping(pc->pmat,&map,NULL);
    7177:     PCBDDCGraphInit(pcbddc->mat_graph,map,N,pcbddc->graphmaxcount);

    7179:     if (pcbddc->user_primal_vertices_local && !pcbddc->user_primal_vertices) {
    7180:       PCBDDCConsistencyCheckIS(pc,MPI_LOR,&pcbddc->user_primal_vertices_local);
    7181:     }
    7182:     /* Check validity of the csr graph passed in by the user */
    7183:     if (pcbddc->mat_graph->nvtxs_csr && pcbddc->mat_graph->nvtxs_csr != pcbddc->mat_graph->nvtxs) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,"Invalid size of local CSR graph! Found %D, expected %D",pcbddc->mat_graph->nvtxs_csr,pcbddc->mat_graph->nvtxs);

    7185:     /* Set default CSR adjacency of local dofs if not provided by the user with PCBDDCSetLocalAdjacencyGraph */
    7186:     if (!pcbddc->mat_graph->xadj && pcbddc->use_local_adj) {
    7187:       PetscInt  *xadj,*adjncy;
    7188:       PetscInt  nvtxs;
    7189:       PetscBool flg_row=PETSC_FALSE;

    7191:       MatGetRowIJ(matis->A,0,PETSC_TRUE,PETSC_FALSE,&nvtxs,(const PetscInt**)&xadj,(const PetscInt**)&adjncy,&flg_row);
    7192:       if (flg_row) {
    7193:         PCBDDCSetLocalAdjacencyGraph(pc,nvtxs,xadj,adjncy,PETSC_COPY_VALUES);
    7194:         pcbddc->computed_rowadj = PETSC_TRUE;
    7195:       }
    7196:       MatRestoreRowIJ(matis->A,0,PETSC_TRUE,PETSC_FALSE,&nvtxs,(const PetscInt**)&xadj,(const PetscInt**)&adjncy,&flg_row);
    7197:       rcsr = PETSC_TRUE;
    7198:     }
    7199:     if (pcbddc->dbg_flag) {
    7200:       PetscViewerFlush(pcbddc->dbg_viewer);
    7201:     }

    7203:     if (pcbddc->mat_graph->cdim && !pcbddc->mat_graph->cloc) {
    7204:       PetscReal    *lcoords;
    7205:       PetscInt     n;
    7206:       MPI_Datatype dimrealtype;

    7208:       /* TODO: support for blocked */
    7209:       if (pcbddc->mat_graph->cnloc != pc->pmat->rmap->n) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_USER,"Invalid number of local coordinates! Got %D, expected %D",pcbddc->mat_graph->cnloc,pc->pmat->rmap->n);
    7210:       MatGetLocalSize(matis->A,&n,NULL);
    7211:       PetscMalloc1(pcbddc->mat_graph->cdim*n,&lcoords);
    7212:       MPI_Type_contiguous(pcbddc->mat_graph->cdim,MPIU_REAL,&dimrealtype);
    7213:       MPI_Type_commit(&dimrealtype);
    7214:       PetscSFBcastBegin(matis->sf,dimrealtype,pcbddc->mat_graph->coords,lcoords);
    7215:       PetscSFBcastEnd(matis->sf,dimrealtype,pcbddc->mat_graph->coords,lcoords);
    7216:       MPI_Type_free(&dimrealtype);
    7217:       PetscFree(pcbddc->mat_graph->coords);

    7219:       pcbddc->mat_graph->coords = lcoords;
    7220:       pcbddc->mat_graph->cloc   = PETSC_TRUE;
    7221:       pcbddc->mat_graph->cnloc  = n;
    7222:     }
    7223:     if (pcbddc->mat_graph->cnloc && pcbddc->mat_graph->cnloc != pcbddc->mat_graph->nvtxs) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_USER,"Invalid number of local subdomain coordinates! Got %D, expected %D",pcbddc->mat_graph->cnloc,pcbddc->mat_graph->nvtxs);
    7224:     pcbddc->mat_graph->active_coords = (PetscBool)(pcbddc->corner_selection && !pcbddc->corner_selected);

    7226:     /* Setup of Graph */
    7227:     pcbddc->mat_graph->commsizelimit = 0; /* don't use the COMM_SELF variant of the graph */
    7228:     PCBDDCGraphSetUp(pcbddc->mat_graph,pcbddc->vertex_size,pcbddc->NeumannBoundariesLocal,pcbddc->DirichletBoundariesLocal,pcbddc->n_ISForDofsLocal,pcbddc->ISForDofsLocal,pcbddc->user_primal_vertices_local);

    7230:     /* attach info on disconnected subdomains if present */
    7231:     if (pcbddc->n_local_subs) {
    7232:       PetscInt *local_subs,n,totn;

    7234:       MatGetLocalSize(matis->A,&n,NULL);
    7235:       PetscMalloc1(n,&local_subs);
    7236:       for (i=0;i<n;i++) local_subs[i] = pcbddc->n_local_subs;
    7237:       for (i=0;i<pcbddc->n_local_subs;i++) {
    7238:         const PetscInt *idxs;
    7239:         PetscInt       nl,j;

    7241:         ISGetLocalSize(pcbddc->local_subs[i],&nl);
    7242:         ISGetIndices(pcbddc->local_subs[i],&idxs);
    7243:         for (j=0;j<nl;j++) local_subs[idxs[j]] = i;
    7244:         ISRestoreIndices(pcbddc->local_subs[i],&idxs);
    7245:       }
    7246:       for (i=0,totn=0;i<n;i++) totn = PetscMax(totn,local_subs[i]);
    7247:       pcbddc->mat_graph->n_local_subs = totn + 1;
    7248:       pcbddc->mat_graph->local_subs = local_subs;
    7249:     }
    7250:   }

    7252:   if (!pcbddc->graphanalyzed) {
    7253:     /* Graph's connected components analysis */
    7254:     PCBDDCGraphComputeConnectedComponents(pcbddc->mat_graph);
    7255:     pcbddc->graphanalyzed = PETSC_TRUE;
    7256:     pcbddc->corner_selected = pcbddc->corner_selection;
    7257:   }
    7258:   if (rcsr) pcbddc->mat_graph->nvtxs_csr = 0;
    7259:   return(0);
    7260: }

    7262: PetscErrorCode PCBDDCOrthonormalizeVecs(PetscInt *nio, Vec vecs[])
    7263: {
    7264:   PetscInt       i,j,n;
    7265:   PetscScalar    *alphas;
    7266:   PetscReal      norm,*onorms;

    7270:   n = *nio;
    7271:   if (!n) return(0);
    7272:   PetscMalloc2(n,&alphas,n,&onorms);
    7273:   VecNormalize(vecs[0],&norm);
    7274:   if (norm < PETSC_SMALL) {
    7275:     onorms[0] = 0.0;
    7276:     VecSet(vecs[0],0.0);
    7277:   } else {
    7278:     onorms[0] = norm;
    7279:   }

    7281:   for (i=1;i<n;i++) {
    7282:     VecMDot(vecs[i],i,vecs,alphas);
    7283:     for (j=0;j<i;j++) alphas[j] = PetscConj(-alphas[j]);
    7284:     VecMAXPY(vecs[i],i,alphas,vecs);
    7285:     VecNormalize(vecs[i],&norm);
    7286:     if (norm < PETSC_SMALL) {
    7287:       onorms[i] = 0.0;
    7288:       VecSet(vecs[i],0.0);
    7289:     } else {
    7290:       onorms[i] = norm;
    7291:     }
    7292:   }
    7293:   /* push nonzero vectors at the beginning */
    7294:   for (i=0;i<n;i++) {
    7295:     if (onorms[i] == 0.0) {
    7296:       for (j=i+1;j<n;j++) {
    7297:         if (onorms[j] != 0.0) {
    7298:           VecCopy(vecs[j],vecs[i]);
    7299:           onorms[j] = 0.0;
    7300:         }
    7301:       }
    7302:     }
    7303:   }
    7304:   for (i=0,*nio=0;i<n;i++) *nio += onorms[i] != 0.0 ? 1 : 0;
    7305:   PetscFree2(alphas,onorms);
    7306:   return(0);
    7307: }

    7309: PetscErrorCode PCBDDCMatISGetSubassemblingPattern(Mat mat, PetscInt *n_subdomains, PetscInt redprocs, IS* is_sends, PetscBool *have_void)
    7310: {
    7311:   Mat            A;
    7312:   PetscInt       n_neighs,*neighs,*n_shared,**shared;
    7313:   PetscMPIInt    size,rank,color;
    7314:   PetscInt       *xadj,*adjncy;
    7315:   PetscInt       *adjncy_wgt,*v_wgt,*ranks_send_to_idx;
    7316:   PetscInt       im_active,active_procs,N,n,i,j,threshold = 2;
    7317:   PetscInt       void_procs,*procs_candidates = NULL;
    7318:   PetscInt       xadj_count,*count;
    7319:   PetscBool      ismatis,use_vwgt=PETSC_FALSE;
    7320:   PetscSubcomm   psubcomm;
    7321:   MPI_Comm       subcomm;

    7326:   PetscObjectTypeCompare((PetscObject)mat,MATIS,&ismatis);
    7327:   if (!ismatis) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Cannot use %s on a matrix object which is not of type MATIS",PETSC_FUNCTION_NAME);
    7330:   if (*n_subdomains <=0) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONG,"Invalid number of subdomains requested %D",*n_subdomains);

    7332:   if (have_void) *have_void = PETSC_FALSE;
    7333:   MPI_Comm_size(PetscObjectComm((PetscObject)mat),&size);
    7334:   MPI_Comm_rank(PetscObjectComm((PetscObject)mat),&rank);
    7335:   MatISGetLocalMat(mat,&A);
    7336:   MatGetLocalSize(A,&n,NULL);
    7337:   im_active = !!n;
    7338:   MPIU_Allreduce(&im_active,&active_procs,1,MPIU_INT,MPI_SUM,PetscObjectComm((PetscObject)mat));
    7339:   void_procs = size - active_procs;
    7340:   /* get ranks of of non-active processes in mat communicator */
    7341:   if (void_procs) {
    7342:     PetscInt ncand;

    7344:     if (have_void) *have_void = PETSC_TRUE;
    7345:     PetscMalloc1(size,&procs_candidates);
    7346:     MPI_Allgather(&im_active,1,MPIU_INT,procs_candidates,1,MPIU_INT,PetscObjectComm((PetscObject)mat));
    7347:     for (i=0,ncand=0;i<size;i++) {
    7348:       if (!procs_candidates[i]) {
    7349:         procs_candidates[ncand++] = i;
    7350:       }
    7351:     }
    7352:     /* force n_subdomains to be not greater that the number of non-active processes */
    7353:     *n_subdomains = PetscMin(void_procs,*n_subdomains);
    7354:   }

    7356:   /* number of subdomains requested greater than active processes or matrix size -> just shift the matrix
    7357:      number of subdomains requested 1 -> send to master or first candidate in voids  */
    7358:   MatGetSize(mat,&N,NULL);
    7359:   if (active_procs < *n_subdomains || *n_subdomains == 1 || N <= *n_subdomains) {
    7360:     PetscInt issize,isidx,dest;
    7361:     if (*n_subdomains == 1) dest = 0;
    7362:     else dest = rank;
    7363:     if (im_active) {
    7364:       issize = 1;
    7365:       if (procs_candidates) { /* shift the pattern on non-active candidates (if any) */
    7366:         isidx = procs_candidates[dest];
    7367:       } else {
    7368:         isidx = dest;
    7369:       }
    7370:     } else {
    7371:       issize = 0;
    7372:       isidx = -1;
    7373:     }
    7374:     if (*n_subdomains != 1) *n_subdomains = active_procs;
    7375:     ISCreateGeneral(PetscObjectComm((PetscObject)mat),issize,&isidx,PETSC_COPY_VALUES,is_sends);
    7376:     PetscFree(procs_candidates);
    7377:     return(0);
    7378:   }
    7379:   PetscOptionsGetBool(NULL,NULL,"-matis_partitioning_use_vwgt",&use_vwgt,NULL);
    7380:   PetscOptionsGetInt(NULL,NULL,"-matis_partitioning_threshold",&threshold,NULL);
    7381:   threshold = PetscMax(threshold,2);

    7383:   /* Get info on mapping */
    7384:   ISLocalToGlobalMappingGetInfo(mat->rmap->mapping,&n_neighs,&neighs,&n_shared,&shared);

    7386:   /* build local CSR graph of subdomains' connectivity */
    7387:   PetscMalloc1(2,&xadj);
    7388:   xadj[0] = 0;
    7389:   xadj[1] = PetscMax(n_neighs-1,0);
    7390:   PetscMalloc1(xadj[1],&adjncy);
    7391:   PetscMalloc1(xadj[1],&adjncy_wgt);
    7392:   PetscCalloc1(n,&count);
    7393:   for (i=1;i<n_neighs;i++)
    7394:     for (j=0;j<n_shared[i];j++)
    7395:       count[shared[i][j]] += 1;

    7397:   xadj_count = 0;
    7398:   for (i=1;i<n_neighs;i++) {
    7399:     for (j=0;j<n_shared[i];j++) {
    7400:       if (count[shared[i][j]] < threshold) {
    7401:         adjncy[xadj_count] = neighs[i];
    7402:         adjncy_wgt[xadj_count] = n_shared[i];
    7403:         xadj_count++;
    7404:         break;
    7405:       }
    7406:     }
    7407:   }
    7408:   xadj[1] = xadj_count;
    7409:   PetscFree(count);
    7410:   ISLocalToGlobalMappingRestoreInfo(mat->rmap->mapping,&n_neighs,&neighs,&n_shared,&shared);
    7411:   PetscSortIntWithArray(xadj[1],adjncy,adjncy_wgt);

    7413:   PetscMalloc1(1,&ranks_send_to_idx);

    7415:   /* Restrict work on active processes only */
    7416:   PetscMPIIntCast(im_active,&color);
    7417:   if (void_procs) {
    7418:     PetscSubcommCreate(PetscObjectComm((PetscObject)mat),&psubcomm);
    7419:     PetscSubcommSetNumber(psubcomm,2); /* 2 groups, active process and not active processes */
    7420:     PetscSubcommSetTypeGeneral(psubcomm,color,rank);
    7421:     subcomm = PetscSubcommChild(psubcomm);
    7422:   } else {
    7423:     psubcomm = NULL;
    7424:     subcomm = PetscObjectComm((PetscObject)mat);
    7425:   }

    7427:   v_wgt = NULL;
    7428:   if (!color) {
    7429:     PetscFree(xadj);
    7430:     PetscFree(adjncy);
    7431:     PetscFree(adjncy_wgt);
    7432:   } else {
    7433:     Mat             subdomain_adj;
    7434:     IS              new_ranks,new_ranks_contig;
    7435:     MatPartitioning partitioner;
    7436:     PetscInt        rstart=0,rend=0;
    7437:     PetscInt        *is_indices,*oldranks;
    7438:     PetscMPIInt     size;
    7439:     PetscBool       aggregate;

    7441:     MPI_Comm_size(subcomm,&size);
    7442:     if (void_procs) {
    7443:       PetscInt prank = rank;
    7444:       PetscMalloc1(size,&oldranks);
    7445:       MPI_Allgather(&prank,1,MPIU_INT,oldranks,1,MPIU_INT,subcomm);
    7446:       for (i=0;i<xadj[1];i++) {
    7447:         PetscFindInt(adjncy[i],size,oldranks,&adjncy[i]);
    7448:       }
    7449:       PetscSortIntWithArray(xadj[1],adjncy,adjncy_wgt);
    7450:     } else {
    7451:       oldranks = NULL;
    7452:     }
    7453:     aggregate = ((redprocs > 0 && redprocs < size) ? PETSC_TRUE : PETSC_FALSE);
    7454:     if (aggregate) { /* TODO: all this part could be made more efficient */
    7455:       PetscInt    lrows,row,ncols,*cols;
    7456:       PetscMPIInt nrank;
    7457:       PetscScalar *vals;

    7459:       MPI_Comm_rank(subcomm,&nrank);
    7460:       lrows = 0;
    7461:       if (nrank<redprocs) {
    7462:         lrows = size/redprocs;
    7463:         if (nrank<size%redprocs) lrows++;
    7464:       }
    7465:       MatCreateAIJ(subcomm,lrows,lrows,size,size,50,NULL,50,NULL,&subdomain_adj);
    7466:       MatGetOwnershipRange(subdomain_adj,&rstart,&rend);
    7467:       MatSetOption(subdomain_adj,MAT_NEW_NONZERO_LOCATION_ERR,PETSC_FALSE);
    7468:       MatSetOption(subdomain_adj,MAT_NEW_NONZERO_ALLOCATION_ERR,PETSC_FALSE);
    7469:       row = nrank;
    7470:       ncols = xadj[1]-xadj[0];
    7471:       cols = adjncy;
    7472:       PetscMalloc1(ncols,&vals);
    7473:       for (i=0;i<ncols;i++) vals[i] = adjncy_wgt[i];
    7474:       MatSetValues(subdomain_adj,1,&row,ncols,cols,vals,INSERT_VALUES);
    7475:       MatAssemblyBegin(subdomain_adj,MAT_FINAL_ASSEMBLY);
    7476:       MatAssemblyEnd(subdomain_adj,MAT_FINAL_ASSEMBLY);
    7477:       PetscFree(xadj);
    7478:       PetscFree(adjncy);
    7479:       PetscFree(adjncy_wgt);
    7480:       PetscFree(vals);
    7481:       if (use_vwgt) {
    7482:         Vec               v;
    7483:         const PetscScalar *array;
    7484:         PetscInt          nl;

    7486:         MatCreateVecs(subdomain_adj,&v,NULL);
    7487:         VecSetValue(v,row,(PetscScalar)n,INSERT_VALUES);
    7488:         VecAssemblyBegin(v);
    7489:         VecAssemblyEnd(v);
    7490:         VecGetLocalSize(v,&nl);
    7491:         VecGetArrayRead(v,&array);
    7492:         PetscMalloc1(nl,&v_wgt);
    7493:         for (i=0;i<nl;i++) v_wgt[i] = (PetscInt)PetscRealPart(array[i]);
    7494:         VecRestoreArrayRead(v,&array);
    7495:         VecDestroy(&v);
    7496:       }
    7497:     } else {
    7498:       MatCreateMPIAdj(subcomm,1,(PetscInt)size,xadj,adjncy,adjncy_wgt,&subdomain_adj);
    7499:       if (use_vwgt) {
    7500:         PetscMalloc1(1,&v_wgt);
    7501:         v_wgt[0] = n;
    7502:       }
    7503:     }
    7504:     /* MatView(subdomain_adj,0); */

    7506:     /* Partition */
    7507:     MatPartitioningCreate(subcomm,&partitioner);
    7508: #if defined(PETSC_HAVE_PTSCOTCH)
    7509:     MatPartitioningSetType(partitioner,MATPARTITIONINGPTSCOTCH);
    7510: #elif defined(PETSC_HAVE_PARMETIS)
    7511:     MatPartitioningSetType(partitioner,MATPARTITIONINGPARMETIS);
    7512: #else
    7513:     MatPartitioningSetType(partitioner,MATPARTITIONINGAVERAGE);
    7514: #endif
    7515:     MatPartitioningSetAdjacency(partitioner,subdomain_adj);
    7516:     if (v_wgt) {
    7517:       MatPartitioningSetVertexWeights(partitioner,v_wgt);
    7518:     }
    7519:     *n_subdomains = PetscMin((PetscInt)size,*n_subdomains);
    7520:     MatPartitioningSetNParts(partitioner,*n_subdomains);
    7521:     MatPartitioningSetFromOptions(partitioner);
    7522:     MatPartitioningApply(partitioner,&new_ranks);
    7523:     /* MatPartitioningView(partitioner,0); */

    7525:     /* renumber new_ranks to avoid "holes" in new set of processors */
    7526:     ISRenumber(new_ranks,NULL,NULL,&new_ranks_contig);
    7527:     ISDestroy(&new_ranks);
    7528:     ISGetIndices(new_ranks_contig,(const PetscInt**)&is_indices);
    7529:     if (!aggregate) {
    7530:       if (procs_candidates) { /* shift the pattern on non-active candidates (if any) */
    7531: #if defined(PETSC_USE_DEBUG)
    7532:         if (!oldranks) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_PLIB,"This should not happen");
    7533: #endif
    7534:         ranks_send_to_idx[0] = procs_candidates[oldranks[is_indices[0]]];
    7535:       } else if (oldranks) {
    7536:         ranks_send_to_idx[0] = oldranks[is_indices[0]];
    7537:       } else {
    7538:         ranks_send_to_idx[0] = is_indices[0];
    7539:       }
    7540:     } else {
    7541:       PetscInt    idx = 0;
    7542:       PetscMPIInt tag;
    7543:       MPI_Request *reqs;

    7545:       PetscObjectGetNewTag((PetscObject)subdomain_adj,&tag);
    7546:       PetscMalloc1(rend-rstart,&reqs);
    7547:       for (i=rstart;i<rend;i++) {
    7548:         MPI_Isend(is_indices+i-rstart,1,MPIU_INT,i,tag,subcomm,&reqs[i-rstart]);
    7549:       }
    7550:       MPI_Recv(&idx,1,MPIU_INT,MPI_ANY_SOURCE,tag,subcomm,MPI_STATUS_IGNORE);
    7551:       MPI_Waitall(rend-rstart,reqs,MPI_STATUSES_IGNORE);
    7552:       PetscFree(reqs);
    7553:       if (procs_candidates) { /* shift the pattern on non-active candidates (if any) */
    7554: #if defined(PETSC_USE_DEBUG)
    7555:         if (!oldranks) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_PLIB,"This should not happen");
    7556: #endif
    7557:         ranks_send_to_idx[0] = procs_candidates[oldranks[idx]];
    7558:       } else if (oldranks) {
    7559:         ranks_send_to_idx[0] = oldranks[idx];
    7560:       } else {
    7561:         ranks_send_to_idx[0] = idx;
    7562:       }
    7563:     }
    7564:     ISRestoreIndices(new_ranks_contig,(const PetscInt**)&is_indices);
    7565:     /* clean up */
    7566:     PetscFree(oldranks);
    7567:     ISDestroy(&new_ranks_contig);
    7568:     MatDestroy(&subdomain_adj);
    7569:     MatPartitioningDestroy(&partitioner);
    7570:   }
    7571:   PetscSubcommDestroy(&psubcomm);
    7572:   PetscFree(procs_candidates);

    7574:   /* assemble parallel IS for sends */
    7575:   i = 1;
    7576:   if (!color) i=0;
    7577:   ISCreateGeneral(PetscObjectComm((PetscObject)mat),i,ranks_send_to_idx,PETSC_OWN_POINTER,is_sends);
    7578:   return(0);
    7579: }

    7581: typedef enum {MATDENSE_PRIVATE=0,MATAIJ_PRIVATE,MATBAIJ_PRIVATE,MATSBAIJ_PRIVATE}MatTypePrivate;

    7583: PetscErrorCode PCBDDCMatISSubassemble(Mat mat, IS is_sends, PetscInt n_subdomains, PetscBool restrict_comm, PetscBool restrict_full, PetscBool reuse, Mat *mat_n, PetscInt nis, IS isarray[], PetscInt nvecs, Vec nnsp_vec[])
    7584: {
    7585:   Mat                    local_mat;
    7586:   IS                     is_sends_internal;
    7587:   PetscInt               rows,cols,new_local_rows;
    7588:   PetscInt               i,bs,buf_size_idxs,buf_size_idxs_is,buf_size_vals,buf_size_vecs;
    7589:   PetscBool              ismatis,isdense,newisdense,destroy_mat;
    7590:   ISLocalToGlobalMapping l2gmap;
    7591:   PetscInt*              l2gmap_indices;
    7592:   const PetscInt*        is_indices;
    7593:   MatType                new_local_type;
    7594:   /* buffers */
    7595:   PetscInt               *ptr_idxs,*send_buffer_idxs,*recv_buffer_idxs;
    7596:   PetscInt               *ptr_idxs_is,*send_buffer_idxs_is,*recv_buffer_idxs_is;
    7597:   PetscInt               *recv_buffer_idxs_local;
    7598:   PetscScalar            *ptr_vals,*recv_buffer_vals;
    7599:   const PetscScalar      *send_buffer_vals;
    7600:   PetscScalar            *ptr_vecs,*send_buffer_vecs,*recv_buffer_vecs;
    7601:   /* MPI */
    7602:   MPI_Comm               comm,comm_n;
    7603:   PetscSubcomm           subcomm;
    7604:   PetscMPIInt            n_sends,n_recvs,size;
    7605:   PetscMPIInt            *iflags,*ilengths_idxs,*ilengths_vals,*ilengths_idxs_is;
    7606:   PetscMPIInt            *onodes,*onodes_is,*olengths_idxs,*olengths_idxs_is,*olengths_vals;
    7607:   PetscMPIInt            len,tag_idxs,tag_idxs_is,tag_vals,tag_vecs,source_dest;
    7608:   MPI_Request            *send_req_idxs,*send_req_idxs_is,*send_req_vals,*send_req_vecs;
    7609:   MPI_Request            *recv_req_idxs,*recv_req_idxs_is,*recv_req_vals,*recv_req_vecs;
    7610:   PetscErrorCode         ierr;

    7614:   PetscObjectTypeCompare((PetscObject)mat,MATIS,&ismatis);
    7615:   if (!ismatis) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Cannot use %s on a matrix object which is not of type MATIS",PETSC_FUNCTION_NAME);
    7622:   if (nvecs) {
    7623:     if (nvecs > 1) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Just 1 vector supported");
    7625:   }
    7626:   /* further checks */
    7627:   MatISGetLocalMat(mat,&local_mat);
    7628:   PetscObjectTypeCompare((PetscObject)local_mat,MATSEQDENSE,&isdense);
    7629:   if (!isdense) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Currently cannot subassemble MATIS when local matrix type is not of type SEQDENSE");
    7630:   MatGetSize(local_mat,&rows,&cols);
    7631:   if (rows != cols) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Local MATIS matrices should be square");
    7632:   if (reuse && *mat_n) {
    7633:     PetscInt mrows,mcols,mnrows,mncols;
    7635:     PetscObjectTypeCompare((PetscObject)*mat_n,MATIS,&ismatis);
    7636:     if (!ismatis) SETERRQ(PetscObjectComm((PetscObject)*mat_n),PETSC_ERR_SUP,"Cannot reuse a matrix which is not of type MATIS");
    7637:     MatGetSize(mat,&mrows,&mcols);
    7638:     MatGetSize(*mat_n,&mnrows,&mncols);
    7639:     if (mrows != mnrows) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Cannot reuse matrix! Wrong number of rows %D != %D",mrows,mnrows);
    7640:     if (mcols != mncols) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Cannot reuse matrix! Wrong number of cols %D != %D",mcols,mncols);
    7641:   }
    7642:   MatGetBlockSize(local_mat,&bs);

    7645:   /* prepare IS for sending if not provided */
    7646:   if (!is_sends) {
    7647:     if (!n_subdomains) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"You should specify either an IS or a target number of subdomains");
    7648:     PCBDDCMatISGetSubassemblingPattern(mat,&n_subdomains,0,&is_sends_internal,NULL);
    7649:   } else {
    7650:     PetscObjectReference((PetscObject)is_sends);
    7651:     is_sends_internal = is_sends;
    7652:   }

    7654:   /* get comm */
    7655:   PetscObjectGetComm((PetscObject)mat,&comm);

    7657:   /* compute number of sends */
    7658:   ISGetLocalSize(is_sends_internal,&i);
    7659:   PetscMPIIntCast(i,&n_sends);

    7661:   /* compute number of receives */
    7662:   MPI_Comm_size(comm,&size);
    7663:   PetscMalloc1(size,&iflags);
    7664:   PetscArrayzero(iflags,size);
    7665:   ISGetIndices(is_sends_internal,&is_indices);
    7666:   for (i=0;i<n_sends;i++) iflags[is_indices[i]] = 1;
    7667:   PetscGatherNumberOfMessages(comm,iflags,NULL,&n_recvs);
    7668:   PetscFree(iflags);

    7670:   /* restrict comm if requested */
    7671:   subcomm = 0;
    7672:   destroy_mat = PETSC_FALSE;
    7673:   if (restrict_comm) {
    7674:     PetscMPIInt color,subcommsize;

    7676:     color = 0;
    7677:     if (restrict_full) {
    7678:       if (!n_recvs) color = 1; /* processes not receiving anything will not partecipate in new comm (full restriction) */
    7679:     } else {
    7680:       if (!n_recvs && n_sends) color = 1; /* just those processes that are sending but not receiving anything will not partecipate in new comm */
    7681:     }
    7682:     MPIU_Allreduce(&color,&subcommsize,1,MPI_INT,MPI_SUM,comm);
    7683:     subcommsize = size - subcommsize;
    7684:     /* check if reuse has been requested */
    7685:     if (reuse) {
    7686:       if (*mat_n) {
    7687:         PetscMPIInt subcommsize2;
    7688:         MPI_Comm_size(PetscObjectComm((PetscObject)*mat_n),&subcommsize2);
    7689:         if (subcommsize != subcommsize2) SETERRQ2(PetscObjectComm((PetscObject)*mat_n),PETSC_ERR_PLIB,"Cannot reuse matrix! wrong subcomm size %d != %d",subcommsize,subcommsize2);
    7690:         comm_n = PetscObjectComm((PetscObject)*mat_n);
    7691:       } else {
    7692:         comm_n = PETSC_COMM_SELF;
    7693:       }
    7694:     } else { /* MAT_INITIAL_MATRIX */
    7695:       PetscMPIInt rank;

    7697:       MPI_Comm_rank(comm,&rank);
    7698:       PetscSubcommCreate(comm,&subcomm);
    7699:       PetscSubcommSetNumber(subcomm,2);
    7700:       PetscSubcommSetTypeGeneral(subcomm,color,rank);
    7701:       comm_n = PetscSubcommChild(subcomm);
    7702:     }
    7703:     /* flag to destroy *mat_n if not significative */
    7704:     if (color) destroy_mat = PETSC_TRUE;
    7705:   } else {
    7706:     comm_n = comm;
    7707:   }

    7709:   /* prepare send/receive buffers */
    7710:   PetscMalloc1(size,&ilengths_idxs);
    7711:   PetscArrayzero(ilengths_idxs,size);
    7712:   PetscMalloc1(size,&ilengths_vals);
    7713:   PetscArrayzero(ilengths_vals,size);
    7714:   if (nis) {
    7715:     PetscCalloc1(size,&ilengths_idxs_is);
    7716:   }

    7718:   /* Get data from local matrices */
    7719:   if (!isdense) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Subassembling of AIJ local matrices not yet implemented");
    7720:     /* TODO: See below some guidelines on how to prepare the local buffers */
    7721:     /*
    7722:        send_buffer_vals should contain the raw values of the local matrix
    7723:        send_buffer_idxs should contain:
    7724:        - MatType_PRIVATE type
    7725:        - PetscInt        size_of_l2gmap
    7726:        - PetscInt        global_row_indices[size_of_l2gmap]
    7727:        - PetscInt        all_other_info_which_is_needed_to_compute_preallocation_and_set_values
    7728:     */
    7729:   else {
    7730:     MatDenseGetArrayRead(local_mat,&send_buffer_vals);
    7731:     ISLocalToGlobalMappingGetSize(mat->rmap->mapping,&i);
    7732:     PetscMalloc1(i+2,&send_buffer_idxs);
    7733:     send_buffer_idxs[0] = (PetscInt)MATDENSE_PRIVATE;
    7734:     send_buffer_idxs[1] = i;
    7735:     ISLocalToGlobalMappingGetIndices(mat->rmap->mapping,(const PetscInt**)&ptr_idxs);
    7736:     PetscArraycpy(&send_buffer_idxs[2],ptr_idxs,i);
    7737:     ISLocalToGlobalMappingRestoreIndices(mat->rmap->mapping,(const PetscInt**)&ptr_idxs);
    7738:     PetscMPIIntCast(i,&len);
    7739:     for (i=0;i<n_sends;i++) {
    7740:       ilengths_vals[is_indices[i]] = len*len;
    7741:       ilengths_idxs[is_indices[i]] = len+2;
    7742:     }
    7743:   }
    7744:   PetscGatherMessageLengths2(comm,n_sends,n_recvs,ilengths_idxs,ilengths_vals,&onodes,&olengths_idxs,&olengths_vals);
    7745:   /* additional is (if any) */
    7746:   if (nis) {
    7747:     PetscMPIInt psum;
    7748:     PetscInt j;
    7749:     for (j=0,psum=0;j<nis;j++) {
    7750:       PetscInt plen;
    7751:       ISGetLocalSize(isarray[j],&plen);
    7752:       PetscMPIIntCast(plen,&len);
    7753:       psum += len+1; /* indices + lenght */
    7754:     }
    7755:     PetscMalloc1(psum,&send_buffer_idxs_is);
    7756:     for (j=0,psum=0;j<nis;j++) {
    7757:       PetscInt plen;
    7758:       const PetscInt *is_array_idxs;
    7759:       ISGetLocalSize(isarray[j],&plen);
    7760:       send_buffer_idxs_is[psum] = plen;
    7761:       ISGetIndices(isarray[j],&is_array_idxs);
    7762:       PetscArraycpy(&send_buffer_idxs_is[psum+1],is_array_idxs,plen);
    7763:       ISRestoreIndices(isarray[j],&is_array_idxs);
    7764:       psum += plen+1; /* indices + lenght */
    7765:     }
    7766:     for (i=0;i<n_sends;i++) {
    7767:       ilengths_idxs_is[is_indices[i]] = psum;
    7768:     }
    7769:     PetscGatherMessageLengths(comm,n_sends,n_recvs,ilengths_idxs_is,&onodes_is,&olengths_idxs_is);
    7770:   }
    7771:   MatISRestoreLocalMat(mat,&local_mat);

    7773:   buf_size_idxs = 0;
    7774:   buf_size_vals = 0;
    7775:   buf_size_idxs_is = 0;
    7776:   buf_size_vecs = 0;
    7777:   for (i=0;i<n_recvs;i++) {
    7778:     buf_size_idxs += (PetscInt)olengths_idxs[i];
    7779:     buf_size_vals += (PetscInt)olengths_vals[i];
    7780:     if (nis) buf_size_idxs_is += (PetscInt)olengths_idxs_is[i];
    7781:     if (nvecs) buf_size_vecs += (PetscInt)olengths_idxs[i];
    7782:   }
    7783:   PetscMalloc1(buf_size_idxs,&recv_buffer_idxs);
    7784:   PetscMalloc1(buf_size_vals,&recv_buffer_vals);
    7785:   PetscMalloc1(buf_size_idxs_is,&recv_buffer_idxs_is);
    7786:   PetscMalloc1(buf_size_vecs,&recv_buffer_vecs);

    7788:   /* get new tags for clean communications */
    7789:   PetscObjectGetNewTag((PetscObject)mat,&tag_idxs);
    7790:   PetscObjectGetNewTag((PetscObject)mat,&tag_vals);
    7791:   PetscObjectGetNewTag((PetscObject)mat,&tag_idxs_is);
    7792:   PetscObjectGetNewTag((PetscObject)mat,&tag_vecs);

    7794:   /* allocate for requests */
    7795:   PetscMalloc1(n_sends,&send_req_idxs);
    7796:   PetscMalloc1(n_sends,&send_req_vals);
    7797:   PetscMalloc1(n_sends,&send_req_idxs_is);
    7798:   PetscMalloc1(n_sends,&send_req_vecs);
    7799:   PetscMalloc1(n_recvs,&recv_req_idxs);
    7800:   PetscMalloc1(n_recvs,&recv_req_vals);
    7801:   PetscMalloc1(n_recvs,&recv_req_idxs_is);
    7802:   PetscMalloc1(n_recvs,&recv_req_vecs);

    7804:   /* communications */
    7805:   ptr_idxs = recv_buffer_idxs;
    7806:   ptr_vals = recv_buffer_vals;
    7807:   ptr_idxs_is = recv_buffer_idxs_is;
    7808:   ptr_vecs = recv_buffer_vecs;
    7809:   for (i=0;i<n_recvs;i++) {
    7810:     source_dest = onodes[i];
    7811:     MPI_Irecv(ptr_idxs,olengths_idxs[i],MPIU_INT,source_dest,tag_idxs,comm,&recv_req_idxs[i]);
    7812:     MPI_Irecv(ptr_vals,olengths_vals[i],MPIU_SCALAR,source_dest,tag_vals,comm,&recv_req_vals[i]);
    7813:     ptr_idxs += olengths_idxs[i];
    7814:     ptr_vals += olengths_vals[i];
    7815:     if (nis) {
    7816:       source_dest = onodes_is[i];
    7817:       MPI_Irecv(ptr_idxs_is,olengths_idxs_is[i],MPIU_INT,source_dest,tag_idxs_is,comm,&recv_req_idxs_is[i]);
    7818:       ptr_idxs_is += olengths_idxs_is[i];
    7819:     }
    7820:     if (nvecs) {
    7821:       source_dest = onodes[i];
    7822:       MPI_Irecv(ptr_vecs,olengths_idxs[i]-2,MPIU_SCALAR,source_dest,tag_vecs,comm,&recv_req_vecs[i]);
    7823:       ptr_vecs += olengths_idxs[i]-2;
    7824:     }
    7825:   }
    7826:   for (i=0;i<n_sends;i++) {
    7827:     PetscMPIIntCast(is_indices[i],&source_dest);
    7828:     MPI_Isend(send_buffer_idxs,ilengths_idxs[source_dest],MPIU_INT,source_dest,tag_idxs,comm,&send_req_idxs[i]);
    7829:     MPI_Isend((PetscScalar*)send_buffer_vals,ilengths_vals[source_dest],MPIU_SCALAR,source_dest,tag_vals,comm,&send_req_vals[i]);
    7830:     if (nis) {
    7831:       MPI_Isend(send_buffer_idxs_is,ilengths_idxs_is[source_dest],MPIU_INT,source_dest,tag_idxs_is,comm,&send_req_idxs_is[i]);
    7832:     }
    7833:     if (nvecs) {
    7834:       VecGetArray(nnsp_vec[0],&send_buffer_vecs);
    7835:       MPI_Isend(send_buffer_vecs,ilengths_idxs[source_dest]-2,MPIU_SCALAR,source_dest,tag_vecs,comm,&send_req_vecs[i]);
    7836:     }
    7837:   }
    7838:   ISRestoreIndices(is_sends_internal,&is_indices);
    7839:   ISDestroy(&is_sends_internal);

    7841:   /* assemble new l2g map */
    7842:   MPI_Waitall(n_recvs,recv_req_idxs,MPI_STATUSES_IGNORE);
    7843:   ptr_idxs = recv_buffer_idxs;
    7844:   new_local_rows = 0;
    7845:   for (i=0;i<n_recvs;i++) {
    7846:     new_local_rows += *(ptr_idxs+1); /* second element is the local size of the l2gmap */
    7847:     ptr_idxs += olengths_idxs[i];
    7848:   }
    7849:   PetscMalloc1(new_local_rows,&l2gmap_indices);
    7850:   ptr_idxs = recv_buffer_idxs;
    7851:   new_local_rows = 0;
    7852:   for (i=0;i<n_recvs;i++) {
    7853:     PetscArraycpy(&l2gmap_indices[new_local_rows],ptr_idxs+2,*(ptr_idxs+1));
    7854:     new_local_rows += *(ptr_idxs+1); /* second element is the local size of the l2gmap */
    7855:     ptr_idxs += olengths_idxs[i];
    7856:   }
    7857:   PetscSortRemoveDupsInt(&new_local_rows,l2gmap_indices);
    7858:   ISLocalToGlobalMappingCreate(comm_n,1,new_local_rows,l2gmap_indices,PETSC_COPY_VALUES,&l2gmap);
    7859:   PetscFree(l2gmap_indices);

    7861:   /* infer new local matrix type from received local matrices type */
    7862:   /* currently if all local matrices are of type X, then the resulting matrix will be of type X, except for the dense case */
    7863:   /* it also assumes that if the block size is set, than it is the same among all local matrices (see checks at the beginning of the function) */
    7864:   if (n_recvs) {
    7865:     MatTypePrivate new_local_type_private = (MatTypePrivate)send_buffer_idxs[0];
    7866:     ptr_idxs = recv_buffer_idxs;
    7867:     for (i=0;i<n_recvs;i++) {
    7868:       if ((PetscInt)new_local_type_private != *ptr_idxs) {
    7869:         new_local_type_private = MATAIJ_PRIVATE;
    7870:         break;
    7871:       }
    7872:       ptr_idxs += olengths_idxs[i];
    7873:     }
    7874:     switch (new_local_type_private) {
    7875:       case MATDENSE_PRIVATE:
    7876:         new_local_type = MATSEQAIJ;
    7877:         bs = 1;
    7878:         break;
    7879:       case MATAIJ_PRIVATE:
    7880:         new_local_type = MATSEQAIJ;
    7881:         bs = 1;
    7882:         break;
    7883:       case MATBAIJ_PRIVATE:
    7884:         new_local_type = MATSEQBAIJ;
    7885:         break;
    7886:       case MATSBAIJ_PRIVATE:
    7887:         new_local_type = MATSEQSBAIJ;
    7888:         break;
    7889:       default:
    7890:         SETERRQ2(comm,PETSC_ERR_SUP,"Unsupported private type %d in %s",new_local_type_private,PETSC_FUNCTION_NAME);
    7891:         break;
    7892:     }
    7893:   } else { /* by default, new_local_type is seqaij */
    7894:     new_local_type = MATSEQAIJ;
    7895:     bs = 1;
    7896:   }

    7898:   /* create MATIS object if needed */
    7899:   if (!reuse) {
    7900:     MatGetSize(mat,&rows,&cols);
    7901:     MatCreateIS(comm_n,bs,PETSC_DECIDE,PETSC_DECIDE,rows,cols,l2gmap,NULL,mat_n);
    7902:   } else {
    7903:     /* it also destroys the local matrices */
    7904:     if (*mat_n) {
    7905:       MatSetLocalToGlobalMapping(*mat_n,l2gmap,l2gmap);
    7906:     } else { /* this is a fake object */
    7907:       MatCreateIS(comm_n,bs,PETSC_DECIDE,PETSC_DECIDE,rows,cols,l2gmap,NULL,mat_n);
    7908:     }
    7909:   }
    7910:   MatISGetLocalMat(*mat_n,&local_mat);
    7911:   MatSetType(local_mat,new_local_type);

    7913:   MPI_Waitall(n_recvs,recv_req_vals,MPI_STATUSES_IGNORE);

    7915:   /* Global to local map of received indices */
    7916:   PetscMalloc1(buf_size_idxs,&recv_buffer_idxs_local); /* needed for values insertion */
    7917:   ISGlobalToLocalMappingApply(l2gmap,IS_GTOLM_MASK,buf_size_idxs,recv_buffer_idxs,&i,recv_buffer_idxs_local);
    7918:   ISLocalToGlobalMappingDestroy(&l2gmap);

    7920:   /* restore attributes -> type of incoming data and its size */
    7921:   buf_size_idxs = 0;
    7922:   for (i=0;i<n_recvs;i++) {
    7923:     recv_buffer_idxs_local[buf_size_idxs] = recv_buffer_idxs[buf_size_idxs];
    7924:     recv_buffer_idxs_local[buf_size_idxs+1] = recv_buffer_idxs[buf_size_idxs+1];
    7925:     buf_size_idxs += (PetscInt)olengths_idxs[i];
    7926:   }
    7927:   PetscFree(recv_buffer_idxs);

    7929:   /* set preallocation */
    7930:   PetscObjectTypeCompare((PetscObject)local_mat,MATSEQDENSE,&newisdense);
    7931:   if (!newisdense) {
    7932:     PetscInt *new_local_nnz=0;

    7934:     ptr_idxs = recv_buffer_idxs_local;
    7935:     if (n_recvs) {
    7936:       PetscCalloc1(new_local_rows,&new_local_nnz);
    7937:     }
    7938:     for (i=0;i<n_recvs;i++) {
    7939:       PetscInt j;
    7940:       if (*ptr_idxs == (PetscInt)MATDENSE_PRIVATE) { /* preallocation provided for dense case only */
    7941:         for (j=0;j<*(ptr_idxs+1);j++) {
    7942:           new_local_nnz[*(ptr_idxs+2+j)] += *(ptr_idxs+1);
    7943:         }
    7944:       } else {
    7945:         /* TODO */
    7946:       }
    7947:       ptr_idxs += olengths_idxs[i];
    7948:     }
    7949:     if (new_local_nnz) {
    7950:       for (i=0;i<new_local_rows;i++) new_local_nnz[i] = PetscMin(new_local_nnz[i],new_local_rows);
    7951:       MatSeqAIJSetPreallocation(local_mat,0,new_local_nnz);
    7952:       for (i=0;i<new_local_rows;i++) new_local_nnz[i] /= bs;
    7953:       MatSeqBAIJSetPreallocation(local_mat,bs,0,new_local_nnz);
    7954:       for (i=0;i<new_local_rows;i++) new_local_nnz[i] = PetscMax(new_local_nnz[i]-i,0);
    7955:       MatSeqSBAIJSetPreallocation(local_mat,bs,0,new_local_nnz);
    7956:     } else {
    7957:       MatSetUp(local_mat);
    7958:     }
    7959:     PetscFree(new_local_nnz);
    7960:   } else {
    7961:     MatSetUp(local_mat);
    7962:   }

    7964:   /* set values */
    7965:   ptr_vals = recv_buffer_vals;
    7966:   ptr_idxs = recv_buffer_idxs_local;
    7967:   for (i=0;i<n_recvs;i++) {
    7968:     if (*ptr_idxs == (PetscInt)MATDENSE_PRIVATE) { /* values insertion provided for dense case only */
    7969:       MatSetOption(local_mat,MAT_ROW_ORIENTED,PETSC_FALSE);
    7970:       MatSetValues(local_mat,*(ptr_idxs+1),ptr_idxs+2,*(ptr_idxs+1),ptr_idxs+2,ptr_vals,ADD_VALUES);
    7971:       MatAssemblyBegin(local_mat,MAT_FLUSH_ASSEMBLY);
    7972:       MatAssemblyEnd(local_mat,MAT_FLUSH_ASSEMBLY);
    7973:       MatSetOption(local_mat,MAT_ROW_ORIENTED,PETSC_TRUE);
    7974:     } else {
    7975:       /* TODO */
    7976:     }
    7977:     ptr_idxs += olengths_idxs[i];
    7978:     ptr_vals += olengths_vals[i];
    7979:   }
    7980:   MatAssemblyBegin(local_mat,MAT_FINAL_ASSEMBLY);
    7981:   MatAssemblyEnd(local_mat,MAT_FINAL_ASSEMBLY);
    7982:   MatISRestoreLocalMat(*mat_n,&local_mat);
    7983:   MatAssemblyBegin(*mat_n,MAT_FINAL_ASSEMBLY);
    7984:   MatAssemblyEnd(*mat_n,MAT_FINAL_ASSEMBLY);
    7985:   PetscFree(recv_buffer_vals);

    7987: #if 0
    7988:   if (!restrict_comm) { /* check */
    7989:     Vec       lvec,rvec;
    7990:     PetscReal infty_error;

    7992:     MatCreateVecs(mat,&rvec,&lvec);
    7993:     VecSetRandom(rvec,NULL);
    7994:     MatMult(mat,rvec,lvec);
    7995:     VecScale(lvec,-1.0);
    7996:     MatMultAdd(*mat_n,rvec,lvec,lvec);
    7997:     VecNorm(lvec,NORM_INFINITY,&infty_error);
    7998:     PetscPrintf(PetscObjectComm((PetscObject)mat),"Infinity error subassembling %1.6e\n",infty_error);
    7999:     VecDestroy(&rvec);
    8000:     VecDestroy(&lvec);
    8001:   }
    8002: #endif

    8004:   /* assemble new additional is (if any) */
    8005:   if (nis) {
    8006:     PetscInt **temp_idxs,*count_is,j,psum;

    8008:     MPI_Waitall(n_recvs,recv_req_idxs_is,MPI_STATUSES_IGNORE);
    8009:     PetscCalloc1(nis,&count_is);
    8010:     ptr_idxs = recv_buffer_idxs_is;
    8011:     psum = 0;
    8012:     for (i=0;i<n_recvs;i++) {
    8013:       for (j=0;j<nis;j++) {
    8014:         PetscInt plen = *(ptr_idxs); /* first element is the local size of IS's indices */
    8015:         count_is[j] += plen; /* increment counting of buffer for j-th IS */
    8016:         psum += plen;
    8017:         ptr_idxs += plen+1; /* shift pointer to received data */
    8018:       }
    8019:     }
    8020:     PetscMalloc1(nis,&temp_idxs);
    8021:     PetscMalloc1(psum,&temp_idxs[0]);
    8022:     for (i=1;i<nis;i++) {
    8023:       temp_idxs[i] = temp_idxs[i-1]+count_is[i-1];
    8024:     }
    8025:     PetscArrayzero(count_is,nis);
    8026:     ptr_idxs = recv_buffer_idxs_is;
    8027:     for (i=0;i<n_recvs;i++) {
    8028:       for (j=0;j<nis;j++) {
    8029:         PetscInt plen = *(ptr_idxs); /* first element is the local size of IS's indices */
    8030:         PetscArraycpy(&temp_idxs[j][count_is[j]],ptr_idxs+1,plen);
    8031:         count_is[j] += plen; /* increment starting point of buffer for j-th IS */
    8032:         ptr_idxs += plen+1; /* shift pointer to received data */
    8033:       }
    8034:     }
    8035:     for (i=0;i<nis;i++) {
    8036:       ISDestroy(&isarray[i]);
    8037:       PetscSortRemoveDupsInt(&count_is[i],temp_idxs[i]);
    8038:       ISCreateGeneral(comm_n,count_is[i],temp_idxs[i],PETSC_COPY_VALUES,&isarray[i]);
    8039:     }
    8040:     PetscFree(count_is);
    8041:     PetscFree(temp_idxs[0]);
    8042:     PetscFree(temp_idxs);
    8043:   }
    8044:   /* free workspace */
    8045:   PetscFree(recv_buffer_idxs_is);
    8046:   MPI_Waitall(n_sends,send_req_idxs,MPI_STATUSES_IGNORE);
    8047:   PetscFree(send_buffer_idxs);
    8048:   MPI_Waitall(n_sends,send_req_vals,MPI_STATUSES_IGNORE);
    8049:   if (isdense) {
    8050:     MatISGetLocalMat(mat,&local_mat);
    8051:     MatDenseRestoreArrayRead(local_mat,&send_buffer_vals);
    8052:     MatISRestoreLocalMat(mat,&local_mat);
    8053:   } else {
    8054:     /* PetscFree(send_buffer_vals); */
    8055:   }
    8056:   if (nis) {
    8057:     MPI_Waitall(n_sends,send_req_idxs_is,MPI_STATUSES_IGNORE);
    8058:     PetscFree(send_buffer_idxs_is);
    8059:   }

    8061:   if (nvecs) {
    8062:     MPI_Waitall(n_recvs,recv_req_vecs,MPI_STATUSES_IGNORE);
    8063:     MPI_Waitall(n_sends,send_req_vecs,MPI_STATUSES_IGNORE);
    8064:     VecRestoreArray(nnsp_vec[0],&send_buffer_vecs);
    8065:     VecDestroy(&nnsp_vec[0]);
    8066:     VecCreate(comm_n,&nnsp_vec[0]);
    8067:     VecSetSizes(nnsp_vec[0],new_local_rows,PETSC_DECIDE);
    8068:     VecSetType(nnsp_vec[0],VECSTANDARD);
    8069:     /* set values */
    8070:     ptr_vals = recv_buffer_vecs;
    8071:     ptr_idxs = recv_buffer_idxs_local;
    8072:     VecGetArray(nnsp_vec[0],&send_buffer_vecs);
    8073:     for (i=0;i<n_recvs;i++) {
    8074:       PetscInt j;
    8075:       for (j=0;j<*(ptr_idxs+1);j++) {
    8076:         send_buffer_vecs[*(ptr_idxs+2+j)] += *(ptr_vals + j);
    8077:       }
    8078:       ptr_idxs += olengths_idxs[i];
    8079:       ptr_vals += olengths_idxs[i]-2;
    8080:     }
    8081:     VecRestoreArray(nnsp_vec[0],&send_buffer_vecs);
    8082:     VecAssemblyBegin(nnsp_vec[0]);
    8083:     VecAssemblyEnd(nnsp_vec[0]);
    8084:   }

    8086:   PetscFree(recv_buffer_vecs);
    8087:   PetscFree(recv_buffer_idxs_local);
    8088:   PetscFree(recv_req_idxs);
    8089:   PetscFree(recv_req_vals);
    8090:   PetscFree(recv_req_vecs);
    8091:   PetscFree(recv_req_idxs_is);
    8092:   PetscFree(send_req_idxs);
    8093:   PetscFree(send_req_vals);
    8094:   PetscFree(send_req_vecs);
    8095:   PetscFree(send_req_idxs_is);
    8096:   PetscFree(ilengths_vals);
    8097:   PetscFree(ilengths_idxs);
    8098:   PetscFree(olengths_vals);
    8099:   PetscFree(olengths_idxs);
    8100:   PetscFree(onodes);
    8101:   if (nis) {
    8102:     PetscFree(ilengths_idxs_is);
    8103:     PetscFree(olengths_idxs_is);
    8104:     PetscFree(onodes_is);
    8105:   }
    8106:   PetscSubcommDestroy(&subcomm);
    8107:   if (destroy_mat) { /* destroy mat is true only if restrict comm is true and process will not partecipate */
    8108:     MatDestroy(mat_n);
    8109:     for (i=0;i<nis;i++) {
    8110:       ISDestroy(&isarray[i]);
    8111:     }
    8112:     if (nvecs) { /* need to match VecDestroy nnsp_vec called in the other code path */
    8113:       VecDestroy(&nnsp_vec[0]);
    8114:     }
    8115:     *mat_n = NULL;
    8116:   }
    8117:   return(0);
    8118: }

    8120: /* temporary hack into ksp private data structure */
    8121:  #include <petsc/private/kspimpl.h>

    8123: PetscErrorCode PCBDDCSetUpCoarseSolver(PC pc,PetscScalar* coarse_submat_vals)
    8124: {
    8125:   PC_BDDC                *pcbddc = (PC_BDDC*)pc->data;
    8126:   PC_IS                  *pcis = (PC_IS*)pc->data;
    8127:   Mat                    coarse_mat,coarse_mat_is,coarse_submat_dense;
    8128:   Mat                    coarsedivudotp = NULL;
    8129:   Mat                    coarseG,t_coarse_mat_is;
    8130:   MatNullSpace           CoarseNullSpace = NULL;
    8131:   ISLocalToGlobalMapping coarse_islg;
    8132:   IS                     coarse_is,*isarray,corners;
    8133:   PetscInt               i,im_active=-1,active_procs=-1;
    8134:   PetscInt               nis,nisdofs,nisneu,nisvert;
    8135:   PetscInt               coarse_eqs_per_proc;
    8136:   PC                     pc_temp;
    8137:   PCType                 coarse_pc_type;
    8138:   KSPType                coarse_ksp_type;
    8139:   PetscBool              multilevel_requested,multilevel_allowed;
    8140:   PetscBool              coarse_reuse;
    8141:   PetscInt               ncoarse,nedcfield;
    8142:   PetscBool              compute_vecs = PETSC_FALSE;
    8143:   PetscScalar            *array;
    8144:   MatReuse               coarse_mat_reuse;
    8145:   PetscBool              restr, full_restr, have_void;
    8146:   PetscMPIInt            size;
    8147:   PetscErrorCode         ierr;

    8150:   PetscLogEventBegin(PC_BDDC_CoarseSetUp[pcbddc->current_level],pc,0,0,0);
    8151:   /* Assign global numbering to coarse dofs */
    8152:   if (pcbddc->new_primal_space || pcbddc->coarse_size == -1) { /* a new primal space is present or it is the first initialization, so recompute global numbering */
    8153:     PetscInt ocoarse_size;
    8154:     compute_vecs = PETSC_TRUE;

    8156:     pcbddc->new_primal_space = PETSC_TRUE;
    8157:     ocoarse_size = pcbddc->coarse_size;
    8158:     PetscFree(pcbddc->global_primal_indices);
    8159:     PCBDDCComputePrimalNumbering(pc,&pcbddc->coarse_size,&pcbddc->global_primal_indices);
    8160:     /* see if we can avoid some work */
    8161:     if (pcbddc->coarse_ksp) { /* coarse ksp has already been created */
    8162:       /* if the coarse size is different or we are using adaptive selection, better to not reuse the coarse matrix */
    8163:       if (ocoarse_size != pcbddc->coarse_size || pcbddc->adaptive_selection) {
    8164:         KSPReset(pcbddc->coarse_ksp);
    8165:         coarse_reuse = PETSC_FALSE;
    8166:       } else { /* we can safely reuse already computed coarse matrix */
    8167:         coarse_reuse = PETSC_TRUE;
    8168:       }
    8169:     } else { /* there's no coarse ksp, so we need to create the coarse matrix too */
    8170:       coarse_reuse = PETSC_FALSE;
    8171:     }
    8172:     /* reset any subassembling information */
    8173:     if (!coarse_reuse || pcbddc->recompute_topography) {
    8174:       ISDestroy(&pcbddc->coarse_subassembling);
    8175:     }
    8176:   } else { /* primal space is unchanged, so we can reuse coarse matrix */
    8177:     coarse_reuse = PETSC_TRUE;
    8178:   }
    8179:   if (coarse_reuse && pcbddc->coarse_ksp) {
    8180:     KSPGetOperators(pcbddc->coarse_ksp,&coarse_mat,NULL);
    8181:     PetscObjectReference((PetscObject)coarse_mat);
    8182:     coarse_mat_reuse = MAT_REUSE_MATRIX;
    8183:   } else {
    8184:     coarse_mat = NULL;
    8185:     coarse_mat_reuse = MAT_INITIAL_MATRIX;
    8186:   }

    8188:   /* creates temporary l2gmap and IS for coarse indexes */
    8189:   ISCreateGeneral(PetscObjectComm((PetscObject)pc),pcbddc->local_primal_size,pcbddc->global_primal_indices,PETSC_COPY_VALUES,&coarse_is);
    8190:   ISLocalToGlobalMappingCreateIS(coarse_is,&coarse_islg);

    8192:   /* creates temporary MATIS object for coarse matrix */
    8193:   MatCreateSeqDense(PETSC_COMM_SELF,pcbddc->local_primal_size,pcbddc->local_primal_size,coarse_submat_vals,&coarse_submat_dense);
    8194:   MatCreateIS(PetscObjectComm((PetscObject)pc),1,PETSC_DECIDE,PETSC_DECIDE,pcbddc->coarse_size,pcbddc->coarse_size,coarse_islg,NULL,&t_coarse_mat_is);
    8195:   MatISSetLocalMat(t_coarse_mat_is,coarse_submat_dense);
    8196:   MatAssemblyBegin(t_coarse_mat_is,MAT_FINAL_ASSEMBLY);
    8197:   MatAssemblyEnd(t_coarse_mat_is,MAT_FINAL_ASSEMBLY);
    8198:   MatDestroy(&coarse_submat_dense);

    8200:   /* count "active" (i.e. with positive local size) and "void" processes */
    8201:   im_active = !!(pcis->n);
    8202:   MPIU_Allreduce(&im_active,&active_procs,1,MPIU_INT,MPI_SUM,PetscObjectComm((PetscObject)pc));

    8204:   /* determine number of processes partecipating to coarse solver and compute subassembling pattern */
    8205:   /* restr : whether we want to exclude senders (which are not receivers) from the subassembling pattern */
    8206:   /* full_restr : just use the receivers from the subassembling pattern */
    8207:   MPI_Comm_size(PetscObjectComm((PetscObject)pc),&size);
    8208:   coarse_mat_is        = NULL;
    8209:   multilevel_allowed   = PETSC_FALSE;
    8210:   multilevel_requested = PETSC_FALSE;
    8211:   coarse_eqs_per_proc  = PetscMin(PetscMax(pcbddc->coarse_size,1),pcbddc->coarse_eqs_per_proc);
    8212:   if (coarse_eqs_per_proc < 0) coarse_eqs_per_proc = pcbddc->coarse_size;
    8213:   if (pcbddc->current_level < pcbddc->max_levels) multilevel_requested = PETSC_TRUE;
    8214:   if (pcbddc->coarse_size <= pcbddc->coarse_eqs_limit) multilevel_requested = PETSC_FALSE;
    8215:   if (multilevel_requested) {
    8216:     ncoarse    = active_procs/pcbddc->coarsening_ratio;
    8217:     restr      = PETSC_FALSE;
    8218:     full_restr = PETSC_FALSE;
    8219:   } else {
    8220:     ncoarse    = pcbddc->coarse_size/coarse_eqs_per_proc + !!(pcbddc->coarse_size%coarse_eqs_per_proc);
    8221:     restr      = PETSC_TRUE;
    8222:     full_restr = PETSC_TRUE;
    8223:   }
    8224:   if (!pcbddc->coarse_size || size == 1) multilevel_allowed = multilevel_requested = restr = full_restr = PETSC_FALSE;
    8225:   ncoarse = PetscMax(1,ncoarse);
    8226:   if (!pcbddc->coarse_subassembling) {
    8227:     if (pcbddc->coarsening_ratio > 1) {
    8228:       if (multilevel_requested) {
    8229:         PCBDDCMatISGetSubassemblingPattern(pc->pmat,&ncoarse,pcbddc->coarse_adj_red,&pcbddc->coarse_subassembling,&have_void);
    8230:       } else {
    8231:         PCBDDCMatISGetSubassemblingPattern(t_coarse_mat_is,&ncoarse,pcbddc->coarse_adj_red,&pcbddc->coarse_subassembling,&have_void);
    8232:       }
    8233:     } else {
    8234:       PetscMPIInt rank;

    8236:       MPI_Comm_rank(PetscObjectComm((PetscObject)pc),&rank);
    8237:       have_void = (active_procs == (PetscInt)size) ? PETSC_FALSE : PETSC_TRUE;
    8238:       ISCreateStride(PetscObjectComm((PetscObject)pc),1,rank,1,&pcbddc->coarse_subassembling);
    8239:     }
    8240:   } else { /* if a subassembling pattern exists, then we can reuse the coarse ksp and compute the number of process involved */
    8241:     PetscInt    psum;
    8242:     if (pcbddc->coarse_ksp) psum = 1;
    8243:     else psum = 0;
    8244:     MPIU_Allreduce(&psum,&ncoarse,1,MPIU_INT,MPI_SUM,PetscObjectComm((PetscObject)pc));
    8245:     have_void = ncoarse < size ? PETSC_TRUE : PETSC_FALSE;
    8246:   }
    8247:   /* determine if we can go multilevel */
    8248:   if (multilevel_requested) {
    8249:     if (ncoarse > 1) multilevel_allowed = PETSC_TRUE; /* found enough processes */
    8250:     else restr = full_restr = PETSC_TRUE; /* 1 subdomain, use a direct solver */
    8251:   }
    8252:   if (multilevel_allowed && have_void) restr = PETSC_TRUE;

    8254:   /* dump subassembling pattern */
    8255:   if (pcbddc->dbg_flag && multilevel_allowed) {
    8256:     ISView(pcbddc->coarse_subassembling,pcbddc->dbg_viewer);
    8257:   }
    8258:   /* compute dofs splitting and neumann boundaries for coarse dofs */
    8259:   nedcfield = -1;
    8260:   corners = NULL;
    8261:   if (multilevel_allowed && !coarse_reuse && (pcbddc->n_ISForDofsLocal || pcbddc->NeumannBoundariesLocal || pcbddc->nedclocal || pcbddc->corner_selected)) { /* protects from unneeded computations */
    8262:     PetscInt               *tidxs,*tidxs2,nout,tsize,i;
    8263:     const PetscInt         *idxs;
    8264:     ISLocalToGlobalMapping tmap;

    8266:     /* create map between primal indices (in local representative ordering) and local primal numbering */
    8267:     ISLocalToGlobalMappingCreate(PETSC_COMM_SELF,1,pcbddc->local_primal_size,pcbddc->primal_indices_local_idxs,PETSC_COPY_VALUES,&tmap);
    8268:     /* allocate space for temporary storage */
    8269:     PetscMalloc1(pcbddc->local_primal_size,&tidxs);
    8270:     PetscMalloc1(pcbddc->local_primal_size,&tidxs2);
    8271:     /* allocate for IS array */
    8272:     nisdofs = pcbddc->n_ISForDofsLocal;
    8273:     if (pcbddc->nedclocal) {
    8274:       if (pcbddc->nedfield > -1) {
    8275:         nedcfield = pcbddc->nedfield;
    8276:       } else {
    8277:         nedcfield = 0;
    8278:         if (nisdofs) SETERRQ1(PetscObjectComm((PetscObject)pc),PETSC_ERR_PLIB,"This should not happen (%D)",nisdofs);
    8279:         nisdofs = 1;
    8280:       }
    8281:     }
    8282:     nisneu = !!pcbddc->NeumannBoundariesLocal;
    8283:     nisvert = 0; /* nisvert is not used */
    8284:     nis = nisdofs + nisneu + nisvert;
    8285:     PetscMalloc1(nis,&isarray);
    8286:     /* dofs splitting */
    8287:     for (i=0;i<nisdofs;i++) {
    8288:       /* ISView(pcbddc->ISForDofsLocal[i],0); */
    8289:       if (nedcfield != i) {
    8290:         ISGetLocalSize(pcbddc->ISForDofsLocal[i],&tsize);
    8291:         ISGetIndices(pcbddc->ISForDofsLocal[i],&idxs);
    8292:         ISGlobalToLocalMappingApply(tmap,IS_GTOLM_DROP,tsize,idxs,&nout,tidxs);
    8293:         ISRestoreIndices(pcbddc->ISForDofsLocal[i],&idxs);
    8294:       } else {
    8295:         ISGetLocalSize(pcbddc->nedclocal,&tsize);
    8296:         ISGetIndices(pcbddc->nedclocal,&idxs);
    8297:         ISGlobalToLocalMappingApply(tmap,IS_GTOLM_DROP,tsize,idxs,&nout,tidxs);
    8298:         if (tsize != nout) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_PLIB,"Failed when mapping coarse nedelec field! %D != %D",tsize,nout);
    8299:         ISRestoreIndices(pcbddc->nedclocal,&idxs);
    8300:       }
    8301:       ISLocalToGlobalMappingApply(coarse_islg,nout,tidxs,tidxs2);
    8302:       ISCreateGeneral(PetscObjectComm((PetscObject)pc),nout,tidxs2,PETSC_COPY_VALUES,&isarray[i]);
    8303:       /* ISView(isarray[i],0); */
    8304:     }
    8305:     /* neumann boundaries */
    8306:     if (pcbddc->NeumannBoundariesLocal) {
    8307:       /* ISView(pcbddc->NeumannBoundariesLocal,0); */
    8308:       ISGetLocalSize(pcbddc->NeumannBoundariesLocal,&tsize);
    8309:       ISGetIndices(pcbddc->NeumannBoundariesLocal,&idxs);
    8310:       ISGlobalToLocalMappingApply(tmap,IS_GTOLM_DROP,tsize,idxs,&nout,tidxs);
    8311:       ISRestoreIndices(pcbddc->NeumannBoundariesLocal,&idxs);
    8312:       ISLocalToGlobalMappingApply(coarse_islg,nout,tidxs,tidxs2);
    8313:       ISCreateGeneral(PetscObjectComm((PetscObject)pc),nout,tidxs2,PETSC_COPY_VALUES,&isarray[nisdofs]);
    8314:       /* ISView(isarray[nisdofs],0); */
    8315:     }
    8316:     /* coordinates */
    8317:     if (pcbddc->corner_selected) {
    8318:       PCBDDCGraphGetCandidatesIS(pcbddc->mat_graph,NULL,NULL,NULL,NULL,&corners);
    8319:       ISGetLocalSize(corners,&tsize);
    8320:       ISGetIndices(corners,&idxs);
    8321:       ISGlobalToLocalMappingApply(tmap,IS_GTOLM_DROP,tsize,idxs,&nout,tidxs);
    8322:       if (tsize != nout) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_PLIB,"Failed when mapping corners! %D != %D",tsize,nout);
    8323:       ISRestoreIndices(corners,&idxs);
    8324:       PCBDDCGraphRestoreCandidatesIS(pcbddc->mat_graph,NULL,NULL,NULL,NULL,&corners);
    8325:       ISLocalToGlobalMappingApply(coarse_islg,nout,tidxs,tidxs2);
    8326:       ISCreateGeneral(PetscObjectComm((PetscObject)pc),nout,tidxs2,PETSC_COPY_VALUES,&corners);
    8327:     }
    8328:     PetscFree(tidxs);
    8329:     PetscFree(tidxs2);
    8330:     ISLocalToGlobalMappingDestroy(&tmap);
    8331:   } else {
    8332:     nis = 0;
    8333:     nisdofs = 0;
    8334:     nisneu = 0;
    8335:     nisvert = 0;
    8336:     isarray = NULL;
    8337:   }
    8338:   /* destroy no longer needed map */
    8339:   ISLocalToGlobalMappingDestroy(&coarse_islg);

    8341:   /* subassemble */
    8342:   if (multilevel_allowed) {
    8343:     Vec       vp[1];
    8344:     PetscInt  nvecs = 0;
    8345:     PetscBool reuse,reuser;

    8347:     if (coarse_mat) reuse = PETSC_TRUE;
    8348:     else reuse = PETSC_FALSE;
    8349:     MPIU_Allreduce(&reuse,&reuser,1,MPIU_BOOL,MPI_LOR,PetscObjectComm((PetscObject)pc));
    8350:     vp[0] = NULL;
    8351:     if (pcbddc->benign_have_null) { /* propagate no-net-flux quadrature to coarser level */
    8352:       VecCreate(PetscObjectComm((PetscObject)pc),&vp[0]);
    8353:       VecSetSizes(vp[0],pcbddc->local_primal_size,PETSC_DECIDE);
    8354:       VecSetType(vp[0],VECSTANDARD);
    8355:       nvecs = 1;

    8357:       if (pcbddc->divudotp) {
    8358:         Mat      B,loc_divudotp;
    8359:         Vec      v,p;
    8360:         IS       dummy;
    8361:         PetscInt np;

    8363:         MatISGetLocalMat(pcbddc->divudotp,&loc_divudotp);
    8364:         MatGetSize(loc_divudotp,&np,NULL);
    8365:         ISCreateStride(PETSC_COMM_SELF,np,0,1,&dummy);
    8366:         MatCreateSubMatrix(loc_divudotp,dummy,pcis->is_B_local,MAT_INITIAL_MATRIX,&B);
    8367:         MatCreateVecs(B,&v,&p);
    8368:         VecSet(p,1.);
    8369:         MatMultTranspose(B,p,v);
    8370:         VecDestroy(&p);
    8371:         MatDestroy(&B);
    8372:         VecGetArray(vp[0],&array);
    8373:         VecPlaceArray(pcbddc->vec1_P,array);
    8374:         VecRestoreArray(vp[0],&array);
    8375:         MatMultTranspose(pcbddc->coarse_phi_B,v,pcbddc->vec1_P);
    8376:         VecResetArray(pcbddc->vec1_P);
    8377:         ISDestroy(&dummy);
    8378:         VecDestroy(&v);
    8379:       }
    8380:     }
    8381:     if (reuser) {
    8382:       PCBDDCMatISSubassemble(t_coarse_mat_is,pcbddc->coarse_subassembling,0,restr,full_restr,PETSC_TRUE,&coarse_mat,nis,isarray,nvecs,vp);
    8383:     } else {
    8384:       PCBDDCMatISSubassemble(t_coarse_mat_is,pcbddc->coarse_subassembling,0,restr,full_restr,PETSC_FALSE,&coarse_mat_is,nis,isarray,nvecs,vp);
    8385:     }
    8386:     if (vp[0]) { /* vp[0] could have been placed on a different set of processes */
    8387:       PetscScalar       *arraym;
    8388:       const PetscScalar *arrayv;
    8389:       PetscInt          nl;
    8390:       VecGetLocalSize(vp[0],&nl);
    8391:       MatCreateSeqDense(PETSC_COMM_SELF,1,nl,NULL,&coarsedivudotp);
    8392:       MatDenseGetArray(coarsedivudotp,&arraym);
    8393:       VecGetArrayRead(vp[0],&arrayv);
    8394:       PetscArraycpy(arraym,arrayv,nl);
    8395:       VecRestoreArrayRead(vp[0],&arrayv);
    8396:       MatDenseRestoreArray(coarsedivudotp,&arraym);
    8397:       VecDestroy(&vp[0]);
    8398:     } else {
    8399:       MatCreateSeqAIJ(PETSC_COMM_SELF,0,0,1,NULL,&coarsedivudotp);
    8400:     }
    8401:   } else {
    8402:     PCBDDCMatISSubassemble(t_coarse_mat_is,pcbddc->coarse_subassembling,0,restr,full_restr,PETSC_FALSE,&coarse_mat_is,0,NULL,0,NULL);
    8403:   }
    8404:   if (coarse_mat_is || coarse_mat) {
    8405:     if (!multilevel_allowed) {
    8406:       MatConvert(coarse_mat_is,MATAIJ,coarse_mat_reuse,&coarse_mat);
    8407:     } else {
    8408:       /* if this matrix is present, it means we are not reusing the coarse matrix */
    8409:       if (coarse_mat_is) {
    8410:         if (coarse_mat) SETERRQ(PetscObjectComm((PetscObject)coarse_mat_is),PETSC_ERR_PLIB,"This should not happen");
    8411:         PetscObjectReference((PetscObject)coarse_mat_is);
    8412:         coarse_mat = coarse_mat_is;
    8413:       }
    8414:     }
    8415:   }
    8416:   MatDestroy(&t_coarse_mat_is);
    8417:   MatDestroy(&coarse_mat_is);

    8419:   /* create local to global scatters for coarse problem */
    8420:   if (compute_vecs) {
    8421:     PetscInt lrows;
    8422:     VecDestroy(&pcbddc->coarse_vec);
    8423:     if (coarse_mat) {
    8424:       MatGetLocalSize(coarse_mat,&lrows,NULL);
    8425:     } else {
    8426:       lrows = 0;
    8427:     }
    8428:     VecCreate(PetscObjectComm((PetscObject)pc),&pcbddc->coarse_vec);
    8429:     VecSetSizes(pcbddc->coarse_vec,lrows,PETSC_DECIDE);
    8430:     VecSetType(pcbddc->coarse_vec,coarse_mat ? coarse_mat->defaultvectype : VECSTANDARD);
    8431:     VecScatterDestroy(&pcbddc->coarse_loc_to_glob);
    8432:     VecScatterCreate(pcbddc->vec1_P,NULL,pcbddc->coarse_vec,coarse_is,&pcbddc->coarse_loc_to_glob);
    8433:   }
    8434:   ISDestroy(&coarse_is);

    8436:   /* set defaults for coarse KSP and PC */
    8437:   if (multilevel_allowed) {
    8438:     coarse_ksp_type = KSPRICHARDSON;
    8439:     coarse_pc_type  = PCBDDC;
    8440:   } else {
    8441:     coarse_ksp_type = KSPPREONLY;
    8442:     coarse_pc_type  = PCREDUNDANT;
    8443:   }

    8445:   /* print some info if requested */
    8446:   if (pcbddc->dbg_flag) {
    8447:     if (!multilevel_allowed) {
    8448:       PetscViewerASCIIPrintf(pcbddc->dbg_viewer,"--------------------------------------------------\n");
    8449:       if (multilevel_requested) {
    8450:         PetscViewerASCIIPrintf(pcbddc->dbg_viewer,"Not enough active processes on level %D (active processes %D, coarsening ratio %D)\n",pcbddc->current_level,active_procs,pcbddc->coarsening_ratio);
    8451:       } else if (pcbddc->max_levels) {
    8452:         PetscViewerASCIIPrintf(pcbddc->dbg_viewer,"Maximum number of requested levels reached (%D)\n",pcbddc->max_levels);
    8453:       }
    8454:       PetscViewerFlush(pcbddc->dbg_viewer);
    8455:     }
    8456:   }

    8458:   /* communicate coarse discrete gradient */
    8459:   coarseG = NULL;
    8460:   if (pcbddc->nedcG && multilevel_allowed) {
    8461:     MPI_Comm ccomm;
    8462:     if (coarse_mat) {
    8463:       ccomm = PetscObjectComm((PetscObject)coarse_mat);
    8464:     } else {
    8465:       ccomm = MPI_COMM_NULL;
    8466:     }
    8467:     MatMPIAIJRestrict(pcbddc->nedcG,ccomm,&coarseG);
    8468:   }

    8470:   /* create the coarse KSP object only once with defaults */
    8471:   if (coarse_mat) {
    8472:     PetscBool   isredundant,isbddc,force,valid;
    8473:     PetscViewer dbg_viewer = NULL;

    8475:     if (pcbddc->dbg_flag) {
    8476:       dbg_viewer = PETSC_VIEWER_STDOUT_(PetscObjectComm((PetscObject)coarse_mat));
    8477:       PetscViewerASCIIAddTab(dbg_viewer,2*pcbddc->current_level);
    8478:     }
    8479:     if (!pcbddc->coarse_ksp) {
    8480:       char   prefix[256],str_level[16];
    8481:       size_t len;

    8483:       KSPCreate(PetscObjectComm((PetscObject)coarse_mat),&pcbddc->coarse_ksp);
    8484:       KSPSetErrorIfNotConverged(pcbddc->coarse_ksp,pc->erroriffailure);
    8485:       PetscObjectIncrementTabLevel((PetscObject)pcbddc->coarse_ksp,(PetscObject)pc,1);
    8486:       KSPSetTolerances(pcbddc->coarse_ksp,PETSC_DEFAULT,PETSC_DEFAULT,PETSC_DEFAULT,1);
    8487:       KSPSetOperators(pcbddc->coarse_ksp,coarse_mat,coarse_mat);
    8488:       KSPSetType(pcbddc->coarse_ksp,coarse_ksp_type);
    8489:       KSPSetNormType(pcbddc->coarse_ksp,KSP_NORM_NONE);
    8490:       KSPGetPC(pcbddc->coarse_ksp,&pc_temp);
    8491:       /* TODO is this logic correct? should check for coarse_mat type */
    8492:       PCSetType(pc_temp,coarse_pc_type);
    8493:       /* prefix */
    8494:       PetscStrcpy(prefix,"");
    8495:       PetscStrcpy(str_level,"");
    8496:       if (!pcbddc->current_level) {
    8497:         PetscStrncpy(prefix,((PetscObject)pc)->prefix,sizeof(prefix));
    8498:         PetscStrlcat(prefix,"pc_bddc_coarse_",sizeof(prefix));
    8499:       } else {
    8500:         PetscStrlen(((PetscObject)pc)->prefix,&len);
    8501:         if (pcbddc->current_level>1) len -= 3; /* remove "lX_" with X level number */
    8502:         if (pcbddc->current_level>10) len -= 1; /* remove another char from level number */
    8503:         /* Nonstandard use of PetscStrncpy() to copy only a portion of the string */
    8504:         PetscStrncpy(prefix,((PetscObject)pc)->prefix,len+1);
    8505:         PetscSNPrintf(str_level,sizeof(str_level),"l%d_",(int)(pcbddc->current_level));
    8506:         PetscStrlcat(prefix,str_level,sizeof(prefix));
    8507:       }
    8508:       KSPSetOptionsPrefix(pcbddc->coarse_ksp,prefix);
    8509:       /* propagate BDDC info to the next level (these are dummy calls if pc_temp is not of type PCBDDC) */
    8510:       PCBDDCSetLevel(pc_temp,pcbddc->current_level+1);
    8511:       PCBDDCSetCoarseningRatio(pc_temp,pcbddc->coarsening_ratio);
    8512:       PCBDDCSetLevels(pc_temp,pcbddc->max_levels);
    8513:       /* allow user customization */
    8514:       KSPSetFromOptions(pcbddc->coarse_ksp);
    8515:       /* get some info after set from options */
    8516:       KSPGetPC(pcbddc->coarse_ksp,&pc_temp);
    8517:       /* multilevel cannot be done with coarse PC different from BDDC, NN, HPDDM, unless forced to */
    8518:       force = PETSC_FALSE;
    8519:       PetscOptionsGetBool(NULL,((PetscObject)pc_temp)->prefix,"-pc_type_forced",&force,NULL);
    8520:       PetscObjectTypeCompareAny((PetscObject)pc_temp,&valid,PCBDDC,PCNN,PCHPDDM,"");
    8521:       PetscObjectTypeCompare((PetscObject)pc_temp,PCBDDC,&isbddc);
    8522:       if (multilevel_allowed && !force && !valid) {
    8523:         isbddc = PETSC_TRUE;
    8524:         PCSetType(pc_temp,PCBDDC);
    8525:         PCBDDCSetLevel(pc_temp,pcbddc->current_level+1);
    8526:         PCBDDCSetCoarseningRatio(pc_temp,pcbddc->coarsening_ratio);
    8527:         PCBDDCSetLevels(pc_temp,pcbddc->max_levels);
    8528:         if (pc_temp->ops->setfromoptions) { /* need to setfromoptions again, skipping the pc_type */
    8529:           PetscObjectOptionsBegin((PetscObject)pc_temp);
    8530:           (*pc_temp->ops->setfromoptions)(PetscOptionsObject,pc_temp);
    8531:           PetscObjectProcessOptionsHandlers(PetscOptionsObject,(PetscObject)pc_temp);
    8532:           PetscOptionsEnd();
    8533:           pc_temp->setfromoptionscalled++;
    8534:         }
    8535:       }
    8536:     }
    8537:     /* propagate BDDC info to the next level (these are dummy calls if pc_temp is not of type PCBDDC) */
    8538:     KSPGetPC(pcbddc->coarse_ksp,&pc_temp);
    8539:     if (nisdofs) {
    8540:       PCBDDCSetDofsSplitting(pc_temp,nisdofs,isarray);
    8541:       for (i=0;i<nisdofs;i++) {
    8542:         ISDestroy(&isarray[i]);
    8543:       }
    8544:     }
    8545:     if (nisneu) {
    8546:       PCBDDCSetNeumannBoundaries(pc_temp,isarray[nisdofs]);
    8547:       ISDestroy(&isarray[nisdofs]);
    8548:     }
    8549:     if (nisvert) {
    8550:       PCBDDCSetPrimalVerticesIS(pc_temp,isarray[nis-1]);
    8551:       ISDestroy(&isarray[nis-1]);
    8552:     }
    8553:     if (coarseG) {
    8554:       PCBDDCSetDiscreteGradient(pc_temp,coarseG,1,nedcfield,PETSC_FALSE,PETSC_TRUE);
    8555:     }

    8557:     /* get some info after set from options */
    8558:     PetscObjectTypeCompare((PetscObject)pc_temp,PCBDDC,&isbddc);

    8560:     /* multilevel can only be requested via -pc_bddc_levels or PCBDDCSetLevels */
    8561:     if (isbddc && !multilevel_allowed) {
    8562:       PCSetType(pc_temp,coarse_pc_type);
    8563:     }
    8564:     /* multilevel cannot be done with coarse PC different from BDDC, NN, HPDDM, unless forced to */
    8565:     force = PETSC_FALSE;
    8566:     PetscOptionsGetBool(NULL,((PetscObject)pc_temp)->prefix,"-pc_type_forced",&force,NULL);
    8567:     PetscObjectTypeCompareAny((PetscObject)pc_temp,&valid,PCBDDC,PCNN,PCHPDDM,"");
    8568:     if (multilevel_requested && multilevel_allowed && !valid && !force) {
    8569:       PCSetType(pc_temp,PCBDDC);
    8570:     }
    8571:     PetscObjectTypeCompare((PetscObject)pc_temp,PCREDUNDANT,&isredundant);
    8572:     if (isredundant) {
    8573:       KSP inner_ksp;
    8574:       PC  inner_pc;

    8576:       PCRedundantGetKSP(pc_temp,&inner_ksp);
    8577:       KSPGetPC(inner_ksp,&inner_pc);
    8578:     }

    8580:     /* parameters which miss an API */
    8581:     PetscObjectTypeCompare((PetscObject)pc_temp,PCBDDC,&isbddc);
    8582:     if (isbddc) {
    8583:       PC_BDDC* pcbddc_coarse = (PC_BDDC*)pc_temp->data;

    8585:       pcbddc_coarse->detect_disconnected = PETSC_TRUE;
    8586:       pcbddc_coarse->coarse_eqs_per_proc = pcbddc->coarse_eqs_per_proc;
    8587:       pcbddc_coarse->coarse_eqs_limit    = pcbddc->coarse_eqs_limit;
    8588:       pcbddc_coarse->benign_saddle_point = pcbddc->benign_have_null;
    8589:       if (pcbddc_coarse->benign_saddle_point) {
    8590:         Mat                    coarsedivudotp_is;
    8591:         ISLocalToGlobalMapping l2gmap,rl2g,cl2g;
    8592:         IS                     row,col;
    8593:         const PetscInt         *gidxs;
    8594:         PetscInt               n,st,M,N;

    8596:         MatGetSize(coarsedivudotp,&n,NULL);
    8597:         MPI_Scan(&n,&st,1,MPIU_INT,MPI_SUM,PetscObjectComm((PetscObject)coarse_mat));
    8598:         st   = st-n;
    8599:         ISCreateStride(PetscObjectComm((PetscObject)coarse_mat),1,st,1,&row);
    8600:         MatGetLocalToGlobalMapping(coarse_mat,&l2gmap,NULL);
    8601:         ISLocalToGlobalMappingGetSize(l2gmap,&n);
    8602:         ISLocalToGlobalMappingGetIndices(l2gmap,&gidxs);
    8603:         ISCreateGeneral(PetscObjectComm((PetscObject)coarse_mat),n,gidxs,PETSC_COPY_VALUES,&col);
    8604:         ISLocalToGlobalMappingRestoreIndices(l2gmap,&gidxs);
    8605:         ISLocalToGlobalMappingCreateIS(row,&rl2g);
    8606:         ISLocalToGlobalMappingCreateIS(col,&cl2g);
    8607:         ISGetSize(row,&M);
    8608:         MatGetSize(coarse_mat,&N,NULL);
    8609:         ISDestroy(&row);
    8610:         ISDestroy(&col);
    8611:         MatCreate(PetscObjectComm((PetscObject)coarse_mat),&coarsedivudotp_is);
    8612:         MatSetType(coarsedivudotp_is,MATIS);
    8613:         MatSetSizes(coarsedivudotp_is,PETSC_DECIDE,PETSC_DECIDE,M,N);
    8614:         MatSetLocalToGlobalMapping(coarsedivudotp_is,rl2g,cl2g);
    8615:         ISLocalToGlobalMappingDestroy(&rl2g);
    8616:         ISLocalToGlobalMappingDestroy(&cl2g);
    8617:         MatISSetLocalMat(coarsedivudotp_is,coarsedivudotp);
    8618:         MatDestroy(&coarsedivudotp);
    8619:         PCBDDCSetDivergenceMat(pc_temp,coarsedivudotp_is,PETSC_FALSE,NULL);
    8620:         MatDestroy(&coarsedivudotp_is);
    8621:         pcbddc_coarse->adaptive_userdefined = PETSC_TRUE;
    8622:         if (pcbddc->adaptive_threshold[0] == 0.0) pcbddc_coarse->deluxe_zerorows = PETSC_TRUE;
    8623:       }
    8624:     }

    8626:     /* propagate symmetry info of coarse matrix */
    8627:     MatSetOption(coarse_mat,MAT_STRUCTURALLY_SYMMETRIC,PETSC_TRUE);
    8628:     if (pc->pmat->symmetric_set) {
    8629:       MatSetOption(coarse_mat,MAT_SYMMETRIC,pc->pmat->symmetric);
    8630:     }
    8631:     if (pc->pmat->hermitian_set) {
    8632:       MatSetOption(coarse_mat,MAT_HERMITIAN,pc->pmat->hermitian);
    8633:     }
    8634:     if (pc->pmat->spd_set) {
    8635:       MatSetOption(coarse_mat,MAT_SPD,pc->pmat->spd);
    8636:     }
    8637:     if (pcbddc->benign_saddle_point && !pcbddc->benign_have_null) {
    8638:       MatSetOption(coarse_mat,MAT_SPD,PETSC_TRUE);
    8639:     }
    8640:     /* set operators */
    8641:     MatViewFromOptions(coarse_mat,(PetscObject)pc,"-pc_bddc_coarse_mat_view");
    8642:     MatSetOptionsPrefix(coarse_mat,((PetscObject)pcbddc->coarse_ksp)->prefix);
    8643:     KSPSetOperators(pcbddc->coarse_ksp,coarse_mat,coarse_mat);
    8644:     if (pcbddc->dbg_flag) {
    8645:       PetscViewerASCIISubtractTab(dbg_viewer,2*pcbddc->current_level);
    8646:     }
    8647:   }
    8648:   MatDestroy(&coarseG);
    8649:   PetscFree(isarray);
    8650: #if 0
    8651:   {
    8652:     PetscViewer viewer;
    8653:     char filename[256];
    8654:     sprintf(filename,"coarse_mat_level%d.m",pcbddc->current_level);
    8655:     PetscViewerASCIIOpen(PetscObjectComm((PetscObject)coarse_mat),filename,&viewer);
    8656:     PetscViewerPushFormat(viewer,PETSC_VIEWER_ASCII_MATLAB);
    8657:     MatView(coarse_mat,viewer);
    8658:     PetscViewerPopFormat(viewer);
    8659:     PetscViewerDestroy(&viewer);
    8660:   }
    8661: #endif

    8663:   if (corners) {
    8664:     Vec            gv;
    8665:     IS             is;
    8666:     const PetscInt *idxs;
    8667:     PetscInt       i,d,N,n,cdim = pcbddc->mat_graph->cdim;
    8668:     PetscScalar    *coords;

    8670:     if (!pcbddc->mat_graph->cloc) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_PLIB,"Missing local coordinates");
    8671:     VecGetSize(pcbddc->coarse_vec,&N);
    8672:     VecGetLocalSize(pcbddc->coarse_vec,&n);
    8673:     VecCreate(PetscObjectComm((PetscObject)pcbddc->coarse_vec),&gv);
    8674:     VecSetBlockSize(gv,cdim);
    8675:     VecSetSizes(gv,n*cdim,N*cdim);
    8676:     VecSetType(gv,VECSTANDARD);
    8677:     VecSetFromOptions(gv);
    8678:     VecSet(gv,PETSC_MAX_REAL); /* we only propagate coordinates from vertices constraints */

    8680:     PCBDDCGraphGetCandidatesIS(pcbddc->mat_graph,NULL,NULL,NULL,NULL,&is);
    8681:     ISGetLocalSize(is,&n);
    8682:     ISGetIndices(is,&idxs);
    8683:     PetscMalloc1(n*cdim,&coords);
    8684:     for (i=0;i<n;i++) {
    8685:       for (d=0;d<cdim;d++) {
    8686:         coords[cdim*i+d] = pcbddc->mat_graph->coords[cdim*idxs[i]+d];
    8687:       }
    8688:     }
    8689:     ISRestoreIndices(is,&idxs);
    8690:     PCBDDCGraphRestoreCandidatesIS(pcbddc->mat_graph,NULL,NULL,NULL,NULL,&is);

    8692:     ISGetLocalSize(corners,&n);
    8693:     ISGetIndices(corners,&idxs);
    8694:     VecSetValuesBlocked(gv,n,idxs,coords,INSERT_VALUES);
    8695:     ISRestoreIndices(corners,&idxs);
    8696:     PetscFree(coords);
    8697:     VecAssemblyBegin(gv);
    8698:     VecAssemblyEnd(gv);
    8699:     VecGetArray(gv,&coords);
    8700:     if (pcbddc->coarse_ksp) {
    8701:       PC        coarse_pc;
    8702:       PetscBool isbddc;

    8704:       KSPGetPC(pcbddc->coarse_ksp,&coarse_pc);
    8705:       PetscObjectTypeCompare((PetscObject)coarse_pc,PCBDDC,&isbddc);
    8706:       if (isbddc) { /* coarse coordinates have PETSC_MAX_REAL, specific for BDDC */
    8707:         PetscReal *realcoords;

    8709:         VecGetLocalSize(gv,&n);
    8710: #if defined(PETSC_USE_COMPLEX)
    8711:         PetscMalloc1(n,&realcoords);
    8712:         for (i=0;i<n;i++) realcoords[i] = PetscRealPart(coords[i]);
    8713: #else
    8714:         realcoords = coords;
    8715: #endif
    8716:         PCSetCoordinates(coarse_pc,cdim,n/cdim,realcoords);
    8717: #if defined(PETSC_USE_COMPLEX)
    8718:         PetscFree(realcoords);
    8719: #endif
    8720:       }
    8721:     }
    8722:     VecRestoreArray(gv,&coords);
    8723:     VecDestroy(&gv);
    8724:   }
    8725:   ISDestroy(&corners);

    8727:   if (pcbddc->coarse_ksp) {
    8728:     Vec crhs,csol;

    8730:     KSPGetSolution(pcbddc->coarse_ksp,&csol);
    8731:     KSPGetRhs(pcbddc->coarse_ksp,&crhs);
    8732:     if (!csol) {
    8733:       MatCreateVecs(coarse_mat,&((pcbddc->coarse_ksp)->vec_sol),NULL);
    8734:     }
    8735:     if (!crhs) {
    8736:       MatCreateVecs(coarse_mat,NULL,&((pcbddc->coarse_ksp)->vec_rhs));
    8737:     }
    8738:   }
    8739:   MatDestroy(&coarsedivudotp);

    8741:   /* compute null space for coarse solver if the benign trick has been requested */
    8742:   if (pcbddc->benign_null) {

    8744:     VecSet(pcbddc->vec1_P,0.);
    8745:     for (i=0;i<pcbddc->benign_n;i++) {
    8746:       VecSetValue(pcbddc->vec1_P,pcbddc->local_primal_size-pcbddc->benign_n+i,1.0,INSERT_VALUES);
    8747:     }
    8748:     VecAssemblyBegin(pcbddc->vec1_P);
    8749:     VecAssemblyEnd(pcbddc->vec1_P);
    8750:     VecScatterBegin(pcbddc->coarse_loc_to_glob,pcbddc->vec1_P,pcbddc->coarse_vec,INSERT_VALUES,SCATTER_FORWARD);
    8751:     VecScatterEnd(pcbddc->coarse_loc_to_glob,pcbddc->vec1_P,pcbddc->coarse_vec,INSERT_VALUES,SCATTER_FORWARD);
    8752:     if (coarse_mat) {
    8753:       Vec         nullv;
    8754:       PetscScalar *array,*array2;
    8755:       PetscInt    nl;

    8757:       MatCreateVecs(coarse_mat,&nullv,NULL);
    8758:       VecGetLocalSize(nullv,&nl);
    8759:       VecGetArrayRead(pcbddc->coarse_vec,(const PetscScalar**)&array);
    8760:       VecGetArray(nullv,&array2);
    8761:       PetscArraycpy(array2,array,nl);
    8762:       VecRestoreArray(nullv,&array2);
    8763:       VecRestoreArrayRead(pcbddc->coarse_vec,(const PetscScalar**)&array);
    8764:       VecNormalize(nullv,NULL);
    8765:       MatNullSpaceCreate(PetscObjectComm((PetscObject)coarse_mat),PETSC_FALSE,1,&nullv,&CoarseNullSpace);
    8766:       VecDestroy(&nullv);
    8767:     }
    8768:   }
    8769:   PetscLogEventEnd(PC_BDDC_CoarseSetUp[pcbddc->current_level],pc,0,0,0);

    8771:   PetscLogEventBegin(PC_BDDC_CoarseSolver[pcbddc->current_level],pc,0,0,0);
    8772:   if (pcbddc->coarse_ksp) {
    8773:     PetscBool ispreonly;

    8775:     if (CoarseNullSpace) {
    8776:       PetscBool isnull;
    8777:       MatNullSpaceTest(CoarseNullSpace,coarse_mat,&isnull);
    8778:       if (isnull) {
    8779:         MatSetNullSpace(coarse_mat,CoarseNullSpace);
    8780:       }
    8781:       /* TODO: add local nullspaces (if any) */
    8782:     }
    8783:     /* setup coarse ksp */
    8784:     KSPSetUp(pcbddc->coarse_ksp);
    8785:     /* Check coarse problem if in debug mode or if solving with an iterative method */
    8786:     PetscObjectTypeCompare((PetscObject)pcbddc->coarse_ksp,KSPPREONLY,&ispreonly);
    8787:     if (pcbddc->dbg_flag || (!ispreonly && pcbddc->use_coarse_estimates) ) {
    8788:       KSP       check_ksp;
    8789:       KSPType   check_ksp_type;
    8790:       PC        check_pc;
    8791:       Vec       check_vec,coarse_vec;
    8792:       PetscReal abs_infty_error,infty_error,lambda_min=1.0,lambda_max=1.0;
    8793:       PetscInt  its;
    8794:       PetscBool compute_eigs;
    8795:       PetscReal *eigs_r,*eigs_c;
    8796:       PetscInt  neigs;
    8797:       const char *prefix;

    8799:       /* Create ksp object suitable for estimation of extreme eigenvalues */
    8800:       KSPCreate(PetscObjectComm((PetscObject)pcbddc->coarse_ksp),&check_ksp);
    8801:       PetscObjectIncrementTabLevel((PetscObject)check_ksp,(PetscObject)pcbddc->coarse_ksp,0);
    8802:       KSPSetErrorIfNotConverged(pcbddc->coarse_ksp,PETSC_FALSE);
    8803:       KSPSetOperators(check_ksp,coarse_mat,coarse_mat);
    8804:       KSPSetTolerances(check_ksp,1.e-12,1.e-12,PETSC_DEFAULT,pcbddc->coarse_size);
    8805:       /* prevent from setup unneeded object */
    8806:       KSPGetPC(check_ksp,&check_pc);
    8807:       PCSetType(check_pc,PCNONE);
    8808:       if (ispreonly) {
    8809:         check_ksp_type = KSPPREONLY;
    8810:         compute_eigs = PETSC_FALSE;
    8811:       } else {
    8812:         check_ksp_type = KSPGMRES;
    8813:         compute_eigs = PETSC_TRUE;
    8814:       }
    8815:       KSPSetType(check_ksp,check_ksp_type);
    8816:       KSPSetComputeSingularValues(check_ksp,compute_eigs);
    8817:       KSPSetComputeEigenvalues(check_ksp,compute_eigs);
    8818:       KSPGMRESSetRestart(check_ksp,pcbddc->coarse_size+1);
    8819:       KSPGetOptionsPrefix(pcbddc->coarse_ksp,&prefix);
    8820:       KSPSetOptionsPrefix(check_ksp,prefix);
    8821:       KSPAppendOptionsPrefix(check_ksp,"check_");
    8822:       KSPSetFromOptions(check_ksp);
    8823:       KSPSetUp(check_ksp);
    8824:       KSPGetPC(pcbddc->coarse_ksp,&check_pc);
    8825:       KSPSetPC(check_ksp,check_pc);
    8826:       /* create random vec */
    8827:       MatCreateVecs(coarse_mat,&coarse_vec,&check_vec);
    8828:       VecSetRandom(check_vec,NULL);
    8829:       MatMult(coarse_mat,check_vec,coarse_vec);
    8830:       /* solve coarse problem */
    8831:       KSPSolve(check_ksp,coarse_vec,coarse_vec);
    8832:       KSPCheckSolve(check_ksp,pc,coarse_vec);
    8833:       /* set eigenvalue estimation if preonly has not been requested */
    8834:       if (compute_eigs) {
    8835:         PetscMalloc1(pcbddc->coarse_size+1,&eigs_r);
    8836:         PetscMalloc1(pcbddc->coarse_size+1,&eigs_c);
    8837:         KSPComputeEigenvalues(check_ksp,pcbddc->coarse_size+1,eigs_r,eigs_c,&neigs);
    8838:         if (neigs) {
    8839:           lambda_max = eigs_r[neigs-1];
    8840:           lambda_min = eigs_r[0];
    8841:           if (pcbddc->use_coarse_estimates) {
    8842:             if (lambda_max>=lambda_min) { /* using PETSC_SMALL since lambda_max == lambda_min is not allowed by KSPChebyshevSetEigenvalues */
    8843:               KSPChebyshevSetEigenvalues(pcbddc->coarse_ksp,lambda_max+PETSC_SMALL,lambda_min);
    8844:               KSPRichardsonSetScale(pcbddc->coarse_ksp,2.0/(lambda_max+lambda_min));
    8845:             }
    8846:           }
    8847:         }
    8848:       }

    8850:       /* check coarse problem residual error */
    8851:       if (pcbddc->dbg_flag) {
    8852:         PetscViewer dbg_viewer = PETSC_VIEWER_STDOUT_(PetscObjectComm((PetscObject)pcbddc->coarse_ksp));
    8853:         PetscViewerASCIIAddTab(dbg_viewer,2*(pcbddc->current_level+1));
    8854:         VecAXPY(check_vec,-1.0,coarse_vec);
    8855:         VecNorm(check_vec,NORM_INFINITY,&infty_error);
    8856:         MatMult(coarse_mat,check_vec,coarse_vec);
    8857:         VecNorm(coarse_vec,NORM_INFINITY,&abs_infty_error);
    8858:         PetscViewerASCIIPrintf(dbg_viewer,"Coarse problem details (use estimates %d)\n",pcbddc->use_coarse_estimates);
    8859:         PetscObjectPrintClassNamePrefixType((PetscObject)(pcbddc->coarse_ksp),dbg_viewer);
    8860:         PetscObjectPrintClassNamePrefixType((PetscObject)(check_pc),dbg_viewer);
    8861:         PetscViewerASCIIPrintf(dbg_viewer,"Coarse problem exact infty_error   : %1.6e\n",infty_error);
    8862:         PetscViewerASCIIPrintf(dbg_viewer,"Coarse problem residual infty_error: %1.6e\n",abs_infty_error);
    8863:         if (CoarseNullSpace) {
    8864:           PetscViewerASCIIPrintf(dbg_viewer,"Coarse problem is singular\n");
    8865:         }
    8866:         if (compute_eigs) {
    8867:           PetscReal          lambda_max_s,lambda_min_s;
    8868:           KSPConvergedReason reason;
    8869:           KSPGetType(check_ksp,&check_ksp_type);
    8870:           KSPGetIterationNumber(check_ksp,&its);
    8871:           KSPGetConvergedReason(check_ksp,&reason);
    8872:           KSPComputeExtremeSingularValues(check_ksp,&lambda_max_s,&lambda_min_s);
    8873:           PetscViewerASCIIPrintf(dbg_viewer,"Coarse problem eigenvalues (estimated with %d iterations of %s, conv reason %d): %1.6e %1.6e (%1.6e %1.6e)\n",its,check_ksp_type,reason,lambda_min,lambda_max,lambda_min_s,lambda_max_s);
    8874:           for (i=0;i<neigs;i++) {
    8875:             PetscViewerASCIIPrintf(dbg_viewer,"%1.6e %1.6ei\n",eigs_r[i],eigs_c[i]);
    8876:           }
    8877:         }
    8878:         PetscViewerFlush(dbg_viewer);
    8879:         PetscViewerASCIISubtractTab(dbg_viewer,2*(pcbddc->current_level+1));
    8880:       }
    8881:       VecDestroy(&check_vec);
    8882:       VecDestroy(&coarse_vec);
    8883:       KSPDestroy(&check_ksp);
    8884:       if (compute_eigs) {
    8885:         PetscFree(eigs_r);
    8886:         PetscFree(eigs_c);
    8887:       }
    8888:     }
    8889:   }
    8890:   MatNullSpaceDestroy(&CoarseNullSpace);
    8891:   /* print additional info */
    8892:   if (pcbddc->dbg_flag) {
    8893:     /* waits until all processes reaches this point */
    8894:     PetscBarrier((PetscObject)pc);
    8895:     PetscViewerASCIIPrintf(pcbddc->dbg_viewer,"Coarse solver setup completed at level %D\n",pcbddc->current_level);
    8896:     PetscViewerFlush(pcbddc->dbg_viewer);
    8897:   }

    8899:   /* free memory */
    8900:   MatDestroy(&coarse_mat);
    8901:   PetscLogEventEnd(PC_BDDC_CoarseSolver[pcbddc->current_level],pc,0,0,0);
    8902:   return(0);
    8903: }

    8905: PetscErrorCode PCBDDCComputePrimalNumbering(PC pc,PetscInt* coarse_size_n,PetscInt** local_primal_indices_n)
    8906: {
    8907:   PC_BDDC*       pcbddc = (PC_BDDC*)pc->data;
    8908:   PC_IS*         pcis = (PC_IS*)pc->data;
    8909:   Mat_IS*        matis = (Mat_IS*)pc->pmat->data;
    8910:   IS             subset,subset_mult,subset_n;
    8911:   PetscInt       local_size,coarse_size=0;
    8912:   PetscInt       *local_primal_indices=NULL;
    8913:   const PetscInt *t_local_primal_indices;

    8917:   /* Compute global number of coarse dofs */
    8918:   if (pcbddc->local_primal_size && !pcbddc->local_primal_ref_node) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_PLIB,"BDDC ConstraintsSetUp should be called first");
    8919:   ISCreateGeneral(PetscObjectComm((PetscObject)(pc->pmat)),pcbddc->local_primal_size_cc,pcbddc->local_primal_ref_node,PETSC_COPY_VALUES,&subset_n);
    8920:   ISLocalToGlobalMappingApplyIS(pcis->mapping,subset_n,&subset);
    8921:   ISDestroy(&subset_n);
    8922:   ISCreateGeneral(PetscObjectComm((PetscObject)(pc->pmat)),pcbddc->local_primal_size_cc,pcbddc->local_primal_ref_mult,PETSC_COPY_VALUES,&subset_mult);
    8923:   ISRenumber(subset,subset_mult,&coarse_size,&subset_n);
    8924:   ISDestroy(&subset);
    8925:   ISDestroy(&subset_mult);
    8926:   ISGetLocalSize(subset_n,&local_size);
    8927:   if (local_size != pcbddc->local_primal_size) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_PLIB,"Invalid number of local primal indices computed %D != %D",local_size,pcbddc->local_primal_size);
    8928:   PetscMalloc1(local_size,&local_primal_indices);
    8929:   ISGetIndices(subset_n,&t_local_primal_indices);
    8930:   PetscArraycpy(local_primal_indices,t_local_primal_indices,local_size);
    8931:   ISRestoreIndices(subset_n,&t_local_primal_indices);
    8932:   ISDestroy(&subset_n);

    8934:   /* check numbering */
    8935:   if (pcbddc->dbg_flag) {
    8936:     PetscScalar coarsesum,*array,*array2;
    8937:     PetscInt    i;
    8938:     PetscBool   set_error = PETSC_FALSE,set_error_reduced = PETSC_FALSE;

    8940:     PetscViewerFlush(pcbddc->dbg_viewer);
    8941:     PetscViewerASCIIPrintf(pcbddc->dbg_viewer,"--------------------------------------------------\n");
    8942:     PetscViewerASCIIPrintf(pcbddc->dbg_viewer,"Check coarse indices\n");
    8943:     PetscViewerASCIIPushSynchronized(pcbddc->dbg_viewer);
    8944:     /* counter */
    8945:     VecSet(pcis->vec1_global,0.0);
    8946:     VecSet(pcis->vec1_N,1.0);
    8947:     VecScatterBegin(matis->rctx,pcis->vec1_N,pcis->vec1_global,ADD_VALUES,SCATTER_REVERSE);
    8948:     VecScatterEnd(matis->rctx,pcis->vec1_N,pcis->vec1_global,ADD_VALUES,SCATTER_REVERSE);
    8949:     VecScatterBegin(matis->rctx,pcis->vec1_global,pcis->vec2_N,INSERT_VALUES,SCATTER_FORWARD);
    8950:     VecScatterEnd(matis->rctx,pcis->vec1_global,pcis->vec2_N,INSERT_VALUES,SCATTER_FORWARD);
    8951:     VecSet(pcis->vec1_N,0.0);
    8952:     for (i=0;i<pcbddc->local_primal_size;i++) {
    8953:       VecSetValue(pcis->vec1_N,pcbddc->primal_indices_local_idxs[i],1.0,INSERT_VALUES);
    8954:     }
    8955:     VecAssemblyBegin(pcis->vec1_N);
    8956:     VecAssemblyEnd(pcis->vec1_N);
    8957:     VecSet(pcis->vec1_global,0.0);
    8958:     VecScatterBegin(matis->rctx,pcis->vec1_N,pcis->vec1_global,ADD_VALUES,SCATTER_REVERSE);
    8959:     VecScatterEnd(matis->rctx,pcis->vec1_N,pcis->vec1_global,ADD_VALUES,SCATTER_REVERSE);
    8960:     VecScatterBegin(matis->rctx,pcis->vec1_global,pcis->vec1_N,INSERT_VALUES,SCATTER_FORWARD);
    8961:     VecScatterEnd(matis->rctx,pcis->vec1_global,pcis->vec1_N,INSERT_VALUES,SCATTER_FORWARD);
    8962:     VecGetArray(pcis->vec1_N,&array);
    8963:     VecGetArray(pcis->vec2_N,&array2);
    8964:     for (i=0;i<pcis->n;i++) {
    8965:       if (array[i] != 0.0 && array[i] != array2[i]) {
    8966:         PetscInt owned = (PetscInt)PetscRealPart(array[i]),gi;
    8967:         PetscInt neigh = (PetscInt)PetscRealPart(array2[i]);
    8968:         set_error = PETSC_TRUE;
    8969:         ISLocalToGlobalMappingApply(pcis->mapping,1,&i,&gi);
    8970:         PetscViewerASCIISynchronizedPrintf(pcbddc->dbg_viewer,"Subdomain %04d: local index %D (gid %D) owned by %D processes instead of %D!\n",PetscGlobalRank,i,gi,owned,neigh);
    8971:       }
    8972:     }
    8973:     VecRestoreArray(pcis->vec2_N,&array2);
    8974:     MPIU_Allreduce(&set_error,&set_error_reduced,1,MPIU_BOOL,MPI_LOR,PetscObjectComm((PetscObject)pc));
    8975:     PetscViewerFlush(pcbddc->dbg_viewer);
    8976:     for (i=0;i<pcis->n;i++) {
    8977:       if (PetscRealPart(array[i]) > 0.0) array[i] = 1.0/PetscRealPart(array[i]);
    8978:     }
    8979:     VecRestoreArray(pcis->vec1_N,&array);
    8980:     VecSet(pcis->vec1_global,0.0);
    8981:     VecScatterBegin(matis->rctx,pcis->vec1_N,pcis->vec1_global,ADD_VALUES,SCATTER_REVERSE);
    8982:     VecScatterEnd(matis->rctx,pcis->vec1_N,pcis->vec1_global,ADD_VALUES,SCATTER_REVERSE);
    8983:     VecSum(pcis->vec1_global,&coarsesum);
    8984:     PetscViewerASCIIPrintf(pcbddc->dbg_viewer,"Size of coarse problem is %D (%lf)\n",coarse_size,PetscRealPart(coarsesum));
    8985:     if (pcbddc->dbg_flag > 1 || set_error_reduced) {
    8986:       PetscInt *gidxs;

    8988:       PetscMalloc1(pcbddc->local_primal_size,&gidxs);
    8989:       ISLocalToGlobalMappingApply(pcis->mapping,pcbddc->local_primal_size,pcbddc->primal_indices_local_idxs,gidxs);
    8990:       PetscViewerASCIIPrintf(pcbddc->dbg_viewer,"Distribution of local primal indices\n");
    8991:       PetscViewerFlush(pcbddc->dbg_viewer);
    8992:       PetscViewerASCIISynchronizedPrintf(pcbddc->dbg_viewer,"Subdomain %04d\n",PetscGlobalRank);
    8993:       for (i=0;i<pcbddc->local_primal_size;i++) {
    8994:         PetscViewerASCIISynchronizedPrintf(pcbddc->dbg_viewer,"local_primal_indices[%D]=%D (%D,%D)\n",i,local_primal_indices[i],pcbddc->primal_indices_local_idxs[i],gidxs[i]);
    8995:       }
    8996:       PetscViewerFlush(pcbddc->dbg_viewer);
    8997:       PetscFree(gidxs);
    8998:     }
    8999:     PetscViewerFlush(pcbddc->dbg_viewer);
    9000:     PetscViewerASCIIPushSynchronized(pcbddc->dbg_viewer);
    9001:     if (set_error_reduced) SETERRQ(PetscObjectComm((PetscObject)pc),PETSC_ERR_PLIB,"BDDC Numbering of coarse dofs failed");
    9002:   }

    9004:   /* get back data */
    9005:   *coarse_size_n = coarse_size;
    9006:   *local_primal_indices_n = local_primal_indices;
    9007:   return(0);
    9008: }

    9010: PetscErrorCode PCBDDCGlobalToLocal(VecScatter g2l_ctx,Vec gwork, Vec lwork, IS globalis, IS* localis)
    9011: {
    9012:   IS             localis_t;
    9013:   PetscInt       i,lsize,*idxs,n;
    9014:   PetscScalar    *vals;

    9018:   /* get indices in local ordering exploiting local to global map */
    9019:   ISGetLocalSize(globalis,&lsize);
    9020:   PetscMalloc1(lsize,&vals);
    9021:   for (i=0;i<lsize;i++) vals[i] = 1.0;
    9022:   ISGetIndices(globalis,(const PetscInt**)&idxs);
    9023:   VecSet(gwork,0.0);
    9024:   VecSet(lwork,0.0);
    9025:   if (idxs) { /* multilevel guard */
    9026:     VecSetOption(gwork,VEC_IGNORE_NEGATIVE_INDICES,PETSC_TRUE);
    9027:     VecSetValues(gwork,lsize,idxs,vals,INSERT_VALUES);
    9028:   }
    9029:   VecAssemblyBegin(gwork);
    9030:   ISRestoreIndices(globalis,(const PetscInt**)&idxs);
    9031:   PetscFree(vals);
    9032:   VecAssemblyEnd(gwork);
    9033:   /* now compute set in local ordering */
    9034:   VecScatterBegin(g2l_ctx,gwork,lwork,INSERT_VALUES,SCATTER_FORWARD);
    9035:   VecScatterEnd(g2l_ctx,gwork,lwork,INSERT_VALUES,SCATTER_FORWARD);
    9036:   VecGetArrayRead(lwork,(const PetscScalar**)&vals);
    9037:   VecGetSize(lwork,&n);
    9038:   for (i=0,lsize=0;i<n;i++) {
    9039:     if (PetscRealPart(vals[i]) > 0.5) {
    9040:       lsize++;
    9041:     }
    9042:   }
    9043:   PetscMalloc1(lsize,&idxs);
    9044:   for (i=0,lsize=0;i<n;i++) {
    9045:     if (PetscRealPart(vals[i]) > 0.5) {
    9046:       idxs[lsize++] = i;
    9047:     }
    9048:   }
    9049:   VecRestoreArrayRead(lwork,(const PetscScalar**)&vals);
    9050:   ISCreateGeneral(PetscObjectComm((PetscObject)gwork),lsize,idxs,PETSC_OWN_POINTER,&localis_t);
    9051:   *localis = localis_t;
    9052:   return(0);
    9053: }

    9055: PetscErrorCode PCBDDCSetUpSubSchurs(PC pc)
    9056: {
    9057:   PC_IS               *pcis=(PC_IS*)pc->data;
    9058:   PC_BDDC             *pcbddc=(PC_BDDC*)pc->data;
    9059:   PCBDDCSubSchurs     sub_schurs=pcbddc->sub_schurs;
    9060:   Mat                 S_j;
    9061:   PetscInt            *used_xadj,*used_adjncy;
    9062:   PetscBool           free_used_adj;
    9063:   PetscErrorCode      ierr;

    9066:   PetscLogEventBegin(PC_BDDC_Schurs[pcbddc->current_level],pc,0,0,0);
    9067:   /* decide the adjacency to be used for determining internal problems for local schur on subsets */
    9068:   free_used_adj = PETSC_FALSE;
    9069:   if (pcbddc->sub_schurs_layers == -1) {
    9070:     used_xadj = NULL;
    9071:     used_adjncy = NULL;
    9072:   } else {
    9073:     if (pcbddc->sub_schurs_use_useradj && pcbddc->mat_graph->xadj) {
    9074:       used_xadj = pcbddc->mat_graph->xadj;
    9075:       used_adjncy = pcbddc->mat_graph->adjncy;
    9076:     } else if (pcbddc->computed_rowadj) {
    9077:       used_xadj = pcbddc->mat_graph->xadj;
    9078:       used_adjncy = pcbddc->mat_graph->adjncy;
    9079:     } else {
    9080:       PetscBool      flg_row=PETSC_FALSE;
    9081:       const PetscInt *xadj,*adjncy;
    9082:       PetscInt       nvtxs;

    9084:       MatGetRowIJ(pcbddc->local_mat,0,PETSC_TRUE,PETSC_FALSE,&nvtxs,&xadj,&adjncy,&flg_row);
    9085:       if (flg_row) {
    9086:         PetscMalloc2(nvtxs+1,&used_xadj,xadj[nvtxs],&used_adjncy);
    9087:         PetscArraycpy(used_xadj,xadj,nvtxs+1);
    9088:         PetscArraycpy(used_adjncy,adjncy,xadj[nvtxs]);
    9089:         free_used_adj = PETSC_TRUE;
    9090:       } else {
    9091:         pcbddc->sub_schurs_layers = -1;
    9092:         used_xadj = NULL;
    9093:         used_adjncy = NULL;
    9094:       }
    9095:       MatRestoreRowIJ(pcbddc->local_mat,0,PETSC_TRUE,PETSC_FALSE,&nvtxs,&xadj,&adjncy,&flg_row);
    9096:     }
    9097:   }

    9099:   /* setup sub_schurs data */
    9100:   MatCreateSchurComplement(pcis->A_II,pcis->pA_II,pcis->A_IB,pcis->A_BI,pcis->A_BB,&S_j);
    9101:   if (!sub_schurs->schur_explicit) {
    9102:     /* pcbddc->ksp_D up to date only if not using MatFactor with Schur complement support */
    9103:     MatSchurComplementSetKSP(S_j,pcbddc->ksp_D);
    9104:     PCBDDCSubSchursSetUp(sub_schurs,NULL,S_j,PETSC_FALSE,used_xadj,used_adjncy,pcbddc->sub_schurs_layers,NULL,pcbddc->adaptive_selection,PETSC_FALSE,PETSC_FALSE,0,NULL,NULL,NULL,NULL);
    9105:   } else {
    9106:     Mat       change = NULL;
    9107:     Vec       scaling = NULL;
    9108:     IS        change_primal = NULL, iP;
    9109:     PetscInt  benign_n;
    9110:     PetscBool reuse_solvers = (PetscBool)!pcbddc->use_change_of_basis;
    9111:     PetscBool need_change = PETSC_FALSE;
    9112:     PetscBool discrete_harmonic = PETSC_FALSE;

    9114:     if (!pcbddc->use_vertices && reuse_solvers) {
    9115:       PetscInt n_vertices;

    9117:       ISGetLocalSize(sub_schurs->is_vertices,&n_vertices);
    9118:       reuse_solvers = (PetscBool)!n_vertices;
    9119:     }
    9120:     if (!pcbddc->benign_change_explicit) {
    9121:       benign_n = pcbddc->benign_n;
    9122:     } else {
    9123:       benign_n = 0;
    9124:     }
    9125:     /* sub_schurs->change is a local object; instead, PCBDDCConstraintsSetUp and the quantities used in the test below are logically collective on pc.
    9126:        We need a global reduction to avoid possible deadlocks.
    9127:        We assume that sub_schurs->change is created once, and then reused for different solves, unless the topography has been recomputed */
    9128:     if (pcbddc->adaptive_userdefined || (pcbddc->deluxe_zerorows && !pcbddc->use_change_of_basis)) {
    9129:       PetscBool have_loc_change = (PetscBool)(!!sub_schurs->change);
    9130:       MPIU_Allreduce(&have_loc_change,&need_change,1,MPIU_BOOL,MPI_LOR,PetscObjectComm((PetscObject)pc));
    9131:       need_change = (PetscBool)(!need_change);
    9132:     }
    9133:     /* If the user defines additional constraints, we import them here.
    9134:        We need to compute the change of basis according to the quadrature weights attached to pmat via MatSetNearNullSpace, and this could not be done (at the moment) without some hacking */
    9135:     if (need_change) {
    9136:       PC_IS   *pcisf;
    9137:       PC_BDDC *pcbddcf;
    9138:       PC      pcf;

    9140:       if (pcbddc->sub_schurs_rebuild) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"Cannot compute change of basis with a different graph");
    9141:       PCCreate(PetscObjectComm((PetscObject)pc),&pcf);
    9142:       PCSetOperators(pcf,pc->mat,pc->pmat);
    9143:       PCSetType(pcf,PCBDDC);

    9145:       /* hacks */
    9146:       pcisf                        = (PC_IS*)pcf->data;
    9147:       pcisf->is_B_local            = pcis->is_B_local;
    9148:       pcisf->vec1_N                = pcis->vec1_N;
    9149:       pcisf->BtoNmap               = pcis->BtoNmap;
    9150:       pcisf->n                     = pcis->n;
    9151:       pcisf->n_B                   = pcis->n_B;
    9152:       pcbddcf                      = (PC_BDDC*)pcf->data;
    9153:       PetscFree(pcbddcf->mat_graph);
    9154:       pcbddcf->mat_graph           = pcbddc->mat_graph;
    9155:       pcbddcf->use_faces           = PETSC_TRUE;
    9156:       pcbddcf->use_change_of_basis = PETSC_TRUE;
    9157:       pcbddcf->use_change_on_faces = PETSC_TRUE;
    9158:       pcbddcf->use_qr_single       = PETSC_TRUE;
    9159:       pcbddcf->fake_change         = PETSC_TRUE;

    9161:       /* setup constraints so that we can get information on primal vertices and change of basis (in local numbering) */
    9162:       PCBDDCConstraintsSetUp(pcf);
    9163:       sub_schurs->change_with_qr = pcbddcf->use_qr_single;
    9164:       ISCreateGeneral(PETSC_COMM_SELF,pcbddcf->n_vertices,pcbddcf->local_primal_ref_node,PETSC_COPY_VALUES,&change_primal);
    9165:       change = pcbddcf->ConstraintMatrix;
    9166:       pcbddcf->ConstraintMatrix = NULL;

    9168:       /* free unneeded memory allocated in PCBDDCConstraintsSetUp */
    9169:       PetscFree(pcbddcf->sub_schurs);
    9170:       MatNullSpaceDestroy(&pcbddcf->onearnullspace);
    9171:       PetscFree2(pcbddcf->local_primal_ref_node,pcbddcf->local_primal_ref_mult);
    9172:       PetscFree(pcbddcf->primal_indices_local_idxs);
    9173:       PetscFree(pcbddcf->onearnullvecs_state);
    9174:       PetscFree(pcf->data);
    9175:       pcf->ops->destroy = NULL;
    9176:       pcf->ops->reset   = NULL;
    9177:       PCDestroy(&pcf);
    9178:     }
    9179:     if (!pcbddc->use_deluxe_scaling) scaling = pcis->D;

    9181:     PetscObjectQuery((PetscObject)pc,"__KSPFETIDP_iP",(PetscObject*)&iP);
    9182:     if (iP) {
    9183:       PetscOptionsBegin(PetscObjectComm((PetscObject)iP),sub_schurs->prefix,"BDDC sub_schurs options","PC");
    9184:       PetscOptionsBool("-sub_schurs_discrete_harmonic",NULL,NULL,discrete_harmonic,&discrete_harmonic,NULL);
    9185:       PetscOptionsEnd();
    9186:     }
    9187:     if (discrete_harmonic) {
    9188:       Mat A;
    9189:       MatDuplicate(pcbddc->local_mat,MAT_COPY_VALUES,&A);
    9190:       MatZeroRowsColumnsIS(A,iP,1.0,NULL,NULL);
    9191:       PetscObjectCompose((PetscObject)A,"__KSPFETIDP_iP",(PetscObject)iP);
    9192:       PCBDDCSubSchursSetUp(sub_schurs,A,S_j,pcbddc->sub_schurs_exact_schur,used_xadj,used_adjncy,pcbddc->sub_schurs_layers,scaling,pcbddc->adaptive_selection,reuse_solvers,pcbddc->benign_saddle_point,benign_n,pcbddc->benign_p0_lidx,pcbddc->benign_zerodiag_subs,change,change_primal);
    9193:       MatDestroy(&A);
    9194:     } else {
    9195:       PCBDDCSubSchursSetUp(sub_schurs,pcbddc->local_mat,S_j,pcbddc->sub_schurs_exact_schur,used_xadj,used_adjncy,pcbddc->sub_schurs_layers,scaling,pcbddc->adaptive_selection,reuse_solvers,pcbddc->benign_saddle_point,benign_n,pcbddc->benign_p0_lidx,pcbddc->benign_zerodiag_subs,change,change_primal);
    9196:     }
    9197:     MatDestroy(&change);
    9198:     ISDestroy(&change_primal);
    9199:   }
    9200:   MatDestroy(&S_j);

    9202:   /* free adjacency */
    9203:   if (free_used_adj) {
    9204:     PetscFree2(used_xadj,used_adjncy);
    9205:   }
    9206:   PetscLogEventEnd(PC_BDDC_Schurs[pcbddc->current_level],pc,0,0,0);
    9207:   return(0);
    9208: }

    9210: PetscErrorCode PCBDDCInitSubSchurs(PC pc)
    9211: {
    9212:   PC_IS               *pcis=(PC_IS*)pc->data;
    9213:   PC_BDDC             *pcbddc=(PC_BDDC*)pc->data;
    9214:   PCBDDCGraph         graph;
    9215:   PetscErrorCode      ierr;

    9218:   /* attach interface graph for determining subsets */
    9219:   if (pcbddc->sub_schurs_rebuild) { /* in case rebuild has been requested, it uses a graph generated only by the neighbouring information */
    9220:     IS       verticesIS,verticescomm;
    9221:     PetscInt vsize,*idxs;

    9223:     PCBDDCGraphGetCandidatesIS(pcbddc->mat_graph,NULL,NULL,NULL,NULL,&verticesIS);
    9224:     ISGetSize(verticesIS,&vsize);
    9225:     ISGetIndices(verticesIS,(const PetscInt**)&idxs);
    9226:     ISCreateGeneral(PetscObjectComm((PetscObject)pc),vsize,idxs,PETSC_COPY_VALUES,&verticescomm);
    9227:     ISRestoreIndices(verticesIS,(const PetscInt**)&idxs);
    9228:     PCBDDCGraphRestoreCandidatesIS(pcbddc->mat_graph,NULL,NULL,NULL,NULL,&verticesIS);
    9229:     PCBDDCGraphCreate(&graph);
    9230:     PCBDDCGraphInit(graph,pcbddc->mat_graph->l2gmap,pcbddc->mat_graph->nvtxs_global,pcbddc->graphmaxcount);
    9231:     PCBDDCGraphSetUp(graph,pcbddc->mat_graph->custom_minimal_size,NULL,pcbddc->DirichletBoundariesLocal,0,NULL,verticescomm);
    9232:     ISDestroy(&verticescomm);
    9233:     PCBDDCGraphComputeConnectedComponents(graph);
    9234:   } else {
    9235:     graph = pcbddc->mat_graph;
    9236:   }
    9237:   /* print some info */
    9238:   if (pcbddc->dbg_flag && !pcbddc->sub_schurs_rebuild) {
    9239:     IS       vertices;
    9240:     PetscInt nv,nedges,nfaces;
    9241:     PCBDDCGraphASCIIView(graph,pcbddc->dbg_flag,pcbddc->dbg_viewer);
    9242:     PCBDDCGraphGetCandidatesIS(graph,&nfaces,NULL,&nedges,NULL,&vertices);
    9243:     ISGetSize(vertices,&nv);
    9244:     PetscViewerASCIIPushSynchronized(pcbddc->dbg_viewer);
    9245:     PetscViewerASCIISynchronizedPrintf(pcbddc->dbg_viewer,"--------------------------------------------------------------\n");
    9246:     PetscViewerASCIISynchronizedPrintf(pcbddc->dbg_viewer,"Subdomain %04d got %02d local candidate vertices (%D)\n",PetscGlobalRank,(int)nv,pcbddc->use_vertices);
    9247:     PetscViewerASCIISynchronizedPrintf(pcbddc->dbg_viewer,"Subdomain %04d got %02d local candidate edges    (%D)\n",PetscGlobalRank,(int)nedges,pcbddc->use_edges);
    9248:     PetscViewerASCIISynchronizedPrintf(pcbddc->dbg_viewer,"Subdomain %04d got %02d local candidate faces    (%D)\n",PetscGlobalRank,(int)nfaces,pcbddc->use_faces);
    9249:     PetscViewerFlush(pcbddc->dbg_viewer);
    9250:     PetscViewerASCIIPopSynchronized(pcbddc->dbg_viewer);
    9251:     PCBDDCGraphRestoreCandidatesIS(graph,&nfaces,NULL,&nedges,NULL,&vertices);
    9252:   }

    9254:   /* sub_schurs init */
    9255:   if (!pcbddc->sub_schurs) {
    9256:     PCBDDCSubSchursCreate(&pcbddc->sub_schurs);
    9257:   }
    9258:   PCBDDCSubSchursInit(pcbddc->sub_schurs,((PetscObject)pc)->prefix,pcis->is_I_local,pcis->is_B_local,graph,pcis->BtoNmap,pcbddc->sub_schurs_rebuild);

    9260:   /* free graph struct */
    9261:   if (pcbddc->sub_schurs_rebuild) {
    9262:     PCBDDCGraphDestroy(&graph);
    9263:   }
    9264:   return(0);
    9265: }

    9267: PetscErrorCode PCBDDCCheckOperator(PC pc)
    9268: {
    9269:   PC_IS               *pcis=(PC_IS*)pc->data;
    9270:   PC_BDDC             *pcbddc=(PC_BDDC*)pc->data;
    9271:   PetscErrorCode      ierr;

    9274:   if (pcbddc->n_vertices == pcbddc->local_primal_size) {
    9275:     IS             zerodiag = NULL;
    9276:     Mat            S_j,B0_B=NULL;
    9277:     Vec            dummy_vec=NULL,vec_check_B,vec_scale_P;
    9278:     PetscScalar    *p0_check,*array,*array2;
    9279:     PetscReal      norm;
    9280:     PetscInt       i;

    9282:     /* B0 and B0_B */
    9283:     if (zerodiag) {
    9284:       IS       dummy;

    9286:       ISCreateStride(PETSC_COMM_SELF,pcbddc->benign_n,0,1,&dummy);
    9287:       MatCreateSubMatrix(pcbddc->benign_B0,dummy,pcis->is_B_local,MAT_INITIAL_MATRIX,&B0_B);
    9288:       MatCreateVecs(B0_B,NULL,&dummy_vec);
    9289:       ISDestroy(&dummy);
    9290:     }
    9291:     /* I need a primal vector to scale primal nodes since BDDC sums contibutions */
    9292:     VecDuplicate(pcbddc->vec1_P,&vec_scale_P);
    9293:     VecSet(pcbddc->vec1_P,1.0);
    9294:     VecScatterBegin(pcbddc->coarse_loc_to_glob,pcbddc->vec1_P,pcbddc->coarse_vec,ADD_VALUES,SCATTER_FORWARD);
    9295:     VecScatterEnd(pcbddc->coarse_loc_to_glob,pcbddc->vec1_P,pcbddc->coarse_vec,ADD_VALUES,SCATTER_FORWARD);
    9296:     VecScatterBegin(pcbddc->coarse_loc_to_glob,pcbddc->coarse_vec,vec_scale_P,INSERT_VALUES,SCATTER_REVERSE);
    9297:     VecScatterEnd(pcbddc->coarse_loc_to_glob,pcbddc->coarse_vec,vec_scale_P,INSERT_VALUES,SCATTER_REVERSE);
    9298:     VecReciprocal(vec_scale_P);
    9299:     /* S_j */
    9300:     MatCreateSchurComplement(pcis->A_II,pcis->pA_II,pcis->A_IB,pcis->A_BI,pcis->A_BB,&S_j);
    9301:     MatSchurComplementSetKSP(S_j,pcbddc->ksp_D);

    9303:     /* mimic vector in \widetilde{W}_\Gamma */
    9304:     VecSetRandom(pcis->vec1_N,NULL);
    9305:     /* continuous in primal space */
    9306:     VecSetRandom(pcbddc->coarse_vec,NULL);
    9307:     VecScatterBegin(pcbddc->coarse_loc_to_glob,pcbddc->coarse_vec,pcbddc->vec1_P,INSERT_VALUES,SCATTER_REVERSE);
    9308:     VecScatterEnd(pcbddc->coarse_loc_to_glob,pcbddc->coarse_vec,pcbddc->vec1_P,INSERT_VALUES,SCATTER_REVERSE);
    9309:     VecGetArray(pcbddc->vec1_P,&array);
    9310:     PetscCalloc1(pcbddc->benign_n,&p0_check);
    9311:     for (i=0;i<pcbddc->benign_n;i++) p0_check[i] = array[pcbddc->local_primal_size-pcbddc->benign_n+i];
    9312:     VecSetValues(pcis->vec1_N,pcbddc->local_primal_size,pcbddc->local_primal_ref_node,array,INSERT_VALUES);
    9313:     VecRestoreArray(pcbddc->vec1_P,&array);
    9314:     VecAssemblyBegin(pcis->vec1_N);
    9315:     VecAssemblyEnd(pcis->vec1_N);
    9316:     VecScatterBegin(pcis->N_to_B,pcis->vec1_N,pcis->vec2_B,INSERT_VALUES,SCATTER_FORWARD);
    9317:     VecScatterEnd(pcis->N_to_B,pcis->vec1_N,pcis->vec2_B,INSERT_VALUES,SCATTER_FORWARD);
    9318:     VecDuplicate(pcis->vec2_B,&vec_check_B);
    9319:     VecCopy(pcis->vec2_B,vec_check_B);

    9321:     /* assemble rhs for coarse problem */
    9322:     /* widetilde{S}_\Gamma w_\Gamma + \widetilde{B0}^T_B p0 */
    9323:     /* local with Schur */
    9324:     MatMult(S_j,pcis->vec2_B,pcis->vec1_B);
    9325:     if (zerodiag) {
    9326:       VecGetArray(dummy_vec,&array);
    9327:       for (i=0;i<pcbddc->benign_n;i++) array[i] = p0_check[i];
    9328:       VecRestoreArray(dummy_vec,&array);
    9329:       MatMultTransposeAdd(B0_B,dummy_vec,pcis->vec1_B,pcis->vec1_B);
    9330:     }
    9331:     /* sum on primal nodes the local contributions */
    9332:     VecScatterBegin(pcis->N_to_B,pcis->vec1_B,pcis->vec1_N,INSERT_VALUES,SCATTER_REVERSE);
    9333:     VecScatterEnd(pcis->N_to_B,pcis->vec1_B,pcis->vec1_N,INSERT_VALUES,SCATTER_REVERSE);
    9334:     VecGetArray(pcis->vec1_N,&array);
    9335:     VecGetArray(pcbddc->vec1_P,&array2);
    9336:     for (i=0;i<pcbddc->local_primal_size;i++) array2[i] = array[pcbddc->local_primal_ref_node[i]];
    9337:     VecRestoreArray(pcbddc->vec1_P,&array2);
    9338:     VecRestoreArray(pcis->vec1_N,&array);
    9339:     VecSet(pcbddc->coarse_vec,0.);
    9340:     VecScatterBegin(pcbddc->coarse_loc_to_glob,pcbddc->vec1_P,pcbddc->coarse_vec,ADD_VALUES,SCATTER_FORWARD);
    9341:     VecScatterEnd(pcbddc->coarse_loc_to_glob,pcbddc->vec1_P,pcbddc->coarse_vec,ADD_VALUES,SCATTER_FORWARD);
    9342:     VecScatterBegin(pcbddc->coarse_loc_to_glob,pcbddc->coarse_vec,pcbddc->vec1_P,INSERT_VALUES,SCATTER_REVERSE);
    9343:     VecScatterEnd(pcbddc->coarse_loc_to_glob,pcbddc->coarse_vec,pcbddc->vec1_P,INSERT_VALUES,SCATTER_REVERSE);
    9344:     VecGetArray(pcbddc->vec1_P,&array);
    9345:     /* scale primal nodes (BDDC sums contibutions) */
    9346:     VecPointwiseMult(pcbddc->vec1_P,vec_scale_P,pcbddc->vec1_P);
    9347:     VecSetValues(pcis->vec1_N,pcbddc->local_primal_size,pcbddc->local_primal_ref_node,array,INSERT_VALUES);
    9348:     VecRestoreArray(pcbddc->vec1_P,&array);
    9349:     VecAssemblyBegin(pcis->vec1_N);
    9350:     VecAssemblyEnd(pcis->vec1_N);
    9351:     VecScatterBegin(pcis->N_to_B,pcis->vec1_N,pcis->vec1_B,INSERT_VALUES,SCATTER_FORWARD);
    9352:     VecScatterEnd(pcis->N_to_B,pcis->vec1_N,pcis->vec1_B,INSERT_VALUES,SCATTER_FORWARD);
    9353:     /* global: \widetilde{B0}_B w_\Gamma */
    9354:     if (zerodiag) {
    9355:       MatMult(B0_B,pcis->vec2_B,dummy_vec);
    9356:       VecGetArray(dummy_vec,&array);
    9357:       for (i=0;i<pcbddc->benign_n;i++) pcbddc->benign_p0[i] = array[i];
    9358:       VecRestoreArray(dummy_vec,&array);
    9359:     }
    9360:     /* BDDC */
    9361:     VecSet(pcis->vec1_D,0.);
    9362:     PCBDDCApplyInterfacePreconditioner(pc,PETSC_FALSE);

    9364:     VecCopy(pcis->vec1_B,pcis->vec2_B);
    9365:     VecAXPY(pcis->vec1_B,-1.0,vec_check_B);
    9366:     VecNorm(pcis->vec1_B,NORM_INFINITY,&norm);
    9367:     PetscPrintf(PETSC_COMM_SELF,"[%d] BDDC local error is %1.4e\n",PetscGlobalRank,norm);
    9368:     for (i=0;i<pcbddc->benign_n;i++) {
    9369:       PetscPrintf(PETSC_COMM_SELF,"[%d] BDDC p0[%D] error is %1.4e\n",PetscGlobalRank,i,PetscAbsScalar(pcbddc->benign_p0[i]-p0_check[i]));
    9370:     }
    9371:     PetscFree(p0_check);
    9372:     VecDestroy(&vec_scale_P);
    9373:     VecDestroy(&vec_check_B);
    9374:     VecDestroy(&dummy_vec);
    9375:     MatDestroy(&S_j);
    9376:     MatDestroy(&B0_B);
    9377:   }
    9378:   return(0);
    9379: }

    9381:  #include <../src/mat/impls/aij/mpi/mpiaij.h>
    9382: PetscErrorCode MatMPIAIJRestrict(Mat A, MPI_Comm ccomm, Mat *B)
    9383: {
    9384:   Mat            At;
    9385:   IS             rows;
    9386:   PetscInt       rst,ren;
    9388:   PetscLayout    rmap;

    9391:   rst = ren = 0;
    9392:   if (ccomm != MPI_COMM_NULL) {
    9393:     PetscLayoutCreate(ccomm,&rmap);
    9394:     PetscLayoutSetSize(rmap,A->rmap->N);
    9395:     PetscLayoutSetBlockSize(rmap,1);
    9396:     PetscLayoutSetUp(rmap);
    9397:     PetscLayoutGetRange(rmap,&rst,&ren);
    9398:   }
    9399:   ISCreateStride(PetscObjectComm((PetscObject)A),ren-rst,rst,1,&rows);
    9400:   MatCreateSubMatrix(A,rows,NULL,MAT_INITIAL_MATRIX,&At);
    9401:   ISDestroy(&rows);

    9403:   if (ccomm != MPI_COMM_NULL) {
    9404:     Mat_MPIAIJ *a,*b;
    9405:     IS         from,to;
    9406:     Vec        gvec;
    9407:     PetscInt   lsize;

    9409:     MatCreate(ccomm,B);
    9410:     MatSetSizes(*B,ren-rst,PETSC_DECIDE,PETSC_DECIDE,At->cmap->N);
    9411:     MatSetType(*B,MATAIJ);
    9412:     PetscLayoutDestroy(&((*B)->rmap));
    9413:     PetscLayoutSetUp((*B)->cmap);
    9414:     a    = (Mat_MPIAIJ*)At->data;
    9415:     b    = (Mat_MPIAIJ*)(*B)->data;
    9416:     MPI_Comm_size(ccomm,&b->size);
    9417:     MPI_Comm_rank(ccomm,&b->rank);
    9418:     PetscObjectReference((PetscObject)a->A);
    9419:     PetscObjectReference((PetscObject)a->B);
    9420:     b->A = a->A;
    9421:     b->B = a->B;

    9423:     b->donotstash      = a->donotstash;
    9424:     b->roworiented     = a->roworiented;
    9425:     b->rowindices      = 0;
    9426:     b->rowvalues       = 0;
    9427:     b->getrowactive    = PETSC_FALSE;

    9429:     (*B)->rmap         = rmap;
    9430:     (*B)->factortype   = A->factortype;
    9431:     (*B)->assembled    = PETSC_TRUE;
    9432:     (*B)->insertmode   = NOT_SET_VALUES;
    9433:     (*B)->preallocated = PETSC_TRUE;

    9435:     if (a->colmap) {
    9436: #if defined(PETSC_USE_CTABLE)
    9437:       PetscTableCreateCopy(a->colmap,&b->colmap);
    9438: #else
    9439:       PetscMalloc1(At->cmap->N,&b->colmap);
    9440:       PetscLogObjectMemory((PetscObject)*B,At->cmap->N*sizeof(PetscInt));
    9441:       PetscArraycpy(b->colmap,a->colmap,At->cmap->N);
    9442: #endif
    9443:     } else b->colmap = 0;
    9444:     if (a->garray) {
    9445:       PetscInt len;
    9446:       len  = a->B->cmap->n;
    9447:       PetscMalloc1(len+1,&b->garray);
    9448:       PetscLogObjectMemory((PetscObject)(*B),len*sizeof(PetscInt));
    9449:       if (len) { PetscArraycpy(b->garray,a->garray,len); }
    9450:     } else b->garray = 0;

    9452:     PetscObjectReference((PetscObject)a->lvec);
    9453:     b->lvec = a->lvec;
    9454:     PetscLogObjectParent((PetscObject)*B,(PetscObject)b->lvec);

    9456:     /* cannot use VecScatterCopy */
    9457:     VecGetLocalSize(b->lvec,&lsize);
    9458:     ISCreateGeneral(ccomm,lsize,b->garray,PETSC_USE_POINTER,&from);
    9459:     ISCreateStride(PETSC_COMM_SELF,lsize,0,1,&to);
    9460:     MatCreateVecs(*B,&gvec,NULL);
    9461:     VecScatterCreate(gvec,from,b->lvec,to,&b->Mvctx);
    9462:     PetscLogObjectParent((PetscObject)*B,(PetscObject)b->Mvctx);
    9463:     ISDestroy(&from);
    9464:     ISDestroy(&to);
    9465:     VecDestroy(&gvec);
    9466:   }
    9467:   MatDestroy(&At);
    9468:   return(0);
    9469: }